From cbb91ee214dd0b138abfbc59ce1591f709b012ce Mon Sep 17 00:00:00 2001 From: jdalton Date: Tue, 1 Dec 2026 20:12:13 -0500 Subject: [PATCH] fix(npm): preserve JSON output on nonzero exits Assisted-by: Codex:GPT-6-Luna --- .config/vitest.config.mts | 6 +-- .config/vitest.e2e.config.mts | 6 +-- .config/vitest.integration.config.mts | 6 +-- .config/vitest.native.config.mts | 6 +-- .config/vitest.terminal.config.mts | 6 +-- src/commands/npm/cmd-npm.mts | 66 ++++++++++++++++--------- src/commands/npm/cmd-npm.test.mts | 71 ++++++++++++++++++++++++++- 7 files changed, 128 insertions(+), 39 deletions(-) diff --git a/.config/vitest.config.mts b/.config/vitest.config.mts index eefa13d630..106bcea952 100644 --- a/.config/vitest.config.mts +++ b/.config/vitest.config.mts @@ -1,10 +1,10 @@ import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' +import type { UserConfig } from 'vitest/config' import { resolveSnapshotPath } from './snapshot-path.mts' -export default defineConfig({ +export default { root: fileURLToPath(new URL('../', import.meta.url)), resolve: { preserveSymlinks: false, @@ -59,4 +59,4 @@ export default defineConfig({ ], }, }, -}) +} satisfies UserConfig diff --git a/.config/vitest.e2e.config.mts b/.config/vitest.e2e.config.mts index 0ed28d4b0d..668a97bdf0 100644 --- a/.config/vitest.e2e.config.mts +++ b/.config/vitest.e2e.config.mts @@ -1,10 +1,10 @@ import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' +import type { UserConfig } from 'vitest/config' import { resolveSnapshotPath } from './snapshot-path.mts' -export default defineConfig({ +export default { root: fileURLToPath(new URL('../', import.meta.url)), resolve: { preserveSymlinks: false, @@ -37,4 +37,4 @@ export default defineConfig({ ], }, }, -}) +} satisfies UserConfig diff --git a/.config/vitest.integration.config.mts b/.config/vitest.integration.config.mts index 5b37d08616..20c092a2b2 100644 --- a/.config/vitest.integration.config.mts +++ b/.config/vitest.integration.config.mts @@ -1,10 +1,10 @@ import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' +import type { UserConfig } from 'vitest/config' import { resolveSnapshotPath } from './snapshot-path.mts' -export default defineConfig({ +export default { root: fileURLToPath(new URL('../', import.meta.url)), resolve: { preserveSymlinks: false, @@ -29,4 +29,4 @@ export default defineConfig({ 'test/fixtures/**', ], }, -}) +} satisfies UserConfig diff --git a/.config/vitest.native.config.mts b/.config/vitest.native.config.mts index 994807a1a3..bf7b0eede3 100644 --- a/.config/vitest.native.config.mts +++ b/.config/vitest.native.config.mts @@ -1,10 +1,10 @@ import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' +import type { UserConfig } from 'vitest/config' import { resolveSnapshotPath } from './snapshot-path.mts' -export default defineConfig({ +export default { root: fileURLToPath(new URL('../', import.meta.url)), resolve: { preserveSymlinks: false, @@ -32,4 +32,4 @@ export default defineConfig({ 'test/fixtures/**', ], }, -}) +} satisfies UserConfig diff --git a/.config/vitest.terminal.config.mts b/.config/vitest.terminal.config.mts index 0636916154..3b40b7130d 100644 --- a/.config/vitest.terminal.config.mts +++ b/.config/vitest.terminal.config.mts @@ -1,10 +1,10 @@ import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' +import type { UserConfig } from 'vitest/config' import { resolveSnapshotPath } from './snapshot-path.mts' -export default defineConfig({ +export default { root: fileURLToPath(new URL('../', import.meta.url)), resolve: { preserveSymlinks: false }, test: { @@ -23,4 +23,4 @@ export default defineConfig({ ], exclude: ['**/node_modules/**', '**/dist/**', '.claude/worktrees/**'], }, -}) +} satisfies UserConfig diff --git a/src/commands/npm/cmd-npm.mts b/src/commands/npm/cmd-npm.mts index 54d2866daf..58b5eda74c 100644 --- a/src/commands/npm/cmd-npm.mts +++ b/src/commands/npm/cmd-npm.mts @@ -9,20 +9,48 @@ import constants, { import { commonFlags, outputFlags } from '../../flags.mts' import { filterFlags } from '../../utils/cmd.mts' import { logger } from '../../utils/logger.mts' +import type { + CliCommandConfig, + CliCommandContext, +} from '../../utils/meow-with-subcommands.mts' import { meowOrExit } from '../../utils/meow-with-subcommands.mts' import { getFlagApiRequirementsOutput } from '../../utils/output-formatting.mts' +import type { SpawnResult } from '../../utils/spawn.mts' +import { isSpawnError } from '../../utils/spawn.mts' import { trackSubprocessExit, trackSubprocessStart, } from '../../utils/telemetry/integration.mts' -import type { - CliCommandConfig, - CliCommandContext, -} from '../../utils/meow-with-subcommands.mts' - const require = createRequire(import.meta.url) +type NpmSpawnOutcome = { + code: number | null + signal: NodeJS.Signals | null +} + +export async function awaitNpmSpawn( + spawnPromise: SpawnResult, + startedAt: number, + trackExit = trackSubprocessExit, +): Promise { + try { + await spawnPromise + } catch (error) { + const { exitCode, signalCode } = spawnPromise.process + const childExit = + (isSpawnError(error) && typeof exitCode === 'number' && exitCode >= 0) || + !!signalCode + if (!childExit) { + throw error + } + } + const { exitCode, signalCode } = spawnPromise.process + const outcome = { code: exitCode, signal: signalCode } + await trackExit(NPM, startedAt, outcome.code) + return outcome +} + export const CMD_NAME = NPM const description = 'Wraps npm with Socket security scanning' @@ -97,23 +125,15 @@ async function run( stdio: 'inherit', }) - // Handle exit codes and signals using event-based pattern. - // See https://nodejs.org/api/child_process.html#event-exit. - spawnPromise.process.on( - 'exit', - (code: number | null, signalName: NodeJS.Signals | null) => { - // Track subprocess exit and flush telemetry before exiting. - // Use .then() to ensure telemetry completes before process.exit(). - void trackSubprocessExit(NPM, subprocessStartTime, code).then(() => { - if (signalName) { - process.kill(process.pid, signalName) - } else if (typeof code === 'number') { - // eslint-disable-next-line n/no-process-exit - process.exit(code) - } - }) - }, + // Preserve the child's exit code or signal after telemetry has flushed. + const { code, signal } = await awaitNpmSpawn( + spawnPromise, + subprocessStartTime, ) - - await spawnPromise + if (signal) { + process.kill(process.pid, signal) + } else if (typeof code === 'number') { + // eslint-disable-next-line n/no-process-exit + process.exit(code) + } } diff --git a/src/commands/npm/cmd-npm.test.mts b/src/commands/npm/cmd-npm.test.mts index 7a02914c65..93c1a97283 100644 --- a/src/commands/npm/cmd-npm.test.mts +++ b/src/commands/npm/cmd-npm.test.mts @@ -1,4 +1,6 @@ -import { describe, expect } from 'vitest' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' import constants, { FLAG_CONFIG, @@ -8,6 +10,73 @@ import constants, { NPM, } from '../../../src/constants.mts' import { cmdit, spawnSocketCli } from '../../../test/utils.mts' +import { spawn } from '../../utils/spawn.mts' +import type { SpawnResult } from '../../utils/spawn.mts' +import { awaitNpmSpawn } from './cmd-npm.mts' + +describe('awaitNpmSpawn', () => { + it('preserves JSON output from a nonzero child exit and waits for telemetry', async () => { + const json = '{"error":{"code":"E404"}}' + const spawnPromise = spawn(process.execPath, [ + '-e', + `process.stdout.write(${JSON.stringify(json)}); process.exit(1)`, + ]) + const capturedStdout = spawnPromise.catch(error => error.stdout) + let telemetryFinished = false + + const outcome = await awaitNpmSpawn(spawnPromise, 1, async () => { + await new Promise(resolve => setTimeout(resolve, 10)) + telemetryFinished = true + }) + + expect(outcome).toMatchObject({ code: 1, signal: null }) + expect(await capturedStdout).toBe(json) + expect(telemetryFinished).toBe(true) + }) + + it('preserves a child signal outcome', async () => { + const spawnPromise = spawn(process.execPath, [ + '-e', + `process.kill(process.pid, 'SIGTERM')`, + ]) + + await expect( + awaitNpmSpawn(spawnPromise, 1, async () => {}), + ).resolves.toMatchObject( + process.platform === 'win32' + ? { code: 1, signal: null } + : { code: null, signal: 'SIGTERM' }, + ) + }) + + it('propagates launch failures', async () => { + const spawnPromise = spawn( + join(tmpdir(), `socket-missing-${process.pid}`), + [], + ) + + await expect( + awaitNpmSpawn(spawnPromise, 1, async () => {}), + ).rejects.toMatchObject({ + code: 'ENOENT', + }) + }) + + it('propagates ENOENT when Windows reports exit code 1', async () => { + const launchError = Object.assign(new Error('spawn npm ENOENT'), { + code: 'ENOENT', + }) + const spawnPromise = Promise.reject(launchError) as SpawnResult + Object.assign(spawnPromise, { + process: { exitCode: 1, signalCode: null }, + stdin: null, + }) + + await expect(awaitNpmSpawn(spawnPromise, 1, async () => {})).rejects.toBe( + launchError, + ) + }) +}) describe('socket npm', async () => { const { binCliPath } = constants