@banou/ripple 0.0.120 → 0.0.121
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"../index-
|
|
1
|
+
import{t as e}from"../index-BiNo8TDE.js";var t=[`loadstart`,`loadedmetadata`,`loadeddata`,`durationchange`,`timeupdate`,`play`,`playing`,`pause`,`seeking`,`seeked`,`progress`,`ratechange`,`volumechange`,`ended`,`waiting`,`stalled`,`suspend`,`canplay`,`canplaythrough`,`emptied`,`resize`,`error`],n=[`chapterschange`,`fullscreenrequest`,`autoplaynextchange`,`previousrequest`,`nextrequest`,`sourceswitchrequest`,`subtitlesbrowserequest`,`subtitleloadrequest`],r=[`currentTime`,`volume`,`muted`,`playbackRate`],i=[`play`,`pause`,`load`],a=e=>[`loadstart`,...e.readyState>=1?[`loadedmetadata`,`durationchange`]:[],...e.readyState>=2?[`loadeddata`]:[],...e.readyState>=3?[`canplay`]:[],`volumechange`,`ratechange`,`progress`,`resize`,e.paused?`pause`:`playing`,...e.ended?[`ended`]:[],...e.error?[`error`]:[]],o=e=>{if(!e)return[];let t=[];for(let n=0;n<e.length;n++)t.push([e.start(n),e.end(n)]);return t},s=(e,t=[],n=!0,r=null)=>({currentTime:c(e.currentTime),duration:c(e.duration),paused:e.paused,ended:e.ended??!1,seeking:e.seeking,readyState:e.readyState,volume:e.volume??1,muted:e.muted??!1,playbackRate:e.playbackRate??1,src:e.src??``,currentSrc:e.currentSrc??``,buffered:o(e.buffered),seekable:o(e.seekable),error:e.error?{code:e.error.code,message:e.error.message}:null,videoWidth:e.videoWidth??0,videoHeight:e.videoHeight??0,chapters:t,endingOffered:n,autoplayNext:r}),c=e=>Number.isNaN(e)?0:e,l={currentTime:0,duration:0,paused:!0,ended:!1,seeking:!1,readyState:0,volume:1,muted:!1,playbackRate:1,src:``,currentSrc:``,buffered:[],seekable:[],error:null,videoWidth:0,videoHeight:0,chapters:[],endingOffered:!0,autoplayNext:null},u=[[`previousEpisode`,`onPreviousEpisode`],[`nextEpisode`,`onNextEpisode`],[`sourceSwitch`,`onSourceSwitch`],[`browseSubtitles`,`onBrowseSubtitles`]],d=Object.fromEntries(u),f=e=>Object.hasOwn(d,e),p=8,m=32,h=(e,t={})=>{y(t.origin);let n=typeof window<`u`&&window.parent!==window;return!t.transport&&!n?()=>{}:v(t).serve(e,t)},g=new WeakMap,_=new Map,v=o=>{let c=o.channel??`banou-media-player`,h=o.transport,v=`${c}|${o.origin??`*`}`,y=h?g.get(h)??(g.set(h,new Map),g.get(h)):_,b=y.get(v);if(b)return b;let S=new Map,C=new Map,w=new Map,T=e=>w.get(e)??w.set(e,new Set).get(e),E=new Map,D=new Map,O=e=>C.get(e)?.onHostFullscreen(E.get(e)?.size?D.get(e)??!1:null),k=new Map,A=e=>C.get(e)?.onAutoplayNext(k.get(e)??null),j=new Map(u.map(([e])=>[e,new Map])),M=(e,t)=>{let n=j.get(t);C.get(e)?.[d[t]]?.(n.has(e)?n.get(e):void 0)},N=new Map,P=e=>C.get(e)?.onExternalSubtitles?.(N.get(e)??null),F=(e,t)=>{if(w.get(e)?.delete(t),E.get(e)?.delete(t)&&O(e),!w.get(e)?.size){k.delete(e)&&A(e);for(let[t,n]of j)n.delete(e)&&M(e,t);N.delete(e)&&P(e)}try{t.onmessage=null,t.close()}catch{}},I=(e,t,n=T(e))=>{for(let r of[...n])try{r.postMessage(t)}catch{F(e,r)}},L=e=>{let t=S.get(e),n=C.get(e);return t?s(t,n?.chapters,n?.endingOffered,n?.autoplayNext):void 0},R=(e,t,n)=>{let r=t===`fullscreenrequest`?E.get(e):w.get(e);if(!r?.size)return;let i=L(e);i&&I(e,n?{event:t,snapshot:i,detail:n}:{event:t,snapshot:i},r)},z={subscribe:(e,t,n)=>{if(typeof e!=`string`)throw TypeError(`a player id must be a string`);if(typeof MessagePort<`u`&&!(t instanceof MessagePort))throw TypeError(`subscribe takes a MessagePort`);if(!w.has(e)&&w.size>=m)throw RangeError(`too many players on this channel`);let r=T(e);if(r.size>=p)throw RangeError(`too many embedders for this player`);r.add(t);let i=n?.fullscreen;typeof i==`boolean`&&((E.get(e)??E.set(e,new Set).get(e)).add(t),D.set(e,i),O(e)),t.onmessage=()=>F(e,t),t.start?.();let a=L(e);a&&I(e,{event:`loadstart`,snapshot:a},[t])},set:(e,t,n)=>{if(t===`fullscreen`){if(typeof n!=`boolean`||!E.get(e)?.size)return;D.set(e,n),O(e);return}if(t===`endingOffered`){typeof n==`boolean`&&C.get(e)?.onEndingOffered(n);return}if(t===`autoplayNext`){if(typeof n!=`boolean`||!w.get(e)?.size)return;k.set(e,n),A(e);return}if(f(t)){if(typeof n!=`boolean`&&typeof n!=`string`&&n!==null||!w.get(e)?.size)return;j.get(t).set(e,n),M(e,t);return}let i=S.get(e);if(i&&r.includes(t))try{i[t]=n}catch{}},setExternalSubtitles:(e,t)=>{if(typeof e!=`string`||!w.get(e)?.size||!Array.isArray(t))return;let n=[];for(let e of t){if(n.length>=64)break;if(!e||typeof e!=`object`)continue;let{id:t,language:r,label:i,format:a,content:o}=e;typeof t==`string`&&typeof r==`string`&&typeof i==`string`&&(a===`srt`||a===`vtt`||a===`ass`)&&(typeof o==`string`&&o.length>5242880||n.push({id:t,language:r,label:i,format:a,...typeof o==`string`?{content:o}:{}}))}N.set(e,n),P(e)},provideExternalSubtitle:(e,t,n,r)=>{if(typeof e==`string`&&typeof t==`string`&&w.get(e)?.size&&(n===null||typeof n==`string`)&&(r===void 0||typeof r==`string`)){if(typeof n==`string`&&n.length>5242880){C.get(e)?.onProvideExternalSubtitle?.(t,null,`External subtitle exceeds size limit`);return}C.get(e)?.onProvideExternalSubtitle?.(t,n,r)}},selectExternalSubtitle:(e,t)=>{typeof e==`string`&&typeof t==`string`&&w.get(e)?.size&&C.get(e)?.onSelectExternalSubtitle?.(t)},call:async(e,t)=>{let n=S.get(e);if(n&&i.includes(t))try{t===`play`?await n.play():t===`pause`?n.pause():n.load?.()}finally{R(e,`timeupdate`)}}},B=new AbortController;B.signal.addEventListener(`abort`,()=>{y.delete(v);for(let[e,t]of w)for(let n of[...t])F(e,n);w.clear(),S.clear(),C.clear()},{once:!0}),e(z,{transport:o.transport??{emit:window.parent,receive:x(()=>window.parent,o.origin)},origin:o.origin,key:c,unregisterSignal:B.signal});let V={serve:(e,r)=>{let i=r.id??`default`,o=r.player,s=[...t.map(t=>[e,t]),...o?n.map(e=>[o,e]):[]].map(([t,n])=>[t,n,t=>{if(S.get(i)!==e)return;n===`autoplaynextchange`&&k.has(i)&&typeof o?.autoplayNext==`boolean`&&k.set(i,o.autoplayNext);let r=n===`subtitleloadrequest`?t.detail:void 0,a=r&&typeof r==`object`&&typeof r.trackId==`string`?{trackId:r.trackId}:void 0;R(i,n,a)}]);for(let[e,t,n]of s)e.addEventListener(t,n);let c=S.has(i),d=C.get(i);if(d&&d!==o){d.onHostFullscreen(null);for(let[,e]of u)d[e]?.(void 0);d.onExternalSubtitles?.(null)}S.set(i,e),o?C.set(i,o):C.delete(i),O(i),k.has(i)&&A(i);for(let[e,t]of j)t.has(i)&&M(i,e);N.has(i)&&P(i),c&&I(i,{event:`emptied`,snapshot:{...l}});for(let e of a(L(i)))R(i,e);let f=()=>{for(let[e,t,n]of s)e.removeEventListener(t,n);if(S.get(i)===e){if(S.delete(i),o&&C.get(i)===o){C.delete(i),o.onHostFullscreen(null);for(let[,e]of u)o[e]?.(void 0);o.onExternalSubtitles?.(null)}I(i,{event:`emptied`,snapshot:{...l}})}},p=()=>{f(),B.abort()};return r.signal&&(r.signal.aborted?p():r.signal.addEventListener(`abort`,p,{once:!0})),f}};return y.set(v,V),V},y=e=>{if(e===void 0||e===`*`)return;if(e===`null`)throw TypeError('an opaque origin ("null") cannot be spoken to; leave `origin` unset and the sender check stands alone');let t;try{t=new URL(e)}catch{throw TypeError(`\`origin\` must be an origin like https://example.com, not ${e}`)}if(t.origin!==e)throw TypeError(`\`origin\` must be an origin like ${t.origin}, not ${e}`)},b=e=>{let t=e&&e!==`*`?e:void 0;return{target:()=>t&&t!==`null`?t:`*`,admits:e=>t?e===t:(e&&(t=e),!0)}},x=(e,t,n=b(t))=>t=>{let r=r=>{r.source===e()&&n.admits(r.origin)&&t(r.data,{source:r.source,origin:r.origin,receiveTransport:window})};return window.addEventListener(`message`,r),()=>window.removeEventListener(`message`,r)};export{h as exposePlayer};
|
|
@@ -24,4 +24,4 @@ var t=Du(),n=Ou(),r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Sym
|
|
|
24
24
|
var n=ku(),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)}})),zd=/* @__PURE__ */ t((e=>{var t=Rd().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):``}})),Bd=/* @__PURE__ */ t(((e,t)=>{var n=Nd().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})),Vd=/* @__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=Bd(),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}})),Hd=/* @__PURE__ */ t(((e,t)=>{t.exports=function(){throw Error(`Readable.from is not available in the browser`)}})),Ud=/* @__PURE__ */ t(((e,t)=>{t.exports=E;var n;E.ReadableState=T,wu().EventEmitter;var r=function(e,t){return e.listeners(t).length},i=Eu(),a=ku().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=Ad(),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=jd(),f=Md(),p=Pd().getHighWaterMark,m=Nd().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;Tu()(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||=Ld(),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||=zd().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=Ld(),!(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,ne(e,o);else{var c;if(i||(c=ee(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):N(e,o)):O(e,o,t,!1)}else r||(o.reading=!1,N(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&&j(e)),N(e,t)}function ee(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||=zd().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 k=1073741824;function te(e){return e>=k?e=k:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function A(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=te(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?se(this):j(this),null;if(e=A(e,t),e===0&&t.ended)return t.length===0&&se(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=A(n,t)));var i=e>0?oe(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&&se(this)),i!==null&&this.emit(`data`,i),i};function ne(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?j(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,M(e)))}}function j(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(M,e))}function M(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,ae(e)}function N(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(P,e,t))}function P(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=F(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&&le(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 F(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,ae(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=le(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?j(this):r.reading||process.nextTick(I,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(re,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(re,this),t};function re(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 I(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,L(this,e)),e.paused=!1,this};function L(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ie,e,t))}function ie(e,t){u(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),ae(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 ae(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=Vd()),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=oe,Object.defineProperty(E.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function oe(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 se(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(ce,t,e))}function ce(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=Hd()),x(E,e,t)});function le(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),Wd=/* @__PURE__ */ t(((e,t)=>{t.exports=l;var n=Nd().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=Ld();Tu()(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)}})),Gd=/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=Wd();Tu()(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)}})),Kd=/* @__PURE__ */ t(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=Nd().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=Bd()),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})),qd=(/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=wu().EventEmitter;Tu()(r,n),r.Readable=Ud(),r.Writable=Id(),r.Duplex=Ld(),r.Transform=Wd(),r.PassThrough=Gd(),r.finished=Bd(),r.pipeline=Kd(),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}})))(),Jd=wu(),Yd=class extends qd.Stream.Duplex{_localAddress;_remoteAddress;_webVPNTcpSocketPromise;_relay;constructor(e){if(e?.fd!==void 0)throw Error(`FKN WebVPN does not support file descriptors`);super({...e,allowHalfOpen:!!e?.allowHalfOpen,autoDestroy:!0}),e?.connection&&this.__webvpn_tcp_socket_init__(e.connection)}_busyRelease;__webvpn_tcp_socket_init__(e,t){return this._busyRelease??=cu(`tcp socket`),t&&(this._localAddress={address:t.localAddress,family:t.localFamily,port:t.localPort},this._remoteAddress={address:t.remoteAddress,family:t.remoteFamily,port:t.remotePort},this._relay=t.relay,this._connected=!0),this._webVPNTcpSocketPromise=e.then(e=>{let t=e.dataReadableStream.getReader(),n=e.dataWritableStream.getWriter();return this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},this._remoteAddress={address:e.remoteAddress,family:e.remoteFamily,port:e.remotePort},this._relay=e.relay,{...e,reader:t,writer:n}}).catch(e=>{this.destroyed||this.destroy(Cu(e))}),this._webVPNTcpSocketPromise.then(e=>{e&&!this.destroyed&&(this._connected=!0,this.emit(`connect`),this.isPaused()||this.read(0))}),this._webVPNTcpSocketPromise}_connected=!1;_read(e){if(!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);this._webVPNTcpSocketPromise.then(e=>{e?e.reader.read().then(({value:e,done:t})=>{t?(this.push(null),this.read(0)):(this._restartTimeoutTimer(),this.push(e))}).catch(e=>{this.destroy(Cu(e))}):this.push(null)})}_write(e,t,n){this._webVPNTcpSocketPromise?this._webVPNTcpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not connected`);await t.writer.ready,await t.writer.write(e)}).then(()=>{this.destroyed||(this._restartTimeoutTimer(),n())},e=>this._fail(e)):n(/* @__PURE__ */ Error(`Socket not connected`))}_fail(e){if(!this.destroyed){e=Cu(e);for(let t of this._pendingCallbacks)t(e);this.destroy(e)}}connect(...e){let t=iu(...e),{relay:n}=t,r=this.__webvpn_tcp_socket_init__(Eo(`an outbound tcp socket`).then(e=>(n!==void 0&&mu(e,`net.connect`),e.cloud.webvpn.tcpSocket({remoteAddress:t.host??`localhost`,remotePort:t.port,relay:n}))));return t.callback&&r.then(e=>{e&&!this.destroyed&&t.callback.call(this)}),this}_final(e){this._webVPNTcpSocketPromise?this._webVPNTcpSocketPromise.then(async e=>{e&&await e.writer.close()}).then(()=>{this.destroyed||e()},e=>this._fail(e)):e()}_destroyError;_destroy(e,t){this._destroyError=e??void 0,this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._busyRelease?.(),this._webVPNTcpSocketPromise?this._webVPNTcpSocketPromise.then(async t=>{t&&(this._resetRequested?await t.resetAndDestroy():!e&&this._writableState.finished&&this._readableState.ended?await t.end():await t.destroy())}).then(()=>t(e),()=>t(e)):t(e)}destroy(e,t){return this.destroyed&&!t?this:(Object.assign(this,{readable:!1,writable:!1}),Reflect.apply(super.destroy,this,[e,t]))}emit(e,...t){if(e===`finish`)for(let e of this._endCallbacks.splice(0))e();if(e!==`close`||!this.destroyed)return super.emit(e,...t);let n=this._destroyError!==void 0;if(!this._connected){let e=super.emit(`close`,n);return this._settlePending(Object.assign(/* @__PURE__ */ Error(`Socket closed before the connection was established`),{code:`ERR_SOCKET_CLOSED_BEFORE_CONNECTION`})),e}return this._settlePending(Object.assign(/* @__PURE__ */ Error(`write ECANCELED`),{code:`ECANCELED`,syscall:`write`})),super.emit(`close`,n)}_settlePending(e){let t=e;for(let e of this._pendingCallbacks)e(t),t=this._destroyError??t}destroySoon(){this._writableState.finished?this.destroy():(this.once(`finish`,()=>this.destroy()),this.end())}_resetRequested=!1;resetAndDestroy(){return this._resetRequested=!0,this.destroy(),this}_timeoutMs;_timeoutTimer;_restartTimeoutTimer(){this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._timeoutMs&&!this.destroyed&&(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=typeof e==`object`&&e?e:{enable:e,initialDelay:t},r=n.initialDelay,i=r!==void 0&&r>0?Math.max(1,Math.round(r/1e3)):0;return this._setTcpOption({type:2,enabled:n.enable??!1,initialDelaySeconds:i}),this}setSendBufferSize(e){return this._setTcpOption({type:3,value:e}),this}setRecvBufferSize(e){return this._setTcpOption({type:4,value:e}),this}_typeOfService;getTypeOfService(){return this._typeOfService??0}setTypeOfService(e){return this._typeOfService=e,this}_setTcpOption(e){this._webVPNTcpSocketPromise?this._webVPNTcpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.destroyed||this.emit(`error`,e)}}):this.emit(`error`,/* @__PURE__ */ Error(`Cannot set socket option before connect`))}_pendingCallbacks=/* @__PURE__ */ new Set;_settleOnClose(e){let t=n=>{this._pendingCallbacks.delete(t)&&e(n)};return this._pendingCallbacks.add(t),t}end(e,t,n){if(typeof t==`function`&&(n=t,t=void 0),typeof e==`function`&&(n=e,e=void 0),e==null&&this._writableState.finished){let e=Object.assign(/* @__PURE__ */ Error(`Cannot call end after a stream was finished`),{code:`ERR_STREAM_ALREADY_FINISHED`});return n&&queueMicrotask(()=>n(e)),this}return this.destroyed?(e!=null&&this.write(e,t,n),this):(n&&this._endCallbacks.push(this._settleOnClose(n)),Reflect.apply(super.end,this,[e,t]))}_endCallbacks=[];write(e,t,n){if(typeof t==`function`&&(n=t,t=void 0),this.destroyed){let e=Object.assign(/* @__PURE__ */ Error(`Cannot call write after a stream was destroyed`),{code:`ERR_STREAM_DESTROYED`});return n&&queueMicrotask(()=>n(e)),!1}if(!n)return t?super.write(e,t):super.write(e);let r=this._settleOnClose(n);return t?super.write(e,t,r):super.write(e,r)}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;server=null},Xd=class extends Jd.EventEmitter{_localAddress;_webVPNTcpSocketListenerPromise;_relayChoice;_allowHalfOpen;_relay;constructor(e,t){super(e),this._relayChoice=e?.relay,this._allowHalfOpen=!!e?.allowHalfOpen,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??=cu(`tcp server`),this._webVPNTcpSocketListenerPromise=e.then(e=>(this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},this._relay=e.relay,e)).catch(e=>{this.emit(`error`,Cu(e))}),this._webVPNTcpSocketListenerPromise.then(e=>{e?this.emit(`listening`):this._busyRelease?.()}),this._webVPNTcpSocketListenerPromise}listen(...e){let t=iu(...e);this._closeEmitted=!1;let n=e=>{let t=new Yd({allowHalfOpen:this._allowHalfOpen});t.server=this,t.__webvpn_tcp_socket_init__(Promise.resolve(e),e),this.emit(`connection`,t)},r=e=>{this._localAddress=void 0;try{e&&this.listenerCount(`error`)>0&&this.emit(`error`,e)}finally{this._emitClose()}},i=this._relayChoice,a=e=>Eo(`a tcp listener`).then(a=>(i!==void 0&&mu(a,`net.createServer`),a.cloud.webvpn.tcpSocketListener({localAddress:e,localPort:t.port,onConnection:n,onClose:r,relay:i}))),o=t.host?a(t.host):a(`::`).catch(()=>a(`0.0.0.0`)),s=this.__webvpn_tcp_socket_listener_init__(o);return t.callback&&s.then(e=>{e&&t.callback.call(this)}),this}_closeEmitted=!1;_emitClose(){this._closeEmitted||(this._closeEmitted=!0,this._busyRelease?.(),this.emit(`close`))}close(e){return this._webVPNTcpSocketListenerPromise&&this._webVPNTcpSocketListenerPromise.then(async t=>{if(t)try{await t.close(),this._localAddress=void 0,this._emitClose(),e&&e()}catch(t){this._localAddress=void 0,this._emitClose(),e&&e(t)}}),this}address(){return this._localAddress??null}getConnections(e){throw Error(`Method not implemented.`)}ref(){return this}unref(){return this}maxConnections;connections;listening;async[Symbol.asyncDispose](){}},Zd=(e,t)=>new Yd({allowHalfOpen:e?.allowHalfOpen}).connect(e,t),Qd=Zd,$d=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new Xd(e);return t&&n.on(`connection`,t),n},ef={Socket:Yd,Server:Xd,connect:Zd,createConnection:Qd,createServer:$d,isIP:ru,isIPv4:tu,isIPv6:nu},tf=/* @__PURE__ */ n({Server:()=>Xd,Socket:()=>Yd,_default:()=>ef,connect:()=>Zd,createConnection:()=>Qd,createServer:()=>$d,default:()=>ef,isIP:()=>ru,isIPv4:()=>tu,isIPv6:()=>nu}),nf=0,rf=1,af=2,of=3,sf=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,cf=new TextEncoder,lf={code:1006,reason:``,wasClean:!1,error:!1},uf=e=>{let t;try{t=new URL(e,globalThis.document?.baseURI??globalThis.location?.href)}catch{throw new DOMException(`The URL '${e}' is invalid.`,`SyntaxError`)}if(t.protocol===`http:`?t.protocol=`ws:`:t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol!==`ws:`&&t.protocol!==`wss:`)throw new DOMException(`The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${t.protocol}' is not allowed.`,`SyntaxError`);if(t.hash||t.href.endsWith(`#`))throw new DOMException(`The URL contains a fragment identifier.`,`SyntaxError`);return t},df=e=>{if(typeof e==`string`)return[e,cf.encode(e).byteLength];if(e instanceof Blob)return[e,e.size];let t=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);return[t.slice().buffer,t.byteLength]},ff=class extends EventTarget{static CONNECTING=nf;static OPEN=rf;static CLOSING=af;static CLOSED=of;url;extensions=``;#e=`blob`;#t=nf;#n=``;#r=0;#i;#a;#o;#s;#c=/* @__PURE__ */ new Map;constructor(e,t=[]){super();let n=uf(e),r=typeof t==`string`?[t]:[...t];if(new Set(r).size!==r.length||r.some(e=>!sf.test(e)))throw new DOMException(`The subprotocols are not unique tokens.`,`SyntaxError`);if(r.some(e=>e===`fkn-proxy`||e.startsWith(`fkn-proxy.`)))throw new DOMException(`The subprotocol '${du}' and those starting '${fu}' are FKN's.`,`SyntaxError`);if(c(n.hostname))throw Error(`websocket refuses FKN platform domains (${n.hostname})`);this.url=n.href,this.#i=n.origin,this.#s=cu(`websocket`),Eo(`a websocket`).then(e=>e.cloud.websocket({url:this.url,protocols:r})).then(e=>this.#l(e)).catch(()=>this.#u({...lf,error:!0}))}get readyState(){return this.#t}get protocol(){return this.#n}get bufferedAmount(){return this.#r}get binaryType(){return this.#e}set binaryType(e){(e===`blob`||e===`arraybuffer`)&&(this.#e=e)}send(e){if(this.#t===nf)throw new DOMException(`Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.`,`InvalidStateError`);let[t,n]=df(e);this.#r+=n,this.#t===rf&&this.#o.write(t).then(()=>{this.#r-=n},()=>{})}close(e,t){if(e!==void 0&&e!==1e3&&(e<3e3||e>4999))throw new DOMException(`The close code must be either 1000, or between 3000 and 4999. ${e} is neither.`,`InvalidAccessError`);if(t!==void 0&&cf.encode(t).byteLength>123)throw new DOMException(`The close reason must not be greater than 123 UTF-8 bytes.`,`SyntaxError`);if(this.#t===af||this.#t===of)return;if(e===void 0&&t!==void 0&&(e=1e3),this.#t===nf){this.#t=af,setTimeout(()=>this.#u({...lf,error:!0}),0);return}this.#t=af;let n=this.#a;this.#o.close().catch(()=>{}).then(()=>n.close(e,t)).catch(()=>{})}async#l(e){if(this.#t!==nf){e.close().catch(()=>{});return}this.#a=e,this.#n=e.protocol,this.#o=e.writable.getWriter(),this.#t=rf,this.dispatchEvent(new Event(`open`));let t=e.readable.getReader();try{for(;;){let{value:e,done:n}=await t.read();if(n)break;if(this.#t!==rf)continue;let r=typeof e==`string`||this.#e===`arraybuffer`?e:new Blob([e]);this.dispatchEvent(new MessageEvent(`message`,{data:r,origin:this.#i}))}}catch{return this.#u(lf)}let n=await e.closed.then(e=>typeof e?.code==`number`?e:lf,()=>lf);this.#u(n)}#u({code:e,reason:t,wasClean:n,error:r}){this.#t!==of&&(this.#t=of,this.#s(),r&&this.dispatchEvent(new Event(`error`)),this.dispatchEvent(new CloseEvent(`close`,{code:e,reason:t,wasClean:n})))}#d(e){return this.#c.get(e)?.handler??null}#f(e,t){let n=this.#c.get(e);if(typeof t!=`function`){n&&this.removeEventListener(e,n.listener),this.#c.delete(e);return}if(n){n.handler=t;return}let r={handler:t,listener:e=>{r.handler.call(this,e)}};this.#c.set(e,r),this.addEventListener(e,r.listener)}get onopen(){return this.#d(`open`)}set onopen(e){this.#f(`open`,e)}get onmessage(){return this.#d(`message`)}set onmessage(e){this.#f(`message`,e)}get onerror(){return this.#d(`error`)}set onerror(e){this.#f(`error`,e)}get onclose(){return this.#d(`close`)}set onclose(e){this.#f(`close`,e)}};for(let[e,t]of Object.entries({CONNECTING:nf,OPEN:rf,CLOSING:af,CLOSED:of}))Object.defineProperty(ff.prototype,e,{value:t,enumerable:!0});var pf=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},mf=(e,...t)=>{let n=pf(t.map(e=>e instanceof Uint8Array?e:new Uint8Array(e))),r=n.length,i=r<128?[r]:r<256?[129,r]:[130,r>>8,r&255];return pf([new Uint8Array([e,...i]),n])},hf=e=>{let t=0;for(;t<e.length-1&&e[t]===0&&!(e[t+1]&128);)t++;let n=e.subarray(t);return mf(2,n[0]&128?[0]:[],n)},gf=e=>mf(23,new TextEncoder().encode(e.toISOString().replace(/[-:T]/g,``).slice(2,14)+`Z`)),_f=mf(48,mf(6,[42,134,72,206,61,4,3,2])),vf=mf(48,mf(49,mf(48,mf(6,[85,4,3]),mf(12,new TextEncoder().encode(`WebRTC`))))),yf=864e5;async function bf(){let e=await crypto.subtle.generateKey({name:`ECDSA`,namedCurve:`P-256`},!0,[`sign`]),t=new Uint8Array(await crypto.subtle.exportKey(`spki`,e.publicKey)),n=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));n[0]=n[0]&127|64;let r=Date.now(),i=mf(48,mf(160,hf(new Uint8Array([2]))),hf(n),_f,vf,mf(48,gf(/* @__PURE__ */ new Date(r-yf)),gf(new Date(r+30*yf))),vf,t),a=new Uint8Array(await crypto.subtle.sign({name:`ECDSA`,hash:`SHA-256`},e.privateKey,i));return{certificate:mf(48,i,_f,mf(3,[0],mf(48,hf(a.subarray(0,32)),hf(a.subarray(32))))),privateKey:new Uint8Array(await crypto.subtle.exportKey(`pkcs8`,e.privateKey))}}var xf=0,Sf=1,Cf=2,wf=3,Tf=4,Ef=5,Df=6,Of=7,kf=8,Af=262144,jf=16777216,Mf=128,Nf=new TextEncoder,Pf=new TextDecoder,Ff=()=>{},If=e=>{let t=e.split(`.`);if(!(t.length!==4||t.some(e=>!/^\d{1,3}$/.test(e)||Number(e)>255)))return t.reduce((e,t)=>e*256+Number(t),0)},Lf=e=>`${e>>>24}.${e>>>16&255}.${e>>>8&255}.${e&255}`,Rf=e=>{let t=e>>>24,n=e>>>16&255,r=e>>>8&255;return!(t===0||t===10||t===127||t>=224||t===100&&n>=64&&n<128||t===169&&n===254||t===172&&n>=16&&n<32||t===192&&n===0&&(r===0||r===2)||t===192&&n===168||t===198&&(n===18||n===19)||t===198&&n===51&&r===100||t===203&&n===0&&r===113)},zf=e=>e.split(/\r?\n/).filter(e=>{if(!e.startsWith(`a=candidate:`))return!0;let t=If(e.split(` `)[4]??``);return t!==void 0&&Rf(t)}).join(`\r
|
|
25
25
|
`);function Bf(e,...t){for(let n of t){let t=Symbol(`on${n}`);Object.defineProperty(e.prototype,`on${n}`,{get(){return this[t]??null},set(e){t in this||this.addEventListener(n,e=>this[t]?.call(this,e)),this[t]=typeof e==`function`?e:null}})}}var Vf=e=>new DOMException(e,`OperationError`),Hf=class{x;socket;ip;port;allowPrivateCandidates;sendBufferSize;certificate;key;panic;connections=/* @__PURE__ */ new Set;routes=/* @__PURE__ */ new Map;dropped=0;closed=!1;#e=0;#t=0;#n=!1;#r=[];#i;#a=0;#o=0;constructor(e,t,n,r,i,a,o,s,c){this.x=e,this.socket=t,this.ip=n,this.port=r,this.allowPrivateCandidates=i,this.sendBufferSize=a,this.certificate=o,this.key=s,this.panic=c,t.on(`message`,this.receive),t.on(`error`,this.fail),t.on(`close`,this.fail)}transmit(e,t,n){this.closed||this.#e<Mf?(this.#e++,this.#n||(this.#n=!0,queueMicrotask(()=>{this.#n=!1})),this.socket.send(e,t,n,Ff)):(this.#r.push([e,t,n]),this.#s())}#s(){this.#i===void 0&&(this.#i=setTimeout(()=>{this.#i=void 0,this.#c()},1))}#c(){let e=performance.now();if(e-this.#t>=1){this.#t=e,this.#e=0;try{for(let e of this.#r.splice(0,Mf))this.transmit(...e)}catch(e){this.fail(e)}}this.#r.length&&this.#s()}put(e){return e.length>this.#o&&(this.#o&&this.x.rtc_free(this.#a,this.#o),this.#o=Math.max(e.length,Af),this.#a=this.x.rtc_alloc(this.#o)),new Uint8Array(this.x.memory.buffer,this.#a,e.length).set(e),this.#a}create(){let{x:e,certificate:t,key:n}=this,r=e.rtc_alloc(t.length),i=e.rtc_alloc(n.length);new Uint8Array(e.memory.buffer,r,t.length).set(t),new Uint8Array(e.memory.buffer,i,n.length).set(n);let a=e.rtc_new(r,t.length,i,n.length,this.ip,this.port,Af,this.sendBufferSize);return e.rtc_free(r,t.length),e.rtc_free(i,n.length),a}receive=(e,t)=>{this.#n||this.#c();let n=`${t.address}:${t.port}`,r=this.routes.get(n);if(!r){let i=If(t.address),a=i===void 0?void 0:this.#l(i,t.port,e);if(i===void 0||!a){this.dropped++;return}r={connection:a,ip:i},this.routes.set(n,r)}r.connection.receive(r.ip,t.port,e)};#l(e,t,n){let r=this.put(n);for(let i of this.connections)if(this.x.rtc_accepts(i.handle,e,t,r,n.length))return i}forget(e){this.connections.delete(e);for(let[t,n]of this.routes)n.connection===e&&this.routes.delete(t)}fail=e=>{let t=e&&Vf(`the socket failed: ${e.message}`);this.close(e=>e.end(`failed`,t))};close(e=e=>e.end(`closed`)){if(!this.closed){this.closed=!0,this.socket.off(`message`,this.receive),this.socket.off(`error`,this.fail),this.socket.off(`close`,this.fail),this.#r.length=0;for(let t of this.connections)e(t)}}},Uf=class{connection;label;target=new Gf(this);index=-1;state=`connecting`;streaming=!1;queue=[];queuedBytes=0;inStack=0;stale=!1;threshold=0;high=!1;constructor(e,t){this.connection=e,this.label=t}get buffered(){return this.queuedBytes+this.inStack}send(e){if(this.state!==`open`)throw new DOMException(`the channel is ${this.state}`,`InvalidStateError`);let t=typeof e==`string`?Nf.encode(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice():e instanceof ArrayBuffer?new Uint8Array(e.slice(0)):void 0;if(!t)throw TypeError(`a message is a string, an ArrayBuffer or a view of one`);if(!t.length)throw new DOMException(`an empty message cannot be sent`,`NotSupportedError`);if(t.length>this.connection.sctp.maxMessageSize)throw TypeError(`the message is larger than the max message size, ${this.connection.sctp.maxMessageSize}`);let n=this.buffered+t.length;if(n>jf)throw Vf(`the send queue is full`);this.queue.push({bytes:t,binary:typeof e!=`string`}),this.queuedBytes+=t.length,n>this.threshold&&(this.high=!0),this.connection.schedule()}close(){if(this.state===`closing`||this.state===`closed`)return;this.state=`closing`;let e=this.connection.waiting.indexOf(this);if(e<0)return this.connection.schedule();this.connection.waiting.splice(e,1),queueMicrotask(()=>this.closed())}closed(e){this.state!==`closed`&&(this.state=`closed`,this.streaming=!1,this.queue.length=0,this.queuedBytes=0,this.inStack=0,this.high=!1,e&&this.target.dispatchEvent(Object.assign(new Event(`error`),{error:e})),this.target.dispatchEvent(new Event(`close`)))}},Wf=class{host;target;handle;channels=/* @__PURE__ */ new Map;waiting=[];local=null;remote=null;offer=null;answer=null;state=`new`;gathering=`new`;peerAddress=``;peerPort=0;sctp={maxMessageSize:Af,transport:{iceTransport:{getSelectedCandidatePair:()=>this.peerAddress?{remote:{address:this.peerAddress,port:this.peerPort}}:null}}};#e=[];#t=!1;#n=!1;#r=0;#i;#a=0;#o;#s=!1;#c=!1;constructor(e,t){if(this.host=e,this.target=t,e.closed)throw new DOMException(`the factory or its socket is closed`,`InvalidStateError`);this.handle=e.create(),e.connections.add(this)}run(e){if(e&&this.#e.push(e),!(this.#t||!this.handle)){this.#t=!0;try{let e=!1;for(;;){let t=this.#e.shift(),n=t??(e?void 0:this.#g());if(!n)break;if(e=n()===!1,this.#p(),!this.handle)return;if(t)for(let e of this.channels.values())e.stale||=e.inStack>0}this.#v(),this.#y()}catch(e){this.#c=e instanceof WebAssembly.RuntimeError;let t=this.#c?this.host.panic.text.trim():``;this.end(`failed`,e instanceof DOMException?e:Vf(t||String(e)))}finally{this.#t=!1}}}schedule(e){e&&this.#e.push(e),!this.#n&&(this.#n=!0,queueMicrotask(()=>{this.#n=!1,this.run()}))}#l(e){if(e<0)throw Vf(this.#d());return e}#u(e=this.handle){let{x:t}=this.host;return new Uint8Array(t.memory.buffer,t.rtc_out_ptr(e),t.rtc_out_len(e))}#d(){return Pf.decode(this.#u())}#f(e){let{x:t}=this.host,n=this.#u(e).slice(),r=t.rtc_port(e),i=Lf(t.rtc_arg(e));n[0]>3&&(this.peerAddress=i,this.peerPort=r),this.host.transmit(n,r,i)}#p(){let{x:e}=this.host;for(;;){let t=this.handle;if(!t)return;let n=this.#l(e.rtc_poll(t)),r=e.rtc_arg(t);if(n===xf){this.#r=r,this.#s&&this.end(`failed`);return}n===Sf?this.#f(t):n===Cf?this.#m(r,this.#d()):n===wf?this.#h(r,this.#u().slice().buffer):n===Tf?this.#h(r,this.#d()):n===Ef?(this.channels.get(r)?.closed(),this.channels.delete(r)):n===Df?this.#b(`connected`):n===Of?this.end(`failed`,Vf(`the peer stopped answering`)):n===kf&&(this.#s=!0)}}#m(e,t){let n=this.channels.get(e);if(!n)n=new Uf(this,t),n.index=e,this.channels.set(e,n),n.state=`open`,n.streaming=n.stale=!0,this.target.dispatchEvent(Object.assign(new Event(`datachannel`),{channel:n.target}));else{if(n.streaming=n.stale=!0,n.state!==`connecting`)return;n.state=`open`}n.state===`open`&&n.target.dispatchEvent(new Event(`open`))}#h(e,t){let n=this.channels.get(e);n&&n.target.dispatchEvent(new MessageEvent(`message`,{data:t}))}#g(){let{x:e,sendBufferSize:t}=this.host,n=t;for(let t of this.channels.values())t.streaming&&(t.stale&&(t.stale=!1,t.inStack=e.rtc_buffered(this.handle,t.index)),n-=t.inStack);for(let t of this.channels.values()){if(!t.streaming)continue;let r=t.queue[0];if(r&&r.bytes.length<=n)return()=>this.#_(t,r);if(!r&&t.state===`closing`&&!t.inStack)return()=>{t.streaming=!1,e.rtc_close_channel(this.handle,t.index)}}}#_(e,t){let{x:n}=this.host,{length:r}=t.bytes,i=this.host.put(t.bytes);if(!this.#l(n.rtc_write(this.handle,e.index,Number(t.binary),i,r)))return!1;e.queue.shift(),e.queuedBytes-=r,e.inStack+=r}#v(){for(let e of this.channels.values())!e.high||e.buffered>e.threshold||(e.high=!1,queueMicrotask(()=>e.target.dispatchEvent(new Event(`bufferedamountlow`))))}#y(){let e=performance.now()+this.#r;this.#i!==void 0&&e>=this.#a||(clearTimeout(this.#i),this.#a=e,this.#i=setTimeout(()=>{this.#i=void 0,this.run(()=>this.#l(this.host.x.rtc_timeout(this.handle)))},this.#r))}#b(e){this.state!==e&&(this.state=e,this.target.dispatchEvent(new Event(`connectionstatechange`)))}receive(e,t,n){this.run(()=>this.#l(this.host.x.rtc_receive(this.handle,e,t,this.host.put(n),n.length)))}#x(){if(!this.handle)throw new DOMException(`the connection is closed`,`InvalidStateError`)}#S(e){this.run(e),this.run(()=>this.#l(this.host.x.rtc_timeout(this.handle)))}#C(e){let t=Nf.encode(e.label);e.index=this.host.x.rtc_open(this.handle,this.host.put(t),t.length),this.channels.set(e.index,e)}createDataChannel(e,t={}){if(this.#x(),t.ordered===!1||t.maxPacketLifeTime!=null||t.maxRetransmits!=null||t.negotiated||t.id!=null||t.protocol)throw new DOMException(`only ordered, reliable channels opened in band, with no protocol`,`NotSupportedError`);let n=new Uf(this,e);return this.remote?this.schedule(()=>this.#C(n)):this.waiting.push(n),n.target}createOffer(){if(this.#x(),this.remote)throw new DOMException(`this connection already has a remote description`,`InvalidStateError`);if(!this.offer){let e=this.waiting.shift();if(!e)throw new DOMException(`an offer needs a data channel: there is no media to offer`,`InvalidStateError`);this.#S(()=>{this.#C(e),this.offer=this.#d()}),this.#x()}return{type:`offer`,sdp:this.offer}}createAnswer(){if(this.#x(),this.remote?.type!==`offer`||this.local)throw new DOMException(`there is no remote offer to answer`,`InvalidStateError`);return{type:`answer`,sdp:this.answer}}setLocalDescription(e){this.#x();let t=e?.type??(this.remote?`answer`:`offer`);if(t!==`offer`&&t!==`answer`)throw new DOMException(`${t} descriptions are not supported`,`NotSupportedError`);if(this.local)throw new DOMException(`this connection already has a local description`,`InvalidStateError`);let{sdp:n}=t===`offer`?this.createOffer():this.createAnswer();if(e?.sdp&&e.sdp!==n)throw new DOMException(`the description is not the one this connection created`,`InvalidModificationError`);this.local={type:t,sdp:n},this.remote&&this.#b(`connecting`),this.#o=setTimeout(()=>this.#w(n))}#w(e){let t=e=>this.handle&&this.target.dispatchEvent(e),n={candidate:/^a=(candidate:.*)$/m.exec(e)[1],sdpMid:/^a=mid:(.*)$/m.exec(e)[1],sdpMLineIndex:0};this.gathering=`gathering`,t(new Event(`icegatheringstatechange`)),t(Object.assign(new Event(`icecandidate`),{candidate:n})),this.handle&&(this.gathering=`complete`,t(new Event(`icegatheringstatechange`)),t(Object.assign(new Event(`icecandidate`),{candidate:null})))}setRemoteDescription(e){this.#x();let{type:t,sdp:n=``}=e;if(t!==`offer`&&t!==`answer`)throw t===`pranswer`||t===`rollback`?new DOMException(`${t} descriptions are not supported`,`NotSupportedError`):TypeError(`'${String(t)}' is not a description type`);if(this.remote||(t===`offer`?this.local:this.local?.type!==`offer`))throw new DOMException(`an ${t} cannot be set now`,`InvalidStateError`);let{x:r}=this.host,i=Nf.encode(this.host.allowPrivateCandidates?n:zf(n)),a=0,o=``;if(this.#S(()=>{let e=this.host.put(i);a=t===`offer`?r.rtc_accept_offer(this.handle,e,i.length):r.rtc_accept_answer(this.handle,e,i.length),o=this.#d()}),a===-1)throw Vf(`the description is not SDP: ${o}`);if(a<0){let e=new DOMException(`the description was refused: ${o}`,`InvalidAccessError`);throw this.end(`failed`,e),e}this.#x(),this.remote={type:t,sdp:n},t===`offer`&&(this.answer=o);let s=/^a=max-message-size:(\d+)/m.exec(n);this.sctp.maxMessageSize=Math.min(Af,(s?Number(s[1]):65536)||1/0),this.local&&this.#b(`connecting`);for(let e of this.waiting.splice(0))this.run(()=>this.#C(e))}end(e,t){let{handle:n,host:r}=this;if(!n){e===`closed`&&(this.state=e);return}this.handle=0,this.#e.length=0,clearTimeout(this.#i),clearTimeout(this.#o),r.forget(this);let i=()=>{for(let e;(e=r.x.rtc_poll(n))>xf;)e===Sf&&this.#f(n)};try{e===`closed`&&(i(),r.x.rtc_close(n),i())}catch{}this.#c||r.x.rtc_delete(n),this.peerAddress=``;let a=[...this.channels.values(),...this.waiting];this.channels.clear(),this.waiting.length=0;for(let e of a)e.state=`closing`;this.state=e,queueMicrotask(()=>{for(let e of a)e.closed(t);e===`failed`&&this.target.dispatchEvent(new Event(`connectionstatechange`))})}},Gf=class extends EventTarget{#e;constructor(e){super(),this.#e=e}get label(){return this.#e.label}get readyState(){return this.#e.state}get binaryType(){return`arraybuffer`}set binaryType(e){if(e!==`arraybuffer`)throw new DOMException(`binary messages arrive as ArrayBuffer only`,`NotSupportedError`)}get bufferedAmount(){return this.#e.buffered}get bufferedAmountLowThreshold(){return this.#e.threshold}set bufferedAmountLowThreshold(e){this.#e.threshold=e}send(e){this.#e.send(e)}close(){this.#e.close()}};Bf(Gf,`open`,`message`,`bufferedamountlow`,`error`,`close`);var Kf=class extends EventTarget{#e;constructor(e,t){super(),this.#e=new Wf(e,this)}get connectionState(){return this.#e.state}get iceGatheringState(){return this.#e.gathering}get localDescription(){return this.#e.local}get remoteDescription(){return this.#e.remote}get sctp(){let{local:e,remote:t,sctp:n}=this.#e;return e||t?n:null}createDataChannel(e,t){return this.#e.createDataChannel(String(e),t)}createOffer(){return Promise.resolve().then(()=>this.#e.createOffer())}createAnswer(){return Promise.resolve().then(()=>this.#e.createAnswer())}setLocalDescription(e){return Promise.resolve().then(()=>this.#e.setLocalDescription(e))}setRemoteDescription(e){return Promise.resolve().then(()=>this.#e.setRemoteDescription(e))}close(){this.#e.end(`closed`)}};Bf(Kf,`connectionstatechange`,`datachannel`,`icecandidate`,`icegatheringstatechange`);var qf=(e,t)=>({random_get(t,n){for(let r=0;r<n;r+=65536)crypto.getRandomValues(new Uint8Array(e(),t+r,Math.min(65536,n-r)));return 0},clock_time_get(t,n,r){let i=t===0?Date.now():performance.now();return new DataView(e()).setBigUint64(r,BigInt(Math.round(i*1e6)),!0),0},environ_sizes_get(t,n){let r=new DataView(e());return r.setUint32(t,0,!0),r.setUint32(n,0,!0),0},environ_get:()=>0,fd_write(n,r,i,a){let o=new DataView(e()),s=0;for(let n=0;n<i;n++){let i=o.getUint32(r+n*8+4,!0);t(new TextDecoder().decode(new Uint8Array(e(),o.getUint32(r+n*8,!0),i))),s+=i}return o.setUint32(a,s,!0),0},proc_exit(e){throw Error(`the WebRTC stack exited with code ${e}`)}});async function Jf(e){if(e instanceof WebAssembly.Module)return e;if(typeof e!=`string`&&!(e instanceof URL))return WebAssembly.compile(e);let t=await fetch(e);if(!t.ok)throw Error(`could not fetch the WebRTC module: ${t.status}`);return WebAssembly.compile(await t.arrayBuffer())}async function Yf(e){let{socket:t,address:n,port:r,allowPrivateCandidates:i=!1,sendBufferSize:a=Af}=e,o=If(n);if(o===void 0||!Number.isInteger(r)||r<1||r>65535)throw TypeError(`address and port are the IPv4 address and UDP port peers reach the socket at`);if(!Number.isInteger(a)||a<262144)throw RangeError(`sendBufferSize is at least ${Af}, the largest message`);let[s,{certificate:c,privateKey:l}]=await Promise.all([Jf(e.wasm??new URL(
|
|
26
26
|
/* @vite-ignore */
|
|
27
|
-
`./webrtc.wasm`,import.meta.url)),bf()]),u={text:``},d={wasi_snapshot_preview1:qf(()=>f.memory.buffer,e=>{u.text=(u.text+e).slice(-2048)})},f=(await WebAssembly.instantiate(s,d)).exports;f._initialize();let p=new Hf(f,t,o,r,i,a,c,l,u),m=p.create();if(!m)throw p.close(),TypeError(`${n}:${r} cannot be a host candidate`);return f.rtc_delete(m),{RTCPeerConnection:Kf.bind(null,p),get droppedDatagrams(){return p.dropped},close:()=>p.close()}}var Xf=262144,Zf=16384,Qf=5e3,$f=class{sink;backpressure=!0;listeners=/* @__PURE__ */ new Map;held=[];heldBytes=0;ended=!1;heard=!1;openedAt=Date.now();destroyedAfter=null;constructor(e){this.sink=e}on(e,t){let n=this.listeners.get(e);if(n?n.push(t):this.listeners.set(e,[t]),e===`data`&&this.held){let e=this.held;this.held=null;for(let n of e)t(n)}if(this.ended&&(e===`end`||e===`close`)&&queueMicrotask(t),this.ended instanceof Error&&e===`error`){let e=this.ended;queueMicrotask(()=>t(e))}return this}listenerCount(e){return this.listeners.get(e)?.length??0}get silent(){return this.ended===!1||this.heard?!1:this.destroyedAfter===null||this.listenerCount(`data`)>0&&this.destroyedAfter>=Qf}write(e){return this.ended?!0:this.sink.write(e)}destroy(){this.ended||(this.ended=!0,this.destroyedAfter=Date.now()-this.openedAt,this.held=null,this.sink.close())}push(e){if(!this.ended){if(this.heard=!0,!this.held)return this.emit(`data`,e);if(this.heldBytes+=e.length,this.heldBytes>1048576){this.end(/* @__PURE__ */ Error(`${this.heldBytes} bytes arrived before anything read the stream`)),this.sink.close();return}this.held.push(e)}}drained(){this.ended||this.emit(`drain`)}end(e){this.ended||(this.ended=e??!0,e&&this.emit(`error`,e),this.emit(`end`),this.emit(`close`))}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}},ep=3e3,tp=class extends Error{},np=({reflexive:e,complete:t})=>new Promise(n=>{let r,i=!1,a=()=>{i=!0,clearTimeout(o),clearTimeout(r),n()},o=setTimeout(a,ep);t.then(a),e.then(()=>{i||(r??=setTimeout(a,300))})}),rp=({RTCPeerConnection:e,iceServers:t=[]})=>{let n=/* @__PURE__ */ new WeakMap,r=async(r,i)=>{let a;try{a=new e({iceServers:t})}catch(e){throw new tp(`no connection could be made`,{cause:e})}let o=null,s=null,c=!1,l=[],u=0,d=!1,f=Zf,p=0,m=0,h=()=>{if(p)return;let e=()=>{try{a.close()}catch{}};Date.now()-m>5?e():setTimeout(e,5)},g=async e=>{p++;try{return await e}finally{p--,m=Date.now(),c&&h()}},_=()=>{if(c=!0,l=[],a.onicecandidate=a.onicegatheringstatechange=a.onconnectionstatechange=a.ondatachannel=null,o){o.onopen=o.onmessage=o.onclose=o.onerror=o.onbufferedamountlow=null;try{o.close()}catch{}}h()},v=e=>{c||(_(),s?.end(e),S.onclose?.())},y=()=>{try{for(;l.length&&o.bufferedAmount<1048576;){let e=l[0],t=e.subarray(u,u+f);o.send(t),u+=t.length,u>=e.length&&(l.shift(),u=0)}}catch(e){v(Error(`the data channel refused a message`,{cause:e}))}},b=()=>{if(s||c)return;let e=a.sctp?.maxMessageSize??0;e>0&&e<16384&&(f=e),s=new $f({write:e=>(l.push(e),y(),!l.length||(d=!0,!1)),close:()=>v()}),S.onopen?.(s)},x=e=>{o=e,e.binaryType=`arraybuffer`,e.bufferedAmountLowThreshold=Xf,e.onopen=b,e.onmessage=({data:e})=>{b(),e instanceof ArrayBuffer?s?.push(new Uint8Array(e)):ArrayBuffer.isView(e)?s?.push(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):v(/* @__PURE__ */ Error(`a message that is not bytes`))},e.onclose=()=>v(),e.onerror=()=>v(/* @__PURE__ */ Error(`the data channel failed`)),e.onbufferedamountlow=()=>{y(),d&&!l.length&&(d=!1,s?.drained())},e.readyState===`open`&&b()},S={onopen:null,onclose:null,accept:async e=>{if(c)throw Error(`the link is closed`);try{await g(a.setRemoteDescription({type:`answer`,sdp:e}))}catch(e){throw v(),e}},close:()=>{c||(_(),s?.end())}};n.set(S,a);let C,w,T={reflexive:new Promise(e=>{C=e}),complete:new Promise(e=>{w=e})};a.onicecandidate=({candidate:e})=>{e?.candidate?/ typ srflx\b/.test(e.candidate)&&C():w()},a.onicegatheringstatechange=()=>{a.iceGatheringState===`complete`&&w()},a.onconnectionstatechange=()=>{a.connectionState===`failed`&&v()};try{await i(a,x,g),a.iceGatheringState===`complete`&&w(),await r(T);let e=a.localDescription?.sdp;if(c||!e)throw Error(`the connection closed before it had a description`);return{sdp:e,link:S}}catch(e){throw S.close(),e}};return{offer:(e=np)=>r(e,async(e,t,n)=>{t(e.createDataChannel(`webtorrent`)),await n(e.setLocalDescription(await n(e.createOffer())))}),answer:(e,t=np)=>r(t,async(t,n,r)=>{t.ondatachannel=({channel:e})=>n(e),await r(t.setRemoteDescription({type:`offer`,sdp:e})),await r(t.setLocalDescription(await r(t.createAnswer())))}),remoteAddress:e=>n.get(e)?.sctp?.transport.iceTransport.getSelectedCandidatePair()?.remote.address||void 0}},ip=e=>new Uint8Array(e).buffer,ap=e=>{let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=0,i=(t,n=[])=>e.postMessage(t,n),a=e=>new Promise((n,a)=>{let o=r++,s,c,l={reflexive:new Promise(e=>{s=e}),complete:new Promise(e=>{c=e})};t.set(o,{resolve:n,reject:a,reflexive:s,complete:c}),i(e(o)),np(l).then(()=>{t.has(o)&&i({t:`flush`,id:o})})}),o=(e,t)=>{let r=n.get(e);r&&(n.delete(e),r.stream?.end(),t&&r.link.onclose?.())},s=e=>{let t={onopen:null,onclose:null,accept:async t=>i({t:`accept`,id:e,sdp:t}),close:()=>{i({t:`close`,id:e}),o(e,!1)}};return n.set(e,{link:t,unsent:0,waiting:!1}),t};return e.onmessage=({data:e})=>{let{id:r}=e,a=t.get(r);if(e.t===`candidate`)return e.last?a?.complete():a?.reflexive();if(e.t===`sdp`||e.t===`failed`){t.delete(r),a?.complete(),e.t===`sdp`?a?.resolve({sdp:e.sdp,link:s(r)}):a?.reject(e.full?new tp(e.reason):Error(e.reason));return}let c=n.get(r);c&&(e.t===`open`?(c.stream=new $f({write:e=>{for(let t=0;t<e.length;t+=Zf){let n=ip(e.subarray(t,t+Zf));i({t:`data`,id:r,bytes:n},[n])}return c.unsent+=e.length,c.unsent<1048576||(c.waiting=!0,!1)},close:()=>{i({t:`close`,id:r}),o(r,!0)}}),c.link.onopen?.(c.stream)):e.t===`data`?(i({t:`ack`,id:r,bytes:e.bytes.byteLength}),c.stream?.push(new Uint8Array(e.bytes))):e.t===`ack`?(c.unsent-=e.bytes,c.waiting&&c.unsent<=262144&&(c.waiting=!1,c.stream?.drained())):e.t===`closed`&&o(r,!0))},{offer:()=>a(e=>({t:`offer`,id:e})),answer:e=>a(t=>({t:`answer`,id:t,sdp:e})),remoteAddress:()=>void 0}},op=1e4,sp=6e5,cp=131072,lp=65536,up=64,dp=200,fp=`-RP0001-`,pp=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`,mp=e=>{let t=``;for(let n of crypto.getRandomValues(new Uint8Array(e)))t+=pp[n%62];return t},hp=()=>mp(20),gp=()=>fp+mp(12),_p=e=>{let t=``;for(let n=0;n<40;n+=2)t+=String.fromCharCode(parseInt(e.slice(n,n+2),16));return t},vp=e=>e===void 0||typeof e==`number`&&Number.isFinite(e)&&e>=0,yp=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,bp=class{url;WebSocket;dropped=0;onopen=null;onclose=null;onreply=null;onfailure=null;onoffer=null;onanswer=null;socket=null;listed=/* @__PURE__ */ new Map;retry;losses=0;constructor(e,t){this.url=e,this.WebSocket=t,this.connect()}get connected(){return this.socket?.readyState===1}announce({infoHash:e,peerId:t,uploaded:n,downloaded:r,left:i,event:a,offers:o}){let s=this.send({action:`announce`,info_hash:e,peer_id:t,uploaded:yp(n),downloaded:yp(r),left:yp(i),numwant:o.length,event:a,offers:o.map(({offerId:e,sdp:t})=>({offer_id:e,offer:{type:`offer`,sdp:t}}))});return s&&this.listed.set(e,a!==`stopped`),s}answer({infoHash:e,peerId:t,toPeerId:n,offerId:r,sdp:i}){return this.send({action:`announce`,info_hash:e,peer_id:t,to_peer_id:n,offer_id:r,answer:{type:`answer`,sdp:i}})}close(){clearTimeout(this.retry);let e=this.socket;this.socket=null,e&&(e.onopen=e.onmessage=e.onclose=null,e.close())}send(e){return this.connected?(this.socket.send(JSON.stringify(e)),!0):!1}connect(){let e;try{e=new this.WebSocket(this.url)}catch{return}this.socket=e,e.onopen=()=>this.onopen?.(),e.onmessage=({data:e})=>this.read(e),e.onclose=()=>{this.socket=null,this.listed.clear();let e=Math.min(op*2**this.losses++,sp);this.retry=setTimeout(()=>this.connect(),e*(1+Math.random()/4)),this.onclose?.()}}read(e){this.accept(e)||this.dropped++}accept(e){if(typeof e!=`string`||e.length>cp)return!1;let t;try{t=JSON.parse(e)}catch{return!1}if(typeof t!=`object`||!t)return!1;let n=t.info_hash,r=t[`failure reason`];if(r!==void 0)return typeof r!=`string`||n!==void 0&&!this.listed.get(n)?!1:(this.onfailure?.(n??null,r.slice(0,dp)),!0);if(t.action!==`announce`)return!1;let i=this.listed.get(n);if(!i)return i===!1&&this.listed.delete(n);this.losses=0;let{offer:a,answer:o}=t;if(a===void 0&&o===void 0){let{interval:e,complete:r,incomplete:i}=t;return!vp(e)||!vp(r)||!vp(i)?!1:(this.onreply?.({infoHash:n,intervalS:e===void 0?null:Math.min(600,Math.max(60,e)),seeders:r??null,leechers:i??null}),!0)}let s=a??o,{peer_id:c,offer_id:l}=t;if(a!==void 0&&o!==void 0||typeof s!=`object`||!s||typeof s.sdp!=`string`||s.sdp.length>lp||typeof c!=`string`||c.length!==20||typeof l!=`string`||l.length<1||l.length>up)return!1;let u={infoHash:n,peerId:c,offerId:l,sdp:s.sdp};return a?this.onoffer?.(u):this.onanswer?.(u),!0}},xp=[[0,8],[167772160,8],[1681915904,10],[2130706432,8],[2851995648,16],[2886729728,12],[3232235520,16]],Sp=e=>xp.some(([t,n])=>e>>>32-n==t>>>32-n),Cp=e=>{if(e.startsWith(`[`)){let t=e.slice(1,-1),n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);return n?Sp((parseInt(n[1],16)<<16|parseInt(n[2],16))>>>0):t===`::`||t===`::1`||/^fe[89ab][0-9a-f]:/.test(t)||/^f[cd][0-9a-f]{2}:/.test(t)}let t=/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(e);if(t)return Sp((t[1]<<24|t[2]<<16|t[3]<<8|t[4])>>>0);let n=e.replace(/\.$/,``);return!n.includes(`.`)||n.endsWith(`.localhost`)||n.endsWith(`.local`)},wp=e=>{let t;try{t=new URL(e)}catch{return null}return t.protocol!==`ws:`&&t.protocol!==`wss:`||Cp(t.hostname)?null:t.href},Tp=[1,7],Ep=2,Dp=(e,t)=>{let n=e.status(t),r=e.infohash(t);return!n||!r?null:{infoHash:r,trackers:e.webSocketTrackers(t),running:!n.paused&&n.errorCode===0,checking:Tp.includes(n.state),uploadMode:(n.flags&Ep)!==0,hasMetadata:n.hasMetadata,private:e.isPrivate(t),uploaded:n.sessionPayloadUpload,downloaded:n.sessionPayloadDownload,left:n.totalWanted-n.totalWantedDone,watched:e.hasStreamWindow(t)}},Op={torrentPeers:20,sessionPeers:60,connections:80,perMinute:40},kp={watched:0,downloading:10,seeding:20},Ap=10,jp=16384,Mp=1e4,Np=5e4,Pp=3e4,Fp=1e4,Ip=6e4,Lp=65e3,Rp=6e5,zp=200,Bp=1e4,Vp=1e3,Hp=12e4,Up=1e3,Wp=e=>(e.answeredAt??0)<e.sentAt,Gp=e=>e.hasMetadata&&e.left<=0,Kp=e=>e.watched?`watched`:Gp(e)?`seeding`:`downloading`,qp=(e,t,n)=>{let r=e.trackers.map(wp).filter(e=>e!==null);return[...new Set(e.private??n?r:[...r,...t])]},Jp=(e,t)=>e<t,Yp=e=>e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``),Xp=(e,t)=>{for(let n of e.keys()){if(e.size<=t)return;e.delete(n)}},Zp=(e,t)=>{let{links:n,WebSocket:r,relay:i=!1}=t,a={...Op,...t.limits},o=(t.trackers??[]).map(e=>new URL(e).href),s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Map,d=0,f=a.perMinute,p=Date.now(),m=!1,h=0,g=0,_=!1,v=!1,y=()=>{_||v||(_=!0,queueMicrotask(()=>{_=!1,se.onchange?.()}))},b=e=>{let t=0;for(let n of e.conns)n.remote&&t++;return t},x=()=>{let e=0;for(let t of c.values())e+=b(t);return e},S=e=>{if(m||e.view.checking)return 0;let t=Date.now();f=Math.min(a.perMinute,f+(t-p)*a.perMinute/6e4),p=t;let n=kp[Kp(e.view)];return Math.max(0,Math.floor(Math.min(a.torrentPeers-b(e),a.sessionPeers-x()-n,a.connections-d-n,f-n)))},C=(e,t,n,r,i)=>{let a={torrent:e,via:t,ours:n,remote:r,offerId:i,state:`making`,deadline:Date.now()+Mp};return e.conns.add(a),d++,f--,y(),a},w=(e,t,n)=>{let r=n.socket?.silent??!1;e.quiet.set(t,{until:Date.now()+(r?Rp:Ip),silent:r,address:r?n.address:void 0}),Xp(e.quiet,zp),n.state===`open`&&!r&&(e.askAt=Date.now()+Lp)},T=e=>{let t=e.torrent;return t.conns.delete(e)?(d--,t.offers.delete(e.offerId),e.remote&&w(t,e.remote,e),y(),!0):!1},E=e=>{T(e)&&e.link?.close()},D=(e,t)=>{t instanceof tp&&(m=!0,h++),T(e)},O=(e,t)=>e.torrent.conns.has(e)?(e.link=t,t.onopen=t=>void k(e,t),t.onclose=()=>T(e),!0):(t.close(),!1),ee=async t=>{t.lookAt=Date.now()+Bp;for(let{endpoint:n}of await e.peers?.(t.handle).catch(()=>[])??[]){let e=Yp(n);t.ordinary.delete(e),t.ordinary.add(e)}Xp(t.ordinary,Vp)},k=async(t,r)=>{let a=t.torrent;t.socket=r;let o=t.address=i?n.remoteAddress(t.link):void 0;if(o){if(await ee(a),!a.conns.has(t))return;if(a.ordinary.has(o))return E(t);for(let e of a.quiet.values())if(e.address===o)return E(t)}if(!t.remote||!Dp(e,a.handle)?.running)return E(t);try{e.addPeerStream(a.handle,r)}catch{return E(t)}a.conns.has(t)&&(t.state=`open`,t.deadline=Date.now()+Fp,a.lastPeerAt=Date.now(),y())},te=e=>({infoHash:e.hash,peerId:e.peerId,uploaded:e.view.uploaded,downloaded:e.view.downloaded,left:e.view.hasMetadata?e.view.left:jp}),A=async(e,t)=>{let r=C(e,t,!0,null,hp());try{let e=await n.offer();return O(r,e.link)?{conn:r,sdp:e.sdp}:null}catch(e){return D(r,e),null}},ne=async(e,t,n=0)=>{if(Gp(e.view)||!t.tracker.connected)return;let r=(t.seeders??0)+(t.leechers??0)-1,i=Math.min(Ap,S(e),r-e.conns.size+n);if(i<1)return;t.offersDue=!1;let a=(await Promise.all(Array.from({length:i},()=>A(e,t.tracker.url)))).filter(e=>e!==null).filter(({conn:t})=>e.conns.has(t));if(!a.length)return;let o=t.tracker.announce({...te(e),offers:a.map(({conn:e,sdp:t})=>({offerId:e.offerId,sdp:t}))});for(let{conn:t}of a){if(!o){E(t);continue}t.state=`offered`,t.deadline=Date.now()+Np,e.offers.set(t.offerId,t)}},j=async(e,{infoHash:t,peerId:r,offerId:i,sdp:a})=>{let o=l.get(t);if(!o||r===o.peerId||o.quiet.has(r))return;let s=[...o.conns].filter(e=>e.remote===r);if(s.length){if(s.some(e=>e.state===`open`||!e.ours)||Jp(o.peerId,r))return;s.forEach(E)}if(S(o)<1)return;let c=C(o,e.url,!1,r,i);try{let s=await n.answer(a);if(!O(c,s.link))return;if(!e.answer({infoHash:t,peerId:o.peerId,toPeerId:r,offerId:i,sdp:s.sdp}))return E(c);c.state=`answered`,c.deadline=Date.now()+Pp}catch(e){D(c,e)}},M=({infoHash:e,peerId:t,offerId:n,sdp:r})=>{let i=l.get(e),o=i?.offers.get(n);if(!i||!o||o.state!==`offered`||t===i.peerId)return;if(i.quiet.get(t)?.silent)return E(o);let s=[...i.conns].filter(e=>e.remote===t);if(s.some(e=>e.state===`open`||e.ours)||s.length&&!Jp(i.peerId,t)||(s.forEach(E),b(i)>=a.torrentPeers||x()+kp[Kp(i.view)]>=a.sessionPeers))return E(o);o.remote=t,o.state=`answered`,o.deadline=Date.now()+Pp,y(),o.link.accept(r).catch(()=>{})},N=e=>{let t=s.get(e);if(t)return t;let n=new bp(e,r);return s.set(e,n),n.onopen=()=>{for(let t of c.values()){let n=t.announcing.get(e);n&&(n.started=!1,n.nextAt=0)}P(),y()},n.onclose=y,n.onreply=({infoHash:t,intervalS:n,seeders:r,leechers:i})=>{let a=l.get(t),o=a?.announcing.get(e);a&&o&&(n!==null&&(o.intervalMs=n*1e3,o.nextAt=o.sentAt+o.intervalMs),o.seeders=r,o.leechers=i,o.answeredAt=Date.now(),o.failure=null,y(),o.offersDue&&ne(a,o))},n.onfailure=(t,n)=>{for(let r of c.values()){let i=r.announcing.get(e);!i||(t===null?!Wp(i):t!==r.hash)||(i.failure=n,i.answeredAt=Date.now(),y())}},n.onoffer=e=>void j(n,e),n.onanswer=M,n},P=()=>{let e=Date.now();for(let t of c.values())for(let n of t.announcing.values())e<n.nextAt||!n.tracker.connected||(n.tracker.announce({...te(t),event:n.started?void 0:`started`,offers:[]}),m=!1,n.started=!0,n.offersDue=!0,n.sentAt=e,n.nextAt=e+n.intervalMs)},F=(e,t,n)=>{t.tracker.announce({...te(e),event:n,offers:[]})},re=(e,t)=>{for(let[n,r]of e.announcing)if(!t.includes(n)){F(e,r,`stopped`),e.announcing.delete(n);for(let t of e.conns)t.via===n&&t.state!==`open`&&E(t);y()}},I=e=>{for(let t of e.announcing.values())F(e,t,`stopped`);for(let t of e.conns)E(t);c.delete(e.handle),l.delete(e.hash),y()},L=t=>{let n=Dp(e,t),r=c.get(t);if(n||u.delete(t),!n?.running){r&&I(r);return}let a=qp(n,o,i);if(n.checking){r&&(r.view.checking=!0,re(r,a));return}if(r?.view.uploadMode&&!n.uploadMode&&n.hasMetadata&&!Gp(n)&&(I(r),r=void 0),!r){let e=u.get(t)??{quiet:/* @__PURE__ */ new Map,ordinary:/* @__PURE__ */ new Set};u.set(t,e);for(let[t,{silent:n}]of e.quiet)n||e.quiet.delete(t);r={...e,peerId:gp(),handle:t,view:n,hash:_p(n.infoHash),announcing:/* @__PURE__ */ new Map,conns:/* @__PURE__ */ new Set,offers:/* @__PURE__ */ new Map,leeching:!1,completed:!1,lastPeerAt:null,lookAt:0,askAt:0},c.set(t,r),l.set(r.hash,r),y()}for(let e of a)r.announcing.has(e)||(r.announcing.set(e,{tracker:N(e),started:!1,offersDue:!1,sentAt:0,nextAt:0,intervalMs:Hp,seeders:null,leechers:null,answeredAt:null,failure:null}),y());if(re(r,a),r.view=n,n.hasMetadata&&n.left>0&&(r.leeching=!0),r.leeching&&!r.completed&&Gp(n)){r.completed=!0;for(let e of r.announcing.values())F(r,e,`completed`)}},ie=()=>{for(let[e,t]of s){let n=!1;for(let t of c.values())n||=t.announcing.has(e);n||(g+=t.dropped,t.close(),s.delete(e))}},ae=()=>{for(let t of/* @__PURE__ */ new Set([...e.torrents(),...c.keys()]))L(t)},oe=()=>{let e=Date.now();ae();for(let t of c.values()){for(let n of t.conns)e<n.deadline||(n.state===`open`&&n.socket.listenerCount(`data`)?n.deadline=1/0:E(n));for(let[n,{until:r,silent:i}]of t.quiet)e<r||(t.quiet.delete(n),i&&y());if(t.askAt&&e>=t.askAt){t.askAt=0;let e=0;for(let n of t.conns)n.state===`offered`&&e++;for(let n of t.announcing.values())ne(t,n,e)}i&&e>=t.lookAt&&ee(t)}ie(),P()},se={onchange:null,close:()=>{if(!v){v=!0,clearInterval(ce);for(let e of c.values())I(e);ie()}},refresh:()=>{v||(ae(),ie(),P())},snapshot:()=>({dropped:[...s.values()].reduce((e,t)=>e+t.dropped,g),unmade:h,torrents:[...c.values()].map(e=>{let t=0;for(let n of e.conns)n.state===`open`&&t++;let n=0;for(let t of e.quiet.values())t.silent&&n++;return{handle:e.handle,trackers:[...e.announcing].map(([e,{tracker:t,seeders:n,leechers:r,answeredAt:i,failure:a}])=>({url:e,connected:t.connected,seeders:n,leechers:r,answeredAt:i,failure:a})),pending:e.conns.size-t,open:t,lastPeerAt:e.lastPeerAt,silent:n}})})},ce=setInterval(oe,Up);return oe(),se},Qp=`/assets/webrtc-DCtPDVeu.wasm`;const $p=(e,t)=>(e?.snapshot().torrents.find(e=>e.handle===t)?.trackers??[]).map(e=>({url:e.url,message:e.failure??``,tier:0,fails:e.failure?1:e.answeredAt===null?-1:0,updating:!1,verified:e.answeredAt!==null,nextAnnounceIn:-1,seeders:e.seeders??-1,leechers:e.leechers??-1,downloaded:-1})),em=(e,t)=>{let{port1:n,port2:r}=new MessageChannel;t({type:`peer-links`,port:r},[r]);let i=Zp(e,{links:ap(n),WebSocket,trackers:Wl});return{refresh:()=>i.refresh(),trackers:e=>$p(i,e),close:()=>i.close()}},tm=(e,{net:t,dgram:n})=>{let r=null,i,a=!1,o=()=>new Promise((e,t)=>{let r=n.createSocket(`udp4`);r.once(`listening`,()=>e(r)),r.on(`error`,t),r.bind(0)}),s=e=>new Promise((n,r)=>{let{hostname:i,port:a,protocol:o}=new URL(e),s=t.connect({host:i,port:Number(a)||(o===`wss:`?443:80)}),c=e=>{clearTimeout(l),s.destroy(),e&&tu(e)?n(e):r(/* @__PURE__ */ Error(`the relay did not say its address`))},l=setTimeout(c,1e4);s.once(`connect`,()=>c(s.localAddress)),s.on(`error`,()=>c()),s.once(`close`,()=>c())}),c=async()=>{for(let e of Wl){let t=await s(e).catch(()=>null);if(t)return t}throw Error(`the relay did not say its address`)};return(async()=>{let t=500;for(;!a;){i??=await fetch(Qp).then(e=>e.arrayBuffer()).then(e=>WebAssembly.compile(e)).catch(()=>void 0);let n=i&&await o().catch(()=>null);if(n){let o=!0,s=new Promise(e=>{let t=()=>{o=!1,e()};n.once(`close`,t),n.once(`error`,t)});try{let l=await c();if(o&&!a){let a=await Yf({socket:n,address:l,port:n.address().port,wasm:i,allowPrivateCandidates:!1});r=Zp(e,{links:rp({RTCPeerConnection:a.RTCPeerConnection}),WebSocket:ff,trackers:Wl,relay:!0}),t=500,await s,r?.close(),r=null,a.close()}}catch{}try{n.close()}catch{}}await new Promise(e=>setTimeout(e,t)),t=Math.min(t*2,i&&!n?2e3:3e4)}})(),{refresh:()=>r?.refresh(),trackers:e=>$p(r,e),close:()=>{a=!0,r?.close(),r=null}}};var nm=ku(),rm=class extends Jd.EventEmitter{_type;_localAddress;_remoteAddress;_connectedLocally;_connectGeneration=0;_destroyed=!1;_busyRelease;_webVPNUdpSocketPromise;_dataPort;_socketId;_sendQueue=[];_sendQueueBytes=0;_sendFlushScheduled=!1;_peerTailCache=/* @__PURE__ */ new Map;_relayChoice;_relay;constructor(e){if(super(e),!e)throw Error(`Missing options`);this._type=e.type,this._relayChoice=e.relay,e.connection&&this.__webvpn_udp_socket_init__(e.connection)}_lastRecvBufferSize=0;_lastSendBufferSize=0;_lastTtl=64;_lastMulticastTtl=1;_lastMulticastLoopback=!0;_setUdpOption(e){this._webVPNUdpSocketPromise?this._webVPNUdpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}}):this.emit(`error`,/* @__PURE__ */ Error(`Cannot set socket option before bind`))}_dataPortAcks=!1;_dataPortConsumedBytes=0;_dataPortAckedBytes=0;_ackDataPortBatch(e){if(!this._dataPortAcks||!this._dataPort||(this._dataPortConsumedBytes+=e,this._dataPortAckedBytes!==0&&this._dataPortConsumedBytes-this._dataPortAckedBytes<524288))return;this._dataPortAckedBytes=this._dataPortConsumedBytes;let t={type:hu,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=sm(n)),s+=n.byteLength,d=t.getUint16(s),s+=2}let f=t.getUint32(s);s+=4;try{this.emit(`message`,nm.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 im;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let i=$l.Address4.isValid(e)?om(e):cm(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($l.Address4.isValid(e)){let n=om(e),r=t&&$l.Address4.isValid(t)?om(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if($l.Address6.isValid(e)){let t=cm(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=au(...e),n=this._type===`udp6`?`::`:`0.0.0.0`,r=this._relayChoice,i=this.__webvpn_udp_socket_init__(Eo(`a udp socket`).then(e=>(r!==void 0&&mu(e,`dgram.createSocket`),e.cloud.webvpn.udpSocket({type:this._type,address:t.address??n,port:t.port,dataPort:!0,relay:r}))));return t.callback&&i.then(e=>{e&&t.callback.call(this)}),this}__webvpn_udp_socket_init__(e,t){return t&&(this._localAddress={address:t.localAddress,family:t.localFamily,port:t.localPort}),this._busyRelease??=cu(`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`,nm.Buffer.from(e.data),{address:e.address,family:e.family,port:e.port,size:e.size})}})().catch(e=>this._onTransportClosed(e instanceof Error?e.message:void 0))}return e.closed?.then(e=>this._onTransportClosed(e?.reason)).catch(()=>{}),this._relay=e.relay,this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e}).catch(e=>{this.emit(`error`,Cu(e))}),this._webVPNUdpSocketPromise.then(e=>{e?this.emit(`listening`):this._busyRelease?.()}),this._webVPNUdpSocketPromise}close(e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);return this._webVPNUdpSocketPromise.then(async t=>{let n=this._destroyed;this._destroyed=!0,this._busyRelease?.(),this._dataPort?.close(),this._dataPort=void 0;try{await t?.close()}finally{try{n||this.emit(`close`)}finally{e&&e()}}}).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`,Cu(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($l.Address4.isValid(e)){let n=om(e),r=t&&$l.Address4.isValid(t)?om(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if($l.Address6.isValid(e)){let t=cm(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=ou(...e),n=am(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||$l.Address4.isValid(a)||$l.Address6.isValid(a))){this._portSend(r,o?void 0:a,o?void 0:t.port),n?.call(this,null,r.byteLength);return}let s=this._destroyed;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=>{if(this._destroyed&&!s)return;let t=Cu(e);n?n.call(this,t,0):this.emit(`error`,t)})})}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)})}},im=new Uint8Array([2]),am=e=>{if(typeof e==`string`)return eu.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(am),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)},om=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)},sm=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(`:`)}`},cm=e=>{let t=new $l.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)))},lm=(e,t)=>{let n=new rm(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},um={Socket:rm,createSocket:lm},dm=/* @__PURE__ */ n({Socket:()=>rm,createSocket:()=>lm,default:()=>um});const fm=({net:e,dgram:t}={net:tf,dgram:dm})=>{let n=/* @__PURE__ */ new Map,r=null,i=(e,t)=>{n.set(e,t),e.then(()=>n.delete(e))},a=(e,t)=>{let n=e[t];return e[t]=(...t)=>{let r=!1;return e.on(`listening`,()=>{r=!0}),i(new Promise(t=>{e.on(`close`,t),e.on(`error`,()=>{r||t()})}),()=>{r?e.close():e.on(`listening`,()=>e.close())}),n.apply(e,t)},e},o=e=>(i(new Promise(t=>e.on(`close`,t)),()=>e.destroy()),e);return{net:{connect:(...t)=>r?r.net.connect():o(e.connect(...t)),createServer:()=>{if(r)return r.net.createServer();let t=a(e.createServer(),`listen`);return t.on(`connection`,o),t}},dgram:{createSocket:(...e)=>r?r.dgram.createSocket():a(t.createSocket(...e),`bind`)},close:()=>{r??=ps();for(let e of n.values())try{e()}catch{}return Promise.race([Promise.all(n.keys()),new Promise(e=>setTimeout(e,1e3))])}}},pm=/* @__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.force-start.recheck.import-list.clear-list.start.start-many.retry.retry-now.flush-resume.inspect.torrent-detail.set-flags.reannounce.add-trackers.queue-move.set-limits.set-session-limits.set-seeding-policy.set-temporary.export-start.export-chunk.export-end.import-start.import.close-sockets`.split(`.`)),mm=e=>`ripple:source:`+e,hm=e=>`ripple:trackers:`+e,gm=self.name===`direct`?`direct`:`relay`,_m=gm===`relay`?fm():null;let W=null,vm=null,ym=null,bm={room:1/0,grownAt:0},xm=0;const Sm=(e,t)=>{let n=xm-bm.grownAt+t>bm.room&&G.some(t=>!Q.has(t)&&W?.files(t)?.storageIndex===e);return n||(xm+=t),!n},Cm=Js(Is,Sm);let wm=null;const Tm=/* @__PURE__ */ new Map;let Em=!1;const G=[],Dm=/* @__PURE__ */ new Map,K=/* @__PURE__ */ new Map,q=/* @__PURE__ */ new Map,Om=/* @__PURE__ */ new Map,km=/* @__PURE__ */ new Map,Am=e=>{let t=km.get(e);return t||(t={},km.set(e,t)),t},jm=e=>km.get(e)?.stop,Mm=e=>jm(e)===`user`,Nm=e=>jm(e)===`cache-idle`,Pm=e=>jm(e)===`seed-policy`,Fm=e=>jm(e)!==void 0,Im=e=>km.get(e)?.forced===!0,Lm=e=>km.get(e)?.userStarted===!0,Rm=e=>km.get(e)?.watchedPastQueue===!0,zm=e=>km.get(e)?.seedBypass===!0,Bm=(e,t)=>{Am(e).stop=t},Vm=(e,t)=>{let n=km.get(e);return!n?.stop||t&&n.stop!==t?!1:(delete n.stop,!0)},J=(e,t,n)=>{if(n){let n=Am(e);return!n[t]&&(n[t]=!0,!0)}let r=km.get(e);return r?.[t]?(delete r[t],!0):!1},Hm=()=>{for(let e of km.values())delete e.seedBypass},Um=()=>{for(let e of km.values())if(e.stop===`seed-policy`)return!0;return!1},Wm=/* @__PURE__ */ new Set,Gm=/* @__PURE__ */ new Set,Km=e=>{Gm.delete(e),Wm.add(e)},qm=e=>{Wm.delete(e),Gm.add(e)},Jm=/* @__PURE__ */ new Map,Ym=/* @__PURE__ */ new Map,Y=ec(gm===`relay`),Xm=e=>e>=4294967040,Zm=(e,t,n)=>hs(t)?e.addMagnet(t,n):-2>>>0,X=(e,t)=>self.postMessage(e,t??[]),Qm=()=>G.map(e=>{let t=W.bitfield(e);return{handle:e,magnet:Dm.get(e)??``,files:W.files(e),status:W.status(e),bitfield:t?{numPieces:t.numPieces,pieceLength:t.pieceLength,length:t.length,pieces:t.pieces}:null,recovery:Y.state(e),userPaused:Mm(e),windowed:mg.has(e),ephemeral:Q.has(e),...Ym.has(e)?{noPeersSince:Ym.get(e)}:{},swarmDownloads:Math.max(-1,...W?.lastTrackers(e).map(e=>e.downloaded)??[]),uptime:$m(e),sessionUptime:eh(e),totals:Kh(e)}}),$m=e=>{let t=W?.status(e),n=Bh.get(e);return!t||!n?Vh.get(e)??ac:uc(Vh.get(e),n,t)},eh=e=>{let t=W?.status(e),n=Bh.get(e);return t&&n?lc(n,t):ac},th=async()=>await Po(`ripple:torrents`)??[],nh=async(e,t)=>{let n=[];await Io(Jc,r=>{n=r??[];let i=n.findIndex(t=>t.infoHash===e.infoHash),a={...Kc(i>=0?n[i]:null,e),...t};return i>=0?n[i]=a:n.push(a),n}),X({type:`list`,list:n})},rh=async(e,t=!1)=>{let n=[];await Io(Jc,t=>(n=t??[],n.forEach((t,r)=>{let i=e.get(t.infoHash);i&&(n[r]={...t,...i})}),n)),t||X({type:`list`,list:n})},Z=(e,t,n=!1)=>rh(/* @__PURE__ */ new Map([[e,t]]),n),ih=e=>{let t=K.get(e);t&&Z(t,{lastUsedAt:Date.now()},!0).catch(()=>{})},ah=async e=>{await Lo($c(e)).catch(()=>{}),await Lo(el(e)).catch(()=>{}),await Lo(mm(e)).catch(()=>{}),await Lo(hm(e)).catch(()=>{}),await Lo(tl(e)).catch(()=>{})},oh=async e=>{let t=[];await Io(Jc,n=>t=(n??[]).filter(t=>t.infoHash!==e)),await Io(Yc,t=>Xc(t,[{infoHash:e,removedAt:Date.now()}])),await ah(e),X({type:`list`,list:t})},Q=/* @__PURE__ */ new Set,sh=/* @__PURE__ */ new Set([4,5]);let ch=Fl;const lh=e=>Im(e)||Rm(e),uh=e=>{lh(e)?W?.setFlags(e,0,V.paused|V.autoManaged):W?.resumeTorrent(e)},dh=/* @__PURE__ */ new Map,fh=/* @__PURE__ */ new Set,ph=/* @__PURE__ */ new Set;let mh=null,hh=0;const gh=5e3;let _h=null,vh=0,yh=0,bh=rc,xh=0,Sh=0;const Ch=/* @__PURE__ */ new Set,wh=async e=>{if(!Ch.has(e)){Ch.add(e);try{let t=W?.files(e)?.storageIndex,n=t===void 0||!ym?null:await ym.usageOfStorage(t);e===mh&&(_h={handle:e,bytes:n})}finally{Ch.delete(e)}}},Th=e=>{let t=mh;if(t==null||!G.includes(t))return null;W.peers(t),e-hh>=gh&&(hh=e,W.trackers(t),wh(t).catch(()=>{}));let n=W.lastTrackers(t),r=W?.pieceAvailability(t);return{handle:t,peers:W.lastPeers(t),trackers:[..._m?n:n.map(Eh),...vm?.trackers(t)??[]],storageBytes:_h?.handle===t?_h.bytes??void 0:void 0,...r?.length?{availability:r}:{}}},Eh=e=>({...e,message:``,fails:-1,updating:!1,nextAnnounceIn:-1}),Dh=()=>{let e=Th(Date.now());X({type:`state`,torrents:Qm(),transport:gm,reachable:W.reachable(),inboundNow:bh,dhtNodes:xh,detail:e,rateLimits:{...Lh}},e?.availability?[e.availability.buffer]:[])},Oh=e=>{let t=W?.files(e);if(!t)return[];let n=t.files.map(e=>e.path.split(`/`).filter(Boolean)[0]).filter(Boolean);return[...new Set(n)]},kh=(e,t,n,r,i=!1)=>{G.includes(e)||G.push(e),Dm.set(e,t),n&&(K.set(e,n),ph.add(e)),q.set(e,r),i?Q.add(e):Q.delete(e)},Ah=e=>{let t=G.indexOf(e);t>=0&&G.splice(t,1),Dm.delete(e),K.delete(e),q.delete(e),Om.delete(e),km.delete(e),Y.forget(e),og.delete(e),eg.delete(e),Wm.delete(e),Gm.delete(e),Jm.delete(e),$.delete(e),fg.delete(e),pg.delete(e),Mh.delete(e),Ih.delete(e),Rh.delete(e),Bh.delete(e),Vh.delete(e),Hh.delete(e),Uh.delete(e),Q.delete(e),dh.delete(e),fh.delete(e),ph.delete(e),Nh.delete(e),Vg.delete(e),mg.delete(e),hg.delete(e),gg.delete(e),_g.delete(e),Ig.delete(e),Lg.delete(e),Ag.delete(e),Ym.delete(e),Fh.delete(e)},jh=e=>{Vm(e,`cache-idle`)&&(qm(e),W?.resumeTorrent(e),Y.hold(e,Date.now()))},Mh=/* @__PURE__ */ new Set,Nh=/* @__PURE__ */ new Set,Ph=e=>{Nh.delete(e)&&W?.setFlags(e,0,V.uploadMode)},Fh=/* @__PURE__ */ new Set,Ih=/* @__PURE__ */ new Map;let Lh={down:0,up:0};const Rh=/* @__PURE__ */ new Map;let zh=0;const Bh=/* @__PURE__ */ new Map,Vh=/* @__PURE__ */ new Map,Hh=/* @__PURE__ */ new Map,Uh=/* @__PURE__ */ new Map,Wh=e=>({activeSeconds:e.activeSeconds,seedingSeconds:e.seedingSeconds,downloaded:e.allTimeDownload,uploaded:e.allTimeUpload,wasted:e.wasted}),Gh=e=>({activeSeconds:e?.activeSeconds??0,seedingSeconds:e?.seedingSeconds??0,downloaded:e?.downloaded??0,uploaded:e?.uploaded??0,wasted:e?.wasted??0}),Kh=e=>{let t=W?.status(e),n=Hh.get(e);return!t||!n?Uh.get(e)??sc:fc(Uh.get(e),n,Wh(t))},qh=(e,t)=>{let n={...Rh.get(e)};Ml(t.down)&&(n.down=t.down),Ml(t.up)&&(n.up=t.up),(Ml(n.down)||Ml(n.up))&&(Rh.set(e,n),Yh(e))},Jh=e=>{let t=Rh.get(e)?.down;return _g.has(e)?Math.min(t||16384,16384):t},Yh=e=>{let t=Rh.get(e);if(!W||!t)return;let n=Jh(e);Ml(n)&&W.setDownloadLimit(e,n),Ml(t.up)&&W.setUploadLimit(e,t.up)},Xh=6e3,Zh=e=>e.reachable().listeners?.some(e=>e.healing)===!0,Qh=U.formatMessage({id:`torrent removed`,defaultMessage:`torrent removed`}),$h=U.formatMessage({id:`torrent paused`,defaultMessage:`torrent paused`}),eg=/* @__PURE__ */ new Map,tg=e=>[...eg.get(e)?.values()??[]].some(t=>!t.viewer||$.get(e)?.has(t.viewer)),ng=e=>[...eg.get(e)?.values()??[]].some(t=>(!t.viewer||$.get(e)?.has(t.viewer))&&!r_(e,t.fileIndex,t.offset,t.len)),rg=(e,t)=>{let n=eg.get(e);if(n?.size){for(let e of n.keys())X({type:`read-error`,id:e,error:t});n.clear()}},ig=async e=>{if(!e||cl(e))return;let t=await navigator.storage.getDirectory();for(let n of e.split(`/`).filter(Boolean))t=await t.getDirectoryHandle(n,{create:!0})},ag=async(e,t,n)=>{if((await Po(el(e)))?.byteLength)return;let r=Dl(t);if(!r)return;let i=Tl(r,El(n));await Io(el(e),e=>e?.byteLength?e:i)},og=/* @__PURE__ */ new Map,sg=async e=>{let t=K.get(e);if(!t||!W||og.has(e)||sl(q.get(e)))return!1;let n=W.status(e);if(!n||Qs.has(n.state)||Nh.has(e))return!1;let r=(async()=>{try{let n=await W.saveResumeData(e);return G.includes(e)?(await ig(q.get(e)),await Fo($c(t),n),await ag(t,n,Dm.get(e)??``).catch(()=>{}),!0):!1}catch(e){return console.error(`[worker] saving resume data failed`,String(e)),!1}})().finally(()=>og.delete(e));return og.set(e,r),r},cg=(e,t)=>{let n=W?.files(e),r=n?.files[t];if(!n||!r||r.size<=0)return null;let i=Math.floor(r.offset/n.pieceLength),a=Math.floor((r.offset+r.size-1)/n.pieceLength);return{file:r,pieceLength:n.pieceLength,p0:i,p1:a}},$=/* @__PURE__ */ new Map;let lg=!1;const ug=()=>[...$].every(([e,t])=>[...t.values()].every(t=>t.held||t.bulk||t.prepare||r_(e,t.fileIndex,t.fromOffset,1/0))),dg=()=>[...$].filter(([,e])=>[...e.values()].some(e=>e.prepare)).map(([e])=>e),fg=/* @__PURE__ */ new Set,pg=/* @__PURE__ */ new Set,mg=/* @__PURE__ */ new Map,hg=/* @__PURE__ */ new Map,gg=/* @__PURE__ */ new Set,_g=/* @__PURE__ */ new Set;let vg,yg;const bg=()=>!!vg?.fixed||yg!==void 0,xg=`ripple:ceiling-fixed`;let Sg,Cg=null;const wg=(e,t,n)=>[...Bg(e).filter(e=>e.fileIndex===t).map(e=>Rs(n,e.fromOffset,e.fromOffset+xs(n.pieceLength))),...[...eg.get(e)?.values()??[]].filter(n=>n.fileIndex===t&&(!n.viewer||$.get(e)?.has(n.viewer))).map(e=>Rs(n,e.offset,e.offset+e.len))],Tg=(e,t,n)=>{let r=hg.get(e),[i]=n;if(r===void 0||!i||!bg()||!Q.has(e)||n.some(e=>e.fileIndex!==i.fileIndex))return null;let a=t.files[i.fileIndex],o=q.get(e);if(!a||o===void 0)return null;let s={offset:a.offset,size:a.size,pieceLength:t.pieceLength},c=Cm.chunkBytesOf(o),l=Cm.chunksOf(o,i.fileIndex),u=Us({file:s,chunkBytes:c,room:r,reader:i.fromOffset,held:l,pinned:wg(e,i.fileIndex,s)});return u&&{...u,fileIndex:i.fileIndex,file:s,chunkBytes:c}},Eg=(e,t)=>e.fileIndex===t.fileIndex&&JSON.stringify(e.want)===JSON.stringify(t.want),Dg=(e,t)=>{let n=W?.bitfield(e);if(!n)return!1;for(let e=t.start;e<t.end;e++)if(!((n.pieces[e>>3]??0)&128>>(e&7)))return!1;return!0},Og=()=>Cg?Cg.space.limitBytes-Cg.space.usedBytes-(Cm.footprint()-Cg.footprint)-hc:1/0,kg=3e4,Ag=/* @__PURE__ */ new Map,jg=e=>(Ag.get(e)?.until??0)>Date.now(),Mg=e=>{let t=mg.get(e),n=!!t&&!tg(e)&&Ws(Dg(e,t.ahead),Og(),t.chunkBytes);n!==_g.has(e)&&(n?_g.add(e):_g.delete(e),W?.setDownloadLimit(e,Jh(e)??0))},Ng=e=>{let t=mg.get(e),n=W?.bitfield(e);if(!t||!n||t.slack.end<=t.slack.start||jg(e))return;let r=[];for(let e=t.slack.start;e<t.slack.end;e++)(n.pieces[e>>3]??0)&128>>(e&7)&&r.push(e);r.length&&t.slack.end-t.slack.start-r.length<2&&W?.forgetPieces(e,r)},Pg=e=>Uc(q.get(e))&&Q.has(e)&&![...$.get(e)?.values()??[]].some(e=>e.held||e.bulk)&&gl(Ih.get(e)??{}),Fg=e=>{let t=[...$.get(e)?.values()??[]],n=W?.files(e),r=q.get(e);if(!n||r===void 0||!Pg(e)||!t.some(e=>!e.prepare)||!bg()||jg(e))return[];let i=new Set(t.map(e=>e.fileIndex)),a=Cm.chunkBytesOf(r),o=({offset:e,size:t})=>({offset:e,size:t,pieceLength:n.pieceLength}),s=n.files.flatMap((t,n)=>i.has(n)?[Rs(o(t),0,t.size)]:wg(e,n,o(t)));return n.files.flatMap((e,t)=>e.pad||i.has(t)?[]:Cm.chunksOf(r,t).map(n=>({chunk:n,fileIndex:t,pieces:zs(o(e),a,n)})).filter(({pieces:e})=>!s.some(t=>t.start<e.end&&e.start<t.end)))},Ig=/* @__PURE__ */ new Set,Lg=/* @__PURE__ */ new Set,Rg=async e=>{if(Ig.has(e)){Lg.add(e);return}Ig.add(e);let t=!1;try{if(jg(e)){t=!0;return}let n=q.get(e),r=()=>{let t=mg.get(e),r=gg.has(e)?Fg(e):[];if(!t||n===void 0)return r;let i=/* @__PURE__ */ new Set([...t.keep,...Bs(t.file,t.chunkBytes,wg(e,t.fileIndex,t.file))]);return[...Cm.chunksOf(n,t.fileIndex).filter(e=>!i.has(e)).map(e=>({chunk:e,fileIndex:t.fileIndex,pieces:zs(t.file,t.chunkBytes,e)})),...r]},i=({start:t,end:n})=>W?.forgetPieces(e,Array.from({length:n-t},(e,n)=>t+n))??null,a=r().filter(({pieces:n})=>{let r=i(n);if(r?.busy){for(let t=n.start;t<n.end;t++)W?.cancelPieceRequests(e,t);t=!0}return r?.busy===0});if(!a.length||n===void 0)return;if(!await sg(e)){t=!0;return}let o=new Set(r().map(({fileIndex:e,chunk:t})=>`${e}:${t}`)),s=[];for(let{chunk:e,fileIndex:t,pieces:r}of a){if(!o.has(`${t}:${e}`))continue;let a=i(r);!a||a.forgotten||a.busy||s.push(Cm.drop(n,t,e))}await Promise.all(s),s.length&&Y.retry(e,Date.now())}catch(e){console.error(`[worker] dropping chunks failed`,String(e))}finally{Ig.delete(e),Lg.delete(e)?Rg(e):t&&(mg.has(e)||gg.has(e))&&setTimeout(()=>void Rg(e),1e3)}},zg=e=>{let t=Ih.get(e);if(!W||!t)return;let n=W.files(e);n&&W.prioritizePieces(e,hl({files:n.files,pieceLength:n.pieceLength,numPieces:Math.ceil(n.totalSize/n.pieceLength),wanted:t.wanted,firstLast:t.firstLast}))},Bg=e=>{let t=$.get(e);return t?[...t.values()].filter(e=>!e.held&&(!e.prepare||lg)):[]},Vg=/* @__PURE__ */ new Set,Hg=(e,t,n)=>{let[r]=n,i=r&&t.files[r.fileIndex],a=r&&i?.size&&!r.bulk&&!r.prepare&&Vg.has(e)?Rs({...i,pieceLength:t.pieceLength},r.fromOffset,r.fromOffset+ys):null;return!a||Dg(e,a)?(Vg.delete(e),null):a},Ug=()=>{for(let e of[...Vg]){let t=W?.files(e);t&&!Hg(e,t,Bg(e))&&$g(e)}},Wg=e=>Q.has(e)&&q.get(e)!==nl&&!Mm(e)&&!Lm(e)&&!Im(e),Gg=e=>{J(e,`watchedPastQueue`,!1),Bm(e,`cache-idle`),Km(e),W?.pauseTorrent(e),Ph(e),sg(e)},Kg=(e,t)=>{let n=e.files[t.fileIndex];if(!n||n.size<=0)return[];let r=Math.ceil(e.totalSize/e.pieceLength),i=Math.floor(n.offset/e.pieceLength),a=Math.min(r-1,Math.floor((n.offset+n.size-1)/e.pieceLength));if(a<i)return[];if(!t.prepare)return[{start:i,end:a+1}];let o=bs(e.pieceLength);return[t.fromOffset,Math.max(0,n.size-ys)].map(t=>{let r=Math.min(Math.max(t,0),Math.max(0,n.size-1)),s=Math.min(Math.max(Math.floor((n.offset+r)/e.pieceLength),i),a);return{start:s,end:Math.min(a+1,s+o)}})},qg=(e,t,n)=>n.every(n=>Kg(t,n).every(t=>Dg(e,t))),Jg=(e,t,n)=>mg.has(e)||!!t&&!!Tg(e,t,n.filter(e=>!e.prepare)),Yg=(e,t)=>{if(!Rl(ch)||!W)return!1;let n=W.status(e);if(!n||!sh.has(n.state))return!1;let r=Kh(e),i=$m(e),a=t?.contentSize??t?.totalSize??0;return Hl(ch,{uploaded:r.uploaded,downloaded:r.downloaded,size:a,seedingSeconds:i.seedingSeconds})},Xg=e=>{J(e,`watchedPastQueue`,!1),Bm(e,`seed-policy`),J(e,`seedBypass`,!1),Km(e),W?.pauseTorrent(e),sg(e);let t=K.get(e);t&&Z(t,{seedStopped:!0,seedBypass:!1}).catch(()=>{})},Zg=e=>{qm(e),uh(e),Y.hold(e,Date.now());let t=K.get(e);t&&Z(t,{seedStopped:!1}).catch(()=>{})},Qg=()=>{if(W&&(Rl(ch)||Um()))for(let e of G){if(q.get(e)===nl||Nm(e)||Mm(e))continue;if(Im(e)||zm(e)){Vm(e,`seed-policy`)&&Zg(e);continue}let t=W.status(e);if(!t||Qs.has(t.state))continue;if(!sh.has(t.state)){Vm(e,`seed-policy`)&&Zg(e);continue}let n=W.files(e)??null,r=Bg(e);if(!(Q.has(e)&&Jg(e,n,r))){if(Yg(e,n)){if(ng(e)||r.length>0&&(!n||!qg(e,n,r)))continue;Pm(e)||Xg(e)}else Vm(e,`seed-policy`)&&Zg(e)}}},$g=e=>{if(!W)return;if(!G.includes(e)){$.delete(e),pg.delete(e);return}let t=Bg(e);if(!t.length){if(Vg.delete(e),J(e,`watchedPastQueue`,!1)&&!Im(e)&&!Fm(e)&&W.setFlags(e,V.autoManaged,V.autoManaged),!W.files(e)){pg.add(e);return}if(pg.delete(e),mg.delete(e),Mg(e),W.clearStreamWindow(e),gl(Ih.get(e)??{})||zg(e),Wg(e)&&!Nm(e)){let t=W.status(e);if(!t||Qs.has(t.state)){pg.add(e);return}if(Vm(e,`seed-policy`)){let t=K.get(e);t&&Z(t,{seedStopped:!1}).catch(()=>{})}Gg(e)}else Ph(e);return}let n=W.files(e);if(n&&(Pm(e)||Nm(e)&&!Im(e)&&!zm(e)&&!ng(e)&&!(Q.has(e)&&Jg(e,n,t))&&Yg(e,n))){if(qg(e,n,t)){if(jm(e)===`cache-idle`){Bm(e,`seed-policy`);let t=K.get(e);t&&Z(t,{seedStopped:!0}).catch(()=>{})}pg.delete(e),Vg.delete(e);return}Vm(e,`seed-policy`)&&Zg(e)}if(jh(e),!Mm(e)&&!Pm(e)&&J(e,`watchedPastQueue`,!0)&&uh(e),Ph(e),!n){pg.add(e);return}fg.delete(e)&&O_();let r=Hg(e,n,t),i=t.flatMap(({fileIndex:e,fromOffset:t,bulk:r,prepare:i})=>{let a={fileIndex:e,offset:t},o=n.files[e];return i?o?.size?[a,{fileIndex:e,offset:Math.max(0,o.size-ys)}]:[]:!r&&o?.size?[a,{fileIndex:e,offset:o.size-1}]:[a]}),a=t.filter(e=>!e.prepare),o=a.some(e=>!e.bulk),s=Tg(e,n,a);s?mg.set(e,s):mg.delete(e);let c=s?.want??(a.length<t.length?a.map(({fileIndex:e})=>n.files[e]).flatMap(e=>e?.size?[Rs({...e,pieceLength:n.pieceLength},0,e.size)]:[]):void 0);W.setStreamWindow(e,i,{unclaimedPriority:H.skip,windowPieces:r?r.end-r.start:bs(n.pieceLength),deadlineStepMs:Cs(n.pieceLength,W.status(e)?.downloadRate||3e6),deadlines:o,...c?{keep:c}:{}})?pg.delete(e):pg.add(e),s&&Rg(e),Ng(e),Mg(e)},e_=e=>{let t=W?.files(e),n=Bg(e).filter(e=>!e.prepare);if(!t||!n.length)return;let r=Tg(e,t,n),i=mg.get(e);if(r&&i&&Eg(r,i)){mg.set(e,r),Rg(e);return}(r||i)&&$g(e),!r&&gg.has(e)&&Rg(e)},t_=(e,t,n,r,i=!1,a,o=!1)=>{if(!G.includes(t))return;let s=$.get(t),c=!s?.size;s||$.set(t,s=/* @__PURE__ */ new Map);let l=s.get(e),u=a??l?.bulk;s.set(e,{fileIndex:n,fromOffset:r,...i?{held:i}:{},...u?{bulk:u}:{},...o?{prepare:o}:{}}),c?(ih(t),fg.add(t),Vg.add(t)):l?.fromOffset!==r&&Vg.delete(t),o&&(lg=ug()),$g(t)},n_=e=>{let t=!1;for(let[n,r]of[...$]){let i=!1;for(let t of[...r.keys()])e(t)&&(r.delete(t),i=!0);r.size||($.delete(n),i&&(ih(n),t=!0)),i&&$g(n)}t&&x_&&O_()},r_=(e,t,n,r)=>{let i=W?.files(e),a=i?.files[t],o=W?.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},i_=(e,t,n,r)=>{let i=W?.files(e),a=i?.files[t];if(!i||!a||n>=a.size)return r;let o=W?.bitfield(e),s=e=>!!o&&!!((o.pieces[e>>3]??0)&128>>(e&7)),c=Math.min(n+r,a.size),l=e=>Math.min(c,(e+1)*i.pieceLength-a.offset),u=Math.floor((a.offset+n)/i.pieceLength),d=l(u);if(s(u))for(;d<c&&s(u+1);)d=l(++u);return d-n},a_=(e,t,n,r)=>{let i=W?.files(e),a=i?.files[t],o=W?.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},o_=(e,t,n)=>{let r=Math.max(0,e-ys-t),i=n?Math.floor(r/n)*n:0;return Math.min(e,xs(t)+e-i)},s_=async(e,t={evictable:[],graced:[]})=>{let n=e=>Math.max(0,e.size-e.held),r=[],i=[],a=/* @__PURE__ */ new Map;for(let[e,t]of[...$]){let n=ym,o=W?.files(e),s=q.get(e);if(!n||!o||!t.size||s===void 0||cl(s))continue;let c=new Set([...t.values()].filter(e=>!e.prepare).map(e=>e.fileIndex)),l=Cm.chunkBytesOf(s),u=async r=>{let i=o.files[r]?.size??0,a=!c.has(r)&&[...t.values()].some(e=>e.prepare&&e.fileIndex===r);return{h:e,size:a?o_(i,o.pieceLength,Uc(s)?l:void 0):i,held:await n.usageOfStorage(o.storageIndex,r)??0}},d=Bg(e).find(e=>!e.prepare),f=bg()&&Q.has(e)&&Uc(s);for(let e of new Set([...t.values()].map(e=>e.fileIndex)))r.push({...await u(e),cache:f&&e===d?.fileIndex,chunkBytes:l});let p=n.refusedFile(o.storageIndex),m=Pg(e)&&![...t.values()].some(e=>e.fileIndex===p);p!==void 0&&!m&&i.push(await u(p));let h=Fg(e),g=0;for(let e of new Set(h.map(e=>e.fileIndex))){let t=Cm.chunksOf(s,e).length-h.filter(t=>t.fileIndex===e).length;g+=Math.max(0,(await n.usageOfStorage(o.storageIndex,e)??0)-t*l)}g>0&&a.set(e,g)}let o=e=>e.reduce((e,t)=>e+n(t),0),s=r.filter(e=>!e.cache),c=o(s.filter(e=>!Q.has(e.h))),l=Math.max(0,xc({...e,candidates:[...t.evictable,...t.graced]},bg())),u=o(s)-c+Math.min(c,l),d=r.filter(e=>e.cache),f=e=>e.reduce((e,t)=>e+t.bytesOnDisk,0),p=e.limitBytes-e.usedBytes+d.reduce((e,t)=>e+t.held,0)+f(t.evictable)-u-hc,m=e=>{let t=Vs(d.map(e=>e.size),p+e),r=new Set(d.filter((e,n)=>Hs(e.size,t[n]??0,e.chunkBytes)).map(e=>e.h));return{shares:t,windowed:r,owed:d.reduce((e,i,a)=>e+(r.has(i.h)?Math.max(0,(t[a]??0)-i.held):n(i)),u)}},h=m(0),g=d.some((e,t)=>e.size>(h.shares[t]??0)&&!h.windowed.has(e.h))?[...a.values()].reduce((e,t)=>e+t,0):0;g||a.clear();let _=m(g),v=m(g+f(t.graced)),y=i.filter(e=>!v.windowed.has(e.h)),b=y.filter(e=>!Q.has(e.h)),x=o(b)+b.length*gc(e.limitBytes),S=o(y.filter(e=>Q.has(e.h)))+x,C=new Map(d.map((e,t)=>[e.h,_.shares[t]??0]));return{pendingBytes:Math.max(0,_.owed-g),laterBytes:v.owed,refusedBytes:S,keptRefusedBytes:x,rooms:C,left:a}},c_=(e,t,n,r,i)=>{if(!e||!G.includes(t))return;let a=$.get(t)?.get(e);if(!a||a.held||a.fileIndex!==n){t_(e,t,n,r);return}let o=cg(t,n);if(!o)return;let s={fileOffset:o.file.offset,pieceLength:o.pieceLength,p1:o.p1};ws(s,a.fromOffset,r,i)&&t_(e,t,n,r)},l_=async e=>{let t=e.filter(e=>!cl(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}},u_=async()=>{let e,t;try{return e=await navigator.storage.getDirectory(),t=`.ripple-probe-${crypto.randomUUID()}`,(await Ms(await e.getFileHandle(t,{create:!0}))).close(),await e.removeEntry(t).catch(()=>{}),!0}catch{return e&&t&&await e.removeEntry(t).catch(()=>{}),!1}},d_=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}),f_=async()=>{let e=xm;try{let{usage:t,quota:n}=await Nc.estimate();return!n||t===void 0?null:{usedBytes:t,limitBytes:n,grownAt:e}}catch{return null}},p_=async()=>{try{let{usage:e,quota:t}=await navigator.storage.estimate();return t&&e!==void 0?t-e:null}catch{return null}},m_=async(e,t=0)=>{for(let n=0;n<4e3;n+=250){await new Promise(e=>setTimeout(e,250));let n=await f_();if(!n||e-n.usedBytes>t/2)return n}return f_()},h_=async(e,t,n,r,i={})=>{rg(t,r),e.removeTorrent(t,!0),Ah(t),await Lo($c(n)).catch(()=>{}),await Z(n,{started:!1,paused:!1,...i})},g_=(e,t,n)=>h_(e,t,n,U.formatMessage({id:`torrent removed to make room`,defaultMessage:`torrent removed to make room`})),__=async(e,t,n,r)=>{if(!await fl(n,r.files))return;let i=K.get(t);i&&al(q.get(t))&&await h_(e,t,i,U.formatMessage({id:`Files missing`,defaultMessage:`Files missing`}),{savePath:Vc(i)})},v_=async(e,t,n,r)=>{let i=kl(q.get(t));if(i===r)return;let a=Dm.get(t)??``,o=Al(r,n),s=Mm(t),c=km.get(t),l=c?.stop===`seed-policy`,u=c?.userStarted===!0,d=c?.forced===!0,f=c?.seedBypass===!0,p=Q.has(t),m=Ih.get(t),h=(await th()).find(e=>e.infoHash===n)?.private===!0||e.isPrivate?.(t)===!0,g=await Po($c(n)).catch(()=>void 0);g?.byteLength&&await ag(n,g,a).catch(()=>{});let _=await Po(el(n)).catch(()=>void 0);if(h&&!_?.byteLength){X({type:`add-failed`,message:U.formatMessage({id:`This private torrent needs its .torrent file. Add it again.`,defaultMessage:`This private torrent needs its .torrent file. Add it again.`})});return}rg(t,U.formatMessage({id:`files moved`,defaultMessage:`files moved`})),e.removeTorrent(t,i===`browser`),Ah(t),await Lo($c(n)).catch(()=>{});let v=_?.byteLength?e.addTorrentFile(_,o):Zm(e,a,o);if(Xm(v)){X({type:`add-failed`,message:U.formatMessage({id:`Moving the files left the torrent unaddable`,defaultMessage:`Moving the files left the torrent unaddable`})}),await Z(n,{savePath:o,saveTo:r,started:!1});return}kh(v,a,n,o,p),m&&Ih.set(v,m),Mh.add(v),r===`folder`&&e.setFlags(v,V.uploadMode,V.uploadMode),s?(Bm(v,`user`),Km(v)):l?(Bm(v,`seed-policy`),Km(v)):qm(v),u&&J(v,`userStarted`,!0),d&&!s&&(J(v,`forced`,!0),uh(v)),f&&!s&&!l&&J(v,`seedBypass`,!0),Y.hold(v,Date.now()),await Z(n,{savePath:o,saveTo:r,started:!0})},y_=(e,{infoHash:t,magnet:n,bytes:r,handles:i,paused:a,seedStopped:o=!1,ephemeral:s=!1})=>{let c=ol(t);Tm.set(c,i);let l=e.addTorrentFile(r,c);return Xm(l)?(Tm.delete(c),null):(kh(l,n,t,c,s),e.setFlags(l,V.uploadMode,V.uploadMode),a?(Bm(l,`user`),Km(l)):o&&(Bm(l,`seed-policy`),Km(l)),Y.hold(l,Date.now()),l)},b_=async(e,t)=>{let n=new Map(e.map(e=>[e.infoHash,e])),r=[],i=[];for(let e of[...G]){let a=K.get(e);if(!a)continue;let o=n.get(a);if(!o?.ephemeral||!Wc(o.savePath,a)||$.get(e)?.size||tg(e))continue;let s=o.lastUsedAt??o.addedAt,c=await ym?.usageOf(o.savePath)??0;if(c<=0)continue;let l=t-(dh.get(e)??0)<6e4||t-s<15e3,u={infoHash:a,usedAt:s,bytesOnDisk:c};l?i.push(u):r.push(u)}return{evictable:r,graced:i}};let x_=!1;const S_=(e,t)=>{let n=yc(e)&&(yc({...e,refusedBytes:e.refusedBytes-t})||`kept`);n!==x_&&(x_=n,X({type:`storage-full`,full:n,usedBytes:e.usedBytes,limitBytes:e.limitBytes}))},C_=/* @__PURE__ */ new Set;let w_=!1;const T_=async()=>{if(!W||w_)return 0;w_=!0;try{let e=await th(),t=new Set(e.map(e=>e.infoHash.toLowerCase()));for(let e of C_)t.add(e.toLowerCase());let n=/* @__PURE__ */ new Set,r=!0;for(let e of G){let i=K.get(e);if(i&&t.add(i.toLowerCase()),(q.get(e)??`/dl`)!==`/dl`)continue;let a=Oh(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(!Uc(e)){if(e!==`/dl`&&!e.startsWith(`/dl/`)){r=!1;continue}if(e===`/dl`){if(t.rootEntry){n.add(t.rootEntry);continue}!G.some(e=>K.get(e)===t.infoHash)&&t.started!==!1&&(r=!1)}}}let i=await navigator.storage.getDirectory(),a=[...await Rc(i,`/dl`,{listedHashes:t,claimedNames:n,attributable:r}),...await Rc(i,`/cache`,{listedHashes:t,claimedNames:/* @__PURE__ */ new Set,attributable:!1})];return await zc(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{w_=!1}};let E_=!1,D_=!1;const O_=async()=>{let e=W;if(!e)return;if(E_){D_=!0;return}E_=!0;let t=null,n={pendingBytes:0,laterBytes:0,refusedBytes:0,keptRefusedBytes:0,rooms:/* @__PURE__ */ new Map,left:/* @__PURE__ */ new Map},r=[],i=[],a=e=>({...e,pendingBytes:vg?.fixed===!1&&yg===void 0?0:n.laterBytes,refusedBytes:n.refusedBytes,candidates:[...r,...i,...[...n.left].map(([e,t])=>({infoHash:K.get(e)??``,usedAt:0,bytesOnDisk:t}))]}),o=()=>{hg.clear(),gg.clear();for(let[e,t]of n.rooms)hg.set(e,t);for(let e of n.left.keys())gg.add(e);for(let e of/* @__PURE__ */ new Set([...hg.keys(),...mg.keys(),...gg]))e_(e)};try{let s=await f_();if(!s)return;t=s,Sg===void 0&&(Sg=await Po(xg).catch(()=>null)??null);let c=async e=>{let t=Cm.footprint(),n=await p_();if(n!==null){let t={usedBytes:e.usedBytes,headroomBytes:n};vg=Gs(vg??(typeof Sg==`boolean`?{...t,fixed:Sg}:void 0),t,Is),vg.fixed!==void 0&&vg.fixed!==Sg&&(Sg=vg.fixed,Fo(xg,Sg).catch(()=>{}));let r=[...$.keys()].some(e=>{let t=W?.files(e)?.storageIndex;return t!==void 0&&Q.has(e)&&Uc(q.get(e))&&ym?.refusedFile(t)!==void 0});yg===void 0&&vg.fixed===!1&&r&&(yg=e.usedBytes)}let r=yg===void 0?e:{...e,limitBytes:Math.min(e.limitBytes,Math.max(yg,e.usedBytes))};return Cg={space:r,footprint:t},r};s=t=await c(s),n=await s_(s);let l=await b_(await th(),Date.now());r=l.evictable,i=l.graced,n=await s_(s,l);let u=!1;for(;r.length;){let[a]=Cc({...s,pendingBytes:n.pendingBytes,candidates:r});if(!a)break;let o=r.find(e=>e.infoHash===a)?.bytesOnDisk??0;r=r.filter(e=>e.infoHash!==a);let l=G.find(e=>K.get(e)===a);if(l===void 0||$.get(l)?.size||tg(l))continue;let d=s.usedBytes;t=null,await g_(e,l,a),u=!0;let f=await m_(d,o);if(!f)return;s=t=await c(f),n=await s_(s,{evictable:r,graced:i})}if(u)for(let e of $.keys())Y.retry(e,Date.now());if(o(),yc(a(s))&&await T_()){s=await c(await m_(s.usedBytes)??s),n=await s_(s,{evictable:r,graced:i});for(let e of $.keys())Y.retry(e,Date.now());o()}t=s}catch(e){console.error(`[worker] storage budget pass failed`,String(e))}finally{E_=!1,t&&(S_(a(t),n.keptRefusedBytes),bm={room:xc(a(t),bg()),grownAt:t.grownAt}),D_&&(D_=!1,O_())}};let k_,A_=!1;const j_=()=>{k_??=setInterval(()=>{let e=W,t=[...$.keys()].filter(t=>Bg(t).length&&!e?.files(t)),n=[...eg.keys()].filter(tg);if(!e||A_||!t.length&&!n.length){clearInterval(k_),k_=void 0;return}for(let t of n)e.postStatus(t);e.tick(),e.popAlerts();let r=t.filter(t=>e.files(t));for(let e of r)$g(e);Ug(),r.length&&Dh()},50)},M_=async()=>{let e=console.error.bind(console);if(console.error=(...t)=>{e(...t);try{X({type:`worker-error`,args:t.map(String)})}catch{}},!await u_()){X({type:`storage-unavailable`});return}th().then(e=>{e.length&&X({type:`list`,list:e})}).catch(()=>{});let t=Promise.race([Po(jl).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]),n=Promise.race([Po(Pl).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]);ym=pl(Fs(Sm),()=>wm,e=>Tm.get(e)??null,Cm),W=await ms(_m?{net:_m.net,dgram:_m.dgram,dnsLookup:ko,storage:ym,utpReceiveBufferBytes:4194304}:{...ps(),storage:ym,enableDht:!1,reserveListenPort:!1});for(let e=0;e<30;e++)W.tick();vm=_m?tm(W,_m):em(W,X),Lh=Nl(await t),ch=Bl(await n),W.setRateLimits({download:Lh.down,upload:Lh.up});try{let e=await th(),t=!await l_(e.filter(e=>e.started!==!1).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 Po($c(r.infoHash)),a=await Po(el(r.infoHash));if(t&&i&&i.byteLength){await Lo($c(r.infoHash)).catch(()=>{}),r.started=!1,n=!0;continue}r.private!==!0&&(a?.byteLength&&bl(a)||i?.byteLength&&Ol(i))&&(r.private=!0,n=!0);let o=r.private===!0,s=i?.byteLength&&(!o||Ol(i))?i:void 0;o&&i?.byteLength&&!s&&await Lo($c(r.infoHash)).catch(()=>{});let c=s?W.addTorrentWithResume(s,e):a&&a.byteLength?W.addTorrentFile(a,e):o?-2>>>0:Zm(W,r.magnet,e);if(Xm(c)){o&&!s&&!a?.byteLength&&(r.started=!1,n=!0);continue}kh(c,r.magnet,r.infoHash,e,r.ephemeral===!0),i?.byteLength&&al(e)&&Fh.add(c),Ih.set(c,{wanted:r.wantedFiles,firstLast:r.firstLast}),Mh.add(c),qh(c,{down:r.downloadLimit??0,up:r.uploadLimit}),Vh.set(c,{activeSeconds:r.activeSeconds??0,seedingSeconds:r.seedingSeconds??0}),Uh.set(c,Gh(r)),r.paused?(Bm(c,`user`),Km(c)):r.seedStopped?(Bm(c,`seed-policy`),Km(c)):qm(c),r.resumed&&J(c,`userStarted`,!0),r.forced&&!r.paused&&(J(c,`forced`,!0),uh(c)),r.seedBypass&&!r.paused&&!r.seedStopped&&J(c,`seedBypass`,!0),Y.hold(c,Date.now()),r.ephemeral&&(!i?.byteLength||Uc(e))&&(Nh.add(c),W.setFlags(c,V.uploadMode,V.uploadMode))}n&&await Fo(Jc,e)}catch(e){console.error(`[worker] restore failed`,e)}X({type:`ready`}),Em=!0,X({type:`list`,list:await th().catch(()=>[])}),Dh(),setInterval(()=>{if(!W)return;let e=Date.now();W.popAlerts();for(let e of G)W.postStatus(e);vm?.refresh();for(let e of[...Mh])W.files(e)&&(Mh.delete(e),Bg(e).length||$g(e));if(wm)for(let e of[...Fh]){let t=W.files(e);t&&(Fh.delete(e),__(W,e,wm,t))}let t=dg();if(t.length&&ug()!==lg){lg=!lg;for(let e of t)$g(e)}for(let e of[...pg])$g(e);Ug();for(let t of[...fh])tg(t)||e-(dh.get(t)??0)<5e3||(fh.delete(t),$g(t));for(let e of[...mg.keys()])Ng(e),Mg(e);for(let e of G){if(Bh.has(e))continue;let t=W.status(e);t&&(Bh.set(e,{activeSeconds:t.activeSeconds,seedingSeconds:t.seedingSeconds}),Hh.set(e,Wh(t)))}for(let e of[...ph]){let[t]=Oh(e);if(!t)continue;ph.delete(e);let n=K.get(e);if(!n)continue;let r=W.files(e);Z(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})),...W.isPrivate?.(e)===!0?{private:!0}:{}}).catch(()=>{})}Qg();for(let e of Wm){let t=W.status(e);t&&!Qs.has(t.state)&&($s(t)?Wm.delete(e):W.pauseTorrent(e))}for(let e of Gm){if(Fm(e)){Gm.delete(e);continue}let t=W.status(e);if(t&&!Qs.has(t.state)){if(!t.paused){Gm.delete(e);continue}if(t.autoManaged||t.errorCode){Gm.delete(e);continue}W.resumeTorrent(e)}}Y.retain(new Set(G));for(let t of G){let n=W.status(t);Y.observe(t,n&&d_(n),Fm(t),e),!n||n.paused||!Zs.has(n.state)||n.numPeers>0?Ym.delete(t):Ym.has(t)||Ym.set(t,e)}for(let{handle:t,reason:n}of Y.due(e))n===`stalled`&&W.pauseTorrent(t),uh(t);if(e-yh>=2e3){yh=e;for(let e of G)W.peers(e)}if(bh=ic(G.map(e=>W.lastPeers(e))),e-Sh>=1e3&&(Sh=e,xh=W.dhtNodes()),$.size&&e-vh>=gh){vh=e;for(let e of $.keys())W.trackers(e)}Dh();for(let t of G){let n=W.status(t);if(!n||n.state!==4&&n.state!==5||Om.get(t)===n.paused||og.has(t))continue;let r=Jm.get(t);if(r&&e<r.at)continue;let i=n.paused;sg(t).then(e=>{if(e){Om.set(t,i),Jm.delete(t);return}let n=(Jm.get(t)?.tries??0)+1;Jm.set(t,{tries:n,at:Date.now()+Math.min(1e3*2**n,6e4)})})}},500),setInterval(()=>{if(!W)return;for(let e of G){let t=W.status(e);t&&t.state===3&&sg(e)}let e=!1;for(let t of G){let n=W.status(t),r=K.get(t),i=Bh.get(t);if(!n||!r||!i)continue;e=!0;let a=uc(Vh.get(t),i,n);if(!mc(Vh.get(t),a))continue;Vh.set(t,a),Bh.set(t,{activeSeconds:n.activeSeconds,seedingSeconds:n.seedingSeconds});let o=Wh(n),s=fc(Uh.get(t),Hh.get(t)??o,o);Uh.set(t,s),Hh.set(t,o),Z(r,{activeSeconds:a.activeSeconds,seedingSeconds:a.seedingSeconds,downloaded:s.downloaded,uploaded:s.uploaded,wasted:s.wasted},!0).catch(()=>{})}e&&Date.now()-zh>=3e5&&(zh=Date.now(),th().then(e=>X({type:`list`,list:e})).catch(()=>{}))},15e3),setInterval(()=>{O_()},1e4),O_(),setTimeout(()=>{T_(),setInterval(()=>{T_()},6e5)},6e4),self.addEventListener(`online`,()=>Y.retryNow(Date.now()))},N_=e=>cl(e.savePath)&&e.saveTo!==`source`,P_=e=>al(e.savePath)?e.saveTo??`folder`:e.saveTo,F_=async(e,t)=>{let n=new Map((await th()).map(e=>[e.infoHash,e])),r=/* @__PURE__ */ new Map;for(let i of t){let t=typeof i==`string`?n.get(i):void 0;if(!t)continue;if(t.saveTo===`source`){X({type:`add-failed`,message:U.formatMessage({id:`Nothing to download this from. Create it again from the same files.`,defaultMessage:`Nothing to download this from. Create it again from the same files.`})});continue}let a=N_(t)?Vc(t.infoHash):t.savePath||`/dl`,o=await Po(el(t.infoHash));if(t.private===!0&&!o?.byteLength){X({type:`add-failed`,message:U.formatMessage({id:`This private torrent needs its .torrent file. Add it again.`,defaultMessage:`This private torrent needs its .torrent file. Add it again.`})});continue}let s=o&&o.byteLength?e.addTorrentFile(o,a):Zm(e,t.magnet,a);if(Xm(s)){X({type:`add-failed`,message:U.formatMessage({id:`That torrent could not be read`,defaultMessage:`That torrent could not be read`})});continue}kh(s,t.magnet,t.infoHash,a,!1),qh(s,{down:t.downloadLimit,up:t.uploadLimit}),Y.hold(s,Date.now()),r.set(t.infoHash,{savePath:a,saveTo:P_(t),started:!0,paused:!1,resumed:!1,forced:!1,seedStopped:!1,seedBypass:!1,ephemeral:!1,lastUsedAt:Date.now()})}r.size&&(Dh(),await rh(r))},I_=(e,t,n=!1)=>X(typeof e.addId==`string`?{...t,addId:e.addId,...n&&{already:n}}:t),L_=async(e,t,n)=>{Q.delete(e),Vm(e,`seed-policy`),J(e,`seedBypass`,!1),n?.paused?(Bm(e,`user`),Km(e),W?.pauseTorrent(e)):jh(e),Bg(e).length&&$g(e),await Z(t,{ephemeral:!1,seedStopped:!1,seedBypass:!1,lastUsedAt:Date.now(),...n?.patch})},R_=async(e,t)=>{try{if(t.type===`add-magnet`){let n=hs(t.magnet),r=n?[...K].find(([,e])=>_s(e,n)):void 0;if(r){let[e,n]=r,i=!Q.has(e);t.ephemeral?ih(e):await L_(e,n),I_(t,{type:`added`,handle:e,magnet:Dm.get(e)||t.magnet},i)}else{let r=n?(await th()).find(e=>_s(e.infoHash,n)):void 0,i=r?.infoHash??n,a=r&&r.infoHash!==n?r.magnet:t.magnet,o=Gc(r,t.ephemeral===!0),s=!!r&&N_(r),c=t.savePath||!s&&r?.savePath||(o&&i?Hc(i):Vc(i)),l;if(r?.private===!0){let n=i?await Po(el(i)).catch(()=>void 0):void 0;if(!n?.byteLength){I_(t,{type:`add-failed`,message:U.formatMessage({id:`This private torrent needs its .torrent file. Add it again.`,defaultMessage:`This private torrent needs its .torrent file. Add it again.`})});return}if(l=e.addTorrentFile(n,c),Xm(l)){I_(t,{type:`add-failed`,message:U.formatMessage({id:`That torrent could not be read`,defaultMessage:`That torrent could not be read`})});return}}else if(l=Zm(e,a,c),Xm(l)){I_(t,{type:`add-failed`,message:U.formatMessage({id:`That is not a valid magnet link`,defaultMessage:`That is not a valid magnet link`})});return}kh(l,a,i,c,o),Ih.set(l,{wanted:r?.wantedFiles,firstLast:r?.firstLast}),t.hold===!0&&(Mh.add(l),o&&(Nh.add(l),e.setFlags(l,V.uploadMode,V.uploadMode))),qh(l,{down:r?.downloadLimit,up:r?.uploadLimit}),Vh.set(l,{activeSeconds:r?.activeSeconds??0,seedingSeconds:r?.seedingSeconds??0}),Uh.set(l,Gh(r)),Y.hold(l,Date.now());let u=Date.now();i&&await nh({infoHash:i,magnet:a,savePath:c,addedAt:u,lastUsedAt:u,ephemeral:o,started:!0,paused:!1},s?{savePath:c,saveTo:P_(r)}:void 0),I_(t,{type:`added`,handle:l,magnet:a}),Dh(),O_()}}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){X({type:`add-failed`,message:U.formatMessage({id:`That torrent could not be created`,defaultMessage:`That torrent could not be created`})});return}if(!r.some(e=>e)){X({type:`add-failed`,message:U.formatMessage({id:`Some of those files could not be opened`,defaultMessage:`Some of those files could not be opened`})});return}await Fo(el(n),i);let a=y_(e,{infoHash:n,magnet:t.magnet,bytes:i,handles:r,paused:!1});if(a===null){await Lo(el(n)).catch(()=>{}),X({type:`add-failed`,message:U.formatMessage({id:`The engine refused the torrent that was just built`,defaultMessage:`The engine refused the torrent that was just built`})});return}let o=Date.now();await nh({infoHash:n,magnet:t.magnet,savePath:ol(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,...qc({name:t.name,size:t.size,files:t.files}),...bl(i)||e.isPrivate?.(a)===!0?{private:!0}:{}}),X({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)){X({type:`add-failed`,message:U.formatMessage({id:`Some of those files could not be opened`,defaultMessage:`Some of those files could not be opened`})});return}let i=[...K.entries()].find(([,e])=>e===n);if(i){X({type:`added`,handle:i[0],magnet:Dm.get(i[0])??``});return}let a=await Po(el(n));if(!a?.byteLength){X({type:`add-failed`,message:U.formatMessage({id:`The torrent this was built from is no longer stored`,defaultMessage:`The torrent this was built from is no longer stored`})});return}let o=(await th()).find(e=>e.infoHash===n),s=await Po(hm(n)).catch(()=>void 0),c=y_(e,{infoHash:n,magnet:o?.magnet??t.magnet??``,bytes:a,handles:r,paused:o?.paused===!0,seedStopped:o?.seedStopped===!0,ephemeral:o?.ephemeral===!0});if(c===null){X({type:`add-failed`,message:U.formatMessage({id:`The engine refused that torrent`,defaultMessage:`The engine refused that torrent`})});return}s?.length&&e.addTrackers(c,s),Ih.set(c,{wanted:o?.wantedFiles,firstLast:o?.firstLast}),Mh.add(c),o?.forced&&!o.paused&&(J(c,`forced`,!0),uh(c)),o?.seedBypass&&!o.paused&&!o.seedStopped&&J(c,`seedBypass`,!0),Vh.set(c,{activeSeconds:o?.activeSeconds??0,seedingSeconds:o?.seedingSeconds??0}),Uh.set(c,Gh(o)),await Z(n,{started:!0,lastUsedAt:Date.now()}),X({type:`added`,handle:c,magnet:o?.magnet??``})}else if(t.type===`add-torrent-file`){let n=t.savePath||`/dl`,r=t.bytes,i=e.addTorrentFile(r,n);if(Xm(i)){I_(t,{type:`add-failed`,message:U.formatMessage({id:`That file is not a valid .torrent`,defaultMessage:`That file is not a valid .torrent`})});return}if(G.includes(i)){let n=!t.ephemeral&&Q.has(i)?K.get(i):void 0;if(n){let a=Array.isArray(t.wanted)?t.wanted.map(e=>Number(e)|0):void 0,o=t.firstLast===!0,s=t.saveTo===`browser`||t.saveTo===`folder`?{saveTo:t.saveTo}:{};await Fo(el(n),r),(a||o)&&(Ih.set(i,{wanted:a,firstLast:o}),Bg(i).length||(e.files(i)?zg(i):Mh.add(i))),t.sequential===!0&&e.setFlags(i,V.sequentialDownload,V.sequentialDownload),t.top===!0&&e.moveInQueue(i,`top`),await L_(i,n,{paused:t.paused===!0,patch:{...a?{wantedFiles:a}:{},...o?{firstLast:!0}:{},...t.paused===!0?{paused:!0}:{},...bl(r)||e.isPrivate?.(i)===!0?{private:!0}:{},...s}})}else t.ephemeral&&Q.has(i)&&ih(i);I_(t,{type:`added`,handle:i,magnet:Dm.get(i)??``},!n),!n&&!t.ephemeral&&typeof t.addId!=`string`&&X({type:`add-failed`,message:U.formatMessage({id:`Already in your list`,defaultMessage:`Already in your list`})});return}kh(i,``,null,n,t.ephemeral===!0);let a=Array.isArray(t.wanted)?t.wanted.map(e=>Number(e)|0):void 0,o=t.firstLast===!0;(a||o||t.paused===!0)&&(Ih.set(i,{wanted:a,firstLast:o}),Mh.add(i),Nh.add(i),e.setFlags(i,V.uploadMode,V.uploadMode)),t.sequential===!0&&e.setFlags(i,V.sequentialDownload,V.sequentialDownload),t.paused===!0&&(Bm(i,`user`),Km(i)),t.top===!0&&e.moveInQueue(i,`top`),Y.hold(i,Date.now());let s=null;for(let t=0;t<40&&!(s=e.infohash(i));t++)await new Promise(e=>setTimeout(e,250));let c=(await th()).find(e=>e.infoHash===s);if(!G.includes(i))return;if(!s){e.removeTorrent(i,!0),Ah(i),I_(t,{type:`add-failed`,message:U.formatMessage({id:`Could not read that torrent`,defaultMessage:`Could not read that torrent`})});return}let l=e.infohashV2(i),u=`magnet:?`+[...s.length===40?[`xt=urn:btih:${s}`]:[],...l?[`xt=urn:btmh:1220${l}`]:[]].join(`&`);kh(i,u,s,n,Gc(c,t.ephemeral===!0)),await Fo(el(s),r);let d=Date.now(),f=t.saveTo===`browser`||t.saveTo===`folder`?{saveTo:t.saveTo}:{};await nh({infoHash:s,magnet:u,savePath:n,addedAt:d,lastUsedAt:d,ephemeral:t.ephemeral===!0,started:!0,paused:Mm(i),wantedFiles:a,firstLast:o||void 0,...f,...t.created===!0?{created:!0}:{},...bl(r)||e.isPrivate?.(i)===!0?{private:!0}:{}},c&&N_(c)?{savePath:n,saveTo:P_(c),...f}:void 0),C_.delete(s),I_(t,{type:`added`,handle:i,magnet:u})}else if(t.type===`read`){if(!G.includes(t.handle)){X({type:`read-error`,id:t.id,error:Qh});return}if(t.prioritize!==!1&&!r_(t.handle,t.fileIndex,t.offset,t.len)&&(Nm(t.handle)&&fh.add(t.handle),jh(t.handle),Vm(t.handle,`seed-policy`)&&Zg(t.handle)),t.viewer||dh.set(t.handle,Date.now()),Mm(t.handle)&&!r_(t.handle,t.fileIndex,t.offset,t.len)){X({type:`read-error`,id:t.id,error:$h});return}if(t.prioritize!==!1)c_(t.viewer,t.handle,t.fileIndex,t.offset,t.len);else if(!r_(t.handle,t.fileIndex,t.offset,t.len)){X({type:`read-error`,id:t.id,error:`not downloaded`});return}let n=eg.get(t.handle);n||eg.set(t.handle,n=/* @__PURE__ */ new Map),n.set(t.id,{fileIndex:t.fileIndex,offset:t.offset,len:t.len,viewer:t.viewer}),j_();try{let r=0;for(let i=0;;i++)try{let r=t.viewer?$.get(t.handle)?.get(t.viewer)?.bulk===!0:!1,i=t.partial?i_(t.handle,t.fileIndex,t.offset,t.len):t.len,a=await e.read(t.handle,t.fileIndex,t.offset,i,{timeoutMs:Xh,...r?{deadlineMs:null}:{}});if(!n.has(t.id))return;X({type:`read-result`,id:t.id,data:a},[a.buffer]);return}catch(a){if(!n.has(t.id))return;if(!/did not arrive/.test(String(a))||t.viewer&&!$.get(t.handle)?.has(t.viewer))throw a;if(Zh(e)&&r<20)r++;else if(i+1-r>=18)throw a;let o=a_(t.handle,t.fileIndex,t.offset,t.len);X({type:`read-stalled`,id:t.id,handle:t.handle,fileIndex:t.fileIndex,offset:t.offset,len:t.len,waitedMs:(i+1)*Xh,missing:o,cancelled:Math.min(o.length,16),downloadRate:e.status(t.handle)?.downloadRate??null,numPeers:e.status(t.handle)?.numPeers??null});for(let n of o.slice(0,16))e.cancelPieceRequests(t.handle,n);let s=t.viewer?$.get(t.handle)?.get(t.viewer):void 0;t.prioritize!==!1&&t.viewer&&s&&!s.held&&$g(t.handle)}}finally{n.delete(t.id),!t.viewer&&G.includes(t.handle)&&dh.set(t.handle,Date.now())}}else if(t.type===`cancel-read`){let e=eg.get(t.handle);e&&(e.delete(t.id),e.size||eg.delete(t.handle))}else if(t.type===`remove`){let n=K.get(t.handle);rg(t.handle,Qh),e.removeTorrent(t.handle,!!t.deleteFiles),Ah(t.handle),n&&await oh(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;Ih.set(t.handle,{wanted:e,firstLast:n}),Bg(t.handle).length||zg(t.handle);let r=K.get(t.handle);r&&await Z(r,{wantedFiles:e,firstLast:n})}else if(t.type===`set-folder`)wm=t.folder??null;else if(t.type===`set-temporary`){if(typeof t.infoHash==`string`){let e=t.temporary===!0,n=G.find(e=>K.get(e)===t.infoHash);n!==void 0&&(e?(Q.add(n),J(n,`seedBypass`,!1)):(Q.delete(n),jh(n)),Bg(n).length&&$g(n)),await Z(t.infoHash,{ephemeral:e,...e?{seedBypass:!1}:{}})}}else if(t.type===`export-start`){let n=G.find(e=>K.get(e)===t.infoHash),r=n===void 0?void 0:q.get(n),i=n===void 0?null:e.files(n);if(n===void 0||!i||r===void 0||!Uc(r)||Nh.has(n)){X({type:`answer`,id:t.id,value:null});return}Ag.set(n,{running:(Ag.get(n)?.running??0)+1,until:Date.now()+kg});let a=await e.saveResumeData(n),o=i.files.flatMap((e,t)=>e.pad?[]:Cm.chunksOf(r,t).map(e=>({fileIndex:t,chunk:e})));X({type:`answer`,id:t.id,value:{magnet:Dm.get(n)??``,resume:a,chunkBytes:Cm.chunkBytesOf(r),chunks:o}})}else if(t.type===`export-chunk`){let e=G.find(e=>K.get(e)===t.infoHash),n=e===void 0?void 0:q.get(e),r=e===void 0?void 0:Ag.get(e);if(!r||n===void 0)throw Error(`that torrent is not being handed over`);r.until=Date.now()+kg;let i=await Cm.readChunk(n,t.fileIndex,t.chunk);X({type:`answer`,id:t.id,value:i},[i.buffer])}else if(t.type===`export-end`){let e=G.find(e=>K.get(e)===t.infoHash),n=e===void 0?void 0:Ag.get(e);if(e===void 0||!n)return;--n.running,n.running||Ag.delete(e)}else if(t.type===`import-start`){if(typeof t.infoHash!=`string`||typeof t.magnet!=`string`)throw Error(`nothing to list`);let e=Date.now();await nh({infoHash:t.infoHash,magnet:t.magnet,savePath:Hc(t.infoHash),addedAt:e,lastUsedAt:e,ephemeral:!1,started:!0,paused:!1}),X({type:`answer`,id:t.id,value:!0})}else if(t.type===`import`){let n=t.infoHash;if(typeof n!=`string`||!(t.resume instanceof Uint8Array)||G.some(e=>K.get(e)===n))return;let r=Hc(n);await Fo($c(n),t.resume);let i=e.addTorrentWithResume(t.resume,r);if(Xm(i)){X({type:`add-failed`,message:U.formatMessage({id:`That torrent could not be read`,defaultMessage:`That torrent could not be read`})});return}kh(i,t.magnet,n,r),Mh.add(i),qh(i,{down:0}),qm(i),Y.hold(i,Date.now()),X({type:`added`,handle:i,magnet:t.magnet})}else if(t.type===`reserve-storage`)typeof t.infoHash==`string`&&t.infoHash&&(t.on===!1?C_.delete(t.infoHash):C_.add(t.infoHash));else if(t.type===`set-location`)typeof t.infoHash==`string`&&await Z(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?G.find(e=>K.get(e)===n):void 0;n&&i!==void 0&&await v_(e,i,n,r)}else if(t.type===`import-list`){let n=[];await Io(Yc,e=>n=Xc(e,t.removed));let r=[],i=[],a=!1,o=[];await Io(Jc,e=>{o.length=0;let s=Qc(e??[],Array.isArray(t.list)?t.list:[],n);r=s.list,i=(e??[]).filter(e=>!r.includes(e)),a=i.length>0;let c=new Map(r.map(e=>[e.infoHash,e]));for(let e of s.incoming){if(!e||typeof e.infoHash!=`string`||!e.magnet)continue;let t=qc(e),n=c.get(e.infoHash);if(n){n.name===void 0&&t.name!==void 0&&(n.name=t.name,a=!0),n.size===void 0&&t.size!==void 0&&(n.size=t.size,a=!0),n.files===void 0&&t.files!==void 0&&(n.files=t.files,a=!0),e.private===!0&&n.private!==!0&&(n.private=!0,o.push(n.infoHash),a=!0);let r=pc(Gh(n),Gh(e));for(let e of oc)(n[e]??0)!==r[e]&&(n[e]=r[e],a=!0);continue}let i={infoHash:e.infoHash,magnet:e.magnet,savePath:e.savePath||`/dl`,addedAt:e.addedAt||Date.now(),started:!1,ephemeral:!1,...t,...Gh(e),...e.private===!0?{private:!0}:{}};r.push(i),c.set(i.infoHash,i),a=!0}return r});for(let e of i)await ah(e.infoHash);let s=/* @__PURE__ */ new Map;for(let t of o){let n=G.find(e=>K.get(e)===t);n!==void 0&&e.isPrivate?.(n)!==!0&&(rg(n,$h),e.removeTorrent(n,!1),Ah(n),s.set(t,{started:!1}))}s.size&&(await rh(s,!0),r=await th(),a=!0),a&&X({type:`list`,list:r,synced:!0})}else if(t.type===`start`||t.type===`start-many`)await F_(e,t.type===`start`?[t.infoHash]:Array.isArray(t.infoHashes)?t.infoHashes:[]);else if(t.type===`remove-missing`){if(typeof t.infoHash==`string`){let n=G.find(e=>K.get(e)===t.infoHash);n!==void 0&&(rg(n,Qh),e.removeTorrent(n,!0),Ah(n)),await oh(t.infoHash)}}else if(t.type===`clear-list`){for(let t of[...G])rg(t,Qh),e.removeTorrent(t,!0),Ah(t);let t=[];await Io(Jc,e=>(t=e??[],[])),await Lo(Yc).catch(()=>{});for(let e of t)await Lo($c(e.infoHash)).catch(()=>{}),await Lo(el(e.infoHash)).catch(()=>{}),await Lo(hm(e.infoHash)).catch(()=>{});X({type:`list`,list:[],synced:!0})}else if(t.type===`pause`){Bm(t.handle,`user`),J(t.handle,`userStarted`,!1),J(t.handle,`forced`,!1),J(t.handle,`seedBypass`,!1),Y.forget(t.handle),e.pauseTorrent(t.handle),rg(t.handle,$h),sg(t.handle);let n=K.get(t.handle);n&&await Z(n,{paused:!0,resumed:!1,forced:!1,seedStopped:!1,seedBypass:!1})}else if(t.type===`resume`||t.type===`force-start`){let n=Pm(t.handle);Vm(t.handle);let r=Q.has(t.handle);r&&J(t.handle,`userStarted`,!0),(n||sh.has(e.status(t.handle)?.state??-1))&&J(t.handle,`seedBypass`,!0);let i=t.type===`force-start`;J(t.handle,`forced`,i),qm(t.handle),Y.forget(t.handle),uh(t.handle),Y.hold(t.handle,Date.now());let a=K.get(t.handle);a&&await Z(a,{paused:!1,resumed:r,forced:i,seedStopped:!1,seedBypass:zm(t.handle)})}else if(t.type===`recheck`){let n=K.get(t.handle);n&&await Lo($c(n)).catch(()=>{}),Om.delete(t.handle),rg(t.handle,U.formatMessage({id:`torrent rechecking`,defaultMessage:`torrent rechecking`})),Vm(t.handle),Wm.delete(t.handle),Gm.delete(t.handle),fh.delete(t.handle),J(t.handle,`seedBypass`,!1),Y.forget(t.handle),e.forceRecheck(t.handle),lh(t.handle)&&e.setFlags(t.handle,0,V.autoManaged),Y.hold(t.handle,Date.now()),n&&await Z(n,{paused:!1,seedStopped:!1,seedBypass:!1})}else if(t.type===`retry-now`)Y.retryNow(Date.now());else if(t.type===`retry`)Y.retry(t.handle,Date.now());else if(t.type===`flush-resume`)await Promise.all(G.map(async e=>{await og.get(e),await sg(e)})),t.id!==void 0&&X({type:`answer`,id:t.id});else if(t.type===`watch`)t.readLen==null?t_(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.held===!0,t.bulk===!0||void 0,t.prepare===!0):c_(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.readLen),j_();else if(t.type===`unwatch`)n_(e=>e===t.viewer);else if(t.type===`set-flags`)e.setFlags(t.handle,t.flags>>>0,t.mask>>>0),sg(t.handle);else if(t.type===`reannounce`)e.forceReannounce(t.handle);else if(t.type===`add-trackers`){let n=e.addTrackers(t.handle,t.urls);hh=0;let r=K.get(t.handle),i=t.urls.filter(e=>!n.includes(e));r&&i.length&&sl(q.get(t.handle))&&await Io(hm(r),e=>[.../* @__PURE__ */ new Set([...e??[],...i])]).catch(()=>{}),(async()=>{await og.get(t.handle),await sg(t.handle)})(),X({type:`answer`,id:t.id,value:n})}else if(t.type===`queue-move`)e.moveInQueue(t.handle,t.where);else if(t.type===`set-limits`){let e=Ml(t.down)?t.down:void 0,n=Ml(t.up)?t.up:void 0;qh(t.handle,{down:e,up:n});let r=K.get(t.handle);if(r){let t={};e!==void 0&&(t.downloadLimit=e),n!==void 0&&(t.uploadLimit=n),Object.keys(t).length&&await Z(r,t)}}else if(t.type===`set-session-limits`){let n={down:Ml(t.down)?t.down:Lh.down,up:Ml(t.up)?t.up:Lh.up};await Fo(jl,{...n}).catch(()=>{}),Lh=n,e.setRateLimits({download:n.down,upload:n.up}),Dh()}else if(t.type===`set-seeding-policy`){let e=Bl(t.policy);if(!Vl(ch,e)){Hm();let e=new Map((await th()).filter(e=>e.seedBypass).map(e=>[e.infoHash,{seedBypass:!1}]));e.size&&await rh(e,!0).catch(()=>{})}ch=e,await Fo(Pl,ch).catch(()=>{}),Qg()}else if(t.type===`inspect`){let e=typeof t.handle==`number`?t.handle:null;e!==mh&&(mh=e,hh=0)}else if(t.type===`torrent-detail`){if(typeof t.handle!=`number`||!G.includes(t.handle))X({type:`answer`,id:t.id,value:null});else{let[n,r]=await Promise.all([e.peers(t.handle),e.trackers(t.handle)]);if(!G.includes(t.handle))X({type:`answer`,id:t.id,value:null});else{let e=[..._m?r:r.map(Eh),...vm?.trackers(t.handle)??[]];X({type:`answer`,id:t.id,value:{peers:n,trackers:e}})}}}else t.type===`unwatch-owner`&&n_(e=>e.startsWith(t.owner+`:`))}catch(e){t.type===`read`?X({type:`read-error`,id:t.id,error:String(e?.stack??e)}):typeof t.addId==`string`?I_(t,{type:`add-failed`,message:String(e?.message??e)}):Bc.has(t.type)&&t.type!==`start-many`?X({type:`answer`,id:t.id,error:String(e?.message??e)}):X({type:`error`,message:String(e?.stack??e)})}},z_=/* @__PURE__ */ new Set([`read`,`cancel-read`,`add-torrent-file`,`export-chunk`,`torrent-detail`]);let B_=Promise.resolve();self.addEventListener(`message`,e=>{let t=e.data;if(!t||typeof t!=`object`||typeof t.type!=`string`||!pm.has(t.type))return;if(t.type===`close-sockets`){A_=!0,vm?.close(),Promise.resolve(_m?.close()).then(()=>X({type:`answer`,id:t.id}));return}let n=W;if(!n){t.type===`read`?X({type:`read-error`,id:t.id,error:`the engine is still starting`}):Bc.has(t.type)?X({type:`answer`,id:t.id,error:`worker not initialized`}):X({type:`error`,message:`worker not initialized`});return}if(z_.has(t.type)){R_(n,t);return}t.type===`start-many`&&X({type:`answer`,id:t.id,value:!0}),B_=B_.then(()=>R_(n,t))}),M_().catch(e=>X({type:Em?`error`:`fatal`,message:String(e?.stack??e)}));
|
|
27
|
+
`./webrtc.wasm`,import.meta.url)),bf()]),u={text:``},d={wasi_snapshot_preview1:qf(()=>f.memory.buffer,e=>{u.text=(u.text+e).slice(-2048)})},f=(await WebAssembly.instantiate(s,d)).exports;f._initialize();let p=new Hf(f,t,o,r,i,a,c,l,u),m=p.create();if(!m)throw p.close(),TypeError(`${n}:${r} cannot be a host candidate`);return f.rtc_delete(m),{RTCPeerConnection:Kf.bind(null,p),get droppedDatagrams(){return p.dropped},close:()=>p.close()}}var Xf=262144,Zf=16384,Qf=5e3,$f=class{sink;backpressure=!0;listeners=/* @__PURE__ */ new Map;held=[];heldBytes=0;ended=!1;heard=!1;openedAt=Date.now();destroyedAfter=null;constructor(e){this.sink=e}on(e,t){let n=this.listeners.get(e);if(n?n.push(t):this.listeners.set(e,[t]),e===`data`&&this.held){let e=this.held;this.held=null;for(let n of e)t(n)}if(this.ended&&(e===`end`||e===`close`)&&queueMicrotask(t),this.ended instanceof Error&&e===`error`){let e=this.ended;queueMicrotask(()=>t(e))}return this}listenerCount(e){return this.listeners.get(e)?.length??0}get silent(){return this.ended===!1||this.heard?!1:this.destroyedAfter===null||this.listenerCount(`data`)>0&&this.destroyedAfter>=Qf}write(e){return this.ended?!0:this.sink.write(e)}destroy(){this.ended||(this.ended=!0,this.destroyedAfter=Date.now()-this.openedAt,this.held=null,this.sink.close())}push(e){if(!this.ended){if(this.heard=!0,!this.held)return this.emit(`data`,e);if(this.heldBytes+=e.length,this.heldBytes>1048576){this.end(/* @__PURE__ */ Error(`${this.heldBytes} bytes arrived before anything read the stream`)),this.sink.close();return}this.held.push(e)}}drained(){this.ended||this.emit(`drain`)}end(e){this.ended||(this.ended=e??!0,e&&this.emit(`error`,e),this.emit(`end`),this.emit(`close`))}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}},ep=3e3,tp=class extends Error{},np=({reflexive:e,complete:t})=>new Promise(n=>{let r,i=!1,a=()=>{i=!0,clearTimeout(o),clearTimeout(r),n()},o=setTimeout(a,ep);t.then(a),e.then(()=>{i||(r??=setTimeout(a,300))})}),rp=({RTCPeerConnection:e,iceServers:t=[]})=>{let n=/* @__PURE__ */ new WeakMap,r=async(r,i)=>{let a;try{a=new e({iceServers:t})}catch(e){throw new tp(`no connection could be made`,{cause:e})}let o=null,s=null,c=!1,l=[],u=0,d=!1,f=Zf,p=0,m=0,h=()=>{if(p)return;let e=()=>{try{a.close()}catch{}};Date.now()-m>5?e():setTimeout(e,5)},g=async e=>{p++;try{return await e}finally{p--,m=Date.now(),c&&h()}},_=()=>{if(c=!0,l=[],a.onicecandidate=a.onicegatheringstatechange=a.onconnectionstatechange=a.ondatachannel=null,o){o.onopen=o.onmessage=o.onclose=o.onerror=o.onbufferedamountlow=null;try{o.close()}catch{}}h()},v=e=>{c||(_(),s?.end(e),S.onclose?.())},y=()=>{try{for(;l.length&&o.bufferedAmount<1048576;){let e=l[0],t=e.subarray(u,u+f);o.send(t),u+=t.length,u>=e.length&&(l.shift(),u=0)}}catch(e){v(Error(`the data channel refused a message`,{cause:e}))}},b=()=>{if(s||c)return;let e=a.sctp?.maxMessageSize??0;e>0&&e<16384&&(f=e),s=new $f({write:e=>(l.push(e),y(),!l.length||(d=!0,!1)),close:()=>v()}),S.onopen?.(s)},x=e=>{o=e,e.binaryType=`arraybuffer`,e.bufferedAmountLowThreshold=Xf,e.onopen=b,e.onmessage=({data:e})=>{b(),e instanceof ArrayBuffer?s?.push(new Uint8Array(e)):ArrayBuffer.isView(e)?s?.push(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):v(/* @__PURE__ */ Error(`a message that is not bytes`))},e.onclose=()=>v(),e.onerror=()=>v(/* @__PURE__ */ Error(`the data channel failed`)),e.onbufferedamountlow=()=>{y(),d&&!l.length&&(d=!1,s?.drained())},e.readyState===`open`&&b()},S={onopen:null,onclose:null,accept:async e=>{if(c)throw Error(`the link is closed`);try{await g(a.setRemoteDescription({type:`answer`,sdp:e}))}catch(e){throw v(),e}},close:()=>{c||(_(),s?.end())}};n.set(S,a);let C,w,T={reflexive:new Promise(e=>{C=e}),complete:new Promise(e=>{w=e})};a.onicecandidate=({candidate:e})=>{e?.candidate?/ typ srflx\b/.test(e.candidate)&&C():w()},a.onicegatheringstatechange=()=>{a.iceGatheringState===`complete`&&w()},a.onconnectionstatechange=()=>{a.connectionState===`failed`&&v()};try{await i(a,x,g),a.iceGatheringState===`complete`&&w(),await r(T);let e=a.localDescription?.sdp;if(c||!e)throw Error(`the connection closed before it had a description`);return{sdp:e,link:S}}catch(e){throw S.close(),e}};return{offer:(e=np)=>r(e,async(e,t,n)=>{t(e.createDataChannel(`webtorrent`)),await n(e.setLocalDescription(await n(e.createOffer())))}),answer:(e,t=np)=>r(t,async(t,n,r)=>{t.ondatachannel=({channel:e})=>n(e),await r(t.setRemoteDescription({type:`offer`,sdp:e})),await r(t.setLocalDescription(await r(t.createAnswer())))}),remoteAddress:e=>n.get(e)?.sctp?.transport.iceTransport.getSelectedCandidatePair()?.remote.address||void 0}},ip=e=>new Uint8Array(e).buffer,ap=e=>{let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=0,i=(t,n=[])=>e.postMessage(t,n),a=e=>new Promise((n,a)=>{let o=r++,s,c,l={reflexive:new Promise(e=>{s=e}),complete:new Promise(e=>{c=e})};t.set(o,{resolve:n,reject:a,reflexive:s,complete:c}),i(e(o)),np(l).then(()=>{t.has(o)&&i({t:`flush`,id:o})})}),o=(e,t)=>{let r=n.get(e);r&&(n.delete(e),r.stream?.end(),t&&r.link.onclose?.())},s=e=>{let t={onopen:null,onclose:null,accept:async t=>i({t:`accept`,id:e,sdp:t}),close:()=>{i({t:`close`,id:e}),o(e,!1)}};return n.set(e,{link:t,unsent:0,waiting:!1}),t};return e.onmessage=({data:e})=>{let{id:r}=e,a=t.get(r);if(e.t===`candidate`)return e.last?a?.complete():a?.reflexive();if(e.t===`sdp`||e.t===`failed`){t.delete(r),a?.complete(),e.t===`sdp`?a?.resolve({sdp:e.sdp,link:s(r)}):a?.reject(e.full?new tp(e.reason):Error(e.reason));return}let c=n.get(r);c&&(e.t===`open`?(c.stream=new $f({write:e=>{for(let t=0;t<e.length;t+=Zf){let n=ip(e.subarray(t,t+Zf));i({t:`data`,id:r,bytes:n},[n])}return c.unsent+=e.length,c.unsent<1048576||(c.waiting=!0,!1)},close:()=>{i({t:`close`,id:r}),o(r,!0)}}),c.link.onopen?.(c.stream)):e.t===`data`?(i({t:`ack`,id:r,bytes:e.bytes.byteLength}),c.stream?.push(new Uint8Array(e.bytes))):e.t===`ack`?(c.unsent-=e.bytes,c.waiting&&c.unsent<=262144&&(c.waiting=!1,c.stream?.drained())):e.t===`closed`&&o(r,!0))},{offer:()=>a(e=>({t:`offer`,id:e})),answer:e=>a(t=>({t:`answer`,id:t,sdp:e})),remoteAddress:()=>void 0}},op=1e4,sp=6e5,cp=131072,lp=65536,up=64,dp=200,fp=`-RP0001-`,pp=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`,mp=e=>{let t=``;for(let n of crypto.getRandomValues(new Uint8Array(e)))t+=pp[n%62];return t},hp=()=>mp(20),gp=()=>fp+mp(12),_p=e=>{let t=``;for(let n=0;n<40;n+=2)t+=String.fromCharCode(parseInt(e.slice(n,n+2),16));return t},vp=e=>e===void 0||typeof e==`number`&&Number.isFinite(e)&&e>=0,yp=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,bp=class{url;WebSocket;dropped=0;onopen=null;onclose=null;onreply=null;onfailure=null;onoffer=null;onanswer=null;socket=null;listed=/* @__PURE__ */ new Map;retry;losses=0;constructor(e,t){this.url=e,this.WebSocket=t,this.connect()}get connected(){return this.socket?.readyState===1}announce({infoHash:e,peerId:t,uploaded:n,downloaded:r,left:i,event:a,offers:o}){let s=this.send({action:`announce`,info_hash:e,peer_id:t,uploaded:yp(n),downloaded:yp(r),left:yp(i),numwant:o.length,event:a,offers:o.map(({offerId:e,sdp:t})=>({offer_id:e,offer:{type:`offer`,sdp:t}}))});return s&&this.listed.set(e,a!==`stopped`),s}answer({infoHash:e,peerId:t,toPeerId:n,offerId:r,sdp:i}){return this.send({action:`announce`,info_hash:e,peer_id:t,to_peer_id:n,offer_id:r,answer:{type:`answer`,sdp:i}})}close(){clearTimeout(this.retry);let e=this.socket;this.socket=null,e&&(e.onopen=e.onmessage=e.onclose=null,e.close())}send(e){return this.connected?(this.socket.send(JSON.stringify(e)),!0):!1}connect(){let e;try{e=new this.WebSocket(this.url)}catch{return}this.socket=e,e.onopen=()=>this.onopen?.(),e.onmessage=({data:e})=>this.read(e),e.onclose=()=>{this.socket=null,this.listed.clear();let e=Math.min(op*2**this.losses++,sp);this.retry=setTimeout(()=>this.connect(),e*(1+Math.random()/4)),this.onclose?.()}}read(e){this.accept(e)||this.dropped++}accept(e){if(typeof e!=`string`||e.length>cp)return!1;let t;try{t=JSON.parse(e)}catch{return!1}if(typeof t!=`object`||!t)return!1;let n=t.info_hash,r=t[`failure reason`];if(r!==void 0)return typeof r!=`string`||n!==void 0&&!this.listed.get(n)?!1:(this.onfailure?.(n??null,r.slice(0,dp)),!0);if(t.action!==`announce`)return!1;let i=this.listed.get(n);if(!i)return i===!1&&this.listed.delete(n);this.losses=0;let{offer:a,answer:o}=t;if(a===void 0&&o===void 0){let{interval:e,complete:r,incomplete:i}=t;return!vp(e)||!vp(r)||!vp(i)?!1:(this.onreply?.({infoHash:n,intervalS:e===void 0?null:Math.min(600,Math.max(60,e)),seeders:r??null,leechers:i??null}),!0)}let s=a??o,{peer_id:c,offer_id:l}=t;if(a!==void 0&&o!==void 0||typeof s!=`object`||!s||typeof s.sdp!=`string`||s.sdp.length>lp||typeof c!=`string`||c.length!==20||typeof l!=`string`||l.length<1||l.length>up)return!1;let u={infoHash:n,peerId:c,offerId:l,sdp:s.sdp};return a?this.onoffer?.(u):this.onanswer?.(u),!0}},xp=[[0,8],[167772160,8],[1681915904,10],[2130706432,8],[2851995648,16],[2886729728,12],[3232235520,16]],Sp=e=>xp.some(([t,n])=>e>>>32-n==t>>>32-n),Cp=e=>{if(e.startsWith(`[`)){let t=e.slice(1,-1),n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);return n?Sp((parseInt(n[1],16)<<16|parseInt(n[2],16))>>>0):t===`::`||t===`::1`||/^fe[89ab][0-9a-f]:/.test(t)||/^f[cd][0-9a-f]{2}:/.test(t)}let t=/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(e);if(t)return Sp((t[1]<<24|t[2]<<16|t[3]<<8|t[4])>>>0);let n=e.replace(/\.$/,``);return!n.includes(`.`)||n.endsWith(`.localhost`)||n.endsWith(`.local`)},wp=e=>{let t;try{t=new URL(e)}catch{return null}return t.protocol!==`ws:`&&t.protocol!==`wss:`||Cp(t.hostname)?null:t.href},Tp=[1,7],Ep=2,Dp=(e,t)=>{let n=e.status(t),r=e.infohash(t);return!n||!r?null:{infoHash:r,trackers:e.webSocketTrackers(t),running:!n.paused&&n.errorCode===0,checking:Tp.includes(n.state),uploadMode:(n.flags&Ep)!==0,hasMetadata:n.hasMetadata,private:e.isPrivate(t),uploaded:n.sessionPayloadUpload,downloaded:n.sessionPayloadDownload,left:n.totalWanted-n.totalWantedDone,watched:e.hasStreamWindow(t)}},Op={torrentPeers:20,sessionPeers:60,connections:80,perMinute:40},kp={watched:0,downloading:10,seeding:20},Ap=10,jp=16384,Mp=1e4,Np=5e4,Pp=3e4,Fp=1e4,Ip=6e4,Lp=65e3,Rp=6e5,zp=200,Bp=1e4,Vp=1e3,Hp=12e4,Up=1e3,Wp=e=>(e.answeredAt??0)<e.sentAt,Gp=e=>e.hasMetadata&&e.left<=0,Kp=e=>e.watched?`watched`:Gp(e)?`seeding`:`downloading`,qp=(e,t,n)=>{let r=e.trackers.map(wp).filter(e=>e!==null);return[...new Set(e.private??n?r:[...r,...t])]},Jp=(e,t)=>e<t,Yp=e=>e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``),Xp=(e,t)=>{for(let n of e.keys()){if(e.size<=t)return;e.delete(n)}},Zp=(e,t)=>{let{links:n,WebSocket:r,relay:i=!1}=t,a={...Op,...t.limits},o=(t.trackers??[]).map(e=>new URL(e).href),s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Map,d=0,f=a.perMinute,p=Date.now(),m=!1,h=0,g=0,_=!1,v=!1,y=()=>{_||v||(_=!0,queueMicrotask(()=>{_=!1,se.onchange?.()}))},b=e=>{let t=0;for(let n of e.conns)n.remote&&t++;return t},x=()=>{let e=0;for(let t of c.values())e+=b(t);return e},S=e=>{if(m||e.view.checking)return 0;let t=Date.now();f=Math.min(a.perMinute,f+(t-p)*a.perMinute/6e4),p=t;let n=kp[Kp(e.view)];return Math.max(0,Math.floor(Math.min(a.torrentPeers-b(e),a.sessionPeers-x()-n,a.connections-d-n,f-n)))},C=(e,t,n,r,i)=>{let a={torrent:e,via:t,ours:n,remote:r,offerId:i,state:`making`,deadline:Date.now()+Mp};return e.conns.add(a),d++,f--,y(),a},w=(e,t,n)=>{let r=n.socket?.silent??!1;e.quiet.set(t,{until:Date.now()+(r?Rp:Ip),silent:r,address:r?n.address:void 0}),Xp(e.quiet,zp),n.state===`open`&&!r&&(e.askAt=Date.now()+Lp)},T=e=>{let t=e.torrent;return t.conns.delete(e)?(d--,t.offers.delete(e.offerId),e.remote&&w(t,e.remote,e),y(),!0):!1},E=e=>{T(e)&&e.link?.close()},D=(e,t)=>{t instanceof tp&&(m=!0,h++),T(e)},O=(e,t)=>e.torrent.conns.has(e)?(e.link=t,t.onopen=t=>void k(e,t),t.onclose=()=>T(e),!0):(t.close(),!1),ee=async t=>{t.lookAt=Date.now()+Bp;for(let{endpoint:n}of await e.peers?.(t.handle).catch(()=>[])??[]){let e=Yp(n);t.ordinary.delete(e),t.ordinary.add(e)}Xp(t.ordinary,Vp)},k=async(t,r)=>{let a=t.torrent;t.socket=r;let o=t.address=i?n.remoteAddress(t.link):void 0;if(o){if(await ee(a),!a.conns.has(t))return;if(a.ordinary.has(o))return E(t);for(let e of a.quiet.values())if(e.address===o)return E(t)}if(!t.remote||!Dp(e,a.handle)?.running)return E(t);try{e.addPeerStream(a.handle,r)}catch{return E(t)}a.conns.has(t)&&(t.state=`open`,t.deadline=Date.now()+Fp,a.lastPeerAt=Date.now(),y())},te=e=>({infoHash:e.hash,peerId:e.peerId,uploaded:e.view.uploaded,downloaded:e.view.downloaded,left:e.view.hasMetadata?e.view.left:jp}),A=async(e,t)=>{let r=C(e,t,!0,null,hp());try{let e=await n.offer();return O(r,e.link)?{conn:r,sdp:e.sdp}:null}catch(e){return D(r,e),null}},ne=async(e,t,n=0)=>{if(Gp(e.view)||!t.tracker.connected)return;let r=(t.seeders??0)+(t.leechers??0)-1,i=Math.min(Ap,S(e),r-e.conns.size+n);if(i<1)return;t.offersDue=!1;let a=(await Promise.all(Array.from({length:i},()=>A(e,t.tracker.url)))).filter(e=>e!==null).filter(({conn:t})=>e.conns.has(t));if(!a.length)return;let o=t.tracker.announce({...te(e),offers:a.map(({conn:e,sdp:t})=>({offerId:e.offerId,sdp:t}))});for(let{conn:t}of a){if(!o){E(t);continue}t.state=`offered`,t.deadline=Date.now()+Np,e.offers.set(t.offerId,t)}},j=async(e,{infoHash:t,peerId:r,offerId:i,sdp:a})=>{let o=l.get(t);if(!o||r===o.peerId||o.quiet.has(r))return;let s=[...o.conns].filter(e=>e.remote===r);if(s.length){if(s.some(e=>e.state===`open`||!e.ours)||Jp(o.peerId,r))return;s.forEach(E)}if(S(o)<1)return;let c=C(o,e.url,!1,r,i);try{let s=await n.answer(a);if(!O(c,s.link))return;if(!e.answer({infoHash:t,peerId:o.peerId,toPeerId:r,offerId:i,sdp:s.sdp}))return E(c);c.state=`answered`,c.deadline=Date.now()+Pp}catch(e){D(c,e)}},M=({infoHash:e,peerId:t,offerId:n,sdp:r})=>{let i=l.get(e),o=i?.offers.get(n);if(!i||!o||o.state!==`offered`||t===i.peerId)return;if(i.quiet.get(t)?.silent)return E(o);let s=[...i.conns].filter(e=>e.remote===t);if(s.some(e=>e.state===`open`||e.ours)||s.length&&!Jp(i.peerId,t)||(s.forEach(E),b(i)>=a.torrentPeers||x()+kp[Kp(i.view)]>=a.sessionPeers))return E(o);o.remote=t,o.state=`answered`,o.deadline=Date.now()+Pp,y(),o.link.accept(r).catch(()=>{})},N=e=>{let t=s.get(e);if(t)return t;let n=new bp(e,r);return s.set(e,n),n.onopen=()=>{for(let t of c.values()){let n=t.announcing.get(e);n&&(n.started=!1,n.nextAt=0)}P(),y()},n.onclose=y,n.onreply=({infoHash:t,intervalS:n,seeders:r,leechers:i})=>{let a=l.get(t),o=a?.announcing.get(e);a&&o&&(n!==null&&(o.intervalMs=n*1e3,o.nextAt=o.sentAt+o.intervalMs),o.seeders=r,o.leechers=i,o.answeredAt=Date.now(),o.failure=null,y(),o.offersDue&&ne(a,o))},n.onfailure=(t,n)=>{for(let r of c.values()){let i=r.announcing.get(e);!i||(t===null?!Wp(i):t!==r.hash)||(i.failure=n,i.answeredAt=Date.now(),y())}},n.onoffer=e=>void j(n,e),n.onanswer=M,n},P=()=>{let e=Date.now();for(let t of c.values())for(let n of t.announcing.values())e<n.nextAt||!n.tracker.connected||(n.tracker.announce({...te(t),event:n.started?void 0:`started`,offers:[]}),m=!1,n.started=!0,n.offersDue=!0,n.sentAt=e,n.nextAt=e+n.intervalMs)},F=(e,t,n)=>{t.tracker.announce({...te(e),event:n,offers:[]})},re=(e,t)=>{for(let[n,r]of e.announcing)if(!t.includes(n)){F(e,r,`stopped`),e.announcing.delete(n);for(let t of e.conns)t.via===n&&t.state!==`open`&&E(t);y()}},I=e=>{for(let t of e.announcing.values())F(e,t,`stopped`);for(let t of e.conns)E(t);c.delete(e.handle),l.delete(e.hash),y()},L=t=>{let n=Dp(e,t),r=c.get(t);if(n||u.delete(t),!n?.running){r&&I(r);return}let a=qp(n,o,i);if(n.checking){r&&(r.view.checking=!0,re(r,a));return}if(r?.view.uploadMode&&!n.uploadMode&&n.hasMetadata&&!Gp(n)&&(I(r),r=void 0),!r){let e=u.get(t)??{quiet:/* @__PURE__ */ new Map,ordinary:/* @__PURE__ */ new Set};u.set(t,e);for(let[t,{silent:n}]of e.quiet)n||e.quiet.delete(t);r={...e,peerId:gp(),handle:t,view:n,hash:_p(n.infoHash),announcing:/* @__PURE__ */ new Map,conns:/* @__PURE__ */ new Set,offers:/* @__PURE__ */ new Map,leeching:!1,completed:!1,lastPeerAt:null,lookAt:0,askAt:0},c.set(t,r),l.set(r.hash,r),y()}for(let e of a)r.announcing.has(e)||(r.announcing.set(e,{tracker:N(e),started:!1,offersDue:!1,sentAt:0,nextAt:0,intervalMs:Hp,seeders:null,leechers:null,answeredAt:null,failure:null}),y());if(re(r,a),r.view=n,n.hasMetadata&&n.left>0&&(r.leeching=!0),r.leeching&&!r.completed&&Gp(n)){r.completed=!0;for(let e of r.announcing.values())F(r,e,`completed`)}},ie=()=>{for(let[e,t]of s){let n=!1;for(let t of c.values())n||=t.announcing.has(e);n||(g+=t.dropped,t.close(),s.delete(e))}},ae=()=>{for(let t of/* @__PURE__ */ new Set([...e.torrents(),...c.keys()]))L(t)},oe=()=>{let e=Date.now();ae();for(let t of c.values()){for(let n of t.conns)e<n.deadline||(n.state===`open`&&n.socket.listenerCount(`data`)?n.deadline=1/0:E(n));for(let[n,{until:r,silent:i}]of t.quiet)e<r||(t.quiet.delete(n),i&&y());if(t.askAt&&e>=t.askAt){t.askAt=0;let e=0;for(let n of t.conns)n.state===`offered`&&e++;for(let n of t.announcing.values())ne(t,n,e)}i&&e>=t.lookAt&&ee(t)}ie(),P()},se={onchange:null,close:()=>{if(!v){v=!0,clearInterval(ce);for(let e of c.values())I(e);ie()}},refresh:()=>{v||(ae(),ie(),P())},snapshot:()=>({dropped:[...s.values()].reduce((e,t)=>e+t.dropped,g),unmade:h,torrents:[...c.values()].map(e=>{let t=0;for(let n of e.conns)n.state===`open`&&t++;let n=0;for(let t of e.quiet.values())t.silent&&n++;return{handle:e.handle,trackers:[...e.announcing].map(([e,{tracker:t,seeders:n,leechers:r,answeredAt:i,failure:a}])=>({url:e,connected:t.connected,seeders:n,leechers:r,answeredAt:i,failure:a})),pending:e.conns.size-t,open:t,lastPeerAt:e.lastPeerAt,silent:n}})})},ce=setInterval(oe,Up);return oe(),se},Qp=`/assets/webrtc-DCtPDVeu.wasm`;const $p=(e,t)=>(e?.snapshot().torrents.find(e=>e.handle===t)?.trackers??[]).map(e=>({url:e.url,message:e.failure??``,tier:0,fails:e.failure?1:e.answeredAt===null?-1:0,updating:!1,verified:e.answeredAt!==null,nextAnnounceIn:-1,seeders:e.seeders??-1,leechers:e.leechers??-1,downloaded:-1})),em=(e,t)=>{let{port1:n,port2:r}=new MessageChannel;t({type:`peer-links`,port:r},[r]);let i=Zp(e,{links:ap(n),WebSocket,trackers:Wl});return{refresh:()=>i.refresh(),trackers:e=>$p(i,e),close:()=>i.close()}},tm=(e,{net:t,dgram:n})=>{let r=null,i,a=!1,o=()=>new Promise((e,t)=>{let r=n.createSocket(`udp4`);r.once(`listening`,()=>e(r)),r.on(`error`,t),r.bind(0)}),s=e=>new Promise((n,r)=>{let{hostname:i,port:a,protocol:o}=new URL(e),s=t.connect({host:i,port:Number(a)||(o===`wss:`?443:80)}),c=e=>{clearTimeout(l),s.destroy(),e&&tu(e)?n(e):r(/* @__PURE__ */ Error(`the relay did not say its address`))},l=setTimeout(c,1e4);s.once(`connect`,()=>c(s.localAddress)),s.on(`error`,()=>c()),s.once(`close`,()=>c())}),c=async()=>{for(let e of Wl){let t=await s(e).catch(()=>null);if(t)return t}throw Error(`the relay did not say its address`)};return(async()=>{let t=500;for(;!a;){i??=await fetch(Qp).then(e=>e.arrayBuffer()).then(e=>WebAssembly.compile(e)).catch(()=>void 0);let n=i&&await o().catch(()=>null);if(n){let o=!0,s=new Promise(e=>{let t=()=>{o=!1,e()};n.once(`close`,t),n.once(`error`,t)});try{let l=await c();if(o&&!a){let a=await Yf({socket:n,address:l,port:n.address().port,wasm:i,allowPrivateCandidates:!1});r=Zp(e,{links:rp({RTCPeerConnection:a.RTCPeerConnection}),WebSocket:ff,trackers:Wl,relay:!0}),t=500,await s,r?.close(),r=null,a.close()}}catch{}try{n.close()}catch{}}await new Promise(e=>setTimeout(e,t)),t=Math.min(t*2,i&&!n?2e3:3e4)}})(),{refresh:()=>r?.refresh(),trackers:e=>$p(r,e),close:()=>{a=!0,r?.close(),r=null}}};var nm=ku(),rm=class extends Jd.EventEmitter{_type;_localAddress;_remoteAddress;_connectedLocally;_connectGeneration=0;_destroyed=!1;_busyRelease;_webVPNUdpSocketPromise;_dataPort;_socketId;_sendQueue=[];_sendQueueBytes=0;_sendFlushScheduled=!1;_peerTailCache=/* @__PURE__ */ new Map;_relayChoice;_relay;constructor(e){if(super(e),!e)throw Error(`Missing options`);this._type=e.type,this._relayChoice=e.relay,e.connection&&this.__webvpn_udp_socket_init__(e.connection)}_lastRecvBufferSize=0;_lastSendBufferSize=0;_lastTtl=64;_lastMulticastTtl=1;_lastMulticastLoopback=!0;_setUdpOption(e){this._webVPNUdpSocketPromise?this._webVPNUdpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}}):this.emit(`error`,/* @__PURE__ */ Error(`Cannot set socket option before bind`))}_dataPortAcks=!1;_dataPortConsumedBytes=0;_dataPortAckedBytes=0;_ackDataPortBatch(e){if(!this._dataPortAcks||!this._dataPort||(this._dataPortConsumedBytes+=e,this._dataPortAckedBytes!==0&&this._dataPortConsumedBytes-this._dataPortAckedBytes<524288))return;this._dataPortAckedBytes=this._dataPortConsumedBytes;let t={type:hu,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=sm(n)),s+=n.byteLength,d=t.getUint16(s),s+=2}let f=t.getUint32(s);s+=4;try{this.emit(`message`,nm.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 im;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let i=$l.Address4.isValid(e)?om(e):cm(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($l.Address4.isValid(e)){let n=om(e),r=t&&$l.Address4.isValid(t)?om(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if($l.Address6.isValid(e)){let t=cm(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=au(...e),n=this._type===`udp6`?`::`:`0.0.0.0`,r=this._relayChoice,i=this.__webvpn_udp_socket_init__(Eo(`a udp socket`).then(e=>(r!==void 0&&mu(e,`dgram.createSocket`),e.cloud.webvpn.udpSocket({type:this._type,address:t.address??n,port:t.port,dataPort:!0,relay:r}))));return t.callback&&i.then(e=>{e&&t.callback.call(this)}),this}__webvpn_udp_socket_init__(e,t){return t&&(this._localAddress={address:t.localAddress,family:t.localFamily,port:t.localPort}),this._busyRelease??=cu(`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`,nm.Buffer.from(e.data),{address:e.address,family:e.family,port:e.port,size:e.size})}})().catch(e=>this._onTransportClosed(e instanceof Error?e.message:void 0))}return e.closed?.then(e=>this._onTransportClosed(e?.reason)).catch(()=>{}),this._relay=e.relay,this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e}).catch(e=>{this.emit(`error`,Cu(e))}),this._webVPNUdpSocketPromise.then(e=>{e?this.emit(`listening`):this._busyRelease?.()}),this._webVPNUdpSocketPromise}close(e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);return this._webVPNUdpSocketPromise.then(async t=>{let n=this._destroyed;this._destroyed=!0,this._busyRelease?.(),this._dataPort?.close(),this._dataPort=void 0;try{await t?.close()}finally{try{n||this.emit(`close`)}finally{e&&e()}}}).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`,Cu(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($l.Address4.isValid(e)){let n=om(e),r=t&&$l.Address4.isValid(t)?om(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if($l.Address6.isValid(e)){let t=cm(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=ou(...e),n=am(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||$l.Address4.isValid(a)||$l.Address6.isValid(a))){this._portSend(r,o?void 0:a,o?void 0:t.port),n?.call(this,null,r.byteLength);return}let s=this._destroyed;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=>{if(this._destroyed&&!s)return;let t=Cu(e);n?n.call(this,t,0):this.emit(`error`,t)})})}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)})}},im=new Uint8Array([2]),am=e=>{if(typeof e==`string`)return eu.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(am),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)},om=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)},sm=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(`:`)}`},cm=e=>{let t=new $l.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)))},lm=(e,t)=>{let n=new rm(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},um={Socket:rm,createSocket:lm},dm=/* @__PURE__ */ n({Socket:()=>rm,createSocket:()=>lm,default:()=>um});const fm=({net:e,dgram:t}={net:tf,dgram:dm})=>{let n=/* @__PURE__ */ new Map,r=null,i=(e,t)=>{n.set(e,t),e.then(()=>n.delete(e))},a=(e,t)=>{let n=e[t];return e[t]=(...t)=>{let r=!1;return e.on(`listening`,()=>{r=!0}),i(new Promise(t=>{e.on(`close`,t),e.on(`error`,()=>{r||t()})}),()=>{r?e.close():e.on(`listening`,()=>e.close())}),n.apply(e,t)},e},o=e=>(i(new Promise(t=>e.on(`close`,t)),()=>e.destroy()),e);return{net:{connect:(...t)=>r?r.net.connect():o(e.connect(...t)),createServer:()=>{if(r)return r.net.createServer();let t=a(e.createServer(),`listen`);return t.on(`connection`,o),t}},dgram:{createSocket:(...e)=>r?r.dgram.createSocket():a(t.createSocket(...e),`bind`)},close:()=>{r??=ps();for(let e of n.values())try{e()}catch{}return Promise.race([Promise.all(n.keys()),new Promise(e=>setTimeout(e,1e3))])}}},pm=/* @__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.force-start.recheck.import-list.clear-list.start.start-many.retry.retry-now.flush-resume.inspect.torrent-detail.set-flags.reannounce.add-trackers.queue-move.set-limits.set-session-limits.set-seeding-policy.set-temporary.export-start.export-chunk.export-end.import-start.import.close-sockets`.split(`.`)),mm=e=>`ripple:source:`+e,hm=e=>`ripple:trackers:`+e,gm=self.name===`direct`?`direct`:`relay`,_m=gm===`relay`?fm():null;let W=null,vm=null,ym=null,bm={room:1/0,grownAt:0},xm=0;const Sm=(e,t)=>{let n=xm-bm.grownAt+t>bm.room&&G.some(t=>!Q.has(t)&&W?.files(t)?.storageIndex===e);return n||(xm+=t),!n},Cm=Js(Is,Sm);let wm=null;const Tm=/* @__PURE__ */ new Map;let Em=!1;const G=[],Dm=/* @__PURE__ */ new Map,K=/* @__PURE__ */ new Map,q=/* @__PURE__ */ new Map,Om=/* @__PURE__ */ new Map,km=/* @__PURE__ */ new Map,Am=e=>{let t=km.get(e);return t||(t={},km.set(e,t)),t},jm=e=>km.get(e)?.stop,Mm=e=>jm(e)===`user`,Nm=e=>jm(e)===`cache-idle`,Pm=e=>jm(e)===`seed-policy`,Fm=e=>jm(e)!==void 0,Im=e=>km.get(e)?.forced===!0,Lm=e=>km.get(e)?.userStarted===!0,Rm=e=>km.get(e)?.watchedPastQueue===!0,zm=e=>km.get(e)?.seedBypass===!0,Bm=(e,t)=>{Am(e).stop=t},Vm=(e,t)=>{let n=km.get(e);return!n?.stop||t&&n.stop!==t?!1:(delete n.stop,!0)},J=(e,t,n)=>{if(n){let n=Am(e);return!n[t]&&(n[t]=!0,!0)}let r=km.get(e);return r?.[t]?(delete r[t],!0):!1},Hm=()=>{for(let e of km.values())delete e.seedBypass},Um=()=>{for(let e of km.values())if(e.stop===`seed-policy`)return!0;return!1},Wm=/* @__PURE__ */ new Set,Gm=/* @__PURE__ */ new Set,Km=e=>{Gm.delete(e),Wm.add(e)},qm=e=>{Wm.delete(e),Gm.add(e)},Jm=/* @__PURE__ */ new Map,Ym=/* @__PURE__ */ new Map,Y=ec(gm===`relay`),Xm=e=>e>=4294967040,Zm=(e,t,n)=>hs(t)?e.addMagnet(t,n):-2>>>0,X=(e,t)=>self.postMessage(e,t??[]),Qm=()=>G.map(e=>{let t=W.bitfield(e);return{handle:e,magnet:Dm.get(e)??``,files:W.files(e),status:W.status(e),bitfield:t?{numPieces:t.numPieces,pieceLength:t.pieceLength,length:t.length,pieces:t.pieces}:null,recovery:Y.state(e),userPaused:Mm(e),windowed:mg.has(e),ephemeral:Q.has(e),...Ym.has(e)?{noPeersSince:Ym.get(e)}:{},swarmDownloads:Math.max(-1,...W?.lastTrackers(e).map(e=>e.downloaded)??[]),uptime:$m(e),sessionUptime:eh(e),totals:Kh(e)}}),$m=e=>{let t=W?.status(e),n=Bh.get(e);return!t||!n?Vh.get(e)??ac:uc(Vh.get(e),n,t)},eh=e=>{let t=W?.status(e),n=Bh.get(e);return t&&n?lc(n,t):ac},th=async()=>await Po(`ripple:torrents`)??[],nh=async(e,t)=>{let n=[];await Io(Jc,r=>{n=r??[];let i=n.findIndex(t=>t.infoHash===e.infoHash),a={...Kc(i>=0?n[i]:null,e),...t};return i>=0?n[i]=a:n.push(a),n}),X({type:`list`,list:n})},rh=async(e,t=!1)=>{let n=[];await Io(Jc,t=>(n=t??[],n.forEach((t,r)=>{let i=e.get(t.infoHash);i&&(n[r]={...t,...i})}),n)),t||X({type:`list`,list:n})},Z=(e,t,n=!1)=>rh(/* @__PURE__ */ new Map([[e,t]]),n),ih=e=>{let t=K.get(e);t&&Z(t,{lastUsedAt:Date.now()},!0).catch(()=>{})},ah=async e=>{await Lo($c(e)).catch(()=>{}),await Lo(el(e)).catch(()=>{}),await Lo(mm(e)).catch(()=>{}),await Lo(hm(e)).catch(()=>{}),await Lo(tl(e)).catch(()=>{})},oh=async e=>{let t=[];await Io(Jc,n=>t=(n??[]).filter(t=>t.infoHash!==e)),await Io(Yc,t=>Xc(t,[{infoHash:e,removedAt:Date.now()}])),await ah(e),X({type:`list`,list:t})},Q=/* @__PURE__ */ new Set,sh=/* @__PURE__ */ new Set([4,5]);let ch=Fl;const lh=e=>Im(e)||Rm(e),uh=e=>{lh(e)?W?.setFlags(e,0,V.paused|V.autoManaged):W?.resumeTorrent(e)},dh=/* @__PURE__ */ new Map,fh=/* @__PURE__ */ new Set,ph=/* @__PURE__ */ new Set;let mh=null,hh=0;const gh=5e3;let _h=null,vh=0,yh=0,bh=rc,xh=0,Sh=0;const Ch=/* @__PURE__ */ new Set,wh=async e=>{if(!Ch.has(e)){Ch.add(e);try{let t=W?.files(e)?.storageIndex,n=t===void 0||!ym?null:await ym.usageOfStorage(t);e===mh&&(_h={handle:e,bytes:n})}finally{Ch.delete(e)}}},Th=e=>{let t=mh;if(t==null||!G.includes(t))return null;W.peers(t),e-hh>=gh&&(hh=e,W.trackers(t),wh(t).catch(()=>{}));let n=W.lastTrackers(t),r=W?.pieceAvailability(t);return{handle:t,peers:W.lastPeers(t),trackers:[..._m?n:n.map(Eh),...vm?.trackers(t)??[]],storageBytes:_h?.handle===t?_h.bytes??void 0:void 0,...r?.length?{availability:r}:{}}},Eh=e=>({...e,message:``,fails:-1,updating:!1,nextAnnounceIn:-1}),Dh=()=>{let e=Th(Date.now());X({type:`state`,torrents:Qm(),transport:gm,reachable:W.reachable(),inboundNow:bh,dhtNodes:xh,detail:e,rateLimits:{...Lh}},e?.availability?[e.availability.buffer]:[])},Oh=e=>{let t=W?.files(e);if(!t)return[];let n=t.files.map(e=>e.path.split(`/`).filter(Boolean)[0]).filter(Boolean);return[...new Set(n)]},kh=(e,t,n,r,i=!1)=>{G.includes(e)||G.push(e),Dm.set(e,t),n&&(K.set(e,n),ph.add(e)),q.set(e,r),i?Q.add(e):Q.delete(e)},Ah=e=>{let t=G.indexOf(e);t>=0&&G.splice(t,1),Dm.delete(e),K.delete(e),q.delete(e),Om.delete(e),km.delete(e),Y.forget(e),og.delete(e),eg.delete(e),Wm.delete(e),Gm.delete(e),Jm.delete(e),$.delete(e),fg.delete(e),pg.delete(e),Mh.delete(e),Ih.delete(e),Rh.delete(e),Bh.delete(e),Vh.delete(e),Hh.delete(e),Uh.delete(e),Q.delete(e),dh.delete(e),fh.delete(e),ph.delete(e),Nh.delete(e),Vg.delete(e),mg.delete(e),hg.delete(e),gg.delete(e),_g.delete(e),Ig.delete(e),Lg.delete(e),Ag.delete(e),Ym.delete(e),Fh.delete(e)},jh=e=>{Vm(e,`cache-idle`)&&(qm(e),W?.resumeTorrent(e),Y.hold(e,Date.now()))},Mh=/* @__PURE__ */ new Set,Nh=/* @__PURE__ */ new Set,Ph=e=>{Nh.delete(e)&&W?.setFlags(e,0,V.uploadMode)},Fh=/* @__PURE__ */ new Set,Ih=/* @__PURE__ */ new Map;let Lh={down:0,up:0};const Rh=/* @__PURE__ */ new Map;let zh=0;const Bh=/* @__PURE__ */ new Map,Vh=/* @__PURE__ */ new Map,Hh=/* @__PURE__ */ new Map,Uh=/* @__PURE__ */ new Map,Wh=e=>({activeSeconds:e.activeSeconds,seedingSeconds:e.seedingSeconds,downloaded:e.allTimeDownload,uploaded:e.allTimeUpload,wasted:e.wasted}),Gh=e=>({activeSeconds:e?.activeSeconds??0,seedingSeconds:e?.seedingSeconds??0,downloaded:e?.downloaded??0,uploaded:e?.uploaded??0,wasted:e?.wasted??0}),Kh=e=>{let t=W?.status(e),n=Hh.get(e);return!t||!n?Uh.get(e)??sc:fc(Uh.get(e),n,Wh(t))},qh=(e,t)=>{let n={...Rh.get(e)};Ml(t.down)&&(n.down=t.down),Ml(t.up)&&(n.up=t.up),(Ml(n.down)||Ml(n.up))&&(Rh.set(e,n),Yh(e))},Jh=e=>{let t=Rh.get(e)?.down;return _g.has(e)?Math.min(t||16384,16384):t},Yh=e=>{let t=Rh.get(e);if(!W||!t)return;let n=Jh(e);Ml(n)&&W.setDownloadLimit(e,n),Ml(t.up)&&W.setUploadLimit(e,t.up)},Xh=6e3,Zh=e=>e.reachable().listeners?.some(e=>e.healing)===!0,Qh=U.formatMessage({id:`torrent removed`,defaultMessage:`torrent removed`}),$h=U.formatMessage({id:`torrent paused`,defaultMessage:`torrent paused`}),eg=/* @__PURE__ */ new Map,tg=e=>[...eg.get(e)?.values()??[]].some(t=>!t.viewer||$.get(e)?.has(t.viewer)),ng=e=>[...eg.get(e)?.values()??[]].some(t=>(!t.viewer||$.get(e)?.has(t.viewer))&&!r_(e,t.fileIndex,t.offset,t.len)),rg=(e,t)=>{let n=eg.get(e);if(n?.size){for(let e of n.keys())X({type:`read-error`,id:e,error:t});n.clear()}},ig=async e=>{if(!e||cl(e))return;let t=await navigator.storage.getDirectory();for(let n of e.split(`/`).filter(Boolean))t=await t.getDirectoryHandle(n,{create:!0})},ag=async(e,t,n)=>{if((await Po(el(e)))?.byteLength)return;let r=Dl(t);if(!r)return;let i=Tl(r,El(n));await Io(el(e),e=>e?.byteLength?e:i)},og=/* @__PURE__ */ new Map,sg=async e=>{let t=K.get(e);if(!t||!W||og.has(e)||sl(q.get(e)))return!1;let n=W.status(e);if(!n||Qs.has(n.state)||Nh.has(e))return!1;let r=(async()=>{try{let n=await W.saveResumeData(e);return G.includes(e)?(await ig(q.get(e)),await Fo($c(t),n),await ag(t,n,Dm.get(e)??``).catch(()=>{}),!0):!1}catch(e){return console.error(`[worker] saving resume data failed`,String(e)),!1}})().finally(()=>og.delete(e));return og.set(e,r),r},cg=(e,t)=>{let n=W?.files(e),r=n?.files[t];if(!n||!r||r.size<=0)return null;let i=Math.floor(r.offset/n.pieceLength),a=Math.floor((r.offset+r.size-1)/n.pieceLength);return{file:r,pieceLength:n.pieceLength,p0:i,p1:a}},$=/* @__PURE__ */ new Map;let lg=!1;const ug=()=>[...$].every(([e,t])=>[...t.values()].every(t=>t.held||t.bulk||t.prepare||r_(e,t.fileIndex,t.fromOffset,1/0))),dg=()=>[...$].filter(([,e])=>[...e.values()].some(e=>e.prepare)).map(([e])=>e),fg=/* @__PURE__ */ new Set,pg=/* @__PURE__ */ new Set,mg=/* @__PURE__ */ new Map,hg=/* @__PURE__ */ new Map,gg=/* @__PURE__ */ new Set,_g=/* @__PURE__ */ new Set;let vg,yg;const bg=()=>!!vg?.fixed||yg!==void 0,xg=`ripple:ceiling-fixed`;let Sg,Cg=null;const wg=(e,t,n)=>[...Bg(e).filter(e=>e.fileIndex===t).map(e=>Rs(n,e.fromOffset,e.fromOffset+xs(n.pieceLength))),...[...eg.get(e)?.values()??[]].filter(n=>n.fileIndex===t&&(!n.viewer||$.get(e)?.has(n.viewer))).map(e=>Rs(n,e.offset,e.offset+e.len))],Tg=(e,t,n)=>{let r=hg.get(e),[i]=n;if(r===void 0||!i||!bg()||!Q.has(e)||n.some(e=>e.fileIndex!==i.fileIndex))return null;let a=t.files[i.fileIndex],o=q.get(e);if(!a||o===void 0)return null;let s={offset:a.offset,size:a.size,pieceLength:t.pieceLength},c=Cm.chunkBytesOf(o),l=Cm.chunksOf(o,i.fileIndex),u=Us({file:s,chunkBytes:c,room:r,reader:i.fromOffset,held:l,pinned:wg(e,i.fileIndex,s)});return u&&{...u,fileIndex:i.fileIndex,file:s,chunkBytes:c}},Eg=(e,t)=>e.fileIndex===t.fileIndex&&JSON.stringify(e.want)===JSON.stringify(t.want),Dg=(e,t)=>{let n=W?.bitfield(e);if(!n)return!1;for(let e=t.start;e<t.end;e++)if(!((n.pieces[e>>3]??0)&128>>(e&7)))return!1;return!0},Og=()=>Cg?Cg.space.limitBytes-Cg.space.usedBytes-(Cm.footprint()-Cg.footprint)-hc:1/0,kg=3e4,Ag=/* @__PURE__ */ new Map,jg=e=>(Ag.get(e)?.until??0)>Date.now(),Mg=e=>{let t=mg.get(e),n=!!t&&!tg(e)&&Ws(Dg(e,t.ahead),Og(),t.chunkBytes);n!==_g.has(e)&&(n?_g.add(e):_g.delete(e),W?.setDownloadLimit(e,Jh(e)??0))},Ng=e=>{let t=mg.get(e),n=W?.bitfield(e);if(!t||!n||t.slack.end<=t.slack.start||jg(e))return;let r=[];for(let e=t.slack.start;e<t.slack.end;e++)(n.pieces[e>>3]??0)&128>>(e&7)&&r.push(e);r.length&&t.slack.end-t.slack.start-r.length<2&&W?.forgetPieces(e,r)},Pg=e=>Uc(q.get(e))&&Q.has(e)&&![...$.get(e)?.values()??[]].some(e=>e.held||e.bulk)&&gl(Ih.get(e)??{}),Fg=e=>{let t=[...$.get(e)?.values()??[]],n=W?.files(e),r=q.get(e);if(!n||r===void 0||!Pg(e)||!t.some(e=>!e.prepare)||!bg()||jg(e))return[];let i=new Set(t.map(e=>e.fileIndex)),a=Cm.chunkBytesOf(r),o=({offset:e,size:t})=>({offset:e,size:t,pieceLength:n.pieceLength}),s=n.files.flatMap((t,n)=>i.has(n)?[Rs(o(t),0,t.size)]:wg(e,n,o(t)));return n.files.flatMap((e,t)=>e.pad||i.has(t)?[]:Cm.chunksOf(r,t).map(n=>({chunk:n,fileIndex:t,pieces:zs(o(e),a,n)})).filter(({pieces:e})=>!s.some(t=>t.start<e.end&&e.start<t.end)))},Ig=/* @__PURE__ */ new Set,Lg=/* @__PURE__ */ new Set,Rg=async e=>{if(Ig.has(e)){Lg.add(e);return}Ig.add(e);let t=!1;try{if(jg(e)){t=!0;return}let n=q.get(e),r=()=>{let t=mg.get(e),r=gg.has(e)?Fg(e):[];if(!t||n===void 0)return r;let i=/* @__PURE__ */ new Set([...t.keep,...Bs(t.file,t.chunkBytes,wg(e,t.fileIndex,t.file))]);return[...Cm.chunksOf(n,t.fileIndex).filter(e=>!i.has(e)).map(e=>({chunk:e,fileIndex:t.fileIndex,pieces:zs(t.file,t.chunkBytes,e)})),...r]},i=({start:t,end:n})=>W?.forgetPieces(e,Array.from({length:n-t},(e,n)=>t+n))??null,a=r().filter(({pieces:n})=>{let r=i(n);if(r?.busy){for(let t=n.start;t<n.end;t++)W?.cancelPieceRequests(e,t);t=!0}return r?.busy===0});if(!a.length||n===void 0)return;if(!await sg(e)){t=!0;return}for(;D_&&gg.has(e);)await new Promise(e=>setTimeout(e,f_));let o=new Set(r().map(({fileIndex:e,chunk:t})=>`${e}:${t}`)),s=[];for(let{chunk:e,fileIndex:t,pieces:r}of a){if(!o.has(`${t}:${e}`))continue;let a=i(r);!a||a.forgotten||a.busy||s.push(Cm.drop(n,t,e))}await Promise.all(s),s.length&&Y.retry(e,Date.now())}catch(e){console.error(`[worker] dropping chunks failed`,String(e))}finally{Ig.delete(e),Lg.delete(e)?Rg(e):t&&(mg.has(e)||gg.has(e))&&setTimeout(()=>void Rg(e),1e3)}},zg=e=>{let t=Ih.get(e);if(!W||!t)return;let n=W.files(e);n&&W.prioritizePieces(e,hl({files:n.files,pieceLength:n.pieceLength,numPieces:Math.ceil(n.totalSize/n.pieceLength),wanted:t.wanted,firstLast:t.firstLast}))},Bg=e=>{let t=$.get(e);return t?[...t.values()].filter(e=>!e.held&&(!e.prepare||lg)):[]},Vg=/* @__PURE__ */ new Set,Hg=(e,t,n)=>{let[r]=n,i=r&&t.files[r.fileIndex],a=r&&i?.size&&!r.bulk&&!r.prepare&&Vg.has(e)?Rs({...i,pieceLength:t.pieceLength},r.fromOffset,r.fromOffset+ys):null;return!a||Dg(e,a)?(Vg.delete(e),null):a},Ug=()=>{for(let e of[...Vg]){let t=W?.files(e);t&&!Hg(e,t,Bg(e))&&$g(e)}},Wg=e=>Q.has(e)&&q.get(e)!==nl&&!Mm(e)&&!Lm(e)&&!Im(e),Gg=e=>{J(e,`watchedPastQueue`,!1),Bm(e,`cache-idle`),Km(e),W?.pauseTorrent(e),Ph(e),sg(e)},Kg=(e,t)=>{let n=e.files[t.fileIndex];if(!n||n.size<=0)return[];let r=Math.ceil(e.totalSize/e.pieceLength),i=Math.floor(n.offset/e.pieceLength),a=Math.min(r-1,Math.floor((n.offset+n.size-1)/e.pieceLength));if(a<i)return[];if(!t.prepare)return[{start:i,end:a+1}];let o=bs(e.pieceLength);return[t.fromOffset,Math.max(0,n.size-ys)].map(t=>{let r=Math.min(Math.max(t,0),Math.max(0,n.size-1)),s=Math.min(Math.max(Math.floor((n.offset+r)/e.pieceLength),i),a);return{start:s,end:Math.min(a+1,s+o)}})},qg=(e,t,n)=>n.every(n=>Kg(t,n).every(t=>Dg(e,t))),Jg=(e,t,n)=>mg.has(e)||!!t&&!!Tg(e,t,n.filter(e=>!e.prepare)),Yg=(e,t)=>{if(!Rl(ch)||!W)return!1;let n=W.status(e);if(!n||!sh.has(n.state))return!1;let r=Kh(e),i=$m(e),a=t?.contentSize??t?.totalSize??0;return Hl(ch,{uploaded:r.uploaded,downloaded:r.downloaded,size:a,seedingSeconds:i.seedingSeconds})},Xg=e=>{J(e,`watchedPastQueue`,!1),Bm(e,`seed-policy`),J(e,`seedBypass`,!1),Km(e),W?.pauseTorrent(e),sg(e);let t=K.get(e);t&&Z(t,{seedStopped:!0,seedBypass:!1}).catch(()=>{})},Zg=e=>{qm(e),uh(e),Y.hold(e,Date.now());let t=K.get(e);t&&Z(t,{seedStopped:!1}).catch(()=>{})},Qg=()=>{if(W&&(Rl(ch)||Um()))for(let e of G){if(q.get(e)===nl||Nm(e)||Mm(e))continue;if(Im(e)||zm(e)){Vm(e,`seed-policy`)&&Zg(e);continue}let t=W.status(e);if(!t||Qs.has(t.state))continue;if(!sh.has(t.state)){Vm(e,`seed-policy`)&&Zg(e);continue}let n=W.files(e)??null,r=Bg(e);if(!(Q.has(e)&&Jg(e,n,r))){if(Yg(e,n)){if(ng(e)||r.length>0&&(!n||!qg(e,n,r)))continue;Pm(e)||Xg(e)}else Vm(e,`seed-policy`)&&Zg(e)}}},$g=e=>{if(!W)return;if(!G.includes(e)){$.delete(e),pg.delete(e);return}let t=Bg(e);if(!t.length){if(Vg.delete(e),J(e,`watchedPastQueue`,!1)&&!Im(e)&&!Fm(e)&&W.setFlags(e,V.autoManaged,V.autoManaged),!W.files(e)){pg.add(e);return}if(pg.delete(e),mg.delete(e),Mg(e),W.clearStreamWindow(e),gl(Ih.get(e)??{})||zg(e),Wg(e)&&!Nm(e)){let t=W.status(e);if(!t||Qs.has(t.state)){pg.add(e);return}if(Vm(e,`seed-policy`)){let t=K.get(e);t&&Z(t,{seedStopped:!1}).catch(()=>{})}Gg(e)}else Ph(e);return}let n=W.files(e);if(n&&(Pm(e)||Nm(e)&&!Im(e)&&!zm(e)&&!ng(e)&&!(Q.has(e)&&Jg(e,n,t))&&Yg(e,n))){if(qg(e,n,t)){if(jm(e)===`cache-idle`){Bm(e,`seed-policy`);let t=K.get(e);t&&Z(t,{seedStopped:!0}).catch(()=>{})}pg.delete(e),Vg.delete(e);return}Vm(e,`seed-policy`)&&Zg(e)}if(jh(e),!Mm(e)&&!Pm(e)&&J(e,`watchedPastQueue`,!0)&&uh(e),Ph(e),!n){pg.add(e);return}fg.delete(e)&&k_();let r=Hg(e,n,t),i=t.flatMap(({fileIndex:e,fromOffset:t,bulk:r,prepare:i})=>{let a={fileIndex:e,offset:t},o=n.files[e];return i?o?.size?[a,{fileIndex:e,offset:Math.max(0,o.size-ys)}]:[]:!r&&o?.size?[a,{fileIndex:e,offset:o.size-1}]:[a]}),a=t.filter(e=>!e.prepare),o=a.some(e=>!e.bulk),s=Tg(e,n,a);s?mg.set(e,s):mg.delete(e);let c=s?.want??(a.length<t.length?a.map(({fileIndex:e})=>n.files[e]).flatMap(e=>e?.size?[Rs({...e,pieceLength:n.pieceLength},0,e.size)]:[]):void 0);W.setStreamWindow(e,i,{unclaimedPriority:H.skip,windowPieces:r?r.end-r.start:bs(n.pieceLength),deadlineStepMs:Cs(n.pieceLength,W.status(e)?.downloadRate||3e6),deadlines:o,...c?{keep:c}:{}})?pg.delete(e):pg.add(e),s&&Rg(e),Ng(e),Mg(e)},e_=e=>{let t=W?.files(e),n=Bg(e).filter(e=>!e.prepare);if(!t||!n.length)return;let r=Tg(e,t,n),i=mg.get(e);if(r&&i&&Eg(r,i)){mg.set(e,r),Rg(e);return}(r||i)&&$g(e),!r&&gg.has(e)&&Rg(e)},t_=(e,t,n,r,i=!1,a,o=!1)=>{if(!G.includes(t))return;let s=$.get(t),c=!s?.size;s||$.set(t,s=/* @__PURE__ */ new Map);let l=s.get(e),u=a??l?.bulk;s.set(e,{fileIndex:n,fromOffset:r,...i?{held:i}:{},...u?{bulk:u}:{},...o?{prepare:o}:{}}),c?(ih(t),fg.add(t),Vg.add(t)):l?.fromOffset!==r&&Vg.delete(t),!c&&!l&&!o&&Fg(t).length&&fg.add(t),o&&(lg=ug()),$g(t)},n_=e=>{let t=!1;for(let[n,r]of[...$]){let i=!1;for(let t of[...r.keys()])e(t)&&(r.delete(t),i=!0);r.size||($.delete(n),i&&(ih(n),t=!0)),i&&$g(n)}t&&S_&&k_()},r_=(e,t,n,r)=>{let i=W?.files(e),a=i?.files[t],o=W?.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},i_=(e,t,n,r)=>{let i=W?.files(e),a=i?.files[t];if(!i||!a||n>=a.size)return r;let o=W?.bitfield(e),s=e=>!!o&&!!((o.pieces[e>>3]??0)&128>>(e&7)),c=Math.min(n+r,a.size),l=e=>Math.min(c,(e+1)*i.pieceLength-a.offset),u=Math.floor((a.offset+n)/i.pieceLength),d=l(u);if(s(u))for(;d<c&&s(u+1);)d=l(++u);return d-n},a_=(e,t,n,r)=>{let i=W?.files(e),a=i?.files[t],o=W?.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},o_=(e,t,n)=>{let r=Math.max(0,e-ys-t),i=n?Math.floor(r/n)*n:0;return Math.min(e,xs(t)+e-i)},s_=async(e,t={evictable:[],graced:[]})=>{let n=e=>Math.max(0,e.size-e.held),r=[],i=[],a=/* @__PURE__ */ new Map;for(let[e,t]of[...$]){let n=ym,o=W?.files(e),s=q.get(e);if(!n||!o||!t.size||s===void 0||cl(s))continue;let c=new Set([...t.values()].filter(e=>!e.prepare).map(e=>e.fileIndex)),l=Cm.chunkBytesOf(s),u=async r=>{let i=o.files[r]?.size??0,a=!c.has(r)&&[...t.values()].some(e=>e.prepare&&e.fileIndex===r);return{h:e,size:a?o_(i,o.pieceLength,Uc(s)?l:void 0):i,held:await n.usageOfStorage(o.storageIndex,r)??0}},d=Bg(e).find(e=>!e.prepare),f=bg()&&Q.has(e)&&Uc(s);for(let e of new Set([...t.values()].map(e=>e.fileIndex)))r.push({...await u(e),cache:f&&e===d?.fileIndex,chunkBytes:l});let p=n.refusedFile(o.storageIndex),m=Pg(e)&&![...t.values()].some(e=>e.fileIndex===p);p!==void 0&&!m&&i.push(await u(p));let h=Fg(e),g=0;for(let e of new Set(h.map(e=>e.fileIndex))){let t=Cm.chunksOf(s,e).length-h.filter(t=>t.fileIndex===e).length;g+=Math.max(0,(await n.usageOfStorage(o.storageIndex,e)??0)-t*l)}g>0&&a.set(e,g)}let o=e=>e.reduce((e,t)=>e+n(t),0),s=r.filter(e=>!e.cache),c=o(s.filter(e=>!Q.has(e.h))),l=Math.max(0,xc({...e,candidates:[...t.evictable,...t.graced]},bg())),u=o(s)-c+Math.min(c,l),d=r.filter(e=>e.cache),f=e=>e.reduce((e,t)=>e+t.bytesOnDisk,0),p=e.limitBytes-e.usedBytes+d.reduce((e,t)=>e+t.held,0)+f(t.evictable)-u-hc,m=e=>{let t=Vs(d.map(e=>e.size),p+e),r=new Set(d.filter((e,n)=>Hs(e.size,t[n]??0,e.chunkBytes)).map(e=>e.h));return{shares:t,windowed:r,owed:d.reduce((e,i,a)=>e+(r.has(i.h)?Math.max(0,(t[a]??0)-i.held):n(i)),u)}},h=m(0),g=d.some((e,t)=>e.size>(h.shares[t]??0)&&!h.windowed.has(e.h))?[...a.values()].reduce((e,t)=>e+t,0):0;g||a.clear();let _=m(g),v=m(g+f(t.graced)),y=i.filter(e=>!v.windowed.has(e.h)),b=y.filter(e=>!Q.has(e.h)),x=o(b)+b.length*gc(e.limitBytes),S=o(y.filter(e=>Q.has(e.h)))+x,C=new Map(d.map((e,t)=>[e.h,_.shares[t]??0]));return{pendingBytes:Math.max(0,_.owed-g),laterBytes:v.owed,refusedBytes:S,keptRefusedBytes:x,rooms:C,left:a}},c_=(e,t,n,r,i)=>{if(!e||!G.includes(t))return;let a=$.get(t)?.get(e);if(!a||a.held||a.fileIndex!==n){t_(e,t,n,r);return}let o=cg(t,n);if(!o)return;let s={fileOffset:o.file.offset,pieceLength:o.pieceLength,p1:o.p1};ws(s,a.fromOffset,r,i)&&t_(e,t,n,r)},l_=async e=>{let t=e.filter(e=>!cl(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}},u_=async()=>{let e,t;try{return e=await navigator.storage.getDirectory(),t=`.ripple-probe-${crypto.randomUUID()}`,(await Ms(await e.getFileHandle(t,{create:!0}))).close(),await e.removeEntry(t).catch(()=>{}),!0}catch{return e&&t&&await e.removeEntry(t).catch(()=>{}),!1}},d_=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}),f_=250,p_=async()=>{let e=xm;try{let{usage:t,quota:n}=await Nc.estimate();return!n||t===void 0?null:{usedBytes:t,limitBytes:n,grownAt:e}}catch{return null}},m_=async()=>{try{let{usage:e,quota:t}=await navigator.storage.estimate();return t&&e!==void 0?t-e:null}catch{return null}},h_=async(e,t=0)=>{for(let n=0;n<4e3;n+=250){await new Promise(e=>setTimeout(e,250));let n=await p_();if(!n||e-n.usedBytes>t/2)return n}return p_()},g_=async(e,t,n,r,i={})=>{rg(t,r),e.removeTorrent(t,!0),Ah(t),await Lo($c(n)).catch(()=>{}),await Z(n,{started:!1,paused:!1,...i})},__=(e,t,n)=>g_(e,t,n,U.formatMessage({id:`torrent removed to make room`,defaultMessage:`torrent removed to make room`})),v_=async(e,t,n,r)=>{if(!await fl(n,r.files))return;let i=K.get(t);i&&al(q.get(t))&&await g_(e,t,i,U.formatMessage({id:`Files missing`,defaultMessage:`Files missing`}),{savePath:Vc(i)})},y_=async(e,t,n,r)=>{let i=kl(q.get(t));if(i===r)return;let a=Dm.get(t)??``,o=Al(r,n),s=Mm(t),c=km.get(t),l=c?.stop===`seed-policy`,u=c?.userStarted===!0,d=c?.forced===!0,f=c?.seedBypass===!0,p=Q.has(t),m=Ih.get(t),h=(await th()).find(e=>e.infoHash===n)?.private===!0||e.isPrivate?.(t)===!0,g=await Po($c(n)).catch(()=>void 0);g?.byteLength&&await ag(n,g,a).catch(()=>{});let _=await Po(el(n)).catch(()=>void 0);if(h&&!_?.byteLength){X({type:`add-failed`,message:U.formatMessage({id:`This private torrent needs its .torrent file. Add it again.`,defaultMessage:`This private torrent needs its .torrent file. Add it again.`})});return}rg(t,U.formatMessage({id:`files moved`,defaultMessage:`files moved`})),e.removeTorrent(t,i===`browser`),Ah(t),await Lo($c(n)).catch(()=>{});let v=_?.byteLength?e.addTorrentFile(_,o):Zm(e,a,o);if(Xm(v)){X({type:`add-failed`,message:U.formatMessage({id:`Moving the files left the torrent unaddable`,defaultMessage:`Moving the files left the torrent unaddable`})}),await Z(n,{savePath:o,saveTo:r,started:!1});return}kh(v,a,n,o,p),m&&Ih.set(v,m),Mh.add(v),r===`folder`&&e.setFlags(v,V.uploadMode,V.uploadMode),s?(Bm(v,`user`),Km(v)):l?(Bm(v,`seed-policy`),Km(v)):qm(v),u&&J(v,`userStarted`,!0),d&&!s&&(J(v,`forced`,!0),uh(v)),f&&!s&&!l&&J(v,`seedBypass`,!0),Y.hold(v,Date.now()),await Z(n,{savePath:o,saveTo:r,started:!0})},b_=(e,{infoHash:t,magnet:n,bytes:r,handles:i,paused:a,seedStopped:o=!1,ephemeral:s=!1})=>{let c=ol(t);Tm.set(c,i);let l=e.addTorrentFile(r,c);return Xm(l)?(Tm.delete(c),null):(kh(l,n,t,c,s),e.setFlags(l,V.uploadMode,V.uploadMode),a?(Bm(l,`user`),Km(l)):o&&(Bm(l,`seed-policy`),Km(l)),Y.hold(l,Date.now()),l)},x_=async(e,t)=>{let n=new Map(e.map(e=>[e.infoHash,e])),r=[],i=[];for(let e of[...G]){let a=K.get(e);if(!a)continue;let o=n.get(a);if(!o?.ephemeral||!Wc(o.savePath,a)||$.get(e)?.size||tg(e))continue;let s=o.lastUsedAt??o.addedAt,c=await ym?.usageOf(o.savePath)??0;if(c<=0)continue;let l=t-(dh.get(e)??0)<6e4||t-s<15e3,u={infoHash:a,usedAt:s,bytesOnDisk:c};l?i.push(u):r.push(u)}return{evictable:r,graced:i}};let S_=!1;const C_=(e,t)=>{let n=yc(e)&&(yc({...e,refusedBytes:e.refusedBytes-t})||`kept`);n!==S_&&(S_=n,X({type:`storage-full`,full:n,usedBytes:e.usedBytes,limitBytes:e.limitBytes}))},w_=/* @__PURE__ */ new Set;let T_=!1;const E_=async()=>{if(!W||T_)return 0;T_=!0;try{let e=await th(),t=new Set(e.map(e=>e.infoHash.toLowerCase()));for(let e of w_)t.add(e.toLowerCase());let n=/* @__PURE__ */ new Set,r=!0;for(let e of G){let i=K.get(e);if(i&&t.add(i.toLowerCase()),(q.get(e)??`/dl`)!==`/dl`)continue;let a=Oh(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(!Uc(e)){if(e!==`/dl`&&!e.startsWith(`/dl/`)){r=!1;continue}if(e===`/dl`){if(t.rootEntry){n.add(t.rootEntry);continue}!G.some(e=>K.get(e)===t.infoHash)&&t.started!==!1&&(r=!1)}}}let i=await navigator.storage.getDirectory(),a=[...await Rc(i,`/dl`,{listedHashes:t,claimedNames:n,attributable:r}),...await Rc(i,`/cache`,{listedHashes:t,claimedNames:/* @__PURE__ */ new Set,attributable:!1})];return await zc(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{T_=!1}};let D_=!1,O_=!1;const k_=async()=>{let e=W;if(!e)return;if(D_){O_=!0;return}D_=!0;let t=null,n={pendingBytes:0,laterBytes:0,refusedBytes:0,keptRefusedBytes:0,rooms:/* @__PURE__ */ new Map,left:/* @__PURE__ */ new Map},r=[],i=[],a=e=>({...e,pendingBytes:vg?.fixed===!1&&yg===void 0?0:n.laterBytes,refusedBytes:n.refusedBytes,candidates:[...r,...i,...[...n.left].map(([e,t])=>({infoHash:K.get(e)??``,usedAt:0,bytesOnDisk:t}))]}),o=()=>{hg.clear(),gg.clear();for(let[e,t]of n.rooms)hg.set(e,t);for(let e of n.left.keys())gg.add(e);for(let e of/* @__PURE__ */ new Set([...hg.keys(),...mg.keys(),...gg]))e_(e)};try{let s=await p_();if(!s)return;t=s,Sg===void 0&&(Sg=await Po(xg).catch(()=>null)??null);let c=async e=>{let t=Cm.footprint(),n=await m_();if(n!==null){let t={usedBytes:e.usedBytes,headroomBytes:n};vg=Gs(vg??(typeof Sg==`boolean`?{...t,fixed:Sg}:void 0),t,Is),vg.fixed!==void 0&&vg.fixed!==Sg&&(Sg=vg.fixed,Fo(xg,Sg).catch(()=>{}));let r=[...$.keys()].some(e=>{let t=W?.files(e)?.storageIndex;return t!==void 0&&Q.has(e)&&Uc(q.get(e))&&ym?.refusedFile(t)!==void 0});yg===void 0&&vg.fixed===!1&&r&&(yg=e.usedBytes)}let r=yg===void 0?e:{...e,limitBytes:Math.min(e.limitBytes,Math.max(yg,e.usedBytes))};return Cg={space:r,footprint:t},r};s=t=await c(s),n=await s_(s);let l=await x_(await th(),Date.now());r=l.evictable,i=l.graced,n=await s_(s,l);let u=!1;for(;r.length;){let[a]=Cc({...s,pendingBytes:n.pendingBytes,candidates:r});if(!a)break;let o=r.find(e=>e.infoHash===a)?.bytesOnDisk??0;r=r.filter(e=>e.infoHash!==a);let l=G.find(e=>K.get(e)===a);if(l===void 0||$.get(l)?.size||tg(l))continue;let d=s.usedBytes;t=null,await __(e,l,a),u=!0;let f=await h_(d,o);if(!f)return;s=t=await c(f),n=await s_(s,{evictable:r,graced:i})}if(u)for(let e of $.keys())Y.retry(e,Date.now());if(o(),yc(a(s))&&await E_()){s=await c(await h_(s.usedBytes)??s),n=await s_(s,{evictable:r,graced:i});for(let e of $.keys())Y.retry(e,Date.now());o()}t=s}catch(e){console.error(`[worker] storage budget pass failed`,String(e))}finally{D_=!1,t&&(C_(a(t),n.keptRefusedBytes),bm={room:xc(a(t),bg()),grownAt:t.grownAt}),O_&&(O_=!1,k_())}};let A_,j_=!1;const M_=()=>{A_??=setInterval(()=>{let e=W,t=[...$.keys()].filter(t=>Bg(t).length&&!e?.files(t)),n=[...eg.keys()].filter(tg);if(!e||j_||!t.length&&!n.length){clearInterval(A_),A_=void 0;return}for(let t of n)e.postStatus(t);e.tick(),e.popAlerts();let r=t.filter(t=>e.files(t));for(let e of r)$g(e);Ug(),r.length&&Dh()},50)},N_=async()=>{let e=console.error.bind(console);if(console.error=(...t)=>{e(...t);try{X({type:`worker-error`,args:t.map(String)})}catch{}},!await u_()){X({type:`storage-unavailable`});return}th().then(e=>{e.length&&X({type:`list`,list:e})}).catch(()=>{});let t=Promise.race([Po(jl).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]),n=Promise.race([Po(Pl).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]);ym=pl(Fs(Sm),()=>wm,e=>Tm.get(e)??null,Cm),W=await ms(_m?{net:_m.net,dgram:_m.dgram,dnsLookup:ko,storage:ym,utpReceiveBufferBytes:4194304}:{...ps(),storage:ym,enableDht:!1,reserveListenPort:!1});for(let e=0;e<30;e++)W.tick();vm=_m?tm(W,_m):em(W,X),Lh=Nl(await t),ch=Bl(await n),W.setRateLimits({download:Lh.down,upload:Lh.up});try{let e=await th(),t=!await l_(e.filter(e=>e.started!==!1).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 Po($c(r.infoHash)),a=await Po(el(r.infoHash));if(t&&i&&i.byteLength){await Lo($c(r.infoHash)).catch(()=>{}),r.started=!1,n=!0;continue}r.private!==!0&&(a?.byteLength&&bl(a)||i?.byteLength&&Ol(i))&&(r.private=!0,n=!0);let o=r.private===!0,s=i?.byteLength&&(!o||Ol(i))?i:void 0;o&&i?.byteLength&&!s&&await Lo($c(r.infoHash)).catch(()=>{});let c=s?W.addTorrentWithResume(s,e):a&&a.byteLength?W.addTorrentFile(a,e):o?-2>>>0:Zm(W,r.magnet,e);if(Xm(c)){o&&!s&&!a?.byteLength&&(r.started=!1,n=!0);continue}kh(c,r.magnet,r.infoHash,e,r.ephemeral===!0),i?.byteLength&&al(e)&&Fh.add(c),Ih.set(c,{wanted:r.wantedFiles,firstLast:r.firstLast}),Mh.add(c),qh(c,{down:r.downloadLimit??0,up:r.uploadLimit}),Vh.set(c,{activeSeconds:r.activeSeconds??0,seedingSeconds:r.seedingSeconds??0}),Uh.set(c,Gh(r)),r.paused?(Bm(c,`user`),Km(c)):r.seedStopped?(Bm(c,`seed-policy`),Km(c)):qm(c),r.resumed&&J(c,`userStarted`,!0),r.forced&&!r.paused&&(J(c,`forced`,!0),uh(c)),r.seedBypass&&!r.paused&&!r.seedStopped&&J(c,`seedBypass`,!0),Y.hold(c,Date.now()),r.ephemeral&&(!i?.byteLength||Uc(e))&&(Nh.add(c),W.setFlags(c,V.uploadMode,V.uploadMode))}n&&await Fo(Jc,e)}catch(e){console.error(`[worker] restore failed`,e)}X({type:`ready`}),Em=!0,X({type:`list`,list:await th().catch(()=>[])}),Dh(),setInterval(()=>{if(!W)return;let e=Date.now();W.popAlerts();for(let e of G)W.postStatus(e);vm?.refresh();for(let e of[...Mh])W.files(e)&&(Mh.delete(e),Bg(e).length||$g(e));if(wm)for(let e of[...Fh]){let t=W.files(e);t&&(Fh.delete(e),v_(W,e,wm,t))}let t=dg();if(t.length&&ug()!==lg){lg=!lg;for(let e of t)$g(e)}for(let e of[...pg])$g(e);Ug();for(let t of[...fh])tg(t)||e-(dh.get(t)??0)<5e3||(fh.delete(t),$g(t));for(let e of[...mg.keys()])Ng(e),Mg(e);for(let e of G){if(Bh.has(e))continue;let t=W.status(e);t&&(Bh.set(e,{activeSeconds:t.activeSeconds,seedingSeconds:t.seedingSeconds}),Hh.set(e,Wh(t)))}for(let e of[...ph]){let[t]=Oh(e);if(!t)continue;ph.delete(e);let n=K.get(e);if(!n)continue;let r=W.files(e);Z(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})),...W.isPrivate?.(e)===!0?{private:!0}:{}}).catch(()=>{})}Qg();for(let e of Wm){let t=W.status(e);t&&!Qs.has(t.state)&&($s(t)?Wm.delete(e):W.pauseTorrent(e))}for(let e of Gm){if(Fm(e)){Gm.delete(e);continue}let t=W.status(e);if(t&&!Qs.has(t.state)){if(!t.paused){Gm.delete(e);continue}if(t.autoManaged||t.errorCode){Gm.delete(e);continue}W.resumeTorrent(e)}}Y.retain(new Set(G));for(let t of G){let n=W.status(t);Y.observe(t,n&&d_(n),Fm(t),e),!n||n.paused||!Zs.has(n.state)||n.numPeers>0?Ym.delete(t):Ym.has(t)||Ym.set(t,e)}for(let{handle:t,reason:n}of Y.due(e))n===`stalled`&&W.pauseTorrent(t),uh(t);if(e-yh>=2e3){yh=e;for(let e of G)W.peers(e)}if(bh=ic(G.map(e=>W.lastPeers(e))),e-Sh>=1e3&&(Sh=e,xh=W.dhtNodes()),$.size&&e-vh>=gh){vh=e;for(let e of $.keys())W.trackers(e)}Dh();for(let t of G){let n=W.status(t);if(!n||n.state!==4&&n.state!==5||Om.get(t)===n.paused||og.has(t))continue;let r=Jm.get(t);if(r&&e<r.at)continue;let i=n.paused;sg(t).then(e=>{if(e){Om.set(t,i),Jm.delete(t);return}let n=(Jm.get(t)?.tries??0)+1;Jm.set(t,{tries:n,at:Date.now()+Math.min(1e3*2**n,6e4)})})}},500),setInterval(()=>{if(!W)return;for(let e of G){let t=W.status(e);t&&t.state===3&&sg(e)}let e=!1;for(let t of G){let n=W.status(t),r=K.get(t),i=Bh.get(t);if(!n||!r||!i)continue;e=!0;let a=uc(Vh.get(t),i,n);if(!mc(Vh.get(t),a))continue;Vh.set(t,a),Bh.set(t,{activeSeconds:n.activeSeconds,seedingSeconds:n.seedingSeconds});let o=Wh(n),s=fc(Uh.get(t),Hh.get(t)??o,o);Uh.set(t,s),Hh.set(t,o),Z(r,{activeSeconds:a.activeSeconds,seedingSeconds:a.seedingSeconds,downloaded:s.downloaded,uploaded:s.uploaded,wasted:s.wasted},!0).catch(()=>{})}e&&Date.now()-zh>=3e5&&(zh=Date.now(),th().then(e=>X({type:`list`,list:e})).catch(()=>{}))},15e3),setInterval(()=>{k_()},1e4),k_(),setTimeout(()=>{E_(),setInterval(()=>{E_()},6e5)},6e4),self.addEventListener(`online`,()=>Y.retryNow(Date.now()))},P_=e=>cl(e.savePath)&&e.saveTo!==`source`,F_=e=>al(e.savePath)?e.saveTo??`folder`:e.saveTo,I_=async(e,t)=>{let n=new Map((await th()).map(e=>[e.infoHash,e])),r=/* @__PURE__ */ new Map;for(let i of t){let t=typeof i==`string`?n.get(i):void 0;if(!t)continue;if(t.saveTo===`source`){X({type:`add-failed`,message:U.formatMessage({id:`Nothing to download this from. Create it again from the same files.`,defaultMessage:`Nothing to download this from. Create it again from the same files.`})});continue}let a=P_(t)?Vc(t.infoHash):t.savePath||`/dl`,o=await Po(el(t.infoHash));if(t.private===!0&&!o?.byteLength){X({type:`add-failed`,message:U.formatMessage({id:`This private torrent needs its .torrent file. Add it again.`,defaultMessage:`This private torrent needs its .torrent file. Add it again.`})});continue}let s=o&&o.byteLength?e.addTorrentFile(o,a):Zm(e,t.magnet,a);if(Xm(s)){X({type:`add-failed`,message:U.formatMessage({id:`That torrent could not be read`,defaultMessage:`That torrent could not be read`})});continue}kh(s,t.magnet,t.infoHash,a,!1),qh(s,{down:t.downloadLimit,up:t.uploadLimit}),Y.hold(s,Date.now()),r.set(t.infoHash,{savePath:a,saveTo:F_(t),started:!0,paused:!1,resumed:!1,forced:!1,seedStopped:!1,seedBypass:!1,ephemeral:!1,lastUsedAt:Date.now()})}r.size&&(Dh(),await rh(r))},L_=(e,t,n=!1)=>X(typeof e.addId==`string`?{...t,addId:e.addId,...n&&{already:n}}:t),R_=async(e,t,n)=>{Q.delete(e),Vm(e,`seed-policy`),J(e,`seedBypass`,!1),n?.paused?(Bm(e,`user`),Km(e),W?.pauseTorrent(e)):jh(e),Bg(e).length&&$g(e),await Z(t,{ephemeral:!1,seedStopped:!1,seedBypass:!1,lastUsedAt:Date.now(),...n?.patch})},z_=async(e,t)=>{try{if(t.type===`add-magnet`){let n=hs(t.magnet),r=n?[...K].find(([,e])=>_s(e,n)):void 0;if(r){let[e,n]=r,i=!Q.has(e);t.ephemeral?ih(e):await R_(e,n),L_(t,{type:`added`,handle:e,magnet:Dm.get(e)||t.magnet},i)}else{let r=n?(await th()).find(e=>_s(e.infoHash,n)):void 0,i=r?.infoHash??n,a=r&&r.infoHash!==n?r.magnet:t.magnet,o=Gc(r,t.ephemeral===!0),s=!!r&&P_(r),c=t.savePath||!s&&r?.savePath||(o&&i?Hc(i):Vc(i)),l;if(r?.private===!0){let n=i?await Po(el(i)).catch(()=>void 0):void 0;if(!n?.byteLength){L_(t,{type:`add-failed`,message:U.formatMessage({id:`This private torrent needs its .torrent file. Add it again.`,defaultMessage:`This private torrent needs its .torrent file. Add it again.`})});return}if(l=e.addTorrentFile(n,c),Xm(l)){L_(t,{type:`add-failed`,message:U.formatMessage({id:`That torrent could not be read`,defaultMessage:`That torrent could not be read`})});return}}else if(l=Zm(e,a,c),Xm(l)){L_(t,{type:`add-failed`,message:U.formatMessage({id:`That is not a valid magnet link`,defaultMessage:`That is not a valid magnet link`})});return}kh(l,a,i,c,o),Ih.set(l,{wanted:r?.wantedFiles,firstLast:r?.firstLast}),t.hold===!0&&(Mh.add(l),o&&(Nh.add(l),e.setFlags(l,V.uploadMode,V.uploadMode))),qh(l,{down:r?.downloadLimit,up:r?.uploadLimit}),Vh.set(l,{activeSeconds:r?.activeSeconds??0,seedingSeconds:r?.seedingSeconds??0}),Uh.set(l,Gh(r)),Y.hold(l,Date.now());let u=Date.now();i&&await nh({infoHash:i,magnet:a,savePath:c,addedAt:u,lastUsedAt:u,ephemeral:o,started:!0,paused:!1},s?{savePath:c,saveTo:F_(r)}:void 0),L_(t,{type:`added`,handle:l,magnet:a}),Dh(),k_()}}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){X({type:`add-failed`,message:U.formatMessage({id:`That torrent could not be created`,defaultMessage:`That torrent could not be created`})});return}if(!r.some(e=>e)){X({type:`add-failed`,message:U.formatMessage({id:`Some of those files could not be opened`,defaultMessage:`Some of those files could not be opened`})});return}await Fo(el(n),i);let a=b_(e,{infoHash:n,magnet:t.magnet,bytes:i,handles:r,paused:!1});if(a===null){await Lo(el(n)).catch(()=>{}),X({type:`add-failed`,message:U.formatMessage({id:`The engine refused the torrent that was just built`,defaultMessage:`The engine refused the torrent that was just built`})});return}let o=Date.now();await nh({infoHash:n,magnet:t.magnet,savePath:ol(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,...qc({name:t.name,size:t.size,files:t.files}),...bl(i)||e.isPrivate?.(a)===!0?{private:!0}:{}}),X({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)){X({type:`add-failed`,message:U.formatMessage({id:`Some of those files could not be opened`,defaultMessage:`Some of those files could not be opened`})});return}let i=[...K.entries()].find(([,e])=>e===n);if(i){X({type:`added`,handle:i[0],magnet:Dm.get(i[0])??``});return}let a=await Po(el(n));if(!a?.byteLength){X({type:`add-failed`,message:U.formatMessage({id:`The torrent this was built from is no longer stored`,defaultMessage:`The torrent this was built from is no longer stored`})});return}let o=(await th()).find(e=>e.infoHash===n),s=await Po(hm(n)).catch(()=>void 0),c=b_(e,{infoHash:n,magnet:o?.magnet??t.magnet??``,bytes:a,handles:r,paused:o?.paused===!0,seedStopped:o?.seedStopped===!0,ephemeral:o?.ephemeral===!0});if(c===null){X({type:`add-failed`,message:U.formatMessage({id:`The engine refused that torrent`,defaultMessage:`The engine refused that torrent`})});return}s?.length&&e.addTrackers(c,s),Ih.set(c,{wanted:o?.wantedFiles,firstLast:o?.firstLast}),Mh.add(c),o?.forced&&!o.paused&&(J(c,`forced`,!0),uh(c)),o?.seedBypass&&!o.paused&&!o.seedStopped&&J(c,`seedBypass`,!0),Vh.set(c,{activeSeconds:o?.activeSeconds??0,seedingSeconds:o?.seedingSeconds??0}),Uh.set(c,Gh(o)),await Z(n,{started:!0,lastUsedAt:Date.now()}),X({type:`added`,handle:c,magnet:o?.magnet??``})}else if(t.type===`add-torrent-file`){let n=t.savePath||`/dl`,r=t.bytes,i=e.addTorrentFile(r,n);if(Xm(i)){L_(t,{type:`add-failed`,message:U.formatMessage({id:`That file is not a valid .torrent`,defaultMessage:`That file is not a valid .torrent`})});return}if(G.includes(i)){let n=!t.ephemeral&&Q.has(i)?K.get(i):void 0;if(n){let a=Array.isArray(t.wanted)?t.wanted.map(e=>Number(e)|0):void 0,o=t.firstLast===!0,s=t.saveTo===`browser`||t.saveTo===`folder`?{saveTo:t.saveTo}:{};await Fo(el(n),r),(a||o)&&(Ih.set(i,{wanted:a,firstLast:o}),Bg(i).length||(e.files(i)?zg(i):Mh.add(i))),t.sequential===!0&&e.setFlags(i,V.sequentialDownload,V.sequentialDownload),t.top===!0&&e.moveInQueue(i,`top`),await R_(i,n,{paused:t.paused===!0,patch:{...a?{wantedFiles:a}:{},...o?{firstLast:!0}:{},...t.paused===!0?{paused:!0}:{},...bl(r)||e.isPrivate?.(i)===!0?{private:!0}:{},...s}})}else t.ephemeral&&Q.has(i)&&ih(i);L_(t,{type:`added`,handle:i,magnet:Dm.get(i)??``},!n),!n&&!t.ephemeral&&typeof t.addId!=`string`&&X({type:`add-failed`,message:U.formatMessage({id:`Already in your list`,defaultMessage:`Already in your list`})});return}kh(i,``,null,n,t.ephemeral===!0);let a=Array.isArray(t.wanted)?t.wanted.map(e=>Number(e)|0):void 0,o=t.firstLast===!0;(a||o||t.paused===!0)&&(Ih.set(i,{wanted:a,firstLast:o}),Mh.add(i),Nh.add(i),e.setFlags(i,V.uploadMode,V.uploadMode)),t.sequential===!0&&e.setFlags(i,V.sequentialDownload,V.sequentialDownload),t.paused===!0&&(Bm(i,`user`),Km(i)),t.top===!0&&e.moveInQueue(i,`top`),Y.hold(i,Date.now());let s=null;for(let t=0;t<40&&!(s=e.infohash(i));t++)await new Promise(e=>setTimeout(e,250));let c=(await th()).find(e=>e.infoHash===s);if(!G.includes(i))return;if(!s){e.removeTorrent(i,!0),Ah(i),L_(t,{type:`add-failed`,message:U.formatMessage({id:`Could not read that torrent`,defaultMessage:`Could not read that torrent`})});return}let l=e.infohashV2(i),u=`magnet:?`+[...s.length===40?[`xt=urn:btih:${s}`]:[],...l?[`xt=urn:btmh:1220${l}`]:[]].join(`&`);kh(i,u,s,n,Gc(c,t.ephemeral===!0)),await Fo(el(s),r);let d=Date.now(),f=t.saveTo===`browser`||t.saveTo===`folder`?{saveTo:t.saveTo}:{};await nh({infoHash:s,magnet:u,savePath:n,addedAt:d,lastUsedAt:d,ephemeral:t.ephemeral===!0,started:!0,paused:Mm(i),wantedFiles:a,firstLast:o||void 0,...f,...t.created===!0?{created:!0}:{},...bl(r)||e.isPrivate?.(i)===!0?{private:!0}:{}},c&&P_(c)?{savePath:n,saveTo:F_(c),...f}:void 0),w_.delete(s),L_(t,{type:`added`,handle:i,magnet:u})}else if(t.type===`read`){if(!G.includes(t.handle)){X({type:`read-error`,id:t.id,error:Qh});return}if(t.prioritize!==!1&&!r_(t.handle,t.fileIndex,t.offset,t.len)&&(Nm(t.handle)&&fh.add(t.handle),jh(t.handle),Vm(t.handle,`seed-policy`)&&Zg(t.handle)),t.viewer||dh.set(t.handle,Date.now()),Mm(t.handle)&&!r_(t.handle,t.fileIndex,t.offset,t.len)){X({type:`read-error`,id:t.id,error:$h});return}if(t.prioritize!==!1)c_(t.viewer,t.handle,t.fileIndex,t.offset,t.len);else if(!r_(t.handle,t.fileIndex,t.offset,t.len)){X({type:`read-error`,id:t.id,error:`not downloaded`});return}let n=eg.get(t.handle);n||eg.set(t.handle,n=/* @__PURE__ */ new Map),n.set(t.id,{fileIndex:t.fileIndex,offset:t.offset,len:t.len,viewer:t.viewer}),M_();try{let r=0;for(let i=0;;i++)try{let r=t.viewer?$.get(t.handle)?.get(t.viewer)?.bulk===!0:!1,i=t.partial?i_(t.handle,t.fileIndex,t.offset,t.len):t.len,a=await e.read(t.handle,t.fileIndex,t.offset,i,{timeoutMs:Xh,...r?{deadlineMs:null}:{}});if(!n.has(t.id))return;X({type:`read-result`,id:t.id,data:a},[a.buffer]);return}catch(a){if(!n.has(t.id))return;if(!/did not arrive/.test(String(a))||t.viewer&&!$.get(t.handle)?.has(t.viewer))throw a;if(Zh(e)&&r<20)r++;else if(i+1-r>=18)throw a;let o=a_(t.handle,t.fileIndex,t.offset,t.len);X({type:`read-stalled`,id:t.id,handle:t.handle,fileIndex:t.fileIndex,offset:t.offset,len:t.len,waitedMs:(i+1)*Xh,missing:o,cancelled:Math.min(o.length,16),downloadRate:e.status(t.handle)?.downloadRate??null,numPeers:e.status(t.handle)?.numPeers??null});for(let n of o.slice(0,16))e.cancelPieceRequests(t.handle,n);let s=t.viewer?$.get(t.handle)?.get(t.viewer):void 0;t.prioritize!==!1&&t.viewer&&s&&!s.held&&$g(t.handle)}}finally{n.delete(t.id),!t.viewer&&G.includes(t.handle)&&dh.set(t.handle,Date.now())}}else if(t.type===`cancel-read`){let e=eg.get(t.handle);e&&(e.delete(t.id),e.size||eg.delete(t.handle))}else if(t.type===`remove`){let n=K.get(t.handle);rg(t.handle,Qh),e.removeTorrent(t.handle,!!t.deleteFiles),Ah(t.handle),n&&await oh(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;Ih.set(t.handle,{wanted:e,firstLast:n}),Bg(t.handle).length||zg(t.handle);let r=K.get(t.handle);r&&await Z(r,{wantedFiles:e,firstLast:n})}else if(t.type===`set-folder`)wm=t.folder??null;else if(t.type===`set-temporary`){if(typeof t.infoHash==`string`){let e=t.temporary===!0,n=G.find(e=>K.get(e)===t.infoHash);n!==void 0&&(e?(Q.add(n),J(n,`seedBypass`,!1)):(Q.delete(n),jh(n)),Bg(n).length&&$g(n)),await Z(t.infoHash,{ephemeral:e,...e?{seedBypass:!1}:{}})}}else if(t.type===`export-start`){let n=G.find(e=>K.get(e)===t.infoHash),r=n===void 0?void 0:q.get(n),i=n===void 0?null:e.files(n);if(n===void 0||!i||r===void 0||!Uc(r)||Nh.has(n)){X({type:`answer`,id:t.id,value:null});return}Ag.set(n,{running:(Ag.get(n)?.running??0)+1,until:Date.now()+kg});let a=await e.saveResumeData(n),o=i.files.flatMap((e,t)=>e.pad?[]:Cm.chunksOf(r,t).map(e=>({fileIndex:t,chunk:e})));X({type:`answer`,id:t.id,value:{magnet:Dm.get(n)??``,resume:a,chunkBytes:Cm.chunkBytesOf(r),chunks:o}})}else if(t.type===`export-chunk`){let e=G.find(e=>K.get(e)===t.infoHash),n=e===void 0?void 0:q.get(e),r=e===void 0?void 0:Ag.get(e);if(!r||n===void 0)throw Error(`that torrent is not being handed over`);r.until=Date.now()+kg;let i=await Cm.readChunk(n,t.fileIndex,t.chunk);X({type:`answer`,id:t.id,value:i},[i.buffer])}else if(t.type===`export-end`){let e=G.find(e=>K.get(e)===t.infoHash),n=e===void 0?void 0:Ag.get(e);if(e===void 0||!n)return;--n.running,n.running||Ag.delete(e)}else if(t.type===`import-start`){if(typeof t.infoHash!=`string`||typeof t.magnet!=`string`)throw Error(`nothing to list`);let e=Date.now();await nh({infoHash:t.infoHash,magnet:t.magnet,savePath:Hc(t.infoHash),addedAt:e,lastUsedAt:e,ephemeral:!1,started:!0,paused:!1}),X({type:`answer`,id:t.id,value:!0})}else if(t.type===`import`){let n=t.infoHash;if(typeof n!=`string`||!(t.resume instanceof Uint8Array)||G.some(e=>K.get(e)===n))return;let r=Hc(n);await Fo($c(n),t.resume);let i=e.addTorrentWithResume(t.resume,r);if(Xm(i)){X({type:`add-failed`,message:U.formatMessage({id:`That torrent could not be read`,defaultMessage:`That torrent could not be read`})});return}kh(i,t.magnet,n,r),Mh.add(i),qh(i,{down:0}),qm(i),Y.hold(i,Date.now()),X({type:`added`,handle:i,magnet:t.magnet})}else if(t.type===`reserve-storage`)typeof t.infoHash==`string`&&t.infoHash&&(t.on===!1?w_.delete(t.infoHash):w_.add(t.infoHash));else if(t.type===`set-location`)typeof t.infoHash==`string`&&await Z(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?G.find(e=>K.get(e)===n):void 0;n&&i!==void 0&&await y_(e,i,n,r)}else if(t.type===`import-list`){let n=[];await Io(Yc,e=>n=Xc(e,t.removed));let r=[],i=[],a=!1,o=[];await Io(Jc,e=>{o.length=0;let s=Qc(e??[],Array.isArray(t.list)?t.list:[],n);r=s.list,i=(e??[]).filter(e=>!r.includes(e)),a=i.length>0;let c=new Map(r.map(e=>[e.infoHash,e]));for(let e of s.incoming){if(!e||typeof e.infoHash!=`string`||!e.magnet)continue;let t=qc(e),n=c.get(e.infoHash);if(n){n.name===void 0&&t.name!==void 0&&(n.name=t.name,a=!0),n.size===void 0&&t.size!==void 0&&(n.size=t.size,a=!0),n.files===void 0&&t.files!==void 0&&(n.files=t.files,a=!0),e.private===!0&&n.private!==!0&&(n.private=!0,o.push(n.infoHash),a=!0);let r=pc(Gh(n),Gh(e));for(let e of oc)(n[e]??0)!==r[e]&&(n[e]=r[e],a=!0);continue}let i={infoHash:e.infoHash,magnet:e.magnet,savePath:e.savePath||`/dl`,addedAt:e.addedAt||Date.now(),started:!1,ephemeral:!1,...t,...Gh(e),...e.private===!0?{private:!0}:{}};r.push(i),c.set(i.infoHash,i),a=!0}return r});for(let e of i)await ah(e.infoHash);let s=/* @__PURE__ */ new Map;for(let t of o){let n=G.find(e=>K.get(e)===t);n!==void 0&&e.isPrivate?.(n)!==!0&&(rg(n,$h),e.removeTorrent(n,!1),Ah(n),s.set(t,{started:!1}))}s.size&&(await rh(s,!0),r=await th(),a=!0),a&&X({type:`list`,list:r,synced:!0})}else if(t.type===`start`||t.type===`start-many`)await I_(e,t.type===`start`?[t.infoHash]:Array.isArray(t.infoHashes)?t.infoHashes:[]);else if(t.type===`remove-missing`){if(typeof t.infoHash==`string`){let n=G.find(e=>K.get(e)===t.infoHash);n!==void 0&&(rg(n,Qh),e.removeTorrent(n,!0),Ah(n)),await oh(t.infoHash)}}else if(t.type===`clear-list`){for(let t of[...G])rg(t,Qh),e.removeTorrent(t,!0),Ah(t);let t=[];await Io(Jc,e=>(t=e??[],[])),await Lo(Yc).catch(()=>{});for(let e of t)await Lo($c(e.infoHash)).catch(()=>{}),await Lo(el(e.infoHash)).catch(()=>{}),await Lo(hm(e.infoHash)).catch(()=>{});X({type:`list`,list:[],synced:!0})}else if(t.type===`pause`){Bm(t.handle,`user`),J(t.handle,`userStarted`,!1),J(t.handle,`forced`,!1),J(t.handle,`seedBypass`,!1),Y.forget(t.handle),e.pauseTorrent(t.handle),rg(t.handle,$h),sg(t.handle);let n=K.get(t.handle);n&&await Z(n,{paused:!0,resumed:!1,forced:!1,seedStopped:!1,seedBypass:!1})}else if(t.type===`resume`||t.type===`force-start`){let n=Pm(t.handle);Vm(t.handle);let r=Q.has(t.handle);r&&J(t.handle,`userStarted`,!0),(n||sh.has(e.status(t.handle)?.state??-1))&&J(t.handle,`seedBypass`,!0);let i=t.type===`force-start`;J(t.handle,`forced`,i),qm(t.handle),Y.forget(t.handle),uh(t.handle),Y.hold(t.handle,Date.now());let a=K.get(t.handle);a&&await Z(a,{paused:!1,resumed:r,forced:i,seedStopped:!1,seedBypass:zm(t.handle)})}else if(t.type===`recheck`){let n=K.get(t.handle);n&&await Lo($c(n)).catch(()=>{}),Om.delete(t.handle),rg(t.handle,U.formatMessage({id:`torrent rechecking`,defaultMessage:`torrent rechecking`})),Vm(t.handle),Wm.delete(t.handle),Gm.delete(t.handle),fh.delete(t.handle),J(t.handle,`seedBypass`,!1),Y.forget(t.handle),e.forceRecheck(t.handle),lh(t.handle)&&e.setFlags(t.handle,0,V.autoManaged),Y.hold(t.handle,Date.now()),n&&await Z(n,{paused:!1,seedStopped:!1,seedBypass:!1})}else if(t.type===`retry-now`)Y.retryNow(Date.now());else if(t.type===`retry`)Y.retry(t.handle,Date.now());else if(t.type===`flush-resume`)await Promise.all(G.map(async e=>{await og.get(e),await sg(e)})),t.id!==void 0&&X({type:`answer`,id:t.id});else if(t.type===`watch`)t.readLen==null?t_(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.held===!0,t.bulk===!0||void 0,t.prepare===!0):c_(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.readLen),M_();else if(t.type===`unwatch`)n_(e=>e===t.viewer);else if(t.type===`set-flags`)e.setFlags(t.handle,t.flags>>>0,t.mask>>>0),sg(t.handle);else if(t.type===`reannounce`)e.forceReannounce(t.handle);else if(t.type===`add-trackers`){let n=e.addTrackers(t.handle,t.urls);hh=0;let r=K.get(t.handle),i=t.urls.filter(e=>!n.includes(e));r&&i.length&&sl(q.get(t.handle))&&await Io(hm(r),e=>[.../* @__PURE__ */ new Set([...e??[],...i])]).catch(()=>{}),(async()=>{await og.get(t.handle),await sg(t.handle)})(),X({type:`answer`,id:t.id,value:n})}else if(t.type===`queue-move`)e.moveInQueue(t.handle,t.where);else if(t.type===`set-limits`){let e=Ml(t.down)?t.down:void 0,n=Ml(t.up)?t.up:void 0;qh(t.handle,{down:e,up:n});let r=K.get(t.handle);if(r){let t={};e!==void 0&&(t.downloadLimit=e),n!==void 0&&(t.uploadLimit=n),Object.keys(t).length&&await Z(r,t)}}else if(t.type===`set-session-limits`){let n={down:Ml(t.down)?t.down:Lh.down,up:Ml(t.up)?t.up:Lh.up};await Fo(jl,{...n}).catch(()=>{}),Lh=n,e.setRateLimits({download:n.down,upload:n.up}),Dh()}else if(t.type===`set-seeding-policy`){let e=Bl(t.policy);if(!Vl(ch,e)){Hm();let e=new Map((await th()).filter(e=>e.seedBypass).map(e=>[e.infoHash,{seedBypass:!1}]));e.size&&await rh(e,!0).catch(()=>{})}ch=e,await Fo(Pl,ch).catch(()=>{}),Qg()}else if(t.type===`inspect`){let e=typeof t.handle==`number`?t.handle:null;e!==mh&&(mh=e,hh=0)}else if(t.type===`torrent-detail`){if(typeof t.handle!=`number`||!G.includes(t.handle))X({type:`answer`,id:t.id,value:null});else{let[n,r]=await Promise.all([e.peers(t.handle),e.trackers(t.handle)]);if(!G.includes(t.handle))X({type:`answer`,id:t.id,value:null});else{let e=[..._m?r:r.map(Eh),...vm?.trackers(t.handle)??[]];X({type:`answer`,id:t.id,value:{peers:n,trackers:e}})}}}else t.type===`unwatch-owner`&&n_(e=>e.startsWith(t.owner+`:`))}catch(e){t.type===`read`?X({type:`read-error`,id:t.id,error:String(e?.stack??e)}):typeof t.addId==`string`?L_(t,{type:`add-failed`,message:String(e?.message??e)}):Bc.has(t.type)&&t.type!==`start-many`?X({type:`answer`,id:t.id,error:String(e?.message??e)}):X({type:`error`,message:String(e?.stack??e)})}},B_=/* @__PURE__ */ new Set([`read`,`cancel-read`,`add-torrent-file`,`export-chunk`,`torrent-detail`]);let V_=Promise.resolve();self.addEventListener(`message`,e=>{let t=e.data;if(!t||typeof t!=`object`||typeof t.type!=`string`||!pm.has(t.type))return;if(t.type===`close-sockets`){j_=!0,vm?.close(),Promise.resolve(_m?.close()).then(()=>X({type:`answer`,id:t.id}));return}let n=W;if(!n){t.type===`read`?X({type:`read-error`,id:t.id,error:`the engine is still starting`}):Bc.has(t.type)?X({type:`answer`,id:t.id,error:`worker not initialized`}):X({type:`error`,message:`worker not initialized`});return}if(B_.has(t.type)){z_(n,t);return}t.type===`start-many`&&X({type:`answer`,id:t.id,value:!0}),V_=V_.then(()=>z_(n,t))}),N_().catch(e=>X({type:Em?`error`:`fatal`,message:String(e?.stack??e)}));
|