@fkn/lib 0.4.1 → 0.4.2

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.
Files changed (4) hide show
  1. package/index.cjs +5 -5
  2. package/index.d.ts +21 -4
  3. package/index.js +292 -213
  4. package/package.json +1 -1
package/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./locator-jHaMLjtv.cjs`);let t=require(`osra`),n=require(`stream`),r=require(`events`),i=require(`ip-address`),a=require(`buffer`);var o=`FKN_WEB_EXTENSION_MAIN_WORLD_CONTENT_SCRIPT_ENABLED_EVENT_KEY`,s=`fknExtension`,c=(0,t.createTypedEventTarget)();typeof document<`u`&&document.addEventListener(o,e=>{c.dispatchEvent(new CustomEvent(`statuschange`,{detail:{enabled:e.detail.enabled}}))});var l=()=>typeof document>`u`?!1:document.documentElement.dataset[s]===`true`,u=null,d=e=>{u=e},ee=150,f=(e=1e3)=>new Promise((t,n)=>{if(l())return t();let r,i=e=>{clearTimeout(r),s.disconnect(),document.removeEventListener(`readystatechange`,c),e()},a=()=>i(async()=>{if(u&&(await u().catch(()=>{}),l()))return t();n(Error(`The FKN WebExtension is not installed, enabled or not exposed on this page.`))}),o=()=>{clearTimeout(r),r=setTimeout(()=>l()?i(t):a(),ee)},s=new MutationObserver(()=>{l()&&i(t)}),c=()=>{document.readyState===`complete`&&!l()&&o()};if(r=setTimeout(a,e),s.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-fkn-extension`]}),document.addEventListener(`readystatechange`,c),document.readyState===`complete`)return o();l()&&i(t)}),te,p=new Proxy({},{get:(n,r)=>async(...n)=>{await f(),te??=(0,t.expose)({},{transport:window,revivableModules:e.l});let i=(await te)[r];return i(...n)}}),m={scope:`network.fetch`,category:`network`,severity:0,title:`Fetch data from other sites`,description:`Lets the app download public data from other websites directly, past the usual cross-origin limits.`},h={scope:`network.fetchCredentialed`,category:`network`,severity:3,unsafe:!0,title:`Fetch from other sites, signed in as you`,description:`Lets the app fetch other sites using your logged-in session cookies, so it can read data only you should see.`},ne=[`fkn.app`,`fkn.dev`],g=e=>{let t;try{t=new URL(e)}catch{return!1}if(t.protocol===`chrome-extension:`||t.protocol===`moz-extension:`)return!0;let n=t.hostname;return ne.some(e=>n===e||n.endsWith(`.${e}`))},_=e=>{if(g(e))throw Error(`fetch: refusing to target the extension's own pages or FKN platform domains`)},re=[`origin`,`referer`],ie=e=>{if(!e?.headers)return;let t=new Headers(e.headers),n=re.map(e=>{let n=t.get(e);return n===null?void 0:[e,n]}).filter(e=>e!==void 0);return n.length?n:void 0},v=async(e,t)=>{let n=new Request(e,t);_(n.url);let r=n.body?await n.arrayBuffer():null;return p.proxyFetch({url:n.url,method:n.method,headers:[...n.headers],body:r,credentials:t?.credentials===`include`?`include`:`omit`,redirect:n.redirect,unsafeHeaders:ie(t),reason:t?.reason,signal:t?.signal??void 0})},ae={scope:`network.readCookie`,category:`network`,severity:3,unsafe:!0,title:`Read a site’s cookie`,description:`Lets the app read a named cookie from another site, which can include the login token only that site should see.`},oe={get:e=>p.getCookie(e)},se={scope:`network.modifyRequestHeaders`,category:`network`,severity:2,unsafe:!0,title:`Rewrite request headers to other sites`,description:`Lets the app set or remove headers (like Origin and Referer) on this page’s own requests to the listed sites.`},ce=e=>p.setRequestHeaderRule(e),y=e=>p.removeRequestHeaderRule({ruleId:e});(()=>{let t={},n=[...e.t.selectorModules,...e.i.selectorModules];for(let e of n)e.render&&!(e.type in t)&&(t[e.type]=e.render);return t})();var b=`FKN_WEB_EXTENSION_ATTACH_FRAME_EVENT_KEY`,x=e=>{if(!e||e===`about:blank`)return!1;let t;try{t=new URL(e,location.href)}catch{return!1}if(t.protocol===`chrome-extension:`||t.protocol===`moz-extension:`)return!0;if(t.protocol===`about:`)return!1;let n=t.hostname;return n===`fkn.app`||n.endsWith(`.fkn.app`)},S=e=>{if(x(e))throw Error(`attachFrame: refusing to target the extension's own pages or fkn.app`)},le={scope:`embed.iframe`,category:`embed`,severity:0,title:`Load another website inside this app`,description:`Lets the app embed external pages directly inside its own view.`},ue={scope:`embed.open`,category:`embed`,severity:0,title:`Open a website inside this app`,description:`Lets the app navigate to another site without leaving its window.`},de=async({iframe:t,domains:n=[]})=>{let r=crypto.randomUUID();if(S(t.src),await f(),!t.isConnected)throw Error(`attachFrame: the iframe must be connected to the document before attaching`);t.dispatchEvent(new CustomEvent(b,{detail:r}));let{executeLocator:i,ensureLocatorPermission:a,goto:o}=await p.attachFrame({marker:r,domains:n}),s=e.r(i,a),c=(e,t={})=>(S(e),o({url:e,...t})),l=()=>t.src;return{...s,goto:c,url:l}},fe={request:e=>p.requestPermissions(e.map(e=>({key:e.key,scope:e.scope??``,reason:e.reason})))},pe=32,me=typeof CSS<`u`&&CSS.supports(`clip-path`,`path('M0 0H1V1H0Z')`),he=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(`clip-path`,`inset(100%)`,`important`),t.setProperty(`background`,`transparent`),t.setProperty(`color-scheme`,`normal`),t.setProperty(`z-index`,`2147483647`),e.setAttribute(`title`,`FKN`)},ge=({x:e,y:t,width:n,height:r})=>`M${e} ${t}h${n}v${r}h${-n}Z`,_e=(e,{modal:t,rects:n})=>{if(!me){let r=t||n.length>0;e.style.setProperty(`pointer-events`,r?`auto`:`none`,`important`),e.style.setProperty(`visibility`,r?`visible`:`hidden`,`important`);return}let r=t?`none`:n.length===0?`inset(100%)`:`path('${n.map(ge).join(``)}')`,i=r===`none`||CSS.supports(`clip-path`,r)?r:`inset(100%)`;e.style.setProperty(`clip-path`,i,`important`)},ve=e=>{if(typeof e!=`object`||!e)return null;let{x:t,y:n,width:r,height:i}=e;if(![t,n,r,i].every(e=>typeof e==`number`&&Number.isFinite(e)))return null;let a=window.innerWidth,o=window.innerHeight,s=Math.max(0,Math.min(Math.round(t),a)),c=Math.max(0,Math.min(Math.round(n),o)),l=Math.max(s,Math.min(Math.round(t+r),a)),u=Math.max(c,Math.min(Math.round(n+i),o));return{x:s,y:c,width:l-s,height:u-c}},ye=e=>{if(typeof e!=`object`||!e)return null;let t=e,n=(Array.isArray(t.rects)?t.rects.slice(0,pe):[]).map(ve).filter(e=>e!==null&&e.width>0&&e.height>0);return{modal:t.modal===!0,rects:n}},C=null,be=()=>C!==null,xe=e=>{he(e),_e(e,{modal:!1,rects:[]}),C=e},Se=e=>{if(!C)return;let t=ye(e);t&&_e(C,t)},Ce=`https://fkn.app`,w=typeof globalThis<`u`&&globalThis.document?globalThis.document:void 0,T=w?.querySelector(`iframe[src="${Ce}/api"]`)??null,E=w?.createElement(`iframe`)??null;!T&&E&&w&&(E.src=`${Ce}/api`,w.body.appendChild(E));var D=T??E,O=D?.contentWindow??null;D&&w&&xe(D);var k=(()=>{if(typeof window<`u`)return O?{receive:window,emit:O}:void 0;if(typeof self<`u`)return{receive:self,emit:self}})(),we=k!==void 0,A=k?(0,t.expose)({},{key:`fkn-api`,transport:k}):new Promise(()=>{});A.then(e=>{be()&&e.overlay.setHost(Se)},()=>{});var Te=[`fkn.app`,`fkn.dev`],j=e=>{let t=typeof e==`string`?e:e instanceof URL?e.href:e.url,n;try{n=new URL(t)}catch{return}let r=n.hostname;if(Te.some(e=>r===e||r.endsWith(`.${e}`)))throw Error(`fetch refuses FKN platform domains (${r})`)},Ee=(e,t)=>(j(e),A.then(n=>n.cloud.fetch(e,t))),De=async()=>{let e=await A.then(e=>e.cloud.quota());return{premium:e.premium,overQuota:e.overQuota,throttled:e.overQuota&&!e.premium,usedBytes:e.usedBytes,limitBytes:e.limitBytes,remainingBytes:e.remaining,bytesPerSecond:e.bytesPerSecond,bitsPerSecond:e.bytesPerSecond*8}},Oe=e.g({lookup:()=>ke}),ke=(e,t)=>A.then(n=>n.cloud.dns.lookup(e,t)),Ae=new TextEncoder;new TextDecoder;var M=e=>i.Address4.isValid(e),N=e=>i.Address6.isValid(e),je=e=>M(e)?4:N(e)?6:0,Me=(...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:e[0]??0,host:typeof e[1]==`string`?e[1]:void 0,callback:t}},Ne=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=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??n,callback:t}:{address:r,port:n,callback:t}},Pe=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=e[0];if(typeof e[2]==`number`)return{message:n,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,offset:0,length:n.length,port:r,address:i,callback:t}}};new TextEncoder,new TextDecoder;var Fe=e.g({Server:()=>F,Socket:()=>P,_default:()=>Re,connect:()=>Ie,createConnection:()=>Le,createServer:()=>I,default:()=>Re,isIP:()=>je,isIPv4:()=>M,isIPv6:()=>N}),P=class extends n.Stream.Duplex{_localAddress;_remoteAddress;_webVPNTcpSocketPromise;constructor(e){if(e?.fd!==void 0)throw Error(`FKN WebVPN does not support file descriptors`);super(e),e?.connection&&this.__webvpn_tcp_socket_init__(e.connection)}__webvpn_tcp_socket_init__(e){if(this._webVPNTcpSocketPromise=e.then(e=>{let t=e.dataReadableStream.getReader(),n=e.dataWritableStream.getWriter();return this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},this._remoteAddress={address:e.remoteAddress,family:e.remoteFamily,port:e.remotePort},{...e,reader:t,writer:n}}).catch(e=>{this.emit(`error`,e)}),!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);return this._webVPNTcpSocketPromise.then(e=>{e&&this.emit(`connect`)}),this._webVPNTcpSocketPromise}_read(e){if(!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);this._webVPNTcpSocketPromise.then(e=>{if(!e){this.push(null);return}e.reader.read().then(({value:e,done:t})=>{if(t){this.push(null);return}this._restartTimeoutTimer(),this.push(e)}).catch(e=>{this.destroy(e)})})}_write(e,t,n){if(!this._webVPNTcpSocketPromise){n(Error(`Socket not connected`));return}this._webVPNTcpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not connected`);await t.writer.ready,await t.writer.write(e),this._restartTimeoutTimer(),n()}).catch(n)}connect(...e){let t=Me(...e),n=this.__webvpn_tcp_socket_init__(A.then(e=>e.cloud.webvpn.tcpSocket({remoteAddress:t.host??`localhost`,remotePort:t.port})));return t.callback&&n.then(e=>{e&&t.callback.call(this)}),this}_end(...e){return this._webVPNTcpSocketPromise?(e.length!==0&&this.write(e[0],e[1],e[2]),this._webVPNTcpSocketPromise.then(async e=>{e&&await e.end()}),this):this}_destroy(e){return this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.destroy()}),this}destroySoon(){this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.destroySoon()})}resetAndDestroy(){return this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.resetAndDestroy()}),this}_timeoutMs;_timeoutTimer;_restartTimeoutTimer(){this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._timeoutMs&&(this._timeoutTimer=setTimeout(()=>this.emit(`timeout`),this._timeoutMs))}setTimeout(e,t){return t&&this.on(`timeout`,t),this._timeoutMs=e,this._restartTimeoutTimer(),this}setNoDelay(e){let t=e??!0;return this._setTcpOption({type:0,value:t}),this}setKeepAlive(e,t){let n=e??!1,r=t!==void 0&&t>0?Math.max(1,Math.round(t/1e3)):0;return this._setTcpOption({type:2,enabled:n,initialDelaySeconds:r}),this}setSendBufferSize(e){return this._setTcpOption({type:3,value:e}),this}setRecvBufferSize(e){return this._setTcpOption({type:4,value:e}),this}_typeOfService;getTypeOfService(){return this._typeOfService??0}setTypeOfService(e){return this._typeOfService=e,this}_setTcpOption(e){if(!this._webVPNTcpSocketPromise){this.emit(`error`,Error(`Cannot set socket option before connect`));return}this._webVPNTcpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}write(e,t,...n){return super.write(e,t,...n)}address(){return this._localAddress??{}}unref(){return this}ref(){return this}autoSelectFamilyAttemptedAddresses;bufferSize;bytesRead;bytesWritten;connecting;pending;get localAddress(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.address}get localPort(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.port}get localFamily(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.family}readyState;get remoteAddress(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.address}get remotePort(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.port}get remoteFamily(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.family}timeout},F=class extends r.EventEmitter{_localAddress;_webVPNTcpSocketListenerPromise;constructor(e,t){super(e),t&&this.on(`connection`,t),e?.connection&&this.__webvpn_tcp_socket_listener_init__(e.connection)}__webvpn_tcp_socket_listener_init__(e){return this._webVPNTcpSocketListenerPromise=e.then(e=>(this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e)).catch(e=>{this.emit(`error`,e)}),this._webVPNTcpSocketListenerPromise.then(e=>{e&&this.emit(`listening`)}),this._webVPNTcpSocketListenerPromise}listen(...e){let t=Me(...e),n=e=>{let t=new P({connection:Promise.resolve(e)});this.emit(`connection`,t)},r=e=>A.then(r=>r.cloud.webvpn.tcpSocketListener({localAddress:e,localPort:t.port,onConnection:n})),i=t.host?r(t.host):r(`::`).catch(()=>r(`0.0.0.0`)),a=this.__webvpn_tcp_socket_listener_init__(i);return t.callback&&a.then(e=>{e&&t.callback.call(this)}),this}close(e){return this._webVPNTcpSocketListenerPromise&&this._webVPNTcpSocketListenerPromise.then(async t=>{if(t)try{await t.close(),this._localAddress=void 0,this.emit(`close`),e&&e()}catch(t){this._localAddress=void 0,this.emit(`close`),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](){}},Ie=(e,t)=>new P().connect(e,t),Le=(e,t)=>new P().connect(e,t),I=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new F(e);return t&&n.on(`connection`,t),n},Re={Socket:P,Server:F,connect:Ie,createConnection:Le,createServer:I,isIP:je,isIPv4:M,isIPv6:N},ze=e.g({Socket:()=>Be,createSocket:()=>He}),Be=class extends r.EventEmitter{_type;_localAddress;_remoteAddress;_webVPNUdpSocketPromise;constructor(e){if(super(e),!e)throw Error(`Missing options`);this._type=e.type}_lastRecvBufferSize=0;_lastSendBufferSize=0;_lastTtl=64;_lastMulticastTtl=1;_lastMulticastLoopback=!0;_setUdpOption(e){if(!this._webVPNUdpSocketPromise){this.emit(`error`,Error(`Cannot set socket option before bind`));return}this._webVPNUdpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}addMembership(e,t){if(i.Address4.isValid(e)){let n=L(e),r=t&&i.Address4.isValid(t)?L(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=Ve(e);this._setUdpOption({type:7,group:t,ifIndex:0})}else this.emit(`error`,Error(`Invalid multicast address: ${e}`))}address(){if(!this._localAddress)throw Error(`EBADF`);return this._localAddress}bind(...e){let t=Ne(...e),n=this._type===`udp6`?`::`:`0.0.0.0`;return this._webVPNUdpSocketPromise=A.then(e=>e.cloud.webvpn.udpSocket({type:this._type,address:t.address??n,port:t.port})).then(e=>{let t=e.dataReadableStream.getReader(),n=async()=>{let{value:e,done:r}=await t.read();r||(this.emit(`message`,a.Buffer.from(e.data),{address:e.address,family:e.family,port:e.port,size:e.size}),n())};return n(),this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e}).catch(e=>{this.emit(`error`,e)}),this._webVPNUdpSocketPromise.then(e=>{e&&this.emit(`listening`)}),t.callback&&this._webVPNUdpSocketPromise.then(e=>{e&&t.callback()}),this}close(e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);return this._webVPNUdpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not bound`);await t.close(),e&&e(),this.emit(`close`)}),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;await t.connect({remotePort:n,remoteAddress:i}),this._remoteAddress={address:i,family:this._type===`udp6`?`IPv6`:`IPv4`,port:n},a&&a()})}disconnect(){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(async e=>{if(!e)throw Error(`Socket not bound`);await e.connect({remotePort:0,remoteAddress:this._type===`udp4`?`0.0.0.0`:`::`})})}dropMembership(e,t){if(i.Address4.isValid(e)){let n=L(e),r=t&&i.Address4.isValid(t)?L(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=Ve(e);this._setUdpOption({type:8,group:t,ifIndex:0})}else this.emit(`error`,Error(`Invalid multicast address: ${e}`))}getRecvBufferSize(){return this._lastRecvBufferSize}getSendBufferSize(){return this._lastSendBufferSize}getSendQueueSize(){return 0}getSendQueueCount(){return 0}ref(){return this}remoteAddress(){if(!this._remoteAddress)throw Error(`ERR_SOCKET_DGRAM_NOT_CONNECTED`);return{address:this._remoteAddress.address,family:this._remoteAddress.family,port:this._remoteAddress.port}}send(...e){this._webVPNUdpSocketPromise||this.bind();let t=Pe(...e),n=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 r=typeof t.message==`string`?Ae.encode(t.message):t.message;e.send({...t,address:t.address??n,message:r.buffer})})}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)})}},L=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)},Ve=e=>{let t=new i.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)))},He=(e,t)=>{let n=new Be(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},Ue=e.g({Agent:()=>J,ClientRequest:()=>K,HTTPParser:()=>H,IncomingMessage:()=>U,METHODS:()=>Ge,STATUS_CODES:()=>R,Server:()=>q,ServerResponse:()=>G,_default:()=>nt,createServer:()=>tt,default:()=>nt,get:()=>et,globalAgent:()=>$e,request:()=>Y}),We=new TextDecoder(`latin1`),Ge=`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE`.split(`.`),R={100:`Continue`,101:`Switching Protocols`,102:`Processing`,103:`Early Hints`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad Request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a Teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too Many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,500:`Internal Server Error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,509:`Bandwidth Limit Exceeded`,510:`Not Extended`,511:`Network Authentication Required`},Ke=new Set([`content-type`,`content-length`,`user-agent`,`referer`,`host`,`authorization`,`proxy-authorization`,`if-modified-since`,`if-unmodified-since`,`from`,`location`,`max-forwards`,`retry-after`,`etag`,`last-modified`,`server`,`age`,`expires`]),z=13,B=10,qe=/^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/,V=(e,t)=>(e.code=t,e),Je=(e,t)=>{if(e.length===0)return t;if(t.length===0)return e;let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n},Ye=(e,t)=>{for(let n=t;n+1<e.length;n++)if(e[n]===z&&e[n+1]===B)return n;return-1},Xe=e=>{for(let t=0;t+3<e.length;t++)if(e[t]===z&&e[t+1]===B&&e[t+2]===z&&e[t+3]===B)return t;return-1},H=class{buf=new Uint8Array;state=`HEAD`;framing=`none`;bodyRemaining=0;chunkState=`size`;skipBody=!1;constructor(e,t){this.mode=e,this.handlers=t}execute(e){this.buf=Je(this.buf,e);let t=!0;for(;t;)if(t=!1,this.state===`HEAD`){let e=Xe(this.buf);if(e===-1)return;let n=this.buf.subarray(0,e);this.buf=this.buf.subarray(e+4);let r=this.parseHead(n);this.handlers.onHeaders(r),this.setupBody(r),this.framing===`none`?(this.handlers.onComplete(),this.reset(),t=this.buf.length>0):(this.state=`BODY`,t=!0)}else this.consumeBody()&&(this.handlers.onComplete(),this.reset(),t=this.buf.length>0)}finish(){this.state===`BODY`&&this.framing===`eof`&&(this.handlers.onComplete(),this.reset())}reset(){this.state=`HEAD`,this.framing=`none`,this.bodyRemaining=0,this.chunkState=`size`,this.skipBody=!1}parseHead(e){let t=We.decode(e).split(`\r
2
- `),n=t.shift()??``,r=[];for(let e of t)(e.startsWith(` `)||e.startsWith(` `))&&r.length>0?r[r.length-1]+=` `+e.trim():r.push(e);let i=[],a={};for(let e of r){if(!e)continue;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();i.push(n,r),this.addHeader(a,n,r)}let o={httpVersionMajor:1,httpVersionMinor:1,httpVersion:`1.1`,headers:a,rawHeaders:i};if(this.mode===`request`){let[e,t,r]=n.split(` `);o.method=(e??`GET`).toUpperCase(),o.url=t??`/`,this.applyVersion(o,r)}else{let e=n.indexOf(` `),t=n.slice(0,e),r=n.slice(e+1),i=r.indexOf(` `),a=i===-1?r:r.slice(0,i);o.statusCode=parseInt(a,10)||0,o.statusMessage=i===-1?``:r.slice(i+1),this.applyVersion(o,t)}return o}applyVersion(e,t){let n=/HTTP\/(\d)\.(\d)/i.exec(t??``);n&&(e.httpVersionMajor=parseInt(n[1],10),e.httpVersionMinor=parseInt(n[2],10),e.httpVersion=`${e.httpVersionMajor}.${e.httpVersionMinor}`)}addHeader(e,t,n){let r=t.toLowerCase();if(r===`set-cookie`){let t=e[`set-cookie`];Array.isArray(t)?t.push(n):e[`set-cookie`]=[n];return}let i=e[r];i===void 0?e[r]=n:Ke.has(r)||(e[r]=`${i}, ${n}`)}setupBody(e){if(this.skipBody){this.framing=`none`;return}let t=e.headers[`transfer-encoding`];if(typeof t==`string`&&t.toLowerCase().includes(`chunked`)){this.framing=`chunked`,this.chunkState=`size`;return}let n=e.headers[`content-length`];if(typeof n==`string`&&n!==``){let e=parseInt(n,10);e>0?(this.framing=`length`,this.bodyRemaining=e):this.framing=`none`;return}if(this.mode===`response`){let t=e.statusCode??0;t>=100&&t<200||t===204||t===304?this.framing=`none`:this.framing=`eof`}else this.framing=`none`}consumeBody(){if(this.framing===`length`){if(this.buf.length===0)return!1;let e=Math.min(this.bodyRemaining,this.buf.length);return this.handlers.onBody(this.buf.subarray(0,e)),this.buf=this.buf.subarray(e),this.bodyRemaining-=e,this.bodyRemaining===0}return this.framing===`eof`?(this.buf.length>0&&(this.handlers.onBody(this.buf),this.buf=new Uint8Array),!1):this.framing===`chunked`?this.consumeChunked():!0}consumeChunked(){for(;;)if(this.chunkState===`size`){let e=Ye(this.buf,0);if(e===-1)return!1;let t=We.decode(this.buf.subarray(0,e)),n=parseInt(t.split(`;`)[0].trim(),16);if(this.buf=this.buf.subarray(e+2),Number.isNaN(n))return!0;n===0?this.chunkState=`trailer`:(this.bodyRemaining=n,this.chunkState=`data`)}else if(this.chunkState===`data`){if(this.buf.length===0)return!1;let e=Math.min(this.bodyRemaining,this.buf.length);this.handlers.onBody(this.buf.subarray(0,e)),this.buf=this.buf.subarray(e),this.bodyRemaining-=e,this.bodyRemaining===0&&(this.chunkState=`dataCRLF`)}else if(this.chunkState===`dataCRLF`){if(this.buf.length<2)return!1;this.buf=this.buf.subarray(2),this.chunkState=`size`}else{let e=Ye(this.buf,0);if(e===-1)return!1;let t=e===0;if(this.buf=this.buf.subarray(e+2),t)return!0}}},Ze=(e,t)=>a.Buffer.isBuffer(e)?e:typeof e==`string`?a.Buffer.from(e,t??`utf8`):e instanceof Uint8Array?a.Buffer.from(e):e instanceof ArrayBuffer?a.Buffer.from(new Uint8Array(e)):a.Buffer.from(String(e)),U=class extends n.Stream.Readable{httpVersion=`1.1`;httpVersionMajor=1;httpVersionMinor=1;headers={};rawHeaders=[];trailers={};rawTrailers=[];method;url;statusCode;statusMessage;complete=!1;socket;constructor(e){super(),this.socket=e}get connection(){return this.socket}_applyHead(e){this.httpVersion=e.httpVersion,this.httpVersionMajor=e.httpVersionMajor,this.httpVersionMinor=e.httpVersionMinor,this.headers=e.headers,this.rawHeaders=e.rawHeaders,this.method=e.method,this.url=e.url,this.statusCode=e.statusCode,this.statusMessage=e.statusMessage}_read(){}setTimeout(e,t){return this.socket.setTimeout(e,t),this}},W=class extends n.Stream.Writable{_headerStore=new Map;headersSent=!1;chunkedEncoding=!1;finished=!1;_bodyWritten=!1;setHeader(e,t){if(this.headersSent)throw V(Error(`Cannot set headers after they are sent to the client`),`ERR_HTTP_HEADERS_SENT`);if(typeof e!=`string`||!qe.test(e))throw V(TypeError(`Header name must be a valid HTTP token [${JSON.stringify(String(e))}]`),`ERR_INVALID_HTTP_TOKEN`);if(t===void 0)throw V(TypeError(`Invalid value "undefined" for header "${e}"`),`ERR_HTTP_INVALID_HEADER_VALUE`);return this._headerStore.set(e.toLowerCase(),[e,Array.isArray(t)?[...t]:t]),this}getHeader(e){return this._headerStore.get(e.toLowerCase())?.[1]}getHeaderNames(){return[...this._headerStore.values()].map(([e])=>e)}getHeaders(){let e={};for(let[t,n]of this._headerStore.values())e[t]=n;return e}hasHeader(e){return this._headerStore.has(e.toLowerCase())}removeHeader(e){if(this.headersSent)throw Error(`Cannot remove headers after they are sent to the client`);this._headerStore.delete(e.toLowerCase())}_storeHeader(e){let t=this.hasHeader(`content-length`),n=this.getHeader(`transfer-encoding`);typeof n==`string`&&n.toLowerCase().includes(`chunked`)?this.chunkedEncoding=!0:!t&&this._shouldSendBody()&&(this.chunkedEncoding=!0,this.setHeader(`Transfer-Encoding`,`chunked`));let r=e+`\r
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./locator-jHaMLjtv.cjs`);let t=require(`osra`),n=require(`stream`),r=require(`events`),i=require(`ip-address`),a=require(`buffer`);var o=`FKN_WEB_EXTENSION_MAIN_WORLD_CONTENT_SCRIPT_ENABLED_EVENT_KEY`,s=`fknExtension`,c=(0,t.createTypedEventTarget)();typeof document<`u`&&document.addEventListener(o,e=>{c.dispatchEvent(new CustomEvent(`statuschange`,{detail:{enabled:e.detail.enabled}}))});var l=()=>typeof document>`u`?!1:document.documentElement.dataset[s]===`true`,u=null,d=e=>{u=e},ee=150,f=(e=1e3)=>new Promise((t,n)=>{if(l())return t();let r,i=e=>{clearTimeout(r),s.disconnect(),document.removeEventListener(`readystatechange`,c),e()},a=()=>i(async()=>{if(u&&(await u().catch(()=>{}),l()))return t();n(Error(`The FKN WebExtension is not installed, enabled or not exposed on this page.`))}),o=()=>{clearTimeout(r),r=setTimeout(()=>l()?i(t):a(),ee)},s=new MutationObserver(()=>{l()&&i(t)}),c=()=>{document.readyState===`complete`&&!l()&&o()};if(r=setTimeout(a,e),s.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-fkn-extension`]}),document.addEventListener(`readystatechange`,c),document.readyState===`complete`)return o();l()&&i(t)}),te,p=new Proxy({},{get:(n,r)=>async(...n)=>{await f(),te??=(0,t.expose)({},{transport:window,revivableModules:e.l});let i=(await te)[r];return i(...n)}}),m={scope:`network.fetch`,category:`network`,severity:0,title:`Fetch data from other sites`,description:`Lets the app download public data from other websites directly, past the usual cross-origin limits.`},ne={scope:`network.fetchCredentialed`,category:`network`,severity:3,unsafe:!0,title:`Fetch from other sites, signed in as you`,description:`Lets the app fetch other sites using your logged-in session cookies, so it can read data only you should see.`},re=[`fkn.app`,`fkn.dev`],h=e=>{let t;try{t=new URL(e)}catch{return!1}if(t.protocol===`chrome-extension:`||t.protocol===`moz-extension:`)return!0;let n=t.hostname;return re.some(e=>n===e||n.endsWith(`.${e}`))},g=e=>{if(h(e))throw Error(`fetch: refusing to target the extension's own pages or FKN platform domains`)},ie=[`origin`,`referer`],ae=e=>{if(!e?.headers)return;let t=new Headers(e.headers),n=ie.map(e=>{let n=t.get(e);return n===null?void 0:[e,n]}).filter(e=>e!==void 0);return n.length?n:void 0},_=async(e,t)=>{let n=new Request(e,t);g(n.url);let r=n.body?await n.arrayBuffer():null;return p.proxyFetch({url:n.url,method:n.method,headers:[...n.headers],body:r,credentials:t?.credentials===`include`?`include`:`omit`,redirect:n.redirect,unsafeHeaders:ae(t),reason:t?.reason,signal:t?.signal??void 0})},v={scope:`network.readCookie`,category:`network`,severity:3,unsafe:!0,title:`Read a site’s cookie`,description:`Lets the app read a named cookie from another site, which can include the login token only that site should see.`},y={get:e=>p.getCookie(e)},oe={scope:`network.modifyRequestHeaders`,category:`network`,severity:2,unsafe:!0,title:`Rewrite request headers to other sites`,description:`Lets the app set or remove headers (like Origin and Referer) on this page’s own requests to the listed sites.`},se=e=>p.setRequestHeaderRule(e),ce=e=>p.removeRequestHeaderRule({ruleId:e});(()=>{let t={},n=[...e.t.selectorModules,...e.i.selectorModules];for(let e of n)e.render&&!(e.type in t)&&(t[e.type]=e.render);return t})();var b=`FKN_WEB_EXTENSION_ATTACH_FRAME_EVENT_KEY`,x=e=>{if(!e||e===`about:blank`)return!1;let t;try{t=new URL(e,location.href)}catch{return!1}if(t.protocol===`chrome-extension:`||t.protocol===`moz-extension:`)return!0;if(t.protocol===`about:`)return!1;let n=t.hostname;return n===`fkn.app`||n.endsWith(`.fkn.app`)},S=e=>{if(x(e))throw Error(`attachFrame: refusing to target the extension's own pages or fkn.app`)},le={scope:`embed.iframe`,category:`embed`,severity:0,title:`Load another website inside this app`,description:`Lets the app embed external pages directly inside its own view.`},ue={scope:`embed.open`,category:`embed`,severity:0,title:`Open a website inside this app`,description:`Lets the app navigate to another site without leaving its window.`},de=async({iframe:t,domains:n=[]})=>{let r=crypto.randomUUID();if(S(t.src),await f(),!t.isConnected)throw Error(`attachFrame: the iframe must be connected to the document before attaching`);t.dispatchEvent(new CustomEvent(b,{detail:r}));let{executeLocator:i,ensureLocatorPermission:a,goto:o}=await p.attachFrame({marker:r,domains:n}),s=e.r(i,a),c=(e,t={})=>(S(e),o({url:e,...t})),l=()=>t.src;return{...s,goto:c,url:l}},fe={request:e=>p.requestPermissions(e.map(e=>({key:e.key,scope:e.scope??``,reason:e.reason})))},pe=32,me=typeof CSS<`u`&&CSS.supports(`clip-path`,`path('M0 0H1V1H0Z')`),he=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(`clip-path`,`inset(100%)`,`important`),t.setProperty(`background`,`transparent`),t.setProperty(`color-scheme`,`normal`),t.setProperty(`z-index`,`2147483647`),e.setAttribute(`title`,`FKN`)},ge=({x:e,y:t,width:n,height:r})=>`M${e} ${t}h${n}v${r}h${-n}Z`,_e=(e,{modal:t,rects:n})=>{if(!me){let r=t||n.length>0;e.style.setProperty(`pointer-events`,r?`auto`:`none`,`important`),e.style.setProperty(`visibility`,r?`visible`:`hidden`,`important`);return}let r=t?`none`:n.length===0?`inset(100%)`:`path('${n.map(ge).join(``)}')`,i=r===`none`||CSS.supports(`clip-path`,r)?r:`inset(100%)`;e.style.setProperty(`clip-path`,i,`important`)},ve=e=>{if(typeof e!=`object`||!e)return null;let{x:t,y:n,width:r,height:i}=e;if(![t,n,r,i].every(e=>typeof e==`number`&&Number.isFinite(e)))return null;let a=window.innerWidth,o=window.innerHeight,s=Math.max(0,Math.min(Math.round(t),a)),c=Math.max(0,Math.min(Math.round(n),o)),l=Math.max(s,Math.min(Math.round(t+r),a)),u=Math.max(c,Math.min(Math.round(n+i),o));return{x:s,y:c,width:l-s,height:u-c}},ye=e=>{if(typeof e!=`object`||!e)return null;let t=e,n=(Array.isArray(t.rects)?t.rects.slice(0,pe):[]).map(ve).filter(e=>e!==null&&e.width>0&&e.height>0);return{modal:t.modal===!0,rects:n}},C=null,be=()=>C!==null,xe=e=>{he(e),_e(e,{modal:!1,rects:[]}),C=e},Se=e=>{if(!C)return;let t=ye(e);t&&_e(C,t)},Ce=`https://fkn.app`,w=typeof globalThis<`u`&&globalThis.document?globalThis.document:void 0,we=w?.querySelector(`iframe[src="${Ce}/api"]`)??null,T=w?.createElement(`iframe`)??null;!we&&T&&w&&(T.src=`${Ce}/api`,w.body.appendChild(T));var E=we??T,D=E?.contentWindow??null;E&&w&&xe(E);var O=(()=>{if(typeof window<`u`)return D?{receive:window,emit:D}:void 0;if(typeof self<`u`)return{receive:self,emit:self}})(),Te=O!==void 0,k=O?(0,t.expose)({},{key:`fkn-api`,transport:O}):new Promise(()=>{});k.then(e=>{be()&&e.overlay.setHost(Se)},()=>{});var Ee=[`fkn.app`,`fkn.dev`],A=e=>{let t=typeof e==`string`?e:e instanceof URL?e.href:e.url,n;try{n=new URL(t)}catch{return}let r=n.hostname;if(Ee.some(e=>r===e||r.endsWith(`.${e}`)))throw Error(`fetch refuses FKN platform domains (${r})`)},j=(e,t)=>(A(e),k.then(n=>n.cloud.fetch(e,t))),De=async()=>{let e=await k.then(e=>e.cloud.quota());return{premium:e.premium,overQuota:e.overQuota,throttled:e.overQuota&&!e.premium,usedBytes:e.usedBytes,limitBytes:e.limitBytes,remainingBytes:e.remaining,bytesPerSecond:e.bytesPerSecond,bitsPerSecond:e.bytesPerSecond*8}},Oe=e.g({lookup:()=>ke}),ke=(e,t)=>k.then(n=>n.cloud.dns.lookup(e,t)),Ae=new TextEncoder;new TextDecoder;var M=e=>i.Address4.isValid(e),N=e=>i.Address6.isValid(e),je=e=>M(e)?4:N(e)?6:0,Me=(...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:e[0]??0,host:typeof e[1]==`string`?e[1]:void 0,callback:t}},Ne=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=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??n,callback:t}:{address:r,port:n,callback:t}},Pe=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=e[0];if(typeof e[2]==`number`)return{message:n,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,offset:0,length:n.length,port:r,address:i,callback:t}}};new TextEncoder,new TextDecoder;var Fe=e.g({Server:()=>F,Socket:()=>P,_default:()=>Re,connect:()=>I,createConnection:()=>Ie,createServer:()=>Le,default:()=>Re,isIP:()=>je,isIPv4:()=>M,isIPv6:()=>N}),P=class extends n.Stream.Duplex{_localAddress;_remoteAddress;_webVPNTcpSocketPromise;constructor(e){if(e?.fd!==void 0)throw Error(`FKN WebVPN does not support file descriptors`);super(e),e?.connection&&this.__webvpn_tcp_socket_init__(e.connection)}__webvpn_tcp_socket_init__(e){if(this._webVPNTcpSocketPromise=e.then(e=>{let t=e.dataReadableStream.getReader(),n=e.dataWritableStream.getWriter();return this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},this._remoteAddress={address:e.remoteAddress,family:e.remoteFamily,port:e.remotePort},{...e,reader:t,writer:n}}).catch(e=>{this.emit(`error`,e)}),!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);return this._webVPNTcpSocketPromise.then(e=>{e&&this.emit(`connect`)}),this._webVPNTcpSocketPromise}_read(e){if(!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);this._webVPNTcpSocketPromise.then(e=>{if(!e){this.push(null);return}e.reader.read().then(({value:e,done:t})=>{if(t){this.push(null);return}this._restartTimeoutTimer(),this.push(e)}).catch(e=>{this.destroy(e)})})}_write(e,t,n){if(!this._webVPNTcpSocketPromise){n(Error(`Socket not connected`));return}this._webVPNTcpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not connected`);await t.writer.ready,await t.writer.write(e),this._restartTimeoutTimer(),n()}).catch(n)}connect(...e){let t=Me(...e),n=this.__webvpn_tcp_socket_init__(k.then(e=>e.cloud.webvpn.tcpSocket({remoteAddress:t.host??`localhost`,remotePort:t.port})));return t.callback&&n.then(e=>{e&&t.callback.call(this)}),this}_end(...e){return this._webVPNTcpSocketPromise?(e.length!==0&&this.write(e[0],e[1],e[2]),this._webVPNTcpSocketPromise.then(async e=>{e&&await e.end()}),this):this}_destroy(e){return this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.destroy()}),this}destroySoon(){this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.destroySoon()})}resetAndDestroy(){return this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.resetAndDestroy()}),this}_timeoutMs;_timeoutTimer;_restartTimeoutTimer(){this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._timeoutMs&&(this._timeoutTimer=setTimeout(()=>this.emit(`timeout`),this._timeoutMs))}setTimeout(e,t){return t&&this.on(`timeout`,t),this._timeoutMs=e,this._restartTimeoutTimer(),this}setNoDelay(e){let t=e??!0;return this._setTcpOption({type:0,value:t}),this}setKeepAlive(e,t){let n=e??!1,r=t!==void 0&&t>0?Math.max(1,Math.round(t/1e3)):0;return this._setTcpOption({type:2,enabled:n,initialDelaySeconds:r}),this}setSendBufferSize(e){return this._setTcpOption({type:3,value:e}),this}setRecvBufferSize(e){return this._setTcpOption({type:4,value:e}),this}_typeOfService;getTypeOfService(){return this._typeOfService??0}setTypeOfService(e){return this._typeOfService=e,this}_setTcpOption(e){if(!this._webVPNTcpSocketPromise){this.emit(`error`,Error(`Cannot set socket option before connect`));return}this._webVPNTcpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}write(e,t,...n){return super.write(e,t,...n)}address(){return this._localAddress??{}}unref(){return this}ref(){return this}autoSelectFamilyAttemptedAddresses;bufferSize;bytesRead;bytesWritten;connecting;pending;get localAddress(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.address}get localPort(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.port}get localFamily(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.family}readyState;get remoteAddress(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.address}get remotePort(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.port}get remoteFamily(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.family}timeout},F=class extends r.EventEmitter{_localAddress;_webVPNTcpSocketListenerPromise;constructor(e,t){super(e),t&&this.on(`connection`,t),e?.connection&&this.__webvpn_tcp_socket_listener_init__(e.connection)}__webvpn_tcp_socket_listener_init__(e){return this._webVPNTcpSocketListenerPromise=e.then(e=>(this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e)).catch(e=>{this.emit(`error`,e)}),this._webVPNTcpSocketListenerPromise.then(e=>{e&&this.emit(`listening`)}),this._webVPNTcpSocketListenerPromise}listen(...e){let t=Me(...e),n=e=>{let t=new P({connection:Promise.resolve(e)});this.emit(`connection`,t)},r=e=>k.then(r=>r.cloud.webvpn.tcpSocketListener({localAddress:e,localPort:t.port,onConnection:n})),i=t.host?r(t.host):r(`::`).catch(()=>r(`0.0.0.0`)),a=this.__webvpn_tcp_socket_listener_init__(i);return t.callback&&a.then(e=>{e&&t.callback.call(this)}),this}close(e){return this._webVPNTcpSocketListenerPromise&&this._webVPNTcpSocketListenerPromise.then(async t=>{if(t)try{await t.close(),this._localAddress=void 0,this.emit(`close`),e&&e()}catch(t){this._localAddress=void 0,this.emit(`close`),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](){}},I=(e,t)=>new P().connect(e,t),Ie=(e,t)=>new P().connect(e,t),Le=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new F(e);return t&&n.on(`connection`,t),n},Re={Socket:P,Server:F,connect:I,createConnection:Ie,createServer:Le,isIP:je,isIPv4:M,isIPv6:N},ze=e.g({Socket:()=>Be,createSocket:()=>Ue}),Be=class extends r.EventEmitter{_type;_localAddress;_remoteAddress;_webVPNUdpSocketPromise;_dataPort;_socketId;_sendQueue=[];_sendQueueBytes=0;_sendFlushScheduled=!1;_peerTailCache=new Map;constructor(e){if(super(e),!e)throw Error(`Missing options`);this._type=e.type}_lastRecvBufferSize=0;_lastSendBufferSize=0;_lastTtl=64;_lastMulticastTtl=1;_lastMulticastLoopback=!0;_setUdpOption(e){if(!this._webVPNUdpSocketPromise){this.emit(`error`,Error(`Cannot set socket option before bind`));return}this._webVPNUdpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}_onDataPortBatch(e){let t=new DataView(e),n=0;for(;n+4<=e.byteLength;){let r=t.getUint32(n);n+=4;let i=n+r;if(i>e.byteLength)break;let o=n+4,s=t.getUint8(o);o+=1;let c,l,u;if(s===2){if(!this._remoteAddress){n=i;continue}c=this._remoteAddress.address,l=this._remoteAddress.family,u=this._remoteAddress.port}else{let n=new Uint8Array(e,o,s===0?4:16);if(s===0)l=`IPv4`,c=`${n[0]}.${n[1]}.${n[2]}.${n[3]}`;else{l=`IPv6`;let e=[];for(let t=0;t<16;t+=2)e.push(((n[t]<<8|n[t+1])>>>0).toString(16));c=e.join(`:`)}o+=n.byteLength,u=t.getUint16(o),o+=2}let d=t.getUint32(o);o+=4,this.emit(`message`,a.Buffer.from(e.slice(o,o+d)),{address:c,family:l,port:u,size:d}),n=i}}_peerTail(e,t){if(e===void 0||t===void 0)return Ve;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let a=i.Address4.isValid(e)?L(e):R(e),o=new Uint8Array(1+a.byteLength+2);return o[0]=a.byteLength===4?0:1,o.set(a,1),new DataView(o.buffer).setUint16(1+a.byteLength,t),this._peerTailCache.set(n,o),o}_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(i.Address4.isValid(e)){let n=L(e),r=t&&i.Address4.isValid(t)?L(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=R(e);this._setUdpOption({type:7,group:t,ifIndex:0})}else this.emit(`error`,Error(`Invalid multicast address: ${e}`))}address(){if(!this._localAddress)throw Error(`EBADF`);return this._localAddress}bind(...e){let t=Ne(...e),n=this._type===`udp6`?`::`:`0.0.0.0`;return this._webVPNUdpSocketPromise=k.then(e=>e.cloud.webvpn.udpSocket({type:this._type,address:t.address??n,port:t.port,dataPort:!0})).then(e=>{if(e.dataPort)this._socketId=e.socketId,this._dataPort=e.dataPort,this._dataPort.onmessage=e=>this._onDataPortBatch(e.data);else{let t=e.dataReadableStream.getReader(),n=async()=>{let{value:e,done:r}=await t.read();r||(this.emit(`message`,a.Buffer.from(e.data),{address:e.address,family:e.family,port:e.port,size:e.size}),n())};n()}return this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e}).catch(e=>{this.emit(`error`,e)}),this._webVPNUdpSocketPromise.then(e=>{e&&this.emit(`listening`)}),t.callback&&this._webVPNUdpSocketPromise.then(e=>{e&&t.callback.call(this)}),this}close(e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);return this._webVPNUdpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not bound`);this._dataPort?.close(),this._dataPort=void 0,await t.close(),e&&e(),this.emit(`close`)}),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;await t.connect({remotePort:n,remoteAddress:i}),this._remoteAddress={address:i,family:this._type===`udp6`?`IPv6`:`IPv4`,port:n},a&&a()})}disconnect(){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(async e=>{if(!e)throw Error(`Socket not bound`);await e.connect({remotePort:0,remoteAddress:this._type===`udp4`?`0.0.0.0`:`::`})})}dropMembership(e,t){if(i.Address4.isValid(e)){let n=L(e),r=t&&i.Address4.isValid(t)?L(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=R(e);this._setUdpOption({type:8,group:t,ifIndex:0})}else this.emit(`error`,Error(`Invalid multicast address: ${e}`))}getRecvBufferSize(){return this._lastRecvBufferSize}getSendBufferSize(){return this._lastSendBufferSize}getSendQueueSize(){return 0}getSendQueueCount(){return 0}ref(){return this}remoteAddress(){if(!this._remoteAddress)throw Error(`ERR_SOCKET_DGRAM_NOT_CONNECTED`);return{address:this._remoteAddress.address,family:this._remoteAddress.family,port:this._remoteAddress.port}}send(...e){this._webVPNUdpSocketPromise||this.bind();let t=Pe(...e),n=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 r=He(t.message),a=t.callback,o=t.address??n,s=this._remoteAddress!==void 0&&t.address===void 0;if(this._dataPort&&(s||i.Address4.isValid(o)||i.Address6.isValid(o))){this._portSend(r,s?void 0:o,s?void 0:t.port),a?.call(this,null,r.byteLength);return}e.send({...t,address:o,message:r.byteOffset===0&&r.byteLength===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}).then(()=>a?.call(this,null,r.byteLength),e=>a?a.call(this,e,0):this.emit(`error`,e))})}setBroadcast(e){this._setUdpOption({type:0,value:e})}setMulticastInterface(e){}setMulticastLoopback(e){return this._setUdpOption({type:3,value:e}),this._setUdpOption({type:4,value:e}),this._lastMulticastLoopback=e,e}setMulticastTTL(e){return this._setUdpOption({type:2,value:e}),this._lastMulticastTtl=e,e}setRecvBufferSize(e){this._setUdpOption({type:10,value:e}),this._lastRecvBufferSize=e}setSendBufferSize(e){this._setUdpOption({type:9,value:e}),this._lastSendBufferSize=e}setTTL(e){return this._setUdpOption({type:1,value:e}),this._lastTtl=e,e}unref(){return this}addSourceSpecificMembership(e,t,n){}dropSourceSpecificMembership(e,t,n){}async[Symbol.asyncDispose](){await new Promise(e=>{this.close(e)})}},Ve=new Uint8Array([2]),He=e=>{if(typeof e==`string`)return Ae.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(He),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)},L=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)},R=e=>{let t=new i.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)))},Ue=(e,t)=>{let n=new Be(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},We=e.g({Agent:()=>Y,ClientRequest:()=>q,HTTPParser:()=>U,IncomingMessage:()=>W,METHODS:()=>Ke,STATUS_CODES:()=>z,Server:()=>J,ServerResponse:()=>K,_default:()=>rt,createServer:()=>nt,default:()=>rt,get:()=>tt,globalAgent:()=>et,request:()=>X}),Ge=new TextDecoder(`latin1`),Ke=`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE`.split(`.`),z={100:`Continue`,101:`Switching Protocols`,102:`Processing`,103:`Early Hints`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad Request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a Teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too Many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,500:`Internal Server Error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,509:`Bandwidth Limit Exceeded`,510:`Not Extended`,511:`Network Authentication Required`},qe=new Set([`content-type`,`content-length`,`user-agent`,`referer`,`host`,`authorization`,`proxy-authorization`,`if-modified-since`,`if-unmodified-since`,`from`,`location`,`max-forwards`,`retry-after`,`etag`,`last-modified`,`server`,`age`,`expires`]),B=13,V=10,Je=/^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/,H=(e,t)=>(e.code=t,e),Ye=(e,t)=>{if(e.length===0)return t;if(t.length===0)return e;let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n},Xe=(e,t)=>{for(let n=t;n+1<e.length;n++)if(e[n]===B&&e[n+1]===V)return n;return-1},Ze=e=>{for(let t=0;t+3<e.length;t++)if(e[t]===B&&e[t+1]===V&&e[t+2]===B&&e[t+3]===V)return t;return-1},U=class{buf=new Uint8Array;state=`HEAD`;framing=`none`;bodyRemaining=0;chunkState=`size`;skipBody=!1;constructor(e,t){this.mode=e,this.handlers=t}execute(e){this.buf=Ye(this.buf,e);let t=!0;for(;t;)if(t=!1,this.state===`HEAD`){let e=Ze(this.buf);if(e===-1)return;let n=this.buf.subarray(0,e);this.buf=this.buf.subarray(e+4);let r=this.parseHead(n);this.handlers.onHeaders(r),this.setupBody(r),this.framing===`none`?(this.handlers.onComplete(),this.reset(),t=this.buf.length>0):(this.state=`BODY`,t=!0)}else this.consumeBody()&&(this.handlers.onComplete(),this.reset(),t=this.buf.length>0)}finish(){this.state===`BODY`&&this.framing===`eof`&&(this.handlers.onComplete(),this.reset())}reset(){this.state=`HEAD`,this.framing=`none`,this.bodyRemaining=0,this.chunkState=`size`,this.skipBody=!1}parseHead(e){let t=Ge.decode(e).split(`\r
2
+ `),n=t.shift()??``,r=[];for(let e of t)(e.startsWith(` `)||e.startsWith(` `))&&r.length>0?r[r.length-1]+=` `+e.trim():r.push(e);let i=[],a={};for(let e of r){if(!e)continue;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();i.push(n,r),this.addHeader(a,n,r)}let o={httpVersionMajor:1,httpVersionMinor:1,httpVersion:`1.1`,headers:a,rawHeaders:i};if(this.mode===`request`){let[e,t,r]=n.split(` `);o.method=(e??`GET`).toUpperCase(),o.url=t??`/`,this.applyVersion(o,r)}else{let e=n.indexOf(` `),t=n.slice(0,e),r=n.slice(e+1),i=r.indexOf(` `),a=i===-1?r:r.slice(0,i);o.statusCode=parseInt(a,10)||0,o.statusMessage=i===-1?``:r.slice(i+1),this.applyVersion(o,t)}return o}applyVersion(e,t){let n=/HTTP\/(\d)\.(\d)/i.exec(t??``);n&&(e.httpVersionMajor=parseInt(n[1],10),e.httpVersionMinor=parseInt(n[2],10),e.httpVersion=`${e.httpVersionMajor}.${e.httpVersionMinor}`)}addHeader(e,t,n){let r=t.toLowerCase();if(r===`set-cookie`){let t=e[`set-cookie`];Array.isArray(t)?t.push(n):e[`set-cookie`]=[n];return}let i=e[r];i===void 0?e[r]=n:qe.has(r)||(e[r]=`${i}, ${n}`)}setupBody(e){if(this.skipBody){this.framing=`none`;return}let t=e.headers[`transfer-encoding`];if(typeof t==`string`&&t.toLowerCase().includes(`chunked`)){this.framing=`chunked`,this.chunkState=`size`;return}let n=e.headers[`content-length`];if(typeof n==`string`&&n!==``){let e=parseInt(n,10);e>0?(this.framing=`length`,this.bodyRemaining=e):this.framing=`none`;return}if(this.mode===`response`){let t=e.statusCode??0;t>=100&&t<200||t===204||t===304?this.framing=`none`:this.framing=`eof`}else this.framing=`none`}consumeBody(){if(this.framing===`length`){if(this.buf.length===0)return!1;let e=Math.min(this.bodyRemaining,this.buf.length);return this.handlers.onBody(this.buf.subarray(0,e)),this.buf=this.buf.subarray(e),this.bodyRemaining-=e,this.bodyRemaining===0}return this.framing===`eof`?(this.buf.length>0&&(this.handlers.onBody(this.buf),this.buf=new Uint8Array),!1):this.framing===`chunked`?this.consumeChunked():!0}consumeChunked(){for(;;)if(this.chunkState===`size`){let e=Xe(this.buf,0);if(e===-1)return!1;let t=Ge.decode(this.buf.subarray(0,e)),n=parseInt(t.split(`;`)[0].trim(),16);if(this.buf=this.buf.subarray(e+2),Number.isNaN(n))return!0;n===0?this.chunkState=`trailer`:(this.bodyRemaining=n,this.chunkState=`data`)}else if(this.chunkState===`data`){if(this.buf.length===0)return!1;let e=Math.min(this.bodyRemaining,this.buf.length);this.handlers.onBody(this.buf.subarray(0,e)),this.buf=this.buf.subarray(e),this.bodyRemaining-=e,this.bodyRemaining===0&&(this.chunkState=`dataCRLF`)}else if(this.chunkState===`dataCRLF`){if(this.buf.length<2)return!1;this.buf=this.buf.subarray(2),this.chunkState=`size`}else{let e=Xe(this.buf,0);if(e===-1)return!1;let t=e===0;if(this.buf=this.buf.subarray(e+2),t)return!0}}},Qe=(e,t)=>a.Buffer.isBuffer(e)?e:typeof e==`string`?a.Buffer.from(e,t??`utf8`):e instanceof Uint8Array?a.Buffer.from(e):e instanceof ArrayBuffer?a.Buffer.from(new Uint8Array(e)):a.Buffer.from(String(e)),W=class extends n.Stream.Readable{httpVersion=`1.1`;httpVersionMajor=1;httpVersionMinor=1;headers={};rawHeaders=[];trailers={};rawTrailers=[];method;url;statusCode;statusMessage;complete=!1;socket;constructor(e){super(),this.socket=e}get connection(){return this.socket}_applyHead(e){this.httpVersion=e.httpVersion,this.httpVersionMajor=e.httpVersionMajor,this.httpVersionMinor=e.httpVersionMinor,this.headers=e.headers,this.rawHeaders=e.rawHeaders,this.method=e.method,this.url=e.url,this.statusCode=e.statusCode,this.statusMessage=e.statusMessage}_read(){}setTimeout(e,t){return this.socket.setTimeout(e,t),this}},G=class extends n.Stream.Writable{_headerStore=new Map;headersSent=!1;chunkedEncoding=!1;finished=!1;_bodyWritten=!1;setHeader(e,t){if(this.headersSent)throw H(Error(`Cannot set headers after they are sent to the client`),`ERR_HTTP_HEADERS_SENT`);if(typeof e!=`string`||!Je.test(e))throw H(TypeError(`Header name must be a valid HTTP token [${JSON.stringify(String(e))}]`),`ERR_INVALID_HTTP_TOKEN`);if(t===void 0)throw H(TypeError(`Invalid value "undefined" for header "${e}"`),`ERR_HTTP_INVALID_HEADER_VALUE`);return this._headerStore.set(e.toLowerCase(),[e,Array.isArray(t)?[...t]:t]),this}getHeader(e){return this._headerStore.get(e.toLowerCase())?.[1]}getHeaderNames(){return[...this._headerStore.values()].map(([e])=>e)}getHeaders(){let e={};for(let[t,n]of this._headerStore.values())e[t]=n;return e}hasHeader(e){return this._headerStore.has(e.toLowerCase())}removeHeader(e){if(this.headersSent)throw Error(`Cannot remove headers after they are sent to the client`);this._headerStore.delete(e.toLowerCase())}_storeHeader(e){let t=this.hasHeader(`content-length`),n=this.getHeader(`transfer-encoding`);typeof n==`string`&&n.toLowerCase().includes(`chunked`)?this.chunkedEncoding=!0:!t&&this._shouldSendBody()&&(this.chunkedEncoding=!0,this.setHeader(`Transfer-Encoding`,`chunked`));let r=e+`\r
3
3
  `;for(let[e,t]of this._headerStore.values())if(Array.isArray(t))for(let n of t)r+=`${e}: ${n}\r\n`;else r+=`${e}: ${t}\r\n`;return r+=`\r
4
- `,r}_writeToSocket(e,t){if(!this.socket){t(Error(`Socket is not available`));return}this.socket.write(e,t)}write(e,t,n){return this._bodyWritten=!0,super.write(e,t,n)}_write(e,t,n){let r=Ze(e),i=[];if(this.headersSent||=(this._implicitHeader(),i.push(a.Buffer.from(this._headBlock,`latin1`)),!0),this.chunkedEncoding?r.length>0&&(i.push(a.Buffer.from(`${r.length.toString(16)}\r\n`,`latin1`)),i.push(r),i.push(a.Buffer.from(`\r
4
+ `,r}_writeToSocket(e,t){if(!this.socket){t(Error(`Socket is not available`));return}this.socket.write(e,t)}write(e,t,n){return this._bodyWritten=!0,super.write(e,t,n)}_write(e,t,n){let r=Qe(e),i=[];if(this.headersSent||=(this._implicitHeader(),i.push(a.Buffer.from(this._headBlock,`latin1`)),!0),this.chunkedEncoding?r.length>0&&(i.push(a.Buffer.from(`${r.length.toString(16)}\r\n`,`latin1`)),i.push(r),i.push(a.Buffer.from(`\r
5
5
  `,`latin1`))):i.push(r),i.length===0){n();return}this._writeToSocket(a.Buffer.concat(i),n)}_final(e){let t=[];if(this.headersSent||=(!this.chunkedEncoding&&!this.hasHeader(`content-length`)&&this.setHeader(`Content-Length`,0),this._implicitHeader(),t.push(a.Buffer.from(this._headBlock,`latin1`)),!0),this.chunkedEncoding&&t.push(a.Buffer.from(`0\r
6
6
  \r
7
- `,`latin1`)),this.finished=!0,t.length===0){e();return}this._writeToSocket(a.Buffer.concat(t),e)}end(e,t,n){if(e!=null&&typeof e!=`function`&&!this._bodyWritten&&!this.headersSent&&!this.chunkedEncoding&&!this.hasHeader(`content-length`)){let n=typeof t==`string`?t:void 0;this.setHeader(`Content-Length`,Ze(e,n).length)}return super.end(e,t,n)}_headBlock},G=class extends W{statusCode=200;statusMessage;_writeHeadCalled=!1;sendDate=!0;req;socket;_keepAlive=!0;constructor(e){super(),this.req=e,this.socket=e.socket}_shouldSendBody(){if(this.req.method===`HEAD`)return!1;let e=this.statusCode;return!(e>=100&&e<200||e===204||e===304)}writeHead(e,t,n){if(this._writeHeadCalled||this.headersSent)throw V(Error(`Cannot render headers after they are sent to the client`),`ERR_HTTP_HEADERS_SENT`);this._writeHeadCalled=!0,this.statusCode=e;let r=n;if(typeof t==`string`?this.statusMessage=t:t!=null&&(r=t),Array.isArray(r)){let e=Array.isArray(r[0])?r:Array.from({length:Math.floor(r.length/2)},(e,t)=>[r[t*2],r[t*2+1]]);for(let[t,n]of e)n!==void 0&&this._appendHeader(t,n)}else if(r)for(let[e,t]of Object.entries(r))t!==void 0&&this.setHeader(e,t);return this}_appendHeader(e,t){let n=this.getHeader(e);if(n===void 0)this.setHeader(e,t);else{let r=[...Array.isArray(n)?n:[n],...Array.isArray(t)?t:[t]].map(String);this.setHeader(e,r)}}_implicitHeader(){let e=this.statusMessage??R[this.statusCode]??`unknown`;this.sendDate&&!this.hasHeader(`date`)&&this.setHeader(`Date`,new Date().toUTCString()),this.hasHeader(`connection`)||this.setHeader(`Connection`,this._keepAlive?`keep-alive`:`close`),this._headBlock=this._storeHeader(`HTTP/1.1 ${this.statusCode} ${e}`)}writeContinue(){this._writeToSocket(a.Buffer.from(`HTTP/1.1 100 Continue\r
7
+ `,`latin1`)),this.finished=!0,t.length===0){e();return}this._writeToSocket(a.Buffer.concat(t),e)}end(e,t,n){if(e!=null&&typeof e!=`function`&&!this._bodyWritten&&!this.headersSent&&!this.chunkedEncoding&&!this.hasHeader(`content-length`)){let n=typeof t==`string`?t:void 0;this.setHeader(`Content-Length`,Qe(e,n).length)}return super.end(e,t,n)}_headBlock},K=class extends G{statusCode=200;statusMessage;_writeHeadCalled=!1;sendDate=!0;req;socket;_keepAlive=!0;constructor(e){super(),this.req=e,this.socket=e.socket}_shouldSendBody(){if(this.req.method===`HEAD`)return!1;let e=this.statusCode;return!(e>=100&&e<200||e===204||e===304)}writeHead(e,t,n){if(this._writeHeadCalled||this.headersSent)throw H(Error(`Cannot render headers after they are sent to the client`),`ERR_HTTP_HEADERS_SENT`);this._writeHeadCalled=!0,this.statusCode=e;let r=n;if(typeof t==`string`?this.statusMessage=t:t!=null&&(r=t),Array.isArray(r)){let e=Array.isArray(r[0])?r:Array.from({length:Math.floor(r.length/2)},(e,t)=>[r[t*2],r[t*2+1]]);for(let[t,n]of e)n!==void 0&&this._appendHeader(t,n)}else if(r)for(let[e,t]of Object.entries(r))t!==void 0&&this.setHeader(e,t);return this}_appendHeader(e,t){let n=this.getHeader(e);if(n===void 0)this.setHeader(e,t);else{let r=[...Array.isArray(n)?n:[n],...Array.isArray(t)?t:[t]].map(String);this.setHeader(e,r)}}_implicitHeader(){let e=this.statusMessage??z[this.statusCode]??`unknown`;this.sendDate&&!this.hasHeader(`date`)&&this.setHeader(`Date`,new Date().toUTCString()),this.hasHeader(`connection`)||this.setHeader(`Connection`,this._keepAlive?`keep-alive`:`close`),this._headBlock=this._storeHeader(`HTTP/1.1 ${this.statusCode} ${e}`)}writeContinue(){this._writeToSocket(a.Buffer.from(`HTTP/1.1 100 Continue\r
8
8
  \r
9
- `,`latin1`),()=>{})}setTimeout(e,t){return this.socket?.setTimeout(e,t),this}},Qe=(...e)=>{let t={},n={},r,i=[...e],a=i.shift();if(typeof a==`string`||a instanceof URL){let e=typeof a==`string`?new URL(a):a;t={protocol:e.protocol,hostname:e.hostname,host:e.hostname,port:e.port,path:`${e.pathname}${e.search}`,auth:e.username?`${e.username}:${e.password}`:void 0};let o=i.shift();typeof o==`function`?r=o:o&&typeof o==`object`&&(n=o,r=i.shift())}else a&&typeof a==`object`&&(n=a,r=i.shift());return{options:{...t,...n},callback:r}},K=class extends W{method;path;host;protocol;socket;get connection(){return this.socket}res=null;aborted=!1;_aborted=!1;constructor(e,t){super(),this.method=(e.method??`GET`).toUpperCase(),this.path=e.path??`/`,this.protocol=e.protocol??`http:`;let n=e.hostname??e.host??`localhost`;this.host=n;let r=Number(e.port??(this.protocol===`https:`?443:80));if(t&&this.once(`response`,t),e.headers)for(let[t,n]of Object.entries(e.headers))n!==void 0&&this.setHeader(t,n);if(!this.hasHeader(`host`)){let e=this.protocol===`https:`&&r===443||this.protocol!==`https:`&&r===80;this.setHeader(`Host`,e?n:`${n}:${r}`)}e.auth&&!this.hasHeader(`authorization`)&&this.setHeader(`Authorization`,`Basic ${a.Buffer.from(e.auth).toString(`base64`)}`),this.socket=new P,this.emit(`socket`,this.socket),this.socket.on(`error`,e=>{this._aborted||this.emit(`error`,e)}),this._attachResponseParser(),this.socket.connect({host:n,port:r},()=>{this.emit(`connect`)})}_shouldSendBody(){return this.method!==`GET`&&this.method!==`HEAD`&&this.method!==`DELETE`}_implicitHeader(){this._headBlock=this._storeHeader(`${this.method} ${this.path} HTTP/1.1`)}_attachResponseParser(){let e=new U(this.socket),t=new H(`response`,{onHeaders:n=>{e._applyHead(n),this.method===`HEAD`&&(t.skipBody=!0),this.res=e,this.emit(`response`,e)},onBody:t=>{e.push(a.Buffer.from(t))},onComplete:()=>{e.complete=!0,e.push(null)}});this.socket.on(`data`,e=>{this._aborted||t.execute(e)}),this.socket.on(`end`,()=>{t.finish()}),this.socket.on(`close`,()=>{this.emit(`close`)})}abort(){this._aborted||(this._aborted=!0,this.aborted=!0,this.emit(`abort`),this.socket.destroy())}destroy(e){return this._aborted?this:(this._aborted=!0,this.socket.destroy(e),super.destroy(e),this)}end(e,t,n){return this._aborted?this:super.end(e,t,n)}_writeToSocket(e,t){if(this._aborted){t();return}super._writeToSocket(e,t)}setTimeout(e,t){return this.socket.setTimeout(e,t),this}setNoDelay(e){this.socket.setNoDelay(e)}setSocketKeepAlive(e,t){this.socket.setKeepAlive(e,t)}},q=new Proxy(class extends F{constructor(e,t){let n={},r=t;typeof e==`function`?r=e:e&&(n=e),super(n),r&&this.on(`request`,r),this.on(`connection`,e=>this._handleConnection(e))}_handleConnection(e){let t=null,n=new H(`request`,{onHeaders:r=>{t=new U(e),t._applyHead(r),r.method===`HEAD`&&(n.skipBody=!0);let i=new G(t),a=String(r.headers.connection??``).toLowerCase();i._keepAlive=r.httpVersionMinor>=1?a!==`close`:a===`keep-alive`,i.on(`finish`,()=>{i._keepAlive||e.end()}),this.emit(`request`,t,i)},onBody:e=>{t?.push(a.Buffer.from(e))},onComplete:()=>{t&&(t.complete=!0,t.push(null)),t=null}});e.on(`data`,e=>n.execute(e)),e.on(`end`,()=>{n.finish(),t&&t.push(null)}),e.on(`error`,t=>this.emit(`clientError`,t,e))}},{apply:(e,t,n)=>new e(...n)}),J=class{maxSockets;maxFreeSockets;keepAlive;options;constructor(e={}){this.options=e,this.keepAlive=!!e.keepAlive,this.maxSockets=e.maxSockets??1/0,this.maxFreeSockets=e.maxFreeSockets??256}getName(e={}){return`${e.host??`localhost`}:${e.port??``}:${e.localAddress??``}`}destroy(){}},$e=new J,Y=(...e)=>{let{options:t,callback:n}=Qe(...e);return new K(t,n)},et=(...e)=>{let t=Y(...e);return t.end(),t},tt=(e,t)=>new q(e,t),nt={METHODS:Ge,STATUS_CODES:R,Agent:J,globalAgent:$e,Server:q,ServerResponse:G,IncomingMessage:U,ClientRequest:K,OutgoingMessage:W,createServer:tt,request:Y,get:et},rt=e.g({available:()=>it,dgram:()=>ze,dns:()=>Oe,fetch:()=>Ee,http:()=>Ue,net:()=>Fe,quota:()=>De}),it=()=>we,X=async e=>{if(typeof window>`u`)return!1;if(l())return!0;let t=await A,n=null,r=new Promise(e=>{n=()=>{l()&&e(!0)},c.addEventListener(`statuschange`,n)}),i=t.installPrompt.show(e).then(()=>!1),a=await Promise.race([r,i]);return n&&c.removeEventListener(`statuschange`,n),await t.installPrompt.hide().catch(()=>{}),a},Z=null;d(()=>(Z||=X().then(()=>void 0).finally(()=>{Z=null}),Z));var at=e.g({available:()=>ot,dgram:()=>ut,dns:()=>ct,fetch:()=>st,fs:()=>dt,net:()=>lt}),ot=()=>!1,Q=e=>(...t)=>{throw Error(`The FKN desktop app is not connected, desktop.${e} is unavailable`)},st=Q(`fetch`),ct={lookup:Q(`dns.lookup`)},lt={connect:Q(`net.connect`),createConnection:Q(`net.createConnection`),createServer:Q(`net.createServer`)},ut={createSocket:Q(`dgram.createSocket`)},dt={isLocalDirectorySupported:()=>!1,pickLocalDirectory:Q(`fs.pickLocalDirectory`),queryDirectoryPermission:Q(`fs.queryDirectoryPermission`),ensureDirectoryPermission:Q(`fs.ensureDirectoryPermission`)},ft=()=>typeof document<`u`&&l(),pt=async(e,t)=>{if(j(e),t?.credentials===`include`){if(typeof document>`u`)throw Error(`fetch with credentials needs the FKN extension, which only exists in window realms`);return v(e,t)}return ft()?v(e,{...t,credentials:`omit`}):ot()?st(e,t):Ee(e,t)},mt=e.g({ATTACH_FRAME_EVENT_KEY:()=>b,assertAttachableFrameUrl:()=>S,assertFetchableUrl:()=>_,attachFrame:()=>de,attachFramePermission:()=>le,available:()=>ft,box:()=>e.u,cookies:()=>oe,createVideoElementHandle:()=>e.d,events:()=>c,extension:()=>c,fetch:()=>v,fetchCredentialedPermission:()=>h,fetchPermission:()=>m,gotoPermission:()=>ue,handleRevivableModules:()=>e.l,isBlockedFetchUrl:()=>g,isBlockedFrameUrl:()=>x,isExtensionExposed:()=>l,isType:()=>e.f,modifyRequestHeadersPermission:()=>se,permissions:()=>fe,promptInstall:()=>X,readCookiePermission:()=>ae,removeRequestHeaderRule:()=>y,revive:()=>e.p,setMissingExtensionHandler:()=>d,setRequestHeaderRule:()=>ce,type:()=>e.m,waitForExtensionExposure:()=>f}),ht=e.g({ensureDirectoryPermission:()=>vt,isLocalDirectorySupported:()=>gt,pickLocalDirectory:()=>_t,queryDirectoryPermission:()=>$}),gt=()=>typeof window<`u`&&`showDirectoryPicker`in window,_t=async(e={})=>{if(!gt())return;let t=window.showDirectoryPicker;return t({mode:`readwrite`,...e}).catch(e=>{if(e?.name!==`AbortError`)throw e})},$=async(e,t=`readwrite`)=>{let{queryPermission:n}=e;return await n?.call(e,{mode:t})??`granted`},vt=async(e,t=`readwrite`)=>{if(await $(e,t)===`granted`)return!0;let{requestPermission:n}=e;return await n?.call(e,{mode:t})===`granted`},yt=`https://fkn.app`,bt=(e,n)=>{if(typeof window>`u`)throw Error(`FKN @fkn/lib: relayWorker must be called from the main thread`);if(!D?.contentWindow)throw Error(`FKN @fkn/lib: relayWorker called before the FKN iframe was injected`);(0,t.relay)({receive:window,emit:D.contentWindow},e,{key:`fkn-api`,originA:n?.originA??yt,originB:n?.originB??`*`,unregisterSignal:n?.unregisterSignal})};exports.ATTACH_FRAME_EVENT_KEY=b,exports.assertAttachableFrameUrl=S,exports.assertFetchableUrl=_,exports.attachFrame=de,exports.attachFramePermission=le,exports.box=e.u,Object.defineProperty(exports,`cloud`,{enumerable:!0,get:function(){return rt}}),exports.cookies=oe,exports.createVideoElementHandle=e.d,Object.defineProperty(exports,`desktop`,{enumerable:!0,get:function(){return at}}),Object.defineProperty(exports,`dgram`,{enumerable:!0,get:function(){return ze}}),Object.defineProperty(exports,`dns`,{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,`extension`,{enumerable:!0,get:function(){return mt}}),exports.fetch=pt,exports.fetchCredentialedPermission=h,exports.fetchPermission=m,Object.defineProperty(exports,`fs`,{enumerable:!0,get:function(){return ht}}),exports.gotoPermission=ue,exports.handleRevivableModules=e.l,Object.defineProperty(exports,`http`,{enumerable:!0,get:function(){return Ue}}),exports.isBlockedFetchUrl=g,exports.isBlockedFrameUrl=x,exports.isExtensionExposed=l,exports.isType=e.f,exports.modifyRequestHeadersPermission=se,Object.defineProperty(exports,`net`,{enumerable:!0,get:function(){return Fe}}),exports.permissions=fe,exports.promptInstall=X,exports.readCookiePermission=ae,exports.relayWorker=bt,exports.removeRequestHeaderRule=y,exports.revive=e.p,exports.setMissingExtensionHandler=d,exports.setRequestHeaderRule=ce,exports.type=e.m,exports.waitForExtensionExposure=f;
9
+ `,`latin1`),()=>{})}setTimeout(e,t){return this.socket?.setTimeout(e,t),this}},$e=(...e)=>{let t={},n={},r,i=[...e],a=i.shift();if(typeof a==`string`||a instanceof URL){let e=typeof a==`string`?new URL(a):a;t={protocol:e.protocol,hostname:e.hostname,host:e.hostname,port:e.port,path:`${e.pathname}${e.search}`,auth:e.username?`${e.username}:${e.password}`:void 0};let o=i.shift();typeof o==`function`?r=o:o&&typeof o==`object`&&(n=o,r=i.shift())}else a&&typeof a==`object`&&(n=a,r=i.shift());return{options:{...t,...n},callback:r}},q=class extends G{method;path;host;protocol;socket;get connection(){return this.socket}res=null;aborted=!1;_aborted=!1;constructor(e,t){super(),this.method=(e.method??`GET`).toUpperCase(),this.path=e.path??`/`,this.protocol=e.protocol??`http:`;let n=e.hostname??e.host??`localhost`;this.host=n;let r=Number(e.port??(this.protocol===`https:`?443:80));if(t&&this.once(`response`,t),e.headers)for(let[t,n]of Object.entries(e.headers))n!==void 0&&this.setHeader(t,n);if(!this.hasHeader(`host`)){let e=this.protocol===`https:`&&r===443||this.protocol!==`https:`&&r===80;this.setHeader(`Host`,e?n:`${n}:${r}`)}e.auth&&!this.hasHeader(`authorization`)&&this.setHeader(`Authorization`,`Basic ${a.Buffer.from(e.auth).toString(`base64`)}`),this.socket=new P,this.emit(`socket`,this.socket),this.socket.on(`error`,e=>{this._aborted||this.emit(`error`,e)}),this._attachResponseParser(),this.socket.connect({host:n,port:r},()=>{this.emit(`connect`)})}_shouldSendBody(){return this.method!==`GET`&&this.method!==`HEAD`&&this.method!==`DELETE`}_implicitHeader(){this._headBlock=this._storeHeader(`${this.method} ${this.path} HTTP/1.1`)}_attachResponseParser(){let e=new W(this.socket),t=new U(`response`,{onHeaders:n=>{e._applyHead(n),this.method===`HEAD`&&(t.skipBody=!0),this.res=e,this.emit(`response`,e)},onBody:t=>{e.push(a.Buffer.from(t))},onComplete:()=>{e.complete=!0,e.push(null)}});this.socket.on(`data`,e=>{this._aborted||t.execute(e)}),this.socket.on(`end`,()=>{t.finish()}),this.socket.on(`close`,()=>{this.emit(`close`)})}abort(){this._aborted||(this._aborted=!0,this.aborted=!0,this.emit(`abort`),this.socket.destroy())}destroy(e){return this._aborted?this:(this._aborted=!0,this.socket.destroy(e),super.destroy(e),this)}end(e,t,n){return this._aborted?this:super.end(e,t,n)}_writeToSocket(e,t){if(this._aborted){t();return}super._writeToSocket(e,t)}setTimeout(e,t){return this.socket.setTimeout(e,t),this}setNoDelay(e){this.socket.setNoDelay(e)}setSocketKeepAlive(e,t){this.socket.setKeepAlive(e,t)}},J=new Proxy(class extends F{constructor(e,t){let n={},r=t;typeof e==`function`?r=e:e&&(n=e),super(n),r&&this.on(`request`,r),this.on(`connection`,e=>this._handleConnection(e))}_handleConnection(e){let t=null,n=new U(`request`,{onHeaders:r=>{t=new W(e),t._applyHead(r),r.method===`HEAD`&&(n.skipBody=!0);let i=new K(t),a=String(r.headers.connection??``).toLowerCase();i._keepAlive=r.httpVersionMinor>=1?a!==`close`:a===`keep-alive`,i.on(`finish`,()=>{i._keepAlive||e.end()}),this.emit(`request`,t,i)},onBody:e=>{t?.push(a.Buffer.from(e))},onComplete:()=>{t&&(t.complete=!0,t.push(null)),t=null}});e.on(`data`,e=>n.execute(e)),e.on(`end`,()=>{n.finish(),t&&t.push(null)}),e.on(`error`,t=>this.emit(`clientError`,t,e))}},{apply:(e,t,n)=>new e(...n)}),Y=class{maxSockets;maxFreeSockets;keepAlive;options;constructor(e={}){this.options=e,this.keepAlive=!!e.keepAlive,this.maxSockets=e.maxSockets??1/0,this.maxFreeSockets=e.maxFreeSockets??256}getName(e={}){return`${e.host??`localhost`}:${e.port??``}:${e.localAddress??``}`}destroy(){}},et=new Y,X=(...e)=>{let{options:t,callback:n}=$e(...e);return new q(t,n)},tt=(...e)=>{let t=X(...e);return t.end(),t},nt=(e,t)=>new J(e,t),rt={METHODS:Ke,STATUS_CODES:z,Agent:Y,globalAgent:et,Server:J,ServerResponse:K,IncomingMessage:W,ClientRequest:q,OutgoingMessage:G,createServer:nt,request:X,get:tt},it=e.g({available:()=>at,dgram:()=>ze,dns:()=>Oe,fetch:()=>j,http:()=>We,net:()=>Fe,quota:()=>De}),at=()=>Te,Z=async e=>{if(typeof window>`u`)return!1;if(l())return!0;let t=await k,n=null,r=new Promise(e=>{n=()=>{l()&&e(!0)},c.addEventListener(`statuschange`,n)}),i=t.installPrompt.show(e).then(()=>!1),a=await Promise.race([r,i]);return n&&c.removeEventListener(`statuschange`,n),await t.installPrompt.hide().catch(()=>{}),a},Q=null;d(()=>(Q||=Z().then(()=>void 0).finally(()=>{Q=null}),Q));var ot=e.g({available:()=>st,dgram:()=>dt,dns:()=>lt,fetch:()=>ct,fs:()=>ft,net:()=>ut}),st=()=>!1,$=e=>(...t)=>{throw Error(`The FKN desktop app is not connected, desktop.${e} is unavailable`)},ct=$(`fetch`),lt={lookup:$(`dns.lookup`)},ut={connect:$(`net.connect`),createConnection:$(`net.createConnection`),createServer:$(`net.createServer`)},dt={createSocket:$(`dgram.createSocket`)},ft={isLocalDirectorySupported:()=>!1,pickLocalDirectory:$(`fs.pickLocalDirectory`),queryDirectoryPermission:$(`fs.queryDirectoryPermission`),ensureDirectoryPermission:$(`fs.ensureDirectoryPermission`)},pt=()=>typeof document<`u`&&l(),mt=async(e,t)=>{if(A(e),t?.credentials===`include`){if(typeof document>`u`)throw Error(`fetch with credentials needs the FKN extension, which only exists in window realms`);return _(e,t)}return pt()?_(e,{...t,credentials:`omit`}):st()?ct(e,t):j(e,t)},ht=e.g({ATTACH_FRAME_EVENT_KEY:()=>b,assertAttachableFrameUrl:()=>S,assertFetchableUrl:()=>g,attachFrame:()=>de,attachFramePermission:()=>le,available:()=>pt,box:()=>e.u,cookies:()=>y,createVideoElementHandle:()=>e.d,events:()=>c,extension:()=>c,fetch:()=>_,fetchCredentialedPermission:()=>ne,fetchPermission:()=>m,gotoPermission:()=>ue,handleRevivableModules:()=>e.l,isBlockedFetchUrl:()=>h,isBlockedFrameUrl:()=>x,isExtensionExposed:()=>l,isType:()=>e.f,modifyRequestHeadersPermission:()=>oe,permissions:()=>fe,promptInstall:()=>Z,readCookiePermission:()=>v,removeRequestHeaderRule:()=>ce,revive:()=>e.p,setMissingExtensionHandler:()=>d,setRequestHeaderRule:()=>se,type:()=>e.m,waitForExtensionExposure:()=>f}),gt=e.g({ensureDirectoryPermission:()=>bt,isLocalDirectorySupported:()=>_t,pickLocalDirectory:()=>vt,queryDirectoryPermission:()=>yt}),_t=()=>typeof window<`u`&&`showDirectoryPicker`in window,vt=async(e={})=>{if(!_t())return;let t=window.showDirectoryPicker;return t({mode:`readwrite`,...e}).catch(e=>{if(e?.name!==`AbortError`)throw e})},yt=async(e,t=`readwrite`)=>{let{queryPermission:n}=e;return await n?.call(e,{mode:t})??`granted`},bt=async(e,t=`readwrite`)=>{if(await yt(e,t)===`granted`)return!0;let{requestPermission:n}=e;return await n?.call(e,{mode:t})===`granted`},xt=`https://fkn.app`,St=(e,n)=>{if(typeof window>`u`)throw Error(`FKN @fkn/lib: relayWorker must be called from the main thread`);if(!E?.contentWindow)throw Error(`FKN @fkn/lib: relayWorker called before the FKN iframe was injected`);(0,t.relay)({receive:window,emit:E.contentWindow},e,{key:`fkn-api`,originA:n?.originA??xt,originB:n?.originB??`*`,unregisterSignal:n?.unregisterSignal})};exports.ATTACH_FRAME_EVENT_KEY=b,exports.assertAttachableFrameUrl=S,exports.assertFetchableUrl=g,exports.attachFrame=de,exports.attachFramePermission=le,exports.box=e.u,Object.defineProperty(exports,`cloud`,{enumerable:!0,get:function(){return it}}),exports.cookies=y,exports.createVideoElementHandle=e.d,Object.defineProperty(exports,`desktop`,{enumerable:!0,get:function(){return ot}}),Object.defineProperty(exports,`dgram`,{enumerable:!0,get:function(){return ze}}),Object.defineProperty(exports,`dns`,{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,`extension`,{enumerable:!0,get:function(){return ht}}),exports.fetch=mt,exports.fetchCredentialedPermission=ne,exports.fetchPermission=m,Object.defineProperty(exports,`fs`,{enumerable:!0,get:function(){return gt}}),exports.gotoPermission=ue,exports.handleRevivableModules=e.l,Object.defineProperty(exports,`http`,{enumerable:!0,get:function(){return We}}),exports.isBlockedFetchUrl=h,exports.isBlockedFrameUrl=x,exports.isExtensionExposed=l,exports.isType=e.f,exports.modifyRequestHeadersPermission=oe,Object.defineProperty(exports,`net`,{enumerable:!0,get:function(){return Fe}}),exports.permissions=fe,exports.promptInstall=Z,exports.readCookiePermission=v,exports.relayWorker=St,exports.removeRequestHeaderRule=ce,exports.revive=e.p,exports.setMissingExtensionHandler=d,exports.setRequestHeaderRule=se,exports.type=e.m,exports.waitForExtensionExposure=f;
package/index.d.ts CHANGED
@@ -1044,6 +1044,8 @@ declare const makeWebVPNWebTransport: () => Promise<{
1044
1044
  readonly dataLength: number;
1045
1045
  readonly data: ArrayBuffer;
1046
1046
  }>;
1047
+ claimUdpRawStream: (socketId: number, sink: (packetBytes: Uint8Array) => void) => void;
1048
+ releaseUdpRawStream: (socketId: number) => void;
1047
1049
  getPacketForId: (packetId: number) => Promise<ServerMetadataPacket>;
1048
1050
  getMetadataReadableStreamForSocketId: (socketId: number) => ReadableStream<ServerMetadataPacket>;
1049
1051
  getMetadataReadableStreamForLocalAddress: (address: Address4 | Address6) => ReadableStream<ServerMetadataPacket>;
@@ -1094,7 +1096,7 @@ type Quota = {
1094
1096
 
1095
1097
  declare const resolvers: {
1096
1098
  readonly cloud: {
1097
- readonly fetch: (input: string | Request | URL, init?: (RequestInit | undefined) & {
1099
+ readonly fetch: (input: string | URL | Request, init?: (RequestInit | undefined) & {
1098
1100
  render?: boolean;
1099
1101
  }) => Promise<Response>;
1100
1102
  readonly quota: () => Promise<Quota>;
@@ -1133,11 +1135,14 @@ declare const resolvers: {
1133
1135
  localPort: number;
1134
1136
  close: () => Promise<void>;
1135
1137
  }>;
1136
- readonly udpSocket: ({ type, port, address }: {
1138
+ readonly udpSocket: ({ type, port, address, dataPort }: {
1137
1139
  type: "udp4" | "udp6";
1138
1140
  port: number;
1139
1141
  address: string;
1142
+ dataPort?: boolean;
1140
1143
  }) => Promise<{
1144
+ socketId: number;
1145
+ dataPort: MessagePort | undefined;
1141
1146
  localAddress: string;
1142
1147
  localFamily: "IPv4" | "IPv6";
1143
1148
  localPort: number;
@@ -1177,7 +1182,7 @@ declare const resolvers: {
1177
1182
  readonly show: (reason?: string) => Promise<void>;
1178
1183
  readonly hide: () => void;
1179
1184
  };
1180
- readonly proxyFetch: (input: string | Request | URL, init?: (RequestInit | undefined) & {
1185
+ readonly proxyFetch: (input: string | URL | Request, init?: (RequestInit | undefined) & {
1181
1186
  render?: boolean;
1182
1187
  }) => Promise<Response>;
1183
1188
  readonly webVpnTcpSocket: ({ remoteAddress: _remoteAddress, remotePort }: {
@@ -1208,11 +1213,14 @@ declare const resolvers: {
1208
1213
  localPort: number;
1209
1214
  close: () => Promise<void>;
1210
1215
  }>;
1211
- readonly webVpnUdpSocket: ({ type, port, address }: {
1216
+ readonly webVpnUdpSocket: ({ type, port, address, dataPort }: {
1212
1217
  type: "udp4" | "udp6";
1213
1218
  port: number;
1214
1219
  address: string;
1220
+ dataPort?: boolean;
1215
1221
  }) => Promise<{
1222
+ socketId: number;
1223
+ dataPort: MessagePort | undefined;
1216
1224
  localAddress: string;
1217
1225
  localFamily: "IPv4" | "IPv6";
1218
1226
  localPort: number;
@@ -1476,6 +1484,12 @@ declare class Socket extends EventEmitter implements Socket$3 {
1476
1484
  port: number;
1477
1485
  };
1478
1486
  _webVPNUdpSocketPromise?: Promise<Awaited<ReturnType<WebVpnUdpSocket>> | undefined>;
1487
+ _dataPort?: MessagePort;
1488
+ _socketId?: number;
1489
+ _sendQueue: Uint8Array[];
1490
+ _sendQueueBytes: number;
1491
+ _sendFlushScheduled: boolean;
1492
+ _peerTailCache: Map<string, Uint8Array<ArrayBufferLike>>;
1479
1493
  constructor(options: SocketOptions & EventEmitterOptions & {
1480
1494
  connection?: ReturnType<WebVpnUdpSocket>;
1481
1495
  });
@@ -1485,6 +1499,9 @@ declare class Socket extends EventEmitter implements Socket$3 {
1485
1499
  _lastMulticastTtl: number;
1486
1500
  _lastMulticastLoopback: boolean;
1487
1501
  _setUdpOption(option: UdpSocketOption): void;
1502
+ _onDataPortBatch(buffer: ArrayBuffer): void;
1503
+ _peerTail(address: string | undefined, port: number | undefined): Uint8Array;
1504
+ _portSend(message: Uint8Array, address: string | undefined, port: number | undefined): void;
1488
1505
  addMembership(multicastAddress: string, multicastInterface?: string | undefined): void;
1489
1506
  address(): AddressInfo;
1490
1507
  bind(port?: number | undefined, address?: string | undefined, callback?: (() => void) | undefined): this;
package/index.js CHANGED
@@ -1,56 +1,56 @@
1
1
  import { d as e, f as t, g as n, i as r, l as i, m as a, p as o, r as s, t as c, u as l } from "./locator-DUbu14FW.js";
2
- import { createTypedEventTarget as ee, expose as te, relay as ne } from "osra";
3
- import { Stream as u } from "stream";
4
- import { EventEmitter as re } from "events";
5
- import { Address4 as d, Address6 as f } from "ip-address";
6
- import { Buffer as p } from "buffer";
2
+ import { createTypedEventTarget as u, expose as ee, relay as te } from "osra";
3
+ import { Stream as d } from "stream";
4
+ import { EventEmitter as ne } from "events";
5
+ import { Address4 as f, Address6 as p } from "ip-address";
6
+ import { Buffer as m } from "buffer";
7
7
  //#region node_modules/@mfkn/web-extension/lib/utils/extension.js
8
- var ie = "FKN_WEB_EXTENSION_MAIN_WORLD_CONTENT_SCRIPT_ENABLED_EVENT_KEY", ae = "fknExtension", m = ee();
9
- typeof document < "u" && document.addEventListener(ie, (e) => {
10
- m.dispatchEvent(new CustomEvent("statuschange", { detail: { enabled: e.detail.enabled } }));
8
+ var re = "FKN_WEB_EXTENSION_MAIN_WORLD_CONTENT_SCRIPT_ENABLED_EVENT_KEY", ie = "fknExtension", h = u();
9
+ typeof document < "u" && document.addEventListener(re, (e) => {
10
+ h.dispatchEvent(new CustomEvent("statuschange", { detail: { enabled: e.detail.enabled } }));
11
11
  });
12
- var h = () => typeof document > "u" ? !1 : document.documentElement.dataset[ae] === "true", g = null, _ = (e) => {
13
- g = e;
14
- }, oe = 150, v = (e = 1e3) => new Promise((t, n) => {
15
- if (h()) return t();
12
+ var g = () => typeof document > "u" ? !1 : document.documentElement.dataset[ie] === "true", _ = null, v = (e) => {
13
+ _ = e;
14
+ }, ae = 150, y = (e = 1e3) => new Promise((t, n) => {
15
+ if (g()) return t();
16
16
  let r, i = (e) => {
17
17
  clearTimeout(r), s.disconnect(), document.removeEventListener("readystatechange", c), e();
18
18
  }, a = () => i(async () => {
19
- if (g && (await g().catch(() => {}), h())) return t();
19
+ if (_ && (await _().catch(() => {}), g())) return t();
20
20
  n(/* @__PURE__ */ Error("The FKN WebExtension is not installed, enabled or not exposed on this page."));
21
21
  }), o = () => {
22
- clearTimeout(r), r = setTimeout(() => h() ? i(t) : a(), oe);
22
+ clearTimeout(r), r = setTimeout(() => g() ? i(t) : a(), ae);
23
23
  }, s = new MutationObserver(() => {
24
- h() && i(t);
24
+ g() && i(t);
25
25
  }), c = () => {
26
- document.readyState === "complete" && !h() && o();
26
+ document.readyState === "complete" && !g() && o();
27
27
  };
28
28
  if (r = setTimeout(a, e), s.observe(document.documentElement, {
29
29
  attributes: !0,
30
30
  attributeFilter: ["data-fkn-extension"]
31
31
  }), document.addEventListener("readystatechange", c), document.readyState === "complete") return o();
32
- h() && i(t);
33
- }), se, y = new Proxy({}, { get: (e, t) => async (...e) => {
34
- await v(), se ??= te({}, {
32
+ g() && i(t);
33
+ }), oe, b = new Proxy({}, { get: (e, t) => async (...e) => {
34
+ await y(), oe ??= ee({}, {
35
35
  transport: window,
36
36
  revivableModules: i
37
37
  });
38
- let n = (await se)[t];
38
+ let n = (await oe)[t];
39
39
  return n(...e);
40
- } }), ce = {
40
+ } }), se = {
41
41
  scope: "network.fetch",
42
42
  category: "network",
43
43
  severity: 0,
44
44
  title: "Fetch data from other sites",
45
45
  description: "Lets the app download public data from other websites directly, past the usual cross-origin limits."
46
- }, le = {
46
+ }, ce = {
47
47
  scope: "network.fetchCredentialed",
48
48
  category: "network",
49
49
  severity: 3,
50
50
  unsafe: !0,
51
51
  title: "Fetch from other sites, signed in as you",
52
52
  description: "Lets the app fetch other sites using your logged-in session cookies, so it can read data only you should see."
53
- }, ue = ["fkn.app", "fkn.dev"], b = (e) => {
53
+ }, le = ["fkn.app", "fkn.dev"], x = (e) => {
54
54
  let t;
55
55
  try {
56
56
  t = new URL(e);
@@ -59,46 +59,46 @@ var h = () => typeof document > "u" ? !1 : document.documentElement.dataset[ae]
59
59
  }
60
60
  if (t.protocol === "chrome-extension:" || t.protocol === "moz-extension:") return !0;
61
61
  let n = t.hostname;
62
- return ue.some((e) => n === e || n.endsWith(`.${e}`));
63
- }, x = (e) => {
64
- if (b(e)) throw Error("fetch: refusing to target the extension's own pages or FKN platform domains");
65
- }, de = ["origin", "referer"], fe = (e) => {
62
+ return le.some((e) => n === e || n.endsWith(`.${e}`));
63
+ }, S = (e) => {
64
+ if (x(e)) throw Error("fetch: refusing to target the extension's own pages or FKN platform domains");
65
+ }, ue = ["origin", "referer"], de = (e) => {
66
66
  if (!e?.headers) return;
67
- let t = new Headers(e.headers), n = de.map((e) => {
67
+ let t = new Headers(e.headers), n = ue.map((e) => {
68
68
  let n = t.get(e);
69
69
  return n === null ? void 0 : [e, n];
70
70
  }).filter((e) => e !== void 0);
71
71
  return n.length ? n : void 0;
72
- }, S = async (e, t) => {
72
+ }, C = async (e, t) => {
73
73
  let n = new Request(e, t);
74
- x(n.url);
74
+ S(n.url);
75
75
  let r = n.body ? await n.arrayBuffer() : null;
76
- return y.proxyFetch({
76
+ return b.proxyFetch({
77
77
  url: n.url,
78
78
  method: n.method,
79
79
  headers: [...n.headers],
80
80
  body: r,
81
81
  credentials: t?.credentials === "include" ? "include" : "omit",
82
82
  redirect: n.redirect,
83
- unsafeHeaders: fe(t),
83
+ unsafeHeaders: de(t),
84
84
  reason: t?.reason,
85
85
  signal: t?.signal ?? void 0
86
86
  });
87
- }, pe = {
87
+ }, fe = {
88
88
  scope: "network.readCookie",
89
89
  category: "network",
90
90
  severity: 3,
91
91
  unsafe: !0,
92
92
  title: "Read a site’s cookie",
93
93
  description: "Lets the app read a named cookie from another site, which can include the login token only that site should see."
94
- }, me = { get: (e) => y.getCookie(e) }, he = {
94
+ }, pe = { get: (e) => b.getCookie(e) }, me = {
95
95
  scope: "network.modifyRequestHeaders",
96
96
  category: "network",
97
97
  severity: 2,
98
98
  unsafe: !0,
99
99
  title: "Rewrite request headers to other sites",
100
100
  description: "Lets the app set or remove headers (like Origin and Referer) on this page’s own requests to the listed sites."
101
- }, ge = (e) => y.setRequestHeaderRule(e), _e = (e) => y.removeRequestHeaderRule({ ruleId: e });
101
+ }, he = (e) => b.setRequestHeaderRule(e), ge = (e) => b.removeRequestHeaderRule({ ruleId: e });
102
102
  (() => {
103
103
  let e = {}, t = [...c.selectorModules, ...r.selectorModules];
104
104
  for (let n of t) n.render && !(n.type in e) && (e[n.type] = n.render);
@@ -106,7 +106,7 @@ var h = () => typeof document > "u" ? !1 : document.documentElement.dataset[ae]
106
106
  })();
107
107
  //#endregion
108
108
  //#region node_modules/@mfkn/web-extension/lib/lib/frame.js
109
- var C = "FKN_WEB_EXTENSION_ATTACH_FRAME_EVENT_KEY", w = (e) => {
109
+ var w = "FKN_WEB_EXTENSION_ATTACH_FRAME_EVENT_KEY", T = (e) => {
110
110
  if (!e || e === "about:blank") return !1;
111
111
  let t;
112
112
  try {
@@ -118,28 +118,28 @@ var C = "FKN_WEB_EXTENSION_ATTACH_FRAME_EVENT_KEY", w = (e) => {
118
118
  if (t.protocol === "about:") return !1;
119
119
  let n = t.hostname;
120
120
  return n === "fkn.app" || n.endsWith(".fkn.app");
121
- }, T = (e) => {
122
- if (w(e)) throw Error("attachFrame: refusing to target the extension's own pages or fkn.app");
123
- }, ve = {
121
+ }, E = (e) => {
122
+ if (T(e)) throw Error("attachFrame: refusing to target the extension's own pages or fkn.app");
123
+ }, _e = {
124
124
  scope: "embed.iframe",
125
125
  category: "embed",
126
126
  severity: 0,
127
127
  title: "Load another website inside this app",
128
128
  description: "Lets the app embed external pages directly inside its own view."
129
- }, ye = {
129
+ }, ve = {
130
130
  scope: "embed.open",
131
131
  category: "embed",
132
132
  severity: 0,
133
133
  title: "Open a website inside this app",
134
134
  description: "Lets the app navigate to another site without leaving its window."
135
- }, be = async ({ iframe: e, domains: t = [] }) => {
135
+ }, ye = async ({ iframe: e, domains: t = [] }) => {
136
136
  let n = crypto.randomUUID();
137
- if (T(e.src), await v(), !e.isConnected) throw Error("attachFrame: the iframe must be connected to the document before attaching");
138
- e.dispatchEvent(new CustomEvent(C, { detail: n }));
139
- let { executeLocator: r, ensureLocatorPermission: i, goto: a } = await y.attachFrame({
137
+ if (E(e.src), await y(), !e.isConnected) throw Error("attachFrame: the iframe must be connected to the document before attaching");
138
+ e.dispatchEvent(new CustomEvent(w, { detail: n }));
139
+ let { executeLocator: r, ensureLocatorPermission: i, goto: a } = await b.attachFrame({
140
140
  marker: n,
141
141
  domains: t
142
- }), o = s(r, i), c = (e, t = {}) => (T(e), a({
142
+ }), o = s(r, i), c = (e, t = {}) => (E(e), a({
143
143
  url: e,
144
144
  ...t
145
145
  })), l = () => e.src;
@@ -148,22 +148,22 @@ var C = "FKN_WEB_EXTENSION_ATTACH_FRAME_EVENT_KEY", w = (e) => {
148
148
  goto: c,
149
149
  url: l
150
150
  };
151
- }, xe = { request: (e) => y.requestPermissions(e.map((e) => ({
151
+ }, be = { request: (e) => b.requestPermissions(e.map((e) => ({
152
152
  key: e.key,
153
153
  scope: e.scope ?? "",
154
154
  reason: e.reason
155
- }))) }, Se = 32, Ce = typeof CSS < "u" && CSS.supports("clip-path", "path('M0 0H1V1H0Z')"), we = (e) => {
155
+ }))) }, xe = 32, Se = typeof CSS < "u" && CSS.supports("clip-path", "path('M0 0H1V1H0Z')"), Ce = (e) => {
156
156
  let t = e.style;
157
157
  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("clip-path", "inset(100%)", "important"), t.setProperty("background", "transparent"), t.setProperty("color-scheme", "normal"), t.setProperty("z-index", "2147483647"), e.setAttribute("title", "FKN");
158
- }, Te = ({ x: e, y: t, width: n, height: r }) => `M${e} ${t}h${n}v${r}h${-n}Z`, Ee = (e, { modal: t, rects: n }) => {
159
- if (!Ce) {
158
+ }, we = ({ x: e, y: t, width: n, height: r }) => `M${e} ${t}h${n}v${r}h${-n}Z`, Te = (e, { modal: t, rects: n }) => {
159
+ if (!Se) {
160
160
  let r = t || n.length > 0;
161
161
  e.style.setProperty("pointer-events", r ? "auto" : "none", "important"), e.style.setProperty("visibility", r ? "visible" : "hidden", "important");
162
162
  return;
163
163
  }
164
- let r = t ? "none" : n.length === 0 ? "inset(100%)" : `path('${n.map(Te).join("")}')`, i = r === "none" || CSS.supports("clip-path", r) ? r : "inset(100%)";
164
+ let r = t ? "none" : n.length === 0 ? "inset(100%)" : `path('${n.map(we).join("")}')`, i = r === "none" || CSS.supports("clip-path", r) ? r : "inset(100%)";
165
165
  e.style.setProperty("clip-path", i, "important");
166
- }, De = (e) => {
166
+ }, Ee = (e) => {
167
167
  if (typeof e != "object" || !e) return null;
168
168
  let { x: t, y: n, width: r, height: i } = e;
169
169
  if (![
@@ -172,33 +172,33 @@ var C = "FKN_WEB_EXTENSION_ATTACH_FRAME_EVENT_KEY", w = (e) => {
172
172
  r,
173
173
  i
174
174
  ].every((e) => typeof e == "number" && Number.isFinite(e))) return null;
175
- let a = window.innerWidth, o = window.innerHeight, s = Math.max(0, Math.min(Math.round(t), a)), c = Math.max(0, Math.min(Math.round(n), o)), l = Math.max(s, Math.min(Math.round(t + r), a)), ee = Math.max(c, Math.min(Math.round(n + i), o));
175
+ let a = window.innerWidth, o = window.innerHeight, s = Math.max(0, Math.min(Math.round(t), a)), c = Math.max(0, Math.min(Math.round(n), o)), l = Math.max(s, Math.min(Math.round(t + r), a)), u = Math.max(c, Math.min(Math.round(n + i), o));
176
176
  return {
177
177
  x: s,
178
178
  y: c,
179
179
  width: l - s,
180
- height: ee - c
180
+ height: u - c
181
181
  };
182
- }, Oe = (e) => {
182
+ }, De = (e) => {
183
183
  if (typeof e != "object" || !e) return null;
184
- let t = e, n = (Array.isArray(t.rects) ? t.rects.slice(0, Se) : []).map(De).filter((e) => e !== null && e.width > 0 && e.height > 0);
184
+ let t = e, n = (Array.isArray(t.rects) ? t.rects.slice(0, xe) : []).map(Ee).filter((e) => e !== null && e.width > 0 && e.height > 0);
185
185
  return {
186
186
  modal: t.modal === !0,
187
187
  rects: n
188
188
  };
189
- }, E = null, ke = () => E !== null, Ae = (e) => {
190
- we(e), Ee(e, {
189
+ }, D = null, Oe = () => D !== null, ke = (e) => {
190
+ Ce(e), Te(e, {
191
191
  modal: !1,
192
192
  rects: []
193
- }), E = e;
194
- }, je = (e) => {
195
- if (!E) return;
196
- let t = Oe(e);
197
- t && Ee(E, t);
198
- }, D = "https://fkn.app", O = typeof globalThis < "u" && globalThis.document ? globalThis.document : void 0, Me = O?.querySelector(`iframe[src="${D}/api"]`) ?? null, k = O?.createElement("iframe") ?? null;
199
- !Me && k && O && (k.src = `${D}/api`, O.body.appendChild(k));
193
+ }), D = e;
194
+ }, Ae = (e) => {
195
+ if (!D) return;
196
+ let t = De(e);
197
+ t && Te(D, t);
198
+ }, je = "https://fkn.app", O = typeof globalThis < "u" && globalThis.document ? globalThis.document : void 0, Me = O?.querySelector(`iframe[src="${je}/api"]`) ?? null, k = O?.createElement("iframe") ?? null;
199
+ !Me && k && O && (k.src = `${je}/api`, O.body.appendChild(k));
200
200
  var A = Me ?? k, Ne = A?.contentWindow ?? null;
201
- A && O && Ae(A);
201
+ A && O && ke(A);
202
202
  var j = (() => {
203
203
  if (typeof window < "u") return Ne ? {
204
204
  receive: window,
@@ -208,12 +208,12 @@ var j = (() => {
208
208
  receive: self,
209
209
  emit: self
210
210
  };
211
- })(), Pe = j !== void 0, M = j ? te({}, {
211
+ })(), Pe = j !== void 0, M = j ? ee({}, {
212
212
  key: "fkn-api",
213
213
  transport: j
214
214
  }) : new Promise(() => {});
215
215
  M.then((e) => {
216
- ke() && e.overlay.setHost(je);
216
+ Oe() && e.overlay.setHost(Ae);
217
217
  }, () => {});
218
218
  //#endregion
219
219
  //#region src/lib/fkn-target.ts
@@ -240,7 +240,7 @@ var Fe = ["fkn.app", "fkn.dev"], Ie = (e) => {
240
240
  };
241
241
  }, ze = /* @__PURE__ */ n({ lookup: () => Be }), Be = (e, t) => M.then((n) => n.cloud.dns.lookup(e, t)), Ve = new TextEncoder();
242
242
  new TextDecoder();
243
- var N = (e) => d.isValid(e), P = (e) => f.isValid(e), He = (e) => N(e) ? 4 : P(e) ? 6 : 0, Ue = (...e) => {
243
+ var N = (e) => f.isValid(e), P = (e) => p.isValid(e), He = (e) => N(e) ? 4 : P(e) ? 6 : 0, Ue = (...e) => {
244
244
  if (typeof e[0] == "string") throw Error("FKN WebVPN does not support IPC connections");
245
245
  let t = typeof e.at(-1) == "function" ? e.at(-1) : void 0;
246
246
  return e[0] && typeof e[0] == "object" ? {
@@ -291,15 +291,15 @@ new TextEncoder(), new TextDecoder();
291
291
  var Ke = /* @__PURE__ */ n({
292
292
  Server: () => I,
293
293
  Socket: () => F,
294
- _default: () => Ye,
294
+ _default: () => Xe,
295
295
  connect: () => qe,
296
296
  createConnection: () => Je,
297
- createServer: () => L,
298
- default: () => Ye,
297
+ createServer: () => Ye,
298
+ default: () => Xe,
299
299
  isIP: () => He,
300
300
  isIPv4: () => N,
301
301
  isIPv6: () => P
302
- }), F = class extends u.Duplex {
302
+ }), F = class extends d.Duplex {
303
303
  _localAddress;
304
304
  _remoteAddress;
305
305
  _webVPNTcpSocketPromise;
@@ -486,7 +486,7 @@ var Ke = /* @__PURE__ */ n({
486
486
  return this._remoteAddress.family;
487
487
  }
488
488
  timeout;
489
- }, I = class extends re {
489
+ }, I = class extends ne {
490
490
  _localAddress;
491
491
  _webVPNTcpSocketListenerPromise;
492
492
  constructor(e, t) {
@@ -541,27 +541,33 @@ var Ke = /* @__PURE__ */ n({
541
541
  connections;
542
542
  listening;
543
543
  async [Symbol.asyncDispose]() {}
544
- }, qe = (e, t) => new F().connect(e, t), Je = (e, t) => new F().connect(e, t), L = (e, t) => {
544
+ }, qe = (e, t) => new F().connect(e, t), Je = (e, t) => new F().connect(e, t), Ye = (e, t) => {
545
545
  typeof e == "function" && (t = e, e = void 0);
546
546
  let n = new I(e);
547
547
  return t && n.on("connection", t), n;
548
- }, Ye = {
548
+ }, Xe = {
549
549
  Socket: F,
550
550
  Server: I,
551
551
  connect: qe,
552
552
  createConnection: Je,
553
- createServer: L,
553
+ createServer: Ye,
554
554
  isIP: He,
555
555
  isIPv4: N,
556
556
  isIPv6: P
557
- }, Xe = /* @__PURE__ */ n({
558
- Socket: () => Ze,
559
- createSocket: () => $e
560
- }), Ze = class extends re {
557
+ }, Ze = /* @__PURE__ */ n({
558
+ Socket: () => Qe,
559
+ createSocket: () => tt
560
+ }), Qe = class extends ne {
561
561
  _type;
562
562
  _localAddress;
563
563
  _remoteAddress;
564
564
  _webVPNUdpSocketPromise;
565
+ _dataPort;
566
+ _socketId;
567
+ _sendQueue = [];
568
+ _sendQueueBytes = 0;
569
+ _sendFlushScheduled = !1;
570
+ _peerTailCache = /* @__PURE__ */ new Map();
565
571
  constructor(e) {
566
572
  if (super(e), !e) throw Error("Missing options");
567
573
  this._type = e.type;
@@ -584,9 +590,63 @@ var Ke = /* @__PURE__ */ n({
584
590
  }
585
591
  });
586
592
  }
593
+ _onDataPortBatch(e) {
594
+ let t = new DataView(e), n = 0;
595
+ for (; n + 4 <= e.byteLength;) {
596
+ let r = t.getUint32(n);
597
+ n += 4;
598
+ let i = n + r;
599
+ if (i > e.byteLength) break;
600
+ let a = n + 4, o = t.getUint8(a);
601
+ a += 1;
602
+ let s, c, l;
603
+ if (o === 2) {
604
+ if (!this._remoteAddress) {
605
+ n = i;
606
+ continue;
607
+ }
608
+ s = this._remoteAddress.address, c = this._remoteAddress.family, l = this._remoteAddress.port;
609
+ } else {
610
+ let n = new Uint8Array(e, a, o === 0 ? 4 : 16);
611
+ if (o === 0) c = "IPv4", s = `${n[0]}.${n[1]}.${n[2]}.${n[3]}`;
612
+ else {
613
+ c = "IPv6";
614
+ let e = [];
615
+ for (let t = 0; t < 16; t += 2) e.push(((n[t] << 8 | n[t + 1]) >>> 0).toString(16));
616
+ s = e.join(":");
617
+ }
618
+ a += n.byteLength, l = t.getUint16(a), a += 2;
619
+ }
620
+ let u = t.getUint32(a);
621
+ a += 4, this.emit("message", m.from(e.slice(a, a + u)), {
622
+ address: s,
623
+ family: c,
624
+ port: l,
625
+ size: u
626
+ }), n = i;
627
+ }
628
+ }
629
+ _peerTail(e, t) {
630
+ if (e === void 0 || t === void 0) return $e;
631
+ let n = `${e}|${t}`, r = this._peerTailCache.get(n);
632
+ if (r) return r;
633
+ let i = f.isValid(e) ? L(e) : R(e), a = new Uint8Array(1 + i.byteLength + 2);
634
+ return a[0] = i.byteLength === 4 ? 0 : 1, a.set(i, 1), new DataView(a.buffer).setUint16(1 + i.byteLength, t), this._peerTailCache.set(n, a), a;
635
+ }
636
+ _portSend(e, t, n) {
637
+ let r = this._peerTail(t, n), i = new Uint8Array(8 + r.byteLength + 4 + e.byteLength), a = new DataView(i.buffer);
638
+ 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(() => {
639
+ this._sendFlushScheduled = !1;
640
+ let e = this._sendQueue, t = this._sendQueueBytes;
641
+ if (this._sendQueue = [], this._sendQueueBytes = 0, !e.length || !this._dataPort) return;
642
+ let n = new Uint8Array(t), r = 0;
643
+ for (let t of e) n.set(t, r), r += t.byteLength;
644
+ this._dataPort.postMessage(n.buffer, [n.buffer]);
645
+ }));
646
+ }
587
647
  addMembership(e, t) {
588
- if (d.isValid(e)) {
589
- let n = R(e), r = t && d.isValid(t) ? R(t) : new Uint8Array([
648
+ if (f.isValid(e)) {
649
+ let n = L(e), r = t && f.isValid(t) ? L(t) : new Uint8Array([
590
650
  0,
591
651
  0,
592
652
  0,
@@ -597,8 +657,8 @@ var Ke = /* @__PURE__ */ n({
597
657
  group: n,
598
658
  interface: r
599
659
  });
600
- } else if (f.isValid(e)) {
601
- let t = Qe(e);
660
+ } else if (p.isValid(e)) {
661
+ let t = R(e);
602
662
  this._setUdpOption({
603
663
  type: 7,
604
664
  group: t,
@@ -615,18 +675,23 @@ var Ke = /* @__PURE__ */ n({
615
675
  return this._webVPNUdpSocketPromise = M.then((e) => e.cloud.webvpn.udpSocket({
616
676
  type: this._type,
617
677
  address: t.address ?? n,
618
- port: t.port
678
+ port: t.port,
679
+ dataPort: !0
619
680
  })).then((e) => {
620
- let t = e.dataReadableStream.getReader(), n = async () => {
621
- let { value: e, done: r } = await t.read();
622
- r || (this.emit("message", p.from(e.data), {
623
- address: e.address,
624
- family: e.family,
625
- port: e.port,
626
- size: e.size
627
- }), n());
628
- };
629
- return n(), this._localAddress = {
681
+ if (e.dataPort) this._socketId = e.socketId, this._dataPort = e.dataPort, this._dataPort.onmessage = (e) => this._onDataPortBatch(e.data);
682
+ else {
683
+ let t = e.dataReadableStream.getReader(), n = async () => {
684
+ let { value: e, done: r } = await t.read();
685
+ r || (this.emit("message", m.from(e.data), {
686
+ address: e.address,
687
+ family: e.family,
688
+ port: e.port,
689
+ size: e.size
690
+ }), n());
691
+ };
692
+ n();
693
+ }
694
+ return this._localAddress = {
630
695
  address: e.localAddress,
631
696
  family: e.localFamily,
632
697
  port: e.localPort
@@ -636,14 +701,14 @@ var Ke = /* @__PURE__ */ n({
636
701
  }), this._webVPNUdpSocketPromise.then((e) => {
637
702
  e && this.emit("listening");
638
703
  }), t.callback && this._webVPNUdpSocketPromise.then((e) => {
639
- e && t.callback();
704
+ e && t.callback.call(this);
640
705
  }), this;
641
706
  }
642
707
  close(e) {
643
708
  if (!this._webVPNUdpSocketPromise) throw Error("Socket not bound");
644
709
  return this._webVPNUdpSocketPromise.then(async (t) => {
645
710
  if (!t) throw Error("Socket not bound");
646
- await t.close(), e && e(), this.emit("close");
711
+ this._dataPort?.close(), this._dataPort = void 0, await t.close(), e && e(), this.emit("close");
647
712
  }), this;
648
713
  }
649
714
  connect(...e) {
@@ -672,8 +737,8 @@ var Ke = /* @__PURE__ */ n({
672
737
  });
673
738
  }
674
739
  dropMembership(e, t) {
675
- if (d.isValid(e)) {
676
- let n = R(e), r = t && d.isValid(t) ? R(t) : new Uint8Array([
740
+ if (f.isValid(e)) {
741
+ let n = L(e), r = t && f.isValid(t) ? L(t) : new Uint8Array([
677
742
  0,
678
743
  0,
679
744
  0,
@@ -684,8 +749,8 @@ var Ke = /* @__PURE__ */ n({
684
749
  group: n,
685
750
  interface: r
686
751
  });
687
- } else if (f.isValid(e)) {
688
- let t = Qe(e);
752
+ } else if (p.isValid(e)) {
753
+ let t = R(e);
689
754
  this._setUdpOption({
690
755
  type: 8,
691
756
  group: t,
@@ -722,12 +787,16 @@ var Ke = /* @__PURE__ */ n({
722
787
  if (!this._webVPNUdpSocketPromise) throw Error("Socket not bound");
723
788
  this._webVPNUdpSocketPromise.then((e) => {
724
789
  if (!e) throw Error("Socket not bound");
725
- let r = typeof t.message == "string" ? Ve.encode(t.message) : t.message;
790
+ let r = et(t.message), i = t.callback, a = t.address ?? n, o = this._remoteAddress !== void 0 && t.address === void 0;
791
+ if (this._dataPort && (o || f.isValid(a) || p.isValid(a))) {
792
+ this._portSend(r, o ? void 0 : a, o ? void 0 : t.port), i?.call(this, null, r.byteLength);
793
+ return;
794
+ }
726
795
  e.send({
727
796
  ...t,
728
- address: t.address ?? n,
729
- message: r.buffer
730
- });
797
+ address: a,
798
+ message: r.byteOffset === 0 && r.byteLength === r.buffer.byteLength ? r.buffer : r.buffer.slice(r.byteOffset, r.byteOffset + r.byteLength)
799
+ }).then(() => i?.call(this, null, r.byteLength), (e) => i ? i.call(this, e, 0) : this.emit("error", e));
731
800
  });
732
801
  }
733
802
  setBroadcast(e) {
@@ -780,33 +849,43 @@ var Ke = /* @__PURE__ */ n({
780
849
  this.close(e);
781
850
  });
782
851
  }
783
- }, R = (e) => {
852
+ }, $e = new Uint8Array([2]), et = (e) => {
853
+ if (typeof e == "string") return Ve.encode(e);
854
+ if (e instanceof Uint8Array) return e;
855
+ if (ArrayBuffer.isView(e)) return new Uint8Array(e.buffer, e.byteOffset, e.byteLength);
856
+ if (Array.isArray(e)) {
857
+ let t = e.map(et), n = new Uint8Array(t.reduce((e, t) => e + t.byteLength, 0)), r = 0;
858
+ for (let e of t) n.set(e, r), r += e.byteLength;
859
+ return n;
860
+ }
861
+ return new Uint8Array(e);
862
+ }, L = (e) => {
784
863
  let t = e.split(".").map((e) => parseInt(e, 10));
785
864
  if (t.length !== 4 || t.some((e) => Number.isNaN(e) || e < 0 || e > 255)) throw Error(`Invalid IPv4 address: ${e}`);
786
865
  return new Uint8Array(t);
787
- }, Qe = (e) => {
788
- let t = new f(e).getBitsBase16(0, 128).match(/.{2}/g);
866
+ }, R = (e) => {
867
+ let t = new p(e).getBitsBase16(0, 128).match(/.{2}/g);
789
868
  if (!t || t.length !== 16) throw Error(`Invalid IPv6 address: ${e}`);
790
869
  return new Uint8Array(t.map((e) => parseInt(e, 16)));
791
- }, $e = (e, t) => {
792
- let n = new Ze(typeof e == "string" ? { type: e } : e);
870
+ }, tt = (e, t) => {
871
+ let n = new Qe(typeof e == "string" ? { type: e } : e);
793
872
  return t && n.on("message", t), n;
794
- }, et = /* @__PURE__ */ n({
873
+ }, nt = /* @__PURE__ */ n({
795
874
  Agent: () => Y,
796
875
  ClientRequest: () => q,
797
876
  HTTPParser: () => U,
798
877
  IncomingMessage: () => W,
799
- METHODS: () => nt,
878
+ METHODS: () => it,
800
879
  STATUS_CODES: () => z,
801
880
  Server: () => J,
802
881
  ServerResponse: () => K,
803
- _default: () => pt,
804
- createServer: () => ft,
805
- default: () => pt,
806
- get: () => dt,
807
- globalAgent: () => ut,
882
+ _default: () => ht,
883
+ createServer: () => mt,
884
+ default: () => ht,
885
+ get: () => pt,
886
+ globalAgent: () => ft,
808
887
  request: () => X
809
- }), tt = new TextDecoder("latin1"), nt = /* @__PURE__ */ "ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE".split("."), z = {
888
+ }), rt = new TextDecoder("latin1"), it = /* @__PURE__ */ "ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE".split("."), z = {
810
889
  100: "Continue",
811
890
  101: "Switching Protocols",
812
891
  102: "Processing",
@@ -870,7 +949,7 @@ var Ke = /* @__PURE__ */ n({
870
949
  509: "Bandwidth Limit Exceeded",
871
950
  510: "Not Extended",
872
951
  511: "Network Authentication Required"
873
- }, rt = new Set([
952
+ }, at = new Set([
874
953
  "content-type",
875
954
  "content-length",
876
955
  "user-agent",
@@ -889,15 +968,15 @@ var Ke = /* @__PURE__ */ n({
889
968
  "server",
890
969
  "age",
891
970
  "expires"
892
- ]), B = 13, V = 10, it = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/, H = (e, t) => (e.code = t, e), at = (e, t) => {
971
+ ]), B = 13, V = 10, ot = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/, H = (e, t) => (e.code = t, e), st = (e, t) => {
893
972
  if (e.length === 0) return t;
894
973
  if (t.length === 0) return e;
895
974
  let n = new Uint8Array(e.length + t.length);
896
975
  return n.set(e, 0), n.set(t, e.length), n;
897
- }, ot = (e, t) => {
976
+ }, ct = (e, t) => {
898
977
  for (let n = t; n + 1 < e.length; n++) if (e[n] === B && e[n + 1] === V) return n;
899
978
  return -1;
900
- }, st = (e) => {
979
+ }, lt = (e) => {
901
980
  for (let t = 0; t + 3 < e.length; t++) if (e[t] === B && e[t + 1] === V && e[t + 2] === B && e[t + 3] === V) return t;
902
981
  return -1;
903
982
  }, U = class {
@@ -911,10 +990,10 @@ var Ke = /* @__PURE__ */ n({
911
990
  this.mode = e, this.handlers = t;
912
991
  }
913
992
  execute(e) {
914
- this.buf = at(this.buf, e);
993
+ this.buf = st(this.buf, e);
915
994
  let t = !0;
916
995
  for (; t;) if (t = !1, this.state === "HEAD") {
917
- let e = st(this.buf);
996
+ let e = lt(this.buf);
918
997
  if (e === -1) return;
919
998
  let n = this.buf.subarray(0, e);
920
999
  this.buf = this.buf.subarray(e + 4);
@@ -929,7 +1008,7 @@ var Ke = /* @__PURE__ */ n({
929
1008
  this.state = "HEAD", this.framing = "none", this.bodyRemaining = 0, this.chunkState = "size", this.skipBody = !1;
930
1009
  }
931
1010
  parseHead(e) {
932
- let t = tt.decode(e).split("\r\n"), n = t.shift() ?? "", r = [];
1011
+ let t = rt.decode(e).split("\r\n"), n = t.shift() ?? "", r = [];
933
1012
  for (let e of t) (e.startsWith(" ") || e.startsWith(" ")) && r.length > 0 ? r[r.length - 1] += " " + e.trim() : r.push(e);
934
1013
  let i = [], a = {};
935
1014
  for (let e of r) {
@@ -967,7 +1046,7 @@ var Ke = /* @__PURE__ */ n({
967
1046
  return;
968
1047
  }
969
1048
  let i = e[r];
970
- i === void 0 ? e[r] = n : rt.has(r) || (e[r] = `${i}, ${n}`);
1049
+ i === void 0 ? e[r] = n : at.has(r) || (e[r] = `${i}, ${n}`);
971
1050
  }
972
1051
  setupBody(e) {
973
1052
  if (this.skipBody) {
@@ -1000,9 +1079,9 @@ var Ke = /* @__PURE__ */ n({
1000
1079
  }
1001
1080
  consumeChunked() {
1002
1081
  for (;;) if (this.chunkState === "size") {
1003
- let e = ot(this.buf, 0);
1082
+ let e = ct(this.buf, 0);
1004
1083
  if (e === -1) return !1;
1005
- let t = tt.decode(this.buf.subarray(0, e)), n = parseInt(t.split(";")[0].trim(), 16);
1084
+ let t = rt.decode(this.buf.subarray(0, e)), n = parseInt(t.split(";")[0].trim(), 16);
1006
1085
  if (this.buf = this.buf.subarray(e + 2), Number.isNaN(n)) return !0;
1007
1086
  n === 0 ? this.chunkState = "trailer" : (this.bodyRemaining = n, this.chunkState = "data");
1008
1087
  } else if (this.chunkState === "data") {
@@ -1013,13 +1092,13 @@ var Ke = /* @__PURE__ */ n({
1013
1092
  if (this.buf.length < 2) return !1;
1014
1093
  this.buf = this.buf.subarray(2), this.chunkState = "size";
1015
1094
  } else {
1016
- let e = ot(this.buf, 0);
1095
+ let e = ct(this.buf, 0);
1017
1096
  if (e === -1) return !1;
1018
1097
  let t = e === 0;
1019
1098
  if (this.buf = this.buf.subarray(e + 2), t) return !0;
1020
1099
  }
1021
1100
  }
1022
- }, ct = (e, t) => p.isBuffer(e) ? e : typeof e == "string" ? p.from(e, t ?? "utf8") : e instanceof Uint8Array ? p.from(e) : e instanceof ArrayBuffer ? p.from(new Uint8Array(e)) : p.from(String(e)), W = class extends u.Readable {
1101
+ }, ut = (e, t) => m.isBuffer(e) ? e : typeof e == "string" ? m.from(e, t ?? "utf8") : e instanceof Uint8Array ? m.from(e) : e instanceof ArrayBuffer ? m.from(new Uint8Array(e)) : m.from(String(e)), W = class extends d.Readable {
1023
1102
  httpVersion = "1.1";
1024
1103
  httpVersionMajor = 1;
1025
1104
  httpVersionMinor = 1;
@@ -1046,7 +1125,7 @@ var Ke = /* @__PURE__ */ n({
1046
1125
  setTimeout(e, t) {
1047
1126
  return this.socket.setTimeout(e, t), this;
1048
1127
  }
1049
- }, G = class extends u.Writable {
1128
+ }, G = class extends d.Writable {
1050
1129
  _headerStore = /* @__PURE__ */ new Map();
1051
1130
  headersSent = !1;
1052
1131
  chunkedEncoding = !1;
@@ -1054,7 +1133,7 @@ var Ke = /* @__PURE__ */ n({
1054
1133
  _bodyWritten = !1;
1055
1134
  setHeader(e, t) {
1056
1135
  if (this.headersSent) throw H(/* @__PURE__ */ Error("Cannot set headers after they are sent to the client"), "ERR_HTTP_HEADERS_SENT");
1057
- if (typeof e != "string" || !it.test(e)) throw H(/* @__PURE__ */ TypeError(`Header name must be a valid HTTP token [${JSON.stringify(String(e))}]`), "ERR_INVALID_HTTP_TOKEN");
1136
+ if (typeof e != "string" || !ot.test(e)) throw H(/* @__PURE__ */ TypeError(`Header name must be a valid HTTP token [${JSON.stringify(String(e))}]`), "ERR_INVALID_HTTP_TOKEN");
1058
1137
  if (t === void 0) throw H(/* @__PURE__ */ TypeError(`Invalid value "undefined" for header "${e}"`), "ERR_HTTP_INVALID_HEADER_VALUE");
1059
1138
  return this._headerStore.set(e.toLowerCase(), [e, Array.isArray(t) ? [...t] : t]), this;
1060
1139
  }
@@ -1095,25 +1174,25 @@ var Ke = /* @__PURE__ */ n({
1095
1174
  return this._bodyWritten = !0, super.write(e, t, n);
1096
1175
  }
1097
1176
  _write(e, t, n) {
1098
- let r = ct(e), i = [];
1099
- if (this.headersSent ||= (this._implicitHeader(), i.push(p.from(this._headBlock, "latin1")), !0), this.chunkedEncoding ? r.length > 0 && (i.push(p.from(`${r.length.toString(16)}\r\n`, "latin1")), i.push(r), i.push(p.from("\r\n", "latin1"))) : i.push(r), i.length === 0) {
1177
+ let r = ut(e), i = [];
1178
+ if (this.headersSent ||= (this._implicitHeader(), i.push(m.from(this._headBlock, "latin1")), !0), this.chunkedEncoding ? r.length > 0 && (i.push(m.from(`${r.length.toString(16)}\r\n`, "latin1")), i.push(r), i.push(m.from("\r\n", "latin1"))) : i.push(r), i.length === 0) {
1100
1179
  n();
1101
1180
  return;
1102
1181
  }
1103
- this._writeToSocket(p.concat(i), n);
1182
+ this._writeToSocket(m.concat(i), n);
1104
1183
  }
1105
1184
  _final(e) {
1106
1185
  let t = [];
1107
- if (this.headersSent ||= (!this.chunkedEncoding && !this.hasHeader("content-length") && this.setHeader("Content-Length", 0), this._implicitHeader(), t.push(p.from(this._headBlock, "latin1")), !0), this.chunkedEncoding && t.push(p.from("0\r\n\r\n", "latin1")), this.finished = !0, t.length === 0) {
1186
+ if (this.headersSent ||= (!this.chunkedEncoding && !this.hasHeader("content-length") && this.setHeader("Content-Length", 0), this._implicitHeader(), t.push(m.from(this._headBlock, "latin1")), !0), this.chunkedEncoding && t.push(m.from("0\r\n\r\n", "latin1")), this.finished = !0, t.length === 0) {
1108
1187
  e();
1109
1188
  return;
1110
1189
  }
1111
- this._writeToSocket(p.concat(t), e);
1190
+ this._writeToSocket(m.concat(t), e);
1112
1191
  }
1113
1192
  end(e, t, n) {
1114
1193
  if (e != null && typeof e != "function" && !this._bodyWritten && !this.headersSent && !this.chunkedEncoding && !this.hasHeader("content-length")) {
1115
1194
  let n = typeof t == "string" ? t : void 0;
1116
- this.setHeader("Content-Length", ct(e, n).length);
1195
+ this.setHeader("Content-Length", ut(e, n).length);
1117
1196
  }
1118
1197
  return super.end(e, t, n);
1119
1198
  }
@@ -1157,12 +1236,12 @@ var Ke = /* @__PURE__ */ n({
1157
1236
  this.sendDate && !this.hasHeader("date") && this.setHeader("Date", (/* @__PURE__ */ new Date()).toUTCString()), this.hasHeader("connection") || this.setHeader("Connection", this._keepAlive ? "keep-alive" : "close"), this._headBlock = this._storeHeader(`HTTP/1.1 ${this.statusCode} ${e}`);
1158
1237
  }
1159
1238
  writeContinue() {
1160
- this._writeToSocket(p.from("HTTP/1.1 100 Continue\r\n\r\n", "latin1"), () => {});
1239
+ this._writeToSocket(m.from("HTTP/1.1 100 Continue\r\n\r\n", "latin1"), () => {});
1161
1240
  }
1162
1241
  setTimeout(e, t) {
1163
1242
  return this.socket?.setTimeout(e, t), this;
1164
1243
  }
1165
- }, lt = (...e) => {
1244
+ }, dt = (...e) => {
1166
1245
  let t = {}, n = {}, r, i = [...e], a = i.shift();
1167
1246
  if (typeof a == "string" || a instanceof URL) {
1168
1247
  let e = typeof a == "string" ? new URL(a) : a;
@@ -1206,7 +1285,7 @@ var Ke = /* @__PURE__ */ n({
1206
1285
  let e = this.protocol === "https:" && r === 443 || this.protocol !== "https:" && r === 80;
1207
1286
  this.setHeader("Host", e ? n : `${n}:${r}`);
1208
1287
  }
1209
- e.auth && !this.hasHeader("authorization") && this.setHeader("Authorization", `Basic ${p.from(e.auth).toString("base64")}`), this.socket = new F(), this.emit("socket", this.socket), this.socket.on("error", (e) => {
1288
+ e.auth && !this.hasHeader("authorization") && this.setHeader("Authorization", `Basic ${m.from(e.auth).toString("base64")}`), this.socket = new F(), this.emit("socket", this.socket), this.socket.on("error", (e) => {
1210
1289
  this._aborted || this.emit("error", e);
1211
1290
  }), this._attachResponseParser(), this.socket.connect({
1212
1291
  host: n,
@@ -1227,7 +1306,7 @@ var Ke = /* @__PURE__ */ n({
1227
1306
  e._applyHead(n), this.method === "HEAD" && (t.skipBody = !0), this.res = e, this.emit("response", e);
1228
1307
  },
1229
1308
  onBody: (t) => {
1230
- e.push(p.from(t));
1309
+ e.push(m.from(t));
1231
1310
  },
1232
1311
  onComplete: () => {
1233
1312
  e.complete = !0, e.push(null);
@@ -1281,7 +1360,7 @@ var Ke = /* @__PURE__ */ n({
1281
1360
  }), this.emit("request", t, i);
1282
1361
  },
1283
1362
  onBody: (e) => {
1284
- t?.push(p.from(e));
1363
+ t?.push(m.from(e));
1285
1364
  },
1286
1365
  onComplete: () => {
1287
1366
  t && (t.complete = !0, t.push(null)), t = null;
@@ -1303,113 +1382,113 @@ var Ke = /* @__PURE__ */ n({
1303
1382
  return `${e.host ?? "localhost"}:${e.port ?? ""}:${e.localAddress ?? ""}`;
1304
1383
  }
1305
1384
  destroy() {}
1306
- }, ut = new Y(), X = (...e) => {
1307
- let { options: t, callback: n } = lt(...e);
1385
+ }, ft = new Y(), X = (...e) => {
1386
+ let { options: t, callback: n } = dt(...e);
1308
1387
  return new q(t, n);
1309
- }, dt = (...e) => {
1388
+ }, pt = (...e) => {
1310
1389
  let t = X(...e);
1311
1390
  return t.end(), t;
1312
- }, ft = (e, t) => new J(e, t), pt = {
1313
- METHODS: nt,
1391
+ }, mt = (e, t) => new J(e, t), ht = {
1392
+ METHODS: it,
1314
1393
  STATUS_CODES: z,
1315
1394
  Agent: Y,
1316
- globalAgent: ut,
1395
+ globalAgent: ft,
1317
1396
  Server: J,
1318
1397
  ServerResponse: K,
1319
1398
  IncomingMessage: W,
1320
1399
  ClientRequest: q,
1321
1400
  OutgoingMessage: G,
1322
- createServer: ft,
1401
+ createServer: mt,
1323
1402
  request: X,
1324
- get: dt
1325
- }, mt = /* @__PURE__ */ n({
1326
- available: () => ht,
1327
- dgram: () => Xe,
1403
+ get: pt
1404
+ }, gt = /* @__PURE__ */ n({
1405
+ available: () => _t,
1406
+ dgram: () => Ze,
1328
1407
  dns: () => ze,
1329
1408
  fetch: () => Le,
1330
- http: () => et,
1409
+ http: () => nt,
1331
1410
  net: () => Ke,
1332
1411
  quota: () => Re
1333
- }), ht = () => Pe, Z = async (e) => {
1412
+ }), _t = () => Pe, Z = async (e) => {
1334
1413
  if (typeof window > "u") return !1;
1335
- if (h()) return !0;
1414
+ if (g()) return !0;
1336
1415
  let t = await M, n = null, r = new Promise((e) => {
1337
1416
  n = () => {
1338
- h() && e(!0);
1339
- }, m.addEventListener("statuschange", n);
1417
+ g() && e(!0);
1418
+ }, h.addEventListener("statuschange", n);
1340
1419
  }), i = t.installPrompt.show(e).then(() => !1), a = await Promise.race([r, i]);
1341
- return n && m.removeEventListener("statuschange", n), await t.installPrompt.hide().catch(() => {}), a;
1420
+ return n && h.removeEventListener("statuschange", n), await t.installPrompt.hide().catch(() => {}), a;
1342
1421
  }, Q = null;
1343
- _(() => (Q ||= Z().then(() => void 0).finally(() => {
1422
+ v(() => (Q ||= Z().then(() => void 0).finally(() => {
1344
1423
  Q = null;
1345
1424
  }), Q));
1346
1425
  //#endregion
1347
1426
  //#region src/lib/desktop.ts
1348
- var gt = /* @__PURE__ */ n({
1349
- available: () => _t,
1350
- dgram: () => xt,
1351
- dns: () => yt,
1352
- fetch: () => vt,
1353
- fs: () => St,
1354
- net: () => bt
1355
- }), _t = () => !1, $ = (e) => (...t) => {
1427
+ var vt = /* @__PURE__ */ n({
1428
+ available: () => yt,
1429
+ dgram: () => Ct,
1430
+ dns: () => xt,
1431
+ fetch: () => bt,
1432
+ fs: () => wt,
1433
+ net: () => St
1434
+ }), yt = () => !1, $ = (e) => (...t) => {
1356
1435
  throw Error(`The FKN desktop app is not connected, desktop.${e} is unavailable`);
1357
- }, vt = $("fetch"), yt = { lookup: $("dns.lookup") }, bt = {
1436
+ }, bt = $("fetch"), xt = { lookup: $("dns.lookup") }, St = {
1358
1437
  connect: $("net.connect"),
1359
1438
  createConnection: $("net.createConnection"),
1360
1439
  createServer: $("net.createServer")
1361
- }, xt = { createSocket: $("dgram.createSocket") }, St = {
1440
+ }, Ct = { createSocket: $("dgram.createSocket") }, wt = {
1362
1441
  isLocalDirectorySupported: () => !1,
1363
1442
  pickLocalDirectory: $("fs.pickLocalDirectory"),
1364
1443
  queryDirectoryPermission: $("fs.queryDirectoryPermission"),
1365
1444
  ensureDirectoryPermission: $("fs.ensureDirectoryPermission")
1366
- }, Ct = () => typeof document < "u" && h(), wt = async (e, t) => {
1445
+ }, Tt = () => typeof document < "u" && g(), Et = async (e, t) => {
1367
1446
  if (Ie(e), t?.credentials === "include") {
1368
1447
  if (typeof document > "u") throw Error("fetch with credentials needs the FKN extension, which only exists in window realms");
1369
- return S(e, t);
1448
+ return C(e, t);
1370
1449
  }
1371
- return Ct() ? S(e, {
1450
+ return Tt() ? C(e, {
1372
1451
  ...t,
1373
1452
  credentials: "omit"
1374
- }) : _t() ? vt(e, t) : Le(e, t);
1375
- }, Tt = /* @__PURE__ */ n({
1376
- ATTACH_FRAME_EVENT_KEY: () => C,
1377
- assertAttachableFrameUrl: () => T,
1378
- assertFetchableUrl: () => x,
1379
- attachFrame: () => be,
1380
- attachFramePermission: () => ve,
1381
- available: () => Ct,
1453
+ }) : yt() ? bt(e, t) : Le(e, t);
1454
+ }, Dt = /* @__PURE__ */ n({
1455
+ ATTACH_FRAME_EVENT_KEY: () => w,
1456
+ assertAttachableFrameUrl: () => E,
1457
+ assertFetchableUrl: () => S,
1458
+ attachFrame: () => ye,
1459
+ attachFramePermission: () => _e,
1460
+ available: () => Tt,
1382
1461
  box: () => l,
1383
- cookies: () => me,
1462
+ cookies: () => pe,
1384
1463
  createVideoElementHandle: () => e,
1385
- events: () => m,
1386
- extension: () => m,
1387
- fetch: () => S,
1388
- fetchCredentialedPermission: () => le,
1389
- fetchPermission: () => ce,
1390
- gotoPermission: () => ye,
1464
+ events: () => h,
1465
+ extension: () => h,
1466
+ fetch: () => C,
1467
+ fetchCredentialedPermission: () => ce,
1468
+ fetchPermission: () => se,
1469
+ gotoPermission: () => ve,
1391
1470
  handleRevivableModules: () => i,
1392
- isBlockedFetchUrl: () => b,
1393
- isBlockedFrameUrl: () => w,
1394
- isExtensionExposed: () => h,
1471
+ isBlockedFetchUrl: () => x,
1472
+ isBlockedFrameUrl: () => T,
1473
+ isExtensionExposed: () => g,
1395
1474
  isType: () => t,
1396
- modifyRequestHeadersPermission: () => he,
1397
- permissions: () => xe,
1475
+ modifyRequestHeadersPermission: () => me,
1476
+ permissions: () => be,
1398
1477
  promptInstall: () => Z,
1399
- readCookiePermission: () => pe,
1400
- removeRequestHeaderRule: () => _e,
1478
+ readCookiePermission: () => fe,
1479
+ removeRequestHeaderRule: () => ge,
1401
1480
  revive: () => o,
1402
- setMissingExtensionHandler: () => _,
1403
- setRequestHeaderRule: () => ge,
1481
+ setMissingExtensionHandler: () => v,
1482
+ setRequestHeaderRule: () => he,
1404
1483
  type: () => a,
1405
- waitForExtensionExposure: () => v
1406
- }), Et = /* @__PURE__ */ n({
1407
- ensureDirectoryPermission: () => At,
1408
- isLocalDirectorySupported: () => Dt,
1409
- pickLocalDirectory: () => Ot,
1410
- queryDirectoryPermission: () => kt
1411
- }), Dt = () => typeof window < "u" && "showDirectoryPicker" in window, Ot = async (e = {}) => {
1412
- if (!Dt()) return;
1484
+ waitForExtensionExposure: () => y
1485
+ }), Ot = /* @__PURE__ */ n({
1486
+ ensureDirectoryPermission: () => Mt,
1487
+ isLocalDirectorySupported: () => kt,
1488
+ pickLocalDirectory: () => At,
1489
+ queryDirectoryPermission: () => jt
1490
+ }), kt = () => typeof window < "u" && "showDirectoryPicker" in window, At = async (e = {}) => {
1491
+ if (!kt()) return;
1413
1492
  let t = window.showDirectoryPicker;
1414
1493
  return t({
1415
1494
  mode: "readwrite",
@@ -1417,25 +1496,25 @@ var gt = /* @__PURE__ */ n({
1417
1496
  }).catch((e) => {
1418
1497
  if (e?.name !== "AbortError") throw e;
1419
1498
  });
1420
- }, kt = async (e, t = "readwrite") => {
1499
+ }, jt = async (e, t = "readwrite") => {
1421
1500
  let { queryPermission: n } = e;
1422
1501
  return await n?.call(e, { mode: t }) ?? "granted";
1423
- }, At = async (e, t = "readwrite") => {
1424
- if (await kt(e, t) === "granted") return !0;
1502
+ }, Mt = async (e, t = "readwrite") => {
1503
+ if (await jt(e, t) === "granted") return !0;
1425
1504
  let { requestPermission: n } = e;
1426
1505
  return await n?.call(e, { mode: t }) === "granted";
1427
- }, jt = "https://fkn.app", Mt = (e, t) => {
1506
+ }, Nt = "https://fkn.app", Pt = (e, t) => {
1428
1507
  if (typeof window > "u") throw Error("FKN @fkn/lib: relayWorker must be called from the main thread");
1429
1508
  if (!A?.contentWindow) throw Error("FKN @fkn/lib: relayWorker called before the FKN iframe was injected");
1430
- ne({
1509
+ te({
1431
1510
  receive: window,
1432
1511
  emit: A.contentWindow
1433
1512
  }, e, {
1434
1513
  key: "fkn-api",
1435
- originA: t?.originA ?? jt,
1514
+ originA: t?.originA ?? Nt,
1436
1515
  originB: t?.originB ?? "*",
1437
1516
  unregisterSignal: t?.unregisterSignal
1438
1517
  });
1439
1518
  };
1440
1519
  //#endregion
1441
- export { C as ATTACH_FRAME_EVENT_KEY, T as assertAttachableFrameUrl, x as assertFetchableUrl, be as attachFrame, ve as attachFramePermission, l as box, mt as cloud, me as cookies, e as createVideoElementHandle, gt as desktop, Xe as dgram, ze as dns, Tt as extension, wt as fetch, le as fetchCredentialedPermission, ce as fetchPermission, Et as fs, ye as gotoPermission, i as handleRevivableModules, et as http, b as isBlockedFetchUrl, w as isBlockedFrameUrl, h as isExtensionExposed, t as isType, he as modifyRequestHeadersPermission, Ke as net, xe as permissions, Z as promptInstall, pe as readCookiePermission, Mt as relayWorker, _e as removeRequestHeaderRule, o as revive, _ as setMissingExtensionHandler, ge as setRequestHeaderRule, a as type, v as waitForExtensionExposure };
1520
+ export { w as ATTACH_FRAME_EVENT_KEY, E as assertAttachableFrameUrl, S as assertFetchableUrl, ye as attachFrame, _e as attachFramePermission, l as box, gt as cloud, pe as cookies, e as createVideoElementHandle, vt as desktop, Ze as dgram, ze as dns, Dt as extension, Et as fetch, ce as fetchCredentialedPermission, se as fetchPermission, Ot as fs, ve as gotoPermission, i as handleRevivableModules, nt as http, x as isBlockedFetchUrl, T as isBlockedFrameUrl, g as isExtensionExposed, t as isType, me as modifyRequestHeadersPermission, Ke as net, be as permissions, Z as promptInstall, fe as readCookiePermission, Pt as relayWorker, ge as removeRequestHeaderRule, o as revive, v as setMissingExtensionHandler, he as setRequestHeaderRule, a as type, y as waitForExtensionExposure };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fkn/lib",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "main": "index.js",
5
5
  "types": "index.d.ts",
6
6
  "type": "module",