Skip to content

Commit 4c9eacb

Browse files
fix(arborist): clean up stale .store and hoisted dirs on strategy switch (#9649)
Backport of #9647 to `release/v11`. Co-authored-by: Manzoor Wani <manzoorwani.jk@gmail.com>
1 parent ae64f88 commit 4c9eacb

2 files changed

Lines changed: 147 additions & 11 deletions

File tree

‎workspaces/arborist/lib/arborist/reify.js‎

Lines changed: 55 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,14 @@ module.exports = cls => class Reifier extends cls {
144144
if (!this.options.dryRun && !this.options.packageLockOnly) {
145145
await this.#cleanOrphanedStoreEntries()
146146
}
147+
} else if (!this.options.dryRun && !this.options.packageLockOnly) {
148+
// The .store directory is exclusively a linked-strategy artifact, and load-actual ignores dot-directories, so the diff never sees it.
149+
// Remove it here when switching away from linked so it does not linger under hoisted/nested.
150+
// Only do this for a full-project install: a workspace-filtered or --workspaces=false install may leave out-of-scope workspaces with links still pointing into the store.
151+
const filtered = this.options.workspaces.length > 0 || !this.options.workspacesEnabled
152+
if (!filtered) {
153+
await this.#removeStaleStoreDir()
154+
}
147155
}
148156
} finally {
149157
// Restore the non-isolated tree so the lockfile is preserved and a reused Arborist never sees the isolated tree, even if reify throws.
@@ -1438,6 +1446,18 @@ module.exports = cls => class Reifier extends cls {
14381446
timeEnd()
14391447
}
14401448

1449+
// Remove the root .store left behind by a previous linked install when reifying under a non-linked strategy.
1450+
async #removeStaleStoreDir () {
1451+
const storeDir = resolve(this.path, 'node_modules', '.store')
1452+
if (!existsSync(storeDir)) {
1453+
return
1454+
}
1455+
log.silly('reify', 'removing stale .store from a previous linked install')
1456+
await rm(storeDir, { recursive: true, force: true })
1457+
.catch(/* istanbul ignore next -- rm with force rarely fails */
1458+
er => log.warn('cleanup', 'Failed to remove stale .store directory', er))
1459+
}
1460+
14411461
// After a linked install, scan node_modules/.store/ and remove any directories that are not referenced by the current ideal tree.
14421462
// Store entries become orphaned when dependencies are updated or removed, because the diff never sees the old store keys.
14431463
// Then sweep the top-level node_modules/ for orphaned symlinks (e.g. an uninstalled dep whose store entry was just removed) so we don't leave dangling links.
@@ -1476,7 +1496,7 @@ module.exports = cls => class Reifier extends cls {
14761496
// Locations are normalized to forward slashes here because IsolatedNode/IsolatedLink locations are built with path.join, which uses backslashes on Windows.
14771497
const validKeys = new Set()
14781498
const nmDirs = new Map()
1479-
// Valid bin shim names per node_modules dir, collected from each top-level link's package.bin so the .bin sweep keeps only shims a still-linked package provides.
1499+
// Valid bin shim names per node_modules dir, collected from each top-level entry's package.bin so the .bin sweep keeps only shims a still-installed package provides.
14801500
const binsByDir = new Map()
14811501
const NM_PREFIX = 'node_modules/'
14821502
const STORE_MARKER = '/.store/'
@@ -1490,13 +1510,11 @@ module.exports = cls => class Reifier extends cls {
14901510
validKeys.add(key)
14911511
continue
14921512
}
1493-
if (!child.isLink) {
1494-
continue
1495-
}
14961513
// Tree-only Links never exist on disk; skipping them lets the sweep remove any stale self-link left by an older npm version.
1497-
if (child.isUndeclaredWorkspaceLink) {
1514+
if (child.isLink && child.isUndeclaredWorkspaceLink) {
14981515
continue
14991516
}
1517+
// Real top-level Nodes (e.g. the root's bundled deps) fall through here too, so they are recorded as valid and never swept as stale.
15001518
const nmIdx = loc.lastIndexOf(NM_PREFIX)
15011519
if (nmIdx === -1 || loc.includes(STORE_MARKER)) {
15021520
continue
@@ -1640,8 +1658,10 @@ module.exports = cls => class Reifier extends cls {
16401658
// Remove node_modules/ entries that aren't represented in the ideal tree.
16411659
// Run for the project root and each workspace's node_modules.
16421660
// The linked diff path can't see these because #buildLinkedActualForDiff derives the actual tree from the ideal, so removed deps are never compared.
1643-
// Only symlinks whose target resolves inside the project root are removed — that covers store links (node_modules/.store/...) and workspace self-links (e.g. node_modules/<ws> -> ../packages/<ws>) that npm itself created.
1644-
// Symlinks pointing outside the project (e.g. `npm link foo` without --save targeting the global prefix, or hand-made `ln -s` to an external path) and real directories are preserved.
1661+
// Two kinds of stale entry are removed:
1662+
// - symlinks whose target resolves inside the project root — store links (node_modules/.store/...) and workspace self-links (e.g. node_modules/<ws> -> ../packages/<ws>) that npm itself created.
1663+
// - real package directories — hoisted-layout deps left behind when switching from the hoisted strategy to linked, where every valid top-level entry is a symlink.
1664+
// Symlinks pointing outside the project (e.g. `npm link foo` without --save targeting the global prefix, or hand-made `ln -s` to an external path) and non-package real directories are preserved.
16451665
async #cleanOrphanedTopLevelLinks (nmDir, validTopLevel) {
16461666
const projectPrefix = resolve(this.path) + sep
16471667
let dirents
@@ -1662,7 +1682,15 @@ module.exports = cls => class Reifier extends cls {
16621682
return resolve(dirname(linkPath), target).startsWith(projectPrefix)
16631683
}
16641684

1685+
// A real directory is stale only when it is an actual package (has a package.json), so unrelated user directories are never touched.
1686+
const isStaleRealPkg = (dirent, entPath) =>
1687+
dirent.isDirectory() && existsSync(resolve(entPath, 'package.json'))
1688+
1689+
const isOrphan = async (dirent, entPath) =>
1690+
(dirent.isSymbolicLink() && await isOurOrphan(entPath)) || isStaleRealPkg(dirent, entPath)
1691+
16651692
const orphaned = []
1693+
const scopes = new Set()
16661694
for (const ent of dirents) {
16671695
// skip npm-managed entries (.bin, .store, .package-lock.json, etc)
16681696
if (ent.name.startsWith('.')) {
@@ -1678,11 +1706,12 @@ module.exports = cls => class Reifier extends cls {
16781706
}
16791707
for (const pkgEnt of scoped) {
16801708
const key = `${ent.name}${sep}${pkgEnt.name}`
1681-
if (!validTopLevel.has(key) && pkgEnt.isSymbolicLink() && await isOurOrphan(resolve(nmDir, key))) {
1709+
if (!validTopLevel.has(key) && await isOrphan(pkgEnt, resolve(nmDir, key))) {
16821710
orphaned.push(key)
1711+
scopes.add(ent.name)
16831712
}
16841713
}
1685-
} else if (!validTopLevel.has(ent.name) && ent.isSymbolicLink() && await isOurOrphan(resolve(nmDir, ent.name))) {
1714+
} else if (!validTopLevel.has(ent.name) && await isOrphan(ent, resolve(nmDir, ent.name))) {
16861715
orphaned.push(ent.name)
16871716
}
16881717
}
@@ -1691,14 +1720,29 @@ module.exports = cls => class Reifier extends cls {
16911720
return
16921721
}
16931722

1694-
log.silly('reify', 'cleaning orphaned top-level links', orphaned)
1723+
log.silly('reify', 'cleaning orphaned top-level entries', orphaned)
16951724
await promiseAllRejectLate(
16961725
orphaned.map(name =>
16971726
rm(resolve(nmDir, name), { recursive: true, force: true })
16981727
.catch(/* istanbul ignore next -- rm with force rarely fails */
1699-
er => log.warn('cleanup', `Failed to remove orphaned link ${name}`, er))
1728+
er => log.warn('cleanup', `Failed to remove orphaned entry ${name}`, er))
17001729
)
17011730
)
1731+
1732+
// Removing the last package under a scope leaves an empty @scope directory behind, so prune any scope directory that is now empty.
1733+
await promiseAllRejectLate(
1734+
[...scopes].map(async scope => {
1735+
const scopeDir = resolve(nmDir, scope)
1736+
try {
1737+
const remaining = await readdir(scopeDir)
1738+
if (!remaining.length) {
1739+
await rm(scopeDir, { recursive: true, force: true })
1740+
}
1741+
} catch {
1742+
/* istanbul ignore next -- readdir of a scope dir we just listed should not fail */
1743+
}
1744+
})
1745+
)
17021746
}
17031747

17041748
// last but not least, we save the ideal tree metadata to the package-lock

‎workspaces/arborist/test/arborist/reify.js‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4512,6 +4512,98 @@ t.test('install strategy linked', async (t) => {
45124512
t.ok(fs.lstatSync(scmd), 'surviving semver.cmd kept')
45134513
t.ok(fs.lstatSync(sps1), 'surviving semver.ps1 kept')
45144514
})
4515+
4516+
t.test('switching hoisted -> linked removes stale real top-level dirs', async t => {
4517+
// Regression test for https://github.com/npm/cli/issues/9615
4518+
const path = t.testdir({
4519+
'package.json': JSON.stringify({
4520+
name: 'sw', version: '1.0.0', dependencies: { minimatch: '3.0.4' },
4521+
}),
4522+
})
4523+
createRegistry(t, true)
4524+
4525+
// A hoisted install lays the transitive deps out as real top-level dirs.
4526+
await reify(path, { installStrategy: 'hoisted' })
4527+
const nm = resolve(path, 'node_modules')
4528+
for (const dep of ['balanced-match', 'brace-expansion', 'concat-map']) {
4529+
t.ok(fs.statSync(resolve(nm, dep)).isDirectory(), `${dep} is a real dir under hoisted`)
4530+
}
4531+
4532+
// Plant a stale scoped real package to cover the scoped removal and empty-scope pruning path.
4533+
const scopedPkg = resolve(nm, '@scope/stale')
4534+
fs.mkdirSync(scopedPkg, { recursive: true })
4535+
fs.writeFileSync(resolve(scopedPkg, 'package.json'),
4536+
JSON.stringify({ name: '@scope/stale', version: '1.0.0' }))
4537+
// A non-package real dir must be preserved.
4538+
fs.mkdirSync(resolve(nm, 'not-a-package'), { recursive: true })
4539+
4540+
// Switching to linked must remove those stale real dirs, leaving only the symlink + .store.
4541+
await reify(path, { installStrategy: 'linked' })
4542+
for (const dep of ['balanced-match', 'brace-expansion', 'concat-map']) {
4543+
t.notOk(fs.existsSync(resolve(nm, dep)), `${dep} stale real dir removed after switch to linked`)
4544+
}
4545+
t.notOk(fs.existsSync(scopedPkg), 'stale scoped real package removed')
4546+
t.notOk(fs.existsSync(resolve(nm, '@scope')), 'emptied scope dir pruned')
4547+
t.ok(fs.existsSync(resolve(nm, 'not-a-package')), 'non-package real dir preserved')
4548+
t.ok(fs.lstatSync(resolve(nm, 'minimatch')).isSymbolicLink(), 'minimatch is a store symlink')
4549+
t.ok(fs.statSync(resolve(nm, '.store')).isDirectory(), '.store created')
4550+
})
4551+
4552+
t.test('switching linked -> hoisted removes the stale .store dir', async t => {
4553+
// Regression test for https://github.com/npm/cli/issues/9615
4554+
const path = t.testdir({
4555+
'package.json': JSON.stringify({
4556+
name: 'sw', version: '1.0.0', dependencies: { minimatch: '3.0.4' },
4557+
}),
4558+
})
4559+
createRegistry(t, true)
4560+
4561+
await reify(path, { installStrategy: 'linked' })
4562+
const nm = resolve(path, 'node_modules')
4563+
t.ok(fs.statSync(resolve(nm, '.store')).isDirectory(), '.store created under linked')
4564+
4565+
// A hoisted install must not leave the linked store behind.
4566+
await reify(path, { installStrategy: 'hoisted' })
4567+
t.notOk(fs.existsSync(resolve(nm, '.store')), '.store removed after switch to hoisted')
4568+
t.ok(fs.statSync(resolve(nm, 'balanced-match')).isDirectory(), 'transitive dep hoisted to a real dir')
4569+
})
4570+
4571+
t.test('a partial hoisted install does not wipe a still-referenced linked .store', async t => {
4572+
// Regression test for https://github.com/npm/cli/issues/9615
4573+
// A workspace-filtered or --workspaces=false hoisted install must not remove the root .store, since out-of-scope workspaces still link into it.
4574+
const path = t.testdir({
4575+
'package.json': JSON.stringify({
4576+
name: 'root', version: '1.0.0', workspaces: ['packages/*'],
4577+
}),
4578+
packages: {
4579+
// a is the out-of-scope workspace that keeps a live link into the store.
4580+
a: { 'package.json': JSON.stringify({ name: 'a', version: '1.0.0', dependencies: { minimatch: '3.0.4' } }) },
4581+
b: { 'package.json': JSON.stringify({ name: 'b', version: '1.0.0' }) },
4582+
},
4583+
})
4584+
createRegistry(t, true)
4585+
const nm = resolve(path, 'node_modules')
4586+
const aLink = resolve(path, 'packages/a/node_modules/minimatch')
4587+
// a's dep resolves through the root .store, so deleting the store would break it.
4588+
const stillLinked = msg => t.ok(
4589+
fs.lstatSync(aLink).isSymbolicLink() && fs.existsSync(fs.realpathSync(aLink)), msg)
4590+
4591+
await reify(path, { installStrategy: 'linked' })
4592+
t.ok(fs.statSync(resolve(nm, '.store')).isDirectory(), '.store created under linked')
4593+
t.match(fs.realpathSync(aLink), /node_modules[\\/]\.store[\\/]/, 'workspace a links into the store')
4594+
4595+
// Filter to workspace b: a is out of scope and must keep its live store link.
4596+
await reify(path, { installStrategy: 'hoisted', workspaces: ['b'] })
4597+
t.ok(fs.existsSync(resolve(nm, '.store')), '.store kept during a workspace-filtered install')
4598+
stillLinked('workspace a still resolves through the store after the filtered install')
4599+
4600+
await reify(path, { installStrategy: 'hoisted', workspacesEnabled: false })
4601+
t.ok(fs.existsSync(resolve(nm, '.store')), '.store kept during a --workspaces=false install')
4602+
stillLinked('workspace a still resolves through the store after the --workspaces=false install')
4603+
4604+
await reify(path, { installStrategy: 'hoisted' })
4605+
t.notOk(fs.existsSync(resolve(nm, '.store')), '.store removed by a full hoisted install')
4606+
})
45154607
})
45164608

45174609
t.test('linked strategy --workspaces=false and --include-workspace-root do not crash', async t => {

0 commit comments

Comments
 (0)