diff --git a/Cargo.lock b/Cargo.lock index 7358ff316d..cf9611c154 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8585,11 +8585,13 @@ dependencies = [ "ast-grep-core", "ast-grep-language", "brush-parser", + "fast-glob", "ignore", "js-semver", "oxc", "rayon", "regex", + "serde", "serde_json", "tempfile", "vp_error", diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/app.test.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/app.test.ts new file mode 100644 index 0000000000..057a5af85f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/app.test.ts @@ -0,0 +1,2 @@ +import { test } from 'vitest'; +test('application', () => {}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/examples/vite.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/examples/vite.config.ts new file mode 100644 index 0000000000..0b79ce8fee --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/examples/vite.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from 'vite'; +export default defineConfig({}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/package.json new file mode 100644 index 0000000000..16cf6cd188 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/package.json @@ -0,0 +1 @@ +{ "name": "lint-import-overrides", "private": true, "type": "module", "devDependencies": { "vite-plus": "latest" } } diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/snapshots.toml new file mode 100644 index 0000000000..db075a3f87 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/snapshots.toml @@ -0,0 +1,10 @@ +[[case]] +name = "lint_vite_plus_imports_overrides" +vp = "local" +comment = "Existing lint.overrides can disable only the import rule in templates and examples, with no migrate configuration. Other lint rules remain active." +steps = [ + { argv = ["vp", "lint", "--threads=1", "--fix", "app.test.ts", "templates/starter.test.ts", "examples/vite.config.ts"], continue-on-failure = true }, + { argv = ["vpt", "print-file", "app.test.ts"], continue-on-failure = true }, + ["vpt", "print-file", "templates/starter.test.ts"], + ["vpt", "print-file", "examples/vite.config.ts"], +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/snapshots/lint_vite_plus_imports_overrides.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/snapshots/lint_vite_plus_imports_overrides.md new file mode 100644 index 0000000000..fb05943e8c --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/snapshots/lint_vite_plus_imports_overrides.md @@ -0,0 +1,44 @@ +# lint_vite_plus_imports_overrides + +Existing lint.overrides can disable only the import rule in templates and examples, with no migrate configuration. Other lint rules remain active. + +## `vp lint --threads=1 --fix app.test.ts templates/starter.test.ts examples/vite.config.ts` + +**Exit code:** 1 + +``` + + × eslint(no-debugger): `debugger` statement is not allowed + ╭─[templates/starter.test.ts:2:1] + 1 │ import { test } from 'vitest'; + 2 │ debugger; + · ───────── + 3 │ test('template', () => {}); + ╰──── + help: Remove the debugger statement + +Found 0 warnings and 1 error. +Finished in on 3 files with rules using threads. +``` + +## `vpt print-file app.test.ts` + +``` +import { test } from 'vite-plus/test'; +test('application', () => {}); +``` + +## `vpt print-file templates/starter.test.ts` + +``` +import { test } from 'vitest'; +debugger; +test('template', () => {}); +``` + +## `vpt print-file examples/vite.config.ts` + +``` +import { defineConfig } from 'vite'; +export default defineConfig({}); +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/templates/starter.test.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/templates/starter.test.ts new file mode 100644 index 0000000000..a95b040e4a --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/templates/starter.test.ts @@ -0,0 +1,3 @@ +import { test } from 'vitest'; +debugger; +test('template', () => {}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/vite.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/vite.config.ts new file mode 100644 index 0000000000..40a3af6960 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/lint_vite_plus_imports_overrides/vite.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vite-plus'; +export default defineConfig({ + lint: { + jsPlugins: [{ name: 'vite-plus', specifier: 'vite-plus/oxlint-plugin' }], + rules: { 'vite-plus/prefer-vite-plus-imports': 'error', 'no-debugger': 'error' }, + overrides: [ + { + files: ['templates/**', 'examples/**'], + rules: { 'vite-plus/prefer-vite-plus-imports': 'off' }, + }, + ], + }, +}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_config_process_crash_isolated/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_config_process_crash_isolated/snapshots.toml index 7270673f22..6fda17a1e5 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_config_process_crash_isolated/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_config_process_crash_isolated/snapshots.toml @@ -5,3 +5,21 @@ steps = [ { argv = ["vp", "migrate", "--no-interactive", "--no-hooks"], comment = "project config process handlers must not terminate migration", continue-on-failure = true }, { argv = ["vpt", "print-file", "vite.config.ts"], comment = "migration still rewrites the config after its compatibility probe crashes", continue-on-failure = true }, ] + +[[case]] +name = "migration_config_dynamic_process_crash_isolated" +vp = "local" +comment = "A crashing dynamic config preserves Vitest imports while migration still rewrites tsdown imports." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "devDependencies", "{\"vite-plus\":\"latest\"}"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "scripts", "{\"build\":\"vite build\"}"], snapshot = false }, + { argv = ["vpt", "replace-file-content", "vite.config.ts", "import { defineConfig } from 'vite';", ""], snapshot = false }, + { argv = ["vpt", "replace-file-content", "vite.config.ts", "export default defineConfig({});", "export default () => ({});"], snapshot = false }, + { argv = ["vpt", "write-file", "unit.test.ts", "import { test } from 'vitest';\n"], snapshot = false }, + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "print-file", "unit.test.ts"], + ["vpt", "print-file", "package.json"], + { argv = ["vpt", "write-file", "unit.test.ts", "import { test } from 'vitest';\nimport { defineConfig } from 'tsdown';\n"], snapshot = false }, + { argv = ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], comment = "Dependencies are up to date on the second run." }, + ["vpt", "print-file", "unit.test.ts"], +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_config_process_crash_isolated/snapshots/migration_config_dynamic_process_crash_isolated.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_config_process_crash_isolated/snapshots/migration_config_dynamic_process_crash_isolated.md new file mode 100644 index 0000000000..fd63ae939a --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_config_process_crash_isolated/snapshots/migration_config_dynamic_process_crash_isolated.md @@ -0,0 +1,85 @@ +# migration_config_dynamic_process_crash_isolated + +A crashing dynamic config preserves Vitest imports while migration still rewrites tsdown imports. + +## `vpt json-edit package.json devDependencies '{"vite-plus":"latest"}'` + + +## `vpt json-edit package.json scripts '{"build":"vite build"}'` + + +## `vpt replace-file-content vite.config.ts 'import { defineConfig } from '\''vite'\'';' ` + + +## `vpt replace-file-content vite.config.ts 'export default defineConfig({});' 'export default () => ({});'` + + +## `vpt write-file unit.test.ts 'import { test } from '\''vitest'\''; +'` + + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Updated . to Vite+ +• Node pnpm +• Dependencies: + vite-plus latest → + vite → +• Package manager settings configured +! Warnings: + - Could not load lint configuration in an isolated process. Skipped Vite/Vitest import rewrites; fix the config and re-run `vp migrate`. +``` + +## `vpt print-file unit.test.ts` + +``` +import { test } from 'vitest'; +``` + +## `vpt print-file package.json` + +``` +{ + "devDependencies": { + "vite-plus": "catalog:" + }, + "name": "migration-config-process-crash-isolated", + "private": true, + "scripts": { + "build": "vp build" + }, + "version": "0.0.0" +} +``` + +## `vpt write-file unit.test.ts 'import { test } from '\''vitest'\''; +import { defineConfig } from '\''tsdown'\''; +'` + + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +Dependencies are up to date on the second run. + +``` +VITE+ - The Unified Toolchain for the Web + +▲ No package manager is declared in package.json; using pnpm for this migration without adding a pin. Run `vp env pin` to declare it explicitly. +◇ Updated . to Vite+ +• Node pnpm +• Dependencies: + vite → +• 1 file had imports rewritten +! Warnings: + - Could not load lint configuration in an isolated process. Skipped Vite/Vitest import rewrites; fix the config and re-run `vp migrate`. +``` + +## `vpt print-file unit.test.ts` + +``` +import { test } from 'vitest'; +import { defineConfig } from 'vite-plus/pack'; +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/examples/standalone/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/examples/standalone/package.json new file mode 100644 index 0000000000..14a01f696b --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/examples/standalone/package.json @@ -0,0 +1 @@ +{ "name": "standalone-template", "private": true, "type": "module", "devDependencies": { "vite": "^8.0.0", "vitest": "^4.1.11" } } diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/examples/standalone/unit.test.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/examples/standalone/unit.test.ts new file mode 100644 index 0000000000..fee5fb1242 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/examples/standalone/unit.test.ts @@ -0,0 +1,2 @@ +import { expect, test } from 'vitest'; +test('outside-workspace', () => expect(1).toBe(1)); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/package.json new file mode 100644 index 0000000000..ab4f2d8a6b --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/package.json @@ -0,0 +1,7 @@ +{ + "name": "migration-import-rule", + "private": true, + "type": "module", + "devDependencies": { "vite-plus": "catalog:" }, + "devEngines": { "packageManager": { "name": "pnpm", "version": "10.33.0", "onFail": "download" } } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/packages/app/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/packages/app/package.json new file mode 100644 index 0000000000..6c0d9255f6 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/packages/app/package.json @@ -0,0 +1,5 @@ +{ + "name": "app", "private": true, "type": "module", + "scripts": { "build": "vite build", "test": "vitest run" }, + "devDependencies": { "vite": "catalog:", "vitest": "catalog:legacy", "@vitest/coverage-v8": "catalog:legacy" } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/packages/app/unit.test.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/packages/app/unit.test.ts new file mode 100644 index 0000000000..43ccd6e1ae --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/packages/app/unit.test.ts @@ -0,0 +1,2 @@ +import { expect, test } from 'vitest'; +test('application', () => expect(1).toBe(1)); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/packages/app/vite.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/packages/app/vite.config.ts new file mode 100644 index 0000000000..0b79ce8fee --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/packages/app/vite.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from 'vite'; +export default defineConfig({}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/pnpm-workspace.yaml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/pnpm-workspace.yaml new file mode 100644 index 0000000000..e7f5c119eb --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/pnpm-workspace.yaml @@ -0,0 +1,12 @@ +packages: + - packages/* + - templates/* +catalog: + vite-plus: latest + vite: ^8.0.0 +catalogs: + legacy: + vitest: ^4.1.11 + '@vitest/coverage-v8': ^4.1.11 +overrides: + unrelated-package: 1.0.0 diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots.toml new file mode 100644 index 0000000000..306ecda6f8 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots.toml @@ -0,0 +1,129 @@ +[[case]] +name = "migration_import_rule_reporter_workspace" +vp = "local" +comment = "Migration and lint autofix respect the root overrides for templates and questions, while rewriting app imports." +steps = [ + { argv = ["vpt", "write-file", "vite.config.ts", "import { defineConfig } from 'vite-plus';\nexport default defineConfig({ lint: { jsPlugins: ['vite-plus/oxlint-plugin'], rules: { 'vite-plus/prefer-vite-plus-imports': 'error' }, overrides: [{ files: ['templates/**', 'questions/**'], rules: { 'vite-plus/prefer-vite-plus-imports': 'off' } }] } });\n"], snapshot = false }, + { argv = ["vpt", "write-file", "questions/demo.test.ts", "import { test } from 'vitest';\ntest('question', () => {});\n"], snapshot = false }, + { argv = ["vpt", "write-file", "packages/app/demo.test.ts", "import { test } from 'vitest';\ntest('app', () => {});\n"], snapshot = false }, + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "print-file", "templates/starter/vite.config.ts"], + ["vpt", "print-file", "questions/demo.test.ts"], + ["vpt", "print-file", "packages/app/demo.test.ts"], + { argv = ["vpt", "write-file", "packages/app/demo.test.ts", "import { test } from 'vitest';\ntest('app', () => {});\n"], snapshot = false }, + ["vp", "lint", "--threads=1", "--fix", "templates/starter/vite.config.ts", "questions/demo.test.ts", "packages/app/demo.test.ts"], + ["vpt", "print-file", "templates/starter/vite.config.ts"], + ["vpt", "print-file", "questions/demo.test.ts"], + ["vpt", "print-file", "packages/app/demo.test.ts"], +] + +[[case]] +name = "migration_import_rule_upgrade" +vp = "local" +comment = "Existing Vite+ migration honors ordered lint overrides while still migrating scripts, dependencies, catalogs and overrides." +steps = [ + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "print-file", "templates/starter/vite.config.ts"], + ["vpt", "print-file", "templates/starter/unit.test.ts"], + ["vpt", "print-file", "templates/managed/unit.test.ts"], + ["vpt", "print-file", "examples/standalone/unit.test.ts"], + ["vpt", "print-file", "packages/app/unit.test.ts"], + ["vpt", "print-file", "templates/starter/package.json"], + ["vpt", "print-file", "pnpm-workspace.yaml"], + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "write-file", "packages/app/unit.test.ts", "import { test } from 'vitest';\ntest('autofix', () => {});\n"], + { argv = ["vp", "lint", "--threads=1", "--fix", "templates/starter/unit.test.ts", "packages/app/unit.test.ts"], continue-on-failure = true }, + { argv = ["vpt", "print-file", "templates/starter/unit.test.ts"], continue-on-failure = true }, + ["vpt", "print-file", "packages/app/unit.test.ts"], +] + +[[case]] +name = "migration_import_rule_fresh" +vp = "local" +comment = "Initial migration respects the same import rule configuration." +steps = [ + ["vpt", "json-edit", "package.json", "devDependencies", "{}"], + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "print-file", "templates/starter/vite.config.ts"], + ["vpt", "print-file", "templates/starter/unit.test.ts"], + ["vpt", "print-file", "templates/managed/unit.test.ts"], + ["vpt", "print-file", "examples/standalone/unit.test.ts"], + ["vpt", "print-file", "packages/app/unit.test.ts"], + ["vpt", "print-file", "templates/starter/package.json"], + ["vpt", "print-file", "pnpm-workspace.yaml"], +] + +[[case]] +name = "migration_import_rule_full" +vp = "local" +comment = "Full migration and check autofix share the import rule; other lint rules remain active." +steps = [ + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor", "--full"], + ["vpt", "print-file", "templates/starter/vite.config.ts"], + ["vpt", "print-file", "templates/starter/unit.test.ts"], + ["vpt", "print-file", "templates/managed/unit.test.ts"], + ["vpt", "print-file", "examples/standalone/unit.test.ts"], + ["vpt", "print-file", "packages/app/unit.test.ts"], + ["vpt", "print-file", "templates/starter/package.json"], + ["vpt", "print-file", "pnpm-workspace.yaml"], + ["vpt", "write-file", "packages/app/unit.test.ts", "import { test } from 'vitest';\ntest('autofix', () => {});\n"], + { argv = ["vp", "check", "--no-fmt", "--fix", "templates/starter/unit.test.ts", "packages/app/unit.test.ts"], continue-on-failure = true }, + { argv = ["vpt", "print-file", "templates/starter/unit.test.ts"], continue-on-failure = true }, + ["vpt", "print-file", "packages/app/unit.test.ts"], +] + +[[case]] +name = "migration_import_rule_global_off" +vp = "local" +comment = "A global numeric off setting applies unless a matching override re-enables imports." +steps = [ + ["vpt", "write-file", "vite.config.ts", "export default { lint: { rules: { 'vite-plus/prefer-vite-plus-imports': [0] }, overrides: [{ files: ['packages/**'], rules: { 'vite-plus/prefer-vite-plus-imports': [1] } }] } };\n"], + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "print-file", "templates/starter/vite.config.ts"], + ["vpt", "print-file", "templates/starter/unit.test.ts"], + ["vpt", "print-file", "templates/managed/unit.test.ts"], + ["vpt", "print-file", "examples/standalone/unit.test.ts"], + ["vpt", "print-file", "packages/app/unit.test.ts"], +] + +[[case]] +name = "migration_import_rule_runtime" +vp = "local" +comment = "Dynamic lint configuration uses normal config resolution." +steps = [ + ["vpt", "write-file", "vite.config.ts", "const files = ['templates/**', 'examples/**'];\nexport default () => ({ lint: { overrides: [{ files, excludeFiles: ['templates/managed/**'], rules: { 'vite-plus/prefer-vite-plus-imports': 'off' } }] } });\n"], + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "print-file", "templates/starter/vite.config.ts"], + ["vpt", "print-file", "templates/starter/unit.test.ts"], + ["vpt", "print-file", "templates/managed/unit.test.ts"], + ["vpt", "print-file", "examples/standalone/unit.test.ts"], + ["vpt", "print-file", "packages/app/unit.test.ts"], +] + +[[case]] +name = "migration_import_rule_extends" +vp = "local" +comment = "Inherited overrides apply before local overrides; bare patterns match at any depth." +steps = [ + ["vpt", "write-file", "vite.config.ts", "export default { lint: { extends: [{ overrides: [{ files: ['*.ts'], rules: { 'vite-plus/prefer-vite-plus-imports': 'off' } }] }], overrides: [{ files: ['packages/**', './templates/managed/**'], rules: { 'vite-plus/prefer-vite-plus-imports': ['error'] } }] } };\n"], + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "print-file", "templates/starter/vite.config.ts"], + ["vpt", "print-file", "templates/starter/unit.test.ts"], + ["vpt", "print-file", "templates/managed/unit.test.ts"], + ["vpt", "print-file", "examples/standalone/unit.test.ts"], + ["vpt", "print-file", "packages/app/unit.test.ts"], +] + +[[case]] +name = "migration_import_rule_runtime_cjs" +vp = "local" +comment = "Isolated config loading preserves CommonJS support and inherited lint overrides." +steps = [ + { argv = ["vpt", "rm", "vite.config.ts"], snapshot = false }, + { argv = ["vpt", "write-file", "vite.config.cjs", "module.exports = () => ({ lint: { extends: [{ overrides: [{ files: ['templates/**', 'examples/**'], rules: { 'vite-plus/prefer-vite-plus-imports': 'off' } }] }], overrides: [{ files: ['templates/managed/**'], rules: { 'vite-plus/prefer-vite-plus-imports': 'error' } }] } });\n"], snapshot = false }, + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "print-file", "templates/starter/unit.test.ts"], + ["vpt", "print-file", "templates/managed/unit.test.ts"], + ["vpt", "print-file", "examples/standalone/unit.test.ts"], + ["vpt", "print-file", "packages/app/unit.test.ts"], +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_extends.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_extends.md new file mode 100644 index 0000000000..9bbe531555 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_extends.md @@ -0,0 +1,65 @@ +# migration_import_rule_extends + +Inherited overrides apply before local overrides; bare patterns match at any depth. + +## `vpt write-file vite.config.ts 'export default { lint: { extends: [{ overrides: [{ files: ['\''*.ts'\''], rules: { '\''vite-plus/prefer-vite-plus-imports'\'': '\''off'\'' } }] }], overrides: [{ files: ['\''packages/**'\'', '\''./templates/managed/**'\''], rules: { '\''vite-plus/prefer-vite-plus-imports'\'': ['\''error'\''] } }] } }; +'` + +``` +``` + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Updated . to Vite+ +• Node pnpm +• Dependencies: + vite-plus latest → + vite → +• 3 files had imports rewritten +• Package manager settings configured +``` + +## `vpt print-file templates/starter/vite.config.ts` + +``` +import { defineConfig } from 'vite'; +export default defineConfig({test: { + // Vitest v4 compatibility: preserve mock call history. + // Remove after tests no longer rely on calls from setup or earlier tests. + // https://viteplus.dev/guide/vitest-v5#remove-unneeded-compatibility-settings + // https://vitest.dev/guide/migration/#clearmocks-is-enabled-by-default + clearMocks: false, + poolOptions: {threads: {singleThread: true}}}}); +``` + +## `vpt print-file templates/starter/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +debugger; +test('template', () => expect(1).toBe(1)); +``` + +## `vpt print-file templates/managed/unit.test.ts` + +``` +import { expect, test } from 'vite-plus/test'; +test('included', () => expect(1).toBe(1)); +``` + +## `vpt print-file examples/standalone/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +test('outside-workspace', () => expect(1).toBe(1)); +``` + +## `vpt print-file packages/app/unit.test.ts` + +``` +import { expect, test } from 'vite-plus/test'; +test('application', () => expect(1).toBe(1)); +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_fresh.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_fresh.md new file mode 100644 index 0000000000..0e5089e3da --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_fresh.md @@ -0,0 +1,108 @@ +# migration_import_rule_fresh + +Initial migration respects the same import rule configuration. + +## `vpt json-edit package.json devDependencies {}` + +``` +``` + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Migrated . to Vite+ +• Node pnpm +• 1 config update applied, 3 files had imports rewritten +! Warnings: + - Removed `"esModuleInterop": false` from templates/starter/tsconfig.json — this option has been deprecated. See https://github.com/oxc-project/tsgolint/issues/351, https://github.com/microsoft/TypeScript/issues/62529 +``` + +## `vpt print-file templates/starter/vite.config.ts` + +``` +import { defineConfig } from 'vite'; +export default defineConfig({test: { + // Vitest v4 compatibility: preserve mock call history. + // Remove after tests no longer rely on calls from setup or earlier tests. + // https://viteplus.dev/guide/vitest-v5#remove-unneeded-compatibility-settings + // https://vitest.dev/guide/migration/#clearmocks-is-enabled-by-default + clearMocks: false, + poolOptions: {threads: {singleThread: true}}}}); +``` + +## `vpt print-file templates/starter/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +debugger; +test('template', () => expect(1).toBe(1)); +``` + +## `vpt print-file templates/managed/unit.test.ts` + +``` +import { expect, test } from 'vite-plus/test'; +test('included', () => expect(1).toBe(1)); +``` + +## `vpt print-file examples/standalone/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +test('outside-workspace', () => expect(1).toBe(1)); +``` + +## `vpt print-file packages/app/unit.test.ts` + +``` +import { expect, test } from 'vite-plus/test'; +test('application', () => expect(1).toBe(1)); +``` + +## `vpt print-file templates/starter/package.json` + +``` +{ + "name": "starter", + "private": true, + "type": "module", + "scripts": { + "build": "vp build", + "test": "vp test run" + }, + "devDependencies": { + "vite": "catalog:", + "vitest": "catalog:legacy", + "@vitest/coverage-v8": "catalog:legacy", + "vite-plus": "catalog:" + } +} +``` + +## `vpt print-file pnpm-workspace.yaml` + +``` +packages: + - packages/* + - templates/* +catalog: + vite-plus: + vite: npm:@voidzero-dev/vite-plus-core@ + vitest: + '@vitest/coverage-v8': +catalogs: + legacy: + vitest: + '@vitest/coverage-v8': +overrides: + unrelated-package: 1.0.0 + vite@*: 'catalog:' + vitest@*: 'catalog:' +peerDependencyRules: + allowAny: + - vitest + allowedVersions: + vitest: '*' +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_full.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_full.md new file mode 100644 index 0000000000..5e64cff4b8 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_full.md @@ -0,0 +1,144 @@ +# migration_import_rule_full + +Full migration and check autofix share the import rule; other lint rules remain active. + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor --full` + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Updated . to Vite+ +• Node pnpm +• Dependencies: + vite-plus latest → + vite → +• 3 files had imports rewritten +• Package manager settings configured +``` + +## `vpt print-file templates/starter/vite.config.ts` + +``` +import { defineConfig } from 'vite'; +export default defineConfig({test: { + // Vitest v4 compatibility: preserve mock call history. + // Remove after tests no longer rely on calls from setup or earlier tests. + // https://viteplus.dev/guide/vitest-v5#remove-unneeded-compatibility-settings + // https://vitest.dev/guide/migration/#clearmocks-is-enabled-by-default + clearMocks: false, + poolOptions: {threads: {singleThread: true}}}}); +``` + +## `vpt print-file templates/starter/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +debugger; +test('template', () => expect(1).toBe(1)); +``` + +## `vpt print-file templates/managed/unit.test.ts` + +``` +import { expect, test } from 'vite-plus/test'; +test('included', () => expect(1).toBe(1)); +``` + +## `vpt print-file examples/standalone/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +test('outside-workspace', () => expect(1).toBe(1)); +``` + +## `vpt print-file packages/app/unit.test.ts` + +``` +import { expect, test } from 'vite-plus/test'; +test('application', () => expect(1).toBe(1)); +``` + +## `vpt print-file templates/starter/package.json` + +``` +{ + "name": "starter", + "private": true, + "type": "module", + "scripts": { + "build": "vp build", + "test": "vp test run" + }, + "devDependencies": { + "vite": "catalog:", + "vitest": "catalog:legacy", + "@vitest/coverage-v8": "catalog:legacy" + } +} +``` + +## `vpt print-file pnpm-workspace.yaml` + +``` +packages: + - packages/* + - templates/* +catalog: + vite-plus: + vite: npm:@voidzero-dev/vite-plus-core@ + vitest: + '@vitest/coverage-v8': +catalogs: + legacy: + vitest: + '@vitest/coverage-v8': +overrides: + unrelated-package: 1.0.0 + vite@*: 'catalog:' + vitest@*: 'catalog:' +peerDependencyRules: + allowAny: + - vitest + allowedVersions: + vitest: '*' +``` + +## `vpt write-file packages/app/unit.test.ts 'import { test } from '\''vitest'\''; +test('\''autofix'\'', () => {}); +'` + +``` +``` + +## `vp check --no-fmt --fix templates/starter/unit.test.ts packages/app/unit.test.ts` + +**Exit code:** 1 + +``` +error: Lint issues found +× eslint(no-debugger): `debugger` statement is not allowed + ╭─[templates/starter/unit.test.ts:2:1] + 1 │ import { expect, test } from 'vitest'; + 2 │ debugger; + · ───────── + 3 │ test('template', () => expect(1).toBe(1)); + ╰──── + help: Remove the debugger statement + +Found 1 error and 0 warnings in 2 files (, threads) +``` + +## `vpt print-file templates/starter/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +debugger; +test('template', () => expect(1).toBe(1)); +``` + +## `vpt print-file packages/app/unit.test.ts` + +``` +import { test } from 'vite-plus/test'; +test('autofix', () => {}); +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_global_off.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_global_off.md new file mode 100644 index 0000000000..63097d475e --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_global_off.md @@ -0,0 +1,65 @@ +# migration_import_rule_global_off + +A global numeric off setting applies unless a matching override re-enables imports. + +## `vpt write-file vite.config.ts 'export default { lint: { rules: { '\''vite-plus/prefer-vite-plus-imports'\'': [0] }, overrides: [{ files: ['\''packages/**'\''], rules: { '\''vite-plus/prefer-vite-plus-imports'\'': [1] } }] } }; +'` + +``` +``` + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Updated . to Vite+ +• Node pnpm +• Dependencies: + vite-plus latest → + vite → +• 2 files had imports rewritten +• Package manager settings configured +``` + +## `vpt print-file templates/starter/vite.config.ts` + +``` +import { defineConfig } from 'vite'; +export default defineConfig({test: { + // Vitest v4 compatibility: preserve mock call history. + // Remove after tests no longer rely on calls from setup or earlier tests. + // https://viteplus.dev/guide/vitest-v5#remove-unneeded-compatibility-settings + // https://vitest.dev/guide/migration/#clearmocks-is-enabled-by-default + clearMocks: false, + poolOptions: {threads: {singleThread: true}}}}); +``` + +## `vpt print-file templates/starter/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +debugger; +test('template', () => expect(1).toBe(1)); +``` + +## `vpt print-file templates/managed/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +test('included', () => expect(1).toBe(1)); +``` + +## `vpt print-file examples/standalone/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +test('outside-workspace', () => expect(1).toBe(1)); +``` + +## `vpt print-file packages/app/unit.test.ts` + +``` +import { expect, test } from 'vite-plus/test'; +test('application', () => expect(1).toBe(1)); +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_reporter_workspace.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_reporter_workspace.md new file mode 100644 index 0000000000..72085a4ac6 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_reporter_workspace.md @@ -0,0 +1,98 @@ +# migration_import_rule_reporter_workspace + +Migration and lint autofix respect the root overrides for templates and questions, while rewriting app imports. + +## `vpt write-file vite.config.ts 'import { defineConfig } from '\''vite-plus'\''; +export default defineConfig({ lint: { jsPlugins: ['\''vite-plus/oxlint-plugin'\''], rules: { '\''vite-plus/prefer-vite-plus-imports'\'': '\''error'\'' }, overrides: [{ files: ['\''templates/**'\'', '\''questions/**'\''], rules: { '\''vite-plus/prefer-vite-plus-imports'\'': '\''off'\'' } }] } }); +'` + + +## `vpt write-file questions/demo.test.ts 'import { test } from '\''vitest'\''; +test('\''question'\'', () => {}); +'` + + +## `vpt write-file packages/app/demo.test.ts 'import { test } from '\''vitest'\''; +test('\''app'\'', () => {}); +'` + + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Updated . to Vite+ +• Node pnpm +• Dependencies: + vite-plus latest → + vite → +• 4 files had imports rewritten +• Package manager settings configured +``` + +## `vpt print-file templates/starter/vite.config.ts` + +``` +import { defineConfig } from 'vite'; +export default defineConfig({test: { + // Vitest v4 compatibility: preserve mock call history. + // Remove after tests no longer rely on calls from setup or earlier tests. + // https://viteplus.dev/guide/vitest-v5#remove-unneeded-compatibility-settings + // https://vitest.dev/guide/migration/#clearmocks-is-enabled-by-default + clearMocks: false, + poolOptions: {threads: {singleThread: true}}}}); +``` + +## `vpt print-file questions/demo.test.ts` + +``` +import { test } from 'vitest'; +test('question', () => {}); +``` + +## `vpt print-file packages/app/demo.test.ts` + +``` +import { test } from 'vite-plus/test'; +test('app', () => {}); +``` + +## `vpt write-file packages/app/demo.test.ts 'import { test } from '\''vitest'\''; +test('\''app'\'', () => {}); +'` + + +## `vp lint --threads=1 --fix templates/starter/vite.config.ts questions/demo.test.ts packages/app/demo.test.ts` + +``` +Found 0 warnings and 0 errors. +Finished in on 3 files with rules using threads. +``` + +## `vpt print-file templates/starter/vite.config.ts` + +``` +import { defineConfig } from 'vite'; +export default defineConfig({test: { + // Vitest v4 compatibility: preserve mock call history. + // Remove after tests no longer rely on calls from setup or earlier tests. + // https://viteplus.dev/guide/vitest-v5#remove-unneeded-compatibility-settings + // https://vitest.dev/guide/migration/#clearmocks-is-enabled-by-default + clearMocks: false, + poolOptions: {threads: {singleThread: true}}}}); +``` + +## `vpt print-file questions/demo.test.ts` + +``` +import { test } from 'vitest'; +test('question', () => {}); +``` + +## `vpt print-file packages/app/demo.test.ts` + +``` +import { test } from 'vite-plus/test'; +test('app', () => {}); +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_runtime.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_runtime.md new file mode 100644 index 0000000000..55b659b359 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_runtime.md @@ -0,0 +1,66 @@ +# migration_import_rule_runtime + +Dynamic lint configuration uses normal config resolution. + +## `vpt write-file vite.config.ts 'const files = ['\''templates/**'\'', '\''examples/**'\'']; +export default () => ({ lint: { overrides: [{ files, excludeFiles: ['\''templates/managed/**'\''], rules: { '\''vite-plus/prefer-vite-plus-imports'\'': '\''off'\'' } }] } }); +'` + +``` +``` + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Updated . to Vite+ +• Node pnpm +• Dependencies: + vite-plus latest → + vite → +• 3 files had imports rewritten +• Package manager settings configured +``` + +## `vpt print-file templates/starter/vite.config.ts` + +``` +import { defineConfig } from 'vite'; +export default defineConfig({test: { + // Vitest v4 compatibility: preserve mock call history. + // Remove after tests no longer rely on calls from setup or earlier tests. + // https://viteplus.dev/guide/vitest-v5#remove-unneeded-compatibility-settings + // https://vitest.dev/guide/migration/#clearmocks-is-enabled-by-default + clearMocks: false, + poolOptions: {threads: {singleThread: true}}}}); +``` + +## `vpt print-file templates/starter/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +debugger; +test('template', () => expect(1).toBe(1)); +``` + +## `vpt print-file templates/managed/unit.test.ts` + +``` +import { expect, test } from 'vite-plus/test'; +test('included', () => expect(1).toBe(1)); +``` + +## `vpt print-file examples/standalone/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +test('outside-workspace', () => expect(1).toBe(1)); +``` + +## `vpt print-file packages/app/unit.test.ts` + +``` +import { expect, test } from 'vite-plus/test'; +test('application', () => expect(1).toBe(1)); +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_runtime_cjs.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_runtime_cjs.md new file mode 100644 index 0000000000..1ce48a2d01 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_runtime_cjs.md @@ -0,0 +1,53 @@ +# migration_import_rule_runtime_cjs + +Isolated config loading preserves CommonJS support and inherited lint overrides. + +## `vpt rm vite.config.ts` + + +## `vpt write-file vite.config.cjs 'module.exports = () => ({ lint: { extends: [{ overrides: [{ files: ['\''templates/**'\'', '\''examples/**'\''], rules: { '\''vite-plus/prefer-vite-plus-imports'\'': '\''off'\'' } }] }], overrides: [{ files: ['\''templates/managed/**'\''], rules: { '\''vite-plus/prefer-vite-plus-imports'\'': '\''error'\'' } }] } }); +'` + + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Updated . to Vite+ +• Node pnpm +• Dependencies: + vite-plus latest → + vite → +• 3 files had imports rewritten +• Package manager settings configured +``` + +## `vpt print-file templates/starter/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +debugger; +test('template', () => expect(1).toBe(1)); +``` + +## `vpt print-file templates/managed/unit.test.ts` + +``` +import { expect, test } from 'vite-plus/test'; +test('included', () => expect(1).toBe(1)); +``` + +## `vpt print-file examples/standalone/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +test('outside-workspace', () => expect(1).toBe(1)); +``` + +## `vpt print-file packages/app/unit.test.ts` + +``` +import { expect, test } from 'vite-plus/test'; +test('application', () => expect(1).toBe(1)); +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_upgrade.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_upgrade.md new file mode 100644 index 0000000000..f3b78ecf3b --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/snapshots/migration_import_rule_upgrade.md @@ -0,0 +1,153 @@ +# migration_import_rule_upgrade + +Existing Vite+ migration honors ordered lint overrides while still migrating scripts, dependencies, catalogs and overrides. + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Updated . to Vite+ +• Node pnpm +• Dependencies: + vite-plus latest → + vite → +• 3 files had imports rewritten +• Package manager settings configured +``` + +## `vpt print-file templates/starter/vite.config.ts` + +``` +import { defineConfig } from 'vite'; +export default defineConfig({test: { + // Vitest v4 compatibility: preserve mock call history. + // Remove after tests no longer rely on calls from setup or earlier tests. + // https://viteplus.dev/guide/vitest-v5#remove-unneeded-compatibility-settings + // https://vitest.dev/guide/migration/#clearmocks-is-enabled-by-default + clearMocks: false, + poolOptions: {threads: {singleThread: true}}}}); +``` + +## `vpt print-file templates/starter/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +debugger; +test('template', () => expect(1).toBe(1)); +``` + +## `vpt print-file templates/managed/unit.test.ts` + +``` +import { expect, test } from 'vite-plus/test'; +test('included', () => expect(1).toBe(1)); +``` + +## `vpt print-file examples/standalone/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +test('outside-workspace', () => expect(1).toBe(1)); +``` + +## `vpt print-file packages/app/unit.test.ts` + +``` +import { expect, test } from 'vite-plus/test'; +test('application', () => expect(1).toBe(1)); +``` + +## `vpt print-file templates/starter/package.json` + +``` +{ + "name": "starter", + "private": true, + "type": "module", + "scripts": { + "build": "vp build", + "test": "vp test run" + }, + "devDependencies": { + "vite": "catalog:", + "vitest": "catalog:legacy", + "@vitest/coverage-v8": "catalog:legacy" + } +} +``` + +## `vpt print-file pnpm-workspace.yaml` + +``` +packages: + - packages/* + - templates/* +catalog: + vite-plus: + vite: npm:@voidzero-dev/vite-plus-core@ + vitest: + '@vitest/coverage-v8': +catalogs: + legacy: + vitest: + '@vitest/coverage-v8': +overrides: + unrelated-package: 1.0.0 + vite@*: 'catalog:' + vitest@*: 'catalog:' +peerDependencyRules: + allowAny: + - vitest + allowedVersions: + vitest: '*' +``` + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +This project is already using Vite+! Happy coding! +``` + +## `vpt write-file packages/app/unit.test.ts 'import { test } from '\''vitest'\''; +test('\''autofix'\'', () => {}); +'` + +``` +``` + +## `vp lint --threads=1 --fix templates/starter/unit.test.ts packages/app/unit.test.ts` + +**Exit code:** 1 + +``` + + × eslint(no-debugger): `debugger` statement is not allowed + ╭─[templates/starter/unit.test.ts:2:1] + 1 │ import { expect, test } from 'vitest'; + 2 │ debugger; + · ───────── + 3 │ test('template', () => expect(1).toBe(1)); + ╰──── + help: Remove the debugger statement + +Found 0 warnings and 1 error. +Finished in on 2 files with rules using threads. +``` + +## `vpt print-file templates/starter/unit.test.ts` + +``` +import { expect, test } from 'vitest'; +debugger; +test('template', () => expect(1).toBe(1)); +``` + +## `vpt print-file packages/app/unit.test.ts` + +``` +import { test } from 'vite-plus/test'; +test('autofix', () => {}); +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/managed/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/managed/package.json new file mode 100644 index 0000000000..fb282db2e7 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/managed/package.json @@ -0,0 +1 @@ +{ "name": "managed", "private": true, "type": "module", "devDependencies": { "vite": "^8.0.0", "vitest": "^4.1.11" } } diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/managed/unit.test.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/managed/unit.test.ts new file mode 100644 index 0000000000..64ccb0c91d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/managed/unit.test.ts @@ -0,0 +1,2 @@ +import { expect, test } from 'vitest'; +test('included', () => expect(1).toBe(1)); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/starter/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/starter/package.json new file mode 100644 index 0000000000..dad97a5f9b --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/starter/package.json @@ -0,0 +1,5 @@ +{ + "name": "starter", "private": true, "type": "module", + "scripts": { "build": "vite build", "test": "vitest run" }, + "devDependencies": { "vite": "catalog:", "vitest": "catalog:legacy", "@vitest/coverage-v8": "catalog:legacy" } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/starter/tsconfig.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/starter/tsconfig.json new file mode 100644 index 0000000000..dc98a30fcd --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/starter/tsconfig.json @@ -0,0 +1 @@ +{ "compilerOptions": { "types": ["vite/client", "vitest/globals"], "esModuleInterop": false } } diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/starter/unit.test.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/starter/unit.test.ts new file mode 100644 index 0000000000..a8415c55f6 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/starter/unit.test.ts @@ -0,0 +1,3 @@ +import { expect, test } from 'vitest'; +debugger; +test('template', () => expect(1).toBe(1)); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/starter/vite.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/starter/vite.config.ts new file mode 100644 index 0000000000..2df3caf172 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/templates/starter/vite.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from 'vite'; +export default defineConfig({test: {poolOptions: {threads: {singleThread: true}}}}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/vite.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/vite.config.ts new file mode 100644 index 0000000000..48f48b642f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule/vite.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from 'vite-plus'; +export default defineConfig({ + lint: { + jsPlugins: ['vite-plus/oxlint-plugin'], + rules: { 'vite-plus/prefer-vite-plus-imports': 'error', 'no-debugger': 'error' }, + overrides: [ + { files: ['templates/**', 'examples/**'], rules: { 'vite-plus/prefer-vite-plus-imports': 'off' } }, + { files: ['templates/managed/**'], rules: { 'vite-plus/prefer-vite-plus-imports': 'warn' } }, + ], + }, +}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/lint-policy/index.js b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/lint-policy/index.js new file mode 100644 index 0000000000..03fe7b8d16 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/lint-policy/index.js @@ -0,0 +1,3 @@ +export default { + overrides: [{ files: ['templates/**'], rules: { 'vite-plus/prefer-vite-plus-imports': 'off' } }], +}; diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/lint-policy/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/lint-policy/package.json new file mode 100644 index 0000000000..66208871a5 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/lint-policy/package.json @@ -0,0 +1,6 @@ +{ + "name": "lint-policy", + "version": "1.0.0", + "type": "module", + "exports": "./index.js" +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/package.json new file mode 100644 index 0000000000..9e91346278 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/package.json @@ -0,0 +1,13 @@ +{ + "name": "migration-import-rule-install", + "private": true, + "type": "module", + "packageManager": "pnpm@12.11.2", + "scripts": { + "build": "vite build" + }, + "devDependencies": { + "lint-policy": "file:./lint-policy", + "vite-plus": "latest" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/snapshots.toml new file mode 100644 index 0000000000..caf772f3e6 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/snapshots.toml @@ -0,0 +1,42 @@ +[[case]] +name = "migration_import_rule_install" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL"] +comment = "After installation makes dynamic lint settings available, the upgrade keeps a direct Vitest dependency for the excluded template and removes it from the app." +steps = [ + { argv = ["vpt", "write-file", "pnpm-workspace.yaml", "packages:\n - templates\n - packages/*\nnodeLinker: isolated\nhoist: false\n"], snapshot = false }, + { argv = ["vpt", "write-file", "templates/package.json", "{\"name\":\"template\",\"private\":true,\"type\":\"module\",\"devDependencies\":{\"vitest\":\"^5.0.0\"}}\n"], snapshot = false }, + { argv = ["vpt", "write-file", "packages/app/package.json", "{\"name\":\"app\",\"private\":true,\"type\":\"module\",\"devDependencies\":{\"vitest\":\"^5.0.0\"}}\n"], snapshot = false }, + { argv = ["vpt", "cp", "unit.test.ts", "packages/app/unit.test.ts"], snapshot = false }, + ["vpt", "stat-file", "node_modules", "--assert", "missing"], + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "stat-file", "node_modules/vite-plus/package.json", "--assert", "file"], + ["vpt", "print-file", "templates/unit.test.ts"], + ["vpt", "print-file", "templates/package.json"], + ["vpt", "print-file", "packages/app/unit.test.ts"], + ["vpt", "print-file", "packages/app/package.json"], + ["vpt", "print-file", "unit.test.ts"], + ["vpt", "print-file", "package.json"], + ["vpt", "stat-file", "templates/node_modules/vitest/package.json", "--assert", "file"], + { cwd = "templates", argv = ["node", "--input-type=module", "-e", "import { test } from 'vitest'; console.log(typeof test);"] }, + ["vpt", "stat-file", "packages/app/node_modules/vitest/package.json", "--assert", "missing"], + { argv = ["vp", "install", "--frozen-lockfile", "--ignore-scripts"], snapshot = false }, + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], +] + +[[case]] +name = "migration_import_rule_runtime_no_install" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL"] +comment = "Reading mode in a dynamic config does not trigger an install on an up-to-date project." +steps = [ + { argv = ["vpt", "write-file", "vite.config.ts", "export default ({ mode }) => ({ mode });\n"], snapshot = false }, + { argv = ["vpt", "write-file", ".pnpmfile.cjs", "require('node:fs').writeFileSync(require('node:path').join(__dirname, 'install-requested'), 'install');\nmodule.exports = {};\n"], snapshot = false }, + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + { argv = ["vpt", "stat-file", "install-requested", "--assert", "file"], comment = "The upgrade's required install activates the probe." }, + { argv = ["vpt", "rm", "install-requested"], snapshot = false }, + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "stat-file", "install-requested", "--assert", "missing"], +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/snapshots/migration_import_rule_install.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/snapshots/migration_import_rule_install.md new file mode 100644 index 0000000000..f806966d79 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/snapshots/migration_import_rule_install.md @@ -0,0 +1,143 @@ +# migration_import_rule_install + +After installation makes dynamic lint settings available, the upgrade keeps a direct Vitest dependency for the excluded template and removes it from the app. + +## `vpt write-file pnpm-workspace.yaml 'packages: + - templates + - packages/* +nodeLinker: isolated +hoist: false +'` + + +## `vpt write-file templates/package.json '{"name":"template","private":true,"type":"module","devDependencies":{"vitest":"^5.0.0"}} +'` + + +## `vpt write-file packages/app/package.json '{"name":"app","private":true,"type":"module","devDependencies":{"vitest":"^5.0.0"}} +'` + + +## `vpt cp unit.test.ts packages/app/unit.test.ts` + + +## `vpt stat-file node_modules --assert missing` + +``` +node_modules: missing +``` + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +● Formatting code... +● Code formatted +◇ Updated . to Vite+ +• Node pnpm +• Dependencies: + vite-plus latest → + vite → +✓ Dependencies installed in +• 2 files had imports rewritten +• Package manager settings configured +``` + +## `vpt stat-file node_modules/vite-plus/package.json --assert file` + +``` +node_modules/vite-plus/package.json: file +``` + +## `vpt print-file templates/unit.test.ts` + +``` +import { test } from "vitest"; +test("template", () => {}); +``` + +## `vpt print-file templates/package.json` + +``` +{ + "name": "template", + "private": true, + "type": "module", + "devDependencies": { + "vitest": "catalog:" + } +} +``` + +## `vpt print-file packages/app/unit.test.ts` + +``` +import { test } from "vite-plus/test"; +test("application", () => {}); +``` + +## `vpt print-file packages/app/package.json` + +``` +{ + "name": "app", + "private": true, + "type": "module", + "devDependencies": {} +} +``` + +## `vpt print-file unit.test.ts` + +``` +import { test } from "vite-plus/test"; +test("application", () => {}); +``` + +## `vpt print-file package.json` + +``` +{ + "name": "migration-import-rule-install", + "private": true, + "type": "module", + "scripts": { + "build": "vp build" + }, + "devDependencies": { + "lint-policy": "file:./lint-policy", + "vite-plus": "catalog:" + }, + "packageManager": "pnpm@12.11.2" +} +``` + +## `vpt stat-file templates/node_modules/vitest/package.json --assert file` + +``` +templates/node_modules/vitest/package.json: file +``` + +## `cd templates && node --input-type=module -e 'import { test } from '\''vitest'\''; console.log(typeof test);'` + +``` +function +``` + +## `vpt stat-file packages/app/node_modules/vitest/package.json --assert missing` + +``` +packages/app/node_modules/vitest/package.json: missing +``` + +## `vp install --frozen-lockfile --ignore-scripts` + + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +This project is already using Vite+! Happy coding! +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/snapshots/migration_import_rule_runtime_no_install.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/snapshots/migration_import_rule_runtime_no_install.md new file mode 100644 index 0000000000..3963ce983a --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/snapshots/migration_import_rule_runtime_no_install.md @@ -0,0 +1,54 @@ +# migration_import_rule_runtime_no_install + +Reading mode in a dynamic config does not trigger an install on an up-to-date project. + +## `vpt write-file vite.config.ts 'export default ({ mode }) => ({ mode }); +'` + + +## `vpt write-file .pnpmfile.cjs 'require('\''node:fs'\'').writeFileSync(require('\''node:path'\'').join(__dirname, '\''install-requested'\''), '\''install'\''); +module.exports = {}; +'` + + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +● Formatting code... +● Code formatted +◇ Updated . to Vite+ +• Node pnpm +• Dependencies: + vite-plus latest → + vite → +✓ Dependencies installed in +• 2 files had imports rewritten +• Package manager settings configured +``` + +## `vpt stat-file install-requested --assert file` + +The upgrade's required install activates the probe. + +``` +install-requested: file +``` + +## `vpt rm install-requested` + + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +This project is already using Vite+! Happy coding! +``` + +## `vpt stat-file install-requested --assert missing` + +``` +install-requested: missing +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/templates/unit.test.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/templates/unit.test.ts new file mode 100644 index 0000000000..9d285b4322 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/templates/unit.test.ts @@ -0,0 +1,2 @@ +import { test } from 'vitest'; +test('template', () => {}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/unit.test.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/unit.test.ts new file mode 100644 index 0000000000..057a5af85f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/unit.test.ts @@ -0,0 +1,2 @@ +import { test } from 'vitest'; +test('application', () => {}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/vite.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/vite.config.ts new file mode 100644 index 0000000000..8a9c817d99 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_install/vite.config.ts @@ -0,0 +1,4 @@ +import { defineConfig } from 'vite-plus'; +import lint from 'lint-policy'; + +export default defineConfig({ lint }); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/package.json new file mode 100644 index 0000000000..b1bc42877a --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/package.json @@ -0,0 +1,6 @@ +{ + "name": "import-rule-workspace", + "private": true, + "type": "module", + "packageManager": "pnpm@12.11.2" +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/packages/app/demo.test.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/packages/app/demo.test.ts new file mode 100644 index 0000000000..6d13a10010 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/packages/app/demo.test.ts @@ -0,0 +1,3 @@ +import { test } from 'vitest'; + +test('app', () => {}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/packages/app/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/packages/app/package.json new file mode 100644 index 0000000000..c3629dd548 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/packages/app/package.json @@ -0,0 +1,6 @@ +{ + "name": "app", + "private": true, + "type": "module", + "devDependencies": { "vitest": "^5.0.0" } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/pnpm-workspace.yaml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/pnpm-workspace.yaml new file mode 100644 index 0000000000..0a01bf9029 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/pnpm-workspace.yaml @@ -0,0 +1,5 @@ +packages: + - templates/* + - packages/* +nodeLinker: isolated +hoist: false diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/snapshots.toml new file mode 100644 index 0000000000..ae9af2078d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/snapshots.toml @@ -0,0 +1,72 @@ +[[case]] +name = "migration_import_rule_template_dependency" +vp = "local" +local-registry = true +comment = "Only the package whose source still imports Vitest needs a direct Vitest dependency." +steps = [ + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "print-file", "templates/starter/demo.test.ts"], + ["vpt", "print-file", "templates/starter/package.json"], + ["vpt", "print-file", "packages/app/demo.test.ts"], + ["vpt", "print-file", "packages/app/package.json"], + ["vpt", "print-file", "pnpm-workspace.yaml"], + ["vpt", "stat-file", "templates/starter/node_modules", "--assert", "missing"], + { argv = ["vp", "install", "--ignore-scripts"], snapshot = false }, + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "print-file", "templates/starter/package.json"], + ["vpt", "stat-file", "templates/starter/node_modules/vitest/package.json", "--assert", "file"], + { cwd = "templates/starter", argv = ["node", "--input-type=module", "-e", "import { test } from 'vitest'; console.log(typeof test);"] }, +] + +[[case]] +name = "migration_import_rule_preserved_dependency_owners" +vp = "local" +local-registry = true +comment = "An unmanaged template resolves Vitest from its workspace root, and a managed template retains its browser packages while the app uses Vite+." +steps = [ + { argv = ["vpt", "replace-file-content", "pnpm-workspace.yaml", "templates/*", "templates/starter"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "devDependencies.vitest", "^5.0.0"], snapshot = false }, + { argv = ["vpt", "write-file", "templates/unmanaged/package.json", "{\"name\":\"unmanaged-template\",\"private\":true}"], snapshot = false }, + { argv = ["vpt", "cp", "templates/starter/demo.test.ts", "templates/unmanaged/demo.test.ts"], snapshot = false }, + { argv = ["vpt", "json-edit", "templates/starter/package.json", "devDependencies.@vitest/browser", "^5.0.0"], snapshot = false }, + { argv = ["vpt", "json-edit", "templates/starter/package.json", "devDependencies.@vitest/browser-preview", "^5.0.0"], snapshot = false }, + { argv = ["vpt", "write-file", "templates/starter/browser.test.ts", "import { page } from '@vitest/browser/context';\nimport '@vitest/browser-preview';\nexport { page };\n"], snapshot = false }, + { argv = ["vpt", "json-edit", "packages/app/package.json", "devDependencies.@vitest/browser", "^5.0.0"], snapshot = false }, + { argv = ["vpt", "json-edit", "packages/app/package.json", "devDependencies.@vitest/browser-preview", "^5.0.0"], snapshot = false }, + { argv = ["vpt", "cp", "templates/starter/browser.test.ts", "packages/app/browser.test.ts"], snapshot = false }, + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "print-file", "templates/unmanaged/demo.test.ts", "package.json"], + ["vpt", "print-file", "templates/starter/browser.test.ts", "templates/starter/package.json"], + ["vpt", "print-file", "packages/app/demo.test.ts", "packages/app/browser.test.ts", "packages/app/package.json"], + { argv = ["vp", "install", "--ignore-scripts"], snapshot = false }, + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + { argv = ["vp", "install", "--frozen-lockfile", "--ignore-scripts"], snapshot = false }, + ["vpt", "stat-file", "node_modules/vitest/package.json", "templates/starter/node_modules/@vitest/browser/package.json", "templates/starter/node_modules/@vitest/browser-preview/package.json", "--assert", "file"], + ["vpt", "stat-file", "templates/unmanaged/node_modules/vitest/package.json", "packages/app/node_modules/@vitest/browser/package.json", "packages/app/node_modules/@vitest/browser-preview/package.json", "--assert", "missing"], + { cwd = "templates/unmanaged", argv = ["node", "--input-type=module", "-e", "import { statSync } from 'node:fs'; console.log(statSync(new URL(import.meta.resolve('vitest'))).isFile());"] }, + { cwd = "templates/starter", argv = ["node", "--input-type=module", "-e", "import { statSync } from 'node:fs'; for (const name of process.argv.slice(1)) console.log(name, statSync(new URL(import.meta.resolve(name))).isFile());", "@vitest/browser/context", "@vitest/browser-preview"] }, +] + +[[case]] +name = "migration_import_rule_tsdown_pack" +vp = "local" +local-registry = true +comment = "Both libraries build with vp pack after migration. The template keeps its Vitest import." +steps = [ + { argv = ["vpt", "json-edit", "templates/starter/package.json", "devDependencies.tsdown", "^0.23.0"], snapshot = false }, + { argv = ["vpt", "json-edit", "packages/app/package.json", "devDependencies.tsdown", "^0.23.0"], snapshot = false }, + { argv = ["vpt", "write-file", "templates/starter/tsdown.config.mjs", "import { defineConfig } from 'tsdown';\nexport default defineConfig({ entry: ['index.ts'], fixedExtension: true });\n"], snapshot = false }, + { argv = ["vpt", "cp", "templates/starter/tsdown.config.mjs", "packages/app/tsdown.config.mjs"], snapshot = false }, + { argv = ["vpt", "write-file", "templates/starter/index.ts", "export const answer = 42;\n"], snapshot = false }, + { argv = ["vpt", "cp", "templates/starter/index.ts", "packages/app/index.ts"], snapshot = false }, + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "print-file", "templates/starter/tsdown.config.mjs", "templates/starter/demo.test.ts"], + ["vpt", "print-file", "packages/app/tsdown.config.mjs", "packages/app/demo.test.ts"], + ["vpt", "stat-file", "templates/starter/node_modules", "packages/app/node_modules", "--assert", "missing"], + { argv = ["vp", "install", "--ignore-scripts"], snapshot = false }, + ["vpt", "stat-file", "templates/starter/node_modules/tsdown", "packages/app/node_modules/tsdown", "--assert", "missing"], + { cwd = "packages/app", argv = ["vp", "pack"], snapshot = false }, + ["vpt", "stat-file", "packages/app/dist/index.mjs", "--assert", "file"], + { cwd = "templates/starter", argv = ["vp", "pack"], snapshot = false }, + ["vpt", "stat-file", "templates/starter/dist/index.mjs", "--assert", "file"], +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/snapshots/migration_import_rule_preserved_dependency_owners.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/snapshots/migration_import_rule_preserved_dependency_owners.md new file mode 100644 index 0000000000..eb56b2a3e6 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/snapshots/migration_import_rule_preserved_dependency_owners.md @@ -0,0 +1,146 @@ +# migration_import_rule_preserved_dependency_owners + +An unmanaged template resolves Vitest from its workspace root, and a managed template retains its browser packages while the app uses Vite+. + +## `vpt replace-file-content pnpm-workspace.yaml templates/* templates/starter` + + +## `vpt json-edit package.json devDependencies.vitest ^5.0.0` + + +## `vpt write-file templates/unmanaged/package.json '{"name":"unmanaged-template","private":true}'` + + +## `vpt cp templates/starter/demo.test.ts templates/unmanaged/demo.test.ts` + + +## `vpt json-edit templates/starter/package.json devDependencies.@vitest/browser ^5.0.0` + + +## `vpt json-edit templates/starter/package.json devDependencies.@vitest/browser-preview ^5.0.0` + + +## `vpt write-file templates/starter/browser.test.ts 'import { page } from '\''@vitest/browser/context'\''; +import '\''@vitest/browser-preview'\''; +export { page }; +'` + + +## `vpt json-edit packages/app/package.json devDependencies.@vitest/browser ^5.0.0` + + +## `vpt json-edit packages/app/package.json devDependencies.@vitest/browser-preview ^5.0.0` + + +## `vpt cp templates/starter/browser.test.ts packages/app/browser.test.ts` + + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Migrated . to Vite+ +• Node pnpm +• 2 files had imports rewritten +``` + +## `vpt print-file templates/unmanaged/demo.test.ts package.json` + +``` +import { test } from 'vitest'; + +test('starter', () => {}); +{ + "devDependencies": { + "vitest": "catalog:", + "vite-plus": "catalog:" + }, + "name": "import-rule-workspace", + "packageManager": "pnpm@12.11.2", + "private": true, + "type": "module" +} +``` + +## `vpt print-file templates/starter/browser.test.ts templates/starter/package.json` + +``` +import { page } from '@vitest/browser/context'; +import '@vitest/browser-preview'; +export { page }; +{ + "devDependencies": { + "@vitest/browser": "catalog:", + "@vitest/browser-preview": "catalog:", + "vitest": "catalog:", + "vite-plus": "catalog:" + }, + "name": "starter", + "private": true, + "type": "module" +} +``` + +## `vpt print-file packages/app/demo.test.ts packages/app/browser.test.ts packages/app/package.json` + +``` +import { test } from 'vite-plus/test'; + +test('app', () => {}); +import { page } from 'vite-plus/test/browser/context'; +import 'vite-plus/test/browser-preview'; +export { page }; +{ + "devDependencies": { + "vitest": "catalog:", + "vite-plus": "catalog:" + }, + "name": "app", + "private": true, + "type": "module" +} +``` + +## `vp install --ignore-scripts` + + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +This project is already using Vite+! Happy coding! +``` + +## `vp install --frozen-lockfile --ignore-scripts` + + +## `vpt stat-file node_modules/vitest/package.json templates/starter/node_modules/@vitest/browser/package.json templates/starter/node_modules/@vitest/browser-preview/package.json --assert file` + +``` +node_modules/vitest/package.json: file +templates/starter/node_modules/@vitest/browser/package.json: file +templates/starter/node_modules/@vitest/browser-preview/package.json: file +``` + +## `vpt stat-file templates/unmanaged/node_modules/vitest/package.json packages/app/node_modules/@vitest/browser/package.json packages/app/node_modules/@vitest/browser-preview/package.json --assert missing` + +``` +templates/unmanaged/node_modules/vitest/package.json: missing +packages/app/node_modules/@vitest/browser/package.json: missing +packages/app/node_modules/@vitest/browser-preview/package.json: missing +``` + +## `cd templates/unmanaged && node --input-type=module -e 'import { statSync } from '\''node:fs'\''; console.log(statSync(new URL(import.meta.resolve('\''vitest'\''))).isFile());'` + +``` +true +``` + +## `cd templates/starter && node --input-type=module -e 'import { statSync } from '\''node:fs'\''; for (const name of process.argv.slice(1)) console.log(name, statSync(new URL(import.meta.resolve(name))).isFile());' @vitest/browser/context @vitest/browser-preview` + +``` +@vitest/browser/context true +@vitest/browser-preview true +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/snapshots/migration_import_rule_template_dependency.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/snapshots/migration_import_rule_template_dependency.md new file mode 100644 index 0000000000..4e65297ef1 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/snapshots/migration_import_rule_template_dependency.md @@ -0,0 +1,121 @@ +# migration_import_rule_template_dependency + +Only the package whose source still imports Vitest needs a direct Vitest dependency. + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Migrated . to Vite+ +• Node pnpm +• 1 file had imports rewritten +``` + +## `vpt print-file templates/starter/demo.test.ts` + +``` +import { test } from 'vitest'; + +test('starter', () => {}); +``` + +## `vpt print-file templates/starter/package.json` + +``` +{ + "name": "starter", + "private": true, + "type": "module", + "devDependencies": { + "vitest": "catalog:", + "vite-plus": "catalog:" + } +} +``` + +## `vpt print-file packages/app/demo.test.ts` + +``` +import { test } from 'vite-plus/test'; + +test('app', () => {}); +``` + +## `vpt print-file packages/app/package.json` + +``` +{ + "name": "app", + "private": true, + "type": "module", + "devDependencies": { + "vite-plus": "catalog:" + } +} +``` + +## `vpt print-file pnpm-workspace.yaml` + +``` +packages: + - templates/* + - packages/* +nodeLinker: isolated +hoist: false +catalog: + vite: npm:@voidzero-dev/vite-plus-core@ + vitest: + vite-plus: +overrides: + vite@*: 'catalog:' + vitest@*: 'catalog:' +peerDependencyRules: + allowAny: + - vitest + allowedVersions: + vitest: '*' +``` + +## `vpt stat-file templates/starter/node_modules --assert missing` + +``` +templates/starter/node_modules: missing +``` + +## `vp install --ignore-scripts` + + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +This project is already using Vite+! Happy coding! +``` + +## `vpt print-file templates/starter/package.json` + +``` +{ + "name": "starter", + "private": true, + "type": "module", + "devDependencies": { + "vitest": "catalog:", + "vite-plus": "catalog:" + } +} +``` + +## `vpt stat-file templates/starter/node_modules/vitest/package.json --assert file` + +``` +templates/starter/node_modules/vitest/package.json: file +``` + +## `cd templates/starter && node --input-type=module -e 'import { test } from '\''vitest'\''; console.log(typeof test);'` + +``` +function +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/snapshots/migration_import_rule_tsdown_pack.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/snapshots/migration_import_rule_tsdown_pack.md new file mode 100644 index 0000000000..283ca58a0c --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/snapshots/migration_import_rule_tsdown_pack.md @@ -0,0 +1,100 @@ +# migration_import_rule_tsdown_pack + +Both libraries build with vp pack after migration. The template keeps its Vitest import. + +## `vpt json-edit templates/starter/package.json devDependencies.tsdown ^0.23.0` + + +## `vpt json-edit packages/app/package.json devDependencies.tsdown ^0.23.0` + + +## `vpt write-file templates/starter/tsdown.config.mjs 'import { defineConfig } from '\''tsdown'\''; +export default defineConfig({ entry: ['\''index.ts'\''], fixedExtension: true }); +'` + + +## `vpt cp templates/starter/tsdown.config.mjs packages/app/tsdown.config.mjs` + + +## `vpt write-file templates/starter/index.ts 'export const answer = 42; +'` + + +## `vpt cp templates/starter/index.ts packages/app/index.ts` + + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Migrated . to Vite+ +• Node pnpm +• 4 config updates applied, 3 files had imports rewritten +→ Manual follow-up: + - Please manually merge packages/app/tsdown.config.mjs into packages/app/vite.config.ts, see https://viteplus.dev/guide/migrate#tsdown + - Please manually merge templates/starter/tsdown.config.mjs into templates/starter/vite.config.ts, see https://viteplus.dev/guide/migrate#tsdown +``` + +## `vpt print-file templates/starter/tsdown.config.mjs templates/starter/demo.test.ts` + +``` +import { defineConfig } from 'vite-plus/pack'; +export default defineConfig({ deps: { + // tsdown <0.23 compatibility: resolve external dependency subpaths. + // Remove to preserve subpath imports as written (the new default). + // https://tsdown.dev/options/dependencies#deps-resolvedepsubpath + resolveDepSubpath: true }, entry: ['index.ts'], fixedExtension: true }); +import { test } from 'vitest'; + +test('starter', () => {}); +``` + +## `vpt print-file packages/app/tsdown.config.mjs packages/app/demo.test.ts` + +``` +import { defineConfig } from 'vite-plus/pack'; +export default defineConfig({ deps: { + // tsdown <0.23 compatibility: resolve external dependency subpaths. + // Remove to preserve subpath imports as written (the new default). + // https://tsdown.dev/options/dependencies#deps-resolvedepsubpath + resolveDepSubpath: true }, entry: ['index.ts'], fixedExtension: true }); +import { test } from 'vite-plus/test'; + +test('app', () => {}); +``` + +## `vpt stat-file templates/starter/node_modules packages/app/node_modules --assert missing` + +``` +templates/starter/node_modules: missing +packages/app/node_modules: missing +``` + +## `vp install --ignore-scripts` + + +## `vpt stat-file templates/starter/node_modules/tsdown packages/app/node_modules/tsdown --assert missing` + +``` +templates/starter/node_modules/tsdown: missing +packages/app/node_modules/tsdown: missing +``` + +## `cd packages/app && vp pack` + + +## `vpt stat-file packages/app/dist/index.mjs --assert file` + +``` +packages/app/dist/index.mjs: file +``` + +## `cd templates/starter && vp pack` + + +## `vpt stat-file templates/starter/dist/index.mjs --assert file` + +``` +templates/starter/dist/index.mjs: file +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/templates/starter/demo.test.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/templates/starter/demo.test.ts new file mode 100644 index 0000000000..c41986f54a --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/templates/starter/demo.test.ts @@ -0,0 +1,3 @@ +import { test } from 'vitest'; + +test('starter', () => {}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/templates/starter/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/templates/starter/package.json new file mode 100644 index 0000000000..65b966eca5 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/templates/starter/package.json @@ -0,0 +1,6 @@ +{ + "name": "starter", + "private": true, + "type": "module", + "devDependencies": { "vitest": "^5.0.0" } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/vite.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/vite.config.ts new file mode 100644 index 0000000000..ac0e58de93 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_import_rule_template_dependency/vite.config.ts @@ -0,0 +1,9 @@ +export default { + lint: { + jsPlugins: ['vite-plus/oxlint-plugin'], + rules: { 'vite-plus/prefer-vite-plus-imports': 'error' }, + overrides: [ + { files: ['templates/**'], rules: { 'vite-plus/prefer-vite-plus-imports': 'off' } }, + ], + }, +}; diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/examples/starter/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/examples/starter/package.json new file mode 100644 index 0000000000..772d7f1641 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/examples/starter/package.json @@ -0,0 +1,14 @@ +{ + "name": "vite-starter", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "test": "vitest run" + }, + "devDependencies": { + "vite": "^8.0.0", + "vitest": "^4.1.11" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/examples/starter/src/example.test.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/examples/starter/src/example.test.ts new file mode 100644 index 0000000000..be9a49686b --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/examples/starter/src/example.test.ts @@ -0,0 +1,5 @@ +import { expect, test } from 'vitest'; + +test('starter', () => { + expect(1 + 1).toBe(2); +}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/examples/starter/tsconfig.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/examples/starter/tsconfig.json new file mode 100644 index 0000000000..9b63a9c44f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/examples/starter/tsconfig.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "types": ["vite/client", "vitest/globals"] + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/examples/starter/vite.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/examples/starter/vite.config.ts new file mode 100644 index 0000000000..c049f46e10 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/examples/starter/vite.config.ts @@ -0,0 +1,3 @@ +import { defineConfig } from 'vite'; + +export default defineConfig({}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/package.json new file mode 100644 index 0000000000..0b5804846a --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/package.json @@ -0,0 +1,15 @@ +{ + "name": "migration-workspace-vite-template", + "private": true, + "type": "module", + "devDependencies": { + "vite-plus": "catalog:" + }, + "devEngines": { + "packageManager": { + "name": "pnpm", + "version": "10.33.0", + "onFail": "download" + } + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/packages/app/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/packages/app/package.json new file mode 100644 index 0000000000..44e2883301 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/packages/app/package.json @@ -0,0 +1,11 @@ +{ + "name": "app", + "private": true, + "type": "module", + "scripts": { + "build": "vp build" + }, + "devDependencies": { + "vite-plus": "catalog:" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/packages/app/vite.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/packages/app/vite.config.ts new file mode 100644 index 0000000000..3210accbf9 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/packages/app/vite.config.ts @@ -0,0 +1,3 @@ +import { defineConfig } from 'vite-plus'; + +export default defineConfig({}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/pnpm-workspace.yaml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/pnpm-workspace.yaml new file mode 100644 index 0000000000..0f1b01f634 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/pnpm-workspace.yaml @@ -0,0 +1,8 @@ +packages: + - packages/* + - examples/* +catalog: + vite-plus: latest + vite: npm:@voidzero-dev/vite-plus-core@latest +overrides: + vite: 'catalog:' diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/snapshots.toml new file mode 100644 index 0000000000..33241f5b6c --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/snapshots.toml @@ -0,0 +1,14 @@ +[[case]] +name = "migration_workspace_vite_template" +vp = "local" +comment = "Without a lint override, migration rewrites template imports along with other workspace files." +steps = [ + { argv = ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], comment = "an ordinary upgrade rewrites template imports by default" }, + { argv = ["vpt", "print-file", "examples/starter/vite.config.ts"], comment = "the template's Vite import is converted to vite-plus" }, + { argv = ["vpt", "print-file", "examples/starter/src/example.test.ts"], comment = "the template's Vitest import is converted to vite-plus/test" }, + { argv = ["vpt", "print-file", "examples/starter/package.json"], comment = "record dependency and script changes that also affect standalone use" }, + { argv = ["vpt", "print-file", "examples/starter/tsconfig.json"], comment = "record related type-reference changes" }, + { argv = ["vpt", "print-file", "pnpm-workspace.yaml"], comment = "the template remains a workspace member and shares toolchain overrides" }, + { argv = ["vpt", "print-file", "packages/app/package.json"], comment = "control: the application continues to use Vite+" }, + ["vpt", "print-file", "packages/app/vite.config.ts"], +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/snapshots/migration_workspace_vite_template.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/snapshots/migration_workspace_vite_template.md new file mode 100644 index 0000000000..28587cbef0 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_workspace_vite_template/snapshots/migration_workspace_vite_template.md @@ -0,0 +1,130 @@ +# migration_workspace_vite_template + +Without a lint override, migration rewrites template imports along with other workspace files. + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +an ordinary upgrade rewrites template imports by default + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Updated . to Vite+ +• Node pnpm +• Dependencies: + vite-plus latest → + vite → +• 2 files had imports rewritten +• Package manager settings configured +``` + +## `vpt print-file examples/starter/vite.config.ts` + +the template's Vite import is converted to vite-plus + +``` +import { defineConfig } from 'vite-plus'; + +export default defineConfig({ + test: { + // Vitest v4 compatibility: preserve mock call history. + // Remove after tests no longer rely on calls from setup or earlier tests. + // https://viteplus.dev/guide/vitest-v5#remove-unneeded-compatibility-settings + // https://vitest.dev/guide/migration/#clearmocks-is-enabled-by-default + clearMocks: false + } +}); +``` + +## `vpt print-file examples/starter/src/example.test.ts` + +the template's Vitest import is converted to vite-plus/test + +``` +import { expect, test } from 'vite-plus/test'; + +test('starter', () => { + expect(1 + 1).toBe(2); +}); +``` + +## `vpt print-file examples/starter/package.json` + +record dependency and script changes that also affect standalone use + +``` +{ + "name": "vite-starter", + "private": true, + "type": "module", + "scripts": { + "dev": "vp dev", + "build": "vp build", + "test": "vp test run" + }, + "devDependencies": { + "vite": "catalog:", + "vitest": "catalog:" + } +} +``` + +## `vpt print-file examples/starter/tsconfig.json` + +record related type-reference changes + +``` +{ + "compilerOptions": { + "types": ["vite/client", "vitest/globals"] + } +} +``` + +## `vpt print-file pnpm-workspace.yaml` + +the template remains a workspace member and shares toolchain overrides + +``` +packages: + - packages/* + - examples/* +catalog: + vite-plus: + vite: npm:@voidzero-dev/vite-plus-core@ + vitest: +overrides: + vite@*: 'catalog:' + vitest@*: 'catalog:' +peerDependencyRules: + allowAny: + - vitest + allowedVersions: + vitest: '*' +``` + +## `vpt print-file packages/app/package.json` + +control: the application continues to use Vite+ + +``` +{ + "name": "app", + "private": true, + "type": "module", + "scripts": { + "build": "vp build" + }, + "devDependencies": { + "vite-plus": "catalog:" + } +} +``` + +## `vpt print-file packages/app/vite.config.ts` + +``` +import { defineConfig } from 'vite-plus'; + +export default defineConfig({}); +``` diff --git a/crates/vp_migration/Cargo.toml b/crates/vp_migration/Cargo.toml index 7422188685..41f4970246 100644 --- a/crates/vp_migration/Cargo.toml +++ b/crates/vp_migration/Cargo.toml @@ -12,11 +12,13 @@ ast-grep-config = { workspace = true } ast-grep-core = { workspace = true } ast-grep-language = { workspace = true } brush-parser = { workspace = true } +fast-glob = { workspace = true } ignore = { workspace = true } js-semver = { workspace = true } oxc = { workspace = true } rayon = { workspace = true } regex = { workspace = true } +serde = { workspace = true } serde_json = { workspace = true, features = ["preserve_order"] } vp_error = { workspace = true, features = ["migration"] } vp_toolchain = { workspace = true } diff --git a/crates/vp_migration/src/file_walker.rs b/crates/vp_migration/src/file_walker.rs index 91585964f9..f67df0978a 100644 --- a/crates/vp_migration/src/file_walker.rs +++ b/crates/vp_migration/src/file_walker.rs @@ -82,9 +82,17 @@ pub fn is_directory_gitignored(root: &Path, directory: &Path) -> Result Result { + find_ts_files_filtered(root, |_| true) +} + +pub(crate) fn find_ts_files_filtered( + root: &Path, + include: impl Fn(&ignore::DirEntry) -> bool + Send + Sync + 'static, +) -> Result { let mut files = Vec::new(); let walker = WalkBuilder::new(root) + .filter_entry(include) .hidden(true) // Skip hidden files/dirs .git_ignore(true) // Respect .gitignore .git_global(true) // Respect global gitignore diff --git a/crates/vp_migration/src/import_rewriter.rs b/crates/vp_migration/src/import_rewriter.rs index da8643be9f..23dc8ac3af 100644 --- a/crates/vp_migration/src/import_rewriter.rs +++ b/crates/vp_migration/src/import_rewriter.rs @@ -1,16 +1,16 @@ use std::{ - collections::{HashMap, HashSet}, + collections::{BTreeMap, BTreeSet, HashMap, HashSet}, path::{Path, PathBuf}, sync::LazyLock, }; use ast_grep_config::RuleConfig; -use ast_grep_language::SupportLang; +use ast_grep_language::{LanguageExt, SupportLang}; use rayon::prelude::*; use regex::Regex; use vp_error::Error; -use crate::{ast_grep, file_walker, import_merge, pack_config}; +use crate::{ImportRuleConfig, ast_grep, file_walker, import_merge, pack_config}; /// ast-grep rules for rewriting vite imports and declare module statements /// @@ -270,7 +270,7 @@ fix: $NEW_IMPORT /// fails at runtime with `ERR_PACKAGE_PATH_NOT_EXPORTED`. The original /// specifier still resolves through the transitively-installed `vitest` /// dependency. -const REWRITE_VITEST_RULES: &str = r#"--- +const REWRITE_VITEST_CONFIG_RULES: &str = r#"--- id: rewrite-vitest-config-import language: TypeScript rule: @@ -344,7 +344,10 @@ transform: replace: vitest/config by: "vite-plus" fix: $NEW_IMPORT ---- +"#; + +// The dependency scan uses these same four import contexts for upstream packages. +const REWRITE_BARE_VITEST_RULES: &str = r#"--- id: rewrite-vitest-import language: TypeScript rule: @@ -418,7 +421,9 @@ transform: replace: vitest by: "vite-plus/test" fix: $NEW_IMPORT ---- +"#; + +const REWRITE_VITEST_BROWSER_AND_SUBPATH_RULES: &str = r#"--- id: rewrite-vitest-browser-import language: TypeScript rule: @@ -1578,13 +1583,13 @@ fn vitest_rewrite_rules() -> String { .map(|name| regex::escape(name)) .collect::>() .join("|"); - let generic = REWRITE_VITEST_RULES.replace( + let browser_and_subpaths = REWRITE_VITEST_BROWSER_AND_SUBPATH_RULES.replace( r#"regex: ^['"]vitest/.+['"]$"#, &format!(r#"regex: ^['"]vitest/({allowed})['"]$"#), ); // Exact public replacements run before the generic subpath rules. Each // generated rule retains the same AST context and Nuxt skip classification. - let template = REWRITE_VITEST_RULES + let template = REWRITE_VITEST_BROWSER_AND_SUBPATH_RULES .split("---\nid: rewrite-vitest-subpath-import") .nth(1) .expect("missing subpath rule template"); @@ -1616,7 +1621,9 @@ fn vitest_rewrite_rules() -> String { ); rules.push('\n'); } - rules.push_str(&generic); + rules.push_str(REWRITE_VITEST_CONFIG_RULES); + rules.push_str(REWRITE_BARE_VITEST_RULES); + rules.push_str(&browser_and_subpaths); rules } @@ -1637,12 +1644,26 @@ fn is_unscoped_vitest_rule(rule: &RuleConfig) -> bool { || rule.id.starts_with("rewrite-vitest-subpath-") } -static PARSED_UNSCOPED_VITEST_RULES: LazyLock>> = LazyLock::new(|| { - ast_grep::load_rules(&vitest_rewrite_rules()) - .expect("failed to parse vitest rewrite rules") - .into_iter() - .filter(is_unscoped_vitest_rule) - .collect() +fn has_unscoped_vitest_import(content: &str) -> bool { + let parsed = SupportLang::TypeScript.ast_grep(content); + let root = parsed.root(); + PARSED_VITEST_RULES + .iter() + .any(|rule| is_unscoped_vitest_rule(rule) && root.find(&rule.matcher).is_some()) +} + +const RETAINED_VITEST_DEPENDENCIES: [&str; 3] = + ["vitest", "@vitest/browser", "@vitest/browser-preview"]; + +// Reuse the import, re-export, require, and dynamic/type-import contexts from +// the bare Vitest rewrite. A preserved subpath needs its package regardless of +// whether Vite+ exports a corresponding shim for that particular entry point. +static RETAINED_VITEST_IMPORT_RULES: LazyLock>> = LazyLock::new(|| { + let rules = REWRITE_BARE_VITEST_RULES.replace( + r#"regex: ^['"]vitest['"]$"#, + &format!(r#"regex: ^['"](?:{})(?:/[^'"]+)?['"]$"#, RETAINED_VITEST_DEPENDENCIES.join("|")), + ); + ast_grep::load_rules(&rules).expect("failed to parse Vitest dependency import rules") }); static PARSED_VITEST_RULES_WITHOUT_UNSCOPED: LazyLock>> = @@ -1777,22 +1798,12 @@ fn apply_regex_replace(content: &mut String, re: &Regex, replacement: &str) -> b } } -/// Rewrite `/// ` directives in place. -/// -/// Only processes the file preamble (blank lines and comments before the first statement) -/// to match TypeScript semantics and avoid false positives inside string/template literals. -/// Allocates only for preamble lines, leaving the file body untouched. -/// Returns whether any changes were made. -fn rewrite_reference_types( - content: &mut String, - skip_packages: &SkipPackages, - preserve_unscoped_vitest: bool, - preserved_vitest: &mut bool, -) -> bool { +/// TypeScript only recognizes triple-slash reference directives in the file preamble. +fn reference_preamble(content: &str) -> &str { // Fast path: skip files with no triple-slash reference directives. // Check for "///" which covers all spacing variants (/// bool { + RE_REF_VITEST.is_match(line) || RE_REF_VITEST_SUBPATH.is_match(line) +} + +/// Rewrite triple-slash type references in the preamble, leaving the file body untouched. +fn rewrite_reference_types( + content: &mut String, + skip_packages: &SkipPackages, + preserve_unscoped_vitest: bool, + preserved_vitest: &mut bool, +) -> bool { + let preamble = reference_preamble(content); + let preamble_end = preamble.len(); // Check for "///" which covers all spacing variants (/// Option { None } +fn retained_vitest_dependency(specifier: &str) -> Option<&'static str> { + RETAINED_VITEST_DEPENDENCIES.into_iter().find(|name| { + specifier.strip_prefix(name).is_some_and(|rest| rest.is_empty() || rest.starts_with('/')) + }) +} + +fn collect_retained_vitest_dependencies(content: &str, dependencies: &mut BTreeSet<&'static str>) { + if !RETAINED_VITEST_DEPENDENCIES + .iter() + .any(|name| !dependencies.contains(name) && content.contains(name)) + { + return; + } + for line in reference_preamble(content).trim_start_matches('\u{feff}').lines() { + if let Some(captures) = RE_REF_TEST_ENTRY.captures(line) { + dependencies.extend(retained_vitest_dependency(&captures[2])); + } + } + let parsed = SupportLang::TypeScript.ast_grep(content); + let root = parsed.root(); + for rule in &*RETAINED_VITEST_IMPORT_RULES { + for matched in root.find_all(&rule.matcher) { + // A string in `export default 'vitest'` is a value, not a module source. + if rule.id == "rewrite-vitest-export" + && matched.parent().and_then(|export| export.field("source")).is_none() + { + continue; + } + dependencies + .extend(retained_vitest_dependency(matched.text().trim_matches(['\'', '"']))); + if dependencies.len() == RETAINED_VITEST_DEPENDENCIES.len() { + return; + } + } + } +} + +/// Group protected imports by their nearest manifest. The migration caller +/// can then determine which workspace package supplies each dependency. +pub fn find_retained_vitest_packages( + root: &Path, + import_rule: &ImportRuleConfig, +) -> Result>, Error> { + let mut owners = BTreeMap::new(); + if !import_rule.can_disable_rewrites() { + return Ok(owners); + } + + // An installed library's own test files cannot justify dependencies in the + // project being migrated, even when it has no .gitignore. + let sources = file_walker::find_ts_files_filtered(root, |entry| { + entry.depth() == 0 || entry.file_name() != "node_modules" + })?; + for path in sources.files { + if import_rule.is_enabled_for(root, &path) { + continue; + } + let Some(manifest) = find_nearest_package_json(&path, root) else { continue }; + let owner = manifest.parent().expect("package.json has a parent directory"); + let dependencies: &mut BTreeSet<_> = owners.entry(owner.to_path_buf()).or_default(); + if dependencies.len() == RETAINED_VITEST_DEPENDENCIES.len() { + continue; + } + let Ok(content) = std::fs::read_to_string(path) else { continue }; + collect_retained_vitest_dependencies(&content, dependencies); + } + owners.retain(|_, dependencies| !dependencies.is_empty()); + Ok(owners) +} + /// Canonical Vite/Vitest config entry basenames, the single source shared with /// the `prefer-vite-plus-imports` oxlint rule. The list lives in /// `packages/cli/src/vite-config-entry-basenames.json` and is embedded here at @@ -2317,7 +2411,14 @@ pub fn rewrite_imports_in_directory_with_options( let results: Vec<(PathBuf, FileResult, bool)> = files_with_context .into_par_iter() .map(|(file_path, package_context)| { - let skip_packages = package_context.skip_packages; + let mut skip_packages = package_context.skip_packages; + // The lint rule covers Vite, Vitest, and Oxlint plugin imports. + // Migration handles tsdown independently when it moves projects to vp pack. + if !options.import_rule.is_enabled_for(root, &file_path) { + skip_packages.skip_vite = true; + skip_packages.skip_vitest = true; + skip_packages.skip_oxlint = true; + } if skip_packages.all_skipped() { return (file_path, FileResult::Unchanged(Vec::new()), false); } @@ -2505,9 +2606,7 @@ fn rewrite_import_content_full( // Apply vitest rules if not skipped (using pre-parsed rules) if !skip_packages.skip_vitest { let vitest_rules = if preserve_unscoped_vitest { - let upstream_rewrite = - ast_grep::apply_loaded_rules(&new_content, &PARSED_UNSCOPED_VITEST_RULES); - preserved_vitest = upstream_rewrite != new_content; + preserved_vitest = has_unscoped_vitest_import(&new_content); &*PARSED_VITEST_RULES_WITHOUT_UNSCOPED } else { &*PARSED_VITEST_RULES @@ -2580,6 +2679,128 @@ mod tests { std::fs::write(file, content).unwrap(); } + #[test] + fn finds_only_owners_of_vitest_imports_retained_by_the_rule() { + let temp = tempdir().unwrap(); + let root = temp.path(); + let config = ImportRuleConfig::from_json( + r#"{ + "enabled": true, + "overrides": [ + { "files": ["./templates/**"], "excludeFiles": [], "enabled": false }, + { "files": ["templates/managed/**"], "excludeFiles": [], "enabled": true } + ] + }"#, + ) + .unwrap(); + write_pack_fixture(root, "package.json", "{}"); + write_pack_fixture(root, "app.ts", "import 'vitest';"); + // Both source files in templates/static contribute to the same package. + write_pack_fixture( + root, + "templates/static/src/browser.ts", + "import '@vitest/browser/context';\nimport '@vitest/browser-preview/provider';", + ); + let vitest = &["vitest"]; + let browser = &["@vitest/browser"]; + let preview = &["@vitest/browser-preview"]; + let combined: &[&str] = &["vitest", "@vitest/browser", "@vitest/browser-preview"]; + let mut expected = BTreeMap::new(); + for (package, source, dependencies) in [ + ("static", "import { test } from 'vitest';", combined), + ("export", "export type { TestProject } from 'vitest/node';", vitest), + ("require", "const config = require('vitest/config');", vitest), + ("dynamic", "const tests = import('vitest');", vitest), + ("type", "type V = typeof import('vitest');", vitest), + ("directive", "/// ", vitest), + ("managed", "import 'vitest';", &[]), + ("scoped", "import '@vitest/browser';", browser), + ("context", "export { page } from '@vitest/browser/context';", browser), + ("browser_type", "type Browser = typeof import('@vitest/browser/matchers');", browser), + ("browser_require", "const browser = require('@vitest/browser/client');", browser), + ("browser_reference", "/// ", browser), + ("preview", "import { preview } from '@vitest/browser-preview';", preview), + ( + "preview_context", + "const context = import('@vitest/browser-preview/context');", + preview, + ), + ( + "preview_reference", + "/// ", + preview, + ), + ("browser_direct_provider", "import '@vitest/browser-playwright';", &[]), + ("preview_prefix", "import '@vitest/browser-preview-extra/context';", &[]), + ( + "preview_reference_prefix", + "/// ", + &[], + ), + ("browser_text", "const example = \"import('@vitest/browser/context')\";", &[]), + ("export_value", "export default '@vitest/browser';", &[]), + ("text", "// import 'vitest';\nconst example = \"import('vitest')\";", &[]), + ] { + let dir = root.join("templates").join(package); + write_pack_fixture(&dir, "package.json", "{}"); + write_pack_fixture(&dir, "src/test.ts", source); + if !dependencies.is_empty() { + expected.insert(dir, dependencies.iter().copied().collect()); + } + } + assert_eq!(find_retained_vitest_packages(root, &config).unwrap(), expected); + } + + #[test] + fn scans_project_sources_but_skips_installed_packages_with_no_gitignore() { + let temp = tempdir().unwrap(); + let root = temp.path().join("node_modules/project"); + write_pack_fixture(&root, "package.json", "{}"); + write_pack_fixture(&root, "test.ts", "import 'vitest';"); + write_pack_fixture(&root, "node_modules/library/package.json", "{}"); + write_pack_fixture(&root, "node_modules/library/test.ts", "import '@vitest/browser';"); + + let config = ImportRuleConfig::from_json(r#"{"enabled": false, "overrides": []}"#).unwrap(); + assert_eq!( + find_retained_vitest_packages(&root, &config).unwrap(), + BTreeMap::from([(root, BTreeSet::from(["vitest"]))]) + ); + } + + #[test] + fn disabled_import_rule_keeps_the_independent_tsdown_rewrites() { + let temp = tempdir().unwrap(); + let root = temp.path(); + let source = r#"/// +/// +import { defineConfig } from 'vite'; +import { test } from 'vitest'; +import { definePlugin } from '@oxlint/plugins'; +import { defineConfig as pack } from 'tsdown'; +"#; + write_pack_fixture(root, "package.json", r#"{"devDependencies":{"tsdown":"*"}}"#); + write_pack_fixture(root, "vite.config.mjs", source); + write_pack_fixture(root, "plugin/package.json", r#"{"peerDependencies":{"tsdown":"*"}}"#); + write_pack_fixture(root, "plugin/vite.config.mjs", source); + + let result = rewrite_imports_in_directory_with_options( + root, + RewriteImportsOptions { + import_rule: ImportRuleConfig::from_json(r#"{"enabled":false,"overrides":[]}"#) + .unwrap(), + ..RewriteImportsOptions::default() + }, + ) + .unwrap(); + + assert_eq!(result.modified_files, [root.join("vite.config.mjs")]); + assert_eq!( + std::fs::read_to_string(root.join("vite.config.mjs")).unwrap(), + source.replace("tsdown", "vite-plus/pack") + ); + assert_eq!(std::fs::read_to_string(root.join("plugin/vite.config.mjs")).unwrap(), source); + } + fn write_tsdown_fixture(root: &Path, version: &str) { write_pack_fixture( root, diff --git a/crates/vp_migration/src/import_rule.rs b/crates/vp_migration/src/import_rule.rs new file mode 100644 index 0000000000..8939fcc41e --- /dev/null +++ b/crates/vp_migration/src/import_rule.rs @@ -0,0 +1,106 @@ +use std::path::Path; + +use serde::Deserialize; +use vp_error::Error; + +/// The import rule's settings, with inherited configs flattened by the JS caller. +#[derive(Debug, Clone, Deserialize)] +pub struct ImportRuleConfig { + enabled: bool, + overrides: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +struct ImportRuleOverride { + files: Vec, + exclude_files: Vec, + enabled: bool, +} + +impl Default for ImportRuleConfig { + fn default() -> Self { + Self { enabled: true, overrides: Vec::new() } + } +} + +impl ImportRuleConfig { + pub fn from_json(json: &str) -> Result { + let mut config: Self = serde_json::from_str(json)?; + for entry in &mut config.overrides { + for pattern in entry.files.iter_mut().chain(&mut entry.exclude_files) { + fast_glob::validate(pattern.as_str()).map_err(|error| { + Error::InvalidArgument(format!("Invalid lint glob {pattern:?}: {error}").into()) + })?; + // Match Oxlint's GlobSet: bare names match at every depth, while + // ./ anchors a pattern to the config directory. These are glob + // patterns, not gitignore rules. + if let Some(relative) = pattern.strip_prefix("./") { + *pattern = relative.to_string(); + } else if !pattern.contains('/') { + *pattern = format!("**/{pattern}"); + } + } + } + Ok(config) + } + + pub(crate) fn can_disable_rewrites(&self) -> bool { + !self.enabled || self.overrides.iter().any(|entry| !entry.enabled) + } + + pub(crate) fn is_enabled_for(&self, root: &Path, path: &Path) -> bool { + if self.overrides.is_empty() { + return self.enabled; + } + let path = path.strip_prefix(root).unwrap_or(path).to_string_lossy().replace('\\', "/"); + let matches_path = |pattern: &String| fast_glob::glob_match(pattern, &path); + self.overrides + .iter() + .rfind(|entry| { + entry.files.iter().any(matches_path) + && !entry.exclude_files.iter().any(matches_path) + }) + .map_or(self.enabled, |entry| entry.enabled) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_oxlint_globs_and_applies_overrides_in_order() { + let config = ImportRuleConfig::from_json(r#"{ + "enabled": true, + "overrides": [ + { "files": ["templates/**", "*.test.ts"], "excludeFiles": ["templates/keep/**"], "enabled": false }, + { "files": ["./root.test.ts", "templates/managed/**/*.{ts,tsx}"], "excludeFiles": [], "enabled": true } + ] + }"#).unwrap(); + for (path, enabled) in [ + ("app.ts", true), + ("templates/starter/vite.config.ts", false), + ("templates/keep/vite.config.ts", true), + ("templates/managed/test.tsx", true), + ("deep/unit.test.ts", false), + ("root.test.ts", true), + ("deep/root.test.ts", false), + (r"templates\starter\vite.config.ts", false), + ] { + let root = Path::new("project"); + assert_eq!(config.is_enabled_for(root, &root.join(path)), enabled, "{path}"); + } + } + + #[test] + fn rejects_invalid_patterns() { + let result = ImportRuleConfig::from_json( + r#"{ + "enabled": true, + "overrides": [{ "files": ["src/*.{ts"], "excludeFiles": [], "enabled": false }] + }"#, + ); + assert!(result.unwrap_err().to_string().contains("Invalid lint glob")); + } +} diff --git a/crates/vp_migration/src/lib.rs b/crates/vp_migration/src/lib.rs index 00ced33720..ac7a69dd3f 100644 --- a/crates/vp_migration/src/lib.rs +++ b/crates/vp_migration/src/lib.rs @@ -11,6 +11,7 @@ mod eslint; mod file_walker; mod import_merge; mod import_rewriter; +mod import_rule; mod pack_config; mod package; mod prettier; @@ -22,9 +23,10 @@ mod vite_config; pub use file_walker::{WalkResult, find_ts_files, is_directory_gitignored}; pub use import_rewriter::{ - BatchRewriteResult, RewriteImportsOptions, rewrite_imports_in_directory, - rewrite_imports_in_directory_with_options, + BatchRewriteResult, RewriteImportsOptions, find_retained_vitest_packages, + rewrite_imports_in_directory, rewrite_imports_in_directory_with_options, }; +pub use import_rule::ImportRuleConfig; pub use package::{rewrite_eslint, rewrite_prettier, rewrite_scripts}; pub use shell_command::{LiteralCommandToken, parse_literal_commands}; pub use source_analysis::analyze_migration_source; diff --git a/crates/vp_static_config/src/lib.rs b/crates/vp_static_config/src/lib.rs index d79c2d1a06..9d96a30d6a 100644 --- a/crates/vp_static_config/src/lib.rs +++ b/crates/vp_static_config/src/lib.rs @@ -18,7 +18,8 @@ use rustc_hash::FxHashMap; use vt_path::AbsolutePath; /// Packages whose `defineConfig` helpers preserve top-level config fields. -const TRUSTED_DEFINE_CONFIG_PACKAGES: &[&str] = &["vite-plus", "vite"]; +const TRUSTED_DEFINE_CONFIG_PACKAGES: &[&str] = + &["vite-plus", "vite", "vitest/config", "vite-plus/test/config"]; /// The name of the config helper static extraction trusts. const DEFINE_CONFIG: &str = "defineConfig"; @@ -173,11 +174,18 @@ fn extract_config_fields(program: &Program<'_>) -> FieldMap { for stmt in &program.body { // ESM: export default ... if let Statement::ExportDefaultDeclaration(decl) = stmt { - if let Some(expr) = decl.declaration.as_expression() { - return extract_config_from_expr(expr, has_trusted_define_config_binding); + let Some(expr) = decl.declaration.as_expression() else { + // export default class/function — not analyzable + return FieldMap::unanalyzable(); + }; + if let Expression::Identifier(id) = expr.get_inner_expression() { + return extract_exported_const( + program, + id.name.as_str(), + has_trusted_define_config_binding, + ); } - // export default class/function — not analyzable - return FieldMap::unanalyzable(); + return extract_config_from_expr(expr, has_trusted_define_config_binding); } // CJS: module.exports = ... @@ -195,6 +203,36 @@ fn extract_config_fields(program: &Program<'_>) -> FieldMap { FieldMap::unanalyzable() } +// A config can be assigned to a const before exporting it. Only accept the +// imports/declaration/export shape: other statements could mutate that object +// or pass it to code that does, so those require normal runtime resolution. +fn extract_exported_const( + program: &Program<'_>, + name: &str, + has_trusted_define_config_binding: bool, +) -> FieldMap { + let mut initializer = None; + for stmt in &program.body { + match stmt { + Statement::ImportDeclaration(_) | Statement::ExportDefaultDeclaration(_) => {} + Statement::VariableDeclaration(decl) + if decl.kind == VariableDeclarationKind::Const && decl.declarations.len() == 1 => + { + let declarator = &decl.declarations[0]; + if !matches!(&declarator.id, BindingPattern::BindingIdentifier(id) if id.name == name) + { + return FieldMap::unanalyzable(); + } + initializer = declarator.init.as_ref(); + } + _ => return FieldMap::unanalyzable(), + } + } + initializer.map_or_else(FieldMap::unanalyzable, |expr| { + extract_config_from_expr(expr, has_trusted_define_config_binding) + }) +} + /// Extract the config object from an expression that is either: /// - `defineConfig({ ... })` → extract the object argument /// - `defineConfig(() => ({ ... }))` → extract from arrow function expression body @@ -752,6 +790,52 @@ mod tests { assert_non_static(&result, "run"); } + #[test] + fn vitest_config_preserves_lint_fields_without_evaluating_plugins() { + for import in [ + "import { defineConfig } from 'vitest/config';", + "import { defineConfig } from 'vite-plus/test/config';", + ] { + let source = [ + import, + "export default defineConfig({ + plugins: [plugin()], + lint: { rules: { 'vite-plus/prefer-vite-plus-imports': 'off' } }, + });", + ] + .join("\n"); + let result = parse(&source); + assert_json( + &result, + "lint", + serde_json::json!({ "rules": { "vite-plus/prefer-vite-plus-imports": "off" } }), + ); + assert!(result.get("run").is_none()); + } + } + + #[test] + fn exported_const_config_is_static_only_without_possible_mutations() { + let source = "import { defineConfig } from 'vitest/config'; + const config = defineConfig({ lint: { rules: { 'vite-plus/prefer-vite-plus-imports': 'off' } } });"; + let result = parse(&[source, "export default config;"].join("\n")); + assert_json( + &result, + "lint", + serde_json::json!({ "rules": { "vite-plus/prefer-vite-plus-imports": "off" } }), + ); + assert!(result.get("run").is_none()); + for mutation in [ + "config.lint = {};", + "Object.assign(config, other);", + "const changed = mutate(config);", + ] { + let result = parse(&[source, mutation, "export default config;"].join("\n")); + assert_non_static(&result, "lint"); + } + assert_non_static(&parse("let config = {}; export default config;"), "lint"); + } + #[test] fn define_config_type_import_from_vite_plus_is_non_static() { let result = parse( diff --git a/docs/guide/migrate-rules.md b/docs/guide/migrate-rules.md index 2d77f0c1ff..b32ecf636e 100644 --- a/docs/guide/migrate-rules.md +++ b/docs/guide/migrate-rules.md @@ -187,7 +187,7 @@ Packages that are **not** aligned: - `@vitest/coverage-c8` stopped at an older release and has no Vitest 4 version; and - third-party `vitest-*` integrations keep their own compatible versions, though their required Vitest peer may still trigger [direct provisioning](#when-vitest-is-directly-required). -For browser mode, Vite+ bundles the base `@vitest/browser` runtime and `@vitest/browser-preview`; migration removes their direct dependency entries. The Playwright provider stays opt-in. Migration uses the bundled Vitest version for `@vitest/browser-playwright`, through the preferred toolchain catalog or the dependency entry, and installs its `playwright` peer alongside. +For browser mode, Vite+ bundles the base `@vitest/browser` runtime and `@vitest/browser-preview`. Migration keeps a declaration for either package if a preserved import uses it. For example, an import from `@vitest/browser/context` needs `@vitest/browser`. Otherwise, migration removes these bundled packages from the project's direct dependencies. The Playwright provider stays opt-in. Migration uses the bundled Vitest version for `@vitest/browser-playwright`, through the preferred toolchain catalog or the dependency entry, and installs its `playwright` peer alongside. Migration detects Playwright usage before it rewrites imports, including legacy `vitest/browser-playwright`, `vitest/browser/providers/playwright`, and `vitest/plugins/browser-playwright` aliases. @@ -197,6 +197,11 @@ Object-valued nested npm and Bun overrides are preserved: they are user-defined ## Source Rewrite Rules +Migration skips Vite and Vitest import rewrites in files where the root lint +config disables `vite-plus/prefer-vite-plus-imports`. If a template outside the +workspace relies on an ancestor's dependency for a preserved Vitest import, +migration keeps that declaration. See [Keeping upstream imports in templates and examples](./migrate.md#keeping-upstream-imports-in-templates-and-examples). + ### `vite` Imports `vite` and `vite/*` imports are rewritten to `vite-plus` **only in config entry files**: `vite.config.*`, `vitest.config.*`, and any config file the migration resolved. Every other file keeps its `vite` imports, for two reasons: diff --git a/docs/guide/migrate.md b/docs/guide/migrate.md index 59cb22fb93..c72c413f72 100644 --- a/docs/guide/migrate.md +++ b/docs/guide/migrate.md @@ -61,6 +61,29 @@ Most projects will require further manual adjustments after running `vp migrate` For the Vitest v5 upgrade, read the [compatibility settings and review checklist](./vitest-v5.md) and the [upstream Vitest migration guide](https://vitest.dev/guide/migration/). The preflight checks your original runner version and Node runtime before dependency updates. Keep the original lockfile available and resolve blocking findings before retrying. +### Keeping upstream imports in templates and examples + +If your root `vite.config.ts` enables `vite-plus/prefer-vite-plus-imports`, add +this entry to `lint.overrides` to keep `vite` and `vitest` imports in templates +and examples. + +```json +{ + "files": ["templates/**", "examples/**"], + "rules": { "vite-plus/prefer-vite-plus-imports": "off" } +} +``` + +`vp migrate`, `vp lint --fix`, and `vp check --fix` all use this override for +Vite and Vitest import rewrites. Oxlint matches the file patterns relative to +the root config directory. A later matching override can re-enable the rule. + +Migration keeps the dependencies that supply preserved `vitest`, +`@vitest/browser`, and `@vitest/browser-preview` imports. If a template outside +the workspace imports `vitest` from the root project, the root keeps its dependency. +When migration removes a `tsdown` development dependency, it still rewrites +imports from `tsdown` to `vite-plus/pack`. + ## Recommended Workflow Before running the migration: diff --git a/packages/cli/binding/index.cjs b/packages/cli/binding/index.cjs index f7606a065d..2ab13da6a9 100644 --- a/packages/cli/binding/index.cjs +++ b/packages/cli/binding/index.cjs @@ -1109,6 +1109,7 @@ module.exports.documentationUrl = nativeBinding.documentationUrl; module.exports.downloadPackageManager = nativeBinding.downloadPackageManager; module.exports.ensureBlockingStdio = nativeBinding.ensureBlockingStdio; module.exports.findMonorepoRoot = nativeBinding.findMonorepoRoot; +module.exports.findRetainedVitestPackages = nativeBinding.findRetainedVitestPackages; module.exports.getPackageManagerOverride = nativeBinding.getPackageManagerOverride; module.exports.getVpDirs = nativeBinding.getVpDirs; module.exports.hasConfigKey = nativeBinding.hasConfigKey; @@ -1122,6 +1123,7 @@ module.exports.parseHooksArgs = nativeBinding.parseHooksArgs; module.exports.parseLiteralCommands = nativeBinding.parseLiteralCommands; module.exports.parseMigrateArgs = nativeBinding.parseMigrateArgs; module.exports.parseStagedArgs = nativeBinding.parseStagedArgs; +module.exports.readStaticLintConfig = nativeBinding.readStaticLintConfig; module.exports.removeConfigKey = nativeBinding.removeConfigKey; module.exports.resolveNpmAuthorization = nativeBinding.resolveNpmAuthorization; module.exports.resolveNpmRegistry = nativeBinding.resolveNpmRegistry; diff --git a/packages/cli/binding/index.d.cts b/packages/cli/binding/index.d.cts index 93b5539778..be8f28a957 100644 --- a/packages/cli/binding/index.d.cts +++ b/packages/cli/binding/index.d.cts @@ -3813,6 +3813,12 @@ export declare function ensureBlockingStdio(): void; */ export declare function findMonorepoRoot(cwd: string): string | null; +/** Upstream Vitest and browser imports preserved in files under each manifest. */ +export declare function findRetainedVitestPackages( + root: string, + importRuleConfig: string, +): Array; + /** Read the same `VP_PACKAGE_MANAGER` override used by `vp install`. */ export declare function getPackageManagerOverride(): PackageManagerOverride | null; @@ -4010,6 +4016,9 @@ export interface PathAccess { readDir: boolean; } +/** JSON for a static lint block; undefined requests normal config resolution. */ +export declare function readStaticLintConfig(root: string): string | null; + /** Remove a top-level key from a recognized Vite config object. */ export declare function removeConfigKey( viteConfigPath: string, @@ -4022,6 +4031,11 @@ export declare function resolveNpmAuthorization(cwd: string, url: string): strin /** Resolve the npm registry for packages in `scope` (without `@`) from the npm config at `cwd`. */ export declare function resolveNpmRegistry(cwd: string, scope?: string | undefined | null): string; +export interface RetainedVitestPackage { + packageDir: string; + dependencies: Array; +} + /** * Rewrite ESLint scripts: rename `eslint` → `vp lint` and strip ESLint-only flags. * @@ -4071,6 +4085,7 @@ export declare function rewriteImportsInDirectory( root: string, preserveVitestInNuxtPackages?: boolean | undefined | null, oxlintOwnerDirs?: Array | undefined | null, + importRuleConfig?: string | undefined | null, ): BatchRewriteResult; /** diff --git a/packages/cli/binding/src/migration.rs b/packages/cli/binding/src/migration.rs index aa0901e775..d43ec08d38 100644 --- a/packages/cli/binding/src/migration.rs +++ b/packages/cli/binding/src/migration.rs @@ -2,6 +2,44 @@ use std::path::Path; use napi::{anyhow, bindgen_prelude::*}; use napi_derive::napi; +use vp_migration::ImportRuleConfig; + +/// JSON for a static lint block; undefined requests normal config resolution. +#[napi] +pub fn read_static_lint_config(root: String) -> Result> { + let root = vt_path::AbsolutePathBuf::new(root.into()) + .ok_or_else(|| Error::from_reason("Migration root must be absolute"))?; + Ok(match vp_static_config::resolve_static_config(&root).get("lint") { + Some(vp_static_config::FieldValue::Json(value)) => Some(value.to_string()), + Some(vp_static_config::FieldValue::NonStatic) => None, + None => Some("null".to_string()), + }) +} + +#[napi(object)] +pub struct RetainedVitestPackage { + pub package_dir: String, + pub dependencies: Vec, +} + +/// Upstream Vitest and browser imports preserved in files under each manifest. +#[napi] +pub fn find_retained_vitest_packages( + root: String, + import_rule_config: String, +) -> Result> { + let import_rule = + ImportRuleConfig::from_json(&import_rule_config).map_err(anyhow::Error::from)?; + let owners = vp_migration::find_retained_vitest_packages(Path::new(&root), &import_rule) + .map_err(anyhow::Error::from)?; + Ok(owners + .into_iter() + .map(|(dir, dependencies)| RetainedVitestPackage { + package_dir: dir.to_string_lossy().into_owned(), + dependencies: dependencies.into_iter().map(str::to_owned).collect(), + }) + .collect()) +} /// A literal argument with its original JavaScript UTF-16 source range. #[napi(object)] @@ -367,10 +405,16 @@ pub fn rewrite_imports_in_directory( root: String, preserve_vitest_in_nuxt_packages: Option, oxlint_owner_dirs: Option>, + import_rule_config: Option, ) -> Result { + let import_rule = match import_rule_config.as_deref() { + Some(json) => ImportRuleConfig::from_json(json).map_err(anyhow::Error::from)?, + None => ImportRuleConfig::default(), + }; let result = vp_migration::rewrite_imports_in_directory_with_options( Path::new(&root), vp_migration::RewriteImportsOptions { + import_rule, preserve_vitest_in_nuxt_packages: preserve_vitest_in_nuxt_packages.unwrap_or(false), oxlint_owner_dirs: oxlint_owner_dirs .unwrap_or_default() diff --git a/packages/cli/src/migration/__tests__/compat-runner.spec.ts b/packages/cli/src/migration/__tests__/compat-runner.spec.ts index 1a4ad461fd..0cabb19eb2 100644 --- a/packages/cli/src/migration/__tests__/compat-runner.spec.ts +++ b/packages/cli/src/migration/__tests__/compat-runner.spec.ts @@ -5,24 +5,33 @@ vi.mock('../../utils/command.ts', () => ({ })); import { runCommandSilently } from '../../utils/command.ts'; -import { checkRolldownCompatibility, ROLLDOWN_COMPAT_RESULT_PREFIX } from '../compat/runner.ts'; +import { LINT_CONFIG_RESULT_PREFIX } from '../compat/protocol.ts'; +import { + checkRolldownCompatibility, + readLintConfigInWorker, + ROLLDOWN_COMPAT_RESULT_PREFIX, +} from '../compat/runner.ts'; import { createMigrationReport } from '../report.ts'; const mockRunCommandSilently = vi.mocked(runCommandSilently); -describe('checkRolldownCompatibility', () => { - beforeEach(() => { - mockRunCommandSilently.mockReset(); +function mockWorkerOutput(stdout: string, exitCode = 0): void { + mockRunCommandSilently.mockResolvedValue({ + exitCode, + stdout: Buffer.from(stdout), + stderr: Buffer.alloc(0), }); +} + +beforeEach(() => { + mockRunCommandSilently.mockReset(); +}); +describe('checkRolldownCompatibility', () => { it('merges warnings returned by the isolated config worker', async () => { - mockRunCommandSilently.mockResolvedValue({ - exitCode: 0, - stdout: Buffer.from( - `project config output\n${ROLLDOWN_COMPAT_RESULT_PREFIX}${JSON.stringify({ warnings: ['manualChunks warning'] })}\n`, - ), - stderr: Buffer.alloc(0), - }); + mockWorkerOutput( + `project config output\n${ROLLDOWN_COMPAT_RESULT_PREFIX}{"warnings":["manualChunks warning"]}\n`, + ); const report = createMigrationReport(); await checkRolldownCompatibility('/project', report); @@ -48,13 +57,7 @@ describe('checkRolldownCompatibility', () => { }); it('skips compatibility checking when project config crashes the worker', async () => { - mockRunCommandSilently.mockResolvedValue({ - exitCode: 7, - stdout: Buffer.from( - `${ROLLDOWN_COMPAT_RESULT_PREFIX}${JSON.stringify({ warnings: ['incomplete result'] })}\n`, - ), - stderr: Buffer.from('project config crashed'), - }); + mockWorkerOutput(`${ROLLDOWN_COMPAT_RESULT_PREFIX}{"warnings":["incomplete result"]}\n`, 7); const report = createMigrationReport(); await expect(checkRolldownCompatibility('/project', report)).resolves.toBeUndefined(); @@ -69,3 +72,40 @@ describe('checkRolldownCompatibility', () => { expect(report.warnings).toEqual([]); }); }); + +describe('readLintConfigInWorker', () => { + it.each([null, { rules: { 'vite-plus/prefer-vite-plus-imports': 'off' } }])( + 'reads lint metadata %j after project output', + async (lint) => { + mockWorkerOutput(`project output\n${LINT_CONFIG_RESULT_PREFIX}${JSON.stringify({ lint })}\n`); + expect(await readLintConfigInWorker('/project')).toEqual(lint ?? undefined); + expect(mockRunCommandSilently).toHaveBeenCalledWith({ + command: process.execPath, + args: [expect.stringMatching(/migration[/\\]compat[/\\]worker\.js$/), '/project', 'lint'], + cwd: '/project', + envs: process.env, + timeoutMs: 30_000, + }); + }, + ); + + it('rejects a crashed worker even if it emitted metadata', async () => { + mockWorkerOutput(`${LINT_CONFIG_RESULT_PREFIX}{"lint":null}\n`, 7); + await expect(readLintConfigInWorker('/project')).rejects.toThrow('exited with code 7'); + }); + + it.each(['', '{', '{}', '{"lint":[]}'])( + 'rejects missing or invalid metadata %j', + async (json) => { + mockWorkerOutput(json ? `${LINT_CONFIG_RESULT_PREFIX}${json}\n` : ''); + await expect(readLintConfigInWorker('/project')).rejects.toThrow( + 'did not return lint metadata', + ); + }, + ); + + it.each(['spawn failed', 'Command timed out'])('reports worker failure: %s', async (message) => { + mockRunCommandSilently.mockRejectedValue(new Error(message)); + await expect(readLintConfigInWorker('/project')).rejects.toThrow(message); + }); +}); diff --git a/packages/cli/src/migration/__tests__/import-rule.spec.ts b/packages/cli/src/migration/__tests__/import-rule.spec.ts new file mode 100644 index 0000000000..ae1b01c31e --- /dev/null +++ b/packages/cli/src/migration/__tests__/import-rule.spec.ts @@ -0,0 +1,177 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { readLintConfigInWorker } from '../compat/runner.ts'; +import { + collectRetainedImportDependencies, + resolveImportRuleConfig, + rewriteAllImports, + tryResolveImportRuleConfig, +} from '../migrator.ts'; +import { createMigrationReport } from '../report.ts'; + +vi.mock('../compat/runner.ts', () => ({ readLintConfigInWorker: vi.fn() })); + +describe('migration import rule settings', () => { + let root: string; + const rule = 'vite-plus/prefer-vite-plus-imports'; + const write = (filename: string, content: string) => { + const file = path.join(root, filename); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content); + }; + const read = (filename: string) => fs.readFileSync(path.join(root, filename), 'utf8'); + const rewrite = async () => + rewriteAllImports(root, true, undefined, { + importRuleConfig: await resolveImportRuleConfig(root), + }); + const config = (lint: unknown) => + write('vite.config.ts', `export default ${JSON.stringify({ lint })};`); + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-import-rule-')); + write('package.json', '{"private":true}'); + write('unit.test.ts', "import { test } from 'vitest';"); + }); + afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); + vi.resetAllMocks(); + }); + + it.each(['off', 0, ['off'], [0], 'allow'].map((severity) => [severity]))( + 'honors disabled severity %j', + async (severity) => { + config({ rules: { [rule]: severity } }); + expect(await rewrite()).toBe(false); + expect(read('unit.test.ts')).toContain("from 'vitest'"); + expect(readLintConfigInWorker).not.toHaveBeenCalled(); + }, + ); + + it.each([undefined, 'warn', 'error', 1, 2, ['warn'], [2], 'deny'].map((severity) => [severity]))( + 'keeps the default rewrite for severity %j', + async (severity) => { + config({ rules: { [rule]: severity } }); + expect(await rewrite()).toBe(true); + expect(read('unit.test.ts')).toContain("from 'vite-plus/test'"); + }, + ); + + it('merges inherited rules before applying ordered overrides', async () => { + config({ + extends: [ + { + rules: { [rule]: 'off' }, + overrides: [{ files: ['templates/**'], rules: { [rule]: 0 } }], + }, + { rules: { [rule]: 'error' } }, + ], + overrides: [ + { files: ['templates/managed/**'], rules: { [rule]: ['warn'] } }, + { files: ['templates/**'], rules: { 'no-debugger': 'error' } }, + ], + }); + for (const file of ['templates/starter/test.ts', 'templates/managed/test.ts']) { + write(file, "export { test } from 'vitest';"); + } + expect(await rewrite()).toBe(true); + expect(read('unit.test.ts')).toContain("from 'vite-plus/test'"); + expect(read('templates/starter/test.ts')).toContain("from 'vitest'"); + expect(read('templates/managed/test.ts')).toContain("from 'vite-plus/test'"); + expect(await rewrite()).toBe(false); + }); + + it('resolves dynamic lint config when static extraction cannot read it', async () => { + write('vite.config.ts', 'export default () => getConfig();'); + vi.mocked(readLintConfigInWorker).mockResolvedValue({ + rules: { [rule]: 'off' }, + }); + expect(await rewrite()).toBe(false); + expect(readLintConfigInWorker).toHaveBeenCalledWith(root); + expect(read('unit.test.ts')).toContain("from 'vitest'"); + }); + + it('finds the nearest managed supplier for each import in an unmanaged template', async () => { + write( + 'package.json', + JSON.stringify({ + devDependencies: { vitest: '*', '@vitest/browser': '*', '@vitest/browser-preview': '*' }, + }), + ); + write( + 'packages/app/package.json', + JSON.stringify({ + optionalDependencies: { '@vitest/browser': '*' }, + peerDependencies: { '@vitest/browser-preview': '^5' }, + }), + ); + write('packages/app/templates/starter/package.json', '{}'); + write( + 'packages/app/templates/starter/test.ts', + "import 'vitest';\nimport '@vitest/browser/context';\nimport '@vitest/browser-preview';", + ); + config({ overrides: [{ files: ['packages/app/templates/**'], rules: { [rule]: 'off' } }] }); + const workspace = { rootDir: root, packages: [{ name: 'app', path: 'packages/app' }] }; + expect( + collectRetainedImportDependencies(workspace, await resolveImportRuleConfig(root)), + ).toEqual({ + vitest: new Set([root]), + browser: new Map([ + [path.join(root, 'packages/app'), new Set(['@vitest/browser', '@vitest/browser-preview'])], + [root, new Set(['@vitest/browser-preview'])], + ]), + }); + }); + + it('defers a failed dynamic load until the scheduled install completes', async () => { + const report = createMigrationReport(); + config({}); + expect(await tryResolveImportRuleConfig(root)).not.toBeNull(); + expect(readLintConfigInWorker).not.toHaveBeenCalled(); + + write('vite.config.ts', 'export default () => getConfig();'); + vi.mocked(readLintConfigInWorker).mockRejectedValueOnce(new Error('missing dependency')); + expect(await tryResolveImportRuleConfig(root)).toBeNull(); + expect(report.warnings).toEqual([]); + expect(read('unit.test.ts')).toContain("from 'vitest'"); + + vi.mocked(readLintConfigInWorker).mockResolvedValue({ + rules: { [rule]: 'off' }, + }); + const importRuleConfig = await resolveImportRuleConfig(root, report); + expect(rewriteAllImports(root, true, report, { importRuleConfig })).toBe(false); + expect(read('unit.test.ts')).toContain("from 'vitest'"); + expect(report.warnings).toEqual([]); + expect(readLintConfigInWorker).toHaveBeenCalledTimes(2); + }); + + it('warns and preserves imports when dynamic config cannot be loaded', async () => { + write('vite.config.ts', 'export default () => getConfig();'); + // A failed Vite config must not fall back to an unrelated JSON rule setting. + write('.oxlintrc.json', JSON.stringify({ rules: { [rule]: 'error' } })); + vi.mocked(readLintConfigInWorker).mockRejectedValue(new Error('config worker crashed')); + const report = createMigrationReport(); + const importRuleConfig = await resolveImportRuleConfig(root, report); + expect(rewriteAllImports(root, true, report, { importRuleConfig })).toBe(false); + expect(read('unit.test.ts')).toContain("from 'vitest'"); + expect(report.warnings).toEqual([ + expect.stringContaining('Skipped Vite/Vitest import rewrites'), + ]); + }); + + it('reads JSON config inheritance before the config migration removes it', async () => { + write('base.json', JSON.stringify({ rules: { [rule]: 'off' } })); + write('.oxlintrc.json', '{"extends":["./base.json"]}'); + expect(await rewrite()).toBe(false); + expect(read('unit.test.ts')).toContain("from 'vitest'"); + }); + + it('fails on an invalid explicit rule setting', async () => { + config({ rules: { [rule]: 'disabled' } }); + await expect(rewrite()).rejects.toThrow('Invalid severity'); + expect(read('unit.test.ts')).toContain("from 'vitest'"); + }); +}); diff --git a/packages/cli/src/migration/__tests__/migrator.spec.ts b/packages/cli/src/migration/__tests__/migrator.spec.ts index 3e3cbda88d..35554da5ba 100644 --- a/packages/cli/src/migration/__tests__/migrator.spec.ts +++ b/packages/cli/src/migration/__tests__/migrator.spec.ts @@ -14,6 +14,10 @@ import { VITE_PLUS_OVERRIDE_PACKAGES, VITEST_VERSION, } from '../../utils/constants.js'; +import { + DISABLED_IMPORT_RULE_CONFIG, + type RetainedImportDependencies, +} from '../migrator/shared.ts'; import { createMigrationReport } from '../report.js'; // A different bundled version verifies that migration follows dependency updates. @@ -3576,6 +3580,122 @@ describe('ensureVitePlusBootstrap', () => { expect(pkg.overrides.vitest).toBeUndefined(); }); + it('keeps a declared browser peer range on the first migration', () => { + const peerDependencies = { '@vitest/browser-preview': '^4 || ^5' }; + writePkgAt(tmpDir, { name: 'test-plugin', peerDependencies }); + fs.writeFileSync( + path.join(tmpDir, 'index.ts'), + "export { preview } from '@vitest/browser-preview';", + ); + + rewriteStandaloneProject( + tmpDir, + makeWorkspaceInfo(tmpDir, PackageManager.npm), + true, + true, + undefined, + DISABLED_IMPORT_RULE_CONFIG, + ); + + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg.peerDependencies).toEqual(peerDependencies); + expect(pkg).not.toHaveProperty(['devDependencies', '@vitest/browser-preview']); + }); + + it('repairs a missing Vitest dependency only in the workspace that keeps the import', () => { + const templateDir = path.join(tmpDir, 'templates/starter'); + writePkgAt(tmpDir, { private: true, devDependencies: { 'vite-plus': 'catalog:' } }); + writePkgAt(templateDir, { name: 'starter' }); + const workspace = { + ...makeWorkspaceInfo(tmpDir, PackageManager.pnpm), + isMonorepo: true, + workspacePatterns: ['templates/*'], + packages: [{ name: 'starter', path: 'templates/starter' }], + }; + const pending = (owners?: RetainedImportDependencies) => + detectVitePlusBootstrapPending( + tmpDir, + workspace.packageManager, + workspace.packages, + workspace.packageManagerVersion, + owners, + ); + + ensureVitePlusBootstrap(workspace); + expect(pending()).toBe(false); + + const owners = { vitest: new Set([templateDir]), browser: new Map>() }; + expect(pending(owners)).toBe(true); + ensureVitePlusBootstrap(workspace, undefined, owners); + expect(readJson(path.join(templateDir, 'package.json'))).toHaveProperty( + 'devDependencies.vitest', + 'catalog:', + ); + expect(readJson(path.join(tmpDir, 'package.json'))).not.toHaveProperty( + 'devDependencies.vitest', + ); + expect(readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml'))).toHaveProperty( + 'catalog.vitest', + VITEST_VERSION, + ); + expect(pending(owners)).toBe(false); + }); + + it.each([ + [PackageManager.pnpm, '10.33.0', 'pnpm-workspace.yaml', readYamlObject], + [PackageManager.yarn, '4.11.0', '.yarnrc.yml', readYamlObject], + [PackageManager.bun, '1.4.4', 'package.json', readJson], + ] as const)( + 'keeps retained browser dependencies and peer ranges in a named %s catalog', + (manager, version, file, readCatalog) => { + const browser = '@vitest/browser'; + const preview = '@vitest/browser-preview'; + const peerRange = '^4 || ^5'; + const catalogFile = path.join(tmpDir, file); + const templateDir = path.join(tmpDir, 'templates/starter'); + const catalogs = { + tools: { [browser]: '^4.0.0', [preview]: peerRange, 'vite-plus': 'latest' }, + }; + const workspace = { + ...makeWorkspaceInfo(tmpDir, manager, version), + isMonorepo: true, + workspacePatterns: ['templates/*'], + packages: [{ name: 'starter', path: 'templates/starter' }], + }; + writePkgAt(tmpDir, { + name: 'root', + private: true, + workspaces: workspace.workspacePatterns, + ...(manager === PackageManager.bun ? { catalogs } : {}), + }); + if (manager !== PackageManager.bun) { + fs.writeFileSync(catalogFile, JSON.stringify({ catalogs })); + } + writePkgAt(templateDir, { + name: 'starter', + dependencies: { [browser]: 'catalog:tools' }, + peerDependencies: { [preview]: 'catalog:tools' }, + }); + const retained = { + vitest: new Set(), + browser: new Map([[templateDir, new Set([browser, preview])]]), + }; + + ensureVitePlusBootstrap(workspace, undefined, retained); + + const result = readCatalog(catalogFile); + expect(result).toHaveProperty(['catalogs', 'tools', browser], VITEST_VERSION); + expect(result).toHaveProperty(['catalogs', 'tools', preview], peerRange); + expect(readJson(path.join(templateDir, 'package.json'))).toMatchObject({ + dependencies: { [browser]: 'catalog:tools' }, + peerDependencies: { [preview]: 'catalog:tools' }, + }); + expect( + detectVitePlusBootstrapPending(tmpDir, manager, workspace.packages, version, retained), + ).toBe(false); + }, + ); + it('reconciles vitest and vite-plus in the workspace package that needs them', () => { const appDir = path.join(tmpDir, 'packages/app'); fs.mkdirSync(appDir, { recursive: true }); diff --git a/packages/cli/src/migration/bin.ts b/packages/cli/src/migration/bin.ts index b639d07499..397c80aaa7 100644 --- a/packages/cli/src/migration/bin.ts +++ b/packages/cli/src/migration/bin.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; -import { styleText } from 'node:util'; +import { isDeepStrictEqual, styleText } from 'node:util'; import * as prompts from '@voidzero-dev/vite-plus-prompts'; import { satisfies } from 'verkit'; @@ -48,6 +48,8 @@ import { applyVitestV5NodeMigration, checkVitestVersion, checkViteVersion, + collectOxlintOwnerDirs, + collectRetainedImportDependencies, collectToolchainVersionChanges, confirmPrettierMigration, confirmTsxMigration, @@ -64,10 +66,12 @@ import { detectTsNodeProject, detectVitePlusBootstrapPending, detectYarnPnpMode, + DISABLED_IMPORT_RULE_CONFIG, ensureVitePlusBootstrap, finalizeCoreMigrationForExistingVitePlus, finishVitestV5Migration, formatVitestV5Findings, + getWorkspaceProjectPaths, hasFrameworkShim, detectLegacyGitHooksMigrationCandidate, injectLintTypeCheckDefaults, @@ -83,8 +87,11 @@ import { migrateOxnodeToVpx, migrateTsNodeToVpx, configureYarnNodeModulesMode, + rewriteAllImports, rewriteMonorepo, rewriteStandaloneProject, + resolveImportRuleConfig, + tryResolveImportRuleConfig, planVitestV5Migration, refreshVitestV5Migration, retryPreservedOxlintConfigs, @@ -92,10 +99,12 @@ import { removeMigratedOxlintConfigs, shouldSkipStagedMigrationForHooks, warnPackageLevelPrettier, + warnUnresolvedImportRuleConfig, vitestV5NeedsMigration, type Framework, type NodeVersionManagerDetection, type VitestV5MigrationPlan, + type RetainedImportDependencies, } from './migrator.ts'; import { prepareNpmViteAliasReinstall } from './npm-reinstall.ts'; import type { MigrationOptions } from './options.ts'; @@ -251,16 +260,6 @@ async function fixBaseUrlForWorkspace( return fixedProjectPaths; } -function getWorkspaceProjectPaths(workspaceInfo: { - rootDir: string; - packages?: WorkspacePackage[]; -}): string[] { - return [ - workspaceInfo.rootDir, - ...(workspaceInfo.packages ?? []).map((pkg) => path.join(workspaceInfo.rootDir, pkg.path)), - ]; -} - function hasBaseUrlInWorkspace(workspaceInfo: { rootDir: string; packages?: WorkspacePackage[]; @@ -856,6 +855,8 @@ async function executeMigrationPlan( }, ); + const importRuleConfig = await resolveImportRuleConfig(workspaceInfo.rootDir, report); + // 4. Check vite and vitest version is supported by migration updateMigrationProgress('Validating toolchain'); const isViteSupported = checkViteVersion(workspaceInfo.rootDir); @@ -949,7 +950,7 @@ async function executeMigrationPlan( // 7. Rewrite configs updateMigrationProgress('Rewriting configs'); if (workspaceInfo.isMonorepo) { - rewriteMonorepo(workspaceInfo, skipStagedMigration, true, report); + rewriteMonorepo(workspaceInfo, skipStagedMigration, true, report, importRuleConfig); } else { rewriteStandaloneProject( workspaceInfo.rootDir, @@ -957,6 +958,7 @@ async function executeMigrationPlan( skipStagedMigration, true, report, + importRuleConfig, ); } @@ -1176,23 +1178,32 @@ async function main() { didMigrate = true; } - const pendingCoreMigration = detectPendingCoreMigration(workspaceInfoOptional); - const vitePlusBootstrapPending = detectVitePlusBootstrapPending( - workspaceInfoOptional.rootDir, - workspaceInfoOptional.packageManager, - workspaceInfoOptional.packages, - workspaceInfoOptional.packageManagerVersion, + // Find the packages that supply preserved imports before bootstrap changes their + // manifests. If the config needs missing dependencies, retry after the normal install. + const importRuleConfig = await tryResolveImportRuleConfig(workspaceInfoOptional.rootDir); + const retainedImportDependencies = collectRetainedImportDependencies( + workspaceInfoOptional, + importRuleConfig, ); - let packageManager: PackageManager | undefined = vitePlusBootstrapPending - ? (workspaceInfoOptional.packageManager ?? - (await selectPackageManager(options.interactive, true, workspaceInfoOptional.rootDir))) - : workspaceInfoOptional.packageManager; - let downloadedPackageManager: Awaited> | undefined; + const pendingCoreMigration = detectPendingCoreMigration(workspaceInfoOptional); + let packageManager = workspaceInfoOptional.packageManager; + let downloadedPackageManager: WorkspaceInfo['downloadPackageManager'] | undefined; let packageManagerVersion = workspaceInfoOptional.packageManagerVersion; - const downloadExistingPackageManager = async () => { - if (!packageManager) { - return undefined; - } + const bootstrapPending = (dependencies: RetainedImportDependencies) => + detectVitePlusBootstrapPending( + workspaceInfoOptional.rootDir, + packageManager, + workspaceInfoOptional.packages, + packageManagerVersion, + dependencies, + ); + const vitePlusBootstrapPending = bootstrapPending(retainedImportDependencies); + async function ensureExistingPackageManager() { + packageManager ??= await selectPackageManager( + options.interactive, + true, + workspaceInfoOptional.rootDir, + ); downloadedPackageManager ??= await downloadSupportedPackageManager({ rootDir: workspaceInfoOptional.rootDir, packageManager, @@ -1202,16 +1213,8 @@ async function main() { failMigrationProgress, }); packageManagerVersion = downloadedPackageManager.version; - return downloadedPackageManager; - }; - const ensureExistingPackageManager = async () => { - packageManager ??= await selectPackageManager( - options.interactive, - true, - workspaceInfoOptional.rootDir, - ); - return downloadExistingPackageManager(); - }; + return { packageManager, downloadPackageManager: downloadedPackageManager }; + } if (vitePlusBootstrapPending) { await ensureExistingPackageManager(); @@ -1244,7 +1247,14 @@ async function main() { // Capture the toolchain version changes BEFORE the reconcile mutates the // manifest, so the `from` values still reflect the pre-migration versions // (raw vite is read from the untouched node_modules). - report.dependencyUpgrades = await collectToolchainVersionChanges(workspaceInfoOptional.rootDir); + report.dependencyUpgrades = await collectToolchainVersionChanges( + workspaceInfoOptional.rootDir, + retainedImportDependencies.vitest.has(workspaceInfoOptional.rootDir), + ); + const deferredOxlintOwnerDirs = + importRuleConfig === null + ? collectOxlintOwnerDirs(workspaceInfoOptional.rootDir, workspaceInfoOptional.packages) + : []; // finalizeCoreMigrationForExistingVitePlus rewrites Vite/Vitest imports across // every workspace package via a synchronous native directory walk; on a large @@ -1257,6 +1267,7 @@ async function main() { true, report, pendingCoreMigration, + importRuleConfig, ); if ( coreMigrationResult.dependencies || @@ -1304,6 +1315,7 @@ async function main() { if ( !didMigrate && + importRuleConfig !== null && !convertYarnPnp && !renovateConfigPath && report.warnings.length === 0 && @@ -1348,21 +1360,18 @@ async function main() { // Runtime metadata can participate in the package manager's lockfile. let needsInstall = coreMigrationResult.dependencies || nodeUpgrades > 0; - if (vitePlusBootstrapPending) { - const downloadResult = await ensureExistingPackageManager(); - if (downloadResult && packageManager) { - updateMigrationProgress('Configuring package manager'); - const bootstrapResult = ensureVitePlusBootstrap( - { - ...workspaceInfoOptional, - packageManager, - downloadPackageManager: downloadResult, - }, - report, - ); - didMigrate = bootstrapResult.changed || didMigrate; - needsInstall = bootstrapResult.changed || needsInstall; - } + async function reconcileBootstrap(dependencies: RetainedImportDependencies): Promise { + const resolved = await ensureExistingPackageManager(); + updateMigrationProgress('Configuring package manager'); + return ensureVitePlusBootstrap( + { ...workspaceInfoOptional, ...resolved }, + report, + dependencies, + ).changed; + } + if (vitePlusBootstrapPending && (await reconcileBootstrap(retainedImportDependencies))) { + didMigrate = true; + needsInstall = true; } let fixBaseUrl = false; @@ -1461,12 +1470,12 @@ async function main() { workspaceInfoOptional.packages, ); if (migrateTsup) { - await ensureExistingPackageManager(); + const resolved = await ensureExistingPackageManager(); updateMigrationProgress('Migrating tsup'); const tsupOk = await migrateTsupToTsdown( workspaceInfoOptional.rootDir, options.interactive, - packageManager!, // is it safe to do this? + resolved.packageManager, tsupConfigFile, workspaceInfoOptional.packages, { silent: true, report }, @@ -1643,12 +1652,9 @@ async function main() { } } - if (needsInstall) { - clearMigrationProgress(); - completeVitestV5Migration(vitestV5Plan, report); - const resolved = await ensureExistingPackageManager(); + async function installExistingDependencies(): Promise { + await ensureExistingPackageManager(); updateMigrationProgress('Installing dependencies'); - const resolvedVersion = resolved?.version ?? packageManagerVersion; const npmReinstallPreparation = packageManager === PackageManager.npm ? prepareNpmViteAliasReinstall( @@ -1668,16 +1674,9 @@ async function main() { { silent: true, packageManager, - packageManagerVersion: resolvedVersion, + packageManagerVersion, }, ); - // Route the install result through the shared helper (mirrors the full - // migration path and is enforced by install-failure-guard.spec): a failed - // install warns, appends to report.warnings, and flips process.exitCode - // rather than being silently credited as a successful migration. Clear the - // spinner first only on failure so the warning isn't interleaved with it; - // on success handleInstallResult returns durationMs, so the credited - // duration is unchanged. if (installSummary.status === 'failed') { clearMigrationProgress(); npmReinstallPreparation?.restore(); @@ -1692,6 +1691,42 @@ async function main() { report, ); } + if (needsInstall) { + clearMigrationProgress(); + completeVitestV5Migration(vitestV5Plan, report); + await installExistingDependencies(); + } + + if (importRuleConfig === null) { + let resolvedImportRuleConfig: string | null = null; + if (needsInstall && finalInstallOk) { + updateMigrationProgress('Reading lint configuration'); + resolvedImportRuleConfig = await tryResolveImportRuleConfig(workspaceInfoOptional.rootDir); + } + if (resolvedImportRuleConfig === null) { + warnUnresolvedImportRuleConfig(report); + } + const resolvedDependencies = + resolvedImportRuleConfig === null + ? retainedImportDependencies + : collectRetainedImportDependencies(workspaceInfoOptional, resolvedImportRuleConfig); + updateMigrationProgress('Rewriting toolchain imports across the workspace'); + didMigrate = + rewriteAllImports(workspaceInfoOptional.rootDir, true, report, { + oxlintOwnerDirs: deferredOxlintOwnerDirs, + importRuleConfig: resolvedImportRuleConfig ?? DISABLED_IMPORT_RULE_CONFIG, + }) || didMigrate; + // The first install used the owners we could identify without loading + // the config. Sync again only if the resolved rule changes dependencies. + if ( + !isDeepStrictEqual(resolvedDependencies, retainedImportDependencies) && + bootstrapPending(resolvedDependencies) && + (await reconcileBootstrap(resolvedDependencies)) + ) { + didMigrate = true; + await installExistingDependencies(); + } + } if (plan.selectedAgentTargetPaths && plan.selectedAgentTargetPaths.length > 0) { updateMigrationProgress('Writing agent instructions'); diff --git a/packages/cli/src/migration/compat/protocol.ts b/packages/cli/src/migration/compat/protocol.ts index 64f8459db4..05b48d0269 100644 --- a/packages/cli/src/migration/compat/protocol.ts +++ b/packages/cli/src/migration/compat/protocol.ts @@ -1 +1,2 @@ export const ROLLDOWN_COMPAT_RESULT_PREFIX = 'VITE_PLUS_ROLLDOWN_COMPAT_RESULT='; +export const LINT_CONFIG_RESULT_PREFIX = 'VITE_PLUS_LINT_CONFIG_RESULT='; diff --git a/packages/cli/src/migration/compat/runner.ts b/packages/cli/src/migration/compat/runner.ts index 5bde4aa9a4..006fd4fe44 100644 --- a/packages/cli/src/migration/compat/runner.ts +++ b/packages/cli/src/migration/compat/runner.ts @@ -1,98 +1,94 @@ import { existsSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; +import type { OxlintConfig } from 'oxlint'; + import { runCommandSilently } from '../../utils/command.ts'; import { addMigrationWarning, type MigrationReport } from '../report.ts'; -import { ROLLDOWN_COMPAT_RESULT_PREFIX } from './protocol.ts'; +import { LINT_CONFIG_RESULT_PREFIX, ROLLDOWN_COMPAT_RESULT_PREFIX } from './protocol.ts'; export { ROLLDOWN_COMPAT_RESULT_PREFIX }; /** * Resolve the isolated compat worker emitted at `migration/compat/worker.js`. * - * The worker is a sibling of this module in source (`src/migration/compat/`), - * so `./worker.js` is the correct relative path. The bundler, however, inlines - * this runner into the parent `migration/bin.js` entry, which sits one level up - * from the emitted `migration/compat/worker.js`; there the worker lives in the - * nested `./compat/` directory. A fixed literal can only satisfy one layout: - * `./compat/worker.js` doubles to `compat/compat/worker.js` in source, while - * `./worker.js` misses the bundled worker. Probe for the nested - * `./compat/worker.js` next to this module to pick the right prefix for - * whichever layout this code is running in. + * In source the worker is a sibling of this module. Bundling can place this + * runner in `migration/bin.js` or a shared chunk at the dist root, since both + * migration and creation import config helpers. Check both bundled layouts + * before falling back to the source layout. */ function resolveWorkerPath(): string { - const nestedWorker = new URL('./compat/worker.js', import.meta.url); - if (existsSync(nestedWorker)) { - return fileURLToPath(nestedWorker); + for (const relativePath of ['./migration/compat/worker.js', './compat/worker.js']) { + const worker = new URL(relativePath, import.meta.url); + if (existsSync(worker)) { + return fileURLToPath(worker); + } } return fileURLToPath(new URL('./worker.js', import.meta.url)); } -// Config resolution executes arbitrary project code; on the upgrade path the -// project's own (older) vite-plus copy may not honor the lazyPlugins-skip env -// handshake, so a blocking plugin factory can wedge the worker. The check is -// best-effort: kill the worker after this long and continue without warnings -// rather than hanging the migration. -const WORKER_TIMEOUT_MS = 30_000; - -interface RolldownCompatibilityResult { - warnings: string[]; +// A project's config can crash or block. Both probes use the same child process +// settings and timeout, and their callers decide how to handle failure. +async function runConfigWorker(rootDir: string, ...args: string[]): Promise { + const { exitCode, stdout } = await runCommandSilently({ + command: process.execPath, + args: [resolveWorkerPath(), rootDir, ...args], + cwd: rootDir, + envs: process.env, + timeoutMs: 30_000, + }); + if (exitCode !== 0) { + throw new Error(`Config worker exited with code ${exitCode}`); + } + return stdout; } -function parseRolldownCompatibilityResult(stdout: Buffer): RolldownCompatibilityResult | undefined { +function parseWorkerResult(stdout: Buffer, prefix: string): Record | undefined { const output = stdout.toString(); - const markerIndex = output.lastIndexOf(ROLLDOWN_COMPAT_RESULT_PREFIX); + const markerIndex = output.lastIndexOf(prefix); if (markerIndex === -1) { return undefined; } - const resultStart = markerIndex + ROLLDOWN_COMPAT_RESULT_PREFIX.length; + const resultStart = markerIndex + prefix.length; const resultEnd = output.indexOf('\n', resultStart); const serialized = output.slice(resultStart, resultEnd === -1 ? undefined : resultEnd).trim(); try { - const result = JSON.parse(serialized) as Partial; - if ( - !Array.isArray(result.warnings) || - !result.warnings.every((item) => typeof item === 'string') - ) { - return undefined; - } - return { warnings: result.warnings }; + const result = JSON.parse(serialized); + return result !== null && typeof result === 'object' ? result : undefined; } catch { return undefined; } } -/** - * Resolve a project's Vite config in a child process before checking it for - * Rolldown-incompatible options. Config files execute arbitrary project code; - * isolating them prevents process-level handlers, explicit exits, and - * asynchronous crashes from terminating the migration itself. - */ export async function checkRolldownCompatibility( rootDir: string, report: MigrationReport, ): Promise { try { - const workerPath = resolveWorkerPath(); - const result = await runCommandSilently({ - command: process.execPath, - args: [workerPath, rootDir], - cwd: rootDir, - envs: process.env, - timeoutMs: WORKER_TIMEOUT_MS, - }); - - if (result.exitCode !== 0) { + const stdout = await runConfigWorker(rootDir); + const warnings = parseWorkerResult(stdout, ROLLDOWN_COMPAT_RESULT_PREFIX)?.warnings; + if (!Array.isArray(warnings) || !warnings.every((item) => typeof item === 'string')) { return; } - - const compatibilityResult = parseRolldownCompatibilityResult(result.stdout); - for (const warning of compatibilityResult?.warnings ?? []) { + for (const warning of warnings) { addMigrationWarning(report, warning); } } catch { // Config resolution is best-effort. Skip failures silently. } } + +/** Read only serializable lint metadata without running project code in migration. */ +export async function readLintConfigInWorker(rootDir: string): Promise { + const stdout = await runConfigWorker(rootDir, 'lint'); + const lint = parseWorkerResult(stdout, LINT_CONFIG_RESULT_PREFIX)?.lint; + if (lint === null) { + return undefined; + } + if (typeof lint !== 'object' || Array.isArray(lint)) { + throw new Error('Config worker did not return lint metadata'); + } + return lint; +} diff --git a/packages/cli/src/migration/compat/worker.ts b/packages/cli/src/migration/compat/worker.ts index aaf92715ec..4e09949fe2 100644 --- a/packages/cli/src/migration/compat/worker.ts +++ b/packages/cli/src/migration/compat/worker.ts @@ -1,8 +1,29 @@ import { writeSync } from 'node:fs'; +import type { OxlintConfig } from 'oxlint'; + +import { PREFER_VITE_PLUS_IMPORTS_RULE } from '../../oxlint-plugin-config.ts'; import { createMigrationReport } from '../report.ts'; import { checkManualChunksCompat } from './manual-chunks.ts'; -import { ROLLDOWN_COMPAT_RESULT_PREFIX } from './protocol.ts'; +import { LINT_CONFIG_RESULT_PREFIX, ROLLDOWN_COMPAT_RESULT_PREFIX } from './protocol.ts'; + +// Plugin objects and unrelated rule options need not be JSON serializable. +// Return only the settings used by migration's import rewrite, including extends. +function importRuleMetadata(lint: OxlintConfig): OxlintConfig { + return { + rules: { [PREFER_VITE_PLUS_IMPORTS_RULE]: lint.rules?.[PREFER_VITE_PLUS_IMPORTS_RULE] }, + extends: lint.extends?.map(importRuleMetadata), + overrides: lint.overrides?.map((override) => ({ + files: override.files, + excludeFiles: override.excludeFiles, + rules: { [PREFER_VITE_PLUS_IMPORTS_RULE]: override.rules?.[PREFER_VITE_PLUS_IMPORTS_RULE] }, + })), + }; +} + +function writeWorkerResult(prefix: string, result: object): void { + writeSync(process.stdout.fd, `${prefix}${JSON.stringify(result)}\n`); +} async function main(): Promise { const rootDir = process.argv[2]; @@ -10,33 +31,28 @@ async function main(): Promise { return; } - try { - const { resolveConfig } = await import('../../index.js'); - const { withConfigMetadataResolution } = await import('../../define-config.js'); - // Use 'runner' configLoader to avoid Rolldown bundling the config file, - // which prints UNRESOLVED_IMPORT warnings that cannot be suppressed via logLevel. - // Reads the config only for the manualChunks compat check, so skip the user's - // plugin factory (lazyPlugins) while it resolves, otherwise a blocking or - // slow factory would hang this worker and a throwing factory would drop the - // warning silently. - const config = await withConfigMetadataResolution(() => - resolveConfig({ root: rootDir, logLevel: 'silent', configLoader: 'runner' }, 'build'), - ); - const report = createMigrationReport(); - checkManualChunksCompat(config.build?.rollupOptions?.output, report); - writeSync( - process.stdout.fd, - `${ROLLDOWN_COMPAT_RESULT_PREFIX}${JSON.stringify({ warnings: report.warnings })}\n`, - ); - } catch { - // Config resolution may fail; skip compatibility checking silently. + const { resolveConfig } = await import('../../index.js'); + const { withConfigMetadataResolution } = await import('../../define-config.js'); + const readLint = process.argv[3] === 'lint'; + // Bundling supports CommonJS lint configs. The runner avoids bundler warnings + // during compatibility checks. Neither probe needs lazy plugin factories. + const config = await withConfigMetadataResolution(() => + resolveConfig( + { root: rootDir, logLevel: 'silent', configLoader: readLint ? 'bundle' : 'runner' }, + 'build', + ), + ); + if (readLint) { + const lint = config.lint ? importRuleMetadata(config.lint) : null; + writeWorkerResult(LINT_CONFIG_RESULT_PREFIX, { lint }); + return; } + + const report = createMigrationReport(); + checkManualChunksCompat(config.build?.rollupOptions?.output, report); + writeWorkerResult(ROLLDOWN_COMPAT_RESULT_PREFIX, { warnings: report.warnings }); } -// Config plugins may leave active handles behind. Once the result has been -// written synchronously, terminate this disposable worker without waiting for -// project-owned cleanup. -main().then( - () => process.exit(0), - () => process.exit(0), -); +// Exit even if project plugins left active handles. On failure, the parent +// detects the missing result and applies the policy for the requested probe. +void main().finally(() => process.exit(0)); diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index b1aaa34448..ea0be5afb7 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -50,7 +50,9 @@ import { type PreparedOxlintConfigs, LEGACY_WRAPPER_FALLBACK_VERSIONS, PROVIDER_OVERRIDE_DROP_NAMES, - REMOVE_PACKAGES, + OPT_IN_BROWSER_PROVIDERS, + bundledPackagesToRemove, + type RetainedImportDependencies, VITEST_IS_MANAGED_OVERRIDE, isPlainRecord, pinnedPackageManagerVersion, @@ -402,8 +404,8 @@ export function rewritePnpmWorkspaceYaml( const currentVersion = getYamlMapScalarStringValue(overrides, overrideKey) ?? getYamlMapScalarStringValue(overrides, key); - // @vitest/browser is an override-only entry: migration removes its direct - // dependency and catalog entry because Vite+ already supplies it. + // Keep the WebdriverIO browser override concrete: it also works in a + // workspace where no package directly imports the browser entry point. const version = key === '@vitest/browser' ? managed[key] @@ -984,19 +986,19 @@ function rewriteYamlCatalogAtPath( catalog.set(scalarString(VITE_PLUS_NAME), scalarString(VITE_PLUS_VERSION)); } if (addMissing && VITEST_IS_MANAGED_OVERRIDE) { - // Injected providers, plus every declared alignable @vitest/* so its - // `catalog:` reference (written by getAlignedVitestEcosystemDependencySpec) - // resolves instead of dangling. That writer does not require `vitest` in - // the catalog, so neither does this one: a project may declare only an - // excluded utility such as `@vitest/utils`. #2005 - const additions = new Set([...catalogAdditions, ...vitestEcosystemPackages]); + // These packages need catalog entries even when the catalog omits vitest (#2005). + // Retained browser peers keep their declared catalog ranges. + const additions = new Set([ + ...vitestEcosystemPackages, + ...OPT_IN_BROWSER_PROVIDERS.filter((name) => catalogAdditions.has(name)), + ]); for (const name of additions) { if (isAlignableVitestEcosystemPackage(name)) { catalog.set(scalarString(name), scalarString(VITEST_VERSION)); } } } - for (const name of REMOVE_PACKAGES) { + for (const name of bundledPackagesToRemove(catalogAdditions)) { catalog.delete(name); } // Drop any entry still pointing at the deleted `vite-plus-test` wrapper. @@ -1038,6 +1040,7 @@ function rewriteCatalogObject( addMissing: boolean, usesVitest: boolean, vitestEcosystemPackages: ReadonlySet, + catalogAdditions: ReadonlySet, otherDefaultCatalog?: Record, ): void { const managed = managedOverridePackages(usesVitest); @@ -1061,7 +1064,7 @@ function rewriteCatalogObject( ) { catalog[VITE_PLUS_NAME] = VITE_PLUS_VERSION; } - for (const name of REMOVE_PACKAGES) { + for (const name of bundledPackagesToRemove(catalogAdditions)) { delete catalog[name]; } if (VITEST_IS_MANAGED_OVERRIDE) { @@ -1082,24 +1085,6 @@ function rewriteCatalogObject( } } -function rewriteCatalogsObject( - catalogs: Record>, - usesVitest: boolean, - vitestEcosystemPackages: ReadonlySet, - targetCatalog?: Record, - defaultCatalog?: Record, -): void { - for (const [name, catalog] of Object.entries(catalogs)) { - rewriteCatalogObject( - catalog, - catalog === targetCatalog, - usesVitest, - vitestEcosystemPackages, - name === 'default' ? defaultCatalog : undefined, - ); - } -} - /** * Write catalog entries to root package.json for bun. * Bun stores catalogs in package.json under the `catalog` key, @@ -1112,6 +1097,7 @@ export function rewriteBunCatalog( vitestEcosystemPackages: ReadonlySet, usesWebdriverioProvider = false, packageManagerVersion = 'latest', + catalogAdditions: ReadonlySet = new Set(), ): void { const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { @@ -1130,7 +1116,6 @@ export function rewriteBunCatalog( const workspacesObj = pkg.workspaces && !Array.isArray(pkg.workspaces) ? pkg.workspaces : undefined; const activeCatalogs = getBunCatalogConfig(pkg); - const useWorkspacesCatalog = activeCatalogs === workspacesObj; // Like the pnpm catalog, add missing entries to the catalog the new // `catalog:` references point at. A named one such as `catalogs.build` // takes them instead of a newly created default catalog. @@ -1141,49 +1126,35 @@ export function rewriteBunCatalog( preferredName || mergeDefaults ? activeCatalogs.catalogs?.[preferredName || 'default'] : undefined; - const defaultCatalog = activeCatalogs.catalog; - const catalog: Record = { ...defaultCatalog }; - - rewriteCatalogObject(catalog, !namedTarget, usesVitest, vitestEcosystemPackages); - pruneLegacyWrapperAliases(catalog); - - if (namedTarget && !defaultCatalog) { - // No default catalog to update, and none is needed. - } else if (useWorkspacesCatalog) { - workspacesObj.catalog = catalog; - if (pkg.catalog) { - rewriteCatalogObject(pkg.catalog, false, usesVitest, vitestEcosystemPackages); - pruneLegacyWrapperAliases(pkg.catalog); - } - } else { - pkg.catalog = catalog; - if (workspacesObj?.catalog) { - rewriteCatalogObject(workspacesObj.catalog, false, usesVitest, vitestEcosystemPackages); - pruneLegacyWrapperAliases(workspacesObj.catalog); - } - } - if (workspacesObj?.catalogs) { - rewriteCatalogsObject( - workspacesObj.catalogs, + function rewriteCatalog( + target: Record, + addMissing: boolean, + otherDefaultCatalog?: Record, + ): void { + rewriteCatalogObject( + target, + addMissing, usesVitest, vitestEcosystemPackages, - namedTarget, - mergeDefaults ? workspacesObj.catalog : undefined, + catalogAdditions, + otherDefaultCatalog, ); - for (const named of Object.values(workspacesObj.catalogs)) { - pruneLegacyWrapperAliases(named); + pruneLegacyWrapperAliases(target); + } + if (!namedTarget || activeCatalogs.catalog) { + const catalog = { ...activeCatalogs.catalog }; + rewriteCatalog(catalog, !namedTarget); + activeCatalogs.catalog = catalog; + + const otherCatalog = activeCatalogs === pkg ? workspacesObj?.catalog : pkg.catalog; + if (otherCatalog) { + rewriteCatalog(otherCatalog, false); } } - if (pkg.catalogs) { - rewriteCatalogsObject( - pkg.catalogs, - usesVitest, - vitestEcosystemPackages, - namedTarget, - mergeDefaults ? pkg.catalog : undefined, - ); - for (const named of Object.values(pkg.catalogs)) { - pruneLegacyWrapperAliases(named); + for (const location of [workspacesObj, pkg]) { + for (const [name, named] of Object.entries(location?.catalogs ?? {})) { + const otherDefault = mergeDefaults && name === 'default' ? location?.catalog : undefined; + rewriteCatalog(named, named === namedTarget, otherDefault); } } @@ -1240,6 +1211,7 @@ export function rewriteRootWorkspacePackageJson( // When false, the root `vite-plus` edge and the direct `vite` edge are concrete. supportCatalog = true, preparedOxlintConfigs?: PreparedOxlintConfigs, + retainedImportDependencies?: RetainedImportDependencies, ): void { const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { @@ -1374,7 +1346,14 @@ export function rewriteRootWorkspacePackageJson( undefined, undefined, catalogDependencyResolver, - packages ? { rootDir: projectPath, packages, oxlintConfigs: preparedOxlintConfigs } : undefined, + packages + ? { + rootDir: projectPath, + packages, + oxlintConfigs: preparedOxlintConfigs, + retainedImportDependencies, + } + : undefined, true, supportCatalog, ); diff --git a/packages/cli/src/migration/migrator/core-finalization.ts b/packages/cli/src/migration/migrator/core-finalization.ts index d57f2b556a..49f2cf9e4c 100644 --- a/packages/cli/src/migration/migrator/core-finalization.ts +++ b/packages/cli/src/migration/migrator/core-finalization.ts @@ -7,6 +7,7 @@ import { editJsonFile, readJsonFile } from '../../utils/json.ts'; import { rulesDir } from '../../utils/path.ts'; import { dropDeadOxlintPluginsDependency, + getWorkspaceProjectPaths, hasTsconfigTypesToRewrite, mergeTsdownConfigFile, migrateTaskCacheConfigInViteConfig, @@ -91,13 +92,6 @@ export type CoreMigrationFinalizationResult = { taskCacheWarnings: string[]; }; -function getCoreMigrationProjectPaths(workspaceInfo: CoreMigrationWorkspace): string[] { - return [ - workspaceInfo.rootDir, - ...(workspaceInfo.packages ?? []).map((pkg) => path.join(workspaceInfo.rootDir, pkg.path)), - ]; -} - function hasCorePackageScriptRewrites(projectPath: string): boolean { const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { @@ -135,7 +129,7 @@ function rewriteCorePackageScripts(projectPath: string): boolean { export function detectPendingCoreMigration( workspaceInfo: CoreMigrationWorkspace, ): PendingCoreMigration { - const projectPaths = getCoreMigrationProjectPaths(workspaceInfo); + const projectPaths = getWorkspaceProjectPaths(workspaceInfo); return { scripts: projectPaths.some((projectPath) => hasCorePackageScriptRewrites(projectPath)), tsconfigTypes: projectPaths.some((projectPath) => hasTsconfigTypesToRewrite(projectPath)), @@ -147,8 +141,10 @@ export function finalizeCoreMigrationForExistingVitePlus( silent = false, report?: MigrationReport, pending = detectPendingCoreMigration(workspaceInfo), + // null defers import rewriting until dynamic lint settings can be resolved. + importRuleConfig?: string | null, ): CoreMigrationFinalizationResult { - const projectPaths = getCoreMigrationProjectPaths(workspaceInfo); + const projectPaths = getWorkspaceProjectPaths(workspaceInfo); const result: CoreMigrationFinalizationResult = { dependencies: false, scripts: false, @@ -172,7 +168,9 @@ export function finalizeCoreMigrationForExistingVitePlus( } } - result.imports = rewriteAllImports(workspaceInfo.rootDir, silent, report, true); + if (importRuleConfig !== null) { + result.imports = rewriteAllImports(workspaceInfo.rootDir, silent, report, { importRuleConfig }); + } result.dependencies = dropDeadOxlintPluginsDependency( workspaceInfo.rootDir, workspaceInfo.packages, diff --git a/packages/cli/src/migration/migrator/orchestrators.ts b/packages/cli/src/migration/migrator/orchestrators.ts index 0280aac009..53645daa03 100644 --- a/packages/cli/src/migration/migrator/orchestrators.ts +++ b/packages/cli/src/migration/migrator/orchestrators.ts @@ -9,9 +9,10 @@ import { applyBuildAllowanceToPackageJsonPnpm, applyYarnWorkspaceHoistingFix, cleanupDeprecatedTsconfigOptions, - collectInjectedProviderNames, + collectBrowserCatalogAdditions, collectOxlintDependencyNames, collectOxlintOwnerDirs, + collectRetainedImportDependencies, collectProviderSourceModes, collectVitestEcosystemInstallDependencyNames, createCatalogDependencyResolver, @@ -20,6 +21,7 @@ import { ensurePnpmWorkspaceExoticSubdepsSetting, ensurePnpmWorkspacePackages, findYarnWorkspaceHoisting, + getWorkspaceProjectPaths, hasDirectVitePlusInstallEntry, hasOwnWebdriverioDependency, injectFmtDefaults, @@ -71,6 +73,7 @@ import { pnpmMajor, type PnpmPackageJsonSettings, type PreparedOxlintConfigs, + type RetainedImportDependencies, } from './shared.ts'; export function rewriteStandaloneProject( @@ -79,6 +82,7 @@ export function rewriteStandaloneProject( skipStagedMigration?: boolean, silent = false, report?: MigrationReport, + importRuleConfig?: string, ): void { const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { @@ -106,17 +110,24 @@ export function rewriteStandaloneProject( workspaceInfo.packages, ); // Source-tree scan signals are computed once here and reused below (and inside - // projectUsesVitestDirectly / collectInjectedProviderNames) so the source tree + // projectUsesVitestDirectly / collectBrowserCatalogAdditions) 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. const providerSourceModes = collectProviderSourceModes(projectPath); const usesWebdriverio = workspaceUsesWebdriverioProvider(projectPath); const browserMode = usesVitestBrowserMode(projectPath); - const retainedVitestModule = sourceTreeReferencesRetainedVitestModule(projectPath); - const providerCatalogAdditions = collectInjectedProviderNames( + const retainedImportDependencies = collectRetainedImportDependencies( + { rootDir: projectPath }, + importRuleConfig, + ); + const retainedVitestModule = + retainedImportDependencies.vitest.has(projectPath) || + sourceTreeReferencesRetainedVitestModule(projectPath); + const browserCatalogAdditions = collectBrowserCatalogAdditions( projectPath, undefined, + retainedImportDependencies.browser, new Map([[projectPath, providerSourceModes]]), ); const pnpmMajorVersion = pnpmMajor(workspaceInfo.downloadPackageManager.version); @@ -264,7 +275,8 @@ export function rewriteStandaloneProject( usesVitest, retainedVitestModule, requiredVitestPeer, - providerCatalogAdditions, + browserCatalogAdditions, + retainedImportDependencies.browser.get(projectPath), ); // ensure vite-plus is in devDependencies — but only when it isn't already a @@ -305,7 +317,7 @@ export function rewriteStandaloneProject( usesVitest, vitestEcosystemPackages, usePnpmWorkspaceYaml, - providerCatalogAdditions, + browserCatalogAdditions, usesWebdriverio, workspaceInfo.downloadPackageManager.version, ); @@ -332,7 +344,7 @@ export function rewriteStandaloneProject( projectPath, usesVitest, vitestEcosystemPackages, - providerCatalogAdditions, + browserCatalogAdditions, supportCatalog, yarnSupportsPreapprovedPackages(workspaceInfo.downloadPackageManager.version), ); @@ -355,7 +367,7 @@ export function rewriteStandaloneProject( injectFmtDefaults(projectPath, silent, report); mergeTsdownConfigFile(projectPath, silent, report); // rewrite imports in all TypeScript/JavaScript files before lazy plugin import merging - rewriteAllImports(projectPath, silent, report, true, oxlintOwnerDirs); + rewriteAllImports(projectPath, silent, report, { oxlintOwnerDirs, importRuleConfig }); dropDeadOxlintPluginsDependency(projectPath, workspaceInfo.packages, originalOxlintDependencies); wrapLazyPluginsInViteConfig(projectPath, silent, report); migrateTaskCacheConfigInViteConfig(projectPath, silent, report); @@ -371,6 +383,7 @@ export function rewriteMonorepo( skipStagedMigration?: boolean, silent = false, report?: MigrationReport, + importRuleConfig?: string, ): void { const reportVitePeerDependencyRuleRemoval = trackVitePeerDependencyRuleRemoval( workspaceInfo.rootDir, @@ -404,18 +417,24 @@ export function rewriteMonorepo( ); // The SHARED workspace sinks (catalog / overrides / peer rules) keep `vitest` // managed iff ANY package in the workspace uses vitest directly. + const retainedImportDependencies = collectRetainedImportDependencies( + workspaceInfo, + importRuleConfig, + ); const workspaceUsesVitest = workspaceUsesVitestDirectly( workspaceInfo.rootDir, workspaceInfo.packages, true, + retainedImportDependencies.vitest, ); const vitestEcosystemPackages = collectVitestEcosystemInstallDependencyNames( workspaceInfo.rootDir, workspaceInfo.packages, ); - const providerCatalogAdditions = collectInjectedProviderNames( + const browserCatalogAdditions = collectBrowserCatalogAdditions( workspaceInfo.rootDir, workspaceInfo.packages, + retainedImportDependencies.browser, ); // Catalog support: pnpm >= 9.5.0, Yarn >= 4.10.0, bun per `bunSupportsCatalog`. // An older PM falls back to concrete. @@ -425,12 +444,10 @@ export function rewriteMonorepo( workspaceInfo.downloadPackageManager.version, ); const workspaceContext = { + retainedImportDependencies, rootDir: workspaceInfo.rootDir, packages: workspaceInfo.packages, - oxlintConfigs: prepareOxlintConfigs([ - workspaceInfo.rootDir, - ...workspaceInfo.packages.map((pkg) => path.join(workspaceInfo.rootDir, pkg.path)), - ]), + oxlintConfigs: prepareOxlintConfigs(getWorkspaceProjectPaths(workspaceInfo)), }; // rewrite root workspace if (workspaceInfo.packageManager === PackageManager.yarn) { @@ -438,7 +455,7 @@ export function rewriteMonorepo( workspaceInfo.rootDir, workspaceUsesVitest, vitestEcosystemPackages, - providerCatalogAdditions, + browserCatalogAdditions, supportCatalog, yarnSupportsPreapprovedPackages(workspaceInfo.downloadPackageManager.version), ); @@ -449,6 +466,7 @@ export function rewriteMonorepo( vitestEcosystemPackages, usesWebdriverio, workspaceInfo.downloadPackageManager.version, + browserCatalogAdditions, ); } rewriteRootWorkspacePackageJson( @@ -463,6 +481,7 @@ export function rewriteMonorepo( workspaceUsesVitest, supportCatalog, workspaceContext.oxlintConfigs, + retainedImportDependencies, ); if (workspaceInfo.packageManager === PackageManager.pnpm) { rewritePnpmWorkspaceYaml( @@ -472,7 +491,7 @@ export function rewriteMonorepo( workspaceUsesVitest, vitestEcosystemPackages, usePnpmWorkspaceSettings, - providerCatalogAdditions, + browserCatalogAdditions, usesWebdriverio, workspaceInfo.downloadPackageManager.version, ); @@ -505,7 +524,7 @@ export function rewriteMonorepo( workspaceContext, true, supportCatalog, - providerCatalogAdditions, + browserCatalogAdditions, ); } @@ -527,7 +546,7 @@ export function rewriteMonorepo( injectFmtDefaults(workspaceInfo.rootDir, silent, report); mergeTsdownConfigFile(workspaceInfo.rootDir, silent, report); // rewrite imports in all TypeScript/JavaScript files before lazy plugin import merging - rewriteAllImports(workspaceInfo.rootDir, silent, report, true, oxlintOwnerDirs); + rewriteAllImports(workspaceInfo.rootDir, silent, report, { oxlintOwnerDirs, importRuleConfig }); dropDeadOxlintPluginsDependency( workspaceInfo.rootDir, workspaceInfo.packages, @@ -563,16 +582,15 @@ export function rewriteMonorepoProject( rootDir: string; packages: WorkspacePackage[]; oxlintConfigs?: PreparedOxlintConfigs; + retainedImportDependencies?: RetainedImportDependencies; }, deferLazyPluginWrapping = false, // Whether this workspace's edges use catalog references. Yarn catalogs require // 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, - // Opt-in browser providers the workspace catalog is gaining (a sibling package - // uses one source-only). An already-installed copy here must reference that - // catalog entry rather than pin a concrete version. See #2005. - providerCatalogAdditions: ReadonlySet = new Set(), + // An installed provider references the shared catalog entry added for a sibling. + browserCatalogAdditions: ReadonlySet = new Set(), ): void { cleanupDeprecatedTsconfigOptions(projectPath, silent, report); rewriteTsconfigTypes(projectPath, silent, report); @@ -616,7 +634,9 @@ export function rewriteMonorepoProject( // not depend on package.json and nothing mutates the source tree between // these reads, so this is identical to the previous per-call scans. const browserMode = usesVitestBrowserMode(projectPath); - const retainedVitestModule = sourceTreeReferencesRetainedVitestModule(projectPath); + const retainedVitestModule = + workspaceContext?.retainedImportDependencies?.vitest.has(projectPath) || + sourceTreeReferencesRetainedVitestModule(projectPath); // rewrite scripts in package.json extractedStagedConfig = rewritePackageJson( pkg, @@ -632,7 +652,8 @@ export function rewriteMonorepoProject( }), retainedVitestModule, requiredVitestPeer, - providerCatalogAdditions, + browserCatalogAdditions, + workspaceContext?.retainedImportDependencies?.browser.get(projectPath), ); // If this SUB-workspace now depends on `vite-plus` and Yarn isolates its // hoisting (via the root `nmHoistingLimits` OR the workspace's own diff --git a/packages/cli/src/migration/migrator/package-json.ts b/packages/cli/src/migration/migrator/package-json.ts index 31d313c822..b95c297f31 100644 --- a/packages/cli/src/migration/migrator/package-json.ts +++ b/packages/cli/src/migration/migrator/package-json.ts @@ -30,7 +30,7 @@ import { OXLINT_PLUGINS_PACKAGE, OXLINT_PLUGIN_API_PACKAGES, packageOwnsOxlintApi, - REMOVE_PACKAGES, + bundledPackagesToRemove, VITEST_BROWSER_DEP_NAMES, VITEST_IS_MANAGED_OVERRIDE, type PackageJsonDependencyField, @@ -60,17 +60,16 @@ export function rewritePackageJson( // is REMOVED so it arrives transitively through vite-plus. Defaults to true to // preserve legacy behavior for callers that don't compute the signal. usesVitestDirectly = true, - // Module augmentations, compilerOptions.types, and `vitest/package.json` - // intentionally retain the upstream package identity after import rewriting - // and therefore require a package-local provider under strict layouts. + // An import preserved by the lint rule, a module augmentation, or a reference + // to Vitest types or package metadata needs the upstream package locally. retainedVitestModule = false, // Installed dependency metadata can reveal required Vitest peers whose // package names do not include "vitest". requiredVitestPeer = false, - // Opt-in browser providers the workspace catalog is gaining (some package uses - // one only through source/a shim). An already-installed copy of such a provider - // must REFERENCE that catalog entry, not pin a concrete version. See #2005. - providerCatalogAdditions: ReadonlySet = new Set(), + // An installed provider references the shared catalog entry added for a sibling. + browserCatalogAdditions: ReadonlySet = new Set(), + // Bundled browser packages that this package still imports. + retainedBrowserPackages?: ReadonlySet, ): Record | null { if (pkg.scripts) { const updated = rewriteScripts( @@ -194,7 +193,7 @@ export function rewritePackageJson( needVitePlus = true; } // remove packages that are replaced with vite-plus - for (const name of REMOVE_PACKAGES) { + for (const name of bundledPackagesToRemove(retainedBrowserPackages)) { let wasRemoved = false; for (const { dependencyField, dependencies } of dependencyGroups) { if ( @@ -255,7 +254,7 @@ export function rewritePackageJson( provider, installGroupEntry.dependencyField, packageManager, - providerCatalogAdditions.has(provider) + browserCatalogAdditions.has(provider) ? supportCatalog && packageManager !== PackageManager.bun : supportCatalog, catalogDependencyResolver, diff --git a/packages/cli/src/migration/migrator/shared.ts b/packages/cli/src/migration/migrator/shared.ts index 690e9bf7fc..136962e532 100644 --- a/packages/cli/src/migration/migrator/shared.ts +++ b/packages/cli/src/migration/migrator/shared.ts @@ -16,6 +16,15 @@ import { detectPackageMetadata } from '../../utils/package.ts'; import { displayRelative } from '../../utils/path.ts'; import { addManualStep, addMigrationWarning, type MigrationReport } from '../report.ts'; +export interface RetainedImportDependencies { + /** Package directories that need a direct Vitest dependency. */ + vitest: ReadonlySet; + /** Declared browser dependencies and peers to keep in each package directory. */ + browser: ReadonlyMap>; +} + +export const DISABLED_IMPORT_RULE_CONFIG = JSON.stringify({ enabled: false, overrides: [] }); + // Commands whose effects prevent literal analysis of later invocations. export const SHELL_STATE_COMMANDS: readonly string[] = [ 'cd', @@ -123,6 +132,11 @@ export const REMOVE_PACKAGES = [ '@vitest/browser-preview', ] as const; +// A preserved browser import still needs its original dependency and catalog entry. +export function bundledPackagesToRemove(retained?: ReadonlySet): readonly string[] { + return retained?.size ? REMOVE_PACKAGES.filter((name) => !retained.has(name)) : REMOVE_PACKAGES; +} + // WebDriverIO is community-maintained. The versioned v5 preflight ensures its // minimum version and framework peer; generic reconciliation must not repin it. export const WEBDRIVERIO_PROVIDER = '@vitest/browser-webdriverio'; diff --git a/packages/cli/src/migration/migrator/source-scan.ts b/packages/cli/src/migration/migrator/source-scan.ts index 5f56f0731b..01f2f96a59 100644 --- a/packages/cli/src/migration/migrator/source-scan.ts +++ b/packages/cli/src/migration/migrator/source-scan.ts @@ -1,6 +1,7 @@ import fs from 'node:fs'; import path from 'node:path'; +import { findRetainedVitestPackages } from '../../../binding/index.js'; import { type WorkspacePackage } from '../../types/index.ts'; import { VITE_PLUS_NAME } from '../../utils/constants.ts'; import { editJsonFile, readJsonFile } from '../../utils/json.ts'; @@ -8,6 +9,7 @@ import { detectPackageMetadata } from '../../utils/package.ts'; import { hasVitestTypesInTsconfig } from '../../utils/tsconfig.ts'; import { projectUsesVitestDirectly } from '../migrator.ts'; import { + DISABLED_IMPORT_RULE_CONFIG, OPT_IN_BROWSER_PROVIDERS, OXLINT_PLUGINS_PACKAGE, packageOwnsOxlintApi, @@ -15,8 +17,70 @@ import { readPackageJsonIfExists, RETENTION_SCAN_SKIP_DIRS, type DependencyBag, + type RetainedImportDependencies, } from './shared.ts'; +type WorkspaceProjects = { rootDir: string; packages?: readonly WorkspacePackage[] }; + +export function getWorkspaceProjectPaths({ rootDir, packages }: WorkspaceProjects): string[] { + return [rootDir, ...(packages ?? []).map((pkg) => path.join(rootDir, pkg.path))]; +} + +/** Find the managed packages that supply imports preserved by the lint rule. */ +export function collectRetainedImportDependencies( + workspace: WorkspaceProjects, + importRuleConfig: string | null | undefined, +): RetainedImportDependencies { + const retained = { vitest: new Set(), browser: new Map>() }; + if (importRuleConfig === undefined) { + return retained; + } + const imports = findRetainedVitestPackages( + workspace.rootDir, + importRuleConfig ?? DISABLED_IMPORT_RULE_CONFIG, + ); + if (imports.length === 0) { + return retained; + } + + const declarations = new Map( + getWorkspaceProjectPaths(workspace).map((dir) => { + const pkg = readPackageJsonIfExists(path.join(dir, 'package.json')); + return [dir, { installed: collectInstallDependencyNames(pkg), peers: pkg?.peerDependencies }]; + }), + ); + + function retainSuppliers(packageDir: string, name: string): void { + // Unmanaged templates resolve imports through their workspace ancestors. + // Keep browser peer contracts on the way to the nearest install declaration. + for (let dir = packageDir; ; dir = path.dirname(dir)) { + const pkg = declarations.get(dir); + const installed = pkg?.installed.has(name); + if (name === 'vitest') { + // A known rule can also repair a missing install in the importing package. + if (installed || (dir === packageDir && pkg && importRuleConfig !== null)) { + retained.vitest.add(dir); + return; + } + } else if (installed || pkg?.peers?.[name] !== undefined) { + const names = retained.browser.get(dir) ?? new Set(); + names.add(name); + retained.browser.set(dir, names); + } + if (installed || dir === workspace.rootDir || dir === path.dirname(dir)) { + return; + } + } + } + + for (const { packageDir, dependencies } of imports) { + for (const name of dependencies) { + retainSuppliers(packageDir, name); + } + } + return retained; +} + // Workspace-wide direct-vitest signal for the SHARED sinks a monorepo root // owns (pnpm-workspace.yaml catalog/overrides/peer rules, .yarnrc.yml catalog, // bun catalog): `vitest` stays managed there iff ANY package in the workspace — @@ -26,22 +90,15 @@ export function workspaceUsesVitestDirectly( rootDir: string, packages: WorkspacePackage[] | undefined, preserveNuxtVitestImports = true, + protectedVitestImportOwners?: ReadonlySet, ): boolean { - const rootPkg = readPackageJsonIfExists(path.join(rootDir, 'package.json')) ?? {}; - if (projectUsesVitestDirectly(rootDir, rootPkg, undefined, preserveNuxtVitestImports)) { + if (protectedVitestImportOwners?.size) { return true; } - if (!packages) { - return false; - } - for (const pkg of packages) { - const packageDir = path.join(rootDir, pkg.path); - const subPkg = readPackageJsonIfExists(path.join(packageDir, 'package.json')) ?? {}; - if (projectUsesVitestDirectly(packageDir, subPkg, undefined, preserveNuxtVitestImports)) { - return true; - } - } - return false; + return getWorkspaceProjectPaths({ rootDir, packages }).some((dir) => { + const pkg = readPackageJsonIfExists(path.join(dir, 'package.json')) ?? {}; + return projectUsesVitestDirectly(dir, pkg, undefined, preserveNuxtVitestImports); + }); } // Specifier fragments that signal vitest browser mode. Matched as substrings @@ -309,11 +366,8 @@ export function hasNuxtTestUtilsDependency(pkg: DependencyBag): boolean { ); } -// Normal imports and triple-slash type directives from `vitest` are rewritten -// to `vite-plus/test` later in the same migration and therefore do not justify -// a lasting direct dependency. Module augmentations, `vitest/package.json`, and -// compilerOptions.types entries deliberately retain the upstream package -// identity, so keep Vitest package-local for those surfaces. +// These references keep their upstream package identity even when import +// rewriting is enabled. They need a package-local Vitest dependency. export function sourceTreeReferencesRetainedVitestModule(projectPath: string): boolean { return ( findPackageTsconfigFiles(projectPath).some(hasVitestTypesInTsconfig) || diff --git a/packages/cli/src/migration/migrator/vite-config.ts b/packages/cli/src/migration/migrator/vite-config.ts index b03b41432c..1e1344fef5 100644 --- a/packages/cli/src/migration/migrator/vite-config.ts +++ b/packages/cli/src/migration/migrator/vite-config.ts @@ -14,6 +14,7 @@ import { mergeJsonConfig, mergeTsdownConfig, migrateTaskCacheConfig, + readStaticLintConfig, rewriteImportsInDirectory, rewriteScripts, upsertJsonConfig, @@ -31,6 +32,7 @@ import { editJsonFile, isJsonFile, readJsonFile } from '../../utils/json.ts'; import { displayRelative } from '../../utils/path.ts'; import { hasBaseUrlInTsconfig } from '../../utils/tsconfig.ts'; import { parseSource, sameStaticValue } from '../ast-utils.ts'; +import { readLintConfigInWorker } from '../compat/runner.ts'; import { detectConfigs, type ConfigFiles } from '../detector.ts'; import { collectInstalledPackageNames, @@ -48,6 +50,7 @@ import { type OxlintConfigMigration, type OxlintModulePlan, type PreparedOxlintConfigs, + DISABLED_IMPORT_RULE_CONFIG, OXLINT_OWNER_CONFIG_KEYS, LINT_STAGED_JSON_CONFIG_FILES, LINT_STAGED_OTHER_CONFIG_FILES, @@ -1002,22 +1005,115 @@ export function migrateTaskCacheConfigInViteConfig( return true; } +function importRuleEnabled(rules: OxlintConfig['rules']): boolean | undefined { + const rule = rules?.[PREFER_VITE_PLUS_IMPORTS_RULE]; + const severity = Array.isArray(rule) ? rule[0] : rule; + switch (severity) { + case undefined: + return undefined; + case 0: + case 'off': + case 'allow': + return false; + case 1: + case 2: + case 'warn': + case 'error': + case 'deny': + return true; + default: + throw new Error( + `Invalid severity for ${PREFER_VITE_PLUS_IMPORTS_RULE}: ${JSON.stringify(rule)}`, + ); + } +} + +export function warnUnresolvedImportRuleConfig(report?: MigrationReport): void { + warnMigration( + 'Could not load lint configuration in an isolated process. Skipped Vite/Vitest import rewrites; fix the config and re-run `vp migrate`.', + report, + ); +} + /** - * Rewrite imports in all TypeScript/JavaScript files under a directory - * This rewrites vite/vitest imports to @voidzero-dev/vite-plus - * @param projectPath - The root directory to search for files + * Read the import rule before migration merges or removes lint configs. + * Return null if the worker cannot load the project config. */ +export async function tryResolveImportRuleConfig(projectPath: string): Promise { + const extracted = readStaticLintConfig(projectPath); + let lint: OxlintConfig | undefined; + if (extracted != null) { + lint = JSON.parse(extracted); + } else { + try { + lint = await readLintConfigInWorker(projectPath); + } catch { + return null; + } + } + if (!lint) { + const filename = detectConfigs(projectPath).oxlintConfig; + if (filename) { + try { + lint = resolveOxlintConfigExtends(path.join(projectPath, filename)).config; + } catch { + // The config migration reports and preserves unresolved JSON configs. + } + } + } + + const layers = lint ? oxlintConfigLayers(lint) : []; + const enabled = layers.reduce( + (previous, layer) => importRuleEnabled(layer.rules) ?? previous, + true, + ); + const overrides = []; + for (const layer of layers) { + for (const override of layer.overrides ?? []) { + const overrideEnabled = importRuleEnabled(override.rules); + if (overrideEnabled !== undefined) { + overrides.push({ + files: override.files, + excludeFiles: override.excludeFiles ?? [], + enabled: overrideEnabled, + }); + } + } + } + return JSON.stringify({ enabled, overrides }); +} + +/** Preserve imports if the last attempt to read the rule fails. */ +export async function resolveImportRuleConfig( + projectPath: string, + report?: MigrationReport, +): Promise { + const config = await tryResolveImportRuleConfig(projectPath); + if (config !== null) { + return config; + } + warnUnresolvedImportRuleConfig(report); + return DISABLED_IMPORT_RULE_CONFIG; +} + +/** Rewrite toolchain imports throughout the project and record the results. */ export function rewriteAllImports( projectPath: string, silent = false, report?: MigrationReport, - preserveNuxtVitestImports = true, - // Directories of packages that own the Oxlint plugin API, captured before - // `rewritePackageJson` stripped `oxlint` from their manifests. See - // `collectOxlintOwnerDirs`. - oxlintOwnerDirs: string[] = [], + options: { + preserveNuxtVitestImports?: boolean; + // Capture package owners before migration removes oxlint from their manifests. + oxlintOwnerDirs?: string[]; + importRuleConfig?: string; + } = {}, ): boolean { - const result = rewriteImportsInDirectory(projectPath, preserveNuxtVitestImports, oxlintOwnerDirs); + const result = rewriteImportsInDirectory( + projectPath, + options.preserveNuxtVitestImports ?? true, + options.oxlintOwnerDirs ?? [], + options.importRuleConfig, + ); const modified = result.modifiedFiles.length; const preserved = result.preservedVitestFiles.length; const errors = result.errors.length; diff --git a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts index ace12a90cd..a6602e5e5f 100644 --- a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts +++ b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts @@ -27,6 +27,7 @@ import { findYarnWorkspaceHoisting, getAlignedVitestEcosystemDependencySpec, getCatalogDependencySpec, + getWorkspaceProjectPaths, isAlignableVitestEcosystemPackage, isLegacyWrapperSpec, isProtocolPinnedSpec, @@ -70,7 +71,8 @@ import { OPT_IN_BROWSER_PROVIDERS, OXLINT_PLUGIN_API_PACKAGES, packageOwnsOxlintApi, - REMOVE_PACKAGES, + bundledPackagesToRemove, + type RetainedImportDependencies, VITEST_IS_MANAGED_OVERRIDE, managedOverrideKey, pinnedPackageManagerVersion, @@ -295,13 +297,14 @@ function reconcileVitePlusBootstrapPackage( supportCatalog: boolean, ensureVitePlus: boolean, catalogDependencyResolver?: CatalogDependencyResolver, - // Opt-in browser providers the workspace catalog is gaining (some package uses - // one only through source/a shim). An already-installed copy of such a provider - // must REFERENCE that catalog entry, not pin a concrete version. See #2005. - providerCatalogAdditions: ReadonlySet = new Set(), + // An installed provider references the shared catalog entry added for a sibling. + browserCatalogAdditions: ReadonlySet = new Set(), + retainedImportDependencies?: RetainedImportDependencies, ): boolean { const before = JSON.stringify(pkg); - const usesVitest = projectUsesVitestDirectly(projectPath, pkg, undefined, true); + const usesVitest = + retainedImportDependencies?.vitest.has(projectPath) || + projectUsesVitestDirectly(projectPath, pkg); ensureVitePlusDependencySpecs(pkg, vitePlusVersion, ensureVitePlus); const installGroups = [pkg.devDependencies, pkg.dependencies, pkg.optionalDependencies]; @@ -359,7 +362,7 @@ function reconcileVitePlusBootstrapPackage( provider, installGroupEntry.dependencyField, packageManager, - providerCatalogAdditions.has(provider) + browserCatalogAdditions.has(provider) ? supportCatalog && packageManager !== PackageManager.bun : supportCatalog, catalogDependencyResolver, @@ -385,18 +388,12 @@ function reconcileVitePlusBootstrapPackage( } } - // The full bundled set (oxlint/oxlint-tsgolint/oxfmt/tsdown plus the base - // `@vitest/browser`/preview runtime) is owned by vite-plus, so strip every - // REMOVE_PACKAGES entry from this package's install groups, matching the - // catalog removal (catalog.ts) and the fresh path (package-json.ts). Leaving - // any of them behind keeps a `catalog:` reference whose catalog entry the - // catalog rewrite just deleted, dangling the next `pnpm install`. A plain - // delete is correct for everything except the published-plugin dependency - // kept below: none of the others carry a project-owned peer (the - // browser-provider peer logic is for the opt-in `@vitest/browser-*` - // providers, which are deliberately NOT in REMOVE_PACKAGES). + // 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 REMOVE_PACKAGES) { + for (const bundledPackage of bundledPackagesToRemove( + retainedImportDependencies?.browser.get(projectPath), + )) { for (const dependencies of installGroups) { if ( ownsOxlintApi && @@ -501,12 +498,14 @@ export function bootstrapProjectPaths( rootDir: string, packages: WorkspacePackage[] | undefined, ): string[] { - return [rootDir, ...(packages ?? []).map((pkg) => path.join(rootDir, pkg.path))]; + return getWorkspaceProjectPaths({ rootDir, packages }); } -export function collectInjectedProviderNames( +/** Catalog entries needed for retained browser imports and newly installed providers. */ +export function collectBrowserCatalogAdditions( rootDir: string, packages?: WorkspacePackage[], + retainedBrowserPackages?: RetainedImportDependencies['browser'], // Optional precomputed provider source-scan results keyed by absolute package // path. Lets a caller that already scanned a path reuse the result instead of // re-traversing the source tree; unknown paths fall back to a fresh scan. @@ -514,6 +513,9 @@ export function collectInjectedProviderNames( ): Set { const names = new Set(); for (const packagePath of bootstrapProjectPaths(rootDir, packages)) { + for (const name of retainedBrowserPackages?.get(packagePath) ?? []) { + names.add(name); + } const packageJsonPath = path.join(packagePath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { continue; @@ -522,15 +524,12 @@ export function collectInjectedProviderNames( const sourceModes = precomputedSourceModes?.get(packagePath) ?? collectProviderSourceModes(packagePath); const installGroups = [pkg.devDependencies, pkg.dependencies, pkg.optionalDependencies]; - const dependencyGroups = [...installGroups, pkg.peerDependencies]; for (const provider of OPT_IN_BROWSER_PROVIDERS) { - const used = - sourceModes[provider] || - dependencyGroups.some((dependencies) => dependencies?.[provider] !== undefined); + const needsProvider = sourceModes[provider] || pkg.peerDependencies?.[provider] !== undefined; const installed = installGroups.some( (dependencies) => dependencies?.[provider] !== undefined, ); - if (used && !installed) { + if (needsProvider && !installed) { names.add(provider); } } @@ -625,6 +624,7 @@ export function detectVitePlusBootstrapPending( packageManager: PackageManager | undefined, packages?: WorkspacePackage[], packageManagerVersion?: string, + retainedImportDependencies?: RetainedImportDependencies, ): boolean { const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { @@ -689,7 +689,11 @@ 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 providerCatalogAdditions = collectInjectedProviderNames(projectPath, packages); + const browserCatalogAdditions = collectBrowserCatalogAdditions( + projectPath, + packages, + retainedImportDependencies?.browser, + ); for (const [index, packagePath] of bootstrapProjectPaths(projectPath, packages).entries()) { const childPackageJsonPath = path.join(packagePath, 'package.json'); if (!fs.existsSync(childPackageJsonPath)) { @@ -706,7 +710,8 @@ export function detectVitePlusBootstrapPending( supportCatalog, index === 0, catalogDependencyResolver, - providerCatalogAdditions, + browserCatalogAdditions, + retainedImportDependencies, ) ) { return true; @@ -715,7 +720,12 @@ export function detectVitePlusBootstrapPending( // Shared override/catalog sinks must keep vitest managed when any package in // the workspace needs it. The direct dependency itself is localized above. - const usesVitest = workspaceUsesVitestDirectly(projectPath, packages, true); + const usesVitest = workspaceUsesVitestDirectly( + projectPath, + packages, + true, + retainedImportDependencies?.vitest, + ); const usesWebdriverio = workspaceUsesWebdriverioProvider(projectPath, packages); if (packageManager === PackageManager.yarn) { @@ -958,6 +968,7 @@ function ensurePnpmPeerDependencyRules( export function ensureVitePlusBootstrap( workspaceInfo: WorkspaceInfo, report?: MigrationReport, + retainedImportDependencies?: RetainedImportDependencies, ): VitePlusBootstrapResult { const projectPath = workspaceInfo.rootDir; const packageJsonPath = path.join(projectPath, 'package.json'); @@ -980,7 +991,12 @@ export function ensureVitePlusBootstrap( // Shared override/catalog sinks are workspace-wide, so keep vitest managed // when any package needs it. Each package's direct vitest dependency is // reconciled independently below. - const usesVitest = workspaceUsesVitestDirectly(projectPath, workspaceInfo.packages, true); + const usesVitest = workspaceUsesVitestDirectly( + projectPath, + workspaceInfo.packages, + true, + retainedImportDependencies?.vitest, + ); const usesWebdriverio = workspaceUsesWebdriverioProvider(projectPath, workspaceInfo.packages); const pnpmMajorVersion = pnpmMajor(workspaceInfo.downloadPackageManager.version); const shouldAllowBrowserBuilds = workspaceUsesWebdriverio(projectPath, workspaceInfo.packages); @@ -1019,9 +1035,10 @@ export function ensureVitePlusBootstrap( projectPath, workspaceInfo.packages, ); - const providerCatalogAdditions = collectInjectedProviderNames( + const browserCatalogAdditions = collectBrowserCatalogAdditions( projectPath, workspaceInfo.packages, + retainedImportDependencies?.browser, ); let movedPnpmSettings: Record | undefined; @@ -1049,7 +1066,7 @@ export function ensureVitePlusBootstrap( usesVitest, vitestEcosystemPackages, false, - providerCatalogAdditions, + browserCatalogAdditions, usesWebdriverio, workspaceInfo.downloadPackageManager.version, ); @@ -1071,7 +1088,8 @@ export function ensureVitePlusBootstrap( supportCatalog, true, catalogDependencyResolver, - providerCatalogAdditions, + browserCatalogAdditions, + retainedImportDependencies, ); if (workspaceInfo.packageManager === PackageManager.yarn) { @@ -1188,7 +1206,8 @@ export function ensureVitePlusBootstrap( supportCatalog, false, catalogDependencyResolver, - providerCatalogAdditions, + browserCatalogAdditions, + retainedImportDependencies, ); if ( yarnHoisting && @@ -1246,7 +1265,7 @@ export function ensureVitePlusBootstrap( usesVitest, vitestEcosystemPackages, true, - providerCatalogAdditions, + browserCatalogAdditions, usesWebdriverio, workspaceInfo.downloadPackageManager.version, ); @@ -1274,7 +1293,7 @@ export function ensureVitePlusBootstrap( projectPath, usesVitest, vitestEcosystemPackages, - providerCatalogAdditions, + browserCatalogAdditions, supportCatalog, yarnSupportsPreapprovedPackages(workspaceInfo.downloadPackageManager.version), ); @@ -1291,6 +1310,7 @@ export function ensureVitePlusBootstrap( vitestEcosystemPackages, usesWebdriverio, workspaceInfo.downloadPackageManager.version, + browserCatalogAdditions, ); const after = fs.readFileSync(packageJsonPath, 'utf-8'); result.packageJson = result.packageJson || before !== after; @@ -1389,6 +1409,7 @@ function readInstalledRawViteVersion(projectPath: string): string | undefined { */ export async function collectToolchainVersionChanges( projectPath: string, + hasProtectedVitestImports = false, ): Promise { const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { @@ -1443,7 +1464,7 @@ export async function collectToolchainVersionChanges( // reconcile uses to keep and align it). if ( declaredRootSpec(pkg, 'vitest') !== undefined && - projectUsesVitestDirectly(projectPath, pkg, undefined, true) + (hasProtectedVitestImports || projectUsesVitestDirectly(projectPath, pkg)) ) { pushChange('vitest', VITEST_VERSION, fromFor('vitest')); }