@@ -25,21 +25,21 @@ function resolveBin(bin) {
2525
2626const gitBin = resolveBin ( "git" ) ;
2727
28- // Resolve Node from PATH (works when running under Bun),
29- // fall back to execPath if resolution fails
30- let nodeBin ;
31- try {
32- nodeBin = resolveBin ( "node" ) ;
33- console . log ( "Resolved nodeBin" , nodeBin ) ;
34- } catch ( _err ) {
35- console . log ( "Failed to resolve nodeBin" , _err ) ;
36- nodeBin = execPath ;
28+ // Helpers to resolve node and npm-cli when needed
29+ function getNodeBin ( ) {
30+ try {
31+ return resolveBin ( "node" ) ;
32+ } catch ( _err ) {
33+ return execPath ;
34+ }
3735}
3836
39- const npmCli = path . join (
40- path . dirname ( nodeBin ) ,
41- "../lib/node_modules/npm/bin/npm-cli.js" ,
42- ) ;
37+ function getNpmCli ( nodeBin ) {
38+ return path . join (
39+ path . dirname ( nodeBin ) ,
40+ "../lib/node_modules/npm/bin/npm-cli.js" ,
41+ ) ;
42+ }
4343
4444/**
4545 * @typedef {{
@@ -301,10 +301,46 @@ export function setup(cwd = process.cwd()) {
301301 * @param {ExecOptions } [options]
302302 * @return {Promise<ExecResult> }
303303 */
304- npm ( args = [ ] , options = { } ) {
304+ async npm ( args = [ ] , options = { } ) {
305305 console . log ( "the options" , options ) ;
306- // Always invoke npm via the current Node.js executable to avoid PATH/resolution issues
307- // on different runners or when using Bun to execute this script.
306+ // Validate working directory to avoid confusing ENOENT from invalid cwd
307+ if ( options . cwd ) {
308+ try {
309+ await fs . stat ( options . cwd ) ;
310+ } catch ( e ) {
311+ console . error ( "Invalid cwd for npm" , options . cwd , e ) ;
312+ throw e ;
313+ }
314+ }
315+
316+ // 1) Prefer corepack to resolve the correct npm
317+ try {
318+ return await exec ( "corepack" , [ "npm" , ...args ] , options ) ;
319+ } catch ( _corepackErr ) {
320+ // ignore and try next
321+ }
322+
323+ // 2) Try PATH npm
324+ try {
325+ return await exec ( "npm" , args , options ) ;
326+ } catch ( _npmErr ) {
327+ // ignore and try fallback
328+ }
329+
330+ // 3) Fallback: node + npm-cli resolved at call time
331+ const nodeBin = getNodeBin ( ) ;
332+ const npmCli = getNpmCli ( nodeBin ) ;
333+ try {
334+ await fs . access ( nodeBin ) ;
335+ } catch ( e ) {
336+ console . error ( "nodeBin not accessible" , nodeBin , e ) ;
337+ }
338+ try {
339+ await fs . access ( npmCli ) ;
340+ } catch ( e ) {
341+ console . error ( "npmCli not accessible" , npmCli , e ) ;
342+ }
343+ console . log ( "Falling back to node+cli" , { nodeBin, npmCli } ) ;
308344 return exec ( nodeBin , [ npmCli , ...args ] , options ) ;
309345 } ,
310346 } ;
0 commit comments