Skip to content

Commit 5b4a7fc

Browse files
committed
fix: handle missing node-gyp gracefully in @npmcli/config definitions
1 parent c54d1e9 commit 5b4a7fc

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

workspaces/config/lib/definitions/definitions.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1304,7 +1304,13 @@ const definitions = {
13041304
flatten,
13051305
}),
13061306
'node-gyp': new Definition('node-gyp', {
1307-
default: require.resolve('node-gyp/bin/node-gyp.js'),
1307+
default: (() => {
1308+
try {
1309+
return require.resolve('node-gyp/bin/node-gyp.js')
1310+
} catch {
1311+
return ''
1312+
}
1313+
})(),
13081314
defaultDescription: `
13091315
The path to the node-gyp bin that ships with npm
13101316
`,

workspaces/config/test/definitions/definitions.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const t = require('tap')
22
const { resolve } = require('node:path')
33
const mockGlobals = require('@npmcli/mock-globals')
4+
const Module = require('node:module')
45

56
// have to fake the node version, or else it'll only pass on this one
67
mockGlobals(t, { 'process.version': 'v14.8.0', 'process.env.NODE_ENV': undefined })
@@ -1020,3 +1021,38 @@ t.test('otp changes auth-type', t => {
10201021
t.strictSame(obj, { 'auth-type': 'legacy', otp: 123456 })
10211022
t.end()
10221023
})
1024+
1025+
t.test('node-gyp', t => {
1026+
t.test('when node-gyp is available', t => {
1027+
const defs = mockDefs()
1028+
t.type(defs['node-gyp'].default, 'string')
1029+
t.ok(defs['node-gyp'].default.length > 0, 'has a default path')
1030+
t.ok(defs['node-gyp'].default.includes('node-gyp'), 'path contains node-gyp')
1031+
t.end()
1032+
})
1033+
1034+
t.test('when node-gyp is not available', t => {
1035+
const origResolve = Module._resolveFilename
1036+
1037+
Module._resolveFilename = function (request, parent, isMain, options) {
1038+
if (request === 'node-gyp/bin/node-gyp.js') {
1039+
const err = new Error(`Cannot find module '${request}'`)
1040+
err.code = 'MODULE_NOT_FOUND'
1041+
throw err
1042+
}
1043+
return origResolve.call(this, request, parent, isMain, options)
1044+
}
1045+
1046+
try {
1047+
const defs = require('../../lib/definitions/definitions.js')
1048+
t.equal(defs['node-gyp'].default, '', 'returns empty string when node-gyp not found')
1049+
} finally {
1050+
// Restore the original resolve
1051+
Module._resolveFilename = origResolve
1052+
}
1053+
1054+
t.end()
1055+
})
1056+
1057+
t.end()
1058+
})

0 commit comments

Comments
 (0)