@banou/ripple 0.0.118 → 0.0.120
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/{libtorrent-53Uv1CpQ.js → libtorrent-CSPif8Ur.js} +1 -1
- package/assets/{libtorrent-BSo_oOmW.wasm → libtorrent-iTDF1t5e.wasm} +0 -0
- package/assets/{remote-1t0WFolM.js → remote-8qGq46o-.js} +1 -1
- package/assets/{worker-BmI22fKm.js → worker-CmHq4V6n.js} +8 -8
- package/fkn.json +1 -1
- package/{index-Bflv0V8N.js → index-CJzcf3ef.js} +7 -4
- package/index.html +1 -1
- package/package.json +2 -2
- package/sw.js +2 -2
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
var e=Object.defineProperty,t=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),n=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};(e=>{e.global||=e;let t=e.process??={};t.env??={NODE_DEBUG:``},(typeof t.env!=`object`||t.env===null)&&(t.env={NODE_DEBUG:``}),t.version??=``,t.browser??=!0,t.platform??=`browser`,t.nextTick??=(e,...t)=>queueMicrotask(()=>e(...t)),t.emit??=()=>!1,t.on??=()=>t,t.once??=()=>t,t.off??=()=>t,t.removeListener??=()=>t,t.cwd??=()=>`/`})(typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:{});var r=/* @__PURE__ */ `fkn.app,fkn.dev,sdbx.app,horionsoftware.com,webvpn.dev,fknmail.app,clairv.app,fkn.cloudflareaccess.com,me-62e.workers.dev,62e9d4fbf21d90ebd4342e54b4babbd3.r2.cloudflarestorage.com,62e9d4fbf21d90ebd4342e54b4babbd3.eu.r2.cloudflarestorage.com,62e9d4fbf21d90ebd4342e54b4babbd3.fedramp.r2.cloudflarestorage.com,pub-8a3dc68041874c7e9c9a54bde972605a.r2.dev,pub-26b534eb9aa04cffbe1cdbb3be3fb1d2.r2.dev,pub-3d97d79220b94243812e60b0e742f2c5.r2.dev,pub-f8bd4876cc3c4b4a951715da5958e49c.r2.dev,web-b3z.pages.dev,fkn-console.pages.dev,dev-dms.pages.dev,fkn-www.pages.dev,fkn-homepage.pages.dev,fkn-sandbox.pages.dev,internal-3ar.pages.dev,stub-ben.pages.dev,ripple-3t3.pages.dev,media-player-e3s.pages.dev,youtube-3c4.pages.dev,horionsoftware.pages.dev,container-ckf.pages.dev,stub-plugin.pages.dev,social-3n2.pages.dev,plugins.banou.dev`.split(`,`),i=e=>e.toLowerCase().replace(/\.+$/,``),a=[`79.127.204.69`,`152.233.49.59`],o=e=>{let t;try{t=new URL(`http://${e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}/`).hostname}catch{return}let n=/^\[(?:::ffff:|64:ff9b::)([0-9a-f]{1,4}):([0-9a-f]{1,4})\]$/.exec(t);if(n){let e=parseInt(n[1],16),t=parseInt(n[2],16);return[e>>8,e&255,t>>8,t&255].join(`.`)}return/^\d+\.\d+\.\d+\.\d+$/.test(t)?t:void 0},s=e=>{let t=i(e);return r.some(e=>t===e||t.endsWith(`.${e}`))},c=e=>{if(s(e))return!0;let t=o(i(e));return t!==void 0&&a.includes(t)},l=/* @__PURE__ */ `autoplay.fullscreen.picture-in-picture.encrypted-media.screen-wake-lock.speaker-selection.captured-surface-control.camera.microphone.display-capture.geolocation.midi.usb.serial.hid.bluetooth.gamepad.keyboard-map.xr-spatial-tracking.accelerometer.gyroscope.magnetometer.ambient-light-sensor.compute-pressure.clipboard-read.clipboard-write.storage-access.window-management.local-fonts.idle-detection.web-share.sync-xhr.unload.payment.publickey-credentials-get.publickey-credentials-create.otp-credentials.identity-credentials-get.digital-credentials-get.local-network.local-network-access.loopback-network`.split(`.`),u=()=>{try{let e=globalThis.document?.featurePolicy?.features?.();return e===void 0?void 0:new Set(e)}catch{return}},d=(e=!0,t=u())=>[...l,...e?[`cross-origin-isolated`]:[]].filter(e=>t===void 0||t.has(e)).join(`; `),f=`https://fkn.app`,p=e=>`${f}/api${e?`?coi=1`:``}`;`${JSON.stringify(l)}${JSON.stringify(p(!0))}${JSON.stringify(p(!1))}`;var m=((e,t,n,r)=>{if(r?.signal?.aborted)return()=>{};let i=()=>e.addEventListener(t,n,r);i();let a=typeof MutationObserver>`u`?void 0:new MutationObserver(i);return a?.observe(e.window===e?e.document:e,{childList:!0}),r?.signal?.addEventListener(`abort`,()=>a?.disconnect(),{once:!0}),()=>{a?.disconnect(),e.removeEventListener(t,n,r)}}),h=Symbol.for(`fkn.lib.headerOpener`),g=e=>{let t=globalThis;e?t[h]=e:delete t[h]},_=(e,t)=>{let n=Promise.resolve().then(e).then(e=>e===!0,()=>!1),r,i=new Promise(e=>{r=setTimeout(e,t,!1)});return Promise.race([n,i]).finally(()=>{r!==void 0&&clearTimeout(r)})},v=typeof window<`u`||typeof self<`u`,y=Object.defineProperty,b=(e,t)=>{let n={};for(var r in e)y(n,r,{get:e[r],enumerable:!0});return t||y(n,Symbol.toStringTag,{value:`Module`}),n},x=`__OSRA_KEY__`,S=`__OSRA_DEFAULT_KEY__`,C=`__OSRA_BOX__`,w=()=>globalThis.browser??globalThis.chrome,T=()=>w()?.runtime,E=(e,t)=>se(e)&&e.__OSRA_KEY__===t,D=(e,t)=>{if(e){if(e.aborted){t();return}e.addEventListener(`abort`,t,{once:!0})}},O=({listener:e,transport:t,remoteName:n,key:r=S,origin:i=`*`,unregisterSignal:a})=>{if(a?.aborted)return;let o=we(t)?t.receive:t;if(typeof o==`function`){let t=o((t,i)=>{a?.aborted||E(t,r)&&(n&&t.name!==n||e(t,i))});typeof t==`function`&&D(a,t);return}if(R(o)||de(o)||pe(o)||me(o)){let t=(t,i)=>{let o=(t,a)=>{E(t,r)&&(n&&t.name!==n||e(t,{port:i,sender:a}))};t.addListener(o),D(a,()=>t.removeListener(o))};if(R(o))t(o.onMessage);else if(pe(o)){let e=e=>t(e.onMessage,e);o.addListener(e),D(a,()=>o.removeListener(e))}else me(o)?t(o):t(o.onMessage);return}let s=ae(o)?o.port:o,c=i!==`*`&&he(o),l=t=>{let a=t.data;if(typeof a==`string`)try{a=JSON.parse(a)}catch{return}E(a,r)&&(n&&a.name!==n||c&&t.origin&&t.origin!==i||e(a,{receiveTransport:o,source:t.source,origin:t.origin}))};s.addEventListener(`message`,l),s instanceof MessagePort&&s.start(),D(a,()=>s.removeEventListener(`message`,l))},ee=/* @__PURE__ */ new WeakSet,k=e=>String(e?.message??e).includes(`disconnected port`),te=(e,t,n=`*`,r=[])=>{let i=we(e)?e.emit:e;if(typeof i==`function`)i(t,r);else if(he(i))i.postMessage(t,n,r);else if(de(i)){if(ee.has(i))return;try{i.postMessage(t)}catch(e){if(!k(e))throw e;ee.add(i)}}else if(R(i))i.sendMessage(t)?.catch?.(e=>{if(!String(e?.message).includes(`Receiving end does not exist`))throw e});else if(F(i)){let e=JSON.stringify(t);i.readyState===WebSocket.CONNECTING?i.addEventListener(`open`,()=>i.send(e),{once:!0}):i.send(e)}else ae(i)?i.port.postMessage(t,r):i.postMessage(t,r)},A=globalThis.Float16Array,ne={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float16Array:A,Float32Array,Float64Array,BigInt64Array,BigUint64Array},j=Object.values(ne),M=e=>{let t=e.constructor.name;if(t in ne)return t;for(let[t,n]of Object.entries(ne))if(n&&e instanceof n)return t;throw Error(`Unknown typed array type`)},N=e=>{let t=ne[e];if(!t)throw Error(`Unknown typed array type`);return t},P=e=>ce(e,j),F=e=>e instanceof WebSocket,re=e=>!!globalThis.ServiceWorkerContainer&&e instanceof ServiceWorkerContainer,I=e=>!!globalThis.ServiceWorker&&e instanceof ServiceWorker,L=e=>!!globalThis.Worker&&e instanceof Worker,ie=e=>{let t=globalThis.DedicatedWorkerGlobalScope;return!!t&&e instanceof t},ae=e=>!!globalThis.SharedWorker&&e instanceof SharedWorker,oe=e=>e instanceof MessagePort,se=e=>!!e&&typeof e==`object`&&`__OSRA_KEY__`in e&&!!e.__OSRA_KEY__,ce=(e,t)=>{if(e===null||typeof e!=`object`&&typeof e!=`function`)return!1;for(let n of t)if(n&&e instanceof n)return!0;return!1},le=e=>ce(e,[globalThis.SharedArrayBuffer]),ue=e=>ce(e,[globalThis.ArrayBuffer,globalThis.MessagePort,globalThis.ReadableStream,globalThis.WritableStream,globalThis.TransformStream,globalThis.ImageBitmap,globalThis.OffscreenCanvas,globalThis.AudioData,globalThis.VideoFrame,globalThis.MediaSourceHandle,globalThis.MediaStreamTrack,globalThis.MIDIAccess,globalThis.RTCDataChannel,globalThis.WebTransportReceiveStream,globalThis.WebTransportSendStream]),R=e=>{let t=T();return t?e===t:!1},de=(e,t=!1)=>!e||typeof e!=`object`||he(e)||!(`name`in e)||!(`disconnect`in e)||!(`postMessage`in e)?!1:!t||`sender`in e&&`onMessage`in e&&`onDisconnect`in e,fe=e=>!!e&&typeof e==`object`&&!he(e)&&`addListener`in e&&`hasListener`in e&&`removeListener`in e,pe=e=>{let t=T();return t?e===t.onConnect||e===t.onConnectExternal:!1},me=e=>fe(e),he=e=>{if(!e||typeof e!=`object`)return!1;try{return`window`in e&&e.window===e}catch{try{return`closed`in e&&typeof e.closed==`boolean`&&`close`in e&&typeof e.close==`function`}catch{return!1}}},ge=e=>F(e)||de(e)||R(e),_e=e=>F(e)||de(e)||pe(e)||me(e)||R(e),ve=e=>!!e&&typeof e==`object`&&!he(e)&&`isJson`in e&&e.isJson===!0||ge(e)||_e(e),ye=e=>he(e)||ge(e)||I(e)||L(e)||ie(e)||ae(e)||oe(e)||Se(e),be=e=>he(e)||_e(e)||re(e)||L(e)||ie(e)||ae(e)||oe(e)||Ce(e),xe=e=>{if(!e||typeof e!=`object`||he(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Se=e=>!xe(e)||!(`emit`in e)?!1:ye(e.emit)||typeof e.emit==`function`,Ce=e=>!xe(e)||!(`receive`in e)?!1:be(e.receive)||typeof e.receive==`function`,we=e=>Se(e)||Ce(e),Te=()=>globalThis.Buffer,Ee=32768,De=e=>{let t=e.toBase64;if(typeof t==`function`)return t.call(e);let n=Te();if(n)return n.from(e).toString(`base64`);let r=``;for(let t=0;t<e.length;t+=Ee)r+=String.fromCharCode(...e.subarray(t,t+Ee));return btoa(r)},Oe=e=>{let t=Uint8Array.fromBase64;if(typeof t==`function`)return t(e);let n=Te();if(n)return new Uint8Array(n.from(e,`base64`));let r=atob(e),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return i},z={[C]:`revivable`},ke=e=>!!e&&typeof e==`object`&&`__OSRA_BOX__`in e&&e.__OSRA_BOX__===`revivable`,Ae=(e,t)=>ve(t.transport)?{base64Buffer:De(new Uint8Array(e))}:{arrayBuffer:e},je=e=>`arrayBuffer`in e?e.arrayBuffer:Oe(e.base64Buffer).buffer,Me=e=>{if(!e||typeof e!=`object`||Array.isArray(e)||!Object.hasOwn(e,`__OSRA_BOX__`)||!Object.hasOwn(e,`box`)||!Object.hasOwn(e,`value`)||Object.keys(e).length!==3)return!1;let t=e;if(t.__OSRA_BOX__!==`quoted`||t.box!==`revivable`&&t.box!==`quoted`)return!1;let n=t.value;return!!n&&typeof n==`object`&&!Array.isArray(n)},Ne=e=>{if(!Me(e))return!1;let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return!1;let n=Object.getPrototypeOf(e.value);return n===Object.prototype||n===null},Pe=0,Fe=()=>Pe>0,Ie=e=>{Pe++;try{return e()}finally{Pe--}},Le=e=>{let t=Pe;Pe=0;try{return e()}finally{Pe=t}},Re=/* @__PURE__ */ b({box:()=>Ve,isType:()=>Be,objectsOnly:()=>!0,revive:()=>He,type:()=>ze}),ze=`arrayBuffer`,Be=e=>e instanceof ArrayBuffer,Ve=(e,t)=>({...z,type:ze,...Ae(e,t)}),He=(e,t)=>je(e),Ue=/* @__PURE__ */ b({box:()=>Ke,isType:()=>Ge,objectsOnly:()=>!0,revive:()=>qe,type:()=>We}),We=`date`,Ge=e=>e instanceof Date,Ke=(e,t)=>({...z,type:We,ISOString:e.toISOString()}),qe=(e,t)=>new Date(e.ISOString),Je=/* @__PURE__ */ b({box:()=>Ze,isType:()=>Xe,objectsOnly:()=>!0,revive:()=>Qe,type:()=>Ye}),Ye=`headers`,Xe=e=>e instanceof Headers,Ze=(e,t)=>({...z,type:Ye,entries:[...e.entries()]}),Qe=(e,t)=>new Headers(e.entries),$e=/* @__PURE__ */ b({box:()=>rt,isType:()=>nt,objectsOnly:()=>!0,revive:()=>it,type:()=>et}),et=`error`,tt={Error,TypeError,RangeError,SyntaxError,ReferenceError,EvalError,URIError},nt=e=>e instanceof Error,rt=(e,t)=>{let n=`cause`in e&&e.cause!==void 0,r=typeof AggregateError<`u`&&e instanceof AggregateError,i=typeof DOMException<`u`&&e instanceof DOMException;return{...z,type:et,name:e.name,message:e.message,stack:e.stack||e.toString(),...n?{cause:B(e.cause,t)}:{},...r?{errors:B(e.errors,t)}:{},...i?{isDOMException:!0}:{}}},it=(e,t)=>{let n=e.cause===void 0?void 0:Di(e.cause,t),r=n===void 0?void 0:{cause:n};if(e.isDOMException&&typeof DOMException<`u`){let t=new DOMException(e.message,e.name);if(e.stack)try{Object.defineProperty(t,"stack",{value:e.stack,configurable:!0})}catch{}return t}let i;if(e.errors!==void 0&&typeof AggregateError<`u`)i=AggregateError(Di(e.errors,t),e.message,r);else{let t=tt[e.name]??Error;i=r===void 0?new t(e.message):new t(e.message,r)}return e.name&&i.name!==e.name&&(i.name=e.name),e.stack&&(i.stack=e.stack),i},at=/* @__PURE__ */ b({box:()=>ct,isType:()=>st,objectsOnly:()=>!0,revive:()=>lt,type:()=>ot}),ot=`typedArray`,st=P,ct=(e,t)=>{let n=e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);return{...z,type:ot,typedArrayType:M(e),...Ae(n,t)}},lt=(e,t)=>new(N(e.typedArrayType))(je(e)),ut=/* @__PURE__ */ new WeakMap,dt=/* @__PURE__ */ new WeakSet,ft=(e,t)=>{if(dt.has(e))return t(),()=>{};let n=ut.get(e);return n||ut.set(e,n=/* @__PURE__ */ new Set),n.add(t),()=>n.delete(t)},pt=e=>dt.has(e),mt=e=>{if(dt.has(e))return;dt.add(e);let t=ut.get(e);if(t){ut.delete(e);for(let e of t)try{e()}catch{}}},ht=/* @__PURE__ */ b({box:()=>Dt,forceTransfer:()=>wt,isInTransfer:()=>Ct,isType:()=>Et,objectsOnly:()=>!0,outsideTransfer:()=>Tt,revive:()=>Ot,transfer:()=>xt,type:()=>gt}),gt=`transfer`,_t=Symbol.for(`osra.transfer`),vt=e=>typeof e==`object`&&!!e,yt=e=>vt(e)&&_t in e&&e[_t]===!0,bt=e=>vt(e)?ArrayBuffer.isView(e)?!0:ce(e,[globalThis.ArrayBuffer,globalThis.MessagePort,globalThis.ReadableStream,globalThis.WritableStream,globalThis.TransformStream,globalThis.Request,globalThis.Response,globalThis.ImageBitmap,globalThis.OffscreenCanvas,globalThis.VideoFrame,globalThis.AudioData]):!1,xt=e=>bt(e)?{[_t]:!0,value:e}:e,St=0,Ct=()=>St>0,wt=e=>vt(e)&&!yt(e)?{[_t]:!0,value:e}:e,Tt=e=>{let t=St;St=0;try{return Le(e)}finally{St=t}},Et=e=>yt(e),Dt=(e,t)=>{St++;try{return{...z,type:gt,inner:B(e.value,t),degraded:ve(t.transport)}}finally{St--}},Ot=(e,t)=>Di(e.inner,t),kt=e=>ce(e,[globalThis.MessagePort,globalThis.ReadableStream,globalThis.WritableStream,globalThis.TransformStream,globalThis.OffscreenCanvas,globalThis.MediaSourceHandle,globalThis.MediaStreamTrack,globalThis.MIDIAccess,globalThis.RTCDataChannel,globalThis.WebTransportReceiveStream,globalThis.WebTransportSendStream]),At=e=>ke(e)&&e.type===`transfer`,jt=e=>{let t=/* @__PURE__ */ new WeakSet,n=e;for(;Ne(n);){if(t.has(n))return;t.add(n);let e=n.value;if(n.box===`revivable`)return e&&typeof e==`object`&&Object.hasOwn(e,`type`)&&e.type===`transfer`&&Object.hasOwn(e,`inner`)&&Object.hasOwn(e,`degraded`)&&typeof e.degraded==`boolean`?e:void 0;n=e}},Mt=e=>{let t=[],n=/* @__PURE__ */ new WeakSet,r=(e,i)=>{if(!e||typeof e!=`object`||n.has(e)||(n.add(e),le(e)))return;if(At(e)){r(e.inner,i||!e.degraded);return}let a=jt(e);if(a){r(a.inner,i||!a.degraded);return}if(kt(e)){t.push(e);return}if(ue(e)){i&&t.push(e);return}if(ArrayBuffer.isView(e)){i&&e instanceof DataView&&!le(e.buffer)&&!n.has(e.buffer)&&(n.add(e.buffer),t.push(e.buffer));return}if(Array.isArray(e)){for(let t of e)r(t,i);return}for(let t of Object.values(e))r(t,i)};return r(e,!1),t},Nt=class{_listeners=/* @__PURE__ */ new Map;addEventListener(e,t,n){if(!t)return;let r=this._listeners.get(e);r||(r=/* @__PURE__ */ new Map,this._listeners.set(e,r)),r.has(t)||r.set(t,typeof n==`object`&&!!n?.once)}removeEventListener(e,t,n){t&&this._listeners.get(e)?.delete(t)}_peer;_queue=[];_started=!1;_closed=!1;_onClose;_onmessage=null;get onmessage(){return this._onmessage}set onmessage(e){this._onmessage=e,e!==null&&this.start()}onmessageerror=null;dispatchEvent(e){e.type===`message`?this._onmessage?.call(this,e):e.type===`messageerror`&&this.onmessageerror?.call(this,e);let t=this._listeners.get(e.type);if(t)for(let[n,r]of[...t])r&&t.delete(n),typeof n==`function`?n.call(this,e):n.handleEvent(e);return!0}postMessage(e,t){let n=this._peer;n&&!n._closed&&queueMicrotask(()=>{if(n._closed)return;let t=new MessageEvent(`message`,{data:e});n._started?n.dispatchEvent(t):n._queue.push(t)})}start(){if(!this._started){this._started=!0;for(let e of this._queue.splice(0))this.dispatchEvent(e)}}close(){if(this._closed)return;this._closed=!0,this._queue.length=0,this._onClose?.();let e=this._peer;e&&!e._closed&&queueMicrotask(()=>{e._closed||e.dispatchEvent(new Event(`close`))})}},Pt=class{port1;port2;constructor(){let e=new Nt,t=new Nt;e._peer=t,t._peer=e,this.port1=e,this.port2=t}},Ft=new FinalizationRegistry(e=>{try{e()}catch{}}),It=(e,t)=>{let n={};return Ft.register(e,t,n),()=>Ft.unregister(n)},Lt=/* @__PURE__ */ b({box:()=>on,createRevivableChannel:()=>fn,init:()=>Yt,isType:()=>Xt,markPortsShipped:()=>un,objectsOnly:()=>!0,postPreBoxed:()=>rn,revive:()=>sn,type:()=>Rt}),Rt=`messagePort`,zt=2048,Bt=128,Vt=1024,Ht=/* @__PURE__ */ new WeakMap,Ut=e=>{let t=Ht.get(e);if(!t)throw Error(`osra message-port: connection state missing; did init() run?`);return t},Wt=(e,t)=>{let n=e.ports.get(t);return n||(n={nextSeq:0,buffer:/* @__PURE__ */ new Map,outSeq:0},e.ports.set(t,n),e.pendingPorts++),n},Gt=(e,t)=>{let n=e.ports.get(t);if(n&&!n.handler&&e.pendingPorts--,e.ports.delete(t),e.tombstones.size>=Bt){let t=e.tombstones.values().next().value;t!==void 0&&e.tombstones.delete(t)}e.tombstones.add(t)},Kt=e=>{if(e.handler)for(let t=e.buffer.get(e.nextSeq);t!==void 0;t=e.buffer.get(e.nextSeq))e.buffer.delete(e.nextSeq),e.nextSeq++,e.handler(t)},qt=(e,t)=>Wt(Ut(e),t).outSeq++,Jt=(e,t,n)=>{let r=Ut(e);if(r.tombstones.has(t)){setTimeout(()=>n({type:`message-port-close`,remoteUuid:e.remoteUuid,portId:t}));return}let i=Wt(r,t);i.handler||r.pendingPorts--,i.handler=n,Kt(i)},Yt=e=>{let t={ports:/* @__PURE__ */ new Map,tombstones:/* @__PURE__ */ new Set,pendingPorts:0};Ht.set(e,t),e.eventTarget.addEventListener(`message`,({detail:n})=>{if(n.type!==`message`&&n.type!==`message-port-close`||t.tombstones.has(n.portId))return;let r=t.ports.get(n.portId);if(n.seq===void 0){r?.handler?.(n);return}if(!r){if(t.pendingPorts>=Vt)return;r=Wt(t,n.portId)}if(!(n.seq<r.nextSeq)){if(r.buffer.size>=zt&&!(n.seq===r.nextSeq&&r.handler)){r.buffer.clear(),Gt(t,n.portId),r.handler?.({type:`message-port-close`,remoteUuid:e.remoteUuid,portId:n.portId});return}r.buffer.set(n.seq,n),Kt(r)}}),ft(e,()=>{for(let[n,r]of[...t.ports])r.handler?.({type:`message-port-close`,remoteUuid:e.remoteUuid,portId:n});t.ports.clear(),t.tombstones.clear(),t.pendingPorts=0})},Xt=e=>e instanceof MessagePort||e instanceof Nt,Zt=(e,t)=>{try{let n=Ut(e).ports.get(t);e.sendMessage({type:`message-port-close`,remoteUuid:e.remoteUuid,portId:t,seq:n?n.outSeq++:0})}catch{}},Qt=(e,t,n)=>{if(n){e.postMessage(t);return}let r=Mt(t);e.postMessage(t,r),un(r)},$t=(e,t,n,r)=>{let i;try{i=Di(e,t)}catch(e){r(),globalThis.reportError?.(e);return}n(i)},en=(e,t,n)=>()=>{let r=e.deref();r&&Zt(r,n);let i=t.deref();i&&Gt(i,n)},tn=/* @__PURE__ */ new WeakSet,nn=e=>e!==null&&(typeof e==`object`||typeof e==`function`),rn=(e,t,n)=>{nn(t)&&tn.add(t),e.postMessage(t,n??[])},an=(e,t)=>nn(e)&&tn.delete(e)?e:Tt(()=>Ie(()=>B(e,t))),on=(e,t,n)=>{let r=e instanceof Nt;if(!r&&!ve(t.transport))return{...z,type:Rt,port:e,...n?.autoBox?{autoBox:!0}:{}};let i=Ut(t),a=e,o=globalThis.crypto.randomUUID(),s=new WeakRef(a),c=new WeakRef(t),l=new WeakRef(i),u=!1,d=()=>{if(u)return;u=!0;let e=l.deref();e&&Gt(e,o),m?.();let t=s.deref();t?.removeEventListener(`message`,p),t instanceof Nt&&(t._onClose=void 0)},f=e=>{if(e.type===`message-port-close`){d(),a.dispatchEvent(new Event(`close`)),a.close();return}$t(e.data,t,e=>Qt(a,e,!1),()=>{})};function p({data:e}){let n;try{n=an(e,t)}catch(e){globalThis.reportError?.(e);return}t.sendMessage({type:`message`,remoteUuid:t.remoteUuid,data:n,portId:o,seq:qt(t,o)})}let m=It(a,en(c,l,o));return a.addEventListener(`message`,p),a.start(),a instanceof Nt&&(a._onClose=()=>{u||(Zt(t,o),d())}),Jt(t,o,f),{...z,type:Rt,portId:o,synthetic:r}},sn=(e,t)=>`port`in e?(un([e.port],!1),e.autoBox?dn(e.port,t):e.port):pn(e.portId,t,e.synthetic),cn=/* @__PURE__ */ new WeakMap,ln=/* @__PURE__ */ new WeakMap,un=(e,t=!0)=>{for(let n of e){let e=cn.get(n);if(e){cn.delete(n),e.shipped=!0;for(let t of e.pending.splice(0))t()}if(t){let e=ln.get(n);e&&(ln.delete(n),e())}}},dn=(e,t,n)=>{let r=new EventTarget,i=({data:e})=>{$t(e,t,e=>r.dispatchEvent(new MessageEvent(`message`,{data:e})),()=>r.dispatchEvent(new Event(`messageerror`)))},a=()=>{r.dispatchEvent(new Event(`messageerror`))},o=()=>{r.dispatchEvent(new Event(`close`))};e.addEventListener(`message`,i),e.addEventListener(`messageerror`,a),e.addEventListener(`close`,o),r.postMessage=(r,i)=>{let a=Tt(()=>B(r,t)),o=Mt(a),s=Array.isArray(i)?i:[],c=s.length?[...o,...s]:o,l=()=>{e.postMessage(a,c),un(c)};if(n&&!n.shipped){n.pending.push(l);return}l()},r.start=()=>e.start();let s=()=>{e.removeEventListener(`message`,i),e.removeEventListener(`messageerror`,a),e.removeEventListener(`close`,o),e.close()};return r.close=()=>{if(n&&!n.shipped){n.pending.push(s);return}s()},r},fn=e=>{if(ve(e.transport)){let{port1:t,port2:n}=new Pt;return{localPort:t,boxedRemote:on(n,e)}}let{port1:t,port2:n}=new MessageChannel,r={shipped:!1,pending:[]};return cn.set(n,r),{localPort:dn(t,e,r),boxedRemote:on(n,e,{autoBox:!0})}},pn=(e,t,n)=>{let r=Ut(t),{port1:i,port2:a}=n?new Pt:new MessageChannel,o=new WeakRef(i),s=new WeakRef(a),c=!1,l=!1,u,d=!1;i instanceof Nt||i.addEventListener(`close`,e=>{d&&e.stopImmediatePropagation()});let f=()=>{if(c)return;c=!0;let t=u??s.deref();u=void 0,Gt(r,e),t?.removeEventListener(`message`,m),t?.close(),h?.()},p=e=>{if(e.type===`message-port-close`){f();let e=o.deref();e?.dispatchEvent(new Event(`close`)),d=!0,e?.close();return}if(!l&&!o.deref()){f();return}let r=u??s.deref();r&&$t(e.data,t,e=>Qt(r,e,n),()=>o.deref()?.dispatchEvent(new Event(`messageerror`)))},m=({data:n})=>{let r;try{r=an(n,t)}catch(e){o.deref()?.dispatchEvent(new Event(`messageerror`)),globalThis.reportError?.(e);return}t.sendMessage({type:`message`,remoteUuid:t.remoteUuid,data:r,portId:e,seq:qt(t,e)})},h=It(i,()=>{Zt(t,e),f()});return i instanceof Nt||(ln.set(i,()=>{l=!0,u=s.deref(),h?.()}),a.addEventListener(`close`,()=>{l&&!c&&(Zt(t,e),f())},{once:!0})),i instanceof Nt&&(i._onClose=()=>{c||(Zt(t,e),f())}),a.addEventListener(`message`,m),a.start(),Jt(t,e,p),i},mn=/* @__PURE__ */ b({box:()=>yn,isType:()=>vn,objectsOnly:()=>!0,revive:()=>bn,type:()=>hn}),hn=`promise`,gn=e=>e instanceof Promise,_n=/* @__PURE__ */ new Set,vn=e=>e instanceof Promise,yn=(e,t)=>{if(!gn(e))throw TypeError(`Expected Promise`);let{localPort:n,boxedRemote:r}=fn(t),i=e=>{n.postMessage(e),n.close()};return e.then(e=>i({type:`resolve`,data:e})).catch(e=>i({type:`reject`,error:e})),{...z,type:hn,port:r}},bn=(e,t)=>{let n=sn(e.port,t);_n.add(n);let r=`portId`in e.port;return new Promise((e,i)=>{let a,o=()=>{n.close(),_n.delete(n),a?.()};if(r&&pt(t)){i(/* @__PURE__ */ Error(`osra: connection closed`)),o();return}a=r?ft(t,()=>{i(/* @__PURE__ */ Error(`osra: connection closed`)),o()}):void 0,n.addEventListener(`message`,({data:t})=>{t.type===`resolve`?e(t.data):i(t.error),o()},{once:!0}),n.start()})},xn=/* @__PURE__ */ b({box:()=>En,isType:()=>Tn,objectsOnly:()=>!0,revive:()=>Dn,type:()=>Sn}),Sn=`function`,Cn=/* @__PURE__ */ new Set,wn=e=>{e instanceof ReadableStream?e.locked||e.cancel(/* @__PURE__ */ Error(`osra: connection closed`)).catch(()=>{}):typeof WritableStream<`u`&&e instanceof WritableStream&&(e.locked||e.abort(/* @__PURE__ */ Error(`osra: connection closed`)).catch(()=>{}))},Tn=e=>typeof e==`function`,En=(e,t)=>{let{port1:n,port2:r}=new Pt;return n.addEventListener(`message`,({data:n})=>{let[r,i]=n;(async()=>{let n;try{n={type:`return`,value:await e(...i)}}catch(e){n={type:`throw`,error:e}}if(pt(t)){n.type===`return`&&wn(n.value);try{r.close()}catch{}return}let a=(()=>{try{return B(n,t)}catch(e){return B({type:`throw`,error:e},t)}})();rn(r,a),queueMicrotask(()=>{try{r.close()}catch{}})})()}),n.start(),{...z,type:Sn,port:on(r,t)}},Dn=(e,t)=>{let n=sn(e.port,t);return((...e)=>new Promise((r,i)=>{if(pt(t)){i(/* @__PURE__ */ Error(`osra: connection closed`));return}let{port1:a,port2:o}=new Pt;Cn.add(a);let s,c=()=>{a.close(),Cn.delete(a),s?.()};s=ft(t,()=>{i(/* @__PURE__ */ Error(`osra: connection closed`)),c()}),a.addEventListener(`message`,({data:e})=>{let t=e;t.type===`return`?r(t.value):i(t.error),c()},{once:!0}),a.start();let l=Tt(()=>B([o,e],t));rn(n,l)}))},On=/* @__PURE__ */ b({MAX_CREDIT_WINDOW:()=>64,box:()=>Pn,isType:()=>An,objectsOnly:()=>!0,revive:()=>Rn,type:()=>kn}),kn=`readableStream`,An=e=>e instanceof ReadableStream,jn=2,Mn=8,Nn=4194304,Pn=(e,t)=>{let{localPort:n,boxedRemote:r}=fn(t),i=e.getReader(),a=Ct(),o=0,s=!1,c=!1,l=e=>{c=!0;try{n.postMessage(e)}catch{}n.close()},u=async()=>{if(!(s||c)){for(s=!0;o>0;){let e;try{e=await i.read()}catch(e){c||l({type:`error`,error:e});return}if(c)return;if(e.done){l({type:`end`});return}o--;let t=a?wt(e.value):e.value;try{n.postMessage({type:`chunk`,value:t})}catch(e){l({type:`error`,error:e}),i.cancel(e).catch(()=>{});return}}s=!1}};return n.addEventListener(`message`,({data:e})=>{e instanceof Promise||!(`type`in e)||(e.type===`pull`?n.postMessage(i.read()):e.type===`credit`?(o+=e.n,u()):e.type===`cancel`&&(c=!0,i.cancel(e.reason).catch(()=>{}),n.close()))}),n.addEventListener(`close`,()=>{c||(c=!0,i.cancel(/* @__PURE__ */ Error(`osra: connection closed`)).catch(()=>{}))},{once:!0}),n.start(),{...z,type:kn,credit:!0,port:r}},Fn=e=>ArrayBuffer.isView(e)||e instanceof ArrayBuffer?e.byteLength:typeof e==`string`?e.length*2:typeof Blob<`u`&&e instanceof Blob?e.size:void 0,In=e=>{let t=!1,n=0,r,i=[],a=!1,o=!1,s,c,l=()=>r===void 0?Mn:Math.max(jn,Math.min(64,Math.floor(Nn/r))),u=()=>{let t=l(),r=n+i.length;if(r>t/2)return;let a=t-r;n+=a,e.postMessage({type:`credit`,n:a})},d=()=>{t=!0,queueMicrotask(()=>e.close())},f=e=>{if(o=!0,s=e,!c||i.length)return;let t=c;c=void 0,d(),t.reject(e)};return new ReadableStream({start:()=>{e.addEventListener(`message`,({data:o})=>{if(!(o instanceof Promise||!(`type`in o))){if(o.type===`chunk`){if(t)return;if(n<=0){i.length=0,f(/* @__PURE__ */ Error(`osra: stream exceeded its credit window`)),queueMicrotask(()=>e.close());return}n--;let a=Fn(o.value);if(a!==void 0&&(r=r===void 0?a:r*.875+a*.125),c){let e=c;c=void 0,e.controller.enqueue(o.value),e.resolve()}else i.push(o.value)}else if(o.type===`end`){if(t||(a=!0,!c||i.length))return;let e=c;c=void 0,d(),e.controller.close(),e.resolve()}else if(o.type===`error`){if(t)return;f(o.error)}}}),e.addEventListener(`messageerror`,()=>{t||f(/* @__PURE__ */ Error(`osra: a chunk failed to deserialize on this platform`))}),e.addEventListener(`close`,()=>{t||a||o||f(/* @__PURE__ */ Error(`osra: connection closed`))},{once:!0})},pull:e=>{if(!t){if(i.length){e.enqueue(i.shift()),!a&&!o&&u();return}if(o)return d(),Promise.reject(s);if(a){d(),e.close();return}return u(),new Promise((t,n)=>{c={controller:e,resolve:t,reject:n}})}},cancel:n=>{t=!0,i.length=0;let r=c;c=void 0,r?.resolve(),e.postMessage({type:`cancel`,reason:n}),queueMicrotask(()=>e.close())}})},Ln=e=>{let t=!1;return new ReadableStream({start:n=>{e.addEventListener(`messageerror`,()=>{if(!t){t=!0;try{n.error(/* @__PURE__ */ Error(`osra: a chunk failed to deserialize on this platform`))}catch{}queueMicrotask(()=>e.close())}}),e.addEventListener(`close`,()=>{if(!t){t=!0;try{n.error(/* @__PURE__ */ Error(`osra: connection closed`))}catch{}}},{once:!0})},pull:n=>new Promise((r,i)=>{e.addEventListener(`message`,({data:a})=>{a instanceof Promise&&a.then(i=>{i.done?(t=!0,n.close(),e.postMessage({type:`cancel`}),queueMicrotask(()=>e.close())):n.enqueue(i.value),r()}).catch(e=>{t=!0,i(e)})},{once:!0}),e.postMessage({type:`pull`})}),cancel:n=>{t=!0,e.postMessage({type:`cancel`,reason:n}),queueMicrotask(()=>e.close())}})},Rn=(e,t)=>{let n=sn(e.port,t);return n.start(),e.credit?In(n):Ln(n)},zn=/* @__PURE__ */ b({box:()=>Hn,isType:()=>Vn,objectsOnly:()=>!0,revive:()=>Un,type:()=>Bn}),Bn=`writableStream`,Vn=e=>e instanceof WritableStream,Hn=(e,t)=>{let{localPort:n,boxedRemote:r}=fn(t),i=e.getWriter(),a=!1,o=(e,t)=>e.then(()=>n.postMessage({type:`ack`})).catch(e=>n.postMessage({type:`err`,error:e?.message??String(e)})).then(()=>{t&&(a=!0,queueMicrotask(()=>n.close()))});return n.addEventListener(`message`,({data:e})=>{e&&typeof e==`object`&&`type`in e&&(e.type===`write`?o(i.write(e.chunk),!1):e.type===`close`?o(i.close(),!0):e.type===`abort`&&o(i.abort(e.reason),!0))}),n.addEventListener(`messageerror`,()=>{n.postMessage({type:`err`,error:`osra: a chunk failed to deserialize on this platform`})}),n.addEventListener(`close`,()=>{a||(a=!0,i.abort(/* @__PURE__ */ Error(`osra: connection closed`)).catch(()=>{}))},{once:!0}),n.start(),{...z,type:Bn,port:r,...Ct()?{transferChunks:!0}:{}}},Un=(e,t)=>{let n=sn(e.port,t);n.start();let r=/* @__PURE__ */ new Set,i=!1;n.addEventListener(`close`,()=>{i=!0;let e=/* @__PURE__ */ Error(`osra: connection closed`);for(let t of[...r])t(e);r.clear()},{once:!0});let a=Promise.resolve(),o=e=>{let t=a.then(()=>new Promise((t,a)=>{if(i){a(/* @__PURE__ */ Error(`osra: connection closed`));return}let o=e=>{r.delete(a),e()};r.add(a),n.addEventListener(`message`,({data:e})=>{e&&typeof e==`object`&&`type`in e&&(e.type===`ack`?o(t):e.type===`err`&&o(()=>a(Error(e.error))))},{once:!0}),n.postMessage(e)}));return a=t.catch(()=>{}),t},s=e.transferChunks===!0;return new WritableStream({write:e=>o({type:`write`,chunk:s?wt(e):e}),close:()=>o({type:`close`}),abort:e=>o({type:`abort`,reason:e})})},Wn=/* @__PURE__ */ b({box:()=>Jn,isType:()=>Kn,objectsOnly:()=>!0,revive:()=>Yn,type:()=>Gn}),Gn=`abortSignal`,Kn=e=>e instanceof AbortSignal,qn=/* @__PURE__ */ new WeakMap,Jn=(e,t)=>{if(e.aborted)return{...z,type:Gn,aborted:!0,reason:B(e.reason,t)};let{localPort:n,boxedRemote:r}=fn(t),i=()=>{n.postMessage({type:`abort`,reason:e.reason}),n.close(),a()},a=ft(t,()=>{e.removeEventListener(`abort`,i),n.close()});return e.addEventListener(`abort`,i,{once:!0}),{...z,type:Gn,aborted:!1,reason:void 0,port:r}},Yn=(e,t)=>{let n=new AbortController;if(e.aborted||e.port===void 0)return n.abort(Di(e.reason,t)),n.signal;let r=sn(e.port,t);return qn.set(n.signal,r),r.start(),r.addEventListener(`message`,({data:e})=>{e.type===`abort`&&(n.abort(e.reason),qn.delete(n.signal),r.close())}),n.signal},Xn=/* @__PURE__ */ b({box:()=>$n,isType:()=>Qn,objectsOnly:()=>!0,revive:()=>er,type:()=>Zn}),Zn=`response`,Qn=e=>e instanceof Response,$n=(e,t)=>({...z,type:Zn,status:e.status,statusText:e.statusText,headers:Ze(e.headers,t),body:e.body?Pn(e.body,t):null,url:e.url,redirected:e.redirected}),er=(e,t)=>{if(e.status===0)return Response.error();let n=Qe(e.headers,t),r=e.body?Rn(e.body,t):null,i=e.status===101||e.status===204||e.status===205||e.status===304;r&&i&&r.cancel().catch(()=>{});let a=new Response(i?null:r,{status:e.status,statusText:e.statusText,headers:n});return e.url&&Object.defineProperty(a,"url",{value:e.url,configurable:!0}),e.redirected&&Object.defineProperty(a,"redirected",{value:!0,configurable:!0}),a},tr=/* @__PURE__ */ b({box:()=>ir,isType:()=>rr,objectsOnly:()=>!0,revive:()=>ar,type:()=>nr}),nr=`request`,rr=e=>e instanceof Request,ir=(e,t)=>({...z,type:nr,method:e.method,url:e.url,headers:Ze(e.headers,t),body:e.body?Pn(e.body,t):null,credentials:e.credentials,cache:e.cache,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,integrity:e.integrity,keepalive:e.keepalive,signal:Jn(e.signal,t)}),ar=(e,t)=>{let n=Qe(e.headers,t),r={method:e.method,headers:n,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,integrity:e.integrity,keepalive:e.keepalive,signal:Yn(e.signal,t)};return e.mode!==`navigate`&&(r.mode=e.mode),e.body&&(r.body=Rn(e.body,t),r.duplex=`half`),new Request(e.url,r)},or=/* @__PURE__ */ b({box:()=>vr,boxByReference:()=>yr,identity:()=>fr,isType:()=>hr,objectsOnly:()=>!0,revive:()=>br,type:()=>sr}),sr=`identity`,cr=e=>e!==null&&(typeof e==`object`||typeof e==`function`),lr=e=>{if(e===null)return!1;let t=typeof e;return t===`object`||t===`function`||t===`symbol`&&Symbol.keyFor(e)===void 0},ur=/* @__PURE__ */ new WeakMap,dr=e=>{let t=ur.get(e);if(t!==void 0)return t;let n=globalThis.crypto.randomUUID();return ur.set(e,n),n},fr=e=>(cr(e)&&dr(e),e),pr=/* @__PURE__ */ new WeakMap,mr=e=>{let t=pr.get(e);if(t)return t;let n=/* @__PURE__ */ new Map,r={idToLocal:n,pins:/* @__PURE__ */ new Map,aliasIds:/* @__PURE__ */ new WeakMap,disposeRegistry:new FinalizationRegistry(t=>{if(n.delete(t),!pt(e))try{e.sendMessage({type:`identity-dispose`,remoteUuid:e.remoteUuid,id:t})}catch{}})};return pr.set(e,r),e.eventTarget.addEventListener(`message`,({detail:e})=>{e?.type===`identity-dispose`&&(r.pins.delete(e.id),r.idToLocal.delete(e.id))}),ft(e,()=>{r.pins.clear(),r.idToLocal.clear()}),r},hr=e=>cr(e)&&ur.has(e),gr=(e,t)=>{let n=t.aliasIds.get(e);if(n!==void 0)return n;let r=dr(e),i=t.idToLocal.get(r);if(i===void 0||i.deref()===e)return r;let a=globalThis.crypto.randomUUID();return t.aliasIds.set(e,a),a},_r=(e,t,n)=>{let r=gr(e,n);if(n.idToLocal.has(r))return{...z,type:sr,id:r};let i=t();return n.idToLocal.set(r,new WeakRef(e)),n.disposeRegistry.register(e,r,e),yi(()=>{},()=>{n.idToLocal.delete(r),n.disposeRegistry.unregister(e)}),{...z,type:sr,id:r,inner:i}},vr=(e,t)=>{let n=mr(t),r=()=>Ei(e,t,sr);return lr(e)?_r(e,r,n):{...z,type:sr,id:globalThis.crypto.randomUUID(),inner:r()}},yr=(e,t,n)=>_r(e,()=>t,mr(n)),br=(e,t)=>{let n=mr(t);if(n.pins.has(e.id))return n.pins.get(e.id);let r=n.idToLocal.get(e.id)?.deref();if(r!==void 0)return r;if(!(`inner`in e)||e.inner===void 0){try{t.sendMessage({type:`identity-dispose`,remoteUuid:t.remoteUuid,id:e.id})}catch{}throw Error(`osra identity: received id=${e.id} with no inner payload and nothing local to resolve it to`)}let i=Di(e.inner,t);return n.pins.set(e.id,i),lr(i)&&(ur.has(i)||ur.set(i,e.id),n.idToLocal.set(e.id,new WeakRef(i))),i},xr=/* @__PURE__ */ b({box:()=>Cr,isType:()=>Sr,objectsOnly:()=>!0,revive:()=>wr,type:()=>`map`}),Sr=e=>e instanceof Map,Cr=(e,t)=>({...z,type:`map`,entries:Array.from(e,([e,n])=>[B(e,t),B(n,t)])}),wr=(e,t)=>new Map(e.entries.map(([e,n])=>[Di(e,t),Di(n,t)])),Tr=/* @__PURE__ */ b({box:()=>Dr,isType:()=>Er,objectsOnly:()=>!0,revive:()=>Or,type:()=>`set`}),Er=e=>e instanceof Set,Dr=(e,t)=>({...z,type:`set`,values:Array.from(e,e=>B(e,t))}),Or=(e,t)=>new Set(e.values.map(e=>Di(e,t))),kr=/* @__PURE__ */ b({box:()=>Mr,isType:()=>jr,revive:()=>Nr,type:()=>Ar}),Ar=`bigint`,jr=e=>typeof e==`bigint`,Mr=(e,t)=>({...z,type:Ar,value:e.toString()}),Nr=(e,t)=>BigInt(e.value),Pr=/* @__PURE__ */ b({box:()=>Lr,isType:()=>Ir,objectsOnly:()=>!0,revive:()=>Rr,type:()=>Fr}),Fr=`event`,Ir=e=>e instanceof Event,Lr=(e,t)=>({...z,type:Fr,eventType:e.type,bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed,...e instanceof CustomEvent?{detail:B(e.detail,t)}:{}}),Rr=(e,t)=>{let n={bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed};return`detail`in e?new CustomEvent(e.eventType,{...n,detail:Di(e.detail,t)}):new Event(e.eventType,n)},zr=/* @__PURE__ */ b({box:()=>Hr,isType:()=>Vr,objectsOnly:()=>!0,revive:()=>Kr,type:()=>Br}),Br=`eventTarget`,Vr=e=>e instanceof EventTarget,Hr=(e,t)=>{let n=[],r=e=>typeof e==`boolean`?e:!!e?.capture;return{...z,type:Br,addListener:En((t,i,a)=>{n.push({eventType:t,listener:i,capture:r(a)}),e.addEventListener(t,i,a)},t),removeListener:En((t,i,a)=>{let o=r(a),s=n.findIndex(e=>e.eventType===t&&e.listener===i&&e.capture===o);s!==-1&&n.splice(s,1),e.removeEventListener(t,i,a)},t),removeAllListeners:En(()=>{for(let{eventType:t,listener:r,capture:i}of n.splice(0))e.removeEventListener(t,r,{capture:i})},t)}},Ur=/* @__PURE__ */ new WeakMap,Wr=e=>{if(typeof e==`function`)return e;let t=Ur.get(e);return t||Ur.set(e,t=t=>e.handleEvent(t)),t},Gr=(e,t,n,r)=>e.find(e=>e.eventType===t&&e.listener===n&&e.capture===r),Kr=(e,t)=>{let n=Dn(e.addListener,t),r=Dn(e.removeListener,t),i=Dn(e.removeAllListeners,t),a=new EventTarget,o=[],s=e=>{let t=o.indexOf(e);t!==-1&&o.splice(t,1)};return Object.defineProperty(a,"addEventListener",{value:(e,t,r)=>{if(t===null)return;let i=Wr(t),a=typeof r==`boolean`?r:!!r?.capture;if(Gr(o,e,i,a))return;let c=typeof r==`object`&&r?.once?e=>(s(l),i(e)):i,l={eventType:e,listener:i,capture:a,wire:c};o.push(l),(typeof r==`object`?r?.signal:void 0)?.addEventListener(`abort`,()=>s(l),{once:!0}),n(e,fr(c),r).catch(()=>{})}}),Object.defineProperty(a,"removeEventListener",{value:(e,t,n)=>{if(t===null)return;let i=Wr(t),a=typeof n==`boolean`?n:!!n?.capture,c=Gr(o,e,i,a);c&&(s(c),r(e,fr(c.wire),{capture:a}).catch(()=>{}))}}),It(a,()=>{i().catch(()=>{})}),a},qr=/* @__PURE__ */ b({box:()=>Xr,isType:()=>Yr,revive:()=>Zr,type:()=>Jr}),Jr=`symbol`,Yr=e=>typeof e==`symbol`,Xr=(e,t)=>{let n=Symbol.keyFor(e);return n===void 0?yr(e,{...z,type:Jr,description:e.description},t):{...z,type:Jr,registryKey:n}},Zr=(e,t)=>`registryKey`in e?Symbol.for(e.registryKey):Symbol(e.description),Qr=/* @__PURE__ */ b({box:()=>ti,isType:()=>ei,objectsOnly:()=>!0,revive:()=>ni,type:()=>$r}),$r=`asyncIterator`,ei=e=>!e||typeof e!=`object`||typeof ReadableStream<`u`&&e instanceof ReadableStream?!1:typeof e[Symbol.asyncIterator]==`function`,ti=(e,t)=>{let n=e[Symbol.asyncIterator]();return{...z,type:$r,next:En((e=>n.next(e)),t),return:En((e=>n.return?.(e)??Promise.resolve({done:!0,value:e})),t),throw:En((e=>n.throw?.(e)??Promise.reject(e)),t)}},ni=(e,t)=>{let n=Dn(e.next,t),r=Dn(e.return,t),i=Dn(e.throw,t),a={next:(...e)=>n(...e),return:e=>r(e),throw:e=>i(e),[Symbol.asyncIterator]:()=>a};return a},ri=[globalThis.File,globalThis.FileList,globalThis.RegExp,globalThis.DataView,globalThis.ImageData,globalThis.FormData,globalThis.DOMException,globalThis.DOMMatrix,globalThis.DOMMatrixReadOnly,globalThis.DOMPoint,globalThis.DOMPointReadOnly,globalThis.DOMQuad,globalThis.DOMRect,globalThis.DOMRectReadOnly,globalThis.CryptoKey,globalThis.FileSystemHandle,globalThis.FileSystemFileHandle,globalThis.FileSystemDirectoryHandle,globalThis.RTCCertificate],ii=[globalThis.CropTarget,globalThis.EncodedAudioChunk,globalThis.EncodedVideoChunk,globalThis.FencedFrameConfig,globalThis.GPUCompilationInfo,globalThis.GPUCompilationMessage,globalThis.GPUPipelineError,globalThis.RTCEncodedAudioFrame,globalThis.RTCEncodedVideoFrame,globalThis.WebTransportError],ai={type:`clonable`,capableOnly:!0,objectsOnly:!0,isType:e=>ce(e,ri)||ce(e,ii),box:(e,t)=>{if(ve(t.transport)){let t=e.constructor?.name||`Clonable`;throw TypeError(`osra: ${t} is only supported on structured-clone transports`)}return e},revive:(e,t)=>e},oi=[globalThis.ImageBitmap,globalThis.OffscreenCanvas,globalThis.WritableStream,globalThis.TransformStream,globalThis.MediaStreamTrack,globalThis.RTCDataChannel],si=[globalThis.AudioData,globalThis.VideoFrame,globalThis.MediaSourceHandle,globalThis.MIDIAccess,globalThis.WebTransportReceiveStream,globalThis.WebTransportSendStream],ci={type:`transferable`,capableOnly:!0,objectsOnly:!0,isType:e=>ce(e,oi)||ce(e,si),box:(e,t)=>{if(ve(t.transport)){let t=e.constructor?.name||`Transferable`;throw TypeError(`osra: ${t} is only supported on structured-clone transports`)}return e},revive:(e,t)=>e},li={type:`blob`,capableOnly:!0,objectsOnly:!0,isType:e=>typeof Blob<`u`&&e instanceof Blob,box:(e,t)=>{if(ve(t.transport))throw TypeError(`osra: Blob is only supported on structured-clone transports, send an ArrayBuffer or Uint8Array instead`);return e},revive:(e,t)=>e},ui=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},di=[ht,or,Re,Ue,Je,$e,at,mn,xn,Lt,On,zn,Wn,Xn,tr,xr,Tr,kr,qr,Pr,Qr,{type:`nonFiniteNumber`,isType:e=>typeof e==`number`&&!Number.isFinite(e),box:(e,t)=>ve(t.transport)?{...z,type:`nonFiniteNumber`,value:String(e)}:e,revive:(e,t)=>Number(e.value)},{type:`undefined`,isType:e=>e===void 0,box:(e,t)=>ve(t.transport)?{...z,type:`undefined`}:e,revive:(e,t)=>void 0},ai,ci,li,zr,{type:`unclonable`,objectsOnly:!0,isType:e=>{if(typeof e!=`object`||!e||Array.isArray(e)||ui(e))return!1;try{return structuredClone(e),!1}catch{return!0}},box:(e,t)=>({...z,type:`unclonable`}),revive:(e,t)=>({})}],fi=(e,t)=>t.find(t=>t.type===e.type),pi=e=>!!e&&typeof e==`object`&&Object.getPrototypeOf(e)===Object.prototype,mi=(e,t)=>Array.isArray(e)?e.map(e=>t(e)):pi(e)?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,t(n)])):e,hi=/* @__PURE__ */ new WeakSet,gi=/* @__PURE__ */ new WeakSet,_i=0,vi=[],yi=(e,t)=>{if(_i===0){e();return}vi.push({commit:e,rollback:t})},bi=e=>{let t=vi;vi=[];for(let n of t)try{e?n.rollback():n.commit()}catch{}},xi=e=>e!==null&&(typeof e==`object`||typeof e==`function`),Si=/* @__PURE__ */ new WeakMap,Ci=e=>{let t=Si.get(e);if(t)return t;let n=e.filter(e=>!e.objectsOnly);return Si.set(e,n),n},wi=(e,t)=>{let n=[];for(let[r,i]of Object.entries(e))r!==`__OSRA_BOX__`&&n.push([r,B(i,t)]);return{[C]:`quoted`,box:e[C],value:Object.fromEntries(n)}},Ti=(e,t,n)=>{let r=(e===null||typeof e!=`object`&&typeof e!=`function`?Ci(t.revivableModules):t.revivableModules).find(t=>t.type!==n&&t.isType(e));return r?r.box(e,t):Me(e)?wi(e,t):mi(e,e=>B(e,t))},B=(e,t)=>{let n=ke(e),r=!n&&Ne(e);if(n&&!Fe())return e;if(n||r){if(hi.has(e))throw TypeError(`osra: cannot serialize a circular structure - break the cycle or send the container by reference`);hi.add(e),_i++;let n=!0;try{let r=wi(e,t);return n=!1,r}finally{hi.delete(e),_i--,_i===0&&bi(n)}}let i=xi(e);if(i){if(hi.has(e))throw TypeError(`osra: cannot serialize a circular structure - break the cycle or send the container by reference`);hi.add(e)}_i++;let a=!0;try{let n=Ti(e,t);return a=!1,n}finally{i&&hi.delete(e),_i--,_i===0&&bi(a)}},Ei=(e,t,n)=>Ti(e,t,n),Di=(e,t)=>{let n=xi(e);if(n){if(gi.has(e))throw TypeError(`osra: cannot revive a circular structure`);gi.add(e)}try{if(Ne(e))return{...mi(e.value,e=>Di(e,t)),[C]:e.box};if(ke(e)){let n=fi(e,t.revivableModules);if(n)return n.revive(e,t)}return mi(e,e=>Di(e,t))}finally{n&&gi.delete(e)}},Oi=/* @__PURE__ */ b({init:()=>ji,startBidirectionalConnection:()=>Ai,type:()=>ki}),ki=`bidirectional`,Ai=({transport:e,value:t,remoteUuid:n,eventTarget:r,send:i,revivableModules:a})=>{let o={transport:e,remoteUuid:n,sendMessage:i,eventTarget:r,revivableModules:a};for(let e of a)e.init?.(o);let{promise:s,resolve:c}=Promise.withResolvers();return r.addEventListener(`message`,function e({detail:t}){t.type===`init`&&(c(t.data),r.removeEventListener(`message`,e))}),i({type:`init`,remoteUuid:n,data:Tt(()=>B(t,o))}),{revivableContext:o,remoteValue:s.then(e=>Di(e,o))}},ji=e=>{if(!(ye(e.transport)&&be(e.transport)))return;if(e.protocolEventTarget.addEventListener(`message`,({detail:{message:t,peer:n}})=>{if(t.type===`announce`){if(!t.remoteUuid){e.sendMessage({type:`announce`,remoteUuid:t.uuid});return}if(t.remoteUuid!==e.getUuid()||e.connectionContexts.has(t.uuid))return;e.sendMessage({type:`announce`,remoteUuid:t.uuid});let r=e.createConnectionEventTarget(),i={...n(),abort:()=>e.abortConnection(t.uuid)},a;try{let n=e.valueFor(i);if(e.claimPendingAbort(t.uuid)){e.sendMessage({type:`close`,remoteUuid:t.uuid});return}a=Ai({transport:e.transport,value:n,remoteUuid:t.uuid,eventTarget:r,send:t=>e.sendMessage(t),revivableModules:e.revivableModules})}catch(n){e.sendMessage({type:`close`,remoteUuid:t.uuid}),e.rejectRemoteValue(n);return}let o={type:`bidirectional`,eventTarget:r,connection:a};e.connectionContexts.set(t.uuid,o),o.connection.remoteValue.then(t=>e.addConnection(i,t),t=>e.rejectRemoteValue(t));return}if(t.type===`close`){if(t.remoteUuid!==e.getUuid())return;let n=e.connectionContexts.get(t.uuid);if(!n)return;e.connectionContexts.delete(t.uuid),mt(n.connection.revivableContext),e.rejectRemoteValue(/* @__PURE__ */ Error(`osra: peer closed the connection`));return}if(t.remoteUuid!==e.getUuid())return;let r=e.connectionContexts.get(t.uuid);r&&r.eventTarget.dispatchEvent(new CustomEvent(`message`,{detail:t}))}),e.presetRemoteUuid!==void 0){let t=e.presetRemoteUuid,n=e.createConnectionEventTarget(),r,i;try{i={abort:()=>e.abortConnection(t)};let a=e.valueFor(i);if(e.claimPendingAbort(t)){e.sendMessage({type:`close`,remoteUuid:t});return}r=Ai({transport:e.transport,value:a,remoteUuid:e.presetRemoteUuid,eventTarget:n,send:t=>e.sendMessage(t),revivableModules:e.revivableModules})}catch(n){e.sendMessage({type:`close`,remoteUuid:t}),e.rejectRemoteValue(n);return}let a={type:`bidirectional`,eventTarget:n,connection:r};e.connectionContexts.set(e.presetRemoteUuid,a),a.connection.remoteValue.then(t=>e.addConnection(i,t),t=>e.rejectRemoteValue(t));return}let t=50,n,r=()=>{if(!(e.unregisterSignal?.aborted||e.connectionContexts.size>0)){try{e.sendMessage({type:`announce`},`*`)}catch{}n=setTimeout(r,t),t=Math.min(t*2,1e3)}};e.unregisterSignal?.addEventListener(`abort`,()=>clearTimeout(n),{once:!0}),r()},Mi=()=>new EventTarget,Ni=e=>{let t=we(e),n=t?e.emit:e,r=t?e.receive:e;return{isJson:t&&`isJson`in e&&e.isJson!==void 0?e.isJson:n!==void 0&&ve(n)||r!==void 0&&ve(r),...n===void 0?{}:{emit:n},...r===void 0?{}:{receive:r}}},Pi=e=>e?e(di):di,Fi=32,Ii=()=>{let e=[],t=/* @__PURE__ */ new Set,n=!1,r=()=>({value:void 0,done:!0});return{push:r=>{if(!n){if(t.size===0){e.push(r),e.length>Fi&&e.shift();return}for(let e of t){let t=e.wake;if(t){e.wake=void 0,t({value:r,done:!1});continue}e.buffered.push(r)}}},close:()=>{n=!0;for(let e of t){let t=e.wake;e.wake=void 0,t?.(r())}},iterate:()=>{let i={buffered:[...e]};t.add(i);let a=!1;return{[Symbol.asyncIterator](){return this},next:()=>{if(a)return Promise.resolve(r());let e=i.buffered.shift();return e?Promise.resolve({value:e,done:!1}):n?Promise.resolve(r()):new Promise(e=>{i.wake=e})},return:()=>{a=!0,t.delete(i);let e=i.wake;return i.wake=void 0,e?.(r()),Promise.resolve(r())}}}}},Li=(e,t,n)=>{let r=e.then(n);r.catch(()=>{});let i=()=>{let e=t.iterate();return{[Symbol.asyncIterator](){return this},next:()=>e.next().then(e=>e.done?{value:void 0,done:!0}:{value:n(e.value),done:!1}),return:()=>e.return?.()??Promise.resolve({value:void 0,done:!0})}};return Object.assign(r,{[Symbol.asyncIterator]:i})},Ri=Symbol.for(`osra.context`),zi=e=>typeof e==`object`&&!!e&&Ri in e,Bi=[Oi],Vi=(e,{transport:t,name:n,remoteName:r,key:i=S,origin:a=`*`,unregisterSignal:o,revivableModules:s,uuid:c,remoteUuid:l,connection:u=({value:e})=>e})=>{let d=u,f=Ni(t);if(!(ye(f)&&be(f))){let e=Ii();e.close();let t=Promise.reject(/* @__PURE__ */ Error(`osra: transport must be able to both emit and receive to establish a connection; pass a bidirectional platform transport or a custom { emit, receive } pair`));return t.catch(()=>{}),Li(t,e,d)}let p=Pi(s),m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Set,g=Ii(),{promise:_,resolve:v,reject:y}=Promise.withResolvers();_.catch(()=>{});let b=c??globalThis.crypto.randomUUID(),C=(e,t=a)=>{let r={[x]:i,name:n,uuid:b,...e},o=Mt(r);te(f,r,t,o),un(o,!ve(f))},w=(e,t)=>{o?.aborted||C(e,t)},T=Mi(),E={transport:f,valueFor:t=>zi(e)?e[Ri](t):e,revivableModules:p,connectionContexts:m,getUuid:()=>b,presetRemoteUuid:l,sendMessage:w,protocolEventTarget:T,rejectRemoteValue:y,abortConnection:e=>{let t=m.get(e);if(!t){h.add(e);return}m.delete(e),C({type:`close`,remoteUuid:e}),mt(t.connection.revivableContext),y(/* @__PURE__ */ Error(`osra: connection aborted`))},claimPendingAbort:e=>h.delete(e),addConnection:(e,t)=>{let n={value:t,context:e};v(n),g.push(n)},createConnectionEventTarget:Mi,unregisterSignal:o};if(O({listener:(e,t)=>{e.uuid!==b&&T.dispatchEvent(new CustomEvent(`message`,{detail:{message:e,peer:()=>({...t.origin?{origin:t.origin}:{},...t.source?{source:t.source}:{},...t.port?{port:t.port}:{},...t.sender?{sender:t.sender}:{}})}}))},transport:f,remoteName:r,key:i,origin:a,unregisterSignal:o}),o?.aborted)return y(o.reason),g.close(),Li(_,g,d);o?.addEventListener(`abort`,()=>{for(let[e,t]of m)C({type:`close`,remoteUuid:e}),mt(t.connection.revivableContext);m.clear(),g.close(),y(o.reason)},{once:!0});for(let e of Bi)e.init(E);return Li(_,g,d)},Hi=(e,t)=>Vi(e,t),Ui=1e4,Wi=16,Gi=e=>{let t;try{t=e.contentWindow}catch{return!0}if(!t)return!0;try{let e=t.location.href;return e!==``&&e!==`about:blank`}catch{return!0}},Ki=(e,t=Ui)=>new Promise(n=>{if(Gi(e))return n();let r=()=>{clearInterval(i),clearTimeout(a),e.removeEventListener(`load`,r),n()},i=setInterval(()=>{Gi(e)&&r()},Wi),a=setTimeout(r,t);e.addEventListener(`load`,r)}),qi=5e3,Ji=9e4,Yi=(e,t,n)=>{let r=1,i,a=e.ownerDocument.defaultView,o=()=>{clearTimeout(i),u?.(),e.removeEventListener(`load`,l)},s=()=>{if(e.isConnected){if(r>=4)return o(),console.error(`FKN @fkn/lib: ${t} did not load in ${r} tries; reload the page`);r+=1,e.contentWindow?.location.replace(t),c(Ji)}},c=e=>{clearTimeout(i),i=setTimeout(s,e)},l=()=>c(qi),u=a?m(a,`message`,t=>{t.source===e.contentWindow&&t.origin===n&&o()}):void 0;if(e.addEventListener(`load`,l),Gi(e))return c(qi);i=setTimeout(()=>Gi(e)?c(8e4):s(),Ui)},Xi=(e,t)=>({receive:n=>m(e.ownerDocument.defaultView,`message`,e=>{e.origin===t&&n(e.data,{source:e.source,origin:t})}),emit:(n,r)=>e.contentWindow?.postMessage(n,t,r)}),Zi=32,Qi=8,$i=120,ea=(e,t)=>typeof CSS<`u`&&typeof CSS?.supports==`function`&&CSS.supports(e,t),ta=ea(`clip-path`,`path('M0 0H1V1H0Z')`),na=ea(`clip-path`,`polygon(nonzero, 0px 0px, 1px 0px, 1px 1px)`),ra=`light dark`,ia=e=>{let t=e.style;t.setProperty(`display`,`block`,`important`),t.setProperty(`position`,`fixed`,`important`),t.setProperty(`top`,`0`,`important`),t.setProperty(`left`,`0`,`important`),t.setProperty(`width`,`100%`,`important`),t.setProperty(`height`,`100%`,`important`),t.setProperty(`border`,`none`,`important`),t.setProperty(`padding`,`0`,`important`),t.setProperty(`box-sizing`,`border-box`,`important`),t.setProperty(`clip-path`,`inset(100%)`,`important`),t.setProperty(`background`,`transparent`),t.setProperty(`color-scheme`,ra),t.setProperty(`z-index`,`2147483647`),e.setAttribute(`title`,`FKN`)},aa=({x:e,y:t,width:n,height:r,radius:i})=>{if(!i)return`M${e} ${t}h${n}v${r}h${-n}Z`;let a=Math.min(n,r)/2,[o,s,c,l]=i.map(e=>Math.max(0,Math.min(e,a)));return`M${e+o} ${t}h${n-o-s}a${s} ${s} 0 0 1 ${s} ${s}v${r-s-c}a${c} ${c} 0 0 1 ${-c} ${c}h${-(n-c-l)}a${l} ${l} 0 0 1 ${-l} ${-l}v${-(r-l-o)}a${o} ${o} 0 0 1 ${o} ${-o}Z`},oa=()=>ta&&na,sa=({x:e,y:t,width:n,height:r})=>[[e,t],[e+n,t],[e+n,t+r],[e,t+r],[e,t]],ca=e=>{let t=e[0];if(!t)return[];let n=sa(t)[0],r=[];return e.forEach((t,i)=>{r.push(...sa(t)),i>0&&i<e.length-1&&r.push(n)}),r},la=e=>`polygon(nonzero, ${ca(e).map(([e,t])=>`${e}px ${t}px`).join(`, `)})`,ua=({x:e,y:t,width:n,height:r,radius:i},a)=>{let o=`${t}px ${a.width-e-n}px ${a.height-t-r}px ${e}px`;return i?`inset(${o} round ${i.map(e=>`${e}px`).join(` `)})`:`inset(${o})`},da=(e,t,n)=>{if(t)return`none`;if(e.length===0)return`inset(100%)`;let r=e.length===1?e[0]:void 0;return r?ua(r,n):na&&e.length<=5&&!e.some(e=>e.radius)?la(e):`path('${e.map(aa).join(``)}')`},fa=e=>{if(e.length<2)return null;let t=Math.min(...e.map(e=>e.x)),n=Math.min(...e.map(e=>e.y));return{x:t,y:n,width:Math.max(...e.map(e=>e.x+e.width))-t,height:Math.max(...e.map(e=>e.y+e.height))-n}},pa=(e,t,n)=>t>=e.x&&t<e.x+e.width&&n>=e.y&&n<e.y+e.height,ma=16,ha=(e,t,n)=>t===1?e*ma:t===2?e*n:e,ga=(e,t,n,r,i)=>{let a=t?r:0,o=n?i:0;return a||o?{target:e,left:a,top:o}:null},_a=(e,t,n)=>{let r=document.documentElement,i=getComputedStyle(r),a=i.overflowX===`visible`&&i.overflowY===`visible`&&document.body?document.body:r;for(let r of e){if(r===a)break;if(!(r instanceof Element))continue;let e=getComputedStyle(r),i=ga(r,/auto|scroll/.test(e.overflowX)&&r.scrollWidth>r.clientWidth,/auto|scroll/.test(e.overflowY)&&r.scrollHeight>r.clientHeight,t,n);if(i)return i;if(e.position===`fixed`&&!r.offsetParent)break}let o=document.scrollingElement,s=a===r?i:getComputedStyle(a);return o&&ga(o,!/hidden|clip/.test(s.overflowX),!/hidden|clip/.test(s.overflowY),t,n)},va=null,ya=null,ba=e=>({width:e.offsetWidth||window.innerWidth,height:e.offsetHeight||window.innerHeight}),xa=e=>{if(!ya||!va||!pa(ya,e.clientX,e.clientY))return;let t=document.fullscreenElement;if(t&&!t.contains(va))return;let n=e.composedPath(),r=n.find(e=>e instanceof Element&&e.matches(`:is(:modal, :popover-open)`));if(r&&!r.contains(va))return;let i=_a(n,ha(e.deltaX,e.deltaMode,window.innerWidth),ha(e.deltaY,e.deltaMode,window.innerHeight));i&&(i.target.scrollBy({left:i.left,top:i.top,behavior:`instant`}),e.cancelable&&e.preventDefault())},Sa,Ca=e=>{ya=e,e?Sa??=m(window,`wheel`,xa,{capture:!0,passive:!1}):(Sa?.(),Sa=void 0)},wa=0,Ta=null,Ea=e=>{let t=document.documentElement;if(!t||e===wa&&(e===0||t===Ta))return;wa=e,Ta=t;let n=t.style;e>0?(n.setProperty(`margin-top`,`${e}px`,`important`),n.setProperty(`--fkn-inset-top`,`${e}px`)):(n.removeProperty(`margin-top`),n.removeProperty(`--fkn-inset-top`))},Da=(e,t)=>{t?(e.removeAttribute(`tabindex`),e.removeAttribute(`aria-hidden`)):(e.setAttribute(`tabindex`,`-1`),e.setAttribute(`aria-hidden`,`true`))},Oa=(e,{modal:t,rects:n,inset:r},i)=>{if(Ea(r),!ta){let r=t||n.length>0;Da(e,r),e.style.setProperty(`pointer-events`,r?`auto`:`none`,`important`),e.style.setProperty(`visibility`,r?`visible`:`hidden`,`important`);return}let a=da(n,t,i),o=a===`none`||ea(`clip-path`,a)?a:`inset(100%)`;e.style.setProperty(`clip-path`,o,`important`),Da(e,o!==`inset(100%)`),Ca(t||o!==a?null:fa(n))},ka=e=>{if(typeof e!=`object`||!e)return 0;let{top:t}=e;return typeof t!=`number`||!Number.isFinite(t)||t<=0?0:Math.min(Math.round(t),$i)},Aa=e=>{if(Array.isArray(e)&&e.length===4&&e.every(e=>typeof e==`number`&&Number.isFinite(e)&&e>=0))return e.some(e=>e>0)?e:void 0},ja=(e,t)=>{if(typeof e!=`object`||!e)return null;let{x:n,y:r,width:i,height:a}=e;if(![n,r,i,a].every(e=>typeof e==`number`&&Number.isFinite(e)))return null;let o=t.width,s=t.height,c=Math.max(0,Math.min(Math.round(n),o)),l=Math.max(0,Math.min(Math.round(r),s)),u=Math.max(c,Math.min(Math.round(n+i),o)),d=Math.max(l,Math.min(Math.round(r+a),s)),f=Aa(e.radius);return{x:c,y:l,width:u-c,height:d-l,...f?{radius:f}:{}}},Ma={"not-rendered":`this page is not painting it at all, so it or an ancestor is display:none, or the frame was moved out of the layout`,clipped:`it is clipped away or positioned outside the viewport`,"not-shown":`it is rendered but would not be seen, so either something is drawn over it, or it or an ancestor has opacity below 1, visibility:hidden, or a filter`},Na=e=>Array.isArray(e)?e.slice(0,Qi).flatMap(e=>{if(typeof e!=`object`||!e)return[];let{kind:t,cause:n,level:r}=e;return typeof t!=`string`||t.length>40||typeof n!=`string`||!(n in Ma)||r!==`full`&&r!==`liveness`?[]:[{kind:t,cause:n,level:r}]}):[],Pa=/* @__PURE__ */ new Set,Fa=e=>{for(let{kind:t,cause:n,level:r}of e)Pa.has(t)||(Pa.add(t),console.error(`[FKN] The FKN ${JSON.stringify(t)} is not visible on this page: ${Ma[n]}. Nobody using this page can see or answer it.
|
|
2
2
|
@fkn/lib draws its UI inside <iframe title="FKN"> and sets display, position, top, left, width, height, border, padding, box-sizing, clip-path and z-index on that element. Leave those as they are, then check for an ancestor with opacity, visibility, display or a clipping transform, and for an element stacked above it.`+(r===`liveness`?`
|
|
3
|
-
This browser reports limited detail, so the cause above is a best guess.`:``)))},Ia=(e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=(Array.isArray(n.rects)?n.rects.slice(0,Zi):[]).map(e=>ja(e,t)).filter(e=>e!==null&&e.width>0&&e.height>0);return{modal:n.modal===!0,rects:r,hidden:Na(n.hidden),inset:ka(n.inset)}},La=()=>va!==null,Ra=null,za=null,Ba=()=>{if(!va||Ra===null)return;let e=ba(va),t=Ia(Ra,e);t&&Oa(va,t,e)},Va=e=>{typeof ResizeObserver<`u`&&(za??=new ResizeObserver(Ba),za.disconnect(),za.observe(e))},Ha=e=>{ia(e),Oa(e,{modal:!1,rects:[],hidden:[],inset:0},ba(e)),va=e,Va(e)},Ua=e=>{if(!va)return;let t=ba(va),n=Ia(e,t);n&&(Ra=e,Oa(va,n,t),Fa(n.hidden))},Wa=`https://fkn.app`,Ga=typeof globalThis<`u`&&globalThis.document?globalThis.document:void 0,Ka=typeof globalThis<`u`&&globalThis.crossOriginIsolated===!0,qa=p(Ka),Ja=`fkn-api-port`,Ya=`fkn-api-port-ack`,Xa=2e3,Za=()=>{if(!Ga||typeof window>`u`||window.parent===window)return Promise.resolve(void 0);let e;try{e=window.parent}catch{return Promise.resolve(void 0)}let t=new MessageChannel;return new Promise(n=>{let r=e=>{if(clearTimeout(a),t.port1.removeEventListener(`message`,i),!e)try{t.port1.close()}catch{}n(e)},i=e=>{e.data?.type===Ya&&r(t.port1)},a=setTimeout(()=>r(void 0),Xa);t.port1.addEventListener(`message`,i),t.port1.start();try{e.postMessage({type:Ja},Wa,[t.port2])}catch{r(void 0)}})},Qa,$a=e=>e.querySelector(`iframe[src="${qa}"]`),eo=async e=>{for(;!e.body;)await new Promise(t=>{let n=new MutationObserver(()=>{n.disconnect(),t()});n.observe(e,{childList:!0,subtree:!0})})},to=async e=>{let t=$a(e);if(t||=(await eo(e),$a(e)),t)Qa=t;else{let t=e.createElement(`iframe`);t.setAttribute(`allow`,d(Ka)),t.src=qa,e.body.appendChild(t),Qa=t}return Yi(Qa,qa,Wa),Ha(Qa),Qa},no=(async()=>{if(!Ga)return;let e=await Za();if(e)return{receive:e,emit:e};let t=await to(Ga);return await Ki(t),t.contentWindow?Xi(t,Wa):void 0})(),ro=(e,{boundRetired:t=e=>e}={})=>{let n,r=0,i=!1,a=()=>{},o=()=>new Promise(e=>{a=e}),s=o(),c=s,l=/* @__PURE__ */ new Set,u=/* @__PURE__ */ new Set,d=0,f=0,p=()=>{let e=[...u];u.clear();let t=/* @__PURE__ */ Error(`FKN: the broker was replaced while this call was pending; retry it`);for(let n of e)try{n(t)}catch{}};(async()=>{for await(let t of e){let e=++r,i=n!==void 0;n={remote:t,epoch:e,replaced:i};let c=a;s=o(),c(t),p();for(let n of[...l])try{n(t,e,i)}catch{}}})().catch(()=>{});let m=async(e,r)=>{let a=n?.remote??await(i?t(s):s);for(let t of e.slice(0,-1))a=a[t];let o=a[e[e.length-1]??``];d=Date.now(),f+=1;let c=()=>{},l=new Promise((e,t)=>{c=t});u.add(c);try{return await Promise.race([Promise.resolve(o.apply(a,r)),l])}finally{--f,u.delete(c),d=Date.now()}},h=/* @__PURE__ */ new Map,g=e=>{let t=e.join(`\0`),r=h.get(t);if(r)return r;let i=new Proxy(function(){},{get:(t,r)=>{if(typeof r!=`string`||r===`then`)return;let i=n;if(i){let t=i.remote;for(let n of e)t=t?.[n];if(t?.[r]===void 0)return}return g([...e,r])},apply:(t,n,r)=>m(e,r)});return h.set(t,i),i};return{facade:g([]),first:c.then(()=>{}),current:()=>n,onEpoch:e=>{if(l.add(e),n)try{e(n.remote,n.epoch,n.replaced)}catch{}return()=>{l.delete(e)}},lastCall:()=>d,inFlight:()=>f,routable:()=>n?Promise.resolve():s.then(()=>{}),retire:()=>{i=!0,n=void 0,p()}}},io=!1,ao=/* @__PURE__ */ new Set,oo=()=>io,so=e=>{ao.add(e)},co=e=>`fkn-relayed-worker-${e}`,lo=e=>new Promise(t=>{let n=globalThis.navigator?.locks;if(!n)return t();n.request(co(e),()=>(t(),new Promise(()=>{}))).catch(()=>t())}),uo=async()=>{if(typeof window<`u`)return no;if(typeof self<`u`)return{receive:self,emit:self}},fo=`fkn-api`,po=`fkn-api-window`,mo={async*[Symbol.asyncIterator](){let e=await uo();if(!e)await new Promise(()=>{});else{if(!oo()){let t=new AbortController;so(()=>t.abort());let n=crypto.randomUUID();typeof window>`u`&&await lo(n);for await(let r of Hi({},{key:fo,transport:e,unregisterSignal:t.signal,uuid:n})){if(t.signal.aborted)break;yield r}}yield*Hi({},{key:po,transport:e})}}},ho=!1,go=uo().then(e=>new Promise(t=>{if(!e)return;let n=new AbortController;O({transport:e,key:fo,unregisterSignal:n.signal,listener:()=>{n.abort(),ho=!0,t()}})})),_o=ro(mo,{boundRetired:e=>Promise.race([e,go.then(()=>To(e,()=>new Co))])});so(()=>_o.retire());var vo=class extends Error{constructor(e,t){super(t===void 0?`@fkn/lib: no FKN broker in this realm (it has no window and no self, as in Node.js), so ${e} could not be requested`:`@fkn/lib: no broker connection within ${t}ms, so ${e} could not be requested`),this.name=`BrokerUnreachableError`}},yo=v?Promise.race([_o.first,new Promise(e=>so(e))]).then(()=>_o.facade):Promise.reject(new vo(`a broker call`));yo.catch(()=>{});var bo=8e3,xo=1e3,So=!1,Co=class extends Error{constructor(){super(`FKN @fkn/lib: this page relays its FKN channel to a worker, and the FKN page it reached predates a channel of the page's own; reload`),this.name=`OwnChannelUnavailableError`}},wo=e=>new Promise((t,n)=>setTimeout(()=>n(e))),To=(e,t)=>{if(So&&!ho)return wo(t(bo));let n=So?xo:bo;return Promise.race([e,new Promise((e,r)=>setTimeout(()=>{So=!0,r(t(n))},n))])},Eo=e=>v?oo()?To(_o.routable().then(()=>_o.facade),t=>ho?new Co:new vo(e,t)):To(yo,t=>new vo(e,t)):wo(new vo(e));so(()=>{go.then(()=>{let e=setTimeout(()=>console.error(new Co),bo);_o.routable().then(()=>clearTimeout(e))})});var Do=_o.onEpoch,Oo=_o.current;_o.lastCall,_o.inFlight,Do(e=>{La()&&e.overlay.setHost(Ua,{exactClips:oa(),colorScheme:ra}).catch(()=>{})}),typeof window<`u`&&g(()=>{let e=Oo();return e?_(()=>e.remote.shell?.showHeader?.(),8e3):!1});var ko=(e,t)=>yo.then(n=>n.cloud.dns.lookup(e,t));function Ao(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function jo(e,t){let n,r=()=>{if(n)return n;let r=indexedDB.open(e);return r.onupgradeneeded=()=>r.result.createObjectStore(t),n=Ao(r),n.then(e=>{e.onclose=()=>n=void 0},()=>{}),n};return(e,n)=>r().then(r=>n(r.transaction(t,e).objectStore(t)))}let Mo;function No(){return Mo||=jo(`keyval-store`,`keyval`),Mo}function Po(e,t=No()){return t(`readonly`,t=>Ao(t.get(e)))}function Fo(e,t,n=No()){return n(`readwrite`,n=>(n.put(t,e),Ao(n.transaction)))}function Io(e,t,n=No()){return n(`readwrite`,n=>new Promise((r,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),r(Ao(n.transaction))}catch(e){i(e)}}}))}function V(e,t=No()){return t(`readwrite`,t=>(t.delete(e),Ao(t.transaction)))}var Lo={checkingFiles:1,downloadingMetadata:2,downloading:3,finished:4,seeding:5,checkingResumeData:7},Ro=/^incoming connection from (\S+) \(([^)]*)\)/,zo=/^successfully listening on \[([^\]]*)\] (\S+)/,Bo=/^listening on .* failed:/,Vo=new TextDecoder,Ho=4026531841,Uo=4026531842,Wo=4026531843,Go=4026531844,Ko=4026531845,qo=4026531846,Jo={interesting:1,choked:2,remoteInterested:4,remoteChoked:8,supportsExtensions:16,localConnection:32,handshake:64,connecting:128,onParole:512,seed:1024,optimisticUnchoke:2048,snubbed:4096,uploadOnly:8192,endgameMode:16384,holepunched:32768,i2pSocket:65536,utpSocket:1<<17,sslSocket:1<<18,rc4Encrypted:1<<19,plaintextEncrypted:1<<20},H={seedMode:1,uploadMode:2,shareMode:4,applyIpFilter:8,paused:16,autoManaged:32,duplicateIsError:64,updateSubscribe:128,superSeeding:256,sequentialDownload:512,stopWhenReady:1024,overrideTrackers:2048,overrideWebSeeds:4096,needSaveResume:8192,disableDht:1<<19,disableLsd:1<<20,disablePex:1<<21,noVerifyFiles:1<<22,defaultDontDownload:1<<23},Yo={top:0,up:1,down:2,bottom:3},Xo={tracker:1,dht:2,pex:4,lsd:8,resumeData:16,incoming:32},U={skip:0,low:1,normal:4,top:7},Zo=1<<22,Qo=6881,$o=1e4,es=100663296,ts=e=>{let t=/^100\.(\d+)\.(\d+)\.(\d+)(?::\d+)?$/.exec(e);return!t||(t[1]&192)!=64?-1:(t[1]&63)<<16|t[2]<<8|t[3]},ns=6e4,rs=12,is=1e3,as=class{mod;storage;destroyed=!1;fallbackTimer;filesByHandle=/* @__PURE__ */ new Map;bitfieldByHandle=/* @__PURE__ */ new Map;statusByHandle=/* @__PURE__ */ new Map;pieceWaiters=[];resumeByHandle=/* @__PURE__ */ new Map;resumeWaiters=[];peersByHandle=/* @__PURE__ */ new Map;trackersByHandle=/* @__PURE__ */ new Map;peerWaiters=[];trackerWaiters=[];priosByHandle=/* @__PURE__ */ new Map;deadlineRefs=/* @__PURE__ */ new Map;textAlerts=[];streams=/* @__PURE__ */ new Map;nextStream=Math.floor(Math.random()*Zo);handles=/* @__PURE__ */ new Set;windows=/* @__PURE__ */ new Set;reachability={listening:{},listenFailed:[],inbound:0,inboundByTransport:{},lastInbound:null,port:null};constructor(e,t){if(this.mod=e,this.storage=t.storage??null,t.utpReceiveBufferBytes&&e._lt_set_utp_receive_buffer(t.utpReceiveBufferBytes),t.enableDht===!1&&e._lt_set_dht(0),t.extraCaPem){let n=e.stringToNewUTF8(t.extraCaPem);try{e._lt_set_extra_ca_pem(n)}finally{e._free(n)}}else e._lt_set_extra_ca_pem?.(0);if(t.rateLimits){let{download:n,upload:r,limitLocalPeers:i}=t.rateLimits;e._lt_session_set_rate_limits(Math.max(0,Math.floor(n??0)),Math.max(0,Math.floor(r??0)),i==null?-1:+!!i)}if(e._lt_session_create()!==0)throw Error(`lt_session_create returned non-zero`);e.fkn&&(e.fkn.takeStream=e=>this.takeStream(e));let n=t.tickIntervalMs??250;this.fallbackTimer=setInterval(()=>this.tick(),n)}addMagnet(e,t=`/downloads`){let n=this.mod,r=n.stringToNewUTF8(e),i=n.stringToNewUTF8(t);try{return this.added(n._lt_session_add_magnet(r,i))}finally{n._free(r),n._free(i)}}addTorrentFile(e,t=`/downloads`){let n=this.mod,r=n._malloc(e.length);n.HEAPU8.set(e,r);let i=n.stringToNewUTF8(t);try{return this.added(n._lt_session_add_torrent_file(r,e.length,i))}finally{n._free(r),n._free(i)}}addTorrentWithResume(e,t=`/downloads`){let n=this.mod,r=n._malloc(e.length);n.HEAPU8.set(e,r);let i=n.stringToNewUTF8(t);try{return this.added(n._lt_session_add_torrent_with_resume(r,e.length,i))}finally{n._free(r),n._free(i)}}added(e){return e>0&&this.handles.add(e),e>>>0}torrents(){return[...this.handles]}removeTorrent(e,t=!1){let n=this.mod._lt_session_remove_torrent_ex(e,+!!t)===0;return this.failPieceWaiters(/* @__PURE__ */ Error(`read: torrent ${e} was removed`),e),this.resumeWaiters=this.resumeWaiters.filter(t=>t.handle!==e||(clearTimeout(t.timer),t.reject(/* @__PURE__ */ Error(`save_resume_data: torrent ${e} was removed`)),!1)),this.handles.delete(e),this.windows.delete(e),this.filesByHandle.delete(e),this.bitfieldByHandle.delete(e),this.statusByHandle.delete(e),this.resumeByHandle.delete(e),this.priosByHandle.delete(e),this.deadlineRefs.delete(e),n}pauseTorrent(e){this.mod._lt_torrent_pause(e)}resumeTorrent(e){this.mod._lt_torrent_resume(e)}forceRecheck(e){this.mod._lt_torrent_force_recheck(e)}saveResumeData(e,t=8e3){return!this.handles.has(e)||this.mod._lt_torrent_save_resume_data(e)!==0?Promise.reject(/* @__PURE__ */ Error(`save_resume_data: no torrent ${e}`)):new Promise((n,r)=>{let i={handle:e,resolve:n,reject:r,timer:setTimeout(()=>{let e=this.resumeWaiters.indexOf(i);e>=0&&(this.resumeWaiters.splice(e,1),r(/* @__PURE__ */ Error(`save_resume_data timed out`)))},t)};this.resumeWaiters.push(i)})}addPeerStream(e,t){let n=this.nextStream;this.nextStream=(n+1)%Zo;let r=`100.${64+(n>>16)}.${n>>8&255}.${n&255}`;return t.maxRecvQueue??=es,this.streams.set(r,{socket:t,timer:setTimeout(()=>this.dropStream(r,`libtorrent did not dial within ${$o} ms`),$o)}),this.drainAlerts(),this.mod._lt_torrent_add_channel_peer(e,1681915904+n,Qo)!==0&&this.dropStream(r,`the engine has no torrent ${e}`),{address:r,port:Qo}}takeStream(e){let t=this.streams.get(e);if(t)return this.streams.delete(e),clearTimeout(t.timer),t.socket}dropStream(e,t){let n=this.takeStream(e);try{n?.destroy(/* @__PURE__ */ Error(`addPeerStream: ${t}`))}catch{}}peers(e,t=4e3){return this.mod._lt_torrent_post_peers(e),this.awaitList(this.peerWaiters,this.peersByHandle,e,t)}lastPeers(e){return this.peersByHandle.get(e)??[]}trackers(e,t=4e3){return this.mod._lt_torrent_post_trackers(e),this.awaitList(this.trackerWaiters,this.trackersByHandle,e,t)}lastTrackers(e){return this.trackersByHandle.get(e)??[]}addTrackers(e,t){let n=this.mod,r=[];for(let i of t){let t=n.stringToNewUTF8(i.trim());try{n._lt_torrent_add_tracker(e,t)!==0&&r.push(i)}finally{n._free(t)}}return r}pieceAvailability(e){let t=this.filesByHandle.get(e);if(!t)return null;let n=this.mod,r=n._malloc(t.numPieces*2);try{let i=n._lt_torrent_piece_availability(e,r,t.numPieces);return i<0?null:new Uint16Array(n.HEAPU8.buffer,r,i).slice()}finally{n._free(r)}}dhtNodes(){return this.mod._lt_session_dht_nodes()}awaitList(e,t,n,r){return new Promise(i=>{let a={handle:n,resolve:i,timer:setTimeout(()=>{let r=e.indexOf(a);r>=0&&(e.splice(r,1),i(t.get(n)??[]))},r)};e.push(a)})}resolveOne(e,t,n){for(let r=e.length-1;r>=0;r--){let i=e[r];i.handle===t&&(clearTimeout(i.timer),e.splice(r,1),i.resolve(n))}}files(e){return this.filesByHandle.get(e)??null}bitfield(e){let t=this.bitfieldByHandle.get(e),n=this.filesByHandle.get(e);return!t||!n?null:{pieces:t.pieces,numPieces:t.numPieces,pieceLength:n.pieceLength,length:n.totalSize}}status(e){return this.statusByHandle.get(e)??null}async read(e,t,n,r,i={}){let a=this.filesByHandle.get(e);if(!a)throw Error(`read: no layout for handle ${e} (metadata not ready)`);let o=a.files[t];if(!o)throw Error(`read: no file ${t}`);if(!this.storage)throw Error(`read: no storage backend configured`);if(n<0)throw RangeError(`read: negative offset ${n}`);let s=Math.min(r,o.size-n);if(s<=0)return/* @__PURE__ */ new Uint8Array;let{pieceLength:c}=a,l=o.offset+n,u=Math.floor(l/c),d=Math.min(a.numPieces-1,Math.floor((l+s-1)/c));if(!this.hasPieces(e,u,d)){let t=i.deadlineMs===void 0?0:i.deadlineMs;if(t!==null){for(let n=u;n<=d;n++)this.mod._lt_torrent_set_piece_deadline(e,n,t,0);this.retainDeadlines(e,u,d)}this.mod._lt_torrent_post_status(e);try{await this.awaitPieces(e,u,d,i)}finally{t!==null&&this.releaseDeadlines(e,u,d)}}let f=await this.storage.read(a.storageIndex,t,n,s);return f instanceof Uint8Array?f:new Uint8Array(f)}setStreamWindow(e,t,n={}){let r=this.filesByHandle.get(e);if(!r)return!1;let{pieceLength:i,numPieces:a}=r,o=Math.max(1,Math.floor(n.windowPieces??rs)),s=Math.max(0,Math.floor(n.deadlineStepMs??is)),c=n.claimedPriority??U.normal,l=n.unclaimedPriority??U.normal,u=new Uint8Array(a).fill(l),d=n.keep&&new Uint8Array(a);if(d)for(let{start:e,end:t}of n.keep)d.fill(1,Math.max(0,e),Math.max(0,t));let f=/* @__PURE__ */ new Map,p=0;for(let e of t){let t=r.files[e.fileIndex];if(!t||t.size<=0)continue;p++;let n=Math.floor(t.offset/i),l=Math.min(a-1,Math.floor((t.offset+t.size-1)/i));for(let e=n;e<=l;e++)(!d||d[e])&&(u[e]=c);let m=Math.min(Math.max(e.offset,0),Math.max(0,t.size-1)),h=Math.min(Math.max(Math.floor((t.offset+m)/i),n),l);for(let e=0;e<o;e++){let t=h+e;if(t>l)break;u[t]=U.top;let n=e*s,r=f.get(t);(r===void 0||n<r)&&f.set(t,n)}}if(!p)return!1;if(this.mod._lt_torrent_clear_piece_deadlines(e),this.prioritizePieces(e,u),n.deadlines!==!1){for(let[t,n]of f)this.mod._lt_torrent_set_piece_deadline(e,t,n,0);this.windows.add(e)}else this.windows.delete(e);return this.reissueReadDeadlines(e),n.sequential!==!1&&this.setSequential(e,!0),!0}hasStreamWindow(e){return this.windows.has(e)}clearStreamWindow(e){this.windows.delete(e),this.mod._lt_torrent_clear_piece_deadlines(e);let t=this.filesByHandle.get(e);t&&this.prioritizePieces(e,new Uint8Array(t.numPieces).fill(U.normal)),this.reissueReadDeadlines(e),this.setSequential(e,!1)}prioritizeRange(e,t,n,r){let i=this.filesByHandle.get(e),a=i?.files[t];if(!i||!a)return;let{pieceLength:o,numPieces:s}=i,c=Math.min(r,a.size-n);if(c<=0)return;let l=Math.max(0,Math.floor((a.offset+n)/o)),u=Math.min(s-1,Math.floor((a.offset+n+c-1)/o));if(u<l)return;let d=new Uint8Array(s).fill(U.normal);for(let e=l;e<=u;e++)d[e]=U.top;this.windows.delete(e),this.mod._lt_torrent_clear_piece_deadlines(e),this.prioritizePieces(e,d);for(let t=l;t<=u;t++)this.mod._lt_torrent_set_piece_deadline(e,t,(t-l)*is,0);this.reissueReadDeadlines(e)}setSequential(e,t){this.mod._lt_torrent_set_sequential(e,+!!t)}setFlags(e,t,n){this.mod._lt_torrent_set_flags(e,t>>>0,n>>>0)}setFlag(e,t,n){this.setFlags(e,n?t:0,t)}forceReannounce(e){this.mod._lt_torrent_force_reannounce(e)}moveInQueue(e,t){this.mod._lt_torrent_queue_position(e,Yo[t])}setRateLimits({download:e,upload:t,limitLocalPeers:n}){let r=e=>e==null?-1:Math.max(0,Math.floor(e));this.mod._lt_session_set_rate_limits(r(e),r(t),n==null?-1:+!!n)}setUploadLimit(e,t){this.mod._lt_torrent_set_upload_limit(e,Math.max(0,Math.floor(t)))}setDownloadLimit(e,t){this.mod._lt_torrent_set_download_limit(e,Math.max(0,Math.floor(t)))}setPieceDeadline(e,t,n,r=!1){this.mod._lt_torrent_set_piece_deadline(e,t,n,+!!r)}clearPieceDeadlines(e){this.mod._lt_torrent_clear_piece_deadlines(e),this.reissueReadDeadlines(e)}resetPieceDeadline(e,t){this.mod._lt_torrent_reset_piece_deadline(e,t)}cancelPieceRequests(e,t){return this.mod._lt_torrent_cancel_piece_requests(e,t)===0}forgetPieces(e,t){let n=[...t];this.drainAlerts();let r=this.mod,i=r._malloc(n.length*4+4),a=i+n.length*4;try{for(let e=0;e<n.length;e++)r.HEAP32[(i>>2)+e]=n[e]|0;r.HEAP32[a>>2]=0;let t=r._lt_torrent_forget_pieces(e,i,n.length,a);if(t<0)return null;let o=this.bitfieldByHandle.get(e);if(o)for(let e of n)e>=0&&e<o.numPieces&&(o.pieces[e>>3]&=~(128>>(e&7)));return{forgotten:t,busy:r.HEAP32[a>>2]}}finally{r._free(i)}}prioritizePieces(e,t){let n=this.mod,r=this.filesByHandle.get(e);if(!r||!r.numPieces)return;let i=t;if(i.length!==r.numPieces){let t=new Uint8Array(r.numPieces),n=this.priosByHandle.get(e);n?t.set(n.subarray(0,r.numPieces)):t.fill(U.normal),t.set(i.subarray(0,r.numPieces)),i=t}let a=n._malloc(i.length);n.HEAPU8.set(i,a);try{n._lt_torrent_prioritize_pieces(e,a,i.length)===0&&this.priosByHandle.set(e,Uint8Array.from(i,e=>Math.min(e,U.top)))}finally{n._free(a)}}prioritizePieceList(e,t){let n=this.mod,r=this.filesByHandle.get(e);if(!r)return;let i=[...t].filter(e=>e.piece>=0&&e.piece<r.numPieces);if(!i.length)return;let a=n._malloc(i.length*4),o=n._malloc(i.length);try{let t=this.priosByHandle.get(e);for(let e=0;e<i.length;e++){let{piece:r,priority:s}=i[e],c=Math.min(Math.max(s,0),U.top);n.HEAP32[(a>>2)+e]=r,n.HEAPU8[o+e]=c,t&&r<t.length&&(t[r]=c)}n._lt_torrent_prioritize_piece_list(e,a,o,i.length)}finally{n._free(a),n._free(o)}}setFilePriorities(e,t){let n=this.mod;if(!t.length)return;let r=n._malloc(t.length);n.HEAPU8.set(t,r);try{n._lt_torrent_prioritize_files(e,r,t.length)}finally{n._free(r)}this.priosByHandle.delete(e)}setFilePriority(e,t,n){let r=this.mod._lt_torrent_set_file_priority(e,t,n)===0;return r&&this.priosByHandle.delete(e),r}piecePriorities(e){let t=this.priosByHandle.get(e);return t?Uint8Array.from(t):null}retainDeadlines(e,t,n){let r=this.deadlineRefs.get(e);r||this.deadlineRefs.set(e,r=/* @__PURE__ */ new Map);for(let e=t;e<=n;e++)r.set(e,(r.get(e)??0)+1)}releaseDeadlines(e,t,n){let r=this.deadlineRefs.get(e);if(!r)return;let i=[],a=this.priosByHandle.get(e);for(let o=t;o<=n;o++){let t=(r.get(o)??0)-1;if(t>0){r.set(o,t);continue}r.delete(o),this.mod._lt_torrent_reset_piece_deadline(e,o),i.push({piece:o,priority:a?.[o]??U.normal})}i.length&&this.prioritizePieceList(e,i),r.size||this.deadlineRefs.delete(e)}reissueReadDeadlines(e){let t=this.deadlineRefs.get(e);if(t)for(let n of t.keys())this.mod._lt_torrent_set_piece_deadline(e,n,0,0)}postStatus(e){this.mod._lt_torrent_post_status(e)}infohash(e){return this.readHash(e,this.mod._lt_torrent_infohash)}infohashV2(e){return this.readHash(e,this.mod._lt_torrent_infohash_v2)}webSocketTrackers(e){let t=this.mod.UTF8ToString(this.mod._lt_torrent_ws_trackers(e));return t?t.split(`
|
|
4
|
-
`):[]}isPrivate(e){let t=this.mod._lt_torrent_private(e);return t<0?void 0:t===1}readHash(e,t){let n=this.mod,r=n._malloc(65);try{return t.call(n,e,r)===0?n.UTF8ToString(r):null}finally{n._free(r)}}hasPieces(e,t,n){let r=this.bitfieldByHandle.get(e);if(!r)return!1;for(let e=t;e<=n;e++){if(e<0||e>=r.numPieces)return!1;let t=r.pieces[e>>3];if(t===void 0||!(t&128>>(e&7)))return!1}return!0}awaitPieces(e,t,n,r){let{signal:i}=r,a=r.timeoutMs??ns;return new Promise((r,o)=>{let s,c,l=e=>{let t=this.pieceWaiters.indexOf(u);t<0||(this.pieceWaiters.splice(t,1),s!==void 0&&clearTimeout(s),c&&i&&i.removeEventListener(`abort`,c),e?o(e):r())},u={handle:e,p0:t,p1:n,settle:l};if(this.pieceWaiters.push(u),i?.aborted){l(/* @__PURE__ */ Error(`read: aborted`));return}a>0&&(s=setTimeout(()=>l(/* @__PURE__ */ Error(`read: pieces ${t}-${n} of handle ${e} did not arrive within ${a}ms`)),a)),i&&(c=()=>l(/* @__PURE__ */ Error(`read: aborted`)),i.addEventListener(`abort`,c,{once:!0}))})}resolvePieceWaiters(){if(this.pieceWaiters.length!==0)for(let e of[...this.pieceWaiters])this.hasPieces(e.handle,e.p0,e.p1)&&e.settle()}failPieceWaiters(e,t){for(let n of[...this.pieceWaiters])(t===void 0||n.handle===t)&&n.settle(e)}popAlerts(){this.drainAlerts();let e=this.textAlerts;return this.textAlerts=[],e}drainAlerts(){let e=this.mod;e._lt_session_pump_alerts();let t=e._lt_alerts_size()>>>0;if(!t)return;let n=e._lt_alerts_data()>>>0,r=new DataView(e.HEAPU8.buffer,n,t),i=this.textAlerts,a=0;try{for(;a+8<=t;){let o=r.getUint32(a,!0);a+=4;let s=r.getUint32(a,!0);if(a+=4,a+s>t)break;if(o===Ho)this.decodeTorrentReady(r,a);else if(o===Uo)this.decodeStateUpdate(r,a);else if(o===Go)this.decodeResumeData(r,a,s);else if(o===Ko)this.decodePeers(r,a);else if(o===qo)this.decodeTrackers(r,a);else if(o!==Wo){let t={type:o,message:e.UTF8ToString(n+a,s)};this.observeReachability(t.message),i.push(t)}a+=s}}finally{e._lt_alerts_clear(),this.resolvePieceWaiters()}}reachable(){let e=this.reachability.port,t=e===null?null:this.shim()?.announced||e,n=this.listeners();return{listening:{...this.reachability.listening},listenFailed:[...this.reachability.listenFailed],inbound:this.reachability.inbound,inboundByTransport:{...this.reachability.inboundByTransport},lastInbound:this.reachability.lastInbound,port:t,listeners:n,portOpen:t!==null&&n.some(e=>e.up&&e.port===t)}}listeners(){try{return this.shim()?.listeners?.()??[]}catch{return[]}}shim(){return this.mod.__FKN}observeReachability(e){let t=Ro.exec(e);if(t){let e=t[2].toLowerCase();this.reachability.inbound++,this.reachability.inboundByTransport[e]=(this.reachability.inboundByTransport[e]??0)+1,this.reachability.lastInbound={endpoint:t[1],transport:e,at:Date.now()};return}let n=zo.exec(e);if(n){this.reachability.listening[n[1].toLowerCase()]=n[2];return}Bo.test(e)&&this.reachability.listenFailed.length<32&&this.reachability.listenFailed.push(e)}readStr(e,t){let n=e.getUint32(t,!0);return t+=4,[Vo.decode(new Uint8Array(e.buffer,e.byteOffset+t,n)),t+n]}decodePeers(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getUint32(t,!0);t+=4;let i=[];for(let n=0;n<r;n++){let n,r;[n,t]=this.readStr(e,t),[r,t]=this.readStr(e,t);let a=e.getUint32(t,!0);t+=4;let o=e.getUint32(t,!0);t+=4;let s=e.getUint32(t,!0);t+=4;let c=e.getInt32(t,!0);t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=Number(e.getBigInt64(t,!0));t+=8;let p=Number(e.getBigInt64(t,!0));t+=8;let m=e.getInt32(t,!0)/1e6;t+=4;let h=e.getInt32(t,!0);t+=4;let g=e.getInt32(t,!0);t+=4;let _=e.getInt32(t,!0);t+=4;let v=e.getInt32(t,!0);t+=4;let y=a&Jo.localConnection?ts(n):-1;i.push({endpoint:y<0?n:`webrtc:${y}`,transport:y>=0?`webrtc`:a&Jo.utpSocket?`utp`:`tcp`,client:r,flags:a,source:o,connectionType:s,downloadRate:c,uploadRate:l,payloadDownloadRate:u,payloadUploadRate:d,totalDownload:f,totalUpload:p,progress:m,rtt:h,numPieces:g,requestsInFlight:_,failCount:v})}this.peersByHandle.set(n,i),this.resolveOne(this.peerWaiters,n,i)}decodeTrackers(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getUint32(t,!0);t+=4;let i=[];for(let n=0;n<r;n++){let n,r;[n,t]=this.readStr(e,t),[r,t]=this.readStr(e,t);let a=e.getInt32(t,!0);t+=4;let o=e.getInt32(t,!0);t+=4;let s=e.getUint32(t,!0)!==0;t+=4;let c=e.getUint32(t,!0)!==0;t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=e.getInt32(t,!0);t+=4,i.push({url:n,message:r,tier:a,fails:o,updating:s,verified:c,nextAnnounceIn:l,seeders:u,leechers:d,downloaded:f})}this.trackersByHandle.set(n,i),this.resolveOne(this.trackerWaiters,n,i)}decodeResumeData(e,t,n){let r=e.getUint32(t,!0),i=new Uint8Array(n-4);i.set(new Uint8Array(e.buffer,e.byteOffset+t+4,n-4)),this.resumeByHandle.set(r,i),this.resumeWaiters=this.resumeWaiters.filter(e=>e.handle!==r||(clearTimeout(e.timer),e.resolve(i),!1))}decodeTorrentReady(e,t){let n=new TextDecoder,r=e.getUint32(t,!0);t+=4;let i=e.getUint32(t,!0);t+=4;let a=e.getUint32(t,!0);t+=4;let o=e.getUint32(t,!0);t+=4;let s=Number(e.getBigInt64(t,!0));t+=8;let c=e.getUint32(t,!0);t+=4;let l=[];for(let r=0;r<c;r++){let r=Number(e.getBigInt64(t,!0));t+=8;let i=Number(e.getBigInt64(t,!0));t+=8;let a=e.getUint8(t)===1;t+=1;let o=e.getUint32(t,!0);t+=4;let s=n.decode(new Uint8Array(e.buffer,e.byteOffset+t,o));t+=o,l.push({path:s,size:i,offset:r,pad:a})}let u=l.reduce((e,t)=>e+(t.pad?0:t.size),0);this.filesByHandle.set(r,{storageIndex:i,pieceLength:a,numPieces:o,totalSize:s,contentSize:u,files:l})}decodeStateUpdate(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getInt32(t,!0);t+=4;let i=Number(e.getBigInt64(t,!0));t+=8;let a=Number(e.getBigInt64(t,!0));t+=8;let o=Number(e.getBigInt64(t,!0));t+=8;let s=e.getFloat32(t,!0);t+=4;let c=e.getInt32(t,!0);t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=e.getUint32(t,!0)!==0;t+=4;let p=e.getUint32(t,!0)!==0;t+=4;let m=e.getUint32(t,!0)!==0;t+=4;let h=e.getUint32(t,!0)>>>0;t+=4;let g=Number(e.getBigInt64(t,!0));t+=8;let _=Number(e.getBigInt64(t,!0));t+=8;let v=Number(e.getBigInt64(t,!0));t+=8;let y=Number(e.getBigInt64(t,!0));t+=8;let b=Number(e.getBigInt64(t,!0));t+=8;let x=Number(e.getBigInt64(t,!0));t+=8;let S=Number(e.getBigInt64(t,!0));t+=8;let C=e.getInt32(t,!0);t+=4;let w=e.getInt32(t,!0);t+=4;let T=e.getInt32(t,!0);t+=4;let E=e.getInt32(t,!0);t+=4,t+=4;let D=e.getFloat32(t,!0);t+=4;let O=e.getInt32(t,!0);t+=4;let ee=e.getInt32(t,!0);t+=4;let k=Number(e.getBigInt64(t,!0));t+=8;let te=Number(e.getBigInt64(t,!0));t+=8;let A=Number(e.getBigInt64(t,!0));t+=8;let ne=e.getUint32(t,!0)!==0;t+=4;let j;[j,t]=this.readStr(e,t);let M=e.getInt32(t,!0);t+=4;let N=e.getInt32(t,!0);t+=4;let P=e.getUint32(t,!0);t+=4;let F=P?Vo.decode(new Uint8Array(e.buffer,e.byteOffset+t,P)):``;t+=P;let re=e.getUint32(t,!0);t+=4;let I=e.getUint32(t,!0);t+=4;let L=new Uint8Array(I);L.set(new Uint8Array(e.buffer,e.byteOffset+t,I)),this.bitfieldByHandle.set(n,{pieces:L,numPieces:re});let ie=0;for(let e=0;e<I;e++){let t=L[e];for(;t;)ie+=t&1,t>>=1}this.statusByHandle.set(n,{state:r,progress:s,totalDone:i,totalWanted:a,totalWantedDone:o,downloadRate:c,uploadRate:l,numPeers:u,numSeeds:d,numPiecesTotal:re,numPiecesHave:ie,paused:f,autoManaged:p,sequential:m,flags:h,queuePosition:M,errorCode:N,error:F,allTimeDownload:g,allTimeUpload:_,sessionDownload:v,sessionUpload:y,sessionPayloadDownload:b,sessionPayloadUpload:x,wasted:S,swarmSeeds:C,swarmPeers:w,numConnections:T,connectionsLimit:E,availability:D,activeSeconds:O,seedingSeconds:ee,addedAt:k,completedAt:te,lastSeenComplete:A,hadIncoming:ne,savePath:j,hasMetadata:r!==Lo.downloadingMetadata})}async*alerts(){for(;!this.destroyed;){for(let e of this.popAlerts())yield e;await new Promise(e=>setTimeout(e,100))}}setReservedPort(e){this.reachability.port=e}tick(){if(!this.destroyed&&(this.mod._lt_session_tick(),this.pieceWaiters.length)){let e=new Set(this.pieceWaiters.map(e=>e.handle));for(let t of e)this.mod._lt_torrent_post_status(t)}}destroy(){if(this.destroyed)return;this.destroyed=!0,this.fallbackTimer!=null&&clearInterval(this.fallbackTimer),this.failPieceWaiters(/* @__PURE__ */ Error(`read: session destroyed`)),this.pieceWaiters=[];for(let e of this.resumeWaiters)clearTimeout(e.timer),e.reject(/* @__PURE__ */ Error(`save_resume_data: session destroyed`));this.resumeWaiters=[],this.deadlineRefs.clear(),this.priosByHandle.clear(),this.handles.clear();for(let e of[...this.streams.keys()])this.dropStream(e,`the session was destroyed`);let e=()=>this.mod.__FKN?.teardown?.();this.mod._lt_session_destroy()?queueMicrotask(()=>{this.mod._lt_session_destroy(),e()}):e()}},os=8e3,ss=e=>String(e?.message).includes(`listening needs a signed-in account`)||e?.name===`WebVpnError`&&e?.code===5||e?.code===`AUTH_REQUIRED`,cs=e=>{try{e?.close()}catch{}},ls=(e,t,n)=>new Promise(r=>{let i;try{i=e()}catch{r(null);return}if(!i||typeof i.on!=`function`){r(null);return}let a=!1,o=e=>{a||(a=!0,clearTimeout(s),cs(i),n?.(e),r(null))},s=setTimeout(o,os);i.on(`listening`,()=>{a||(a=!0,clearTimeout(s),r(i))}),i.on(`error`,o);try{t(i)}catch(e){o(e)}});async function us(e,t,n=4){try{return await ds(e,t,n)}catch{return null}}async function ds(e,t,n){for(let r=0;r<n;r++){let i=await ls(()=>t.createSocket({type:`udp4`}),e=>e.bind(0,`0.0.0.0`));if(!i)return null;let a=i.address?.()?.port;if(!a)return cs(i),null;let o,s=await ls(()=>e.createServer(),e=>e.listen(a,`0.0.0.0`),e=>{o=e}),c=s?s.address?.()?.port:void 0,l=!!s&&c===a;if(s&&!l&&cs(s),!l){if(ss(o))return{port:a,server:null,udp:i,backlog:[],adopted:!1,authRequired:!0};if(r<n-1){cs(i);continue}return{port:a,server:null,udp:i,backlog:[],adopted:!1}}let u={port:a,server:s,udp:i,backlog:[],adopted:!1};return s.on(`connection`,e=>{u.adopted||u.backlog.push(e)}),u}return null}function fs(){return{net:{connect:()=>{let e;return queueMicrotask(()=>e?.(Object.assign(/* @__PURE__ */ Error(`offline host: connection refused`),{code:`ECONNREFUSED`}))),{on(t,n){t===`error`&&(e=n)},write:()=>!0,destroy(){}}},createServer:()=>({on(){},listen(){},close(){}})},dgram:{createSocket:()=>({on(){},bind(){},send(){},close(){}})},dnsLookup:async()=>void 0}}async function ps(e){let t=e.moduleFactory??(await import(`./libtorrent-53Uv1CpQ.js`)).default,n={net:e.net,dgram:e.dgram,storage:e.storage??null,debug:e.debug??!1,dnsLookup:e.dnsLookup,listenNeedsAccount:ss},r=e.reserveListenPort===!1?Promise.resolve(null):us(e.net,e.dgram),i=await t({fkn:n});i._lt_set_log(+!!e.debug);let a=await r;a?(n.prebound=a,i._lt_set_listen_port(a.port),!a.server&&e.debug&&console.warn(`[fkn] reserved udp ${a.port} but no matching tcp listener: inbound uTP works, inbound TCP is dark`)):e.debug&&console.warn(`[fkn] nothing reserved: the announced port is not one anyone can reach`);let o;try{o=new as(i,e)}catch(e){throw a&&!a.adopted&&(cs(a.server),cs(a.udp)),e}return o.setReservedPort(a?a.port:null),o}const ms=e=>{let t=[],n=[],r=!1;for(let i of e.slice(e.indexOf(`?`)+1).split(`&`)){let e=i.indexOf(`=`);if(r||e<0){r=e<0;continue}if(!/^xt(\.\d*)?$/i.test(i.slice(0,e)))continue;let a=i.slice(e+1);try{a=decodeURIComponent(a)}catch{}let o=a.match(/^urn:btih:([0-9a-zA-Z]+)/)?.[1];if(o){t.push(o.toLowerCase());continue}let s=a.match(/^urn:btmh:([0-9a-fA-F]+)/)?.[1]?.toLowerCase();s&&n.push(s.startsWith(`1220`)&&s.length===68?s.slice(4):s)}return new Set(t.map(hs)).size>1||new Set(n).size>1?null:t[0]??n[0]??null},hs=e=>{let t=e.toLowerCase();if(!/^[a-z2-7]{32}$/.test(t))return t;let n=``;for(let e of t)n+=`abcdefghijklmnopqrstuvwxyz234567`.indexOf(e).toString(2).padStart(5,`0`);let r=``;for(let e=0;e<n.length;e+=4)r+=parseInt(n.slice(e,e+4),2).toString(16);return r},gs=(e,t)=>!!e&&!!t&&hs(e)===hs(t),_s=(e,t)=>{let n=[];for(let r of e.matchAll(RegExp(`[?&]`+t+`=([^&]+)`,`g`))){let e=r[1];try{n.push(decodeURIComponent(e.replace(/\+/g,` `)))}catch{n.push(e)}}return[...new Set(n)]},vs=25e5,ys=e=>{if(!Number.isFinite(e)||e<=0)return 12;let t=Math.ceil(vs/e)+1,n=Math.max(2,Math.floor(8388608/e));return Math.min(Math.max(t,2),n)},bs=e=>ys(e)*Math.max(0,e),xs=e=>Math.max(1,Math.floor(bs(e)/2)),Ss=(e,t)=>Math.min(2e3,Math.max(50,Math.round(e/Math.max(t,25e4)*1e3))),Cs=(e,t,n,r=vs)=>{let i=e.fileOffset+n+Math.max(0,r-1);return Math.floor(i/e.pieceLength)>=e.p1?!1:Math.abs(n-t)>=xs(e.pieceLength)};var ws=(e,t,n)=>{let r=e.write(t,n);if(r<t.byteLength){let e=`the storage quota took ${r} of ${t.byteLength} bytes`,n=globalThis.QuotaExceededError;throw n?new n(e):new DOMException(e,`QuotaExceededError`)}return r},Ts=(e,t)=>e.createSyncAccessHandle(t).finally(()=>e),Es=class{storages=/* @__PURE__ */ new Map;opened=/* @__PURE__ */ new Map;onNewStorage(e,t,n){let r=(async()=>{let r=await Ds(await navigator.storage.getDirectory(),t.replace(/^\/+/,``));this.storages.set(e,{rootDir:r,files:/* @__PURE__ */ new Map,opening:/* @__PURE__ */ new Map,fileMeta:n})})();return this.opened.set(e,r),r.then(()=>{this.opened.get(e)===r&&this.opened.delete(e)},()=>{}),r}async onRemoveStorage(e){this.opened.delete(e);let t=this.storages.get(e);if(t){for(let e of t.files.values())try{e.close()}catch{}this.storages.delete(e)}}read(e,t,n,r){let i=this.openFile(e,t),a=e=>{let t=new Uint8Array(r),i=e.read(t,{at:n});return i<r&&t.fill(0,i),t};return i instanceof Promise?i.then(a):a(i)}write(e,t,n,r){let i=this.openFile(e,t),a=i=>{try{let a=i.write(r,{at:n});if(a<r.length)throw console.error(`[opfs] short write`,{id:e,fileIndex:t,offset:n,want:r.length,wrote:a}),Error(`short write`)}catch(i){throw console.error(`[opfs] write failed`,{id:e,fileIndex:t,offset:n,len:r.length,err:String(i),errName:i?.name,errMsg:i?.message,isView:ArrayBuffer.isView(r),bytesType:Object.prototype.toString.call(r)}),i}};return i instanceof Promise?i.then(a).catch(n=>{throw console.error(`[opfs] openFile failed`,{id:e,fileIndex:t,err:String(n)}),n}):a(i)}async release(e){let t=this.storages.get(e);if(t){for(let e of t.files.values())try{e.flush(),e.close()}catch{}t.files.clear()}}async stop(e){return this.release(e)}async check(e){let t=!1;if(await this.opened.get(e)?.catch(()=>{t=!0}),t)return 2;let n=this.storages.get(e);if(!n)return 0;await this.release(e);for(let e of n.fileMeta)if(await this.hasBytes(n,e.path))return 2;return 0}async hasBytes(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(!r)return!1;let i=e.rootDir;try{for(let e of n)i=await i.getDirectoryHandle(e);return(await(await i.getFileHandle(r)).getFile()).size>0}catch(e){return e?.name!==`NotFoundError`}}async deleteFiles(e,t){let n=this.storages.get(e);if(n){for(let e of n.files.values())try{e.close()}catch{}n.files.clear();for(let e of n.fileMeta){let t=e.path.split(`/`).filter(Boolean),r=t.pop();if(!r)continue;let i=n.rootDir;for(let e of t)try{i=await i.getDirectoryHandle(e)}catch{i=null;break}if(i)try{await i.removeEntry(r)}catch{}}}}openFile(e,t){let n=this.storages.get(e);if(!n)throw Error(`unknown storage ${e}`);let r=n.files.get(t);if(r)return r;let i=n.opening.get(t);if(i)return i;let a=this.openFileSlow(e,t);return n.opening.set(t,a),a.finally(()=>n.opening.delete(t)),a}async openFileSlow(e,t){let n=this.storages.get(e),r=n.fileMeta[t];if(!r)throw Error(`unknown file ${t}`);let i=r.path.split(`/`).filter(Boolean),a=i.pop(),o=n.rootDir;for(let e of i)o=await o.getDirectoryHandle(e,{create:!0});let s=await Ts(await o.getFileHandle(a,{create:!0}));return n.files.set(t,s),s}};async function Ds(e,t){if(!t)return e;let n=e;for(let e of t.split(`/`).filter(Boolean))n=await n.getDirectoryHandle(e,{create:!0});return n}const Os=[50,150,400,900,1500],ks=e=>e?.name===`QuotaExceededError`,As=(e,t,n)=>{if(n>0&&e&&!e(t,n))throw new DOMException(`kept for temporary films`,`QuotaExceededError`)},js=e=>Ts(e),Ms=e=>new Promise(t=>setTimeout(t,e)),Ns=e=>{let t=async(t,n,r,i)=>{let a=i;for(let i of Os){if(ks(a))break;if(n(),await Ms(i),e.has(t))throw a;try{return await r()}catch(e){a=e}}throw a};return(e,n,r)=>{try{let i=r();return i instanceof Promise?i.catch(i=>t(e,n,r,i)):i}catch(i){return t(e,n,r,i)}}},Ps=e=>{let t=new Es,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=t,o=(e,t)=>{let n=a.storages?.get(e),r=n?.files?.get(t);if(r){n.files.delete(t);try{r.close()}catch{}}},s=async(e,t)=>{let n=a.storages?.get(e);if(!n?.fileMeta||!n.rootDir)return null;let r=0;for(let e=0;e<n.fileMeta.length;e++){if(t!==void 0&&e!==t)continue;let i=n.files?.get(e);if(i)try{r+=i.getSize();continue}catch{}let a=n.fileMeta[e].path.split(`/`).filter(Boolean),o=a.pop();if(!o)continue;let s=n.rootDir;for(let e of a)s=s?await s.getDirectoryHandle(e).catch(()=>null):null;s&&(r+=await s.getFileHandle(o).then(e=>e.getFile()).then(e=>e.size).catch(()=>0))}return r},c=async e=>{let t=r.get(e);return t===void 0?null:s(t)},l=Ns(n),u=(e,t,n)=>l(e,()=>o(e,t),n),d=(t,n,r,o)=>{let s=a=>{try{As(e,t,r+o.length-a.getSize()),ws(a,o,{at:r})}catch(e){throw ks(e)&&i.set(t,n),e}},c=a.openFile(t,n);return c instanceof Promise?c.then(s):s(c)};return{usageOf:c,usageOfStorage:s,refusedFile:e=>i.get(e),onNewStorage:(e,a,o)=>(n.delete(e),i.delete(e),r.set(a,e),u(e,-1,()=>t.onNewStorage(e,a,o))),onRemoveStorage:e=>{n.add(e);for(let[t,n]of r)n===e&&r.delete(t);return t.onRemoveStorage(e)},read:(e,n,r,i)=>u(e,n,()=>t.read(e,n,r,i)),write:(e,t,n,r)=>u(e,t,()=>d(e,t,n,r)),release:e=>t.release(e),check:e=>t.check(e).catch(()=>2),deleteFiles:(e,r)=>(n.add(e),t.deleteFiles(e,r)),stop:e=>t.stop(e)}},Fs=67108864,Is={start:0,end:0},Ls=(e,t,n)=>{let r=Math.min(n,e.size);return r<=t?Is:{start:Math.floor((e.offset+t)/e.pieceLength),end:Math.floor((e.offset+r-1)/e.pieceLength)+1}},Rs=(e,t,n)=>Ls(e,n*t,(n+1)*t),zs=(e,t,n)=>{let r=/* @__PURE__ */ new Set;for(let{start:i,end:a}of n){let n=Math.max(0,i*e.pieceLength-e.offset),o=Math.min(e.size,a*e.pieceLength-e.offset);for(let e=Math.floor(n/t);n<o&&e<=Math.floor((o-1)/t);e++)r.add(e)}return r},Bs=(e,t)=>{let n=[],r=t,i=e.map((e,t)=>({size:e,i:t})).sort((e,t)=>e.size-t.size);return i.forEach(({size:e,i:t},a)=>{let o=Math.min(e,r/(i.length-a));n[t]=o,r-=o}),n},Vs=(e,t,n)=>e>t&&Math.floor(t/n)>=23,Hs=({file:e,chunkBytes:t,room:n,reader:r,held:i,pinned:a=[]})=>{if(!Vs(e.size,n,t))return null;let o=Math.ceil(e.size/t)-1,s=Math.floor(Math.min(Math.max(r,0),e.size-1)/t),c=Math.floor(n/t)-3,l=new Set(i),u=Ls(e,0,t),d=Math.max(0,o-2-s),f=n=>{if(!d){let n=Ls(e,s*t,e.size);return{want:[u,n],ahead:n,slack:Is}}let r=Ls(e,s*t,n*t),i=Ls(e,n*t,(n+2)*t);return{want:[u,r,i,Ls(e,o*t,e.size)],ahead:r,slack:i}},p=n=>zs(e,t,[...f(n).want,...a]),m=s+Math.min(16,d),h=p(m);for(;m<s+d;){let e=p(m+1);if(e.size>c||[...e].some(e=>!h.has(e)&&!l.has(e))&&(/* @__PURE__ */ new Set([...e,...l])).size>c)break;m++,h=e}let g=/* @__PURE__ */ new Set([...h,...l]),_=[...l].filter(e=>!h.has(e)).sort((e,t)=>Math.abs(t-s)-Math.abs(e-s)||t-e);for(let e of _){if(g.size<=c)break;g.delete(e)}return{...f(m),keep:[...g].sort((e,t)=>e-t)}},Us=(e,t,n)=>e||t<n,Ws=(e,t,n)=>{if(!e||t.usedBytes<e.usedBytes||t.headroomBytes>e.headroomBytes)return{...t,fixed:e?.fixed};let r=t.usedBytes-e.usedBytes;return r<n?e:{...t,fixed:e.headroomBytes-t.headroomBytes>=r/2}},Gs=/^(\d+)-(\d+)$/,Ks=/^\d+$/,qs=(e=Fs,t)=>{let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set,s=Ns(o),c=/* @__PURE__ */ new Map,l=(e,t,n)=>{let r=`${e}/${t}`,i=c.get(r);i||c.set(r,i=/* @__PURE__ */ new Set),i.add(n);let a=()=>{i.delete(n),!i.size&&c.get(r)===i&&c.delete(r)};n.then(a,a)},u=(e,t)=>`${e}-${t}`,d=e=>{let t=i.get(e);return t===void 0?void 0:n.get(t)},f=(e,t)=>{let i=n.get(e);if(i)return t(i);let a=r.get(e);if(!a)throw Error(`unknown storage ${e}`);return a.then(t)},p=(e,t,n,r)=>{let i=[];for(let a=0;a<r;){let o=Math.floor((n+a)/e.chunkBytes),s=n+a-o*e.chunkBytes,c=Math.min(r,a+e.chunkBytes-s);i.push({name:u(t,o),at:s,from:a,to:c}),a=c}return i},m=(e,t)=>{let n=e.handles.get(t);if(n)return n;let r=e.opening.get(t);if(r)return r;let i=e.dropping.get(t),a=(async()=>{i&&await i;let n=await js(await e.dir.getFileHandle(t,{create:!0}));return e.handles.set(t,n),n})();e.opening.set(t,a);let o=()=>{e.opening.get(t)===a&&e.opening.delete(t)};return a.then(o,o),a},h=(e,t,r,i)=>{let a=n.get(e);if(a)for(let{name:e}of p(a,t,r,i)){let t=a.handles.get(e);a.handles.delete(e);try{t?.close()}catch{}}},g=e=>{for(let t of e.handles.values())try{t.flush(),t.close()}catch{}e.handles.clear()},_=(e,t)=>{let n=0;for(let[r,i]of e.extents)(t===void 0||r.startsWith(`${t}-`))&&(n+=i);return n},v=async(e,t)=>{if(e===void 0)return null;let i=n.get(e)??await r.get(e)?.catch(()=>void 0);return i?_(i,t):null},y=async t=>{let n=t.split(`/`).filter(Boolean),r=n.pop()??``,i=await navigator.storage.getDirectory();for(let e of n)i=await i.getDirectoryHandle(e,{create:!0});let a=await i.getDirectoryHandle(r,{create:!0}),o=e=>e.values(),s=e;for await(let e of o(a))e.kind===`directory`&&Ks.test(e.name)&&(s=Number(e.name));let c=await a.getDirectoryHandle(String(s),{create:!0}),l=/* @__PURE__ */ new Map;for await(let e of o(c))e.kind===`file`&&l.set(e.name,await e.getFile().then(e=>e.size,()=>s));return{parent:i,name:r,chunkBytes:s,dir:c,extents:l,handles:/* @__PURE__ */ new Map,opening:/* @__PURE__ */ new Map,dropping:/* @__PURE__ */ new Map}};return{chunkBytesOf:t=>d(t)?.chunkBytes??e,chunksOf:(e,t)=>{let n=d(e);if(!n)return[];let r=[];for(let[e,i]of n.extents){let n=Gs.exec(e);n&&Number(n[1])===t&&i>0&&r.push(Number(n[2]))}return r.sort((e,t)=>e-t)},footprint:()=>{let e=0;for(let t of n.values())e+=_(t);return e},usageOf:e=>v(i.get(e)),usageOfStorage:v,refusedFile:e=>a.get(e),drop:(e,t,n)=>{let r=d(e);if(!r)return Promise.resolve();let i=u(t,n),a=r.dropping.get(i);if(a)return a;r.extents.delete(i);let o=r.handles.get(i);r.handles.delete(i);try{o?.close()}catch{}let s=r.opening.get(i),c=(async()=>{s&&await s.then(e=>{r.handles.get(i)===e&&r.handles.delete(i);try{e.close()}catch{}},()=>{}),await r.dir.removeEntry(i).catch(()=>{})})();return r.dropping.set(i,c),c.then(()=>{r.dropping.get(i)===c&&r.dropping.delete(i)}),c},readChunk:async(e,t,n)=>{let r=d(e),i=u(t,n);if(!r?.extents.has(i))return/* @__PURE__ */ new Uint8Array;let a=await m(r,i),o=new Uint8Array(a.getSize());return a.read(o,{at:0}),o},onNewStorage:(e,t)=>{o.delete(e),a.delete(e),i.set(t,e);let c=Promise.resolve(s(e,()=>{},()=>y(t)));return r.set(e,c),c.then(t=>{r.get(e)===c&&(r.delete(e),n.set(e,t))})},onRemoveStorage:e=>{o.add(e),r.delete(e);let t=n.get(e);n.delete(e);for(let[t,n]of i)n===e&&i.delete(t);t&&g(t)},read:(e,t,n,r)=>s(e,()=>h(e,t,n,r),()=>f(e,i=>{let a=new Uint8Array(r),o=[];for(let s of p(i,t,n,r)){let t=()=>{if(!i.extents.has(s.name))return;let e=e=>{e.read(a.subarray(s.from,s.to),{at:s.at})},t=m(i,s.name);if(t instanceof Promise)return t.then(e);e(t)},n=c.get(`${e}/${s.name}`);if(n)o.push(Promise.allSettled([...n]).then(t));else{let e=t();e&&o.push(e)}}return o.length?Promise.all(o).then(()=>a):a})),write:(e,i,o,c)=>{let u=s(e,()=>h(e,i,o,c.length),()=>f(e,n=>{let r=[];for(let s of p(n,i,o,c.length)){let o=r=>{try{As(t,e,s.at+s.to-s.from-(n.extents.get(s.name)??0)),ws(r,c.subarray(s.from,s.to),{at:s.at})}catch(t){ks(t)&&a.set(e,i);try{n.extents.set(s.name,r.getSize())}catch{}throw t}let o=s.at+s.to-s.from;(n.extents.get(s.name)??0)<o&&n.extents.set(s.name,o)},l=m(n,s.name);l instanceof Promise?r.push(l.then(o)):o(l)}return r.length?Promise.all(r).then(()=>{}):void 0}));if(u instanceof Promise){let t=t=>{for(let{name:n}of p(t,i,o,c.length))l(e,n,u)},a=n.get(e);a?t(a):r.get(e)?.then(t,()=>{})}return u},check:async e=>{try{let t=n.get(e)??await r.get(e);return t&&_(t)>0?2:0}catch{return 2}},release:async e=>{let t=n.get(e);t&&g(t)},stop:async e=>{let t=n.get(e);t&&g(t)},deleteFiles:async e=>{o.add(e);let t=n.get(e)??await r.get(e)?.catch(()=>void 0);t&&(await Promise.all([...t.opening.values()].map(e=>e.catch(()=>{}))),g(t),t.extents.clear(),await t.parent.removeEntry(t.name,{recursive:!0}).catch(()=>{}))}}},Js=[5e3,15e3,3e4,6e4,12e4,3e5],Ys=1e4,Xs=/* @__PURE__ */ new Set([2,3]),Zs=/* @__PURE__ */ new Set([1,7]),Qs=e=>!!e&&e.paused&&!e.autoManaged,$s=(e=!0)=>{let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=e=>Js[Math.min(e,Js.length-1)],o=e=>{t.delete(e),n.delete(e),r.delete(e),i.delete(e)};return{hold:(e,t,n=Ys)=>i.set(e,t+n),observe:(s,c,l,u)=>{if(l){o(s);return}if(!c)return;let d=i.get(s);if(d!==void 0){if(u<d)return;i.delete(s)}let f=n.get(s);(!f||c.totalDone>f.totalDone)&&n.set(s,{totalDone:c.totalDone,at:u});let p=n.get(s).at;if(Zs.has(c.state))return;let m=t.get(s);if(c.error&&(r.set(s,c.error),m&&(m.message=c.error)),m&&u<m.graceUntil||c.paused&&c.queued)return;let h=c.paused?`stopped`:e&&Xs.has(c.state)&&c.numPeers===0&&c.downloadRate===0&&u-p>=12e4?`stalled`:null;if(!h){if(!m)return;m.healthySince??=u,u-m.healthySince>=6e4&&o(s);return}if(!m){t.set(s,{reason:h,attempt:0,retryAt:u+a(0),message:r.get(s),healthySince:null,graceUntil:0});return}m.reason=h,m.healthySince!==null&&(m.healthySince=null,m.retryAt=u+a(m.attempt))},due:e=>{let n=[];for(let[r,i]of t)i.healthySince!==null||e<i.retryAt||(i.attempt++,i.retryAt=e+a(i.attempt),i.graceUntil=e+Ys,n.push({handle:r,reason:i.reason}));return n},retryNow:e=>{for(let n of t.values())n.healthySince===null&&(n.attempt=0,n.retryAt=e)},retry:(e,n)=>{let r=t.get(e);r&&(r.attempt=0,r.retryAt=n,r.healthySince=null,r.graceUntil=0,i.delete(e))},state:e=>{let n=t.get(e);return!n||n.healthySince!==null?null:{reason:n.reason,attempt:n.attempt,retryAt:n.retryAt,message:n.message}},forget:o,retain:e=>{for(let a of[t,n,r,i])for(let t of[...a.keys()])e.has(t)||o(t)}}},ec=e=>!(e.flags&Jo.localConnection)||!!(e.source&Xo.incoming),tc=e=>e.transport,nc={total:0,byTransport:{}},rc=e=>{let t={},n=0;for(let r of e)for(let e of r){if(!ec(e)||e.connectionType!==0)continue;n+=1;let r=tc(e);t[r]=(t[r]??0)+1}return{total:n,byTransport:t}},ic={activeSeconds:0,seedingSeconds:0},ac=[`activeSeconds`,`seedingSeconds`,`downloaded`,`uploaded`,`wasted`],oc={activeSeconds:0,seedingSeconds:0,downloaded:0,uploaded:0,wasted:0},sc=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0,cc=(e,t)=>({activeSeconds:Math.max(0,sc(t.activeSeconds)-sc(e.activeSeconds)),seedingSeconds:Math.max(0,sc(t.seedingSeconds)-sc(e.seedingSeconds))}),lc=(e,t,n)=>{let r=cc(t,n);return{activeSeconds:sc(e?.activeSeconds)+r.activeSeconds,seedingSeconds:sc(e?.seedingSeconds)+r.seedingSeconds}},uc=(e,t)=>Object.fromEntries(ac.map(n=>[n,Math.max(0,sc(t[n])-sc(e[n]))])),dc=(e,t,n)=>{let r=uc(t,n);return Object.fromEntries(ac.map(t=>[t,sc(e?.[t])+r[t]]))},fc=(e,t)=>Object.fromEntries(ac.map(n=>[n,Math.max(sc(e?.[n]),sc(t?.[n]))])),pc=(e,t)=>t.activeSeconds-sc(e?.activeSeconds)>=30||t.seedingSeconds-sc(e?.seedingSeconds)>=30,mc=67108864,hc=e=>e>0?Math.min(1677721600,Math.floor(e/2)):0,gc=e=>!Number.isFinite(e)||e<=0?0:Math.min(1e9,Math.floor(e*.1)),_c=(e,t)=>!Number.isFinite(e)||e<=0?Math.max(0,t):Math.max(Math.min(.25*e,2e10),Math.max(0,t)),vc=({usedBytes:e,limitBytes:t,pendingBytes:n,refusedBytes:r,candidates:i})=>{if(!Number.isFinite(t)||t<=0||!Number.isFinite(e)||e<0)return!1;let a=t-e,o=yc(i);return a<Math.min(n,67108864)&&n>a+o||r>0&&r+67108864>a+o},yc=e=>e.reduce((e,t)=>e+Math.max(0,t.bytesOnDisk),0),bc=({usedBytes:e,limitBytes:t,candidates:n},r)=>!r||!(t>0)||!(e>=0)?1/0:t-e+yc(n)-hc(t),xc=(e,t)=>e.usedAt-t.usedAt||(e.infoHash<t.infoHash?-1:+(e.infoHash>t.infoHash)),Sc=({usedBytes:e,limitBytes:t,pendingBytes:n,candidates:r})=>{if(!Number.isFinite(t)||t<=0||!Number.isFinite(e)||e<0)return[];let i=r.filter(e=>e.bytesOnDisk>0).sort(xc);if(!i.length)return[];let a=[0];for(let e of i)a.push(a[a.length-1]+e.bytesOnDisk);let o=e=>{for(let t=0;t<=i.length;t++)if(e(t))return t;return-1},s=Math.max(0,n),c=t-e,l=o(e=>c+a[e]>=s+gc(t)),u=o(e=>c+a[e]>=s+mc),d=l>=0?l:Math.max(0,u),f=a[i.length],p=i.reduce((e,t)=>Math.max(e,t.bytesOnDisk),0),m=_c(t,p),h=o(e=>f-a[e]<=m);return i.slice(0,Math.max(d,h<0?i.length:h)).map(e=>e.infoHash)};var Cc=8,wc=2e4,Tc=e=>typeof e.values==`function`,Ec=async e=>{let t=0,n=0,r=async(e,i)=>{if(!(i>Cc))for await(let a of e.values()){if(++n>wc)return;if(Tc(a)){await r(a,i+1);continue}let e=await a.getFile().catch(()=>null);e&&(t+=e.size)}};try{return await r(e,0),t}catch{return null}},Dc=(e,t)=>{let n=e.usage;if(t===null||!Number.isFinite(t)||t<0)return n;if(n===void 0)return t;let r=e.usageDetails?.fileSystem;if(typeof r==`number`){let e=Math.max(0,n-r);return Math.max(n,t+e)}return Math.max(n,t)},Oc,kc,Ac=(e,t,n)=>{if(e!==void 0)return n!==kc&&(Oc=void 0),kc=n,Oc=Oc===void 0?e:Math.min(Oc,e),Math.max(Oc,t??0)},jc=async e=>e.persisted?e.persisted().then(e=>e===!0).catch(()=>kc):void 0,Mc={estimate:async()=>{let e=globalThis.navigator?.storage;if(!e?.estimate)return{};let t=await e.estimate(),[n,r]=await Promise.all([e.getDirectory?e.getDirectory().then(e=>Ec(e)).catch(()=>null):null,jc(e)]),i=Dc(t,n);return{...t,usage:i,quota:Ac(t.quota,i,r)}},persist:async()=>{let e=globalThis.navigator?.storage;if(!e?.persist)return!1;let t=await e.persist().catch(()=>!1);return await jc(e)??null??t},persisted:()=>globalThis.navigator?.storage?.persisted?.()??Promise.resolve(!1),getDirectory:()=>{let e=globalThis.navigator?.storage;return e?.getDirectory?e.getDirectory():Promise.reject(/* @__PURE__ */ Error(`this browser has no origin private file system`))}};const Nc=/^(?:[0-9a-f]{40}|[0-9a-f]{64}|[a-z2-7]{32})$/i,Pc=({entries:e,listedHashes:t,claimedNames:n,attributable:r})=>e.filter(({name:e,kind:i})=>n.has(e)?!1:i===`directory`&&Nc.test(e)?!t.has(e.toLowerCase()):r).map(({name:e})=>e),Fc=async e=>{let t=[];for await(let n of e.values())t.push({name:n.name,kind:n.kind});return t},Ic=async(e,t)=>{let n=e;for(let e of t.split(`/`).filter(Boolean))n=n?await n.getDirectoryHandle(e).catch(()=>null):null;return n},Lc=async(e,t,n)=>{let r=await Ic(e,t);if(!r)return[];let i=[];for(let e of Pc({...n,entries:await Fc(r)}))try{await r.removeEntry(e,{recursive:!0}),i.push(e)}catch{}return i},Rc=async e=>{let t=0;for(let{name:n,kind:r}of await Fc(e))r===`file`&&n.startsWith(`.ripple-probe-`)&&await e.removeEntry(n).then(()=>!0,()=>!1)&&t++;return t},zc=/* @__PURE__ */ new Set([`export-start`,`export-chunk`,`import-start`,`add-trackers`,`start-many`,`torrent-detail`]),Bc=e=>e?`/dl/`+e:`/dl`,Vc=e=>`/cache/`+e,Hc=e=>!!e?.startsWith(`/cache/`),Uc=(e,t)=>!!t&&(e===Bc(t)||e===Vc(t)),Wc=(e,t)=>t&&(!e||e.ephemeral===!0),Gc=(e,t)=>{let{private:n,...r}=t,i=n===!0||e?.private===!0;return e?{...r,ephemeral:Wc(e,t.ephemeral===!0),addedAt:Math.min(e.addedAt,t.addedAt),lastUsedAt:Math.max(e.lastUsedAt??0,t.lastUsedAt??t.addedAt),savePath:e.savePath||t.savePath,rootEntry:t.rootEntry??e.rootEntry,name:t.name??e.name,size:t.size??e.size,files:t.files??e.files,format:t.format??e.format,pieceLength:t.pieceLength??e.pieceLength,downloadLimit:t.downloadLimit??e.downloadLimit,uploadLimit:t.uploadLimit??e.uploadLimit,activeSeconds:t.activeSeconds??e.activeSeconds,seedingSeconds:t.seedingSeconds??e.seedingSeconds,downloaded:t.downloaded??e.downloaded,uploaded:t.uploaded??e.uploaded,wasted:t.wasted??e.wasted,saveTo:t.saveTo??e.saveTo,wantedFiles:t.wantedFiles??e.wantedFiles,firstLast:t.firstLast??e.firstLast,created:t.created??e.created,...i?{private:!0}:{}}:i?{...r,private:!0}:r},Kc=e=>({name:typeof e.name==`string`&&e.name?e.name:void 0,size:typeof e.size==`number`&&Number.isFinite(e.size)&&e.size>=0?e.size:void 0,files:Array.isArray(e.files)?e.files.filter(e=>!!e&&typeof e.name==`string`&&typeof e.size==`number`&&Number.isFinite(e.size)).slice(0,100):void 0}),qc=`ripple:torrents`,Jc=`ripple:removed`,Yc=(...e)=>{let t=/* @__PURE__ */ new Map;for(let n of e)if(Array.isArray(n))for(let e of n)typeof e?.infoHash==`string`&&e.infoHash&&typeof e.removedAt==`number`&&Number.isFinite(e.removedAt)&&t.set(e.infoHash,Math.max(t.get(e.infoHash)??e.removedAt,e.removedAt));return[...t].map(([e,t])=>({infoHash:e,removedAt:t}))},Xc=e=>{let t=new Map(e.map(e=>[e.infoHash,e.removedAt]));return e=>{let n=t.get(e.infoHash);return n===void 0||(e.addedAt??0)>n}},Zc=(e,t,n)=>{let r=Xc(n),i=t.filter(e=>!!e&&r(e)),a=new Set(i.map(e=>e.infoHash));return{list:e.filter(e=>e.started!==!1||a.has(e.infoHash)||r(e)),incoming:i}},Qc=e=>`ripple:resume:`+e,$c=e=>`ripple:torrent:`+e,el=e=>`ripple:thumb:`+e,tl=Bc(ms(`magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.torrent.eu.org%3A451&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F`)),W={formatMessage:(e,t)=>t?{message:e.id,values:t}:{message:e.id}},nl=e=>typeof e.getFile==`function`?e.getFile():Promise.resolve(e),rl=e=>`/native/${e}`,il=e=>e===`/native`||!!e?.startsWith(`/native/`),al=e=>`/source/${e}`,ol=e=>e===`/source`||!!e?.startsWith(`/source/`),sl=e=>il(e)||ol(e),cl=async(e,t)=>{let n=t.split(`/`).filter(Boolean),r=n.pop();if(!r)throw Error(`hybrid storage: empty file path`);let i=e;for(let e of n)i=await i.getDirectoryHandle(e);return(await i.getFileHandle(r)).getFile()},ll=(e,t)=>cl(e,t).catch(e=>{if(e?.name===`NotFoundError`)return null;throw e}),ul=e=>e.keys().next(),dl=async(e,t)=>{try{for(let{path:n,size:r,pad:i}of t){if(i||r<=0)continue;let t=await ll(e,n);if(!(t&&t.size>=r))return await ul(e),!0}return!1}catch{return!1}},fl=(e,t,n=()=>null,r=e)=>{let i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set,s=t=>o.has(t)?r:e,c=t=>Hc(t)?r:e,l=e=>{let n=t();if(!n)throw Error(`hybrid storage: no folder granted, cannot ${e}`);return n},u=async(e,t)=>{if(!e.handles)throw Error(`hybrid storage: ${e.savePath} has no source handles registered`);if(e.handles.length!==e.files.length)throw Error(`hybrid storage: ${e.savePath} has ${e.handles.length} handles for ${e.files.length} files`);if(t<0||t>=e.handles.length)throw Error(`hybrid storage: no source handle ${t} in ${e.savePath}`);let n=e.handles[t];return n?nl(n):null};return{usageOf:async e=>sl(e)?0:c(e).usageOf(e),usageOfStorage:async(e,t)=>i.has(e)||a.has(e)?null:s(e).usageOfStorage(e,t),refusedFile:e=>s(e).refusedFile(e),onNewStorage:(e,t,r)=>{if(ol(t)){a.set(e,{savePath:t,files:r,handles:n(t)});return}if(Hc(t)?o.add(e):o.delete(e),!il(t))return s(e).onNewStorage(e,t,r);i.set(e,{savePath:t,files:r})},onRemoveStorage:e=>{if(!a.delete(e)&&!i.delete(e))return s(e).onRemoveStorage(e)},read:(e,t,n,r)=>{let o=a.get(e);if(o)return(async()=>{let e=await u(o,t);if(!e)return new Uint8Array(r);let i=await e.slice(n,n+r).arrayBuffer();if(i.byteLength<r)throw Error(`hybrid storage: source file ${t} of ${o.savePath} ended early, wanted ${r} at ${n}, got ${i.byteLength}`);return new Uint8Array(i)})();let c=i.get(e);if(!c)return s(e).read(e,t,n,r);let d=c.files[t];if(!d)throw Error(`hybrid storage: no file ${t} in ${c.savePath}`);return(async()=>{let e=await(await cl(l(`read`),d.path)).slice(n,n+r).arrayBuffer();if(e.byteLength<r)throw Error(`hybrid storage: ${d.path} ended early, wanted ${r} at ${n}, got ${e.byteLength}`);return new Uint8Array(e)})()},write:(e,t,n,r)=>{let o=a.get(e);if(o)throw Error(`hybrid storage: ${o.savePath} is somebody's own files, refusing a write of ${r.length} at ${n} in file ${t}`);let c=i.get(e);if(!c)return s(e).write(e,t,n,r);throw Error(`hybrid storage: ${c.savePath} is read only, refusing a write of ${r.length} at ${n} in file ${t}`)},check:async e=>{if(a.get(e))return 2;let t=i.get(e);if(!t)return s(e).check(e);try{let e=l(`check`);for(let n of t.files){let t=await ll(e,n.path);if(t&&t.size>0)return 2}return await ul(e),0}catch{return 2}},deleteFiles:async(e,t)=>{if(!a.has(e)&&!i.get(e))return s(e).deleteFiles(e,t)},release:async e=>{!i.has(e)&&!a.has(e)&&await s(e).release(e)},stop:async e=>{!i.has(e)&&!a.has(e)&&await s(e).stop(e)}}},pl=(e,t,n)=>[Math.max(0,Math.floor(e.offset/t)),Math.min(n-1,Math.floor((e.offset+Math.max(0,e.size-1))/t))],ml=({files:e,pieceLength:t,numPieces:n,wanted:r,firstLast:i,windowBytes:a=4194304})=>{let o=r===void 0,s=new Set(r??[]),c=e=>o||s.has(e),l=new Uint8Array(n).fill(o?U.normal:U.skip);if(!o)for(let[r,i]of e.entries()){if(!c(r)||i.size<=0)continue;let[e,a]=pl(i,t,n);for(let t=e;t<=a;t++)l[t]=U.normal}if(i){let r=Math.max(1,Math.ceil(a/t));for(let[i,a]of e.entries()){if(!c(i)||a.size<=0)continue;let[e,o]=pl(a,t,n);for(let t=0;t<r;t++){let n=e+t,r=o-t;n<=o&&(l[n]=U.top),r>=e&&(l[r]=U.top)}}}return l},hl=({wanted:e,firstLast:t})=>e===void 0&&!t,gl=new TextEncoder;gl.encode(`i`),gl.encode(`e`),gl.encode(`l`),gl.encode(`d`),gl.encode(`:`);const _l=(e,t)=>{if(t>=e.length)throw Error(`truncated`);let n=e[t];if(n===105){let n=e.indexOf(101,t+1);if(n<0)throw Error(`unterminated integer`);return[Number(new TextDecoder().decode(e.subarray(t+1,n))),n+1]}if(n===108){let n=[],r=t+1;for(;r<e.length&&e[r]!==101;){let[t,i]=_l(e,r);n.push(t),r=i}if(r>=e.length)throw Error(`unterminated list`);return[n,r+1]}if(n===100){let n=/* @__PURE__ */ new Map,r=t+1;for(;r<e.length&&e[r]!==101;){let[t,i]=_l(e,r);if(!(t instanceof Uint8Array))throw Error(`dict key is not a string`);let[a,o]=_l(e,i);n.set(new TextDecoder().decode(t),a),r=o}if(r>=e.length)throw Error(`unterminated dict`);return[n,r+1]}let r=t,i=0,a=0;for(;r<e.length&&e[r]>=48&&e[r]<=57;)if(i=i*10+(e[r]-48),r+=1,a+=1,a>12)throw Error(`absurd string length`);if(a===0||e[r]!==58)throw Error(`not a bencode value`);let o=r+1,s=o+i;if(s>e.length)throw Error(`string runs past the end`);return[e.subarray(o,s),s]},vl=e=>{let t=e.get(`private`);return typeof t==`number`&&t!==0},yl=e=>{try{let[t]=_l(e,0),n=t instanceof Map?t.get(`info`):void 0;return n instanceof Map&&vl(n)}catch{return!1}},bl=e=>{if(e[0]!==100)return null;let t=1;for(;t<e.length&&e[t]!==101;){let[n,r]=_l(e,t),[,i]=_l(e,r);if(n instanceof Uint8Array&&new TextDecoder().decode(n)===`info`)return[r,i];t=i}return null},xl=new TextEncoder,Sl=e=>{let t=xl.encode(e),n=xl.encode(`${t.length}:`),r=new Uint8Array(n.length+t.length);return r.set(n),r.set(t,n.length),r},Cl=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},wl=(e,{trackers:t=[],webSeeds:n=[]}={})=>{let r=[xl.encode(`d`)];if(t.length){r.push(Sl(`announce`),Sl(t[0])),r.push(Sl(`announce-list`),xl.encode(`l`));for(let e of t)r.push(xl.encode(`l`),Sl(e),xl.encode(`e`));r.push(xl.encode(`e`))}if(r.push(Sl(`info`),e),n.length){r.push(Sl(`url-list`),xl.encode(`l`));for(let e of n)r.push(Sl(e));r.push(xl.encode(`e`))}return r.push(xl.encode(`e`)),Cl(r)},Tl=e=>({trackers:_s(e,`tr`),webSeeds:_s(e,`ws`)}),El=e=>{let t=bl(e);if(!t)return null;let[n,r]=t;return new Uint8Array(e.slice(n,r))},Dl=e=>{try{let t=El(e);if(!t)return!1;let[n]=_l(t,0);return n instanceof Map&&vl(n)}catch{return!1}},Ol=e=>ol(e)?`source`:il(e)?`folder`:`browser`,kl=(e,t)=>{if(e===`source`){if(!t)throw Error(`a source-backed torrent needs its infohash to name its save path`);return al(t)}return e===`folder`?t?rl(t):`/dl`:Bc(t)},Al=`ripple:rate-limits`,jl=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,Ml=e=>{let t=e??{};return{down:jl(t.down)?t.down:0,up:jl(t.up)?t.up:0}},Nl=`ripple:seeding-policy`,Pl={ratio:null,minutes:null},Fl=e=>typeof e==`number`&&Number.isFinite(e)&&e>=.01&&e<=1e3,Il=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=1&&e<=525600,Ll=e=>e.ratio!==null||e.minutes!==null,Rl=e=>{if(!Fl(e))return null;let t=Math.round(e*1e4)/1e4;return Fl(t)?t:null},zl=e=>{if(!e||typeof e!=`object`||Array.isArray(e))return Pl;let t=e;if(`mode`in t)return t.mode===`ratio`?{ratio:Rl(t.ratio)??1,minutes:null}:t.mode===`duration`?{ratio:null,minutes:Il(t.minutes)?t.minutes:60}:Pl;let n=Rl(t.ratio),r=Il(t.minutes)?t.minutes:null;return n===null&&r===null?Pl:{ratio:n,minutes:r}},Bl=(e,t)=>e.ratio===t.ratio&&e.minutes===t.minutes,Vl=(e,t)=>{if(e.ratio!==null){let n=t.downloaded>0&&(t.size<=0||t.downloaded>=t.size*.01)?t.downloaded:t.size;if(n>0&&t.uploaded/n>=e.ratio)return!0}return e.minutes!==null&&t.seedingSeconds>=e.minutes*60},Hl=[`tracker.openwebtorrent.com`,`tracker.webtorrent.dev`],Ul=Hl.map(e=>`wss://${e}`);[...Hl];var Wl=/* @__PURE__ */ t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AddressError=void 0,e.AddressError=class extends Error{constructor(e,t){super(e),this.name=`AddressError`,this.parseMessage=t}}})),Gl=/* @__PURE__ */ t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isInSubnet=n,e.isCorrect=r,e.prefixLengthFromMask=i,e.numberToPaddedHex=a,e.stringToPaddedHex=o,e.testBit=s;let t=Wl();function n(e){return this.subnetMask<e.subnetMask?!1:this.mask(e.subnetMask)===e.mask()}function r(e){return function(){return this.addressMinusSuffix===this.correctForm()?this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask):!1}}function i(e,n){let r=e.toString(2).padStart(n,`0`);if(r.length>n)throw new t.AddressError(`Invalid subnet mask.`);let i=r.indexOf(`0`);if(i===-1)return n;if(r.slice(i).includes(`1`))throw new t.AddressError(`Invalid subnet mask.`);return i}function a(e){return e.toString(16).padStart(2,`0`)}function o(e){return a(parseInt(e,10))}function s(e,t){let{length:n}=e;if(t>n)return!1;let r=n-t;return e.substring(r,r+1)===`1`}})),Kl=/* @__PURE__ */ t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RE_SUBNET_STRING=e.RE_ADDRESS=e.GROUPS=e.BITS=void 0,e.BITS=32,e.GROUPS=4,e.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g,e.RE_SUBNET_STRING=/\/\d{1,2}$/})),ql=/* @__PURE__ */ t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.Address4=void 0;let i=r(Gl()),a=r(Kl()),o=Wl(),s=i.isCorrect(a.BITS);var c=class e{constructor(e){this.groups=a.GROUPS,this.parsedAddress=[],this.parsedSubnet=``,this.subnet=`/32`,this.subnetMask=32,this.v4=!0,this.isCorrect=s,this.isInSubnet=i.isInSubnet,this.address=e;let t=a.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace(`/`,``),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>a.BITS)throw new o.AddressError(`Invalid subnet mask.`);e=e.replace(a.RE_SUBNET_STRING,``)}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(t){try{return new e(t),!0}catch{return!1}}parse(e){let t=e.split(`.`);if(!e.match(a.RE_ADDRESS))throw new o.AddressError(`Invalid IPv4 address.`);return t}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(`.`)}static fromAddressAndMask(t,n){let r=i.prefixLengthFromMask(new e(n).bigInt(),a.BITS);return new e(`${t}/${r}`)}static fromAddressAndWildcardMask(t,n){let r=new e(n).bigInt()^(BigInt(1)<<BigInt(a.BITS))-BigInt(1),o=i.prefixLengthFromMask(r,a.BITS);return new e(`${t}/${o}`)}static fromWildcard(t){let n=t.split(`.`);if(n.length!==a.GROUPS)throw new o.AddressError(`Wildcard pattern must have 4 octets`);let r=-1;for(let e=0;e<n.length;e++)if(n[e]===`*`)r===-1&&(r=e);else if(r!==-1)throw new o.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");let i=r===-1?0:n.length-r,s=n.map(e=>e===`*`?`0`:e),c=a.BITS-i*8;return new e(`${s.join(`.`)}/${c}`)}static fromHex(t){let n=t.replace(/:/g,``);if(!/^[0-9a-fA-F]{8}$/.test(n))throw new o.AddressError(`IPv4 hex must be exactly 8 hex digits`);let r=[];for(let e=0;e<8;e+=2)r.push(parseInt(n.slice(e,e+2),16));return new e(r.join(`.`))}static fromInteger(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new o.AddressError(`IPv4 integer must be in the range 0 to 2**32 - 1`);return e.fromHex(t.toString(16).padStart(8,`0`))}static fromArpa(t){let n=t.replace(/(\.in-addr\.arpa)?\.$/,``).split(`.`).reverse().join(`.`);return new e(n)}toHex(){return this.parsedAddress.map(e=>i.stringToPaddedHex(e)).join(`:`)}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],t=0;for(;t<a.GROUPS;t+=2)e.push(`${i.stringToPaddedHex(this.parsedAddress[t])}${i.stringToPaddedHex(this.parsedAddress[t+1])}`);return e.join(`:`)}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>i.stringToPaddedHex(e)).join(``)}`)}_startAddress(){return BigInt(`0b${this.mask()+`0`.repeat(a.BITS-this.subnetMask)}`)}startAddress(){return e.fromBigInt(this._startAddress())}startAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._startAddress()+t)}_endAddress(){return BigInt(`0b${this.mask()+`1`.repeat(a.BITS-this.subnetMask)}`)}endAddress(){return e.fromBigInt(this._endAddress())}endAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._endAddress()-t)}subnetMaskAddress(){return e.fromBigInt(BigInt(`0b${`1`.repeat(this.subnetMask)}${`0`.repeat(a.BITS-this.subnetMask)}`))}wildcardMask(){return e.fromBigInt(BigInt(`0b${`0`.repeat(this.subnetMask)}${`1`.repeat(a.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(t){if(t<0n||t>4294967295n)throw new o.AddressError(`IPv4 BigInt must be in the range 0 to 2**32 - 1`);return e.fromHex(t.toString(16).padStart(8,`0`))}static fromByteArray(e){if(e.length!==4)throw new o.AddressError(`IPv4 addresses require exactly 4 bytes`);for(let t=0;t<e.length;t++)if(!Number.isInteger(e[t])||e[t]<0||e[t]>255)throw new o.AddressError(`All bytes must be integers between 0 and 255`);return this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(t){if(t.length!==4)throw new o.AddressError(`IPv4 addresses require exactly 4 bytes`);let n=t.join(`.`);return new e(n)}mask(e){return e===void 0&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||={};let t=this.correctForm().split(`.`).reverse().join(`.`);return e.omitSuffix?t:`${t}.in-addr.arpa.`}isMulticast(){return this.isInSubnet(l)}isPrivate(){return u.some(e=>this.isInSubnet(e))}isLoopback(){return this.isInSubnet(d)}isLinkLocal(){return this.isInSubnet(f)}isUnspecified(){return this.isInSubnet(p)}isBroadcast(){return this.isInSubnet(m)}isCGNAT(){return this.isInSubnet(h)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(a.BITS,`0`)),this._binaryZeroPad}groupForV6(){let e=this.parsedAddress;return this.address.replace(a.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(`.`)}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(`.`)}</span>`)}};e.Address4=c;let l=new c(`224.0.0.0/4`),u=[new c(`10.0.0.0/8`),new c(`172.16.0.0/12`),new c(`192.168.0.0/16`)],d=new c(`127.0.0.0/8`),f=new c(`169.254.0.0/16`),p=new c(`0.0.0.0/32`),m=new c(`255.255.255.255/32`),h=new c(`100.64.0.0/10`)})),Jl=/* @__PURE__ */ t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RE_URL_WITH_PORT=e.RE_URL=e.RE_ZONE_STRING=e.RE_SUBNET_STRING=e.RE_BAD_ADDRESS=e.RE_BAD_CHARACTERS=e.TYPES=e.SCOPES=e.GROUPS=e.BITS=void 0,e.BITS=128,e.GROUPS=8,e.SCOPES={0:`Reserved`,1:`Interface local`,2:`Link local`,4:`Admin local`,5:`Site local`,8:`Organization local`,14:`Global`,15:`Reserved`},e.TYPES={"ff01::1/128":`Multicast (All nodes on this interface)`,"ff01::2/128":`Multicast (All routers on this interface)`,"ff02::1/128":`Multicast (All nodes on this link)`,"ff02::2/128":`Multicast (All routers on this link)`,"ff05::2/128":`Multicast (All routers in this site)`,"ff02::5/128":`Multicast (OSPFv3 AllSPF routers)`,"ff02::6/128":`Multicast (OSPFv3 AllDR routers)`,"ff02::9/128":`Multicast (RIP routers)`,"ff02::a/128":`Multicast (EIGRP routers)`,"ff02::d/128":`Multicast (PIM routers)`,"ff02::16/128":`Multicast (MLDv2 reports)`,"ff01::fb/128":`Multicast (mDNSv6)`,"ff02::fb/128":`Multicast (mDNSv6)`,"ff05::fb/128":`Multicast (mDNSv6)`,"ff02::1:2/128":`Multicast (All DHCP servers and relay agents on this link)`,"ff05::1:2/128":`Multicast (All DHCP servers and relay agents in this site)`,"ff02::1:3/128":`Multicast (All DHCP servers on this link)`,"ff05::1:3/128":`Multicast (All DHCP servers in this site)`,"::/128":`Unspecified`,"::1/128":`Loopback`,"ff00::/8":`Multicast`,"fe80::/10":`Link-local unicast`,"fc00::/7":`Unique local`,"2002::/16":`6to4`,"2001:db8::/32":`Documentation`,"64:ff9b::/96":`NAT64 (well-known)`,"64:ff9b:1::/48":`NAT64 (local-use)`},e.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,e.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,e.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,e.RE_ZONE_STRING=/%.*$/,e.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/,e.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/})),Yl=/* @__PURE__ */ t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.escapeHtml=t,e.spanAllZeroes=n,e.spanAll=r,e.spanLeadingZeroes=a,e.simpleGroup=o;function t(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function n(e){return t(e).replace(/(0+)/g,`<span class="zero">$1</span>`)}function r(e,r=0){return e.split(``).map((e,i)=>`<span class="digit value-${t(e)} position-${i+r}">${n(e)}</span>`).join(``)}function i(e){return t(e).replace(/^(0+)/,`<span class="zero">$1</span>`)}function a(e){return e.split(`:`).map(e=>i(e)).join(`:`)}function o(e,t=0){return e.split(`:`).map((e,n)=>/group-v4/.test(e)?e:`<span class="hover-group group-${n+t}">${i(e)}</span>`)}})),Xl=/* @__PURE__ */ t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.ADDRESS_BOUNDARY=void 0,e.groupPossibilities=a,e.padGroup=o,e.simpleRegularExpression=s,e.possibleElisions=c;let i=r(Jl());function a(e){return`(${e.join(`|`)})`}function o(e){return e.length<4?`0{0,${4-e.length}}${e}`:e}e.ADDRESS_BOUNDARY=`[^A-Fa-f0-9:]`;function s(e){let t=[];e.forEach((e,n)=>{parseInt(e,16)===0&&t.push(n)});let n=t.map(t=>e.map((e,n)=>{if(n===t){let t=n===0||n===i.GROUPS-1?`:`:``;return a([o(e),t])}return o(e)}).join(`:`));return n.push(e.map(o).join(`:`)),a(n)}function c(e,t,n){let r=t?``:`:`,i=n?``:`:`,o=[];!t&&!n&&o.push(`::`),t&&n&&o.push(``),(n&&!t||!n&&t)&&o.push(`:`),o.push(`${r}(:0{1,4}){1,${e-1}}`),o.push(`(0{1,4}:){1,${e-1}}${i}`),o.push(`(0{1,4}:){${e-1}}0{1,4}`);for(let t=1;t<e-1;t++)for(let n=1;n<e-t;n++)o.push(`(0{1,4}:){${n}}:(0{1,4}:){${e-n-t-1}}0{1,4}`);return a(o)}})),Zl=/* @__PURE__ */ t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.Address6=void 0;let i=r(Gl()),a=r(Kl()),o=r(Jl()),s=r(Yl()),c=ql(),l=Xl(),u=Wl(),d=Gl(),f=i.isCorrect(o.BITS);function p(e){if(!e)throw Error(`Assertion failed.`)}function m(e){let t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,`$1,$2`);return e}function h(e){return e=e.replace(/^(0{1,})([1-9]+)$/,`<span class="parse-error">$1</span>$2`),e=e.replace(/^(0{1,})(0)$/,`<span class="parse-error">$1</span>$2`),e}function g(e,t){let n=[],r=[],i=0;for(;i<e.length;i++)i<t[0]?n.push(e[i]):i>t[1]&&r.push(e[i]);return n.concat([`compact`]).concat(r)}function _(e){return parseInt(e,16).toString(16).padStart(4,`0`)}function v(e){return e&255}var y=class e{constructor(e,t){this.addressMinusSuffix=``,this.parsedSubnet=``,this.subnet=`/128`,this.subnetMask=128,this.v4=!1,this.zone=``,this.isInSubnet=i.isInSubnet,this.isCorrect=f,this.groups=t===void 0?o.GROUPS:t,this.address=e;let n=o.RE_SUBNET_STRING.exec(e);if(n){if(this.parsedSubnet=n[0].replace(`/`,``),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>o.BITS)throw new u.AddressError(`Invalid subnet mask.`);e=e.replace(o.RE_SUBNET_STRING,``)}else if(/\//.test(e))throw new u.AddressError(`Invalid subnet mask.`);let r=o.RE_ZONE_STRING.exec(e);r&&(this.zone=r[0],e=e.replace(o.RE_ZONE_STRING,``)),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(t){try{return new e(t),!0}catch{return!1}}static fromBigInt(t){if(t<0n||t>(1n<<BigInt(o.BITS))-1n)throw new u.AddressError(`IPv6 BigInt must be in the range 0 to 2**128 - 1`);let n=t.toString(16).padStart(32,`0`),r=[];for(let e=0;e<o.GROUPS;e++)r.push(n.slice(e*4,(e+1)*4));return new e(r.join(`:`))}static fromURL(t){let n,r=null,i;if(t.indexOf(`[`)!==-1&&t.indexOf(`]:`)!==-1){if(i=o.RE_URL_WITH_PORT.exec(t),i===null)return{error:`failed to parse address with port`,address:null,port:null};n=i[1],r=i[2]}else if(t.indexOf(`/`)!==-1){if(t=t.replace(/^[a-z0-9]+:\/\//,``),i=o.RE_URL.exec(t),i===null)return{error:`failed to parse address from URL`,address:null,port:null};n=i[1]}else n=t;return r?(r=parseInt(r,10),(r<0||r>65536)&&(r=null)):r=null,{address:new e(n),port:r}}static fromAddressAndMask(t,n){let r=i.prefixLengthFromMask(new e(n).bigInt(),o.BITS);return new e(`${t}/${r}`)}static fromAddressAndWildcardMask(t,n){let r=new e(n).bigInt()^(BigInt(1)<<BigInt(o.BITS))-BigInt(1),a=i.prefixLengthFromMask(r,o.BITS);return new e(`${t}/${a}`)}static fromWildcard(t){if(t.includes(`%`)||t.includes(`/`))throw new u.AddressError(`Wildcard pattern must not include a zone or CIDR suffix`);let n=t.split(`::`);if(n.length>2)throw new u.AddressError(`Wildcard pattern cannot contain more than one '::'`);let r;if(n.length===2){let e=n[0]===``?[]:n[0].split(`:`),t=n[1]===``?[]:n[1].split(`:`),i=o.GROUPS-e.length-t.length;if(i<1)throw new u.AddressError(`Wildcard pattern with '::' has too many groups`);r=[...e,...Array(i).fill(`0`),...t]}else r=t.split(`:`);if(r.length!==o.GROUPS)throw new u.AddressError(`Wildcard pattern must have 8 groups`);let i=-1;for(let e=0;e<r.length;e++)if(r[e]===`*`)i===-1&&(i=e);else if(i!==-1)throw new u.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");let a=i===-1?0:r.length-i,s=r.map(e=>e===`*`?`0`:e),c=o.BITS-a*16;return new e(`${s.join(`:`)}/${c}`)}static fromAddress4(t){let n=new c.Address4(t),r=o.BITS-(a.BITS-n.subnetMask);return new e(`::ffff:${n.correctForm()}/${r}`)}static fromArpa(t){let n=t.replace(/(\.ip6\.arpa)?\.$/,``);if(n.length!==63)throw new u.AddressError(`Invalid 'ip6.arpa' form.`);let r=n.split(`.`).reverse();for(let e=7;e>0;e--){let t=e*4;r.splice(t,0,`:`)}return n=r.join(``),new e(n)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,`-`)}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){let t=o.BITS-this.subnetMask-Math.abs(e-o.BITS);return t<0?`0`:m((BigInt(`2`)**BigInt(t)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+`0`.repeat(o.BITS-this.subnetMask)}`)}startAddress(){return e.fromBigInt(this._startAddress())}startAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._startAddress()+t)}_endAddress(){return BigInt(`0b${this.mask()+`1`.repeat(o.BITS-this.subnetMask)}`)}endAddress(){return e.fromBigInt(this._endAddress())}endAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._endAddress()-t)}subnetMaskAddress(){return e.fromBigInt(BigInt(`0b${`1`.repeat(this.subnetMask)}${`0`.repeat(o.BITS-this.subnetMask)}`))}wildcardMask(){return e.fromBigInt(BigInt(`0b${`0`.repeat(this.subnetMask)}${`1`.repeat(o.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let e=this.getType();return e===`Multicast`||e.startsWith(`Multicast `)?o.SCOPES[parseInt(this.getBits(12,16).toString(10),10)]||`Unknown`:e===`Link-local unicast`||e===`Loopback`?`Link local`:e===`Unspecified`?`Unknown`:`Global`}getType(){for(let e=0;e<b.length;e++){let t=b[e];if(this.isInSubnet(t[0]))return t[1]}return`Global unicast`}getBits(e,t){return BigInt(`0b${this.getBitsBase2(e,t)}`)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){let n=t-e;if(n%4!=0)throw Error(`Length of bits to retrieve must be divisible by four`);return this.getBits(e,t).toString(16).padStart(n/4,`0`)}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,o.BITS)}reverseForm(e){e||={};let t=Math.floor(this.subnetMask/4),n=this.canonicalForm().replace(/:/g,``).split(``).slice(0,t).reverse().join(`.`);return t>0?e.omitSuffix?n:`${n}.ip6.arpa.`:e.omitSuffix?``:`ip6.arpa.`}correctForm(){let e,t=[],n=0,r=[];for(e=0;e<this.parsedAddress.length;e++){let t=parseInt(this.parsedAddress[e],16);t===0&&n++,t!==0&&n>0&&(n>1&&r.push([e-n,e-1]),n=0)}n>1&&r.push([this.parsedAddress.length-n,this.parsedAddress.length-1]);let i=r.map(e=>e[1]-e[0]+1);if(r.length>0){let e=i.indexOf(Math.max(...i));t=g(this.parsedAddress,r[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)t[e]!==`compact`&&(t[e]=parseInt(t[e],16).toString(16));let a=t.join(`:`);return a=a.replace(/^compact$/,`::`),a=a.replace(/(^compact)|(compact$)/,`:`),a=a.replace(/compact/,``),a}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(o.BITS,`0`)),this._binaryZeroPad}parse4in6(e){if(e.indexOf(`.`)===-1)return e;let t=e.split(`:`),n=t.slice(-1)[0].match(a.RE_ADDRESS);if(n){this.parsedAddress4=n[0],this.address4=new c.Address4(this.parsedAddress4);for(let e=0;e<this.address4.groups;e++)if(/^0[0-9]+/.test(this.address4.parsedAddress[e])){let e=this.address4.parsedAddress.map(h).join(`.`),n=t.slice(0,-1).map(s.escapeHtml).join(`:`),r=t.length>1?`:`:``;throw new u.AddressError(`IPv4 addresses can't have leading zeroes.`,`${n}${r}${e}`)}this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(`:`)}return e}parse(e){e=this.parse4in6(e);let t=e.match(o.RE_BAD_CHARACTERS);if(t)throw new u.AddressError(`Bad character${t.length>1?`s`:``} detected in address: ${t.join(``)}`,e.replace(o.RE_BAD_CHARACTERS,`<span class="parse-error">$1</span>`));let n=e.match(o.RE_BAD_ADDRESS);if(n)throw new u.AddressError(`Address failed regex: ${n.join(``)}`,e.replace(o.RE_BAD_ADDRESS,`<span class="parse-error">$1</span>`));let r=[],i=e.split(`::`);if(i.length===2){let e=i[0].split(`:`),t=i[1].split(`:`);e.length===1&&e[0]===``&&(e=[]),t.length===1&&t[0]===``&&(t=[]);let n=this.groups-(e.length+t.length);if(!n)throw new u.AddressError(`Error parsing groups`);this.elidedGroups=n,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,r=r.concat(e);for(let e=0;e<n;e++)r.push(`0`);r=r.concat(t)}else if(i.length===1)r=e.split(`:`),this.elidedGroups=0;else throw new u.AddressError(`Too many :: groups found`);if(r=r.map(e=>parseInt(e,16).toString(16)),r.length!==this.groups)throw new u.AddressError(`Incorrect number of groups found`);return r}canonicalForm(){return this.parsedAddress.map(_).join(`:`)}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,`0`)).join(`:`)}bigInt(){return BigInt(`0x${this.parsedAddress.map(_).join(``)}`)}to4(){let e=this.binaryZeroPad().split(``);return c.Address4.fromHex(BigInt(`0b${e.slice(96,128).join(``)}`).toString(16).padStart(8,`0`))}to4in6(){let t=this.to4(),n=new e(this.parsedAddress.slice(0,6).join(`:`),6).correctForm(),r=``;return/:$/.test(n)||(r=`:`),n+r+t.address}inspectTeredo(){let e=this.getBitsBase16(0,32),t=(this.getBits(80,96)^BigInt(`0xffff`)).toString(),n=c.Address4.fromHex(this.getBitsBase16(32,64)),r=this.getBits(96,128),i=c.Address4.fromHex((r^BigInt(`0xffffffff`)).toString(16).padStart(8,`0`)),a=this.getBitsBase2(64,80),o=(0,d.testBit)(a,15),s=(0,d.testBit)(a,14),l=(0,d.testBit)(a,8),u=(0,d.testBit)(a,9),f=BigInt(`0b${a.slice(2,6)+a.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:n.address,client4:i.address,flags:a,coneNat:o,microsoft:{reserved:s,universalLocal:u,groupIndividual:l,nonce:f},udpPort:t}}inspect6to4(){let e=this.getBitsBase16(0,16),t=c.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:t.address}}to6to4(){if(!this.is4())return null;let t=[`2002`,this.getBitsBase16(96,112),this.getBitsBase16(112,128),``,`/16`].join(`:`);return new e(t)}static fromAddress4Nat64(t,n=`64:ff9b::/96`){let r=new c.Address4(t),i=new e(n),a=i.subnetMask;if(a!==32&&a!==40&&a!==48&&a!==56&&a!==64&&a!==96)throw new u.AddressError(`NAT64 prefix length must be 32, 40, 48, 56, 64, or 96`);let o=i.binaryZeroPad(),s=r.binaryZeroPad(),l;if(a===96)l=o.slice(0,96)+s;else{let e=64-a;l=o.slice(0,a)+s.slice(0,e)+`00000000`+s.slice(e)+`0`.repeat(56-(32-e))}let d=BigInt(`0b${l}`).toString(16).padStart(32,`0`),f=[];for(let e=0;e<8;e++)f.push(d.slice(e*4,(e+1)*4));return new e(f.join(`:`))}toAddress4Nat64(t=`64:ff9b::/96`){let n=new e(t),r=n.subnetMask;if(r!==32&&r!==40&&r!==48&&r!==56&&r!==64&&r!==96)throw new u.AddressError(`NAT64 prefix length must be 32, 40, 48, 56, 64, or 96`);if(!this.isInSubnet(n))return null;let i=this.binaryZeroPad(),a;if(r===96)a=i.slice(96,128);else{let e=64-r;a=i.slice(r,r+e)+i.slice(72,72+(32-e))}let o=[];for(let e=0;e<4;e++)o.push(parseInt(a.slice(e*8,(e+1)*8),2).toString());return new c.Address4(o.join(`.`))}toByteArray(){let e=this.bigInt().toString(16),t=`${`0`.repeat(e.length%2)}${e}`,n=[];for(let e=0,r=t.length;e<r;e+=2)n.push(parseInt(t.substring(e,e+2),16));return n}toUnsignedByteArray(){return this.toByteArray().map(v)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(v))}static fromUnsignedByteArray(t){let n=BigInt(`256`),r=BigInt(`0`),i=BigInt(`1`);for(let e=t.length-1;e>=0;e--)r+=i*BigInt(t[e].toString(10)),i*=n;return e.fromBigInt(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){return this.getBitsBase2(0,64)===`1111111010000000000000000000000000000000000000000000000000000000`}isMulticast(){let e=this.getType();return e===`Multicast`||e.startsWith(`Multicast `)}is4(){return this.v4}isMapped4(){return this.isInSubnet(T)}isTeredo(){return this.isInSubnet(x)}is6to4(){return this.isInSubnet(S)}isLoopback(){return this.getType()===`Loopback`}isULA(){return this.isInSubnet(C)}isUnspecified(){return this.getType()===`Unspecified`}isDocumentation(){return this.isInSubnet(w)}href(e){return e=e===void 0?``:`:${e}`,`http://[${this.correctForm()}]${e}/`}link(e){e||={},e.className===void 0&&(e.className=``),e.prefix===void 0&&(e.prefix=`/#address=`),e.v4===void 0&&(e.v4=!1);let t=this.correctForm;e.v4&&(t=this.to4in6);let n=t.call(this),r=s.escapeHtml(`${e.prefix}${n}`),i=s.escapeHtml(n);return e.className?`<a href="${r}" class="${s.escapeHtml(e.className)}">${i}</a>`:`<a href="${r}">${i}</a>`}group(){if(this.elidedGroups===0)return s.simpleGroup(this.addressMinusSuffix).join(`:`);p(typeof this.elidedGroups==`number`),p(typeof this.elisionBegin==`number`);let e=[],[t,n]=this.addressMinusSuffix.split(`::`);t.length?e.push(...s.simpleGroup(t)):e.push(``);let r=[`hover-group`];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)r.push(`group-${e}`);return e.push(`<span class="${r.join(` `)}"></span>`),n.length?e.push(...s.simpleGroup(n,this.elisionEnd)):e.push(``),this.is4()&&(p(this.address4 instanceof c.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(`:`)}regularExpressionString(t=!1){let n=[],r=new e(this.correctForm());if(r.elidedGroups===0)n.push((0,l.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===o.GROUPS)n.push((0,l.possibleElisions)(o.GROUPS));else{let e=r.address.split(`::`);e[0].length&&n.push((0,l.simpleRegularExpression)(e[0].split(`:`))),p(typeof r.elidedGroups==`number`),n.push((0,l.possibleElisions)(r.elidedGroups,e[0].length!==0,e[1].length!==0)),e[1].length&&n.push((0,l.simpleRegularExpression)(e[1].split(`:`))),n=[n.join(`:`)]}return t||(n=[`(?=^|`,l.ADDRESS_BOUNDARY,`|[^\\w\\:])(`,...n,`)(?=[^\\w\\:]|`,l.ADDRESS_BOUNDARY,`|$)`]),n.join(``)}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),`i`)}};e.Address6=y;let b=Object.keys(o.TYPES).map(e=>[new y(e),o.TYPES[e]]),x=new y(`2001::/32`),S=new y(`2002::/16`),C=new y(`fc00::/7`),w=new y(`2001:db8::/32`),T=new y(`::ffff:0:0/96`)})),Ql=(/* @__PURE__ */ t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;var i=ql();Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return i.Address4}});var a=Zl();Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return a.Address6}});var o=Wl();Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}}),e.v6={helpers:r(Yl())}})))(),$l=new TextEncoder,eu=e=>Ql.Address4.isValid(e),tu=e=>Ql.Address6.isValid(e),nu=e=>eu(e)?4:tu(e)?6:0,ru=(...e)=>{if(typeof e[0]==`string`)throw Error(`FKN WebVPN does not support IPC connections`);let t=typeof e.at(-1)==`function`?e.at(-1):void 0;return e[0]&&typeof e[0]==`object`?{...e[0],callback:t}:{port:typeof e[0]==`function`?0:e[0]??0,host:typeof e[1]==`string`?e[1]:void 0,callback:t}},iu=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=typeof e[0]==`function`?0:e[0]??0,r=typeof e[1]==`string`?e[1]:void 0;return typeof e[0]==`object`?{...e[0],address:e[0].address??r,port:e[0].port??0,callback:t}:{address:r,port:n,callback:t}},au=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=e[0];if(typeof e[2]==`number`)return{message:n,hasRange:!0,offset:e[1],length:e[2],port:typeof e[3]==`number`?e[3]:0,address:typeof e[4]==`string`?e[4]:void 0,callback:t};{let r=typeof e[1]==`number`?e[1]:0,i=typeof e[2]==`string`?e[2]:void 0;return{message:n,hasRange:!1,offset:0,length:n.length,port:r,address:i,callback:t}}},ou=/* @__PURE__ */ new Map,su=e=>{ou.set(e,(ou.get(e)??0)+1);let t=!1;return()=>{t||(t=!0,ou.set(e,Math.max(0,(ou.get(e)??1)-1)))}},cu=`RelayUnavailableError`,lu=`this FKN page cannot choose a relay; reload the app to load the current one`,uu=`fkn-proxy`,du=`fkn-proxy.`,fu=e=>Object.assign(Error(e),{name:cu}),pu=(e,t)=>{if(typeof e.relay?.resolve!=`function`)throw fu(`${t}: ${lu}`)},mu=`webvpn-udp-port-ack`,hu=`read ECONNRESET`,gu=()=>Object.assign(/* @__PURE__ */ Error(hu),{code:`ECONNRESET`,errno:-104,syscall:`read`}),_u={ECONNREFUSED:-111,ETIMEDOUT:-110,EHOSTUNREACH:-113,ENETUNREACH:-101},vu=(e,t,n)=>{let r=e===`ENETUNREACH`?` - Local (${t.includes(`:`)?`::`:`0.0.0.0`}:0)`:``;return Object.assign(/* @__PURE__ */ Error(`connect ${e} ${t}:${n}${r}`),{errno:_u[e],code:e,syscall:`connect`,address:t,port:n})},yu=e=>Object.assign(/* @__PURE__ */ Error(`getaddrinfo ENOTFOUND ${e}`),{errno:-3008,code:`ENOTFOUND`,syscall:`getaddrinfo`,hostname:e}),bu=/^connect (ECONNREFUSED|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH) (\S+):(\d+)(?: - Local \(\S+\))?$/,xu=/^getaddrinfo ENOTFOUND (\S+)$/,Su=e=>{let t=e?.message;if(typeof t!=`string`)return e;if(t===`read ECONNRESET`)return gu();let n=bu.exec(t);if(n)return vu(n[1],n[2],Number(n[3]));let r=xu.exec(t);return r?yu(r[1]):e},Cu=/* @__PURE__ */ t(((e,t)=>{var n=typeof Reflect==`object`?Reflect:null,r=n&&typeof n.apply==`function`?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},i=n&&typeof n.ownKeys==`function`?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function a(e){console&&console.warn&&console.warn(e)}var o=Number.isNaN||function(e){return e!==e};function s(){s.init.call(this)}t.exports=s,t.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function l(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);c=e}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function u(e){return e._maxListeners===void 0?s.defaultMaxListeners:e._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=/* @__PURE__ */ Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)r(c,this,t);else for(var l=c.length,u=g(c,l),n=0;n<l;++n)r(u[n],this,t);return!0};function d(e,t,n,r){var i,o,s;if(l(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),s=o[t]),s===void 0)s=o[t]=n,++e._eventsCount;else if(typeof s==`function`?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),i=u(e),i>0&&s.length>i&&!s.warned){s.warned=!0;var c=/* @__PURE__ */ Error(`Possible EventEmitter memory leak detected. `+s.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);c.name=`MaxListenersExceededWarning`,c.emitter=e,c.type=t,c.count=s.length,a(c)}return e}s.prototype.addListener=function(e,t){return d(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return d(this,e,t,!0)};function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=f.bind(r);return i.listener=n,r.wrapFn=i,i}s.prototype.once=function(e,t){return l(t),this.on(e,p(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,p(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,a,o;if(l(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():_(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function m(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?v(i):g(i,i.length)}s.prototype.listeners=function(e){return m(this,e,!0)},s.prototype.rawListeners=function(e){return m(this,e,!1)},s.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h;function h(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]};function g(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function _(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function v(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function y(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}x(e,t,a,{once:!0}),t!==`error`&&b(e,i,{once:!0})})}function b(e,t,n){typeof e.on==`function`&&x(e,`error`,t,n)}function x(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}})),wu=/* @__PURE__ */ t(((e,t)=>{t.exports=typeof Object.create==`function`?function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Tu=/* @__PURE__ */ t(((e,t)=>{t.exports=Cu().EventEmitter})),Eu=/* @__PURE__ */ t((e=>{e.byteLength=c,e.toByteArray=u,e.fromByteArray=p;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e){var t=s(e),n=t[0],r=t[1];return(n+r)*3/4-r}function l(e,t,n){return(t+n)*3/4-n}function u(e){for(var t,i=s(e),a=i[0],o=i[1],c=new r(l(e,a,o)),u=0,d=o>0?a-4:a,f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,c[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,c[u++]=t>>8&255,c[u++]=t&255),c}function d(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[e&63]}function f(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(d(r));return i.join(``)}function p(e){for(var n,r=e.length,i=r%3,a=[],o=16383,s=0,c=r-i;s<c;s+=o)a.push(f(e,s,s+o>c?c:s+o));return i===1?(n=e[r-1],a.push(t[n>>2]+t[n<<4&63]+`==`)):i===2&&(n=(e[r-2]<<8)+e[r-1],a.push(t[n>>10]+t[n>>4&63]+t[n<<2&63]+`=`)),a.join(``)}})),Du=/* @__PURE__ */ t((e=>{
|
|
3
|
+
This browser reports limited detail, so the cause above is a best guess.`:``)))},Ia=(e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=(Array.isArray(n.rects)?n.rects.slice(0,Zi):[]).map(e=>ja(e,t)).filter(e=>e!==null&&e.width>0&&e.height>0);return{modal:n.modal===!0,rects:r,hidden:Na(n.hidden),inset:ka(n.inset)}},La=()=>va!==null,Ra=null,za=null,Ba=()=>{if(!va||Ra===null)return;let e=ba(va),t=Ia(Ra,e);t&&Oa(va,t,e)},Va=e=>{typeof ResizeObserver<`u`&&(za??=new ResizeObserver(Ba),za.disconnect(),za.observe(e))},Ha=e=>{ia(e),Oa(e,{modal:!1,rects:[],hidden:[],inset:0},ba(e)),va=e,Va(e)},Ua=e=>{if(!va)return;let t=ba(va),n=Ia(e,t);n&&(Ra=e,Oa(va,n,t),Fa(n.hidden))},Wa=`https://fkn.app`,Ga=typeof globalThis<`u`&&globalThis.document?globalThis.document:void 0,Ka=typeof globalThis<`u`&&globalThis.crossOriginIsolated===!0,qa=p(Ka),Ja=`fkn-api-port`,Ya=`fkn-api-port-ack`,Xa=2e3,Za=()=>{if(!Ga||typeof window>`u`||window.parent===window)return Promise.resolve(void 0);let e;try{e=window.parent}catch{return Promise.resolve(void 0)}let t=new MessageChannel;return new Promise(n=>{let r=e=>{if(clearTimeout(a),t.port1.removeEventListener(`message`,i),!e)try{t.port1.close()}catch{}n(e)},i=e=>{e.data?.type===Ya&&r(t.port1)},a=setTimeout(()=>r(void 0),Xa);t.port1.addEventListener(`message`,i),t.port1.start();try{e.postMessage({type:Ja},Wa,[t.port2])}catch{r(void 0)}})},Qa,$a=e=>e.querySelector(`iframe[src="${qa}"]`),eo=async e=>{for(;!e.body;)await new Promise(t=>{let n=new MutationObserver(()=>{n.disconnect(),t()});n.observe(e,{childList:!0,subtree:!0})})},to=async e=>{let t=$a(e);if(t||=(await eo(e),$a(e)),t)Qa=t;else{let t=e.createElement(`iframe`);t.setAttribute(`allow`,d(Ka)),t.src=qa,e.body.appendChild(t),Qa=t}return Yi(Qa,qa,Wa),Ha(Qa),Qa},no=(async()=>{if(!Ga)return;let e=await Za();if(e)return{receive:e,emit:e};let t=await to(Ga);return await Ki(t),t.contentWindow?Xi(t,Wa):void 0})(),ro=(e,{boundRetired:t=e=>e}={})=>{let n,r=0,i=!1,a=()=>{},o=()=>new Promise(e=>{a=e}),s=o(),c=s,l=/* @__PURE__ */ new Set,u=/* @__PURE__ */ new Set,d=0,f=0,p=()=>{let e=[...u];u.clear();let t=/* @__PURE__ */ Error(`FKN: the broker was replaced while this call was pending; retry it`);for(let n of e)try{n(t)}catch{}};(async()=>{for await(let t of e){let e=++r,i=n!==void 0;n={remote:t,epoch:e,replaced:i};let c=a;s=o(),c(t),p();for(let n of[...l])try{n(t,e,i)}catch{}}})().catch(()=>{});let m=async(e,r)=>{let a=n?.remote??await(i?t(s):s);for(let t of e.slice(0,-1))a=a[t];let o=a[e[e.length-1]??``];d=Date.now(),f+=1;let c=()=>{},l=new Promise((e,t)=>{c=t});u.add(c);try{return await Promise.race([Promise.resolve(o.apply(a,r)),l])}finally{--f,u.delete(c),d=Date.now()}},h=/* @__PURE__ */ new Map,g=e=>{let t=e.join(`\0`),r=h.get(t);if(r)return r;let i=new Proxy(function(){},{get:(t,r)=>{if(typeof r!=`string`||r===`then`)return;let i=n;if(i){let t=i.remote;for(let n of e)t=t?.[n];if(t?.[r]===void 0)return}return g([...e,r])},apply:(t,n,r)=>m(e,r)});return h.set(t,i),i};return{facade:g([]),first:c.then(()=>{}),current:()=>n,onEpoch:e=>{if(l.add(e),n)try{e(n.remote,n.epoch,n.replaced)}catch{}return()=>{l.delete(e)}},lastCall:()=>d,inFlight:()=>f,routable:()=>n?Promise.resolve():s.then(()=>{}),retire:()=>{i=!0,n=void 0,p()}}},io=!1,ao=/* @__PURE__ */ new Set,oo=()=>io,so=e=>{ao.add(e)},co=e=>`fkn-relayed-worker-${e}`,lo=e=>new Promise(t=>{let n=globalThis.navigator?.locks;if(!n)return t();n.request(co(e),()=>(t(),new Promise(()=>{}))).catch(()=>t())}),uo=async()=>{if(typeof window<`u`)return no;if(typeof self<`u`)return{receive:self,emit:self}},fo=`fkn-api`,po=`fkn-api-window`,mo={async*[Symbol.asyncIterator](){let e=await uo();if(!e)await new Promise(()=>{});else{if(!oo()){let t=new AbortController;so(()=>t.abort());let n=crypto.randomUUID();typeof window>`u`&&await lo(n);for await(let r of Hi({},{key:fo,transport:e,unregisterSignal:t.signal,uuid:n})){if(t.signal.aborted)break;yield r}}yield*Hi({},{key:po,transport:e})}}},ho=!1,go=uo().then(e=>new Promise(t=>{if(!e)return;let n=new AbortController;O({transport:e,key:fo,unregisterSignal:n.signal,listener:()=>{n.abort(),ho=!0,t()}})})),_o=ro(mo,{boundRetired:e=>Promise.race([e,go.then(()=>To(e,()=>new Co))])});so(()=>_o.retire());var vo=class extends Error{constructor(e,t){super(t===void 0?`@fkn/lib: no FKN broker in this realm (it has no window and no self, as in Node.js), so ${e} could not be requested`:`@fkn/lib: no broker connection within ${t}ms, so ${e} could not be requested`),this.name=`BrokerUnreachableError`}},yo=v?Promise.race([_o.first,new Promise(e=>so(e))]).then(()=>_o.facade):Promise.reject(new vo(`a broker call`));yo.catch(()=>{});var bo=8e3,xo=1e3,So=!1,Co=class extends Error{constructor(){super(`FKN @fkn/lib: this page relays its FKN channel to a worker, and the FKN page it reached predates a channel of the page's own; reload`),this.name=`OwnChannelUnavailableError`}},wo=e=>new Promise((t,n)=>setTimeout(()=>n(e))),To=(e,t)=>{if(So&&!ho)return wo(t(bo));let n=So?xo:bo;return Promise.race([e,new Promise((e,r)=>setTimeout(()=>{So=!0,r(t(n))},n))])},Eo=e=>v?oo()?To(_o.routable().then(()=>_o.facade),t=>ho?new Co:new vo(e,t)):To(yo,t=>new vo(e,t)):wo(new vo(e));so(()=>{go.then(()=>{let e=setTimeout(()=>console.error(new Co),bo);_o.routable().then(()=>clearTimeout(e))})});var Do=_o.onEpoch,Oo=_o.current;_o.lastCall,_o.inFlight,Do(e=>{La()&&e.overlay.setHost(Ua,{exactClips:oa(),colorScheme:ra}).catch(()=>{})}),typeof window<`u`&&g(()=>{let e=Oo();return e?_(()=>e.remote.shell?.showHeader?.(),8e3):!1});var ko=(e,t)=>yo.then(n=>n.cloud.dns.lookup(e,t));function Ao(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function jo(e,t){let n,r=()=>{if(n)return n;let r=indexedDB.open(e);return r.onupgradeneeded=()=>r.result.createObjectStore(t),n=Ao(r),n.then(e=>{e.onclose=()=>n=void 0},()=>{}),n};return(e,n)=>r().then(r=>n(r.transaction(t,e).objectStore(t)))}let Mo;function No(){return Mo||=jo(`keyval-store`,`keyval`),Mo}function Po(e,t=No()){return t(`readonly`,t=>Ao(t.get(e)))}function Fo(e,t,n=No()){return n(`readwrite`,n=>(n.put(t,e),Ao(n.transaction)))}function Io(e,t,n=No()){return n(`readwrite`,n=>new Promise((r,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),r(Ao(n.transaction))}catch(e){i(e)}}}))}function Lo(e,t=No()){return t(`readwrite`,t=>(t.delete(e),Ao(t.transaction)))}var Ro={checkingFiles:1,downloadingMetadata:2,downloading:3,finished:4,seeding:5,checkingResumeData:7},zo=/^incoming connection from (\S+) \(([^)]*)\)/,Bo=/^successfully listening on \[([^\]]*)\] (\S+)/,Vo=/^listening on .* failed:/,Ho=new TextDecoder,Uo=4026531841,Wo=4026531842,Go=4026531843,Ko=4026531844,qo=4026531845,Jo=4026531846,Yo={interesting:1,choked:2,remoteInterested:4,remoteChoked:8,supportsExtensions:16,localConnection:32,handshake:64,connecting:128,onParole:512,seed:1024,optimisticUnchoke:2048,snubbed:4096,uploadOnly:8192,endgameMode:16384,holepunched:32768,i2pSocket:65536,utpSocket:1<<17,sslSocket:1<<18,rc4Encrypted:1<<19,plaintextEncrypted:1<<20},V={seedMode:1,uploadMode:2,shareMode:4,applyIpFilter:8,paused:16,autoManaged:32,duplicateIsError:64,updateSubscribe:128,superSeeding:256,sequentialDownload:512,stopWhenReady:1024,overrideTrackers:2048,overrideWebSeeds:4096,needSaveResume:8192,disableDht:1<<19,disableLsd:1<<20,disablePex:1<<21,noVerifyFiles:1<<22,defaultDontDownload:1<<23},Xo={top:0,up:1,down:2,bottom:3},Zo={tracker:1,dht:2,pex:4,lsd:8,resumeData:16,incoming:32},H={skip:0,low:1,normal:4,top:7},Qo=1<<22,$o=6881,es=1e4,ts=100663296,ns=e=>{let t=/^100\.(\d+)\.(\d+)\.(\d+)(?::\d+)?$/.exec(e);return!t||(t[1]&192)!=64?-1:(t[1]&63)<<16|t[2]<<8|t[3]},rs=6e4,is=12,as=1e3,os=class{mod;storage;destroyed=!1;fallbackTimer;filesByHandle=/* @__PURE__ */ new Map;bitfieldByHandle=/* @__PURE__ */ new Map;statusByHandle=/* @__PURE__ */ new Map;pieceWaiters=[];resumeByHandle=/* @__PURE__ */ new Map;resumeWaiters=[];peersByHandle=/* @__PURE__ */ new Map;trackersByHandle=/* @__PURE__ */ new Map;peerWaiters=[];trackerWaiters=[];priosByHandle=/* @__PURE__ */ new Map;deadlineRefs=/* @__PURE__ */ new Map;textAlerts=[];streams=/* @__PURE__ */ new Map;nextStream=Math.floor(Math.random()*Qo);handles=/* @__PURE__ */ new Set;windows=/* @__PURE__ */ new Set;reachability={listening:{},listenFailed:[],inbound:0,inboundByTransport:{},lastInbound:null,port:null};constructor(e,t){if(this.mod=e,this.storage=t.storage??null,t.utpReceiveBufferBytes&&e._lt_set_utp_receive_buffer(t.utpReceiveBufferBytes),t.enableDht===!1&&e._lt_set_dht(0),t.extraCaPem){let n=e.stringToNewUTF8(t.extraCaPem);try{e._lt_set_extra_ca_pem(n)}finally{e._free(n)}}else e._lt_set_extra_ca_pem?.(0);if(t.rateLimits){let{download:n,upload:r,limitLocalPeers:i}=t.rateLimits;e._lt_session_set_rate_limits(Math.max(0,Math.floor(n??0)),Math.max(0,Math.floor(r??0)),i==null?-1:+!!i)}if(e._lt_session_create()!==0)throw Error(`lt_session_create returned non-zero`);e.fkn&&(e.fkn.takeStream=e=>this.takeStream(e));let n=t.tickIntervalMs??250;this.fallbackTimer=setInterval(()=>this.tick(),n)}addMagnet(e,t=`/downloads`){let n=this.mod,r=n.stringToNewUTF8(e),i=n.stringToNewUTF8(t);try{return this.added(n._lt_session_add_magnet(r,i))}finally{n._free(r),n._free(i)}}addTorrentFile(e,t=`/downloads`){let n=this.mod,r=n._malloc(e.length);n.HEAPU8.set(e,r);let i=n.stringToNewUTF8(t);try{return this.added(n._lt_session_add_torrent_file(r,e.length,i))}finally{n._free(r),n._free(i)}}addTorrentWithResume(e,t=`/downloads`){let n=this.mod,r=n._malloc(e.length);n.HEAPU8.set(e,r);let i=n.stringToNewUTF8(t);try{return this.added(n._lt_session_add_torrent_with_resume(r,e.length,i))}finally{n._free(r),n._free(i)}}added(e){return e>0&&this.handles.add(e),e>>>0}torrents(){return[...this.handles]}removeTorrent(e,t=!1){let n=this.mod._lt_session_remove_torrent_ex(e,+!!t)===0;return this.failPieceWaiters(/* @__PURE__ */ Error(`read: torrent ${e} was removed`),e),this.resumeWaiters=this.resumeWaiters.filter(t=>t.handle!==e||(clearTimeout(t.timer),t.reject(/* @__PURE__ */ Error(`save_resume_data: torrent ${e} was removed`)),!1)),this.handles.delete(e),this.windows.delete(e),this.filesByHandle.delete(e),this.bitfieldByHandle.delete(e),this.statusByHandle.delete(e),this.resumeByHandle.delete(e),this.priosByHandle.delete(e),this.deadlineRefs.delete(e),n}pauseTorrent(e){this.mod._lt_torrent_pause(e)}resumeTorrent(e){this.mod._lt_torrent_resume(e)}forceRecheck(e){this.mod._lt_torrent_force_recheck(e)}saveResumeData(e,t=8e3){return!this.handles.has(e)||this.mod._lt_torrent_save_resume_data(e)!==0?Promise.reject(/* @__PURE__ */ Error(`save_resume_data: no torrent ${e}`)):new Promise((n,r)=>{let i={handle:e,resolve:n,reject:r,timer:setTimeout(()=>{let e=this.resumeWaiters.indexOf(i);e>=0&&(this.resumeWaiters.splice(e,1),r(/* @__PURE__ */ Error(`save_resume_data timed out`)))},t)};this.resumeWaiters.push(i)})}addPeerStream(e,t){let n=this.nextStream;this.nextStream=(n+1)%Qo;let r=`100.${64+(n>>16)}.${n>>8&255}.${n&255}`;return t.maxRecvQueue??=ts,this.streams.set(r,{socket:t,timer:setTimeout(()=>this.dropStream(r,`libtorrent did not dial within ${es} ms`),es)}),this.drainAlerts(),this.mod._lt_torrent_add_channel_peer(e,1681915904+n,$o)!==0&&this.dropStream(r,`the engine has no torrent ${e}`),{address:r,port:$o}}takeStream(e){let t=this.streams.get(e);if(t)return this.streams.delete(e),clearTimeout(t.timer),t.socket}dropStream(e,t){let n=this.takeStream(e);try{n?.destroy(/* @__PURE__ */ Error(`addPeerStream: ${t}`))}catch{}}peers(e,t=4e3){return this.mod._lt_torrent_post_peers(e),this.awaitList(this.peerWaiters,this.peersByHandle,e,t)}lastPeers(e){return this.peersByHandle.get(e)??[]}trackers(e,t=4e3){return this.mod._lt_torrent_post_trackers(e),this.awaitList(this.trackerWaiters,this.trackersByHandle,e,t)}lastTrackers(e){return this.trackersByHandle.get(e)??[]}addTrackers(e,t){let n=this.mod,r=[];for(let i of t){let t=n.stringToNewUTF8(i.trim());try{n._lt_torrent_add_tracker(e,t)!==0&&r.push(i)}finally{n._free(t)}}return r}pieceAvailability(e){let t=this.filesByHandle.get(e);if(!t)return null;let n=this.mod,r=n._malloc(t.numPieces*2);try{let i=n._lt_torrent_piece_availability(e,r,t.numPieces);return i<0?null:new Uint16Array(n.HEAPU8.buffer,r,i).slice()}finally{n._free(r)}}dhtNodes(){return this.mod._lt_session_dht_nodes()}awaitList(e,t,n,r){return new Promise(i=>{let a={handle:n,resolve:i,timer:setTimeout(()=>{let r=e.indexOf(a);r>=0&&(e.splice(r,1),i(t.get(n)??[]))},r)};e.push(a)})}resolveOne(e,t,n){for(let r=e.length-1;r>=0;r--){let i=e[r];i.handle===t&&(clearTimeout(i.timer),e.splice(r,1),i.resolve(n))}}files(e){return this.filesByHandle.get(e)??null}bitfield(e){let t=this.bitfieldByHandle.get(e),n=this.filesByHandle.get(e);return!t||!n?null:{pieces:t.pieces,numPieces:t.numPieces,pieceLength:n.pieceLength,length:n.totalSize}}status(e){return this.statusByHandle.get(e)??null}async read(e,t,n,r,i={}){let a=this.filesByHandle.get(e);if(!a)throw Error(`read: no layout for handle ${e} (metadata not ready)`);let o=a.files[t];if(!o)throw Error(`read: no file ${t}`);if(!this.storage)throw Error(`read: no storage backend configured`);if(n<0)throw RangeError(`read: negative offset ${n}`);let s=Math.min(r,o.size-n);if(s<=0)return/* @__PURE__ */ new Uint8Array;let{pieceLength:c}=a,l=o.offset+n,u=Math.floor(l/c),d=Math.min(a.numPieces-1,Math.floor((l+s-1)/c));if(!this.hasPieces(e,u,d)){let t=i.deadlineMs===void 0?0:i.deadlineMs;if(t!==null){for(let n=u;n<=d;n++)this.mod._lt_torrent_set_piece_deadline(e,n,t,0);this.retainDeadlines(e,u,d)}this.mod._lt_torrent_post_status(e);try{await this.awaitPieces(e,u,d,i)}finally{t!==null&&this.releaseDeadlines(e,u,d)}}let f=await this.storage.read(a.storageIndex,t,n,s);return f instanceof Uint8Array?f:new Uint8Array(f)}setStreamWindow(e,t,n={}){let r=this.filesByHandle.get(e);if(!r)return!1;let{pieceLength:i,numPieces:a}=r,o=Math.max(1,Math.floor(n.windowPieces??is)),s=Math.max(0,Math.floor(n.deadlineStepMs??as)),c=n.claimedPriority??H.normal,l=n.unclaimedPriority??H.normal,u=new Uint8Array(a).fill(l),d=n.keep&&new Uint8Array(a);if(d)for(let{start:e,end:t}of n.keep)d.fill(1,Math.max(0,e),Math.max(0,t));let f=/* @__PURE__ */ new Map,p=0;for(let e of t){let t=r.files[e.fileIndex];if(!t||t.size<=0)continue;p++;let n=Math.floor(t.offset/i),l=Math.min(a-1,Math.floor((t.offset+t.size-1)/i));for(let e=n;e<=l;e++)(!d||d[e])&&(u[e]=c);let m=Math.min(Math.max(e.offset,0),Math.max(0,t.size-1)),h=Math.min(Math.max(Math.floor((t.offset+m)/i),n),l);for(let e=0;e<o;e++){let t=h+e;if(t>l)break;u[t]=H.top;let n=e*s,r=f.get(t);(r===void 0||n<r)&&f.set(t,n)}}if(!p)return!1;if(this.mod._lt_torrent_clear_piece_deadlines(e),this.prioritizePieces(e,u),n.deadlines!==!1){for(let[t,n]of f)this.mod._lt_torrent_set_piece_deadline(e,t,n,0);this.windows.add(e)}else this.windows.delete(e);return this.reissueReadDeadlines(e),n.sequential!==!1&&this.setSequential(e,!0),!0}hasStreamWindow(e){return this.windows.has(e)}clearStreamWindow(e){this.windows.delete(e),this.mod._lt_torrent_clear_piece_deadlines(e);let t=this.filesByHandle.get(e);t&&this.prioritizePieces(e,new Uint8Array(t.numPieces).fill(H.normal)),this.reissueReadDeadlines(e),this.setSequential(e,!1)}prioritizeRange(e,t,n,r){let i=this.filesByHandle.get(e),a=i?.files[t];if(!i||!a)return;let{pieceLength:o,numPieces:s}=i,c=Math.min(r,a.size-n);if(c<=0)return;let l=Math.max(0,Math.floor((a.offset+n)/o)),u=Math.min(s-1,Math.floor((a.offset+n+c-1)/o));if(u<l)return;let d=new Uint8Array(s).fill(H.normal);for(let e=l;e<=u;e++)d[e]=H.top;this.windows.delete(e),this.mod._lt_torrent_clear_piece_deadlines(e),this.prioritizePieces(e,d);for(let t=l;t<=u;t++)this.mod._lt_torrent_set_piece_deadline(e,t,(t-l)*as,0);this.reissueReadDeadlines(e)}setSequential(e,t){this.mod._lt_torrent_set_sequential(e,+!!t)}setFlags(e,t,n){this.mod._lt_torrent_set_flags(e,t>>>0,n>>>0)}setFlag(e,t,n){this.setFlags(e,n?t:0,t)}forceReannounce(e){this.mod._lt_torrent_force_reannounce(e)}moveInQueue(e,t){this.mod._lt_torrent_queue_position(e,Xo[t])}setRateLimits({download:e,upload:t,limitLocalPeers:n}){let r=e=>e==null?-1:Math.max(0,Math.floor(e));this.mod._lt_session_set_rate_limits(r(e),r(t),n==null?-1:+!!n)}setUploadLimit(e,t){this.mod._lt_torrent_set_upload_limit(e,Math.max(0,Math.floor(t)))}setDownloadLimit(e,t){this.mod._lt_torrent_set_download_limit(e,Math.max(0,Math.floor(t)))}setPieceDeadline(e,t,n,r=!1){this.mod._lt_torrent_set_piece_deadline(e,t,n,+!!r)}clearPieceDeadlines(e){this.mod._lt_torrent_clear_piece_deadlines(e),this.reissueReadDeadlines(e)}resetPieceDeadline(e,t){this.mod._lt_torrent_reset_piece_deadline(e,t)}cancelPieceRequests(e,t){return this.mod._lt_torrent_cancel_piece_requests(e,t)===0}forgetPieces(e,t){let n=[...t];this.drainAlerts();let r=this.mod,i=r._malloc(n.length*4+4),a=i+n.length*4;try{for(let e=0;e<n.length;e++)r.HEAP32[(i>>2)+e]=n[e]|0;r.HEAP32[a>>2]=0;let t=r._lt_torrent_forget_pieces(e,i,n.length,a);if(t<0)return null;let o=this.bitfieldByHandle.get(e);if(o)for(let e of n)e>=0&&e<o.numPieces&&(o.pieces[e>>3]&=~(128>>(e&7)));return{forgotten:t,busy:r.HEAP32[a>>2]}}finally{r._free(i)}}prioritizePieces(e,t){let n=this.mod,r=this.filesByHandle.get(e);if(!r||!r.numPieces)return;let i=t;if(i.length!==r.numPieces){let t=new Uint8Array(r.numPieces),n=this.priosByHandle.get(e);n?t.set(n.subarray(0,r.numPieces)):t.fill(H.normal),t.set(i.subarray(0,r.numPieces)),i=t}let a=n._malloc(i.length);n.HEAPU8.set(i,a);try{n._lt_torrent_prioritize_pieces(e,a,i.length)===0&&this.priosByHandle.set(e,Uint8Array.from(i,e=>Math.min(e,H.top)))}finally{n._free(a)}}prioritizePieceList(e,t){let n=this.mod,r=this.filesByHandle.get(e);if(!r)return;let i=[...t].filter(e=>e.piece>=0&&e.piece<r.numPieces);if(!i.length)return;let a=n._malloc(i.length*4),o=n._malloc(i.length);try{let t=this.priosByHandle.get(e);for(let e=0;e<i.length;e++){let{piece:r,priority:s}=i[e],c=Math.min(Math.max(s,0),H.top);n.HEAP32[(a>>2)+e]=r,n.HEAPU8[o+e]=c,t&&r<t.length&&(t[r]=c)}n._lt_torrent_prioritize_piece_list(e,a,o,i.length)}finally{n._free(a),n._free(o)}}setFilePriorities(e,t){let n=this.mod;if(!t.length)return;let r=n._malloc(t.length);n.HEAPU8.set(t,r);try{n._lt_torrent_prioritize_files(e,r,t.length)}finally{n._free(r)}this.priosByHandle.delete(e)}setFilePriority(e,t,n){let r=this.mod._lt_torrent_set_file_priority(e,t,n)===0;return r&&this.priosByHandle.delete(e),r}piecePriorities(e){let t=this.priosByHandle.get(e);return t?Uint8Array.from(t):null}retainDeadlines(e,t,n){let r=this.deadlineRefs.get(e);r||this.deadlineRefs.set(e,r=/* @__PURE__ */ new Map);for(let e=t;e<=n;e++)r.set(e,(r.get(e)??0)+1)}releaseDeadlines(e,t,n){let r=this.deadlineRefs.get(e);if(!r)return;let i=[],a=this.priosByHandle.get(e);for(let o=t;o<=n;o++){let t=(r.get(o)??0)-1;if(t>0){r.set(o,t);continue}r.delete(o),this.mod._lt_torrent_reset_piece_deadline(e,o),i.push({piece:o,priority:a?.[o]??H.normal})}i.length&&this.prioritizePieceList(e,i),r.size||this.deadlineRefs.delete(e)}reissueReadDeadlines(e){let t=this.deadlineRefs.get(e);if(t)for(let n of t.keys())this.mod._lt_torrent_set_piece_deadline(e,n,0,0)}postStatus(e){this.mod._lt_torrent_post_status(e)}infohash(e){return this.readHash(e,this.mod._lt_torrent_infohash)}infohashV2(e){return this.readHash(e,this.mod._lt_torrent_infohash_v2)}webSocketTrackers(e){let t=this.mod.UTF8ToString(this.mod._lt_torrent_ws_trackers(e));return t?t.split(`
|
|
4
|
+
`):[]}isPrivate(e){let t=this.mod._lt_torrent_private(e);return t<0?void 0:t===1}readHash(e,t){let n=this.mod,r=n._malloc(65);try{return t.call(n,e,r)===0?n.UTF8ToString(r):null}finally{n._free(r)}}hasPieces(e,t,n){let r=this.bitfieldByHandle.get(e);if(!r)return!1;for(let e=t;e<=n;e++){if(e<0||e>=r.numPieces)return!1;let t=r.pieces[e>>3];if(t===void 0||!(t&128>>(e&7)))return!1}return!0}awaitPieces(e,t,n,r){let{signal:i}=r,a=r.timeoutMs??rs;return new Promise((r,o)=>{let s,c,l=e=>{let t=this.pieceWaiters.indexOf(u);t<0||(this.pieceWaiters.splice(t,1),s!==void 0&&clearTimeout(s),c&&i&&i.removeEventListener(`abort`,c),e?o(e):r())},u={handle:e,p0:t,p1:n,settle:l};if(this.pieceWaiters.push(u),i?.aborted){l(/* @__PURE__ */ Error(`read: aborted`));return}a>0&&(s=setTimeout(()=>l(/* @__PURE__ */ Error(`read: pieces ${t}-${n} of handle ${e} did not arrive within ${a}ms`)),a)),i&&(c=()=>l(/* @__PURE__ */ Error(`read: aborted`)),i.addEventListener(`abort`,c,{once:!0}))})}resolvePieceWaiters(){if(this.pieceWaiters.length!==0)for(let e of[...this.pieceWaiters])this.hasPieces(e.handle,e.p0,e.p1)&&e.settle()}failPieceWaiters(e,t){for(let n of[...this.pieceWaiters])(t===void 0||n.handle===t)&&n.settle(e)}popAlerts(){this.drainAlerts();let e=this.textAlerts;return this.textAlerts=[],e}drainAlerts(){let e=this.mod;e._lt_session_pump_alerts();let t=e._lt_alerts_size()>>>0;if(!t)return;let n=e._lt_alerts_data()>>>0,r=new DataView(e.HEAPU8.buffer,n,t),i=this.textAlerts,a=0;try{for(;a+8<=t;){let o=r.getUint32(a,!0);a+=4;let s=r.getUint32(a,!0);if(a+=4,a+s>t)break;if(o===Uo)this.decodeTorrentReady(r,a);else if(o===Wo)this.decodeStateUpdate(r,a);else if(o===Ko)this.decodeResumeData(r,a,s);else if(o===qo)this.decodePeers(r,a);else if(o===Jo)this.decodeTrackers(r,a);else if(o!==Go){let t={type:o,message:e.UTF8ToString(n+a,s)};this.observeReachability(t.message),i.push(t)}a+=s}}finally{e._lt_alerts_clear(),this.resolvePieceWaiters()}}reachable(){let e=this.reachability.port,t=e===null?null:this.shim()?.announced||e,n=this.listeners();return{listening:{...this.reachability.listening},listenFailed:[...this.reachability.listenFailed],inbound:this.reachability.inbound,inboundByTransport:{...this.reachability.inboundByTransport},lastInbound:this.reachability.lastInbound,port:t,listeners:n,portOpen:t!==null&&n.some(e=>e.up&&e.port===t)}}listeners(){try{return this.shim()?.listeners?.()??[]}catch{return[]}}shim(){return this.mod.__FKN}observeReachability(e){let t=zo.exec(e);if(t){let e=t[2].toLowerCase();this.reachability.inbound++,this.reachability.inboundByTransport[e]=(this.reachability.inboundByTransport[e]??0)+1,this.reachability.lastInbound={endpoint:t[1],transport:e,at:Date.now()};return}let n=Bo.exec(e);if(n){this.reachability.listening[n[1].toLowerCase()]=n[2];return}Vo.test(e)&&this.reachability.listenFailed.length<32&&this.reachability.listenFailed.push(e)}readStr(e,t){let n=e.getUint32(t,!0);return t+=4,[Ho.decode(new Uint8Array(e.buffer,e.byteOffset+t,n)),t+n]}decodePeers(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getUint32(t,!0);t+=4;let i=[];for(let n=0;n<r;n++){let n,r;[n,t]=this.readStr(e,t),[r,t]=this.readStr(e,t);let a=e.getUint32(t,!0);t+=4;let o=e.getUint32(t,!0);t+=4;let s=e.getUint32(t,!0);t+=4;let c=e.getInt32(t,!0);t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=Number(e.getBigInt64(t,!0));t+=8;let p=Number(e.getBigInt64(t,!0));t+=8;let m=e.getInt32(t,!0)/1e6;t+=4;let h=e.getInt32(t,!0);t+=4;let g=e.getInt32(t,!0);t+=4;let _=e.getInt32(t,!0);t+=4;let v=e.getInt32(t,!0);t+=4;let y=a&Yo.localConnection?ns(n):-1;i.push({endpoint:y<0?n:`webrtc:${y}`,transport:y>=0?`webrtc`:a&Yo.utpSocket?`utp`:`tcp`,client:r,flags:a,source:o,connectionType:s,downloadRate:c,uploadRate:l,payloadDownloadRate:u,payloadUploadRate:d,totalDownload:f,totalUpload:p,progress:m,rtt:h,numPieces:g,requestsInFlight:_,failCount:v})}this.peersByHandle.set(n,i),this.resolveOne(this.peerWaiters,n,i)}decodeTrackers(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getUint32(t,!0);t+=4;let i=[];for(let n=0;n<r;n++){let n,r;[n,t]=this.readStr(e,t),[r,t]=this.readStr(e,t);let a=e.getInt32(t,!0);t+=4;let o=e.getInt32(t,!0);t+=4;let s=e.getUint32(t,!0)!==0;t+=4;let c=e.getUint32(t,!0)!==0;t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=e.getInt32(t,!0);t+=4,i.push({url:n,message:r,tier:a,fails:o,updating:s,verified:c,nextAnnounceIn:l,seeders:u,leechers:d,downloaded:f})}this.trackersByHandle.set(n,i),this.resolveOne(this.trackerWaiters,n,i)}decodeResumeData(e,t,n){let r=e.getUint32(t,!0),i=new Uint8Array(n-4);i.set(new Uint8Array(e.buffer,e.byteOffset+t+4,n-4)),this.resumeByHandle.set(r,i),this.resumeWaiters=this.resumeWaiters.filter(e=>e.handle!==r||(clearTimeout(e.timer),e.resolve(i),!1))}decodeTorrentReady(e,t){let n=new TextDecoder,r=e.getUint32(t,!0);t+=4;let i=e.getUint32(t,!0);t+=4;let a=e.getUint32(t,!0);t+=4;let o=e.getUint32(t,!0);t+=4;let s=Number(e.getBigInt64(t,!0));t+=8;let c=e.getUint32(t,!0);t+=4;let l=[];for(let r=0;r<c;r++){let r=Number(e.getBigInt64(t,!0));t+=8;let i=Number(e.getBigInt64(t,!0));t+=8;let a=e.getUint8(t)===1;t+=1;let o=e.getUint32(t,!0);t+=4;let s=n.decode(new Uint8Array(e.buffer,e.byteOffset+t,o));t+=o,l.push({path:s,size:i,offset:r,pad:a})}let u=l.reduce((e,t)=>e+(t.pad?0:t.size),0);this.filesByHandle.set(r,{storageIndex:i,pieceLength:a,numPieces:o,totalSize:s,contentSize:u,files:l})}decodeStateUpdate(e,t){let n=e.getUint32(t,!0);t+=4;let r=e.getInt32(t,!0);t+=4;let i=Number(e.getBigInt64(t,!0));t+=8;let a=Number(e.getBigInt64(t,!0));t+=8;let o=Number(e.getBigInt64(t,!0));t+=8;let s=e.getFloat32(t,!0);t+=4;let c=e.getInt32(t,!0);t+=4;let l=e.getInt32(t,!0);t+=4;let u=e.getInt32(t,!0);t+=4;let d=e.getInt32(t,!0);t+=4;let f=e.getUint32(t,!0)!==0;t+=4;let p=e.getUint32(t,!0)!==0;t+=4;let m=e.getUint32(t,!0)!==0;t+=4;let h=e.getUint32(t,!0)>>>0;t+=4;let g=Number(e.getBigInt64(t,!0));t+=8;let _=Number(e.getBigInt64(t,!0));t+=8;let v=Number(e.getBigInt64(t,!0));t+=8;let y=Number(e.getBigInt64(t,!0));t+=8;let b=Number(e.getBigInt64(t,!0));t+=8;let x=Number(e.getBigInt64(t,!0));t+=8;let S=Number(e.getBigInt64(t,!0));t+=8;let C=e.getInt32(t,!0);t+=4;let w=e.getInt32(t,!0);t+=4;let T=e.getInt32(t,!0);t+=4;let E=e.getInt32(t,!0);t+=4,t+=4;let D=e.getFloat32(t,!0);t+=4;let O=e.getInt32(t,!0);t+=4;let ee=e.getInt32(t,!0);t+=4;let k=Number(e.getBigInt64(t,!0));t+=8;let te=Number(e.getBigInt64(t,!0));t+=8;let A=Number(e.getBigInt64(t,!0));t+=8;let ne=e.getUint32(t,!0)!==0;t+=4;let j;[j,t]=this.readStr(e,t);let M=e.getInt32(t,!0);t+=4;let N=e.getInt32(t,!0);t+=4;let P=e.getUint32(t,!0);t+=4;let F=P?Ho.decode(new Uint8Array(e.buffer,e.byteOffset+t,P)):``;t+=P;let re=e.getUint32(t,!0);t+=4;let I=e.getUint32(t,!0);t+=4;let L=new Uint8Array(I);L.set(new Uint8Array(e.buffer,e.byteOffset+t,I)),this.bitfieldByHandle.set(n,{pieces:L,numPieces:re});let ie=0;for(let e=0;e<I;e++){let t=L[e];for(;t;)ie+=t&1,t>>=1}this.statusByHandle.set(n,{state:r,progress:s,totalDone:i,totalWanted:a,totalWantedDone:o,downloadRate:c,uploadRate:l,numPeers:u,numSeeds:d,numPiecesTotal:re,numPiecesHave:ie,paused:f,autoManaged:p,sequential:m,flags:h,queuePosition:M,errorCode:N,error:F,allTimeDownload:g,allTimeUpload:_,sessionDownload:v,sessionUpload:y,sessionPayloadDownload:b,sessionPayloadUpload:x,wasted:S,swarmSeeds:C,swarmPeers:w,numConnections:T,connectionsLimit:E,availability:D,activeSeconds:O,seedingSeconds:ee,addedAt:k,completedAt:te,lastSeenComplete:A,hadIncoming:ne,savePath:j,hasMetadata:r!==Ro.downloadingMetadata})}async*alerts(){for(;!this.destroyed;){for(let e of this.popAlerts())yield e;await new Promise(e=>setTimeout(e,100))}}setReservedPort(e){this.reachability.port=e}tick(){if(!this.destroyed&&(this.mod._lt_session_tick(),this.pieceWaiters.length)){let e=new Set(this.pieceWaiters.map(e=>e.handle));for(let t of e)this.mod._lt_torrent_post_status(t)}}destroy(){if(this.destroyed)return;this.destroyed=!0,this.fallbackTimer!=null&&clearInterval(this.fallbackTimer),this.failPieceWaiters(/* @__PURE__ */ Error(`read: session destroyed`)),this.pieceWaiters=[];for(let e of this.resumeWaiters)clearTimeout(e.timer),e.reject(/* @__PURE__ */ Error(`save_resume_data: session destroyed`));this.resumeWaiters=[],this.deadlineRefs.clear(),this.priosByHandle.clear(),this.handles.clear();for(let e of[...this.streams.keys()])this.dropStream(e,`the session was destroyed`);let e=()=>this.mod.__FKN?.teardown?.();this.mod._lt_session_destroy()?queueMicrotask(()=>{this.mod._lt_session_destroy(),e()}):e()}},ss=8e3,cs=e=>String(e?.message).includes(`listening needs a signed-in account`)||e?.name===`WebVpnError`&&e?.code===5||e?.code===`AUTH_REQUIRED`,ls=e=>{try{e?.close()}catch{}},us=(e,t,n)=>new Promise(r=>{let i;try{i=e()}catch{r(null);return}if(!i||typeof i.on!=`function`){r(null);return}let a=!1,o=e=>{a||(a=!0,clearTimeout(s),ls(i),n?.(e),r(null))},s=setTimeout(o,ss);i.on(`listening`,()=>{a||(a=!0,clearTimeout(s),r(i))}),i.on(`error`,o);try{t(i)}catch(e){o(e)}});async function ds(e,t,n=4){try{return await fs(e,t,n)}catch{return null}}async function fs(e,t,n){for(let r=0;r<n;r++){let i=await us(()=>t.createSocket({type:`udp4`}),e=>e.bind(0,`0.0.0.0`));if(!i)return null;let a=i.address?.()?.port;if(!a)return ls(i),null;let o,s=await us(()=>e.createServer(),e=>e.listen(a,`0.0.0.0`),e=>{o=e}),c=s?s.address?.()?.port:void 0,l=!!s&&c===a;if(s&&!l&&ls(s),!l){if(cs(o))return{port:a,server:null,udp:i,backlog:[],adopted:!1,authRequired:!0};if(r<n-1){ls(i);continue}return{port:a,server:null,udp:i,backlog:[],adopted:!1}}let u={port:a,server:s,udp:i,backlog:[],adopted:!1};return s.on(`connection`,e=>{u.adopted||u.backlog.push(e)}),u}return null}function ps(){return{net:{connect:()=>{let e;return queueMicrotask(()=>e?.(Object.assign(/* @__PURE__ */ Error(`offline host: connection refused`),{code:`ECONNREFUSED`}))),{on(t,n){t===`error`&&(e=n)},write:()=>!0,destroy(){}}},createServer:()=>({on(){},listen(){},close(){}})},dgram:{createSocket:()=>({on(){},bind(){},send(){},close(){}})},dnsLookup:async()=>void 0}}async function ms(e){let t=e.moduleFactory??(await import(`./libtorrent-CSPif8Ur.js`)).default,n={net:e.net,dgram:e.dgram,storage:e.storage??null,debug:e.debug??!1,dnsLookup:e.dnsLookup,listenNeedsAccount:cs},r=e.reserveListenPort===!1?Promise.resolve(null):ds(e.net,e.dgram),i=await t({fkn:n});i._lt_set_log(+!!e.debug);let a=await r;a?(n.prebound=a,i._lt_set_listen_port(a.port),!a.server&&e.debug&&console.warn(`[fkn] reserved udp ${a.port} but no matching tcp listener: inbound uTP works, inbound TCP is dark`)):e.debug&&console.warn(`[fkn] nothing reserved: the announced port is not one anyone can reach`);let o;try{o=new os(i,e)}catch(e){throw a&&!a.adopted&&(ls(a.server),ls(a.udp)),e}return o.setReservedPort(a?a.port:null),o}const hs=e=>{let t=[],n=[],r=!1;for(let i of e.slice(e.indexOf(`?`)+1).split(`&`)){let e=i.indexOf(`=`);if(r||e<0){r=e<0;continue}if(!/^xt(\.\d*)?$/i.test(i.slice(0,e)))continue;let a=i.slice(e+1);try{a=decodeURIComponent(a)}catch{}let o=a.match(/^urn:btih:([0-9a-zA-Z]+)/)?.[1];if(o){t.push(o.toLowerCase());continue}let s=a.match(/^urn:btmh:([0-9a-fA-F]+)/)?.[1]?.toLowerCase();s&&n.push(s.startsWith(`1220`)&&s.length===68?s.slice(4):s)}return new Set(t.map(gs)).size>1||new Set(n).size>1?null:t[0]??n[0]??null},gs=e=>{let t=e.toLowerCase();if(!/^[a-z2-7]{32}$/.test(t))return t;let n=``;for(let e of t)n+=`abcdefghijklmnopqrstuvwxyz234567`.indexOf(e).toString(2).padStart(5,`0`);let r=``;for(let e=0;e<n.length;e+=4)r+=parseInt(n.slice(e,e+4),2).toString(16);return r},_s=(e,t)=>!!e&&!!t&&gs(e)===gs(t),vs=(e,t)=>{let n=[];for(let r of e.matchAll(RegExp(`[?&]`+t+`=([^&]+)`,`g`))){let e=r[1];try{n.push(decodeURIComponent(e.replace(/\+/g,` `)))}catch{n.push(e)}}return[...new Set(n)]},ys=25e5,bs=e=>{if(!Number.isFinite(e)||e<=0)return 12;let t=Math.ceil(ys/e)+1,n=Math.max(2,Math.floor(8388608/e));return Math.min(Math.max(t,2),n)},xs=e=>bs(e)*Math.max(0,e),Ss=e=>Math.max(1,Math.floor(xs(e)/2)),Cs=(e,t)=>Math.min(2e3,Math.max(50,Math.round(e/Math.max(t,25e4)*1e3))),ws=(e,t,n,r=ys)=>{let i=e.fileOffset+n+Math.max(0,r-1);return Math.floor(i/e.pieceLength)>=e.p1?!1:Math.abs(n-t)>=Ss(e.pieceLength)};var Ts=(e,t,n)=>{let r=e.write(t,n);if(r<t.byteLength){let e=`the storage quota took ${r} of ${t.byteLength} bytes`,n=globalThis.QuotaExceededError;throw n?new n(e):new DOMException(e,`QuotaExceededError`)}return r},Es=(e,t)=>e.createSyncAccessHandle(t).finally(()=>e),Ds=class{storages=/* @__PURE__ */ new Map;opened=/* @__PURE__ */ new Map;onNewStorage(e,t,n){let r=(async()=>{let r=await Os(await navigator.storage.getDirectory(),t.replace(/^\/+/,``));this.storages.set(e,{rootDir:r,files:/* @__PURE__ */ new Map,opening:/* @__PURE__ */ new Map,fileMeta:n})})();return this.opened.set(e,r),r.then(()=>{this.opened.get(e)===r&&this.opened.delete(e)},()=>{}),r}async onRemoveStorage(e){this.opened.delete(e);let t=this.storages.get(e);if(t){for(let e of t.files.values())try{e.close()}catch{}this.storages.delete(e)}}read(e,t,n,r){let i=this.openFile(e,t),a=e=>{let t=new Uint8Array(r),i=e.read(t,{at:n});return i<r&&t.fill(0,i),t};return i instanceof Promise?i.then(a):a(i)}write(e,t,n,r){let i=this.openFile(e,t),a=i=>{try{let a=i.write(r,{at:n});if(a<r.length)throw console.error(`[opfs] short write`,{id:e,fileIndex:t,offset:n,want:r.length,wrote:a}),Error(`short write`)}catch(i){throw console.error(`[opfs] write failed`,{id:e,fileIndex:t,offset:n,len:r.length,err:String(i),errName:i?.name,errMsg:i?.message,isView:ArrayBuffer.isView(r),bytesType:Object.prototype.toString.call(r)}),i}};return i instanceof Promise?i.then(a).catch(n=>{throw console.error(`[opfs] openFile failed`,{id:e,fileIndex:t,err:String(n)}),n}):a(i)}async release(e){let t=this.storages.get(e);if(t){for(let e of t.files.values())try{e.flush(),e.close()}catch{}t.files.clear()}}async stop(e){return this.release(e)}async check(e){let t=!1;if(await this.opened.get(e)?.catch(()=>{t=!0}),t)return 2;let n=this.storages.get(e);if(!n)return 0;await this.release(e);for(let e of n.fileMeta)if(await this.hasBytes(n,e.path))return 2;return 0}async hasBytes(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(!r)return!1;let i=e.rootDir;try{for(let e of n)i=await i.getDirectoryHandle(e);return(await(await i.getFileHandle(r)).getFile()).size>0}catch(e){return e?.name!==`NotFoundError`}}async deleteFiles(e,t){let n=this.storages.get(e);if(n){for(let e of n.files.values())try{e.close()}catch{}n.files.clear();for(let e of n.fileMeta){let t=e.path.split(`/`).filter(Boolean),r=t.pop();if(!r)continue;let i=n.rootDir;for(let e of t)try{i=await i.getDirectoryHandle(e)}catch{i=null;break}if(i)try{await i.removeEntry(r)}catch{}}}}openFile(e,t){let n=this.storages.get(e);if(!n)throw Error(`unknown storage ${e}`);let r=n.files.get(t);if(r)return r;let i=n.opening.get(t);if(i)return i;let a=this.openFileSlow(e,t);return n.opening.set(t,a),a.finally(()=>n.opening.delete(t)),a}async openFileSlow(e,t){let n=this.storages.get(e),r=n.fileMeta[t];if(!r)throw Error(`unknown file ${t}`);let i=r.path.split(`/`).filter(Boolean),a=i.pop(),o=n.rootDir;for(let e of i)o=await o.getDirectoryHandle(e,{create:!0});let s=await Es(await o.getFileHandle(a,{create:!0}));return n.files.set(t,s),s}};async function Os(e,t){if(!t)return e;let n=e;for(let e of t.split(`/`).filter(Boolean))n=await n.getDirectoryHandle(e,{create:!0});return n}const ks=[50,150,400,900,1500],As=e=>e?.name===`QuotaExceededError`,js=(e,t,n)=>{if(n>0&&e&&!e(t,n))throw new DOMException(`kept for temporary films`,`QuotaExceededError`)},Ms=e=>Es(e),Ns=e=>new Promise(t=>setTimeout(t,e)),Ps=e=>{let t=async(t,n,r,i)=>{let a=i;for(let i of ks){if(As(a))break;if(n(),await Ns(i),e.has(t))throw a;try{return await r()}catch(e){a=e}}throw a};return(e,n,r)=>{try{let i=r();return i instanceof Promise?i.catch(i=>t(e,n,r,i)):i}catch(i){return t(e,n,r,i)}}},Fs=e=>{let t=new Ds,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=t,o=(e,t)=>{let n=a.storages?.get(e),r=n?.files?.get(t);if(r){n.files.delete(t);try{r.close()}catch{}}},s=async(e,t)=>{let n=a.storages?.get(e);if(!n?.fileMeta||!n.rootDir)return null;let r=0;for(let e=0;e<n.fileMeta.length;e++){if(t!==void 0&&e!==t)continue;let i=n.files?.get(e);if(i)try{r+=i.getSize();continue}catch{}let a=n.fileMeta[e].path.split(`/`).filter(Boolean),o=a.pop();if(!o)continue;let s=n.rootDir;for(let e of a)s=s?await s.getDirectoryHandle(e).catch(()=>null):null;s&&(r+=await s.getFileHandle(o).then(e=>e.getFile()).then(e=>e.size).catch(()=>0))}return r},c=async e=>{let t=r.get(e);return t===void 0?null:s(t)},l=Ps(n),u=(e,t,n)=>l(e,()=>o(e,t),n),d=(t,n,r,o)=>{let s=a=>{try{js(e,t,r+o.length-a.getSize()),Ts(a,o,{at:r})}catch(e){throw As(e)&&i.set(t,n),e}},c=a.openFile(t,n);return c instanceof Promise?c.then(s):s(c)};return{usageOf:c,usageOfStorage:s,refusedFile:e=>i.get(e),onNewStorage:(e,a,o)=>(n.delete(e),i.delete(e),r.set(a,e),u(e,-1,()=>t.onNewStorage(e,a,o))),onRemoveStorage:e=>{n.add(e);for(let[t,n]of r)n===e&&r.delete(t);return t.onRemoveStorage(e)},read:(e,n,r,i)=>u(e,n,()=>t.read(e,n,r,i)),write:(e,t,n,r)=>u(e,t,()=>d(e,t,n,r)),release:e=>t.release(e),check:e=>t.check(e).catch(()=>2),deleteFiles:(e,r)=>(n.add(e),t.deleteFiles(e,r)),stop:e=>t.stop(e)}},Is=67108864,Ls={start:0,end:0},Rs=(e,t,n)=>{let r=Math.min(n,e.size);return r<=t?Ls:{start:Math.floor((e.offset+t)/e.pieceLength),end:Math.floor((e.offset+r-1)/e.pieceLength)+1}},zs=(e,t,n)=>Rs(e,n*t,(n+1)*t),Bs=(e,t,n)=>{let r=/* @__PURE__ */ new Set;for(let{start:i,end:a}of n){let n=Math.max(0,i*e.pieceLength-e.offset),o=Math.min(e.size,a*e.pieceLength-e.offset);for(let e=Math.floor(n/t);n<o&&e<=Math.floor((o-1)/t);e++)r.add(e)}return r},Vs=(e,t)=>{let n=[],r=t,i=e.map((e,t)=>({size:e,i:t})).sort((e,t)=>e.size-t.size);return i.forEach(({size:e,i:t},a)=>{let o=Math.min(e,r/(i.length-a));n[t]=o,r-=o}),n},Hs=(e,t,n)=>e>t&&Math.floor(t/n)>=23,Us=({file:e,chunkBytes:t,room:n,reader:r,held:i,pinned:a=[]})=>{if(!Hs(e.size,n,t))return null;let o=Math.ceil(e.size/t)-1,s=Math.floor(Math.min(Math.max(r,0),e.size-1)/t),c=Math.floor(n/t)-3,l=new Set(i),u=Rs(e,0,t),d=Math.max(0,o-2-s),f=n=>{if(!d){let n=Rs(e,s*t,e.size);return{want:[u,n],ahead:n,slack:Ls}}let r=Rs(e,s*t,n*t),i=Rs(e,n*t,(n+2)*t);return{want:[u,r,i,Rs(e,o*t,e.size)],ahead:r,slack:i}},p=n=>Bs(e,t,[...f(n).want,...a]),m=s+Math.min(16,d),h=p(m);for(;m<s+d;){let e=p(m+1);if(e.size>c||[...e].some(e=>!h.has(e)&&!l.has(e))&&(/* @__PURE__ */ new Set([...e,...l])).size>c)break;m++,h=e}let g=/* @__PURE__ */ new Set([...h,...l]),_=[...l].filter(e=>!h.has(e)).sort((e,t)=>Math.abs(t-s)-Math.abs(e-s)||t-e);for(let e of _){if(g.size<=c)break;g.delete(e)}return{...f(m),keep:[...g].sort((e,t)=>e-t)}},Ws=(e,t,n)=>e||t<n,Gs=(e,t,n)=>{if(!e||t.usedBytes<e.usedBytes||t.headroomBytes>e.headroomBytes)return{...t,fixed:e?.fixed};let r=t.usedBytes-e.usedBytes;return r<n?e:{...t,fixed:e.headroomBytes-t.headroomBytes>=r/2}},Ks=/^(\d+)-(\d+)$/,qs=/^\d+$/,Js=(e=Is,t)=>{let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set,s=Ps(o),c=/* @__PURE__ */ new Map,l=(e,t,n)=>{let r=`${e}/${t}`,i=c.get(r);i||c.set(r,i=/* @__PURE__ */ new Set),i.add(n);let a=()=>{i.delete(n),!i.size&&c.get(r)===i&&c.delete(r)};n.then(a,a)},u=(e,t)=>`${e}-${t}`,d=e=>{let t=i.get(e);return t===void 0?void 0:n.get(t)},f=(e,t)=>{let i=n.get(e);if(i)return t(i);let a=r.get(e);if(!a)throw Error(`unknown storage ${e}`);return a.then(t)},p=(e,t,n,r)=>{let i=[];for(let a=0;a<r;){let o=Math.floor((n+a)/e.chunkBytes),s=n+a-o*e.chunkBytes,c=Math.min(r,a+e.chunkBytes-s);i.push({name:u(t,o),at:s,from:a,to:c}),a=c}return i},m=(e,t)=>{let n=e.handles.get(t);if(n)return n;let r=e.opening.get(t);if(r)return r;let i=e.dropping.get(t),a=(async()=>{i&&await i;let n=await Ms(await e.dir.getFileHandle(t,{create:!0}));return e.handles.set(t,n),n})();e.opening.set(t,a);let o=()=>{e.opening.get(t)===a&&e.opening.delete(t)};return a.then(o,o),a},h=(e,t,r,i)=>{let a=n.get(e);if(a)for(let{name:e}of p(a,t,r,i)){let t=a.handles.get(e);a.handles.delete(e);try{t?.close()}catch{}}},g=e=>{for(let t of e.handles.values())try{t.flush(),t.close()}catch{}e.handles.clear()},_=(e,t)=>{let n=0;for(let[r,i]of e.extents)(t===void 0||r.startsWith(`${t}-`))&&(n+=i);return n},v=async(e,t)=>{if(e===void 0)return null;let i=n.get(e)??await r.get(e)?.catch(()=>void 0);return i?_(i,t):null},y=async t=>{let n=t.split(`/`).filter(Boolean),r=n.pop()??``,i=await navigator.storage.getDirectory();for(let e of n)i=await i.getDirectoryHandle(e,{create:!0});let a=await i.getDirectoryHandle(r,{create:!0}),o=e=>e.values(),s=e;for await(let e of o(a))e.kind===`directory`&&qs.test(e.name)&&(s=Number(e.name));let c=await a.getDirectoryHandle(String(s),{create:!0}),l=/* @__PURE__ */ new Map;for await(let e of o(c))e.kind===`file`&&l.set(e.name,await e.getFile().then(e=>e.size,()=>s));return{parent:i,name:r,chunkBytes:s,dir:c,extents:l,handles:/* @__PURE__ */ new Map,opening:/* @__PURE__ */ new Map,dropping:/* @__PURE__ */ new Map}};return{chunkBytesOf:t=>d(t)?.chunkBytes??e,chunksOf:(e,t)=>{let n=d(e);if(!n)return[];let r=[];for(let[e,i]of n.extents){let n=Ks.exec(e);n&&Number(n[1])===t&&i>0&&r.push(Number(n[2]))}return r.sort((e,t)=>e-t)},footprint:()=>{let e=0;for(let t of n.values())e+=_(t);return e},usageOf:e=>v(i.get(e)),usageOfStorage:v,refusedFile:e=>a.get(e),drop:(e,t,n)=>{let r=d(e);if(!r)return Promise.resolve();let i=u(t,n),a=r.dropping.get(i);if(a)return a;r.extents.delete(i);let o=r.handles.get(i);r.handles.delete(i);try{o?.close()}catch{}let s=r.opening.get(i),c=(async()=>{s&&await s.then(e=>{r.handles.get(i)===e&&r.handles.delete(i);try{e.close()}catch{}},()=>{}),await r.dir.removeEntry(i).catch(()=>{})})();return r.dropping.set(i,c),c.then(()=>{r.dropping.get(i)===c&&r.dropping.delete(i)}),c},readChunk:async(e,t,n)=>{let r=d(e),i=u(t,n);if(!r?.extents.has(i))return/* @__PURE__ */ new Uint8Array;let a=await m(r,i),o=new Uint8Array(a.getSize());return a.read(o,{at:0}),o},onNewStorage:(e,t)=>{o.delete(e),a.delete(e),i.set(t,e);let c=Promise.resolve(s(e,()=>{},()=>y(t)));return r.set(e,c),c.then(t=>{r.get(e)===c&&(r.delete(e),n.set(e,t))})},onRemoveStorage:e=>{o.add(e),r.delete(e);let t=n.get(e);n.delete(e);for(let[t,n]of i)n===e&&i.delete(t);t&&g(t)},read:(e,t,n,r)=>s(e,()=>h(e,t,n,r),()=>f(e,i=>{let a=new Uint8Array(r),o=[];for(let s of p(i,t,n,r)){let t=()=>{if(!i.extents.has(s.name))return;let e=e=>{e.read(a.subarray(s.from,s.to),{at:s.at})},t=m(i,s.name);if(t instanceof Promise)return t.then(e);e(t)},n=c.get(`${e}/${s.name}`);if(n)o.push(Promise.allSettled([...n]).then(t));else{let e=t();e&&o.push(e)}}return o.length?Promise.all(o).then(()=>a):a})),write:(e,i,o,c)=>{let u=s(e,()=>h(e,i,o,c.length),()=>f(e,n=>{let r=[];for(let s of p(n,i,o,c.length)){let o=r=>{try{js(t,e,s.at+s.to-s.from-(n.extents.get(s.name)??0)),Ts(r,c.subarray(s.from,s.to),{at:s.at})}catch(t){As(t)&&a.set(e,i);try{n.extents.set(s.name,r.getSize())}catch{}throw t}let o=s.at+s.to-s.from;(n.extents.get(s.name)??0)<o&&n.extents.set(s.name,o)},l=m(n,s.name);l instanceof Promise?r.push(l.then(o)):o(l)}return r.length?Promise.all(r).then(()=>{}):void 0}));if(u instanceof Promise){let t=t=>{for(let{name:n}of p(t,i,o,c.length))l(e,n,u)},a=n.get(e);a?t(a):r.get(e)?.then(t,()=>{})}return u},check:async e=>{try{let t=n.get(e)??await r.get(e);return t&&_(t)>0?2:0}catch{return 2}},release:async e=>{let t=n.get(e);t&&g(t)},stop:async e=>{let t=n.get(e);t&&g(t)},deleteFiles:async e=>{o.add(e);let t=n.get(e)??await r.get(e)?.catch(()=>void 0);t&&(await Promise.all([...t.opening.values()].map(e=>e.catch(()=>{}))),g(t),t.extents.clear(),await t.parent.removeEntry(t.name,{recursive:!0}).catch(()=>{}))}}},Ys=[5e3,15e3,3e4,6e4,12e4,3e5],Xs=1e4,Zs=/* @__PURE__ */ new Set([2,3]),Qs=/* @__PURE__ */ new Set([1,7]),$s=e=>!!e&&e.paused&&!e.autoManaged,ec=(e=!0)=>{let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=e=>Ys[Math.min(e,Ys.length-1)],o=e=>{t.delete(e),n.delete(e),r.delete(e),i.delete(e)};return{hold:(e,t,n=Xs)=>i.set(e,t+n),observe:(s,c,l,u)=>{if(l){o(s);return}if(!c)return;let d=i.get(s);if(d!==void 0){if(u<d)return;i.delete(s)}let f=n.get(s);(!f||c.totalDone>f.totalDone)&&n.set(s,{totalDone:c.totalDone,at:u});let p=n.get(s).at;if(Qs.has(c.state))return;let m=t.get(s);if(c.error&&(r.set(s,c.error),m&&(m.message=c.error)),m&&u<m.graceUntil||c.paused&&c.queued)return;let h=c.paused?`stopped`:e&&Zs.has(c.state)&&c.numPeers===0&&c.downloadRate===0&&u-p>=12e4?`stalled`:null;if(!h){if(!m)return;m.healthySince??=u,u-m.healthySince>=6e4&&o(s);return}if(!m){t.set(s,{reason:h,attempt:0,retryAt:u+a(0),message:r.get(s),healthySince:null,graceUntil:0});return}m.reason=h,m.healthySince!==null&&(m.healthySince=null,m.retryAt=u+a(m.attempt))},due:e=>{let n=[];for(let[r,i]of t)i.healthySince!==null||e<i.retryAt||(i.attempt++,i.retryAt=e+a(i.attempt),i.graceUntil=e+Xs,n.push({handle:r,reason:i.reason}));return n},retryNow:e=>{for(let n of t.values())n.healthySince===null&&(n.attempt=0,n.retryAt=e)},retry:(e,n)=>{let r=t.get(e);r&&(r.attempt=0,r.retryAt=n,r.healthySince=null,r.graceUntil=0,i.delete(e))},state:e=>{let n=t.get(e);return!n||n.healthySince!==null?null:{reason:n.reason,attempt:n.attempt,retryAt:n.retryAt,message:n.message}},forget:o,retain:e=>{for(let a of[t,n,r,i])for(let t of[...a.keys()])e.has(t)||o(t)}}},tc=e=>!(e.flags&Yo.localConnection)||!!(e.source&Zo.incoming),nc=e=>e.transport,rc={total:0,byTransport:{}},ic=e=>{let t={},n=0;for(let r of e)for(let e of r){if(!tc(e)||e.connectionType!==0)continue;n+=1;let r=nc(e);t[r]=(t[r]??0)+1}return{total:n,byTransport:t}},ac={activeSeconds:0,seedingSeconds:0},oc=[`activeSeconds`,`seedingSeconds`,`downloaded`,`uploaded`,`wasted`],sc={activeSeconds:0,seedingSeconds:0,downloaded:0,uploaded:0,wasted:0},cc=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0,lc=(e,t)=>({activeSeconds:Math.max(0,cc(t.activeSeconds)-cc(e.activeSeconds)),seedingSeconds:Math.max(0,cc(t.seedingSeconds)-cc(e.seedingSeconds))}),uc=(e,t,n)=>{let r=lc(t,n);return{activeSeconds:cc(e?.activeSeconds)+r.activeSeconds,seedingSeconds:cc(e?.seedingSeconds)+r.seedingSeconds}},dc=(e,t)=>Object.fromEntries(oc.map(n=>[n,Math.max(0,cc(t[n])-cc(e[n]))])),fc=(e,t,n)=>{let r=dc(t,n);return Object.fromEntries(oc.map(t=>[t,cc(e?.[t])+r[t]]))},pc=(e,t)=>Object.fromEntries(oc.map(n=>[n,Math.max(cc(e?.[n]),cc(t?.[n]))])),mc=(e,t)=>t.activeSeconds-cc(e?.activeSeconds)>=30||t.seedingSeconds-cc(e?.seedingSeconds)>=30,hc=67108864,gc=e=>e>0?Math.min(1677721600,Math.floor(e/2)):0,_c=e=>!Number.isFinite(e)||e<=0?0:Math.min(1e9,Math.floor(e*.1)),vc=(e,t)=>!Number.isFinite(e)||e<=0?Math.max(0,t):Math.max(Math.min(.25*e,2e10),Math.max(0,t)),yc=({usedBytes:e,limitBytes:t,pendingBytes:n,refusedBytes:r,candidates:i})=>{if(!Number.isFinite(t)||t<=0||!Number.isFinite(e)||e<0)return!1;let a=t-e,o=bc(i);return a<Math.min(n,67108864)&&n>a+o||r>0&&r+67108864>a+o},bc=e=>e.reduce((e,t)=>e+Math.max(0,t.bytesOnDisk),0),xc=({usedBytes:e,limitBytes:t,candidates:n},r)=>!r||!(t>0)||!(e>=0)?1/0:t-e+bc(n)-gc(t),Sc=(e,t)=>e.usedAt-t.usedAt||(e.infoHash<t.infoHash?-1:+(e.infoHash>t.infoHash)),Cc=({usedBytes:e,limitBytes:t,pendingBytes:n,candidates:r})=>{if(!Number.isFinite(t)||t<=0||!Number.isFinite(e)||e<0)return[];let i=r.filter(e=>e.bytesOnDisk>0).sort(Sc);if(!i.length)return[];let a=[0];for(let e of i)a.push(a[a.length-1]+e.bytesOnDisk);let o=e=>{for(let t=0;t<=i.length;t++)if(e(t))return t;return-1},s=Math.max(0,n),c=t-e,l=o(e=>c+a[e]>=s+_c(t)),u=o(e=>c+a[e]>=s+hc),d=l>=0?l:Math.max(0,u),f=a[i.length],p=i.reduce((e,t)=>Math.max(e,t.bytesOnDisk),0),m=vc(t,p),h=o(e=>f-a[e]<=m);return i.slice(0,Math.max(d,h<0?i.length:h)).map(e=>e.infoHash)};var wc=8,Tc=2e4,Ec=e=>typeof e.values==`function`,Dc=async e=>{let t=0,n=0,r=async(e,i)=>{if(!(i>wc))for await(let a of e.values()){if(++n>Tc)return;if(Ec(a)){await r(a,i+1);continue}let e=await a.getFile().catch(()=>null);e&&(t+=e.size)}};try{return await r(e,0),t}catch{return null}},Oc=(e,t)=>{let n=e.usage;if(t===null||!Number.isFinite(t)||t<0)return n;if(n===void 0)return t;let r=e.usageDetails?.fileSystem;if(typeof r==`number`){let e=Math.max(0,n-r);return Math.max(n,t+e)}return Math.max(n,t)},kc,Ac,jc=(e,t,n)=>{if(e!==void 0)return n!==Ac&&(kc=void 0),Ac=n,kc=kc===void 0?e:Math.min(kc,e),Math.max(kc,t??0)},Mc=async e=>e.persisted?e.persisted().then(e=>e===!0).catch(()=>Ac):void 0,Nc={estimate:async()=>{let e=globalThis.navigator?.storage;if(!e?.estimate)return{};let t=await e.estimate(),[n,r]=await Promise.all([e.getDirectory?e.getDirectory().then(e=>Dc(e)).catch(()=>null):null,Mc(e)]),i=Oc(t,n);return{...t,usage:i,quota:jc(t.quota,i,r)}},persist:async()=>{let e=globalThis.navigator?.storage;if(!e?.persist)return!1;let t=await e.persist().catch(()=>!1);return await Mc(e)??null??t},persisted:()=>globalThis.navigator?.storage?.persisted?.()??Promise.resolve(!1),getDirectory:()=>{let e=globalThis.navigator?.storage;return e?.getDirectory?e.getDirectory():Promise.reject(/* @__PURE__ */ Error(`this browser has no origin private file system`))}};const Pc=/^(?:[0-9a-f]{40}|[0-9a-f]{64}|[a-z2-7]{32})$/i,Fc=({entries:e,listedHashes:t,claimedNames:n,attributable:r})=>e.filter(({name:e,kind:i})=>n.has(e)?!1:i===`directory`&&Pc.test(e)?!t.has(e.toLowerCase()):r).map(({name:e})=>e),Ic=async e=>{let t=[];for await(let n of e.values())t.push({name:n.name,kind:n.kind});return t},Lc=async(e,t)=>{let n=e;for(let e of t.split(`/`).filter(Boolean))n=n?await n.getDirectoryHandle(e).catch(()=>null):null;return n},Rc=async(e,t,n)=>{let r=await Lc(e,t);if(!r)return[];let i=[];for(let e of Fc({...n,entries:await Ic(r)}))try{await r.removeEntry(e,{recursive:!0}),i.push(e)}catch{}return i},zc=async e=>{let t=0;for(let{name:n,kind:r}of await Ic(e))r===`file`&&n.startsWith(`.ripple-probe-`)&&await e.removeEntry(n).then(()=>!0,()=>!1)&&t++;return t},Bc=/* @__PURE__ */ new Set([`export-start`,`export-chunk`,`import-start`,`add-trackers`,`start-many`,`torrent-detail`]),Vc=e=>e?`/dl/`+e:`/dl`,Hc=e=>`/cache/`+e,Uc=e=>!!e?.startsWith(`/cache/`),Wc=(e,t)=>!!t&&(e===Vc(t)||e===Hc(t)),Gc=(e,t)=>t&&(!e||e.ephemeral===!0),Kc=(e,t)=>{let{private:n,...r}=t,i=n===!0||e?.private===!0;return e?{...r,ephemeral:Gc(e,t.ephemeral===!0),addedAt:Math.min(e.addedAt,t.addedAt),lastUsedAt:Math.max(e.lastUsedAt??0,t.lastUsedAt??t.addedAt),savePath:e.savePath||t.savePath,rootEntry:t.rootEntry??e.rootEntry,name:t.name??e.name,size:t.size??e.size,files:t.files??e.files,format:t.format??e.format,pieceLength:t.pieceLength??e.pieceLength,downloadLimit:t.downloadLimit??e.downloadLimit,uploadLimit:t.uploadLimit??e.uploadLimit,activeSeconds:t.activeSeconds??e.activeSeconds,seedingSeconds:t.seedingSeconds??e.seedingSeconds,downloaded:t.downloaded??e.downloaded,uploaded:t.uploaded??e.uploaded,wasted:t.wasted??e.wasted,saveTo:t.saveTo??e.saveTo,wantedFiles:t.wantedFiles??e.wantedFiles,firstLast:t.firstLast??e.firstLast,created:t.created??e.created,...i?{private:!0}:{}}:i?{...r,private:!0}:r},qc=e=>({name:typeof e.name==`string`&&e.name?e.name:void 0,size:typeof e.size==`number`&&Number.isFinite(e.size)&&e.size>=0?e.size:void 0,files:Array.isArray(e.files)?e.files.filter(e=>!!e&&typeof e.name==`string`&&typeof e.size==`number`&&Number.isFinite(e.size)).slice(0,100):void 0}),Jc=`ripple:torrents`,Yc=`ripple:removed`,Xc=(...e)=>{let t=/* @__PURE__ */ new Map;for(let n of e)if(Array.isArray(n))for(let e of n)typeof e?.infoHash==`string`&&e.infoHash&&typeof e.removedAt==`number`&&Number.isFinite(e.removedAt)&&t.set(e.infoHash,Math.max(t.get(e.infoHash)??e.removedAt,e.removedAt));return[...t].map(([e,t])=>({infoHash:e,removedAt:t}))},Zc=e=>{let t=new Map(e.map(e=>[e.infoHash,e.removedAt]));return e=>{let n=t.get(e.infoHash);return n===void 0||(e.addedAt??0)>n}},Qc=(e,t,n)=>{let r=Zc(n),i=t.filter(e=>!!e&&r(e)),a=new Set(i.map(e=>e.infoHash));return{list:e.filter(e=>e.started!==!1||a.has(e.infoHash)||r(e)),incoming:i}},$c=e=>`ripple:resume:`+e,el=e=>`ripple:torrent:`+e,tl=e=>`ripple:thumb:`+e,nl=Vc(hs(`magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.torrent.eu.org%3A451&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F`)),U={formatMessage:(e,t)=>t?{message:e.id,values:t}:{message:e.id}},rl=e=>typeof e.getFile==`function`?e.getFile():Promise.resolve(e),il=e=>`/native/${e}`,al=e=>e===`/native`||!!e?.startsWith(`/native/`),ol=e=>`/source/${e}`,sl=e=>e===`/source`||!!e?.startsWith(`/source/`),cl=e=>al(e)||sl(e),ll=async(e,t)=>{let n=t.split(`/`).filter(Boolean),r=n.pop();if(!r)throw Error(`hybrid storage: empty file path`);let i=e;for(let e of n)i=await i.getDirectoryHandle(e);return(await i.getFileHandle(r)).getFile()},ul=(e,t)=>ll(e,t).catch(e=>{if(e?.name===`NotFoundError`)return null;throw e}),dl=e=>e.keys().next(),fl=async(e,t)=>{try{for(let{path:n,size:r,pad:i}of t){if(i||r<=0)continue;let t=await ul(e,n);if(!(t&&t.size>=r))return await dl(e),!0}return!1}catch{return!1}},pl=(e,t,n=()=>null,r=e)=>{let i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set,s=t=>o.has(t)?r:e,c=t=>Uc(t)?r:e,l=e=>{let n=t();if(!n)throw Error(`hybrid storage: no folder granted, cannot ${e}`);return n},u=async(e,t)=>{if(!e.handles)throw Error(`hybrid storage: ${e.savePath} has no source handles registered`);if(e.handles.length!==e.files.length)throw Error(`hybrid storage: ${e.savePath} has ${e.handles.length} handles for ${e.files.length} files`);if(t<0||t>=e.handles.length)throw Error(`hybrid storage: no source handle ${t} in ${e.savePath}`);let n=e.handles[t];return n?rl(n):null};return{usageOf:async e=>cl(e)?0:c(e).usageOf(e),usageOfStorage:async(e,t)=>i.has(e)||a.has(e)?null:s(e).usageOfStorage(e,t),refusedFile:e=>s(e).refusedFile(e),onNewStorage:(e,t,r)=>{if(sl(t)){a.set(e,{savePath:t,files:r,handles:n(t)});return}if(Uc(t)?o.add(e):o.delete(e),!al(t))return s(e).onNewStorage(e,t,r);i.set(e,{savePath:t,files:r})},onRemoveStorage:e=>{if(!a.delete(e)&&!i.delete(e))return s(e).onRemoveStorage(e)},read:(e,t,n,r)=>{let o=a.get(e);if(o)return(async()=>{let e=await u(o,t);if(!e)return new Uint8Array(r);let i=await e.slice(n,n+r).arrayBuffer();if(i.byteLength<r)throw Error(`hybrid storage: source file ${t} of ${o.savePath} ended early, wanted ${r} at ${n}, got ${i.byteLength}`);return new Uint8Array(i)})();let c=i.get(e);if(!c)return s(e).read(e,t,n,r);let d=c.files[t];if(!d)throw Error(`hybrid storage: no file ${t} in ${c.savePath}`);return(async()=>{let e=await(await ll(l(`read`),d.path)).slice(n,n+r).arrayBuffer();if(e.byteLength<r)throw Error(`hybrid storage: ${d.path} ended early, wanted ${r} at ${n}, got ${e.byteLength}`);return new Uint8Array(e)})()},write:(e,t,n,r)=>{let o=a.get(e);if(o)throw Error(`hybrid storage: ${o.savePath} is somebody's own files, refusing a write of ${r.length} at ${n} in file ${t}`);let c=i.get(e);if(!c)return s(e).write(e,t,n,r);throw Error(`hybrid storage: ${c.savePath} is read only, refusing a write of ${r.length} at ${n} in file ${t}`)},check:async e=>{if(a.get(e))return 2;let t=i.get(e);if(!t)return s(e).check(e);try{let e=l(`check`);for(let n of t.files){let t=await ul(e,n.path);if(t&&t.size>0)return 2}return await dl(e),0}catch{return 2}},deleteFiles:async(e,t)=>{if(!a.has(e)&&!i.get(e))return s(e).deleteFiles(e,t)},release:async e=>{!i.has(e)&&!a.has(e)&&await s(e).release(e)},stop:async e=>{!i.has(e)&&!a.has(e)&&await s(e).stop(e)}}},ml=(e,t,n)=>[Math.max(0,Math.floor(e.offset/t)),Math.min(n-1,Math.floor((e.offset+Math.max(0,e.size-1))/t))],hl=({files:e,pieceLength:t,numPieces:n,wanted:r,firstLast:i,windowBytes:a=4194304})=>{let o=r===void 0,s=new Set(r??[]),c=e=>o||s.has(e),l=new Uint8Array(n).fill(o?H.normal:H.skip);if(!o)for(let[r,i]of e.entries()){if(!c(r)||i.size<=0)continue;let[e,a]=ml(i,t,n);for(let t=e;t<=a;t++)l[t]=H.normal}if(i){let r=Math.max(1,Math.ceil(a/t));for(let[i,a]of e.entries()){if(!c(i)||a.size<=0)continue;let[e,o]=ml(a,t,n);for(let t=0;t<r;t++){let n=e+t,r=o-t;n<=o&&(l[n]=H.top),r>=e&&(l[r]=H.top)}}}return l},gl=({wanted:e,firstLast:t})=>e===void 0&&!t,_l=new TextEncoder;_l.encode(`i`),_l.encode(`e`),_l.encode(`l`),_l.encode(`d`),_l.encode(`:`);const vl=(e,t)=>{if(t>=e.length)throw Error(`truncated`);let n=e[t];if(n===105){let n=e.indexOf(101,t+1);if(n<0)throw Error(`unterminated integer`);return[Number(new TextDecoder().decode(e.subarray(t+1,n))),n+1]}if(n===108){let n=[],r=t+1;for(;r<e.length&&e[r]!==101;){let[t,i]=vl(e,r);n.push(t),r=i}if(r>=e.length)throw Error(`unterminated list`);return[n,r+1]}if(n===100){let n=/* @__PURE__ */ new Map,r=t+1;for(;r<e.length&&e[r]!==101;){let[t,i]=vl(e,r);if(!(t instanceof Uint8Array))throw Error(`dict key is not a string`);let[a,o]=vl(e,i);n.set(new TextDecoder().decode(t),a),r=o}if(r>=e.length)throw Error(`unterminated dict`);return[n,r+1]}let r=t,i=0,a=0;for(;r<e.length&&e[r]>=48&&e[r]<=57;)if(i=i*10+(e[r]-48),r+=1,a+=1,a>12)throw Error(`absurd string length`);if(a===0||e[r]!==58)throw Error(`not a bencode value`);let o=r+1,s=o+i;if(s>e.length)throw Error(`string runs past the end`);return[e.subarray(o,s),s]},yl=e=>{let t=e.get(`private`);return typeof t==`number`&&t!==0},bl=e=>{try{let[t]=vl(e,0),n=t instanceof Map?t.get(`info`):void 0;return n instanceof Map&&yl(n)}catch{return!1}},xl=e=>{if(e[0]!==100)return null;let t=1;for(;t<e.length&&e[t]!==101;){let[n,r]=vl(e,t),[,i]=vl(e,r);if(n instanceof Uint8Array&&new TextDecoder().decode(n)===`info`)return[r,i];t=i}return null},Sl=new TextEncoder,Cl=e=>{let t=Sl.encode(e),n=Sl.encode(`${t.length}:`),r=new Uint8Array(n.length+t.length);return r.set(n),r.set(t,n.length),r},wl=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},Tl=(e,{trackers:t=[],webSeeds:n=[]}={})=>{let r=[Sl.encode(`d`)];if(t.length){r.push(Cl(`announce`),Cl(t[0])),r.push(Cl(`announce-list`),Sl.encode(`l`));for(let e of t)r.push(Sl.encode(`l`),Cl(e),Sl.encode(`e`));r.push(Sl.encode(`e`))}if(r.push(Cl(`info`),e),n.length){r.push(Cl(`url-list`),Sl.encode(`l`));for(let e of n)r.push(Cl(e));r.push(Sl.encode(`e`))}return r.push(Sl.encode(`e`)),wl(r)},El=e=>({trackers:vs(e,`tr`),webSeeds:vs(e,`ws`)}),Dl=e=>{let t=xl(e);if(!t)return null;let[n,r]=t;return new Uint8Array(e.slice(n,r))},Ol=e=>{try{let t=Dl(e);if(!t)return!1;let[n]=vl(t,0);return n instanceof Map&&yl(n)}catch{return!1}},kl=e=>sl(e)?`source`:al(e)?`folder`:`browser`,Al=(e,t)=>{if(e===`source`){if(!t)throw Error(`a source-backed torrent needs its infohash to name its save path`);return ol(t)}return e===`folder`?t?il(t):`/dl`:Vc(t)},jl=`ripple:rate-limits`,Ml=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,Nl=e=>{let t=e??{};return{down:Ml(t.down)?t.down:0,up:Ml(t.up)?t.up:0}},Pl=`ripple:seeding-policy`,Fl={ratio:null,minutes:null},Il=e=>typeof e==`number`&&Number.isFinite(e)&&e>=.01&&e<=1e3,Ll=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=1&&e<=525600,Rl=e=>e.ratio!==null||e.minutes!==null,zl=e=>{if(!Il(e))return null;let t=Math.round(e*1e4)/1e4;return Il(t)?t:null},Bl=e=>{if(!e||typeof e!=`object`||Array.isArray(e))return Fl;let t=e;if(`mode`in t)return t.mode===`ratio`?{ratio:zl(t.ratio)??1,minutes:null}:t.mode===`duration`?{ratio:null,minutes:Ll(t.minutes)?t.minutes:60}:Fl;let n=zl(t.ratio),r=Ll(t.minutes)?t.minutes:null;return n===null&&r===null?Fl:{ratio:n,minutes:r}},Vl=(e,t)=>e.ratio===t.ratio&&e.minutes===t.minutes,Hl=(e,t)=>{if(e.ratio!==null){let n=t.downloaded>0&&(t.size<=0||t.downloaded>=t.size*.01)?t.downloaded:t.size;if(n>0&&t.uploaded/n>=e.ratio)return!0}return e.minutes!==null&&t.seedingSeconds>=e.minutes*60},Ul=[`tracker.openwebtorrent.com`,`tracker.webtorrent.dev`],Wl=Ul.map(e=>`wss://${e}`);[...Ul];var Gl=/* @__PURE__ */ t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AddressError=void 0,e.AddressError=class extends Error{constructor(e,t){super(e),this.name=`AddressError`,this.parseMessage=t}}})),Kl=/* @__PURE__ */ t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isInSubnet=n,e.isCorrect=r,e.prefixLengthFromMask=i,e.numberToPaddedHex=a,e.stringToPaddedHex=o,e.testBit=s;let t=Gl();function n(e){return this.subnetMask<e.subnetMask?!1:this.mask(e.subnetMask)===e.mask()}function r(e){return function(){return this.addressMinusSuffix===this.correctForm()?this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask):!1}}function i(e,n){let r=e.toString(2).padStart(n,`0`);if(r.length>n)throw new t.AddressError(`Invalid subnet mask.`);let i=r.indexOf(`0`);if(i===-1)return n;if(r.slice(i).includes(`1`))throw new t.AddressError(`Invalid subnet mask.`);return i}function a(e){return e.toString(16).padStart(2,`0`)}function o(e){return a(parseInt(e,10))}function s(e,t){let{length:n}=e;if(t>n)return!1;let r=n-t;return e.substring(r,r+1)===`1`}})),ql=/* @__PURE__ */ t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RE_SUBNET_STRING=e.RE_ADDRESS=e.GROUPS=e.BITS=void 0,e.BITS=32,e.GROUPS=4,e.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g,e.RE_SUBNET_STRING=/\/\d{1,2}$/})),Jl=/* @__PURE__ */ t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.Address4=void 0;let i=r(Kl()),a=r(ql()),o=Gl(),s=i.isCorrect(a.BITS);var c=class e{constructor(e){this.groups=a.GROUPS,this.parsedAddress=[],this.parsedSubnet=``,this.subnet=`/32`,this.subnetMask=32,this.v4=!0,this.isCorrect=s,this.isInSubnet=i.isInSubnet,this.address=e;let t=a.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace(`/`,``),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>a.BITS)throw new o.AddressError(`Invalid subnet mask.`);e=e.replace(a.RE_SUBNET_STRING,``)}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(t){try{return new e(t),!0}catch{return!1}}parse(e){let t=e.split(`.`);if(!e.match(a.RE_ADDRESS))throw new o.AddressError(`Invalid IPv4 address.`);return t}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(`.`)}static fromAddressAndMask(t,n){let r=i.prefixLengthFromMask(new e(n).bigInt(),a.BITS);return new e(`${t}/${r}`)}static fromAddressAndWildcardMask(t,n){let r=new e(n).bigInt()^(BigInt(1)<<BigInt(a.BITS))-BigInt(1),o=i.prefixLengthFromMask(r,a.BITS);return new e(`${t}/${o}`)}static fromWildcard(t){let n=t.split(`.`);if(n.length!==a.GROUPS)throw new o.AddressError(`Wildcard pattern must have 4 octets`);let r=-1;for(let e=0;e<n.length;e++)if(n[e]===`*`)r===-1&&(r=e);else if(r!==-1)throw new o.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");let i=r===-1?0:n.length-r,s=n.map(e=>e===`*`?`0`:e),c=a.BITS-i*8;return new e(`${s.join(`.`)}/${c}`)}static fromHex(t){let n=t.replace(/:/g,``);if(!/^[0-9a-fA-F]{8}$/.test(n))throw new o.AddressError(`IPv4 hex must be exactly 8 hex digits`);let r=[];for(let e=0;e<8;e+=2)r.push(parseInt(n.slice(e,e+2),16));return new e(r.join(`.`))}static fromInteger(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new o.AddressError(`IPv4 integer must be in the range 0 to 2**32 - 1`);return e.fromHex(t.toString(16).padStart(8,`0`))}static fromArpa(t){let n=t.replace(/(\.in-addr\.arpa)?\.$/,``).split(`.`).reverse().join(`.`);return new e(n)}toHex(){return this.parsedAddress.map(e=>i.stringToPaddedHex(e)).join(`:`)}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],t=0;for(;t<a.GROUPS;t+=2)e.push(`${i.stringToPaddedHex(this.parsedAddress[t])}${i.stringToPaddedHex(this.parsedAddress[t+1])}`);return e.join(`:`)}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>i.stringToPaddedHex(e)).join(``)}`)}_startAddress(){return BigInt(`0b${this.mask()+`0`.repeat(a.BITS-this.subnetMask)}`)}startAddress(){return e.fromBigInt(this._startAddress())}startAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._startAddress()+t)}_endAddress(){return BigInt(`0b${this.mask()+`1`.repeat(a.BITS-this.subnetMask)}`)}endAddress(){return e.fromBigInt(this._endAddress())}endAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._endAddress()-t)}subnetMaskAddress(){return e.fromBigInt(BigInt(`0b${`1`.repeat(this.subnetMask)}${`0`.repeat(a.BITS-this.subnetMask)}`))}wildcardMask(){return e.fromBigInt(BigInt(`0b${`0`.repeat(this.subnetMask)}${`1`.repeat(a.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(t){if(t<0n||t>4294967295n)throw new o.AddressError(`IPv4 BigInt must be in the range 0 to 2**32 - 1`);return e.fromHex(t.toString(16).padStart(8,`0`))}static fromByteArray(e){if(e.length!==4)throw new o.AddressError(`IPv4 addresses require exactly 4 bytes`);for(let t=0;t<e.length;t++)if(!Number.isInteger(e[t])||e[t]<0||e[t]>255)throw new o.AddressError(`All bytes must be integers between 0 and 255`);return this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(t){if(t.length!==4)throw new o.AddressError(`IPv4 addresses require exactly 4 bytes`);let n=t.join(`.`);return new e(n)}mask(e){return e===void 0&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||={};let t=this.correctForm().split(`.`).reverse().join(`.`);return e.omitSuffix?t:`${t}.in-addr.arpa.`}isMulticast(){return this.isInSubnet(l)}isPrivate(){return u.some(e=>this.isInSubnet(e))}isLoopback(){return this.isInSubnet(d)}isLinkLocal(){return this.isInSubnet(f)}isUnspecified(){return this.isInSubnet(p)}isBroadcast(){return this.isInSubnet(m)}isCGNAT(){return this.isInSubnet(h)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(a.BITS,`0`)),this._binaryZeroPad}groupForV6(){let e=this.parsedAddress;return this.address.replace(a.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(`.`)}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(`.`)}</span>`)}};e.Address4=c;let l=new c(`224.0.0.0/4`),u=[new c(`10.0.0.0/8`),new c(`172.16.0.0/12`),new c(`192.168.0.0/16`)],d=new c(`127.0.0.0/8`),f=new c(`169.254.0.0/16`),p=new c(`0.0.0.0/32`),m=new c(`255.255.255.255/32`),h=new c(`100.64.0.0/10`)})),Yl=/* @__PURE__ */ t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RE_URL_WITH_PORT=e.RE_URL=e.RE_ZONE_STRING=e.RE_SUBNET_STRING=e.RE_BAD_ADDRESS=e.RE_BAD_CHARACTERS=e.TYPES=e.SCOPES=e.GROUPS=e.BITS=void 0,e.BITS=128,e.GROUPS=8,e.SCOPES={0:`Reserved`,1:`Interface local`,2:`Link local`,4:`Admin local`,5:`Site local`,8:`Organization local`,14:`Global`,15:`Reserved`},e.TYPES={"ff01::1/128":`Multicast (All nodes on this interface)`,"ff01::2/128":`Multicast (All routers on this interface)`,"ff02::1/128":`Multicast (All nodes on this link)`,"ff02::2/128":`Multicast (All routers on this link)`,"ff05::2/128":`Multicast (All routers in this site)`,"ff02::5/128":`Multicast (OSPFv3 AllSPF routers)`,"ff02::6/128":`Multicast (OSPFv3 AllDR routers)`,"ff02::9/128":`Multicast (RIP routers)`,"ff02::a/128":`Multicast (EIGRP routers)`,"ff02::d/128":`Multicast (PIM routers)`,"ff02::16/128":`Multicast (MLDv2 reports)`,"ff01::fb/128":`Multicast (mDNSv6)`,"ff02::fb/128":`Multicast (mDNSv6)`,"ff05::fb/128":`Multicast (mDNSv6)`,"ff02::1:2/128":`Multicast (All DHCP servers and relay agents on this link)`,"ff05::1:2/128":`Multicast (All DHCP servers and relay agents in this site)`,"ff02::1:3/128":`Multicast (All DHCP servers on this link)`,"ff05::1:3/128":`Multicast (All DHCP servers in this site)`,"::/128":`Unspecified`,"::1/128":`Loopback`,"ff00::/8":`Multicast`,"fe80::/10":`Link-local unicast`,"fc00::/7":`Unique local`,"2002::/16":`6to4`,"2001:db8::/32":`Documentation`,"64:ff9b::/96":`NAT64 (well-known)`,"64:ff9b:1::/48":`NAT64 (local-use)`},e.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,e.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,e.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,e.RE_ZONE_STRING=/%.*$/,e.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/,e.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/})),Xl=/* @__PURE__ */ t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.escapeHtml=t,e.spanAllZeroes=n,e.spanAll=r,e.spanLeadingZeroes=a,e.simpleGroup=o;function t(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function n(e){return t(e).replace(/(0+)/g,`<span class="zero">$1</span>`)}function r(e,r=0){return e.split(``).map((e,i)=>`<span class="digit value-${t(e)} position-${i+r}">${n(e)}</span>`).join(``)}function i(e){return t(e).replace(/^(0+)/,`<span class="zero">$1</span>`)}function a(e){return e.split(`:`).map(e=>i(e)).join(`:`)}function o(e,t=0){return e.split(`:`).map((e,n)=>/group-v4/.test(e)?e:`<span class="hover-group group-${n+t}">${i(e)}</span>`)}})),Zl=/* @__PURE__ */ t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.ADDRESS_BOUNDARY=void 0,e.groupPossibilities=a,e.padGroup=o,e.simpleRegularExpression=s,e.possibleElisions=c;let i=r(Yl());function a(e){return`(${e.join(`|`)})`}function o(e){return e.length<4?`0{0,${4-e.length}}${e}`:e}e.ADDRESS_BOUNDARY=`[^A-Fa-f0-9:]`;function s(e){let t=[];e.forEach((e,n)=>{parseInt(e,16)===0&&t.push(n)});let n=t.map(t=>e.map((e,n)=>{if(n===t){let t=n===0||n===i.GROUPS-1?`:`:``;return a([o(e),t])}return o(e)}).join(`:`));return n.push(e.map(o).join(`:`)),a(n)}function c(e,t,n){let r=t?``:`:`,i=n?``:`:`,o=[];!t&&!n&&o.push(`::`),t&&n&&o.push(``),(n&&!t||!n&&t)&&o.push(`:`),o.push(`${r}(:0{1,4}){1,${e-1}}`),o.push(`(0{1,4}:){1,${e-1}}${i}`),o.push(`(0{1,4}:){${e-1}}0{1,4}`);for(let t=1;t<e-1;t++)for(let n=1;n<e-t;n++)o.push(`(0{1,4}:){${n}}:(0{1,4}:){${e-n-t-1}}0{1,4}`);return a(o)}})),Ql=/* @__PURE__ */ t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.Address6=void 0;let i=r(Kl()),a=r(ql()),o=r(Yl()),s=r(Xl()),c=Jl(),l=Zl(),u=Gl(),d=Kl(),f=i.isCorrect(o.BITS);function p(e){if(!e)throw Error(`Assertion failed.`)}function m(e){let t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,`$1,$2`);return e}function h(e){return e=e.replace(/^(0{1,})([1-9]+)$/,`<span class="parse-error">$1</span>$2`),e=e.replace(/^(0{1,})(0)$/,`<span class="parse-error">$1</span>$2`),e}function g(e,t){let n=[],r=[],i=0;for(;i<e.length;i++)i<t[0]?n.push(e[i]):i>t[1]&&r.push(e[i]);return n.concat([`compact`]).concat(r)}function _(e){return parseInt(e,16).toString(16).padStart(4,`0`)}function v(e){return e&255}var y=class e{constructor(e,t){this.addressMinusSuffix=``,this.parsedSubnet=``,this.subnet=`/128`,this.subnetMask=128,this.v4=!1,this.zone=``,this.isInSubnet=i.isInSubnet,this.isCorrect=f,this.groups=t===void 0?o.GROUPS:t,this.address=e;let n=o.RE_SUBNET_STRING.exec(e);if(n){if(this.parsedSubnet=n[0].replace(`/`,``),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>o.BITS)throw new u.AddressError(`Invalid subnet mask.`);e=e.replace(o.RE_SUBNET_STRING,``)}else if(/\//.test(e))throw new u.AddressError(`Invalid subnet mask.`);let r=o.RE_ZONE_STRING.exec(e);r&&(this.zone=r[0],e=e.replace(o.RE_ZONE_STRING,``)),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(t){try{return new e(t),!0}catch{return!1}}static fromBigInt(t){if(t<0n||t>(1n<<BigInt(o.BITS))-1n)throw new u.AddressError(`IPv6 BigInt must be in the range 0 to 2**128 - 1`);let n=t.toString(16).padStart(32,`0`),r=[];for(let e=0;e<o.GROUPS;e++)r.push(n.slice(e*4,(e+1)*4));return new e(r.join(`:`))}static fromURL(t){let n,r=null,i;if(t.indexOf(`[`)!==-1&&t.indexOf(`]:`)!==-1){if(i=o.RE_URL_WITH_PORT.exec(t),i===null)return{error:`failed to parse address with port`,address:null,port:null};n=i[1],r=i[2]}else if(t.indexOf(`/`)!==-1){if(t=t.replace(/^[a-z0-9]+:\/\//,``),i=o.RE_URL.exec(t),i===null)return{error:`failed to parse address from URL`,address:null,port:null};n=i[1]}else n=t;return r?(r=parseInt(r,10),(r<0||r>65536)&&(r=null)):r=null,{address:new e(n),port:r}}static fromAddressAndMask(t,n){let r=i.prefixLengthFromMask(new e(n).bigInt(),o.BITS);return new e(`${t}/${r}`)}static fromAddressAndWildcardMask(t,n){let r=new e(n).bigInt()^(BigInt(1)<<BigInt(o.BITS))-BigInt(1),a=i.prefixLengthFromMask(r,o.BITS);return new e(`${t}/${a}`)}static fromWildcard(t){if(t.includes(`%`)||t.includes(`/`))throw new u.AddressError(`Wildcard pattern must not include a zone or CIDR suffix`);let n=t.split(`::`);if(n.length>2)throw new u.AddressError(`Wildcard pattern cannot contain more than one '::'`);let r;if(n.length===2){let e=n[0]===``?[]:n[0].split(`:`),t=n[1]===``?[]:n[1].split(`:`),i=o.GROUPS-e.length-t.length;if(i<1)throw new u.AddressError(`Wildcard pattern with '::' has too many groups`);r=[...e,...Array(i).fill(`0`),...t]}else r=t.split(`:`);if(r.length!==o.GROUPS)throw new u.AddressError(`Wildcard pattern must have 8 groups`);let i=-1;for(let e=0;e<r.length;e++)if(r[e]===`*`)i===-1&&(i=e);else if(i!==-1)throw new u.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");let a=i===-1?0:r.length-i,s=r.map(e=>e===`*`?`0`:e),c=o.BITS-a*16;return new e(`${s.join(`:`)}/${c}`)}static fromAddress4(t){let n=new c.Address4(t),r=o.BITS-(a.BITS-n.subnetMask);return new e(`::ffff:${n.correctForm()}/${r}`)}static fromArpa(t){let n=t.replace(/(\.ip6\.arpa)?\.$/,``);if(n.length!==63)throw new u.AddressError(`Invalid 'ip6.arpa' form.`);let r=n.split(`.`).reverse();for(let e=7;e>0;e--){let t=e*4;r.splice(t,0,`:`)}return n=r.join(``),new e(n)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,`-`)}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){let t=o.BITS-this.subnetMask-Math.abs(e-o.BITS);return t<0?`0`:m((BigInt(`2`)**BigInt(t)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+`0`.repeat(o.BITS-this.subnetMask)}`)}startAddress(){return e.fromBigInt(this._startAddress())}startAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._startAddress()+t)}_endAddress(){return BigInt(`0b${this.mask()+`1`.repeat(o.BITS-this.subnetMask)}`)}endAddress(){return e.fromBigInt(this._endAddress())}endAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._endAddress()-t)}subnetMaskAddress(){return e.fromBigInt(BigInt(`0b${`1`.repeat(this.subnetMask)}${`0`.repeat(o.BITS-this.subnetMask)}`))}wildcardMask(){return e.fromBigInt(BigInt(`0b${`0`.repeat(this.subnetMask)}${`1`.repeat(o.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let e=this.getType();return e===`Multicast`||e.startsWith(`Multicast `)?o.SCOPES[parseInt(this.getBits(12,16).toString(10),10)]||`Unknown`:e===`Link-local unicast`||e===`Loopback`?`Link local`:e===`Unspecified`?`Unknown`:`Global`}getType(){for(let e=0;e<b.length;e++){let t=b[e];if(this.isInSubnet(t[0]))return t[1]}return`Global unicast`}getBits(e,t){return BigInt(`0b${this.getBitsBase2(e,t)}`)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){let n=t-e;if(n%4!=0)throw Error(`Length of bits to retrieve must be divisible by four`);return this.getBits(e,t).toString(16).padStart(n/4,`0`)}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,o.BITS)}reverseForm(e){e||={};let t=Math.floor(this.subnetMask/4),n=this.canonicalForm().replace(/:/g,``).split(``).slice(0,t).reverse().join(`.`);return t>0?e.omitSuffix?n:`${n}.ip6.arpa.`:e.omitSuffix?``:`ip6.arpa.`}correctForm(){let e,t=[],n=0,r=[];for(e=0;e<this.parsedAddress.length;e++){let t=parseInt(this.parsedAddress[e],16);t===0&&n++,t!==0&&n>0&&(n>1&&r.push([e-n,e-1]),n=0)}n>1&&r.push([this.parsedAddress.length-n,this.parsedAddress.length-1]);let i=r.map(e=>e[1]-e[0]+1);if(r.length>0){let e=i.indexOf(Math.max(...i));t=g(this.parsedAddress,r[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)t[e]!==`compact`&&(t[e]=parseInt(t[e],16).toString(16));let a=t.join(`:`);return a=a.replace(/^compact$/,`::`),a=a.replace(/(^compact)|(compact$)/,`:`),a=a.replace(/compact/,``),a}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(o.BITS,`0`)),this._binaryZeroPad}parse4in6(e){if(e.indexOf(`.`)===-1)return e;let t=e.split(`:`),n=t.slice(-1)[0].match(a.RE_ADDRESS);if(n){this.parsedAddress4=n[0],this.address4=new c.Address4(this.parsedAddress4);for(let e=0;e<this.address4.groups;e++)if(/^0[0-9]+/.test(this.address4.parsedAddress[e])){let e=this.address4.parsedAddress.map(h).join(`.`),n=t.slice(0,-1).map(s.escapeHtml).join(`:`),r=t.length>1?`:`:``;throw new u.AddressError(`IPv4 addresses can't have leading zeroes.`,`${n}${r}${e}`)}this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(`:`)}return e}parse(e){e=this.parse4in6(e);let t=e.match(o.RE_BAD_CHARACTERS);if(t)throw new u.AddressError(`Bad character${t.length>1?`s`:``} detected in address: ${t.join(``)}`,e.replace(o.RE_BAD_CHARACTERS,`<span class="parse-error">$1</span>`));let n=e.match(o.RE_BAD_ADDRESS);if(n)throw new u.AddressError(`Address failed regex: ${n.join(``)}`,e.replace(o.RE_BAD_ADDRESS,`<span class="parse-error">$1</span>`));let r=[],i=e.split(`::`);if(i.length===2){let e=i[0].split(`:`),t=i[1].split(`:`);e.length===1&&e[0]===``&&(e=[]),t.length===1&&t[0]===``&&(t=[]);let n=this.groups-(e.length+t.length);if(!n)throw new u.AddressError(`Error parsing groups`);this.elidedGroups=n,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,r=r.concat(e);for(let e=0;e<n;e++)r.push(`0`);r=r.concat(t)}else if(i.length===1)r=e.split(`:`),this.elidedGroups=0;else throw new u.AddressError(`Too many :: groups found`);if(r=r.map(e=>parseInt(e,16).toString(16)),r.length!==this.groups)throw new u.AddressError(`Incorrect number of groups found`);return r}canonicalForm(){return this.parsedAddress.map(_).join(`:`)}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,`0`)).join(`:`)}bigInt(){return BigInt(`0x${this.parsedAddress.map(_).join(``)}`)}to4(){let e=this.binaryZeroPad().split(``);return c.Address4.fromHex(BigInt(`0b${e.slice(96,128).join(``)}`).toString(16).padStart(8,`0`))}to4in6(){let t=this.to4(),n=new e(this.parsedAddress.slice(0,6).join(`:`),6).correctForm(),r=``;return/:$/.test(n)||(r=`:`),n+r+t.address}inspectTeredo(){let e=this.getBitsBase16(0,32),t=(this.getBits(80,96)^BigInt(`0xffff`)).toString(),n=c.Address4.fromHex(this.getBitsBase16(32,64)),r=this.getBits(96,128),i=c.Address4.fromHex((r^BigInt(`0xffffffff`)).toString(16).padStart(8,`0`)),a=this.getBitsBase2(64,80),o=(0,d.testBit)(a,15),s=(0,d.testBit)(a,14),l=(0,d.testBit)(a,8),u=(0,d.testBit)(a,9),f=BigInt(`0b${a.slice(2,6)+a.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:n.address,client4:i.address,flags:a,coneNat:o,microsoft:{reserved:s,universalLocal:u,groupIndividual:l,nonce:f},udpPort:t}}inspect6to4(){let e=this.getBitsBase16(0,16),t=c.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:t.address}}to6to4(){if(!this.is4())return null;let t=[`2002`,this.getBitsBase16(96,112),this.getBitsBase16(112,128),``,`/16`].join(`:`);return new e(t)}static fromAddress4Nat64(t,n=`64:ff9b::/96`){let r=new c.Address4(t),i=new e(n),a=i.subnetMask;if(a!==32&&a!==40&&a!==48&&a!==56&&a!==64&&a!==96)throw new u.AddressError(`NAT64 prefix length must be 32, 40, 48, 56, 64, or 96`);let o=i.binaryZeroPad(),s=r.binaryZeroPad(),l;if(a===96)l=o.slice(0,96)+s;else{let e=64-a;l=o.slice(0,a)+s.slice(0,e)+`00000000`+s.slice(e)+`0`.repeat(56-(32-e))}let d=BigInt(`0b${l}`).toString(16).padStart(32,`0`),f=[];for(let e=0;e<8;e++)f.push(d.slice(e*4,(e+1)*4));return new e(f.join(`:`))}toAddress4Nat64(t=`64:ff9b::/96`){let n=new e(t),r=n.subnetMask;if(r!==32&&r!==40&&r!==48&&r!==56&&r!==64&&r!==96)throw new u.AddressError(`NAT64 prefix length must be 32, 40, 48, 56, 64, or 96`);if(!this.isInSubnet(n))return null;let i=this.binaryZeroPad(),a;if(r===96)a=i.slice(96,128);else{let e=64-r;a=i.slice(r,r+e)+i.slice(72,72+(32-e))}let o=[];for(let e=0;e<4;e++)o.push(parseInt(a.slice(e*8,(e+1)*8),2).toString());return new c.Address4(o.join(`.`))}toByteArray(){let e=this.bigInt().toString(16),t=`${`0`.repeat(e.length%2)}${e}`,n=[];for(let e=0,r=t.length;e<r;e+=2)n.push(parseInt(t.substring(e,e+2),16));return n}toUnsignedByteArray(){return this.toByteArray().map(v)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(v))}static fromUnsignedByteArray(t){let n=BigInt(`256`),r=BigInt(`0`),i=BigInt(`1`);for(let e=t.length-1;e>=0;e--)r+=i*BigInt(t[e].toString(10)),i*=n;return e.fromBigInt(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){return this.getBitsBase2(0,64)===`1111111010000000000000000000000000000000000000000000000000000000`}isMulticast(){let e=this.getType();return e===`Multicast`||e.startsWith(`Multicast `)}is4(){return this.v4}isMapped4(){return this.isInSubnet(T)}isTeredo(){return this.isInSubnet(x)}is6to4(){return this.isInSubnet(S)}isLoopback(){return this.getType()===`Loopback`}isULA(){return this.isInSubnet(C)}isUnspecified(){return this.getType()===`Unspecified`}isDocumentation(){return this.isInSubnet(w)}href(e){return e=e===void 0?``:`:${e}`,`http://[${this.correctForm()}]${e}/`}link(e){e||={},e.className===void 0&&(e.className=``),e.prefix===void 0&&(e.prefix=`/#address=`),e.v4===void 0&&(e.v4=!1);let t=this.correctForm;e.v4&&(t=this.to4in6);let n=t.call(this),r=s.escapeHtml(`${e.prefix}${n}`),i=s.escapeHtml(n);return e.className?`<a href="${r}" class="${s.escapeHtml(e.className)}">${i}</a>`:`<a href="${r}">${i}</a>`}group(){if(this.elidedGroups===0)return s.simpleGroup(this.addressMinusSuffix).join(`:`);p(typeof this.elidedGroups==`number`),p(typeof this.elisionBegin==`number`);let e=[],[t,n]=this.addressMinusSuffix.split(`::`);t.length?e.push(...s.simpleGroup(t)):e.push(``);let r=[`hover-group`];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)r.push(`group-${e}`);return e.push(`<span class="${r.join(` `)}"></span>`),n.length?e.push(...s.simpleGroup(n,this.elisionEnd)):e.push(``),this.is4()&&(p(this.address4 instanceof c.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(`:`)}regularExpressionString(t=!1){let n=[],r=new e(this.correctForm());if(r.elidedGroups===0)n.push((0,l.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===o.GROUPS)n.push((0,l.possibleElisions)(o.GROUPS));else{let e=r.address.split(`::`);e[0].length&&n.push((0,l.simpleRegularExpression)(e[0].split(`:`))),p(typeof r.elidedGroups==`number`),n.push((0,l.possibleElisions)(r.elidedGroups,e[0].length!==0,e[1].length!==0)),e[1].length&&n.push((0,l.simpleRegularExpression)(e[1].split(`:`))),n=[n.join(`:`)]}return t||(n=[`(?=^|`,l.ADDRESS_BOUNDARY,`|[^\\w\\:])(`,...n,`)(?=[^\\w\\:]|`,l.ADDRESS_BOUNDARY,`|$)`]),n.join(``)}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),`i`)}};e.Address6=y;let b=Object.keys(o.TYPES).map(e=>[new y(e),o.TYPES[e]]),x=new y(`2001::/32`),S=new y(`2002::/16`),C=new y(`fc00::/7`),w=new y(`2001:db8::/32`),T=new y(`::ffff:0:0/96`)})),$l=(/* @__PURE__ */ t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;var i=Jl();Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return i.Address4}});var a=Ql();Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return a.Address6}});var o=Gl();Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}}),e.v6={helpers:r(Xl())}})))(),eu=new TextEncoder,tu=e=>$l.Address4.isValid(e),nu=e=>$l.Address6.isValid(e),ru=e=>tu(e)?4:nu(e)?6:0,iu=(...e)=>{if(typeof e[0]==`string`)throw Error(`FKN WebVPN does not support IPC connections`);let t=typeof e.at(-1)==`function`?e.at(-1):void 0;return e[0]&&typeof e[0]==`object`?{...e[0],callback:t}:{port:typeof e[0]==`function`?0:e[0]??0,host:typeof e[1]==`string`?e[1]:void 0,callback:t}},au=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=typeof e[0]==`function`?0:e[0]??0,r=typeof e[1]==`string`?e[1]:void 0;return typeof e[0]==`object`?{...e[0],address:e[0].address??r,port:e[0].port??0,callback:t}:{address:r,port:n,callback:t}},ou=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=e[0];if(typeof e[2]==`number`)return{message:n,hasRange:!0,offset:e[1],length:e[2],port:typeof e[3]==`number`?e[3]:0,address:typeof e[4]==`string`?e[4]:void 0,callback:t};{let r=typeof e[1]==`number`?e[1]:0,i=typeof e[2]==`string`?e[2]:void 0;return{message:n,hasRange:!1,offset:0,length:n.length,port:r,address:i,callback:t}}},su=/* @__PURE__ */ new Map,cu=e=>{su.set(e,(su.get(e)??0)+1);let t=!1;return()=>{t||(t=!0,su.set(e,Math.max(0,(su.get(e)??1)-1)))}},lu=`RelayUnavailableError`,uu=`this FKN page cannot choose a relay; reload the app to load the current one`,du=`fkn-proxy`,fu=`fkn-proxy.`,pu=e=>Object.assign(Error(e),{name:lu}),mu=(e,t)=>{if(typeof e.relay?.resolve!=`function`)throw pu(`${t}: ${uu}`)},hu=`webvpn-udp-port-ack`,gu=`read ECONNRESET`,_u=()=>Object.assign(/* @__PURE__ */ Error(gu),{code:`ECONNRESET`,errno:-104,syscall:`read`}),vu={ECONNREFUSED:-111,ETIMEDOUT:-110,EHOSTUNREACH:-113,ENETUNREACH:-101},yu=(e,t,n)=>{let r=e===`ENETUNREACH`?` - Local (${t.includes(`:`)?`::`:`0.0.0.0`}:0)`:``;return Object.assign(/* @__PURE__ */ Error(`connect ${e} ${t}:${n}${r}`),{errno:vu[e],code:e,syscall:`connect`,address:t,port:n})},bu=e=>Object.assign(/* @__PURE__ */ Error(`getaddrinfo ENOTFOUND ${e}`),{errno:-3008,code:`ENOTFOUND`,syscall:`getaddrinfo`,hostname:e}),xu=/^connect (ECONNREFUSED|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH) (\S+):(\d+)(?: - Local \(\S+\))?$/,Su=/^getaddrinfo ENOTFOUND (\S+)$/,Cu=e=>{let t=e?.message;if(typeof t!=`string`)return e;if(t===`read ECONNRESET`)return _u();let n=xu.exec(t);if(n)return yu(n[1],n[2],Number(n[3]));let r=Su.exec(t);return r?bu(r[1]):e},wu=/* @__PURE__ */ t(((e,t)=>{var n=typeof Reflect==`object`?Reflect:null,r=n&&typeof n.apply==`function`?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},i=n&&typeof n.ownKeys==`function`?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function a(e){console&&console.warn&&console.warn(e)}var o=Number.isNaN||function(e){return e!==e};function s(){s.init.call(this)}t.exports=s,t.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function l(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);c=e}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function u(e){return e._maxListeners===void 0?s.defaultMaxListeners:e._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=/* @__PURE__ */ Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)r(c,this,t);else for(var l=c.length,u=g(c,l),n=0;n<l;++n)r(u[n],this,t);return!0};function d(e,t,n,r){var i,o,s;if(l(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),s=o[t]),s===void 0)s=o[t]=n,++e._eventsCount;else if(typeof s==`function`?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),i=u(e),i>0&&s.length>i&&!s.warned){s.warned=!0;var c=/* @__PURE__ */ Error(`Possible EventEmitter memory leak detected. `+s.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);c.name=`MaxListenersExceededWarning`,c.emitter=e,c.type=t,c.count=s.length,a(c)}return e}s.prototype.addListener=function(e,t){return d(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return d(this,e,t,!0)};function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=f.bind(r);return i.listener=n,r.wrapFn=i,i}s.prototype.once=function(e,t){return l(t),this.on(e,p(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,p(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,a,o;if(l(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():_(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function m(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?v(i):g(i,i.length)}s.prototype.listeners=function(e){return m(this,e,!0)},s.prototype.rawListeners=function(e){return m(this,e,!1)},s.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h;function h(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]};function g(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function _(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function v(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function y(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}x(e,t,a,{once:!0}),t!==`error`&&b(e,i,{once:!0})})}function b(e,t,n){typeof e.on==`function`&&x(e,`error`,t,n)}function x(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}})),Tu=/* @__PURE__ */ t(((e,t)=>{t.exports=typeof Object.create==`function`?function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Eu=/* @__PURE__ */ t(((e,t)=>{t.exports=wu().EventEmitter})),Du=/* @__PURE__ */ t((e=>{e.byteLength=c,e.toByteArray=u,e.fromByteArray=p;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e){var t=s(e),n=t[0],r=t[1];return(n+r)*3/4-r}function l(e,t,n){return(t+n)*3/4-n}function u(e){for(var t,i=s(e),a=i[0],o=i[1],c=new r(l(e,a,o)),u=0,d=o>0?a-4:a,f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,c[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,c[u++]=t>>8&255,c[u++]=t&255),c}function d(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[e&63]}function f(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(d(r));return i.join(``)}function p(e){for(var n,r=e.length,i=r%3,a=[],o=16383,s=0,c=r-i;s<c;s+=o)a.push(f(e,s,s+o>c?c:s+o));return i===1?(n=e[r-1],a.push(t[n>>2]+t[n<<4&63]+`==`)):i===2&&(n=(e[r-2]<<8)+e[r-1],a.push(t[n>>10]+t[n>>4&63]+t[n<<2&63]+`=`)),a.join(``)}})),Ou=/* @__PURE__ */ t((e=>{
|
|
5
5
|
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
6
|
-
e.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<<s)-1,l=c>>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)},e.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<<l)-1,d=u>>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128}})),
|
|
6
|
+
e.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<<s)-1,l=c>>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)},e.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<<l)-1,d=u>>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128}})),ku=/* @__PURE__ */ t((e=>{
|
|
7
7
|
/*!
|
|
8
8
|
* The buffer module from node.js, for the browser.
|
|
9
9
|
*
|
|
10
10
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
11
11
|
* @license MIT
|
|
12
12
|
*/
|
|
13
|
-
var t=Eu(),n=Du(),r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Symbol.for(`nodejs.util.inspect.custom`):null;e.Buffer=s,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50;var i=2147483647;e.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=a(),!s.TYPED_ARRAY_SUPPORT&&typeof console<`u`&&typeof console.error==`function`&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{var e=/* @__PURE__ */ new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function o(e){if(e>i)throw RangeError(`The value "`+e+`" is invalid for option "size"`);var t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if(typeof e==`number`){if(typeof t==`string`)throw TypeError(`The "string" argument must be of type string. Received type number`);return d(e)}return c(e,t,n)}s.poolSize=8192;function c(e,t,n){if(typeof e==`string`)return f(e,t);if(ArrayBuffer.isView(e))return m(e);if(e==null)throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e);if(R(e,ArrayBuffer)||e&&R(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<`u`&&(R(e,SharedArrayBuffer)||e&&R(e.buffer,SharedArrayBuffer)))return h(e,t,n);if(typeof e==`number`)throw TypeError(`The "value" argument must not be of type number. Received type number`);var r=e.valueOf&&e.valueOf();if(r!=null&&r!==e)return s.from(r,t,n);var i=g(e);if(i)return i;if(typeof Symbol<`u`&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]==`function`)return s.from(e[Symbol.toPrimitive](`string`),t,n);throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e)}s.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(e){if(typeof e!=`number`)throw TypeError(`"size" argument must be of type number`);if(e<0)throw RangeError(`The value "`+e+`" is invalid for option "size"`)}function u(e,t,n){return l(e),e<=0||t===void 0?o(e):typeof n==`string`?o(e).fill(t,n):o(e).fill(t)}s.alloc=function(e,t,n){return u(e,t,n)};function d(e){return l(e),o(e<0?0:_(e)|0)}s.allocUnsafe=function(e){return d(e)},s.allocUnsafeSlow=function(e){return d(e)};function f(e,t){if((typeof t!=`string`||t===``)&&(t=`utf8`),!s.isEncoding(t))throw TypeError(`Unknown encoding: `+t);var n=y(e,t)|0,r=o(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function p(e){for(var t=e.length<0?0:_(e.length)|0,n=o(t),r=0;r<t;r+=1)n[r]=e[r]&255;return n}function m(e){if(R(e,Uint8Array)){var t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return p(e)}function h(e,t,n){if(t<0||e.byteLength<t)throw RangeError(`"offset" is outside of buffer bounds`);if(e.byteLength<t+(n||0))throw RangeError(`"length" is outside of buffer bounds`);var r=t===void 0&&n===void 0?new Uint8Array(e):n===void 0?new Uint8Array(e,t):new Uint8Array(e,t,n);return Object.setPrototypeOf(r,s.prototype),r}function g(e){if(s.isBuffer(e)){var t=_(e.length)|0,n=o(t);return n.length===0||e.copy(n,0,0,t),n}if(e.length!==void 0)return typeof e.length!=`number`||de(e.length)?o(0):p(e);if(e.type===`Buffer`&&Array.isArray(e.data))return p(e.data)}function _(e){if(e>=i)throw RangeError(`Attempt to allocate Buffer larger than maximum size: 0x`+i.toString(16)+` bytes`);return e|0}function v(e){return+e!=e&&(e=0),s.alloc(+e)}s.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==s.prototype},s.compare=function(e,t){if(R(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),R(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw TypeError(`The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array`);if(e===t)return 0;for(var n=e.length,r=t.length,i=0,a=Math.min(n,r);i<a;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:+(r<n)},s.isEncoding=function(e){switch(String(e).toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`latin1`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw TypeError(`"list" argument must be an Array of Buffers`);if(e.length===0)return s.alloc(0);var n;if(t===void 0)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=s.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var a=e[n];if(R(a,Uint8Array))i+a.length>r.length?s.from(a).copy(r,i):Uint8Array.prototype.set.call(r,a,i);else if(s.isBuffer(a))a.copy(r,i);else throw TypeError(`"list" argument must be an Array of Buffers`);i+=a.length}return r};function y(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||R(e,ArrayBuffer))return e.byteLength;if(typeof e!=`string`)throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type `+typeof e);var n=e.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&n===0)return 0;for(var i=!1;;)switch(t){case`ascii`:case`latin1`:case`binary`:return n;case`utf8`:case`utf-8`:return oe(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return le(e).length;default:if(i)return r?-1:oe(e).length;t=(``+t).toLowerCase(),i=!0}}s.byteLength=y;function b(e,t,n){var r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,t>>>=0,n<=t))return``;for(e||=`utf8`;;)switch(e){case`hex`:return M(this,t,n);case`utf8`:case`utf-8`:return k(this,t,n);case`ascii`:return ne(this,t,n);case`latin1`:case`binary`:return j(this,t,n);case`base64`:return ee(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return N(this,t,n);default:if(r)throw TypeError(`Unknown encoding: `+e);e=(e+``).toLowerCase(),r=!0}}s.prototype._isBuffer=!0;function x(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}s.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(var t=0;t<e;t+=2)x(this,t,t+1);return this},s.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(var t=0;t<e;t+=4)x(this,t,t+3),x(this,t+1,t+2);return this},s.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(var t=0;t<e;t+=8)x(this,t,t+7),x(this,t+1,t+6),x(this,t+2,t+5),x(this,t+3,t+4);return this},s.prototype.toString=function(){var e=this.length;return e===0?``:arguments.length===0?k(this,0,e):b.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw TypeError(`Argument must be a Buffer`);return this===e||s.compare(this,e)===0},s.prototype.inspect=function(){var t=``,n=e.INSPECT_MAX_BYTES;return t=this.toString(`hex`,0,n).replace(/(.{2})/g,`$1 `).trim(),this.length>n&&(t+=` ... `),`<Buffer `+t+`>`},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(R(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw TypeError(`The "target" argument must be one of type Buffer or Uint8Array. Received type `+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),r===void 0&&(r=0),i===void 0&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw RangeError(`out of range index`);if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;for(var a=i-r,o=n-t,c=Math.min(a,o),l=this.slice(r,i),u=e.slice(t,n),d=0;d<c;++d)if(l[d]!==u[d]){a=l[d],o=u[d];break}return a<o?-1:+(o<a)};function S(e,t,n,r,i){if(e.length===0)return-1;if(typeof n==`string`?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,de(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(i)n=0;else return-1}if(typeof t==`string`&&(t=s.from(t,r)),s.isBuffer(t))return t.length===0?-1:C(e,t,n,r,i);if(typeof t==`number`)return t&=255,typeof Uint8Array.prototype.indexOf==`function`?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):C(e,[t],n,r,i);throw TypeError(`val must be string, number or Buffer`)}function C(e,t,n,r,i){var a=1,o=e.length,s=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r===`ucs2`||r===`ucs-2`||r===`utf16le`||r===`utf-16le`)){if(e.length<2||t.length<2)return-1;a=2,o/=2,s/=2,n/=2}function c(e,t){return a===1?e[t]:e.readUInt16BE(t*a)}var l;if(i){var u=-1;for(l=n;l<o;l++)if(c(e,l)===c(t,u===-1?0:l-u)){if(u===-1&&(u=l),l-u+1===s)return u*a}else u!==-1&&(l-=l-u),u=-1}else for(n+s>o&&(n=o-s),l=n;l>=0;l--){for(var d=!0,f=0;f<s;f++)if(c(e,l+f)!==c(t,f)){d=!1;break}if(d)return l}return-1}s.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1},s.prototype.indexOf=function(e,t,n){return S(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return S(this,e,t,n,!1)};function w(e,t,n,r){n=Number(n)||0;var i=e.length-n;r?(r=Number(r),r>i&&(r=i)):r=i;var a=t.length;r>a/2&&(r=a/2);for(var o=0;o<r;++o){var s=parseInt(t.substr(o*2,2),16);if(de(s))return o;e[n+o]=s}return o}function T(e,t,n,r){return ue(oe(t,e.length-n),e,n,r)}function E(e,t,n,r){return ue(se(t),e,n,r)}function D(e,t,n,r){return ue(le(t),e,n,r)}function O(e,t,n,r){return ue(ce(t,e.length-n),e,n,r)}s.prototype.write=function(e,t,n,r){if(t===void 0)r=`utf8`,n=this.length,t=0;else if(n===void 0&&typeof t==`string`)r=t,n=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(n)?(n>>>=0,r===void 0&&(r=`utf8`)):(r=n,n=void 0);else throw Error(`Buffer.write(string, encoding, offset[, length]) is no longer supported`);var i=this.length-t;if((n===void 0||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError(`Attempt to write outside buffer bounds`);r||=`utf8`;for(var a=!1;;)switch(r){case`hex`:return w(this,e,t,n);case`utf8`:case`utf-8`:return T(this,e,t,n);case`ascii`:case`latin1`:case`binary`:return E(this,e,t,n);case`base64`:return D(this,e,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return O(this,e,t,n);default:if(a)throw TypeError(`Unknown encoding: `+r);r=(``+r).toLowerCase(),a=!0}},s.prototype.toJSON=function(){return{type:`Buffer`,data:Array.prototype.slice.call(this._arr||this,0)}};function ee(e,n,r){return n===0&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function k(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i<n;){var a=e[i],o=null,s=a>239?4:a>223?3:a>191?2:1;if(i+s<=n){var c,l,u,d;switch(s){case 1:a<128&&(o=a);break;case 2:c=e[i+1],(c&192)==128&&(d=(a&31)<<6|c&63,d>127&&(o=d));break;case 3:c=e[i+1],l=e[i+2],(c&192)==128&&(l&192)==128&&(d=(a&15)<<12|(c&63)<<6|l&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:c=e[i+1],l=e[i+2],u=e[i+3],(c&192)==128&&(l&192)==128&&(u&192)==128&&(d=(a&15)<<18|(c&63)<<12|(l&63)<<6|u&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|o&1023),r.push(o),i+=s}return A(r)}var te=4096;function A(e){var t=e.length;if(t<=te)return String.fromCharCode.apply(String,e);for(var n=``,r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=te));return n}function ne(e,t,n){var r=``;n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(e[i]&127);return r}function j(e,t,n){var r=``;n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function M(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var i=``,a=t;a<n;++a)i+=fe[e[a]];return i}function N(e,t,n){for(var r=e.slice(t,n),i=``,a=0;a<r.length-1;a+=2)i+=String.fromCharCode(r[a]+r[a+1]*256);return i}s.prototype.slice=function(e,t){var n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r};function P(e,t,n){if(e%1!=0||e<0)throw RangeError(`offset is not uint`);if(e+t>n)throw RangeError(`Trying to access beyond buffer length`)}s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=this[e],i=1,a=0;++a<t&&(i*=256);)r+=this[e+a]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=this[e+--t],i=1;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=this[e],i=1,a=0;++a<t&&(i*=256);)r+=this[e+a]*i;return i*=128,r>=i&&(r-=2**(8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=t,i=1,a=this[e+--r];r>0&&(i*=256);)a+=this[e+--r]*i;return i*=128,a>=i&&(a-=2**(8*t)),a},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!1,52,8)};function F(e,t,n,r,i,a){if(!s.isBuffer(e))throw TypeError(`"buffer" argument must be a Buffer instance`);if(t>i||t<a)throw RangeError(`"value" argument is out of bounds`);if(n+r>e.length)throw RangeError(`Index out of range`)}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){var i=2**(8*n)-1;F(this,e,t,n,i,0)}var a=1,o=0;for(this[t]=e&255;++o<n&&(a*=256);)this[t+o]=e/a&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){var i=2**(8*n)-1;F(this,e,t,n,i,0)}var a=n-1,o=1;for(this[t+a]=e&255;--a>=0&&(o*=256);)this[t+a]=e/o&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,1,255,0),this[t]=e&255,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=2**(8*n-1);F(this,e,t,n,i-1,-i)}var a=0,o=1,s=0;for(this[t]=e&255;++a<n&&(o*=256);)e<0&&s===0&&this[t+a-1]!==0&&(s=1),this[t+a]=(e/o>>0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=2**(8*n-1);F(this,e,t,n,i-1,-i)}var a=n-1,o=1,s=0;for(this[t+a]=e&255;--a>=0&&(o*=256);)e<0&&s===0&&this[t+a+1]!==0&&(s=1),this[t+a]=(e/o>>0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function re(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function I(e,t,r,i,a){return t=+t,r>>>=0,a||re(e,t,r,4,34028234663852886e22,-34028234663852886e22),n.write(e,t,r,i,23,4),r+4}s.prototype.writeFloatLE=function(e,t,n){return I(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return I(this,e,t,!1,n)};function L(e,t,r,i,a){return t=+t,r>>>=0,a||re(e,t,r,8,17976931348623157e292,-17976931348623157e292),n.write(e,t,r,i,52,8),r+8}s.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw TypeError(`argument should be a Buffer`);if(n||=0,!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||=0,r>0&&r<n&&(r=n),r===n||e.length===0||this.length===0)return 0;if(t<0)throw RangeError(`targetStart out of bounds`);if(n<0||n>=this.length)throw RangeError(`Index out of range`);if(r<0)throw RangeError(`sourceEnd out of bounds`);r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var i=r-n;return this===e&&typeof Uint8Array.prototype.copyWithin==`function`?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),i},s.prototype.fill=function(e,t,n,r){if(typeof e==`string`){if(typeof t==`string`?(r=t,t=0,n=this.length):typeof n==`string`&&(r=n,n=this.length),r!==void 0&&typeof r!=`string`)throw TypeError(`encoding must be a string`);if(typeof r==`string`&&!s.isEncoding(r))throw TypeError(`Unknown encoding: `+r);if(e.length===1){var i=e.charCodeAt(0);(r===`utf8`&&i<128||r===`latin1`)&&(e=i)}}else typeof e==`number`?e&=255:typeof e==`boolean`&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw RangeError(`Out of range index`);if(n<=t)return this;t>>>=0,n=n===void 0?this.length:n>>>0,e||=0;var a;if(typeof e==`number`)for(a=t;a<n;++a)this[a]=e;else{var o=s.isBuffer(e)?e:s.from(e,r),c=o.length;if(c===0)throw TypeError(`The value "`+e+`" is invalid for argument "value"`);for(a=0;a<n-t;++a)this[a+t]=o[a%c]}return this};var ie=/[^+/0-9A-Za-z-_]/g;function ae(e){if(e=e.split(`=`)[0],e=e.trim().replace(ie,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function oe(e,t){t||=1/0;for(var n,r=e.length,i=null,a=[],o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if(--t<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,n&63|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw Error(`Invalid code point`)}return a}function se(e){for(var t=[],n=0;n<e.length;++n)t.push(e.charCodeAt(n)&255);return t}function ce(e,t){for(var n,r,i,a=[],o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,i=n%256,a.push(i),a.push(r);return a}function le(e){return t.toByteArray(ae(e))}function ue(e,t,n,r){for(var i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function R(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function de(e){return e!==e}var fe=(function(){for(var e=`0123456789abcdef`,t=Array(256),n=0;n<16;++n)for(var r=n*16,i=0;i<16;++i)t[r+i]=e[n]+e[i];return t})()})),ku=/* @__PURE__ */ t(((e,t)=>{t.exports=function(){if(typeof Symbol!=`function`||typeof Object.getOwnPropertySymbols!=`function`)return!1;if(typeof Symbol.iterator==`symbol`)return!0;var e={},t=Symbol(`test`),n=Object(t);if(typeof t==`string`||Object.prototype.toString.call(t)!==`[object Symbol]`||Object.prototype.toString.call(n)!==`[object Symbol]`)return!1;var r=42;for(var i in e[t]=r,e)return!1;if(typeof Object.keys==`function`&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames==`function`&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==t||!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if(typeof Object.getOwnPropertyDescriptor==`function`){var o=Object.getOwnPropertyDescriptor(e,t);if(o.value!==r||o.enumerable!==!0)return!1}return!0}})),Au=/* @__PURE__ */ t(((e,t)=>{var n=ku();t.exports=function(){return n()&&!!Symbol.toStringTag}})),ju=/* @__PURE__ */ t(((e,t)=>{t.exports=Object})),Mu=/* @__PURE__ */ t(((e,t)=>{t.exports=Error})),Nu=/* @__PURE__ */ t(((e,t)=>{t.exports=EvalError})),Pu=/* @__PURE__ */ t(((e,t)=>{t.exports=RangeError})),Fu=/* @__PURE__ */ t(((e,t)=>{t.exports=ReferenceError})),Iu=/* @__PURE__ */ t(((e,t)=>{t.exports=SyntaxError})),Lu=/* @__PURE__ */ t(((e,t)=>{t.exports=TypeError})),Ru=/* @__PURE__ */ t(((e,t)=>{t.exports=URIError})),zu=/* @__PURE__ */ t(((e,t)=>{t.exports=Math.abs})),Bu=/* @__PURE__ */ t(((e,t)=>{t.exports=Math.floor})),Vu=/* @__PURE__ */ t(((e,t)=>{t.exports=Math.max})),Hu=/* @__PURE__ */ t(((e,t)=>{t.exports=Math.min})),Uu=/* @__PURE__ */ t(((e,t)=>{t.exports=Math.pow})),Wu=/* @__PURE__ */ t(((e,t)=>{t.exports=Math.round})),Gu=/* @__PURE__ */ t(((e,t)=>{t.exports=Number.isNaN||function(e){return e!==e}})),Ku=/* @__PURE__ */ t(((e,t)=>{var n=Gu();t.exports=function(e){return n(e)||e===0?e:e<0?-1:1}})),qu=/* @__PURE__ */ t(((e,t)=>{t.exports=Object.getOwnPropertyDescriptor})),Ju=/* @__PURE__ */ t(((e,t)=>{var n=qu();if(n)try{n([],`length`)}catch{n=null}t.exports=n})),Yu=/* @__PURE__ */ t(((e,t)=>{var n=Object.defineProperty||!1;if(n)try{n({},`a`,{value:1})}catch{n=!1}t.exports=n})),Xu=/* @__PURE__ */ t(((e,t)=>{var n=typeof Symbol<`u`&&Symbol,r=ku();t.exports=function(){return typeof n!=`function`||typeof Symbol!=`function`||typeof n(`foo`)!=`symbol`||typeof Symbol(`bar`)!=`symbol`?!1:r()}})),Zu=/* @__PURE__ */ t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect.getPrototypeOf||null})),Qu=/* @__PURE__ */ t(((e,t)=>{t.exports=ju().getPrototypeOf||null})),$u=/* @__PURE__ */ t(((e,t)=>{var n=Object.prototype.toString,r=Math.max,i=`[object Function]`,a=function(e,t){for(var n=[],r=0;r<e.length;r+=1)n[r]=e[r];for(var i=0;i<t.length;i+=1)n[i+e.length]=t[i];return n},o=function(e,t){for(var n=[],r=t||0,i=0;r<e.length;r+=1,i+=1)n[i]=e[r];return n},s=function(e,t){for(var n=``,r=0;r<e.length;r+=1)n+=e[r],r+1<e.length&&(n+=t);return n};t.exports=function(e){var t=this;if(typeof t!=`function`||n.apply(t)!==i)throw TypeError(`Function.prototype.bind called on incompatible `+t);for(var c=o(arguments,1),l,u=function(){if(this instanceof l){var n=t.apply(this,a(c,arguments));return Object(n)===n?n:this}return t.apply(e,a(c,arguments))},d=r(0,t.length-c.length),f=[],p=0;p<d;p++)f[p]=`$`+p;if(l=Function(`binder`,`return function (`+s(f,`,`)+`){ return binder.apply(this,arguments); }`)(u),t.prototype){var m=function(){};m.prototype=t.prototype,l.prototype=new m,m.prototype=null}return l}})),ed=/* @__PURE__ */ t(((e,t)=>{var n=$u();t.exports=Function.prototype.bind||n})),td=/* @__PURE__ */ t(((e,t)=>{t.exports=Function.prototype.call})),nd=/* @__PURE__ */ t(((e,t)=>{t.exports=Function.prototype.apply})),rd=/* @__PURE__ */ t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect&&Reflect.apply})),id=/* @__PURE__ */ t(((e,t)=>{var n=ed(),r=nd(),i=td();t.exports=rd()||n.call(i,r)})),ad=/* @__PURE__ */ t(((e,t)=>{var n=ed(),r=Lu(),i=td(),a=id();t.exports=function(e){if(e.length<1||typeof e[0]!=`function`)throw new r(`a function is required`);return a(n,i,e)}})),od=/* @__PURE__ */ t(((e,t)=>{var n=ad(),r=Ju(),i;try{i=[].__proto__===Array.prototype}catch(e){if(!e||typeof e!=`object`||!(`code`in e)||e.code!==`ERR_PROTO_ACCESS`)throw e}var a=!!i&&r&&r(Object.prototype,`__proto__`),o=Object,s=o.getPrototypeOf;t.exports=a&&typeof a.get==`function`?n([a.get]):typeof s==`function`&&function(e){return s(e==null?e:o(e))}})),sd=/* @__PURE__ */ t(((e,t)=>{var n=Zu(),r=Qu(),i=od();t.exports=n?function(e){return n(e)}:r?function(e){if(!e||typeof e!=`object`&&typeof e!=`function`)throw TypeError(`getProto: not an object`);return r(e)}:i?function(e){return i(e)}:null})),cd=/* @__PURE__ */ t(((e,t)=>{var n=Function.prototype.call,r=Object.prototype.hasOwnProperty;t.exports=ed().call(n,r)})),ld=/* @__PURE__ */ t(((e,t)=>{var n,r=ju(),i=Mu(),a=Nu(),o=Pu(),s=Fu(),c=Iu(),l=Lu(),u=Ru(),d=zu(),f=Bu(),p=Vu(),m=Hu(),h=Uu(),g=Wu(),_=Ku(),v=Function,y=function(e){try{return v(`"use strict"; return (`+e+`).constructor;`)()}catch{}},b=Ju(),x=Yu(),S=function(){throw new l},C=b?function(){try{return arguments.callee,S}catch{try{return b(arguments,`callee`).get}catch{return S}}}():S,w=Xu()(),T=sd(),E=Qu(),D=Zu(),O=nd(),ee=td(),k={},te=typeof Uint8Array>`u`||!T?n:T(Uint8Array),A={__proto__:null,"%AggregateError%":typeof AggregateError>`u`?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>`u`?n:ArrayBuffer,"%ArrayIteratorPrototype%":w&&T?T([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":k,"%AsyncGenerator%":k,"%AsyncGeneratorFunction%":k,"%AsyncIteratorPrototype%":k,"%Atomics%":typeof Atomics>`u`?n:Atomics,"%BigInt%":typeof BigInt>`u`?n:BigInt,"%BigInt64Array%":typeof BigInt64Array>`u`?n:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>`u`?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>`u`?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":a,"%Float16Array%":typeof Float16Array>`u`?n:Float16Array,"%Float32Array%":typeof Float32Array>`u`?n:Float32Array,"%Float64Array%":typeof Float64Array>`u`?n:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>`u`?n:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":k,"%Int8Array%":typeof Int8Array>`u`?n:Int8Array,"%Int16Array%":typeof Int16Array>`u`?n:Int16Array,"%Int32Array%":typeof Int32Array>`u`?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":w&&T?T(T([][Symbol.iterator]())):n,"%JSON%":typeof JSON==`object`?JSON:n,"%Map%":typeof Map>`u`?n:Map,"%MapIteratorPrototype%":typeof Map>`u`||!w||!T?n:T((/* @__PURE__ */ new Map())[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":r,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>`u`?n:Promise,"%Proxy%":typeof Proxy>`u`?n:Proxy,"%RangeError%":o,"%ReferenceError%":s,"%Reflect%":typeof Reflect>`u`?n:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>`u`?n:Set,"%SetIteratorPrototype%":typeof Set>`u`||!w||!T?n:T((/* @__PURE__ */ new Set())[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>`u`?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":w&&T?T(``[Symbol.iterator]()):n,"%Symbol%":w?Symbol:n,"%SyntaxError%":c,"%ThrowTypeError%":C,"%TypedArray%":te,"%TypeError%":l,"%Uint8Array%":typeof Uint8Array>`u`?n:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>`u`?n:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>`u`?n:Uint16Array,"%Uint32Array%":typeof Uint32Array>`u`?n:Uint32Array,"%URIError%":u,"%WeakMap%":typeof WeakMap>`u`?n:WeakMap,"%WeakRef%":typeof WeakRef>`u`?n:WeakRef,"%WeakSet%":typeof WeakSet>`u`?n:WeakSet,"%Function.prototype.call%":ee,"%Function.prototype.apply%":O,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":E,"%Math.abs%":d,"%Math.floor%":f,"%Math.max%":p,"%Math.min%":m,"%Math.pow%":h,"%Math.round%":g,"%Math.sign%":_,"%Reflect.getPrototypeOf%":D};if(T)try{null.error}catch(e){A[`%Error.prototype%`]=T(T(e))}var ne=function e(t){var n;if(t===`%AsyncFunction%`)n=y(`async function () {}`);else if(t===`%GeneratorFunction%`)n=y(`function* () {}`);else if(t===`%AsyncGeneratorFunction%`)n=y(`async function* () {}`);else if(t===`%AsyncGenerator%`){var r=e(`%AsyncGeneratorFunction%`);r&&(n=r.prototype)}else if(t===`%AsyncIteratorPrototype%`){var i=e(`%AsyncGenerator%`);i&&T&&(n=T(i.prototype))}return A[t]=n,n},j={__proto__:null,"%ArrayBufferPrototype%":[`ArrayBuffer`,`prototype`],"%ArrayPrototype%":[`Array`,`prototype`],"%ArrayProto_entries%":[`Array`,`prototype`,`entries`],"%ArrayProto_forEach%":[`Array`,`prototype`,`forEach`],"%ArrayProto_keys%":[`Array`,`prototype`,`keys`],"%ArrayProto_values%":[`Array`,`prototype`,`values`],"%AsyncFunctionPrototype%":[`AsyncFunction`,`prototype`],"%AsyncGenerator%":[`AsyncGeneratorFunction`,`prototype`],"%AsyncGeneratorPrototype%":[`AsyncGeneratorFunction`,`prototype`,`prototype`],"%BooleanPrototype%":[`Boolean`,`prototype`],"%DataViewPrototype%":[`DataView`,`prototype`],"%DatePrototype%":[`Date`,`prototype`],"%ErrorPrototype%":[`Error`,`prototype`],"%EvalErrorPrototype%":[`EvalError`,`prototype`],"%Float32ArrayPrototype%":[`Float32Array`,`prototype`],"%Float64ArrayPrototype%":[`Float64Array`,`prototype`],"%FunctionPrototype%":[`Function`,`prototype`],"%Generator%":[`GeneratorFunction`,`prototype`],"%GeneratorPrototype%":[`GeneratorFunction`,`prototype`,`prototype`],"%Int8ArrayPrototype%":[`Int8Array`,`prototype`],"%Int16ArrayPrototype%":[`Int16Array`,`prototype`],"%Int32ArrayPrototype%":[`Int32Array`,`prototype`],"%JSONParse%":[`JSON`,`parse`],"%JSONStringify%":[`JSON`,`stringify`],"%MapPrototype%":[`Map`,`prototype`],"%NumberPrototype%":[`Number`,`prototype`],"%ObjectPrototype%":[`Object`,`prototype`],"%ObjProto_toString%":[`Object`,`prototype`,`toString`],"%ObjProto_valueOf%":[`Object`,`prototype`,`valueOf`],"%PromisePrototype%":[`Promise`,`prototype`],"%PromiseProto_then%":[`Promise`,`prototype`,`then`],"%Promise_all%":[`Promise`,`all`],"%Promise_reject%":[`Promise`,`reject`],"%Promise_resolve%":[`Promise`,`resolve`],"%RangeErrorPrototype%":[`RangeError`,`prototype`],"%ReferenceErrorPrototype%":[`ReferenceError`,`prototype`],"%RegExpPrototype%":[`RegExp`,`prototype`],"%SetPrototype%":[`Set`,`prototype`],"%SharedArrayBufferPrototype%":[`SharedArrayBuffer`,`prototype`],"%StringPrototype%":[`String`,`prototype`],"%SymbolPrototype%":[`Symbol`,`prototype`],"%SyntaxErrorPrototype%":[`SyntaxError`,`prototype`],"%TypedArrayPrototype%":[`TypedArray`,`prototype`],"%TypeErrorPrototype%":[`TypeError`,`prototype`],"%Uint8ArrayPrototype%":[`Uint8Array`,`prototype`],"%Uint8ClampedArrayPrototype%":[`Uint8ClampedArray`,`prototype`],"%Uint16ArrayPrototype%":[`Uint16Array`,`prototype`],"%Uint32ArrayPrototype%":[`Uint32Array`,`prototype`],"%URIErrorPrototype%":[`URIError`,`prototype`],"%WeakMapPrototype%":[`WeakMap`,`prototype`],"%WeakSetPrototype%":[`WeakSet`,`prototype`]},M=ed(),N=cd(),P=M.call(ee,Array.prototype.concat),F=M.call(O,Array.prototype.splice),re=M.call(ee,String.prototype.replace),I=M.call(ee,String.prototype.slice),L=M.call(ee,RegExp.prototype.exec),ie=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ae=/\\(\\)?/g,oe=function(e){var t=I(e,0,1),n=I(e,-1);if(t===`%`&&n!==`%`)throw new c("invalid intrinsic syntax, expected closing `%`");if(n===`%`&&t!==`%`)throw new c("invalid intrinsic syntax, expected opening `%`");var r=[];return re(e,ie,function(e,t,n,i){r[r.length]=n?re(i,ae,`$1`):t||e}),r},se=function(e,t){var n=e,r;if(N(j,n)&&(r=j[n],n=`%`+r[0]+`%`),N(A,n)){var i=A[n];if(i===k&&(i=ne(n)),i===void 0&&!t)throw new l(`intrinsic `+e+` exists, but is not available. Please file an issue!`);return{alias:r,name:n,value:i}}throw new c(`intrinsic `+e+` does not exist!`)};t.exports=function(e,t){if(typeof e!=`string`||e.length===0)throw new l(`intrinsic name must be a non-empty string`);if(arguments.length>1&&typeof t!=`boolean`)throw new l(`"allowMissing" argument must be a boolean`);if(L(/^%?[^%]*%?$/,e)===null)throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=oe(e),r=n.length>0?n[0]:``,i=se(`%`+r+`%`,t),a=i.name,o=i.value,s=!1,u=i.alias;u&&(r=u[0],F(n,P([0,1],u)));for(var d=1,f=!0;d<n.length;d+=1){var p=n[d],m=I(p,0,1),h=I(p,-1);if((m===`"`||m===`'`||m==="`"||h===`"`||h===`'`||h==="`")&&m!==h)throw new c(`property names with quotes must have matching quotes`);if((p===`constructor`||!f)&&(s=!0),r+=`.`+p,a=`%`+r+`%`,N(A,a))o=A[a];else if(o!=null){if(!(p in o)){if(!t)throw new l(`base intrinsic for `+e+` exists, but the property is not available.`);return}if(b&&d+1>=n.length){var g=b(o,p);f=!!g,o=f&&`get`in g&&!(`originalValue`in g.get)?g.get:o[p]}else f=N(o,p),o=o[p];f&&!s&&(A[a]=o)}}return o}})),ud=/* @__PURE__ */ t(((e,t)=>{var n=ld(),r=ad(),i=r([n(`%String.prototype.indexOf%`)]);t.exports=function(e,t){var a=n(e,!!t);return typeof a==`function`&&i(e,`.prototype.`)>-1?r([a]):a}})),dd=/* @__PURE__ */ t(((e,t)=>{var n=Au()(),r=ud()(`Object.prototype.toString`),i=function(e){return n&&e&&typeof e==`object`&&Symbol.toStringTag in e?!1:r(e)===`[object Arguments]`},a=function(e){return i(e)?!0:typeof e==`object`&&!!e&&`length`in e&&typeof e.length==`number`&&e.length>=0&&r(e)!==`[object Array]`&&`callee`in e&&r(e.callee)===`[object Function]`},o=function(){return i(arguments)}();i.isLegacyArguments=a,t.exports=o?i:a})),fd=/* @__PURE__ */ t(((e,t)=>{var n=ud(),r=Au()(),i=cd(),a=Ju(),o;if(r){var s=n(`RegExp.prototype.exec`),c={},l=function(){throw c},u={toString:l,valueOf:l};typeof Symbol.toPrimitive==`symbol`&&(u[Symbol.toPrimitive]=l),o=function(e){if(!e||typeof e!=`object`)return!1;var t=a(e,`lastIndex`);if(!(t&&i(t,`value`)))return!1;try{s(e,u)}catch(e){return e===c}}}else{var d=n(`Object.prototype.toString`),f=`[object RegExp]`;o=function(e){return!e||typeof e!=`object`&&typeof e!=`function`?!1:d(e)===f}}t.exports=o})),pd=/* @__PURE__ */ t(((e,t)=>{var n=ud(),r=fd(),i=n(`RegExp.prototype.exec`),a=Lu();t.exports=function(e){if(!r(e))throw new a("`regex` must be a RegExp");return function(t){return i(e,t)!==null}}})),md=/* @__PURE__ */ t(((e,t)=>{let n=function*(){}.constructor;t.exports=()=>n})),hd=/* @__PURE__ */ t(((e,t)=>{var n=ud(),r=pd()(/^\s*(?:function)?\*/),i=Au()(),a=sd(),o=n(`Object.prototype.toString`),s=n(`Function.prototype.toString`),c=md();t.exports=function(e){if(typeof e!=`function`)return!1;if(r(s(e)))return!0;if(!i)return o(e)===`[object GeneratorFunction]`;if(!a)return!1;var t=c();return t&&a(e)===t.prototype}})),gd=/* @__PURE__ */ t(((e,t)=>{var n=Function.prototype.toString,r=typeof Reflect==`object`&&Reflect!==null&&Reflect.apply,i,a;if(typeof r==`function`&&typeof Object.defineProperty==`function`)try{i=Object.defineProperty({},"length",{get:function(){throw a}}),a={},r(function(){throw 42},null,i)}catch(e){e!==a&&(r=null)}else r=null;var o=/^\s*class\b/,s=function(e){try{var t=n.call(e);return o.test(t)}catch{return!1}},c=function(e){try{return!s(e)&&(n.call(e),!0)}catch{return!1}},l=Object.prototype.toString,u=`[object Object]`,d=`[object Function]`,f=`[object GeneratorFunction]`,p=`[object HTMLAllCollection]`,m=`[object HTML document.all class]`,h=`[object HTMLCollection]`,g=typeof Symbol==`function`&&!!Symbol.toStringTag,_=!(0 in[,]),v=function(){return!1};if(typeof document==`object`){var y=document.all;l.call(y)===l.call(document.all)&&(v=function(e){if((_||!e)&&(e===void 0||typeof e==`object`))try{var t=l.call(e);return(t===p||t===m||t===h||t===u)&&e(``)==null}catch{}return!1})}t.exports=r?function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;try{r(e,null,i)}catch(e){if(e!==a)return!1}return!s(e)&&c(e)}:function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;if(g)return c(e);if(s(e))return!1;var t=l.call(e);return t!==d&&t!==f&&!/^\[object HTML/.test(t)?!1:c(e)}})),_d=/* @__PURE__ */ t(((e,t)=>{var n=gd(),r=Object.prototype.toString,i=Object.prototype.hasOwnProperty,a=function(e,t,n){for(var r=0,a=e.length;r<a;r++)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))},o=function(e,t,n){for(var r=0,i=e.length;r<i;r++)n==null?t(e.charAt(r),r,e):t.call(n,e.charAt(r),r,e)},s=function(e,t,n){for(var r in e)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))};function c(e){return r.call(e)===`[object Array]`}t.exports=function(e,t,r){if(!n(t))throw TypeError(`iterator must be a function`);var i;arguments.length>=3&&(i=r),c(e)?a(e,t,i):typeof e==`string`?o(e,t,i):s(e,t,i)}})),vd=/* @__PURE__ */ t(((e,t)=>{t.exports=[`Float16Array`,`Float32Array`,`Float64Array`,`Int8Array`,`Int16Array`,`Int32Array`,`Uint8Array`,`Uint8ClampedArray`,`Uint16Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`]})),yd=/* @__PURE__ */ t(((e,t)=>{var n=vd(),r=typeof globalThis>`u`?global:globalThis;t.exports=function(){for(var e=[],t=0;t<n.length;t++)typeof r[n[t]]==`function`&&(e[e.length]=n[t]);return e}})),bd=/* @__PURE__ */ t(((e,t)=>{var n=Yu(),r=Iu(),i=Lu(),a=Ju();t.exports=function(e,t,o){if(!e||typeof e!=`object`&&typeof e!=`function`)throw new i("`obj` must be an object or a function`");if(typeof t!=`string`&&typeof t!=`symbol`)throw new i("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!=`boolean`&&arguments[3]!==null)throw new i("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!=`boolean`&&arguments[4]!==null)throw new i("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!=`boolean`&&arguments[5]!==null)throw new i("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!=`boolean`)throw new i("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,u=arguments.length>6&&arguments[6],d=!!a&&a(e,t);if(n)n(e,t,{configurable:l===null&&d?d.configurable:!l,enumerable:s===null&&d?d.enumerable:!s,value:o,writable:c===null&&d?d.writable:!c});else if(u||!s&&!c&&!l)e[t]=o;else throw new r(`This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.`)}})),xd=/* @__PURE__ */ t(((e,t)=>{var n=Yu(),r=function(){return!!n};r.hasArrayLengthDefineBug=function(){if(!n)return null;try{return n([],`length`,{value:1}).length!==1}catch{return!0}},t.exports=r})),Sd=/* @__PURE__ */ t(((e,t)=>{var n=ld(),r=bd(),i=xd()(),a=Ju(),o=Lu(),s=n(`%Math.floor%`);t.exports=function(e,t){if(typeof e!=`function`)throw new o("`fn` is not a function");if(typeof t!=`number`||t<0||t>4294967295||s(t)!==t)throw new o("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],c=!0,l=!0;if(`length`in e&&a){var u=a(e,`length`);u&&!u.configurable&&(c=!1),u&&!u.writable&&(l=!1)}return(c||l||!n)&&(i?r(e,`length`,t,!0,!0):r(e,`length`,t)),e}})),Cd=/* @__PURE__ */ t(((e,t)=>{var n=ed(),r=nd(),i=id();t.exports=function(){return i(n,r,arguments)}})),wd=/* @__PURE__ */ t(((e,t)=>{var n=Sd(),r=Yu(),i=ad(),a=Cd();t.exports=function(e){var t=i(arguments),r=e.length-(arguments.length-1);return n(t,1+(r>0?r:0),!0)},r?r(t.exports,`apply`,{value:a}):t.exports.apply=a})),Td=/* @__PURE__ */ t(((e,t)=>{var n=_d(),r=yd(),i=wd(),a=ud(),o=Ju(),s=sd(),c=a(`Object.prototype.toString`),l=Au()(),u=typeof globalThis>`u`?global:globalThis,d=r(),f=a(`String.prototype.slice`),p=a(`Array.prototype.indexOf`,!0)||function(e,t){for(var n=0;n<e.length;n+=1)if(e[n]===t)return n;return-1},m={__proto__:null};l&&o&&s?n(d,function(e){var t=new u[e];if(Symbol.toStringTag in t&&s){var n=s(t),r=o(n,Symbol.toStringTag);!r&&n&&(r=o(s(n),Symbol.toStringTag)),m[`$`+e]=i(r.get)}}):n(d,function(e){var t=new u[e],n=t.slice||t.set;n&&(m[`$`+e]=i(n))});var h=function(e){var t=!1;return n(m,function(n,r){if(!t)try{`$`+n(e)===r&&(t=f(r,1))}catch{}}),t},g=function(e){var t=!1;return n(m,function(n,r){if(!t)try{n(e),t=f(r,1)}catch{}}),t};t.exports=function(e){if(!e||typeof e!=`object`)return!1;if(!l){var t=f(c(e),8,-1);return p(d,t)>-1?t:t===`Object`&&g(e)}return o?h(e):null}})),Ed=/* @__PURE__ */ t(((e,t)=>{var n=Td();t.exports=function(e){return!!n(e)}})),Dd=/* @__PURE__ */ t((e=>{var t=dd(),n=hd(),r=Td(),i=Ed();function a(e){return e.call.bind(e)}var o=typeof BigInt<`u`,s=typeof Symbol<`u`,c=a(Object.prototype.toString),l=a(Number.prototype.valueOf),u=a(String.prototype.valueOf),d=a(Boolean.prototype.valueOf);if(o)var f=a(BigInt.prototype.valueOf);if(s)var p=a(Symbol.prototype.valueOf);function m(e,t){if(typeof e!=`object`)return!1;try{return t(e),!0}catch{return!1}}e.isArgumentsObject=t,e.isGeneratorFunction=n,e.isTypedArray=i;function h(e){return typeof Promise<`u`&&e instanceof Promise||typeof e==`object`&&!!e&&typeof e.then==`function`&&typeof e.catch==`function`}e.isPromise=h;function g(e){return typeof ArrayBuffer<`u`&&ArrayBuffer.isView?ArrayBuffer.isView(e):i(e)||re(e)}e.isArrayBufferView=g;function _(e){return r(e)===`Uint8Array`}e.isUint8Array=_;function v(e){return r(e)===`Uint8ClampedArray`}e.isUint8ClampedArray=v;function y(e){return r(e)===`Uint16Array`}e.isUint16Array=y;function b(e){return r(e)===`Uint32Array`}e.isUint32Array=b;function x(e){return r(e)===`Int8Array`}e.isInt8Array=x;function S(e){return r(e)===`Int16Array`}e.isInt16Array=S;function C(e){return r(e)===`Int32Array`}e.isInt32Array=C;function w(e){return r(e)===`Float32Array`}e.isFloat32Array=w;function T(e){return r(e)===`Float64Array`}e.isFloat64Array=T;function E(e){return r(e)===`BigInt64Array`}e.isBigInt64Array=E;function D(e){return r(e)===`BigUint64Array`}e.isBigUint64Array=D;function O(e){return c(e)===`[object Map]`}O.working=typeof Map<`u`&&O(/* @__PURE__ */ new Map);function ee(e){return typeof Map>`u`?!1:O.working?O(e):e instanceof Map}e.isMap=ee;function k(e){return c(e)===`[object Set]`}k.working=typeof Set<`u`&&k(/* @__PURE__ */ new Set);function te(e){return typeof Set>`u`?!1:k.working?k(e):e instanceof Set}e.isSet=te;function A(e){return c(e)===`[object WeakMap]`}A.working=typeof WeakMap<`u`&&A(/* @__PURE__ */ new WeakMap);function ne(e){return typeof WeakMap>`u`?!1:A.working?A(e):e instanceof WeakMap}e.isWeakMap=ne;function j(e){return c(e)===`[object WeakSet]`}j.working=typeof WeakSet<`u`&&j(/* @__PURE__ */ new WeakSet);function M(e){return j(e)}e.isWeakSet=M;function N(e){return c(e)===`[object ArrayBuffer]`}N.working=typeof ArrayBuffer<`u`&&N(/* @__PURE__ */ new ArrayBuffer);function P(e){return typeof ArrayBuffer>`u`?!1:N.working?N(e):e instanceof ArrayBuffer}e.isArrayBuffer=P;function F(e){return c(e)===`[object DataView]`}F.working=typeof ArrayBuffer<`u`&&typeof DataView<`u`&&F(new DataView(/* @__PURE__ */ new ArrayBuffer(1),0,1));function re(e){return typeof DataView>`u`?!1:F.working?F(e):e instanceof DataView}e.isDataView=re;var I=typeof SharedArrayBuffer<`u`?SharedArrayBuffer:void 0;function L(e){return c(e)===`[object SharedArrayBuffer]`}function ie(e){return I!==void 0&&(L.working===void 0&&(L.working=L(new I)),L.working?L(e):e instanceof I)}e.isSharedArrayBuffer=ie;function ae(e){return c(e)===`[object AsyncFunction]`}e.isAsyncFunction=ae;function oe(e){return c(e)===`[object Map Iterator]`}e.isMapIterator=oe;function se(e){return c(e)===`[object Set Iterator]`}e.isSetIterator=se;function ce(e){return c(e)===`[object Generator]`}e.isGeneratorObject=ce;function le(e){return c(e)===`[object WebAssembly.Module]`}e.isWebAssemblyCompiledModule=le;function ue(e){return m(e,l)}e.isNumberObject=ue;function R(e){return m(e,u)}e.isStringObject=R;function de(e){return m(e,d)}e.isBooleanObject=de;function fe(e){return o&&m(e,f)}e.isBigIntObject=fe;function pe(e){return s&&m(e,p)}e.isSymbolObject=pe;function me(e){return ue(e)||R(e)||de(e)||fe(e)||pe(e)}e.isBoxedPrimitive=me;function he(e){return typeof Uint8Array<`u`&&(P(e)||ie(e))}e.isAnyArrayBuffer=he,[`isProxy`,`isExternal`,`isModuleNamespaceObject`].forEach(function(t){Object.defineProperty(e,t,{enumerable:!1,value:function(){throw Error(t+` is not supported in userland`)}})})})),Od=/* @__PURE__ */ t(((e,t)=>{t.exports=function(e){return e&&typeof e==`object`&&typeof e.copy==`function`&&typeof e.fill==`function`&&typeof e.readUInt8==`function`}})),kd=/* @__PURE__ */ t((e=>{var t=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),n={},r=0;r<t.length;r++)n[t[r]]=Object.getOwnPropertyDescriptor(e,t[r]);return n},n=/%[sdj%]/g;e.format=function(e){if(!x(e)){for(var t=[],r=0;r<arguments.length;r++)t.push(o(arguments[r]));return t.join(` `)}for(var r=1,i=arguments,a=i.length,s=String(e).replace(n,function(e){if(e===`%%`)return`%`;if(r>=a)return e;switch(e){case`%s`:return String(i[r++]);case`%d`:return Number(i[r++]);case`%j`:try{return JSON.stringify(i[r++])}catch{return`[Circular]`}default:return e}}),c=i[r];r<a;c=i[++r])v(c)||!T(c)?s+=` `+c:s+=` `+o(c);return s},e.deprecate=function(t,n){if(typeof process<`u`&&process.noDeprecation===!0)return t;if(typeof process>`u`)return function(){return e.deprecate(t,n).apply(this,arguments)};var r=!1;function i(){if(!r){if(process.throwDeprecation)throw Error(n);process.traceDeprecation?console.trace(n):console.error(n),r=!0}return t.apply(this,arguments)}return i};var r={},i=/^$/;if({}.NODE_DEBUG){var a={}.NODE_DEBUG;a=a.replace(/[|\\{}()[\]^$+?.]/g,`\\$&`).replace(/\*/g,`.*`).replace(/,/g,`$|^`).toUpperCase(),i=RegExp(`^`+a+`$`,`i`)}e.debuglog=function(t){if(t=t.toUpperCase(),!r[t]){if(i.test(t)){var n=process.pid;r[t]=function(){var r=e.format.apply(e,arguments);console.error(`%s %d: %s`,t,n,r)}}else r[t]=function(){}}return r[t]};function o(t,n){var r={seen:[],stylize:c};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),_(n)?r.showHidden=n:n&&e._extend(r,n),C(r.showHidden)&&(r.showHidden=!1),C(r.depth)&&(r.depth=2),C(r.colors)&&(r.colors=!1),C(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=s),u(r,t,r.depth)}e.inspect=o,o.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},o.styles={special:`cyan`,number:`yellow`,boolean:`yellow`,undefined:`grey`,null:`bold`,string:`green`,date:`magenta`,regexp:`red`};function s(e,t){var n=o.styles[t];return n?`\x1B[`+o.colors[n][0]+`m`+e+`\x1B[`+o.colors[n][1]+`m`:e}function c(e,t){return e}function l(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}function u(t,n,r){if(t.customInspect&&n&&O(n.inspect)&&n.inspect!==e.inspect&&!(n.constructor&&n.constructor.prototype===n)){var i=n.inspect(r,t);return x(i)||(i=u(t,i,r)),i}var a=d(t,n);if(a)return a;var o=Object.keys(n),s=l(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(n)),D(n)&&(o.indexOf(`message`)>=0||o.indexOf(`description`)>=0))return f(n);if(o.length===0){if(O(n)){var c=n.name?`: `+n.name:``;return t.stylize(`[Function`+c+`]`,`special`)}if(w(n))return t.stylize(RegExp.prototype.toString.call(n),`regexp`);if(E(n))return t.stylize(Date.prototype.toString.call(n),`date`);if(D(n))return f(n)}var _=``,v=!1,y=[`{`,`}`];if(g(n)&&(v=!0,y=[`[`,`]`]),O(n)&&(_=` [Function`+(n.name?`: `+n.name:``)+`]`),w(n)&&(_=` `+RegExp.prototype.toString.call(n)),E(n)&&(_=` `+Date.prototype.toUTCString.call(n)),D(n)&&(_=` `+f(n)),o.length===0&&(!v||n.length==0))return y[0]+_+y[1];if(r<0)return w(n)?t.stylize(RegExp.prototype.toString.call(n),`regexp`):t.stylize(`[Object]`,`special`);t.seen.push(n);var b=v?p(t,n,r,s,o):o.map(function(e){return m(t,n,r,s,e,v)});return t.seen.pop(),h(b,_,y)}function d(e,t){if(C(t))return e.stylize(`undefined`,`undefined`);if(x(t)){var n=`'`+JSON.stringify(t).replace(/^"|"$/g,``).replace(/'/g,`\\'`).replace(/\\"/g,`"`)+`'`;return e.stylize(n,`string`)}if(b(t))return e.stylize(``+t,`number`);if(_(t))return e.stylize(``+t,`boolean`);if(v(t))return e.stylize(`null`,`null`)}function f(e){return`[`+Error.prototype.toString.call(e)+`]`}function p(e,t,n,r,i){for(var a=[],o=0,s=t.length;o<s;++o)j(t,String(o))?a.push(m(e,t,n,r,String(o),!0)):a.push(``);return i.forEach(function(i){i.match(/^\d+$/)||a.push(m(e,t,n,r,i,!0))}),a}function m(e,t,n,r,i,a){var o,s,c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]};if(c.get?s=c.set?e.stylize(`[Getter/Setter]`,`special`):e.stylize(`[Getter]`,`special`):c.set&&(s=e.stylize(`[Setter]`,`special`)),j(r,i)||(o=`[`+i+`]`),s||(e.seen.indexOf(c.value)<0?(s=v(n)?u(e,c.value,null):u(e,c.value,n-1),s.indexOf(`
|
|
13
|
+
var t=Du(),n=Ou(),r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Symbol.for(`nodejs.util.inspect.custom`):null;e.Buffer=s,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50;var i=2147483647;e.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=a(),!s.TYPED_ARRAY_SUPPORT&&typeof console<`u`&&typeof console.error==`function`&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{var e=/* @__PURE__ */ new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function o(e){if(e>i)throw RangeError(`The value "`+e+`" is invalid for option "size"`);var t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if(typeof e==`number`){if(typeof t==`string`)throw TypeError(`The "string" argument must be of type string. Received type number`);return d(e)}return c(e,t,n)}s.poolSize=8192;function c(e,t,n){if(typeof e==`string`)return f(e,t);if(ArrayBuffer.isView(e))return m(e);if(e==null)throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e);if(R(e,ArrayBuffer)||e&&R(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<`u`&&(R(e,SharedArrayBuffer)||e&&R(e.buffer,SharedArrayBuffer)))return h(e,t,n);if(typeof e==`number`)throw TypeError(`The "value" argument must not be of type number. Received type number`);var r=e.valueOf&&e.valueOf();if(r!=null&&r!==e)return s.from(r,t,n);var i=g(e);if(i)return i;if(typeof Symbol<`u`&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]==`function`)return s.from(e[Symbol.toPrimitive](`string`),t,n);throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e)}s.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(e){if(typeof e!=`number`)throw TypeError(`"size" argument must be of type number`);if(e<0)throw RangeError(`The value "`+e+`" is invalid for option "size"`)}function u(e,t,n){return l(e),e<=0||t===void 0?o(e):typeof n==`string`?o(e).fill(t,n):o(e).fill(t)}s.alloc=function(e,t,n){return u(e,t,n)};function d(e){return l(e),o(e<0?0:_(e)|0)}s.allocUnsafe=function(e){return d(e)},s.allocUnsafeSlow=function(e){return d(e)};function f(e,t){if((typeof t!=`string`||t===``)&&(t=`utf8`),!s.isEncoding(t))throw TypeError(`Unknown encoding: `+t);var n=y(e,t)|0,r=o(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function p(e){for(var t=e.length<0?0:_(e.length)|0,n=o(t),r=0;r<t;r+=1)n[r]=e[r]&255;return n}function m(e){if(R(e,Uint8Array)){var t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return p(e)}function h(e,t,n){if(t<0||e.byteLength<t)throw RangeError(`"offset" is outside of buffer bounds`);if(e.byteLength<t+(n||0))throw RangeError(`"length" is outside of buffer bounds`);var r=t===void 0&&n===void 0?new Uint8Array(e):n===void 0?new Uint8Array(e,t):new Uint8Array(e,t,n);return Object.setPrototypeOf(r,s.prototype),r}function g(e){if(s.isBuffer(e)){var t=_(e.length)|0,n=o(t);return n.length===0||e.copy(n,0,0,t),n}if(e.length!==void 0)return typeof e.length!=`number`||de(e.length)?o(0):p(e);if(e.type===`Buffer`&&Array.isArray(e.data))return p(e.data)}function _(e){if(e>=i)throw RangeError(`Attempt to allocate Buffer larger than maximum size: 0x`+i.toString(16)+` bytes`);return e|0}function v(e){return+e!=e&&(e=0),s.alloc(+e)}s.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==s.prototype},s.compare=function(e,t){if(R(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),R(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw TypeError(`The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array`);if(e===t)return 0;for(var n=e.length,r=t.length,i=0,a=Math.min(n,r);i<a;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:+(r<n)},s.isEncoding=function(e){switch(String(e).toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`latin1`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw TypeError(`"list" argument must be an Array of Buffers`);if(e.length===0)return s.alloc(0);var n;if(t===void 0)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=s.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var a=e[n];if(R(a,Uint8Array))i+a.length>r.length?s.from(a).copy(r,i):Uint8Array.prototype.set.call(r,a,i);else if(s.isBuffer(a))a.copy(r,i);else throw TypeError(`"list" argument must be an Array of Buffers`);i+=a.length}return r};function y(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||R(e,ArrayBuffer))return e.byteLength;if(typeof e!=`string`)throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type `+typeof e);var n=e.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&n===0)return 0;for(var i=!1;;)switch(t){case`ascii`:case`latin1`:case`binary`:return n;case`utf8`:case`utf-8`:return oe(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return le(e).length;default:if(i)return r?-1:oe(e).length;t=(``+t).toLowerCase(),i=!0}}s.byteLength=y;function b(e,t,n){var r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,t>>>=0,n<=t))return``;for(e||=`utf8`;;)switch(e){case`hex`:return M(this,t,n);case`utf8`:case`utf-8`:return k(this,t,n);case`ascii`:return ne(this,t,n);case`latin1`:case`binary`:return j(this,t,n);case`base64`:return ee(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return N(this,t,n);default:if(r)throw TypeError(`Unknown encoding: `+e);e=(e+``).toLowerCase(),r=!0}}s.prototype._isBuffer=!0;function x(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}s.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(var t=0;t<e;t+=2)x(this,t,t+1);return this},s.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(var t=0;t<e;t+=4)x(this,t,t+3),x(this,t+1,t+2);return this},s.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(var t=0;t<e;t+=8)x(this,t,t+7),x(this,t+1,t+6),x(this,t+2,t+5),x(this,t+3,t+4);return this},s.prototype.toString=function(){var e=this.length;return e===0?``:arguments.length===0?k(this,0,e):b.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw TypeError(`Argument must be a Buffer`);return this===e||s.compare(this,e)===0},s.prototype.inspect=function(){var t=``,n=e.INSPECT_MAX_BYTES;return t=this.toString(`hex`,0,n).replace(/(.{2})/g,`$1 `).trim(),this.length>n&&(t+=` ... `),`<Buffer `+t+`>`},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(R(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw TypeError(`The "target" argument must be one of type Buffer or Uint8Array. Received type `+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),r===void 0&&(r=0),i===void 0&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw RangeError(`out of range index`);if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;for(var a=i-r,o=n-t,c=Math.min(a,o),l=this.slice(r,i),u=e.slice(t,n),d=0;d<c;++d)if(l[d]!==u[d]){a=l[d],o=u[d];break}return a<o?-1:+(o<a)};function S(e,t,n,r,i){if(e.length===0)return-1;if(typeof n==`string`?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,de(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(i)n=0;else return-1}if(typeof t==`string`&&(t=s.from(t,r)),s.isBuffer(t))return t.length===0?-1:C(e,t,n,r,i);if(typeof t==`number`)return t&=255,typeof Uint8Array.prototype.indexOf==`function`?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):C(e,[t],n,r,i);throw TypeError(`val must be string, number or Buffer`)}function C(e,t,n,r,i){var a=1,o=e.length,s=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r===`ucs2`||r===`ucs-2`||r===`utf16le`||r===`utf-16le`)){if(e.length<2||t.length<2)return-1;a=2,o/=2,s/=2,n/=2}function c(e,t){return a===1?e[t]:e.readUInt16BE(t*a)}var l;if(i){var u=-1;for(l=n;l<o;l++)if(c(e,l)===c(t,u===-1?0:l-u)){if(u===-1&&(u=l),l-u+1===s)return u*a}else u!==-1&&(l-=l-u),u=-1}else for(n+s>o&&(n=o-s),l=n;l>=0;l--){for(var d=!0,f=0;f<s;f++)if(c(e,l+f)!==c(t,f)){d=!1;break}if(d)return l}return-1}s.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1},s.prototype.indexOf=function(e,t,n){return S(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return S(this,e,t,n,!1)};function w(e,t,n,r){n=Number(n)||0;var i=e.length-n;r?(r=Number(r),r>i&&(r=i)):r=i;var a=t.length;r>a/2&&(r=a/2);for(var o=0;o<r;++o){var s=parseInt(t.substr(o*2,2),16);if(de(s))return o;e[n+o]=s}return o}function T(e,t,n,r){return ue(oe(t,e.length-n),e,n,r)}function E(e,t,n,r){return ue(se(t),e,n,r)}function D(e,t,n,r){return ue(le(t),e,n,r)}function O(e,t,n,r){return ue(ce(t,e.length-n),e,n,r)}s.prototype.write=function(e,t,n,r){if(t===void 0)r=`utf8`,n=this.length,t=0;else if(n===void 0&&typeof t==`string`)r=t,n=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(n)?(n>>>=0,r===void 0&&(r=`utf8`)):(r=n,n=void 0);else throw Error(`Buffer.write(string, encoding, offset[, length]) is no longer supported`);var i=this.length-t;if((n===void 0||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError(`Attempt to write outside buffer bounds`);r||=`utf8`;for(var a=!1;;)switch(r){case`hex`:return w(this,e,t,n);case`utf8`:case`utf-8`:return T(this,e,t,n);case`ascii`:case`latin1`:case`binary`:return E(this,e,t,n);case`base64`:return D(this,e,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return O(this,e,t,n);default:if(a)throw TypeError(`Unknown encoding: `+r);r=(``+r).toLowerCase(),a=!0}},s.prototype.toJSON=function(){return{type:`Buffer`,data:Array.prototype.slice.call(this._arr||this,0)}};function ee(e,n,r){return n===0&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function k(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i<n;){var a=e[i],o=null,s=a>239?4:a>223?3:a>191?2:1;if(i+s<=n){var c,l,u,d;switch(s){case 1:a<128&&(o=a);break;case 2:c=e[i+1],(c&192)==128&&(d=(a&31)<<6|c&63,d>127&&(o=d));break;case 3:c=e[i+1],l=e[i+2],(c&192)==128&&(l&192)==128&&(d=(a&15)<<12|(c&63)<<6|l&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:c=e[i+1],l=e[i+2],u=e[i+3],(c&192)==128&&(l&192)==128&&(u&192)==128&&(d=(a&15)<<18|(c&63)<<12|(l&63)<<6|u&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|o&1023),r.push(o),i+=s}return A(r)}var te=4096;function A(e){var t=e.length;if(t<=te)return String.fromCharCode.apply(String,e);for(var n=``,r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=te));return n}function ne(e,t,n){var r=``;n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(e[i]&127);return r}function j(e,t,n){var r=``;n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function M(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var i=``,a=t;a<n;++a)i+=fe[e[a]];return i}function N(e,t,n){for(var r=e.slice(t,n),i=``,a=0;a<r.length-1;a+=2)i+=String.fromCharCode(r[a]+r[a+1]*256);return i}s.prototype.slice=function(e,t){var n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r};function P(e,t,n){if(e%1!=0||e<0)throw RangeError(`offset is not uint`);if(e+t>n)throw RangeError(`Trying to access beyond buffer length`)}s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=this[e],i=1,a=0;++a<t&&(i*=256);)r+=this[e+a]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=this[e+--t],i=1;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=this[e],i=1,a=0;++a<t&&(i*=256);)r+=this[e+a]*i;return i*=128,r>=i&&(r-=2**(8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||P(e,t,this.length);for(var r=t,i=1,a=this[e+--r];r>0&&(i*=256);)a+=this[e+--r]*i;return i*=128,a>=i&&(a-=2**(8*t)),a},s.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),n.read(this,e,!1,52,8)};function F(e,t,n,r,i,a){if(!s.isBuffer(e))throw TypeError(`"buffer" argument must be a Buffer instance`);if(t>i||t<a)throw RangeError(`"value" argument is out of bounds`);if(n+r>e.length)throw RangeError(`Index out of range`)}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){var i=2**(8*n)-1;F(this,e,t,n,i,0)}var a=1,o=0;for(this[t]=e&255;++o<n&&(a*=256);)this[t+o]=e/a&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){var i=2**(8*n)-1;F(this,e,t,n,i,0)}var a=n-1,o=1;for(this[t+a]=e&255;--a>=0&&(o*=256);)this[t+a]=e/o&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,1,255,0),this[t]=e&255,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=2**(8*n-1);F(this,e,t,n,i-1,-i)}var a=0,o=1,s=0;for(this[t]=e&255;++a<n&&(o*=256);)e<0&&s===0&&this[t+a-1]!==0&&(s=1),this[t+a]=(e/o>>0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=2**(8*n-1);F(this,e,t,n,i-1,-i)}var a=n-1,o=1,s=0;for(this[t+a]=e&255;--a>=0&&(o*=256);)e<0&&s===0&&this[t+a+1]!==0&&(s=1),this[t+a]=(e/o>>0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function re(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function I(e,t,r,i,a){return t=+t,r>>>=0,a||re(e,t,r,4,34028234663852886e22,-34028234663852886e22),n.write(e,t,r,i,23,4),r+4}s.prototype.writeFloatLE=function(e,t,n){return I(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return I(this,e,t,!1,n)};function L(e,t,r,i,a){return t=+t,r>>>=0,a||re(e,t,r,8,17976931348623157e292,-17976931348623157e292),n.write(e,t,r,i,52,8),r+8}s.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw TypeError(`argument should be a Buffer`);if(n||=0,!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||=0,r>0&&r<n&&(r=n),r===n||e.length===0||this.length===0)return 0;if(t<0)throw RangeError(`targetStart out of bounds`);if(n<0||n>=this.length)throw RangeError(`Index out of range`);if(r<0)throw RangeError(`sourceEnd out of bounds`);r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var i=r-n;return this===e&&typeof Uint8Array.prototype.copyWithin==`function`?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),i},s.prototype.fill=function(e,t,n,r){if(typeof e==`string`){if(typeof t==`string`?(r=t,t=0,n=this.length):typeof n==`string`&&(r=n,n=this.length),r!==void 0&&typeof r!=`string`)throw TypeError(`encoding must be a string`);if(typeof r==`string`&&!s.isEncoding(r))throw TypeError(`Unknown encoding: `+r);if(e.length===1){var i=e.charCodeAt(0);(r===`utf8`&&i<128||r===`latin1`)&&(e=i)}}else typeof e==`number`?e&=255:typeof e==`boolean`&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw RangeError(`Out of range index`);if(n<=t)return this;t>>>=0,n=n===void 0?this.length:n>>>0,e||=0;var a;if(typeof e==`number`)for(a=t;a<n;++a)this[a]=e;else{var o=s.isBuffer(e)?e:s.from(e,r),c=o.length;if(c===0)throw TypeError(`The value "`+e+`" is invalid for argument "value"`);for(a=0;a<n-t;++a)this[a+t]=o[a%c]}return this};var ie=/[^+/0-9A-Za-z-_]/g;function ae(e){if(e=e.split(`=`)[0],e=e.trim().replace(ie,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function oe(e,t){t||=1/0;for(var n,r=e.length,i=null,a=[],o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if(--t<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,n&63|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw Error(`Invalid code point`)}return a}function se(e){for(var t=[],n=0;n<e.length;++n)t.push(e.charCodeAt(n)&255);return t}function ce(e,t){for(var n,r,i,a=[],o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,i=n%256,a.push(i),a.push(r);return a}function le(e){return t.toByteArray(ae(e))}function ue(e,t,n,r){for(var i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function R(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function de(e){return e!==e}var fe=(function(){for(var e=`0123456789abcdef`,t=Array(256),n=0;n<16;++n)for(var r=n*16,i=0;i<16;++i)t[r+i]=e[n]+e[i];return t})()})),Au=/* @__PURE__ */ t(((e,t)=>{t.exports=function(){if(typeof Symbol!=`function`||typeof Object.getOwnPropertySymbols!=`function`)return!1;if(typeof Symbol.iterator==`symbol`)return!0;var e={},t=Symbol(`test`),n=Object(t);if(typeof t==`string`||Object.prototype.toString.call(t)!==`[object Symbol]`||Object.prototype.toString.call(n)!==`[object Symbol]`)return!1;var r=42;for(var i in e[t]=r,e)return!1;if(typeof Object.keys==`function`&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames==`function`&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==t||!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if(typeof Object.getOwnPropertyDescriptor==`function`){var o=Object.getOwnPropertyDescriptor(e,t);if(o.value!==r||o.enumerable!==!0)return!1}return!0}})),ju=/* @__PURE__ */ t(((e,t)=>{var n=Au();t.exports=function(){return n()&&!!Symbol.toStringTag}})),Mu=/* @__PURE__ */ t(((e,t)=>{t.exports=Object})),Nu=/* @__PURE__ */ t(((e,t)=>{t.exports=Error})),Pu=/* @__PURE__ */ t(((e,t)=>{t.exports=EvalError})),Fu=/* @__PURE__ */ t(((e,t)=>{t.exports=RangeError})),Iu=/* @__PURE__ */ t(((e,t)=>{t.exports=ReferenceError})),Lu=/* @__PURE__ */ t(((e,t)=>{t.exports=SyntaxError})),Ru=/* @__PURE__ */ t(((e,t)=>{t.exports=TypeError})),zu=/* @__PURE__ */ t(((e,t)=>{t.exports=URIError})),Bu=/* @__PURE__ */ t(((e,t)=>{t.exports=Math.abs})),Vu=/* @__PURE__ */ t(((e,t)=>{t.exports=Math.floor})),Hu=/* @__PURE__ */ t(((e,t)=>{t.exports=Math.max})),Uu=/* @__PURE__ */ t(((e,t)=>{t.exports=Math.min})),Wu=/* @__PURE__ */ t(((e,t)=>{t.exports=Math.pow})),Gu=/* @__PURE__ */ t(((e,t)=>{t.exports=Math.round})),Ku=/* @__PURE__ */ t(((e,t)=>{t.exports=Number.isNaN||function(e){return e!==e}})),qu=/* @__PURE__ */ t(((e,t)=>{var n=Ku();t.exports=function(e){return n(e)||e===0?e:e<0?-1:1}})),Ju=/* @__PURE__ */ t(((e,t)=>{t.exports=Object.getOwnPropertyDescriptor})),Yu=/* @__PURE__ */ t(((e,t)=>{var n=Ju();if(n)try{n([],`length`)}catch{n=null}t.exports=n})),Xu=/* @__PURE__ */ t(((e,t)=>{var n=Object.defineProperty||!1;if(n)try{n({},`a`,{value:1})}catch{n=!1}t.exports=n})),Zu=/* @__PURE__ */ t(((e,t)=>{var n=typeof Symbol<`u`&&Symbol,r=Au();t.exports=function(){return typeof n!=`function`||typeof Symbol!=`function`||typeof n(`foo`)!=`symbol`||typeof Symbol(`bar`)!=`symbol`?!1:r()}})),Qu=/* @__PURE__ */ t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect.getPrototypeOf||null})),$u=/* @__PURE__ */ t(((e,t)=>{t.exports=Mu().getPrototypeOf||null})),ed=/* @__PURE__ */ t(((e,t)=>{var n=Object.prototype.toString,r=Math.max,i=`[object Function]`,a=function(e,t){for(var n=[],r=0;r<e.length;r+=1)n[r]=e[r];for(var i=0;i<t.length;i+=1)n[i+e.length]=t[i];return n},o=function(e,t){for(var n=[],r=t||0,i=0;r<e.length;r+=1,i+=1)n[i]=e[r];return n},s=function(e,t){for(var n=``,r=0;r<e.length;r+=1)n+=e[r],r+1<e.length&&(n+=t);return n};t.exports=function(e){var t=this;if(typeof t!=`function`||n.apply(t)!==i)throw TypeError(`Function.prototype.bind called on incompatible `+t);for(var c=o(arguments,1),l,u=function(){if(this instanceof l){var n=t.apply(this,a(c,arguments));return Object(n)===n?n:this}return t.apply(e,a(c,arguments))},d=r(0,t.length-c.length),f=[],p=0;p<d;p++)f[p]=`$`+p;if(l=Function(`binder`,`return function (`+s(f,`,`)+`){ return binder.apply(this,arguments); }`)(u),t.prototype){var m=function(){};m.prototype=t.prototype,l.prototype=new m,m.prototype=null}return l}})),td=/* @__PURE__ */ t(((e,t)=>{var n=ed();t.exports=Function.prototype.bind||n})),nd=/* @__PURE__ */ t(((e,t)=>{t.exports=Function.prototype.call})),rd=/* @__PURE__ */ t(((e,t)=>{t.exports=Function.prototype.apply})),id=/* @__PURE__ */ t(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect&&Reflect.apply})),ad=/* @__PURE__ */ t(((e,t)=>{var n=td(),r=rd(),i=nd();t.exports=id()||n.call(i,r)})),od=/* @__PURE__ */ t(((e,t)=>{var n=td(),r=Ru(),i=nd(),a=ad();t.exports=function(e){if(e.length<1||typeof e[0]!=`function`)throw new r(`a function is required`);return a(n,i,e)}})),sd=/* @__PURE__ */ t(((e,t)=>{var n=od(),r=Yu(),i;try{i=[].__proto__===Array.prototype}catch(e){if(!e||typeof e!=`object`||!(`code`in e)||e.code!==`ERR_PROTO_ACCESS`)throw e}var a=!!i&&r&&r(Object.prototype,`__proto__`),o=Object,s=o.getPrototypeOf;t.exports=a&&typeof a.get==`function`?n([a.get]):typeof s==`function`&&function(e){return s(e==null?e:o(e))}})),cd=/* @__PURE__ */ t(((e,t)=>{var n=Qu(),r=$u(),i=sd();t.exports=n?function(e){return n(e)}:r?function(e){if(!e||typeof e!=`object`&&typeof e!=`function`)throw TypeError(`getProto: not an object`);return r(e)}:i?function(e){return i(e)}:null})),ld=/* @__PURE__ */ t(((e,t)=>{var n=Function.prototype.call,r=Object.prototype.hasOwnProperty;t.exports=td().call(n,r)})),ud=/* @__PURE__ */ t(((e,t)=>{var n,r=Mu(),i=Nu(),a=Pu(),o=Fu(),s=Iu(),c=Lu(),l=Ru(),u=zu(),d=Bu(),f=Vu(),p=Hu(),m=Uu(),h=Wu(),g=Gu(),_=qu(),v=Function,y=function(e){try{return v(`"use strict"; return (`+e+`).constructor;`)()}catch{}},b=Yu(),x=Xu(),S=function(){throw new l},C=b?function(){try{return arguments.callee,S}catch{try{return b(arguments,`callee`).get}catch{return S}}}():S,w=Zu()(),T=cd(),E=$u(),D=Qu(),O=rd(),ee=nd(),k={},te=typeof Uint8Array>`u`||!T?n:T(Uint8Array),A={__proto__:null,"%AggregateError%":typeof AggregateError>`u`?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>`u`?n:ArrayBuffer,"%ArrayIteratorPrototype%":w&&T?T([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":k,"%AsyncGenerator%":k,"%AsyncGeneratorFunction%":k,"%AsyncIteratorPrototype%":k,"%Atomics%":typeof Atomics>`u`?n:Atomics,"%BigInt%":typeof BigInt>`u`?n:BigInt,"%BigInt64Array%":typeof BigInt64Array>`u`?n:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>`u`?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>`u`?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":a,"%Float16Array%":typeof Float16Array>`u`?n:Float16Array,"%Float32Array%":typeof Float32Array>`u`?n:Float32Array,"%Float64Array%":typeof Float64Array>`u`?n:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>`u`?n:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":k,"%Int8Array%":typeof Int8Array>`u`?n:Int8Array,"%Int16Array%":typeof Int16Array>`u`?n:Int16Array,"%Int32Array%":typeof Int32Array>`u`?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":w&&T?T(T([][Symbol.iterator]())):n,"%JSON%":typeof JSON==`object`?JSON:n,"%Map%":typeof Map>`u`?n:Map,"%MapIteratorPrototype%":typeof Map>`u`||!w||!T?n:T((/* @__PURE__ */ new Map())[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":r,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>`u`?n:Promise,"%Proxy%":typeof Proxy>`u`?n:Proxy,"%RangeError%":o,"%ReferenceError%":s,"%Reflect%":typeof Reflect>`u`?n:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>`u`?n:Set,"%SetIteratorPrototype%":typeof Set>`u`||!w||!T?n:T((/* @__PURE__ */ new Set())[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>`u`?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":w&&T?T(``[Symbol.iterator]()):n,"%Symbol%":w?Symbol:n,"%SyntaxError%":c,"%ThrowTypeError%":C,"%TypedArray%":te,"%TypeError%":l,"%Uint8Array%":typeof Uint8Array>`u`?n:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>`u`?n:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>`u`?n:Uint16Array,"%Uint32Array%":typeof Uint32Array>`u`?n:Uint32Array,"%URIError%":u,"%WeakMap%":typeof WeakMap>`u`?n:WeakMap,"%WeakRef%":typeof WeakRef>`u`?n:WeakRef,"%WeakSet%":typeof WeakSet>`u`?n:WeakSet,"%Function.prototype.call%":ee,"%Function.prototype.apply%":O,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":E,"%Math.abs%":d,"%Math.floor%":f,"%Math.max%":p,"%Math.min%":m,"%Math.pow%":h,"%Math.round%":g,"%Math.sign%":_,"%Reflect.getPrototypeOf%":D};if(T)try{null.error}catch(e){A[`%Error.prototype%`]=T(T(e))}var ne=function e(t){var n;if(t===`%AsyncFunction%`)n=y(`async function () {}`);else if(t===`%GeneratorFunction%`)n=y(`function* () {}`);else if(t===`%AsyncGeneratorFunction%`)n=y(`async function* () {}`);else if(t===`%AsyncGenerator%`){var r=e(`%AsyncGeneratorFunction%`);r&&(n=r.prototype)}else if(t===`%AsyncIteratorPrototype%`){var i=e(`%AsyncGenerator%`);i&&T&&(n=T(i.prototype))}return A[t]=n,n},j={__proto__:null,"%ArrayBufferPrototype%":[`ArrayBuffer`,`prototype`],"%ArrayPrototype%":[`Array`,`prototype`],"%ArrayProto_entries%":[`Array`,`prototype`,`entries`],"%ArrayProto_forEach%":[`Array`,`prototype`,`forEach`],"%ArrayProto_keys%":[`Array`,`prototype`,`keys`],"%ArrayProto_values%":[`Array`,`prototype`,`values`],"%AsyncFunctionPrototype%":[`AsyncFunction`,`prototype`],"%AsyncGenerator%":[`AsyncGeneratorFunction`,`prototype`],"%AsyncGeneratorPrototype%":[`AsyncGeneratorFunction`,`prototype`,`prototype`],"%BooleanPrototype%":[`Boolean`,`prototype`],"%DataViewPrototype%":[`DataView`,`prototype`],"%DatePrototype%":[`Date`,`prototype`],"%ErrorPrototype%":[`Error`,`prototype`],"%EvalErrorPrototype%":[`EvalError`,`prototype`],"%Float32ArrayPrototype%":[`Float32Array`,`prototype`],"%Float64ArrayPrototype%":[`Float64Array`,`prototype`],"%FunctionPrototype%":[`Function`,`prototype`],"%Generator%":[`GeneratorFunction`,`prototype`],"%GeneratorPrototype%":[`GeneratorFunction`,`prototype`,`prototype`],"%Int8ArrayPrototype%":[`Int8Array`,`prototype`],"%Int16ArrayPrototype%":[`Int16Array`,`prototype`],"%Int32ArrayPrototype%":[`Int32Array`,`prototype`],"%JSONParse%":[`JSON`,`parse`],"%JSONStringify%":[`JSON`,`stringify`],"%MapPrototype%":[`Map`,`prototype`],"%NumberPrototype%":[`Number`,`prototype`],"%ObjectPrototype%":[`Object`,`prototype`],"%ObjProto_toString%":[`Object`,`prototype`,`toString`],"%ObjProto_valueOf%":[`Object`,`prototype`,`valueOf`],"%PromisePrototype%":[`Promise`,`prototype`],"%PromiseProto_then%":[`Promise`,`prototype`,`then`],"%Promise_all%":[`Promise`,`all`],"%Promise_reject%":[`Promise`,`reject`],"%Promise_resolve%":[`Promise`,`resolve`],"%RangeErrorPrototype%":[`RangeError`,`prototype`],"%ReferenceErrorPrototype%":[`ReferenceError`,`prototype`],"%RegExpPrototype%":[`RegExp`,`prototype`],"%SetPrototype%":[`Set`,`prototype`],"%SharedArrayBufferPrototype%":[`SharedArrayBuffer`,`prototype`],"%StringPrototype%":[`String`,`prototype`],"%SymbolPrototype%":[`Symbol`,`prototype`],"%SyntaxErrorPrototype%":[`SyntaxError`,`prototype`],"%TypedArrayPrototype%":[`TypedArray`,`prototype`],"%TypeErrorPrototype%":[`TypeError`,`prototype`],"%Uint8ArrayPrototype%":[`Uint8Array`,`prototype`],"%Uint8ClampedArrayPrototype%":[`Uint8ClampedArray`,`prototype`],"%Uint16ArrayPrototype%":[`Uint16Array`,`prototype`],"%Uint32ArrayPrototype%":[`Uint32Array`,`prototype`],"%URIErrorPrototype%":[`URIError`,`prototype`],"%WeakMapPrototype%":[`WeakMap`,`prototype`],"%WeakSetPrototype%":[`WeakSet`,`prototype`]},M=td(),N=ld(),P=M.call(ee,Array.prototype.concat),F=M.call(O,Array.prototype.splice),re=M.call(ee,String.prototype.replace),I=M.call(ee,String.prototype.slice),L=M.call(ee,RegExp.prototype.exec),ie=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,ae=/\\(\\)?/g,oe=function(e){var t=I(e,0,1),n=I(e,-1);if(t===`%`&&n!==`%`)throw new c("invalid intrinsic syntax, expected closing `%`");if(n===`%`&&t!==`%`)throw new c("invalid intrinsic syntax, expected opening `%`");var r=[];return re(e,ie,function(e,t,n,i){r[r.length]=n?re(i,ae,`$1`):t||e}),r},se=function(e,t){var n=e,r;if(N(j,n)&&(r=j[n],n=`%`+r[0]+`%`),N(A,n)){var i=A[n];if(i===k&&(i=ne(n)),i===void 0&&!t)throw new l(`intrinsic `+e+` exists, but is not available. Please file an issue!`);return{alias:r,name:n,value:i}}throw new c(`intrinsic `+e+` does not exist!`)};t.exports=function(e,t){if(typeof e!=`string`||e.length===0)throw new l(`intrinsic name must be a non-empty string`);if(arguments.length>1&&typeof t!=`boolean`)throw new l(`"allowMissing" argument must be a boolean`);if(L(/^%?[^%]*%?$/,e)===null)throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=oe(e),r=n.length>0?n[0]:``,i=se(`%`+r+`%`,t),a=i.name,o=i.value,s=!1,u=i.alias;u&&(r=u[0],F(n,P([0,1],u)));for(var d=1,f=!0;d<n.length;d+=1){var p=n[d],m=I(p,0,1),h=I(p,-1);if((m===`"`||m===`'`||m==="`"||h===`"`||h===`'`||h==="`")&&m!==h)throw new c(`property names with quotes must have matching quotes`);if((p===`constructor`||!f)&&(s=!0),r+=`.`+p,a=`%`+r+`%`,N(A,a))o=A[a];else if(o!=null){if(!(p in o)){if(!t)throw new l(`base intrinsic for `+e+` exists, but the property is not available.`);return}if(b&&d+1>=n.length){var g=b(o,p);f=!!g,o=f&&`get`in g&&!(`originalValue`in g.get)?g.get:o[p]}else f=N(o,p),o=o[p];f&&!s&&(A[a]=o)}}return o}})),dd=/* @__PURE__ */ t(((e,t)=>{var n=ud(),r=od(),i=r([n(`%String.prototype.indexOf%`)]);t.exports=function(e,t){var a=n(e,!!t);return typeof a==`function`&&i(e,`.prototype.`)>-1?r([a]):a}})),fd=/* @__PURE__ */ t(((e,t)=>{var n=ju()(),r=dd()(`Object.prototype.toString`),i=function(e){return n&&e&&typeof e==`object`&&Symbol.toStringTag in e?!1:r(e)===`[object Arguments]`},a=function(e){return i(e)?!0:typeof e==`object`&&!!e&&`length`in e&&typeof e.length==`number`&&e.length>=0&&r(e)!==`[object Array]`&&`callee`in e&&r(e.callee)===`[object Function]`},o=function(){return i(arguments)}();i.isLegacyArguments=a,t.exports=o?i:a})),pd=/* @__PURE__ */ t(((e,t)=>{var n=dd(),r=ju()(),i=ld(),a=Yu(),o;if(r){var s=n(`RegExp.prototype.exec`),c={},l=function(){throw c},u={toString:l,valueOf:l};typeof Symbol.toPrimitive==`symbol`&&(u[Symbol.toPrimitive]=l),o=function(e){if(!e||typeof e!=`object`)return!1;var t=a(e,`lastIndex`);if(!(t&&i(t,`value`)))return!1;try{s(e,u)}catch(e){return e===c}}}else{var d=n(`Object.prototype.toString`),f=`[object RegExp]`;o=function(e){return!e||typeof e!=`object`&&typeof e!=`function`?!1:d(e)===f}}t.exports=o})),md=/* @__PURE__ */ t(((e,t)=>{var n=dd(),r=pd(),i=n(`RegExp.prototype.exec`),a=Ru();t.exports=function(e){if(!r(e))throw new a("`regex` must be a RegExp");return function(t){return i(e,t)!==null}}})),hd=/* @__PURE__ */ t(((e,t)=>{let n=function*(){}.constructor;t.exports=()=>n})),gd=/* @__PURE__ */ t(((e,t)=>{var n=dd(),r=md()(/^\s*(?:function)?\*/),i=ju()(),a=cd(),o=n(`Object.prototype.toString`),s=n(`Function.prototype.toString`),c=hd();t.exports=function(e){if(typeof e!=`function`)return!1;if(r(s(e)))return!0;if(!i)return o(e)===`[object GeneratorFunction]`;if(!a)return!1;var t=c();return t&&a(e)===t.prototype}})),_d=/* @__PURE__ */ t(((e,t)=>{var n=Function.prototype.toString,r=typeof Reflect==`object`&&Reflect!==null&&Reflect.apply,i,a;if(typeof r==`function`&&typeof Object.defineProperty==`function`)try{i=Object.defineProperty({},"length",{get:function(){throw a}}),a={},r(function(){throw 42},null,i)}catch(e){e!==a&&(r=null)}else r=null;var o=/^\s*class\b/,s=function(e){try{var t=n.call(e);return o.test(t)}catch{return!1}},c=function(e){try{return!s(e)&&(n.call(e),!0)}catch{return!1}},l=Object.prototype.toString,u=`[object Object]`,d=`[object Function]`,f=`[object GeneratorFunction]`,p=`[object HTMLAllCollection]`,m=`[object HTML document.all class]`,h=`[object HTMLCollection]`,g=typeof Symbol==`function`&&!!Symbol.toStringTag,_=!(0 in[,]),v=function(){return!1};if(typeof document==`object`){var y=document.all;l.call(y)===l.call(document.all)&&(v=function(e){if((_||!e)&&(e===void 0||typeof e==`object`))try{var t=l.call(e);return(t===p||t===m||t===h||t===u)&&e(``)==null}catch{}return!1})}t.exports=r?function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;try{r(e,null,i)}catch(e){if(e!==a)return!1}return!s(e)&&c(e)}:function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;if(g)return c(e);if(s(e))return!1;var t=l.call(e);return t!==d&&t!==f&&!/^\[object HTML/.test(t)?!1:c(e)}})),vd=/* @__PURE__ */ t(((e,t)=>{var n=_d(),r=Object.prototype.toString,i=Object.prototype.hasOwnProperty,a=function(e,t,n){for(var r=0,a=e.length;r<a;r++)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))},o=function(e,t,n){for(var r=0,i=e.length;r<i;r++)n==null?t(e.charAt(r),r,e):t.call(n,e.charAt(r),r,e)},s=function(e,t,n){for(var r in e)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))};function c(e){return r.call(e)===`[object Array]`}t.exports=function(e,t,r){if(!n(t))throw TypeError(`iterator must be a function`);var i;arguments.length>=3&&(i=r),c(e)?a(e,t,i):typeof e==`string`?o(e,t,i):s(e,t,i)}})),yd=/* @__PURE__ */ t(((e,t)=>{t.exports=[`Float16Array`,`Float32Array`,`Float64Array`,`Int8Array`,`Int16Array`,`Int32Array`,`Uint8Array`,`Uint8ClampedArray`,`Uint16Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`]})),bd=/* @__PURE__ */ t(((e,t)=>{var n=yd(),r=typeof globalThis>`u`?global:globalThis;t.exports=function(){for(var e=[],t=0;t<n.length;t++)typeof r[n[t]]==`function`&&(e[e.length]=n[t]);return e}})),xd=/* @__PURE__ */ t(((e,t)=>{var n=Xu(),r=Lu(),i=Ru(),a=Yu();t.exports=function(e,t,o){if(!e||typeof e!=`object`&&typeof e!=`function`)throw new i("`obj` must be an object or a function`");if(typeof t!=`string`&&typeof t!=`symbol`)throw new i("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!=`boolean`&&arguments[3]!==null)throw new i("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!=`boolean`&&arguments[4]!==null)throw new i("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!=`boolean`&&arguments[5]!==null)throw new i("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!=`boolean`)throw new i("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,u=arguments.length>6&&arguments[6],d=!!a&&a(e,t);if(n)n(e,t,{configurable:l===null&&d?d.configurable:!l,enumerable:s===null&&d?d.enumerable:!s,value:o,writable:c===null&&d?d.writable:!c});else if(u||!s&&!c&&!l)e[t]=o;else throw new r(`This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.`)}})),Sd=/* @__PURE__ */ t(((e,t)=>{var n=Xu(),r=function(){return!!n};r.hasArrayLengthDefineBug=function(){if(!n)return null;try{return n([],`length`,{value:1}).length!==1}catch{return!0}},t.exports=r})),Cd=/* @__PURE__ */ t(((e,t)=>{var n=ud(),r=xd(),i=Sd()(),a=Yu(),o=Ru(),s=n(`%Math.floor%`);t.exports=function(e,t){if(typeof e!=`function`)throw new o("`fn` is not a function");if(typeof t!=`number`||t<0||t>4294967295||s(t)!==t)throw new o("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],c=!0,l=!0;if(`length`in e&&a){var u=a(e,`length`);u&&!u.configurable&&(c=!1),u&&!u.writable&&(l=!1)}return(c||l||!n)&&(i?r(e,`length`,t,!0,!0):r(e,`length`,t)),e}})),wd=/* @__PURE__ */ t(((e,t)=>{var n=td(),r=rd(),i=ad();t.exports=function(){return i(n,r,arguments)}})),Td=/* @__PURE__ */ t(((e,t)=>{var n=Cd(),r=Xu(),i=od(),a=wd();t.exports=function(e){var t=i(arguments),r=e.length-(arguments.length-1);return n(t,1+(r>0?r:0),!0)},r?r(t.exports,`apply`,{value:a}):t.exports.apply=a})),Ed=/* @__PURE__ */ t(((e,t)=>{var n=vd(),r=bd(),i=Td(),a=dd(),o=Yu(),s=cd(),c=a(`Object.prototype.toString`),l=ju()(),u=typeof globalThis>`u`?global:globalThis,d=r(),f=a(`String.prototype.slice`),p=a(`Array.prototype.indexOf`,!0)||function(e,t){for(var n=0;n<e.length;n+=1)if(e[n]===t)return n;return-1},m={__proto__:null};l&&o&&s?n(d,function(e){var t=new u[e];if(Symbol.toStringTag in t&&s){var n=s(t),r=o(n,Symbol.toStringTag);!r&&n&&(r=o(s(n),Symbol.toStringTag)),m[`$`+e]=i(r.get)}}):n(d,function(e){var t=new u[e],n=t.slice||t.set;n&&(m[`$`+e]=i(n))});var h=function(e){var t=!1;return n(m,function(n,r){if(!t)try{`$`+n(e)===r&&(t=f(r,1))}catch{}}),t},g=function(e){var t=!1;return n(m,function(n,r){if(!t)try{n(e),t=f(r,1)}catch{}}),t};t.exports=function(e){if(!e||typeof e!=`object`)return!1;if(!l){var t=f(c(e),8,-1);return p(d,t)>-1?t:t===`Object`&&g(e)}return o?h(e):null}})),Dd=/* @__PURE__ */ t(((e,t)=>{var n=Ed();t.exports=function(e){return!!n(e)}})),Od=/* @__PURE__ */ t((e=>{var t=fd(),n=gd(),r=Ed(),i=Dd();function a(e){return e.call.bind(e)}var o=typeof BigInt<`u`,s=typeof Symbol<`u`,c=a(Object.prototype.toString),l=a(Number.prototype.valueOf),u=a(String.prototype.valueOf),d=a(Boolean.prototype.valueOf);if(o)var f=a(BigInt.prototype.valueOf);if(s)var p=a(Symbol.prototype.valueOf);function m(e,t){if(typeof e!=`object`)return!1;try{return t(e),!0}catch{return!1}}e.isArgumentsObject=t,e.isGeneratorFunction=n,e.isTypedArray=i;function h(e){return typeof Promise<`u`&&e instanceof Promise||typeof e==`object`&&!!e&&typeof e.then==`function`&&typeof e.catch==`function`}e.isPromise=h;function g(e){return typeof ArrayBuffer<`u`&&ArrayBuffer.isView?ArrayBuffer.isView(e):i(e)||re(e)}e.isArrayBufferView=g;function _(e){return r(e)===`Uint8Array`}e.isUint8Array=_;function v(e){return r(e)===`Uint8ClampedArray`}e.isUint8ClampedArray=v;function y(e){return r(e)===`Uint16Array`}e.isUint16Array=y;function b(e){return r(e)===`Uint32Array`}e.isUint32Array=b;function x(e){return r(e)===`Int8Array`}e.isInt8Array=x;function S(e){return r(e)===`Int16Array`}e.isInt16Array=S;function C(e){return r(e)===`Int32Array`}e.isInt32Array=C;function w(e){return r(e)===`Float32Array`}e.isFloat32Array=w;function T(e){return r(e)===`Float64Array`}e.isFloat64Array=T;function E(e){return r(e)===`BigInt64Array`}e.isBigInt64Array=E;function D(e){return r(e)===`BigUint64Array`}e.isBigUint64Array=D;function O(e){return c(e)===`[object Map]`}O.working=typeof Map<`u`&&O(/* @__PURE__ */ new Map);function ee(e){return typeof Map>`u`?!1:O.working?O(e):e instanceof Map}e.isMap=ee;function k(e){return c(e)===`[object Set]`}k.working=typeof Set<`u`&&k(/* @__PURE__ */ new Set);function te(e){return typeof Set>`u`?!1:k.working?k(e):e instanceof Set}e.isSet=te;function A(e){return c(e)===`[object WeakMap]`}A.working=typeof WeakMap<`u`&&A(/* @__PURE__ */ new WeakMap);function ne(e){return typeof WeakMap>`u`?!1:A.working?A(e):e instanceof WeakMap}e.isWeakMap=ne;function j(e){return c(e)===`[object WeakSet]`}j.working=typeof WeakSet<`u`&&j(/* @__PURE__ */ new WeakSet);function M(e){return j(e)}e.isWeakSet=M;function N(e){return c(e)===`[object ArrayBuffer]`}N.working=typeof ArrayBuffer<`u`&&N(/* @__PURE__ */ new ArrayBuffer);function P(e){return typeof ArrayBuffer>`u`?!1:N.working?N(e):e instanceof ArrayBuffer}e.isArrayBuffer=P;function F(e){return c(e)===`[object DataView]`}F.working=typeof ArrayBuffer<`u`&&typeof DataView<`u`&&F(new DataView(/* @__PURE__ */ new ArrayBuffer(1),0,1));function re(e){return typeof DataView>`u`?!1:F.working?F(e):e instanceof DataView}e.isDataView=re;var I=typeof SharedArrayBuffer<`u`?SharedArrayBuffer:void 0;function L(e){return c(e)===`[object SharedArrayBuffer]`}function ie(e){return I!==void 0&&(L.working===void 0&&(L.working=L(new I)),L.working?L(e):e instanceof I)}e.isSharedArrayBuffer=ie;function ae(e){return c(e)===`[object AsyncFunction]`}e.isAsyncFunction=ae;function oe(e){return c(e)===`[object Map Iterator]`}e.isMapIterator=oe;function se(e){return c(e)===`[object Set Iterator]`}e.isSetIterator=se;function ce(e){return c(e)===`[object Generator]`}e.isGeneratorObject=ce;function le(e){return c(e)===`[object WebAssembly.Module]`}e.isWebAssemblyCompiledModule=le;function ue(e){return m(e,l)}e.isNumberObject=ue;function R(e){return m(e,u)}e.isStringObject=R;function de(e){return m(e,d)}e.isBooleanObject=de;function fe(e){return o&&m(e,f)}e.isBigIntObject=fe;function pe(e){return s&&m(e,p)}e.isSymbolObject=pe;function me(e){return ue(e)||R(e)||de(e)||fe(e)||pe(e)}e.isBoxedPrimitive=me;function he(e){return typeof Uint8Array<`u`&&(P(e)||ie(e))}e.isAnyArrayBuffer=he,[`isProxy`,`isExternal`,`isModuleNamespaceObject`].forEach(function(t){Object.defineProperty(e,t,{enumerable:!1,value:function(){throw Error(t+` is not supported in userland`)}})})})),kd=/* @__PURE__ */ t(((e,t)=>{t.exports=function(e){return e&&typeof e==`object`&&typeof e.copy==`function`&&typeof e.fill==`function`&&typeof e.readUInt8==`function`}})),Ad=/* @__PURE__ */ t((e=>{var t=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),n={},r=0;r<t.length;r++)n[t[r]]=Object.getOwnPropertyDescriptor(e,t[r]);return n},n=/%[sdj%]/g;e.format=function(e){if(!x(e)){for(var t=[],r=0;r<arguments.length;r++)t.push(o(arguments[r]));return t.join(` `)}for(var r=1,i=arguments,a=i.length,s=String(e).replace(n,function(e){if(e===`%%`)return`%`;if(r>=a)return e;switch(e){case`%s`:return String(i[r++]);case`%d`:return Number(i[r++]);case`%j`:try{return JSON.stringify(i[r++])}catch{return`[Circular]`}default:return e}}),c=i[r];r<a;c=i[++r])v(c)||!T(c)?s+=` `+c:s+=` `+o(c);return s},e.deprecate=function(t,n){if(typeof process<`u`&&process.noDeprecation===!0)return t;if(typeof process>`u`)return function(){return e.deprecate(t,n).apply(this,arguments)};var r=!1;function i(){if(!r){if(process.throwDeprecation)throw Error(n);process.traceDeprecation?console.trace(n):console.error(n),r=!0}return t.apply(this,arguments)}return i};var r={},i=/^$/;if({}.NODE_DEBUG){var a={}.NODE_DEBUG;a=a.replace(/[|\\{}()[\]^$+?.]/g,`\\$&`).replace(/\*/g,`.*`).replace(/,/g,`$|^`).toUpperCase(),i=RegExp(`^`+a+`$`,`i`)}e.debuglog=function(t){if(t=t.toUpperCase(),!r[t]){if(i.test(t)){var n=process.pid;r[t]=function(){var r=e.format.apply(e,arguments);console.error(`%s %d: %s`,t,n,r)}}else r[t]=function(){}}return r[t]};function o(t,n){var r={seen:[],stylize:c};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),_(n)?r.showHidden=n:n&&e._extend(r,n),C(r.showHidden)&&(r.showHidden=!1),C(r.depth)&&(r.depth=2),C(r.colors)&&(r.colors=!1),C(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=s),u(r,t,r.depth)}e.inspect=o,o.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},o.styles={special:`cyan`,number:`yellow`,boolean:`yellow`,undefined:`grey`,null:`bold`,string:`green`,date:`magenta`,regexp:`red`};function s(e,t){var n=o.styles[t];return n?`\x1B[`+o.colors[n][0]+`m`+e+`\x1B[`+o.colors[n][1]+`m`:e}function c(e,t){return e}function l(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}function u(t,n,r){if(t.customInspect&&n&&O(n.inspect)&&n.inspect!==e.inspect&&!(n.constructor&&n.constructor.prototype===n)){var i=n.inspect(r,t);return x(i)||(i=u(t,i,r)),i}var a=d(t,n);if(a)return a;var o=Object.keys(n),s=l(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(n)),D(n)&&(o.indexOf(`message`)>=0||o.indexOf(`description`)>=0))return f(n);if(o.length===0){if(O(n)){var c=n.name?`: `+n.name:``;return t.stylize(`[Function`+c+`]`,`special`)}if(w(n))return t.stylize(RegExp.prototype.toString.call(n),`regexp`);if(E(n))return t.stylize(Date.prototype.toString.call(n),`date`);if(D(n))return f(n)}var _=``,v=!1,y=[`{`,`}`];if(g(n)&&(v=!0,y=[`[`,`]`]),O(n)&&(_=` [Function`+(n.name?`: `+n.name:``)+`]`),w(n)&&(_=` `+RegExp.prototype.toString.call(n)),E(n)&&(_=` `+Date.prototype.toUTCString.call(n)),D(n)&&(_=` `+f(n)),o.length===0&&(!v||n.length==0))return y[0]+_+y[1];if(r<0)return w(n)?t.stylize(RegExp.prototype.toString.call(n),`regexp`):t.stylize(`[Object]`,`special`);t.seen.push(n);var b=v?p(t,n,r,s,o):o.map(function(e){return m(t,n,r,s,e,v)});return t.seen.pop(),h(b,_,y)}function d(e,t){if(C(t))return e.stylize(`undefined`,`undefined`);if(x(t)){var n=`'`+JSON.stringify(t).replace(/^"|"$/g,``).replace(/'/g,`\\'`).replace(/\\"/g,`"`)+`'`;return e.stylize(n,`string`)}if(b(t))return e.stylize(``+t,`number`);if(_(t))return e.stylize(``+t,`boolean`);if(v(t))return e.stylize(`null`,`null`)}function f(e){return`[`+Error.prototype.toString.call(e)+`]`}function p(e,t,n,r,i){for(var a=[],o=0,s=t.length;o<s;++o)j(t,String(o))?a.push(m(e,t,n,r,String(o),!0)):a.push(``);return i.forEach(function(i){i.match(/^\d+$/)||a.push(m(e,t,n,r,i,!0))}),a}function m(e,t,n,r,i,a){var o,s,c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]};if(c.get?s=c.set?e.stylize(`[Getter/Setter]`,`special`):e.stylize(`[Getter]`,`special`):c.set&&(s=e.stylize(`[Setter]`,`special`)),j(r,i)||(o=`[`+i+`]`),s||(e.seen.indexOf(c.value)<0?(s=v(n)?u(e,c.value,null):u(e,c.value,n-1),s.indexOf(`
|
|
14
14
|
`)>-1&&(s=a?s.split(`
|
|
15
15
|
`).map(function(e){return` `+e}).join(`
|
|
16
16
|
`).slice(2):`
|
|
@@ -19,9 +19,9 @@ var t=Eu(),n=Du(),r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Sym
|
|
|
19
19
|
`))):s=e.stylize(`[Circular]`,`special`)),C(o)){if(a&&i.match(/^\d+$/))return s;o=JSON.stringify(``+i),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.slice(1,-1),o=e.stylize(o,`name`)):(o=o.replace(/'/g,`\\'`).replace(/\\"/g,`"`).replace(/(^"|"$)/g,`'`),o=e.stylize(o,`string`))}return o+`: `+s}function h(e,t,n){var r=0;return e.reduce(function(e,t){return r++,t.indexOf(`
|
|
20
20
|
`)>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,``).length+1},0)>60?n[0]+(t===``?``:t+`
|
|
21
21
|
`)+` `+e.join(`,
|
|
22
|
-
`)+` `+n[1]:n[0]+t+` `+e.join(`, `)+` `+n[1]}e.types=Dd();function g(e){return Array.isArray(e)}e.isArray=g;function _(e){return typeof e==`boolean`}e.isBoolean=_;function v(e){return e===null}e.isNull=v;function y(e){return e==null}e.isNullOrUndefined=y;function b(e){return typeof e==`number`}e.isNumber=b;function x(e){return typeof e==`string`}e.isString=x;function S(e){return typeof e==`symbol`}e.isSymbol=S;function C(e){return e===void 0}e.isUndefined=C;function w(e){return T(e)&&k(e)===`[object RegExp]`}e.isRegExp=w,e.types.isRegExp=w;function T(e){return typeof e==`object`&&!!e}e.isObject=T;function E(e){return T(e)&&k(e)===`[object Date]`}e.isDate=E,e.types.isDate=E;function D(e){return T(e)&&(k(e)===`[object Error]`||e instanceof Error)}e.isError=D,e.types.isNativeError=D;function O(e){return typeof e==`function`}e.isFunction=O;function ee(e){return e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`||typeof e==`symbol`||e===void 0}e.isPrimitive=ee,e.isBuffer=Od();function k(e){return Object.prototype.toString.call(e)}function te(e){return e<10?`0`+e.toString(10):e.toString(10)}var A=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function ne(){var e=/* @__PURE__ */ new Date,t=[te(e.getHours()),te(e.getMinutes()),te(e.getSeconds())].join(`:`);return[e.getDate(),A[e.getMonth()],t].join(` `)}e.log=function(){console.log(`%s - %s`,ne(),e.format.apply(e,arguments))},e.inherits=wu(),e._extend=function(e,t){if(!t||!T(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e};function j(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var M=typeof Symbol<`u`?Symbol(`util.promisify.custom`):void 0;e.promisify=function(e){if(typeof e!=`function`)throw TypeError(`The "original" argument must be of type Function`);if(M&&e[M]){var n=e[M];if(typeof n!=`function`)throw TypeError(`The "util.promisify.custom" argument must be of type Function`);return Object.defineProperty(n,M,{value:n,enumerable:!1,writable:!1,configurable:!0}),n}function n(){for(var t,n,r=new Promise(function(e,r){t=e,n=r}),i=[],a=0;a<arguments.length;a++)i.push(arguments[a]);i.push(function(e,r){e?n(e):t(r)});try{e.apply(this,i)}catch(e){n(e)}return r}return Object.setPrototypeOf(n,Object.getPrototypeOf(e)),M&&Object.defineProperty(n,M,{value:n,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(n,t(e))},e.promisify.custom=M;function N(e,t){if(!e){var n=/* @__PURE__ */ Error(`Promise was rejected with a falsy value`);n.reason=e,e=n}return t(e)}function P(e){if(typeof e!=`function`)throw TypeError(`The "original" argument must be of type Function`);function n(){for(var t=[],n=0;n<arguments.length;n++)t.push(arguments[n]);var r=t.pop();if(typeof r!=`function`)throw TypeError(`The last argument must be of type Function`);var i=this,a=function(){return r.apply(i,arguments)};e.apply(this,t).then(function(e){process.nextTick(a.bind(null,null,e))},function(e){process.nextTick(N.bind(null,e,a))})}return Object.setPrototypeOf(n,Object.getPrototypeOf(e)),Object.defineProperties(n,t(e)),n}e.callbackify=P})),Ad=/* @__PURE__ */ t(((e,t)=>{function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function r(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]==null?{}:arguments[t];t%2?n(Object(r),!0).forEach(function(t){i(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function i(e,t,n){return t=c(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,c(r.key),r)}}function s(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function c(e){var t=l(e,`string`);return typeof t==`symbol`?t:String(t)}function l(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var u=Ou().Buffer,d=kd().inspect,f=d&&d.custom||`inspect`;function p(e,t,n){u.prototype.copy.call(e,t,n)}t.exports=/*#__PURE__*/ function(){function e(){a(this,e),this.head=null,this.tail=null,this.length=0}return s(e,[{key:`push`,value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:`unshift`,value:function(e){var t={data:e,next:this.head};this.length===0&&(this.tail=t),this.head=t,++this.length}},{key:`shift`,value:function(){if(this.length!==0){var e=this.head.data;return this.head=this.length===1?this.tail=null:this.head.next,--this.length,e}}},{key:`clear`,value:function(){this.head=this.tail=null,this.length=0}},{key:`join`,value:function(e){if(this.length===0)return``;for(var t=this.head,n=``+t.data;t=t.next;)n+=e+t.data;return n}},{key:`concat`,value:function(e){if(this.length===0)return u.alloc(0);for(var t=u.allocUnsafe(e>>>0),n=this.head,r=0;n;)p(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:`consume`,value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:`first`,value:function(){return this.head.data}},{key:`_getString`,value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,a=e>i.length?i.length:e;if(a===i.length?r+=i:r+=i.slice(0,e),e-=a,e===0){a===i.length?(++n,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=i.slice(a));break}++n}return this.length-=n,r}},{key:`_getBuffer`,value:function(e){var t=u.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,a=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,a),e-=a,e===0){a===i.length?(++r,this.head=n.next?n.next:this.tail=null):(this.head=n,n.data=i.slice(a));break}++r}return this.length-=r,t}},{key:f,value:function(e,t){return d(this,r(r({},t),{},{depth:0,customInspect:!1}))}}]),e}()})),jd=/* @__PURE__ */ t(((e,t)=>{function n(e,t){var n=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(o,this,e)):process.nextTick(o,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?n._writableState?n._writableState.errorEmitted?process.nextTick(i,n):(n._writableState.errorEmitted=!0,process.nextTick(r,n,e)):process.nextTick(r,n,e):t?(process.nextTick(i,n),t(e)):process.nextTick(i,n)}),this)}function r(e,t){o(e,t),i(e)}function i(e){(!e._writableState||e._writableState.emitClose)&&(!e._readableState||e._readableState.emitClose)&&e.emit(`close`)}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit(`error`,t)}function s(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(`error`,t)}t.exports={destroy:n,undestroy:a,errorOrDestroy:s}})),Md=/* @__PURE__ */ t(((e,t)=>{function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var r={};function i(e,t,i){i||=Error;function a(e,n,r){return typeof t==`string`?t:t(e,n,r)}var o=/*#__PURE__*/ function(e){n(t,e);function t(t,n,r){return e.call(this,a(t,n,r))||this}return t}(i);o.prototype.name=i.name,o.prototype.code=e,r[e]=o}function a(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map(function(e){return String(e)}),n>2?`one of ${t} ${e.slice(0,n-1).join(`, `)}, or `+e[n-1]:n===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}return`of ${t} ${String(e)}`}function o(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function s(e,t,n){return(n===void 0||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function c(e,t,n){return typeof n!=`number`&&(n=0),n+t.length>e.length?!1:e.indexOf(t,n)!==-1}i(`ERR_INVALID_OPT_VALUE`,function(e,t){return`The value "`+t+`" is invalid for option "`+e+`"`},TypeError),i(`ERR_INVALID_ARG_TYPE`,function(e,t,n){var r;typeof t==`string`&&o(t,`not `)?(r=`must not be`,t=t.replace(/^not /,``)):r=`must be`;var i=s(e,` argument`)?`The ${e} ${r} ${a(t,`type`)}`:`The "${e}" ${c(e,`.`)?`property`:`argument`} ${r} ${a(t,`type`)}`;return i+=`. Received type ${typeof n}`,i},TypeError),i(`ERR_STREAM_PUSH_AFTER_EOF`,`stream.push() after EOF`),i(`ERR_METHOD_NOT_IMPLEMENTED`,function(e){return`The `+e+` method is not implemented`}),i(`ERR_STREAM_PREMATURE_CLOSE`,`Premature close`),i(`ERR_STREAM_DESTROYED`,function(e){return`Cannot call `+e+` after a stream was destroyed`}),i(`ERR_MULTIPLE_CALLBACK`,`Callback called multiple times`),i(`ERR_STREAM_CANNOT_PIPE`,`Cannot pipe, not readable`),i(`ERR_STREAM_WRITE_AFTER_END`,`write after end`),i(`ERR_STREAM_NULL_VALUES`,`May not write null values to stream`,TypeError),i(`ERR_UNKNOWN_ENCODING`,function(e){return`Unknown encoding: `+e},TypeError),i(`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`,`stream.unshift() after end event`),t.exports.codes=r})),Nd=/* @__PURE__ */ t(((e,t)=>{var n=Md().codes.ERR_INVALID_OPT_VALUE;function r(e,t,n){return e.highWaterMark==null?t?e[n]:null:e.highWaterMark}function i(e,t,i,a){var o=r(t,a,i);if(o!=null){if(!(isFinite(o)&&Math.floor(o)===o)||o<0)throw new n(a?i:`highWaterMark`,o);return Math.floor(o)}return e.objectMode?16:16384}t.exports={getHighWaterMark:i}})),Pd=/* @__PURE__ */ t(((e,t)=>{t.exports=n;function n(e,t){if(r(`noDeprecation`))return e;var n=!1;function i(){if(!n){if(r(`throwDeprecation`))throw Error(t);r(`traceDeprecation`)?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return i}function r(e){try{if(!global.localStorage)return!1}catch{return!1}var t=global.localStorage[e];return t!=null&&String(t).toLowerCase()===`true`}})),Fd=/* @__PURE__ */ t(((e,t)=>{t.exports=T;function n(e){var t=this;this.next=null,this.entry=null,this.finish=function(){ie(t,e)}}var r;T.WritableState=C;var i={deprecate:Pd()},a=Tu(),o=Ou().Buffer,s=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function c(e){return o.from(e)}function l(e){return o.isBuffer(e)||e instanceof s}var u=jd(),d=Nd().getHighWaterMark,f=Md().codes,p=f.ERR_INVALID_ARG_TYPE,m=f.ERR_METHOD_NOT_IMPLEMENTED,h=f.ERR_MULTIPLE_CALLBACK,g=f.ERR_STREAM_CANNOT_PIPE,_=f.ERR_STREAM_DESTROYED,v=f.ERR_STREAM_NULL_VALUES,y=f.ERR_STREAM_WRITE_AFTER_END,b=f.ERR_UNKNOWN_ENCODING,x=u.errorOrDestroy;wu()(T,a);function S(){}function C(e,t,i){r||=Id(),e||={},typeof i!=`boolean`&&(i=t instanceof r),this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=d(this,e,`writableHighWaterMark`,i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=e.decodeStrings===!1;this.decodeStrings=!a,this.defaultEncoding=e.defaultEncoding||`utf8`,this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){ne(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new n(this)}C.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},(function(){try{Object.defineProperty(C.prototype,"buffer",{get:i.deprecate(function(){return this.getBuffer()},`_writableState.buffer is deprecated. Use _writableState.getBuffer instead.`,`DEP0003`)})}catch{}})();var w;typeof Symbol==`function`&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==`function`?(w=Function.prototype[Symbol.hasInstance],Object.defineProperty(T,Symbol.hasInstance,{value:function(e){return w.call(this,e)?!0:this===T&&e&&e._writableState instanceof C}})):w=function(e){return e instanceof this};function T(e){r||=Id();var t=this instanceof r;if(!t&&!w.call(T,this))return new T(e);this._writableState=new C(e,this,t),this.writable=!0,e&&(typeof e.write==`function`&&(this._write=e.write),typeof e.writev==`function`&&(this._writev=e.writev),typeof e.destroy==`function`&&(this._destroy=e.destroy),typeof e.final==`function`&&(this._final=e.final)),a.call(this)}T.prototype.pipe=function(){x(this,new g)};function E(e,t){var n=new y;x(e,n),process.nextTick(t,n)}function D(e,t,n,r){var i;return n===null?i=new v:typeof n!=`string`&&!t.objectMode&&(i=new p(`chunk`,[`string`,`Buffer`],n)),!i||(x(e,i),process.nextTick(r,i),!1)}T.prototype.write=function(e,t,n){var r=this._writableState,i=!1,a=!r.objectMode&&l(e);return a&&!o.isBuffer(e)&&(e=c(e)),typeof t==`function`&&(n=t,t=null),a?t=`buffer`:t||=r.defaultEncoding,typeof n!=`function`&&(n=S),r.ending?E(this,n):(a||D(this,r,e,n))&&(r.pendingcb++,i=ee(this,r,a,e,t,n)),i},T.prototype.cork=function(){this._writableState.corked++},T.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&N(this,e))},T.prototype.setDefaultEncoding=function(e){if(typeof e==`string`&&(e=e.toLowerCase()),!([`hex`,`utf8`,`utf-8`,`ascii`,`binary`,`base64`,`ucs2`,`ucs-2`,`utf16le`,`utf-16le`,`raw`].indexOf((e+``).toLowerCase())>-1))throw new b(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(T.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function O(e,t,n){return!e.objectMode&&e.decodeStrings!==!1&&typeof t==`string`&&(t=o.from(t,n)),t}Object.defineProperty(T.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function ee(e,t,n,r,i,a){if(!n){var o=O(t,r,i);r!==o&&(n=!0,i=`buffer`,r=o)}var s=t.objectMode?1:r.length;t.length+=s;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else k(e,t,!1,s,r,i,a);return c}function k(e,t,n,r,i,a,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new _(`write`)):n?e._writev(i,t.onwrite):e._write(i,a,t.onwrite),t.sync=!1}function te(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick(I,e,t),e._writableState.errorEmitted=!0,x(e,r)):(i(r),e._writableState.errorEmitted=!0,x(e,r),I(e,t))}function A(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function ne(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(typeof i!=`function`)throw new h;if(A(n),t)te(e,n,r,t,i);else{var a=P(n)||e.destroyed;!a&&!n.corked&&!n.bufferProcessing&&n.bufferedRequest&&N(e,n),r?process.nextTick(j,e,n,a,i):j(e,n,a,i)}}function j(e,t,n,r){n||M(e,t),t.pendingcb--,r(),I(e,t)}function M(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit(`drain`))}function N(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var i=t.bufferedRequestCount,a=Array(i),o=t.corkedRequestsFree;o.entry=r;for(var s=0,c=!0;r;)a[s]=r,r.isBuf||(c=!1),r=r.next,s+=1;a.allBuffers=c,k(e,t,!0,t.length,a,``,o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new n(t),t.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,u=r.encoding,d=r.callback;if(k(e,t,!1,t.objectMode?1:l.length,l,u,d),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}T.prototype._write=function(e,t,n){n(new m(`_write()`))},T.prototype._writev=null,T.prototype.end=function(e,t,n){var r=this._writableState;return typeof e==`function`?(n=e,e=null,t=null):typeof t==`function`&&(n=t,t=null),e!=null&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||L(this,r,n),this},Object.defineProperty(T.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function P(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function F(e,t){e._final(function(n){t.pendingcb--,n&&x(e,n),t.prefinished=!0,e.emit(`prefinish`),I(e,t)})}function re(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final==`function`&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(F,e,t)):(t.prefinished=!0,e.emit(`prefinish`)))}function I(e,t){var n=P(t);if(n&&(re(e,t),t.pendingcb===0&&(t.finished=!0,e.emit(`finish`),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function L(e,t,n){t.ending=!0,I(e,t),n&&(t.finished?process.nextTick(n):e.once(`finish`,n)),t.ended=!0,e.writable=!1}function ie(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}Object.defineProperty(T.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState!==void 0&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),T.prototype.destroy=u.destroy,T.prototype._undestroy=u.undestroy,T.prototype._destroy=function(e,t){t(e)}})),Id=/* @__PURE__ */ t(((e,t)=>{var n=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=c;var r=Hd(),i=Fd();wu()(c,r);for(var a=n(i.prototype),o=0;o<a.length;o++){var s=a[o];c.prototype[s]||(c.prototype[s]=i.prototype[s])}function c(e){if(!(this instanceof c))return new c(e);r.call(this,e),i.call(this,e),this.allowHalfOpen=!0,e&&(e.readable===!1&&(this.readable=!1),e.writable===!1&&(this.writable=!1),e.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once(`end`,l)))}Object.defineProperty(c.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(c.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(c.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function l(){this._writableState.ended||process.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(c.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState!==void 0&&this._writableState!==void 0&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})})),Ld=/* @__PURE__ */ t(((e,t)=>{
|
|
22
|
+
`)+` `+n[1]:n[0]+t+` `+e.join(`, `)+` `+n[1]}e.types=Od();function g(e){return Array.isArray(e)}e.isArray=g;function _(e){return typeof e==`boolean`}e.isBoolean=_;function v(e){return e===null}e.isNull=v;function y(e){return e==null}e.isNullOrUndefined=y;function b(e){return typeof e==`number`}e.isNumber=b;function x(e){return typeof e==`string`}e.isString=x;function S(e){return typeof e==`symbol`}e.isSymbol=S;function C(e){return e===void 0}e.isUndefined=C;function w(e){return T(e)&&k(e)===`[object RegExp]`}e.isRegExp=w,e.types.isRegExp=w;function T(e){return typeof e==`object`&&!!e}e.isObject=T;function E(e){return T(e)&&k(e)===`[object Date]`}e.isDate=E,e.types.isDate=E;function D(e){return T(e)&&(k(e)===`[object Error]`||e instanceof Error)}e.isError=D,e.types.isNativeError=D;function O(e){return typeof e==`function`}e.isFunction=O;function ee(e){return e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`||typeof e==`symbol`||e===void 0}e.isPrimitive=ee,e.isBuffer=kd();function k(e){return Object.prototype.toString.call(e)}function te(e){return e<10?`0`+e.toString(10):e.toString(10)}var A=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function ne(){var e=/* @__PURE__ */ new Date,t=[te(e.getHours()),te(e.getMinutes()),te(e.getSeconds())].join(`:`);return[e.getDate(),A[e.getMonth()],t].join(` `)}e.log=function(){console.log(`%s - %s`,ne(),e.format.apply(e,arguments))},e.inherits=Tu(),e._extend=function(e,t){if(!t||!T(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e};function j(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var M=typeof Symbol<`u`?Symbol(`util.promisify.custom`):void 0;e.promisify=function(e){if(typeof e!=`function`)throw TypeError(`The "original" argument must be of type Function`);if(M&&e[M]){var n=e[M];if(typeof n!=`function`)throw TypeError(`The "util.promisify.custom" argument must be of type Function`);return Object.defineProperty(n,M,{value:n,enumerable:!1,writable:!1,configurable:!0}),n}function n(){for(var t,n,r=new Promise(function(e,r){t=e,n=r}),i=[],a=0;a<arguments.length;a++)i.push(arguments[a]);i.push(function(e,r){e?n(e):t(r)});try{e.apply(this,i)}catch(e){n(e)}return r}return Object.setPrototypeOf(n,Object.getPrototypeOf(e)),M&&Object.defineProperty(n,M,{value:n,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(n,t(e))},e.promisify.custom=M;function N(e,t){if(!e){var n=/* @__PURE__ */ Error(`Promise was rejected with a falsy value`);n.reason=e,e=n}return t(e)}function P(e){if(typeof e!=`function`)throw TypeError(`The "original" argument must be of type Function`);function n(){for(var t=[],n=0;n<arguments.length;n++)t.push(arguments[n]);var r=t.pop();if(typeof r!=`function`)throw TypeError(`The last argument must be of type Function`);var i=this,a=function(){return r.apply(i,arguments)};e.apply(this,t).then(function(e){process.nextTick(a.bind(null,null,e))},function(e){process.nextTick(N.bind(null,e,a))})}return Object.setPrototypeOf(n,Object.getPrototypeOf(e)),Object.defineProperties(n,t(e)),n}e.callbackify=P})),jd=/* @__PURE__ */ t(((e,t)=>{function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function r(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]==null?{}:arguments[t];t%2?n(Object(r),!0).forEach(function(t){i(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function i(e,t,n){return t=c(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,c(r.key),r)}}function s(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function c(e){var t=l(e,`string`);return typeof t==`symbol`?t:String(t)}function l(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var u=ku().Buffer,d=Ad().inspect,f=d&&d.custom||`inspect`;function p(e,t,n){u.prototype.copy.call(e,t,n)}t.exports=/*#__PURE__*/ function(){function e(){a(this,e),this.head=null,this.tail=null,this.length=0}return s(e,[{key:`push`,value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:`unshift`,value:function(e){var t={data:e,next:this.head};this.length===0&&(this.tail=t),this.head=t,++this.length}},{key:`shift`,value:function(){if(this.length!==0){var e=this.head.data;return this.head=this.length===1?this.tail=null:this.head.next,--this.length,e}}},{key:`clear`,value:function(){this.head=this.tail=null,this.length=0}},{key:`join`,value:function(e){if(this.length===0)return``;for(var t=this.head,n=``+t.data;t=t.next;)n+=e+t.data;return n}},{key:`concat`,value:function(e){if(this.length===0)return u.alloc(0);for(var t=u.allocUnsafe(e>>>0),n=this.head,r=0;n;)p(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:`consume`,value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:`first`,value:function(){return this.head.data}},{key:`_getString`,value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,a=e>i.length?i.length:e;if(a===i.length?r+=i:r+=i.slice(0,e),e-=a,e===0){a===i.length?(++n,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=i.slice(a));break}++n}return this.length-=n,r}},{key:`_getBuffer`,value:function(e){var t=u.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,a=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,a),e-=a,e===0){a===i.length?(++r,this.head=n.next?n.next:this.tail=null):(this.head=n,n.data=i.slice(a));break}++r}return this.length-=r,t}},{key:f,value:function(e,t){return d(this,r(r({},t),{},{depth:0,customInspect:!1}))}}]),e}()})),Md=/* @__PURE__ */ t(((e,t)=>{function n(e,t){var n=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(o,this,e)):process.nextTick(o,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?n._writableState?n._writableState.errorEmitted?process.nextTick(i,n):(n._writableState.errorEmitted=!0,process.nextTick(r,n,e)):process.nextTick(r,n,e):t?(process.nextTick(i,n),t(e)):process.nextTick(i,n)}),this)}function r(e,t){o(e,t),i(e)}function i(e){(!e._writableState||e._writableState.emitClose)&&(!e._readableState||e._readableState.emitClose)&&e.emit(`close`)}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit(`error`,t)}function s(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(`error`,t)}t.exports={destroy:n,undestroy:a,errorOrDestroy:s}})),Nd=/* @__PURE__ */ t(((e,t)=>{function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var r={};function i(e,t,i){i||=Error;function a(e,n,r){return typeof t==`string`?t:t(e,n,r)}var o=/*#__PURE__*/ function(e){n(t,e);function t(t,n,r){return e.call(this,a(t,n,r))||this}return t}(i);o.prototype.name=i.name,o.prototype.code=e,r[e]=o}function a(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map(function(e){return String(e)}),n>2?`one of ${t} ${e.slice(0,n-1).join(`, `)}, or `+e[n-1]:n===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}return`of ${t} ${String(e)}`}function o(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function s(e,t,n){return(n===void 0||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function c(e,t,n){return typeof n!=`number`&&(n=0),n+t.length>e.length?!1:e.indexOf(t,n)!==-1}i(`ERR_INVALID_OPT_VALUE`,function(e,t){return`The value "`+t+`" is invalid for option "`+e+`"`},TypeError),i(`ERR_INVALID_ARG_TYPE`,function(e,t,n){var r;typeof t==`string`&&o(t,`not `)?(r=`must not be`,t=t.replace(/^not /,``)):r=`must be`;var i=s(e,` argument`)?`The ${e} ${r} ${a(t,`type`)}`:`The "${e}" ${c(e,`.`)?`property`:`argument`} ${r} ${a(t,`type`)}`;return i+=`. Received type ${typeof n}`,i},TypeError),i(`ERR_STREAM_PUSH_AFTER_EOF`,`stream.push() after EOF`),i(`ERR_METHOD_NOT_IMPLEMENTED`,function(e){return`The `+e+` method is not implemented`}),i(`ERR_STREAM_PREMATURE_CLOSE`,`Premature close`),i(`ERR_STREAM_DESTROYED`,function(e){return`Cannot call `+e+` after a stream was destroyed`}),i(`ERR_MULTIPLE_CALLBACK`,`Callback called multiple times`),i(`ERR_STREAM_CANNOT_PIPE`,`Cannot pipe, not readable`),i(`ERR_STREAM_WRITE_AFTER_END`,`write after end`),i(`ERR_STREAM_NULL_VALUES`,`May not write null values to stream`,TypeError),i(`ERR_UNKNOWN_ENCODING`,function(e){return`Unknown encoding: `+e},TypeError),i(`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`,`stream.unshift() after end event`),t.exports.codes=r})),Pd=/* @__PURE__ */ t(((e,t)=>{var n=Nd().codes.ERR_INVALID_OPT_VALUE;function r(e,t,n){return e.highWaterMark==null?t?e[n]:null:e.highWaterMark}function i(e,t,i,a){var o=r(t,a,i);if(o!=null){if(!(isFinite(o)&&Math.floor(o)===o)||o<0)throw new n(a?i:`highWaterMark`,o);return Math.floor(o)}return e.objectMode?16:16384}t.exports={getHighWaterMark:i}})),Fd=/* @__PURE__ */ t(((e,t)=>{t.exports=n;function n(e,t){if(r(`noDeprecation`))return e;var n=!1;function i(){if(!n){if(r(`throwDeprecation`))throw Error(t);r(`traceDeprecation`)?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return i}function r(e){try{if(!global.localStorage)return!1}catch{return!1}var t=global.localStorage[e];return t!=null&&String(t).toLowerCase()===`true`}})),Id=/* @__PURE__ */ t(((e,t)=>{t.exports=T;function n(e){var t=this;this.next=null,this.entry=null,this.finish=function(){ie(t,e)}}var r;T.WritableState=C;var i={deprecate:Fd()},a=Eu(),o=ku().Buffer,s=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function c(e){return o.from(e)}function l(e){return o.isBuffer(e)||e instanceof s}var u=Md(),d=Pd().getHighWaterMark,f=Nd().codes,p=f.ERR_INVALID_ARG_TYPE,m=f.ERR_METHOD_NOT_IMPLEMENTED,h=f.ERR_MULTIPLE_CALLBACK,g=f.ERR_STREAM_CANNOT_PIPE,_=f.ERR_STREAM_DESTROYED,v=f.ERR_STREAM_NULL_VALUES,y=f.ERR_STREAM_WRITE_AFTER_END,b=f.ERR_UNKNOWN_ENCODING,x=u.errorOrDestroy;Tu()(T,a);function S(){}function C(e,t,i){r||=Ld(),e||={},typeof i!=`boolean`&&(i=t instanceof r),this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=d(this,e,`writableHighWaterMark`,i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=e.decodeStrings===!1;this.decodeStrings=!a,this.defaultEncoding=e.defaultEncoding||`utf8`,this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){ne(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new n(this)}C.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},(function(){try{Object.defineProperty(C.prototype,"buffer",{get:i.deprecate(function(){return this.getBuffer()},`_writableState.buffer is deprecated. Use _writableState.getBuffer instead.`,`DEP0003`)})}catch{}})();var w;typeof Symbol==`function`&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==`function`?(w=Function.prototype[Symbol.hasInstance],Object.defineProperty(T,Symbol.hasInstance,{value:function(e){return w.call(this,e)?!0:this===T&&e&&e._writableState instanceof C}})):w=function(e){return e instanceof this};function T(e){r||=Ld();var t=this instanceof r;if(!t&&!w.call(T,this))return new T(e);this._writableState=new C(e,this,t),this.writable=!0,e&&(typeof e.write==`function`&&(this._write=e.write),typeof e.writev==`function`&&(this._writev=e.writev),typeof e.destroy==`function`&&(this._destroy=e.destroy),typeof e.final==`function`&&(this._final=e.final)),a.call(this)}T.prototype.pipe=function(){x(this,new g)};function E(e,t){var n=new y;x(e,n),process.nextTick(t,n)}function D(e,t,n,r){var i;return n===null?i=new v:typeof n!=`string`&&!t.objectMode&&(i=new p(`chunk`,[`string`,`Buffer`],n)),!i||(x(e,i),process.nextTick(r,i),!1)}T.prototype.write=function(e,t,n){var r=this._writableState,i=!1,a=!r.objectMode&&l(e);return a&&!o.isBuffer(e)&&(e=c(e)),typeof t==`function`&&(n=t,t=null),a?t=`buffer`:t||=r.defaultEncoding,typeof n!=`function`&&(n=S),r.ending?E(this,n):(a||D(this,r,e,n))&&(r.pendingcb++,i=ee(this,r,a,e,t,n)),i},T.prototype.cork=function(){this._writableState.corked++},T.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&N(this,e))},T.prototype.setDefaultEncoding=function(e){if(typeof e==`string`&&(e=e.toLowerCase()),!([`hex`,`utf8`,`utf-8`,`ascii`,`binary`,`base64`,`ucs2`,`ucs-2`,`utf16le`,`utf-16le`,`raw`].indexOf((e+``).toLowerCase())>-1))throw new b(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(T.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function O(e,t,n){return!e.objectMode&&e.decodeStrings!==!1&&typeof t==`string`&&(t=o.from(t,n)),t}Object.defineProperty(T.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function ee(e,t,n,r,i,a){if(!n){var o=O(t,r,i);r!==o&&(n=!0,i=`buffer`,r=o)}var s=t.objectMode?1:r.length;t.length+=s;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else k(e,t,!1,s,r,i,a);return c}function k(e,t,n,r,i,a,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new _(`write`)):n?e._writev(i,t.onwrite):e._write(i,a,t.onwrite),t.sync=!1}function te(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick(I,e,t),e._writableState.errorEmitted=!0,x(e,r)):(i(r),e._writableState.errorEmitted=!0,x(e,r),I(e,t))}function A(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function ne(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(typeof i!=`function`)throw new h;if(A(n),t)te(e,n,r,t,i);else{var a=P(n)||e.destroyed;!a&&!n.corked&&!n.bufferProcessing&&n.bufferedRequest&&N(e,n),r?process.nextTick(j,e,n,a,i):j(e,n,a,i)}}function j(e,t,n,r){n||M(e,t),t.pendingcb--,r(),I(e,t)}function M(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit(`drain`))}function N(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var i=t.bufferedRequestCount,a=Array(i),o=t.corkedRequestsFree;o.entry=r;for(var s=0,c=!0;r;)a[s]=r,r.isBuf||(c=!1),r=r.next,s+=1;a.allBuffers=c,k(e,t,!0,t.length,a,``,o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new n(t),t.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,u=r.encoding,d=r.callback;if(k(e,t,!1,t.objectMode?1:l.length,l,u,d),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}T.prototype._write=function(e,t,n){n(new m(`_write()`))},T.prototype._writev=null,T.prototype.end=function(e,t,n){var r=this._writableState;return typeof e==`function`?(n=e,e=null,t=null):typeof t==`function`&&(n=t,t=null),e!=null&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||L(this,r,n),this},Object.defineProperty(T.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function P(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function F(e,t){e._final(function(n){t.pendingcb--,n&&x(e,n),t.prefinished=!0,e.emit(`prefinish`),I(e,t)})}function re(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final==`function`&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(F,e,t)):(t.prefinished=!0,e.emit(`prefinish`)))}function I(e,t){var n=P(t);if(n&&(re(e,t),t.pendingcb===0&&(t.finished=!0,e.emit(`finish`),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function L(e,t,n){t.ending=!0,I(e,t),n&&(t.finished?process.nextTick(n):e.once(`finish`,n)),t.ended=!0,e.writable=!1}function ie(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}Object.defineProperty(T.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState!==void 0&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),T.prototype.destroy=u.destroy,T.prototype._undestroy=u.undestroy,T.prototype._destroy=function(e,t){t(e)}})),Ld=/* @__PURE__ */ t(((e,t)=>{var n=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=c;var r=Ud(),i=Id();Tu()(c,r);for(var a=n(i.prototype),o=0;o<a.length;o++){var s=a[o];c.prototype[s]||(c.prototype[s]=i.prototype[s])}function c(e){if(!(this instanceof c))return new c(e);r.call(this,e),i.call(this,e),this.allowHalfOpen=!0,e&&(e.readable===!1&&(this.readable=!1),e.writable===!1&&(this.writable=!1),e.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once(`end`,l)))}Object.defineProperty(c.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(c.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(c.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function l(){this._writableState.ended||process.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(c.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState!==void 0&&this._writableState!==void 0&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})})),Rd=/* @__PURE__ */ t(((e,t)=>{
|
|
23
23
|
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
24
|
-
var n=Ou(),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)}})),Rd=/* @__PURE__ */ t((e=>{var t=Ld().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):``}})),zd=/* @__PURE__ */ t(((e,t)=>{var n=Md().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})),Bd=/* @__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=zd(),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}})),Vd=/* @__PURE__ */ t(((e,t)=>{t.exports=function(){throw Error(`Readable.from is not available in the browser`)}})),Hd=/* @__PURE__ */ t(((e,t)=>{t.exports=E;var n;E.ReadableState=T,Cu().EventEmitter;var r=function(e,t){return e.listeners(t).length},i=Tu(),a=Ou().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=kd(),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=Ad(),f=jd(),p=Nd().getHighWaterMark,m=Md().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;wu()(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||=Id(),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||=Rd().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=Id(),!(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||=Rd().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=Bd()),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=Vd()),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}})),Ud=/* @__PURE__ */ t(((e,t)=>{t.exports=l;var n=Md().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=Id();wu()(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)}})),Wd=/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=Ud();wu()(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)}})),Gd=/* @__PURE__ */ t(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=Md().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=zd()),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})),Kd=(/* @__PURE__ */ t(((e,t)=>{t.exports=r;var n=Cu().EventEmitter;wu()(r,n),r.Readable=Hd(),r.Writable=Fd(),r.Duplex=Id(),r.Transform=Ud(),r.PassThrough=Wd(),r.finished=zd(),r.pipeline=Gd(),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}})))(),qd=Cu(),Jd=class extends Kd.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??=su(`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(Su(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(Su(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=Su(e);for(let t of this._pendingCallbacks)t(e);this.destroy(e)}}connect(...e){let t=ru(...e),{relay:n}=t,r=this.__webvpn_tcp_socket_init__(Eo(`an outbound tcp socket`).then(e=>(n!==void 0&&pu(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},Yd=class extends qd.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??=su(`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`,Su(e))}),this._webVPNTcpSocketListenerPromise.then(e=>{e?this.emit(`listening`):this._busyRelease?.()}),this._webVPNTcpSocketListenerPromise}listen(...e){let t=ru(...e);this._closeEmitted=!1;let n=e=>{let t=new Jd({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&&pu(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](){}},Xd=(e,t)=>new Jd({allowHalfOpen:e?.allowHalfOpen}).connect(e,t),Zd=Xd,Qd=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new Yd(e);return t&&n.on(`connection`,t),n},$d={Socket:Jd,Server:Yd,connect:Xd,createConnection:Zd,createServer:Qd,isIP:nu,isIPv4:eu,isIPv6:tu},ef=/* @__PURE__ */ n({Server:()=>Yd,Socket:()=>Jd,_default:()=>$d,connect:()=>Xd,createConnection:()=>Zd,createServer:()=>Qd,default:()=>$d,isIP:()=>nu,isIPv4:()=>eu,isIPv6:()=>tu}),tf=0,nf=1,rf=2,af=3,of=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,sf=new TextEncoder,cf={code:1006,reason:``,wasClean:!1,error:!1},lf=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},uf=e=>{if(typeof e==`string`)return[e,sf.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]},df=class extends EventTarget{static CONNECTING=tf;static OPEN=nf;static CLOSING=rf;static CLOSED=af;url;extensions=``;#e=`blob`;#t=tf;#n=``;#r=0;#i;#a;#o;#s;#c=/* @__PURE__ */ new Map;constructor(e,t=[]){super();let n=lf(e),r=typeof t==`string`?[t]:[...t];if(new Set(r).size!==r.length||r.some(e=>!of.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 '${uu}' and those starting '${du}' 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=su(`websocket`),Eo(`a websocket`).then(e=>e.cloud.websocket({url:this.url,protocols:r})).then(e=>this.#l(e)).catch(()=>this.#u({...cf,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===tf)throw new DOMException(`Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.`,`InvalidStateError`);let[t,n]=uf(e);this.#r+=n,this.#t===nf&&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&&sf.encode(t).byteLength>123)throw new DOMException(`The close reason must not be greater than 123 UTF-8 bytes.`,`SyntaxError`);if(this.#t===rf||this.#t===af)return;if(e===void 0&&t!==void 0&&(e=1e3),this.#t===tf){this.#t=rf,setTimeout(()=>this.#u({...cf,error:!0}),0);return}this.#t=rf;let n=this.#a;this.#o.close().catch(()=>{}).then(()=>n.close(e,t)).catch(()=>{})}async#l(e){if(this.#t!==tf){e.close().catch(()=>{});return}this.#a=e,this.#n=e.protocol,this.#o=e.writable.getWriter(),this.#t=nf,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!==nf)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(cf)}let n=await e.closed.then(e=>typeof e?.code==`number`?e:cf,()=>cf);this.#u(n)}#u({code:e,reason:t,wasClean:n,error:r}){this.#t!==af&&(this.#t=af,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:tf,OPEN:nf,CLOSING:rf,CLOSED:af}))Object.defineProperty(df.prototype,e,{value:t,enumerable:!0});var ff=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},pf=(e,...t)=>{let n=ff(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 ff([new Uint8Array([e,...i]),n])},mf=e=>{let t=0;for(;t<e.length-1&&e[t]===0&&!(e[t+1]&128);)t++;let n=e.subarray(t);return pf(2,n[0]&128?[0]:[],n)},hf=e=>pf(23,new TextEncoder().encode(e.toISOString().replace(/[-:T]/g,``).slice(2,14)+`Z`)),gf=pf(48,pf(6,[42,134,72,206,61,4,3,2])),_f=pf(48,pf(49,pf(48,pf(6,[85,4,3]),pf(12,new TextEncoder().encode(`WebRTC`))))),vf=864e5;async function yf(){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=pf(48,pf(160,mf(new Uint8Array([2]))),mf(n),gf,_f,pf(48,hf(/* @__PURE__ */ new Date(r-vf)),hf(new Date(r+30*vf))),_f,t),a=new Uint8Array(await crypto.subtle.sign({name:`ECDSA`,hash:`SHA-256`},e.privateKey,i));return{certificate:pf(48,i,gf,pf(3,[0],pf(48,mf(a.subarray(0,32)),mf(a.subarray(32))))),privateKey:new Uint8Array(await crypto.subtle.exportKey(`pkcs8`,e.privateKey))}}var bf=0,xf=1,Sf=2,Cf=3,wf=4,Tf=5,Ef=6,Df=7,Of=8,kf=262144,Af=16777216,jf=128,Mf=new TextEncoder,Nf=new TextDecoder,Pf=()=>{},Ff=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)},If=e=>`${e>>>24}.${e>>>16&255}.${e>>>8&255}.${e&255}`,Lf=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)},Rf=e=>e.split(/\r?\n/).filter(e=>{if(!e.startsWith(`a=candidate:`))return!0;let t=Ff(e.split(` `)[4]??``);return t!==void 0&&Lf(t)}).join(`\r
|
|
25
|
-
`);function zf(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 Bf=e=>new DOMException(e,`OperationError`),Vf=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<jf?(this.#e++,this.#n||(this.#n=!0,queueMicrotask(()=>{this.#n=!1})),this.socket.send(e,t,n,Pf)):(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,jf))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,kf),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,kf,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=Ff(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&&Bf(`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)}}},Hf=class{connection;label;target=new Wf(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`?Mf.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>Af)throw Bf(`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`)))}},Uf=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:kf,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:Bf(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 Bf(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 Nf.decode(this.#u())}#f(e){let{x:t}=this.host,n=this.#u(e).slice(),r=t.rtc_port(e),i=If(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===bf){this.#r=r,this.#s&&this.end(`failed`);return}n===xf?this.#f(t):n===Sf?this.#m(r,this.#d()):n===Cf?this.#h(r,this.#u().slice().buffer):n===wf?this.#h(r,this.#d()):n===Tf?(this.channels.get(r)?.closed(),this.channels.delete(r)):n===Ef?this.#b(`connected`):n===Df?this.end(`failed`,Bf(`the peer stopped answering`)):n===Of&&(this.#s=!0)}}#m(e,t){let n=this.channels.get(e);if(!n)n=new Hf(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=Mf.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 Hf(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=Mf.encode(this.host.allowPrivateCandidates?n:Rf(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 Bf(`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(kf,(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))>bf;)e===xf&&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`))})}},Wf=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()}};zf(Wf,`open`,`message`,`bufferedamountlow`,`error`,`close`);var Gf=class extends EventTarget{#e;constructor(e,t){super(),this.#e=new Uf(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`)}};zf(Gf,`connectionstatechange`,`datachannel`,`icecandidate`,`icegatheringstatechange`);var Kf=(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 qf(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 Jf(e){let{socket:t,address:n,port:r,allowPrivateCandidates:i=!1,sendBufferSize:a=kf}=e,o=Ff(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 ${kf}, the largest message`);let[s,{certificate:c,privateKey:l}]=await Promise.all([qf(e.wasm??new URL(
|
|
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
|
+
`);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)),yf()]),u={text:``},d={wasi_snapshot_preview1:Kf(()=>f.memory.buffer,e=>{u.text=(u.text+e).slice(-2048)})},f=(await WebAssembly.instantiate(s,d)).exports;f._initialize();let p=new Vf(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:Gf.bind(null,p),get droppedDatagrams(){return p.dropped},close:()=>p.close()}}var Yf=262144,Xf=16384,Zf=5e3,Qf=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>=Zf}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)}},$f=3e3,ep=class extends Error{},tp=({reflexive:e,complete:t})=>new Promise(n=>{let r,i=!1,a=()=>{i=!0,clearTimeout(o),clearTimeout(r),n()},o=setTimeout(a,$f);t.then(a),e.then(()=>{i||(r??=setTimeout(a,300))})}),np=({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 ep(`no connection could be made`,{cause:e})}let o=null,s=null,c=!1,l=[],u=0,d=!1,f=Xf,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 Qf({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=Yf,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=tp)=>r(e,async(e,t,n)=>{t(e.createDataChannel(`webtorrent`)),await n(e.setLocalDescription(await n(e.createOffer())))}),answer:(e,t=tp)=>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}},rp=e=>new Uint8Array(e).buffer,ip=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)),tp(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 ep(e.reason):Error(e.reason));return}let c=n.get(r);c&&(e.t===`open`?(c.stream=new Qf({write:e=>{for(let t=0;t<e.length;t+=Xf){let n=rp(e.subarray(t,t+Xf));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}},ap=1e4,op=6e5,sp=131072,cp=65536,lp=64,up=200,dp=`-RP0001-`,fp=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`,pp=e=>{let t=``;for(let n of crypto.getRandomValues(new Uint8Array(e)))t+=fp[n%62];return t},mp=()=>pp(20),hp=()=>dp+pp(12),gp=e=>{let t=``;for(let n=0;n<40;n+=2)t+=String.fromCharCode(parseInt(e.slice(n,n+2),16));return t},_p=e=>e===void 0||typeof e==`number`&&Number.isFinite(e)&&e>=0,vp=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,yp=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:vp(n),downloaded:vp(r),left:vp(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(ap*2**this.losses++,op);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>sp)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,up)),!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!_p(e)||!_p(r)||!_p(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>cp||typeof c!=`string`||c.length!==20||typeof l!=`string`||l.length<1||l.length>lp)return!1;let u={infoHash:n,peerId:c,offerId:l,sdp:s.sdp};return a?this.onoffer?.(u):this.onanswer?.(u),!0}},bp=[[0,8],[167772160,8],[1681915904,10],[2130706432,8],[2851995648,16],[2886729728,12],[3232235520,16]],xp=e=>bp.some(([t,n])=>e>>>32-n==t>>>32-n),Sp=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?xp((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 xp((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`)},Cp=e=>{let t;try{t=new URL(e)}catch{return null}return t.protocol!==`ws:`&&t.protocol!==`wss:`||Sp(t.hostname)?null:t.href},wp=[1,7],Tp=2,Ep=(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:wp.includes(n.state),uploadMode:(n.flags&Tp)!==0,hasMetadata:n.hasMetadata,private:e.isPrivate(t),uploaded:n.sessionPayloadUpload,downloaded:n.sessionPayloadDownload,left:n.totalWanted-n.totalWantedDone,watched:e.hasStreamWindow(t)}},Dp={torrentPeers:20,sessionPeers:60,connections:80,perMinute:40},Op={watched:0,downloading:10,seeding:20},kp=10,Ap=16384,jp=1e4,Mp=5e4,Np=3e4,Pp=1e4,Fp=6e4,Ip=65e3,Lp=6e5,Rp=200,zp=1e4,Bp=1e3,Vp=12e4,Hp=1e3,Up=e=>(e.answeredAt??0)<e.sentAt,Wp=e=>e.hasMetadata&&e.left<=0,Gp=e=>e.watched?`watched`:Wp(e)?`seeding`:`downloading`,Kp=(e,t,n)=>{let r=e.trackers.map(Cp).filter(e=>e!==null);return[...new Set(e.private??n?r:[...r,...t])]},qp=(e,t)=>e<t,Jp=e=>e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``),Yp=(e,t)=>{for(let n of e.keys()){if(e.size<=t)return;e.delete(n)}},Xp=(e,t)=>{let{links:n,WebSocket:r,relay:i=!1}=t,a={...Dp,...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=Op[Gp(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()+jp};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?Lp:Fp),silent:r,address:r?n.address:void 0}),Yp(e.quiet,Rp),n.state===`open`&&!r&&(e.askAt=Date.now()+Ip)},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 ep&&(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()+zp;for(let{endpoint:n}of await e.peers?.(t.handle).catch(()=>[])??[]){let e=Jp(n);t.ordinary.delete(e),t.ordinary.add(e)}Yp(t.ordinary,Bp)},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||!Ep(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()+Pp,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:Ap}),A=async(e,t)=>{let r=C(e,t,!0,null,mp());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(Wp(e.view)||!t.tracker.connected)return;let r=(t.seeders??0)+(t.leechers??0)-1,i=Math.min(kp,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()+Mp,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)||qp(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()+Np}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&&!qp(i.peerId,t)||(s.forEach(E),b(i)>=a.torrentPeers||x()+Op[Gp(i.view)]>=a.sessionPeers))return E(o);o.remote=t,o.state=`answered`,o.deadline=Date.now()+Np,y(),o.link.accept(r).catch(()=>{})},N=e=>{let t=s.get(e);if(t)return t;let n=new yp(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?!Up(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=Ep(e,t),r=c.get(t);if(n||u.delete(t),!n?.running){r&&I(r);return}let a=Kp(n,o,i);if(n.checking){r&&(r.view.checking=!0,re(r,a));return}if(r?.view.uploadMode&&!n.uploadMode&&n.hasMetadata&&!Wp(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:hp(),handle:t,view:n,hash:gp(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:Vp,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&&Wp(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,Hp);return oe(),se},Zp=`/assets/webrtc-DCtPDVeu.wasm`;const Qp=(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})),$p=(e,t)=>{let{port1:n,port2:r}=new MessageChannel;t({type:`peer-links`,port:r},[r]);let i=Xp(e,{links:ip(n),WebSocket,trackers:Ul});return{refresh:()=>i.refresh(),trackers:e=>Qp(i,e),close:()=>i.close()}},em=(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&&eu(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 Ul){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(Zp).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 Jf({socket:n,address:l,port:n.address().port,wasm:i,allowPrivateCandidates:!1});r=Xp(e,{links:np({RTCPeerConnection:a.RTCPeerConnection}),WebSocket:df,trackers:Ul,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=>Qp(r,e),close:()=>{a=!0,r?.close(),r=null}}};var tm=Ou(),nm=class extends qd.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:mu,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=om(n)),s+=n.byteLength,d=t.getUint16(s),s+=2}let f=t.getUint32(s);s+=4;try{this.emit(`message`,tm.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 rm;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let i=Ql.Address4.isValid(e)?am(e):sm(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(Ql.Address4.isValid(e)){let n=am(e),r=t&&Ql.Address4.isValid(t)?am(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(Ql.Address6.isValid(e)){let t=sm(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=iu(...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&&pu(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??=su(`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`,tm.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`,Su(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`,Su(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(Ql.Address4.isValid(e)){let n=am(e),r=t&&Ql.Address4.isValid(t)?am(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(Ql.Address6.isValid(e)){let t=sm(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=au(...e),n=im(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||Ql.Address4.isValid(a)||Ql.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=Su(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)})}},rm=new Uint8Array([2]),im=e=>{if(typeof e==`string`)return $l.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(im),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)},am=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)},om=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(`:`)}`},sm=e=>{let t=new Ql.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)))},cm=(e,t)=>{let n=new nm(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},lm={Socket:nm,createSocket:cm},um=/* @__PURE__ */ n({Socket:()=>nm,createSocket:()=>cm,default:()=>lm});const dm=({net:e,dgram:t}={net:ef,dgram:um})=>{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??=fs();for(let e of n.values())try{e()}catch{}return Promise.race([Promise.all(n.keys()),new Promise(e=>setTimeout(e,1e3))])}}},fm=/* @__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(`.`)),pm=e=>`ripple:source:`+e,mm=e=>`ripple:trackers:`+e,hm=self.name===`direct`?`direct`:`relay`,gm=hm===`relay`?dm():null;let G=null,_m=null,vm=null,ym={room:1/0,grownAt:0},bm=0;const xm=(e,t)=>{let n=bm-ym.grownAt+t>ym.room&&K.some(t=>!Q.has(t)&&G?.files(t)?.storageIndex===e);return n||(bm+=t),!n},Sm=qs(Fs,xm);let Cm=null;const wm=/* @__PURE__ */ new Map;let Tm=!1;const K=[],Em=/* @__PURE__ */ new Map,q=/* @__PURE__ */ new Map,Dm=/* @__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=$s(hm===`relay`),Xm=e=>e>=4294967040,Zm=(e,t,n)=>ms(t)?e.addMagnet(t,n):-2>>>0,X=(e,t)=>self.postMessage(e,t??[]),Qm=()=>K.map(e=>{let t=G.bitfield(e);return{handle:e,magnet:Em.get(e)??``,files:G.files(e),status:G.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,...G?.lastTrackers(e).map(e=>e.downloaded)??[]),uptime:$m(e),sessionUptime:eh(e),totals:Kh(e)}}),$m=e=>{let t=G?.status(e),n=Bh.get(e);return!t||!n?Vh.get(e)??ic:lc(Vh.get(e),n,t)},eh=e=>{let t=G?.status(e),n=Bh.get(e);return t&&n?cc(n,t):ic},th=async()=>await Po(`ripple:torrents`)??[],nh=async(e,t)=>{let n=[];await Io(qc,r=>{n=r??[];let i=n.findIndex(t=>t.infoHash===e.infoHash),a={...Gc(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(qc,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=q.get(e);t&&Z(t,{lastUsedAt:Date.now()},!0).catch(()=>{})},ah=async e=>{await V(Qc(e)).catch(()=>{}),await V($c(e)).catch(()=>{}),await V(pm(e)).catch(()=>{}),await V(mm(e)).catch(()=>{}),await V(el(e)).catch(()=>{})},oh=async e=>{let t=[];await Io(qc,n=>t=(n??[]).filter(t=>t.infoHash!==e)),await Io(Jc,t=>Yc(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=Pl;const lh=e=>Im(e)||Rm(e),uh=e=>{lh(e)?G?.setFlags(e,0,H.paused|H.autoManaged):G?.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=nc,xh=0,Sh=0;const Ch=/* @__PURE__ */ new Set,wh=async e=>{if(!Ch.has(e)){Ch.add(e);try{let t=G?.files(e)?.storageIndex,n=t===void 0||!vm?null:await vm.usageOfStorage(t);e===mh&&(_h={handle:e,bytes:n})}finally{Ch.delete(e)}}},Th=e=>{let t=mh;if(t==null||!K.includes(t))return null;G.peers(t),e-hh>=gh&&(hh=e,G.trackers(t),wh(t).catch(()=>{}));let n=G.lastTrackers(t),r=G?.pieceAvailability(t);return{handle:t,peers:G.lastPeers(t),trackers:[...gm?n:n.map(Eh),..._m?.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:hm,reachable:G.reachable(),inboundNow:bh,dhtNodes:xh,detail:e,rateLimits:{...Lh}},e?.availability?[e.availability.buffer]:[])},Oh=e=>{let t=G?.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)=>{K.includes(e)||K.push(e),Em.set(e,t),n&&(q.set(e,n),ph.add(e)),Dm.set(e,r),i?Q.add(e):Q.delete(e)},Ah=e=>{let t=K.indexOf(e);t>=0&&K.splice(t,1),Em.delete(e),q.delete(e),Dm.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),Ig.delete(e),mg.delete(e),hg.delete(e),gg.delete(e),jg.delete(e),Mg.delete(e),Dg.delete(e),Ym.delete(e),Fh.delete(e)},jh=e=>{Vm(e,`cache-idle`)&&(qm(e),G?.resumeTorrent(e),Y.hold(e,Date.now()))},Mh=/* @__PURE__ */ new Set,Nh=/* @__PURE__ */ new Set,Ph=e=>{Nh.delete(e)&&G?.setFlags(e,0,H.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=G?.status(e),n=Hh.get(e);return!t||!n?Uh.get(e)??oc:dc(Uh.get(e),n,Wh(t))},qh=(e,t)=>{let n={...Rh.get(e)};jl(t.down)&&(n.down=t.down),jl(t.up)&&(n.up=t.up),(jl(n.down)||jl(n.up))&&(Rh.set(e,n),Yh(e))},Jh=e=>{let t=Rh.get(e)?.down;return gg.has(e)?Math.min(t||16384,16384):t},Yh=e=>{let t=Rh.get(e);if(!G||!t)return;let n=Jh(e);jl(n)&&G.setDownloadLimit(e,n),jl(t.up)&&G.setUploadLimit(e,t.up)},Xh=6e3,Zh=e=>e.reachable().listeners?.some(e=>e.healing)===!0,Qh=W.formatMessage({id:`torrent removed`,defaultMessage:`torrent removed`}),$h=W.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))&&!Qg(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||sl(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($c(e)))?.byteLength)return;let r=El(t);if(!r)return;let i=wl(r,Tl(n));await Io($c(e),e=>e?.byteLength?e:i)},og=/* @__PURE__ */ new Map,sg=async e=>{let t=q.get(e);if(!t||!G||og.has(e)||ol(Dm.get(e)))return!1;let n=G.status(e);if(!n||Zs.has(n.state)||Nh.has(e))return!1;let r=(async()=>{try{let n=await G.saveResumeData(e);return K.includes(e)?(await ig(Dm.get(e)),await Fo(Qc(t),n),await ag(t,n,Em.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=G?.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||Qg(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;let _g;const vg=`ripple:ceiling-fixed`;let yg,bg=null;const xg=(e,t,n)=>[...Fg(e).filter(e=>e.fileIndex===t).map(e=>Ls(n,e.fromOffset,e.fromOffset+bs(n.pieceLength))),...[...eg.get(e)?.values()??[]].filter(n=>n.fileIndex===t&&(!n.viewer||$.get(e)?.has(n.viewer))).map(e=>Ls(n,e.offset,e.offset+e.len))],Sg=(e,t,n)=>{let r=hg.get(e),[i]=n;if(r===void 0||!i||!_g?.fixed||!Q.has(e)||n.some(e=>e.fileIndex!==i.fileIndex))return null;let a=t.files[i.fileIndex],o=Dm.get(e);if(!a||o===void 0)return null;let s={offset:a.offset,size:a.size,pieceLength:t.pieceLength},c=Sm.chunkBytesOf(o),l=Sm.chunksOf(o,i.fileIndex),u=Hs({file:s,chunkBytes:c,room:r,reader:i.fromOffset,held:l,pinned:xg(e,i.fileIndex,s)});return u&&{...u,fileIndex:i.fileIndex,file:s,chunkBytes:c}},Cg=(e,t)=>e.fileIndex===t.fileIndex&&JSON.stringify(e.want)===JSON.stringify(t.want),wg=(e,t)=>{let n=G?.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},Tg=()=>bg?bg.space.limitBytes-bg.space.usedBytes-(Sm.footprint()-bg.footprint)-mc:1/0,Eg=3e4,Dg=/* @__PURE__ */ new Map,Og=e=>(Dg.get(e)?.until??0)>Date.now(),kg=e=>{let t=mg.get(e),n=!!t&&!tg(e)&&Us(wg(e,t.ahead),Tg(),t.chunkBytes);n!==gg.has(e)&&(n?gg.add(e):gg.delete(e),G?.setDownloadLimit(e,Jh(e)??0))},Ag=e=>{let t=mg.get(e),n=G?.bitfield(e);if(!t||!n||t.slack.end<=t.slack.start||Og(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&&G?.forgetPieces(e,r)},jg=/* @__PURE__ */ new Set,Mg=/* @__PURE__ */ new Set,Ng=async e=>{if(jg.has(e)){Mg.add(e);return}jg.add(e);let t=!1;try{if(Og(e)){t=!0;return}let n=Dm.get(e),r=()=>{let t=mg.get(e);if(!t||n===void 0)return[];let r=/* @__PURE__ */ new Set([...t.keep,...zs(t.file,t.chunkBytes,xg(e,t.fileIndex,t.file))]);return Sm.chunksOf(n,t.fileIndex).filter(e=>!r.has(e)).map(e=>({chunk:e,fileIndex:t.fileIndex,pieces:Rs(t.file,t.chunkBytes,e)}))},i=({start:t,end:n})=>G?.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++)G?.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(({chunk:e})=>e)),s=[];for(let{chunk:e,fileIndex:t,pieces:r}of a){if(!o.has(e))continue;let a=i(r);!a||a.forgotten||a.busy||s.push(Sm.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{jg.delete(e),Mg.delete(e)?Ng(e):t&&mg.has(e)&&setTimeout(()=>void Ng(e),1e3)}},Pg=e=>{let t=Ih.get(e);if(!G||!t)return;let n=G.files(e);n&&G.prioritizePieces(e,ml({files:n.files,pieceLength:n.pieceLength,numPieces:Math.ceil(n.totalSize/n.pieceLength),wanted:t.wanted,firstLast:t.firstLast}))},Fg=e=>{let t=$.get(e);return t?[...t.values()].filter(e=>!e.held&&(!e.prepare||lg)):[]},Ig=/* @__PURE__ */ new Set,Lg=(e,t,n)=>{let[r]=n,i=r&&t.files[r.fileIndex],a=r&&i?.size&&!r.bulk&&!r.prepare&&Ig.has(e)?Ls({...i,pieceLength:t.pieceLength},r.fromOffset,r.fromOffset+vs):null;return!a||wg(e,a)?(Ig.delete(e),null):a},Rg=()=>{for(let e of[...Ig]){let t=G?.files(e);t&&!Lg(e,t,Fg(e))&&Jg(e)}},zg=e=>Q.has(e)&&Dm.get(e)!==tl&&!Mm(e)&&!Lm(e)&&!Im(e),Bg=e=>{J(e,`watchedPastQueue`,!1),Bm(e,`cache-idle`),Km(e),G?.pauseTorrent(e),Ph(e),sg(e)},Vg=(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=ys(e.pieceLength);return[t.fromOffset,Math.max(0,n.size-vs)].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)}})},Hg=(e,t,n)=>n.every(n=>Vg(t,n).every(t=>wg(e,t))),Ug=(e,t,n)=>mg.has(e)||!!t&&!!Sg(e,t,n.filter(e=>!e.prepare)),Wg=(e,t)=>{if(!Ll(ch)||!G)return!1;let n=G.status(e);if(!n||!sh.has(n.state))return!1;let r=Kh(e),i=$m(e),a=t?.contentSize??t?.totalSize??0;return Vl(ch,{uploaded:r.uploaded,downloaded:r.downloaded,size:a,seedingSeconds:i.seedingSeconds})},Gg=e=>{J(e,`watchedPastQueue`,!1),Bm(e,`seed-policy`),J(e,`seedBypass`,!1),Km(e),G?.pauseTorrent(e),sg(e);let t=q.get(e);t&&Z(t,{seedStopped:!0,seedBypass:!1}).catch(()=>{})},Kg=e=>{qm(e),uh(e),Y.hold(e,Date.now());let t=q.get(e);t&&Z(t,{seedStopped:!1}).catch(()=>{})},qg=()=>{if(G&&(Ll(ch)||Um()))for(let e of K){if(Dm.get(e)===tl||Nm(e)||Mm(e))continue;if(Im(e)||zm(e)){Vm(e,`seed-policy`)&&Kg(e);continue}let t=G.status(e);if(!t||Zs.has(t.state))continue;if(!sh.has(t.state)){Vm(e,`seed-policy`)&&Kg(e);continue}let n=G.files(e)??null,r=Fg(e);if(!(Q.has(e)&&Ug(e,n,r))){if(Wg(e,n)){if(ng(e)||r.length>0&&(!n||!Hg(e,n,r)))continue;Pm(e)||Gg(e)}else Vm(e,`seed-policy`)&&Kg(e)}}},Jg=e=>{if(!G)return;if(!K.includes(e)){$.delete(e),pg.delete(e);return}let t=Fg(e);if(!t.length){if(Ig.delete(e),J(e,`watchedPastQueue`,!1)&&!Im(e)&&!Fm(e)&&G.setFlags(e,H.autoManaged,H.autoManaged),!G.files(e)){pg.add(e);return}if(pg.delete(e),mg.delete(e),kg(e),G.clearStreamWindow(e),hl(Ih.get(e)??{})||Pg(e),zg(e)&&!Nm(e)){let t=G.status(e);if(!t||Zs.has(t.state)){pg.add(e);return}if(Vm(e,`seed-policy`)){let t=q.get(e);t&&Z(t,{seedStopped:!1}).catch(()=>{})}Bg(e)}else Ph(e);return}let n=G.files(e);if(n&&(Pm(e)||Nm(e)&&!Im(e)&&!zm(e)&&!ng(e)&&!(Q.has(e)&&Ug(e,n,t))&&Wg(e,n))){if(Hg(e,n,t)){if(jm(e)===`cache-idle`){Bm(e,`seed-policy`);let t=q.get(e);t&&Z(t,{seedStopped:!0}).catch(()=>{})}pg.delete(e),Ig.delete(e);return}Vm(e,`seed-policy`)&&Kg(e)}if(jh(e),!Mm(e)&&!Pm(e)&&J(e,`watchedPastQueue`,!0)&&uh(e),Ph(e),!n){pg.add(e);return}fg.delete(e)&&C_();let r=Lg(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-vs)}]:[]:!r&&o?.size?[a,{fileIndex:e,offset:o.size-1}]:[a]}),a=t.filter(e=>!e.prepare),o=a.some(e=>!e.bulk),s=Sg(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?[Ls({...e,pieceLength:n.pieceLength},0,e.size)]:[]):void 0);G.setStreamWindow(e,i,{unclaimedPriority:U.skip,windowPieces:r?r.end-r.start:ys(n.pieceLength),deadlineStepMs:Ss(n.pieceLength,G.status(e)?.downloadRate||3e6),deadlines:o,...c?{keep:c}:{}})?pg.delete(e):pg.add(e),s&&Ng(e),Ag(e),kg(e)},Yg=e=>{let t=G?.files(e),n=Fg(e).filter(e=>!e.prepare);if(!t||!n.length)return;let r=Sg(e,t,n),i=mg.get(e);if(r||i){if(!r||!i||!Cg(r,i)){Jg(e);return}mg.set(e,r),Ng(e)}},Xg=(e,t,n,r,i=!1,a,o=!1)=>{if(!K.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),Ig.add(t)):l?.fromOffset!==r&&Ig.delete(t),o&&(lg=ug()),Jg(t)},Zg=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&&Jg(n)}t&&g_&&C_()},Qg=(e,t,n,r)=>{let i=G?.files(e),a=i?.files[t],o=G?.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},$g=(e,t,n,r)=>{let i=G?.files(e),a=i?.files[t];if(!i||!a||n>=a.size)return r;let o=G?.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},e_=(e,t,n,r)=>{let i=G?.files(e),a=i?.files[t],o=G?.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},t_=(e,t,n)=>{let r=Math.max(0,e-vs-t),i=n?Math.floor(r/n)*n:0;return Math.min(e,bs(t)+e-i)},n_=async(e,t={evictable:[],graced:[]})=>{let n=e=>Math.max(0,e.size-e.held),r=[],i=[];for(let[e,t]of[...$]){let n=vm,a=G?.files(e),o=Dm.get(e);if(!n||!a||!t.size||o===void 0||sl(o))continue;let s=new Set([...t.values()].filter(e=>!e.prepare).map(e=>e.fileIndex)),c=Sm.chunkBytesOf(o),l=async r=>{let i=a.files[r]?.size??0,l=!s.has(r)&&[...t.values()].some(e=>e.prepare&&e.fileIndex===r);return{h:e,size:l?t_(i,a.pieceLength,Hc(o)?c:void 0):i,held:await n.usageOfStorage(a.storageIndex,r)??0}},u=Fg(e).find(e=>!e.prepare),d=!!_g?.fixed&&Q.has(e)&&Hc(o);for(let e of new Set([...t.values()].map(e=>e.fileIndex)))r.push({...await l(e),cache:d&&e===u?.fileIndex,chunkBytes:c});let f=n.refusedFile(a.storageIndex);f!==void 0&&i.push(await l(f))}let a=e=>e.reduce((e,t)=>e+n(t),0),o=r.filter(e=>!e.cache),s=a(o.filter(e=>!Q.has(e.h))),c=Math.max(0,bc({...e,candidates:[...t.evictable,...t.graced]},_g?.fixed)),l=a(o)-s+Math.min(s,c),u=r.filter(e=>e.cache),d=e=>e.reduce((e,t)=>e+t.bytesOnDisk,0),f=e.limitBytes-e.usedBytes+u.reduce((e,t)=>e+t.held,0)+d(t.evictable)-l-mc,p=e=>{let t=Bs(u.map(e=>e.size),f+e),r=new Set(u.filter((e,n)=>Vs(e.size,t[n]??0,e.chunkBytes)).map(e=>e.h));return{shares:t,windowed:r,owed:u.reduce((e,i,a)=>e+(r.has(i.h)?Math.max(0,(t[a]??0)-i.held):n(i)),l)}},m=p(0),h=p(d(t.graced)),g=i.filter(e=>!h.windowed.has(e.h)),_=g.filter(e=>!Q.has(e.h)),v=a(_)+_.length*hc(e.limitBytes),y=a(g.filter(e=>Q.has(e.h)))+v,b=new Map(u.map((e,t)=>[e.h,m.shares[t]??0]));return{pendingBytes:m.owed,laterBytes:h.owed,refusedBytes:y,keptRefusedBytes:v,rooms:b}},r_=(e,t,n,r,i)=>{if(!e||!K.includes(t))return;let a=$.get(t)?.get(e);if(!a||a.held||a.fileIndex!==n){Xg(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};Cs(s,a.fromOffset,r,i)&&Xg(e,t,n,r)},i_=async e=>{let t=e.filter(e=>!sl(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}},a_=async()=>{let e,t;try{return e=await navigator.storage.getDirectory(),t=`.ripple-probe-${crypto.randomUUID()}`,(await js(await e.getFileHandle(t,{create:!0}))).close(),await e.removeEntry(t).catch(()=>{}),!0}catch{return e&&t&&await e.removeEntry(t).catch(()=>{}),!1}},o_=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}),s_=async()=>{let e=bm;try{let{usage:t,quota:n}=await Mc.estimate();return!n||t===void 0?null:{usedBytes:t,limitBytes:n,grownAt:e}}catch{return null}},c_=async()=>{try{let{usage:e,quota:t}=await navigator.storage.estimate();return t&&e!==void 0?t-e:null}catch{return null}},l_=async(e,t=0)=>{for(let n=0;n<4e3;n+=250){await new Promise(e=>setTimeout(e,250));let n=await s_();if(!n||e-n.usedBytes>t/2)return n}return s_()},u_=async(e,t,n,r,i={})=>{rg(t,r),e.removeTorrent(t,!0),Ah(t),await V(Qc(n)).catch(()=>{}),await Z(n,{started:!1,paused:!1,...i})},d_=(e,t,n)=>u_(e,t,n,W.formatMessage({id:`torrent removed to make room`,defaultMessage:`torrent removed to make room`})),f_=async(e,t,n,r)=>{if(!await dl(n,r.files))return;let i=q.get(t);i&&il(Dm.get(t))&&await u_(e,t,i,W.formatMessage({id:`Files missing`,defaultMessage:`Files missing`}),{savePath:Bc(i)})},p_=async(e,t,n,r)=>{let i=Ol(Dm.get(t));if(i===r)return;let a=Em.get(t)??``,o=kl(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(Qc(n)).catch(()=>void 0);g?.byteLength&&await ag(n,g,a).catch(()=>{});let _=await Po($c(n)).catch(()=>void 0);if(h&&!_?.byteLength){X({type:`add-failed`,message:W.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,W.formatMessage({id:`files moved`,defaultMessage:`files moved`})),e.removeTorrent(t,i===`browser`),Ah(t),await V(Qc(n)).catch(()=>{});let v=_?.byteLength?e.addTorrentFile(_,o):Zm(e,a,o);if(Xm(v)){X({type:`add-failed`,message:W.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,H.uploadMode,H.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})},m_=(e,{infoHash:t,magnet:n,bytes:r,handles:i,paused:a,seedStopped:o=!1,ephemeral:s=!1})=>{let c=al(t);wm.set(c,i);let l=e.addTorrentFile(r,c);return Xm(l)?(wm.delete(c),null):(kh(l,n,t,c,s),e.setFlags(l,H.uploadMode,H.uploadMode),a?(Bm(l,`user`),Km(l)):o&&(Bm(l,`seed-policy`),Km(l)),Y.hold(l,Date.now()),l)},h_=async(e,t)=>{let n=new Map(e.map(e=>[e.infoHash,e])),r=[],i=[];for(let e of[...K]){let a=q.get(e);if(!a)continue;let o=n.get(a);if(!o?.ephemeral||!Uc(o.savePath,a)||$.get(e)?.size||tg(e))continue;let s=o.lastUsedAt??o.addedAt,c=await vm?.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 g_=!1;const __=(e,t)=>{let n=vc(e)&&(vc({...e,refusedBytes:e.refusedBytes-t})||`kept`);n!==g_&&(g_=n,X({type:`storage-full`,full:n,usedBytes:e.usedBytes,limitBytes:e.limitBytes}))},v_=/* @__PURE__ */ new Set;let y_=!1;const b_=async()=>{if(!G||y_)return 0;y_=!0;try{let e=await th(),t=new Set(e.map(e=>e.infoHash.toLowerCase()));for(let e of v_)t.add(e.toLowerCase());let n=/* @__PURE__ */ new Set,r=!0;for(let e of K){let i=q.get(e);if(i&&t.add(i.toLowerCase()),(Dm.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(!Hc(e)){if(e!==`/dl`&&!e.startsWith(`/dl/`)){r=!1;continue}if(e===`/dl`){if(t.rootEntry){n.add(t.rootEntry);continue}!K.some(e=>q.get(e)===t.infoHash)&&t.started!==!1&&(r=!1)}}}let i=await navigator.storage.getDirectory(),a=[...await Lc(i,`/dl`,{listedHashes:t,claimedNames:n,attributable:r}),...await Lc(i,`/cache`,{listedHashes:t,claimedNames:/* @__PURE__ */ new Set,attributable:!1})];return await Rc(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{y_=!1}};let x_=!1,S_=!1;const C_=async()=>{let e=G;if(!e)return;if(x_){S_=!0;return}x_=!0;let t=null,n={pendingBytes:0,laterBytes:0,refusedBytes:0,keptRefusedBytes:0,rooms:/* @__PURE__ */ new Map},r=[],i=[],a=e=>({...e,pendingBytes:_g?.fixed===!1?0:n.laterBytes,refusedBytes:n.refusedBytes,candidates:[...r,...i]});try{let o=await s_();if(!o)return;t=o,yg===void 0&&(yg=await Po(vg).catch(()=>null)??null);let s=async e=>{bg={space:e,footprint:Sm.footprint()};let t=await c_();if(t===null)return;let n={usedBytes:e.usedBytes,headroomBytes:t};_g=Ws(_g??(typeof yg==`boolean`?{...n,fixed:yg}:void 0),n,Fs),_g.fixed!==void 0&&_g.fixed!==yg&&(yg=_g.fixed,Fo(vg,yg).catch(()=>{}))};await s(o),n=await n_(o);let c=await h_(await th(),Date.now());r=c.evictable,i=c.graced,n=await n_(o,c);let l=!1;for(;r.length;){let[a]=Sc({...o,pendingBytes:n.pendingBytes,candidates:r});if(!a)break;let c=r.find(e=>e.infoHash===a)?.bytesOnDisk??0;r=r.filter(e=>e.infoHash!==a);let u=K.find(e=>q.get(e)===a);if(u===void 0||$.get(u)?.size||tg(u))continue;let d=o.usedBytes;t=null,await d_(e,u,a),l=!0;let f=await l_(d,c);if(!f)return;o=f,t=f,await s(f),n=await n_(o,{evictable:r,graced:i})}if(l)for(let e of $.keys())Y.retry(e,Date.now());hg.clear();for(let[e,t]of n.rooms)hg.set(e,t);for(let e of/* @__PURE__ */ new Set([...hg.keys(),...mg.keys()]))Yg(e);if(vc(a(o))&&await b_()){o=await l_(o.usedBytes)??o,await s(o),n=await n_(o,{evictable:r,graced:i});for(let e of $.keys())Y.retry(e,Date.now());hg.clear();for(let[e,t]of n.rooms)hg.set(e,t);for(let e of/* @__PURE__ */ new Set([...hg.keys(),...mg.keys()]))Yg(e)}t=o}catch(e){console.error(`[worker] storage budget pass failed`,String(e))}finally{x_=!1,t&&(__(a(t),n.keptRefusedBytes),ym={room:bc(a(t),_g?.fixed),grownAt:t.grownAt}),S_&&(S_=!1,C_())}};let w_,T_=!1;const E_=()=>{w_??=setInterval(()=>{let e=G,t=[...$.keys()].filter(t=>Fg(t).length&&!e?.files(t)),n=[...eg.keys()].filter(tg);if(!e||T_||!t.length&&!n.length){clearInterval(w_),w_=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)Jg(e);Rg(),r.length&&Dh()},50)},D_=async()=>{let e=console.error.bind(console);if(console.error=(...t)=>{e(...t);try{X({type:`worker-error`,args:t.map(String)})}catch{}},!await a_()){X({type:`storage-unavailable`});return}th().then(e=>{e.length&&X({type:`list`,list:e})}).catch(()=>{});let t=Promise.race([Po(Al).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]),n=Promise.race([Po(Nl).catch(()=>void 0),new Promise(e=>setTimeout(()=>e(void 0),2e3))]);vm=fl(Ps(xm),()=>Cm,e=>wm.get(e)??null,Sm),G=await ps(gm?{net:gm.net,dgram:gm.dgram,dnsLookup:ko,storage:vm,utpReceiveBufferBytes:4194304}:{...fs(),storage:vm,enableDht:!1,reserveListenPort:!1});for(let e=0;e<30;e++)G.tick();_m=gm?em(G,gm):$p(G,X),Lh=Ml(await t),ch=zl(await n),G.setRateLimits({download:Lh.down,upload:Lh.up});try{let e=await th(),t=!await i_(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(Qc(r.infoHash)),a=await Po($c(r.infoHash));if(t&&i&&i.byteLength){await V(Qc(r.infoHash)).catch(()=>{}),r.started=!1,n=!0;continue}r.private!==!0&&(a?.byteLength&&yl(a)||i?.byteLength&&Dl(i))&&(r.private=!0,n=!0);let o=r.private===!0,s=i?.byteLength&&(!o||Dl(i))?i:void 0;o&&i?.byteLength&&!s&&await V(Qc(r.infoHash)).catch(()=>{});let c=s?G.addTorrentWithResume(s,e):a&&a.byteLength?G.addTorrentFile(a,e):o?-2>>>0:Zm(G,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&&il(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||Hc(e))&&(Nh.add(c),G.setFlags(c,H.uploadMode,H.uploadMode))}n&&await Fo(qc,e)}catch(e){console.error(`[worker] restore failed`,e)}X({type:`ready`}),Tm=!0,X({type:`list`,list:await th().catch(()=>[])}),Dh(),setInterval(()=>{if(!G)return;let e=Date.now();G.popAlerts();for(let e of K)G.postStatus(e);_m?.refresh();for(let e of[...Mh])G.files(e)&&(Mh.delete(e),Fg(e).length||Jg(e));if(Cm)for(let e of[...Fh]){let t=G.files(e);t&&(Fh.delete(e),f_(G,e,Cm,t))}let t=dg();if(t.length&&ug()!==lg){lg=!lg;for(let e of t)Jg(e)}for(let e of[...pg])Jg(e);Rg();for(let t of[...fh])tg(t)||e-(dh.get(t)??0)<5e3||(fh.delete(t),Jg(t));for(let e of[...mg.keys()])Ag(e),kg(e);for(let e of K){if(Bh.has(e))continue;let t=G.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=q.get(e);if(!n)continue;let r=G.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})),...G.isPrivate?.(e)===!0?{private:!0}:{}}).catch(()=>{})}qg();for(let e of Wm){let t=G.status(e);t&&!Zs.has(t.state)&&(Qs(t)?Wm.delete(e):G.pauseTorrent(e))}for(let e of Gm){if(Fm(e)){Gm.delete(e);continue}let t=G.status(e);if(t&&!Zs.has(t.state)){if(!t.paused){Gm.delete(e);continue}if(t.autoManaged||t.errorCode){Gm.delete(e);continue}G.resumeTorrent(e)}}Y.retain(new Set(K));for(let t of K){let n=G.status(t);Y.observe(t,n&&o_(n),Fm(t),e),!n||n.paused||!Xs.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`&&G.pauseTorrent(t),uh(t);if(e-yh>=2e3){yh=e;for(let e of K)G.peers(e)}if(bh=rc(K.map(e=>G.lastPeers(e))),e-Sh>=1e3&&(Sh=e,xh=G.dhtNodes()),$.size&&e-vh>=gh){vh=e;for(let e of $.keys())G.trackers(e)}Dh();for(let t of K){let n=G.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(!G)return;for(let e of K){let t=G.status(e);t&&t.state===3&&sg(e)}let e=!1;for(let t of K){let n=G.status(t),r=q.get(t),i=Bh.get(t);if(!n||!r||!i)continue;e=!0;let a=lc(Vh.get(t),i,n);if(!pc(Vh.get(t),a))continue;Vh.set(t,a),Bh.set(t,{activeSeconds:n.activeSeconds,seedingSeconds:n.seedingSeconds});let o=Wh(n),s=dc(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(()=>{C_()},1e4),C_(),setTimeout(()=>{b_(),setInterval(()=>{b_()},6e5)},6e4),self.addEventListener(`online`,()=>Y.retryNow(Date.now()))},O_=e=>sl(e.savePath)&&e.saveTo!==`source`,k_=e=>il(e.savePath)?e.saveTo??`folder`:e.saveTo,A_=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:W.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=O_(t)?Bc(t.infoHash):t.savePath||`/dl`,o=await Po($c(t.infoHash));if(t.private===!0&&!o?.byteLength){X({type:`add-failed`,message:W.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:W.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:k_(t),started:!0,paused:!1,resumed:!1,forced:!1,seedStopped:!1,seedBypass:!1,ephemeral:!1,lastUsedAt:Date.now()})}r.size&&(Dh(),await rh(r))},j_=(e,t,n=!1)=>X(typeof e.addId==`string`?{...t,addId:e.addId,...n&&{already:n}}:t),M_=async(e,t,n)=>{Q.delete(e),Vm(e,`seed-policy`),J(e,`seedBypass`,!1),n?.paused?(Bm(e,`user`),Km(e),G?.pauseTorrent(e)):jh(e),Fg(e).length&&Jg(e),await Z(t,{ephemeral:!1,seedStopped:!1,seedBypass:!1,lastUsedAt:Date.now(),...n?.patch})},N_=async(e,t)=>{try{if(t.type===`add-magnet`){let n=ms(t.magnet),r=n?[...q].find(([,e])=>gs(e,n)):void 0;if(r){let[e,n]=r,i=!Q.has(e);t.ephemeral?ih(e):await M_(e,n),j_(t,{type:`added`,handle:e,magnet:Em.get(e)||t.magnet},i)}else{let r=n?(await th()).find(e=>gs(e.infoHash,n)):void 0,i=r?.infoHash??n,a=r&&r.infoHash!==n?r.magnet:t.magnet,o=Wc(r,t.ephemeral===!0),s=!!r&&O_(r),c=t.savePath||!s&&r?.savePath||(o&&i?Vc(i):Bc(i)),l;if(r?.private===!0){let n=i?await Po($c(i)).catch(()=>void 0):void 0;if(!n?.byteLength){j_(t,{type:`add-failed`,message:W.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)){j_(t,{type:`add-failed`,message:W.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)){j_(t,{type:`add-failed`,message:W.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,H.uploadMode,H.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:k_(r)}:void 0),j_(t,{type:`added`,handle:l,magnet:a}),Dh(),C_()}}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:W.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:W.formatMessage({id:`Some of those files could not be opened`,defaultMessage:`Some of those files could not be opened`})});return}await Fo($c(n),i);let a=m_(e,{infoHash:n,magnet:t.magnet,bytes:i,handles:r,paused:!1});if(a===null){await V($c(n)).catch(()=>{}),X({type:`add-failed`,message:W.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:al(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,...Kc({name:t.name,size:t.size,files:t.files}),...yl(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:W.formatMessage({id:`Some of those files could not be opened`,defaultMessage:`Some of those files could not be opened`})});return}let i=[...q.entries()].find(([,e])=>e===n);if(i){X({type:`added`,handle:i[0],magnet:Em.get(i[0])??``});return}let a=await Po($c(n));if(!a?.byteLength){X({type:`add-failed`,message:W.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(mm(n)).catch(()=>void 0),c=m_(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:W.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)){j_(t,{type:`add-failed`,message:W.formatMessage({id:`That file is not a valid .torrent`,defaultMessage:`That file is not a valid .torrent`})});return}if(K.includes(i)){let n=!t.ephemeral&&Q.has(i)?q.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($c(n),r),(a||o)&&(Ih.set(i,{wanted:a,firstLast:o}),Fg(i).length||(e.files(i)?Pg(i):Mh.add(i))),t.sequential===!0&&e.setFlags(i,H.sequentialDownload,H.sequentialDownload),t.top===!0&&e.moveInQueue(i,`top`),await M_(i,n,{paused:t.paused===!0,patch:{...a?{wantedFiles:a}:{},...o?{firstLast:!0}:{},...t.paused===!0?{paused:!0}:{},...yl(r)||e.isPrivate?.(i)===!0?{private:!0}:{},...s}})}else t.ephemeral&&Q.has(i)&&ih(i);j_(t,{type:`added`,handle:i,magnet:Em.get(i)??``},!n),!n&&!t.ephemeral&&typeof t.addId!=`string`&&X({type:`add-failed`,message:W.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,H.uploadMode,H.uploadMode)),t.sequential===!0&&e.setFlags(i,H.sequentialDownload,H.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(!K.includes(i))return;if(!s){e.removeTorrent(i,!0),Ah(i),j_(t,{type:`add-failed`,message:W.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,Wc(c,t.ephemeral===!0)),await Fo($c(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}:{},...yl(r)||e.isPrivate?.(i)===!0?{private:!0}:{}},c&&O_(c)?{savePath:n,saveTo:k_(c),...f}:void 0),v_.delete(s),j_(t,{type:`added`,handle:i,magnet:u})}else if(t.type===`read`){if(!K.includes(t.handle)){X({type:`read-error`,id:t.id,error:Qh});return}if(t.prioritize!==!1&&!Qg(t.handle,t.fileIndex,t.offset,t.len)&&(Nm(t.handle)&&fh.add(t.handle),jh(t.handle),Vm(t.handle,`seed-policy`)&&Kg(t.handle)),t.viewer||dh.set(t.handle,Date.now()),Mm(t.handle)&&!Qg(t.handle,t.fileIndex,t.offset,t.len)){X({type:`read-error`,id:t.id,error:$h});return}if(t.prioritize!==!1)r_(t.viewer,t.handle,t.fileIndex,t.offset,t.len);else if(!Qg(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}),E_();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?$g(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=e_(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&&Jg(t.handle)}}finally{n.delete(t.id),!t.viewer&&K.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=q.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}),Fg(t.handle).length||Pg(t.handle);let r=q.get(t.handle);r&&await Z(r,{wantedFiles:e,firstLast:n})}else if(t.type===`set-folder`)Cm=t.folder??null;else if(t.type===`set-temporary`){if(typeof t.infoHash==`string`){let e=t.temporary===!0,n=K.find(e=>q.get(e)===t.infoHash);n!==void 0&&(e?(Q.add(n),J(n,`seedBypass`,!1)):(Q.delete(n),jh(n)),Fg(n).length&&Jg(n)),await Z(t.infoHash,{ephemeral:e,...e?{seedBypass:!1}:{}})}}else if(t.type===`export-start`){let n=K.find(e=>q.get(e)===t.infoHash),r=n===void 0?void 0:Dm.get(n),i=n===void 0?null:e.files(n);if(n===void 0||!i||r===void 0||!Hc(r)||Nh.has(n)){X({type:`answer`,id:t.id,value:null});return}Dg.set(n,{running:(Dg.get(n)?.running??0)+1,until:Date.now()+Eg});let a=await e.saveResumeData(n),o=i.files.flatMap((e,t)=>e.pad?[]:Sm.chunksOf(r,t).map(e=>({fileIndex:t,chunk:e})));X({type:`answer`,id:t.id,value:{magnet:Em.get(n)??``,resume:a,chunkBytes:Sm.chunkBytesOf(r),chunks:o}})}else if(t.type===`export-chunk`){let e=K.find(e=>q.get(e)===t.infoHash),n=e===void 0?void 0:Dm.get(e),r=e===void 0?void 0:Dg.get(e);if(!r||n===void 0)throw Error(`that torrent is not being handed over`);r.until=Date.now()+Eg;let i=await Sm.readChunk(n,t.fileIndex,t.chunk);X({type:`answer`,id:t.id,value:i},[i.buffer])}else if(t.type===`export-end`){let e=K.find(e=>q.get(e)===t.infoHash),n=e===void 0?void 0:Dg.get(e);if(e===void 0||!n)return;--n.running,n.running||Dg.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:Vc(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)||K.some(e=>q.get(e)===n))return;let r=Vc(n);await Fo(Qc(n),t.resume);let i=e.addTorrentWithResume(t.resume,r);if(Xm(i)){X({type:`add-failed`,message:W.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?v_.delete(t.infoHash):v_.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?K.find(e=>q.get(e)===n):void 0;n&&i!==void 0&&await p_(e,i,n,r)}else if(t.type===`import-list`){let n=[];await Io(Jc,e=>n=Yc(e,t.removed));let r=[],i=[],a=!1,o=[];await Io(qc,e=>{o.length=0;let s=Zc(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=Kc(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=fc(Gh(n),Gh(e));for(let e of ac)(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=K.find(e=>q.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 A_(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=K.find(e=>q.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[...K])rg(t,Qh),e.removeTorrent(t,!0),Ah(t);let t=[];await Io(qc,e=>(t=e??[],[])),await V(Jc).catch(()=>{});for(let e of t)await V(Qc(e.infoHash)).catch(()=>{}),await V($c(e.infoHash)).catch(()=>{}),await V(mm(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=q.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=q.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=q.get(t.handle);n&&await V(Qc(n)).catch(()=>{}),Om.delete(t.handle),rg(t.handle,W.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,H.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(K.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?Xg(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.held===!0,t.bulk===!0||void 0,t.prepare===!0):r_(t.viewer,t.handle,t.fileIndex,t.fromOffset??0,t.readLen),E_();else if(t.type===`unwatch`)Zg(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=q.get(t.handle),i=t.urls.filter(e=>!n.includes(e));r&&i.length&&ol(Dm.get(t.handle))&&await Io(mm(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=jl(t.down)?t.down:void 0,n=jl(t.up)?t.up:void 0;qh(t.handle,{down:e,up:n});let r=q.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:jl(t.down)?t.down:Lh.down,up:jl(t.up)?t.up:Lh.up};await Fo(Al,{...n}).catch(()=>{}),Lh=n,e.setRateLimits({download:n.down,upload:n.up}),Dh()}else if(t.type===`set-seeding-policy`){let e=zl(t.policy);if(!Bl(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(Nl,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`||!K.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(!K.includes(t.handle))X({type:`answer`,id:t.id,value:null});else{let e=[...gm?r:r.map(Eh),..._m?.trackers(t.handle)??[]];X({type:`answer`,id:t.id,value:{peers:n,trackers:e}})}}}else t.type===`unwatch-owner`&&Zg(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`?j_(t,{type:`add-failed`,message:String(e?.message??e)}):zc.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)})}},P_=/* @__PURE__ */ new Set([`read`,`cancel-read`,`add-torrent-file`,`export-chunk`,`torrent-detail`]);let F_=Promise.resolve();self.addEventListener(`message`,e=>{let t=e.data;if(!t||typeof t!=`object`||typeof t.type!=`string`||!fm.has(t.type))return;if(t.type===`close-sockets`){T_=!0,_m?.close(),Promise.resolve(gm?.close()).then(()=>X({type:`answer`,id:t.id}));return}let n=G;if(!n){t.type===`read`?X({type:`read-error`,id:t.id,error:`the engine is still starting`}):zc.has(t.type)?X({type:`answer`,id:t.id,error:`worker not initialized`}):X({type:`error`,message:`worker not initialized`});return}if(P_.has(t.type)){N_(n,t);return}t.type===`start-many`&&X({type:`answer`,id:t.id,value:!0}),F_=F_.then(()=>N_(n,t))}),D_().catch(e=>X({type:Tm?`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}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)}));
|