@socketsecurity/lib 1.1.2 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/dist/agent.js +3 -0
- package/dist/agent.js.map +2 -2
- package/dist/bin.js +7 -5
- package/dist/bin.js.map +2 -2
- package/dist/dlx-binary.d.ts +1 -0
- package/dist/dlx-binary.js +1 -1
- package/dist/dlx-binary.js.map +2 -2
- package/dist/dlx-package.d.ts +35 -0
- package/dist/dlx-package.js +151 -0
- package/dist/dlx-package.js.map +7 -0
- package/dist/external/libnpmpack.js +70 -72
- package/dist/fs.d.ts +48 -0
- package/dist/fs.js +18 -0
- package/dist/fs.js.map +2 -2
- package/dist/git.js +3 -2
- package/dist/git.js.map +2 -2
- package/dist/path.js +11 -3
- package/dist/path.js.map +2 -2
- package/dist/paths.js.map +2 -2
- package/dist/temporary-executor.js +2 -1
- package/dist/temporary-executor.js.map +2 -2
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,34 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [1.3.0](https://github.com/SocketDev/socket-lib/releases/tag/v1.3.0) - 2025-10-23
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Added `validateFiles()` utility function to `fs` module for defensive file access validation
|
|
13
|
+
- Returns `ValidateFilesResult` with `validPaths` and `invalidPaths` arrays
|
|
14
|
+
- Filters out unreadable files before processing (common with Yarn Berry PnP virtual filesystem, pnpm symlinks)
|
|
15
|
+
- Prevents ENOENT errors when files exist in glob results but are not accessible
|
|
16
|
+
- Comprehensive test coverage for all validation scenarios
|
|
17
|
+
|
|
18
|
+
## [1.2.0](https://github.com/SocketDev/socket-lib/releases/tag/v1.2.0) - 2025-10-23
|
|
19
|
+
|
|
20
|
+
### Added
|
|
21
|
+
|
|
22
|
+
- Added `dlx-package` module for installing and executing npm packages directly
|
|
23
|
+
- Content-addressed caching using SHA256 hash (like npm's _npx)
|
|
24
|
+
- Auto-force for version ranges (^, ~, >, <) to get latest within range
|
|
25
|
+
- Cross-platform support with comprehensive tests (30 tests)
|
|
26
|
+
- Parses scoped and unscoped package specs correctly
|
|
27
|
+
- Resolves binaries from package.json bin field
|
|
28
|
+
|
|
29
|
+
### Changed
|
|
30
|
+
|
|
31
|
+
- Unified DLX storage under `~/.socket/_dlx/` directory
|
|
32
|
+
- Binary downloads now use `~/.socket/_dlx/` instead of non-existent cache path
|
|
33
|
+
- Both npm packages and binaries share parent directory with content-addressed hashing
|
|
34
|
+
- Updated paths.ts documentation to clarify unified directory structure
|
|
35
|
+
|
|
8
36
|
## [1.1.2] - 2025-10-23
|
|
9
37
|
|
|
10
38
|
### Fixed
|
package/dist/agent.js
CHANGED
|
@@ -34,6 +34,7 @@ __export(agent_exports, {
|
|
|
34
34
|
});
|
|
35
35
|
module.exports = __toCommonJS(agent_exports);
|
|
36
36
|
var import_ci = require("#env/ci");
|
|
37
|
+
var import_platform = require("#constants/platform");
|
|
37
38
|
var import_bin = require("./bin");
|
|
38
39
|
var import_debug = require("./debug");
|
|
39
40
|
var import_fs = require("./fs");
|
|
@@ -105,6 +106,8 @@ function execNpm(args, options) {
|
|
|
105
106
|
],
|
|
106
107
|
{
|
|
107
108
|
__proto__: null,
|
|
109
|
+
// On Windows, npm is a .cmd file that requires shell to execute.
|
|
110
|
+
shell: import_platform.WIN32,
|
|
108
111
|
...options
|
|
109
112
|
}
|
|
110
113
|
);
|
package/dist/agent.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/agent.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Package manager agent for executing npm, pnpm, and yarn commands.\n * Provides cross-platform utilities with optimized flags and security defaults.\n *\n * SECURITY: Array-Based Arguments Prevent Command Injection\n *\n * All functions in this module (execNpm, execPnpm, execYarn) use array-based\n * arguments when calling spawn(). This is the PRIMARY DEFENSE against command\n * injection attacks.\n *\n * When arguments are passed as an array:\n * spawn(cmd, ['install', packageName, '--flag'], options)\n *\n * Node.js handles escaping automatically. Each argument is passed directly to\n * the OS without shell interpretation. Shell metacharacters like ; | & $ ( )\n * are treated as LITERAL STRINGS, not as commands.\n *\n * Example: If packageName = \"lodash; rm -rf /\", the package manager will try to\n * install a package literally named \"lodash; rm -rf /\" (which doesn't exist),\n * rather than executing the malicious command.\n *\n * This approach is secure even when shell: true is used on Windows for .cmd\n * file resolution, because Node.js properly escapes each array element.\n */\n\nimport { CI } from '#env/ci'\n\nimport { execBin } from './bin'\nimport { isDebug } from './debug'\nimport { findUpSync } from './fs'\nimport { getOwn } from './objects'\nimport type { SpawnOptions } from './spawn'\nimport { spawn } from './spawn'\n\n// Note: npm flag checking is done with regex patterns in the is*Flag functions below.\n\nconst pnpmIgnoreScriptsFlags = new Set([\n '--ignore-scripts',\n '--no-ignore-scripts',\n])\n\nconst pnpmFrozenLockfileFlags = new Set([\n '--frozen-lockfile',\n '--no-frozen-lockfile',\n])\n\nconst pnpmInstallCommands = new Set(['install', 'i'])\n\n// Commands that support --ignore-scripts flag in pnpm:\n// Installation-related: install, add, update, remove, link, unlink, import, rebuild.\nconst pnpmInstallLikeCommands = new Set([\n 'install',\n 'i',\n 'add',\n 'update',\n 'up',\n 'remove',\n 'rm',\n 'link',\n 'ln',\n 'unlink',\n 'import',\n 'rebuild',\n 'rb',\n])\n\n// Commands that support --ignore-scripts flag in yarn:\n// Similar to npm/pnpm: installation-related commands.\nconst yarnInstallLikeCommands = new Set([\n 'install',\n 'add',\n 'upgrade',\n 'remove',\n 'link',\n 'unlink',\n 'import',\n])\n\n/**\n * Execute npm commands with optimized flags and settings.\n *\n * SECURITY: Uses array-based arguments to prevent command injection. All elements\n * in the args array are properly escaped by Node.js when passed to spawn().\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function execNpm(args: string[], options?: SpawnOptions | undefined) {\n const useDebug = isDebug()\n const terminatorPos = args.indexOf('--')\n const npmArgs = (\n terminatorPos === -1 ? args : args.slice(0, terminatorPos)\n ).filter(\n (a: string) =>\n !isNpmAuditFlag(a) && !isNpmFundFlag(a) && !isNpmProgressFlag(a),\n )\n const otherArgs = terminatorPos === -1 ? [] : args.slice(terminatorPos)\n const logLevelArgs =\n // The default value of loglevel is \"notice\". We default to \"warn\" which is\n // one level quieter.\n useDebug || npmArgs.some(isNpmLoglevelFlag) ? [] : ['--loglevel', 'warn']\n // SECURITY: Array-based arguments prevent command injection. Each element is\n // passed directly to the OS without shell interpretation.\n //\n // NOTE: We don't apply hardening flags to npm because:\n // 1. npm is a trusted system tool installed with Node.js\n // 2. npm requires full system access (filesystem, network, child processes)\n // 3. Hardening flags would prevent npm from functioning (even with --allow-* grants)\n // 4. The permission model is intended for untrusted user code, not package managers\n //\n // We also use the npm binary wrapper instead of calling cli.js directly because\n // cli.js exports a function that needs to be invoked with process as an argument.\n const npmBin = /*@__PURE__*/ require('../constants/agents').NPM_BIN_PATH\n return spawn(\n npmBin,\n [\n // Even though '--loglevel=error' is passed npm will still run through\n // code paths for 'audit' and 'fund' unless '--no-audit' and '--no-fund'\n // flags are passed.\n '--no-audit',\n '--no-fund',\n // Add `--no-progress` and `--silent` flags to fix input being swallowed\n // by the spinner when running the command with recent versions of npm.\n '--no-progress',\n // Add '--loglevel=error' if a loglevel flag is not provided and the\n // SOCKET_DEBUG environment variable is not truthy.\n ...logLevelArgs,\n ...npmArgs,\n ...otherArgs,\n ],\n {\n __proto__: null,\n ...options,\n } as SpawnOptions,\n )\n}\n\nexport interface PnpmOptions extends SpawnOptions {\n allowLockfileUpdate?: boolean\n}\n\n/**\n * Execute pnpm commands with optimized flags and settings.\n *\n * SECURITY: Uses array-based arguments to prevent command injection. All elements\n * in the args array are properly escaped by Node.js when passed to execBin().\n */\n/*@__NO_SIDE_EFFECTS__*/\n\nexport function execPnpm(args: string[], options?: PnpmOptions | undefined) {\n const { allowLockfileUpdate, ...extBinOpts } = {\n __proto__: null,\n ...options,\n } as PnpmOptions\n const useDebug = isDebug()\n const terminatorPos = args.indexOf('--')\n const pnpmArgs = (\n terminatorPos === -1 ? args : args.slice(0, terminatorPos)\n ).filter((a: string) => !isNpmProgressFlag(a))\n const otherArgs = terminatorPos === -1 ? [] : args.slice(terminatorPos)\n\n const firstArg = pnpmArgs[0]\n const supportsIgnoreScripts = firstArg\n ? pnpmInstallLikeCommands.has(firstArg)\n : false\n\n // pnpm uses --loglevel for all commands.\n const logLevelArgs =\n useDebug || pnpmArgs.some(isPnpmLoglevelFlag) ? [] : ['--loglevel', 'warn']\n\n // Only add --ignore-scripts for commands that support it.\n const hasIgnoreScriptsFlag = pnpmArgs.some(isPnpmIgnoreScriptsFlag)\n const ignoreScriptsArgs =\n !supportsIgnoreScripts || hasIgnoreScriptsFlag ? [] : ['--ignore-scripts']\n\n // In CI environments, pnpm uses --frozen-lockfile by default which prevents lockfile updates.\n // For commands that need to update the lockfile (like install with new packages/overrides),\n // we need to explicitly add --no-frozen-lockfile in CI mode if not already present.\n const frozenLockfileArgs = []\n if (\n CI &&\n allowLockfileUpdate &&\n firstArg &&\n isPnpmInstallCommand(firstArg) &&\n !pnpmArgs.some(isPnpmFrozenLockfileFlag)\n ) {\n frozenLockfileArgs.push('--no-frozen-lockfile')\n }\n\n // Note: pnpm doesn't have a --no-progress flag. It uses --reporter instead.\n // We removed --no-progress as it causes \"Unknown option\" errors with pnpm.\n\n // SECURITY: Array-based arguments prevent command injection. Each element is\n // passed directly to the OS without shell interpretation.\n return execBin(\n 'pnpm',\n [\n // Add '--loglevel=warn' if a loglevel flag is not provided and debug is off.\n ...logLevelArgs,\n // Add '--ignore-scripts' by default for security (only for installation commands).\n ...ignoreScriptsArgs,\n // Add '--no-frozen-lockfile' in CI when lockfile updates are needed.\n ...frozenLockfileArgs,\n ...pnpmArgs,\n ...otherArgs,\n ],\n extBinOpts,\n )\n}\n\n/**\n * Execute yarn commands with optimized flags and settings.\n *\n * SECURITY: Uses array-based arguments to prevent command injection. All elements\n * in the args array are properly escaped by Node.js when passed to execBin().\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function execYarn(\n args: string[],\n options?: import('./spawn').SpawnOptions,\n) {\n const useDebug = isDebug()\n const terminatorPos = args.indexOf('--')\n const yarnArgs = (\n terminatorPos === -1 ? args : args.slice(0, terminatorPos)\n ).filter((a: string) => !isNpmProgressFlag(a))\n const otherArgs = terminatorPos === -1 ? [] : args.slice(terminatorPos)\n\n const firstArg = yarnArgs[0]\n const supportsIgnoreScripts = firstArg\n ? yarnInstallLikeCommands.has(firstArg)\n : false\n\n // Yarn uses --silent flag for quieter output.\n const logLevelArgs =\n useDebug || yarnArgs.some(isNpmLoglevelFlag) ? [] : ['--silent']\n\n // Only add --ignore-scripts for commands that support it.\n const hasIgnoreScriptsFlag = yarnArgs.some(isPnpmIgnoreScriptsFlag)\n const ignoreScriptsArgs =\n !supportsIgnoreScripts || hasIgnoreScriptsFlag ? [] : ['--ignore-scripts']\n\n // SECURITY: Array-based arguments prevent command injection. Each element is\n // passed directly to the OS without shell interpretation.\n return execBin(\n 'yarn',\n [\n // Add '--silent' if a loglevel flag is not provided and debug is off.\n ...logLevelArgs,\n // Add '--ignore-scripts' by default for security (only for installation commands).\n ...ignoreScriptsArgs,\n ...yarnArgs,\n ...otherArgs,\n ],\n {\n __proto__: null,\n ...options,\n } as SpawnOptions,\n )\n}\n\n/**\n * Check if a command argument is an npm audit flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isNpmAuditFlag(cmdArg: string): boolean {\n return /^--(no-)?audit(=.*)?$/.test(cmdArg)\n}\n\n/**\n * Check if a command argument is an npm fund flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isNpmFundFlag(cmdArg: string): boolean {\n return /^--(no-)?fund(=.*)?$/.test(cmdArg)\n}\n\n/**\n * Check if a command argument is an npm loglevel flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isNpmLoglevelFlag(cmdArg: string): boolean {\n // https://docs.npmjs.com/cli/v11/using-npm/logging#setting-log-levels\n if (/^--loglevel(=.*)?$/.test(cmdArg)) {\n return true\n }\n // Check for long form flags\n if (/^--(silent|verbose|info|warn|error|quiet)$/.test(cmdArg)) {\n return true\n }\n // Check for shorthand flags\n return /^-(s|q|d|dd|ddd|v)$/.test(cmdArg)\n}\n\n/**\n * Check if a command argument is an npm node-options flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isNpmNodeOptionsFlag(cmdArg: string): boolean {\n // https://docs.npmjs.com/cli/v9/using-npm/config#node-options\n return /^--node-options(=.*)?$/.test(cmdArg)\n}\n\n/**\n * Check if a command argument is an npm progress flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isNpmProgressFlag(cmdArg: string): boolean {\n return /^--(no-)?progress(=.*)?$/.test(cmdArg)\n}\n\n/**\n * Check if a command argument is a pnpm ignore-scripts flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isPnpmIgnoreScriptsFlag(cmdArg: string): boolean {\n return pnpmIgnoreScriptsFlags.has(cmdArg)\n}\n\n/**\n * Check if a command argument is a pnpm frozen-lockfile flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isPnpmFrozenLockfileFlag(cmdArg: string): boolean {\n return pnpmFrozenLockfileFlags.has(cmdArg)\n}\n\n/**\n * Check if a command argument is a pnpm install command.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isPnpmInstallCommand(cmdArg: string): boolean {\n return pnpmInstallCommands.has(cmdArg)\n}\n\n/**\n * Alias for isNpmLoglevelFlag for pnpm usage.\n */\nexport const isPnpmLoglevelFlag = isNpmLoglevelFlag\n\n/**\n * Execute a package.json script using the appropriate package manager.\n * Automatically detects pnpm, yarn, or npm based on lockfiles.\n */\nexport interface ExecScriptOptions extends SpawnOptions {\n prepost?: boolean | undefined\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nexport function execScript(\n scriptName: string,\n args?: string[] | readonly string[] | ExecScriptOptions | undefined,\n options?: ExecScriptOptions | undefined,\n) {\n // Handle overloaded signatures: execScript(name, options) or execScript(name, args, options).\n let resolvedOptions: ExecScriptOptions | undefined\n let resolvedArgs: string[]\n if (!Array.isArray(args) && args !== null && typeof args === 'object') {\n resolvedOptions = args as ExecScriptOptions\n resolvedArgs = []\n } else {\n resolvedOptions = options\n resolvedArgs = (args || []) as string[]\n }\n const { prepost, ...spawnOptions } = {\n __proto__: null,\n ...resolvedOptions,\n } as ExecScriptOptions\n\n // If shell: true is passed, run the command directly as a shell command.\n if (spawnOptions.shell === true) {\n return spawn(scriptName, resolvedArgs, spawnOptions)\n }\n\n const useNodeRun =\n !prepost && /*@__PURE__*/ require('../constants/node').SUPPORTS_NODE_RUN\n\n // Detect package manager based on lockfile by traversing up from current directory.\n const cwd =\n (getOwn(spawnOptions, 'cwd') as string | undefined) ?? process.cwd()\n\n // Check for pnpm-lock.yaml.\n const pnpmLockPath = findUpSync(\n /*@__INLINE__*/ require('../constants/agents').PNPM_LOCK_YAML,\n { cwd },\n ) as string | undefined\n if (pnpmLockPath) {\n return execPnpm(['run', scriptName, ...resolvedArgs], spawnOptions)\n }\n\n // Check for package-lock.json.\n // When in an npm workspace, use npm run to ensure workspace binaries are available.\n const packageLockPath = findUpSync(\n /*@__INLINE__*/ require('../constants/agents').PACKAGE_LOCK_JSON,\n { cwd },\n ) as string | undefined\n if (packageLockPath) {\n return execNpm(['run', scriptName, ...resolvedArgs], spawnOptions)\n }\n\n // Check for yarn.lock.\n const yarnLockPath = findUpSync(\n /*@__INLINE__*/ require('../constants/agents').YARN_LOCK,\n { cwd },\n ) as string | undefined\n if (yarnLockPath) {\n return execYarn(['run', scriptName, ...resolvedArgs], spawnOptions)\n }\n\n return spawn(\n /*@__PURE__*/ require('../constants/node').getExecPath(),\n [\n .../*@__PURE__*/ require('../constants/node').getNodeNoWarningsFlags(),\n ...(useNodeRun\n ? ['--run']\n : [\n /*@__PURE__*/ require('../constants/agents').NPM_REAL_EXEC_PATH,\n 'run',\n ]),\n scriptName,\n ...resolvedArgs,\n ],\n {\n ...spawnOptions,\n },\n )\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyBA,gBAAmB;AAEnB,iBAAwB;AACxB,mBAAwB;AACxB,gBAA2B;AAC3B,qBAAuB;AAEvB,mBAAsB;AAItB,MAAM,yBAAyB,oBAAI,IAAI;AAAA,EACrC;AAAA,EACA;AACF,CAAC;AAED,MAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AACF,CAAC;AAED,MAAM,sBAAsB,oBAAI,IAAI,CAAC,WAAW,GAAG,CAAC;AAIpD,MAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAID,MAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAAA;AASM,SAAS,QAAQ,MAAgB,SAAoC;AAC1E,QAAM,eAAW,sBAAQ;AACzB,QAAM,gBAAgB,KAAK,QAAQ,IAAI;AACvC,QAAM,WACJ,kBAAkB,KAAK,OAAO,KAAK,MAAM,GAAG,aAAa,GACzD;AAAA,IACA,CAAC,MACC,CAAC,+BAAe,CAAC,KAAK,CAAC,8BAAc,CAAC,KAAK,CAAC,kCAAkB,CAAC;AAAA,EACnE;AACA,QAAM,YAAY,kBAAkB,KAAK,CAAC,IAAI,KAAK,MAAM,aAAa;AACtE,QAAM;AAAA;AAAA;AAAA,IAGJ,YAAY,QAAQ,KAAK,iBAAiB,IAAI,CAAC,IAAI,CAAC,cAAc,MAAM;AAAA;AAY1E,QAAM,SAAuB,QAAQ,qBAAqB,EAAE;AAC5D,aAAO;AAAA,IACL;AAAA,IACA;AAAA;AAAA;AAAA;AAAA,MAIE;AAAA,MACA;AAAA;AAAA;AAAA,MAGA;AAAA;AAAA;AAAA,MAGA,GAAG;AAAA,MACH,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,IACA;AAAA,MACE,WAAW;AAAA,
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Package manager agent for executing npm, pnpm, and yarn commands.\n * Provides cross-platform utilities with optimized flags and security defaults.\n *\n * SECURITY: Array-Based Arguments Prevent Command Injection\n *\n * All functions in this module (execNpm, execPnpm, execYarn) use array-based\n * arguments when calling spawn(). This is the PRIMARY DEFENSE against command\n * injection attacks.\n *\n * When arguments are passed as an array:\n * spawn(cmd, ['install', packageName, '--flag'], options)\n *\n * Node.js handles escaping automatically. Each argument is passed directly to\n * the OS without shell interpretation. Shell metacharacters like ; | & $ ( )\n * are treated as LITERAL STRINGS, not as commands.\n *\n * Example: If packageName = \"lodash; rm -rf /\", the package manager will try to\n * install a package literally named \"lodash; rm -rf /\" (which doesn't exist),\n * rather than executing the malicious command.\n *\n * This approach is secure even when shell: true is used on Windows for .cmd\n * file resolution, because Node.js properly escapes each array element.\n */\n\nimport { CI } from '#env/ci'\n\nimport { WIN32 } from '#constants/platform'\nimport { execBin } from './bin'\nimport { isDebug } from './debug'\nimport { findUpSync } from './fs'\nimport { getOwn } from './objects'\nimport type { SpawnOptions } from './spawn'\nimport { spawn } from './spawn'\n\n// Note: npm flag checking is done with regex patterns in the is*Flag functions below.\n\nconst pnpmIgnoreScriptsFlags = new Set([\n '--ignore-scripts',\n '--no-ignore-scripts',\n])\n\nconst pnpmFrozenLockfileFlags = new Set([\n '--frozen-lockfile',\n '--no-frozen-lockfile',\n])\n\nconst pnpmInstallCommands = new Set(['install', 'i'])\n\n// Commands that support --ignore-scripts flag in pnpm:\n// Installation-related: install, add, update, remove, link, unlink, import, rebuild.\nconst pnpmInstallLikeCommands = new Set([\n 'install',\n 'i',\n 'add',\n 'update',\n 'up',\n 'remove',\n 'rm',\n 'link',\n 'ln',\n 'unlink',\n 'import',\n 'rebuild',\n 'rb',\n])\n\n// Commands that support --ignore-scripts flag in yarn:\n// Similar to npm/pnpm: installation-related commands.\nconst yarnInstallLikeCommands = new Set([\n 'install',\n 'add',\n 'upgrade',\n 'remove',\n 'link',\n 'unlink',\n 'import',\n])\n\n/**\n * Execute npm commands with optimized flags and settings.\n *\n * SECURITY: Uses array-based arguments to prevent command injection. All elements\n * in the args array are properly escaped by Node.js when passed to spawn().\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function execNpm(args: string[], options?: SpawnOptions | undefined) {\n const useDebug = isDebug()\n const terminatorPos = args.indexOf('--')\n const npmArgs = (\n terminatorPos === -1 ? args : args.slice(0, terminatorPos)\n ).filter(\n (a: string) =>\n !isNpmAuditFlag(a) && !isNpmFundFlag(a) && !isNpmProgressFlag(a),\n )\n const otherArgs = terminatorPos === -1 ? [] : args.slice(terminatorPos)\n const logLevelArgs =\n // The default value of loglevel is \"notice\". We default to \"warn\" which is\n // one level quieter.\n useDebug || npmArgs.some(isNpmLoglevelFlag) ? [] : ['--loglevel', 'warn']\n // SECURITY: Array-based arguments prevent command injection. Each element is\n // passed directly to the OS without shell interpretation.\n //\n // NOTE: We don't apply hardening flags to npm because:\n // 1. npm is a trusted system tool installed with Node.js\n // 2. npm requires full system access (filesystem, network, child processes)\n // 3. Hardening flags would prevent npm from functioning (even with --allow-* grants)\n // 4. The permission model is intended for untrusted user code, not package managers\n //\n // We also use the npm binary wrapper instead of calling cli.js directly because\n // cli.js exports a function that needs to be invoked with process as an argument.\n const npmBin = /*@__PURE__*/ require('../constants/agents').NPM_BIN_PATH\n return spawn(\n npmBin,\n [\n // Even though '--loglevel=error' is passed npm will still run through\n // code paths for 'audit' and 'fund' unless '--no-audit' and '--no-fund'\n // flags are passed.\n '--no-audit',\n '--no-fund',\n // Add `--no-progress` and `--silent` flags to fix input being swallowed\n // by the spinner when running the command with recent versions of npm.\n '--no-progress',\n // Add '--loglevel=error' if a loglevel flag is not provided and the\n // SOCKET_DEBUG environment variable is not truthy.\n ...logLevelArgs,\n ...npmArgs,\n ...otherArgs,\n ],\n {\n __proto__: null,\n // On Windows, npm is a .cmd file that requires shell to execute.\n shell: WIN32,\n ...options,\n } as SpawnOptions,\n )\n}\n\nexport interface PnpmOptions extends SpawnOptions {\n allowLockfileUpdate?: boolean\n}\n\n/**\n * Execute pnpm commands with optimized flags and settings.\n *\n * SECURITY: Uses array-based arguments to prevent command injection. All elements\n * in the args array are properly escaped by Node.js when passed to execBin().\n */\n/*@__NO_SIDE_EFFECTS__*/\n\nexport function execPnpm(args: string[], options?: PnpmOptions | undefined) {\n const { allowLockfileUpdate, ...extBinOpts } = {\n __proto__: null,\n ...options,\n } as PnpmOptions\n const useDebug = isDebug()\n const terminatorPos = args.indexOf('--')\n const pnpmArgs = (\n terminatorPos === -1 ? args : args.slice(0, terminatorPos)\n ).filter((a: string) => !isNpmProgressFlag(a))\n const otherArgs = terminatorPos === -1 ? [] : args.slice(terminatorPos)\n\n const firstArg = pnpmArgs[0]\n const supportsIgnoreScripts = firstArg\n ? pnpmInstallLikeCommands.has(firstArg)\n : false\n\n // pnpm uses --loglevel for all commands.\n const logLevelArgs =\n useDebug || pnpmArgs.some(isPnpmLoglevelFlag) ? [] : ['--loglevel', 'warn']\n\n // Only add --ignore-scripts for commands that support it.\n const hasIgnoreScriptsFlag = pnpmArgs.some(isPnpmIgnoreScriptsFlag)\n const ignoreScriptsArgs =\n !supportsIgnoreScripts || hasIgnoreScriptsFlag ? [] : ['--ignore-scripts']\n\n // In CI environments, pnpm uses --frozen-lockfile by default which prevents lockfile updates.\n // For commands that need to update the lockfile (like install with new packages/overrides),\n // we need to explicitly add --no-frozen-lockfile in CI mode if not already present.\n const frozenLockfileArgs = []\n if (\n CI &&\n allowLockfileUpdate &&\n firstArg &&\n isPnpmInstallCommand(firstArg) &&\n !pnpmArgs.some(isPnpmFrozenLockfileFlag)\n ) {\n frozenLockfileArgs.push('--no-frozen-lockfile')\n }\n\n // Note: pnpm doesn't have a --no-progress flag. It uses --reporter instead.\n // We removed --no-progress as it causes \"Unknown option\" errors with pnpm.\n\n // SECURITY: Array-based arguments prevent command injection. Each element is\n // passed directly to the OS without shell interpretation.\n return execBin(\n 'pnpm',\n [\n // Add '--loglevel=warn' if a loglevel flag is not provided and debug is off.\n ...logLevelArgs,\n // Add '--ignore-scripts' by default for security (only for installation commands).\n ...ignoreScriptsArgs,\n // Add '--no-frozen-lockfile' in CI when lockfile updates are needed.\n ...frozenLockfileArgs,\n ...pnpmArgs,\n ...otherArgs,\n ],\n extBinOpts,\n )\n}\n\n/**\n * Execute yarn commands with optimized flags and settings.\n *\n * SECURITY: Uses array-based arguments to prevent command injection. All elements\n * in the args array are properly escaped by Node.js when passed to execBin().\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function execYarn(\n args: string[],\n options?: import('./spawn').SpawnOptions,\n) {\n const useDebug = isDebug()\n const terminatorPos = args.indexOf('--')\n const yarnArgs = (\n terminatorPos === -1 ? args : args.slice(0, terminatorPos)\n ).filter((a: string) => !isNpmProgressFlag(a))\n const otherArgs = terminatorPos === -1 ? [] : args.slice(terminatorPos)\n\n const firstArg = yarnArgs[0]\n const supportsIgnoreScripts = firstArg\n ? yarnInstallLikeCommands.has(firstArg)\n : false\n\n // Yarn uses --silent flag for quieter output.\n const logLevelArgs =\n useDebug || yarnArgs.some(isNpmLoglevelFlag) ? [] : ['--silent']\n\n // Only add --ignore-scripts for commands that support it.\n const hasIgnoreScriptsFlag = yarnArgs.some(isPnpmIgnoreScriptsFlag)\n const ignoreScriptsArgs =\n !supportsIgnoreScripts || hasIgnoreScriptsFlag ? [] : ['--ignore-scripts']\n\n // SECURITY: Array-based arguments prevent command injection. Each element is\n // passed directly to the OS without shell interpretation.\n return execBin(\n 'yarn',\n [\n // Add '--silent' if a loglevel flag is not provided and debug is off.\n ...logLevelArgs,\n // Add '--ignore-scripts' by default for security (only for installation commands).\n ...ignoreScriptsArgs,\n ...yarnArgs,\n ...otherArgs,\n ],\n {\n __proto__: null,\n ...options,\n } as SpawnOptions,\n )\n}\n\n/**\n * Check if a command argument is an npm audit flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isNpmAuditFlag(cmdArg: string): boolean {\n return /^--(no-)?audit(=.*)?$/.test(cmdArg)\n}\n\n/**\n * Check if a command argument is an npm fund flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isNpmFundFlag(cmdArg: string): boolean {\n return /^--(no-)?fund(=.*)?$/.test(cmdArg)\n}\n\n/**\n * Check if a command argument is an npm loglevel flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isNpmLoglevelFlag(cmdArg: string): boolean {\n // https://docs.npmjs.com/cli/v11/using-npm/logging#setting-log-levels\n if (/^--loglevel(=.*)?$/.test(cmdArg)) {\n return true\n }\n // Check for long form flags\n if (/^--(silent|verbose|info|warn|error|quiet)$/.test(cmdArg)) {\n return true\n }\n // Check for shorthand flags\n return /^-(s|q|d|dd|ddd|v)$/.test(cmdArg)\n}\n\n/**\n * Check if a command argument is an npm node-options flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isNpmNodeOptionsFlag(cmdArg: string): boolean {\n // https://docs.npmjs.com/cli/v9/using-npm/config#node-options\n return /^--node-options(=.*)?$/.test(cmdArg)\n}\n\n/**\n * Check if a command argument is an npm progress flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isNpmProgressFlag(cmdArg: string): boolean {\n return /^--(no-)?progress(=.*)?$/.test(cmdArg)\n}\n\n/**\n * Check if a command argument is a pnpm ignore-scripts flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isPnpmIgnoreScriptsFlag(cmdArg: string): boolean {\n return pnpmIgnoreScriptsFlags.has(cmdArg)\n}\n\n/**\n * Check if a command argument is a pnpm frozen-lockfile flag.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isPnpmFrozenLockfileFlag(cmdArg: string): boolean {\n return pnpmFrozenLockfileFlags.has(cmdArg)\n}\n\n/**\n * Check if a command argument is a pnpm install command.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isPnpmInstallCommand(cmdArg: string): boolean {\n return pnpmInstallCommands.has(cmdArg)\n}\n\n/**\n * Alias for isNpmLoglevelFlag for pnpm usage.\n */\nexport const isPnpmLoglevelFlag = isNpmLoglevelFlag\n\n/**\n * Execute a package.json script using the appropriate package manager.\n * Automatically detects pnpm, yarn, or npm based on lockfiles.\n */\nexport interface ExecScriptOptions extends SpawnOptions {\n prepost?: boolean | undefined\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nexport function execScript(\n scriptName: string,\n args?: string[] | readonly string[] | ExecScriptOptions | undefined,\n options?: ExecScriptOptions | undefined,\n) {\n // Handle overloaded signatures: execScript(name, options) or execScript(name, args, options).\n let resolvedOptions: ExecScriptOptions | undefined\n let resolvedArgs: string[]\n if (!Array.isArray(args) && args !== null && typeof args === 'object') {\n resolvedOptions = args as ExecScriptOptions\n resolvedArgs = []\n } else {\n resolvedOptions = options\n resolvedArgs = (args || []) as string[]\n }\n const { prepost, ...spawnOptions } = {\n __proto__: null,\n ...resolvedOptions,\n } as ExecScriptOptions\n\n // If shell: true is passed, run the command directly as a shell command.\n if (spawnOptions.shell === true) {\n return spawn(scriptName, resolvedArgs, spawnOptions)\n }\n\n const useNodeRun =\n !prepost && /*@__PURE__*/ require('../constants/node').SUPPORTS_NODE_RUN\n\n // Detect package manager based on lockfile by traversing up from current directory.\n const cwd =\n (getOwn(spawnOptions, 'cwd') as string | undefined) ?? process.cwd()\n\n // Check for pnpm-lock.yaml.\n const pnpmLockPath = findUpSync(\n /*@__INLINE__*/ require('../constants/agents').PNPM_LOCK_YAML,\n { cwd },\n ) as string | undefined\n if (pnpmLockPath) {\n return execPnpm(['run', scriptName, ...resolvedArgs], spawnOptions)\n }\n\n // Check for package-lock.json.\n // When in an npm workspace, use npm run to ensure workspace binaries are available.\n const packageLockPath = findUpSync(\n /*@__INLINE__*/ require('../constants/agents').PACKAGE_LOCK_JSON,\n { cwd },\n ) as string | undefined\n if (packageLockPath) {\n return execNpm(['run', scriptName, ...resolvedArgs], spawnOptions)\n }\n\n // Check for yarn.lock.\n const yarnLockPath = findUpSync(\n /*@__INLINE__*/ require('../constants/agents').YARN_LOCK,\n { cwd },\n ) as string | undefined\n if (yarnLockPath) {\n return execYarn(['run', scriptName, ...resolvedArgs], spawnOptions)\n }\n\n return spawn(\n /*@__PURE__*/ require('../constants/node').getExecPath(),\n [\n .../*@__PURE__*/ require('../constants/node').getNodeNoWarningsFlags(),\n ...(useNodeRun\n ? ['--run']\n : [\n /*@__PURE__*/ require('../constants/agents').NPM_REAL_EXEC_PATH,\n 'run',\n ]),\n scriptName,\n ...resolvedArgs,\n ],\n {\n ...spawnOptions,\n },\n )\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyBA,gBAAmB;AAEnB,sBAAsB;AACtB,iBAAwB;AACxB,mBAAwB;AACxB,gBAA2B;AAC3B,qBAAuB;AAEvB,mBAAsB;AAItB,MAAM,yBAAyB,oBAAI,IAAI;AAAA,EACrC;AAAA,EACA;AACF,CAAC;AAED,MAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AACF,CAAC;AAED,MAAM,sBAAsB,oBAAI,IAAI,CAAC,WAAW,GAAG,CAAC;AAIpD,MAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC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,6 +33,7 @@ var import_appdata = require("#env/appdata");
|
|
|
33
33
|
var import_home = require("#env/home");
|
|
34
34
|
var import_localappdata = require("#env/localappdata");
|
|
35
35
|
var import_xdg_data_home = require("#env/xdg-data-home");
|
|
36
|
+
var import_platform = require("#constants/platform");
|
|
36
37
|
var import_fs = require("./fs");
|
|
37
38
|
var import_objects = require("./objects");
|
|
38
39
|
var import_path = require("./path");
|
|
@@ -70,7 +71,10 @@ async function execBin(binPath, args, options) {
|
|
|
70
71
|
throw error;
|
|
71
72
|
}
|
|
72
73
|
const binCommand = Array.isArray(resolvedPath) ? resolvedPath[0] : resolvedPath;
|
|
73
|
-
return await (0, import_spawn.spawn)(binCommand, args ?? [],
|
|
74
|
+
return await (0, import_spawn.spawn)(binCommand, args ?? [], {
|
|
75
|
+
shell: import_platform.WIN32,
|
|
76
|
+
...options
|
|
77
|
+
});
|
|
74
78
|
}
|
|
75
79
|
async function whichBin(binName, options) {
|
|
76
80
|
const which = /* @__PURE__ */ getWhich();
|
|
@@ -150,9 +154,8 @@ function findRealNpm() {
|
|
|
150
154
|
return "npm";
|
|
151
155
|
}
|
|
152
156
|
function findRealPnpm() {
|
|
153
|
-
const WIN32 = require("./constants/platform").WIN32;
|
|
154
157
|
const path = /* @__PURE__ */ getPath();
|
|
155
|
-
const commonPaths = WIN32 ? [
|
|
158
|
+
const commonPaths = import_platform.WIN32 ? [
|
|
156
159
|
// Windows common paths.
|
|
157
160
|
path?.join(import_appdata.APPDATA, "npm", "pnpm.cmd"),
|
|
158
161
|
path?.join(import_appdata.APPDATA, "npm", "pnpm"),
|
|
@@ -260,8 +263,7 @@ function resolveBinPathSync(binPath) {
|
|
|
260
263
|
return voltaBinPath;
|
|
261
264
|
}
|
|
262
265
|
}
|
|
263
|
-
|
|
264
|
-
if (WIN32) {
|
|
266
|
+
if (import_platform.WIN32) {
|
|
265
267
|
const hasKnownExt = extLowered === "" || extLowered === ".cmd" || extLowered === ".exe" || extLowered === ".ps1";
|
|
266
268
|
const isNpmOrNpx = basename === "npm" || basename === "npx";
|
|
267
269
|
const isPnpmOrYarn = basename === "pnpm" || basename === "yarn";
|
package/dist/bin.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/bin.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Binary path resolution and execution utilities for package managers.\n * Provides cross-platform bin path lookup, command execution, and path normalization.\n */\n\nimport { APPDATA } from '#env/appdata'\nimport { HOME } from '#env/home'\nimport { LOCALAPPDATA } from '#env/localappdata'\nimport { XDG_DATA_HOME } from '#env/xdg-data-home'\n\nimport { readJsonSync } from './fs'\nimport { getOwn } from './objects'\nimport { isPath, normalizePath } from './path'\nimport { spawn } from './spawn'\n\nlet _fs: typeof import('node:fs') | undefined\n/**\n * Lazily load the fs module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getFs() {\n if (_fs === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _fs = /*@__PURE__*/ require('node:fs')\n }\n return _fs!\n}\n\nlet _path: typeof import('node:path') | undefined\n/**\n * Lazily load the path module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPath() {\n if (_path === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _path = /*@__PURE__*/ require('node:path')\n }\n return _path!\n}\n\nlet _which: typeof import('which') | undefined\n/**\n * Lazily load the which module for finding executables.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getWhich() {\n if (_which === undefined) {\n _which = /*@__PURE__*/ require('./external/which')\n }\n return _which!\n}\n\n/**\n * Execute a binary with the given arguments.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function execBin(\n binPath: string,\n args?: string[],\n options?: import('./spawn').SpawnOptions,\n) {\n // Resolve the binary path.\n const resolvedPath = isPath(binPath)\n ? resolveBinPathSync(binPath)\n : await whichBin(binPath)\n\n if (!resolvedPath) {\n const error = new Error(`Binary not found: ${binPath}`) as Error & {\n code: string\n }\n error.code = 'ENOENT'\n throw error\n }\n\n // Execute the binary directly.\n const binCommand = Array.isArray(resolvedPath)\n ? resolvedPath[0]!\n : resolvedPath\n return await spawn(binCommand, args ?? [], options)\n}\n\n/**\n * Find and resolve a binary in the system PATH asynchronously.\n * @template {import('which').Options} T\n * @throws {Error} If the binary is not found and nothrow is false.\n */\nexport async function whichBin(\n binName: string,\n options?: import('which').Options,\n): Promise<string | string[] | undefined> {\n const which = getWhich()\n // Default to nothrow: true if not specified to return undefined instead of throwing\n const opts = { nothrow: true, ...options }\n // Depending on options `which` may throw if `binName` is not found.\n // With nothrow: true, it returns null when `binName` is not found.\n const result = await which?.(binName, opts)\n\n // When 'all: true' is specified, ensure we always return an array.\n if (options?.all) {\n const paths = Array.isArray(result)\n ? result\n : typeof result === 'string'\n ? [result]\n : undefined\n // If all is true and we have paths, resolve each one.\n return paths?.length ? paths.map(p => resolveBinPathSync(p)) : paths\n }\n\n // If result is undefined (binary not found), return undefined\n if (!result) {\n return undefined\n }\n\n return resolveBinPathSync(result)\n}\n\n/**\n * Find and resolve a binary in the system PATH synchronously.\n * @template {import('which').Options} T\n * @throws {Error} If the binary is not found and nothrow is false.\n */\nexport function whichBinSync(\n binName: string,\n options?: import('which').Options,\n): string | string[] | undefined {\n // Default to nothrow: true if not specified to return undefined instead of throwing\n const opts = { nothrow: true, ...options }\n // Depending on options `which` may throw if `binName` is not found.\n // With nothrow: true, it returns null when `binName` is not found.\n const result = getWhich()?.sync(binName, opts)\n\n // When 'all: true' is specified, ensure we always return an array.\n if (getOwn(options, 'all')) {\n const paths = Array.isArray(result)\n ? result\n : typeof result === 'string'\n ? [result]\n : undefined\n // If all is true and we have paths, resolve each one.\n return paths?.length ? paths.map(p => resolveBinPathSync(p)) : paths\n }\n\n // If result is undefined (binary not found), return undefined\n if (!result) {\n return undefined\n }\n\n return resolveBinPathSync(result)\n}\n\n/**\n * Check if a directory path contains any shadow bin patterns.\n */\nexport function isShadowBinPath(dirPath: string | undefined): boolean {\n if (!dirPath) {\n return false\n }\n // Check for node_modules/.bin pattern (Unix and Windows)\n const normalized = dirPath.replace(/\\\\/g, '/')\n return normalized.includes('node_modules/.bin')\n}\n\n/**\n * Find the real executable for a binary, bypassing shadow bins.\n */\nexport function findRealBin(\n binName: string,\n commonPaths: string[] = [],\n): string | undefined {\n const fs = getFs()\n const path = getPath()\n const which = getWhich()\n\n // Try common locations first.\n for (const binPath of commonPaths) {\n if (fs?.existsSync(binPath)) {\n return binPath\n }\n }\n\n // Fall back to which.sync if no direct path found.\n const binPath = which?.sync(binName, { nothrow: true })\n if (binPath) {\n const binDir = path?.dirname(binPath)\n\n if (isShadowBinPath(binDir)) {\n // This is likely a shadowed binary, try to find the real one.\n const allPaths = which?.sync(binName, { all: true, nothrow: true }) || []\n // Ensure allPaths is an array.\n const pathsArray = Array.isArray(allPaths)\n ? allPaths\n : typeof allPaths === 'string'\n ? [allPaths]\n : []\n\n for (const altPath of pathsArray) {\n const altDir = path?.dirname(altPath)\n if (!isShadowBinPath(altDir)) {\n return altPath\n }\n }\n }\n return binPath\n }\n // If all else fails, return undefined to indicate binary not found.\n return undefined\n}\n\n/**\n * Find the real npm executable, bypassing any aliases and shadow bins.\n */\nexport function findRealNpm(): string {\n const fs = getFs()\n const path = getPath()\n\n // Try to find npm in the same directory as the node executable.\n const nodeDir = path?.dirname(process.execPath)\n const npmInNodeDir = path?.join(nodeDir, 'npm')\n\n if (fs?.existsSync(npmInNodeDir)) {\n return npmInNodeDir\n }\n\n // Try common npm locations.\n const commonPaths = ['/usr/local/bin/npm', '/usr/bin/npm']\n const result = findRealBin('npm', commonPaths)\n\n // If we found a valid path, return it.\n if (result && fs?.existsSync(result)) {\n return result\n }\n\n // As a last resort, try to use whichBinSync to find npm.\n // This handles cases where npm is installed in non-standard locations.\n const npmPath = whichBinSync('npm', { nothrow: true })\n if (npmPath && typeof npmPath === 'string' && fs?.existsSync(npmPath)) {\n return npmPath\n }\n\n // Return the basic 'npm' and let the system resolve it.\n return 'npm'\n}\n\n/**\n * Find the real pnpm executable, bypassing any aliases and shadow bins.\n */\nexport function findRealPnpm(): string {\n const WIN32 = require('../constants/platform').WIN32\n const path = getPath()\n\n // Try common pnpm locations.\n const commonPaths = WIN32\n ? [\n // Windows common paths.\n path?.join(APPDATA as string, 'npm', 'pnpm.cmd'),\n path?.join(APPDATA as string, 'npm', 'pnpm'),\n path?.join(LOCALAPPDATA as string, 'pnpm', 'pnpm.cmd'),\n path?.join(LOCALAPPDATA as string, 'pnpm', 'pnpm'),\n 'C:\\\\Program Files\\\\nodejs\\\\pnpm.cmd',\n 'C:\\\\Program Files\\\\nodejs\\\\pnpm',\n ].filter(Boolean)\n : [\n // Unix common paths.\n '/usr/local/bin/pnpm',\n '/usr/bin/pnpm',\n path?.join(\n (XDG_DATA_HOME as string) || `${HOME as string}/.local/share`,\n 'pnpm/pnpm',\n ),\n path?.join(HOME as string, '.pnpm/pnpm'),\n ].filter(Boolean)\n\n return findRealBin('pnpm', commonPaths) ?? ''\n}\n\n/**\n * Find the real yarn executable, bypassing any aliases and shadow bins.\n */\nexport function findRealYarn(): string {\n const path = getPath()\n\n // Try common yarn locations.\n const commonPaths = [\n '/usr/local/bin/yarn',\n '/usr/bin/yarn',\n path?.join(HOME as string, '.yarn/bin/yarn'),\n path?.join(HOME as string, '.config/yarn/global/node_modules/.bin/yarn'),\n ].filter(Boolean)\n\n return findRealBin('yarn', commonPaths) ?? ''\n}\n\n/*@__NO_SIDE_EFFECTS__*/\n/**\n * Resolve a binary path to its actual executable file.\n * Handles Windows .cmd wrappers and Unix shell scripts.\n */\nexport function resolveBinPathSync(binPath: string): string {\n const fs = getFs()\n const path = getPath()\n\n // If it's not an absolute path, try to find it in PATH first\n if (!path?.isAbsolute(binPath)) {\n try {\n const resolved = whichBinSync(binPath)\n if (resolved) {\n binPath = resolved as string\n }\n } catch {}\n }\n\n // Normalize the path once for consistent pattern matching.\n binPath = normalizePath(binPath)\n\n // Handle empty string that normalized to '.' (current directory)\n if (binPath === '.') {\n return binPath\n }\n\n const ext = path?.extname(binPath)\n const extLowered = ext.toLowerCase()\n const basename = path?.basename(binPath, ext)\n const voltaIndex =\n basename === 'node' ? -1 : (/(?<=\\/)\\.volta\\//i.exec(binPath)?.index ?? -1)\n if (voltaIndex !== -1) {\n const voltaPath = binPath.slice(0, voltaIndex)\n const voltaToolsPath = path?.join(voltaPath, 'tools')\n const voltaImagePath = path?.join(voltaToolsPath, 'image')\n const voltaUserPath = path?.join(voltaToolsPath, 'user')\n const voltaPlatform = readJsonSync(\n path?.join(voltaUserPath, 'platform.json'),\n { throws: false },\n ) as any\n const voltaNodeVersion = voltaPlatform?.node?.runtime\n const voltaNpmVersion = voltaPlatform?.node?.npm\n let voltaBinPath = ''\n if (basename === 'npm' || basename === 'npx') {\n if (voltaNpmVersion) {\n const relCliPath = `bin/${basename}-cli.js`\n voltaBinPath = path?.join(\n voltaImagePath,\n `npm/${voltaNpmVersion}/${relCliPath}`,\n )\n if (voltaNodeVersion && !fs?.existsSync(voltaBinPath)) {\n voltaBinPath = path?.join(\n voltaImagePath,\n `node/${voltaNodeVersion}/lib/node_modules/npm/${relCliPath}`,\n )\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = ''\n }\n }\n }\n } else {\n const voltaUserBinPath = path?.join(voltaUserPath, 'bin')\n const binInfo = readJsonSync(\n path?.join(voltaUserBinPath, `${basename}.json`),\n { throws: false },\n ) as any\n const binPackage = binInfo?.package\n if (binPackage) {\n voltaBinPath = path?.join(\n voltaImagePath,\n `packages/${binPackage}/bin/${basename}`,\n )\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = `${voltaBinPath}.cmd`\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = ''\n }\n }\n }\n }\n if (voltaBinPath) {\n try {\n return normalizePath(fs?.realpathSync.native(voltaBinPath))\n } catch {}\n return voltaBinPath\n }\n }\n const WIN32 = require('../constants/platform').WIN32\n if (WIN32) {\n const hasKnownExt =\n extLowered === '' ||\n extLowered === '.cmd' ||\n extLowered === '.exe' ||\n extLowered === '.ps1'\n const isNpmOrNpx = basename === 'npm' || basename === 'npx'\n const isPnpmOrYarn = basename === 'pnpm' || basename === 'yarn'\n if (hasKnownExt && isNpmOrNpx) {\n // The quick route assumes a bin path like: C:\\Program Files\\nodejs\\npm.cmd\n const quickPath = path?.join(\n path?.dirname(binPath),\n `node_modules/npm/bin/${basename}-cli.js`,\n )\n if (fs?.existsSync(quickPath)) {\n try {\n return fs?.realpathSync.native(quickPath)\n } catch {}\n return quickPath\n }\n }\n let relPath = ''\n if (\n hasKnownExt &&\n // Only parse shell scripts and batch files, not actual executables.\n // .exe files are already executables and don't need path resolution from wrapper scripts.\n extLowered !== '.exe' &&\n // Check if file exists before attempting to read it to avoid ENOENT errors.\n fs?.existsSync(binPath)\n ) {\n const source = fs?.readFileSync(binPath, 'utf8')\n if (isNpmOrNpx) {\n if (extLowered === '.cmd') {\n // \"npm.cmd\" and \"npx.cmd\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm.cmd\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx.cmd\n relPath =\n basename === 'npm'\n ? /(?<=\"NPM_CLI_JS=%~dp0\\\\).*(?=\")/.exec(source)?.[0] || ''\n : /(?<=\"NPX_CLI_JS=%~dp0\\\\).*(?=\")/.exec(source)?.[0] || ''\n } else if (extLowered === '') {\n // Extensionless \"npm\" and \"npx\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx\n relPath =\n basename === 'npm'\n ? /(?<=NPM_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] ||\n ''\n : /(?<=NPX_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] ||\n ''\n } else if (extLowered === '.ps1') {\n // \"npm.ps1\" and \"npx.ps1\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm.ps1\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx.ps1\n relPath =\n basename === 'npm'\n ? /(?<=\\$NPM_CLI_JS=\"\\$PSScriptRoot\\/).*(?=\")/.exec(\n source,\n )?.[0] || ''\n : /(?<=\\$NPX_CLI_JS=\"\\$PSScriptRoot\\/).*(?=\")/.exec(\n source,\n )?.[0] || ''\n }\n } else if (isPnpmOrYarn) {\n if (extLowered === '.cmd') {\n // pnpm.cmd and yarn.cmd can have different formats depending on installation method\n // Common formats include:\n // 1. Setup-pnpm action format: node \"%~dp0\\..\\pnpm\\bin\\pnpm.cjs\" %*\n // 2. npm install -g pnpm format: similar to cmd-shim\n // 3. Standalone installer format: various patterns\n\n // Try setup-pnpm/setup-yarn action format first\n relPath =\n /(?<=node\\s+\")%~dp0\\\\([^\"]+)(?=\"\\s+%\\*)/.exec(source)?.[1] || ''\n\n // Try alternative format: \"%~dp0\\node.exe\" \"%~dp0\\..\\package\\bin\\binary.js\" %*\n if (!relPath) {\n relPath =\n /(?<=\"%~dp0\\\\[^\"]*node[^\"]*\"\\s+\")%~dp0\\\\([^\"]+)(?=\"\\s+%\\*)/.exec(\n source,\n )?.[1] || ''\n }\n\n // Try cmd-shim format as fallback\n if (!relPath) {\n relPath = /(?<=\"%dp0%\\\\).*(?=\" %\\*\\r\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '') {\n // Extensionless pnpm/yarn - try common shebang formats\n // Handle pnpm installed via standalone installer or global install\n // Format: exec \"$basedir/node\" \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n // Note: may have multiple spaces between arguments\n relPath =\n /(?<=\"\\$basedir\\/)\\.tools\\/pnpm\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(\n source,\n )?.[0] || ''\n if (!relPath) {\n // Also try: exec node \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n relPath =\n /(?<=exec\\s+node\\s+\"\\$basedir\\/)\\.tools\\/pnpm\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(\n source,\n )?.[0] || ''\n }\n if (!relPath) {\n // Try standard cmd-shim format: exec node \"$basedir/../package/bin/binary.js\" \"$@\"\n relPath = /(?<=\"\\$basedir\\/).*(?=\" \"\\$@\"\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '.ps1') {\n // PowerShell format\n relPath = /(?<=\"\\$basedir\\/).*(?=\" $args\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '.cmd') {\n // \"bin.CMD\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L98:\n //\n // @ECHO off\n // GOTO start\n // :find_dp0\n // SET dp0=%~dp0\n // EXIT /b\n // :start\n // SETLOCAL\n // CALL :find_dp0\n //\n // IF EXIST \"%dp0%\\node.exe\" (\n // SET \"_prog=%dp0%\\node.exe\"\n // ) ELSE (\n // SET \"_prog=node\"\n // SET PATHEXT=%PATHEXT:;.JS;=;%\n // )\n //\n // endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\..\\<PACKAGE_NAME>\\path\\to\\bin.js\" %*\n relPath = /(?<=\"%dp0%\\\\).*(?=\" %\\*\\r\\n)/.exec(source)?.[0] || ''\n } else if (extLowered === '') {\n // Extensionless \"bin\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L138:\n //\n // #!/bin/sh\n // basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n //\n // case `uname` in\n // *CYGWIN*|*MINGW*|*MSYS*)\n // if command -v cygpath > /dev/null 2>&1; then\n // basedir=`cygpath -w \"$basedir\"`\n // fi\n // ;;\n // esac\n //\n // if [ -x \"$basedir/node\" ]; then\n // exec \"$basedir/node\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" \"$@\"\n // else\n // exec node \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" \"$@\"\n // fi\n relPath = /(?<=\"$basedir\\/).*(?=\" \"\\$@\"\\n)/.exec(source)?.[0] || ''\n } else if (extLowered === '.ps1') {\n // \"bin.PS1\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L192:\n //\n // #!/usr/bin/env pwsh\n // $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n //\n // $exe=\"\"\n // if ($PSVersionTable.PSVersion -lt \"6.0\" -or $IsWindows) {\n // # Fix case when both the Windows and Linux builds of Node\n // # are installed in the same directory\n // $exe=\".exe\"\n // }\n // $ret=0\n // if (Test-Path \"$basedir/node$exe\") {\n // # Support pipeline input\n // if ($MyInvocation.ExpectingInput) {\n // $input | & \"$basedir/node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // } else {\n // & \"$basedir/node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // }\n // $ret=$LASTEXITCODE\n // } else {\n // # Support pipeline input\n // if ($MyInvocation.ExpectingInput) {\n // $input | & \"node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // } else {\n // & \"node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // }\n // $ret=$LASTEXITCODE\n // }\n // exit $ret\n relPath = /(?<=\"\\$basedir\\/).*(?=\" $args\\n)/.exec(source)?.[0] || ''\n }\n if (relPath) {\n binPath = normalizePath(path?.resolve(path?.dirname(binPath), relPath))\n }\n }\n } else {\n // Handle Unix shell scripts (non-Windows platforms)\n let hasNoExt = extLowered === ''\n const isPnpmOrYarn = basename === 'pnpm' || basename === 'yarn'\n const isNpmOrNpx = basename === 'npm' || basename === 'npx'\n\n // Handle special case where pnpm path in CI has extra segments.\n // In setup-pnpm GitHub Action, the path might be malformed like:\n // /home/runner/setup-pnpm/node_modules/.bin/pnpm/bin/pnpm.cjs\n // This happens when the shell script contains a relative path that\n // when resolved, creates an invalid nested structure.\n if (isPnpmOrYarn && binPath.includes('/.bin/pnpm/bin/')) {\n // Extract the correct pnpm bin path.\n const binIndex = binPath.indexOf('/.bin/pnpm')\n if (binIndex !== -1) {\n // Get the base path up to /.bin/pnpm.\n const baseBinPath = binPath.slice(0, binIndex + '/.bin/pnpm'.length)\n // Check if the original shell script exists.\n try {\n const stats = fs?.statSync(baseBinPath)\n // Only use this path if it's a file (the shell script).\n if (stats.isFile()) {\n binPath = normalizePath(baseBinPath)\n // Recompute hasNoExt since we changed the path.\n hasNoExt = !path?.extname(binPath)\n }\n } catch {\n // If stat fails, continue with the original path.\n }\n }\n }\n\n if (\n hasNoExt &&\n (isPnpmOrYarn || isNpmOrNpx) &&\n // For extensionless files (Unix shell scripts), verify existence before reading.\n // This prevents ENOENT errors when the bin path doesn't exist.\n fs?.existsSync(binPath)\n ) {\n const source = fs?.readFileSync(binPath, 'utf8')\n let relPath = ''\n\n if (isPnpmOrYarn) {\n // Handle pnpm/yarn Unix shell scripts.\n // Format: exec \"$basedir/node\" \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n // or: exec node \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n relPath =\n /(?<=\"\\$basedir\\/)\\.tools\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(source)?.[0] || ''\n if (!relPath) {\n // Try standard cmd-shim format: exec node \"$basedir/../package/bin/binary.js\" \"$@\"\n // Example: exec node \"$basedir/../pnpm/bin/pnpm.cjs\" \"$@\"\n // ^^^^^^^^^^^^^^^^^^^^^ captures this part\n // This regex needs to be more careful to not match \"$@\" at the end.\n relPath =\n /(?<=\"\\$basedir\\/)[^\"]+(?=\"\\s+\"\\$@\")/.exec(source)?.[0] || ''\n }\n // Special case for setup-pnpm GitHub Action which may use a different format.\n // The setup-pnpm action creates a shell script that references ../pnpm/bin/pnpm.cjs\n if (!relPath) {\n // Try to match: exec node \"$basedir/../pnpm/bin/pnpm.cjs\" \"$@\"\n const match = /exec\\s+node\\s+\"?\\$basedir\\/([^\"]+)\"?\\s+\"\\$@\"/.exec(\n source,\n )\n if (match) {\n relPath = match[1] || ''\n }\n }\n // Check if the extracted path looks wrong (e.g., pnpm/bin/pnpm.cjs without ../).\n // This happens with setup-pnpm action when it creates a malformed shell script.\n if (relPath && basename === 'pnpm' && relPath.startsWith('pnpm/')) {\n // The path should be ../pnpm/... not pnpm/...\n // Prepend ../ to fix the relative path.\n relPath = `../${relPath}`\n }\n } else if (isNpmOrNpx) {\n // Handle npm/npx Unix shell scripts\n relPath =\n basename === 'npm'\n ? /(?<=NPM_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] || ''\n : /(?<=NPX_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] || ''\n }\n\n if (relPath) {\n // Resolve the relative path to handle .. segments properly.\n binPath = normalizePath(path?.resolve(path?.dirname(binPath), relPath))\n }\n }\n }\n try {\n const realPath = fs?.realpathSync.native(binPath)\n return normalizePath(realPath)\n } catch {}\n // Return normalized path even if realpath fails.\n return normalizePath(binPath)\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,qBAAwB;AACxB,kBAAqB;AACrB,0BAA6B;AAC7B,2BAA8B;AAE9B,gBAA6B;AAC7B,qBAAuB;AACvB,kBAAsC;AACtC,mBAAsB;AAEtB,IAAI;AAAA;AAKJ,SAAS,QAAQ;AACf,MAAI,QAAQ,QAAW;AAGrB,UAAoB,QAAQ,SAAS;AAAA,EACvC;AACA,SAAO;AACT;AAEA,IAAI;AAAA;AAKJ,SAAS,UAAU;AACjB,MAAI,UAAU,QAAW;AAGvB,YAAsB,QAAQ,WAAW;AAAA,EAC3C;AACA,SAAO;AACT;AAEA,IAAI;AAAA;AAKJ,SAAS,WAAW;AAClB,MAAI,WAAW,QAAW;AACxB,aAAuB,QAAQ,kBAAkB;AAAA,EACnD;AACA,SAAO;AACT;AAAA;AAMA,eAAsB,QACpB,SACA,MACA,SACA;AAEA,QAAM,mBAAe,oBAAO,OAAO,IAC/B,mCAAmB,OAAO,IAC1B,MAAM,SAAS,OAAO;AAE1B,MAAI,CAAC,cAAc;AACjB,UAAM,QAAQ,IAAI,MAAM,qBAAqB,OAAO,EAAE;AAGtD,UAAM,OAAO;AACb,UAAM;AAAA,EACR;AAGA,QAAM,aAAa,MAAM,QAAQ,YAAY,IACzC,aAAa,CAAC,IACd;
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Binary path resolution and execution utilities for package managers.\n * Provides cross-platform bin path lookup, command execution, and path normalization.\n */\n\nimport { APPDATA } from '#env/appdata'\nimport { HOME } from '#env/home'\nimport { LOCALAPPDATA } from '#env/localappdata'\nimport { XDG_DATA_HOME } from '#env/xdg-data-home'\n\nimport { WIN32 } from '#constants/platform'\nimport { readJsonSync } from './fs'\nimport { getOwn } from './objects'\nimport { isPath, normalizePath } from './path'\nimport { spawn } from './spawn'\n\nlet _fs: typeof import('node:fs') | undefined\n/**\n * Lazily load the fs module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getFs() {\n if (_fs === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _fs = /*@__PURE__*/ require('node:fs')\n }\n return _fs!\n}\n\nlet _path: typeof import('node:path') | undefined\n/**\n * Lazily load the path module to avoid Webpack errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPath() {\n if (_path === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _path = /*@__PURE__*/ require('node:path')\n }\n return _path!\n}\n\nlet _which: typeof import('which') | undefined\n/**\n * Lazily load the which module for finding executables.\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getWhich() {\n if (_which === undefined) {\n _which = /*@__PURE__*/ require('./external/which')\n }\n return _which!\n}\n\n/**\n * Execute a binary with the given arguments.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function execBin(\n binPath: string,\n args?: string[],\n options?: import('./spawn').SpawnOptions,\n) {\n // Resolve the binary path.\n const resolvedPath = isPath(binPath)\n ? resolveBinPathSync(binPath)\n : await whichBin(binPath)\n\n if (!resolvedPath) {\n const error = new Error(`Binary not found: ${binPath}`) as Error & {\n code: string\n }\n error.code = 'ENOENT'\n throw error\n }\n\n // Execute the binary directly.\n const binCommand = Array.isArray(resolvedPath)\n ? resolvedPath[0]!\n : resolvedPath\n // On Windows, binaries are often .cmd files that require shell to execute.\n return await spawn(binCommand, args ?? [], {\n shell: WIN32,\n ...options,\n })\n}\n\n/**\n * Find and resolve a binary in the system PATH asynchronously.\n * @template {import('which').Options} T\n * @throws {Error} If the binary is not found and nothrow is false.\n */\nexport async function whichBin(\n binName: string,\n options?: import('which').Options,\n): Promise<string | string[] | undefined> {\n const which = getWhich()\n // Default to nothrow: true if not specified to return undefined instead of throwing\n const opts = { nothrow: true, ...options }\n // Depending on options `which` may throw if `binName` is not found.\n // With nothrow: true, it returns null when `binName` is not found.\n const result = await which?.(binName, opts)\n\n // When 'all: true' is specified, ensure we always return an array.\n if (options?.all) {\n const paths = Array.isArray(result)\n ? result\n : typeof result === 'string'\n ? [result]\n : undefined\n // If all is true and we have paths, resolve each one.\n return paths?.length ? paths.map(p => resolveBinPathSync(p)) : paths\n }\n\n // If result is undefined (binary not found), return undefined\n if (!result) {\n return undefined\n }\n\n return resolveBinPathSync(result)\n}\n\n/**\n * Find and resolve a binary in the system PATH synchronously.\n * @template {import('which').Options} T\n * @throws {Error} If the binary is not found and nothrow is false.\n */\nexport function whichBinSync(\n binName: string,\n options?: import('which').Options,\n): string | string[] | undefined {\n // Default to nothrow: true if not specified to return undefined instead of throwing\n const opts = { nothrow: true, ...options }\n // Depending on options `which` may throw if `binName` is not found.\n // With nothrow: true, it returns null when `binName` is not found.\n const result = getWhich()?.sync(binName, opts)\n\n // When 'all: true' is specified, ensure we always return an array.\n if (getOwn(options, 'all')) {\n const paths = Array.isArray(result)\n ? result\n : typeof result === 'string'\n ? [result]\n : undefined\n // If all is true and we have paths, resolve each one.\n return paths?.length ? paths.map(p => resolveBinPathSync(p)) : paths\n }\n\n // If result is undefined (binary not found), return undefined\n if (!result) {\n return undefined\n }\n\n return resolveBinPathSync(result)\n}\n\n/**\n * Check if a directory path contains any shadow bin patterns.\n */\nexport function isShadowBinPath(dirPath: string | undefined): boolean {\n if (!dirPath) {\n return false\n }\n // Check for node_modules/.bin pattern (Unix and Windows)\n const normalized = dirPath.replace(/\\\\/g, '/')\n return normalized.includes('node_modules/.bin')\n}\n\n/**\n * Find the real executable for a binary, bypassing shadow bins.\n */\nexport function findRealBin(\n binName: string,\n commonPaths: string[] = [],\n): string | undefined {\n const fs = getFs()\n const path = getPath()\n const which = getWhich()\n\n // Try common locations first.\n for (const binPath of commonPaths) {\n if (fs?.existsSync(binPath)) {\n return binPath\n }\n }\n\n // Fall back to which.sync if no direct path found.\n const binPath = which?.sync(binName, { nothrow: true })\n if (binPath) {\n const binDir = path?.dirname(binPath)\n\n if (isShadowBinPath(binDir)) {\n // This is likely a shadowed binary, try to find the real one.\n const allPaths = which?.sync(binName, { all: true, nothrow: true }) || []\n // Ensure allPaths is an array.\n const pathsArray = Array.isArray(allPaths)\n ? allPaths\n : typeof allPaths === 'string'\n ? [allPaths]\n : []\n\n for (const altPath of pathsArray) {\n const altDir = path?.dirname(altPath)\n if (!isShadowBinPath(altDir)) {\n return altPath\n }\n }\n }\n return binPath\n }\n // If all else fails, return undefined to indicate binary not found.\n return undefined\n}\n\n/**\n * Find the real npm executable, bypassing any aliases and shadow bins.\n */\nexport function findRealNpm(): string {\n const fs = getFs()\n const path = getPath()\n\n // Try to find npm in the same directory as the node executable.\n const nodeDir = path?.dirname(process.execPath)\n const npmInNodeDir = path?.join(nodeDir, 'npm')\n\n if (fs?.existsSync(npmInNodeDir)) {\n return npmInNodeDir\n }\n\n // Try common npm locations.\n const commonPaths = ['/usr/local/bin/npm', '/usr/bin/npm']\n const result = findRealBin('npm', commonPaths)\n\n // If we found a valid path, return it.\n if (result && fs?.existsSync(result)) {\n return result\n }\n\n // As a last resort, try to use whichBinSync to find npm.\n // This handles cases where npm is installed in non-standard locations.\n const npmPath = whichBinSync('npm', { nothrow: true })\n if (npmPath && typeof npmPath === 'string' && fs?.existsSync(npmPath)) {\n return npmPath\n }\n\n // Return the basic 'npm' and let the system resolve it.\n return 'npm'\n}\n\n/**\n * Find the real pnpm executable, bypassing any aliases and shadow bins.\n */\nexport function findRealPnpm(): string {\n const path = getPath()\n\n // Try common pnpm locations.\n const commonPaths = WIN32\n ? [\n // Windows common paths.\n path?.join(APPDATA as string, 'npm', 'pnpm.cmd'),\n path?.join(APPDATA as string, 'npm', 'pnpm'),\n path?.join(LOCALAPPDATA as string, 'pnpm', 'pnpm.cmd'),\n path?.join(LOCALAPPDATA as string, 'pnpm', 'pnpm'),\n 'C:\\\\Program Files\\\\nodejs\\\\pnpm.cmd',\n 'C:\\\\Program Files\\\\nodejs\\\\pnpm',\n ].filter(Boolean)\n : [\n // Unix common paths.\n '/usr/local/bin/pnpm',\n '/usr/bin/pnpm',\n path?.join(\n (XDG_DATA_HOME as string) || `${HOME as string}/.local/share`,\n 'pnpm/pnpm',\n ),\n path?.join(HOME as string, '.pnpm/pnpm'),\n ].filter(Boolean)\n\n return findRealBin('pnpm', commonPaths) ?? ''\n}\n\n/**\n * Find the real yarn executable, bypassing any aliases and shadow bins.\n */\nexport function findRealYarn(): string {\n const path = getPath()\n\n // Try common yarn locations.\n const commonPaths = [\n '/usr/local/bin/yarn',\n '/usr/bin/yarn',\n path?.join(HOME as string, '.yarn/bin/yarn'),\n path?.join(HOME as string, '.config/yarn/global/node_modules/.bin/yarn'),\n ].filter(Boolean)\n\n return findRealBin('yarn', commonPaths) ?? ''\n}\n\n/*@__NO_SIDE_EFFECTS__*/\n/**\n * Resolve a binary path to its actual executable file.\n * Handles Windows .cmd wrappers and Unix shell scripts.\n */\nexport function resolveBinPathSync(binPath: string): string {\n const fs = getFs()\n const path = getPath()\n\n // If it's not an absolute path, try to find it in PATH first\n if (!path?.isAbsolute(binPath)) {\n try {\n const resolved = whichBinSync(binPath)\n if (resolved) {\n binPath = resolved as string\n }\n } catch {}\n }\n\n // Normalize the path once for consistent pattern matching.\n binPath = normalizePath(binPath)\n\n // Handle empty string that normalized to '.' (current directory)\n if (binPath === '.') {\n return binPath\n }\n\n const ext = path?.extname(binPath)\n const extLowered = ext.toLowerCase()\n const basename = path?.basename(binPath, ext)\n const voltaIndex =\n basename === 'node' ? -1 : (/(?<=\\/)\\.volta\\//i.exec(binPath)?.index ?? -1)\n if (voltaIndex !== -1) {\n const voltaPath = binPath.slice(0, voltaIndex)\n const voltaToolsPath = path?.join(voltaPath, 'tools')\n const voltaImagePath = path?.join(voltaToolsPath, 'image')\n const voltaUserPath = path?.join(voltaToolsPath, 'user')\n const voltaPlatform = readJsonSync(\n path?.join(voltaUserPath, 'platform.json'),\n { throws: false },\n ) as any\n const voltaNodeVersion = voltaPlatform?.node?.runtime\n const voltaNpmVersion = voltaPlatform?.node?.npm\n let voltaBinPath = ''\n if (basename === 'npm' || basename === 'npx') {\n if (voltaNpmVersion) {\n const relCliPath = `bin/${basename}-cli.js`\n voltaBinPath = path?.join(\n voltaImagePath,\n `npm/${voltaNpmVersion}/${relCliPath}`,\n )\n if (voltaNodeVersion && !fs?.existsSync(voltaBinPath)) {\n voltaBinPath = path?.join(\n voltaImagePath,\n `node/${voltaNodeVersion}/lib/node_modules/npm/${relCliPath}`,\n )\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = ''\n }\n }\n }\n } else {\n const voltaUserBinPath = path?.join(voltaUserPath, 'bin')\n const binInfo = readJsonSync(\n path?.join(voltaUserBinPath, `${basename}.json`),\n { throws: false },\n ) as any\n const binPackage = binInfo?.package\n if (binPackage) {\n voltaBinPath = path?.join(\n voltaImagePath,\n `packages/${binPackage}/bin/${basename}`,\n )\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = `${voltaBinPath}.cmd`\n if (!fs?.existsSync(voltaBinPath)) {\n voltaBinPath = ''\n }\n }\n }\n }\n if (voltaBinPath) {\n try {\n return normalizePath(fs?.realpathSync.native(voltaBinPath))\n } catch {}\n return voltaBinPath\n }\n }\n if (WIN32) {\n const hasKnownExt =\n extLowered === '' ||\n extLowered === '.cmd' ||\n extLowered === '.exe' ||\n extLowered === '.ps1'\n const isNpmOrNpx = basename === 'npm' || basename === 'npx'\n const isPnpmOrYarn = basename === 'pnpm' || basename === 'yarn'\n if (hasKnownExt && isNpmOrNpx) {\n // The quick route assumes a bin path like: C:\\Program Files\\nodejs\\npm.cmd\n const quickPath = path?.join(\n path?.dirname(binPath),\n `node_modules/npm/bin/${basename}-cli.js`,\n )\n if (fs?.existsSync(quickPath)) {\n try {\n return fs?.realpathSync.native(quickPath)\n } catch {}\n return quickPath\n }\n }\n let relPath = ''\n if (\n hasKnownExt &&\n // Only parse shell scripts and batch files, not actual executables.\n // .exe files are already executables and don't need path resolution from wrapper scripts.\n extLowered !== '.exe' &&\n // Check if file exists before attempting to read it to avoid ENOENT errors.\n fs?.existsSync(binPath)\n ) {\n const source = fs?.readFileSync(binPath, 'utf8')\n if (isNpmOrNpx) {\n if (extLowered === '.cmd') {\n // \"npm.cmd\" and \"npx.cmd\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm.cmd\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx.cmd\n relPath =\n basename === 'npm'\n ? /(?<=\"NPM_CLI_JS=%~dp0\\\\).*(?=\")/.exec(source)?.[0] || ''\n : /(?<=\"NPX_CLI_JS=%~dp0\\\\).*(?=\")/.exec(source)?.[0] || ''\n } else if (extLowered === '') {\n // Extensionless \"npm\" and \"npx\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx\n relPath =\n basename === 'npm'\n ? /(?<=NPM_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] ||\n ''\n : /(?<=NPX_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] ||\n ''\n } else if (extLowered === '.ps1') {\n // \"npm.ps1\" and \"npx.ps1\" defined by\n // https://github.com/npm/cli/blob/v11.4.2/bin/npm.ps1\n // https://github.com/npm/cli/blob/v11.4.2/bin/npx.ps1\n relPath =\n basename === 'npm'\n ? /(?<=\\$NPM_CLI_JS=\"\\$PSScriptRoot\\/).*(?=\")/.exec(\n source,\n )?.[0] || ''\n : /(?<=\\$NPX_CLI_JS=\"\\$PSScriptRoot\\/).*(?=\")/.exec(\n source,\n )?.[0] || ''\n }\n } else if (isPnpmOrYarn) {\n if (extLowered === '.cmd') {\n // pnpm.cmd and yarn.cmd can have different formats depending on installation method\n // Common formats include:\n // 1. Setup-pnpm action format: node \"%~dp0\\..\\pnpm\\bin\\pnpm.cjs\" %*\n // 2. npm install -g pnpm format: similar to cmd-shim\n // 3. Standalone installer format: various patterns\n\n // Try setup-pnpm/setup-yarn action format first\n relPath =\n /(?<=node\\s+\")%~dp0\\\\([^\"]+)(?=\"\\s+%\\*)/.exec(source)?.[1] || ''\n\n // Try alternative format: \"%~dp0\\node.exe\" \"%~dp0\\..\\package\\bin\\binary.js\" %*\n if (!relPath) {\n relPath =\n /(?<=\"%~dp0\\\\[^\"]*node[^\"]*\"\\s+\")%~dp0\\\\([^\"]+)(?=\"\\s+%\\*)/.exec(\n source,\n )?.[1] || ''\n }\n\n // Try cmd-shim format as fallback\n if (!relPath) {\n relPath = /(?<=\"%dp0%\\\\).*(?=\" %\\*\\r\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '') {\n // Extensionless pnpm/yarn - try common shebang formats\n // Handle pnpm installed via standalone installer or global install\n // Format: exec \"$basedir/node\" \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n // Note: may have multiple spaces between arguments\n relPath =\n /(?<=\"\\$basedir\\/)\\.tools\\/pnpm\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(\n source,\n )?.[0] || ''\n if (!relPath) {\n // Also try: exec node \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n relPath =\n /(?<=exec\\s+node\\s+\"\\$basedir\\/)\\.tools\\/pnpm\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(\n source,\n )?.[0] || ''\n }\n if (!relPath) {\n // Try standard cmd-shim format: exec node \"$basedir/../package/bin/binary.js\" \"$@\"\n relPath = /(?<=\"\\$basedir\\/).*(?=\" \"\\$@\"\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '.ps1') {\n // PowerShell format\n relPath = /(?<=\"\\$basedir\\/).*(?=\" $args\\n)/.exec(source)?.[0] || ''\n }\n } else if (extLowered === '.cmd') {\n // \"bin.CMD\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L98:\n //\n // @ECHO off\n // GOTO start\n // :find_dp0\n // SET dp0=%~dp0\n // EXIT /b\n // :start\n // SETLOCAL\n // CALL :find_dp0\n //\n // IF EXIST \"%dp0%\\node.exe\" (\n // SET \"_prog=%dp0%\\node.exe\"\n // ) ELSE (\n // SET \"_prog=node\"\n // SET PATHEXT=%PATHEXT:;.JS;=;%\n // )\n //\n // endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\..\\<PACKAGE_NAME>\\path\\to\\bin.js\" %*\n relPath = /(?<=\"%dp0%\\\\).*(?=\" %\\*\\r\\n)/.exec(source)?.[0] || ''\n } else if (extLowered === '') {\n // Extensionless \"bin\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L138:\n //\n // #!/bin/sh\n // basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n //\n // case `uname` in\n // *CYGWIN*|*MINGW*|*MSYS*)\n // if command -v cygpath > /dev/null 2>&1; then\n // basedir=`cygpath -w \"$basedir\"`\n // fi\n // ;;\n // esac\n //\n // if [ -x \"$basedir/node\" ]; then\n // exec \"$basedir/node\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" \"$@\"\n // else\n // exec node \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" \"$@\"\n // fi\n relPath = /(?<=\"$basedir\\/).*(?=\" \"\\$@\"\\n)/.exec(source)?.[0] || ''\n } else if (extLowered === '.ps1') {\n // \"bin.PS1\" generated by\n // https://github.com/npm/cmd-shim/blob/v7.0.0/lib/index.js#L192:\n //\n // #!/usr/bin/env pwsh\n // $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n //\n // $exe=\"\"\n // if ($PSVersionTable.PSVersion -lt \"6.0\" -or $IsWindows) {\n // # Fix case when both the Windows and Linux builds of Node\n // # are installed in the same directory\n // $exe=\".exe\"\n // }\n // $ret=0\n // if (Test-Path \"$basedir/node$exe\") {\n // # Support pipeline input\n // if ($MyInvocation.ExpectingInput) {\n // $input | & \"$basedir/node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // } else {\n // & \"$basedir/node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // }\n // $ret=$LASTEXITCODE\n // } else {\n // # Support pipeline input\n // if ($MyInvocation.ExpectingInput) {\n // $input | & \"node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // } else {\n // & \"node$exe\" \"$basedir/../<PACKAGE_NAME>/path/to/bin.js\" $args\n // }\n // $ret=$LASTEXITCODE\n // }\n // exit $ret\n relPath = /(?<=\"\\$basedir\\/).*(?=\" $args\\n)/.exec(source)?.[0] || ''\n }\n if (relPath) {\n binPath = normalizePath(path?.resolve(path?.dirname(binPath), relPath))\n }\n }\n } else {\n // Handle Unix shell scripts (non-Windows platforms)\n let hasNoExt = extLowered === ''\n const isPnpmOrYarn = basename === 'pnpm' || basename === 'yarn'\n const isNpmOrNpx = basename === 'npm' || basename === 'npx'\n\n // Handle special case where pnpm path in CI has extra segments.\n // In setup-pnpm GitHub Action, the path might be malformed like:\n // /home/runner/setup-pnpm/node_modules/.bin/pnpm/bin/pnpm.cjs\n // This happens when the shell script contains a relative path that\n // when resolved, creates an invalid nested structure.\n if (isPnpmOrYarn && binPath.includes('/.bin/pnpm/bin/')) {\n // Extract the correct pnpm bin path.\n const binIndex = binPath.indexOf('/.bin/pnpm')\n if (binIndex !== -1) {\n // Get the base path up to /.bin/pnpm.\n const baseBinPath = binPath.slice(0, binIndex + '/.bin/pnpm'.length)\n // Check if the original shell script exists.\n try {\n const stats = fs?.statSync(baseBinPath)\n // Only use this path if it's a file (the shell script).\n if (stats.isFile()) {\n binPath = normalizePath(baseBinPath)\n // Recompute hasNoExt since we changed the path.\n hasNoExt = !path?.extname(binPath)\n }\n } catch {\n // If stat fails, continue with the original path.\n }\n }\n }\n\n if (\n hasNoExt &&\n (isPnpmOrYarn || isNpmOrNpx) &&\n // For extensionless files (Unix shell scripts), verify existence before reading.\n // This prevents ENOENT errors when the bin path doesn't exist.\n fs?.existsSync(binPath)\n ) {\n const source = fs?.readFileSync(binPath, 'utf8')\n let relPath = ''\n\n if (isPnpmOrYarn) {\n // Handle pnpm/yarn Unix shell scripts.\n // Format: exec \"$basedir/node\" \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n // or: exec node \"$basedir/.tools/pnpm/VERSION/...\" \"$@\"\n relPath =\n /(?<=\"\\$basedir\\/)\\.tools\\/[^\"]+(?=\"\\s+\"\\$@\")/.exec(source)?.[0] || ''\n if (!relPath) {\n // Try standard cmd-shim format: exec node \"$basedir/../package/bin/binary.js\" \"$@\"\n // Example: exec node \"$basedir/../pnpm/bin/pnpm.cjs\" \"$@\"\n // ^^^^^^^^^^^^^^^^^^^^^ captures this part\n // This regex needs to be more careful to not match \"$@\" at the end.\n relPath =\n /(?<=\"\\$basedir\\/)[^\"]+(?=\"\\s+\"\\$@\")/.exec(source)?.[0] || ''\n }\n // Special case for setup-pnpm GitHub Action which may use a different format.\n // The setup-pnpm action creates a shell script that references ../pnpm/bin/pnpm.cjs\n if (!relPath) {\n // Try to match: exec node \"$basedir/../pnpm/bin/pnpm.cjs\" \"$@\"\n const match = /exec\\s+node\\s+\"?\\$basedir\\/([^\"]+)\"?\\s+\"\\$@\"/.exec(\n source,\n )\n if (match) {\n relPath = match[1] || ''\n }\n }\n // Check if the extracted path looks wrong (e.g., pnpm/bin/pnpm.cjs without ../).\n // This happens with setup-pnpm action when it creates a malformed shell script.\n if (relPath && basename === 'pnpm' && relPath.startsWith('pnpm/')) {\n // The path should be ../pnpm/... not pnpm/...\n // Prepend ../ to fix the relative path.\n relPath = `../${relPath}`\n }\n } else if (isNpmOrNpx) {\n // Handle npm/npx Unix shell scripts\n relPath =\n basename === 'npm'\n ? /(?<=NPM_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] || ''\n : /(?<=NPX_CLI_JS=\"\\$CLI_BASEDIR\\/).*(?=\")/.exec(source)?.[0] || ''\n }\n\n if (relPath) {\n // Resolve the relative path to handle .. segments properly.\n binPath = normalizePath(path?.resolve(path?.dirname(binPath), relPath))\n }\n }\n }\n try {\n const realPath = fs?.realpathSync.native(binPath)\n return normalizePath(realPath)\n } catch {}\n // Return normalized path even if realpath fails.\n return normalizePath(binPath)\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,qBAAwB;AACxB,kBAAqB;AACrB,0BAA6B;AAC7B,2BAA8B;AAE9B,sBAAsB;AACtB,gBAA6B;AAC7B,qBAAuB;AACvB,kBAAsC;AACtC,mBAAsB;AAEtB,IAAI;AAAA;AAKJ,SAAS,QAAQ;AACf,MAAI,QAAQ,QAAW;AAGrB,UAAoB,QAAQ,SAAS;AAAA,EACvC;AACA,SAAO;AACT;AAEA,IAAI;AAAA;AAKJ,SAAS,UAAU;AACjB,MAAI,UAAU,QAAW;AAGvB,YAAsB,QAAQ,WAAW;AAAA,EAC3C;AACA,SAAO;AACT;AAEA,IAAI;AAA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ACvE;AAEA,UAAI,SAAS;AAEX,sBAAU,2BAAc,MAAM,QAAQ,MAAM,QAAQ,OAAO,GAAG,OAAO,CAAC;AAAA,MACxE;AAAA,IACF;AAAA,EACF;AACA,MAAI;AACF,UAAM,WAAW,IAAI,aAAa,OAAO,OAAO;AAChD,eAAO,2BAAc,QAAQ;AAAA,EAC/B,QAAQ;AAAA,EAAC;AAET,aAAO,2BAAc,OAAO;AAC9B;",
|
|
6
6
|
"names": ["binPath"]
|
|
7
7
|
}
|
package/dist/dlx-binary.d.ts
CHANGED
|
@@ -33,6 +33,7 @@ export declare function dlxBinary(args: readonly string[] | string[], options?:
|
|
|
33
33
|
/**
|
|
34
34
|
* Get the DLX binary cache directory path.
|
|
35
35
|
* Returns normalized path for cross-platform compatibility.
|
|
36
|
+
* Uses same directory as dlx-package for unified DLX storage.
|
|
36
37
|
*/
|
|
37
38
|
export declare function getDlxCachePath(): string;
|
|
38
39
|
/**
|
package/dist/dlx-binary.js
CHANGED
|
@@ -209,7 +209,7 @@ async function dlxBinary(args, options, spawnExtra) {
|
|
|
209
209
|
};
|
|
210
210
|
}
|
|
211
211
|
function getDlxCachePath() {
|
|
212
|
-
return (0,
|
|
212
|
+
return (0, import_paths.getSocketDlxDir)();
|
|
213
213
|
}
|
|
214
214
|
async function listDlxCache() {
|
|
215
215
|
const cacheDir = getDlxCachePath();
|
package/dist/dlx-binary.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/dlx-binary.ts"],
|
|
4
|
-
"sourcesContent": ["/** @fileoverview DLX binary execution utilities for Socket ecosystem. */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, promises as fs } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\n\nimport { WIN32 } from '#constants/platform'\n\nimport { isDir, readJson, safeDelete } from './fs'\nimport { httpRequest } from './http-request'\nimport { isObjectObject } from './objects'\nimport { normalizePath } from './path'\nimport { getSocketHomePath } from './paths'\nimport type { SpawnExtra, SpawnOptions } from './spawn'\nimport { spawn } from './spawn'\n\nexport interface DlxBinaryOptions {\n /** URL to download the binary from. */\n url: string\n /** Optional name for the cached binary (defaults to URL hash). */\n name?: string | undefined\n /** Expected checksum (sha256) for verification. */\n checksum?: string | undefined\n /** Cache TTL in milliseconds (default: 7 days). */\n cacheTtl?: number | undefined\n /** Force re-download even if cached. */\n force?: boolean | undefined\n /** Additional spawn options. */\n spawnOptions?: SpawnOptions | undefined\n}\n\nexport interface DlxBinaryResult {\n /** Path to the cached binary. */\n binaryPath: string\n /** Whether the binary was newly downloaded. */\n downloaded: boolean\n /** The spawn promise for the running process. */\n spawnPromise: ReturnType<typeof spawn>\n}\n\n/**\n * Generate a cache directory name from URL, similar to pnpm/npx.\n * Uses SHA256 hash to create content-addressed storage.\n */\nfunction generateCacheKey(url: string): string {\n return createHash('sha256').update(url).digest('hex')\n}\n\n/**\n * Get metadata file path for a cached binary.\n */\nfunction getMetadataPath(cacheEntryPath: string): string {\n return path.join(cacheEntryPath, '.dlx-metadata.json')\n}\n\n/**\n * Check if a cached binary is still valid.\n */\nasync function isCacheValid(\n cacheEntryPath: string,\n cacheTtl: number,\n): Promise<boolean> {\n try {\n const metaPath = getMetadataPath(cacheEntryPath)\n if (!existsSync(metaPath)) {\n return false\n }\n\n const metadata = await readJson(metaPath, { throws: false })\n if (!isObjectObject(metadata)) {\n return false\n }\n const now = Date.now()\n const age =\n now -\n (((metadata as Record<string, unknown>)['timestamp'] as number) || 0)\n\n return age < cacheTtl\n } catch {\n return false\n }\n}\n\n/**\n * Download a file from a URL with integrity checking.\n */\nasync function downloadBinary(\n url: string,\n destPath: string,\n checksum?: string | undefined,\n): Promise<string> {\n const response = await httpRequest(url)\n if (!response.ok) {\n throw new Error(\n `Failed to download binary: ${response.status} ${response.statusText}`,\n )\n }\n\n // Create a temporary file first.\n const tempPath = `${destPath}.download`\n const hasher = createHash('sha256')\n\n try {\n // Ensure directory exists.\n await fs.mkdir(path.dirname(destPath), { recursive: true })\n\n // Get the response as a buffer and compute hash.\n const buffer = response.body\n\n // Compute hash.\n hasher.update(buffer)\n const actualChecksum = hasher.digest('hex')\n\n // Verify checksum if provided.\n if (checksum && actualChecksum !== checksum) {\n throw new Error(\n `Checksum mismatch: expected ${checksum}, got ${actualChecksum}`,\n )\n }\n\n // Write to temp file.\n await fs.writeFile(tempPath, buffer)\n\n // Make executable on POSIX systems.\n if (!WIN32) {\n await fs.chmod(tempPath, 0o755)\n }\n\n // Move temp file to final location.\n await fs.rename(tempPath, destPath)\n\n return actualChecksum\n } catch (e) {\n // Clean up temp file on error.\n try {\n await safeDelete(tempPath)\n } catch {\n // Ignore cleanup errors.\n }\n throw e\n }\n}\n\n/**\n * Write metadata for a cached binary.\n */\nasync function writeMetadata(\n cacheEntryPath: string,\n url: string,\n checksum: string,\n): Promise<void> {\n const metaPath = getMetadataPath(cacheEntryPath)\n const metadata = {\n arch: os.arch(),\n checksum,\n platform: os.platform(),\n timestamp: Date.now(),\n url,\n version: '1.0.0',\n }\n await fs.writeFile(metaPath, JSON.stringify(metadata, null, 2))\n}\n\n/**\n * Clean expired entries from the DLX cache.\n */\nexport async function cleanDlxCache(\n maxAge: number = /*@__INLINE__*/ require('../constants/time').DLX_BINARY_CACHE_TTL,\n): Promise<number> {\n const cacheDir = getDlxCachePath()\n\n if (!existsSync(cacheDir)) {\n return 0\n }\n\n let cleaned = 0\n const now = Date.now()\n const entries = await fs.readdir(cacheDir)\n\n for (const entry of entries) {\n const entryPath = path.join(cacheDir, entry)\n const metaPath = getMetadataPath(entryPath)\n\n try {\n // eslint-disable-next-line no-await-in-loop\n if (!(await isDir(entryPath))) {\n continue\n }\n\n // eslint-disable-next-line no-await-in-loop\n const metadata = await readJson(metaPath, { throws: false })\n if (\n !metadata ||\n typeof metadata !== 'object' ||\n Array.isArray(metadata)\n ) {\n continue\n }\n const age =\n now -\n (((metadata as Record<string, unknown>)['timestamp'] as number) || 0)\n\n if (age > maxAge) {\n // Remove entire cache entry directory.\n // eslint-disable-next-line no-await-in-loop\n await safeDelete(entryPath, { force: true, recursive: true })\n cleaned += 1\n }\n } catch {\n // If we can't read metadata, check if directory is empty or corrupted.\n try {\n // eslint-disable-next-line no-await-in-loop\n const contents = await fs.readdir(entryPath)\n if (!contents.length) {\n // Remove empty directory.\n // eslint-disable-next-line no-await-in-loop\n await safeDelete(entryPath)\n cleaned += 1\n }\n } catch {}\n }\n }\n\n return cleaned\n}\n\n/**\n * Download and execute a binary from a URL with caching.\n */\nexport async function dlxBinary(\n args: readonly string[] | string[],\n options?: DlxBinaryOptions | undefined,\n spawnExtra?: SpawnExtra | undefined,\n): Promise<DlxBinaryResult> {\n const {\n cacheTtl = /*@__INLINE__*/ require('../constants/time').DLX_BINARY_CACHE_TTL,\n checksum,\n force = false,\n name,\n spawnOptions,\n url,\n } = { __proto__: null, ...options } as DlxBinaryOptions\n\n // Generate cache paths similar to pnpm/npx structure.\n const cacheDir = getDlxCachePath()\n const cacheKey = generateCacheKey(url)\n const cacheEntryDir = path.join(cacheDir, cacheKey)\n const binaryName = name || `binary-${process.platform}-${os.arch()}`\n const binaryPath = normalizePath(path.join(cacheEntryDir, binaryName))\n\n let downloaded = false\n let computedChecksum = checksum\n\n // Check if we need to download.\n if (\n !force &&\n existsSync(cacheEntryDir) &&\n (await isCacheValid(cacheEntryDir, cacheTtl))\n ) {\n // Binary is cached and valid, read the checksum from metadata.\n try {\n const metaPath = getMetadataPath(cacheEntryDir)\n const metadata = await readJson(metaPath, { throws: false })\n if (\n metadata &&\n typeof metadata === 'object' &&\n !Array.isArray(metadata) &&\n typeof (metadata as Record<string, unknown>)['checksum'] === 'string'\n ) {\n computedChecksum = (metadata as Record<string, unknown>)[\n 'checksum'\n ] as string\n } else {\n // If metadata is invalid, re-download.\n downloaded = true\n }\n } catch {\n // If we can't read metadata, re-download.\n downloaded = true\n }\n } else {\n downloaded = true\n }\n\n if (downloaded) {\n // Ensure cache directory exists.\n await fs.mkdir(cacheEntryDir, { recursive: true })\n\n // Download the binary.\n computedChecksum = await downloadBinary(url, binaryPath, checksum)\n await writeMetadata(cacheEntryDir, url, computedChecksum || '')\n }\n\n // Execute the binary.\n // On Windows, script files (.bat, .cmd, .ps1) require shell: true because\n // they are not executable on their own and must be run through cmd.exe.\n // Note: .exe files are actual binaries and don't need shell mode.\n const needsShell = WIN32 && /\\.(?:bat|cmd|ps1)$/i.test(binaryPath)\n // Windows cmd.exe PATH resolution behavior:\n // When shell: true on Windows with .cmd/.bat/.ps1 files, spawn will automatically\n // strip the full path down to just the basename without extension (e.g.,\n // C:\\cache\\test.cmd becomes just \"test\"). Windows cmd.exe then searches for \"test\"\n // in directories listed in PATH, trying each extension from PATHEXT environment\n // variable (.COM, .EXE, .BAT, .CMD, etc.) until it finds a match.\n //\n // Since our binaries are downloaded to a custom cache directory that's not in PATH\n // (unlike system package managers like npm/pnpm/yarn which are already in PATH),\n // we must prepend the cache directory to PATH so cmd.exe can locate the binary.\n //\n // This approach is consistent with how other tools handle Windows command execution:\n // - npm's promise-spawn: uses which.sync() to find commands in PATH\n // - cross-spawn: spawns cmd.exe with escaped arguments\n // - Node.js spawn with shell: true: delegates to cmd.exe which uses PATH\n const finalSpawnOptions = needsShell\n ? {\n ...spawnOptions,\n env: {\n ...spawnOptions?.env,\n PATH: `${cacheEntryDir}${path.delimiter}${process.env['PATH'] || ''}`,\n },\n shell: true,\n }\n : spawnOptions\n const spawnPromise = spawn(binaryPath, args, finalSpawnOptions, spawnExtra)\n\n return {\n binaryPath,\n downloaded,\n spawnPromise,\n }\n}\n\n/**\n * Get the DLX binary cache directory path.\n * Returns normalized path for cross-platform compatibility.\n */\nexport function getDlxCachePath(): string {\n return normalizePath(path.join(getSocketHomePath(), 'cache', 'dlx'))\n}\n\n/**\n * Get information about cached binaries.\n */\nexport async function listDlxCache(): Promise<\n Array<{\n age: number\n arch: string\n checksum: string\n name: string\n platform: string\n size: number\n url: string\n }>\n> {\n const cacheDir = getDlxCachePath()\n\n if (!existsSync(cacheDir)) {\n return []\n }\n\n const results = []\n const now = Date.now()\n const entries = await fs.readdir(cacheDir)\n\n for (const entry of entries) {\n const entryPath = path.join(cacheDir, entry)\n try {\n // eslint-disable-next-line no-await-in-loop\n if (!(await isDir(entryPath))) {\n continue\n }\n\n const metaPath = getMetadataPath(entryPath)\n // eslint-disable-next-line no-await-in-loop\n const metadata = await readJson(metaPath, { throws: false })\n if (\n !metadata ||\n typeof metadata !== 'object' ||\n Array.isArray(metadata)\n ) {\n continue\n }\n\n // Find the binary file in the directory.\n // eslint-disable-next-line no-await-in-loop\n const files = await fs.readdir(entryPath)\n const binaryFile = files.find(f => !f.startsWith('.'))\n\n if (binaryFile) {\n const binaryPath = path.join(entryPath, binaryFile)\n // eslint-disable-next-line no-await-in-loop\n const binaryStats = await fs.stat(binaryPath)\n\n const metaObj = metadata as Record<string, unknown>\n results.push({\n age: now - ((metaObj['timestamp'] as number) || 0),\n arch: (metaObj['arch'] as string) || 'unknown',\n checksum: (metaObj['checksum'] as string) || '',\n name: binaryFile,\n platform: (metaObj['platform'] as string) || 'unknown',\n size: binaryStats.size,\n url: (metaObj['url'] as string) || '',\n })\n }\n } catch {}\n }\n\n return results\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,yBAA2B;AAC3B,qBAA2C;AAC3C,qBAAe;AACf,uBAAiB;AAEjB,sBAAsB;AAEtB,gBAA4C;AAC5C,0BAA4B;AAC5B,qBAA+B;AAC/B,kBAA8B;AAC9B,
|
|
4
|
+
"sourcesContent": ["/** @fileoverview DLX binary execution utilities for Socket ecosystem. */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, promises as fs } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\n\nimport { WIN32 } from '#constants/platform'\n\nimport { isDir, readJson, safeDelete } from './fs'\nimport { httpRequest } from './http-request'\nimport { isObjectObject } from './objects'\nimport { normalizePath } from './path'\nimport { getSocketDlxDir } from './paths'\nimport type { SpawnExtra, SpawnOptions } from './spawn'\nimport { spawn } from './spawn'\n\nexport interface DlxBinaryOptions {\n /** URL to download the binary from. */\n url: string\n /** Optional name for the cached binary (defaults to URL hash). */\n name?: string | undefined\n /** Expected checksum (sha256) for verification. */\n checksum?: string | undefined\n /** Cache TTL in milliseconds (default: 7 days). */\n cacheTtl?: number | undefined\n /** Force re-download even if cached. */\n force?: boolean | undefined\n /** Additional spawn options. */\n spawnOptions?: SpawnOptions | undefined\n}\n\nexport interface DlxBinaryResult {\n /** Path to the cached binary. */\n binaryPath: string\n /** Whether the binary was newly downloaded. */\n downloaded: boolean\n /** The spawn promise for the running process. */\n spawnPromise: ReturnType<typeof spawn>\n}\n\n/**\n * Generate a cache directory name from URL, similar to pnpm/npx.\n * Uses SHA256 hash to create content-addressed storage.\n */\nfunction generateCacheKey(url: string): string {\n return createHash('sha256').update(url).digest('hex')\n}\n\n/**\n * Get metadata file path for a cached binary.\n */\nfunction getMetadataPath(cacheEntryPath: string): string {\n return path.join(cacheEntryPath, '.dlx-metadata.json')\n}\n\n/**\n * Check if a cached binary is still valid.\n */\nasync function isCacheValid(\n cacheEntryPath: string,\n cacheTtl: number,\n): Promise<boolean> {\n try {\n const metaPath = getMetadataPath(cacheEntryPath)\n if (!existsSync(metaPath)) {\n return false\n }\n\n const metadata = await readJson(metaPath, { throws: false })\n if (!isObjectObject(metadata)) {\n return false\n }\n const now = Date.now()\n const age =\n now -\n (((metadata as Record<string, unknown>)['timestamp'] as number) || 0)\n\n return age < cacheTtl\n } catch {\n return false\n }\n}\n\n/**\n * Download a file from a URL with integrity checking.\n */\nasync function downloadBinary(\n url: string,\n destPath: string,\n checksum?: string | undefined,\n): Promise<string> {\n const response = await httpRequest(url)\n if (!response.ok) {\n throw new Error(\n `Failed to download binary: ${response.status} ${response.statusText}`,\n )\n }\n\n // Create a temporary file first.\n const tempPath = `${destPath}.download`\n const hasher = createHash('sha256')\n\n try {\n // Ensure directory exists.\n await fs.mkdir(path.dirname(destPath), { recursive: true })\n\n // Get the response as a buffer and compute hash.\n const buffer = response.body\n\n // Compute hash.\n hasher.update(buffer)\n const actualChecksum = hasher.digest('hex')\n\n // Verify checksum if provided.\n if (checksum && actualChecksum !== checksum) {\n throw new Error(\n `Checksum mismatch: expected ${checksum}, got ${actualChecksum}`,\n )\n }\n\n // Write to temp file.\n await fs.writeFile(tempPath, buffer)\n\n // Make executable on POSIX systems.\n if (!WIN32) {\n await fs.chmod(tempPath, 0o755)\n }\n\n // Move temp file to final location.\n await fs.rename(tempPath, destPath)\n\n return actualChecksum\n } catch (e) {\n // Clean up temp file on error.\n try {\n await safeDelete(tempPath)\n } catch {\n // Ignore cleanup errors.\n }\n throw e\n }\n}\n\n/**\n * Write metadata for a cached binary.\n */\nasync function writeMetadata(\n cacheEntryPath: string,\n url: string,\n checksum: string,\n): Promise<void> {\n const metaPath = getMetadataPath(cacheEntryPath)\n const metadata = {\n arch: os.arch(),\n checksum,\n platform: os.platform(),\n timestamp: Date.now(),\n url,\n version: '1.0.0',\n }\n await fs.writeFile(metaPath, JSON.stringify(metadata, null, 2))\n}\n\n/**\n * Clean expired entries from the DLX cache.\n */\nexport async function cleanDlxCache(\n maxAge: number = /*@__INLINE__*/ require('../constants/time').DLX_BINARY_CACHE_TTL,\n): Promise<number> {\n const cacheDir = getDlxCachePath()\n\n if (!existsSync(cacheDir)) {\n return 0\n }\n\n let cleaned = 0\n const now = Date.now()\n const entries = await fs.readdir(cacheDir)\n\n for (const entry of entries) {\n const entryPath = path.join(cacheDir, entry)\n const metaPath = getMetadataPath(entryPath)\n\n try {\n // eslint-disable-next-line no-await-in-loop\n if (!(await isDir(entryPath))) {\n continue\n }\n\n // eslint-disable-next-line no-await-in-loop\n const metadata = await readJson(metaPath, { throws: false })\n if (\n !metadata ||\n typeof metadata !== 'object' ||\n Array.isArray(metadata)\n ) {\n continue\n }\n const age =\n now -\n (((metadata as Record<string, unknown>)['timestamp'] as number) || 0)\n\n if (age > maxAge) {\n // Remove entire cache entry directory.\n // eslint-disable-next-line no-await-in-loop\n await safeDelete(entryPath, { force: true, recursive: true })\n cleaned += 1\n }\n } catch {\n // If we can't read metadata, check if directory is empty or corrupted.\n try {\n // eslint-disable-next-line no-await-in-loop\n const contents = await fs.readdir(entryPath)\n if (!contents.length) {\n // Remove empty directory.\n // eslint-disable-next-line no-await-in-loop\n await safeDelete(entryPath)\n cleaned += 1\n }\n } catch {}\n }\n }\n\n return cleaned\n}\n\n/**\n * Download and execute a binary from a URL with caching.\n */\nexport async function dlxBinary(\n args: readonly string[] | string[],\n options?: DlxBinaryOptions | undefined,\n spawnExtra?: SpawnExtra | undefined,\n): Promise<DlxBinaryResult> {\n const {\n cacheTtl = /*@__INLINE__*/ require('../constants/time').DLX_BINARY_CACHE_TTL,\n checksum,\n force = false,\n name,\n spawnOptions,\n url,\n } = { __proto__: null, ...options } as DlxBinaryOptions\n\n // Generate cache paths similar to pnpm/npx structure.\n const cacheDir = getDlxCachePath()\n const cacheKey = generateCacheKey(url)\n const cacheEntryDir = path.join(cacheDir, cacheKey)\n const binaryName = name || `binary-${process.platform}-${os.arch()}`\n const binaryPath = normalizePath(path.join(cacheEntryDir, binaryName))\n\n let downloaded = false\n let computedChecksum = checksum\n\n // Check if we need to download.\n if (\n !force &&\n existsSync(cacheEntryDir) &&\n (await isCacheValid(cacheEntryDir, cacheTtl))\n ) {\n // Binary is cached and valid, read the checksum from metadata.\n try {\n const metaPath = getMetadataPath(cacheEntryDir)\n const metadata = await readJson(metaPath, { throws: false })\n if (\n metadata &&\n typeof metadata === 'object' &&\n !Array.isArray(metadata) &&\n typeof (metadata as Record<string, unknown>)['checksum'] === 'string'\n ) {\n computedChecksum = (metadata as Record<string, unknown>)[\n 'checksum'\n ] as string\n } else {\n // If metadata is invalid, re-download.\n downloaded = true\n }\n } catch {\n // If we can't read metadata, re-download.\n downloaded = true\n }\n } else {\n downloaded = true\n }\n\n if (downloaded) {\n // Ensure cache directory exists.\n await fs.mkdir(cacheEntryDir, { recursive: true })\n\n // Download the binary.\n computedChecksum = await downloadBinary(url, binaryPath, checksum)\n await writeMetadata(cacheEntryDir, url, computedChecksum || '')\n }\n\n // Execute the binary.\n // On Windows, script files (.bat, .cmd, .ps1) require shell: true because\n // they are not executable on their own and must be run through cmd.exe.\n // Note: .exe files are actual binaries and don't need shell mode.\n const needsShell = WIN32 && /\\.(?:bat|cmd|ps1)$/i.test(binaryPath)\n // Windows cmd.exe PATH resolution behavior:\n // When shell: true on Windows with .cmd/.bat/.ps1 files, spawn will automatically\n // strip the full path down to just the basename without extension (e.g.,\n // C:\\cache\\test.cmd becomes just \"test\"). Windows cmd.exe then searches for \"test\"\n // in directories listed in PATH, trying each extension from PATHEXT environment\n // variable (.COM, .EXE, .BAT, .CMD, etc.) until it finds a match.\n //\n // Since our binaries are downloaded to a custom cache directory that's not in PATH\n // (unlike system package managers like npm/pnpm/yarn which are already in PATH),\n // we must prepend the cache directory to PATH so cmd.exe can locate the binary.\n //\n // This approach is consistent with how other tools handle Windows command execution:\n // - npm's promise-spawn: uses which.sync() to find commands in PATH\n // - cross-spawn: spawns cmd.exe with escaped arguments\n // - Node.js spawn with shell: true: delegates to cmd.exe which uses PATH\n const finalSpawnOptions = needsShell\n ? {\n ...spawnOptions,\n env: {\n ...spawnOptions?.env,\n PATH: `${cacheEntryDir}${path.delimiter}${process.env['PATH'] || ''}`,\n },\n shell: true,\n }\n : spawnOptions\n const spawnPromise = spawn(binaryPath, args, finalSpawnOptions, spawnExtra)\n\n return {\n binaryPath,\n downloaded,\n spawnPromise,\n }\n}\n\n/**\n * Get the DLX binary cache directory path.\n * Returns normalized path for cross-platform compatibility.\n * Uses same directory as dlx-package for unified DLX storage.\n */\nexport function getDlxCachePath(): string {\n return getSocketDlxDir()\n}\n\n/**\n * Get information about cached binaries.\n */\nexport async function listDlxCache(): Promise<\n Array<{\n age: number\n arch: string\n checksum: string\n name: string\n platform: string\n size: number\n url: string\n }>\n> {\n const cacheDir = getDlxCachePath()\n\n if (!existsSync(cacheDir)) {\n return []\n }\n\n const results = []\n const now = Date.now()\n const entries = await fs.readdir(cacheDir)\n\n for (const entry of entries) {\n const entryPath = path.join(cacheDir, entry)\n try {\n // eslint-disable-next-line no-await-in-loop\n if (!(await isDir(entryPath))) {\n continue\n }\n\n const metaPath = getMetadataPath(entryPath)\n // eslint-disable-next-line no-await-in-loop\n const metadata = await readJson(metaPath, { throws: false })\n if (\n !metadata ||\n typeof metadata !== 'object' ||\n Array.isArray(metadata)\n ) {\n continue\n }\n\n // Find the binary file in the directory.\n // eslint-disable-next-line no-await-in-loop\n const files = await fs.readdir(entryPath)\n const binaryFile = files.find(f => !f.startsWith('.'))\n\n if (binaryFile) {\n const binaryPath = path.join(entryPath, binaryFile)\n // eslint-disable-next-line no-await-in-loop\n const binaryStats = await fs.stat(binaryPath)\n\n const metaObj = metadata as Record<string, unknown>\n results.push({\n age: now - ((metaObj['timestamp'] as number) || 0),\n arch: (metaObj['arch'] as string) || 'unknown',\n checksum: (metaObj['checksum'] as string) || '',\n name: binaryFile,\n platform: (metaObj['platform'] as string) || 'unknown',\n size: binaryStats.size,\n url: (metaObj['url'] as string) || '',\n })\n }\n } catch {}\n }\n\n return results\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,yBAA2B;AAC3B,qBAA2C;AAC3C,qBAAe;AACf,uBAAiB;AAEjB,sBAAsB;AAEtB,gBAA4C;AAC5C,0BAA4B;AAC5B,qBAA+B;AAC/B,kBAA8B;AAC9B,mBAAgC;AAEhC,mBAAsB;AA8BtB,SAAS,iBAAiB,KAAqB;AAC7C,aAAO,+BAAW,QAAQ,EAAE,OAAO,GAAG,EAAE,OAAO,KAAK;AACtD;AAKA,SAAS,gBAAgB,gBAAgC;AACvD,SAAO,i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AK,UAAU;AAE5C,cAAM,UAAU;AAChB,gBAAQ,KAAK;AAAA,UACX,KAAK,OAAQ,QAAQ,WAAW,KAAgB;AAAA,UAChD,MAAO,QAAQ,MAAM,KAAgB;AAAA,UACrC,UAAW,QAAQ,UAAU,KAAgB;AAAA,UAC7C,MAAM;AAAA,UACN,UAAW,QAAQ,UAAU,KAAgB;AAAA,UAC7C,MAAM,YAAY;AAAA,UAClB,KAAM,QAAQ,KAAK,KAAgB;AAAA,QACrC,CAAC;AAAA,MACH;AAAA,IACF,QAAQ;AAAA,IAAC;AAAA,EACX;AAEA,SAAO;AACT;",
|
|
6
6
|
"names": ["path", "fs", "os"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { SpawnExtra, SpawnOptions } from './spawn';
|
|
2
|
+
import { spawn } from './spawn';
|
|
3
|
+
export interface DlxPackageOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Package to install (e.g., '@cyclonedx/cdxgen@10.0.0').
|
|
6
|
+
*/
|
|
7
|
+
package: string;
|
|
8
|
+
/**
|
|
9
|
+
* Force reinstallation even if package exists.
|
|
10
|
+
*/
|
|
11
|
+
force?: boolean | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* Additional spawn options for the execution.
|
|
14
|
+
*/
|
|
15
|
+
spawnOptions?: SpawnOptions | undefined;
|
|
16
|
+
}
|
|
17
|
+
export interface DlxPackageResult {
|
|
18
|
+
/** Path to the installed package directory. */
|
|
19
|
+
packageDir: string;
|
|
20
|
+
/** Path to the binary that was executed. */
|
|
21
|
+
binaryPath: string;
|
|
22
|
+
/** Whether the package was newly installed. */
|
|
23
|
+
installed: boolean;
|
|
24
|
+
/** The spawn promise for the running process. */
|
|
25
|
+
spawnPromise: ReturnType<typeof spawn>;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Execute a package via DLX - install if needed and run its binary.
|
|
29
|
+
*
|
|
30
|
+
* This is the Socket equivalent of npx/pnpm dlx/yarn dlx, but using
|
|
31
|
+
* our own cache directory (~/.socket/_dlx) and installation logic.
|
|
32
|
+
*
|
|
33
|
+
* Auto-forces reinstall for version ranges to get latest within range.
|
|
34
|
+
*/
|
|
35
|
+
export declare function dlxPackage(args: readonly string[] | string[], options?: DlxPackageOptions | undefined, spawnExtra?: SpawnExtra | undefined): Promise<DlxPackageResult>;
|