@fkn/lib 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +5 -5
- package/index.d.ts +24 -7
- package/index.js +311 -232
- 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`)},C={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.`},le={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.`},ue=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}},de={request:e=>p.requestPermissions(e.map(e=>({key:e.key,scope:e.scope??``,reason:e.reason})))},fe=32,pe=typeof CSS<`u`&&CSS.supports(`clip-path`,`path('M0 0H1V1H0Z')`),me=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`)},he=({x:e,y:t,width:n,height:r})=>`M${e} ${t}h${n}v${r}h${-n}Z`,ge=(e,{modal:t,rects:n})=>{if(!pe){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(he).join(``)}')`,i=r===`none`||CSS.supports(`clip-path`,r)?r:`inset(100%)`;e.style.setProperty(`clip-path`,i,`important`)},_e=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}},ve=e=>{if(typeof e!=`object`||!e)return null;let t=e,n=(Array.isArray(t.rects)?t.rects.slice(0,fe):[]).map(_e).filter(e=>e!==null&&e.width>0&&e.height>0);return{modal:t.modal===!0,rects:n}},w=null,ye=()=>w!==null,be=e=>{me(e),ge(e,{modal:!1,rects:[]}),w=e},xe=e=>{if(!w)return;let t=ve(e);t&&ge(w,t)},Se=`https://fkn.app`,T=typeof globalThis<`u`&&globalThis.document?globalThis.document:void 0,Ce=T?.querySelector(`iframe[src="${Se}/api"]`)??null,E=T?.createElement(`iframe`)??null;!Ce&&E&&T&&(E.src=`${Se}/api`,T.body.appendChild(E));var D=Ce??E,O=D?.contentWindow??null;D&&T&&be(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=>{ye()&&e.overlay.setHost(xe)},()=>{});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})`)},M=(e,t)=>(j(e),A.then(n=>n.cloud.fetch(e,t))),Ee=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}},De=e.g({lookup:()=>Oe}),Oe=(e,t)=>A.then(n=>n.cloud.dns.lookup(e,t)),ke=new TextEncoder;new TextDecoder;var N=e=>i.Address4.isValid(e),P=e=>i.Address6.isValid(e),Ae=e=>N(e)?4:P(e)?6:0,je=(...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}},Me=(...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}},Ne=(...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 Pe=e.g({Server:()=>I,Socket:()=>F,_default:()=>Le,connect:()=>Fe,createConnection:()=>Ie,createServer:()=>L,default:()=>Le,isIP:()=>Ae,isIPv4:()=>N,isIPv6:()=>P}),F=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=je(...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},I=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=je(...e),n=e=>{let t=new F({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](){}},Fe=(e,t)=>new F().connect(e,t),Ie=(e,t)=>new F().connect(e,t),L=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new I(e);return t&&n.on(`connection`,t),n},Le={Socket:F,Server:I,connect:Fe,createConnection:Ie,createServer:L,isIP:Ae,isIPv4:N,isIPv6:P},Re=e.g({Socket:()=>ze,createSocket:()=>Ve}),ze=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=R(e),r=t&&i.Address4.isValid(t)?R(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=Be(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=Me(...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=R(e),r=t&&i.Address4.isValid(t)?R(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=Be(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=Ne(...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`?ke.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)})}},R=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)},Be=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)))},Ve=(e,t)=>{let n=new ze(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},He=e.g({Agent:()=>Y,ClientRequest:()=>q,HTTPParser:()=>U,IncomingMessage:()=>W,METHODS:()=>We,STATUS_CODES:()=>z,Server:()=>J,ServerResponse:()=>K,_default:()=>tt,createServer:()=>et,default:()=>tt,get:()=>$e,globalAgent:()=>Qe,request:()=>X}),Ue=new TextDecoder(`latin1`),We=`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE`.split(`.`),z={100:`Continue`,101:`Switching Protocols`,102:`Processing`,103:`Early Hints`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad Request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a Teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too Many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,500:`Internal Server Error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,509:`Bandwidth Limit Exceeded`,510:`Not Extended`,511:`Network Authentication Required`},Ge=new Set([`content-type`,`content-length`,`user-agent`,`referer`,`host`,`authorization`,`proxy-authorization`,`if-modified-since`,`if-unmodified-since`,`from`,`location`,`max-forwards`,`retry-after`,`etag`,`last-modified`,`server`,`age`,`expires`]),B=13,V=10,Ke=/^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/,H=(e,t)=>(e.code=t,e),qe=(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},Je=(e,t)=>{for(let n=t;n+1<e.length;n++)if(e[n]===B&&e[n+1]===V)return n;return-1},Ye=e=>{for(let t=0;t+3<e.length;t++)if(e[t]===B&&e[t+1]===V&&e[t+2]===B&&e[t+3]===V)return t;return-1},U=class{buf=new Uint8Array;state=`HEAD`;framing=`none`;bodyRemaining=0;chunkState=`size`;skipBody=!1;constructor(e,t){this.mode=e,this.handlers=t}execute(e){this.buf=qe(this.buf,e);let t=!0;for(;t;)if(t=!1,this.state===`HEAD`){let e=Ye(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=Ue.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:
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./locator-jHaMLjtv.cjs`);let t=require(`osra`),n=require(`stream`),r=require(`events`),i=require(`ip-address`),a=require(`buffer`);var o=`FKN_WEB_EXTENSION_MAIN_WORLD_CONTENT_SCRIPT_ENABLED_EVENT_KEY`,s=`fknExtension`,c=(0,t.createTypedEventTarget)();typeof document<`u`&&document.addEventListener(o,e=>{c.dispatchEvent(new CustomEvent(`statuschange`,{detail:{enabled:e.detail.enabled}}))});var l=()=>typeof document>`u`?!1:document.documentElement.dataset[s]===`true`,u=null,d=e=>{u=e},ee=150,f=(e=1e3)=>new Promise((t,n)=>{if(l())return t();let r,i=e=>{clearTimeout(r),s.disconnect(),document.removeEventListener(`readystatechange`,c),e()},a=()=>i(async()=>{if(u&&(await u().catch(()=>{}),l()))return t();n(Error(`The FKN WebExtension is not installed, enabled or not exposed on this page.`))}),o=()=>{clearTimeout(r),r=setTimeout(()=>l()?i(t):a(),ee)},s=new MutationObserver(()=>{l()&&i(t)}),c=()=>{document.readyState===`complete`&&!l()&&o()};if(r=setTimeout(a,e),s.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-fkn-extension`]}),document.addEventListener(`readystatechange`,c),document.readyState===`complete`)return o();l()&&i(t)}),te,p=new Proxy({},{get:(n,r)=>async(...n)=>{await f(),te??=(0,t.expose)({},{transport:window,revivableModules:e.l});let i=(await te)[r];return i(...n)}}),m={scope:`network.fetch`,category:`network`,severity:0,title:`Fetch data from other sites`,description:`Lets the app download public data from other websites directly, past the usual cross-origin limits.`},ne={scope:`network.fetchCredentialed`,category:`network`,severity:3,unsafe:!0,title:`Fetch from other sites, signed in as you`,description:`Lets the app fetch other sites using your logged-in session cookies, so it can read data only you should see.`},re=[`fkn.app`,`fkn.dev`],h=e=>{let t;try{t=new URL(e)}catch{return!1}if(t.protocol===`chrome-extension:`||t.protocol===`moz-extension:`)return!0;let n=t.hostname;return re.some(e=>n===e||n.endsWith(`.${e}`))},g=e=>{if(h(e))throw Error(`fetch: refusing to target the extension's own pages or FKN platform domains`)},ie=[`origin`,`referer`],ae=e=>{if(!e?.headers)return;let t=new Headers(e.headers),n=ie.map(e=>{let n=t.get(e);return n===null?void 0:[e,n]}).filter(e=>e!==void 0);return n.length?n:void 0},_=async(e,t)=>{let n=new Request(e,t);g(n.url);let r=n.body?await n.arrayBuffer():null;return p.proxyFetch({url:n.url,method:n.method,headers:[...n.headers],body:r,credentials:t?.credentials===`include`?`include`:`omit`,redirect:n.redirect,unsafeHeaders:ae(t),reason:t?.reason,signal:t?.signal??void 0})},v={scope:`network.readCookie`,category:`network`,severity:3,unsafe:!0,title:`Read a site’s cookie`,description:`Lets the app read a named cookie from another site, which can include the login token only that site should see.`},y={get:e=>p.getCookie(e)},oe={scope:`network.modifyRequestHeaders`,category:`network`,severity:2,unsafe:!0,title:`Rewrite request headers to other sites`,description:`Lets the app set or remove headers (like Origin and Referer) on this page’s own requests to the listed sites.`},se=e=>p.setRequestHeaderRule(e),ce=e=>p.removeRequestHeaderRule({ruleId:e});(()=>{let t={},n=[...e.t.selectorModules,...e.i.selectorModules];for(let e of n)e.render&&!(e.type in t)&&(t[e.type]=e.render);return t})();var b=`FKN_WEB_EXTENSION_ATTACH_FRAME_EVENT_KEY`,x=e=>{if(!e||e===`about:blank`)return!1;let t;try{t=new URL(e,location.href)}catch{return!1}if(t.protocol===`chrome-extension:`||t.protocol===`moz-extension:`)return!0;if(t.protocol===`about:`)return!1;let n=t.hostname;return n===`fkn.app`||n.endsWith(`.fkn.app`)},S=e=>{if(x(e))throw Error(`attachFrame: refusing to target the extension's own pages or fkn.app`)},le={scope:`embed.iframe`,category:`embed`,severity:0,title:`Load another website inside this app`,description:`Lets the app embed external pages directly inside its own view.`},ue={scope:`embed.open`,category:`embed`,severity:0,title:`Open a website inside this app`,description:`Lets the app navigate to another site without leaving its window.`},de=async({iframe:t,domains:n=[]})=>{let r=crypto.randomUUID();if(S(t.src),await f(),!t.isConnected)throw Error(`attachFrame: the iframe must be connected to the document before attaching`);t.dispatchEvent(new CustomEvent(b,{detail:r}));let{executeLocator:i,ensureLocatorPermission:a,goto:o}=await p.attachFrame({marker:r,domains:n}),s=e.r(i,a),c=(e,t={})=>(S(e),o({url:e,...t})),l=()=>t.src;return{...s,goto:c,url:l}},fe={request:e=>p.requestPermissions(e.map(e=>({key:e.key,scope:e.scope??``,reason:e.reason})))},pe=32,me=typeof CSS<`u`&&CSS.supports(`clip-path`,`path('M0 0H1V1H0Z')`),he=e=>{let t=e.style;t.setProperty(`display`,`block`,`important`),t.setProperty(`position`,`fixed`,`important`),t.setProperty(`top`,`0`,`important`),t.setProperty(`left`,`0`,`important`),t.setProperty(`width`,`100%`,`important`),t.setProperty(`height`,`100%`,`important`),t.setProperty(`border`,`none`,`important`),t.setProperty(`clip-path`,`inset(100%)`,`important`),t.setProperty(`background`,`transparent`),t.setProperty(`color-scheme`,`normal`),t.setProperty(`z-index`,`2147483647`),e.setAttribute(`title`,`FKN`)},ge=({x:e,y:t,width:n,height:r})=>`M${e} ${t}h${n}v${r}h${-n}Z`,_e=(e,{modal:t,rects:n})=>{if(!me){let r=t||n.length>0;e.style.setProperty(`pointer-events`,r?`auto`:`none`,`important`),e.style.setProperty(`visibility`,r?`visible`:`hidden`,`important`);return}let r=t?`none`:n.length===0?`inset(100%)`:`path('${n.map(ge).join(``)}')`,i=r===`none`||CSS.supports(`clip-path`,r)?r:`inset(100%)`;e.style.setProperty(`clip-path`,i,`important`)},ve=e=>{if(typeof e!=`object`||!e)return null;let{x:t,y:n,width:r,height:i}=e;if(![t,n,r,i].every(e=>typeof e==`number`&&Number.isFinite(e)))return null;let a=window.innerWidth,o=window.innerHeight,s=Math.max(0,Math.min(Math.round(t),a)),c=Math.max(0,Math.min(Math.round(n),o)),l=Math.max(s,Math.min(Math.round(t+r),a)),u=Math.max(c,Math.min(Math.round(n+i),o));return{x:s,y:c,width:l-s,height:u-c}},ye=e=>{if(typeof e!=`object`||!e)return null;let t=e,n=(Array.isArray(t.rects)?t.rects.slice(0,pe):[]).map(ve).filter(e=>e!==null&&e.width>0&&e.height>0);return{modal:t.modal===!0,rects:n}},C=null,be=()=>C!==null,xe=e=>{he(e),_e(e,{modal:!1,rects:[]}),C=e},Se=e=>{if(!C)return;let t=ye(e);t&&_e(C,t)},Ce=`https://fkn.app`,w=typeof globalThis<`u`&&globalThis.document?globalThis.document:void 0,we=w?.querySelector(`iframe[src="${Ce}/api"]`)??null,T=w?.createElement(`iframe`)??null;!we&&T&&w&&(T.src=`${Ce}/api`,w.body.appendChild(T));var E=we??T,D=E?.contentWindow??null;E&&w&&xe(E);var O=(()=>{if(typeof window<`u`)return D?{receive:window,emit:D}:void 0;if(typeof self<`u`)return{receive:self,emit:self}})(),Te=O!==void 0,k=O?(0,t.expose)({},{key:`fkn-api`,transport:O}):new Promise(()=>{});k.then(e=>{be()&&e.overlay.setHost(Se)},()=>{});var Ee=[`fkn.app`,`fkn.dev`],A=e=>{let t=typeof e==`string`?e:e instanceof URL?e.href:e.url,n;try{n=new URL(t)}catch{return}let r=n.hostname;if(Ee.some(e=>r===e||r.endsWith(`.${e}`)))throw Error(`fetch refuses FKN platform domains (${r})`)},j=(e,t)=>(A(e),k.then(n=>n.cloud.fetch(e,t))),De=async()=>{let e=await k.then(e=>e.cloud.quota());return{premium:e.premium,overQuota:e.overQuota,throttled:e.overQuota&&!e.premium,usedBytes:e.usedBytes,limitBytes:e.limitBytes,remainingBytes:e.remaining,bytesPerSecond:e.bytesPerSecond,bitsPerSecond:e.bytesPerSecond*8}},Oe=e.g({lookup:()=>ke}),ke=(e,t)=>k.then(n=>n.cloud.dns.lookup(e,t)),Ae=new TextEncoder;new TextDecoder;var M=e=>i.Address4.isValid(e),N=e=>i.Address6.isValid(e),je=e=>M(e)?4:N(e)?6:0,Me=(...e)=>{if(typeof e[0]==`string`)throw Error(`FKN WebVPN does not support IPC connections`);let t=typeof e.at(-1)==`function`?e.at(-1):void 0;return e[0]&&typeof e[0]==`object`?{...e[0],callback:t}:{port:e[0]??0,host:typeof e[1]==`string`?e[1]:void 0,callback:t}},Ne=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=e[0]??0,r=typeof e[1]==`string`?e[1]:void 0;return typeof e[0]==`object`?{...e[0],address:e[0].address??r,port:e[0].port??n,callback:t}:{address:r,port:n,callback:t}},Pe=(...e)=>{let t=typeof e.at(-1)==`function`?e.at(-1):void 0,n=e[0];if(typeof e[2]==`number`)return{message:n,offset:e[1],length:e[2],port:typeof e[3]==`number`?e[3]:0,address:typeof e[4]==`string`?e[4]:void 0,callback:t};{let r=typeof e[1]==`number`?e[1]:0,i=typeof e[2]==`string`?e[2]:void 0;return{message:n,offset:0,length:n.length,port:r,address:i,callback:t}}};new TextEncoder,new TextDecoder;var Fe=e.g({Server:()=>F,Socket:()=>P,_default:()=>Re,connect:()=>I,createConnection:()=>Ie,createServer:()=>Le,default:()=>Re,isIP:()=>je,isIPv4:()=>M,isIPv6:()=>N}),P=class extends n.Stream.Duplex{_localAddress;_remoteAddress;_webVPNTcpSocketPromise;constructor(e){if(e?.fd!==void 0)throw Error(`FKN WebVPN does not support file descriptors`);super(e),e?.connection&&this.__webvpn_tcp_socket_init__(e.connection)}__webvpn_tcp_socket_init__(e){if(this._webVPNTcpSocketPromise=e.then(e=>{let t=e.dataReadableStream.getReader(),n=e.dataWritableStream.getWriter();return this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},this._remoteAddress={address:e.remoteAddress,family:e.remoteFamily,port:e.remotePort},{...e,reader:t,writer:n}}).catch(e=>{this.emit(`error`,e)}),!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);return this._webVPNTcpSocketPromise.then(e=>{e&&this.emit(`connect`)}),this._webVPNTcpSocketPromise}_read(e){if(!this._webVPNTcpSocketPromise)throw Error(`Socket not connected`);this._webVPNTcpSocketPromise.then(e=>{if(!e){this.push(null);return}e.reader.read().then(({value:e,done:t})=>{if(t){this.push(null);return}this._restartTimeoutTimer(),this.push(e)}).catch(e=>{this.destroy(e)})})}_write(e,t,n){if(!this._webVPNTcpSocketPromise){n(Error(`Socket not connected`));return}this._webVPNTcpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not connected`);await t.writer.ready,await t.writer.write(e),this._restartTimeoutTimer(),n()}).catch(n)}connect(...e){let t=Me(...e),n=this.__webvpn_tcp_socket_init__(k.then(e=>e.cloud.webvpn.tcpSocket({remoteAddress:t.host??`localhost`,remotePort:t.port})));return t.callback&&n.then(e=>{e&&t.callback.call(this)}),this}_end(...e){return this._webVPNTcpSocketPromise?(e.length!==0&&this.write(e[0],e[1],e[2]),this._webVPNTcpSocketPromise.then(async e=>{e&&await e.end()}),this):this}_destroy(e){return this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.destroy()}),this}destroySoon(){this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.destroySoon()})}resetAndDestroy(){return this._webVPNTcpSocketPromise&&this._webVPNTcpSocketPromise.then(async e=>{e&&await e.resetAndDestroy()}),this}_timeoutMs;_timeoutTimer;_restartTimeoutTimer(){this._timeoutTimer&&clearTimeout(this._timeoutTimer),this._timeoutMs&&(this._timeoutTimer=setTimeout(()=>this.emit(`timeout`),this._timeoutMs))}setTimeout(e,t){return t&&this.on(`timeout`,t),this._timeoutMs=e,this._restartTimeoutTimer(),this}setNoDelay(e){let t=e??!0;return this._setTcpOption({type:0,value:t}),this}setKeepAlive(e,t){let n=e??!1,r=t!==void 0&&t>0?Math.max(1,Math.round(t/1e3)):0;return this._setTcpOption({type:2,enabled:n,initialDelaySeconds:r}),this}setSendBufferSize(e){return this._setTcpOption({type:3,value:e}),this}setRecvBufferSize(e){return this._setTcpOption({type:4,value:e}),this}_typeOfService;getTypeOfService(){return this._typeOfService??0}setTypeOfService(e){return this._typeOfService=e,this}_setTcpOption(e){if(!this._webVPNTcpSocketPromise){this.emit(`error`,Error(`Cannot set socket option before connect`));return}this._webVPNTcpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}write(e,t,...n){return super.write(e,t,...n)}address(){return this._localAddress??{}}unref(){return this}ref(){return this}autoSelectFamilyAttemptedAddresses;bufferSize;bytesRead;bytesWritten;connecting;pending;get localAddress(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.address}get localPort(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.port}get localFamily(){if(!this._localAddress)throw Error(`Socket is not connected`);return this._localAddress.family}readyState;get remoteAddress(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.address}get remotePort(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.port}get remoteFamily(){if(!this._remoteAddress)throw Error(`Socket is not connected`);return this._remoteAddress.family}timeout},F=class extends r.EventEmitter{_localAddress;_webVPNTcpSocketListenerPromise;constructor(e,t){super(e),t&&this.on(`connection`,t),e?.connection&&this.__webvpn_tcp_socket_listener_init__(e.connection)}__webvpn_tcp_socket_listener_init__(e){return this._webVPNTcpSocketListenerPromise=e.then(e=>(this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e)).catch(e=>{this.emit(`error`,e)}),this._webVPNTcpSocketListenerPromise.then(e=>{e&&this.emit(`listening`)}),this._webVPNTcpSocketListenerPromise}listen(...e){let t=Me(...e),n=e=>{let t=new P({connection:Promise.resolve(e)});this.emit(`connection`,t)},r=e=>k.then(r=>r.cloud.webvpn.tcpSocketListener({localAddress:e,localPort:t.port,onConnection:n})),i=t.host?r(t.host):r(`::`).catch(()=>r(`0.0.0.0`)),a=this.__webvpn_tcp_socket_listener_init__(i);return t.callback&&a.then(e=>{e&&t.callback.call(this)}),this}close(e){return this._webVPNTcpSocketListenerPromise&&this._webVPNTcpSocketListenerPromise.then(async t=>{if(t)try{await t.close(),this._localAddress=void 0,this.emit(`close`),e&&e()}catch(t){this._localAddress=void 0,this.emit(`close`),e&&e(t)}}),this}address(){return this._localAddress??null}getConnections(e){throw Error(`Method not implemented.`)}ref(){return this}unref(){return this}maxConnections;connections;listening;async[Symbol.asyncDispose](){}},I=(e,t)=>new P().connect(e,t),Ie=(e,t)=>new P().connect(e,t),Le=(e,t)=>{typeof e==`function`&&(t=e,e=void 0);let n=new F(e);return t&&n.on(`connection`,t),n},Re={Socket:P,Server:F,connect:I,createConnection:Ie,createServer:Le,isIP:je,isIPv4:M,isIPv6:N},ze=e.g({Socket:()=>Be,createSocket:()=>Ue}),Be=class extends r.EventEmitter{_type;_localAddress;_remoteAddress;_webVPNUdpSocketPromise;_dataPort;_socketId;_sendQueue=[];_sendQueueBytes=0;_sendFlushScheduled=!1;_peerTailCache=new Map;constructor(e){if(super(e),!e)throw Error(`Missing options`);this._type=e.type}_lastRecvBufferSize=0;_lastSendBufferSize=0;_lastTtl=64;_lastMulticastTtl=1;_lastMulticastLoopback=!0;_setUdpOption(e){if(!this._webVPNUdpSocketPromise){this.emit(`error`,Error(`Cannot set socket option before bind`));return}this._webVPNUdpSocketPromise.then(async t=>{if(t)try{await t.setOption(e)}catch(e){this.emit(`error`,e)}})}_onDataPortBatch(e){let t=new DataView(e),n=0;for(;n+4<=e.byteLength;){let r=t.getUint32(n);n+=4;let i=n+r;if(i>e.byteLength)break;let o=n+4,s=t.getUint8(o);o+=1;let c,l,u;if(s===2){if(!this._remoteAddress){n=i;continue}c=this._remoteAddress.address,l=this._remoteAddress.family,u=this._remoteAddress.port}else{let n=new Uint8Array(e,o,s===0?4:16);if(s===0)l=`IPv4`,c=`${n[0]}.${n[1]}.${n[2]}.${n[3]}`;else{l=`IPv6`;let e=[];for(let t=0;t<16;t+=2)e.push(((n[t]<<8|n[t+1])>>>0).toString(16));c=e.join(`:`)}o+=n.byteLength,u=t.getUint16(o),o+=2}let d=t.getUint32(o);o+=4,this.emit(`message`,a.Buffer.from(e.slice(o,o+d)),{address:c,family:l,port:u,size:d}),n=i}}_peerTail(e,t){if(e===void 0||t===void 0)return Ve;let n=`${e}|${t}`,r=this._peerTailCache.get(n);if(r)return r;let a=i.Address4.isValid(e)?L(e):R(e),o=new Uint8Array(1+a.byteLength+2);return o[0]=a.byteLength===4?0:1,o.set(a,1),new DataView(o.buffer).setUint16(1+a.byteLength,t),this._peerTailCache.set(n,o),o}_portSend(e,t,n){let r=this._peerTail(t,n),i=new Uint8Array(8+r.byteLength+4+e.byteLength),a=new DataView(i.buffer);a.setUint32(0,i.byteLength-4),a.setUint32(4,this._socketId),i.set(r,8),a.setUint32(8+r.byteLength,e.byteLength),i.set(e,12+r.byteLength),this._sendQueue.push(i),this._sendQueueBytes+=i.byteLength,!this._sendFlushScheduled&&(this._sendFlushScheduled=!0,queueMicrotask(()=>{this._sendFlushScheduled=!1;let e=this._sendQueue,t=this._sendQueueBytes;if(this._sendQueue=[],this._sendQueueBytes=0,!e.length||!this._dataPort)return;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;this._dataPort.postMessage(n.buffer,[n.buffer])}))}addMembership(e,t){if(i.Address4.isValid(e)){let n=L(e),r=t&&i.Address4.isValid(t)?L(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:5,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=R(e);this._setUdpOption({type:7,group:t,ifIndex:0})}else this.emit(`error`,Error(`Invalid multicast address: ${e}`))}address(){if(!this._localAddress)throw Error(`EBADF`);return this._localAddress}bind(...e){let t=Ne(...e),n=this._type===`udp6`?`::`:`0.0.0.0`;return this._webVPNUdpSocketPromise=k.then(e=>e.cloud.webvpn.udpSocket({type:this._type,address:t.address??n,port:t.port,dataPort:!0})).then(e=>{if(e.dataPort)this._socketId=e.socketId,this._dataPort=e.dataPort,this._dataPort.onmessage=e=>this._onDataPortBatch(e.data);else{let t=e.dataReadableStream.getReader(),n=async()=>{let{value:e,done:r}=await t.read();r||(this.emit(`message`,a.Buffer.from(e.data),{address:e.address,family:e.family,port:e.port,size:e.size}),n())};n()}return this._localAddress={address:e.localAddress,family:e.localFamily,port:e.localPort},e}).catch(e=>{this.emit(`error`,e)}),this._webVPNUdpSocketPromise.then(e=>{e&&this.emit(`listening`)}),t.callback&&this._webVPNUdpSocketPromise.then(e=>{e&&t.callback.call(this)}),this}close(e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);return this._webVPNUdpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not bound`);this._dataPort?.close(),this._dataPort=void 0,await t.close(),e&&e(),this.emit(`close`)}),this}connect(...e){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(async t=>{if(!t)throw Error(`Socket not bound`);let n=e[0],r=this._type===`udp6`?`::1`:`127.0.0.1`,i=typeof e[1]==`string`?e[1]:r,a=typeof e.at(-1)==`function`?e.at(-1):void 0;await t.connect({remotePort:n,remoteAddress:i}),this._remoteAddress={address:i,family:this._type===`udp6`?`IPv6`:`IPv4`,port:n},a&&a()})}disconnect(){if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(async e=>{if(!e)throw Error(`Socket not bound`);await e.connect({remotePort:0,remoteAddress:this._type===`udp4`?`0.0.0.0`:`::`})})}dropMembership(e,t){if(i.Address4.isValid(e)){let n=L(e),r=t&&i.Address4.isValid(t)?L(t):new Uint8Array([0,0,0,0]);this._setUdpOption({type:6,group:n,interface:r})}else if(i.Address6.isValid(e)){let t=R(e);this._setUdpOption({type:8,group:t,ifIndex:0})}else this.emit(`error`,Error(`Invalid multicast address: ${e}`))}getRecvBufferSize(){return this._lastRecvBufferSize}getSendBufferSize(){return this._lastSendBufferSize}getSendQueueSize(){return 0}getSendQueueCount(){return 0}ref(){return this}remoteAddress(){if(!this._remoteAddress)throw Error(`ERR_SOCKET_DGRAM_NOT_CONNECTED`);return{address:this._remoteAddress.address,family:this._remoteAddress.family,port:this._remoteAddress.port}}send(...e){this._webVPNUdpSocketPromise||this.bind();let t=Pe(...e),n=this._type===`udp6`?`::1`:`127.0.0.1`;if(!this._webVPNUdpSocketPromise)throw Error(`Socket not bound`);this._webVPNUdpSocketPromise.then(e=>{if(!e)throw Error(`Socket not bound`);let r=He(t.message),a=t.callback,o=t.address??n,s=this._remoteAddress!==void 0&&t.address===void 0;if(this._dataPort&&(s||i.Address4.isValid(o)||i.Address6.isValid(o))){this._portSend(r,s?void 0:o,s?void 0:t.port),a?.call(this,null,r.byteLength);return}e.send({...t,address:o,message:r.byteOffset===0&&r.byteLength===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}).then(()=>a?.call(this,null,r.byteLength),e=>a?a.call(this,e,0):this.emit(`error`,e))})}setBroadcast(e){this._setUdpOption({type:0,value:e})}setMulticastInterface(e){}setMulticastLoopback(e){return this._setUdpOption({type:3,value:e}),this._setUdpOption({type:4,value:e}),this._lastMulticastLoopback=e,e}setMulticastTTL(e){return this._setUdpOption({type:2,value:e}),this._lastMulticastTtl=e,e}setRecvBufferSize(e){this._setUdpOption({type:10,value:e}),this._lastRecvBufferSize=e}setSendBufferSize(e){this._setUdpOption({type:9,value:e}),this._lastSendBufferSize=e}setTTL(e){return this._setUdpOption({type:1,value:e}),this._lastTtl=e,e}unref(){return this}addSourceSpecificMembership(e,t,n){}dropSourceSpecificMembership(e,t,n){}async[Symbol.asyncDispose](){await new Promise(e=>{this.close(e)})}},Ve=new Uint8Array([2]),He=e=>{if(typeof e==`string`)return Ae.encode(e);if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(Array.isArray(e)){let t=e.map(He),n=new Uint8Array(t.reduce((e,t)=>e+t.byteLength,0)),r=0;for(let e of t)n.set(e,r),r+=e.byteLength;return n}return new Uint8Array(e)},L=e=>{let t=e.split(`.`).map(e=>parseInt(e,10));if(t.length!==4||t.some(e=>Number.isNaN(e)||e<0||e>255))throw Error(`Invalid IPv4 address: ${e}`);return new Uint8Array(t)},R=e=>{let t=new i.Address6(e).getBitsBase16(0,128).match(/.{2}/g);if(!t||t.length!==16)throw Error(`Invalid IPv6 address: ${e}`);return new Uint8Array(t.map(e=>parseInt(e,16)))},Ue=(e,t)=>{let n=new Be(typeof e==`string`?{type:e}:e);return t&&n.on(`message`,t),n},We=e.g({Agent:()=>Y,ClientRequest:()=>q,HTTPParser:()=>U,IncomingMessage:()=>W,METHODS:()=>Ke,STATUS_CODES:()=>z,Server:()=>J,ServerResponse:()=>K,_default:()=>rt,createServer:()=>nt,default:()=>rt,get:()=>tt,globalAgent:()=>et,request:()=>X}),Ge=new TextDecoder(`latin1`),Ke=`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE`.split(`.`),z={100:`Continue`,101:`Switching Protocols`,102:`Processing`,103:`Early Hints`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad Request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a Teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too Many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,500:`Internal Server Error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,509:`Bandwidth Limit Exceeded`,510:`Not Extended`,511:`Network Authentication Required`},qe=new Set([`content-type`,`content-length`,`user-agent`,`referer`,`host`,`authorization`,`proxy-authorization`,`if-modified-since`,`if-unmodified-since`,`from`,`location`,`max-forwards`,`retry-after`,`etag`,`last-modified`,`server`,`age`,`expires`]),B=13,V=10,Je=/^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/,H=(e,t)=>(e.code=t,e),Ye=(e,t)=>{if(e.length===0)return t;if(t.length===0)return e;let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n},Xe=(e,t)=>{for(let n=t;n+1<e.length;n++)if(e[n]===B&&e[n+1]===V)return n;return-1},Ze=e=>{for(let t=0;t+3<e.length;t++)if(e[t]===B&&e[t+1]===V&&e[t+2]===B&&e[t+3]===V)return t;return-1},U=class{buf=new Uint8Array;state=`HEAD`;framing=`none`;bodyRemaining=0;chunkState=`size`;skipBody=!1;constructor(e,t){this.mode=e,this.handlers=t}execute(e){this.buf=Ye(this.buf,e);let t=!0;for(;t;)if(t=!1,this.state===`HEAD`){let e=Ze(this.buf);if(e===-1)return;let n=this.buf.subarray(0,e);this.buf=this.buf.subarray(e+4);let r=this.parseHead(n);this.handlers.onHeaders(r),this.setupBody(r),this.framing===`none`?(this.handlers.onComplete(),this.reset(),t=this.buf.length>0):(this.state=`BODY`,t=!0)}else this.consumeBody()&&(this.handlers.onComplete(),this.reset(),t=this.buf.length>0)}finish(){this.state===`BODY`&&this.framing===`eof`&&(this.handlers.onComplete(),this.reset())}reset(){this.state=`HEAD`,this.framing=`none`,this.bodyRemaining=0,this.chunkState=`size`,this.skipBody=!1}parseHead(e){let t=Ge.decode(e).split(`\r
|
|
2
|
+
`),n=t.shift()??``,r=[];for(let e of t)(e.startsWith(` `)||e.startsWith(` `))&&r.length>0?r[r.length-1]+=` `+e.trim():r.push(e);let i=[],a={};for(let e of r){if(!e)continue;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();i.push(n,r),this.addHeader(a,n,r)}let o={httpVersionMajor:1,httpVersionMinor:1,httpVersion:`1.1`,headers:a,rawHeaders:i};if(this.mode===`request`){let[e,t,r]=n.split(` `);o.method=(e??`GET`).toUpperCase(),o.url=t??`/`,this.applyVersion(o,r)}else{let e=n.indexOf(` `),t=n.slice(0,e),r=n.slice(e+1),i=r.indexOf(` `),a=i===-1?r:r.slice(0,i);o.statusCode=parseInt(a,10)||0,o.statusMessage=i===-1?``:r.slice(i+1),this.applyVersion(o,t)}return o}applyVersion(e,t){let n=/HTTP\/(\d)\.(\d)/i.exec(t??``);n&&(e.httpVersionMajor=parseInt(n[1],10),e.httpVersionMinor=parseInt(n[2],10),e.httpVersion=`${e.httpVersionMajor}.${e.httpVersionMinor}`)}addHeader(e,t,n){let r=t.toLowerCase();if(r===`set-cookie`){let t=e[`set-cookie`];Array.isArray(t)?t.push(n):e[`set-cookie`]=[n];return}let i=e[r];i===void 0?e[r]=n:qe.has(r)||(e[r]=`${i}, ${n}`)}setupBody(e){if(this.skipBody){this.framing=`none`;return}let t=e.headers[`transfer-encoding`];if(typeof t==`string`&&t.toLowerCase().includes(`chunked`)){this.framing=`chunked`,this.chunkState=`size`;return}let n=e.headers[`content-length`];if(typeof n==`string`&&n!==``){let e=parseInt(n,10);e>0?(this.framing=`length`,this.bodyRemaining=e):this.framing=`none`;return}if(this.mode===`response`){let t=e.statusCode??0;t>=100&&t<200||t===204||t===304?this.framing=`none`:this.framing=`eof`}else this.framing=`none`}consumeBody(){if(this.framing===`length`){if(this.buf.length===0)return!1;let e=Math.min(this.bodyRemaining,this.buf.length);return this.handlers.onBody(this.buf.subarray(0,e)),this.buf=this.buf.subarray(e),this.bodyRemaining-=e,this.bodyRemaining===0}return this.framing===`eof`?(this.buf.length>0&&(this.handlers.onBody(this.buf),this.buf=new Uint8Array),!1):this.framing===`chunked`?this.consumeChunked():!0}consumeChunked(){for(;;)if(this.chunkState===`size`){let e=Xe(this.buf,0);if(e===-1)return!1;let t=Ge.decode(this.buf.subarray(0,e)),n=parseInt(t.split(`;`)[0].trim(),16);if(this.buf=this.buf.subarray(e+2),Number.isNaN(n))return!0;n===0?this.chunkState=`trailer`:(this.bodyRemaining=n,this.chunkState=`data`)}else if(this.chunkState===`data`){if(this.buf.length===0)return!1;let e=Math.min(this.bodyRemaining,this.buf.length);this.handlers.onBody(this.buf.subarray(0,e)),this.buf=this.buf.subarray(e),this.bodyRemaining-=e,this.bodyRemaining===0&&(this.chunkState=`dataCRLF`)}else if(this.chunkState===`dataCRLF`){if(this.buf.length<2)return!1;this.buf=this.buf.subarray(2),this.chunkState=`size`}else{let e=Xe(this.buf,0);if(e===-1)return!1;let t=e===0;if(this.buf=this.buf.subarray(e+2),t)return!0}}},Qe=(e,t)=>a.Buffer.isBuffer(e)?e:typeof e==`string`?a.Buffer.from(e,t??`utf8`):e instanceof Uint8Array?a.Buffer.from(e):e instanceof ArrayBuffer?a.Buffer.from(new Uint8Array(e)):a.Buffer.from(String(e)),W=class extends n.Stream.Readable{httpVersion=`1.1`;httpVersionMajor=1;httpVersionMinor=1;headers={};rawHeaders=[];trailers={};rawTrailers=[];method;url;statusCode;statusMessage;complete=!1;socket;constructor(e){super(),this.socket=e}get connection(){return this.socket}_applyHead(e){this.httpVersion=e.httpVersion,this.httpVersionMajor=e.httpVersionMajor,this.httpVersionMinor=e.httpVersionMinor,this.headers=e.headers,this.rawHeaders=e.rawHeaders,this.method=e.method,this.url=e.url,this.statusCode=e.statusCode,this.statusMessage=e.statusMessage}_read(){}setTimeout(e,t){return this.socket.setTimeout(e,t),this}},G=class extends n.Stream.Writable{_headerStore=new Map;headersSent=!1;chunkedEncoding=!1;finished=!1;_bodyWritten=!1;setHeader(e,t){if(this.headersSent)throw H(Error(`Cannot set headers after they are sent to the client`),`ERR_HTTP_HEADERS_SENT`);if(typeof e!=`string`||!Je.test(e))throw H(TypeError(`Header name must be a valid HTTP token [${JSON.stringify(String(e))}]`),`ERR_INVALID_HTTP_TOKEN`);if(t===void 0)throw H(TypeError(`Invalid value "undefined" for header "${e}"`),`ERR_HTTP_INVALID_HEADER_VALUE`);return this._headerStore.set(e.toLowerCase(),[e,Array.isArray(t)?[...t]:t]),this}getHeader(e){return this._headerStore.get(e.toLowerCase())?.[1]}getHeaderNames(){return[...this._headerStore.values()].map(([e])=>e)}getHeaders(){let e={};for(let[t,n]of this._headerStore.values())e[t]=n;return e}hasHeader(e){return this._headerStore.has(e.toLowerCase())}removeHeader(e){if(this.headersSent)throw Error(`Cannot remove headers after they are sent to the client`);this._headerStore.delete(e.toLowerCase())}_storeHeader(e){let t=this.hasHeader(`content-length`),n=this.getHeader(`transfer-encoding`);typeof n==`string`&&n.toLowerCase().includes(`chunked`)?this.chunkedEncoding=!0:!t&&this._shouldSendBody()&&(this.chunkedEncoding=!0,this.setHeader(`Transfer-Encoding`,`chunked`));let r=e+`\r
|
|
3
3
|
`;for(let[e,t]of this._headerStore.values())if(Array.isArray(t))for(let n of t)r+=`${e}: ${n}\r\n`;else r+=`${e}: ${t}\r\n`;return r+=`\r
|
|
4
|
-
`,r}_writeToSocket(e,t){if(!this.socket){t(Error(`Socket is not available`));return}this.socket.write(e,t)}write(e,t,n){return this._bodyWritten=!0,super.write(e,t,n)}_write(e,t,n){let r=
|
|
4
|
+
`,r}_writeToSocket(e,t){if(!this.socket){t(Error(`Socket is not available`));return}this.socket.write(e,t)}write(e,t,n){return this._bodyWritten=!0,super.write(e,t,n)}_write(e,t,n){let r=Qe(e),i=[];if(this.headersSent||=(this._implicitHeader(),i.push(a.Buffer.from(this._headBlock,`latin1`)),!0),this.chunkedEncoding?r.length>0&&(i.push(a.Buffer.from(`${r.length.toString(16)}\r\n`,`latin1`)),i.push(r),i.push(a.Buffer.from(`\r
|
|
5
5
|
`,`latin1`))):i.push(r),i.length===0){n();return}this._writeToSocket(a.Buffer.concat(i),n)}_final(e){let t=[];if(this.headersSent||=(!this.chunkedEncoding&&!this.hasHeader(`content-length`)&&this.setHeader(`Content-Length`,0),this._implicitHeader(),t.push(a.Buffer.from(this._headBlock,`latin1`)),!0),this.chunkedEncoding&&t.push(a.Buffer.from(`0\r
|
|
6
6
|
\r
|
|
7
|
-
`,`latin1`)),this.finished=!0,t.length===0){e();return}this._writeToSocket(a.Buffer.concat(t),e)}end(e,t,n){if(e!=null&&typeof e!=`function`&&!this._bodyWritten&&!this.headersSent&&!this.chunkedEncoding&&!this.hasHeader(`content-length`)){let n=typeof t==`string`?t:void 0;this.setHeader(`Content-Length`,
|
|
7
|
+
`,`latin1`)),this.finished=!0,t.length===0){e();return}this._writeToSocket(a.Buffer.concat(t),e)}end(e,t,n){if(e!=null&&typeof e!=`function`&&!this._bodyWritten&&!this.headersSent&&!this.chunkedEncoding&&!this.hasHeader(`content-length`)){let n=typeof t==`string`?t:void 0;this.setHeader(`Content-Length`,Qe(e,n).length)}return super.end(e,t,n)}_headBlock},K=class extends G{statusCode=200;statusMessage;_writeHeadCalled=!1;sendDate=!0;req;socket;_keepAlive=!0;constructor(e){super(),this.req=e,this.socket=e.socket}_shouldSendBody(){if(this.req.method===`HEAD`)return!1;let e=this.statusCode;return!(e>=100&&e<200||e===204||e===304)}writeHead(e,t,n){if(this._writeHeadCalled||this.headersSent)throw H(Error(`Cannot render headers after they are sent to the client`),`ERR_HTTP_HEADERS_SENT`);this._writeHeadCalled=!0,this.statusCode=e;let r=n;if(typeof t==`string`?this.statusMessage=t:t!=null&&(r=t),Array.isArray(r)){let e=Array.isArray(r[0])?r:Array.from({length:Math.floor(r.length/2)},(e,t)=>[r[t*2],r[t*2+1]]);for(let[t,n]of e)n!==void 0&&this._appendHeader(t,n)}else if(r)for(let[e,t]of Object.entries(r))t!==void 0&&this.setHeader(e,t);return this}_appendHeader(e,t){let n=this.getHeader(e);if(n===void 0)this.setHeader(e,t);else{let r=[...Array.isArray(n)?n:[n],...Array.isArray(t)?t:[t]].map(String);this.setHeader(e,r)}}_implicitHeader(){let e=this.statusMessage??z[this.statusCode]??`unknown`;this.sendDate&&!this.hasHeader(`date`)&&this.setHeader(`Date`,new Date().toUTCString()),this.hasHeader(`connection`)||this.setHeader(`Connection`,this._keepAlive?`keep-alive`:`close`),this._headBlock=this._storeHeader(`HTTP/1.1 ${this.statusCode} ${e}`)}writeContinue(){this._writeToSocket(a.Buffer.from(`HTTP/1.1 100 Continue\r
|
|
8
8
|
\r
|
|
9
|
-
`,`latin1`),()=>{})}setTimeout(e,t){return this.socket?.setTimeout(e,t),this}}
|
|
9
|
+
`,`latin1`),()=>{})}setTimeout(e,t){return this.socket?.setTimeout(e,t),this}},$e=(...e)=>{let t={},n={},r,i=[...e],a=i.shift();if(typeof a==`string`||a instanceof URL){let e=typeof a==`string`?new URL(a):a;t={protocol:e.protocol,hostname:e.hostname,host:e.hostname,port:e.port,path:`${e.pathname}${e.search}`,auth:e.username?`${e.username}:${e.password}`:void 0};let o=i.shift();typeof o==`function`?r=o:o&&typeof o==`object`&&(n=o,r=i.shift())}else a&&typeof a==`object`&&(n=a,r=i.shift());return{options:{...t,...n},callback:r}},q=class extends G{method;path;host;protocol;socket;get connection(){return this.socket}res=null;aborted=!1;_aborted=!1;constructor(e,t){super(),this.method=(e.method??`GET`).toUpperCase(),this.path=e.path??`/`,this.protocol=e.protocol??`http:`;let n=e.hostname??e.host??`localhost`;this.host=n;let r=Number(e.port??(this.protocol===`https:`?443:80));if(t&&this.once(`response`,t),e.headers)for(let[t,n]of Object.entries(e.headers))n!==void 0&&this.setHeader(t,n);if(!this.hasHeader(`host`)){let e=this.protocol===`https:`&&r===443||this.protocol!==`https:`&&r===80;this.setHeader(`Host`,e?n:`${n}:${r}`)}e.auth&&!this.hasHeader(`authorization`)&&this.setHeader(`Authorization`,`Basic ${a.Buffer.from(e.auth).toString(`base64`)}`),this.socket=new P,this.emit(`socket`,this.socket),this.socket.on(`error`,e=>{this._aborted||this.emit(`error`,e)}),this._attachResponseParser(),this.socket.connect({host:n,port:r},()=>{this.emit(`connect`)})}_shouldSendBody(){return this.method!==`GET`&&this.method!==`HEAD`&&this.method!==`DELETE`}_implicitHeader(){this._headBlock=this._storeHeader(`${this.method} ${this.path} HTTP/1.1`)}_attachResponseParser(){let e=new W(this.socket),t=new U(`response`,{onHeaders:n=>{e._applyHead(n),this.method===`HEAD`&&(t.skipBody=!0),this.res=e,this.emit(`response`,e)},onBody:t=>{e.push(a.Buffer.from(t))},onComplete:()=>{e.complete=!0,e.push(null)}});this.socket.on(`data`,e=>{this._aborted||t.execute(e)}),this.socket.on(`end`,()=>{t.finish()}),this.socket.on(`close`,()=>{this.emit(`close`)})}abort(){this._aborted||(this._aborted=!0,this.aborted=!0,this.emit(`abort`),this.socket.destroy())}destroy(e){return this._aborted?this:(this._aborted=!0,this.socket.destroy(e),super.destroy(e),this)}end(e,t,n){return this._aborted?this:super.end(e,t,n)}_writeToSocket(e,t){if(this._aborted){t();return}super._writeToSocket(e,t)}setTimeout(e,t){return this.socket.setTimeout(e,t),this}setNoDelay(e){this.socket.setNoDelay(e)}setSocketKeepAlive(e,t){this.socket.setKeepAlive(e,t)}},J=new Proxy(class extends F{constructor(e,t){let n={},r=t;typeof e==`function`?r=e:e&&(n=e),super(n),r&&this.on(`request`,r),this.on(`connection`,e=>this._handleConnection(e))}_handleConnection(e){let t=null,n=new U(`request`,{onHeaders:r=>{t=new W(e),t._applyHead(r),r.method===`HEAD`&&(n.skipBody=!0);let i=new K(t),a=String(r.headers.connection??``).toLowerCase();i._keepAlive=r.httpVersionMinor>=1?a!==`close`:a===`keep-alive`,i.on(`finish`,()=>{i._keepAlive||e.end()}),this.emit(`request`,t,i)},onBody:e=>{t?.push(a.Buffer.from(e))},onComplete:()=>{t&&(t.complete=!0,t.push(null)),t=null}});e.on(`data`,e=>n.execute(e)),e.on(`end`,()=>{n.finish(),t&&t.push(null)}),e.on(`error`,t=>this.emit(`clientError`,t,e))}},{apply:(e,t,n)=>new e(...n)}),Y=class{maxSockets;maxFreeSockets;keepAlive;options;constructor(e={}){this.options=e,this.keepAlive=!!e.keepAlive,this.maxSockets=e.maxSockets??1/0,this.maxFreeSockets=e.maxFreeSockets??256}getName(e={}){return`${e.host??`localhost`}:${e.port??``}:${e.localAddress??``}`}destroy(){}},et=new Y,X=(...e)=>{let{options:t,callback:n}=$e(...e);return new q(t,n)},tt=(...e)=>{let t=X(...e);return t.end(),t},nt=(e,t)=>new J(e,t),rt={METHODS:Ke,STATUS_CODES:z,Agent:Y,globalAgent:et,Server:J,ServerResponse:K,IncomingMessage:W,ClientRequest:q,OutgoingMessage:G,createServer:nt,request:X,get:tt},it=e.g({available:()=>at,dgram:()=>ze,dns:()=>Oe,fetch:()=>j,http:()=>We,net:()=>Fe,quota:()=>De}),at=()=>Te,Z=async e=>{if(typeof window>`u`)return!1;if(l())return!0;let t=await k,n=null,r=new Promise(e=>{n=()=>{l()&&e(!0)},c.addEventListener(`statuschange`,n)}),i=t.installPrompt.show(e).then(()=>!1),a=await Promise.race([r,i]);return n&&c.removeEventListener(`statuschange`,n),await t.installPrompt.hide().catch(()=>{}),a},Q=null;d(()=>(Q||=Z().then(()=>void 0).finally(()=>{Q=null}),Q));var ot=e.g({available:()=>st,dgram:()=>dt,dns:()=>lt,fetch:()=>ct,fs:()=>ft,net:()=>ut}),st=()=>!1,$=e=>(...t)=>{throw Error(`The FKN desktop app is not connected, desktop.${e} is unavailable`)},ct=$(`fetch`),lt={lookup:$(`dns.lookup`)},ut={connect:$(`net.connect`),createConnection:$(`net.createConnection`),createServer:$(`net.createServer`)},dt={createSocket:$(`dgram.createSocket`)},ft={isLocalDirectorySupported:()=>!1,pickLocalDirectory:$(`fs.pickLocalDirectory`),queryDirectoryPermission:$(`fs.queryDirectoryPermission`),ensureDirectoryPermission:$(`fs.ensureDirectoryPermission`)},pt=()=>typeof document<`u`&&l(),mt=async(e,t)=>{if(A(e),t?.credentials===`include`){if(typeof document>`u`)throw Error(`fetch with credentials needs the FKN extension, which only exists in window realms`);return _(e,t)}return pt()?_(e,{...t,credentials:`omit`}):st()?ct(e,t):j(e,t)},ht=e.g({ATTACH_FRAME_EVENT_KEY:()=>b,assertAttachableFrameUrl:()=>S,assertFetchableUrl:()=>g,attachFrame:()=>de,attachFramePermission:()=>le,available:()=>pt,box:()=>e.u,cookies:()=>y,createVideoElementHandle:()=>e.d,events:()=>c,extension:()=>c,fetch:()=>_,fetchCredentialedPermission:()=>ne,fetchPermission:()=>m,gotoPermission:()=>ue,handleRevivableModules:()=>e.l,isBlockedFetchUrl:()=>h,isBlockedFrameUrl:()=>x,isExtensionExposed:()=>l,isType:()=>e.f,modifyRequestHeadersPermission:()=>oe,permissions:()=>fe,promptInstall:()=>Z,readCookiePermission:()=>v,removeRequestHeaderRule:()=>ce,revive:()=>e.p,setMissingExtensionHandler:()=>d,setRequestHeaderRule:()=>se,type:()=>e.m,waitForExtensionExposure:()=>f}),gt=e.g({ensureDirectoryPermission:()=>bt,isLocalDirectorySupported:()=>_t,pickLocalDirectory:()=>vt,queryDirectoryPermission:()=>yt}),_t=()=>typeof window<`u`&&`showDirectoryPicker`in window,vt=async(e={})=>{if(!_t())return;let t=window.showDirectoryPicker;return t({mode:`readwrite`,...e}).catch(e=>{if(e?.name!==`AbortError`)throw e})},yt=async(e,t=`readwrite`)=>{let{queryPermission:n}=e;return await n?.call(e,{mode:t})??`granted`},bt=async(e,t=`readwrite`)=>{if(await yt(e,t)===`granted`)return!0;let{requestPermission:n}=e;return await n?.call(e,{mode:t})===`granted`},xt=`https://fkn.app`,St=(e,n)=>{if(typeof window>`u`)throw Error(`FKN @fkn/lib: relayWorker must be called from the main thread`);if(!E?.contentWindow)throw Error(`FKN @fkn/lib: relayWorker called before the FKN iframe was injected`);(0,t.relay)({receive:window,emit:E.contentWindow},e,{key:`fkn-api`,originA:n?.originA??xt,originB:n?.originB??`*`,unregisterSignal:n?.unregisterSignal})};exports.ATTACH_FRAME_EVENT_KEY=b,exports.assertAttachableFrameUrl=S,exports.assertFetchableUrl=g,exports.attachFrame=de,exports.attachFramePermission=le,exports.box=e.u,Object.defineProperty(exports,`cloud`,{enumerable:!0,get:function(){return it}}),exports.cookies=y,exports.createVideoElementHandle=e.d,Object.defineProperty(exports,`desktop`,{enumerable:!0,get:function(){return ot}}),Object.defineProperty(exports,`dgram`,{enumerable:!0,get:function(){return ze}}),Object.defineProperty(exports,`dns`,{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,`extension`,{enumerable:!0,get:function(){return ht}}),exports.fetch=mt,exports.fetchCredentialedPermission=ne,exports.fetchPermission=m,Object.defineProperty(exports,`fs`,{enumerable:!0,get:function(){return gt}}),exports.gotoPermission=ue,exports.handleRevivableModules=e.l,Object.defineProperty(exports,`http`,{enumerable:!0,get:function(){return We}}),exports.isBlockedFetchUrl=h,exports.isBlockedFrameUrl=x,exports.isExtensionExposed=l,exports.isType=e.f,exports.modifyRequestHeadersPermission=oe,Object.defineProperty(exports,`net`,{enumerable:!0,get:function(){return Fe}}),exports.permissions=fe,exports.promptInstall=Z,exports.readCookiePermission=v,exports.relayWorker=St,exports.removeRequestHeaderRule=ce,exports.revive=e.p,exports.setMissingExtensionHandler=d,exports.setRequestHeaderRule=se,exports.type=e.m,exports.waitForExtensionExposure=f;
|
package/index.d.ts
CHANGED
|
@@ -1044,6 +1044,8 @@ declare const makeWebVPNWebTransport: () => Promise<{
|
|
|
1044
1044
|
readonly dataLength: number;
|
|
1045
1045
|
readonly data: ArrayBuffer;
|
|
1046
1046
|
}>;
|
|
1047
|
+
claimUdpRawStream: (socketId: number, sink: (packetBytes: Uint8Array) => void) => void;
|
|
1048
|
+
releaseUdpRawStream: (socketId: number) => void;
|
|
1047
1049
|
getPacketForId: (packetId: number) => Promise<ServerMetadataPacket>;
|
|
1048
1050
|
getMetadataReadableStreamForSocketId: (socketId: number) => ReadableStream<ServerMetadataPacket>;
|
|
1049
1051
|
getMetadataReadableStreamForLocalAddress: (address: Address4 | Address6) => ReadableStream<ServerMetadataPacket>;
|
|
@@ -1094,7 +1096,7 @@ type Quota = {
|
|
|
1094
1096
|
|
|
1095
1097
|
declare const resolvers: {
|
|
1096
1098
|
readonly cloud: {
|
|
1097
|
-
readonly fetch: (input: string |
|
|
1099
|
+
readonly fetch: (input: string | URL | Request, init?: (RequestInit | undefined) & {
|
|
1098
1100
|
render?: boolean;
|
|
1099
1101
|
}) => Promise<Response>;
|
|
1100
1102
|
readonly quota: () => Promise<Quota>;
|
|
@@ -1133,11 +1135,14 @@ declare const resolvers: {
|
|
|
1133
1135
|
localPort: number;
|
|
1134
1136
|
close: () => Promise<void>;
|
|
1135
1137
|
}>;
|
|
1136
|
-
readonly udpSocket: ({ type, port, address }: {
|
|
1138
|
+
readonly udpSocket: ({ type, port, address, dataPort }: {
|
|
1137
1139
|
type: "udp4" | "udp6";
|
|
1138
1140
|
port: number;
|
|
1139
1141
|
address: string;
|
|
1142
|
+
dataPort?: boolean;
|
|
1140
1143
|
}) => Promise<{
|
|
1144
|
+
socketId: number;
|
|
1145
|
+
dataPort: MessagePort | undefined;
|
|
1141
1146
|
localAddress: string;
|
|
1142
1147
|
localFamily: "IPv4" | "IPv6";
|
|
1143
1148
|
localPort: number;
|
|
@@ -1177,7 +1182,7 @@ declare const resolvers: {
|
|
|
1177
1182
|
readonly show: (reason?: string) => Promise<void>;
|
|
1178
1183
|
readonly hide: () => void;
|
|
1179
1184
|
};
|
|
1180
|
-
readonly proxyFetch: (input: string |
|
|
1185
|
+
readonly proxyFetch: (input: string | URL | Request, init?: (RequestInit | undefined) & {
|
|
1181
1186
|
render?: boolean;
|
|
1182
1187
|
}) => Promise<Response>;
|
|
1183
1188
|
readonly webVpnTcpSocket: ({ remoteAddress: _remoteAddress, remotePort }: {
|
|
@@ -1208,11 +1213,14 @@ declare const resolvers: {
|
|
|
1208
1213
|
localPort: number;
|
|
1209
1214
|
close: () => Promise<void>;
|
|
1210
1215
|
}>;
|
|
1211
|
-
readonly webVpnUdpSocket: ({ type, port, address }: {
|
|
1216
|
+
readonly webVpnUdpSocket: ({ type, port, address, dataPort }: {
|
|
1212
1217
|
type: "udp4" | "udp6";
|
|
1213
1218
|
port: number;
|
|
1214
1219
|
address: string;
|
|
1220
|
+
dataPort?: boolean;
|
|
1215
1221
|
}) => Promise<{
|
|
1222
|
+
socketId: number;
|
|
1223
|
+
dataPort: MessagePort | undefined;
|
|
1216
1224
|
localAddress: string;
|
|
1217
1225
|
localFamily: "IPv4" | "IPv6";
|
|
1218
1226
|
localPort: number;
|
|
@@ -1255,7 +1263,7 @@ type Resolvers = typeof resolvers;
|
|
|
1255
1263
|
|
|
1256
1264
|
type ProxyFetch = Resolvers['cloud']['fetch'];
|
|
1257
1265
|
type FetchParameters = Parameters<ProxyFetch>;
|
|
1258
|
-
declare const
|
|
1266
|
+
declare const cloudFetch: (input: FetchParameters[0], init?: FetchParameters[1]) => Promise<Response>;
|
|
1259
1267
|
|
|
1260
1268
|
type QuotaStatus = {
|
|
1261
1269
|
/** the user has a paid subscription, throttle never applies */
|
|
@@ -1476,6 +1484,12 @@ declare class Socket extends EventEmitter implements Socket$3 {
|
|
|
1476
1484
|
port: number;
|
|
1477
1485
|
};
|
|
1478
1486
|
_webVPNUdpSocketPromise?: Promise<Awaited<ReturnType<WebVpnUdpSocket>> | undefined>;
|
|
1487
|
+
_dataPort?: MessagePort;
|
|
1488
|
+
_socketId?: number;
|
|
1489
|
+
_sendQueue: Uint8Array[];
|
|
1490
|
+
_sendQueueBytes: number;
|
|
1491
|
+
_sendFlushScheduled: boolean;
|
|
1492
|
+
_peerTailCache: Map<string, Uint8Array<ArrayBufferLike>>;
|
|
1479
1493
|
constructor(options: SocketOptions & EventEmitterOptions & {
|
|
1480
1494
|
connection?: ReturnType<WebVpnUdpSocket>;
|
|
1481
1495
|
});
|
|
@@ -1485,6 +1499,9 @@ declare class Socket extends EventEmitter implements Socket$3 {
|
|
|
1485
1499
|
_lastMulticastTtl: number;
|
|
1486
1500
|
_lastMulticastLoopback: boolean;
|
|
1487
1501
|
_setUdpOption(option: UdpSocketOption): void;
|
|
1502
|
+
_onDataPortBatch(buffer: ArrayBuffer): void;
|
|
1503
|
+
_peerTail(address: string | undefined, port: number | undefined): Uint8Array;
|
|
1504
|
+
_portSend(message: Uint8Array, address: string | undefined, port: number | undefined): void;
|
|
1488
1505
|
addMembership(multicastAddress: string, multicastInterface?: string | undefined): void;
|
|
1489
1506
|
address(): AddressInfo;
|
|
1490
1507
|
bind(port?: number | undefined, address?: string | undefined, callback?: (() => void) | undefined): this;
|
|
@@ -1742,7 +1759,7 @@ type cloud_QuotaStatus = QuotaStatus;
|
|
|
1742
1759
|
declare const cloud_http: typeof http;
|
|
1743
1760
|
declare const cloud_quota: typeof quota;
|
|
1744
1761
|
declare namespace cloud {
|
|
1745
|
-
export { available$1 as available, dgram$1 as dgram, dns$1 as dns,
|
|
1762
|
+
export { available$1 as available, dgram$1 as dgram, dns$1 as dns, cloudFetch as fetch, cloud_http as http, net$1 as net, cloud_quota as quota };
|
|
1746
1763
|
export type { cloud_QuotaStatus as QuotaStatus };
|
|
1747
1764
|
}
|
|
1748
1765
|
|
|
@@ -1863,5 +1880,5 @@ declare const relayWorker: (worker: Worker, options?: {
|
|
|
1863
1880
|
originB?: string;
|
|
1864
1881
|
}) => void;
|
|
1865
1882
|
|
|
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,
|
|
1883
|
+
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 };
|
|
1867
1884
|
export type { AttachFrameOptions, BoxedVideoElement, CookieDetails, FetchInit, Frame, GotoOptions, HeaderOperation, PermissionGrant, PermissionRequest, ProxyFetchRequest, RemoteVideoElement, RequestHeaderRule, SiteCookie, VideoElementState };
|