Loading workspace insights... Statistics interval
7 days30 daysLatest CI Pipeline Executions
b46de60c fix(js): guard against undefined closest node in rehoistNodes (#34347)
## Current Behavior
When running `@nx/js:prune-lockfile` on a monorepo with transitive
dependencies that have multiple versions where neither version is
reachable from a direct dependency in package.json, the executor throws:
```
NX An error occurred while creating pruned lockfile
Original error: Cannot read properties of undefined (reading 'name')
TypeError: Cannot read properties of undefined (reading 'name')
at switchNodeToHoisted (node_modules/nx/src/plugins/js/lock-file/project-graph-pruning.js:165:31)
```
## Expected Behavior
The lockfile pruning should complete without crashing, even when some
transitive dependencies cannot be traced back to a direct dependency.
## Root Cause
In `rehoistNodes()`, when there are multiple nested nodes for a package,
the code finds the "closest" node by computing `pathLengthToIncoming()`
for each. However, when none of the nested nodes have a path to any
direct dependency in package.json, `pathLengthToIncoming()` returns
`undefined` for all of them. Since `undefined < Infinity` is `false` in
JavaScript, `closest` remains `undefined`, and then
`switchNodeToHoisted(undefined, ...)` crashes.
## Fix
Add a guard to only call `switchNodeToHoisted()` when a closest node was
actually found:
```typescript
if (closest) {
switchNodeToHoisted(closest, builder, invBuilder);
}
```
This allows the pruning to continue - the nested nodes simply won't be
rehoisted if no closest node can be determined.
## Related Issue
Fixes #34322
## Test Added
Added a unit test that verifies `rehoistNodes()` doesn't crash when
nested nodes have no path to package.json dependencies.