@stacksjs/rpx 0.11.21 → 0.11.22

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.
@@ -1 +1 @@
1
- import{Ha as a,Ia as b,Ja as c,Ka as d,La as e,Ma as f,Na as g,Oa as h,Pa as i,Qa as j,Ra as k,Sa as l,Ta as m,Ua as n,Va as o}from"./chunk-qs36t2rf.js";import"./chunk-cqkz06bg.js";export{m as tearDownDevelopmentDns,l as syncDevelopmentDnsFromRegistry,d as stopDnsServer,c as startDnsServer,i as setupResolver,k as setupDevelopmentDns,g as resolverFilePath,n as removeResolver,j as removeLegacyTldResolvers,o as reconcileStaleDevelopmentDns,f as isRpxDevelopmentDnsAnswering,e as isDnsServerRunning,h as contentLooksLikeRpxResolver,b as RPX_RESOLVER_MARKER,a as DNS_PORT};
1
+ import{Ha as a,Ia as b,Ja as c,Ka as d,La as e,Ma as f,Na as g,Oa as h,Pa as i,Qa as j,Ra as k,Sa as l,Ta as m,Ua as n,Va as o}from"./chunk-cd843mzv.js";import"./chunk-cqkz06bg.js";export{m as tearDownDevelopmentDns,l as syncDevelopmentDnsFromRegistry,d as stopDnsServer,c as startDnsServer,i as setupResolver,k as setupDevelopmentDns,g as resolverFilePath,n as removeResolver,j as removeLegacyTldResolvers,o as reconcileStaleDevelopmentDns,f as isRpxDevelopmentDnsAnswering,e as isDnsServerRunning,h as contentLooksLikeRpxResolver,b as RPX_RESOLVER_MARKER,a as DNS_PORT};
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{$ as qR,$a as vD,A as US,Aa as QD,B as U,Ba as VD,C as o,Ca as XD,D as FR,Da as ZD,E as PS,Ea as WD,F as OS,Fa as zD,G as RR,Ga as ID,H as LS,Ha as FD,I as MR,Ia as MD,J as cS,Ja as xD,K as xR,Ka as TD,L as mS,La as jD,M as vS,N as hS,Na as HD,O as uS,Oa as kD,P as bS,Pa as wD,Q as TR,Qa as ED,R as jR,Ra as qD,S as HR,Sa as CD,T as GR,Ta as yD,U as lS,Ua as fD,V as kR,Va as UD,W as aS,Wa as PD,X as wR,Xa as OD,Y as pS,Ya as LD,Z as ER,Za as cD,_ as dS,_a as mD,a as G,aa as gS,ab as hD,b as s,ba as iS,bb as uD,c as $S,ca as nS,cb as KR,d as GS,da as rS,db as bD,e as JS,ea as tS,eb as lD,f as QS,fa as sS,g as VS,ga as eS,h as XS,ha as oS,i as ZS,ia as RD,j as WS,ja as SD,k as zS,ka as C,l as IS,la as DD,m as FS,ma as CR,n as MS,na as _D,o as xS,oa as DR,p as TS,pa as _R,q as jS,qa as ND,r as HS,ra as NR,s as kS,sa as BR,t as wS,ta as BD,u as ES,ua as KD,v as qS,va as AD,w as CS,wa as YD,x as yS,xa as $D,y as fS,ya as GD,z as e,za as JD}from"./chunk-qs36t2rf.js";import{fb as zR,gb as m,hb as mR,ib as QN,jb as _,kb as lR,lb as VN,mb as E,nb as XN,ob as ZN,pb as WN,qb as zN,rb as IN,sb as FN,tb as MN,ub as xN,vb as TN}from"./chunk-cqkz06bg.js";import{execSync as SS}from"node:child_process";import*as SR from"node:http";import*as aR from"node:net";import*as z from"node:process";var l=(S,R)=>(D)=>`\x1B[${S}m${D}\x1B[${R}m`,H={bold:l(1,22),dim:l(2,22),green:l(32,39),cyan:l(36,39)};import*as PR from"node:fs";import*as OR from"node:path";import*as k from"node:process";function LR(S,R){let B=(R&&R!=="/"?`${S}${R}`:S).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return B.length>0?B:"rpx"}async function a(S){if(S.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let R=S.verbose??!1,D=S.registryDir,B=new Set,K=S.proxies.map((X)=>{let W=X.id??LR(X.to,X.path);if(!_R(W))throw Error(`invalid registry id "${W}" derived from to="${X.to}"`);if(B.has(W))throw Error(`duplicate registry id "${W}" — set an explicit \`id\` on one of the proxies`);return B.add(W),{...X,id:W}}),N=new Date().toISOString();for(let X of K)await NR({id:X.id,from:X.from,to:X.to,path:X.path,pid:S.persistent?void 0:k.pid,cwd:k.cwd(),createdAt:N,cleanUrls:X.cleanUrls,changeOrigin:X.changeOrigin,pathRewrites:X.pathRewrites,static:X.static},D,R);let A=await KR({rpxDir:S.rpxDir,verbose:R,spawnCommand:S.spawnCommand,startupTimeoutMs:S.startupTimeoutMs,spawnEnv:S.spawnEnv});for(let X of K){let W=X.static?`static ${typeof X.static==="string"?X.static:X.static.dir}`:X.from;G.success(`https://${X.to} → ${W}`)}if(G.info(`(via rpx daemon pid=${A.pid}; \`rpx daemon:status\` to inspect)`),S.detached)return;let V=!1,Y=D??DR(),J=K.map((X)=>X.id),Q=async()=>{if(V)return;V=!0;for(let X of J)await BR(X,D,R).catch((W)=>{_("runner",`removeEntry(${X}) failed: ${W}`,R)})},Z=(X)=>{_("runner",`received ${X}, unregistering ${J.length} entries`,R),Q().finally(()=>k.exit(0))};k.once("SIGINT",Z),k.once("SIGTERM",Z),k.once("exit",()=>{if(V)return;for(let X of J)try{PR.unlinkSync(OR.join(Y,`${X}.json`))}catch{}}),await new Promise(()=>{})}import{exec as nR}from"node:child_process";import q from"node:fs";import vR from"node:os";import YR from"node:path";import*as v from"node:process";import{promisify as rR}from"node:util";var c=rR(nR);function cR(S){let R=S.trim().toLowerCase();return R==="localhost"||R.endsWith(".localhost")||R.endsWith(".localhost.")}var j=v.platform==="win32"?YR.join(v.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",AR=!1;async function p(S){if(v.platform==="win32")throw Error("Administrator privileges required on Windows");if(mR()){let{stdout:B}=await c(S);return B}let R=m(),D=S.replace(/'/g,"'\\''");try{if(R){let{stdout:B}=await c(`echo '${R}' | sudo -S sh -c '${D}' 2>/dev/null`);return AR=!0,B}if(AR)try{let{stdout:B}=await c(`sudo -n sh -c '${D}'`);return B}catch(B){_("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:B}=await c(`sudo -n sh -c '${D}'`);return AR=!0,B}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(B){throw Error(`Failed to execute sudo command: ${B.message}`)}}async function y(S,R){let D=S.filter((K)=>!cR(K)),B=S.filter((K)=>cR(K));if(B.length>0)_("hosts",`Skipping /etc/hosts for loopback dev names: ${B.join(", ")}`,R);if(D.length===0)return;_("hosts",`Adding hosts: ${D.join(", ")}`,R),_("hosts",`Using hosts file at: ${j}`,R);try{let K;try{K=await q.promises.readFile(j,"utf-8")}catch{_("hosts","Reading hosts file requires elevated permissions, using sudo",R);try{K=await p(`cat "${j}"`)}catch(Y){throw console.log(" Could not read hosts file — skipping hosts setup"),_("hosts",`sudo read also failed: ${Y}`,R),Error(`Cannot read hosts file: ${Y}`)}}let N=D.filter((Y)=>{let J=`127.0.0.1 ${Y}`,Q=`::1 ${Y}`;return!K.includes(J)&&!K.includes(Q)});if(N.length===0){_("hosts","All hosts already exist in hosts file",R);return}let A=N.map((Y)=>`
1
+ import{$ as qR,$a as vD,A as US,Aa as QD,B as U,Ba as VD,C as o,Ca as XD,D as FR,Da as ZD,E as PS,Ea as WD,F as OS,Fa as zD,G as RR,Ga as ID,H as LS,Ha as FD,I as MR,Ia as MD,J as cS,Ja as xD,K as xR,Ka as TD,L as mS,La as jD,M as vS,N as hS,Na as HD,O as uS,Oa as kD,P as bS,Pa as wD,Q as TR,Qa as ED,R as jR,Ra as qD,S as HR,Sa as CD,T as GR,Ta as yD,U as lS,Ua as fD,V as kR,Va as UD,W as aS,Wa as PD,X as wR,Xa as OD,Y as pS,Ya as LD,Z as ER,Za as cD,_ as dS,_a as mD,a as G,aa as gS,ab as hD,b as s,ba as iS,bb as uD,c as $S,ca as nS,cb as KR,d as GS,da as rS,db as bD,e as JS,ea as tS,eb as lD,f as QS,fa as sS,g as VS,ga as eS,h as XS,ha as oS,i as ZS,ia as RD,j as WS,ja as SD,k as zS,ka as C,l as IS,la as DD,m as FS,ma as CR,n as MS,na as _D,o as xS,oa as DR,p as TS,pa as _R,q as jS,qa as ND,r as HS,ra as NR,s as kS,sa as BR,t as wS,ta as BD,u as ES,ua as KD,v as qS,va as AD,w as CS,wa as YD,x as yS,xa as $D,y as fS,ya as GD,z as e,za as JD}from"./chunk-cd843mzv.js";import{fb as zR,gb as m,hb as mR,ib as QN,jb as _,kb as lR,lb as VN,mb as E,nb as XN,ob as ZN,pb as WN,qb as zN,rb as IN,sb as FN,tb as MN,ub as xN,vb as TN}from"./chunk-cqkz06bg.js";import{execSync as SS}from"node:child_process";import*as SR from"node:http";import*as aR from"node:net";import*as z from"node:process";var l=(S,R)=>(D)=>`\x1B[${S}m${D}\x1B[${R}m`,H={bold:l(1,22),dim:l(2,22),green:l(32,39),cyan:l(36,39)};import*as PR from"node:fs";import*as OR from"node:path";import*as k from"node:process";function LR(S,R){let B=(R&&R!=="/"?`${S}${R}`:S).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return B.length>0?B:"rpx"}async function a(S){if(S.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let R=S.verbose??!1,D=S.registryDir,B=new Set,K=S.proxies.map((X)=>{let W=X.id??LR(X.to,X.path);if(!_R(W))throw Error(`invalid registry id "${W}" derived from to="${X.to}"`);if(B.has(W))throw Error(`duplicate registry id "${W}" — set an explicit \`id\` on one of the proxies`);return B.add(W),{...X,id:W}}),N=new Date().toISOString();for(let X of K)await NR({id:X.id,from:X.from,to:X.to,path:X.path,pid:S.persistent?void 0:k.pid,cwd:k.cwd(),createdAt:N,cleanUrls:X.cleanUrls,changeOrigin:X.changeOrigin,pathRewrites:X.pathRewrites,static:X.static},D,R);let A=await KR({rpxDir:S.rpxDir,verbose:R,spawnCommand:S.spawnCommand,startupTimeoutMs:S.startupTimeoutMs,spawnEnv:S.spawnEnv});for(let X of K){let W=X.static?`static ${typeof X.static==="string"?X.static:X.static.dir}`:X.from;G.success(`https://${X.to} → ${W}`)}if(G.info(`(via rpx daemon pid=${A.pid}; \`rpx daemon:status\` to inspect)`),S.detached)return;let V=!1,Y=D??DR(),J=K.map((X)=>X.id),Q=async()=>{if(V)return;V=!0;for(let X of J)await BR(X,D,R).catch((W)=>{_("runner",`removeEntry(${X}) failed: ${W}`,R)})},Z=(X)=>{_("runner",`received ${X}, unregistering ${J.length} entries`,R),Q().finally(()=>k.exit(0))};k.once("SIGINT",Z),k.once("SIGTERM",Z),k.once("exit",()=>{if(V)return;for(let X of J)try{PR.unlinkSync(OR.join(Y,`${X}.json`))}catch{}}),await new Promise(()=>{})}import{exec as nR}from"node:child_process";import q from"node:fs";import vR from"node:os";import YR from"node:path";import*as v from"node:process";import{promisify as rR}from"node:util";var c=rR(nR);function cR(S){let R=S.trim().toLowerCase();return R==="localhost"||R.endsWith(".localhost")||R.endsWith(".localhost.")}var j=v.platform==="win32"?YR.join(v.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",AR=!1;async function p(S){if(v.platform==="win32")throw Error("Administrator privileges required on Windows");if(mR()){let{stdout:B}=await c(S);return B}let R=m(),D=S.replace(/'/g,"'\\''");try{if(R){let{stdout:B}=await c(`echo '${R}' | sudo -S sh -c '${D}' 2>/dev/null`);return AR=!0,B}if(AR)try{let{stdout:B}=await c(`sudo -n sh -c '${D}'`);return B}catch(B){_("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:B}=await c(`sudo -n sh -c '${D}'`);return AR=!0,B}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(B){throw Error(`Failed to execute sudo command: ${B.message}`)}}async function y(S,R){let D=S.filter((K)=>!cR(K)),B=S.filter((K)=>cR(K));if(B.length>0)_("hosts",`Skipping /etc/hosts for loopback dev names: ${B.join(", ")}`,R);if(D.length===0)return;_("hosts",`Adding hosts: ${D.join(", ")}`,R),_("hosts",`Using hosts file at: ${j}`,R);try{let K;try{K=await q.promises.readFile(j,"utf-8")}catch{_("hosts","Reading hosts file requires elevated permissions, using sudo",R);try{K=await p(`cat "${j}"`)}catch(Y){throw console.log(" Could not read hosts file — skipping hosts setup"),_("hosts",`sudo read also failed: ${Y}`,R),Error(`Cannot read hosts file: ${Y}`)}}let N=D.filter((Y)=>{let J=`127.0.0.1 ${Y}`,Q=`::1 ${Y}`;return!K.includes(J)&&!K.includes(Q)});if(N.length===0){_("hosts","All hosts already exist in hosts file",R);return}let A=N.map((Y)=>`
2
2
  # Added by rpx
3
3
  127.0.0.1 ${Y}
4
4
  ::1 ${Y}`).join(`
@@ -6,4 +6,4 @@ import{$ as qR,$a as vD,A as US,Aa as QD,B as U,Ba as VD,C as o,Ca as XD,D as FR
6
6
  `),K=!1,N=B.filter((Y)=>{if(S.some((Q)=>Y.includes(` ${Q}`)&&(Y.includes("127.0.0.1")||Y.includes("::1"))))return K=!0,!1;if(Y.trim()==="# Added by rpx")return K=!0,!1;return!0});if(!K){_("hosts","No matching hosts found to remove",R);return}while(N[N.length-1]?.trim()==="")N.pop();let A=`${N.join(`
7
7
  `)}
8
8
  `,V=YR.join(vR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await q.promises.writeFile(V,A,"utf8"),await p(`cat "${V}" | tee "${j}" > /dev/null`),_("hosts","Hosts removed successfully",R)}catch(Y){_("hosts","Could not clean up hosts file automatically",R)}finally{try{await q.promises.unlink(V)}catch(Y){_("hosts",`Failed to remove temporary file: ${Y}`,R)}}}catch(D){_("hosts",`Failed to clean up hosts file: ${D.message}`,R)}}async function f(S,R){_("hosts",`Checking hosts: ${S}`,R);let D;try{D=await q.promises.readFile(j,"utf-8")}catch(B){_("hosts",`Error reading hosts file: ${B}`,R);try{let K=m(),N;if(K)N=`echo '${K}' | sudo -S cat "${j}" 2>/dev/null`;else N=`sudo -n cat "${j}" 2>/dev/null || cat "${j}" 2>/dev/null || echo ""`;let{stdout:A}=await c(N);D=A}catch(K){return _("hosts",`Cannot read hosts file, assuming entries don't exist: ${K}`,R),S.map(()=>!1)}}return S.map((B)=>{let K=`127.0.0.1 ${B}`,N=`::1 ${B}`;return D.includes(K)||D.includes(N)})}import{spawn as tR}from"node:child_process";import*as d from"node:process";class g{processes=new Map;isShuttingDown=!1;async startProcess(S,R,D){if(this.processes.has(S)){_("start",`Process ${S} is already running`,D);return}let[B,...K]=R.command.split(" "),N=R.cwd||d.cwd();_("start",`Starting process ${S}:`,D),_("start",` Command: ${B} ${K.join(" ")}`,D),_("start",` Working directory: ${N}`,D),_("start",` Environment variables: ${E(R.env)}`,D);let A=tR(B,K,{cwd:N,env:{...d.env,...R.env},shell:!0,stdio:"inherit"});return this.processes.set(S,{command:R.command,cwd:N,process:A,env:R.env}),new Promise((V,Y)=>{if(A.on("error",(J)=>{if(!this.isShuttingDown)_("start",`Process ${S} failed to start: ${J}`,D),this.processes.delete(S),Y(J)}),A.on("exit",(J)=>{if(!this.isShuttingDown&&J!==null&&J!==0)_("start",`Process ${S} exited with code ${J}; leaving the proxy running`,D),this.processes.delete(S),Y(Error(`Process ${S} exited with code ${J}`))}),D)A.stdout?.on("data",(J)=>{_("process",`[${S}] ${J.toString().trim()}`,!0)}),A.stderr?.on("data",(J)=>{_("process",`[${S}] ERR: ${J.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&A.killed)this.processes.delete(S),Y(Error(`Process ${S} was killed during startup`));else _("start",`Process ${S} started successfully`,D),V()},1000)})}async stopProcess(S,R){let D=this.processes.get(S);if(!D?.process){_("start",`No process found for ${S}`,R);return}return _("start",`Stopping process ${S}`,R),new Promise((B)=>{if(!D.process){B();return}D.process.once("exit",()=>{this.processes.delete(S),_("start",`Process ${S} stopped`,R),B()});try{D.process.kill("SIGTERM"),setTimeout(()=>{if(D.process){_("start",`Force killing process ${S}`,R);try{D.process.kill("SIGKILL")}catch(K){}}},3000)}catch(K){_("start",`Error stopping process ${S}: ${K}`,R),this.processes.delete(S),B()}})}async stopAll(S){if(this.isShuttingDown){_("start","Already shutting down, skipping duplicate stopAll call",S);return}this.isShuttingDown=!0,_("start","Stopping all processes",S);let R=Array.from(this.processes.keys()).map((D)=>this.stopProcess(D,S).catch((B)=>{G.error(`Failed to stop process ${D}:`,B)}));await Promise.allSettled(R),this.processes.clear(),this.isShuttingDown=!1}isRunning(S){let R=this.processes.get(S);return!!R?.process&&!R.process.killed}}var B_=new g;import{timingSafeEqual as sR}from"node:crypto";function eR(S,R){if(S==null)return!1;let D=Buffer.from(S),B=Buffer.from(R);if(D.length!==B.length)return!1;return sR(D,B)}function i(S){return S.toLowerCase().replace(/\.$/,"")}var oR=["/.well-known/acme-challenge/"];function RS(S){let R=S.headers.get("host");if(R)return i(R.split(":")[0]);try{return i(new URL(S.url).hostname)}catch{return""}}function JR(S){let R=S.header.toLowerCase(),D=new Set,B=[];for(let Y of S.hosts){let J=i(Y);if(J.startsWith("*."))B.push(J);else D.add(J)}let K=S.exemptPaths??oR,N=S.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
9
- `,A=(Y)=>{let J=i(Y);return D.has(J)||B.some((Q)=>GR(J,Q))},V=(Y)=>{let J=RS(Y);if(!A(J))return;let Q="/";try{Q=new URL(Y.url).pathname}catch{}if(K.some((Z)=>Q.startsWith(Z)))return;if(eR(Y.headers.get(R),S.value))return;return new Response(N,{status:403,headers:{"content-type":"text/plain"}})};return V.protects=A,V}import*as hR from"node:fs";import*as uR from"node:path";var QR="/.well-known/acme-challenge/";function VR(S,R){if(!S||!R.startsWith(QR))return null;let D=R.slice(QR.length);if(!D||!/^[A-Za-z0-9_-]+$/.test(D))return null;try{return hR.readFileSync(uR.join(S,D),"utf8")}catch{return null}}var r=new g,DS="0.12.0",_S=new CR("0.0.0.0"),t=new Set,XR=!1,n=null,ZR=null;async function u(S){if(XR)return _("cleanup","Cleanup already in progress, skipping",S?.verbose),ZR||Promise.resolve();XR=!0,_("cleanup","Starting cleanup process",S?.verbose),ZR=new Promise((R)=>{n=R});try{await r.stopAll(S?.verbose),G.info("Shutting down proxy servers...");let R=[],D=Array.from(t).map((B)=>new Promise((K)=>{let N=B;try{if(typeof N.stop==="function")N.stop(!0),_("cleanup","Bun server stopped",S?.verbose),K();else if(typeof N.close==="function")N.close(()=>{_("cleanup","Server closed successfully",S?.verbose),K()});else K()}catch(A){_("cleanup",`Error stopping server: ${A}`,S?.verbose),K()}}));if(R.push(...D),t.clear(),S?.hosts&&S.domains?.length){_("cleanup","Cleaning up hosts file entries",S?.verbose),_("cleanup",`Original domains for cleanup: ${JSON.stringify(S.domains)}`,S?.verbose);let B=S.domains.filter((K)=>{if(K==="test.local")return!0;return K!=="localhost"&&!K.startsWith("localhost.")&&K!=="127.0.0.1"});if(_("cleanup",`Filtered domains for cleanup: ${JSON.stringify(B)}`,S?.verbose),B.length>0)G.info("Cleaning up hosts file entries..."),R.push($R(B,S?.verbose).then(()=>{_("cleanup",`Removed hosts entries for ${B.join(", ")}`,S?.verbose)}).catch((K)=>{_("cleanup",`Failed to remove hosts entries: ${K}`,S?.verbose),G.warn(`Failed to clean up hosts file entries for ${B.join(", ")}:`,K)}))}if(S?.certs&&S.domains?.length){_("cleanup","Cleaning up SSL certificates",S?.verbose),G.info("Cleaning up SSL certificates...");let B=S.domains.map(async(K)=>{try{await FR(K,S?.verbose),_("cleanup",`Removed certificates for ${K}`,S?.verbose)}catch(N){_("cleanup",`Failed to remove certificates for ${K}: ${N}`,S?.verbose),G.warn(`Failed to clean up certificates for ${K}:`,N)}});R.push(...B)}await Promise.allSettled(R),_("cleanup","All cleanup tasks completed successfully",S?.verbose),G.success("All cleanup tasks completed successfully")}catch(R){_("cleanup",`Error during cleanup: ${R}`,S?.verbose),G.error("Error during cleanup:",R)}finally{if(n)n();n=null,XR=!1;let R=S&&"vitePluginUsage"in S&&S.vitePluginUsage===!0;if(z.env.NODE_ENV!=="test"&&z.env.BUN_ENV!=="test"&&!R)z.exit(0)}return ZR}var WR=!1;function pR(S){if(WR){_("signal",`Received second ${S} signal, forcing exit`,!0),z.exit(1);return}WR=!0,_("signal",`Received ${S} signal, initiating cleanup`,!0),u().catch((R)=>{_("signal",`Cleanup failed after ${S}: ${R}`,!0),z.exit(1)}).finally(()=>{WR=!1})}z.once("SIGINT",()=>pR("SIGINT"));z.once("SIGTERM",()=>pR("SIGTERM"));z.on("uncaughtException",(S)=>{G.error("Uncaught exception (continuing):",S)});z.on("unhandledRejection",(S)=>{G.error("Unhandled rejection (continuing):",S)});async function h(S,R,D,B=5){_("connection",`Testing connection to ${S}:${R} (retries left: ${B})`,D);let K=15000,N=Date.now();if(z.env.RPX_BYPASS_CONNECTION_TEST==="true"){_("connection",`Bypassing connection test for ${S}:${R} due to RPX_BYPASS_CONNECTION_TEST flag`,D);return}let A=()=>new Promise((V,Y)=>{let J=aR.connect({host:S,port:R,timeout:3000});J.once("connect",()=>{_("connection",`Successfully connected to ${S}:${R}`,D),J.end(),V()}),J.once("timeout",()=>{_("connection",`Connection to ${S}:${R} timed out`,D),J.destroy(),Y(Error("Connection timed out"))}),J.once("error",(Q)=>{_("connection",`Failed to connect to ${S}:${R}: ${Q}`,D),J.destroy(),Y(Q)})});try{await A()}catch(V){let Y=V;if(Date.now()-N>K){_("connection",`Connection test timed out after ${K}ms, but continuing anyway`,D),G.warn(`Connection test to ${S}:${R} timed out, but RPX will try to proceed anyway.`);return}if(Y.code==="ECONNREFUSED"&&B>0)return _("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${B} retries left)`,D),await new Promise((Q)=>setTimeout(Q,2000)),h(S,R,D,B-1);if(B>0)try{_("connection",`Trying HTTP request to ${S}:${R}`,D),await new Promise((Q,Z)=>{let X=SR.request({hostname:S,port:R,path:"/",method:"HEAD",timeout:5000},(W)=>{_("connection",`Received HTTP response with status: ${W.statusCode}`,D),Q()});X.on("error",(W)=>Z(W)),X.on("timeout",()=>{X.destroy(),Z(Error("HTTP request timed out"))}),X.end()}),_("connection",`HTTP request to ${S}:${R} succeeded`,D);return}catch(Q){return _("connection",`HTTP request to ${S}:${R} failed: ${Q}`,D),_("connection",`Retrying socket connection in 2 seconds... (${B} retries left)`,D),await new Promise((Z)=>setTimeout(Z,2000)),h(S,R,D,B-1)}let J=`Failed to connect to ${S}:${R} after ${5-B} attempts: ${Y.message}`;_("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,D),G.warn(J),G.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function yR(S){_("server",`Starting server with options: ${E(S)}`,S.verbose);let R=new URL((S.from?.startsWith("http")?S.from:`http://${S.from}`)||"localhost:5173"),D=new URL((S.to?.startsWith("http")?S.to:`http://${S.to}`)||"rpx.localhost"),B=Number.parseInt(R.port)||(R.protocol.includes("https:")?443:80),K=[D.hostname];if(fR(S)&&!D.hostname.includes("localhost")&&!D.hostname.includes("127.0.0.1")){_("hosts",`Checking if hosts file entry exists for: ${D.hostname}`,S?.verbose);try{if(!(await f(K,S.verbose))[0]){G.info(`Adding ${D.hostname} to hosts file...`),G.info("This may require sudo/administrator privileges");try{await y(K,S.verbose)}catch(V){if(G.error("Failed to add hosts entry:",V.message),G.warn("You can manually add this entry to your hosts file:"),G.warn(`127.0.0.1 ${D.hostname}`),G.warn(`::1 ${D.hostname}`),z.platform==="win32")G.warn("On Windows:"),G.warn("1. Run notepad as administrator"),G.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else G.warn("On Unix systems:"),G.warn("sudo nano /etc/hosts")}}else _("hosts",`Host entry already exists for ${D.hostname}`,S.verbose)}catch(A){G.error("Failed to check hosts file:",A.message)}}try{await h(R.hostname,B,S.verbose)}catch(A){_("server",`Connection test failed: ${A}`,S.verbose),G.error(A.message),G.warn("Continuing with proxy setup despite connection test failure..."),G.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let N=S._cachedSSLConfig||null;if(S.https)try{if(S.https===!0)S.https=o({...S,to:D.hostname});if(N=await U({...S,to:D.hostname,https:S.https}),!N){if(_("ssl",`Generating new certificates for ${D.hostname}`,S.verbose),await e({...S,from:R.toString(),to:D.hostname,https:S.https}),N=await U({...S,to:D.hostname,https:S.https}),!N)throw Error(`Failed to load SSL configuration after generating certificates for ${D.hostname}`)}}catch(A){throw _("server",`SSL setup failed: ${A}`,S.verbose),A}_("server",`Setting up reverse proxy with SSL config for ${D.hostname}`,S.verbose),await BS({...S,from:S.from||"localhost:5173",to:D.hostname,fromPort:B,sourceUrl:{hostname:R.hostname,host:R.host},ssl:N})}async function NS(S,R,D,B,K,N,A,V,Y,J){_("proxy",`Creating proxy server ${S} -> ${R} with cleanUrls: ${V}`,A);let Q=[{host:R,route:{sourceHost:B.host,cleanUrls:V||!1,changeOrigin:Y||!1,basePath:"/",auth:J}}];if(!IR({routeEntries:Q,listenPort:D,sslConfig:K,originGuard:null,verbose:A??!1}))throw Error(`Failed to start proxy server for ${R} on port ${D}`);YS({from:S,to:R,vitePluginUsage:N,listenPort:D,ssl:!!K,cleanUrls:V,verbose:A})}async function BS(S){_("setup",`Setting up reverse proxy: ${E(S)}`,S.verbose);let{from:R,to:D,sourceUrl:B,ssl:K,verbose:N,cleanup:A,vitePluginUsage:V,changeOrigin:Y,cleanUrls:J}=S,Q=80,Z=443,X="0.0.0.0",W=S.portManager||_S,P=fR(S);try{if(P&&D&&!D.includes("localhost")&&!D.includes("127.0.0.1")){if(!(await f([D],N))[0]){G.warn(`The hostname ${D} isn't in your hosts file. Adding it now...`);try{await y([D],N),G.success(`Added ${D} to your hosts file.`)}catch(L){G.error(`Failed to add ${D} to your hosts file: ${L}`),G.info(`You may need to manually add '127.0.0.1 ${D}' to your /etc/hosts file.`)}}}else if(P&&z.platform!=="darwin"&&D&&D.includes("localhost")&&!D.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await f([D],N))[0]){_("hosts",`${D} not found in hosts file, adding...`,N);try{await y([D],N)}catch(L){_("hosts",`Failed to add ${D} to hosts file: ${L}`,N)}}}if(K&&!W.usedPorts.has(Q)){if(!await C(Q,X,N))_("setup","Starting HTTP redirect server",N),dR(N),W.usedPorts.add(Q);else if(_("setup","Port 80 is in use, skipping HTTP redirect",N),N)G.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let x=K?Z:Q,w=await C(x,X,N),F;if(w){if(_("setup",`Port ${x} is already in use`,N),N)G.warn(`Port ${x} is already in use. This may be another instance of rpx or another service.`);if(x===443){if(F=await W.getNextAvailablePort(3443,!0),_("setup",`Using port ${F} instead of ${x}`,N),N)G.info(`Using port ${F} instead. Access your site at https://${D}:${F}`)}else if(F=await W.getNextAvailablePort(x+1000,!0),_("setup",`Using port ${F} instead of ${x}`,N),N)G.info(`Using port ${F} instead. Access your site at http://${D}:${F}`)}else F=x,W.usedPorts.add(F),_("setup",`Using standard ${x===443?"HTTPS":"HTTP"} port ${x} for ${D}`,N);await NS(R,D,F,B,K,V,N,J,Y,RR(S.auth))}catch(x){_("setup",`Setup failed: ${x}`,N),G.error(`Failed to setup reverse proxy: ${x.message}`),u({domains:[D],hosts:typeof A==="boolean"?A:A?.hosts,certs:typeof A==="boolean"?A:A?.certs,verbose:N,vitePluginUsage:V})}}function dR(S,R=80,D=443,B){_("redirect",`Starting HTTP redirect server on port ${R}`,S);let K=SR.createServer((N,A)=>{if(B&&N.url){let Q=N.url.split("?",1)[0],Z=VR(B,Q);if(Z!=null){_("redirect",`Serving ACME challenge ${Q}`,S),A.writeHead(200,{"content-type":"text/plain"}),A.end(Z);return}}let V=N.headers.host||"",Y=V.includes(":")?V.slice(0,V.indexOf(":")):V,J=D===443?Y:`${Y}:${D}`;_("redirect",`Redirecting request from ${V}${N.url} to https://${J}`,S),A.writeHead(301,{Location:`https://${J}${N.url}`}),A.end()}).listen(R);t.add(K),_("redirect","HTTP redirect server started",S)}function KS(S){let R={...s,...S};if(_("proxy",`Starting proxy with options: ${E(R)}`,R?.verbose),R.viaDaemon){if(!R.from||!R.to){G.error("viaDaemon mode requires both `from` and `to`");return}a({proxies:[{id:R.id,from:R.from,to:R.to,path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}],verbose:R.verbose}).catch((Y)=>{G.error(`Failed to register with rpx daemon: ${Y.message}`),z.exit(1)});return}let D=R.to||"",B=D.split(".").pop()?.toLowerCase()||"",K=z.platform==="darwin"&&D&&!D.includes("localhost")&&!D.includes("127.0.0.1"),N=["dev","app","page","new","day","foo"],A=["test","localhost","local","example","invalid"];if(K&&N.includes(B)&&R?.verbose)G.warn(`The .${B} TLD may not work reliably for local development`),G.info(` Google owns .${B} with HSTS preloading, which can bypass local DNS`),G.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(K)import("./chunk-1108y1dk.js").then(({setupDevelopmentDns:Y})=>{Y({domains:[D],verbose:R.verbose}).then((J)=>{if(J)Promise.resolve().then(()=>{if(R.verbose)if(A.includes(B))G.success(`DNS server started for .${B} domains`);else G.success(`DNS server started for .${B} domains (hosts file entry also added)`)});else _("dns",`Could not start DNS server - ${D} may not resolve in browser`,R.verbose)})}).catch((Y)=>{_("dns",`Failed to start DNS server: ${Y}`,R.verbose)});let V={from:R.from,to:R.to,cleanUrls:R.cleanUrls,https:o(R),cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,changeOrigin:R.changeOrigin,verbose:R.verbose,regenerateUntrustedCerts:R.regenerateUntrustedCerts};_("proxy",`Server options: ${E(V)}`,R.verbose),yR(V).catch((Y)=>{_("proxy",`Failed to start proxy: ${Y}`,R.verbose),G.error(`Failed to start proxy: ${Y.message}`),u({domains:[R.to],hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose})})}function AS(S){return S?.verbose||!1}function fR(S){if(S?.hostsManagement===!1)return!1;let R=S?.cleanup;if(R===!1)return!1;if(R&&typeof R==="object"&&R.hosts===!1)return!1;return!0}async function UR(S){let R={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(S)R={...R,...S};let D=AS(R),B=fR(R);if(_("config",`Starting with config: ${E(R,2)}`,D),_("config",`Is multi-proxy? ${"proxies"in R}`,D),_("config",`Hosts management enabled? ${B}`,D),R.viaDaemon){let I="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((M)=>({id:M.id,from:M.from,to:M.to,path:M.path,cleanUrls:M.cleanUrls??R.cleanUrls,changeOrigin:M.changeOrigin??R.changeOrigin,pathRewrites:M.pathRewrites})):[{id:R.id,from:R.from,to:R.to??"rpx.localhost",path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}];await a({proxies:I,verbose:D});return}if("proxies"in R&&Array.isArray(R.proxies)){_("servers",`Found ${R.proxies.length} proxies in config`,D);for(let $ of R.proxies)if($.start){let I=`${$.from}-${$.to}`;try{_("watch",`Starting command for ${I} with command: ${$.start.command}`,D),G.info(`Starting command for ${I}...`),await r.startProcess(I,$.start,D);let M=new URL($.from?.startsWith("http")?$.from:`http://${$.from}`),T=M.hostname||"localhost",b=Number(M.port)||80;try{await h(T,b,D),_("watch",`Dev server is ready at ${T}:${b}`,D)}catch(iR){_("watch",`Connection check failed, but continuing with proxy setup: ${iR}`,D),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw _("watch",`Failed to start command for ${I}: ${M}`,D),Error(`Failed to start command for ${I}: ${M}`)}}else _("watch",`No start command for proxy ${$.from} -> ${$.to}`,D)}else if("start"in R&&R.start){_("watch","Found start command in single proxy config",D);let $=`${R.from}-${R.to}`;try{if(R.start)_("watch",`Starting command: ${R.start.command}`,D),await r.startProcess($,R.start,D);let I=new URL(R.from?.startsWith("http")?R.from:`http://${R.from}`),M=I.hostname||"localhost",T=Number(I.port)||80;try{await h(M,T,D),_("watch",`Dev server is ready at ${M}:${T}`,D)}catch(b){_("watch",`Connection check failed, but continuing with proxy setup: ${b}`,D),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(I){throw _("watch",`Failed to run start command: ${I}`,D),Error(`Failed to run start command: ${I}`)}}else _("watch","No start command found in config",D);let K="proxies"in R&&Array.isArray(R.proxies)?R.proxies[0]?.to:("to"in R)?R.to:"rpx.localhost";if(z.platform!=="win32"&&(R.https||B)){if(!m())try{_("sudo","Pre-acquiring sudo credentials for privileged operations",D),SS("sudo -v",{stdio:"inherit"})}catch{_("sudo","Could not pre-acquire sudo credentials",D)}}let N=[];if(R.productionCerts){if(N=await qR(R.productionCerts,D),N.length>0)_("ssl",`Using ${N.length} production SNI cert(s): ${N.map(($)=>$.serverName).join(", ")}`,D)}if(R.https){let $=N.length>0?null:await U(R);if(!$&&N.length===0){if(_("ssl",`No valid or trusted certificates found for ${K}, generating new ones`,R.verbose),await e(R),$=await U(R),!$)throw Error(`Failed to load SSL certificates after generation for ${K}`)}else _("ssl",`Using existing and trusted certificates for ${K}`,R.verbose);R._cachedSSLConfig=$}let A="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map(($)=>({...$,https:R.https,cleanup:R.cleanup,cleanUrls:$.cleanUrls??("cleanUrls"in R?R.cleanUrls:!1),vitePluginUsage:R.vitePluginUsage,changeOrigin:$.changeOrigin??R.changeOrigin,verbose:D,_cachedSSLConfig:R._cachedSSLConfig})):[{from:"from"in R?R.from:"localhost:5173",to:"to"in R?R.to:"rpx.localhost",cleanUrls:"cleanUrls"in R?R.cleanUrls:!1,https:R.https,cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,start:"start"in R?R.start:void 0,changeOrigin:R.changeOrigin,auth:"auth"in R?R.auth:void 0,verbose:D,_cachedSSLConfig:R._cachedSSLConfig}],V=A.map(($)=>$.to||"rpx.localhost"),Y=N.length>0?N:R._cachedSSLConfig??null,J=V.filter(($)=>$&&!$.includes("localhost")&&!$.includes("127.0.0.1")),Q=["dev","app","page","new","day","foo"],Z=["test","localhost","local","example","invalid"],X=[...new Set(J.map(($)=>$.split(".").pop()?.toLowerCase()))],W=X.filter(($)=>!!$&&Q.includes($));if(W.length>0&&D)G.warn(`The following TLDs may not work reliably for local development: ${W.map(($)=>`.${$}`).join(", ")}`),G.info(" These TLDs have HSTS preloading which can bypass local DNS"),G.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(B&&z.platform==="darwin"&&J.length>0){let{setupDevelopmentDns:$}=await import("./chunk-1108y1dk.js");if(await $({domains:J,verbose:D})){if(D)if(X.every((T)=>!!T&&Z.includes(T)))G.success(`DNS server started for ${X.map((T)=>`.${T}`).join(", ")} domains`);else G.success(`DNS server started for ${X.map((T)=>`.${T}`).join(", ")} domains (hosts file entries also added)`)}else _("dns","Could not start DNS server - custom domains may not resolve",D)}let P=async()=>{_("cleanup","Starting cleanup handler",R.verbose);try{let{tearDownDevelopmentDns:$}=await import("./chunk-1108y1dk.js");await $({verbose:R.verbose})}catch($){_("cleanup",`Error stopping DNS server: ${$}`,R.verbose)}try{await r.stopAll(R.verbose)}catch($){_("cleanup",`Error stopping processes: ${$}`,R.verbose)}await u({domains:V,hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose||!1})};z.on("SIGINT",P),z.on("SIGTERM",P);let x=R.singlePortMode===!0,w=R.httpsPort??443,F=R.httpPort??80,O=R.originGuard?JR(R.originGuard):null,L=!!Y&&(A.length>1||x),gR=!Y&&x&&A.length>0;if(L&&Y){_("proxies",`Creating shared HTTPS server for ${A.length} domains on port ${w}`,D);let $=await bR(A,B,D);if(!await C(F,"0.0.0.0",D))dR(D,F,w,R.acmeChallengeWebroot);if(await C(w,"0.0.0.0",D)){if(_("proxies",`Port ${w} is already in use, cannot start shared proxy`,D),D)G.warn(`Port ${w} is in use. Shared HTTPS proxy cannot start.`);return}if(!IR({routeEntries:$,listenPort:w,sslConfig:Y,originGuard:O,verbose:D})){G.error(`Shared HTTPS proxy failed to bind :${w}; not exiting`);return}}else if(gR){_("proxies",`Creating shared HTTP server for ${A.length} domains on port ${F}`,D);let $=await bR(A,B,D);if(await C(F,"0.0.0.0",D)){if(_("proxies",`Port ${F} is already in use, cannot start shared proxy`,D),D)G.warn(`Port ${F} is in use. Shared HTTP proxy cannot start.`);return}if(!IR({routeEntries:$,listenPort:F,sslConfig:null,originGuard:O,verbose:D})){G.error(`Shared HTTP proxy failed to bind :${F}; not exiting`);return}}else for(let $ of A)try{let I=$.to||"rpx.localhost";_("proxy",`Starting proxy for ${I} with SSL config: ${!!Y}`,$.verbose),await yR({from:$.from||"localhost:5173",to:I,cleanUrls:$.cleanUrls||!1,https:$.https||!1,cleanup:$.cleanup||!1,vitePluginUsage:$.vitePluginUsage||!1,verbose:$.verbose||!1,_cachedSSLConfig:R._cachedSSLConfig,changeOrigin:$.changeOrigin||!1})}catch(I){_("proxies",`Failed to start proxy for ${$.to}: ${I}`,$.verbose),G.error(`Failed to start proxy for ${$.to}:`,I)}}async function bR(S,R,D){let B=[],K=new Set;for(let N of S){let A=N.to||"rpx.localhost",V=N.cleanUrls||!1,Y=N.path,J=kR(Y),Q=RR(N.auth);if(N.redirect){let Z=MR(N.redirect);B.push({host:A,path:Y,route:{redirect:Z,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → redirect ${Z.status} ${Z.to}${Q?" (auth)":""}`,D)}else if(N.static)B.push({host:A,path:Y,route:{static:xR(N.static,V),cleanUrls:V,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → static ${typeof N.static==="string"?N.static:N.static.dir}${Q?" (auth)":""}`,D);else{let Z=new URL(N.from?.startsWith("http")?N.from:`http://${N.from}`);B.push({host:A,path:Y,route:{sourceHost:Z.host,cleanUrls:V,changeOrigin:N.changeOrigin||!1,pathRewrites:N.pathRewrites,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → ${Z.host}${Q?" (auth)":""}`,D)}if(K.has(A))continue;if(K.add(A),R&&!HR(A)&&!A.includes("localhost")&&!A.includes("127.0.0.1"))try{if(!(await f([A],D))[0])await y([A],D)}catch{_("hosts",`Could not add hosts entry for ${A}`,D)}}return B}function IR(S){let{routeEntries:R,listenPort:D,sslConfig:B,originGuard:K,verbose:N}=S,A=wR(R),V=TR((Q,Z)=>ER(A,Q,Z),N),Y=K?(Q,Z)=>K(Q)??V(Q,Z):V,J=jR(N);try{let Q=Bun.serve({port:D,hostname:"0.0.0.0",reusePort:lR(),...B?{tls:Array.isArray(B)?B.map((Z)=>({serverName:Z.serverName,key:Z.key,cert:Z.cert})):{key:B.key,cert:B.cert,ca:B.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(Z,X){return Y(Z,X)},websocket:J,error(Z){return _("server",`Shared proxy server error: ${Z}`,N),new Response(`Server Error: ${Z.message}`,{status:500})}});return t.add(Q),_("proxies",`Shared ${B?"HTTPS":"HTTP"} proxy listening on port ${D} for ${A.size} domains`,N),Q}catch(Q){return _("proxies",`Failed to start shared proxy: ${Q}`,N),console.error("Failed to start shared proxy:",Q),null}}function YS(S){if(S?.vitePluginUsage||!S?.verbose)return;if(console.log(""),console.log(` ${H.green(H.bold("rpx"))} ${H.green(`v${DS}`)}`),console.log(` ${H.green("➜")} ${H.dim(S?.from??"")} ${H.dim("➜")} ${H.cyan(S?.ssl?`https://${S?.to}`:`http://${S?.to}`)}`),S?.listenPort!==(S?.ssl?443:80))console.log(` ${H.green("➜")} Listening on port ${S?.listenPort}`);if(S?.cleanUrls)console.log(` ${H.green("➜")} Clean URLs enabled`)}var JN=UR;export{NR as writeEntry,YD as watchRegistry,VS as verifyHttpsChain,HS as trustRootCaForBrowsers,yD as tearDownDevelopmentDns,CD as syncDevelopmentDnsFromRegistry,bS as stripBasePath,TD as stopDnsServer,bD as stopDaemon,yR as startServer,KS as startProxy,UR as startProxies,xD as startDnsServer,tS as siteIdForHost,lR as shouldReusePort,wD as setupResolver,qD as setupDevelopmentDns,dS as serverNameFromCertFilename,uS as serveStaticFile,E as safeStringify,vS as safeRelativePath,TN as safeDeleteFile,a as runViaDaemon,hD as runDaemon,HD as resolverFilePath,zD as resolverBasenamesForDomains,WD as resolverBasenameForDomain,xR as resolveStaticRoute,hS as resolveStaticFile,MR as resolveRedirect,xN as resolvePathRewrite,RR as resolveAuth,JD as renderStartingPage,QD as renderFailedPage,fD as removeResolver,ED as removeLegacyTldResolvers,$R as removeHosts,BR as removeEntry,vD as releaseDaemonLock,VN as redactSensitive,UD as reconcileStaleDevelopmentDns,lD as reconcileDevelopmentDnsOnIdle,eS as readSiteManifest,BD as readEntry,LD as readDaemonPid,GS as readCertSha256Fingerprint,JS as readCertCommonName,KD as readAll,VR as readAcmeChallenge,xS as pruneStaleRootCas,sS as projectNameFromHost,_D as portManager,aS as pathPrefixMatches,XS as parseSha256HashesFromSecurityListing,OS as parseHtpasswd,$S as normalizeSha256Fingerprint,kR as normalizePathPrefix,ZD as normalizeDevDomain,GR as matchesWildcard,gS as matchesAllowedSuffix,ER as matchHostRoute,pS as matchHostList,lS as matchHost,yS as loadSSLConfig,SD as listDiscoverableSites,MS as listCertSha256HashesByCommonName,HR as isWildcardPattern,ZN as isValidRootCA,_R as isValidId,FN as isSingleProxyOptions,MN as isSingleProxyConfig,TS as isRootCaTrustedForSsl,jS as isRootCaFingerprintInKeychains,mR as isProcessElevated,C as isPortInUse,ND as isPidAlive,IN as isMultiProxyOptions,zN as isMultiProxyConfig,iS as isLikelyHostname,jD as isDnsServerRunning,cD as isDaemonRunning,PS as isCertTrusted,o as httpsConfig,m as getSudoPassword,CS as getSharedDaemonCertPaths,qS as getRootCAPaths,DR as getRegistryDir,WN as getPrimaryDomain,FS as getMacosTrustKeychains,IS as getMacosLoginKeychainPath,PD as getDaemonRpxDir,OD as getDaemonPidPath,e as generateCertificate,AD as gcStaleEntries,fS as forceTrustCertificate,DD as findAvailablePort,XN as extractHostname,rS as expandHome,QN as execSudoSync,GD as escapeHtml,KR as ensureDaemonRunning,LS as enforceBasicAuth,wS as devSslToSniEntries,ID as devDomainsFromHosts,oS as detectProjectPreset,LR as deriveIdFromTarget,uD as defaultDaemonSpawnCommand,s as defaultConfig,JN as default,_ as debugLog,RD as createSiteResolver,jR as createProxyWebSocketHandler,TR as createProxyFetchHandler,JR as createOriginGuard,mS as contentTypeFor,kD as contentLooksLikeRpxResolver,s as config,H as colors,US as clearSslConfigCache,FR as cleanupCertificates,u as cleanup,f as checkHosts,U as checkExistingCertificates,QS as certIncludesSanHostnames,qR as buildSniTlsConfig,ES as buildRegistryTlsProxyOptions,cS as buildRedirectLocation,wR as buildHostRoutes,y as addHosts,mD as acquireDaemonLock,$D as SiteSupervisor,kS as SHARED_DEV_HOST_CERT_PATH,zS as RPX_ROOT_CA_COMMON_NAME,MD as RPX_RESOLVER_MARKER,nS as OnDemandCertManager,WS as MACOS_SYSTEM_KEYCHAIN,ZS as MACOS_CA_TRUST_FLAGS,XD as LEGACY_TLD_RESOLVER_LABELS,CR as DefaultPortManager,VD as DNS_STATE_VERSION,FD as DNS_PORT,QR as ACME_CHALLENGE_PREFIX};
9
+ `,A=(Y)=>{let J=i(Y);return D.has(J)||B.some((Q)=>GR(J,Q))},V=(Y)=>{let J=RS(Y);if(!A(J))return;let Q="/";try{Q=new URL(Y.url).pathname}catch{}if(K.some((Z)=>Q.startsWith(Z)))return;if(eR(Y.headers.get(R),S.value))return;return new Response(N,{status:403,headers:{"content-type":"text/plain"}})};return V.protects=A,V}import*as hR from"node:fs";import*as uR from"node:path";var QR="/.well-known/acme-challenge/";function VR(S,R){if(!S||!R.startsWith(QR))return null;let D=R.slice(QR.length);if(!D||!/^[A-Za-z0-9_-]+$/.test(D))return null;try{return hR.readFileSync(uR.join(S,D),"utf8")}catch{return null}}var r=new g,DS="0.12.0",_S=new CR("0.0.0.0"),t=new Set,XR=!1,n=null,ZR=null;async function u(S){if(XR)return _("cleanup","Cleanup already in progress, skipping",S?.verbose),ZR||Promise.resolve();XR=!0,_("cleanup","Starting cleanup process",S?.verbose),ZR=new Promise((R)=>{n=R});try{await r.stopAll(S?.verbose),G.info("Shutting down proxy servers...");let R=[],D=Array.from(t).map((B)=>new Promise((K)=>{let N=B;try{if(typeof N.stop==="function")N.stop(!0),_("cleanup","Bun server stopped",S?.verbose),K();else if(typeof N.close==="function")N.close(()=>{_("cleanup","Server closed successfully",S?.verbose),K()});else K()}catch(A){_("cleanup",`Error stopping server: ${A}`,S?.verbose),K()}}));if(R.push(...D),t.clear(),S?.hosts&&S.domains?.length){_("cleanup","Cleaning up hosts file entries",S?.verbose),_("cleanup",`Original domains for cleanup: ${JSON.stringify(S.domains)}`,S?.verbose);let B=S.domains.filter((K)=>{if(K==="test.local")return!0;return K!=="localhost"&&!K.startsWith("localhost.")&&K!=="127.0.0.1"});if(_("cleanup",`Filtered domains for cleanup: ${JSON.stringify(B)}`,S?.verbose),B.length>0)G.info("Cleaning up hosts file entries..."),R.push($R(B,S?.verbose).then(()=>{_("cleanup",`Removed hosts entries for ${B.join(", ")}`,S?.verbose)}).catch((K)=>{_("cleanup",`Failed to remove hosts entries: ${K}`,S?.verbose),G.warn(`Failed to clean up hosts file entries for ${B.join(", ")}:`,K)}))}if(S?.certs&&S.domains?.length){_("cleanup","Cleaning up SSL certificates",S?.verbose),G.info("Cleaning up SSL certificates...");let B=S.domains.map(async(K)=>{try{await FR(K,S?.verbose),_("cleanup",`Removed certificates for ${K}`,S?.verbose)}catch(N){_("cleanup",`Failed to remove certificates for ${K}: ${N}`,S?.verbose),G.warn(`Failed to clean up certificates for ${K}:`,N)}});R.push(...B)}await Promise.allSettled(R),_("cleanup","All cleanup tasks completed successfully",S?.verbose),G.success("All cleanup tasks completed successfully")}catch(R){_("cleanup",`Error during cleanup: ${R}`,S?.verbose),G.error("Error during cleanup:",R)}finally{if(n)n();n=null,XR=!1;let R=S&&"vitePluginUsage"in S&&S.vitePluginUsage===!0;if(z.env.NODE_ENV!=="test"&&z.env.BUN_ENV!=="test"&&!R)z.exit(0)}return ZR}var WR=!1;function pR(S){if(WR){_("signal",`Received second ${S} signal, forcing exit`,!0),z.exit(1);return}WR=!0,_("signal",`Received ${S} signal, initiating cleanup`,!0),u().catch((R)=>{_("signal",`Cleanup failed after ${S}: ${R}`,!0),z.exit(1)}).finally(()=>{WR=!1})}z.once("SIGINT",()=>pR("SIGINT"));z.once("SIGTERM",()=>pR("SIGTERM"));z.on("uncaughtException",(S)=>{G.error("Uncaught exception (continuing):",S)});z.on("unhandledRejection",(S)=>{G.error("Unhandled rejection (continuing):",S)});async function h(S,R,D,B=5){_("connection",`Testing connection to ${S}:${R} (retries left: ${B})`,D);let K=15000,N=Date.now();if(z.env.RPX_BYPASS_CONNECTION_TEST==="true"){_("connection",`Bypassing connection test for ${S}:${R} due to RPX_BYPASS_CONNECTION_TEST flag`,D);return}let A=()=>new Promise((V,Y)=>{let J=aR.connect({host:S,port:R,timeout:3000});J.once("connect",()=>{_("connection",`Successfully connected to ${S}:${R}`,D),J.end(),V()}),J.once("timeout",()=>{_("connection",`Connection to ${S}:${R} timed out`,D),J.destroy(),Y(Error("Connection timed out"))}),J.once("error",(Q)=>{_("connection",`Failed to connect to ${S}:${R}: ${Q}`,D),J.destroy(),Y(Q)})});try{await A()}catch(V){let Y=V;if(Date.now()-N>K){_("connection",`Connection test timed out after ${K}ms, but continuing anyway`,D),G.warn(`Connection test to ${S}:${R} timed out, but RPX will try to proceed anyway.`);return}if(Y.code==="ECONNREFUSED"&&B>0)return _("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${B} retries left)`,D),await new Promise((Q)=>setTimeout(Q,2000)),h(S,R,D,B-1);if(B>0)try{_("connection",`Trying HTTP request to ${S}:${R}`,D),await new Promise((Q,Z)=>{let X=SR.request({hostname:S,port:R,path:"/",method:"HEAD",timeout:5000},(W)=>{_("connection",`Received HTTP response with status: ${W.statusCode}`,D),Q()});X.on("error",(W)=>Z(W)),X.on("timeout",()=>{X.destroy(),Z(Error("HTTP request timed out"))}),X.end()}),_("connection",`HTTP request to ${S}:${R} succeeded`,D);return}catch(Q){return _("connection",`HTTP request to ${S}:${R} failed: ${Q}`,D),_("connection",`Retrying socket connection in 2 seconds... (${B} retries left)`,D),await new Promise((Z)=>setTimeout(Z,2000)),h(S,R,D,B-1)}let J=`Failed to connect to ${S}:${R} after ${5-B} attempts: ${Y.message}`;_("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,D),G.warn(J),G.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function yR(S){_("server",`Starting server with options: ${E(S)}`,S.verbose);let R=new URL((S.from?.startsWith("http")?S.from:`http://${S.from}`)||"localhost:5173"),D=new URL((S.to?.startsWith("http")?S.to:`http://${S.to}`)||"rpx.localhost"),B=Number.parseInt(R.port)||(R.protocol.includes("https:")?443:80),K=[D.hostname];if(fR(S)&&!D.hostname.includes("localhost")&&!D.hostname.includes("127.0.0.1")){_("hosts",`Checking if hosts file entry exists for: ${D.hostname}`,S?.verbose);try{if(!(await f(K,S.verbose))[0]){G.info(`Adding ${D.hostname} to hosts file...`),G.info("This may require sudo/administrator privileges");try{await y(K,S.verbose)}catch(V){if(G.error("Failed to add hosts entry:",V.message),G.warn("You can manually add this entry to your hosts file:"),G.warn(`127.0.0.1 ${D.hostname}`),G.warn(`::1 ${D.hostname}`),z.platform==="win32")G.warn("On Windows:"),G.warn("1. Run notepad as administrator"),G.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else G.warn("On Unix systems:"),G.warn("sudo nano /etc/hosts")}}else _("hosts",`Host entry already exists for ${D.hostname}`,S.verbose)}catch(A){G.error("Failed to check hosts file:",A.message)}}try{await h(R.hostname,B,S.verbose)}catch(A){_("server",`Connection test failed: ${A}`,S.verbose),G.error(A.message),G.warn("Continuing with proxy setup despite connection test failure..."),G.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let N=S._cachedSSLConfig||null;if(S.https)try{if(S.https===!0)S.https=o({...S,to:D.hostname});if(N=await U({...S,to:D.hostname,https:S.https}),!N){if(_("ssl",`Generating new certificates for ${D.hostname}`,S.verbose),await e({...S,from:R.toString(),to:D.hostname,https:S.https}),N=await U({...S,to:D.hostname,https:S.https}),!N)throw Error(`Failed to load SSL configuration after generating certificates for ${D.hostname}`)}}catch(A){throw _("server",`SSL setup failed: ${A}`,S.verbose),A}_("server",`Setting up reverse proxy with SSL config for ${D.hostname}`,S.verbose),await BS({...S,from:S.from||"localhost:5173",to:D.hostname,fromPort:B,sourceUrl:{hostname:R.hostname,host:R.host},ssl:N})}async function NS(S,R,D,B,K,N,A,V,Y,J){_("proxy",`Creating proxy server ${S} -> ${R} with cleanUrls: ${V}`,A);let Q=[{host:R,route:{sourceHost:B.host,cleanUrls:V||!1,changeOrigin:Y||!1,basePath:"/",auth:J}}];if(!IR({routeEntries:Q,listenPort:D,sslConfig:K,originGuard:null,verbose:A??!1}))throw Error(`Failed to start proxy server for ${R} on port ${D}`);YS({from:S,to:R,vitePluginUsage:N,listenPort:D,ssl:!!K,cleanUrls:V,verbose:A})}async function BS(S){_("setup",`Setting up reverse proxy: ${E(S)}`,S.verbose);let{from:R,to:D,sourceUrl:B,ssl:K,verbose:N,cleanup:A,vitePluginUsage:V,changeOrigin:Y,cleanUrls:J}=S,Q=80,Z=443,X="0.0.0.0",W=S.portManager||_S,P=fR(S);try{if(P&&D&&!D.includes("localhost")&&!D.includes("127.0.0.1")){if(!(await f([D],N))[0]){G.warn(`The hostname ${D} isn't in your hosts file. Adding it now...`);try{await y([D],N),G.success(`Added ${D} to your hosts file.`)}catch(L){G.error(`Failed to add ${D} to your hosts file: ${L}`),G.info(`You may need to manually add '127.0.0.1 ${D}' to your /etc/hosts file.`)}}}else if(P&&z.platform!=="darwin"&&D&&D.includes("localhost")&&!D.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await f([D],N))[0]){_("hosts",`${D} not found in hosts file, adding...`,N);try{await y([D],N)}catch(L){_("hosts",`Failed to add ${D} to hosts file: ${L}`,N)}}}if(K&&!W.usedPorts.has(Q)){if(!await C(Q,X,N))_("setup","Starting HTTP redirect server",N),dR(N),W.usedPorts.add(Q);else if(_("setup","Port 80 is in use, skipping HTTP redirect",N),N)G.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let x=K?Z:Q,w=await C(x,X,N),F;if(w){if(_("setup",`Port ${x} is already in use`,N),N)G.warn(`Port ${x} is already in use. This may be another instance of rpx or another service.`);if(x===443){if(F=await W.getNextAvailablePort(3443,!0),_("setup",`Using port ${F} instead of ${x}`,N),N)G.info(`Using port ${F} instead. Access your site at https://${D}:${F}`)}else if(F=await W.getNextAvailablePort(x+1000,!0),_("setup",`Using port ${F} instead of ${x}`,N),N)G.info(`Using port ${F} instead. Access your site at http://${D}:${F}`)}else F=x,W.usedPorts.add(F),_("setup",`Using standard ${x===443?"HTTPS":"HTTP"} port ${x} for ${D}`,N);await NS(R,D,F,B,K,V,N,J,Y,RR(S.auth))}catch(x){_("setup",`Setup failed: ${x}`,N),G.error(`Failed to setup reverse proxy: ${x.message}`),u({domains:[D],hosts:typeof A==="boolean"?A:A?.hosts,certs:typeof A==="boolean"?A:A?.certs,verbose:N,vitePluginUsage:V})}}function dR(S,R=80,D=443,B){_("redirect",`Starting HTTP redirect server on port ${R}`,S);let K=SR.createServer((N,A)=>{if(B&&N.url){let Q=N.url.split("?",1)[0],Z=VR(B,Q);if(Z!=null){_("redirect",`Serving ACME challenge ${Q}`,S),A.writeHead(200,{"content-type":"text/plain"}),A.end(Z);return}}let V=N.headers.host||"",Y=V.includes(":")?V.slice(0,V.indexOf(":")):V,J=D===443?Y:`${Y}:${D}`;_("redirect",`Redirecting request from ${V}${N.url} to https://${J}`,S),A.writeHead(301,{Location:`https://${J}${N.url}`}),A.end()}).listen(R);t.add(K),_("redirect","HTTP redirect server started",S)}function KS(S){let R={...s,...S};if(_("proxy",`Starting proxy with options: ${E(R)}`,R?.verbose),R.viaDaemon){if(!R.from||!R.to){G.error("viaDaemon mode requires both `from` and `to`");return}a({proxies:[{id:R.id,from:R.from,to:R.to,path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}],verbose:R.verbose}).catch((Y)=>{G.error(`Failed to register with rpx daemon: ${Y.message}`),z.exit(1)});return}let D=R.to||"",B=D.split(".").pop()?.toLowerCase()||"",K=z.platform==="darwin"&&D&&!D.includes("localhost")&&!D.includes("127.0.0.1"),N=["dev","app","page","new","day","foo"],A=["test","localhost","local","example","invalid"];if(K&&N.includes(B)&&R?.verbose)G.warn(`The .${B} TLD may not work reliably for local development`),G.info(` Google owns .${B} with HSTS preloading, which can bypass local DNS`),G.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(K)import("./chunk-ybpnwmfx.js").then(({setupDevelopmentDns:Y})=>{Y({domains:[D],verbose:R.verbose}).then((J)=>{if(J)Promise.resolve().then(()=>{if(R.verbose)if(A.includes(B))G.success(`DNS server started for .${B} domains`);else G.success(`DNS server started for .${B} domains (hosts file entry also added)`)});else _("dns",`Could not start DNS server - ${D} may not resolve in browser`,R.verbose)})}).catch((Y)=>{_("dns",`Failed to start DNS server: ${Y}`,R.verbose)});let V={from:R.from,to:R.to,cleanUrls:R.cleanUrls,https:o(R),cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,changeOrigin:R.changeOrigin,verbose:R.verbose,regenerateUntrustedCerts:R.regenerateUntrustedCerts};_("proxy",`Server options: ${E(V)}`,R.verbose),yR(V).catch((Y)=>{_("proxy",`Failed to start proxy: ${Y}`,R.verbose),G.error(`Failed to start proxy: ${Y.message}`),u({domains:[R.to],hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose})})}function AS(S){return S?.verbose||!1}function fR(S){if(S?.hostsManagement===!1)return!1;let R=S?.cleanup;if(R===!1)return!1;if(R&&typeof R==="object"&&R.hosts===!1)return!1;return!0}async function UR(S){let R={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(S)R={...R,...S};let D=AS(R),B=fR(R);if(_("config",`Starting with config: ${E(R,2)}`,D),_("config",`Is multi-proxy? ${"proxies"in R}`,D),_("config",`Hosts management enabled? ${B}`,D),R.viaDaemon){let I="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((M)=>({id:M.id,from:M.from,to:M.to,path:M.path,cleanUrls:M.cleanUrls??R.cleanUrls,changeOrigin:M.changeOrigin??R.changeOrigin,pathRewrites:M.pathRewrites})):[{id:R.id,from:R.from,to:R.to??"rpx.localhost",path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}];await a({proxies:I,verbose:D});return}if("proxies"in R&&Array.isArray(R.proxies)){_("servers",`Found ${R.proxies.length} proxies in config`,D);for(let $ of R.proxies)if($.start){let I=`${$.from}-${$.to}`;try{_("watch",`Starting command for ${I} with command: ${$.start.command}`,D),G.info(`Starting command for ${I}...`),await r.startProcess(I,$.start,D);let M=new URL($.from?.startsWith("http")?$.from:`http://${$.from}`),T=M.hostname||"localhost",b=Number(M.port)||80;try{await h(T,b,D),_("watch",`Dev server is ready at ${T}:${b}`,D)}catch(iR){_("watch",`Connection check failed, but continuing with proxy setup: ${iR}`,D),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw _("watch",`Failed to start command for ${I}: ${M}`,D),Error(`Failed to start command for ${I}: ${M}`)}}else _("watch",`No start command for proxy ${$.from} -> ${$.to}`,D)}else if("start"in R&&R.start){_("watch","Found start command in single proxy config",D);let $=`${R.from}-${R.to}`;try{if(R.start)_("watch",`Starting command: ${R.start.command}`,D),await r.startProcess($,R.start,D);let I=new URL(R.from?.startsWith("http")?R.from:`http://${R.from}`),M=I.hostname||"localhost",T=Number(I.port)||80;try{await h(M,T,D),_("watch",`Dev server is ready at ${M}:${T}`,D)}catch(b){_("watch",`Connection check failed, but continuing with proxy setup: ${b}`,D),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(I){throw _("watch",`Failed to run start command: ${I}`,D),Error(`Failed to run start command: ${I}`)}}else _("watch","No start command found in config",D);let K="proxies"in R&&Array.isArray(R.proxies)?R.proxies[0]?.to:("to"in R)?R.to:"rpx.localhost";if(z.platform!=="win32"&&(R.https||B)){if(!m())try{_("sudo","Pre-acquiring sudo credentials for privileged operations",D),SS("sudo -v",{stdio:"inherit"})}catch{_("sudo","Could not pre-acquire sudo credentials",D)}}let N=[];if(R.productionCerts){if(N=await qR(R.productionCerts,D),N.length>0)_("ssl",`Using ${N.length} production SNI cert(s): ${N.map(($)=>$.serverName).join(", ")}`,D)}if(R.https){let $=N.length>0?null:await U(R);if(!$&&N.length===0){if(_("ssl",`No valid or trusted certificates found for ${K}, generating new ones`,R.verbose),await e(R),$=await U(R),!$)throw Error(`Failed to load SSL certificates after generation for ${K}`)}else _("ssl",`Using existing and trusted certificates for ${K}`,R.verbose);R._cachedSSLConfig=$}let A="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map(($)=>({...$,https:R.https,cleanup:R.cleanup,cleanUrls:$.cleanUrls??("cleanUrls"in R?R.cleanUrls:!1),vitePluginUsage:R.vitePluginUsage,changeOrigin:$.changeOrigin??R.changeOrigin,verbose:D,_cachedSSLConfig:R._cachedSSLConfig})):[{from:"from"in R?R.from:"localhost:5173",to:"to"in R?R.to:"rpx.localhost",cleanUrls:"cleanUrls"in R?R.cleanUrls:!1,https:R.https,cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,start:"start"in R?R.start:void 0,changeOrigin:R.changeOrigin,auth:"auth"in R?R.auth:void 0,verbose:D,_cachedSSLConfig:R._cachedSSLConfig}],V=A.map(($)=>$.to||"rpx.localhost"),Y=N.length>0?N:R._cachedSSLConfig??null,J=V.filter(($)=>$&&!$.includes("localhost")&&!$.includes("127.0.0.1")),Q=["dev","app","page","new","day","foo"],Z=["test","localhost","local","example","invalid"],X=[...new Set(J.map(($)=>$.split(".").pop()?.toLowerCase()))],W=X.filter(($)=>!!$&&Q.includes($));if(W.length>0&&D)G.warn(`The following TLDs may not work reliably for local development: ${W.map(($)=>`.${$}`).join(", ")}`),G.info(" These TLDs have HSTS preloading which can bypass local DNS"),G.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(B&&z.platform==="darwin"&&J.length>0){let{setupDevelopmentDns:$}=await import("./chunk-ybpnwmfx.js");if(await $({domains:J,verbose:D})){if(D)if(X.every((T)=>!!T&&Z.includes(T)))G.success(`DNS server started for ${X.map((T)=>`.${T}`).join(", ")} domains`);else G.success(`DNS server started for ${X.map((T)=>`.${T}`).join(", ")} domains (hosts file entries also added)`)}else _("dns","Could not start DNS server - custom domains may not resolve",D)}let P=async()=>{_("cleanup","Starting cleanup handler",R.verbose);try{let{tearDownDevelopmentDns:$}=await import("./chunk-ybpnwmfx.js");await $({verbose:R.verbose})}catch($){_("cleanup",`Error stopping DNS server: ${$}`,R.verbose)}try{await r.stopAll(R.verbose)}catch($){_("cleanup",`Error stopping processes: ${$}`,R.verbose)}await u({domains:V,hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose||!1})};z.on("SIGINT",P),z.on("SIGTERM",P);let x=R.singlePortMode===!0,w=R.httpsPort??443,F=R.httpPort??80,O=R.originGuard?JR(R.originGuard):null,L=!!Y&&(A.length>1||x),gR=!Y&&x&&A.length>0;if(L&&Y){_("proxies",`Creating shared HTTPS server for ${A.length} domains on port ${w}`,D);let $=await bR(A,B,D);if(!await C(F,"0.0.0.0",D))dR(D,F,w,R.acmeChallengeWebroot);if(await C(w,"0.0.0.0",D)){if(_("proxies",`Port ${w} is already in use, cannot start shared proxy`,D),D)G.warn(`Port ${w} is in use. Shared HTTPS proxy cannot start.`);return}if(!IR({routeEntries:$,listenPort:w,sslConfig:Y,originGuard:O,verbose:D})){G.error(`Shared HTTPS proxy failed to bind :${w}; not exiting`);return}}else if(gR){_("proxies",`Creating shared HTTP server for ${A.length} domains on port ${F}`,D);let $=await bR(A,B,D);if(await C(F,"0.0.0.0",D)){if(_("proxies",`Port ${F} is already in use, cannot start shared proxy`,D),D)G.warn(`Port ${F} is in use. Shared HTTP proxy cannot start.`);return}if(!IR({routeEntries:$,listenPort:F,sslConfig:null,originGuard:O,verbose:D})){G.error(`Shared HTTP proxy failed to bind :${F}; not exiting`);return}}else for(let $ of A)try{let I=$.to||"rpx.localhost";_("proxy",`Starting proxy for ${I} with SSL config: ${!!Y}`,$.verbose),await yR({from:$.from||"localhost:5173",to:I,cleanUrls:$.cleanUrls||!1,https:$.https||!1,cleanup:$.cleanup||!1,vitePluginUsage:$.vitePluginUsage||!1,verbose:$.verbose||!1,_cachedSSLConfig:R._cachedSSLConfig,changeOrigin:$.changeOrigin||!1})}catch(I){_("proxies",`Failed to start proxy for ${$.to}: ${I}`,$.verbose),G.error(`Failed to start proxy for ${$.to}:`,I)}}async function bR(S,R,D){let B=[],K=new Set;for(let N of S){let A=N.to||"rpx.localhost",V=N.cleanUrls||!1,Y=N.path,J=kR(Y),Q=RR(N.auth);if(N.redirect){let Z=MR(N.redirect);B.push({host:A,path:Y,route:{redirect:Z,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → redirect ${Z.status} ${Z.to}${Q?" (auth)":""}`,D)}else if(N.static)B.push({host:A,path:Y,route:{static:xR(N.static,V),cleanUrls:V,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → static ${typeof N.static==="string"?N.static:N.static.dir}${Q?" (auth)":""}`,D);else{let Z=new URL(N.from?.startsWith("http")?N.from:`http://${N.from}`);B.push({host:A,path:Y,route:{sourceHost:Z.host,cleanUrls:V,changeOrigin:N.changeOrigin||!1,pathRewrites:N.pathRewrites,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → ${Z.host}${Q?" (auth)":""}`,D)}if(K.has(A))continue;if(K.add(A),R&&!HR(A)&&!A.includes("localhost")&&!A.includes("127.0.0.1"))try{if(!(await f([A],D))[0])await y([A],D)}catch{_("hosts",`Could not add hosts entry for ${A}`,D)}}return B}function IR(S){let{routeEntries:R,listenPort:D,sslConfig:B,originGuard:K,verbose:N}=S,A=wR(R),V=TR((Q,Z)=>ER(A,Q,Z),N),Y=K?(Q,Z)=>K(Q)??V(Q,Z):V,J=jR(N);try{let Q=Bun.serve({port:D,hostname:"0.0.0.0",reusePort:lR(),...B?{tls:Array.isArray(B)?B.map((Z)=>({serverName:Z.serverName,key:Z.key,cert:Z.cert})):{key:B.key,cert:B.cert,ca:B.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(Z,X){return Y(Z,X)},websocket:J,error(Z){return _("server",`Shared proxy server error: ${Z}`,N),new Response(`Server Error: ${Z.message}`,{status:500})}});return t.add(Q),_("proxies",`Shared ${B?"HTTPS":"HTTP"} proxy listening on port ${D} for ${A.size} domains`,N),Q}catch(Q){return _("proxies",`Failed to start shared proxy: ${Q}`,N),console.error("Failed to start shared proxy:",Q),null}}function YS(S){if(S?.vitePluginUsage||!S?.verbose)return;if(console.log(""),console.log(` ${H.green(H.bold("rpx"))} ${H.green(`v${DS}`)}`),console.log(` ${H.green("➜")} ${H.dim(S?.from??"")} ${H.dim("➜")} ${H.cyan(S?.ssl?`https://${S?.to}`:`http://${S?.to}`)}`),S?.listenPort!==(S?.ssl?443:80))console.log(` ${H.green("➜")} Listening on port ${S?.listenPort}`);if(S?.cleanUrls)console.log(` ${H.green("➜")} Clean URLs enabled`)}var JN=UR;export{NR as writeEntry,YD as watchRegistry,VS as verifyHttpsChain,HS as trustRootCaForBrowsers,yD as tearDownDevelopmentDns,CD as syncDevelopmentDnsFromRegistry,bS as stripBasePath,TD as stopDnsServer,bD as stopDaemon,yR as startServer,KS as startProxy,UR as startProxies,xD as startDnsServer,tS as siteIdForHost,lR as shouldReusePort,wD as setupResolver,qD as setupDevelopmentDns,dS as serverNameFromCertFilename,uS as serveStaticFile,E as safeStringify,vS as safeRelativePath,TN as safeDeleteFile,a as runViaDaemon,hD as runDaemon,HD as resolverFilePath,zD as resolverBasenamesForDomains,WD as resolverBasenameForDomain,xR as resolveStaticRoute,hS as resolveStaticFile,MR as resolveRedirect,xN as resolvePathRewrite,RR as resolveAuth,JD as renderStartingPage,QD as renderFailedPage,fD as removeResolver,ED as removeLegacyTldResolvers,$R as removeHosts,BR as removeEntry,vD as releaseDaemonLock,VN as redactSensitive,UD as reconcileStaleDevelopmentDns,lD as reconcileDevelopmentDnsOnIdle,eS as readSiteManifest,BD as readEntry,LD as readDaemonPid,GS as readCertSha256Fingerprint,JS as readCertCommonName,KD as readAll,VR as readAcmeChallenge,xS as pruneStaleRootCas,sS as projectNameFromHost,_D as portManager,aS as pathPrefixMatches,XS as parseSha256HashesFromSecurityListing,OS as parseHtpasswd,$S as normalizeSha256Fingerprint,kR as normalizePathPrefix,ZD as normalizeDevDomain,GR as matchesWildcard,gS as matchesAllowedSuffix,ER as matchHostRoute,pS as matchHostList,lS as matchHost,yS as loadSSLConfig,SD as listDiscoverableSites,MS as listCertSha256HashesByCommonName,HR as isWildcardPattern,ZN as isValidRootCA,_R as isValidId,FN as isSingleProxyOptions,MN as isSingleProxyConfig,TS as isRootCaTrustedForSsl,jS as isRootCaFingerprintInKeychains,mR as isProcessElevated,C as isPortInUse,ND as isPidAlive,IN as isMultiProxyOptions,zN as isMultiProxyConfig,iS as isLikelyHostname,jD as isDnsServerRunning,cD as isDaemonRunning,PS as isCertTrusted,o as httpsConfig,m as getSudoPassword,CS as getSharedDaemonCertPaths,qS as getRootCAPaths,DR as getRegistryDir,WN as getPrimaryDomain,FS as getMacosTrustKeychains,IS as getMacosLoginKeychainPath,PD as getDaemonRpxDir,OD as getDaemonPidPath,e as generateCertificate,AD as gcStaleEntries,fS as forceTrustCertificate,DD as findAvailablePort,XN as extractHostname,rS as expandHome,QN as execSudoSync,GD as escapeHtml,KR as ensureDaemonRunning,LS as enforceBasicAuth,wS as devSslToSniEntries,ID as devDomainsFromHosts,oS as detectProjectPreset,LR as deriveIdFromTarget,uD as defaultDaemonSpawnCommand,s as defaultConfig,JN as default,_ as debugLog,RD as createSiteResolver,jR as createProxyWebSocketHandler,TR as createProxyFetchHandler,JR as createOriginGuard,mS as contentTypeFor,kD as contentLooksLikeRpxResolver,s as config,H as colors,US as clearSslConfigCache,FR as cleanupCertificates,u as cleanup,f as checkHosts,U as checkExistingCertificates,QS as certIncludesSanHostnames,qR as buildSniTlsConfig,ES as buildRegistryTlsProxyOptions,cS as buildRedirectLocation,wR as buildHostRoutes,y as addHosts,mD as acquireDaemonLock,$D as SiteSupervisor,kS as SHARED_DEV_HOST_CERT_PATH,zS as RPX_ROOT_CA_COMMON_NAME,MD as RPX_RESOLVER_MARKER,nS as OnDemandCertManager,WS as MACOS_SYSTEM_KEYCHAIN,ZS as MACOS_CA_TRUST_FLAGS,XD as LEGACY_TLD_RESOLVER_LABELS,CR as DefaultPortManager,VD as DNS_STATE_VERSION,FD as DNS_PORT,QR as ACME_CHALLENGE_PREFIX};
@@ -2,6 +2,14 @@ import type { PathRewrite } from './types';
2
2
  import type { ResolvedAuth } from './auth';
3
3
  import type { ResolvedRedirect } from './redirect';
4
4
  import type { ResolvedStaticRoute } from './static-files';
5
+ /**
6
+ * Cap on client→upstream frames buffered *before the upstream WebSocket opens*.
7
+ * Without it, a fast client (or an upstream that never opens) grows `pending`
8
+ * without bound until the gateway OOMs. Beyond the cap the client socket is
9
+ * closed with 1009 (message too big). Override with `RPX_MAX_WS_PENDING_BYTES`;
10
+ * read once per handler so tests (and reloads) can pick up a new value.
11
+ */
12
+ export declare function wsPendingCapBytes(): number;
5
13
  /**
6
14
  * Strip the route's mount prefix (`basePath`) from a request pathname so a
7
15
  * target mounted under `/docs` sees `/` for `/docs` and `/guide` for
@@ -73,7 +73,7 @@ declare class Conn {
73
73
  * the trade nginx makes, and the reason it stays up under load.
74
74
  */
75
75
  declare class UpstreamPool {
76
- constructor(host: string, port: number, maxTotal: number);
76
+ constructor(host: string, port: number, maxTotal: number, key?: string);
77
77
  dial(): Promise<Conn>;
78
78
  acquireIdleSync(): Conn | null;
79
79
  acquireOrDial(): Promise<Conn>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/rpx",
3
3
  "type": "module",
4
- "version": "0.11.21",
4
+ "version": "0.11.22",
5
5
  "description": "A modern and smart reverse proxy.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",