@@ -8,6 +8,7 @@ export interface ResolveDesktopBackendPortOptions {
88 readonly host : string ;
99 readonly startPort ?: number ;
1010 readonly maxPort ?: number ;
11+ readonly requiredHosts ?: ReadonlyArray < string > ;
1112 readonly canListenOnHost ?: ( port : number , host : string ) => Promise < boolean > ;
1213}
1314
@@ -21,10 +22,37 @@ const defaultCanListenOnHost = async (port: number, host: string): Promise<boole
2122const isValidPort = ( port : number ) : boolean =>
2223 Number . isInteger ( port ) && port >= 1 && port <= MAX_TCP_PORT ;
2324
25+ const normalizeHosts = (
26+ host : string ,
27+ requiredHosts : ReadonlyArray < string > ,
28+ ) : ReadonlyArray < string > =>
29+ Array . from (
30+ new Set (
31+ [ host , ...requiredHosts ]
32+ . map ( ( candidate ) => candidate . trim ( ) )
33+ . filter ( ( candidate ) => candidate . length > 0 ) ,
34+ ) ,
35+ ) ;
36+
37+ async function canListenOnAllHosts (
38+ port : number ,
39+ hosts : ReadonlyArray < string > ,
40+ canListenOnHost : ( port : number , host : string ) => Promise < boolean > ,
41+ ) : Promise < boolean > {
42+ for ( const candidateHost of hosts ) {
43+ if ( ! ( await canListenOnHost ( port , candidateHost ) ) ) {
44+ return false ;
45+ }
46+ }
47+
48+ return true ;
49+ }
50+
2451export async function resolveDesktopBackendPort ( {
2552 host,
2653 startPort = DEFAULT_DESKTOP_BACKEND_PORT ,
2754 maxPort = MAX_TCP_PORT ,
55+ requiredHosts = [ ] ,
2856 canListenOnHost = defaultCanListenOnHost ,
2957} : ResolveDesktopBackendPortOptions ) : Promise < number > {
3058 if ( ! isValidPort ( startPort ) ) {
@@ -39,15 +67,17 @@ export async function resolveDesktopBackendPort({
3967 throw new Error ( `Desktop backend max port ${ maxPort } is below start port ${ startPort } ` ) ;
4068 }
4169
70+ const hostsToCheck = normalizeHosts ( host , requiredHosts ) ;
71+
4272 // Keep desktop startup predictable across app restarts by probing upward from
4373 // the same preferred port instead of picking a fresh ephemeral port.
4474 for ( let port = startPort ; port <= maxPort ; port += 1 ) {
45- if ( await canListenOnHost ( port , host ) ) {
75+ if ( await canListenOnAllHosts ( port , hostsToCheck , canListenOnHost ) ) {
4676 return port ;
4777 }
4878 }
4979
5080 throw new Error (
51- `No desktop backend port is available on ${ host } between ${ startPort } and ${ maxPort } ` ,
81+ `No desktop backend port is available on hosts ${ hostsToCheck . join ( ", " ) } between ${ startPort } and ${ maxPort } ` ,
5282 ) ;
5383}
0 commit comments