@stacksjs/rpx 0.11.20 → 0.11.21

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/daemon.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { OnDemandTlsConfig, ProductionTlsConfig, TlsOption } from './types';
1
+ import type { OnDemandSitesConfig, OnDemandTlsConfig, ProductionTlsConfig, TlsOption } from './types';
2
+ import type { SiteSnapshot } from './site-supervisor';
2
3
  export declare function getDaemonRpxDir(): string;
3
4
  export declare function getDaemonPidPath(rpxDir?: string): string;
4
5
  /**
@@ -71,6 +72,7 @@ export declare interface DaemonOptions {
71
72
  https?: TlsOption
72
73
  productionCerts?: ProductionTlsConfig
73
74
  onDemandTls?: OnDemandTlsConfig
75
+ onDemandSites?: OnDemandSitesConfig
74
76
  gcIntervalMs?: number
75
77
  workers?: number
76
78
  }
@@ -81,6 +83,7 @@ export declare interface DaemonHandle {
81
83
  httpPort: number
82
84
  pidPath: string
83
85
  ensureCert: (host: string) => Promise<boolean>
86
+ listSites: () => SiteSnapshot[]
84
87
  }
85
88
  // ───────────────────────── cluster: coordinator + workers ─────────────────────
86
89
  declare interface WorkerCtx {
package/dist/index.d.ts CHANGED
@@ -9,12 +9,30 @@ export type {
9
9
  StopDaemonOptions,
10
10
  StopDaemonResult,
11
11
  } from './daemon';
12
- export type { GetRoute, ProxyFetchHandler, ProxyRoute, ProxyServer } from './proxy-handler';
12
+ export type { GetRoute, NoRouteOutcome, OnNoRoute, ProxyFetchHandler, ProxyRoute, ProxyServer } from './proxy-handler';
13
+ export type { RedirectRouteConfig, ResolvedRedirect } from './redirect';
13
14
  export type { OriginGuard, OriginGuardOptions } from './origin-guard';
15
+ export type { ResolvedAuth } from './auth';
14
16
  export type { HostRoutes, PathRoute } from './host-routes';
15
17
  export type { ResolvedStaticRoute, StaticResolution } from './static-files';
16
18
  export type { SniTlsEntry } from './sni';
17
19
  export type { CertIssuer, OnDemandCertManagerOptions } from './on-demand';
20
+ export type {
21
+ ResolvedSite,
22
+ ResolverProbes,
23
+ SiteDetector,
24
+ SiteManifest,
25
+ SitePreset,
26
+ SiteResolver,
27
+ SiteResolverDeps,
28
+ } from './site-resolver';
29
+ export type {
30
+ SiteLauncher,
31
+ SiteProcessHandle,
32
+ SiteRequestStatus,
33
+ SiteSnapshot,
34
+ SiteSupervisorOptions,
35
+ } from './site-supervisor';
18
36
  export type { DaemonRunnerOptions, DaemonRunnerProxy } from './daemon-runner';
19
37
  export { colors } from './colors';
20
38
  export { config, config as defaultConfig } from './config';
@@ -108,8 +126,11 @@ export {
108
126
  stopDaemon,
109
127
  } from './daemon';
110
128
  export { createProxyFetchHandler, createProxyWebSocketHandler, stripBasePath } from './proxy-handler';
129
+ export { buildRedirectLocation, resolveRedirect } from './redirect';
130
+ export { ACME_CHALLENGE_PREFIX, readAcmeChallenge } from './acme-challenge';
111
131
  export { isWildcardPattern, matchesWildcard, matchHost } from './host-match';
112
132
  export { createOriginGuard } from './origin-guard';
133
+ export { enforceBasicAuth, parseHtpasswd, resolveAuth } from './auth';
113
134
  export {
114
135
  buildHostRoutes,
115
136
  matchHostList,
@@ -126,6 +147,17 @@ export {
126
147
  } from './static-files';
127
148
  export { buildSniTlsConfig, serverNameFromCertFilename } from './sni';
128
149
  export { isLikelyHostname, matchesAllowedSuffix, OnDemandCertManager } from './on-demand';
150
+ export {
151
+ createSiteResolver,
152
+ detectProjectPreset,
153
+ expandHome,
154
+ listDiscoverableSites,
155
+ projectNameFromHost,
156
+ readSiteManifest,
157
+ siteIdForHost,
158
+ } from './site-resolver';
159
+ export { SiteSupervisor } from './site-supervisor';
160
+ export { escapeHtml, renderFailedPage, renderStartingPage } from './site-splash';
129
161
  export { deriveIdFromTarget, runViaDaemon } from './daemon-runner';
130
162
  export { cleanup } from './start';
131
163
  export { startProxies, startProxy, startServer } from './start';
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
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)=>`
1
+ import{$ as qR,$a as vD,A as US,Aa as QD,B as U,Ba as VD,C as o,Ca as XD,D as FR,Da as ZD,E as PS,Ea as WD,F as OS,Fa as zD,G as RR,Ga as ID,H as LS,Ha as FD,I as MR,Ia as MD,J as cS,Ja as xD,K as xR,Ka as TD,L as mS,La as jD,M as vS,N as hS,Na as HD,O as uS,Oa as kD,P as bS,Pa as wD,Q as TR,Qa as ED,R as jR,Ra as qD,S as HR,Sa as CD,T as GR,Ta as yD,U as lS,Ua as fD,V as kR,Va as UD,W as aS,Wa as PD,X as wR,Xa as OD,Y as pS,Ya as LD,Z as ER,Za as cD,_ as dS,_a as mD,a as G,aa as gS,ab as hD,b as s,ba as iS,bb as uD,c as $S,ca as nS,cb as KR,d as GS,da as rS,db as bD,e as JS,ea as tS,eb as lD,f as QS,fa as sS,g as VS,ga as eS,h as XS,ha as oS,i as ZS,ia as RD,j as WS,ja as SD,k as zS,ka as C,l as IS,la as DD,m as FS,ma as CR,n as MS,na as _D,o as xS,oa as DR,p as TS,pa as _R,q as jS,qa as ND,r as HS,ra as NR,s as kS,sa as BR,t as wS,ta as BD,u as ES,ua as KD,v as qS,va as AD,w as CS,wa as YD,x as yS,xa as $D,y as fS,ya as GD,z as e,za as JD}from"./chunk-qs36t2rf.js";import{fb as zR,gb as m,hb as mR,ib as QN,jb as _,kb as lR,lb as VN,mb as E,nb as XN,ob as ZN,pb as WN,qb as zN,rb as IN,sb as FN,tb as MN,ub as xN,vb as TN}from"./chunk-cqkz06bg.js";import{execSync as SS}from"node:child_process";import*as SR from"node:http";import*as aR from"node:net";import*as z from"node:process";var l=(S,R)=>(D)=>`\x1B[${S}m${D}\x1B[${R}m`,H={bold:l(1,22),dim:l(2,22),green:l(32,39),cyan:l(36,39)};import*as PR from"node:fs";import*as OR from"node:path";import*as k from"node:process";function LR(S,R){let B=(R&&R!=="/"?`${S}${R}`:S).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return B.length>0?B:"rpx"}async function a(S){if(S.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let R=S.verbose??!1,D=S.registryDir,B=new Set,K=S.proxies.map((X)=>{let W=X.id??LR(X.to,X.path);if(!_R(W))throw Error(`invalid registry id "${W}" derived from to="${X.to}"`);if(B.has(W))throw Error(`duplicate registry id "${W}" — set an explicit \`id\` on one of the proxies`);return B.add(W),{...X,id:W}}),N=new Date().toISOString();for(let X of K)await NR({id:X.id,from:X.from,to:X.to,path:X.path,pid:S.persistent?void 0:k.pid,cwd:k.cwd(),createdAt:N,cleanUrls:X.cleanUrls,changeOrigin:X.changeOrigin,pathRewrites:X.pathRewrites,static:X.static},D,R);let A=await KR({rpxDir:S.rpxDir,verbose:R,spawnCommand:S.spawnCommand,startupTimeoutMs:S.startupTimeoutMs,spawnEnv:S.spawnEnv});for(let X of K){let W=X.static?`static ${typeof X.static==="string"?X.static:X.static.dir}`:X.from;G.success(`https://${X.to} → ${W}`)}if(G.info(`(via rpx daemon pid=${A.pid}; \`rpx daemon:status\` to inspect)`),S.detached)return;let V=!1,Y=D??DR(),J=K.map((X)=>X.id),Q=async()=>{if(V)return;V=!0;for(let X of J)await BR(X,D,R).catch((W)=>{_("runner",`removeEntry(${X}) failed: ${W}`,R)})},Z=(X)=>{_("runner",`received ${X}, unregistering ${J.length} entries`,R),Q().finally(()=>k.exit(0))};k.once("SIGINT",Z),k.once("SIGTERM",Z),k.once("exit",()=>{if(V)return;for(let X of J)try{PR.unlinkSync(OR.join(Y,`${X}.json`))}catch{}}),await new Promise(()=>{})}import{exec as nR}from"node:child_process";import q from"node:fs";import vR from"node:os";import YR from"node:path";import*as v from"node:process";import{promisify as rR}from"node:util";var c=rR(nR);function cR(S){let R=S.trim().toLowerCase();return R==="localhost"||R.endsWith(".localhost")||R.endsWith(".localhost.")}var j=v.platform==="win32"?YR.join(v.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",AR=!1;async function p(S){if(v.platform==="win32")throw Error("Administrator privileges required on Windows");if(mR()){let{stdout:B}=await c(S);return B}let R=m(),D=S.replace(/'/g,"'\\''");try{if(R){let{stdout:B}=await c(`echo '${R}' | sudo -S sh -c '${D}' 2>/dev/null`);return AR=!0,B}if(AR)try{let{stdout:B}=await c(`sudo -n sh -c '${D}'`);return B}catch(B){_("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:B}=await c(`sudo -n sh -c '${D}'`);return AR=!0,B}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(B){throw Error(`Failed to execute sudo command: ${B.message}`)}}async function y(S,R){let D=S.filter((K)=>!cR(K)),B=S.filter((K)=>cR(K));if(B.length>0)_("hosts",`Skipping /etc/hosts for loopback dev names: ${B.join(", ")}`,R);if(D.length===0)return;_("hosts",`Adding hosts: ${D.join(", ")}`,R),_("hosts",`Using hosts file at: ${j}`,R);try{let K;try{K=await q.promises.readFile(j,"utf-8")}catch{_("hosts","Reading hosts file requires elevated permissions, using sudo",R);try{K=await p(`cat "${j}"`)}catch(Y){throw console.log(" Could not read hosts file — skipping hosts setup"),_("hosts",`sudo read also failed: ${Y}`,R),Error(`Cannot read hosts file: ${Y}`)}}let N=D.filter((Y)=>{let J=`127.0.0.1 ${Y}`,Q=`::1 ${Y}`;return!K.includes(J)&&!K.includes(Q)});if(N.length===0){_("hosts","All hosts already exist in hosts file",R);return}let A=N.map((Y)=>`
2
2
  # Added by rpx
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(`
3
+ 127.0.0.1 ${Y}
4
+ ::1 ${Y}`).join(`
5
+ `),V=YR.join(vR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await q.promises.writeFile(V,K+A,"utf8"),await p(`cat "${V}" | tee "${j}" > /dev/null`),console.log(` Hosts updated: ${N.join(", ")}`)}catch(Y){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),N.forEach((J)=>{console.log(` 127.0.0.1 ${J}`),console.log(` ::1 ${J}`)}),console.log(` Or run: sudo nano ${j}`)}finally{try{await q.promises.unlink(V)}catch{}}}catch(K){_("hosts",`Failed to manage hosts file: ${K.message}`,R)}}async function $R(S,R){_("hosts",`Removing hosts: ${S.join(", ")}`,R);try{let D;try{D=await q.promises.readFile(j,"utf-8")}catch{_("hosts","Reading hosts file requires elevated permissions, using sudo",R);try{D=await p(`cat "${j}"`)}catch(Y){throw _("hosts",`sudo read also failed: ${Y}`,R),Error(`Cannot read hosts file: ${Y}`)}}let B=D.split(`
6
+ `),K=!1,N=B.filter((Y)=>{if(S.some((Q)=>Y.includes(` ${Q}`)&&(Y.includes("127.0.0.1")||Y.includes("::1"))))return K=!0,!1;if(Y.trim()==="# Added by rpx")return K=!0,!1;return!0});if(!K){_("hosts","No matching hosts found to remove",R);return}while(N[N.length-1]?.trim()==="")N.pop();let A=`${N.join(`
7
7
  `)}
8
- `,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};
8
+ `,V=YR.join(vR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await q.promises.writeFile(V,A,"utf8"),await p(`cat "${V}" | tee "${j}" > /dev/null`),_("hosts","Hosts removed successfully",R)}catch(Y){_("hosts","Could not clean up hosts file automatically",R)}finally{try{await q.promises.unlink(V)}catch(Y){_("hosts",`Failed to remove temporary file: ${Y}`,R)}}}catch(D){_("hosts",`Failed to clean up hosts file: ${D.message}`,R)}}async function f(S,R){_("hosts",`Checking hosts: ${S}`,R);let D;try{D=await q.promises.readFile(j,"utf-8")}catch(B){_("hosts",`Error reading hosts file: ${B}`,R);try{let K=m(),N;if(K)N=`echo '${K}' | sudo -S cat "${j}" 2>/dev/null`;else N=`sudo -n cat "${j}" 2>/dev/null || cat "${j}" 2>/dev/null || echo ""`;let{stdout:A}=await c(N);D=A}catch(K){return _("hosts",`Cannot read hosts file, assuming entries don't exist: ${K}`,R),S.map(()=>!1)}}return S.map((B)=>{let K=`127.0.0.1 ${B}`,N=`::1 ${B}`;return D.includes(K)||D.includes(N)})}import{spawn as tR}from"node:child_process";import*as d from"node:process";class g{processes=new Map;isShuttingDown=!1;async startProcess(S,R,D){if(this.processes.has(S)){_("start",`Process ${S} is already running`,D);return}let[B,...K]=R.command.split(" "),N=R.cwd||d.cwd();_("start",`Starting process ${S}:`,D),_("start",` Command: ${B} ${K.join(" ")}`,D),_("start",` Working directory: ${N}`,D),_("start",` Environment variables: ${E(R.env)}`,D);let A=tR(B,K,{cwd:N,env:{...d.env,...R.env},shell:!0,stdio:"inherit"});return this.processes.set(S,{command:R.command,cwd:N,process:A,env:R.env}),new Promise((V,Y)=>{if(A.on("error",(J)=>{if(!this.isShuttingDown)_("start",`Process ${S} failed to start: ${J}`,D),this.processes.delete(S),Y(J)}),A.on("exit",(J)=>{if(!this.isShuttingDown&&J!==null&&J!==0)_("start",`Process ${S} exited with code ${J}; leaving the proxy running`,D),this.processes.delete(S),Y(Error(`Process ${S} exited with code ${J}`))}),D)A.stdout?.on("data",(J)=>{_("process",`[${S}] ${J.toString().trim()}`,!0)}),A.stderr?.on("data",(J)=>{_("process",`[${S}] ERR: ${J.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&A.killed)this.processes.delete(S),Y(Error(`Process ${S} was killed during startup`));else _("start",`Process ${S} started successfully`,D),V()},1000)})}async stopProcess(S,R){let D=this.processes.get(S);if(!D?.process){_("start",`No process found for ${S}`,R);return}return _("start",`Stopping process ${S}`,R),new Promise((B)=>{if(!D.process){B();return}D.process.once("exit",()=>{this.processes.delete(S),_("start",`Process ${S} stopped`,R),B()});try{D.process.kill("SIGTERM"),setTimeout(()=>{if(D.process){_("start",`Force killing process ${S}`,R);try{D.process.kill("SIGKILL")}catch(K){}}},3000)}catch(K){_("start",`Error stopping process ${S}: ${K}`,R),this.processes.delete(S),B()}})}async stopAll(S){if(this.isShuttingDown){_("start","Already shutting down, skipping duplicate stopAll call",S);return}this.isShuttingDown=!0,_("start","Stopping all processes",S);let R=Array.from(this.processes.keys()).map((D)=>this.stopProcess(D,S).catch((B)=>{G.error(`Failed to stop process ${D}:`,B)}));await Promise.allSettled(R),this.processes.clear(),this.isShuttingDown=!1}isRunning(S){let R=this.processes.get(S);return!!R?.process&&!R.process.killed}}var B_=new g;import{timingSafeEqual as sR}from"node:crypto";function eR(S,R){if(S==null)return!1;let D=Buffer.from(S),B=Buffer.from(R);if(D.length!==B.length)return!1;return sR(D,B)}function i(S){return S.toLowerCase().replace(/\.$/,"")}var oR=["/.well-known/acme-challenge/"];function RS(S){let R=S.headers.get("host");if(R)return i(R.split(":")[0]);try{return i(new URL(S.url).hostname)}catch{return""}}function JR(S){let R=S.header.toLowerCase(),D=new Set,B=[];for(let Y of S.hosts){let J=i(Y);if(J.startsWith("*."))B.push(J);else D.add(J)}let K=S.exemptPaths??oR,N=S.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
9
+ `,A=(Y)=>{let J=i(Y);return D.has(J)||B.some((Q)=>GR(J,Q))},V=(Y)=>{let J=RS(Y);if(!A(J))return;let Q="/";try{Q=new URL(Y.url).pathname}catch{}if(K.some((Z)=>Q.startsWith(Z)))return;if(eR(Y.headers.get(R),S.value))return;return new Response(N,{status:403,headers:{"content-type":"text/plain"}})};return V.protects=A,V}import*as hR from"node:fs";import*as uR from"node:path";var QR="/.well-known/acme-challenge/";function VR(S,R){if(!S||!R.startsWith(QR))return null;let D=R.slice(QR.length);if(!D||!/^[A-Za-z0-9_-]+$/.test(D))return null;try{return hR.readFileSync(uR.join(S,D),"utf8")}catch{return null}}var r=new g,DS="0.12.0",_S=new CR("0.0.0.0"),t=new Set,XR=!1,n=null,ZR=null;async function u(S){if(XR)return _("cleanup","Cleanup already in progress, skipping",S?.verbose),ZR||Promise.resolve();XR=!0,_("cleanup","Starting cleanup process",S?.verbose),ZR=new Promise((R)=>{n=R});try{await r.stopAll(S?.verbose),G.info("Shutting down proxy servers...");let R=[],D=Array.from(t).map((B)=>new Promise((K)=>{let N=B;try{if(typeof N.stop==="function")N.stop(!0),_("cleanup","Bun server stopped",S?.verbose),K();else if(typeof N.close==="function")N.close(()=>{_("cleanup","Server closed successfully",S?.verbose),K()});else K()}catch(A){_("cleanup",`Error stopping server: ${A}`,S?.verbose),K()}}));if(R.push(...D),t.clear(),S?.hosts&&S.domains?.length){_("cleanup","Cleaning up hosts file entries",S?.verbose),_("cleanup",`Original domains for cleanup: ${JSON.stringify(S.domains)}`,S?.verbose);let B=S.domains.filter((K)=>{if(K==="test.local")return!0;return K!=="localhost"&&!K.startsWith("localhost.")&&K!=="127.0.0.1"});if(_("cleanup",`Filtered domains for cleanup: ${JSON.stringify(B)}`,S?.verbose),B.length>0)G.info("Cleaning up hosts file entries..."),R.push($R(B,S?.verbose).then(()=>{_("cleanup",`Removed hosts entries for ${B.join(", ")}`,S?.verbose)}).catch((K)=>{_("cleanup",`Failed to remove hosts entries: ${K}`,S?.verbose),G.warn(`Failed to clean up hosts file entries for ${B.join(", ")}:`,K)}))}if(S?.certs&&S.domains?.length){_("cleanup","Cleaning up SSL certificates",S?.verbose),G.info("Cleaning up SSL certificates...");let B=S.domains.map(async(K)=>{try{await FR(K,S?.verbose),_("cleanup",`Removed certificates for ${K}`,S?.verbose)}catch(N){_("cleanup",`Failed to remove certificates for ${K}: ${N}`,S?.verbose),G.warn(`Failed to clean up certificates for ${K}:`,N)}});R.push(...B)}await Promise.allSettled(R),_("cleanup","All cleanup tasks completed successfully",S?.verbose),G.success("All cleanup tasks completed successfully")}catch(R){_("cleanup",`Error during cleanup: ${R}`,S?.verbose),G.error("Error during cleanup:",R)}finally{if(n)n();n=null,XR=!1;let R=S&&"vitePluginUsage"in S&&S.vitePluginUsage===!0;if(z.env.NODE_ENV!=="test"&&z.env.BUN_ENV!=="test"&&!R)z.exit(0)}return ZR}var WR=!1;function pR(S){if(WR){_("signal",`Received second ${S} signal, forcing exit`,!0),z.exit(1);return}WR=!0,_("signal",`Received ${S} signal, initiating cleanup`,!0),u().catch((R)=>{_("signal",`Cleanup failed after ${S}: ${R}`,!0),z.exit(1)}).finally(()=>{WR=!1})}z.once("SIGINT",()=>pR("SIGINT"));z.once("SIGTERM",()=>pR("SIGTERM"));z.on("uncaughtException",(S)=>{G.error("Uncaught exception (continuing):",S)});z.on("unhandledRejection",(S)=>{G.error("Unhandled rejection (continuing):",S)});async function h(S,R,D,B=5){_("connection",`Testing connection to ${S}:${R} (retries left: ${B})`,D);let K=15000,N=Date.now();if(z.env.RPX_BYPASS_CONNECTION_TEST==="true"){_("connection",`Bypassing connection test for ${S}:${R} due to RPX_BYPASS_CONNECTION_TEST flag`,D);return}let A=()=>new Promise((V,Y)=>{let J=aR.connect({host:S,port:R,timeout:3000});J.once("connect",()=>{_("connection",`Successfully connected to ${S}:${R}`,D),J.end(),V()}),J.once("timeout",()=>{_("connection",`Connection to ${S}:${R} timed out`,D),J.destroy(),Y(Error("Connection timed out"))}),J.once("error",(Q)=>{_("connection",`Failed to connect to ${S}:${R}: ${Q}`,D),J.destroy(),Y(Q)})});try{await A()}catch(V){let Y=V;if(Date.now()-N>K){_("connection",`Connection test timed out after ${K}ms, but continuing anyway`,D),G.warn(`Connection test to ${S}:${R} timed out, but RPX will try to proceed anyway.`);return}if(Y.code==="ECONNREFUSED"&&B>0)return _("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${B} retries left)`,D),await new Promise((Q)=>setTimeout(Q,2000)),h(S,R,D,B-1);if(B>0)try{_("connection",`Trying HTTP request to ${S}:${R}`,D),await new Promise((Q,Z)=>{let X=SR.request({hostname:S,port:R,path:"/",method:"HEAD",timeout:5000},(W)=>{_("connection",`Received HTTP response with status: ${W.statusCode}`,D),Q()});X.on("error",(W)=>Z(W)),X.on("timeout",()=>{X.destroy(),Z(Error("HTTP request timed out"))}),X.end()}),_("connection",`HTTP request to ${S}:${R} succeeded`,D);return}catch(Q){return _("connection",`HTTP request to ${S}:${R} failed: ${Q}`,D),_("connection",`Retrying socket connection in 2 seconds... (${B} retries left)`,D),await new Promise((Z)=>setTimeout(Z,2000)),h(S,R,D,B-1)}let J=`Failed to connect to ${S}:${R} after ${5-B} attempts: ${Y.message}`;_("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,D),G.warn(J),G.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function yR(S){_("server",`Starting server with options: ${E(S)}`,S.verbose);let R=new URL((S.from?.startsWith("http")?S.from:`http://${S.from}`)||"localhost:5173"),D=new URL((S.to?.startsWith("http")?S.to:`http://${S.to}`)||"rpx.localhost"),B=Number.parseInt(R.port)||(R.protocol.includes("https:")?443:80),K=[D.hostname];if(fR(S)&&!D.hostname.includes("localhost")&&!D.hostname.includes("127.0.0.1")){_("hosts",`Checking if hosts file entry exists for: ${D.hostname}`,S?.verbose);try{if(!(await f(K,S.verbose))[0]){G.info(`Adding ${D.hostname} to hosts file...`),G.info("This may require sudo/administrator privileges");try{await y(K,S.verbose)}catch(V){if(G.error("Failed to add hosts entry:",V.message),G.warn("You can manually add this entry to your hosts file:"),G.warn(`127.0.0.1 ${D.hostname}`),G.warn(`::1 ${D.hostname}`),z.platform==="win32")G.warn("On Windows:"),G.warn("1. Run notepad as administrator"),G.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else G.warn("On Unix systems:"),G.warn("sudo nano /etc/hosts")}}else _("hosts",`Host entry already exists for ${D.hostname}`,S.verbose)}catch(A){G.error("Failed to check hosts file:",A.message)}}try{await h(R.hostname,B,S.verbose)}catch(A){_("server",`Connection test failed: ${A}`,S.verbose),G.error(A.message),G.warn("Continuing with proxy setup despite connection test failure..."),G.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let N=S._cachedSSLConfig||null;if(S.https)try{if(S.https===!0)S.https=o({...S,to:D.hostname});if(N=await U({...S,to:D.hostname,https:S.https}),!N){if(_("ssl",`Generating new certificates for ${D.hostname}`,S.verbose),await e({...S,from:R.toString(),to:D.hostname,https:S.https}),N=await U({...S,to:D.hostname,https:S.https}),!N)throw Error(`Failed to load SSL configuration after generating certificates for ${D.hostname}`)}}catch(A){throw _("server",`SSL setup failed: ${A}`,S.verbose),A}_("server",`Setting up reverse proxy with SSL config for ${D.hostname}`,S.verbose),await BS({...S,from:S.from||"localhost:5173",to:D.hostname,fromPort:B,sourceUrl:{hostname:R.hostname,host:R.host},ssl:N})}async function NS(S,R,D,B,K,N,A,V,Y,J){_("proxy",`Creating proxy server ${S} -> ${R} with cleanUrls: ${V}`,A);let Q=[{host:R,route:{sourceHost:B.host,cleanUrls:V||!1,changeOrigin:Y||!1,basePath:"/",auth:J}}];if(!IR({routeEntries:Q,listenPort:D,sslConfig:K,originGuard:null,verbose:A??!1}))throw Error(`Failed to start proxy server for ${R} on port ${D}`);YS({from:S,to:R,vitePluginUsage:N,listenPort:D,ssl:!!K,cleanUrls:V,verbose:A})}async function BS(S){_("setup",`Setting up reverse proxy: ${E(S)}`,S.verbose);let{from:R,to:D,sourceUrl:B,ssl:K,verbose:N,cleanup:A,vitePluginUsage:V,changeOrigin:Y,cleanUrls:J}=S,Q=80,Z=443,X="0.0.0.0",W=S.portManager||_S,P=fR(S);try{if(P&&D&&!D.includes("localhost")&&!D.includes("127.0.0.1")){if(!(await f([D],N))[0]){G.warn(`The hostname ${D} isn't in your hosts file. Adding it now...`);try{await y([D],N),G.success(`Added ${D} to your hosts file.`)}catch(L){G.error(`Failed to add ${D} to your hosts file: ${L}`),G.info(`You may need to manually add '127.0.0.1 ${D}' to your /etc/hosts file.`)}}}else if(P&&z.platform!=="darwin"&&D&&D.includes("localhost")&&!D.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await f([D],N))[0]){_("hosts",`${D} not found in hosts file, adding...`,N);try{await y([D],N)}catch(L){_("hosts",`Failed to add ${D} to hosts file: ${L}`,N)}}}if(K&&!W.usedPorts.has(Q)){if(!await C(Q,X,N))_("setup","Starting HTTP redirect server",N),dR(N),W.usedPorts.add(Q);else if(_("setup","Port 80 is in use, skipping HTTP redirect",N),N)G.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let x=K?Z:Q,w=await C(x,X,N),F;if(w){if(_("setup",`Port ${x} is already in use`,N),N)G.warn(`Port ${x} is already in use. This may be another instance of rpx or another service.`);if(x===443){if(F=await W.getNextAvailablePort(3443,!0),_("setup",`Using port ${F} instead of ${x}`,N),N)G.info(`Using port ${F} instead. Access your site at https://${D}:${F}`)}else if(F=await W.getNextAvailablePort(x+1000,!0),_("setup",`Using port ${F} instead of ${x}`,N),N)G.info(`Using port ${F} instead. Access your site at http://${D}:${F}`)}else F=x,W.usedPorts.add(F),_("setup",`Using standard ${x===443?"HTTPS":"HTTP"} port ${x} for ${D}`,N);await NS(R,D,F,B,K,V,N,J,Y,RR(S.auth))}catch(x){_("setup",`Setup failed: ${x}`,N),G.error(`Failed to setup reverse proxy: ${x.message}`),u({domains:[D],hosts:typeof A==="boolean"?A:A?.hosts,certs:typeof A==="boolean"?A:A?.certs,verbose:N,vitePluginUsage:V})}}function dR(S,R=80,D=443,B){_("redirect",`Starting HTTP redirect server on port ${R}`,S);let K=SR.createServer((N,A)=>{if(B&&N.url){let Q=N.url.split("?",1)[0],Z=VR(B,Q);if(Z!=null){_("redirect",`Serving ACME challenge ${Q}`,S),A.writeHead(200,{"content-type":"text/plain"}),A.end(Z);return}}let V=N.headers.host||"",Y=V.includes(":")?V.slice(0,V.indexOf(":")):V,J=D===443?Y:`${Y}:${D}`;_("redirect",`Redirecting request from ${V}${N.url} to https://${J}`,S),A.writeHead(301,{Location:`https://${J}${N.url}`}),A.end()}).listen(R);t.add(K),_("redirect","HTTP redirect server started",S)}function KS(S){let R={...s,...S};if(_("proxy",`Starting proxy with options: ${E(R)}`,R?.verbose),R.viaDaemon){if(!R.from||!R.to){G.error("viaDaemon mode requires both `from` and `to`");return}a({proxies:[{id:R.id,from:R.from,to:R.to,path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}],verbose:R.verbose}).catch((Y)=>{G.error(`Failed to register with rpx daemon: ${Y.message}`),z.exit(1)});return}let D=R.to||"",B=D.split(".").pop()?.toLowerCase()||"",K=z.platform==="darwin"&&D&&!D.includes("localhost")&&!D.includes("127.0.0.1"),N=["dev","app","page","new","day","foo"],A=["test","localhost","local","example","invalid"];if(K&&N.includes(B)&&R?.verbose)G.warn(`The .${B} TLD may not work reliably for local development`),G.info(` Google owns .${B} with HSTS preloading, which can bypass local DNS`),G.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(K)import("./chunk-1108y1dk.js").then(({setupDevelopmentDns:Y})=>{Y({domains:[D],verbose:R.verbose}).then((J)=>{if(J)Promise.resolve().then(()=>{if(R.verbose)if(A.includes(B))G.success(`DNS server started for .${B} domains`);else G.success(`DNS server started for .${B} domains (hosts file entry also added)`)});else _("dns",`Could not start DNS server - ${D} may not resolve in browser`,R.verbose)})}).catch((Y)=>{_("dns",`Failed to start DNS server: ${Y}`,R.verbose)});let V={from:R.from,to:R.to,cleanUrls:R.cleanUrls,https:o(R),cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,changeOrigin:R.changeOrigin,verbose:R.verbose,regenerateUntrustedCerts:R.regenerateUntrustedCerts};_("proxy",`Server options: ${E(V)}`,R.verbose),yR(V).catch((Y)=>{_("proxy",`Failed to start proxy: ${Y}`,R.verbose),G.error(`Failed to start proxy: ${Y.message}`),u({domains:[R.to],hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose})})}function AS(S){return S?.verbose||!1}function fR(S){if(S?.hostsManagement===!1)return!1;let R=S?.cleanup;if(R===!1)return!1;if(R&&typeof R==="object"&&R.hosts===!1)return!1;return!0}async function UR(S){let R={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(S)R={...R,...S};let D=AS(R),B=fR(R);if(_("config",`Starting with config: ${E(R,2)}`,D),_("config",`Is multi-proxy? ${"proxies"in R}`,D),_("config",`Hosts management enabled? ${B}`,D),R.viaDaemon){let I="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map((M)=>({id:M.id,from:M.from,to:M.to,path:M.path,cleanUrls:M.cleanUrls??R.cleanUrls,changeOrigin:M.changeOrigin??R.changeOrigin,pathRewrites:M.pathRewrites})):[{id:R.id,from:R.from,to:R.to??"rpx.localhost",path:R.path,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites}];await a({proxies:I,verbose:D});return}if("proxies"in R&&Array.isArray(R.proxies)){_("servers",`Found ${R.proxies.length} proxies in config`,D);for(let $ of R.proxies)if($.start){let I=`${$.from}-${$.to}`;try{_("watch",`Starting command for ${I} with command: ${$.start.command}`,D),G.info(`Starting command for ${I}...`),await r.startProcess(I,$.start,D);let M=new URL($.from?.startsWith("http")?$.from:`http://${$.from}`),T=M.hostname||"localhost",b=Number(M.port)||80;try{await h(T,b,D),_("watch",`Dev server is ready at ${T}:${b}`,D)}catch(iR){_("watch",`Connection check failed, but continuing with proxy setup: ${iR}`,D),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw _("watch",`Failed to start command for ${I}: ${M}`,D),Error(`Failed to start command for ${I}: ${M}`)}}else _("watch",`No start command for proxy ${$.from} -> ${$.to}`,D)}else if("start"in R&&R.start){_("watch","Found start command in single proxy config",D);let $=`${R.from}-${R.to}`;try{if(R.start)_("watch",`Starting command: ${R.start.command}`,D),await r.startProcess($,R.start,D);let I=new URL(R.from?.startsWith("http")?R.from:`http://${R.from}`),M=I.hostname||"localhost",T=Number(I.port)||80;try{await h(M,T,D),_("watch",`Dev server is ready at ${M}:${T}`,D)}catch(b){_("watch",`Connection check failed, but continuing with proxy setup: ${b}`,D),G.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(I){throw _("watch",`Failed to run start command: ${I}`,D),Error(`Failed to run start command: ${I}`)}}else _("watch","No start command found in config",D);let K="proxies"in R&&Array.isArray(R.proxies)?R.proxies[0]?.to:("to"in R)?R.to:"rpx.localhost";if(z.platform!=="win32"&&(R.https||B)){if(!m())try{_("sudo","Pre-acquiring sudo credentials for privileged operations",D),SS("sudo -v",{stdio:"inherit"})}catch{_("sudo","Could not pre-acquire sudo credentials",D)}}let N=[];if(R.productionCerts){if(N=await qR(R.productionCerts,D),N.length>0)_("ssl",`Using ${N.length} production SNI cert(s): ${N.map(($)=>$.serverName).join(", ")}`,D)}if(R.https){let $=N.length>0?null:await U(R);if(!$&&N.length===0){if(_("ssl",`No valid or trusted certificates found for ${K}, generating new ones`,R.verbose),await e(R),$=await U(R),!$)throw Error(`Failed to load SSL certificates after generation for ${K}`)}else _("ssl",`Using existing and trusted certificates for ${K}`,R.verbose);R._cachedSSLConfig=$}let A="proxies"in R&&Array.isArray(R.proxies)?R.proxies.map(($)=>({...$,https:R.https,cleanup:R.cleanup,cleanUrls:$.cleanUrls??("cleanUrls"in R?R.cleanUrls:!1),vitePluginUsage:R.vitePluginUsage,changeOrigin:$.changeOrigin??R.changeOrigin,verbose:D,_cachedSSLConfig:R._cachedSSLConfig})):[{from:"from"in R?R.from:"localhost:5173",to:"to"in R?R.to:"rpx.localhost",cleanUrls:"cleanUrls"in R?R.cleanUrls:!1,https:R.https,cleanup:R.cleanup,vitePluginUsage:R.vitePluginUsage,start:"start"in R?R.start:void 0,changeOrigin:R.changeOrigin,auth:"auth"in R?R.auth:void 0,verbose:D,_cachedSSLConfig:R._cachedSSLConfig}],V=A.map(($)=>$.to||"rpx.localhost"),Y=N.length>0?N:R._cachedSSLConfig??null,J=V.filter(($)=>$&&!$.includes("localhost")&&!$.includes("127.0.0.1")),Q=["dev","app","page","new","day","foo"],Z=["test","localhost","local","example","invalid"],X=[...new Set(J.map(($)=>$.split(".").pop()?.toLowerCase()))],W=X.filter(($)=>!!$&&Q.includes($));if(W.length>0&&D)G.warn(`The following TLDs may not work reliably for local development: ${W.map(($)=>`.${$}`).join(", ")}`),G.info(" These TLDs have HSTS preloading which can bypass local DNS"),G.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(B&&z.platform==="darwin"&&J.length>0){let{setupDevelopmentDns:$}=await import("./chunk-1108y1dk.js");if(await $({domains:J,verbose:D})){if(D)if(X.every((T)=>!!T&&Z.includes(T)))G.success(`DNS server started for ${X.map((T)=>`.${T}`).join(", ")} domains`);else G.success(`DNS server started for ${X.map((T)=>`.${T}`).join(", ")} domains (hosts file entries also added)`)}else _("dns","Could not start DNS server - custom domains may not resolve",D)}let P=async()=>{_("cleanup","Starting cleanup handler",R.verbose);try{let{tearDownDevelopmentDns:$}=await import("./chunk-1108y1dk.js");await $({verbose:R.verbose})}catch($){_("cleanup",`Error stopping DNS server: ${$}`,R.verbose)}try{await r.stopAll(R.verbose)}catch($){_("cleanup",`Error stopping processes: ${$}`,R.verbose)}await u({domains:V,hosts:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.hosts,certs:typeof R.cleanup==="boolean"?R.cleanup:R.cleanup?.certs,verbose:R.verbose||!1})};z.on("SIGINT",P),z.on("SIGTERM",P);let x=R.singlePortMode===!0,w=R.httpsPort??443,F=R.httpPort??80,O=R.originGuard?JR(R.originGuard):null,L=!!Y&&(A.length>1||x),gR=!Y&&x&&A.length>0;if(L&&Y){_("proxies",`Creating shared HTTPS server for ${A.length} domains on port ${w}`,D);let $=await bR(A,B,D);if(!await C(F,"0.0.0.0",D))dR(D,F,w,R.acmeChallengeWebroot);if(await C(w,"0.0.0.0",D)){if(_("proxies",`Port ${w} is already in use, cannot start shared proxy`,D),D)G.warn(`Port ${w} is in use. Shared HTTPS proxy cannot start.`);return}if(!IR({routeEntries:$,listenPort:w,sslConfig:Y,originGuard:O,verbose:D})){G.error(`Shared HTTPS proxy failed to bind :${w}; not exiting`);return}}else if(gR){_("proxies",`Creating shared HTTP server for ${A.length} domains on port ${F}`,D);let $=await bR(A,B,D);if(await C(F,"0.0.0.0",D)){if(_("proxies",`Port ${F} is already in use, cannot start shared proxy`,D),D)G.warn(`Port ${F} is in use. Shared HTTP proxy cannot start.`);return}if(!IR({routeEntries:$,listenPort:F,sslConfig:null,originGuard:O,verbose:D})){G.error(`Shared HTTP proxy failed to bind :${F}; not exiting`);return}}else for(let $ of A)try{let I=$.to||"rpx.localhost";_("proxy",`Starting proxy for ${I} with SSL config: ${!!Y}`,$.verbose),await yR({from:$.from||"localhost:5173",to:I,cleanUrls:$.cleanUrls||!1,https:$.https||!1,cleanup:$.cleanup||!1,vitePluginUsage:$.vitePluginUsage||!1,verbose:$.verbose||!1,_cachedSSLConfig:R._cachedSSLConfig,changeOrigin:$.changeOrigin||!1})}catch(I){_("proxies",`Failed to start proxy for ${$.to}: ${I}`,$.verbose),G.error(`Failed to start proxy for ${$.to}:`,I)}}async function bR(S,R,D){let B=[],K=new Set;for(let N of S){let A=N.to||"rpx.localhost",V=N.cleanUrls||!1,Y=N.path,J=kR(Y),Q=RR(N.auth);if(N.redirect){let Z=MR(N.redirect);B.push({host:A,path:Y,route:{redirect:Z,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → redirect ${Z.status} ${Z.to}${Q?" (auth)":""}`,D)}else if(N.static)B.push({host:A,path:Y,route:{static:xR(N.static,V),cleanUrls:V,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → static ${typeof N.static==="string"?N.static:N.static.dir}${Q?" (auth)":""}`,D);else{let Z=new URL(N.from?.startsWith("http")?N.from:`http://${N.from}`);B.push({host:A,path:Y,route:{sourceHost:Z.host,cleanUrls:V,changeOrigin:N.changeOrigin||!1,pathRewrites:N.pathRewrites,basePath:J,auth:Q}}),_("proxies",`Route: ${A}${Y??""} → ${Z.host}${Q?" (auth)":""}`,D)}if(K.has(A))continue;if(K.add(A),R&&!HR(A)&&!A.includes("localhost")&&!A.includes("127.0.0.1"))try{if(!(await f([A],D))[0])await y([A],D)}catch{_("hosts",`Could not add hosts entry for ${A}`,D)}}return B}function IR(S){let{routeEntries:R,listenPort:D,sslConfig:B,originGuard:K,verbose:N}=S,A=wR(R),V=TR((Q,Z)=>ER(A,Q,Z),N),Y=K?(Q,Z)=>K(Q)??V(Q,Z):V,J=jR(N);try{let Q=Bun.serve({port:D,hostname:"0.0.0.0",reusePort:lR(),...B?{tls:Array.isArray(B)?B.map((Z)=>({serverName:Z.serverName,key:Z.key,cert:Z.cert})):{key:B.key,cert:B.cert,ca:B.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(Z,X){return Y(Z,X)},websocket:J,error(Z){return _("server",`Shared proxy server error: ${Z}`,N),new Response(`Server Error: ${Z.message}`,{status:500})}});return t.add(Q),_("proxies",`Shared ${B?"HTTPS":"HTTP"} proxy listening on port ${D} for ${A.size} domains`,N),Q}catch(Q){return _("proxies",`Failed to start shared proxy: ${Q}`,N),console.error("Failed to start shared proxy:",Q),null}}function YS(S){if(S?.vitePluginUsage||!S?.verbose)return;if(console.log(""),console.log(` ${H.green(H.bold("rpx"))} ${H.green(`v${DS}`)}`),console.log(` ${H.green("➜")} ${H.dim(S?.from??"")} ${H.dim("➜")} ${H.cyan(S?.ssl?`https://${S?.to}`:`http://${S?.to}`)}`),S?.listenPort!==(S?.ssl?443:80))console.log(` ${H.green("➜")} Listening on port ${S?.listenPort}`);if(S?.cleanUrls)console.log(` ${H.green("➜")} Clean URLs enabled`)}var JN=UR;export{NR as writeEntry,YD as watchRegistry,VS as verifyHttpsChain,HS as trustRootCaForBrowsers,yD as tearDownDevelopmentDns,CD as syncDevelopmentDnsFromRegistry,bS as stripBasePath,TD as stopDnsServer,bD as stopDaemon,yR as startServer,KS as startProxy,UR as startProxies,xD as startDnsServer,tS as siteIdForHost,lR as shouldReusePort,wD as setupResolver,qD as setupDevelopmentDns,dS as serverNameFromCertFilename,uS as serveStaticFile,E as safeStringify,vS as safeRelativePath,TN as safeDeleteFile,a as runViaDaemon,hD as runDaemon,HD as resolverFilePath,zD as resolverBasenamesForDomains,WD as resolverBasenameForDomain,xR as resolveStaticRoute,hS as resolveStaticFile,MR as resolveRedirect,xN as resolvePathRewrite,RR as resolveAuth,JD as renderStartingPage,QD as renderFailedPage,fD as removeResolver,ED as removeLegacyTldResolvers,$R as removeHosts,BR as removeEntry,vD as releaseDaemonLock,VN as redactSensitive,UD as reconcileStaleDevelopmentDns,lD as reconcileDevelopmentDnsOnIdle,eS as readSiteManifest,BD as readEntry,LD as readDaemonPid,GS as readCertSha256Fingerprint,JS as readCertCommonName,KD as readAll,VR as readAcmeChallenge,xS as pruneStaleRootCas,sS as projectNameFromHost,_D as portManager,aS as pathPrefixMatches,XS as parseSha256HashesFromSecurityListing,OS as parseHtpasswd,$S as normalizeSha256Fingerprint,kR as normalizePathPrefix,ZD as normalizeDevDomain,GR as matchesWildcard,gS as matchesAllowedSuffix,ER as matchHostRoute,pS as matchHostList,lS as matchHost,yS as loadSSLConfig,SD as listDiscoverableSites,MS as listCertSha256HashesByCommonName,HR as isWildcardPattern,ZN as isValidRootCA,_R as isValidId,FN as isSingleProxyOptions,MN as isSingleProxyConfig,TS as isRootCaTrustedForSsl,jS as isRootCaFingerprintInKeychains,mR as isProcessElevated,C as isPortInUse,ND as isPidAlive,IN as isMultiProxyOptions,zN as isMultiProxyConfig,iS as isLikelyHostname,jD as isDnsServerRunning,cD as isDaemonRunning,PS as isCertTrusted,o as httpsConfig,m as getSudoPassword,CS as getSharedDaemonCertPaths,qS as getRootCAPaths,DR as getRegistryDir,WN as getPrimaryDomain,FS as getMacosTrustKeychains,IS as getMacosLoginKeychainPath,PD as getDaemonRpxDir,OD as getDaemonPidPath,e as generateCertificate,AD as gcStaleEntries,fS as forceTrustCertificate,DD as findAvailablePort,XN as extractHostname,rS as expandHome,QN as execSudoSync,GD as escapeHtml,KR as ensureDaemonRunning,LS as enforceBasicAuth,wS as devSslToSniEntries,ID as devDomainsFromHosts,oS as detectProjectPreset,LR as deriveIdFromTarget,uD as defaultDaemonSpawnCommand,s as defaultConfig,JN as default,_ as debugLog,RD as createSiteResolver,jR as createProxyWebSocketHandler,TR as createProxyFetchHandler,JR as createOriginGuard,mS as contentTypeFor,kD as contentLooksLikeRpxResolver,s as config,H as colors,US as clearSslConfigCache,FR as cleanupCertificates,u as cleanup,f as checkHosts,U as checkExistingCertificates,QS as certIncludesSanHostnames,qR as buildSniTlsConfig,ES as buildRegistryTlsProxyOptions,cS as buildRedirectLocation,wR as buildHostRoutes,y as addHosts,mD as acquireDaemonLock,$D as SiteSupervisor,kS as SHARED_DEV_HOST_CERT_PATH,zS as RPX_ROOT_CA_COMMON_NAME,MD as RPX_RESOLVER_MARKER,nS as OnDemandCertManager,WS as MACOS_SYSTEM_KEYCHAIN,ZS as MACOS_CA_TRUST_FLAGS,XD as LEGACY_TLD_RESOLVER_LABELS,CR as DefaultPortManager,VD as DNS_STATE_VERSION,FD as DNS_PORT,QR as ACME_CHALLENGE_PREFIX};
@@ -1,4 +1,6 @@
1
1
  import type { PathRewrite } from './types';
2
+ import type { ResolvedAuth } from './auth';
3
+ import type { ResolvedRedirect } from './redirect';
2
4
  import type { ResolvedStaticRoute } from './static-files';
3
5
  /**
4
6
  * Strip the route's mount prefix (`basePath`) from a request pathname so a
@@ -14,7 +16,7 @@ export declare function stripBasePath(pathname: string, basePath?: string): stri
14
16
  * is upgraded (returns `undefined` so Bun completes the handshake) and the
15
17
  * traffic is handled by the `websocket` handler from {@link createProxyWebSocketHandler}.
16
18
  */
17
- export declare function createProxyFetchHandler(getRoute: GetRoute, verbose?: boolean): ProxyFetchHandler;
19
+ export declare function createProxyFetchHandler(getRoute: GetRoute, verbose?: boolean, onNoRoute?: OnNoRoute): ProxyFetchHandler;
18
20
  /**
19
21
  * Build the `websocket` handler block for Bun.serve. It opens an upstream
20
22
  * `WebSocket` per client socket, buffers client→upstream frames until the
@@ -28,8 +30,10 @@ export declare interface ProxyRoute {
28
30
  changeOrigin?: boolean
29
31
  pathRewrites?: PathRewrite[]
30
32
  static?: ResolvedStaticRoute
33
+ redirect?: ResolvedRedirect
31
34
  basePath?: string
32
35
  stripBasePathPrefix?: boolean
36
+ auth?: ResolvedAuth
33
37
  }
34
38
  /** Minimal shape of the Bun server needed for WebSocket upgrades. */
35
39
  export declare interface ProxyServer {
@@ -40,4 +44,17 @@ export declare interface ProxyServer {
40
44
  * existing host-only `getRoute` callbacks remain valid.
41
45
  */
42
46
  export type GetRoute = (hostname: string, pathname: string) => ProxyRoute | undefined;
47
+ /**
48
+ * Outcome of the no-route fallback ({@link OnNoRoute}):
49
+ * - a `Response` — serve it as-is (e.g. a "starting…" splash);
50
+ * - `{ retry: true }` — a route was just published, so re-resolve and proxy;
51
+ * - `undefined` — no fallback applies, fall through to 404.
52
+ */
53
+ export type NoRouteOutcome = Response | { retry: true } | undefined;
54
+ /**
55
+ * Called when `getRoute` finds nothing for a request. Lets the daemon lazily
56
+ * boot an on-demand site (see {@link import('./site-supervisor').SiteSupervisor})
57
+ * and either hold the request behind a splash or signal that the route is now live.
58
+ */
59
+ export type OnNoRoute = (hostname: string, pathname: string, req: Request) => Promise<NoRouteOutcome>;
43
60
  export type ProxyFetchHandler = (req: Request, server?: ProxyServer) => Promise<Response | undefined>;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Normalize a `redirect` config (string shorthand or object) into a
3
+ * {@link ResolvedRedirect}. A `to` without a scheme is treated as `https://<to>`
4
+ * (a public redirect should land on TLS), and any trailing slash is trimmed so
5
+ * appending the request path joins cleanly.
6
+ */
7
+ export declare function resolveRedirect(input: string | RedirectRouteConfig): ResolvedRedirect;
8
+ /**
9
+ * Build the `Location` value for a redirect route. With `preservePath` the
10
+ * request `pathname` + `search` (e.g. `/a/b?x=1`) is appended to the target
11
+ * base; otherwise the bare target is used. `pathname` always starts with `/`
12
+ * and `search` carries its own leading `?` (or is empty).
13
+ */
14
+ export declare function buildRedirectLocation(redirect: ResolvedRedirect, pathname: string, search: string): string;
15
+ /**
16
+ * Redirect routes: a gateway host whose requests are answered with an HTTP
17
+ * redirect (a `Location` response) instead of being proxied to an upstream or
18
+ * served from disk. The canonical use is pointing an alternate/parked domain at
19
+ * its primary host — e.g. `very-good-adblock.org` → `https://verygoodadblock.org`
20
+ * — while preserving deep links: the request path + query are appended to the
21
+ * target by default.
22
+ *
23
+ * Kept transport-agnostic and dependency-free so both the shared `:443` handler
24
+ * and tests can use it directly.
25
+ */
26
+ /**
27
+ * Public redirect config for a route. A bare string is shorthand for a
28
+ * permanent (301) redirect to that URL, path-preserving.
29
+ */
30
+ export declare interface RedirectRouteConfig {
31
+ to: string
32
+ status?: 301 | 302 | 307 | 308
33
+ preservePath?: boolean
34
+ }
35
+ /** A normalized redirect, ready to serve. */
36
+ export declare interface ResolvedRedirect {
37
+ to: string
38
+ status: 301 | 302 | 307 | 308
39
+ preservePath: boolean
40
+ }
@@ -1,5 +1,5 @@
1
1
  import * as path from 'node:path';
2
- import type { PathRewrite, StaticRouteConfig } from './types';
2
+ import type { BasicAuthConfig, PathRewrite, StaticRouteConfig } from './types';
3
3
  /**
4
4
  * Default location for the registry directory. The daemon's PID file and log
5
5
  * sit alongside it under `~/.stacks/rpx/`.
@@ -66,6 +66,7 @@ export declare interface RegistryEntry {
66
66
  cleanUrls?: boolean
67
67
  changeOrigin?: boolean
68
68
  static?: string | StaticRouteConfig
69
+ auth?: BasicAuthConfig
69
70
  }
70
71
  export declare interface WatchHandle {
71
72
  close: () => void
@@ -0,0 +1,106 @@
1
+ import type { OnDemandSitesConfig, SiteRouteTemplate } from './types';
2
+ /** Expand a leading `~` (or `~/…`) to the resolved home directory. */
3
+ export declare function expandHome(p: string, home: string): string;
4
+ /** A registry-safe id derived from a host (`a.localhost` → `a.localhost`). */
5
+ export declare function siteIdForHost(host: string): string;
6
+ /**
7
+ * The host's single project label for convention discovery: `<name>.<tld>` →
8
+ * `name`. Multi-label hosts (`docs.app.localhost`) and bare TLDs don't discover —
9
+ * point those at an explicit `sites` entry. Returns `null` when no TLD matches.
10
+ */
11
+ export declare function projectNameFromHost(host: string, tlds: string[]): string | null;
12
+ /**
13
+ * Read a per-project {@link SiteManifest} so users can define the dev startup
14
+ * manually. Checked sources, in order: a `rpx.site.json` file in the project,
15
+ * then a `"rpx"` key in its `package.json`. Returns `null` when neither exists
16
+ * (or both are malformed).
17
+ */
18
+ export declare function readSiteManifest(dir: string, deps: ResolverProbes): SiteManifest | null;
19
+ /*` dependency in
20
+ * `package.json`. Boots frontend (`/`), API (`/api`) and docs (`/docs`) with
21
+ * the conventional `PORT`/`PORT_API`/`PORT_DOCS` env, deferring proxy + TLS to
22
+ * rpx (`STACKS_PROXY_MANAGED=1`) and taking its public origin via `APP_URL`.
23
+ * - **Generic** — any `package.json` with a `dev` script: a single `bun run dev`
24
+ * backend on `PORT`.
25
+ * - Otherwise `null`.
26
+ */
27
+ export declare function detectProjectPreset(dir: string, deps: ResolverProbes): SitePreset | null;
28
+ /**
29
+ * Build a {@link SiteResolver} over an {@link OnDemandSitesConfig}. Explicit
30
+ * `sites` are matched first (exact host, then wildcard), then convention
31
+ * discovery under `roots`.
32
+ */
33
+ export declare function createSiteResolver(config: OnDemandSitesConfig, deps?: SiteResolverDeps): SiteResolver;
34
+ /**
35
+ * Enumerate the sites rpx can currently boot — explicit non-wildcard
36
+ * {@link SiteConfig}s plus every project discovered by scanning the configured
37
+ * roots. Powers `rpx sites`. Each entry is a fully-resolved {@link ResolvedSite}
38
+ * (so the caller sees the dir, command, and host it would serve).
39
+ */
40
+ export declare function listDiscoverableSites(config: OnDemandSitesConfig, deps?: SiteResolverDeps): ResolvedSite[];
41
+ /** A fully-resolved site, ready for the supervisor to boot and route. */
42
+ export declare interface ResolvedSite {
43
+ host: string
44
+ id: string
45
+ dir: string
46
+ command: string
47
+ env: Record<string, string>
48
+ routes: SiteRouteTemplate[]
49
+ selfRegisters: boolean
50
+ idleTimeoutMs: number
51
+ source: 'config' | 'discovered'
52
+ }
53
+ /**
54
+ * The dev-command shape for a recognized project kind. Returned by a
55
+ * {@link SiteDetector}; the resolver folds it into a {@link ResolvedSite}.
56
+ */
57
+ export declare interface SitePreset {
58
+ command: string
59
+ env?: Record<string, string>
60
+ routes?: SiteRouteTemplate[]
61
+ selfRegisters?: boolean
62
+ urlEnv?: string[]
63
+ }
64
+ /**
65
+ * A per-project override of how rpx boots a site — so the dev startup can be
66
+ * defined **manually** instead of relying on auto-detection. Read from a
67
+ * `rpx.site.json` file in the project, or a `"rpx"` key in its `package.json`.
68
+ * A manifest with a `command` fully defines the preset (and makes even a
69
+ * directory that isn't otherwise a recognized project bootable).
70
+ *
71
+ * ```jsonc
72
+ * // rpx.site.json
73
+ * {
74
+ * "command": "pnpm dev",
75
+ * "env": { "NODE_ENV": "development" },
76
+ * "routes": [
77
+ * { "path": "/", "portEnv": "PORT", "defaultPort": 5173, "readyGate": true },
78
+ * { "path": "/api", "portEnv": "API_PORT", "defaultPort": 4000 }
79
+ * ]
80
+ * }
81
+ * ```
82
+ */
83
+ export declare interface SiteManifest {
84
+ command?: string
85
+ env?: Record<string, string>
86
+ routes?: SiteRouteTemplate[]
87
+ selfRegisters?: boolean
88
+ urlEnv?: string[]
89
+ }
90
+ /** Filesystem probes the resolver and detector use — injected for tests. */
91
+ export declare interface ResolverProbes {
92
+ dirExists: (p: string) => boolean
93
+ fileExists: (p: string) => boolean
94
+ readText: (p: string) => string | null
95
+ }
96
+ export declare interface SiteResolverDeps extends Partial<ResolverProbes> {
97
+ detect?: SiteDetector
98
+ homeDir?: string
99
+ readdir?: (p: string) => string[]
100
+ }
101
+ /** Resolve a host to a site (or `null`). Construct once, call per request. */
102
+ export declare interface SiteResolver {
103
+ resolve: (host: string) => ResolvedSite | null
104
+ }
105
+ /** Detect a project kind from its directory. Returns `null` for "not a dev project". */
106
+ export type SiteDetector = (dir: string, deps: ResolverProbes) => SitePreset | null;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The interstitial pages rpx serves while an on-demand site boots (or after it
3
+ * fails). Plain server-rendered HTML with a `<meta http-equiv="refresh">` so the
4
+ * browser re-requests on its own — no client JS — and the moment the site's
5
+ * routes are published the refresh lands on the real app instead.
6
+ */
7
+ /** Escape the five HTML-significant characters for safe interpolation. */
8
+ export declare function escapeHtml(value: string): string;
9
+ /**
10
+ * The "starting…" splash (HTTP 503 + `Retry-After`). Auto-refreshes until the
11
+ * site's routes go live, at which point the refresh hits the real app. Shows the
12
+ * tail of the boot log so progress is visible while waiting.
13
+ */
14
+ export declare function renderStartingPage(opts: { host: string, sinceMs: number, logTail?: string }): Response;
15
+ /**
16
+ * The failure page (HTTP 502). Shows the tail of the site's log and keeps a slow
17
+ * refresh so a fix + restart is picked up without a manual reload.
18
+ */
19
+ export declare function renderFailedPage(opts: { host: string, error: string, logTail: string }): Response;
@@ -0,0 +1,56 @@
1
+ import type { RegistryEntry } from './registry';
2
+ import type { SiteResolver } from './site-resolver';
3
+ /** A launched site process, abstracted so tests can inject a fake. */
4
+ export declare interface SiteProcessHandle {
5
+ pid: number
6
+ exited: Promise<number | null>
7
+ stop: (signal?: NodeJS.Signals) => void
8
+ }
9
+ /** A point-in-time view of one supervised site, for `rpx sites` / status. */
10
+ export declare interface SiteSnapshot {
11
+ host: string
12
+ dir: string
13
+ status: 'starting' | 'ready' | 'failed'
14
+ pid: number | null
15
+ ports: Record<string, number>
16
+ uptimeMs: number
17
+ idleMs: number
18
+ error?: string
19
+ }
20
+ export declare interface SiteSupervisorOptions {
21
+ resolver: SiteResolver
22
+ registryDir?: string
23
+ rpxDir?: string
24
+ verbose?: boolean
25
+ startupTimeoutMs?: number
26
+ pollIntervalMs?: number
27
+ reapIntervalMs?: number
28
+ restartDelayMs?: number
29
+ killGraceMs?: number
30
+ launcher?: SiteLauncher
31
+ probePort?: (port: number) => Promise<boolean>
32
+ pickPort?: (preferred: number) => Promise<number>
33
+ isHostRoutable?: (host: string) => boolean
34
+ onSiteActivating?: (host: string) => void
35
+ now?: () => number
36
+ writeEntry?: (entry: RegistryEntry, dir?: string, verbose?: boolean) => Promise<void>
37
+ removeEntry?: (id: string, dir?: string, verbose?: boolean) => Promise<void>
38
+ }
39
+ /** Spawn a site's dev command. Injected for tests; default spawns a shell. */
40
+ export type SiteLauncher = (spec: {
41
+ command: string
42
+ cwd: string
43
+ env: Record<string, string>
44
+ logPath: string
45
+ }) => SiteProcessHandle;
46
+ export type SiteRequestStatus = | { kind: 'unknown' }
47
+ | { kind: 'starting', host: string, sinceMs: number, source: 'config' | 'discovered', logTail: string }
48
+ | { kind: 'ready', host: string }
49
+ | { kind: 'failed', host: string, error: string, logTail: string }
50
+ export declare class SiteSupervisor {
51
+ constructor(opts: SiteSupervisorOptions);
52
+ onRequest(host: string): Promise<SiteRequestStatus>;
53
+ stop(host: string): Promise<void>;
54
+ list(): SiteSnapshot[];
55
+ stopAll(): Promise<void>;
56
+ }
package/dist/start.d.ts CHANGED
@@ -6,7 +6,7 @@ import type { SniTlsEntry } from './sni';
6
6
  export declare function cleanup(options?: CleanupOptions): Promise<void>;
7
7
  export declare function startServer(options: SingleProxyConfig): Promise<void>;
8
8
  export declare function setupProxy(options: ProxySetupOptions): Promise<void>;
9
- export declare function startHttpRedirectServer(verbose?: boolean, httpPort?: number, httpsPort?: number): void;
9
+ export declare function startHttpRedirectServer(verbose?: boolean, httpPort?: number, httpsPort?: number, acmeChallengeWebroot?: string): void;
10
10
  export declare function startProxy(options: ProxyOption): void;
11
11
  export declare function startProxies(options?: ProxyOptions): Promise<void>;
12
12
  /**