UNPKG

2.92 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3const cli = require('../lib/cli.js')
4
5// run the resulting command as `npm exec ...args`
6process.argv[1] = require.resolve('./npm-cli.js')
7process.argv.splice(2, 0, 'exec')
8
9// TODO: remove the affordances for removed items in npm v9
10const removedSwitches = new Set([
11 'always-spawn',
12 'ignore-existing',
13 'shell-auto-fallback',
14])
15
16const removedOpts = new Set([
17 'npm',
18 'node-arg',
19 'n',
20])
21
22const removed = new Set([
23 ...removedSwitches,
24 ...removedOpts,
25])
26
27const { definitions, shorthands } = require('@npmcli/config/lib/definitions')
28const npmSwitches = Object.entries(definitions)
29 .filter(([, { type }]) => type === Boolean ||
30 (Array.isArray(type) && type.includes(Boolean)))
31 .map(([key]) => key)
32
33// things that don't take a value
34const switches = new Set([
35 ...removedSwitches,
36 ...npmSwitches,
37 'no-install',
38 'quiet',
39 'q',
40 'version',
41 'v',
42 'help',
43 'h',
44])
45
46// things that do take a value
47const opts = new Set([
48 ...removedOpts,
49 'package',
50 'p',
51 'cache',
52 'userconfig',
53 'call',
54 'c',
55 'shell',
56 'npm',
57 'node-arg',
58 'n',
59])
60
61// break out of loop when we find a positional argument or --
62// If we find a positional arg, we shove -- in front of it, and
63// let the normal npm cli handle the rest.
64let i
65let sawRemovedFlags = false
66for (i = 3; i < process.argv.length; i++) {
67 const arg = process.argv[i]
68 if (arg === '--') {
69 break
70 } else if (/^-/.test(arg)) {
71 const [key, ...v] = arg.replace(/^-+/, '').split('=')
72
73 switch (key) {
74 case 'p':
75 process.argv[i] = ['--package', ...v].join('=')
76 break
77
78 case 'shell':
79 process.argv[i] = ['--script-shell', ...v].join('=')
80 break
81
82 case 'no-install':
83 process.argv[i] = '--yes=false'
84 break
85
86 default:
87 // resolve shorthands and run again
88 if (shorthands[key] && !removed.has(key)) {
89 const a = [...shorthands[key]]
90 if (v.length) {
91 a.push(v.join('='))
92 }
93 process.argv.splice(i, 1, ...a)
94 i--
95 continue
96 }
97 break
98 }
99
100 if (removed.has(key)) {
101 // eslint-disable-next-line no-console
102 console.error(`npx: the --${key} argument has been removed.`)
103 sawRemovedFlags = true
104 process.argv.splice(i, 1)
105 i--
106 }
107
108 if (v.length === 0 && !switches.has(key) &&
109 (opts.has(key) || !/^-/.test(process.argv[i + 1]))) {
110 // value will be next argument, skip over it.
111 if (removed.has(key)) {
112 // also remove the value for the cut key.
113 process.argv.splice(i + 1, 1)
114 } else {
115 i++
116 }
117 }
118 } else {
119 // found a positional arg, put -- in front of it, and we're done
120 process.argv.splice(i, 0, '--')
121 break
122 }
123}
124
125if (sawRemovedFlags) {
126 // eslint-disable-next-line no-console
127 console.error('See `npm help exec` for more information')
128}
129
130cli(process)