@stacksjs/rpx 0.11.35 → 0.11.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{Ab as a,Bb as b,Cb as c,Db as d,Eb as e,Fb as f,Gb as g,Hb as h,Ib as i,Jb as j,Kb as k,Lb as l,Mb as m,Nb as n,Ob as o,Pb as p,Qb as q}from"./chunk-35444zrq.js";export{f as shouldReusePort,h as safeStringify,q as safeDeleteFile,p as resolvePathRewrite,g as redactSensitive,j as isValidRootCA,n as isSingleProxyOptions,o as isSingleProxyConfig,b as isProcessElevated,m as isMultiProxyOptions,l as isMultiProxyConfig,a as getSudoPassword,k as getPrimaryDomain,i as extractHostname,d as execSudoSync,e as debugLog,c as authorizeSystemAccess};
1
+ import{Bb as a,Cb as b,Db as c,Eb as d,Fb as e,Gb as f,Hb as g,Ib as h,Jb as i,Kb as j,Lb as k,Mb as l,Nb as m,Ob as n,Pb as o,Qb as p,Rb as q}from"./chunk-w4t1nar9.js";export{f as shouldReusePort,h as safeStringify,q as safeDeleteFile,p as resolvePathRewrite,g as redactSensitive,j as isValidRootCA,n as isSingleProxyOptions,o as isSingleProxyConfig,b as isProcessElevated,m as isMultiProxyOptions,l as isMultiProxyConfig,a as getSudoPassword,k as getPrimaryDomain,i as extractHostname,d as execSudoSync,e as debugLog,c as authorizeSystemAccess};
@@ -1 +1 @@
1
- import{$a as a,ab as b,bb as c,cb as d,db as e,eb as f,fb as g,gb as h,hb as i,ib as j,jb as k,kb as l,lb as m,mb as n,nb as o}from"./chunk-52j763a0.js";import"./chunk-35444zrq.js";export{m as tearDownDevelopmentDns,l as syncDevelopmentDnsFromRegistry,d as stopDnsServer,c as startDnsServer,i as setupResolver,k as setupDevelopmentDns,g as resolverFilePath,n as removeResolver,j as removeLegacyTldResolvers,o as reconcileStaleDevelopmentDns,f as isRpxDevelopmentDnsAnswering,e as isDnsServerRunning,h as contentLooksLikeRpxResolver,b as RPX_RESOLVER_MARKER,a as DNS_PORT};
1
+ import{ab as a,bb as b,cb as c,db as d,eb as e,fb as f,gb as g,hb as h,ib as i,jb as j,kb as k,lb as l,mb as m,nb as n,ob as o}from"./chunk-abrzcb7x.js";import"./chunk-w4t1nar9.js";export{m as tearDownDevelopmentDns,l as syncDevelopmentDnsFromRegistry,d as stopDnsServer,c as startDnsServer,i as setupResolver,k as setupDevelopmentDns,g as resolverFilePath,n as removeResolver,j as removeLegacyTldResolvers,o as reconcileStaleDevelopmentDns,f as isRpxDevelopmentDnsAnswering,e as isDnsServerRunning,h as contentLooksLikeRpxResolver,b as RPX_RESOLVER_MARKER,a as DNS_PORT};
@@ -46,4 +46,4 @@ export type ConfigOf = Config
46
46
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}async prompt(Q){if(O())return Promise.resolve(!0);return new Promise((U)=>{console.error(`${K.cyan("?")} ${Q} (y/n) `);let X=(Z)=>{let $=Z.toString().trim().toLowerCase();L.stdin.removeListener("data",X);try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!1)}catch{}L.stdin.pause(),console.error(""),U($==="y"||$==="yes")};try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!0)}catch{}L.stdin.resume(),L.stdin.once("data",X)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...U){if(!this.enabled)return;let X=Q;if(U&&U.length>0){let H=/%([sdijfo%])/g,q=0;if(X=Q.replace(H,(_,A)=>{if(A==="%")return"%";if(q>=U.length)return _;let z=U[q++];switch(A){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return _}}),q<U.length)X+=` ${U.slice(q).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let H=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",q=this.options.showIcons===!1?"":`${K.blue("◐")} `;console.error(`${q}${H} ${K.cyan(Z)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
47
47
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(Q,U=!1){if(!this.enabled||!this.shouldStyleConsole()||!L.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*X/100),$=Q.barLength-Z,Y=K.green("━".repeat(Z)),G=K.gray("━".repeat($)),J=`[${Y}${G}]`,H=`${X}%`.padStart(4),q=Q.message?` ${Q.message}`:"",_=this.options.showIcons===!1?"":U||X===100?K.green("✓"):K.blue("▶"),A=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",z=`\r${_}${A} ${J} ${H}${q}`,W=L.stdout.columns||80,V=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${V}`,L.stdout.write(Q.lastRenderedLine),U)L.stdout.write(`
48
48
  `)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||O()||!L.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(O()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let U=await DQ(this.config.logDirectory),X=[];for(let Z of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let Y=GQ(this.config.logDirectory,Z);if(Q.before)try{if((await YQ(Y)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${Y}:`,G);continue}X.push(Y)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Z of X)try{await NQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}var W8=new BQ("stacks");var f0=new BQ("rpx",{showTags:!1});function hX(){return process.env.SUDO_PASSWORD}function dX(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function L8(Q={}){if(process.platform==="win32")return!0;if(dX()||!!hX())return!0;let U=Q.exec??cQ;try{return U("sudo -n true",{stdio:"ignore"}),!0}catch{if(!Q.interactive)return!1}try{return U("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function w8(Q){if(dX())return cQ(Q,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let U=hX(),X=Q.replace(/'/g,"'\\''");if(U)return cQ(`echo '${U}' | sudo -S sh -c '${X}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return cQ(`sudo -n sh -c '${X}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function bX(Q,U,X){if(X)f0.debug(`[rpx:${Q}] ${U}`)}function K8(){let Q=process.env.RPX_REUSE_PORT;return Q==="1"||Q==="true"}var yX="[redacted]",p0=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),u0=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function m0(Q){let U=Q.toLowerCase();return p0.has(U)||U.endsWith("password")||U.includes("secret")||U.includes("token")}function OU(Q){if(Array.isArray(Q))return Q.map((X)=>OU(X));if(typeof Q==="string")return u0.test(Q)?yX:Q;if(!Q||typeof Q!=="object")return Q;let U={};for(let[X,Z]of Object.entries(Q)){if(m0(X)){U[X]=yX;continue}U[X]=OU(Z)}return U}function j8(Q,U){return JSON.stringify(OU(Q),null,U)}function F8(Q){if(fX(Q))return Q.proxies.map((U)=>{let X=U.to||"stacks.localhost";return X.startsWith("http")?new URL(X).hostname:X});if(pX(Q)){let U=Q.to||"stacks.localhost";return[U.startsWith("http")?new URL(U).hostname:U]}return["stacks.localhost"]}function I8(Q){return typeof Q==="object"&&Q!==null&&"certificate"in Q&&"privateKey"in Q&&typeof Q.certificate==="string"&&typeof Q.privateKey==="string"}function M8(Q){if(!Q)return"stacks.localhost";if(fX(Q)&&Q.proxies.length>0)return Q.proxies[0].to||"stacks.localhost";if(pX(Q))return Q.to||"stacks.localhost";return"stacks.localhost"}function V8(Q){return!!(Q&&("proxies"in Q)&&Array.isArray(Q.proxies))}function fX(Q){return"proxies"in Q&&Array.isArray(Q.proxies)}function pX(Q){return"to"in Q&&typeof Q.to==="string"}function D8(Q){return!!(Q&&("to"in Q)&&!("proxies"in Q))}function N8(Q,U){if(!U||U.length===0)return null;for(let X of U)if(Q===X.from||Q.startsWith(`${X.from}/`)){let Z=X.to.startsWith("http")?new URL(X.to).host:X.to,$=X.stripPrefix===!0?Q.slice(X.from.length)||"/":Q;return{targetHost:Z,targetPath:$}}return null}async function E8(Q,U){try{await vX.unlink(Q),bX("certificates",`Successfully deleted: ${Q}`,U)}catch(X){if(X.code!=="ENOENT")bX("certificates",`Warning: Could not delete ${Q}: ${X}`,U)}}
49
- export{r as zb,hX as Ab,dX as Bb,L8 as Cb,w8 as Db,bX as Eb,K8 as Fb,OU as Gb,j8 as Hb,F8 as Ib,I8 as Jb,M8 as Kb,V8 as Lb,fX as Mb,pX as Nb,D8 as Ob,N8 as Pb,E8 as Qb};
49
+ export{r as Ab,hX as Bb,dX as Cb,L8 as Db,w8 as Eb,bX as Fb,K8 as Gb,OU as Hb,j8 as Ib,F8 as Jb,I8 as Kb,M8 as Lb,V8 as Mb,fX as Nb,pX as Ob,D8 as Pb,N8 as Qb,E8 as Rb};
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{$ as wR,$a as yS,A as L_,Aa as YS,B as y,Ba as $R,C as e,Ca as GR,D as IR,Da as $S,E as O_,Ea as GS,F as U,Fa as JS,G as o,Ga as QS,H as c_,Ha as VS,I as h_,Ia as ZS,J as u_,Ja as zS,K as RR,Ka as DS,L as _R,La as FS,M as v_,Ma as IS,N as SR,Na as HS,O as m_,Oa as WS,P as HR,Pa as ES,Q as b_,Qa as P,R as WR,Ra as UR,S as l_,Sa as L,T as a_,Ta as MS,U as d_,Ua as jS,V as p_,Va as wS,W as g_,Wa as TS,X as ER,Xa as kS,Y as MR,Ya as fS,Z as i_,Za as qS,_ as jR,_a as CS,a as X,aa as QR,ab as US,b as s,ba as n_,bb as PS,c as G_,ca as TR,cb as LS,d as J_,da as t_,db as OS,e as Q_,ea as kR,f as V_,fa as s_,fb as cS,g as Z_,ga as fR,gb as hS,h as z_,ha as dR,hb as uS,i as D_,ia as r_,ib as vS,j as F_,ja as qR,jb as mS,k as I_,ka as e_,kb as bS,l as H_,la as o_,lb as lS,m as W_,ma as CR,mb as aS,n as E_,na as RS,nb as dS,o as M_,oa as _S,ob as pS,p as j_,pa as SS,pb as gS,q as w_,qa as AS,qb as iS,r as T_,ra as xS,rb as nS,s as k_,sa as NS,sb as tS,t as f_,ta as BS,tb as sS,u as q_,ua as C,ub as rS,v as C_,va as KS,vb as eS,w as y_,wa as yR,wb as JR,x as U_,xa as XS,xb as oS,y as P_,ya as XR,yb as RA,z as r,za as YR}from"./chunk-52j763a0.js";import{Ab as lR,Bb as Wx,Cb as Ex,Db as Mx,Eb as A,Fb as aR,Gb as jx,Hb as q,Ib as wx,Jb as Tx,Kb as kx,Lb as fx,Mb as qx,Nb as Cx,Ob as yx,Pb as Ux,Qb as Px,zb as FR}from"./chunk-35444zrq.js";import{execSync as A_}from"node:child_process";import*as AR from"node:http";import*as pR from"node:net";import*as gR from"node:os";import*as iR from"node:path";import*as H from"node:process";var b=(_,R)=>(S)=>`\x1B[${_}m${S}\x1B[${R}m`,M={bold:b(1,22),dim:b(2,22),green:b(32,39),cyan:b(36,39)};import*as uR from"node:fs";import*as vR from"node:path";import*as T from"node:process";function mR(_,R){let x=(R&&R!=="/"?`${_}${R}`:_).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return x.length>0?x:"rpx"}async function l(_){if(_.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let R=_.verbose??!1,S=_.registryDir,x=new Set,Y=_.proxies.map(($)=>{let D=$.id??mR($.to,$.path);if(!YR(D))throw Error(`invalid registry id "${D}" derived from to="${$.to}"`);if(x.has(D))throw Error(`duplicate registry id "${D}" — set an explicit \`id\` on one of the proxies`);return x.add(D),{...$,id:D}}),K=new Date().toISOString();for(let $ of Y)await $R({id:$.id,from:$.from,to:$.to,path:$.path,pid:_.persistent?void 0:T.pid,cwd:T.cwd(),createdAt:K,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites,static:$.static,loadBalancer:$.loadBalancer},S,R);let N=await JR({rpxDir:_.rpxDir,verbose:R,spawnCommand:_.spawnCommand,startupTimeoutMs:_.startupTimeoutMs,spawnEnv:_.spawnEnv});for(let $ of Y){let D=$.static?`static ${typeof $.static==="string"?$.static:$.static.dir}`:$.from;X.success(`https://${$.to} → ${D}`)}if(X.info(`(via rpx daemon pid=${N.pid}; \`rpx daemon:status\` to inspect)`),_.detached)return;let Q=!1,G=S??XR(),J=Y.map(($)=>$.id),V=async()=>{if(Q)return;Q=!0;for(let $ of J)await GR($,S,R).catch((D)=>{A("runner",`removeEntry(${$}) failed: ${D}`,R)})},Z=($)=>{A("runner",`received ${$}, unregistering ${J.length} entries`,R),V().finally(()=>T.exit(0))};T.once("SIGINT",Z),T.once("SIGTERM",Z),T.once("exit",()=>{if(Q)return;for(let $ of J)try{uR.unlinkSync(vR.join(G,`${$}.json`))}catch{}}),await new Promise(()=>{})}import{spawn as eR}from"node:child_process";import*as a from"node:process";class d{processes=new Map;isShuttingDown=!1;async startProcess(_,R,S){if(this.processes.has(_)){A("start",`Process ${_} is already running`,S);return}let[x,...Y]=R.command.split(" "),K=R.cwd||a.cwd();A("start",`Starting process ${_}:`,S),A("start",` Command: ${x} ${Y.join(" ")}`,S),A("start",` Working directory: ${K}`,S),A("start",` Environment variables: ${q(R.env)}`,S);let N=eR(x,Y,{cwd:K,env:{...a.env,...R.env},shell:!0,stdio:"inherit"});return this.processes.set(_,{command:R.command,cwd:K,process:N,env:R.env}),new Promise((Q,G)=>{if(N.on("error",(J)=>{if(!this.isShuttingDown)A("start",`Process ${_} failed to start: ${J}`,S),this.processes.delete(_),G(J)}),N.on("exit",(J)=>{if(!this.isShuttingDown&&J!==null&&J!==0)A("start",`Process ${_} exited with code ${J}; leaving the proxy running`,S),this.processes.delete(_),G(Error(`Process ${_} exited with code ${J}`))}),S)N.stdout?.on("data",(J)=>{A("process",`[${_}] ${J.toString().trim()}`,!0)}),N.stderr?.on("data",(J)=>{A("process",`[${_}] ERR: ${J.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&N.killed)this.processes.delete(_),G(Error(`Process ${_} was killed during startup`));else A("start",`Process ${_} started successfully`,S),Q()},1000)})}async stopProcess(_,R){let S=this.processes.get(_);if(!S?.process){A("start",`No process found for ${_}`,R);return}return A("start",`Stopping process ${_}`,R),new Promise((x)=>{if(!S.process){x();return}S.process.once("exit",()=>{this.processes.delete(_),A("start",`Process ${_} stopped`,R),x()});try{S.process.kill("SIGTERM"),setTimeout(()=>{if(S.process){A("start",`Force killing process ${_}`,R);try{S.process.kill("SIGKILL")}catch(Y){}}},3000)}catch(Y){A("start",`Error stopping process ${_}: ${Y}`,R),this.processes.delete(_),x()}})}async stopAll(_){if(this.isShuttingDown){A("start","Already shutting down, skipping duplicate stopAll call",_);return}this.isShuttingDown=!0,A("start","Stopping all processes",_);let R=Array.from(this.processes.keys()).map((S)=>this.stopProcess(S,_).catch((x)=>{X.error(`Failed to stop process ${S}:`,x)}));await Promise.allSettled(R),this.processes.clear(),this.isShuttingDown=!1}isRunning(_){let R=this.processes.get(_);return!!R?.process&&!R.process.killed}}var JA=new d;import{timingSafeEqual as oR}from"node:crypto";function R_(_,R){if(_==null)return!1;let S=Buffer.from(_),x=Buffer.from(R);if(S.length!==x.length)return!1;return oR(S,x)}function p(_){return _.toLowerCase().replace(/\.$/,"")}var __=["/.well-known/acme-challenge/"];function S_(_){let R=_.headers.get("host");if(R)return p(R.split(":")[0]);try{return p(new URL(_.url).hostname)}catch{return""}}function VR(_){let R=_.header.toLowerCase(),S=new Set,x=[];for(let G of _.hosts){let J=p(G);if(J.startsWith("*."))x.push(J);else S.add(J)}let Y=_.exemptPaths??__,K=_.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
2
- `,N=(G)=>{let J=p(G);return S.has(J)||x.some((V)=>QR(J,V))},Q=(G)=>{let J=S_(G);if(!N(J))return;let V="/";try{V=new URL(G.url).pathname}catch{}if(Y.some((Z)=>V.startsWith(Z)))return;if(R_(G.headers.get(R),_.value))return;return new Response(K,{status:403,headers:{"content-type":"text/plain"}})};return Q.protects=N,Q}var i=new d,x_="0.12.0",N_=new yR("0.0.0.0"),h=new Set,t=new Set,ZR=!1,g=null,zR=null;async function v(_){if(ZR)return A("cleanup","Cleanup already in progress, skipping",_?.verbose),zR||Promise.resolve();ZR=!0,A("cleanup","Starting cleanup process",_?.verbose),zR=new Promise((R)=>{g=R});try{await i.stopAll(_?.verbose),X.info("Shutting down proxy servers...");let R=[],S=Array.from(h).map((x)=>new Promise((Y)=>{let K=x;try{if(typeof K.stop==="function")K.stop(!0),A("cleanup","Bun server stopped",_?.verbose),Y();else if(typeof K.close==="function")K.close(()=>{A("cleanup","Server closed successfully",_?.verbose),Y()});else Y()}catch(N){A("cleanup",`Error stopping server: ${N}`,_?.verbose),Y()}}));R.push(...S),h.clear();for(let x of t)_R(x);if(t.clear(),_?.hosts&&_.domains?.length){A("cleanup","Cleaning up hosts file entries",_?.verbose),A("cleanup",`Original domains for cleanup: ${JSON.stringify(_.domains)}`,_?.verbose);let x=_.domains.filter((Y)=>{if(Y==="test.local")return!0;return Y!=="localhost"&&!Y.startsWith("localhost.")&&Y!=="127.0.0.1"});if(A("cleanup",`Filtered domains for cleanup: ${JSON.stringify(x)}`,_?.verbose),x.length>0)X.info("Cleaning up hosts file entries..."),R.push(UR(x,_?.verbose).then(()=>{A("cleanup",`Removed hosts entries for ${x.join(", ")}`,_?.verbose)}).catch((Y)=>{A("cleanup",`Failed to remove hosts entries: ${Y}`,_?.verbose),X.warn(`Failed to clean up hosts file entries for ${x.join(", ")}:`,Y)}))}if(_?.certs&&_.domains?.length){A("cleanup","Cleaning up SSL certificates",_?.verbose),X.info("Cleaning up SSL certificates...");let x=_.domains.map(async(Y)=>{try{await IR(Y,_?.verbose),A("cleanup",`Removed certificates for ${Y}`,_?.verbose)}catch(K){A("cleanup",`Failed to remove certificates for ${Y}: ${K}`,_?.verbose),X.warn(`Failed to clean up certificates for ${Y}:`,K)}});R.push(...x)}await Promise.allSettled(R),A("cleanup","All cleanup tasks completed successfully",_?.verbose),X.success("All cleanup tasks completed successfully")}catch(R){A("cleanup",`Error during cleanup: ${R}`,_?.verbose),X.error("Error during cleanup:",R)}finally{if(g)g();g=null,ZR=!1;let R=_&&"vitePluginUsage"in _&&_.vitePluginUsage===!0;if(H.env.NODE_ENV!=="test"&&H.env.BUN_ENV!=="test"&&!R)H.exit(0)}return zR}var DR=!1;function nR(_){if(DR){A("signal",`Received second ${_} signal, forcing exit`,!0),H.exit(1);return}DR=!0,A("signal",`Received ${_} signal, initiating cleanup`,!0),v().catch((R)=>{A("signal",`Cleanup failed after ${_}: ${R}`,!0),H.exit(1)}).finally(()=>{DR=!1})}H.once("SIGINT",()=>nR("SIGINT"));H.once("SIGTERM",()=>nR("SIGTERM"));H.on("uncaughtException",(_)=>{X.error("Uncaught exception (continuing):",_)});H.on("unhandledRejection",(_)=>{X.error("Unhandled rejection (continuing):",_)});async function u(_,R,S,x=5){A("connection",`Testing connection to ${_}:${R} (retries left: ${x})`,S);let Y=15000,K=Date.now();if(H.env.RPX_BYPASS_CONNECTION_TEST==="true"){A("connection",`Bypassing connection test for ${_}:${R} due to RPX_BYPASS_CONNECTION_TEST flag`,S);return}let N=()=>new Promise((Q,G)=>{let J=pR.connect({host:_,port:R,timeout:3000});J.once("connect",()=>{A("connection",`Successfully connected to ${_}:${R}`,S),J.end(),Q()}),J.once("timeout",()=>{A("connection",`Connection to ${_}:${R} timed out`,S),J.destroy(),G(Error("Connection timed out"))}),J.once("error",(V)=>{A("connection",`Failed to connect to ${_}:${R}: ${V}`,S),J.destroy(),G(V)})});try{await N()}catch(Q){let G=Q;if(Date.now()-K>Y){A("connection",`Connection test timed out after ${Y}ms, but continuing anyway`,S),X.warn(`Connection test to ${_}:${R} timed out, but RPX will try to proceed anyway.`);return}if(G.code==="ECONNREFUSED"&&x>0)return A("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${x} retries left)`,S),await new Promise((V)=>setTimeout(V,2000)),u(_,R,S,x-1);if(x>0)try{A("connection",`Trying HTTP request to ${_}:${R}`,S),await new Promise((V,Z)=>{let $=AR.request({hostname:_,port:R,path:"/",method:"HEAD",timeout:5000},(D)=>{A("connection",`Received HTTP response with status: ${D.statusCode}`,S),V()});$.on("error",(D)=>Z(D)),$.on("timeout",()=>{$.destroy(),Z(Error("HTTP request timed out"))}),$.end()}),A("connection",`HTTP request to ${_}:${R} succeeded`,S);return}catch(V){return A("connection",`HTTP request to ${_}:${R} failed: ${V}`,S),A("connection",`Retrying socket connection in 2 seconds... (${x} retries left)`,S),await new Promise((Z)=>setTimeout(Z,2000)),u(_,R,S,x-1)}let J=`Failed to connect to ${_}:${R} after ${5-x} attempts: ${G.message}`;A("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,S),X.warn(J),X.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 PR(_){A("server",`Starting server with options: ${q(_)}`,_.verbose);let R=U(_.from),S=new URL(R.startsWith("http")?R:`http://${R}`),x=new URL((_.to?.startsWith("http")?_.to:`http://${_.to}`)||"rpx.localhost"),Y=Number.parseInt(S.port)||(S.protocol.includes("https:")?443:80),K=[x.hostname];if(LR(_)&&!x.hostname.includes("localhost")&&!x.hostname.includes("127.0.0.1")){A("hosts",`Checking if hosts file entry exists for: ${x.hostname}`,_?.verbose);try{if(!(await L(K,_.verbose))[0]){X.info(`Adding ${x.hostname} to hosts file...`),X.info("This may require sudo/administrator privileges");try{await P(K,_.verbose)}catch(G){if(X.error("Failed to add hosts entry:",G.message),X.warn("You can manually add this entry to your hosts file:"),X.warn(`127.0.0.1 ${x.hostname}`),X.warn(`::1 ${x.hostname}`),H.platform==="win32")X.warn("On Windows:"),X.warn("1. Run notepad as administrator"),X.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else X.warn("On Unix systems:"),X.warn("sudo nano /etc/hosts")}}else A("hosts",`Host entry already exists for ${x.hostname}`,_.verbose)}catch(Q){X.error("Failed to check hosts file:",Q.message)}}try{await u(S.hostname,Y,_.verbose)}catch(Q){A("server",`Connection test failed: ${Q}`,_.verbose),X.error(Q.message),X.warn("Continuing with proxy setup despite connection test failure..."),X.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let N=_._cachedSSLConfig||null;if(_.https)try{if(_.https===!0)_.https=e({..._,to:x.hostname});if(N=await y({..._,to:x.hostname,https:_.https}),!N){if(A("ssl",`Generating new certificates for ${x.hostname}`,_.verbose),await r({..._,from:S.toString(),to:x.hostname,https:_.https}),N=await y({..._,to:x.hostname,https:_.https}),!N)throw Error(`Failed to load SSL configuration after generating certificates for ${x.hostname}`)}}catch(Q){throw A("server",`SSL setup failed: ${Q}`,_.verbose),Q}A("server",`Setting up reverse proxy with SSL config for ${x.hostname}`,_.verbose),await K_({..._,from:R,originalFrom:_.from||R,to:x.hostname,fromPort:Y,sourceUrl:{hostname:S.hostname,host:S.host},ssl:N})}async function B_(_,R,S,x,Y,K,N,Q,G,J,V,Z){A("proxy",`Creating proxy server ${_} -> ${R} with cleanUrls: ${Q}`,N);let $=o(V??x.host,Z);RR($);let D=[{host:R,route:{sourceHost:x.host,upstreamPool:$,cleanUrls:Q||!1,changeOrigin:G||!1,basePath:"/",auth:J}}];if(!n({routeEntries:D,listenPort:S,sslConfig:Y,originGuard:null,verbose:N??!1}))throw _R($),Error(`Failed to start proxy server for ${R} on port ${S}`);t.add($),$_({from:_,to:R,vitePluginUsage:K,listenPort:S,ssl:!!Y,cleanUrls:Q,verbose:N})}async function K_(_){A("setup",`Setting up reverse proxy: ${q(_)}`,_.verbose);let{from:R,originalFrom:S,to:x,sourceUrl:Y,ssl:K,verbose:N,cleanup:Q,vitePluginUsage:G,changeOrigin:J,cleanUrls:V}=_,Z=80,$=443,D="0.0.0.0",k=_.portManager||N_,O=LR(_);try{if(O&&x&&!x.includes("localhost")&&!x.includes("127.0.0.1")){if(!(await L([x],N))[0]){X.warn(`The hostname ${x} isn't in your hosts file. Adding it now...`);try{await P([x],N),X.success(`Added ${x} to your hosts file.`)}catch(c){X.error(`Failed to add ${x} to your hosts file: ${c}`),X.info(`You may need to manually add '127.0.0.1 ${x}' to your /etc/hosts file.`)}}}else if(O&&H.platform!=="darwin"&&x&&x.includes("localhost")&&!x.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await L([x],N))[0]){A("hosts",`${x} not found in hosts file, adding...`,N);try{await P([x],N)}catch(c){A("hosts",`Failed to add ${x} to hosts file: ${c}`,N)}}}if(K&&!k.usedPorts.has(Z)){if(!await C(Z,D,N))A("setup","Starting HTTP redirect server",N),tR(N),k.usedPorts.add(Z);else if(A("setup","Port 80 is in use, skipping HTTP redirect",N),N)X.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let F=K?$:Z,j=await C(F,D,N),E;if(j){if(A("setup",`Port ${F} is already in use`,N),N)X.warn(`Port ${F} is already in use. This may be another instance of rpx or another service.`);if(F===443){if(E=await k.getNextAvailablePort(3443,!0),A("setup",`Using port ${E} instead of ${F}`,N),N)X.info(`Using port ${E} instead. Access your site at https://${x}:${E}`)}else if(E=await k.getNextAvailablePort(F+1000,!0),A("setup",`Using port ${E} instead of ${F}`,N),N)X.info(`Using port ${E} instead. Access your site at http://${x}:${E}`)}else E=F,k.usedPorts.add(E),A("setup",`Using standard ${F===443?"HTTPS":"HTTP"} port ${F} for ${x}`,N);await B_(R,x,E,Y,K,G,N,V,J,SR(_.auth),S,_.loadBalancer)}catch(F){A("setup",`Setup failed: ${F}`,N),X.error(`Failed to setup reverse proxy: ${F.message}`),v({domains:[x],hosts:typeof Q==="boolean"?Q:Q?.hosts,certs:typeof Q==="boolean"?Q:Q?.certs,verbose:N,vitePluginUsage:G})}}function tR(_,R=80,S=443,x,Y){A("redirect",`Starting HTTP redirect server on port ${R}`,_);let K=AR.createServer((N,Q)=>{let G=N.url?N.url.split("?",1)[0]:"";if(G.startsWith("/.well-known/acme-challenge/")){if(Y){let $=Y.challengeStore.handlePath(G);if($!==void 0){A("redirect",`Serving on-demand ACME challenge ${G}`,_),Q.writeHead(200,{"content-type":"text/plain"}),Q.end($);return}}if(x){let $=jR(x,G);if($!=null){A("redirect",`Serving ACME challenge ${G}`,_),Q.writeHead(200,{"content-type":"text/plain"}),Q.end($);return}}if(Y){Q.writeHead(404,{"content-type":"text/plain"}),Q.end("challenge not found");return}}let J=N.headers.host||"",V=J.includes(":")?J.slice(0,J.indexOf(":")):J;if(Y&&V&&!Y.hasCert(V))Y.ensureCert(V).catch(()=>{});let Z=S===443?V:`${V}:${S}`;A("redirect",`Redirecting request from ${J}${N.url} to https://${Z}`,_),Q.writeHead(301,{Location:`https://${Z}${N.url}`}),Q.end()}).listen(R);h.add(K),A("redirect","HTTP redirect server started",_)}function X_(_){let R={...s,..._};if(A("proxy",`Starting proxy with options: ${q(R)}`,R?.verbose),R.viaDaemon){if(!R.from||!R.to){X.error("viaDaemon mode requires both `from` and `to`");return}l({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((G)=>{X.error(`Failed to register with rpx daemon: ${G.message}`),H.exit(1)});return}let S=R.to||"",x=S.split(".").pop()?.toLowerCase()||"",Y=H.platform==="darwin"&&S&&!S.includes("localhost")&&!S.includes("127.0.0.1"),K=["dev","app","page","new","day","foo"],N=["test","localhost","local","example","invalid"];if(Y&&K.includes(x)&&R?.verbose)X.warn(`The .${x} TLD may not work reliably for local development`),X.info(` Google owns .${x} with HSTS preloading, which can bypass local DNS`),X.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(Y)import("./chunk-j8pg56tn.js").then(({setupDevelopmentDns:G})=>{G({domains:[S],verbose:R.verbose}).then((J)=>{if(J)Promise.resolve().then(()=>{if(R.verbose)if(N.includes(x))X.success(`DNS server started for .${x} domains`);else X.success(`DNS server started for .${x} domains (hosts file entry also added)`)});else A("dns",`Could not start DNS server - ${S} may not resolve in browser`,R.verbose)})}).catch((G)=>{A("dns",`Failed to start DNS server: ${G}`,R.verbose)});let Q={from:R.from,to:R.to,cleanUrls:R.cleanUrls,https:e(R),cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,changeOrigin:R.changeOrigin,verbose:R.verbose,regenerateUntrustedCerts:R.regenerateUntrustedCerts};A("proxy",`Server options: ${q(Q)}`,R.verbose),PR(Q).catch((G)=>{A("proxy",`Failed to start proxy: ${G}`,R.verbose),X.error(`Failed to start proxy: ${G.message}`),v({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 Y_(_){return _?.verbose||!1}function LR(_){if(_?.hostsManagement===!1)return!1;let R=_?.cleanup;if(R===!1)return!1;if(R&&typeof R==="object"&&R.hosts===!1)return!1;return!0}async function OR(_){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(_)R={...R,..._};let S=Y_(R),x=LR(R);if(A("config",`Starting with config: ${q(R,2)}`,S),A("config",`Is multi-proxy? ${"proxies"in R}`,S),A("config",`Hosts management enabled? ${x}`,S),R.viaDaemon){let z="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((I)=>({id:I.id,from:I.from,to:I.to,path:I.path,cleanUrls:I.cleanUrls??R.cleanUrls,changeOrigin:I.changeOrigin??R.changeOrigin,pathRewrites:I.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 l({proxies:z,verbose:S});return}if("proxies"in R&&Array.isArray(R.proxies)){A("servers",`Found ${R.proxies.length} proxies in config`,S);for(let B of R.proxies)if(B.start){let z=`${B.from}-${B.to}`;try{A("watch",`Starting command for ${z} with command: ${B.start.command}`,S),X.info(`Starting command for ${z}...`),await i.startProcess(z,B.start,S);let I=U(B.from),W=new URL(I.startsWith("http")?I:`http://${I}`),w=W.hostname||"localhost",f=Number(W.port)||80;try{await u(w,f,S),A("watch",`Dev server is ready at ${w}:${f}`,S)}catch(xR){A("watch",`Connection check failed, but continuing with proxy setup: ${xR}`,S),X.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(I){throw A("watch",`Failed to start command for ${z}: ${I}`,S),Error(`Failed to start command for ${z}: ${I}`)}}else A("watch",`No start command for proxy ${B.from} -> ${B.to}`,S)}else if("start"in R&&R.start){A("watch","Found start command in single proxy config",S);let B=`${R.from}-${R.to}`;try{if(R.start)A("watch",`Starting command: ${R.start.command}`,S),await i.startProcess(B,R.start,S);let z=U(R.from),I=new URL(z.startsWith("http")?z:`http://${z}`),W=I.hostname||"localhost",w=Number(I.port)||80;try{await u(W,w,S),A("watch",`Dev server is ready at ${W}:${w}`,S)}catch(f){A("watch",`Connection check failed, but continuing with proxy setup: ${f}`,S),X.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(z){throw A("watch",`Failed to run start command: ${z}`,S),Error(`Failed to run start command: ${z}`)}}else A("watch","No start command found in config",S);let Y="proxies"in R&&Array.isArray(R.proxies)?R.proxies[0]?.to:("to"in R)?R.to:"rpx.localhost";if(H.platform!=="win32"&&(R.https||x)){if(!lR())try{A("sudo","Pre-acquiring sudo credentials for privileged operations",S),A_("sudo -v",{stdio:"inherit"})}catch{A("sudo","Could not pre-acquire sudo credentials",S)}}let K=[];if(R.productionCerts){if(K=await qR(R.productionCerts,S),K.length>0)A("ssl",`Using ${K.length} production SNI cert(s): ${K.map((B)=>B.serverName).join(", ")}`,S)}if(R.https){let B=K.length>0?null:await y(R);if(!B&&K.length===0){if(A("ssl",`No valid or trusted certificates found for ${Y}, generating new ones`,R.verbose),await r(R),B=await y(R),!B)throw Error(`Failed to load SSL certificates after generation for ${Y}`)}else A("ssl",`Using existing and trusted certificates for ${Y}`,R.verbose);R._cachedSSLConfig=B}let N="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((B)=>({...B,https:R.https,cleanup:R.cleanup,cleanUrls:B.cleanUrls??("cleanUrls"in R?R.cleanUrls:!1),vitePluginUsage:R.vitePluginUsage,changeOrigin:B.changeOrigin??R.changeOrigin,verbose:S,_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:S,_cachedSSLConfig:R._cachedSSLConfig}],Q=N.map((B)=>B.to||"rpx.localhost"),G=K.length>0?K:R._cachedSSLConfig??null,J=Q.filter((B)=>B&&!B.includes("localhost")&&!B.includes("127.0.0.1")),V=["dev","app","page","new","day","foo"],Z=["test","localhost","local","example","invalid"],$=[...new Set(J.map((B)=>B.split(".").pop()?.toLowerCase()))],D=$.filter((B)=>!!B&&V.includes(B));if(D.length>0&&S)X.warn(`The following TLDs may not work reliably for local development: ${D.map((B)=>`.${B}`).join(", ")}`),X.info(" These TLDs have HSTS preloading which can bypass local DNS"),X.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(x&&H.platform==="darwin"&&J.length>0){let{setupDevelopmentDns:B}=await import("./chunk-j8pg56tn.js");if(await B({domains:J,verbose:S})){if(S)if($.every((W)=>!!W&&Z.includes(W)))X.success(`DNS server started for ${$.map((W)=>`.${W}`).join(", ")} domains`);else X.success(`DNS server started for ${$.map((W)=>`.${W}`).join(", ")} domains (hosts file entries also added)`)}else A("dns","Could not start DNS server - custom domains may not resolve",S)}let k=async()=>{A("cleanup","Starting cleanup handler",R.verbose);try{let{tearDownDevelopmentDns:B}=await import("./chunk-j8pg56tn.js");await B({verbose:R.verbose})}catch(B){A("cleanup",`Error stopping DNS server: ${B}`,R.verbose)}try{await i.stopAll(R.verbose)}catch(B){A("cleanup",`Error stopping processes: ${B}`,R.verbose)}await v({domains:Q,hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose||!1})};H.on("SIGINT",k),H.on("SIGTERM",k);let O=R.singlePortMode===!0,F=R.httpsPort??443,j=R.httpPort??80,E=R.originGuard?VR(R.originGuard):null,m=!!G&&(N.length>1||O||K.length>0),c=!G&&O&&N.length>0;if(m&&G){A("proxies",`Creating shared HTTPS server for ${N.length} domains on port ${F}`,S);let B=await bR(N,x,S),z=null,I=R.onDemandTls,W=I?.enabled?new CR({config:I,certsDir:I.certsDir??R.productionCerts?.certsDir??iR.join(gR.homedir(),".stacks","rpx","on-demand-certs"),initial:K,verbose:S,onCertAdded:(NR)=>{xR(NR)}}):null,w=null,f=!1;async function xR(NR){if(w=NR,f)return;f=!0;try{while(w){let cR=w;if(w=null,A("proxies",`rebuilding :${F} with ${cR.length} SNI cert(s)`,S),z)h.delete(z),z.stop(!1);let BR=!1;for(let KR=0;!BR&&KR<60;KR++){let hR=n({routeEntries:B,listenPort:F,sslConfig:cR,originGuard:E,verbose:S});if(hR){z=hR,BR=!0;break}await new Promise((rR)=>setTimeout(rR,Math.min(25*2**Math.min(KR,4),500)))}if(!BR)X.error(`rpx: CRITICAL — could not rebind :${F} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{f=!1}}if(!await C(j,"0.0.0.0",S))tR(S,j,F,R.acmeChallengeWebroot,W);if(await C(F,"0.0.0.0",S)){if(A("proxies",`Port ${F} is already in use, cannot start shared proxy`,S),S)X.warn(`Port ${F} is in use. Shared HTTPS proxy cannot start.`);return}let sR=W&&W.sniEntries().length>0?W.sniEntries():G;if(z=n({routeEntries:B,listenPort:F,sslConfig:sR,originGuard:E,verbose:S}),!z){X.error(`Shared HTTPS proxy failed to bind :${F}; not exiting`);return}}else if(c){A("proxies",`Creating shared HTTP server for ${N.length} domains on port ${j}`,S);let B=await bR(N,x,S);if(await C(j,"0.0.0.0",S)){if(A("proxies",`Port ${j} is already in use, cannot start shared proxy`,S),S)X.warn(`Port ${j} is in use. Shared HTTP proxy cannot start.`);return}if(!n({routeEntries:B,listenPort:j,sslConfig:null,originGuard:E,verbose:S})){X.error(`Shared HTTP proxy failed to bind :${j}; not exiting`);return}}else for(let B of N)try{let z=B.to||"rpx.localhost";A("proxy",`Starting proxy for ${z} with SSL config: ${!!G}`,B.verbose),await PR({from:B.from||"localhost:5173",to:z,cleanUrls:B.cleanUrls||!1,https:B.https||!1,cleanup:B.cleanup||!1,vitePluginUsage:B.vitePluginUsage||!1,verbose:B.verbose||!1,_cachedSSLConfig:R._cachedSSLConfig,changeOrigin:B.changeOrigin||!1,loadBalancer:B.loadBalancer,auth:B.auth,path:B.path,pathRewrites:B.pathRewrites})}catch(z){A("proxies",`Failed to start proxy for ${B.to}: ${z}`,B.verbose),X.error(`Failed to start proxy for ${B.to}:`,z)}}async function bR(_,R,S){let x=[],Y=new Set;for(let K of _){let N=K.to||"rpx.localhost",Q=K.cleanUrls||!1,G=K.path,J=TR(G),V=SR(K.auth);if(K.redirect){let Z=HR(K.redirect);x.push({host:N,path:G,route:{redirect:Z,basePath:J,auth:V}}),A("proxies",`Route: ${N}${G??""} → redirect ${Z.status} ${Z.to}${V?" (auth)":""}`,S)}else if(K.static)x.push({host:N,path:G,route:{static:WR(K.static,Q),cleanUrls:Q,basePath:J,auth:V}}),A("proxies",`Route: ${N}${G??""} → static ${typeof K.static==="string"?K.static:K.static.dir}${V?" (auth)":""}`,S);else{let Z=U(K.from),$=new URL(Z.startsWith("http")?Z:`http://${Z}`),D=o(K.from??$.host,K.loadBalancer);RR(D),t.add(D),x.push({host:N,path:G,route:{sourceHost:$.host,upstreamPool:D,cleanUrls:Q,changeOrigin:K.changeOrigin||!1,pathRewrites:K.pathRewrites,basePath:J,auth:V}}),A("proxies",`Route: ${N}${G??""} → ${$.host}${V?" (auth)":""}`,S)}if(Y.has(N))continue;if(Y.add(N),R&&!wR(N)&&!N.includes("localhost")&&!N.includes("127.0.0.1"))try{if(!(await L([N],S))[0])await P([N],S)}catch{A("hosts",`Could not add hosts entry for ${N}`,S)}}return x}function n(_){let{routeEntries:R,listenPort:S,sslConfig:x,originGuard:Y,verbose:K}=_,N=kR(R),Q=ER((V,Z)=>fR(N,V,Z),K),G=Y?(V,Z)=>Y(V)??Q(V,Z):Q,J=MR(K);try{let V=Bun.serve({port:S,hostname:"0.0.0.0",reusePort:aR(),...x?{tls:dR(Array.isArray(x)?x.map((Z)=>({serverName:Z.serverName,key:Z.key,cert:Z.cert})):{key:x.key,cert:x.cert,ca:x.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch(Z,$){return G(Z,$)},websocket:J,error(Z){return A("server",`Shared proxy server error: ${Z}`,K),new Response(`Server Error: ${Z.message}`,{status:500})}});return h.add(V),A("proxies",`Shared ${x?"HTTPS":"HTTP"} proxy listening on port ${S} for ${N.size} domains`,K),V}catch(V){return A("proxies",`Failed to start shared proxy: ${V}`,K),console.error("Failed to start shared proxy:",V),null}}function $_(_){if(_?.vitePluginUsage||!_?.verbose)return;if(console.log(""),console.log(` ${M.green(M.bold("rpx"))} ${M.green(`v${x_}`)}`),console.log(` ${M.green("➜")} ${M.dim(_?.from??"")} ${M.dim("➜")} ${M.cyan(_?.ssl?`https://${_?.to}`:`http://${_?.to}`)}`),_?.listenPort!==(_?.ssl?443:80))console.log(` ${M.green("➜")} Listening on port ${_?.listenPort}`);if(_?.cleanUrls)console.log(` ${M.green("➜")} Clean URLs enabled`)}var Hx=OR;export{$R as writeEntry,QS as watchRegistry,Z_ as verifyHttpsChain,T_ as trustRootCaForBrowsers,lS as tearDownDevelopmentDns,bS as syncDevelopmentDnsFromRegistry,g_ as stripBasePath,_R as stopHealthChecks,LS as stopDnsServer,oS as stopDaemon,PR as startServer,X_ as startProxy,OR as startProxies,RR as startHealthChecks,PS as startDnsServer,_S as siteIdForHost,aR as shouldReusePort,uS as setupResolver,mS as setupDevelopmentDns,r_ as serverNameFromCertFilename,p_ as serveStaticFile,c_ as selectUpstream,q as safeStringify,a_ as safeRelativePath,Px as safeDeleteFile,l as runViaDaemon,rS as runDaemon,cS as resolverFilePath,qS as resolverBasenamesForDomains,fS as resolverBasenameForDomain,WR as resolveStaticRoute,d_ as resolveStaticFile,HR as resolveRedirect,Ux as resolvePathRewrite,SR as resolveAuth,zS as renderStartingPage,DS as renderFailedPage,jS as removeStaleRpxHosts,aS as removeResolver,vS as removeLegacyTldResolvers,UR as removeHosts,GR as removeEntry,sS as releaseDaemonLock,jx as redactSensitive,dS as reconcileStaleDevelopmentDns,RA as reconcileDevelopmentDnsOnIdle,AS as readSiteManifest,$S as readEntry,iS as readDaemonPid,J_ as readCertSha256Fingerprint,Q_ as readCertCommonName,GS as readAll,jR as readAcmeChallenge,M_ as pruneStaleRootCas,SS as projectNameFromHost,U as primaryUpstreamUrl,XS as portManager,t_ as pathPrefixMatches,z_ as parseSha256HashesFromSecurityListing,v_ as parseHtpasswd,IS as parseHostsLine,G_ as normalizeSha256Fingerprint,TR as normalizePathPrefix,kS as normalizeDevDomain,QR as matchesWildcard,e_ as matchesAllowedSuffix,fR as matchHostRoute,s_ as matchHostList,n_ as matchHost,h_ as markSuccess,u_ as markFailure,U_ as loadSSLConfig,BS as listDiscoverableSites,E_ as listCertSha256HashesByCommonName,wR as isWildcardPattern,Tx as isValidRootCA,YR as isValidId,Cx as isSingleProxyOptions,yx as isSingleProxyConfig,j_ as isRootCaTrustedForSsl,w_ as isRootCaFingerprintInKeychains,Wx as isProcessElevated,C as isPortInUse,YS as isPidAlive,qx as isMultiProxyOptions,fx as isMultiProxyConfig,o_ as isLikelyHostname,OS as isDnsServerRunning,nS as isDaemonRunning,O_ as isCertTrusted,e as httpsConfig,HS as hostsLineMapsHost,lR as getSudoPassword,y_ as getSharedDaemonCertPaths,C_ as getRootCAPaths,XR as getRegistryDir,kx as getPrimaryDomain,W_ as getMacosTrustKeychains,H_ as getMacosLoginKeychainPath,pS as getDaemonRpxDir,gS as getDaemonPidPath,r as generateCertificate,JS as gcStaleEntries,P_ as forceTrustCertificate,MS as findStaleRpxHosts,KS as findAvailablePort,WS as filterRpxHostsEntries,wx as extractHostname,RS as expandHome,Mx as execSudoSync,ZS as escapeHtml,JR as ensureDaemonRunning,m_ as enforceBasicAuth,ES as dropStaleRpxHostsLines,f_ as devSslToSniEntries,CS as devDomainsFromHosts,xS as detectProjectPreset,mR as deriveIdFromTarget,eS as defaultDaemonSpawnCommand,s as defaultConfig,Hx as default,A as debugLog,o as createUpstreamPool,NS as createSiteResolver,MR as createProxyWebSocketHandler,ER as createProxyFetchHandler,VR as createOriginGuard,l_ as contentTypeFor,hS as contentLooksLikeRpxResolver,s as config,M as colors,L_ as clearSslConfigCache,IR as cleanupCertificates,v as cleanup,L as checkHosts,y as checkExistingCertificates,V_ as certIncludesSanHostnames,qR as buildSniTlsConfig,q_ as buildRegistryTlsProxyOptions,b_ as buildRedirectLocation,kR as buildHostRoutes,Ex as authorizeSystemAccess,P as addHosts,tS as acquireDaemonLock,VS as SiteSupervisor,k_ as SHARED_DEV_HOST_CERT_PATH,I_ as RPX_ROOT_CA_COMMON_NAME,US as RPX_RESOLVER_MARKER,FS as RPX_HOSTS_MARKER,CR as OnDemandCertManager,F_ as MACOS_SYSTEM_KEYCHAIN,D_ as MACOS_CA_TRUST_FLAGS,TS as LEGACY_TLD_RESOLVER_LABELS,yR as DefaultPortManager,wS as DNS_STATE_VERSION,yS as DNS_PORT,i_ as ACME_CHALLENGE_PREFIX};
1
+ import{$ as Fx,$a as c6,A as OR,Aa as Bx,B as q,Ba as G6,C as e,Ca as Hx,D as Qx,Da as Kx,E as hR,Ea as X6,F as U,Fa as Y6,G as o,Ga as $6,H as mR,Ha as J6,I as vR,Ia as V6,J as lR,Ja as D6,K as xx,Ka as Q6,L as Rx,La as Z6,M as bR,Ma as E6,N as Sx,Na as k6,O as aR,Oa as I6,P as Zx,Pa as f6,Q as iR,Qa as F6,R as Ex,Ra as c,S as dR,Sa as Ux,T as pR,Ta as u,U as nR,Ua as M6,V as gR,Va as W6,W as tR,Wa as T6,X as kx,Xa as y6,Y as Ix,Ya as C6,Z as sR,Za as q6,_ as fx,_a as U6,a as j,aa as Xx,ab as u6,b as s,ba as rR,bb as P6,c as YR,ca as Mx,cb as L6,d as $R,da as eR,db as O6,e as JR,ea as Wx,eb as h6,f as VR,fa as oR,g as DR,ga as Tx,gb as m6,h as QR,ha as px,hb as v6,i as ZR,ia as x6,ib as l6,j as ER,ja as yx,jb as b6,k as kR,ka as nx,kb as a6,l as IR,la as R6,lb as i6,m as fR,ma as S6,mb as d6,n as FR,na as Cx,nb as p6,o as MR,oa as _6,ob as n6,p as WR,pa as w6,pb as g6,q as TR,qa as z6,qb as t6,r as yR,ra as A6,rb as s6,s as CR,sa as N6,sb as r6,t as qR,ta as j6,tb as e6,u as UR,ua as B6,ub as o6,v as cR,va as C,vb as x4,w as uR,wa as H6,wb as R4,x as PR,xa as qx,xb as Gx,y as LR,ya as K6,yb as S4,z as r,za as jx,zb as _4}from"./chunk-abrzcb7x.js";import{Ab as Dx,Bb as ix,Cb as TS,Db as yS,Eb as CS,Fb as _,Gb as dx,Hb as qS,Ib as y,Jb as US,Kb as cS,Lb as uS,Mb as PS,Nb as LS,Ob as OS,Pb as hS,Qb as mS,Rb as vS}from"./chunk-w4t1nar9.js";import{execSync as NR}from"node:child_process";import*as _x from"node:http";import*as gx from"node:net";import*as tx from"node:os";import*as sx from"node:path";import*as V from"node:process";var l=(R,x)=>(S)=>`\x1B[${R}m${S}\x1B[${x}m`,I={bold:l(1,22),dim:l(2,22),green:l(32,39),cyan:l(36,39)};import*as hx from"node:fs";import*as mx from"node:path";import*as M from"node:process";function vx(R,x){let w=(x&&x!=="/"?`${R}${x}`:R).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return w.length>0?w:"rpx"}async function b(R){if(R.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let x=R.verbose??!1,S=R.registryDir,w=new Set,B=R.proxies.map((H)=>{let D=H.id??vx(H.to,H.path);if(!Bx(D))throw Error(`invalid registry id "${D}" derived from to="${H.to}"`);if(w.has(D))throw Error(`duplicate registry id "${D}" — set an explicit \`id\` on one of the proxies`);return w.add(D),{...H,id:D}}),N=new Date().toISOString();for(let H of B)await Hx({id:H.id,from:H.from,to:H.to,path:H.path,pid:R.persistent?void 0:M.pid,cwd:M.cwd(),createdAt:N,cleanUrls:H.cleanUrls,changeOrigin:H.changeOrigin,pathRewrites:H.pathRewrites,static:H.static,loadBalancer:H.loadBalancer},S,x);let z=await Gx({rpxDir:R.rpxDir,verbose:x,spawnCommand:R.spawnCommand,startupTimeoutMs:R.startupTimeoutMs,spawnEnv:R.spawnEnv});for(let H of B){let D=H.static?`static ${typeof H.static==="string"?H.static:H.static.dir}`:H.from;j.success(`https://${H.to} → ${D}`)}if(j.info(`(via rpx daemon pid=${z.pid}; \`rpx daemon:status\` to inspect)`),R.detached)return;let X=!1,K=S??jx(),G=B.map((H)=>H.id),Y=async()=>{if(X)return;X=!0;for(let H of G)await Kx(H,S,x).catch((D)=>{_("runner",`removeEntry(${H}) failed: ${D}`,x)})},$=(H)=>{_("runner",`received ${H}, unregistering ${G.length} entries`,x),Y().finally(()=>M.exit(0))};M.once("SIGINT",$),M.once("SIGTERM",$),M.once("exit",()=>{if(X)return;for(let H of G)try{hx.unlinkSync(mx.join(K,`${H}.json`))}catch{}}),await new Promise(()=>{})}import{spawn as RR}from"node:child_process";import*as a from"node:process";class i{processes=new Map;isShuttingDown=!1;async startProcess(R,x,S){if(this.processes.has(R)){_("start",`Process ${R} is already running`,S);return}let[w,...B]=x.command.split(" "),N=x.cwd||a.cwd();_("start",`Starting process ${R}:`,S),_("start",` Command: ${w} ${B.join(" ")}`,S),_("start",` Working directory: ${N}`,S),_("start",` Environment variables: ${y(x.env)}`,S);let z=RR(w,B,{cwd:N,env:{...a.env,...x.env},shell:!0,stdio:"inherit"});return this.processes.set(R,{command:x.command,cwd:N,process:z,env:x.env}),new Promise((X,K)=>{if(z.on("error",(G)=>{if(!this.isShuttingDown)_("start",`Process ${R} failed to start: ${G}`,S),this.processes.delete(R),K(G)}),z.on("exit",(G)=>{if(!this.isShuttingDown&&G!==null&&G!==0)_("start",`Process ${R} exited with code ${G}; leaving the proxy running`,S),this.processes.delete(R),K(Error(`Process ${R} exited with code ${G}`))}),S)z.stdout?.on("data",(G)=>{_("process",`[${R}] ${G.toString().trim()}`,!0)}),z.stderr?.on("data",(G)=>{_("process",`[${R}] ERR: ${G.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&z.killed)this.processes.delete(R),K(Error(`Process ${R} was killed during startup`));else _("start",`Process ${R} started successfully`,S),X()},1000)})}async stopProcess(R,x){let S=this.processes.get(R);if(!S?.process){_("start",`No process found for ${R}`,x);return}return _("start",`Stopping process ${R}`,x),new Promise((w)=>{if(!S.process){w();return}S.process.once("exit",()=>{this.processes.delete(R),_("start",`Process ${R} stopped`,x),w()});try{S.process.kill("SIGTERM"),setTimeout(()=>{if(S.process){_("start",`Force killing process ${R}`,x);try{S.process.kill("SIGKILL")}catch(B){}}},3000)}catch(B){_("start",`Error stopping process ${R}: ${B}`,x),this.processes.delete(R),w()}})}async stopAll(R){if(this.isShuttingDown){_("start","Already shutting down, skipping duplicate stopAll call",R);return}this.isShuttingDown=!0,_("start","Stopping all processes",R);let x=Array.from(this.processes.keys()).map((S)=>this.stopProcess(S,R).catch((w)=>{j.error(`Failed to stop process ${S}:`,w)}));await Promise.allSettled(x),this.processes.clear(),this.isShuttingDown=!1}isRunning(R){let x=this.processes.get(R);return!!x?.process&&!x.process.killed}}var $4=new i;import{timingSafeEqual as SR}from"node:crypto";function _R(R,x){if(R==null)return!1;let S=Buffer.from(R),w=Buffer.from(x);if(S.length!==w.length)return!1;return SR(S,w)}function d(R){return R.toLowerCase().replace(/\.$/,"")}var wR=["/.well-known/acme-challenge/"];function zR(R){let x=R.headers.get("host");if(x)return d(x.split(":")[0]);try{return d(new URL(R.url).hostname)}catch{return""}}function Yx(R){let x=R.header.toLowerCase(),S=new Set,w=[];for(let K of R.hosts){let G=d(K);if(G.startsWith("*."))w.push(G);else S.add(G)}let B=R.exemptPaths??wR,N=R.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
2
+ `,z=(K)=>{let G=d(K);return S.has(G)||w.some((Y)=>Xx(G,Y))},X=(K)=>{let G=zR(K);if(!z(G))return;let Y="/";try{Y=new URL(K.url).pathname}catch{}if(B.some(($)=>Y.startsWith($)))return;if(_R(K.headers.get(x),R.value))return;return new Response(N,{status:403,headers:{"content-type":"text/plain"}})};return X.protects=z,X}var lx={name:"@stacksjs/rpx",type:"module",version:"0.11.37",description:"A modern and smart reverse proxy.",author:"Chris Breuer <chris@stacksjs.org>",license:"MIT",homepage:"https://github.com/stacksjs/rpx",repository:{type:"git",url:"git+https://github.com/stacksjs/rpx.git"},bugs:{url:"https://github.com/stacksjs/rpx/issues"},keywords:["reverse proxy","ssl","development","environment","proxy","bun","stacks","typescript","javascript"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js"}},module:"./dist/index.js",types:"./dist/index.d.ts",bin:{rpx:"./dist/bin/cli.js","reverse-proxy":"./dist/bin/cli.js"},files:["README.md","dist"],scripts:{build:"bun build.ts && bun build ./bin/cli.ts --compile --minify --outfile bin/rpx",compile:"bun build ./bin/cli.ts --compile --minify --outfile bin/rpx","compile:all":"bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:windows-x64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64","compile:linux-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-x64 --outfile bin/rpx-linux-x64","compile:linux-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-arm64 --outfile bin/rpx-linux-arm64","compile:windows-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-windows-x64 --outfile bin/rpx-windows-x64.exe","compile:darwin-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-x64 --outfile bin/rpx-darwin-x64","compile:darwin-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-arm64 --outfile bin/rpx-darwin-arm64",bench:"bun run bench/run.ts","bench:html":"bun run bench/run.ts --html","bench:latency":"bun run bench/run.ts --latency","bench:throughput":"bun run bench/run.ts --throughput",lint:"bunx --bun pickier .","lint:fix":"bunx --bun pickier . --fix",fresh:"bunx rimraf node_modules/ bun.lock && bun i",changelog:"changelogen --output CHANGELOG.md",prepublishOnly:"bun build.ts","release:binaries":"bun run compile:all && bun run zip",test:"bun test",typecheck:"bunx tsc --noEmit",zip:"bun run zip:all","zip:all":"bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:windows-x64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64","zip:linux-x64":"zip -j bin/rpx-linux-x64.zip bin/rpx-linux-x64","zip:linux-arm64":"zip -j bin/rpx-linux-arm64.zip bin/rpx-linux-arm64","zip:windows-x64":"zip -j bin/rpx-windows-x64.zip bin/rpx-windows-x64.exe","zip:darwin-x64":"zip -j bin/rpx-darwin-x64.zip bin/rpx-darwin-x64","zip:darwin-arm64":"zip -j bin/rpx-darwin-arm64.zip bin/rpx-darwin-arm64"},dependencies:{"@stacksjs/clapp":"^0.2.10","@stacksjs/tlsx":"^0.13.13"},devDependencies:{bunfig:"^0.15.6",mitata:"^1.0.34",typescript:"^7.0.2"},"simple-git-hooks":{"pre-commit":"bunx lint-staged"},"lint-staged":{"*.{js,ts}":"bunx --bun pickier . --fix"}};var bx=lx.version;var n=new i,jR=new qx("0.0.0.0"),O=new Set,t=new Set,$x=!1,p=null,Jx=null;async function m(R){if($x)return _("cleanup","Cleanup already in progress, skipping",R?.verbose),Jx||Promise.resolve();$x=!0,_("cleanup","Starting cleanup process",R?.verbose),Jx=new Promise((x)=>{p=x});try{await n.stopAll(R?.verbose),j.info("Shutting down proxy servers...");let x=[],S=Array.from(O).map((w)=>new Promise((B)=>{let N=w;try{if(typeof N.stop==="function")N.stop(!0),_("cleanup","Bun server stopped",R?.verbose),B();else if(typeof N.close==="function")N.close(()=>{_("cleanup","Server closed successfully",R?.verbose),B()});else B()}catch(z){_("cleanup",`Error stopping server: ${z}`,R?.verbose),B()}}));x.push(...S),O.clear();for(let w of t)Rx(w);if(t.clear(),R?.hosts&&R.domains?.length){_("cleanup","Cleaning up hosts file entries",R?.verbose),_("cleanup",`Original domains for cleanup: ${JSON.stringify(R.domains)}`,R?.verbose);let w=R.domains.filter((B)=>{if(B==="test.local")return!0;return B!=="localhost"&&!B.startsWith("localhost.")&&B!=="127.0.0.1"});if(_("cleanup",`Filtered domains for cleanup: ${JSON.stringify(w)}`,R?.verbose),w.length>0)j.info("Cleaning up hosts file entries..."),x.push(Ux(w,R?.verbose).then(()=>{_("cleanup",`Removed hosts entries for ${w.join(", ")}`,R?.verbose)}).catch((B)=>{_("cleanup",`Failed to remove hosts entries: ${B}`,R?.verbose),j.warn(`Failed to clean up hosts file entries for ${w.join(", ")}:`,B)}))}if(R?.certs&&R.domains?.length){_("cleanup","Cleaning up SSL certificates",R?.verbose),j.info("Cleaning up SSL certificates...");let w=R.domains.map(async(B)=>{try{await Qx(B,R?.verbose),_("cleanup",`Removed certificates for ${B}`,R?.verbose)}catch(N){_("cleanup",`Failed to remove certificates for ${B}: ${N}`,R?.verbose),j.warn(`Failed to clean up certificates for ${B}:`,N)}});x.push(...w)}await Promise.allSettled(x),_("cleanup","All cleanup tasks completed successfully",R?.verbose),j.success("All cleanup tasks completed successfully")}catch(x){_("cleanup",`Error during cleanup: ${x}`,R?.verbose),j.error("Error during cleanup:",x)}finally{if(p)p();p=null,$x=!1;let x=R&&"vitePluginUsage"in R&&R.vitePluginUsage===!0;if(V.env.NODE_ENV!=="test"&&V.env.BUN_ENV!=="test"&&!x)V.exit(0)}return Jx}var Vx=!1;function rx(R){if(Vx){_("signal",`Received second ${R} signal, forcing exit`,!0),V.exit(1);return}Vx=!0,_("signal",`Received ${R} signal, initiating cleanup`,!0),m().catch((x)=>{_("signal",`Cleanup failed after ${R}: ${x}`,!0),V.exit(1)}).finally(()=>{Vx=!1})}V.once("SIGINT",()=>rx("SIGINT"));V.once("SIGTERM",()=>rx("SIGTERM"));V.on("uncaughtException",(R)=>{j.error("Uncaught exception (continuing):",R)});V.on("unhandledRejection",(R)=>{j.error("Unhandled rejection (continuing):",R)});async function h(R,x,S,w=5){_("connection",`Testing connection to ${R}:${x} (retries left: ${w})`,S);let B=15000,N=Date.now();if(V.env.RPX_BYPASS_CONNECTION_TEST==="true"){_("connection",`Bypassing connection test for ${R}:${x} due to RPX_BYPASS_CONNECTION_TEST flag`,S);return}let z=()=>new Promise((X,K)=>{let G=gx.connect({host:R,port:x,timeout:3000});G.once("connect",()=>{_("connection",`Successfully connected to ${R}:${x}`,S),G.end(),X()}),G.once("timeout",()=>{_("connection",`Connection to ${R}:${x} timed out`,S),G.destroy(),K(Error("Connection timed out"))}),G.once("error",(Y)=>{_("connection",`Failed to connect to ${R}:${x}: ${Y}`,S),G.destroy(),K(Y)})});try{await z()}catch(X){let K=X;if(Date.now()-N>B){_("connection",`Connection test timed out after ${B}ms, but continuing anyway`,S),j.warn(`Connection test to ${R}:${x} timed out, but RPX will try to proceed anyway.`);return}if(K.code==="ECONNREFUSED"&&w>0)return _("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${w} retries left)`,S),await new Promise((Y)=>setTimeout(Y,2000)),h(R,x,S,w-1);if(w>0)try{_("connection",`Trying HTTP request to ${R}:${x}`,S),await new Promise((Y,$)=>{let H=_x.request({hostname:R,port:x,path:"/",method:"HEAD",timeout:5000},(D)=>{_("connection",`Received HTTP response with status: ${D.statusCode}`,S),Y()});H.on("error",(D)=>$(D)),H.on("timeout",()=>{H.destroy(),$(Error("HTTP request timed out"))}),H.end()}),_("connection",`HTTP request to ${R}:${x} succeeded`,S);return}catch(Y){return _("connection",`HTTP request to ${R}:${x} failed: ${Y}`,S),_("connection",`Retrying socket connection in 2 seconds... (${w} retries left)`,S),await new Promise(($)=>setTimeout($,2000)),h(R,x,S,w-1)}let G=`Failed to connect to ${R}:${x} after ${5-w} attempts: ${K.message}`;_("connection",`${G}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,S),j.warn(G),j.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 cx(R){_("server",`Starting server with options: ${y(R)}`,R.verbose);let x=U(R.from),S=new URL(x.startsWith("http")?x:`http://${x}`),w=new URL((R.to?.startsWith("http")?R.to:`http://${R.to}`)||"rpx.localhost"),B=Number.parseInt(S.port)||(S.protocol.includes("https:")?443:80),N=[w.hostname];if(ux(R)&&!w.hostname.includes("localhost")&&!w.hostname.includes("127.0.0.1")){_("hosts",`Checking if hosts file entry exists for: ${w.hostname}`,R?.verbose);try{if(!(await u(N,R.verbose))[0]){j.info(`Adding ${w.hostname} to hosts file...`),j.info("This may require sudo/administrator privileges");try{await c(N,R.verbose)}catch(K){if(j.error("Failed to add hosts entry:",K.message),j.warn("You can manually add this entry to your hosts file:"),j.warn(`127.0.0.1 ${w.hostname}`),j.warn(`::1 ${w.hostname}`),V.platform==="win32")j.warn("On Windows:"),j.warn("1. Run notepad as administrator"),j.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else j.warn("On Unix systems:"),j.warn("sudo nano /etc/hosts")}}else _("hosts",`Host entry already exists for ${w.hostname}`,R.verbose)}catch(X){j.error("Failed to check hosts file:",X.message)}}try{await h(S.hostname,B,R.verbose)}catch(X){_("server",`Connection test failed: ${X}`,R.verbose),j.error(X.message),j.warn("Continuing with proxy setup despite connection test failure..."),j.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let z=R._cachedSSLConfig||null;if(R.https)try{if(R.https===!0)R.https=e({...R,to:w.hostname});if(z=await q({...R,to:w.hostname,https:R.https}),!z){if(_("ssl",`Generating new certificates for ${w.hostname}`,R.verbose),await r({...R,from:S.toString(),to:w.hostname,https:R.https}),z=await q({...R,to:w.hostname,https:R.https}),!z)throw Error(`Failed to load SSL configuration after generating certificates for ${w.hostname}`)}}catch(X){throw _("server",`SSL setup failed: ${X}`,R.verbose),X}_("server",`Setting up reverse proxy with SSL config for ${w.hostname}`,R.verbose),await HR({...R,from:x,originalFrom:R.from||x,to:w.hostname,fromPort:B,sourceUrl:{hostname:S.hostname,host:S.host},ssl:z})}async function BR(R,x,S,w,B,N,z,X,K,G,Y,$){_("proxy",`Creating proxy server ${R} -> ${x} with cleanUrls: ${X}`,z);let H=o(Y??w.host,$);xx(H);let D=[{host:x,route:{sourceHost:w.host,upstreamPool:H,cleanUrls:X||!1,changeOrigin:K||!1,basePath:"/",auth:G}}];if(!g({routeEntries:D,listenPort:S,sslConfig:B,originGuard:null,verbose:z??!1}))throw Rx(H),Error(`Failed to start proxy server for ${x} on port ${S}`);t.add(H),XR({from:R,to:x,vitePluginUsage:N,listenPort:S,ssl:!!B,cleanUrls:X,verbose:z})}async function HR(R){_("setup",`Setting up reverse proxy: ${y(R)}`,R.verbose);let{from:x,originalFrom:S,to:w,sourceUrl:B,ssl:N,verbose:z,cleanup:X,vitePluginUsage:K,changeOrigin:G,cleanUrls:Y}=R,$=80,H=443,D="0.0.0.0",W=R.portManager||jR,P=ux(R);try{if(P&&w&&!w.includes("localhost")&&!w.includes("127.0.0.1")){if(!(await u([w],z))[0]){j.warn(`The hostname ${w} isn't in your hosts file. Adding it now...`);try{await c([w],z),j.success(`Added ${w} to your hosts file.`)}catch(L){j.error(`Failed to add ${w} to your hosts file: ${L}`),j.info(`You may need to manually add '127.0.0.1 ${w}' to your /etc/hosts file.`)}}}else if(P&&V.platform!=="darwin"&&w&&w.includes("localhost")&&!w.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await u([w],z))[0]){_("hosts",`${w} not found in hosts file, adding...`,z);try{await c([w],z)}catch(L){_("hosts",`Failed to add ${w} to hosts file: ${L}`,z)}}}if(N&&!W.usedPorts.has($)){if(!await C($,D,z))_("setup","Starting HTTP redirect server",z),ex(z),W.usedPorts.add($);else if(_("setup","Port 80 is in use, skipping HTTP redirect",z),z)j.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let Q=N?H:$,f=await C(Q,D,z),k;if(f){if(_("setup",`Port ${Q} is already in use`,z),z)j.warn(`Port ${Q} is already in use. This may be another instance of rpx or another service.`);if(Q===443){if(k=await W.getNextAvailablePort(3443,!0),_("setup",`Using port ${k} instead of ${Q}`,z),z)j.info(`Using port ${k} instead. Access your site at https://${w}:${k}`)}else if(k=await W.getNextAvailablePort(Q+1000,!0),_("setup",`Using port ${k} instead of ${Q}`,z),z)j.info(`Using port ${k} instead. Access your site at http://${w}:${k}`)}else k=Q,W.usedPorts.add(k),_("setup",`Using standard ${Q===443?"HTTPS":"HTTP"} port ${Q} for ${w}`,z);await BR(x,w,k,B,N,K,z,Y,G,Sx(R.auth),S,R.loadBalancer)}catch(Q){_("setup",`Setup failed: ${Q}`,z),j.error(`Failed to setup reverse proxy: ${Q.message}`),m({domains:[w],hosts:typeof X==="boolean"?X:X?.hosts,certs:typeof X==="boolean"?X:X?.certs,verbose:z,vitePluginUsage:K})}}function ex(R,x=80,S=443,w,B){_("redirect",`Starting HTTP redirect server on port ${x}`,R);let N=_x.createServer((z,X)=>{let K=z.url?z.url.split("?",1)[0]:"";if(K.startsWith("/.well-known/acme-challenge/")){if(B){let H=B.challengeStore.handlePath(K);if(H!==void 0){_("redirect",`Serving on-demand ACME challenge ${K}`,R),X.writeHead(200,{"content-type":"text/plain"}),X.end(H);return}}if(w){let H=fx(w,K);if(H!=null){_("redirect",`Serving ACME challenge ${K}`,R),X.writeHead(200,{"content-type":"text/plain"}),X.end(H);return}}if(B){X.writeHead(404,{"content-type":"text/plain"}),X.end("challenge not found");return}}let G=z.headers.host||"",Y=G.includes(":")?G.slice(0,G.indexOf(":")):G;if(B&&Y&&!B.hasCert(Y))B.ensureCert(Y).catch(()=>{});let $=S===443?Y:`${Y}:${S}`;_("redirect",`Redirecting request from ${G}${z.url} to https://${$}`,R),X.writeHead(301,{Location:`https://${$}${z.url}`}),X.end()}).listen(x);O.add(N),_("redirect","HTTP redirect server started",R)}function KR(R){let x={...s,...R};if(_("proxy",`Starting proxy with options: ${y(x)}`,x?.verbose),x.viaDaemon){if(!x.from||!x.to){j.error("viaDaemon mode requires both `from` and `to`");return}b({proxies:[{id:x.id,from:x.from,to:x.to,path:x.path,cleanUrls:x.cleanUrls,changeOrigin:x.changeOrigin,pathRewrites:x.pathRewrites}],verbose:x.verbose}).catch((K)=>{j.error(`Failed to register with rpx daemon: ${K.message}`),V.exit(1)});return}let S=x.to||"",w=S.split(".").pop()?.toLowerCase()||"",B=V.platform==="darwin"&&S&&!S.includes("localhost")&&!S.includes("127.0.0.1"),N=["dev","app","page","new","day","foo"],z=["test","localhost","local","example","invalid"];if(B&&N.includes(w)&&x?.verbose)j.warn(`The .${w} TLD may not work reliably for local development`),j.info(` Google owns .${w} with HSTS preloading, which can bypass local DNS`),j.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(B)import("./chunk-mvrj419f.js").then(({setupDevelopmentDns:K})=>{K({domains:[S],verbose:x.verbose}).then((G)=>{if(G)Promise.resolve().then(()=>{if(x.verbose)if(z.includes(w))j.success(`DNS server started for .${w} domains`);else j.success(`DNS server started for .${w} domains (hosts file entry also added)`)});else _("dns",`Could not start DNS server - ${S} may not resolve in browser`,x.verbose)})}).catch((K)=>{_("dns",`Failed to start DNS server: ${K}`,x.verbose)});let X={from:x.from,to:x.to,cleanUrls:x.cleanUrls,https:e(x),cleanup:x.cleanup,vitePluginUsage:x.vitePluginUsage,changeOrigin:x.changeOrigin,verbose:x.verbose,regenerateUntrustedCerts:x.regenerateUntrustedCerts};_("proxy",`Server options: ${y(X)}`,x.verbose),cx(X).catch((K)=>{_("proxy",`Failed to start proxy: ${K}`,x.verbose),j.error(`Failed to start proxy: ${K.message}`),m({domains:[x.to],hosts:typeof x.cleanup==="boolean"?x.cleanup:x.cleanup?.hosts,certs:typeof x.cleanup==="boolean"?x.cleanup:x.cleanup?.certs,verbose:x.verbose})})}function GR(R){return R?.verbose||!1}function ux(R){if(R?.hostsManagement===!1)return!1;let x=R?.cleanup;if(x===!1)return!1;if(x&&typeof x==="object"&&x.hosts===!1)return!1;return!0}async function Px(R){let x={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(R)x={...x,...R};let S=GR(x),w=ux(x);if(_("config",`Starting with config: ${y(x,2)}`,S),_("config",`Is multi-proxy? ${"proxies"in x}`,S),_("config",`Hosts management enabled? ${w}`,S),x.viaDaemon){let J="proxies"in x&&Array.isArray(x.proxies)?x.proxies.map((Z)=>({id:Z.id,from:Z.from,to:Z.to,path:Z.path,cleanUrls:Z.cleanUrls??x.cleanUrls,changeOrigin:Z.changeOrigin??x.changeOrigin,pathRewrites:Z.pathRewrites})):[{id:x.id,from:x.from,to:x.to??"rpx.localhost",path:x.path,cleanUrls:x.cleanUrls,changeOrigin:x.changeOrigin,pathRewrites:x.pathRewrites}];await b({proxies:J,verbose:S});return}if("proxies"in x&&Array.isArray(x.proxies)){_("servers",`Found ${x.proxies.length} proxies in config`,S);for(let A of x.proxies)if(A.start){let J=`${A.from}-${A.to}`;try{_("watch",`Starting command for ${J} with command: ${A.start.command}`,S),j.info(`Starting command for ${J}...`),await n.startProcess(J,A.start,S);let Z=U(A.from),E=new URL(Z.startsWith("http")?Z:`http://${Z}`),F=E.hostname||"localhost",T=Number(E.port)||80;try{await h(F,T,S),_("watch",`Dev server is ready at ${F}:${T}`,S)}catch(wx){_("watch",`Connection check failed, but continuing with proxy setup: ${wx}`,S),j.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(Z){throw _("watch",`Failed to start command for ${J}: ${Z}`,S),Error(`Failed to start command for ${J}: ${Z}`)}}else _("watch",`No start command for proxy ${A.from} -> ${A.to}`,S)}else if("start"in x&&x.start){_("watch","Found start command in single proxy config",S);let A=`${x.from}-${x.to}`;try{if(x.start)_("watch",`Starting command: ${x.start.command}`,S),await n.startProcess(A,x.start,S);let J=U(x.from),Z=new URL(J.startsWith("http")?J:`http://${J}`),E=Z.hostname||"localhost",F=Number(Z.port)||80;try{await h(E,F,S),_("watch",`Dev server is ready at ${E}:${F}`,S)}catch(T){_("watch",`Connection check failed, but continuing with proxy setup: ${T}`,S),j.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(J){throw _("watch",`Failed to run start command: ${J}`,S),Error(`Failed to run start command: ${J}`)}}else _("watch","No start command found in config",S);let B="proxies"in x&&Array.isArray(x.proxies)?x.proxies[0]?.to:("to"in x)?x.to:"rpx.localhost";if(V.platform!=="win32"&&(x.https||w)){if(!ix())try{_("sudo","Pre-acquiring sudo credentials for privileged operations",S),NR("sudo -v",{stdio:"inherit"})}catch{_("sudo","Could not pre-acquire sudo credentials",S)}}let N=[];if(x.productionCerts){if(N=await yx(x.productionCerts,S),N.length>0)_("ssl",`Using ${N.length} production SNI cert(s): ${N.map((A)=>A.serverName).join(", ")}`,S)}if(x.https){let A=N.length>0?null:await q(x);if(!A&&N.length===0){if(_("ssl",`No valid or trusted certificates found for ${B}, generating new ones`,x.verbose),await r(x),A=await q(x),!A)throw Error(`Failed to load SSL certificates after generation for ${B}`)}else _("ssl",`Using existing and trusted certificates for ${B}`,x.verbose);x._cachedSSLConfig=A}let z="proxies"in x&&Array.isArray(x.proxies)?x.proxies.map((A)=>({...A,https:x.https,cleanup:x.cleanup,cleanUrls:A.cleanUrls??("cleanUrls"in x?x.cleanUrls:!1),vitePluginUsage:x.vitePluginUsage,changeOrigin:A.changeOrigin??x.changeOrigin,verbose:S,_cachedSSLConfig:x._cachedSSLConfig})):[{from:"from"in x?x.from:"localhost:5173",to:"to"in x?x.to:"rpx.localhost",cleanUrls:"cleanUrls"in x?x.cleanUrls:!1,https:x.https,cleanup:x.cleanup,vitePluginUsage:x.vitePluginUsage,start:"start"in x?x.start:void 0,changeOrigin:x.changeOrigin,auth:"auth"in x?x.auth:void 0,verbose:S,_cachedSSLConfig:x._cachedSSLConfig}],X=z.map((A)=>A.to||"rpx.localhost"),K=N.length>0?N:x._cachedSSLConfig??null,G=X.filter((A)=>A&&!A.includes("localhost")&&!A.includes("127.0.0.1")),Y=["dev","app","page","new","day","foo"],$=["test","localhost","local","example","invalid"],H=[...new Set(G.map((A)=>A.split(".").pop()?.toLowerCase()))],D=H.filter((A)=>!!A&&Y.includes(A));if(D.length>0&&S)j.warn(`The following TLDs may not work reliably for local development: ${D.map((A)=>`.${A}`).join(", ")}`),j.info(" These TLDs have HSTS preloading which can bypass local DNS"),j.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(w&&V.platform==="darwin"&&G.length>0){let{setupDevelopmentDns:A}=await import("./chunk-mvrj419f.js");if(await A({domains:G,verbose:S})){if(S)if(H.every((E)=>!!E&&$.includes(E)))j.success(`DNS server started for ${H.map((E)=>`.${E}`).join(", ")} domains`);else j.success(`DNS server started for ${H.map((E)=>`.${E}`).join(", ")} domains (hosts file entries also added)`)}else _("dns","Could not start DNS server - custom domains may not resolve",S)}let W=async()=>{_("cleanup","Starting cleanup handler",x.verbose);try{let{tearDownDevelopmentDns:A}=await import("./chunk-mvrj419f.js");await A({verbose:x.verbose})}catch(A){_("cleanup",`Error stopping DNS server: ${A}`,x.verbose)}try{await n.stopAll(x.verbose)}catch(A){_("cleanup",`Error stopping processes: ${A}`,x.verbose)}await m({domains:X,hosts:typeof x.cleanup==="boolean"?x.cleanup:x.cleanup?.hosts,certs:typeof x.cleanup==="boolean"?x.cleanup:x.cleanup?.certs,verbose:x.verbose||!1})};V.on("SIGINT",W),V.on("SIGTERM",W);let P=x.singlePortMode===!0,Q=x.httpsPort??443,f=x.httpPort??80,k=x.originGuard?Yx(x.originGuard):null,v=!!K&&(z.length>1||P||N.length>0),L=!K&&P&&z.length>0;if(v&&K){_("proxies",`Creating shared HTTPS server for ${z.length} domains on port ${Q}`,S);let A=await ax(z,w,S),J=null,Z=x.onDemandTls,E=Z?.enabled?new Cx({config:Z,certsDir:Z.certsDir??x.productionCerts?.certsDir??sx.join(tx.homedir(),".stacks","rpx","on-demand-certs"),initial:N,verbose:S,onCertAdded:(zx)=>{if(nx()==="restart")_("on-demand","certificate installed; restarting supervised gateway to reload TLS",S),setTimeout(()=>V.kill(V.pid,"SIGTERM"),10).unref();else wx(zx)}}):null,F=null,T=!1;async function wx(zx){if(F=zx,T)return;T=!0;try{while(F){let Lx=F;if(F=null,_("proxies",`rebuilding :${Q} with ${Lx.length} SNI cert(s)`,S),J)O.delete(J),J.stop(!1);let Ax=!1;for(let Nx=0;!Ax&&Nx<60;Nx++){let Ox=g({routeEntries:A,listenPort:Q,sslConfig:Lx,originGuard:k,verbose:S});if(Ox){J=Ox,Ax=!0;break}await new Promise((xR)=>setTimeout(xR,Math.min(25*2**Math.min(Nx,4),500)))}if(!Ax)j.error(`rpx: CRITICAL — could not rebind :${Q} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{T=!1}}if(!await C(f,"0.0.0.0",S))ex(S,f,Q,x.acmeChallengeWebroot,E);if(await C(Q,"0.0.0.0",S)){if(_("proxies",`Port ${Q} is already in use, cannot start shared proxy`,S),S)j.warn(`Port ${Q} is in use. Shared HTTPS proxy cannot start.`);return}let ox=E&&E.sniEntries().length>0?E.sniEntries():K;if(J=g({routeEntries:A,listenPort:Q,sslConfig:ox,originGuard:k,verbose:S}),!J){j.error(`Shared HTTPS proxy failed to bind :${Q}; not exiting`);return}}else if(L){_("proxies",`Creating shared HTTP server for ${z.length} domains on port ${f}`,S);let A=await ax(z,w,S);if(await C(f,"0.0.0.0",S)){if(_("proxies",`Port ${f} is already in use, cannot start shared proxy`,S),S)j.warn(`Port ${f} is in use. Shared HTTP proxy cannot start.`);return}if(!g({routeEntries:A,listenPort:f,sslConfig:null,originGuard:k,verbose:S})){j.error(`Shared HTTP proxy failed to bind :${f}; not exiting`);return}}else for(let A of z)try{let J=A.to||"rpx.localhost";_("proxy",`Starting proxy for ${J} with SSL config: ${!!K}`,A.verbose),await cx({from:A.from||"localhost:5173",to:J,cleanUrls:A.cleanUrls||!1,https:A.https||!1,cleanup:A.cleanup||!1,vitePluginUsage:A.vitePluginUsage||!1,verbose:A.verbose||!1,_cachedSSLConfig:x._cachedSSLConfig,changeOrigin:A.changeOrigin||!1,loadBalancer:A.loadBalancer,auth:A.auth,path:A.path,pathRewrites:A.pathRewrites})}catch(J){_("proxies",`Failed to start proxy for ${A.to}: ${J}`,A.verbose),j.error(`Failed to start proxy for ${A.to}:`,J)}}async function ax(R,x,S){let w=[],B=new Set;for(let N of R){let z=N.to||"rpx.localhost",X=N.cleanUrls||!1,K=N.path,G=Mx(K),Y=Sx(N.auth);if(N.redirect){let $=Zx(N.redirect);w.push({host:z,path:K,route:{redirect:$,basePath:G,auth:Y}}),_("proxies",`Route: ${z}${K??""} → redirect ${$.status} ${$.to}${Y?" (auth)":""}`,S)}else if(N.static)w.push({host:z,path:K,route:{static:Ex(N.static,X),cleanUrls:X,basePath:G,auth:Y}}),_("proxies",`Route: ${z}${K??""} → static ${typeof N.static==="string"?N.static:N.static.dir}${Y?" (auth)":""}`,S);else{let $=U(N.from),H=new URL($.startsWith("http")?$:`http://${$}`),D=o(N.from??H.host,N.loadBalancer);xx(D),t.add(D),w.push({host:z,path:K,route:{sourceHost:H.host,upstreamPool:D,cleanUrls:X,changeOrigin:N.changeOrigin||!1,pathRewrites:N.pathRewrites,basePath:G,auth:Y}}),_("proxies",`Route: ${z}${K??""} → ${H.host}${Y?" (auth)":""}`,S)}if(B.has(z))continue;if(B.add(z),x&&!Fx(z)&&!z.includes("localhost")&&!z.includes("127.0.0.1"))try{if(!(await u([z],S))[0])await c([z],S)}catch{_("hosts",`Could not add hosts entry for ${z}`,S)}}return w}function g(R){let{routeEntries:x,listenPort:S,sslConfig:w,originGuard:B,verbose:N}=R,z=Wx(x),X=kx((Y,$)=>Tx(z,Y,$),N),K=B?(Y,$)=>B(Y)??X(Y,$):X,G=Ix(N);try{let Y=Bun.serve({port:S,hostname:"0.0.0.0",reusePort:dx(),...w?{tls:px(Array.isArray(w)?w.map(($)=>({serverName:$.serverName,key:$.key,cert:$.cert})):{key:w.key,cert:w.cert,ca:w.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch($,H){return K($,H)},websocket:G,error($){return _("server",`Shared proxy server error: ${$}`,N),new Response(`Server Error: ${$.message}`,{status:500})}});return O.add(Y),_("proxies",`Shared ${w?"HTTPS":"HTTP"} proxy listening on port ${S} for ${z.size} domains`,N),Y}catch(Y){return _("proxies",`Failed to start shared proxy: ${Y}`,N),console.error("Failed to start shared proxy:",Y),null}}function XR(R){if(R?.vitePluginUsage||!R?.verbose)return;if(console.log(""),console.log(` ${I.green(I.bold("rpx"))} ${I.green(`v${bx}`)}`),console.log(` ${I.green("➜")} ${I.dim(R?.from??"")} ${I.dim("➜")} ${I.cyan(R?.ssl?`https://${R?.to}`:`http://${R?.to}`)}`),R?.listenPort!==(R?.ssl?443:80))console.log(` ${I.green("➜")} Listening on port ${R?.listenPort}`);if(R?.cleanUrls)console.log(` ${I.green("➜")} Clean URLs enabled`)}var WS=Px;export{Hx as writeEntry,J6 as watchRegistry,DR as verifyHttpsChain,yR as trustRootCaForBrowsers,d6 as tearDownDevelopmentDns,i6 as syncDevelopmentDnsFromRegistry,tR as stripBasePath,Rx as stopHealthChecks,O6 as stopDnsServer,S4 as stopDaemon,cx as startServer,KR as startProxy,Px as startProxies,xx as startHealthChecks,L6 as startDnsServer,w6 as siteIdForHost,dx as shouldReusePort,l6 as setupResolver,a6 as setupDevelopmentDns,x6 as serverNameFromCertFilename,gR as serveStaticFile,mR as selectUpstream,y as safeStringify,pR as safeRelativePath,vS as safeDeleteFile,b as runViaDaemon,x4 as runDaemon,m6 as resolverFilePath,U6 as resolverBasenamesForDomains,q6 as resolverBasenameForDomain,Ex as resolveStaticRoute,nR as resolveStaticFile,Zx as resolveRedirect,mS as resolvePathRewrite,Sx as resolveAuth,Q6 as renderStartingPage,Z6 as renderFailedPage,W6 as removeStaleRpxHosts,p6 as removeResolver,b6 as removeLegacyTldResolvers,Ux as removeHosts,Kx as removeEntry,o6 as releaseDaemonLock,qS as redactSensitive,n6 as reconcileStaleDevelopmentDns,_4 as reconcileDevelopmentDnsOnIdle,A6 as readSiteManifest,X6 as readEntry,s6 as readDaemonPid,$R as readCertSha256Fingerprint,JR as readCertCommonName,Y6 as readAll,fx as readAcmeChallenge,MR as pruneStaleRootCas,z6 as projectNameFromHost,U as primaryUpstreamUrl,K6 as portManager,eR as pathPrefixMatches,QR as parseSha256HashesFromSecurityListing,bR as parseHtpasswd,k6 as parseHostsLine,YR as normalizeSha256Fingerprint,Mx as normalizePathPrefix,C6 as normalizeDevDomain,Xx as matchesWildcard,R6 as matchesAllowedSuffix,Tx as matchHostRoute,oR as matchHostList,rR as matchHost,vR as markSuccess,lR as markFailure,PR as loadSSLConfig,B6 as listDiscoverableSites,FR as listCertSha256HashesByCommonName,Fx as isWildcardPattern,cS as isValidRootCA,Bx as isValidId,OS as isSingleProxyOptions,hS as isSingleProxyConfig,WR as isRootCaTrustedForSsl,TR as isRootCaFingerprintInKeychains,TS as isProcessElevated,C as isPortInUse,G6 as isPidAlive,LS as isMultiProxyOptions,PS as isMultiProxyConfig,S6 as isLikelyHostname,h6 as isDnsServerRunning,r6 as isDaemonRunning,hR as isCertTrusted,e as httpsConfig,I6 as hostsLineMapsHost,ix as getSudoPassword,uR as getSharedDaemonCertPaths,cR as getRootCAPaths,jx as getRegistryDir,uS as getPrimaryDomain,fR as getMacosTrustKeychains,IR as getMacosLoginKeychainPath,g6 as getDaemonRpxDir,t6 as getDaemonPidPath,r as generateCertificate,$6 as gcStaleEntries,LR as forceTrustCertificate,M6 as findStaleRpxHosts,H6 as findAvailablePort,f6 as filterRpxHostsEntries,US as extractHostname,_6 as expandHome,CS as execSudoSync,D6 as escapeHtml,Gx as ensureDaemonRunning,aR as enforceBasicAuth,F6 as dropStaleRpxHostsLines,qR as devSslToSniEntries,c6 as devDomainsFromHosts,N6 as detectProjectPreset,vx as deriveIdFromTarget,R4 as defaultDaemonSpawnCommand,s as defaultConfig,WS as default,_ as debugLog,o as createUpstreamPool,j6 as createSiteResolver,Ix as createProxyWebSocketHandler,kx as createProxyFetchHandler,Yx as createOriginGuard,dR as contentTypeFor,v6 as contentLooksLikeRpxResolver,s as config,I as colors,OR as clearSslConfigCache,Qx as cleanupCertificates,m as cleanup,u as checkHosts,q as checkExistingCertificates,VR as certIncludesSanHostnames,yx as buildSniTlsConfig,UR as buildRegistryTlsProxyOptions,iR as buildRedirectLocation,Wx as buildHostRoutes,yS as authorizeSystemAccess,c as addHosts,e6 as acquireDaemonLock,V6 as SiteSupervisor,CR as SHARED_DEV_HOST_CERT_PATH,kR as RPX_ROOT_CA_COMMON_NAME,P6 as RPX_RESOLVER_MARKER,E6 as RPX_HOSTS_MARKER,Cx as OnDemandCertManager,ER as MACOS_SYSTEM_KEYCHAIN,ZR as MACOS_CA_TRUST_FLAGS,y6 as LEGACY_TLD_RESOLVER_LABELS,qx as DefaultPortManager,T6 as DNS_STATE_VERSION,u6 as DNS_PORT,sR as ACME_CHALLENGE_PREFIX};
@@ -1,6 +1,13 @@
1
1
  import type { Http01Store, ObtainCertificateOptions, ObtainCertificateResult } from '@stacksjs/tlsx';
2
2
  import type { OnDemandTlsConfig } from './types';
3
3
  import type { SniTlsEntry } from './sni';
4
+ /**
5
+ * Bun cannot hot-reload TLS. A local foreground process can recreate its
6
+ * listener, while a supervised production process should restart after the
7
+ * certificate is persisted and let its supervisor bring it back with the new
8
+ * SNI set. This avoids a Bun 1.3.x Linux crash in stop-and-rebind.
9
+ */
10
+ export declare function resolveCertificateReloadStrategy(env?: Record<string, string | undefined>): CertificateReloadStrategy;
4
11
  /**
5
12
  * True if `host` is covered by the `allowedSuffixes` allowlist: it equals a
6
13
  * suffix, or is a subdomain of one (`a.example.com` for suffix `example.com`).
@@ -18,6 +25,7 @@ export declare interface OnDemandCertManagerOptions {
18
25
  verbose?: boolean
19
26
  negativeCacheMs?: number
20
27
  }
28
+ export type CertificateReloadStrategy = 'rebind' | 'restart';
21
29
  /**
22
30
  * The issuance function the manager calls. Defaults to tlsx's
23
31
  * {@link obtainCertificate}; tests inject a stub so the suite never touches
@@ -0,0 +1 @@
1
+ export declare const version: string;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/rpx",
3
3
  "type": "module",
4
- "version": "0.11.35",
4
+ "version": "0.11.37",
5
5
  "description": "A modern and smart reverse proxy.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",