@banou/ripple 0.0.18 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,4 +20,4 @@ var t=co(),n=lo(),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=us();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=ds();function A(e){return Object.prototype.toString.call(e)}function ee(e){return e<10?`0`+e.toString(10):e.toString(10)}var j=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function te(){var e=/* @__PURE__ */ new Date,t=[ee(e.getHours()),ee(e.getMinutes()),ee(e.getSeconds())].join(`:`);return[e.getDate(),j[e.getMonth()],t].join(` `)}e.log=function(){console.log(`%s - %s`,te(),e.format.apply(e,arguments))},e.inherits=oo(),e._extend=function(e,t){if(!t||!T(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e};function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var N=typeof Symbol<`u`?Symbol(`util.promisify.custom`):void 0;e.promisify=function(e){if(typeof e!=`function`)throw TypeError(`The "original" argument must be of type Function`);if(N&&e[N]){var n=e[N];if(typeof n!=`function`)throw TypeError(`The "util.promisify.custom" argument must be of type Function`);return Object.defineProperty(n,N,{value:n,enumerable:!1,writable:!1,configurable:!0}),n}function n(){for(var t,n,r=new Promise(function(e,r){t=e,n=r}),i=[],a=0;a<arguments.length;a++)i.push(arguments[a]);i.push(function(e,r){e?n(e):t(r)});try{e.apply(this,i)}catch(e){n(e)}return r}return Object.setPrototypeOf(n,Object.getPrototypeOf(e)),N&&Object.defineProperty(n,N,{value:n,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(n,t(e))},e.promisify.custom=N;function P(e,t){if(!e){var n=/* @__PURE__ */ Error(`Promise was rejected with a falsy value`);n.reason=e,e=n}return t(e)}function F(e){if(typeof e!=`function`)throw TypeError(`The "original" argument must be of type Function`);function n(){for(var t=[],n=0;n<arguments.length;n++)t.push(arguments[n]);var r=t.pop();if(typeof r!=`function`)throw TypeError(`The last argument must be of type Function`);var i=this,a=function(){return r.apply(i,arguments)};e.apply(this,t).then(function(e){process.nextTick(a.bind(null,null,e))},function(e){process.nextTick(P.bind(null,e,a))})}return Object.setPrototypeOf(n,Object.getPrototypeOf(e)),Object.defineProperties(n,t(e)),n}e.callbackify=F})),ps=/* @__PURE__ */ t(((e,t)=>{function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function r(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]==null?{}:arguments[t];t%2?n(Object(r),!0).forEach(function(t){i(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function i(e,t,n){return t=c(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,c(r.key),r)}}function s(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function c(e){var t=l(e,`string`);return typeof t==`symbol`?t:String(t)}function l(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var u=uo().Buffer,d=fs().inspect,f=d&&d.custom||`inspect`;function p(e,t,n){u.prototype.copy.call(e,t,n)}t.exports=/*#__PURE__*/ function(){function e(){a(this,e),this.head=null,this.tail=null,this.length=0}return s(e,[{key:`push`,value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:`unshift`,value:function(e){var t={data:e,next:this.head};this.length===0&&(this.tail=t),this.head=t,++this.length}},{key:`shift`,value:function(){if(this.length!==0){var e=this.head.data;return this.head=this.length===1?this.tail=null:this.head.next,--this.length,e}}},{key:`clear`,value:function(){this.head=this.tail=null,this.length=0}},{key:`join`,value:function(e){if(this.length===0)return``;for(var t=this.head,n=``+t.data;t=t.next;)n+=e+t.data;return n}},{key:`concat`,value:function(e){if(this.length===0)return u.alloc(0);for(var t=u.allocUnsafe(e>>>0),n=this.head,r=0;n;)p(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:`consume`,value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:`first`,value:function(){return this.head.data}},{key:`_getString`,value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,a=e>i.length?i.length:e;if(a===i.length?r+=i:r+=i.slice(0,e),e-=a,e===0){a===i.length?(++n,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=i.slice(a));break}++n}return this.length-=n,r}},{key:`_getBuffer`,value:function(e){var t=u.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,a=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,a),e-=a,e===0){a===i.length?(++r,this.head=n.next?n.next:this.tail=null):(this.head=n,n.data=i.slice(a));break}++r}return this.length-=r,t}},{key:f,value:function(e,t){return d(this,r(r({},t),{},{depth:0,customInspect:!1}))}}]),e}()})),ms=/* @__PURE__ */ t(((e,t)=>{function n(e,t){var n=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(o,this,e)):process.nextTick(o,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?n._writableState?n._writableState.errorEmitted?process.nextTick(i,n):(n._writableState.errorEmitted=!0,process.nextTick(r,n,e)):process.nextTick(r,n,e):t?(process.nextTick(i,n),t(e)):process.nextTick(i,n)}),this)}function r(e,t){o(e,t),i(e)}function i(e){(!e._writableState||e._writableState.emitClose)&&(!e._readableState||e._readableState.emitClose)&&e.emit(`close`)}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit(`error`,t)}function s(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(`error`,t)}t.exports={destroy:n,undestroy:a,errorOrDestroy:s}})),hs=/* @__PURE__ */ t(((e,t)=>{function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var r={};function i(e,t,i){i||=Error;function a(e,n,r){return typeof t==`string`?t:t(e,n,r)}var o=/*#__PURE__*/ function(e){n(t,e);function t(t,n,r){return e.call(this,a(t,n,r))||this}return t}(i);o.prototype.name=i.name,o.prototype.code=e,r[e]=o}function a(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map(function(e){return String(e)}),n>2?`one of ${t} ${e.slice(0,n-1).join(`, `)}, or `+e[n-1]:n===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}return`of ${t} ${String(e)}`}function o(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function s(e,t,n){return(n===void 0||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function c(e,t,n){return typeof n!=`number`&&(n=0),n+t.length>e.length?!1:e.indexOf(t,n)!==-1}i(`ERR_INVALID_OPT_VALUE`,function(e,t){return`The value "`+t+`" is invalid for option "`+e+`"`},TypeError),i(`ERR_INVALID_ARG_TYPE`,function(e,t,n){var r;typeof t==`string`&&o(t,`not `)?(r=`must not be`,t=t.replace(/^not /,``)):r=`must be`;var i=s(e,` argument`)?`The ${e} ${r} ${a(t,`type`)}`:`The "${e}" ${c(e,`.`)?`property`:`argument`} ${r} ${a(t,`type`)}`;return i+=`. Received type ${typeof n}`,i},TypeError),i(`ERR_STREAM_PUSH_AFTER_EOF`,`stream.push() after EOF`),i(`ERR_METHOD_NOT_IMPLEMENTED`,function(e){return`The `+e+` method is not implemented`}),i(`ERR_STREAM_PREMATURE_CLOSE`,`Premature close`),i(`ERR_STREAM_DESTROYED`,function(e){return`Cannot call `+e+` after a stream was destroyed`}),i(`ERR_MULTIPLE_CALLBACK`,`Callback called multiple times`),i(`ERR_STREAM_CANNOT_PIPE`,`Cannot pipe, not readable`),i(`ERR_STREAM_WRITE_AFTER_END`,`write after end`),i(`ERR_STREAM_NULL_VALUES`,`May not write null values to stream`,TypeError),i(`ERR_UNKNOWN_ENCODING`,function(e){return`Unknown encoding: `+e},TypeError),i(`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`,`stream.unshift() after end event`),t.exports.codes=r})),gs=/* @__PURE__ */ t(((e,t)=>{var n=hs().codes.ERR_INVALID_OPT_VALUE;function r(e,t,n){return e.highWaterMark==null?t?e[n]:null:e.highWaterMark}function i(e,t,i,a){var o=r(t,a,i);if(o!=null){if(!(isFinite(o)&&Math.floor(o)===o)||o<0)throw new n(a?i:`highWaterMark`,o);return Math.floor(o)}return e.objectMode?16:16384}t.exports={getHighWaterMark:i}})),_s=/* @__PURE__ */ t(((e,t)=>{t.exports=n;function n(e,t){if(r(`noDeprecation`))return e;var n=!1;function i(){if(!n){if(r(`throwDeprecation`))throw Error(t);r(`traceDeprecation`)?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return i}function r(e){try{if(!global.localStorage)return!1}catch{return!1}var t=global.localStorage[e];return t!=null&&String(t).toLowerCase()===`true`}})),vs=/* @__PURE__ */ t(((e,t)=>{t.exports=T;function n(e){var t=this;this.next=null,this.entry=null,this.finish=function(){ne(t,e)}}var r;T.WritableState=C;var i={deprecate:_s()},a=so(),o=uo().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=ms(),d=gs().getHighWaterMark,f=hs().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;oo()(T,a);function S(){}function C(e,t,i){r||=ys(),e||={},typeof i!=`boolean`&&(i=t instanceof r),this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=d(this,e,`writableHighWaterMark`,i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=e.decodeStrings===!1;this.decodeStrings=!a,this.defaultEncoding=e.defaultEncoding||`utf8`,this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){te(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new n(this)}C.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},(function(){try{Object.defineProperty(C.prototype,"buffer",{get:i.deprecate(function(){return this.getBuffer()},`_writableState.buffer is deprecated. Use _writableState.getBuffer instead.`,`DEP0003`)})}catch{}})();var w;typeof Symbol==`function`&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==`function`?(w=Function.prototype[Symbol.hasInstance],Object.defineProperty(T,Symbol.hasInstance,{value:function(e){return w.call(this,e)?!0:this===T&&e&&e._writableState instanceof C}})):w=function(e){return e instanceof this};function T(e){r||=ys();var t=this instanceof r;if(!t&&!w.call(T,this))return new T(e);this._writableState=new C(e,this,t),this.writable=!0,e&&(typeof e.write==`function`&&(this._write=e.write),typeof e.writev==`function`&&(this._writev=e.writev),typeof e.destroy==`function`&&(this._destroy=e.destroy),typeof e.final==`function`&&(this._final=e.final)),a.call(this)}T.prototype.pipe=function(){x(this,new g)};function E(e,t){var n=new y;x(e,n),process.nextTick(t,n)}function D(e,t,n,r){var i;return n===null?i=new v:typeof n!=`string`&&!t.objectMode&&(i=new p(`chunk`,[`string`,`Buffer`],n)),!i||(x(e,i),process.nextTick(r,i),!1)}T.prototype.write=function(e,t,n){var r=this._writableState,i=!1,a=!r.objectMode&&l(e);return a&&!o.isBuffer(e)&&(e=c(e)),typeof t==`function`&&(n=t,t=null),a?t=`buffer`:t||=r.defaultEncoding,typeof n!=`function`&&(n=S),r.ending?E(this,n):(a||D(this,r,e,n))&&(r.pendingcb++,i=k(this,r,a,e,t,n)),i},T.prototype.cork=function(){this._writableState.corked++},T.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&P(this,e))},T.prototype.setDefaultEncoding=function(e){if(typeof e==`string`&&(e=e.toLowerCase()),!([`hex`,`utf8`,`utf-8`,`ascii`,`binary`,`base64`,`ucs2`,`ucs-2`,`utf16le`,`utf-16le`,`raw`].indexOf((e+``).toLowerCase())>-1))throw new b(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(T.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function O(e,t,n){return!e.objectMode&&e.decodeStrings!==!1&&typeof t==`string`&&(t=o.from(t,n)),t}Object.defineProperty(T.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function k(e,t,n,r,i,a){if(!n){var o=O(t,r,i);r!==o&&(n=!0,i=`buffer`,r=o)}var s=t.objectMode?1:r.length;t.length+=s;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else A(e,t,!1,s,r,i,a);return c}function A(e,t,n,r,i,a,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new _(`write`)):n?e._writev(i,t.onwrite):e._write(i,a,t.onwrite),t.sync=!1}function ee(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick(R,e,t),e._writableState.errorEmitted=!0,x(e,r)):(i(r),e._writableState.errorEmitted=!0,x(e,r),R(e,t))}function j(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function te(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(typeof i!=`function`)throw new h;if(j(n),t)ee(e,n,r,t,i);else{var a=F(n)||e.destroyed;!a&&!n.corked&&!n.bufferProcessing&&n.bufferedRequest&&P(e,n),r?process.nextTick(M,e,n,a,i):M(e,n,a,i)}}function M(e,t,n,r){n||N(e,t),t.pendingcb--,r(),R(e,t)}function N(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit(`drain`))}function P(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var i=t.bufferedRequestCount,a=Array(i),o=t.corkedRequestsFree;o.entry=r;for(var s=0,c=!0;r;)a[s]=r,r.isBuf||(c=!1),r=r.next,s+=1;a.allBuffers=c,A(e,t,!0,t.length,a,``,o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new n(t),t.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,u=r.encoding,d=r.callback;if(A(e,t,!1,t.objectMode?1:l.length,l,u,d),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}T.prototype._write=function(e,t,n){n(new m(`_write()`))},T.prototype._writev=null,T.prototype.end=function(e,t,n){var r=this._writableState;return typeof e==`function`?(n=e,e=null,t=null):typeof t==`function`&&(n=t,t=null),e!=null&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||z(this,r,n),this},Object.defineProperty(T.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function F(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function I(e,t){e._final(function(n){t.pendingcb--,n&&x(e,n),t.prefinished=!0,e.emit(`prefinish`),R(e,t)})}function L(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final==`function`&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(I,e,t)):(t.prefinished=!0,e.emit(`prefinish`)))}function R(e,t){var n=F(t);if(n&&(L(e,t),t.pendingcb===0&&(t.finished=!0,e.emit(`finish`),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function z(e,t,n){t.ending=!0,R(e,t),n&&(t.finished?process.nextTick(n):e.once(`finish`,n)),t.ended=!0,e.writable=!1}function ne(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}Object.defineProperty(T.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState!==void 0&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),T.prototype.destroy=u.destroy,T.prototype._undestroy=u.undestroy,T.prototype._destroy=function(e,t){t(e)}})),ys=/* @__PURE__ */ t(((e,t)=>{var n=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=c;var r=Ts(),i=vs();oo()(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)}})})),bs=/* @__PURE__ */ t(((e,t)=>{
22
22
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
23
- var n=uo(),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)}})),xs=/* @__PURE__ */ t((e=>{var t=bs().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):``}})),Ss=/* @__PURE__ */ t(((e,t)=>{var n=hs().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})),Cs=/* @__PURE__ */ t(((e,t)=>{var n;function r(e,t,n){return t=i(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=a(e,`string`);return typeof t==`symbol`?t:String(t)}function a(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var o=Ss(),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}})),ws=/* @__PURE__ */ t(((e,t)=>{t.exports=function(){throw Error(`Readable.from is not available in the browser`)}})),Ts=/* @__PURE__ */ t(((e,t)=>{t.exports=E;var n;E.ReadableState=T,ao().EventEmitter;var r=function(e,t){return e.listeners(t).length},i=so(),a=uo().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=fs(),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=ps(),f=ms(),p=gs().getHighWaterMark,m=hs().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;oo()(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||=ys(),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||=xs().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=ys(),!(this instanceof E))return new E(e);var t=this instanceof n;this._readableState=new T(e,this,t),this.readable=!0,e&&(typeof e.read==`function`&&(this._read=e.read),typeof e.destroy==`function`&&(this._destroy=e.destroy)),i.call(this)}Object.defineProperty(E.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),E.prototype.destroy=f.destroy,E.prototype._undestroy=f.undestroy,E.prototype._destroy=function(e,t){t(e)},E.prototype.push=function(e,t){var n=this._readableState,r;return n.objectMode?r=!0:typeof e==`string`&&(t||=n.defaultEncoding,t!==n.encoding&&(e=a.from(e,t),t=``),r=!0),D(this,e,t,!1,r)},E.prototype.unshift=function(e){return D(this,e,null,!0,!1)};function D(e,t,n,r,i){u(`readableAddChunk`,t);var o=e._readableState;if(t===null)o.reading=!1,te(e,o);else{var c;if(i||(c=k(o,t)),c)S(e,c);else if(o.objectMode||t&&t.length>0){if(typeof t!=`string`&&!o.objectMode&&Object.getPrototypeOf(t)!==a.prototype&&(t=s(t)),r)o.endEmitted?S(e,new v):O(e,o,t,!0);else if(o.ended)S(e,new g);else if(o.destroyed)return!1;else o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||t.length!==0?O(e,o,t,!1):P(e,o)):O(e,o,t,!1)}else r||(o.reading=!1,P(e,o))}return!o.ended&&(o.length<o.highWaterMark||o.length===0)}function O(e,t,n,r){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit(`data`,n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&M(e)),P(e,t)}function k(e,t){var n;return!c(t)&&typeof t!=`string`&&t!==void 0&&!e.objectMode&&(n=new h(`chunk`,[`string`,`Buffer`,`Uint8Array`],t)),n}E.prototype.isPaused=function(){return this._readableState.flowing===!1},E.prototype.setEncoding=function(e){y||=xs().StringDecoder;var t=new y(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r=``;n!==null;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),r!==``&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var A=1073741824;function ee(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function j(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=ee(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}E.prototype.read=function(e){u(`read`,e),e=parseInt(e,10);var t=this._readableState,n=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark===0?t.length>0:t.length>=t.highWaterMark)||t.ended))return u(`read: emitReadable`,t.length,t.ended),t.length===0&&t.ended?ie(this):M(this),null;if(e=j(e,t),e===0&&t.ended)return t.length===0&&ie(this),null;var r=t.needReadable;u(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,u(`length less than watermark`,r)),t.ended||t.reading?(r=!1,u(`reading or ended`,r)):r&&(u(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=j(n,t)));var i=e>0?re(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&ie(this)),i!==null&&this.emit(`data`,i),i};function te(e,t){if(u(`onEofChunk`),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?M(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,N(e)))}}function M(e){var t=e._readableState;u(`emitReadable`,t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u(`emitReadable`,t.flowing),t.emittedReadable=!0,process.nextTick(N,e))}function N(e){var t=e._readableState;u(`emitReadable_`,t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(`readable`),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,B(e)}function P(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(F,e,t))}function F(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var n=t.length;if(u(`maybeReadMore read 0`),e.read(0),n===t.length)break}t.readingMore=!1}E.prototype._read=function(e){S(this,new _(`_read()`))},E.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,u(`pipe count=%d opts=%j`,i.pipesCount,t);var a=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr?s:g;i.endEmitted?process.nextTick(a):n.once(`end`,a),e.on(`unpipe`,o);function o(e,t){u(`onunpipe`),e===n&&t&&t.hasUnpiped===!1&&(t.hasUnpiped=!0,d())}function s(){u(`onend`),e.end()}var c=I(n);e.on(`drain`,c);var l=!1;function d(){u(`cleanup`),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`drain`,c),e.removeListener(`error`,p),e.removeListener(`unpipe`,o),n.removeListener(`end`,s),n.removeListener(`end`,g),n.removeListener(`data`,f),l=!0,i.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}n.on(`data`,f);function f(t){u(`ondata`);var r=e.write(t);u(`dest.write`,r),r===!1&&((i.pipesCount===1&&i.pipes===e||i.pipesCount>1&&oe(i.pipes,e)!==-1)&&!l&&(u(`false write response, pause`,i.awaitDrain),i.awaitDrain++),n.pause())}function p(t){u(`onerror`,t),g(),e.removeListener(`error`,p),r(e,`error`)===0&&S(e,t)}w(e,`error`,p);function m(){e.removeListener(`finish`,h),g()}e.once(`close`,m);function h(){u(`onfinish`),e.removeListener(`close`,m),g()}e.once(`finish`,h);function g(){u(`unpipe`),n.unpipe(e)}return e.emit(`pipe`,n),i.flowing||(u(`pipe resume`),n.resume()),e};function I(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,B(e))}}E.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=oe(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),--t.pipesCount,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit(`unpipe`,this,n),this)},E.prototype.on=function(e,t){var n=i.prototype.on.call(this,e,t),r=this._readableState;return e===`data`?(r.readableListening=this.listenerCount(`readable`)>0,r.flowing!==!1&&this.resume()):e===`readable`&&!r.endEmitted&&!r.readableListening&&(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,u(`on readable`,r.length,r.reading),r.length?M(this):r.reading||process.nextTick(R,this)),n},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var n=i.prototype.removeListener.call(this,e,t);return e===`readable`&&process.nextTick(L,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(L,this),t};function L(e){var t=e._readableState;t.readableListening=e.listenerCount(`readable`)>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount(`data`)>0&&e.resume()}function R(e){u(`readable nexttick read 0`),e.read(0)}E.prototype.resume=function(){var e=this._readableState;return e.flowing||(u(`resume`),e.flowing=!e.readableListening,z(this,e)),e.paused=!1,this};function z(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ne,e,t))}function ne(e,t){u(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),B(e),t.flowing&&!t.reading&&e.read(0)}E.prototype.pause=function(){return u(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(u(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function B(e){var t=e._readableState;for(u(`flow`,t.flowing);t.flowing&&e.read()!==null;);}E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(u(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){u(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(n.objectMode||i&&i.length)&&(t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<C.length;a++)e.on(C[a],this.emit.bind(this,C[a]));return this._read=function(t){u(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(E.prototype[Symbol.asyncIterator]=function(){return b===void 0&&(b=Cs()),b(this)}),Object.defineProperty(E.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=re,Object.defineProperty(E.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function re(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function ie(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(ae,t,e))}function ae(e,t){if(u(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(E.from=function(e,t){return x===void 0&&(x=ws()),x(E,e,t)});function oe(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),Es=/* @__PURE__ */ t(((e,t)=>{t.exports=l;var n=hs().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=ys();oo()(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)}})),Ds=/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=Es();oo()(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)}})),Os=/* @__PURE__ */ t(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=hs().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=Ss()),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})),ks=/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=ao().EventEmitter;oo()(r,n),r.Readable=Ts(),r.Writable=vs(),r.Duplex=ys(),r.Transform=Es(),r.PassThrough=Ds(),r.finished=Ss(),r.pipeline=Os(),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}})),As=/* @__PURE__ */ n({Server:()=>Fs,Socket:()=>Ps,_default:()=>zs,connect:()=>Is,createConnection:()=>Ls,createServer:()=>Rs,default:()=>zs,isIP:()=>to,isIPv4:()=>$a,isIPv6:()=>eo,t:()=>Ns}),js=ks(),Ms=ao(),Ns=/* @__PURE__ */ i({Server:()=>Fs,Socket:()=>Ps,_default:()=>zs,connect:()=>Is,createConnection:()=>Ls,createServer:()=>Rs,default:()=>zs,isIP:()=>to,isIPv4:()=>$a,isIPv6:()=>eo}),Ps=class extends js.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??=Va(`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(/* @__PURE__ */ Error(`Socket not connected`));return}this._webVPNTcpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not connected`);await t.writer.ready,await t.writer.write(e),this._restartTimeoutTimer(),n()}).catch(n)}connect(...e){let t=no(...e),n=this.__webvpn_tcp_socket_init__(Ra(`an outbound tcp socket`).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`,/* @__PURE__ */ Error(`Cannot set socket option before connect`));return}this._webVPNTcpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}write(e,t,...n){return super.write(e,t,...n)}address(){return this._localAddress??{}}unref(){return this}ref(){return this}autoSelectFamilyAttemptedAddresses;bufferSize;bytesRead;bytesWritten;connecting;pending;get localAddress(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.address}get localPort(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.port}get localFamily(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.family}readyState;get remoteAddress(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.address}get remotePort(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.port}get remoteFamily(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.family}timeout},Fs=class extends Ms.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??=Va(`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=no(...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=>Ra(`a tcp listener`).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](){}},Is=(e,t)=>new Ps().connect(e,t),Ls=(e,t)=>new Ps().connect(e,t),Rs=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new Fs(e);return t&&n.on(`connection`,t),n},zs={Socket:Ps,Server:Fs,connect:Is,createConnection:Ls,createServer:Rs,isIP:to,isIPv4:$a,isIPv6:eo},Bs=/* @__PURE__ */ n({Socket:()=>Us,createSocket:()=>Ys,default:()=>Xs,t:()=>Hs}),Vs=uo(),Hs=/* @__PURE__ */ i({Socket:()=>Us,createSocket:()=>Ys,default:()=>Xs}),Us=class extends Ms.EventEmitter{_type;_localAddress;_remoteAddress;_connectedLocally;_connectGeneration=0;_destroyed=!1;_busyRelease;_webVPNUdpSocketPromise;_dataPort;_socketId;_sendQueue=[];_sendQueueBytes=0;_sendFlushScheduled=!1;_peerTailCache=/* @__PURE__ */ 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`,/* @__PURE__ */ Error(`Cannot set socket option before bind`));return}this._webVPNUdpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}_dataPortAcks=!1;_dataPortConsumedBytes=0;_dataPortAckedBytes=0;_ackDataPortBatch(e){if(!this._dataPortAcks||!this._dataPort||(this._dataPortConsumedBytes+=e,this._dataPortAckedBytes!==0&&this._dataPortConsumedBytes-this._dataPortAckedBytes<524288))return;this._dataPortAckedBytes=this._dataPortConsumedBytes;let t={type:Qa,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=qs(n)),s+=n.byteLength,d=t.getUint16(s),s+=2}let f=t.getUint32(s);s+=4;try{this.emit(`message`,Vs.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 Ws;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let i=Xa.Address4.isValid(e)?Ks(e):Js(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(Xa.Address4.isValid(e)){let n=Ks(e),r=t&&Xa.Address4.isValid(t)?Ks(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(Xa.Address6.isValid(e)){let t=Js(e);this._setUdpOption({type:7,group:t,ifIndex:0})}else this.emit(`error`,/* @__PURE__ */ Error(`Invalid multicast address: ${e}`))}address(){if(!this._localAddress)throw Error(`EBADF`);return this._localAddress}bind(...e){let t=ro(...e),n=this._type===`udp6`?`::`:`0.0.0.0`,r=this.__webvpn_udp_socket_init__(Ra(`a udp socket`).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??=Va(`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`,Vs.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(Xa.Address4.isValid(e)){let n=Ks(e),r=t&&Xa.Address4.isValid(t)?Ks(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(Xa.Address6.isValid(e)){let t=Js(e);this._setUdpOption({type:8,group:t,ifIndex:0})}else this.emit(`error`,/* @__PURE__ */ Error(`Invalid multicast address: ${e}`))}getRecvBufferSize(){return this._lastRecvBufferSize}getSendBufferSize(){return this._lastSendBufferSize}getSendQueueSize(){return 0}getSendQueueCount(){return 0}ref(){return this}remoteAddress(){if(!this._remoteAddress)throw Error(`ERR_SOCKET_DGRAM_NOT_CONNECTED`);return{address:this._remoteAddress.address,family:this._remoteAddress.family,port:this._remoteAddress.port}}send(...e){this._webVPNUdpSocketPromise||this.bind();let t=io(...e),n=Gs(t.message),r=n;if(t.hasRange){let{offset:e,length:i}=t;if(!Number.isInteger(e)||e<0||e>n.byteLength)throw Object.assign(/* @__PURE__ */ RangeError(`"offset" is outside of buffer bounds`),{code:`ERR_BUFFER_OUT_OF_BOUNDS`});if(!Number.isInteger(i)||i<0||i>n.byteLength-e)throw Object.assign(/* @__PURE__ */ RangeError(`"length" is outside of buffer bounds`),{code:`ERR_BUFFER_OUT_OF_BOUNDS`});r=n.subarray(e,e+i)}let i=this._type===`udp6`?`::1`:`127.0.0.1`;if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(e=>{if(!e)throw Error(`Socket not bound`);let n=t.callback,a=t.address??i,o=this._remoteAddress!==void 0&&t.address===void 0;if(this._dataPort&&(o||Xa.Address4.isValid(a)||Xa.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)})}},Ws=new Uint8Array([2]),Gs=e=>{if(typeof e==`string`)return Za.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(Gs),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)},Ks=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)},qs=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(`:`)}`},Js=e=>{let t=new Xa.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)))},Ys=(e,t)=>{let n=new Us(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},Xs={Socket:Us,createSocket:Ys};function Zs(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function Qs(e,t){let n,r=()=>{if(n)return n;let r=indexedDB.open(e);return r.onupgradeneeded=()=>r.result.createObjectStore(t),n=Zs(r),n.then(e=>{e.onclose=()=>n=void 0},()=>{}),n};return(e,n)=>r().then(r=>n(r.transaction(t,e).objectStore(t)))}let $s;function ec(){return $s||=Qs(`keyval-store`,`keyval`),$s}function tc(e,t=ec()){return t(`readonly`,t=>Zs(t.get(e)))}function nc(e,t,n=ec()){return n(`readwrite`,n=>(n.put(t,e),Zs(n.transaction)))}function rc(e,t,n=ec()){return n(`readwrite`,n=>new Promise((r,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),r(Zs(n.transaction))}catch(e){i(e)}}}))}function ic(e,t=ec()){return t(`readwrite`,t=>(t.delete(e),Zs(t.transaction)))}var ac={checkingFiles:1,downloadingMetadata:2,downloading:3,finished:4,seeding:5,checkingResumeData:7},oc=/^incoming connection from (\S+) \(([^)]*)\)/,sc=/^successfully listening on \[([^\]]*)\] (\S+)/,cc=/^listening on .* failed:/,lc=new TextDecoder,uc=4026531841,dc=4026531842,fc=4026531843,pc=4026531844,mc=4026531845,hc=4026531846,gc={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},_c={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},vc={top:0,up:1,down:2,bottom:3},yc={tracker:1,dht:2,pex:4,lsd:8,resumeData:16,incoming:32},G={skip:0,low:1,normal:4,top:7},bc=6e4,xc=12,Sc=1e3,Cc=class{mod;storage;destroyed=!1;fallbackTimer;filesByHandle=/* @__PURE__ */ new Map;bitfieldByHandle=/* @__PURE__ */ new Map;statusByHandle=/* @__PURE__ */ new Map;pieceWaiters=[];resumeByHandle=/* @__PURE__ */ new Map;resumeWaiters=[];peersByHandle=/* @__PURE__ */ new Map;trackersByHandle=/* @__PURE__ */ new Map;peerWaiters=[];trackerWaiters=[];priosByHandle=/* @__PURE__ */ new Map;deadlineRefs=/* @__PURE__ */ new Map;reachability={listening:{},listenFailed:[],inbound:0,inboundByTransport:{},lastInbound:null,port:null};constructor(e,t){if(this.mod=e,this.storage=t.storage??null,t.utpReceiveBufferBytes&&e._lt_set_utp_receive_buffer(t.utpReceiveBufferBytes),t.enableDht===!1&&e._lt_set_dht(0),t.rateLimits){let{download:n,upload:r,limitLocalPeers:i}=t.rateLimits;e._lt_session_set_rate_limits(Math.max(0,Math.floor(n??0)),Math.max(0,Math.floor(r??0)),i==null?-1:+!!i)}if(e._lt_session_create()!==0)throw Error(`lt_session_create returned non-zero`);let n=t.tickIntervalMs??250;this.fallbackTimer=setInterval(()=>this.tick(),n)}addMagnet(e,t=`/downloads`){let n=this.mod,r=n.stringToNewUTF8(e),i=n.stringToNewUTF8(t);try{return n._lt_session_add_magnet(r,i)>>>0}finally{n._free(r),n._free(i)}}addTorrentFile(e,t=`/downloads`){let n=this.mod,r=n._malloc(e.length);n.HEAPU8.set(e,r);let i=n.stringToNewUTF8(t);try{return n._lt_session_add_torrent_file(r,e.length,i)>>>0}finally{n._free(r),n._free(i)}}addTorrentWithResume(e,t=`/downloads`){let n=this.mod,r=n._malloc(e.length);n.HEAPU8.set(e,r);let i=n.stringToNewUTF8(t);try{return n._lt_session_add_torrent_with_resume(r,e.length,i)>>>0}finally{n._free(r),n._free(i)}}removeTorrent(e,t=!1){this.mod._lt_session_remove_torrent_ex(e,+!!t),this.failPieceWaiters(/* @__PURE__ */ Error(`read: torrent ${e} was removed`),e),this.filesByHandle.delete(e),this.bitfieldByHandle.delete(e),this.statusByHandle.delete(e),this.resumeByHandle.delete(e),this.priosByHandle.delete(e),this.deadlineRefs.delete(e)}pauseTorrent(e){this.mod._lt_torrent_pause(e)}resumeTorrent(e){this.mod._lt_torrent_resume(e)}forceRecheck(e){this.mod._lt_torrent_force_recheck(e)}saveResumeData(e,t=8e3){return this.mod._lt_torrent_save_resume_data(e),new Promise((n,r)=>{let i={handle:e,resolve:n};this.resumeWaiters.push(i),setTimeout(()=>{let e=this.resumeWaiters.indexOf(i);e>=0&&(this.resumeWaiters.splice(e,1),r(/* @__PURE__ */ Error(`save_resume_data timed out`)))},t)})}peers(e,t=4e3){return this.mod._lt_torrent_post_peers(e),this.awaitList(this.peerWaiters,this.peersByHandle,e,t)}lastPeers(e){return this.peersByHandle.get(e)??[]}trackers(e,t=4e3){return this.mod._lt_torrent_post_trackers(e),this.awaitList(this.trackerWaiters,this.trackersByHandle,e,t)}lastTrackers(e){return this.trackersByHandle.get(e)??[]}awaitList(e,t,n,r){return new Promise(i=>{let a={handle:n,resolve:i,timer:setTimeout(()=>{let r=e.indexOf(a);r>=0&&(e.splice(r,1),i(t.get(n)??[]))},r)};e.push(a)})}resolveOne(e,t,n){for(let r=e.length-1;r>=0;r--){let i=e[r];i.handle===t&&(clearTimeout(i.timer),e.splice(r,1),i.resolve(n))}}files(e){return this.filesByHandle.get(e)??null}bitfield(e){let t=this.bitfieldByHandle.get(e),n=this.filesByHandle.get(e);return!t||!n?null:{pieces:t.pieces,numPieces:t.numPieces,pieceLength:n.pieceLength,length:n.totalSize}}status(e){return this.statusByHandle.get(e)??null}async read(e,t,n,r,i={}){let a=this.filesByHandle.get(e);if(!a)throw Error(`read: no layout for handle ${e} (metadata not ready)`);let o=a.files[t];if(!o)throw Error(`read: no file ${t}`);if(!this.storage)throw Error(`read: no storage backend configured`);if(n<0)throw RangeError(`read: negative offset ${n}`);let s=Math.min(r,o.size-n);if(s<=0)return/* @__PURE__ */ new Uint8Array;let{pieceLength:c}=a,l=o.offset+n,u=Math.floor(l/c),d=Math.min(a.numPieces-1,Math.floor((l+s-1)/c));if(!this.hasPieces(e,u,d)){let t=i.deadlineMs===void 0?0:i.deadlineMs;if(t!==null){for(let n=u;n<=d;n++)this.mod._lt_torrent_set_piece_deadline(e,n,t,0);this.retainDeadlines(e,u,d)}this.mod._lt_torrent_post_status(e);try{await this.awaitPieces(e,u,d,i)}finally{t!==null&&this.releaseDeadlines(e,u,d)}}let f=await this.storage.read(a.storageIndex,t,n,s);return f instanceof Uint8Array?f:new Uint8Array(f)}setStreamWindow(e,t,n={}){let r=this.filesByHandle.get(e);if(!r)return!1;let{pieceLength:i,numPieces:a}=r,o=Math.max(1,Math.floor(n.windowPieces??xc)),s=Math.max(0,Math.floor(n.deadlineStepMs??Sc)),c=n.claimedPriority??G.normal,l=n.unclaimedPriority??G.normal,u=new Uint8Array(a).fill(l),d=/* @__PURE__ */ 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)*Sc,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,vc[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=/* @__PURE__ */ new Map);for(let e=t;e<=n;e++)r.set(e,(r.get(e)??0)+1)}releaseDeadlines(e,t,n){let r=this.deadlineRefs.get(e);if(!r)return;let i=[],a=this.priosByHandle.get(e);for(let o=t;o<=n;o++){let t=(r.get(o)??0)-1;if(t>0){r.set(o,t);continue}r.delete(o),this.mod._lt_torrent_reset_piece_deadline(e,o),i.push({piece:o,priority:a?.[o]??G.normal})}i.length&&this.prioritizePieceList(e,i),r.size||this.deadlineRefs.delete(e)}reissueReadDeadlines(e){let t=this.deadlineRefs.get(e);if(t)for(let n of t.keys())this.mod._lt_torrent_set_piece_deadline(e,n,0,0)}postStatus(e){this.mod._lt_torrent_post_status(e)}infohash(e){return this.readHash(e,this.mod._lt_torrent_infohash)}infohashV2(e){return this.readHash(e,this.mod._lt_torrent_infohash_v2)}readHash(e,t){let n=this.mod,r=n._malloc(65);try{return t.call(n,e,r)===0?n.UTF8ToString(r):null}finally{n._free(r)}}hasPieces(e,t,n){let r=this.bitfieldByHandle.get(e);if(!r)return!1;for(let e=t;e<=n;e++){if(e<0||e>=r.numPieces)return!1;let t=r.pieces[e>>3];if(t===void 0||!(t&128>>(e&7)))return!1}return!0}awaitPieces(e,t,n,r){let{signal:i}=r,a=r.timeoutMs??bc;return new Promise((r,o)=>{let s,c,l=e=>{let t=this.pieceWaiters.indexOf(u);t<0||(this.pieceWaiters.splice(t,1),s!==void 0&&clearTimeout(s),c&&i&&i.removeEventListener(`abort`,c),e?o(e):r())},u={handle:e,p0:t,p1:n,settle:l};if(this.pieceWaiters.push(u),i?.aborted){l(/* @__PURE__ */ Error(`read: aborted`));return}a>0&&(s=setTimeout(()=>l(/* @__PURE__ */ Error(`read: pieces ${t}-${n} of handle ${e} did not arrive within ${a}ms`)),a)),i&&(c=()=>l(/* @__PURE__ */ Error(`read: aborted`)),i.addEventListener(`abort`,c,{once:!0}))})}resolvePieceWaiters(){if(this.pieceWaiters.length!==0)for(let e of[...this.pieceWaiters])this.hasPieces(e.handle,e.p0,e.p1)&&e.settle()}failPieceWaiters(e,t){for(let n of[...this.pieceWaiters])(t===void 0||n.handle===t)&&n.settle(e)}popAlerts(){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===uc)this.decodeTorrentReady(r,a);else if(o===dc)this.decodeStateUpdate(r,a);else if(o===pc)this.decodeResumeData(r,a,s);else if(o===mc)this.decodePeers(r,a);else if(o===hc)this.decodeTrackers(r,a);else if(o!==fc){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=oc.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=sc.exec(e);if(n){this.reachability.listening[n[1].toLowerCase()]=n[2];return}cc.test(e)&&this.reachability.listenFailed.length<32&&this.reachability.listenFailed.push(e)}readStr(e,t){let n=e.getUint32(t,!0);return t+=4,[lc.decode(new Uint8Array(e.buffer,e.byteOffset+t,n)),t+n]}decodePeers(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getUint32(t,!0);t+=4;let i=[];for(let n=0;n<r;n++){let n,r;[n,t]=this.readStr(e,t),[r,t]=this.readStr(e,t);let a=e.getUint32(t,!0);t+=4;let o=e.getUint32(t,!0);t+=4;let s=e.getUint32(t,!0);t+=4;let c=e.getInt32(t,!0);t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=Number(e.getBigInt64(t,!0));t+=8;let p=Number(e.getBigInt64(t,!0));t+=8;let m=e.getInt32(t,!0)/1e6;t+=4;let h=e.getInt32(t,!0);t+=4;let g=e.getInt32(t,!0);t+=4;let _=e.getInt32(t,!0);t+=4;let v=e.getInt32(t,!0);t+=4,i.push({endpoint:n,client:r,flags:a,source:o,connectionType:s,downloadRate:c,uploadRate:l,payloadDownloadRate:u,payloadUploadRate:d,totalDownload:f,totalUpload:p,progress:m,rtt:h,numPieces:g,requestsInFlight:_,failCount:v})}this.peersByHandle.set(n,i),this.resolveOne(this.peerWaiters,n,i)}decodeTrackers(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getUint32(t,!0);t+=4;let i=[];for(let n=0;n<r;n++){let n,r;[n,t]=this.readStr(e,t),[r,t]=this.readStr(e,t);let a=e.getInt32(t,!0);t+=4;let o=e.getInt32(t,!0);t+=4;let s=e.getUint32(t,!0)!==0;t+=4;let c=e.getUint32(t,!0)!==0;t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=e.getInt32(t,!0);t+=4,i.push({url:n,message:r,tier:a,fails:o,updating:s,verified:c,nextAnnounceIn:l,seeders:u,leechers:d,downloaded:f})}this.trackersByHandle.set(n,i),this.resolveOne(this.trackerWaiters,n,i)}decodeResumeData(e,t,n){let r=e.getUint32(t,!0),i=new Uint8Array(n-4);i.set(new Uint8Array(e.buffer,e.byteOffset+t+4,n-4)),this.resumeByHandle.set(r,i),this.resumeWaiters=this.resumeWaiters.filter(e=>e.handle!==r||(e.resolve(i),!1))}decodeTorrentReady(e,t){let n=new TextDecoder,r=e.getUint32(t,!0);t+=4;let i=e.getUint32(t,!0);t+=4;let a=e.getUint32(t,!0);t+=4;let o=e.getUint32(t,!0);t+=4;let s=Number(e.getBigInt64(t,!0));t+=8;let c=e.getUint32(t,!0);t+=4;let l=[];for(let r=0;r<c;r++){let r=Number(e.getBigInt64(t,!0));t+=8;let i=Number(e.getBigInt64(t,!0));t+=8;let a=e.getUint8(t)===1;t+=1;let o=e.getUint32(t,!0);t+=4;let s=n.decode(new Uint8Array(e.buffer,e.byteOffset+t,o));t+=o,l.push({path:s,size:i,offset:r,pad:a})}let u=l.reduce((e,t)=>e+(t.pad?0:t.size),0);this.filesByHandle.set(r,{storageIndex:i,pieceLength:a,numPieces:o,totalSize:s,contentSize:u,files:l})}decodeStateUpdate(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getInt32(t,!0);t+=4;let i=Number(e.getBigInt64(t,!0));t+=8;let a=Number(e.getBigInt64(t,!0));t+=8;let o=e.getFloat32(t,!0);t+=4;let s=e.getInt32(t,!0);t+=4;let c=e.getInt32(t,!0);t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getUint32(t,!0)!==0;t+=4;let f=e.getUint32(t,!0)!==0;t+=4;let p=e.getUint32(t,!0)!==0;t+=4;let m=e.getUint32(t,!0)>>>0;t+=4;let h=Number(e.getBigInt64(t,!0));t+=8;let g=Number(e.getBigInt64(t,!0));t+=8;let _=Number(e.getBigInt64(t,!0));t+=8;let v=Number(e.getBigInt64(t,!0));t+=8;let y=Number(e.getBigInt64(t,!0));t+=8;let b=Number(e.getBigInt64(t,!0));t+=8;let x=Number(e.getBigInt64(t,!0));t+=8;let S=e.getInt32(t,!0);t+=4;let C=e.getInt32(t,!0);t+=4;let w=e.getInt32(t,!0);t+=4;let T=e.getInt32(t,!0);t+=4,t+=4;let E=e.getFloat32(t,!0);t+=4;let D=e.getInt32(t,!0);t+=4;let O=e.getInt32(t,!0);t+=4;let k=Number(e.getBigInt64(t,!0));t+=8;let A=Number(e.getBigInt64(t,!0));t+=8;let ee=Number(e.getBigInt64(t,!0));t+=8;let j=e.getUint32(t,!0)!==0;t+=4;let te;[te,t]=this.readStr(e,t);let M=e.getInt32(t,!0);t+=4;let N=e.getInt32(t,!0);t+=4;let P=e.getUint32(t,!0);t+=4;let F=P?lc.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!==ac.downloadingMetadata})}async*alerts(){for(;!this.destroyed;){for(let e of this.popAlerts())yield e;await new Promise(e=>setTimeout(e,100))}}setReservedPort(e){this.reachability.port=e}tick(){if(!this.destroyed&&(this.mod._lt_session_tick(),this.pieceWaiters.length)){let e=new Set(this.pieceWaiters.map(e=>e.handle));for(let t of e)this.mod._lt_torrent_post_status(t)}}destroy(){this.destroyed||(this.destroyed=!0,this.fallbackTimer!=null&&clearInterval(this.fallbackTimer),this.failPieceWaiters(/* @__PURE__ */ Error(`read: session destroyed`)),this.pieceWaiters=[],this.resumeWaiters=[],this.deadlineRefs.clear(),this.priosByHandle.clear(),this.mod._lt_session_destroy(),this.mod.__FKN?.teardown?.())}},wc=8e3,Tc=e=>{try{e?.close()}catch{}},Ec=(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),Tc(r),n(null))},o=setTimeout(a,wc);r.on(`listening`,()=>{i||(i=!0,clearTimeout(o),n(r))}),r.on(`error`,a);try{t(r)}catch{a()}});async function Dc(e,t,n=4){try{return await Oc(e,t,n)}catch{return null}}async function Oc(e,t,n){for(let r=0;r<n;r++){let i=await Ec(()=>t.createSocket({type:`udp4`}),e=>e.bind(0,`0.0.0.0`));if(!i)return null;let a=i.address?.()?.port;if(!a)return Tc(i),null;let o=await Ec(()=>e.createServer(),e=>e.listen(a,`0.0.0.0`)),s=o?o.address?.()?.port:void 0,c=!!o&&s===a;if(o&&!c&&Tc(o),!c){if(r<n-1){Tc(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 kc(e){let t=e.moduleFactory??(await import(`./libtorrent-CnjRmD5O.js`)).default,n={net:e.net,dgram:e.dgram,storage:e.storage??null,debug:e.debug??!1},r=e.reserveListenPort===!1?Promise.resolve(null):Dc(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 Cc(i,e)}catch(e){throw a&&!a.adopted&&(Tc(a.server),Tc(a.udp)),e}return o.setReservedPort(a?a.port:null),o}const Ac=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},jc=25e5,Mc=e=>{if(!Number.isFinite(e)||e<=0)return 12;let t=Math.ceil(jc/e)+1,n=Math.max(2,Math.floor(8388608/e));return Math.min(Math.max(t,2),n)},Nc=e=>Mc(e)*Math.max(0,e),Pc=e=>Math.max(1,Math.floor(Nc(e)/2)),Fc=(e,t)=>Math.min(2e3,Math.max(50,Math.round(e/Math.max(t,25e4)*1e3))),Ic=(e,t,n,r=jc)=>{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 Lc=class{storages=/* @__PURE__ */ new Map;opened=/* @__PURE__ */ new Map;onNewStorage(e,t,n){let r=(async()=>{let r=await Rc(await navigator.storage.getDirectory(),t.replace(/^\/+/,``));this.storages.set(e,{rootDir:r,files:/* @__PURE__ */ new Map,opening:/* @__PURE__ */ new Map,fileMeta:n})})();return this.opened.set(e,r),r.then(()=>{this.opened.get(e)===r&&this.opened.delete(e)},()=>{}),r}async onRemoveStorage(e){this.opened.delete(e);let t=this.storages.get(e);if(t){for(let e of t.files.values())try{e.close()}catch{}this.storages.delete(e)}}read(e,t,n,r){let i=this.openFile(e,t),a=e=>{let t=new Uint8Array(r),i=e.read(t,{at:n});return i<r&&t.fill(0,i),t};return i instanceof Promise?i.then(a):a(i)}write(e,t,n,r){let i=this.openFile(e,t),a=i=>{try{let a=i.write(r,{at:n});if(a<r.length)throw console.error(`[opfs] short write`,{id:e,fileIndex:t,offset:n,want:r.length,wrote:a}),Error(`short write`)}catch(i){throw console.error(`[opfs] write failed`,{id:e,fileIndex:t,offset:n,len:r.length,err:String(i),errName:i?.name,errMsg:i?.message,isView:ArrayBuffer.isView(r),bytesType:Object.prototype.toString.call(r)}),i}};return i instanceof Promise?i.then(a).catch(n=>{throw console.error(`[opfs] openFile failed`,{id:e,fileIndex:t,err:String(n)}),n}):a(i)}async release(e){let t=this.storages.get(e);if(t){for(let e of t.files.values())try{e.flush(),e.close()}catch{}t.files.clear()}}async stop(e){return this.release(e)}async check(e){let t=!1;if(await this.opened.get(e)?.catch(()=>{t=!0}),t)return 2;let n=this.storages.get(e);if(!n)return 0;await this.release(e);for(let e of n.fileMeta)if(await this.hasBytes(n,e.path))return 2;return 0}async hasBytes(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(!r)return!1;let i=e.rootDir;try{for(let e of n)i=await i.getDirectoryHandle(e);return(await(await i.getFileHandle(r)).getFile()).size>0}catch(e){return e?.name!==`NotFoundError`}}async deleteFiles(e,t){let n=this.storages.get(e);if(n){for(let e of n.files.values())try{e.close()}catch{}n.files.clear();for(let e of n.fileMeta){let t=e.path.split(`/`).filter(Boolean),r=t.pop();if(!r)continue;let i=n.rootDir;for(let e of t)try{i=await i.getDirectoryHandle(e)}catch{i=null;break}if(i)try{await i.removeEntry(r)}catch{}}}}openFile(e,t){let n=this.storages.get(e);if(!n)throw Error(`unknown storage ${e}`);let r=n.files.get(t);if(r)return r;let i=n.opening.get(t);if(i)return i;let a=this.openFileSlow(e,t);return n.opening.set(t,a),a.finally(()=>n.opening.delete(t)),a}async openFileSlow(e,t){let n=this.storages.get(e),r=n.fileMeta[t];if(!r)throw Error(`unknown file ${t}`);let i=r.path.split(`/`).filter(Boolean),a=i.pop(),o=n.rootDir;for(let e of i)o=await o.getDirectoryHandle(e,{create:!0});let s=await(await o.getFileHandle(a,{create:!0})).createSyncAccessHandle();return n.files.set(t,s),s}};async function Rc(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 zc=[50,150,400,900,1500],Bc=e=>e?.name===`QuotaExceededError`,Vc=e=>new Promise(t=>setTimeout(t,e)),Hc=()=>{let e=new Lc,t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ 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 zc){if(Bc(o))break;if(i(e,n),await Vc(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)}},Uc=[5e3,15e3,3e4,6e4,12e4,3e5],Wc=1e4,Gc=/* @__PURE__ */ new Set([2,3]),Kc=/* @__PURE__ */ new Set([1,7]),qc=e=>!!e&&e.paused&&!e.autoManaged,Jc=()=>{let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=e=>Uc[Math.min(e,Uc.length-1)],a=i=>{e.delete(i),t.delete(i),n.delete(i),r.delete(i)};return{hold:(e,t,n=Wc)=>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(Kc.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`:Gc.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+Wc,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)}}},Yc=e=>!(e.flags&gc.localConnection)||!!(e.source&yc.incoming),Xc=e=>e.flags&gc.utpSocket?`utp`:`tcp`,Zc={total:0,byTransport:{}},Qc=e=>{let t={},n=0;for(let r of e)for(let e of r){if(!Yc(e)||e.connectionType!==0)continue;n+=1;let r=Xc(e);t[r]=(t[r]??0)+1}return{total:n,byTransport:t}},$c={activeSeconds:0,seedingSeconds:0},el=[`activeSeconds`,`seedingSeconds`,`downloaded`,`uploaded`,`wasted`],tl={activeSeconds:0,seedingSeconds:0,downloaded:0,uploaded:0,wasted:0},K=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0,nl=(e,t)=>({activeSeconds:Math.max(0,K(t.activeSeconds)-K(e.activeSeconds)),seedingSeconds:Math.max(0,K(t.seedingSeconds)-K(e.seedingSeconds))}),rl=(e,t,n)=>{let r=nl(t,n);return{activeSeconds:K(e?.activeSeconds)+r.activeSeconds,seedingSeconds:K(e?.seedingSeconds)+r.seedingSeconds}},il=(e,t)=>Object.fromEntries(el.map(n=>[n,Math.max(0,K(t[n])-K(e[n]))])),al=(e,t,n)=>{let r=il(t,n);return Object.fromEntries(el.map(t=>[t,K(e?.[t])+r[t]]))},ol=(e,t)=>Object.fromEntries(el.map(n=>[n,Math.max(K(e?.[n]),K(t?.[n]))])),sl=(e,t)=>t.activeSeconds-K(e?.activeSeconds)>=30||t.seedingSeconds-K(e?.seedingSeconds)>=30,cl=e=>!Number.isFinite(e)||e<=0?0:Math.min(1e9,Math.floor(e*.1)),ll=(e,t)=>!Number.isFinite(e)||e<=0?Math.max(0,t):Math.max(Math.min(.25*e,2e10),Math.max(0,t)),ul=({usedBytes:e,limitBytes:t})=>!Number.isFinite(t)||t<=0||!Number.isFinite(e)||e<0?!1:t-e<cl(t),dl=(e,t)=>e.usedAt-t.usedAt||(e.infoHash<t.infoHash?-1:+(e.infoHash>t.infoHash)),fl=({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(dl);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=cl(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=ll(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 pl=8,ml=2e4,hl=e=>typeof e.values==`function`,gl=async e=>{let t=0,n=0,r=async(e,i)=>{if(!(i>pl))for await(let a of e.values()){if(++n>ml)return;if(hl(a)){await r(a,i+1);continue}let e=await a.getFile().catch(()=>null);e&&(t+=e.size)}};try{return await r(e,0),t}catch{return null}},_l=(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)},vl,yl,bl=(e,t,n)=>{if(e!==void 0)return n!==yl&&(vl=void 0),yl=n,vl=vl===void 0?e:Math.min(vl,e),Math.max(vl,t??0)},xl=async e=>e.persisted?e.persisted().then(e=>e===!0).catch(()=>yl):void 0,Sl={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=>gl(e)).catch(()=>null):null,xl(e)]),i=_l(t,n);return{...t,usage:i,quota:bl(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 xl(e)??null??t},persisted:()=>globalThis.navigator?.storage?.persisted?.()??Promise.resolve(!1),getDirectory:()=>{let e=globalThis.navigator?.storage;return e?.getDirectory?e.getDirectory():Promise.reject(/* @__PURE__ */ Error(`this browser has no origin private file system`))}};const Cl=/^(?:[0-9a-f]{40}|[0-9a-f]{64}|[a-z2-7]{32})$/i,wl=({entries:e,listedHashes:t,claimedNames:n,attributable:r})=>e.filter(({name:e,kind:i})=>n.has(e)?!1:i===`directory`&&Cl.test(e)?!t.has(e.toLowerCase()):r).map(({name:e})=>e),Tl=async e=>{let t=[];for await(let n of e.values())t.push({name:n.name,kind:n.kind});return t},El=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},Dl=async(e,t,n)=>{let r=await El(e,t);if(!r)return[];let i=[];for(let e of wl({...n,entries:await Tl(r)}))try{await r.removeEntry(e,{recursive:!0}),i.push(e)}catch{}return i},Ol=async e=>{let t=0;for(let{name:n,kind:r}of await Tl(e))r===`file`&&n.startsWith(`.ripple-probe-`)&&await e.removeEntry(n).then(()=>!0,()=>!1)&&t++;return t},kl=e=>e?`/dl/`+e:`/dl`,Al=(e,t)=>e===kl(t),jl=(e,t)=>t&&(!e||e.ephemeral===!0),Ml=(e,t)=>e?{...t,ephemeral:jl(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,Nl=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`,Fl=`ripple:removed`,Il=(...e)=>{let t=/* @__PURE__ */ new Map;for(let n of e)if(Array.isArray(n))for(let e of n)typeof e?.infoHash==`string`&&e.infoHash&&typeof e.removedAt==`number`&&Number.isFinite(e.removedAt)&&t.set(e.infoHash,Math.max(t.get(e.infoHash)??e.removedAt,e.removedAt));return[...t].map(([e,t])=>({infoHash:e,removedAt:t}))},Ll=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}},Rl=(e,t,n)=>{let r=Ll(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}},zl=e=>`ripple:resume:`+e,Bl=e=>`ripple:torrent:`+e,Vl=e=>`ripple:thumb:`+e,Hl=e=>typeof e.getFile==`function`?e.getFile():Promise.resolve(e),Ul=e=>`/native/${e}`,Wl=e=>e===`/native`||!!e?.startsWith(`/native/`),Gl=e=>`/source/${e}`,Kl=e=>e===`/source`||!!e?.startsWith(`/source/`),ql=e=>Wl(e)||Kl(e),Jl=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()},Yl=(e,t,n=()=>null)=>{let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ 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=>ql(t)?0:e.usageOf(t),onNewStorage:(t,a,o)=>{if(Kl(a)){i.set(t,{savePath:a,files:o,handles:n(a)});return}if(!Wl(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 Jl(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 Jl(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)}}},Xl=(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))],Zl=({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]=Xl(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]=Xl(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},Ql=({wanted:e,firstLast:t})=>e===void 0&&!t,$l=e=>Kl(e)?`source`:Wl(e)?`folder`:`browser`,eu=(e,t)=>{if(e===`source`){if(!t)throw Error(`a source-backed torrent needs its infohash to name its save path`);return Gl(t)}return e===`folder`?t?Ul(t):`/dl`:kl(t)},tu=`ripple:rate-limits`,nu=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,ru=e=>{let t=e??{};return{down:nu(t.down)?t.down:0,up:nu(t.up)?t.up:0}},iu=/* @__PURE__ */ new Set(/* @__PURE__ */ `add-magnet.add-torrent-file.create-source.reserve-storage.start-source.read.cancel-read.remove.relocate.set-location.set-folder.set-plan.remove-missing.watch.unwatch.unwatch-owner.pause.resume.recheck.import-list.clear-list.start.retry.retry-now.flush-resume.inspect.set-flags.reannounce.queue-move.set-limits.set-session-limits.set-temporary`.split(`.`)),au=e=>`ripple:source:`+e;let q=null,ou=null,su=null;const cu=/* @__PURE__ */ new Map;let lu=!1;const J=[],uu=/* @__PURE__ */ new Map,Y=/* @__PURE__ */ new Map,du=/* @__PURE__ */ new Map,fu=/* @__PURE__ */ new Map,X=/* @__PURE__ */ new Set,pu=/* @__PURE__ */ new Set,mu=/* @__PURE__ */ new Set,hu=e=>{mu.delete(e),pu.add(e)},gu=e=>{pu.delete(e),mu.add(e)},_u=/* @__PURE__ */ new Map,Z=Jc(),vu=e=>e>=4294967040,Q=(e,t)=>self.postMessage(e,t??[]),yu=()=>J.map(e=>{let t=q.bitfield(e);return{handle:e,magnet:uu.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:bu(e),sessionUptime:xu(e),totals:$u(e)}}),bu=e=>{let t=q?.status(e),n=qu.get(e);return!t||!n?Ju.get(e)??$c:rl(Ju.get(e),n,t)},xu=e=>{let t=q?.status(e),n=qu.get(e);return t&&n?nl(n,t):$c},Su=async()=>await tc(`ripple:torrents`)??[],Cu=async e=>{let t=[];await rc(Pl,n=>{t=n??[];let r=t.findIndex(t=>t.infoHash===e.infoHash),i=Ml(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 rc(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})},wu=e=>{let t=Y.get(e);t&&$(t,{lastUsedAt:Date.now()},!0).catch(()=>{})},Tu=async e=>{await ic(zl(e)).catch(()=>{}),await ic(Bl(e)).catch(()=>{}),await ic(au(e)).catch(()=>{}),await ic(Vl(e)).catch(()=>{})},Eu=async e=>{let t=[];await rc(Pl,n=>t=(n??[]).filter(t=>t.infoHash!==e)),await rc(Fl,t=>Il(t,[{infoHash:e,removedAt:Date.now()}])),await Tu(e),Q({type:`list`,list:t})},Du=/* @__PURE__ */ new Set,Ou=/* @__PURE__ */ new Set,ku=/* @__PURE__ */ new Map,Au=/* @__PURE__ */ new Set;let ju=null,Mu=0,Nu=0,Pu=Zc;const Fu=e=>{let t=ju;return t==null||!J.includes(t)?null:(q.peers(t),e-Mu>=5e3&&(Mu=e,q.trackers(t)),{handle:t,peers:q.lastPeers(t),trackers:q.lastTrackers(t)})},Iu=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)]},Lu=(e,t,n,r,i=!1)=>{J.includes(e)||J.push(e),uu.set(e,t),n&&(Y.set(e,n),Au.add(e)),du.set(e,r),i?Du.add(e):Du.delete(e)},Ru=e=>{let t=J.indexOf(e);t>=0&&J.splice(t,1),uu.delete(e),Y.delete(e),du.delete(e),fu.delete(e),X.delete(e),Z.forget(e),od.delete(e),id.delete(e),pu.delete(e),mu.delete(e),_u.delete(e),ld.delete(e),ud.delete(e),Bu.delete(e),Vu.delete(e),Uu.delete(e),Wu.delete(e),Gu.delete(e),qu.delete(e),Ju.delete(e),Yu.delete(e),Xu.delete(e),Du.delete(e),Ou.delete(e),ku.delete(e),Au.delete(e)},zu=e=>{Ou.delete(e)&&(gu(e),q?.resumeTorrent(e),Z.hold(e,Date.now()))},Bu=/* @__PURE__ */ new Set,Vu=/* @__PURE__ */ new Map;let Hu={down:0,up:0};const Uu=/* @__PURE__ */ new Map,Wu=/* @__PURE__ */ new Set,Gu=/* @__PURE__ */ new Map;let Ku=0;const qu=/* @__PURE__ */ new Map,Ju=/* @__PURE__ */ new Map,Yu=/* @__PURE__ */ new Map,Xu=/* @__PURE__ */ new Map,Zu=e=>({activeSeconds:e.activeSeconds,seedingSeconds:e.seedingSeconds,downloaded:e.allTimeDownload,uploaded:e.allTimeUpload,wasted:e.wasted}),Qu=e=>({activeSeconds:e?.activeSeconds??0,seedingSeconds:e?.seedingSeconds??0,downloaded:e?.downloaded??0,uploaded:e?.uploaded??0,wasted:e?.wasted??0}),$u=e=>{let t=q?.status(e),n=Yu.get(e);return!t||!n?Xu.get(e)??tl:al(Xu.get(e),n,Zu(t))},ed=(e,t,n)=>{let r=Gu.get(e);Gu.set(e,r?{flags:r.flags&~n|t&n,mask:r.mask|n}:{flags:t&n,mask:n})},td=(e,t)=>{let n={...Uu.get(e)};return nu(t.down)&&(n.down=t.down),nu(t.up)&&(n.up=t.up),!nu(n.down)&&!nu(n.up)?!1:(Uu.set(e,n),Wu.add(e),!0)},nd=e=>{let t=Uu.get(e);q&&t&&(nu(t.down)&&q.setDownloadLimit(e,t.down),nu(t.up)&&q.setUploadLimit(e,t.up))},rd=6e3,id=/* @__PURE__ */ new Map,ad=(e,t)=>{let n=id.get(e);if(n?.size){for(let e of n)Q({type:`read-error`,id:e,error:t});n.clear()}},od=/* @__PURE__ */ new Set,sd=async e=>{let t=Y.get(e);if(!t||!q||od.has(e)||Kl(du.get(e)))return!1;od.add(e);try{let n=await q.saveResumeData(e);return J.includes(e)?(await nc(zl(t),n),!0):!1}catch(e){return console.error(`[worker] saving resume data failed`,String(e)),!1}finally{od.delete(e)}},cd=(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}},ld=/* @__PURE__ */ new Map,ud=/* @__PURE__ */ new Set,dd=e=>{let t=Vu.get(e);if(!q||!t||Ql(t))return;let n=q.files(e);n&&q.prioritizePieces(e,Zl({files:n.files,pieceLength:n.pieceLength,numPieces:Math.ceil(n.totalSize/n.pieceLength),wanted:t.wanted,firstLast:t.firstLast}))},fd=e=>{let t=ld.get(e);return t?[...t.values()].filter(e=>!e.held):[]},pd=e=>{if(!q)return;if(!J.includes(e)){ld.delete(e),ud.delete(e);return}let t=fd(e);if(!t.length){if(!q.files(e)){ud.add(e);return}ud.delete(e),q.clearStreamWindow(e),dd(e),Du.has(e)&&!X.has(e)&&!Ou.has(e)&&(Ou.add(e),hu(e),q.pauseTorrent(e),sd(e));return}zu(e);let n=q.files(e);if(!n){ud.add(e);return}let r=t.flatMap(({fileIndex:e,fromOffset:t,bulk:r})=>{let i={fileIndex:e,offset:t},a=n.files[e];return!r&&a?.size?[i,{fileIndex:e,offset:a.size-1}]:[i]}),i=t.some(e=>!e.bulk);q.setStreamWindow(e,r,{unclaimedPriority:G.skip,windowPieces:Mc(n.pieceLength),deadlineStepMs:Fc(n.pieceLength,q.status(e)?.downloadRate||3e6),deadlines:i})?ud.delete(e):ud.add(e)},md=e=>{X.add(e),Ou.delete(e),hu(e),Z.forget(e),q?.pauseTorrent(e)},hd=(e,t,n,r,i=!1,a)=>{if(!J.includes(t))return;let o=ld.get(t),s=!o?.size;o||ld.set(t,o=/* @__PURE__ */ new Map);let c=a??o.get(e)?.bulk;o.set(e,{fileIndex:n,fromOffset:r,...i?{held:i}:{},...c?{bulk:c}:{}}),s&&wu(t),pd(t)},gd=e=>{for(let[t,n]of ld){let r=!1;for(let t of[...n.keys()])e(t)&&(n.delete(t),r=!0);n.size||(ld.delete(t),r&&wu(t)),r&&pd(t)}},_d=(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},vd=(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},yd=()=>{if(!q)return 0;let e=0;for(let[t,n]of ld){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=/* @__PURE__ */ new Set;for(let{fileIndex:e}of n.values()){let n=cd(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},bd=(e,t,n,r,i)=>{if(!e||!J.includes(t))return;let a=ld.get(t)?.get(e);if(!a||a.held||a.fileIndex!==n){hd(e,t,n,r);return}let o=cd(t,n);if(!o)return;let s={fileOffset:o.file.offset,pieceLength:o.pieceLength,p1:o.p1};Ic(s,a.fromOffset,r,i)&&hd(e,t,n,r)},xd=async e=>{let t=e.filter(e=>!ql(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}},Sd=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}},Cd=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}),wd=async()=>{try{let{usage:e,quota:t}=await Sl.estimate();return!t||e===void 0?null:{usedBytes:e,limitBytes:t}}catch{return null}},Td=async e=>{for(let t=0;t<4e3;t+=250){await new Promise(e=>setTimeout(e,250));let t=await wd();if(!t||t.usedBytes<e)return t}return wd()},Ed=async(e,t,n,r,i={})=>{ad(t,r),e.removeTorrent(t,!0),Ru(t),await ic(zl(n)).catch(()=>{}),await $(n,{started:!1,paused:!1,...i})},Dd=(e,t,n)=>Ed(e,t,n,`torrent removed to make room`),Od=async(e,t,n,r)=>{let i=$l(du.get(t));if(i===r)return;let a=uu.get(t)??``,o=eu(r,n),s=X.has(t),c=Du.has(t);ad(t,`files moved`),e.removeTorrent(t,i===`browser`),Ru(t),await ic(zl(n)).catch(()=>{});let l=e.addMagnet(a,o);if(vu(l)){Q({type:`add-failed`,message:`Moving the files left the torrent unaddable`}),await $(n,{savePath:o,saveTo:r,started:!1});return}Lu(l,a,n,o,c),r===`folder`&&ed(l,_c.uploadMode,_c.uploadMode),s?(X.add(l),hu(l)):gu(l),Z.hold(l,Date.now()),await $(n,{savePath:o,saveTo:r,started:!0})},kd=(e,{infoHash:t,magnet:n,bytes:r,handles:i,paused:a})=>{let o=Gl(t);cu.set(o,i);let s=e.addTorrentFile(r,o);return vu(s)?(cu.delete(o),null):(Lu(s,n,t,o,!1),ed(s,_c.uploadMode,_c.uploadMode),a&&(X.add(s),hu(s)),Z.hold(s,Date.now()),s)},Ad=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||!Al(a.savePath,i)||ld.get(e)?.size||id.get(e)?.size||t-(ku.get(e)??0)<6e4)continue;let o=a.lastUsedAt??a.addedAt;if(t-o<15e3)continue;let s=await ou?.usageOf(a.savePath)??0;s<=0||r.push({infoHash:i,usedAt:o,bytesOnDisk:s})}return r};let jd=!1;const Md=e=>{let t=ul(e);t!==jd&&(jd=t,Q({type:`storage-full`,full:t,usedBytes:e.usedBytes,limitBytes:e.limitBytes}))},Nd=/* @__PURE__ */ new Set;let Pd=!1;const Fd=async()=>{if(!q||Pd)return 0;Pd=!0;try{let e=await Su(),t=new Set(e.map(e=>e.infoHash.toLowerCase()));for(let e of Nd)t.add(e.toLowerCase());let n=/* @__PURE__ */ new Set,r=!0;for(let e of J){let i=Y.get(e);if(i&&t.add(i.toLowerCase()),(du.get(e)??`/dl`)!==`/dl`)continue;let a=Iu(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 Dl(i,`/dl`,{listedHashes:t,claimedNames:n,attributable:r});return await Ol(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 Id=!1;const Ld=async()=>{let e=q;if(!e||Id)return;Id=!0;let t=null;try{let n=await wd();if(!n)return;t=n;let r=yd(),i=await Ad(await Su(),Date.now());for(;i.length;){let[a]=fl({...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||ld.get(o)?.size||id.get(o)?.size)continue;let s=n.usedBytes;t=null,await Dd(e,o,a);let c=await Td(s);if(!c)return;n=c,t=c}ul(n)&&await Fd()&&(n=await Td(n.usedBytes)??n),t=n}catch(e){console.error(`[worker] storage budget pass failed`,String(e))}finally{Id=!1,t&&Md(t)}},Rd=async()=>{let e=console.error.bind(console);if(console.error=(...t)=>{e(...t);try{Q({type:`worker-error`,args:t.map(String)})}catch{}},!await Sd()){Q({type:`storage-unavailable`});return}Su().then(e=>{e.length&&Q({type:`list`,list:e})}).catch(()=>{});let t=Promise.race([tc(tu).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]);ou=Yl(Hc(),()=>su,e=>cu.get(e)??null),q=await kc({net:As,dgram:Bs,storage:ou,utpReceiveBufferBytes:4194304});for(let e=0;e<30;e++)q.tick();Hu=ru(await t),q.setRateLimits({download:Hu.down,upload:Hu.up});try{let e=await Su(),t=!await xd(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 tc(zl(r.infoHash)),a=await tc(Bl(r.infoHash));if(t&&i&&i.byteLength){await ic(zl(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);vu(o)||(Lu(o,r.magnet,r.infoHash,e,r.ephemeral===!0),Vu.set(o,{wanted:r.wantedFiles,firstLast:r.firstLast}),Bu.add(o),td(o,{down:r.downloadLimit,up:r.uploadLimit}),Ju.set(o,{activeSeconds:r.activeSeconds??0,seedingSeconds:r.seedingSeconds??0}),Xu.set(o,Qu(r)),r.paused?(X.add(o),hu(o)):gu(o),Z.hold(o,Date.now()))}n&&await nc(Pl,e)}catch(e){console.error(`[worker] restore failed`,e)}Q({type:`ready`}),lu=!0,Q({type:`list`,list:await Su().catch(()=>[])}),Q({type:`state`,torrents:yu(),reachable:q.reachable(),inboundNow:Pu,rateLimits:{...Hu}}),setInterval(()=>{if(!q)return;let e=Date.now();q.popAlerts();for(let e of J)q.postStatus(e);for(let e of[...Bu])q.files(e)&&(Bu.delete(e),fd(e).length||pd(e));for(let e of[...ud])pd(e);for(let e of[...Wu])q.status(e)&&(Wu.delete(e),nd(e));for(let e of J){if(qu.has(e))continue;let t=q.status(e);t&&(qu.set(e,{activeSeconds:t.activeSeconds,seedingSeconds:t.seedingSeconds}),Yu.set(e,Zu(t)))}for(let[e,t]of[...Gu])q.status(e)&&(Gu.delete(e),q.setFlags(e,t.flags>>>0,t.mask>>>0));for(let e of[...Au]){let[t]=Iu(e);if(!t)continue;Au.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 pu){let t=q.status(e);t&&!Kc.has(t.state)&&(qc(t)?pu.delete(e):q.pauseTorrent(e))}for(let e of mu){if(X.has(e)||Ou.has(e)){mu.delete(e);continue}let t=q.status(e);if(t&&!Kc.has(t.state)){if(!t.paused){mu.delete(e);continue}if(t.autoManaged||t.errorCode){mu.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&&Cd(n),X.has(t)||Ou.has(t),e)}for(let{handle:t,reason:n}of Z.due(e))n===`stalled`&&q.pauseTorrent(t),q.resumeTorrent(t);if(e-Nu>=2e3){Nu=e;for(let e of J)q.peers(e)}Pu=Qc(J.map(e=>q.lastPeers(e))),Q({type:`state`,torrents:yu(),reachable:q.reachable(),inboundNow:Pu,detail:Fu(e),rateLimits:{...Hu}});for(let t of J){let n=q.status(t);if(!n||n.state!==4&&n.state!==5||fu.get(t)===n.paused||od.has(t))continue;let r=_u.get(t);if(r&&e<r.at)continue;let i=n.paused;sd(t).then(e=>{if(e){fu.set(t,i),_u.delete(t);return}let n=(_u.get(t)?.tries??0)+1;_u.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&&sd(e)}let e=!1;for(let t of J){let n=q.status(t),r=Y.get(t),i=qu.get(t);if(!n||!r||!i)continue;e=!0;let a=rl(Ju.get(t),i,n);if(!sl(Ju.get(t),a))continue;Ju.set(t,a),qu.set(t,{activeSeconds:n.activeSeconds,seedingSeconds:n.seedingSeconds});let o=Zu(n),s=al(Xu.get(t),Yu.get(t)??o,o);Xu.set(t,s),Yu.set(t,o),$(r,{activeSeconds:a.activeSeconds,seedingSeconds:a.seedingSeconds,downloaded:s.downloaded,uploaded:s.uploaded,wasted:s.wasted},!0).catch(()=>{})}e&&Date.now()-Ku>=3e5&&(Ku=Date.now(),Su().then(e=>Q({type:`list`,list:e})).catch(()=>{}))},15e3),setInterval(()=>{Ld()},1e4),Ld(),setTimeout(()=>{Fd(),setInterval(()=>{Fd()},6e5)},6e4),self.addEventListener(`online`,()=>Z.retryNow(Date.now()))},zd=async(e,t)=>{try{if(t.type===`add-magnet`){let n=Ac(t.magnet),r=n?J.find(e=>Y.get(e)===n):void 0;if(r!==void 0)n&&!t.ephemeral?(Du.delete(r),zu(r),await $(n,{ephemeral:!1,lastUsedAt:Date.now()})):wu(r),Q({type:`added`,handle:r,magnet:uu.get(r)||t.magnet});else{let r=n?(await Su()).find(e=>e.infoHash===n):void 0,i=t.savePath||r?.savePath||kl(n),a=jl(r,t.ephemeral===!0),o=e.addMagnet(t.magnet,i);if(vu(o)){Q({type:`add-failed`,message:`That is not a valid magnet link`});return}Lu(o,t.magnet,n,i,a),Vu.set(o,{wanted:r?.wantedFiles,firstLast:r?.firstLast}),t.hold===!0&&Bu.add(o),td(o,{down:r?.downloadLimit,up:r?.uploadLimit}),Ju.set(o,{activeSeconds:r?.activeSeconds??0,seedingSeconds:r?.seedingSeconds??0}),Xu.set(o,Qu(r)),Z.hold(o,Date.now());let s=Date.now();t.paused===!0&&md(o),n&&await Cu({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}),Ld()}}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 nc(Bl(n),i);let a=kd(e,{infoHash:n,magnet:t.magnet,bytes:i,handles:r,paused:!1});if(a===null){await ic(Bl(n)).catch(()=>{}),Q({type:`add-failed`,message:`The engine refused the torrent that was just built`});return}let o=Date.now();await Cu({infoHash:n,magnet:t.magnet,savePath:Gl(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,...Nl({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:uu.get(i[0])??``});return}let a=await tc(Bl(n));if(!a?.byteLength){Q({type:`add-failed`,message:`The torrent this was built from is no longer stored`});return}let o=(await Su()).find(e=>e.infoHash===n),s=kd(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}Ju.set(s,{activeSeconds:o?.activeSeconds??0,seedingSeconds:o?.seedingSeconds??0}),Xu.set(s,Qu(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(vu(i)){Q({type:`add-failed`,message:`That file is not a valid .torrent`});return}Lu(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),Ru(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(`&`);Lu(i,s,a,n),await nc(Bl(a),r);let c=Date.now();t.paused===!0&&md(i);let l=t.saveTo===`browser`||t.saveTo===`folder`?{saveTo:t.saveTo}:{};await Cu({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}:{}}),Nd.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(zu(t.handle),ku.set(t.handle,Date.now()),X.has(t.handle)&&!_d(t.handle,t.fileIndex,t.offset,t.len)){Q({type:`read-error`,id:t.id,error:`torrent paused`});return}if(t.prioritize!==!1)bd(t.viewer,t.handle,t.fileIndex,t.offset,t.len);else if(!_d(t.handle,t.fileIndex,t.offset,t.len)){Q({type:`read-error`,id:t.id,error:`not downloaded`});return}let n=id.get(t.handle);n||id.set(t.handle,n=/* @__PURE__ */ new Set),n.add(t.id);try{for(let r=0;;r++)try{let r=t.viewer?ld.get(t.handle)?.get(t.viewer)?.bulk===!0:!1,i=await e.read(t.handle,t.fileIndex,t.offset,t.len,{timeoutMs:rd,...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=vd(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)*rd,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?ld.get(t.handle)?.get(t.viewer):void 0;t.prioritize!==!1&&t.viewer&&o&&!o.held&&pd(t.handle)}}finally{n.delete(t.id),J.includes(t.handle)&&ku.set(t.handle,Date.now())}}else if(t.type===`cancel-read`)id.get(t.handle)?.delete(t.id);else if(t.type===`remove`){let n=Y.get(t.handle);ad(t.handle,`torrent removed`),e.removeTorrent(t.handle,!!t.deleteFiles),Ru(t.handle),n&&await Eu(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;Vu.set(t.handle,{wanted:e,firstLast:n}),dd(t.handle);let r=Y.get(t.handle);r&&await $(r,{wantedFiles:e,firstLast:n})}else if(t.type===`set-folder`)su=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?Du.add(n):(Du.delete(n),zu(n))),await $(t.infoHash,{ephemeral:e})}}else if(t.type===`reserve-storage`)typeof t.infoHash==`string`&&t.infoHash&&(t.on===!1?Nd.delete(t.infoHash):Nd.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 Od(e,i,n,r)}else if(t.type===`import-list`){let e=[];await rc(Fl,n=>e=Il(n,t.removed));let n=[],r=[],i=!1;await rc(Pl,a=>{let o=Rl(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=Nl(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=ol(Qu(r),Qu(e));for(let e of el)(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,...Qu(e)};n.push(a),s.set(a.infoHash,a),i=!0}return n});for(let e of r)await Tu(e.infoHash);i&&Q({type:`list`,list:n})}else if(t.type===`start`){let n=(await Su()).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 tc(Bl(n.infoHash)),i=r&&r.byteLength?e.addTorrentFile(r,t):e.addMagnet(n.magnet,t);if(vu(i)){Q({type:`add-failed`,message:`That torrent could not be read`});return}Lu(i,n.magnet,n.infoHash,t,!1),td(i,{down:n.downloadLimit,up:n.uploadLimit}),Z.hold(i,Date.now()),Q({type:`state`,torrents:yu(),reachable:e.reachable()}),await Cu({...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&&(ad(n,`torrent removed`),e.removeTorrent(n,!0),Ru(n)),await Eu(t.infoHash)}}else if(t.type===`clear-list`){for(let t of[...J])ad(t,`torrent removed`),e.removeTorrent(t,!0),Ru(t);let t=[];await rc(Pl,e=>(t=e??[],[])),await ic(Fl).catch(()=>{});for(let e of t)await ic(zl(e.infoHash)).catch(()=>{}),await ic(Bl(e.infoHash)).catch(()=>{});Q({type:`list`,list:[]})}else if(t.type===`pause`){X.add(t.handle),Ou.delete(t.handle),hu(t.handle),Z.forget(t.handle),e.pauseTorrent(t.handle),ad(t.handle,`torrent paused`),sd(t.handle);let n=Y.get(t.handle);n&&await $(n,{paused:!0})}else if(t.type===`resume`){X.delete(t.handle),Ou.delete(t.handle),gu(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 ic(zl(n)).catch(()=>{}),fu.delete(t.handle),ad(t.handle,`torrent rechecking`),X.delete(t.handle),pu.delete(t.handle),mu.delete(t.handle),Ou.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=>sd(e)));else if(t.type===`watch`)t.readLen==null?hd(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.held===!0,t.bulk===!0||void 0):bd(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.readLen);else if(t.type===`unwatch`)gd(e=>e===t.viewer);else if(t.type===`set-flags`)e.setFlags(t.handle,t.flags>>>0,t.mask>>>0),sd(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=nu(t.down)?t.down:void 0,r=nu(t.up)?t.up:void 0;td(t.handle,{down:n,up:r})&&e.status(t.handle)&&(Wu.delete(t.handle),nd(t.handle));let i=Y.get(t.handle);if(i){let e={};n!==void 0&&(e.downloadLimit=n),r!==void 0&&(e.uploadLimit=r),Object.keys(e).length&&await $(i,e)}}else if(t.type===`set-session-limits`)nu(t.down)&&(Hu.down=t.down),nu(t.up)&&(Hu.up=t.up),e.setRateLimits({download:Hu.down,upload:Hu.up}),await nc(tu,{...Hu});else if(t.type===`inspect`){let e=typeof t.handle==`number`?t.handle:null;e!==ju&&(ju=e,Mu=0)}else t.type===`unwatch-owner`&&gd(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)})}},Bd=/* @__PURE__ */ new Set([`read`,`add-torrent-file`]);let Vd=Promise.resolve();self.addEventListener(`message`,e=>{let t=e.data;if(!t||typeof t!=`object`||typeof t.type!=`string`||!iu.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(Bd.has(t.type)){zd(n,t);return}Vd=Vd.then(()=>zd(n,t))}),Rd().catch(e=>Q({type:lu?`error`:`fatal`,message:String(e?.stack??e)}));
23
+ var n=uo(),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)}})),xs=/* @__PURE__ */ t((e=>{var t=bs().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):``}})),Ss=/* @__PURE__ */ t(((e,t)=>{var n=hs().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})),Cs=/* @__PURE__ */ t(((e,t)=>{var n;function r(e,t,n){return t=i(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=a(e,`string`);return typeof t==`symbol`?t:String(t)}function a(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var o=Ss(),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}})),ws=/* @__PURE__ */ t(((e,t)=>{t.exports=function(){throw Error(`Readable.from is not available in the browser`)}})),Ts=/* @__PURE__ */ t(((e,t)=>{t.exports=E;var n;E.ReadableState=T,ao().EventEmitter;var r=function(e,t){return e.listeners(t).length},i=so(),a=uo().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=fs(),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=ps(),f=ms(),p=gs().getHighWaterMark,m=hs().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;oo()(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||=ys(),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||=xs().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=ys(),!(this instanceof E))return new E(e);var t=this instanceof n;this._readableState=new T(e,this,t),this.readable=!0,e&&(typeof e.read==`function`&&(this._read=e.read),typeof e.destroy==`function`&&(this._destroy=e.destroy)),i.call(this)}Object.defineProperty(E.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),E.prototype.destroy=f.destroy,E.prototype._undestroy=f.undestroy,E.prototype._destroy=function(e,t){t(e)},E.prototype.push=function(e,t){var n=this._readableState,r;return n.objectMode?r=!0:typeof e==`string`&&(t||=n.defaultEncoding,t!==n.encoding&&(e=a.from(e,t),t=``),r=!0),D(this,e,t,!1,r)},E.prototype.unshift=function(e){return D(this,e,null,!0,!1)};function D(e,t,n,r,i){u(`readableAddChunk`,t);var o=e._readableState;if(t===null)o.reading=!1,te(e,o);else{var c;if(i||(c=k(o,t)),c)S(e,c);else if(o.objectMode||t&&t.length>0){if(typeof t!=`string`&&!o.objectMode&&Object.getPrototypeOf(t)!==a.prototype&&(t=s(t)),r)o.endEmitted?S(e,new v):O(e,o,t,!0);else if(o.ended)S(e,new g);else if(o.destroyed)return!1;else o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||t.length!==0?O(e,o,t,!1):P(e,o)):O(e,o,t,!1)}else r||(o.reading=!1,P(e,o))}return!o.ended&&(o.length<o.highWaterMark||o.length===0)}function O(e,t,n,r){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit(`data`,n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&M(e)),P(e,t)}function k(e,t){var n;return!c(t)&&typeof t!=`string`&&t!==void 0&&!e.objectMode&&(n=new h(`chunk`,[`string`,`Buffer`,`Uint8Array`],t)),n}E.prototype.isPaused=function(){return this._readableState.flowing===!1},E.prototype.setEncoding=function(e){y||=xs().StringDecoder;var t=new y(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r=``;n!==null;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),r!==``&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var A=1073741824;function ee(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function j(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=ee(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}E.prototype.read=function(e){u(`read`,e),e=parseInt(e,10);var t=this._readableState,n=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark===0?t.length>0:t.length>=t.highWaterMark)||t.ended))return u(`read: emitReadable`,t.length,t.ended),t.length===0&&t.ended?ie(this):M(this),null;if(e=j(e,t),e===0&&t.ended)return t.length===0&&ie(this),null;var r=t.needReadable;u(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,u(`length less than watermark`,r)),t.ended||t.reading?(r=!1,u(`reading or ended`,r)):r&&(u(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=j(n,t)));var i=e>0?re(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&ie(this)),i!==null&&this.emit(`data`,i),i};function te(e,t){if(u(`onEofChunk`),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?M(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,N(e)))}}function M(e){var t=e._readableState;u(`emitReadable`,t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u(`emitReadable`,t.flowing),t.emittedReadable=!0,process.nextTick(N,e))}function N(e){var t=e._readableState;u(`emitReadable_`,t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(`readable`),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,B(e)}function P(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(F,e,t))}function F(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var n=t.length;if(u(`maybeReadMore read 0`),e.read(0),n===t.length)break}t.readingMore=!1}E.prototype._read=function(e){S(this,new _(`_read()`))},E.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,u(`pipe count=%d opts=%j`,i.pipesCount,t);var a=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr?s:g;i.endEmitted?process.nextTick(a):n.once(`end`,a),e.on(`unpipe`,o);function o(e,t){u(`onunpipe`),e===n&&t&&t.hasUnpiped===!1&&(t.hasUnpiped=!0,d())}function s(){u(`onend`),e.end()}var c=I(n);e.on(`drain`,c);var l=!1;function d(){u(`cleanup`),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`drain`,c),e.removeListener(`error`,p),e.removeListener(`unpipe`,o),n.removeListener(`end`,s),n.removeListener(`end`,g),n.removeListener(`data`,f),l=!0,i.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}n.on(`data`,f);function f(t){u(`ondata`);var r=e.write(t);u(`dest.write`,r),r===!1&&((i.pipesCount===1&&i.pipes===e||i.pipesCount>1&&oe(i.pipes,e)!==-1)&&!l&&(u(`false write response, pause`,i.awaitDrain),i.awaitDrain++),n.pause())}function p(t){u(`onerror`,t),g(),e.removeListener(`error`,p),r(e,`error`)===0&&S(e,t)}w(e,`error`,p);function m(){e.removeListener(`finish`,h),g()}e.once(`close`,m);function h(){u(`onfinish`),e.removeListener(`close`,m),g()}e.once(`finish`,h);function g(){u(`unpipe`),n.unpipe(e)}return e.emit(`pipe`,n),i.flowing||(u(`pipe resume`),n.resume()),e};function I(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,B(e))}}E.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=oe(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),--t.pipesCount,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit(`unpipe`,this,n),this)},E.prototype.on=function(e,t){var n=i.prototype.on.call(this,e,t),r=this._readableState;return e===`data`?(r.readableListening=this.listenerCount(`readable`)>0,r.flowing!==!1&&this.resume()):e===`readable`&&!r.endEmitted&&!r.readableListening&&(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,u(`on readable`,r.length,r.reading),r.length?M(this):r.reading||process.nextTick(R,this)),n},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var n=i.prototype.removeListener.call(this,e,t);return e===`readable`&&process.nextTick(L,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(L,this),t};function L(e){var t=e._readableState;t.readableListening=e.listenerCount(`readable`)>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount(`data`)>0&&e.resume()}function R(e){u(`readable nexttick read 0`),e.read(0)}E.prototype.resume=function(){var e=this._readableState;return e.flowing||(u(`resume`),e.flowing=!e.readableListening,z(this,e)),e.paused=!1,this};function z(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ne,e,t))}function ne(e,t){u(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),B(e),t.flowing&&!t.reading&&e.read(0)}E.prototype.pause=function(){return u(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(u(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function B(e){var t=e._readableState;for(u(`flow`,t.flowing);t.flowing&&e.read()!==null;);}E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(u(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){u(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(n.objectMode||i&&i.length)&&(t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<C.length;a++)e.on(C[a],this.emit.bind(this,C[a]));return this._read=function(t){u(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(E.prototype[Symbol.asyncIterator]=function(){return b===void 0&&(b=Cs()),b(this)}),Object.defineProperty(E.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=re,Object.defineProperty(E.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function re(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function ie(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(ae,t,e))}function ae(e,t){if(u(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(E.from=function(e,t){return x===void 0&&(x=ws()),x(E,e,t)});function oe(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),Es=/* @__PURE__ */ t(((e,t)=>{t.exports=l;var n=hs().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=ys();oo()(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)}})),Ds=/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=Es();oo()(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)}})),Os=/* @__PURE__ */ t(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=hs().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=Ss()),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})),ks=/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=ao().EventEmitter;oo()(r,n),r.Readable=Ts(),r.Writable=vs(),r.Duplex=ys(),r.Transform=Es(),r.PassThrough=Ds(),r.finished=Ss(),r.pipeline=Os(),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}})),As=/* @__PURE__ */ n({Server:()=>Fs,Socket:()=>Ps,_default:()=>zs,connect:()=>Is,createConnection:()=>Ls,createServer:()=>Rs,default:()=>zs,isIP:()=>to,isIPv4:()=>$a,isIPv6:()=>eo,t:()=>Ns}),js=ks(),Ms=ao(),Ns=/* @__PURE__ */ i({Server:()=>Fs,Socket:()=>Ps,_default:()=>zs,connect:()=>Is,createConnection:()=>Ls,createServer:()=>Rs,default:()=>zs,isIP:()=>to,isIPv4:()=>$a,isIPv6:()=>eo}),Ps=class extends js.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??=Va(`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(/* @__PURE__ */ Error(`Socket not connected`));return}this._webVPNTcpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not connected`);await t.writer.ready,await t.writer.write(e),this._restartTimeoutTimer(),n()}).catch(n)}connect(...e){let t=no(...e),n=this.__webvpn_tcp_socket_init__(Ra(`an outbound tcp socket`).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`,/* @__PURE__ */ Error(`Cannot set socket option before connect`));return}this._webVPNTcpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}write(e,t,...n){return super.write(e,t,...n)}address(){return this._localAddress??{}}unref(){return this}ref(){return this}autoSelectFamilyAttemptedAddresses;bufferSize;bytesRead;bytesWritten;connecting;pending;get localAddress(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.address}get localPort(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.port}get localFamily(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.family}readyState;get remoteAddress(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.address}get remotePort(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.port}get remoteFamily(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.family}timeout},Fs=class extends Ms.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??=Va(`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=no(...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=>Ra(`a tcp listener`).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](){}},Is=(e,t)=>new Ps().connect(e,t),Ls=(e,t)=>new Ps().connect(e,t),Rs=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new Fs(e);return t&&n.on(`connection`,t),n},zs={Socket:Ps,Server:Fs,connect:Is,createConnection:Ls,createServer:Rs,isIP:to,isIPv4:$a,isIPv6:eo},Bs=/* @__PURE__ */ n({Socket:()=>Us,createSocket:()=>Ys,default:()=>Xs,t:()=>Hs}),Vs=uo(),Hs=/* @__PURE__ */ i({Socket:()=>Us,createSocket:()=>Ys,default:()=>Xs}),Us=class extends Ms.EventEmitter{_type;_localAddress;_remoteAddress;_connectedLocally;_connectGeneration=0;_destroyed=!1;_busyRelease;_webVPNUdpSocketPromise;_dataPort;_socketId;_sendQueue=[];_sendQueueBytes=0;_sendFlushScheduled=!1;_peerTailCache=/* @__PURE__ */ 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`,/* @__PURE__ */ Error(`Cannot set socket option before bind`));return}this._webVPNUdpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}_dataPortAcks=!1;_dataPortConsumedBytes=0;_dataPortAckedBytes=0;_ackDataPortBatch(e){if(!this._dataPortAcks||!this._dataPort||(this._dataPortConsumedBytes+=e,this._dataPortAckedBytes!==0&&this._dataPortConsumedBytes-this._dataPortAckedBytes<524288))return;this._dataPortAckedBytes=this._dataPortConsumedBytes;let t={type:Qa,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=qs(n)),s+=n.byteLength,d=t.getUint16(s),s+=2}let f=t.getUint32(s);s+=4;try{this.emit(`message`,Vs.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 Ws;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let i=Xa.Address4.isValid(e)?Ks(e):Js(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(Xa.Address4.isValid(e)){let n=Ks(e),r=t&&Xa.Address4.isValid(t)?Ks(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(Xa.Address6.isValid(e)){let t=Js(e);this._setUdpOption({type:7,group:t,ifIndex:0})}else this.emit(`error`,/* @__PURE__ */ Error(`Invalid multicast address: ${e}`))}address(){if(!this._localAddress)throw Error(`EBADF`);return this._localAddress}bind(...e){let t=ro(...e),n=this._type===`udp6`?`::`:`0.0.0.0`,r=this.__webvpn_udp_socket_init__(Ra(`a udp socket`).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??=Va(`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`,Vs.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(Xa.Address4.isValid(e)){let n=Ks(e),r=t&&Xa.Address4.isValid(t)?Ks(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(Xa.Address6.isValid(e)){let t=Js(e);this._setUdpOption({type:8,group:t,ifIndex:0})}else this.emit(`error`,/* @__PURE__ */ Error(`Invalid multicast address: ${e}`))}getRecvBufferSize(){return this._lastRecvBufferSize}getSendBufferSize(){return this._lastSendBufferSize}getSendQueueSize(){return 0}getSendQueueCount(){return 0}ref(){return this}remoteAddress(){if(!this._remoteAddress)throw Error(`ERR_SOCKET_DGRAM_NOT_CONNECTED`);return{address:this._remoteAddress.address,family:this._remoteAddress.family,port:this._remoteAddress.port}}send(...e){this._webVPNUdpSocketPromise||this.bind();let t=io(...e),n=Gs(t.message),r=n;if(t.hasRange){let{offset:e,length:i}=t;if(!Number.isInteger(e)||e<0||e>n.byteLength)throw Object.assign(/* @__PURE__ */ RangeError(`"offset" is outside of buffer bounds`),{code:`ERR_BUFFER_OUT_OF_BOUNDS`});if(!Number.isInteger(i)||i<0||i>n.byteLength-e)throw Object.assign(/* @__PURE__ */ RangeError(`"length" is outside of buffer bounds`),{code:`ERR_BUFFER_OUT_OF_BOUNDS`});r=n.subarray(e,e+i)}let i=this._type===`udp6`?`::1`:`127.0.0.1`;if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(e=>{if(!e)throw Error(`Socket not bound`);let n=t.callback,a=t.address??i,o=this._remoteAddress!==void 0&&t.address===void 0;if(this._dataPort&&(o||Xa.Address4.isValid(a)||Xa.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)})}},Ws=new Uint8Array([2]),Gs=e=>{if(typeof e==`string`)return Za.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(Gs),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)},Ks=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)},qs=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(`:`)}`},Js=e=>{let t=new Xa.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)))},Ys=(e,t)=>{let n=new Us(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},Xs={Socket:Us,createSocket:Ys};function Zs(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function Qs(e,t){let n,r=()=>{if(n)return n;let r=indexedDB.open(e);return r.onupgradeneeded=()=>r.result.createObjectStore(t),n=Zs(r),n.then(e=>{e.onclose=()=>n=void 0},()=>{}),n};return(e,n)=>r().then(r=>n(r.transaction(t,e).objectStore(t)))}let $s;function ec(){return $s||=Qs(`keyval-store`,`keyval`),$s}function tc(e,t=ec()){return t(`readonly`,t=>Zs(t.get(e)))}function nc(e,t,n=ec()){return n(`readwrite`,n=>(n.put(t,e),Zs(n.transaction)))}function rc(e,t,n=ec()){return n(`readwrite`,n=>new Promise((r,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),r(Zs(n.transaction))}catch(e){i(e)}}}))}function ic(e,t=ec()){return t(`readwrite`,t=>(t.delete(e),Zs(t.transaction)))}var ac={checkingFiles:1,downloadingMetadata:2,downloading:3,finished:4,seeding:5,checkingResumeData:7},oc=/^incoming connection from (\S+) \(([^)]*)\)/,sc=/^successfully listening on \[([^\]]*)\] (\S+)/,cc=/^listening on .* failed:/,lc=new TextDecoder,uc=4026531841,dc=4026531842,fc=4026531843,pc=4026531844,mc=4026531845,hc=4026531846,gc={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},_c={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},vc={top:0,up:1,down:2,bottom:3},yc={tracker:1,dht:2,pex:4,lsd:8,resumeData:16,incoming:32},G={skip:0,low:1,normal:4,top:7},bc=6e4,xc=12,Sc=1e3,Cc=class{mod;storage;destroyed=!1;fallbackTimer;filesByHandle=/* @__PURE__ */ new Map;bitfieldByHandle=/* @__PURE__ */ new Map;statusByHandle=/* @__PURE__ */ new Map;pieceWaiters=[];resumeByHandle=/* @__PURE__ */ new Map;resumeWaiters=[];peersByHandle=/* @__PURE__ */ new Map;trackersByHandle=/* @__PURE__ */ new Map;peerWaiters=[];trackerWaiters=[];priosByHandle=/* @__PURE__ */ new Map;deadlineRefs=/* @__PURE__ */ new Map;reachability={listening:{},listenFailed:[],inbound:0,inboundByTransport:{},lastInbound:null,port:null};constructor(e,t){if(this.mod=e,this.storage=t.storage??null,t.utpReceiveBufferBytes&&e._lt_set_utp_receive_buffer(t.utpReceiveBufferBytes),t.enableDht===!1&&e._lt_set_dht(0),t.rateLimits){let{download:n,upload:r,limitLocalPeers:i}=t.rateLimits;e._lt_session_set_rate_limits(Math.max(0,Math.floor(n??0)),Math.max(0,Math.floor(r??0)),i==null?-1:+!!i)}if(e._lt_session_create()!==0)throw Error(`lt_session_create returned non-zero`);let n=t.tickIntervalMs??250;this.fallbackTimer=setInterval(()=>this.tick(),n)}addMagnet(e,t=`/downloads`){let n=this.mod,r=n.stringToNewUTF8(e),i=n.stringToNewUTF8(t);try{return n._lt_session_add_magnet(r,i)>>>0}finally{n._free(r),n._free(i)}}addTorrentFile(e,t=`/downloads`){let n=this.mod,r=n._malloc(e.length);n.HEAPU8.set(e,r);let i=n.stringToNewUTF8(t);try{return n._lt_session_add_torrent_file(r,e.length,i)>>>0}finally{n._free(r),n._free(i)}}addTorrentWithResume(e,t=`/downloads`){let n=this.mod,r=n._malloc(e.length);n.HEAPU8.set(e,r);let i=n.stringToNewUTF8(t);try{return n._lt_session_add_torrent_with_resume(r,e.length,i)>>>0}finally{n._free(r),n._free(i)}}removeTorrent(e,t=!1){this.mod._lt_session_remove_torrent_ex(e,+!!t),this.failPieceWaiters(/* @__PURE__ */ Error(`read: torrent ${e} was removed`),e),this.filesByHandle.delete(e),this.bitfieldByHandle.delete(e),this.statusByHandle.delete(e),this.resumeByHandle.delete(e),this.priosByHandle.delete(e),this.deadlineRefs.delete(e)}pauseTorrent(e){this.mod._lt_torrent_pause(e)}resumeTorrent(e){this.mod._lt_torrent_resume(e)}forceRecheck(e){this.mod._lt_torrent_force_recheck(e)}saveResumeData(e,t=8e3){return this.mod._lt_torrent_save_resume_data(e),new Promise((n,r)=>{let i={handle:e,resolve:n};this.resumeWaiters.push(i),setTimeout(()=>{let e=this.resumeWaiters.indexOf(i);e>=0&&(this.resumeWaiters.splice(e,1),r(/* @__PURE__ */ Error(`save_resume_data timed out`)))},t)})}peers(e,t=4e3){return this.mod._lt_torrent_post_peers(e),this.awaitList(this.peerWaiters,this.peersByHandle,e,t)}lastPeers(e){return this.peersByHandle.get(e)??[]}trackers(e,t=4e3){return this.mod._lt_torrent_post_trackers(e),this.awaitList(this.trackerWaiters,this.trackersByHandle,e,t)}lastTrackers(e){return this.trackersByHandle.get(e)??[]}awaitList(e,t,n,r){return new Promise(i=>{let a={handle:n,resolve:i,timer:setTimeout(()=>{let r=e.indexOf(a);r>=0&&(e.splice(r,1),i(t.get(n)??[]))},r)};e.push(a)})}resolveOne(e,t,n){for(let r=e.length-1;r>=0;r--){let i=e[r];i.handle===t&&(clearTimeout(i.timer),e.splice(r,1),i.resolve(n))}}files(e){return this.filesByHandle.get(e)??null}bitfield(e){let t=this.bitfieldByHandle.get(e),n=this.filesByHandle.get(e);return!t||!n?null:{pieces:t.pieces,numPieces:t.numPieces,pieceLength:n.pieceLength,length:n.totalSize}}status(e){return this.statusByHandle.get(e)??null}async read(e,t,n,r,i={}){let a=this.filesByHandle.get(e);if(!a)throw Error(`read: no layout for handle ${e} (metadata not ready)`);let o=a.files[t];if(!o)throw Error(`read: no file ${t}`);if(!this.storage)throw Error(`read: no storage backend configured`);if(n<0)throw RangeError(`read: negative offset ${n}`);let s=Math.min(r,o.size-n);if(s<=0)return/* @__PURE__ */ new Uint8Array;let{pieceLength:c}=a,l=o.offset+n,u=Math.floor(l/c),d=Math.min(a.numPieces-1,Math.floor((l+s-1)/c));if(!this.hasPieces(e,u,d)){let t=i.deadlineMs===void 0?0:i.deadlineMs;if(t!==null){for(let n=u;n<=d;n++)this.mod._lt_torrent_set_piece_deadline(e,n,t,0);this.retainDeadlines(e,u,d)}this.mod._lt_torrent_post_status(e);try{await this.awaitPieces(e,u,d,i)}finally{t!==null&&this.releaseDeadlines(e,u,d)}}let f=await this.storage.read(a.storageIndex,t,n,s);return f instanceof Uint8Array?f:new Uint8Array(f)}setStreamWindow(e,t,n={}){let r=this.filesByHandle.get(e);if(!r)return!1;let{pieceLength:i,numPieces:a}=r,o=Math.max(1,Math.floor(n.windowPieces??xc)),s=Math.max(0,Math.floor(n.deadlineStepMs??Sc)),c=n.claimedPriority??G.normal,l=n.unclaimedPriority??G.normal,u=new Uint8Array(a).fill(l),d=/* @__PURE__ */ 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)*Sc,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,vc[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=/* @__PURE__ */ new Map);for(let e=t;e<=n;e++)r.set(e,(r.get(e)??0)+1)}releaseDeadlines(e,t,n){let r=this.deadlineRefs.get(e);if(!r)return;let i=[],a=this.priosByHandle.get(e);for(let o=t;o<=n;o++){let t=(r.get(o)??0)-1;if(t>0){r.set(o,t);continue}r.delete(o),this.mod._lt_torrent_reset_piece_deadline(e,o),i.push({piece:o,priority:a?.[o]??G.normal})}i.length&&this.prioritizePieceList(e,i),r.size||this.deadlineRefs.delete(e)}reissueReadDeadlines(e){let t=this.deadlineRefs.get(e);if(t)for(let n of t.keys())this.mod._lt_torrent_set_piece_deadline(e,n,0,0)}postStatus(e){this.mod._lt_torrent_post_status(e)}infohash(e){return this.readHash(e,this.mod._lt_torrent_infohash)}infohashV2(e){return this.readHash(e,this.mod._lt_torrent_infohash_v2)}readHash(e,t){let n=this.mod,r=n._malloc(65);try{return t.call(n,e,r)===0?n.UTF8ToString(r):null}finally{n._free(r)}}hasPieces(e,t,n){let r=this.bitfieldByHandle.get(e);if(!r)return!1;for(let e=t;e<=n;e++){if(e<0||e>=r.numPieces)return!1;let t=r.pieces[e>>3];if(t===void 0||!(t&128>>(e&7)))return!1}return!0}awaitPieces(e,t,n,r){let{signal:i}=r,a=r.timeoutMs??bc;return new Promise((r,o)=>{let s,c,l=e=>{let t=this.pieceWaiters.indexOf(u);t<0||(this.pieceWaiters.splice(t,1),s!==void 0&&clearTimeout(s),c&&i&&i.removeEventListener(`abort`,c),e?o(e):r())},u={handle:e,p0:t,p1:n,settle:l};if(this.pieceWaiters.push(u),i?.aborted){l(/* @__PURE__ */ Error(`read: aborted`));return}a>0&&(s=setTimeout(()=>l(/* @__PURE__ */ Error(`read: pieces ${t}-${n} of handle ${e} did not arrive within ${a}ms`)),a)),i&&(c=()=>l(/* @__PURE__ */ Error(`read: aborted`)),i.addEventListener(`abort`,c,{once:!0}))})}resolvePieceWaiters(){if(this.pieceWaiters.length!==0)for(let e of[...this.pieceWaiters])this.hasPieces(e.handle,e.p0,e.p1)&&e.settle()}failPieceWaiters(e,t){for(let n of[...this.pieceWaiters])(t===void 0||n.handle===t)&&n.settle(e)}popAlerts(){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===uc)this.decodeTorrentReady(r,a);else if(o===dc)this.decodeStateUpdate(r,a);else if(o===pc)this.decodeResumeData(r,a,s);else if(o===mc)this.decodePeers(r,a);else if(o===hc)this.decodeTrackers(r,a);else if(o!==fc){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=oc.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=sc.exec(e);if(n){this.reachability.listening[n[1].toLowerCase()]=n[2];return}cc.test(e)&&this.reachability.listenFailed.length<32&&this.reachability.listenFailed.push(e)}readStr(e,t){let n=e.getUint32(t,!0);return t+=4,[lc.decode(new Uint8Array(e.buffer,e.byteOffset+t,n)),t+n]}decodePeers(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getUint32(t,!0);t+=4;let i=[];for(let n=0;n<r;n++){let n,r;[n,t]=this.readStr(e,t),[r,t]=this.readStr(e,t);let a=e.getUint32(t,!0);t+=4;let o=e.getUint32(t,!0);t+=4;let s=e.getUint32(t,!0);t+=4;let c=e.getInt32(t,!0);t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=Number(e.getBigInt64(t,!0));t+=8;let p=Number(e.getBigInt64(t,!0));t+=8;let m=e.getInt32(t,!0)/1e6;t+=4;let h=e.getInt32(t,!0);t+=4;let g=e.getInt32(t,!0);t+=4;let _=e.getInt32(t,!0);t+=4;let v=e.getInt32(t,!0);t+=4,i.push({endpoint:n,client:r,flags:a,source:o,connectionType:s,downloadRate:c,uploadRate:l,payloadDownloadRate:u,payloadUploadRate:d,totalDownload:f,totalUpload:p,progress:m,rtt:h,numPieces:g,requestsInFlight:_,failCount:v})}this.peersByHandle.set(n,i),this.resolveOne(this.peerWaiters,n,i)}decodeTrackers(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getUint32(t,!0);t+=4;let i=[];for(let n=0;n<r;n++){let n,r;[n,t]=this.readStr(e,t),[r,t]=this.readStr(e,t);let a=e.getInt32(t,!0);t+=4;let o=e.getInt32(t,!0);t+=4;let s=e.getUint32(t,!0)!==0;t+=4;let c=e.getUint32(t,!0)!==0;t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=e.getInt32(t,!0);t+=4,i.push({url:n,message:r,tier:a,fails:o,updating:s,verified:c,nextAnnounceIn:l,seeders:u,leechers:d,downloaded:f})}this.trackersByHandle.set(n,i),this.resolveOne(this.trackerWaiters,n,i)}decodeResumeData(e,t,n){let r=e.getUint32(t,!0),i=new Uint8Array(n-4);i.set(new Uint8Array(e.buffer,e.byteOffset+t+4,n-4)),this.resumeByHandle.set(r,i),this.resumeWaiters=this.resumeWaiters.filter(e=>e.handle!==r||(e.resolve(i),!1))}decodeTorrentReady(e,t){let n=new TextDecoder,r=e.getUint32(t,!0);t+=4;let i=e.getUint32(t,!0);t+=4;let a=e.getUint32(t,!0);t+=4;let o=e.getUint32(t,!0);t+=4;let s=Number(e.getBigInt64(t,!0));t+=8;let c=e.getUint32(t,!0);t+=4;let l=[];for(let r=0;r<c;r++){let r=Number(e.getBigInt64(t,!0));t+=8;let i=Number(e.getBigInt64(t,!0));t+=8;let a=e.getUint8(t)===1;t+=1;let o=e.getUint32(t,!0);t+=4;let s=n.decode(new Uint8Array(e.buffer,e.byteOffset+t,o));t+=o,l.push({path:s,size:i,offset:r,pad:a})}let u=l.reduce((e,t)=>e+(t.pad?0:t.size),0);this.filesByHandle.set(r,{storageIndex:i,pieceLength:a,numPieces:o,totalSize:s,contentSize:u,files:l})}decodeStateUpdate(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getInt32(t,!0);t+=4;let i=Number(e.getBigInt64(t,!0));t+=8;let a=Number(e.getBigInt64(t,!0));t+=8;let o=e.getFloat32(t,!0);t+=4;let s=e.getInt32(t,!0);t+=4;let c=e.getInt32(t,!0);t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getUint32(t,!0)!==0;t+=4;let f=e.getUint32(t,!0)!==0;t+=4;let p=e.getUint32(t,!0)!==0;t+=4;let m=e.getUint32(t,!0)>>>0;t+=4;let h=Number(e.getBigInt64(t,!0));t+=8;let g=Number(e.getBigInt64(t,!0));t+=8;let _=Number(e.getBigInt64(t,!0));t+=8;let v=Number(e.getBigInt64(t,!0));t+=8;let y=Number(e.getBigInt64(t,!0));t+=8;let b=Number(e.getBigInt64(t,!0));t+=8;let x=Number(e.getBigInt64(t,!0));t+=8;let S=e.getInt32(t,!0);t+=4;let C=e.getInt32(t,!0);t+=4;let w=e.getInt32(t,!0);t+=4;let T=e.getInt32(t,!0);t+=4,t+=4;let E=e.getFloat32(t,!0);t+=4;let D=e.getInt32(t,!0);t+=4;let O=e.getInt32(t,!0);t+=4;let k=Number(e.getBigInt64(t,!0));t+=8;let A=Number(e.getBigInt64(t,!0));t+=8;let ee=Number(e.getBigInt64(t,!0));t+=8;let j=e.getUint32(t,!0)!==0;t+=4;let te;[te,t]=this.readStr(e,t);let M=e.getInt32(t,!0);t+=4;let N=e.getInt32(t,!0);t+=4;let P=e.getUint32(t,!0);t+=4;let F=P?lc.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!==ac.downloadingMetadata})}async*alerts(){for(;!this.destroyed;){for(let e of this.popAlerts())yield e;await new Promise(e=>setTimeout(e,100))}}setReservedPort(e){this.reachability.port=e}tick(){if(!this.destroyed&&(this.mod._lt_session_tick(),this.pieceWaiters.length)){let e=new Set(this.pieceWaiters.map(e=>e.handle));for(let t of e)this.mod._lt_torrent_post_status(t)}}destroy(){this.destroyed||(this.destroyed=!0,this.fallbackTimer!=null&&clearInterval(this.fallbackTimer),this.failPieceWaiters(/* @__PURE__ */ Error(`read: session destroyed`)),this.pieceWaiters=[],this.resumeWaiters=[],this.deadlineRefs.clear(),this.priosByHandle.clear(),this.mod._lt_session_destroy(),this.mod.__FKN?.teardown?.())}},wc=8e3,Tc=e=>{try{e?.close()}catch{}},Ec=(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),Tc(r),n(null))},o=setTimeout(a,wc);r.on(`listening`,()=>{i||(i=!0,clearTimeout(o),n(r))}),r.on(`error`,a);try{t(r)}catch{a()}});async function Dc(e,t,n=4){try{return await Oc(e,t,n)}catch{return null}}async function Oc(e,t,n){for(let r=0;r<n;r++){let i=await Ec(()=>t.createSocket({type:`udp4`}),e=>e.bind(0,`0.0.0.0`));if(!i)return null;let a=i.address?.()?.port;if(!a)return Tc(i),null;let o=await Ec(()=>e.createServer(),e=>e.listen(a,`0.0.0.0`)),s=o?o.address?.()?.port:void 0,c=!!o&&s===a;if(o&&!c&&Tc(o),!c){if(r<n-1){Tc(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 kc(e){let t=e.moduleFactory??(await import(`./libtorrent-CnjRmD5O.js`)).default,n={net:e.net,dgram:e.dgram,storage:e.storage??null,debug:e.debug??!1},r=e.reserveListenPort===!1?Promise.resolve(null):Dc(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 Cc(i,e)}catch(e){throw a&&!a.adopted&&(Tc(a.server),Tc(a.udp)),e}return o.setReservedPort(a?a.port:null),o}const Ac=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},jc=25e5,Mc=e=>{if(!Number.isFinite(e)||e<=0)return 12;let t=Math.ceil(jc/e)+1,n=Math.max(2,Math.floor(8388608/e));return Math.min(Math.max(t,2),n)},Nc=e=>Mc(e)*Math.max(0,e),Pc=e=>Math.max(1,Math.floor(Nc(e)/2)),Fc=(e,t)=>Math.min(2e3,Math.max(50,Math.round(e/Math.max(t,25e4)*1e3))),Ic=(e,t,n,r=jc)=>{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 Lc=class{storages=/* @__PURE__ */ new Map;opened=/* @__PURE__ */ new Map;onNewStorage(e,t,n){let r=(async()=>{let r=await Rc(await navigator.storage.getDirectory(),t.replace(/^\/+/,``));this.storages.set(e,{rootDir:r,files:/* @__PURE__ */ new Map,opening:/* @__PURE__ */ new Map,fileMeta:n})})();return this.opened.set(e,r),r.then(()=>{this.opened.get(e)===r&&this.opened.delete(e)},()=>{}),r}async onRemoveStorage(e){this.opened.delete(e);let t=this.storages.get(e);if(t){for(let e of t.files.values())try{e.close()}catch{}this.storages.delete(e)}}read(e,t,n,r){let i=this.openFile(e,t),a=e=>{let t=new Uint8Array(r),i=e.read(t,{at:n});return i<r&&t.fill(0,i),t};return i instanceof Promise?i.then(a):a(i)}write(e,t,n,r){let i=this.openFile(e,t),a=i=>{try{let a=i.write(r,{at:n});if(a<r.length)throw console.error(`[opfs] short write`,{id:e,fileIndex:t,offset:n,want:r.length,wrote:a}),Error(`short write`)}catch(i){throw console.error(`[opfs] write failed`,{id:e,fileIndex:t,offset:n,len:r.length,err:String(i),errName:i?.name,errMsg:i?.message,isView:ArrayBuffer.isView(r),bytesType:Object.prototype.toString.call(r)}),i}};return i instanceof Promise?i.then(a).catch(n=>{throw console.error(`[opfs] openFile failed`,{id:e,fileIndex:t,err:String(n)}),n}):a(i)}async release(e){let t=this.storages.get(e);if(t){for(let e of t.files.values())try{e.flush(),e.close()}catch{}t.files.clear()}}async stop(e){return this.release(e)}async check(e){let t=!1;if(await this.opened.get(e)?.catch(()=>{t=!0}),t)return 2;let n=this.storages.get(e);if(!n)return 0;await this.release(e);for(let e of n.fileMeta)if(await this.hasBytes(n,e.path))return 2;return 0}async hasBytes(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(!r)return!1;let i=e.rootDir;try{for(let e of n)i=await i.getDirectoryHandle(e);return(await(await i.getFileHandle(r)).getFile()).size>0}catch(e){return e?.name!==`NotFoundError`}}async deleteFiles(e,t){let n=this.storages.get(e);if(n){for(let e of n.files.values())try{e.close()}catch{}n.files.clear();for(let e of n.fileMeta){let t=e.path.split(`/`).filter(Boolean),r=t.pop();if(!r)continue;let i=n.rootDir;for(let e of t)try{i=await i.getDirectoryHandle(e)}catch{i=null;break}if(i)try{await i.removeEntry(r)}catch{}}}}openFile(e,t){let n=this.storages.get(e);if(!n)throw Error(`unknown storage ${e}`);let r=n.files.get(t);if(r)return r;let i=n.opening.get(t);if(i)return i;let a=this.openFileSlow(e,t);return n.opening.set(t,a),a.finally(()=>n.opening.delete(t)),a}async openFileSlow(e,t){let n=this.storages.get(e),r=n.fileMeta[t];if(!r)throw Error(`unknown file ${t}`);let i=r.path.split(`/`).filter(Boolean),a=i.pop(),o=n.rootDir;for(let e of i)o=await o.getDirectoryHandle(e,{create:!0});let s=await(await o.getFileHandle(a,{create:!0})).createSyncAccessHandle();return n.files.set(t,s),s}};async function Rc(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 zc=[50,150,400,900,1500],Bc=e=>e?.name===`QuotaExceededError`,Vc=e=>new Promise(t=>setTimeout(t,e)),Hc=()=>{let e=new Lc,t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ 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 zc){if(Bc(o))break;if(i(e,n),await Vc(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)}},Uc=[5e3,15e3,3e4,6e4,12e4,3e5],Wc=1e4,Gc=/* @__PURE__ */ new Set([2,3]),Kc=/* @__PURE__ */ new Set([1,7]),qc=e=>!!e&&e.paused&&!e.autoManaged,Jc=()=>{let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=e=>Uc[Math.min(e,Uc.length-1)],a=i=>{e.delete(i),t.delete(i),n.delete(i),r.delete(i)};return{hold:(e,t,n=Wc)=>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(Kc.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`:Gc.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+Wc,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)}}},Yc=e=>!(e.flags&gc.localConnection)||!!(e.source&yc.incoming),Xc=e=>e.flags&gc.utpSocket?`utp`:`tcp`,Zc={total:0,byTransport:{}},Qc=e=>{let t={},n=0;for(let r of e)for(let e of r){if(!Yc(e)||e.connectionType!==0)continue;n+=1;let r=Xc(e);t[r]=(t[r]??0)+1}return{total:n,byTransport:t}},$c={activeSeconds:0,seedingSeconds:0},el=[`activeSeconds`,`seedingSeconds`,`downloaded`,`uploaded`,`wasted`],tl={activeSeconds:0,seedingSeconds:0,downloaded:0,uploaded:0,wasted:0},K=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0,nl=(e,t)=>({activeSeconds:Math.max(0,K(t.activeSeconds)-K(e.activeSeconds)),seedingSeconds:Math.max(0,K(t.seedingSeconds)-K(e.seedingSeconds))}),rl=(e,t,n)=>{let r=nl(t,n);return{activeSeconds:K(e?.activeSeconds)+r.activeSeconds,seedingSeconds:K(e?.seedingSeconds)+r.seedingSeconds}},il=(e,t)=>Object.fromEntries(el.map(n=>[n,Math.max(0,K(t[n])-K(e[n]))])),al=(e,t,n)=>{let r=il(t,n);return Object.fromEntries(el.map(t=>[t,K(e?.[t])+r[t]]))},ol=(e,t)=>Object.fromEntries(el.map(n=>[n,Math.max(K(e?.[n]),K(t?.[n]))])),sl=(e,t)=>t.activeSeconds-K(e?.activeSeconds)>=30||t.seedingSeconds-K(e?.seedingSeconds)>=30,cl=e=>!Number.isFinite(e)||e<=0?0:Math.min(1e9,Math.floor(e*.1)),ll=(e,t)=>!Number.isFinite(e)||e<=0?Math.max(0,t):Math.max(Math.min(.25*e,2e10),Math.max(0,t)),ul=({usedBytes:e,limitBytes:t})=>!Number.isFinite(t)||t<=0||!Number.isFinite(e)||e<0?!1:t-e<cl(t),dl=(e,t)=>e.usedAt-t.usedAt||(e.infoHash<t.infoHash?-1:+(e.infoHash>t.infoHash)),fl=({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(dl);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=cl(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=ll(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 pl=8,ml=2e4,hl=e=>typeof e.values==`function`,gl=async e=>{let t=0,n=0,r=async(e,i)=>{if(!(i>pl))for await(let a of e.values()){if(++n>ml)return;if(hl(a)){await r(a,i+1);continue}let e=await a.getFile().catch(()=>null);e&&(t+=e.size)}};try{return await r(e,0),t}catch{return null}},_l=(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)},vl,yl,bl=(e,t,n)=>{if(e!==void 0)return n!==yl&&(vl=void 0),yl=n,vl=vl===void 0?e:Math.min(vl,e),Math.max(vl,t??0)},xl=async e=>e.persisted?e.persisted().then(e=>e===!0).catch(()=>yl):void 0,Sl={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=>gl(e)).catch(()=>null):null,xl(e)]),i=_l(t,n);return{...t,usage:i,quota:bl(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 xl(e)??null??t},persisted:()=>globalThis.navigator?.storage?.persisted?.()??Promise.resolve(!1),getDirectory:()=>{let e=globalThis.navigator?.storage;return e?.getDirectory?e.getDirectory():Promise.reject(/* @__PURE__ */ Error(`this browser has no origin private file system`))}};const Cl=/^(?:[0-9a-f]{40}|[0-9a-f]{64}|[a-z2-7]{32})$/i,wl=({entries:e,listedHashes:t,claimedNames:n,attributable:r})=>e.filter(({name:e,kind:i})=>n.has(e)?!1:i===`directory`&&Cl.test(e)?!t.has(e.toLowerCase()):r).map(({name:e})=>e),Tl=async e=>{let t=[];for await(let n of e.values())t.push({name:n.name,kind:n.kind});return t},El=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},Dl=async(e,t,n)=>{let r=await El(e,t);if(!r)return[];let i=[];for(let e of wl({...n,entries:await Tl(r)}))try{await r.removeEntry(e,{recursive:!0}),i.push(e)}catch{}return i},Ol=async e=>{let t=0;for(let{name:n,kind:r}of await Tl(e))r===`file`&&n.startsWith(`.ripple-probe-`)&&await e.removeEntry(n).then(()=>!0,()=>!1)&&t++;return t},kl=e=>e?`/dl/`+e:`/dl`,Al=(e,t)=>e===kl(t),jl=(e,t)=>t&&(!e||e.ephemeral===!0),Ml=(e,t)=>e?{...t,ephemeral:jl(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,Nl=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`,Fl=`ripple:removed`,Il=(...e)=>{let t=/* @__PURE__ */ new Map;for(let n of e)if(Array.isArray(n))for(let e of n)typeof e?.infoHash==`string`&&e.infoHash&&typeof e.removedAt==`number`&&Number.isFinite(e.removedAt)&&t.set(e.infoHash,Math.max(t.get(e.infoHash)??e.removedAt,e.removedAt));return[...t].map(([e,t])=>({infoHash:e,removedAt:t}))},Ll=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}},Rl=(e,t,n)=>{let r=Ll(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}},zl=e=>`ripple:resume:`+e,Bl=e=>`ripple:torrent:`+e,Vl=e=>`ripple:thumb:`+e,Hl=e=>typeof e.getFile==`function`?e.getFile():Promise.resolve(e),Ul=e=>`/native/${e}`,Wl=e=>e===`/native`||!!e?.startsWith(`/native/`),Gl=e=>`/source/${e}`,Kl=e=>e===`/source`||!!e?.startsWith(`/source/`),ql=e=>Wl(e)||Kl(e),Jl=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()},Yl=(e,t,n=()=>null)=>{let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ 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=>ql(t)?0:e.usageOf(t),onNewStorage:(t,a,o)=>{if(Kl(a)){i.set(t,{savePath:a,files:o,handles:n(a)});return}if(!Wl(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 Jl(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 Jl(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)}}},Xl=(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))],Zl=({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]=Xl(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]=Xl(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},Ql=({wanted:e,firstLast:t})=>e===void 0&&!t,$l=e=>Kl(e)?`source`:Wl(e)?`folder`:`browser`,eu=(e,t)=>{if(e===`source`){if(!t)throw Error(`a source-backed torrent needs its infohash to name its save path`);return Gl(t)}return e===`folder`?t?Ul(t):`/dl`:kl(t)},tu=`ripple:rate-limits`,nu=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,ru=e=>{let t=e??{};return{down:nu(t.down)?t.down:0,up:nu(t.up)?t.up:0}},iu=/* @__PURE__ */ new Set(/* @__PURE__ */ `add-magnet.add-torrent-file.create-source.reserve-storage.start-source.read.cancel-read.remove.relocate.set-location.set-folder.set-plan.remove-missing.watch.unwatch.unwatch-owner.pause.resume.recheck.import-list.clear-list.start.retry.retry-now.flush-resume.inspect.set-flags.reannounce.queue-move.set-limits.set-session-limits.set-temporary`.split(`.`)),au=e=>`ripple:source:`+e;let q=null,ou=null,su=null;const cu=/* @__PURE__ */ new Map;let lu=!1;const J=[],uu=/* @__PURE__ */ new Map,Y=/* @__PURE__ */ new Map,du=/* @__PURE__ */ new Map,fu=/* @__PURE__ */ new Map,X=/* @__PURE__ */ new Set,pu=/* @__PURE__ */ new Set,mu=/* @__PURE__ */ new Set,hu=e=>{mu.delete(e),pu.add(e)},gu=e=>{pu.delete(e),mu.add(e)},_u=/* @__PURE__ */ new Map,Z=Jc(),vu=e=>e>=4294967040,Q=(e,t)=>self.postMessage(e,t??[]),yu=()=>J.map(e=>{let t=q.bitfield(e);return{handle:e,magnet:uu.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:bu(e),sessionUptime:xu(e),totals:$u(e)}}),bu=e=>{let t=q?.status(e),n=qu.get(e);return!t||!n?Ju.get(e)??$c:rl(Ju.get(e),n,t)},xu=e=>{let t=q?.status(e),n=qu.get(e);return t&&n?nl(n,t):$c},Su=async()=>await tc(`ripple:torrents`)??[],Cu=async e=>{let t=[];await rc(Pl,n=>{t=n??[];let r=t.findIndex(t=>t.infoHash===e.infoHash),i=Ml(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 rc(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})},wu=e=>{let t=Y.get(e);t&&$(t,{lastUsedAt:Date.now()},!0).catch(()=>{})},Tu=async e=>{await ic(zl(e)).catch(()=>{}),await ic(Bl(e)).catch(()=>{}),await ic(au(e)).catch(()=>{}),await ic(Vl(e)).catch(()=>{})},Eu=async e=>{let t=[];await rc(Pl,n=>t=(n??[]).filter(t=>t.infoHash!==e)),await rc(Fl,t=>Il(t,[{infoHash:e,removedAt:Date.now()}])),await Tu(e),Q({type:`list`,list:t})},Du=/* @__PURE__ */ new Set,Ou=/* @__PURE__ */ new Set,ku=/* @__PURE__ */ new Map,Au=/* @__PURE__ */ new Set;let ju=null,Mu=0,Nu=0,Pu=Zc;const Fu=e=>{let t=ju;return t==null||!J.includes(t)?null:(q.peers(t),e-Mu>=5e3&&(Mu=e,q.trackers(t)),{handle:t,peers:q.lastPeers(t),trackers:q.lastTrackers(t)})},Iu=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)]},Lu=(e,t,n,r,i=!1)=>{J.includes(e)||J.push(e),uu.set(e,t),n&&(Y.set(e,n),Au.add(e)),du.set(e,r),i?Du.add(e):Du.delete(e)},Ru=e=>{let t=J.indexOf(e);t>=0&&J.splice(t,1),uu.delete(e),Y.delete(e),du.delete(e),fu.delete(e),X.delete(e),Z.forget(e),od.delete(e),id.delete(e),pu.delete(e),mu.delete(e),_u.delete(e),ld.delete(e),ud.delete(e),Bu.delete(e),Vu.delete(e),Uu.delete(e),Wu.delete(e),Gu.delete(e),qu.delete(e),Ju.delete(e),Yu.delete(e),Xu.delete(e),Du.delete(e),Ou.delete(e),ku.delete(e),Au.delete(e)},zu=e=>{Ou.delete(e)&&(gu(e),q?.resumeTorrent(e),Z.hold(e,Date.now()))},Bu=/* @__PURE__ */ new Set,Vu=/* @__PURE__ */ new Map;let Hu={down:0,up:0};const Uu=/* @__PURE__ */ new Map,Wu=/* @__PURE__ */ new Set,Gu=/* @__PURE__ */ new Map;let Ku=0;const qu=/* @__PURE__ */ new Map,Ju=/* @__PURE__ */ new Map,Yu=/* @__PURE__ */ new Map,Xu=/* @__PURE__ */ new Map,Zu=e=>({activeSeconds:e.activeSeconds,seedingSeconds:e.seedingSeconds,downloaded:e.allTimeDownload,uploaded:e.allTimeUpload,wasted:e.wasted}),Qu=e=>({activeSeconds:e?.activeSeconds??0,seedingSeconds:e?.seedingSeconds??0,downloaded:e?.downloaded??0,uploaded:e?.uploaded??0,wasted:e?.wasted??0}),$u=e=>{let t=q?.status(e),n=Yu.get(e);return!t||!n?Xu.get(e)??tl:al(Xu.get(e),n,Zu(t))},ed=(e,t,n)=>{let r=Gu.get(e);Gu.set(e,r?{flags:r.flags&~n|t&n,mask:r.mask|n}:{flags:t&n,mask:n})},td=(e,t)=>{let n={...Uu.get(e)};return nu(t.down)&&(n.down=t.down),nu(t.up)&&(n.up=t.up),!nu(n.down)&&!nu(n.up)?!1:(Uu.set(e,n),Wu.add(e),!0)},nd=e=>{let t=Uu.get(e);q&&t&&(nu(t.down)&&q.setDownloadLimit(e,t.down),nu(t.up)&&q.setUploadLimit(e,t.up))},rd=6e3,id=/* @__PURE__ */ new Map,ad=(e,t)=>{let n=id.get(e);if(n?.size){for(let e of n)Q({type:`read-error`,id:e,error:t});n.clear()}},od=/* @__PURE__ */ new Set,sd=async e=>{let t=Y.get(e);if(!t||!q||od.has(e)||Kl(du.get(e)))return!1;od.add(e);try{let n=await q.saveResumeData(e);return J.includes(e)?(await nc(zl(t),n),!0):!1}catch(e){return console.error(`[worker] saving resume data failed`,String(e)),!1}finally{od.delete(e)}},cd=(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}},ld=/* @__PURE__ */ new Map,ud=/* @__PURE__ */ new Set,dd=e=>{let t=Vu.get(e);if(!q||!t||Ql(t))return;let n=q.files(e);n&&q.prioritizePieces(e,Zl({files:n.files,pieceLength:n.pieceLength,numPieces:Math.ceil(n.totalSize/n.pieceLength),wanted:t.wanted,firstLast:t.firstLast}))},fd=e=>{let t=ld.get(e);return t?[...t.values()].filter(e=>!e.held):[]},pd=e=>{if(!q)return;if(!J.includes(e)){ld.delete(e),ud.delete(e);return}let t=fd(e);if(!t.length){if(!q.files(e)){ud.add(e);return}ud.delete(e),q.clearStreamWindow(e),dd(e),Du.has(e)&&!X.has(e)&&!Ou.has(e)&&(Ou.add(e),hu(e),q.pauseTorrent(e),sd(e));return}zu(e);let n=q.files(e);if(!n){ud.add(e);return}let r=t.flatMap(({fileIndex:e,fromOffset:t,bulk:r})=>{let i={fileIndex:e,offset:t},a=n.files[e];return!r&&a?.size?[i,{fileIndex:e,offset:a.size-1}]:[i]}),i=t.some(e=>!e.bulk);q.setStreamWindow(e,r,{unclaimedPriority:G.skip,windowPieces:Mc(n.pieceLength),deadlineStepMs:Fc(n.pieceLength,q.status(e)?.downloadRate||3e6),deadlines:i})?ud.delete(e):ud.add(e)},md=e=>{X.add(e),Ou.delete(e),hu(e),Z.forget(e),q?.pauseTorrent(e)},hd=(e,t,n,r,i=!1,a)=>{if(!J.includes(t))return;let o=ld.get(t),s=!o?.size;o||ld.set(t,o=/* @__PURE__ */ new Map);let c=a??o.get(e)?.bulk;o.set(e,{fileIndex:n,fromOffset:r,...i?{held:i}:{},...c?{bulk:c}:{}}),s&&wu(t),pd(t)},gd=e=>{for(let[t,n]of ld){let r=!1;for(let t of[...n.keys()])e(t)&&(n.delete(t),r=!0);n.size||(ld.delete(t),r&&wu(t)),r&&pd(t)}},_d=(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},vd=(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},yd=()=>{if(!q)return 0;let e=0;for(let[t,n]of ld){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=/* @__PURE__ */ new Set;for(let{fileIndex:e}of n.values()){let n=cd(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},bd=(e,t,n,r,i)=>{if(!e||!J.includes(t))return;let a=ld.get(t)?.get(e);if(!a||a.held||a.fileIndex!==n){hd(e,t,n,r);return}let o=cd(t,n);if(!o)return;let s={fileOffset:o.file.offset,pieceLength:o.pieceLength,p1:o.p1};Ic(s,a.fromOffset,r,i)&&hd(e,t,n,r)},xd=async e=>{let t=e.filter(e=>!ql(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}},Sd=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}},Cd=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}),wd=async()=>{try{let{usage:e,quota:t}=await Sl.estimate();return!t||e===void 0?null:{usedBytes:e,limitBytes:t}}catch{return null}},Td=async e=>{for(let t=0;t<4e3;t+=250){await new Promise(e=>setTimeout(e,250));let t=await wd();if(!t||t.usedBytes<e)return t}return wd()},Ed=async(e,t,n,r,i={})=>{ad(t,r),e.removeTorrent(t,!0),Ru(t),await ic(zl(n)).catch(()=>{}),await $(n,{started:!1,paused:!1,...i})},Dd=(e,t,n)=>Ed(e,t,n,`torrent removed to make room`),Od=async(e,t,n,r)=>{let i=$l(du.get(t));if(i===r)return;let a=uu.get(t)??``,o=eu(r,n),s=X.has(t),c=Du.has(t);ad(t,`files moved`),e.removeTorrent(t,i===`browser`),Ru(t),await ic(zl(n)).catch(()=>{});let l=e.addMagnet(a,o);if(vu(l)){Q({type:`add-failed`,message:`Moving the files left the torrent unaddable`}),await $(n,{savePath:o,saveTo:r,started:!1});return}Lu(l,a,n,o,c),r===`folder`&&ed(l,_c.uploadMode,_c.uploadMode),s?(X.add(l),hu(l)):gu(l),Z.hold(l,Date.now()),await $(n,{savePath:o,saveTo:r,started:!0})},kd=(e,{infoHash:t,magnet:n,bytes:r,handles:i,paused:a})=>{let o=Gl(t);cu.set(o,i);let s=e.addTorrentFile(r,o);return vu(s)?(cu.delete(o),null):(Lu(s,n,t,o,!1),ed(s,_c.uploadMode,_c.uploadMode),a&&(X.add(s),hu(s)),Z.hold(s,Date.now()),s)},Ad=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||!Al(a.savePath,i)||ld.get(e)?.size||id.get(e)?.size||t-(ku.get(e)??0)<6e4)continue;let o=a.lastUsedAt??a.addedAt;if(t-o<15e3)continue;let s=await ou?.usageOf(a.savePath)??0;s<=0||r.push({infoHash:i,usedAt:o,bytesOnDisk:s})}return r};let jd=!1;const Md=e=>{let t=ul(e);t!==jd&&(jd=t,Q({type:`storage-full`,full:t,usedBytes:e.usedBytes,limitBytes:e.limitBytes}))},Nd=/* @__PURE__ */ new Set;let Pd=!1;const Fd=async()=>{if(!q||Pd)return 0;Pd=!0;try{let e=await Su(),t=new Set(e.map(e=>e.infoHash.toLowerCase()));for(let e of Nd)t.add(e.toLowerCase());let n=/* @__PURE__ */ new Set,r=!0;for(let e of J){let i=Y.get(e);if(i&&t.add(i.toLowerCase()),(du.get(e)??`/dl`)!==`/dl`)continue;let a=Iu(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 Dl(i,`/dl`,{listedHashes:t,claimedNames:n,attributable:r});return await Ol(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 Id=!1;const Ld=async()=>{let e=q;if(!e||Id)return;Id=!0;let t=null;try{let n=await wd();if(!n)return;t=n;let r=yd(),i=await Ad(await Su(),Date.now());for(;i.length;){let[a]=fl({...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||ld.get(o)?.size||id.get(o)?.size)continue;let s=n.usedBytes;t=null,await Dd(e,o,a);let c=await Td(s);if(!c)return;n=c,t=c}ul(n)&&await Fd()&&(n=await Td(n.usedBytes)??n),t=n}catch(e){console.error(`[worker] storage budget pass failed`,String(e))}finally{Id=!1,t&&Md(t)}},Rd=async()=>{let e=console.error.bind(console);if(console.error=(...t)=>{e(...t);try{Q({type:`worker-error`,args:t.map(String)})}catch{}},!await Sd()){Q({type:`storage-unavailable`});return}Su().then(e=>{e.length&&Q({type:`list`,list:e})}).catch(()=>{});let t=Promise.race([tc(tu).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]);ou=Yl(Hc(),()=>su,e=>cu.get(e)??null),q=await kc({net:As,dgram:Bs,storage:ou,utpReceiveBufferBytes:4194304});for(let e=0;e<30;e++)q.tick();Hu=ru(await t),q.setRateLimits({download:Hu.down,upload:Hu.up});try{let e=await Su(),t=!await xd(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 tc(zl(r.infoHash)),a=await tc(Bl(r.infoHash));if(t&&i&&i.byteLength){await ic(zl(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);vu(o)||(Lu(o,r.magnet,r.infoHash,e,r.ephemeral===!0),Vu.set(o,{wanted:r.wantedFiles,firstLast:r.firstLast}),Bu.add(o),td(o,{down:r.downloadLimit,up:r.uploadLimit}),Ju.set(o,{activeSeconds:r.activeSeconds??0,seedingSeconds:r.seedingSeconds??0}),Xu.set(o,Qu(r)),r.paused?(X.add(o),hu(o)):gu(o),Z.hold(o,Date.now()))}n&&await nc(Pl,e)}catch(e){console.error(`[worker] restore failed`,e)}Q({type:`ready`}),lu=!0,Q({type:`list`,list:await Su().catch(()=>[])}),Q({type:`state`,torrents:yu(),reachable:q.reachable(),inboundNow:Pu,rateLimits:{...Hu}}),setInterval(()=>{if(!q)return;let e=Date.now();q.popAlerts();for(let e of J)q.postStatus(e);for(let e of[...Bu])q.files(e)&&(Bu.delete(e),fd(e).length||pd(e));for(let e of[...ud])pd(e);for(let e of[...Wu])q.status(e)&&(Wu.delete(e),nd(e));for(let e of J){if(qu.has(e))continue;let t=q.status(e);t&&(qu.set(e,{activeSeconds:t.activeSeconds,seedingSeconds:t.seedingSeconds}),Yu.set(e,Zu(t)))}for(let[e,t]of[...Gu])q.status(e)&&(Gu.delete(e),q.setFlags(e,t.flags>>>0,t.mask>>>0));for(let e of[...Au]){let[t]=Iu(e);if(!t)continue;Au.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 pu){let t=q.status(e);t&&!Kc.has(t.state)&&(qc(t)?pu.delete(e):q.pauseTorrent(e))}for(let e of mu){if(X.has(e)||Ou.has(e)){mu.delete(e);continue}let t=q.status(e);if(t&&!Kc.has(t.state)){if(!t.paused){mu.delete(e);continue}if(t.autoManaged||t.errorCode){mu.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&&Cd(n),X.has(t)||Ou.has(t),e)}for(let{handle:t,reason:n}of Z.due(e))n===`stalled`&&q.pauseTorrent(t),q.resumeTorrent(t);if(e-Nu>=2e3){Nu=e;for(let e of J)q.peers(e)}Pu=Qc(J.map(e=>q.lastPeers(e))),Q({type:`state`,torrents:yu(),reachable:q.reachable(),inboundNow:Pu,detail:Fu(e),rateLimits:{...Hu}});for(let t of J){let n=q.status(t);if(!n||n.state!==4&&n.state!==5||fu.get(t)===n.paused||od.has(t))continue;let r=_u.get(t);if(r&&e<r.at)continue;let i=n.paused;sd(t).then(e=>{if(e){fu.set(t,i),_u.delete(t);return}let n=(_u.get(t)?.tries??0)+1;_u.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&&sd(e)}let e=!1;for(let t of J){let n=q.status(t),r=Y.get(t),i=qu.get(t);if(!n||!r||!i)continue;e=!0;let a=rl(Ju.get(t),i,n);if(!sl(Ju.get(t),a))continue;Ju.set(t,a),qu.set(t,{activeSeconds:n.activeSeconds,seedingSeconds:n.seedingSeconds});let o=Zu(n),s=al(Xu.get(t),Yu.get(t)??o,o);Xu.set(t,s),Yu.set(t,o),$(r,{activeSeconds:a.activeSeconds,seedingSeconds:a.seedingSeconds,downloaded:s.downloaded,uploaded:s.uploaded,wasted:s.wasted},!0).catch(()=>{})}e&&Date.now()-Ku>=3e5&&(Ku=Date.now(),Su().then(e=>Q({type:`list`,list:e})).catch(()=>{}))},15e3),setInterval(()=>{Ld()},1e4),Ld(),setTimeout(()=>{Fd(),setInterval(()=>{Fd()},6e5)},6e4),self.addEventListener(`online`,()=>Z.retryNow(Date.now()))},zd=async(e,t)=>{try{if(t.type===`add-magnet`){let n=Ac(t.magnet),r=n?J.find(e=>Y.get(e)===n):void 0;if(r!==void 0)n&&!t.ephemeral?(Du.delete(r),zu(r),await $(n,{ephemeral:!1,lastUsedAt:Date.now()})):wu(r),Q({type:`added`,handle:r,magnet:uu.get(r)||t.magnet});else{let r=n?(await Su()).find(e=>e.infoHash===n):void 0,i=t.savePath||r?.savePath||kl(n),a=jl(r,t.ephemeral===!0),o=e.addMagnet(t.magnet,i);if(vu(o)){Q({type:`add-failed`,message:`That is not a valid magnet link`});return}Lu(o,t.magnet,n,i,a),Vu.set(o,{wanted:r?.wantedFiles,firstLast:r?.firstLast}),t.hold===!0&&Bu.add(o),td(o,{down:r?.downloadLimit,up:r?.uploadLimit}),Ju.set(o,{activeSeconds:r?.activeSeconds??0,seedingSeconds:r?.seedingSeconds??0}),Xu.set(o,Qu(r)),Z.hold(o,Date.now());let s=Date.now();t.paused===!0&&md(o),n&&await Cu({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}),Ld()}}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 nc(Bl(n),i);let a=kd(e,{infoHash:n,magnet:t.magnet,bytes:i,handles:r,paused:!1});if(a===null){await ic(Bl(n)).catch(()=>{}),Q({type:`add-failed`,message:`The engine refused the torrent that was just built`});return}let o=Date.now();await Cu({infoHash:n,magnet:t.magnet,savePath:Gl(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,...Nl({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:uu.get(i[0])??``});return}let a=await tc(Bl(n));if(!a?.byteLength){Q({type:`add-failed`,message:`The torrent this was built from is no longer stored`});return}let o=(await Su()).find(e=>e.infoHash===n),s=kd(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}Ju.set(s,{activeSeconds:o?.activeSeconds??0,seedingSeconds:o?.seedingSeconds??0}),Xu.set(s,Qu(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(vu(i)){Q({type:`add-failed`,message:`That file is not a valid .torrent`});return}Lu(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),Ru(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(`&`);Lu(i,s,a,n),await nc(Bl(a),r);let c=Date.now();t.paused===!0&&md(i);let l=t.saveTo===`browser`||t.saveTo===`folder`?{saveTo:t.saveTo}:{};await Cu({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}:{}}),Nd.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(zu(t.handle),ku.set(t.handle,Date.now()),X.has(t.handle)&&!_d(t.handle,t.fileIndex,t.offset,t.len)){Q({type:`read-error`,id:t.id,error:`torrent paused`});return}if(t.prioritize!==!1)bd(t.viewer,t.handle,t.fileIndex,t.offset,t.len);else if(!_d(t.handle,t.fileIndex,t.offset,t.len)){Q({type:`read-error`,id:t.id,error:`not downloaded`});return}let n=id.get(t.handle);n||id.set(t.handle,n=/* @__PURE__ */ new Set),n.add(t.id);try{for(let r=0;;r++)try{let r=t.viewer?ld.get(t.handle)?.get(t.viewer)?.bulk===!0:!1,i=await e.read(t.handle,t.fileIndex,t.offset,t.len,{timeoutMs:rd,...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=vd(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)*rd,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?ld.get(t.handle)?.get(t.viewer):void 0;t.prioritize!==!1&&t.viewer&&o&&!o.held&&pd(t.handle)}}finally{n.delete(t.id),J.includes(t.handle)&&ku.set(t.handle,Date.now())}}else if(t.type===`cancel-read`)id.get(t.handle)?.delete(t.id);else if(t.type===`remove`){let n=Y.get(t.handle);ad(t.handle,`torrent removed`),e.removeTorrent(t.handle,!!t.deleteFiles),Ru(t.handle),n&&await Eu(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;Vu.set(t.handle,{wanted:e,firstLast:n}),dd(t.handle);let r=Y.get(t.handle);r&&await $(r,{wantedFiles:e,firstLast:n})}else if(t.type===`set-folder`)su=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?Du.add(n):(Du.delete(n),zu(n))),await $(t.infoHash,{ephemeral:e})}}else if(t.type===`reserve-storage`)typeof t.infoHash==`string`&&t.infoHash&&(t.on===!1?Nd.delete(t.infoHash):Nd.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 Od(e,i,n,r)}else if(t.type===`import-list`){let e=[];await rc(Fl,n=>e=Il(n,t.removed));let n=[],r=[],i=!1;await rc(Pl,a=>{let o=Rl(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=Nl(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=ol(Qu(r),Qu(e));for(let e of el)(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,...Qu(e)};n.push(a),s.set(a.infoHash,a),i=!0}return n});for(let e of r)await Tu(e.infoHash);i&&Q({type:`list`,list:n})}else if(t.type===`start`){let n=(await Su()).find(e=>e.infoHash===t.infoHash);if(n?.saveTo===`source`){Q({type:`add-failed`,message:`Nothing to download this from. Create it again from the same files.`});return}if(n){let t=n.savePath||`/dl`,r=await tc(Bl(n.infoHash)),i=r&&r.byteLength?e.addTorrentFile(r,t):e.addMagnet(n.magnet,t);if(vu(i)){Q({type:`add-failed`,message:`That torrent could not be read`});return}Lu(i,n.magnet,n.infoHash,t,!1),td(i,{down:n.downloadLimit,up:n.uploadLimit}),Z.hold(i,Date.now()),Q({type:`state`,torrents:yu(),reachable:e.reachable()}),await Cu({...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&&(ad(n,`torrent removed`),e.removeTorrent(n,!0),Ru(n)),await Eu(t.infoHash)}}else if(t.type===`clear-list`){for(let t of[...J])ad(t,`torrent removed`),e.removeTorrent(t,!0),Ru(t);let t=[];await rc(Pl,e=>(t=e??[],[])),await ic(Fl).catch(()=>{});for(let e of t)await ic(zl(e.infoHash)).catch(()=>{}),await ic(Bl(e.infoHash)).catch(()=>{});Q({type:`list`,list:[]})}else if(t.type===`pause`){X.add(t.handle),Ou.delete(t.handle),hu(t.handle),Z.forget(t.handle),e.pauseTorrent(t.handle),ad(t.handle,`torrent paused`),sd(t.handle);let n=Y.get(t.handle);n&&await $(n,{paused:!0})}else if(t.type===`resume`){X.delete(t.handle),Ou.delete(t.handle),gu(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 ic(zl(n)).catch(()=>{}),fu.delete(t.handle),ad(t.handle,`torrent rechecking`),X.delete(t.handle),pu.delete(t.handle),mu.delete(t.handle),Ou.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=>sd(e)));else if(t.type===`watch`)t.readLen==null?hd(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.held===!0,t.bulk===!0||void 0):bd(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.readLen);else if(t.type===`unwatch`)gd(e=>e===t.viewer);else if(t.type===`set-flags`)e.setFlags(t.handle,t.flags>>>0,t.mask>>>0),sd(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=nu(t.down)?t.down:void 0,r=nu(t.up)?t.up:void 0;td(t.handle,{down:n,up:r})&&e.status(t.handle)&&(Wu.delete(t.handle),nd(t.handle));let i=Y.get(t.handle);if(i){let e={};n!==void 0&&(e.downloadLimit=n),r!==void 0&&(e.uploadLimit=r),Object.keys(e).length&&await $(i,e)}}else if(t.type===`set-session-limits`)nu(t.down)&&(Hu.down=t.down),nu(t.up)&&(Hu.up=t.up),e.setRateLimits({download:Hu.down,upload:Hu.up}),await nc(tu,{...Hu});else if(t.type===`inspect`){let e=typeof t.handle==`number`?t.handle:null;e!==ju&&(ju=e,Mu=0)}else t.type===`unwatch-owner`&&gd(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)})}},Bd=/* @__PURE__ */ new Set([`read`,`add-torrent-file`]);let Vd=Promise.resolve();self.addEventListener(`message`,e=>{let t=e.data;if(!t||typeof t!=`object`||typeof t.type!=`string`||!iu.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(Bd.has(t.type)){zd(n,t);return}Vd=Vd.then(()=>zd(n,t))}),Rd().catch(e=>Q({type:lu?`error`:`fatal`,message:String(e?.stack??e)}));
package/fkn.json CHANGED
@@ -1 +1 @@
1
- {"v":0,"app":"fkn:app:1c7clnsv53zt7dr7q7rcbt455hxauykaxl4gibkuoao24dfmk2eqq","name":"Ripple","version":"0.0.18","key":"vB+5jsZMRya/m8nc1Ba6qNELaua1jUjbGj90dEzuaF0=","issuedAt":1791664632,"perSource":["npm:@banou/ripple"],"url":"https://torrent.fkn.app/","contentsDigest":"Uhq/R1qaM8DAHfgOrUPUEw+TsWX0OFlrq1wRQt99Hgs=","sig":"yXDfMN7W12k1WYFs9GrN+DNe/Uqoq3iFM00+SuAEbaNGIGfHtPoRePhbeljys7whvh81o7I/iVpqjJXZzdzwBg==","contents":{"name":"@banou/ripple","version":"0.0.18","alg":"sha256","files":{"README.md":"BhsiYnbFSdDOWa6Mzt2EjUghpTfW5AQmhg+xkIck48A=","_headers":"/3GnajpvIIUp907PK8pIPx9H2wEmJgfEbrC3BKNLlgo=","api-DIgTslNb-BSzu7eku.js":"Bz7w65kFdIVwnCSxUxxNXi7LPH2Mta0M1aKoM+0OPss=","api-d5i206BT.js":"WRWCiUcBoC7+asLldepnOURaCl2SqA418OC96ZZBFeU=","app.webmanifest":"gIWmbT8RLQZNhLkGKZKO8zLWTEX3F1Dj7RAjIr1zEcQ=","assets/empty-BvRk9kiK.js":"47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=","assets/libtorrent-CnjRmD5O.js":"q09wBuBpwNzmPkmd5o3ue+rzrClzBmDQkwsHPFZrCKs=","assets/logo.png":"/u2ZiOWTOJxhO6AxbamaptNtn+kUxlrAiPncAEyqwIM=","assets/logo.svg":"3Ciuaqc0v2MjXzWy8x8yLaYwZsDdM0m1H42lzdQPKTg=","assets/sintel.torrent":"TI/a0EFLR2dUag+S/j1mCmbtwyRxh056HPqXEgMXuEo=","assets/worker-1qEVNJrZ.js":"R3RYmC9svlTMi3T8QWjmpMrUFrt30io8kpePpWh7s1E=","build-JdIfVZn7.js":"aIaK4j25GqAT2a1E+/Cwt+JRgmGKJTHysNMYPog5+gc=","index.html":"NzDOFOXPmq6jpxfz7igvOO2ti9cLkmZSJm1K3NhBxNE=","index.js":"N0p1U+WfVNnIxsWYC3UclVYf2sKDN1XYHx3cOUt9R2o=","jassub/default.woff2":"iGkpkDcHxbsosHzS7taZIbPV71xJxzoN0eGH6/ZUakw=","jassub/fonts.js":"JFrcfQn7ONAEVBPA8HdbKDW9YM3BYoIKvVpwHPdwMhw=","jassub/jassub-assets.js":"LkOyTls8XUtOqkH3PzaW5tDCgxL/e+3exAOIUP0F53Q=","jassub/jassub-worker-modern.wasm":"2ryQh6ZZOS3g/IbRZ8h6CF/HUA8xRabX9L8kMsxlDAM=","jassub/jassub-worker.js":"bakeHatafNtt0otborw+KQ/nnI5yRZ9aH7AUU9dnFS4=","jassub/jassub-worker.wasm":"IEZIYFRcqKpiSk7Fbv9FqzgDd89yR8MfQDY0IHeDbtE=","jassub/worker.js":"GkJ90cst1LkPx1b3tixhjcZBxzQ/o0h3VQMtYQJ3hA4=","libav-jspi.wasm":"k/NfZEYDgZk4M4qdSMDQfFMp/BGL+W7Rc2ZarwEJSvg=","libav-worker.js":"T6v9T4nmn6ayTrXy2CV5LLzvs/lkEMgw0wlb8E4O3pg=","libav.wasm":"Yj5TFMr+/vH6a3Uf7IPKuNXDPG7jeDxEEmvu2EBLYfQ=","package.json":"D9WPzq5Q1cWIiQvlFa2QN3e1zQPalOKtNHHiaP4+s4s=","remote-U0iHKFtw.js":"HVcgm0wvam8DUylwOFv8m2zGp8hmkw3fLu7nS48+DF8=","sw.js":"lJmvHJLmA0WsM7H2K4677FYGnaL/JavI4ZHQYlYK9GI=","volume-normalizer-worklet.js":"uERAQN4GaSzVMTY5hfsqvFH25HBOohimVr3HwLUM3WM="},"types":{"README.md":"text/markdown","_headers":"application/octet-stream","api-DIgTslNb-BSzu7eku.js":"text/javascript","api-d5i206BT.js":"text/javascript","app.webmanifest":"application/manifest+json","assets/empty-BvRk9kiK.js":"text/javascript","assets/libtorrent-CnjRmD5O.js":"text/javascript","assets/logo.png":"image/png","assets/logo.svg":"image/svg+xml","assets/sintel.torrent":"application/octet-stream","assets/worker-1qEVNJrZ.js":"text/javascript","build-JdIfVZn7.js":"text/javascript","index.html":"text/html","index.js":"text/javascript","jassub/default.woff2":"font/woff2","jassub/fonts.js":"text/javascript","jassub/jassub-assets.js":"text/javascript","jassub/jassub-worker-modern.wasm":"application/wasm","jassub/jassub-worker.js":"text/javascript","jassub/jassub-worker.wasm":"application/wasm","jassub/worker.js":"text/javascript","libav-jspi.wasm":"application/wasm","libav-worker.js":"text/javascript","libav.wasm":"application/wasm","package.json":"application/json","remote-U0iHKFtw.js":"text/javascript","sw.js":"text/javascript","volume-normalizer-worklet.js":"text/javascript"}},"keys":{"app":"fkn:app:1c7clnsv53zt7dr7q7rcbt455hxauykaxl4gibkuoao24dfmk2eqq","serial":1790278249316,"issuedAt":1790278249,"founder":{"kind":"fkn","seed":"fsqkqngttg4s2gpm23qiz5nonk"},"signer":"fkn-1","name":"Ripple","members":[{"key":"vB+5jsZMRya/m8nc1Ba6qNELaua1jUjbGj90dEzuaF0=","since":1790278249}],"sig":"1ulbdoxt48ngFVZw6Oufds/QhcKE2+KRG7ZQqShFVPeiPyoLGH2IR3m8CmeSOxe3tA7oTmAGKSc4vWZ6pAuFDQ=="}}
1
+ {"v":0,"app":"fkn:app:1c7clnsv53zt7dr7q7rcbt455hxauykaxl4gibkuoao24dfmk2eqq","name":"Ripple","version":"0.0.19","key":"vB+5jsZMRya/m8nc1Ba6qNELaua1jUjbGj90dEzuaF0=","issuedAt":1791753174,"perSource":["npm:@banou/ripple"],"url":"https://torrent.fkn.app/","contentsDigest":"7FscK+eLR31ZkexXBfvD+VBbUQTd5eL774cJhAv0hD4=","sig":"l+qafgjjwIoNrp4Mmu1cDpmmPI7+LgFdexdCyXtaKFuW2bP5pAuAKlSEYxrnf0t5YFsgcGlLDh8AYwX/vxcPCA==","contents":{"name":"@banou/ripple","version":"0.0.19","alg":"sha256","files":{"README.md":"BhsiYnbFSdDOWa6Mzt2EjUghpTfW5AQmhg+xkIck48A=","_headers":"/3GnajpvIIUp907PK8pIPx9H2wEmJgfEbrC3BKNLlgo=","api-DIgTslNb-BSzu7eku.js":"Bz7w65kFdIVwnCSxUxxNXi7LPH2Mta0M1aKoM+0OPss=","api-d5i206BT.js":"WRWCiUcBoC7+asLldepnOURaCl2SqA418OC96ZZBFeU=","app.webmanifest":"gIWmbT8RLQZNhLkGKZKO8zLWTEX3F1Dj7RAjIr1zEcQ=","assets/empty-BvRk9kiK.js":"47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=","assets/libtorrent-CnjRmD5O.js":"q09wBuBpwNzmPkmd5o3ue+rzrClzBmDQkwsHPFZrCKs=","assets/logo.png":"/u2ZiOWTOJxhO6AxbamaptNtn+kUxlrAiPncAEyqwIM=","assets/logo.svg":"3Ciuaqc0v2MjXzWy8x8yLaYwZsDdM0m1H42lzdQPKTg=","assets/sintel.torrent":"TI/a0EFLR2dUag+S/j1mCmbtwyRxh056HPqXEgMXuEo=","assets/worker-i0pDn8fp.js":"zarmKx7XSTiYIuw2YjdwIsqV/NzwyNrYbqXYgiATQa8=","build-JdIfVZn7.js":"aIaK4j25GqAT2a1E+/Cwt+JRgmGKJTHysNMYPog5+gc=","index.html":"NzDOFOXPmq6jpxfz7igvOO2ti9cLkmZSJm1K3NhBxNE=","index.js":"R+y7/07Ra9QSNEvGDIdMgkI/CFHNclXlems//n1iHUQ=","jassub/default.woff2":"iGkpkDcHxbsosHzS7taZIbPV71xJxzoN0eGH6/ZUakw=","jassub/fonts.js":"JFrcfQn7ONAEVBPA8HdbKDW9YM3BYoIKvVpwHPdwMhw=","jassub/jassub-assets.js":"LkOyTls8XUtOqkH3PzaW5tDCgxL/e+3exAOIUP0F53Q=","jassub/jassub-worker-modern.wasm":"2ryQh6ZZOS3g/IbRZ8h6CF/HUA8xRabX9L8kMsxlDAM=","jassub/jassub-worker.js":"bakeHatafNtt0otborw+KQ/nnI5yRZ9aH7AUU9dnFS4=","jassub/jassub-worker.wasm":"IEZIYFRcqKpiSk7Fbv9FqzgDd89yR8MfQDY0IHeDbtE=","jassub/worker.js":"GkJ90cst1LkPx1b3tixhjcZBxzQ/o0h3VQMtYQJ3hA4=","libav-jspi.wasm":"MEAQ3i+O1ZSYGVqP9UyRpdM4zdydljX7mX3+5blHXcA=","libav-worker.js":"DbxMU+90HP9hRjy5mHqhkVBxMSTAHtSnXgvpAe3gZy0=","libav.wasm":"cu4WLx4dsl85gHuQdU5EY6H9btNctu9kkPDcRPc102g=","package.json":"YGvdO/mj9Wtb11D6OOZH2qs0ED7wmkoiwATHiXe7iIE=","remote-U0iHKFtw.js":"HVcgm0wvam8DUylwOFv8m2zGp8hmkw3fLu7nS48+DF8=","sw.js":"lYZp9wakPNK3ulmGSKnxUoC94bIXmqI0k3Emd7UdO4Y=","volume-normalizer-worklet.js":"uERAQN4GaSzVMTY5hfsqvFH25HBOohimVr3HwLUM3WM="},"types":{"README.md":"text/markdown","_headers":"application/octet-stream","api-DIgTslNb-BSzu7eku.js":"text/javascript","api-d5i206BT.js":"text/javascript","app.webmanifest":"application/manifest+json","assets/empty-BvRk9kiK.js":"text/javascript","assets/libtorrent-CnjRmD5O.js":"text/javascript","assets/logo.png":"image/png","assets/logo.svg":"image/svg+xml","assets/sintel.torrent":"application/octet-stream","assets/worker-i0pDn8fp.js":"text/javascript","build-JdIfVZn7.js":"text/javascript","index.html":"text/html","index.js":"text/javascript","jassub/default.woff2":"font/woff2","jassub/fonts.js":"text/javascript","jassub/jassub-assets.js":"text/javascript","jassub/jassub-worker-modern.wasm":"application/wasm","jassub/jassub-worker.js":"text/javascript","jassub/jassub-worker.wasm":"application/wasm","jassub/worker.js":"text/javascript","libav-jspi.wasm":"application/wasm","libav-worker.js":"text/javascript","libav.wasm":"application/wasm","package.json":"application/json","remote-U0iHKFtw.js":"text/javascript","sw.js":"text/javascript","volume-normalizer-worklet.js":"text/javascript"}},"keys":{"app":"fkn:app:1c7clnsv53zt7dr7q7rcbt455hxauykaxl4gibkuoao24dfmk2eqq","serial":1790278249316,"issuedAt":1790278249,"founder":{"kind":"fkn","seed":"fsqkqngttg4s2gpm23qiz5nonk"},"signer":"fkn-1","name":"Ripple","members":[{"key":"vB+5jsZMRya/m8nc1Ba6qNELaua1jUjbGj90dEzuaF0=","since":1790278249}],"sig":"1ulbdoxt48ngFVZw6Oufds/QhcKE2+KRG7ZQqShFVPeiPyoLGH2IR3m8CmeSOxe3tA7oTmAGKSc4vWZ6pAuFDQ=="}}