From d93be3049f0a3bc12c2dda7693dde6291f88a1c9 Mon Sep 17 00:00:00 2001 From: Liang Date: Mon, 30 Nov 2026 06:08:04 +0800 Subject: [PATCH] fix(migrate): replace bundled packages only when they are devDependencies The current `vp migrate` removes Oxlint, Oxfmt, tsdown, `@vitest/browser`, and `@vitest/browser-preview` from every dependency field. A tsdown plugin that lists `tsdown` in both `devDependencies` and `peerDependencies` loses both declarations, so the published package drops its `tsdown` peer and its own tests no longer run against a real tsdown. This PR replaces these packages only when they are devDependencies. A package that also lists one in `dependencies`, `optionalDependencies`, or `peerDependencies` keeps every declaration of it, including the development copy. Such a package publishes or runs the tool, and its consumers may not use Vite+. Migration also keeps the catalog entry of such a package, so a kept `catalog:` reference still resolves. Its imports also stay unchanged instead of moving to the Vite+ surfaces. This PR includes a shared `declaresRuntimeDependency` check in `migrator/shared.ts`. It replaces the Oxlint-only exception in both the fresh and existing Vite+ paths, and the tsx, oxnode, and ts-node runner check, which already followed this rule. Optional `oxlint` now counts as a runtime declaration too. --- crates/vp_migration/src/import_rewriter.rs | 63 ++++++++-------- docs/guide/migrate-rules.md | 4 +- .../cli/src/__tests__/oxlint-plugin.spec.ts | 12 ++- .../src/migration/__tests__/migrator.spec.ts | 52 +++++++++++-- .../oxlint-plugin-dependency.spec.ts | 16 ++-- .../src/migration/migrator/orchestrators.ts | 28 +++---- .../src/migration/migrator/package-json.ts | 49 +++--------- .../src/migration/migrator/script-runner.ts | 13 +--- packages/cli/src/migration/migrator/shared.ts | 42 ++++++++--- .../migration/migrator/vite-plus-bootstrap.ts | 74 ++++++++----------- packages/cli/src/oxlint-plugin.ts | 21 ++---- 11 files changed, 194 insertions(+), 180 deletions(-) diff --git a/crates/vp_migration/src/import_rewriter.rs b/crates/vp_migration/src/import_rewriter.rs index 23dc8ac3af..bea62cec8c 100644 --- a/crates/vp_migration/src/import_rewriter.rs +++ b/crates/vp_migration/src/import_rewriter.rs @@ -2066,10 +2066,10 @@ struct SkipPackages { skip_vite: bool, /// Skip rewriting vitest imports (vitest is in peerDependencies or dependencies) skip_vitest: bool, - /// Skip rewriting tsdown imports (tsdown is in peerDependencies or dependencies) + /// Skip rewriting tsdown imports (tsdown is in dependencies, optionalDependencies, or peerDependencies) skip_tsdown: bool, /// Skip rewriting Oxlint JS-plugin API imports (`oxlint` or `@oxlint/plugins` - /// is in peerDependencies or dependencies, or @oxlint/plugins is optional). + /// is in dependencies, optionalDependencies, or peerDependencies). /// Published plugin consumers may not have Vite+. DevDependencies alone /// do not mark a published plugin and do not prevent rewriting. skip_oxlint: bool, @@ -2090,9 +2090,9 @@ pub struct RewriteImportsOptions { /// whose nearest package.json declares `@nuxt/test-utils`. pub preserve_vitest_in_nuxt_packages: bool, /// Directories of packages that declared `oxlint` or `@oxlint/plugins` in - /// `dependencies` or `peerDependencies`, or optional `@oxlint/plugins`, - /// before migration. Capture these before manifest edits so ownership - /// does not depend on which dependency declarations survive those edits. + /// `dependencies`, `optionalDependencies`, or `peerDependencies` before + /// migration. Capture these before manifest edits so ownership does not + /// depend on which dependency declarations survive those edits. pub oxlint_owner_dirs: Vec, } @@ -2266,10 +2266,18 @@ fn get_package_rewrite_context(package_json_path: &Path) -> PackageRewriteContex .and_then(|v| v.as_object()) .is_some_and(|deps| deps.contains_key(package_name)) }; + // Matches `declaresRuntimeDependency` in `migrator/shared.ts`: such a package keeps its + // declaration of a bundled tool, so its imports must keep resolving to that tool. + let declares_runtime = |package_name: &str| -> bool { + ["dependencies", "optionalDependencies", "peerDependencies"] + .into_iter() + .any(|key| has_package(key, package_name)) + }; // Peer and runtime dependencies preserve the existing whole-package skip - // behavior. Nuxt compatibility is narrower and accepts the three install - // groups where @nuxt/test-utils is normally declared. + // behavior; bundled tools also count optional declarations. Nuxt + // compatibility is narrower and accepts the three install groups where + // @nuxt/test-utils is normally declared. // // `vite` is additionally skipped when the package follows a published-plugin // naming convention: an unscoped name starting with `vite-plugin-` @@ -2288,13 +2296,8 @@ fn get_package_rewrite_context(package_json_path: &Path) -> PackageRewriteContex || package_name_is_plugin(&pkg), skip_vitest: has_package("peerDependencies", "vitest") || has_package("dependencies", "vitest"), - skip_tsdown: has_package("peerDependencies", "tsdown") - || has_package("dependencies", "tsdown"), - skip_oxlint: has_package("peerDependencies", "oxlint") - || has_package("dependencies", "oxlint") - || has_package("peerDependencies", "@oxlint/plugins") - || has_package("dependencies", "@oxlint/plugins") - || has_package("optionalDependencies", "@oxlint/plugins"), + skip_tsdown: declares_runtime("tsdown"), + skip_oxlint: declares_runtime("oxlint") || declares_runtime("@oxlint/plugins"), }, uses_nuxt_test_utils: ["dependencies", "devDependencies", "optionalDependencies"] .into_iter() @@ -5042,23 +5045,25 @@ export default defineConfig({});"#; } #[test] - fn test_optional_oxlint_keeps_existing_rewrite_policy() { - let temp = tempdir().unwrap(); - std::fs::write( - temp.path().join("package.json"), - r#"{"optionalDependencies":{"oxlint":"^1.79.0"}}"#, - ) - .unwrap(); - let file = temp.path().join("plugin.js"); - std::fs::write(&file, "import { defineRule } from 'oxlint';").unwrap(); + fn test_optional_bundled_tools_keep_upstream_imports() { + for (package, content) in [ + ("oxlint", "import { defineRule } from 'oxlint';"), + ("tsdown", "const { build } = await import('tsdown');"), + ] { + let temp = tempdir().unwrap(); + std::fs::write( + temp.path().join("package.json"), + format!(r#"{{"optionalDependencies":{{"{package}":"*"}}}}"#), + ) + .unwrap(); + let file = temp.path().join("index.js"); + std::fs::write(&file, content).unwrap(); - let result = rewrite_imports_in_directory(temp.path()).unwrap(); + let result = rewrite_imports_in_directory(temp.path()).unwrap(); - assert_eq!(result.modified_files, vec![file.clone()]); - assert_eq!( - std::fs::read_to_string(file).unwrap(), - "import { defineRule } from 'vite-plus/lint/plugins';" - ); + assert!(result.modified_files.is_empty(), "{package}"); + assert_eq!(std::fs::read_to_string(file).unwrap(), content); + } } #[test] diff --git a/docs/guide/migrate-rules.md b/docs/guide/migrate-rules.md index 94a87b558c..b874681f09 100644 --- a/docs/guide/migrate-rules.md +++ b/docs/guide/migrate-rules.md @@ -135,6 +135,8 @@ What happens to each toolchain dependency, at a glance: | `@vitest/*` | Directly installed lockstep packages aligned to the bundled Vitest version (see [Vitest Ecosystem Packages](#vitest-ecosystem-packages)). | | `@voidzero-dev/vite-plus-test` | Removed everywhere: dependencies, overrides, resolutions, and catalog aliases. Imports are rewritten to the current `vite-plus/test*` surface. | +Vite+ bundles Oxlint, Oxfmt, tsdown, `@vitest/browser`, and `@vitest/browser-preview`, so migration removes their `devDependencies` entries. A package that also lists one of them in `dependencies`, `optionalDependencies`, or `peerDependencies` keeps every declaration of it, including the development copy. Such a package publishes or runs the tool, and its consumers may not use Vite+. A tsdown plugin, for example, keeps `tsdown` as a peer and as the devDependency it tests against. Its `tsdown` imports also stay unchanged instead of moving to `vite-plus/pack`. Migration also keeps the catalog entries for these declarations, so a kept `catalog:` reference still resolves. + ### Version Selection - `vite-plus` is pinned to the concrete version of the CLI running the migration, never the `latest` dist-tag. @@ -239,7 +241,7 @@ The migration leaves three forms alone: - Default and namespace `oxlint` imports. They name no binding, so the migration cannot tell the two surfaces apart. - Bare side-effect `oxlint` imports, for the same reason. -The migration also skips a package that declares `oxlint` or `@oxlint/plugins` in `dependencies` or `peerDependencies`, or `@oxlint/plugins` in `optionalDependencies`. These dependencies can supply a published Oxlint plugin. Its consumers may not run Vite+. +The migration also skips a package that declares `oxlint` or `@oxlint/plugins` in `dependencies`, `optionalDependencies`, or `peerDependencies`. These dependencies can supply a published Oxlint plugin. Its consumers may not run Vite+. The cleanup retains a development dependency on `@oxlint/plugins` when source, package import aliases, or built plugins still reference it. This includes ignored output in directories such as `dist`, `build`, and `out`. diff --git a/packages/cli/src/__tests__/oxlint-plugin.spec.ts b/packages/cli/src/__tests__/oxlint-plugin.spec.ts index 34acac6d23..5eea19505a 100644 --- a/packages/cli/src/__tests__/oxlint-plugin.spec.ts +++ b/packages/cli/src/__tests__/oxlint-plugin.spec.ts @@ -332,6 +332,11 @@ new RuleTester({ `export { 'defineRule' as rule } from 'oxlint'`, `import { RuleTester } from 'oxlint/plugins-dev'`, ].map((code) => ({ code, filename: oxlintOptionalPluginPackageFilename })), + // Migration keeps optional `oxlint`, so its plugin API imports stay upstream too. + { + code: `import { defineRule } from 'oxlint'`, + filename: oxlintOptionalToolPackageFilename, + }, // `declare module` keeps the upstream module identity, so augmentations // still merge with the upstream declarations. { @@ -447,13 +452,6 @@ new RuleTester({ }, ], invalid: [ - { - // Optional oxlint retains the existing tool-migration policy. - code: `import { defineRule } from 'oxlint'`, - filename: oxlintOptionalToolPackageFilename, - errors: 1, - output: `import { defineRule } from 'vite-plus/lint/plugins'`, - }, { code: `import { definePlugin, defineRule } from '@oxlint/plugins'`, errors: 1, diff --git a/packages/cli/src/migration/__tests__/migrator.spec.ts b/packages/cli/src/migration/__tests__/migrator.spec.ts index b306677972..ad2e10279d 100644 --- a/packages/cli/src/migration/__tests__/migrator.spec.ts +++ b/packages/cli/src/migration/__tests__/migrator.spec.ts @@ -272,7 +272,7 @@ describe('rewritePackageJson', () => { }; rewritePackageJson(pkg, packageManager, isMonorepo); expect(pkg).toEqual({ - dependencies: { foo: '1.0.0' }, + dependencies: { foo: '1.0.0', tsdown: '1.0.0' }, devDependencies: { 'vite-plus': vitePlusSpec }, }); }, @@ -529,9 +529,9 @@ describe('rewritePackageJson', () => { rewritePackageJson(pkg, PackageManager.pnpm, true); expect(pkg.peerDependencies.vite).toBe('*'); - expect(pkg.peerDependencies).not.toHaveProperty('tsdown'); + expect(pkg.peerDependencies).toHaveProperty('tsdown'); expect(pkg.optionalDependencies.vitest).toBe('catalog:test'); - expect(pkg.optionalDependencies).not.toHaveProperty('oxlint'); + expect(pkg.optionalDependencies).toHaveProperty('oxlint'); expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); }); @@ -5634,7 +5634,8 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(yaml).toHaveProperty(['catalogs', 'vite7', 'vite-plus'], 'latest'); const testCatalog = fixtureObject(yaml, 'catalogs', 'test'); expect(testCatalog.vitest).toBeUndefined(); - expect(testCatalog.tsdown).toBeUndefined(); + // The tsdown peer survives migration, so its catalog entry does too. + expect(testCatalog.tsdown).toBe('^0.1.0'); expect(testCatalog['vite-plus']).toBeUndefined(); const pkg = readJson(path.join(tmpDir, 'package.json')); @@ -5645,7 +5646,48 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { // catalog entry to its public range before pruning it so the peer cannot // dangle after migration. expect(pkg).toHaveProperty(['peerDependencies', 'vitest'], '^4.0.0'); - expect(pkg.peerDependencies).not.toHaveProperty('tsdown'); + expect(pkg).toHaveProperty(['peerDependencies', 'tsdown'], 'catalog:test'); + }); + + // A tsdown plugin builds and tests against the tsdown its consumers provide. + it('keeps a bundled package that the project also declares as a peer', () => { + const packageJsonPath = path.join(tmpDir, 'package.json'); + fs.writeFileSync( + packageJsonPath, + JSON.stringify({ + name: 'tsdown-plugin-example', + peerDependencies: { tsdown: '^0.23.0' }, + devDependencies: { tsdown: '^0.23.0' }, + }), + ); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.pnpm); + + rewriteStandaloneProject(tmpDir, workspace, true, true); + + const pkg = readJson(packageJsonPath); + expect(pkg.peerDependencies).toEqual({ tsdown: '^0.23.0' }); + expect(pkg.devDependencies).toEqual({ tsdown: '^0.23.0', 'vite-plus': 'catalog:' }); + checkBootstrapPass(workspace, false); + expect(readJson(packageJsonPath)).toEqual(pkg); + }); + + // Vitest alignment turns the range into `catalog:`, so the kept runtime dependency needs its catalog entry. + it('adds a catalog entry for an aligned bundled package kept at runtime', () => { + const packageJsonPath = path.join(tmpDir, 'package.json'); + writePkgAt(tmpDir, { name: 'test', dependencies: { '@vitest/browser-preview': '^4.1.0' } }); + fs.writeFileSync(path.join(tmpDir, 'pnpm-workspace.yaml'), 'catalog:\n vite: ^7.0.0\n'); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.pnpm); + + rewriteStandaloneProject(tmpDir, workspace, true, true); + + const pkg = readJson(packageJsonPath); + expect(pkg).toHaveProperty(['dependencies', '@vitest/browser-preview'], 'catalog:'); + expect(readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml'))).toHaveProperty( + ['catalog', '@vitest/browser-preview'], + VITEST_VERSION, + ); + checkBootstrapPass(workspace, false); + expect(readJson(packageJsonPath)).toEqual(pkg); }); it('reuses catalogs.default without creating a duplicate top-level catalog', () => { diff --git a/packages/cli/src/migration/__tests__/oxlint-plugin-dependency.spec.ts b/packages/cli/src/migration/__tests__/oxlint-plugin-dependency.spec.ts index a25a90d576..8aecc8cc9d 100644 --- a/packages/cli/src/migration/__tests__/oxlint-plugin-dependency.spec.ts +++ b/packages/cli/src/migration/__tests__/oxlint-plugin-dependency.spec.ts @@ -589,8 +589,7 @@ describe('Oxlint plugin dependency cleanup', () => { expect(ensureVitePlusBootstrap(workspace).changed).toBe(false); expect(readJsonFile(packageJsonPath).dependencies).toEqual({ oxlint: '^1.0.0' }); - // An existing Vite+ project can still reference a catalog entry that the - // bootstrap deletes, so the kept dependency takes the concrete range. + // A kept `catalog:` reference keeps the catalog entry it points at. const pkg = readJsonFile(packageJsonPath); writeJsonFile(packageJsonPath, { ...pkg, dependencies: { oxlint: 'catalog:' } }); fs.writeFileSync( @@ -600,18 +599,17 @@ describe('Oxlint plugin dependency cleanup', () => { .replace('catalog:\n', 'catalog:\n oxlint: ^1.0.0\n'), ); - expect(pending()).toBe(true); - expect(ensureVitePlusBootstrap(workspace).changed).toBe(true); - expect(readJsonFile(packageJsonPath).dependencies).toEqual({ oxlint: '^1.0.0' }); - expect(fs.readFileSync(workspaceYamlPath, 'utf8')).not.toContain('oxlint: ^1.0.0'); expect(pending()).toBe(false); + expect(ensureVitePlusBootstrap(workspace).changed).toBe(false); + expect(readJsonFile(packageJsonPath).dependencies).toEqual({ oxlint: 'catalog:' }); + expect(fs.readFileSync(workspaceYamlPath, 'utf8')).toContain('oxlint: ^1.0.0'); }); - it('keeps optional oxlint on the existing tool-migration path', () => { + it('keeps optional oxlint as a runtime dependency', () => { const pkg = { optionalDependencies: { oxlint: '^1.79.0' } }; - expect(packageOwnsOxlintApi(pkg)).toBe(false); + expect(packageOwnsOxlintApi(pkg)).toBe(true); rewritePackageJson(pkg, PackageManager.pnpm); - expect(pkg.optionalDependencies).toEqual({}); + expect(pkg.optionalDependencies).toEqual({ oxlint: '^1.79.0' }); }); }); diff --git a/packages/cli/src/migration/migrator/orchestrators.ts b/packages/cli/src/migration/migrator/orchestrators.ts index 093bff699d..9db144e858 100644 --- a/packages/cli/src/migration/migrator/orchestrators.ts +++ b/packages/cli/src/migration/migrator/orchestrators.ts @@ -11,7 +11,7 @@ import { applyBuildAllowanceToPackageJsonPnpm, applyYarnWorkspaceHoistingFix, cleanupDeprecatedTsconfigOptions, - collectBrowserCatalogAdditions, + collectCatalogAdditions, collectOxlintDependencyNames, collectOxlintOwnerDirs, collectRetainedImportDependencies, @@ -112,7 +112,7 @@ export function rewriteStandaloneProject( workspaceInfo.packages, ); // Source-tree scan signals are computed once here and reused below (and inside - // projectUsesVitestDirectly / collectBrowserCatalogAdditions) so the source tree + // projectUsesVitestDirectly / collectCatalogAdditions) so the source tree // is traversed once each instead of repeatedly. They do not depend on // package.json contents and no scanned source files are mutated before they // are consumed, so the values match the previous lazy per-call scans exactly. @@ -126,7 +126,7 @@ export function rewriteStandaloneProject( const retainedVitestModule = retainedImportDependencies.vitest.has(projectPath) || sourceTreeReferencesRetainedVitestModule(projectPath); - const browserCatalogAdditions = collectBrowserCatalogAdditions( + const catalogAdditions = collectCatalogAdditions( projectPath, undefined, retainedImportDependencies.browser, @@ -274,7 +274,7 @@ export function rewriteStandaloneProject( usesVitest, retainedVitestModule, requiredVitestPeer, - browserCatalogAdditions, + catalogAdditions, retainedImportDependencies.browser.get(projectPath), ); @@ -316,7 +316,7 @@ export function rewriteStandaloneProject( usesVitest, vitestEcosystemPackages, usePnpmWorkspaceYaml, - browserCatalogAdditions, + catalogAdditions, usesWebdriverio, workspaceInfo.downloadPackageManager.version, ); @@ -343,7 +343,7 @@ export function rewriteStandaloneProject( projectPath, usesVitest, vitestEcosystemPackages, - browserCatalogAdditions, + catalogAdditions, supportCatalog, yarnSupportsPreapprovedPackages(workspaceInfo.downloadPackageManager.version), ); @@ -430,7 +430,7 @@ export function rewriteMonorepo( workspaceInfo.rootDir, workspaceInfo.packages, ); - const browserCatalogAdditions = collectBrowserCatalogAdditions( + const catalogAdditions = collectCatalogAdditions( workspaceInfo.rootDir, workspaceInfo.packages, retainedImportDependencies.browser, @@ -454,7 +454,7 @@ export function rewriteMonorepo( workspaceInfo.rootDir, workspaceUsesVitest, vitestEcosystemPackages, - browserCatalogAdditions, + catalogAdditions, supportCatalog, yarnSupportsPreapprovedPackages(workspaceInfo.downloadPackageManager.version), ); @@ -481,7 +481,7 @@ export function rewriteMonorepo( workspaceUsesVitest, vitestEcosystemPackages, usePnpmWorkspaceSettings, - browserCatalogAdditions, + catalogAdditions, usesWebdriverio, workspaceInfo.downloadPackageManager.version, ); @@ -499,7 +499,7 @@ export function rewriteMonorepo( vitestEcosystemPackages, usesWebdriverio, workspaceInfo.downloadPackageManager.version, - browserCatalogAdditions, + catalogAdditions, ); } // (mergeViteConfigFiles below will sanitize the merged lint config @@ -524,7 +524,7 @@ export function rewriteMonorepo( workspaceContext, true, supportCatalog, - browserCatalogAdditions, + catalogAdditions, ); } @@ -589,8 +589,8 @@ export function rewriteMonorepoProject( // Yarn >= 4.10.0; pnpm/bun monorepos always manage a catalog. Defaults to true // so the `vp create` callers (always a catalog-capable bundled PM) are covered. supportCatalog = true, - // An installed provider references the shared catalog entry added for a sibling. - browserCatalogAdditions: ReadonlySet = new Set(), + // Catalog entries that migration keeps or adds. An installed provider references one added for a sibling. + catalogAdditions: ReadonlySet = new Set(), ): void { cleanupDeprecatedTsconfigOptions(projectPath, silent, report); rewriteTsconfigTypes(projectPath, silent, report); @@ -652,7 +652,7 @@ export function rewriteMonorepoProject( }), retainedVitestModule, requiredVitestPeer, - browserCatalogAdditions, + catalogAdditions, workspaceContext?.retainedImportDependencies?.browser.get(projectPath), ); // If this SUB-workspace now depends on `vite-plus` and Yarn isolates its diff --git a/packages/cli/src/migration/migrator/package-json.ts b/packages/cli/src/migration/migrator/package-json.ts index 8842463c28..fe134d50e6 100644 --- a/packages/cli/src/migration/migrator/package-json.ts +++ b/packages/cli/src/migration/migrator/package-json.ts @@ -30,9 +30,9 @@ import { resolveProviderPeerSpec, OPT_IN_BROWSER_PROVIDERS, OXLINT_PLUGINS_PACKAGE, - OXLINT_PLUGIN_API_PACKAGES, packageOwnsOxlintApi, bundledPackagesToRemove, + removeBundledDevDependencies, VITEST_BROWSER_DEP_NAMES, VITEST_IS_MANAGED_OVERRIDE, } from './shared.ts'; @@ -67,8 +67,8 @@ export function rewritePackageJson( // Installed dependency metadata can reveal required Vitest peers whose // package names do not include "vitest". requiredVitestPeer = false, - // An installed provider references the shared catalog entry added for a sibling. - browserCatalogAdditions: ReadonlySet = new Set(), + // Catalog entries that migration keeps or adds. An installed provider references one added for a sibling. + catalogAdditions: ReadonlySet = new Set(), // Bundled browser packages that this package still imports. retainedBrowserPackages?: ReadonlySet, ): Record> | null { @@ -186,43 +186,14 @@ export function rewritePackageJson( const hasBrowserDepSignal = VITEST_BROWSER_DEP_NAMES.some((name) => dependencyGroups.some(({ dependencies }) => dependencies?.[name] !== undefined), ); - // Published plugins keep their upstream imports and the dependencies that - // supply them, including optional @oxlint/plugins integrations. - const ownsOxlintApi = packageOwnsOxlintApi(pkg); - // Rewritten imports need a direct vite-plus dependency. Defer removal of - // @oxlint/plugins until dropDeadOxlintPluginsDependency checks the final source. - if (pkg.devDependencies?.[OXLINT_PLUGINS_PACKAGE] !== undefined && !ownsOxlintApi) { + // Rewritten imports need a direct vite-plus dependency, but published plugins + // keep their upstream imports. Defer removal of @oxlint/plugins until + // dropDeadOxlintPluginsDependency checks the final source. + if (pkg.devDependencies?.[OXLINT_PLUGINS_PACKAGE] !== undefined && !packageOwnsOxlintApi(pkg)) { needVitePlus = true; } - // remove packages that are replaced with vite-plus - for (const name of bundledPackagesToRemove(retainedBrowserPackages)) { - let wasRemoved = false; - for (const { dependencyField, dependencies } of dependencyGroups) { - if ( - ownsOxlintApi && - (dependencyField === 'peerDependencies' || dependencyField === 'dependencies') && - (OXLINT_PLUGIN_API_PACKAGES as ReadonlyArray).includes(name) - ) { - // A `catalog:` reference would dangle once the catalog entry for a - // REMOVE_PACKAGES name is dropped, and the next install fails. Resolve - // it to the concrete range the catalog currently points at. - const current = dependencies?.[name]; - if (current?.startsWith('catalog:') && dependencies) { - const resolved = catalogDependencyResolver?.(current, name); - if (resolved) { - dependencies[name] = resolved; - } - } - continue; - } - if (dependencies?.[name]) { - delete dependencies[name]; - wasRemoved = true; - } - } - if (wasRemoved) { - needVitePlus = true; - } + if (removeBundledDevDependencies(pkg, bundledPackagesToRemove(retainedBrowserPackages))) { + needVitePlus = true; } // Official opt-in providers remain project dependencies. Align their versions // with bundled Vitest and ensure the framework peer required by each shim. @@ -256,7 +227,7 @@ export function rewritePackageJson( provider, installGroupEntry.dependencyField, packageManager, - browserCatalogAdditions.has(provider) + catalogAdditions.has(provider) ? supportCatalog && packageManager !== PackageManager.bun : supportCatalog, catalogDependencyResolver, diff --git a/packages/cli/src/migration/migrator/script-runner.ts b/packages/cli/src/migration/migrator/script-runner.ts index 69f465ee9b..3939a4e43c 100644 --- a/packages/cli/src/migration/migrator/script-runner.ts +++ b/packages/cli/src/migration/migrator/script-runner.ts @@ -15,6 +15,7 @@ import { sourceTreeMatches } from '../migrator.ts'; import type { MigrationReport } from '../report.ts'; import type { DependencyBag } from './shared.ts'; import { + declaresRuntimeDependency, getCommandStartIndex, isPlainRecord, LINT_STAGED_JSON_CONFIG_FILES, @@ -944,17 +945,9 @@ function lintStagedJsonFiles(dir: string): Array { ); } -/** - * A package that lists a runner outside devDependencies keeps it: published code or - * production scripts can need it, and `vpx` comes from the vite-plus devDependency. - */ +// `vpx` comes from the vite-plus devDependency, so it cannot replace a runner the package needs at runtime. function ownsRunnerAtRuntime(runner: ScriptRunnerMigration, pkg: DependencyBag): boolean { - return runner.dependencies.some( - (dependency) => - pkg.dependencies?.[dependency] !== undefined || - pkg.optionalDependencies?.[dependency] !== undefined || - pkg.peerDependencies?.[dependency] !== undefined, - ); + return runner.dependencies.some((dependency) => declaresRuntimeDependency(pkg, dependency)); } function packageDirs(rootDir: string, packages?: ReadonlyArray): Array { diff --git a/packages/cli/src/migration/migrator/shared.ts b/packages/cli/src/migration/migrator/shared.ts index f136365131..7d7a511333 100644 --- a/packages/cli/src/migration/migrator/shared.ts +++ b/packages/cli/src/migration/migrator/shared.ts @@ -469,23 +469,47 @@ export function pnpmMajor(version: string | undefined): number | undefined { return version ? coerce(version)?.major : undefined; } -// Packages that own the Oxlint JS-plugin authoring API as a published contract. -// Optional `@oxlint/plugins` is also a runtime contract for consumers of a -// published integration. Optional `oxlint` keeps the existing tool policy. export const OXLINT_PLUGINS_PACKAGE = '@oxlint/plugins'; -export const OXLINT_PLUGIN_API_PACKAGES = ['oxlint', OXLINT_PLUGINS_PACKAGE] as const; +const OXLINT_PLUGIN_API_PACKAGES = ['oxlint', OXLINT_PLUGINS_PACKAGE] as const; +// A package that declares either at runtime owns the Oxlint JS-plugin authoring API as a published contract. export function packageOwnsOxlintApi(pkg: DependencyBag): boolean { + return OXLINT_PLUGIN_API_PACKAGES.some((name) => declaresRuntimeDependency(pkg, name)); +} + +/** + * Vite+ replaces only a devDependency. A package that also lists it in + * `dependencies`, `optionalDependencies`, or `peerDependencies` publishes or + * runs it, and its consumers may not use Vite+. + */ +export function declaresRuntimeDependency(pkg: DependencyBag, name: string): boolean { return ( - pkg.optionalDependencies?.[OXLINT_PLUGINS_PACKAGE] !== undefined || - OXLINT_PLUGIN_API_PACKAGES.some( - (name) => - pkg.dependencies?.[name] !== undefined || pkg.peerDependencies?.[name] !== undefined, - ) + pkg.dependencies?.[name] !== undefined || + pkg.optionalDependencies?.[name] !== undefined || + pkg.peerDependencies?.[name] !== undefined ); } +/** + * Remove the bundled packages that Vite+ replaces. Returns whether the package + * lists any of them as a devDependency, kept or not. + */ +export function removeBundledDevDependencies( + pkg: DependencyBag, + names: ReadonlyArray, +): boolean { + let declared = false; + for (const name of names) { + declared ||= pkg.devDependencies?.[name] !== undefined; + // A kept `catalog:` reference still resolves because `collectCatalogAdditions` keeps its entry. + if (!declaresRuntimeDependency(pkg, name)) { + delete pkg.devDependencies?.[name]; + } + } + return declared; +} + /** * Capture plugin owners before manifest edits, so the import rewriter can * preserve their upstream API imports after those edits. diff --git a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts index bcb0737a07..e2b9cf5677 100644 --- a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts +++ b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts @@ -75,9 +75,10 @@ import { hasProviderPeerDependency, resolveProviderPeerSpec, OPT_IN_BROWSER_PROVIDERS, - OXLINT_PLUGIN_API_PACKAGES, - packageOwnsOxlintApi, bundledPackagesToRemove, + declaresRuntimeDependency, + REMOVE_PACKAGES, + removeBundledDevDependencies, VITEST_IS_MANAGED_OVERRIDE, managedOverrideKey, pinnedPackageManagerVersion, @@ -301,8 +302,8 @@ function reconcileVitePlusBootstrapPackage( supportCatalog: boolean, ensureVitePlus: boolean, catalogDependencyResolver?: CatalogDependencyResolver, - // An installed provider references the shared catalog entry added for a sibling. - browserCatalogAdditions: ReadonlySet = new Set(), + // Catalog entries that migration keeps or adds. An installed provider references one added for a sibling. + catalogAdditions: ReadonlySet = new Set(), retainedImportDependencies?: RetainedImportDependencies, ): boolean { const before = JSON.stringify(pkg); @@ -366,7 +367,7 @@ function reconcileVitePlusBootstrapPackage( provider, installGroupEntry.dependencyField, packageManager, - browserCatalogAdditions.has(provider) + catalogAdditions.has(provider) ? supportCatalog && packageManager !== PackageManager.bun : supportCatalog, catalogDependencyResolver, @@ -394,34 +395,10 @@ function reconcileVitePlusBootstrapPackage( // Match the fresh migration and catalog cleanup. A preserved browser import // still needs its declared browser dependency in this package. - const ownsOxlintApi = packageOwnsOxlintApi(pkg); - for (const bundledPackage of bundledPackagesToRemove( - retainedImportDependencies?.browser.get(projectPath), - )) { - for (const dependencies of installGroups) { - if ( - ownsOxlintApi && - dependencies !== undefined && - dependencies === pkg.dependencies && - (OXLINT_PLUGIN_API_PACKAGES as ReadonlyArray).includes(bundledPackage) - ) { - // A published plugin keeps the runtime dependency that supplies its - // upstream imports, as the fresh path does. Its `catalog:` reference - // becomes the concrete range because the catalog entry is deleted. - const current = dependencies[bundledPackage]; - if (current?.startsWith('catalog:')) { - const resolved = catalogDependencyResolver?.(current, bundledPackage); - if (resolved) { - dependencies[bundledPackage] = resolved; - } - } - continue; - } - if (dependencies?.[bundledPackage] !== undefined) { - delete dependencies[bundledPackage]; - } - } - } + removeBundledDevDependencies( + pkg, + bundledPackagesToRemove(retainedImportDependencies?.browser.get(projectPath)), + ); if (usesAnyOptInProvider && packageManager === PackageManager.npm) { const viteAlreadyDirect = installGroups.some( @@ -505,8 +482,11 @@ export function bootstrapProjectPaths( return getWorkspaceProjectPaths({ rootDir, packages }); } -/** Catalog entries needed for retained browser imports and newly installed providers. */ -export function collectBrowserCatalogAdditions( +/** + * Catalog entries needed for retained browser imports, newly installed + * providers, and bundled packages that a package declares at runtime. + */ +export function collectCatalogAdditions( rootDir: string, packages?: Array, retainedBrowserPackages?: RetainedImportDependencies['browser'], @@ -525,6 +505,12 @@ export function collectBrowserCatalogAdditions( continue; } const pkg = readJsonFile(packageJsonPath) as BootstrapPackageJson; + // Migration keeps these declarations, and a `catalog:` reference among them still needs its entry. + for (const name of REMOVE_PACKAGES) { + if (declaresRuntimeDependency(pkg, name)) { + names.add(name); + } + } const sourceModes = precomputedSourceModes?.get(packagePath) ?? collectProviderSourceModes(packagePath); const installGroups = [pkg.devDependencies, pkg.dependencies, pkg.optionalDependencies]; @@ -689,7 +675,7 @@ export function detectVitePlusBootstrapPending( // Match the actual reconcile so an already-installed provider whose catalog // entry the migration will add is reported pending (its spec must become // `catalog:`). See #2005. - const browserCatalogAdditions = collectBrowserCatalogAdditions( + const catalogAdditions = collectCatalogAdditions( projectPath, packages, retainedImportDependencies?.browser, @@ -710,7 +696,7 @@ export function detectVitePlusBootstrapPending( supportCatalog, index === 0, catalogDependencyResolver, - browserCatalogAdditions, + catalogAdditions, retainedImportDependencies, ) ) { @@ -1035,7 +1021,7 @@ export function ensureVitePlusBootstrap( projectPath, workspaceInfo.packages, ); - const browserCatalogAdditions = collectBrowserCatalogAdditions( + const catalogAdditions = collectCatalogAdditions( projectPath, workspaceInfo.packages, retainedImportDependencies?.browser, @@ -1066,7 +1052,7 @@ export function ensureVitePlusBootstrap( usesVitest, vitestEcosystemPackages, false, - browserCatalogAdditions, + catalogAdditions, usesWebdriverio, workspaceInfo.downloadPackageManager.version, ); @@ -1082,7 +1068,7 @@ export function ensureVitePlusBootstrap( supportCatalog, true, catalogDependencyResolver, - browserCatalogAdditions, + catalogAdditions, retainedImportDependencies, ); @@ -1182,7 +1168,7 @@ export function ensureVitePlusBootstrap( supportCatalog, false, catalogDependencyResolver, - browserCatalogAdditions, + catalogAdditions, retainedImportDependencies, ); if ( @@ -1241,7 +1227,7 @@ export function ensureVitePlusBootstrap( usesVitest, vitestEcosystemPackages, true, - browserCatalogAdditions, + catalogAdditions, usesWebdriverio, workspaceInfo.downloadPackageManager.version, ); @@ -1269,7 +1255,7 @@ export function ensureVitePlusBootstrap( projectPath, usesVitest, vitestEcosystemPackages, - browserCatalogAdditions, + catalogAdditions, supportCatalog, yarnSupportsPreapprovedPackages(workspaceInfo.downloadPackageManager.version), ); @@ -1283,7 +1269,7 @@ export function ensureVitePlusBootstrap( vitestEcosystemPackages, usesWebdriverio, workspaceInfo.downloadPackageManager.version, - browserCatalogAdditions, + catalogAdditions, ); const after = fs.readFileSync(packageJsonPath, 'utf8'); result.packageJson = result.packageJson || before !== after; diff --git a/packages/cli/src/oxlint-plugin.ts b/packages/cli/src/oxlint-plugin.ts index ea46f9be4e..a255285687 100644 --- a/packages/cli/src/oxlint-plugin.ts +++ b/packages/cli/src/oxlint-plugin.ts @@ -304,20 +304,15 @@ function nearestPackageKeepsVitest(filename: string): boolean { } // Match the migrator's published-plugin exemption. Development-only APIs do not -// exempt a package; optional @oxlint/plugins is a consumer runtime dependency. +// exempt a package; optional declarations are consumer runtime dependencies. function nearestPackageOwnsOxlintApi(filename: string): boolean { - return nearestPackageMatches( - filename, - oxlintOwnerPackageCache, - (pkg) => - (isObjectValue(pkg.optionalDependencies) && - pkg.optionalDependencies[OXLINT_PLUGINS_PACKAGE] !== undefined) || - [pkg.dependencies, pkg.peerDependencies].some( - (dependencies) => - isObjectValue(dependencies) && - (dependencies[OXLINT_PACKAGE] !== undefined || - dependencies[OXLINT_PLUGINS_PACKAGE] !== undefined), - ), + return nearestPackageMatches(filename, oxlintOwnerPackageCache, (pkg) => + [pkg.dependencies, pkg.optionalDependencies, pkg.peerDependencies].some( + (dependencies) => + isObjectValue(dependencies) && + (dependencies[OXLINT_PACKAGE] !== undefined || + dependencies[OXLINT_PLUGINS_PACKAGE] !== undefined), + ), ); }