diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots.toml index b3edd43e93..745e23f09d 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots.toml @@ -3,7 +3,7 @@ name = "command_add_npm11_with_workspace" vp = "global" skip-platforms = ["windows"] steps = [ - { argv = ["vp", "add", "testnpm2", "-D", "-w", "--", "--no-audit"], comment = "should add package to workspace root" }, + { argv = ["vp", "add", "testnpm2", "-D", "-w", "--", "--no-audit"], cwd = "packages/app", comment = "add to the root from a workspace member" }, { argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"], continue-on-failure = true }, { argv = ["vp", "add", "@vite-plus-test/utils", "--workspace", "--", "--no-audit"], comment = "reject unsupported --workspace without adding packages to the root", continue-on-failure = true }, { argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"], continue-on-failure = true }, @@ -17,4 +17,7 @@ steps = [ { argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"], continue-on-failure = true }, { argv = ["vp", "install", "test-vite-plus-package@1.0.0", "--filter", "*", "--workspace-root", "--", "--no-audit"], comment = "should install packages alias for add command" }, { argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"], continue-on-failure = true }, + { argv = ["vp", "remove", "-w", "testnpm2", "--", "--no-audit"], cwd = "packages/app", comment = "remove the root devDependency and preserve the member dependencies" }, + { argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"] }, + { argv = ["node", "-e", "const { packages } = require('./package-lock.json'); console.log(packages[''].devDependencies?.testnpm2, packages['packages/app'].dependencies.testnpm2)"], comment = "the lockfile records the same removal at the root and keeps the app dependency" }, ] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots/command_add_npm11_with_workspace.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots/command_add_npm11_with_workspace.md index 4f9e5a0234..50b7440aed 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots/command_add_npm11_with_workspace.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm11_with_workspace/snapshots/command_add_npm11_with_workspace.md @@ -1,8 +1,8 @@ # command_add_npm11_with_workspace -## `vp add testnpm2 -D -w -- --no-audit` +## `cd packages/app && vp add testnpm2 -D -w -- --no-audit` -should add package to workspace root +add to the root from a workspace member ``` @@ -274,3 +274,55 @@ added 1 package in } } ``` + +## `cd packages/app && vp remove -w testnpm2 -- --no-audit` + +remove the root devDependency and preserve the member dependencies + +``` + +up to date in +``` + +## `vpt print-file package.json packages/app/package.json packages/utils/package.json` + +``` +{ + "name": "command-add-npm11-with-workspace", + "version": "1.0.0", + "workspaces": [ + "packages/*" + ], + "packageManager": "npm@11.6.2", + "dependencies": { + "test-vite-plus-install": "1.0.0", + "test-vite-plus-package": "^1.0.0" + } +} +{ + "name": "app", + "dependencies": { + "test-vite-plus-install": "1.0.0", + "test-vite-plus-package": "^1.0.0", + "testnpm2": "1.0.1" + } +} +{ + "name": "@vite-plus-test/utils", + "version": "1.0.0", + "private": true, + "dependencies": { + "test-vite-plus-install": "1.0.0", + "test-vite-plus-package": "^1.0.0", + "testnpm2": "1.0.1" + } +} +``` + +## `node -e 'const { packages } = require('\''./package-lock.json'\''); console.log(packages['\'''\''].devDependencies?.testnpm2, packages['\''packages/app'\''].dependencies.testnpm2)'` + +the lockfile records the same removal at the root and keeps the app dependency + +``` +undefined 1.0.1 +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/check.cjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/check.cjs new file mode 100644 index 0000000000..57128d025d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/check.cjs @@ -0,0 +1,13 @@ +const assert = require('node:assert/strict'); +const { realpathSync } = require('node:fs'); +const path = require('node:path'); + +const member = realpathSync('packages/app'); +assert.equal(realpathSync(require.resolve('fixture-member/package.json')), path.join(member, 'package.json')); +assert.equal(require('./package.json').dependencies['lifecycle-probe'], 'file:packages/app/lifecycle-probe-1.0.0.tgz'); +assert.equal(require('./packages/app/package.json').dependencies?.['lifecycle-probe'], undefined); + +const { caller, globalPrefix } = require('lifecycle-probe/install-context.json'); +assert.equal(realpathSync(caller), member); +assert.equal(realpathSync(globalPrefix), path.join(member, 'test-global')); +console.log('Root dependencies resolve and the install script retains its caller and global prefix.'); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/capture.cjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/capture.cjs new file mode 100644 index 0000000000..6fbc797bd7 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/capture.cjs @@ -0,0 +1,7 @@ +const { execFileSync } = require('node:child_process'); +const { writeFileSync } = require('node:fs'); + +const globalPrefix = execFileSync(process.execPath, [process.env.npm_execpath, 'prefix', '-g'], { + encoding: 'utf8', +}).trim(); +writeFileSync('install-context.json', JSON.stringify({ caller: process.env.INIT_CWD, globalPrefix })); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/package.json new file mode 100644 index 0000000000..0bd5870547 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/local-package/package.json @@ -0,0 +1,7 @@ +{ + "name": "lifecycle-probe", + "version": "1.0.0", + "scripts": { + "install": "node capture.cjs" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/package.json new file mode 100644 index 0000000000..2eb17812ad --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/package.json @@ -0,0 +1,10 @@ +{ + "name": "workspace-root", + "private": true, + "version": "1.0.0", + "packageManager": "npm@10.9.2", + "workspaces": ["packages/*"], + "dependencies": { + "fixture-member": "1.0.0" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/packages/app/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/packages/app/package.json new file mode 100644 index 0000000000..2ad20c0797 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/packages/app/package.json @@ -0,0 +1,4 @@ +{ + "name": "fixture-member", + "version": "1.0.0" +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots.toml new file mode 100644 index 0000000000..8e04bfe31a --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots.toml @@ -0,0 +1,9 @@ +[[case]] +name = "command_add_npm_workspace_lifecycle" +vp = "global" +steps = [ + { argv = ["npm", "pack", "./local-package", "--pack-destination", "packages/app", "--silent"], snapshot = false }, + { argv = ["vpt", "mkdir", "packages/app/test-global"], snapshot = false }, + { argv = ["vp", "add", "-w", "./lifecycle-probe-1.0.0.tgz", "--offline", "--", "--no-audit", "--no-fund"], cwd = "packages/app", envs = [["NPM_CONFIG_PREFIX", "${workspace}/test-global"]], snapshot = false }, + ["node", "check.cjs"], +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots/command_add_npm_workspace_lifecycle.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots/command_add_npm_workspace_lifecycle.md new file mode 100644 index 0000000000..d07f2bde6d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_add_npm_workspace_lifecycle/snapshots/command_add_npm_workspace_lifecycle.md @@ -0,0 +1,16 @@ +# command_add_npm_workspace_lifecycle + +## `npm pack ./local-package --pack-destination packages/app --silent` + + +## `vpt mkdir packages/app/test-global` + + +## `cd packages/app && NPM_CONFIG_PREFIX=${workspace}/test-global vp add -w ./lifecycle-probe-1.0.0.tgz --offline -- --no-audit --no-fund` + + +## `node check.cjs` + +``` +Root dependencies resolve and the install script retains its caller and global prefix. +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/check-tarball.cjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/check-tarball.cjs new file mode 100644 index 0000000000..2249949b19 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/check-tarball.cjs @@ -0,0 +1,17 @@ +const assert = require('node:assert/strict'); +const { spawnSync } = require('node:child_process'); +const { existsSync, readFileSync } = require('node:fs'); + +const files = ['package.json', 'packages/app/package.json', 'packages/docs/package.json']; +const manifests = () => files.map((file) => readFileSync(file, 'utf8')); +const before = manifests(); +const result = spawnSync('vp', ['add', '-w', '--filter', 'docs', './docs-1.0.0.tgz', '--offline'], { + cwd: 'packages/app', + encoding: 'utf8', +}); +assert.ifError(result.error); +assert.notEqual(result.status, 0); +assert.match(result.stdout + result.stderr, /requires npm 8\.19\.0 or later/); +assert.deepEqual(manifests(), before); +assert.equal(existsSync('package-lock.json'), false); +console.log('npm 8.1 rejected the combined tarball edit before writing manifests or a lockfile.'); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/package.json new file mode 100644 index 0000000000..6b7e54e44f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/package.json @@ -0,0 +1,12 @@ +{ + "name": "root", + "private": true, + "packageManager": "npm@8.1.0", + "workspaces": [ + "packages/*" + ], + "devDependencies": { + "testnpm2": "1.0.1", + "test-vite-plus-install": "1.0.0" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/package.json new file mode 100644 index 0000000000..aa4ddee795 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/package.json @@ -0,0 +1,12 @@ +{ + "name": "app", + "version": "1.0.0", + "packageManager": "npm@8.1.0", + "workspaces": [ + "plugins/*" + ], + "dependencies": { + "testnpm2": "1.0.1", + "test-vite-plus-install": "1.0.0" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/plugins/docs/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/plugins/docs/package.json new file mode 100644 index 0000000000..49e5bba220 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/app/plugins/docs/package.json @@ -0,0 +1,7 @@ +{ + "name": "docs", + "version": "1.0.0", + "dependencies": { + "test-vite-plus-install": "1.0.0" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/docs/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/docs/package.json new file mode 100644 index 0000000000..0dbbff9ce8 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/packages/docs/package.json @@ -0,0 +1,8 @@ +{ + "name": "docs", + "version": "1.0.0", + "dependencies": { + "testnpm2": "1.0.1", + "test-vite-plus-install": "1.0.0" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml new file mode 100644 index 0000000000..8d0fd4c962 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots.toml @@ -0,0 +1,13 @@ +[[case]] +name = "command_remove_npm8_nested_workspace" +vp = "global" +steps = [ + { argv = ["npm", "pack", "./packages/docs", "--pack-destination", "packages/app", "--silent"], snapshot = false }, + ["node", "check-tarball.cjs"], + { argv = ["vp", "remove", "-w", "testnpm2", "--", "--no-audit"], cwd = "packages/app", comment = "remove only the outer root declaration when the current member owns a workspace" }, + { argv = ["vp", "remove", "-w", "--filter", "docs", "test-vite-plus-install", "--", "--no-audit"], cwd = "packages/app", comment = "select the outer docs package when the inner workspace also has a member named docs" }, + { argv = ["vp", "remove", "-w", "testnpm2", "--", "--workspace=../docs", "--no-audit"], cwd = "packages/app", comment = "resolve an attached workspace path from the calling member" }, + ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/docs/package.json", "packages/app/plugins/docs/package.json"], + ["node", "-p", "require('./package-lock.json').packages['packages/app'].dependencies"], + ["vpt", "stat-file", "packages/app/package-lock.json", "--assert", "missing"], +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md new file mode 100644 index 0000000000..e0320be4d1 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_remove_npm8_nested_workspace/snapshots/command_remove_npm8_nested_workspace.md @@ -0,0 +1,85 @@ +# command_remove_npm8_nested_workspace + +## `npm pack ./packages/docs --pack-destination packages/app --silent` + + +## `node check-tarball.cjs` + +``` +npm 8.1 rejected the combined tarball edit before writing manifests or a lockfile. +``` + +## `cd packages/app && vp remove -w testnpm2 -- --no-audit` + +remove only the outer root declaration when the current member owns a workspace + +``` + +added 4 packages in +``` + +## `cd packages/app && vp remove -w --filter docs test-vite-plus-install -- --no-audit` + +select the outer docs package when the inner workspace also has a member named docs + +``` + +up to date in +``` + +## `cd packages/app && vp remove -w testnpm2 -- --workspace=../docs --no-audit` + +resolve an attached workspace path from the calling member + +``` + +up to date in +``` + +## `vpt print-file package.json packages/app/package.json packages/docs/package.json packages/app/plugins/docs/package.json` + +``` +{ + "name": "root", + "private": true, + "packageManager": "npm@8.1.0", + "workspaces": [ + "packages/*" + ] +} +{ + "name": "app", + "version": "1.0.0", + "packageManager": "npm@8.1.0", + "workspaces": [ + "plugins/*" + ], + "dependencies": { + "testnpm2": "1.0.1", + "test-vite-plus-install": "1.0.0" + } +} +{ + "name": "docs", + "version": "1.0.0" +} +{ + "name": "docs", + "version": "1.0.0", + "dependencies": { + "test-vite-plus-install": "1.0.0" + } +} +``` + +## `node -p require('./package-lock.json').packages['packages/app'].dependencies` + +``` +{ 'test-vite-plus-install': '1.0.0', testnpm2: '1.0.1' } +``` + +## `vpt stat-file packages/app/package-lock.json --assert missing` + +``` +packages/app/package-lock.json: missing +``` diff --git a/crates/vp_pm_cli/src/resolution/command.rs b/crates/vp_pm_cli/src/resolution/command.rs index c81e8188f6..1ba21e5095 100644 --- a/crates/vp_pm_cli/src/resolution/command.rs +++ b/crates/vp_pm_cli/src/resolution/command.rs @@ -13,6 +13,7 @@ pub(crate) struct ResolvedCommand { pub(crate) args: Vec, pub(crate) env: BTreeMap, pub(crate) pre_run: Vec, + pub(crate) npm_workspace_edit: bool, } impl ResolvedCommand { @@ -23,7 +24,7 @@ impl ResolvedCommand { // Include npm/npx fallbacks: Vite+ manages their versions too. env.insert("npm_config_update_notifier".to_string(), "false".to_string()); } - Self { program, args: Vec::new(), env, pre_run: Vec::new() } + Self { program, args: Vec::new(), env, pre_run: Vec::new(), npm_workspace_edit: false } } } @@ -94,6 +95,11 @@ impl CommandBuilder { self } + pub(crate) fn npm_workspace_edit(&mut self, edit: bool) -> &mut Self { + self.command.npm_workspace_edit = edit; + self + } + pub(crate) fn create_dir(&mut self, path: impl ToString) -> &mut Self { self.command.pre_run.push(PreRunAction::CreateDir { path: path.to_string() }); self diff --git a/crates/vp_pm_cli/src/resolution/commands/add.rs b/crates/vp_pm_cli/src/resolution/commands/add.rs index 1973513a27..8058a97b88 100644 --- a/crates/vp_pm_cli/src/resolution/commands/add.rs +++ b/crates/vp_pm_cli/src/resolution/commands/add.rs @@ -227,7 +227,8 @@ impl Npm { return cmd.into(); } - cmd.arg("install") + cmd.npm_workspace_edit(args.workspace_root && !args.packages.is_empty()) + .arg("install") .repeated("--workspace", args.filter.iter()) .arg_if("--include-workspace-root", args.workspace_root); match args.save_dependency.target() { diff --git a/crates/vp_pm_cli/src/resolution/commands/remove.rs b/crates/vp_pm_cli/src/resolution/commands/remove.rs index e2b3a6516e..84d5860ca3 100644 --- a/crates/vp_pm_cli/src/resolution/commands/remove.rs +++ b/crates/vp_pm_cli/src/resolution/commands/remove.rs @@ -79,7 +79,9 @@ impl Npm { return cmd.into(); } - cmd.arg("uninstall").repeated("--workspace", args.filter.iter()); + cmd.npm_workspace_edit(args.workspace_root && !args.recursive) + .arg("uninstall") + .repeated("--workspace", args.filter.iter()); if args.workspace_root || args.recursive { cmd.arg("--include-workspace-root"); } diff --git a/crates/vp_pm_cli/src/resolution/mod.rs b/crates/vp_pm_cli/src/resolution/mod.rs index 52302e0da0..168ef9c1d4 100644 --- a/crates/vp_pm_cli/src/resolution/mod.rs +++ b/crates/vp_pm_cli/src/resolution/mod.rs @@ -31,6 +31,7 @@ mod command; mod commands; mod diagnostics; mod dialect; +mod npm_workspace; mod resolve; mod runner; mod support; diff --git a/crates/vp_pm_cli/src/resolution/npm_workspace.cjs b/crates/vp_pm_cli/src/resolution/npm_workspace.cjs new file mode 100644 index 0000000000..d3fb5bcbee --- /dev/null +++ b/crates/vp_pm_cli/src/resolution/npm_workspace.cjs @@ -0,0 +1,174 @@ +// This preload is scoped to the npm process that performs the edit. Loading +// through the original launcher preserves its Node version and environment. +const fs = require('fs'); +const path = require('path'); +const Module = require('module'); + +function nativeScope(config) { + return ( + config.get('global') || + config.get('location') === 'global' || + config.find('prefix') === 'cli' || + config.get('workspaces') === false || + !config.get('include-workspace-root') + ); +} + +function readManifest(dir) { + try { + return JSON.parse( + fs.readFileSync(path.join(dir, 'package.json'), 'utf8').replace(/^\uFEFF/, ''), + ); + } catch (error) { + if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) { + throw error; + } + return null; + } +} + +async function plan(Config, options, npm, member) { + async function loadConfig(root) { + const config = new Config({ ...options, env: { ...process.env } }); + if (root) { + config.loadLocalPrefix = () => { + config.localPrefix = root; + }; + } + await config.load(); + return config; + } + let config = await loadConfig(); + if (nativeScope(config)) { + return null; + } + + const mapWorkspaces = npm('@npmcli/map-workspaces'); + member = fs.realpathSync(member); + let root = member; + let workspaces; + for (let dir = path.dirname(member); ; dir = path.dirname(dir)) { + const pkg = readManifest(dir); + if (pkg && pkg.workspaces) { + const members = await mapWorkspaces({ cwd: dir, pkg }); + if ([...members.values()].includes(member)) { + root = dir; + workspaces = members; + break; + } + } + if (dir === path.dirname(dir)) { + break; + } + } + if (!workspaces) { + const pkg = readManifest(member); + if (!pkg || !pkg.workspaces) { + return null; + } + workspaces = await mapWorkspaces({ cwd: member, pkg }); + } + // An early npm 8 release or a nested node_modules can select the wrong + // project configuration. Load the owner's npmrc before resolving selectors. + const differentRoot = config.localPrefix !== root; + if (differentRoot) { + config = await loadConfig(root); + if (nativeScope(config)) { + return null; + } + } + const selectors = config.find('workspace') === 'default' ? [] : config.get('workspace'); + const combined = selectors.length > 0 || config.get('workspaces') === true; + const [command, ...operands] = config.parsedArgv.remain; + if (command === 'install' && combined && config.get('save') && !config.get('dry-run')) { + const npa = npm('npm-package-arg'); + const specs = operands.map((arg) => npa(arg, process.cwd())); + const members = new Set(workspaces.values()); + const oldNpm = npm('semver').lt(npm('../package.json').version, '8.19.0'); + if ( + specs.some((spec) => { + if (spec.type !== 'directory') { + return false; + } + return oldNpm || spec.name || !members.has(spec.fetchSpec); + }) + ) { + throw new Error( + 'Add the local directory to the root and each selected workspace separately so npm saves the correct relative paths.', + ); + } + if (specs.some((spec) => spec.type === 'file' && spec.name)) { + throw new Error( + 'Pass the tarball path without a package name, or add it to each target separately.', + ); + } + if (specs.some((spec) => spec.type === 'file') && oldNpm) { + throw new Error( + 'Adding a local tarball to both the root and a workspace requires npm 8.19.0 or later.', + ); + } + } + if (!differentRoot && (root === member || selectors.length > 0)) { + return null; + } + // npm 8 resolves path selectors from its prefix. Preserve their origin + // when selecting another prefix, including selectors configured in npmrc. + return { + root, + selectors: selectors.map((value) => + /^(?:\.{1,2})(?:[\\/]|$)/.test(value) ? path.resolve(value) : value, + ), + }; +} + +module.exports = function enable(member, preload) { + const original = Module.prototype.require; + let active = true; + function workspaceRequire(id) { + const result = original.call(this, id); + if (!active || id !== '@npmcli/config' || path.basename(this.filename) !== 'npm.js') { + return result; + } + const npm = Module.createRequire(this.filename); + if ( + path.basename(path.dirname(this.filename)) !== 'lib' || + !fs.existsSync(path.resolve(path.dirname(this.filename), '../package.json')) || + npm('../package.json').name !== 'npm' + ) { + return result; + } + active = false; + // A user preload may have wrapped this function after it was installed. + if (Module.prototype.require === workspaceRequire) { + Module.prototype.require = original; + } + // A lifecycle script can start another npm. Only the outer invocation is scoped. + const options = (process.env.NODE_OPTIONS || '') + .replace(preload + ' ', '') + .replace(preload, ''); + if (options) { + process.env.NODE_OPTIONS = options; + } else { + delete process.env.NODE_OPTIONS; + } + return class WorkspaceConfig extends result { + constructor(options) { + super(options); + this.workspaceOptions = options; + } + async load() { + const edit = await plan(result, this.workspaceOptions, npm, member); + if (edit) { + this.loadLocalPrefix = () => { + this.localPrefix = edit.root; + }; + } + await super.load(); + if (edit && edit.selectors.length) { + this.set('workspace', edit.selectors); + } + } + }; + } + Module.prototype.require = workspaceRequire; +}; diff --git a/crates/vp_pm_cli/src/resolution/npm_workspace.rs b/crates/vp_pm_cli/src/resolution/npm_workspace.rs new file mode 100644 index 0000000000..895c3161f2 --- /dev/null +++ b/crates/vp_pm_cli/src/resolution/npm_workspace.rs @@ -0,0 +1,47 @@ +//! Select npm's local project while preserving its launcher, cwd and global configuration. +use std::{collections::HashMap, ffi::OsString, io::Write}; + +use tempfile::NamedTempFile; +use vt_path::AbsolutePath; + +use crate::Error; + +pub(super) fn prepare( + cwd: &AbsolutePath, + env: &mut HashMap, +) -> Result, Error> { + let Ok(member) = vt_workspace::find_package_root(cwd) else { return Ok(None) }; + let has_parent_project = + member.path.as_path().ancestors().skip(1).any(|p| p.join("package.json").is_file()); + if !has_parent_project + && serde_json::from_slice::(member.package_json.content()) + .is_ok_and(|pkg| pkg.get("workspaces").is_none()) + { + return Ok(None); + } + // npm has no CLI flag for its local prefix alone. Load the adapter in the + // selected npm, including when the launcher chooses a runtime for this cwd. + let mut script = tempfile::Builder::new().prefix("vp-npm-").suffix(".cjs").tempfile()?; + let preload = + vt_str::format!("--require {}", serde_json::to_string(script.path())?).to_string(); + writeln!( + script, + "{}\nmodule.exports({}, {});", + include_str!("npm_workspace.cjs"), + serde_json::to_string(member.path.as_path())?, + serde_json::to_string(&preload)?, + )?; + script.flush()?; + let original = env + .get("NODE_OPTIONS") + .map(OsString::from) + .or_else(|| std::env::var_os("NODE_OPTIONS")) + .unwrap_or_default(); + let options = if original.is_empty() { + preload + } else { + vt_str::format!("{preload} {}", original.to_string_lossy()).to_string() + }; + env.insert("NODE_OPTIONS".into(), options); + Ok(Some(script)) +} diff --git a/crates/vp_pm_cli/src/resolution/runner.rs b/crates/vp_pm_cli/src/resolution/runner.rs index 58a26a84a3..4a657452f6 100644 --- a/crates/vp_pm_cli/src/resolution/runner.rs +++ b/crates/vp_pm_cli/src/resolution/runner.rs @@ -27,10 +27,12 @@ pub(crate) async fn run_resolution( } async fn run_command(cwd: &AbsolutePath, command: ResolvedCommand) -> Result { - let ResolvedCommand { program, args, env, pre_run } = command; + let ResolvedCommand { program, args, env, pre_run, npm_workspace_edit } = command; run_pre_run_actions(cwd, pre_run).await?; - let env = env.into_iter().collect::>(); + let mut env = env.into_iter().collect::>(); + let _npm_workspace_preload = + if npm_workspace_edit { super::npm_workspace::prepare(cwd, &mut env)? } else { None }; Ok(vp_command::run_command(&program, args, &env, cwd).await?) } diff --git a/docs/guide/package-management/add.md b/docs/guide/package-management/add.md index ec03914ae5..42a77153d6 100644 --- a/docs/guide/package-management/add.md +++ b/docs/guide/package-management/add.md @@ -81,4 +81,8 @@ The commands below describe project operations. Global mode is described under [ ## Native Options +With npm, `-w` adds the dependency to the root even when you run the command in a member. Add `--filter ` to include a member too. + +When adding a local tarball to both the root and a member, pass the tarball path without a package name and use npm 8.19.0 or later. For an external directory, add it to each target separately so each manifest gets the correct relative path. + For native options, see [npm install](https://docs.npmjs.com/cli/v11/commands/npm-install), [pnpm add](https://pnpm.io/cli/add), [Yarn add](https://yarnpkg.com/cli/add), [Yarn Classic add](https://classic.yarnpkg.com/en/docs/cli/add), and [Bun add](https://bun.com/docs/pm/cli/add). To pass these options through Vite+, see [Native Arguments](./#native-arguments).