| 1 |
'use strict'; |
| 2 |
|
| 3 |
const path = require('path') |
| 4 |
const {debug} = require("../debug") |
| 5 |
const {getExeBasename} = require("../exe-type") |
| 6 |
const whichOrUndefined = require("../which-or-undefined") |
| 7 |
|
| 8 |
/** |
| 9 |
* Intercepts Node spawned processes. |
| 10 |
* |
| 11 |
* @param workingDir {string} Absolute system-dependent path to the directory containing the shim files. |
| 12 |
* @param options {import("../munge").InternalSpawnOptions} Original internal spawn options. |
| 13 |
* @return {import("../munge").InternalSpawnOptions} Updated internal spawn options. |
| 14 |
*/ |
| 15 |
function mungeNode(workingDir, options) { |
| 16 |
// Remember the original Node command to use it in the shim |
| 17 |
const originalNode = options.file |
| 18 |
|
| 19 |
const command = getExeBasename(options.file) |
| 20 |
// make sure it has a main script. |
| 21 |
// otherwise, just let it through. |
| 22 |
let a = 0 |
| 23 |
let hasMain = false |
| 24 |
let mainIndex = 1 |
| 25 |
for (a = 1; !hasMain && a < options.args.length; a++) { |
| 26 |
switch (options.args[a]) { |
| 27 |
case '-p': |
| 28 |
case '-i': |
| 29 |
case '--interactive': |
| 30 |
case '--eval': |
| 31 |
case '-e': |
| 32 |
case '-pe': |
| 33 |
hasMain = false |
| 34 |
a = options.args.length |
| 35 |
continue |
| 36 |
|
| 37 |
case '-r': |
| 38 |
case '--require': |
| 39 |
a += 1 |
| 40 |
continue |
| 41 |
|
| 42 |
default: |
| 43 |
// TODO: Double-check this part |
| 44 |
if (options.args[a].startsWith('-')) { |
| 45 |
continue |
| 46 |
} else { |
| 47 |
hasMain = true |
| 48 |
mainIndex = a |
| 49 |
a = options.args.length |
| 50 |
break |
| 51 |
} |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
const newArgs = [...options.args]; |
| 56 |
let newFile = options.file; |
| 57 |
|
| 58 |
if (hasMain) { |
| 59 |
const replace = path.join(workingDir, command) |
| 60 |
newArgs.splice(mainIndex, 0, replace) |
| 61 |
} |
| 62 |
|
| 63 |
// If the file is just something like 'node' then that'll |
| 64 |
// resolve to our shim, and so to prevent double-shimming, we need |
| 65 |
// to resolve that here first. |
| 66 |
// This also handles the case where there's not a main file, like |
| 67 |
// `node -e 'program'`, where we want to avoid the shim entirely. |
| 68 |
if (options.file === command) { |
| 69 |
const realNode = whichOrUndefined(options.file) || process.execPath |
| 70 |
newArgs[0] = realNode |
| 71 |
newFile = realNode |
| 72 |
} |
| 73 |
|
| 74 |
debug('mungeNode after', options.file, options.args) |
| 75 |
|
| 76 |
return {...options, file: newFile, args: newArgs, originalNode}; |
| 77 |
} |
| 78 |
|
| 79 |
module.exports = mungeNode |