-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebtorrent.min.js
More file actions
2 lines (2 loc) · 213 KB
/
Copy pathwebtorrent.min.js
File metadata and controls
2 lines (2 loc) · 213 KB
1
2
var e,t,i={405:e=>{e.exports=async function*(e){for(let t of e)"function"==typeof t&&(t=t()),yield*t}},580:e=>{var t=/["'&<>]/;e.exports=function(e){var i,s=""+e,n=t.exec(s);if(!n)return s;var r="",o=0,a=0;for(o=n.index;o<s.length;o++){switch(s.charCodeAt(o)){case 34:i=""";break;case 38:i="&";break;case 39:i="'";break;case 60:i="<";break;case 62:i=">";break;default:continue}a!==o&&(r+=s.substring(a,o)),a=o+1,r+=i}return a!==o?r+s.substring(a,o):r}},717:(e,t,i)=>{i.r(t),i.d(t,{addListener:()=>u,argv:()=>a,binding:()=>S,browser:()=>r,chdir:()=>E,cwd:()=>k,emit:()=>g,env:()=>o,listeners:()=>v,nextTick:()=>b,off:()=>f,on:()=>d,once:()=>p,prependListener:()=>y,prependOnceListener:()=>w,removeAllListeners:()=>_,removeListener:()=>m,title:()=>n,umask:()=>x,version:()=>h,versions:()=>l});var s=i(9596);const n="browser",r=!0,o={},a=[],h="",l={};function c(){}const d=c,u=c,p=c,f=c,m=c,_=c,g=c,y=c,w=c,b=(e,...t)=>s(()=>e(...t)),v=e=>[],k=()=>"/",x=()=>0,S=e=>{throw new Error("process.binding is not supported")},E=e=>{throw new Error("process.chdir is not supported")}},736:(e,t,i)=>{e.exports=function(e){function t(e){let i,n,r,o=null;function a(...e){if(!a.enabled)return;const s=a,n=Number(new Date),r=n-(i||n);s.diff=r,s.prev=i,s.curr=n,i=n,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,(i,n)=>{if("%%"===i)return"%";o++;const r=t.formatters[n];if("function"==typeof r){const t=e[o];i=r.call(s,t),e.splice(o,1),o--}return i}),t.formatArgs.call(s,e);(s.log||t.log).apply(s,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=s,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==t.namespaces&&(n=t.namespaces,r=t.enabled(e)),r),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function s(e,i){const s=t(this.namespace+(void 0===i?":":i)+e);return s.log=this.log,s}function n(e,t){let i=0,s=0,n=-1,r=0;for(;i<e.length;)if(s<t.length&&(t[s]===e[i]||"*"===t[s]))"*"===t[s]?(n=s,r=i,s++):(i++,s++);else{if(-1===n)return!1;s=n+1,r++,i=r}for(;s<t.length&&"*"===t[s];)s++;return s===t.length}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,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const i=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of i)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const i of t.skips)if(n(e,i))return!1;for(const i of t.names)if(n(e,i))return!0;return!1},t.humanize=i(6585),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(i=>{t[i]=e[i]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let i=0;for(let t=0;t<e.length;t++)i=(i<<5)-i+e.charCodeAt(t),i|=0;return t.colors[Math.abs(i)%t.colors.length]},t.enable(t.load()),t}},815:(e,t,i)=>{var s,n=i(717),r=i(3519),o=i(6611);try{s=i(2376)}catch(e){}var a=function(){},h=void 0!==n&&/^v?\.0/.test(n.version),l=function(e){return"function"==typeof e},c=function(e,t,i,n){n=r(n);var c=!1;e.on("close",function(){c=!0}),o(e,{readable:t,writable:i},function(e){if(e)return n(e);c=!0,n()});var d=!1;return function(t){if(!c&&!d)return d=!0,function(e){return!!h&&!!s&&(e instanceof(s.ReadStream||a)||e instanceof(s.WriteStream||a))&&l(e.close)}(e)?e.close(a):function(e){return e.setHeader&&l(e.abort)}(e)?e.abort():l(e.destroy)?e.destroy():void n(t||new Error("stream was destroyed"))}},d=function(e){e()},u=function(e,t){return e.pipe(t)};e.exports=function(){var e,t=Array.prototype.slice.call(arguments),i=l(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 s=t.map(function(n,r){var o=r<t.length-1;return c(n,o,r>0,function(t){e||(e=t),t&&s.forEach(d),o||(s.forEach(d),i(e))})});return t.reduce(u)}},988:(e,t,i)=>{i.d(t,{A:()=>f});var s=i(9639);function n(e){const t=e<0?1:0;return e=Math.abs(Number(e||1)),Math.floor(Math.log10(e))+1+t}function r(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,i){const n=[];let r=null;return o._encode(n,e),r=(0,s.xW)(n),o.bytes=r.length,ArrayBuffer.isView(t)?(t.set(r,i),t):r}o.bytes=-1,o._floatConversionDetected=!1,o._encode=function(e,t){if(null!=t)switch(r(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]),l=new Uint8Array([108]);o.buffer=function(e,t){e.push((0,s.L0)(t.length+":"),t)},o.string=function(e,t){e.push((0,s.L0)((0,s.L0)(t).byteLength+":"+t))},o.number=function(e,t){if(Number.isInteger(t))return e.push((0,s.L0)("i"+BigInt(t)+"e"));const i=2147483648,n=(t/i|0)*i+(t%i|0);e.push((0,s.L0)("i"+n+"e")),n===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 "'+n+'"'),console.trace())},o.dict=function(e,t){e.push(h);let i,s=0;const n=Object.keys(t).sort(),r=n.length;for(;s<r;s++)i=n[s],null!=t[i]&&(o.string(e,i),o._encode(e,t[i]));e.push(a)},o.dictMap=function(e,t){e.push(h);const i=Array.from(t.keys()).sort();for(const s of i)null!=t.get(s)&&(ArrayBuffer.isView(s)?o._encode(e,s):o.string(e,String(s)),o._encode(e,t.get(s)));e.push(a)},o.list=function(e,t){let i=0;const s=t.length;for(e.push(l);i<s;i++)null!=t[i]&&o._encode(e,t[i]);e.push(a)},o.listSet=function(e,t){e.push(l);for(const i of t)null!=i&&o._encode(e,i);e.push(a)};const c=o;function d(e,t,i){let s=0,n=1;for(let r=t;r<i;r++){const i=e[r];if(i<58&&i>=48)s=10*s+(i-48);else if(r!==t||43!==i){if(r!==t||45!==i){if(46===i)break;throw new Error("not a number: buffer["+r+"] = "+i)}n=-1}}return s*n}function u(e,t,i,n){return null==e||0===e.length?null:("number"!=typeof t&&null==n&&(n=t,t=void 0),"number"!=typeof i&&null==n&&(n=i,i=void 0),u.position=0,u.encoding=n||null,u.data=ArrayBuffer.isView(e)?new Uint8Array(e.slice(t,i)):(0,s.L0)(e),u.bytes=u.data.length,u.next())}u.bytes=0,u.position=0,u.data=null,u.encoding=null,u.next=function(){switch(u.data[u.position]){case 100:return u.dictionary();case 108:return u.list();case 105:return u.integer();default:return u.buffer()}},u.find=function(e){let t=u.position;const i=u.data.length,s=u.data;for(;t<i;){if(s[t]===e)return t;t++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(e)+'" [0x'+e.toString(16)+"]")},u.dictionary=function(){u.position++;const e={};for(;101!==u.data[u.position];){const t=u.buffer();let i=(0,s.dU)(t);i.includes("�")&&(i=(0,s.V5)(t)),e[i]=u.next()}return u.position++,e},u.list=function(){u.position++;const e=[];for(;101!==u.data[u.position];)e.push(u.next());return u.position++,e},u.integer=function(){const e=u.find(101),t=d(u.data,u.position+1,e);return u.position+=e+1-u.position,t},u.buffer=function(){let e=u.find(58);const t=d(u.data,u.position,e),i=++e+t;return u.position=i,u.encoding?(0,s.dU)(u.data.slice(e,i)):u.data.slice(e,i)};function p(e){if(null==e)return 0;const t=r(e);switch(t){case"arraybufferview":return function(e){const t=e.byteLength-e.byteOffset;return n(t)+1+t}(e);case"string":return function(e){const t=(0,s.L0)(e).byteLength;return n(t)+1+t}(e);case"array":case"set":return function(e){let t=2;for(const i of e)t+=p(i);return t}(e);case"number":return 1+n(Math.floor(e))+1;case"bigint":return 1+e.toString().length+1;case"object":return function(e){let t=2;const i=Object.keys(e);for(let r=0;r<i.length;r++){const o=(0,s.L0)(i[r]).byteLength;t+=n(o)+1+o,t+=p(e[i[r]])}return t}(e);case"map":return function(e){let t=2;for(const[i,r]of e){const e=(0,s.L0)(i).byteLength;t+=n(e)+1+e,t+=p(r)}return t}(e);default:throw new TypeError(`Unsupported value of type "${t}"`)}}const f={encode:c,decode:u,byteLength:p,encodingLength:p}},1035:(e,t,i)=>{var s=i(717);const n=void 0!==s&&!!s.hrtime,r=65535,o=n?1e8:100,a=n?()=>{const[e,t]=s.hrtime();return 1e9*e+t}:()=>performance.now();function h(e){return(a()-e)/o&r}e.exports=function(e){const t=a(),i=10*(e||5),s=[0];let n=1,o=h(t)-1&r;return function(e){const a=h(t);let l=a-o&r;for(l>i&&(l=i),o=a;l--;)n===i&&(n=0),s[n]=s[0===n?i-1:n-1],n++;e&&(s[n-1]+=e);const c=s[n-1],d=s.length<i?0:s[n===i?0:n];return s.length<10?c:10*(c-d)/s.length}}},1048:()=>{},1133:(e,t,i)=>{let s=i(8673);e.exports=new s(i(8446))},1314:e=>{e.exports=function(e,t){if(t>=e.length||t<0)return;var i=e.pop();if(t<e.length){var s=e[t];return e[t]=i,s}return i}},1467:e=>{function t(e,t){if("string"==typeof e[0])return e.join("");if("number"==typeof e[0])return new Uint8Array(e);const i=new Uint8Array(t);let s=0;for(let t=0,n=e.length;t<n;t++){const n=e[t];i.set(n,s),s+=n.byteLength||n.length}return i}e.exports=async function*(e,i=512,s={}){"object"==typeof i&&(i=(s=i).size);let{nopad:n,zeroPadding:r=!0}=s;n&&(r=!1);let o=[],a=0;for await(const s of e)if(a+=s.byteLength||s.length||1,o.push(s),a>=i){const e=t(o,a);let s=0;for(;a>=i;)yield e.slice(s,s+i),a-=i,s+=i;o=[e.slice(s,e.length)]}a&&(yield t(o,r?i:a))}},1827:()=>{},2072:e=>{e.exports={wait:function(e){return new Promise(t=>setTimeout(t,e))}}},2123:()=>{},2376:()=>{},2532:()=>{},2701:()=>{},2799:()=>{},2878:e=>{function t(e,t){return{start:e.start,end:e.end,index:t}}function i(e){return{start:e.start,end:e.end}}function s(e,t){return e.index-t.index}function n(e,t){return e.start-t.start}e.exports=function(e,r,o){if("string"!=typeof r)throw new TypeError("argument str must be a string");var a=r.indexOf("=");if(-1===a)return-2;var h=r.slice(a+1).split(","),l=[];l.type=r.slice(0,a);for(var c=0;c<h.length;c++){var d=h[c].split("-"),u=parseInt(d[0],10),p=parseInt(d[1],10);isNaN(u)?(u=e-p,p=e-1):isNaN(p)&&(p=e-1),p>e-1&&(p=e-1),isNaN(u)||isNaN(p)||u>p||u<0||l.push({start:u,end:p})}if(l.length<1)return-1;return o&&o.combine?function(e){for(var r=e.map(t).sort(n),o=0,a=1;a<r.length;a++){var h=r[a],l=r[o];h.start>l.end+1?r[++o]=h:h.end>l.end&&(l.end=h.end,l.index=Math.min(l.index,h.index))}r.length=o+1;var c=r.sort(s).map(i);return c.type=e.type,c}(l):l}},3033:(e,t,i)=>{function s(e){return(e>>3)+Number(e%8!=0)}i.d(t,{A:()=>n});class n{get length(){return this.buffer.length<<3}constructor(e=0,t){const i=null==t?void 0:t.grow;this.grow=i?Number.isFinite(i)?s(i):i:0,this.buffer="number"==typeof e?new Uint8Array(s(e)):e}get(e){const t=e>>3;return t<this.buffer.length&&!!(this.buffer[t]&128>>e%8)}set(e,t=!0){const i=e>>3;if(t){if(i>=this.buffer.length){const e=Math.max(i+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[i]|=128>>e%8}else i<this.buffer.length&&(this.buffer[i]&=~(128>>e%8))}setAll(e,t=0){const i=Math.min(s(t+e.length),this.grow);if(this.buffer.length<i){const e=new Uint8Array(i);e.set(this.buffer),this.buffer=e}let n=t>>3,r=128>>t%8;for(let t=0;t<e.length;t++)if(e[t]?this.buffer[n]|=r:this.buffer[n]&=~r,1===r){if(n+=1,n>=this.buffer.length)break;r=128}else r>>=1}forEach(e,t=0,i=8*this.buffer.length){let s=t>>3,n=128>>t%8;for(let r=t;r<i;r++)e(!!(this.buffer[s]&n),r),1===n?(s+=1,n=128):n>>=1}isEmpty(){for(let e=0;e<this.buffer.length;e++)if(0!==this.buffer[e])return!1;return!0}}},3065:(e,t,i)=>{var s=i(717),n=i(5472),r=i(3085),o=function(e,t,i){this.tokenBucket=new n(e,e,t,null),this.tokenBucket.content=e,this.curIntervalStart=r(),this.tokensThisInterval=0,this.fireImmediately=i};o.prototype={tokenBucket:null,curIntervalStart:0,tokensThisInterval:0,fireImmediately:!1,removeTokens:function(e,t){if(e>this.tokenBucket.bucketSize)return s.nextTick(t.bind(null,"Requested tokens "+e+" exceeds maximum tokens per interval "+this.tokenBucket.bucketSize,null)),!1;var i=this,n=r();if((n<this.curIntervalStart||n-this.curIntervalStart>=this.tokenBucket.interval)&&(this.curIntervalStart=n,this.tokensThisInterval=0),e>this.tokenBucket.tokensPerInterval-this.tokensThisInterval){if(this.fireImmediately)s.nextTick(t.bind(null,null,-1));else{var o=Math.ceil(this.curIntervalStart+this.tokenBucket.interval-n);setTimeout(function(){i.tokenBucket.removeTokens(e,a)},o)}return!1}return this.tokenBucket.removeTokens(e,a);function a(s,n){if(s)return t(s,null);i.tokensThisInterval+=e,t(null,n)}},tryRemoveTokens:function(e){if(e>this.tokenBucket.bucketSize)return!1;var t=r();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 i=this.tokenBucket.tryRemoveTokens(e);return i&&(this.tokensThisInterval+=e),i},getTokensRemaining:function(){return this.tokenBucket.drip(),this.tokenBucket.content}},e.exports=o},3085:(e,t,i)=>{var s=i(717);e.exports=function(){if(void 0!==s&&s.hrtime){var e=s.hrtime(),t=e[0],i=e[1];return 1e3*t+Math.floor(i/1e6)}return(new Date).getTime()}},3198:e=>{e.exports=class{constructor(e){this.decoder=new TextDecoder("utf16le"===e?"utf16-le":e)}get remaining(){return-1}decode(e){return this.decoder.decode(e,{stream:!0})}flush(){return this.decoder.decode(new Uint8Array(0))}}},3208:()=>{},3278:()=>{},3468:()=>{"undefined"!=typeof ReadableStream&&(ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=function({preventCancel:e}={}){const t=this.getReader(),i=this;let s=t.read();return{next(){const e=s;return s=t.read(),e},return:async n=>(await s,t.releaseLock(),e||i.cancel(),{done:!0,value:n}),async throw(e){throw await this.return(),e},[Symbol.asyncIterator](){return this}}}),ReadableStream.prototype.getIterator||(ReadableStream.prototype.getIterator=function({preventCancel:e}={}){return this[Symbol.asyncIterator]({preventCancel:e})}))},3519:(e,t,i)=>{var s=i(6587);function n(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function r(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},i=e.name||"Function wrapped with `once`";return t.onceError=i+" shouldn't be called more than once",t.called=!1,t}e.exports=s(n),e.exports.strict=s(r),n.proto=n(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return n(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return r(this)},configurable:!0})})},3714:(e,t,i)=>{const s=i(9596);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,i=()=>{}){this.mem[e]=t,this.store.put(e,t,t=>{this.mem[e]=null,i(t)})}get(e,t,i=()=>{}){if("function"==typeof t)return this.get(e,null,t);let n=this.mem[e];if(!n)return this.store.get(e,t,i);t||(t={});const r=t.offset||0,o=t.length||n.length-r;0===r&&o===n.length||(n=n.slice(r,o+r)),s(()=>i(null,n))}close(e=()=>{}){this.store.close(e)}destroy(e=()=>{}){this.store.destroy(e)}}},3970:()=>{},4018:e=>{e.exports=function(){for(var e=navigator.hardwareConcurrency||1,t=[],i=0;i<e;i++)t.push({model:"",speed:0,times:{user:0,nice:0,sys:0,idle:0,irq:0}});return t}},4043:()=>{},4343:()=>{},4497:(e,t,i)=>{const s=i(8454),n=i(9596);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 s(t)}put(e,t,i=()=>{}){if(!this.cache)return n(()=>i(new Error("CacheStore closed")));this.cache.remove(e),this.store.put(e,t,i)}get(e,t,i=()=>{}){if("function"==typeof t)return this.get(e,null,t);if(!this.cache)return n(()=>i(new Error("CacheStore closed")));t||(t={});let s=this.cache.get(e);if(s){const e=t.offset||0,r=t.length||s.length-e;return 0===e&&r===s.length||(s=s.slice(e,r+e)),n(()=>i(null,s))}let r=this.inProgressGets.get(e);const o=!!r;r||(r=[],this.inProgressGets.set(e,r)),r.push({opts:t,cb:i}),o||this.store.get(e,(t,i)=>{t||null==this.cache||this.cache.set(e,i);const s=this.inProgressGets.get(e);this.inProgressGets.delete(e);for(const{opts:e,cb:n}of s)if(t)n(t);else{const t=e.offset||0,s=e.length||i.length-t;let r=i;0===t&&s===i.length||(r=i.slice(t,s+t)),n(null,r)}})}close(e=()=>{}){if(!this.cache)return n(()=>e(new Error("CacheStore closed")));this.cache=null,this.store.close(e)}destroy(e=()=>{}){if(!this.cache)return n(()=>e(new Error("CacheStore closed")));this.cache=null,this.store.destroy(e)}}},4862:(e,t,i)=>{e.exports=n;const s=i(9596);function n(e,t){if(!(this instanceof n))return new n(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)}n.prototype.put=function(e,t,i=()=>{}){if(this.closed)return s(()=>i(new Error("Storage is closed")));const n=e===this.lastChunkIndex;return n&&t.length!==this.lastChunkLength?s(()=>i(new Error("Last chunk length must be "+this.lastChunkLength))):n||t.length===this.chunkLength?(this.chunks[e]=t,void s(()=>i(null))):s(()=>i(new Error("Chunk length must be "+this.chunkLength)))},n.prototype.get=function(e,t,i=()=>{}){if("function"==typeof t)return this.get(e,null,t);if(this.closed)return s(()=>i(new Error("Storage is closed")));let n=this.chunks[e];if(!n){const e=new Error("Chunk not found");return e.notFound=!0,s(()=>i(e))}t||(t={});const r=t.offset||0,o=t.length||n.length-r;0===r&&o===n.length||(n=n.slice(r,o+r)),s(()=>i(null,n))},n.prototype.close=n.prototype.destroy=function(e=()=>{}){if(this.closed)return s(()=>e(new Error("Storage is closed")));this.closed=!0,this.chunks=null,s(()=>e(null))}},5335:(e,t,i)=>{const s=i(3198),n=i(3198);e.exports=class{constructor(e="utf8"){switch(this.encoding=function(e){switch(e=e.toLowerCase()){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:throw new Error("Unknown encoding: "+e)}}(e),this.encoding){case"utf8":this.decoder=new n;break;case"utf16le":case"base64":throw new Error("Unsupported encoding: "+this.encoding);default:this.decoder=new s(this.encoding)}}get remaining(){return this.decoder.remaining}push(e){return"string"==typeof e?e:this.decoder.decode(e)}write(e){return this.push(e)}end(e){let t="";return e&&(t=this.push(e)),t+=this.decoder.flush(),t}}},5372:(e,t,i)=>{e.exports=function(e,t,i){if("number"!=typeof t)throw new Error("second argument must be a Number");let n,r,o,a,h,l,c=!0;Array.isArray(e)?(n=[],o=r=e.length):(a=Object.keys(e),n={},o=r=a.length);function d(e){function t(){i&&i(e,n),i=null}c?s(t):t()}function u(t,i,s){if(n[t]=s,i&&(h=!0),0===--o||i)d(i);else if(!h&&l<r){let t;a?(t=a[l],l+=1,e[t](function(e,i){u(t,e,i)})):(t=l,l+=1,e[t](function(e,i){u(t,e,i)}))}}l=t,o?a?a.some(function(i,s){return e[i](function(e,t){u(i,e,t)}),s===t-1}):e.some(function(e,i){return e(function(e,t){u(i,e,t)}),i===t-1}):d(null);c=!1};const s=i(9596)},5472:(e,t,i)=>{var s=i(717),n=function(e,t,i,s){if(this.bucketSize=e,this.tokensPerInterval=t,"string"==typeof i)switch(i){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 "+i)}else this.interval=i;this.parentBucket=s,this.content=0,this.lastDrip=+new Date};n.prototype={bucketSize:1,tokensPerInterval:1,interval:1e3,parentBucket:null,content:0,lastDrip:0,removeTokens:function(e,t){var i=this;return this.bucketSize?e>this.bucketSize?(s.nextTick(t.bind(null,"Requested tokens "+e+" exceeds bucket size "+this.bucketSize,null)),!1):(this.drip(),e>this.content?n():this.parentBucket?this.parentBucket.removeTokens(e,function(s,r){return s?t(s,null):e>i.content?n():(i.content-=e,void t(null,Math.min(r,i.content)))}):(this.content-=e,s.nextTick(t.bind(null,null,this.content)),!0)):(s.nextTick(t.bind(null,null,e,Number.POSITIVE_INFINITY)),!0);function n(){var s=Math.ceil((e-i.content)*(i.interval/i.tokensPerInterval));return setTimeout(function(){i.removeTokens(e,t)},s),!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 i=t*(this.tokensPerInterval/this.interval);this.content=Math.min(this.content+i,this.bucketSize)}else this.content=this.bucketSize}},e.exports=n},5658:(e,t,i)=>{i.d(t,{A:()=>_,enableSecure:()=>m});var s=i(7007),n=i(8179),r=i(1314),o=i(7833),a=i(6458);const h="tcpIncoming",l="tcpOutgoing",c="utpIncoming",d="utpOutgoing",u="webSeed",p=o("webtorrent:peer");let f=!1;const m=()=>{f=!0};class _ extends s{constructor(e,t){super(),this.id=e,this.type=t,p("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,this.emit("connect"),p("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.A(this.type,this.retries,f);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?f&&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,n.pipeline)(this.conn,this.throttleGroups.down.throttle(),new n.Transform({transform(t,i){e.emit("download",t.length),e.destroyed||i(null,t)}}),this.wire,this.throttleGroups.up.throttle(),new n.Transform({transform(t,i){e.emit("upload",t.length),e.destroyed||i(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"));p("Peer %s got handshake %s",this.id,e),clearTimeout(this.handshakeTimeout),this.retries=0;let i=this.addr;!i&&this.conn.remoteAddress&&this.conn.remotePort&&(i=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,i),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&&this.emit("disconnect",e),this.connected=!1,p("destroy %s %s (error: %s)",this.type,this.id,e&&(e.message||e)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const t=this.swarm,i=this.conn,s=this.wire;this.swarm=null,this.conn=null,this.wire=null,t&&s&&r(t.wires,t.wires.indexOf(s)),i&&(i.on("error",()=>{}),i.destroy()),s&&s.destroy(),t&&t.removePeer(this.id)}}_.TYPE_TCP_INCOMING=h,_.TYPE_TCP_OUTGOING=l,_.TYPE_UTP_INCOMING=c,_.TYPE_UTP_OUTGOING=d,_.TYPE_WEBRTC="webrtc",_.TYPE_WEBSEED=u,_.SOURCE_MANUAL="manual",_.SOURCE_TRACKER="tracker",_.SOURCE_DHT="dht",_.SOURCE_LSD="lsd",_.SOURCE_UT_PEX="ut_pex",_.createWebRTCPeer=(e,t,i,s=null)=>{const n=new _(e.id,"webrtc");if(n.conn=e,n.swarm=t,n.throttleGroups=i,n.source=s,n.conn.connected)n.onConnect();else{const e=()=>{n.conn.removeListener("connect",t),n.conn.removeListener("error",i)},t=()=>{e(),n.onConnect()},i=t=>{e(),n.destroy(t)};n.conn.once("connect",t),n.conn.once("error",i),n.startConnectTimeout()}return n},_.createTCPIncomingPeer=(e,t)=>_._createIncomingPeer(e,h,t),_.createUTPIncomingPeer=(e,t)=>_._createIncomingPeer(e,c,t),_.createTCPOutgoingPeer=(e,t,i,s)=>_._createOutgoingPeer(e,t,l,i,s),_.createUTPOutgoingPeer=(e,t,i,s)=>_._createOutgoingPeer(e,t,d,i,s),_._createIncomingPeer=(e,t,i)=>{const s=`${e.remoteAddress}:${e.remotePort}`,n=new _(s,t);return n.conn=e,n.addr=s,n.throttleGroups=i,n.onConnect(),n},_._createOutgoingPeer=(e,t,i,s,n=null)=>{const r=new _(e,i);return r.addr=e,r.swarm=t,r.throttleGroups=s,r.source=n,r},_.createWebSeedPeer=(e,t,i,s)=>{const n=new _(t,u);return n.swarm=i,n.conn=e,n.throttleGroups=s,n.onConnect(),n}},5809:e=>{e.exports=class{constructor(e){if(!(e>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}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return void 0===this.buffer[this.btm]}}},6080:(e,t,i)=>{const s=i(5809);e.exports=class{constructor(e){this.hwm=e||16,this.head=new s(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(e){if(this.length++,!this.head.push(e)){const t=this.head;this.head=t.next=new s(2*this.head.buffer.length),this.head.push(e)}}shift(){0!==this.length&&this.length--;const e=this.tail.shift();if(void 0===e&&this.tail.next){const e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){const e=this.tail.peek();return void 0===e&&this.tail.next?this.tail.next.peek():e}isEmpty(){return 0===this.length}}},6310:e=>{function t(e,t){for(const i in t)Object.defineProperty(e,i,{value:t[i],enumerable:!0,configurable:!0});return e}e.exports=function(e,i,s){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");s||(s={}),"object"==typeof i&&(s=i,i=""),i&&(s.code=i);try{return t(e,s)}catch(i){s.message=e.message,s.stack=e.stack;const n=function(){};n.prototype=Object.create(Object.getPrototypeOf(e));return t(new n,s)}}},6458:(e,t,i)=>{i.d(t,{A:()=>O});var s=i(988),n=i(3033),r=i(7264),o=i(7833),a=i(8727),h=i(8179),l=i(9639),c=i(1035),d=i(1314);const u=o("bittorrent-protocol"),p=(0,l.L0)("BitTorrent protocol"),f=new Uint8Array([0,0,0,0]),m=new Uint8Array([0,0,0,1,0]),_=new Uint8Array([0,0,0,1,1]),g=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]),S=new Uint8Array([0,0,1,2]),E=new Uint8Array([0,0,0,2]);function C(e,t){for(let i=e.length;i--;)e[i]^=t[i];return e}function A(e,t=0){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function P(e,t,i){e[t]=i>>>24&255,e[t+1]=i>>>16&255,e[t+2]=i>>>8&255,e[t+3]=255&i}class T{constructor(e,t,i,s){this.piece=e,this.offset=t,this.length=i,this.callback=s}}class I{constructor(){this.buffer=new Uint8Array}get(e){return!0}set(e){}}class L extends h.Duplex{constructor(e=null,t=0,i=!1){super(),this._debugId=(0,l.V5)((0,l.po)(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 n.A(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=c(),this.downloadSpeed=c(),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=i,i?(this._dh=r.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 i=this._nextExt,s=new e(this);function n(){}"function"!=typeof s.onHandshake&&(s.onHandshake=n),"function"!=typeof s.onExtendedHandshake&&(s.onExtendedHandshake=n),"function"!=typeof s.onMessage&&(s.onMessage=n),this.extendedMapping[i]=t,this._ext[t]=s,this[t]=s,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(f)}sendPe1(){if(this._peEnabled){const e=Math.floor(513*Math.random()),t=(0,l.po)(e);this._push((0,l.xW)([(0,l.fk)(this._myPubKey),t]))}}sendPe2(){const e=Math.floor(513*Math.random()),t=(0,l.po)(e);this._push((0,l.xW)([(0,l.fk)(this._myPubKey),t]))}async sendPe3(e){await this.setEncrypt(this._sharedSecret,e);const t=await(0,l.tW)((0,l.fk)(this._utfToHex("req1")+this._sharedSecret)),i=C(await(0,l.tW)((0,l.fk)(this._utfToHex("req2")+e)),await(0,l.tW)((0,l.fk)(this._utfToHex("req3")+this._sharedSecret))),s=new DataView((0,l.po)(2).buffer).getUint16(0)%512,n=(0,l.po)(s);let r=new Uint8Array(14+s+2);r.set(x),r.set(S,8);const o=new DataView(r.buffer);o.setInt16(12,s),n.copy(r,14),o.setInt16(14+s,0),r=this._encryptHandshake(r),this._push((0,l.xW)([t,i,r]))}async sendPe4(e){await this.setEncrypt(this._sharedSecret,e);const t=new DataView((0,l.po)(2).buffer).getUint16(0)%512,i=(0,l.po)(t);let s=new Uint8Array(14+t);const n=new DataView(s.buffer);s.set(x),s.set(E,8),n.setInt16(12,t),s.set(i,14),s=this._encryptHandshake(s),this._push(s),this._cryptoHandshakeDone=!0,this._debug("completed crypto handshake")}handshake(e,t,i){let s,n;if("string"==typeof e?(e=e.toLowerCase(),s=(0,l.fk)(e)):(s=e,e=(0,l.V5)(s)),"string"==typeof t?n=(0,l.fk)(t):(n=t,t=(0,l.V5)(n)),this._infoHash=s,20!==s.length||20!==n.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",e,t,i);const r=new Uint8Array(w);this.extensions={extended:!0,dht:!(!i||!i.dht),fast:!(!i||!i.fast)},r[5]|=16,this.extensions.dht&&(r[7]|=1),this.extensions.fast&&(r[7]|=4),this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this._push((0,l.xW)([p,r,s,n])),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 i=this.extendedMapping[t];e.m[i]=Number(t)}this.extended(0,s.A.encode(e)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking)if(this.amChoking=!0,this._debug("choke"),this._push(m),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(_))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(g))}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,i,s){return s||(s=()=>{}),this._finished?s(new Error("wire is closed")):!this.peerChoking||this.hasFast&&this.peerAllowedFastSet.includes(e)?(this._debug("request index=%d offset=%d length=%d",e,t,i),this.requests.push(new T(e,t,i,s)),this._timeout||this._resetTimeout(!0),void this._message(6,[e,t,i],null)):s(new Error("peer is choking"))}piece(e,t,i){this._debug("piece index=%d offset=%d",e,t),this._message(7,[e,t],i),this.uploaded+=i.length,this.uploadSpeed(i.length),this.emit("upload",i.length)}cancel(e,t,i){this._debug("cancel index=%d offset=%d length=%d",e,t,i),this._callback(this._pull(this.requests,e,t,i),new Error("request was cancelled"),null),this._message(8,[e,t,i],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,i){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("reject index=%d offset=%d length=%d",e,t,i),this._pull(this.peerRequests,e,t,i),this._message(16,[e,t,i],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 i=new Uint8Array([e]),n=ArrayBuffer.isView(t)?t:s.A.encode(t);this._message(20,[],(0,l.xW)([i,n]))}}async setEncrypt(e,t){if(!this.type.startsWith("tcp"))return!1;const i="tcpOutgoing"===this.type,s=new a([...await(0,l.tW)((0,l.fk)(this._utfToHex("keyA")+e+t))]),n=new a([...await(0,l.tW)((0,l.fk)(this._utfToHex("keyB")+e+t))]);this._encryptGenerator=i?s:n,this._decryptGenerator=i?n:s;for(let e=0;e<1024;e++)this._encryptGenerator.randomByte(),this._decryptGenerator.randomByte();return this._setGenerators=!0,this.emit("_generators"),!0}_message(e,t,i){const s=i?i.length:0,n=new Uint8Array(5+4*t.length);P(n,0,n.length+s-4),n[4]=e;for(let e=0;e<t.length;e++)P(n,5+4*e,t[e]);this._push(n),i&&this._push(i)}_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,l.V5)(e),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe1")}_onPe2(e){this._peerPubKey=(0,l.V5)(e),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe2")}async _onPe3(e){const t=await(0,l.tW)((0,l.fk)(this._utfToHex("req3")+this._sharedSecret)),i=(0,l.V5)(C(t,e));this.emit("pe3",i)}_onPe3Encrypted(e,t){if(!(0,l.LC)(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],S.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,i){const s=(0,l.V5)(e),n=(0,l.V5)(t);this._debug("got handshake i=%s p=%s exts=%o",s,n,i),this.peerId=n,this.peerIdBuffer=t,this.peerExtensions=i,this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this.emit("handshake",s,n,i);for(const e in this._ext)this._ext[e].onHandshake(s,n,i);i.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 n.A(e),this._debug("got bitfield"),this.emit("bitfield",this.peerPieces)}_onRequest(e,t,i){if(this.amChoking&&(!this.hasFast||!this.allowedFastSet.includes(e)))return void(this.hasFast&&this.reject(e,t,i));this._debug("got request index=%d offset=%d length=%d",e,t,i);const s=(s,r)=>{if(n===this._pull(this.peerRequests,e,t,i))return s?(this._debug("error satisfying request index=%d offset=%d length=%d (%s)",e,t,i,s.message),void(this.hasFast&&this.reject(e,t,i))):void this.piece(e,t,r)},n=new T(e,t,i,s);this.peerRequests.push(n),this.emit("request",e,t,i,s)}_onPiece(e,t,i){this._debug("got piece index=%d offset=%d",e,t),this._callback(this._pull(this.requests,e,t,i.length),null,i),this.downloaded+=i.length,this.downloadSpeed(i.length),this.emit("download",i.length),this.emit("piece",e,t,i)}_onCancel(e,t,i){this._debug("got cancel index=%d offset=%d length=%d",e,t,i),this._pull(this.peerRequests,e,t,i),this.emit("cancel",e,t,i)}_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 I,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,i){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,i),this._callback(this._pull(this.requests,e,t,i),new Error("request was rejected"),null),this.emit("reject",e,t,i)}_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=s.A.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,l.xW)(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.subarray(this._parserSize)]:[],this._parser(e.subarray(0,this._parserSize))}t(null)}_callback(e,t,i){e&&(this._resetTimeout(!this.peerChoking&&!this._finished),e.callback(t,i))}_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=A(e);t>0?this._parse(t,this._onMessage):(this._onKeepAlive(),this._parse(4,this._onMessageLength))}_onMessage(e){switch(this._parse(4,this._onMessageLength),e[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(A(e,1));case 5:return this._onBitField(e.subarray(1));case 6:return this._onRequest(A(e,1),A(e,5),A(e,9));case 7:return this._onPiece(A(e,1),A(e,5),e.subarray(9));case 8:return this._onCancel(A(e,1),A(e,5),A(e,9));case 9:return this._onPort(e[1]<<8|e[2]);case 13:return this._onSuggest(A(e,1));case 14:return this._onHaveAll();case 15:return this._onHaveNone();case 16:return this._onReject(A(e,1),A(e,5),A(e,9));case 17:return this._onAllowedFast(A(e,1));case 20:return this._onExtended(e[1],e.subarray(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,l.xW)([e,t])),this._parsePe3()})}_parsePe2(){this._parse(96,async e=>{this._onPe2(e),this._setGenerators||await new Promise(e=>this.once("_generators",e)),this._parsePe4()})}async _parsePe3(){const e=await(0,l.tW)((0,l.fk)(this._utfToHex("req1")+this._sharedSecret));this._parseUntil(e,512),this._parse(20,async e=>{this._onPe3(e),this._setGenerators||await new Promise(e=>this.once("_generators",e)),this._parsePe3Encrypted()})}_parsePe3Encrypted(){this._parse(14,e=>{const t=this._decryptHandshake(e.slice(0,8)),i=this._decryptHandshake(e.slice(8,12)),s=new DataView(this._decryptHandshake(e.slice(12,14)).buffer).getUint16(0);this._parse(s,e=>{e=this._decryptHandshake(e),this._parse(2,s=>{const n=new DataView(this._decryptHandshake(s).buffer).getUint16(0);this._parse(n,s=>{s=this._decryptHandshake(s),this._onPe3Encrypted(t,i,e,s);const r=n?s[0]:null,o=n?s.slice(1,20):null;19===r&&"BitTorrent protocol"===(0,l.dU)(o)?this._onHandshakeBuffer(s.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)),i=new DataView(this._decryptHandshake(e.slice(4,6)).buffer).getUint16(0);this._parse(i,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,l.dU)(t))return this._debug("Error: wire not speaking BitTorrent protocol (%s)",(0,l.dU)(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]}`,u(...e)}_pull(e,t,i,s){for(let n=0;n<e.length;n++){const r=e[n];if(r.piece===t&&r.offset===i&&r.length===s)return d(e,n),r}return null}_encryptHandshake(e){const t=new Uint8Array(e);if(!this._encryptGenerator)return this._debug("Warning: Encrypting without any generator"),t;for(let i=0;i<e.length;i++){const e=this._encryptGenerator.randomByte();t[i]=t[i]^e}return t}_encrypt(e){const t=new Uint8Array(e);if(!this._encryptGenerator||2!==this._encryptionMethod)return t;for(let i=0;i<e.length;i++){const e=this._encryptGenerator.randomByte();t[i]=t[i]^e}return t}_decryptHandshake(e){const t=new Uint8Array(e);if(!this._decryptGenerator)return this._debug("Warning: Decrypting without any generator"),t;for(let i=0;i<e.length;i++){const e=this._decryptGenerator.randomByte();t[i]=t[i]^e}return t}_decrypt(e){const t=new Uint8Array(e);if(!this._decryptGenerator||2!==this._encryptionMethod)return t;for(let i=0;i<e.length;i++){const e=this._decryptGenerator.randomByte();t[i]=t[i]^e}return t}_utfToHex(e){return(0,l.V5)((0,l.L0)(e))}}const O=L},6585:e=>{var t=1e3,i=60*t,s=60*i,n=24*s,r=7*n,o=365.25*n;function a(e,t,i,s){var n=t>=1.5*i;return Math.round(e/i)+" "+s+(n?"s":"")}e.exports=function(e,h){h=h||{};var l=typeof e;if("string"===l&&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*r;case"days":case"day":case"d":return h*n;case"hours":case"hour":case"hrs":case"hr":case"h":return h*s;case"minutes":case"minute":case"mins":case"min":case"m":return h*i;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"===l&&isFinite(e))return h.long?function(e){var r=Math.abs(e);if(r>=n)return a(e,r,n,"day");if(r>=s)return a(e,r,s,"hour");if(r>=i)return a(e,r,i,"minute");if(r>=t)return a(e,r,t,"second");return e+" ms"}(e):function(e){var r=Math.abs(e);if(r>=n)return Math.round(e/n)+"d";if(r>=s)return Math.round(e/s)+"h";if(r>=i)return Math.round(e/i)+"m";if(r>=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))}},6587:e=>{e.exports=function e(t,i){if(t&&i)return e(t)(i);if("function"!=typeof t)throw new TypeError("need wrapper function");return Object.keys(t).forEach(function(e){s[e]=t[e]}),s;function s(){for(var e=new Array(arguments.length),i=0;i<e.length;i++)e[i]=arguments[i];var s=t.apply(this,e),n=e[e.length-1];return"function"==typeof s&&s!==n&&Object.keys(n).forEach(function(e){s[e]=n[e]}),s}}},6611:(e,t,i)=>{var s=i(717),n=i(3519),r=function(){},o=globalThis.Bare?queueMicrotask:s.nextTick.bind(s),a=function(e,t,i){if("function"==typeof t)return a(e,null,t);t||(t={}),i=n(i||r);var s=e._writableState,h=e._readableState,l=t.readable||!1!==t.readable&&e.readable,c=t.writable||!1!==t.writable&&e.writable,d=!1,u=function(){e.writable||p()},p=function(){c=!1,l||i.call(e)},f=function(){l=!1,c||i.call(e)},m=function(t){i.call(e,t?new Error("exited with error code: "+t):null)},_=function(t){i.call(e,t)},g=function(){o(y)},y=function(){if(!d)return(!l||h&&h.ended&&!h.destroyed)&&(!c||s&&s.ended&&!s.destroyed)?void 0:i.call(e,new Error("premature close"))},w=function(){e.req.on("finish",p)};return!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?c&&!s&&(e.on("end",u),e.on("close",u)):(e.on("complete",p),e.on("abort",g),e.req?w():e.on("request",w)),function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length}(e)&&e.on("exit",m),e.on("end",f),e.on("finish",p),!1!==t.error&&e.on("error",_),e.on("close",g),function(){d=!0,e.removeListener("complete",p),e.removeListener("abort",g),e.removeListener("request",w),e.req&&e.req.removeListener("finish",p),e.removeListener("end",u),e.removeListener("close",u),e.removeListener("finish",p),e.removeListener("exit",m),e.removeListener("end",f),e.removeListener("error",_),e.removeListener("close",g)}};e.exports=a},6664:()=>{},6686:()=>{},6698: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 i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}}},6819:(e,t,i)=>{e.exports=i(8330).version},6889:()=>{},7007:e=>{var t=Object.create||function(e){var t=function(){};return t.prototype=e,new t},i=Object.keys||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.push(i);return i},s=Function.prototype.bind||function(e){var t=this;return function(){return t.apply(e,arguments)}};function n(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=t(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0;var r,o=10;try{var a={};Object.defineProperty&&Object.defineProperty(a,"x",{value:0}),r=0===a.x}catch(e){r=!1}function h(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function l(e,i,s,n){var r,o,a;if("function"!=typeof s)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",i,s.listener?s.listener:s),o=e._events),a=o[i]):(o=e._events=t(null),e._eventsCount=0),a){if("function"==typeof a?a=o[i]=n?[s,a]:[a,s]:n?a.unshift(s):a.push(s),!a.warned&&(r=h(e))&&r>0&&a.length>r){a.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+a.length+' "'+String(i)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');l.name="MaxListenersExceededWarning",l.emitter=e,l.type=i,l.count=a.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",l.name,l.message)}}else a=o[i]=s,++e._eventsCount;return e}function c(){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 d(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=s.call(c,n);return r.listener=i,n.wrapFn=r,r}function u(e,t,i){var s=e._events;if(!s)return[];var n=s[t];return n?"function"==typeof n?i?[n.listener||n]:[n]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(n):f(n,n.length):[]}function p(e){var t=this._events;if(t){var i=t[e];if("function"==typeof i)return 1;if(i)return i.length}return 0}function f(e,t){for(var i=new Array(t),s=0;s<t;++s)i[s]=e[s];return i}r?Object.defineProperty(n,"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}}):n.defaultMaxListeners=o,n.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},n.prototype.getMaxListeners=function(){return h(this)},n.prototype.emit=function(e){var t,i,s,n,r,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(!(i=o[e]))return!1;var l="function"==typeof i;switch(s=arguments.length){case 1:!function(e,t,i){if(t)e.call(i);else for(var s=e.length,n=f(e,s),r=0;r<s;++r)n[r].call(i)}(i,l,this);break;case 2:!function(e,t,i,s){if(t)e.call(i,s);else for(var n=e.length,r=f(e,n),o=0;o<n;++o)r[o].call(i,s)}(i,l,this,arguments[1]);break;case 3:!function(e,t,i,s,n){if(t)e.call(i,s,n);else for(var r=e.length,o=f(e,r),a=0;a<r;++a)o[a].call(i,s,n)}(i,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,i,s,n,r){if(t)e.call(i,s,n,r);else for(var o=e.length,a=f(e,o),h=0;h<o;++h)a[h].call(i,s,n,r)}(i,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(n=new Array(s-1),r=1;r<s;r++)n[r-1]=arguments[r];!function(e,t,i,s){if(t)e.apply(i,s);else for(var n=e.length,r=f(e,n),o=0;o<n;++o)r[o].apply(i,s)}(i,l,this,n)}return!0},n.prototype.addListener=function(e,t){return l(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return l(this,e,t,!0)},n.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,d(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,d(this,e,t)),this},n.prototype.removeListener=function(e,i){var s,n,r,o,a;if("function"!=typeof i)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(s=n[e]))return this;if(s===i||s.listener===i)0===--this._eventsCount?this._events=t(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,s.listener||i));else if("function"!=typeof s){for(r=-1,o=s.length-1;o>=0;o--)if(s[o]===i||s[o].listener===i){a=s[o].listener,r=o;break}if(r<0)return this;0===r?s.shift():function(e,t){for(var i=t,s=i+1,n=e.length;s<n;i+=1,s+=1)e[i]=e[s];e.pop()}(s,r),1===s.length&&(n[e]=s[0]),n.removeListener&&this.emit("removeListener",e,a||i)}return this},n.prototype.removeAllListeners=function(e){var s,n,r;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=t(null),this._eventsCount=0):n[e]&&(0===--this._eventsCount?this._events=t(null):delete n[e]),this;if(0===arguments.length){var o,a=i(n);for(r=0;r<a.length;++r)"removeListener"!==(o=a[r])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=t(null),this._eventsCount=0,this}if("function"==typeof(s=n[e]))this.removeListener(e,s);else if(s)for(r=s.length-1;r>=0;r--)this.removeListener(e,s[r]);return this},n.prototype.listeners=function(e){return u(this,e,!0)},n.prototype.rawListeners=function(e){return u(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},n.prototype.listenerCount=p,n.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},7264:()=>{},7373:e=>{e.exports=function(e){var t=0;return function(){if(t===e.length)return null;var i=e.length-t,s=Math.random()*i|0,n=e[t+s],r=e[t];return e[t]=n,e[t+s]=r,t++,n}}},7541:(e,t,i)=>{const s=i(8765),n=i(8499);e.exports={Throttle:s,ThrottleGroup:n}},7828:()=>{},7833:(e,t,i)=>{var s=i(717);t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const i="color: "+this.color;t.splice(1,0,i,"color: inherit");let s=0,n=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(s++,"%c"===e&&(n=s))}),t.splice(n,0,i)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&void 0!==s&&"env"in s&&(e=s.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;let e;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&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[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=i(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},8179:(e,t,i)=>{const{EventEmitter:s}=i(7007),n=new Error("Stream was destroyed"),r=new Error("Premature close"),o=i(6080),a=i(5335),h="undefined"==typeof queueMicrotask?e=>globalThis.process.nextTick(e):queueMicrotask,l=536870911,c=1^l,d=2^l,u=32,p=64,f=128,m=256,_=1024,g=2048,y=4096,w=8192,b=16384,v=32768,k=131072,x=131328,S=16^l,E=536805375,C=768^l,A=536838143,P=536739839,T=1<<18,I=2<<18,L=4<<18,O=8<<18,R=16<<18,H=32<<18,N=64<<18,M=128<<18,F=256<<18,U=512<<18,j=1024<<18,B=535822335,D=503316479,q=268435455,W=262160,$=536608751,z=8404992,V=14,G=15,K=8405006,Y=33587200,J=33587215,X=2359296,Q=270794767,Z=Symbol.asyncIterator||Symbol("asyncIterator");class ee{constructor(e,{highWaterMark:t=16384,map:i=null,mapWritable:s,byteLength:n,byteLengthWritable:r}={}){this.stream=e,this.queue=new o,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=r||n||Se,this.map=s||i,this.afterWrite=ae.bind(this),this.afterUpdateNextTick=ce.bind(this)}get ended(){return 0!==(this.stream._duplexState&H)}push(e){return!(142606350&this.stream._duplexState)&&(null!==this.map&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=O,!0):(this.stream._duplexState|=6291456,!1))}shift(){const e=this.queue.shift();return this.buffered-=this.byteLength(e),0===this.buffered&&(this.stream._duplexState&=534773759),e}end(e){"function"==typeof e?this.stream.once("finish",e):null!=e&&this.push(e),this.stream._duplexState=(this.stream._duplexState|U)&B}autoBatch(e,t){const i=[],s=this.stream;for(i.push(e);(s._duplexState&Q)===X;)i.push(s._writableState.shift());if(0!==(s._duplexState&G))return t(null);s._writev(i,t)}update(){const e=this.stream;e._duplexState|=I;do{for(;(e._duplexState&Q)===O;){const t=this.shift();e._duplexState|=67371008,e._write(t,this.afterWrite)}1310720&e._duplexState||this.updateNonPrimary()}while(!0===this.continueUpdate());e._duplexState&=536346623}updateNonPrimary(){const e=this.stream;if((144965647&e._duplexState)===U)return e._duplexState=e._duplexState|T,void e._final(re.bind(this));4!==(e._duplexState&V)?1===(e._duplexState&J)&&(e._duplexState=(e._duplexState|W)&c,e._open(de.bind(this))):0===(e._duplexState&Y)&&(e._duplexState|=W,e._destroy(oe.bind(this)))}continueUpdate(){return 0!==(this.stream._duplexState&M)&&(this.stream._duplexState&=D,!0)}updateCallback(){(35127311&this.stream._duplexState)===L?this.update():this.updateNextTick()}updateNextTick(){0===(this.stream._duplexState&M)&&(this.stream._duplexState|=M,0===(this.stream._duplexState&I)&&h(this.afterUpdateNextTick))}}class te{constructor(e,{highWaterMark:t=16384,map:i=null,mapReadable:s,byteLength:n,byteLengthReadable:r}={}){this.stream=e,this.queue=new o,this.highWaterMark=0===t?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=r||n||Se,this.map=s||i,this.pipeTo=null,this.afterRead=he.bind(this),this.afterUpdateNextTick=le.bind(this)}get ended(){return 0!==(this.stream._duplexState&b)}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 se(this.stream,e,t),t&&this.stream.on("error",Ee),xe(e))e._writableState.pipeline=this.pipeline,t&&e.on("error",Ee),e.on("finish",this.pipeline.finished.bind(this.pipeline));else{const t=this.pipeline.done.bind(this.pipeline,e),i=this.pipeline.done.bind(this.pipeline,e,null);e.on("error",t),e.on("close",i),e.on("finish",this.pipeline.finished.bind(this.pipeline))}e.on("drain",ne.bind(this)),this.stream.emit("piping",e),e.emit("pipe",this.stream)}push(e){const t=this.stream;return null===e?(this.highWaterMark=0,t._duplexState=536805311&t._duplexState|1024,!1):null!==this.map&&null===(e=this.map(e))?(t._duplexState&=E,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=(t._duplexState|f)&E,this.buffered<this.highWaterMark)}shift(){const e=this.queue.shift();return this.buffered-=this.byteLength(e),0===this.buffered&&(this.stream._duplexState&=536862591),e}unshift(e){const t=[null!==this.map?this.map(e):e];for(;this.buffered>0;)t.push(this.shift());for(let e=0;e<t.length-1;e++){const i=t[e];this.buffered+=this.byteLength(i),this.queue.push(i)}this.push(t[t.length-1])}read(){const e=this.stream;if((16527&e._duplexState)===f){const t=this.shift();return null!==this.pipeTo&&!1===this.pipeTo.write(t)&&(e._duplexState&=C),0!==(e._duplexState&g)&&e.emit("data",t),t}return!1===this.readAhead&&(e._duplexState|=k,this.updateNextTick()),null}drain(){const e=this.stream;for(;(16527&e._duplexState)===f&&768&e._duplexState;){const t=this.shift();null!==this.pipeTo&&!1===this.pipeTo.write(t)&&(e._duplexState&=C),0!==(e._duplexState&g)&&e.emit("data",t)}}update(){const e=this.stream;e._duplexState|=u;do{for(this.drain();this.buffered<this.highWaterMark&&(214047&e._duplexState)===k;)e._duplexState|=65552,e._read(this.afterRead),this.drain();4224==(12431&e._duplexState)&&(e._duplexState|=w,e.emit("readable")),80&e._duplexState||this.updateNonPrimary()}while(!0===this.continueUpdate());e._duplexState&=536870879}updateNonPrimary(){const e=this.stream;(1167&e._duplexState)===_&&(e._duplexState=536869887&e._duplexState|16384,e.emit("end"),(e._duplexState&K)===z&&(e._duplexState|=4),null!==this.pipeTo&&this.pipeTo.end()),4!==(e._duplexState&V)?1===(e._duplexState&J)&&(e._duplexState=(e._duplexState|W)&c,e._open(de.bind(this))):0===(e._duplexState&Y)&&(e._duplexState|=W,e._destroy(oe.bind(this)))}continueUpdate(){return 0!==(this.stream._duplexState&v)&&(this.stream._duplexState&=A,!0)}updateCallback(){(32879&this.stream._duplexState)===p?this.update():this.updateNextTick()}updateNextTickIfOpen(){32769&this.stream._duplexState||(this.stream._duplexState|=v,0===(this.stream._duplexState&u)&&h(this.afterUpdateNextTick))}updateNextTick(){0===(this.stream._duplexState&v)&&(this.stream._duplexState|=v,0===(this.stream._duplexState&u)&&h(this.afterUpdateNextTick))}}class ie{constructor(e){this.data=null,this.afterTransform=ue.bind(e),this.afterFinal=null}}class se{constructor(e,t,i){this.from=e,this.to=t,this.afterPipe=i,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&b)&&this.to.destroy(this.error||new Error("Readable stream closed before ending")):0!==(this.from._duplexState&b)&&this.pipeToFinished||this.from.destroy(this.error||new Error("Writable stream closed prematurely"))}}function ne(){this.stream._duplexState|=512,this.updateCallback()}function re(e){const t=this.stream;e&&t.destroy(e),0===(t._duplexState&V)&&(t._duplexState|=H,t.emit("finish")),(t._duplexState&K)===z&&(t._duplexState|=4),t._duplexState&=402391039,0===(t._duplexState&I)?this.update():this.updateNextTick()}function oe(e){const t=this.stream;e||this.error===n||(e=this.error),e&&t.emit("error",e),t._duplexState|=8,t.emit("close");const i=t._readableState,s=t._writableState;if(null!==i&&null!==i.pipeline&&i.pipeline.done(t,e),null!==s){for(;null!==s.drains&&s.drains.length>0;)s.drains.shift().resolve(!1);null!==s.pipeline&&s.pipeline.done(t,e)}}function ae(e){const t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,null!==this.drains&&function(e){for(let t=0;t<e.length;t++)0===--e[t].writes&&(e.shift().resolve(!0),t--)}(this.drains),(6553615&t._duplexState)===R&&(t._duplexState&=532676607,(t._duplexState&N)===N&&t.emit("drain")),this.updateCallback()}function he(e){e&&this.stream.destroy(e),this.stream._duplexState&=S,!1===this.readAhead&&0===(this.stream._duplexState&m)&&(this.stream._duplexState&=P),this.updateCallback()}function le(){0===(this.stream._duplexState&u)&&(this.stream._duplexState&=A,this.update())}function ce(){0===(this.stream._duplexState&I)&&(this.stream._duplexState&=D,this.update())}function de(e){const t=this.stream;e&&t.destroy(e),4&t._duplexState||(17423&t._duplexState||(t._duplexState|=p),142606351&t._duplexState||(t._duplexState|=L),t.emit("open")),t._duplexState&=$,null!==t._writableState&&t._writableState.updateCallback(),null!==t._readableState&&t._readableState.updateCallback()}function ue(e,t){null!=t&&this.push(t),this._writableState.afterWrite(e)}function pe(e){null!==this._readableState&&("data"===e&&(this._duplexState|=133376,this._readableState.updateNextTick()),"readable"===e&&(this._duplexState|=y,this._readableState.updateNextTick())),null!==this._writableState&&"drain"===e&&(this._duplexState|=N,this._writableState.updateNextTick())}class fe extends s{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",Ce.bind(this))),this.on("newListener",pe)}_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return null!==this._readableState||void 0}get writable(){return null!==this._writableState||void 0}get destroyed(){return!!(8&this._duplexState)}get destroying(){return 0!==(this._duplexState&V)}destroy(e){0===(this._duplexState&V)&&(e||(e=n),this._duplexState=535822271&this._duplexState|4,null!==this._readableState&&(this._readableState.highWaterMark=0,this._readableState.error=e),null!==this._writableState&&(this._writableState.highWaterMark=0,this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=d,null!==this._readableState&&this._readableState.updateNextTick(),null!==this._writableState&&this._writableState.updateNextTick())}}class me extends fe{constructor(e){super(e),this._duplexState|=8519681,this._readableState=new te(this,e),e&&(!1===this._readableState.readAhead&&(this._duplexState&=P),e.read&&(this._read=e.read),e.eagerOpen&&this._readableState.updateNextTick(),e.encoding&&this.setEncoding(e.encoding))}setEncoding(e){const t=new a(e),i=this._readableState.map||ve;return this._readableState.map=function(e){const s=t.push(e);return""===s&&(0!==e.byteLength||t.remaining>0)?null:i(s)},this}_read(e){e(null)}pipe(e,t){return this._readableState.updateNextTick(),this._readableState.pipe(e,t),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTickIfOpen(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(e)}resume(){return this._duplexState|=x,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=!1===this._readableState.readAhead?536739583:536870655,this}static _fromAsyncIterator(e,t){let i;const s=new me({...t,read(t){e.next().then(n).then(t.bind(null,null)).catch(t)},predestroy(){i=e.return()},destroy(e){if(!i)return e(null);i.then(e.bind(null,null)).catch(e)}});return s;function n(e){e.done?s.push(null):s.push(e.value)}}static from(e,t){if(xe(i=e)&&i.readable)return e;var i;if(e[Z])return this._fromAsyncIterator(e[Z](),t);Array.isArray(e)||(e=void 0===e?[]:[e]);let s=0;return new me({...t,read(t){this.push(s===e.length?null:e[s++]),t(null)}})}static isBackpressured(e){return!!(17422&e._duplexState)||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return 0===(e._duplexState&m)}[Z](){const e=this;let t=null,i=null,s=null;return this.on("error",e=>{t=e}),this.on("readable",function(){null!==i&&r(e.read())}),this.on("close",function(){null!==i&&r(null)}),{[Z](){return this},next:()=>new Promise(function(t,n){i=t,s=n;const o=e.read();null!==o?r(o):8&e._duplexState&&r(null)}),return:()=>o(null),throw:e=>o(e)};function r(r){null!==s&&(t?s(t):null===r&&0===(e._duplexState&b)?s(n):i({value:r,done:null===r}),s=i=null)}function o(t){return e.destroy(t),new Promise((i,s)=>{if(8&e._duplexState)return i({value:void 0,done:!0});e.once("close",function(){t?s(t):i({value:void 0,done:!0})})})}}}class _e extends fe{constructor(e){super(e),this._duplexState|=16385,this._writableState=new ee(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final),e.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=j}uncork(){this._duplexState&=q,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return!!(146800654&e._duplexState)}static drained(e){if(e.destroyed)return Promise.resolve(!1);const t=e._writableState;var i;const s=((i=e)._writev!==_e.prototype._writev&&i._writev!==ge.prototype._writev?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&F?1:0);return 0===s?Promise.resolve(!0):(null===t.drains&&(t.drains=[]),new Promise(e=>{t.drains.push({writes:s,resolve:e})}))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}}class ge extends me{constructor(e){super(e),this._duplexState=1|this._duplexState&k,this._writableState=new ee(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=j}uncork(){this._duplexState&=q,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}}class ye extends ge{constructor(e){super(e),this._transformState=new ie(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)}destroy(e){super.destroy(e),null!==this._transformState.data&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(e,t){t(null,e)}_flush(e){e(null)}_final(e){this._transformState.afterFinal=e,this._flush(we.bind(this))}}function we(e,t){const i=this._transformState.afterFinal;if(e)return i(e);null!=t&&this.push(t),this.push(null),i(null)}function be(e,...t){const i=Array.isArray(e)?[...e,...t]:[e,...t],s=i.length&&"function"==typeof i[i.length-1]?i.pop():null;if(i.length<2)throw new Error("Pipeline requires at least 2 streams");let n=i[0],o=null,a=null;for(let e=1;e<i.length;e++)o=i[e],xe(n)?n.pipe(o,l):(h(n,!0,e>1,l),n.pipe(o)),n=o;if(s){let e=!1;const t=xe(o)||!(!o._writableState||!o._writableState.autoDestroy);o.on("error",e=>{null===a&&(a=e)}),o.on("finish",()=>{e=!0,t||s(a)}),t&&o.on("close",()=>s(a||(e?null:r)))}return o;function h(e,t,i,s){e.on("error",s),e.on("close",function(){if(t&&e._readableState&&!e._readableState.ended)return s(r);if(i&&e._writableState&&!e._writableState.ended)return s(r)})}function l(e){if(e&&!a){a=e;for(const t of i)t.destroy(e)}}}function ve(e){return e}function ke(e){return!!e._readableState||!!e._writableState}function xe(e){return"number"==typeof e._duplexState&&ke(e)}function Se(e){return function(e){return"object"==typeof e&&null!==e&&"number"==typeof e.byteLength}(e)?e.byteLength:1024}function Ee(){}function Ce(){this.destroy(new Error("Stream aborted."))}e.exports={pipeline:be,pipelinePromise:function(...e){return new Promise((t,i)=>be(...e,e=>{if(e)return i(e);t()}))},isStream:ke,isStreamx:xe,isEnded:function(e){return!!e._readableState&&e._readableState.ended},isFinished:function(e){return!!e._writableState&&e._writableState.ended},isDisturbed:function(e){return!!(1&~e._duplexState)||0!==(e._duplexState&Y)},getStreamError:function(e,t={}){const i=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return t.all||i!==n?i:null},Stream:fe,Writable:_e,Readable:me,Duplex:ge,Transform:ye,PassThrough:class extends ye{}}},8190:(e,t,i)=>{e.exports=function(e,t){let i,n,r,o=!0;Array.isArray(e)?(i=[],n=e.length):(r=Object.keys(e),i={},n=r.length);function a(e){function n(){t&&t(e,i),t=null}o?s(n):n()}function h(e,t,s){i[e]=s,(0===--n||t)&&a(t)}n?r?r.forEach(function(t){e[t](function(e,i){h(t,e,i)})}):e.forEach(function(e,t){e(function(e,i){h(t,e,i)})}):a(null);o=!1};const s=i(9596)},8271:()=>{},8330:e=>{e.exports={version:"2.8.5"}},8436:()=>{},8444:e=>{e.exports=function(e){return Math.max(16384,1<<Math.log2(e<1024?1:e/1024)+.5)}},8446: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"]}},8454:(e,t,i)=>{var s=i(7007),n=i(6698);function r(e){if(!(this instanceof r))return new r(e);"number"==typeof e&&(e={max:e}),e||(e={}),s.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=r,n(r,s.EventEmitter),Object.defineProperty(r.prototype,"keys",{get:function(){return Object.keys(this.cache)}}),r.prototype.clear=function(){this.cache={},this.head=this.tail=null,this.length=0},r.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}},r.prototype._unlink=function(e,t,i){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=i,this.cache[this.tail].prev=null):(this.cache[t].next=i,this.cache[i].prev=t)},r.prototype.peek=function(e){if(this.cache.hasOwnProperty(e)){var t=this.cache[e];if(this._checkAge(e,t))return t.value}},r.prototype.set=function(e,t){var i;if("string"!=typeof e&&(e=""+e),this.cache.hasOwnProperty(e)){if((i=this.cache[e]).value=t,this.maxAge&&(i.modified=Date.now()),e===this.head)return t;this._unlink(e,i.prev,i.next)}else i={value:t,modified:0,next:null,prev:null},this.maxAge&&(i.modified=Date.now()),this.cache[e]=i,this.length===this.max&&this.evict();return this.length++,i.next=null,i.prev=this.head,this.head&&(this.cache[this.head].next=e),this.head=e,this.tail||(this.tail=e),t},r.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)},r.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}},r.prototype.evict=function(){if(this.tail){var e=this.tail,t=this.remove(this.tail);this.emit("evict",{key:e,value:t})}}},8499:(e,t,i)=>{const{TokenBucket:s}=i(9439),n=i(8765);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 s(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 n({...e,group:this})}destroy(){for(const e of this.throttles)e.destroy();this.throttles=[]}_addThrottle(e){if(!(e instanceof n))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)}}},8529:()=>{},8673: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 i in e){let s=e[i].map(function(e){return e.toLowerCase()});i=i.toLowerCase();for(let e=0;e<s.length;e++){const n=s[e];if("*"!==n[0]){if(!t&&n in this._types)throw new Error('Attempt to change mapping for "'+n+'" extension from "'+this._types[n]+'" to "'+i+'". Pass `force=true` to allow this, otherwise remove "'+n+'" from the list of extensions for "'+i+'".');this._types[n]=i}}if(t||!this._extensions[i]){const e=s[0];this._extensions[i]="*"!==e[0]?e:e.substr(1)}}},t.prototype.getType=function(e){let t=(e=String(e)).replace(/^.*[/\\]/,"").toLowerCase(),i=t.replace(/^.*\./,"").toLowerCase(),s=t.length<e.length;return(i.length<t.length-1||!s)&&this._types[i]||null},t.prototype.getExtension=function(e){return(e=/^\s*([^;\s]*)/.test(e)&&RegExp.$1)&&this._extensions[e.toLowerCase()]||null},e.exports=t},8727:e=>{function t(e){return parseInt(e,10)===e}function i(e){function i(t){if(void 0===t){t=new Array(e);for(var i=0;i<e;i++)t[i]=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 s=t.length,n=function(){for(var t=new Array(e),i=0;i<e;i++)t[i]=i;return t}(),r=0,o=0;o<e;o++){r=(r+n[o]+t[o%s])%e;var a=n[o];n[o]=n[r],n[r]=a}return n}function s(e){this.s=i(e),this.i=0,this.j=0}return s.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]},s.prototype.randomUInt32=function(){return 256*(256*(256*this.randomByte()+this.randomByte())+this.randomByte())+this.randomByte()},s.prototype.randomFloat=function(){return this.randomUInt32()/4294967296},s.prototype.random=function(){var e,i;if(1===arguments.length)e=0,i=arguments[0];else{if(2!==arguments.length)throw new TypeError("random takes one or two integer arguments");e=arguments[0],i=arguments[1]}if(!t(e)||!t(i))throw new TypeError("random takes one or two integer arguments");return e+this.randomUInt32()%(i-e+1)},s.prototype.currentState=function(){return{i:this.i,j:this.j,s:this.s.slice()}},s.prototype.setState=function(t){var i=t.s,s=t.i,n=t.j;if(!(s===(0|s)&&0<=s&&s<e))throw new Error("state.i should be integer [0, "+(e-1)+"]");if(!(n===(0|n)&&0<=n&&n<e))throw new Error("state.j should be integer [0, "+(e-1)+"]");if(!Array.isArray(i)||i.length!==e)throw new Error("state should be array of length "+e);for(var r=0;r<e;r++)if(-1===i.indexOf(r))throw new Error("state should be permutation of 0.."+(e-1)+": "+r+" is missing");this.i=s,this.j=n,this.s=i.slice()},s}var s=i(256);s.prototype.randomByte=s.prototype.randomNative;var n=i(16);n.prototype.randomByte=function(){return 16*this.randomNative()+this.randomNative()};var r="a".charCodeAt(0),o="0".charCodeAt(0);function a(e){return e<10?String.fromCharCode(o+e):String.fromCharCode(r+e-10)}function h(e){return parseInt(e,16)}n.prototype.currentStateString=function(){var e=this.currentState();return a(e.i)+a(e.j)+e.s.map(a).join("")},n.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]),i=h(e[1]),s=e.split("").slice(2).map(h);this.setState({i:t,j:i,s})},s.RC4small=n,e.exports=s},8765:(e,t,i)=>{const{EventEmitter:s}=i(7007),{Transform:n}=i(8179),{wait:r}=i(2072);e.exports=class extends n{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 s,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,i)=>{let s=!1;const n=this;function r(e){if(n._emitter.removeListener("disabled",r),n._emitter.removeListener("destroyed",r),!s){if(s=!0,e)return i(e);t()}}this._emitter.once("disabled",r),this._emitter.once("destroyed",r),this._group.bucket.removeTokens(e,r)})}_areBothEnabled(){return this._enabled&&this._group.getEnabled()}async _processChunk(e,t){if(!this._areBothEnabled())return t(null,e);let i=0,s=this._group.getChunksize(),n=e.slice(i,i+s);for(;n.length>0;){if(this._areBothEnabled())try{for(;0===this._group.getRate()&&!this._destroyed&&this._areBothEnabled();)if(await r(1e3),this._destroyed)return;if(this._areBothEnabled()&&!this._group.bucket.tryRemoveTokens(n.length)&&(await this._waitForTokens(n.length),this._destroyed))return}catch(e){return t(e)}this.push(n),i+=s,s=this._areBothEnabled()?this._group.getChunksize():e.length-i,n=e.slice(i,i+s)}return t()}destroy(...e){this._group._removeThrottle(this),this._destroyed=!0,this._emitter.emit("destroyed"),super.destroy(...e)}};const o=i(8499)},8878:()=>{},9439:(e,t,i)=>{t.RateLimiter=i(3065),t.TokenBucket=i(5472)},9596: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))},9639:(e,t,i)=>{i.d(t,{NJ:()=>g,V5:()=>o,dU:()=>f,HB:()=>y,xW:()=>h,LC:()=>l,tW:()=>S,fk:()=>a,Ht:()=>w,po:()=>E,L0:()=>_});const s="0123456789abcdef",n=[],r=[];for(let e=0;e<256;e++)n[e]=s[e>>4&15]+s[15&e],e<16&&(e<10?r[48+e]=e:r[87+e]=e);const o=e=>{const t=e.length;let i="",s=0;for(;s<t;)i+=n[e[s++]];return i},a=e=>{const t=e.length>>1,i=t<<1,s=new Uint8Array(t);let n=0,o=0;for(;o<i;)s[n++]=r[e.charCodeAt(o++)]<<4|r[e.charCodeAt(o++)];return s},h=(e,t=0)=>{const i=e.length||0;if(!t){let s=i;for(;s--;)t+=e[s].length}const s=new Uint8Array(t);let n=t,r=i;for(;r--;)n-=e[r].length,s.set(e[r],n);return s},l=(e,t)=>{if(e.length!==t.length)return!1;for(let i=e.length;i>-1;i-=1)if(e[i]!==t[i])return!1;return!0};for(var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d="undefined"==typeof Uint8Array?[]:new Uint8Array(256),u=0;u<64;u++)d[c.charCodeAt(u)]=u;const p=new TextDecoder,f=(e,t)=>{if(!t)return p.decode(e);return new TextDecoder(t).decode(e)},m=new TextEncoder,_=e=>m.encode(e),g=e=>function(e){var t,i=new Uint8Array(e),s=i.length,n="";for(t=0;t<s;t+=3)n+=c[i[t]>>2],n+=c[(3&i[t])<<4|i[t+1]>>4],n+=c[(15&i[t+1])<<2|i[t+2]>>6],n+=c[63&i[t+2]];return s%3==2?n=n.substring(0,n.length-1)+"=":s%3==1&&(n=n.substring(0,n.length-2)+"=="),n}(e),y=e=>{let t,i="",n=0;const r=e.length;for(;n<r;)t=e.charCodeAt(n++),i+=s[t>>4]+s[15&t];return i},w=e=>{const t=a(e);if(t.length<=65536)return String.fromCharCode(...t);let i="",s=0;for(;s<t.length;)i+=String.fromCharCode(...t.subarray(s,s+=65536));return i},b="undefined"!=typeof window?window:self,v=b.crypto||b.msCrypto||{},k=v.subtle||v.webkitSubtle,x={hex:o,base64:g},S=async(e,t,i="sha-1")=>{if(!k)throw new Error("no web crypto support");"string"==typeof e&&(e=_(e));const s=new Uint8Array(await k.digest(i,e));return t?x[t](s):s},E=e=>{const t=new Uint8Array(e);return v.getRandomValues(t)}}},s={};function n(e){var t=s[e];if(void 0!==t)return t.exports;var r=s[e]={exports:{}};return i[e](r,r.exports,n),r.exports}t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,n.t=function(i,s){if(1&s&&(i=this(i)),8&s)return i;if("object"==typeof i&&i){if(4&s&&i.__esModule)return i;if(16&s&&"function"==typeof i.then)return i}var r=Object.create(null);n.r(r);var o={};e=e||[null,t({}),t([]),t(t)];for(var a=2&s&&i;("object"==typeof a||"function"==typeof a)&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach(e=>o[e]=()=>i[e]);return o.default=()=>i,n.d(r,o),r},n.d=(e,t)=>{for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r=n(7007);function o(e){if("string"!=typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function a(e,t){let i,s="",n=0,r=-1,o=0;for(let a=0;a<=e.length;++a){if(a<e.length)i=e.charCodeAt(a);else{if(47===i)break;i=47}if(47===i){if(r===a-1||1===o);else if(r!==a-1&&2===o){if(s.length<2||2!==n||46!==s.charCodeAt(s.length-1)||46!==s.charCodeAt(s.length-2))if(s.length>2){const e=s.lastIndexOf("/");if(e!==s.length-1){-1===e?(s="",n=0):(s=s.slice(0,e),n=s.length-1-s.lastIndexOf("/")),r=a,o=0;continue}}else if(2===s.length||1===s.length){s="",n=0,r=a,o=0;continue}t&&(s.length>0?s+="/..":s="..",n=2)}else s.length>0?s+="/"+e.slice(r+1,a):s=e.slice(r+1,a),n=a-r-1;r=a,o=0}else 46===i&&-1!==o?++o:o=-1}return s}function h(){if(0===arguments.length)return".";let e;for(let t=0;t<arguments.length;++t){const i=arguments[t];o(i),i.length>0&&(void 0===e?e=i:e+="/"+i)}return void 0===e?".":function(e){if(o(e),0===e.length)return".";const t=47===e.charCodeAt(0),i=47===e.charCodeAt(e.length-1);return 0!==(e=a(e,!t)).length||t||(e="."),e.length>0&&i&&(e+="/"),t?"/"+e:e}(e)}n(717);const l="/";var c=n(988),d=n(1467),u=n(8444),p=n(2123);const f=new RegExp(["^npm-debug\\.log$","^\\..*\\.swp$","^\\.DS_Store$","^\\.AppleDouble$","^\\.LSOverride$","^Icon\\r$","^\\._.*","^\\.Spotlight-V100(?:$|\\/)","\\.Trashes","^__MACOSX$","~$","^Thumbs\\.db$","^ehthumbs\\.db$","^[Dd]esktop\\.ini$","@eaDir$"].join("|"));function m(e){return f.test(e)}var _=n(405),g=n(8190),y=n(9596),w=n(9639),b=(n(3468),n(2532));const v=[["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://tracker.opentrackr.org:1337"],["udp://explodie.org:6969"],["udp://tracker.empire-js.us:1337"],["wss://tracker.btorrent.xyz"],["wss://tracker.openwebtorrent.com"],["wss://tracker.webtorrent.dev"]];const k=Symbol("itemPath");function x(e,t,i){var s;if(s=e,"undefined"!=typeof FileList&&s 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=>C(e)&&"string"==typeof e.path&&"function"==typeof b?e.path:e)).length||"string"==typeof e[0]||e[0].name||(e[0].name=t.name);let n=null;e.forEach((t,i)=>{if("string"==typeof t)return;let s=t.fullPath||t.name;s||(s=`Unknown File ${i+1}`,t.unknownName=!0),t[k]=s.split("/"),t[k][0]||t[k].shift(),t[k].length<2?n=null:0===i&&e.length>1?n=t[k][0]:t[k][0]!==n&&(n=null)});(void 0===t.filterJunkFiles||t.filterJunkFiles)&&(e=e.filter(e=>"string"==typeof e||!function(e){const t=e[e.length-1];return"."===t[0]&&m(t)}(e[k]))),n&&e.forEach(e=>{const t=(ArrayBuffer.isView(e)||A(e))&&!e[k];"string"==typeof e||t||e[k].shift()}),!t.name&&n&&(t.name=n),t.name||e.some(e=>"string"==typeof e?(t.name=function(e,t){if(void 0!==t&&"string"!=typeof t)throw new TypeError('"ext" argument must be a string');o(e);let i,s=0,n=-1,r=!0;if(void 0!==t&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";let o=t.length-1,a=-1;for(i=e.length-1;i>=0;--i){const h=e.charCodeAt(i);if(47===h){if(!r){s=i+1;break}}else-1===a&&(r=!1,a=i+1),o>=0&&(h===t.charCodeAt(o)?-1===--o&&(n=i):(o=-1,n=a))}return s===n?n=a:-1===n&&(n=e.length),e.slice(s,n)}for(i=e.length-1;i>=0;--i)if(47===e.charCodeAt(i)){if(!r){s=i+1;break}}else-1===n&&(r=!1,n=i+1);return-1===n?"":e.slice(s,n)}(e),!0):!e.unknownName&&(t.name=e[k][e[k].length-1],!0)),t.name||(t.name=`Unnamed Torrent ${Date.now()}`),t.maxPieceLength||(t.maxPieceLength=4194304);const r=e.reduce((e,t)=>e+Number("string"==typeof t),0);let a=1===e.length;if(1===e.length&&"string"==typeof e[0]){if("function"!=typeof b)throw new Error("filesystem paths do not work in the browser");p(e[0],(e,t)=>{if(e)return i(e);a=t,h()})}else y(h);function h(){g(e.map(e=>t=>{const i={};if(C(e))i.getStream=e.stream(),i.length=e.size;else if(ArrayBuffer.isView(e))i.getStream=[e],i.length=e.length;else{if(!A(e)){if("string"==typeof e){if("function"!=typeof b)throw new Error("filesystem paths do not work in the browser");return void b(e,r>1||a,t)}throw new Error("invalid input type")}i.getStream=async function*(e,t){for await(const i of e)t.length+=i.length,yield i}(e,i),i.length=0}i.path=e[k],t(null,i)}),(e,t)=>{if(e)return i(e);t=t.flat(),i(null,t,a)})}}const S=5;function E(e,t){return e+t.length}function C(e){return"undefined"!=typeof Blob&&e instanceof Blob}function A(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}const P=function(e,t,i){"function"==typeof t&&([t,i]=[i,t]),x(e,t=t?Object.assign({},t):{},(e,s,n)=>{if(e)return i(e);t.singleFileTorrent=n,function(e,t,i){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(v));"string"==typeof t.urlList&&(t.urlList=[t.urlList]);const n={info:{name:t.name},"creation date":Math.ceil((Number(t.creationDate)||Date.now())/1e3),encoding:"UTF-8"};0!==s.length&&(n.announce=s[0][0],n["announce-list"]=s);void 0!==t.comment&&(n.comment=t.comment);void 0!==t.createdBy&&(n["created by"]=t.createdBy);void 0!==t.private&&(n.info.private=Number(t.private));void 0!==t.info&&Object.assign(n.info,t.info);void 0!==t.sslCert&&(n.info["ssl-cert"]=t.sslCert);void 0!==t.urlList&&(n["url-list"]=t.urlList);const r=e.reduce(E,0),o=t.pieceLength||Math.min(u(r),t.maxPieceLength);n.info["piece length"]=o,async function(e,t,i,s,n){const r=[];let o=0,a=0;const h=e.map(e=>e.getStream),l=s.onProgress;let c=0,u=0,p=!1;const f=d(_(h),t,{zeroPadding:!1});try{for await(const e of f)await new Promise(t=>{o+=e.length;const s=u;++u,++c<S&&t(),(0,w.tW)(e,"hex").then(h=>{r[s]=h,--c,a+=e.length,l&&l(a,i),t(),p&&0===c&&n(null,(0,w.fk)(r.join("")),o)})});if(0===c)return n(null,(0,w.fk)(r.join("")),o);p=!0}catch(e){n(e)}}(e,o,r,t,(s,r,o)=>{if(s)return i(s);n.info.pieces=r,e.forEach(e=>{delete e.getStream}),t.singleFileTorrent?n.info.length=o:n.info.files=e,i(null,c.A.encode(n))})}(s,t,i)})};var T=n(7833),I=n(6664),L=n(1827),O=n(3208);self.Blob,self.File,self.FormData,self.Headers,self.Request,self.Response,self.AbortController,self.AbortSignal;const R=self.fetch||(()=>{throw new Error("global fetch is not available!")}),H=[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];const N=function(e){if(!ArrayBuffer.isView(e)&&"string"!=typeof e)throw new TypeError("base32.decode only takes Buffer or string as parameter");let t,i=0,s=0,n=0;ArrayBuffer.isView(e)||(e=(0,w.L0)(e));const r=new Uint8Array(Math.ceil(5*e.length/8));for(let o=0;o<e.length&&61!==e[o];o++){const a=e[o]-48;if(!(a<H.length))throw new Error("Invalid input - it is not base32 encoded string");s=H[a],i<=3?(i=(i+5)%8,0===i?(t|=s,r[n]=t,n++,t=0):t|=255&s<<8-i):(i=(i+5)%8,t|=255&s>>>i,r[n]=t,n++,t=255&s<<8-i)}return r.subarray(0,n)};function M(e){return e.reduce((e,t,i,s)=>{const n=t.split("-").map(e=>parseInt(e));return e.concat(((e,t=e)=>Array.from({length:t-e+1},(t,i)=>i+e))(...n))},[])}const F=function(e){const t={},i=e.split("magnet:?")[1];let s;if((i&&i.length>=0?i.split("&"):[]).forEach(e=>{const i=e.split("=");if(2!==i.length)return;const s=i[0];let n=i[1];"dn"===s&&(n=decodeURIComponent(n).replace(/\+/g," ")),"tr"!==s&&"xs"!==s&&"as"!==s&&"ws"!==s||(n=decodeURIComponent(n)),"kt"===s&&(n=decodeURIComponent(n).split("+")),"ix"===s&&(n=Number(n)),"so"===s&&(n=M(decodeURIComponent(n).split(","))),t[s]?(Array.isArray(t[s])||(t[s]=[t[s]]),t[s].push(n)):t[s]=n}),t.xt){(Array.isArray(t.xt)?t.xt:[t.xt]).forEach(e=>{(s=e.match(/^urn:btih:(.{40})/))?t.infoHash=s[1].toLowerCase():(s=e.match(/^urn:btih:(.{32})/))?t.infoHash=(0,w.V5)(N(s[1])):(s=e.match(/^urn:btmh:1220(.{64})/))&&(t.infoHashV2=s[1].toLowerCase())})}if(t.xs){(Array.isArray(t.xs)?t.xs:[t.xs]).forEach(e=>{(s=e.match(/^urn:btpk:(.{64})/))&&(t.publicKey=s[1].toLowerCase())})}return t.infoHash&&(t.infoHashBuffer=(0,w.fk)(t.infoHash)),t.infoHashV2&&(t.infoHashV2Buffer=(0,w.fk)(t.infoHashV2)),t.publicKey&&(t.publicKeyBuffer=(0,w.fk)(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 U(e){if("string"==typeof e&&/^(stream-)?magnet:/.test(e)){const t=F(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 F(`magnet:?xt=urn:btih:${e}`);if(ArrayBuffer.isView(e)&&20===e.length)return F(`magnet:?xt=urn:btih:${(0,w.V5)(e)}`);if(ArrayBuffer.isView(e))return await async function(e){ArrayBuffer.isView(e)&&(e=c.A.decode(e));B(e.info,"info"),B(e.info["name.utf-8"]||e.info.name,"info.name"),B(e.info["piece length"],"info['piece length']"),B(e.info.pieces,"info.pieces"),e.info.files?e.info.files.forEach(e=>{B("number"==typeof e.length,"info.files[0].length"),B(e["path.utf-8"]||e.path,"info.files[0].path")}):B("number"==typeof e.info.length,"info.length");const t={info:e.info,infoBuffer:c.A.encode(e.info),name:(0,w.dU)(e.info["name.utf-8"]||e.info.name),announce:[]};t.infoHashBuffer=await(0,w.tW)(t.infoBuffer),t.infoHash=(0,w.V5)(t.infoHashBuffer),void 0!==e.info.private&&(t.private=!!e.info.private);e["creation date"]&&(t.created=new Date(1e3*e["creation date"]));e["created by"]&&(t.createdBy=(0,w.dU)(e["created by"]));ArrayBuffer.isView(e.comment)&&(t.comment=(0,w.dU)(e.comment));Array.isArray(e["announce-list"])&&e["announce-list"].length>0?e["announce-list"].forEach(e=>{e.forEach(e=>{t.announce.push((0,w.dU)(e))})}):e.announce&&t.announce.push((0,w.dU)(e.announce));ArrayBuffer.isView(e["url-list"])&&(e["url-list"]=e["url-list"].length>0?[e["url-list"]]:[]);t.urlList=(e["url-list"]||[]).map(e=>(0,w.dU)(e)),t.announce=Array.from(new Set(t.announce)),t.urlList=Array.from(new Set(t.urlList));let i=0;const s=e.info.files||[e.info];t.files=s.map((e,s)=>{const n=[].concat(t.name,e["path.utf-8"]||e.path||[]).map(e=>ArrayBuffer.isView(e)?(0,w.dU)(e):e);return i+=e.length,{path:h.apply(null,[l].concat(n)).slice(1),name:n[n.length-1],length:e.length,offset:i-e.length}}),t.length=i;const n=t.files[t.files.length-1];return t.pieceLength=e.info["piece length"],t.lastPieceLength=(n.offset+n.length)%t.pieceLength||t.pieceLength,t.pieces=function(e){const t=[];for(let i=0;i<e.length;i+=20)t.push((0,w.V5)(e.slice(i,i+20)));return t}(e.info.pieces),t}(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 j(e,t,i){if("function"==typeof t)return j(e,{},t);if("function"!=typeof i)throw new Error("second argument must be a Function");let s;try{s=await U(e)}catch(e){}if(s&&s.infoHash)y(()=>{i(null,s)});else if(n=e,"undefined"!=typeof Blob&&n instanceof Blob)try{r(new Uint8Array(await e.arrayBuffer()))}catch(e){return i(new Error(`Error converting Blob: ${e.message}`))}else if(/^https?:/.test(e))try{const i=await R(e,{headers:{"user-agent":"WebTorrent (https://webtorrent.io)"},signal:AbortSignal.timeout(3e4),...t});r(new Uint8Array(await i.arrayBuffer()))}catch(e){return i(new Error(`Error downloading torrent: ${e.message}`))}else"function"==typeof O.readFile&&"string"==typeof e?O.readFile(e,(e,t)=>{if(e)return i(new Error("Invalid torrent identifier"));r(t)}):y(()=>{i(new Error("Invalid torrent identifier"))});var n;async function r(e){try{s=await U(e)}catch(e){return i(e)}s&&s.infoHash?i(null,s):i(new Error("Invalid torrent identifier"))}}function B(e,t){if(!e)throw new Error(`Torrent is missing required field: ${t}`)}const D=U,q=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,w.V5)(e.infoHashBuffer)}`),e.infoHash&&t.add(`urn:btih:${e.infoHash}`),e.infoHashV2Buffer&&t.add(e.xt=`urn:btmh:1220${(0,w.V5)(e.infoHashV2Buffer)}`),e.infoHashV2&&t.add(`urn:btmh:1220${e.infoHashV2}`);const i=Array.from(t);1===i.length&&(e.xt=i[0]),i.length>1&&(e.xt=i),e.publicKeyBuffer&&(e.xs=`urn:btpk:${(0,w.V5)(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 s="magnet:?";return Object.keys(e).filter(e=>2===e.length||"x.pe"===e).forEach((t,i)=>{const n=Array.isArray(e[t])?e[t]:[e[t]];var r;n.forEach((e,n)=>{(i>0||n>0)&&("kt"!==t&&"so"!==t||0===n)&&(s+="&"),"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&&(s+="kt"===t&&n>0?`+${e}`:`${t}=${e}`)}),"so"===t&&(s+=`${t}=${r=n,r.reduce((e,t,i,s)=>(0!==i&&t===s[i-1]+1||e.push([]),e[e.length-1].push(t),e),[]).map(e=>e.length>1?`${e[0]}-${e[e.length-1]}`:`${e[0]}`)}`)}),s},W="undefined"!=typeof window?window:self,$=W.RTCPeerConnection||W.mozRTCPeerConnection||W.webkitRTCPeerConnection,z=W.RTCSessionDescription||W.mozRTCSessionDescription||W.webkitRTCSessionDescription,V=W.RTCIceCandidate||W.mozRTCIceCandidate||W.webkitRTCIceCandidate;W.RTCIceTransport,W.RTCDataChannel,W.RTCSctpTransport,W.RTCDtlsTransport,W.RTCCertificate,W.MediaStream,W.MediaStreamTrack,W.MediaStreamTrackEvent,W.RTCPeerConnectionIceEvent,W.RTCDataChannelEvent,W.RTCTrackEvent,W.RTCError,W.RTCErrorEvent,W.RTCRtpTransceiver,W.RTCRtpReceiver,W.RTCRtpSender;var G=n(8179),K=n(6310);const Y=T("simple-peer"),J=65536;function X(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class Q extends G.Duplex{_pc;constructor(e){if(super(e=Object.assign({allowHalfOpen:!1},e)),this.__objectMode=!!e.objectMode,this._id=(0,w.V5)((0,w.po)(4)).slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||(0,w.V5)((0,w.po)(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.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,!$)throw"undefined"==typeof window?K(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):K(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._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new $(this.config)}catch(e){return void this.__destroy(K(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(K(e,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}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 K(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 z(e)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(e=>{this._addIceCandidate(e)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(e=>{this.__destroy(K(e,"ERR_SET_REMOTE_DESCRIPTION"))}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.__destroy(K(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const t=new V(e);this._pc.addIceCandidate(t).catch(e=>{var i;!t.address||t.address.endsWith(".local")?(i="Ignoring unsupported ICE candidate.",console.warn(i)):this.__destroy(K(e,"ERR_ADD_ICE_CANDIDATE"))})}send(e){if(!this._destroying){if(this.destroyed)throw K(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(e)}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this._destroying){if(this.destroyed)throw K(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&&this.emit("disconnect"),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(K(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=J),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(K(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(K(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(e){return this.__destroy(K(e,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>J?(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=X(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(K(e,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(e=>{this.__destroy(K(e,"ERR_CREATE_OFFER"))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=X(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(K(e,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(e=>{this.__destroy(K(e,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._destroying||"failed"===this._pc.connectionState&&this.__destroy(K(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(K(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.__destroy(K(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(i=>{const s=[];i.forEach(e=>{s.push(t(e))}),e(null,s)},t=>e(t)):this._pc.getStats.length>0?this._pc.getStats(i=>{if(this.destroyed)return;const s=[];i.result().forEach(e=>{const i={};e.names().forEach(t=>{i[t]=e.stat(t)}),i.id=e.id,i.type=e.type,i.timestamp=e.timestamp,s.push(t(i))}),e(null,s)},t=>e(t)):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this._destroying||this.getStats((t,i)=>{if(this.destroyed||this._destroying)return;t&&(i=[]);const s={},n={},r={};let o=!1;i.forEach(e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(s[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(n[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(r[e.id]=e)});const a=e=>{o=!0;let t=n[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let i=s[e.remoteCandidateId];i&&(i.ip||i.address)?(this.remoteAddress=i.ip||i.address,this.remotePort=Number(i.port)):i&&i.ipAddress?(this.remoteAddress=i.ipAddress,this.remotePort=Number(i.portNumber)):"string"==typeof e.googRemoteAddress&&(i=e.googRemoteAddress.split(":"),this.remoteAddress=i[0],this.remotePort=Number(i[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(i.forEach(e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(r[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)}),o||Object.keys(r).length&&!Object.keys(n).length){if(this._connecting=!1,this._connected=!0,this.emit("connect"),this._chunk){try{this.send(this._chunk)}catch(t){return this.__destroy(K(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>J||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,w.L0)(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())}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],Y.apply(null,e)}}Q.WEBRTC_SUPPORT=!!$,Q.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Q.channelConfig={};const Z=Q;var ee=n(1035),te=n(7541),ie=n(3278),se=n(8271),ne=n(6686),re=n(7828),oe=n(6889);const ae=/^\[?([^\]]+)]?:(\d+)$/;let he=new Map;function le(e){if(1e5===he.size&&he.clear(),!he.has(e)){const t=ae.exec(e);if(!t)throw new Error(`invalid addr: ${e}`);he.set(e,[t[1],Number(t[2])])}return he.get(e)}var ce=n(3033),de=n(4497);async function*ue(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 i=t.chunkLength||e.chunkLength;if(!i)throw new Error("missing required `chunkLength` property");let s=t.length||e.length;if(!Number.isFinite(s))throw new Error("missing required `length` property");const n=t.offset||0,r=(t,i,s)=>new Promise((n,r)=>{e.get(t,{offset:s,length:i},(e,t)=>{e&&r(e),n(t)})});let o=Math.floor(n/i);const a=n%i;if(n){const e=Math.min(s,i-a);s-=e,yield r(o++,e,a)}for(let e=s;e>0;++o,e-=i)yield r(o,Math.min(e,i))}async function pe(e,t,i={}){if(!e?.put)throw new Error("First argument must be an abstract-chunk-store compliant store");const s=i.chunkLength||e.chunkLength;if(!s)throw new Error("missing required `chunkLength` property");const n=i.storeMaxOutstandingPuts||16;let r=0,o=0,a=()=>{},h=!1;for await(const l of d(t,s,{zeroPadding:i.zeroPadding||!1}))await new Promise((t,i)=>{r++<=n&&t(),e.put(o++,l,e=>{if(e)return i(e);--r,t(),h&&0===r&&a()})});0!==r&&(h=new Promise(e=>{a=e}),await h)}var fe=n(4018),me=n(3970),_e=n(3519),ge=n(8436);const ye={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},...n.t(ge,2)};var we=n(8529),be=n(1048),ve=n(2701);const ke=T("simple-websocket"),xe="function"!=typeof ve?WebSocket:ve;class Se extends G.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,w.V5)((0,w.po)(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===xe.OPEN;else{this.url=e.url;try{this._ws="function"==typeof ve?new xe(e.url,{...e,encoding:void 0}):new xe(e.url)}catch(e){return void y(()=>this.destroy(e))}}this._ws.binaryType="arraybuffer",e.socket&&this.connected?y(()=>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===xe.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 ve&&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 ve&&(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,w.L0)(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],ke.apply(null,e)}}Se.WEBSOCKET_SUPPORT=!!xe;const Ee=class extends r{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())}},Ce=T("bittorrent-tracker:websocket-tracker"),Ae={};class Pe extends Ee{constructor(e,t){super(e,t),Ce("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 i=Math.min(e.numwant,5);this._generateOffers(i,e=>{t.numwant=i,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,w.Ht)(e)):e.infoHash&&(0,w.Ht)(e.infoHash)||this.client._infoHashBinary};this._send(t)}destroy(e=Te){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,Ae[this.announceUrl]&&(Ae[this.announceUrl].consumers-=1),Ae[this.announceUrl].consumers>0)return e();let t,i=Ae[this.announceUrl];if(delete Ae[this.announceUrl],i.on("error",Te),i.once("close",e),!this.expectingResponse)return s();function s(){t&&(clearTimeout(t),t=null),i.removeListener("data",s),i.destroy(),i=null}t=setTimeout(s,ye.DESTROY_TIMEOUT),i.once("data",s)}_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=Ae[this.announceUrl],this.socket)Ae[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=this.client._proxyOpts.socksProxy)),this.socket=Ae[this.announceUrl]=new Se({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,w.dU)(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 Ce("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,(0,w.HB)(e.info_hash),this.client.infoHash);if(e.peer_id&&e.peer_id===this.client._peerIdBinary)return;Ce("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 i=e["warning message"];i&&this.client.emit("warning",new Error(i));const s=e.interval||e["min interval"];s&&this.setInterval(1e3*s);const n=e["tracker id"];if(n&&(this._trackerId=n),null!=e.complete){const t=Object.assign({},e,{announce:this.announceUrl,infoHash:(0,w.HB)(e.info_hash)});this.client.emit("update",t)}let r;if(e.offer&&e.peer_id&&(Ce("creating peer (from remote offer)"),r=this._createPeer(),r.id=(0,w.HB)(e.peer_id),r.once("signal",t=>{const i={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&&(i.trackerid=this._trackerId),this._send(i)}),this.client.emit("peer",r),r.signal(e.offer)),e.answer&&e.peer_id){const t=(0,w.HB)(e.offer_id);r=this.peers[t],r?(r.id=(0,w.HB)(e.peer_id),this.client.emit("peer",r),r.signal(e.answer),clearTimeout(r.trackerTimeout),r.trackerTimeout=null,delete this.peers[t]):Ce(`got unexpected answer: ${JSON.stringify(e.answer)}`)}}_onScrapeResponse(e){e=e.files||{};const t=Object.keys(e);0!==t.length?t.forEach(t=>{const i=Object.assign(e[t],{announce:this.announceUrl,infoHash:(0,w.HB)(t)});this.client.emit("scrape",i)}):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(),Ce("reconnecting socket in %s ms",e)}_send(e){if(this.destroyed)return;this.expectingResponse=!0;const t=JSON.stringify(e);Ce("send %s",t),this.socket.send(t)}_generateOffers(e,t){const i=this,s=[];Ce("generating %s offers",e);for(let t=0;t<e;++t)n();function n(){const e=(0,w.V5)((0,w.po)(20));Ce("creating peer (from _generateOffers)");const t=i.peers[e]=i._createPeer({initiator:!0});t.once("signal",t=>{s.push({offer:t,offer_id:(0,w.Ht)(e)}),r()}),t.trackerTimeout=setTimeout(()=>{Ce("tracker timeout: destroying peer"),t.trackerTimeout=null,delete i.peers[e],t.destroy()},5e4),t.trackerTimeout.unref&&t.trackerTimeout.unref()}function r(){s.length===e&&(Ce("generated %s offers",e),t(s))}r()}_createPeer(e){const t=this;e=Object.assign({trickle:!1,config:t.client._rtcConfig,wrtc:t.client._wrtc},e);const i=new Z(e);return i.once("error",s),i.once("connect",function e(){i.removeListener("error",s),i.removeListener("connect",e)}),i;function s(e){t.client.emit("warning",new Error(`Connection error: ${e.message}`)),i.destroy()}}}function Te(){}Pe.prototype.DEFAULT_ANNOUNCE_INTERVAL=3e4,Pe._socketPool=Ae;const Ie=Pe;var Le=n(717);const Oe=T("bittorrent-tracker:client");class Re extends r{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(!Le.browser&&!e.port)throw new Error("Option `port` is required");this.peerId="string"==typeof e.peerId?e.peerId:(0,w.V5)(e.peerId),this._peerIdBuffer=(0,w.fk)(this.peerId),this._peerIdBinary=(0,w.Ht)(this.peerId),this.infoHash="string"==typeof e.infoHash?e.infoHash.toLowerCase():(0,w.V5)(e.infoHash),this._infoHashBuffer=(0,w.fk)(this.infoHash),this._infoHashBinary=(0,w.Ht)(this.infoHash),Oe("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,w.dU)(e)),"/"===e[e.length-1]&&(e=e.substring(0,e.length-1)),e)),t=Array.from(new Set(t));const i=!1!==this._wrtc&&(!!this._wrtc||Z.WEBRTC_SUPPORT),s=e=>{y(()=>{this.emit("warning",e)})};this._trackers=t.map(e=>{let t;try{t=ye.parseUrl(e)}catch(t){return s(new Error(`Invalid tracker URL: ${e}`)),null}const n=t.port;if(n<0||n>65535)return s(new Error(`Invalid tracker port: ${e}`)),null;const r=t.protocol;return"http:"!==r&&"https:"!==r||"function"!=typeof we?"udp:"===r&&"function"==typeof be?new be(this,e):"ws:"!==r&&"wss:"!==r||!i||"ws:"===r&&"undefined"!=typeof window&&"https:"===window.location.protocol?(s(new Error(`Unsupported tracker protocol: ${e}`)),null):new Ie(this,e):new we(this,e)}).filter(Boolean)}start(e){(e=this._defaultAnnounceOpts(e)).event="started",Oe("send `start` %o",e),this._announce(e),this._trackers.forEach(e=>{e.setInterval()})}stop(e){(e=this._defaultAnnounceOpts(e)).event="stopped",Oe("send `stop` %o",e),this._announce(e)}complete(e){e||(e={}),(e=this._defaultAnnounceOpts(e)).event="completed",Oe("send `complete` %o",e),this._announce(e)}update(e){(e=this._defaultAnnounceOpts(e)).event&&delete e.event,Oe("send `update` %o",e),this._announce(e)}_announce(e){this._trackers.forEach(t=>{t.announce(e)})}scrape(e){Oe("send `scrape`"),e||(e={}),this._trackers.forEach(t=>{t.scrape(e)})}setInterval(e){Oe("setInterval %d",e),this._trackers.forEach(t=>{t.setInterval(e)})}destroy(e){if(this.destroyed)return;this.destroyed=!0,Oe("destroy");const t=this._trackers.map(e=>t=>{e.destroy(t)});g(t,e),this._trackers=[],this._getAnnounceOpts=null}_defaultAnnounceOpts(e={}){return null==e.numwant&&(e.numwant=ye.DEFAULT_ANNOUNCE_PEERS),null==e.uploaded&&(e.uploaded=0),null==e.downloaded&&(e.downloaded=0),this._getAnnounceOpts&&(e=Object.assign({},e,this._getAnnounceOpts())),e}}Re.scrape=(e,t)=>{if(t=_e(t),!e.infoHash)throw new Error("Option `infoHash` is required");if(!e.announce)throw new Error("Option `announce` is required");const i=Object.assign({},e,{infoHash:Array.isArray(e.infoHash)?e.infoHash[0]:e.infoHash,peerId:(0,w.L0)("01234567890123456789"),port:6881}),s=new Re(i);s.once("error",t),s.once("warning",t);let n=Array.isArray(e.infoHash)?e.infoHash.length:1;const r={};return s.on("scrape",e=>{if(n-=1,r[e.infoHash]=e,0===n){s.destroy();const e=Object.keys(r);1===e.length?t(null,r[e[0]]):t(null,r)}}),s.scrape({infoHash:e.infoHash}),s};const He=Re;var Ne=n(2799),Me=n(717);const Fe=T("torrent-discovery");class Ue extends r.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(!Me.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 i=new me.Client(t);return i.on("warning",this._onWarning),i.on("error",this._onError),i.listen(e),this._internalDHT=!0,i};!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 me.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 Ne?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)})),g(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 He(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||(Fe("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,e=>{this._dhtAnnouncing=!1,Fe("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 Ne(e);return t.on("warning",this._onWarning),t.on("error",this._onError),t.on("peer",this._onLSDPeer),t.start(),t}}const je=Ue;const Be=["seeking position failed.","InvalidStateError"],De=["A requested file or directory could not be found at the time an operation was processed.","NotFoundError"],qe=e=>[`Failed to execute 'write' on 'UnderlyingSinkBase': Invalid params passed. ${e}`,"SyntaxError"];class We extends WritableStream{constructor(e){super(e),Object.setPrototypeOf(this,FileSystemWritableFileStream.prototype),this._closed=!1}async close(){this._closed=!0;const e=this.getWriter(),t=e.close();return e.releaseLock(),t}seek(e){return this.write({type:"seek",position:e})}truncate(e){return this.write({type:"truncate",size:e})}write(e){if(this._closed)return Promise.reject(new TypeError("Cannot write to a CLOSED writable stream"));const t=this.getWriter(),i=t.write(e);return t.releaseLock(),i}}if(Object.defineProperty(We.prototype,Symbol.toStringTag,{value:"FileSystemWritableFileStream",writable:!1,enumerable:!1,configurable:!0}),Object.defineProperties(We.prototype,{close:{enumerable:!0},seek:{enumerable:!0},truncate:{enumerable:!0},write:{enumerable:!0}}),!globalThis.FileSystemFileHandle||globalThis.FileSystemFileHandle.prototype.createWritable||globalThis.FileSystemWritableFileStream||(globalThis.FileSystemWritableFileStream=We),globalThis.FileSystemFileHandle&&!globalThis.FileSystemFileHandle.prototype.createWritable){const e=new WeakMap;let t;const i=()=>{let e,t;onmessage=async i=>{const s=i.ports[0],n=i.data;switch(n.type){case"open":{const i=n.name;let s=await navigator.storage.getDirectory();for(const e of n.path)s=await s.getDirectoryHandle(e);e=await s.getFileHandle(i),t=await e.createSyncAccessHandle();break}case"write":t.write(n.data,{at:n.position}),t.flush();break;case"truncate":t.truncate(n.size);break;case"abort":case"close":t.close()}s.postMessage(0)}};globalThis.FileSystemFileHandle.prototype.createWritable=async function(s){if(!t){const e=`(${i.toString()})()`,s=new Blob([e],{type:"text/javascript"});t=URL.createObjectURL(s)}const n=new Worker(t,{type:"module"});let r=0;const o=new TextEncoder;let a=await this.getFile().then(e=>e.size);const h=e=>new Promise((t,i)=>{const s=new MessageChannel;s.port1.onmessage=e=>{e.data instanceof Error?i(e.data):t(e.data),s.port1.close(),s.port2.close(),s.port1.onmessage=null},n.postMessage(e,[s.port2])}),l=await navigator.storage.getDirectory(),c=await e.get(this),d=await l.resolve(c);if(null===d)throw new DOMException(...De);return await h({type:"open",path:d,name:this.name}),!1===s?.keepExistingData&&(await h({type:"truncate",size:0}),a=0),new We({async write(e){if("write"===(e=e?.constructor===Object?{...e}:{type:"write",data:e,position:r}).type){if(!("data"in e))throw await h({type:"close"}),new DOMException(...qe("write requires a data argument"));if(e.position??=r,"string"==typeof e.data)e.data=o.encode(e.data);else if(e.data instanceof ArrayBuffer)e.data=new Uint8Array(e.data);else if(e.data instanceof Uint8Array||!ArrayBuffer.isView(e.data)){if(!(e.data instanceof Uint8Array)){const t=await new Response(e.data).arrayBuffer();e.data=new Uint8Array(t)}}else e.data=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);Number.isInteger(e.position)&&e.position>=0&&(r=e.position),r+=e.data.byteLength,a+=e.data.byteLength}else{if("seek"===e.type){if(Number.isInteger(e.position)&&e.position>=0){if(a<e.position)throw new DOMException(...Be);return void(r=e.position)}throw await h({type:"close"}),new DOMException(...qe("seek requires a position argument"))}if("truncate"===e.type){if(!(Number.isInteger(e.size)&&e.size>=0))throw await h({type:"close"}),new DOMException(...qe("truncate requires a size argument"));a=e.size,r>a&&(r=a)}}await h(e)},async close(){await h({type:"close"}),n.terminate()},async abort(e){await h({type:"abort",reason:e}),n.terminate()}})};const s=FileSystemDirectoryHandle.prototype.getFileHandle;FileSystemDirectoryHandle.prototype.getFileHandle=async function(...t){const i=await s.call(this,...t);return e.set(i,this),i}}const $e=/[<>:"/\\|?*\u0000-\u001F]/g;globalThis.navigator?.storage?.getDirectory&&navigator.storage.getDirectory().then(e=>{e.removeEntry("chunks",{recursive:!0}).catch(()=>{})});const ze=(e,t)=>{};class Ve{name="";chunks=[];chunkMap=[];directoryMap={};files;rootDirPromise;storageDirPromise;chunksDirPromise;closing=!1;closed=!1;constructor(e,t={}){if(this.chunkLength=Number(e),!this.chunkLength)throw new Error("First argument must be a chunk length");if(!globalThis.navigator?.storage?.getDirectory)throw new Error("FSA API is not supported");if(this.closed=!1,this.name=t.name||crypto.randomUUID(),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.chunksDirPromise=this._getChunksDirHandle(),this.files=t.files.map((e,t,i)=>{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 s=i[t-1];e.offset=s.offset+s.length}null==e.handle&&(e.handle=this._createFileHandle({path:e.path})),e.blob=this._createBlobReference(e.handle);const s=e.offset,n=e.offset+e.length,r=Math.floor(s/this.chunkLength),o=Math.floor((n-1)/this.chunkLength);for(let t=r;t<=o;++t){const i=t*this.chunkLength,r=s<i?0:s-i,o=n>i+this.chunkLength?this.chunkLength:n-i,a=s>i?0:i-s;this.chunkMap[t]||(this.chunkMap[t]=[]),this.chunkMap[t].push({from:r,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 i=await this.chunksDirPromise;this.chunks[e]=t=await i.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.replace($e,""),{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 i=e.path=e.path.slice(0,t);return this.directoryMap[i]||(this.directoryMap[i]=(async()=>(await this._getDirectoryHandle(e)).getDirectoryHandle(i.slice(i.lastIndexOf("/")+1),{create:!0}))()),this.directoryMap[i]}async _getChunksDirHandle(){const e=await navigator.storage.getDirectory();return(await e.getDirectoryHandle("chunks",{create:!0})).getDirectoryHandle(this.name,{create:!0})}async put(e,t,i=ze){try{return await this._put(e,t),i(null),null}catch(e){return queueMicrotask(()=>i(e)),e}}async getStreamForHandle(e){return(await e).createWritable({keepExistingData:!0})}async _put(e,t){if(this.closed)throw new Error("Storage is closed");const i=e===this.lastChunkIndex;if(i&&t.length!==this.lastChunkLength)throw new Error(`Last chunk length must be ${this.lastChunkLength}`);if(!i&&t.length!==this.chunkLength)throw new Error(`Chunk length must be ${this.chunkLength}`);const s=(async()=>{const i=await this._getChunkHandle(e),s=await i.createWritable({keepExistingData:!1});await s.write(t),await s.close()})();if(!this.files)return s;const n=this.chunkMap[e];if(!n)throw new Error("No files matching the request range");const r=n.map(async({file:e,offset:i,from:s,to:n})=>{e.stream||(e.stream=this.getStreamForHandle(e.handle)),await(await e.stream).write({type:"write",position:i,data:t.slice(s,n)})});r.push(s),await Promise.all(r)}async get(e,t,i=ze){null==t&&(t={});try{const s=await this._get(e,t);return i(null,s),s}catch(e){return i(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 i=e===this.lastChunkIndex?this.lastChunkLength:this.chunkLength,s=t.offset||0,n=t.length?s+t.length:i,r=t.length||i-s;if(s<0||s<0||n>i)throw new Error("Invalid offset and/or length");if(s===n)return new Uint8Array(0);if(!this.files||this.chunks[e]){const t=await this._getChunkHandle(e);let n=await t.getFile();0===s&&r===i||(n=n.slice(s,r+s));const o=await n.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>s&&e<n),0===o.length))throw new Error("No files matching the request range");const a=o.map(async({from:e,to:i,offset:r,file:o})=>{t&&(i>n&&(i=n),e<s&&(r+=s-e,e=s));return(await o.blob).slice(r,r+i-e)}),h=await Promise.all(a),l=1===h.length?await h[0].arrayBuffer():await new Blob(h).arrayBuffer();if(0===l.byteLength)throw new Error(`Index ${e} does not exist`);return new Uint8Array(l)}async close(e=ze){if(this.closing)return((e=ze,t)=>queueMicrotask(()=>e(new Error(t))))(e,"Storage is closed");this.closing=!0,this.chunkMap=void 0,this.directoryMap=void 0,this.files&&await this.cleanup(),this.closed=!0,queueMicrotask(()=>e(null))}async cleanup(){if(this.closed||!this.files)return;const e=[];for(const t of this.files)t.stream&&(e.push(t.stream.then(e=>e.close())),t.stream=void 0);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=this._getChunksDirHandle(),await this.chunksDirPromise})();await Promise.all(e);for(const e of this.files)e.blob=this._createBlobReference(e.handle);await t}async destroy(e=ze){this.close(async t=>{if(t)return e(t);try{const e=await this.rootDirPromise;await e.removeEntry(this.name,{recursive:!0})}catch(t){return e(t)}e(null)})}}var Ge=n(3714),Ke=n(1314);const Ye=T("lt_donthave"),Je=()=>{class e extends r.EventEmitter{constructor(e){super(),this._peerSupports=!1,this._wire=e}onExtendedHandshake(){this._peerSupports=!0}onMessage(e){let t;try{t=new DataView(e.buffer).getUint32(0)}catch(e){return}this._wire.peerPieces.get(t)&&(Ye("got donthave %d",t),this._wire.peerPieces.set(t,!1),this.emit("donthave",t),this._failRequests(t))}donthave(e){if(!this._peerSupports)return;Ye("donthave %d",e);const t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e),this._wire.extended("lt_donthave",t)}_failRequests(e){const t=this._wire.requests;for(let i=0;i<t.length;i++){const s=t[i];s.piece===e&&(Ke(t,i),i-=1,this._wire._callback(s,new Error("peer sent donthave"),null))}}}return e.prototype.name="lt_donthave",e};var Xe=n(4862),Qe=n(5372);const Ze=16384;class et{constructor(e){this.length=e,this.missing=e,this.sources=null,this._chunks=Math.ceil(e/Ze),this._remainder=e%Ze||Ze,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(e){return e===this._chunks-1?this._remainder:Ze}chunkLengthRemaining(e){return this.length-e*Ze}chunkOffset(e){return e*Ze}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,i){if(!this.init())return!1;const s=t.length,n=Math.ceil(s/Ze);for(let s=0;s<n;s++)if(!this._buffer[e+s]){const n=s*Ze,r=t.subarray(n,n+Ze);this._buffered++,this._buffer[e+s]=r,this.missing-=r.length,this.sources.includes(i)||this.sources.push(i)}return this._buffered===this._chunks}flush(){if(!this._buffer||this._chunks!==this._buffered)return null;const e=(0,w.xW)(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)}}et.BLOCK_LENGTH=Ze;var tt=n(7373);const it=T("ut_metadata"),st=16384,nt=e=>{class t extends r.EventEmitter{constructor(t){super(),this._wire=t,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new ce.A(0,{grow:1e3}),ArrayBuffer.isView(e)&&this.setMetadata(e)}onHandshake(e,t,i){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/st),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 s=(0,w.dU)(e),n=s.indexOf("ee")+2;t=c.A.decode(s.substring(0,n)),i=e.slice(n)}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;it("set metadata");try{const t=c.A.decode(e).info;t&&(e=c.A.encode(t))}catch(e){}return(!this._infoHash||this._infoHash===await(0,w.tW)(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",c.A.encode({info:c.A.decode(this.metadata)})),!0)}_send(e,t){let i=c.A.encode(e);ArrayBuffer.isView(t)&&(i=(0,w.xW)([i,t])),this._wire.extended("ut_metadata",i)}_request(e){this._send({msg_type:0,piece:e})}_data(e,t,i){const s={msg_type:1,piece:e};"number"==typeof i&&(s.total_size=i),this._send(s,t)}_reject(e){this._send({msg_type:2,piece:e})}_onRequest(e){if(!this._metadataComplete)return void this._reject(e);const t=e*st;let i=t+st;i>this._metadataSize&&(i=this._metadataSize);const s=this.metadata.slice(t,i);this._data(e,s,this._metadataSize)}_onData(e,t,i){t.length>st||!this._fetching||(this.metadata.set(t,e*st),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 ce.A(0,{grow:1e3}),this._remainingRejects-=this._numPieces,this._remainingRejects>0?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))}}return t.prototype.name="ut_metadata",t};var rt=n(8878),ot=n(1133);const at=T("webtorrent:file-iterator");class ht extends r{constructor(e,{start:t,end:i}){super(),this._torrent=e._torrent,this._pieceLength=e._torrent.pieceLength,this._startPiece=(t+e.offset)/this._pieceLength|0,this._endPiece=(i+e.offset)/this._pieceLength|0,this._piece=this._startPiece,this._offset=t+e.offset-this._startPiece*this._pieceLength,this._missing=i-t+1,this._criticalLength=Math.min(1048576/this._pieceLength|0,2),this._torrent._select(this._startPiece,this._endPiece,1,null,!0),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 i=(t,s)=>{if(!this._torrent.bitfield.get(t)){const n=r=>{(r===t||this.destroyed)&&(this._torrent.removeListener("verified",n),r===t?i(t,s):e({done:!0}))};return this._torrent.on("verified",n),this._torrent.critical(t,t+this._criticalLength)}if(this.destroyed)return e({done:!0});this._torrent.store.get(t,s,(i,s)=>this.destroyed?e({done:!0}):(at("read %s and yielding (length %s) (err %s)",t,s?.length,i?.message),i?(this.destroy(void 0,i),e({done:!0})):void e({value:s,done:!1})))},s=Math.min(this._missing,this._pieceLength-this._offset);i(this._piece++,{length:s,offset:this._offset}),this._missing-=s,this._offset=0})}async return(){return this.destroy(),{done:!0,value:void 0}}async throw(e){throw e}destroy(e=e=>{},t){this.destroyed||(this.destroyed=!0,this._torrent.destroyed||this._torrent._deselect(this._startPiece,this._endPiece,!0),this.emit("return"),e(t))}}class lt extends r{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=ot.getType(this.name)||"application/octet-stream",this.offset=t.offset,this.done=!1;const i=t.offset,s=i+t.length-1;this._startPiece=i/this._torrent.pieceLength|0,this._endPiece=s/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:i,lastPieceLength:s}=this._torrent,{_startPiece:n,_endPiece:r}=this,o=t=>t===e.length-1?s:i,a=n=>{const r=n===e.length-1?s:i;return t.get(n)?r:r-e[n].missing};let h=0;for(let e=n;e<=r;e+=1){const t=a(e);if(h+=t,e===n){const e=this.offset%i;h-=Math.min(e,t)}if(e===r){const e=o(r)-(this.offset+this.length)%i;h-=Math.min(e,t)}}return h}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)}[Symbol.asyncIterator](e={}){if(0===this.length||this._destroyed)return async function*(){}();const{start:t=0}=e??{},i=e?.end&&e.end<this.length?e.end:this.length-1;if(this.done)return ue(this._torrent.store,{offset:t+this.offset,length:i-t+1});const s=new ht(this,{start:t,end:i});return this._iterators.add(s),s.once("return",()=>{this._iterators.delete(s)}),s}createReadStream(e){if(this._destroyed)throw new Error("File is destroyed");const t=this[Symbol.asyncIterator](e),i=G.Readable.from(t);return this._fileStreams.add(i),i.once("close",()=>{this._fileStreams.delete(i)}),i}async arrayBuffer(e={}){if(this._destroyed)throw new Error("File is destroyed");const{start:t=0}=e,i=e?.end&&e.end<this.length?e.end:this.length-1,s=new Uint8Array(i-t+1);let n=0;for await(const e of this[Symbol.asyncIterator]({start:t,end:i}))s.set(e,n),n+=e.length;return s.buffer}async blob(e){if(this._destroyed)throw new Error("File is destroyed");return new Blob([await this.arrayBuffer(e)],{type:this.type})}stream(e){if(this._destroyed)throw new Error("File is destroyed");let t;return new ReadableStream({start:()=>{t=this[Symbol.asyncIterator](e)},async pull(e){const{value:i,done:s}=await t.next();s?e.close():e.enqueue(i)},cancel(){t.return()}})}get streamURL(){if(!this._client._server)throw new Error("No server created");return`${this._client._server.pathname}/${this._torrent.infoHash}/${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 ct=n(5658);class dt{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=[],i=1/0;for(let s=0;s<this._numPieces;++s){if(e&&!e(s))continue;const n=this._pieces[s];n===i?t.push(s):n<i&&(t=[s],i=n)}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 ut=n(4343),pt=n(6458),ft=n(6819);const mt=T("webtorrent:webconn");class _t extends pt.A{constructor(e,t){super(),this.url=e,this.connId=e,this._torrent=t,this._init(e)}_init(e){this.setKeepAlive(!0),this.use(Je()),this.once("handshake",async(t,i)=>{const s=await(0,w.tW)(e,"hex");if(this.destroyed)return;this.handshake(t,s);const n=this._torrent.pieces.length,r=new ce.A(n);for(let e=0;e<=n;e++)r.set(e,!0);this.bitfield(r)}),this.once("interested",()=>{mt("interested"),this.unchoke()}),this.on("uninterested",()=>{mt("uninterested")}),this.on("choke",()=>{mt("choke")}),this.on("unchoke",()=>{mt("unchoke")}),this.on("bitfield",()=>{mt("bitfield")}),this.lt_donthave.on("donthave",()=>{mt("donthave")}),this.on("request",(e,t,i,s)=>{mt("request pieceIndex=%d offset=%d length=%d",e,t,i),this.httpRequest(e,t,i,(t,i)=>{if(t){this.lt_donthave.donthave(e);const t=setTimeout(()=>{this.destroyed||this.have(e)},1e4);t.unref&&t.unref()}s(t,i)})})}async httpRequest(e,t,i,s){s=_e(s);const n=e*this._torrent.pieceLength+t,r=n+i-1,o=this._torrent.files;let a,h;if(o.length<=1)a=[{url:this.url,start:n,end:r}];else{const e=o.filter(e=>e.offset<=r&&e.offset+e.length>n);if(e.length<1)return s(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-n,0),start:Math.max(n-e.offset,0),end:Math.min(t,r-e.offset)}})}try{h=await Promise.all(a.map(async({start:s,end:n,url:r})=>{mt("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",r,e,t,i,s,n);const o=await R(r,{cache:"no-store",method:"GET",headers:{"Cache-Control":"no-store","user-agent":`WebTorrent/${ft} (https://webtorrent.io)`,range:`bytes=${s}-${n}`},signal:AbortSignal.timeout(6e4)});if(!o.ok)throw new Error(`Unexpected HTTP status code ${o.status}`);const a=new Uint8Array(await o.arrayBuffer());return mt("Got data of length %d",a.length),a}))}catch(e){return s(e)}s(null,(0,w.xW)(h))}destroy(){super.destroy(),this._torrent=null}}class gt{_items=[];remove(e){for(let t=0;t<this._items.length;t++){const i=this._items[t];if(!i.isStreamSelection==!e.isStreamSelection)if(i.isStreamSelection){if(i.from===e.from&&i.to===e.to){this._items.splice(t,1);break}}else if(yt(e,i))i.to=Math.max(e.from-1,0);else if(wt(e,i))i.from=e.to+1;else if(bt(e,i)){const s=[],n={...i,to:Math.max(e.from-1,0)};n.to-n.from>=0&&0!==e.from&&s.push(n);const r={...i,from:e.to+1};r.to-r.from>=0&&s.push(r),this._items.splice(t,1,...s),t=t-1+s.length}else vt(e,i)&&(this._items.splice(t,1),t--)}}_mergePriorityAndNotify(e,t){if((t.priority??0)>(e.priority??0)&&(e.priority=t.priority),e.notify&&t.notify){const i=e.notify;e.notify=()=>{i(),t.notify?.()}}else e.notify=t.notify||e.notify}concatenate(e){for(let t=0;t<this._items.length;t++){const i=this._items[t];if(!i.isStreamSelection){if(yt(e,i))e.from=i.from;else if(wt(e,i))e.to=i.to;else{if(!bt(e,i)){if(vt(e,i))continue;continue}e.from=i.from,e.to=i.to}this._mergePriorityAndNotify(e,i)}}this.remove(e)}insert(e){if(e.from>e.to)throw new Error("Invalid interval");e.isStreamSelection||this.concatenate(e),this._items.push(e)}sort(e=(e,t)=>e.from-t.from){this._items.sort(e)}get length(){return this._items.length}get(e){return this._items[e]}swap(e,t){const i=this._items[e];this._items[e]=this._items[t],this._items[t]=i}clear(){this._items.length=0}*[Symbol.iterator](){for(let e=0;e<this._items.length;e++){const t=this._items[e];t.remove=()=>{this._items.splice(e,1),e--},yield t,delete t.remove}}}function yt(e,t){return e.from<=t.to+1&&e.from>t.from&&e.to>t.to}function wt(e,t){return e.to>=t.from-1&&e.to<t.to&&e.from<t.from}function bt(e,t){const i=t.to-t.from,s=e.to-e.from;return e.from>=t.from&&e.to<=t.to&&s<i}function vt(e,t){return e.from<=t.from&&e.to>=t.to}var kt=n(717);const xt=T("webtorrent:torrent"),St=5e3,Et=3*et.BLOCK_LENGTH,Ct=kt.browser?fe().length:2,At=[1e3,5e3,15e3],Pt=`WebTorrent/${ft} (https://webtorrent.io)`,Tt=globalThis.navigator?.storage?.getDirectory&&globalThis.FileSystemFileHandle?.prototype?.createWritable,It=!kt.browser||Tt?Ve:Xe;let Lt;try{Lt=h(ne.statSync("/tmp")&&"/tmp","webtorrent")}catch(e){Lt=h("function"==typeof oe.tmpdir?oe.tmpdir():"/","webtorrent")}const Ot="undefined"!=typeof window&&"function"==typeof window.requestIdleCallback&&window.requestIdleCallback;class Rt extends r{constructor(e,t,i){super(),this._debugId="unknown infohash",this.client=t,this.announce=i.announce,this.urlList=i.urlList,this.path=i.path||Lt,this.addUID=i.addUID||!1,this.rootDir=i.rootDir||null,this.skipVerify=!!i.skipVerify,this._startupBitfield=i.bitfield,this._store=i.store||It,this._preloadedStore=i.preloadedStore||null,this._storeCacheSlots=void 0!==i.storeCacheSlots?i.storeCacheSlots:20,this._destroyStoreOnDestroy=i.destroyStoreOnDestroy||!1,this.store=null,this.storeOpts=i.storeOpts,this.alwaysChokeSeeders=i.alwaysChokeSeeders??!0,this._getAnnounceOpts=i.getAnnounceOpts,"boolean"==typeof i.private&&(this.private=i.private),this.strategy=i.strategy||"sequential",this.maxWebConns=i.maxWebConns||4,this._rechokeNumSlots=!1===i.uploads||0===i.uploads?0:+i.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this._noPeersIntervalId=null,this._noPeersIntervalTime=i.noPeersIntervalTime?1e3*i.noPeersIntervalTime:3e4,this._startAsDeselected=i.deselect||!1,this.ready=!1,this.destroyed=!1,this.paused=i.paused||!1,this.done=!1,this.metadata=null,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=new gt,this._critical=[],this.wires=[],this._queue=[],this._peers=new Map,this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=ee(),this._uploadSpeed=ee(),this._servers=[],this._xsRequests=[],this._fileModtimes=i.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,i=this.pieces.length;t<i;++t)if(this.bitfield.get(t))e+=t===i-1?this.lastPieceLength:this.pieceLength;else{const i=this.pieces[t];e+=i.length-i.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)}_numConns=0;async _onTorrentId(e){if(this.destroyed)return;let t;try{t=await D(e)}catch(e){}t?(this.infoHash=t.infoHash,this._debugId=(0,w.V5)(t.infoHash).substring(0,7),y(()=>{this.destroyed||this._onParsedTorrent(t)})):j(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,w.V5)(e.infoHash).substring(0,7),void 0!==this.private&&(e.private=this.private),Array.isArray(this.announce)&&(e.announce=e.announce.concat(this.announce)),this.client.tracker&&Array.isArray(this.client.tracker.announce)&&!e.private&&(e.announce=e.announce.concat(this.client.tracker.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=q(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,w.L0)(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),c.A.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,ct.A.SOURCE_MANUAL)),this.discovery=new je({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:e,port:this.client.torrentPort,userAgent:Pt,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),this.client.seedOutgoingConnections||!this.done?this.addPeer(e,t):this._debug("discovery ignoring peer %s: torrent is done and seedOutgoingConnections is false",e)}),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={[ct.A.SOURCE_TRACKER]:{enabled:!!this.client.tracker,numPeers:0},[ct.A.SOURCE_DHT]:{enabled:!!this.client.dht,numPeers:0},[ct.A.SOURCE_LSD]:{enabled:!!this.client.lsd,numPeers:0},[ct.A.SOURCE_UT_PEX]:{enabled:this.client.utPex&&"function"==typeof rt,numPeers:0}};for(const t of this._peers.values()){const i=e[t.source];void 0!==i&&i.numPeers++}for(const t of Object.keys(e)){const i=e[t];i.enabled&&0===i.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 i=e._xsRequestsController.signal,s=t.map(t=>s=>{!async function(t,s){if(0!==t.indexOf("http://")&&0!==t.indexOf("https://"))return e.emit("warning",new Error(`skipping non-http xs param: ${t}`)),s(null);const n={method:"GET",headers:{"user-agent":Pt},signal:i};let r,o,a;try{r=await R(t,n)}catch(i){return e.emit("warning",new Error(`http error from xs param: ${t}`)),s(null)}if(e.destroyed)return s(null);if(e.metadata)return s(null);if(200!==r.status)return e.emit("warning",new Error(`non-200 status code ${r.status} from xs param: ${t}`)),s(null);try{o=new Uint8Array(await r.arrayBuffer())}catch(t){return e.emit("warning",t),s(null)}try{a=await D(o)}catch(e){}if(!a)return e.emit("warning",new Error(`got invalid torrent file from xs param: ${t}`)),s(null);if(a.infoHash!==e.infoHash)return e.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${t}`)),s(null);e._onMetadata(a),s(null)}(t,s)});g(s)}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 D(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 dt(this),this.files=this.files.map(e=>new lt(this,e));let i=this._preloadedStore;if(i||(i=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&&!(i instanceof Xe)&&(i=new de(i,{max:this._storeCacheSlots})),this.store=new Ge(i),this.so&&!this._startAsDeselected?this.files.forEach((e,t)=>{this.so.includes(t)&&this.files[t].select()}):0===this.pieces.length||this._startAsDeselected||this.select(0,this.pieces.length-1),this._hashes=this.pieces,this._hasStartupBitfield=this._startupBitfield&&this._startupBitfield.length===Math.ceil(this.pieces.length/8)&&!this.skipVerify,this.bitfield=new ce.A(this._hasStartupBitfield?new Uint8Array(this._startupBitfield):this.pieces.length),this._reservations=this._hasStartupBitfield?this.pieces.map((e,t)=>this.bitfield.get(t)?null:[]):this.pieces.map(()=>[]),this.pieces=this.pieces.map((e,t)=>{if(this._hasStartupBitfield&&this.bitfield.get(t))return null;const i=t===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new et(i)}),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===Ve?this.getFileModtimes((t,i)=>{if(t)return this._destroy(t);this.files.map((e,t)=>i[t]===this._fileModtimes[t]).every(e=>e)?(this._markAllVerified(),this._onStore()):this._verifyPieces(e)}):this._verifyPieces(e)}}getFileModtimes(e){const t=[];Qe(this.files.map((e,i)=>s=>{const n=this.addUID?h(this.name+" - "+this.infoHash.slice(0,8)):h(this.path,e.path);ne.stat(n,(e,n)=>{if(e&&"ENOENT"!==e.code)return s(e);t[i]=n&&n.mtime.getTime(),s(null)})}),Ct,i=>{this._debug("done getting file modtimes"),e(i,t)})}_verifyPiece(e,t){if(this.destroyed)return t(new Error("torrent is destroyed"));const i={};e===this.pieces.length-1&&(i.length=this.lastPieceLength),this.store.get(e,i,async(i,s)=>{if(this.destroyed)return t(new Error("torrent is destroyed"));if(i)return y(()=>t(null,!1));const n=await(0,w.tW)(s,"hex");if(this.destroyed)return t(new Error("torrent is destroyed"));t(null,n===this._hashes[e])})}_verifyPiecesUsingBitfield(e){const t=new Set,i=new Map;for(const e of this.files){let s=2,n=null;for(let t=e._startPiece;t<=e._endPiece;++t)this.bitfield.get(t)&&(s&&(n=t,s--),i.has(t)||i.set(t,[]),i.get(t).push(e));null!==n&&t.add(n)}this._verifyPiecesUsingHash([...t],s=>{if(s)return e(s);const n=new Set;for(const e of t)if(!this.bitfield.get(e)){const t=i.get(e);for(const e of t)n.add(e)}if(n.size){const t=[];for(const e of n)for(let i=e._startPiece;i<=e._endPiece;++i)-1===t.indexOf(i)&&t.push(i);return this._verifyPiecesUsingHash(t,e)}e(null)})}_verifyPiecesUsingHash(e,t){Qe(e.map((e,t)=>i=>{const s=Number.isInteger(e)?e:t;this._verifyPiece(s,(e,t)=>{if(e)return i(e);t?(this._debug("piece verified %s",s),this._markVerified(s)):(this._markUnverified(s),this._debug("piece invalid %s",s)),i(null)})}),Ct,t)}_verifyPieces(e){if(this._hasStartupBitfield)return this._verifyPiecesUsingBitfield(e);this._verifyPiecesUsingHash(this.pieces,e)}rescanFiles(e){if(this.destroyed)throw new Error("torrent is destroyed");e||(e=Nt),this._verifyPiecesUsingHash(this.pieces,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),this.emit("verified",e)}_markUnverified(e){const t=e===this.pieces.length-1?this.lastPieceLength:this.pieceLength;this.pieces[e]=new et(t),this.bitfield.set(e,!1),this._startAsDeselected||this.select(e,e);for(const t of this.files)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 i=0;i<this.pieces.length;i++)if(this.bitfield.get(i)&&(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,i){if("function"==typeof t)return this._destroy(e,null,t);if(this.destroyed)return;this.destroyed=!0,this._debug("destroy"),this.client._remove(this),this._selections.clear(),clearInterval(this._rechokeIntervalId),clearInterval(this._noPeersIntervalId),this._xsRequestsController?.abort(),this._rarityMap&&this._rarityMap.destroy();for(const e of this._peers.keys())this.removePeer(e);for(const e of this.files)e instanceof lt&&e._destroy();const s=this._servers.map(e=>t=>{e.destroy(t)});if(this.discovery&&s.push(e=>{this.discovery.destroy(e)}),this.store){let e=this._destroyStoreOnDestroy;t&&void 0!==t.destroyStore&&(e=t.destroyStore),s.push(t=>{e?this.store.destroy(t):this.store.close(t)})}g(s,i),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.clear(),this._peers=null,this._servers=null,this._xsRequests=null,this._queue=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 i;if("string"==typeof e){let t;try{t=le(e)}catch(t){return this._debug("ignoring peer: invalid %s",e),this.emit("invalidPeer",e),!1}i=t[0]}else"string"==typeof e.remoteAddress&&(i=e.remoteAddress);if(this.client.blocked&&i&&this.client.blocked.contains(i))return this._debug("ignoring peer: blocked %s",e),"string"!=typeof e&&e.destroy(),this.emit("blockedPeer",e),!1;const s=this.client.utp&&this._isIPv4(i)?"utp":"tcp",n=!!this._addPeer(e,s,t);return n?this.emit("peer",e):this.emit("invalidPeer",e),n}_addPeer(e,t,i){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 s=e&&e.id||e;if(this._peers.has(s))return this._debug("ignoring peer: duplicate (%s)",s),"string"!=typeof e&&e.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof e&&e.destroy(),null;let n;return this._debug("add peer %s",s),n="string"==typeof e?"utp"===t?ct.A.createUTPOutgoingPeer(e,this,this.client.throttleGroups,i):ct.A.createTCPOutgoingPeer(e,this,this.client.throttleGroups,i):ct.A.createWebRTCPeer(e,this,this.client.throttleGroups,i),this._registerPeer(n),"string"==typeof e&&(this._queue.push(n),this._drain()),n}addWebSeed(e){if(this.destroyed)throw new Error("torrent is destroyed");let t,i;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.has(t))return this.emit("warning",new Error(`ignoring duplicate web seed: ${t}`)),void this.emit("invalidPeer",t);i=new _t(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(i=e,t=i.connId,this._peers.has(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 s=ct.A.createWebSeedPeer(i,t,this,this.client.throttleGroups);this._registerPeer(s),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))}),e.connected?this._numConns+=1:e.once("connect",()=>{this.destroyed||(this._numConns+=1)}),e.once("disconnect",()=>{this._numConns-=1}),this._peers.set(e.id,e),this._peersLength+=1}removePeer(e){const t=e?.id||e;e&&!e.id&&(e=this._peers?.get(t)),e&&(e.destroy(),this.destroyed||(this._debug("removePeer %s",t),this._peers.delete(t),this._peersLength-=1,this._drain()))}_select(e=0,t=this.pieces.length-1,i,s,n=!1){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}`);i=Number(i)||0,this._debug("select %s-%s (priority %s)",e,t,i),this._selections.insert({from:e,to:t,offset:0,priority:i,notify:s,isStreamSelection:n}),this._selections.sort((e,t)=>t.priority-e.priority),this._updateSelections()}select(e,t,i,s){this._select(e,t,i,s,!1)}_deselect(e,t,i=!1){if(this.destroyed)throw new Error("torrent is destroyed");this._debug("deselect %s-%s",e,t),this._selections.remove({from:e,to:t,isStreamSelection:i}),this._updateSelections()}deselect(e,t){this._deselect(e,t,!1)}critical(e,t){if(this.destroyed)throw new Error("torrent is destroyed");this._debug("critical %s-%s",e,t);for(let i=e;i<=t;++i)this._critical[i]=!0;this._updateSelections()}_onWire(e,t){if(this._debug("got wire %s (%s)",e._debugId,t||"Unknown"),this.wires.push(e),t){const i=le(t);e.remoteAddress=i[0],e.remotePort=i[1]}this.client.dht&&this.client.dht.listening&&e.on("port",i=>{if(!this.destroyed&&!this.client.dht.destroyed){if(!e.remoteAddress)return this._debug("ignoring PORT from peer with no address");if(0===i||i>65536)return this._debug("ignoring invalid PORT from peer");this._debug("port: %s (from %s)",i,t),this.client.dht.addNode({host:e.remoteAddress,port:i})}}),e.on("timeout",()=>{this._debug("wire timeout (%s)",t),e.destroy()}),"webSeed"!==e.type&&e.setTimeout(3e4,!0),e.setKeepAlive(!0),e.use(nt(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 rt&&!this.private&&(e.use(rt()),e.ut_pex.on("peer",e=>{this.client.seedOutgoingConnections||!this.done?(this._debug("ut_pex: got peer: %s (from %s)",e,t),this.addPeer(e,ct.A.SOURCE_UT_PEX)):this._debug("ut_pex ignoring peer %s: torrent is done and seedOutgoingConnections is false",e)}),e.ut_pex.on("dropped",e=>{const i=this._peers.get(e);i&&!i.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",e,t),this.removePeer(e))}),e.once("close",()=>{e.ut_pex.reset()})),e.use(Je()),this.emit("wire",e,t),this.ready&&y(()=>{this._onWireWithMetadata(e)})}_onWireWithMetadata(e){let t=null;const i=()=>{this.destroyed||e.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&e.amInterested?e.destroy():(t=setTimeout(i,St),t.unref&&t.unref()))};let s;const n=()=>{if(e.peerPieces.buffer.length&&e.peerPieces.setAll){if(e.peerPieces.buffer.length!==this.bitfield.buffer.length)return;for(s=0;s<this.pieces.length;++s)if(!e.peerPieces.get(s))return}e.isSeeder=!0,this.alwaysChokeSeeders&&e.choke()};e.on("bitfield",()=>{n(),this._update(),this._updateWireInterest(e)}),e.on("have",()=>{n(),this._update(),this._updateWireInterest(e)}),e.lt_donthave.on("donthave",()=>{n(),this._update(),this._updateWireInterest(e)}),e.on("have-all",()=>{e.isSeeder=!0,this.alwaysChokeSeeders&&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(i,St),t.unref&&t.unref()}),e.on("unchoke",()=>{clearTimeout(t),this._update()}),e.on("request",(t,i,s,n)=>{if(s>131072)return e.destroy();this.pieces[t]||this.store.get(t,{offset:i,length:s},n)}),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(i,St),t.unref&&t.unref()),e.isSeeder=!1,n()}_updateSelections(){this.ready&&!this.destroyed&&(y(()=>{this._gcSelections()}),this._updateInterest(),this._update())}_gcSelections(){for(const e of this._selections){const t=e.offset;for(;this.bitfield.get(e.from+e.offset)&&e.from+e.offset<e.to;)e.offset+=1;t!==e.offset&&e.notify?.(),e.to===e.from+e.offset&&(this.bitfield.get(e.from+e.offset)&&(e.remove(),e.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 i=0;i<this.pieces.length;++i)if(this.pieces[i]&&e.peerPieces.get(i)){t=!0;break}t?e.interested():e.uninterested()}_update(){Ot?Ot(()=>this._updateWireWrapper(),{timeout:250}):this._updateWireWrapper()}_updateWireWrapper(){if(this.destroyed)return;const e=tt(this.wires);let t;for(;t=e();)this._updateWire(t)}_updateWire(e){if(e.destroyed)return!1;const t=this,i=Ht(e,.5);if(e.requests.length>=i)return;const s=Ht(e,1);if(e.peerChoking)e.hasFast&&e.peerAllowedFastSet.length>0&&!this._hasMorePieces(e.peerAllowedFastSet.length-1)&&function(){if(e.requests.length>=s)return!1;for(const i of e.peerAllowedFastSet){if(e.peerPieces.get(i)&&!t.bitfield.get(i))for(;t._request(e,i,!1)&&e.requests.length<s;);if(!(e.requests.length<s))return!0}}();else{if(!e.downloaded)return function(){if(e.requests.length)return;let i=t._selections.length;for(;i--;){const s=t._selections.get(i);let r;if("rarest"===t.strategy){const i=s.from+s.offset,o=s.to,a=o-i+1,h={};let l=0;const c=n(i,o,h);for(;l<a&&(r=t._rarityMap.getRarestPiece(c),!(r<0));){if(t._request(e,r,!1))return;h[r]=!0,l+=1}}else for(r=s.to;r>=s.from+s.offset;--r)if(e.peerPieces.get(r)&&t._request(e,r,!1))return}}();o(!1)||o(!0)}function n(t,i,s,n){return r=>r>=t&&r<=i&&!(r in s)&&e.peerPieces.get(r)&&(!n||n(r))}function r(e){let i=e;for(let s=e;s<t._selections.length&&t._selections.get(s).priority;s++)i=s;t._selections.swap(e,i)}function o(i){if(e.requests.length>=s)return!0;const o=function(){const i=e.downloadSpeed()||1;if(i>Et)return()=>!0;const s=Math.max(1,e.requests.length)*et.BLOCK_LENGTH/i;let n=10,r=0;return e=>{if(!n||t.bitfield.get(e))return!0;let o=t.pieces[e].missing;for(;r<t.wires.length;r++){const a=t.wires[r],h=a.downloadSpeed();if(!(h<Et)&&!(h<=i)&&a.peerPieces.get(e)&&!((o-=h*s)>0))return n--,!1}return!0}}();for(let a=0;a<t._selections.length;a++){const h=t._selections.get(a);let l;if("rarest"===t.strategy){const c=h.from+h.offset,d=h.to,u=d-c+1,p={};let f=0;const m=n(c,d,p,o);for(;f<u&&(l=t._rarityMap.getRarestPiece(m),!(l<0));){for(;t._request(e,l,t._critical[l]||i)&&e.requests.length<s;);if(!(e.requests.length<s))return h.priority&&r(a),!0;p[l]=!0,f++}}else for(l=h.from+h.offset;l<=h.to;l++)if(e.peerPieces.get(l)&&o(l)){for(;t._request(e,l,t._critical[l]||i)&&e.requests.length<s;);if(!(e.requests.length<s))return h.priority&&r(a),!0}}return!1}}_rechoke(){if(!this.ready)return;const e=this.wires.map(e=>({wire:e,random:Math.random()})).sort((e,t)=>{const i=e.wire,s=t.wire;return i.downloadSpeed()!==s.downloadSpeed()?i.downloadSpeed()-s.downloadSpeed():i.uploadSpeed()!==s.uploadSpeed()?i.uploadSpeed()-s.uploadSpeed():i.amChoking!==s.amChoking?i.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 i=e.pop();i.isSeeder||i===this._rechokeOptimisticWire||(i.unchoke(),i.peerInterested&&t++)}if(null===this._rechokeOptimisticWire&&this._rechokeNumSlots>0){const t=e.filter(e=>e.peerInterested);if(t.length>0){const e=t[(i=t.length,Math.random()*i|0)];e.unchoke(),this._rechokeOptimisticWire=e,this._rechokeOptimisticTime=2}}var i;e.filter(e=>e!==this._rechokeOptimisticWire).forEach(e=>e.choke())}_hotswap(e,t){const i=e.downloadSpeed();if(i<et.BLOCK_LENGTH)return!1;if(!this._reservations[t])return!1;const s=this._reservations[t];if(!s)return!1;let n,r,o=1/0;for(r=0;r<s.length;r++){const t=s[r];if(!t||t===e)continue;const a=t.downloadSpeed();a>=Et||(2*a>i||a>o||(n=t,o=a))}if(!n)return!1;for(r=0;r<s.length;r++)s[r]===n&&(s[r]=null);for(r=0;r<n.requests.length;r++){const e=n.requests[r];e.piece===t&&this.pieces[t].cancel(e.offset/et.BLOCK_LENGTH|0)}return this.emit("hotswap",n,e,t),!0}_request(e,t,i){const s=this,n=e.requests.length,r="webSeed"===e.type;if(s.bitfield.get(t))return!1;const o=r?Math.min(function(e,t,i){return 1+Math.ceil(t*e.downloadSpeed()/i)}(e,1,s.pieceLength),s.maxWebConns):Ht(e,1);if(n>=o)return!1;const a=s.pieces[t];let h=r?a.reserveRemaining():a.reserve();if(-1===h&&i&&s._hotswap(e,t)&&(h=r?a.reserveRemaining():a.reserve()),-1===h)return!1;let l=s._reservations[t];l||(l=s._reservations[t]=[]);let c=l.indexOf(null);-1===c&&(c=l.length),l[c]=e;const d=a.chunkOffset(h),u=r?a.chunkLengthRemaining(h):a.chunkLength(h);function p(){y(()=>{s._update()})}return e.request(t,d,u,async function i(n,o){if(s.destroyed)return;if(!s.ready)return s.once("ready",()=>{i(n,o)});if(l[c]===e&&(l[c]=null),a!==s.pieces[t])return p();if(n)return s._debug("error getting piece %s (offset: %s length: %s) from %s: %s",t,d,u,`${e.remoteAddress}:${e.remotePort}`,n.message),r?a.cancelRemaining(h):a.cancel(h),void p();if(s._debug("got piece %s (offset: %s length: %s) from %s",t,d,u,`${e.remoteAddress}:${e.remotePort}`),!a.set(h,o,e))return p();const f=a.flush(),m=await(0,w.tW)(f,"hex");s.destroyed||(m===s._hashes[t]?(s._debug("piece verified %s",t),s.store.put(t,f,e=>{e?s._destroy(e):(s.pieces[t]=null,s._markVerified(t),s.wires.forEach(e=>{e.have(t)}),s._checkDone(),p())})):(s.pieces[t]=new et(a.length),s.emit("warning",new Error(`Piece ${t} failed verification`)),p()))}),!0}_checkDone(){if(this.destroyed)return;this.files.forEach(e=>{if(!e.done){for(let t=e._startPiece;t<=e._endPiece;++t)if(!this.bitfield.get(t))return;e.done=!0,e.emit("done"),this._debug(`file done: ${e.name}`)}});const e=this.files.every(e=>e.done);return!this.done&&e?(this.done=!0,this._debug(`torrent done: ${this.infoHash}`),this.emit("done"),this.destroyed||this.discovery.complete()):this.done&&!e&&(this.done=!1,this.discovery.tracker?.start()),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=Nt);try{await pe(this.store,_(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(...e){e[0]=`[${this.client._debugId}] [${this._debugId}] ${e[0]}`,xt(...e)}_drain(){if(this._debug("_drain numConns %s maxConns %s _peersLength %s",this._numConns,this.client.maxConns,this._peersLength),"function"!=typeof re.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=le(e.addr),i={host:t[0],port:t[1]};this.client.utp&&e.type===ct.A.TYPE_UTP_OUTGOING?e.conn=ut.connect(i.port,i.host):e.conn=re.connect(i);const s=e.conn;s.once("connect",()=>{this.destroyed||e.onConnect()}),s.once("error",t=>{e.destroy(t)}),e.startConnectTimeout(),s.on("close",()=>{if(this.destroyed)return;if(e.retries>=At.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,At.length);return}const t=At[e.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",e.addr,t,e.retries+1);const i=setTimeout(()=>{if(this.destroyed)return;const t=le(e.addr)[0],i=this.client.utp&&this._isIPv4(t)?"utp":"tcp",s=this._addPeer(e.addr,i,e.source);s&&(s.retries=e.retries+1)},t);i.unref&&i.unref()})}_validAddr(e){let t;try{t=le(e)}catch(e){return!1}const i=t[0],s=t[1];return s>0&&s<65535&&!("127.0.0.1"===i&&s===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 Ht(e,t){let i=2+Math.ceil(t*e.downloadSpeed()/et.BLOCK_LENGTH);if(e.peerExtendedHandshake){const t=e.peerExtendedHandshake.reqq;"number"==typeof t&&t>0&&(i=Math.min(i,t))}return i}function Nt(){}var Mt=n(4043),Ft=n(580),Ut=n(815),jt=n(2878);class Bt{constructor(e,t={}){this.client=e,t.origin||(t.origin="*"),this.opts=t,this.pendingReady=new Set}static serveIndexPage(e,t,i){const s=t.map(e=>`<li>\n <a href="${Ft(i)}/${e.infoHash}">\n ${Ft(e.name)}\n </a>\n (${Ft(e.length)} bytes)\n </li>`).join("<br>");return e.status=200,e.headers["Content-Type"]="text/html",e.body=Wt("WebTorrent",`<h1>WebTorrent</h1>\n <ol>${s}</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=Wt("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=Wt("404 - Not Found","<h1>404 - Not Found</h1>"),e}static serveTorrentPage(e,t,i){const s=e.files.map(t=>`<li>\n <a href="${Ft(i)}/${e.infoHash}/${Ft(t.path)}">\n ${Ft(t.path)}\n </a>\n (${Ft(t.length)} bytes)\n </li>`).join("<br>");return t.status=200,t.headers["Content-Type"]="text/html",t.body=Wt(`${Ft(e.name)} - WebTorrent`,`<h1>${Ft(e.name)}</h1>\n <ol>${s}</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,i){i.status=200,i.headers.Expires="0",i.headers["Cache-Control"]="no-cache, no-store, must-revalidate, max-age=0",i.headers["Accept-Ranges"]="bytes",i.headers["Content-Type"]=e.type,i.headers["transferMode.dlna.org"]="Streaming",i.headers["contentFeatures.dlna.org"]="DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000","document"===t.destination?(i.headers["Content-Type"]="application/octet-stream",i.headers["Content-Disposition"]=`attachment; filename*=UTF-8''${$t(e.name)}`,i.body="DOWNLOAD"):i.headers["Content-Disposition"]=`inline; filename*=UTF-8''${$t(e.name)}`;let s=jt(e.length,t.headers.range||"");if(Array.isArray(s)?(i.status=206,s=s[0],i.headers["Content-Range"]=`bytes ${s.start}-${s.end}/${e.length}`,i.headers["Content-Length"]=s.end-s.start+1):(i.statusCode=200,s=null,i.headers["Content-Length"]=e.length),"GET"===t.method){const n=e[Symbol.asyncIterator](s);let r=null;e.emit("iterator",{iterator:n,req:t,file:e},e=>{r=e});const o=G.Readable.from(r||n);let a=null;e.emit("stream",{stream:o,req:t,file:e},e=>{a=Ut(o,e)}),i.body=a||o}else i.body=!1;return i}async onRequest(e,t){let i=new URL(e.url,"http://example.com").pathname;i=i.slice(i.indexOf(this.pathname)+this.pathname.length+1);const s={headers:{"X-Content-Type-Options":"nosniff","Content-Security-Policy":"base-uri 'none'; frame-ancestors 'none'; form-action 'none';"}};if(this.isOriginAllowed(e)&&(s.headers["Access-Control-Allow-Origin"]="*"===this.opts.origin?"*":e.headers.origin),"favicon.ico"===i)return t(Bt.serve404Page(s));if("OPTIONS"===e.method)return this.isOriginAllowed(e)?t(Bt.serveOptionsRequest(e,s)):t(Bt.serveMethodNotAllowed(s));const n=async()=>{this.pendingReady.delete(n);const e=await r();t(e)},r=async()=>{if(""===i)return Bt.serveIndexPage(s,this.client.torrents,this.pathname);let[t,...n]=i.split("/");n=decodeURI(n.join("/"));const r=await this.client.get(t);if(!t||!r)return Bt.serve404Page(s);if(!n)return Bt.serveTorrentPage(r,s,this.pathname);const o=r.files.find(e=>e.path.replace(/\\/g,"/")===n);return o?Bt.serveFile(o,e,s):Bt.serve404Page(s)};if("GET"===e.method||"HEAD"===e.method){if(this.client.ready){const e=await r();return t(e)}return this.pendingReady.add(n),void this.client.once("ready",n)}return t(Bt.serveMethodNotAllowed(s))}close(e=()=>{}){this.closed=!0,this.pendingReady.forEach(e=>{this.client.removeListener("ready",e)}),this.pendingReady.clear(),y(e)}destroy(e=()=>{}){this.closed?y(e):this.close(e),this.client=null}}class Dt extends Bt{constructor(e,t){super(e,t),this.server=Mt.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:i,body:s})=>{t.writeHead(e,i),s?._readableState||s?._writableState?Ut(s,t):t.end(s)}):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"),this.server.removeAllListeners("listening"),super.close(),this._close.call(this.server,e)}destroy(e){this.sockets.forEach(e=>{e.destroy()}),super.destroy(e)}}class qt extends Bt{constructor(e,t){super(e,t),this.registration=t.controller,this.workerKeepAliveInterval=null,this.workerPortCount=0;const i=new URL(t.controller.scope);this.pathname=i.pathname+"webtorrent",this._address={port:i.port,family:"IPv4",address:i.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[i]=e.ports;this.onRequest(t,({status:e,headers:t,body:s})=>{const n=s[Symbol.asyncIterator]?.(),r=()=>{i.onmessage=null,s?.destroy&&s.destroy(),this.workerPortCount--,this.workerPortCount||(clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null)};i.onmessage=async e=>{if(e.data){let e;try{e=(await n.next()).value}catch(e){}i.postMessage(e),e||r(),this.workerKeepAliveInterval||(this.workerKeepAliveInterval=setInterval(()=>fetch(`${this.pathname}/keepalive/`),2e4))}else r()},this.workerPortCount++,i.postMessage({status:e,headers:t,body:n?"STREAM":s})})}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 Wt(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 $t(e){return encodeURIComponent(e).replace(/['()]/g,escape).replace(/\*/g,"%2A").replace(/%(?:7C|60|5E)/g,unescape)}const zt=T("webtorrent"),Vt=ft.replace(/\d*./g,e=>("0"+e%100).slice(-2)).slice(0,4),Gt=`-WW${Vt}-`;class Kt extends r{constructor(e={}){super(),"string"==typeof e.peerId?this.peerId=e.peerId:ArrayBuffer.isView(e.peerId)?this.peerId=(0,w.V5)(e.peerId):this.peerId=(0,w.V5)((0,w.L0)(Gt+(0,w.NJ)((0,w.po)(9)))),this.peerIdBuffer=(0,w.fk)(this.peerId),"string"==typeof e.nodeId?this.nodeId=e.nodeId:ArrayBuffer.isView(e.nodeId)?this.nodeId=(0,w.V5)(e.nodeId):this.nodeId=(0,w.V5)((0,w.po)(20)),this.nodeIdBuffer=(0,w.fk)(this.nodeId),this._debugId=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.natUpnp=e.natUpnp??!0,this.natPmp=e.natPmp??!0,this.torrents=[],this.maxConns=Number(e.maxConns)||55,this.utp=Kt.UTP_SUPPORT&&!1!==e.utp,this.seedOutgoingConnections=e.seedOutgoingConnections??!0,this._downloadLimit=Math.max("number"==typeof e.downloadLimit?e.downloadLimit:-1,-1),this._uploadLimit=Math.max("number"==typeof e.uploadLimit?e.uploadLimit:-1,-1),(this.natUpnp||this.natPmp)&&"function"==typeof ie&&(this.natTraversal=new ie({enableUPNP:this.natUpnp,enablePMP:this.natPmp,upnpPermanentFallback:"permanent"===e.natUpnp})),!0===e.secure&&Promise.resolve().then(n.bind(n,5658)).then(({enableSecure:e})=>e()),this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.throttleGroups={down:new te.ThrottleGroup({rate:Math.max(this._downloadLimit,0),enabled:this._downloadLimit>=0}),up:new te.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 se?this._connPool=new se(this):y(()=>{this._onListening()}),this._downloadSpeed=ee(),this._uploadSpeed=ee(),!1!==e.dht&&"function"==typeof I.Client?(this.dht=new I.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.natTraversal&&this.natTraversal.map({publicPort:this.dhtPort,privatePort:this.dhtPort,protocol:"udp",description:"WebTorrent DHT"}).catch(e=>{zt("error mapping DHT port via UPnP/PMP: %o",e)}))}),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 L&&null!=e.blocklist?L(e.blocklist,{headers:{"user-agent":`WebTorrent/${ft} (https://webtorrent.io)`}},(e,i)=>{if(e)return console.error(`Failed to load blocklist: ${e.message}`);this.blocked=i,t()}):y(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 qt(this,e),this._server}return this._server=new Dt(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 Rt){if(this.torrents.includes(e))return e}else{const t=this.torrents;let i;try{i=await D(e)}catch(e){}if(!i)return null;if(!i.infoHash)throw new Error("Invalid torrent identifier");for(const e of t)if(e.infoHash===i.infoHash)return e}return null}add(e,t={},i=()=>{}){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,i]=[{},t]);const s=()=>{if(!this.destroyed)for(const e of this.torrents)if(e.infoHash===r.infoHash&&e!==r)return r._destroy(new Error(`Cannot add duplicate torrent ${r.infoHash}`)),void i(e)},n=()=>{this.destroyed||(i(r),this.emit("torrent",r))};this._debug("add"),t=t?Object.assign({},t):{};const r=new Rt(e,this,t);return this.torrents.push(r),r.once("_infoHash",s),r.once("ready",n),r.once("close",function e(){r.removeListener("_infoHash",s),r.removeListener("ready",n),r.removeListener("close",e)}),this.emit("add",r),r}seed(e,t,i){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,i]=[{},t]),this._debug("seed"),(t=t?Object.assign({},t):{}).skipVerify=!0;const s="string"==typeof e;s&&(t.path=function(e){if(o(e),0===e.length)return".";let t=e.charCodeAt(0);const i=47===t;let s=-1,n=!0;for(let i=e.length-1;i>=1;--i)if(t=e.charCodeAt(i),47===t){if(!n){s=i;break}}else n=!1;return-1===s?i?"/":".":i&&1===s?"//":e.slice(0,s)}(e)),t.createdBy||(t.createdBy=`WebTorrent/${Vt}`);const n=e=>{this._debug("on seed"),"function"==typeof i&&i(e),e.emit("seed"),this.emit("seed",e)},r=this.add(null,t,e=>{const i=[i=>{if(s||t.preloadedStore)return i();e.load(a,i)}];this.dht&&i.push(t=>{e.once("dhtAnnounce",t)}),g(i,t=>{if(!this.destroyed)return t?e._destroy(t):void n(e)})});let a;var h;return h=e,"undefined"!=typeof FileList&&h instanceof FileList?e=Array.from(e):Array.isArray(e)||(e=[e]),g(e.map(e=>async i=>{if(!t.preloadedStore&&function(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}(e)){const t=[];try{for await(const i of e)t.push(i)}catch(e){return i(e)}const s=(0,w.xW)(t);s.name=e.name,i(null,s)}else i(null,e)}),(e,s)=>{if(!this.destroyed)return e?r._destroy(e):void function(e,t,i){"function"==typeof t&&([t,i]=[i,t]),x(e,t=t?Object.assign({},t):{},i)}(s,t,(e,n)=>{if(!this.destroyed){if(e)return r._destroy(e);a=n.map(e=>e.getStream),P(s,t,async(e,t)=>{if(this.destroyed)return;if(e)return r._destroy(e);const s=await this.get(t);s?(console.warn("A torrent with the same id is already being seeded"),r._destroy(),"function"==typeof i&&i(s)):r._onTorrentId(t)})}})}),r}async remove(e,t,i){if("function"==typeof t)return this.remove(e,null,t);this._debug("remove");const s=await this.get(e);if(!s)throw new Error(`No torrent with id ${e}`);this._remove(s,t,i)}_remove(e,t,i){if(!e)return;if("function"==typeof t)return this._remove(e,null,t);const s=this.torrents.indexOf(e);-1!==s&&(this.torrents.splice(s,1),e.destroy(t,i),this.dht&&this.dht._tables.remove(e.infoHash),this.emit("remove",e))}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 i=this.torrents.map(e=>t=>{e.destroy(t)});this._connPool&&i.push(e=>{this._connPool.destroy(e)}),this.dht&&i.push(e=>{this.dht.destroy(e)}),this._server&&i.push(e=>{this._server.destroy(e)}),this.natTraversal&&i.push(e=>{this.natTraversal.destroy().then(()=>e())}),g(i,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.natTraversal&&this.natTraversal.map({publicPort:this.torrentPort,privatePort:this.torrentPort,protocol:this.utp?null:"tcp",description:"WebTorrent Torrent"}).catch(e=>{zt("error mapping WebTorrent port via UPnP/PMP: %o",e)}))}this.emit("listening")}_debug(){const e=[].slice.call(arguments);e[0]=`[${this._debugId}] ${e[0]}`,zt(...e)}async _getByHash(e){for(const t of this.torrents)if(t.infoHashHash||(t.infoHashHash=await(0,w.tW)((0,w.fk)("72657132"+t.infoHash),"hex")),e===t.infoHashHash)return t;return null}}Kt.WEBRTC_SUPPORT=Z.WEBRTC_SUPPORT,Kt.UTP_SUPPORT=se.UTP_SUPPORT,Kt.VERSION=ft;export{Kt as default};
//# sourceMappingURL=webtorrent.min.js.map