@banou/ripple 0.0.9 → 0.0.10
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.
- package/assets/{worker-SJZDGuG-.js → worker-t_vkKkNz.js} +1 -1
- package/index.js +1272 -1252
- package/package.json +1 -1
- package/sw.js +2 -2
|
@@ -20,4 +20,4 @@ var t=Wa(),n=Ga(),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=Ko();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=qo();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=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=Ha(),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=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})),Yo=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=Ka().Buffer,d=Jo().inspect,f=d&&d.custom||`inspect`;function p(e,t,n){u.prototype.copy.call(e,t,n)}t.exports=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.length===1?this.head=this.tail=null:this.head=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,t.next?this.head=t.next:this.head=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,n.next?this.head=n.next:this.head=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}()})),Xo=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}})),Zo=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=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]}`}else 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})),Qo=t(((e,t)=>{var n=Zo().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:16*1024}t.exports={getHighWaterMark:i}})),$o=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?!1:String(t).toLowerCase()===`true`}})),es=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:$o()},a=Ua(),o=Ka().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=Xo(),d=Qo().getHighWaterMark,f=Zo().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;Ha()(T,a);function S(){}function C(e,t,i){r||=ts(),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:!1}})):w=function(e){return e instanceof this};function T(e){r||=ts();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):!0}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?!1: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)}})),ts=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=ss(),i=es();Ha()(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)}})})),ns=t(((e,t)=>{
|
|
22
22
|
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
23
|
-
var n=Ka(),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)}})),rs=t((e=>{var t=ns().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):``}})),is=t(((e,t)=>{var n=Zo().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})),as=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=is(),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}})),os=t(((e,t)=>{t.exports=function(){throw Error(`Readable.from is not available in the browser`)}})),ss=t(((e,t)=>{t.exports=E;var n;E.ReadableState=T,Va().EventEmitter;var r=function(e,t){return e.listeners(t).length},i=Ua(),a=Ka().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=Jo(),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=Yo(),f=Xo(),p=Qo().getHighWaterMark,m=Zo().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;Ha()(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||=ts(),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||=rs().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=ts(),!(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?!1: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||=rs().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?ae(this):M(this),null;if(e=j(e,t),e===0&&t.ended)return t.length===0&&ae(this),null;var r=t.needReadable;u(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,u(`length less than watermark`,r)),t.ended||t.reading?(r=!1,u(`reading or ended`,r)):r&&(u(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=j(n,t)));var i=e>0?ie(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&ae(this)),i!==null&&this.emit(`data`,i),i};function 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,re(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);break}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&&B(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,re(e))}}E.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=B(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`),re(e),t.flowing&&!t.reading&&e.read(0)}E.prototype.pause=function(){return u(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(u(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function re(e){var t=e._readableState;for(u(`flow`,t.flowing);t.flowing&&e.read()!==null;);}E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(u(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){u(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(!n.objectMode&&(!i||!i.length)||t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<C.length;a++)e.on(C[a],this.emit.bind(this,C[a]));return this._read=function(t){u(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(E.prototype[Symbol.asyncIterator]=function(){return b===void 0&&(b=as()),b(this)}),Object.defineProperty(E.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=ie,Object.defineProperty(E.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function ie(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function ae(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(oe,t,e))}function oe(e,t){if(u(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(E.from=function(e,t){return x===void 0&&(x=os()),x(E,e,t)});function B(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),cs=t(((e,t)=>{t.exports=l;var n=Zo().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=ts();Ha()(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)}})),ls=t(((e,t)=>{t.exports=r;var n=cs();Ha()(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)}})),us=t(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=Zo().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=is()),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})),ds=t(((e,t)=>{t.exports=r;var n=Va().EventEmitter;Ha()(r,n),r.Readable=ss(),r.Writable=es(),r.Duplex=ts(),r.Transform=cs(),r.PassThrough=ls(),r.finished=is(),r.pipeline=us(),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}}))(),fs=Va(),ps=class extends ds.Stream.Duplex{_localAddress;_remoteAddress;_webVPNTcpSocketPromise;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){if(this._busyRelease??=Ba(`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._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},{...e,reader:t,writer:n}}).catch(e=>{this.emit(`error`,e)}),!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);return 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(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=_(...e),n=this.__webvpn_tcp_socket_init__(La.then(e=>e.cloud.webvpn.tcpSocket({remoteAddress:t.host??`localhost`,remotePort:t.port})));return t.callback&&n.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`,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},ms=class extends fs.EventEmitter{_localAddress;_webVPNTcpSocketListenerPromise;constructor(e,t){super(e),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??=Ba(`tcp server`),this._webVPNTcpSocketListenerPromise=e.then(e=>(this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},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=_(...e);this._closeEmitted=!1;let n=e=>{let t=new ps;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=e=>La.then(i=>i.cloud.webvpn.tcpSocketListener({localAddress:e,localPort:t.port,onConnection:n,onClose:r})),a=t.host?i(t.host):i(`::`).catch(()=>i(`0.0.0.0`)),o=this.__webvpn_tcp_socket_listener_init__(a);return t.callback&&o.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](){}},hs=(e,t)=>new ps().connect(e,t),gs=(e,t)=>new ps().connect(e,t),_s=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new ms(e);return t&&n.on(`connection`,t),n},vs={Socket:ps,Server:ms,connect:hs,createConnection:gs,createServer:_s,isIP:g,isIPv4:m,isIPv6:h},ys=n({Server:()=>ms,Socket:()=>ps,_default:()=>vs,connect:()=>hs,createConnection:()=>gs,createServer:()=>_s,default:()=>vs,isIP:()=>g,isIPv4:()=>m,isIPv6:()=>h}),bs=Ka(),xs=class extends fs.EventEmitter{_type;_localAddress;_remoteAddress;_connectedLocally;_connectGeneration=0;_destroyed=!1;_busyRelease;_webVPNUdpSocketPromise;_dataPort;_socketId;_sendQueue=[];_sendQueueBytes=0;_sendFlushScheduled=!1;_peerTailCache=new Map;constructor(e){if(super(e),!e)throw Error(`Missing options`);this._type=e.type,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`,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:p,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=Ts(n)),s+=n.byteLength,d=t.getUint16(s),s+=2}let f=t.getUint32(s);s+=4;try{this.emit(`message`,bs.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 Ss;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let i=d.Address4.isValid(e)?ws(e):Es(e),a=new Uint8Array(1+i.byteLength+2);return a[0]=i.byteLength===4?0:1,a.set(i,1),new DataView(a.buffer).setUint16(1+i.byteLength,t),this._peerTailCache.size>=4096&&this._peerTailCache.clear(),this._peerTailCache.set(n,a),a}_portSend(e,t,n){let r=this._peerTail(t,n),i=new Uint8Array(8+r.byteLength+4+e.byteLength),a=new DataView(i.buffer);a.setUint32(0,i.byteLength-4),a.setUint32(4,this._socketId),i.set(r,8),a.setUint32(8+r.byteLength,e.byteLength),i.set(e,12+r.byteLength),this._sendQueue.push(i),this._sendQueueBytes+=i.byteLength,!this._sendFlushScheduled&&(this._sendFlushScheduled=!0,queueMicrotask(()=>{this._sendFlushScheduled=!1;let e=this._sendQueue,t=this._sendQueueBytes;if(this._sendQueue=[],this._sendQueueBytes=0,!e.length||!this._dataPort)return;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;this._dataPort.postMessage(n.buffer,[n.buffer])}))}addMembership(e,t){if(d.Address4.isValid(e)){let n=ws(e),r=t&&d.Address4.isValid(t)?ws(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(d.Address6.isValid(e)){let t=Es(e);this._setUdpOption({type:7,group:t,ifIndex:0})}else this.emit(`error`,Error(`Invalid multicast address: ${e}`))}address(){if(!this._localAddress)throw Error(`EBADF`);return this._localAddress}bind(...e){let t=v(...e),n=this._type===`udp6`?`::`:`0.0.0.0`,r=this.__webvpn_udp_socket_init__(La.then(e=>e.cloud.webvpn.udpSocket({type:this._type,address:t.address??n,port:t.port,dataPort:!0})));return t.callback&&r.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??=Ba(`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`,bs.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._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(d.Address4.isValid(e)){let n=ws(e),r=t&&d.Address4.isValid(t)?ws(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(d.Address6.isValid(e)){let t=Es(e);this._setUdpOption({type:8,group:t,ifIndex:0})}else this.emit(`error`,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=y(...e),n=Cs(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(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(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||d.Address4.isValid(a)||d.Address6.isValid(a))){this._portSend(r,o?void 0:a,o?void 0:t.port),n?.call(this,null,r.byteLength);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)})}},Ss=new Uint8Array([2]),Cs=e=>{if(typeof e==`string`)return f.encode(e);if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(Array.isArray(e)){let t=e.map(Cs),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)},ws=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)},Ts=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(`:`)}`},Es=e=>{let t=new d.Address6(e).getBitsBase16(0,128).match(/.{2}/g);if(!t||t.length!==16)throw Error(`Invalid IPv6 address: ${e}`);return new Uint8Array(t.map(e=>parseInt(e,16)))},Ds=(e,t)=>{let n=new xs(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},Os={Socket:xs,createSocket:Ds},ks=n({Socket:()=>xs,createSocket:()=>Ds,default:()=>Os});function As(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function js(e,t){let n,r=()=>{if(n)return n;let r=indexedDB.open(e);return r.onupgradeneeded=()=>r.result.createObjectStore(t),n=As(r),n.then(e=>{e.onclose=()=>n=void 0},()=>{}),n};return(e,n)=>r().then(r=>n(r.transaction(t,e).objectStore(t)))}let Ms;function Ns(){return Ms||=js(`keyval-store`,`keyval`),Ms}function Ps(e,t=Ns()){return t(`readonly`,t=>As(t.get(e)))}function Fs(e,t,n=Ns()){return n(`readwrite`,n=>(n.put(t,e),As(n.transaction)))}function Is(e,t,n=Ns()){return n(`readwrite`,n=>new Promise((r,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),r(As(n.transaction))}catch(e){i(e)}}}))}function Ls(e,t=Ns()){return t(`readwrite`,t=>(t.delete(e),As(t.transaction)))}var Rs={checkingFiles:1,downloadingMetadata:2,downloading:3,finished:4,seeding:5,checkingResumeData:7},zs=/^incoming connection from (\S+) \(([^)]*)\)/,Bs=/^successfully listening on \[([^\]]*)\] (\S+)/,Vs=/^listening on .* failed:/,Hs=new TextDecoder,Us=4026531841,Ws=4026531842,Gs=4026531843,Ks=4026531844,qs=4026531845,Js=4026531846,Ys={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},Xs={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},Zs={top:0,up:1,down:2,bottom:3},Qs={tracker:1,dht:2,pex:4,lsd:8,resumeData:16,incoming:32},G={skip:0,low:1,normal:4,top:7},$s=6e4,ec=12,tc=1e3,nc=class{mod;storage;destroyed=!1;fallbackTimer;filesByHandle=new Map;bitfieldByHandle=new Map;statusByHandle=new Map;pieceWaiters=[];resumeByHandle=new Map;resumeWaiters=[];peersByHandle=new Map;trackersByHandle=new Map;peerWaiters=[];trackerWaiters=[];priosByHandle=new Map;deadlineRefs=new Map;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(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(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 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??ec)),s=Math.max(0,Math.floor(n.deadlineStepMs??tc)),c=n.claimedPriority??G.normal,l=n.unclaimedPriority??G.normal,u=new Uint8Array(a).fill(l),d=new Map,f=0;for(let e of t){let t=r.files[e.fileIndex];if(!t||t.size<=0)continue;f++;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++)u[e]=c;let p=Math.min(Math.max(e.offset,0),Math.max(0,t.size-1)),m=Math.min(Math.max(Math.floor((t.offset+p)/i),n),l);for(let e=0;e<o;e++){let t=m+e;if(t>l)break;u[t]=G.top;let n=e*s,r=d.get(t);(r===void 0||n<r)&&d.set(t,n)}}if(!f)return!1;if(this.mod._lt_torrent_clear_piece_deadlines(e),this.prioritizePieces(e,u),n.deadlines!==!1)for(let[t,n]of d)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)*tc,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,Zs[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}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=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??$s;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(Error(`read: aborted`));return}a>0&&(s=setTimeout(()=>l(Error(`read: pieces ${t}-${n} of handle ${e} did not arrive within ${a}ms`)),a)),i&&(c=()=>l(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(){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=[],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===Us)this.decodeTorrentReady(r,a);else if(o===Ws)this.decodeStateUpdate(r,a);else if(o===Ks)this.decodeResumeData(r,a,s);else if(o===qs)this.decodePeers(r,a);else if(o===Js)this.decodeTrackers(r,a);else if(o!==Gs){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()}return i}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=zs.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=Bs.exec(e);if(n){this.reachability.listening[n[1].toLowerCase()]=n[2];return}Vs.test(e)&&this.reachability.listenFailed.length<32&&this.reachability.listenFailed.push(e)}readStr(e,t){let n=e.getUint32(t,!0);return t+=4,[Hs.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):!0)}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?Hs.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!==Rs.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(Error(`read: session destroyed`)),this.pieceWaiters=[],this.resumeWaiters=[],this.deadlineRefs.clear(),this.priosByHandle.clear(),this.mod._lt_session_destroy(),this.mod.__FKN?.teardown?.())}},rc=8e3,ic=e=>{try{e?.close()}catch{}},ac=(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,rc);r.on(`listening`,()=>{i||(i=!0,clearTimeout(o),n(r))}),r.on(`error`,a);try{t(r)}catch{a()}});async function oc(e,t,n=4){try{return await sc(e,t,n)}catch{return null}}async function sc(e,t,n){for(let r=0;r<n;r++){let i=await ac(()=>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 ac(()=>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 cc(e){let t=e.moduleFactory??(await import(`./libtorrent-DS_9Yo8M.js`)).default,n={net:e.net,dgram:e.dgram,storage:e.storage??null,debug:e.debug??!1},r=e.reserveListenPort===!1?Promise.resolve(null):oc(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 nc(i,e)}catch(e){throw a&&!a.adopted&&(ic(a.server),ic(a.udp)),e}return o.setReservedPort(a?a.port:null),o}const lc=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},uc=25e5,dc=e=>{if(!Number.isFinite(e)||e<=0)return 12;let t=Math.ceil(uc/e)+1,n=Math.max(2,Math.floor(8388608/e));return Math.min(Math.max(t,2),n)},fc=e=>dc(e)*Math.max(0,e),pc=e=>Math.max(1,Math.floor(fc(e)/2)),mc=(e,t)=>Math.min(2e3,Math.max(50,Math.round(e/Math.max(t,25e4)*1e3))),hc=(e,t,n,r=uc)=>{let i=e.fileOffset+n+Math.max(0,r-1);return Math.floor(i/e.pieceLength)>=e.p1?!1:Math.abs(n-t)>=pc(e.pieceLength)};var gc=class{storages=new Map;opened=new Map;onNewStorage(e,t,n){let r=(async()=>{let r=await _c(await navigator.storage.getDirectory(),t.replace(/^\/+/,``));this.storages.set(e,{rootDir:r,files:new Map,opening: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 _c(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}const vc=[50,150,400,900,1500],yc=e=>e?.name===`QuotaExceededError`,bc=e=>new Promise(t=>setTimeout(t,e)),xc=()=>{let e=new gc,t=new Set,n=new Map,r=e,i=(e,t)=>{let n=r.storages?.get(e),i=n?.files?.get(t);if(i){n.files.delete(t);try{i.close()}catch{}}},a=async e=>{let t=n.get(e);if(t===void 0)return null;let i=r.storages?.get(t);if(!i?.fileMeta||!i.rootDir)return null;let a=0;for(let e=0;e<i.fileMeta.length;e++){let t=i.files?.get(e);if(t)try{a+=t.getSize();continue}catch{}let n=i.fileMeta[e].path.split(`/`).filter(Boolean),r=n.pop();if(!r)continue;let o=i.rootDir;for(let e of n)o=o?await o.getDirectoryHandle(e).catch(()=>null):null;o&&(a+=await o.getFileHandle(r).then(e=>e.getFile()).then(e=>e.size).catch(()=>0))}return a},o=async(e,n,r,a)=>{let o=a;for(let a of vc){if(yc(o))break;if(i(e,n),await bc(a),t.has(e))throw o;try{return await r()}catch(e){o=e}}throw o},s=(e,t,n)=>{try{let r=n();return r instanceof Promise?r.catch(r=>o(e,t,n,r)):r}catch(r){return o(e,t,n,r)}};return{usageOf:a,onNewStorage:(r,i,a)=>(t.delete(r),n.set(i,r),s(r,-1,()=>e.onNewStorage(r,i,a))),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)=>s(t,n,()=>e.read(t,n,r,i)),write:(t,n,r,i)=>s(t,n,()=>e.write(t,n,r,i)),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)}},Sc=[5e3,15e3,3e4,6e4,12e4,3e5],Cc=1e4,wc=new Set([2,3]),Tc=new Set([1,7]),Ec=e=>!!e&&e.paused&&!e.autoManaged,Dc=()=>{let e=new Map,t=new Map,n=new Map,r=new Map,i=e=>Sc[Math.min(e,Sc.length-1)],a=i=>{e.delete(i),t.delete(i),n.delete(i),r.delete(i)};return{hold:(e,t,n=Cc)=>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(Tc.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`:wc.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+Cc,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)}}},Oc=e=>!(e.flags&Ys.localConnection)||!!(e.source&Qs.incoming),kc=e=>e.flags&Ys.utpSocket?`utp`:`tcp`,Ac={total:0,byTransport:{}},jc=e=>{let t={},n=0;for(let r of e)for(let e of r){if(!Oc(e)||e.connectionType!==0)continue;n+=1;let r=kc(e);t[r]=(t[r]??0)+1}return{total:n,byTransport:t}},Mc={activeSeconds:0,seedingSeconds:0},Nc=[`activeSeconds`,`seedingSeconds`,`downloaded`,`uploaded`,`wasted`],Pc={activeSeconds:0,seedingSeconds:0,downloaded:0,uploaded:0,wasted:0},K=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0,Fc=(e,t)=>({activeSeconds:Math.max(0,K(t.activeSeconds)-K(e.activeSeconds)),seedingSeconds:Math.max(0,K(t.seedingSeconds)-K(e.seedingSeconds))}),Ic=(e,t,n)=>{let r=Fc(t,n);return{activeSeconds:K(e?.activeSeconds)+r.activeSeconds,seedingSeconds:K(e?.seedingSeconds)+r.seedingSeconds}},Lc=(e,t)=>Object.fromEntries(Nc.map(n=>[n,Math.max(0,K(t[n])-K(e[n]))])),Rc=(e,t,n)=>{let r=Lc(t,n);return Object.fromEntries(Nc.map(t=>[t,K(e?.[t])+r[t]]))},zc=(e,t)=>Object.fromEntries(Nc.map(n=>[n,Math.max(K(e?.[n]),K(t?.[n]))])),Bc=(e,t)=>t.activeSeconds-K(e?.activeSeconds)>=30||t.seedingSeconds-K(e?.seedingSeconds)>=30,Vc=e=>!Number.isFinite(e)||e<=0?0:Math.min(1e9,Math.floor(e*.1)),Hc=(e,t)=>!Number.isFinite(e)||e<=0?Math.max(0,t):Math.max(Math.min(.25*e,2e10),Math.max(0,t)),Uc=({usedBytes:e,limitBytes:t})=>!Number.isFinite(t)||t<=0||!Number.isFinite(e)||e<0?!1:t-e<Vc(t),Wc=(e,t)=>e.usedAt-t.usedAt||(e.infoHash<t.infoHash?-1:+(e.infoHash>t.infoHash)),Gc=({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(Wc);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=Vc(t),c=s+Math.max(0,n),l=t-e,u=o(e=>l+a[e]>=c),d=o(e=>l+a[e]>=s),f=u>=0?u:d>=0?d:i.length,p=a[i.length],m=i.reduce((e,t)=>Math.max(e,t.bytesOnDisk),0),h=Hc(t,m),g=o(e=>p-a[e]<=h);return i.slice(0,Math.max(f,g<0?i.length:g)).map(e=>e.infoHash)};var Kc=8,qc=2e4,Jc=e=>typeof e.values==`function`,Yc=async e=>{let t=0,n=0,r=async(e,i)=>{if(!(i>Kc))for await(let a of e.values()){if(++n>qc)return;if(Jc(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}},Xc=(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)},Zc,Qc,$c=(e,t,n)=>{if(e!==void 0)return n!==Qc&&(Zc=void 0),Qc=n,Zc=Zc===void 0?e:Math.min(Zc,e),Math.max(Zc,t??0)},el=async e=>e.persisted?e.persisted().then(e=>e===!0).catch(()=>Qc):void 0,tl={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=>Yc(e)).catch(()=>null):null,el(e)]),i=Xc(t,n);return{...t,usage:i,quota:$c(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 el(e)??null??t},persisted:()=>globalThis.navigator?.storage?.persisted?.()??Promise.resolve(!1),getDirectory:()=>{let e=globalThis.navigator?.storage;return e?.getDirectory?e.getDirectory():Promise.reject(Error(`this browser has no origin private file system`))}};const nl=/^(?:[0-9a-f]{40}|[0-9a-f]{64}|[a-z2-7]{32})$/i,rl=({entries:e,listedHashes:t,claimedNames:n,attributable:r})=>e.filter(({name:e,kind:i})=>n.has(e)?!1:i===`directory`&&nl.test(e)?!t.has(e.toLowerCase()):r).map(({name:e})=>e),il=async e=>{let t=[];for await(let n of e.values())t.push({name:n.name,kind:n.kind});return t},al=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},ol=async(e,t,n)=>{let r=await al(e,t);if(!r)return[];let i=[];for(let e of rl({...n,entries:await il(r)}))try{await r.removeEntry(e,{recursive:!0}),i.push(e)}catch{}return i},sl=async e=>{let t=0;for(let{name:n,kind:r}of await il(e))r!==`file`||!n.startsWith(`.ripple-probe-`)||await e.removeEntry(n).then(()=>!0,()=>!1)&&t++;return t},cl=e=>e?`/dl/`+e:`/dl`,ll=(e,t)=>e===cl(t),ul=(e,t)=>t&&(e?e.ephemeral===!0:!0),dl=(e,t)=>e?{...t,ephemeral:ul(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,fl=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}),pl=`ripple:torrents`,ml=e=>`ripple:resume:`+e,hl=e=>typeof e.getFile==`function`?e.getFile():Promise.resolve(e),gl=e=>`/native/${e}`,_l=e=>e===`/native`||!!e?.startsWith(`/native/`),vl=e=>`/source/${e}`,yl=e=>e===`/source`||!!e?.startsWith(`/source/`),bl=e=>_l(e)||yl(e),xl=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()},Sl=(e,t,n=()=>null)=>{let r=new Map,i=new Map,a=e=>{let n=t();if(!n)throw Error(`hybrid storage: no folder granted, cannot ${e}`);return n},o=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?hl(n):null};return{usageOf:async t=>bl(t)?0:e.usageOf(t),onNewStorage:(t,a,o)=>{if(yl(a)){i.set(t,{savePath:a,files:o,handles:n(a)});return}if(!_l(a))return e.onNewStorage(t,a,o);r.set(t,{savePath:a,files:o})},onRemoveStorage:t=>{if(!i.delete(t)&&!r.delete(t))return e.onRemoveStorage(t)},read:(t,n,s,c)=>{let l=i.get(t);if(l)return(async()=>{let e=await o(l,n);if(!e)return new Uint8Array(c);let t=await e.slice(s,s+c).arrayBuffer();if(t.byteLength<c)throw Error(`hybrid storage: source file ${n} of ${l.savePath} ended early, wanted ${c} at ${s}, got ${t.byteLength}`);return new Uint8Array(t)})();let u=r.get(t);if(!u)return e.read(t,n,s,c);let d=u.files[n];if(!d)throw Error(`hybrid storage: no file ${n} in ${u.savePath}`);return(async()=>{let e=await(await xl(a(`read`),d.path)).slice(s,s+c).arrayBuffer();if(e.byteLength<c)throw Error(`hybrid storage: ${d.path} ended early, wanted ${c} at ${s}, got ${e.byteLength}`);return new Uint8Array(e)})()},write:(t,n,a,o)=>{let s=i.get(t);if(s)throw Error(`hybrid storage: ${s.savePath} is somebody's own files, refusing a write of ${o.length} at ${a} in file ${n}`);let c=r.get(t);if(!c)return e.write(t,n,a,o);throw Error(`hybrid storage: ${c.savePath} is read only, refusing a write of ${o.length} at ${a} in file ${n}`)},check:async t=>{if(i.get(t))return 2;let n=r.get(t);if(!n)return e.check(t);try{let e=a(`check`);for(let t of n.files){let n=await xl(e,t.path).catch(()=>null);if(n&&n.size>0)return 2}return 0}catch{return 2}},deleteFiles:async(t,n)=>{if(!i.has(t)&&!r.get(t))return e.deleteFiles(t,n)},release:async t=>{!r.has(t)&&!i.has(t)&&await e.release(t)},stop:async t=>{!r.has(t)&&!i.has(t)&&await e.stop(t)}}},Cl=(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))],wl=({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]=Cl(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]=Cl(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},Tl=({wanted:e,firstLast:t})=>e===void 0&&!t,El=e=>yl(e)?`source`:_l(e)?`folder`:`browser`,Dl=(e,t)=>{if(e===`source`){if(!t)throw Error(`a source-backed torrent needs its infohash to name its save path`);return vl(t)}return e===`folder`?t?gl(t):`/dl`:cl(t)},Ol=`ripple:rate-limits`,kl=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,Al=e=>{let t=e??{};return{down:kl(t.down)?t.down:0,up:kl(t.up)?t.up:0}},jl=new Set(`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(`.`)),Ml=e=>`ripple:torrent:`+e,Nl=e=>`ripple:source:`+e;let q=null,Pl=null,Fl=null;const Il=new Map;let Ll=!1;const J=[],Rl=new Map,Y=new Map,zl=new Map,Bl=new Map,X=new Set,Vl=new Set,Hl=new Set,Ul=e=>{Hl.delete(e),Vl.add(e)},Wl=e=>{Vl.delete(e),Hl.add(e)},Gl=new Map,Z=Dc(),Kl=e=>e>=4294967040,Q=(e,t)=>self.postMessage(e,t??[]),ql=()=>J.map(e=>{let t=q.bitfield(e);return{handle:e,magnet:Rl.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),uptime:Jl(e),sessionUptime:Yl(e),totals:Eu(e)}}),Jl=e=>{let t=q?.status(e),n=bu.get(e);return!t||!n?xu.get(e)??Mc:Ic(xu.get(e),n,t)},Yl=e=>{let t=q?.status(e),n=bu.get(e);return t&&n?Fc(n,t):Mc},Xl=async()=>await Ps(`ripple:torrents`)??[],Zl=async e=>{let t=[];await Is(pl,n=>{t=n??[];let r=t.findIndex(t=>t.infoHash===e.infoHash),i=dl(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 Is(pl,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})},Ql=e=>{let t=Y.get(e);t&&$(t,{lastUsedAt:Date.now()},!0).catch(()=>{})},$l=async e=>{let t=[];await Is(pl,n=>t=(n??[]).filter(t=>t.infoHash!==e)),await Ls(ml(e)).catch(()=>{}),await Ls(Ml(e)).catch(()=>{}),await Ls(Nl(e)).catch(()=>{}),Q({type:`list`,list:t})},eu=new Set,tu=new Set,nu=new Map,ru=new Set;let iu=null,au=0,ou=0,su=Ac;const cu=e=>{let t=iu;return t==null||!J.includes(t)?null:(q.peers(t),e-au>=5e3&&(au=e,q.trackers(t)),{handle:t,peers:q.lastPeers(t),trackers:q.lastTrackers(t)})},lu=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)]},uu=(e,t,n,r,i=!1)=>{J.includes(e)||J.push(e),Rl.set(e,t),n&&(Y.set(e,n),ru.add(e)),zl.set(e,r),i?eu.add(e):eu.delete(e)},du=e=>{let t=J.indexOf(e);t>=0&&J.splice(t,1),Rl.delete(e),Y.delete(e),zl.delete(e),Bl.delete(e),X.delete(e),Z.forget(e),Nu.delete(e),ju.delete(e),Vl.delete(e),Hl.delete(e),Gl.delete(e),Iu.delete(e),Lu.delete(e),pu.delete(e),mu.delete(e),gu.delete(e),_u.delete(e),vu.delete(e),bu.delete(e),xu.delete(e),Su.delete(e),Cu.delete(e),eu.delete(e),tu.delete(e),nu.delete(e),ru.delete(e)},fu=e=>{tu.delete(e)&&(Wl(e),q?.resumeTorrent(e),Z.hold(e,Date.now()))},pu=new Set,mu=new Map;let hu={down:0,up:0};const gu=new Map,_u=new Set,vu=new Map;let yu=0;const bu=new Map,xu=new Map,Su=new Map,Cu=new Map,wu=e=>({activeSeconds:e.activeSeconds,seedingSeconds:e.seedingSeconds,downloaded:e.allTimeDownload,uploaded:e.allTimeUpload,wasted:e.wasted}),Tu=e=>({activeSeconds:e?.activeSeconds??0,seedingSeconds:e?.seedingSeconds??0,downloaded:e?.downloaded??0,uploaded:e?.uploaded??0,wasted:e?.wasted??0}),Eu=e=>{let t=q?.status(e),n=Su.get(e);return!t||!n?Cu.get(e)??Pc:Rc(Cu.get(e),n,wu(t))},Du=(e,t,n)=>{let r=vu.get(e);vu.set(e,r?{flags:r.flags&~n|t&n,mask:r.mask|n}:{flags:t&n,mask:n})},Ou=(e,t)=>{let n={...gu.get(e)};return kl(t.down)&&(n.down=t.down),kl(t.up)&&(n.up=t.up),!kl(n.down)&&!kl(n.up)?!1:(gu.set(e,n),_u.add(e),!0)},ku=e=>{let t=gu.get(e);!q||!t||(kl(t.down)&&q.setDownloadLimit(e,t.down),kl(t.up)&&q.setUploadLimit(e,t.up))},Au=6e3,ju=new Map,Mu=(e,t)=>{let n=ju.get(e);if(n?.size){for(let e of n)Q({type:`read-error`,id:e,error:t});n.clear()}},Nu=new Set,Pu=async e=>{let t=Y.get(e);if(!t||!q||Nu.has(e)||yl(zl.get(e)))return!1;Nu.add(e);try{let n=await q.saveResumeData(e);return J.includes(e)?(await Fs(ml(t),n),!0):!1}catch(e){return console.error(`[worker] saving resume data failed`,String(e)),!1}finally{Nu.delete(e)}},Fu=(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}},Iu=new Map,Lu=new Set,Ru=e=>{let t=mu.get(e);if(!q||!t||Tl(t))return;let n=q.files(e);n&&q.prioritizePieces(e,wl({files:n.files,pieceLength:n.pieceLength,numPieces:Math.ceil(n.totalSize/n.pieceLength),wanted:t.wanted,firstLast:t.firstLast}))},zu=e=>{let t=Iu.get(e);return t?[...t.values()].filter(e=>!e.held):[]},Bu=e=>{if(!q)return;if(!J.includes(e)){Iu.delete(e),Lu.delete(e);return}let t=zu(e);if(!t.length){if(!q.files(e)){Lu.add(e);return}Lu.delete(e),q.clearStreamWindow(e),Ru(e),eu.has(e)&&!X.has(e)&&!tu.has(e)&&(tu.add(e),Ul(e),q.pauseTorrent(e),Pu(e));return}fu(e);let n=q.files(e);if(!n){Lu.add(e);return}let r=t.map(({fileIndex:e,fromOffset:t})=>({fileIndex:e,offset:t})),i=t.some(e=>!e.bulk);q.setStreamWindow(e,r,{unclaimedPriority:G.skip,windowPieces:dc(n.pieceLength),deadlineStepMs:mc(n.pieceLength,q.status(e)?.downloadRate||3e6),deadlines:i})?Lu.delete(e):Lu.add(e)},Vu=e=>{X.add(e),tu.delete(e),Ul(e),Z.forget(e),q?.pauseTorrent(e)},Hu=(e,t,n,r,i=!1,a)=>{if(!J.includes(t))return;let o=Iu.get(t),s=!o?.size;o||Iu.set(t,o=new Map);let c=a??o.get(e)?.bulk;o.set(e,{fileIndex:n,fromOffset:r,...i?{held:i}:{},...c?{bulk:c}:{}}),s&&Ql(t),Bu(t)},Uu=e=>{for(let[t,n]of Iu){let r=!1;for(let t of[...n.keys()])e(t)&&(n.delete(t),r=!0);n.size||(Iu.delete(t),r&&Ql(t)),r&&Bu(t)}},Wu=(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},Gu=(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},Ku=()=>{if(!q)return 0;let e=0;for(let[t,n]of Iu){if(!n.size||!J.includes(t))continue;let r=q.files(t),i=q.bitfield(t);if(!r)continue;if(!i){for(let{fileIndex:t}of n.values())e+=r.files[t]?.size??0;continue}let a=new Set;for(let{fileIndex:e}of n.values()){let n=Fu(t,e);if(n)for(let e=n.p0;e<=n.p1;e++)(i.pieces[e>>3]??0)&128>>(e&7)||a.add(e)}e+=a.size*r.pieceLength}return e},qu=(e,t,n,r,i)=>{if(!e||!J.includes(t))return;let a=Iu.get(t)?.get(e);if(!a||a.held||a.fileIndex!==n){Hu(e,t,n,r);return}let o=Fu(t,n);o&&hc({fileOffset:o.file.offset,pieceLength:o.pieceLength,p1:o.p1},a.fromOffset,r,i)&&Hu(e,t,n,r)},Ju=async e=>{let t=e.filter(e=>!bl(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}},Yu=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}},Xu=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}),Zu=async()=>{try{let{usage:e,quota:t}=await tl.estimate();return!t||e===void 0?null:{usedBytes:e,limitBytes:t}}catch{return null}},Qu=async e=>{for(let t=0;t<4e3;t+=250){await new Promise(e=>setTimeout(e,250));let t=await Zu();if(!t||t.usedBytes<e)return t}return Zu()},$u=async(e,t,n,r,i={})=>{Mu(t,r),e.removeTorrent(t,!0),du(t),await Ls(ml(n)).catch(()=>{}),await $(n,{started:!1,paused:!1,...i})},ed=(e,t,n)=>$u(e,t,n,`torrent removed to make room`),td=async(e,t,n,r)=>{let i=El(zl.get(t));if(i===r)return;let a=Rl.get(t)??``,o=Dl(r,n),s=X.has(t),c=eu.has(t);Mu(t,`files moved`),e.removeTorrent(t,i===`browser`),du(t),await Ls(ml(n)).catch(()=>{});let l=e.addMagnet(a,o);if(Kl(l)){Q({type:`add-failed`,message:`Moving the files left the torrent unaddable`}),await $(n,{savePath:o,saveTo:r,started:!1});return}uu(l,a,n,o,c),r===`folder`&&Du(l,Xs.uploadMode,Xs.uploadMode),s?(X.add(l),Ul(l)):Wl(l),Z.hold(l,Date.now()),await $(n,{savePath:o,saveTo:r,started:!0})},nd=(e,{infoHash:t,magnet:n,bytes:r,handles:i,paused:a})=>{let o=vl(t);Il.set(o,i);let s=e.addTorrentFile(r,o);return Kl(s)?(Il.delete(o),null):(uu(s,n,t,o,!1),Du(s,Xs.uploadMode,Xs.uploadMode),a&&(X.add(s),Ul(s)),Z.hold(s,Date.now()),s)},rd=async(e,t)=>{let n=new Map(e.map(e=>[e.infoHash,e])),r=[];for(let e of[...J]){let i=Y.get(e);if(!i)continue;let a=n.get(i);if(!a?.ephemeral||!ll(a.savePath,i)||Iu.get(e)?.size||ju.get(e)?.size||t-(nu.get(e)??0)<6e4)continue;let o=a.lastUsedAt??a.addedAt;if(t-o<15e3)continue;let s=await Pl?.usageOf(a.savePath)??0;s<=0||r.push({infoHash:i,usedAt:o,bytesOnDisk:s})}return r};let id=!1;const ad=e=>{let t=Uc(e);t!==id&&(id=t,Q({type:`storage-full`,full:t,usedBytes:e.usedBytes,limitBytes:e.limitBytes}))},od=new Set;let sd=!1;const cd=async()=>{if(!q||sd)return 0;sd=!0;try{let e=await Xl(),t=new Set(e.map(e=>e.infoHash.toLowerCase()));for(let e of od)t.add(e.toLowerCase());let n=new Set,r=!0;for(let e of J){let i=Y.get(e);if(i&&t.add(i.toLowerCase()),(zl.get(e)??`/dl`)!==`/dl`)continue;let a=lu(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(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 ol(i,`/dl`,{listedHashes:t,claimedNames:n,attributable:r});return await sl(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{sd=!1}};let ld=!1;const ud=async()=>{let e=q;if(!e||ld)return;ld=!0;let t=null;try{let n=await Zu();if(!n)return;t=n;let r=Ku(),i=await rd(await Xl(),Date.now());for(;i.length;){let[a]=Gc({...n,pendingBytes:r,candidates:i});if(!a)break;i=i.filter(e=>e.infoHash!==a);let o=J.find(e=>Y.get(e)===a);if(o===void 0||Iu.get(o)?.size||ju.get(o)?.size)continue;let s=n.usedBytes;t=null,await ed(e,o,a);let c=await Qu(s);if(!c)return;n=c,t=c}Uc(n)&&await cd()&&(n=await Qu(n.usedBytes)??n),t=n}catch(e){console.error(`[worker] storage budget pass failed`,String(e))}finally{ld=!1,t&&ad(t)}},dd=async()=>{let e=console.error.bind(console);if(console.error=(...t)=>{e(...t);try{Q({type:`worker-error`,args:t.map(String)})}catch{}},!await Yu()){Q({type:`storage-unavailable`});return}Xl().then(e=>{e.length&&Q({type:`list`,list:e})}).catch(()=>{});let t=Promise.race([Ps(Ol).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]);Pl=Sl(xc(),()=>Fl,e=>Il.get(e)??null),q=await cc({net:ys,dgram:ks,storage:Pl,utpReceiveBufferBytes:4194304});for(let e=0;e<30;e++)q.tick();hu=Al(await t),q.setRateLimits({download:hu.down,upload:hu.up});try{let e=await Xl(),t=!await Ju(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 Ps(ml(r.infoHash)),a=await Ps(Ml(r.infoHash));if(t&&i&&i.byteLength){await Ls(ml(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);Kl(o)||(uu(o,r.magnet,r.infoHash,e,r.ephemeral===!0),mu.set(o,{wanted:r.wantedFiles,firstLast:r.firstLast}),pu.add(o),Ou(o,{down:r.downloadLimit,up:r.uploadLimit}),xu.set(o,{activeSeconds:r.activeSeconds??0,seedingSeconds:r.seedingSeconds??0}),Cu.set(o,Tu(r)),r.paused?(X.add(o),Ul(o)):Wl(o),Z.hold(o,Date.now()))}n&&await Fs(pl,e)}catch(e){console.error(`[worker] restore failed`,e)}Q({type:`ready`}),Ll=!0,Q({type:`list`,list:await Xl().catch(()=>[])}),Q({type:`state`,torrents:ql(),reachable:q.reachable(),inboundNow:su,rateLimits:{...hu}}),setInterval(()=>{if(!q)return;let e=Date.now();q.popAlerts();for(let e of J)q.postStatus(e);for(let e of[...pu])q.files(e)&&(pu.delete(e),zu(e).length||Bu(e));for(let e of[...Lu])Bu(e);for(let e of[..._u])q.status(e)&&(_u.delete(e),ku(e));for(let e of J){if(bu.has(e))continue;let t=q.status(e);t&&(bu.set(e,{activeSeconds:t.activeSeconds,seedingSeconds:t.seedingSeconds}),Su.set(e,wu(t)))}for(let[e,t]of[...vu])q.status(e)&&(vu.delete(e),q.setFlags(e,t.flags>>>0,t.mask>>>0));for(let e of[...ru]){let[t]=lu(e);if(!t)continue;ru.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 Vl){let t=q.status(e);!t||Tc.has(t.state)||(Ec(t)?Vl.delete(e):q.pauseTorrent(e))}for(let e of Hl){if(X.has(e)||tu.has(e)){Hl.delete(e);continue}let t=q.status(e);if(!(!t||Tc.has(t.state))){if(!t.paused){Hl.delete(e);continue}if(t.autoManaged||t.errorCode){Hl.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&&Xu(n),X.has(t)||tu.has(t),e)}for(let{handle:t,reason:n}of Z.due(e))n===`stalled`&&q.pauseTorrent(t),q.resumeTorrent(t);if(e-ou>=2e3){ou=e;for(let e of J)q.peers(e)}su=jc(J.map(e=>q.lastPeers(e))),Q({type:`state`,torrents:ql(),reachable:q.reachable(),inboundNow:su,detail:cu(e),rateLimits:{...hu}});for(let t of J){let n=q.status(t);if(!n||n.state!==4&&n.state!==5||Bl.get(t)===n.paused||Nu.has(t))continue;let r=Gl.get(t);if(r&&e<r.at)continue;let i=n.paused;Pu(t).then(e=>{if(e){Bl.set(t,i),Gl.delete(t);return}let n=(Gl.get(t)?.tries??0)+1;Gl.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&&Pu(e)}let e=!1;for(let t of J){let n=q.status(t),r=Y.get(t),i=bu.get(t);if(!n||!r||!i)continue;e=!0;let a=Ic(xu.get(t),i,n);if(!Bc(xu.get(t),a))continue;xu.set(t,a),bu.set(t,{activeSeconds:n.activeSeconds,seedingSeconds:n.seedingSeconds});let o=wu(n),s=Rc(Cu.get(t),Su.get(t)??o,o);Cu.set(t,s),Su.set(t,o),$(r,{activeSeconds:a.activeSeconds,seedingSeconds:a.seedingSeconds,downloaded:s.downloaded,uploaded:s.uploaded,wasted:s.wasted},!0).catch(()=>{})}e&&Date.now()-yu>=3e5&&(yu=Date.now(),Xl().then(e=>Q({type:`list`,list:e})).catch(()=>{}))},15e3),setInterval(()=>{ud()},1e4),ud(),setTimeout(()=>{cd(),setInterval(()=>{cd()},6e5)},6e4),self.addEventListener(`online`,()=>Z.retryNow(Date.now()))},fd=async(e,t)=>{try{if(t.type===`add-magnet`){let n=lc(t.magnet),r=n?J.find(e=>Y.get(e)===n):void 0;if(r!==void 0)n&&!t.ephemeral?(eu.delete(r),fu(r),await $(n,{ephemeral:!1,lastUsedAt:Date.now()})):Ql(r),Q({type:`added`,handle:r,magnet:Rl.get(r)||t.magnet});else{let r=n?(await Xl()).find(e=>e.infoHash===n):void 0,i=t.savePath||r?.savePath||cl(n),a=ul(r,t.ephemeral===!0),o=e.addMagnet(t.magnet,i);if(Kl(o)){Q({type:`add-failed`,message:`That is not a valid magnet link`});return}uu(o,t.magnet,n,i,a),mu.set(o,{wanted:r?.wantedFiles,firstLast:r?.firstLast}),t.hold===!0&&pu.add(o),Ou(o,{down:r?.downloadLimit,up:r?.uploadLimit}),xu.set(o,{activeSeconds:r?.activeSeconds??0,seedingSeconds:r?.seedingSeconds??0}),Cu.set(o,Tu(r)),Z.hold(o,Date.now());let s=Date.now();t.paused===!0&&Vu(o),n&&await Zl({infoHash:n,magnet:t.magnet,savePath:i,addedAt:s,lastUsedAt:s,ephemeral:a,started:!0,paused:t.paused===!0}),Q({type:`added`,handle:o,magnet:t.magnet}),ud()}}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 Fs(Ml(n),i);let a=nd(e,{infoHash:n,magnet:t.magnet,bytes:i,handles:r,paused:!1});if(a===null){await Ls(Ml(n)).catch(()=>{}),Q({type:`add-failed`,message:`The engine refused the torrent that was just built`});return}let o=Date.now();await Zl({infoHash:n,magnet:t.magnet,savePath:vl(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,...fl({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:Rl.get(i[0])??``});return}let a=await Ps(Ml(n));if(!a?.byteLength){Q({type:`add-failed`,message:`The torrent this was built from is no longer stored`});return}let o=(await Xl()).find(e=>e.infoHash===n),s=nd(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}xu.set(s,{activeSeconds:o?.activeSeconds??0,seedingSeconds:o?.seedingSeconds??0}),Cu.set(s,Tu(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(Kl(i)){Q({type:`add-failed`,message:`That file is not a valid .torrent`});return}uu(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),du(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(`&`);uu(i,s,a,n),await Fs(Ml(a),r);let c=Date.now();t.paused===!0&&Vu(i);let l=t.saveTo===`browser`||t.saveTo===`folder`?{saveTo:t.saveTo}:{};await Zl({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}:{}}),od.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(fu(t.handle),nu.set(t.handle,Date.now()),X.has(t.handle)&&!Wu(t.handle,t.fileIndex,t.offset,t.len)){Q({type:`read-error`,id:t.id,error:`torrent paused`});return}if(t.prioritize!==!1)qu(t.viewer,t.handle,t.fileIndex,t.offset,t.len);else if(!Wu(t.handle,t.fileIndex,t.offset,t.len)){Q({type:`read-error`,id:t.id,error:`not downloaded`});return}let n=ju.get(t.handle);n||ju.set(t.handle,n=new Set),n.add(t.id);try{for(let r=0;;r++)try{let r=t.viewer?Iu.get(t.handle)?.get(t.viewer)?.bulk===!0:!1,i=await e.read(t.handle,t.fileIndex,t.offset,t.len,{timeoutMs:Au,...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=Gu(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)*Au,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?Iu.get(t.handle)?.get(t.viewer):void 0;t.prioritize!==!1&&t.viewer&&o&&!o.held&&Hu(t.viewer,t.handle,t.fileIndex,t.offset)}}finally{n.delete(t.id),J.includes(t.handle)&&nu.set(t.handle,Date.now())}}else if(t.type===`cancel-read`)ju.get(t.handle)?.delete(t.id);else if(t.type===`remove`){let n=Y.get(t.handle);Mu(t.handle,`torrent removed`),e.removeTorrent(t.handle,!!t.deleteFiles),du(t.handle),n&&await $l(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;mu.set(t.handle,{wanted:e,firstLast:n}),Ru(t.handle);let r=Y.get(t.handle);r&&await $(r,{wantedFiles:e,firstLast:n})}else if(t.type===`set-folder`)Fl=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?eu.add(n):(eu.delete(n),fu(n))),await $(t.infoHash,{ephemeral:e})}}else if(t.type===`reserve-storage`)typeof t.infoHash==`string`&&t.infoHash&&(t.on===!1?od.delete(t.infoHash):od.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 td(e,i,n,r)}else if(t.type===`import-list`){let e=Array.isArray(t.list)?t.list:[],n=[],r=!1;await Is(pl,t=>{n=t??[];let i=new Map(n.map(e=>[e.infoHash,e]));for(let t of e){if(!t||typeof t.infoHash!=`string`||!t.magnet)continue;let e=fl(t),a=i.get(t.infoHash);if(a){a.name===void 0&&e.name!==void 0&&(a.name=e.name,r=!0),a.size===void 0&&e.size!==void 0&&(a.size=e.size,r=!0),a.files===void 0&&e.files!==void 0&&(a.files=e.files,r=!0);let n=zc(Tu(a),Tu(t));for(let e of Nc)(a[e]??0)!==n[e]&&(a[e]=n[e],r=!0);continue}let o={infoHash:t.infoHash,magnet:t.magnet,savePath:t.savePath||`/dl`,addedAt:t.addedAt||Date.now(),started:!1,ephemeral:!1,...e,...Tu(t)};n.push(o),i.set(o.infoHash,o),r=!0}return n}),r&&Q({type:`list`,list:n})}else if(t.type===`start`){let n=(await Xl()).find(e=>e.infoHash===t.infoHash);if(n?.saveTo===`source`){Q({type:`add-failed`,message:`This torrent was made from files on this device, so there is nowhere to fetch it from. Create it again from the same files to share it.`});return}if(n){let t=n.savePath||`/dl`,r=await Ps(Ml(n.infoHash)),i=r&&r.byteLength?e.addTorrentFile(r,t):e.addMagnet(n.magnet,t);if(Kl(i)){Q({type:`add-failed`,message:`That torrent could not be read`});return}uu(i,n.magnet,n.infoHash,t,!1),Ou(i,{down:n.downloadLimit,up:n.uploadLimit}),Z.hold(i,Date.now()),Q({type:`state`,torrents:ql(),reachable:e.reachable()}),await Zl({...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&&(Mu(n,`torrent removed`),e.removeTorrent(n,!0),du(n)),await $l(t.infoHash)}}else if(t.type===`clear-list`){for(let t of[...J])Mu(t,`torrent removed`),e.removeTorrent(t,!0),du(t);let t=[];await Is(pl,e=>(t=e??[],[]));for(let e of t)await Ls(ml(e.infoHash)).catch(()=>{}),await Ls(Ml(e.infoHash)).catch(()=>{});Q({type:`list`,list:[]})}else if(t.type===`pause`){X.add(t.handle),tu.delete(t.handle),Ul(t.handle),Z.forget(t.handle),e.pauseTorrent(t.handle),Mu(t.handle,`torrent paused`),Pu(t.handle);let n=Y.get(t.handle);n&&await $(n,{paused:!0})}else if(t.type===`resume`){X.delete(t.handle),tu.delete(t.handle),Wl(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 Ls(ml(n)).catch(()=>{}),Bl.delete(t.handle),Mu(t.handle,`torrent rechecking`),X.delete(t.handle),Vl.delete(t.handle),Hl.delete(t.handle),tu.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=>Pu(e)));else if(t.type===`watch`)t.readLen==null?Hu(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.held===!0,t.bulk===!0?!0:void 0):qu(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.readLen);else if(t.type===`unwatch`)Uu(e=>e===t.viewer);else if(t.type===`set-flags`)e.setFlags(t.handle,t.flags>>>0,t.mask>>>0),Pu(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=kl(t.down)?t.down:void 0,r=kl(t.up)?t.up:void 0;Ou(t.handle,{down:n,up:r})&&e.status(t.handle)&&(_u.delete(t.handle),ku(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`)kl(t.down)&&(hu.down=t.down),kl(t.up)&&(hu.up=t.up),e.setRateLimits({download:hu.down,upload:hu.up}),await Fs(Ol,{...hu});else if(t.type===`inspect`){let e=typeof t.handle==`number`?t.handle:null;e!==iu&&(iu=e,au=0)}else t.type===`unwatch-owner`&&Uu(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)})}},pd=new Set([`read`,`add-torrent-file`]);let md=Promise.resolve();self.addEventListener(`message`,e=>{let t=e.data;if(!t||typeof t!=`object`||typeof t.type!=`string`||!jl.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(pd.has(t.type)){fd(n,t);return}md=md.then(()=>fd(n,t))}),dd().catch(e=>Q({type:Ll?`error`:`fatal`,message:String(e?.stack??e)}));
|
|
23
|
+
var n=Ka(),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)}})),rs=t((e=>{var t=ns().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):``}})),is=t(((e,t)=>{var n=Zo().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})),as=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=is(),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}})),os=t(((e,t)=>{t.exports=function(){throw Error(`Readable.from is not available in the browser`)}})),ss=t(((e,t)=>{t.exports=E;var n;E.ReadableState=T,Va().EventEmitter;var r=function(e,t){return e.listeners(t).length},i=Ua(),a=Ka().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=Jo(),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=Yo(),f=Xo(),p=Qo().getHighWaterMark,m=Zo().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;Ha()(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||=ts(),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||=rs().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=ts(),!(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?!1: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||=rs().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?ae(this):M(this),null;if(e=j(e,t),e===0&&t.ended)return t.length===0&&ae(this),null;var r=t.needReadable;u(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,u(`length less than watermark`,r)),t.ended||t.reading?(r=!1,u(`reading or ended`,r)):r&&(u(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=j(n,t)));var i=e>0?ie(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&ae(this)),i!==null&&this.emit(`data`,i),i};function 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,re(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);break}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&&B(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,re(e))}}E.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=B(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`),re(e),t.flowing&&!t.reading&&e.read(0)}E.prototype.pause=function(){return u(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(u(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function re(e){var t=e._readableState;for(u(`flow`,t.flowing);t.flowing&&e.read()!==null;);}E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(u(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){u(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(!n.objectMode&&(!i||!i.length)||t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<C.length;a++)e.on(C[a],this.emit.bind(this,C[a]));return this._read=function(t){u(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(E.prototype[Symbol.asyncIterator]=function(){return b===void 0&&(b=as()),b(this)}),Object.defineProperty(E.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=ie,Object.defineProperty(E.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function ie(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function ae(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(oe,t,e))}function oe(e,t){if(u(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(E.from=function(e,t){return x===void 0&&(x=os()),x(E,e,t)});function B(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),cs=t(((e,t)=>{t.exports=l;var n=Zo().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=ts();Ha()(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)}})),ls=t(((e,t)=>{t.exports=r;var n=cs();Ha()(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)}})),us=t(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=Zo().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=is()),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})),ds=t(((e,t)=>{t.exports=r;var n=Va().EventEmitter;Ha()(r,n),r.Readable=ss(),r.Writable=es(),r.Duplex=ts(),r.Transform=cs(),r.PassThrough=ls(),r.finished=is(),r.pipeline=us(),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}}))(),fs=Va(),ps=class extends ds.Stream.Duplex{_localAddress;_remoteAddress;_webVPNTcpSocketPromise;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){if(this._busyRelease??=Ba(`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._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},{...e,reader:t,writer:n}}).catch(e=>{this.emit(`error`,e)}),!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);return 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(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=_(...e),n=this.__webvpn_tcp_socket_init__(La.then(e=>e.cloud.webvpn.tcpSocket({remoteAddress:t.host??`localhost`,remotePort:t.port})));return t.callback&&n.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`,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},ms=class extends fs.EventEmitter{_localAddress;_webVPNTcpSocketListenerPromise;constructor(e,t){super(e),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??=Ba(`tcp server`),this._webVPNTcpSocketListenerPromise=e.then(e=>(this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},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=_(...e);this._closeEmitted=!1;let n=e=>{let t=new ps;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=e=>La.then(i=>i.cloud.webvpn.tcpSocketListener({localAddress:e,localPort:t.port,onConnection:n,onClose:r})),a=t.host?i(t.host):i(`::`).catch(()=>i(`0.0.0.0`)),o=this.__webvpn_tcp_socket_listener_init__(a);return t.callback&&o.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](){}},hs=(e,t)=>new ps().connect(e,t),gs=(e,t)=>new ps().connect(e,t),_s=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new ms(e);return t&&n.on(`connection`,t),n},vs={Socket:ps,Server:ms,connect:hs,createConnection:gs,createServer:_s,isIP:g,isIPv4:m,isIPv6:h},ys=n({Server:()=>ms,Socket:()=>ps,_default:()=>vs,connect:()=>hs,createConnection:()=>gs,createServer:()=>_s,default:()=>vs,isIP:()=>g,isIPv4:()=>m,isIPv6:()=>h}),bs=Ka(),xs=class extends fs.EventEmitter{_type;_localAddress;_remoteAddress;_connectedLocally;_connectGeneration=0;_destroyed=!1;_busyRelease;_webVPNUdpSocketPromise;_dataPort;_socketId;_sendQueue=[];_sendQueueBytes=0;_sendFlushScheduled=!1;_peerTailCache=new Map;constructor(e){if(super(e),!e)throw Error(`Missing options`);this._type=e.type,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`,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:p,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=Ts(n)),s+=n.byteLength,d=t.getUint16(s),s+=2}let f=t.getUint32(s);s+=4;try{this.emit(`message`,bs.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 Ss;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let i=d.Address4.isValid(e)?ws(e):Es(e),a=new Uint8Array(1+i.byteLength+2);return a[0]=i.byteLength===4?0:1,a.set(i,1),new DataView(a.buffer).setUint16(1+i.byteLength,t),this._peerTailCache.size>=4096&&this._peerTailCache.clear(),this._peerTailCache.set(n,a),a}_portSend(e,t,n){let r=this._peerTail(t,n),i=new Uint8Array(8+r.byteLength+4+e.byteLength),a=new DataView(i.buffer);a.setUint32(0,i.byteLength-4),a.setUint32(4,this._socketId),i.set(r,8),a.setUint32(8+r.byteLength,e.byteLength),i.set(e,12+r.byteLength),this._sendQueue.push(i),this._sendQueueBytes+=i.byteLength,!this._sendFlushScheduled&&(this._sendFlushScheduled=!0,queueMicrotask(()=>{this._sendFlushScheduled=!1;let e=this._sendQueue,t=this._sendQueueBytes;if(this._sendQueue=[],this._sendQueueBytes=0,!e.length||!this._dataPort)return;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;this._dataPort.postMessage(n.buffer,[n.buffer])}))}addMembership(e,t){if(d.Address4.isValid(e)){let n=ws(e),r=t&&d.Address4.isValid(t)?ws(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(d.Address6.isValid(e)){let t=Es(e);this._setUdpOption({type:7,group:t,ifIndex:0})}else this.emit(`error`,Error(`Invalid multicast address: ${e}`))}address(){if(!this._localAddress)throw Error(`EBADF`);return this._localAddress}bind(...e){let t=v(...e),n=this._type===`udp6`?`::`:`0.0.0.0`,r=this.__webvpn_udp_socket_init__(La.then(e=>e.cloud.webvpn.udpSocket({type:this._type,address:t.address??n,port:t.port,dataPort:!0})));return t.callback&&r.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??=Ba(`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`,bs.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._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(d.Address4.isValid(e)){let n=ws(e),r=t&&d.Address4.isValid(t)?ws(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(d.Address6.isValid(e)){let t=Es(e);this._setUdpOption({type:8,group:t,ifIndex:0})}else this.emit(`error`,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=y(...e),n=Cs(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(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(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||d.Address4.isValid(a)||d.Address6.isValid(a))){this._portSend(r,o?void 0:a,o?void 0:t.port),n?.call(this,null,r.byteLength);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)})}},Ss=new Uint8Array([2]),Cs=e=>{if(typeof e==`string`)return f.encode(e);if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(Array.isArray(e)){let t=e.map(Cs),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)},ws=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)},Ts=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(`:`)}`},Es=e=>{let t=new d.Address6(e).getBitsBase16(0,128).match(/.{2}/g);if(!t||t.length!==16)throw Error(`Invalid IPv6 address: ${e}`);return new Uint8Array(t.map(e=>parseInt(e,16)))},Ds=(e,t)=>{let n=new xs(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},Os={Socket:xs,createSocket:Ds},ks=n({Socket:()=>xs,createSocket:()=>Ds,default:()=>Os});function As(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function js(e,t){let n,r=()=>{if(n)return n;let r=indexedDB.open(e);return r.onupgradeneeded=()=>r.result.createObjectStore(t),n=As(r),n.then(e=>{e.onclose=()=>n=void 0},()=>{}),n};return(e,n)=>r().then(r=>n(r.transaction(t,e).objectStore(t)))}let Ms;function Ns(){return Ms||=js(`keyval-store`,`keyval`),Ms}function Ps(e,t=Ns()){return t(`readonly`,t=>As(t.get(e)))}function Fs(e,t,n=Ns()){return n(`readwrite`,n=>(n.put(t,e),As(n.transaction)))}function Is(e,t,n=Ns()){return n(`readwrite`,n=>new Promise((r,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),r(As(n.transaction))}catch(e){i(e)}}}))}function Ls(e,t=Ns()){return t(`readwrite`,t=>(t.delete(e),As(t.transaction)))}var Rs={checkingFiles:1,downloadingMetadata:2,downloading:3,finished:4,seeding:5,checkingResumeData:7},zs=/^incoming connection from (\S+) \(([^)]*)\)/,Bs=/^successfully listening on \[([^\]]*)\] (\S+)/,Vs=/^listening on .* failed:/,Hs=new TextDecoder,Us=4026531841,Ws=4026531842,Gs=4026531843,Ks=4026531844,qs=4026531845,Js=4026531846,Ys={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},Xs={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},Zs={top:0,up:1,down:2,bottom:3},Qs={tracker:1,dht:2,pex:4,lsd:8,resumeData:16,incoming:32},G={skip:0,low:1,normal:4,top:7},$s=6e4,ec=12,tc=1e3,nc=class{mod;storage;destroyed=!1;fallbackTimer;filesByHandle=new Map;bitfieldByHandle=new Map;statusByHandle=new Map;pieceWaiters=[];resumeByHandle=new Map;resumeWaiters=[];peersByHandle=new Map;trackersByHandle=new Map;peerWaiters=[];trackerWaiters=[];priosByHandle=new Map;deadlineRefs=new Map;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(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(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 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??ec)),s=Math.max(0,Math.floor(n.deadlineStepMs??tc)),c=n.claimedPriority??G.normal,l=n.unclaimedPriority??G.normal,u=new Uint8Array(a).fill(l),d=new Map,f=0;for(let e of t){let t=r.files[e.fileIndex];if(!t||t.size<=0)continue;f++;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++)u[e]=c;let p=Math.min(Math.max(e.offset,0),Math.max(0,t.size-1)),m=Math.min(Math.max(Math.floor((t.offset+p)/i),n),l);for(let e=0;e<o;e++){let t=m+e;if(t>l)break;u[t]=G.top;let n=e*s,r=d.get(t);(r===void 0||n<r)&&d.set(t,n)}}if(!f)return!1;if(this.mod._lt_torrent_clear_piece_deadlines(e),this.prioritizePieces(e,u),n.deadlines!==!1)for(let[t,n]of d)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)*tc,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,Zs[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}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=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??$s;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(Error(`read: aborted`));return}a>0&&(s=setTimeout(()=>l(Error(`read: pieces ${t}-${n} of handle ${e} did not arrive within ${a}ms`)),a)),i&&(c=()=>l(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(){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=[],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===Us)this.decodeTorrentReady(r,a);else if(o===Ws)this.decodeStateUpdate(r,a);else if(o===Ks)this.decodeResumeData(r,a,s);else if(o===qs)this.decodePeers(r,a);else if(o===Js)this.decodeTrackers(r,a);else if(o!==Gs){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()}return i}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=zs.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=Bs.exec(e);if(n){this.reachability.listening[n[1].toLowerCase()]=n[2];return}Vs.test(e)&&this.reachability.listenFailed.length<32&&this.reachability.listenFailed.push(e)}readStr(e,t){let n=e.getUint32(t,!0);return t+=4,[Hs.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):!0)}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?Hs.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!==Rs.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(Error(`read: session destroyed`)),this.pieceWaiters=[],this.resumeWaiters=[],this.deadlineRefs.clear(),this.priosByHandle.clear(),this.mod._lt_session_destroy(),this.mod.__FKN?.teardown?.())}},rc=8e3,ic=e=>{try{e?.close()}catch{}},ac=(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,rc);r.on(`listening`,()=>{i||(i=!0,clearTimeout(o),n(r))}),r.on(`error`,a);try{t(r)}catch{a()}});async function oc(e,t,n=4){try{return await sc(e,t,n)}catch{return null}}async function sc(e,t,n){for(let r=0;r<n;r++){let i=await ac(()=>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 ac(()=>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 cc(e){let t=e.moduleFactory??(await import(`./libtorrent-DS_9Yo8M.js`)).default,n={net:e.net,dgram:e.dgram,storage:e.storage??null,debug:e.debug??!1},r=e.reserveListenPort===!1?Promise.resolve(null):oc(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 nc(i,e)}catch(e){throw a&&!a.adopted&&(ic(a.server),ic(a.udp)),e}return o.setReservedPort(a?a.port:null),o}const lc=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},uc=25e5,dc=e=>{if(!Number.isFinite(e)||e<=0)return 12;let t=Math.ceil(uc/e)+1,n=Math.max(2,Math.floor(8388608/e));return Math.min(Math.max(t,2),n)},fc=e=>dc(e)*Math.max(0,e),pc=e=>Math.max(1,Math.floor(fc(e)/2)),mc=(e,t)=>Math.min(2e3,Math.max(50,Math.round(e/Math.max(t,25e4)*1e3))),hc=(e,t,n,r=uc)=>{let i=e.fileOffset+n+Math.max(0,r-1);return Math.floor(i/e.pieceLength)>=e.p1?!1:Math.abs(n-t)>=pc(e.pieceLength)};var gc=class{storages=new Map;opened=new Map;onNewStorage(e,t,n){let r=(async()=>{let r=await _c(await navigator.storage.getDirectory(),t.replace(/^\/+/,``));this.storages.set(e,{rootDir:r,files:new Map,opening: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 _c(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}const vc=[50,150,400,900,1500],yc=e=>e?.name===`QuotaExceededError`,bc=e=>new Promise(t=>setTimeout(t,e)),xc=()=>{let e=new gc,t=new Set,n=new Map,r=e,i=(e,t)=>{let n=r.storages?.get(e),i=n?.files?.get(t);if(i){n.files.delete(t);try{i.close()}catch{}}},a=async e=>{let t=n.get(e);if(t===void 0)return null;let i=r.storages?.get(t);if(!i?.fileMeta||!i.rootDir)return null;let a=0;for(let e=0;e<i.fileMeta.length;e++){let t=i.files?.get(e);if(t)try{a+=t.getSize();continue}catch{}let n=i.fileMeta[e].path.split(`/`).filter(Boolean),r=n.pop();if(!r)continue;let o=i.rootDir;for(let e of n)o=o?await o.getDirectoryHandle(e).catch(()=>null):null;o&&(a+=await o.getFileHandle(r).then(e=>e.getFile()).then(e=>e.size).catch(()=>0))}return a},o=async(e,n,r,a)=>{let o=a;for(let a of vc){if(yc(o))break;if(i(e,n),await bc(a),t.has(e))throw o;try{return await r()}catch(e){o=e}}throw o},s=(e,t,n)=>{try{let r=n();return r instanceof Promise?r.catch(r=>o(e,t,n,r)):r}catch(r){return o(e,t,n,r)}};return{usageOf:a,onNewStorage:(r,i,a)=>(t.delete(r),n.set(i,r),s(r,-1,()=>e.onNewStorage(r,i,a))),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)=>s(t,n,()=>e.read(t,n,r,i)),write:(t,n,r,i)=>s(t,n,()=>e.write(t,n,r,i)),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)}},Sc=[5e3,15e3,3e4,6e4,12e4,3e5],Cc=1e4,wc=new Set([2,3]),Tc=new Set([1,7]),Ec=e=>!!e&&e.paused&&!e.autoManaged,Dc=()=>{let e=new Map,t=new Map,n=new Map,r=new Map,i=e=>Sc[Math.min(e,Sc.length-1)],a=i=>{e.delete(i),t.delete(i),n.delete(i),r.delete(i)};return{hold:(e,t,n=Cc)=>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(Tc.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`:wc.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+Cc,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)}}},Oc=e=>!(e.flags&Ys.localConnection)||!!(e.source&Qs.incoming),kc=e=>e.flags&Ys.utpSocket?`utp`:`tcp`,Ac={total:0,byTransport:{}},jc=e=>{let t={},n=0;for(let r of e)for(let e of r){if(!Oc(e)||e.connectionType!==0)continue;n+=1;let r=kc(e);t[r]=(t[r]??0)+1}return{total:n,byTransport:t}},Mc={activeSeconds:0,seedingSeconds:0},Nc=[`activeSeconds`,`seedingSeconds`,`downloaded`,`uploaded`,`wasted`],Pc={activeSeconds:0,seedingSeconds:0,downloaded:0,uploaded:0,wasted:0},K=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0,Fc=(e,t)=>({activeSeconds:Math.max(0,K(t.activeSeconds)-K(e.activeSeconds)),seedingSeconds:Math.max(0,K(t.seedingSeconds)-K(e.seedingSeconds))}),Ic=(e,t,n)=>{let r=Fc(t,n);return{activeSeconds:K(e?.activeSeconds)+r.activeSeconds,seedingSeconds:K(e?.seedingSeconds)+r.seedingSeconds}},Lc=(e,t)=>Object.fromEntries(Nc.map(n=>[n,Math.max(0,K(t[n])-K(e[n]))])),Rc=(e,t,n)=>{let r=Lc(t,n);return Object.fromEntries(Nc.map(t=>[t,K(e?.[t])+r[t]]))},zc=(e,t)=>Object.fromEntries(Nc.map(n=>[n,Math.max(K(e?.[n]),K(t?.[n]))])),Bc=(e,t)=>t.activeSeconds-K(e?.activeSeconds)>=30||t.seedingSeconds-K(e?.seedingSeconds)>=30,Vc=e=>!Number.isFinite(e)||e<=0?0:Math.min(1e9,Math.floor(e*.1)),Hc=(e,t)=>!Number.isFinite(e)||e<=0?Math.max(0,t):Math.max(Math.min(.25*e,2e10),Math.max(0,t)),Uc=({usedBytes:e,limitBytes:t})=>!Number.isFinite(t)||t<=0||!Number.isFinite(e)||e<0?!1:t-e<Vc(t),Wc=(e,t)=>e.usedAt-t.usedAt||(e.infoHash<t.infoHash?-1:+(e.infoHash>t.infoHash)),Gc=({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(Wc);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=Vc(t),c=s+Math.max(0,n),l=t-e,u=o(e=>l+a[e]>=c),d=o(e=>l+a[e]>=s),f=u>=0?u:d>=0?d:i.length,p=a[i.length],m=i.reduce((e,t)=>Math.max(e,t.bytesOnDisk),0),h=Hc(t,m),g=o(e=>p-a[e]<=h);return i.slice(0,Math.max(f,g<0?i.length:g)).map(e=>e.infoHash)};var Kc=8,qc=2e4,Jc=e=>typeof e.values==`function`,Yc=async e=>{let t=0,n=0,r=async(e,i)=>{if(!(i>Kc))for await(let a of e.values()){if(++n>qc)return;if(Jc(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}},Xc=(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)},Zc,Qc,$c=(e,t,n)=>{if(e!==void 0)return n!==Qc&&(Zc=void 0),Qc=n,Zc=Zc===void 0?e:Math.min(Zc,e),Math.max(Zc,t??0)},el=async e=>e.persisted?e.persisted().then(e=>e===!0).catch(()=>Qc):void 0,tl={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=>Yc(e)).catch(()=>null):null,el(e)]),i=Xc(t,n);return{...t,usage:i,quota:$c(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 el(e)??null??t},persisted:()=>globalThis.navigator?.storage?.persisted?.()??Promise.resolve(!1),getDirectory:()=>{let e=globalThis.navigator?.storage;return e?.getDirectory?e.getDirectory():Promise.reject(Error(`this browser has no origin private file system`))}};const nl=/^(?:[0-9a-f]{40}|[0-9a-f]{64}|[a-z2-7]{32})$/i,rl=({entries:e,listedHashes:t,claimedNames:n,attributable:r})=>e.filter(({name:e,kind:i})=>n.has(e)?!1:i===`directory`&&nl.test(e)?!t.has(e.toLowerCase()):r).map(({name:e})=>e),il=async e=>{let t=[];for await(let n of e.values())t.push({name:n.name,kind:n.kind});return t},al=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},ol=async(e,t,n)=>{let r=await al(e,t);if(!r)return[];let i=[];for(let e of rl({...n,entries:await il(r)}))try{await r.removeEntry(e,{recursive:!0}),i.push(e)}catch{}return i},sl=async e=>{let t=0;for(let{name:n,kind:r}of await il(e))r!==`file`||!n.startsWith(`.ripple-probe-`)||await e.removeEntry(n).then(()=>!0,()=>!1)&&t++;return t},cl=e=>e?`/dl/`+e:`/dl`,ll=(e,t)=>e===cl(t),ul=(e,t)=>t&&(e?e.ephemeral===!0:!0),dl=(e,t)=>e?{...t,ephemeral:ul(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,fl=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}),pl=`ripple:torrents`,ml=`ripple:removed`,hl=(...e)=>{let t=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}))},gl=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}},_l=(e,t,n)=>{let r=gl(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}},vl=e=>`ripple:resume:`+e,yl=e=>`ripple:thumb:`+e,bl=e=>typeof e.getFile==`function`?e.getFile():Promise.resolve(e),xl=e=>`/native/${e}`,Sl=e=>e===`/native`||!!e?.startsWith(`/native/`),Cl=e=>`/source/${e}`,wl=e=>e===`/source`||!!e?.startsWith(`/source/`),Tl=e=>Sl(e)||wl(e),El=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()},Dl=(e,t,n=()=>null)=>{let r=new Map,i=new Map,a=e=>{let n=t();if(!n)throw Error(`hybrid storage: no folder granted, cannot ${e}`);return n},o=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?bl(n):null};return{usageOf:async t=>Tl(t)?0:e.usageOf(t),onNewStorage:(t,a,o)=>{if(wl(a)){i.set(t,{savePath:a,files:o,handles:n(a)});return}if(!Sl(a))return e.onNewStorage(t,a,o);r.set(t,{savePath:a,files:o})},onRemoveStorage:t=>{if(!i.delete(t)&&!r.delete(t))return e.onRemoveStorage(t)},read:(t,n,s,c)=>{let l=i.get(t);if(l)return(async()=>{let e=await o(l,n);if(!e)return new Uint8Array(c);let t=await e.slice(s,s+c).arrayBuffer();if(t.byteLength<c)throw Error(`hybrid storage: source file ${n} of ${l.savePath} ended early, wanted ${c} at ${s}, got ${t.byteLength}`);return new Uint8Array(t)})();let u=r.get(t);if(!u)return e.read(t,n,s,c);let d=u.files[n];if(!d)throw Error(`hybrid storage: no file ${n} in ${u.savePath}`);return(async()=>{let e=await(await El(a(`read`),d.path)).slice(s,s+c).arrayBuffer();if(e.byteLength<c)throw Error(`hybrid storage: ${d.path} ended early, wanted ${c} at ${s}, got ${e.byteLength}`);return new Uint8Array(e)})()},write:(t,n,a,o)=>{let s=i.get(t);if(s)throw Error(`hybrid storage: ${s.savePath} is somebody's own files, refusing a write of ${o.length} at ${a} in file ${n}`);let c=r.get(t);if(!c)return e.write(t,n,a,o);throw Error(`hybrid storage: ${c.savePath} is read only, refusing a write of ${o.length} at ${a} in file ${n}`)},check:async t=>{if(i.get(t))return 2;let n=r.get(t);if(!n)return e.check(t);try{let e=a(`check`);for(let t of n.files){let n=await El(e,t.path).catch(()=>null);if(n&&n.size>0)return 2}return 0}catch{return 2}},deleteFiles:async(t,n)=>{if(!i.has(t)&&!r.get(t))return e.deleteFiles(t,n)},release:async t=>{!r.has(t)&&!i.has(t)&&await e.release(t)},stop:async t=>{!r.has(t)&&!i.has(t)&&await e.stop(t)}}},Ol=(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))],kl=({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]=Ol(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]=Ol(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},Al=({wanted:e,firstLast:t})=>e===void 0&&!t,jl=e=>wl(e)?`source`:Sl(e)?`folder`:`browser`,Ml=(e,t)=>{if(e===`source`){if(!t)throw Error(`a source-backed torrent needs its infohash to name its save path`);return Cl(t)}return e===`folder`?t?xl(t):`/dl`:cl(t)},Nl=`ripple:rate-limits`,Pl=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,Fl=e=>{let t=e??{};return{down:Pl(t.down)?t.down:0,up:Pl(t.up)?t.up:0}},Il=new Set(`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(`.`)),Ll=e=>`ripple:torrent:`+e,Rl=e=>`ripple:source:`+e;let q=null,zl=null,Bl=null;const Vl=new Map;let Hl=!1;const J=[],Ul=new Map,Y=new Map,Wl=new Map,Gl=new Map,X=new Set,Kl=new Set,ql=new Set,Jl=e=>{ql.delete(e),Kl.add(e)},Yl=e=>{Kl.delete(e),ql.add(e)},Xl=new Map,Z=Dc(),Zl=e=>e>=4294967040,Q=(e,t)=>self.postMessage(e,t??[]),Ql=()=>J.map(e=>{let t=q.bitfield(e);return{handle:e,magnet:Ul.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),uptime:$l(e),sessionUptime:eu(e),totals:Mu(e)}}),$l=e=>{let t=q?.status(e),n=Eu.get(e);return!t||!n?Du.get(e)??Mc:Ic(Du.get(e),n,t)},eu=e=>{let t=q?.status(e),n=Eu.get(e);return t&&n?Fc(n,t):Mc},tu=async()=>await Ps(`ripple:torrents`)??[],nu=async e=>{let t=[];await Is(pl,n=>{t=n??[];let r=t.findIndex(t=>t.infoHash===e.infoHash),i=dl(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 Is(pl,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})},ru=e=>{let t=Y.get(e);t&&$(t,{lastUsedAt:Date.now()},!0).catch(()=>{})},iu=async e=>{await Ls(vl(e)).catch(()=>{}),await Ls(Ll(e)).catch(()=>{}),await Ls(Rl(e)).catch(()=>{}),await Ls(yl(e)).catch(()=>{})},au=async e=>{let t=[];await Is(pl,n=>t=(n??[]).filter(t=>t.infoHash!==e)),await Is(ml,t=>hl(t,[{infoHash:e,removedAt:Date.now()}])),await iu(e),Q({type:`list`,list:t})},ou=new Set,su=new Set,cu=new Map,lu=new Set;let uu=null,du=0,fu=0,pu=Ac;const mu=e=>{let t=uu;return t==null||!J.includes(t)?null:(q.peers(t),e-du>=5e3&&(du=e,q.trackers(t)),{handle:t,peers:q.lastPeers(t),trackers:q.lastTrackers(t)})},hu=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)]},gu=(e,t,n,r,i=!1)=>{J.includes(e)||J.push(e),Ul.set(e,t),n&&(Y.set(e,n),lu.add(e)),Wl.set(e,r),i?ou.add(e):ou.delete(e)},_u=e=>{let t=J.indexOf(e);t>=0&&J.splice(t,1),Ul.delete(e),Y.delete(e),Wl.delete(e),Gl.delete(e),X.delete(e),Z.forget(e),zu.delete(e),Lu.delete(e),Kl.delete(e),ql.delete(e),Xl.delete(e),Hu.delete(e),Uu.delete(e),yu.delete(e),bu.delete(e),Su.delete(e),Cu.delete(e),wu.delete(e),Eu.delete(e),Du.delete(e),Ou.delete(e),ku.delete(e),ou.delete(e),su.delete(e),cu.delete(e),lu.delete(e)},vu=e=>{su.delete(e)&&(Yl(e),q?.resumeTorrent(e),Z.hold(e,Date.now()))},yu=new Set,bu=new Map;let xu={down:0,up:0};const Su=new Map,Cu=new Set,wu=new Map;let Tu=0;const Eu=new Map,Du=new Map,Ou=new Map,ku=new Map,Au=e=>({activeSeconds:e.activeSeconds,seedingSeconds:e.seedingSeconds,downloaded:e.allTimeDownload,uploaded:e.allTimeUpload,wasted:e.wasted}),ju=e=>({activeSeconds:e?.activeSeconds??0,seedingSeconds:e?.seedingSeconds??0,downloaded:e?.downloaded??0,uploaded:e?.uploaded??0,wasted:e?.wasted??0}),Mu=e=>{let t=q?.status(e),n=Ou.get(e);return!t||!n?ku.get(e)??Pc:Rc(ku.get(e),n,Au(t))},Nu=(e,t,n)=>{let r=wu.get(e);wu.set(e,r?{flags:r.flags&~n|t&n,mask:r.mask|n}:{flags:t&n,mask:n})},Pu=(e,t)=>{let n={...Su.get(e)};return Pl(t.down)&&(n.down=t.down),Pl(t.up)&&(n.up=t.up),!Pl(n.down)&&!Pl(n.up)?!1:(Su.set(e,n),Cu.add(e),!0)},Fu=e=>{let t=Su.get(e);!q||!t||(Pl(t.down)&&q.setDownloadLimit(e,t.down),Pl(t.up)&&q.setUploadLimit(e,t.up))},Iu=6e3,Lu=new Map,Ru=(e,t)=>{let n=Lu.get(e);if(n?.size){for(let e of n)Q({type:`read-error`,id:e,error:t});n.clear()}},zu=new Set,Bu=async e=>{let t=Y.get(e);if(!t||!q||zu.has(e)||wl(Wl.get(e)))return!1;zu.add(e);try{let n=await q.saveResumeData(e);return J.includes(e)?(await Fs(vl(t),n),!0):!1}catch(e){return console.error(`[worker] saving resume data failed`,String(e)),!1}finally{zu.delete(e)}},Vu=(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}},Hu=new Map,Uu=new Set,Wu=e=>{let t=bu.get(e);if(!q||!t||Al(t))return;let n=q.files(e);n&&q.prioritizePieces(e,kl({files:n.files,pieceLength:n.pieceLength,numPieces:Math.ceil(n.totalSize/n.pieceLength),wanted:t.wanted,firstLast:t.firstLast}))},Gu=e=>{let t=Hu.get(e);return t?[...t.values()].filter(e=>!e.held):[]},Ku=e=>{if(!q)return;if(!J.includes(e)){Hu.delete(e),Uu.delete(e);return}let t=Gu(e);if(!t.length){if(!q.files(e)){Uu.add(e);return}Uu.delete(e),q.clearStreamWindow(e),Wu(e),ou.has(e)&&!X.has(e)&&!su.has(e)&&(su.add(e),Jl(e),q.pauseTorrent(e),Bu(e));return}vu(e);let n=q.files(e);if(!n){Uu.add(e);return}let r=t.map(({fileIndex:e,fromOffset:t})=>({fileIndex:e,offset:t})),i=t.some(e=>!e.bulk);q.setStreamWindow(e,r,{unclaimedPriority:G.skip,windowPieces:dc(n.pieceLength),deadlineStepMs:mc(n.pieceLength,q.status(e)?.downloadRate||3e6),deadlines:i})?Uu.delete(e):Uu.add(e)},qu=e=>{X.add(e),su.delete(e),Jl(e),Z.forget(e),q?.pauseTorrent(e)},Ju=(e,t,n,r,i=!1,a)=>{if(!J.includes(t))return;let o=Hu.get(t),s=!o?.size;o||Hu.set(t,o=new Map);let c=a??o.get(e)?.bulk;o.set(e,{fileIndex:n,fromOffset:r,...i?{held:i}:{},...c?{bulk:c}:{}}),s&&ru(t),Ku(t)},Yu=e=>{for(let[t,n]of Hu){let r=!1;for(let t of[...n.keys()])e(t)&&(n.delete(t),r=!0);n.size||(Hu.delete(t),r&&ru(t)),r&&Ku(t)}},Xu=(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},Zu=(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},Qu=()=>{if(!q)return 0;let e=0;for(let[t,n]of Hu){if(!n.size||!J.includes(t))continue;let r=q.files(t),i=q.bitfield(t);if(!r)continue;if(!i){for(let{fileIndex:t}of n.values())e+=r.files[t]?.size??0;continue}let a=new Set;for(let{fileIndex:e}of n.values()){let n=Vu(t,e);if(n)for(let e=n.p0;e<=n.p1;e++)(i.pieces[e>>3]??0)&128>>(e&7)||a.add(e)}e+=a.size*r.pieceLength}return e},$u=(e,t,n,r,i)=>{if(!e||!J.includes(t))return;let a=Hu.get(t)?.get(e);if(!a||a.held||a.fileIndex!==n){Ju(e,t,n,r);return}let o=Vu(t,n);o&&hc({fileOffset:o.file.offset,pieceLength:o.pieceLength,p1:o.p1},a.fromOffset,r,i)&&Ju(e,t,n,r)},ed=async e=>{let t=e.filter(e=>!Tl(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}},td=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}},nd=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}),rd=async()=>{try{let{usage:e,quota:t}=await tl.estimate();return!t||e===void 0?null:{usedBytes:e,limitBytes:t}}catch{return null}},id=async e=>{for(let t=0;t<4e3;t+=250){await new Promise(e=>setTimeout(e,250));let t=await rd();if(!t||t.usedBytes<e)return t}return rd()},ad=async(e,t,n,r,i={})=>{Ru(t,r),e.removeTorrent(t,!0),_u(t),await Ls(vl(n)).catch(()=>{}),await $(n,{started:!1,paused:!1,...i})},od=(e,t,n)=>ad(e,t,n,`torrent removed to make room`),sd=async(e,t,n,r)=>{let i=jl(Wl.get(t));if(i===r)return;let a=Ul.get(t)??``,o=Ml(r,n),s=X.has(t),c=ou.has(t);Ru(t,`files moved`),e.removeTorrent(t,i===`browser`),_u(t),await Ls(vl(n)).catch(()=>{});let l=e.addMagnet(a,o);if(Zl(l)){Q({type:`add-failed`,message:`Moving the files left the torrent unaddable`}),await $(n,{savePath:o,saveTo:r,started:!1});return}gu(l,a,n,o,c),r===`folder`&&Nu(l,Xs.uploadMode,Xs.uploadMode),s?(X.add(l),Jl(l)):Yl(l),Z.hold(l,Date.now()),await $(n,{savePath:o,saveTo:r,started:!0})},cd=(e,{infoHash:t,magnet:n,bytes:r,handles:i,paused:a})=>{let o=Cl(t);Vl.set(o,i);let s=e.addTorrentFile(r,o);return Zl(s)?(Vl.delete(o),null):(gu(s,n,t,o,!1),Nu(s,Xs.uploadMode,Xs.uploadMode),a&&(X.add(s),Jl(s)),Z.hold(s,Date.now()),s)},ld=async(e,t)=>{let n=new Map(e.map(e=>[e.infoHash,e])),r=[];for(let e of[...J]){let i=Y.get(e);if(!i)continue;let a=n.get(i);if(!a?.ephemeral||!ll(a.savePath,i)||Hu.get(e)?.size||Lu.get(e)?.size||t-(cu.get(e)??0)<6e4)continue;let o=a.lastUsedAt??a.addedAt;if(t-o<15e3)continue;let s=await zl?.usageOf(a.savePath)??0;s<=0||r.push({infoHash:i,usedAt:o,bytesOnDisk:s})}return r};let ud=!1;const dd=e=>{let t=Uc(e);t!==ud&&(ud=t,Q({type:`storage-full`,full:t,usedBytes:e.usedBytes,limitBytes:e.limitBytes}))},fd=new Set;let pd=!1;const md=async()=>{if(!q||pd)return 0;pd=!0;try{let e=await tu(),t=new Set(e.map(e=>e.infoHash.toLowerCase()));for(let e of fd)t.add(e.toLowerCase());let n=new Set,r=!0;for(let e of J){let i=Y.get(e);if(i&&t.add(i.toLowerCase()),(Wl.get(e)??`/dl`)!==`/dl`)continue;let a=hu(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(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 ol(i,`/dl`,{listedHashes:t,claimedNames:n,attributable:r});return await sl(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{pd=!1}};let hd=!1;const gd=async()=>{let e=q;if(!e||hd)return;hd=!0;let t=null;try{let n=await rd();if(!n)return;t=n;let r=Qu(),i=await ld(await tu(),Date.now());for(;i.length;){let[a]=Gc({...n,pendingBytes:r,candidates:i});if(!a)break;i=i.filter(e=>e.infoHash!==a);let o=J.find(e=>Y.get(e)===a);if(o===void 0||Hu.get(o)?.size||Lu.get(o)?.size)continue;let s=n.usedBytes;t=null,await od(e,o,a);let c=await id(s);if(!c)return;n=c,t=c}Uc(n)&&await md()&&(n=await id(n.usedBytes)??n),t=n}catch(e){console.error(`[worker] storage budget pass failed`,String(e))}finally{hd=!1,t&&dd(t)}},_d=async()=>{let e=console.error.bind(console);if(console.error=(...t)=>{e(...t);try{Q({type:`worker-error`,args:t.map(String)})}catch{}},!await td()){Q({type:`storage-unavailable`});return}tu().then(e=>{e.length&&Q({type:`list`,list:e})}).catch(()=>{});let t=Promise.race([Ps(Nl).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]);zl=Dl(xc(),()=>Bl,e=>Vl.get(e)??null),q=await cc({net:ys,dgram:ks,storage:zl,utpReceiveBufferBytes:4194304});for(let e=0;e<30;e++)q.tick();xu=Fl(await t),q.setRateLimits({download:xu.down,upload:xu.up});try{let e=await tu(),t=!await ed(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 Ps(vl(r.infoHash)),a=await Ps(Ll(r.infoHash));if(t&&i&&i.byteLength){await Ls(vl(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);Zl(o)||(gu(o,r.magnet,r.infoHash,e,r.ephemeral===!0),bu.set(o,{wanted:r.wantedFiles,firstLast:r.firstLast}),yu.add(o),Pu(o,{down:r.downloadLimit,up:r.uploadLimit}),Du.set(o,{activeSeconds:r.activeSeconds??0,seedingSeconds:r.seedingSeconds??0}),ku.set(o,ju(r)),r.paused?(X.add(o),Jl(o)):Yl(o),Z.hold(o,Date.now()))}n&&await Fs(pl,e)}catch(e){console.error(`[worker] restore failed`,e)}Q({type:`ready`}),Hl=!0,Q({type:`list`,list:await tu().catch(()=>[])}),Q({type:`state`,torrents:Ql(),reachable:q.reachable(),inboundNow:pu,rateLimits:{...xu}}),setInterval(()=>{if(!q)return;let e=Date.now();q.popAlerts();for(let e of J)q.postStatus(e);for(let e of[...yu])q.files(e)&&(yu.delete(e),Gu(e).length||Ku(e));for(let e of[...Uu])Ku(e);for(let e of[...Cu])q.status(e)&&(Cu.delete(e),Fu(e));for(let e of J){if(Eu.has(e))continue;let t=q.status(e);t&&(Eu.set(e,{activeSeconds:t.activeSeconds,seedingSeconds:t.seedingSeconds}),Ou.set(e,Au(t)))}for(let[e,t]of[...wu])q.status(e)&&(wu.delete(e),q.setFlags(e,t.flags>>>0,t.mask>>>0));for(let e of[...lu]){let[t]=hu(e);if(!t)continue;lu.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 Kl){let t=q.status(e);!t||Tc.has(t.state)||(Ec(t)?Kl.delete(e):q.pauseTorrent(e))}for(let e of ql){if(X.has(e)||su.has(e)){ql.delete(e);continue}let t=q.status(e);if(!(!t||Tc.has(t.state))){if(!t.paused){ql.delete(e);continue}if(t.autoManaged||t.errorCode){ql.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&&nd(n),X.has(t)||su.has(t),e)}for(let{handle:t,reason:n}of Z.due(e))n===`stalled`&&q.pauseTorrent(t),q.resumeTorrent(t);if(e-fu>=2e3){fu=e;for(let e of J)q.peers(e)}pu=jc(J.map(e=>q.lastPeers(e))),Q({type:`state`,torrents:Ql(),reachable:q.reachable(),inboundNow:pu,detail:mu(e),rateLimits:{...xu}});for(let t of J){let n=q.status(t);if(!n||n.state!==4&&n.state!==5||Gl.get(t)===n.paused||zu.has(t))continue;let r=Xl.get(t);if(r&&e<r.at)continue;let i=n.paused;Bu(t).then(e=>{if(e){Gl.set(t,i),Xl.delete(t);return}let n=(Xl.get(t)?.tries??0)+1;Xl.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&&Bu(e)}let e=!1;for(let t of J){let n=q.status(t),r=Y.get(t),i=Eu.get(t);if(!n||!r||!i)continue;e=!0;let a=Ic(Du.get(t),i,n);if(!Bc(Du.get(t),a))continue;Du.set(t,a),Eu.set(t,{activeSeconds:n.activeSeconds,seedingSeconds:n.seedingSeconds});let o=Au(n),s=Rc(ku.get(t),Ou.get(t)??o,o);ku.set(t,s),Ou.set(t,o),$(r,{activeSeconds:a.activeSeconds,seedingSeconds:a.seedingSeconds,downloaded:s.downloaded,uploaded:s.uploaded,wasted:s.wasted},!0).catch(()=>{})}e&&Date.now()-Tu>=3e5&&(Tu=Date.now(),tu().then(e=>Q({type:`list`,list:e})).catch(()=>{}))},15e3),setInterval(()=>{gd()},1e4),gd(),setTimeout(()=>{md(),setInterval(()=>{md()},6e5)},6e4),self.addEventListener(`online`,()=>Z.retryNow(Date.now()))},vd=async(e,t)=>{try{if(t.type===`add-magnet`){let n=lc(t.magnet),r=n?J.find(e=>Y.get(e)===n):void 0;if(r!==void 0)n&&!t.ephemeral?(ou.delete(r),vu(r),await $(n,{ephemeral:!1,lastUsedAt:Date.now()})):ru(r),Q({type:`added`,handle:r,magnet:Ul.get(r)||t.magnet});else{let r=n?(await tu()).find(e=>e.infoHash===n):void 0,i=t.savePath||r?.savePath||cl(n),a=ul(r,t.ephemeral===!0),o=e.addMagnet(t.magnet,i);if(Zl(o)){Q({type:`add-failed`,message:`That is not a valid magnet link`});return}gu(o,t.magnet,n,i,a),bu.set(o,{wanted:r?.wantedFiles,firstLast:r?.firstLast}),t.hold===!0&&yu.add(o),Pu(o,{down:r?.downloadLimit,up:r?.uploadLimit}),Du.set(o,{activeSeconds:r?.activeSeconds??0,seedingSeconds:r?.seedingSeconds??0}),ku.set(o,ju(r)),Z.hold(o,Date.now());let s=Date.now();t.paused===!0&&qu(o),n&&await nu({infoHash:n,magnet:t.magnet,savePath:i,addedAt:s,lastUsedAt:s,ephemeral:a,started:!0,paused:t.paused===!0}),Q({type:`added`,handle:o,magnet:t.magnet}),gd()}}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 Fs(Ll(n),i);let a=cd(e,{infoHash:n,magnet:t.magnet,bytes:i,handles:r,paused:!1});if(a===null){await Ls(Ll(n)).catch(()=>{}),Q({type:`add-failed`,message:`The engine refused the torrent that was just built`});return}let o=Date.now();await nu({infoHash:n,magnet:t.magnet,savePath:Cl(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,...fl({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:Ul.get(i[0])??``});return}let a=await Ps(Ll(n));if(!a?.byteLength){Q({type:`add-failed`,message:`The torrent this was built from is no longer stored`});return}let o=(await tu()).find(e=>e.infoHash===n),s=cd(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}Du.set(s,{activeSeconds:o?.activeSeconds??0,seedingSeconds:o?.seedingSeconds??0}),ku.set(s,ju(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(Zl(i)){Q({type:`add-failed`,message:`That file is not a valid .torrent`});return}gu(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),_u(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(`&`);gu(i,s,a,n),await Fs(Ll(a),r);let c=Date.now();t.paused===!0&&qu(i);let l=t.saveTo===`browser`||t.saveTo===`folder`?{saveTo:t.saveTo}:{};await nu({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}:{}}),fd.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(vu(t.handle),cu.set(t.handle,Date.now()),X.has(t.handle)&&!Xu(t.handle,t.fileIndex,t.offset,t.len)){Q({type:`read-error`,id:t.id,error:`torrent paused`});return}if(t.prioritize!==!1)$u(t.viewer,t.handle,t.fileIndex,t.offset,t.len);else if(!Xu(t.handle,t.fileIndex,t.offset,t.len)){Q({type:`read-error`,id:t.id,error:`not downloaded`});return}let n=Lu.get(t.handle);n||Lu.set(t.handle,n=new Set),n.add(t.id);try{for(let r=0;;r++)try{let r=t.viewer?Hu.get(t.handle)?.get(t.viewer)?.bulk===!0:!1,i=await e.read(t.handle,t.fileIndex,t.offset,t.len,{timeoutMs:Iu,...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=Zu(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)*Iu,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?Hu.get(t.handle)?.get(t.viewer):void 0;t.prioritize!==!1&&t.viewer&&o&&!o.held&&Ju(t.viewer,t.handle,t.fileIndex,t.offset)}}finally{n.delete(t.id),J.includes(t.handle)&&cu.set(t.handle,Date.now())}}else if(t.type===`cancel-read`)Lu.get(t.handle)?.delete(t.id);else if(t.type===`remove`){let n=Y.get(t.handle);Ru(t.handle,`torrent removed`),e.removeTorrent(t.handle,!!t.deleteFiles),_u(t.handle),n&&await au(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;bu.set(t.handle,{wanted:e,firstLast:n}),Wu(t.handle);let r=Y.get(t.handle);r&&await $(r,{wantedFiles:e,firstLast:n})}else if(t.type===`set-folder`)Bl=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?ou.add(n):(ou.delete(n),vu(n))),await $(t.infoHash,{ephemeral:e})}}else if(t.type===`reserve-storage`)typeof t.infoHash==`string`&&t.infoHash&&(t.on===!1?fd.delete(t.infoHash):fd.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 sd(e,i,n,r)}else if(t.type===`import-list`){let e=[];await Is(ml,n=>e=hl(n,t.removed));let n=[],r=[],i=!1;await Is(pl,a=>{let o=_l(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=fl(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=zc(ju(r),ju(e));for(let e of Nc)(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,...ju(e)};n.push(a),s.set(a.infoHash,a),i=!0}return n});for(let e of r)await iu(e.infoHash);i&&Q({type:`list`,list:n})}else if(t.type===`start`){let n=(await tu()).find(e=>e.infoHash===t.infoHash);if(n?.saveTo===`source`){Q({type:`add-failed`,message:`This torrent was made from files on this device, so there is nowhere to fetch it from. Create it again from the same files to share it.`});return}if(n){let t=n.savePath||`/dl`,r=await Ps(Ll(n.infoHash)),i=r&&r.byteLength?e.addTorrentFile(r,t):e.addMagnet(n.magnet,t);if(Zl(i)){Q({type:`add-failed`,message:`That torrent could not be read`});return}gu(i,n.magnet,n.infoHash,t,!1),Pu(i,{down:n.downloadLimit,up:n.uploadLimit}),Z.hold(i,Date.now()),Q({type:`state`,torrents:Ql(),reachable:e.reachable()}),await nu({...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&&(Ru(n,`torrent removed`),e.removeTorrent(n,!0),_u(n)),await au(t.infoHash)}}else if(t.type===`clear-list`){for(let t of[...J])Ru(t,`torrent removed`),e.removeTorrent(t,!0),_u(t);let t=[];await Is(pl,e=>(t=e??[],[])),await Ls(ml).catch(()=>{});for(let e of t)await Ls(vl(e.infoHash)).catch(()=>{}),await Ls(Ll(e.infoHash)).catch(()=>{});Q({type:`list`,list:[]})}else if(t.type===`pause`){X.add(t.handle),su.delete(t.handle),Jl(t.handle),Z.forget(t.handle),e.pauseTorrent(t.handle),Ru(t.handle,`torrent paused`),Bu(t.handle);let n=Y.get(t.handle);n&&await $(n,{paused:!0})}else if(t.type===`resume`){X.delete(t.handle),su.delete(t.handle),Yl(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 Ls(vl(n)).catch(()=>{}),Gl.delete(t.handle),Ru(t.handle,`torrent rechecking`),X.delete(t.handle),Kl.delete(t.handle),ql.delete(t.handle),su.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=>Bu(e)));else if(t.type===`watch`)t.readLen==null?Ju(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.held===!0,t.bulk===!0?!0:void 0):$u(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.readLen);else if(t.type===`unwatch`)Yu(e=>e===t.viewer);else if(t.type===`set-flags`)e.setFlags(t.handle,t.flags>>>0,t.mask>>>0),Bu(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=Pl(t.down)?t.down:void 0,r=Pl(t.up)?t.up:void 0;Pu(t.handle,{down:n,up:r})&&e.status(t.handle)&&(Cu.delete(t.handle),Fu(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`)Pl(t.down)&&(xu.down=t.down),Pl(t.up)&&(xu.up=t.up),e.setRateLimits({download:xu.down,upload:xu.up}),await Fs(Nl,{...xu});else if(t.type===`inspect`){let e=typeof t.handle==`number`?t.handle:null;e!==uu&&(uu=e,du=0)}else t.type===`unwatch-owner`&&Yu(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)})}},yd=new Set([`read`,`add-torrent-file`]);let bd=Promise.resolve();self.addEventListener(`message`,e=>{let t=e.data;if(!t||typeof t!=`object`||typeof t.type!=`string`||!Il.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(yd.has(t.type)){vd(n,t);return}bd=bd.then(()=>vd(n,t))}),_d().catch(e=>Q({type:Hl?`error`:`fatal`,message:String(e?.stack??e)}));
|