@stacksjs/rpx 0.11.25 → 0.11.27
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 +1 -1
- package/dist/index.js +3 -3
- package/package.json +1 -1
package/dist/bin/cli.js
CHANGED
|
@@ -315,6 +315,6 @@ Run \`${this.name??"cli"} --help\` for usage.`;Bw.stderr.write(`${J}${X}${U}
|
|
|
315
315
|
`),X=!1,J=A.filter((W)=>{if($.some((z)=>W.includes(` ${z}`)&&(W.includes("127.0.0.1")||W.includes("::1"))))return X=!0,!1;if(W.trim()==="# Added by rpx")return X=!0,!1;return!0});if(!X){N("hosts","No matching hosts found to remove",w);return}while(J[J.length-1]?.trim()==="")J.pop();let U=`${J.join(`
|
|
316
316
|
`)}
|
|
317
317
|
`,B=Aj.join(b6.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await gw.promises.writeFile(B,U,"utf8"),await r8(`cat "${B}" | tee "${G$}" > /dev/null`),N("hosts","Hosts removed successfully",w)}catch(W){N("hosts","Could not clean up hosts file automatically",w)}finally{try{await gw.promises.unlink(B)}catch(W){N("hosts",`Failed to remove temporary file: ${W}`,w)}}}catch(Y){N("hosts",`Failed to clean up hosts file: ${Y.message}`,w)}}async function oY($,w){N("hosts",`Checking hosts: ${$}`,w);let Y;try{Y=await gw.promises.readFile(G$,"utf-8")}catch(A){N("hosts",`Error reading hosts file: ${A}`,w);try{let X=uw(),J;if(X)J=`echo '${X}' | sudo -S cat "${G$}" 2>/dev/null`;else J=`sudo -n cat "${G$}" 2>/dev/null || cat "${G$}" 2>/dev/null || echo ""`;let{stdout:U}=await tY(J);Y=U}catch(X){return N("hosts",`Cannot read hosts file, assuming entries don't exist: ${X}`,w),$.map(()=>!1)}}return $.map((A)=>{let X=`127.0.0.1 ${A}`,J=`::1 ${A}`;return Y.includes(X)||Y.includes(J)})}V8();SB();i$();X0();import{spawn as oM}from"node:child_process";import*as t8 from"node:process";class a8{processes=new Map;isShuttingDown=!1;async startProcess($,w,Y){if(this.processes.has($)){N("start",`Process ${$} is already running`,Y);return}let[A,...X]=w.command.split(" "),J=w.cwd||t8.cwd();N("start",`Starting process ${$}:`,Y),N("start",` Command: ${A} ${X.join(" ")}`,Y),N("start",` Working directory: ${J}`,Y),N("start",` Environment variables: ${R$(w.env)}`,Y);let U=oM(A,X,{cwd:J,env:{...t8.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:J,process:U,env:w.env}),new Promise((B,W)=>{if(U.on("error",(j)=>{if(!this.isShuttingDown)N("start",`Process ${$} failed to start: ${j}`,Y),this.processes.delete($),W(j)}),U.on("exit",(j)=>{if(!this.isShuttingDown&&j!==null&&j!==0)N("start",`Process ${$} exited with code ${j}; leaving the proxy running`,Y),this.processes.delete($),W(Error(`Process ${$} exited with code ${j}`))}),Y)U.stdout?.on("data",(j)=>{N("process",`[${$}] ${j.toString().trim()}`,!0)}),U.stderr?.on("data",(j)=>{N("process",`[${$}] ERR: ${j.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),W(Error(`Process ${$} was killed during startup`));else N("start",`Process ${$} started successfully`,Y),B()},1000)})}async stopProcess($,w){let Y=this.processes.get($);if(!Y?.process){N("start",`No process found for ${$}`,w);return}return N("start",`Stopping process ${$}`,w),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete($),N("start",`Process ${$} stopped`,w),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){N("start",`Force killing process ${$}`,w);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){N("start",`Error stopping process ${$}: ${X}`,w),this.processes.delete($),A()}})}async stopAll($){if(this.isShuttingDown){N("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,N("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,$).catch((A)=>{R.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var l_=new a8;import{timingSafeEqual as eM}from"node:crypto";function $4($,w){if($==null)return!1;let Y=Buffer.from($),A=Buffer.from(w);if(Y.length!==A.length)return!1;return eM(Y,A)}function s8($){return $.toLowerCase().replace(/\.$/,"")}var w4=["/.well-known/acme-challenge/"];function Y4($){let w=$.headers.get("host");if(w)return s8(w.split(":")[0]);try{return s8(new URL($.url).hostname)}catch{return""}}function v6($){let w=$.header.toLowerCase(),Y=new Set,A=[];for(let W of $.hosts){let j=s8(W);if(j.startsWith("*."))A.push(j);else Y.add(j)}let X=$.exemptPaths??w4,J=$.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
|
|
318
|
-
`,U=(W)=>{let j=s8(W);return Y.has(j)||A.some((z)=>NY(j,z))},B=(W)=>{let j=Y4(W);if(!U(j))return;let z="/";try{z=new URL(W.url).pathname}catch{}if(X.some((G)=>z.startsWith(G)))return;if($4(W.headers.get(w),$.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return B.protects=U,B}L8();O8();DY();vY();S8();bY();X0();var e8=new a8,X4="0.12.0",J4=new h8("0.0.0.0"),$J=new Set,wJ=new Set,Xj=!1,o8=null,Jj=null;async function AJ($){if(Xj)return N("cleanup","Cleanup already in progress, skipping",$?.verbose),Jj||Promise.resolve();Xj=!0,N("cleanup","Starting cleanup process",$?.verbose),Jj=new Promise((w)=>{o8=w});try{await e8.stopAll($?.verbose),R.info("Shutting down proxy servers...");let w=[],Y=Array.from($J).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),N("cleanup","Bun server stopped",$?.verbose),X();else if(typeof J.close==="function")J.close(()=>{N("cleanup","Server closed successfully",$?.verbose),X()});else X()}catch(U){N("cleanup",`Error stopping server: ${U}`,$?.verbose),X()}}));w.push(...Y),$J.clear();for(let A of wJ)d1(A);if(wJ.clear(),$?.hosts&&$.domains?.length){N("cleanup","Cleaning up hosts file entries",$?.verbose),N("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let A=$.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(N("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,$?.verbose),A.length>0)R.info("Cleaning up hosts file entries..."),w.push(u6(A,$?.verbose).then(()=>{N("cleanup",`Removed hosts entries for ${A.join(", ")}`,$?.verbose)}).catch((X)=>{N("cleanup",`Failed to remove hosts entries: ${X}`,$?.verbose),R.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if($?.certs&&$.domains?.length){N("cleanup","Cleaning up SSL certificates",$?.verbose),R.info("Cleaning up SSL certificates...");let A=$.domains.map(async(X)=>{try{await f5(X,$?.verbose),N("cleanup",`Removed certificates for ${X}`,$?.verbose)}catch(J){N("cleanup",`Failed to remove certificates for ${X}: ${J}`,$?.verbose),R.warn(`Failed to clean up certificates for ${X}:`,J)}});w.push(...A)}await Promise.allSettled(w),N("cleanup","All cleanup tasks completed successfully",$?.verbose),R.success("All cleanup tasks completed successfully")}catch(w){N("cleanup",`Error during cleanup: ${w}`,$?.verbose),R.error("Error during cleanup:",w)}finally{if(o8)o8();o8=null,Xj=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(J0.env.NODE_ENV!=="test"&&J0.env.BUN_ENV!=="test"&&!w)J0.exit(0)}return Jj}var Uj=!1;function m6($){if(Uj){N("signal",`Received second ${$} signal, forcing exit`,!0),J0.exit(1);return}Uj=!0,N("signal",`Received ${$} signal, initiating cleanup`,!0),AJ().catch((w)=>{N("signal",`Cleanup failed after ${$}: ${w}`,!0),J0.exit(1)}).finally(()=>{Uj=!1})}J0.once("SIGINT",()=>m6("SIGINT"));J0.once("SIGTERM",()=>m6("SIGTERM"));J0.on("uncaughtException",($)=>{R.error("Uncaught exception (continuing):",$)});J0.on("unhandledRejection",($)=>{R.error("Unhandled rejection (continuing):",$)});async function eY($,w,Y,A=5){N("connection",`Testing connection to ${$}:${w} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(J0.env.RPX_BYPASS_CONNECTION_TEST==="true"){N("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((B,W)=>{let j=i6.connect({host:$,port:w,timeout:3000});j.once("connect",()=>{N("connection",`Successfully connected to ${$}:${w}`,Y),j.end(),B()}),j.once("timeout",()=>{N("connection",`Connection to ${$}:${w} timed out`,Y),j.destroy(),W(Error("Connection timed out"))}),j.once("error",(z)=>{N("connection",`Failed to connect to ${$}:${w}: ${z}`,Y),j.destroy(),W(z)})});try{await U()}catch(B){let W=B;if(Date.now()-J>X){N("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),R.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&A>0)return N("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),eY($,w,Y,A-1);if(A>0)try{N("connection",`Trying HTTP request to ${$}:${w}`,Y),await new Promise((z,G)=>{let K=YJ.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(F)=>{N("connection",`Received HTTP response with status: ${F.statusCode}`,Y),z()});K.on("error",(F)=>G(F)),K.on("timeout",()=>{K.destroy(),G(Error("HTTP request timed out"))}),K.end()}),N("connection",`HTTP request to ${$}:${w} succeeded`,Y);return}catch(z){return N("connection",`HTTP request to ${$}:${w} failed: ${z}`,Y),N("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((G)=>setTimeout(G,2000)),eY($,w,Y,A-1)}let j=`Failed to connect to ${$}:${w} after ${5-A} attempts: ${W.message}`;N("connection",`${j}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),R.warn(j),R.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 g6($){N("server",`Starting server with options: ${R$($)}`,$.verbose);let w=Rw($.from),Y=new URL(w.startsWith("http")?w:`http://${w}`),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),X=Number.parseInt(Y.port)||(Y.protocol.includes("https:")?443:80),J=[A.hostname];if(Bj($)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){N("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await oY(J,$.verbose))[0]){R.info(`Adding ${A.hostname} to hosts file...`),R.info("This may require sudo/administrator privileges");try{await sY(J,$.verbose)}catch(W){if(R.error("Failed to add hosts entry:",W.message),R.warn("You can manually add this entry to your hosts file:"),R.warn(`127.0.0.1 ${A.hostname}`),R.warn(`::1 ${A.hostname}`),J0.platform==="win32")R.warn("On Windows:"),R.warn("1. Run notepad as administrator"),R.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else R.warn("On Unix systems:"),R.warn("sudo nano /etc/hosts")}}else N("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(B){R.error("Failed to check hosts file:",B.message)}}try{await eY(Y.hostname,X,$.verbose)}catch(B){N("server",`Connection test failed: ${B}`,$.verbose),R.error(B.message),R.warn("Continuing with proxy setup despite connection test failure..."),R.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=ZY({...$,to:A.hostname});if(U=await Yw({...$,to:A.hostname,https:$.https}),!U){if(N("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await i1({...$,from:Y.toString(),to:A.hostname,https:$.https}),U=await Yw({...$,to:A.hostname,https:$.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(B){throw N("server",`SSL setup failed: ${B}`,$.verbose),B}N("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await W4({...$,from:w,originalFrom:$.from||w,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function U4($,w,Y,A,X,J,U,B,W,j,z,G){N("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${B}`,U);let K=m1(z??A.host,G);g1(K);let F=[{host:w,route:{sourceHost:A.host,upstreamPool:K,cleanUrls:B||!1,changeOrigin:W||!1,basePath:"/",auth:j}}];if(!Wj({routeEntries:F,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw d1(K),Error(`Failed to start proxy server for ${w} on port ${Y}`);wJ.add(K),j4({from:$,to:w,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:B,verbose:U})}async function W4($){N("setup",`Setting up reverse proxy: ${R$($)}`,$.verbose);let{from:w,originalFrom:Y,to:A,sourceUrl:X,ssl:J,verbose:U,cleanup:B,vitePluginUsage:W,changeOrigin:j,cleanUrls:z}=$,G=80,K=443,F="0.0.0.0",T=$.portManager||J4,q=Bj($);try{if(q&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await oY([A],U))[0]){R.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await sY([A],U),R.success(`Added ${A} to your hosts file.`)}catch(V){R.error(`Failed to add ${A} to your hosts file: ${V}`),R.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(q&&J0.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await oY([A],U))[0]){N("hosts",`${A} not found in hosts file, adding...`,U);try{await sY([A],U)}catch(V){N("hosts",`Failed to add ${A} to hosts file: ${V}`,U)}}}if(J&&!T.usedPorts.has(G)){if(!await Iw(G,F,U))N("setup","Starting HTTP redirect server",U),d6(U),T.usedPorts.add(G);else if(N("setup","Port 80 is in use, skipping HTTP redirect",U),U)R.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let E=J?K:G,f=await Iw(E,F,U),M;if(f){if(N("setup",`Port ${E} is already in use`,U),U)R.warn(`Port ${E} is already in use. This may be another instance of rpx or another service.`);if(E===443){if(M=await T.getNextAvailablePort(3443,!0),N("setup",`Using port ${M} instead of ${E}`,U),U)R.info(`Using port ${M} instead. Access your site at https://${A}:${M}`)}else if(M=await T.getNextAvailablePort(E+1000,!0),N("setup",`Using port ${M} instead of ${E}`,U),U)R.info(`Using port ${M} instead. Access your site at http://${A}:${M}`)}else M=E,T.usedPorts.add(M),N("setup",`Using standard ${E===443?"HTTPS":"HTTP"} port ${E} for ${A}`,U);await U4(w,A,M,X,J,W,U,z,j,l1($.auth),Y,$.loadBalancer)}catch(E){N("setup",`Setup failed: ${E}`,U),R.error(`Failed to setup reverse proxy: ${E.message}`),AJ({domains:[A],hosts:typeof B==="boolean"?B:B?.hosts,certs:typeof B==="boolean"?B:B?.certs,verbose:U,vitePluginUsage:W})}}function d6($,w=80,Y=443,A){N("redirect",`Starting HTTP redirect server on port ${w}`,$);let X=YJ.createServer((J,U)=>{if(A&&J.url){let z=J.url.split("?",1)[0],G=uY(A,z);if(G!=null){N("redirect",`Serving ACME challenge ${z}`,$),U.writeHead(200,{"content-type":"text/plain"}),U.end(G);return}}let B=J.headers.host||"",W=B.includes(":")?B.slice(0,B.indexOf(":")):B,j=Y===443?W:`${W}:${Y}`;N("redirect",`Redirecting request from ${B}${J.url} to https://${j}`,$),U.writeHead(301,{Location:`https://${j}${J.url}`}),U.end()}).listen(w);$J.add(X),N("redirect","HTTP redirect server started",$)}function l6($){let w={...IW,...$};if(N("proxy",`Starting proxy with options: ${R$(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){R.error("viaDaemon mode requires both `from` and `to`");return}wj({proxies:[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((W)=>{R.error(`Failed to register with rpx daemon: ${W.message}`),J0.exit(1)});return}let Y=w.to||"",A=Y.split(".").pop()?.toLowerCase()||"",X=J0.platform==="darwin"&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1"),J=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(X&&J.includes(A)&&w?.verbose)R.warn(`The .${A} TLD may not work reliably for local development`),R.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),R.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (wY(),c8)).then(({setupDevelopmentDns:W})=>{W({domains:[Y],verbose:w.verbose}).then((j)=>{if(j)Promise.resolve().then(()=>{if(w.verbose)if(U.includes(A))R.success(`DNS server started for .${A} domains`);else R.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else N("dns",`Could not start DNS server - ${Y} may not resolve in browser`,w.verbose)})}).catch((W)=>{N("dns",`Failed to start DNS server: ${W}`,w.verbose)});let B={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:ZY(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};N("proxy",`Server options: ${R$(B)}`,w.verbose),g6(B).catch((W)=>{N("proxy",`Failed to start proxy: ${W}`,w.verbose),R.error(`Failed to start proxy: ${W.message}`),AJ({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function B4($){return $?.verbose||!1}function Bj($){if($?.hostsManagement===!1)return!1;let w=$?.cleanup;if(w===!1)return!1;if(w&&typeof w==="object"&&w.hosts===!1)return!1;return!0}async function n6($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let Y=B4(w),A=Bj(w);if(N("config",`Starting with config: ${R$(w,2)}`,Y),N("config",`Is multi-proxy? ${"proxies"in w}`,Y),N("config",`Hosts management enabled? ${A}`,Y),w.viaDaemon){let I="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((O)=>({id:O.id,from:O.from,to:O.to,path:O.path,cleanUrls:O.cleanUrls??w.cleanUrls,changeOrigin:O.changeOrigin??w.changeOrigin,pathRewrites:O.pathRewrites})):[{id:w.id,from:w.from,to:w.to??"rpx.localhost",path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await wj({proxies:I,verbose:Y});return}if("proxies"in w&&Array.isArray(w.proxies)){N("servers",`Found ${w.proxies.length} proxies in config`,Y);for(let H of w.proxies)if(H.start){let I=`${H.from}-${H.to}`;try{N("watch",`Starting command for ${I} with command: ${H.start.command}`,Y),R.info(`Starting command for ${I}...`),await e8.startProcess(I,H.start,Y);let O=Rw(H.from),Z=new URL(O.startsWith("http")?O:`http://${O}`),P0=Z.hostname||"localhost",Z$=Number(Z.port)||80;try{await eY(P0,Z$,Y),N("watch",`Dev server is ready at ${P0}:${Z$}`,Y)}catch(h$){N("watch",`Connection check failed, but continuing with proxy setup: ${h$}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(O){throw N("watch",`Failed to start command for ${I}: ${O}`,Y),Error(`Failed to start command for ${I}: ${O}`)}}else N("watch",`No start command for proxy ${H.from} -> ${H.to}`,Y)}else if("start"in w&&w.start){N("watch","Found start command in single proxy config",Y);let H=`${w.from}-${w.to}`;try{if(w.start)N("watch",`Starting command: ${w.start.command}`,Y),await e8.startProcess(H,w.start,Y);let I=Rw(w.from),O=new URL(I.startsWith("http")?I:`http://${I}`),Z=O.hostname||"localhost",P0=Number(O.port)||80;try{await eY(Z,P0,Y),N("watch",`Dev server is ready at ${Z}:${P0}`,Y)}catch(Z$){N("watch",`Connection check failed, but continuing with proxy setup: ${Z$}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(I){throw N("watch",`Failed to run start command: ${I}`,Y),Error(`Failed to run start command: ${I}`)}}else N("watch","No start command found in config",Y);let X="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(J0.platform!=="win32"&&(w.https||A)){if(!uw())try{N("sudo","Pre-acquiring sudo credentials for privileged operations",Y),A4("sudo -v",{stdio:"inherit"})}catch{N("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if(w.productionCerts){if(J=await a1(w.productionCerts,Y),J.length>0)N("ssl",`Using ${J.length} production SNI cert(s): ${J.map((H)=>H.serverName).join(", ")}`,Y)}if(w.https){let H=J.length>0?null:await Yw(w);if(!H&&J.length===0){if(N("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,w.verbose),await i1(w),H=await Yw(w),!H)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else N("ssl",`Using existing and trusted certificates for ${X}`,w.verbose);w._cachedSSLConfig=H}let U="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({...H,https:w.https,cleanup:w.cleanup,cleanUrls:H.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:H.changeOrigin??w.changeOrigin,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,auth:"auth"in w?w.auth:void 0,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig}],B=U.map((H)=>H.to||"rpx.localhost"),W=J.length>0?J:w._cachedSSLConfig??null,j=B.filter((H)=>H&&!H.includes("localhost")&&!H.includes("127.0.0.1")),z=["dev","app","page","new","day","foo"],G=["test","localhost","local","example","invalid"],K=[...new Set(j.map((H)=>H.split(".").pop()?.toLowerCase()))],F=K.filter((H)=>!!H&&z.includes(H));if(F.length>0&&Y)R.warn(`The following TLDs may not work reliably for local development: ${F.map((H)=>`.${H}`).join(", ")}`),R.info(" These TLDs have HSTS preloading which can bypass local DNS"),R.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&J0.platform==="darwin"&&j.length>0){let{setupDevelopmentDns:H}=await Promise.resolve().then(() => (wY(),c8));if(await H({domains:j,verbose:Y})){if(Y)if(K.every((Z)=>!!Z&&G.includes(Z)))R.success(`DNS server started for ${K.map((Z)=>`.${Z}`).join(", ")} domains`);else R.success(`DNS server started for ${K.map((Z)=>`.${Z}`).join(", ")} domains (hosts file entries also added)`)}else N("dns","Could not start DNS server - custom domains may not resolve",Y)}let T=async()=>{N("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:H}=await Promise.resolve().then(() => (wY(),c8));await H({verbose:w.verbose})}catch(H){N("cleanup",`Error stopping DNS server: ${H}`,w.verbose)}try{await e8.stopAll(w.verbose)}catch(H){N("cleanup",`Error stopping processes: ${H}`,w.verbose)}await AJ({domains:B,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};J0.on("SIGINT",T),J0.on("SIGTERM",T);let q=w.singlePortMode===!0,E=w.httpsPort??443,f=w.httpPort??80,M=w.originGuard?v6(w.originGuard):null,Q=!!W&&(U.length>1||q),V=!W&&q&&U.length>0;if(Q&&W){N("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${E}`,Y);let H=await c6(U,A,Y);if(!await Iw(f,"0.0.0.0",Y))d6(Y,f,E,w.acmeChallengeWebroot);if(await Iw(E,"0.0.0.0",Y)){if(N("proxies",`Port ${E} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${E} is in use. Shared HTTPS proxy cannot start.`);return}if(!Wj({routeEntries:H,listenPort:E,sslConfig:W,originGuard:M,verbose:Y})){R.error(`Shared HTTPS proxy failed to bind :${E}; not exiting`);return}}else if(V){N("proxies",`Creating shared HTTP server for ${U.length} domains on port ${f}`,Y);let H=await c6(U,A,Y);if(await Iw(f,"0.0.0.0",Y)){if(N("proxies",`Port ${f} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${f} is in use. Shared HTTP proxy cannot start.`);return}if(!Wj({routeEntries:H,listenPort:f,sslConfig:null,originGuard:M,verbose:Y})){R.error(`Shared HTTP proxy failed to bind :${f}; not exiting`);return}}else for(let H of U)try{let I=H.to||"rpx.localhost";N("proxy",`Starting proxy for ${I} with SSL config: ${!!W}`,H.verbose),await g6({from:H.from||"localhost:5173",to:I,cleanUrls:H.cleanUrls||!1,https:H.https||!1,cleanup:H.cleanup||!1,vitePluginUsage:H.vitePluginUsage||!1,verbose:H.verbose||!1,_cachedSSLConfig:w._cachedSSLConfig,changeOrigin:H.changeOrigin||!1,loadBalancer:H.loadBalancer,auth:H.auth,path:H.path,pathRewrites:H.pathRewrites})}catch(I){N("proxies",`Failed to start proxy for ${H.to}: ${I}`,H.verbose),R.error(`Failed to start proxy for ${H.to}:`,I)}}async function c6($,w,Y){let A=[],X=new Set;for(let J of $){let U=J.to||"rpx.localhost",B=J.cleanUrls||!1,W=J.path,j=Q$(W),z=l1(J.auth);if(J.redirect){let G=D5(J.redirect);A.push({host:U,path:W,route:{redirect:G,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → redirect ${G.status} ${G.to}${z?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:W,route:{static:PY(J.static,B),cleanUrls:B,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${z?" (auth)":""}`,Y);else{let G=Rw(J.from),K=new URL(G.startsWith("http")?G:`http://${G}`),F=m1(J.from??K.host,J.loadBalancer);g1(F),wJ.add(F),A.push({host:U,path:W,route:{sourceHost:K.host,upstreamPool:F,cleanUrls:B,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → ${K.host}${z?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),w&&!B1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await oY([U],Y))[0])await sY([U],Y)}catch{N("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}function Wj($){let{routeEntries:w,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=$,U=r1(w),B=n1((z,G)=>t1(U,z,G),J),W=X?(z,G)=>X(z)??B(z,G):B,j=p1(J);try{let z=Bun.serve({port:Y,hostname:"0.0.0.0",reusePort:P1(),...A?{tls:Array.isArray(A)?A.map((G)=>({serverName:G.serverName,key:G.key,cert:G.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(G,K){return W(G,K)},websocket:j,error(G){return N("server",`Shared proxy server error: ${G}`,J),new Response(`Server Error: ${G.message}`,{status:500})}});return $J.add(z),N("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),z}catch(z){return N("proxies",`Failed to start shared proxy: ${z}`,J),console.error("Failed to start shared proxy:",z),null}}function j4($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${_$.green(_$.bold("rpx"))} ${_$.green(`v${X4}`)}`),console.log(` ${_$.green("➜")} ${_$.dim($?.from??"")} ${_$.dim("➜")} ${_$.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${_$.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${_$.green("➜")} Clean URLs enabled`)}WB();var MS=new bw("rpx",{showTags:!1});function p6($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}x0.chdir(G4(z4(K4(import.meta.url)),".."));var u0=new EJ("rpx"),r6="0.12.0";u0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async($)=>{if(!$?.from||!$.to)return n6(W1);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,singlePortMode:$.singlePortMode||!1,httpPort:$.httpPort!==void 0?Number($.httpPort):void 0,httpsPort:$.httpsPort!==void 0?Number($.httpsPort):void 0,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let Y={command:$.startCommand};if($.startCwd)Y.cwd=$.startCwd;if($.startEnv)try{Y.env=JSON.parse($.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),x0.exit(1)}w.start=Y}return l6(w)});u0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let Y=p6(W1)?W1.proxies.find((A)=>A.to===$||`${A.from}-${A.to}`===$):W1.to===$?W1:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${$}`),x0.exit(1);try{await n8.startProcess($,Y.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(A){console.error(`Failed to start dev server for ${$}:`,A),x0.exit(1)}});u0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await n8.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(Y){console.error(`Failed to stop dev server for ${$}:`,Y),x0.exit(1)}});u0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await n8.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),x0.exit(1)}});async function t6($){let Y={...(await a9().catch(()=>null))?.onDemand??{},enabled:!0};if($){let A=$.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}u0.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async($)=>{try{let w=$.onDemand?await t6($.roots):void 0;await(await y6({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,workers:$.workers===void 0?void 0:typeof $.workers==="string"?Number.parseInt($.workers,10):$.workers,onDemandSites:w,verbose:$.verbose??!0})).done,x0.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),x0.exit(1)}});u0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,Y=await O6({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!Y.stopped&&Y.pid===null){console.log("rpx daemon is not running");return}if(!Y.stopped){console.log(`rpx daemon pid=${Y.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${Y.pid} stopped${Y.forced?" (SIGKILL)":""}`)});u0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??w$(),Y=await Qw(w),A=await d8(w),X=$.registryDir,J=await $j(X).catch(()=>[]);if($.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:yw(w),rpxDir:w,registryDir:X??mw(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${yw(w)} \u2192 pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${yw(w)}`);if(console.log(`registry: ${X??mw()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let B=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} \u2192 ${U.from} (id=${U.id}${B})`)}});u0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),x0.exit(1);if(!XY($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),x0.exit(1);try{await h6({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),x0.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await L6({rpxDir:$.rpxDir,verbose:$.verbose}),Y=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${Y} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),x0.exit(1)}});u0.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async($,w)=>{if(!XY($))console.error(`invalid id: ${JSON.stringify($)}`),x0.exit(1);let Y=await eB($,w.registryDir,w.verbose);if(!Y){console.log(`no registry entry for id=${$}`);return}await k6($,w.registryDir,w.verbose),console.log(`unregistered ${Y.to} (id=${$})`)});u0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??w$();if(await d8(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await _6({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});u0.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async($)=>{let w=await t6($.roots),Y=wz(w),A=await $j($.registryDir).catch(()=>[]),X=new Set(A.map((B)=>B.to)),J=Y.map((B)=>({host:B.host,dir:B.dir,command:B.command,source:B.source,live:X.has(B.host)}));if($.json){console.log(JSON.stringify(J,null,2));return}let U=w.roots??["~/Code"];if(J.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${U.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${J.length}) \u2014 scanned ${U.join(", ")}:`);for(let B of J)console.log(` ${B.live?"\u25CF":"\u25CB"} https://${B.host} ${B.live?"(live)":"(idle)"}`),console.log(` ${B.command} ${B.dir}`)});u0.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async($,w)=>{let{readFile:Y}=await import("fs/promises"),{join:A}=await import("path"),X=w.rpxDir??w$(),J=A(X,"sites",`${dA($.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${$} (it may not have been booted yet) \u2014 looked in ${J}`);return}let B=w.lines===void 0?void 0:typeof w.lines==="string"?Number.parseInt(w.lines,10):w.lines,W=U.split(`
|
|
318
|
+
`,U=(W)=>{let j=s8(W);return Y.has(j)||A.some((z)=>NY(j,z))},B=(W)=>{let j=Y4(W);if(!U(j))return;let z="/";try{z=new URL(W.url).pathname}catch{}if(X.some((G)=>z.startsWith(G)))return;if($4(W.headers.get(w),$.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return B.protects=U,B}L8();O8();DY();vY();S8();bY();X0();var e8=new a8,X4="0.12.0",J4=new h8("0.0.0.0"),$J=new Set,wJ=new Set,Xj=!1,o8=null,Jj=null;async function AJ($){if(Xj)return N("cleanup","Cleanup already in progress, skipping",$?.verbose),Jj||Promise.resolve();Xj=!0,N("cleanup","Starting cleanup process",$?.verbose),Jj=new Promise((w)=>{o8=w});try{await e8.stopAll($?.verbose),R.info("Shutting down proxy servers...");let w=[],Y=Array.from($J).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),N("cleanup","Bun server stopped",$?.verbose),X();else if(typeof J.close==="function")J.close(()=>{N("cleanup","Server closed successfully",$?.verbose),X()});else X()}catch(U){N("cleanup",`Error stopping server: ${U}`,$?.verbose),X()}}));w.push(...Y),$J.clear();for(let A of wJ)d1(A);if(wJ.clear(),$?.hosts&&$.domains?.length){N("cleanup","Cleaning up hosts file entries",$?.verbose),N("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let A=$.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(N("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,$?.verbose),A.length>0)R.info("Cleaning up hosts file entries..."),w.push(u6(A,$?.verbose).then(()=>{N("cleanup",`Removed hosts entries for ${A.join(", ")}`,$?.verbose)}).catch((X)=>{N("cleanup",`Failed to remove hosts entries: ${X}`,$?.verbose),R.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if($?.certs&&$.domains?.length){N("cleanup","Cleaning up SSL certificates",$?.verbose),R.info("Cleaning up SSL certificates...");let A=$.domains.map(async(X)=>{try{await f5(X,$?.verbose),N("cleanup",`Removed certificates for ${X}`,$?.verbose)}catch(J){N("cleanup",`Failed to remove certificates for ${X}: ${J}`,$?.verbose),R.warn(`Failed to clean up certificates for ${X}:`,J)}});w.push(...A)}await Promise.allSettled(w),N("cleanup","All cleanup tasks completed successfully",$?.verbose),R.success("All cleanup tasks completed successfully")}catch(w){N("cleanup",`Error during cleanup: ${w}`,$?.verbose),R.error("Error during cleanup:",w)}finally{if(o8)o8();o8=null,Xj=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(J0.env.NODE_ENV!=="test"&&J0.env.BUN_ENV!=="test"&&!w)J0.exit(0)}return Jj}var Uj=!1;function m6($){if(Uj){N("signal",`Received second ${$} signal, forcing exit`,!0),J0.exit(1);return}Uj=!0,N("signal",`Received ${$} signal, initiating cleanup`,!0),AJ().catch((w)=>{N("signal",`Cleanup failed after ${$}: ${w}`,!0),J0.exit(1)}).finally(()=>{Uj=!1})}J0.once("SIGINT",()=>m6("SIGINT"));J0.once("SIGTERM",()=>m6("SIGTERM"));J0.on("uncaughtException",($)=>{R.error("Uncaught exception (continuing):",$)});J0.on("unhandledRejection",($)=>{R.error("Unhandled rejection (continuing):",$)});async function eY($,w,Y,A=5){N("connection",`Testing connection to ${$}:${w} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(J0.env.RPX_BYPASS_CONNECTION_TEST==="true"){N("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((B,W)=>{let j=i6.connect({host:$,port:w,timeout:3000});j.once("connect",()=>{N("connection",`Successfully connected to ${$}:${w}`,Y),j.end(),B()}),j.once("timeout",()=>{N("connection",`Connection to ${$}:${w} timed out`,Y),j.destroy(),W(Error("Connection timed out"))}),j.once("error",(z)=>{N("connection",`Failed to connect to ${$}:${w}: ${z}`,Y),j.destroy(),W(z)})});try{await U()}catch(B){let W=B;if(Date.now()-J>X){N("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),R.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&A>0)return N("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),eY($,w,Y,A-1);if(A>0)try{N("connection",`Trying HTTP request to ${$}:${w}`,Y),await new Promise((z,G)=>{let K=YJ.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(F)=>{N("connection",`Received HTTP response with status: ${F.statusCode}`,Y),z()});K.on("error",(F)=>G(F)),K.on("timeout",()=>{K.destroy(),G(Error("HTTP request timed out"))}),K.end()}),N("connection",`HTTP request to ${$}:${w} succeeded`,Y);return}catch(z){return N("connection",`HTTP request to ${$}:${w} failed: ${z}`,Y),N("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((G)=>setTimeout(G,2000)),eY($,w,Y,A-1)}let j=`Failed to connect to ${$}:${w} after ${5-A} attempts: ${W.message}`;N("connection",`${j}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),R.warn(j),R.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 g6($){N("server",`Starting server with options: ${R$($)}`,$.verbose);let w=Rw($.from),Y=new URL(w.startsWith("http")?w:`http://${w}`),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),X=Number.parseInt(Y.port)||(Y.protocol.includes("https:")?443:80),J=[A.hostname];if(Bj($)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){N("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await oY(J,$.verbose))[0]){R.info(`Adding ${A.hostname} to hosts file...`),R.info("This may require sudo/administrator privileges");try{await sY(J,$.verbose)}catch(W){if(R.error("Failed to add hosts entry:",W.message),R.warn("You can manually add this entry to your hosts file:"),R.warn(`127.0.0.1 ${A.hostname}`),R.warn(`::1 ${A.hostname}`),J0.platform==="win32")R.warn("On Windows:"),R.warn("1. Run notepad as administrator"),R.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else R.warn("On Unix systems:"),R.warn("sudo nano /etc/hosts")}}else N("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(B){R.error("Failed to check hosts file:",B.message)}}try{await eY(Y.hostname,X,$.verbose)}catch(B){N("server",`Connection test failed: ${B}`,$.verbose),R.error(B.message),R.warn("Continuing with proxy setup despite connection test failure..."),R.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=ZY({...$,to:A.hostname});if(U=await Yw({...$,to:A.hostname,https:$.https}),!U){if(N("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await i1({...$,from:Y.toString(),to:A.hostname,https:$.https}),U=await Yw({...$,to:A.hostname,https:$.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(B){throw N("server",`SSL setup failed: ${B}`,$.verbose),B}N("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await W4({...$,from:w,originalFrom:$.from||w,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function U4($,w,Y,A,X,J,U,B,W,j,z,G){N("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${B}`,U);let K=m1(z??A.host,G);g1(K);let F=[{host:w,route:{sourceHost:A.host,upstreamPool:K,cleanUrls:B||!1,changeOrigin:W||!1,basePath:"/",auth:j}}];if(!Wj({routeEntries:F,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw d1(K),Error(`Failed to start proxy server for ${w} on port ${Y}`);wJ.add(K),j4({from:$,to:w,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:B,verbose:U})}async function W4($){N("setup",`Setting up reverse proxy: ${R$($)}`,$.verbose);let{from:w,originalFrom:Y,to:A,sourceUrl:X,ssl:J,verbose:U,cleanup:B,vitePluginUsage:W,changeOrigin:j,cleanUrls:z}=$,G=80,K=443,F="0.0.0.0",T=$.portManager||J4,q=Bj($);try{if(q&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await oY([A],U))[0]){R.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await sY([A],U),R.success(`Added ${A} to your hosts file.`)}catch(V){R.error(`Failed to add ${A} to your hosts file: ${V}`),R.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(q&&J0.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await oY([A],U))[0]){N("hosts",`${A} not found in hosts file, adding...`,U);try{await sY([A],U)}catch(V){N("hosts",`Failed to add ${A} to hosts file: ${V}`,U)}}}if(J&&!T.usedPorts.has(G)){if(!await Iw(G,F,U))N("setup","Starting HTTP redirect server",U),d6(U),T.usedPorts.add(G);else if(N("setup","Port 80 is in use, skipping HTTP redirect",U),U)R.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let E=J?K:G,f=await Iw(E,F,U),M;if(f){if(N("setup",`Port ${E} is already in use`,U),U)R.warn(`Port ${E} is already in use. This may be another instance of rpx or another service.`);if(E===443){if(M=await T.getNextAvailablePort(3443,!0),N("setup",`Using port ${M} instead of ${E}`,U),U)R.info(`Using port ${M} instead. Access your site at https://${A}:${M}`)}else if(M=await T.getNextAvailablePort(E+1000,!0),N("setup",`Using port ${M} instead of ${E}`,U),U)R.info(`Using port ${M} instead. Access your site at http://${A}:${M}`)}else M=E,T.usedPorts.add(M),N("setup",`Using standard ${E===443?"HTTPS":"HTTP"} port ${E} for ${A}`,U);await U4(w,A,M,X,J,W,U,z,j,l1($.auth),Y,$.loadBalancer)}catch(E){N("setup",`Setup failed: ${E}`,U),R.error(`Failed to setup reverse proxy: ${E.message}`),AJ({domains:[A],hosts:typeof B==="boolean"?B:B?.hosts,certs:typeof B==="boolean"?B:B?.certs,verbose:U,vitePluginUsage:W})}}function d6($,w=80,Y=443,A){N("redirect",`Starting HTTP redirect server on port ${w}`,$);let X=YJ.createServer((J,U)=>{if(A&&J.url){let z=J.url.split("?",1)[0],G=uY(A,z);if(G!=null){N("redirect",`Serving ACME challenge ${z}`,$),U.writeHead(200,{"content-type":"text/plain"}),U.end(G);return}}let B=J.headers.host||"",W=B.includes(":")?B.slice(0,B.indexOf(":")):B,j=Y===443?W:`${W}:${Y}`;N("redirect",`Redirecting request from ${B}${J.url} to https://${j}`,$),U.writeHead(301,{Location:`https://${j}${J.url}`}),U.end()}).listen(w);$J.add(X),N("redirect","HTTP redirect server started",$)}function l6($){let w={...IW,...$};if(N("proxy",`Starting proxy with options: ${R$(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){R.error("viaDaemon mode requires both `from` and `to`");return}wj({proxies:[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((W)=>{R.error(`Failed to register with rpx daemon: ${W.message}`),J0.exit(1)});return}let Y=w.to||"",A=Y.split(".").pop()?.toLowerCase()||"",X=J0.platform==="darwin"&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1"),J=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(X&&J.includes(A)&&w?.verbose)R.warn(`The .${A} TLD may not work reliably for local development`),R.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),R.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (wY(),c8)).then(({setupDevelopmentDns:W})=>{W({domains:[Y],verbose:w.verbose}).then((j)=>{if(j)Promise.resolve().then(()=>{if(w.verbose)if(U.includes(A))R.success(`DNS server started for .${A} domains`);else R.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else N("dns",`Could not start DNS server - ${Y} may not resolve in browser`,w.verbose)})}).catch((W)=>{N("dns",`Failed to start DNS server: ${W}`,w.verbose)});let B={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:ZY(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};N("proxy",`Server options: ${R$(B)}`,w.verbose),g6(B).catch((W)=>{N("proxy",`Failed to start proxy: ${W}`,w.verbose),R.error(`Failed to start proxy: ${W.message}`),AJ({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function B4($){return $?.verbose||!1}function Bj($){if($?.hostsManagement===!1)return!1;let w=$?.cleanup;if(w===!1)return!1;if(w&&typeof w==="object"&&w.hosts===!1)return!1;return!0}async function n6($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let Y=B4(w),A=Bj(w);if(N("config",`Starting with config: ${R$(w,2)}`,Y),N("config",`Is multi-proxy? ${"proxies"in w}`,Y),N("config",`Hosts management enabled? ${A}`,Y),w.viaDaemon){let I="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((O)=>({id:O.id,from:O.from,to:O.to,path:O.path,cleanUrls:O.cleanUrls??w.cleanUrls,changeOrigin:O.changeOrigin??w.changeOrigin,pathRewrites:O.pathRewrites})):[{id:w.id,from:w.from,to:w.to??"rpx.localhost",path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await wj({proxies:I,verbose:Y});return}if("proxies"in w&&Array.isArray(w.proxies)){N("servers",`Found ${w.proxies.length} proxies in config`,Y);for(let H of w.proxies)if(H.start){let I=`${H.from}-${H.to}`;try{N("watch",`Starting command for ${I} with command: ${H.start.command}`,Y),R.info(`Starting command for ${I}...`),await e8.startProcess(I,H.start,Y);let O=Rw(H.from),Z=new URL(O.startsWith("http")?O:`http://${O}`),P0=Z.hostname||"localhost",Z$=Number(Z.port)||80;try{await eY(P0,Z$,Y),N("watch",`Dev server is ready at ${P0}:${Z$}`,Y)}catch(h$){N("watch",`Connection check failed, but continuing with proxy setup: ${h$}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(O){throw N("watch",`Failed to start command for ${I}: ${O}`,Y),Error(`Failed to start command for ${I}: ${O}`)}}else N("watch",`No start command for proxy ${H.from} -> ${H.to}`,Y)}else if("start"in w&&w.start){N("watch","Found start command in single proxy config",Y);let H=`${w.from}-${w.to}`;try{if(w.start)N("watch",`Starting command: ${w.start.command}`,Y),await e8.startProcess(H,w.start,Y);let I=Rw(w.from),O=new URL(I.startsWith("http")?I:`http://${I}`),Z=O.hostname||"localhost",P0=Number(O.port)||80;try{await eY(Z,P0,Y),N("watch",`Dev server is ready at ${Z}:${P0}`,Y)}catch(Z$){N("watch",`Connection check failed, but continuing with proxy setup: ${Z$}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(I){throw N("watch",`Failed to run start command: ${I}`,Y),Error(`Failed to run start command: ${I}`)}}else N("watch","No start command found in config",Y);let X="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(J0.platform!=="win32"&&(w.https||A)){if(!uw())try{N("sudo","Pre-acquiring sudo credentials for privileged operations",Y),A4("sudo -v",{stdio:"inherit"})}catch{N("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if(w.productionCerts){if(J=await a1(w.productionCerts,Y),J.length>0)N("ssl",`Using ${J.length} production SNI cert(s): ${J.map((H)=>H.serverName).join(", ")}`,Y)}if(w.https){let H=J.length>0?null:await Yw(w);if(!H&&J.length===0){if(N("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,w.verbose),await i1(w),H=await Yw(w),!H)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else N("ssl",`Using existing and trusted certificates for ${X}`,w.verbose);w._cachedSSLConfig=H}let U="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({...H,https:w.https,cleanup:w.cleanup,cleanUrls:H.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:H.changeOrigin??w.changeOrigin,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,auth:"auth"in w?w.auth:void 0,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig}],B=U.map((H)=>H.to||"rpx.localhost"),W=J.length>0?J:w._cachedSSLConfig??null,j=B.filter((H)=>H&&!H.includes("localhost")&&!H.includes("127.0.0.1")),z=["dev","app","page","new","day","foo"],G=["test","localhost","local","example","invalid"],K=[...new Set(j.map((H)=>H.split(".").pop()?.toLowerCase()))],F=K.filter((H)=>!!H&&z.includes(H));if(F.length>0&&Y)R.warn(`The following TLDs may not work reliably for local development: ${F.map((H)=>`.${H}`).join(", ")}`),R.info(" These TLDs have HSTS preloading which can bypass local DNS"),R.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&J0.platform==="darwin"&&j.length>0){let{setupDevelopmentDns:H}=await Promise.resolve().then(() => (wY(),c8));if(await H({domains:j,verbose:Y})){if(Y)if(K.every((Z)=>!!Z&&G.includes(Z)))R.success(`DNS server started for ${K.map((Z)=>`.${Z}`).join(", ")} domains`);else R.success(`DNS server started for ${K.map((Z)=>`.${Z}`).join(", ")} domains (hosts file entries also added)`)}else N("dns","Could not start DNS server - custom domains may not resolve",Y)}let T=async()=>{N("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:H}=await Promise.resolve().then(() => (wY(),c8));await H({verbose:w.verbose})}catch(H){N("cleanup",`Error stopping DNS server: ${H}`,w.verbose)}try{await e8.stopAll(w.verbose)}catch(H){N("cleanup",`Error stopping processes: ${H}`,w.verbose)}await AJ({domains:B,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};J0.on("SIGINT",T),J0.on("SIGTERM",T);let q=w.singlePortMode===!0,E=w.httpsPort??443,f=w.httpPort??80,M=w.originGuard?v6(w.originGuard):null,Q=!!W&&(U.length>1||q||J.length>0),V=!W&&q&&U.length>0;if(Q&&W){N("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${E}`,Y);let H=await c6(U,A,Y);if(!await Iw(f,"0.0.0.0",Y))d6(Y,f,E,w.acmeChallengeWebroot);if(await Iw(E,"0.0.0.0",Y)){if(N("proxies",`Port ${E} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${E} is in use. Shared HTTPS proxy cannot start.`);return}if(!Wj({routeEntries:H,listenPort:E,sslConfig:W,originGuard:M,verbose:Y})){R.error(`Shared HTTPS proxy failed to bind :${E}; not exiting`);return}}else if(V){N("proxies",`Creating shared HTTP server for ${U.length} domains on port ${f}`,Y);let H=await c6(U,A,Y);if(await Iw(f,"0.0.0.0",Y)){if(N("proxies",`Port ${f} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${f} is in use. Shared HTTP proxy cannot start.`);return}if(!Wj({routeEntries:H,listenPort:f,sslConfig:null,originGuard:M,verbose:Y})){R.error(`Shared HTTP proxy failed to bind :${f}; not exiting`);return}}else for(let H of U)try{let I=H.to||"rpx.localhost";N("proxy",`Starting proxy for ${I} with SSL config: ${!!W}`,H.verbose),await g6({from:H.from||"localhost:5173",to:I,cleanUrls:H.cleanUrls||!1,https:H.https||!1,cleanup:H.cleanup||!1,vitePluginUsage:H.vitePluginUsage||!1,verbose:H.verbose||!1,_cachedSSLConfig:w._cachedSSLConfig,changeOrigin:H.changeOrigin||!1,loadBalancer:H.loadBalancer,auth:H.auth,path:H.path,pathRewrites:H.pathRewrites})}catch(I){N("proxies",`Failed to start proxy for ${H.to}: ${I}`,H.verbose),R.error(`Failed to start proxy for ${H.to}:`,I)}}async function c6($,w,Y){let A=[],X=new Set;for(let J of $){let U=J.to||"rpx.localhost",B=J.cleanUrls||!1,W=J.path,j=Q$(W),z=l1(J.auth);if(J.redirect){let G=D5(J.redirect);A.push({host:U,path:W,route:{redirect:G,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → redirect ${G.status} ${G.to}${z?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:W,route:{static:PY(J.static,B),cleanUrls:B,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${z?" (auth)":""}`,Y);else{let G=Rw(J.from),K=new URL(G.startsWith("http")?G:`http://${G}`),F=m1(J.from??K.host,J.loadBalancer);g1(F),wJ.add(F),A.push({host:U,path:W,route:{sourceHost:K.host,upstreamPool:F,cleanUrls:B,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → ${K.host}${z?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),w&&!B1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await oY([U],Y))[0])await sY([U],Y)}catch{N("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}function Wj($){let{routeEntries:w,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=$,U=r1(w),B=n1((z,G)=>t1(U,z,G),J),W=X?(z,G)=>X(z)??B(z,G):B,j=p1(J);try{let z=Bun.serve({port:Y,hostname:"0.0.0.0",reusePort:P1(),...A?{tls:Array.isArray(A)?A.map((G)=>({serverName:G.serverName,key:G.key,cert:G.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(G,K){return W(G,K)},websocket:j,error(G){return N("server",`Shared proxy server error: ${G}`,J),new Response(`Server Error: ${G.message}`,{status:500})}});return $J.add(z),N("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),z}catch(z){return N("proxies",`Failed to start shared proxy: ${z}`,J),console.error("Failed to start shared proxy:",z),null}}function j4($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${_$.green(_$.bold("rpx"))} ${_$.green(`v${X4}`)}`),console.log(` ${_$.green("➜")} ${_$.dim($?.from??"")} ${_$.dim("➜")} ${_$.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${_$.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${_$.green("➜")} Clean URLs enabled`)}WB();var MS=new bw("rpx",{showTags:!1});function p6($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}x0.chdir(G4(z4(K4(import.meta.url)),".."));var u0=new EJ("rpx"),r6="0.12.0";u0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async($)=>{if(!$?.from||!$.to)return n6(W1);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,singlePortMode:$.singlePortMode||!1,httpPort:$.httpPort!==void 0?Number($.httpPort):void 0,httpsPort:$.httpsPort!==void 0?Number($.httpsPort):void 0,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let Y={command:$.startCommand};if($.startCwd)Y.cwd=$.startCwd;if($.startEnv)try{Y.env=JSON.parse($.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),x0.exit(1)}w.start=Y}return l6(w)});u0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let Y=p6(W1)?W1.proxies.find((A)=>A.to===$||`${A.from}-${A.to}`===$):W1.to===$?W1:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${$}`),x0.exit(1);try{await n8.startProcess($,Y.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(A){console.error(`Failed to start dev server for ${$}:`,A),x0.exit(1)}});u0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await n8.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(Y){console.error(`Failed to stop dev server for ${$}:`,Y),x0.exit(1)}});u0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await n8.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),x0.exit(1)}});async function t6($){let Y={...(await a9().catch(()=>null))?.onDemand??{},enabled:!0};if($){let A=$.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}u0.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async($)=>{try{let w=$.onDemand?await t6($.roots):void 0;await(await y6({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,workers:$.workers===void 0?void 0:typeof $.workers==="string"?Number.parseInt($.workers,10):$.workers,onDemandSites:w,verbose:$.verbose??!0})).done,x0.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),x0.exit(1)}});u0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,Y=await O6({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!Y.stopped&&Y.pid===null){console.log("rpx daemon is not running");return}if(!Y.stopped){console.log(`rpx daemon pid=${Y.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${Y.pid} stopped${Y.forced?" (SIGKILL)":""}`)});u0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??w$(),Y=await Qw(w),A=await d8(w),X=$.registryDir,J=await $j(X).catch(()=>[]);if($.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:yw(w),rpxDir:w,registryDir:X??mw(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${yw(w)} \u2192 pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${yw(w)}`);if(console.log(`registry: ${X??mw()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let B=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} \u2192 ${U.from} (id=${U.id}${B})`)}});u0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),x0.exit(1);if(!XY($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),x0.exit(1);try{await h6({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),x0.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await L6({rpxDir:$.rpxDir,verbose:$.verbose}),Y=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${Y} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),x0.exit(1)}});u0.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async($,w)=>{if(!XY($))console.error(`invalid id: ${JSON.stringify($)}`),x0.exit(1);let Y=await eB($,w.registryDir,w.verbose);if(!Y){console.log(`no registry entry for id=${$}`);return}await k6($,w.registryDir,w.verbose),console.log(`unregistered ${Y.to} (id=${$})`)});u0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??w$();if(await d8(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await _6({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});u0.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async($)=>{let w=await t6($.roots),Y=wz(w),A=await $j($.registryDir).catch(()=>[]),X=new Set(A.map((B)=>B.to)),J=Y.map((B)=>({host:B.host,dir:B.dir,command:B.command,source:B.source,live:X.has(B.host)}));if($.json){console.log(JSON.stringify(J,null,2));return}let U=w.roots??["~/Code"];if(J.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${U.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${J.length}) \u2014 scanned ${U.join(", ")}:`);for(let B of J)console.log(` ${B.live?"\u25CF":"\u25CB"} https://${B.host} ${B.live?"(live)":"(idle)"}`),console.log(` ${B.command} ${B.dir}`)});u0.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async($,w)=>{let{readFile:Y}=await import("fs/promises"),{join:A}=await import("path"),X=w.rpxDir??w$(),J=A(X,"sites",`${dA($.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${$} (it may not have been booted yet) \u2014 looked in ${J}`);return}let B=w.lines===void 0?void 0:typeof w.lines==="string"?Number.parseInt(w.lines,10):w.lines,W=U.split(`
|
|
319
319
|
`);x0.stdout.write((B&&B>0?W.slice(-B):W).join(`
|
|
320
320
|
`))});u0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(r6)});u0.version(r6);u0.help();u0.run();
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{$ as fR,$a as c_,A as OS,Aa as XR,B as P,Ba as JR,C as DR,Ca as J_,D as kR,Da as Q_,E as cS,Ea as V_,F as L,Fa as Z_,G as NR,Ga as I_,H as hS,Ha as W_,I as
|
|
1
|
+
import{$ as fR,$a as c_,A as OS,Aa as XR,B as P,Ba as JR,C as DR,Ca as J_,D as kR,Da as Q_,E as cS,Ea as V_,F as L,Fa as Z_,G as NR,Ga as I_,H as hS,Ha as W_,I as vS,Ia as z_,J as uS,Ja as M_,K as AR,Ka as x_,L as BR,La as j_,M as mS,Ma as T_,N as KR,Na as H_,O as bS,Oa as k_,P as wR,Pa as w_,Q as aS,Qa as E_,R as ER,Ra as F_,S as lS,Sa as q_,T as dS,Ta as C_,U as pS,Ua as f_,V as gS,W as nS,Wa as y_,X as FR,Xa as U_,Y as qR,Ya as P_,Z as iS,Za as L_,_ as CR,_a as O_,a as G,aa as WR,ab as h_,b as SR,ba as tS,bb as v_,c as JS,ca as yR,cb as u_,d as QS,da as rS,db as m_,e as VS,ea as UR,eb as b_,f as ZS,fa as sS,fb as a_,g as IS,ga as PR,gb as l_,h as WS,ha as eS,hb as d_,i as zS,ia as LR,ib as p_,j as MS,ja as oS,jb as g_,k as xS,ka as R_,kb as n_,l as jS,la as S_,lb as QR,m as TS,ma as __,mb as i_,n as HS,na as D_,nb as t_,o as kS,oa as N_,p as wS,pa as A_,q as ES,qa as B_,r as FS,ra as K_,s as qS,sa as Y_,t as CS,ta as f,u as fS,ua as $_,v as yS,va as OR,w as US,wa as G_,x as PS,xa as $R,y as LS,ya as GR,z as _R,za as X_}from"./chunk-6m0f5m3q.js";import{Ab as EN,Bb as FN,Cb as qN,Db as CN,Eb as fN,ob as TR,pb as u,qb as lR,rb as xN,sb as D,tb as gR,ub as jN,vb as q,wb as TN,xb as HN,yb as kN,zb as wN}from"./chunk-2yk7jygq.js";import{execSync as NS}from"node:child_process";import*as YR from"node:http";import*as nR from"node:net";import*as z from"node:process";var p=(S,R)=>(_)=>`\x1B[${S}m${_}\x1B[${R}m`,k={bold:p(1,22),dim:p(2,22),green:p(32,39),cyan:p(36,39)};import*as uR from"node:fs";import*as mR from"node:path";import*as E from"node:process";function bR(S,R){let N=(R&&R!=="/"?`${S}${R}`:S).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return N.length>0?N:"rpx"}async function g(S){if(S.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let R=S.verbose??!1,_=S.registryDir,N=new Set,K=S.proxies.map((Q)=>{let I=Q.id??bR(Q.to,Q.path);if(!GR(I))throw Error(`invalid registry id "${I}" derived from to="${Q.to}"`);if(N.has(I))throw Error(`duplicate registry id "${I}" — set an explicit \`id\` on one of the proxies`);return N.add(I),{...Q,id:I}}),B=new Date().toISOString();for(let Q of K)await XR({id:Q.id,from:Q.from,to:Q.to,path:Q.path,pid:S.persistent?void 0:E.pid,cwd:E.cwd(),createdAt:B,cleanUrls:Q.cleanUrls,changeOrigin:Q.changeOrigin,pathRewrites:Q.pathRewrites,static:Q.static,loadBalancer:Q.loadBalancer},_,R);let A=await QR({rpxDir:S.rpxDir,verbose:R,spawnCommand:S.spawnCommand,startupTimeoutMs:S.startupTimeoutMs,spawnEnv:S.spawnEnv});for(let Q of K){let I=Q.static?`static ${typeof Q.static==="string"?Q.static:Q.static.dir}`:Q.from;G.success(`https://${Q.to} → ${I}`)}if(G.info(`(via rpx daemon pid=${A.pid}; \`rpx daemon:status\` to inspect)`),S.detached)return;let X=!1,Y=_??$R(),J=K.map((Q)=>Q.id),V=async()=>{if(X)return;X=!0;for(let Q of J)await JR(Q,_,R).catch((I)=>{D("runner",`removeEntry(${Q}) failed: ${I}`,R)})},Z=(Q)=>{D("runner",`received ${Q}, unregistering ${J.length} entries`,R),V().finally(()=>E.exit(0))};E.once("SIGINT",Z),E.once("SIGTERM",Z),E.once("exit",()=>{if(X)return;for(let Q of J)try{uR.unlinkSync(mR.join(Y,`${Q}.json`))}catch{}}),await new Promise(()=>{})}import{exec as sR}from"node:child_process";import C from"node:fs";import dR from"node:os";import ZR from"node:path";import*as m from"node:process";import{promisify as eR}from"node:util";var v=eR(sR);function aR(S){let R=S.trim().toLowerCase();return R==="localhost"||R.endsWith(".localhost")||R.endsWith(".localhost.")}var H=m.platform==="win32"?ZR.join(m.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",VR=!1;async function n(S){if(m.platform==="win32")throw Error("Administrator privileges required on Windows");if(lR()){let{stdout:N}=await v(S);return N}let R=u(),_=S.replace(/'/g,"'\\''");try{if(R){let{stdout:N}=await v(`echo '${R}' | sudo -S sh -c '${_}' 2>/dev/null`);return VR=!0,N}if(VR)try{let{stdout:N}=await v(`sudo -n sh -c '${_}'`);return N}catch(N){D("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:N}=await v(`sudo -n sh -c '${_}'`);return VR=!0,N}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(N){throw Error(`Failed to execute sudo command: ${N.message}`)}}async function y(S,R){let _=S.filter((K)=>!aR(K)),N=S.filter((K)=>aR(K));if(N.length>0)D("hosts",`Skipping /etc/hosts for loopback dev names: ${N.join(", ")}`,R);if(_.length===0)return;D("hosts",`Adding hosts: ${_.join(", ")}`,R),D("hosts",`Using hosts file at: ${H}`,R);try{let K;try{K=await C.promises.readFile(H,"utf-8")}catch{D("hosts","Reading hosts file requires elevated permissions, using sudo",R);try{K=await n(`cat "${H}"`)}catch(Y){throw console.log(" Could not read hosts file — skipping hosts setup"),D("hosts",`sudo read also failed: ${Y}`,R),Error(`Cannot read hosts file: ${Y}`)}}let B=_.filter((Y)=>{let J=`127.0.0.1 ${Y}`,V=`::1 ${Y}`;return!K.includes(J)&&!K.includes(V)});if(B.length===0){D("hosts","All hosts already exist in hosts file",R);return}let A=B.map((Y)=>`
|
|
2
2
|
# Added by rpx
|
|
3
3
|
127.0.0.1 ${Y}
|
|
4
4
|
::1 ${Y}`).join(`
|
|
5
5
|
`),X=ZR.join(dR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await C.promises.writeFile(X,K+A,"utf8"),await n(`cat "${X}" | tee "${H}" > /dev/null`),console.log(` Hosts updated: ${B.join(", ")}`)}catch(Y){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),B.forEach((J)=>{console.log(` 127.0.0.1 ${J}`),console.log(` ::1 ${J}`)}),console.log(` Or run: sudo nano ${H}`)}finally{try{await C.promises.unlink(X)}catch{}}}catch(K){D("hosts",`Failed to manage hosts file: ${K.message}`,R)}}async function IR(S,R){D("hosts",`Removing hosts: ${S.join(", ")}`,R);try{let _;try{_=await C.promises.readFile(H,"utf-8")}catch{D("hosts","Reading hosts file requires elevated permissions, using sudo",R);try{_=await n(`cat "${H}"`)}catch(Y){throw D("hosts",`sudo read also failed: ${Y}`,R),Error(`Cannot read hosts file: ${Y}`)}}let N=_.split(`
|
|
6
6
|
`),K=!1,B=N.filter((Y)=>{if(S.some((V)=>Y.includes(` ${V}`)&&(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){D("hosts","No matching hosts found to remove",R);return}while(B[B.length-1]?.trim()==="")B.pop();let A=`${B.join(`
|
|
7
7
|
`)}
|
|
8
|
-
`,X=ZR.join(dR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await C.promises.writeFile(X,A,"utf8"),await n(`cat "${X}" | tee "${H}" > /dev/null`),D("hosts","Hosts removed successfully",R)}catch(Y){D("hosts","Could not clean up hosts file automatically",R)}finally{try{await C.promises.unlink(X)}catch(Y){D("hosts",`Failed to remove temporary file: ${Y}`,R)}}}catch(_){D("hosts",`Failed to clean up hosts file: ${_.message}`,R)}}async function U(S,R){D("hosts",`Checking hosts: ${S}`,R);let _;try{_=await C.promises.readFile(H,"utf-8")}catch(N){D("hosts",`Error reading hosts file: ${N}`,R);try{let K=
|
|
9
|
-
`,A=(Y)=>{let J=r(Y);return _.has(J)||N.some((V)=>WR(J,V))},X=(Y)=>{let J=DS(Y);if(!A(J))return;let V="/";try{V=new URL(Y.url).pathname}catch{}if(K.some((Z)=>V.startsWith(Z)))return;if(SS(Y.headers.get(R),S.value))return;return new Response(B,{status:403,headers:{"content-type":"text/plain"}})};return X.protects=A,X}var e=new t,AS="0.12.0",BS=new OR("0.0.0.0"),o=new Set,RR=new Set,MR=!1,s=null,xR=null;async function a(S){if(MR)return D("cleanup","Cleanup already in progress, skipping",S?.verbose),xR||Promise.resolve();MR=!0,D("cleanup","Starting cleanup process",S?.verbose),xR=new Promise((R)=>{s=R});try{await e.stopAll(S?.verbose),G.info("Shutting down proxy servers...");let R=[],_=Array.from(o).map((N)=>new Promise((K)=>{let B=N;try{if(typeof B.stop==="function")B.stop(!0),D("cleanup","Bun server stopped",S?.verbose),K();else if(typeof B.close==="function")B.close(()=>{D("cleanup","Server closed successfully",S?.verbose),K()});else K()}catch(A){D("cleanup",`Error stopping server: ${A}`,S?.verbose),K()}}));R.push(..._),o.clear();for(let N of RR)BR(N);if(RR.clear(),S?.hosts&&S.domains?.length){D("cleanup","Cleaning up hosts file entries",S?.verbose),D("cleanup",`Original domains for cleanup: ${JSON.stringify(S.domains)}`,S?.verbose);let N=S.domains.filter((K)=>{if(K==="test.local")return!0;return K!=="localhost"&&!K.startsWith("localhost.")&&K!=="127.0.0.1"});if(D("cleanup",`Filtered domains for cleanup: ${JSON.stringify(N)}`,S?.verbose),N.length>0)G.info("Cleaning up hosts file entries..."),R.push(IR(N,S?.verbose).then(()=>{D("cleanup",`Removed hosts entries for ${N.join(", ")}`,S?.verbose)}).catch((K)=>{D("cleanup",`Failed to remove hosts entries: ${K}`,S?.verbose),G.warn(`Failed to clean up hosts file entries for ${N.join(", ")}:`,K)}))}if(S?.certs&&S.domains?.length){D("cleanup","Cleaning up SSL certificates",S?.verbose),G.info("Cleaning up SSL certificates...");let N=S.domains.map(async(K)=>{try{await kR(K,S?.verbose),D("cleanup",`Removed certificates for ${K}`,S?.verbose)}catch(B){D("cleanup",`Failed to remove certificates for ${K}: ${B}`,S?.verbose),G.warn(`Failed to clean up certificates for ${K}:`,B)}});R.push(...N)}await Promise.allSettled(R),D("cleanup","All cleanup tasks completed successfully",S?.verbose),G.success("All cleanup tasks completed successfully")}catch(R){D("cleanup",`Error during cleanup: ${R}`,S?.verbose),G.error("Error during cleanup:",R)}finally{if(s)s();s=null,MR=!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 xR}var jR=!1;function iR(S){if(jR){D("signal",`Received second ${S} signal, forcing exit`,!0),z.exit(1);return}jR=!0,D("signal",`Received ${S} signal, initiating cleanup`,!0),a().catch((R)=>{D("signal",`Cleanup failed after ${S}: ${R}`,!0),z.exit(1)}).finally(()=>{jR=!1})}z.once("SIGINT",()=>iR("SIGINT"));z.once("SIGTERM",()=>iR("SIGTERM"));z.on("uncaughtException",(S)=>{G.error("Uncaught exception (continuing):",S)});z.on("unhandledRejection",(S)=>{G.error("Unhandled rejection (continuing):",S)});async function b(S,R,_,N=5){D("connection",`Testing connection to ${S}:${R} (retries left: ${N})`,_);let K=15000,B=Date.now();if(z.env.RPX_BYPASS_CONNECTION_TEST==="true"){D("connection",`Bypassing connection test for ${S}:${R} due to RPX_BYPASS_CONNECTION_TEST flag`,_);return}let A=()=>new Promise((X,Y)=>{let J=nR.connect({host:S,port:R,timeout:3000});J.once("connect",()=>{D("connection",`Successfully connected to ${S}:${R}`,_),J.end(),X()}),J.once("timeout",()=>{D("connection",`Connection to ${S}:${R} timed out`,_),J.destroy(),Y(Error("Connection timed out"))}),J.once("error",(V)=>{D("connection",`Failed to connect to ${S}:${R}: ${V}`,_),J.destroy(),Y(V)})});try{await A()}catch(X){let Y=X;if(Date.now()-B>K){D("connection",`Connection test timed out after ${K}ms, but continuing anyway`,_),G.warn(`Connection test to ${S}:${R} timed out, but RPX will try to proceed anyway.`);return}if(Y.code==="ECONNREFUSED"&&N>0)return D("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${N} retries left)`,_),await new Promise((V)=>setTimeout(V,2000)),b(S,R,_,N-1);if(N>0)try{D("connection",`Trying HTTP request to ${S}:${R}`,_),await new Promise((V,Z)=>{let Q=YR.request({hostname:S,port:R,path:"/",method:"HEAD",timeout:5000},(I)=>{D("connection",`Received HTTP response with status: ${I.statusCode}`,_),V()});Q.on("error",(I)=>Z(I)),Q.on("timeout",()=>{Q.destroy(),Z(Error("HTTP request timed out"))}),Q.end()}),D("connection",`HTTP request to ${S}:${R} succeeded`,_);return}catch(V){return D("connection",`HTTP request to ${S}:${R} failed: ${V}`,_),D("connection",`Retrying socket connection in 2 seconds... (${N} retries left)`,_),await new Promise((Z)=>setTimeout(Z,2000)),b(S,R,_,N-1)}let J=`Failed to connect to ${S}:${R} after ${5-N} attempts: ${Y.message}`;D("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,_),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 cR(S){D("server",`Starting server with options: ${q(S)}`,S.verbose);let R=L(S.from),_=new URL(R.startsWith("http")?R:`http://${R}`),N=new URL((S.to?.startsWith("http")?S.to:`http://${S.to}`)||"rpx.localhost"),K=Number.parseInt(_.port)||(_.protocol.includes("https:")?443:80),B=[N.hostname];if(hR(S)&&!N.hostname.includes("localhost")&&!N.hostname.includes("127.0.0.1")){D("hosts",`Checking if hosts file entry exists for: ${N.hostname}`,S?.verbose);try{if(!(await U(B,S.verbose))[0]){G.info(`Adding ${N.hostname} to hosts file...`),G.info("This may require sudo/administrator privileges");try{await y(B,S.verbose)}catch(Y){if(G.error("Failed to add hosts entry:",Y.message),G.warn("You can manually add this entry to your hosts file:"),G.warn(`127.0.0.1 ${N.hostname}`),G.warn(`::1 ${N.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 D("hosts",`Host entry already exists for ${N.hostname}`,S.verbose)}catch(X){G.error("Failed to check hosts file:",X.message)}}try{await b(_.hostname,K,S.verbose)}catch(X){D("server",`Connection test failed: ${X}`,S.verbose),G.error(X.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 A=S._cachedSSLConfig||null;if(S.https)try{if(S.https===!0)S.https=DR({...S,to:N.hostname});if(A=await P({...S,to:N.hostname,https:S.https}),!A){if(D("ssl",`Generating new certificates for ${N.hostname}`,S.verbose),await _R({...S,from:_.toString(),to:N.hostname,https:S.https}),A=await P({...S,to:N.hostname,https:S.https}),!A)throw Error(`Failed to load SSL configuration after generating certificates for ${N.hostname}`)}}catch(X){throw D("server",`SSL setup failed: ${X}`,S.verbose),X}D("server",`Setting up reverse proxy with SSL config for ${N.hostname}`,S.verbose),await YS({...S,from:R,originalFrom:S.from||R,to:N.hostname,fromPort:K,sourceUrl:{hostname:_.hostname,host:_.host},ssl:A})}async function KS(S,R,_,N,K,B,A,X,Y,J,V,Z){D("proxy",`Creating proxy server ${S} -> ${R} with cleanUrls: ${X}`,A);let Q=NR(V??N.host,Z);AR(Q);let I=[{host:R,route:{sourceHost:N.host,upstreamPool:Q,cleanUrls:X||!1,changeOrigin:Y||!1,basePath:"/",auth:J}}];if(!HR({routeEntries:I,listenPort:_,sslConfig:K,originGuard:null,verbose:A??!1}))throw BR(Q),Error(`Failed to start proxy server for ${R} on port ${_}`);RR.add(Q),XS({from:S,to:R,vitePluginUsage:B,listenPort:_,ssl:!!K,cleanUrls:X,verbose:A})}async function YS(S){D("setup",`Setting up reverse proxy: ${q(S)}`,S.verbose);let{from:R,originalFrom:_,to:N,sourceUrl:K,ssl:B,verbose:A,cleanup:X,vitePluginUsage:Y,changeOrigin:J,cleanUrls:V}=S,Z=80,Q=443,I="0.0.0.0",F=S.portManager||BS,O=hR(S);try{if(O&&N&&!N.includes("localhost")&&!N.includes("127.0.0.1")){if(!(await U([N],A))[0]){G.warn(`The hostname ${N} isn't in your hosts file. Adding it now...`);try{await y([N],A),G.success(`Added ${N} to your hosts file.`)}catch(c){G.error(`Failed to add ${N} to your hosts file: ${c}`),G.info(`You may need to manually add '127.0.0.1 ${N}' to your /etc/hosts file.`)}}}else if(O&&z.platform!=="darwin"&&N&&N.includes("localhost")&&!N.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await U([N],A))[0]){D("hosts",`${N} not found in hosts file, adding...`,A);try{await y([N],A)}catch(c){D("hosts",`Failed to add ${N} to hosts file: ${c}`,A)}}}if(B&&!F.usedPorts.has(Z)){if(!await f(Z,I,A))D("setup","Starting HTTP redirect server",A),tR(A),F.usedPorts.add(Z);else if(D("setup","Port 80 is in use, skipping HTTP redirect",A),A)G.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let M=B?Q:Z,w=await f(M,I,A),j;if(w){if(D("setup",`Port ${M} is already in use`,A),A)G.warn(`Port ${M} is already in use. This may be another instance of rpx or another service.`);if(M===443){if(j=await F.getNextAvailablePort(3443,!0),D("setup",`Using port ${j} instead of ${M}`,A),A)G.info(`Using port ${j} instead. Access your site at https://${N}:${j}`)}else if(j=await F.getNextAvailablePort(M+1000,!0),D("setup",`Using port ${j} instead of ${M}`,A),A)G.info(`Using port ${j} instead. Access your site at http://${N}:${j}`)}else j=M,F.usedPorts.add(j),D("setup",`Using standard ${M===443?"HTTPS":"HTTP"} port ${M} for ${N}`,A);await KS(R,N,j,K,B,Y,A,V,J,KR(S.auth),_,S.loadBalancer)}catch(M){D("setup",`Setup failed: ${M}`,A),G.error(`Failed to setup reverse proxy: ${M.message}`),a({domains:[N],hosts:typeof X==="boolean"?X:X?.hosts,certs:typeof X==="boolean"?X:X?.certs,verbose:A,vitePluginUsage:Y})}}function tR(S,R=80,_=443,N){D("redirect",`Starting HTTP redirect server on port ${R}`,S);let K=YR.createServer((B,A)=>{if(N&&B.url){let V=B.url.split("?",1)[0],Z=CR(N,V);if(Z!=null){D("redirect",`Serving ACME challenge ${V}`,S),A.writeHead(200,{"content-type":"text/plain"}),A.end(Z);return}}let X=B.headers.host||"",Y=X.includes(":")?X.slice(0,X.indexOf(":")):X,J=_===443?Y:`${Y}:${_}`;D("redirect",`Redirecting request from ${X}${B.url} to https://${J}`,S),A.writeHead(301,{Location:`https://${J}${B.url}`}),A.end()}).listen(R);o.add(K),D("redirect","HTTP redirect server started",S)}function $S(S){let R={...SR,...S};if(D("proxy",`Starting proxy with options: ${q(R)}`,R?.verbose),R.viaDaemon){if(!R.from||!R.to){G.error("viaDaemon mode requires both `from` and `to`");return}g({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 _=R.to||"",N=_.split(".").pop()?.toLowerCase()||"",K=z.platform==="darwin"&&_&&!_.includes("localhost")&&!_.includes("127.0.0.1"),B=["dev","app","page","new","day","foo"],A=["test","localhost","local","example","invalid"];if(K&&B.includes(N)&&R?.verbose)G.warn(`The .${N} TLD may not work reliably for local development`),G.info(` Google owns .${N} with HSTS preloading, which can bypass local DNS`),G.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(K)import("./chunk-r1k4wgag.js").then(({setupDevelopmentDns:Y})=>{Y({domains:[_],verbose:R.verbose}).then((J)=>{if(J)Promise.resolve().then(()=>{if(R.verbose)if(A.includes(N))G.success(`DNS server started for .${N} domains`);else G.success(`DNS server started for .${N} domains (hosts file entry also added)`)});else D("dns",`Could not start DNS server - ${_} may not resolve in browser`,R.verbose)})}).catch((Y)=>{D("dns",`Failed to start DNS server: ${Y}`,R.verbose)});let X={from:R.from,to:R.to,cleanUrls:R.cleanUrls,https:DR(R),cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,changeOrigin:R.changeOrigin,verbose:R.verbose,regenerateUntrustedCerts:R.regenerateUntrustedCerts};D("proxy",`Server options: ${q(X)}`,R.verbose),cR(X).catch((Y)=>{D("proxy",`Failed to start proxy: ${Y}`,R.verbose),G.error(`Failed to start proxy: ${Y.message}`),a({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 GS(S){return S?.verbose||!1}function hR(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 _=GS(R),N=hR(R);if(D("config",`Starting with config: ${q(R,2)}`,_),D("config",`Is multi-proxy? ${"proxies"in R}`,_),D("config",`Hosts management enabled? ${N}`,_),R.viaDaemon){let W="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((x)=>({id:x.id,from:x.from,to:x.to,path:x.path,cleanUrls:x.cleanUrls??R.cleanUrls,changeOrigin:x.changeOrigin??R.changeOrigin,pathRewrites:x.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 g({proxies:W,verbose:_});return}if("proxies"in R&&Array.isArray(R.proxies)){D("servers",`Found ${R.proxies.length} proxies in config`,_);for(let $ of R.proxies)if($.start){let W=`${$.from}-${$.to}`;try{D("watch",`Starting command for ${W} with command: ${$.start.command}`,_),G.info(`Starting command for ${W}...`),await e.startProcess(W,$.start,_);let x=L($.from),T=new URL(x.startsWith("http")?x:`http://${x}`),h=T.hostname||"localhost",d=Number(T.port)||80;try{await b(h,d,_),D("watch",`Dev server is ready at ${h}:${d}`,_)}catch(rR){D("watch",`Connection check failed, but continuing with proxy setup: ${rR}`,_),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(x){throw D("watch",`Failed to start command for ${W}: ${x}`,_),Error(`Failed to start command for ${W}: ${x}`)}}else D("watch",`No start command for proxy ${$.from} -> ${$.to}`,_)}else if("start"in R&&R.start){D("watch","Found start command in single proxy config",_);let $=`${R.from}-${R.to}`;try{if(R.start)D("watch",`Starting command: ${R.start.command}`,_),await e.startProcess($,R.start,_);let W=L(R.from),x=new URL(W.startsWith("http")?W:`http://${W}`),T=x.hostname||"localhost",h=Number(x.port)||80;try{await b(T,h,_),D("watch",`Dev server is ready at ${T}:${h}`,_)}catch(d){D("watch",`Connection check failed, but continuing with proxy setup: ${d}`,_),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(W){throw D("watch",`Failed to run start command: ${W}`,_),Error(`Failed to run start command: ${W}`)}}else D("watch","No start command found in config",_);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||N)){if(!v())try{D("sudo","Pre-acquiring sudo credentials for privileged operations",_),NS("sudo -v",{stdio:"inherit"})}catch{D("sudo","Could not pre-acquire sudo credentials",_)}}let B=[];if(R.productionCerts){if(B=await LR(R.productionCerts,_),B.length>0)D("ssl",`Using ${B.length} production SNI cert(s): ${B.map(($)=>$.serverName).join(", ")}`,_)}if(R.https){let $=B.length>0?null:await P(R);if(!$&&B.length===0){if(D("ssl",`No valid or trusted certificates found for ${K}, generating new ones`,R.verbose),await _R(R),$=await P(R),!$)throw Error(`Failed to load SSL certificates after generation for ${K}`)}else D("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:_,_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:_,_cachedSSLConfig:R._cachedSSLConfig}],X=A.map(($)=>$.to||"rpx.localhost"),Y=B.length>0?B:R._cachedSSLConfig??null,J=X.filter(($)=>$&&!$.includes("localhost")&&!$.includes("127.0.0.1")),V=["dev","app","page","new","day","foo"],Z=["test","localhost","local","example","invalid"],Q=[...new Set(J.map(($)=>$.split(".").pop()?.toLowerCase()))],I=Q.filter(($)=>!!$&&V.includes($));if(I.length>0&&_)G.warn(`The following TLDs may not work reliably for local development: ${I.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(N&&z.platform==="darwin"&&J.length>0){let{setupDevelopmentDns:$}=await import("./chunk-r1k4wgag.js");if(await $({domains:J,verbose:_})){if(_)if(Q.every((T)=>!!T&&Z.includes(T)))G.success(`DNS server started for ${Q.map((T)=>`.${T}`).join(", ")} domains`);else G.success(`DNS server started for ${Q.map((T)=>`.${T}`).join(", ")} domains (hosts file entries also added)`)}else D("dns","Could not start DNS server - custom domains may not resolve",_)}let F=async()=>{D("cleanup","Starting cleanup handler",R.verbose);try{let{tearDownDevelopmentDns:$}=await import("./chunk-r1k4wgag.js");await $({verbose:R.verbose})}catch($){D("cleanup",`Error stopping DNS server: ${$}`,R.verbose)}try{await e.stopAll(R.verbose)}catch($){D("cleanup",`Error stopping processes: ${$}`,R.verbose)}await a({domains:X,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",F),z.on("SIGTERM",F);let O=R.singlePortMode===!0,M=R.httpsPort??443,w=R.httpPort??80,j=R.originGuard?zR(R.originGuard):null,l=!!Y&&(A.length>1||O),c=!Y&&O&&A.length>0;if(l&&Y){D("proxies",`Creating shared HTTPS server for ${A.length} domains on port ${M}`,_);let $=await pR(A,N,_);if(!await f(w,"0.0.0.0",_))tR(_,w,M,R.acmeChallengeWebroot);if(await f(M,"0.0.0.0",_)){if(D("proxies",`Port ${M} is already in use, cannot start shared proxy`,_),_)G.warn(`Port ${M} is in use. Shared HTTPS proxy cannot start.`);return}if(!HR({routeEntries:$,listenPort:M,sslConfig:Y,originGuard:j,verbose:_})){G.error(`Shared HTTPS proxy failed to bind :${M}; not exiting`);return}}else if(c){D("proxies",`Creating shared HTTP server for ${A.length} domains on port ${w}`,_);let $=await pR(A,N,_);if(await f(w,"0.0.0.0",_)){if(D("proxies",`Port ${w} is already in use, cannot start shared proxy`,_),_)G.warn(`Port ${w} is in use. Shared HTTP proxy cannot start.`);return}if(!HR({routeEntries:$,listenPort:w,sslConfig:null,originGuard:j,verbose:_})){G.error(`Shared HTTP proxy failed to bind :${w}; not exiting`);return}}else for(let $ of A)try{let W=$.to||"rpx.localhost";D("proxy",`Starting proxy for ${W} with SSL config: ${!!Y}`,$.verbose),await cR({from:$.from||"localhost:5173",to:W,cleanUrls:$.cleanUrls||!1,https:$.https||!1,cleanup:$.cleanup||!1,vitePluginUsage:$.vitePluginUsage||!1,verbose:$.verbose||!1,_cachedSSLConfig:R._cachedSSLConfig,changeOrigin:$.changeOrigin||!1,loadBalancer:$.loadBalancer,auth:$.auth,path:$.path,pathRewrites:$.pathRewrites})}catch(W){D("proxies",`Failed to start proxy for ${$.to}: ${W}`,$.verbose),G.error(`Failed to start proxy for ${$.to}:`,W)}}async function pR(S,R,_){let N=[],K=new Set;for(let B of S){let A=B.to||"rpx.localhost",X=B.cleanUrls||!1,Y=B.path,J=yR(Y),V=KR(B.auth);if(B.redirect){let Z=wR(B.redirect);N.push({host:A,path:Y,route:{redirect:Z,basePath:J,auth:V}}),D("proxies",`Route: ${A}${Y??""} → redirect ${Z.status} ${Z.to}${V?" (auth)":""}`,_)}else if(B.static)N.push({host:A,path:Y,route:{static:ER(B.static,X),cleanUrls:X,basePath:J,auth:V}}),D("proxies",`Route: ${A}${Y??""} → static ${typeof B.static==="string"?B.static:B.static.dir}${V?" (auth)":""}`,_);else{let Z=L(B.from),Q=new URL(Z.startsWith("http")?Z:`http://${Z}`),I=NR(B.from??Q.host,B.loadBalancer);AR(I),RR.add(I),N.push({host:A,path:Y,route:{sourceHost:Q.host,upstreamPool:I,cleanUrls:X,changeOrigin:B.changeOrigin||!1,pathRewrites:B.pathRewrites,basePath:J,auth:V}}),D("proxies",`Route: ${A}${Y??""} → ${Q.host}${V?" (auth)":""}`,_)}if(K.has(A))continue;if(K.add(A),R&&!fR(A)&&!A.includes("localhost")&&!A.includes("127.0.0.1"))try{if(!(await U([A],_))[0])await y([A],_)}catch{D("hosts",`Could not add hosts entry for ${A}`,_)}}return N}function HR(S){let{routeEntries:R,listenPort:_,sslConfig:N,originGuard:K,verbose:B}=S,A=UR(R),X=FR((V,Z)=>PR(A,V,Z),B),Y=K?(V,Z)=>K(V)??X(V,Z):X,J=qR(B);try{let V=Bun.serve({port:_,hostname:"0.0.0.0",reusePort:gR(),...N?{tls:Array.isArray(N)?N.map((Z)=>({serverName:Z.serverName,key:Z.key,cert:Z.cert})):{key:N.key,cert:N.cert,ca:N.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(Z,Q){return Y(Z,Q)},websocket:J,error(Z){return D("server",`Shared proxy server error: ${Z}`,B),new Response(`Server Error: ${Z.message}`,{status:500})}});return o.add(V),D("proxies",`Shared ${N?"HTTPS":"HTTP"} proxy listening on port ${_} for ${A.size} domains`,B),V}catch(V){return D("proxies",`Failed to start shared proxy: ${V}`,B),console.error("Failed to start shared proxy:",V),null}}function XS(S){if(S?.vitePluginUsage||!S?.verbose)return;if(console.log(""),console.log(` ${k.green(k.bold("rpx"))} ${k.green(`v${AS}`)}`),console.log(` ${k.green("➜")} ${k.dim(S?.from??"")} ${k.dim("➜")} ${k.cyan(S?.ssl?`https://${S?.to}`:`http://${S?.to}`)}`),S?.listenPort!==(S?.ssl?443:80))console.log(` ${k.green("➜")} Listening on port ${S?.listenPort}`);if(S?.cleanUrls)console.log(` ${k.green("➜")} Clean URLs enabled`)}var MN=uR;export{XR as writeEntry,Z_ as watchRegistry,IS as verifyHttpsChain,FS as trustRootCaForBrowsers,h_ as tearDownDevelopmentDns,c_ as syncDevelopmentDnsFromRegistry,nS as stripBasePath,BR as stopHealthChecks,C_ as stopDnsServer,i_ as stopDaemon,cR as startServer,$S as startProxy,uR as startProxies,AR as startHealthChecks,q_ as startDnsServer,D_ as siteIdForHost,gR as shouldReusePort,P_ as setupResolver,O_ as setupDevelopmentDns,eS as serverNameFromCertFilename,gS as serveStaticFile,hS as selectUpstream,q as safeStringify,dS as safeRelativePath,fN as safeDeleteFile,g as runViaDaemon,g_ as runDaemon,y_ as resolverFilePath,k_ as resolverBasenamesForDomains,H_ as resolverBasenameForDomain,ER as resolveStaticRoute,pS as resolveStaticFile,wR as resolveRedirect,CN as resolvePathRewrite,KR as resolveAuth,z_ as renderStartingPage,M_ as renderFailedPage,u_ as removeResolver,L_ as removeLegacyTldResolvers,IR as removeHosts,JR as removeEntry,p_ as releaseDaemonLock,jN as redactSensitive,v_ as reconcileStaleDevelopmentDns,t_ as reconcileDevelopmentDnsOnIdle,A_ as readSiteManifest,J_ as readEntry,a_ as readDaemonPid,QS as readCertSha256Fingerprint,VS as readCertCommonName,Q_ as readAll,CR as readAcmeChallenge,kS as pruneStaleRootCas,N_ as projectNameFromHost,L as primaryUpstreamUrl,G_ as portManager,rS as pathPrefixMatches,WS as parseSha256HashesFromSecurityListing,mS as parseHtpasswd,JS as normalizeSha256Fingerprint,yR as normalizePathPrefix,T_ as normalizeDevDomain,WR as matchesWildcard,oS as matchesAllowedSuffix,PR as matchHostRoute,sS as matchHostList,tS as matchHost,uS as markSuccess,vS as markFailure,PS as loadSSLConfig,Y_ as listDiscoverableSites,HS as listCertSha256HashesByCommonName,fR as isWildcardPattern,HN as isValidRootCA,GR as isValidId,FN as isSingleProxyOptions,qN as isSingleProxyConfig,wS as isRootCaTrustedForSsl,ES as isRootCaFingerprintInKeychains,lR as isProcessElevated,f as isPortInUse,X_ as isPidAlive,EN as isMultiProxyOptions,wN as isMultiProxyConfig,R_ as isLikelyHostname,f_ as isDnsServerRunning,l_ as isDaemonRunning,cS as isCertTrusted,DR as httpsConfig,v as getSudoPassword,US as getSharedDaemonCertPaths,yS as getRootCAPaths,$R as getRegistryDir,kN as getPrimaryDomain,TS as getMacosTrustKeychains,jS as getMacosLoginKeychainPath,m_ as getDaemonRpxDir,b_ as getDaemonPidPath,_R as generateCertificate,V_ as gcStaleEntries,LS as forceTrustCertificate,$_ as findAvailablePort,TN as extractHostname,__ as expandHome,xN as execSudoSync,W_ as escapeHtml,QR as ensureDaemonRunning,bS as enforceBasicAuth,CS as devSslToSniEntries,w_ as devDomainsFromHosts,B_ as detectProjectPreset,bR as deriveIdFromTarget,n_ as defaultDaemonSpawnCommand,SR as defaultConfig,MN as default,D as debugLog,NR as createUpstreamPool,K_ as createSiteResolver,qR as createProxyWebSocketHandler,FR as createProxyFetchHandler,zR as createOriginGuard,lS as contentTypeFor,U_ as contentLooksLikeRpxResolver,SR as config,k as colors,OS as clearSslConfigCache,kR as cleanupCertificates,a as cleanup,U as checkHosts,P as checkExistingCertificates,ZS as certIncludesSanHostnames,LR as buildSniTlsConfig,fS as buildRegistryTlsProxyOptions,aS as buildRedirectLocation,UR as buildHostRoutes,y as addHosts,d_ as acquireDaemonLock,I_ as SiteSupervisor,qS as SHARED_DEV_HOST_CERT_PATH,xS as RPX_ROOT_CA_COMMON_NAME,F_ as RPX_RESOLVER_MARKER,S_ as OnDemandCertManager,MS as MACOS_SYSTEM_KEYCHAIN,zS as MACOS_CA_TRUST_FLAGS,j_ as LEGACY_TLD_RESOLVER_LABELS,OR as DefaultPortManager,x_ as DNS_STATE_VERSION,E_ as DNS_PORT,iS as ACME_CHALLENGE_PREFIX};
|
|
8
|
+
`,X=ZR.join(dR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await C.promises.writeFile(X,A,"utf8"),await n(`cat "${X}" | tee "${H}" > /dev/null`),D("hosts","Hosts removed successfully",R)}catch(Y){D("hosts","Could not clean up hosts file automatically",R)}finally{try{await C.promises.unlink(X)}catch(Y){D("hosts",`Failed to remove temporary file: ${Y}`,R)}}}catch(_){D("hosts",`Failed to clean up hosts file: ${_.message}`,R)}}async function U(S,R){D("hosts",`Checking hosts: ${S}`,R);let _;try{_=await C.promises.readFile(H,"utf-8")}catch(N){D("hosts",`Error reading hosts file: ${N}`,R);try{let K=u(),B;if(K)B=`echo '${K}' | sudo -S cat "${H}" 2>/dev/null`;else B=`sudo -n cat "${H}" 2>/dev/null || cat "${H}" 2>/dev/null || echo ""`;let{stdout:A}=await v(B);_=A}catch(K){return D("hosts",`Cannot read hosts file, assuming entries don't exist: ${K}`,R),S.map(()=>!1)}}return S.map((N)=>{let K=`127.0.0.1 ${N}`,B=`::1 ${N}`;return _.includes(K)||_.includes(B)})}import{spawn as oR}from"node:child_process";import*as i from"node:process";class t{processes=new Map;isShuttingDown=!1;async startProcess(S,R,_){if(this.processes.has(S)){D("start",`Process ${S} is already running`,_);return}let[N,...K]=R.command.split(" "),B=R.cwd||i.cwd();D("start",`Starting process ${S}:`,_),D("start",` Command: ${N} ${K.join(" ")}`,_),D("start",` Working directory: ${B}`,_),D("start",` Environment variables: ${q(R.env)}`,_);let A=oR(N,K,{cwd:B,env:{...i.env,...R.env},shell:!0,stdio:"inherit"});return this.processes.set(S,{command:R.command,cwd:B,process:A,env:R.env}),new Promise((X,Y)=>{if(A.on("error",(J)=>{if(!this.isShuttingDown)D("start",`Process ${S} failed to start: ${J}`,_),this.processes.delete(S),Y(J)}),A.on("exit",(J)=>{if(!this.isShuttingDown&&J!==null&&J!==0)D("start",`Process ${S} exited with code ${J}; leaving the proxy running`,_),this.processes.delete(S),Y(Error(`Process ${S} exited with code ${J}`))}),_)A.stdout?.on("data",(J)=>{D("process",`[${S}] ${J.toString().trim()}`,!0)}),A.stderr?.on("data",(J)=>{D("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 D("start",`Process ${S} started successfully`,_),X()},1000)})}async stopProcess(S,R){let _=this.processes.get(S);if(!_?.process){D("start",`No process found for ${S}`,R);return}return D("start",`Stopping process ${S}`,R),new Promise((N)=>{if(!_.process){N();return}_.process.once("exit",()=>{this.processes.delete(S),D("start",`Process ${S} stopped`,R),N()});try{_.process.kill("SIGTERM"),setTimeout(()=>{if(_.process){D("start",`Force killing process ${S}`,R);try{_.process.kill("SIGKILL")}catch(K){}}},3000)}catch(K){D("start",`Error stopping process ${S}: ${K}`,R),this.processes.delete(S),N()}})}async stopAll(S){if(this.isShuttingDown){D("start","Already shutting down, skipping duplicate stopAll call",S);return}this.isShuttingDown=!0,D("start","Stopping all processes",S);let R=Array.from(this.processes.keys()).map((_)=>this.stopProcess(_,S).catch((N)=>{G.error(`Failed to stop process ${_}:`,N)}));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 JD=new t;import{timingSafeEqual as RS}from"node:crypto";function SS(S,R){if(S==null)return!1;let _=Buffer.from(S),N=Buffer.from(R);if(_.length!==N.length)return!1;return RS(_,N)}function r(S){return S.toLowerCase().replace(/\.$/,"")}var _S=["/.well-known/acme-challenge/"];function DS(S){let R=S.headers.get("host");if(R)return r(R.split(":")[0]);try{return r(new URL(S.url).hostname)}catch{return""}}function zR(S){let R=S.header.toLowerCase(),_=new Set,N=[];for(let Y of S.hosts){let J=r(Y);if(J.startsWith("*."))N.push(J);else _.add(J)}let K=S.exemptPaths??_S,B=S.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
|
|
9
|
+
`,A=(Y)=>{let J=r(Y);return _.has(J)||N.some((V)=>WR(J,V))},X=(Y)=>{let J=DS(Y);if(!A(J))return;let V="/";try{V=new URL(Y.url).pathname}catch{}if(K.some((Z)=>V.startsWith(Z)))return;if(SS(Y.headers.get(R),S.value))return;return new Response(B,{status:403,headers:{"content-type":"text/plain"}})};return X.protects=A,X}var e=new t,AS="0.12.0",BS=new OR("0.0.0.0"),o=new Set,RR=new Set,MR=!1,s=null,xR=null;async function a(S){if(MR)return D("cleanup","Cleanup already in progress, skipping",S?.verbose),xR||Promise.resolve();MR=!0,D("cleanup","Starting cleanup process",S?.verbose),xR=new Promise((R)=>{s=R});try{await e.stopAll(S?.verbose),G.info("Shutting down proxy servers...");let R=[],_=Array.from(o).map((N)=>new Promise((K)=>{let B=N;try{if(typeof B.stop==="function")B.stop(!0),D("cleanup","Bun server stopped",S?.verbose),K();else if(typeof B.close==="function")B.close(()=>{D("cleanup","Server closed successfully",S?.verbose),K()});else K()}catch(A){D("cleanup",`Error stopping server: ${A}`,S?.verbose),K()}}));R.push(..._),o.clear();for(let N of RR)BR(N);if(RR.clear(),S?.hosts&&S.domains?.length){D("cleanup","Cleaning up hosts file entries",S?.verbose),D("cleanup",`Original domains for cleanup: ${JSON.stringify(S.domains)}`,S?.verbose);let N=S.domains.filter((K)=>{if(K==="test.local")return!0;return K!=="localhost"&&!K.startsWith("localhost.")&&K!=="127.0.0.1"});if(D("cleanup",`Filtered domains for cleanup: ${JSON.stringify(N)}`,S?.verbose),N.length>0)G.info("Cleaning up hosts file entries..."),R.push(IR(N,S?.verbose).then(()=>{D("cleanup",`Removed hosts entries for ${N.join(", ")}`,S?.verbose)}).catch((K)=>{D("cleanup",`Failed to remove hosts entries: ${K}`,S?.verbose),G.warn(`Failed to clean up hosts file entries for ${N.join(", ")}:`,K)}))}if(S?.certs&&S.domains?.length){D("cleanup","Cleaning up SSL certificates",S?.verbose),G.info("Cleaning up SSL certificates...");let N=S.domains.map(async(K)=>{try{await kR(K,S?.verbose),D("cleanup",`Removed certificates for ${K}`,S?.verbose)}catch(B){D("cleanup",`Failed to remove certificates for ${K}: ${B}`,S?.verbose),G.warn(`Failed to clean up certificates for ${K}:`,B)}});R.push(...N)}await Promise.allSettled(R),D("cleanup","All cleanup tasks completed successfully",S?.verbose),G.success("All cleanup tasks completed successfully")}catch(R){D("cleanup",`Error during cleanup: ${R}`,S?.verbose),G.error("Error during cleanup:",R)}finally{if(s)s();s=null,MR=!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 xR}var jR=!1;function iR(S){if(jR){D("signal",`Received second ${S} signal, forcing exit`,!0),z.exit(1);return}jR=!0,D("signal",`Received ${S} signal, initiating cleanup`,!0),a().catch((R)=>{D("signal",`Cleanup failed after ${S}: ${R}`,!0),z.exit(1)}).finally(()=>{jR=!1})}z.once("SIGINT",()=>iR("SIGINT"));z.once("SIGTERM",()=>iR("SIGTERM"));z.on("uncaughtException",(S)=>{G.error("Uncaught exception (continuing):",S)});z.on("unhandledRejection",(S)=>{G.error("Unhandled rejection (continuing):",S)});async function b(S,R,_,N=5){D("connection",`Testing connection to ${S}:${R} (retries left: ${N})`,_);let K=15000,B=Date.now();if(z.env.RPX_BYPASS_CONNECTION_TEST==="true"){D("connection",`Bypassing connection test for ${S}:${R} due to RPX_BYPASS_CONNECTION_TEST flag`,_);return}let A=()=>new Promise((X,Y)=>{let J=nR.connect({host:S,port:R,timeout:3000});J.once("connect",()=>{D("connection",`Successfully connected to ${S}:${R}`,_),J.end(),X()}),J.once("timeout",()=>{D("connection",`Connection to ${S}:${R} timed out`,_),J.destroy(),Y(Error("Connection timed out"))}),J.once("error",(V)=>{D("connection",`Failed to connect to ${S}:${R}: ${V}`,_),J.destroy(),Y(V)})});try{await A()}catch(X){let Y=X;if(Date.now()-B>K){D("connection",`Connection test timed out after ${K}ms, but continuing anyway`,_),G.warn(`Connection test to ${S}:${R} timed out, but RPX will try to proceed anyway.`);return}if(Y.code==="ECONNREFUSED"&&N>0)return D("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${N} retries left)`,_),await new Promise((V)=>setTimeout(V,2000)),b(S,R,_,N-1);if(N>0)try{D("connection",`Trying HTTP request to ${S}:${R}`,_),await new Promise((V,Z)=>{let Q=YR.request({hostname:S,port:R,path:"/",method:"HEAD",timeout:5000},(I)=>{D("connection",`Received HTTP response with status: ${I.statusCode}`,_),V()});Q.on("error",(I)=>Z(I)),Q.on("timeout",()=>{Q.destroy(),Z(Error("HTTP request timed out"))}),Q.end()}),D("connection",`HTTP request to ${S}:${R} succeeded`,_);return}catch(V){return D("connection",`HTTP request to ${S}:${R} failed: ${V}`,_),D("connection",`Retrying socket connection in 2 seconds... (${N} retries left)`,_),await new Promise((Z)=>setTimeout(Z,2000)),b(S,R,_,N-1)}let J=`Failed to connect to ${S}:${R} after ${5-N} attempts: ${Y.message}`;D("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,_),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 cR(S){D("server",`Starting server with options: ${q(S)}`,S.verbose);let R=L(S.from),_=new URL(R.startsWith("http")?R:`http://${R}`),N=new URL((S.to?.startsWith("http")?S.to:`http://${S.to}`)||"rpx.localhost"),K=Number.parseInt(_.port)||(_.protocol.includes("https:")?443:80),B=[N.hostname];if(hR(S)&&!N.hostname.includes("localhost")&&!N.hostname.includes("127.0.0.1")){D("hosts",`Checking if hosts file entry exists for: ${N.hostname}`,S?.verbose);try{if(!(await U(B,S.verbose))[0]){G.info(`Adding ${N.hostname} to hosts file...`),G.info("This may require sudo/administrator privileges");try{await y(B,S.verbose)}catch(Y){if(G.error("Failed to add hosts entry:",Y.message),G.warn("You can manually add this entry to your hosts file:"),G.warn(`127.0.0.1 ${N.hostname}`),G.warn(`::1 ${N.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 D("hosts",`Host entry already exists for ${N.hostname}`,S.verbose)}catch(X){G.error("Failed to check hosts file:",X.message)}}try{await b(_.hostname,K,S.verbose)}catch(X){D("server",`Connection test failed: ${X}`,S.verbose),G.error(X.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 A=S._cachedSSLConfig||null;if(S.https)try{if(S.https===!0)S.https=DR({...S,to:N.hostname});if(A=await P({...S,to:N.hostname,https:S.https}),!A){if(D("ssl",`Generating new certificates for ${N.hostname}`,S.verbose),await _R({...S,from:_.toString(),to:N.hostname,https:S.https}),A=await P({...S,to:N.hostname,https:S.https}),!A)throw Error(`Failed to load SSL configuration after generating certificates for ${N.hostname}`)}}catch(X){throw D("server",`SSL setup failed: ${X}`,S.verbose),X}D("server",`Setting up reverse proxy with SSL config for ${N.hostname}`,S.verbose),await YS({...S,from:R,originalFrom:S.from||R,to:N.hostname,fromPort:K,sourceUrl:{hostname:_.hostname,host:_.host},ssl:A})}async function KS(S,R,_,N,K,B,A,X,Y,J,V,Z){D("proxy",`Creating proxy server ${S} -> ${R} with cleanUrls: ${X}`,A);let Q=NR(V??N.host,Z);AR(Q);let I=[{host:R,route:{sourceHost:N.host,upstreamPool:Q,cleanUrls:X||!1,changeOrigin:Y||!1,basePath:"/",auth:J}}];if(!HR({routeEntries:I,listenPort:_,sslConfig:K,originGuard:null,verbose:A??!1}))throw BR(Q),Error(`Failed to start proxy server for ${R} on port ${_}`);RR.add(Q),XS({from:S,to:R,vitePluginUsage:B,listenPort:_,ssl:!!K,cleanUrls:X,verbose:A})}async function YS(S){D("setup",`Setting up reverse proxy: ${q(S)}`,S.verbose);let{from:R,originalFrom:_,to:N,sourceUrl:K,ssl:B,verbose:A,cleanup:X,vitePluginUsage:Y,changeOrigin:J,cleanUrls:V}=S,Z=80,Q=443,I="0.0.0.0",F=S.portManager||BS,O=hR(S);try{if(O&&N&&!N.includes("localhost")&&!N.includes("127.0.0.1")){if(!(await U([N],A))[0]){G.warn(`The hostname ${N} isn't in your hosts file. Adding it now...`);try{await y([N],A),G.success(`Added ${N} to your hosts file.`)}catch(c){G.error(`Failed to add ${N} to your hosts file: ${c}`),G.info(`You may need to manually add '127.0.0.1 ${N}' to your /etc/hosts file.`)}}}else if(O&&z.platform!=="darwin"&&N&&N.includes("localhost")&&!N.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await U([N],A))[0]){D("hosts",`${N} not found in hosts file, adding...`,A);try{await y([N],A)}catch(c){D("hosts",`Failed to add ${N} to hosts file: ${c}`,A)}}}if(B&&!F.usedPorts.has(Z)){if(!await f(Z,I,A))D("setup","Starting HTTP redirect server",A),tR(A),F.usedPorts.add(Z);else if(D("setup","Port 80 is in use, skipping HTTP redirect",A),A)G.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let M=B?Q:Z,w=await f(M,I,A),j;if(w){if(D("setup",`Port ${M} is already in use`,A),A)G.warn(`Port ${M} is already in use. This may be another instance of rpx or another service.`);if(M===443){if(j=await F.getNextAvailablePort(3443,!0),D("setup",`Using port ${j} instead of ${M}`,A),A)G.info(`Using port ${j} instead. Access your site at https://${N}:${j}`)}else if(j=await F.getNextAvailablePort(M+1000,!0),D("setup",`Using port ${j} instead of ${M}`,A),A)G.info(`Using port ${j} instead. Access your site at http://${N}:${j}`)}else j=M,F.usedPorts.add(j),D("setup",`Using standard ${M===443?"HTTPS":"HTTP"} port ${M} for ${N}`,A);await KS(R,N,j,K,B,Y,A,V,J,KR(S.auth),_,S.loadBalancer)}catch(M){D("setup",`Setup failed: ${M}`,A),G.error(`Failed to setup reverse proxy: ${M.message}`),a({domains:[N],hosts:typeof X==="boolean"?X:X?.hosts,certs:typeof X==="boolean"?X:X?.certs,verbose:A,vitePluginUsage:Y})}}function tR(S,R=80,_=443,N){D("redirect",`Starting HTTP redirect server on port ${R}`,S);let K=YR.createServer((B,A)=>{if(N&&B.url){let V=B.url.split("?",1)[0],Z=CR(N,V);if(Z!=null){D("redirect",`Serving ACME challenge ${V}`,S),A.writeHead(200,{"content-type":"text/plain"}),A.end(Z);return}}let X=B.headers.host||"",Y=X.includes(":")?X.slice(0,X.indexOf(":")):X,J=_===443?Y:`${Y}:${_}`;D("redirect",`Redirecting request from ${X}${B.url} to https://${J}`,S),A.writeHead(301,{Location:`https://${J}${B.url}`}),A.end()}).listen(R);o.add(K),D("redirect","HTTP redirect server started",S)}function $S(S){let R={...SR,...S};if(D("proxy",`Starting proxy with options: ${q(R)}`,R?.verbose),R.viaDaemon){if(!R.from||!R.to){G.error("viaDaemon mode requires both `from` and `to`");return}g({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 _=R.to||"",N=_.split(".").pop()?.toLowerCase()||"",K=z.platform==="darwin"&&_&&!_.includes("localhost")&&!_.includes("127.0.0.1"),B=["dev","app","page","new","day","foo"],A=["test","localhost","local","example","invalid"];if(K&&B.includes(N)&&R?.verbose)G.warn(`The .${N} TLD may not work reliably for local development`),G.info(` Google owns .${N} with HSTS preloading, which can bypass local DNS`),G.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(K)import("./chunk-r1k4wgag.js").then(({setupDevelopmentDns:Y})=>{Y({domains:[_],verbose:R.verbose}).then((J)=>{if(J)Promise.resolve().then(()=>{if(R.verbose)if(A.includes(N))G.success(`DNS server started for .${N} domains`);else G.success(`DNS server started for .${N} domains (hosts file entry also added)`)});else D("dns",`Could not start DNS server - ${_} may not resolve in browser`,R.verbose)})}).catch((Y)=>{D("dns",`Failed to start DNS server: ${Y}`,R.verbose)});let X={from:R.from,to:R.to,cleanUrls:R.cleanUrls,https:DR(R),cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,changeOrigin:R.changeOrigin,verbose:R.verbose,regenerateUntrustedCerts:R.regenerateUntrustedCerts};D("proxy",`Server options: ${q(X)}`,R.verbose),cR(X).catch((Y)=>{D("proxy",`Failed to start proxy: ${Y}`,R.verbose),G.error(`Failed to start proxy: ${Y.message}`),a({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 GS(S){return S?.verbose||!1}function hR(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 vR(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 _=GS(R),N=hR(R);if(D("config",`Starting with config: ${q(R,2)}`,_),D("config",`Is multi-proxy? ${"proxies"in R}`,_),D("config",`Hosts management enabled? ${N}`,_),R.viaDaemon){let W="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((x)=>({id:x.id,from:x.from,to:x.to,path:x.path,cleanUrls:x.cleanUrls??R.cleanUrls,changeOrigin:x.changeOrigin??R.changeOrigin,pathRewrites:x.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 g({proxies:W,verbose:_});return}if("proxies"in R&&Array.isArray(R.proxies)){D("servers",`Found ${R.proxies.length} proxies in config`,_);for(let $ of R.proxies)if($.start){let W=`${$.from}-${$.to}`;try{D("watch",`Starting command for ${W} with command: ${$.start.command}`,_),G.info(`Starting command for ${W}...`),await e.startProcess(W,$.start,_);let x=L($.from),T=new URL(x.startsWith("http")?x:`http://${x}`),h=T.hostname||"localhost",d=Number(T.port)||80;try{await b(h,d,_),D("watch",`Dev server is ready at ${h}:${d}`,_)}catch(rR){D("watch",`Connection check failed, but continuing with proxy setup: ${rR}`,_),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(x){throw D("watch",`Failed to start command for ${W}: ${x}`,_),Error(`Failed to start command for ${W}: ${x}`)}}else D("watch",`No start command for proxy ${$.from} -> ${$.to}`,_)}else if("start"in R&&R.start){D("watch","Found start command in single proxy config",_);let $=`${R.from}-${R.to}`;try{if(R.start)D("watch",`Starting command: ${R.start.command}`,_),await e.startProcess($,R.start,_);let W=L(R.from),x=new URL(W.startsWith("http")?W:`http://${W}`),T=x.hostname||"localhost",h=Number(x.port)||80;try{await b(T,h,_),D("watch",`Dev server is ready at ${T}:${h}`,_)}catch(d){D("watch",`Connection check failed, but continuing with proxy setup: ${d}`,_),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(W){throw D("watch",`Failed to run start command: ${W}`,_),Error(`Failed to run start command: ${W}`)}}else D("watch","No start command found in config",_);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||N)){if(!u())try{D("sudo","Pre-acquiring sudo credentials for privileged operations",_),NS("sudo -v",{stdio:"inherit"})}catch{D("sudo","Could not pre-acquire sudo credentials",_)}}let B=[];if(R.productionCerts){if(B=await LR(R.productionCerts,_),B.length>0)D("ssl",`Using ${B.length} production SNI cert(s): ${B.map(($)=>$.serverName).join(", ")}`,_)}if(R.https){let $=B.length>0?null:await P(R);if(!$&&B.length===0){if(D("ssl",`No valid or trusted certificates found for ${K}, generating new ones`,R.verbose),await _R(R),$=await P(R),!$)throw Error(`Failed to load SSL certificates after generation for ${K}`)}else D("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:_,_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:_,_cachedSSLConfig:R._cachedSSLConfig}],X=A.map(($)=>$.to||"rpx.localhost"),Y=B.length>0?B:R._cachedSSLConfig??null,J=X.filter(($)=>$&&!$.includes("localhost")&&!$.includes("127.0.0.1")),V=["dev","app","page","new","day","foo"],Z=["test","localhost","local","example","invalid"],Q=[...new Set(J.map(($)=>$.split(".").pop()?.toLowerCase()))],I=Q.filter(($)=>!!$&&V.includes($));if(I.length>0&&_)G.warn(`The following TLDs may not work reliably for local development: ${I.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(N&&z.platform==="darwin"&&J.length>0){let{setupDevelopmentDns:$}=await import("./chunk-r1k4wgag.js");if(await $({domains:J,verbose:_})){if(_)if(Q.every((T)=>!!T&&Z.includes(T)))G.success(`DNS server started for ${Q.map((T)=>`.${T}`).join(", ")} domains`);else G.success(`DNS server started for ${Q.map((T)=>`.${T}`).join(", ")} domains (hosts file entries also added)`)}else D("dns","Could not start DNS server - custom domains may not resolve",_)}let F=async()=>{D("cleanup","Starting cleanup handler",R.verbose);try{let{tearDownDevelopmentDns:$}=await import("./chunk-r1k4wgag.js");await $({verbose:R.verbose})}catch($){D("cleanup",`Error stopping DNS server: ${$}`,R.verbose)}try{await e.stopAll(R.verbose)}catch($){D("cleanup",`Error stopping processes: ${$}`,R.verbose)}await a({domains:X,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",F),z.on("SIGTERM",F);let O=R.singlePortMode===!0,M=R.httpsPort??443,w=R.httpPort??80,j=R.originGuard?zR(R.originGuard):null,l=!!Y&&(A.length>1||O||B.length>0),c=!Y&&O&&A.length>0;if(l&&Y){D("proxies",`Creating shared HTTPS server for ${A.length} domains on port ${M}`,_);let $=await pR(A,N,_);if(!await f(w,"0.0.0.0",_))tR(_,w,M,R.acmeChallengeWebroot);if(await f(M,"0.0.0.0",_)){if(D("proxies",`Port ${M} is already in use, cannot start shared proxy`,_),_)G.warn(`Port ${M} is in use. Shared HTTPS proxy cannot start.`);return}if(!HR({routeEntries:$,listenPort:M,sslConfig:Y,originGuard:j,verbose:_})){G.error(`Shared HTTPS proxy failed to bind :${M}; not exiting`);return}}else if(c){D("proxies",`Creating shared HTTP server for ${A.length} domains on port ${w}`,_);let $=await pR(A,N,_);if(await f(w,"0.0.0.0",_)){if(D("proxies",`Port ${w} is already in use, cannot start shared proxy`,_),_)G.warn(`Port ${w} is in use. Shared HTTP proxy cannot start.`);return}if(!HR({routeEntries:$,listenPort:w,sslConfig:null,originGuard:j,verbose:_})){G.error(`Shared HTTP proxy failed to bind :${w}; not exiting`);return}}else for(let $ of A)try{let W=$.to||"rpx.localhost";D("proxy",`Starting proxy for ${W} with SSL config: ${!!Y}`,$.verbose),await cR({from:$.from||"localhost:5173",to:W,cleanUrls:$.cleanUrls||!1,https:$.https||!1,cleanup:$.cleanup||!1,vitePluginUsage:$.vitePluginUsage||!1,verbose:$.verbose||!1,_cachedSSLConfig:R._cachedSSLConfig,changeOrigin:$.changeOrigin||!1,loadBalancer:$.loadBalancer,auth:$.auth,path:$.path,pathRewrites:$.pathRewrites})}catch(W){D("proxies",`Failed to start proxy for ${$.to}: ${W}`,$.verbose),G.error(`Failed to start proxy for ${$.to}:`,W)}}async function pR(S,R,_){let N=[],K=new Set;for(let B of S){let A=B.to||"rpx.localhost",X=B.cleanUrls||!1,Y=B.path,J=yR(Y),V=KR(B.auth);if(B.redirect){let Z=wR(B.redirect);N.push({host:A,path:Y,route:{redirect:Z,basePath:J,auth:V}}),D("proxies",`Route: ${A}${Y??""} → redirect ${Z.status} ${Z.to}${V?" (auth)":""}`,_)}else if(B.static)N.push({host:A,path:Y,route:{static:ER(B.static,X),cleanUrls:X,basePath:J,auth:V}}),D("proxies",`Route: ${A}${Y??""} → static ${typeof B.static==="string"?B.static:B.static.dir}${V?" (auth)":""}`,_);else{let Z=L(B.from),Q=new URL(Z.startsWith("http")?Z:`http://${Z}`),I=NR(B.from??Q.host,B.loadBalancer);AR(I),RR.add(I),N.push({host:A,path:Y,route:{sourceHost:Q.host,upstreamPool:I,cleanUrls:X,changeOrigin:B.changeOrigin||!1,pathRewrites:B.pathRewrites,basePath:J,auth:V}}),D("proxies",`Route: ${A}${Y??""} → ${Q.host}${V?" (auth)":""}`,_)}if(K.has(A))continue;if(K.add(A),R&&!fR(A)&&!A.includes("localhost")&&!A.includes("127.0.0.1"))try{if(!(await U([A],_))[0])await y([A],_)}catch{D("hosts",`Could not add hosts entry for ${A}`,_)}}return N}function HR(S){let{routeEntries:R,listenPort:_,sslConfig:N,originGuard:K,verbose:B}=S,A=UR(R),X=FR((V,Z)=>PR(A,V,Z),B),Y=K?(V,Z)=>K(V)??X(V,Z):X,J=qR(B);try{let V=Bun.serve({port:_,hostname:"0.0.0.0",reusePort:gR(),...N?{tls:Array.isArray(N)?N.map((Z)=>({serverName:Z.serverName,key:Z.key,cert:Z.cert})):{key:N.key,cert:N.cert,ca:N.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(Z,Q){return Y(Z,Q)},websocket:J,error(Z){return D("server",`Shared proxy server error: ${Z}`,B),new Response(`Server Error: ${Z.message}`,{status:500})}});return o.add(V),D("proxies",`Shared ${N?"HTTPS":"HTTP"} proxy listening on port ${_} for ${A.size} domains`,B),V}catch(V){return D("proxies",`Failed to start shared proxy: ${V}`,B),console.error("Failed to start shared proxy:",V),null}}function XS(S){if(S?.vitePluginUsage||!S?.verbose)return;if(console.log(""),console.log(` ${k.green(k.bold("rpx"))} ${k.green(`v${AS}`)}`),console.log(` ${k.green("➜")} ${k.dim(S?.from??"")} ${k.dim("➜")} ${k.cyan(S?.ssl?`https://${S?.to}`:`http://${S?.to}`)}`),S?.listenPort!==(S?.ssl?443:80))console.log(` ${k.green("➜")} Listening on port ${S?.listenPort}`);if(S?.cleanUrls)console.log(` ${k.green("➜")} Clean URLs enabled`)}var MN=vR;export{XR as writeEntry,Z_ as watchRegistry,IS as verifyHttpsChain,FS as trustRootCaForBrowsers,h_ as tearDownDevelopmentDns,c_ as syncDevelopmentDnsFromRegistry,nS as stripBasePath,BR as stopHealthChecks,C_ as stopDnsServer,i_ as stopDaemon,cR as startServer,$S as startProxy,vR as startProxies,AR as startHealthChecks,q_ as startDnsServer,D_ as siteIdForHost,gR as shouldReusePort,P_ as setupResolver,O_ as setupDevelopmentDns,eS as serverNameFromCertFilename,gS as serveStaticFile,hS as selectUpstream,q as safeStringify,dS as safeRelativePath,fN as safeDeleteFile,g as runViaDaemon,g_ as runDaemon,y_ as resolverFilePath,k_ as resolverBasenamesForDomains,H_ as resolverBasenameForDomain,ER as resolveStaticRoute,pS as resolveStaticFile,wR as resolveRedirect,CN as resolvePathRewrite,KR as resolveAuth,z_ as renderStartingPage,M_ as renderFailedPage,v_ as removeResolver,L_ as removeLegacyTldResolvers,IR as removeHosts,JR as removeEntry,p_ as releaseDaemonLock,jN as redactSensitive,u_ as reconcileStaleDevelopmentDns,t_ as reconcileDevelopmentDnsOnIdle,A_ as readSiteManifest,J_ as readEntry,a_ as readDaemonPid,QS as readCertSha256Fingerprint,VS as readCertCommonName,Q_ as readAll,CR as readAcmeChallenge,kS as pruneStaleRootCas,N_ as projectNameFromHost,L as primaryUpstreamUrl,G_ as portManager,rS as pathPrefixMatches,WS as parseSha256HashesFromSecurityListing,mS as parseHtpasswd,JS as normalizeSha256Fingerprint,yR as normalizePathPrefix,T_ as normalizeDevDomain,WR as matchesWildcard,oS as matchesAllowedSuffix,PR as matchHostRoute,sS as matchHostList,tS as matchHost,vS as markSuccess,uS as markFailure,PS as loadSSLConfig,Y_ as listDiscoverableSites,HS as listCertSha256HashesByCommonName,fR as isWildcardPattern,HN as isValidRootCA,GR as isValidId,FN as isSingleProxyOptions,qN as isSingleProxyConfig,wS as isRootCaTrustedForSsl,ES as isRootCaFingerprintInKeychains,lR as isProcessElevated,f as isPortInUse,X_ as isPidAlive,EN as isMultiProxyOptions,wN as isMultiProxyConfig,R_ as isLikelyHostname,f_ as isDnsServerRunning,l_ as isDaemonRunning,cS as isCertTrusted,DR as httpsConfig,u as getSudoPassword,US as getSharedDaemonCertPaths,yS as getRootCAPaths,$R as getRegistryDir,kN as getPrimaryDomain,TS as getMacosTrustKeychains,jS as getMacosLoginKeychainPath,m_ as getDaemonRpxDir,b_ as getDaemonPidPath,_R as generateCertificate,V_ as gcStaleEntries,LS as forceTrustCertificate,$_ as findAvailablePort,TN as extractHostname,__ as expandHome,xN as execSudoSync,W_ as escapeHtml,QR as ensureDaemonRunning,bS as enforceBasicAuth,CS as devSslToSniEntries,w_ as devDomainsFromHosts,B_ as detectProjectPreset,bR as deriveIdFromTarget,n_ as defaultDaemonSpawnCommand,SR as defaultConfig,MN as default,D as debugLog,NR as createUpstreamPool,K_ as createSiteResolver,qR as createProxyWebSocketHandler,FR as createProxyFetchHandler,zR as createOriginGuard,lS as contentTypeFor,U_ as contentLooksLikeRpxResolver,SR as config,k as colors,OS as clearSslConfigCache,kR as cleanupCertificates,a as cleanup,U as checkHosts,P as checkExistingCertificates,ZS as certIncludesSanHostnames,LR as buildSniTlsConfig,fS as buildRegistryTlsProxyOptions,aS as buildRedirectLocation,UR as buildHostRoutes,y as addHosts,d_ as acquireDaemonLock,I_ as SiteSupervisor,qS as SHARED_DEV_HOST_CERT_PATH,xS as RPX_ROOT_CA_COMMON_NAME,F_ as RPX_RESOLVER_MARKER,S_ as OnDemandCertManager,MS as MACOS_SYSTEM_KEYCHAIN,zS as MACOS_CA_TRUST_FLAGS,j_ as LEGACY_TLD_RESOLVER_LABELS,OR as DefaultPortManager,x_ as DNS_STATE_VERSION,E_ as DNS_PORT,iS as ACME_CHALLENGE_PREFIX};
|