Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
d7af66a
refactor: add parse.ts
hyperz111 Mar 17, 2026
a0a0a33
chore: inline some regexes
hyperz111 Mar 18, 2026
e6d189c
chore: don't use destruction
hyperz111 Mar 18, 2026
ad782b3
chore: use better named imports
hyperz111 Mar 18, 2026
62771d3
docs: say if using sync version
hyperz111 Mar 18, 2026
f3e60a4
chore: pass parsed object
hyperz111 Mar 18, 2026
694b890
style: format
hyperz111 Mar 19, 2026
9d5be90
chore: handle quoted env paths
hyperz111 Mar 19, 2026
26aa933
Merge branch 'main' into inline-parse
hyperz111 Mar 22, 2026
4c5a8b0
style: format
hyperz111 Mar 26, 2026
808ce03
chore: fix and change
hyperz111 Mar 26, 2026
6b981a7
chore: use our parser
hyperz111 Mar 26, 2026
7f6f894
refactor: some type annotation & code vhange
hyperz111 Mar 27, 2026
7d8f7dc
test: add parse test
hyperz111 Mar 27, 2026
728e1dc
fix: use shell if command is not resolved too
hyperz111 Mar 28, 2026
9003fbe
style: format
hyperz111 Mar 28, 2026
c7a7f89
test: add Windows tests
hyperz111 Mar 28, 2026
d3e8e54
perf: slight optimisation in shebang splitting
43081j Mar 31, 2026
e400042
chore: fix typos
hyperz111 Mar 31, 2026
a25b887
Merge branch 'main' into inline-parse
hyperz111 Apr 11, 2026
be449dd
Merge branch 'main' into inline-parse
43081j Apr 30, 2026
153a956
chore: fix up
43081j Apr 30, 2026
784b9d0
test: use describe block per os
43081j Apr 30, 2026
636ef54
fix: a few things
43081j Apr 30, 2026
ad55676
chore: remove unused import
43081j May 2, 2026
e77cc18
chore: rework and simplify some things
43081j May 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions THIRD_PARTY_LICENSES.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# cross-spawn

The MIT License (MIT)

Copyright (c) 2018 Made With MOXY Lda <hello@moxy.studio>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"node": ">=18"
},
"files": [
"dist"
"dist",
"THIRD-PARTY-LICENSES.txt"
],
"scripts": {
"build": "tsdown",
Expand Down
12 changes: 8 additions & 4 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import {cwd as getCwd} from 'node:process';
import {computeEnv} from './env.js';
import {combineStreams} from './stream.js';
import readline from 'node:readline';
import {_parse} from 'cross-spawn';
import {normalizeSpawnCommand} from './normalize.js';
import {NonZeroExitError} from './non-zero-exit-error.js';

export {NonZeroExitError};
export {NonZeroExitError, normalizeSpawnCommand};

const LINE_SEPARATOR_REGEX = /\r?\n/;

Expand Down Expand Up @@ -312,7 +312,11 @@ export class ExecProcess implements Result {

nodeOptions.env = computeEnv(cwd, nodeOptions.env);

const crossResult = _parse(this._command, this._args, nodeOptions);
const crossResult = normalizeSpawnCommand(
this._command,
this._args,
nodeOptions
);

const handle = spawn(
crossResult.command,
Expand Down Expand Up @@ -386,7 +390,7 @@ export function xSync(

nodeOptions.env = computeEnv(cwd, nodeOptions.env);

const crossResult = _parse(command, args ?? [], nodeOptions);
const crossResult = normalizeSpawnCommand(command, args ?? [], nodeOptions);

const spawnResult = spawnSync(
crossResult.command,
Expand Down
180 changes: 180 additions & 0 deletions src/normalize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import {type SpawnOptions} from 'node:child_process';
import {closeSync, openSync, readSync, statSync} from 'node:fs';
import {
delimiter as pathDelimiter,
normalize as normalizePath,
resolve as resolvePath,
basename
} from 'node:path';
import {cwd as getCwd} from 'node:process';
import {getPathFromEnv} from './env.js';

// See http://www.robvanderwoude.com/escapechars.php
const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
const shebangRegExp = /^#!\s*(.+)$/;
const isWindowsExecutableRegExp = /\.(?:com|exe)$/i;
const isNodeModulesCmdRegExp = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i;
const isWindows = process.platform === 'win32';
const defaultPathExt = ['.EXE', '.CMD', '.BAT', '.COM'];

interface NormalizedSpawnCommand {
command: string;
args: readonly string[];
options: SpawnOptions;
}

/**
* Normalizes the command and arguments to work cross-platform.
* On Windows, this basically handles things like shebangs, calling
* `node_modules/.bin` commands, and escaping meta characters.
* On other platforms, it just returns the command and arguments as-is.
*/
export function normalizeSpawnCommand(
command: string,
args: readonly string[] = [],
options: SpawnOptions = {}
): NormalizedSpawnCommand {
// Early return if use `shell` option or not on Windows.
if (options.shell === true || !isWindows) {
return {command, args, options};
}

// Detect & add support for shebangs
let file = resolveCommand(command, options);
let shebang: string | null = null;

if (file !== null) {
// Read the first 150 bytes from the file
const size = 150;
const buffer = Buffer.alloc(size);

let fd: number | null = null;
try {
fd = openSync(file, 'r');
readSync(fd, buffer, 0, size, 0);
} catch {
// do nothing, we'll just assume it's not a shebang
} finally {
if (fd !== null) {
closeSync(fd);
}
}

const match = buffer.toString().match(shebangRegExp);

if (match !== null) {
const line = match[1].trim();
const separatorIndex = line.indexOf(' ');
const path = separatorIndex !== -1 ? line.slice(0, separatorIndex) : line;
const argument =
separatorIndex !== -1 ? line.slice(separatorIndex + 1) : '';
const binary = basename(path);

shebang = binary === 'env' ? argument || null : binary;
}
}

if (shebang !== null && file !== null) {
args = [file, ...args];
command = shebang;

file = resolveCommand(command, options);
}

// We don't need a shell if the command filename is resolved and an executable
if (file === null || !isWindowsExecutableRegExp.test(file)) {
// Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
// The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
// Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
// we need to double escape them
const needsDoubleEscapeMetaChars =
file !== null && isNodeModulesCmdRegExp.test(file);

// Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
// This is necessary otherwise it will always fail with ENOENT in those cases
command = normalizePath(command);

// Escape command & arguments
command = command.replace(metaCharsRegExp, '^$1');
args = args.map((arg) => {
// Algorithm below is based on https://qntm.org/cmd
// It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input
// Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information

// Sequence of backslashes followed by a double quote:
// double up all the backslashes and escape the double quote
arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');

// Sequence of backslashes followed by the end of the string
// (which will become a double quote later):
// double up all the backslashes
arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1');

// All other backslashes occur literally

// Quote the whole thing:
arg = `"${arg}"`;

// Escape meta chars
arg = arg.replace(metaCharsRegExp, '^$1');

// Double escape meta chars if necessary
if (needsDoubleEscapeMetaChars) {
arg = arg.replace(metaCharsRegExp, '^$1');
}

return arg;
});

args = ['/d', '/s', '/c', `"${[command, ...args].join(' ')}"`];
command = options.env?.comspec ?? 'cmd.exe';
// Tell node's spawn that the arguments are already escaped
options = {...options, windowsVerbatimArguments: true};
}

return {command, args, options};
}

/**
* Resolves the command to an absolute path if possible.
* Handles things like traversing PATH and adding extensions from PATHEXT
*/
function resolveCommand(command: string, options: SpawnOptions): string | null {
const cwd = (options.cwd ?? getCwd()).toString();
const env = options.env ?? process.env;
const PATH = getPathFromEnv(env).value;

const pathEnv =
command.includes('/') || command.includes('\\')
? ['']
: [cwd, ...PATH.split(pathDelimiter)];
const pathExt = env.PATHEXT
? env.PATHEXT.split(pathDelimiter)
: defaultPathExt;

if (command.includes('.') && pathExt[0] !== '') {
pathExt.unshift('');
}

for (const path of pathEnv) {
const unquoted =
path.startsWith('"') && path.endsWith('"') && path.length > 1
? path.slice(1, -1)
: path;
const dest = resolvePath(cwd, unquoted, command);

for (const ext of pathExt) {
const destWithExt = dest + ext;

try {
if (statSync(destWithExt).isFile()) {
return destWithExt;
}
} catch {
// do nothing, it didn't exist
}
}
}

return null;
}
53 changes: 53 additions & 0 deletions src/test/normalize_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {normalizeSpawnCommand} from '../normalize.js';
import {describe, test, expect} from 'vitest';
import os from 'node:os';

const isWindows = os.platform() === 'win32';
const baseWindowsOptions = {
env: process.env
};

describe('normalizeSpawnCommand', () => {
test('return from arguments if `shell` option is `true`', () => {
expect(normalizeSpawnCommand('node', ['-v'], {shell: true})).toEqual({
command: 'node',
args: ['-v'],
options: {shell: true}
});
});

describe.runIf(isWindows)('windows only', () => {
test('just return the same input if resolved', () => {
const normalized = normalizeSpawnCommand(
'node',
['-v'],
baseWindowsOptions
);

expect(normalized.command).toBe('node');
expect(normalized.args).toEqual(['-v']);
});

test('use shell if command are not resolved/available', () => {
const normalized = normalizeSpawnCommand(
'notexist',
['hi'],
baseWindowsOptions
);

expect(normalized.command.endsWith('cmd.exe')).ok;
expect(normalized.args).toEqual(['/d', '/s', '/c', '"notexist ^"hi^""']);
expect(normalized.options.windowsVerbatimArguments).toBe(true);
});
});

describe.runIf(!isWindows)('unix only', () => {
test('return from arguments', () => {
expect(normalizeSpawnCommand('node', ['-v'])).toEqual({
command: 'node',
args: ['-v'],
options: {}
});
});
});
});
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"types": ["node"],
"declaration": true,
"outDir": "./lib",
"rootDir": "./src",
"importHelpers": false,
"isolatedModules": true,
"forceConsistentCasingInFileNames": true,
Expand Down