@fkn/lib 0.4.1 → 0.4.3

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 +47 -7
  3. package/index.js +341 -239
  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)}),p,m=new Proxy({},{get:(n,r)=>async(...n)=>{await f(),p??=(0,t.expose)({},{transport:window,revivableModules:e.l});let i=(await p)[r];return i(...n)}}),te={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={scope:`network.fetchLocal`,category:`network`,severity:3,unsafe:!0,title:`Access devices on your local network`,description:`Lets the app reach devices and services on your home or work network, which websites normally cannot touch.`},ie=e=>{let t=e.match(/^(\d+)\.(\d+)\.\d+\.\d+$/);if(!t)return!1;let[n,r]=[Number(t[1]),Number(t[2])];return n===10||n===127||n===0||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168},ae=e=>{let t;try{t=new URL(e)}catch{return!1}let n=t.hostname.replace(/^\[|\]$/g,``).toLowerCase().replace(/\.$/,``);return n===`localhost`||n.endsWith(`.localhost`)||n.endsWith(`.local`)||n.endsWith(`.internal`)||n.endsWith(`.home.arpa`)?!0:n.includes(`:`)?n===`::`||n===`::1`||n.startsWith(`fc`)||n.startsWith(`fd`)||/^fe[89ab]/.test(n)||n.startsWith(`::ffff:`):ie(n)},oe=[`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 oe.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`)},se=[`origin`,`referer`],ce=e=>{if(!e?.headers)return;let t=new Headers(e.headers),n=se.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 m.proxyFetch({url:n.url,method:n.method,headers:[...n.headers],body:r,credentials:t?.credentials===`include`?`include`:`omit`,redirect:n.redirect,unsafeHeaders:ce(t),reason:t?.reason,signal:t?.signal??void 0})},le={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.`},ue={get:e=>m.getCookie(e)},de={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.`},fe=e=>m.setRequestHeaderRule(e),pe=e=>m.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 v=`FKN_WEB_EXTENSION_ATTACH_FRAME_EVENT_KEY`,y=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`)},b=e=>{if(y(e))throw Error(`attachFrame: refusing to target the extension's own pages or fkn.app`)},me={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.`},he={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.`},ge=async({iframe:t,domains:n=[]})=>{let r=crypto.randomUUID();if(b(t.src),await f(),!t.isConnected)throw Error(`attachFrame: the iframe must be connected to the document before attaching`);t.dispatchEvent(new CustomEvent(v,{detail:r}));let{executeLocator:i,ensureLocatorPermission:a,goto:o}=await m.attachFrame({marker:r,domains:n}),s=e.r(i,a),c=(e,t={})=>(b(e),o({url:e,...t})),l=()=>t.src;return{...s,goto:c,url:l}},_e={request:e=>m.requestPermissions(e.map(e=>({key:e.key,scope:e.scope??``,reason:e.reason})))},ve=32,ye=typeof CSS<`u`&&CSS.supports(`clip-path`,`path('M0 0H1V1H0Z')`),be=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`)},xe=({x:e,y:t,width:n,height:r})=>`M${e} ${t}h${n}v${r}h${-n}Z`,Se=(e,{modal:t,rects:n})=>{if(!ye){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(xe).join(``)}')`,i=r===`none`||CSS.supports(`clip-path`,r)?r:`inset(100%)`;e.style.setProperty(`clip-path`,i,`important`)},Ce=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}},we=e=>{if(typeof e!=`object`||!e)return null;let t=e,n=(Array.isArray(t.rects)?t.rects.slice(0,ve):[]).map(Ce).filter(e=>e!==null&&e.width>0&&e.height>0);return{modal:t.modal===!0,rects:n}},x=null,Te=()=>x!==null,Ee=e=>{be(e),Se(e,{modal:!1,rects:[]}),x=e},De=e=>{if(!x)return;let t=we(e);t&&Se(x,t)},S=`https://fkn.app`,C=typeof globalThis<`u`&&globalThis.document?globalThis.document:void 0,Oe=C?.querySelector(`iframe[src="${S}/api"]`)??null,w=C?.createElement(`iframe`)??null;!Oe&&w&&C&&(w.src=`${S}/api`,C.body.appendChild(w));var T=Oe??w,E=T?.contentWindow??null;T&&C&&Ee(T);var D=(()=>{if(typeof window<`u`)return E?{receive:window,emit:E}:void 0;if(typeof self<`u`)return{receive:self,emit:self}})(),ke=D!==void 0,O=D?(0,t.expose)({},{key:`fkn-api`,transport:D}):new Promise(()=>{});O.then(e=>{Te()&&e.overlay.setHost(De)},()=>{});var Ae=[`fkn.app`,`fkn.dev`],k=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(Ae.some(e=>r===e||r.endsWith(`.${e}`)))throw Error(`fetch refuses FKN platform domains (${r})`)},A=(e,t)=>(k(e),O.then(n=>n.cloud.fetch(e,t))),je=async()=>{let e=await O.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}},Me=e.g({lookup:()=>Ne}),Ne=(e,t)=>O.then(n=>n.cloud.dns.lookup(e,t)),Pe=new TextEncoder;new TextDecoder;var j=e=>i.Address4.isValid(e),M=e=>i.Address6.isValid(e),Fe=e=>j(e)?4:M(e)?6:0,Ie=(...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}},Le=(...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}},Re=(...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 N=e.g({Server:()=>F,Socket:()=>P,_default:()=>He,connect:()=>ze,createConnection:()=>Be,createServer:()=>Ve,default:()=>He,isIP:()=>Fe,isIPv4:()=>j,isIPv6:()=>M}),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=Ie(...e),n=this.__webvpn_tcp_socket_init__(O.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=Ie(...e),n=e=>{let t=new P({connection:Promise.resolve(e)});this.emit(`connection`,t)},r=e=>O.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](){}},ze=(e,t)=>new P().connect(e,t),Be=(e,t)=>new P().connect(e,t),Ve=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new F(e);return t&&n.on(`connection`,t),n},He={Socket:P,Server:F,connect:ze,createConnection:Be,createServer:Ve,isIP:Fe,isIPv4:j,isIPv6:M},Ue=e.g({Socket:()=>We,createSocket:()=>qe}),We=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 Ge;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let a=i.Address4.isValid(e)?I(e):L(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=I(e),r=t&&i.Address4.isValid(t)?I(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=L(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=Le(...e),n=this._type===`udp6`?`::`:`0.0.0.0`;return this._webVPNUdpSocketPromise=O.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=I(e),r=t&&i.Address4.isValid(t)?I(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=L(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=Re(...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=Ke(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)})}},Ge=new Uint8Array([2]),Ke=e=>{if(typeof e==`string`)return Pe.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(Ke),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)},I=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)},L=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)))},qe=(e,t)=>{let n=new We(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},Je=e.g({Agent:()=>J,ClientRequest:()=>K,HTTPParser:()=>H,IncomingMessage:()=>U,METHODS:()=>Xe,STATUS_CODES:()=>R,Server:()=>q,ServerResponse:()=>G,_default:()=>st,createServer:()=>ot,default:()=>st,get:()=>at,globalAgent:()=>it,request:()=>Y}),Ye=new TextDecoder(`latin1`),Xe=`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`},Ze=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),$e=(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},et=(e,t)=>{for(let n=t;n+1<e.length;n++)if(e[n]===z&&e[n+1]===B)return n;return-1},tt=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=$e(this.buf,e);let t=!0;for(;t;)if(t=!1,this.state===`HEAD`){let e=tt(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=Ye.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:Ze.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=et(this.buf,0);if(e===-1)return!1;let t=Ye.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=et(this.buf,0);if(e===-1)return!1;let t=e===0;if(this.buf=this.buf.subarray(e+2),t)return!0}}},nt=(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
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=nt(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`,nt(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
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}},rt=(...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(){}},it=new J,Y=(...e)=>{let{options:t,callback:n}=rt(...e);return new K(t,n)},at=(...e)=>{let t=Y(...e);return t.end(),t},ot=(e,t)=>new q(e,t),st={METHODS:Xe,STATUS_CODES:R,Agent:J,globalAgent:it,Server:q,ServerResponse:G,IncomingMessage:U,ClientRequest:K,OutgoingMessage:W,createServer:ot,request:Y,get:at},ct=e.g({available:()=>lt,dgram:()=>Ue,dns:()=>Me,fetch:()=>A,http:()=>Je,net:()=>N,quota:()=>je}),lt=()=>ke,X=async e=>{if(typeof window>`u`)return!1;if(l())return!0;let t=await O,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 ut=e.g({available:()=>dt,dgram:()=>ht,dns:()=>pt,fetch:()=>ft,fs:()=>gt,net:()=>mt}),dt=()=>!1,Q=e=>(...t)=>{throw Error(`The FKN desktop app is not connected, desktop.${e} is unavailable`)},ft=Q(`fetch`),pt={lookup:Q(`dns.lookup`)},mt={connect:Q(`net.connect`),createConnection:Q(`net.createConnection`),createServer:Q(`net.createServer`)},ht={createSocket:Q(`dgram.createSocket`)},gt={isLocalDirectorySupported:()=>!1,pickLocalDirectory:Q(`fs.pickLocalDirectory`),queryDirectoryPermission:Q(`fs.queryDirectoryPermission`),ensureDirectoryPermission:Q(`fs.ensureDirectoryPermission`)},_t=()=>typeof document<`u`&&l(),vt=async(e,t)=>{if(k(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 _t()?_(e,{...t,credentials:`omit`}):dt()?ft(e,t):A(e,t)},yt=e.g({ATTACH_FRAME_EVENT_KEY:()=>v,assertAttachableFrameUrl:()=>b,assertFetchableUrl:()=>g,attachFrame:()=>ge,attachFramePermission:()=>me,available:()=>_t,box:()=>e.u,cookies:()=>ue,createVideoElementHandle:()=>e.d,events:()=>c,extension:()=>c,fetch:()=>_,fetchCredentialedPermission:()=>ne,fetchLocalPermission:()=>re,fetchPermission:()=>te,gotoPermission:()=>he,handleRevivableModules:()=>e.l,isBlockedFetchUrl:()=>h,isBlockedFrameUrl:()=>y,isExtensionExposed:()=>l,isLocalNetworkUrl:()=>ae,isType:()=>e.f,modifyRequestHeadersPermission:()=>de,permissions:()=>_e,promptInstall:()=>X,readCookiePermission:()=>le,removeRequestHeaderRule:()=>pe,revive:()=>e.p,setMissingExtensionHandler:()=>d,setRequestHeaderRule:()=>fe,type:()=>e.m,waitForExtensionExposure:()=>f}),bt=e.g({ensureDirectoryPermission:()=>Ct,isLocalDirectorySupported:()=>xt,pickLocalDirectory:()=>St,queryDirectoryPermission:()=>$}),xt=()=>typeof window<`u`&&`showDirectoryPicker`in window,St=async(e={})=>{if(!xt())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`},Ct=async(e,t=`readwrite`)=>{if(await $(e,t)===`granted`)return!0;let{requestPermission:n}=e;return await n?.call(e,{mode:t})===`granted`},wt=`https://fkn.app`,Tt=(e,n)=>{if(typeof window>`u`)throw Error(`FKN @fkn/lib: relayWorker must be called from the main thread`);if(!T?.contentWindow)throw Error(`FKN @fkn/lib: relayWorker called before the FKN iframe was injected`);(0,t.relay)({receive:window,emit:T.contentWindow},e,{key:`fkn-api`,originA:n?.originA??wt,originB:n?.originB??`*`,unregisterSignal:n?.unregisterSignal})},Et=async()=>typeof window>`u`?!1:(await O).connect.prompt(location.origin).catch(()=>!1);exports.ATTACH_FRAME_EVENT_KEY=v,exports.assertAttachableFrameUrl=b,exports.assertFetchableUrl=g,exports.attachFrame=ge,exports.attachFramePermission=me,exports.box=e.u,Object.defineProperty(exports,`cloud`,{enumerable:!0,get:function(){return ct}}),exports.connect=Et,exports.cookies=ue,exports.createVideoElementHandle=e.d,Object.defineProperty(exports,`desktop`,{enumerable:!0,get:function(){return ut}}),Object.defineProperty(exports,`dgram`,{enumerable:!0,get:function(){return Ue}}),Object.defineProperty(exports,`dns`,{enumerable:!0,get:function(){return Me}}),Object.defineProperty(exports,`extension`,{enumerable:!0,get:function(){return yt}}),exports.fetch=vt,exports.fetchCredentialedPermission=ne,exports.fetchLocalPermission=re,exports.fetchPermission=te,Object.defineProperty(exports,`fs`,{enumerable:!0,get:function(){return bt}}),exports.gotoPermission=he,exports.handleRevivableModules=e.l,Object.defineProperty(exports,`http`,{enumerable:!0,get:function(){return Je}}),exports.isBlockedFetchUrl=h,exports.isBlockedFrameUrl=y,exports.isExtensionExposed=l,exports.isLocalNetworkUrl=ae,exports.isType=e.f,exports.modifyRequestHeadersPermission=de,Object.defineProperty(exports,`net`,{enumerable:!0,get:function(){return N}}),exports.permissions=_e,exports.promptInstall=X,exports.readCookiePermission=le,exports.relayWorker=Tt,exports.removeRequestHeaderRule=pe,exports.revive=e.p,exports.setMissingExtensionHandler=d,exports.setRequestHeaderRule=fe,exports.type=e.m,exports.waitForExtensionExposure=f;
package/index.d.ts CHANGED
@@ -49,6 +49,15 @@ declare const fetchCredentialedPermission: {
49
49
  readonly title: "Fetch from other sites, signed in as you";
50
50
  readonly description: "Lets the app fetch other sites using your logged-in session cookies, so it can read data only you should see.";
51
51
  };
52
+ declare const fetchLocalPermission: {
53
+ readonly scope: "network.fetchLocal";
54
+ readonly category: "network";
55
+ readonly severity: 3;
56
+ readonly unsafe: true;
57
+ readonly title: "Access devices on your local network";
58
+ readonly description: "Lets the app reach devices and services on your home or work network, which websites normally cannot touch.";
59
+ };
60
+ declare const isLocalNetworkUrl: (raw: string) => boolean;
52
61
  type ProxyFetchRequest = {
53
62
  url: string;
54
63
  method: string;
@@ -672,6 +681,13 @@ declare const PERMISSIONS: readonly [{
672
681
  readonly unsafe: true;
673
682
  readonly title: "Fetch from other sites, signed in as you";
674
683
  readonly description: "Lets the app fetch other sites using your logged-in session cookies, so it can read data only you should see.";
684
+ }, {
685
+ readonly scope: "network.fetchLocal";
686
+ readonly category: "network";
687
+ readonly severity: 3;
688
+ readonly unsafe: true;
689
+ readonly title: "Access devices on your local network";
690
+ readonly description: "Lets the app reach devices and services on your home or work network, which websites normally cannot touch.";
675
691
  }, {
676
692
  readonly scope: "network.readCookie";
677
693
  readonly category: "network";
@@ -1044,12 +1060,15 @@ declare const makeWebVPNWebTransport: () => Promise<{
1044
1060
  readonly dataLength: number;
1045
1061
  readonly data: ArrayBuffer;
1046
1062
  }>;
1063
+ claimUdpRawStream: (socketId: number, sink: (packetBytes: Uint8Array) => void) => void;
1064
+ releaseUdpRawStream: (socketId: number) => void;
1047
1065
  getPacketForId: (packetId: number) => Promise<ServerMetadataPacket>;
1048
1066
  getMetadataReadableStreamForSocketId: (socketId: number) => ReadableStream<ServerMetadataPacket>;
1049
1067
  getMetadataReadableStreamForLocalAddress: (address: Address4 | Address6) => ReadableStream<ServerMetadataPacket>;
1050
1068
  getMetadataReadableStreamForLocalPort: (port: number) => ReadableStream<ServerMetadataPacket>;
1051
1069
  getMetadataWritableStream: () => WritableStream<Uint8Array<ArrayBufferLike>>;
1052
1070
  getDatagramWritableStream: () => WritableStream<Uint8Array<ArrayBufferLike>>;
1071
+ presentRateToken: () => Promise<void>;
1053
1072
  }>;
1054
1073
  type WebVPNWebTransport = Awaited<ReturnType<typeof makeWebVPNWebTransport>>;
1055
1074
 
@@ -1133,11 +1152,14 @@ declare const resolvers: {
1133
1152
  localPort: number;
1134
1153
  close: () => Promise<void>;
1135
1154
  }>;
1136
- readonly udpSocket: ({ type, port, address }: {
1155
+ readonly udpSocket: ({ type, port, address, dataPort }: {
1137
1156
  type: "udp4" | "udp6";
1138
1157
  port: number;
1139
1158
  address: string;
1159
+ dataPort?: boolean;
1140
1160
  }) => Promise<{
1161
+ socketId: number;
1162
+ dataPort: MessagePort | undefined;
1141
1163
  localAddress: string;
1142
1164
  localFamily: "IPv4" | "IPv6";
1143
1165
  localPort: number;
@@ -1177,6 +1199,9 @@ declare const resolvers: {
1177
1199
  readonly show: (reason?: string) => Promise<void>;
1178
1200
  readonly hide: () => void;
1179
1201
  };
1202
+ readonly connect: {
1203
+ readonly prompt: (consumerOrigin: string) => Promise<boolean>;
1204
+ };
1180
1205
  readonly proxyFetch: (input: string | Request | URL, init?: (RequestInit | undefined) & {
1181
1206
  render?: boolean;
1182
1207
  }) => Promise<Response>;
@@ -1208,11 +1233,14 @@ declare const resolvers: {
1208
1233
  localPort: number;
1209
1234
  close: () => Promise<void>;
1210
1235
  }>;
1211
- readonly webVpnUdpSocket: ({ type, port, address }: {
1236
+ readonly webVpnUdpSocket: ({ type, port, address, dataPort }: {
1212
1237
  type: "udp4" | "udp6";
1213
1238
  port: number;
1214
1239
  address: string;
1240
+ dataPort?: boolean;
1215
1241
  }) => Promise<{
1242
+ socketId: number;
1243
+ dataPort: MessagePort | undefined;
1216
1244
  localAddress: string;
1217
1245
  localFamily: "IPv4" | "IPv6";
1218
1246
  localPort: number;
@@ -1421,7 +1449,7 @@ declare class Server$1 extends EventEmitter implements Server$2 {
1421
1449
  listening: boolean;
1422
1450
  [Symbol.asyncDispose](): Promise<void>;
1423
1451
  }
1424
- declare const connect: (options: SocketConnectOpts, connectionListener?: () => void) => Socket$1;
1452
+ declare const connect$1: (options: SocketConnectOpts, connectionListener?: () => void) => Socket$1;
1425
1453
  declare const createConnection: (options: SocketConnectOpts, connectionListener?: () => void) => Socket$1;
1426
1454
  declare const createServer$1: (options?: ServerOpts | ((socket: Socket$1) => void), connectionListener?: (socket: Socket$1) => void) => Server$1;
1427
1455
 
@@ -1436,7 +1464,6 @@ declare const _default$1: {
1436
1464
  isIPv6: (input: string) => boolean;
1437
1465
  };
1438
1466
 
1439
- declare const net$1_connect: typeof connect;
1440
1467
  declare const net$1_createConnection: typeof createConnection;
1441
1468
  declare const net$1_isIP: typeof isIP;
1442
1469
  declare const net$1_isIPv4: typeof isIPv4;
@@ -1446,7 +1473,7 @@ declare namespace net$1 {
1446
1473
  Server$1 as Server,
1447
1474
  Socket$1 as Socket,
1448
1475
  _default$1 as _default,
1449
- net$1_connect as connect,
1476
+ connect$1 as connect,
1450
1477
  net$1_createConnection as createConnection,
1451
1478
  createServer$1 as createServer,
1452
1479
  _default$1 as default,
@@ -1476,6 +1503,12 @@ declare class Socket extends EventEmitter implements Socket$3 {
1476
1503
  port: number;
1477
1504
  };
1478
1505
  _webVPNUdpSocketPromise?: Promise<Awaited<ReturnType<WebVpnUdpSocket>> | undefined>;
1506
+ _dataPort?: MessagePort;
1507
+ _socketId?: number;
1508
+ _sendQueue: Uint8Array[];
1509
+ _sendQueueBytes: number;
1510
+ _sendFlushScheduled: boolean;
1511
+ _peerTailCache: Map<string, Uint8Array<ArrayBufferLike>>;
1479
1512
  constructor(options: SocketOptions & EventEmitterOptions & {
1480
1513
  connection?: ReturnType<WebVpnUdpSocket>;
1481
1514
  });
@@ -1485,6 +1518,9 @@ declare class Socket extends EventEmitter implements Socket$3 {
1485
1518
  _lastMulticastTtl: number;
1486
1519
  _lastMulticastLoopback: boolean;
1487
1520
  _setUdpOption(option: UdpSocketOption): void;
1521
+ _onDataPortBatch(buffer: ArrayBuffer): void;
1522
+ _peerTail(address: string | undefined, port: number | undefined): Uint8Array;
1523
+ _portSend(message: Uint8Array, address: string | undefined, port: number | undefined): void;
1488
1524
  addMembership(multicastAddress: string, multicastInterface?: string | undefined): void;
1489
1525
  address(): AddressInfo;
1490
1526
  bind(port?: number | undefined, address?: string | undefined, callback?: (() => void) | undefined): this;
@@ -1777,12 +1813,14 @@ declare const extension_box: typeof box;
1777
1813
  declare const extension_cookies: typeof cookies;
1778
1814
  declare const extension_createVideoElementHandle: typeof createVideoElementHandle;
1779
1815
  declare const extension_fetchCredentialedPermission: typeof fetchCredentialedPermission;
1816
+ declare const extension_fetchLocalPermission: typeof fetchLocalPermission;
1780
1817
  declare const extension_fetchPermission: typeof fetchPermission;
1781
1818
  declare const extension_gotoPermission: typeof gotoPermission;
1782
1819
  declare const extension_handleRevivableModules: typeof handleRevivableModules;
1783
1820
  declare const extension_isBlockedFetchUrl: typeof isBlockedFetchUrl;
1784
1821
  declare const extension_isBlockedFrameUrl: typeof isBlockedFrameUrl;
1785
1822
  declare const extension_isExtensionExposed: typeof isExtensionExposed;
1823
+ declare const extension_isLocalNetworkUrl: typeof isLocalNetworkUrl;
1786
1824
  declare const extension_isType: typeof isType;
1787
1825
  declare const extension_modifyRequestHeadersPermission: typeof modifyRequestHeadersPermission;
1788
1826
  declare const extension_permissions: typeof permissions;
@@ -1795,7 +1833,7 @@ declare const extension_setRequestHeaderRule: typeof setRequestHeaderRule;
1795
1833
  declare const extension_type: typeof type;
1796
1834
  declare const extension_waitForExtensionExposure: typeof waitForExtensionExposure;
1797
1835
  declare namespace extension {
1798
- export { extension_ATTACH_FRAME_EVENT_KEY as ATTACH_FRAME_EVENT_KEY, extension_assertAttachableFrameUrl as assertAttachableFrameUrl, extension_assertFetchableUrl as assertFetchableUrl, extension_attachFrame as attachFrame, extension_attachFramePermission as attachFramePermission, isExtensionAvailable as available, extension_box as box, extension_cookies as cookies, extension_createVideoElementHandle as createVideoElementHandle, extension$1 as events, extension$1 as extension, fetch$2 as fetch, extension_fetchCredentialedPermission as fetchCredentialedPermission, extension_fetchPermission as fetchPermission, extension_gotoPermission as gotoPermission, extension_handleRevivableModules as handleRevivableModules, extension_isBlockedFetchUrl as isBlockedFetchUrl, extension_isBlockedFrameUrl as isBlockedFrameUrl, extension_isExtensionExposed as isExtensionExposed, extension_isType as isType, extension_modifyRequestHeadersPermission as modifyRequestHeadersPermission, extension_permissions as permissions, extension_promptInstall as promptInstall, extension_readCookiePermission as readCookiePermission, extension_removeRequestHeaderRule as removeRequestHeaderRule, extension_revive as revive, extension_setMissingExtensionHandler as setMissingExtensionHandler, extension_setRequestHeaderRule as setRequestHeaderRule, extension_type as type, extension_waitForExtensionExposure as waitForExtensionExposure };
1836
+ export { extension_ATTACH_FRAME_EVENT_KEY as ATTACH_FRAME_EVENT_KEY, extension_assertAttachableFrameUrl as assertAttachableFrameUrl, extension_assertFetchableUrl as assertFetchableUrl, extension_attachFrame as attachFrame, extension_attachFramePermission as attachFramePermission, isExtensionAvailable as available, extension_box as box, extension_cookies as cookies, extension_createVideoElementHandle as createVideoElementHandle, extension$1 as events, extension$1 as extension, fetch$2 as fetch, extension_fetchCredentialedPermission as fetchCredentialedPermission, extension_fetchLocalPermission as fetchLocalPermission, extension_fetchPermission as fetchPermission, extension_gotoPermission as gotoPermission, extension_handleRevivableModules as handleRevivableModules, extension_isBlockedFetchUrl as isBlockedFetchUrl, extension_isBlockedFrameUrl as isBlockedFrameUrl, extension_isExtensionExposed as isExtensionExposed, extension_isLocalNetworkUrl as isLocalNetworkUrl, extension_isType as isType, extension_modifyRequestHeadersPermission as modifyRequestHeadersPermission, extension_permissions as permissions, extension_promptInstall as promptInstall, extension_readCookiePermission as readCookiePermission, extension_removeRequestHeaderRule as removeRequestHeaderRule, extension_revive as revive, extension_setMissingExtensionHandler as setMissingExtensionHandler, extension_setRequestHeaderRule as setRequestHeaderRule, extension_type as type, extension_waitForExtensionExposure as waitForExtensionExposure };
1799
1837
  export type { extension_AttachFrameOptions as AttachFrameOptions, extension_BoxedVideoElement as BoxedVideoElement, extension_CookieDetails as CookieDetails, extension_FetchInit as FetchInit, extension_Frame as Frame, extension_GotoOptions as GotoOptions, extension_HeaderOperation as HeaderOperation, extension_PermissionGrant as PermissionGrant, extension_PermissionRequest as PermissionRequest, extension_ProxyFetchRequest as ProxyFetchRequest, extension_RemoteVideoElement as RemoteVideoElement, extension_RequestHeaderRule as RequestHeaderRule, extension_SiteCookie as SiteCookie, extension_VideoElementState as VideoElementState };
1800
1838
  }
1801
1839
 
@@ -1863,5 +1901,7 @@ declare const relayWorker: (worker: Worker, options?: {
1863
1901
  originB?: string;
1864
1902
  }) => void;
1865
1903
 
1866
- export { ATTACH_FRAME_EVENT_KEY, assertAttachableFrameUrl, assertFetchableUrl, attachFrame, attachFramePermission, box, cloud, cookies, createVideoElementHandle, desktop, dgram$1 as dgram, dns$1 as dns, extension, fetch$1 as fetch, fetchCredentialedPermission, fetchPermission, fs, gotoPermission, handleRevivableModules, http, isBlockedFetchUrl, isBlockedFrameUrl, isExtensionExposed, isType, modifyRequestHeadersPermission, net$1 as net, permissions, promptInstall, readCookiePermission, relayWorker, removeRequestHeaderRule, revive, setMissingExtensionHandler, setRequestHeaderRule, type, waitForExtensionExposure };
1904
+ declare const connect: () => Promise<boolean>;
1905
+
1906
+ export { ATTACH_FRAME_EVENT_KEY, assertAttachableFrameUrl, assertFetchableUrl, attachFrame, attachFramePermission, box, cloud, connect, cookies, createVideoElementHandle, desktop, dgram$1 as dgram, dns$1 as dns, extension, fetch$1 as fetch, fetchCredentialedPermission, fetchLocalPermission, fetchPermission, fs, gotoPermission, handleRevivableModules, http, isBlockedFetchUrl, isBlockedFrameUrl, isExtensionExposed, isLocalNetworkUrl, isType, modifyRequestHeadersPermission, net$1 as net, permissions, promptInstall, readCookiePermission, relayWorker, removeRequestHeaderRule, revive, setMissingExtensionHandler, setRequestHeaderRule, type, waitForExtensionExposure };
1867
1907
  export type { AttachFrameOptions, BoxedVideoElement, CookieDetails, FetchInit, Frame, GotoOptions, HeaderOperation, PermissionGrant, PermissionRequest, ProxyFetchRequest, RemoteVideoElement, RequestHeaderRule, SiteCookie, VideoElementState };