'use strict'; const { ArrayPrototypePop, ArrayPrototypePush, ArrayPrototypePushApply, MapPrototypeGet, Number, Promise, PromiseWithResolvers, RegExpPrototypeExec, RegExpPrototypeSymbolReplace, SafePromiseRace, StringPrototypeEndsWith, StringPrototypeIndexOf, StringPrototypeSlice, StringPrototypeStartsWith, } = primordials; const { spawn } = require('child_process'); const net = require('net'); const { setInterval: pSetInterval, setTimeout: pSetTimeout, } = require('timers/promises'); const { AbortController, } = require('internal/abort_controller'); const { ERR_DEBUGGER_ERROR, ERR_DEBUGGER_STARTUP_ERROR, } = require('internal/errors').codes; const { exitCodes: { kInvalidCommandLineArgument, }, } = internalBinding('errors'); const { types: { kBoolean, kNoOp, kV8Option, }, } = internalBinding('options'); const { getCLIOptionsInfo } = require('internal/options'); const debugRegex = /Debugger listening on ws:\/\/\[?(.+?)\]?:(\d+)\//; async function portIsFree(host, port, timeout = 3000) { if (port === 0) return; // Binding to a random port. const retryDelay = 150; const ac = new AbortController(); const { signal } = ac; pSetTimeout(timeout).then(() => ac.abort()); const asyncIterator = pSetInterval(retryDelay); while (true) { await asyncIterator.next(); if (signal.aborted) { throw new ERR_DEBUGGER_STARTUP_ERROR( `Timeout (${timeout}) waiting for ${host}:${port} to be free`); } const error = await new Promise((resolve) => { const socket = net.connect(port, host); socket.on('error', resolve); socket.on('connect', () => { socket.end(); resolve(); }); }); if (error?.code === 'ECONNREFUSED') { return; } } } function ensureTrailingNewline(text) { return StringPrototypeEndsWith(text, '\n') ? text : `${text}\n`; } // Mirror OptionsParser::Parse() far enough to find the child script. Options // before it must not undo the inspector setup added by launchChildProcess(). function validateChildArgs(childArgs) { const { options, aliases } = getCLIOptionsInfo(); const syntheticArgs = []; let breakFirstLine = true; let childArgIndex = 0; let inspectorEnabled = true; function peekArg() { return syntheticArgs.length > 0 ? syntheticArgs[syntheticArgs.length - 1] : childArgs[childArgIndex]; } function shiftArg() { return syntheticArgs.length > 0 ? ArrayPrototypePop(syntheticArgs) : childArgs[childArgIndex++]; } while (true) { const nextArg = peekArg(); if (nextArg === undefined || nextArg.length <= 1 || nextArg[0] !== '-') { break; } const isSynthetic = syntheticArgs.length > 0; const arg = shiftArg(); if (arg === '--') { break; } if (!isSynthetic && (arg === '--experimental-config-file' || arg === '--experimental-default-config-file')) { // ConfigReader rewrites these to an inline default path before parsing. continue; } if (!isSynthetic && StringPrototypeStartsWith( arg, '--experimental-default-config-file=')) { // ConfigReader rejects this form before parsing the remaining options. return; } const equalsIndex = arg[1] === '-' ? StringPrototypeIndexOf(arg, '=') : -1; let name = equalsIndex === -1 ? arg : StringPrototypeSlice(arg, 0, equalsIndex); if (name.length > 2) { name = `${StringPrototypeSlice(name, 0, 2)}${ RegExpPrototypeSymbolReplace(/_/g, StringPrototypeSlice(name, 2), '-')}`; } let isNegation = false; if (StringPrototypeStartsWith(name, '--no-')) { name = `--${StringPrototypeSlice(name, 5)}`; isNegation = true; } while (true) { let expansion = MapPrototypeGet(aliases, name); if (expansion === undefined && equalsIndex !== -1) { expansion = MapPrototypeGet(aliases, `${name}=`); } const aliasArg = peekArg(); if (expansion === undefined && aliasArg !== undefined && aliasArg.length > 0 && aliasArg[0] !== '-') { expansion = MapPrototypeGet(aliases, `${name} `); } if (expansion === undefined) { break; } const previousName = name; // process.allowedNodeEnvironmentFlags may remove a self-recursive // first entry from the cached alias metadata. Preserve the native // parser's synthetic option terminator in that case. if (expansion[0] === '--') { for (let i = expansion.length - 1; i >= 0; i--) { ArrayPrototypePush(syntheticArgs, expansion[i]); } break; } name = expansion[0]; for (let i = expansion.length - 1; i > 0; i--) { ArrayPrototypePush(syntheticArgs, expansion[i]); } if (name === previousName) { break; } } const info = MapPrototypeGet(options, name); if (info === undefined) { continue; } if (isNegation && info.type !== kBoolean && info.type !== kV8Option) { return; } if (info.type === kBoolean || info.type === kNoOp || info.type === kV8Option) { if (name === '--inspect') { inspectorEnabled = !isNegation; } else if (name === '--inspect-brk') { breakFirstLine = !isNegation; if (!isNegation) { inspectorEnabled = true; } } else if (!isNegation && (name === '--inspect-wait' || name === '--inspect-brk-node')) { inspectorEnabled = true; } continue; } if (equalsIndex !== -1) { if (equalsIndex === arg.length - 1) { return; } continue; } const value = peekArg(); if (value === undefined || (value.length > 0 && value[0] === '-')) { return; } shiftArg(); } if (!inspectorEnabled) { throw new ERR_DEBUGGER_STARTUP_ERROR( '--no-inspect is incompatible with node inspect before the child script'); } if (!breakFirstLine) { throw new ERR_DEBUGGER_STARTUP_ERROR( '--no-inspect-brk is incompatible with node inspect before the child script'); } } async function waitForDebugger( client, callMethod = (method) => client.callMethod(method), ) { const { promise: waitingPromise, resolve: resolveWaiting, } = PromiseWithResolvers(); const { promise: closedPromise, reject: rejectClosed, } = PromiseWithResolvers(); const onWaiting = () => resolveWaiting(); const onClose = () => { rejectClosed(new ERR_DEBUGGER_ERROR( 'Debugger session ended while waiting for target startup')); }; // The inspector can accept a connection before the target reaches its // startup wait. Enabling NodeRuntime makes that state observable whether // the target was already waiting or starts waiting later. client.once('NodeRuntime.waitingForDebugger', onWaiting); client.once('close', onClose); try { await SafePromiseRace([ callMethod('NodeRuntime.enable'), closedPromise, ]); await SafePromiseRace([ waitingPromise, closedPromise, ]); await SafePromiseRace([ callMethod('NodeRuntime.disable'), closedPromise, ]); } finally { client.removeListener('NodeRuntime.waitingForDebugger', onWaiting); client.removeListener('close', onClose); } } function writeInspectUsageAndExit(invokedAs, message, exitCode) { const code = exitCode ?? (message ? kInvalidCommandLineArgument : 0); const out = code === 0 ? process.stdout : process.stderr; if (message) { out.write(`${message}\n`); } out.write(`Usage: ${invokedAs} [--port=] [ ...] [