11import type { DevframeRpcConnection , WsOriginRegistry } from 'devframe/rpc/transports/ws-server'
2+ import type { Server } from 'node:http'
23import type { DevframeAuthHandler } from '../node/auth/handler'
34import type { StartedServer } from '../node/instance-shell'
45import type { DevframeDefinition , DevframeSseOptions , DevframeWsOptions , McpSetting } from '../types/devframe'
@@ -9,6 +10,7 @@ import { open } from 'devframe/utils/open'
910import { withBase } from 'devframe/utils/url'
1011import { H3 , toNodeHandler } from 'h3'
1112import { diagnostics } from '../node/diagnostics'
13+ import { isAddressInUse , listenWithLoopbackTwin } from '../node/listen'
1214import { normalizeHttpServerUrl } from '../node/utils'
1315import { normalizeBasePath , resolveBasePath , resolveDevServerPort } from './_shared'
1416import { getInstanceInternals , initDevframe } from './initiate'
@@ -22,9 +24,15 @@ export interface CreateDevServerOptions {
2224 /**
2325 * Port to listen on. When omitted, falls back to
2426 * {@link resolveDevServerPort}, which respects `def.cli?.port` /
25- * `portRange` / `random`.
27+ * `portRange` / `random`. A port set here is used as given: if it is
28+ * taken, startup fails (`DF0052`) instead of moving to another port.
2629 */
2730 port ?: number
31+ /**
32+ * Preferred port when `port` is omitted, passed to
33+ * {@link resolveDevServerPort}. Default: `def.cli?.port ?? 9999`.
34+ */
35+ defaultPort ?: number
2836 /**
2937 * Parsed flag bag forwarded to `setup(ctx, { flags })`. The dev
3038 * server itself only reads `flags.open` from this bag, and only when
@@ -147,7 +155,6 @@ export async function createDevServer(
147155 throw diagnostics . DF0058 ( { id : def . id } )
148156
149157 const host = options . host ?? def . cli ?. host ?? 'localhost'
150- const requestedPort = options . port ?? await resolveDevServerPort ( def , { host } )
151158 const flags = options . flags ?? { }
152159 const basePath = options . basePath ? normalizeBasePath ( options . basePath ) : resolveBasePath ( def , 'standalone' )
153160 const app = options . app ?? new H3 ( )
@@ -157,27 +164,7 @@ export async function createDevServer(
157164 // starts first so the shared WS tier and advertised origin reflect the real
158165 // bound port (`port: 0` binds an ephemeral one).
159166 const server = createServer ( toNodeHandler ( app ) )
160- try {
161- await new Promise < void > ( ( resolveListen , rejectListen ) => {
162- const onError = ( error : Error ) : void => rejectListen ( error )
163- // Without this listener a failed bind emits `error` with nobody
164- // attached (an uncaughtException) and the `listen` callback never
165- // fires, so this promise never settles.
166- server . once ( 'error' , onError )
167- server . listen ( requestedPort , host , ( ) => {
168- server . removeListener ( 'error' , onError )
169- resolveListen ( )
170- } )
171- } )
172- }
173- catch ( error ) {
174- throw diagnostics . DF0052 ( {
175- host,
176- port : requestedPort ,
177- reason : error instanceof Error ? error . message : String ( error ) ,
178- cause : error ,
179- } )
180- }
167+ const { requestedPort, closeLoopbackTwin } = await listenDevServer ( server , def , host , options )
181168 const address = server . address ( )
182169 const port = typeof address === 'object' && address ? address . port : requestedPort
183170 // A wildcard bind host (`0.0.0.0` / `::`) isn't dialable from a browser, so
@@ -220,6 +207,7 @@ export async function createDevServer(
220207 await devframe . ready
221208 }
222209 catch ( error ) {
210+ await closeLoopbackTwin ( )
223211 await new Promise < void > ( resolveClose => server . close ( ( ) => resolveClose ( ) ) )
224212 throw error
225213 }
@@ -244,11 +232,44 @@ export async function createDevServer(
244232 // transport (and closes any dedicated-port socket server), and disposes
245233 // MCP sessions; the HTTP server is this function's own to close.
246234 await devframe . close ( )
235+ await closeLoopbackTwin ( )
247236 await new Promise < void > ( resolveClose => server . close ( ( ) => resolveClose ( ) ) )
248237 } ,
249238 }
250239}
251240
241+ /**
242+ * Bind the dev server. `getPort` probes only `host`, so it can call a port
243+ * free while another process holds it on the other loopback address of
244+ * `localhost`. The twin bind catches that, and a port that was not pinned
245+ * moves to the next free one.
246+ */
247+ async function listenDevServer (
248+ server : Server ,
249+ def : DevframeDefinition ,
250+ host : string ,
251+ options : CreateDevServerOptions ,
252+ ) : Promise < { requestedPort : number , closeLoopbackTwin : ( ) => Promise < void > } > {
253+ let requestedPort = options . port ?? await resolveDevServerPort ( def , { host, defaultPort : options . defaultPort } )
254+ for ( let attempt = 1 ; ; attempt ++ ) {
255+ try {
256+ return { requestedPort, closeLoopbackTwin : await listenWithLoopbackTwin ( server , requestedPort , host ) }
257+ }
258+ catch ( error ) {
259+ if ( options . port == null && attempt < 3 && isAddressInUse ( error ) ) {
260+ requestedPort = await resolveDevServerPort ( def , { host, defaultPort : requestedPort + 1 } )
261+ continue
262+ }
263+ throw diagnostics . DF0052 ( {
264+ host,
265+ port : requestedPort ,
266+ reason : error instanceof Error ? error . message : String ( error ) ,
267+ cause : error ,
268+ } )
269+ }
270+ }
271+ }
272+
252273async function maybeOpenBrowser (
253274 def : DevframeDefinition ,
254275 flags : Record < string , unknown > ,
0 commit comments