Skip to content

Commit 94a0d84

Browse files
committed
fix(libnpmexec): correctly resolve binaries from workspace dependencies
Fixes npm#9640 by preventing fallback to hoisted .bin directories for workspace packages.
1 parent a6f9044 commit 94a0d84

3 files changed

Lines changed: 323 additions & 19 deletions

File tree

‎workspaces/libnpmexec/lib/index.js‎

Lines changed: 62 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,13 @@ const exec = async (opts) => {
137137
return run()
138138
}
139139

140+
// Detect workspace context before appending the root path.
141+
// In workspace mode, the CLI explicitly sets pkgPath to the workspace dir.
142+
// When pkgPath is not provided (undefined), we're not in workspace context.
143+
const explicitPkgPath = opts.pkgPath
144+
const inWorkspaceContext = explicitPkgPath != null
145+
&& resolve(String(explicitPkgPath)) !== resolve(path)
146+
140147
// Look in the local tree too
141148
pkgPaths.push(path)
142149

@@ -146,6 +153,7 @@ const exec = async (opts) => {
146153
// - in any local packages (pkgPaths can have workspaces in them or just the root)
147154
// - in the local tree (path)
148155
// - globally
156+
let localTree
149157
if (needPackageCommandSwap) {
150158
// Local packages and local tree
151159
for (const p of pkgPaths) {
@@ -163,18 +171,58 @@ const exec = async (opts) => {
163171
}
164172
}
165173
if (needPackageCommandSwap) {
166-
// no bin entry in local packages or in tree, now we look for binPaths
167-
const dir = dirname(dirname(localBin))
168-
const localBinPath = await localFileExists(dir, args[0], '/')
169-
if (localBinPath) {
170-
binPaths.push(localBinPath)
171-
return await run()
172-
} else if (globalPath && await fileExists(`${globalBin}/${args[0]}`)) {
173-
binPaths.push(globalBin)
174+
const localArb = new Arborist({ ...flatOptions, path })
175+
localTree = await localArb.loadActual()
176+
177+
let targetNode = null
178+
for (const p of pkgPaths) {
179+
let wsNode = localTree
180+
for (const node of localTree.inventory.values()) {
181+
if (node.path === p) {
182+
wsNode = node; break
183+
}
184+
}
185+
186+
// If we didn't find the workspace node in the inventory, and it's not the root path, skip it.
187+
if (wsNode === localTree && p !== path) {
188+
continue
189+
}
190+
191+
for (const edge of wsNode.edgesOut.values()) {
192+
if (edge.to?.package?.bin?.[args[0]]) {
193+
targetNode = edge.to
194+
break
195+
}
196+
}
197+
if (targetNode) {
198+
break
199+
}
200+
}
201+
202+
if (targetNode) {
203+
const binFile = targetNode.package.bin[args[0]]
204+
const execNode = isWindows ? `"${process.execPath}"` : process.execPath
205+
args.splice(0, 1, execNode, resolve(targetNode.path, binFile))
174206
return await run()
207+
} else {
208+
// In workspace context, the dep-graph lookup is authoritative —
209+
// don't fall back to the hoisted .bin which may contain bins from
210+
// other workspaces' dependencies that this workspace doesn't declare.
211+
if (!inWorkspaceContext) {
212+
const dir = dirname(dirname(localBin))
213+
const localBinPath = await localFileExists(dir, args[0], '/')
214+
if (localBinPath) {
215+
binPaths.push(localBinPath)
216+
return await run()
217+
}
218+
}
219+
if (globalPath && await fileExists(`${globalBin}/${args[0]}`)) {
220+
binPaths.push(globalBin)
221+
return await run()
222+
}
223+
// We swap out args[0] with the bin from the manifest later
224+
packages.push(args[0])
175225
}
176-
// We swap out args[0] with the bin from the manifest later
177-
packages.push(args[0])
178226
}
179227
}
180228

@@ -188,8 +236,10 @@ const exec = async (opts) => {
188236
}
189237
}
190238

191-
const localArb = new Arborist({ ...flatOptions, path })
192-
const localTree = await localArb.loadActual()
239+
if (!localTree) {
240+
const localArb = new Arborist({ ...flatOptions, path })
241+
localTree = await localArb.loadActual()
242+
}
193243

194244
// Find anything that isn't installed locally
195245
const needInstall = []

‎workspaces/libnpmexec/test/index.js‎

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,177 @@ t.test('no args', async t => {
1414

1515
await exec()
1616
})
17+
18+
t.test('resolves binary from workspace dependencies', async t => {
19+
t.plan(2)
20+
21+
const { exec, path } = setup(t, {
22+
testdir: {
23+
'tool-v1': {
24+
'package.json': { name: 'tool-v1', version: '1.0.0', bin: { 'shared-bin': 'cli.js' } },
25+
'cli.js': { key: 'tool-v1', value: 'hello' },
26+
},
27+
packages: {
28+
a: {},
29+
},
30+
},
31+
mocks: {
32+
'@npmcli/arborist': class MockArborist {
33+
constructor (options) {
34+
this.path = options.path
35+
}
36+
37+
async loadActual () {
38+
const resolve = require('path').resolve
39+
const wsPath = resolve(this.path, 'packages/a')
40+
const wsNode = {
41+
path: wsPath,
42+
name: 'workspace-a',
43+
edgesOut: new Map([
44+
['tool-v1', {
45+
to: {
46+
path: `${this.path}/tool-v1`,
47+
package: { name: 'tool-v1', bin: { 'shared-bin': 'cli.js' } },
48+
},
49+
}],
50+
]),
51+
}
52+
const inventory = new Map([
53+
[wsPath, wsNode],
54+
])
55+
inventory.query = () => []
56+
return {
57+
inventory,
58+
edgesOut: new Map(),
59+
}
60+
}
61+
62+
async reify () {}
63+
},
64+
'../../lib/run-script': ({ args }) => {
65+
t.equal(args[0], process.execPath, 'args[0] should be process.execPath')
66+
t.match(args[1], /tool-v1[/\\]cli\.js$/, 'args[1] should point to correct cli.js')
67+
},
68+
},
69+
})
70+
71+
const resolve = require('path').resolve
72+
await exec({ pkgPath: resolve(path, 'packages/a'), args: ['shared-bin'] })
73+
})
74+
75+
t.test('resolves binary from workspace dependencies (windows)', async t => {
76+
t.plan(2)
77+
78+
const { exec, path } = setup(t, {
79+
testdir: {
80+
'tool-v1': {
81+
'package.json': { name: 'tool-v1', version: '1.0.0', bin: { 'shared-bin': 'cli.js' } },
82+
'cli.js': { key: 'tool-v1', value: 'hello' },
83+
},
84+
packages: {
85+
a: {},
86+
},
87+
},
88+
mocks: {
89+
'../../lib/is-windows.js': true,
90+
'@npmcli/arborist': class MockArborist {
91+
constructor (options) {
92+
this.path = options.path
93+
}
94+
95+
async loadActual () {
96+
const resolve = require('path').resolve
97+
const wsPath = resolve(this.path, 'packages/a')
98+
const wsNode = {
99+
path: wsPath,
100+
name: 'workspace-a',
101+
edgesOut: new Map([
102+
['tool-v1', {
103+
to: {
104+
path: `${this.path}/tool-v1`,
105+
package: { name: 'tool-v1', bin: { 'shared-bin': 'cli.js' } },
106+
},
107+
}],
108+
]),
109+
}
110+
const inventory = new Map([
111+
[wsPath, wsNode],
112+
])
113+
inventory.query = () => []
114+
return {
115+
inventory,
116+
edgesOut: new Map(),
117+
}
118+
}
119+
120+
async reify () {}
121+
},
122+
'../../lib/run-script': ({ args }) => {
123+
t.equal(args[0], `"${process.execPath}"`, 'args[0] should be securely quoted on Windows')
124+
t.match(args[1], /tool-v1[/\\]cli\.js$/, 'args[1] should point to correct cli.js')
125+
},
126+
},
127+
})
128+
129+
const resolve = require('path').resolve
130+
await exec({ pkgPath: resolve(path, 'packages/a'), args: ['shared-bin'] })
131+
})
132+
133+
t.test('does not fallback to hoisted .bin for missing workspace dep', async t => {
134+
t.plan(1)
135+
136+
const { exec, path } = setup(t, {
137+
testdir: {
138+
packages: {
139+
a: {},
140+
},
141+
},
142+
mocks: {
143+
'@npmcli/arborist': class MockArborist {
144+
constructor (options) {
145+
this.path = options.path
146+
}
147+
148+
async loadActual () {
149+
const resolve = require('path').resolve
150+
const wsPath = resolve(this.path, 'packages/a')
151+
const wsNode = {
152+
path: wsPath,
153+
name: 'workspace-a',
154+
edgesOut: new Map(),
155+
}
156+
const inventory = new Map([
157+
[wsPath, wsNode],
158+
])
159+
inventory.query = () => []
160+
return {
161+
inventory,
162+
edgesOut: new Map(),
163+
}
164+
}
165+
166+
async reify () {}
167+
},
168+
'../../lib/file-exists.js': {
169+
localFileExists: async () => {
170+
t.fail('localFileExists should not be called in workspace context for undeclared bins')
171+
return null
172+
},
173+
fileExists: async () => false,
174+
},
175+
pacote: {
176+
manifest: async () => {
177+
throw new Error('ABORT_TEST')
178+
},
179+
},
180+
},
181+
})
182+
183+
const resolve = require('path').resolve
184+
try {
185+
await exec({ pkgPath: resolve(path, 'packages/a'), args: ['missing-bin'] })
186+
t.fail('should have aborted')
187+
} catch (err) {
188+
t.equal(err.message, 'ABORT_TEST', 'skipped localFileExists and proceeded to missingFromTree')
189+
}
190+
})

0 commit comments

Comments
 (0)