Skip to content

Commit 8b5ee0a

Browse files
committed
fix: refactor engines validation to lint syntax
1 parent 173bc89 commit 8b5ee0a

File tree

7 files changed

+195
-107
lines changed

7 files changed

+195
-107
lines changed

.eslintrc.local.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
const { resolve, relative } = require('path')
2+
3+
// Create an override to lockdown a file to es6 syntax only
4+
// and only allow it to require an allowlist of files
5+
const res = (p) => resolve(__dirname, p)
6+
const rel = (p) => relative(__dirname, res(p))
7+
const braces = (a) => a.length > 1 ? `{${a.map(rel).join(',')}}` : a[0]
8+
9+
const es6Files = (e) => Object.entries(e).map(([file, allow]) => ({
10+
files: `./${rel(file)}`,
11+
parserOptions: {
12+
ecmaVersion: 6,
13+
},
14+
rules: {
15+
'node/no-restricted-require': ['error', [{
16+
name: ['/**', `!${__dirname}/${braces(allow)}`],
17+
message: `This file can only require: ${allow.join(',')}`,
18+
}]],
19+
},
20+
}))
21+
22+
module.exports = {
23+
rules: {
24+
'no-console': 'error',
25+
},
26+
overrides: es6Files({
27+
'index.js': ['lib/cli.js'],
28+
'bin/npm-cli.js': ['lib/cli.js'],
29+
'bin/npx-cli.js': ['bin/npm-cli.js', 'lib/cli.js', 'lib/utils/config/index.js'],
30+
'lib/cli.js': ['lib/es6/validate-engines.js'],
31+
'lib/es6/validate-engines.js': ['package.json'],
32+
}),
33+
}

.eslintrc.local.json

Lines changed: 0 additions & 5 deletions
This file was deleted.

lib/cli-entry.js

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/* eslint-disable max-len */
2+
3+
// Separated out for easier unit testing
4+
module.exports = async (process, validateEngines) => {
5+
// set it here so that regardless of what happens later, we don't
6+
// leak any private CLI configs to other programs
7+
process.title = 'npm'
8+
9+
// if npm is called as "npmg" or "npm_g", then run in global mode.
10+
if (process.argv[1][process.argv[1].length - 1] === 'g') {
11+
process.argv.splice(1, 1, 'npm', '-g')
12+
}
13+
14+
const satisfies = require('semver/functions/satisfies')
15+
const exitHandler = require('./utils/exit-handler.js')
16+
const Npm = require('./npm.js')
17+
const npm = new Npm()
18+
exitHandler.setNpm(npm)
19+
20+
// only log node and npm paths in argv initially since argv can contain sensitive info. a cleaned version will be logged later
21+
const log = require('./utils/log-shim.js')
22+
log.verbose('cli', process.argv.slice(0, 2).join(' '))
23+
log.info('using', 'npm@%s', npm.version)
24+
log.info('using', 'node@%s', process.version)
25+
26+
// At this point we've required a few files and can be pretty sure we dont contain invalid syntax for this version of node. It's possible a lazy require would, but that's unlikely enough that it's not worth catching anymore and we attach the more important exit handlers.
27+
validateEngines.off()
28+
process.on('uncaughtException', exitHandler)
29+
process.on('unhandledRejection', exitHandler)
30+
31+
// It is now safe to log a warning if they are using a version of node that is not going to fail on syntax errors but is still unsupported and untested and might not work reliably. This is safe to use the logger now which we want since this will show up in the error log too.
32+
if (!satisfies(validateEngines.node, validateEngines.engines)) {
33+
log.warn('cli', validateEngines.unsupportedMessage)
34+
}
35+
36+
let cmd
37+
// Now actually fire up npm and run the command.
38+
// This is how to use npm programmatically:
39+
try {
40+
await npm.load()
41+
42+
// npm -v
43+
if (npm.config.get('version', 'cli')) {
44+
npm.output(npm.version)
45+
return exitHandler()
46+
}
47+
48+
// npm --versions
49+
if (npm.config.get('versions', 'cli')) {
50+
npm.argv = ['version']
51+
npm.config.set('usage', false, 'cli')
52+
}
53+
54+
cmd = npm.argv.shift()
55+
if (!cmd) {
56+
npm.output(await npm.usage)
57+
process.exitCode = 1
58+
return exitHandler()
59+
}
60+
61+
await npm.exec(cmd)
62+
return exitHandler()
63+
} catch (err) {
64+
if (err.code === 'EUNKNOWNCOMMAND') {
65+
const didYouMean = require('./utils/did-you-mean.js')
66+
const suggestions = await didYouMean(npm, npm.localPrefix, cmd)
67+
npm.output(`Unknown command: "${cmd}"${suggestions}\n`)
68+
npm.output('To see a list of supported npm commands, run:\n npm help')
69+
process.exitCode = 1
70+
return exitHandler()
71+
}
72+
return exitHandler(err)
73+
}
74+
}

lib/cli.js

Lines changed: 3 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -1,102 +1,4 @@
1-
/* eslint-disable max-len */
2-
// Code in this file should work in all conceivably runnable versions of node.
3-
// A best effort is made to catch syntax errors to give users a good error message if they are using a node version that doesn't allow syntax we are using in other files such as private properties, etc
1+
const validateEngines = require('./es6/validate-engines.js')
2+
const cliEntry = require('path').resolve(__dirname, 'cli-entry.js')
43

5-
// Separated out for easier unit testing
6-
module.exports = async process => {
7-
// set it here so that regardless of what happens later, we don't
8-
// leak any private CLI configs to other programs
9-
process.title = 'npm'
10-
11-
// if npm is called as "npmg" or "npm_g", then run in global mode.
12-
if (process.argv[1][process.argv[1].length - 1] === 'g') {
13-
process.argv.splice(1, 1, 'npm', '-g')
14-
}
15-
16-
const nodeVersion = process.version.replace(/-.*$/, '')
17-
const pkg = require('../package.json')
18-
const engines = pkg.engines.node
19-
const npmVersion = `v${pkg.version}`
20-
21-
const unsupportedMessage = `npm ${npmVersion} does not support Node.js ${nodeVersion}. This version of npm supports the following node versions: \`${engines}\`. You can find the latest version at https://nodejs.org/.`
22-
23-
const brokenMessage = `ERROR: npm ${npmVersion} is known not to run on Node.js ${nodeVersion}. This version of npm supports the following node versions: \`${engines}\`. You can find the latest version at https://nodejs.org/.`
24-
25-
// Coverage ignored because this is only hit in very unsupported node versions and it's a best effort attempt to show something nice in those cases
26-
/* istanbul ignore next */
27-
const syntaxErrorHandler = (err) => {
28-
if (err instanceof SyntaxError) {
29-
// eslint-disable-next-line no-console
30-
console.error(`${brokenMessage}\n\nERROR:`)
31-
// eslint-disable-next-line no-console
32-
console.error(err)
33-
return process.exit(1)
34-
}
35-
throw err
36-
}
37-
38-
process.on('uncaughtException', syntaxErrorHandler)
39-
process.on('unhandledRejection', syntaxErrorHandler)
40-
41-
const satisfies = require('semver/functions/satisfies')
42-
const exitHandler = require('./utils/exit-handler.js')
43-
const Npm = require('./npm.js')
44-
const npm = new Npm()
45-
exitHandler.setNpm(npm)
46-
47-
// only log node and npm paths in argv initially since argv can contain sensitive info. a cleaned version will be logged later
48-
const log = require('./utils/log-shim.js')
49-
log.verbose('cli', process.argv.slice(0, 2).join(' '))
50-
log.info('using', 'npm@%s', npm.version)
51-
log.info('using', 'node@%s', process.version)
52-
53-
// At this point we've required a few files and can be pretty sure we dont contain invalid syntax for this version of node. It's possible a lazy require would, but that's unlikely enough that it's not worth catching anymore and we attach the more important exit handlers.
54-
process.off('uncaughtException', syntaxErrorHandler)
55-
process.off('unhandledRejection', syntaxErrorHandler)
56-
process.on('uncaughtException', exitHandler)
57-
process.on('unhandledRejection', exitHandler)
58-
59-
// It is now safe to log a warning if they are using a version of node that is not going to fail on syntax errors but is still unsupported and untested and might not work reliably. This is safe to use the logger now which we want since this will show up in the error log too.
60-
if (!satisfies(nodeVersion, engines)) {
61-
log.warn('cli', unsupportedMessage)
62-
}
63-
64-
let cmd
65-
// Now actually fire up npm and run the command.
66-
// This is how to use npm programmatically:
67-
try {
68-
await npm.load()
69-
70-
// npm -v
71-
if (npm.config.get('version', 'cli')) {
72-
npm.output(npm.version)
73-
return exitHandler()
74-
}
75-
76-
// npm --versions
77-
if (npm.config.get('versions', 'cli')) {
78-
npm.argv = ['version']
79-
npm.config.set('usage', false, 'cli')
80-
}
81-
82-
cmd = npm.argv.shift()
83-
if (!cmd) {
84-
npm.output(await npm.usage)
85-
process.exitCode = 1
86-
return exitHandler()
87-
}
88-
89-
await npm.exec(cmd)
90-
return exitHandler()
91-
} catch (err) {
92-
if (err.code === 'EUNKNOWNCOMMAND') {
93-
const didYouMean = require('./utils/did-you-mean.js')
94-
const suggestions = await didYouMean(npm, npm.localPrefix, cmd)
95-
npm.output(`Unknown command: "${cmd}"${suggestions}\n`)
96-
npm.output('To see a list of supported npm commands, run:\n npm help')
97-
process.exitCode = 1
98-
return exitHandler()
99-
}
100-
return exitHandler(err)
101-
}
102-
}
4+
module.exports = (process) => validateEngines(process, () => require(cliEntry))

lib/es6/validate-engines.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// This is separate to indicate that it should contain code we expect to work in
2+
// all versions of node >= 6. This is a best effort to catch syntax errors to
3+
// give users a good error message if they are using a node version that doesn't
4+
// allow syntax we are using such as private properties, etc. This file is
5+
// linted with ecmaVersion=6 so we don't use invalid syntax, which is set in the
6+
// .eslintrc.local.json file
7+
8+
const { engines: { node: engines }, version } = require('../../package.json')
9+
const npm = `v${version}`
10+
11+
module.exports = (process, getCli) => {
12+
const node = process.version.replace(/-.*$/, '')
13+
14+
/* eslint-disable-next-line max-len */
15+
const unsupportedMessage = `npm ${npm} does not support Node.js ${node}. This version of npm supports the following node versions: \`${engines}\`. You can find the latest version at https://nodejs.org/.`
16+
17+
/* eslint-disable-next-line max-len */
18+
const brokenMessage = `ERROR: npm ${npm} is known not to run on Node.js ${node}. This version of npm supports the following node versions: \`${engines}\`. You can find the latest version at https://nodejs.org/.`
19+
20+
// coverage ignored because this is only hit in very unsupported node versions
21+
// and it's a best effort attempt to show something nice in those cases
22+
/* istanbul ignore next */
23+
const syntaxErrorHandler = (err) => {
24+
if (err instanceof SyntaxError) {
25+
// eslint-disable-next-line no-console
26+
console.error(`${brokenMessage}\n\nERROR:`)
27+
// eslint-disable-next-line no-console
28+
console.error(err)
29+
return process.exit(1)
30+
}
31+
throw err
32+
}
33+
34+
process.on('uncaughtException', syntaxErrorHandler)
35+
process.on('unhandledRejection', syntaxErrorHandler)
36+
37+
// require this only after setting up the error handlers
38+
const cli = getCli()
39+
return cli(process, {
40+
node,
41+
npm,
42+
engines,
43+
unsupportedMessage,
44+
off: () => {
45+
process.off('uncaughtException', syntaxErrorHandler)
46+
process.off('unhandledRejection', syntaxErrorHandler)
47+
},
48+
})
49+
}

test/lib/cli.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const t = require('tap')
22
const { load: loadMockNpm } = require('../fixtures/mock-npm.js')
33
const tmock = require('../fixtures/tmock')
4+
const validateEngines = require('../../lib/es6/validate-engines.js')
45

56
const cliMock = async (t, opts) => {
67
let exitHandlerArgs = null
@@ -20,7 +21,7 @@ const cliMock = async (t, opts) => {
2021

2122
return {
2223
Npm,
23-
cli,
24+
cli: (p) => validateEngines(p, () => cli),
2425
outputs,
2526
exitHandlerCalled: () => exitHandlerArgs,
2627
exitHandlerNpm: () => npm,

test/lib/es6/validate-engines.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const t = require('tap')
2+
const mockGlobals = require('@npmcli/mock-globals')
3+
const tmock = require('../../fixtures/tmock')
4+
5+
const mockValidateEngines = (t) => {
6+
const validateEngines = tmock(t, '{LIB}/es6/validate-engines.js', {
7+
'{ROOT}/package.json': { version: '1.2.3', engines: { node: '>=0' } },
8+
})
9+
mockGlobals(t, { 'process.version': 'v4.5.6' })
10+
return validateEngines(process, () => (_, r) => r)
11+
}
12+
13+
t.test('validate engines', async t => {
14+
t.equal(process.listenerCount('uncaughtException'), 0)
15+
t.equal(process.listenerCount('unhandledRejection'), 0)
16+
17+
const result = mockValidateEngines(t)
18+
19+
t.equal(process.listenerCount('uncaughtException'), 1)
20+
t.equal(process.listenerCount('unhandledRejection'), 1)
21+
22+
t.match(result, {
23+
node: 'v4.5.6',
24+
npm: 'v1.2.3',
25+
engines: '>=0',
26+
/* eslint-disable-next-line max-len */
27+
unsupportedMessage: 'npm v1.2.3 does not support Node.js v4.5.6. This version of npm supports the following node versions: `>=0`. You can find the latest version at https://nodejs.org/.',
28+
})
29+
30+
result.off()
31+
32+
t.equal(process.listenerCount('uncaughtException'), 0)
33+
t.equal(process.listenerCount('unhandledRejection'), 0)
34+
})

0 commit comments

Comments
 (0)