@stacksjs/rpx 0.11.34 → 0.11.35

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/dist/bin/cli.js CHANGED
@@ -221,7 +221,7 @@ Write-Host "Root CA trusted successfully!"
221
221
  `,z=K0(yW.tmpdir(),"rpx-trust.ps1");if(await G0.writeFile(z,j),CW(`powershell -ExecutionPolicy Bypass -File "${z}"`),w.verbose)H.success("Successfully added certificate to Windows trust store");B=!0}catch(j){if(w.verbose)H.warn(`Could not trust certificate: ${j}`)}else try{await LQ(W,J.certificate,Y),B=!0}catch(j){if(w.verbose)H.warn(`Could not add certificate to trust store: ${j}`)}if(L$={key:W.privateKey,cert:W.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);if(!B&&w.verbose)H.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),H.warn("This will bypass the warning and you should only need to do it once")}function O8(){L$=null}async function W$(w){if(!w)return null;if(L$)return L$;let $=PY(w);try{let[Y,A,X]=await Promise.all([G0.access($.keyPath).then(()=>!0).catch(()=>!1),G0.access($.certPath).then(()=>!0).catch(()=>!1),$.caCertPath?G0.access($.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return F("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${$.keyPath}, ${$.certPath}`,w.verbose),null;let J="regenerateUntrustedCerts"in w,U=w.regenerateUntrustedCerts,W=J?U!==!1:!0;F("ssl",`Trust check: hasFlag=${J}, flagValue=${U}, shouldCheckTrust=${W}`,w.verbose);let Q=$.basePath||K0(l1(),".stacks","ssl"),B=CG(Q);if(!(W?await LG(B.caCertPath,w):!0))return F("ssl","Root CA exists but is not trusted, will regenerate",w.verbose),null;let[z,G,K]=await Promise.all([G0.readFile($.keyPath,"utf8"),G0.readFile($.certPath,"utf8"),X&&$.caCertPath?G0.readFile($.caCertPath,"utf8"):Promise.resolve(void 0)]);if(K&&!K.includes("-----BEGIN CERTIFICATE-----"))return F("ssl","Invalid root CA certificate content, will regenerate",w.verbose),null;if(l$(w))try{let{X509Certificate:E}=await import("node:crypto"),N=new E(G).subjectAltName||"",R=w.proxies.map((O)=>O.to).filter((O)=>!N.includes(`DNS:${O}`));if(R.length>0)return F("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,w.verbose),null}catch(E){F("ssl",`Could not verify cert SANs: ${E}`,w.verbose)}return F("ssl","Successfully loaded existing certificates",w.verbose),L$={key:z,cert:G,ca:K},L$}catch(Y){return F("ssl",`Error checking existing certificates: ${Y}`,w.verbose),null}}function PY(w,$){let Y=M8(w);F("ssl",`Primary domain: ${Y}`,$);let A=yG(w),X=K0(l1(),".stacks","ssl");if(typeof w.https==="object"){let J=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:X,U={domain:Y,hostCertCN:Y,basePath:J,caCertPath:w.https.caCertPath||A.caCertPath,certPath:w.https.certPath||A.certPath,keyPath:w.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:w.https.commonName||Y,organizationName:w.https.organizationName||"Local Development",countryName:w.https.countryName||"US",stateName:w.https.stateName||"California",localityName:w.https.localityName||"Playa Vista",validityDays:w.https.validityDays||825,verbose:$||!1,subjectAltNames:Array.from(IG(w)).map((W)=>({type:2,value:W}))};if(EW(w.https.rootCA))U.rootCA=w.https.rootCA;return U}return{domain:Y,hostCertCN:Y,basePath:X,...A,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:Y,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:$||!1,subjectAltNames:Array.from(IG(w)).map((J)=>({type:2,value:J}))}}async function OG(w,$){let Y=yG({to:w,verbose:$}),A=[Y.caCertPath,Y.certPath,Y.keyPath];F("certificates","Attempting to clean up relating certificates",$),await Promise.all(A.map((X)=>TW(X,$)))}async function LG(w,$){try{if(F("ssl",`Checking if certificate is trusted: ${w}`,$?.verbose),O$.platform==="darwin"){if($?.serverName)return IW(w,$.serverName,{verbose:$?.verbose});return C8(w,{verbose:$?.verbose})}else if(O$.platform==="win32")try{let Y=hQ(w)||"";if(!Y)return F("ssl","Could not extract certificate subject",$?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(CW(A).toString().includes(Y))return F("ssl","Certificate found in trusted root store",$?.verbose),!0;return F("ssl","Certificate not found in trusted root store",$?.verbose),!1}catch(Y){return F("ssl",`Error checking certificate trust on Windows: ${Y}`,$?.verbose),!1}else if(O$.platform==="linux")try{let Y=m$(w);if(!Y)return F("ssl","Could not extract certificate fingerprint",$?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of A){let J;try{J=await G0.readdir(X)}catch{continue}for(let U of J){let W=m$(VG.join(X,U));if(W&&W===Y)return F("ssl",`Certificate fingerprint found in ${X}`,$?.verbose),!0}}return F("ssl","Certificate not found in system trust stores",$?.verbose),!1}catch(Y){return F("ssl",`Error checking certificate trust on Linux: ${Y}`,$?.verbose),!1}return F("ssl",`Platform ${O$.platform} not supported for certificate trust check`,$?.verbose),!1}catch(Y){return F("ssl",`Error checking if certificate is trusted: ${Y}`,$?.verbose),!1}}var L$=null,y8,YH="rpx-root-ca.crt",AH="rpx-root-ca.key";var L8=t(()=>{mX();nw();kQ();VW();X0();VW();dX();dX();y8=K0(l1(),".stacks","ssl","rpx.localhost.crt")});function JH(w){return{enabled:w?.enabled??!1,path:w?.path??"/",interval:w?.interval??1e4,timeout:w?.timeout??2000,healthyThreshold:w?.healthyThreshold??2,unhealthyThreshold:w?.unhealthyThreshold??3}}function UH(w){return(Array.isArray(w)?w:[w]).map((Y)=>{let A=typeof Y==="string"?{url:Y}:Y;return{url:A.url,weight:A.weight&&A.weight>0?A.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function _W(w){return(Array.isArray(w)?w:[w]).map((Y)=>typeof Y==="string"?Y:Y.url)}function _$(w){if(!w)return"localhost:5173";let $=Array.isArray(w)?w[0]:w;if(!$)return"localhost:5173";return typeof $==="string"?$:$.url}function p1(w,$){return{upstreams:UH(w),strategy:$?.strategy??"round-robin",healthCheck:JH($?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function QH(w){let $=w.upstreams.filter((Y)=>Y.healthy);if($.length===0&&w.upstreams.length===1)return w.upstreams;return $}function WH(w,$){let Y=w.cursor%$.length;return w.cursor=(w.cursor+1)%$.length,$[Y]}function BH(w,$){if(w.wrrCurrentWeights.length!==$.length)w.wrrCurrentWeights=$.map(()=>0);let Y=$.reduce((X,J)=>X+J.weight,0),A=0;for(let X=0;X<$.length;X++)if(w.wrrCurrentWeights[X]+=$[X].weight,w.wrrCurrentWeights[X]>w.wrrCurrentWeights[A])A=X;return w.wrrCurrentWeights[A]-=Y,$[A]}function jH(w){let $=w[0];for(let Y=1;Y<w.length;Y++)if(w[Y].activeConnections<$.activeConnections)$=w[Y];return $}function _G(w){let $=QH(w);if($.length===0)return;if($.length===1)return $[0];switch(w.strategy){case"weighted-round-robin":return BH(w,$);case"least-connections":return jH($);case"round-robin":default:return WH(w,$)}}function _8(w,$){if($.consecutiveFailures=0,$.consecutiveSuccesses+=1,!$.healthy&&$.consecutiveSuccesses>=w.healthCheck.healthyThreshold)$.healthy=!0}function bY(w,$){if($.consecutiveSuccesses=0,$.consecutiveFailures+=1,$.healthy&&$.consecutiveFailures>=w.healthCheck.unhealthyThreshold)$.healthy=!1}function zH(w){let $=w.lastIndexOf(":");if($===-1)return{hostname:w,port:80};let Y=Number(w.slice($+1));return{hostname:w.slice(0,$),port:Number.isFinite(Y)?Y:80}}async function GH(w,$){let{hostname:Y,port:A}=zH($.url),X=new AbortController,J=setTimeout(()=>X.abort(),w.healthCheck.timeout);try{(await fetch(`http://${Y}:${A}${w.healthCheck.path}`,{signal:X.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),_8(w,$)}catch{bY(w,$)}finally{clearTimeout(J)}}function r1(w){if(!w.healthCheck.enabled||w.healthCheckTimer||w.upstreams.length<2)return;let $=setInterval(()=>{for(let Y of w.upstreams)GH(w,Y)},w.healthCheck.interval);$.unref?.(),w.healthCheckTimer=$}function n$(w){if(w.healthCheckTimer)clearInterval(w.healthCheckTimer),w.healthCheckTimer=null}import{createHash as ZG,timingSafeEqual as SG}from"node:crypto";import{readFileSync as KH}from"node:fs";function uY(w,$){let Y=Buffer.from(w,"utf8"),A=Buffer.from($,"utf8");if(Y.length!==A.length)return SG(Y,Y),!1;return SG(Y,A)}function qH(w,$){let Y=(G)=>ZG("md5").update(G).digest(),A=Buffer.from(w,"utf8"),X=Buffer.from($,"utf8"),J=Y(Buffer.concat([A,X,A])),U=[A,Buffer.from("$apr1$","utf8"),X];for(let G=A.length;G>0;G-=16)U.push(J.subarray(0,Math.min(G,16)));for(let G=A.length;G>0;G>>=1)U.push(G&1?Buffer.from([0]):A.subarray(0,1));let W=Y(Buffer.concat(U));for(let G=0;G<1000;G++){let K=[];if(K.push(G&1?A:W.subarray(0,16)),G%3)K.push(X);if(G%7)K.push(A);K.push(G&1?W.subarray(0,16):A),W=Y(Buffer.concat(K))}let Q="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",B=(G,K)=>{let E="",q=G;for(let N=0;N<K;N++)E+=Q[q&63],q>>=6;return E},j=W,z="";return z+=B(j[0]<<16|j[6]<<8|j[12],4),z+=B(j[1]<<16|j[7]<<8|j[13],4),z+=B(j[2]<<16|j[8]<<8|j[14],4),z+=B(j[3]<<16|j[9]<<8|j[15],4),z+=B(j[4]<<16|j[10]<<8|j[5],4),z+=B(j[11],2),`$apr1$${$}$${z}`}function NH(w,$){if(/^\$2[aby]?\$/.test($))try{return Bun.password.verifySync(w,$)}catch{return!1}if($.startsWith("$apr1$")){let A=$.split("$")[2]??"";return uY(qH(w,A),$)}if($.startsWith("{SHA}")){let Y=ZG("sha1").update(w,"utf8").digest("base64");return uY(`{SHA}${Y}`,$)}return uY(w,$)}function EH(w){let $=new Map;for(let Y of w.split(`
222
222
  `)){let A=Y.trim();if(!A||A.startsWith("#"))continue;let X=A.indexOf(":");if(X<=0)continue;$.set(A.slice(0,X),A.slice(X+1))}return $}function t1(w){if(!w)return;let $=(w.realm??"").trim()||"Restricted",Y=[];if(w.username)Y.push({username:w.username,password:w.password??""});for(let J of w.users??[])if(J?.username)Y.push({username:J.username,password:J.password??""});let A;if(w.htpasswdFile)try{A=EH(KH(w.htpasswdFile,"utf8"))}catch{A=void 0}if(Y.length===0&&(!A||A.size===0))return;return{realm:$,verify:(J,U)=>{let W=!1;for(let Q of Y)if(uY(J,Q.username)&&uY(U,Q.password))W=!0;if(A){let Q=A.get(J);if(Q&&NH(U,Q))W=!0}return W}}}function kG(w,$,Y){if($.startsWith(FH))return;let A=w.headers.get("authorization")??"",X=A.indexOf(" "),J=X===-1?A:A.slice(0,X),U=X===-1?"":A.slice(X+1).trim();if(J.toLowerCase()==="basic"&&U){let Q="";try{Q=Buffer.from(U,"base64").toString("utf8")}catch{Q=""}let B=Q.indexOf(":");if(B>=0&&Y.verify(Q.slice(0,B),Q.slice(B+1)))return}let W=Y.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${W}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var FH="/.well-known/acme-challenge/";var cY=()=>{};function HH(w){return TH.has(w.toUpperCase())}function RH(){let w=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(w)&&w>0?w:30000}function MH(w){let $=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite($)&&$>0?$:w*8}function IH(){let w=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(w)&&w>0?w:0}function VH(){let w=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(w)&&w>0?w:0}function CH(){let w=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(w)&&w>0?w:256}class bG{socket=null;buf=new Uint8Array(yH);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(w){let $=this.socket,Y=$.write(w);while(Y<w.length){if(this.closed)throw S8;await new Promise((A)=>{this.drainWaiter=A}),Y+=$.write(w.subarray(Y))}}wakeDrain(){let w=this.drainWaiter;if(w)this.drainWaiter=null,w()}push(w){if(this.bodyQueue){let $=w.length<=this.bodyRemaining?w.length:this.bodyRemaining;if($>0)this.bodyQueue.push(w.slice(0,$)),this.queuedBytes+=$;if(this.bodyRemaining-=$,$<w.length)this.appendToBuf(w.subarray($));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(w),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>OH)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=LH)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(w){let $=this.len+w.length;if($>this.buf.length){let Y=new Uint8Array(Math.max(this.buf.length*2,$));Y.set(this.buf.subarray(0,this.len)),this.buf=Y}this.buf.set(w,this.len),this.len=$}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let w=this.waiter;if(w)this.waiter=null,w()}waitForData(w){if(this.len>w||this.closed)return Promise.resolve();return new Promise(($)=>{this.waiter=$})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((w)=>{this.waiter=w})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class uG{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=RH();maxWaiters;checkoutIdleMs=IH();inUse=new Set;constructor(w,$,Y,A=""){this.host=w;this.port=$;this.maxTotal=Y;this.key=A;this.maxWaiters=MH(Y)}trackCheckout(w){if(w.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(w),this.ensureSweeper()}dial(){let w=new bG;return fH({hostname:this.host,port:this.port,socket:{data:($,Y)=>w.push(Y),drain:()=>w.wakeDrain(),close:()=>w.markClosed(),end:()=>w.markClosed(),error:()=>w.markClosed(),connectError:()=>w.markClosed(),timeout:()=>w.markTimedOut()}}).then(($)=>{let Y=$;Y.setNoDelay?.(!0);let A=VH();if(A>0)Y.timeout?.(A);return w.socket=$,w})}acquireIdleSync(){while(this.idle.length){let w=this.idle.pop();if(!w.closed)return w.socket?.ref(),w.pos=0,w.len=0,this.trackCheckout(w),w;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw p$;let w=await this.waitForSlot();if(w===p$)throw p$;if(w)return w.pos=0,w.len=0,this.trackCheckout(w),w}this.open++;try{let w=await this.dial();return this.trackCheckout(w),w}catch(w){throw this.open--,this.wakeWaiter(),w}}waitForSlot(){return new Promise((w)=>{let $=!1,Y=(J)=>{if($)return;$=!0,clearTimeout(X),w(J)},A=(J)=>Y(J),X=setTimeout(()=>{let J=this.waiters.indexOf(A);if(J!==-1)this.waiters.splice(J,1);Y(p$)},this.queueWaitMs);X.unref?.(),this.waiters.push(A)})}release(w){if(this.inUse.delete(w),w.closed){this.open--,this.wakeWaiter();return}w.clearStreaming(),w.compact(),w.fresh=!1;let $=this.waiters.shift();if($){w.socket?.ref(),this.trackCheckout(w),$(w);return}w.idleSince=Date.now(),w.socket?.unref(),this.idle.push(w),this.ensureSweeper()}destroy(w){this.inUse.delete(w),w.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let w=this.waiters.shift();if(w)w(null)}ensureSweeper(){if(this.sweeper)return;let w=this.checkoutIdleMs>0?Math.min(SW,this.checkoutIdleMs):SW;this.sweeper=setInterval(()=>this.sweep(),w),this.sweeper.unref?.()}sweep(){let w=Date.now(),$=w-SW;if(this.idle.length){let Y=[];for(let A of this.idle)if(A.closed||A.idleSince<=$)A.destroy(),this.open--;else Y.push(A);this.idle=Y}if(this.checkoutIdleMs>0&&this.inUse.size){let Y=w-this.checkoutIdleMs;for(let A of this.inUse)if(!A.closed&&A.lastActivityAt>0&&A.lastActivityAt<=Y)A.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&Z8.get(this.key)===this)Z8.delete(this.key)}}}function hH(w,$){let Y=Z8.get(w);if(!Y){let A=w.lastIndexOf(":"),X=A===-1?w:w.slice(0,A),J=A===-1?80:Number(w.slice(A+1));Y=new uG(X,J,$,w),Z8.set(w,Y)}return Y}function hG(w,$,Y){for(let A=Y+3;A<$;A++)if(w[A]===10&&w[A-1]===13&&w[A-2]===10&&w[A-3]===13)return A-3;return-1}function DH(w,$,Y){let A=PG.decode(w.subarray($,Y)),X=A.indexOf(`\r
223
223
  `),J=X===-1?A:A.slice(0,X),U=J.indexOf(" "),W=Number.parseInt(J.slice(U+1,U+5),10),Q=J.startsWith("HTTP/1.0"),B=[],j=-1,z=!1,G=Q,K=!1,E=!1,q=X===-1?A.length:X+2;while(q<A.length){let N=A.indexOf(`\r
224
- `,q);if(N===-1)N=A.length;let f=A.slice(q,N);if(q=N+2,f==="")continue;let R=f.indexOf(":");if(R===-1)continue;let O=f.slice(0,R),y=f.slice(R+1).trim(),T=O.charCodeAt(0)|32;if(T===99||T===116||T===107){let M=O.toLowerCase();if(M==="content-length"){let V=/^\d+$/.test(y)?Number(y):Number.NaN;if(!Number.isSafeInteger(V)||j>=0&&j!==V)E=!0;else j=V;continue}if(M==="transfer-encoding"){if(y.toLowerCase().includes("chunked"))z=!0;continue}if(M==="connection"){let V=y.toLowerCase();if(V.includes("close"))G=!0;if(V.includes("keep-alive"))K=!0;continue}if(M==="keep-alive")continue}B.push([O,y])}if(Q&&K)G=!1;if(z&&j>=0)j=-1;return{status:W,headerEnd:Y,headers:B,contentLength:j,chunked:z,closeConn:G,malformed:E}}function xH(w,$){return $||w===204||w===304}async function cG(w){let{hostPort:$,method:Y,path:A,reqHeaders:X,forwardedHost:J,originOverride:U,body:W}=w,Q=Y==="HEAD";if(X.get("expect")||X.get("upgrade"))throw vY;let B=null;if(W){let K=X.get("content-length"),E=K?Number.parseInt(K,10):Number.NaN;if(Number.isNaN(E)||E>DG)throw vY;if(B=await mH(W),B===null)throw vY}let j=iH(Y,A,X,$,J,U,B),z=j;if(B&&B.length)z=new Uint8Array(j.length+B.length),z.set(j),z.set(B,j.length);let G=hH($,w.maxPerHost??CH());for(let K=0;;K++){if(K>0)await new Promise((q)=>{setTimeout(q,K)});let E;try{E=G.acquireIdleSync()??await G.acquireOrDial()}catch(q){if(q!==p$&&K<4)continue;throw q}try{let q=E.socket.write(z);if(q<z.length)await E.writeAll(z.subarray(q));return await bH(G,E,Q)}catch(q){let N=q===S8&&K<4&&(E.fresh||HH(Y));if(G.destroy(E),N)continue;if(q===S8)throw Error("upstream closed connection");throw q}}}async function PH(w){let $=hG(w.buf,w.len,w.pos);while($===-1){if(w.closed){if(w.timedOut)throw ZW;if(w.len===w.pos)throw S8;throw Error("upstream closed mid-header")}if(w.len-w.pos>xG)throw Error("upstream header block too large");await w.waitForData(w.len),$=hG(w.buf,w.len,w.pos)}return $}async function bH(w,$,Y){let A;for(;;){let J=await PH($);if(A=DH($.buf,$.pos,J),$.pos=J+4,A.status>=100&&A.status<200)continue;break}if(A.malformed)throw w.destroy($),Error("upstream sent malformed response framing");let X=A.headers;if(xH(A.status,Y))return vG(w,$,A.closeConn),new Response(null,{status:A.status,headers:X});if(A.chunked)return new Response(vH(w,$,A.closeConn),{status:A.status,headers:X});if(A.contentLength>=0){if($.len-$.pos>=A.contentLength){let U=$.pos+A.contentLength,W=$.len>U,Q=null;if(A.contentLength>=_H)Q=$.buf.subarray($.pos,U),$.buf=new Uint8Array(SH);else if(A.contentLength>0)Q=$.buf.slice($.pos,U);if($.pos=0,$.len=0,A.closeConn||W)w.destroy($);else w.release($);return new Response(Q,{status:A.status,headers:X})}return new Response(uH(w,$,A.contentLength,A.closeConn),{status:A.status,headers:X})}return new Response(cH($),{status:A.status,headers:X})}function vG(w,$,Y){if(Y||$.pos!==$.len)w.destroy($);else w.release($)}function uH(w,$,Y,A){let X=$.len-$.pos,J=X>0?$.buf.slice($.pos,$.len):null;$.pos=0,$.len=0,$.bodyQueue=[],$.bodyRemaining=Y-X,$.queuedBytes=0,$.streamingBody=!0;let U=(W)=>{if($.bodyQueue=null,A||$.len>0)w.destroy($);else w.release($);W.close()};return new ReadableStream({start(W){if(J)W.enqueue(J);if($.bodyRemaining===0&&$.bodyQueue.length===0)U(W)},async pull(W){for(;;){let Q=$.bodyQueue;if(Q&&Q.length>0){let B=Q.shift();if($.queuedBytes-=B.length,$.resumeIfDrained(),W.enqueue(B),$.bodyRemaining===0&&Q.length===0)U(W);return}if($.bodyRemaining===0){if($.bodyQueue)U(W);return}if($.closed){$.bodyQueue=null,w.destroy($),W.error(Error("upstream closed mid-body"));return}await $.waitForBody()}},cancel(){$.bodyQueue=null,w.destroy($)}})}function cH(w){return w.streamingBody=!0,new ReadableStream({async pull($){for(;;){if(w.len>w.pos){$.enqueue(w.buf.slice(w.pos,w.len)),w.pos=w.len,w.resumeIfDrained();return}if(w.closed){w.destroy(),$.close();return}await w.waitForData(w.len)}},cancel(){w.destroy()}})}function vH(w,$,Y){$.streamingBody=!0;let A=0,X=!1;async function J(){for(;;){for(let U=$.pos;U+1<$.len;U++)if($.buf[U]===13&&$.buf[U+1]===10){let W=PG.decode($.buf.subarray($.pos,U));return $.pos=U+2,W}if($.closed)throw Error("upstream closed mid-chunk-header");if($.len-$.pos>xG)throw Error("upstream chunk header too large");await $.waitForData($.len)}}return new ReadableStream({async pull(U){for(;;){if(A>0){if($.len===$.pos){if($.closed){w.destroy($),U.error(Error("upstream closed mid-chunk"));return}await $.waitForData($.len);continue}let j=Math.min(A,$.len-$.pos);if(U.enqueue($.buf.slice($.pos,$.pos+j)),$.pos+=j,A-=j,$.resumeIfDrained(),A===0)X=!0;return}if(X)await J(),X=!1;let W=await J(),Q=W.indexOf(";"),B=Number.parseInt(Q===-1?W:W.slice(0,Q),16);if(!Number.isInteger(B)||B<0){w.destroy($),U.error(Error("upstream sent malformed chunk size"));return}if(B===0){for(;;)if(await J()==="")break;vG(w,$,Y),U.close();return}A=B}},cancel(){w.destroy($)}})}function iH(w,$,Y,A,X,J,U){let W=`${w} ${$} HTTP/1.1\r
224
+ `,q);if(N===-1)N=A.length;let f=A.slice(q,N);if(q=N+2,f==="")continue;let R=f.indexOf(":");if(R===-1)continue;let O=f.slice(0,R),y=f.slice(R+1).trim(),T=O.charCodeAt(0)|32;if(T===99||T===116||T===107){let M=O.toLowerCase();if(M==="content-length"){let V=/^\d+$/.test(y)?Number(y):Number.NaN;if(!Number.isSafeInteger(V)||j>=0&&j!==V)E=!0;else j=V;continue}if(M==="transfer-encoding"){if(y.toLowerCase().includes("chunked"))z=!0;continue}if(M==="connection"){let V=y.toLowerCase();if(V.includes("close"))G=!0;if(V.includes("keep-alive"))K=!0;continue}if(M==="keep-alive")continue}B.push([O,y])}if(Q&&K)G=!1;if(z&&j>=0)j=-1;return{status:W,headerEnd:Y,headers:B,contentLength:j,chunked:z,closeConn:G,malformed:E}}function xH(w,$){return $||w===204||w===304}async function cG(w){let{hostPort:$,method:Y,path:A,reqHeaders:X,forwardedHost:J,originOverride:U,body:W}=w,Q=Y==="HEAD";if(X.get("expect")||X.get("upgrade"))throw vY;let B=null;if(W){let K=X.get("content-length"),E=K?Number.parseInt(K,10):Number.NaN;if(Number.isNaN(E)||E>DG)throw vY;if(B=await mH(W),B===null)throw vY}let j=iH(Y,A,X,$,J,U,B),z=j;if(B&&B.length)z=new Uint8Array(j.length+B.length),z.set(j),z.set(B,j.length);let G=hH($,w.maxPerHost??CH());for(let K=0;;K++){if(K>0)await new Promise((q)=>{setTimeout(q,K)});let E;try{E=G.acquireIdleSync()??await G.acquireOrDial()}catch(q){if(q!==p$&&K<4)continue;throw q}try{let q=E.socket.write(z);if(q<z.length)await E.writeAll(z.subarray(q));return await bH(G,E,Q)}catch(q){let N=q===S8&&K<4&&(E.fresh||HH(Y));if(G.destroy(E),N)continue;if(q===S8)throw Error("upstream closed connection");throw q}}}async function PH(w){let $=hG(w.buf,w.len,w.pos);while($===-1){if(w.closed){if(w.timedOut)throw ZW;if(w.len===w.pos)throw S8;throw Error("upstream closed mid-header")}if(w.len-w.pos>xG)throw Error("upstream header block too large");await w.waitForData(w.len),$=hG(w.buf,w.len,w.pos)}return $}async function bH(w,$,Y){let A;for(;;){let J=await PH($);if(A=DH($.buf,$.pos,J),$.pos=J+4,A.status>=100&&A.status<200)continue;break}if(A.malformed)throw w.destroy($),Error("upstream sent malformed response framing");let X=A.headers;if(xH(A.status,Y))return vG(w,$,A.closeConn),new Response(null,{status:A.status,headers:X});if(A.chunked)return new Response(vH(w,$,A.closeConn),{status:A.status,headers:X});if(A.contentLength>=0){if($.len-$.pos>=A.contentLength){let U=$.pos+A.contentLength,W=$.len>U,Q=null;if(A.contentLength>=_H)Q=$.buf.subarray($.pos,U),$.buf=new Uint8Array(SH);else if(A.contentLength>0)Q=$.buf.slice($.pos,U);if($.pos=0,$.len=0,A.closeConn||W)w.destroy($);else w.release($);return new Response(Q,{status:A.status,headers:X})}return new Response(uH(w,$,A.contentLength,A.closeConn),{status:A.status,headers:X})}return new Response(cH($),{status:A.status,headers:X})}function vG(w,$,Y){if(Y||$.pos!==$.len)w.destroy($);else w.release($)}function uH(w,$,Y,A){let X=$.len-$.pos,J=X>0?$.buf.slice($.pos,$.len):null;$.pos=0,$.len=0,$.bodyQueue=[],$.bodyRemaining=Y-X,$.queuedBytes=0,$.streamingBody=!0;let U=(W)=>{if($.bodyQueue=null,A||$.len>0)w.destroy($);else w.release($);W.close()};return new ReadableStream({start(W){if(J)W.enqueue(J);if($.bodyRemaining===0&&$.bodyQueue.length===0)U(W)},async pull(W){for(;;){let Q=$.bodyQueue;if(Q&&Q.length>0){let B=Q.shift();if($.queuedBytes-=B.length,$.resumeIfDrained(),W.enqueue(B),$.bodyRemaining===0&&Q.length===0)U(W);return}if($.bodyRemaining===0){if($.bodyQueue)U(W);return}if($.closed){$.bodyQueue=null,w.destroy($),W.error(Error("upstream closed mid-body"));return}await $.waitForBody()}},cancel(){$.bodyQueue=null,w.destroy($)}})}function cH(w){return w.streamingBody=!0,new ReadableStream({async pull($){for(;;){if(w.len>w.pos){$.enqueue(w.buf.slice(w.pos,w.len)),w.pos=w.len,w.resumeIfDrained();return}if(w.closed){w.destroy(),$.close();return}await w.waitForData(w.len)}},cancel(){w.destroy()}})}function vH(w,$,Y){$.streamingBody=!0;let A=0,X=!1,J=!1;async function U(){for(;;){for(let W=$.pos;W+1<$.len;W++)if($.buf[W]===13&&$.buf[W+1]===10){let Q=PG.decode($.buf.subarray($.pos,W));return $.pos=W+2,Q}if($.closed)throw Error("upstream closed mid-chunk-header");if($.len-$.pos>xG)throw Error("upstream chunk header too large");await $.waitForData($.len)}}return new ReadableStream({async pull(W){try{for(;;){if(A>0){if($.len===$.pos){if($.closed){w.destroy($),W.error(Error("upstream closed mid-chunk"));return}await $.waitForData($.len);continue}let z=Math.min(A,$.len-$.pos);if(W.enqueue($.buf.slice($.pos,$.pos+z)),$.pos+=z,A-=z,$.resumeIfDrained(),A===0)X=!0;return}if(X)await U(),X=!1;let Q=await U(),B=Q.indexOf(";"),j=Number.parseInt(B===-1?Q:Q.slice(0,B),16);if(!Number.isInteger(j)||j<0){w.destroy($),W.error(Error("upstream sent malformed chunk size"));return}if(j===0){for(;;)if(await U()==="")break;vG(w,$,Y),W.close();return}A=j}}catch(Q){if(w.destroy($),!J)W.error(Q)}},cancel(){J=!0,w.destroy($)}})}function iH(w,$,Y,A,X,J,U){let W=`${w} ${$} HTTP/1.1\r
225
225
  host: ${A}\r
226
226
  x-forwarded-for: 127.0.0.1\r
227
227
  x-forwarded-proto: https\r