codekingpro/portable-devtools
115k
1const makeSpawnArgs = require('./make-spawn-args.js')
2const promiseSpawn = require('@npmcli/promise-spawn')
3const packageEnvs = require('./package-envs.js')
4const { isNodeGypPackage, defaultGypInstallScript } = require('@npmcli/node-gyp')
5const signalManager = require('./signal-manager.js')
6const isServerPackage = require('./is-server-package.js')
7
8const runScriptPkg = async options => {
9 const {
10 args = [],
11 binPaths = false,
12 env = {},
13 event,
14 nodeGyp,
15 path,
16 pkg,
17 scriptShell,
18 // how long to wait for a process.kill signal
19 // only exposed here so that we can make the test go a bit faster.
20 signalTimeout = 500,
21 stdio = 'pipe',
22 stdioString,
23 } = options
24
25 const { scripts = {}, gypfile } = pkg
26 let cmd = null
27 if (options.cmd) {
28 cmd = options.cmd
29 } else if (pkg.scripts && pkg.scripts[event]) {
30 cmd = pkg.scripts[event]
31 } else if (
32 // If there is no preinstall or install script, default to rebuilding node-gyp packages.
33 event === 'install' &&
34 !scripts.install &&
35 !scripts.preinstall &&
36 gypfile !== false &&
37 await isNodeGypPackage(path)
38 ) {
39 cmd = defaultGypInstallScript
40 } else if (event === 'start' && await isServerPackage(path)) {
41 cmd = 'node server.js'
42 }
43
44 if (!cmd) {
45 return { code: 0, signal: null }
46 }
47
48 let inputEnd = () => {}
49 if (stdio === 'inherit') {
50 let banner
51 if (pkg._id) {
52 banner = `\n> ${pkg._id} ${event}\n`
53 } else {
54 banner = `\n> ${event}\n`
55 }
56 banner += `> ${cmd.trim().replace(/\n/g, '\n> ')}`
57 if (args.length) {
58 banner += ` ${args.join(' ')}`
59 }
60 banner += '\n'
61 const { output, input } = require('proc-log')
62 output.standard(banner)
63 inputEnd = input.start()
64 }
65
66 const [spawnShell, spawnArgs, spawnOpts] = makeSpawnArgs({
67 args,
68 binPaths,
69 cmd,
70 env: { ...env, ...packageEnvs(pkg) },
71 event,
72 nodeGyp,
73 path,
74 scriptShell,
75 stdio,
76 stdioString,
77 })
78
79 const p = promiseSpawn(spawnShell, spawnArgs, spawnOpts, {
80 event,
81 script: cmd,
82 pkgid: pkg._id,
83 path,
84 })
85
86 if (stdio === 'inherit') {
87 signalManager.add(p.process)
88 }
89
90 if (p.stdin) {
91 p.stdin.end()
92 }
93
94 return p.catch(er => {
95 const { signal } = er
96 // coverage disabled because win32 never emits signals
97 /* istanbul ignore next */
98 if (stdio === 'inherit' && signal) {
99 // by the time we reach here, the child has already exited. we send the
100 // signal back to ourselves again so that npm will exit with the same
101 // status as the child
102 process.kill(process.pid, signal)
103
104 // just in case we don't die, reject after 500ms
105 // this also keeps the node process open long enough to actually
106 // get the signal, rather than terminating gracefully.
107 return new Promise((res, rej) => setTimeout(() => rej(er), signalTimeout))
108 } else {
109 throw er
110 }
111 }).finally(inputEnd)
112}
113
114module.exports = runScriptPkg
115 