@@ -205,16 +205,18 @@ class PhpDebugSession extends vscode.DebugSession {
205205 }
206206 this . _args = args
207207 /** launches the script as CLI */
208- const launchScript = async ( ) => {
208+ const launchScript = async ( port : number ) => {
209209 // check if program exists
210210 await new Promise < void > ( ( resolve , reject ) =>
211211 fs . access ( args . program ! , fs . constants . F_OK , err => ( err ? reject ( err ) : resolve ( ) ) )
212212 )
213- const runtimeArgs = args . runtimeArgs || [ ]
213+ const runtimeArgs = ( args . runtimeArgs || [ ] ) . map ( v => v . replace ( '${port}' , port . toString ( ) ) )
214214 const runtimeExecutable = args . runtimeExecutable || 'php'
215215 const programArgs = args . args || [ ]
216216 const cwd = args . cwd || process . cwd ( )
217- const env = args . env || process . env
217+ const env = Object . fromEntries (
218+ Object . entries ( args . env || process . env ) . map ( v => [ v [ 0 ] , v [ 1 ] ?. replace ( '${port}' , port . toString ( ) ) ] )
219+ )
218220 // launch in CLI mode
219221 if ( args . externalConsole ) {
220222 const script = await Terminal . launchInTerminal (
@@ -252,7 +254,7 @@ class PhpDebugSession extends vscode.DebugSession {
252254 }
253255 /** sets up a TCP server to listen for Xdebug connections */
254256 const createServer = ( ) =>
255- new Promise < void > ( ( resolve , reject ) => {
257+ new Promise < number > ( ( resolve , reject ) => {
256258 const server = ( this . _server = net . createServer ( ) )
257259 server . on ( 'connection' , async ( socket : net . Socket ) => {
258260 try {
@@ -316,16 +318,22 @@ class PhpDebugSession extends vscode.DebugSession {
316318 } )
317319 server . on ( 'error' , ( error : Error ) => {
318320 this . sendEvent ( new vscode . OutputEvent ( util . inspect ( error ) + '\n' ) )
319- this . sendErrorResponse ( response , < Error > error )
321+ reject ( error )
322+ } )
323+ server . on ( 'listening' , ( ) => {
324+ const port = ( server . address ( ) as net . AddressInfo ) . port
325+ resolve ( port )
320326 } )
321- server . listen ( args . port || 9000 , args . hostname , ( ) => resolve ( ) )
327+ const listenPort = args . port === undefined ? 9000 : args . port
328+ server . listen ( listenPort , args . hostname )
322329 } )
323330 try {
331+ let port = 0
324332 if ( ! args . noDebug ) {
325- await createServer ( )
333+ port = await createServer ( )
326334 }
327335 if ( args . program ) {
328- await launchScript ( )
336+ await launchScript ( port )
329337 }
330338 } catch ( error ) {
331339 this . sendErrorResponse ( response , < Error > error )
0 commit comments