@banou/ripple 0.0.36 → 0.0.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,4 +20,4 @@ var t=xo(),n=So(),r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Sym
20
20
  `)+` `+e.join(`,
21
21
  `)+` `+n[1]:n[0]+t+` `+e.join(`, `)+` `+n[1]}e.types=Ss();function g(e){return Array.isArray(e)}e.isArray=g;function _(e){return typeof e==`boolean`}e.isBoolean=_;function v(e){return e===null}e.isNull=v;function y(e){return e==null}e.isNullOrUndefined=y;function b(e){return typeof e==`number`}e.isNumber=b;function x(e){return typeof e==`string`}e.isString=x;function S(e){return typeof e==`symbol`}e.isSymbol=S;function C(e){return e===void 0}e.isUndefined=C;function w(e){return T(e)&&A(e)===`[object RegExp]`}e.isRegExp=w,e.types.isRegExp=w;function T(e){return typeof e==`object`&&!!e}e.isObject=T;function E(e){return T(e)&&A(e)===`[object Date]`}e.isDate=E,e.types.isDate=E;function D(e){return T(e)&&(A(e)===`[object Error]`||e instanceof Error)}e.isError=D,e.types.isNativeError=D;function O(e){return typeof e==`function`}e.isFunction=O;function k(e){return e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`||typeof e==`symbol`||e===void 0}e.isPrimitive=k,e.isBuffer=Cs();function A(e){return Object.prototype.toString.call(e)}function j(e){return e<10?`0`+e.toString(10):e.toString(10)}var M=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function ee(){var e=/* @__PURE__ */ new Date,t=[j(e.getHours()),j(e.getMinutes()),j(e.getSeconds())].join(`:`);return[e.getDate(),M[e.getMonth()],t].join(` `)}e.log=function(){console.log(`%s - %s`,ee(),e.format.apply(e,arguments))},e.inherits=yo(),e._extend=function(e,t){if(!t||!T(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e};function N(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var P=typeof Symbol<`u`?Symbol(`util.promisify.custom`):void 0;e.promisify=function(e){if(typeof e!=`function`)throw TypeError(`The "original" argument must be of type Function`);if(P&&e[P]){var n=e[P];if(typeof n!=`function`)throw TypeError(`The "util.promisify.custom" argument must be of type Function`);return Object.defineProperty(n,P,{value:n,enumerable:!1,writable:!1,configurable:!0}),n}function n(){for(var t,n,r=new Promise(function(e,r){t=e,n=r}),i=[],a=0;a<arguments.length;a++)i.push(arguments[a]);i.push(function(e,r){e?n(e):t(r)});try{e.apply(this,i)}catch(e){n(e)}return r}return Object.setPrototypeOf(n,Object.getPrototypeOf(e)),P&&Object.defineProperty(n,P,{value:n,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(n,t(e))},e.promisify.custom=P;function F(e,t){if(!e){var n=/* @__PURE__ */ Error(`Promise was rejected with a falsy value`);n.reason=e,e=n}return t(e)}function I(e){if(typeof e!=`function`)throw TypeError(`The "original" argument must be of type Function`);function n(){for(var t=[],n=0;n<arguments.length;n++)t.push(arguments[n]);var r=t.pop();if(typeof r!=`function`)throw TypeError(`The last argument must be of type Function`);var i=this,a=function(){return r.apply(i,arguments)};e.apply(this,t).then(function(e){process.nextTick(a.bind(null,null,e))},function(e){process.nextTick(F.bind(null,e,a))})}return Object.setPrototypeOf(n,Object.getPrototypeOf(e)),Object.defineProperties(n,t(e)),n}e.callbackify=I})),Ts=/* @__PURE__ */ t(((e,t)=>{function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function r(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]==null?{}:arguments[t];t%2?n(Object(r),!0).forEach(function(t){i(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function i(e,t,n){return t=c(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,c(r.key),r)}}function s(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function c(e){var t=l(e,`string`);return typeof t==`symbol`?t:String(t)}function l(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var u=Co().Buffer,d=ws().inspect,f=d&&d.custom||`inspect`;function p(e,t,n){u.prototype.copy.call(e,t,n)}t.exports=/*#__PURE__*/ function(){function e(){a(this,e),this.head=null,this.tail=null,this.length=0}return s(e,[{key:`push`,value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:`unshift`,value:function(e){var t={data:e,next:this.head};this.length===0&&(this.tail=t),this.head=t,++this.length}},{key:`shift`,value:function(){if(this.length!==0){var e=this.head.data;return this.head=this.length===1?this.tail=null:this.head.next,--this.length,e}}},{key:`clear`,value:function(){this.head=this.tail=null,this.length=0}},{key:`join`,value:function(e){if(this.length===0)return``;for(var t=this.head,n=``+t.data;t=t.next;)n+=e+t.data;return n}},{key:`concat`,value:function(e){if(this.length===0)return u.alloc(0);for(var t=u.allocUnsafe(e>>>0),n=this.head,r=0;n;)p(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:`consume`,value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:`first`,value:function(){return this.head.data}},{key:`_getString`,value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,a=e>i.length?i.length:e;if(a===i.length?r+=i:r+=i.slice(0,e),e-=a,e===0){a===i.length?(++n,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=i.slice(a));break}++n}return this.length-=n,r}},{key:`_getBuffer`,value:function(e){var t=u.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,a=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,a),e-=a,e===0){a===i.length?(++r,this.head=n.next?n.next:this.tail=null):(this.head=n,n.data=i.slice(a));break}++r}return this.length-=r,t}},{key:f,value:function(e,t){return d(this,r(r({},t),{},{depth:0,customInspect:!1}))}}]),e}()})),Es=/* @__PURE__ */ t(((e,t)=>{function n(e,t){var n=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(o,this,e)):process.nextTick(o,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?n._writableState?n._writableState.errorEmitted?process.nextTick(i,n):(n._writableState.errorEmitted=!0,process.nextTick(r,n,e)):process.nextTick(r,n,e):t?(process.nextTick(i,n),t(e)):process.nextTick(i,n)}),this)}function r(e,t){o(e,t),i(e)}function i(e){(!e._writableState||e._writableState.emitClose)&&(!e._readableState||e._readableState.emitClose)&&e.emit(`close`)}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit(`error`,t)}function s(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(`error`,t)}t.exports={destroy:n,undestroy:a,errorOrDestroy:s}})),Ds=/* @__PURE__ */ t(((e,t)=>{function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var r={};function i(e,t,i){i||=Error;function a(e,n,r){return typeof t==`string`?t:t(e,n,r)}var o=/*#__PURE__*/ function(e){n(t,e);function t(t,n,r){return e.call(this,a(t,n,r))||this}return t}(i);o.prototype.name=i.name,o.prototype.code=e,r[e]=o}function a(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map(function(e){return String(e)}),n>2?`one of ${t} ${e.slice(0,n-1).join(`, `)}, or `+e[n-1]:n===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}return`of ${t} ${String(e)}`}function o(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function s(e,t,n){return(n===void 0||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function c(e,t,n){return typeof n!=`number`&&(n=0),n+t.length>e.length?!1:e.indexOf(t,n)!==-1}i(`ERR_INVALID_OPT_VALUE`,function(e,t){return`The value "`+t+`" is invalid for option "`+e+`"`},TypeError),i(`ERR_INVALID_ARG_TYPE`,function(e,t,n){var r;typeof t==`string`&&o(t,`not `)?(r=`must not be`,t=t.replace(/^not /,``)):r=`must be`;var i=s(e,` argument`)?`The ${e} ${r} ${a(t,`type`)}`:`The "${e}" ${c(e,`.`)?`property`:`argument`} ${r} ${a(t,`type`)}`;return i+=`. Received type ${typeof n}`,i},TypeError),i(`ERR_STREAM_PUSH_AFTER_EOF`,`stream.push() after EOF`),i(`ERR_METHOD_NOT_IMPLEMENTED`,function(e){return`The `+e+` method is not implemented`}),i(`ERR_STREAM_PREMATURE_CLOSE`,`Premature close`),i(`ERR_STREAM_DESTROYED`,function(e){return`Cannot call `+e+` after a stream was destroyed`}),i(`ERR_MULTIPLE_CALLBACK`,`Callback called multiple times`),i(`ERR_STREAM_CANNOT_PIPE`,`Cannot pipe, not readable`),i(`ERR_STREAM_WRITE_AFTER_END`,`write after end`),i(`ERR_STREAM_NULL_VALUES`,`May not write null values to stream`,TypeError),i(`ERR_UNKNOWN_ENCODING`,function(e){return`Unknown encoding: `+e},TypeError),i(`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`,`stream.unshift() after end event`),t.exports.codes=r})),Os=/* @__PURE__ */ t(((e,t)=>{var n=Ds().codes.ERR_INVALID_OPT_VALUE;function r(e,t,n){return e.highWaterMark==null?t?e[n]:null:e.highWaterMark}function i(e,t,i,a){var o=r(t,a,i);if(o!=null){if(!(isFinite(o)&&Math.floor(o)===o)||o<0)throw new n(a?i:`highWaterMark`,o);return Math.floor(o)}return e.objectMode?16:16384}t.exports={getHighWaterMark:i}})),ks=/* @__PURE__ */ t(((e,t)=>{t.exports=n;function n(e,t){if(r(`noDeprecation`))return e;var n=!1;function i(){if(!n){if(r(`throwDeprecation`))throw Error(t);r(`traceDeprecation`)?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return i}function r(e){try{if(!global.localStorage)return!1}catch{return!1}var t=global.localStorage[e];return t!=null&&String(t).toLowerCase()===`true`}})),As=/* @__PURE__ */ t(((e,t)=>{t.exports=T;function n(e){var t=this;this.next=null,this.entry=null,this.finish=function(){ne(t,e)}}var r;T.WritableState=C;var i={deprecate:ks()},a=bo(),o=Co().Buffer,s=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function c(e){return o.from(e)}function l(e){return o.isBuffer(e)||e instanceof s}var u=Es(),d=Os().getHighWaterMark,f=Ds().codes,p=f.ERR_INVALID_ARG_TYPE,m=f.ERR_METHOD_NOT_IMPLEMENTED,h=f.ERR_MULTIPLE_CALLBACK,g=f.ERR_STREAM_CANNOT_PIPE,_=f.ERR_STREAM_DESTROYED,v=f.ERR_STREAM_NULL_VALUES,y=f.ERR_STREAM_WRITE_AFTER_END,b=f.ERR_UNKNOWN_ENCODING,x=u.errorOrDestroy;yo()(T,a);function S(){}function C(e,t,i){r||=js(),e||={},typeof i!=`boolean`&&(i=t instanceof r),this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=d(this,e,`writableHighWaterMark`,i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=e.decodeStrings===!1;this.decodeStrings=!a,this.defaultEncoding=e.defaultEncoding||`utf8`,this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){ee(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new n(this)}C.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},(function(){try{Object.defineProperty(C.prototype,"buffer",{get:i.deprecate(function(){return this.getBuffer()},`_writableState.buffer is deprecated. Use _writableState.getBuffer instead.`,`DEP0003`)})}catch{}})();var w;typeof Symbol==`function`&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==`function`?(w=Function.prototype[Symbol.hasInstance],Object.defineProperty(T,Symbol.hasInstance,{value:function(e){return w.call(this,e)?!0:this===T&&e&&e._writableState instanceof C}})):w=function(e){return e instanceof this};function T(e){r||=js();var t=this instanceof r;if(!t&&!w.call(T,this))return new T(e);this._writableState=new C(e,this,t),this.writable=!0,e&&(typeof e.write==`function`&&(this._write=e.write),typeof e.writev==`function`&&(this._writev=e.writev),typeof e.destroy==`function`&&(this._destroy=e.destroy),typeof e.final==`function`&&(this._final=e.final)),a.call(this)}T.prototype.pipe=function(){x(this,new g)};function E(e,t){var n=new y;x(e,n),process.nextTick(t,n)}function D(e,t,n,r){var i;return n===null?i=new v:typeof n!=`string`&&!t.objectMode&&(i=new p(`chunk`,[`string`,`Buffer`],n)),!i||(x(e,i),process.nextTick(r,i),!1)}T.prototype.write=function(e,t,n){var r=this._writableState,i=!1,a=!r.objectMode&&l(e);return a&&!o.isBuffer(e)&&(e=c(e)),typeof t==`function`&&(n=t,t=null),a?t=`buffer`:t||=r.defaultEncoding,typeof n!=`function`&&(n=S),r.ending?E(this,n):(a||D(this,r,e,n))&&(r.pendingcb++,i=k(this,r,a,e,t,n)),i},T.prototype.cork=function(){this._writableState.corked++},T.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&F(this,e))},T.prototype.setDefaultEncoding=function(e){if(typeof e==`string`&&(e=e.toLowerCase()),!([`hex`,`utf8`,`utf-8`,`ascii`,`binary`,`base64`,`ucs2`,`ucs-2`,`utf16le`,`utf-16le`,`raw`].indexOf((e+``).toLowerCase())>-1))throw new b(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(T.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function O(e,t,n){return!e.objectMode&&e.decodeStrings!==!1&&typeof t==`string`&&(t=o.from(t,n)),t}Object.defineProperty(T.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function k(e,t,n,r,i,a){if(!n){var o=O(t,r,i);r!==o&&(n=!0,i=`buffer`,r=o)}var s=t.objectMode?1:r.length;t.length+=s;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else A(e,t,!1,s,r,i,a);return c}function A(e,t,n,r,i,a,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new _(`write`)):n?e._writev(i,t.onwrite):e._write(i,a,t.onwrite),t.sync=!1}function j(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick(z,e,t),e._writableState.errorEmitted=!0,x(e,r)):(i(r),e._writableState.errorEmitted=!0,x(e,r),z(e,t))}function M(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function ee(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(typeof i!=`function`)throw new h;if(M(n),t)j(e,n,r,t,i);else{var a=I(n)||e.destroyed;!a&&!n.corked&&!n.bufferProcessing&&n.bufferedRequest&&F(e,n),r?process.nextTick(N,e,n,a,i):N(e,n,a,i)}}function N(e,t,n,r){n||P(e,t),t.pendingcb--,r(),z(e,t)}function P(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit(`drain`))}function F(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var i=t.bufferedRequestCount,a=Array(i),o=t.corkedRequestsFree;o.entry=r;for(var s=0,c=!0;r;)a[s]=r,r.isBuf||(c=!1),r=r.next,s+=1;a.allBuffers=c,A(e,t,!0,t.length,a,``,o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new n(t),t.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,u=r.encoding,d=r.callback;if(A(e,t,!1,t.objectMode?1:l.length,l,u,d),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}T.prototype._write=function(e,t,n){n(new m(`_write()`))},T.prototype._writev=null,T.prototype.end=function(e,t,n){var r=this._writableState;return typeof e==`function`?(n=e,e=null,t=null):typeof t==`function`&&(n=t,t=null),e!=null&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||te(this,r,n),this},Object.defineProperty(T.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function I(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function L(e,t){e._final(function(n){t.pendingcb--,n&&x(e,n),t.prefinished=!0,e.emit(`prefinish`),z(e,t)})}function R(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final==`function`&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(L,e,t)):(t.prefinished=!0,e.emit(`prefinish`)))}function z(e,t){var n=I(t);if(n&&(R(e,t),t.pendingcb===0&&(t.finished=!0,e.emit(`finish`),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function te(e,t,n){t.ending=!0,z(e,t),n&&(t.finished?process.nextTick(n):e.once(`finish`,n)),t.ended=!0,e.writable=!1}function ne(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}Object.defineProperty(T.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState!==void 0&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),T.prototype.destroy=u.destroy,T.prototype._undestroy=u.undestroy,T.prototype._destroy=function(e,t){t(e)}})),js=/* @__PURE__ */ t(((e,t)=>{var n=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=c;var r=Ls(),i=As();yo()(c,r);for(var a=n(i.prototype),o=0;o<a.length;o++){var s=a[o];c.prototype[s]||(c.prototype[s]=i.prototype[s])}function c(e){if(!(this instanceof c))return new c(e);r.call(this,e),i.call(this,e),this.allowHalfOpen=!0,e&&(e.readable===!1&&(this.readable=!1),e.writable===!1&&(this.writable=!1),e.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once(`end`,l)))}Object.defineProperty(c.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(c.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(c.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function l(){this._writableState.ended||process.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(c.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState!==void 0&&this._writableState!==void 0&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})})),Ms=/* @__PURE__ */ t(((e,t)=>{
22
22
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
23
- var n=Co(),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),Ns=/* @__PURE__ */ t((e=>{var t=Ms().Buffer,n=t.isEncoding||function(e){switch(e=``+e,e&&e.toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:case`raw`:return!0;default:return!1}};function r(e){if(!e)return`utf8`;for(var t;;)switch(e){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:if(t)return;e=(``+e).toLowerCase(),t=!0}}function i(e){var i=r(e);if(typeof i!=`string`&&(t.isEncoding===n||!n(e)))throw Error(`Unknown encoding: `+e);return i||e}e.StringDecoder=a;function a(e){this.encoding=i(e);var n;switch(this.encoding){case`utf16le`:this.text=f,this.end=p,n=4;break;case`utf8`:this.fillLast=l,n=4;break;case`base64`:this.text=m,this.end=h,n=3;break;default:this.write=g,this.end=_;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=t.allocUnsafe(n)}a.prototype.write=function(e){if(e.length===0)return``;var t,n;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return``;n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||``},a.prototype.end=d,a.prototype.text=u,a.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function o(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e,t,n){var r=t.length-1;if(r<n)return 0;var i=o(t[r]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(e.lastNeed=i-2),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function c(e,t,n){if((t[0]&192)!=128)return e.lastNeed=0,`�`;if(e.lastNeed>1&&t.length>1){if((t[1]&192)!=128)return e.lastNeed=1,`�`;if(e.lastNeed>2&&t.length>2&&(t[2]&192)!=128)return e.lastNeed=2,`�`}}function l(e){var t=this.lastTotal-this.lastNeed,n=c(this,e,t);if(n!==void 0)return n;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function u(e,t){var n=s(this,e,t);if(!this.lastNeed)return e.toString(`utf8`,t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString(`utf8`,t,r)}function d(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+`�`:t}function f(e,t){if((e.length-t)%2==0){var n=e.toString(`utf16le`,t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString(`utf16le`,t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):``;if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString(`utf16le`,0,n)}return t}function m(e,t){var n=(e.length-t)%3;return n===0?e.toString(`base64`,t):(this.lastNeed=3-n,this.lastTotal=3,n===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString(`base64`,t,e.length-n))}function h(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+this.lastChar.toString(`base64`,0,3-this.lastNeed):t}function g(e){return e.toString(this.encoding)}function _(e){return e&&e.length?this.write(e):``}})),Ps=/* @__PURE__ */ t(((e,t)=>{var n=Ds().codes.ERR_STREAM_PREMATURE_CLOSE;function r(e){var t=!1;return function(){if(!t){t=!0;var n=[...arguments];e.apply(this,n)}}}function i(){}function a(e){return e.setHeader&&typeof e.abort==`function`}function o(e,t,s){if(typeof t==`function`)return o(e,null,t);t||={},s=r(s||i);var c=t.readable||t.readable!==!1&&e.readable,l=t.writable||t.writable!==!1&&e.writable,u=function(){e.writable||f()},d=e._writableState&&e._writableState.finished,f=function(){l=!1,d=!0,c||s.call(e)},p=e._readableState&&e._readableState.endEmitted,m=function(){c=!1,p=!0,l||s.call(e)},h=function(t){s.call(e,t)},g=function(){var t;if(c&&!p)return(!e._readableState||!e._readableState.ended)&&(t=new n),s.call(e,t);if(l&&!d)return(!e._writableState||!e._writableState.ended)&&(t=new n),s.call(e,t)},_=function(){e.req.on(`finish`,f)};return a(e)?(e.on(`complete`,f),e.on(`abort`,g),e.req?_():e.on(`request`,_)):l&&!e._writableState&&(e.on(`end`,u),e.on(`close`,u)),e.on(`end`,m),e.on(`finish`,f),t.error!==!1&&e.on(`error`,h),e.on(`close`,g),function(){e.removeListener(`complete`,f),e.removeListener(`abort`,g),e.removeListener(`request`,_),e.req&&e.req.removeListener(`finish`,f),e.removeListener(`end`,u),e.removeListener(`close`,u),e.removeListener(`finish`,f),e.removeListener(`end`,m),e.removeListener(`error`,h),e.removeListener(`close`,g)}}t.exports=o})),Fs=/* @__PURE__ */ t(((e,t)=>{var n;function r(e,t,n){return t=i(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=a(e,`string`);return typeof t==`symbol`?t:String(t)}function a(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var o=Ps(),s=Symbol(`lastResolve`),c=Symbol(`lastReject`),l=Symbol(`error`),u=Symbol(`ended`),d=Symbol(`lastPromise`),f=Symbol(`handlePromise`),p=Symbol(`stream`);function m(e,t){return{value:e,done:t}}function h(e){var t=e[s];if(t!==null){var n=e[p].read();n!==null&&(e[d]=null,e[s]=null,e[c]=null,t(m(n,!1)))}}function g(e){process.nextTick(h,e)}function _(e,t){return function(n,r){e.then(function(){if(t[u]){n(m(void 0,!0));return}t[f](n,r)},r)}}var v=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((n={get stream(){return this[p]},next:function(){var e=this,t=this[l];if(t!==null)return Promise.reject(t);if(this[u])return Promise.resolve(m(void 0,!0));if(this[p].destroyed)return new Promise(function(t,n){process.nextTick(function(){e[l]?n(e[l]):t(m(void 0,!0))})});var n=this[d],r;if(n)r=new Promise(_(n,this));else{var i=this[p].read();if(i!==null)return Promise.resolve(m(i,!1));r=new Promise(this[f])}return this[d]=r,r}},r(n,Symbol.asyncIterator,function(){return this}),r(n,`return`,function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){if(e){n(e);return}t(m(void 0,!0))})})}),n),v);t.exports=function(e){var t,n=Object.create(y,(t={},r(t,p,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,f,{value:function(e,t){var r=n[p].read();r?(n[d]=null,n[s]=null,n[c]=null,e(m(r,!1))):(n[s]=e,n[c]=t)},writable:!0}),t));return n[d]=null,o(e,function(e){if(e&&e.code!==`ERR_STREAM_PREMATURE_CLOSE`){var t=n[c];t!==null&&(n[d]=null,n[s]=null,n[c]=null,t(e)),n[l]=e;return}var r=n[s];r!==null&&(n[d]=null,n[s]=null,n[c]=null,r(m(void 0,!0))),n[u]=!0}),e.on(`readable`,g.bind(null,n)),n}})),Is=/* @__PURE__ */ t(((e,t)=>{t.exports=function(){throw Error(`Readable.from is not available in the browser`)}})),Ls=/* @__PURE__ */ t(((e,t)=>{t.exports=E;var n;E.ReadableState=T,vo().EventEmitter;var r=function(e,t){return e.listeners(t).length},i=bo(),a=Co().Buffer,o=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function s(e){return a.from(e)}function c(e){return a.isBuffer(e)||e instanceof o}var l=ws(),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=Ts(),f=Es(),p=Os().getHighWaterMark,m=Ds().codes,h=m.ERR_INVALID_ARG_TYPE,g=m.ERR_STREAM_PUSH_AFTER_EOF,_=m.ERR_METHOD_NOT_IMPLEMENTED,v=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,y,b,x;yo()(E,i);var S=f.errorOrDestroy,C=[`error`,`close`,`destroy`,`pause`,`resume`];function w(e,t,n){if(typeof e.prependListener==`function`)return e.prependListener(t,n);!e._events||!e._events[t]?e.on(t,n):Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]}function T(e,t,r){n||=js(),e||={},typeof r!=`boolean`&&(r=t instanceof n),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=p(this,e,`readableHighWaterMark`,r),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(y||=Ns().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=js(),!(this instanceof E))return new E(e);var t=this instanceof n;this._readableState=new T(e,this,t),this.readable=!0,e&&(typeof e.read==`function`&&(this._read=e.read),typeof e.destroy==`function`&&(this._destroy=e.destroy)),i.call(this)}Object.defineProperty(E.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),E.prototype.destroy=f.destroy,E.prototype._undestroy=f.undestroy,E.prototype._destroy=function(e,t){t(e)},E.prototype.push=function(e,t){var n=this._readableState,r;return n.objectMode?r=!0:typeof e==`string`&&(t||=n.defaultEncoding,t!==n.encoding&&(e=a.from(e,t),t=``),r=!0),D(this,e,t,!1,r)},E.prototype.unshift=function(e){return D(this,e,null,!0,!1)};function D(e,t,n,r,i){u(`readableAddChunk`,t);var o=e._readableState;if(t===null)o.reading=!1,ee(e,o);else{var c;if(i||(c=k(o,t)),c)S(e,c);else if(o.objectMode||t&&t.length>0){if(typeof t!=`string`&&!o.objectMode&&Object.getPrototypeOf(t)!==a.prototype&&(t=s(t)),r)o.endEmitted?S(e,new v):O(e,o,t,!0);else if(o.ended)S(e,new g);else if(o.destroyed)return!1;else o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||t.length!==0?O(e,o,t,!1):F(e,o)):O(e,o,t,!1)}else r||(o.reading=!1,F(e,o))}return!o.ended&&(o.length<o.highWaterMark||o.length===0)}function O(e,t,n,r){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit(`data`,n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&N(e)),F(e,t)}function k(e,t){var n;return!c(t)&&typeof t!=`string`&&t!==void 0&&!e.objectMode&&(n=new h(`chunk`,[`string`,`Buffer`,`Uint8Array`],t)),n}E.prototype.isPaused=function(){return this._readableState.flowing===!1},E.prototype.setEncoding=function(e){y||=Ns().StringDecoder;var t=new y(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r=``;n!==null;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),r!==``&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var A=1073741824;function j(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function M(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=j(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}E.prototype.read=function(e){u(`read`,e),e=parseInt(e,10);var t=this._readableState,n=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark===0?t.length>0:t.length>=t.highWaterMark)||t.ended))return u(`read: emitReadable`,t.length,t.ended),t.length===0&&t.ended?ae(this):N(this),null;if(e=M(e,t),e===0&&t.ended)return t.length===0&&ae(this),null;var r=t.needReadable;u(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,u(`length less than watermark`,r)),t.ended||t.reading?(r=!1,u(`reading or ended`,r)):r&&(u(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=M(n,t)));var i=e>0?ie(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&ae(this)),i!==null&&this.emit(`data`,i),i};function ee(e,t){if(u(`onEofChunk`),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?N(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,P(e)))}}function N(e){var t=e._readableState;u(`emitReadable`,t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u(`emitReadable`,t.flowing),t.emittedReadable=!0,process.nextTick(P,e))}function P(e){var t=e._readableState;u(`emitReadable_`,t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(`readable`),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,re(e)}function F(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(I,e,t))}function I(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var n=t.length;if(u(`maybeReadMore read 0`),e.read(0),n===t.length)break}t.readingMore=!1}E.prototype._read=function(e){S(this,new _(`_read()`))},E.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,u(`pipe count=%d opts=%j`,i.pipesCount,t);var a=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr?s:g;i.endEmitted?process.nextTick(a):n.once(`end`,a),e.on(`unpipe`,o);function o(e,t){u(`onunpipe`),e===n&&t&&t.hasUnpiped===!1&&(t.hasUnpiped=!0,d())}function s(){u(`onend`),e.end()}var c=L(n);e.on(`drain`,c);var l=!1;function d(){u(`cleanup`),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`drain`,c),e.removeListener(`error`,p),e.removeListener(`unpipe`,o),n.removeListener(`end`,s),n.removeListener(`end`,g),n.removeListener(`data`,f),l=!0,i.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}n.on(`data`,f);function f(t){u(`ondata`);var r=e.write(t);u(`dest.write`,r),r===!1&&((i.pipesCount===1&&i.pipes===e||i.pipesCount>1&&se(i.pipes,e)!==-1)&&!l&&(u(`false write response, pause`,i.awaitDrain),i.awaitDrain++),n.pause())}function p(t){u(`onerror`,t),g(),e.removeListener(`error`,p),r(e,`error`)===0&&S(e,t)}w(e,`error`,p);function m(){e.removeListener(`finish`,h),g()}e.once(`close`,m);function h(){u(`onfinish`),e.removeListener(`close`,m),g()}e.once(`finish`,h);function g(){u(`unpipe`),n.unpipe(e)}return e.emit(`pipe`,n),i.flowing||(u(`pipe resume`),n.resume()),e};function L(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,re(e))}}E.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=se(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),--t.pipesCount,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit(`unpipe`,this,n),this)},E.prototype.on=function(e,t){var n=i.prototype.on.call(this,e,t),r=this._readableState;return e===`data`?(r.readableListening=this.listenerCount(`readable`)>0,r.flowing!==!1&&this.resume()):e===`readable`&&!r.endEmitted&&!r.readableListening&&(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,u(`on readable`,r.length,r.reading),r.length?N(this):r.reading||process.nextTick(z,this)),n},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var n=i.prototype.removeListener.call(this,e,t);return e===`readable`&&process.nextTick(R,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(R,this),t};function R(e){var t=e._readableState;t.readableListening=e.listenerCount(`readable`)>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount(`data`)>0&&e.resume()}function z(e){u(`readable nexttick read 0`),e.read(0)}E.prototype.resume=function(){var e=this._readableState;return e.flowing||(u(`resume`),e.flowing=!e.readableListening,te(this,e)),e.paused=!1,this};function te(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ne,e,t))}function ne(e,t){u(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),re(e),t.flowing&&!t.reading&&e.read(0)}E.prototype.pause=function(){return u(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(u(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function re(e){var t=e._readableState;for(u(`flow`,t.flowing);t.flowing&&e.read()!==null;);}E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(u(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){u(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(n.objectMode||i&&i.length)&&(t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<C.length;a++)e.on(C[a],this.emit.bind(this,C[a]));return this._read=function(t){u(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(E.prototype[Symbol.asyncIterator]=function(){return b===void 0&&(b=Fs()),b(this)}),Object.defineProperty(E.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=ie,Object.defineProperty(E.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function ie(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function ae(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(oe,t,e))}function oe(e,t){if(u(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(E.from=function(e,t){return x===void 0&&(x=Is()),x(E,e,t)});function se(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),Rs=/* @__PURE__ */ t(((e,t)=>{t.exports=l;var n=Ds().codes,r=n.ERR_METHOD_NOT_IMPLEMENTED,i=n.ERR_MULTIPLE_CALLBACK,a=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,o=n.ERR_TRANSFORM_WITH_LENGTH_0,s=js();yo()(l,s);function c(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(r===null)return this.emit(`error`,new i);n.writechunk=null,n.writecb=null,t!=null&&this.push(t),r(e);var a=this._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark)}function l(e){if(!(this instanceof l))return new l(e);s.call(this,e),this._transformState={afterTransform:c.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform==`function`&&(this._transform=e.transform),typeof e.flush==`function`&&(this._flush=e.flush)),this.on(`prefinish`,u)}function u(){var e=this;typeof this._flush==`function`&&!this._readableState.destroyed?this._flush(function(t,n){d(e,t,n)}):d(this,null,null)}l.prototype.push=function(e,t){return this._transformState.needTransform=!1,s.prototype.push.call(this,e,t)},l.prototype._transform=function(e,t,n){n(new r(`_transform()`))},l.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},l.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},l.prototype._destroy=function(e,t){s.prototype._destroy.call(this,e,function(e){t(e)})};function d(e,t,n){if(t)return e.emit(`error`,t);if(n!=null&&e.push(n),e._writableState.length)throw new o;if(e._transformState.transforming)throw new a;return e.push(null)}})),zs=/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=Rs();yo()(r,n);function r(e){if(!(this instanceof r))return new r(e);n.call(this,e)}r.prototype._transform=function(e,t,n){n(null,e)}})),Bs=/* @__PURE__ */ t(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=Ds().codes,a=i.ERR_MISSING_ARGS,o=i.ERR_STREAM_DESTROYED;function s(e){if(e)throw e}function c(e){return e.setHeader&&typeof e.abort==`function`}function l(e,t,i,a){a=r(a);var s=!1;e.on(`close`,function(){s=!0}),n===void 0&&(n=Ps()),n(e,{readable:t,writable:i},function(e){if(e)return a(e);s=!0,a()});var l=!1;return function(t){if(!s&&!l){if(l=!0,c(e))return e.abort();if(typeof e.destroy==`function`)return e.destroy();a(t||new o(`pipe`))}}}function u(e){e()}function d(e,t){return e.pipe(t)}function f(e){return!e.length||typeof e[e.length-1]!=`function`?s:e.pop()}function p(){var e=[...arguments],t=f(e);if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw new a(`streams`);var n,r=e.map(function(i,a){var o=a<e.length-1;return l(i,o,a>0,function(e){n||=e,e&&r.forEach(u),!o&&(r.forEach(u),t(n))})});return e.reduce(d)}t.exports=p})),Vs=(/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=vo().EventEmitter;yo()(r,n),r.Readable=Ls(),r.Writable=As(),r.Duplex=js(),r.Transform=Rs(),r.PassThrough=zs(),r.finished=Ps(),r.pipeline=Bs(),r.Stream=r;function r(){n.call(this)}r.prototype.pipe=function(e,t){var r=this;function i(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}r.on(`data`,i);function a(){r.readable&&r.resume&&r.resume()}e.on(`drain`,a),!e._isStdio&&(!t||t.end!==!1)&&(r.on(`end`,s),r.on(`close`,c));var o=!1;function s(){o||(o=!0,e.end())}function c(){o||(o=!0,typeof e.destroy==`function`&&e.destroy())}function l(e){if(u(),n.listenerCount(this,`error`)===0)throw e}r.on(`error`,l),e.on(`error`,l);function u(){r.removeListener(`data`,i),e.removeListener(`drain`,a),r.removeListener(`end`,s),r.removeListener(`close`,c),r.removeListener(`error`,l),e.removeListener(`error`,l),r.removeListener(`end`,u),r.removeListener(`close`,u),e.removeListener(`close`,u)}return r.on(`end`,u),r.on(`close`,u),e.on(`close`,u),e.emit(`pipe`,r),e}})))(),Hs=vo(),Us=class extends Vs.Stream.Duplex{_localAddress;_remoteAddress;_webVPNTcpSocketPromise;_relay;constructor(e){if(e?.fd!==void 0)throw Error(`FKN WebVPN does not support file descriptors`);super(e),e?.connection&&this.__webvpn_tcp_socket_init__(e.connection)}_busyRelease;__webvpn_tcp_socket_init__(e,t){return this._busyRelease??=fo(`tcp socket`),t&&(this._localAddress={address:t.localAddress,family:t.localFamily,port:t.localPort},this._remoteAddress={address:t.remoteAddress,family:t.remoteFamily,port:t.remotePort},this._relay=t.relay),this._webVPNTcpSocketPromise=e.then(e=>{let t=e.dataReadableStream.getReader(),n=e.dataWritableStream.getWriter();return this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},this._remoteAddress={address:e.remoteAddress,family:e.remoteFamily,port:e.remotePort},this._relay=e.relay,{...e,reader:t,writer:n}}).catch(e=>{this.emit(`error`,e)}),this._webVPNTcpSocketPromise.then(e=>{e?this.emit(`connect`):this._busyRelease?.()}),this._webVPNTcpSocketPromise}_read(e){if(!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);this._webVPNTcpSocketPromise.then(e=>{e?e.reader.read().then(({value:e,done:t})=>{t?this.push(null):(this._restartTimeoutTimer(),this.push(e))}).catch(e=>{this.destroy(e)}):this.push(null)})}_write(e,t,n){this._webVPNTcpSocketPromise?this._webVPNTcpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not connected`);await t.writer.ready,await t.writer.write(e),this._restartTimeoutTimer(),n()}).catch(n):n(/* @__PURE__ */ Error(`Socket not connected`))}connect(...e){let t=g(...e),{relay:n}=t,r=this.__webvpn_tcp_socket_init__(co(`an outbound tcp socket`).then(e=>(n!==void 0&&go(e,`net.connect`),e.cloud.webvpn.tcpSocket({remoteAddress:t.host??`localhost`,remotePort:t.port,relay:n}))));return t.callback&&r.then(e=>{e&&t.callback.call(this)}),this}_final(e){this._webVPNTcpSocketPromise?this._webVPNTcpSocketPromise.then(async e=>{e&&await e.writer.close()}).then(()=>e(),t=>e(t)):e()}_destroy(e,t){this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._busyRelease?.(),this._webVPNTcpSocketPromise?this._webVPNTcpSocketPromise.then(async e=>{e&&await(this._resetRequested?e.resetAndDestroy():e.destroy())}).then(()=>t(e),()=>t(e)):t(e)}destroySoon(){this.writableFinished?this.destroy():(this.once(`finish`,()=>this.destroy()),this.end())}_resetRequested=!1;resetAndDestroy(){return this._resetRequested=!0,this.destroy(),this}_timeoutMs;_timeoutTimer;_restartTimeoutTimer(){this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._timeoutMs&&(this._timeoutTimer=setTimeout(()=>this.emit(`timeout`),this._timeoutMs))}setTimeout(e,t){return t&&this.on(`timeout`,t),this._timeoutMs=e,this._restartTimeoutTimer(),this}setNoDelay(e){let t=e??!0;return this._setTcpOption({type:0,value:t}),this}setKeepAlive(e,t){let n=e??!1,r=t!==void 0&&t>0?Math.max(1,Math.round(t/1e3)):0;return this._setTcpOption({type:2,enabled:n,initialDelaySeconds:r}),this}setSendBufferSize(e){return this._setTcpOption({type:3,value:e}),this}setRecvBufferSize(e){return this._setTcpOption({type:4,value:e}),this}_typeOfService;getTypeOfService(){return this._typeOfService??0}setTypeOfService(e){return this._typeOfService=e,this}_setTcpOption(e){this._webVPNTcpSocketPromise?this._webVPNTcpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}}):this.emit(`error`,/* @__PURE__ */ Error(`Cannot set socket option before connect`))}write(e,t,...n){return super.write(e,t,...n)}address(){return this._localAddress??{}}unref(){return this}ref(){return this}autoSelectFamilyAttemptedAddresses;bufferSize;bytesRead;bytesWritten;connecting;pending;get localAddress(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.address}get localPort(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.port}get localFamily(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.family}readyState;get remoteAddress(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.address}get remotePort(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.port}get remoteFamily(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.family}timeout},Ws=class extends Hs.EventEmitter{_localAddress;_webVPNTcpSocketListenerPromise;_relayChoice;_relay;constructor(e,t){super(e),this._relayChoice=e?.relay,t&&this.on(`connection`,t),e?.connection&&this.__webvpn_tcp_socket_listener_init__(e.connection)}_busyRelease;__webvpn_tcp_socket_listener_init__(e){return this._busyRelease??=fo(`tcp server`),this._webVPNTcpSocketListenerPromise=e.then(e=>(this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},this._relay=e.relay,e)).catch(e=>{this.emit(`error`,e)}),this._webVPNTcpSocketListenerPromise.then(e=>{e?this.emit(`listening`):this._busyRelease?.()}),this._webVPNTcpSocketListenerPromise}listen(...e){let t=g(...e);this._closeEmitted=!1;let n=e=>{let t=new Us;t.__webvpn_tcp_socket_init__(Promise.resolve(e),e),this.emit(`connection`,t)},r=e=>{this._localAddress=void 0;try{e&&this.listenerCount(`error`)>0&&this.emit(`error`,e)}finally{this._emitClose()}},i=this._relayChoice,a=e=>co(`a tcp listener`).then(a=>(i!==void 0&&go(a,`net.createServer`),a.cloud.webvpn.tcpSocketListener({localAddress:e,localPort:t.port,onConnection:n,onClose:r,relay:i}))),o=t.host?a(t.host):a(`::`).catch(()=>a(`0.0.0.0`)),s=this.__webvpn_tcp_socket_listener_init__(o);return t.callback&&s.then(e=>{e&&t.callback.call(this)}),this}_closeEmitted=!1;_emitClose(){this._closeEmitted||(this._closeEmitted=!0,this._busyRelease?.(),this.emit(`close`))}close(e){return this._webVPNTcpSocketListenerPromise&&this._webVPNTcpSocketListenerPromise.then(async t=>{if(t)try{await t.close(),this._localAddress=void 0,this._emitClose(),e&&e()}catch(t){this._localAddress=void 0,this._emitClose(),e&&e(t)}}),this}address(){return this._localAddress??null}getConnections(e){throw Error(`Method not implemented.`)}ref(){return this}unref(){return this}maxConnections;connections;listening;async[Symbol.asyncDispose](){}},Gs=(e,t)=>new Us().connect(e,t),Ks=Gs,qs=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new Ws(e);return t&&n.on(`connection`,t),n},Js={Socket:Us,Server:Ws,connect:Gs,createConnection:Ks,createServer:qs,isIP:h,isIPv4:p,isIPv6:m},Ys=/* @__PURE__ */ n({Server:()=>Ws,Socket:()=>Us,_default:()=>Js,connect:()=>Gs,createConnection:()=>Ks,createServer:()=>qs,default:()=>Js,isIP:()=>h,isIPv4:()=>p,isIPv6:()=>m}),Xs=Co(),Zs=class extends Hs.EventEmitter{_type;_localAddress;_remoteAddress;_connectedLocally;_connectGeneration=0;_destroyed=!1;_busyRelease;_webVPNUdpSocketPromise;_dataPort;_socketId;_sendQueue=[];_sendQueueBytes=0;_sendFlushScheduled=!1;_peerTailCache=/* @__PURE__ */ new Map;_relayChoice;_relay;constructor(e){if(super(e),!e)throw Error(`Missing options`);this._type=e.type,this._relayChoice=e.relay,e.connection&&this.__webvpn_udp_socket_init__(e.connection)}_lastRecvBufferSize=0;_lastSendBufferSize=0;_lastTtl=64;_lastMulticastTtl=1;_lastMulticastLoopback=!0;_setUdpOption(e){this._webVPNUdpSocketPromise?this._webVPNUdpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}}):this.emit(`error`,/* @__PURE__ */ Error(`Cannot set socket option before bind`))}_dataPortAcks=!1;_dataPortConsumedBytes=0;_dataPortAckedBytes=0;_ackDataPortBatch(e){if(!this._dataPortAcks||!this._dataPort||(this._dataPortConsumedBytes+=e,this._dataPortAckedBytes!==0&&this._dataPortConsumedBytes-this._dataPortAckedBytes<524288))return;this._dataPortAckedBytes=this._dataPortConsumedBytes;let t={type:_o,consumedBytes:this._dataPortConsumedBytes};this._dataPort.postMessage(t)}_onTransportClosed(e){this._destroyed||(this._destroyed=!0,this._busyRelease?.(),this._dataPort?.close(),this._dataPort=void 0,this.listenerCount(`error`)>0&&this.emit(`error`,Error(e||`WebVPN session closed`)),this.emit(`close`))}_onDataPortBatch(e){let t=new DataView(e),n=!1,r,i=0;for(;i+4<=e.byteLength;){let a=t.getUint32(i);i+=4;let o=i+a;if(o>e.byteLength)break;let s=i+4,c=t.getUint8(s);s+=1;let l,u,d;if(c===2){if(!this._remoteAddress){i=o;continue}l=this._remoteAddress.address,u=this._remoteAddress.family,d=this._remoteAddress.port}else{let n=new Uint8Array(e,s,c===0?4:16);c===0?(u=`IPv4`,l=`${n[0]}.${n[1]}.${n[2]}.${n[3]}`):(u=`IPv6`,l=tc(n)),s+=n.byteLength,d=t.getUint16(s),s+=2}let f=t.getUint32(s);s+=4;try{this.emit(`message`,Xs.Buffer.from(e.slice(s,s+f)),{address:l,family:u,port:d,size:f})}catch(e){n||(n=!0,r=e)}i=o}if(n)throw r}_peerTail(e,t){if(e===void 0||t===void 0)return Qs;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let i=d.Address4.isValid(e)?ec(e):nc(e),a=new Uint8Array(1+i.byteLength+2);return a[0]=i.byteLength===4?0:1,a.set(i,1),new DataView(a.buffer).setUint16(1+i.byteLength,t),this._peerTailCache.size>=4096&&this._peerTailCache.clear(),this._peerTailCache.set(n,a),a}_portSend(e,t,n){let r=this._peerTail(t,n),i=new Uint8Array(8+r.byteLength+4+e.byteLength),a=new DataView(i.buffer);a.setUint32(0,i.byteLength-4),a.setUint32(4,this._socketId),i.set(r,8),a.setUint32(8+r.byteLength,e.byteLength),i.set(e,12+r.byteLength),this._sendQueue.push(i),this._sendQueueBytes+=i.byteLength,!this._sendFlushScheduled&&(this._sendFlushScheduled=!0,queueMicrotask(()=>{this._sendFlushScheduled=!1;let e=this._sendQueue,t=this._sendQueueBytes;if(this._sendQueue=[],this._sendQueueBytes=0,!e.length||!this._dataPort)return;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;this._dataPort.postMessage(n.buffer,[n.buffer])}))}addMembership(e,t){if(d.Address4.isValid(e)){let n=ec(e),r=t&&d.Address4.isValid(t)?ec(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(d.Address6.isValid(e)){let t=nc(e);this._setUdpOption({type:7,group:t,ifIndex:0})}else this.emit(`error`,/* @__PURE__ */ Error(`Invalid multicast address: ${e}`))}address(){if(!this._localAddress)throw Error(`EBADF`);return this._localAddress}bind(...e){let t=_(...e),n=this._type===`udp6`?`::`:`0.0.0.0`,r=this._relayChoice,i=this.__webvpn_udp_socket_init__(co(`a udp socket`).then(e=>(r!==void 0&&go(e,`dgram.createSocket`),e.cloud.webvpn.udpSocket({type:this._type,address:t.address??n,port:t.port,dataPort:!0,relay:r}))));return t.callback&&i.then(e=>{e&&t.callback.call(this)}),this}__webvpn_udp_socket_init__(e,t){return t&&(this._localAddress={address:t.localAddress,family:t.localFamily,port:t.localPort}),this._busyRelease??=fo(`udp socket`),this._webVPNUdpSocketPromise=e.then(e=>{if(e.dataPort)this._socketId=e.socketId,this._dataPort=e.dataPort,this._dataPortAcks=e.dataPortAcks===!0,this._dataPort.onmessage=e=>{try{this._onDataPortBatch(e.data)}finally{this._ackDataPortBatch(e.data.byteLength)}};else{let t=e.dataReadableStream.getReader();(async()=>{for(;;){let{value:e,done:n}=await t.read();if(n)return;this.emit(`message`,Xs.Buffer.from(e.data),{address:e.address,family:e.family,port:e.port,size:e.size})}})().catch(e=>this._onTransportClosed(e instanceof Error?e.message:void 0))}return e.closed?.then(e=>this._onTransportClosed(e?.reason)).catch(()=>{}),this._relay=e.relay,this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e}).catch(e=>{this.emit(`error`,e)}),this._webVPNUdpSocketPromise.then(e=>{e?this.emit(`listening`):this._busyRelease?.()}),this._webVPNUdpSocketPromise}close(e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);return this._webVPNUdpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not bound`);let n=this._destroyed;this._destroyed=!0,this._busyRelease?.(),this._dataPort?.close(),this._dataPort=void 0;try{await t.close()}finally{try{e&&e()}finally{n||this.emit(`close`)}}}).catch(()=>{}),this}connect(...e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not bound`);let n=e[0],r=this._type===`udp6`?`::1`:`127.0.0.1`,i=typeof e[1]==`string`?e[1]:r,a=typeof e.at(-1)==`function`?e.at(-1):void 0,o=await t.connect({remotePort:n,remoteAddress:i});this._connectedLocally=o?.local===!0,this._remoteAddress=o?.address?{address:o.address,family:o.family,port:o.port}:{address:i,family:this._type===`udp6`?`IPv6`:`IPv4`,port:n},this._connectGeneration+=1,a&&a()}).catch(e=>{this.emit(`error`,e)})}disconnect(){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);if(!this._remoteAddress)throw Error(`ERR_SOCKET_DGRAM_NOT_CONNECTED`);let e=this._remoteAddress,t=this._connectedLocally,n=this._connectGeneration;this._remoteAddress=void 0,this._connectedLocally=void 0,this._webVPNUdpSocketPromise.then(e=>e?.disconnect?.()).catch(r=>{this._connectGeneration===n&&(this._remoteAddress=e,this._connectedLocally=t),this.emit(`error`,r)})}dropMembership(e,t){if(d.Address4.isValid(e)){let n=ec(e),r=t&&d.Address4.isValid(t)?ec(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(d.Address6.isValid(e)){let t=nc(e);this._setUdpOption({type:8,group:t,ifIndex:0})}else this.emit(`error`,/* @__PURE__ */ Error(`Invalid multicast address: ${e}`))}getRecvBufferSize(){return this._lastRecvBufferSize}getSendBufferSize(){return this._lastSendBufferSize}getSendQueueSize(){return 0}getSendQueueCount(){return 0}ref(){return this}remoteAddress(){if(!this._remoteAddress)throw Error(`ERR_SOCKET_DGRAM_NOT_CONNECTED`);return{address:this._remoteAddress.address,family:this._remoteAddress.family,port:this._remoteAddress.port}}send(...e){this._webVPNUdpSocketPromise||this.bind();let t=v(...e),n=$s(t.message),r=n;if(t.hasRange){let{offset:e,length:i}=t;if(!Number.isInteger(e)||e<0||e>n.byteLength)throw Object.assign(/* @__PURE__ */ RangeError(`"offset" is outside of buffer bounds`),{code:`ERR_BUFFER_OUT_OF_BOUNDS`});if(!Number.isInteger(i)||i<0||i>n.byteLength-e)throw Object.assign(/* @__PURE__ */ RangeError(`"length" is outside of buffer bounds`),{code:`ERR_BUFFER_OUT_OF_BOUNDS`});r=n.subarray(e,e+i)}let i=this._type===`udp6`?`::1`:`127.0.0.1`;if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(e=>{if(!e)throw Error(`Socket not bound`);let n=t.callback,a=t.address??i,o=this._remoteAddress!==void 0&&t.address===void 0;this._dataPort&&(o||d.Address4.isValid(a)||d.Address6.isValid(a))?(this._portSend(r,o?void 0:a,o?void 0:t.port),n?.call(this,null,r.byteLength)):e.send({port:t.port,address:a,message:r.byteOffset===0&&r.byteLength===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}).then(()=>n?.call(this,null,r.byteLength),e=>n?n.call(this,e,0):this.emit(`error`,e))})}setBroadcast(e){this._setUdpOption({type:0,value:e})}setMulticastInterface(e){}setMulticastLoopback(e){return this._setUdpOption({type:3,value:e}),this._setUdpOption({type:4,value:e}),this._lastMulticastLoopback=e,e}setMulticastTTL(e){return this._setUdpOption({type:2,value:e}),this._lastMulticastTtl=e,e}setRecvBufferSize(e){this._setUdpOption({type:10,value:e}),this._lastRecvBufferSize=e}setSendBufferSize(e){this._setUdpOption({type:9,value:e}),this._lastSendBufferSize=e}setTTL(e){return this._setUdpOption({type:1,value:e}),this._lastTtl=e,e}unref(){return this}addSourceSpecificMembership(e,t,n){}dropSourceSpecificMembership(e,t,n){}async[Symbol.asyncDispose](){await new Promise(e=>{this.close(e)})}},Qs=new Uint8Array([2]),$s=e=>{if(typeof e==`string`)return f.encode(e);if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(Array.isArray(e)){let t=e.map($s),n=new Uint8Array(t.reduce((e,t)=>e+t.byteLength,0)),r=0;for(let e of t)n.set(e,r),r+=e.byteLength;return n}return new Uint8Array(e)},ec=e=>{let t=e.split(`.`).map(e=>parseInt(e,10));if(t.length!==4||t.some(e=>Number.isNaN(e)||e<0||e>255))throw Error(`Invalid IPv4 address: ${e}`);return new Uint8Array(t)},tc=e=>{let t=[];for(let n=0;n<16;n+=2)t.push(e[n]<<8|e[n+1]);let n=-1,r=1;for(let e=0;e<8;){if(t[e]!==0){e++;continue}let i=e;for(;i<8&&t[i]===0;)i++;i-e>r&&(n=e,r=i-e),e=i}return n===-1?t.map(e=>e.toString(16)).join(`:`):`${t.slice(0,n).map(e=>e.toString(16)).join(`:`)}::${t.slice(n+r).map(e=>e.toString(16)).join(`:`)}`},nc=e=>{let t=new d.Address6(e).getBitsBase16(0,128).match(/.{2}/g);if(!t||t.length!==16)throw Error(`Invalid IPv6 address: ${e}`);return new Uint8Array(t.map(e=>parseInt(e,16)))},rc=(e,t)=>{let n=new Zs(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},ic={Socket:Zs,createSocket:rc},ac=/* @__PURE__ */ n({Socket:()=>Zs,createSocket:()=>rc,default:()=>ic});function oc(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function sc(e,t){let n,r=()=>{if(n)return n;let r=indexedDB.open(e);return r.onupgradeneeded=()=>r.result.createObjectStore(t),n=oc(r),n.then(e=>{e.onclose=()=>n=void 0},()=>{}),n};return(e,n)=>r().then(r=>n(r.transaction(t,e).objectStore(t)))}let cc;function lc(){return cc||=sc(`keyval-store`,`keyval`),cc}function uc(e,t=lc()){return t(`readonly`,t=>oc(t.get(e)))}function dc(e,t,n=lc()){return n(`readwrite`,n=>(n.put(t,e),oc(n.transaction)))}function fc(e,t,n=lc()){return n(`readwrite`,n=>new Promise((r,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),r(oc(n.transaction))}catch(e){i(e)}}}))}function pc(e,t=lc()){return t(`readwrite`,t=>(t.delete(e),oc(t.transaction)))}var mc={checkingFiles:1,downloadingMetadata:2,downloading:3,finished:4,seeding:5,checkingResumeData:7},hc=/^incoming connection from (\S+) \(([^)]*)\)/,gc=/^successfully listening on \[([^\]]*)\] (\S+)/,_c=/^listening on .* failed:/,vc=new TextDecoder,yc=4026531841,bc=4026531842,xc=4026531843,Sc=4026531844,Cc=4026531845,wc=4026531846,Tc={interesting:1,choked:2,remoteInterested:4,remoteChoked:8,supportsExtensions:16,localConnection:32,handshake:64,connecting:128,onParole:512,seed:1024,optimisticUnchoke:2048,snubbed:4096,uploadOnly:8192,endgameMode:16384,holepunched:32768,i2pSocket:65536,utpSocket:1<<17,sslSocket:1<<18,rc4Encrypted:1<<19,plaintextEncrypted:1<<20},Ec={seedMode:1,uploadMode:2,shareMode:4,applyIpFilter:8,paused:16,autoManaged:32,duplicateIsError:64,updateSubscribe:128,superSeeding:256,sequentialDownload:512,stopWhenReady:1024,overrideTrackers:2048,overrideWebSeeds:4096,needSaveResume:8192,disableDht:1<<19,disableLsd:1<<20,disablePex:1<<21,noVerifyFiles:1<<22,defaultDontDownload:1<<23},Dc={top:0,up:1,down:2,bottom:3},Oc={tracker:1,dht:2,pex:4,lsd:8,resumeData:16,incoming:32},W={skip:0,low:1,normal:4,top:7},kc=6e4,Ac=12,jc=1e3,Mc=class{mod;storage;destroyed=!1;fallbackTimer;filesByHandle=/* @__PURE__ */ new Map;bitfieldByHandle=/* @__PURE__ */ new Map;statusByHandle=/* @__PURE__ */ new Map;pieceWaiters=[];resumeByHandle=/* @__PURE__ */ new Map;resumeWaiters=[];peersByHandle=/* @__PURE__ */ new Map;trackersByHandle=/* @__PURE__ */ new Map;peerWaiters=[];trackerWaiters=[];priosByHandle=/* @__PURE__ */ new Map;deadlineRefs=/* @__PURE__ */ new Map;textAlerts=[];reachability={listening:{},listenFailed:[],inbound:0,inboundByTransport:{},lastInbound:null,port:null};constructor(e,t){if(this.mod=e,this.storage=t.storage??null,t.utpReceiveBufferBytes&&e._lt_set_utp_receive_buffer(t.utpReceiveBufferBytes),t.enableDht===!1&&e._lt_set_dht(0),t.rateLimits){let{download:n,upload:r,limitLocalPeers:i}=t.rateLimits;e._lt_session_set_rate_limits(Math.max(0,Math.floor(n??0)),Math.max(0,Math.floor(r??0)),i==null?-1:+!!i)}if(e._lt_session_create()!==0)throw Error(`lt_session_create returned non-zero`);let n=t.tickIntervalMs??250;this.fallbackTimer=setInterval(()=>this.tick(),n)}addMagnet(e,t=`/downloads`){let n=this.mod,r=n.stringToNewUTF8(e),i=n.stringToNewUTF8(t);try{return n._lt_session_add_magnet(r,i)>>>0}finally{n._free(r),n._free(i)}}addTorrentFile(e,t=`/downloads`){let n=this.mod,r=n._malloc(e.length);n.HEAPU8.set(e,r);let i=n.stringToNewUTF8(t);try{return n._lt_session_add_torrent_file(r,e.length,i)>>>0}finally{n._free(r),n._free(i)}}addTorrentWithResume(e,t=`/downloads`){let n=this.mod,r=n._malloc(e.length);n.HEAPU8.set(e,r);let i=n.stringToNewUTF8(t);try{return n._lt_session_add_torrent_with_resume(r,e.length,i)>>>0}finally{n._free(r),n._free(i)}}removeTorrent(e,t=!1){this.mod._lt_session_remove_torrent_ex(e,+!!t),this.failPieceWaiters(/* @__PURE__ */ Error(`read: torrent ${e} was removed`),e),this.filesByHandle.delete(e),this.bitfieldByHandle.delete(e),this.statusByHandle.delete(e),this.resumeByHandle.delete(e),this.priosByHandle.delete(e),this.deadlineRefs.delete(e)}pauseTorrent(e){this.mod._lt_torrent_pause(e)}resumeTorrent(e){this.mod._lt_torrent_resume(e)}forceRecheck(e){this.mod._lt_torrent_force_recheck(e)}saveResumeData(e,t=8e3){return this.mod._lt_torrent_save_resume_data(e),new Promise((n,r)=>{let i={handle:e,resolve:n};this.resumeWaiters.push(i),setTimeout(()=>{let e=this.resumeWaiters.indexOf(i);e>=0&&(this.resumeWaiters.splice(e,1),r(/* @__PURE__ */ Error(`save_resume_data timed out`)))},t)})}peers(e,t=4e3){return this.mod._lt_torrent_post_peers(e),this.awaitList(this.peerWaiters,this.peersByHandle,e,t)}lastPeers(e){return this.peersByHandle.get(e)??[]}trackers(e,t=4e3){return this.mod._lt_torrent_post_trackers(e),this.awaitList(this.trackerWaiters,this.trackersByHandle,e,t)}lastTrackers(e){return this.trackersByHandle.get(e)??[]}awaitList(e,t,n,r){return new Promise(i=>{let a={handle:n,resolve:i,timer:setTimeout(()=>{let r=e.indexOf(a);r>=0&&(e.splice(r,1),i(t.get(n)??[]))},r)};e.push(a)})}resolveOne(e,t,n){for(let r=e.length-1;r>=0;r--){let i=e[r];i.handle===t&&(clearTimeout(i.timer),e.splice(r,1),i.resolve(n))}}files(e){return this.filesByHandle.get(e)??null}bitfield(e){let t=this.bitfieldByHandle.get(e),n=this.filesByHandle.get(e);return!t||!n?null:{pieces:t.pieces,numPieces:t.numPieces,pieceLength:n.pieceLength,length:n.totalSize}}status(e){return this.statusByHandle.get(e)??null}async read(e,t,n,r,i={}){let a=this.filesByHandle.get(e);if(!a)throw Error(`read: no layout for handle ${e} (metadata not ready)`);let o=a.files[t];if(!o)throw Error(`read: no file ${t}`);if(!this.storage)throw Error(`read: no storage backend configured`);if(n<0)throw RangeError(`read: negative offset ${n}`);let s=Math.min(r,o.size-n);if(s<=0)return/* @__PURE__ */ new Uint8Array;let{pieceLength:c}=a,l=o.offset+n,u=Math.floor(l/c),d=Math.min(a.numPieces-1,Math.floor((l+s-1)/c));if(!this.hasPieces(e,u,d)){let t=i.deadlineMs===void 0?0:i.deadlineMs;if(t!==null){for(let n=u;n<=d;n++)this.mod._lt_torrent_set_piece_deadline(e,n,t,0);this.retainDeadlines(e,u,d)}this.mod._lt_torrent_post_status(e);try{await this.awaitPieces(e,u,d,i)}finally{t!==null&&this.releaseDeadlines(e,u,d)}}let f=await this.storage.read(a.storageIndex,t,n,s);return f instanceof Uint8Array?f:new Uint8Array(f)}setStreamWindow(e,t,n={}){let r=this.filesByHandle.get(e);if(!r)return!1;let{pieceLength:i,numPieces:a}=r,o=Math.max(1,Math.floor(n.windowPieces??Ac)),s=Math.max(0,Math.floor(n.deadlineStepMs??jc)),c=n.claimedPriority??W.normal,l=n.unclaimedPriority??W.normal,u=new Uint8Array(a).fill(l),d=n.keep&&new Uint8Array(a);if(d)for(let{start:e,end:t}of n.keep)d.fill(1,Math.max(0,e),Math.max(0,t));let f=/* @__PURE__ */ new Map,p=0;for(let e of t){let t=r.files[e.fileIndex];if(!t||t.size<=0)continue;p++;let n=Math.floor(t.offset/i),l=Math.min(a-1,Math.floor((t.offset+t.size-1)/i));for(let e=n;e<=l;e++)(!d||d[e])&&(u[e]=c);let m=Math.min(Math.max(e.offset,0),Math.max(0,t.size-1)),h=Math.min(Math.max(Math.floor((t.offset+m)/i),n),l);for(let e=0;e<o;e++){let t=h+e;if(t>l)break;u[t]=W.top;let n=e*s,r=f.get(t);(r===void 0||n<r)&&f.set(t,n)}}if(!p)return!1;if(this.mod._lt_torrent_clear_piece_deadlines(e),this.prioritizePieces(e,u),n.deadlines!==!1)for(let[t,n]of f)this.mod._lt_torrent_set_piece_deadline(e,t,n,0);return this.reissueReadDeadlines(e),n.sequential!==!1&&this.setSequential(e,!0),!0}clearStreamWindow(e){this.mod._lt_torrent_clear_piece_deadlines(e);let t=this.filesByHandle.get(e);t&&this.prioritizePieces(e,new Uint8Array(t.numPieces).fill(W.normal)),this.reissueReadDeadlines(e),this.setSequential(e,!1)}prioritizeRange(e,t,n,r){let i=this.filesByHandle.get(e),a=i?.files[t];if(!i||!a)return;let{pieceLength:o,numPieces:s}=i,c=Math.min(r,a.size-n);if(c<=0)return;let l=Math.max(0,Math.floor((a.offset+n)/o)),u=Math.min(s-1,Math.floor((a.offset+n+c-1)/o));if(u<l)return;let d=new Uint8Array(s).fill(W.normal);for(let e=l;e<=u;e++)d[e]=W.top;this.mod._lt_torrent_clear_piece_deadlines(e),this.prioritizePieces(e,d);for(let t=l;t<=u;t++)this.mod._lt_torrent_set_piece_deadline(e,t,(t-l)*jc,0);this.reissueReadDeadlines(e)}setSequential(e,t){this.mod._lt_torrent_set_sequential(e,+!!t)}setFlags(e,t,n){this.mod._lt_torrent_set_flags(e,t>>>0,n>>>0)}setFlag(e,t,n){this.setFlags(e,n?t:0,t)}forceReannounce(e){this.mod._lt_torrent_force_reannounce(e)}moveInQueue(e,t){this.mod._lt_torrent_queue_position(e,Dc[t])}setRateLimits({download:e,upload:t,limitLocalPeers:n}){let r=e=>e==null?-1:Math.max(0,Math.floor(e));this.mod._lt_session_set_rate_limits(r(e),r(t),n==null?-1:+!!n)}setUploadLimit(e,t){this.mod._lt_torrent_set_upload_limit(e,Math.max(0,Math.floor(t)))}setDownloadLimit(e,t){this.mod._lt_torrent_set_download_limit(e,Math.max(0,Math.floor(t)))}setPieceDeadline(e,t,n,r=!1){this.mod._lt_torrent_set_piece_deadline(e,t,n,+!!r)}clearPieceDeadlines(e){this.mod._lt_torrent_clear_piece_deadlines(e),this.reissueReadDeadlines(e)}resetPieceDeadline(e,t){this.mod._lt_torrent_reset_piece_deadline(e,t)}cancelPieceRequests(e,t){return this.mod._lt_torrent_cancel_piece_requests(e,t)===0}forgetPieces(e,t){let n=[...t];this.drainAlerts();let r=this.mod,i=r._malloc(n.length*4+4),a=i+n.length*4;try{for(let e=0;e<n.length;e++)r.HEAP32[(i>>2)+e]=n[e]|0;r.HEAP32[a>>2]=0;let t=r._lt_torrent_forget_pieces(e,i,n.length,a);if(t<0)return null;let o=this.bitfieldByHandle.get(e);if(o)for(let e of n)e>=0&&e<o.numPieces&&(o.pieces[e>>3]&=~(128>>(e&7)));return{forgotten:t,busy:r.HEAP32[a>>2]}}finally{r._free(i)}}prioritizePieces(e,t){let n=this.mod,r=this.filesByHandle.get(e);if(!r||!r.numPieces)return;let i=t;if(i.length!==r.numPieces){let t=new Uint8Array(r.numPieces),n=this.priosByHandle.get(e);n?t.set(n.subarray(0,r.numPieces)):t.fill(W.normal),t.set(i.subarray(0,r.numPieces)),i=t}let a=n._malloc(i.length);n.HEAPU8.set(i,a);try{n._lt_torrent_prioritize_pieces(e,a,i.length)===0&&this.priosByHandle.set(e,Uint8Array.from(i,e=>Math.min(e,W.top)))}finally{n._free(a)}}prioritizePieceList(e,t){let n=this.mod,r=this.filesByHandle.get(e);if(!r)return;let i=[...t].filter(e=>e.piece>=0&&e.piece<r.numPieces);if(!i.length)return;let a=n._malloc(i.length*4),o=n._malloc(i.length);try{let t=this.priosByHandle.get(e);for(let e=0;e<i.length;e++){let{piece:r,priority:s}=i[e],c=Math.min(Math.max(s,0),W.top);n.HEAP32[(a>>2)+e]=r,n.HEAPU8[o+e]=c,t&&r<t.length&&(t[r]=c)}n._lt_torrent_prioritize_piece_list(e,a,o,i.length)}finally{n._free(a),n._free(o)}}setFilePriorities(e,t){let n=this.mod;if(!t.length)return;let r=n._malloc(t.length);n.HEAPU8.set(t,r);try{n._lt_torrent_prioritize_files(e,r,t.length)}finally{n._free(r)}this.priosByHandle.delete(e)}setFilePriority(e,t,n){let r=this.mod._lt_torrent_set_file_priority(e,t,n)===0;return r&&this.priosByHandle.delete(e),r}piecePriorities(e){let t=this.priosByHandle.get(e);return t?Uint8Array.from(t):null}retainDeadlines(e,t,n){let r=this.deadlineRefs.get(e);r||this.deadlineRefs.set(e,r=/* @__PURE__ */ new Map);for(let e=t;e<=n;e++)r.set(e,(r.get(e)??0)+1)}releaseDeadlines(e,t,n){let r=this.deadlineRefs.get(e);if(!r)return;let i=[],a=this.priosByHandle.get(e);for(let o=t;o<=n;o++){let t=(r.get(o)??0)-1;if(t>0){r.set(o,t);continue}r.delete(o),this.mod._lt_torrent_reset_piece_deadline(e,o),i.push({piece:o,priority:a?.[o]??W.normal})}i.length&&this.prioritizePieceList(e,i),r.size||this.deadlineRefs.delete(e)}reissueReadDeadlines(e){let t=this.deadlineRefs.get(e);if(t)for(let n of t.keys())this.mod._lt_torrent_set_piece_deadline(e,n,0,0)}postStatus(e){this.mod._lt_torrent_post_status(e)}infohash(e){return this.readHash(e,this.mod._lt_torrent_infohash)}infohashV2(e){return this.readHash(e,this.mod._lt_torrent_infohash_v2)}readHash(e,t){let n=this.mod,r=n._malloc(65);try{return t.call(n,e,r)===0?n.UTF8ToString(r):null}finally{n._free(r)}}hasPieces(e,t,n){let r=this.bitfieldByHandle.get(e);if(!r)return!1;for(let e=t;e<=n;e++){if(e<0||e>=r.numPieces)return!1;let t=r.pieces[e>>3];if(t===void 0||!(t&128>>(e&7)))return!1}return!0}awaitPieces(e,t,n,r){let{signal:i}=r,a=r.timeoutMs??kc;return new Promise((r,o)=>{let s,c,l=e=>{let t=this.pieceWaiters.indexOf(u);t<0||(this.pieceWaiters.splice(t,1),s!==void 0&&clearTimeout(s),c&&i&&i.removeEventListener(`abort`,c),e?o(e):r())},u={handle:e,p0:t,p1:n,settle:l};if(this.pieceWaiters.push(u),i?.aborted){l(/* @__PURE__ */ Error(`read: aborted`));return}a>0&&(s=setTimeout(()=>l(/* @__PURE__ */ Error(`read: pieces ${t}-${n} of handle ${e} did not arrive within ${a}ms`)),a)),i&&(c=()=>l(/* @__PURE__ */ Error(`read: aborted`)),i.addEventListener(`abort`,c,{once:!0}))})}resolvePieceWaiters(){if(this.pieceWaiters.length!==0)for(let e of[...this.pieceWaiters])this.hasPieces(e.handle,e.p0,e.p1)&&e.settle()}failPieceWaiters(e,t){for(let n of[...this.pieceWaiters])(t===void 0||n.handle===t)&&n.settle(e)}popAlerts(){this.drainAlerts();let e=this.textAlerts;return this.textAlerts=[],e}drainAlerts(){let e=this.mod;e._lt_session_pump_alerts();let t=e._lt_alerts_size()>>>0;if(!t)return;let n=e._lt_alerts_data()>>>0,r=new DataView(e.HEAPU8.buffer,n,t),i=this.textAlerts,a=0;try{for(;a+8<=t;){let o=r.getUint32(a,!0);a+=4;let s=r.getUint32(a,!0);if(a+=4,a+s>t)break;if(o===yc)this.decodeTorrentReady(r,a);else if(o===bc)this.decodeStateUpdate(r,a);else if(o===Sc)this.decodeResumeData(r,a,s);else if(o===Cc)this.decodePeers(r,a);else if(o===wc)this.decodeTrackers(r,a);else if(o!==xc){let t={type:o,message:e.UTF8ToString(n+a,s)};this.observeReachability(t.message),i.push(t)}a+=s}}finally{e._lt_alerts_clear(),this.resolvePieceWaiters()}}reachable(){let e=this.reachability.port,t=this.listeners();return{listening:{...this.reachability.listening},listenFailed:[...this.reachability.listenFailed],inbound:this.reachability.inbound,inboundByTransport:{...this.reachability.inboundByTransport},lastInbound:this.reachability.lastInbound,port:e,listeners:t,portOpen:e!==null&&t.some(t=>t.up&&t.port===e)}}listeners(){let e=this.mod.__FKN;try{return e?.listeners?.()??[]}catch{return[]}}observeReachability(e){let t=hc.exec(e);if(t){let e=t[2].toLowerCase();this.reachability.inbound++,this.reachability.inboundByTransport[e]=(this.reachability.inboundByTransport[e]??0)+1,this.reachability.lastInbound={endpoint:t[1],transport:e,at:Date.now()};return}let n=gc.exec(e);if(n){this.reachability.listening[n[1].toLowerCase()]=n[2];return}_c.test(e)&&this.reachability.listenFailed.length<32&&this.reachability.listenFailed.push(e)}readStr(e,t){let n=e.getUint32(t,!0);return t+=4,[vc.decode(new Uint8Array(e.buffer,e.byteOffset+t,n)),t+n]}decodePeers(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getUint32(t,!0);t+=4;let i=[];for(let n=0;n<r;n++){let n,r;[n,t]=this.readStr(e,t),[r,t]=this.readStr(e,t);let a=e.getUint32(t,!0);t+=4;let o=e.getUint32(t,!0);t+=4;let s=e.getUint32(t,!0);t+=4;let c=e.getInt32(t,!0);t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=Number(e.getBigInt64(t,!0));t+=8;let p=Number(e.getBigInt64(t,!0));t+=8;let m=e.getInt32(t,!0)/1e6;t+=4;let h=e.getInt32(t,!0);t+=4;let g=e.getInt32(t,!0);t+=4;let _=e.getInt32(t,!0);t+=4;let v=e.getInt32(t,!0);t+=4,i.push({endpoint:n,client:r,flags:a,source:o,connectionType:s,downloadRate:c,uploadRate:l,payloadDownloadRate:u,payloadUploadRate:d,totalDownload:f,totalUpload:p,progress:m,rtt:h,numPieces:g,requestsInFlight:_,failCount:v})}this.peersByHandle.set(n,i),this.resolveOne(this.peerWaiters,n,i)}decodeTrackers(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getUint32(t,!0);t+=4;let i=[];for(let n=0;n<r;n++){let n,r;[n,t]=this.readStr(e,t),[r,t]=this.readStr(e,t);let a=e.getInt32(t,!0);t+=4;let o=e.getInt32(t,!0);t+=4;let s=e.getUint32(t,!0)!==0;t+=4;let c=e.getUint32(t,!0)!==0;t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=e.getInt32(t,!0);t+=4,i.push({url:n,message:r,tier:a,fails:o,updating:s,verified:c,nextAnnounceIn:l,seeders:u,leechers:d,downloaded:f})}this.trackersByHandle.set(n,i),this.resolveOne(this.trackerWaiters,n,i)}decodeResumeData(e,t,n){let r=e.getUint32(t,!0),i=new Uint8Array(n-4);i.set(new Uint8Array(e.buffer,e.byteOffset+t+4,n-4)),this.resumeByHandle.set(r,i),this.resumeWaiters=this.resumeWaiters.filter(e=>e.handle!==r||(e.resolve(i),!1))}decodeTorrentReady(e,t){let n=new TextDecoder,r=e.getUint32(t,!0);t+=4;let i=e.getUint32(t,!0);t+=4;let a=e.getUint32(t,!0);t+=4;let o=e.getUint32(t,!0);t+=4;let s=Number(e.getBigInt64(t,!0));t+=8;let c=e.getUint32(t,!0);t+=4;let l=[];for(let r=0;r<c;r++){let r=Number(e.getBigInt64(t,!0));t+=8;let i=Number(e.getBigInt64(t,!0));t+=8;let a=e.getUint8(t)===1;t+=1;let o=e.getUint32(t,!0);t+=4;let s=n.decode(new Uint8Array(e.buffer,e.byteOffset+t,o));t+=o,l.push({path:s,size:i,offset:r,pad:a})}let u=l.reduce((e,t)=>e+(t.pad?0:t.size),0);this.filesByHandle.set(r,{storageIndex:i,pieceLength:a,numPieces:o,totalSize:s,contentSize:u,files:l})}decodeStateUpdate(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getInt32(t,!0);t+=4;let i=Number(e.getBigInt64(t,!0));t+=8;let a=Number(e.getBigInt64(t,!0));t+=8;let o=e.getFloat32(t,!0);t+=4;let s=e.getInt32(t,!0);t+=4;let c=e.getInt32(t,!0);t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getUint32(t,!0)!==0;t+=4;let f=e.getUint32(t,!0)!==0;t+=4;let p=e.getUint32(t,!0)!==0;t+=4;let m=e.getUint32(t,!0)>>>0;t+=4;let h=Number(e.getBigInt64(t,!0));t+=8;let g=Number(e.getBigInt64(t,!0));t+=8;let _=Number(e.getBigInt64(t,!0));t+=8;let v=Number(e.getBigInt64(t,!0));t+=8;let y=Number(e.getBigInt64(t,!0));t+=8;let b=Number(e.getBigInt64(t,!0));t+=8;let x=Number(e.getBigInt64(t,!0));t+=8;let S=e.getInt32(t,!0);t+=4;let C=e.getInt32(t,!0);t+=4;let w=e.getInt32(t,!0);t+=4;let T=e.getInt32(t,!0);t+=4,t+=4;let E=e.getFloat32(t,!0);t+=4;let D=e.getInt32(t,!0);t+=4;let O=e.getInt32(t,!0);t+=4;let k=Number(e.getBigInt64(t,!0));t+=8;let A=Number(e.getBigInt64(t,!0));t+=8;let j=Number(e.getBigInt64(t,!0));t+=8;let M=e.getUint32(t,!0)!==0;t+=4;let ee;[ee,t]=this.readStr(e,t);let N=e.getInt32(t,!0);t+=4;let P=e.getInt32(t,!0);t+=4;let F=e.getUint32(t,!0);t+=4;let I=F?vc.decode(new Uint8Array(e.buffer,e.byteOffset+t,F)):``;t+=F;let L=e.getUint32(t,!0);t+=4;let R=e.getUint32(t,!0);t+=4;let z=new Uint8Array(R);z.set(new Uint8Array(e.buffer,e.byteOffset+t,R)),this.bitfieldByHandle.set(n,{pieces:z,numPieces:L});let te=0;for(let e=0;e<R;e++){let t=z[e];for(;t;)te+=t&1,t>>=1}this.statusByHandle.set(n,{state:r,progress:o,totalDone:i,totalWanted:a,downloadRate:s,uploadRate:c,numPeers:l,numSeeds:u,numPiecesTotal:L,numPiecesHave:te,paused:d,autoManaged:f,sequential:p,flags:m,queuePosition:N,errorCode:P,error:I,allTimeDownload:h,allTimeUpload:g,sessionDownload:_,sessionUpload:v,sessionPayloadDownload:y,sessionPayloadUpload:b,wasted:x,swarmSeeds:S,swarmPeers:C,numConnections:w,connectionsLimit:T,availability:E,activeSeconds:D,seedingSeconds:O,addedAt:k,completedAt:A,lastSeenComplete:j,hadIncoming:M,savePath:ee,hasMetadata:r!==mc.downloadingMetadata})}async*alerts(){for(;!this.destroyed;){for(let e of this.popAlerts())yield e;await new Promise(e=>setTimeout(e,100))}}setReservedPort(e){this.reachability.port=e}tick(){if(!this.destroyed&&(this.mod._lt_session_tick(),this.pieceWaiters.length)){let e=new Set(this.pieceWaiters.map(e=>e.handle));for(let t of e)this.mod._lt_torrent_post_status(t)}}destroy(){this.destroyed||(this.destroyed=!0,this.fallbackTimer!=null&&clearInterval(this.fallbackTimer),this.failPieceWaiters(/* @__PURE__ */ Error(`read: session destroyed`)),this.pieceWaiters=[],this.resumeWaiters=[],this.deadlineRefs.clear(),this.priosByHandle.clear(),this.mod._lt_session_destroy(),this.mod.__FKN?.teardown?.())}},Nc=8e3,Pc=e=>{try{e?.close()}catch{}},Fc=(e,t)=>new Promise(n=>{let r;try{r=e()}catch{n(null);return}if(!r||typeof r.on!=`function`){n(null);return}let i=!1,a=()=>{i||(i=!0,clearTimeout(o),Pc(r),n(null))},o=setTimeout(a,Nc);r.on(`listening`,()=>{i||(i=!0,clearTimeout(o),n(r))}),r.on(`error`,a);try{t(r)}catch{a()}});async function Ic(e,t,n=4){try{return await Lc(e,t,n)}catch{return null}}async function Lc(e,t,n){for(let r=0;r<n;r++){let i=await Fc(()=>t.createSocket({type:`udp4`}),e=>e.bind(0,`0.0.0.0`));if(!i)return null;let a=i.address?.()?.port;if(!a)return Pc(i),null;let o=await Fc(()=>e.createServer(),e=>e.listen(a,`0.0.0.0`)),s=o?o.address?.()?.port:void 0,c=!!o&&s===a;if(o&&!c&&Pc(o),!c){if(r<n-1){Pc(i);continue}return{port:a,server:null,udp:i,backlog:[],adopted:!1}}let l={port:a,server:o,udp:i,backlog:[],adopted:!1};return o.on(`connection`,e=>{l.adopted||l.backlog.push(e)}),l}return null}async function Rc(e){let t=e.moduleFactory??(await import(`./libtorrent-DleyqKUt.js`)).default,n={net:e.net,dgram:e.dgram,storage:e.storage??null,debug:e.debug??!1},r=e.reserveListenPort===!1?Promise.resolve(null):Ic(e.net,e.dgram),i=await t({fkn:n});i._lt_set_log(+!!e.debug);let a=await r;a?(n.prebound=a,i._lt_set_listen_port(a.port),!a.server&&e.debug&&console.warn(`[fkn] reserved udp ${a.port} but no matching tcp listener: inbound uTP works, inbound TCP is dark`)):e.debug&&console.warn(`[fkn] nothing reserved: the announced port is not one anyone can reach`);let o;try{o=new Mc(i,e)}catch(e){throw a&&!a.adopted&&(Pc(a.server),Pc(a.udp)),e}return o.setReservedPort(a?a.port:null),o}const zc=e=>{let t=e.match(/xt=urn:btih:([0-9a-z]+)/i);if(t)return t[1].toLowerCase();let n=e.match(/xt=urn:btmh:([0-9a-f]+)/i);if(!n)return null;let r=n[1].toLowerCase();return r.startsWith(`1220`)&&r.length===68?r.slice(4):r},Bc=25e5,Vc=e=>{if(!Number.isFinite(e)||e<=0)return 12;let t=Math.ceil(Bc/e)+1,n=Math.max(2,Math.floor(8388608/e));return Math.min(Math.max(t,2),n)},Hc=e=>Vc(e)*Math.max(0,e),Uc=e=>Math.max(1,Math.floor(Hc(e)/2)),Wc=(e,t)=>Math.min(2e3,Math.max(50,Math.round(e/Math.max(t,25e4)*1e3))),Gc=(e,t,n,r=Bc)=>{let i=e.fileOffset+n+Math.max(0,r-1);return Math.floor(i/e.pieceLength)>=e.p1?!1:Math.abs(n-t)>=Uc(e.pieceLength)};var Kc=class{storages=/* @__PURE__ */ new Map;opened=/* @__PURE__ */ new Map;onNewStorage(e,t,n){let r=(async()=>{let r=await qc(await navigator.storage.getDirectory(),t.replace(/^\/+/,``));this.storages.set(e,{rootDir:r,files:/* @__PURE__ */ new Map,opening:/* @__PURE__ */ new Map,fileMeta:n})})();return this.opened.set(e,r),r.then(()=>{this.opened.get(e)===r&&this.opened.delete(e)},()=>{}),r}async onRemoveStorage(e){this.opened.delete(e);let t=this.storages.get(e);if(t){for(let e of t.files.values())try{e.close()}catch{}this.storages.delete(e)}}read(e,t,n,r){let i=this.openFile(e,t),a=e=>{let t=new Uint8Array(r),i=e.read(t,{at:n});return i<r&&t.fill(0,i),t};return i instanceof Promise?i.then(a):a(i)}write(e,t,n,r){let i=this.openFile(e,t),a=i=>{try{let a=i.write(r,{at:n});if(a<r.length)throw console.error(`[opfs] short write`,{id:e,fileIndex:t,offset:n,want:r.length,wrote:a}),Error(`short write`)}catch(i){throw console.error(`[opfs] write failed`,{id:e,fileIndex:t,offset:n,len:r.length,err:String(i),errName:i?.name,errMsg:i?.message,isView:ArrayBuffer.isView(r),bytesType:Object.prototype.toString.call(r)}),i}};return i instanceof Promise?i.then(a).catch(n=>{throw console.error(`[opfs] openFile failed`,{id:e,fileIndex:t,err:String(n)}),n}):a(i)}async release(e){let t=this.storages.get(e);if(t){for(let e of t.files.values())try{e.flush(),e.close()}catch{}t.files.clear()}}async stop(e){return this.release(e)}async check(e){let t=!1;if(await this.opened.get(e)?.catch(()=>{t=!0}),t)return 2;let n=this.storages.get(e);if(!n)return 0;await this.release(e);for(let e of n.fileMeta)if(await this.hasBytes(n,e.path))return 2;return 0}async hasBytes(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(!r)return!1;let i=e.rootDir;try{for(let e of n)i=await i.getDirectoryHandle(e);return(await(await i.getFileHandle(r)).getFile()).size>0}catch(e){return e?.name!==`NotFoundError`}}async deleteFiles(e,t){let n=this.storages.get(e);if(n){for(let e of n.files.values())try{e.close()}catch{}n.files.clear();for(let e of n.fileMeta){let t=e.path.split(`/`).filter(Boolean),r=t.pop();if(!r)continue;let i=n.rootDir;for(let e of t)try{i=await i.getDirectoryHandle(e)}catch{i=null;break}if(i)try{await i.removeEntry(r)}catch{}}}}openFile(e,t){let n=this.storages.get(e);if(!n)throw Error(`unknown storage ${e}`);let r=n.files.get(t);if(r)return r;let i=n.opening.get(t);if(i)return i;let a=this.openFileSlow(e,t);return n.opening.set(t,a),a.finally(()=>n.opening.delete(t)),a}async openFileSlow(e,t){let n=this.storages.get(e),r=n.fileMeta[t];if(!r)throw Error(`unknown file ${t}`);let i=r.path.split(`/`).filter(Boolean),a=i.pop(),o=n.rootDir;for(let e of i)o=await o.getDirectoryHandle(e,{create:!0});let s=await(await o.getFileHandle(a,{create:!0})).createSyncAccessHandle();return n.files.set(t,s),s}};async function qc(e,t){if(!t)return e;let n=e;for(let e of t.split(`/`).filter(Boolean))n=await n.getDirectoryHandle(e,{create:!0});return n}var Jc=(e,t,n)=>{let r=e.write(t,n);if(r<t.byteLength){let e=`the storage quota took ${r} of ${t.byteLength} bytes`,n=globalThis.QuotaExceededError;throw n?new n(e):new DOMException(e,`QuotaExceededError`)}return r};const Yc=[50,150,400,900,1500],Xc=e=>e?.name===`QuotaExceededError`,Zc=e=>new Promise(t=>setTimeout(t,e)),Qc=e=>{let t=async(t,n,r,i)=>{let a=i;for(let i of Yc){if(Xc(a))break;if(n(),await Zc(i),e.has(t))throw a;try{return await r()}catch(e){a=e}}throw a};return(e,n,r)=>{try{let i=r();return i instanceof Promise?i.catch(i=>t(e,n,r,i)):i}catch(i){return t(e,n,r,i)}}},$c=()=>{let e=new Kc,t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=e,a=(e,t)=>{let n=i.storages?.get(e),r=n?.files?.get(t);if(r){n.files.delete(t);try{r.close()}catch{}}},o=async(e,t)=>{let r=n.get(e);if(r===void 0)return null;let a=i.storages?.get(r);if(!a?.fileMeta||!a.rootDir)return null;let o=0;for(let e=0;e<a.fileMeta.length;e++){if(t!==void 0&&e!==t)continue;let n=a.files?.get(e);if(n)try{o+=n.getSize();continue}catch{}let r=a.fileMeta[e].path.split(`/`).filter(Boolean),i=r.pop();if(!i)continue;let s=a.rootDir;for(let e of r)s=s?await s.getDirectoryHandle(e).catch(()=>null):null;s&&(o+=await s.getFileHandle(i).then(e=>e.getFile()).then(e=>e.size).catch(()=>0))}return o},s=Qc(t),c=(e,t,n)=>s(e,()=>a(e,t),n),l=(e,t,n,a)=>{let o=i=>{try{Jc(i,a,{at:n})}catch(n){throw Xc(n)&&r.set(e,t),n}},s=i.openFile(e,t);return s instanceof Promise?s.then(o):o(s)};return{usageOf:o,refusedFile:e=>{let t=n.get(e);return t===void 0?void 0:r.get(t)},onNewStorage:(i,a,o)=>(t.delete(i),r.delete(i),n.set(a,i),c(i,-1,()=>e.onNewStorage(i,a,o))),onRemoveStorage:r=>{t.add(r);for(let[e,t]of n)t===r&&n.delete(e);return e.onRemoveStorage(r)},read:(t,n,r,i)=>c(t,n,()=>e.read(t,n,r,i)),write:(e,t,n,r)=>c(e,t,()=>l(e,t,n,r)),release:t=>e.release(t),check:t=>e.check(t).catch(()=>2),deleteFiles:(n,r)=>(t.add(n),e.deleteFiles(n,r)),stop:t=>e.stop(t)}},el=67108864,tl=/^(\d+)-(\d+)$/,nl=/^\d+$/,rl=(e=el)=>{let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Set,o=Qc(a),s=/* @__PURE__ */ new Map,c=(e,t,n)=>{let r=`${e}/${t}`,i=s.get(r);i||s.set(r,i=/* @__PURE__ */ new Set),i.add(n);let a=()=>{i.delete(n),!i.size&&s.get(r)===i&&s.delete(r)};n.then(a,a)},l=(e,t)=>`${e}-${t}`,u=e=>{let n=r.get(e);return n===void 0?void 0:t.get(n)},d=(e,r)=>{let i=t.get(e);if(i)return r(i);let a=n.get(e);if(!a)throw Error(`unknown storage ${e}`);return a.then(r)},f=(e,t,n,r)=>{let i=[];for(let a=0;a<r;){let o=Math.floor((n+a)/e.chunkBytes),s=n+a-o*e.chunkBytes,c=Math.min(r,a+e.chunkBytes-s);i.push({name:l(t,o),at:s,from:a,to:c}),a=c}return i},p=(e,t)=>{let n=e.handles.get(t);if(n)return n;let r=e.opening.get(t);if(r)return r;let i=e.dropping.get(t),a=(async()=>{i&&await i;let n=await(await e.dir.getFileHandle(t,{create:!0})).createSyncAccessHandle();return e.handles.set(t,n),n})();e.opening.set(t,a);let o=()=>{e.opening.get(t)===a&&e.opening.delete(t)};return a.then(o,o),a},m=(e,n,r,i)=>{let a=t.get(e);if(a)for(let{name:e}of f(a,n,r,i)){let t=a.handles.get(e);a.handles.delete(e);try{t?.close()}catch{}}},h=e=>{for(let t of e.handles.values())try{t.flush(),t.close()}catch{}e.handles.clear()},g=(e,t)=>{let n=0;for(let[r,i]of e.extents)(t===void 0||r.startsWith(`${t}-`))&&(n+=i);return n},_=async t=>{let n=t.split(`/`).filter(Boolean),r=n.pop()??``,i=await navigator.storage.getDirectory();for(let e of n)i=await i.getDirectoryHandle(e,{create:!0});let a=await i.getDirectoryHandle(r,{create:!0}),o=e=>e.values(),s=e;for await(let e of o(a))e.kind===`directory`&&nl.test(e.name)&&(s=Number(e.name));let c=await a.getDirectoryHandle(String(s),{create:!0}),l=/* @__PURE__ */ new Map;for await(let e of o(c))e.kind===`file`&&l.set(e.name,await e.getFile().then(e=>e.size,()=>s));return{parent:i,name:r,chunkBytes:s,dir:c,extents:l,handles:/* @__PURE__ */ new Map,opening:/* @__PURE__ */ new Map,dropping:/* @__PURE__ */ new Map}};return{chunkBytesOf:t=>u(t)?.chunkBytes??e,chunksOf:(e,t)=>{let n=u(e);if(!n)return[];let r=[];for(let[e,i]of n.extents){let n=tl.exec(e);n&&Number(n[1])===t&&i>0&&r.push(Number(n[2]))}return r.sort((e,t)=>e-t)},footprint:()=>{let e=0;for(let n of t.values())e+=g(n);return e},usageOf:async(e,i)=>{let a=r.get(e);if(a===void 0)return null;let o=t.get(a)??await n.get(a)?.catch(()=>void 0);return o?g(o,i):null},refusedFile:e=>{let t=r.get(e);return t===void 0?void 0:i.get(t)},drop:(e,t,n)=>{let r=u(e);if(!r)return Promise.resolve();let i=l(t,n),a=r.dropping.get(i);if(a)return a;r.extents.delete(i);let o=r.handles.get(i);r.handles.delete(i);try{o?.close()}catch{}let s=r.opening.get(i),c=(async()=>{s&&await s.then(e=>{r.handles.get(i)===e&&r.handles.delete(i);try{e.close()}catch{}},()=>{}),await r.dir.removeEntry(i).catch(()=>{})})();return r.dropping.set(i,c),c.then(()=>{r.dropping.get(i)===c&&r.dropping.delete(i)}),c},readChunk:async(e,t,n)=>{let r=u(e),i=l(t,n);if(!r?.extents.has(i))return/* @__PURE__ */ new Uint8Array;let a=await p(r,i),o=new Uint8Array(a.getSize());return a.read(o,{at:0}),o},onNewStorage:(e,s)=>{a.delete(e),i.delete(e),r.set(s,e);let c=Promise.resolve(o(e,()=>{},()=>_(s)));return n.set(e,c),c.then(r=>{n.get(e)===c&&(n.delete(e),t.set(e,r))})},onRemoveStorage:e=>{a.add(e),n.delete(e);let i=t.get(e);t.delete(e);for(let[t,n]of r)n===e&&r.delete(t);i&&h(i)},read:(e,t,n,r)=>o(e,()=>m(e,t,n,r),()=>d(e,i=>{let a=new Uint8Array(r),o=[];for(let c of f(i,t,n,r)){let t=()=>{if(!i.extents.has(c.name))return;let e=e=>{e.read(a.subarray(c.from,c.to),{at:c.at})},t=p(i,c.name);if(t instanceof Promise)return t.then(e);e(t)},n=s.get(`${e}/${c.name}`);if(n)o.push(Promise.allSettled([...n]).then(t));else{let e=t();e&&o.push(e)}}return o.length?Promise.all(o).then(()=>a):a})),write:(e,r,a,s)=>{let l=o(e,()=>m(e,r,a,s.length),()=>d(e,t=>{let n=[];for(let o of f(t,r,a,s.length)){let a=n=>{try{Jc(n,s.subarray(o.from,o.to),{at:o.at})}catch(a){Xc(a)&&i.set(e,r);try{t.extents.set(o.name,n.getSize())}catch{}throw a}let a=o.at+o.to-o.from;(t.extents.get(o.name)??0)<a&&t.extents.set(o.name,a)},c=p(t,o.name);c instanceof Promise?n.push(c.then(a)):a(c)}return n.length?Promise.all(n).then(()=>{}):void 0}));if(l instanceof Promise){let i=t=>{for(let{name:n}of f(t,r,a,s.length))c(e,n,l)},o=t.get(e);o?i(o):n.get(e)?.then(i,()=>{})}return l},check:async e=>{try{let r=t.get(e)??await n.get(e);return r&&g(r)>0?2:0}catch{return 2}},release:async e=>{let n=t.get(e);n&&h(n)},stop:async e=>{let n=t.get(e);n&&h(n)},deleteFiles:async e=>{a.add(e);let r=t.get(e)??await n.get(e)?.catch(()=>void 0);r&&(await Promise.all([...r.opening.values()].map(e=>e.catch(()=>{}))),h(r),r.extents.clear(),await r.parent.removeEntry(r.name,{recursive:!0}).catch(()=>{}))}}},il=[5e3,15e3,3e4,6e4,12e4,3e5],al=1e4,ol=/* @__PURE__ */ new Set([2,3]),sl=/* @__PURE__ */ new Set([1,7]),cl=e=>!!e&&e.paused&&!e.autoManaged,ll=()=>{let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=e=>il[Math.min(e,il.length-1)],a=i=>{e.delete(i),t.delete(i),n.delete(i),r.delete(i)};return{hold:(e,t,n=al)=>r.set(e,t+n),observe:(o,s,c,l)=>{if(c){a(o);return}if(!s)return;let u=r.get(o);if(u!==void 0){if(l<u)return;r.delete(o)}let d=t.get(o);(!d||s.totalDone>d.totalDone)&&t.set(o,{totalDone:s.totalDone,at:l});let f=t.get(o).at;if(sl.has(s.state))return;let p=e.get(o);if(s.error&&(n.set(o,s.error),p&&(p.message=s.error)),p&&l<p.graceUntil||s.paused&&s.queued)return;let m=s.paused?`stopped`:ol.has(s.state)&&s.numPeers===0&&s.downloadRate===0&&l-f>=12e4?`stalled`:null;if(!m){if(!p)return;p.healthySince??=l,l-p.healthySince>=6e4&&a(o);return}if(!p){e.set(o,{reason:m,attempt:0,retryAt:l+i(0),message:n.get(o),healthySince:null,graceUntil:0});return}p.reason=m,p.healthySince!==null&&(p.healthySince=null,p.retryAt=l+i(p.attempt))},due:t=>{let n=[];for(let[r,a]of e)a.healthySince!==null||t<a.retryAt||(a.attempt++,a.retryAt=t+i(a.attempt),a.graceUntil=t+al,n.push({handle:r,reason:a.reason}));return n},retryNow:t=>{for(let n of e.values())n.healthySince===null&&(n.attempt=0,n.retryAt=t)},retry:(t,n)=>{let i=e.get(t);i&&(i.attempt=0,i.retryAt=n,i.healthySince=null,i.graceUntil=0,r.delete(t))},state:t=>{let n=e.get(t);return!n||n.healthySince!==null?null:{reason:n.reason,attempt:n.attempt,retryAt:n.retryAt,message:n.message}},forget:a,retain:i=>{for(let o of[e,t,n,r])for(let e of[...o.keys()])i.has(e)||a(e)}}},ul=e=>!(e.flags&Tc.localConnection)||!!(e.source&Oc.incoming),dl=e=>e.flags&Tc.utpSocket?`utp`:`tcp`,fl={total:0,byTransport:{}},pl=e=>{let t={},n=0;for(let r of e)for(let e of r){if(!ul(e)||e.connectionType!==0)continue;n+=1;let r=dl(e);t[r]=(t[r]??0)+1}return{total:n,byTransport:t}},ml={activeSeconds:0,seedingSeconds:0},hl=[`activeSeconds`,`seedingSeconds`,`downloaded`,`uploaded`,`wasted`],gl={activeSeconds:0,seedingSeconds:0,downloaded:0,uploaded:0,wasted:0},_l=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0,vl=(e,t)=>({activeSeconds:Math.max(0,_l(t.activeSeconds)-_l(e.activeSeconds)),seedingSeconds:Math.max(0,_l(t.seedingSeconds)-_l(e.seedingSeconds))}),yl=(e,t,n)=>{let r=vl(t,n);return{activeSeconds:_l(e?.activeSeconds)+r.activeSeconds,seedingSeconds:_l(e?.seedingSeconds)+r.seedingSeconds}},bl=(e,t)=>Object.fromEntries(hl.map(n=>[n,Math.max(0,_l(t[n])-_l(e[n]))])),xl=(e,t,n)=>{let r=bl(t,n);return Object.fromEntries(hl.map(t=>[t,_l(e?.[t])+r[t]]))},Sl=(e,t)=>Object.fromEntries(hl.map(n=>[n,Math.max(_l(e?.[n]),_l(t?.[n]))])),Cl=(e,t)=>t.activeSeconds-_l(e?.activeSeconds)>=30||t.seedingSeconds-_l(e?.seedingSeconds)>=30,wl=67108864,Tl=e=>!Number.isFinite(e)||e<=0?0:Math.min(1e9,Math.floor(e*.1)),El=(e,t)=>!Number.isFinite(e)||e<=0?Math.max(0,t):Math.max(Math.min(.25*e,2e10),Math.max(0,t)),Dl=({usedBytes:e,limitBytes:t,pendingBytes:n,refusedBytes:r,candidates:i})=>{if(!Number.isFinite(t)||t<=0||!Number.isFinite(e)||e<0)return!1;let a=t-e,o=i.reduce((e,t)=>e+Math.max(0,t.bytesOnDisk),0);return a<Math.min(n,67108864)&&n>a+o||r>0&&r+67108864>a+o},Ol=(e,t)=>e.usedAt-t.usedAt||(e.infoHash<t.infoHash?-1:+(e.infoHash>t.infoHash)),kl=({usedBytes:e,limitBytes:t,pendingBytes:n,candidates:r})=>{if(!Number.isFinite(t)||t<=0||!Number.isFinite(e)||e<0)return[];let i=r.filter(e=>e.bytesOnDisk>0).sort(Ol);if(!i.length)return[];let a=[0];for(let e of i)a.push(a[a.length-1]+e.bytesOnDisk);let o=e=>{for(let t=0;t<=i.length;t++)if(e(t))return t;return-1},s=Math.max(0,n),c=t-e,l=o(e=>c+a[e]>=s+Tl(t)),u=o(e=>c+a[e]>=s+wl),d=l>=0?l:Math.max(0,u),f=a[i.length],p=i.reduce((e,t)=>Math.max(e,t.bytesOnDisk),0),m=El(t,p),h=o(e=>f-a[e]<=m);return i.slice(0,Math.max(d,h<0?i.length:h)).map(e=>e.infoHash)},Al={start:0,end:0},jl=(e,t,n)=>{let r=Math.min(n,e.size);return r<=t?Al:{start:Math.floor((e.offset+t)/e.pieceLength),end:Math.floor((e.offset+r-1)/e.pieceLength)+1}},Ml=(e,t,n)=>jl(e,n*t,(n+1)*t),Nl=(e,t,n)=>{let r=/* @__PURE__ */ new Set;for(let{start:i,end:a}of n){let n=Math.max(0,i*e.pieceLength-e.offset),o=Math.min(e.size,a*e.pieceLength-e.offset);for(let e=Math.floor(n/t);n<o&&e<=Math.floor((o-1)/t);e++)r.add(e)}return r},Pl=(e,t)=>{let n=[],r=t,i=e.map((e,t)=>({size:e,i:t})).sort((e,t)=>e.size-t.size);return i.forEach(({size:e,i:t},a)=>{let o=Math.min(e,r/(i.length-a));n[t]=o,r-=o}),n},Fl=(e,t,n)=>e>t&&Math.floor(t/n)>=23,Il=({file:e,chunkBytes:t,room:n,reader:r,held:i,pinned:a=[]})=>{if(!Fl(e.size,n,t))return null;let o=Math.ceil(e.size/t)-1,s=Math.floor(Math.min(Math.max(r,0),e.size-1)/t),c=Math.floor(n/t)-3,l=new Set(i),u=jl(e,0,t),d=Math.max(0,o-2-s),f=n=>{if(!d){let n=jl(e,s*t,e.size);return{want:[u,n],ahead:n,slack:Al}}let r=jl(e,s*t,n*t),i=jl(e,n*t,(n+2)*t);return{want:[u,r,i,jl(e,o*t,e.size)],ahead:r,slack:i}},p=n=>Nl(e,t,[...f(n).want,...a]),m=s+Math.min(16,d),h=p(m);for(;m<s+d;){let e=p(m+1);if(e.size>c||[...e].some(e=>!h.has(e)&&!l.has(e))&&(/* @__PURE__ */ new Set([...e,...l])).size>c)break;m++,h=e}let g=/* @__PURE__ */ new Set([...h,...l]),_=[...l].filter(e=>!h.has(e)).sort((e,t)=>Math.abs(t-s)-Math.abs(e-s)||t-e);for(let e of _){if(g.size<=c)break;g.delete(e)}return{...f(m),keep:[...g].sort((e,t)=>e-t)}},Ll=(e,t,n)=>e||t<n,Rl=(e,t,n)=>{if(!e||t.usedBytes<e.usedBytes||t.headroomBytes>e.headroomBytes)return{...t,fixed:e?.fixed};let r=t.usedBytes-e.usedBytes;return r<n?e:{...t,fixed:e.headroomBytes-t.headroomBytes>=r/2}};var zl=8,Bl=2e4,Vl=e=>typeof e.values==`function`,Hl=async e=>{let t=0,n=0,r=async(e,i)=>{if(!(i>zl))for await(let a of e.values()){if(++n>Bl)return;if(Vl(a)){await r(a,i+1);continue}let e=await a.getFile().catch(()=>null);e&&(t+=e.size)}};try{return await r(e,0),t}catch{return null}},Ul=(e,t)=>{let n=e.usage;if(t===null||!Number.isFinite(t)||t<0)return n;if(n===void 0)return t;let r=e.usageDetails?.fileSystem;if(typeof r==`number`){let e=Math.max(0,n-r);return Math.max(n,t+e)}return Math.max(n,t)},Wl,Gl,Kl=(e,t,n)=>{if(e!==void 0)return n!==Gl&&(Wl=void 0),Gl=n,Wl=Wl===void 0?e:Math.min(Wl,e),Math.max(Wl,t??0)},ql=async e=>e.persisted?e.persisted().then(e=>e===!0).catch(()=>Gl):void 0,Jl={estimate:async()=>{let e=globalThis.navigator?.storage;if(!e?.estimate)return{};let t=await e.estimate(),[n,r]=await Promise.all([e.getDirectory?e.getDirectory().then(e=>Hl(e)).catch(()=>null):null,ql(e)]),i=Ul(t,n);return{...t,usage:i,quota:Kl(t.quota,i,r)}},persist:async()=>{let e=globalThis.navigator?.storage;if(!e?.persist)return!1;let t=await e.persist().catch(()=>!1);return await ql(e)??null??t},persisted:()=>globalThis.navigator?.storage?.persisted?.()??Promise.resolve(!1),getDirectory:()=>{let e=globalThis.navigator?.storage;return e?.getDirectory?e.getDirectory():Promise.reject(/* @__PURE__ */ Error(`this browser has no origin private file system`))}};const Yl=/^(?:[0-9a-f]{40}|[0-9a-f]{64}|[a-z2-7]{32})$/i,Xl=({entries:e,listedHashes:t,claimedNames:n,attributable:r})=>e.filter(({name:e,kind:i})=>n.has(e)?!1:i===`directory`&&Yl.test(e)?!t.has(e.toLowerCase()):r).map(({name:e})=>e),Zl=async e=>{let t=[];for await(let n of e.values())t.push({name:n.name,kind:n.kind});return t},Ql=async(e,t)=>{let n=e;for(let e of t.split(`/`).filter(Boolean))n=n?await n.getDirectoryHandle(e).catch(()=>null):null;return n},$l=async(e,t,n)=>{let r=await Ql(e,t);if(!r)return[];let i=[];for(let e of Xl({...n,entries:await Zl(r)}))try{await r.removeEntry(e,{recursive:!0}),i.push(e)}catch{}return i},eu=async e=>{let t=0;for(let{name:n,kind:r}of await Zl(e))r===`file`&&n.startsWith(`.ripple-probe-`)&&await e.removeEntry(n).then(()=>!0,()=>!1)&&t++;return t},tu=/* @__PURE__ */ new Set([`export-start`,`export-chunk`,`import-start`]),nu=e=>e?`/dl/`+e:`/dl`,ru=e=>`/cache/`+e,iu=e=>!!e?.startsWith(`/cache/`),au=(e,t)=>e===nu(t)||e===ru(t),ou=(e,t)=>t&&(!e||e.ephemeral===!0),su=(e,t)=>e?{...t,ephemeral:ou(e,t.ephemeral===!0),addedAt:Math.min(e.addedAt,t.addedAt),lastUsedAt:Math.max(e.lastUsedAt??0,t.lastUsedAt??t.addedAt),savePath:e.savePath||t.savePath,rootEntry:t.rootEntry??e.rootEntry,name:t.name??e.name,size:t.size??e.size,files:t.files??e.files,format:t.format??e.format,pieceLength:t.pieceLength??e.pieceLength,downloadLimit:t.downloadLimit??e.downloadLimit,uploadLimit:t.uploadLimit??e.uploadLimit,activeSeconds:t.activeSeconds??e.activeSeconds,seedingSeconds:t.seedingSeconds??e.seedingSeconds,downloaded:t.downloaded??e.downloaded,uploaded:t.uploaded??e.uploaded,wasted:t.wasted??e.wasted,saveTo:t.saveTo??e.saveTo,wantedFiles:t.wantedFiles??e.wantedFiles,firstLast:t.firstLast??e.firstLast,created:t.created??e.created}:t,cu=e=>({name:typeof e.name==`string`&&e.name?e.name:void 0,size:typeof e.size==`number`&&Number.isFinite(e.size)&&e.size>=0?e.size:void 0,files:Array.isArray(e.files)?e.files.filter(e=>!!e&&typeof e.name==`string`&&typeof e.size==`number`&&Number.isFinite(e.size)).slice(0,100):void 0}),lu=`ripple:torrents`,uu=`ripple:removed`,du=(...e)=>{let t=/* @__PURE__ */ new Map;for(let n of e)if(Array.isArray(n))for(let e of n)typeof e?.infoHash==`string`&&e.infoHash&&typeof e.removedAt==`number`&&Number.isFinite(e.removedAt)&&t.set(e.infoHash,Math.max(t.get(e.infoHash)??e.removedAt,e.removedAt));return[...t].map(([e,t])=>({infoHash:e,removedAt:t}))},fu=e=>{let t=new Map(e.map(e=>[e.infoHash,e.removedAt]));return e=>{let n=t.get(e.infoHash);return n===void 0||(e.addedAt??0)>n}},pu=(e,t,n)=>{let r=fu(n),i=t.filter(e=>!!e&&r(e)),a=new Set(i.map(e=>e.infoHash));return{list:e.filter(e=>e.started!==!1||a.has(e.infoHash)||r(e)),incoming:i}},mu=e=>`ripple:resume:`+e,hu=e=>`ripple:torrent:`+e,gu=e=>`ripple:thumb:`+e,_u=nu(zc(`magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.torrent.eu.org%3A451&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F`)),G={formatMessage:(e,t)=>t?{message:e.id,values:t}:{message:e.id}},vu=e=>typeof e.getFile==`function`?e.getFile():Promise.resolve(e),yu=e=>`/native/${e}`,bu=e=>e===`/native`||!!e?.startsWith(`/native/`),xu=e=>`/source/${e}`,Su=e=>e===`/source`||!!e?.startsWith(`/source/`),Cu=e=>bu(e)||Su(e),wu=async(e,t)=>{let n=t.split(`/`).filter(Boolean),r=n.pop();if(!r)throw Error(`hybrid storage: empty file path`);let i=e;for(let e of n)i=await i.getDirectoryHandle(e);return(await i.getFileHandle(r)).getFile()},Tu=(e,t,n=()=>null,r=e)=>{let i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set,s=t=>o.has(t)?r:e,c=t=>iu(t)?r:e,l=e=>{let n=t();if(!n)throw Error(`hybrid storage: no folder granted, cannot ${e}`);return n},u=async(e,t)=>{if(!e.handles)throw Error(`hybrid storage: ${e.savePath} has no source handles registered`);if(e.handles.length!==e.files.length)throw Error(`hybrid storage: ${e.savePath} has ${e.handles.length} handles for ${e.files.length} files`);if(t<0||t>=e.handles.length)throw Error(`hybrid storage: no source handle ${t} in ${e.savePath}`);let n=e.handles[t];return n?vu(n):null};return{usageOf:async(e,t)=>Cu(e)?0:c(e).usageOf(e,t),refusedFile:e=>c(e).refusedFile(e),onNewStorage:(e,t,r)=>{if(Su(t)){a.set(e,{savePath:t,files:r,handles:n(t)});return}if(iu(t)?o.add(e):o.delete(e),!bu(t))return s(e).onNewStorage(e,t,r);i.set(e,{savePath:t,files:r})},onRemoveStorage:e=>{if(!a.delete(e)&&!i.delete(e))return s(e).onRemoveStorage(e)},read:(e,t,n,r)=>{let o=a.get(e);if(o)return(async()=>{let e=await u(o,t);if(!e)return new Uint8Array(r);let i=await e.slice(n,n+r).arrayBuffer();if(i.byteLength<r)throw Error(`hybrid storage: source file ${t} of ${o.savePath} ended early, wanted ${r} at ${n}, got ${i.byteLength}`);return new Uint8Array(i)})();let c=i.get(e);if(!c)return s(e).read(e,t,n,r);let d=c.files[t];if(!d)throw Error(`hybrid storage: no file ${t} in ${c.savePath}`);return(async()=>{let e=await(await wu(l(`read`),d.path)).slice(n,n+r).arrayBuffer();if(e.byteLength<r)throw Error(`hybrid storage: ${d.path} ended early, wanted ${r} at ${n}, got ${e.byteLength}`);return new Uint8Array(e)})()},write:(e,t,n,r)=>{let o=a.get(e);if(o)throw Error(`hybrid storage: ${o.savePath} is somebody's own files, refusing a write of ${r.length} at ${n} in file ${t}`);let c=i.get(e);if(!c)return s(e).write(e,t,n,r);throw Error(`hybrid storage: ${c.savePath} is read only, refusing a write of ${r.length} at ${n} in file ${t}`)},check:async e=>{if(a.get(e))return 2;let t=i.get(e);if(!t)return s(e).check(e);try{let e=l(`check`);for(let n of t.files){let t=await wu(e,n.path).catch(()=>null);if(t&&t.size>0)return 2}return 0}catch{return 2}},deleteFiles:async(e,t)=>{if(!a.has(e)&&!i.get(e))return s(e).deleteFiles(e,t)},release:async e=>{!i.has(e)&&!a.has(e)&&await s(e).release(e)},stop:async e=>{!i.has(e)&&!a.has(e)&&await s(e).stop(e)}}},Eu=(e,t,n)=>[Math.max(0,Math.floor(e.offset/t)),Math.min(n-1,Math.floor((e.offset+Math.max(0,e.size-1))/t))],Du=({files:e,pieceLength:t,numPieces:n,wanted:r,firstLast:i,windowBytes:a=4194304})=>{let o=r===void 0,s=new Set(r??[]),c=e=>o||s.has(e),l=new Uint8Array(n).fill(o?W.normal:W.skip);if(!o)for(let[r,i]of e.entries()){if(!c(r)||i.size<=0)continue;let[e,a]=Eu(i,t,n);for(let t=e;t<=a;t++)l[t]=W.normal}if(i){let r=Math.max(1,Math.ceil(a/t));for(let[i,a]of e.entries()){if(!c(i)||a.size<=0)continue;let[e,o]=Eu(a,t,n);for(let t=0;t<r;t++){let n=e+t,r=o-t;n<=o&&(l[n]=W.top),r>=e&&(l[r]=W.top)}}}return l},Ou=({wanted:e,firstLast:t})=>e===void 0&&!t,ku=e=>Su(e)?`source`:bu(e)?`folder`:`browser`,Au=(e,t)=>{if(e===`source`){if(!t)throw Error(`a source-backed torrent needs its infohash to name its save path`);return xu(t)}return e===`folder`?t?yu(t):`/dl`:nu(t)},ju=`ripple:rate-limits`,Mu=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,Nu=e=>{let t=e??{};return{down:Mu(t.down)?t.down:0,up:Mu(t.up)?t.up:0}},Pu=/* @__PURE__ */ new Set(/* @__PURE__ */ `add-magnet.add-torrent-file.create-source.reserve-storage.start-source.read.cancel-read.remove.relocate.set-location.set-folder.set-plan.remove-missing.watch.unwatch.unwatch-owner.pause.resume.recheck.import-list.clear-list.start.retry.retry-now.flush-resume.inspect.set-flags.reannounce.queue-move.set-limits.set-session-limits.set-temporary.export-start.export-chunk.export-end.import-start.import`.split(`.`)),Fu=e=>`ripple:source:`+e;let K=null,Iu=null;const Lu=rl(el);let Ru=null;const zu=/* @__PURE__ */ new Map;let Bu=!1;const q=[],Vu=/* @__PURE__ */ new Map,J=/* @__PURE__ */ new Map,Hu=/* @__PURE__ */ new Map,Uu=/* @__PURE__ */ new Map,Y=/* @__PURE__ */ new Set,Wu=/* @__PURE__ */ new Set,Gu=/* @__PURE__ */ new Set,Ku=e=>{Gu.delete(e),Wu.add(e)},qu=e=>{Wu.delete(e),Gu.add(e)},Ju=/* @__PURE__ */ new Map,X=ll(),Yu=e=>e>=4294967040,Z=(e,t)=>self.postMessage(e,t??[]),Xu=()=>q.map(e=>{let t=K.bitfield(e);return{handle:e,magnet:Vu.get(e)??``,files:K.files(e),status:K.status(e),bitfield:t?{numPieces:t.numPieces,pieceLength:t.pieceLength,length:t.length,pieces:t.pieces}:null,recovery:X.state(e),userPaused:Y.has(e),windowed:Xd.has(e),swarmDownloads:Math.max(-1,...K?.lastTrackers(e).map(e=>e.downloaded)??[]),uptime:Zu(e),sessionUptime:Qu(e),totals:Md(e)}}),Zu=e=>{let t=K?.status(e),n=Ed.get(e);return!t||!n?Dd.get(e)??ml:yl(Dd.get(e),n,t)},Qu=e=>{let t=K?.status(e),n=Ed.get(e);return t&&n?vl(n,t):ml},$u=async()=>await uc(`ripple:torrents`)??[],ed=async e=>{let t=[];await fc(lu,n=>{t=n??[];let r=t.findIndex(t=>t.infoHash===e.infoHash),i=su(r>=0?t[r]:null,e);return r>=0?t[r]=i:t.push(i),t}),Z({type:`list`,list:t})},Q=async(e,t,n=!1)=>{let r=[];await fc(lu,n=>{r=n??[];let i=r.findIndex(t=>t.infoHash===e);return i>=0&&(r[i]={...r[i],...t}),r}),n||Z({type:`list`,list:r})},td=e=>{let t=J.get(e);t&&Q(t,{lastUsedAt:Date.now()},!0).catch(()=>{})},nd=async e=>{await pc(mu(e)).catch(()=>{}),await pc(hu(e)).catch(()=>{}),await pc(Fu(e)).catch(()=>{}),await pc(gu(e)).catch(()=>{})},rd=async e=>{let t=[];await fc(lu,n=>t=(n??[]).filter(t=>t.infoHash!==e)),await fc(uu,t=>du(t,[{infoHash:e,removedAt:Date.now()}])),await nd(e),Z({type:`list`,list:t})},id=/* @__PURE__ */ new Set,ad=/* @__PURE__ */ new Set,od=/* @__PURE__ */ new Map,sd=/* @__PURE__ */ new Set;let cd=null,ld=0;const ud=5e3;let dd=0,fd=0,pd=fl;const md=e=>{let t=cd;return t==null||!q.includes(t)?null:(K.peers(t),e-ld>=ud&&(ld=e,K.trackers(t)),{handle:t,peers:K.lastPeers(t),trackers:K.lastTrackers(t)})},hd=e=>{let t=K?.files(e);if(!t)return[];let n=t.files.map(e=>e.path.split(`/`).filter(Boolean)[0]).filter(Boolean);return[...new Set(n)]},gd=(e,t,n,r,i=!1)=>{q.includes(e)||q.push(e),Vu.set(e,t),n&&(J.set(e,n),sd.add(e)),Hu.set(e,r),i?id.add(e):id.delete(e)},_d=e=>{let t=q.indexOf(e);t>=0&&q.splice(t,1),Vu.delete(e),J.delete(e),Hu.delete(e),Uu.delete(e),Y.delete(e),X.forget(e),Hd.delete(e),Bd.delete(e),Wu.delete(e),Gu.delete(e),Ju.delete(e),$.delete(e),Jd.delete(e),Yd.delete(e),yd.delete(e),bd.delete(e),Sd.delete(e),Cd.delete(e),wd.delete(e),Ed.delete(e),Dd.delete(e),Od.delete(e),kd.delete(e),id.delete(e),ad.delete(e),od.delete(e),sd.delete(e),Xd.delete(e),Zd.delete(e),Qd.delete(e),mf.delete(e),hf.delete(e),uf.delete(e)},vd=e=>{ad.delete(e)&&(qu(e),K?.resumeTorrent(e),X.hold(e,Date.now()))},yd=/* @__PURE__ */ new Set,bd=/* @__PURE__ */ new Map;let xd={down:0,up:0};const Sd=/* @__PURE__ */ new Map,Cd=/* @__PURE__ */ new Set,wd=/* @__PURE__ */ new Map;let Td=0;const Ed=/* @__PURE__ */ new Map,Dd=/* @__PURE__ */ new Map,Od=/* @__PURE__ */ new Map,kd=/* @__PURE__ */ new Map,Ad=e=>({activeSeconds:e.activeSeconds,seedingSeconds:e.seedingSeconds,downloaded:e.allTimeDownload,uploaded:e.allTimeUpload,wasted:e.wasted}),jd=e=>({activeSeconds:e?.activeSeconds??0,seedingSeconds:e?.seedingSeconds??0,downloaded:e?.downloaded??0,uploaded:e?.uploaded??0,wasted:e?.wasted??0}),Md=e=>{let t=K?.status(e),n=Od.get(e);return!t||!n?kd.get(e)??gl:xl(kd.get(e),n,Ad(t))},Nd=(e,t,n)=>{let r=wd.get(e);wd.set(e,r?{flags:r.flags&~n|t&n,mask:r.mask|n}:{flags:t&n,mask:n})},Pd=(e,t)=>{let n={...Sd.get(e)};return Mu(t.down)&&(n.down=t.down),Mu(t.up)&&(n.up=t.up),!Mu(n.down)&&!Mu(n.up)?!1:(Sd.set(e,n),Cd.add(e),!0)},Fd=e=>{let t=Sd.get(e)?.down;return Qd.has(e)?Math.min(t||16384,16384):t},Id=e=>{let t=Sd.get(e);if(!K||!t)return;let n=Fd(e);Mu(n)&&K.setDownloadLimit(e,n),Mu(t.up)&&K.setUploadLimit(e,t.up)},Ld=6e3,Rd=G.formatMessage({id:`torrent removed`,defaultMessage:`torrent removed`}),zd=G.formatMessage({id:`torrent paused`,defaultMessage:`torrent paused`}),Bd=/* @__PURE__ */ new Map,Vd=(e,t)=>{let n=Bd.get(e);if(n?.size){for(let e of n.keys())Z({type:`read-error`,id:e,error:t});n.clear()}},Hd=/* @__PURE__ */ new Set,Ud=async e=>{let t=J.get(e);if(!t||!K||Hd.has(e)||Su(Hu.get(e)))return!1;let n=K.status(e);if(n&&sl.has(n.state))return!1;Hd.add(e);try{let n=await K.saveResumeData(e);return q.includes(e)?(await dc(mu(t),n),!0):!1}catch(e){return console.error(`[worker] saving resume data failed`,String(e)),!1}finally{Hd.delete(e)}},Wd=(e,t)=>{let n=K?.files(e),r=n?.files[t];if(!n||!r||r.size<=0)return null;let i=Math.floor(r.offset/n.pieceLength),a=Math.floor((r.offset+r.size-1)/n.pieceLength);return{file:r,pieceLength:n.pieceLength,p0:i,p1:a}},$=/* @__PURE__ */ new Map;let Gd=!1;const Kd=()=>[...$].every(([e,t])=>[...t.values()].every(t=>t.held||t.bulk||t.prepare||Cf(e,t.fileIndex,t.fromOffset,1/0))),qd=()=>[...$].filter(([,e])=>[...e.values()].some(e=>e.prepare)).map(([e])=>e),Jd=/* @__PURE__ */ new Set,Yd=/* @__PURE__ */ new Set,Xd=/* @__PURE__ */ new Map,Zd=/* @__PURE__ */ new Map,Qd=/* @__PURE__ */ new Set;let $d;const ef=`ripple:ceiling-fixed`;let tf,nf=null;const rf=(e,t,n)=>[...vf(e).filter(e=>e.fileIndex===t).map(e=>jl(n,e.fromOffset,e.fromOffset+Hc(n.pieceLength))),...[...Bd.get(e)?.values()??[]].filter(e=>e.fileIndex===t).map(e=>jl(n,e.offset,e.offset+e.len))],af=(e,t,n)=>{let r=Zd.get(e),[i]=n;if(r===void 0||!i||!$d?.fixed||!id.has(e)||n.some(e=>e.fileIndex!==i.fileIndex))return null;let a=t.files[i.fileIndex],o=Hu.get(e);if(!a||o===void 0)return null;let s={offset:a.offset,size:a.size,pieceLength:t.pieceLength},c=Lu.chunkBytesOf(o),l=Lu.chunksOf(o,i.fileIndex),u=Il({file:s,chunkBytes:c,room:r,reader:i.fromOffset,held:l,pinned:rf(e,i.fileIndex,s)});return u&&{...u,fileIndex:i.fileIndex,file:s,chunkBytes:c}},of=(e,t)=>e.fileIndex===t.fileIndex&&JSON.stringify(e.want)===JSON.stringify(t.want),sf=(e,t)=>{let n=K?.bitfield(e);if(!n)return!1;for(let e=t.start;e<t.end;e++)if(!((n.pieces[e>>3]??0)&128>>(e&7)))return!1;return!0},cf=()=>nf?nf.space.limitBytes-nf.space.usedBytes-(Lu.footprint()-nf.footprint)-wl:1/0,lf=3e4,uf=/* @__PURE__ */ new Map,df=e=>(uf.get(e)?.until??0)>Date.now(),ff=e=>{let t=Xd.get(e),n=!!t&&!Bd.get(e)?.size&&Ll(sf(e,t.ahead),cf(),t.chunkBytes);n!==Qd.has(e)&&(n?Qd.add(e):Qd.delete(e),K?.setDownloadLimit(e,Fd(e)??0))},pf=e=>{let t=Xd.get(e),n=K?.bitfield(e);if(!t||!n||t.slack.end<=t.slack.start||df(e))return;let r=[];for(let e=t.slack.start;e<t.slack.end;e++)(n.pieces[e>>3]??0)&128>>(e&7)&&r.push(e);r.length&&t.slack.end-t.slack.start-r.length<2&&K?.forgetPieces(e,r)},mf=/* @__PURE__ */ new Set,hf=/* @__PURE__ */ new Set,gf=async e=>{if(mf.has(e)){hf.add(e);return}mf.add(e);let t=!1;try{if(df(e)){t=!0;return}let n=Hu.get(e),r=()=>{let t=Xd.get(e);if(!t||n===void 0)return[];let r=/* @__PURE__ */ new Set([...t.keep,...Nl(t.file,t.chunkBytes,rf(e,t.fileIndex,t.file))]);return Lu.chunksOf(n,t.fileIndex).filter(e=>!r.has(e)).map(e=>({chunk:e,fileIndex:t.fileIndex,pieces:Ml(t.file,t.chunkBytes,e)}))},i=({start:t,end:n})=>K?.forgetPieces(e,Array.from({length:n-t},(e,n)=>t+n))??null,a=r().filter(({pieces:n})=>{let r=i(n);if(r?.busy){for(let t=n.start;t<n.end;t++)K?.cancelPieceRequests(e,t);t=!0}return r?.busy===0});if(!a.length||n===void 0)return;if(!await Ud(e)){t=!0;return}let o=new Set(r().map(({chunk:e})=>e)),s=[];for(let{chunk:e,fileIndex:t,pieces:r}of a){if(!o.has(e))continue;let a=i(r);!a||a.forgotten||a.busy||s.push(Lu.drop(n,t,e))}await Promise.all(s)}catch(e){console.error(`[worker] dropping chunks failed`,String(e))}finally{mf.delete(e),hf.delete(e)?gf(e):t&&Xd.has(e)&&setTimeout(()=>void gf(e),1e3)}},_f=e=>{let t=bd.get(e);if(!K||!t||Ou(t))return;let n=K.files(e);n&&K.prioritizePieces(e,Du({files:n.files,pieceLength:n.pieceLength,numPieces:Math.ceil(n.totalSize/n.pieceLength),wanted:t.wanted,firstLast:t.firstLast}))},vf=e=>{let t=$.get(e);return t?[...t.values()].filter(e=>!e.held&&(!e.prepare||Gd)):[]},yf=e=>{if(!K)return;if(!q.includes(e)){$.delete(e),Yd.delete(e);return}let t=vf(e);if(!t.length){if(!K.files(e)){Yd.add(e);return}Yd.delete(e),Xd.delete(e),ff(e),K.clearStreamWindow(e),_f(e),id.has(e)&&Hu.get(e)!==_u&&!Y.has(e)&&!ad.has(e)&&(ad.add(e),Ku(e),K.pauseTorrent(e),Ud(e));return}vd(e);let n=K.files(e);if(!n){Yd.add(e);return}Jd.delete(e)&&Kf();let r=t.flatMap(({fileIndex:e,fromOffset:t,bulk:r,prepare:i})=>{let a={fileIndex:e,offset:t},o=n.files[e];return i?o?.size?[a,{fileIndex:e,offset:Math.max(0,o.size-Bc)}]:[]:!r&&o?.size?[a,{fileIndex:e,offset:o.size-1}]:[a]}),i=t.filter(e=>!e.prepare),a=i.some(e=>!e.bulk),o=af(e,n,i);o?Xd.set(e,o):Xd.delete(e);let s=o?.want??(i.length<t.length?i.map(({fileIndex:e})=>n.files[e]).flatMap(e=>e?.size?[jl({...e,pieceLength:n.pieceLength},0,e.size)]:[]):void 0);K.setStreamWindow(e,r,{unclaimedPriority:W.skip,windowPieces:Vc(n.pieceLength),deadlineStepMs:Wc(n.pieceLength,K.status(e)?.downloadRate||3e6),deadlines:a,...s?{keep:s}:{}})?Yd.delete(e):Yd.add(e),o&&gf(e),pf(e),ff(e)},bf=e=>{let t=K?.files(e),n=vf(e).filter(e=>!e.prepare);if(!t||!n.length)return;let r=af(e,t,n),i=Xd.get(e);if(r||i){if(!r||!i||!of(r,i)){yf(e);return}Xd.set(e,r),gf(e)}},xf=(e,t,n,r,i=!1,a,o=!1)=>{if(!q.includes(t))return;let s=$.get(t),c=!s?.size;s||$.set(t,s=/* @__PURE__ */ new Map);let l=a??s.get(e)?.bulk;s.set(e,{fileIndex:n,fromOffset:r,...i?{held:i}:{},...l?{bulk:l}:{},...o?{prepare:o}:{}}),c&&(td(t),Jd.add(t)),o&&(Gd=Kd()),yf(t)},Sf=e=>{for(let[t,n]of $){let r=!1;for(let t of[...n.keys()])e(t)&&(n.delete(t),r=!0);n.size||($.delete(t),r&&td(t)),r&&yf(t)}},Cf=(e,t,n,r)=>{let i=K?.files(e),a=i?.files[t],o=K?.bitfield(e);if(!i||!a||!o)return!1;let s=Math.floor((a.offset+n)/i.pieceLength),c=Math.floor((a.offset+Math.min(n+r,a.size)-1)/i.pieceLength);for(let e=s;e<=c;e++)if(!((o.pieces[e>>3]??0)&128>>(e&7)))return!1;return!0},wf=(e,t,n,r)=>{let i=K?.files(e),a=i?.files[t],o=K?.bitfield(e);if(!i||!a||!o)return[];let s=Math.floor((a.offset+n)/i.pieceLength),c=Math.floor((a.offset+Math.min(n+r,a.size)-1)/i.pieceLength),l=[];for(let e=s;e<=c;e++)(o.pieces[e>>3]??0)&128>>(e&7)||l.push(e);return l},Tf=(e,t,n)=>{let r=Math.max(0,e-Bc-t),i=n?Math.floor(r/n)*n:0;return Math.min(e,Hc(t)+e-i)},Ef=async(e,t={evictable:[],graced:[]})=>{let n=e=>Math.max(0,e.size-e.held),r=[],i=[];for(let[e,t]of[...$]){let n=Iu,a=K?.files(e),o=Hu.get(e);if(!n||!a||!t.size||o===void 0||Cu(o))continue;let s=new Set([...t.values()].filter(e=>!e.prepare).map(e=>e.fileIndex)),c=Lu.chunkBytesOf(o),l=async r=>{let i=a.files[r]?.size??0,l=!s.has(r)&&[...t.values()].some(e=>e.prepare&&e.fileIndex===r);return{h:e,size:l?Tf(i,a.pieceLength,iu(o)?c:void 0):i,held:await n.usageOf(o,r)??0}},u=vf(e).find(e=>!e.prepare),d=!!$d?.fixed&&id.has(e)&&iu(o);for(let e of new Set([...t.values()].map(e=>e.fileIndex)))r.push({...await l(e),cache:d&&e===u?.fileIndex,chunkBytes:c});let f=n.refusedFile(o);f!==void 0&&i.push(await l(f))}let a=r.filter(e=>!e.cache).reduce((e,t)=>e+n(t),0),o=r.filter(e=>e.cache),s=e=>e.reduce((e,t)=>e+t.bytesOnDisk,0),c=e.limitBytes-e.usedBytes+o.reduce((e,t)=>e+t.held,0)+s(t.evictable)-a-wl,l=e=>{let t=Pl(o.map(e=>e.size),c+e),r=new Set(o.filter((e,n)=>Fl(e.size,t[n]??0,e.chunkBytes)).map(e=>e.h));return{shares:t,windowed:r,owed:o.reduce((e,i,a)=>e+(r.has(i.h)?Math.max(0,(t[a]??0)-i.held):n(i)),a)}},u=l(0),d=l(s(t.graced)),f=i.filter(e=>!d.windowed.has(e.h)).reduce((e,t)=>e+n(t),0),p=new Map(o.map((e,t)=>[e.h,u.shares[t]??0]));return{pendingBytes:u.owed,laterBytes:d.owed,refusedBytes:f,rooms:p}},Df=(e,t,n,r,i)=>{if(!e||!q.includes(t))return;let a=$.get(t)?.get(e);if(!a||a.held||a.fileIndex!==n){xf(e,t,n,r);return}let o=Wd(t,n);if(!o)return;let s={fileOffset:o.file.offset,pieceLength:o.pieceLength,p1:o.p1};Gc(s,a.fromOffset,r,i)&&xf(e,t,n,r)},Of=async e=>{let t=e.filter(e=>!Cu(e));if(!t.length)return!0;try{let e=await navigator.storage.getDirectory();for(let n of new Set(t)){let t=e;for(let e of n.split(`/`).filter(Boolean))t=t?await t.getDirectoryHandle(e).catch(()=>null):null;if(t)return!0}return!1}catch{return!0}},kf=async()=>{let e,t;try{return e=await navigator.storage.getDirectory(),t=`.ripple-probe-${crypto.randomUUID()}`,(await(await e.getFileHandle(t,{create:!0})).createSyncAccessHandle()).close(),await e.removeEntry(t).catch(()=>{}),!0}catch{return e&&t&&await e.removeEntry(t).catch(()=>{}),!1}},Af=e=>({paused:e.paused,state:e.state,totalDone:e.totalDone,downloadRate:e.downloadRate,numPeers:e.numPeers,queued:e.paused&&e.autoManaged&&!e.errorCode,error:e.error}),jf=async()=>{try{let{usage:e,quota:t}=await Jl.estimate();return!t||e===void 0?null:{usedBytes:e,limitBytes:t}}catch{return null}},Mf=async()=>{try{let{usage:e,quota:t}=await navigator.storage.estimate();return t&&e!==void 0?t-e:null}catch{return null}},Nf=async e=>{for(let t=0;t<4e3;t+=250){await new Promise(e=>setTimeout(e,250));let t=await jf();if(!t||t.usedBytes<e)return t}return jf()},Pf=async(e,t,n,r,i={})=>{Vd(t,r),e.removeTorrent(t,!0),_d(t),await pc(mu(n)).catch(()=>{}),await Q(n,{started:!1,paused:!1,...i})},Ff=(e,t,n)=>Pf(e,t,n,G.formatMessage({id:`torrent removed to make room`,defaultMessage:`torrent removed to make room`})),If=async(e,t,n,r)=>{let i=ku(Hu.get(t));if(i===r)return;let a=Vu.get(t)??``,o=Au(r,n),s=Y.has(t),c=id.has(t);Vd(t,G.formatMessage({id:`files moved`,defaultMessage:`files moved`})),e.removeTorrent(t,i===`browser`),_d(t),await pc(mu(n)).catch(()=>{});let l=e.addMagnet(a,o);if(Yu(l)){Z({type:`add-failed`,message:G.formatMessage({id:`Moving the files left the torrent unaddable`,defaultMessage:`Moving the files left the torrent unaddable`})}),await Q(n,{savePath:o,saveTo:r,started:!1});return}gd(l,a,n,o,c),r===`folder`&&Nd(l,Ec.uploadMode,Ec.uploadMode),s?(Y.add(l),Ku(l)):qu(l),X.hold(l,Date.now()),await Q(n,{savePath:o,saveTo:r,started:!0})},Lf=(e,{infoHash:t,magnet:n,bytes:r,handles:i,paused:a})=>{let o=xu(t);zu.set(o,i);let s=e.addTorrentFile(r,o);return Yu(s)?(zu.delete(o),null):(gd(s,n,t,o,!1),Nd(s,Ec.uploadMode,Ec.uploadMode),a&&(Y.add(s),Ku(s)),X.hold(s,Date.now()),s)},Rf=async(e,t)=>{let n=new Map(e.map(e=>[e.infoHash,e])),r=[],i=[];for(let e of[...q]){let a=J.get(e);if(!a)continue;let o=n.get(a);if(!o?.ephemeral||!au(o.savePath,a)||$.get(e)?.size||Bd.get(e)?.size)continue;let s=o.lastUsedAt??o.addedAt,c=await Iu?.usageOf(o.savePath)??0;if(c<=0)continue;let l=t-(od.get(e)??0)<6e4||t-s<15e3,u={infoHash:a,usedAt:s,bytesOnDisk:c};l?i.push(u):r.push(u)}return{evictable:r,graced:i}};let zf=!1;const Bf=e=>{let t=Dl(e);t!==zf&&(zf=t,Z({type:`storage-full`,full:t,usedBytes:e.usedBytes,limitBytes:e.limitBytes}))},Vf=/* @__PURE__ */ new Set;let Hf=!1;const Uf=async()=>{if(!K||Hf)return 0;Hf=!0;try{let e=await $u(),t=new Set(e.map(e=>e.infoHash.toLowerCase()));for(let e of Vf)t.add(e.toLowerCase());let n=/* @__PURE__ */ new Set,r=!0;for(let e of q){let i=J.get(e);if(i&&t.add(i.toLowerCase()),(Hu.get(e)??`/dl`)!==`/dl`)continue;let a=hd(e);if(!a.length){r=!1;continue}for(let e of a)n.add(e)}for(let t of e){let e=t.savePath||`/dl`;if(!iu(e)){if(e!==`/dl`&&!e.startsWith(`/dl/`)){r=!1;continue}if(e===`/dl`){if(t.rootEntry){n.add(t.rootEntry);continue}!q.some(e=>J.get(e)===t.infoHash)&&t.started!==!1&&(r=!1)}}}let i=await navigator.storage.getDirectory(),a=[...await $l(i,`/dl`,{listedHashes:t,claimedNames:n,attributable:r}),...await $l(i,`/cache`,{listedHashes:t,claimedNames:/* @__PURE__ */ new Set,attributable:!1})];return await eu(i).catch(()=>0),a.length&&console.log(`[worker] removed storage nothing owns`,a),a.length}catch(e){return console.error(`[worker] orphan sweep failed`,String(e)),0}finally{Hf=!1}};let Wf=!1,Gf=!1;const Kf=async()=>{let e=K;if(!e)return;if(Wf){Gf=!0;return}Wf=!0;let t=null,n={pendingBytes:0,laterBytes:0,refusedBytes:0,rooms:/* @__PURE__ */ new Map},r=[],i=[],a=e=>({...e,pendingBytes:$d?.fixed===!1?0:n.laterBytes,refusedBytes:n.refusedBytes,candidates:[...r,...i]});try{let o=await jf();if(!o)return;t=o,tf===void 0&&(tf=await uc(ef).catch(()=>null)??null);let s=async e=>{nf={space:e,footprint:Lu.footprint()};let t=await Mf();if(t===null)return;let n={usedBytes:e.usedBytes,headroomBytes:t};$d=Rl($d??(typeof tf==`boolean`?{...n,fixed:tf}:void 0),n,el),$d.fixed!==void 0&&$d.fixed!==tf&&(tf=$d.fixed,dc(ef,tf).catch(()=>{}))};await s(o),n=await Ef(o);let c=await Rf(await $u(),Date.now());r=c.evictable,i=c.graced,n=await Ef(o,c);let l=!1;for(;r.length;){let[a]=kl({...o,pendingBytes:n.pendingBytes,candidates:r});if(!a)break;r=r.filter(e=>e.infoHash!==a);let c=q.find(e=>J.get(e)===a);if(c===void 0||$.get(c)?.size||Bd.get(c)?.size)continue;let u=o.usedBytes;t=null,await Ff(e,c,a),l=!0;let d=await Nf(u);if(!d)return;o=d,t=d,await s(d),n=await Ef(o,{evictable:r,graced:i})}if(l)for(let e of $.keys())X.retry(e,Date.now());Zd.clear();for(let[e,t]of n.rooms)Zd.set(e,t);for(let e of/* @__PURE__ */ new Set([...Zd.keys(),...Xd.keys()]))bf(e);Dl(a(o))&&await Uf()&&(o=await Nf(o.usedBytes)??o),t=o}catch(e){console.error(`[worker] storage budget pass failed`,String(e))}finally{Wf=!1,t&&Bf(a(t)),Gf&&(Gf=!1,Kf())}},qf=async()=>{let e=console.error.bind(console);if(console.error=(...t)=>{e(...t);try{Z({type:`worker-error`,args:t.map(String)})}catch{}},!await kf()){Z({type:`storage-unavailable`});return}$u().then(e=>{e.length&&Z({type:`list`,list:e})}).catch(()=>{});let t=Promise.race([uc(ju).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]);Iu=Tu($c(),()=>Ru,e=>zu.get(e)??null,Lu),K=await Rc({net:Ys,dgram:ac,storage:Iu,utpReceiveBufferBytes:4194304});for(let e=0;e<30;e++)K.tick();xd=Nu(await t),K.setRateLimits({download:xd.down,upload:xd.up});try{let e=await $u(),t=!await Of(e.map(e=>e.savePath||`/dl`)),n=!1;for(let r of e){if(r.started===!1||r.saveTo===`source`)continue;let e=r.savePath||`/dl`,i=await uc(mu(r.infoHash)),a=await uc(hu(r.infoHash));if(t&&i&&i.byteLength){await pc(mu(r.infoHash)).catch(()=>{}),r.started=!1,n=!0;continue}let o=i&&i.byteLength?K.addTorrentWithResume(i,e):a&&a.byteLength?K.addTorrentFile(a,e):K.addMagnet(r.magnet,e);Yu(o)||(gd(o,r.magnet,r.infoHash,e,r.ephemeral===!0),bd.set(o,{wanted:r.wantedFiles,firstLast:r.firstLast}),yd.add(o),Pd(o,{down:r.downloadLimit??0,up:r.uploadLimit}),Dd.set(o,{activeSeconds:r.activeSeconds??0,seedingSeconds:r.seedingSeconds??0}),kd.set(o,jd(r)),r.paused?(Y.add(o),Ku(o)):qu(o),X.hold(o,Date.now()))}n&&await dc(lu,e)}catch(e){console.error(`[worker] restore failed`,e)}Z({type:`ready`}),Bu=!0,Z({type:`list`,list:await $u().catch(()=>[])}),Z({type:`state`,torrents:Xu(),reachable:K.reachable(),inboundNow:pd,rateLimits:{...xd}}),setInterval(()=>{if(!K)return;let e=Date.now();K.popAlerts();for(let e of q)K.postStatus(e);for(let e of[...yd])K.files(e)&&(yd.delete(e),vf(e).length||yf(e));for(let e of[...Yd])yf(e);let t=qd();if(t.length&&Kd()!==Gd){Gd=!Gd;for(let e of t)yf(e)}for(let e of[...Xd.keys()])pf(e),ff(e);for(let e of[...Cd])K.status(e)&&(Cd.delete(e),Id(e));for(let e of q){if(Ed.has(e))continue;let t=K.status(e);t&&(Ed.set(e,{activeSeconds:t.activeSeconds,seedingSeconds:t.seedingSeconds}),Od.set(e,Ad(t)))}for(let[e,t]of[...wd])K.status(e)&&(wd.delete(e),K.setFlags(e,t.flags>>>0,t.mask>>>0));for(let e of[...sd]){let[t]=hd(e);if(!t)continue;sd.delete(e);let n=J.get(e);if(!n)continue;let r=K.files(e);Q(n,{rootEntry:t,name:t,size:r?.contentSize,files:r?.files.filter(e=>!e.pad).slice(0,100).map(e=>({name:e.path,size:e.size}))}).catch(()=>{})}for(let e of Wu){let t=K.status(e);t&&!sl.has(t.state)&&(cl(t)?Wu.delete(e):K.pauseTorrent(e))}for(let e of Gu){if(Y.has(e)||ad.has(e)){Gu.delete(e);continue}let t=K.status(e);if(t&&!sl.has(t.state)){if(!t.paused){Gu.delete(e);continue}if(t.autoManaged||t.errorCode){Gu.delete(e);continue}K.resumeTorrent(e)}}X.retain(new Set(q));for(let t of q){let n=K.status(t);X.observe(t,n&&Af(n),Y.has(t)||ad.has(t),e)}for(let{handle:t,reason:n}of X.due(e))n===`stalled`&&K.pauseTorrent(t),K.resumeTorrent(t);if(e-fd>=2e3){fd=e;for(let e of q)K.peers(e)}if(pd=pl(q.map(e=>K.lastPeers(e))),$.size&&e-dd>=ud){dd=e;for(let e of $.keys())K.trackers(e)}Z({type:`state`,torrents:Xu(),reachable:K.reachable(),inboundNow:pd,detail:md(e),rateLimits:{...xd}});for(let t of q){let n=K.status(t);if(!n||n.state!==4&&n.state!==5||Uu.get(t)===n.paused||Hd.has(t))continue;let r=Ju.get(t);if(r&&e<r.at)continue;let i=n.paused;Ud(t).then(e=>{if(e){Uu.set(t,i),Ju.delete(t);return}let n=(Ju.get(t)?.tries??0)+1;Ju.set(t,{tries:n,at:Date.now()+Math.min(1e3*2**n,6e4)})})}},500),setInterval(()=>{if(!K)return;for(let e of q){let t=K.status(e);t&&t.state===3&&Ud(e)}let e=!1;for(let t of q){let n=K.status(t),r=J.get(t),i=Ed.get(t);if(!n||!r||!i)continue;e=!0;let a=yl(Dd.get(t),i,n);if(!Cl(Dd.get(t),a))continue;Dd.set(t,a),Ed.set(t,{activeSeconds:n.activeSeconds,seedingSeconds:n.seedingSeconds});let o=Ad(n),s=xl(kd.get(t),Od.get(t)??o,o);kd.set(t,s),Od.set(t,o),Q(r,{activeSeconds:a.activeSeconds,seedingSeconds:a.seedingSeconds,downloaded:s.downloaded,uploaded:s.uploaded,wasted:s.wasted},!0).catch(()=>{})}e&&Date.now()-Td>=3e5&&(Td=Date.now(),$u().then(e=>Z({type:`list`,list:e})).catch(()=>{}))},15e3),setInterval(()=>{Kf()},1e4),Kf(),setTimeout(()=>{Uf(),setInterval(()=>{Uf()},6e5)},6e4),self.addEventListener(`online`,()=>X.retryNow(Date.now()))},Jf=async(e,t)=>{try{if(t.type===`add-magnet`){let n=zc(t.magnet),r=n?q.find(e=>J.get(e)===n):void 0;if(r!==void 0)n&&!t.ephemeral?(id.delete(r),vd(r),vf(r).length&&yf(r),await Q(n,{ephemeral:!1,lastUsedAt:Date.now()})):td(r),Z({type:`added`,handle:r,magnet:Vu.get(r)||t.magnet});else{let r=n?(await $u()).find(e=>e.infoHash===n):void 0,i=ou(r,t.ephemeral===!0),a=t.savePath||r?.savePath||(i&&n?ru(n):nu(n)),o=e.addMagnet(t.magnet,a);if(Yu(o)){Z({type:`add-failed`,message:G.formatMessage({id:`That is not a valid magnet link`,defaultMessage:`That is not a valid magnet link`})});return}gd(o,t.magnet,n,a,i),bd.set(o,{wanted:r?.wantedFiles,firstLast:r?.firstLast}),t.hold===!0&&yd.add(o),Pd(o,{down:r?.downloadLimit,up:r?.uploadLimit}),Dd.set(o,{activeSeconds:r?.activeSeconds??0,seedingSeconds:r?.seedingSeconds??0}),kd.set(o,jd(r)),X.hold(o,Date.now());let s=Date.now();n&&await ed({infoHash:n,magnet:t.magnet,savePath:a,addedAt:s,lastUsedAt:s,ephemeral:i,started:!0,paused:!1}),Z({type:`added`,handle:o,magnet:t.magnet}),Kf()}}else if(t.type===`create-source`){let n=t.infoHash,r=t.handles??[],i=t.bytes;if(typeof n!=`string`||!n||!r.length||!i?.byteLength){Z({type:`add-failed`,message:G.formatMessage({id:`That torrent could not be created`,defaultMessage:`That torrent could not be created`})});return}if(!r.some(e=>e)){Z({type:`add-failed`,message:G.formatMessage({id:`Some of those files could not be opened`,defaultMessage:`Some of those files could not be opened`})});return}await dc(hu(n),i);let a=Lf(e,{infoHash:n,magnet:t.magnet,bytes:i,handles:r,paused:!1});if(a===null){await pc(hu(n)).catch(()=>{}),Z({type:`add-failed`,message:G.formatMessage({id:`The engine refused the torrent that was just built`,defaultMessage:`The engine refused the torrent that was just built`})});return}let o=Date.now();await ed({infoHash:n,magnet:t.magnet,savePath:xu(n),addedAt:o,lastUsedAt:o,ephemeral:!1,started:t.reopenable!==!1,paused:!1,saveTo:`source`,format:t.format??`v1`,pieceLength:typeof t.pieceLength==`number`?t.pieceLength:void 0,...cu({name:t.name,size:t.size,files:t.files})}),Z({type:`added`,handle:a,magnet:t.magnet})}else if(t.type===`start-source`){let n=t.infoHash,r=t.handles??[];if(typeof n!=`string`||!n||!r.length)return;if(!r.some(e=>e)){Z({type:`add-failed`,message:G.formatMessage({id:`Some of those files could not be opened`,defaultMessage:`Some of those files could not be opened`})});return}let i=[...J.entries()].find(([,e])=>e===n);if(i){Z({type:`added`,handle:i[0],magnet:Vu.get(i[0])??``});return}let a=await uc(hu(n));if(!a?.byteLength){Z({type:`add-failed`,message:G.formatMessage({id:`The torrent this was built from is no longer stored`,defaultMessage:`The torrent this was built from is no longer stored`})});return}let o=(await $u()).find(e=>e.infoHash===n),s=Lf(e,{infoHash:n,magnet:o?.magnet??t.magnet??``,bytes:a,handles:r,paused:o?.paused===!0});if(s===null){Z({type:`add-failed`,message:G.formatMessage({id:`The engine refused that torrent`,defaultMessage:`The engine refused that torrent`})});return}Dd.set(s,{activeSeconds:o?.activeSeconds??0,seedingSeconds:o?.seedingSeconds??0}),kd.set(s,jd(o)),await Q(n,{started:!0,lastUsedAt:Date.now()}),Z({type:`added`,handle:s,magnet:o?.magnet??``})}else if(t.type===`add-torrent-file`){let n=t.savePath||`/dl`,r=t.bytes,i=e.addTorrentFile(r,n);if(Yu(i)){Z({type:`add-failed`,message:G.formatMessage({id:`That file is not a valid .torrent`,defaultMessage:`That file is not a valid .torrent`})});return}gd(i,``,null,n,t.ephemeral===!0),X.hold(i,Date.now());let a=null;for(let t=0;t<40&&!(a=e.infohash(i));t++)await new Promise(e=>setTimeout(e,250));if(!q.includes(i))return;if(!a){e.removeTorrent(i,!0),_d(i),Z({type:`add-failed`,message:G.formatMessage({id:`Could not read that torrent`,defaultMessage:`Could not read that torrent`})});return}let o=e.infohashV2(i),s=`magnet:?`+[...a.length===40?[`xt=urn:btih:${a}`]:[],...o?[`xt=urn:btmh:1220${o}`]:[]].join(`&`);gd(i,s,a,n),await dc(hu(a),r);let c=Date.now(),l=t.saveTo===`browser`||t.saveTo===`folder`?{saveTo:t.saveTo}:{};await ed({infoHash:a,magnet:s,savePath:n,addedAt:c,lastUsedAt:c,ephemeral:t.ephemeral===!0,started:!0,paused:!1,...l,...t.created===!0?{created:!0}:{}}),Vf.delete(a),Z({type:`added`,handle:i,magnet:s})}else if(t.type===`read`){if(!q.includes(t.handle)){Z({type:`read-error`,id:t.id,error:Rd});return}if(vd(t.handle),t.viewer||od.set(t.handle,Date.now()),Y.has(t.handle)&&!Cf(t.handle,t.fileIndex,t.offset,t.len)){Z({type:`read-error`,id:t.id,error:zd});return}if(t.prioritize!==!1)Df(t.viewer,t.handle,t.fileIndex,t.offset,t.len);else if(!Cf(t.handle,t.fileIndex,t.offset,t.len)){Z({type:`read-error`,id:t.id,error:`not downloaded`});return}let n=Bd.get(t.handle);n||Bd.set(t.handle,n=/* @__PURE__ */ new Map),n.set(t.id,{fileIndex:t.fileIndex,offset:t.offset,len:t.len});try{for(let r=0;;r++)try{let r=t.viewer?$.get(t.handle)?.get(t.viewer)?.bulk===!0:!1,i=await e.read(t.handle,t.fileIndex,t.offset,t.len,{timeoutMs:Ld,...r?{deadlineMs:null}:{}});if(!n.has(t.id))return;Z({type:`read-result`,id:t.id,data:i},[i.buffer]);return}catch(i){if(!n.has(t.id))return;if(r+1>=18||!/did not arrive/.test(String(i)))throw i;let a=wf(t.handle,t.fileIndex,t.offset,t.len);Z({type:`read-stalled`,id:t.id,handle:t.handle,fileIndex:t.fileIndex,offset:t.offset,len:t.len,waitedMs:(r+1)*Ld,missing:a,cancelled:Math.min(a.length,16),downloadRate:e.status(t.handle)?.downloadRate??null,numPeers:e.status(t.handle)?.numPeers??null});for(let n of a.slice(0,16))e.cancelPieceRequests(t.handle,n);let o=t.viewer?$.get(t.handle)?.get(t.viewer):void 0;t.prioritize!==!1&&t.viewer&&o&&!o.held&&yf(t.handle)}}finally{n.delete(t.id),!t.viewer&&q.includes(t.handle)&&od.set(t.handle,Date.now())}}else if(t.type===`cancel-read`)Bd.get(t.handle)?.delete(t.id);else if(t.type===`remove`){let n=J.get(t.handle);Vd(t.handle,Rd),e.removeTorrent(t.handle,!!t.deleteFiles),_d(t.handle),n&&await rd(n)}else if(t.type===`set-plan`){let e=Array.isArray(t.wanted)?t.wanted.map(e=>Number(e)|0):void 0,n=t.firstLast===!0;bd.set(t.handle,{wanted:e,firstLast:n}),_f(t.handle);let r=J.get(t.handle);r&&await Q(r,{wantedFiles:e,firstLast:n})}else if(t.type===`set-folder`)Ru=t.handle??null;else if(t.type===`set-temporary`){if(typeof t.infoHash==`string`){let e=t.temporary===!0,n=q.find(e=>J.get(e)===t.infoHash);n!==void 0&&(e?id.add(n):(id.delete(n),vd(n)),vf(n).length&&yf(n)),await Q(t.infoHash,{ephemeral:e})}}else if(t.type===`export-start`){let n=q.find(e=>J.get(e)===t.infoHash),r=n===void 0?void 0:Hu.get(n),i=n===void 0?null:e.files(n);if(n===void 0||!i||r===void 0||!iu(r)){Z({type:`answer`,id:t.id,value:null});return}uf.set(n,{running:(uf.get(n)?.running??0)+1,until:Date.now()+lf});let a=await e.saveResumeData(n),o=i.files.flatMap((e,t)=>e.pad?[]:Lu.chunksOf(r,t).map(e=>({fileIndex:t,chunk:e})));Z({type:`answer`,id:t.id,value:{magnet:Vu.get(n)??``,resume:a,chunkBytes:Lu.chunkBytesOf(r),chunks:o}})}else if(t.type===`export-chunk`){let e=q.find(e=>J.get(e)===t.infoHash),n=e===void 0?void 0:Hu.get(e),r=e===void 0?void 0:uf.get(e);if(!r||n===void 0)throw Error(`that torrent is not being handed over`);r.until=Date.now()+lf;let i=await Lu.readChunk(n,t.fileIndex,t.chunk);Z({type:`answer`,id:t.id,value:i},[i.buffer])}else if(t.type===`export-end`){let e=q.find(e=>J.get(e)===t.infoHash),n=e===void 0?void 0:uf.get(e);if(e===void 0||!n)return;--n.running,n.running||uf.delete(e)}else if(t.type===`import-start`){if(typeof t.infoHash!=`string`||typeof t.magnet!=`string`)throw Error(`nothing to list`);let e=Date.now();await ed({infoHash:t.infoHash,magnet:t.magnet,savePath:ru(t.infoHash),addedAt:e,lastUsedAt:e,ephemeral:!1,started:!0,paused:!1}),Z({type:`answer`,id:t.id,value:!0})}else if(t.type===`import`){let n=t.infoHash;if(typeof n!=`string`||!(t.resume instanceof Uint8Array)||q.some(e=>J.get(e)===n))return;let r=ru(n);await dc(mu(n),t.resume);let i=e.addTorrentWithResume(t.resume,r);if(Yu(i)){Z({type:`add-failed`,message:G.formatMessage({id:`That torrent could not be read`,defaultMessage:`That torrent could not be read`})});return}gd(i,t.magnet,n,r),yd.add(i),Pd(i,{down:0}),qu(i),X.hold(i,Date.now()),Z({type:`added`,handle:i,magnet:t.magnet})}else if(t.type===`reserve-storage`)typeof t.infoHash==`string`&&t.infoHash&&(t.on===!1?Vf.delete(t.infoHash):Vf.add(t.infoHash));else if(t.type===`set-location`)typeof t.infoHash==`string`&&await Q(t.infoHash,{saveTo:t.to===`folder`?`folder`:`browser`});else if(t.type===`relocate`){let n=typeof t.infoHash==`string`?t.infoHash:null,r=t.to===`folder`?`folder`:`browser`,i=n?q.find(e=>J.get(e)===n):void 0;n&&i!==void 0&&await If(e,i,n,r)}else if(t.type===`import-list`){let e=[];await fc(uu,n=>e=du(n,t.removed));let n=[],r=[],i=!1;await fc(lu,a=>{let o=pu(a??[],Array.isArray(t.list)?t.list:[],e);n=o.list,r=(a??[]).filter(e=>!n.includes(e)),i=r.length>0;let s=new Map(n.map(e=>[e.infoHash,e]));for(let e of o.incoming){if(!e||typeof e.infoHash!=`string`||!e.magnet)continue;let t=cu(e),r=s.get(e.infoHash);if(r){r.name===void 0&&t.name!==void 0&&(r.name=t.name,i=!0),r.size===void 0&&t.size!==void 0&&(r.size=t.size,i=!0),r.files===void 0&&t.files!==void 0&&(r.files=t.files,i=!0);let n=Sl(jd(r),jd(e));for(let e of hl)(r[e]??0)!==n[e]&&(r[e]=n[e],i=!0);continue}let a={infoHash:e.infoHash,magnet:e.magnet,savePath:e.savePath||`/dl`,addedAt:e.addedAt||Date.now(),started:!1,ephemeral:!1,...t,...jd(e)};n.push(a),s.set(a.infoHash,a),i=!0}return n});for(let e of r)await nd(e.infoHash);i&&Z({type:`list`,list:n})}else if(t.type===`start`){let n=(await $u()).find(e=>e.infoHash===t.infoHash);if(n?.saveTo===`source`){Z({type:`add-failed`,message:G.formatMessage({id:`Nothing to download this from. Create it again from the same files.`,defaultMessage:`Nothing to download this from. Create it again from the same files.`})});return}if(n){let t=n.savePath||`/dl`,r=await uc(hu(n.infoHash)),i=r&&r.byteLength?e.addTorrentFile(r,t):e.addMagnet(n.magnet,t);if(Yu(i)){Z({type:`add-failed`,message:G.formatMessage({id:`That torrent could not be read`,defaultMessage:`That torrent could not be read`})});return}gd(i,n.magnet,n.infoHash,t,!1),Pd(i,{down:n.downloadLimit,up:n.uploadLimit}),X.hold(i,Date.now()),Z({type:`state`,torrents:Xu(),reachable:e.reachable()}),await ed({...n,started:!0,paused:!1,ephemeral:!1,lastUsedAt:Date.now()})}}else if(t.type===`remove-missing`){if(typeof t.infoHash==`string`){let n=q.find(e=>J.get(e)===t.infoHash);n!==void 0&&(Vd(n,Rd),e.removeTorrent(n,!0),_d(n)),await rd(t.infoHash)}}else if(t.type===`clear-list`){for(let t of[...q])Vd(t,Rd),e.removeTorrent(t,!0),_d(t);let t=[];await fc(lu,e=>(t=e??[],[])),await pc(uu).catch(()=>{});for(let e of t)await pc(mu(e.infoHash)).catch(()=>{}),await pc(hu(e.infoHash)).catch(()=>{});Z({type:`list`,list:[]})}else if(t.type===`pause`){Y.add(t.handle),ad.delete(t.handle),Ku(t.handle),X.forget(t.handle),e.pauseTorrent(t.handle),Vd(t.handle,zd),Ud(t.handle);let n=J.get(t.handle);n&&await Q(n,{paused:!0})}else if(t.type===`resume`){Y.delete(t.handle),ad.delete(t.handle),qu(t.handle),X.forget(t.handle),e.resumeTorrent(t.handle),X.hold(t.handle,Date.now());let n=J.get(t.handle);n&&await Q(n,{paused:!1})}else if(t.type===`recheck`){let n=J.get(t.handle);n&&await pc(mu(n)).catch(()=>{}),Uu.delete(t.handle),Vd(t.handle,G.formatMessage({id:`torrent rechecking`,defaultMessage:`torrent rechecking`})),Y.delete(t.handle),Wu.delete(t.handle),Gu.delete(t.handle),ad.delete(t.handle),X.forget(t.handle),e.forceRecheck(t.handle),X.hold(t.handle,Date.now()),n&&await Q(n,{paused:!1})}else if(t.type===`retry-now`)X.retryNow(Date.now());else if(t.type===`retry`)X.retry(t.handle,Date.now());else if(t.type===`flush-resume`)await Promise.all(q.map(e=>Ud(e)));else if(t.type===`watch`)t.readLen==null?xf(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.held===!0,t.bulk===!0||void 0,t.prepare===!0):Df(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.readLen);else if(t.type===`unwatch`)Sf(e=>e===t.viewer);else if(t.type===`set-flags`)e.setFlags(t.handle,t.flags>>>0,t.mask>>>0),Ud(t.handle);else if(t.type===`reannounce`)e.forceReannounce(t.handle);else if(t.type===`queue-move`)e.moveInQueue(t.handle,t.where);else if(t.type===`set-limits`){let n=Mu(t.down)?t.down:void 0,r=Mu(t.up)?t.up:void 0;Pd(t.handle,{down:n,up:r})&&e.status(t.handle)&&(Cd.delete(t.handle),Id(t.handle));let i=J.get(t.handle);if(i){let e={};n!==void 0&&(e.downloadLimit=n),r!==void 0&&(e.uploadLimit=r),Object.keys(e).length&&await Q(i,e)}}else if(t.type===`set-session-limits`)Mu(t.down)&&(xd.down=t.down),Mu(t.up)&&(xd.up=t.up),e.setRateLimits({download:xd.down,upload:xd.up}),await dc(ju,{...xd});else if(t.type===`inspect`){let e=typeof t.handle==`number`?t.handle:null;e!==cd&&(cd=e,ld=0)}else t.type===`unwatch-owner`&&Sf(e=>e.startsWith(t.owner+`:`))}catch(e){t.type===`read`?Z({type:`read-error`,id:t.id,error:String(e?.stack??e)}):tu.has(t.type)?Z({type:`answer`,id:t.id,error:String(e?.message??e)}):Z({type:`error`,message:String(e?.stack??e)})}},Yf=/* @__PURE__ */ new Set([`read`,`add-torrent-file`,`export-chunk`]);let Xf=Promise.resolve();self.addEventListener(`message`,e=>{let t=e.data;if(!t||typeof t!=`object`||typeof t.type!=`string`||!Pu.has(t.type))return;let n=K;if(!n){t.type===`read`?Z({type:`read-error`,id:t.id,error:`the engine is still starting`}):Z({type:`error`,message:`worker not initialized`});return}if(Yf.has(t.type)){Jf(n,t);return}Xf=Xf.then(()=>Jf(n,t))}),qf().catch(e=>Z({type:Bu?`error`:`fatal`,message:String(e?.stack??e)}));
23
+ var n=Co(),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),Ns=/* @__PURE__ */ t((e=>{var t=Ms().Buffer,n=t.isEncoding||function(e){switch(e=``+e,e&&e.toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:case`raw`:return!0;default:return!1}};function r(e){if(!e)return`utf8`;for(var t;;)switch(e){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:if(t)return;e=(``+e).toLowerCase(),t=!0}}function i(e){var i=r(e);if(typeof i!=`string`&&(t.isEncoding===n||!n(e)))throw Error(`Unknown encoding: `+e);return i||e}e.StringDecoder=a;function a(e){this.encoding=i(e);var n;switch(this.encoding){case`utf16le`:this.text=f,this.end=p,n=4;break;case`utf8`:this.fillLast=l,n=4;break;case`base64`:this.text=m,this.end=h,n=3;break;default:this.write=g,this.end=_;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=t.allocUnsafe(n)}a.prototype.write=function(e){if(e.length===0)return``;var t,n;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return``;n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||``},a.prototype.end=d,a.prototype.text=u,a.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function o(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e,t,n){var r=t.length-1;if(r<n)return 0;var i=o(t[r]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(e.lastNeed=i-2),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function c(e,t,n){if((t[0]&192)!=128)return e.lastNeed=0,`�`;if(e.lastNeed>1&&t.length>1){if((t[1]&192)!=128)return e.lastNeed=1,`�`;if(e.lastNeed>2&&t.length>2&&(t[2]&192)!=128)return e.lastNeed=2,`�`}}function l(e){var t=this.lastTotal-this.lastNeed,n=c(this,e,t);if(n!==void 0)return n;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function u(e,t){var n=s(this,e,t);if(!this.lastNeed)return e.toString(`utf8`,t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString(`utf8`,t,r)}function d(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+`�`:t}function f(e,t){if((e.length-t)%2==0){var n=e.toString(`utf16le`,t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString(`utf16le`,t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):``;if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString(`utf16le`,0,n)}return t}function m(e,t){var n=(e.length-t)%3;return n===0?e.toString(`base64`,t):(this.lastNeed=3-n,this.lastTotal=3,n===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString(`base64`,t,e.length-n))}function h(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+this.lastChar.toString(`base64`,0,3-this.lastNeed):t}function g(e){return e.toString(this.encoding)}function _(e){return e&&e.length?this.write(e):``}})),Ps=/* @__PURE__ */ t(((e,t)=>{var n=Ds().codes.ERR_STREAM_PREMATURE_CLOSE;function r(e){var t=!1;return function(){if(!t){t=!0;var n=[...arguments];e.apply(this,n)}}}function i(){}function a(e){return e.setHeader&&typeof e.abort==`function`}function o(e,t,s){if(typeof t==`function`)return o(e,null,t);t||={},s=r(s||i);var c=t.readable||t.readable!==!1&&e.readable,l=t.writable||t.writable!==!1&&e.writable,u=function(){e.writable||f()},d=e._writableState&&e._writableState.finished,f=function(){l=!1,d=!0,c||s.call(e)},p=e._readableState&&e._readableState.endEmitted,m=function(){c=!1,p=!0,l||s.call(e)},h=function(t){s.call(e,t)},g=function(){var t;if(c&&!p)return(!e._readableState||!e._readableState.ended)&&(t=new n),s.call(e,t);if(l&&!d)return(!e._writableState||!e._writableState.ended)&&(t=new n),s.call(e,t)},_=function(){e.req.on(`finish`,f)};return a(e)?(e.on(`complete`,f),e.on(`abort`,g),e.req?_():e.on(`request`,_)):l&&!e._writableState&&(e.on(`end`,u),e.on(`close`,u)),e.on(`end`,m),e.on(`finish`,f),t.error!==!1&&e.on(`error`,h),e.on(`close`,g),function(){e.removeListener(`complete`,f),e.removeListener(`abort`,g),e.removeListener(`request`,_),e.req&&e.req.removeListener(`finish`,f),e.removeListener(`end`,u),e.removeListener(`close`,u),e.removeListener(`finish`,f),e.removeListener(`end`,m),e.removeListener(`error`,h),e.removeListener(`close`,g)}}t.exports=o})),Fs=/* @__PURE__ */ t(((e,t)=>{var n;function r(e,t,n){return t=i(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=a(e,`string`);return typeof t==`symbol`?t:String(t)}function a(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var o=Ps(),s=Symbol(`lastResolve`),c=Symbol(`lastReject`),l=Symbol(`error`),u=Symbol(`ended`),d=Symbol(`lastPromise`),f=Symbol(`handlePromise`),p=Symbol(`stream`);function m(e,t){return{value:e,done:t}}function h(e){var t=e[s];if(t!==null){var n=e[p].read();n!==null&&(e[d]=null,e[s]=null,e[c]=null,t(m(n,!1)))}}function g(e){process.nextTick(h,e)}function _(e,t){return function(n,r){e.then(function(){if(t[u]){n(m(void 0,!0));return}t[f](n,r)},r)}}var v=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((n={get stream(){return this[p]},next:function(){var e=this,t=this[l];if(t!==null)return Promise.reject(t);if(this[u])return Promise.resolve(m(void 0,!0));if(this[p].destroyed)return new Promise(function(t,n){process.nextTick(function(){e[l]?n(e[l]):t(m(void 0,!0))})});var n=this[d],r;if(n)r=new Promise(_(n,this));else{var i=this[p].read();if(i!==null)return Promise.resolve(m(i,!1));r=new Promise(this[f])}return this[d]=r,r}},r(n,Symbol.asyncIterator,function(){return this}),r(n,`return`,function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){if(e){n(e);return}t(m(void 0,!0))})})}),n),v);t.exports=function(e){var t,n=Object.create(y,(t={},r(t,p,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,f,{value:function(e,t){var r=n[p].read();r?(n[d]=null,n[s]=null,n[c]=null,e(m(r,!1))):(n[s]=e,n[c]=t)},writable:!0}),t));return n[d]=null,o(e,function(e){if(e&&e.code!==`ERR_STREAM_PREMATURE_CLOSE`){var t=n[c];t!==null&&(n[d]=null,n[s]=null,n[c]=null,t(e)),n[l]=e;return}var r=n[s];r!==null&&(n[d]=null,n[s]=null,n[c]=null,r(m(void 0,!0))),n[u]=!0}),e.on(`readable`,g.bind(null,n)),n}})),Is=/* @__PURE__ */ t(((e,t)=>{t.exports=function(){throw Error(`Readable.from is not available in the browser`)}})),Ls=/* @__PURE__ */ t(((e,t)=>{t.exports=E;var n;E.ReadableState=T,vo().EventEmitter;var r=function(e,t){return e.listeners(t).length},i=bo(),a=Co().Buffer,o=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function s(e){return a.from(e)}function c(e){return a.isBuffer(e)||e instanceof o}var l=ws(),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=Ts(),f=Es(),p=Os().getHighWaterMark,m=Ds().codes,h=m.ERR_INVALID_ARG_TYPE,g=m.ERR_STREAM_PUSH_AFTER_EOF,_=m.ERR_METHOD_NOT_IMPLEMENTED,v=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,y,b,x;yo()(E,i);var S=f.errorOrDestroy,C=[`error`,`close`,`destroy`,`pause`,`resume`];function w(e,t,n){if(typeof e.prependListener==`function`)return e.prependListener(t,n);!e._events||!e._events[t]?e.on(t,n):Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]}function T(e,t,r){n||=js(),e||={},typeof r!=`boolean`&&(r=t instanceof n),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=p(this,e,`readableHighWaterMark`,r),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(y||=Ns().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=js(),!(this instanceof E))return new E(e);var t=this instanceof n;this._readableState=new T(e,this,t),this.readable=!0,e&&(typeof e.read==`function`&&(this._read=e.read),typeof e.destroy==`function`&&(this._destroy=e.destroy)),i.call(this)}Object.defineProperty(E.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),E.prototype.destroy=f.destroy,E.prototype._undestroy=f.undestroy,E.prototype._destroy=function(e,t){t(e)},E.prototype.push=function(e,t){var n=this._readableState,r;return n.objectMode?r=!0:typeof e==`string`&&(t||=n.defaultEncoding,t!==n.encoding&&(e=a.from(e,t),t=``),r=!0),D(this,e,t,!1,r)},E.prototype.unshift=function(e){return D(this,e,null,!0,!1)};function D(e,t,n,r,i){u(`readableAddChunk`,t);var o=e._readableState;if(t===null)o.reading=!1,ee(e,o);else{var c;if(i||(c=k(o,t)),c)S(e,c);else if(o.objectMode||t&&t.length>0){if(typeof t!=`string`&&!o.objectMode&&Object.getPrototypeOf(t)!==a.prototype&&(t=s(t)),r)o.endEmitted?S(e,new v):O(e,o,t,!0);else if(o.ended)S(e,new g);else if(o.destroyed)return!1;else o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||t.length!==0?O(e,o,t,!1):F(e,o)):O(e,o,t,!1)}else r||(o.reading=!1,F(e,o))}return!o.ended&&(o.length<o.highWaterMark||o.length===0)}function O(e,t,n,r){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit(`data`,n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&N(e)),F(e,t)}function k(e,t){var n;return!c(t)&&typeof t!=`string`&&t!==void 0&&!e.objectMode&&(n=new h(`chunk`,[`string`,`Buffer`,`Uint8Array`],t)),n}E.prototype.isPaused=function(){return this._readableState.flowing===!1},E.prototype.setEncoding=function(e){y||=Ns().StringDecoder;var t=new y(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r=``;n!==null;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),r!==``&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var A=1073741824;function j(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function M(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=j(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}E.prototype.read=function(e){u(`read`,e),e=parseInt(e,10);var t=this._readableState,n=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark===0?t.length>0:t.length>=t.highWaterMark)||t.ended))return u(`read: emitReadable`,t.length,t.ended),t.length===0&&t.ended?ae(this):N(this),null;if(e=M(e,t),e===0&&t.ended)return t.length===0&&ae(this),null;var r=t.needReadable;u(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,u(`length less than watermark`,r)),t.ended||t.reading?(r=!1,u(`reading or ended`,r)):r&&(u(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=M(n,t)));var i=e>0?ie(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&ae(this)),i!==null&&this.emit(`data`,i),i};function ee(e,t){if(u(`onEofChunk`),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?N(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,P(e)))}}function N(e){var t=e._readableState;u(`emitReadable`,t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u(`emitReadable`,t.flowing),t.emittedReadable=!0,process.nextTick(P,e))}function P(e){var t=e._readableState;u(`emitReadable_`,t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(`readable`),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,re(e)}function F(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(I,e,t))}function I(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var n=t.length;if(u(`maybeReadMore read 0`),e.read(0),n===t.length)break}t.readingMore=!1}E.prototype._read=function(e){S(this,new _(`_read()`))},E.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,u(`pipe count=%d opts=%j`,i.pipesCount,t);var a=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr?s:g;i.endEmitted?process.nextTick(a):n.once(`end`,a),e.on(`unpipe`,o);function o(e,t){u(`onunpipe`),e===n&&t&&t.hasUnpiped===!1&&(t.hasUnpiped=!0,d())}function s(){u(`onend`),e.end()}var c=L(n);e.on(`drain`,c);var l=!1;function d(){u(`cleanup`),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`drain`,c),e.removeListener(`error`,p),e.removeListener(`unpipe`,o),n.removeListener(`end`,s),n.removeListener(`end`,g),n.removeListener(`data`,f),l=!0,i.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}n.on(`data`,f);function f(t){u(`ondata`);var r=e.write(t);u(`dest.write`,r),r===!1&&((i.pipesCount===1&&i.pipes===e||i.pipesCount>1&&se(i.pipes,e)!==-1)&&!l&&(u(`false write response, pause`,i.awaitDrain),i.awaitDrain++),n.pause())}function p(t){u(`onerror`,t),g(),e.removeListener(`error`,p),r(e,`error`)===0&&S(e,t)}w(e,`error`,p);function m(){e.removeListener(`finish`,h),g()}e.once(`close`,m);function h(){u(`onfinish`),e.removeListener(`close`,m),g()}e.once(`finish`,h);function g(){u(`unpipe`),n.unpipe(e)}return e.emit(`pipe`,n),i.flowing||(u(`pipe resume`),n.resume()),e};function L(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,re(e))}}E.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=se(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),--t.pipesCount,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit(`unpipe`,this,n),this)},E.prototype.on=function(e,t){var n=i.prototype.on.call(this,e,t),r=this._readableState;return e===`data`?(r.readableListening=this.listenerCount(`readable`)>0,r.flowing!==!1&&this.resume()):e===`readable`&&!r.endEmitted&&!r.readableListening&&(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,u(`on readable`,r.length,r.reading),r.length?N(this):r.reading||process.nextTick(z,this)),n},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var n=i.prototype.removeListener.call(this,e,t);return e===`readable`&&process.nextTick(R,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(R,this),t};function R(e){var t=e._readableState;t.readableListening=e.listenerCount(`readable`)>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount(`data`)>0&&e.resume()}function z(e){u(`readable nexttick read 0`),e.read(0)}E.prototype.resume=function(){var e=this._readableState;return e.flowing||(u(`resume`),e.flowing=!e.readableListening,te(this,e)),e.paused=!1,this};function te(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ne,e,t))}function ne(e,t){u(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),re(e),t.flowing&&!t.reading&&e.read(0)}E.prototype.pause=function(){return u(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(u(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function re(e){var t=e._readableState;for(u(`flow`,t.flowing);t.flowing&&e.read()!==null;);}E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(u(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){u(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(n.objectMode||i&&i.length)&&(t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<C.length;a++)e.on(C[a],this.emit.bind(this,C[a]));return this._read=function(t){u(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(E.prototype[Symbol.asyncIterator]=function(){return b===void 0&&(b=Fs()),b(this)}),Object.defineProperty(E.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=ie,Object.defineProperty(E.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function ie(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function ae(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(oe,t,e))}function oe(e,t){if(u(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(E.from=function(e,t){return x===void 0&&(x=Is()),x(E,e,t)});function se(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),Rs=/* @__PURE__ */ t(((e,t)=>{t.exports=l;var n=Ds().codes,r=n.ERR_METHOD_NOT_IMPLEMENTED,i=n.ERR_MULTIPLE_CALLBACK,a=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,o=n.ERR_TRANSFORM_WITH_LENGTH_0,s=js();yo()(l,s);function c(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(r===null)return this.emit(`error`,new i);n.writechunk=null,n.writecb=null,t!=null&&this.push(t),r(e);var a=this._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark)}function l(e){if(!(this instanceof l))return new l(e);s.call(this,e),this._transformState={afterTransform:c.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform==`function`&&(this._transform=e.transform),typeof e.flush==`function`&&(this._flush=e.flush)),this.on(`prefinish`,u)}function u(){var e=this;typeof this._flush==`function`&&!this._readableState.destroyed?this._flush(function(t,n){d(e,t,n)}):d(this,null,null)}l.prototype.push=function(e,t){return this._transformState.needTransform=!1,s.prototype.push.call(this,e,t)},l.prototype._transform=function(e,t,n){n(new r(`_transform()`))},l.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},l.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},l.prototype._destroy=function(e,t){s.prototype._destroy.call(this,e,function(e){t(e)})};function d(e,t,n){if(t)return e.emit(`error`,t);if(n!=null&&e.push(n),e._writableState.length)throw new o;if(e._transformState.transforming)throw new a;return e.push(null)}})),zs=/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=Rs();yo()(r,n);function r(e){if(!(this instanceof r))return new r(e);n.call(this,e)}r.prototype._transform=function(e,t,n){n(null,e)}})),Bs=/* @__PURE__ */ t(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=Ds().codes,a=i.ERR_MISSING_ARGS,o=i.ERR_STREAM_DESTROYED;function s(e){if(e)throw e}function c(e){return e.setHeader&&typeof e.abort==`function`}function l(e,t,i,a){a=r(a);var s=!1;e.on(`close`,function(){s=!0}),n===void 0&&(n=Ps()),n(e,{readable:t,writable:i},function(e){if(e)return a(e);s=!0,a()});var l=!1;return function(t){if(!s&&!l){if(l=!0,c(e))return e.abort();if(typeof e.destroy==`function`)return e.destroy();a(t||new o(`pipe`))}}}function u(e){e()}function d(e,t){return e.pipe(t)}function f(e){return!e.length||typeof e[e.length-1]!=`function`?s:e.pop()}function p(){var e=[...arguments],t=f(e);if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw new a(`streams`);var n,r=e.map(function(i,a){var o=a<e.length-1;return l(i,o,a>0,function(e){n||=e,e&&r.forEach(u),!o&&(r.forEach(u),t(n))})});return e.reduce(d)}t.exports=p})),Vs=(/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=vo().EventEmitter;yo()(r,n),r.Readable=Ls(),r.Writable=As(),r.Duplex=js(),r.Transform=Rs(),r.PassThrough=zs(),r.finished=Ps(),r.pipeline=Bs(),r.Stream=r;function r(){n.call(this)}r.prototype.pipe=function(e,t){var r=this;function i(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}r.on(`data`,i);function a(){r.readable&&r.resume&&r.resume()}e.on(`drain`,a),!e._isStdio&&(!t||t.end!==!1)&&(r.on(`end`,s),r.on(`close`,c));var o=!1;function s(){o||(o=!0,e.end())}function c(){o||(o=!0,typeof e.destroy==`function`&&e.destroy())}function l(e){if(u(),n.listenerCount(this,`error`)===0)throw e}r.on(`error`,l),e.on(`error`,l);function u(){r.removeListener(`data`,i),e.removeListener(`drain`,a),r.removeListener(`end`,s),r.removeListener(`close`,c),r.removeListener(`error`,l),e.removeListener(`error`,l),r.removeListener(`end`,u),r.removeListener(`close`,u),e.removeListener(`close`,u)}return r.on(`end`,u),r.on(`close`,u),e.on(`close`,u),e.emit(`pipe`,r),e}})))(),Hs=vo(),Us=class extends Vs.Stream.Duplex{_localAddress;_remoteAddress;_webVPNTcpSocketPromise;_relay;constructor(e){if(e?.fd!==void 0)throw Error(`FKN WebVPN does not support file descriptors`);super(e),e?.connection&&this.__webvpn_tcp_socket_init__(e.connection)}_busyRelease;__webvpn_tcp_socket_init__(e,t){return this._busyRelease??=fo(`tcp socket`),t&&(this._localAddress={address:t.localAddress,family:t.localFamily,port:t.localPort},this._remoteAddress={address:t.remoteAddress,family:t.remoteFamily,port:t.remotePort},this._relay=t.relay),this._webVPNTcpSocketPromise=e.then(e=>{let t=e.dataReadableStream.getReader(),n=e.dataWritableStream.getWriter();return this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},this._remoteAddress={address:e.remoteAddress,family:e.remoteFamily,port:e.remotePort},this._relay=e.relay,{...e,reader:t,writer:n}}).catch(e=>{this.emit(`error`,e)}),this._webVPNTcpSocketPromise.then(e=>{e?this.emit(`connect`):this._busyRelease?.()}),this._webVPNTcpSocketPromise}_read(e){if(!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);this._webVPNTcpSocketPromise.then(e=>{e?e.reader.read().then(({value:e,done:t})=>{t?this.push(null):(this._restartTimeoutTimer(),this.push(e))}).catch(e=>{this.destroy(e)}):this.push(null)})}_write(e,t,n){this._webVPNTcpSocketPromise?this._webVPNTcpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not connected`);await t.writer.ready,await t.writer.write(e),this._restartTimeoutTimer(),n()}).catch(n):n(/* @__PURE__ */ Error(`Socket not connected`))}connect(...e){let t=g(...e),{relay:n}=t,r=this.__webvpn_tcp_socket_init__(co(`an outbound tcp socket`).then(e=>(n!==void 0&&go(e,`net.connect`),e.cloud.webvpn.tcpSocket({remoteAddress:t.host??`localhost`,remotePort:t.port,relay:n}))));return t.callback&&r.then(e=>{e&&t.callback.call(this)}),this}_final(e){this._webVPNTcpSocketPromise?this._webVPNTcpSocketPromise.then(async e=>{e&&await e.writer.close()}).then(()=>e(),t=>e(t)):e()}_destroy(e,t){this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._busyRelease?.(),this._webVPNTcpSocketPromise?this._webVPNTcpSocketPromise.then(async e=>{e&&await(this._resetRequested?e.resetAndDestroy():e.destroy())}).then(()=>t(e),()=>t(e)):t(e)}destroySoon(){this.writableFinished?this.destroy():(this.once(`finish`,()=>this.destroy()),this.end())}_resetRequested=!1;resetAndDestroy(){return this._resetRequested=!0,this.destroy(),this}_timeoutMs;_timeoutTimer;_restartTimeoutTimer(){this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._timeoutMs&&(this._timeoutTimer=setTimeout(()=>this.emit(`timeout`),this._timeoutMs))}setTimeout(e,t){return t&&this.on(`timeout`,t),this._timeoutMs=e,this._restartTimeoutTimer(),this}setNoDelay(e){let t=e??!0;return this._setTcpOption({type:0,value:t}),this}setKeepAlive(e,t){let n=e??!1,r=t!==void 0&&t>0?Math.max(1,Math.round(t/1e3)):0;return this._setTcpOption({type:2,enabled:n,initialDelaySeconds:r}),this}setSendBufferSize(e){return this._setTcpOption({type:3,value:e}),this}setRecvBufferSize(e){return this._setTcpOption({type:4,value:e}),this}_typeOfService;getTypeOfService(){return this._typeOfService??0}setTypeOfService(e){return this._typeOfService=e,this}_setTcpOption(e){this._webVPNTcpSocketPromise?this._webVPNTcpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}}):this.emit(`error`,/* @__PURE__ */ Error(`Cannot set socket option before connect`))}write(e,t,...n){return super.write(e,t,...n)}address(){return this._localAddress??{}}unref(){return this}ref(){return this}autoSelectFamilyAttemptedAddresses;bufferSize;bytesRead;bytesWritten;connecting;pending;get localAddress(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.address}get localPort(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.port}get localFamily(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.family}readyState;get remoteAddress(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.address}get remotePort(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.port}get remoteFamily(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.family}timeout},Ws=class extends Hs.EventEmitter{_localAddress;_webVPNTcpSocketListenerPromise;_relayChoice;_relay;constructor(e,t){super(e),this._relayChoice=e?.relay,t&&this.on(`connection`,t),e?.connection&&this.__webvpn_tcp_socket_listener_init__(e.connection)}_busyRelease;__webvpn_tcp_socket_listener_init__(e){return this._busyRelease??=fo(`tcp server`),this._webVPNTcpSocketListenerPromise=e.then(e=>(this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},this._relay=e.relay,e)).catch(e=>{this.emit(`error`,e)}),this._webVPNTcpSocketListenerPromise.then(e=>{e?this.emit(`listening`):this._busyRelease?.()}),this._webVPNTcpSocketListenerPromise}listen(...e){let t=g(...e);this._closeEmitted=!1;let n=e=>{let t=new Us;t.__webvpn_tcp_socket_init__(Promise.resolve(e),e),this.emit(`connection`,t)},r=e=>{this._localAddress=void 0;try{e&&this.listenerCount(`error`)>0&&this.emit(`error`,e)}finally{this._emitClose()}},i=this._relayChoice,a=e=>co(`a tcp listener`).then(a=>(i!==void 0&&go(a,`net.createServer`),a.cloud.webvpn.tcpSocketListener({localAddress:e,localPort:t.port,onConnection:n,onClose:r,relay:i}))),o=t.host?a(t.host):a(`::`).catch(()=>a(`0.0.0.0`)),s=this.__webvpn_tcp_socket_listener_init__(o);return t.callback&&s.then(e=>{e&&t.callback.call(this)}),this}_closeEmitted=!1;_emitClose(){this._closeEmitted||(this._closeEmitted=!0,this._busyRelease?.(),this.emit(`close`))}close(e){return this._webVPNTcpSocketListenerPromise&&this._webVPNTcpSocketListenerPromise.then(async t=>{if(t)try{await t.close(),this._localAddress=void 0,this._emitClose(),e&&e()}catch(t){this._localAddress=void 0,this._emitClose(),e&&e(t)}}),this}address(){return this._localAddress??null}getConnections(e){throw Error(`Method not implemented.`)}ref(){return this}unref(){return this}maxConnections;connections;listening;async[Symbol.asyncDispose](){}},Gs=(e,t)=>new Us().connect(e,t),Ks=Gs,qs=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new Ws(e);return t&&n.on(`connection`,t),n},Js={Socket:Us,Server:Ws,connect:Gs,createConnection:Ks,createServer:qs,isIP:h,isIPv4:p,isIPv6:m},Ys=/* @__PURE__ */ n({Server:()=>Ws,Socket:()=>Us,_default:()=>Js,connect:()=>Gs,createConnection:()=>Ks,createServer:()=>qs,default:()=>Js,isIP:()=>h,isIPv4:()=>p,isIPv6:()=>m}),Xs=Co(),Zs=class extends Hs.EventEmitter{_type;_localAddress;_remoteAddress;_connectedLocally;_connectGeneration=0;_destroyed=!1;_busyRelease;_webVPNUdpSocketPromise;_dataPort;_socketId;_sendQueue=[];_sendQueueBytes=0;_sendFlushScheduled=!1;_peerTailCache=/* @__PURE__ */ new Map;_relayChoice;_relay;constructor(e){if(super(e),!e)throw Error(`Missing options`);this._type=e.type,this._relayChoice=e.relay,e.connection&&this.__webvpn_udp_socket_init__(e.connection)}_lastRecvBufferSize=0;_lastSendBufferSize=0;_lastTtl=64;_lastMulticastTtl=1;_lastMulticastLoopback=!0;_setUdpOption(e){this._webVPNUdpSocketPromise?this._webVPNUdpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}}):this.emit(`error`,/* @__PURE__ */ Error(`Cannot set socket option before bind`))}_dataPortAcks=!1;_dataPortConsumedBytes=0;_dataPortAckedBytes=0;_ackDataPortBatch(e){if(!this._dataPortAcks||!this._dataPort||(this._dataPortConsumedBytes+=e,this._dataPortAckedBytes!==0&&this._dataPortConsumedBytes-this._dataPortAckedBytes<524288))return;this._dataPortAckedBytes=this._dataPortConsumedBytes;let t={type:_o,consumedBytes:this._dataPortConsumedBytes};this._dataPort.postMessage(t)}_onTransportClosed(e){this._destroyed||(this._destroyed=!0,this._busyRelease?.(),this._dataPort?.close(),this._dataPort=void 0,this.listenerCount(`error`)>0&&this.emit(`error`,Error(e||`WebVPN session closed`)),this.emit(`close`))}_onDataPortBatch(e){let t=new DataView(e),n=!1,r,i=0;for(;i+4<=e.byteLength;){let a=t.getUint32(i);i+=4;let o=i+a;if(o>e.byteLength)break;let s=i+4,c=t.getUint8(s);s+=1;let l,u,d;if(c===2){if(!this._remoteAddress){i=o;continue}l=this._remoteAddress.address,u=this._remoteAddress.family,d=this._remoteAddress.port}else{let n=new Uint8Array(e,s,c===0?4:16);c===0?(u=`IPv4`,l=`${n[0]}.${n[1]}.${n[2]}.${n[3]}`):(u=`IPv6`,l=tc(n)),s+=n.byteLength,d=t.getUint16(s),s+=2}let f=t.getUint32(s);s+=4;try{this.emit(`message`,Xs.Buffer.from(e.slice(s,s+f)),{address:l,family:u,port:d,size:f})}catch(e){n||(n=!0,r=e)}i=o}if(n)throw r}_peerTail(e,t){if(e===void 0||t===void 0)return Qs;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let i=d.Address4.isValid(e)?ec(e):nc(e),a=new Uint8Array(1+i.byteLength+2);return a[0]=i.byteLength===4?0:1,a.set(i,1),new DataView(a.buffer).setUint16(1+i.byteLength,t),this._peerTailCache.size>=4096&&this._peerTailCache.clear(),this._peerTailCache.set(n,a),a}_portSend(e,t,n){let r=this._peerTail(t,n),i=new Uint8Array(8+r.byteLength+4+e.byteLength),a=new DataView(i.buffer);a.setUint32(0,i.byteLength-4),a.setUint32(4,this._socketId),i.set(r,8),a.setUint32(8+r.byteLength,e.byteLength),i.set(e,12+r.byteLength),this._sendQueue.push(i),this._sendQueueBytes+=i.byteLength,!this._sendFlushScheduled&&(this._sendFlushScheduled=!0,queueMicrotask(()=>{this._sendFlushScheduled=!1;let e=this._sendQueue,t=this._sendQueueBytes;if(this._sendQueue=[],this._sendQueueBytes=0,!e.length||!this._dataPort)return;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;this._dataPort.postMessage(n.buffer,[n.buffer])}))}addMembership(e,t){if(d.Address4.isValid(e)){let n=ec(e),r=t&&d.Address4.isValid(t)?ec(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(d.Address6.isValid(e)){let t=nc(e);this._setUdpOption({type:7,group:t,ifIndex:0})}else this.emit(`error`,/* @__PURE__ */ Error(`Invalid multicast address: ${e}`))}address(){if(!this._localAddress)throw Error(`EBADF`);return this._localAddress}bind(...e){let t=_(...e),n=this._type===`udp6`?`::`:`0.0.0.0`,r=this._relayChoice,i=this.__webvpn_udp_socket_init__(co(`a udp socket`).then(e=>(r!==void 0&&go(e,`dgram.createSocket`),e.cloud.webvpn.udpSocket({type:this._type,address:t.address??n,port:t.port,dataPort:!0,relay:r}))));return t.callback&&i.then(e=>{e&&t.callback.call(this)}),this}__webvpn_udp_socket_init__(e,t){return t&&(this._localAddress={address:t.localAddress,family:t.localFamily,port:t.localPort}),this._busyRelease??=fo(`udp socket`),this._webVPNUdpSocketPromise=e.then(e=>{if(e.dataPort)this._socketId=e.socketId,this._dataPort=e.dataPort,this._dataPortAcks=e.dataPortAcks===!0,this._dataPort.onmessage=e=>{try{this._onDataPortBatch(e.data)}finally{this._ackDataPortBatch(e.data.byteLength)}};else{let t=e.dataReadableStream.getReader();(async()=>{for(;;){let{value:e,done:n}=await t.read();if(n)return;this.emit(`message`,Xs.Buffer.from(e.data),{address:e.address,family:e.family,port:e.port,size:e.size})}})().catch(e=>this._onTransportClosed(e instanceof Error?e.message:void 0))}return e.closed?.then(e=>this._onTransportClosed(e?.reason)).catch(()=>{}),this._relay=e.relay,this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e}).catch(e=>{this.emit(`error`,e)}),this._webVPNUdpSocketPromise.then(e=>{e?this.emit(`listening`):this._busyRelease?.()}),this._webVPNUdpSocketPromise}close(e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);return this._webVPNUdpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not bound`);let n=this._destroyed;this._destroyed=!0,this._busyRelease?.(),this._dataPort?.close(),this._dataPort=void 0;try{await t.close()}finally{try{e&&e()}finally{n||this.emit(`close`)}}}).catch(()=>{}),this}connect(...e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not bound`);let n=e[0],r=this._type===`udp6`?`::1`:`127.0.0.1`,i=typeof e[1]==`string`?e[1]:r,a=typeof e.at(-1)==`function`?e.at(-1):void 0,o=await t.connect({remotePort:n,remoteAddress:i});this._connectedLocally=o?.local===!0,this._remoteAddress=o?.address?{address:o.address,family:o.family,port:o.port}:{address:i,family:this._type===`udp6`?`IPv6`:`IPv4`,port:n},this._connectGeneration+=1,a&&a()}).catch(e=>{this.emit(`error`,e)})}disconnect(){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);if(!this._remoteAddress)throw Error(`ERR_SOCKET_DGRAM_NOT_CONNECTED`);let e=this._remoteAddress,t=this._connectedLocally,n=this._connectGeneration;this._remoteAddress=void 0,this._connectedLocally=void 0,this._webVPNUdpSocketPromise.then(e=>e?.disconnect?.()).catch(r=>{this._connectGeneration===n&&(this._remoteAddress=e,this._connectedLocally=t),this.emit(`error`,r)})}dropMembership(e,t){if(d.Address4.isValid(e)){let n=ec(e),r=t&&d.Address4.isValid(t)?ec(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(d.Address6.isValid(e)){let t=nc(e);this._setUdpOption({type:8,group:t,ifIndex:0})}else this.emit(`error`,/* @__PURE__ */ Error(`Invalid multicast address: ${e}`))}getRecvBufferSize(){return this._lastRecvBufferSize}getSendBufferSize(){return this._lastSendBufferSize}getSendQueueSize(){return 0}getSendQueueCount(){return 0}ref(){return this}remoteAddress(){if(!this._remoteAddress)throw Error(`ERR_SOCKET_DGRAM_NOT_CONNECTED`);return{address:this._remoteAddress.address,family:this._remoteAddress.family,port:this._remoteAddress.port}}send(...e){this._webVPNUdpSocketPromise||this.bind();let t=v(...e),n=$s(t.message),r=n;if(t.hasRange){let{offset:e,length:i}=t;if(!Number.isInteger(e)||e<0||e>n.byteLength)throw Object.assign(/* @__PURE__ */ RangeError(`"offset" is outside of buffer bounds`),{code:`ERR_BUFFER_OUT_OF_BOUNDS`});if(!Number.isInteger(i)||i<0||i>n.byteLength-e)throw Object.assign(/* @__PURE__ */ RangeError(`"length" is outside of buffer bounds`),{code:`ERR_BUFFER_OUT_OF_BOUNDS`});r=n.subarray(e,e+i)}let i=this._type===`udp6`?`::1`:`127.0.0.1`;if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(e=>{if(!e)throw Error(`Socket not bound`);let n=t.callback,a=t.address??i,o=this._remoteAddress!==void 0&&t.address===void 0;this._dataPort&&(o||d.Address4.isValid(a)||d.Address6.isValid(a))?(this._portSend(r,o?void 0:a,o?void 0:t.port),n?.call(this,null,r.byteLength)):e.send({port:t.port,address:a,message:r.byteOffset===0&&r.byteLength===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}).then(()=>n?.call(this,null,r.byteLength),e=>n?n.call(this,e,0):this.emit(`error`,e))})}setBroadcast(e){this._setUdpOption({type:0,value:e})}setMulticastInterface(e){}setMulticastLoopback(e){return this._setUdpOption({type:3,value:e}),this._setUdpOption({type:4,value:e}),this._lastMulticastLoopback=e,e}setMulticastTTL(e){return this._setUdpOption({type:2,value:e}),this._lastMulticastTtl=e,e}setRecvBufferSize(e){this._setUdpOption({type:10,value:e}),this._lastRecvBufferSize=e}setSendBufferSize(e){this._setUdpOption({type:9,value:e}),this._lastSendBufferSize=e}setTTL(e){return this._setUdpOption({type:1,value:e}),this._lastTtl=e,e}unref(){return this}addSourceSpecificMembership(e,t,n){}dropSourceSpecificMembership(e,t,n){}async[Symbol.asyncDispose](){await new Promise(e=>{this.close(e)})}},Qs=new Uint8Array([2]),$s=e=>{if(typeof e==`string`)return f.encode(e);if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(Array.isArray(e)){let t=e.map($s),n=new Uint8Array(t.reduce((e,t)=>e+t.byteLength,0)),r=0;for(let e of t)n.set(e,r),r+=e.byteLength;return n}return new Uint8Array(e)},ec=e=>{let t=e.split(`.`).map(e=>parseInt(e,10));if(t.length!==4||t.some(e=>Number.isNaN(e)||e<0||e>255))throw Error(`Invalid IPv4 address: ${e}`);return new Uint8Array(t)},tc=e=>{let t=[];for(let n=0;n<16;n+=2)t.push(e[n]<<8|e[n+1]);let n=-1,r=1;for(let e=0;e<8;){if(t[e]!==0){e++;continue}let i=e;for(;i<8&&t[i]===0;)i++;i-e>r&&(n=e,r=i-e),e=i}return n===-1?t.map(e=>e.toString(16)).join(`:`):`${t.slice(0,n).map(e=>e.toString(16)).join(`:`)}::${t.slice(n+r).map(e=>e.toString(16)).join(`:`)}`},nc=e=>{let t=new d.Address6(e).getBitsBase16(0,128).match(/.{2}/g);if(!t||t.length!==16)throw Error(`Invalid IPv6 address: ${e}`);return new Uint8Array(t.map(e=>parseInt(e,16)))},rc=(e,t)=>{let n=new Zs(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},ic={Socket:Zs,createSocket:rc},ac=/* @__PURE__ */ n({Socket:()=>Zs,createSocket:()=>rc,default:()=>ic});function oc(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function sc(e,t){let n,r=()=>{if(n)return n;let r=indexedDB.open(e);return r.onupgradeneeded=()=>r.result.createObjectStore(t),n=oc(r),n.then(e=>{e.onclose=()=>n=void 0},()=>{}),n};return(e,n)=>r().then(r=>n(r.transaction(t,e).objectStore(t)))}let cc;function lc(){return cc||=sc(`keyval-store`,`keyval`),cc}function uc(e,t=lc()){return t(`readonly`,t=>oc(t.get(e)))}function dc(e,t,n=lc()){return n(`readwrite`,n=>(n.put(t,e),oc(n.transaction)))}function fc(e,t,n=lc()){return n(`readwrite`,n=>new Promise((r,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),r(oc(n.transaction))}catch(e){i(e)}}}))}function pc(e,t=lc()){return t(`readwrite`,t=>(t.delete(e),oc(t.transaction)))}var mc={checkingFiles:1,downloadingMetadata:2,downloading:3,finished:4,seeding:5,checkingResumeData:7},hc=/^incoming connection from (\S+) \(([^)]*)\)/,gc=/^successfully listening on \[([^\]]*)\] (\S+)/,_c=/^listening on .* failed:/,vc=new TextDecoder,yc=4026531841,bc=4026531842,xc=4026531843,Sc=4026531844,Cc=4026531845,wc=4026531846,Tc={interesting:1,choked:2,remoteInterested:4,remoteChoked:8,supportsExtensions:16,localConnection:32,handshake:64,connecting:128,onParole:512,seed:1024,optimisticUnchoke:2048,snubbed:4096,uploadOnly:8192,endgameMode:16384,holepunched:32768,i2pSocket:65536,utpSocket:1<<17,sslSocket:1<<18,rc4Encrypted:1<<19,plaintextEncrypted:1<<20},Ec={seedMode:1,uploadMode:2,shareMode:4,applyIpFilter:8,paused:16,autoManaged:32,duplicateIsError:64,updateSubscribe:128,superSeeding:256,sequentialDownload:512,stopWhenReady:1024,overrideTrackers:2048,overrideWebSeeds:4096,needSaveResume:8192,disableDht:1<<19,disableLsd:1<<20,disablePex:1<<21,noVerifyFiles:1<<22,defaultDontDownload:1<<23},Dc={top:0,up:1,down:2,bottom:3},Oc={tracker:1,dht:2,pex:4,lsd:8,resumeData:16,incoming:32},W={skip:0,low:1,normal:4,top:7},kc=6e4,Ac=12,jc=1e3,Mc=class{mod;storage;destroyed=!1;fallbackTimer;filesByHandle=/* @__PURE__ */ new Map;bitfieldByHandle=/* @__PURE__ */ new Map;statusByHandle=/* @__PURE__ */ new Map;pieceWaiters=[];resumeByHandle=/* @__PURE__ */ new Map;resumeWaiters=[];peersByHandle=/* @__PURE__ */ new Map;trackersByHandle=/* @__PURE__ */ new Map;peerWaiters=[];trackerWaiters=[];priosByHandle=/* @__PURE__ */ new Map;deadlineRefs=/* @__PURE__ */ new Map;textAlerts=[];reachability={listening:{},listenFailed:[],inbound:0,inboundByTransport:{},lastInbound:null,port:null};constructor(e,t){if(this.mod=e,this.storage=t.storage??null,t.utpReceiveBufferBytes&&e._lt_set_utp_receive_buffer(t.utpReceiveBufferBytes),t.enableDht===!1&&e._lt_set_dht(0),t.rateLimits){let{download:n,upload:r,limitLocalPeers:i}=t.rateLimits;e._lt_session_set_rate_limits(Math.max(0,Math.floor(n??0)),Math.max(0,Math.floor(r??0)),i==null?-1:+!!i)}if(e._lt_session_create()!==0)throw Error(`lt_session_create returned non-zero`);let n=t.tickIntervalMs??250;this.fallbackTimer=setInterval(()=>this.tick(),n)}addMagnet(e,t=`/downloads`){let n=this.mod,r=n.stringToNewUTF8(e),i=n.stringToNewUTF8(t);try{return n._lt_session_add_magnet(r,i)>>>0}finally{n._free(r),n._free(i)}}addTorrentFile(e,t=`/downloads`){let n=this.mod,r=n._malloc(e.length);n.HEAPU8.set(e,r);let i=n.stringToNewUTF8(t);try{return n._lt_session_add_torrent_file(r,e.length,i)>>>0}finally{n._free(r),n._free(i)}}addTorrentWithResume(e,t=`/downloads`){let n=this.mod,r=n._malloc(e.length);n.HEAPU8.set(e,r);let i=n.stringToNewUTF8(t);try{return n._lt_session_add_torrent_with_resume(r,e.length,i)>>>0}finally{n._free(r),n._free(i)}}removeTorrent(e,t=!1){this.mod._lt_session_remove_torrent_ex(e,+!!t),this.failPieceWaiters(/* @__PURE__ */ Error(`read: torrent ${e} was removed`),e),this.filesByHandle.delete(e),this.bitfieldByHandle.delete(e),this.statusByHandle.delete(e),this.resumeByHandle.delete(e),this.priosByHandle.delete(e),this.deadlineRefs.delete(e)}pauseTorrent(e){this.mod._lt_torrent_pause(e)}resumeTorrent(e){this.mod._lt_torrent_resume(e)}forceRecheck(e){this.mod._lt_torrent_force_recheck(e)}saveResumeData(e,t=8e3){return this.mod._lt_torrent_save_resume_data(e),new Promise((n,r)=>{let i={handle:e,resolve:n};this.resumeWaiters.push(i),setTimeout(()=>{let e=this.resumeWaiters.indexOf(i);e>=0&&(this.resumeWaiters.splice(e,1),r(/* @__PURE__ */ Error(`save_resume_data timed out`)))},t)})}peers(e,t=4e3){return this.mod._lt_torrent_post_peers(e),this.awaitList(this.peerWaiters,this.peersByHandle,e,t)}lastPeers(e){return this.peersByHandle.get(e)??[]}trackers(e,t=4e3){return this.mod._lt_torrent_post_trackers(e),this.awaitList(this.trackerWaiters,this.trackersByHandle,e,t)}lastTrackers(e){return this.trackersByHandle.get(e)??[]}awaitList(e,t,n,r){return new Promise(i=>{let a={handle:n,resolve:i,timer:setTimeout(()=>{let r=e.indexOf(a);r>=0&&(e.splice(r,1),i(t.get(n)??[]))},r)};e.push(a)})}resolveOne(e,t,n){for(let r=e.length-1;r>=0;r--){let i=e[r];i.handle===t&&(clearTimeout(i.timer),e.splice(r,1),i.resolve(n))}}files(e){return this.filesByHandle.get(e)??null}bitfield(e){let t=this.bitfieldByHandle.get(e),n=this.filesByHandle.get(e);return!t||!n?null:{pieces:t.pieces,numPieces:t.numPieces,pieceLength:n.pieceLength,length:n.totalSize}}status(e){return this.statusByHandle.get(e)??null}async read(e,t,n,r,i={}){let a=this.filesByHandle.get(e);if(!a)throw Error(`read: no layout for handle ${e} (metadata not ready)`);let o=a.files[t];if(!o)throw Error(`read: no file ${t}`);if(!this.storage)throw Error(`read: no storage backend configured`);if(n<0)throw RangeError(`read: negative offset ${n}`);let s=Math.min(r,o.size-n);if(s<=0)return/* @__PURE__ */ new Uint8Array;let{pieceLength:c}=a,l=o.offset+n,u=Math.floor(l/c),d=Math.min(a.numPieces-1,Math.floor((l+s-1)/c));if(!this.hasPieces(e,u,d)){let t=i.deadlineMs===void 0?0:i.deadlineMs;if(t!==null){for(let n=u;n<=d;n++)this.mod._lt_torrent_set_piece_deadline(e,n,t,0);this.retainDeadlines(e,u,d)}this.mod._lt_torrent_post_status(e);try{await this.awaitPieces(e,u,d,i)}finally{t!==null&&this.releaseDeadlines(e,u,d)}}let f=await this.storage.read(a.storageIndex,t,n,s);return f instanceof Uint8Array?f:new Uint8Array(f)}setStreamWindow(e,t,n={}){let r=this.filesByHandle.get(e);if(!r)return!1;let{pieceLength:i,numPieces:a}=r,o=Math.max(1,Math.floor(n.windowPieces??Ac)),s=Math.max(0,Math.floor(n.deadlineStepMs??jc)),c=n.claimedPriority??W.normal,l=n.unclaimedPriority??W.normal,u=new Uint8Array(a).fill(l),d=n.keep&&new Uint8Array(a);if(d)for(let{start:e,end:t}of n.keep)d.fill(1,Math.max(0,e),Math.max(0,t));let f=/* @__PURE__ */ new Map,p=0;for(let e of t){let t=r.files[e.fileIndex];if(!t||t.size<=0)continue;p++;let n=Math.floor(t.offset/i),l=Math.min(a-1,Math.floor((t.offset+t.size-1)/i));for(let e=n;e<=l;e++)(!d||d[e])&&(u[e]=c);let m=Math.min(Math.max(e.offset,0),Math.max(0,t.size-1)),h=Math.min(Math.max(Math.floor((t.offset+m)/i),n),l);for(let e=0;e<o;e++){let t=h+e;if(t>l)break;u[t]=W.top;let n=e*s,r=f.get(t);(r===void 0||n<r)&&f.set(t,n)}}if(!p)return!1;if(this.mod._lt_torrent_clear_piece_deadlines(e),this.prioritizePieces(e,u),n.deadlines!==!1)for(let[t,n]of f)this.mod._lt_torrent_set_piece_deadline(e,t,n,0);return this.reissueReadDeadlines(e),n.sequential!==!1&&this.setSequential(e,!0),!0}clearStreamWindow(e){this.mod._lt_torrent_clear_piece_deadlines(e);let t=this.filesByHandle.get(e);t&&this.prioritizePieces(e,new Uint8Array(t.numPieces).fill(W.normal)),this.reissueReadDeadlines(e),this.setSequential(e,!1)}prioritizeRange(e,t,n,r){let i=this.filesByHandle.get(e),a=i?.files[t];if(!i||!a)return;let{pieceLength:o,numPieces:s}=i,c=Math.min(r,a.size-n);if(c<=0)return;let l=Math.max(0,Math.floor((a.offset+n)/o)),u=Math.min(s-1,Math.floor((a.offset+n+c-1)/o));if(u<l)return;let d=new Uint8Array(s).fill(W.normal);for(let e=l;e<=u;e++)d[e]=W.top;this.mod._lt_torrent_clear_piece_deadlines(e),this.prioritizePieces(e,d);for(let t=l;t<=u;t++)this.mod._lt_torrent_set_piece_deadline(e,t,(t-l)*jc,0);this.reissueReadDeadlines(e)}setSequential(e,t){this.mod._lt_torrent_set_sequential(e,+!!t)}setFlags(e,t,n){this.mod._lt_torrent_set_flags(e,t>>>0,n>>>0)}setFlag(e,t,n){this.setFlags(e,n?t:0,t)}forceReannounce(e){this.mod._lt_torrent_force_reannounce(e)}moveInQueue(e,t){this.mod._lt_torrent_queue_position(e,Dc[t])}setRateLimits({download:e,upload:t,limitLocalPeers:n}){let r=e=>e==null?-1:Math.max(0,Math.floor(e));this.mod._lt_session_set_rate_limits(r(e),r(t),n==null?-1:+!!n)}setUploadLimit(e,t){this.mod._lt_torrent_set_upload_limit(e,Math.max(0,Math.floor(t)))}setDownloadLimit(e,t){this.mod._lt_torrent_set_download_limit(e,Math.max(0,Math.floor(t)))}setPieceDeadline(e,t,n,r=!1){this.mod._lt_torrent_set_piece_deadline(e,t,n,+!!r)}clearPieceDeadlines(e){this.mod._lt_torrent_clear_piece_deadlines(e),this.reissueReadDeadlines(e)}resetPieceDeadline(e,t){this.mod._lt_torrent_reset_piece_deadline(e,t)}cancelPieceRequests(e,t){return this.mod._lt_torrent_cancel_piece_requests(e,t)===0}forgetPieces(e,t){let n=[...t];this.drainAlerts();let r=this.mod,i=r._malloc(n.length*4+4),a=i+n.length*4;try{for(let e=0;e<n.length;e++)r.HEAP32[(i>>2)+e]=n[e]|0;r.HEAP32[a>>2]=0;let t=r._lt_torrent_forget_pieces(e,i,n.length,a);if(t<0)return null;let o=this.bitfieldByHandle.get(e);if(o)for(let e of n)e>=0&&e<o.numPieces&&(o.pieces[e>>3]&=~(128>>(e&7)));return{forgotten:t,busy:r.HEAP32[a>>2]}}finally{r._free(i)}}prioritizePieces(e,t){let n=this.mod,r=this.filesByHandle.get(e);if(!r||!r.numPieces)return;let i=t;if(i.length!==r.numPieces){let t=new Uint8Array(r.numPieces),n=this.priosByHandle.get(e);n?t.set(n.subarray(0,r.numPieces)):t.fill(W.normal),t.set(i.subarray(0,r.numPieces)),i=t}let a=n._malloc(i.length);n.HEAPU8.set(i,a);try{n._lt_torrent_prioritize_pieces(e,a,i.length)===0&&this.priosByHandle.set(e,Uint8Array.from(i,e=>Math.min(e,W.top)))}finally{n._free(a)}}prioritizePieceList(e,t){let n=this.mod,r=this.filesByHandle.get(e);if(!r)return;let i=[...t].filter(e=>e.piece>=0&&e.piece<r.numPieces);if(!i.length)return;let a=n._malloc(i.length*4),o=n._malloc(i.length);try{let t=this.priosByHandle.get(e);for(let e=0;e<i.length;e++){let{piece:r,priority:s}=i[e],c=Math.min(Math.max(s,0),W.top);n.HEAP32[(a>>2)+e]=r,n.HEAPU8[o+e]=c,t&&r<t.length&&(t[r]=c)}n._lt_torrent_prioritize_piece_list(e,a,o,i.length)}finally{n._free(a),n._free(o)}}setFilePriorities(e,t){let n=this.mod;if(!t.length)return;let r=n._malloc(t.length);n.HEAPU8.set(t,r);try{n._lt_torrent_prioritize_files(e,r,t.length)}finally{n._free(r)}this.priosByHandle.delete(e)}setFilePriority(e,t,n){let r=this.mod._lt_torrent_set_file_priority(e,t,n)===0;return r&&this.priosByHandle.delete(e),r}piecePriorities(e){let t=this.priosByHandle.get(e);return t?Uint8Array.from(t):null}retainDeadlines(e,t,n){let r=this.deadlineRefs.get(e);r||this.deadlineRefs.set(e,r=/* @__PURE__ */ new Map);for(let e=t;e<=n;e++)r.set(e,(r.get(e)??0)+1)}releaseDeadlines(e,t,n){let r=this.deadlineRefs.get(e);if(!r)return;let i=[],a=this.priosByHandle.get(e);for(let o=t;o<=n;o++){let t=(r.get(o)??0)-1;if(t>0){r.set(o,t);continue}r.delete(o),this.mod._lt_torrent_reset_piece_deadline(e,o),i.push({piece:o,priority:a?.[o]??W.normal})}i.length&&this.prioritizePieceList(e,i),r.size||this.deadlineRefs.delete(e)}reissueReadDeadlines(e){let t=this.deadlineRefs.get(e);if(t)for(let n of t.keys())this.mod._lt_torrent_set_piece_deadline(e,n,0,0)}postStatus(e){this.mod._lt_torrent_post_status(e)}infohash(e){return this.readHash(e,this.mod._lt_torrent_infohash)}infohashV2(e){return this.readHash(e,this.mod._lt_torrent_infohash_v2)}readHash(e,t){let n=this.mod,r=n._malloc(65);try{return t.call(n,e,r)===0?n.UTF8ToString(r):null}finally{n._free(r)}}hasPieces(e,t,n){let r=this.bitfieldByHandle.get(e);if(!r)return!1;for(let e=t;e<=n;e++){if(e<0||e>=r.numPieces)return!1;let t=r.pieces[e>>3];if(t===void 0||!(t&128>>(e&7)))return!1}return!0}awaitPieces(e,t,n,r){let{signal:i}=r,a=r.timeoutMs??kc;return new Promise((r,o)=>{let s,c,l=e=>{let t=this.pieceWaiters.indexOf(u);t<0||(this.pieceWaiters.splice(t,1),s!==void 0&&clearTimeout(s),c&&i&&i.removeEventListener(`abort`,c),e?o(e):r())},u={handle:e,p0:t,p1:n,settle:l};if(this.pieceWaiters.push(u),i?.aborted){l(/* @__PURE__ */ Error(`read: aborted`));return}a>0&&(s=setTimeout(()=>l(/* @__PURE__ */ Error(`read: pieces ${t}-${n} of handle ${e} did not arrive within ${a}ms`)),a)),i&&(c=()=>l(/* @__PURE__ */ Error(`read: aborted`)),i.addEventListener(`abort`,c,{once:!0}))})}resolvePieceWaiters(){if(this.pieceWaiters.length!==0)for(let e of[...this.pieceWaiters])this.hasPieces(e.handle,e.p0,e.p1)&&e.settle()}failPieceWaiters(e,t){for(let n of[...this.pieceWaiters])(t===void 0||n.handle===t)&&n.settle(e)}popAlerts(){this.drainAlerts();let e=this.textAlerts;return this.textAlerts=[],e}drainAlerts(){let e=this.mod;e._lt_session_pump_alerts();let t=e._lt_alerts_size()>>>0;if(!t)return;let n=e._lt_alerts_data()>>>0,r=new DataView(e.HEAPU8.buffer,n,t),i=this.textAlerts,a=0;try{for(;a+8<=t;){let o=r.getUint32(a,!0);a+=4;let s=r.getUint32(a,!0);if(a+=4,a+s>t)break;if(o===yc)this.decodeTorrentReady(r,a);else if(o===bc)this.decodeStateUpdate(r,a);else if(o===Sc)this.decodeResumeData(r,a,s);else if(o===Cc)this.decodePeers(r,a);else if(o===wc)this.decodeTrackers(r,a);else if(o!==xc){let t={type:o,message:e.UTF8ToString(n+a,s)};this.observeReachability(t.message),i.push(t)}a+=s}}finally{e._lt_alerts_clear(),this.resolvePieceWaiters()}}reachable(){let e=this.reachability.port,t=this.listeners();return{listening:{...this.reachability.listening},listenFailed:[...this.reachability.listenFailed],inbound:this.reachability.inbound,inboundByTransport:{...this.reachability.inboundByTransport},lastInbound:this.reachability.lastInbound,port:e,listeners:t,portOpen:e!==null&&t.some(t=>t.up&&t.port===e)}}listeners(){let e=this.mod.__FKN;try{return e?.listeners?.()??[]}catch{return[]}}observeReachability(e){let t=hc.exec(e);if(t){let e=t[2].toLowerCase();this.reachability.inbound++,this.reachability.inboundByTransport[e]=(this.reachability.inboundByTransport[e]??0)+1,this.reachability.lastInbound={endpoint:t[1],transport:e,at:Date.now()};return}let n=gc.exec(e);if(n){this.reachability.listening[n[1].toLowerCase()]=n[2];return}_c.test(e)&&this.reachability.listenFailed.length<32&&this.reachability.listenFailed.push(e)}readStr(e,t){let n=e.getUint32(t,!0);return t+=4,[vc.decode(new Uint8Array(e.buffer,e.byteOffset+t,n)),t+n]}decodePeers(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getUint32(t,!0);t+=4;let i=[];for(let n=0;n<r;n++){let n,r;[n,t]=this.readStr(e,t),[r,t]=this.readStr(e,t);let a=e.getUint32(t,!0);t+=4;let o=e.getUint32(t,!0);t+=4;let s=e.getUint32(t,!0);t+=4;let c=e.getInt32(t,!0);t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=Number(e.getBigInt64(t,!0));t+=8;let p=Number(e.getBigInt64(t,!0));t+=8;let m=e.getInt32(t,!0)/1e6;t+=4;let h=e.getInt32(t,!0);t+=4;let g=e.getInt32(t,!0);t+=4;let _=e.getInt32(t,!0);t+=4;let v=e.getInt32(t,!0);t+=4,i.push({endpoint:n,client:r,flags:a,source:o,connectionType:s,downloadRate:c,uploadRate:l,payloadDownloadRate:u,payloadUploadRate:d,totalDownload:f,totalUpload:p,progress:m,rtt:h,numPieces:g,requestsInFlight:_,failCount:v})}this.peersByHandle.set(n,i),this.resolveOne(this.peerWaiters,n,i)}decodeTrackers(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getUint32(t,!0);t+=4;let i=[];for(let n=0;n<r;n++){let n,r;[n,t]=this.readStr(e,t),[r,t]=this.readStr(e,t);let a=e.getInt32(t,!0);t+=4;let o=e.getInt32(t,!0);t+=4;let s=e.getUint32(t,!0)!==0;t+=4;let c=e.getUint32(t,!0)!==0;t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=e.getInt32(t,!0);t+=4,i.push({url:n,message:r,tier:a,fails:o,updating:s,verified:c,nextAnnounceIn:l,seeders:u,leechers:d,downloaded:f})}this.trackersByHandle.set(n,i),this.resolveOne(this.trackerWaiters,n,i)}decodeResumeData(e,t,n){let r=e.getUint32(t,!0),i=new Uint8Array(n-4);i.set(new Uint8Array(e.buffer,e.byteOffset+t+4,n-4)),this.resumeByHandle.set(r,i),this.resumeWaiters=this.resumeWaiters.filter(e=>e.handle!==r||(e.resolve(i),!1))}decodeTorrentReady(e,t){let n=new TextDecoder,r=e.getUint32(t,!0);t+=4;let i=e.getUint32(t,!0);t+=4;let a=e.getUint32(t,!0);t+=4;let o=e.getUint32(t,!0);t+=4;let s=Number(e.getBigInt64(t,!0));t+=8;let c=e.getUint32(t,!0);t+=4;let l=[];for(let r=0;r<c;r++){let r=Number(e.getBigInt64(t,!0));t+=8;let i=Number(e.getBigInt64(t,!0));t+=8;let a=e.getUint8(t)===1;t+=1;let o=e.getUint32(t,!0);t+=4;let s=n.decode(new Uint8Array(e.buffer,e.byteOffset+t,o));t+=o,l.push({path:s,size:i,offset:r,pad:a})}let u=l.reduce((e,t)=>e+(t.pad?0:t.size),0);this.filesByHandle.set(r,{storageIndex:i,pieceLength:a,numPieces:o,totalSize:s,contentSize:u,files:l})}decodeStateUpdate(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getInt32(t,!0);t+=4;let i=Number(e.getBigInt64(t,!0));t+=8;let a=Number(e.getBigInt64(t,!0));t+=8;let o=e.getFloat32(t,!0);t+=4;let s=e.getInt32(t,!0);t+=4;let c=e.getInt32(t,!0);t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getUint32(t,!0)!==0;t+=4;let f=e.getUint32(t,!0)!==0;t+=4;let p=e.getUint32(t,!0)!==0;t+=4;let m=e.getUint32(t,!0)>>>0;t+=4;let h=Number(e.getBigInt64(t,!0));t+=8;let g=Number(e.getBigInt64(t,!0));t+=8;let _=Number(e.getBigInt64(t,!0));t+=8;let v=Number(e.getBigInt64(t,!0));t+=8;let y=Number(e.getBigInt64(t,!0));t+=8;let b=Number(e.getBigInt64(t,!0));t+=8;let x=Number(e.getBigInt64(t,!0));t+=8;let S=e.getInt32(t,!0);t+=4;let C=e.getInt32(t,!0);t+=4;let w=e.getInt32(t,!0);t+=4;let T=e.getInt32(t,!0);t+=4,t+=4;let E=e.getFloat32(t,!0);t+=4;let D=e.getInt32(t,!0);t+=4;let O=e.getInt32(t,!0);t+=4;let k=Number(e.getBigInt64(t,!0));t+=8;let A=Number(e.getBigInt64(t,!0));t+=8;let j=Number(e.getBigInt64(t,!0));t+=8;let M=e.getUint32(t,!0)!==0;t+=4;let ee;[ee,t]=this.readStr(e,t);let N=e.getInt32(t,!0);t+=4;let P=e.getInt32(t,!0);t+=4;let F=e.getUint32(t,!0);t+=4;let I=F?vc.decode(new Uint8Array(e.buffer,e.byteOffset+t,F)):``;t+=F;let L=e.getUint32(t,!0);t+=4;let R=e.getUint32(t,!0);t+=4;let z=new Uint8Array(R);z.set(new Uint8Array(e.buffer,e.byteOffset+t,R)),this.bitfieldByHandle.set(n,{pieces:z,numPieces:L});let te=0;for(let e=0;e<R;e++){let t=z[e];for(;t;)te+=t&1,t>>=1}this.statusByHandle.set(n,{state:r,progress:o,totalDone:i,totalWanted:a,downloadRate:s,uploadRate:c,numPeers:l,numSeeds:u,numPiecesTotal:L,numPiecesHave:te,paused:d,autoManaged:f,sequential:p,flags:m,queuePosition:N,errorCode:P,error:I,allTimeDownload:h,allTimeUpload:g,sessionDownload:_,sessionUpload:v,sessionPayloadDownload:y,sessionPayloadUpload:b,wasted:x,swarmSeeds:S,swarmPeers:C,numConnections:w,connectionsLimit:T,availability:E,activeSeconds:D,seedingSeconds:O,addedAt:k,completedAt:A,lastSeenComplete:j,hadIncoming:M,savePath:ee,hasMetadata:r!==mc.downloadingMetadata})}async*alerts(){for(;!this.destroyed;){for(let e of this.popAlerts())yield e;await new Promise(e=>setTimeout(e,100))}}setReservedPort(e){this.reachability.port=e}tick(){if(!this.destroyed&&(this.mod._lt_session_tick(),this.pieceWaiters.length)){let e=new Set(this.pieceWaiters.map(e=>e.handle));for(let t of e)this.mod._lt_torrent_post_status(t)}}destroy(){this.destroyed||(this.destroyed=!0,this.fallbackTimer!=null&&clearInterval(this.fallbackTimer),this.failPieceWaiters(/* @__PURE__ */ Error(`read: session destroyed`)),this.pieceWaiters=[],this.resumeWaiters=[],this.deadlineRefs.clear(),this.priosByHandle.clear(),this.mod._lt_session_destroy(),this.mod.__FKN?.teardown?.())}},Nc=8e3,Pc=e=>{try{e?.close()}catch{}},Fc=(e,t)=>new Promise(n=>{let r;try{r=e()}catch{n(null);return}if(!r||typeof r.on!=`function`){n(null);return}let i=!1,a=()=>{i||(i=!0,clearTimeout(o),Pc(r),n(null))},o=setTimeout(a,Nc);r.on(`listening`,()=>{i||(i=!0,clearTimeout(o),n(r))}),r.on(`error`,a);try{t(r)}catch{a()}});async function Ic(e,t,n=4){try{return await Lc(e,t,n)}catch{return null}}async function Lc(e,t,n){for(let r=0;r<n;r++){let i=await Fc(()=>t.createSocket({type:`udp4`}),e=>e.bind(0,`0.0.0.0`));if(!i)return null;let a=i.address?.()?.port;if(!a)return Pc(i),null;let o=await Fc(()=>e.createServer(),e=>e.listen(a,`0.0.0.0`)),s=o?o.address?.()?.port:void 0,c=!!o&&s===a;if(o&&!c&&Pc(o),!c){if(r<n-1){Pc(i);continue}return{port:a,server:null,udp:i,backlog:[],adopted:!1}}let l={port:a,server:o,udp:i,backlog:[],adopted:!1};return o.on(`connection`,e=>{l.adopted||l.backlog.push(e)}),l}return null}async function Rc(e){let t=e.moduleFactory??(await import(`./libtorrent-BazNmFSU.js`)).default,n={net:e.net,dgram:e.dgram,storage:e.storage??null,debug:e.debug??!1},r=e.reserveListenPort===!1?Promise.resolve(null):Ic(e.net,e.dgram),i=await t({fkn:n});i._lt_set_log(+!!e.debug);let a=await r;a?(n.prebound=a,i._lt_set_listen_port(a.port),!a.server&&e.debug&&console.warn(`[fkn] reserved udp ${a.port} but no matching tcp listener: inbound uTP works, inbound TCP is dark`)):e.debug&&console.warn(`[fkn] nothing reserved: the announced port is not one anyone can reach`);let o;try{o=new Mc(i,e)}catch(e){throw a&&!a.adopted&&(Pc(a.server),Pc(a.udp)),e}return o.setReservedPort(a?a.port:null),o}const zc=e=>{let t=e.match(/xt=urn:btih:([0-9a-z]+)/i);if(t)return t[1].toLowerCase();let n=e.match(/xt=urn:btmh:([0-9a-f]+)/i);if(!n)return null;let r=n[1].toLowerCase();return r.startsWith(`1220`)&&r.length===68?r.slice(4):r},Bc=25e5,Vc=e=>{if(!Number.isFinite(e)||e<=0)return 12;let t=Math.ceil(Bc/e)+1,n=Math.max(2,Math.floor(8388608/e));return Math.min(Math.max(t,2),n)},Hc=e=>Vc(e)*Math.max(0,e),Uc=e=>Math.max(1,Math.floor(Hc(e)/2)),Wc=(e,t)=>Math.min(2e3,Math.max(50,Math.round(e/Math.max(t,25e4)*1e3))),Gc=(e,t,n,r=Bc)=>{let i=e.fileOffset+n+Math.max(0,r-1);return Math.floor(i/e.pieceLength)>=e.p1?!1:Math.abs(n-t)>=Uc(e.pieceLength)};var Kc=class{storages=/* @__PURE__ */ new Map;opened=/* @__PURE__ */ new Map;onNewStorage(e,t,n){let r=(async()=>{let r=await qc(await navigator.storage.getDirectory(),t.replace(/^\/+/,``));this.storages.set(e,{rootDir:r,files:/* @__PURE__ */ new Map,opening:/* @__PURE__ */ new Map,fileMeta:n})})();return this.opened.set(e,r),r.then(()=>{this.opened.get(e)===r&&this.opened.delete(e)},()=>{}),r}async onRemoveStorage(e){this.opened.delete(e);let t=this.storages.get(e);if(t){for(let e of t.files.values())try{e.close()}catch{}this.storages.delete(e)}}read(e,t,n,r){let i=this.openFile(e,t),a=e=>{let t=new Uint8Array(r),i=e.read(t,{at:n});return i<r&&t.fill(0,i),t};return i instanceof Promise?i.then(a):a(i)}write(e,t,n,r){let i=this.openFile(e,t),a=i=>{try{let a=i.write(r,{at:n});if(a<r.length)throw console.error(`[opfs] short write`,{id:e,fileIndex:t,offset:n,want:r.length,wrote:a}),Error(`short write`)}catch(i){throw console.error(`[opfs] write failed`,{id:e,fileIndex:t,offset:n,len:r.length,err:String(i),errName:i?.name,errMsg:i?.message,isView:ArrayBuffer.isView(r),bytesType:Object.prototype.toString.call(r)}),i}};return i instanceof Promise?i.then(a).catch(n=>{throw console.error(`[opfs] openFile failed`,{id:e,fileIndex:t,err:String(n)}),n}):a(i)}async release(e){let t=this.storages.get(e);if(t){for(let e of t.files.values())try{e.flush(),e.close()}catch{}t.files.clear()}}async stop(e){return this.release(e)}async check(e){let t=!1;if(await this.opened.get(e)?.catch(()=>{t=!0}),t)return 2;let n=this.storages.get(e);if(!n)return 0;await this.release(e);for(let e of n.fileMeta)if(await this.hasBytes(n,e.path))return 2;return 0}async hasBytes(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(!r)return!1;let i=e.rootDir;try{for(let e of n)i=await i.getDirectoryHandle(e);return(await(await i.getFileHandle(r)).getFile()).size>0}catch(e){return e?.name!==`NotFoundError`}}async deleteFiles(e,t){let n=this.storages.get(e);if(n){for(let e of n.files.values())try{e.close()}catch{}n.files.clear();for(let e of n.fileMeta){let t=e.path.split(`/`).filter(Boolean),r=t.pop();if(!r)continue;let i=n.rootDir;for(let e of t)try{i=await i.getDirectoryHandle(e)}catch{i=null;break}if(i)try{await i.removeEntry(r)}catch{}}}}openFile(e,t){let n=this.storages.get(e);if(!n)throw Error(`unknown storage ${e}`);let r=n.files.get(t);if(r)return r;let i=n.opening.get(t);if(i)return i;let a=this.openFileSlow(e,t);return n.opening.set(t,a),a.finally(()=>n.opening.delete(t)),a}async openFileSlow(e,t){let n=this.storages.get(e),r=n.fileMeta[t];if(!r)throw Error(`unknown file ${t}`);let i=r.path.split(`/`).filter(Boolean),a=i.pop(),o=n.rootDir;for(let e of i)o=await o.getDirectoryHandle(e,{create:!0});let s=await(await o.getFileHandle(a,{create:!0})).createSyncAccessHandle();return n.files.set(t,s),s}};async function qc(e,t){if(!t)return e;let n=e;for(let e of t.split(`/`).filter(Boolean))n=await n.getDirectoryHandle(e,{create:!0});return n}var Jc=(e,t,n)=>{let r=e.write(t,n);if(r<t.byteLength){let e=`the storage quota took ${r} of ${t.byteLength} bytes`,n=globalThis.QuotaExceededError;throw n?new n(e):new DOMException(e,`QuotaExceededError`)}return r};const Yc=[50,150,400,900,1500],Xc=e=>e?.name===`QuotaExceededError`,Zc=e=>new Promise(t=>setTimeout(t,e)),Qc=e=>{let t=async(t,n,r,i)=>{let a=i;for(let i of Yc){if(Xc(a))break;if(n(),await Zc(i),e.has(t))throw a;try{return await r()}catch(e){a=e}}throw a};return(e,n,r)=>{try{let i=r();return i instanceof Promise?i.catch(i=>t(e,n,r,i)):i}catch(i){return t(e,n,r,i)}}},$c=()=>{let e=new Kc,t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=e,a=(e,t)=>{let n=i.storages?.get(e),r=n?.files?.get(t);if(r){n.files.delete(t);try{r.close()}catch{}}},o=async(e,t)=>{let r=n.get(e);if(r===void 0)return null;let a=i.storages?.get(r);if(!a?.fileMeta||!a.rootDir)return null;let o=0;for(let e=0;e<a.fileMeta.length;e++){if(t!==void 0&&e!==t)continue;let n=a.files?.get(e);if(n)try{o+=n.getSize();continue}catch{}let r=a.fileMeta[e].path.split(`/`).filter(Boolean),i=r.pop();if(!i)continue;let s=a.rootDir;for(let e of r)s=s?await s.getDirectoryHandle(e).catch(()=>null):null;s&&(o+=await s.getFileHandle(i).then(e=>e.getFile()).then(e=>e.size).catch(()=>0))}return o},s=Qc(t),c=(e,t,n)=>s(e,()=>a(e,t),n),l=(e,t,n,a)=>{let o=i=>{try{Jc(i,a,{at:n})}catch(n){throw Xc(n)&&r.set(e,t),n}},s=i.openFile(e,t);return s instanceof Promise?s.then(o):o(s)};return{usageOf:o,refusedFile:e=>{let t=n.get(e);return t===void 0?void 0:r.get(t)},onNewStorage:(i,a,o)=>(t.delete(i),r.delete(i),n.set(a,i),c(i,-1,()=>e.onNewStorage(i,a,o))),onRemoveStorage:r=>{t.add(r);for(let[e,t]of n)t===r&&n.delete(e);return e.onRemoveStorage(r)},read:(t,n,r,i)=>c(t,n,()=>e.read(t,n,r,i)),write:(e,t,n,r)=>c(e,t,()=>l(e,t,n,r)),release:t=>e.release(t),check:t=>e.check(t).catch(()=>2),deleteFiles:(n,r)=>(t.add(n),e.deleteFiles(n,r)),stop:t=>e.stop(t)}},el=67108864,tl=/^(\d+)-(\d+)$/,nl=/^\d+$/,rl=(e=el)=>{let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Set,o=Qc(a),s=/* @__PURE__ */ new Map,c=(e,t,n)=>{let r=`${e}/${t}`,i=s.get(r);i||s.set(r,i=/* @__PURE__ */ new Set),i.add(n);let a=()=>{i.delete(n),!i.size&&s.get(r)===i&&s.delete(r)};n.then(a,a)},l=(e,t)=>`${e}-${t}`,u=e=>{let n=r.get(e);return n===void 0?void 0:t.get(n)},d=(e,r)=>{let i=t.get(e);if(i)return r(i);let a=n.get(e);if(!a)throw Error(`unknown storage ${e}`);return a.then(r)},f=(e,t,n,r)=>{let i=[];for(let a=0;a<r;){let o=Math.floor((n+a)/e.chunkBytes),s=n+a-o*e.chunkBytes,c=Math.min(r,a+e.chunkBytes-s);i.push({name:l(t,o),at:s,from:a,to:c}),a=c}return i},p=(e,t)=>{let n=e.handles.get(t);if(n)return n;let r=e.opening.get(t);if(r)return r;let i=e.dropping.get(t),a=(async()=>{i&&await i;let n=await(await e.dir.getFileHandle(t,{create:!0})).createSyncAccessHandle();return e.handles.set(t,n),n})();e.opening.set(t,a);let o=()=>{e.opening.get(t)===a&&e.opening.delete(t)};return a.then(o,o),a},m=(e,n,r,i)=>{let a=t.get(e);if(a)for(let{name:e}of f(a,n,r,i)){let t=a.handles.get(e);a.handles.delete(e);try{t?.close()}catch{}}},h=e=>{for(let t of e.handles.values())try{t.flush(),t.close()}catch{}e.handles.clear()},g=(e,t)=>{let n=0;for(let[r,i]of e.extents)(t===void 0||r.startsWith(`${t}-`))&&(n+=i);return n},_=async t=>{let n=t.split(`/`).filter(Boolean),r=n.pop()??``,i=await navigator.storage.getDirectory();for(let e of n)i=await i.getDirectoryHandle(e,{create:!0});let a=await i.getDirectoryHandle(r,{create:!0}),o=e=>e.values(),s=e;for await(let e of o(a))e.kind===`directory`&&nl.test(e.name)&&(s=Number(e.name));let c=await a.getDirectoryHandle(String(s),{create:!0}),l=/* @__PURE__ */ new Map;for await(let e of o(c))e.kind===`file`&&l.set(e.name,await e.getFile().then(e=>e.size,()=>s));return{parent:i,name:r,chunkBytes:s,dir:c,extents:l,handles:/* @__PURE__ */ new Map,opening:/* @__PURE__ */ new Map,dropping:/* @__PURE__ */ new Map}};return{chunkBytesOf:t=>u(t)?.chunkBytes??e,chunksOf:(e,t)=>{let n=u(e);if(!n)return[];let r=[];for(let[e,i]of n.extents){let n=tl.exec(e);n&&Number(n[1])===t&&i>0&&r.push(Number(n[2]))}return r.sort((e,t)=>e-t)},footprint:()=>{let e=0;for(let n of t.values())e+=g(n);return e},usageOf:async(e,i)=>{let a=r.get(e);if(a===void 0)return null;let o=t.get(a)??await n.get(a)?.catch(()=>void 0);return o?g(o,i):null},refusedFile:e=>{let t=r.get(e);return t===void 0?void 0:i.get(t)},drop:(e,t,n)=>{let r=u(e);if(!r)return Promise.resolve();let i=l(t,n),a=r.dropping.get(i);if(a)return a;r.extents.delete(i);let o=r.handles.get(i);r.handles.delete(i);try{o?.close()}catch{}let s=r.opening.get(i),c=(async()=>{s&&await s.then(e=>{r.handles.get(i)===e&&r.handles.delete(i);try{e.close()}catch{}},()=>{}),await r.dir.removeEntry(i).catch(()=>{})})();return r.dropping.set(i,c),c.then(()=>{r.dropping.get(i)===c&&r.dropping.delete(i)}),c},readChunk:async(e,t,n)=>{let r=u(e),i=l(t,n);if(!r?.extents.has(i))return/* @__PURE__ */ new Uint8Array;let a=await p(r,i),o=new Uint8Array(a.getSize());return a.read(o,{at:0}),o},onNewStorage:(e,s)=>{a.delete(e),i.delete(e),r.set(s,e);let c=Promise.resolve(o(e,()=>{},()=>_(s)));return n.set(e,c),c.then(r=>{n.get(e)===c&&(n.delete(e),t.set(e,r))})},onRemoveStorage:e=>{a.add(e),n.delete(e);let i=t.get(e);t.delete(e);for(let[t,n]of r)n===e&&r.delete(t);i&&h(i)},read:(e,t,n,r)=>o(e,()=>m(e,t,n,r),()=>d(e,i=>{let a=new Uint8Array(r),o=[];for(let c of f(i,t,n,r)){let t=()=>{if(!i.extents.has(c.name))return;let e=e=>{e.read(a.subarray(c.from,c.to),{at:c.at})},t=p(i,c.name);if(t instanceof Promise)return t.then(e);e(t)},n=s.get(`${e}/${c.name}`);if(n)o.push(Promise.allSettled([...n]).then(t));else{let e=t();e&&o.push(e)}}return o.length?Promise.all(o).then(()=>a):a})),write:(e,r,a,s)=>{let l=o(e,()=>m(e,r,a,s.length),()=>d(e,t=>{let n=[];for(let o of f(t,r,a,s.length)){let a=n=>{try{Jc(n,s.subarray(o.from,o.to),{at:o.at})}catch(a){Xc(a)&&i.set(e,r);try{t.extents.set(o.name,n.getSize())}catch{}throw a}let a=o.at+o.to-o.from;(t.extents.get(o.name)??0)<a&&t.extents.set(o.name,a)},c=p(t,o.name);c instanceof Promise?n.push(c.then(a)):a(c)}return n.length?Promise.all(n).then(()=>{}):void 0}));if(l instanceof Promise){let i=t=>{for(let{name:n}of f(t,r,a,s.length))c(e,n,l)},o=t.get(e);o?i(o):n.get(e)?.then(i,()=>{})}return l},check:async e=>{try{let r=t.get(e)??await n.get(e);return r&&g(r)>0?2:0}catch{return 2}},release:async e=>{let n=t.get(e);n&&h(n)},stop:async e=>{let n=t.get(e);n&&h(n)},deleteFiles:async e=>{a.add(e);let r=t.get(e)??await n.get(e)?.catch(()=>void 0);r&&(await Promise.all([...r.opening.values()].map(e=>e.catch(()=>{}))),h(r),r.extents.clear(),await r.parent.removeEntry(r.name,{recursive:!0}).catch(()=>{}))}}},il=[5e3,15e3,3e4,6e4,12e4,3e5],al=1e4,ol=/* @__PURE__ */ new Set([2,3]),sl=/* @__PURE__ */ new Set([1,7]),cl=e=>!!e&&e.paused&&!e.autoManaged,ll=()=>{let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=e=>il[Math.min(e,il.length-1)],a=i=>{e.delete(i),t.delete(i),n.delete(i),r.delete(i)};return{hold:(e,t,n=al)=>r.set(e,t+n),observe:(o,s,c,l)=>{if(c){a(o);return}if(!s)return;let u=r.get(o);if(u!==void 0){if(l<u)return;r.delete(o)}let d=t.get(o);(!d||s.totalDone>d.totalDone)&&t.set(o,{totalDone:s.totalDone,at:l});let f=t.get(o).at;if(sl.has(s.state))return;let p=e.get(o);if(s.error&&(n.set(o,s.error),p&&(p.message=s.error)),p&&l<p.graceUntil||s.paused&&s.queued)return;let m=s.paused?`stopped`:ol.has(s.state)&&s.numPeers===0&&s.downloadRate===0&&l-f>=12e4?`stalled`:null;if(!m){if(!p)return;p.healthySince??=l,l-p.healthySince>=6e4&&a(o);return}if(!p){e.set(o,{reason:m,attempt:0,retryAt:l+i(0),message:n.get(o),healthySince:null,graceUntil:0});return}p.reason=m,p.healthySince!==null&&(p.healthySince=null,p.retryAt=l+i(p.attempt))},due:t=>{let n=[];for(let[r,a]of e)a.healthySince!==null||t<a.retryAt||(a.attempt++,a.retryAt=t+i(a.attempt),a.graceUntil=t+al,n.push({handle:r,reason:a.reason}));return n},retryNow:t=>{for(let n of e.values())n.healthySince===null&&(n.attempt=0,n.retryAt=t)},retry:(t,n)=>{let i=e.get(t);i&&(i.attempt=0,i.retryAt=n,i.healthySince=null,i.graceUntil=0,r.delete(t))},state:t=>{let n=e.get(t);return!n||n.healthySince!==null?null:{reason:n.reason,attempt:n.attempt,retryAt:n.retryAt,message:n.message}},forget:a,retain:i=>{for(let o of[e,t,n,r])for(let e of[...o.keys()])i.has(e)||a(e)}}},ul=e=>!(e.flags&Tc.localConnection)||!!(e.source&Oc.incoming),dl=e=>e.flags&Tc.utpSocket?`utp`:`tcp`,fl={total:0,byTransport:{}},pl=e=>{let t={},n=0;for(let r of e)for(let e of r){if(!ul(e)||e.connectionType!==0)continue;n+=1;let r=dl(e);t[r]=(t[r]??0)+1}return{total:n,byTransport:t}},ml={activeSeconds:0,seedingSeconds:0},hl=[`activeSeconds`,`seedingSeconds`,`downloaded`,`uploaded`,`wasted`],gl={activeSeconds:0,seedingSeconds:0,downloaded:0,uploaded:0,wasted:0},_l=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0,vl=(e,t)=>({activeSeconds:Math.max(0,_l(t.activeSeconds)-_l(e.activeSeconds)),seedingSeconds:Math.max(0,_l(t.seedingSeconds)-_l(e.seedingSeconds))}),yl=(e,t,n)=>{let r=vl(t,n);return{activeSeconds:_l(e?.activeSeconds)+r.activeSeconds,seedingSeconds:_l(e?.seedingSeconds)+r.seedingSeconds}},bl=(e,t)=>Object.fromEntries(hl.map(n=>[n,Math.max(0,_l(t[n])-_l(e[n]))])),xl=(e,t,n)=>{let r=bl(t,n);return Object.fromEntries(hl.map(t=>[t,_l(e?.[t])+r[t]]))},Sl=(e,t)=>Object.fromEntries(hl.map(n=>[n,Math.max(_l(e?.[n]),_l(t?.[n]))])),Cl=(e,t)=>t.activeSeconds-_l(e?.activeSeconds)>=30||t.seedingSeconds-_l(e?.seedingSeconds)>=30,wl=67108864,Tl=e=>!Number.isFinite(e)||e<=0?0:Math.min(1e9,Math.floor(e*.1)),El=(e,t)=>!Number.isFinite(e)||e<=0?Math.max(0,t):Math.max(Math.min(.25*e,2e10),Math.max(0,t)),Dl=({usedBytes:e,limitBytes:t,pendingBytes:n,refusedBytes:r,candidates:i})=>{if(!Number.isFinite(t)||t<=0||!Number.isFinite(e)||e<0)return!1;let a=t-e,o=i.reduce((e,t)=>e+Math.max(0,t.bytesOnDisk),0);return a<Math.min(n,67108864)&&n>a+o||r>0&&r+67108864>a+o},Ol=(e,t)=>e.usedAt-t.usedAt||(e.infoHash<t.infoHash?-1:+(e.infoHash>t.infoHash)),kl=({usedBytes:e,limitBytes:t,pendingBytes:n,candidates:r})=>{if(!Number.isFinite(t)||t<=0||!Number.isFinite(e)||e<0)return[];let i=r.filter(e=>e.bytesOnDisk>0).sort(Ol);if(!i.length)return[];let a=[0];for(let e of i)a.push(a[a.length-1]+e.bytesOnDisk);let o=e=>{for(let t=0;t<=i.length;t++)if(e(t))return t;return-1},s=Math.max(0,n),c=t-e,l=o(e=>c+a[e]>=s+Tl(t)),u=o(e=>c+a[e]>=s+wl),d=l>=0?l:Math.max(0,u),f=a[i.length],p=i.reduce((e,t)=>Math.max(e,t.bytesOnDisk),0),m=El(t,p),h=o(e=>f-a[e]<=m);return i.slice(0,Math.max(d,h<0?i.length:h)).map(e=>e.infoHash)},Al={start:0,end:0},jl=(e,t,n)=>{let r=Math.min(n,e.size);return r<=t?Al:{start:Math.floor((e.offset+t)/e.pieceLength),end:Math.floor((e.offset+r-1)/e.pieceLength)+1}},Ml=(e,t,n)=>jl(e,n*t,(n+1)*t),Nl=(e,t,n)=>{let r=/* @__PURE__ */ new Set;for(let{start:i,end:a}of n){let n=Math.max(0,i*e.pieceLength-e.offset),o=Math.min(e.size,a*e.pieceLength-e.offset);for(let e=Math.floor(n/t);n<o&&e<=Math.floor((o-1)/t);e++)r.add(e)}return r},Pl=(e,t)=>{let n=[],r=t,i=e.map((e,t)=>({size:e,i:t})).sort((e,t)=>e.size-t.size);return i.forEach(({size:e,i:t},a)=>{let o=Math.min(e,r/(i.length-a));n[t]=o,r-=o}),n},Fl=(e,t,n)=>e>t&&Math.floor(t/n)>=23,Il=({file:e,chunkBytes:t,room:n,reader:r,held:i,pinned:a=[]})=>{if(!Fl(e.size,n,t))return null;let o=Math.ceil(e.size/t)-1,s=Math.floor(Math.min(Math.max(r,0),e.size-1)/t),c=Math.floor(n/t)-3,l=new Set(i),u=jl(e,0,t),d=Math.max(0,o-2-s),f=n=>{if(!d){let n=jl(e,s*t,e.size);return{want:[u,n],ahead:n,slack:Al}}let r=jl(e,s*t,n*t),i=jl(e,n*t,(n+2)*t);return{want:[u,r,i,jl(e,o*t,e.size)],ahead:r,slack:i}},p=n=>Nl(e,t,[...f(n).want,...a]),m=s+Math.min(16,d),h=p(m);for(;m<s+d;){let e=p(m+1);if(e.size>c||[...e].some(e=>!h.has(e)&&!l.has(e))&&(/* @__PURE__ */ new Set([...e,...l])).size>c)break;m++,h=e}let g=/* @__PURE__ */ new Set([...h,...l]),_=[...l].filter(e=>!h.has(e)).sort((e,t)=>Math.abs(t-s)-Math.abs(e-s)||t-e);for(let e of _){if(g.size<=c)break;g.delete(e)}return{...f(m),keep:[...g].sort((e,t)=>e-t)}},Ll=(e,t,n)=>e||t<n,Rl=(e,t,n)=>{if(!e||t.usedBytes<e.usedBytes||t.headroomBytes>e.headroomBytes)return{...t,fixed:e?.fixed};let r=t.usedBytes-e.usedBytes;return r<n?e:{...t,fixed:e.headroomBytes-t.headroomBytes>=r/2}};var zl=8,Bl=2e4,Vl=e=>typeof e.values==`function`,Hl=async e=>{let t=0,n=0,r=async(e,i)=>{if(!(i>zl))for await(let a of e.values()){if(++n>Bl)return;if(Vl(a)){await r(a,i+1);continue}let e=await a.getFile().catch(()=>null);e&&(t+=e.size)}};try{return await r(e,0),t}catch{return null}},Ul=(e,t)=>{let n=e.usage;if(t===null||!Number.isFinite(t)||t<0)return n;if(n===void 0)return t;let r=e.usageDetails?.fileSystem;if(typeof r==`number`){let e=Math.max(0,n-r);return Math.max(n,t+e)}return Math.max(n,t)},Wl,Gl,Kl=(e,t,n)=>{if(e!==void 0)return n!==Gl&&(Wl=void 0),Gl=n,Wl=Wl===void 0?e:Math.min(Wl,e),Math.max(Wl,t??0)},ql=async e=>e.persisted?e.persisted().then(e=>e===!0).catch(()=>Gl):void 0,Jl={estimate:async()=>{let e=globalThis.navigator?.storage;if(!e?.estimate)return{};let t=await e.estimate(),[n,r]=await Promise.all([e.getDirectory?e.getDirectory().then(e=>Hl(e)).catch(()=>null):null,ql(e)]),i=Ul(t,n);return{...t,usage:i,quota:Kl(t.quota,i,r)}},persist:async()=>{let e=globalThis.navigator?.storage;if(!e?.persist)return!1;let t=await e.persist().catch(()=>!1);return await ql(e)??null??t},persisted:()=>globalThis.navigator?.storage?.persisted?.()??Promise.resolve(!1),getDirectory:()=>{let e=globalThis.navigator?.storage;return e?.getDirectory?e.getDirectory():Promise.reject(/* @__PURE__ */ Error(`this browser has no origin private file system`))}};const Yl=/^(?:[0-9a-f]{40}|[0-9a-f]{64}|[a-z2-7]{32})$/i,Xl=({entries:e,listedHashes:t,claimedNames:n,attributable:r})=>e.filter(({name:e,kind:i})=>n.has(e)?!1:i===`directory`&&Yl.test(e)?!t.has(e.toLowerCase()):r).map(({name:e})=>e),Zl=async e=>{let t=[];for await(let n of e.values())t.push({name:n.name,kind:n.kind});return t},Ql=async(e,t)=>{let n=e;for(let e of t.split(`/`).filter(Boolean))n=n?await n.getDirectoryHandle(e).catch(()=>null):null;return n},$l=async(e,t,n)=>{let r=await Ql(e,t);if(!r)return[];let i=[];for(let e of Xl({...n,entries:await Zl(r)}))try{await r.removeEntry(e,{recursive:!0}),i.push(e)}catch{}return i},eu=async e=>{let t=0;for(let{name:n,kind:r}of await Zl(e))r===`file`&&n.startsWith(`.ripple-probe-`)&&await e.removeEntry(n).then(()=>!0,()=>!1)&&t++;return t},tu=/* @__PURE__ */ new Set([`export-start`,`export-chunk`,`import-start`]),nu=e=>e?`/dl/`+e:`/dl`,ru=e=>`/cache/`+e,iu=e=>!!e?.startsWith(`/cache/`),au=(e,t)=>e===nu(t)||e===ru(t),ou=(e,t)=>t&&(!e||e.ephemeral===!0),su=(e,t)=>e?{...t,ephemeral:ou(e,t.ephemeral===!0),addedAt:Math.min(e.addedAt,t.addedAt),lastUsedAt:Math.max(e.lastUsedAt??0,t.lastUsedAt??t.addedAt),savePath:e.savePath||t.savePath,rootEntry:t.rootEntry??e.rootEntry,name:t.name??e.name,size:t.size??e.size,files:t.files??e.files,format:t.format??e.format,pieceLength:t.pieceLength??e.pieceLength,downloadLimit:t.downloadLimit??e.downloadLimit,uploadLimit:t.uploadLimit??e.uploadLimit,activeSeconds:t.activeSeconds??e.activeSeconds,seedingSeconds:t.seedingSeconds??e.seedingSeconds,downloaded:t.downloaded??e.downloaded,uploaded:t.uploaded??e.uploaded,wasted:t.wasted??e.wasted,saveTo:t.saveTo??e.saveTo,wantedFiles:t.wantedFiles??e.wantedFiles,firstLast:t.firstLast??e.firstLast,created:t.created??e.created}:t,cu=e=>({name:typeof e.name==`string`&&e.name?e.name:void 0,size:typeof e.size==`number`&&Number.isFinite(e.size)&&e.size>=0?e.size:void 0,files:Array.isArray(e.files)?e.files.filter(e=>!!e&&typeof e.name==`string`&&typeof e.size==`number`&&Number.isFinite(e.size)).slice(0,100):void 0}),lu=`ripple:torrents`,uu=`ripple:removed`,du=(...e)=>{let t=/* @__PURE__ */ new Map;for(let n of e)if(Array.isArray(n))for(let e of n)typeof e?.infoHash==`string`&&e.infoHash&&typeof e.removedAt==`number`&&Number.isFinite(e.removedAt)&&t.set(e.infoHash,Math.max(t.get(e.infoHash)??e.removedAt,e.removedAt));return[...t].map(([e,t])=>({infoHash:e,removedAt:t}))},fu=e=>{let t=new Map(e.map(e=>[e.infoHash,e.removedAt]));return e=>{let n=t.get(e.infoHash);return n===void 0||(e.addedAt??0)>n}},pu=(e,t,n)=>{let r=fu(n),i=t.filter(e=>!!e&&r(e)),a=new Set(i.map(e=>e.infoHash));return{list:e.filter(e=>e.started!==!1||a.has(e.infoHash)||r(e)),incoming:i}},mu=e=>`ripple:resume:`+e,hu=e=>`ripple:torrent:`+e,gu=e=>`ripple:thumb:`+e,_u=nu(zc(`magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.torrent.eu.org%3A451&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F`)),G={formatMessage:(e,t)=>t?{message:e.id,values:t}:{message:e.id}},vu=e=>typeof e.getFile==`function`?e.getFile():Promise.resolve(e),yu=e=>`/native/${e}`,bu=e=>e===`/native`||!!e?.startsWith(`/native/`),xu=e=>`/source/${e}`,Su=e=>e===`/source`||!!e?.startsWith(`/source/`),Cu=e=>bu(e)||Su(e),wu=async(e,t)=>{let n=t.split(`/`).filter(Boolean),r=n.pop();if(!r)throw Error(`hybrid storage: empty file path`);let i=e;for(let e of n)i=await i.getDirectoryHandle(e);return(await i.getFileHandle(r)).getFile()},Tu=(e,t,n=()=>null,r=e)=>{let i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set,s=t=>o.has(t)?r:e,c=t=>iu(t)?r:e,l=e=>{let n=t();if(!n)throw Error(`hybrid storage: no folder granted, cannot ${e}`);return n},u=async(e,t)=>{if(!e.handles)throw Error(`hybrid storage: ${e.savePath} has no source handles registered`);if(e.handles.length!==e.files.length)throw Error(`hybrid storage: ${e.savePath} has ${e.handles.length} handles for ${e.files.length} files`);if(t<0||t>=e.handles.length)throw Error(`hybrid storage: no source handle ${t} in ${e.savePath}`);let n=e.handles[t];return n?vu(n):null};return{usageOf:async(e,t)=>Cu(e)?0:c(e).usageOf(e,t),refusedFile:e=>c(e).refusedFile(e),onNewStorage:(e,t,r)=>{if(Su(t)){a.set(e,{savePath:t,files:r,handles:n(t)});return}if(iu(t)?o.add(e):o.delete(e),!bu(t))return s(e).onNewStorage(e,t,r);i.set(e,{savePath:t,files:r})},onRemoveStorage:e=>{if(!a.delete(e)&&!i.delete(e))return s(e).onRemoveStorage(e)},read:(e,t,n,r)=>{let o=a.get(e);if(o)return(async()=>{let e=await u(o,t);if(!e)return new Uint8Array(r);let i=await e.slice(n,n+r).arrayBuffer();if(i.byteLength<r)throw Error(`hybrid storage: source file ${t} of ${o.savePath} ended early, wanted ${r} at ${n}, got ${i.byteLength}`);return new Uint8Array(i)})();let c=i.get(e);if(!c)return s(e).read(e,t,n,r);let d=c.files[t];if(!d)throw Error(`hybrid storage: no file ${t} in ${c.savePath}`);return(async()=>{let e=await(await wu(l(`read`),d.path)).slice(n,n+r).arrayBuffer();if(e.byteLength<r)throw Error(`hybrid storage: ${d.path} ended early, wanted ${r} at ${n}, got ${e.byteLength}`);return new Uint8Array(e)})()},write:(e,t,n,r)=>{let o=a.get(e);if(o)throw Error(`hybrid storage: ${o.savePath} is somebody's own files, refusing a write of ${r.length} at ${n} in file ${t}`);let c=i.get(e);if(!c)return s(e).write(e,t,n,r);throw Error(`hybrid storage: ${c.savePath} is read only, refusing a write of ${r.length} at ${n} in file ${t}`)},check:async e=>{if(a.get(e))return 2;let t=i.get(e);if(!t)return s(e).check(e);try{let e=l(`check`);for(let n of t.files){let t=await wu(e,n.path).catch(()=>null);if(t&&t.size>0)return 2}return 0}catch{return 2}},deleteFiles:async(e,t)=>{if(!a.has(e)&&!i.get(e))return s(e).deleteFiles(e,t)},release:async e=>{!i.has(e)&&!a.has(e)&&await s(e).release(e)},stop:async e=>{!i.has(e)&&!a.has(e)&&await s(e).stop(e)}}},Eu=(e,t,n)=>[Math.max(0,Math.floor(e.offset/t)),Math.min(n-1,Math.floor((e.offset+Math.max(0,e.size-1))/t))],Du=({files:e,pieceLength:t,numPieces:n,wanted:r,firstLast:i,windowBytes:a=4194304})=>{let o=r===void 0,s=new Set(r??[]),c=e=>o||s.has(e),l=new Uint8Array(n).fill(o?W.normal:W.skip);if(!o)for(let[r,i]of e.entries()){if(!c(r)||i.size<=0)continue;let[e,a]=Eu(i,t,n);for(let t=e;t<=a;t++)l[t]=W.normal}if(i){let r=Math.max(1,Math.ceil(a/t));for(let[i,a]of e.entries()){if(!c(i)||a.size<=0)continue;let[e,o]=Eu(a,t,n);for(let t=0;t<r;t++){let n=e+t,r=o-t;n<=o&&(l[n]=W.top),r>=e&&(l[r]=W.top)}}}return l},Ou=({wanted:e,firstLast:t})=>e===void 0&&!t,ku=e=>Su(e)?`source`:bu(e)?`folder`:`browser`,Au=(e,t)=>{if(e===`source`){if(!t)throw Error(`a source-backed torrent needs its infohash to name its save path`);return xu(t)}return e===`folder`?t?yu(t):`/dl`:nu(t)},ju=`ripple:rate-limits`,Mu=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,Nu=e=>{let t=e??{};return{down:Mu(t.down)?t.down:0,up:Mu(t.up)?t.up:0}},Pu=/* @__PURE__ */ new Set(/* @__PURE__ */ `add-magnet.add-torrent-file.create-source.reserve-storage.start-source.read.cancel-read.remove.relocate.set-location.set-folder.set-plan.remove-missing.watch.unwatch.unwatch-owner.pause.resume.recheck.import-list.clear-list.start.retry.retry-now.flush-resume.inspect.set-flags.reannounce.queue-move.set-limits.set-session-limits.set-temporary.export-start.export-chunk.export-end.import-start.import`.split(`.`)),Fu=e=>`ripple:source:`+e;let K=null,Iu=null;const Lu=rl(el);let Ru=null;const zu=/* @__PURE__ */ new Map;let Bu=!1;const q=[],Vu=/* @__PURE__ */ new Map,J=/* @__PURE__ */ new Map,Hu=/* @__PURE__ */ new Map,Uu=/* @__PURE__ */ new Map,Y=/* @__PURE__ */ new Set,Wu=/* @__PURE__ */ new Set,Gu=/* @__PURE__ */ new Set,Ku=e=>{Gu.delete(e),Wu.add(e)},qu=e=>{Wu.delete(e),Gu.add(e)},Ju=/* @__PURE__ */ new Map,X=ll(),Yu=e=>e>=4294967040,Z=(e,t)=>self.postMessage(e,t??[]),Xu=()=>q.map(e=>{let t=K.bitfield(e);return{handle:e,magnet:Vu.get(e)??``,files:K.files(e),status:K.status(e),bitfield:t?{numPieces:t.numPieces,pieceLength:t.pieceLength,length:t.length,pieces:t.pieces}:null,recovery:X.state(e),userPaused:Y.has(e),windowed:Xd.has(e),swarmDownloads:Math.max(-1,...K?.lastTrackers(e).map(e=>e.downloaded)??[]),uptime:Zu(e),sessionUptime:Qu(e),totals:Md(e)}}),Zu=e=>{let t=K?.status(e),n=Ed.get(e);return!t||!n?Dd.get(e)??ml:yl(Dd.get(e),n,t)},Qu=e=>{let t=K?.status(e),n=Ed.get(e);return t&&n?vl(n,t):ml},$u=async()=>await uc(`ripple:torrents`)??[],ed=async e=>{let t=[];await fc(lu,n=>{t=n??[];let r=t.findIndex(t=>t.infoHash===e.infoHash),i=su(r>=0?t[r]:null,e);return r>=0?t[r]=i:t.push(i),t}),Z({type:`list`,list:t})},Q=async(e,t,n=!1)=>{let r=[];await fc(lu,n=>{r=n??[];let i=r.findIndex(t=>t.infoHash===e);return i>=0&&(r[i]={...r[i],...t}),r}),n||Z({type:`list`,list:r})},td=e=>{let t=J.get(e);t&&Q(t,{lastUsedAt:Date.now()},!0).catch(()=>{})},nd=async e=>{await pc(mu(e)).catch(()=>{}),await pc(hu(e)).catch(()=>{}),await pc(Fu(e)).catch(()=>{}),await pc(gu(e)).catch(()=>{})},rd=async e=>{let t=[];await fc(lu,n=>t=(n??[]).filter(t=>t.infoHash!==e)),await fc(uu,t=>du(t,[{infoHash:e,removedAt:Date.now()}])),await nd(e),Z({type:`list`,list:t})},id=/* @__PURE__ */ new Set,ad=/* @__PURE__ */ new Set,od=/* @__PURE__ */ new Map,sd=/* @__PURE__ */ new Set;let cd=null,ld=0;const ud=5e3;let dd=0,fd=0,pd=fl;const md=e=>{let t=cd;return t==null||!q.includes(t)?null:(K.peers(t),e-ld>=ud&&(ld=e,K.trackers(t)),{handle:t,peers:K.lastPeers(t),trackers:K.lastTrackers(t)})},hd=e=>{let t=K?.files(e);if(!t)return[];let n=t.files.map(e=>e.path.split(`/`).filter(Boolean)[0]).filter(Boolean);return[...new Set(n)]},gd=(e,t,n,r,i=!1)=>{q.includes(e)||q.push(e),Vu.set(e,t),n&&(J.set(e,n),sd.add(e)),Hu.set(e,r),i?id.add(e):id.delete(e)},_d=e=>{let t=q.indexOf(e);t>=0&&q.splice(t,1),Vu.delete(e),J.delete(e),Hu.delete(e),Uu.delete(e),Y.delete(e),X.forget(e),Hd.delete(e),Bd.delete(e),Wu.delete(e),Gu.delete(e),Ju.delete(e),$.delete(e),Jd.delete(e),Yd.delete(e),yd.delete(e),bd.delete(e),Sd.delete(e),Cd.delete(e),wd.delete(e),Ed.delete(e),Dd.delete(e),Od.delete(e),kd.delete(e),id.delete(e),ad.delete(e),od.delete(e),sd.delete(e),Xd.delete(e),Zd.delete(e),Qd.delete(e),mf.delete(e),hf.delete(e),uf.delete(e)},vd=e=>{ad.delete(e)&&(qu(e),K?.resumeTorrent(e),X.hold(e,Date.now()))},yd=/* @__PURE__ */ new Set,bd=/* @__PURE__ */ new Map;let xd={down:0,up:0};const Sd=/* @__PURE__ */ new Map,Cd=/* @__PURE__ */ new Set,wd=/* @__PURE__ */ new Map;let Td=0;const Ed=/* @__PURE__ */ new Map,Dd=/* @__PURE__ */ new Map,Od=/* @__PURE__ */ new Map,kd=/* @__PURE__ */ new Map,Ad=e=>({activeSeconds:e.activeSeconds,seedingSeconds:e.seedingSeconds,downloaded:e.allTimeDownload,uploaded:e.allTimeUpload,wasted:e.wasted}),jd=e=>({activeSeconds:e?.activeSeconds??0,seedingSeconds:e?.seedingSeconds??0,downloaded:e?.downloaded??0,uploaded:e?.uploaded??0,wasted:e?.wasted??0}),Md=e=>{let t=K?.status(e),n=Od.get(e);return!t||!n?kd.get(e)??gl:xl(kd.get(e),n,Ad(t))},Nd=(e,t,n)=>{let r=wd.get(e);wd.set(e,r?{flags:r.flags&~n|t&n,mask:r.mask|n}:{flags:t&n,mask:n})},Pd=(e,t)=>{let n={...Sd.get(e)};return Mu(t.down)&&(n.down=t.down),Mu(t.up)&&(n.up=t.up),!Mu(n.down)&&!Mu(n.up)?!1:(Sd.set(e,n),Cd.add(e),!0)},Fd=e=>{let t=Sd.get(e)?.down;return Qd.has(e)?Math.min(t||16384,16384):t},Id=e=>{let t=Sd.get(e);if(!K||!t)return;let n=Fd(e);Mu(n)&&K.setDownloadLimit(e,n),Mu(t.up)&&K.setUploadLimit(e,t.up)},Ld=6e3,Rd=G.formatMessage({id:`torrent removed`,defaultMessage:`torrent removed`}),zd=G.formatMessage({id:`torrent paused`,defaultMessage:`torrent paused`}),Bd=/* @__PURE__ */ new Map,Vd=(e,t)=>{let n=Bd.get(e);if(n?.size){for(let e of n.keys())Z({type:`read-error`,id:e,error:t});n.clear()}},Hd=/* @__PURE__ */ new Set,Ud=async e=>{let t=J.get(e);if(!t||!K||Hd.has(e)||Su(Hu.get(e)))return!1;let n=K.status(e);if(n&&sl.has(n.state))return!1;Hd.add(e);try{let n=await K.saveResumeData(e);return q.includes(e)?(await dc(mu(t),n),!0):!1}catch(e){return console.error(`[worker] saving resume data failed`,String(e)),!1}finally{Hd.delete(e)}},Wd=(e,t)=>{let n=K?.files(e),r=n?.files[t];if(!n||!r||r.size<=0)return null;let i=Math.floor(r.offset/n.pieceLength),a=Math.floor((r.offset+r.size-1)/n.pieceLength);return{file:r,pieceLength:n.pieceLength,p0:i,p1:a}},$=/* @__PURE__ */ new Map;let Gd=!1;const Kd=()=>[...$].every(([e,t])=>[...t.values()].every(t=>t.held||t.bulk||t.prepare||Cf(e,t.fileIndex,t.fromOffset,1/0))),qd=()=>[...$].filter(([,e])=>[...e.values()].some(e=>e.prepare)).map(([e])=>e),Jd=/* @__PURE__ */ new Set,Yd=/* @__PURE__ */ new Set,Xd=/* @__PURE__ */ new Map,Zd=/* @__PURE__ */ new Map,Qd=/* @__PURE__ */ new Set;let $d;const ef=`ripple:ceiling-fixed`;let tf,nf=null;const rf=(e,t,n)=>[...vf(e).filter(e=>e.fileIndex===t).map(e=>jl(n,e.fromOffset,e.fromOffset+Hc(n.pieceLength))),...[...Bd.get(e)?.values()??[]].filter(e=>e.fileIndex===t).map(e=>jl(n,e.offset,e.offset+e.len))],af=(e,t,n)=>{let r=Zd.get(e),[i]=n;if(r===void 0||!i||!$d?.fixed||!id.has(e)||n.some(e=>e.fileIndex!==i.fileIndex))return null;let a=t.files[i.fileIndex],o=Hu.get(e);if(!a||o===void 0)return null;let s={offset:a.offset,size:a.size,pieceLength:t.pieceLength},c=Lu.chunkBytesOf(o),l=Lu.chunksOf(o,i.fileIndex),u=Il({file:s,chunkBytes:c,room:r,reader:i.fromOffset,held:l,pinned:rf(e,i.fileIndex,s)});return u&&{...u,fileIndex:i.fileIndex,file:s,chunkBytes:c}},of=(e,t)=>e.fileIndex===t.fileIndex&&JSON.stringify(e.want)===JSON.stringify(t.want),sf=(e,t)=>{let n=K?.bitfield(e);if(!n)return!1;for(let e=t.start;e<t.end;e++)if(!((n.pieces[e>>3]??0)&128>>(e&7)))return!1;return!0},cf=()=>nf?nf.space.limitBytes-nf.space.usedBytes-(Lu.footprint()-nf.footprint)-wl:1/0,lf=3e4,uf=/* @__PURE__ */ new Map,df=e=>(uf.get(e)?.until??0)>Date.now(),ff=e=>{let t=Xd.get(e),n=!!t&&!Bd.get(e)?.size&&Ll(sf(e,t.ahead),cf(),t.chunkBytes);n!==Qd.has(e)&&(n?Qd.add(e):Qd.delete(e),K?.setDownloadLimit(e,Fd(e)??0))},pf=e=>{let t=Xd.get(e),n=K?.bitfield(e);if(!t||!n||t.slack.end<=t.slack.start||df(e))return;let r=[];for(let e=t.slack.start;e<t.slack.end;e++)(n.pieces[e>>3]??0)&128>>(e&7)&&r.push(e);r.length&&t.slack.end-t.slack.start-r.length<2&&K?.forgetPieces(e,r)},mf=/* @__PURE__ */ new Set,hf=/* @__PURE__ */ new Set,gf=async e=>{if(mf.has(e)){hf.add(e);return}mf.add(e);let t=!1;try{if(df(e)){t=!0;return}let n=Hu.get(e),r=()=>{let t=Xd.get(e);if(!t||n===void 0)return[];let r=/* @__PURE__ */ new Set([...t.keep,...Nl(t.file,t.chunkBytes,rf(e,t.fileIndex,t.file))]);return Lu.chunksOf(n,t.fileIndex).filter(e=>!r.has(e)).map(e=>({chunk:e,fileIndex:t.fileIndex,pieces:Ml(t.file,t.chunkBytes,e)}))},i=({start:t,end:n})=>K?.forgetPieces(e,Array.from({length:n-t},(e,n)=>t+n))??null,a=r().filter(({pieces:n})=>{let r=i(n);if(r?.busy){for(let t=n.start;t<n.end;t++)K?.cancelPieceRequests(e,t);t=!0}return r?.busy===0});if(!a.length||n===void 0)return;if(!await Ud(e)){t=!0;return}let o=new Set(r().map(({chunk:e})=>e)),s=[];for(let{chunk:e,fileIndex:t,pieces:r}of a){if(!o.has(e))continue;let a=i(r);!a||a.forgotten||a.busy||s.push(Lu.drop(n,t,e))}await Promise.all(s)}catch(e){console.error(`[worker] dropping chunks failed`,String(e))}finally{mf.delete(e),hf.delete(e)?gf(e):t&&Xd.has(e)&&setTimeout(()=>void gf(e),1e3)}},_f=e=>{let t=bd.get(e);if(!K||!t||Ou(t))return;let n=K.files(e);n&&K.prioritizePieces(e,Du({files:n.files,pieceLength:n.pieceLength,numPieces:Math.ceil(n.totalSize/n.pieceLength),wanted:t.wanted,firstLast:t.firstLast}))},vf=e=>{let t=$.get(e);return t?[...t.values()].filter(e=>!e.held&&(!e.prepare||Gd)):[]},yf=e=>{if(!K)return;if(!q.includes(e)){$.delete(e),Yd.delete(e);return}let t=vf(e);if(!t.length){if(!K.files(e)){Yd.add(e);return}Yd.delete(e),Xd.delete(e),ff(e),K.clearStreamWindow(e),_f(e),id.has(e)&&Hu.get(e)!==_u&&!Y.has(e)&&!ad.has(e)&&(ad.add(e),Ku(e),K.pauseTorrent(e),Ud(e));return}vd(e);let n=K.files(e);if(!n){Yd.add(e);return}Jd.delete(e)&&Kf();let r=t.flatMap(({fileIndex:e,fromOffset:t,bulk:r,prepare:i})=>{let a={fileIndex:e,offset:t},o=n.files[e];return i?o?.size?[a,{fileIndex:e,offset:Math.max(0,o.size-Bc)}]:[]:!r&&o?.size?[a,{fileIndex:e,offset:o.size-1}]:[a]}),i=t.filter(e=>!e.prepare),a=i.some(e=>!e.bulk),o=af(e,n,i);o?Xd.set(e,o):Xd.delete(e);let s=o?.want??(i.length<t.length?i.map(({fileIndex:e})=>n.files[e]).flatMap(e=>e?.size?[jl({...e,pieceLength:n.pieceLength},0,e.size)]:[]):void 0);K.setStreamWindow(e,r,{unclaimedPriority:W.skip,windowPieces:Vc(n.pieceLength),deadlineStepMs:Wc(n.pieceLength,K.status(e)?.downloadRate||3e6),deadlines:a,...s?{keep:s}:{}})?Yd.delete(e):Yd.add(e),o&&gf(e),pf(e),ff(e)},bf=e=>{let t=K?.files(e),n=vf(e).filter(e=>!e.prepare);if(!t||!n.length)return;let r=af(e,t,n),i=Xd.get(e);if(r||i){if(!r||!i||!of(r,i)){yf(e);return}Xd.set(e,r),gf(e)}},xf=(e,t,n,r,i=!1,a,o=!1)=>{if(!q.includes(t))return;let s=$.get(t),c=!s?.size;s||$.set(t,s=/* @__PURE__ */ new Map);let l=a??s.get(e)?.bulk;s.set(e,{fileIndex:n,fromOffset:r,...i?{held:i}:{},...l?{bulk:l}:{},...o?{prepare:o}:{}}),c&&(td(t),Jd.add(t)),o&&(Gd=Kd()),yf(t)},Sf=e=>{for(let[t,n]of $){let r=!1;for(let t of[...n.keys()])e(t)&&(n.delete(t),r=!0);n.size||($.delete(t),r&&td(t)),r&&yf(t)}},Cf=(e,t,n,r)=>{let i=K?.files(e),a=i?.files[t],o=K?.bitfield(e);if(!i||!a||!o)return!1;let s=Math.floor((a.offset+n)/i.pieceLength),c=Math.floor((a.offset+Math.min(n+r,a.size)-1)/i.pieceLength);for(let e=s;e<=c;e++)if(!((o.pieces[e>>3]??0)&128>>(e&7)))return!1;return!0},wf=(e,t,n,r)=>{let i=K?.files(e),a=i?.files[t],o=K?.bitfield(e);if(!i||!a||!o)return[];let s=Math.floor((a.offset+n)/i.pieceLength),c=Math.floor((a.offset+Math.min(n+r,a.size)-1)/i.pieceLength),l=[];for(let e=s;e<=c;e++)(o.pieces[e>>3]??0)&128>>(e&7)||l.push(e);return l},Tf=(e,t,n)=>{let r=Math.max(0,e-Bc-t),i=n?Math.floor(r/n)*n:0;return Math.min(e,Hc(t)+e-i)},Ef=async(e,t={evictable:[],graced:[]})=>{let n=e=>Math.max(0,e.size-e.held),r=[],i=[];for(let[e,t]of[...$]){let n=Iu,a=K?.files(e),o=Hu.get(e);if(!n||!a||!t.size||o===void 0||Cu(o))continue;let s=new Set([...t.values()].filter(e=>!e.prepare).map(e=>e.fileIndex)),c=Lu.chunkBytesOf(o),l=async r=>{let i=a.files[r]?.size??0,l=!s.has(r)&&[...t.values()].some(e=>e.prepare&&e.fileIndex===r);return{h:e,size:l?Tf(i,a.pieceLength,iu(o)?c:void 0):i,held:await n.usageOf(o,r)??0}},u=vf(e).find(e=>!e.prepare),d=!!$d?.fixed&&id.has(e)&&iu(o);for(let e of new Set([...t.values()].map(e=>e.fileIndex)))r.push({...await l(e),cache:d&&e===u?.fileIndex,chunkBytes:c});let f=n.refusedFile(o);f!==void 0&&i.push(await l(f))}let a=r.filter(e=>!e.cache).reduce((e,t)=>e+n(t),0),o=r.filter(e=>e.cache),s=e=>e.reduce((e,t)=>e+t.bytesOnDisk,0),c=e.limitBytes-e.usedBytes+o.reduce((e,t)=>e+t.held,0)+s(t.evictable)-a-wl,l=e=>{let t=Pl(o.map(e=>e.size),c+e),r=new Set(o.filter((e,n)=>Fl(e.size,t[n]??0,e.chunkBytes)).map(e=>e.h));return{shares:t,windowed:r,owed:o.reduce((e,i,a)=>e+(r.has(i.h)?Math.max(0,(t[a]??0)-i.held):n(i)),a)}},u=l(0),d=l(s(t.graced)),f=i.filter(e=>!d.windowed.has(e.h)).reduce((e,t)=>e+n(t),0),p=new Map(o.map((e,t)=>[e.h,u.shares[t]??0]));return{pendingBytes:u.owed,laterBytes:d.owed,refusedBytes:f,rooms:p}},Df=(e,t,n,r,i)=>{if(!e||!q.includes(t))return;let a=$.get(t)?.get(e);if(!a||a.held||a.fileIndex!==n){xf(e,t,n,r);return}let o=Wd(t,n);if(!o)return;let s={fileOffset:o.file.offset,pieceLength:o.pieceLength,p1:o.p1};Gc(s,a.fromOffset,r,i)&&xf(e,t,n,r)},Of=async e=>{let t=e.filter(e=>!Cu(e));if(!t.length)return!0;try{let e=await navigator.storage.getDirectory();for(let n of new Set(t)){let t=e;for(let e of n.split(`/`).filter(Boolean))t=t?await t.getDirectoryHandle(e).catch(()=>null):null;if(t)return!0}return!1}catch{return!0}},kf=async()=>{let e,t;try{return e=await navigator.storage.getDirectory(),t=`.ripple-probe-${crypto.randomUUID()}`,(await(await e.getFileHandle(t,{create:!0})).createSyncAccessHandle()).close(),await e.removeEntry(t).catch(()=>{}),!0}catch{return e&&t&&await e.removeEntry(t).catch(()=>{}),!1}},Af=e=>({paused:e.paused,state:e.state,totalDone:e.totalDone,downloadRate:e.downloadRate,numPeers:e.numPeers,queued:e.paused&&e.autoManaged&&!e.errorCode,error:e.error}),jf=async()=>{try{let{usage:e,quota:t}=await Jl.estimate();return!t||e===void 0?null:{usedBytes:e,limitBytes:t}}catch{return null}},Mf=async()=>{try{let{usage:e,quota:t}=await navigator.storage.estimate();return t&&e!==void 0?t-e:null}catch{return null}},Nf=async(e,t=0)=>{for(let n=0;n<4e3;n+=250){await new Promise(e=>setTimeout(e,250));let n=await jf();if(!n||e-n.usedBytes>t/2)return n}return jf()},Pf=async(e,t,n,r,i={})=>{Vd(t,r),e.popAlerts(),e.removeTorrent(t,!0),_d(t),await pc(mu(n)).catch(()=>{}),await Q(n,{started:!1,paused:!1,...i})},Ff=(e,t,n)=>Pf(e,t,n,G.formatMessage({id:`torrent removed to make room`,defaultMessage:`torrent removed to make room`})),If=async(e,t,n,r)=>{let i=ku(Hu.get(t));if(i===r)return;let a=Vu.get(t)??``,o=Au(r,n),s=Y.has(t),c=id.has(t);Vd(t,G.formatMessage({id:`files moved`,defaultMessage:`files moved`})),e.removeTorrent(t,i===`browser`),_d(t),await pc(mu(n)).catch(()=>{});let l=e.addMagnet(a,o);if(Yu(l)){Z({type:`add-failed`,message:G.formatMessage({id:`Moving the files left the torrent unaddable`,defaultMessage:`Moving the files left the torrent unaddable`})}),await Q(n,{savePath:o,saveTo:r,started:!1});return}gd(l,a,n,o,c),r===`folder`&&Nd(l,Ec.uploadMode,Ec.uploadMode),s?(Y.add(l),Ku(l)):qu(l),X.hold(l,Date.now()),await Q(n,{savePath:o,saveTo:r,started:!0})},Lf=(e,{infoHash:t,magnet:n,bytes:r,handles:i,paused:a})=>{let o=xu(t);zu.set(o,i);let s=e.addTorrentFile(r,o);return Yu(s)?(zu.delete(o),null):(gd(s,n,t,o,!1),Nd(s,Ec.uploadMode,Ec.uploadMode),a&&(Y.add(s),Ku(s)),X.hold(s,Date.now()),s)},Rf=async(e,t)=>{let n=new Map(e.map(e=>[e.infoHash,e])),r=[],i=[];for(let e of[...q]){let a=J.get(e);if(!a)continue;let o=n.get(a);if(!o?.ephemeral||!au(o.savePath,a)||$.get(e)?.size||Bd.get(e)?.size)continue;let s=o.lastUsedAt??o.addedAt,c=await Iu?.usageOf(o.savePath)??0;if(c<=0)continue;let l=t-(od.get(e)??0)<6e4||t-s<15e3,u={infoHash:a,usedAt:s,bytesOnDisk:c};l?i.push(u):r.push(u)}return{evictable:r,graced:i}};let zf=!1;const Bf=e=>{let t=Dl(e);t!==zf&&(zf=t,Z({type:`storage-full`,full:t,usedBytes:e.usedBytes,limitBytes:e.limitBytes}))},Vf=/* @__PURE__ */ new Set;let Hf=!1;const Uf=async()=>{if(!K||Hf)return 0;Hf=!0;try{let e=await $u(),t=new Set(e.map(e=>e.infoHash.toLowerCase()));for(let e of Vf)t.add(e.toLowerCase());let n=/* @__PURE__ */ new Set,r=!0;for(let e of q){let i=J.get(e);if(i&&t.add(i.toLowerCase()),(Hu.get(e)??`/dl`)!==`/dl`)continue;let a=hd(e);if(!a.length){r=!1;continue}for(let e of a)n.add(e)}for(let t of e){let e=t.savePath||`/dl`;if(!iu(e)){if(e!==`/dl`&&!e.startsWith(`/dl/`)){r=!1;continue}if(e===`/dl`){if(t.rootEntry){n.add(t.rootEntry);continue}!q.some(e=>J.get(e)===t.infoHash)&&t.started!==!1&&(r=!1)}}}let i=await navigator.storage.getDirectory(),a=[...await $l(i,`/dl`,{listedHashes:t,claimedNames:n,attributable:r}),...await $l(i,`/cache`,{listedHashes:t,claimedNames:/* @__PURE__ */ new Set,attributable:!1})];return await eu(i).catch(()=>0),a.length&&console.log(`[worker] removed storage nothing owns`,a),a.length}catch(e){return console.error(`[worker] orphan sweep failed`,String(e)),0}finally{Hf=!1}};let Wf=!1,Gf=!1;const Kf=async()=>{let e=K;if(!e)return;if(Wf){Gf=!0;return}Wf=!0;let t=null,n={pendingBytes:0,laterBytes:0,refusedBytes:0,rooms:/* @__PURE__ */ new Map},r=[],i=[],a=e=>({...e,pendingBytes:$d?.fixed===!1?0:n.laterBytes,refusedBytes:n.refusedBytes,candidates:[...r,...i]});try{let o=await jf();if(!o)return;t=o,tf===void 0&&(tf=await uc(ef).catch(()=>null)??null);let s=async e=>{nf={space:e,footprint:Lu.footprint()};let t=await Mf();if(t===null)return;let n={usedBytes:e.usedBytes,headroomBytes:t};$d=Rl($d??(typeof tf==`boolean`?{...n,fixed:tf}:void 0),n,el),$d.fixed!==void 0&&$d.fixed!==tf&&(tf=$d.fixed,dc(ef,tf).catch(()=>{}))};await s(o),n=await Ef(o);let c=await Rf(await $u(),Date.now());r=c.evictable,i=c.graced,n=await Ef(o,c);let l=!1;for(;r.length;){let[a]=kl({...o,pendingBytes:n.pendingBytes,candidates:r});if(!a)break;let c=r.find(e=>e.infoHash===a)?.bytesOnDisk??0;r=r.filter(e=>e.infoHash!==a);let u=q.find(e=>J.get(e)===a);if(u===void 0||$.get(u)?.size||Bd.get(u)?.size)continue;let d=o.usedBytes;t=null,await Ff(e,u,a),l=!0;let f=await Nf(d,c);if(!f)return;o=f,t=f,await s(f),n=await Ef(o,{evictable:r,graced:i})}if(l)for(let e of $.keys())X.retry(e,Date.now());Zd.clear();for(let[e,t]of n.rooms)Zd.set(e,t);for(let e of/* @__PURE__ */ new Set([...Zd.keys(),...Xd.keys()]))bf(e);Dl(a(o))&&await Uf()&&(o=await Nf(o.usedBytes)??o),t=o}catch(e){console.error(`[worker] storage budget pass failed`,String(e))}finally{Wf=!1,t&&Bf(a(t)),Gf&&(Gf=!1,Kf())}},qf=async()=>{let e=console.error.bind(console);if(console.error=(...t)=>{e(...t);try{Z({type:`worker-error`,args:t.map(String)})}catch{}},!await kf()){Z({type:`storage-unavailable`});return}$u().then(e=>{e.length&&Z({type:`list`,list:e})}).catch(()=>{});let t=Promise.race([uc(ju).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]);Iu=Tu($c(),()=>Ru,e=>zu.get(e)??null,Lu),K=await Rc({net:Ys,dgram:ac,storage:Iu,utpReceiveBufferBytes:4194304});for(let e=0;e<30;e++)K.tick();xd=Nu(await t),K.setRateLimits({download:xd.down,upload:xd.up});try{let e=await $u(),t=!await Of(e.map(e=>e.savePath||`/dl`)),n=!1;for(let r of e){if(r.started===!1||r.saveTo===`source`)continue;let e=r.savePath||`/dl`,i=await uc(mu(r.infoHash)),a=await uc(hu(r.infoHash));if(t&&i&&i.byteLength){await pc(mu(r.infoHash)).catch(()=>{}),r.started=!1,n=!0;continue}let o=i&&i.byteLength?K.addTorrentWithResume(i,e):a&&a.byteLength?K.addTorrentFile(a,e):K.addMagnet(r.magnet,e);Yu(o)||(gd(o,r.magnet,r.infoHash,e,r.ephemeral===!0),bd.set(o,{wanted:r.wantedFiles,firstLast:r.firstLast}),yd.add(o),Pd(o,{down:r.downloadLimit??0,up:r.uploadLimit}),Dd.set(o,{activeSeconds:r.activeSeconds??0,seedingSeconds:r.seedingSeconds??0}),kd.set(o,jd(r)),r.paused?(Y.add(o),Ku(o)):qu(o),X.hold(o,Date.now()))}n&&await dc(lu,e)}catch(e){console.error(`[worker] restore failed`,e)}Z({type:`ready`}),Bu=!0,Z({type:`list`,list:await $u().catch(()=>[])}),Z({type:`state`,torrents:Xu(),reachable:K.reachable(),inboundNow:pd,rateLimits:{...xd}}),setInterval(()=>{if(!K)return;let e=Date.now();K.popAlerts();for(let e of q)K.postStatus(e);for(let e of[...yd])K.files(e)&&(yd.delete(e),vf(e).length||yf(e));for(let e of[...Yd])yf(e);let t=qd();if(t.length&&Kd()!==Gd){Gd=!Gd;for(let e of t)yf(e)}for(let e of[...Xd.keys()])pf(e),ff(e);for(let e of[...Cd])K.status(e)&&(Cd.delete(e),Id(e));for(let e of q){if(Ed.has(e))continue;let t=K.status(e);t&&(Ed.set(e,{activeSeconds:t.activeSeconds,seedingSeconds:t.seedingSeconds}),Od.set(e,Ad(t)))}for(let[e,t]of[...wd])K.status(e)&&(wd.delete(e),K.setFlags(e,t.flags>>>0,t.mask>>>0));for(let e of[...sd]){let[t]=hd(e);if(!t)continue;sd.delete(e);let n=J.get(e);if(!n)continue;let r=K.files(e);Q(n,{rootEntry:t,name:t,size:r?.contentSize,files:r?.files.filter(e=>!e.pad).slice(0,100).map(e=>({name:e.path,size:e.size}))}).catch(()=>{})}for(let e of Wu){let t=K.status(e);t&&!sl.has(t.state)&&(cl(t)?Wu.delete(e):K.pauseTorrent(e))}for(let e of Gu){if(Y.has(e)||ad.has(e)){Gu.delete(e);continue}let t=K.status(e);if(t&&!sl.has(t.state)){if(!t.paused){Gu.delete(e);continue}if(t.autoManaged||t.errorCode){Gu.delete(e);continue}K.resumeTorrent(e)}}X.retain(new Set(q));for(let t of q){let n=K.status(t);X.observe(t,n&&Af(n),Y.has(t)||ad.has(t),e)}for(let{handle:t,reason:n}of X.due(e))n===`stalled`&&K.pauseTorrent(t),K.resumeTorrent(t);if(e-fd>=2e3){fd=e;for(let e of q)K.peers(e)}if(pd=pl(q.map(e=>K.lastPeers(e))),$.size&&e-dd>=ud){dd=e;for(let e of $.keys())K.trackers(e)}Z({type:`state`,torrents:Xu(),reachable:K.reachable(),inboundNow:pd,detail:md(e),rateLimits:{...xd}});for(let t of q){let n=K.status(t);if(!n||n.state!==4&&n.state!==5||Uu.get(t)===n.paused||Hd.has(t))continue;let r=Ju.get(t);if(r&&e<r.at)continue;let i=n.paused;Ud(t).then(e=>{if(e){Uu.set(t,i),Ju.delete(t);return}let n=(Ju.get(t)?.tries??0)+1;Ju.set(t,{tries:n,at:Date.now()+Math.min(1e3*2**n,6e4)})})}},500),setInterval(()=>{if(!K)return;for(let e of q){let t=K.status(e);t&&t.state===3&&Ud(e)}let e=!1;for(let t of q){let n=K.status(t),r=J.get(t),i=Ed.get(t);if(!n||!r||!i)continue;e=!0;let a=yl(Dd.get(t),i,n);if(!Cl(Dd.get(t),a))continue;Dd.set(t,a),Ed.set(t,{activeSeconds:n.activeSeconds,seedingSeconds:n.seedingSeconds});let o=Ad(n),s=xl(kd.get(t),Od.get(t)??o,o);kd.set(t,s),Od.set(t,o),Q(r,{activeSeconds:a.activeSeconds,seedingSeconds:a.seedingSeconds,downloaded:s.downloaded,uploaded:s.uploaded,wasted:s.wasted},!0).catch(()=>{})}e&&Date.now()-Td>=3e5&&(Td=Date.now(),$u().then(e=>Z({type:`list`,list:e})).catch(()=>{}))},15e3),setInterval(()=>{Kf()},1e4),Kf(),setTimeout(()=>{Uf(),setInterval(()=>{Uf()},6e5)},6e4),self.addEventListener(`online`,()=>X.retryNow(Date.now()))},Jf=async(e,t)=>{try{if(t.type===`add-magnet`){let n=zc(t.magnet),r=n?q.find(e=>J.get(e)===n):void 0;if(r!==void 0)n&&!t.ephemeral?(id.delete(r),vd(r),vf(r).length&&yf(r),await Q(n,{ephemeral:!1,lastUsedAt:Date.now()})):td(r),Z({type:`added`,handle:r,magnet:Vu.get(r)||t.magnet});else{let r=n?(await $u()).find(e=>e.infoHash===n):void 0,i=ou(r,t.ephemeral===!0),a=t.savePath||r?.savePath||(i&&n?ru(n):nu(n)),o=e.addMagnet(t.magnet,a);if(Yu(o)){Z({type:`add-failed`,message:G.formatMessage({id:`That is not a valid magnet link`,defaultMessage:`That is not a valid magnet link`})});return}gd(o,t.magnet,n,a,i),bd.set(o,{wanted:r?.wantedFiles,firstLast:r?.firstLast}),t.hold===!0&&yd.add(o),Pd(o,{down:r?.downloadLimit,up:r?.uploadLimit}),Dd.set(o,{activeSeconds:r?.activeSeconds??0,seedingSeconds:r?.seedingSeconds??0}),kd.set(o,jd(r)),X.hold(o,Date.now());let s=Date.now();n&&await ed({infoHash:n,magnet:t.magnet,savePath:a,addedAt:s,lastUsedAt:s,ephemeral:i,started:!0,paused:!1}),Z({type:`added`,handle:o,magnet:t.magnet}),Kf()}}else if(t.type===`create-source`){let n=t.infoHash,r=t.handles??[],i=t.bytes;if(typeof n!=`string`||!n||!r.length||!i?.byteLength){Z({type:`add-failed`,message:G.formatMessage({id:`That torrent could not be created`,defaultMessage:`That torrent could not be created`})});return}if(!r.some(e=>e)){Z({type:`add-failed`,message:G.formatMessage({id:`Some of those files could not be opened`,defaultMessage:`Some of those files could not be opened`})});return}await dc(hu(n),i);let a=Lf(e,{infoHash:n,magnet:t.magnet,bytes:i,handles:r,paused:!1});if(a===null){await pc(hu(n)).catch(()=>{}),Z({type:`add-failed`,message:G.formatMessage({id:`The engine refused the torrent that was just built`,defaultMessage:`The engine refused the torrent that was just built`})});return}let o=Date.now();await ed({infoHash:n,magnet:t.magnet,savePath:xu(n),addedAt:o,lastUsedAt:o,ephemeral:!1,started:t.reopenable!==!1,paused:!1,saveTo:`source`,format:t.format??`v1`,pieceLength:typeof t.pieceLength==`number`?t.pieceLength:void 0,...cu({name:t.name,size:t.size,files:t.files})}),Z({type:`added`,handle:a,magnet:t.magnet})}else if(t.type===`start-source`){let n=t.infoHash,r=t.handles??[];if(typeof n!=`string`||!n||!r.length)return;if(!r.some(e=>e)){Z({type:`add-failed`,message:G.formatMessage({id:`Some of those files could not be opened`,defaultMessage:`Some of those files could not be opened`})});return}let i=[...J.entries()].find(([,e])=>e===n);if(i){Z({type:`added`,handle:i[0],magnet:Vu.get(i[0])??``});return}let a=await uc(hu(n));if(!a?.byteLength){Z({type:`add-failed`,message:G.formatMessage({id:`The torrent this was built from is no longer stored`,defaultMessage:`The torrent this was built from is no longer stored`})});return}let o=(await $u()).find(e=>e.infoHash===n),s=Lf(e,{infoHash:n,magnet:o?.magnet??t.magnet??``,bytes:a,handles:r,paused:o?.paused===!0});if(s===null){Z({type:`add-failed`,message:G.formatMessage({id:`The engine refused that torrent`,defaultMessage:`The engine refused that torrent`})});return}Dd.set(s,{activeSeconds:o?.activeSeconds??0,seedingSeconds:o?.seedingSeconds??0}),kd.set(s,jd(o)),await Q(n,{started:!0,lastUsedAt:Date.now()}),Z({type:`added`,handle:s,magnet:o?.magnet??``})}else if(t.type===`add-torrent-file`){let n=t.savePath||`/dl`,r=t.bytes,i=e.addTorrentFile(r,n);if(Yu(i)){Z({type:`add-failed`,message:G.formatMessage({id:`That file is not a valid .torrent`,defaultMessage:`That file is not a valid .torrent`})});return}gd(i,``,null,n,t.ephemeral===!0),X.hold(i,Date.now());let a=null;for(let t=0;t<40&&!(a=e.infohash(i));t++)await new Promise(e=>setTimeout(e,250));if(!q.includes(i))return;if(!a){e.removeTorrent(i,!0),_d(i),Z({type:`add-failed`,message:G.formatMessage({id:`Could not read that torrent`,defaultMessage:`Could not read that torrent`})});return}let o=e.infohashV2(i),s=`magnet:?`+[...a.length===40?[`xt=urn:btih:${a}`]:[],...o?[`xt=urn:btmh:1220${o}`]:[]].join(`&`);gd(i,s,a,n),await dc(hu(a),r);let c=Date.now(),l=t.saveTo===`browser`||t.saveTo===`folder`?{saveTo:t.saveTo}:{};await ed({infoHash:a,magnet:s,savePath:n,addedAt:c,lastUsedAt:c,ephemeral:t.ephemeral===!0,started:!0,paused:!1,...l,...t.created===!0?{created:!0}:{}}),Vf.delete(a),Z({type:`added`,handle:i,magnet:s})}else if(t.type===`read`){if(!q.includes(t.handle)){Z({type:`read-error`,id:t.id,error:Rd});return}if(vd(t.handle),t.viewer||od.set(t.handle,Date.now()),Y.has(t.handle)&&!Cf(t.handle,t.fileIndex,t.offset,t.len)){Z({type:`read-error`,id:t.id,error:zd});return}if(t.prioritize!==!1)Df(t.viewer,t.handle,t.fileIndex,t.offset,t.len);else if(!Cf(t.handle,t.fileIndex,t.offset,t.len)){Z({type:`read-error`,id:t.id,error:`not downloaded`});return}let n=Bd.get(t.handle);n||Bd.set(t.handle,n=/* @__PURE__ */ new Map),n.set(t.id,{fileIndex:t.fileIndex,offset:t.offset,len:t.len});try{for(let r=0;;r++)try{let r=t.viewer?$.get(t.handle)?.get(t.viewer)?.bulk===!0:!1,i=await e.read(t.handle,t.fileIndex,t.offset,t.len,{timeoutMs:Ld,...r?{deadlineMs:null}:{}});if(!n.has(t.id))return;Z({type:`read-result`,id:t.id,data:i},[i.buffer]);return}catch(i){if(!n.has(t.id))return;if(r+1>=18||!/did not arrive/.test(String(i)))throw i;let a=wf(t.handle,t.fileIndex,t.offset,t.len);Z({type:`read-stalled`,id:t.id,handle:t.handle,fileIndex:t.fileIndex,offset:t.offset,len:t.len,waitedMs:(r+1)*Ld,missing:a,cancelled:Math.min(a.length,16),downloadRate:e.status(t.handle)?.downloadRate??null,numPeers:e.status(t.handle)?.numPeers??null});for(let n of a.slice(0,16))e.cancelPieceRequests(t.handle,n);let o=t.viewer?$.get(t.handle)?.get(t.viewer):void 0;t.prioritize!==!1&&t.viewer&&o&&!o.held&&yf(t.handle)}}finally{n.delete(t.id),!t.viewer&&q.includes(t.handle)&&od.set(t.handle,Date.now())}}else if(t.type===`cancel-read`)Bd.get(t.handle)?.delete(t.id);else if(t.type===`remove`){let n=J.get(t.handle);Vd(t.handle,Rd),e.removeTorrent(t.handle,!!t.deleteFiles),_d(t.handle),n&&await rd(n)}else if(t.type===`set-plan`){let e=Array.isArray(t.wanted)?t.wanted.map(e=>Number(e)|0):void 0,n=t.firstLast===!0;bd.set(t.handle,{wanted:e,firstLast:n}),_f(t.handle);let r=J.get(t.handle);r&&await Q(r,{wantedFiles:e,firstLast:n})}else if(t.type===`set-folder`)Ru=t.handle??null;else if(t.type===`set-temporary`){if(typeof t.infoHash==`string`){let e=t.temporary===!0,n=q.find(e=>J.get(e)===t.infoHash);n!==void 0&&(e?id.add(n):(id.delete(n),vd(n)),vf(n).length&&yf(n)),await Q(t.infoHash,{ephemeral:e})}}else if(t.type===`export-start`){let n=q.find(e=>J.get(e)===t.infoHash),r=n===void 0?void 0:Hu.get(n),i=n===void 0?null:e.files(n);if(n===void 0||!i||r===void 0||!iu(r)){Z({type:`answer`,id:t.id,value:null});return}uf.set(n,{running:(uf.get(n)?.running??0)+1,until:Date.now()+lf});let a=await e.saveResumeData(n),o=i.files.flatMap((e,t)=>e.pad?[]:Lu.chunksOf(r,t).map(e=>({fileIndex:t,chunk:e})));Z({type:`answer`,id:t.id,value:{magnet:Vu.get(n)??``,resume:a,chunkBytes:Lu.chunkBytesOf(r),chunks:o}})}else if(t.type===`export-chunk`){let e=q.find(e=>J.get(e)===t.infoHash),n=e===void 0?void 0:Hu.get(e),r=e===void 0?void 0:uf.get(e);if(!r||n===void 0)throw Error(`that torrent is not being handed over`);r.until=Date.now()+lf;let i=await Lu.readChunk(n,t.fileIndex,t.chunk);Z({type:`answer`,id:t.id,value:i},[i.buffer])}else if(t.type===`export-end`){let e=q.find(e=>J.get(e)===t.infoHash),n=e===void 0?void 0:uf.get(e);if(e===void 0||!n)return;--n.running,n.running||uf.delete(e)}else if(t.type===`import-start`){if(typeof t.infoHash!=`string`||typeof t.magnet!=`string`)throw Error(`nothing to list`);let e=Date.now();await ed({infoHash:t.infoHash,magnet:t.magnet,savePath:ru(t.infoHash),addedAt:e,lastUsedAt:e,ephemeral:!1,started:!0,paused:!1}),Z({type:`answer`,id:t.id,value:!0})}else if(t.type===`import`){let n=t.infoHash;if(typeof n!=`string`||!(t.resume instanceof Uint8Array)||q.some(e=>J.get(e)===n))return;let r=ru(n);await dc(mu(n),t.resume);let i=e.addTorrentWithResume(t.resume,r);if(Yu(i)){Z({type:`add-failed`,message:G.formatMessage({id:`That torrent could not be read`,defaultMessage:`That torrent could not be read`})});return}gd(i,t.magnet,n,r),yd.add(i),Pd(i,{down:0}),qu(i),X.hold(i,Date.now()),Z({type:`added`,handle:i,magnet:t.magnet})}else if(t.type===`reserve-storage`)typeof t.infoHash==`string`&&t.infoHash&&(t.on===!1?Vf.delete(t.infoHash):Vf.add(t.infoHash));else if(t.type===`set-location`)typeof t.infoHash==`string`&&await Q(t.infoHash,{saveTo:t.to===`folder`?`folder`:`browser`});else if(t.type===`relocate`){let n=typeof t.infoHash==`string`?t.infoHash:null,r=t.to===`folder`?`folder`:`browser`,i=n?q.find(e=>J.get(e)===n):void 0;n&&i!==void 0&&await If(e,i,n,r)}else if(t.type===`import-list`){let e=[];await fc(uu,n=>e=du(n,t.removed));let n=[],r=[],i=!1;await fc(lu,a=>{let o=pu(a??[],Array.isArray(t.list)?t.list:[],e);n=o.list,r=(a??[]).filter(e=>!n.includes(e)),i=r.length>0;let s=new Map(n.map(e=>[e.infoHash,e]));for(let e of o.incoming){if(!e||typeof e.infoHash!=`string`||!e.magnet)continue;let t=cu(e),r=s.get(e.infoHash);if(r){r.name===void 0&&t.name!==void 0&&(r.name=t.name,i=!0),r.size===void 0&&t.size!==void 0&&(r.size=t.size,i=!0),r.files===void 0&&t.files!==void 0&&(r.files=t.files,i=!0);let n=Sl(jd(r),jd(e));for(let e of hl)(r[e]??0)!==n[e]&&(r[e]=n[e],i=!0);continue}let a={infoHash:e.infoHash,magnet:e.magnet,savePath:e.savePath||`/dl`,addedAt:e.addedAt||Date.now(),started:!1,ephemeral:!1,...t,...jd(e)};n.push(a),s.set(a.infoHash,a),i=!0}return n});for(let e of r)await nd(e.infoHash);i&&Z({type:`list`,list:n})}else if(t.type===`start`){let n=(await $u()).find(e=>e.infoHash===t.infoHash);if(n?.saveTo===`source`){Z({type:`add-failed`,message:G.formatMessage({id:`Nothing to download this from. Create it again from the same files.`,defaultMessage:`Nothing to download this from. Create it again from the same files.`})});return}if(n){let t=n.savePath||`/dl`,r=await uc(hu(n.infoHash)),i=r&&r.byteLength?e.addTorrentFile(r,t):e.addMagnet(n.magnet,t);if(Yu(i)){Z({type:`add-failed`,message:G.formatMessage({id:`That torrent could not be read`,defaultMessage:`That torrent could not be read`})});return}gd(i,n.magnet,n.infoHash,t,!1),Pd(i,{down:n.downloadLimit,up:n.uploadLimit}),X.hold(i,Date.now()),Z({type:`state`,torrents:Xu(),reachable:e.reachable()}),await ed({...n,started:!0,paused:!1,ephemeral:!1,lastUsedAt:Date.now()})}}else if(t.type===`remove-missing`){if(typeof t.infoHash==`string`){let n=q.find(e=>J.get(e)===t.infoHash);n!==void 0&&(Vd(n,Rd),e.removeTorrent(n,!0),_d(n)),await rd(t.infoHash)}}else if(t.type===`clear-list`){for(let t of[...q])Vd(t,Rd),e.removeTorrent(t,!0),_d(t);let t=[];await fc(lu,e=>(t=e??[],[])),await pc(uu).catch(()=>{});for(let e of t)await pc(mu(e.infoHash)).catch(()=>{}),await pc(hu(e.infoHash)).catch(()=>{});Z({type:`list`,list:[]})}else if(t.type===`pause`){Y.add(t.handle),ad.delete(t.handle),Ku(t.handle),X.forget(t.handle),e.pauseTorrent(t.handle),Vd(t.handle,zd),Ud(t.handle);let n=J.get(t.handle);n&&await Q(n,{paused:!0})}else if(t.type===`resume`){Y.delete(t.handle),ad.delete(t.handle),qu(t.handle),X.forget(t.handle),e.resumeTorrent(t.handle),X.hold(t.handle,Date.now());let n=J.get(t.handle);n&&await Q(n,{paused:!1})}else if(t.type===`recheck`){let n=J.get(t.handle);n&&await pc(mu(n)).catch(()=>{}),Uu.delete(t.handle),Vd(t.handle,G.formatMessage({id:`torrent rechecking`,defaultMessage:`torrent rechecking`})),Y.delete(t.handle),Wu.delete(t.handle),Gu.delete(t.handle),ad.delete(t.handle),X.forget(t.handle),e.forceRecheck(t.handle),X.hold(t.handle,Date.now()),n&&await Q(n,{paused:!1})}else if(t.type===`retry-now`)X.retryNow(Date.now());else if(t.type===`retry`)X.retry(t.handle,Date.now());else if(t.type===`flush-resume`)await Promise.all(q.map(e=>Ud(e)));else if(t.type===`watch`)t.readLen==null?xf(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.held===!0,t.bulk===!0||void 0,t.prepare===!0):Df(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.readLen);else if(t.type===`unwatch`)Sf(e=>e===t.viewer);else if(t.type===`set-flags`)e.setFlags(t.handle,t.flags>>>0,t.mask>>>0),Ud(t.handle);else if(t.type===`reannounce`)e.forceReannounce(t.handle);else if(t.type===`queue-move`)e.moveInQueue(t.handle,t.where);else if(t.type===`set-limits`){let n=Mu(t.down)?t.down:void 0,r=Mu(t.up)?t.up:void 0;Pd(t.handle,{down:n,up:r})&&e.status(t.handle)&&(Cd.delete(t.handle),Id(t.handle));let i=J.get(t.handle);if(i){let e={};n!==void 0&&(e.downloadLimit=n),r!==void 0&&(e.uploadLimit=r),Object.keys(e).length&&await Q(i,e)}}else if(t.type===`set-session-limits`)Mu(t.down)&&(xd.down=t.down),Mu(t.up)&&(xd.up=t.up),e.setRateLimits({download:xd.down,upload:xd.up}),await dc(ju,{...xd});else if(t.type===`inspect`){let e=typeof t.handle==`number`?t.handle:null;e!==cd&&(cd=e,ld=0)}else t.type===`unwatch-owner`&&Sf(e=>e.startsWith(t.owner+`:`))}catch(e){t.type===`read`?Z({type:`read-error`,id:t.id,error:String(e?.stack??e)}):tu.has(t.type)?Z({type:`answer`,id:t.id,error:String(e?.message??e)}):Z({type:`error`,message:String(e?.stack??e)})}},Yf=/* @__PURE__ */ new Set([`read`,`add-torrent-file`,`export-chunk`]);let Xf=Promise.resolve();self.addEventListener(`message`,e=>{let t=e.data;if(!t||typeof t!=`object`||typeof t.type!=`string`||!Pu.has(t.type))return;let n=K;if(!n){t.type===`read`?Z({type:`read-error`,id:t.id,error:`the engine is still starting`}):Z({type:`error`,message:`worker not initialized`});return}if(Yf.has(t.type)){Jf(n,t);return}Xf=Xf.then(()=>Jf(n,t))}),qf().catch(e=>Z({type:Bu?`error`:`fatal`,message:String(e?.stack??e)}));