Skip to content

Commit 3e6b2a8

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

File tree

7 files changed

+123
-39
lines changed

7 files changed

+123
-39
lines changed

.eslintrc.local.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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/es6/validate-engines.js'],
28+
'lib/es6/validate-engines.js': ['package.json', 'lib/cli.js'],
29+
}),
30+
}

.eslintrc.local.json

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

index.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
if (require.main === module) {
2-
require('./lib/cli.js')(process)
2+
require('./lib/es6/validate-engines.js')(
3+
process,
4+
() => require(require('path').resolve(__dirname, './lib/cli.js'))
5+
)
36
} else {
47
throw new Error('The programmatic API was removed in npm v8.0.0')
58
}

lib/cli.js

Lines changed: 4 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
/* 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
42

53
// Separated out for easier unit testing
6-
module.exports = async process => {
4+
module.exports = async (process, validateEngines) => {
75
// set it here so that regardless of what happens later, we don't
86
// leak any private CLI configs to other programs
97
process.title = 'npm'
@@ -13,31 +11,6 @@ module.exports = async process => {
1311
process.argv.splice(1, 1, 'npm', '-g')
1412
}
1513

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-
4114
const satisfies = require('semver/functions/satisfies')
4215
const exitHandler = require('./utils/exit-handler.js')
4316
const Npm = require('./npm.js')
@@ -51,14 +24,13 @@ module.exports = async process => {
5124
log.info('using', 'node@%s', process.version)
5225

5326
// 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)
27+
validateEngines.off()
5628
process.on('uncaughtException', exitHandler)
5729
process.on('unhandledRejection', exitHandler)
5830

5931
// 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)
32+
if (!satisfies(validateEngines.node, validateEngines.engines)) {
33+
log.warn('cli', validateEngines.unsupportedMessage)
6234
}
6335

6436
let cmd

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)