@banou/ripple 0.0.28 → 0.0.30

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=bo(),n=xo(),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=xs();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=Ss();function A(e){return Object.prototype.toString.call(e)}function ee(e){return e<10?`0`+e.toString(10):e.toString(10)}var j=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function te(){var e=/* @__PURE__ */ new Date,t=[ee(e.getHours()),ee(e.getMinutes()),ee(e.getSeconds())].join(`:`);return[e.getDate(),j[e.getMonth()],t].join(` `)}e.log=function(){console.log(`%s - %s`,te(),e.format.apply(e,arguments))},e.inherits=vo(),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 M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var N=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(N&&e[N]){var n=e[N];if(typeof n!=`function`)throw TypeError(`The "util.promisify.custom" argument must be of type Function`);return Object.defineProperty(n,N,{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)),N&&Object.defineProperty(n,N,{value:n,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(n,t(e))},e.promisify.custom=N;function P(e,t){if(!e){var n=/* @__PURE__ */ Error(`Promise was rejected with a falsy value`);n.reason=e,e=n}return t(e)}function F(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(P.bind(null,e,a))})}return Object.setPrototypeOf(n,Object.getPrototypeOf(e)),Object.defineProperties(n,t(e)),n}e.callbackify=F})),ws=/* @__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=So().Buffer,d=Cs().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}()})),Ts=/* @__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}})),Es=/* @__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})),Ds=/* @__PURE__ */ t(((e,t)=>{var n=Es().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}})),Os=/* @__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`}})),ks=/* @__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:Os()},a=yo(),o=So().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=Ts(),d=Ds().getHighWaterMark,f=Es().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;vo()(T,a);function S(){}function C(e,t,i){r||=As(),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){te(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||=As();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&&P(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 ee(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick(R,e,t),e._writableState.errorEmitted=!0,x(e,r)):(i(r),e._writableState.errorEmitted=!0,x(e,r),R(e,t))}function j(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function te(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(typeof i!=`function`)throw new h;if(j(n),t)ee(e,n,r,t,i);else{var a=F(n)||e.destroyed;!a&&!n.corked&&!n.bufferProcessing&&n.bufferedRequest&&P(e,n),r?process.nextTick(M,e,n,a,i):M(e,n,a,i)}}function M(e,t,n,r){n||N(e,t),t.pendingcb--,r(),R(e,t)}function N(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit(`drain`))}function P(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||z(this,r,n),this},Object.defineProperty(T.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function F(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function I(e,t){e._final(function(n){t.pendingcb--,n&&x(e,n),t.prefinished=!0,e.emit(`prefinish`),R(e,t)})}function L(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final==`function`&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(I,e,t)):(t.prefinished=!0,e.emit(`prefinish`)))}function R(e,t){var n=F(t);if(n&&(L(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 z(e,t,n){t.ending=!0,R(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)}})),As=/* @__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=Is(),i=ks();vo()(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)}})})),js=/* @__PURE__ */ t(((e,t)=>{
22
22
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
23
- var n=So(),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)}})),Ms=/* @__PURE__ */ t((e=>{var t=js().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):``}})),Ns=/* @__PURE__ */ t(((e,t)=>{var n=Es().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})),Ps=/* @__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=Ns(),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}})),Fs=/* @__PURE__ */ t(((e,t)=>{t.exports=function(){throw Error(`Readable.from is not available in the browser`)}})),Is=/* @__PURE__ */ t(((e,t)=>{t.exports=E;var n;E.ReadableState=T,_o().EventEmitter;var r=function(e,t){return e.listeners(t).length},i=yo(),a=So().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=Cs(),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=ws(),f=Ts(),p=Ds().getHighWaterMark,m=Es().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;vo()(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||=As(),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||=Ms().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=As(),!(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,te(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):P(e,o)):O(e,o,t,!1)}else r||(o.reading=!1,P(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&&M(e)),P(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||=Ms().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 ee(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 j(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=ee(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?ie(this):M(this),null;if(e=j(e,t),e===0&&t.ended)return t.length===0&&ie(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=j(n,t)));var i=e>0?re(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&&ie(this)),i!==null&&this.emit(`data`,i),i};function te(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?M(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,N(e)))}}function M(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(N,e))}function N(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,B(e)}function P(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(F,e,t))}function F(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=I(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&&oe(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 I(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,B(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=oe(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?M(this):r.reading||process.nextTick(R,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(L,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(L,this),t};function L(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 R(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,z(this,e)),e.paused=!1,this};function z(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`),B(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 B(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=Ps()),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=re,Object.defineProperty(E.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function re(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 ie(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(ae,t,e))}function ae(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=Fs()),x(E,e,t)});function oe(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),Ls=/* @__PURE__ */ t(((e,t)=>{t.exports=l;var n=Es().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=As();vo()(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)}})),Rs=/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=Ls();vo()(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)}})),zs=/* @__PURE__ */ t(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=Es().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=Ns()),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})),Bs=/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=_o().EventEmitter;vo()(r,n),r.Readable=Is(),r.Writable=ks(),r.Duplex=As(),r.Transform=Ls(),r.PassThrough=Rs(),r.finished=Ns(),r.pipeline=zs(),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}})),Vs=/* @__PURE__ */ n({Server:()=>Ks,Socket:()=>Gs,_default:()=>Xs,connect:()=>qs,createConnection:()=>Js,createServer:()=>Ys,default:()=>Xs,isIP:()=>fo,isIPv4:()=>lo,isIPv6:()=>uo,t:()=>Ws}),Hs=Bs(),Us=_o(),Ws=/* @__PURE__ */ i({Server:()=>Ks,Socket:()=>Gs,_default:()=>Xs,connect:()=>qs,createConnection:()=>Js,createServer:()=>Ys,default:()=>Xs,isIP:()=>fo,isIPv4:()=>lo,isIPv6:()=>uo}),Gs=class extends Hs.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??=Ja(`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=>{if(!e){this._busyRelease?.();return}this.emit(`connect`)}),this._webVPNTcpSocketPromise}_read(e){if(!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);this._webVPNTcpSocketPromise.then(e=>{if(!e){this.push(null);return}e.reader.read().then(({value:e,done:t})=>{if(t){this.push(null);return}this._restartTimeoutTimer(),this.push(e)}).catch(e=>{this.destroy(e)})})}_write(e,t,n){if(!this._webVPNTcpSocketPromise){n(/* @__PURE__ */ Error(`Socket not connected`));return}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)}connect(...e){let t=po(...e),{relay:n}=t,r=this.__webvpn_tcp_socket_init__(Ga(`an outbound tcp socket`).then(e=>(n!==void 0&&Qa(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){if(!this._webVPNTcpSocketPromise){e();return}this._webVPNTcpSocketPromise.then(async e=>{e&&await e.writer.close()}).then(()=>e(),t=>e(t))}_destroy(e,t){if(this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._busyRelease?.(),!this._webVPNTcpSocketPromise){t(e);return}this._webVPNTcpSocketPromise.then(async e=>{e&&await(this._resetRequested?e.resetAndDestroy():e.destroy())}).then(()=>t(e),()=>t(e))}destroySoon(){if(this.writableFinished){this.destroy();return}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){if(!this._webVPNTcpSocketPromise){this.emit(`error`,/* @__PURE__ */ Error(`Cannot set socket option before connect`));return}this._webVPNTcpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}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},Ks=class extends Us.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??=Ja(`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=>{if(!e){this._busyRelease?.();return}this.emit(`listening`)}),this._webVPNTcpSocketListenerPromise}listen(...e){let t=po(...e);this._closeEmitted=!1;let n=e=>{let t=new Gs;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=>Ga(`a tcp listener`).then(a=>(i!==void 0&&Qa(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](){}},qs=(e,t)=>new Gs().connect(e,t),Js=qs,Ys=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new Ks(e);return t&&n.on(`connection`,t),n},Xs={Socket:Gs,Server:Ks,connect:qs,createConnection:Js,createServer:Ys,isIP:fo,isIPv4:lo,isIPv6:uo},Zs=/* @__PURE__ */ n({Socket:()=>ec,createSocket:()=>oc,default:()=>sc,t:()=>$s}),Qs=So(),$s=/* @__PURE__ */ i({Socket:()=>ec,createSocket:()=>oc,default:()=>sc}),ec=class extends Us.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){if(!this._webVPNUdpSocketPromise){this.emit(`error`,/* @__PURE__ */ Error(`Cannot set socket option before bind`));return}this._webVPNUdpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}_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:go,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=ic(n)),s+=n.byteLength,d=t.getUint16(s),s+=2}let f=t.getUint32(s);s+=4;try{this.emit(`message`,Qs.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 tc;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let i=so.Address4.isValid(e)?rc(e):ac(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(so.Address4.isValid(e)){let n=rc(e),r=t&&so.Address4.isValid(t)?rc(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(so.Address6.isValid(e)){let t=ac(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=mo(...e),n=this._type===`udp6`?`::`:`0.0.0.0`,r=this._relayChoice,i=this.__webvpn_udp_socket_init__(Ga(`a udp socket`).then(e=>(r!==void 0&&Qa(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??=Ja(`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`,Qs.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=>{if(!e){this._busyRelease?.();return}this.emit(`listening`)}),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(so.Address4.isValid(e)){let n=rc(e),r=t&&so.Address4.isValid(t)?rc(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(so.Address6.isValid(e)){let t=ac(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=ho(...e),n=nc(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;if(this._dataPort&&(o||so.Address4.isValid(a)||so.Address6.isValid(a))){this._portSend(r,o?void 0:a,o?void 0:t.port),n?.call(this,null,r.byteLength);return}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)})}},tc=new Uint8Array([2]),nc=e=>{if(typeof e==`string`)return co.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(nc),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)},rc=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)},ic=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(`:`)}`},ac=e=>{let t=new so.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)))},oc=(e,t)=>{let n=new ec(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},sc={Socket:ec,createSocket:oc};function cc(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function lc(e,t){let n,r=()=>{if(n)return n;let r=indexedDB.open(e);return r.onupgradeneeded=()=>r.result.createObjectStore(t),n=cc(r),n.then(e=>{e.onclose=()=>n=void 0},()=>{}),n};return(e,n)=>r().then(r=>n(r.transaction(t,e).objectStore(t)))}let uc;function dc(){return uc||=lc(`keyval-store`,`keyval`),uc}function fc(e,t=dc()){return t(`readonly`,t=>cc(t.get(e)))}function pc(e,t,n=dc()){return n(`readwrite`,n=>(n.put(t,e),cc(n.transaction)))}function mc(e,t,n=dc()){return n(`readwrite`,n=>new Promise((r,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),r(cc(n.transaction))}catch(e){i(e)}}}))}function hc(e,t=dc()){return t(`readwrite`,t=>(t.delete(e),cc(t.transaction)))}var gc={checkingFiles:1,downloadingMetadata:2,downloading:3,finished:4,seeding:5,checkingResumeData:7},_c=/^incoming connection from (\S+) \(([^)]*)\)/,vc=/^successfully listening on \[([^\]]*)\] (\S+)/,yc=/^listening on .* failed:/,bc=new TextDecoder,xc=4026531841,Sc=4026531842,Cc=4026531843,wc=4026531844,Tc=4026531845,Ec=4026531846,Dc={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},Oc={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},kc={top:0,up:1,down:2,bottom:3},Ac={tracker:1,dht:2,pex:4,lsd:8,resumeData:16,incoming:32},G={skip:0,low:1,normal:4,top:7},jc=6e4,Mc=12,Nc=1e3,Pc=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??Mc)),s=Math.max(0,Math.floor(n.deadlineStepMs??Nc)),c=n.claimedPriority??G.normal,l=n.unclaimedPriority??G.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]=G.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(G.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(G.normal);for(let e=l;e<=u;e++)d[e]=G.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)*Nc,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,kc[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(G.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,G.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),G.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]??G.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??jc;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===xc)this.decodeTorrentReady(r,a);else if(o===Sc)this.decodeStateUpdate(r,a);else if(o===wc)this.decodeResumeData(r,a,s);else if(o===Tc)this.decodePeers(r,a);else if(o===Ec)this.decodeTrackers(r,a);else if(o!==Cc){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=_c.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=vc.exec(e);if(n){this.reachability.listening[n[1].toLowerCase()]=n[2];return}yc.test(e)&&this.reachability.listenFailed.length<32&&this.reachability.listenFailed.push(e)}readStr(e,t){let n=e.getUint32(t,!0);return t+=4,[bc.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 ee=Number(e.getBigInt64(t,!0));t+=8;let j=e.getUint32(t,!0)!==0;t+=4;let te;[te,t]=this.readStr(e,t);let M=e.getInt32(t,!0);t+=4;let N=e.getInt32(t,!0);t+=4;let P=e.getUint32(t,!0);t+=4;let F=P?bc.decode(new Uint8Array(e.buffer,e.byteOffset+t,P)):``;t+=P;let I=e.getUint32(t,!0);t+=4;let L=e.getUint32(t,!0);t+=4;let R=new Uint8Array(L);R.set(new Uint8Array(e.buffer,e.byteOffset+t,L)),this.bitfieldByHandle.set(n,{pieces:R,numPieces:I});let z=0;for(let e=0;e<L;e++){let t=R[e];for(;t;)z+=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:I,numPiecesHave:z,paused:d,autoManaged:f,sequential:p,flags:m,queuePosition:M,errorCode:N,error:F,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:ee,hadIncoming:j,savePath:te,hasMetadata:r!==gc.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?.())}},Fc=8e3,Ic=e=>{try{e?.close()}catch{}},Lc=(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),Ic(r),n(null))},o=setTimeout(a,Fc);r.on(`listening`,()=>{i||(i=!0,clearTimeout(o),n(r))}),r.on(`error`,a);try{t(r)}catch{a()}});async function Rc(e,t,n=4){try{return await zc(e,t,n)}catch{return null}}async function zc(e,t,n){for(let r=0;r<n;r++){let i=await Lc(()=>t.createSocket({type:`udp4`}),e=>e.bind(0,`0.0.0.0`));if(!i)return null;let a=i.address?.()?.port;if(!a)return Ic(i),null;let o=await Lc(()=>e.createServer(),e=>e.listen(a,`0.0.0.0`)),s=o?o.address?.()?.port:void 0,c=!!o&&s===a;if(o&&!c&&Ic(o),!c){if(r<n-1){Ic(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 Bc(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):Rc(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 Pc(i,e)}catch(e){throw a&&!a.adopted&&(Ic(a.server),Ic(a.udp)),e}return o.setReservedPort(a?a.port:null),o}const Vc=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},Hc=25e5,Uc=e=>{if(!Number.isFinite(e)||e<=0)return 12;let t=Math.ceil(Hc/e)+1,n=Math.max(2,Math.floor(8388608/e));return Math.min(Math.max(t,2),n)},Wc=e=>Uc(e)*Math.max(0,e),Gc=e=>Math.max(1,Math.floor(Wc(e)/2)),Kc=(e,t)=>Math.min(2e3,Math.max(50,Math.round(e/Math.max(t,25e4)*1e3))),qc=(e,t,n,r=Hc)=>{let i=e.fileOffset+n+Math.max(0,r-1);return Math.floor(i/e.pieceLength)>=e.p1?!1:Math.abs(n-t)>=Gc(e.pieceLength)};var Jc=class{storages=/* @__PURE__ */ new Map;opened=/* @__PURE__ */ new Map;onNewStorage(e,t,n){let r=(async()=>{let r=await Yc(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 Yc(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 Xc=(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 Zc=[50,150,400,900,1500],Qc=e=>e?.name===`QuotaExceededError`,$c=e=>new Promise(t=>setTimeout(t,e)),el=e=>{let t=async(t,n,r,i)=>{let a=i;for(let i of Zc){if(Qc(a))break;if(n(),await $c(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)}}},tl=()=>{let e=new Jc,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=el(t),c=(e,t,n)=>s(e,()=>a(e,t),n),l=(e,t,n,a)=>{let o=i=>{try{Xc(i,a,{at:n})}catch(n){throw Qc(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)}},nl=67108864,rl=/^(\d+)-(\d+)$/,il=/^\d+$/,al=(e=nl)=>{let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Set,o=el(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`&&il.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=rl.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},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{Xc(n,s.subarray(o.from,o.to),{at:o.at})}catch(a){Qc(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(()=>{}))}}},ol=[5e3,15e3,3e4,6e4,12e4,3e5],sl=1e4,cl=/* @__PURE__ */ new Set([2,3]),ll=/* @__PURE__ */ new Set([1,7]),ul=e=>!!e&&e.paused&&!e.autoManaged,dl=()=>{let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=e=>ol[Math.min(e,ol.length-1)],a=i=>{e.delete(i),t.delete(i),n.delete(i),r.delete(i)};return{hold:(e,t,n=sl)=>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(ll.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`:cl.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+sl,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)}}},fl=e=>!(e.flags&Dc.localConnection)||!!(e.source&Ac.incoming),pl=e=>e.flags&Dc.utpSocket?`utp`:`tcp`,ml={total:0,byTransport:{}},hl=e=>{let t={},n=0;for(let r of e)for(let e of r){if(!fl(e)||e.connectionType!==0)continue;n+=1;let r=pl(e);t[r]=(t[r]??0)+1}return{total:n,byTransport:t}},gl={activeSeconds:0,seedingSeconds:0},_l=[`activeSeconds`,`seedingSeconds`,`downloaded`,`uploaded`,`wasted`],vl={activeSeconds:0,seedingSeconds:0,downloaded:0,uploaded:0,wasted:0},K=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0,yl=(e,t)=>({activeSeconds:Math.max(0,K(t.activeSeconds)-K(e.activeSeconds)),seedingSeconds:Math.max(0,K(t.seedingSeconds)-K(e.seedingSeconds))}),bl=(e,t,n)=>{let r=yl(t,n);return{activeSeconds:K(e?.activeSeconds)+r.activeSeconds,seedingSeconds:K(e?.seedingSeconds)+r.seedingSeconds}},xl=(e,t)=>Object.fromEntries(_l.map(n=>[n,Math.max(0,K(t[n])-K(e[n]))])),Sl=(e,t,n)=>{let r=xl(t,n);return Object.fromEntries(_l.map(t=>[t,K(e?.[t])+r[t]]))},Cl=(e,t)=>Object.fromEntries(_l.map(n=>[n,Math.max(K(e?.[n]),K(t?.[n]))])),wl=(e,t)=>t.activeSeconds-K(e?.activeSeconds)>=30||t.seedingSeconds-K(e?.seedingSeconds)>=30,Tl=67108864,El=e=>!Number.isFinite(e)||e<=0?0:Math.min(1e9,Math.floor(e*.1)),Dl=(e,t)=>!Number.isFinite(e)||e<=0?Math.max(0,t):Math.max(Math.min(.25*e,2e10),Math.max(0,t)),Ol=({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;if(a<Math.min(n,67108864))return!0;let o=i.reduce((e,t)=>e+Math.max(0,t.bytesOnDisk),0);return r>0&&r+67108864>a+o},kl=(e,t)=>e.usedAt-t.usedAt||(e.infoHash<t.infoHash?-1:+(e.infoHash>t.infoHash)),Al=({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(kl);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+El(t)),u=o(e=>c+a[e]>=s+Tl),d=l>=0?l:Math.max(0,u),f=a[i.length],p=i.reduce((e,t)=>Math.max(e,t.bytesOnDisk),0),m=Dl(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)},jl={start:0,end:0},Ml=(e,t,n)=>{let r=Math.min(n,e.size);return r<=t?jl:{start:Math.floor((e.offset+t)/e.pieceLength),end:Math.floor((e.offset+r-1)/e.pieceLength)+1}},Nl=(e,t,n)=>Ml(e,n*t,(n+1)*t),Pl=(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},Fl=(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},Il=(e,t,n)=>e>t&&Math.floor(t/n)>=23,Ll=({file:e,chunkBytes:t,room:n,reader:r,held:i,pinned:a=[]})=>{if(!Il(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=Ml(e,0,t),d=Math.max(0,o-2-s),f=n=>{if(!d){let n=Ml(e,s*t,e.size);return{want:[u,n],ahead:n,slack:jl}}let r=Ml(e,s*t,n*t),i=Ml(e,n*t,(n+2)*t);return{want:[u,r,i,Ml(e,o*t,e.size)],ahead:r,slack:i}},p=n=>Pl(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)}},Rl=(e,t,n)=>e||t<n,zl=(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 Bl=8,Vl=2e4,Hl=e=>typeof e.values==`function`,Ul=async e=>{let t=0,n=0,r=async(e,i)=>{if(!(i>Bl))for await(let a of e.values()){if(++n>Vl)return;if(Hl(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}},Wl=(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)},Gl,Kl,ql=(e,t,n)=>{if(e!==void 0)return n!==Kl&&(Gl=void 0),Kl=n,Gl=Gl===void 0?e:Math.min(Gl,e),Math.max(Gl,t??0)},Jl=async e=>e.persisted?e.persisted().then(e=>e===!0).catch(()=>Kl):void 0,Yl={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=>Ul(e)).catch(()=>null):null,Jl(e)]),i=Wl(t,n);return{...t,usage:i,quota:ql(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 Jl(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 Xl=/^(?:[0-9a-f]{40}|[0-9a-f]{64}|[a-z2-7]{32})$/i,Zl=({entries:e,listedHashes:t,claimedNames:n,attributable:r})=>e.filter(({name:e,kind:i})=>n.has(e)?!1:i===`directory`&&Xl.test(e)?!t.has(e.toLowerCase()):r).map(({name:e})=>e),Ql=async e=>{let t=[];for await(let n of e.values())t.push({name:n.name,kind:n.kind});return t},$l=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},eu=async(e,t,n)=>{let r=await $l(e,t);if(!r)return[];let i=[];for(let e of Zl({...n,entries:await Ql(r)}))try{await r.removeEntry(e,{recursive:!0}),i.push(e)}catch{}return i},tu=async e=>{let t=0;for(let{name:n,kind:r}of await Ql(e))r===`file`&&n.startsWith(`.ripple-probe-`)&&await e.removeEntry(n).then(()=>!0,()=>!1)&&t++;return t},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=e=>typeof e.getFile==`function`?e.getFile():Promise.resolve(e),vu=e=>`/native/${e}`,yu=e=>e===`/native`||!!e?.startsWith(`/native/`),bu=e=>`/source/${e}`,xu=e=>e===`/source`||!!e?.startsWith(`/source/`),Su=e=>yu(e)||xu(e),Cu=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()},wu=(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?_u(n):null};return{usageOf:async(e,t)=>Su(e)?0:c(e).usageOf(e,t),refusedFile:e=>c(e).refusedFile(e),onNewStorage:(e,t,r)=>{if(xu(t)){a.set(e,{savePath:t,files:r,handles:n(t)});return}if(iu(t)?o.add(e):o.delete(e),!yu(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 Cu(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 Cu(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)}}},Tu=(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))],Eu=({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?G.normal:G.skip);if(!o)for(let[r,i]of e.entries()){if(!c(r)||i.size<=0)continue;let[e,a]=Tu(i,t,n);for(let t=e;t<=a;t++)l[t]=G.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]=Tu(a,t,n);for(let t=0;t<r;t++){let n=e+t,r=o-t;n<=o&&(l[n]=G.top),r>=e&&(l[r]=G.top)}}}return l},Du=({wanted:e,firstLast:t})=>e===void 0&&!t,Ou=e=>xu(e)?`source`:yu(e)?`folder`:`browser`,ku=(e,t)=>{if(e===`source`){if(!t)throw Error(`a source-backed torrent needs its infohash to name its save path`);return bu(t)}return e===`folder`?t?vu(t):`/dl`:nu(t)},Au=`ripple:rate-limits`,ju=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,Mu=e=>{let t=e??{};return{down:ju(t.down)?t.down:0,up:ju(t.up)?t.up:0}},Nu=/* @__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`.split(`.`)),Pu=e=>`ripple:source:`+e;let q=null,Fu=null;const Iu=al(nl);let Lu=null;const Ru=/* @__PURE__ */ new Map;let zu=!1;const J=[],Bu=/* @__PURE__ */ new Map,Y=/* @__PURE__ */ new Map,Vu=/* @__PURE__ */ new Map,Hu=/* @__PURE__ */ new Map,X=/* @__PURE__ */ new Set,Uu=/* @__PURE__ */ new Set,Wu=/* @__PURE__ */ new Set,Gu=e=>{Wu.delete(e),Uu.add(e)},Ku=e=>{Uu.delete(e),Wu.add(e)},qu=/* @__PURE__ */ new Map,Z=dl(),Ju=e=>e>=4294967040,Q=(e,t)=>self.postMessage(e,t??[]),Yu=()=>J.map(e=>{let t=q.bitfield(e);return{handle:e,magnet:Bu.get(e)??``,files:q.files(e),status:q.status(e),bitfield:t?{numPieces:t.numPieces,pieceLength:t.pieceLength,length:t.length,pieces:t.pieces}:null,recovery:Z.state(e),userPaused:X.has(e),windowed:Ud.has(e),uptime:Xu(e),sessionUptime:Zu(e),totals:kd(e)}}),Xu=e=>{let t=q?.status(e),n=Cd.get(e);return!t||!n?wd.get(e)??gl:bl(wd.get(e),n,t)},Zu=e=>{let t=q?.status(e),n=Cd.get(e);return t&&n?yl(n,t):gl},Qu=async()=>await fc(`ripple:torrents`)??[],$u=async e=>{let t=[];await mc(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}),Q({type:`list`,list:t})},$=async(e,t,n=!1)=>{let r=[];await mc(lu,n=>{r=n??[];let i=r.findIndex(t=>t.infoHash===e);return i>=0&&(r[i]={...r[i],...t}),r}),n||Q({type:`list`,list:r})},ed=e=>{let t=Y.get(e);t&&$(t,{lastUsedAt:Date.now()},!0).catch(()=>{})},td=async e=>{await hc(mu(e)).catch(()=>{}),await hc(hu(e)).catch(()=>{}),await hc(Pu(e)).catch(()=>{}),await hc(gu(e)).catch(()=>{})},nd=async e=>{let t=[];await mc(lu,n=>t=(n??[]).filter(t=>t.infoHash!==e)),await mc(uu,t=>du(t,[{infoHash:e,removedAt:Date.now()}])),await td(e),Q({type:`list`,list:t})},rd=/* @__PURE__ */ new Set,id=/* @__PURE__ */ new Set,ad=/* @__PURE__ */ new Map,od=/* @__PURE__ */ new Set;let sd=null,cd=0,ld=0,ud=ml;const dd=e=>{let t=sd;return t==null||!J.includes(t)?null:(q.peers(t),e-cd>=5e3&&(cd=e,q.trackers(t)),{handle:t,peers:q.lastPeers(t),trackers:q.lastTrackers(t)})},fd=e=>{let t=q?.files(e);if(!t)return[];let n=t.files.map(e=>e.path.split(`/`).filter(Boolean)[0]).filter(Boolean);return[...new Set(n)]},pd=(e,t,n,r,i=!1)=>{J.includes(e)||J.push(e),Bu.set(e,t),n&&(Y.set(e,n),od.add(e)),Vu.set(e,r),i?rd.add(e):rd.delete(e)},md=e=>{let t=J.indexOf(e);t>=0&&J.splice(t,1),Bu.delete(e),Y.delete(e),Vu.delete(e),Hu.delete(e),X.delete(e),Z.forget(e),Ld.delete(e),Fd.delete(e),Uu.delete(e),Wu.delete(e),qu.delete(e),Bd.delete(e),Vd.delete(e),Hd.delete(e),gd.delete(e),_d.delete(e),yd.delete(e),bd.delete(e),xd.delete(e),Cd.delete(e),wd.delete(e),Td.delete(e),Ed.delete(e),rd.delete(e),id.delete(e),ad.delete(e),od.delete(e),Ud.delete(e),Wd.delete(e),Gd.delete(e),rf.delete(e),af.delete(e)},hd=e=>{id.delete(e)&&(Ku(e),q?.resumeTorrent(e),Z.hold(e,Date.now()))},gd=/* @__PURE__ */ new Set,_d=/* @__PURE__ */ new Map;let vd={down:0,up:0};const yd=/* @__PURE__ */ new Map,bd=/* @__PURE__ */ new Set,xd=/* @__PURE__ */ new Map;let Sd=0;const Cd=/* @__PURE__ */ new Map,wd=/* @__PURE__ */ new Map,Td=/* @__PURE__ */ new Map,Ed=/* @__PURE__ */ new Map,Dd=e=>({activeSeconds:e.activeSeconds,seedingSeconds:e.seedingSeconds,downloaded:e.allTimeDownload,uploaded:e.allTimeUpload,wasted:e.wasted}),Od=e=>({activeSeconds:e?.activeSeconds??0,seedingSeconds:e?.seedingSeconds??0,downloaded:e?.downloaded??0,uploaded:e?.uploaded??0,wasted:e?.wasted??0}),kd=e=>{let t=q?.status(e),n=Td.get(e);return!t||!n?Ed.get(e)??vl:Sl(Ed.get(e),n,Dd(t))},Ad=(e,t,n)=>{let r=xd.get(e);xd.set(e,r?{flags:r.flags&~n|t&n,mask:r.mask|n}:{flags:t&n,mask:n})},jd=(e,t)=>{let n={...yd.get(e)};return ju(t.down)&&(n.down=t.down),ju(t.up)&&(n.up=t.up),!ju(n.down)&&!ju(n.up)?!1:(yd.set(e,n),bd.add(e),!0)},Md=e=>{let t=yd.get(e)?.down;return Gd.has(e)?Math.min(t||16384,16384):t},Nd=e=>{let t=yd.get(e);if(!q||!t)return;let n=Md(e);ju(n)&&q.setDownloadLimit(e,n),ju(t.up)&&q.setUploadLimit(e,t.up)},Pd=6e3,Fd=/* @__PURE__ */ new Map,Id=(e,t)=>{let n=Fd.get(e);if(n?.size){for(let e of n.keys())Q({type:`read-error`,id:e,error:t});n.clear()}},Ld=/* @__PURE__ */ new Set,Rd=async e=>{let t=Y.get(e);if(!t||!q||Ld.has(e)||xu(Vu.get(e)))return!1;Ld.add(e);try{let n=await q.saveResumeData(e);return J.includes(e)?(await pc(mu(t),n),!0):!1}catch(e){return console.error(`[worker] saving resume data failed`,String(e)),!1}finally{Ld.delete(e)}},zd=(e,t)=>{let n=q?.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}},Bd=/* @__PURE__ */ new Map,Vd=/* @__PURE__ */ new Set,Hd=/* @__PURE__ */ new Set,Ud=/* @__PURE__ */ new Map,Wd=/* @__PURE__ */ new Map,Gd=/* @__PURE__ */ new Set;let Kd;const qd=`ripple:ceiling-fixed`;let Jd,Yd=null;const Xd=(e,t,n)=>[...cf(e).filter(e=>e.fileIndex===t).map(e=>Ml(n,e.fromOffset,e.fromOffset+Wc(n.pieceLength))),...[...Fd.get(e)?.values()??[]].filter(e=>e.fileIndex===t).map(e=>Ml(n,e.offset,e.offset+e.len))],Zd=(e,t,n)=>{let r=Wd.get(e),[i]=n;if(r===void 0||!i||!Kd?.fixed||!rd.has(e)||n.some(e=>e.fileIndex!==i.fileIndex))return null;let a=t.files[i.fileIndex],o=Vu.get(e);if(!a||o===void 0)return null;let s={offset:a.offset,size:a.size,pieceLength:t.pieceLength},c=Iu.chunkBytesOf(o),l=Iu.chunksOf(o,i.fileIndex),u=Ll({file:s,chunkBytes:c,room:r,reader:i.fromOffset,held:l,pinned:Xd(e,i.fileIndex,s)});return u&&{...u,fileIndex:i.fileIndex,file:s,chunkBytes:c}},Qd=(e,t)=>e.fileIndex===t.fileIndex&&JSON.stringify(e.want)===JSON.stringify(t.want),$d=(e,t)=>{let n=q?.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},ef=()=>Yd?Yd.space.limitBytes-Yd.space.usedBytes-(Iu.footprint()-Yd.footprint)-Tl:1/0,tf=e=>{let t=Ud.get(e),n=!!t&&!Fd.get(e)?.size&&Rl($d(e,t.ahead),ef(),t.chunkBytes);n!==Gd.has(e)&&(n?Gd.add(e):Gd.delete(e),q?.setDownloadLimit(e,Md(e)??0))},nf=e=>{let t=Ud.get(e),n=q?.bitfield(e);if(!t||!n||t.slack.end<=t.slack.start)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&&q?.forgetPieces(e,r)},rf=/* @__PURE__ */ new Set,af=/* @__PURE__ */ new Set,of=async e=>{if(rf.has(e)){af.add(e);return}rf.add(e);let t=!1;try{let n=Vu.get(e),r=()=>{let t=Ud.get(e);if(!t||n===void 0)return[];let r=/* @__PURE__ */ new Set([...t.keep,...Pl(t.file,t.chunkBytes,Xd(e,t.fileIndex,t.file))]);return Iu.chunksOf(n,t.fileIndex).filter(e=>!r.has(e)).map(e=>({chunk:e,fileIndex:t.fileIndex,pieces:Nl(t.file,t.chunkBytes,e)}))},i=({start:t,end:n})=>q?.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++)q?.cancelPieceRequests(e,t);t=!0}return r?.busy===0});if(!a.length||n===void 0)return;if(!await Rd(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(Iu.drop(n,t,e))}await Promise.all(s)}catch(e){console.error(`[worker] dropping chunks failed`,String(e))}finally{rf.delete(e),af.delete(e)?of(e):t&&Ud.has(e)&&setTimeout(()=>void of(e),1e3)}},sf=e=>{let t=_d.get(e);if(!q||!t||Du(t))return;let n=q.files(e);n&&q.prioritizePieces(e,Eu({files:n.files,pieceLength:n.pieceLength,numPieces:Math.ceil(n.totalSize/n.pieceLength),wanted:t.wanted,firstLast:t.firstLast}))},cf=e=>{let t=Bd.get(e);return t?[...t.values()].filter(e=>!e.held):[]},lf=e=>{if(!q)return;if(!J.includes(e)){Bd.delete(e),Hd.delete(e);return}let t=cf(e);if(!t.length){if(!q.files(e)){Hd.add(e);return}Hd.delete(e),Ud.delete(e),tf(e),q.clearStreamWindow(e),sf(e),rd.has(e)&&!X.has(e)&&!id.has(e)&&(id.add(e),Gu(e),q.pauseTorrent(e),Rd(e));return}hd(e);let n=q.files(e);if(!n){Hd.add(e);return}Vd.delete(e)&&If();let r=t.flatMap(({fileIndex:e,fromOffset:t,bulk:r})=>{let i={fileIndex:e,offset:t},a=n.files[e];return!r&&a?.size?[i,{fileIndex:e,offset:a.size-1}]:[i]}),i=t.some(e=>!e.bulk),a=Zd(e,n,t);a?Ud.set(e,a):Ud.delete(e),q.setStreamWindow(e,r,{unclaimedPriority:G.skip,windowPieces:Uc(n.pieceLength),deadlineStepMs:Kc(n.pieceLength,q.status(e)?.downloadRate||3e6),deadlines:i,...a?{keep:a.want}:{}})?Hd.delete(e):Hd.add(e),a&&of(e),nf(e),tf(e)},uf=e=>{let t=q?.files(e),n=cf(e);if(!t||!n.length)return;let r=Zd(e,t,n),i=Ud.get(e);if(r||i){if(!r||!i||!Qd(r,i)){lf(e);return}Ud.set(e,r),of(e)}},df=e=>{X.add(e),id.delete(e),Gu(e),Z.forget(e),q?.pauseTorrent(e)},ff=(e,t,n,r,i=!1,a)=>{if(!J.includes(t))return;let o=Bd.get(t),s=!o?.size;o||Bd.set(t,o=/* @__PURE__ */ new Map);let c=a??o.get(e)?.bulk;o.set(e,{fileIndex:n,fromOffset:r,...i?{held:i}:{},...c?{bulk:c}:{}}),s&&(ed(t),Vd.add(t)),lf(t)},pf=e=>{for(let[t,n]of Bd){let r=!1;for(let t of[...n.keys()])e(t)&&(n.delete(t),r=!0);n.size||(Bd.delete(t),r&&ed(t)),r&&lf(t)}},mf=(e,t,n,r)=>{let i=q?.files(e),a=i?.files[t],o=q?.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},hf=(e,t,n,r)=>{let i=q?.files(e),a=i?.files[t],o=q?.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},gf=async e=>{let t=e=>Math.max(0,e.size-e.held),n=[],r=[];for(let[e,t]of[...Bd]){let i=Fu,a=q?.files(e),o=Vu.get(e);if(!i||!a||!t.size||o===void 0||Su(o))continue;let s=async t=>({h:e,size:a.files[t]?.size??0,held:await i.usageOf(o,t)??0}),[c]=cf(e),l=!!Kd?.fixed&&rd.has(e)&&iu(o);for(let e of new Set([...t.values()].map(e=>e.fileIndex)))n.push({...await s(e),cache:l&&e===c?.fileIndex,chunkBytes:Iu.chunkBytesOf(o)});let u=i.refusedFile(o);u!==void 0&&r.push(await s(u))}let i=n.filter(e=>!e.cache).reduce((e,n)=>e+t(n),0),a=n.filter(e=>e.cache),o=e.limitBytes-e.usedBytes+a.reduce((e,t)=>e+t.held,0)-i-Tl,s=Fl(a.map(e=>e.size),o),c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Set,u=i;a.forEach((e,n)=>{let r=s[n]??0;c.set(e.h,r),Il(e.size,r,e.chunkBytes)&&l.add(e.h),u+=l.has(e.h)?Math.max(0,r-e.held):t(e)});let d=r.filter(e=>!l.has(e.h)).reduce((e,n)=>e+t(n),0);return{pendingBytes:u,refusedBytes:d,rooms:c}},_f=(e,t,n,r,i)=>{if(!e||!J.includes(t))return;let a=Bd.get(t)?.get(e);if(!a||a.held||a.fileIndex!==n){ff(e,t,n,r);return}let o=zd(t,n);if(!o)return;let s={fileOffset:o.file.offset,pieceLength:o.pieceLength,p1:o.p1};qc(s,a.fromOffset,r,i)&&ff(e,t,n,r)},vf=async e=>{let t=e.filter(e=>!Su(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}},yf=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}},bf=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}),xf=async()=>{try{let{usage:e,quota:t}=await Yl.estimate();return!t||e===void 0?null:{usedBytes:e,limitBytes:t}}catch{return null}},Sf=async()=>{try{let{usage:e,quota:t}=await navigator.storage.estimate();return t&&e!==void 0?t-e:null}catch{return null}},Cf=async e=>{for(let t=0;t<4e3;t+=250){await new Promise(e=>setTimeout(e,250));let t=await xf();if(!t||t.usedBytes<e)return t}return xf()},wf=async(e,t,n,r,i={})=>{Id(t,r),e.removeTorrent(t,!0),md(t),await hc(mu(n)).catch(()=>{}),await $(n,{started:!1,paused:!1,...i})},Tf=(e,t,n)=>wf(e,t,n,`torrent removed to make room`),Ef=async(e,t,n,r)=>{let i=Ou(Vu.get(t));if(i===r)return;let a=Bu.get(t)??``,o=ku(r,n),s=X.has(t),c=rd.has(t);Id(t,`files moved`),e.removeTorrent(t,i===`browser`),md(t),await hc(mu(n)).catch(()=>{});let l=e.addMagnet(a,o);if(Ju(l)){Q({type:`add-failed`,message:`Moving the files left the torrent unaddable`}),await $(n,{savePath:o,saveTo:r,started:!1});return}pd(l,a,n,o,c),r===`folder`&&Ad(l,Oc.uploadMode,Oc.uploadMode),s?(X.add(l),Gu(l)):Ku(l),Z.hold(l,Date.now()),await $(n,{savePath:o,saveTo:r,started:!0})},Df=(e,{infoHash:t,magnet:n,bytes:r,handles:i,paused:a})=>{let o=bu(t);Ru.set(o,i);let s=e.addTorrentFile(r,o);return Ju(s)?(Ru.delete(o),null):(pd(s,n,t,o,!1),Ad(s,Oc.uploadMode,Oc.uploadMode),a&&(X.add(s),Gu(s)),Z.hold(s,Date.now()),s)},Of=async(e,t)=>{let n=new Map(e.map(e=>[e.infoHash,e])),r=[],i=[];for(let e of[...J]){let a=Y.get(e);if(!a)continue;let o=n.get(a);if(!o?.ephemeral||!au(o.savePath,a)||Bd.get(e)?.size||Fd.get(e)?.size)continue;let s=o.lastUsedAt??o.addedAt,c=await Fu?.usageOf(o.savePath)??0;if(c<=0)continue;let l=t-(ad.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 kf=!1;const Af=e=>{let t=Ol(e);t!==kf&&(kf=t,Q({type:`storage-full`,full:t,usedBytes:e.usedBytes,limitBytes:e.limitBytes}))},jf=/* @__PURE__ */ new Set;let Mf=!1;const Nf=async()=>{if(!q||Mf)return 0;Mf=!0;try{let e=await Qu(),t=new Set(e.map(e=>e.infoHash.toLowerCase()));for(let e of jf)t.add(e.toLowerCase());let n=/* @__PURE__ */ new Set,r=!0;for(let e of J){let i=Y.get(e);if(i&&t.add(i.toLowerCase()),(Vu.get(e)??`/dl`)!==`/dl`)continue;let a=fd(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}!J.some(e=>Y.get(e)===t.infoHash)&&t.started!==!1&&(r=!1)}}}let i=await navigator.storage.getDirectory(),a=[...await eu(i,`/dl`,{listedHashes:t,claimedNames:n,attributable:r}),...await eu(i,`/cache`,{listedHashes:t,claimedNames:/* @__PURE__ */ new Set,attributable:!1})];return await tu(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{Mf=!1}};let Pf=!1,Ff=!1;const If=async()=>{let e=q;if(!e)return;if(Pf){Ff=!0;return}Pf=!0;let t=null,n={pendingBytes:0,refusedBytes:0,rooms:/* @__PURE__ */ new Map},r=[],i=[],a=e=>({...e,pendingBytes:Kd?.fixed===!1?0:n.pendingBytes,refusedBytes:n.refusedBytes,candidates:[...r,...i]});try{let o=await xf();if(!o)return;t=o,Jd===void 0&&(Jd=await fc(qd).catch(()=>null)??null);let s=async e=>{Yd={space:e,footprint:Iu.footprint()};let t=await Sf();if(t===null)return;let n={usedBytes:e.usedBytes,headroomBytes:t};Kd=zl(Kd??(typeof Jd==`boolean`?{...n,fixed:Jd}:void 0),n,nl),Kd.fixed!==void 0&&Kd.fixed!==Jd&&(Jd=Kd.fixed,pc(qd,Jd).catch(()=>{}))};await s(o),n=await gf(o);let c=await Of(await Qu(),Date.now());for(r=c.evictable,i=c.graced;r.length;){let[i]=Al({...o,pendingBytes:n.pendingBytes,candidates:r});if(!i)break;r=r.filter(e=>e.infoHash!==i);let a=J.find(e=>Y.get(e)===i);if(a===void 0||Bd.get(a)?.size||Fd.get(a)?.size)continue;let c=o.usedBytes;t=null,await Tf(e,a,i);let l=await Cf(c);if(!l)return;o=l,t=l,await s(l),n=await gf(o)}Wd.clear();for(let[e,t]of n.rooms)Wd.set(e,t);for(let e of/* @__PURE__ */ new Set([...Wd.keys(),...Ud.keys()]))uf(e);Ol(a(o))&&await Nf()&&(o=await Cf(o.usedBytes)??o),t=o}catch(e){console.error(`[worker] storage budget pass failed`,String(e))}finally{Pf=!1,t&&Af(a(t)),Ff&&(Ff=!1,If())}},Lf=async()=>{let e=console.error.bind(console);if(console.error=(...t)=>{e(...t);try{Q({type:`worker-error`,args:t.map(String)})}catch{}},!await yf()){Q({type:`storage-unavailable`});return}Qu().then(e=>{e.length&&Q({type:`list`,list:e})}).catch(()=>{});let t=Promise.race([fc(Au).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]);Fu=wu(tl(),()=>Lu,e=>Ru.get(e)??null,Iu),q=await Bc({net:Vs,dgram:Zs,storage:Fu,utpReceiveBufferBytes:4194304});for(let e=0;e<30;e++)q.tick();vd=Mu(await t),q.setRateLimits({download:vd.down,upload:vd.up});try{let e=await Qu(),t=!await vf(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 fc(mu(r.infoHash)),a=await fc(hu(r.infoHash));if(t&&i&&i.byteLength){await hc(mu(r.infoHash)).catch(()=>{}),r.started=!1,n=!0;continue}let o=i&&i.byteLength?q.addTorrentWithResume(i,e):a&&a.byteLength?q.addTorrentFile(a,e):q.addMagnet(r.magnet,e);Ju(o)||(pd(o,r.magnet,r.infoHash,e,r.ephemeral===!0),_d.set(o,{wanted:r.wantedFiles,firstLast:r.firstLast}),gd.add(o),jd(o,{down:r.downloadLimit,up:r.uploadLimit}),wd.set(o,{activeSeconds:r.activeSeconds??0,seedingSeconds:r.seedingSeconds??0}),Ed.set(o,Od(r)),r.paused?(X.add(o),Gu(o)):Ku(o),Z.hold(o,Date.now()))}n&&await pc(lu,e)}catch(e){console.error(`[worker] restore failed`,e)}Q({type:`ready`}),zu=!0,Q({type:`list`,list:await Qu().catch(()=>[])}),Q({type:`state`,torrents:Yu(),reachable:q.reachable(),inboundNow:ud,rateLimits:{...vd}}),setInterval(()=>{if(!q)return;let e=Date.now();q.popAlerts();for(let e of J)q.postStatus(e);for(let e of[...gd])q.files(e)&&(gd.delete(e),cf(e).length||lf(e));for(let e of[...Hd])lf(e);for(let e of[...Ud.keys()])nf(e),tf(e);for(let e of[...bd])q.status(e)&&(bd.delete(e),Nd(e));for(let e of J){if(Cd.has(e))continue;let t=q.status(e);t&&(Cd.set(e,{activeSeconds:t.activeSeconds,seedingSeconds:t.seedingSeconds}),Td.set(e,Dd(t)))}for(let[e,t]of[...xd])q.status(e)&&(xd.delete(e),q.setFlags(e,t.flags>>>0,t.mask>>>0));for(let e of[...od]){let[t]=fd(e);if(!t)continue;od.delete(e);let n=Y.get(e);if(!n)continue;let r=q.files(e);$(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 Uu){let t=q.status(e);t&&!ll.has(t.state)&&(ul(t)?Uu.delete(e):q.pauseTorrent(e))}for(let e of Wu){if(X.has(e)||id.has(e)){Wu.delete(e);continue}let t=q.status(e);if(t&&!ll.has(t.state)){if(!t.paused){Wu.delete(e);continue}if(t.autoManaged||t.errorCode){Wu.delete(e);continue}q.resumeTorrent(e)}}Z.retain(new Set(J));for(let t of J){let n=q.status(t);Z.observe(t,n&&bf(n),X.has(t)||id.has(t),e)}for(let{handle:t,reason:n}of Z.due(e))n===`stalled`&&q.pauseTorrent(t),q.resumeTorrent(t);if(e-ld>=2e3){ld=e;for(let e of J)q.peers(e)}ud=hl(J.map(e=>q.lastPeers(e))),Q({type:`state`,torrents:Yu(),reachable:q.reachable(),inboundNow:ud,detail:dd(e),rateLimits:{...vd}});for(let t of J){let n=q.status(t);if(!n||n.state!==4&&n.state!==5||Hu.get(t)===n.paused||Ld.has(t))continue;let r=qu.get(t);if(r&&e<r.at)continue;let i=n.paused;Rd(t).then(e=>{if(e){Hu.set(t,i),qu.delete(t);return}let n=(qu.get(t)?.tries??0)+1;qu.set(t,{tries:n,at:Date.now()+Math.min(1e3*2**n,6e4)})})}},500),setInterval(()=>{if(!q)return;for(let e of J){let t=q.status(e);t&&t.state===3&&Rd(e)}let e=!1;for(let t of J){let n=q.status(t),r=Y.get(t),i=Cd.get(t);if(!n||!r||!i)continue;e=!0;let a=bl(wd.get(t),i,n);if(!wl(wd.get(t),a))continue;wd.set(t,a),Cd.set(t,{activeSeconds:n.activeSeconds,seedingSeconds:n.seedingSeconds});let o=Dd(n),s=Sl(Ed.get(t),Td.get(t)??o,o);Ed.set(t,s),Td.set(t,o),$(r,{activeSeconds:a.activeSeconds,seedingSeconds:a.seedingSeconds,downloaded:s.downloaded,uploaded:s.uploaded,wasted:s.wasted},!0).catch(()=>{})}e&&Date.now()-Sd>=3e5&&(Sd=Date.now(),Qu().then(e=>Q({type:`list`,list:e})).catch(()=>{}))},15e3),setInterval(()=>{If()},1e4),If(),setTimeout(()=>{Nf(),setInterval(()=>{Nf()},6e5)},6e4),self.addEventListener(`online`,()=>Z.retryNow(Date.now()))},Rf=async(e,t)=>{try{if(t.type===`add-magnet`){let n=Vc(t.magnet),r=n?J.find(e=>Y.get(e)===n):void 0;if(r!==void 0)n&&!t.ephemeral?(rd.delete(r),hd(r),cf(r).length&&lf(r),await $(n,{ephemeral:!1,lastUsedAt:Date.now()})):ed(r),Q({type:`added`,handle:r,magnet:Bu.get(r)||t.magnet});else{let r=n?(await Qu()).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(Ju(o)){Q({type:`add-failed`,message:`That is not a valid magnet link`});return}pd(o,t.magnet,n,a,i),_d.set(o,{wanted:r?.wantedFiles,firstLast:r?.firstLast}),t.hold===!0&&gd.add(o),jd(o,{down:r?.downloadLimit,up:r?.uploadLimit}),wd.set(o,{activeSeconds:r?.activeSeconds??0,seedingSeconds:r?.seedingSeconds??0}),Ed.set(o,Od(r)),Z.hold(o,Date.now());let s=Date.now();t.paused===!0&&df(o),n&&await $u({infoHash:n,magnet:t.magnet,savePath:a,addedAt:s,lastUsedAt:s,ephemeral:i,started:!0,paused:t.paused===!0}),Q({type:`added`,handle:o,magnet:t.magnet}),If()}}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){Q({type:`add-failed`,message:`That torrent could not be created`});return}if(!r.some(e=>e)){Q({type:`add-failed`,message:`Some of those files could not be opened`});return}await pc(hu(n),i);let a=Df(e,{infoHash:n,magnet:t.magnet,bytes:i,handles:r,paused:!1});if(a===null){await hc(hu(n)).catch(()=>{}),Q({type:`add-failed`,message:`The engine refused the torrent that was just built`});return}let o=Date.now();await $u({infoHash:n,magnet:t.magnet,savePath:bu(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})}),Q({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)){Q({type:`add-failed`,message:`Some of those files could not be opened`});return}let i=[...Y.entries()].find(([,e])=>e===n);if(i){Q({type:`added`,handle:i[0],magnet:Bu.get(i[0])??``});return}let a=await fc(hu(n));if(!a?.byteLength){Q({type:`add-failed`,message:`The torrent this was built from is no longer stored`});return}let o=(await Qu()).find(e=>e.infoHash===n),s=Df(e,{infoHash:n,magnet:o?.magnet??t.magnet??``,bytes:a,handles:r,paused:o?.paused===!0});if(s===null){Q({type:`add-failed`,message:`The engine refused that torrent`});return}wd.set(s,{activeSeconds:o?.activeSeconds??0,seedingSeconds:o?.seedingSeconds??0}),Ed.set(s,Od(o)),await $(n,{started:!0,lastUsedAt:Date.now()}),Q({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(Ju(i)){Q({type:`add-failed`,message:`That file is not a valid .torrent`});return}pd(i,``,null,n,t.ephemeral===!0),Z.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(!J.includes(i))return;if(!a){e.removeTorrent(i,!0),md(i),Q({type:`add-failed`,message:`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(`&`);pd(i,s,a,n),await pc(hu(a),r);let c=Date.now();t.paused===!0&&df(i);let l=t.saveTo===`browser`||t.saveTo===`folder`?{saveTo:t.saveTo}:{};await $u({infoHash:a,magnet:s,savePath:n,addedAt:c,lastUsedAt:c,ephemeral:t.ephemeral===!0,started:!0,paused:t.paused===!0,...l,...t.created===!0?{created:!0}:{}}),jf.delete(a),Q({type:`added`,handle:i,magnet:s})}else if(t.type===`read`){if(!J.includes(t.handle)){Q({type:`read-error`,id:t.id,error:`torrent removed`});return}if(hd(t.handle),ad.set(t.handle,Date.now()),X.has(t.handle)&&!mf(t.handle,t.fileIndex,t.offset,t.len)){Q({type:`read-error`,id:t.id,error:`torrent paused`});return}if(t.prioritize!==!1)_f(t.viewer,t.handle,t.fileIndex,t.offset,t.len);else if(!mf(t.handle,t.fileIndex,t.offset,t.len)){Q({type:`read-error`,id:t.id,error:`not downloaded`});return}let n=Fd.get(t.handle);n||Fd.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?Bd.get(t.handle)?.get(t.viewer)?.bulk===!0:!1,i=await e.read(t.handle,t.fileIndex,t.offset,t.len,{timeoutMs:Pd,...r?{deadlineMs:null}:{}});if(!n.has(t.id))return;Q({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=hf(t.handle,t.fileIndex,t.offset,t.len);Q({type:`read-stalled`,id:t.id,handle:t.handle,fileIndex:t.fileIndex,offset:t.offset,len:t.len,waitedMs:(r+1)*Pd,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?Bd.get(t.handle)?.get(t.viewer):void 0;t.prioritize!==!1&&t.viewer&&o&&!o.held&&lf(t.handle)}}finally{n.delete(t.id),J.includes(t.handle)&&ad.set(t.handle,Date.now())}}else if(t.type===`cancel-read`)Fd.get(t.handle)?.delete(t.id);else if(t.type===`remove`){let n=Y.get(t.handle);Id(t.handle,`torrent removed`),e.removeTorrent(t.handle,!!t.deleteFiles),md(t.handle),n&&await nd(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;_d.set(t.handle,{wanted:e,firstLast:n}),sf(t.handle);let r=Y.get(t.handle);r&&await $(r,{wantedFiles:e,firstLast:n})}else if(t.type===`set-folder`)Lu=t.handle??null;else if(t.type===`set-temporary`){if(typeof t.infoHash==`string`){let e=t.temporary===!0,n=J.find(e=>Y.get(e)===t.infoHash);n!==void 0&&(e?rd.add(n):(rd.delete(n),hd(n)),cf(n).length&&lf(n)),await $(t.infoHash,{ephemeral:e})}}else if(t.type===`reserve-storage`)typeof t.infoHash==`string`&&t.infoHash&&(t.on===!1?jf.delete(t.infoHash):jf.add(t.infoHash));else if(t.type===`set-location`)typeof t.infoHash==`string`&&await $(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?J.find(e=>Y.get(e)===n):void 0;n&&i!==void 0&&await Ef(e,i,n,r)}else if(t.type===`import-list`){let e=[];await mc(uu,n=>e=du(n,t.removed));let n=[],r=[],i=!1;await mc(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=Cl(Od(r),Od(e));for(let e of _l)(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,...Od(e)};n.push(a),s.set(a.infoHash,a),i=!0}return n});for(let e of r)await td(e.infoHash);i&&Q({type:`list`,list:n})}else if(t.type===`start`){let n=(await Qu()).find(e=>e.infoHash===t.infoHash);if(n?.saveTo===`source`){Q({type:`add-failed`,message:`Nothing to download this from. Create it again from the same files.`});return}if(n){let t=n.savePath||`/dl`,r=await fc(hu(n.infoHash)),i=r&&r.byteLength?e.addTorrentFile(r,t):e.addMagnet(n.magnet,t);if(Ju(i)){Q({type:`add-failed`,message:`That torrent could not be read`});return}pd(i,n.magnet,n.infoHash,t,!1),jd(i,{down:n.downloadLimit,up:n.uploadLimit}),Z.hold(i,Date.now()),Q({type:`state`,torrents:Yu(),reachable:e.reachable()}),await $u({...n,started:!0,paused:!1,ephemeral:!1,lastUsedAt:Date.now()})}}else if(t.type===`remove-missing`){if(typeof t.infoHash==`string`){let n=J.find(e=>Y.get(e)===t.infoHash);n!==void 0&&(Id(n,`torrent removed`),e.removeTorrent(n,!0),md(n)),await nd(t.infoHash)}}else if(t.type===`clear-list`){for(let t of[...J])Id(t,`torrent removed`),e.removeTorrent(t,!0),md(t);let t=[];await mc(lu,e=>(t=e??[],[])),await hc(uu).catch(()=>{});for(let e of t)await hc(mu(e.infoHash)).catch(()=>{}),await hc(hu(e.infoHash)).catch(()=>{});Q({type:`list`,list:[]})}else if(t.type===`pause`){X.add(t.handle),id.delete(t.handle),Gu(t.handle),Z.forget(t.handle),e.pauseTorrent(t.handle),Id(t.handle,`torrent paused`),Rd(t.handle);let n=Y.get(t.handle);n&&await $(n,{paused:!0})}else if(t.type===`resume`){X.delete(t.handle),id.delete(t.handle),Ku(t.handle),Z.forget(t.handle),e.resumeTorrent(t.handle),Z.hold(t.handle,Date.now());let n=Y.get(t.handle);n&&await $(n,{paused:!1})}else if(t.type===`recheck`){let n=Y.get(t.handle);n&&await hc(mu(n)).catch(()=>{}),Hu.delete(t.handle),Id(t.handle,`torrent rechecking`),X.delete(t.handle),Uu.delete(t.handle),Wu.delete(t.handle),id.delete(t.handle),Z.forget(t.handle),e.forceRecheck(t.handle),Z.hold(t.handle,Date.now()),n&&await $(n,{paused:!1})}else if(t.type===`retry-now`)Z.retryNow(Date.now());else if(t.type===`retry`)Z.retry(t.handle,Date.now());else if(t.type===`flush-resume`)await Promise.all(J.map(e=>Rd(e)));else if(t.type===`watch`)t.readLen==null?ff(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.held===!0,t.bulk===!0||void 0):_f(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.readLen);else if(t.type===`unwatch`)pf(e=>e===t.viewer);else if(t.type===`set-flags`)e.setFlags(t.handle,t.flags>>>0,t.mask>>>0),Rd(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=ju(t.down)?t.down:void 0,r=ju(t.up)?t.up:void 0;jd(t.handle,{down:n,up:r})&&e.status(t.handle)&&(bd.delete(t.handle),Nd(t.handle));let i=Y.get(t.handle);if(i){let e={};n!==void 0&&(e.downloadLimit=n),r!==void 0&&(e.uploadLimit=r),Object.keys(e).length&&await $(i,e)}}else if(t.type===`set-session-limits`)ju(t.down)&&(vd.down=t.down),ju(t.up)&&(vd.up=t.up),e.setRateLimits({download:vd.down,upload:vd.up}),await pc(Au,{...vd});else if(t.type===`inspect`){let e=typeof t.handle==`number`?t.handle:null;e!==sd&&(sd=e,cd=0)}else t.type===`unwatch-owner`&&pf(e=>e.startsWith(t.owner+`:`))}catch(e){t.type===`read`?Q({type:`read-error`,id:t.id,error:String(e?.stack??e)}):Q({type:`error`,message:String(e?.stack??e)})}},zf=/* @__PURE__ */ new Set([`read`,`add-torrent-file`]);let Bf=Promise.resolve();self.addEventListener(`message`,e=>{let t=e.data;if(!t||typeof t!=`object`||typeof t.type!=`string`||!Nu.has(t.type))return;let n=q;if(!n){t.type===`read`?Q({type:`read-error`,id:t.id,error:`the engine is still starting`}):Q({type:`error`,message:`worker not initialized`});return}if(zf.has(t.type)){Rf(n,t);return}Bf=Bf.then(()=>Rf(n,t))}),Lf().catch(e=>Q({type:zu?`error`:`fatal`,message:String(e?.stack??e)}));
23
+ var n=So(),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)}})),Ms=/* @__PURE__ */ t((e=>{var t=js().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):``}})),Ns=/* @__PURE__ */ t(((e,t)=>{var n=Es().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})),Ps=/* @__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=Ns(),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}})),Fs=/* @__PURE__ */ t(((e,t)=>{t.exports=function(){throw Error(`Readable.from is not available in the browser`)}})),Is=/* @__PURE__ */ t(((e,t)=>{t.exports=E;var n;E.ReadableState=T,_o().EventEmitter;var r=function(e,t){return e.listeners(t).length},i=yo(),a=So().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=Cs(),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=ws(),f=Ts(),p=Ds().getHighWaterMark,m=Es().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;vo()(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||=As(),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||=Ms().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=As(),!(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,te(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):P(e,o)):O(e,o,t,!1)}else r||(o.reading=!1,P(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&&M(e)),P(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||=Ms().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 ee(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 j(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=ee(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?ie(this):M(this),null;if(e=j(e,t),e===0&&t.ended)return t.length===0&&ie(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=j(n,t)));var i=e>0?re(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&&ie(this)),i!==null&&this.emit(`data`,i),i};function te(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?M(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,N(e)))}}function M(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(N,e))}function N(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,B(e)}function P(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(F,e,t))}function F(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=I(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&&oe(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 I(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,B(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=oe(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?M(this):r.reading||process.nextTick(R,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(L,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(L,this),t};function L(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 R(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,z(this,e)),e.paused=!1,this};function z(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`),B(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 B(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=Ps()),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=re,Object.defineProperty(E.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function re(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 ie(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(ae,t,e))}function ae(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=Fs()),x(E,e,t)});function oe(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),Ls=/* @__PURE__ */ t(((e,t)=>{t.exports=l;var n=Es().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=As();vo()(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)}})),Rs=/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=Ls();vo()(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)}})),zs=/* @__PURE__ */ t(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=Es().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=Ns()),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})),Bs=/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=_o().EventEmitter;vo()(r,n),r.Readable=Is(),r.Writable=ks(),r.Duplex=As(),r.Transform=Ls(),r.PassThrough=Rs(),r.finished=Ns(),r.pipeline=zs(),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}})),Vs=/* @__PURE__ */ n({Server:()=>Ks,Socket:()=>Gs,_default:()=>Xs,connect:()=>qs,createConnection:()=>Js,createServer:()=>Ys,default:()=>Xs,isIP:()=>fo,isIPv4:()=>lo,isIPv6:()=>uo,t:()=>Ws}),Hs=Bs(),Us=_o(),Ws=/* @__PURE__ */ i({Server:()=>Ks,Socket:()=>Gs,_default:()=>Xs,connect:()=>qs,createConnection:()=>Js,createServer:()=>Ys,default:()=>Xs,isIP:()=>fo,isIPv4:()=>lo,isIPv6:()=>uo}),Gs=class extends Hs.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??=Ja(`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=>{if(!e){this._busyRelease?.();return}this.emit(`connect`)}),this._webVPNTcpSocketPromise}_read(e){if(!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);this._webVPNTcpSocketPromise.then(e=>{if(!e){this.push(null);return}e.reader.read().then(({value:e,done:t})=>{if(t){this.push(null);return}this._restartTimeoutTimer(),this.push(e)}).catch(e=>{this.destroy(e)})})}_write(e,t,n){if(!this._webVPNTcpSocketPromise){n(/* @__PURE__ */ Error(`Socket not connected`));return}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)}connect(...e){let t=po(...e),{relay:n}=t,r=this.__webvpn_tcp_socket_init__(Ga(`an outbound tcp socket`).then(e=>(n!==void 0&&Qa(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){if(!this._webVPNTcpSocketPromise){e();return}this._webVPNTcpSocketPromise.then(async e=>{e&&await e.writer.close()}).then(()=>e(),t=>e(t))}_destroy(e,t){if(this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._busyRelease?.(),!this._webVPNTcpSocketPromise){t(e);return}this._webVPNTcpSocketPromise.then(async e=>{e&&await(this._resetRequested?e.resetAndDestroy():e.destroy())}).then(()=>t(e),()=>t(e))}destroySoon(){if(this.writableFinished){this.destroy();return}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){if(!this._webVPNTcpSocketPromise){this.emit(`error`,/* @__PURE__ */ Error(`Cannot set socket option before connect`));return}this._webVPNTcpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}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},Ks=class extends Us.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??=Ja(`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=>{if(!e){this._busyRelease?.();return}this.emit(`listening`)}),this._webVPNTcpSocketListenerPromise}listen(...e){let t=po(...e);this._closeEmitted=!1;let n=e=>{let t=new Gs;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=>Ga(`a tcp listener`).then(a=>(i!==void 0&&Qa(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](){}},qs=(e,t)=>new Gs().connect(e,t),Js=qs,Ys=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new Ks(e);return t&&n.on(`connection`,t),n},Xs={Socket:Gs,Server:Ks,connect:qs,createConnection:Js,createServer:Ys,isIP:fo,isIPv4:lo,isIPv6:uo},Zs=/* @__PURE__ */ n({Socket:()=>ec,createSocket:()=>oc,default:()=>sc,t:()=>$s}),Qs=So(),$s=/* @__PURE__ */ i({Socket:()=>ec,createSocket:()=>oc,default:()=>sc}),ec=class extends Us.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){if(!this._webVPNUdpSocketPromise){this.emit(`error`,/* @__PURE__ */ Error(`Cannot set socket option before bind`));return}this._webVPNUdpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}_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:go,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=ic(n)),s+=n.byteLength,d=t.getUint16(s),s+=2}let f=t.getUint32(s);s+=4;try{this.emit(`message`,Qs.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 tc;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let i=so.Address4.isValid(e)?rc(e):ac(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(so.Address4.isValid(e)){let n=rc(e),r=t&&so.Address4.isValid(t)?rc(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(so.Address6.isValid(e)){let t=ac(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=mo(...e),n=this._type===`udp6`?`::`:`0.0.0.0`,r=this._relayChoice,i=this.__webvpn_udp_socket_init__(Ga(`a udp socket`).then(e=>(r!==void 0&&Qa(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??=Ja(`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`,Qs.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=>{if(!e){this._busyRelease?.();return}this.emit(`listening`)}),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(so.Address4.isValid(e)){let n=rc(e),r=t&&so.Address4.isValid(t)?rc(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(so.Address6.isValid(e)){let t=ac(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=ho(...e),n=nc(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;if(this._dataPort&&(o||so.Address4.isValid(a)||so.Address6.isValid(a))){this._portSend(r,o?void 0:a,o?void 0:t.port),n?.call(this,null,r.byteLength);return}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)})}},tc=new Uint8Array([2]),nc=e=>{if(typeof e==`string`)return co.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(nc),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)},rc=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)},ic=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(`:`)}`},ac=e=>{let t=new so.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)))},oc=(e,t)=>{let n=new ec(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},sc={Socket:ec,createSocket:oc};function cc(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function lc(e,t){let n,r=()=>{if(n)return n;let r=indexedDB.open(e);return r.onupgradeneeded=()=>r.result.createObjectStore(t),n=cc(r),n.then(e=>{e.onclose=()=>n=void 0},()=>{}),n};return(e,n)=>r().then(r=>n(r.transaction(t,e).objectStore(t)))}let uc;function dc(){return uc||=lc(`keyval-store`,`keyval`),uc}function fc(e,t=dc()){return t(`readonly`,t=>cc(t.get(e)))}function pc(e,t,n=dc()){return n(`readwrite`,n=>(n.put(t,e),cc(n.transaction)))}function mc(e,t,n=dc()){return n(`readwrite`,n=>new Promise((r,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),r(cc(n.transaction))}catch(e){i(e)}}}))}function hc(e,t=dc()){return t(`readwrite`,t=>(t.delete(e),cc(t.transaction)))}var gc={checkingFiles:1,downloadingMetadata:2,downloading:3,finished:4,seeding:5,checkingResumeData:7},_c=/^incoming connection from (\S+) \(([^)]*)\)/,vc=/^successfully listening on \[([^\]]*)\] (\S+)/,yc=/^listening on .* failed:/,bc=new TextDecoder,xc=4026531841,Sc=4026531842,Cc=4026531843,wc=4026531844,Tc=4026531845,Ec=4026531846,Dc={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},Oc={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},kc={top:0,up:1,down:2,bottom:3},Ac={tracker:1,dht:2,pex:4,lsd:8,resumeData:16,incoming:32},G={skip:0,low:1,normal:4,top:7},jc=6e4,Mc=12,Nc=1e3,Pc=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??Mc)),s=Math.max(0,Math.floor(n.deadlineStepMs??Nc)),c=n.claimedPriority??G.normal,l=n.unclaimedPriority??G.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]=G.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(G.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(G.normal);for(let e=l;e<=u;e++)d[e]=G.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)*Nc,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,kc[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(G.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,G.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),G.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]??G.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??jc;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===xc)this.decodeTorrentReady(r,a);else if(o===Sc)this.decodeStateUpdate(r,a);else if(o===wc)this.decodeResumeData(r,a,s);else if(o===Tc)this.decodePeers(r,a);else if(o===Ec)this.decodeTrackers(r,a);else if(o!==Cc){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=_c.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=vc.exec(e);if(n){this.reachability.listening[n[1].toLowerCase()]=n[2];return}yc.test(e)&&this.reachability.listenFailed.length<32&&this.reachability.listenFailed.push(e)}readStr(e,t){let n=e.getUint32(t,!0);return t+=4,[bc.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 ee=Number(e.getBigInt64(t,!0));t+=8;let j=e.getUint32(t,!0)!==0;t+=4;let te;[te,t]=this.readStr(e,t);let M=e.getInt32(t,!0);t+=4;let N=e.getInt32(t,!0);t+=4;let P=e.getUint32(t,!0);t+=4;let F=P?bc.decode(new Uint8Array(e.buffer,e.byteOffset+t,P)):``;t+=P;let I=e.getUint32(t,!0);t+=4;let L=e.getUint32(t,!0);t+=4;let R=new Uint8Array(L);R.set(new Uint8Array(e.buffer,e.byteOffset+t,L)),this.bitfieldByHandle.set(n,{pieces:R,numPieces:I});let z=0;for(let e=0;e<L;e++){let t=R[e];for(;t;)z+=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:I,numPiecesHave:z,paused:d,autoManaged:f,sequential:p,flags:m,queuePosition:M,errorCode:N,error:F,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:ee,hadIncoming:j,savePath:te,hasMetadata:r!==gc.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?.())}},Fc=8e3,Ic=e=>{try{e?.close()}catch{}},Lc=(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),Ic(r),n(null))},o=setTimeout(a,Fc);r.on(`listening`,()=>{i||(i=!0,clearTimeout(o),n(r))}),r.on(`error`,a);try{t(r)}catch{a()}});async function Rc(e,t,n=4){try{return await zc(e,t,n)}catch{return null}}async function zc(e,t,n){for(let r=0;r<n;r++){let i=await Lc(()=>t.createSocket({type:`udp4`}),e=>e.bind(0,`0.0.0.0`));if(!i)return null;let a=i.address?.()?.port;if(!a)return Ic(i),null;let o=await Lc(()=>e.createServer(),e=>e.listen(a,`0.0.0.0`)),s=o?o.address?.()?.port:void 0,c=!!o&&s===a;if(o&&!c&&Ic(o),!c){if(r<n-1){Ic(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 Bc(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):Rc(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 Pc(i,e)}catch(e){throw a&&!a.adopted&&(Ic(a.server),Ic(a.udp)),e}return o.setReservedPort(a?a.port:null),o}const Vc=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},Hc=25e5,Uc=e=>{if(!Number.isFinite(e)||e<=0)return 12;let t=Math.ceil(Hc/e)+1,n=Math.max(2,Math.floor(8388608/e));return Math.min(Math.max(t,2),n)},Wc=e=>Uc(e)*Math.max(0,e),Gc=e=>Math.max(1,Math.floor(Wc(e)/2)),Kc=(e,t)=>Math.min(2e3,Math.max(50,Math.round(e/Math.max(t,25e4)*1e3))),qc=(e,t,n,r=Hc)=>{let i=e.fileOffset+n+Math.max(0,r-1);return Math.floor(i/e.pieceLength)>=e.p1?!1:Math.abs(n-t)>=Gc(e.pieceLength)};var Jc=class{storages=/* @__PURE__ */ new Map;opened=/* @__PURE__ */ new Map;onNewStorage(e,t,n){let r=(async()=>{let r=await Yc(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 Yc(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 Xc=(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 Zc=[50,150,400,900,1500],Qc=e=>e?.name===`QuotaExceededError`,$c=e=>new Promise(t=>setTimeout(t,e)),el=e=>{let t=async(t,n,r,i)=>{let a=i;for(let i of Zc){if(Qc(a))break;if(n(),await $c(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)}}},tl=()=>{let e=new Jc,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=el(t),c=(e,t,n)=>s(e,()=>a(e,t),n),l=(e,t,n,a)=>{let o=i=>{try{Xc(i,a,{at:n})}catch(n){throw Qc(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)}},nl=67108864,rl=/^(\d+)-(\d+)$/,il=/^\d+$/,al=(e=nl)=>{let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Set,o=el(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`&&il.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=rl.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{Xc(n,s.subarray(o.from,o.to),{at:o.at})}catch(a){Qc(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(()=>{}))}}},ol=[5e3,15e3,3e4,6e4,12e4,3e5],sl=1e4,cl=/* @__PURE__ */ new Set([2,3]),ll=/* @__PURE__ */ new Set([1,7]),ul=e=>!!e&&e.paused&&!e.autoManaged,dl=()=>{let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=e=>ol[Math.min(e,ol.length-1)],a=i=>{e.delete(i),t.delete(i),n.delete(i),r.delete(i)};return{hold:(e,t,n=sl)=>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(ll.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`:cl.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+sl,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)}}},fl=e=>!(e.flags&Dc.localConnection)||!!(e.source&Ac.incoming),pl=e=>e.flags&Dc.utpSocket?`utp`:`tcp`,ml={total:0,byTransport:{}},hl=e=>{let t={},n=0;for(let r of e)for(let e of r){if(!fl(e)||e.connectionType!==0)continue;n+=1;let r=pl(e);t[r]=(t[r]??0)+1}return{total:n,byTransport:t}},gl={activeSeconds:0,seedingSeconds:0},_l=[`activeSeconds`,`seedingSeconds`,`downloaded`,`uploaded`,`wasted`],vl={activeSeconds:0,seedingSeconds:0,downloaded:0,uploaded:0,wasted:0},K=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0,yl=(e,t)=>({activeSeconds:Math.max(0,K(t.activeSeconds)-K(e.activeSeconds)),seedingSeconds:Math.max(0,K(t.seedingSeconds)-K(e.seedingSeconds))}),bl=(e,t,n)=>{let r=yl(t,n);return{activeSeconds:K(e?.activeSeconds)+r.activeSeconds,seedingSeconds:K(e?.seedingSeconds)+r.seedingSeconds}},xl=(e,t)=>Object.fromEntries(_l.map(n=>[n,Math.max(0,K(t[n])-K(e[n]))])),Sl=(e,t,n)=>{let r=xl(t,n);return Object.fromEntries(_l.map(t=>[t,K(e?.[t])+r[t]]))},Cl=(e,t)=>Object.fromEntries(_l.map(n=>[n,Math.max(K(e?.[n]),K(t?.[n]))])),wl=(e,t)=>t.activeSeconds-K(e?.activeSeconds)>=30||t.seedingSeconds-K(e?.seedingSeconds)>=30,Tl=67108864,El=e=>!Number.isFinite(e)||e<=0?0:Math.min(1e9,Math.floor(e*.1)),Dl=(e,t)=>!Number.isFinite(e)||e<=0?Math.max(0,t):Math.max(Math.min(.25*e,2e10),Math.max(0,t)),Ol=({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;if(a<Math.min(n,67108864))return!0;let o=i.reduce((e,t)=>e+Math.max(0,t.bytesOnDisk),0);return r>0&&r+67108864>a+o},kl=(e,t)=>e.usedAt-t.usedAt||(e.infoHash<t.infoHash?-1:+(e.infoHash>t.infoHash)),Al=({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(kl);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+El(t)),u=o(e=>c+a[e]>=s+Tl),d=l>=0?l:Math.max(0,u),f=a[i.length],p=i.reduce((e,t)=>Math.max(e,t.bytesOnDisk),0),m=Dl(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)},jl={start:0,end:0},Ml=(e,t,n)=>{let r=Math.min(n,e.size);return r<=t?jl:{start:Math.floor((e.offset+t)/e.pieceLength),end:Math.floor((e.offset+r-1)/e.pieceLength)+1}},Nl=(e,t,n)=>Ml(e,n*t,(n+1)*t),Pl=(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},Fl=(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},Il=(e,t,n)=>e>t&&Math.floor(t/n)>=23,Ll=({file:e,chunkBytes:t,room:n,reader:r,held:i,pinned:a=[]})=>{if(!Il(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=Ml(e,0,t),d=Math.max(0,o-2-s),f=n=>{if(!d){let n=Ml(e,s*t,e.size);return{want:[u,n],ahead:n,slack:jl}}let r=Ml(e,s*t,n*t),i=Ml(e,n*t,(n+2)*t);return{want:[u,r,i,Ml(e,o*t,e.size)],ahead:r,slack:i}},p=n=>Pl(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)}},Rl=(e,t,n)=>e||t<n,zl=(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 Bl=8,Vl=2e4,Hl=e=>typeof e.values==`function`,Ul=async e=>{let t=0,n=0,r=async(e,i)=>{if(!(i>Bl))for await(let a of e.values()){if(++n>Vl)return;if(Hl(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}},Wl=(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)},Gl,Kl,ql=(e,t,n)=>{if(e!==void 0)return n!==Kl&&(Gl=void 0),Kl=n,Gl=Gl===void 0?e:Math.min(Gl,e),Math.max(Gl,t??0)},Jl=async e=>e.persisted?e.persisted().then(e=>e===!0).catch(()=>Kl):void 0,Yl={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=>Ul(e)).catch(()=>null):null,Jl(e)]),i=Wl(t,n);return{...t,usage:i,quota:ql(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 Jl(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 Xl=/^(?:[0-9a-f]{40}|[0-9a-f]{64}|[a-z2-7]{32})$/i,Zl=({entries:e,listedHashes:t,claimedNames:n,attributable:r})=>e.filter(({name:e,kind:i})=>n.has(e)?!1:i===`directory`&&Xl.test(e)?!t.has(e.toLowerCase()):r).map(({name:e})=>e),Ql=async e=>{let t=[];for await(let n of e.values())t.push({name:n.name,kind:n.kind});return t},$l=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},eu=async(e,t,n)=>{let r=await $l(e,t);if(!r)return[];let i=[];for(let e of Zl({...n,entries:await Ql(r)}))try{await r.removeEntry(e,{recursive:!0}),i.push(e)}catch{}return i},tu=async e=>{let t=0;for(let{name:n,kind:r}of await Ql(e))r===`file`&&n.startsWith(`.ripple-probe-`)&&await e.removeEntry(n).then(()=>!0,()=>!1)&&t++;return t},nu=/* @__PURE__ */ new Set([`export-start`,`export-chunk`,`import-start`]),ru=e=>e?`/dl/`+e:`/dl`,iu=e=>`/cache/`+e,au=e=>!!e?.startsWith(`/cache/`),ou=(e,t)=>e===ru(t)||e===iu(t),su=(e,t)=>t&&(!e||e.ephemeral===!0),cu=(e,t)=>e?{...t,ephemeral:su(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,lu=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}),uu=`ripple:torrents`,du=`ripple:removed`,fu=(...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}))},pu=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}},mu=(e,t,n)=>{let r=pu(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}},hu=e=>`ripple:resume:`+e,gu=e=>`ripple:torrent:`+e,_u=e=>`ripple:thumb:`+e,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=>au(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(au(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?G.normal:G.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]=G.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]=G.top),r>=e&&(l[r]=G.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`:ru(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 q=null,Iu=null;const Lu=al(nl);let Ru=null;const zu=/* @__PURE__ */ new Map;let Bu=!1;const J=[],Vu=/* @__PURE__ */ new Map,Y=/* @__PURE__ */ new Map,Hu=/* @__PURE__ */ new Map,Uu=/* @__PURE__ */ new Map,X=/* @__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,Z=dl(),Yu=e=>e>=4294967040,Q=(e,t)=>self.postMessage(e,t??[]),Xu=()=>J.map(e=>{let t=q.bitfield(e);return{handle:e,magnet:Vu.get(e)??``,files:q.files(e),status:q.status(e),bitfield:t?{numPieces:t.numPieces,pieceLength:t.pieceLength,length:t.length,pieces:t.pieces}:null,recovery:Z.state(e),userPaused:X.has(e),windowed:Wd.has(e),uptime:Zu(e),sessionUptime:Qu(e),totals:Ad(e)}}),Zu=e=>{let t=q?.status(e),n=wd.get(e);return!t||!n?Td.get(e)??gl:bl(Td.get(e),n,t)},Qu=e=>{let t=q?.status(e),n=wd.get(e);return t&&n?yl(n,t):gl},$u=async()=>await fc(`ripple:torrents`)??[],ed=async e=>{let t=[];await mc(uu,n=>{t=n??[];let r=t.findIndex(t=>t.infoHash===e.infoHash),i=cu(r>=0?t[r]:null,e);return r>=0?t[r]=i:t.push(i),t}),Q({type:`list`,list:t})},$=async(e,t,n=!1)=>{let r=[];await mc(uu,n=>{r=n??[];let i=r.findIndex(t=>t.infoHash===e);return i>=0&&(r[i]={...r[i],...t}),r}),n||Q({type:`list`,list:r})},td=e=>{let t=Y.get(e);t&&$(t,{lastUsedAt:Date.now()},!0).catch(()=>{})},nd=async e=>{await hc(hu(e)).catch(()=>{}),await hc(gu(e)).catch(()=>{}),await hc(Fu(e)).catch(()=>{}),await hc(_u(e)).catch(()=>{})},rd=async e=>{let t=[];await mc(uu,n=>t=(n??[]).filter(t=>t.infoHash!==e)),await mc(du,t=>fu(t,[{infoHash:e,removedAt:Date.now()}])),await nd(e),Q({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,ud=0,dd=ml;const fd=e=>{let t=cd;return t==null||!J.includes(t)?null:(q.peers(t),e-ld>=5e3&&(ld=e,q.trackers(t)),{handle:t,peers:q.lastPeers(t),trackers:q.lastTrackers(t)})},pd=e=>{let t=q?.files(e);if(!t)return[];let n=t.files.map(e=>e.path.split(`/`).filter(Boolean)[0]).filter(Boolean);return[...new Set(n)]},md=(e,t,n,r,i=!1)=>{J.includes(e)||J.push(e),Vu.set(e,t),n&&(Y.set(e,n),sd.add(e)),Hu.set(e,r),i?id.add(e):id.delete(e)},hd=e=>{let t=J.indexOf(e);t>=0&&J.splice(t,1),Vu.delete(e),Y.delete(e),Hu.delete(e),Uu.delete(e),X.delete(e),Z.forget(e),Rd.delete(e),Id.delete(e),Wu.delete(e),Gu.delete(e),Ju.delete(e),Vd.delete(e),Hd.delete(e),Ud.delete(e),_d.delete(e),vd.delete(e),bd.delete(e),xd.delete(e),Sd.delete(e),wd.delete(e),Td.delete(e),Ed.delete(e),Dd.delete(e),id.delete(e),ad.delete(e),od.delete(e),sd.delete(e),Wd.delete(e),Gd.delete(e),Kd.delete(e),cf.delete(e),lf.delete(e),rf.delete(e)},gd=e=>{ad.delete(e)&&(qu(e),q?.resumeTorrent(e),Z.hold(e,Date.now()))},_d=/* @__PURE__ */ new Set,vd=/* @__PURE__ */ new Map;let yd={down:0,up:0};const bd=/* @__PURE__ */ new Map,xd=/* @__PURE__ */ new Set,Sd=/* @__PURE__ */ new Map;let Cd=0;const wd=/* @__PURE__ */ new Map,Td=/* @__PURE__ */ new Map,Ed=/* @__PURE__ */ new Map,Dd=/* @__PURE__ */ new Map,Od=e=>({activeSeconds:e.activeSeconds,seedingSeconds:e.seedingSeconds,downloaded:e.allTimeDownload,uploaded:e.allTimeUpload,wasted:e.wasted}),kd=e=>({activeSeconds:e?.activeSeconds??0,seedingSeconds:e?.seedingSeconds??0,downloaded:e?.downloaded??0,uploaded:e?.uploaded??0,wasted:e?.wasted??0}),Ad=e=>{let t=q?.status(e),n=Ed.get(e);return!t||!n?Dd.get(e)??vl:Sl(Dd.get(e),n,Od(t))},jd=(e,t,n)=>{let r=Sd.get(e);Sd.set(e,r?{flags:r.flags&~n|t&n,mask:r.mask|n}:{flags:t&n,mask:n})},Md=(e,t)=>{let n={...bd.get(e)};return Mu(t.down)&&(n.down=t.down),Mu(t.up)&&(n.up=t.up),!Mu(n.down)&&!Mu(n.up)?!1:(bd.set(e,n),xd.add(e),!0)},Nd=e=>{let t=bd.get(e)?.down;return Kd.has(e)?Math.min(t||16384,16384):t},Pd=e=>{let t=bd.get(e);if(!q||!t)return;let n=Nd(e);Mu(n)&&q.setDownloadLimit(e,n),Mu(t.up)&&q.setUploadLimit(e,t.up)},Fd=6e3,Id=/* @__PURE__ */ new Map,Ld=(e,t)=>{let n=Id.get(e);if(n?.size){for(let e of n.keys())Q({type:`read-error`,id:e,error:t});n.clear()}},Rd=/* @__PURE__ */ new Set,zd=async e=>{let t=Y.get(e);if(!t||!q||Rd.has(e)||Su(Hu.get(e)))return!1;Rd.add(e);try{let n=await q.saveResumeData(e);return J.includes(e)?(await pc(hu(t),n),!0):!1}catch(e){return console.error(`[worker] saving resume data failed`,String(e)),!1}finally{Rd.delete(e)}},Bd=(e,t)=>{let n=q?.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}},Vd=/* @__PURE__ */ new Map,Hd=/* @__PURE__ */ new Set,Ud=/* @__PURE__ */ new Set,Wd=/* @__PURE__ */ new Map,Gd=/* @__PURE__ */ new Map,Kd=/* @__PURE__ */ new Set;let qd;const Jd=`ripple:ceiling-fixed`;let Yd,Xd=null;const Zd=(e,t,n)=>[...ff(e).filter(e=>e.fileIndex===t).map(e=>Ml(n,e.fromOffset,e.fromOffset+Wc(n.pieceLength))),...[...Id.get(e)?.values()??[]].filter(e=>e.fileIndex===t).map(e=>Ml(n,e.offset,e.offset+e.len))],Qd=(e,t,n)=>{let r=Gd.get(e),[i]=n;if(r===void 0||!i||!qd?.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=Ll({file:s,chunkBytes:c,room:r,reader:i.fromOffset,held:l,pinned:Zd(e,i.fileIndex,s)});return u&&{...u,fileIndex:i.fileIndex,file:s,chunkBytes:c}},$d=(e,t)=>e.fileIndex===t.fileIndex&&JSON.stringify(e.want)===JSON.stringify(t.want),ef=(e,t)=>{let n=q?.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},tf=()=>Xd?Xd.space.limitBytes-Xd.space.usedBytes-(Lu.footprint()-Xd.footprint)-Tl:1/0,nf=3e4,rf=/* @__PURE__ */ new Map,af=e=>(rf.get(e)?.until??0)>Date.now(),of=e=>{let t=Wd.get(e),n=!!t&&!Id.get(e)?.size&&Rl(ef(e,t.ahead),tf(),t.chunkBytes);n!==Kd.has(e)&&(n?Kd.add(e):Kd.delete(e),q?.setDownloadLimit(e,Nd(e)??0))},sf=e=>{let t=Wd.get(e),n=q?.bitfield(e);if(!t||!n||t.slack.end<=t.slack.start||af(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&&q?.forgetPieces(e,r)},cf=/* @__PURE__ */ new Set,lf=/* @__PURE__ */ new Set,uf=async e=>{if(cf.has(e)){lf.add(e);return}cf.add(e);let t=!1;try{if(af(e)){t=!0;return}let n=Hu.get(e),r=()=>{let t=Wd.get(e);if(!t||n===void 0)return[];let r=/* @__PURE__ */ new Set([...t.keep,...Pl(t.file,t.chunkBytes,Zd(e,t.fileIndex,t.file))]);return Lu.chunksOf(n,t.fileIndex).filter(e=>!r.has(e)).map(e=>({chunk:e,fileIndex:t.fileIndex,pieces:Nl(t.file,t.chunkBytes,e)}))},i=({start:t,end:n})=>q?.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++)q?.cancelPieceRequests(e,t);t=!0}return r?.busy===0});if(!a.length||n===void 0)return;if(!await zd(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{cf.delete(e),lf.delete(e)?uf(e):t&&Wd.has(e)&&setTimeout(()=>void uf(e),1e3)}},df=e=>{let t=vd.get(e);if(!q||!t||Ou(t))return;let n=q.files(e);n&&q.prioritizePieces(e,Du({files:n.files,pieceLength:n.pieceLength,numPieces:Math.ceil(n.totalSize/n.pieceLength),wanted:t.wanted,firstLast:t.firstLast}))},ff=e=>{let t=Vd.get(e);return t?[...t.values()].filter(e=>!e.held):[]},pf=e=>{if(!q)return;if(!J.includes(e)){Vd.delete(e),Ud.delete(e);return}let t=ff(e);if(!t.length){if(!q.files(e)){Ud.add(e);return}Ud.delete(e),Wd.delete(e),of(e),q.clearStreamWindow(e),df(e),id.has(e)&&!X.has(e)&&!ad.has(e)&&(ad.add(e),Ku(e),q.pauseTorrent(e),zd(e));return}gd(e);let n=q.files(e);if(!n){Ud.add(e);return}Hd.delete(e)&&Bf();let r=t.flatMap(({fileIndex:e,fromOffset:t,bulk:r})=>{let i={fileIndex:e,offset:t},a=n.files[e];return!r&&a?.size?[i,{fileIndex:e,offset:a.size-1}]:[i]}),i=t.some(e=>!e.bulk),a=Qd(e,n,t);a?Wd.set(e,a):Wd.delete(e),q.setStreamWindow(e,r,{unclaimedPriority:G.skip,windowPieces:Uc(n.pieceLength),deadlineStepMs:Kc(n.pieceLength,q.status(e)?.downloadRate||3e6),deadlines:i,...a?{keep:a.want}:{}})?Ud.delete(e):Ud.add(e),a&&uf(e),sf(e),of(e)},mf=e=>{let t=q?.files(e),n=ff(e);if(!t||!n.length)return;let r=Qd(e,t,n),i=Wd.get(e);if(r||i){if(!r||!i||!$d(r,i)){pf(e);return}Wd.set(e,r),uf(e)}},hf=e=>{X.add(e),ad.delete(e),Ku(e),Z.forget(e),q?.pauseTorrent(e)},gf=(e,t,n,r,i=!1,a)=>{if(!J.includes(t))return;let o=Vd.get(t),s=!o?.size;o||Vd.set(t,o=/* @__PURE__ */ new Map);let c=a??o.get(e)?.bulk;o.set(e,{fileIndex:n,fromOffset:r,...i?{held:i}:{},...c?{bulk:c}:{}}),s&&(td(t),Hd.add(t)),pf(t)},_f=e=>{for(let[t,n]of Vd){let r=!1;for(let t of[...n.keys()])e(t)&&(n.delete(t),r=!0);n.size||(Vd.delete(t),r&&td(t)),r&&pf(t)}},vf=(e,t,n,r)=>{let i=q?.files(e),a=i?.files[t],o=q?.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},yf=(e,t,n,r)=>{let i=q?.files(e),a=i?.files[t],o=q?.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},bf=async e=>{let t=e=>Math.max(0,e.size-e.held),n=[],r=[];for(let[e,t]of[...Vd]){let i=Iu,a=q?.files(e),o=Hu.get(e);if(!i||!a||!t.size||o===void 0||Cu(o))continue;let s=async t=>({h:e,size:a.files[t]?.size??0,held:await i.usageOf(o,t)??0}),[c]=ff(e),l=!!qd?.fixed&&id.has(e)&&au(o);for(let e of new Set([...t.values()].map(e=>e.fileIndex)))n.push({...await s(e),cache:l&&e===c?.fileIndex,chunkBytes:Lu.chunkBytesOf(o)});let u=i.refusedFile(o);u!==void 0&&r.push(await s(u))}let i=n.filter(e=>!e.cache).reduce((e,n)=>e+t(n),0),a=n.filter(e=>e.cache),o=e.limitBytes-e.usedBytes+a.reduce((e,t)=>e+t.held,0)-i-Tl,s=Fl(a.map(e=>e.size),o),c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Set,u=i;a.forEach((e,n)=>{let r=s[n]??0;c.set(e.h,r),Il(e.size,r,e.chunkBytes)&&l.add(e.h),u+=l.has(e.h)?Math.max(0,r-e.held):t(e)});let d=r.filter(e=>!l.has(e.h)).reduce((e,n)=>e+t(n),0);return{pendingBytes:u,refusedBytes:d,rooms:c}},xf=(e,t,n,r,i)=>{if(!e||!J.includes(t))return;let a=Vd.get(t)?.get(e);if(!a||a.held||a.fileIndex!==n){gf(e,t,n,r);return}let o=Bd(t,n);if(!o)return;let s={fileOffset:o.file.offset,pieceLength:o.pieceLength,p1:o.p1};qc(s,a.fromOffset,r,i)&&gf(e,t,n,r)},Sf=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}},Cf=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}},wf=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}),Tf=async()=>{try{let{usage:e,quota:t}=await Yl.estimate();return!t||e===void 0?null:{usedBytes:e,limitBytes:t}}catch{return null}},Ef=async()=>{try{let{usage:e,quota:t}=await navigator.storage.estimate();return t&&e!==void 0?t-e:null}catch{return null}},Df=async e=>{for(let t=0;t<4e3;t+=250){await new Promise(e=>setTimeout(e,250));let t=await Tf();if(!t||t.usedBytes<e)return t}return Tf()},Of=async(e,t,n,r,i={})=>{Ld(t,r),e.removeTorrent(t,!0),hd(t),await hc(hu(n)).catch(()=>{}),await $(n,{started:!1,paused:!1,...i})},kf=(e,t,n)=>Of(e,t,n,`torrent removed to make room`),Af=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=X.has(t),c=id.has(t);Ld(t,`files moved`),e.removeTorrent(t,i===`browser`),hd(t),await hc(hu(n)).catch(()=>{});let l=e.addMagnet(a,o);if(Yu(l)){Q({type:`add-failed`,message:`Moving the files left the torrent unaddable`}),await $(n,{savePath:o,saveTo:r,started:!1});return}md(l,a,n,o,c),r===`folder`&&jd(l,Oc.uploadMode,Oc.uploadMode),s?(X.add(l),Ku(l)):qu(l),Z.hold(l,Date.now()),await $(n,{savePath:o,saveTo:r,started:!0})},jf=(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):(md(s,n,t,o,!1),jd(s,Oc.uploadMode,Oc.uploadMode),a&&(X.add(s),Ku(s)),Z.hold(s,Date.now()),s)},Mf=async(e,t)=>{let n=new Map(e.map(e=>[e.infoHash,e])),r=[],i=[];for(let e of[...J]){let a=Y.get(e);if(!a)continue;let o=n.get(a);if(!o?.ephemeral||!ou(o.savePath,a)||Vd.get(e)?.size||Id.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 Nf=!1;const Pf=e=>{let t=Ol(e);t!==Nf&&(Nf=t,Q({type:`storage-full`,full:t,usedBytes:e.usedBytes,limitBytes:e.limitBytes}))},Ff=/* @__PURE__ */ new Set;let If=!1;const Lf=async()=>{if(!q||If)return 0;If=!0;try{let e=await $u(),t=new Set(e.map(e=>e.infoHash.toLowerCase()));for(let e of Ff)t.add(e.toLowerCase());let n=/* @__PURE__ */ new Set,r=!0;for(let e of J){let i=Y.get(e);if(i&&t.add(i.toLowerCase()),(Hu.get(e)??`/dl`)!==`/dl`)continue;let a=pd(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(!au(e)){if(e!==`/dl`&&!e.startsWith(`/dl/`)){r=!1;continue}if(e===`/dl`){if(t.rootEntry){n.add(t.rootEntry);continue}!J.some(e=>Y.get(e)===t.infoHash)&&t.started!==!1&&(r=!1)}}}let i=await navigator.storage.getDirectory(),a=[...await eu(i,`/dl`,{listedHashes:t,claimedNames:n,attributable:r}),...await eu(i,`/cache`,{listedHashes:t,claimedNames:/* @__PURE__ */ new Set,attributable:!1})];return await tu(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{If=!1}};let Rf=!1,zf=!1;const Bf=async()=>{let e=q;if(!e)return;if(Rf){zf=!0;return}Rf=!0;let t=null,n={pendingBytes:0,refusedBytes:0,rooms:/* @__PURE__ */ new Map},r=[],i=[],a=e=>({...e,pendingBytes:qd?.fixed===!1?0:n.pendingBytes,refusedBytes:n.refusedBytes,candidates:[...r,...i]});try{let o=await Tf();if(!o)return;t=o,Yd===void 0&&(Yd=await fc(Jd).catch(()=>null)??null);let s=async e=>{Xd={space:e,footprint:Lu.footprint()};let t=await Ef();if(t===null)return;let n={usedBytes:e.usedBytes,headroomBytes:t};qd=zl(qd??(typeof Yd==`boolean`?{...n,fixed:Yd}:void 0),n,nl),qd.fixed!==void 0&&qd.fixed!==Yd&&(Yd=qd.fixed,pc(Jd,Yd).catch(()=>{}))};await s(o),n=await bf(o);let c=await Mf(await $u(),Date.now());for(r=c.evictable,i=c.graced;r.length;){let[i]=Al({...o,pendingBytes:n.pendingBytes,candidates:r});if(!i)break;r=r.filter(e=>e.infoHash!==i);let a=J.find(e=>Y.get(e)===i);if(a===void 0||Vd.get(a)?.size||Id.get(a)?.size)continue;let c=o.usedBytes;t=null,await kf(e,a,i);let l=await Df(c);if(!l)return;o=l,t=l,await s(l),n=await bf(o)}Gd.clear();for(let[e,t]of n.rooms)Gd.set(e,t);for(let e of/* @__PURE__ */ new Set([...Gd.keys(),...Wd.keys()]))mf(e);Ol(a(o))&&await Lf()&&(o=await Df(o.usedBytes)??o),t=o}catch(e){console.error(`[worker] storage budget pass failed`,String(e))}finally{Rf=!1,t&&Pf(a(t)),zf&&(zf=!1,Bf())}},Vf=async()=>{let e=console.error.bind(console);if(console.error=(...t)=>{e(...t);try{Q({type:`worker-error`,args:t.map(String)})}catch{}},!await Cf()){Q({type:`storage-unavailable`});return}$u().then(e=>{e.length&&Q({type:`list`,list:e})}).catch(()=>{});let t=Promise.race([fc(ju).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]);Iu=Tu(tl(),()=>Ru,e=>zu.get(e)??null,Lu),q=await Bc({net:Vs,dgram:Zs,storage:Iu,utpReceiveBufferBytes:4194304});for(let e=0;e<30;e++)q.tick();yd=Nu(await t),q.setRateLimits({download:yd.down,upload:yd.up});try{let e=await $u(),t=!await Sf(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 fc(hu(r.infoHash)),a=await fc(gu(r.infoHash));if(t&&i&&i.byteLength){await hc(hu(r.infoHash)).catch(()=>{}),r.started=!1,n=!0;continue}let o=i&&i.byteLength?q.addTorrentWithResume(i,e):a&&a.byteLength?q.addTorrentFile(a,e):q.addMagnet(r.magnet,e);Yu(o)||(md(o,r.magnet,r.infoHash,e,r.ephemeral===!0),vd.set(o,{wanted:r.wantedFiles,firstLast:r.firstLast}),_d.add(o),Md(o,{down:r.downloadLimit??0,up:r.uploadLimit}),Td.set(o,{activeSeconds:r.activeSeconds??0,seedingSeconds:r.seedingSeconds??0}),Dd.set(o,kd(r)),r.paused?(X.add(o),Ku(o)):qu(o),Z.hold(o,Date.now()))}n&&await pc(uu,e)}catch(e){console.error(`[worker] restore failed`,e)}Q({type:`ready`}),Bu=!0,Q({type:`list`,list:await $u().catch(()=>[])}),Q({type:`state`,torrents:Xu(),reachable:q.reachable(),inboundNow:dd,rateLimits:{...yd}}),setInterval(()=>{if(!q)return;let e=Date.now();q.popAlerts();for(let e of J)q.postStatus(e);for(let e of[..._d])q.files(e)&&(_d.delete(e),ff(e).length||pf(e));for(let e of[...Ud])pf(e);for(let e of[...Wd.keys()])sf(e),of(e);for(let e of[...xd])q.status(e)&&(xd.delete(e),Pd(e));for(let e of J){if(wd.has(e))continue;let t=q.status(e);t&&(wd.set(e,{activeSeconds:t.activeSeconds,seedingSeconds:t.seedingSeconds}),Ed.set(e,Od(t)))}for(let[e,t]of[...Sd])q.status(e)&&(Sd.delete(e),q.setFlags(e,t.flags>>>0,t.mask>>>0));for(let e of[...sd]){let[t]=pd(e);if(!t)continue;sd.delete(e);let n=Y.get(e);if(!n)continue;let r=q.files(e);$(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=q.status(e);t&&!ll.has(t.state)&&(ul(t)?Wu.delete(e):q.pauseTorrent(e))}for(let e of Gu){if(X.has(e)||ad.has(e)){Gu.delete(e);continue}let t=q.status(e);if(t&&!ll.has(t.state)){if(!t.paused){Gu.delete(e);continue}if(t.autoManaged||t.errorCode){Gu.delete(e);continue}q.resumeTorrent(e)}}Z.retain(new Set(J));for(let t of J){let n=q.status(t);Z.observe(t,n&&wf(n),X.has(t)||ad.has(t),e)}for(let{handle:t,reason:n}of Z.due(e))n===`stalled`&&q.pauseTorrent(t),q.resumeTorrent(t);if(e-ud>=2e3){ud=e;for(let e of J)q.peers(e)}dd=hl(J.map(e=>q.lastPeers(e))),Q({type:`state`,torrents:Xu(),reachable:q.reachable(),inboundNow:dd,detail:fd(e),rateLimits:{...yd}});for(let t of J){let n=q.status(t);if(!n||n.state!==4&&n.state!==5||Uu.get(t)===n.paused||Rd.has(t))continue;let r=Ju.get(t);if(r&&e<r.at)continue;let i=n.paused;zd(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(!q)return;for(let e of J){let t=q.status(e);t&&t.state===3&&zd(e)}let e=!1;for(let t of J){let n=q.status(t),r=Y.get(t),i=wd.get(t);if(!n||!r||!i)continue;e=!0;let a=bl(Td.get(t),i,n);if(!wl(Td.get(t),a))continue;Td.set(t,a),wd.set(t,{activeSeconds:n.activeSeconds,seedingSeconds:n.seedingSeconds});let o=Od(n),s=Sl(Dd.get(t),Ed.get(t)??o,o);Dd.set(t,s),Ed.set(t,o),$(r,{activeSeconds:a.activeSeconds,seedingSeconds:a.seedingSeconds,downloaded:s.downloaded,uploaded:s.uploaded,wasted:s.wasted},!0).catch(()=>{})}e&&Date.now()-Cd>=3e5&&(Cd=Date.now(),$u().then(e=>Q({type:`list`,list:e})).catch(()=>{}))},15e3),setInterval(()=>{Bf()},1e4),Bf(),setTimeout(()=>{Lf(),setInterval(()=>{Lf()},6e5)},6e4),self.addEventListener(`online`,()=>Z.retryNow(Date.now()))},Hf=async(e,t)=>{try{if(t.type===`add-magnet`){let n=Vc(t.magnet),r=n?J.find(e=>Y.get(e)===n):void 0;if(r!==void 0)n&&!t.ephemeral?(id.delete(r),gd(r),ff(r).length&&pf(r),await $(n,{ephemeral:!1,lastUsedAt:Date.now()})):td(r),Q({type:`added`,handle:r,magnet:Vu.get(r)||t.magnet});else{let r=n?(await $u()).find(e=>e.infoHash===n):void 0,i=su(r,t.ephemeral===!0),a=t.savePath||r?.savePath||(i&&n?iu(n):ru(n)),o=e.addMagnet(t.magnet,a);if(Yu(o)){Q({type:`add-failed`,message:`That is not a valid magnet link`});return}md(o,t.magnet,n,a,i),vd.set(o,{wanted:r?.wantedFiles,firstLast:r?.firstLast}),t.hold===!0&&_d.add(o),Md(o,{down:r?.downloadLimit,up:r?.uploadLimit}),Td.set(o,{activeSeconds:r?.activeSeconds??0,seedingSeconds:r?.seedingSeconds??0}),Dd.set(o,kd(r)),Z.hold(o,Date.now());let s=Date.now();t.paused===!0&&hf(o),n&&await ed({infoHash:n,magnet:t.magnet,savePath:a,addedAt:s,lastUsedAt:s,ephemeral:i,started:!0,paused:t.paused===!0}),Q({type:`added`,handle:o,magnet:t.magnet}),Bf()}}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){Q({type:`add-failed`,message:`That torrent could not be created`});return}if(!r.some(e=>e)){Q({type:`add-failed`,message:`Some of those files could not be opened`});return}await pc(gu(n),i);let a=jf(e,{infoHash:n,magnet:t.magnet,bytes:i,handles:r,paused:!1});if(a===null){await hc(gu(n)).catch(()=>{}),Q({type:`add-failed`,message:`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,...lu({name:t.name,size:t.size,files:t.files})}),Q({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)){Q({type:`add-failed`,message:`Some of those files could not be opened`});return}let i=[...Y.entries()].find(([,e])=>e===n);if(i){Q({type:`added`,handle:i[0],magnet:Vu.get(i[0])??``});return}let a=await fc(gu(n));if(!a?.byteLength){Q({type:`add-failed`,message:`The torrent this was built from is no longer stored`});return}let o=(await $u()).find(e=>e.infoHash===n),s=jf(e,{infoHash:n,magnet:o?.magnet??t.magnet??``,bytes:a,handles:r,paused:o?.paused===!0});if(s===null){Q({type:`add-failed`,message:`The engine refused that torrent`});return}Td.set(s,{activeSeconds:o?.activeSeconds??0,seedingSeconds:o?.seedingSeconds??0}),Dd.set(s,kd(o)),await $(n,{started:!0,lastUsedAt:Date.now()}),Q({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)){Q({type:`add-failed`,message:`That file is not a valid .torrent`});return}md(i,``,null,n,t.ephemeral===!0),Z.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(!J.includes(i))return;if(!a){e.removeTorrent(i,!0),hd(i),Q({type:`add-failed`,message:`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(`&`);md(i,s,a,n),await pc(gu(a),r);let c=Date.now();t.paused===!0&&hf(i);let 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:t.paused===!0,...l,...t.created===!0?{created:!0}:{}}),Ff.delete(a),Q({type:`added`,handle:i,magnet:s})}else if(t.type===`read`){if(!J.includes(t.handle)){Q({type:`read-error`,id:t.id,error:`torrent removed`});return}if(gd(t.handle),od.set(t.handle,Date.now()),X.has(t.handle)&&!vf(t.handle,t.fileIndex,t.offset,t.len)){Q({type:`read-error`,id:t.id,error:`torrent paused`});return}if(t.prioritize!==!1)xf(t.viewer,t.handle,t.fileIndex,t.offset,t.len);else if(!vf(t.handle,t.fileIndex,t.offset,t.len)){Q({type:`read-error`,id:t.id,error:`not downloaded`});return}let n=Id.get(t.handle);n||Id.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?Vd.get(t.handle)?.get(t.viewer)?.bulk===!0:!1,i=await e.read(t.handle,t.fileIndex,t.offset,t.len,{timeoutMs:Fd,...r?{deadlineMs:null}:{}});if(!n.has(t.id))return;Q({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=yf(t.handle,t.fileIndex,t.offset,t.len);Q({type:`read-stalled`,id:t.id,handle:t.handle,fileIndex:t.fileIndex,offset:t.offset,len:t.len,waitedMs:(r+1)*Fd,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?Vd.get(t.handle)?.get(t.viewer):void 0;t.prioritize!==!1&&t.viewer&&o&&!o.held&&pf(t.handle)}}finally{n.delete(t.id),J.includes(t.handle)&&od.set(t.handle,Date.now())}}else if(t.type===`cancel-read`)Id.get(t.handle)?.delete(t.id);else if(t.type===`remove`){let n=Y.get(t.handle);Ld(t.handle,`torrent removed`),e.removeTorrent(t.handle,!!t.deleteFiles),hd(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;vd.set(t.handle,{wanted:e,firstLast:n}),df(t.handle);let r=Y.get(t.handle);r&&await $(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=J.find(e=>Y.get(e)===t.infoHash);n!==void 0&&(e?id.add(n):(id.delete(n),gd(n)),ff(n).length&&pf(n)),await $(t.infoHash,{ephemeral:e})}}else if(t.type===`export-start`){let n=J.find(e=>Y.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||!au(r)){Q({type:`answer`,id:t.id,value:null});return}rf.set(n,{running:(rf.get(n)?.running??0)+1,until:Date.now()+nf});let a=await e.saveResumeData(n),o=i.files.flatMap((e,t)=>e.pad?[]:Lu.chunksOf(r,t).map(e=>({fileIndex:t,chunk:e})));Q({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=J.find(e=>Y.get(e)===t.infoHash),n=e===void 0?void 0:Hu.get(e),r=e===void 0?void 0:rf.get(e);if(!r||n===void 0)throw Error(`that torrent is not being handed over`);r.until=Date.now()+nf;let i=await Lu.readChunk(n,t.fileIndex,t.chunk);Q({type:`answer`,id:t.id,value:i},[i.buffer])}else if(t.type===`export-end`){let e=J.find(e=>Y.get(e)===t.infoHash),n=e===void 0?void 0:rf.get(e);if(e===void 0||!n)return;--n.running,n.running||rf.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:iu(t.infoHash),addedAt:e,lastUsedAt:e,ephemeral:!1,started:!0,paused:!1}),Q({type:`answer`,id:t.id,value:!0})}else if(t.type===`import`){let n=t.infoHash;if(typeof n!=`string`||!(t.resume instanceof Uint8Array)||J.some(e=>Y.get(e)===n))return;let r=iu(n);await pc(hu(n),t.resume);let i=e.addTorrentWithResume(t.resume,r);if(Yu(i)){Q({type:`add-failed`,message:`That torrent could not be read`});return}md(i,t.magnet,n,r),_d.add(i),Md(i,{down:0}),qu(i),Z.hold(i,Date.now()),Q({type:`added`,handle:i,magnet:t.magnet})}else if(t.type===`reserve-storage`)typeof t.infoHash==`string`&&t.infoHash&&(t.on===!1?Ff.delete(t.infoHash):Ff.add(t.infoHash));else if(t.type===`set-location`)typeof t.infoHash==`string`&&await $(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?J.find(e=>Y.get(e)===n):void 0;n&&i!==void 0&&await Af(e,i,n,r)}else if(t.type===`import-list`){let e=[];await mc(du,n=>e=fu(n,t.removed));let n=[],r=[],i=!1;await mc(uu,a=>{let o=mu(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=lu(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=Cl(kd(r),kd(e));for(let e of _l)(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,...kd(e)};n.push(a),s.set(a.infoHash,a),i=!0}return n});for(let e of r)await nd(e.infoHash);i&&Q({type:`list`,list:n})}else if(t.type===`start`){let n=(await $u()).find(e=>e.infoHash===t.infoHash);if(n?.saveTo===`source`){Q({type:`add-failed`,message:`Nothing to download this from. Create it again from the same files.`});return}if(n){let t=n.savePath||`/dl`,r=await fc(gu(n.infoHash)),i=r&&r.byteLength?e.addTorrentFile(r,t):e.addMagnet(n.magnet,t);if(Yu(i)){Q({type:`add-failed`,message:`That torrent could not be read`});return}md(i,n.magnet,n.infoHash,t,!1),Md(i,{down:n.downloadLimit,up:n.uploadLimit}),Z.hold(i,Date.now()),Q({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=J.find(e=>Y.get(e)===t.infoHash);n!==void 0&&(Ld(n,`torrent removed`),e.removeTorrent(n,!0),hd(n)),await rd(t.infoHash)}}else if(t.type===`clear-list`){for(let t of[...J])Ld(t,`torrent removed`),e.removeTorrent(t,!0),hd(t);let t=[];await mc(uu,e=>(t=e??[],[])),await hc(du).catch(()=>{});for(let e of t)await hc(hu(e.infoHash)).catch(()=>{}),await hc(gu(e.infoHash)).catch(()=>{});Q({type:`list`,list:[]})}else if(t.type===`pause`){X.add(t.handle),ad.delete(t.handle),Ku(t.handle),Z.forget(t.handle),e.pauseTorrent(t.handle),Ld(t.handle,`torrent paused`),zd(t.handle);let n=Y.get(t.handle);n&&await $(n,{paused:!0})}else if(t.type===`resume`){X.delete(t.handle),ad.delete(t.handle),qu(t.handle),Z.forget(t.handle),e.resumeTorrent(t.handle),Z.hold(t.handle,Date.now());let n=Y.get(t.handle);n&&await $(n,{paused:!1})}else if(t.type===`recheck`){let n=Y.get(t.handle);n&&await hc(hu(n)).catch(()=>{}),Uu.delete(t.handle),Ld(t.handle,`torrent rechecking`),X.delete(t.handle),Wu.delete(t.handle),Gu.delete(t.handle),ad.delete(t.handle),Z.forget(t.handle),e.forceRecheck(t.handle),Z.hold(t.handle,Date.now()),n&&await $(n,{paused:!1})}else if(t.type===`retry-now`)Z.retryNow(Date.now());else if(t.type===`retry`)Z.retry(t.handle,Date.now());else if(t.type===`flush-resume`)await Promise.all(J.map(e=>zd(e)));else if(t.type===`watch`)t.readLen==null?gf(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.held===!0,t.bulk===!0||void 0):xf(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.readLen);else if(t.type===`unwatch`)_f(e=>e===t.viewer);else if(t.type===`set-flags`)e.setFlags(t.handle,t.flags>>>0,t.mask>>>0),zd(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;Md(t.handle,{down:n,up:r})&&e.status(t.handle)&&(xd.delete(t.handle),Pd(t.handle));let i=Y.get(t.handle);if(i){let e={};n!==void 0&&(e.downloadLimit=n),r!==void 0&&(e.uploadLimit=r),Object.keys(e).length&&await $(i,e)}}else if(t.type===`set-session-limits`)Mu(t.down)&&(yd.down=t.down),Mu(t.up)&&(yd.up=t.up),e.setRateLimits({download:yd.down,upload:yd.up}),await pc(ju,{...yd});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`&&_f(e=>e.startsWith(t.owner+`:`))}catch(e){t.type===`read`?Q({type:`read-error`,id:t.id,error:String(e?.stack??e)}):nu.has(t.type)?Q({type:`answer`,id:t.id,error:String(e?.message??e)}):Q({type:`error`,message:String(e?.stack??e)})}},Uf=/* @__PURE__ */ new Set([`read`,`add-torrent-file`,`export-chunk`]);let Wf=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=q;if(!n){t.type===`read`?Q({type:`read-error`,id:t.id,error:`the engine is still starting`}):Q({type:`error`,message:`worker not initialized`});return}if(Uf.has(t.type)){Hf(n,t);return}Wf=Wf.then(()=>Hf(n,t))}),Vf().catch(e=>Q({type:Bu?`error`:`fatal`,message:String(e?.stack??e)}));