/**
 * Spawn npm in a way that works on Windows without shell: true.
 * Node's spawn/spawnSync cannot reliably run .cmd/.bat files; using the same
 * Node that runs 4r to execute npm-cli.js matches `npm.cmd` behavior.
 * Avoiding shell: true prevents a flashing cmd.exe window for background tasks.
 */
import { spawn, spawnSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
const npmStdio = ['ignore', 'pipe', 'pipe'];
/** Path to npm-cli.js next to the running Node (Windows); used for detached updates without npm.cmd. */
export function getNpmCliJsPath() {
    if (process.platform !== 'win32')
        return null;
    const nodeDir = path.dirname(process.execPath);
    const npmCli = path.join(nodeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js');
    return fs.existsSync(npmCli) ? npmCli : null;
}
function npmCliPath() {
    return getNpmCliJsPath();
}
export function spawnNpmSync(args) {
    const opts = { encoding: 'utf-8', stdio: npmStdio };
    const cli = npmCliPath();
    if (cli) {
        return spawnSync(process.execPath, [cli, ...args], opts);
    }
    const cmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
    return spawnSync(cmd, args, opts);
}
/**
 * Async spawn for long-running / detached processes (e.g. Gateway). Prefer this over
 * `spawn('npm run start', { shell: true })` on Windows to avoid a console flash.
 */
export function spawnNpm(args, options) {
    const merged = {
        ...options,
        windowsHide: options.windowsHide !== false,
    };
    const cli = npmCliPath();
    if (cli) {
        return spawn(process.execPath, [cli, ...args], merged);
    }
    const cmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
    return spawn(cmd, args, merged);
}
//# sourceMappingURL=npm-spawn.js.map