@stacksjs/rpx 0.11.19 → 0.11.20

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/https.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { config } from './config';
2
2
  import { MACOS_CA_TRUST_FLAGS, MACOS_SYSTEM_KEYCHAIN, getMacosLoginKeychainPath, isRootCaFingerprintInKeychains, isRootCaTrustedForSsl, pruneStaleRootCas, trustRootCaForBrowsers } from './macos-trust';
3
+ import { readCertCommonName, readCertSha256Fingerprint } from './cert-inspect';
3
4
  import type { ProxyConfigs, ProxyOption, ProxyOptions, SSLConfig, TlsConfig } from './types';
4
5
  /**
5
6
  * Bun needs one `tls[]` entry per SNI name even when a single PEM covers every SAN.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import{$ as X_,A as UD,Aa as A2,B as b,Ba as T2,C as Y_,Ca as M2,D as w_,Da as z2,E as OD,Ea as F2,F as H_,Fa as I2,G as PD,Ga as E2,H as LD,Ha as j2,I as cD,Ia as w2,J as hD,Ja as H2,K as uD,Ka as V_,L as k_,La as k2,M as C_,Ma as C2,N as x_,O as T_,P as mD,Q as f_,R as vD,S as q_,T as bD,U as y_,V as lD,W as aD,X as dD,Y as gD,Z as pD,_ as G_,a as X,aa as iD,b as R_,ba as J_,c as GD,ca as Q_,d as XD,da as nD,e as JD,ea as tD,f as QD,fa as rD,g as VD,ga as sD,h as WD,ha as oD,i as ZD,ia as eD,j as AD,ja as _2,k as TD,ka as D2,l as MD,la as B2,m as zD,ma as N2,n as FD,na as K2,o as ID,oa as R2,p as ED,pa as S2,q as jD,qa as Y2,r as wD,ra as $2,s as HD,t as kD,ta as G2,u as CD,ua as X2,v as xD,va as J2,w as fD,wa as Q2,x as qD,xa as V2,y as yD,ya as W2,z as S_,za as Z2}from"./chunk-rs8gqpax.js";import{$a as rB,Na as E_,Oa as a,Pa as v_,Qa as lB,Ra as N,Sa as j_,Ta as aB,Ua as y,Va as dB,Wa as gB,Xa as pB,Ya as iB,Za as nB,_a as tB,ab as sB,bb as oB}from"./chunk-w888yhnp.js";import{execSync as BD}from"node:child_process";import*as h from"node:http";import*as g_ from"node:http2";import*as p_ from"node:net";import*as j from"node:process";var s=(D,_)=>(B)=>`\x1B[${D}m${B}\x1B[${_}m`,x={bold:s(1,22),dim:s(2,22),green:s(32,39),cyan:s(36,39)};import*as c_ from"node:fs";import*as h_ from"node:path";import*as q from"node:process";function u_(D,_){let K=(_&&_!=="/"?`${D}${_}`:D).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return K.length>0?K:"rpx"}async function o(D){if(D.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let _=D.verbose??!1,B=D.registryDir,K=new Set,R=D.proxies.map((A)=>{let I=A.id??u_(A.to,A.path);if(!X_(I))throw Error(`invalid registry id "${I}" derived from to="${A.to}"`);if(K.has(I))throw Error(`duplicate registry id "${I}" — set an explicit \`id\` on one of the proxies`);return K.add(I),{...A,id:I}}),G=new Date().toISOString();for(let A of R)await J_({id:A.id,from:A.from,to:A.to,path:A.path,pid:D.persistent?void 0:q.pid,cwd:q.cwd(),createdAt:G,cleanUrls:A.cleanUrls,changeOrigin:A.changeOrigin,pathRewrites:A.pathRewrites,static:A.static},B,_);let $=await V_({rpxDir:D.rpxDir,verbose:_,spawnCommand:D.spawnCommand,startupTimeoutMs:D.startupTimeoutMs,spawnEnv:D.spawnEnv});for(let A of R){let I=A.static?`static ${typeof A.static==="string"?A.static:A.static.dir}`:A.from;X.success(`https://${A.to} → ${I}`)}if(X.info(`(via rpx daemon pid=${$.pid}; \`rpx daemon:status\` to inspect)`),D.detached)return;let Z=!1,S=B??G_(),J=R.map((A)=>A.id),F=async()=>{if(Z)return;Z=!0;for(let A of J)await Q_(A,B,_).catch((I)=>{N("runner",`removeEntry(${A}) failed: ${I}`,_)})},w=(A)=>{N("runner",`received ${A}, unregistering ${J.length} entries`,_),F().finally(()=>q.exit(0))};q.once("SIGINT",w),q.once("SIGTERM",w),q.once("exit",()=>{if(Z)return;for(let A of J)try{c_.unlinkSync(h_.join(S,`${A}.json`))}catch{}}),await new Promise(()=>{})}import{exec as n_}from"node:child_process";import L from"node:fs";import b_ from"node:os";import Z_ from"node:path";import*as d from"node:process";import{promisify as t_}from"node:util";var l=t_(n_);function m_(D){let _=D.trim().toLowerCase();return _==="localhost"||_.endsWith(".localhost")||_.endsWith(".localhost.")}var C=d.platform==="win32"?Z_.join(d.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",W_=!1;async function e(D){if(d.platform==="win32")throw Error("Administrator privileges required on Windows");if(v_()){let{stdout:K}=await l(D);return K}let _=a(),B=D.replace(/'/g,"'\\''");try{if(_){let{stdout:K}=await l(`echo '${_}' | sudo -S sh -c '${B}' 2>/dev/null`);return W_=!0,K}if(W_)try{let{stdout:K}=await l(`sudo -n sh -c '${B}'`);return K}catch(K){N("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:K}=await l(`sudo -n sh -c '${B}'`);return W_=!0,K}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(K){throw Error(`Failed to execute sudo command: ${K.message}`)}}async function m(D,_){let B=D.filter((R)=>!m_(R)),K=D.filter((R)=>m_(R));if(K.length>0)N("hosts",`Skipping /etc/hosts for loopback dev names: ${K.join(", ")}`,_);if(B.length===0)return;N("hosts",`Adding hosts: ${B.join(", ")}`,_),N("hosts",`Using hosts file at: ${C}`,_);try{let R;try{R=await L.promises.readFile(C,"utf-8")}catch{N("hosts","Reading hosts file requires elevated permissions, using sudo",_);try{R=await e(`cat "${C}"`)}catch(S){throw console.log(" Could not read hosts file — skipping hosts setup"),N("hosts",`sudo read also failed: ${S}`,_),Error(`Cannot read hosts file: ${S}`)}}let G=B.filter((S)=>{let J=`127.0.0.1 ${S}`,F=`::1 ${S}`;return!R.includes(J)&&!R.includes(F)});if(G.length===0){N("hosts","All hosts already exist in hosts file",_);return}let $=G.map((S)=>`
1
+ import{$ as BR,A as U_,Aa as WD,B as f,Ba as ZD,C as _R,Ca as AD,D as IR,Da as SD,E as y_,Ea as zD,F as MR,Fa as ID,G as f_,Ga as MD,H as O_,Ha as FD,I as L_,Ia as TD,J as P_,Ja as jD,K as c_,Ka as $R,L as FR,La as HD,M as TR,Ma as kD,N as jR,O as QR,P as h_,Q as HR,R as u_,S as kR,T as m_,U as wR,V as v_,W as ER,X as l_,Y as b_,Z as a_,_ as NR,a as J,aa as d_,b as o,ba as KR,c as $_,ca as YR,d as X_,da as g_,e as G_,ea as p_,f as J_,fa as i_,g as Q_,ga as n_,h as V_,ha as r_,i as W_,ia as t_,j as Z_,ja as s_,k as A_,ka as e_,l as S_,la as o_,m as z_,ma as RD,n as I_,na as _D,o as M_,oa as DD,p as F_,pa as ND,q as T_,qa as BD,r as j_,ra as KD,s as H_,t as k_,ta as YD,u as w_,ua as $D,v as E_,va as XD,w as q_,wa as GD,x as x_,xa as JD,y as C_,ya as QD,z as RR,za as VD}from"./chunk-vxj1ckdm.js";import{$a as n2,Na as SR,Oa as h,Pa as LR,Qa as v2,Ra as N,Sa as mR,Ta as l2,Ua as x,Va as b2,Wa as a2,Xa as d2,Ya as g2,Za as p2,_a as i2,ab as r2,bb as t2}from"./chunk-w888yhnp.js";import{execSync as oR}from"node:child_process";import*as DR from"node:http";import*as vR from"node:net";import*as z from"node:process";var a=(_,R)=>(D)=>`\x1B[${_}m${D}\x1B[${R}m`,k={bold:a(1,22),dim:a(2,22),green:a(32,39),cyan:a(36,39)};import*as UR from"node:fs";import*as yR from"node:path";import*as w from"node:process";function fR(_,R){let K=(R&&R!=="/"?`${_}${R}`:_).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return K.length>0?K:"rpx"}async function d(_){if(_.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let R=_.verbose??!1,D=_.registryDir,K=new Set,Y=_.proxies.map((W)=>{let S=W.id??fR(W.to,W.path);if(!BR(S))throw Error(`invalid registry id "${S}" derived from to="${W.to}"`);if(K.has(S))throw Error(`duplicate registry id "${S}" — set an explicit \`id\` on one of the proxies`);return K.add(S),{...W,id:S}}),B=new Date().toISOString();for(let W of Y)await KR({id:W.id,from:W.from,to:W.to,path:W.path,pid:_.persistent?void 0:w.pid,cwd:w.cwd(),createdAt:B,cleanUrls:W.cleanUrls,changeOrigin:W.changeOrigin,pathRewrites:W.pathRewrites,static:W.static},D,R);let $=await $R({rpxDir:_.rpxDir,verbose:R,spawnCommand:_.spawnCommand,startupTimeoutMs:_.startupTimeoutMs,spawnEnv:_.spawnEnv});for(let W of Y){let S=W.static?`static ${typeof W.static==="string"?W.static:W.static.dir}`:W.from;J.success(`https://${W.to} → ${S}`)}if(J.info(`(via rpx daemon pid=${$.pid}; \`rpx daemon:status\` to inspect)`),_.detached)return;let V=!1,X=D??NR(),Q=Y.map((W)=>W.id),Z=async()=>{if(V)return;V=!0;for(let W of Q)await YR(W,D,R).catch((S)=>{N("runner",`removeEntry(${W}) failed: ${S}`,R)})},A=(W)=>{N("runner",`received ${W}, unregistering ${Q.length} entries`,R),Z().finally(()=>w.exit(0))};w.once("SIGINT",A),w.once("SIGTERM",A),w.once("exit",()=>{if(V)return;for(let W of Q)try{UR.unlinkSync(yR.join(X,`${W}.json`))}catch{}}),await new Promise(()=>{})}import{exec as gR}from"node:child_process";import C from"node:fs";import PR from"node:os";import GR from"node:path";import*as u from"node:process";import{promisify as pR}from"node:util";var c=pR(gR);function OR(_){let R=_.trim().toLowerCase();return R==="localhost"||R.endsWith(".localhost")||R.endsWith(".localhost.")}var H=u.platform==="win32"?GR.join(u.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",XR=!1;async function g(_){if(u.platform==="win32")throw Error("Administrator privileges required on Windows");if(LR()){let{stdout:K}=await c(_);return K}let R=h(),D=_.replace(/'/g,"'\\''");try{if(R){let{stdout:K}=await c(`echo '${R}' | sudo -S sh -c '${D}' 2>/dev/null`);return XR=!0,K}if(XR)try{let{stdout:K}=await c(`sudo -n sh -c '${D}'`);return K}catch(K){N("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:K}=await c(`sudo -n sh -c '${D}'`);return XR=!0,K}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(K){throw Error(`Failed to execute sudo command: ${K.message}`)}}async function U(_,R){let D=_.filter((Y)=>!OR(Y)),K=_.filter((Y)=>OR(Y));if(K.length>0)N("hosts",`Skipping /etc/hosts for loopback dev names: ${K.join(", ")}`,R);if(D.length===0)return;N("hosts",`Adding hosts: ${D.join(", ")}`,R),N("hosts",`Using hosts file at: ${H}`,R);try{let Y;try{Y=await C.promises.readFile(H,"utf-8")}catch{N("hosts","Reading hosts file requires elevated permissions, using sudo",R);try{Y=await g(`cat "${H}"`)}catch(X){throw console.log(" Could not read hosts file — skipping hosts setup"),N("hosts",`sudo read also failed: ${X}`,R),Error(`Cannot read hosts file: ${X}`)}}let B=D.filter((X)=>{let Q=`127.0.0.1 ${X}`,Z=`::1 ${X}`;return!Y.includes(Q)&&!Y.includes(Z)});if(B.length===0){N("hosts","All hosts already exist in hosts file",R);return}let $=B.map((X)=>`
2
2
  # Added by rpx
3
- 127.0.0.1 ${S}
4
- ::1 ${S}`).join(`
5
- `),Z=Z_.join(b_.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await L.promises.writeFile(Z,R+$,"utf8"),await e(`cat "${Z}" | tee "${C}" > /dev/null`),console.log(` Hosts updated: ${G.join(", ")}`)}catch(S){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),G.forEach((J)=>{console.log(` 127.0.0.1 ${J}`),console.log(` ::1 ${J}`)}),console.log(` Or run: sudo nano ${C}`)}finally{try{await L.promises.unlink(Z)}catch{}}}catch(R){N("hosts",`Failed to manage hosts file: ${R.message}`,_)}}async function A_(D,_){N("hosts",`Removing hosts: ${D.join(", ")}`,_);try{let B;try{B=await L.promises.readFile(C,"utf-8")}catch{N("hosts","Reading hosts file requires elevated permissions, using sudo",_);try{B=await e(`cat "${C}"`)}catch(S){throw N("hosts",`sudo read also failed: ${S}`,_),Error(`Cannot read hosts file: ${S}`)}}let K=B.split(`
6
- `),R=!1,G=K.filter((S)=>{if(D.some((F)=>S.includes(` ${F}`)&&(S.includes("127.0.0.1")||S.includes("::1"))))return R=!0,!1;if(S.trim()==="# Added by rpx")return R=!0,!1;return!0});if(!R){N("hosts","No matching hosts found to remove",_);return}while(G[G.length-1]?.trim()==="")G.pop();let $=`${G.join(`
3
+ 127.0.0.1 ${X}
4
+ ::1 ${X}`).join(`
5
+ `),V=GR.join(PR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await C.promises.writeFile(V,Y+$,"utf8"),await g(`cat "${V}" | tee "${H}" > /dev/null`),console.log(` Hosts updated: ${B.join(", ")}`)}catch(X){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),B.forEach((Q)=>{console.log(` 127.0.0.1 ${Q}`),console.log(` ::1 ${Q}`)}),console.log(` Or run: sudo nano ${H}`)}finally{try{await C.promises.unlink(V)}catch{}}}catch(Y){N("hosts",`Failed to manage hosts file: ${Y.message}`,R)}}async function JR(_,R){N("hosts",`Removing hosts: ${_.join(", ")}`,R);try{let D;try{D=await C.promises.readFile(H,"utf-8")}catch{N("hosts","Reading hosts file requires elevated permissions, using sudo",R);try{D=await g(`cat "${H}"`)}catch(X){throw N("hosts",`sudo read also failed: ${X}`,R),Error(`Cannot read hosts file: ${X}`)}}let K=D.split(`
6
+ `),Y=!1,B=K.filter((X)=>{if(_.some((Z)=>X.includes(` ${Z}`)&&(X.includes("127.0.0.1")||X.includes("::1"))))return Y=!0,!1;if(X.trim()==="# Added by rpx")return Y=!0,!1;return!0});if(!Y){N("hosts","No matching hosts found to remove",R);return}while(B[B.length-1]?.trim()==="")B.pop();let $=`${B.join(`
7
7
  `)}
8
- `,Z=Z_.join(b_.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await L.promises.writeFile(Z,$,"utf8"),await e(`cat "${Z}" | tee "${C}" > /dev/null`),N("hosts","Hosts removed successfully",_)}catch(S){N("hosts","Could not clean up hosts file automatically",_)}finally{try{await L.promises.unlink(Z)}catch(S){N("hosts",`Failed to remove temporary file: ${S}`,_)}}}catch(B){N("hosts",`Failed to clean up hosts file: ${B.message}`,_)}}async function v(D,_){N("hosts",`Checking hosts: ${D}`,_);let B;try{B=await L.promises.readFile(C,"utf-8")}catch(K){N("hosts",`Error reading hosts file: ${K}`,_);try{let R=a(),G;if(R)G=`echo '${R}' | sudo -S cat "${C}" 2>/dev/null`;else G=`sudo -n cat "${C}" 2>/dev/null || cat "${C}" 2>/dev/null || echo ""`;let{stdout:$}=await l(G);B=$}catch(R){return N("hosts",`Cannot read hosts file, assuming entries don't exist: ${R}`,_),D.map(()=>!1)}}return D.map((K)=>{let R=`127.0.0.1 ${K}`,G=`::1 ${K}`;return B.includes(R)||B.includes(G)})}import*as __ from"node:net";function O(D,_,B){return N("port",`Checking if port ${D} is in use on ${_}`,B),new Promise((K)=>{let R=__.createServer(),G=setTimeout(()=>{N("port",`Checking port ${D} timed out, assuming it's in use`,B),R.close(),K(!0)},3000);R.once("error",($)=>{if(clearTimeout(G),$.code==="EADDRINUSE")N("port",`Port ${D} is in use`,B),K(!0);else N("port",`Error checking port ${D}: ${$.message}`,B),K(!0)}),R.once("listening",()=>{clearTimeout(G),N("port",`Port ${D} is available`,B),R.close(),K(!1)});try{R.listen(D,_)}catch($){clearTimeout(G),N("port",`Exception checking port ${D}: ${$}`,B),K(!0)}})}async function a_(D,_,B,K=50){N("port",`Finding available port starting from ${D} (max attempts: ${K})`,B);let R=D,G=0;while(G<K){if(G++,!await O(R,_,B))return N("port",`Found available port: ${R} after ${G} attempts`,B),R;N("port",`Port ${R} is in use, trying ${R+1} (attempt ${G}/${K})`,B),R++}throw Error(`Unable to find available port after ${K} attempts starting from ${D}`)}function l_(D,_,B=5000,K){return N("port",`Testing connection to ${_}:${D}`,K),new Promise((R)=>{let G=__.connect({host:_,port:D,timeout:B});G.once("connect",()=>{N("port",`Successfully connected to ${_}:${D}`,K),G.end(),R(!0)}),G.once("timeout",()=>{N("port",`Connection to ${_}:${D} timed out`,K),G.destroy(),R(!1)}),G.once("error",($)=>{N("port",`Failed to connect to ${_}:${D}: ${$.message}`,K),G.destroy(),R(!1)})})}class g{usedPorts=new Set;hostname;verbose;maxRetries;constructor(D="0.0.0.0",_,B=50){this.hostname=D,this.verbose=_,this.maxRetries=B}async getNextAvailablePort(D,_=!1){if(this.usedPorts.has(D))return this.findNextAvailablePort(D+1,_);if(await O(D,this.hostname,this.verbose))return this.findNextAvailablePort(D+1,_);if(_){if(!await l_(D,this.hostname,3000,this.verbose))return N("port",`Port ${D} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(D+1,_)}return this.usedPorts.add(D),D}async findNextAvailablePort(D,_=!1){let B=await a_(D,this.hostname,this.verbose,this.maxRetries);if(_){if(!await l_(B,this.hostname,3000,this.verbose))if(B<D+this.maxRetries)return this.findNextAvailablePort(B+1,_);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(B),B}releasePort(D){N("port",`Releasing port ${D}`,this.verbose),this.usedPorts.delete(D)}}var r_=new g;import{spawn as s_}from"node:child_process";import*as c from"node:process";class D_{processes=new Map;isShuttingDown=!1;async startProcess(D,_,B){if(this.processes.has(D)){N("start",`Process ${D} is already running`,B);return}let[K,...R]=_.command.split(" "),G=_.cwd||c.cwd();N("start",`Starting process ${D}:`,B),N("start",` Command: ${K} ${R.join(" ")}`,B),N("start",` Working directory: ${G}`,B),N("start",` Environment variables: ${y(_.env)}`,B);let $=s_(K,R,{cwd:G,env:{...c.env,..._.env},shell:!0,stdio:"inherit"});return this.processes.set(D,{command:_.command,cwd:G,process:$,env:_.env}),new Promise((Z,S)=>{if($.on("error",(J)=>{if(!this.isShuttingDown)N("start",`Process ${D} failed to start: ${J}`,B),this.processes.delete(D),S(J),c.emit("SIGINT")}),$.on("exit",(J)=>{if(!this.isShuttingDown&&J!==null&&J!==0)N("start",`Process ${D} exited with code ${J}`,B),this.processes.delete(D),S(Error(`Process ${D} exited with code ${J}`)),c.emit("SIGINT")}),B)$.stdout?.on("data",(J)=>{N("process",`[${D}] ${J.toString().trim()}`,!0)}),$.stderr?.on("data",(J)=>{N("process",`[${D}] ERR: ${J.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&$.killed)this.processes.delete(D),S(Error(`Process ${D} was killed during startup`));else N("start",`Process ${D} started successfully`,B),Z()},1000)})}async stopProcess(D,_){let B=this.processes.get(D);if(!B?.process){N("start",`No process found for ${D}`,_);return}return N("start",`Stopping process ${D}`,_),new Promise((K)=>{if(!B.process){K();return}B.process.once("exit",()=>{this.processes.delete(D),N("start",`Process ${D} stopped`,_),K()});try{B.process.kill("SIGTERM"),setTimeout(()=>{if(B.process){N("start",`Force killing process ${D}`,_);try{B.process.kill("SIGKILL")}catch(R){}}},3000)}catch(R){N("start",`Error stopping process ${D}: ${R}`,_),this.processes.delete(D),K()}})}async stopAll(D){if(this.isShuttingDown){N("start","Already shutting down, skipping duplicate stopAll call",D);return}this.isShuttingDown=!0,N("start","Stopping all processes",D);let _=Array.from(this.processes.keys()).map((B)=>this.stopProcess(B,D).catch((K)=>{X.error(`Failed to stop process ${B}:`,K)}));await Promise.allSettled(_),this.processes.clear(),this.isShuttingDown=!1}isRunning(D){let _=this.processes.get(D);return!!_?.process&&!_.process.killed}}var p2=new D_;import{timingSafeEqual as o_}from"node:crypto";function e_(D,_){if(D==null)return!1;let B=Buffer.from(D),K=Buffer.from(_);if(B.length!==K.length)return!1;return o_(B,K)}function B_(D){return D.toLowerCase().replace(/\.$/,"")}var _D=["/.well-known/acme-challenge/"];function DD(D){let _=D.headers.get("host");if(_)return B_(_.split(":")[0]);try{return B_(new URL(D.url).hostname)}catch{return""}}function M_(D){let _=D.header.toLowerCase(),B=new Set,K=[];for(let S of D.hosts){let J=B_(S);if(J.startsWith("*."))K.push(J);else B.add(J)}let R=D.exemptPaths??_D,G=D.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
9
- `,$=(S)=>{let J=B_(S);return B.has(J)||K.some((F)=>T_(J,F))},Z=(S)=>{let J=DD(S);if(!$(J))return;let F="/";try{F=new URL(S.url).pathname}catch{}if(R.some((w)=>F.startsWith(w)))return;if(e_(S.headers.get(_),D.value))return;return new Response(G,{status:403,headers:{"content-type":"text/plain"}})};return Z.protects=$,Z}var K_=new D_,ND="0.12.0",KD=new g("0.0.0.0"),p=new Set,z_=!1,N_=null,F_=null;async function n(D){if(z_)return N("cleanup","Cleanup already in progress, skipping",D?.verbose),F_||Promise.resolve();z_=!0,N("cleanup","Starting cleanup process",D?.verbose),F_=new Promise((_)=>{N_=_});try{await K_.stopAll(D?.verbose),X.info("Shutting down proxy servers...");let _=[],B=Array.from(p).map((K)=>new Promise((R)=>{K.close(()=>{N("cleanup","Server closed successfully",D?.verbose),R()})}));if(_.push(...B),D?.hosts&&D.domains?.length){N("cleanup","Cleaning up hosts file entries",D?.verbose),N("cleanup",`Original domains for cleanup: ${JSON.stringify(D.domains)}`,D?.verbose);let K=D.domains.filter((R)=>{if(R==="test.local")return!0;return R!=="localhost"&&!R.startsWith("localhost.")&&R!=="127.0.0.1"});if(N("cleanup",`Filtered domains for cleanup: ${JSON.stringify(K)}`,D?.verbose),K.length>0)X.info("Cleaning up hosts file entries..."),_.push(A_(K,D?.verbose).then(()=>{N("cleanup",`Removed hosts entries for ${K.join(", ")}`,D?.verbose)}).catch((R)=>{N("cleanup",`Failed to remove hosts entries: ${R}`,D?.verbose),X.warn(`Failed to clean up hosts file entries for ${K.join(", ")}:`,R)}))}if(D?.certs&&D.domains?.length){N("cleanup","Cleaning up SSL certificates",D?.verbose),X.info("Cleaning up SSL certificates...");let K=D.domains.map(async(R)=>{try{await w_(R,D?.verbose),N("cleanup",`Removed certificates for ${R}`,D?.verbose)}catch(G){N("cleanup",`Failed to remove certificates for ${R}: ${G}`,D?.verbose),X.warn(`Failed to clean up certificates for ${R}:`,G)}});_.push(...K)}await Promise.allSettled(_),N("cleanup","All cleanup tasks completed successfully",D?.verbose),X.success("All cleanup tasks completed successfully")}catch(_){N("cleanup",`Error during cleanup: ${_}`,D?.verbose),X.error("Error during cleanup:",_)}finally{if(N_)N_();N_=null,z_=!1;let _=D&&"vitePluginUsage"in D&&D.vitePluginUsage===!0;if(j.env.NODE_ENV!=="test"&&j.env.BUN_ENV!=="test"&&!_)j.exit(0)}return F_}var I_=!1;function U_(D){if(I_){N("signal",`Received second ${D} signal, forcing exit`,!0),j.exit(1);return}I_=!0,N("signal",`Received ${D} signal, initiating cleanup`,!0),n().catch((_)=>{N("signal",`Cleanup failed after ${D}: ${_}`,!0),j.exit(1)}).finally(()=>{I_=!1})}j.once("SIGINT",()=>U_("SIGINT"));j.once("SIGTERM",()=>U_("SIGTERM"));j.on("uncaughtException",(D)=>{N("process",`Uncaught exception: ${D}`,!0),X.error("Uncaught exception:",D),U_("uncaughtException")});async function i(D,_,B,K=5){N("connection",`Testing connection to ${D}:${_} (retries left: ${K})`,B);let R=15000,G=Date.now();if(j.env.RPX_BYPASS_CONNECTION_TEST==="true"){N("connection",`Bypassing connection test for ${D}:${_} due to RPX_BYPASS_CONNECTION_TEST flag`,B);return}let $=()=>new Promise((Z,S)=>{let J=p_.connect({host:D,port:_,timeout:3000});J.once("connect",()=>{N("connection",`Successfully connected to ${D}:${_}`,B),J.end(),Z()}),J.once("timeout",()=>{N("connection",`Connection to ${D}:${_} timed out`,B),J.destroy(),S(Error("Connection timed out"))}),J.once("error",(F)=>{N("connection",`Failed to connect to ${D}:${_}: ${F}`,B),J.destroy(),S(F)})});try{await $()}catch(Z){let S=Z;if(Date.now()-G>R){N("connection",`Connection test timed out after ${R}ms, but continuing anyway`,B),X.warn(`Connection test to ${D}:${_} timed out, but RPX will try to proceed anyway.`);return}if(S.code==="ECONNREFUSED"&&K>0)return N("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${K} retries left)`,B),await new Promise((F)=>setTimeout(F,2000)),i(D,_,B,K-1);if(K>0)try{N("connection",`Trying HTTP request to ${D}:${_}`,B),await new Promise((F,w)=>{let A=h.request({hostname:D,port:_,path:"/",method:"HEAD",timeout:5000},(I)=>{N("connection",`Received HTTP response with status: ${I.statusCode}`,B),F()});A.on("error",(I)=>w(I)),A.on("timeout",()=>{A.destroy(),w(Error("HTTP request timed out"))}),A.end()}),N("connection",`HTTP request to ${D}:${_} succeeded`,B);return}catch(F){return N("connection",`HTTP request to ${D}:${_} failed: ${F}`,B),N("connection",`Retrying socket connection in 2 seconds... (${K} retries left)`,B),await new Promise((w)=>setTimeout(w,2000)),i(D,_,B,K-1)}let J=`Failed to connect to ${D}:${_} after ${5-K} attempts: ${S.message}`;N("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,B),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 O_(D){N("server",`Starting server with options: ${y(D)}`,D.verbose);let _=new URL((D.from?.startsWith("http")?D.from:`http://${D.from}`)||"localhost:5173"),B=new URL((D.to?.startsWith("http")?D.to:`http://${D.to}`)||"rpx.localhost"),K=Number.parseInt(_.port)||(_.protocol.includes("https:")?443:80),R=[B.hostname];if(P_(D)&&!B.hostname.includes("localhost")&&!B.hostname.includes("127.0.0.1")){N("hosts",`Checking if hosts file entry exists for: ${B.hostname}`,D?.verbose);try{if(!(await v(R,D.verbose))[0]){X.info(`Adding ${B.hostname} to hosts file...`),X.info("This may require sudo/administrator privileges");try{await m(R,D.verbose)}catch(Z){if(X.error("Failed to add hosts entry:",Z.message),X.warn("You can manually add this entry to your hosts file:"),X.warn(`127.0.0.1 ${B.hostname}`),X.warn(`::1 ${B.hostname}`),j.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 N("hosts",`Host entry already exists for ${B.hostname}`,D.verbose)}catch($){X.error("Failed to check hosts file:",$.message)}}try{await i(_.hostname,K,D.verbose)}catch($){N("server",`Connection test failed: ${$}`,D.verbose),X.error($.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 G=D._cachedSSLConfig||null;if(D.https)try{if(D.https===!0)D.https=Y_({...D,to:B.hostname});if(G=await b({...D,to:B.hostname,https:D.https}),!G){if(N("ssl",`Generating new certificates for ${B.hostname}`,D.verbose),await S_({...D,from:_.toString(),to:B.hostname,https:D.https}),G=await b({...D,to:B.hostname,https:D.https}),!G)throw Error(`Failed to load SSL configuration after generating certificates for ${B.hostname}`)}}catch($){throw N("server",`SSL setup failed: ${$}`,D.verbose),$}N("server",`Setting up reverse proxy with SSL config for ${B.hostname}`,D.verbose),await SD({...D,from:D.from||"localhost:5173",to:B.hostname,fromPort:K,sourceUrl:{hostname:_.hostname,host:_.host},ssl:G})}async function RD(D,_,B,K,R,G,$,Z,S,J,F){N("proxy",`Creating proxy server ${D} -> ${_} with cleanUrls: ${J}`,S);function w(W){let Q={};for(let[V,T]of Object.entries(W))if(!V.startsWith(":"))Q[V]=T;return Q}let A=(W,Q)=>{N("request",`Incoming request: ${W.method} ${W.url}`,S);let V=W.url||"/",T=W.method||"GET";if(W instanceof g_.Http2ServerRequest){let z=W.headers;T=z[":method"]||T,V=z[":path"]||V}if(J){if(!V.match(/\.[a-z0-9]+$/i))if(V.endsWith("/"))V=`${V}index.html`;else V=`${V}.html`}let H=w(W.headers);if(F)H.host=`${G.hostname}:${B}`,N("request",`Changed origin: setting host header to ${H.host}`,S);let k={hostname:G.hostname,port:B,path:V,method:T,headers:H};N("request",`Proxy request options: ${y(k)}`,S);let P=h.request(k,(z)=>{if(N("response",`Proxy response received with status ${z.statusCode}`,S),J&&z.statusCode===404){let M=[];if(V.endsWith(".html"))M.push(V.slice(0,-5));else if(!V.match(/\.[a-z0-9]+$/i))M.push(`${V}.html`);if(!V.endsWith("/"))M.push(`${V}/index.html`);if(M.length>0){N("cleanUrls",`Trying alternative paths: ${M.join(", ")}`,S);let E=(f)=>{if(f.length===0){Q.writeHead(z.statusCode||404,z.headers),z.pipe(Q);return}let U=f[0],t={...k,path:U},u=h.request(t,(r)=>{if(r.statusCode===200)N("cleanUrls",`Found matching path: ${U}`,S),Q.writeHead(r.statusCode,r.headers),r.pipe(Q);else E(f.slice(1))});u.on("error",()=>E(f.slice(1))),u.end()};E(M);return}}let $_={...z.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};Q.writeHead(z.statusCode||500,$_),z.pipe(Q)});P.on("error",(z)=>{N("request",`Proxy request failed: ${z}`,S),X.error("Proxy request failed:",z),Q.writeHead(502),Q.end(`Proxy Error: ${z.message}`)}),W.pipe(P)};if(N("server",`Creating server with SSL config: ${!!$}`,S),$)return new Promise((W,Q)=>{try{let V=Bun.serve({port:K,hostname:R,reusePort:j_(),tls:{key:$.key,cert:$.cert,ca:$.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(T){let H=new URL(T.url);if(N("request",`Bun.serve received: ${T.method} ${H.pathname}`,S),J&&H.pathname.endsWith(".html")){let z=H.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:z}})}let k=`http://${G.host}`,P=`${k}${H.pathname}${H.search}`;try{let z=new Headers(T.headers);if(z.set("host",G.host),F)z.set("origin",k);return z.set("x-forwarded-for","127.0.0.1"),z.set("x-forwarded-proto","https"),z.set("x-forwarded-host",_),await fetch(P,{method:T.method,headers:z,body:T.body,redirect:"manual"})}catch(z){return N("request",`Proxy error: ${z}`,S),new Response(`Proxy Error: ${z}`,{status:502})}},error(T){return N("server",`Bun.serve error: ${T}`,S),new Response(`Server Error: ${T.message}`,{status:500})}});p.add(V),d_({from:D,to:_,vitePluginUsage:Z,listenPort:K,ssl:!0,cleanUrls:J,verbose:S}),W()}catch(V){Q(V)}});let I=h.createServer(A);function Y(W){return p.add(W),new Promise((Q,V)=>{W.listen(K,R,()=>{N("server",`Server listening on port ${K}`,S),d_({from:D,to:_,vitePluginUsage:Z,listenPort:K,ssl:!!$,cleanUrls:J,verbose:S}),Q()}),W.on("error",(T)=>{N("server",`Server error: ${T}`,S),V(T)})})}return Y(I)}async function SD(D){N("setup",`Setting up reverse proxy: ${y(D)}`,D.verbose);let{from:_,to:B,fromPort:K,sourceUrl:R,ssl:G,verbose:$,cleanup:Z,vitePluginUsage:S,changeOrigin:J,cleanUrls:F}=D,w=80,A=443,I="0.0.0.0",Y=D.portManager||KD,W=P_(D);try{if(W&&B&&!B.includes("localhost")&&!B.includes("127.0.0.1")){if(!(await v([B],$))[0]){X.warn(`The hostname ${B} isn't in your hosts file. Adding it now...`);try{await m([B],$),X.success(`Added ${B} to your hosts file.`)}catch(k){X.error(`Failed to add ${B} to your hosts file: ${k}`),X.info(`You may need to manually add '127.0.0.1 ${B}' to your /etc/hosts file.`)}}}else if(W&&j.platform!=="darwin"&&B&&B.includes("localhost")&&!B.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await v([B],$))[0]){N("hosts",`${B} not found in hosts file, adding...`,$);try{await m([B],$)}catch(k){N("hosts",`Failed to add ${B} to hosts file: ${k}`,$)}}}if(G&&!Y.usedPorts.has(w)){if(!await O(w,I,$))N("setup","Starting HTTP redirect server",$),i_($),Y.usedPorts.add(w);else if(N("setup","Port 80 is in use, skipping HTTP redirect",$),$)X.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let Q=G?A:w,V=await O(Q,I,$),T;if(V){if(N("setup",`Port ${Q} is already in use`,$),$)X.warn(`Port ${Q} is already in use. This may be another instance of rpx or another service.`);if(Q===443){if(T=await Y.getNextAvailablePort(3443,!0),N("setup",`Using port ${T} instead of ${Q}`,$),$)X.info(`Using port ${T} instead. Access your site at https://${B}:${T}`)}else if(T=await Y.getNextAvailablePort(Q+1000,!0),N("setup",`Using port ${T} instead of ${Q}`,$),$)X.info(`Using port ${T} instead. Access your site at http://${B}:${T}`)}else T=Q,Y.usedPorts.add(T),N("setup",`Using standard ${Q===443?"HTTPS":"HTTP"} port ${Q} for ${B}`,$);await RD(_,B,K,T,I,R,G,S,$,F,J)}catch(Q){N("setup",`Setup failed: ${Q}`,$),X.error(`Failed to setup reverse proxy: ${Q.message}`),n({domains:[B],hosts:typeof Z==="boolean"?Z:Z?.hosts,certs:typeof Z==="boolean"?Z:Z?.certs,verbose:$,vitePluginUsage:S})}}function i_(D){N("redirect","Starting HTTP redirect server",D);let _=h.createServer((B,K)=>{let R=B.headers.host||"";N("redirect",`Redirecting request from ${R}${B.url} to HTTPS`,D),K.writeHead(301,{Location:`https://${R}${B.url}`}),K.end()}).listen(80);p.add(_),N("redirect","HTTP redirect server started",D)}function YD(D){let _={...R_,...D};if(N("proxy",`Starting proxy with options: ${y(_)}`,_?.verbose),_.viaDaemon){if(!_.from||!_.to){X.error("viaDaemon mode requires both `from` and `to`");return}o({proxies:[{id:_.id,from:_.from,to:_.to,path:_.path,cleanUrls:_.cleanUrls,changeOrigin:_.changeOrigin,pathRewrites:_.pathRewrites}],verbose:_.verbose}).catch((S)=>{X.error(`Failed to register with rpx daemon: ${S.message}`),j.exit(1)});return}let B=_.to||"",K=B.split(".").pop()?.toLowerCase()||"",R=j.platform==="darwin"&&B&&!B.includes("localhost")&&!B.includes("127.0.0.1"),G=["dev","app","page","new","day","foo"],$=["test","localhost","local","example","invalid"];if(R&&G.includes(K)&&_?.verbose)X.warn(`The .${K} TLD may not work reliably for local development`),X.info(` Google owns .${K} with HSTS preloading, which can bypass local DNS`),X.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(R)import("./chunk-83dqq28c.js").then(({setupDevelopmentDns:S})=>{S({domains:[B],verbose:_.verbose}).then((J)=>{if(J)Promise.resolve().then(()=>{if(_.verbose)if($.includes(K))X.success(`DNS server started for .${K} domains`);else X.success(`DNS server started for .${K} domains (hosts file entry also added)`)});else N("dns",`Could not start DNS server - ${B} may not resolve in browser`,_.verbose)})}).catch((S)=>{N("dns",`Failed to start DNS server: ${S}`,_.verbose)});let Z={from:_.from,to:_.to,cleanUrls:_.cleanUrls,https:Y_(_),cleanup:_.cleanup,vitePluginUsage:_.vitePluginUsage,changeOrigin:_.changeOrigin,verbose:_.verbose,regenerateUntrustedCerts:_.regenerateUntrustedCerts};N("proxy",`Server options: ${y(Z)}`,_.verbose),O_(Z).catch((S)=>{N("proxy",`Failed to start proxy: ${S}`,_.verbose),X.error(`Failed to start proxy: ${S.message}`),n({domains:[_.to],hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose})})}function $D(D){return D?.verbose||!1}function P_(D){if(D?.hostsManagement===!1)return!1;let _=D?.cleanup;if(_===!1)return!1;if(_&&typeof _==="object"&&_.hosts===!1)return!1;return!0}async function L_(D){let _={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(D)_={..._,...D};let B=$D(_),K=P_(_);if(N("config",`Starting with config: ${y(_,2)}`,B),N("config",`Is multi-proxy? ${"proxies"in _}`,B),N("config",`Hosts management enabled? ${K}`,B),_.viaDaemon){let W="proxies"in _&&Array.isArray(_.proxies)?_.proxies.map((Q)=>({id:Q.id,from:Q.from,to:Q.to,path:Q.path,cleanUrls:Q.cleanUrls??_.cleanUrls,changeOrigin:Q.changeOrigin??_.changeOrigin,pathRewrites:Q.pathRewrites})):[{id:_.id,from:_.from,to:_.to??"rpx.localhost",path:_.path,cleanUrls:_.cleanUrls,changeOrigin:_.changeOrigin,pathRewrites:_.pathRewrites}];await o({proxies:W,verbose:B});return}if("proxies"in _&&Array.isArray(_.proxies)){N("servers",`Found ${_.proxies.length} proxies in config`,B);for(let Y of _.proxies)if(Y.start){let W=`${Y.from}-${Y.to}`;try{N("watch",`Starting command for ${W} with command: ${Y.start.command}`,B),X.info(`Starting command for ${W}...`),await K_.startProcess(W,Y.start,B);let Q=new URL(Y.from?.startsWith("http")?Y.from:`http://${Y.from}`),V=Q.hostname||"localhost",T=Number(Q.port)||80;try{await i(V,T,B),N("watch",`Dev server is ready at ${V}:${T}`,B)}catch(H){N("watch",`Connection check failed, but continuing with proxy setup: ${H}`,B),X.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(Q){throw N("watch",`Failed to start command for ${W}: ${Q}`,B),Error(`Failed to start command for ${W}: ${Q}`)}}else N("watch",`No start command for proxy ${Y.from} -> ${Y.to}`,B)}else if("start"in _&&_.start){N("watch","Found start command in single proxy config",B);let Y=`${_.from}-${_.to}`;try{if(_.start)N("watch",`Starting command: ${_.start.command}`,B),await K_.startProcess(Y,_.start,B);let W=new URL(_.from?.startsWith("http")?_.from:`http://${_.from}`),Q=W.hostname||"localhost",V=Number(W.port)||80;try{await i(Q,V,B),N("watch",`Dev server is ready at ${Q}:${V}`,B)}catch(T){N("watch",`Connection check failed, but continuing with proxy setup: ${T}`,B),X.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(W){throw N("watch",`Failed to run start command: ${W}`,B),Error(`Failed to run start command: ${W}`)}}else N("watch","No start command found in config",B);let R="proxies"in _&&Array.isArray(_.proxies)?_.proxies[0]?.to:("to"in _)?_.to:"rpx.localhost";if(j.platform!=="win32"&&(_.https||K)){if(!a())try{N("sudo","Pre-acquiring sudo credentials for privileged operations",B),BD("sudo -v",{stdio:"inherit"})}catch{N("sudo","Could not pre-acquire sudo credentials",B)}}if(_.https){let Y=await b(_);if(!Y){if(N("ssl",`No valid or trusted certificates found for ${R}, generating new ones`,_.verbose),await S_(_),Y=await b(_),!Y)throw Error(`Failed to load SSL certificates after generation for ${R}`)}else N("ssl",`Using existing and trusted certificates for ${R}`,_.verbose);_._cachedSSLConfig=Y}let G="proxies"in _&&Array.isArray(_.proxies)?_.proxies.map((Y)=>({...Y,https:_.https,cleanup:_.cleanup,cleanUrls:Y.cleanUrls??("cleanUrls"in _?_.cleanUrls:!1),vitePluginUsage:_.vitePluginUsage,changeOrigin:Y.changeOrigin??_.changeOrigin,verbose:B,_cachedSSLConfig:_._cachedSSLConfig})):[{from:"from"in _?_.from:"localhost:5173",to:"to"in _?_.to:"rpx.localhost",cleanUrls:"cleanUrls"in _?_.cleanUrls:!1,https:_.https,cleanup:_.cleanup,vitePluginUsage:_.vitePluginUsage,start:"start"in _?_.start:void 0,changeOrigin:_.changeOrigin,verbose:B,_cachedSSLConfig:_._cachedSSLConfig}],$=G.map((Y)=>Y.to||"rpx.localhost"),Z=_._cachedSSLConfig,S=$.filter((Y)=>Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1")),J=["dev","app","page","new","day","foo"],F=["test","localhost","local","example","invalid"],w=[...new Set(S.map((Y)=>Y.split(".").pop()?.toLowerCase()))],A=w.filter((Y)=>!!Y&&J.includes(Y));if(A.length>0&&B)X.warn(`The following TLDs may not work reliably for local development: ${A.map((Y)=>`.${Y}`).join(", ")}`),X.info(" These TLDs have HSTS preloading which can bypass local DNS"),X.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(K&&j.platform==="darwin"&&S.length>0){let{setupDevelopmentDns:Y}=await import("./chunk-83dqq28c.js");if(await Y({domains:S,verbose:B})){if(B)if(w.every((V)=>!!V&&F.includes(V)))X.success(`DNS server started for ${w.map((V)=>`.${V}`).join(", ")} domains`);else X.success(`DNS server started for ${w.map((V)=>`.${V}`).join(", ")} domains (hosts file entries also added)`)}else N("dns","Could not start DNS server - custom domains may not resolve",B)}let I=async()=>{N("cleanup","Starting cleanup handler",_.verbose);try{let{tearDownDevelopmentDns:Y}=await import("./chunk-83dqq28c.js");await Y({verbose:_.verbose})}catch(Y){N("cleanup",`Error stopping DNS server: ${Y}`,_.verbose)}try{await K_.stopAll(_.verbose)}catch(Y){N("cleanup",`Error stopping processes: ${Y}`,_.verbose)}await n({domains:$,hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose||!1})};if(j.on("SIGINT",I),j.on("SIGTERM",I),j.on("uncaughtException",(Y)=>{N("process",`Uncaught exception: ${Y}`,!0),console.error("Uncaught exception:",Y),I()}),Z&&G.length>1){N("proxies",`Creating shared HTTPS server for ${G.length} domains`,B);let Y=[],W=new Set;for(let M of G){let E=M.to||"rpx.localhost",f=M.cleanUrls||!1,U=M.path,t=f_(U);if(M.static)Y.push({host:E,path:U,route:{static:H_(M.static,f),cleanUrls:f,basePath:t}}),N("proxies",`Route: ${E}${U??""} → static ${typeof M.static==="string"?M.static:M.static.dir}`,B);else{let u=new URL(M.from?.startsWith("http")?M.from:`http://${M.from}`);Y.push({host:E,path:U,route:{sourceHost:u.host,cleanUrls:f,changeOrigin:M.changeOrigin||!1,pathRewrites:M.pathRewrites,basePath:t}}),N("proxies",`Route: ${E}${U??""} → ${u.host}`,B)}if(W.has(E))continue;if(W.add(E),K&&!x_(E)&&!E.includes("localhost")&&!E.includes("127.0.0.1"))try{if(!(await v([E],B))[0])await m([E],B)}catch{N("hosts",`Could not add hosts entry for ${E}`,B)}}if(!await O(80,"0.0.0.0",B))i_(B);let V=443;if(await O(V,"0.0.0.0",B)){if(N("proxies",`Port ${V} is already in use, cannot start shared proxy`,B),B)X.warn(`Port ${V} is in use. Shared HTTPS proxy cannot start.`);return}let H=q_(Y),k=k_((M,E)=>y_(H,M,E),B),P=_.originGuard?M_(_.originGuard):null,z=P?(M,E)=>P(M)??k(M,E):k,$_=C_(B);try{let M=Bun.serve({port:V,hostname:"0.0.0.0",reusePort:j_(),tls:{key:Z.key,cert:Z.cert,ca:Z.ca,requestCert:!1,rejectUnauthorized:!1},fetch(E,f){return z(E,f)},websocket:$_,error(E){return N("server",`Shared proxy server error: ${E}`,B),new Response(`Server Error: ${E.message}`,{status:500})}});p.add(M),N("proxies",`Shared HTTPS proxy listening on port ${V} for ${H.size} domains`,B)}catch(M){N("proxies",`Failed to start shared proxy: ${M}`,B),console.error("Failed to start shared HTTPS proxy:",M),I()}}else for(let Y of G)try{let W=Y.to||"rpx.localhost";N("proxy",`Starting proxy for ${W} with SSL config: ${!!Z}`,Y.verbose),await O_({from:Y.from||"localhost:5173",to:W,cleanUrls:Y.cleanUrls||!1,https:Y.https||!1,cleanup:Y.cleanup||!1,vitePluginUsage:Y.vitePluginUsage||!1,verbose:Y.verbose||!1,_cachedSSLConfig:Z,changeOrigin:Y.changeOrigin||!1})}catch(W){N("proxies",`Failed to start proxy for ${Y.to}: ${W}`,Y.verbose),console.error(`Failed to start proxy for ${Y.to}:`,W),I()}}function d_(D){if(D?.vitePluginUsage||!D?.verbose)return;if(console.log(""),console.log(` ${x.green(x.bold("rpx"))} ${x.green(`v${ND}`)}`),console.log(` ${x.green("➜")} ${x.dim(D?.from??"")} ${x.dim("➜")} ${x.cyan(D?.ssl?`https://${D?.to}`:`http://${D?.to}`)}`),D?.listenPort!==(D?.ssl?443:80))console.log(` ${x.green("➜")} Listening on port ${D?.listenPort}`);if(D?.cleanUrls)console.log(` ${x.green("➜")} Clean URLs enabled`)}var bB=L_;export{J_ as writeEntry,sD as watchRegistry,VD as verifyHttpsChain,wD as trustRootCaForBrowsers,Z2 as tearDownDevelopmentDns,W2 as syncDevelopmentDnsFromRegistry,uD as stripBasePath,Y2 as stopDnsServer,k2 as stopDaemon,O_ as startServer,YD as startProxy,L_ as startProxies,S2 as startDnsServer,j_ as shouldReusePort,J2 as setupResolver,V2 as setupDevelopmentDns,lD as serverNameFromCertFilename,hD as serveStaticFile,y as safeStringify,LD as safeRelativePath,oB as safeDeleteFile,o as runViaDaemon,w2 as runDaemon,G2 as resolverFilePath,B2 as resolverBasenamesForDomains,D2 as resolverBasenameForDomain,H_ as resolveStaticRoute,cD as resolveStaticFile,sB as resolvePathRewrite,A2 as removeResolver,Q2 as removeLegacyTldResolvers,A_ as removeHosts,Q_ as removeEntry,j2 as releaseDaemonLock,aB as redactSensitive,T2 as reconcileStaleDevelopmentDns,C2 as reconcileDevelopmentDnsOnIdle,nD as readEntry,F2 as readDaemonPid,XD as readCertSha256Fingerprint,JD as readCertCommonName,tD as readAll,ID as pruneStaleRootCas,r_ as portManager,vD as pathPrefixMatches,WD as parseSha256HashesFromSecurityListing,GD as normalizeSha256Fingerprint,f_ as normalizePathPrefix,_2 as normalizeDevDomain,T_ as matchesWildcard,dD as matchesAllowedSuffix,y_ as matchHostRoute,bD as matchHostList,mD as matchHost,qD as loadSSLConfig,FD as listCertSha256HashesByCommonName,x_ as isWildcardPattern,gB as isValidRootCA,X_ as isValidId,tB as isSingleProxyOptions,rB as isSingleProxyConfig,ED as isRootCaTrustedForSsl,jD as isRootCaFingerprintInKeychains,v_ as isProcessElevated,O as isPortInUse,iD as isPidAlive,nB as isMultiProxyOptions,iB as isMultiProxyConfig,gD as isLikelyHostname,$2 as isDnsServerRunning,I2 as isDaemonRunning,OD as isCertTrusted,Y_ as httpsConfig,a as getSudoPassword,fD as getSharedDaemonCertPaths,xD as getRootCAPaths,G_ as getRegistryDir,pB as getPrimaryDomain,zD as getMacosTrustKeychains,MD as getMacosLoginKeychainPath,M2 as getDaemonRpxDir,z2 as getDaemonPidPath,S_ as generateCertificate,rD as gcStaleEntries,yD as forceTrustCertificate,a_ as findAvailablePort,dB as extractHostname,lB as execSudoSync,V_ as ensureDaemonRunning,kD as devSslToSniEntries,N2 as devDomainsFromHosts,u_ as deriveIdFromTarget,H2 as defaultDaemonSpawnCommand,R_ as defaultConfig,bB as default,N as debugLog,C_ as createProxyWebSocketHandler,k_ as createProxyFetchHandler,M_ as createOriginGuard,PD as contentTypeFor,X2 as contentLooksLikeRpxResolver,R_ as config,x as colors,UD as clearSslConfigCache,w_ as cleanupCertificates,n as cleanup,v as checkHosts,b as checkExistingCertificates,QD as certIncludesSanHostnames,aD as buildSniTlsConfig,CD as buildRegistryTlsProxyOptions,q_ as buildHostRoutes,m as addHosts,E2 as acquireDaemonLock,HD as SHARED_DEV_HOST_CERT_PATH,TD as RPX_ROOT_CA_COMMON_NAME,R2 as RPX_RESOLVER_MARKER,pD as OnDemandCertManager,AD as MACOS_SYSTEM_KEYCHAIN,ZD as MACOS_CA_TRUST_FLAGS,eD as LEGACY_TLD_RESOLVER_LABELS,g as DefaultPortManager,oD as DNS_STATE_VERSION,K2 as DNS_PORT};
8
+ `,V=GR.join(PR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await C.promises.writeFile(V,$,"utf8"),await g(`cat "${V}" | tee "${H}" > /dev/null`),N("hosts","Hosts removed successfully",R)}catch(X){N("hosts","Could not clean up hosts file automatically",R)}finally{try{await C.promises.unlink(V)}catch(X){N("hosts",`Failed to remove temporary file: ${X}`,R)}}}catch(D){N("hosts",`Failed to clean up hosts file: ${D.message}`,R)}}async function y(_,R){N("hosts",`Checking hosts: ${_}`,R);let D;try{D=await C.promises.readFile(H,"utf-8")}catch(K){N("hosts",`Error reading hosts file: ${K}`,R);try{let Y=h(),B;if(Y)B=`echo '${Y}' | sudo -S cat "${H}" 2>/dev/null`;else B=`sudo -n cat "${H}" 2>/dev/null || cat "${H}" 2>/dev/null || echo ""`;let{stdout:$}=await c(B);D=$}catch(Y){return N("hosts",`Cannot read hosts file, assuming entries don't exist: ${Y}`,R),_.map(()=>!1)}}return _.map((K)=>{let Y=`127.0.0.1 ${K}`,B=`::1 ${K}`;return D.includes(Y)||D.includes(B)})}import*as p from"node:net";function q(_,R,D){return N("port",`Checking if port ${_} is in use on ${R}`,D),new Promise((K)=>{let Y=p.createServer(),B=setTimeout(()=>{N("port",`Checking port ${_} timed out, assuming it's in use`,D),Y.close(),K(!0)},3000);Y.once("error",($)=>{if(clearTimeout(B),$.code==="EADDRINUSE")N("port",`Port ${_} is in use`,D),K(!0);else N("port",`Error checking port ${_}: ${$.message}`,D),K(!0)}),Y.once("listening",()=>{clearTimeout(B),N("port",`Port ${_} is available`,D),Y.close(),K(!1)});try{Y.listen(_,R)}catch($){clearTimeout(B),N("port",`Exception checking port ${_}: ${$}`,D),K(!0)}})}async function hR(_,R,D,K=50){N("port",`Finding available port starting from ${_} (max attempts: ${K})`,D);let Y=_,B=0;while(B<K){if(B++,!await q(Y,R,D))return N("port",`Found available port: ${Y} after ${B} attempts`,D),Y;N("port",`Port ${Y} is in use, trying ${Y+1} (attempt ${B}/${K})`,D),Y++}throw Error(`Unable to find available port after ${K} attempts starting from ${_}`)}function cR(_,R,D=5000,K){return N("port",`Testing connection to ${R}:${_}`,K),new Promise((Y)=>{let B=p.connect({host:R,port:_,timeout:D});B.once("connect",()=>{N("port",`Successfully connected to ${R}:${_}`,K),B.end(),Y(!0)}),B.once("timeout",()=>{N("port",`Connection to ${R}:${_} timed out`,K),B.destroy(),Y(!1)}),B.once("error",($)=>{N("port",`Failed to connect to ${R}:${_}: ${$.message}`,K),B.destroy(),Y(!1)})})}class m{usedPorts=new Set;hostname;verbose;maxRetries;constructor(_="0.0.0.0",R,D=50){this.hostname=_,this.verbose=R,this.maxRetries=D}async getNextAvailablePort(_,R=!1){if(this.usedPorts.has(_))return this.findNextAvailablePort(_+1,R);if(await q(_,this.hostname,this.verbose))return this.findNextAvailablePort(_+1,R);if(R){if(!await cR(_,this.hostname,3000,this.verbose))return N("port",`Port ${_} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(_+1,R)}return this.usedPorts.add(_),_}async findNextAvailablePort(_,R=!1){let D=await hR(_,this.hostname,this.verbose,this.maxRetries);if(R){if(!await cR(D,this.hostname,3000,this.verbose))if(D<_+this.maxRetries)return this.findNextAvailablePort(D+1,R);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(D),D}releasePort(_){N("port",`Releasing port ${_}`,this.verbose),this.usedPorts.delete(_)}}var iR=new m;import{spawn as nR}from"node:child_process";import*as i from"node:process";class n{processes=new Map;isShuttingDown=!1;async startProcess(_,R,D){if(this.processes.has(_)){N("start",`Process ${_} is already running`,D);return}let[K,...Y]=R.command.split(" "),B=R.cwd||i.cwd();N("start",`Starting process ${_}:`,D),N("start",` Command: ${K} ${Y.join(" ")}`,D),N("start",` Working directory: ${B}`,D),N("start",` Environment variables: ${x(R.env)}`,D);let $=nR(K,Y,{cwd:B,env:{...i.env,...R.env},shell:!0,stdio:"inherit"});return this.processes.set(_,{command:R.command,cwd:B,process:$,env:R.env}),new Promise((V,X)=>{if($.on("error",(Q)=>{if(!this.isShuttingDown)N("start",`Process ${_} failed to start: ${Q}`,D),this.processes.delete(_),X(Q)}),$.on("exit",(Q)=>{if(!this.isShuttingDown&&Q!==null&&Q!==0)N("start",`Process ${_} exited with code ${Q}; leaving the proxy running`,D),this.processes.delete(_),X(Error(`Process ${_} exited with code ${Q}`))}),D)$.stdout?.on("data",(Q)=>{N("process",`[${_}] ${Q.toString().trim()}`,!0)}),$.stderr?.on("data",(Q)=>{N("process",`[${_}] ERR: ${Q.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&$.killed)this.processes.delete(_),X(Error(`Process ${_} was killed during startup`));else N("start",`Process ${_} started successfully`,D),V()},1000)})}async stopProcess(_,R){let D=this.processes.get(_);if(!D?.process){N("start",`No process found for ${_}`,R);return}return N("start",`Stopping process ${_}`,R),new Promise((K)=>{if(!D.process){K();return}D.process.once("exit",()=>{this.processes.delete(_),N("start",`Process ${_} stopped`,R),K()});try{D.process.kill("SIGTERM"),setTimeout(()=>{if(D.process){N("start",`Force killing process ${_}`,R);try{D.process.kill("SIGKILL")}catch(Y){}}},3000)}catch(Y){N("start",`Error stopping process ${_}: ${Y}`,R),this.processes.delete(_),K()}})}async stopAll(_){if(this.isShuttingDown){N("start","Already shutting down, skipping duplicate stopAll call",_);return}this.isShuttingDown=!0,N("start","Stopping all processes",_);let R=Array.from(this.processes.keys()).map((D)=>this.stopProcess(D,_).catch((K)=>{J.error(`Failed to stop process ${D}:`,K)}));await Promise.allSettled(R),this.processes.clear(),this.isShuttingDown=!1}isRunning(_){let R=this.processes.get(_);return!!R?.process&&!R.process.killed}}var aD=new n;import{timingSafeEqual as rR}from"node:crypto";function tR(_,R){if(_==null)return!1;let D=Buffer.from(_),K=Buffer.from(R);if(D.length!==K.length)return!1;return rR(D,K)}function r(_){return _.toLowerCase().replace(/\.$/,"")}var sR=["/.well-known/acme-challenge/"];function eR(_){let R=_.headers.get("host");if(R)return r(R.split(":")[0]);try{return r(new URL(_.url).hostname)}catch{return""}}function VR(_){let R=_.header.toLowerCase(),D=new Set,K=[];for(let X of _.hosts){let Q=r(X);if(Q.startsWith("*."))K.push(Q);else D.add(Q)}let Y=_.exemptPaths??sR,B=_.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
9
+ `,$=(X)=>{let Q=r(X);return D.has(Q)||K.some((Z)=>QR(Q,Z))},V=(X)=>{let Q=eR(X);if(!$(Q))return;let Z="/";try{Z=new URL(X.url).pathname}catch{}if(Y.some((A)=>Z.startsWith(A)))return;if(tR(X.headers.get(R),_.value))return;return new Response(B,{status:403,headers:{"content-type":"text/plain"}})};return V.protects=$,V}var s=new n,R_="0.12.0",__=new m("0.0.0.0"),e=new Set,WR=!1,t=null,ZR=null;async function l(_){if(WR)return N("cleanup","Cleanup already in progress, skipping",_?.verbose),ZR||Promise.resolve();WR=!0,N("cleanup","Starting cleanup process",_?.verbose),ZR=new Promise((R)=>{t=R});try{await s.stopAll(_?.verbose),J.info("Shutting down proxy servers...");let R=[],D=Array.from(e).map((K)=>new Promise((Y)=>{let B=K;try{if(typeof B.stop==="function")B.stop(!0),N("cleanup","Bun server stopped",_?.verbose),Y();else if(typeof B.close==="function")B.close(()=>{N("cleanup","Server closed successfully",_?.verbose),Y()});else Y()}catch($){N("cleanup",`Error stopping server: ${$}`,_?.verbose),Y()}}));if(R.push(...D),e.clear(),_?.hosts&&_.domains?.length){N("cleanup","Cleaning up hosts file entries",_?.verbose),N("cleanup",`Original domains for cleanup: ${JSON.stringify(_.domains)}`,_?.verbose);let K=_.domains.filter((Y)=>{if(Y==="test.local")return!0;return Y!=="localhost"&&!Y.startsWith("localhost.")&&Y!=="127.0.0.1"});if(N("cleanup",`Filtered domains for cleanup: ${JSON.stringify(K)}`,_?.verbose),K.length>0)J.info("Cleaning up hosts file entries..."),R.push(JR(K,_?.verbose).then(()=>{N("cleanup",`Removed hosts entries for ${K.join(", ")}`,_?.verbose)}).catch((Y)=>{N("cleanup",`Failed to remove hosts entries: ${Y}`,_?.verbose),J.warn(`Failed to clean up hosts file entries for ${K.join(", ")}:`,Y)}))}if(_?.certs&&_.domains?.length){N("cleanup","Cleaning up SSL certificates",_?.verbose),J.info("Cleaning up SSL certificates...");let K=_.domains.map(async(Y)=>{try{await IR(Y,_?.verbose),N("cleanup",`Removed certificates for ${Y}`,_?.verbose)}catch(B){N("cleanup",`Failed to remove certificates for ${Y}: ${B}`,_?.verbose),J.warn(`Failed to clean up certificates for ${Y}:`,B)}});R.push(...K)}await Promise.allSettled(R),N("cleanup","All cleanup tasks completed successfully",_?.verbose),J.success("All cleanup tasks completed successfully")}catch(R){N("cleanup",`Error during cleanup: ${R}`,_?.verbose),J.error("Error during cleanup:",R)}finally{if(t)t();t=null,WR=!1;let R=_&&"vitePluginUsage"in _&&_.vitePluginUsage===!0;if(z.env.NODE_ENV!=="test"&&z.env.BUN_ENV!=="test"&&!R)z.exit(0)}return ZR}var AR=!1;function lR(_){if(AR){N("signal",`Received second ${_} signal, forcing exit`,!0),z.exit(1);return}AR=!0,N("signal",`Received ${_} signal, initiating cleanup`,!0),l().catch((R)=>{N("signal",`Cleanup failed after ${_}: ${R}`,!0),z.exit(1)}).finally(()=>{AR=!1})}z.once("SIGINT",()=>lR("SIGINT"));z.once("SIGTERM",()=>lR("SIGTERM"));z.on("uncaughtException",(_)=>{J.error("Uncaught exception (continuing):",_)});z.on("unhandledRejection",(_)=>{J.error("Unhandled rejection (continuing):",_)});async function v(_,R,D,K=5){N("connection",`Testing connection to ${_}:${R} (retries left: ${K})`,D);let Y=15000,B=Date.now();if(z.env.RPX_BYPASS_CONNECTION_TEST==="true"){N("connection",`Bypassing connection test for ${_}:${R} due to RPX_BYPASS_CONNECTION_TEST flag`,D);return}let $=()=>new Promise((V,X)=>{let Q=vR.connect({host:_,port:R,timeout:3000});Q.once("connect",()=>{N("connection",`Successfully connected to ${_}:${R}`,D),Q.end(),V()}),Q.once("timeout",()=>{N("connection",`Connection to ${_}:${R} timed out`,D),Q.destroy(),X(Error("Connection timed out"))}),Q.once("error",(Z)=>{N("connection",`Failed to connect to ${_}:${R}: ${Z}`,D),Q.destroy(),X(Z)})});try{await $()}catch(V){let X=V;if(Date.now()-B>Y){N("connection",`Connection test timed out after ${Y}ms, but continuing anyway`,D),J.warn(`Connection test to ${_}:${R} timed out, but RPX will try to proceed anyway.`);return}if(X.code==="ECONNREFUSED"&&K>0)return N("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${K} retries left)`,D),await new Promise((Z)=>setTimeout(Z,2000)),v(_,R,D,K-1);if(K>0)try{N("connection",`Trying HTTP request to ${_}:${R}`,D),await new Promise((Z,A)=>{let W=DR.request({hostname:_,port:R,path:"/",method:"HEAD",timeout:5000},(S)=>{N("connection",`Received HTTP response with status: ${S.statusCode}`,D),Z()});W.on("error",(S)=>A(S)),W.on("timeout",()=>{W.destroy(),A(Error("HTTP request timed out"))}),W.end()}),N("connection",`HTTP request to ${_}:${R} succeeded`,D);return}catch(Z){return N("connection",`HTTP request to ${_}:${R} failed: ${Z}`,D),N("connection",`Retrying socket connection in 2 seconds... (${K} retries left)`,D),await new Promise((A)=>setTimeout(A,2000)),v(_,R,D,K-1)}let Q=`Failed to connect to ${_}:${R} after ${5-K} attempts: ${X.message}`;N("connection",`${Q}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,D),J.warn(Q),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 qR(_){N("server",`Starting server with options: ${x(_)}`,_.verbose);let R=new URL((_.from?.startsWith("http")?_.from:`http://${_.from}`)||"localhost:5173"),D=new URL((_.to?.startsWith("http")?_.to:`http://${_.to}`)||"rpx.localhost"),K=Number.parseInt(R.port)||(R.protocol.includes("https:")?443:80),Y=[D.hostname];if(xR(_)&&!D.hostname.includes("localhost")&&!D.hostname.includes("127.0.0.1")){N("hosts",`Checking if hosts file entry exists for: ${D.hostname}`,_?.verbose);try{if(!(await y(Y,_.verbose))[0]){J.info(`Adding ${D.hostname} to hosts file...`),J.info("This may require sudo/administrator privileges");try{await U(Y,_.verbose)}catch(V){if(J.error("Failed to add hosts entry:",V.message),J.warn("You can manually add this entry to your hosts file:"),J.warn(`127.0.0.1 ${D.hostname}`),J.warn(`::1 ${D.hostname}`),z.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 N("hosts",`Host entry already exists for ${D.hostname}`,_.verbose)}catch($){J.error("Failed to check hosts file:",$.message)}}try{await v(R.hostname,K,_.verbose)}catch($){N("server",`Connection test failed: ${$}`,_.verbose),J.error($.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 B=_._cachedSSLConfig||null;if(_.https)try{if(_.https===!0)_.https=_R({..._,to:D.hostname});if(B=await f({..._,to:D.hostname,https:_.https}),!B){if(N("ssl",`Generating new certificates for ${D.hostname}`,_.verbose),await RR({..._,from:R.toString(),to:D.hostname,https:_.https}),B=await f({..._,to:D.hostname,https:_.https}),!B)throw Error(`Failed to load SSL configuration after generating certificates for ${D.hostname}`)}}catch($){throw N("server",`SSL setup failed: ${$}`,_.verbose),$}N("server",`Setting up reverse proxy with SSL config for ${D.hostname}`,_.verbose),await N_({..._,from:_.from||"localhost:5173",to:D.hostname,fromPort:K,sourceUrl:{hostname:R.hostname,host:R.host},ssl:B})}async function D_(_,R,D,K,Y,B,$,V,X){N("proxy",`Creating proxy server ${_} -> ${R} with cleanUrls: ${V}`,$);let Q=[{host:R,route:{sourceHost:K.host,cleanUrls:V||!1,changeOrigin:X||!1,basePath:"/"}}];if(!zR({routeEntries:Q,listenPort:D,sslConfig:Y,originGuard:null,verbose:$??!1}))throw Error(`Failed to start proxy server for ${R} on port ${D}`);Y_({from:_,to:R,vitePluginUsage:B,listenPort:D,ssl:!!Y,cleanUrls:V,verbose:$})}async function N_(_){N("setup",`Setting up reverse proxy: ${x(_)}`,_.verbose);let{from:R,to:D,sourceUrl:K,ssl:Y,verbose:B,cleanup:$,vitePluginUsage:V,changeOrigin:X,cleanUrls:Q}=_,Z=80,A=443,W="0.0.0.0",S=_.portManager||__,O=xR(_);try{if(O&&D&&!D.includes("localhost")&&!D.includes("127.0.0.1")){if(!(await y([D],B))[0]){J.warn(`The hostname ${D} isn't in your hosts file. Adding it now...`);try{await U([D],B),J.success(`Added ${D} to your hosts file.`)}catch(P){J.error(`Failed to add ${D} to your hosts file: ${P}`),J.info(`You may need to manually add '127.0.0.1 ${D}' to your /etc/hosts file.`)}}}else if(O&&z.platform!=="darwin"&&D&&D.includes("localhost")&&!D.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await y([D],B))[0]){N("hosts",`${D} not found in hosts file, adding...`,B);try{await U([D],B)}catch(P){N("hosts",`Failed to add ${D} to hosts file: ${P}`,B)}}}if(Y&&!S.usedPorts.has(Z)){if(!await q(Z,W,B))N("setup","Starting HTTP redirect server",B),bR(B),S.usedPorts.add(Z);else if(N("setup","Port 80 is in use, skipping HTTP redirect",B),B)J.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let T=Y?A:Z,E=await q(T,W,B),M;if(E){if(N("setup",`Port ${T} is already in use`,B),B)J.warn(`Port ${T} is already in use. This may be another instance of rpx or another service.`);if(T===443){if(M=await S.getNextAvailablePort(3443,!0),N("setup",`Using port ${M} instead of ${T}`,B),B)J.info(`Using port ${M} instead. Access your site at https://${D}:${M}`)}else if(M=await S.getNextAvailablePort(T+1000,!0),N("setup",`Using port ${M} instead of ${T}`,B),B)J.info(`Using port ${M} instead. Access your site at http://${D}:${M}`)}else M=T,S.usedPorts.add(M),N("setup",`Using standard ${T===443?"HTTPS":"HTTP"} port ${T} for ${D}`,B);await D_(R,D,M,K,Y,V,B,Q,X)}catch(T){N("setup",`Setup failed: ${T}`,B),J.error(`Failed to setup reverse proxy: ${T.message}`),l({domains:[D],hosts:typeof $==="boolean"?$:$?.hosts,certs:typeof $==="boolean"?$:$?.certs,verbose:B,vitePluginUsage:V})}}function bR(_,R=80,D=443){N("redirect",`Starting HTTP redirect server on port ${R}`,_);let K=DR.createServer((Y,B)=>{let $=Y.headers.host||"",V=$.includes(":")?$.slice(0,$.indexOf(":")):$,X=D===443?V:`${V}:${D}`;N("redirect",`Redirecting request from ${$}${Y.url} to https://${X}`,_),B.writeHead(301,{Location:`https://${X}${Y.url}`}),B.end()}).listen(R);e.add(K),N("redirect","HTTP redirect server started",_)}function B_(_){let R={...o,..._};if(N("proxy",`Starting proxy with options: ${x(R)}`,R?.verbose),R.viaDaemon){if(!R.from||!R.to){J.error("viaDaemon mode requires both `from` and `to`");return}d({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((X)=>{J.error(`Failed to register with rpx daemon: ${X.message}`),z.exit(1)});return}let D=R.to||"",K=D.split(".").pop()?.toLowerCase()||"",Y=z.platform==="darwin"&&D&&!D.includes("localhost")&&!D.includes("127.0.0.1"),B=["dev","app","page","new","day","foo"],$=["test","localhost","local","example","invalid"];if(Y&&B.includes(K)&&R?.verbose)J.warn(`The .${K} TLD may not work reliably for local development`),J.info(` Google owns .${K} with HSTS preloading, which can bypass local DNS`),J.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(Y)import("./chunk-bs9e342s.js").then(({setupDevelopmentDns:X})=>{X({domains:[D],verbose:R.verbose}).then((Q)=>{if(Q)Promise.resolve().then(()=>{if(R.verbose)if($.includes(K))J.success(`DNS server started for .${K} domains`);else J.success(`DNS server started for .${K} domains (hosts file entry also added)`)});else N("dns",`Could not start DNS server - ${D} may not resolve in browser`,R.verbose)})}).catch((X)=>{N("dns",`Failed to start DNS server: ${X}`,R.verbose)});let V={from:R.from,to:R.to,cleanUrls:R.cleanUrls,https:_R(R),cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,changeOrigin:R.changeOrigin,verbose:R.verbose,regenerateUntrustedCerts:R.regenerateUntrustedCerts};N("proxy",`Server options: ${x(V)}`,R.verbose),qR(V).catch((X)=>{N("proxy",`Failed to start proxy: ${X}`,R.verbose),J.error(`Failed to start proxy: ${X.message}`),l({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 K_(_){return _?.verbose||!1}function xR(_){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 CR(_){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 D=K_(R),K=xR(R);if(N("config",`Starting with config: ${x(R,2)}`,D),N("config",`Is multi-proxy? ${"proxies"in R}`,D),N("config",`Hosts management enabled? ${K}`,D),R.viaDaemon){let I="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((F)=>({id:F.id,from:F.from,to:F.to,path:F.path,cleanUrls:F.cleanUrls??R.cleanUrls,changeOrigin:F.changeOrigin??R.changeOrigin,pathRewrites:F.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 d({proxies:I,verbose:D});return}if("proxies"in R&&Array.isArray(R.proxies)){N("servers",`Found ${R.proxies.length} proxies in config`,D);for(let G of R.proxies)if(G.start){let I=`${G.from}-${G.to}`;try{N("watch",`Starting command for ${I} with command: ${G.start.command}`,D),J.info(`Starting command for ${I}...`),await s.startProcess(I,G.start,D);let F=new URL(G.from?.startsWith("http")?G.from:`http://${G.from}`),j=F.hostname||"localhost",b=Number(F.port)||80;try{await v(j,b,D),N("watch",`Dev server is ready at ${j}:${b}`,D)}catch(dR){N("watch",`Connection check failed, but continuing with proxy setup: ${dR}`,D),J.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(F){throw N("watch",`Failed to start command for ${I}: ${F}`,D),Error(`Failed to start command for ${I}: ${F}`)}}else N("watch",`No start command for proxy ${G.from} -> ${G.to}`,D)}else if("start"in R&&R.start){N("watch","Found start command in single proxy config",D);let G=`${R.from}-${R.to}`;try{if(R.start)N("watch",`Starting command: ${R.start.command}`,D),await s.startProcess(G,R.start,D);let I=new URL(R.from?.startsWith("http")?R.from:`http://${R.from}`),F=I.hostname||"localhost",j=Number(I.port)||80;try{await v(F,j,D),N("watch",`Dev server is ready at ${F}:${j}`,D)}catch(b){N("watch",`Connection check failed, but continuing with proxy setup: ${b}`,D),J.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(I){throw N("watch",`Failed to run start command: ${I}`,D),Error(`Failed to run start command: ${I}`)}}else N("watch","No start command found in config",D);let Y="proxies"in R&&Array.isArray(R.proxies)?R.proxies[0]?.to:("to"in R)?R.to:"rpx.localhost";if(z.platform!=="win32"&&(R.https||K)){if(!h())try{N("sudo","Pre-acquiring sudo credentials for privileged operations",D),oR("sudo -v",{stdio:"inherit"})}catch{N("sudo","Could not pre-acquire sudo credentials",D)}}let B=[];if(R.productionCerts){if(B=await ER(R.productionCerts,D),B.length>0)N("ssl",`Using ${B.length} production SNI cert(s): ${B.map((G)=>G.serverName).join(", ")}`,D)}if(R.https){let G=B.length>0?null:await f(R);if(!G&&B.length===0){if(N("ssl",`No valid or trusted certificates found for ${Y}, generating new ones`,R.verbose),await RR(R),G=await f(R),!G)throw Error(`Failed to load SSL certificates after generation for ${Y}`)}else N("ssl",`Using existing and trusted certificates for ${Y}`,R.verbose);R._cachedSSLConfig=G}let $="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((G)=>({...G,https:R.https,cleanup:R.cleanup,cleanUrls:G.cleanUrls??("cleanUrls"in R?R.cleanUrls:!1),vitePluginUsage:R.vitePluginUsage,changeOrigin:G.changeOrigin??R.changeOrigin,verbose:D,_cachedSSLConfig:R._cachedSSLConfig})):[{from:"from"in R?R.from:"localhost:5173",to:"to"in R?R.to:"rpx.localhost",cleanUrls:"cleanUrls"in R?R.cleanUrls:!1,https:R.https,cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,start:"start"in R?R.start:void 0,changeOrigin:R.changeOrigin,verbose:D,_cachedSSLConfig:R._cachedSSLConfig}],V=$.map((G)=>G.to||"rpx.localhost"),X=B.length>0?B:R._cachedSSLConfig??null,Q=V.filter((G)=>G&&!G.includes("localhost")&&!G.includes("127.0.0.1")),Z=["dev","app","page","new","day","foo"],A=["test","localhost","local","example","invalid"],W=[...new Set(Q.map((G)=>G.split(".").pop()?.toLowerCase()))],S=W.filter((G)=>!!G&&Z.includes(G));if(S.length>0&&D)J.warn(`The following TLDs may not work reliably for local development: ${S.map((G)=>`.${G}`).join(", ")}`),J.info(" These TLDs have HSTS preloading which can bypass local DNS"),J.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(K&&z.platform==="darwin"&&Q.length>0){let{setupDevelopmentDns:G}=await import("./chunk-bs9e342s.js");if(await G({domains:Q,verbose:D})){if(D)if(W.every((j)=>!!j&&A.includes(j)))J.success(`DNS server started for ${W.map((j)=>`.${j}`).join(", ")} domains`);else J.success(`DNS server started for ${W.map((j)=>`.${j}`).join(", ")} domains (hosts file entries also added)`)}else N("dns","Could not start DNS server - custom domains may not resolve",D)}let O=async()=>{N("cleanup","Starting cleanup handler",R.verbose);try{let{tearDownDevelopmentDns:G}=await import("./chunk-bs9e342s.js");await G({verbose:R.verbose})}catch(G){N("cleanup",`Error stopping DNS server: ${G}`,R.verbose)}try{await s.stopAll(R.verbose)}catch(G){N("cleanup",`Error stopping processes: ${G}`,R.verbose)}await l({domains:V,hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose||!1})};z.on("SIGINT",O),z.on("SIGTERM",O);let T=R.singlePortMode===!0,E=R.httpsPort??443,M=R.httpPort??80,L=R.originGuard?VR(R.originGuard):null,P=!!X&&($.length>1||T),aR=!X&&T&&$.length>0;if(P&&X){N("proxies",`Creating shared HTTPS server for ${$.length} domains on port ${E}`,D);let G=await uR($,K,D);if(!await q(M,"0.0.0.0",D))bR(D,M,E);if(await q(E,"0.0.0.0",D)){if(N("proxies",`Port ${E} is already in use, cannot start shared proxy`,D),D)J.warn(`Port ${E} is in use. Shared HTTPS proxy cannot start.`);return}if(!zR({routeEntries:G,listenPort:E,sslConfig:X,originGuard:L,verbose:D})){J.error(`Shared HTTPS proxy failed to bind :${E}; not exiting`);return}}else if(aR){N("proxies",`Creating shared HTTP server for ${$.length} domains on port ${M}`,D);let G=await uR($,K,D);if(await q(M,"0.0.0.0",D)){if(N("proxies",`Port ${M} is already in use, cannot start shared proxy`,D),D)J.warn(`Port ${M} is in use. Shared HTTP proxy cannot start.`);return}if(!zR({routeEntries:G,listenPort:M,sslConfig:null,originGuard:L,verbose:D})){J.error(`Shared HTTP proxy failed to bind :${M}; not exiting`);return}}else for(let G of $)try{let I=G.to||"rpx.localhost";N("proxy",`Starting proxy for ${I} with SSL config: ${!!X}`,G.verbose),await qR({from:G.from||"localhost:5173",to:I,cleanUrls:G.cleanUrls||!1,https:G.https||!1,cleanup:G.cleanup||!1,vitePluginUsage:G.vitePluginUsage||!1,verbose:G.verbose||!1,_cachedSSLConfig:R._cachedSSLConfig,changeOrigin:G.changeOrigin||!1})}catch(I){N("proxies",`Failed to start proxy for ${G.to}: ${I}`,G.verbose),J.error(`Failed to start proxy for ${G.to}:`,I)}}async function uR(_,R,D){let K=[],Y=new Set;for(let B of _){let $=B.to||"rpx.localhost",V=B.cleanUrls||!1,X=B.path,Q=HR(X);if(B.static)K.push({host:$,path:X,route:{static:MR(B.static,V),cleanUrls:V,basePath:Q}}),N("proxies",`Route: ${$}${X??""} → static ${typeof B.static==="string"?B.static:B.static.dir}`,D);else{let Z=new URL(B.from?.startsWith("http")?B.from:`http://${B.from}`);K.push({host:$,path:X,route:{sourceHost:Z.host,cleanUrls:V,changeOrigin:B.changeOrigin||!1,pathRewrites:B.pathRewrites,basePath:Q}}),N("proxies",`Route: ${$}${X??""} → ${Z.host}`,D)}if(Y.has($))continue;if(Y.add($),R&&!jR($)&&!$.includes("localhost")&&!$.includes("127.0.0.1"))try{if(!(await y([$],D))[0])await U([$],D)}catch{N("hosts",`Could not add hosts entry for ${$}`,D)}}return K}function zR(_){let{routeEntries:R,listenPort:D,sslConfig:K,originGuard:Y,verbose:B}=_,$=kR(R),V=FR((Z,A)=>wR($,Z,A),B),X=Y?(Z,A)=>Y(Z)??V(Z,A):V,Q=TR(B);try{let Z=Bun.serve({port:D,hostname:"0.0.0.0",reusePort:mR(),...K?{tls:Array.isArray(K)?K.map((A)=>({serverName:A.serverName,key:A.key,cert:A.cert})):{key:K.key,cert:K.cert,ca:K.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(A,W){return X(A,W)},websocket:Q,error(A){return N("server",`Shared proxy server error: ${A}`,B),new Response(`Server Error: ${A.message}`,{status:500})}});return e.add(Z),N("proxies",`Shared ${K?"HTTPS":"HTTP"} proxy listening on port ${D} for ${$.size} domains`,B),Z}catch(Z){return N("proxies",`Failed to start shared proxy: ${Z}`,B),console.error("Failed to start shared proxy:",Z),null}}function Y_(_){if(_?.vitePluginUsage||!_?.verbose)return;if(console.log(""),console.log(` ${k.green(k.bold("rpx"))} ${k.green(`v${R_}`)}`),console.log(` ${k.green("➜")} ${k.dim(_?.from??"")} ${k.dim("➜")} ${k.cyan(_?.ssl?`https://${_?.to}`:`http://${_?.to}`)}`),_?.listenPort!==(_?.ssl?443:80))console.log(` ${k.green("➜")} Listening on port ${_?.listenPort}`);if(_?.cleanUrls)console.log(` ${k.green("➜")} Clean URLs enabled`)}var m2=CR;export{KR as writeEntry,n_ as watchRegistry,Q_ as verifyHttpsChain,j_ as trustRootCaForBrowsers,VD as tearDownDevelopmentDns,QD as syncDevelopmentDnsFromRegistry,c_ as stripBasePath,BD as stopDnsServer,HD as stopDaemon,qR as startServer,B_ as startProxy,CR as startProxies,ND as startDnsServer,mR as shouldReusePort,XD as setupResolver,JD as setupDevelopmentDns,v_ as serverNameFromCertFilename,P_ as serveStaticFile,x as safeStringify,O_ as safeRelativePath,t2 as safeDeleteFile,d as runViaDaemon,TD as runDaemon,YD as resolverFilePath,o_ as resolverBasenamesForDomains,e_ as resolverBasenameForDomain,MR as resolveStaticRoute,L_ as resolveStaticFile,r2 as resolvePathRewrite,WD as removeResolver,GD as removeLegacyTldResolvers,JR as removeHosts,YR as removeEntry,FD as releaseDaemonLock,l2 as redactSensitive,ZD as reconcileStaleDevelopmentDns,kD as reconcileDevelopmentDnsOnIdle,g_ as readEntry,zD as readDaemonPid,X_ as readCertSha256Fingerprint,G_ as readCertCommonName,p_ as readAll,M_ as pruneStaleRootCas,iR as portManager,u_ as pathPrefixMatches,V_ as parseSha256HashesFromSecurityListing,$_ as normalizeSha256Fingerprint,HR as normalizePathPrefix,s_ as normalizeDevDomain,QR as matchesWildcard,l_ as matchesAllowedSuffix,wR as matchHostRoute,m_ as matchHostList,h_ as matchHost,x_ as loadSSLConfig,I_ as listCertSha256HashesByCommonName,jR as isWildcardPattern,a2 as isValidRootCA,BR as isValidId,i2 as isSingleProxyOptions,n2 as isSingleProxyConfig,F_ as isRootCaTrustedForSsl,T_ as isRootCaFingerprintInKeychains,LR as isProcessElevated,q as isPortInUse,d_ as isPidAlive,p2 as isMultiProxyOptions,g2 as isMultiProxyConfig,b_ as isLikelyHostname,KD as isDnsServerRunning,ID as isDaemonRunning,y_ as isCertTrusted,_R as httpsConfig,h as getSudoPassword,q_ as getSharedDaemonCertPaths,E_ as getRootCAPaths,NR as getRegistryDir,d2 as getPrimaryDomain,z_ as getMacosTrustKeychains,S_ as getMacosLoginKeychainPath,AD as getDaemonRpxDir,SD as getDaemonPidPath,RR as generateCertificate,i_ as gcStaleEntries,C_ as forceTrustCertificate,hR as findAvailablePort,b2 as extractHostname,v2 as execSudoSync,$R as ensureDaemonRunning,k_ as devSslToSniEntries,RD as devDomainsFromHosts,fR as deriveIdFromTarget,jD as defaultDaemonSpawnCommand,o as defaultConfig,m2 as default,N as debugLog,TR as createProxyWebSocketHandler,FR as createProxyFetchHandler,VR as createOriginGuard,f_ as contentTypeFor,$D as contentLooksLikeRpxResolver,o as config,k as colors,U_ as clearSslConfigCache,IR as cleanupCertificates,l as cleanup,y as checkHosts,f as checkExistingCertificates,J_ as certIncludesSanHostnames,ER as buildSniTlsConfig,w_ as buildRegistryTlsProxyOptions,kR as buildHostRoutes,U as addHosts,MD as acquireDaemonLock,H_ as SHARED_DEV_HOST_CERT_PATH,A_ as RPX_ROOT_CA_COMMON_NAME,DD as RPX_RESOLVER_MARKER,a_ as OnDemandCertManager,Z_ as MACOS_SYSTEM_KEYCHAIN,W_ as MACOS_CA_TRUST_FLAGS,t_ as LEGACY_TLD_RESOLVER_LABELS,m as DefaultPortManager,r_ as DNS_STATE_VERSION,_D as DNS_PORT};
@@ -41,10 +41,15 @@ declare class Conn {
41
41
  idleSince: number;
42
42
  bodyQueue: Uint8Array[] | null;
43
43
  bodyRemaining: number;
44
+ queuedBytes: number;
45
+ streamingBody: boolean;
46
+ lastActivityAt: number;
44
47
  drainWaiter: (() => void) | null;
45
48
  writeAll(bytes: Uint8Array): Promise<void>;
46
49
  wakeDrain(): void;
47
50
  push(chunk: Uint8Array): void;
51
+ resumeIfDrained(): void;
52
+ clearStreaming(): void;
48
53
  markClosed(): void;
49
54
  markTimedOut(): void;
50
55
  waitForData(seen: number): Promise<void>;
package/dist/start.d.ts CHANGED
@@ -1,13 +1,36 @@
1
- import * as http from 'node:http';
2
- import * as http2 from 'node:http2';
3
- import * as https from 'node:https';
4
- import type { CleanupOptions, ProxyOption, ProxyOptions, ProxySetupOptions, SingleProxyConfig } from './types';
1
+ import { createOriginGuard } from './origin-guard';
2
+ import * as path from 'node:path';
3
+ import type { CleanupOptions, ProxyOption, ProxyOptions, ProxySetupOptions, SingleProxyConfig, SSLConfig } from './types';
4
+ import type { ProxyRoute } from './proxy-handler';
5
+ import type { SniTlsEntry } from './sni';
5
6
  export declare function cleanup(options?: CleanupOptions): Promise<void>;
6
7
  export declare function startServer(options: SingleProxyConfig): Promise<void>;
7
8
  export declare function setupProxy(options: ProxySetupOptions): Promise<void>;
8
- export declare function startHttpRedirectServer(verbose?: boolean): void;
9
+ export declare function startHttpRedirectServer(verbose?: boolean, httpPort?: number, httpsPort?: number): void;
9
10
  export declare function startProxy(options: ProxyOption): void;
10
11
  export declare function startProxies(options?: ProxyOptions): Promise<void>;
11
- declare type AnyServerType = http.Server | https.Server | http2.Http2SecureServer;
12
- declare type AnyIncomingMessage = http.IncomingMessage | http2.Http2ServerRequest;
13
- declare type AnyServerResponse = http.ServerResponse | http2.Http2ServerResponse;
12
+ /**
13
+ * Build the `(host, path, route)` entries for a shared single-port listener from
14
+ * the resolved per-proxy options, and ensure an `/etc/hosts` entry exists for
15
+ * each non-localhost domain (once per domain). Several proxies can share one
16
+ * domain on different paths (e.g. `/api` → app, `/docs` → static dir, `/` →
17
+ * public) — `buildHostRoutes` groups + longest-prefix-sorts them later. Shared
18
+ * by the single-port HTTPS and HTTP paths so routing is identical regardless of
19
+ * whether TLS is terminated.
20
+ */
21
+ export declare function collectRouteEntries(proxyOptions: ProxyOption[], hostsEnabled: boolean, verbose: boolean): Promise<Array<{ host: string, path?: string, route: ProxyRoute }>>;
22
+ /**
23
+ * Create a single shared `Bun.serve` listener that routes every request by
24
+ * `Host` header (and path) to the right upstream. When `sslConfig` is provided
25
+ * the listener terminates TLS; otherwise it serves plain HTTP (single-port HTTP
26
+ * mode). Registers the server for cleanup and returns it, or `null` if
27
+ * `Bun.serve` threw (e.g. the port could not be bound).
28
+ */
29
+ export declare function createSharedProxyServer(opts: {
30
+ routeEntries: Array<{ host: string, path?: string, route: ProxyRoute }>
31
+ listenPort: number
32
+ sslConfig: SharedTlsConfig | null
33
+ originGuard: ReturnType<typeof createOriginGuard> | null
34
+ verbose: boolean
35
+ }): ReturnType<typeof Bun.serve> | null;
36
+ declare type SharedTlsConfig = SSLConfig | SniTlsEntry[];
package/dist/types.d.ts CHANGED
@@ -89,6 +89,9 @@ export declare interface SharedProxyConfig {
89
89
  cleanUrls: boolean
90
90
  changeOrigin?: boolean
91
91
  regenerateUntrustedCerts?: boolean
92
+ singlePortMode?: boolean
93
+ httpPort?: number
94
+ httpsPort?: number
92
95
  viaDaemon?: boolean
93
96
  hostsManagement?: boolean
94
97
  productionCerts?: ProductionTlsConfig
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/rpx",
3
3
  "type": "module",
4
- "version": "0.11.19",
4
+ "version": "0.11.20",
5
5
  "description": "A modern and smart reverse proxy.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
@@ -27,11 +27,11 @@
27
27
  "exports": {
28
28
  ".": {
29
29
  "types": "./dist/index.d.ts",
30
- "bun": "./src/index.ts",
31
- "import": "./dist/src/index.js"
30
+ "bun": "./dist/index.js",
31
+ "import": "./dist/index.js"
32
32
  }
33
33
  },
34
- "module": "./dist/src/index.js",
34
+ "module": "./dist/index.js",
35
35
  "types": "./dist/index.d.ts",
36
36
  "bin": {
37
37
  "rpx": "./dist/bin/cli.js",
@@ -39,8 +39,7 @@
39
39
  },
40
40
  "files": [
41
41
  "README.md",
42
- "dist",
43
- "src"
42
+ "dist"
44
43
  ],
45
44
  "scripts": {
46
45
  "build": "bun build.ts && bun build ./bin/cli.ts --compile --minify --outfile bin/rpx",
@@ -73,7 +72,7 @@
73
72
  },
74
73
  "dependencies": {
75
74
  "@stacksjs/clapp": "^0.2.10",
76
- "@stacksjs/tlsx": "^0.13.7"
75
+ "@stacksjs/tlsx": "^0.13.9"
77
76
  },
78
77
  "devDependencies": {
79
78
  "bunfig": "^0.15.6",