Repository navigation
refactor(pnpm): render output, answer bit why, and own the lockfile through @pnpm/napi - #10653
Conversation
…npm/napi Installs run on pnpm's Rust engine, but four pnpm v11 JavaScript packages stayed behind it: `@pnpm/logger` and `@pnpm/cli.default-reporter` re-rendered the engine's event stream, and `@pnpm/deps.inspection.tree-builder` + `@pnpm/deps.inspection.list` answered `bit why`. Both jobs depend on a v11 package staying compatible with a v12 engine's events and lockfile — a coupling Bit ends up maintaining. `@pnpm/napi` now does both itself (pnpm/pnpm#TBD), so all four are dropped. Output: `install` / `rebuild` get `options.reporter`, and the engine renders with the reporter `pnpm install` itself uses. Every reporting option Bit set maps across, including the two it relied on pnpm extension points for — the approve-builds instruction text, and hiding linked `@teambit/*` core aspects from the packages-diff summary (`filterPkgsDiff` is a callback the engine cannot call synchronously, so it is expressed as a name pattern instead). Rendered chunks come back through an `onOutput` callback rather than being written by the engine. That is required, not stylistic: Bit monkey-patches `process.stdout.write` to mirror output to a tty, and the CLI server swaps in a stream that forwards to connected editors, both of which a write from Rust would bypass. `ReportOptions.process` — a whole spread `process` object that existed only to carry that stream — becomes `outputStream`. `bit why`: `getDependents` reads the lockfile and returns the reverse trees, `renderDependents` prints them. The `nameFormatter` callback that rendered component ids instead of package names has no equivalent across the addon boundary, so Bit asks the engine for the `componentId` manifest field and writes `displayName` onto the trees before rendering them — same output. Also removes `log-converter.ts`, the last `@pnpm/logger` reference, which nothing imported. Needs an `@pnpm/napi` release containing the engine-side change; the pin is set to the next prerelease.
PR Summary by Qodorefactor(pnpm): use @pnpm/napi for install output and
AI Description
Diagram
High-Level Assessment
Files changed (3)
|
Code Review by Qodo
1. Eager native engine load
|
| const rebuildReportOptions: ReportOptions = { appendOnly: true, hideLifecycleOutput: true }; | ||
| await nodeApi.rebuild( | ||
| { | ||
| ...installOptions, |
There was a problem hiding this comment.
1. Rebuild bypasses output stream 🐞 Bug ≡ Correctness
The rebuild() path constructs fresh rebuildReportOptions without carrying over reportOptions.outputStream, so reporterOutputStream() falls back to process.stdout and bypasses Bit’s CLI-server forwarding stream. In BIT_CLI_SERVER_NO_TTY mode this means rebuild output will not be sent to connected clients/editors (and may bypass stdout monkey-patching expectations).
Agent Prompt
### Issue description
`rebuild()` creates a new `rebuildReportOptions` object that omits `outputStream`. As a result, `reporterOutputStream()` defaults to `process.stdout` and rebuild output can bypass the CLI server’s forwarding stream.
### Issue Context
`install()` is called with `reportOptions.outputStream` set to a `ServerSendOutStream` when `BIT_CLI_SERVER_NO_TTY` is enabled. The rebuild path should reuse that same output routing.
### Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[472-490]
- scopes/dependencies/pnpm/lynx.ts[573-618]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[241-253]
### Concrete fix
In `rebuild`, build report options by extending the existing ones, e.g.:
- `const rebuildReportOptions: ReportOptions = { ...options.reportOptions, appendOnly: true, hideLifecycleOutput: true };`
- Use `toReporterOptions(rebuildReportOptions)` and `reporterOutput(rebuildReportOptions)` so both reporter config and onOutput target the same stream.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
Three pnpm v11 JavaScript packages were still in the install path, all of them about a file the engine already owns: `@pnpm/lockfile.fs` read and wrote `pnpm-lock.yaml`, `@pnpm/lockfile.filtering` narrowed one to a component's importer, and `@pnpm/installing.modules-yaml` read `.modules.yaml`. `@pnpm/napi` now exposes all three (pnpm/pnpm#14082), so they are dropped. The lockfile now crosses the boundary in the file's own shape rather than the in-memory one, which removes a conversion rather than adding one: `calcDependenciesGraph` used to read the object shape, mutate it, filter, and then convert to the file shape for the graph converter — which consumes the file shape. It now reads, mutates, and filters that shape throughout. The mutation reads `ref.version` where it read a bare string ref, and drops `specifiers`, which the file shape inlines next to each version. The `bit:` block Bit records beside pnpm's keys survives a read/edit/write through the engine: pnpm no longer drops top-level keys it does not define. Bit still re-asserts the block after an install — an install builds a fresh lockfile, and Bit is writing that block's new `depsRequiringBuild` anyway. `getLockfileImporterId` is inlined; it is one `path.relative` call, and it was the only reason the ESM shim loaded `@pnpm/lockfile.fs`. The shim now loads `@pnpm/deps.path` alone, which stays a JavaScript dependency on purpose: it is pure dep-path string parsing whose helpers run once per graph edge, and that is not a shape to put behind an FFI call. Every other remaining `@pnpm/*` dependency is type-only or unrelated to the engine. Needs the same `@pnpm/napi` release as the reporter and dependents change.
bit why through @pnpm/napibit why, and own the lockfile through @pnpm/napi
| const lockfile = await nodeApi.readLockfile({ dir: rootDir, kind: 'current' }); | ||
| const snapshots = (lockfile?.snapshots ?? {}) as Record<string, unknown>; | ||
| const dirsShouldBePresent = Object.keys(snapshots).map((depPath) => depPathToDirName(depPath)); |
There was a problem hiding this comment.
1. Prune may delete everything 🐞 Bug ≡ Correctness
pnpmPruneModules() derives the set of required virtual-store directories only from lockfile.snapshots; if snapshots is absent/empty (or the lockfile can’t be read), dirsShouldBePresent becomes empty and the function may delete all package directories under node_modules/.pnpm. This can break the workspace by removing installed packages even though the lockfile still lists them under packages (a shape other parts of the codebase still assume for lock.yaml).
Agent Prompt
### Issue description
`pnpmPruneModules()` computes `dirsShouldBePresent` from `lockfile.snapshots` only. If the current lockfile read via `nodeApi.readLockfile({ kind: 'current' })` returns `null` or returns an object without `snapshots`, the computed set becomes empty and the function can delete all virtual-store package directories.
### Issue Context
Other code paths that parse `node_modules/.pnpm/lock.yaml` still expect package dep paths under `lockfile.packages`.
### Fix Focus Areas
- scopes/dependencies/pnpm/pnpm-prune-modules.ts[16-18]
### Suggested change
- Treat the dep-path source as `lockfile.snapshots ?? lockfile.packages` (or the union of both), and if neither exists (or the lockfile is null), return early (do not prune).
- Consider adding a small safety check: if the derived dep-path key set is empty but `pkgDirs` is non-empty, skip pruning unless you can prove the lockfile has no entries.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
|
Code review by qodo was updated up to the latest commit 4d81bef |
Three findings from review of the engine rewiring:
`rebuild` built its reporting options from scratch, so the CLI server's
forwarding stream — and the width and throttle the caller chose — reached
the install's output but not the rebuild's. It now extends the install's
options rather than replacing them.
The reporter width came from `columns - 2` unconditionally, which is zero or
negative on a one- or two-column terminal. Floored at one column (the engine
floors it too, so neither side can hand the renderer a width it cannot
honor).
`pnpmPruneModules` treated an unreadable current lockfile as "nothing
belongs in the virtual store" and would delete every package directory,
leaving the workspace needing a reinstall. A missing lockfile now stops the
prune. This behavior predates the rewiring — the old code read
`lockfile?.packages ?? {}` — but the line was being rewritten anyway and the
hazard is real.
Note for review: the dep paths come from `snapshots`, not `packages`. Those
are the same map in the in-memory lockfile shape this code used to read, but
in the file shape it now reads, `snapshots` is keyed by the peer-suffixed
dep path — which is what the virtual store's directory names are derived
from — while `packages` is keyed without the suffix and would not match.
|
All three Qodo findings fixed in 8b77421. Rebuild bypassed the output stream — real, and the fix is worth more than the report suggests. Width can be invalid — real. Floored at one column here, and also floored in the engine (pnpm/pnpm#14082), so neither side can hand the renderer a width it cannot honor. Prune may delete everything — the hazard is real and now guarded: a missing current lockfile stops the prune instead of reading as "nothing belongs here". Worth noting it predates this PR — the old code was I did not take the suggested Verified end to end: install and rebuild both rendering to a host stream that reports a 1-column terminal, and a prune against a deleted |
| import path from 'path'; | ||
| import { difference } from 'lodash'; | ||
| import type * as LockfileFs from '@pnpm/lockfile.fs'; | ||
| import * as nodeApi from '@pnpm/napi'; |
There was a problem hiding this comment.
1. Eager native engine load 🐞 Bug ➹ Performance
pnpm-prune-modules.ts now imports @pnpm/napi at module top-level, which can map/load the native engine as soon as pnpm.package-manager.ts is imported (even if pruning is never invoked). This contradicts the file’s own lazy-load intent and can increase startup cost or cause native-load failures in code paths that previously didn't require the engine binary.
Agent Prompt
### Issue description
`scopes/dependencies/pnpm/pnpm-prune-modules.ts` imports `@pnpm/napi` at top-level, which eagerly loads the native engine when the module is evaluated. Since `PnpmPackageManager` imports `pnpmPruneModules` at module load time, this defeats the lazy-loading strategy intended to avoid mapping the native binary into every `bit` process.
### Issue Context
`PnpmPackageManager` explicitly documents a convention of requiring `@pnpm/napi` lazily to avoid startup overhead. `pnpm-prune-modules.ts` should follow the same pattern.
### Fix Focus Areas
- scopes/dependencies/pnpm/pnpm-prune-modules.ts[2-26]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[25-35]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[62-69]
### Suggested change
1. Remove the top-level `import * as nodeApi from '@pnpm/napi'`.
2. Add a small local `loadNodeApi()` helper (like the one in `pnpm.package-manager.ts`) and call it inside `pnpmPruneModules()` right before `readLockfile()`.
Example sketch:
```ts
import type * as NodeApi from '@pnpm/napi';
function loadNodeApi(): typeof NodeApi {
// eslint-disable-next-line global-require, import/no-dynamic-require
return require('@pnpm/napi') as typeof NodeApi;
}
export async function pnpmPruneModules(rootDir: string) {
const nodeApi = loadNodeApi();
const lockfile = await nodeApi.readLockfile({ dir: rootDir, kind: 'current' });
...
}
```
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
|
Code review by qodo was updated up to the latest commit 8b77421 |
…leased rc.9 12.0.0-rc.9 is published, so the pin this branch already carries resolves for real. Installing it drops @pnpm/installing.modules-yaml from the root node_modules along with the rest of the JS packages this branch replaced (cli.default-reporter, deps.inspection.*, lockfile.fs, lockfile.filtering, @pnpm/logger) - and three e2e suites still imported that package to read .modules.yaml, so they no longer resolved it. rc.9 exposes readModulesManifest, so the read goes through the engine like the rest of the pnpm integration, and the helper the three suites each carried their own copy of now lives in one place. The helper reaches the addon through a static namespace import. The addon assigns module.exports from a call, so cjs-module-lexer detects no named exports and node's esm loader - which is what babel-register's untransformed `import()` reaches - hands back a namespace holding only `default`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Code review by qodo was updated up to the latest commit 6a7f566 |
…t fix rc.8's hoister collapsed every peer variant of a package version onto one copy, which for injected directory deps rewired one root component's copy onto another's — the hoisted root-components e2e failed with `expected '1.0.0' to match /^2\./`. rc.10 ships the fix (pnpm/pnpm#14126): directory `file:` snapshots keep their peer suffix, so each root component's injected copies stay its own. Verified against the published binary: the hoisted root-components suite passes (12 passing, the two previously failing react-17 tests included). Co-Authored-By: Claude Fable 5 <[email protected]>
|
Code review by qodo was updated up to the latest commit 8bec2ec |
| const componentId = node.manifest?.componentId as { scope?: string; name?: string } | undefined; | ||
| if (componentId?.scope && componentId.name) { | ||
| node.displayName = `${componentId.scope}/${componentId.name}`; | ||
| } |
There was a problem hiding this comment.
1. Component ids never render 🐞 Bug ≡ Correctness
applyComponentIdNames() treats the manifest's componentId as an object, but Bit writes that field as a serialized string, so scope and name are always undefined and bit why continues rendering package names instead of component IDs.
Agent Prompt
## Issue description
`applyComponentIdNames()` assumes `manifest.componentId` is an object with `scope` and `name`, while Bit package manifests store it as a serialized component-ID string. Parse the string and set `displayName` to the equivalent scope/name form expected by `bit why`.
## Issue Context
Preserve the prior intended output without the component version, and safely leave nodes without a valid component ID unchanged.
## Fix Focus Areas
- scopes/dependencies/pnpm/pnpm.package-manager.ts[570-576]
- scopes/component/sources/package-json-file.ts[149-154]
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
|
Code review by qodo was updated up to the latest commit 4d9d338 |
Installs already run on pnpm's Rust engine, but seven pnpm v11 JavaScript packages stayed behind it:
@pnpm/logger+@pnpm/cli.default-reporter@pnpm/deps.inspection.tree-builder+@pnpm/deps.inspection.listbit why@pnpm/lockfile.fspnpm-lock.yaml@pnpm/lockfile.filtering@pnpm/installing.modules-yaml.modules.yamlEvery one of them has to keep agreeing with a v12 engine about events and file formats it already owns — a coupling Bit ends up maintaining.
@pnpm/napinow does all of it itself (pnpm/pnpm#14082), so all seven are dropped.Output
install/rebuildgetoptions.reporter, and the engine renders with the reporterpnpm installitself uses. Every reporting option Bit set maps across one-for-one, including the two that needed pnpm extension points:ignoredBuildsInstructionText@teambit/*core aspects from the packages-diff summary →hideLinkedPkgsDiff: ['@teambit/*'].filterPkgsDiffwas a callback, and the engine's reporter is synchronous, so it can't be called across the addon boundary; as a name pattern it hides the same entries (linked ones only — an installed@teambit/*still shows).Rendered chunks come back through an
onOutputcallback rather than being written by the engine. That's required, not stylistic:cli-raw.route.tsmonkey-patchesprocess.stdout.writeto mirror output to a tty, and the CLI server swaps in aServerSendOutStreamthat forwards to connected editors — a write from Rust would bypass both.ReportOptions.process(a whole spreadprocessobject that existed only to carry that stream) becomesoutputStream.bit whygetDependentsreads the lockfile and returns the reverse trees;renderDependentsprints them. ThenameFormattercallback that rendered component ids instead of package names has no equivalent across the addon boundary, so Bit asks the engine for each node'scomponentIdmanifest field (manifestFields: ['componentId']) and writesdisplayNameonto the trees before rendering — same output..bit_rootsimporters are excluded viaexcludeProjectPatternsinstead of a JS-side lockfile read.This also drops the
readWantedLockfile+ per-importerpackage.jsonreadsfindUsageswas doing in JS.log-converter.tsgoes too — it was the last@pnpm/loggerreference and nothing imported it.Lockfile
readLockfile/writeLockfile/filterLockfileByImporters/readModulesManifestreplace the four JS entry points. The lockfile now crosses the boundary in the file's own shape rather than the in-memory one, which removes a conversion rather than adding one:calcDependenciesGraphused to read the object shape, mutate it, filter, and thenconvertToLockfileFilefor the graph converter — which consumes the file shape. It now reads, mutates, and filters that shape throughout. The mutation readsref.versionwhere it read a bare string ref, and dropsspecifiers, which the file shape inlines next to each version.The
bit:block survives a read → edit → write through the engine: pnpm no longer drops top-level keys it does not define. Bit still re-asserts it after an install — an install builds a fresh lockfile, and Bit is writing that block's newdepsRequiringBuildanyway.getLockfileImporterIdis inlined (onepath.relativecall), which was the only reason the ESM shim loaded@pnpm/lockfile.fs. The shim now loads@pnpm/deps.pathalone.What stays JavaScript, and why
@pnpm/deps.path— pure dep-path string parsing whose helpers run once per graph edge, millions of times on a large workspace. That is exactly the shape that should not go behind an FFI call.@pnpm/lockfile.types,@pnpm/types,@pnpm/error— type-only, no runtime.@pnpm/semver-diff,@pnpm/colorize-semver-diff,@pnpm/network.ca-file,@pnpm/node-fetch,@pnpm/network.fetch,@pnpm/plugin-trusted-deps,@pnpm/config.parse-overrides,@pnpm/registry-mock— small and unrelated to the engine (config.parse-overridesis used by the yarn package manager;registry-mockis e2e infra).Verified
npm run lint(tsc --noEmit + oxlint --deny-warnings) cleanlynx.installdriven throughbabel-registeragainst a real[email protected]install: the engine rendered the progress line, thePackages: +2summary, the dependencies diff, and the footer, and every chunk arrived on a host-supplied stream (aWritablestanding in forServerSendOutStream) — nothing was written to the process's own stdoutPnpmPackageManager#findUsages('is-number')against that workspace printed the expected tree, withis-oddrendered asacme.numbers/is-oddafter acomponentIdwas added to its manifest — i.e. the display-name path that replacednameFormatterbit:block written bylynx.install, read back, edited, written, and re-read with importers/packages/snapshots intact; the current lockfile read andpnpmPruneModuleskeeping the right virtual-store dirs;.modules.yamlread through the engine;filterLockfileByImportersreturning the component's closurecalcDependenciesGraphon a fixture where a component injects one workspace sibling viafile:and links another: the injected sibling survives in the component's graph, the linked one is stripped, and an unrelated package is filtered out — the file-shape rewrite of that mutationlockfile-deps-graph-converter.spec.ts(22 tests) passesBlocked on
pnpm/pnpm#14082 landing and being released. The
@pnpm/napipin here is set to12.0.0-rc.9(the next prerelease); bump it if the release lands under a different number. Everything above was verified against a local build of that branch.