From f86721ea4b324ee5c5d07a44651d0ea8eaff42ea Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 09:40:25 +0900 Subject: [PATCH 01/14] fix(create): complete catalogs in Yarn and Bun workspaces Preserve existing catalog entries and locations when adding managed dependencies. Use concrete versions when the package manager does not support catalogs, and return a failing exit code when dependency installation fails. --- .../package.json | 6 + .../snapshots.toml | 13 ++ .../create_existing_bun_workspace.md | 35 +++++ .../.yarnrc.yml | 1 + .../package.json | 6 + .../snapshots.toml | 41 ++++++ ...e_existing_yarn_without_catalog_support.md | 47 +++++++ .../create_existing_yarn_workspace.md | 27 ++++ .../create_workspace_install_failure.md | 24 ++++ .../__tests__/workspace-catalog.spec.ts | 125 +++++++++++++++++- packages/cli/src/create/bin.ts | 30 ++++- packages/cli/src/create/utils.ts | 92 ++++++++++--- 12 files changed, 416 insertions(+), 31 deletions(-) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/package.json create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_workspace.md create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/.yarnrc.yml create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/package.json create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_without_catalog_support.md create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_workspace.md create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_workspace_install_failure.md diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/package.json new file mode 100644 index 0000000000..269eb0fa3f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/package.json @@ -0,0 +1,6 @@ +{ + "name": "plain-workspace", + "private": true, + "packageManager": "bun@1.4.0", + "workspaces": ["apps/*"] +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml new file mode 100644 index 0000000000..3d0c677818 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml @@ -0,0 +1,13 @@ +[[case]] +name = "create_existing_bun_workspace" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Creating an application supplies missing Bun catalog entries before installation." +steps = [ + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "stat-file", "bun.lock", "--assert", "file"], + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_workspace.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_workspace.md new file mode 100644 index 0000000000..fb50eb0116 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_workspace.md @@ -0,0 +1,35 @@ +# create_existing_bun_workspace + +Creating an application supplies missing Bun catalog entries before installation. + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt stat-file bun.lock --assert file` + +``` +bun.lock: file +``` + +## `vpt print-file package.json` + +``` +{ + "name": "plain-workspace", + "private": true, + "packageManager": "bun@1.4.0", + "workspaces": [ + "apps/*" + ], + "catalog": { + "vite": "npm:@voidzero-dev/vite-plus-core@", + "vite-plus": "" + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/.yarnrc.yml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/.yarnrc.yml new file mode 100644 index 0000000000..3186f3f079 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/.yarnrc.yml @@ -0,0 +1 @@ +nodeLinker: node-modules diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/package.json new file mode 100644 index 0000000000..93359cc191 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/package.json @@ -0,0 +1,6 @@ +{ + "name": "plain-workspace", + "private": true, + "packageManager": "yarn@4.18.1", + "workspaces": ["apps/*"] +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml new file mode 100644 index 0000000000..3f03f6ba6f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml @@ -0,0 +1,41 @@ +[[case]] +name = "create_existing_yarn_workspace" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Creating an application supplies missing Yarn catalog entries before installation." +env = { YARN_NPM_MINIMAL_AGE_GATE = "0" } +steps = [ + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "stat-file", "yarn.lock", "--assert", "file"], + ["vpt", "print-file", ".yarnrc.yml"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] + +[[case]] +name = "create_existing_yarn_without_catalog_support" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Yarn before 4.10 receives concrete versions instead of unsupported catalog references." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "packageManager", "yarn@4.9.0"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "resolutions.typescript", "5.9.3"], comment = "Yarn 4.9's built-in TypeScript patch predates TypeScript 7.", snapshot = false }, + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "stat-file", "yarn.lock", "--assert", "file"], + ["vpt", "print-file", "apps/web/package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] + +[[case]] +name = "create_workspace_install_failure" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Creation reports a failing exit code when workspace dependency installation fails." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "dependencies.missing-dependency", "file:./missing-dependency"], snapshot = false }, + ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_without_catalog_support.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_without_catalog_support.md new file mode 100644 index 0000000000..71c303a338 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_without_catalog_support.md @@ -0,0 +1,47 @@ +# create_existing_yarn_without_catalog_support + +Yarn before 4.10 receives concrete versions instead of unsupported catalog references. + +## `vpt json-edit package.json packageManager yarn@4.9.0` + + +## `vpt json-edit package.json resolutions.typescript 5.9.3` + +Yarn 4.9's built-in TypeScript patch predates TypeScript 7. + + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt stat-file yarn.lock --assert file` + +``` +yarn.lock: file +``` + +## `vpt print-file apps/web/package.json` + +``` +{ + "name": "web", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vp dev", + "build": "tsc && vp build", + "preview": "vp preview" + }, + "devDependencies": { + "typescript": "~7.0.2", + "vite": "npm:@voidzero-dev/vite-plus-core@", + "vite-plus": "" + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_workspace.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_workspace.md new file mode 100644 index 0000000000..e5b23038f2 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_workspace.md @@ -0,0 +1,27 @@ +# create_existing_yarn_workspace + +Creating an application supplies missing Yarn catalog entries before installation. + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt stat-file yarn.lock --assert file` + +``` +yarn.lock: file +``` + +## `vpt print-file .yarnrc.yml` + +``` +nodeLinker: node-modules +catalog: + vite: npm:@voidzero-dev/vite-plus-core@ + vite-plus: +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_workspace_install_failure.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_workspace_install_failure.md new file mode 100644 index 0000000000..35536f5011 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_workspace_install_failure.md @@ -0,0 +1,24 @@ +# create_workspace_install_failure + +Creation reports a failing exit code when workspace dependency installation fails. + +## `vpt json-edit package.json dependencies.missing-dependency file:./missing-dependency` + + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + +**Exit code:** 1 + +``` +● ➤ YN0000: · Yarn + ➤ YN0000: ┌ Resolution step + ➤ YN0001: │ Error: missing-dependency@file:./missing-dependency::locator=plain-workspace%40workspace%3A.: ENOENT: no such file or directory, lstat '/missing-dependency' + ➤ YN0000: └ Completed + ➤ YN0000: · Failed with errors in + +■ +● You may need to run "vp install" manually in +◇ Scaffolded apps/web with Vite application +• Node yarn +→ Next: cd apps/web && vp run +``` diff --git a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts index 4786036f72..2838460a30 100644 --- a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts +++ b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts @@ -3,6 +3,7 @@ import os from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { stringify } from 'yaml'; import { createCatalogDependencyResolver, @@ -12,7 +13,7 @@ import { PackageManager } from '../../types/index.ts'; import { VITE_PLUS_OVERRIDE_PACKAGES, VITE_PLUS_VERSION } from '../../utils/constants.ts'; import { readJsonFile } from '../../utils/json.ts'; import { readYamlFile } from '../../utils/yaml.ts'; -import { ensurePnpmCreateCatalogEntries } from '../utils.ts'; +import { ensureCreateCatalogEntries } from '../utils.ts'; let root: string; let project: string; @@ -42,10 +43,126 @@ function integrate(dependencies: Record = { vite: '^8.0.0' }) { undefined, createCatalogDependencyResolver(root, PackageManager.pnpm), ); - ensurePnpmCreateCatalogEntries(root, project); + ensureCreateCatalogEntries(root, project, PackageManager.pnpm); return readYamlFile(workspaceFile); } +describe.each([PackageManager.yarn, PackageManager.bun])('%s workspace catalogs', (pm) => { + it.each(['missing', 'partial', 'named', 'default'] as const)( + 'completes a %s catalog without changing existing versions', + (kind) => { + const existing = { 'vite-plus': '0.3.2', react: '^19.0.0' }; + const config = { + missing: {}, + partial: { catalog: existing }, + named: { catalogs: { tools: existing } }, + default: { catalogs: { default: existing } }, + }[kind]; + const file = path.join(root, pm === PackageManager.yarn ? '.yarnrc.yml' : 'package.json'); + const contents = { private: true, workspaces: ['apps/*'], ...config }; + if (pm !== PackageManager.yarn || kind !== 'missing') { + fs.writeFileSync( + file, + pm === PackageManager.yarn ? stringify(config) : JSON.stringify(contents), + ); + } + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ devDependencies: { vite: '^8.0.0' } }), + ); + rewriteMonorepoProject( + project, + pm, + true, + true, + undefined, + createCatalogDependencyResolver(root, pm), + ); + ensureCreateCatalogEntries(root, project, pm); + const result = pm === PackageManager.yarn ? readYamlFile(file) : readJsonFile(file); + const entries = { + ...(kind === 'missing' ? { 'vite-plus': VITE_PLUS_VERSION } : existing), + vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, + }; + const expected = + kind === 'named' + ? { catalogs: { tools: entries } } + : kind === 'default' + ? { catalogs: { default: entries } } + : { catalog: entries }; + expect(result).toEqual( + pm === PackageManager.yarn + ? expected + : { private: true, workspaces: ['apps/*'], ...expected }, + ); + const before = fs.readFileSync(file, 'utf8'); + ensureCreateCatalogEntries(root, project, pm); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }, + ); +}); + +it('fills Bun nested named catalogs without moving or replacing existing settings', () => { + const file = path.join(root, 'package.json'); + fs.writeFileSync( + file, + JSON.stringify({ + private: true, + workspaces: { packages: ['apps/*'], catalogs: { tools: { 'vite-plus': '0.3.2' } } }, + catalog: { react: '^19.0.0' }, + }), + ); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { vite: 'catalog:tools', 'vite-plus': 'catalog:tools' }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.bun); + expect(readJsonFile(file)).toEqual({ + private: true, + workspaces: { + packages: ['apps/*'], + catalogs: { + tools: { + 'vite-plus': '0.3.2', + vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, + }, + }, + }, + catalog: { react: '^19.0.0' }, + }); +}); + +it('keeps Bun nested default catalogs separate from top-level settings', () => { + const file = path.join(root, 'package.json'); + const contents = { + private: true, + workspaces: { packages: ['apps/*'], catalogs: { default: { 'vite-plus': '0.3.2' } } }, + catalog: { react: '^19.0.0' }, + }; + fs.writeFileSync(file, JSON.stringify(contents)); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { vite: 'catalog:', 'vite-plus': 'catalog:' }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.bun); + expect(readJsonFile(file)).toEqual({ + ...contents, + workspaces: { + packages: ['apps/*'], + catalogs: { + default: { + 'vite-plus': '0.3.2', + vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, + }, + }, + }, + }); +}); + describe('catalogs for applications created in existing pnpm workspaces', () => { it('makes references generated by member integration resolvable in a plain workspace', () => { const workspace = integrate(); @@ -113,7 +230,7 @@ describe('catalogs for applications created in existing pnpm workspaces', () => it('leaves templates without a package manifest alone', () => { const content = fs.readFileSync(workspaceFile, 'utf8'); - ensurePnpmCreateCatalogEntries(root, project); + ensureCreateCatalogEntries(root, project, PackageManager.pnpm); expect(fs.readFileSync(workspaceFile, 'utf8')).toBe(content); }); @@ -129,7 +246,7 @@ describe('catalogs for applications created in existing pnpm workspaces', () => }, }), ); - ensurePnpmCreateCatalogEntries(root, project); + ensureCreateCatalogEntries(root, project, PackageManager.pnpm); expect(fs.readFileSync(workspaceFile, 'utf8')).toBe(content); }); }); diff --git a/packages/cli/src/create/bin.ts b/packages/cli/src/create/bin.ts index 6a8680efe6..a2c78ced8d 100644 --- a/packages/cli/src/create/bin.ts +++ b/packages/cli/src/create/bin.ts @@ -7,6 +7,7 @@ import * as prompts from '@voidzero-dev/vite-plus-prompts'; import { getPackageManagerOverride, parseCreateArgs, vitePlusHeader } from '../../binding/index.js'; import { addFrameworkShim, + bunSupportsCatalog, createCatalogDependencyResolver, detectEslintProject, detectFramework, @@ -18,11 +19,13 @@ import { promptEslintMigration, promptPrettierMigration, promptTsupMigration, + readBunCatalogDependencyResolver, rewriteMonorepo, rewriteMonorepoProject, rewriteStandaloneProject, setPackageManager, shouldSkipStagedMigrationForHooks, + supportsCatalog, } from '../migration/migrator.ts'; import { DependencyType, PackageManager, type WorkspaceInfo } from '../types/index.ts'; import { @@ -92,7 +95,7 @@ import { BuiltinTemplate, TemplateType } from './templates/types.ts'; import { deriveDefaultPackageName, detectLauncherPackageManager, - ensurePnpmCreateCatalogEntries, + ensureCreateCatalogEntries, ensureDefaultGitignoreEntries, ensureGitignoreVsCodeEditorConfigs, formatLocalVpCommand, @@ -1031,6 +1034,9 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h packageManagerVersion: workspaceInfo.downloadPackageManager.version, projectDir, }); + if (installSummary.status === 'failed') { + process.exitCode = installSummary.exitCode || 1; + } return; } // #endregion @@ -1317,15 +1323,22 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h shouldSetupHooks, workspaceInfo.packageManager, ); + const bunWorkspace = + workspaceInfo.packageManager === PackageManager.bun + ? readJsonFile(path.join(workspaceInfo.rootDir, 'package.json')) + : undefined; + const supportCatalog = bunWorkspace + ? bunSupportsCatalog(bunWorkspace, workspaceInfo.packageManagerVersion) + : supportsCatalog(workspaceInfo.packageManager, workspaceInfo.packageManagerVersion); rewriteMonorepoProject( fullPath, workspaceInfo.packageManager, skipStagedMigration, compactOutput, undefined, - workspaceInfo.packageManager === PackageManager.pnpm - ? createCatalogDependencyResolver(workspaceInfo.rootDir, workspaceInfo.packageManager) - : undefined, + bunWorkspace + ? readBunCatalogDependencyResolver(bunWorkspace) + : createCatalogDependencyResolver(workspaceInfo.rootDir, workspaceInfo.packageManager), { rootDir: workspaceInfo.rootDir, packages: discoverWorkspacePackages( @@ -1333,10 +1346,10 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h workspaceInfo.rootDir, ), }, + false, + supportCatalog, ); - if (workspaceInfo.packageManager === PackageManager.pnpm) { - ensurePnpmCreateCatalogEntries(workspaceInfo.rootDir, fullPath); - } + ensureCreateCatalogEntries(workspaceInfo.rootDir, fullPath, workspaceInfo.packageManager); for (const framework of detectFramework(fullPath)) { if (!hasFrameworkShim(fullPath, framework)) { addFrameworkShim(fullPath, framework); @@ -1415,6 +1428,9 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h packageManagerVersion: workspaceInfo.downloadPackageManager.version, projectDir, }); + if (installSummary?.status === 'failed') { + process.exitCode = installSummary.exitCode || 1; + } // #endregion } diff --git a/packages/cli/src/create/utils.ts b/packages/cli/src/create/utils.ts index 83fbddb9e2..94c23bd48e 100644 --- a/packages/cli/src/create/utils.ts +++ b/packages/cli/src/create/utils.ts @@ -4,6 +4,7 @@ import path from 'node:path'; import validateNpmPackageName from 'validate-npm-package-name'; import { parseDocument } from 'yaml'; +import { readBunCatalogDependencyResolver } from '../migration/migrator/catalog.ts'; import { PackageManager } from '../types/index.ts'; import { VITE_PLUS_NAME, @@ -11,6 +12,7 @@ import { VITE_PLUS_VERSION, } from '../utils/constants.ts'; import { editJsonFile, readJsonFile } from '../utils/json.ts'; +import type { NpmWorkspaces } from '../utils/workspace.ts'; import { getRandomProjectName } from './random-name.ts'; export type CreateEditorOption = string | false | undefined; @@ -18,13 +20,15 @@ export type CreateEditorOption = string | false | undefined; /** Complete only the managed catalog references of a newly created workspace member. * Running the full root migrator here would also change unrelated packages and overrides. */ -export function ensurePnpmCreateCatalogEntries(rootDir: string, projectDir: string): void { - const workspacePath = path.join(rootDir, 'pnpm-workspace.yaml'); +export function ensureCreateCatalogEntries( + rootDir: string, + projectDir: string, + packageManager: PackageManager, +): void { const packageJsonPath = path.join(projectDir, 'package.json'); - if (!fs.existsSync(workspacePath) || !fs.existsSync(packageJsonPath)) { + if (packageManager === PackageManager.npm || !fs.existsSync(packageJsonPath)) { return; } - const doc = parseDocument(fs.readFileSync(workspacePath, 'utf8')); const pkg = readJsonFile(packageJsonPath) as Partial< Record<'dependencies' | 'devDependencies' | 'optionalDependencies', Record> >; @@ -32,24 +36,72 @@ export function ensurePnpmCreateCatalogEntries(rootDir: string, projectDir: stri ...VITE_PLUS_OVERRIDE_PACKAGES, [VITE_PLUS_NAME]: VITE_PLUS_VERSION, }; - let changed = false; - for (const field of ['dependencies', 'devDependencies', 'optionalDependencies'] as const) { - for (const [name, spec] of Object.entries(pkg[field] ?? {})) { - if (!Object.hasOwn(versions, name) || !spec.startsWith('catalog:')) { - continue; - } - const catalogName = spec.slice('catalog:'.length); - const catalogPath = - catalogName && catalogName !== 'default' - ? ['catalogs', catalogName] - : doc.has('catalog') || !doc.hasIn(['catalogs', 'default']) - ? ['catalog'] - : ['catalogs', 'default']; - const entryPath = [...catalogPath, name]; - if (!doc.hasIn(entryPath)) { - doc.setIn(entryPath, versions[name]); + const entries = (['dependencies', 'devDependencies', 'optionalDependencies'] as const) + .flatMap((field) => Object.entries(pkg[field] ?? {})) + .filter(([name, spec]) => Object.hasOwn(versions, name) && spec.startsWith('catalog:')); + if (entries.length === 0) { + return; + } + if (packageManager === PackageManager.bun) { + editJsonFile<{ + workspaces?: NpmWorkspaces; + catalog?: Record; + catalogs?: Record>; + }>(path.join(rootDir, 'package.json'), (root) => { + const nested = + root.workspaces && !Array.isArray(root.workspaces) ? root.workspaces : undefined; + const resolveCatalog = readBunCatalogDependencyResolver(root); + let changed = false; + for (const [name, spec] of entries) { + if (resolveCatalog(spec, name) !== undefined) { + continue; + } + const catalogName = spec.slice('catalog:'.length); + const named = catalogName && catalogName !== 'default'; + // Keep each catalog in its existing location, including older Bun's nested form. + const useNested = + nested && + (named + ? nested.catalogs?.[catalogName] != null || + (root.catalogs?.[catalogName] == null && + (nested.catalog != null || (root.catalog == null && nested.catalogs != null))) + : nested.catalog != null || + nested.catalogs?.default != null || + (root.catalog == null && nested.catalogs != null)); + const target = useNested ? nested : root; + const catalog = named + ? ((target.catalogs ??= {})[catalogName] ??= {}) + : (target.catalog ?? target.catalogs?.default ?? (target.catalog = {})); + catalog[name] = versions[name]; changed = true; } + return changed ? root : undefined; + }); + return; + } + const workspacePath = path.join( + rootDir, + packageManager === PackageManager.yarn ? '.yarnrc.yml' : 'pnpm-workspace.yaml', + ); + if (packageManager === PackageManager.pnpm && !fs.existsSync(workspacePath)) { + return; + } + const doc = parseDocument( + fs.existsSync(workspacePath) ? fs.readFileSync(workspacePath, 'utf8') : '', + ); + let changed = false; + for (const [name, spec] of entries) { + const catalogName = spec.slice('catalog:'.length); + const catalogPath = + catalogName && catalogName !== 'default' + ? ['catalogs', catalogName] + : doc.has('catalog') || !doc.hasIn(['catalogs', 'default']) + ? ['catalog'] + : ['catalogs', 'default']; + const entryPath = [...catalogPath, name]; + if (!doc.hasIn(entryPath)) { + doc.setIn(entryPath, versions[name]); + changed = true; } } if (changed) { From 6a98b9f7f175056fffada5a9f6003c02da94be2f Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 10:14:14 +0900 Subject: [PATCH 02/14] fix(create): respect Yarn and Bun catalog semantics Keep Yarn's named default catalog distinct from its unnamed catalog and use Bun's active catalog configuration without merging root entries. Cover installation and builds in both workspace layouts and preserve existing install-failure exit behavior. --- .../nested-catalogs.json | 15 +++ .../snapshots.toml | 16 +++ .../create_existing_bun_nested_catalogs.md | 50 ++++++++ .../snapshots.toml | 29 +++-- ...ate_existing_yarn_named_default_catalog.md | 69 +++++++++++ .../create_workspace_install_failure.md | 24 ---- .../__tests__/generator-scaffold.spec.ts | 9 +- .../__tests__/workspace-catalog.spec.ts | 117 ++++++++++++++++++ packages/cli/src/create/bin.ts | 6 - packages/cli/src/create/utils.ts | 24 ++-- .../cli/src/migration/migrator/catalog.ts | 96 +++++++------- packages/cli/src/migration/migrator/yarn.ts | 21 ++-- 12 files changed, 368 insertions(+), 108 deletions(-) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/nested-catalogs.json create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_nested_catalogs.md create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_named_default_catalog.md delete mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_workspace_install_failure.md diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/nested-catalogs.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/nested-catalogs.json new file mode 100644 index 0000000000..64567eb456 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/nested-catalogs.json @@ -0,0 +1,15 @@ +{ + "name": "plain-workspace", + "private": true, + "packageManager": "bun@1.4.0", + "workspaces": { + "packages": ["apps/*"], + "catalog": { + "is-number": "7.0.0" + } + }, + "catalog": { + "vite": "0.0.0-unused", + "vite-plus": "0.0.0-unused" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml index 3d0c677818..aca43833b2 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml @@ -11,3 +11,19 @@ steps = [ { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, ] + +[[case]] +name = "create_existing_bun_nested_catalogs" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Bun uses nested catalog configuration without falling back to ignored root entries." +steps = [ + { argv = ["vpt", "cp", "nested-catalogs.json", "package.json"], snapshot = false }, + { argv = ["vp", "install"], comment = "The ignored root catalog does not prevent installation before creation.", snapshot = false }, + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "stat-file", "bun.lock", "--assert", "file"], + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_nested_catalogs.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_nested_catalogs.md new file mode 100644 index 0000000000..924568bdc0 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_nested_catalogs.md @@ -0,0 +1,50 @@ +# create_existing_bun_nested_catalogs + +Bun uses nested catalog configuration without falling back to ignored root entries. + +## `vpt cp nested-catalogs.json package.json` + + +## `vp install` + +The ignored root catalog does not prevent installation before creation. + + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt stat-file bun.lock --assert file` + +``` +bun.lock: file +``` + +## `vpt print-file package.json` + +``` +{ + "name": "plain-workspace", + "private": true, + "packageManager": "bun@1.4.0", + "workspaces": { + "packages": [ + "apps/*" + ], + "catalog": { + "is-number": "7.0.0", + "vite": "npm:@voidzero-dev/vite-plus-core@", + "vite-plus": "" + } + }, + "catalog": { + "vite": "0.0.0-unused", + "vite-plus": "" + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml index 3f03f6ba6f..cda9f8be70 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml @@ -14,28 +14,39 @@ steps = [ ] [[case]] -name = "create_existing_yarn_without_catalog_support" +name = "create_existing_yarn_named_default_catalog" vp = "local" local-registry = true unset-env = ["VP_SKIP_INSTALL", "CI"] -comment = "Yarn before 4.10 receives concrete versions instead of unsupported catalog references." +env = { YARN_NPM_MINIMAL_AGE_GATE = "0" } +comment = "Yarn's named default catalog must remain catalog:default, not catalog:." steps = [ - { argv = ["vpt", "json-edit", "package.json", "packageManager", "yarn@4.9.0"], snapshot = false }, - { argv = ["vpt", "json-edit", "package.json", "resolutions.typescript", "5.9.3"], comment = "Yarn 4.9's built-in TypeScript patch predates TypeScript 7.", snapshot = false }, + { argv = ["vp", "create", "vite:application", "--directory", "apps/seed", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + { argv = ["vpt", "replace-file-content", ".yarnrc.yml", "catalog:\n", "catalogs:\n default:\n"], snapshot = false }, + { argv = ["vpt", "replace-file-content", ".yarnrc.yml", " vite:", " vite:"], snapshot = false }, + { argv = ["vpt", "replace-file-content", ".yarnrc.yml", " vite-plus:", " vite-plus:"], snapshot = false }, + { argv = ["vpt", "json-edit", "apps/seed/package.json", "devDependencies.vite", "catalog:default"], snapshot = false }, + { argv = ["vpt", "json-edit", "apps/seed/package.json", "devDependencies.vite-plus", "catalog:default"], snapshot = false }, + { argv = ["vp", "install"], comment = "Verify that the existing workspace installs before adding another app.", snapshot = false }, { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, - ["vpt", "stat-file", "yarn.lock", "--assert", "file"], + ["vpt", "print-file", ".yarnrc.yml"], ["vpt", "print-file", "apps/web/package.json"], { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, ] [[case]] -name = "create_workspace_install_failure" +name = "create_existing_yarn_without_catalog_support" vp = "local" local-registry = true unset-env = ["VP_SKIP_INSTALL", "CI"] -comment = "Creation reports a failing exit code when workspace dependency installation fails." +comment = "Yarn before 4.10 receives concrete versions instead of unsupported catalog references." steps = [ - { argv = ["vpt", "json-edit", "package.json", "dependencies.missing-dependency", "file:./missing-dependency"], snapshot = false }, - ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], + { argv = ["vpt", "json-edit", "package.json", "packageManager", "yarn@4.9.0"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "resolutions.typescript", "5.9.3"], comment = "Yarn 4.9's built-in TypeScript patch predates TypeScript 7.", snapshot = false }, + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "stat-file", "yarn.lock", "--assert", "file"], + ["vpt", "print-file", "apps/web/package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, ] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_named_default_catalog.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_named_default_catalog.md new file mode 100644 index 0000000000..5b554c297a --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_named_default_catalog.md @@ -0,0 +1,69 @@ +# create_existing_yarn_named_default_catalog + +Yarn's named default catalog must remain catalog:default, not catalog:. + +## `vp create vite:application --directory apps/seed --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt replace-file-content .yarnrc.yml 'catalog: +' 'catalogs: + default: +'` + + +## `vpt replace-file-content .yarnrc.yml ' vite:' ' vite:'` + + +## `vpt replace-file-content .yarnrc.yml ' vite-plus:' ' vite-plus:'` + + +## `vpt json-edit apps/seed/package.json devDependencies.vite catalog:default` + + +## `vpt json-edit apps/seed/package.json devDependencies.vite-plus catalog:default` + + +## `vp install` + +Verify that the existing workspace installs before adding another app. + + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file .yarnrc.yml` + +``` +nodeLinker: node-modules +catalogs: + default: + vite: npm:@voidzero-dev/vite-plus-core@ + vite-plus: +``` + +## `vpt print-file apps/web/package.json` + +``` +{ + "name": "web", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vp dev", + "build": "tsc && vp build", + "preview": "vp preview" + }, + "devDependencies": { + "typescript": "~7.0.2", + "vite": "catalog:default", + "vite-plus": "catalog:default" + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_workspace_install_failure.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_workspace_install_failure.md deleted file mode 100644 index 35536f5011..0000000000 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_workspace_install_failure.md +++ /dev/null @@ -1,24 +0,0 @@ -# create_workspace_install_failure - -Creation reports a failing exit code when workspace dependency installation fails. - -## `vpt json-edit package.json dependencies.missing-dependency file:./missing-dependency` - - -## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` - -**Exit code:** 1 - -``` -● ➤ YN0000: · Yarn - ➤ YN0000: ┌ Resolution step - ➤ YN0001: │ Error: missing-dependency@file:./missing-dependency::locator=plain-workspace%40workspace%3A.: ENOENT: no such file or directory, lstat '/missing-dependency' - ➤ YN0000: └ Completed - ➤ YN0000: · Failed with errors in - -■ -● You may need to run "vp install" manually in -◇ Scaffolded apps/web with Vite application -• Node yarn -→ Next: cd apps/web && vp run -``` diff --git a/packages/cli/src/create/__tests__/generator-scaffold.spec.ts b/packages/cli/src/create/__tests__/generator-scaffold.spec.ts index c49ff43274..e6fd6897bf 100644 --- a/packages/cli/src/create/__tests__/generator-scaffold.spec.ts +++ b/packages/cli/src/create/__tests__/generator-scaffold.spec.ts @@ -124,10 +124,15 @@ describe('generator scaffold dependencies', () => { [PackageManager.pnpm, '10.0.0'], [PackageManager.yarn, '4.10.0'], [PackageManager.bun, '1.3.0'], - ])('resolves catalogs.default for %s %s', async (manager, version) => { + ])('uses installable versions with catalogs.default for %s %s', async (manager, version) => { const pkg = await scaffold(manager, version, { catalogs: { default: { '@types/node': '^22', typescript: '^5' } }, }); - expect(pkg.devDependencies).toEqual({ '@types/node': 'catalog:', typescript: 'catalog:' }); + const { catalog } = readYamlFile(path.join(templatesDir, 'monorepo/pnpm-workspace.yaml')); + expect(pkg.devDependencies).toEqual( + manager === PackageManager.yarn + ? catalog + : { '@types/node': 'catalog:', typescript: 'catalog:' }, + ); }); }); diff --git a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts index 2838460a30..57212c24db 100644 --- a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts +++ b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts @@ -8,6 +8,8 @@ import { stringify } from 'yaml'; import { createCatalogDependencyResolver, rewriteMonorepoProject, + rewriteYarnrcYml, + yarnrcSatisfiesVitePlus, } from '../../migration/migrator.ts'; import { PackageManager } from '../../types/index.ts'; import { VITE_PLUS_OVERRIDE_PACKAGES, VITE_PLUS_VERSION } from '../../utils/constants.ts'; @@ -79,6 +81,16 @@ describe.each([PackageManager.yarn, PackageManager.bun])('%s workspace catalogs' createCatalogDependencyResolver(root, pm), ); ensureCreateCatalogEntries(root, project, pm); + const spec = + kind === 'named' + ? 'catalog:tools' + : kind === 'default' && pm === PackageManager.yarn + ? 'catalog:default' + : 'catalog:'; + expect(readJsonFile(path.join(project, 'package.json')).devDependencies).toEqual({ + vite: spec, + 'vite-plus': spec, + }); const result = pm === PackageManager.yarn ? readYamlFile(file) : readJsonFile(file); const entries = { ...(kind === 'missing' ? { 'vite-plus': VITE_PLUS_VERSION } : existing), @@ -102,6 +114,111 @@ describe.each([PackageManager.yarn, PackageManager.bun])('%s workspace catalogs' ); }); +it('fills the active Bun catalog even when ignored root catalogs have those entries', () => { + const file = path.join(root, 'package.json'); + const ignored = { vite: '0.0.0-unused', 'vite-plus': '0.0.0-unused' }; + fs.writeFileSync( + file, + JSON.stringify({ + workspaces: { packages: ['apps/*'], catalog: { react: '^19.0.0' } }, + catalog: ignored, + catalogs: { tools: ignored }, + }), + ); + const resolver = createCatalogDependencyResolver(root, PackageManager.bun)!; + expect(resolver('catalog:', 'vite')).toBeUndefined(); + expect(resolver('catalog:tools', 'vite')).toBeUndefined(); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { vite: 'catalog:', 'vite-plus': 'catalog:tools' }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.bun); + expect(readJsonFile(file)).toEqual({ + workspaces: { + packages: ['apps/*'], + catalog: { react: '^19.0.0', vite: VITE_PLUS_OVERRIDE_PACKAGES.vite }, + catalogs: { tools: { 'vite-plus': VITE_PLUS_VERSION } }, + }, + catalog: ignored, + catalogs: { tools: ignored }, + }); +}); + +it('keeps Yarn default and named default catalog references distinct', () => { + fs.writeFileSync( + path.join(root, '.yarnrc.yml'), + stringify({ + catalog: { vite: '^8.0.0' }, + catalogs: { default: { 'vite-plus': '0.3.2' } }, + }), + ); + const resolver = createCatalogDependencyResolver(root, PackageManager.yarn)!; + expect(resolver.preferredCatalogSpec).toBe('catalog:default'); + expect(resolver('catalog:', 'vite')).toBe('^8.0.0'); + expect(resolver('catalog:', 'vite-plus')).toBeUndefined(); + expect(resolver('catalog:default', 'vite-plus')).toBe('0.3.2'); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { vite: 'catalog:default', 'vite-plus': 'catalog:default' }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.yarn); + expect(readYamlFile(path.join(root, '.yarnrc.yml'))).toEqual({ + catalog: { vite: '^8.0.0' }, + catalogs: { default: { 'vite-plus': '0.3.2', vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } }, + }); +}); + +it('uses the same named default catalog when migrating Yarn settings', () => { + const file = path.join(root, '.yarnrc.yml'); + fs.writeFileSync( + file, + stringify({ + catalog: { react: '^19.0.0' }, + catalogs: { default: { 'vite-plus': '0.3.2' } }, + }), + ); + rewriteYarnrcYml(root, false, new Set(), new Set(), true, false); + const config = readYamlFile(file); + expect(config.catalog).toEqual({ react: '^19.0.0' }); + expect(config).toMatchObject({ + catalogs: { + default: { 'vite-plus': VITE_PLUS_VERSION, vite: VITE_PLUS_OVERRIDE_PACKAGES.vite }, + }, + }); + expect(yarnrcSatisfiesVitePlus(root, false, true, false)).toBe(true); +}); + +it('uses Bun catalogs.default before its catalog shorthand', () => { + const file = path.join(root, 'package.json'); + fs.writeFileSync( + file, + JSON.stringify({ + workspaces: ['apps/*'], + catalog: { vite: '0.0.0-unused' }, + catalogs: { default: { 'vite-plus': '0.3.2' } }, + }), + ); + const resolver = createCatalogDependencyResolver(root, PackageManager.bun)!; + expect(resolver('catalog:', 'vite')).toBeUndefined(); + expect(resolver('catalog:default', 'vite-plus')).toBe('0.3.2'); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { vite: 'catalog:', 'vite-plus': 'catalog:' }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.bun); + expect(readJsonFile(file)).toEqual({ + workspaces: ['apps/*'], + catalog: { vite: '0.0.0-unused' }, + catalogs: { default: { 'vite-plus': '0.3.2', vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } }, + }); +}); + it('fills Bun nested named catalogs without moving or replacing existing settings', () => { const file = path.join(root, 'package.json'); fs.writeFileSync( diff --git a/packages/cli/src/create/bin.ts b/packages/cli/src/create/bin.ts index a2c78ced8d..79704ecef6 100644 --- a/packages/cli/src/create/bin.ts +++ b/packages/cli/src/create/bin.ts @@ -1034,9 +1034,6 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h packageManagerVersion: workspaceInfo.downloadPackageManager.version, projectDir, }); - if (installSummary.status === 'failed') { - process.exitCode = installSummary.exitCode || 1; - } return; } // #endregion @@ -1428,9 +1425,6 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h packageManagerVersion: workspaceInfo.downloadPackageManager.version, projectDir, }); - if (installSummary?.status === 'failed') { - process.exitCode = installSummary.exitCode || 1; - } // #endregion } diff --git a/packages/cli/src/create/utils.ts b/packages/cli/src/create/utils.ts index 94c23bd48e..72f19eda35 100644 --- a/packages/cli/src/create/utils.ts +++ b/packages/cli/src/create/utils.ts @@ -4,7 +4,7 @@ import path from 'node:path'; import validateNpmPackageName from 'validate-npm-package-name'; import { parseDocument } from 'yaml'; -import { readBunCatalogDependencyResolver } from '../migration/migrator/catalog.ts'; +import { getBunCatalogConfig, readBunCatalogDependencyResolver } from '../migration/migrator.ts'; import { PackageManager } from '../types/index.ts'; import { VITE_PLUS_NAME, @@ -48,8 +48,7 @@ export function ensureCreateCatalogEntries( catalog?: Record; catalogs?: Record>; }>(path.join(rootDir, 'package.json'), (root) => { - const nested = - root.workspaces && !Array.isArray(root.workspaces) ? root.workspaces : undefined; + const target = getBunCatalogConfig(root); const resolveCatalog = readBunCatalogDependencyResolver(root); let changed = false; for (const [name, spec] of entries) { @@ -58,20 +57,9 @@ export function ensureCreateCatalogEntries( } const catalogName = spec.slice('catalog:'.length); const named = catalogName && catalogName !== 'default'; - // Keep each catalog in its existing location, including older Bun's nested form. - const useNested = - nested && - (named - ? nested.catalogs?.[catalogName] != null || - (root.catalogs?.[catalogName] == null && - (nested.catalog != null || (root.catalog == null && nested.catalogs != null))) - : nested.catalog != null || - nested.catalogs?.default != null || - (root.catalog == null && nested.catalogs != null)); - const target = useNested ? nested : root; const catalog = named ? ((target.catalogs ??= {})[catalogName] ??= {}) - : (target.catalog ?? target.catalogs?.default ?? (target.catalog = {})); + : (target.catalogs?.default ?? target.catalog ?? (target.catalog = {})); catalog[name] = versions[name]; changed = true; } @@ -93,9 +81,11 @@ export function ensureCreateCatalogEntries( for (const [name, spec] of entries) { const catalogName = spec.slice('catalog:'.length); const catalogPath = - catalogName && catalogName !== 'default' + catalogName && (catalogName !== 'default' || packageManager === PackageManager.yarn) ? ['catalogs', catalogName] - : doc.has('catalog') || !doc.hasIn(['catalogs', 'default']) + : packageManager === PackageManager.yarn || + doc.has('catalog') || + !doc.hasIn(['catalogs', 'default']) ? ['catalog'] : ['catalogs', 'default']; const entryPath = [...catalogPath, name]; diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index fe85046cb5..3eb65704b0 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -183,8 +183,7 @@ export function bunSupportsCatalog( } // Mirrors `useWorkspacesCatalog` in rewriteBunCatalog. const writesNestedCatalog = - !Array.isArray(workspaces) && - (workspaces.catalog != null || (pkg.catalog == null && workspaces.catalogs != null)); + !Array.isArray(workspaces) && (workspaces.catalog != null || workspaces.catalogs != null); return ( writesNestedCatalog || versionAtLeast(version, BUN_TOP_LEVEL_CATALOG_MIN_VERSION, ['latest', 'canary']) @@ -347,6 +346,7 @@ export function rewritePnpmWorkspaceYaml( usesVitest, vitestEcosystemPackages, catalogAdditions, + PackageManager.pnpm, ); if (!writeWorkspaceSettings) { return; @@ -771,7 +771,7 @@ export function createCatalogDependencyResolver( catalog?: Record; catalogs?: Record>; } | null; - return createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs); + return createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs, packageManager); } if (packageManager === PackageManager.yarn) { const yarnrcYmlPath = path.join(projectPath, '.yarnrc.yml'); @@ -782,7 +782,7 @@ export function createCatalogDependencyResolver( catalog?: Record; catalogs?: Record>; } | null; - return createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs); + return createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs, packageManager); } if (packageManager === PackageManager.bun) { const packageJsonPath = path.join(projectPath, 'package.json'); @@ -794,9 +794,6 @@ export function createCatalogDependencyResolver( catalog?: Record; catalogs?: Record>; }; - // A missing/absent `workspaces.catalog` resolves identically whether the - // fallback is `undefined` (optional chaining) or `{}`, so this shares the - // exact bun catalog resolution used by the in-memory callers. return readBunCatalogDependencyResolver(pkg); } return undefined; @@ -805,18 +802,22 @@ export function createCatalogDependencyResolver( export function createCatalogDependencyResolverFromCatalogs( catalog: Record | undefined, catalogs: Record> | undefined, + packageManager: PackageManager, ): CatalogDependencyResolver { - const preferredCatalogSpec = selectPreferredCatalogSpec(catalog, catalogs); + // Bun's named default overrides its shorthand; Yarn keeps the two catalogs separate. + const defaultCatalog = + packageManager === PackageManager.bun + ? (catalogs?.default ?? catalog) + : packageManager === PackageManager.yarn + ? catalog + : (catalog ?? catalogs?.default); + const preferredCatalogSpec = selectPreferredCatalogSpec(defaultCatalog, catalogs, packageManager); const resolver = (catalogSpec: string, dependencyName: string) => { const catalogName = catalogSpec.slice('catalog:'.length); - // pnpm accepts the default catalog in either `catalog` or - // `catalogs.default`, but rejects a workspace that defines both. Both - // `catalog:` and `catalog:default` resolve through that one logical - // default catalog. - if (catalogName && catalogName !== 'default') { + if (catalogName && (catalogName !== 'default' || packageManager === PackageManager.yarn)) { return catalogs?.[catalogName]?.[dependencyName]; } - return (catalog ?? catalogs?.default)?.[dependencyName]; + return defaultCatalog?.[dependencyName]; }; return Object.assign(resolver, { preferredCatalogSpec }); } @@ -824,6 +825,7 @@ export function createCatalogDependencyResolverFromCatalogs( function selectPreferredCatalogSpec( catalog: Record | undefined, catalogs: Record> | undefined, + packageManager: PackageManager, ): string { const candidates: Array<{ spec: string; values: Record }> = []; if (catalog) { @@ -831,7 +833,10 @@ function selectPreferredCatalogSpec( } for (const [name, values] of Object.entries(catalogs ?? {})) { candidates.push({ - spec: name === 'default' ? 'catalog:' : `catalog:${name}`, + spec: + name === 'default' && packageManager !== PackageManager.yarn + ? 'catalog:' + : `catalog:${name}`, values, }); } @@ -848,11 +853,8 @@ function selectPreferredCatalogSpec( } } - // Reuse either valid spelling of the default catalog. Do not repurpose an - // unrelated named catalog; when no managed/default catalog exists, create - // the conventional top-level `catalog` instead. - if (catalog || catalogs?.default) { - return 'catalog:'; + if (!catalog && catalogs?.default && packageManager === PackageManager.yarn) { + return 'catalog:default'; } return 'catalog:'; } @@ -942,17 +944,25 @@ export function rewriteCatalog( usesVitest: boolean, vitestEcosystemPackages: ReadonlySet, catalogAdditions: ReadonlySet, + packageManager: PackageManager, ): string { const parsed = doc.toJS() as { catalog?: Record; catalogs?: Record>; } | null; - const preferredCatalogSpec = selectPreferredCatalogSpec(parsed?.catalog, parsed?.catalogs); + const preferredCatalogSpec = selectPreferredCatalogSpec( + parsed?.catalog, + parsed?.catalogs, + packageManager, + ); const preferredCatalogName = preferredCatalogSpec.slice('catalog:'.length); const targetPath: readonly string[] = - preferredCatalogName && preferredCatalogName !== 'default' + preferredCatalogName && + (preferredCatalogName !== 'default' || packageManager === PackageManager.yarn) ? ['catalogs', preferredCatalogName] - : doc.has('catalog') || !doc.hasIn(['catalogs', 'default']) + : packageManager === PackageManager.yarn || + doc.has('catalog') || + !doc.hasIn(['catalogs', 'default']) ? ['catalog'] : ['catalogs', 'default']; @@ -1153,16 +1163,14 @@ export function rewriteBunCatalog( // prefer the location the user already chose to avoid moving their config. const workspacesObj = pkg.workspaces && !Array.isArray(pkg.workspaces) ? pkg.workspaces : undefined; - const useWorkspacesCatalog = - workspacesObj?.catalog != null || (pkg.catalog == null && workspacesObj?.catalogs != null); + 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. const { preferredCatalogSpec } = readBunCatalogDependencyResolver(pkg); const preferredName = preferredCatalogSpec.slice('catalog:'.length); - const namedTarget = preferredName - ? (workspacesObj?.catalogs?.[preferredName] ?? pkg.catalogs?.[preferredName]) - : undefined; + const namedTarget = activeCatalogs.catalogs?.[preferredName || 'default']; const defaultCatalog = useWorkspacesCatalog ? workspacesObj?.catalog : pkg.catalog; const catalog: Record = { ...defaultCatalog }; @@ -1406,7 +1414,11 @@ export function readPnpmWorkspaceCatalogDependencyResolver( catalog?: Record; catalogs?: Record>; } | null; - return createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs); + return createCatalogDependencyResolverFromCatalogs( + doc?.catalog, + doc?.catalogs, + PackageManager.pnpm, + ); } export function readPnpmWorkspaceOverrides( @@ -1557,23 +1569,21 @@ export function ensurePnpmWorkspacePackages( return changed; } +export function getBunCatalogConfig(pkg: { + workspaces?: NpmWorkspaces; + catalog?: Record; + catalogs?: Record>; +}) { + const nested = pkg.workspaces && !Array.isArray(pkg.workspaces) ? pkg.workspaces : undefined; + // Bun uses the nested catalog configuration as a whole, without falling back to root entries. + return nested?.catalog != null || nested?.catalogs != null ? nested : pkg; +} + export function readBunCatalogDependencyResolver(pkg: { workspaces?: NpmWorkspaces; catalog?: Record; catalogs?: Record>; }): CatalogDependencyResolver { - const workspacesObj = pkg.workspaces && !Array.isArray(pkg.workspaces) ? pkg.workspaces : {}; - const fromWorkspaces = createCatalogDependencyResolverFromCatalogs( - workspacesObj.catalog, - workspacesObj.catalogs, - ); - const fromPkg = createCatalogDependencyResolverFromCatalogs(pkg.catalog, pkg.catalogs); - const resolver = (catalogSpec: string, dependencyName: string) => - fromWorkspaces(catalogSpec, dependencyName) ?? fromPkg(catalogSpec, dependencyName); - return Object.assign(resolver, { - preferredCatalogSpec: - workspacesObj.catalog || workspacesObj.catalogs - ? fromWorkspaces.preferredCatalogSpec - : fromPkg.preferredCatalogSpec, - }); + const { catalog, catalogs } = getBunCatalogConfig(pkg); + return createCatalogDependencyResolverFromCatalogs(catalog, catalogs, PackageManager.bun); } diff --git a/packages/cli/src/migration/migrator/yarn.ts b/packages/cli/src/migration/migrator/yarn.ts index 2f042e9bfc..2bbcea00d9 100644 --- a/packages/cli/src/migration/migrator/yarn.ts +++ b/packages/cli/src/migration/migrator/yarn.ts @@ -5,7 +5,7 @@ import path from 'node:path'; import { coerce } from 'verkit'; import { Scalar, YAMLSeq } from 'yaml'; -import { type WorkspacePackage } from '../../types/index.ts'; +import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; import { VITEST_AGE_GATE_EXEMPT_PACKAGES, VITE_PLUS_NAME, @@ -393,7 +393,13 @@ export function rewriteYarnrcYml( } // catalog (Yarn >= 4.10.0 only) if (supportCatalog) { - rewriteCatalog(doc, usesVitest, vitestEcosystemPackages, catalogAdditions); + rewriteCatalog( + doc, + usesVitest, + vitestEcosystemPackages, + catalogAdditions, + PackageManager.yarn, + ); } }); } @@ -434,12 +440,13 @@ export function yarnrcSatisfiesVitePlus( if (!supportCatalog) { return Object.hasOwn(doc, 'nodeLinker') && npmPreapprovedSatisfied; } - const resolver = createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs); + const resolver = createCatalogDependencyResolverFromCatalogs( + doc?.catalog, + doc?.catalogs, + PackageManager.yarn, + ); const catalogName = resolver.preferredCatalogSpec.slice('catalog:'.length); - const managedCatalog = - catalogName && catalogName !== 'default' - ? doc?.catalogs?.[catalogName] - : (doc?.catalog ?? doc?.catalogs?.default); + const managedCatalog = catalogName ? doc?.catalogs?.[catalogName] : doc?.catalog; return ( Object.hasOwn(doc, 'nodeLinker') && npmPreapprovedSatisfied && From 2ff5dbfd6fa2acc345972b650663825100457249 Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 10:35:45 +0900 Subject: [PATCH 03/14] refactor(cli): share catalog resolution between create and migrate Move catalog interpretation helpers and their resolver type into utils/catalog.ts so create and migration callers share them without depending on migration internals. Keep catalog writers and runtime behavior unchanged. --- packages/cli/src/create/bin.ts | 2 +- packages/cli/src/create/utils.ts | 2 +- packages/cli/src/migration/migrator/README.md | 2 +- .../cli/src/migration/migrator/catalog.ts | 87 ++---------------- .../src/migration/migrator/orchestrators.ts | 2 +- .../src/migration/migrator/package-json.ts | 2 +- packages/cli/src/migration/migrator/shared.ts | 8 +- .../migration/migrator/vite-plus-bootstrap.ts | 6 +- .../migration/migrator/vitest-ecosystem.ts | 2 +- packages/cli/src/migration/migrator/yarn.ts | 8 +- packages/cli/src/utils/catalog.ts | 89 +++++++++++++++++++ 11 files changed, 109 insertions(+), 101 deletions(-) create mode 100644 packages/cli/src/utils/catalog.ts diff --git a/packages/cli/src/create/bin.ts b/packages/cli/src/create/bin.ts index 79704ecef6..db5aeb2a63 100644 --- a/packages/cli/src/create/bin.ts +++ b/packages/cli/src/create/bin.ts @@ -19,7 +19,6 @@ import { promptEslintMigration, promptPrettierMigration, promptTsupMigration, - readBunCatalogDependencyResolver, rewriteMonorepo, rewriteMonorepoProject, rewriteStandaloneProject, @@ -40,6 +39,7 @@ import { detectGatedBuilds, resolveApproveBuildTargets, } from '../utils/approve-builds.ts'; +import { readBunCatalogDependencyResolver } from '../utils/catalog.ts'; import { unwrapCliParseOutcome } from '../utils/cli-parse.ts'; import { isForceOverrideMode } from '../utils/constants.ts'; import { documentationUrl } from '../utils/documentation.ts'; diff --git a/packages/cli/src/create/utils.ts b/packages/cli/src/create/utils.ts index 72f19eda35..fa82dab343 100644 --- a/packages/cli/src/create/utils.ts +++ b/packages/cli/src/create/utils.ts @@ -4,8 +4,8 @@ import path from 'node:path'; import validateNpmPackageName from 'validate-npm-package-name'; import { parseDocument } from 'yaml'; -import { getBunCatalogConfig, readBunCatalogDependencyResolver } from '../migration/migrator.ts'; import { PackageManager } from '../types/index.ts'; +import { getBunCatalogConfig, readBunCatalogDependencyResolver } from '../utils/catalog.ts'; import { VITE_PLUS_NAME, VITE_PLUS_OVERRIDE_PACKAGES, diff --git a/packages/cli/src/migration/migrator/README.md b/packages/cli/src/migration/migrator/README.md index acd19f4eb8..ac3e6b7e33 100644 --- a/packages/cli/src/migration/migrator/README.md +++ b/packages/cli/src/migration/migrator/README.md @@ -71,7 +71,7 @@ Pick the file by what a function _does_, not by where it happens to be called. time, so they must be imported from a fully-evaluated leaf: ```ts - import { REMOVE_PACKAGES, type CatalogDependencyResolver } from './shared.ts'; + import { REMOVE_PACKAGES, type PackageJsonDependencyField } from './shared.ts'; ``` Keep `shared.ts` a **pure leaf**: it may import external packages and diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index 3eb65704b0..a57e06c15e 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -6,6 +6,13 @@ import { coerce, isGreaterThanOrEqual, isLessThan } from 'verkit'; import { Scalar, YAMLMap, YAMLSeq } from 'yaml'; import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; +import { + createCatalogDependencyResolverFromCatalogs, + getBunCatalogConfig, + readBunCatalogDependencyResolver, + selectPreferredCatalogSpec, + type CatalogDependencyResolver, +} from '../../utils/catalog.ts'; import { VITEST_AGE_GATE_EXEMPT_PACKAGES, VITEST_VERSION, @@ -46,7 +53,6 @@ import { pnpmOverrideKey, readPackageJsonIfExists, vitePeerDependencyRuleRequired, - type CatalogDependencyResolver, type PackageJsonDependencyField, type PnpmPackageJsonSettings, } from './shared.ts'; @@ -799,66 +805,6 @@ export function createCatalogDependencyResolver( return undefined; } -export function createCatalogDependencyResolverFromCatalogs( - catalog: Record | undefined, - catalogs: Record> | undefined, - packageManager: PackageManager, -): CatalogDependencyResolver { - // Bun's named default overrides its shorthand; Yarn keeps the two catalogs separate. - const defaultCatalog = - packageManager === PackageManager.bun - ? (catalogs?.default ?? catalog) - : packageManager === PackageManager.yarn - ? catalog - : (catalog ?? catalogs?.default); - const preferredCatalogSpec = selectPreferredCatalogSpec(defaultCatalog, catalogs, packageManager); - const resolver = (catalogSpec: string, dependencyName: string) => { - const catalogName = catalogSpec.slice('catalog:'.length); - if (catalogName && (catalogName !== 'default' || packageManager === PackageManager.yarn)) { - return catalogs?.[catalogName]?.[dependencyName]; - } - return defaultCatalog?.[dependencyName]; - }; - return Object.assign(resolver, { preferredCatalogSpec }); -} - -function selectPreferredCatalogSpec( - catalog: Record | undefined, - catalogs: Record> | undefined, - packageManager: PackageManager, -): string { - const candidates: Array<{ spec: string; values: Record }> = []; - if (catalog) { - candidates.push({ spec: 'catalog:', values: catalog }); - } - for (const [name, values] of Object.entries(catalogs ?? {})) { - candidates.push({ - spec: - name === 'default' && packageManager !== PackageManager.yarn - ? 'catalog:' - : `catalog:${name}`, - values, - }); - } - - // Keep the managed toolchain together when a project already has a catalog - // for it (for example Vize's `catalogs.vite-stack` and Rari's - // `catalogs.build`). Prefer vite-plus as the strongest signal, followed by - // vite and vitest. Existing dependency references keep their exact catalog - // spec; this choice is for newly injected dependencies and overrides. - for (const dependencyName of [VITE_PLUS_NAME, 'vite', 'vitest']) { - const matching = candidates.find(({ values }) => Object.hasOwn(values, dependencyName)); - if (matching) { - return matching.spec; - } - } - - if (!catalog && catalogs?.default && packageManager === PackageManager.yarn) { - return 'catalog:default'; - } - return 'catalog:'; -} - function getYamlMapScalarStringValue(map: unknown, key: string): string | undefined { if (!(map instanceof YAMLMap)) { return undefined; @@ -1568,22 +1514,3 @@ export function ensurePnpmWorkspacePackages( }); return changed; } - -export function getBunCatalogConfig(pkg: { - workspaces?: NpmWorkspaces; - catalog?: Record; - catalogs?: Record>; -}) { - const nested = pkg.workspaces && !Array.isArray(pkg.workspaces) ? pkg.workspaces : undefined; - // Bun uses the nested catalog configuration as a whole, without falling back to root entries. - return nested?.catalog != null || nested?.catalogs != null ? nested : pkg; -} - -export function readBunCatalogDependencyResolver(pkg: { - workspaces?: NpmWorkspaces; - catalog?: Record; - catalogs?: Record>; -}): CatalogDependencyResolver { - const { catalog, catalogs } = getBunCatalogConfig(pkg); - return createCatalogDependencyResolverFromCatalogs(catalog, catalogs, PackageManager.bun); -} diff --git a/packages/cli/src/migration/migrator/orchestrators.ts b/packages/cli/src/migration/migrator/orchestrators.ts index d32bb6f176..a32408c9da 100644 --- a/packages/cli/src/migration/migrator/orchestrators.ts +++ b/packages/cli/src/migration/migrator/orchestrators.ts @@ -2,6 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { PackageManager, type WorkspaceInfo, type WorkspacePackage } from '../../types/index.ts'; +import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; import { VITE_PLUS_NAME, VITE_PLUS_VERSION, isForceOverrideMode } from '../../utils/constants.ts'; import { editJsonFile, readJsonFile } from '../../utils/json.ts'; import { @@ -68,7 +69,6 @@ import { type MigrationReport } from '../report.ts'; import { PROVIDER_OVERRIDE_DROP_NAMES, pnpmMajor, - type CatalogDependencyResolver, type PnpmPackageJsonSettings, type PreparedOxlintConfigs, } from './shared.ts'; diff --git a/packages/cli/src/migration/migrator/package-json.ts b/packages/cli/src/migration/migrator/package-json.ts index 95f06a2d38..31d313c822 100644 --- a/packages/cli/src/migration/migrator/package-json.ts +++ b/packages/cli/src/migration/migrator/package-json.ts @@ -1,5 +1,6 @@ import { rewriteScripts } from '../../../binding/index.js'; import { PackageManager } from '../../types/index.ts'; +import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; import { VITEST_VERSION, VITE_PLUS_NAME, @@ -32,7 +33,6 @@ import { REMOVE_PACKAGES, VITEST_BROWSER_DEP_NAMES, VITEST_IS_MANAGED_OVERRIDE, - type CatalogDependencyResolver, type PackageJsonDependencyField, } from './shared.ts'; diff --git a/packages/cli/src/migration/migrator/shared.ts b/packages/cli/src/migration/migrator/shared.ts index 95a6cfcf68..ab1444dd1e 100644 --- a/packages/cli/src/migration/migrator/shared.ts +++ b/packages/cli/src/migration/migrator/shared.ts @@ -5,6 +5,7 @@ import * as prompts from '@voidzero-dev/vite-plus-prompts'; import type { OxlintConfig } from 'oxlint'; import { coerce, isLessThan, satisfies, tryParse } from 'verkit'; +import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; import { VITEST_VERSION, VITE_PLUS_OVERRIDE_PACKAGES, @@ -334,13 +335,6 @@ export type PackageJsonDependencyField = | 'peerDependencies' | 'optionalDependencies'; -export type CatalogDependencyResolver = (( - catalogSpec: string, - dependencyName: string, -) => string | undefined) & { - preferredCatalogSpec: string; -}; - export function warnMigration(message: string, report?: MigrationReport) { addMigrationWarning(report, message); if (!report) { diff --git a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts index 7cf4de01ed..dd724b270e 100644 --- a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts +++ b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts @@ -2,6 +2,10 @@ import fs from 'node:fs'; import path from 'node:path'; import { PackageManager, type WorkspaceInfo, type WorkspacePackage } from '../../types/index.ts'; +import { + readBunCatalogDependencyResolver, + type CatalogDependencyResolver, +} from '../../utils/catalog.ts'; import { VITEST_VERSION, VITE_PLUS_NAME, @@ -40,7 +44,6 @@ import { pnpmWorkspaceTsrsTrustPolicyExceptionPending, projectUsesVitestDirectly, pruneLegacyWrapperAliases, - readBunCatalogDependencyResolver, readPnpmWorkspaceCatalogDependencyResolver, readPnpmWorkspaceOverrides, readPnpmWorkspacePeerDependencyRules, @@ -72,7 +75,6 @@ import { managedOverrideKey, pnpmMajor, pnpmOverrideKey, - type CatalogDependencyResolver, type ManagedOverrideKeyStyle, type PnpmPackageJsonSettings, } from './shared.ts'; diff --git a/packages/cli/src/migration/migrator/vitest-ecosystem.ts b/packages/cli/src/migration/migrator/vitest-ecosystem.ts index ba065f75a3..12df14be9d 100644 --- a/packages/cli/src/migration/migrator/vitest-ecosystem.ts +++ b/packages/cli/src/migration/migrator/vitest-ecosystem.ts @@ -4,6 +4,7 @@ import path from 'node:path'; import { YAMLMap } from 'yaml'; import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; +import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; import { VITEST_VERSION, VITE_PLUS_NAME, @@ -30,7 +31,6 @@ import { isPlainRecord, pnpmOverrideKey, vitePeerDependencyRuleRequired, - type CatalogDependencyResolver, type ManagedOverrideKeyStyle, type PackageJsonDependencyField, type PnpmPeerDependencyRules, diff --git a/packages/cli/src/migration/migrator/yarn.ts b/packages/cli/src/migration/migrator/yarn.ts index 2bbcea00d9..3717466c5d 100644 --- a/packages/cli/src/migration/migrator/yarn.ts +++ b/packages/cli/src/migration/migrator/yarn.ts @@ -6,6 +6,7 @@ import { coerce } from 'verkit'; import { Scalar, YAMLSeq } from 'yaml'; import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; +import { createCatalogDependencyResolverFromCatalogs } from '../../utils/catalog.ts'; import { VITEST_AGE_GATE_EXEMPT_PACKAGES, VITE_PLUS_NAME, @@ -13,12 +14,7 @@ import { } from '../../utils/constants.ts'; import { readJsonFile } from '../../utils/json.ts'; import { editYamlFile, readYamlFile, scalarString } from '../../utils/yaml.ts'; -import { - createCatalogDependencyResolverFromCatalogs, - overridesSatisfyVitePlus, - rewriteCatalog, - usesWebdriverioProvider, -} from '../migrator.ts'; +import { overridesSatisfyVitePlus, rewriteCatalog, usesWebdriverioProvider } from '../migrator.ts'; import { type MigrationReport } from '../report.ts'; import { WEBDRIVERIO_PROVIDER, diff --git a/packages/cli/src/utils/catalog.ts b/packages/cli/src/utils/catalog.ts new file mode 100644 index 0000000000..6977a3873a --- /dev/null +++ b/packages/cli/src/utils/catalog.ts @@ -0,0 +1,89 @@ +import { PackageManager } from '../types/index.ts'; +import { VITE_PLUS_NAME } from './constants.ts'; +import type { NpmWorkspaces } from './workspace.ts'; + +export type CatalogDependencyResolver = (( + catalogSpec: string, + dependencyName: string, +) => string | undefined) & { + preferredCatalogSpec: string; +}; + +export function createCatalogDependencyResolverFromCatalogs( + catalog: Record | undefined, + catalogs: Record> | undefined, + packageManager: PackageManager, +): CatalogDependencyResolver { + // Bun's named default overrides its shorthand; Yarn keeps the two catalogs separate. + const defaultCatalog = + packageManager === PackageManager.bun + ? (catalogs?.default ?? catalog) + : packageManager === PackageManager.yarn + ? catalog + : (catalog ?? catalogs?.default); + const preferredCatalogSpec = selectPreferredCatalogSpec(defaultCatalog, catalogs, packageManager); + const resolver = (catalogSpec: string, dependencyName: string) => { + const catalogName = catalogSpec.slice('catalog:'.length); + if (catalogName && (catalogName !== 'default' || packageManager === PackageManager.yarn)) { + return catalogs?.[catalogName]?.[dependencyName]; + } + return defaultCatalog?.[dependencyName]; + }; + return Object.assign(resolver, { preferredCatalogSpec }); +} + +export function selectPreferredCatalogSpec( + catalog: Record | undefined, + catalogs: Record> | undefined, + packageManager: PackageManager, +): string { + const candidates: Array<{ spec: string; values: Record }> = []; + if (catalog) { + candidates.push({ spec: 'catalog:', values: catalog }); + } + for (const [name, values] of Object.entries(catalogs ?? {})) { + candidates.push({ + spec: + name === 'default' && packageManager !== PackageManager.yarn + ? 'catalog:' + : `catalog:${name}`, + values, + }); + } + + // Keep the managed toolchain together when a project already has a catalog + // for it (for example Vize's `catalogs.vite-stack` and Rari's + // `catalogs.build`). Prefer vite-plus as the strongest signal, followed by + // vite and vitest. Existing dependency references keep their exact catalog + // spec; this choice is for newly injected dependencies and overrides. + for (const dependencyName of [VITE_PLUS_NAME, 'vite', 'vitest']) { + const matching = candidates.find(({ values }) => Object.hasOwn(values, dependencyName)); + if (matching) { + return matching.spec; + } + } + + if (!catalog && catalogs?.default && packageManager === PackageManager.yarn) { + return 'catalog:default'; + } + return 'catalog:'; +} + +export function getBunCatalogConfig(pkg: { + workspaces?: NpmWorkspaces; + catalog?: Record; + catalogs?: Record>; +}) { + const nested = pkg.workspaces && !Array.isArray(pkg.workspaces) ? pkg.workspaces : undefined; + // Bun uses the nested catalog configuration as a whole, without falling back to root entries. + return nested?.catalog != null || nested?.catalogs != null ? nested : pkg; +} + +export function readBunCatalogDependencyResolver(pkg: { + workspaces?: NpmWorkspaces; + catalog?: Record; + catalogs?: Record>; +}): CatalogDependencyResolver { + const { catalog, catalogs } = getBunCatalogConfig(pkg); + return createCatalogDependencyResolverFromCatalogs(catalog, catalogs, PackageManager.bun); +} From 62294feef9f743e7b6f6c4dfbc5503561adea71b Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 11:36:13 +0900 Subject: [PATCH 04/14] fix(create): complete aligned Vitest catalog entries Fill missing catalog entries for aligned Vitest packages referenced by a new workspace member. Preserve existing catalog values and leave Vitest packages unmanaged when the Vitest override is absent. Cover pnpm, Yarn, and Bun in unit tests and verify Yarn and Bun creation and frozen installs with CLI snapshots. --- .../snapshots.toml | 17 ++++ ...ate_existing_bun_aligned_vitest_catalog.md | 56 ++++++++++++ .../vitest-template.config.ts | 7 ++ .../vitest-template/index.mjs | 12 +++ .../vitest-template/package.json | 5 ++ .../snapshots.toml | 17 ++++ ...te_existing_yarn_aligned_vitest_catalog.md | 49 ++++++++++ .../vitest-template.config.ts | 7 ++ .../vitest-template/index.mjs | 12 +++ .../vitest-template/package.json | 5 ++ .../__tests__/workspace-catalog.spec.ts | 90 ++++++++++++++++++- packages/cli/src/create/utils.ts | 7 ++ 12 files changed, 283 insertions(+), 1 deletion(-) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_aligned_vitest_catalog.md create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template.config.ts create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/index.mjs create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/package.json create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_aligned_vitest_catalog.md create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template.config.ts create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/index.mjs create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/package.json diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml index aca43833b2..486f61a338 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml @@ -12,6 +12,23 @@ steps = [ { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, ] +[[case]] +name = "create_existing_bun_aligned_vitest_catalog" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Creating a member completes aligned Vitest entries in the named toolchain catalog without changing the default catalog." +steps = [ + { argv = ["vpt", "cp", "vitest-template.config.ts", "vite.config.ts"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalog.@vitest/utils", "^5.0.0"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalogs.tools.vite-plus", "*"], snapshot = false }, + { argv = ["vp", "install"], snapshot = false }, + { argv = ["vp", "create", "vitest-app", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "apps/web/package.json"], + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, +] + [[case]] name = "create_existing_bun_nested_catalogs" vp = "local" diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_aligned_vitest_catalog.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_aligned_vitest_catalog.md new file mode 100644 index 0000000000..aa50a558ee --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_aligned_vitest_catalog.md @@ -0,0 +1,56 @@ +# create_existing_bun_aligned_vitest_catalog + +Creating a member completes aligned Vitest entries in the named toolchain catalog without changing the default catalog. + +## `vpt cp vitest-template.config.ts vite.config.ts` + + +## `vpt json-edit package.json catalog.@vitest/utils ^5.0.0` + + +## `vpt json-edit package.json catalogs.tools.vite-plus *` + + +## `vp install` + + +## `vp create vitest-app --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file apps/web/package.json` + +``` +{ + "name": "web", + "private": true, + "devDependencies": { + "@vitest/utils": "catalog:tools", + "vite-plus": "catalog:tools" + } +} +``` + +## `vpt print-file package.json` + +``` +{ + "catalog": { + "@vitest/utils": "^5.0.0" + }, + "catalogs": { + "tools": { + "vite-plus": "*", + "@vitest/utils": "" + } + }, + "name": "plain-workspace", + "packageManager": "bun@1.4.0", + "private": true, + "workspaces": [ + "apps/*" + ] +} +``` + +## `vp install --frozen-lockfile` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template.config.ts new file mode 100644 index 0000000000..638a6e72b8 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template.config.ts @@ -0,0 +1,7 @@ +export default { + create: { + templates: [ + { name: 'vitest-app', description: 'Create a member with Vitest utilities.', template: './vitest-template' }, + ], + }, +}; diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/index.mjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/index.mjs new file mode 100644 index 0000000000..c5486fd49d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/index.mjs @@ -0,0 +1,12 @@ +#!/usr/bin/env node +import { mkdirSync, writeFileSync } from 'node:fs'; + +mkdirSync('web', { recursive: true }); +writeFileSync('web/package.json', JSON.stringify({ + name: 'web', + private: true, + devDependencies: { + 'vite-plus': 'catalog:tools', + '@vitest/utils': '^5.0.0', + }, +}, null, 2) + '\n'); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/package.json new file mode 100644 index 0000000000..a6af6ce81d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/vitest-template/package.json @@ -0,0 +1,5 @@ +{ + "name": "vitest-template", + "private": true, + "bin": "index.mjs" +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml index cda9f8be70..0fd7a76434 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml @@ -35,6 +35,23 @@ steps = [ { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, ] +[[case]] +name = "create_existing_yarn_aligned_vitest_catalog" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +env = { YARN_NPM_MINIMAL_AGE_GATE = "0" } +comment = "Creating a member completes aligned Vitest entries in the named toolchain catalog without changing the default catalog." +steps = [ + { argv = ["vpt", "cp", "vitest-template.config.ts", "vite.config.ts"], snapshot = false }, + { argv = ["vpt", "write-file", ".yarnrc.yml", "nodeLinker: node-modules\ncatalog:\n '@vitest/utils': '^5.0.0'\ncatalogs:\n tools:\n vite-plus: '*'\n"], snapshot = false }, + { argv = ["vp", "install"], snapshot = false }, + { argv = ["vp", "create", "vitest-app", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "apps/web/package.json"], + ["vpt", "print-file", ".yarnrc.yml"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, +] + [[case]] name = "create_existing_yarn_without_catalog_support" vp = "local" diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_aligned_vitest_catalog.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_aligned_vitest_catalog.md new file mode 100644 index 0000000000..88399ba958 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_aligned_vitest_catalog.md @@ -0,0 +1,49 @@ +# create_existing_yarn_aligned_vitest_catalog + +Creating a member completes aligned Vitest entries in the named toolchain catalog without changing the default catalog. + +## `vpt cp vitest-template.config.ts vite.config.ts` + + +## `vpt write-file .yarnrc.yml 'nodeLinker: node-modules +catalog: + '\''@vitest/utils'\'': '\''^5.0.0'\'' +catalogs: + tools: + vite-plus: '\''*'\'' +'` + + +## `vp install` + + +## `vp create vitest-app --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file apps/web/package.json` + +``` +{ + "name": "web", + "private": true, + "devDependencies": { + "@vitest/utils": "catalog:tools", + "vite-plus": "catalog:tools" + } +} +``` + +## `vpt print-file .yarnrc.yml` + +``` +nodeLinker: node-modules +catalog: + '@vitest/utils': '^5.0.0' +catalogs: + tools: + vite-plus: '*' + '@vitest/utils': +``` + +## `vp install --frozen-lockfile` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template.config.ts new file mode 100644 index 0000000000..638a6e72b8 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template.config.ts @@ -0,0 +1,7 @@ +export default { + create: { + templates: [ + { name: 'vitest-app', description: 'Create a member with Vitest utilities.', template: './vitest-template' }, + ], + }, +}; diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/index.mjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/index.mjs new file mode 100644 index 0000000000..c5486fd49d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/index.mjs @@ -0,0 +1,12 @@ +#!/usr/bin/env node +import { mkdirSync, writeFileSync } from 'node:fs'; + +mkdirSync('web', { recursive: true }); +writeFileSync('web/package.json', JSON.stringify({ + name: 'web', + private: true, + devDependencies: { + 'vite-plus': 'catalog:tools', + '@vitest/utils': '^5.0.0', + }, +}, null, 2) + '\n'); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/package.json new file mode 100644 index 0000000000..a6af6ce81d --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/vitest-template/package.json @@ -0,0 +1,5 @@ +{ + "name": "vitest-template", + "private": true, + "bin": "index.mjs" +} diff --git a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts index 57212c24db..8a92d6a4f9 100644 --- a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts +++ b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts @@ -12,7 +12,11 @@ import { yarnrcSatisfiesVitePlus, } from '../../migration/migrator.ts'; import { PackageManager } from '../../types/index.ts'; -import { VITE_PLUS_OVERRIDE_PACKAGES, VITE_PLUS_VERSION } from '../../utils/constants.ts'; +import { + VITEST_VERSION, + VITE_PLUS_OVERRIDE_PACKAGES, + VITE_PLUS_VERSION, +} from '../../utils/constants.ts'; import { readJsonFile } from '../../utils/json.ts'; import { readYamlFile } from '../../utils/yaml.ts'; import { ensureCreateCatalogEntries } from '../utils.ts'; @@ -49,6 +53,90 @@ function integrate(dependencies: Record = { vite: '^8.0.0' }) { return readYamlFile(workspaceFile); } +it.each([PackageManager.pnpm, PackageManager.yarn, PackageManager.bun])( + 'completes aligned Vitest entries in the selected %s catalog without replacing existing versions', + (pm) => { + const config = { + catalog: { '@vitest/utils': '^4.0.0' }, + catalogs: { tools: { 'vite-plus': '0.3.2', '@vitest/spy': '^4.0.0' } }, + }; + const file = path.join( + root, + { + [PackageManager.pnpm]: 'pnpm-workspace.yaml', + [PackageManager.yarn]: '.yarnrc.yml', + [PackageManager.bun]: 'package.json', + }[pm], + ); + fs.writeFileSync(file, pm === PackageManager.bun ? JSON.stringify(config) : stringify(config)); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { + 'vite-plus': 'catalog:tools', + '@vitest/utils': '^5.0.0', + '@vitest/spy': 'catalog:tools', + }, + }), + ); + rewriteMonorepoProject( + project, + pm, + true, + true, + undefined, + createCatalogDependencyResolver(root, pm), + ); + ensureCreateCatalogEntries(root, project, pm); + expect(readJsonFile(path.join(project, 'package.json')).devDependencies).toMatchObject({ + '@vitest/utils': 'catalog:tools', + '@vitest/spy': 'catalog:tools', + }); + expect(pm === PackageManager.bun ? readJsonFile(file) : readYamlFile(file)).toMatchObject({ + catalog: config.catalog, + catalogs: { tools: { ...config.catalogs.tools, '@vitest/utils': VITEST_VERSION } }, + }); + const before = fs.readFileSync(file, 'utf8'); + ensureCreateCatalogEntries(root, project, pm); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }, +); + +it('only completes referenced install dependencies in the aligned Vitest package set', () => { + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + dependencies: { '@vitest/utils': 'catalog:tools' }, + optionalDependencies: { '@vitest/spy': 'catalog:tools' }, + devDependencies: { '@vitest/expect': 'catalog:tools', '@vitest/mocker': '^5.0.0' }, + peerDependencies: { '@vitest/browser': 'catalog:tools' }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.pnpm); + expect(readYamlFile(workspaceFile)).toEqual({ + packages: ['apps/*'], + catalogs: { tools: { '@vitest/utils': VITEST_VERSION, '@vitest/spy': VITEST_VERSION } }, + }); +}); + +it('leaves Vitest ecosystem catalogs unmanaged when the Vitest override is absent', () => { + const version = VITE_PLUS_OVERRIDE_PACKAGES.vitest; + try { + delete VITE_PLUS_OVERRIDE_PACKAGES.vitest; + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { '@vitest/utils': 'catalog:tools' }, + }), + ); + const before = fs.readFileSync(workspaceFile, 'utf8'); + ensureCreateCatalogEntries(root, project, PackageManager.pnpm); + expect(fs.readFileSync(workspaceFile, 'utf8')).toBe(before); + } finally { + VITE_PLUS_OVERRIDE_PACKAGES.vitest = version; + } +}); + describe.each([PackageManager.yarn, PackageManager.bun])('%s workspace catalogs', (pm) => { it.each(['missing', 'partial', 'named', 'default'] as const)( 'completes a %s catalog without changing existing versions', diff --git a/packages/cli/src/create/utils.ts b/packages/cli/src/create/utils.ts index fa82dab343..b90857c950 100644 --- a/packages/cli/src/create/utils.ts +++ b/packages/cli/src/create/utils.ts @@ -7,11 +7,13 @@ import { parseDocument } from 'yaml'; import { PackageManager } from '../types/index.ts'; import { getBunCatalogConfig, readBunCatalogDependencyResolver } from '../utils/catalog.ts'; import { + VITEST_VERSION, VITE_PLUS_NAME, VITE_PLUS_OVERRIDE_PACKAGES, VITE_PLUS_VERSION, } from '../utils/constants.ts'; import { editJsonFile, readJsonFile } from '../utils/json.ts'; +import { VITEST_EXACT_VERSION_PACKAGES } from '../utils/vitest-ecosystem.ts'; import type { NpmWorkspaces } from '../utils/workspace.ts'; import { getRandomProjectName } from './random-name.ts'; @@ -36,6 +38,11 @@ export function ensureCreateCatalogEntries( ...VITE_PLUS_OVERRIDE_PACKAGES, [VITE_PLUS_NAME]: VITE_PLUS_VERSION, }; + if ('vitest' in VITE_PLUS_OVERRIDE_PACKAGES) { + for (const name of VITEST_EXACT_VERSION_PACKAGES) { + versions[name] ??= VITEST_VERSION; + } + } const entries = (['dependencies', 'devDependencies', 'optionalDependencies'] as const) .flatMap((field) => Object.entries(pkg[field] ?? {})) .filter(([name, spec]) => Object.hasOwn(versions, name) && spec.startsWith('catalog:')); From 7279b190df861c15d559c7b0bd48bcedd70776bf Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 11:58:25 +0900 Subject: [PATCH 05/14] fix(cli): respect Bun's shared default catalog Resolve Bun's default catalog entries from both supported locations. Restore migration's named-target selection so it does not duplicate shorthand entries in catalogs.default. Cover root and nested configuration and verify creation, migration, frozen installs, and builds with Bun 1.4.4. --- .../snapshots.toml | 22 ++++ ...eate_existing_bun_split_default_catalog.md | 94 ++++++++++++++++ .../__tests__/workspace-catalog.spec.ts | 101 ++++++++++++++---- .../cli/src/migration/migrator/catalog.ts | 2 +- packages/cli/src/utils/catalog.ts | 4 +- 5 files changed, 197 insertions(+), 26 deletions(-) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_split_default_catalog.md diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml index 486f61a338..3ba233bd25 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml @@ -12,6 +12,28 @@ steps = [ { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, ] +[[case]] +name = "create_existing_bun_split_default_catalog" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Creating and migrating a member keeps Bun's shared default catalog installable without duplicating entries." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "packageManager", "bun@1.4.4"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalog.vite", "npm:@voidzero-dev/vite-plus-core@*"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalog.vite-plus", "*"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalogs.default.react", "19.2.0"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "devDependencies.react", "catalog:default"], snapshot = false }, + { argv = ["vp", "install"], snapshot = false }, + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "migrate", "--no-interactive"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] + [[case]] name = "create_existing_bun_aligned_vitest_catalog" vp = "local" diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_split_default_catalog.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_split_default_catalog.md new file mode 100644 index 0000000000..edc15c80cf --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_split_default_catalog.md @@ -0,0 +1,94 @@ +# create_existing_bun_split_default_catalog + +Creating and migrating a member keeps Bun's shared default catalog installable without duplicating entries. + +## `vpt json-edit package.json packageManager bun@1.4.4` + + +## `vpt json-edit package.json catalog.vite npm:@voidzero-dev/vite-plus-core@*` + + +## `vpt json-edit package.json catalog.vite-plus *` + + +## `vpt json-edit package.json catalogs.default.react 19.2.0` + + +## `vpt json-edit package.json devDependencies.react catalog:default` + + +## `vp install` + + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file package.json` + +``` +{ + "catalog": { + "vite": "npm:@voidzero-dev/vite-plus-core@*", + "vite-plus": "*" + }, + "catalogs": { + "default": { + "react": "19.2.0" + } + }, + "devDependencies": { + "react": "catalog:default" + }, + "name": "plain-workspace", + "packageManager": "bun@1.4.4", + "private": true, + "workspaces": [ + "apps/*" + ] +} +``` + +## `vp install --frozen-lockfile` + + +## `vp migrate --no-interactive` + + +## `vpt print-file package.json` + +``` +{ + "name": "plain-workspace", + "private": true, + "workspaces": [ + "apps/*" + ], + "scripts": { + "prepare": "vp config" + }, + "devDependencies": { + "react": "catalog:default", + "vite": "catalog:", + "vite-plus": "catalog:" + }, + "overrides": { + "vite": "catalog:" + }, + "packageManager": "bun@1.4.4", + "catalog": { + "vite": "npm:@voidzero-dev/vite-plus-core@", + "vite-plus": "" + }, + "catalogs": { + "default": { + "react": "19.2.0" + } + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts index 8a92d6a4f9..5eaa6bbbdb 100644 --- a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts +++ b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts @@ -7,6 +7,7 @@ import { stringify } from 'yaml'; import { createCatalogDependencyResolver, + rewriteBunCatalog, rewriteMonorepoProject, rewriteYarnrcYml, yarnrcSatisfiesVitePlus, @@ -280,30 +281,84 @@ it('uses the same named default catalog when migrating Yarn settings', () => { expect(yarnrcSatisfiesVitePlus(root, false, true, false)).toBe(true); }); -it('uses Bun catalogs.default before its catalog shorthand', () => { - const file = path.join(root, 'package.json'); - fs.writeFileSync( - file, - JSON.stringify({ - workspaces: ['apps/*'], - catalog: { vite: '0.0.0-unused' }, - catalogs: { default: { 'vite-plus': '0.3.2' } }, - }), - ); - const resolver = createCatalogDependencyResolver(root, PackageManager.bun)!; - expect(resolver('catalog:', 'vite')).toBeUndefined(); - expect(resolver('catalog:default', 'vite-plus')).toBe('0.3.2'); - fs.writeFileSync( - path.join(project, 'package.json'), - JSON.stringify({ - devDependencies: { vite: 'catalog:', 'vite-plus': 'catalog:' }, - }), +describe.each(['root', 'nested'])('Bun %s shared default catalog', (location) => { + const config = { + catalog: { vite: '^8.0.0', 'vite-plus': '0.3.2', '@vitest/spy': '^5.0.0' }, + catalogs: { default: { react: '^19.0.0' } }, + }; + let file: string; + + beforeEach(() => { + file = path.join(root, 'package.json'); + fs.writeFileSync( + file, + JSON.stringify( + location === 'nested' + ? { workspaces: { packages: ['apps/*'], ...config } } + : { workspaces: ['apps/*'], ...config }, + ), + ); + }); + + it.each(['catalog:', 'catalog:default'])( + 'resolves and completes %s without duplicating existing entries', + (spec) => { + const resolver = createCatalogDependencyResolver(root, PackageManager.bun)!; + expect(resolver(spec, 'vite')).toBe('^8.0.0'); + expect(resolver(spec, 'vite-plus')).toBe('0.3.2'); + expect(resolver(spec, 'react')).toBe('^19.0.0'); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { + vite: spec, + 'vite-plus': spec, + '@vitest/spy': spec, + '@vitest/utils': spec, + }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.bun); + const result = readJsonFile(file); + const active = (location === 'nested' ? result.workspaces : result) as typeof config; + expect(active.catalog).toEqual(config.catalog); + expect(active.catalogs).toEqual({ + default: { react: '^19.0.0', '@vitest/utils': VITEST_VERSION }, + }); + const before = fs.readFileSync(file, 'utf8'); + ensureCreateCatalogEntries(root, project, PackageManager.bun); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }, ); - ensureCreateCatalogEntries(root, project, PackageManager.bun); - expect(readJsonFile(file)).toEqual({ - workspaces: ['apps/*'], - catalog: { vite: '0.0.0-unused' }, - catalogs: { default: { 'vite-plus': '0.3.2', vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } }, + + it('migrates entries in their existing locations and adds only missing entries', () => { + const ecosystem = new Set(['@vitest/spy', '@vitest/utils']); + rewriteBunCatalog(root, false, ecosystem); + const result = readJsonFile(file); + const active = (location === 'nested' ? result.workspaces : result) as typeof config; + expect(active.catalog).toEqual({ + vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, + 'vite-plus': VITE_PLUS_VERSION, + '@vitest/spy': VITEST_VERSION, + '@vitest/utils': VITEST_VERSION, + }); + expect(active.catalogs).toEqual(config.catalogs); + const before = fs.readFileSync(file, 'utf8'); + rewriteBunCatalog(root, false, ecosystem); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }); + + it('does not silently remove pre-existing duplicate entries', () => { + const contents = readJsonFile(file); + const active = (location === 'nested' ? contents.workspaces : contents) as typeof config; + Object.assign(active.catalog, { react: active.catalogs.default.react }); + fs.writeFileSync(file, JSON.stringify(contents)); + rewriteBunCatalog(root, false, new Set()); + const result = readJsonFile(file); + expect(location === 'nested' ? result.workspaces : result).toMatchObject({ + catalog: { react: '^19.0.0' }, + catalogs: { default: { react: '^19.0.0' } }, + }); }); }); diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index a57e06c15e..b11004d5ea 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -1116,7 +1116,7 @@ export function rewriteBunCatalog( // takes them instead of a newly created default catalog. const { preferredCatalogSpec } = readBunCatalogDependencyResolver(pkg); const preferredName = preferredCatalogSpec.slice('catalog:'.length); - const namedTarget = activeCatalogs.catalogs?.[preferredName || 'default']; + const namedTarget = preferredName ? activeCatalogs.catalogs?.[preferredName] : undefined; const defaultCatalog = useWorkspacesCatalog ? workspacesObj?.catalog : pkg.catalog; const catalog: Record = { ...defaultCatalog }; diff --git a/packages/cli/src/utils/catalog.ts b/packages/cli/src/utils/catalog.ts index 6977a3873a..e679358151 100644 --- a/packages/cli/src/utils/catalog.ts +++ b/packages/cli/src/utils/catalog.ts @@ -14,10 +14,10 @@ export function createCatalogDependencyResolverFromCatalogs( catalogs: Record> | undefined, packageManager: PackageManager, ): CatalogDependencyResolver { - // Bun's named default overrides its shorthand; Yarn keeps the two catalogs separate. + // Bun merges the two default catalogs; Yarn keeps them separate. const defaultCatalog = packageManager === PackageManager.bun - ? (catalogs?.default ?? catalog) + ? { ...catalog, ...catalogs?.default } : packageManager === PackageManager.yarn ? catalog : (catalog ?? catalogs?.default); From 01cf4593a8262839daf9948f156644177c416acd Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 12:02:06 +0900 Subject: [PATCH 06/14] refactor(cli): share YAML catalog path selection Use one helper to map pnpm and Yarn catalog references to their YAML paths. Keep create's explicit references and migrate's preferred-catalog selection unchanged. --- packages/cli/src/create/utils.ts | 16 ++++++---------- packages/cli/src/migration/migrator/catalog.ts | 12 ++---------- packages/cli/src/utils/catalog.ts | 16 ++++++++++++++++ 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/packages/cli/src/create/utils.ts b/packages/cli/src/create/utils.ts index b90857c950..20eb30e78b 100644 --- a/packages/cli/src/create/utils.ts +++ b/packages/cli/src/create/utils.ts @@ -5,7 +5,11 @@ import validateNpmPackageName from 'validate-npm-package-name'; import { parseDocument } from 'yaml'; import { PackageManager } from '../types/index.ts'; -import { getBunCatalogConfig, readBunCatalogDependencyResolver } from '../utils/catalog.ts'; +import { + getBunCatalogConfig, + getYamlCatalogPath, + readBunCatalogDependencyResolver, +} from '../utils/catalog.ts'; import { VITEST_VERSION, VITE_PLUS_NAME, @@ -86,15 +90,7 @@ export function ensureCreateCatalogEntries( ); let changed = false; for (const [name, spec] of entries) { - const catalogName = spec.slice('catalog:'.length); - const catalogPath = - catalogName && (catalogName !== 'default' || packageManager === PackageManager.yarn) - ? ['catalogs', catalogName] - : packageManager === PackageManager.yarn || - doc.has('catalog') || - !doc.hasIn(['catalogs', 'default']) - ? ['catalog'] - : ['catalogs', 'default']; + const catalogPath = getYamlCatalogPath(doc, spec, packageManager); const entryPath = [...catalogPath, name]; if (!doc.hasIn(entryPath)) { doc.setIn(entryPath, versions[name]); diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index b11004d5ea..b2b9937ef8 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -9,6 +9,7 @@ import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; import { createCatalogDependencyResolverFromCatalogs, getBunCatalogConfig, + getYamlCatalogPath, readBunCatalogDependencyResolver, selectPreferredCatalogSpec, type CatalogDependencyResolver, @@ -901,16 +902,7 @@ export function rewriteCatalog( parsed?.catalogs, packageManager, ); - const preferredCatalogName = preferredCatalogSpec.slice('catalog:'.length); - const targetPath: readonly string[] = - preferredCatalogName && - (preferredCatalogName !== 'default' || packageManager === PackageManager.yarn) - ? ['catalogs', preferredCatalogName] - : packageManager === PackageManager.yarn || - doc.has('catalog') || - !doc.hasIn(['catalogs', 'default']) - ? ['catalog'] - : ['catalogs', 'default']; + const targetPath = getYamlCatalogPath(doc, preferredCatalogSpec, packageManager); rewriteYamlCatalogAtPath( doc, diff --git a/packages/cli/src/utils/catalog.ts b/packages/cli/src/utils/catalog.ts index e679358151..f7c1fdcb51 100644 --- a/packages/cli/src/utils/catalog.ts +++ b/packages/cli/src/utils/catalog.ts @@ -1,6 +1,7 @@ import { PackageManager } from '../types/index.ts'; import { VITE_PLUS_NAME } from './constants.ts'; import type { NpmWorkspaces } from './workspace.ts'; +import type { YamlDocument } from './yaml.ts'; export type CatalogDependencyResolver = (( catalogSpec: string, @@ -69,6 +70,21 @@ export function selectPreferredCatalogSpec( return 'catalog:'; } +export function getYamlCatalogPath( + doc: YamlDocument, + catalogSpec: string, + packageManager: PackageManager, +): string[] { + const catalogName = catalogSpec.slice('catalog:'.length); + return catalogName && (catalogName !== 'default' || packageManager === PackageManager.yarn) + ? ['catalogs', catalogName] + : packageManager === PackageManager.yarn || + doc.has('catalog') || + !doc.hasIn(['catalogs', 'default']) + ? ['catalog'] + : ['catalogs', 'default']; +} + export function getBunCatalogConfig(pkg: { workspaces?: NpmWorkspaces; catalog?: Record; From e0794c76a9b199dfe254b4ef9171854ff8c83e9c Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 12:29:39 +0900 Subject: [PATCH 07/14] fix(migrate): avoid duplicate Bun default catalog entries Treat catalog and catalogs.default as one logical default catalog when adding managed dependencies. Update existing entries in place and reuse catalogs.default without creating a conflicting shorthand catalog. Keep the write decision in a private helper and cover default-only and split catalogs at both root and nested locations. Add a CLI regression case that verifies creation, migration, frozen installs, and builds with Bun 1.4.4. --- .../snapshots.toml | 21 +++++ ...eate_existing_bun_named_default_catalog.md | 87 +++++++++++++++++++ .../__tests__/workspace-catalog.spec.ts | 42 ++++++++- .../cli/src/migration/migrator/catalog.ts | 49 +++++++++-- 4 files changed, 190 insertions(+), 9 deletions(-) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_named_default_catalog.md diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml index 3ba233bd25..2ae1f88334 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml @@ -34,6 +34,27 @@ steps = [ { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, ] +[[case]] +name = "create_existing_bun_named_default_catalog" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Creating and migrating a member reuses Bun's named default catalog without creating a duplicate shorthand catalog." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "packageManager", "bun@1.4.4"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalogs.default.vite-plus", "*"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "catalogs.default.react", "19.2.0"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "devDependencies.react", "catalog:default"], snapshot = false }, + { argv = ["vp", "install"], snapshot = false }, + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "migrate", "--no-interactive"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] + [[case]] name = "create_existing_bun_aligned_vitest_catalog" vp = "local" diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_named_default_catalog.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_named_default_catalog.md new file mode 100644 index 0000000000..ab00799adb --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_named_default_catalog.md @@ -0,0 +1,87 @@ +# create_existing_bun_named_default_catalog + +Creating and migrating a member reuses Bun's named default catalog without creating a duplicate shorthand catalog. + +## `vpt json-edit package.json packageManager bun@1.4.4` + + +## `vpt json-edit package.json catalogs.default.vite-plus *` + + +## `vpt json-edit package.json catalogs.default.react 19.2.0` + + +## `vpt json-edit package.json devDependencies.react catalog:default` + + +## `vp install` + + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file package.json` + +``` +{ + "catalogs": { + "default": { + "react": "19.2.0", + "vite-plus": "*", + "vite": "npm:@voidzero-dev/vite-plus-core@" + } + }, + "devDependencies": { + "react": "catalog:default" + }, + "name": "plain-workspace", + "packageManager": "bun@1.4.4", + "private": true, + "workspaces": [ + "apps/*" + ] +} +``` + +## `vp install --frozen-lockfile` + + +## `vp migrate --no-interactive` + + +## `vpt print-file package.json` + +``` +{ + "name": "plain-workspace", + "private": true, + "workspaces": [ + "apps/*" + ], + "scripts": { + "prepare": "vp config" + }, + "devDependencies": { + "react": "catalog:default", + "vite": "catalog:", + "vite-plus": "catalog:" + }, + "overrides": { + "vite": "catalog:" + }, + "packageManager": "bun@1.4.4", + "catalogs": { + "default": { + "react": "19.2.0", + "vite-plus": "", + "vite": "npm:@voidzero-dev/vite-plus-core@" + } + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts index 5eaa6bbbdb..09f33db93d 100644 --- a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts +++ b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts @@ -340,14 +340,52 @@ describe.each(['root', 'nested'])('Bun %s shared default catalog', (location) => vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, 'vite-plus': VITE_PLUS_VERSION, '@vitest/spy': VITEST_VERSION, - '@vitest/utils': VITEST_VERSION, }); - expect(active.catalogs).toEqual(config.catalogs); + expect(active.catalogs).toEqual({ + default: { react: '^19.0.0', '@vitest/utils': VITEST_VERSION }, + }); const before = fs.readFileSync(file, 'utf8'); rewriteBunCatalog(root, false, ecosystem); expect(fs.readFileSync(file, 'utf8')).toBe(before); }); + it.each([ + { name: 'default only', catalog: undefined }, + { name: 'split toolchain', catalog: { vite: '^8.0.0' } }, + { name: 'unrelated shorthand', catalog: { react: '^19.0.0' } }, + ])('migrates $name without duplicating named default entries', ({ catalog }) => { + const initial = { catalog, catalogs: { default: { 'vite-plus': '0.3.2' } } }; + fs.writeFileSync( + file, + JSON.stringify( + location === 'nested' + ? { workspaces: { packages: ['apps/*'], ...initial } } + : { workspaces: ['apps/*'], ...initial }, + ), + ); + rewriteBunCatalog(root, false, new Set()); + const result = readJsonFile(file); + const active = (location === 'nested' ? result.workspaces : result) as { + catalog?: Record; + catalogs: Record>; + }; + expect(active.catalog).toEqual( + catalog && { + ...catalog, + ...(catalog.vite ? { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } : {}), + }, + ); + expect(active.catalogs).toEqual({ + default: { + 'vite-plus': VITE_PLUS_VERSION, + ...(!catalog?.vite ? { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } : {}), + }, + }); + const before = fs.readFileSync(file, 'utf8'); + rewriteBunCatalog(root, false, new Set()); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }); + it('does not silently remove pre-existing duplicate entries', () => { const contents = readJsonFile(file); const active = (location === 'nested' ? contents.workspaces : contents) as typeof config; diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index b2b9937ef8..51bd9b16cb 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -1024,11 +1024,22 @@ function rewriteVitestEcosystemYamlCatalog( } } +function shouldWriteCatalogEntry( + name: string, + catalog: Record, + addMissing: boolean, + otherDefaultCatalog?: Record, +): boolean { + // Bun merges the two default catalogs and rejects names defined in both. + return name in catalog || (addMissing && !Object.hasOwn(otherDefaultCatalog ?? {}, name)); +} + function rewriteCatalogObject( catalog: Record, addMissing: boolean, usesVitest: boolean, vitestEcosystemPackages: ReadonlySet, + otherDefaultCatalog?: Record, ): void { const managed = managedOverridePackages(usesVitest); // Common case (no direct vitest): strip a lingering managed `vitest` catalog @@ -1037,12 +1048,18 @@ function rewriteCatalogObject( removeManagedVitestEntry(catalog); } for (const [key, value] of Object.entries(managed)) { - if (value.startsWith('file:') || (!addMissing && !(key in catalog))) { + if ( + value.startsWith('file:') || + !shouldWriteCatalogEntry(key, catalog, addMissing, otherDefaultCatalog) + ) { continue; } catalog[key] = value; } - if (!VITE_PLUS_VERSION.startsWith('file:') && (addMissing || VITE_PLUS_NAME in catalog)) { + if ( + !VITE_PLUS_VERSION.startsWith('file:') && + shouldWriteCatalogEntry(VITE_PLUS_NAME, catalog, addMissing, otherDefaultCatalog) + ) { catalog[VITE_PLUS_NAME] = VITE_PLUS_VERSION; } for (const name of REMOVE_PACKAGES) { @@ -1055,7 +1072,11 @@ function rewriteCatalogObject( ? new Set([...Object.keys(catalog), ...vitestEcosystemPackages]) : Object.keys(catalog); for (const name of names) { - if (vitestEcosystemPackages.has(name) && isAlignableVitestEcosystemPackage(name)) { + if ( + vitestEcosystemPackages.has(name) && + isAlignableVitestEcosystemPackage(name) && + shouldWriteCatalogEntry(name, catalog, addMissing, otherDefaultCatalog) + ) { catalog[name] = VITEST_VERSION; } } @@ -1067,9 +1088,16 @@ function rewriteCatalogsObject( usesVitest: boolean, vitestEcosystemPackages: ReadonlySet, targetCatalog?: Record, + defaultCatalog?: Record, ): void { - for (const catalog of Object.values(catalogs)) { - rewriteCatalogObject(catalog, catalog === targetCatalog, usesVitest, vitestEcosystemPackages); + for (const [name, catalog] of Object.entries(catalogs)) { + rewriteCatalogObject( + catalog, + catalog === targetCatalog, + usesVitest, + vitestEcosystemPackages, + name === 'default' ? defaultCatalog : undefined, + ); } } @@ -1108,7 +1136,7 @@ export function rewriteBunCatalog( // takes them instead of a newly created default catalog. const { preferredCatalogSpec } = readBunCatalogDependencyResolver(pkg); const preferredName = preferredCatalogSpec.slice('catalog:'.length); - const namedTarget = preferredName ? activeCatalogs.catalogs?.[preferredName] : undefined; + const namedTarget = activeCatalogs.catalogs?.[preferredName || 'default']; const defaultCatalog = useWorkspacesCatalog ? workspacesObj?.catalog : pkg.catalog; const catalog: Record = { ...defaultCatalog }; @@ -1136,13 +1164,20 @@ export function rewriteBunCatalog( usesVitest, vitestEcosystemPackages, namedTarget, + workspacesObj.catalog, ); for (const named of Object.values(workspacesObj.catalogs)) { pruneLegacyWrapperAliases(named); } } if (pkg.catalogs) { - rewriteCatalogsObject(pkg.catalogs, usesVitest, vitestEcosystemPackages, namedTarget); + rewriteCatalogsObject( + pkg.catalogs, + usesVitest, + vitestEcosystemPackages, + namedTarget, + pkg.catalog, + ); for (const named of Object.values(pkg.catalogs)) { pruneLegacyWrapperAliases(named); } From ee126bb89e7c157cfa78ac83a9074b148bc105f5 Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 15:01:52 +0900 Subject: [PATCH 08/14] fix(migrate): preserve pnpm catalog selection order Use the original catalog definition when selecting the preferred pnpm catalog so dependency references and YAML writes agree. Keep Bun's merged default catalog and Yarn's existing behavior unchanged. Cover both declaration orders and verify migration followed by a frozen install with a CLI snapshot. --- .../snapshots.toml | 16 ++++++ .../migrate_existing_pnpm_catalog_order.md | 57 +++++++++++++++++++ .../src/migration/__tests__/migrator.spec.ts | 49 +++++++++++++++- packages/cli/src/utils/catalog.ts | 6 +- 4 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots/migrate_existing_pnpm_catalog_order.md diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots.toml index e6b82e155f..758e58e7b1 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots.toml @@ -11,3 +11,19 @@ steps = [ { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, ] + +[[case]] +name = "migrate_existing_pnpm_catalog_order" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Migration writes Vite+ into the same catalog selected for dependency references when a named catalog precedes the default." +steps = [ + { argv = ["vpt", "write-file", "pnpm-workspace.yaml", "packages:\n - apps/*\ncatalogs:\n legacy:\n vite: 'npm:@voidzero-dev/vite-plus-core@*'\n default:\n vite: 'npm:@voidzero-dev/vite-plus-core@*'\n"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "devDependencies.vite", "catalog:legacy"], snapshot = false }, + { argv = ["vp", "install"], snapshot = false, timeout = 240000 }, + { argv = ["vp", "migrate", "--no-interactive"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + ["vpt", "print-file", "pnpm-workspace.yaml"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots/migrate_existing_pnpm_catalog_order.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots/migrate_existing_pnpm_catalog_order.md new file mode 100644 index 0000000000..b32891fa47 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_pnpm_workspace/snapshots/migrate_existing_pnpm_catalog_order.md @@ -0,0 +1,57 @@ +# migrate_existing_pnpm_catalog_order + +Migration writes Vite+ into the same catalog selected for dependency references when a named catalog precedes the default. + +## `vpt write-file pnpm-workspace.yaml 'packages: + - apps/* +catalogs: + legacy: + vite: '\''npm:@voidzero-dev/vite-plus-core@*'\'' + default: + vite: '\''npm:@voidzero-dev/vite-plus-core@*'\'' +'` + + +## `vpt json-edit package.json devDependencies.vite catalog:legacy` + + +## `vp install` + + +## `vp migrate --no-interactive` + + +## `vpt print-file package.json` + +``` +{ + "name": "plain-workspace", + "private": true, + "scripts": { + "prepare": "vp config" + }, + "devDependencies": { + "vite": "catalog:legacy", + "vite-plus": "catalog:legacy" + }, + "packageManager": "pnpm@11.24.0" +} +``` + +## `vpt print-file pnpm-workspace.yaml` + +``` +packages: + - apps/* +catalogs: + legacy: + vite: npm:@voidzero-dev/vite-plus-core@ + vite-plus: + default: + vite: npm:@voidzero-dev/vite-plus-core@ +overrides: + vite@*: catalog:legacy +``` + +## `vp install --frozen-lockfile` + diff --git a/packages/cli/src/migration/__tests__/migrator.spec.ts b/packages/cli/src/migration/__tests__/migrator.spec.ts index 81cb42e996..4a836d7da3 100644 --- a/packages/cli/src/migration/__tests__/migrator.spec.ts +++ b/packages/cli/src/migration/__tests__/migrator.spec.ts @@ -5,7 +5,7 @@ import path from 'node:path'; import tsrsPkg from 'tsrs/package.json' with { type: 'json' }; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { parseAllDocuments, parse as parseYaml } from 'yaml'; +import { parseAllDocuments, parseDocument, parse as parseYaml } from 'yaml'; import { rewriteScripts } from '../../../binding/index.js'; import { PackageManager } from '../../types/index.js'; @@ -36,6 +36,8 @@ vi.mock('../../utils/constants.js', async (importOriginal) => { const { rewritePackageJson, + createCatalogDependencyResolver, + rewriteCatalog, rewriteStandaloneProject, rewriteMonorepo, rewriteMonorepoProject, @@ -5626,6 +5628,51 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); + it.each([ + ['legacy', 'default'], + ['default', 'legacy'], + ])('keeps pnpm catalog references resolvable when %s precedes %s', (first, second) => { + fs.writeFileSync( + path.join(tmpDir, 'package.json'), + JSON.stringify({ + name: 'catalog-order-workspace', + devDependencies: { vite: 'catalog:legacy' }, + }), + ); + const contents = [ + 'packages: [packages/*]', + 'catalogs:', + ` ${first}:`, + ' vite: ^8.0.0', + ` ${second}:`, + ' vite: ^8.0.0', + '', + ].join('\n'); + fs.writeFileSync(path.join(tmpDir, 'pnpm-workspace.yaml'), contents); + const expectedSpec = first === 'default' ? 'catalog:' : `catalog:${first}`; + const resolver = createCatalogDependencyResolver(tmpDir, PackageManager.pnpm)!; + expect(resolver.preferredCatalogSpec).toBe(expectedSpec); + expect( + rewriteCatalog(parseDocument(contents), false, new Set(), new Set(), PackageManager.pnpm), + ).toBe(resolver.preferredCatalogSpec); + + rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true); + + const pkg = readJson(path.join(tmpDir, 'package.json')) as { + devDependencies: Record; + }; + expect(pkg.devDependencies.vite).toBe('catalog:legacy'); + expect(pkg.devDependencies['vite-plus']).toBe(expectedSpec); + const migratedResolver = createCatalogDependencyResolver(tmpDir, PackageManager.pnpm)!; + expect(migratedResolver(pkg.devDependencies['vite-plus'], 'vite-plus')).toBe('latest'); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { + catalog?: unknown; + catalogs: Record>; + }; + expect(workspace.catalog).toBeUndefined(); + expect(workspace.catalogs[second]['vite-plus']).toBeUndefined(); + }); + it('writes managed dependencies into an active catalogs.default definition', () => { fs.writeFileSync( path.join(tmpDir, 'package.json'), diff --git a/packages/cli/src/utils/catalog.ts b/packages/cli/src/utils/catalog.ts index f7c1fdcb51..3b75dd8b9a 100644 --- a/packages/cli/src/utils/catalog.ts +++ b/packages/cli/src/utils/catalog.ts @@ -22,7 +22,11 @@ export function createCatalogDependencyResolverFromCatalogs( : packageManager === PackageManager.yarn ? catalog : (catalog ?? catalogs?.default); - const preferredCatalogSpec = selectPreferredCatalogSpec(defaultCatalog, catalogs, packageManager); + const preferredCatalogSpec = selectPreferredCatalogSpec( + packageManager === PackageManager.bun ? defaultCatalog : catalog, + catalogs, + packageManager, + ); const resolver = (catalogSpec: string, dependencyName: string) => { const catalogName = catalogSpec.slice('catalog:'.length); if (catalogName && (catalogName !== 'default' || packageManager === PackageManager.yarn)) { From 949a6badb5cf5fe7977951d2800b38569fa8826d Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 15:24:12 +0900 Subject: [PATCH 09/14] refactor(cli): reuse catalog selection rules Share named catalog and Bun configuration checks, route create through the common resolver, and avoid repeated workspace existence checks. Replace nested YAML path conditionals with early returns while preserving catalog precedence. --- packages/cli/src/create/bin.ts | 21 +++++++------ packages/cli/src/create/utils.ts | 11 ++++--- .../cli/src/migration/migrator/catalog.ts | 9 ++---- packages/cli/src/utils/catalog.ts | 30 +++++++++++-------- 4 files changed, 35 insertions(+), 36 deletions(-) diff --git a/packages/cli/src/create/bin.ts b/packages/cli/src/create/bin.ts index db5aeb2a63..d3f6e137d1 100644 --- a/packages/cli/src/create/bin.ts +++ b/packages/cli/src/create/bin.ts @@ -39,7 +39,6 @@ import { detectGatedBuilds, resolveApproveBuildTargets, } from '../utils/approve-builds.ts'; -import { readBunCatalogDependencyResolver } from '../utils/catalog.ts'; import { unwrapCliParseOutcome } from '../utils/cli-parse.ts'; import { isForceOverrideMode } from '../utils/constants.ts'; import { documentationUrl } from '../utils/documentation.ts'; @@ -1320,22 +1319,22 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h shouldSetupHooks, workspaceInfo.packageManager, ); - const bunWorkspace = - workspaceInfo.packageManager === PackageManager.bun - ? readJsonFile(path.join(workspaceInfo.rootDir, 'package.json')) - : undefined; - const supportCatalog = bunWorkspace - ? bunSupportsCatalog(bunWorkspace, workspaceInfo.packageManagerVersion) - : supportsCatalog(workspaceInfo.packageManager, workspaceInfo.packageManagerVersion); + const supportCatalog = supportsCatalog( + workspaceInfo.packageManager, + workspaceInfo.packageManagerVersion, + workspaceInfo.packageManager === PackageManager.bun && + bunSupportsCatalog( + readJsonFile(path.join(workspaceInfo.rootDir, 'package.json')), + workspaceInfo.packageManagerVersion, + ), + ); rewriteMonorepoProject( fullPath, workspaceInfo.packageManager, skipStagedMigration, compactOutput, undefined, - bunWorkspace - ? readBunCatalogDependencyResolver(bunWorkspace) - : createCatalogDependencyResolver(workspaceInfo.rootDir, workspaceInfo.packageManager), + createCatalogDependencyResolver(workspaceInfo.rootDir, workspaceInfo.packageManager), { rootDir: workspaceInfo.rootDir, packages: discoverWorkspacePackages( diff --git a/packages/cli/src/create/utils.ts b/packages/cli/src/create/utils.ts index 20eb30e78b..397ef749ba 100644 --- a/packages/cli/src/create/utils.ts +++ b/packages/cli/src/create/utils.ts @@ -8,6 +8,7 @@ import { PackageManager } from '../types/index.ts'; import { getBunCatalogConfig, getYamlCatalogPath, + isNamedCatalog, readBunCatalogDependencyResolver, } from '../utils/catalog.ts'; import { @@ -67,8 +68,7 @@ export function ensureCreateCatalogEntries( continue; } const catalogName = spec.slice('catalog:'.length); - const named = catalogName && catalogName !== 'default'; - const catalog = named + const catalog = isNamedCatalog(catalogName, packageManager) ? ((target.catalogs ??= {})[catalogName] ??= {}) : (target.catalogs?.default ?? target.catalog ?? (target.catalog = {})); catalog[name] = versions[name]; @@ -82,12 +82,11 @@ export function ensureCreateCatalogEntries( rootDir, packageManager === PackageManager.yarn ? '.yarnrc.yml' : 'pnpm-workspace.yaml', ); - if (packageManager === PackageManager.pnpm && !fs.existsSync(workspacePath)) { + const workspaceExists = fs.existsSync(workspacePath); + if (packageManager === PackageManager.pnpm && !workspaceExists) { return; } - const doc = parseDocument( - fs.existsSync(workspacePath) ? fs.readFileSync(workspacePath, 'utf8') : '', - ); + const doc = parseDocument(workspaceExists ? fs.readFileSync(workspacePath, 'utf8') : ''); let changed = false; for (const [name, spec] of entries) { const catalogPath = getYamlCatalogPath(doc, spec, packageManager); diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index 51bd9b16cb..aa321815a6 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -180,17 +180,12 @@ const BUN_TOP_LEVEL_CATALOG_MIN_VERSION = '1.2.21'; // needs the nested location that `rewriteBunCatalog` keeps in place. Otherwise // `catalog:` edges make `bun install` abort with "vite@catalog: failed to // resolve", so the toolchain edges must stay concrete. -export function bunSupportsCatalog( - pkg: { workspaces?: NpmWorkspaces; catalog?: Record }, - version: string, -): boolean { +export function bunSupportsCatalog(pkg: { workspaces?: NpmWorkspaces }, version: string): boolean { const { workspaces } = pkg; if (workspaces == null) { return false; } - // Mirrors `useWorkspacesCatalog` in rewriteBunCatalog. - const writesNestedCatalog = - !Array.isArray(workspaces) && (workspaces.catalog != null || workspaces.catalogs != null); + const writesNestedCatalog = getBunCatalogConfig(pkg) !== pkg; return ( writesNestedCatalog || versionAtLeast(version, BUN_TOP_LEVEL_CATALOG_MIN_VERSION, ['latest', 'canary']) diff --git a/packages/cli/src/utils/catalog.ts b/packages/cli/src/utils/catalog.ts index 3b75dd8b9a..72b6ecb122 100644 --- a/packages/cli/src/utils/catalog.ts +++ b/packages/cli/src/utils/catalog.ts @@ -10,6 +10,12 @@ export type CatalogDependencyResolver = (( preferredCatalogSpec: string; }; +export function isNamedCatalog(catalogName: string, packageManager: PackageManager): boolean { + return ( + catalogName !== '' && (catalogName !== 'default' || packageManager === PackageManager.yarn) + ); +} + export function createCatalogDependencyResolverFromCatalogs( catalog: Record | undefined, catalogs: Record> | undefined, @@ -29,7 +35,7 @@ export function createCatalogDependencyResolverFromCatalogs( ); const resolver = (catalogSpec: string, dependencyName: string) => { const catalogName = catalogSpec.slice('catalog:'.length); - if (catalogName && (catalogName !== 'default' || packageManager === PackageManager.yarn)) { + if (isNamedCatalog(catalogName, packageManager)) { return catalogs?.[catalogName]?.[dependencyName]; } return defaultCatalog?.[dependencyName]; @@ -48,10 +54,7 @@ export function selectPreferredCatalogSpec( } for (const [name, values] of Object.entries(catalogs ?? {})) { candidates.push({ - spec: - name === 'default' && packageManager !== PackageManager.yarn - ? 'catalog:' - : `catalog:${name}`, + spec: isNamedCatalog(name, packageManager) ? `catalog:${name}` : 'catalog:', values, }); } @@ -80,13 +83,16 @@ export function getYamlCatalogPath( packageManager: PackageManager, ): string[] { const catalogName = catalogSpec.slice('catalog:'.length); - return catalogName && (catalogName !== 'default' || packageManager === PackageManager.yarn) - ? ['catalogs', catalogName] - : packageManager === PackageManager.yarn || - doc.has('catalog') || - !doc.hasIn(['catalogs', 'default']) - ? ['catalog'] - : ['catalogs', 'default']; + if (isNamedCatalog(catalogName, packageManager)) { + return ['catalogs', catalogName]; + } + if (packageManager === PackageManager.yarn || doc.has('catalog')) { + return ['catalog']; + } + if (doc.hasIn(['catalogs', 'default'])) { + return ['catalogs', 'default']; + } + return ['catalog']; } export function getBunCatalogConfig(pkg: { From df470349883812f76092f53beec53d9d84efec20 Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 15:24:22 +0900 Subject: [PATCH 10/14] test(cli): simplify workspace catalog coverage Remove the redundant resolver and writer comparison while retaining migration result checks. Parameterize nested Bun catalog cases without changing the inputs or preservation assertions. --- .../__tests__/workspace-catalog.spec.ts | 86 +++++++------------ .../src/migration/__tests__/migrator.spec.ts | 6 +- 2 files changed, 31 insertions(+), 61 deletions(-) diff --git a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts index 09f33db93d..33080fecfd 100644 --- a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts +++ b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts @@ -400,66 +400,40 @@ describe.each(['root', 'nested'])('Bun %s shared default catalog', (location) => }); }); -it('fills Bun nested named catalogs without moving or replacing existing settings', () => { - const file = path.join(root, 'package.json'); - fs.writeFileSync( - file, - JSON.stringify({ +it.each([ + { name: 'tools', spec: 'catalog:tools' }, + { name: 'default', spec: 'catalog:' }, +])( + 'fills Bun nested $name catalogs without moving or replacing existing settings', + ({ name, spec }) => { + const file = path.join(root, 'package.json'); + const contents = { private: true, - workspaces: { packages: ['apps/*'], catalogs: { tools: { 'vite-plus': '0.3.2' } } }, + workspaces: { packages: ['apps/*'], catalogs: { [name]: { 'vite-plus': '0.3.2' } } }, catalog: { react: '^19.0.0' }, - }), - ); - fs.writeFileSync( - path.join(project, 'package.json'), - JSON.stringify({ - devDependencies: { vite: 'catalog:tools', 'vite-plus': 'catalog:tools' }, - }), - ); - ensureCreateCatalogEntries(root, project, PackageManager.bun); - expect(readJsonFile(file)).toEqual({ - private: true, - workspaces: { - packages: ['apps/*'], - catalogs: { - tools: { - 'vite-plus': '0.3.2', - vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, - }, - }, - }, - catalog: { react: '^19.0.0' }, - }); -}); - -it('keeps Bun nested default catalogs separate from top-level settings', () => { - const file = path.join(root, 'package.json'); - const contents = { - private: true, - workspaces: { packages: ['apps/*'], catalogs: { default: { 'vite-plus': '0.3.2' } } }, - catalog: { react: '^19.0.0' }, - }; - fs.writeFileSync(file, JSON.stringify(contents)); - fs.writeFileSync( - path.join(project, 'package.json'), - JSON.stringify({ - devDependencies: { vite: 'catalog:', 'vite-plus': 'catalog:' }, - }), - ); - ensureCreateCatalogEntries(root, project, PackageManager.bun); - expect(readJsonFile(file)).toEqual({ - ...contents, - workspaces: { - packages: ['apps/*'], - catalogs: { - default: { - 'vite-plus': '0.3.2', - vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, + }; + fs.writeFileSync(file, JSON.stringify(contents)); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { vite: spec, 'vite-plus': spec }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.bun); + expect(readJsonFile(file)).toEqual({ + ...contents, + workspaces: { + packages: ['apps/*'], + catalogs: { + [name]: { + 'vite-plus': '0.3.2', + vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, + }, }, }, - }, - }); -}); + }); + }, +); describe('catalogs for applications created in existing pnpm workspaces', () => { it('makes references generated by member integration resolvable in a plain workspace', () => { diff --git a/packages/cli/src/migration/__tests__/migrator.spec.ts b/packages/cli/src/migration/__tests__/migrator.spec.ts index 4a836d7da3..078057db4e 100644 --- a/packages/cli/src/migration/__tests__/migrator.spec.ts +++ b/packages/cli/src/migration/__tests__/migrator.spec.ts @@ -5,7 +5,7 @@ import path from 'node:path'; import tsrsPkg from 'tsrs/package.json' with { type: 'json' }; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { parseAllDocuments, parseDocument, parse as parseYaml } from 'yaml'; +import { parseAllDocuments, parse as parseYaml } from 'yaml'; import { rewriteScripts } from '../../../binding/index.js'; import { PackageManager } from '../../types/index.js'; @@ -37,7 +37,6 @@ vi.mock('../../utils/constants.js', async (importOriginal) => { const { rewritePackageJson, createCatalogDependencyResolver, - rewriteCatalog, rewriteStandaloneProject, rewriteMonorepo, rewriteMonorepoProject, @@ -5652,9 +5651,6 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { const expectedSpec = first === 'default' ? 'catalog:' : `catalog:${first}`; const resolver = createCatalogDependencyResolver(tmpDir, PackageManager.pnpm)!; expect(resolver.preferredCatalogSpec).toBe(expectedSpec); - expect( - rewriteCatalog(parseDocument(contents), false, new Set(), new Set(), PackageManager.pnpm), - ).toBe(resolver.preferredCatalogSpec); rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true); From 103af51ddadb3925352f434ba2eab1183756d886 Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 16:24:22 +0900 Subject: [PATCH 11/14] fix(cli): preserve separate default catalogs on older Bun Bun only merges catalog and catalogs.default from 1.4.0. Use the resolved package manager version consistently when resolving and completing catalogs during create, migration, and bootstrap. Fall back to the declared package manager version for read-only callers. Keep the two defaults independent on older Bun while preserving duplicate prevention on newer releases. Cover the version boundary, both catalog locations, named-default completion, and repeated migration. Add CLI snapshots for Bun 1.2.14 migration and Bun 1.3.14 creation with frozen installs. --- .../snapshots.toml | 36 ++++++ ...te_existing_bun_legacy_default_catalogs.md | 73 +++++++++++ ...te_existing_bun_legacy_default_catalogs.md | 62 ++++++++++ .../__tests__/generator-scaffold.spec.ts | 30 ++--- .../__tests__/workspace-catalog.spec.ts | 70 +++++++++++ packages/cli/src/create/bin.ts | 13 +- .../cli/src/create/templates/generator.ts | 6 +- packages/cli/src/create/utils.ts | 16 ++- .../src/migration/__tests__/migrator.spec.ts | 117 ++++++++++++++++++ .../cli/src/migration/migrator/catalog.ts | 25 +++- .../src/migration/migrator/orchestrators.ts | 8 +- packages/cli/src/migration/migrator/shared.ts | 23 ++++ .../migration/migrator/vite-plus-bootstrap.ts | 44 +++---- packages/cli/src/utils/catalog.ts | 63 +++++++--- 14 files changed, 516 insertions(+), 70 deletions(-) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_legacy_default_catalogs.md create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/migrate_existing_bun_legacy_default_catalogs.md diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml index 2ae1f88334..75d5fe1d79 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots.toml @@ -55,6 +55,42 @@ steps = [ { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, ] +[[case]] +name = "migrate_existing_bun_legacy_default_catalogs" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Bun 1.2.14 keeps catalog and catalogs.default separate through migration and a second bootstrap pass." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "packageManager", "bun@1.2.14"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "workspaces", '{"packages":["apps/*"],"catalog":{"vite":"npm:@voidzero-dev/vite-plus-core@*"},"catalogs":{"default":{"react":"19.2.0"}}}'], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "devDependencies", '{"vite":"catalog:","react":"catalog:default"}'], snapshot = false }, + { argv = ["vp", "install"], snapshot = false, timeout = 240000 }, + { argv = ["vp", "migrate", "--no-interactive"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "migrate", "--no-interactive"], snapshot = false, timeout = 240000 }, + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, +] + +[[case]] +name = "create_existing_bun_legacy_default_catalogs" +vp = "local" +local-registry = true +unset-env = ["VP_SKIP_INSTALL", "CI"] +comment = "Bun 1.3.14 still needs shorthand references completed in catalog rather than catalogs.default." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "packageManager", "bun@1.3.14"], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "workspaces", '{"packages":["apps/*"],"catalog":{"vite":"npm:@voidzero-dev/vite-plus-core@*"},"catalogs":{"default":{"react":"19.2.0"}}}'], snapshot = false }, + { argv = ["vpt", "json-edit", "package.json", "devDependencies", '{"vite":"catalog:","react":"catalog:default"}'], snapshot = false }, + { argv = ["vp", "install"], snapshot = false, timeout = 240000 }, + { argv = ["vp", "create", "vite:application", "--directory", "apps/web", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", "package.json"], + ["vpt", "print-file", "apps/web/package.json"], + { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, + { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, +] + [[case]] name = "create_existing_bun_aligned_vitest_catalog" vp = "local" diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_legacy_default_catalogs.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_legacy_default_catalogs.md new file mode 100644 index 0000000000..34fb4b035e --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/create_existing_bun_legacy_default_catalogs.md @@ -0,0 +1,73 @@ +# create_existing_bun_legacy_default_catalogs + +Bun 1.3.14 still needs shorthand references completed in catalog rather than catalogs.default. + +## `vpt json-edit package.json packageManager bun@1.3.14` + + +## `vpt json-edit package.json workspaces '{"packages":["apps/*"],"catalog":{"vite":"npm:@voidzero-dev/vite-plus-core@*"},"catalogs":{"default":{"react":"19.2.0"}}}'` + + +## `vpt json-edit package.json devDependencies '{"vite":"catalog:","react":"catalog:default"}'` + + +## `vp install` + + +## `vp create vite:application --directory apps/web --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file package.json` + +``` +{ + "devDependencies": { + "react": "catalog:default", + "vite": "catalog:" + }, + "name": "plain-workspace", + "packageManager": "bun@1.3.14", + "private": true, + "workspaces": { + "catalog": { + "vite": "npm:@voidzero-dev/vite-plus-core@*", + "vite-plus": "" + }, + "catalogs": { + "default": { + "react": "19.2.0" + } + }, + "packages": [ + "apps/*" + ] + } +} +``` + +## `vpt print-file apps/web/package.json` + +``` +{ + "name": "web", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vp dev", + "build": "tsc && vp build", + "preview": "vp preview" + }, + "devDependencies": { + "typescript": "~7.0.2", + "vite": "catalog:", + "vite-plus": "catalog:" + } +} +``` + +## `vp install --frozen-lockfile` + + +## `cd apps/web && vp run build` + diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/migrate_existing_bun_legacy_default_catalogs.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/migrate_existing_bun_legacy_default_catalogs.md new file mode 100644 index 0000000000..3d01051925 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_bun_workspace/snapshots/migrate_existing_bun_legacy_default_catalogs.md @@ -0,0 +1,62 @@ +# migrate_existing_bun_legacy_default_catalogs + +Bun 1.2.14 keeps catalog and catalogs.default separate through migration and a second bootstrap pass. + +## `vpt json-edit package.json packageManager bun@1.2.14` + + +## `vpt json-edit package.json workspaces '{"packages":["apps/*"],"catalog":{"vite":"npm:@voidzero-dev/vite-plus-core@*"},"catalogs":{"default":{"react":"19.2.0"}}}'` + + +## `vpt json-edit package.json devDependencies '{"vite":"catalog:","react":"catalog:default"}'` + + +## `vp install` + + +## `vp migrate --no-interactive` + + +## `vpt print-file package.json` + +``` +{ + "name": "plain-workspace", + "private": true, + "workspaces": { + "catalog": { + "vite": "npm:@voidzero-dev/vite-plus-core@", + "vite-plus": "" + }, + "catalogs": { + "default": { + "react": "19.2.0" + } + }, + "packages": [ + "apps/*" + ] + }, + "scripts": { + "prepare": "vp config" + }, + "devDependencies": { + "react": "catalog:default", + "vite": "catalog:", + "vite-plus": "catalog:" + }, + "overrides": { + "vite": "catalog:" + }, + "packageManager": "bun@1.2.14" +} +``` + +## `vp install --frozen-lockfile` + + +## `vp migrate --no-interactive` + + +## `vp install --frozen-lockfile` + diff --git a/packages/cli/src/create/__tests__/generator-scaffold.spec.ts b/packages/cli/src/create/__tests__/generator-scaffold.spec.ts index e6fd6897bf..17b2fc9d84 100644 --- a/packages/cli/src/create/__tests__/generator-scaffold.spec.ts +++ b/packages/cli/src/create/__tests__/generator-scaffold.spec.ts @@ -121,18 +121,20 @@ describe('generator scaffold dependencies', () => { }); it.each([ - [PackageManager.pnpm, '10.0.0'], - [PackageManager.yarn, '4.10.0'], - [PackageManager.bun, '1.3.0'], - ])('uses installable versions with catalogs.default for %s %s', async (manager, version) => { - const pkg = await scaffold(manager, version, { - catalogs: { default: { '@types/node': '^22', typescript: '^5' } }, - }); - const { catalog } = readYamlFile(path.join(templatesDir, 'monorepo/pnpm-workspace.yaml')); - expect(pkg.devDependencies).toEqual( - manager === PackageManager.yarn - ? catalog - : { '@types/node': 'catalog:', typescript: 'catalog:' }, - ); - }); + [PackageManager.pnpm, '10.0.0', true], + [PackageManager.yarn, '4.10.0', false], + [PackageManager.bun, '1.3.0', false], + [PackageManager.bun, '1.4.0', true], + ] as const)( + 'uses installable versions with catalogs.default for %s %s', + async (manager, version, sharedDefault) => { + const pkg = await scaffold(manager, version, { + catalogs: { default: { '@types/node': '^22', typescript: '^5' } }, + }); + const { catalog } = readYamlFile(path.join(templatesDir, 'monorepo/pnpm-workspace.yaml')); + expect(pkg.devDependencies).toEqual( + sharedDefault ? { '@types/node': 'catalog:', typescript: 'catalog:' } : catalog, + ); + }, + ); }); diff --git a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts index 33080fecfd..86bcdf59d9 100644 --- a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts +++ b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts @@ -435,6 +435,76 @@ it.each([ }, ); +it.each(['1.2.14', '1.3.14', '1.4.0'])( + 'completes references in the correct default catalog on Bun %s', + (version) => { + const file = path.join(root, 'package.json'); + fs.writeFileSync( + file, + JSON.stringify({ + private: true, + workspaces: { + packages: ['apps/*'], + catalog: { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite }, + catalogs: { default: { react: '^19.0.0' } }, + }, + }), + ); + fs.writeFileSync( + path.join(project, 'package.json'), + JSON.stringify({ + devDependencies: { vite: 'catalog:default', 'vite-plus': 'catalog:' }, + }), + ); + ensureCreateCatalogEntries(root, project, PackageManager.bun, version); + const merged = version === '1.4.0'; + expect(readJsonFile(file)).toEqual({ + private: true, + workspaces: { + packages: ['apps/*'], + catalog: { + vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, + ...(merged ? {} : { 'vite-plus': VITE_PLUS_VERSION }), + }, + catalogs: { + default: { + react: '^19.0.0', + ...(merged + ? { 'vite-plus': VITE_PLUS_VERSION } + : { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite }), + }, + }, + }, + }); + const before = fs.readFileSync(file, 'utf8'); + ensureCreateCatalogEntries(root, project, PackageManager.bun, version); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }, +); + +it.each([ + { packageManager: 'bun@1.3.14' }, + { devEngines: { packageManager: { name: 'bun', version: '1.3.14' } } }, +])('uses the Bun pin when no resolved version is supplied: %j', (pin) => { + fs.writeFileSync( + path.join(root, 'package.json'), + JSON.stringify({ + ...pin, + workspaces: { + packages: ['apps/*'], + catalog: { vite: '^8.0.0' }, + catalogs: { default: { react: '^19.0.0' } }, + }, + }), + ); + const pinned = createCatalogDependencyResolver(root, PackageManager.bun)!; + expect(pinned('catalog:', 'react')).toBeUndefined(); + expect(pinned('catalog:default', 'vite')).toBeUndefined(); + const resolved = createCatalogDependencyResolver(root, PackageManager.bun, '1.4.0')!; + expect(resolved('catalog:', 'react')).toBe('^19.0.0'); + expect(resolved('catalog:default', 'vite')).toBe('^8.0.0'); +}); + describe('catalogs for applications created in existing pnpm workspaces', () => { it('makes references generated by member integration resolvable in a plain workspace', () => { const workspace = integrate(); diff --git a/packages/cli/src/create/bin.ts b/packages/cli/src/create/bin.ts index d3f6e137d1..01a89ecac2 100644 --- a/packages/cli/src/create/bin.ts +++ b/packages/cli/src/create/bin.ts @@ -1334,7 +1334,11 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h skipStagedMigration, compactOutput, undefined, - createCatalogDependencyResolver(workspaceInfo.rootDir, workspaceInfo.packageManager), + createCatalogDependencyResolver( + workspaceInfo.rootDir, + workspaceInfo.packageManager, + workspaceInfo.packageManagerVersion, + ), { rootDir: workspaceInfo.rootDir, packages: discoverWorkspacePackages( @@ -1345,7 +1349,12 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h false, supportCatalog, ); - ensureCreateCatalogEntries(workspaceInfo.rootDir, fullPath, workspaceInfo.packageManager); + ensureCreateCatalogEntries( + workspaceInfo.rootDir, + fullPath, + workspaceInfo.packageManager, + workspaceInfo.packageManagerVersion, + ); for (const framework of detectFramework(fullPath)) { if (!hasFrameworkShim(fullPath, framework)) { addFrameworkShim(fullPath, framework); diff --git a/packages/cli/src/create/templates/generator.ts b/packages/cli/src/create/templates/generator.ts index aef69f42c7..0ef0570b36 100644 --- a/packages/cli/src/create/templates/generator.ts +++ b/packages/cli/src/create/templates/generator.ts @@ -45,7 +45,11 @@ export async function executeGeneratorScaffold( workspaceInfo.downloadPackageManager.version, workspaceInfo.isMonorepo, ) - ? createCatalogDependencyResolver(workspaceInfo.rootDir, workspaceInfo.packageManager) + ? createCatalogDependencyResolver( + workspaceInfo.rootDir, + workspaceInfo.packageManager, + workspaceInfo.downloadPackageManager.version, + ) : undefined; const { catalog } = readYamlFile(path.join(templatesDir, 'monorepo/pnpm-workspace.yaml')) as { catalog: Record; diff --git a/packages/cli/src/create/utils.ts b/packages/cli/src/create/utils.ts index 397ef749ba..a3cc8dea88 100644 --- a/packages/cli/src/create/utils.ts +++ b/packages/cli/src/create/utils.ts @@ -6,6 +6,7 @@ import { parseDocument } from 'yaml'; import { PackageManager } from '../types/index.ts'; import { + bunSupportsMergedDefaultCatalogs, getBunCatalogConfig, getYamlCatalogPath, isNamedCatalog, @@ -31,6 +32,7 @@ export function ensureCreateCatalogEntries( rootDir: string, projectDir: string, packageManager: PackageManager, + packageManagerVersion = 'latest', ): void { const packageJsonPath = path.join(projectDir, 'package.json'); if (packageManager === PackageManager.npm || !fs.existsSync(packageJsonPath)) { @@ -61,16 +63,22 @@ export function ensureCreateCatalogEntries( catalogs?: Record>; }>(path.join(rootDir, 'package.json'), (root) => { const target = getBunCatalogConfig(root); - const resolveCatalog = readBunCatalogDependencyResolver(root); + const resolveCatalog = readBunCatalogDependencyResolver(root, packageManagerVersion); + const mergeDefaults = bunSupportsMergedDefaultCatalogs(packageManagerVersion); let changed = false; for (const [name, spec] of entries) { if (resolveCatalog(spec, name) !== undefined) { continue; } const catalogName = spec.slice('catalog:'.length); - const catalog = isNamedCatalog(catalogName, packageManager) - ? ((target.catalogs ??= {})[catalogName] ??= {}) - : (target.catalogs?.default ?? target.catalog ?? (target.catalog = {})); + let catalog: Record; + if (isNamedCatalog(catalogName, packageManager, packageManagerVersion)) { + catalog = (target.catalogs ??= {})[catalogName] ??= {}; + } else if (mergeDefaults && target.catalogs?.default) { + catalog = target.catalogs.default; + } else { + catalog = target.catalog ??= {}; + } catalog[name] = versions[name]; changed = true; } diff --git a/packages/cli/src/migration/__tests__/migrator.spec.ts b/packages/cli/src/migration/__tests__/migrator.spec.ts index 078057db4e..ce5801c1fc 100644 --- a/packages/cli/src/migration/__tests__/migrator.spec.ts +++ b/packages/cli/src/migration/__tests__/migrator.spec.ts @@ -2144,6 +2144,123 @@ describe('ensureVitePlusBootstrap', () => { expect(pkg.overrides).toEqual({ vite: 'catalog:' }); }); + it.each(['1.2.14', '1.3.14', '1.4.0'])( + 'keeps split default catalogs resolvable when migrating Bun %s', + (version) => { + const file = path.join(tmpDir, 'package.json'); + fs.writeFileSync( + file, + JSON.stringify({ + name: 'bun-split-default', + packageManager: `bun@${version}`, + devDependencies: { vite: 'catalog:', react: 'catalog:default' }, + workspaces: { + packages: [], + catalog: { vite: '^8.0.0' }, + catalogs: { default: { react: '^19.0.0' } }, + }, + }), + ); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.bun, version); + rewriteMonorepo(workspace, true); + const pkg = readJson(file) as { + devDependencies: Record; + workspaces: { + catalog: Record; + catalogs: Record>; + }; + }; + const merged = version === '1.4.0'; + expect(pkg.devDependencies['vite-plus']).toBe('catalog:'); + expect(pkg.devDependencies.react).toBe('catalog:default'); + expect(pkg.workspaces.catalog['vite-plus']).toBe(merged ? undefined : 'latest'); + expect(pkg.workspaces.catalogs.default).toEqual( + merged ? { react: '^19.0.0', 'vite-plus': 'latest' } : { react: '^19.0.0' }, + ); + const resolver = createCatalogDependencyResolver(tmpDir, PackageManager.bun, version)!; + expect(resolver('catalog:', 'vite-plus')).toBe('latest'); + expect(resolver('catalog:', 'react')).toBe(merged ? '^19.0.0' : undefined); + const before = fs.readFileSync(file, 'utf8'); + rewriteMonorepo(workspace, true); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }, + ); + + it.each(['1.2.14', '1.3.14', '1.4.0'])( + 'reconciles a named default catalog with the correct reference on Bun %s', + (version) => { + const file = path.join(tmpDir, 'package.json'); + fs.writeFileSync( + file, + JSON.stringify({ + name: 'bun-named-default', + packageManager: `bun@${version}`, + devDependencies: { vite: 'catalog:default', 'vite-plus': '0.3.2' }, + workspaces: { + packages: [], + catalogs: { default: { vite: '^8.0.0', 'vite-plus': '0.3.2' } }, + }, + }), + ); + const workspace = makeWorkspaceInfo(tmpDir, PackageManager.bun, version); + ensureVitePlusBootstrap(workspace); + const pkg = readJson(file) as { + devDependencies: Record; + workspaces: { catalog?: unknown }; + }; + expect(pkg.devDependencies['vite-plus']).toBe( + version === '1.4.0' ? 'catalog:' : 'catalog:default', + ); + expect(pkg.workspaces.catalog).toBeUndefined(); + const resolver = createCatalogDependencyResolver(tmpDir, PackageManager.bun, version)!; + expect(resolver(pkg.devDependencies['vite-plus'], 'vite-plus')).toBe('latest'); + expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun)).toBe(false); + const before = fs.readFileSync(file, 'utf8'); + ensureVitePlusBootstrap(workspace); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + }, + ); + + it.each([ + ['1.3.14', 'root'], + ['1.3.14', 'nested'], + ['1.4.0', 'root'], + ['1.4.0', 'nested'], + ])('fills a missing named-default entry on Bun %s in %s catalogs', (version, location) => { + const file = path.join(tmpDir, 'package.json'); + const catalogs: { + catalog: Record; + catalogs: Record>; + } = { + catalog: { vite: '^8.0.0' }, + catalogs: { default: { 'vite-plus': '0.3.2' } }, + }; + fs.writeFileSync( + file, + JSON.stringify({ + name: 'bun-split-toolchain', + packageManager: `bun@${version}`, + devDependencies: { 'vite-plus': 'catalog:default' }, + ...(location === 'nested' + ? { workspaces: { packages: [], ...catalogs } } + : { workspaces: [], ...catalogs }), + }), + ); + ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.bun, version)); + const pkg = readJson(file) as { + devDependencies: Record; + workspaces: typeof catalogs; + } & typeof catalogs; + const active = location === 'nested' ? pkg.workspaces : pkg; + expect(active.catalog.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); + expect(active.catalogs.default.vite).toBe( + version === '1.4.0' ? undefined : VITE_PLUS_OVERRIDE_PACKAGES.vite, + ); + const resolver = createCatalogDependencyResolver(tmpDir, PackageManager.bun)!; + expect(resolver(pkg.devDependencies.vite, 'vite')).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); + expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun)).toBe(false); + }); + it('adds a missing @vitest/* entry to the bun catalog it now references', () => { fs.writeFileSync( path.join(tmpDir, 'package.json'), diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index aa321815a6..fa4674a05b 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -7,6 +7,7 @@ import { Scalar, YAMLMap, YAMLSeq } from 'yaml'; import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; import { + bunSupportsMergedDefaultCatalogs, createCatalogDependencyResolverFromCatalogs, getBunCatalogConfig, getYamlCatalogPath, @@ -51,6 +52,7 @@ import { REMOVE_PACKAGES, VITEST_IS_MANAGED_OVERRIDE, isPlainRecord, + pinnedPackageManagerVersion, pnpmOverrideKey, readPackageJsonIfExists, vitePeerDependencyRuleRequired, @@ -763,6 +765,7 @@ function isVitePlusOverrideSpec(value: string): boolean { export function createCatalogDependencyResolver( projectPath: string, packageManager: PackageManager, + packageManagerVersion?: string, ): CatalogDependencyResolver | undefined { if (packageManager === PackageManager.pnpm) { const pnpmWorkspaceYamlPath = path.join(projectPath, 'pnpm-workspace.yaml'); @@ -795,8 +798,13 @@ export function createCatalogDependencyResolver( workspaces?: NpmWorkspaces; catalog?: Record; catalogs?: Record>; + packageManager?: string; + devEngines?: { packageManager?: unknown }; }; - return readBunCatalogDependencyResolver(pkg); + return readBunCatalogDependencyResolver( + pkg, + packageManagerVersion ?? pinnedPackageManagerVersion(pkg), + ); } return undefined; } @@ -1025,7 +1033,7 @@ function shouldWriteCatalogEntry( addMissing: boolean, otherDefaultCatalog?: Record, ): boolean { - // Bun merges the two default catalogs and rejects names defined in both. + // Merged Bun default catalogs reject names defined in both. return name in catalog || (addMissing && !Object.hasOwn(otherDefaultCatalog ?? {}, name)); } @@ -1107,6 +1115,7 @@ export function rewriteBunCatalog( usesVitest: boolean, vitestEcosystemPackages: ReadonlySet, usesWebdriverioProvider = false, + packageManagerVersion = 'latest', ): void { const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { @@ -1129,9 +1138,13 @@ export function rewriteBunCatalog( // 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. - const { preferredCatalogSpec } = readBunCatalogDependencyResolver(pkg); + const { preferredCatalogSpec } = readBunCatalogDependencyResolver(pkg, packageManagerVersion); + const mergeDefaults = bunSupportsMergedDefaultCatalogs(packageManagerVersion); const preferredName = preferredCatalogSpec.slice('catalog:'.length); - const namedTarget = activeCatalogs.catalogs?.[preferredName || 'default']; + const namedTarget = + preferredName || mergeDefaults + ? activeCatalogs.catalogs?.[preferredName || 'default'] + : undefined; const defaultCatalog = useWorkspacesCatalog ? workspacesObj?.catalog : pkg.catalog; const catalog: Record = { ...defaultCatalog }; @@ -1159,7 +1172,7 @@ export function rewriteBunCatalog( usesVitest, vitestEcosystemPackages, namedTarget, - workspacesObj.catalog, + mergeDefaults ? workspacesObj.catalog : undefined, ); for (const named of Object.values(workspacesObj.catalogs)) { pruneLegacyWrapperAliases(named); @@ -1171,7 +1184,7 @@ export function rewriteBunCatalog( usesVitest, vitestEcosystemPackages, namedTarget, - pkg.catalog, + mergeDefaults ? pkg.catalog : undefined, ); for (const named of Object.values(pkg.catalogs)) { pruneLegacyWrapperAliases(named); diff --git a/packages/cli/src/migration/migrator/orchestrators.ts b/packages/cli/src/migration/migrator/orchestrators.ts index a32408c9da..ab75a4c974 100644 --- a/packages/cli/src/migration/migrator/orchestrators.ts +++ b/packages/cli/src/migration/migrator/orchestrators.ts @@ -92,7 +92,11 @@ export function rewriteStandaloneProject( report, workspaceInfo.downloadPackageManager.version, ); - const catalogDependencyResolver = createCatalogDependencyResolver(projectPath, packageManager); + const catalogDependencyResolver = createCatalogDependencyResolver( + projectPath, + packageManager, + workspaceInfo.downloadPackageManager.version, + ); const vitestEcosystemPackages = collectVitestEcosystemInstallDependencyNames(projectPath); // Captured before `rewritePackageJson` strips `oxlint`; the import rewriter // reads the manifests afterwards and would no longer see the signal. @@ -377,6 +381,7 @@ export function rewriteMonorepo( const catalogDependencyResolver = createCatalogDependencyResolver( workspaceInfo.rootDir, workspaceInfo.packageManager, + workspaceInfo.downloadPackageManager.version, ); // Captured before `rewritePackageJson` strips `oxlint`; the import rewriter // reads the manifests afterwards and would no longer see the signal. @@ -447,6 +452,7 @@ export function rewriteMonorepo( workspaceUsesVitest, vitestEcosystemPackages, usesWebdriverio, + workspaceInfo.downloadPackageManager.version, ); } rewriteRootWorkspacePackageJson( diff --git a/packages/cli/src/migration/migrator/shared.ts b/packages/cli/src/migration/migrator/shared.ts index ab1444dd1e..690e9bf7fc 100644 --- a/packages/cli/src/migration/migrator/shared.ts +++ b/packages/cli/src/migration/migrator/shared.ts @@ -416,6 +416,29 @@ export function readPackageJsonIfExists(packageJsonPath: string): DependencyBag } } +export function pinnedPackageManagerVersion(pkg: { + packageManager?: string; + devEngines?: { packageManager?: unknown }; +}): string | undefined { + if (typeof pkg.packageManager === 'string') { + const separator = pkg.packageManager.indexOf('@'); + if (separator !== -1) { + return pkg.packageManager.slice(separator + 1); + } + } + const devEngine = pkg.devEngines?.packageManager; + if ( + typeof devEngine === 'object' && + devEngine !== null && + !Array.isArray(devEngine) && + 'version' in devEngine && + typeof devEngine.version === 'string' + ) { + return devEngine.version; + } + return undefined; +} + // pnpm v10 introduced the map-shaped `allowBuilds` and removed the implicit // "build everything" default; v9 (>= 9.5) gates builds via the list-shaped // `onlyBuiltDependencies`. Both live in pnpm-workspace.yaml or in diff --git a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts index dd724b270e..ace12a90cd 100644 --- a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts +++ b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts @@ -73,6 +73,7 @@ import { REMOVE_PACKAGES, VITEST_IS_MANAGED_OVERRIDE, managedOverrideKey, + pinnedPackageManagerVersion, pnpmMajor, pnpmOverrideKey, type ManagedOverrideKeyStyle, @@ -178,26 +179,6 @@ export function overridesSatisfyVitePlus( ); } -function pinnedPackageManagerVersion(pkg: BootstrapPackageJson): string | undefined { - if (typeof pkg.packageManager === 'string') { - const separator = pkg.packageManager.indexOf('@'); - if (separator !== -1) { - return pkg.packageManager.slice(separator + 1); - } - } - const devEngine = pkg.devEngines?.packageManager; - if ( - typeof devEngine === 'object' && - devEngine !== null && - !Array.isArray(devEngine) && - 'version' in devEngine && - typeof devEngine.version === 'string' - ) { - return devEngine.version; - } - return undefined; -} - function vitePlusDependencyNeedsConcreteVersion(pkg: BootstrapPackageJson): boolean { const dependencyGroups = [pkg.devDependencies, pkg.dependencies, pkg.optionalDependencies]; return dependencyGroups.some( @@ -688,7 +669,11 @@ export function detectVitePlusBootstrapPending( packageManager === PackageManager.bun && bunSupportsCatalog(pkg, resolvedPackageManagerVersion), ); - const catalogDependencyResolver = createCatalogDependencyResolver(projectPath, packageManager); + const catalogDependencyResolver = createCatalogDependencyResolver( + projectPath, + packageManager, + resolvedPackageManagerVersion, + ); const canonicalVitePlusSpec = supportCatalog ? (catalogDependencyResolver?.preferredCatalogSpec ?? 'catalog:') : VITE_PLUS_VERSION; @@ -757,7 +742,9 @@ export function detectVitePlusBootstrapPending( // `catalog:` references, so the catalog resolver must NOT be consulted — // otherwise a dangling `catalog:` override resolves through the dead catalog // field and is mistaken for satisfied, masking the pending rewrite. - const bunCatalogResolver = supportCatalog ? readBunCatalogDependencyResolver(pkg) : undefined; + const bunCatalogResolver = supportCatalog + ? readBunCatalogDependencyResolver(pkg, resolvedPackageManagerVersion) + : undefined; // A `catalog:` vite-plus spec looks current, so judge its catalog value too. return ( (supportCatalog && @@ -1018,6 +1005,7 @@ export function ensureVitePlusBootstrap( const catalogDependencyResolver = createCatalogDependencyResolver( projectPath, workspaceInfo.packageManager, + workspaceInfo.downloadPackageManager.version, ); const canonicalVitePlusSpec = supportCatalog ? (catalogDependencyResolver?.preferredCatalogSpec ?? 'catalog:') @@ -1118,7 +1106,9 @@ export function ensureVitePlusBootstrap( const ensured = ensureOverrideEntries( pkg.overrides, usesVitest, - supportCatalog ? readBunCatalogDependencyResolver(pkg) : undefined, + supportCatalog + ? readBunCatalogDependencyResolver(pkg, workspaceInfo.downloadPackageManager.version) + : undefined, 'bare', usesWebdriverio, ); @@ -1295,7 +1285,13 @@ export function ensureVitePlusBootstrap( // rewriteBunCatalog runs only on monorepo roots). A standalone bun project // keeps the concrete overrides set by `ensureOverrideEntries` above. const before = fs.readFileSync(packageJsonPath, 'utf-8'); - rewriteBunCatalog(projectPath, usesVitest, vitestEcosystemPackages, usesWebdriverio); + rewriteBunCatalog( + projectPath, + usesVitest, + vitestEcosystemPackages, + usesWebdriverio, + workspaceInfo.downloadPackageManager.version, + ); const after = fs.readFileSync(packageJsonPath, 'utf-8'); result.packageJson = result.packageJson || before !== after; } diff --git a/packages/cli/src/utils/catalog.ts b/packages/cli/src/utils/catalog.ts index 72b6ecb122..00cf2d1900 100644 --- a/packages/cli/src/utils/catalog.ts +++ b/packages/cli/src/utils/catalog.ts @@ -1,3 +1,5 @@ +import { coerce, isGreaterThanOrEqual } from 'verkit'; + import { PackageManager } from '../types/index.ts'; import { VITE_PLUS_NAME } from './constants.ts'; import type { NpmWorkspaces } from './workspace.ts'; @@ -10,9 +12,24 @@ export type CatalogDependencyResolver = (( preferredCatalogSpec: string; }; -export function isNamedCatalog(catalogName: string, packageManager: PackageManager): boolean { +export function bunSupportsMergedDefaultCatalogs(version: string): boolean { + // Bun 1.4.0 unified the default catalogs: https://github.com/oven-sh/bun/pull/38333. + const coerced = coerce(version); + return coerced + ? isGreaterThanOrEqual(coerced, '1.4.0') + : version === 'latest' || version === 'canary'; +} + +export function isNamedCatalog( + catalogName: string, + packageManager: PackageManager, + version = 'latest', +): boolean { return ( - catalogName !== '' && (catalogName !== 'default' || packageManager === PackageManager.yarn) + catalogName !== '' && + (catalogName !== 'default' || + packageManager === PackageManager.yarn || + (packageManager === PackageManager.bun && !bunSupportsMergedDefaultCatalogs(version))) ); } @@ -20,22 +37,23 @@ export function createCatalogDependencyResolverFromCatalogs( catalog: Record | undefined, catalogs: Record> | undefined, packageManager: PackageManager, + version = 'latest', ): CatalogDependencyResolver { - // Bun merges the two default catalogs; Yarn keeps them separate. - const defaultCatalog = - packageManager === PackageManager.bun - ? { ...catalog, ...catalogs?.default } - : packageManager === PackageManager.yarn - ? catalog - : (catalog ?? catalogs?.default); + let defaultCatalog = catalog ?? catalogs?.default; + if (isNamedCatalog('default', packageManager, version)) { + defaultCatalog = catalog; + } else if (packageManager === PackageManager.bun) { + defaultCatalog = { ...catalog, ...catalogs?.default }; + } const preferredCatalogSpec = selectPreferredCatalogSpec( packageManager === PackageManager.bun ? defaultCatalog : catalog, catalogs, packageManager, + version, ); const resolver = (catalogSpec: string, dependencyName: string) => { const catalogName = catalogSpec.slice('catalog:'.length); - if (isNamedCatalog(catalogName, packageManager)) { + if (isNamedCatalog(catalogName, packageManager, version)) { return catalogs?.[catalogName]?.[dependencyName]; } return defaultCatalog?.[dependencyName]; @@ -47,6 +65,7 @@ export function selectPreferredCatalogSpec( catalog: Record | undefined, catalogs: Record> | undefined, packageManager: PackageManager, + version = 'latest', ): string { const candidates: Array<{ spec: string; values: Record }> = []; if (catalog) { @@ -54,7 +73,7 @@ export function selectPreferredCatalogSpec( } for (const [name, values] of Object.entries(catalogs ?? {})) { candidates.push({ - spec: isNamedCatalog(name, packageManager) ? `catalog:${name}` : 'catalog:', + spec: isNamedCatalog(name, packageManager, version) ? `catalog:${name}` : 'catalog:', values, }); } @@ -71,7 +90,7 @@ export function selectPreferredCatalogSpec( } } - if (!catalog && catalogs?.default && packageManager === PackageManager.yarn) { + if (!catalog && catalogs?.default && isNamedCatalog('default', packageManager, version)) { return 'catalog:default'; } return 'catalog:'; @@ -105,11 +124,19 @@ export function getBunCatalogConfig(pkg: { return nested?.catalog != null || nested?.catalogs != null ? nested : pkg; } -export function readBunCatalogDependencyResolver(pkg: { - workspaces?: NpmWorkspaces; - catalog?: Record; - catalogs?: Record>; -}): CatalogDependencyResolver { +export function readBunCatalogDependencyResolver( + pkg: { + workspaces?: NpmWorkspaces; + catalog?: Record; + catalogs?: Record>; + }, + version = 'latest', +): CatalogDependencyResolver { const { catalog, catalogs } = getBunCatalogConfig(pkg); - return createCatalogDependencyResolverFromCatalogs(catalog, catalogs, PackageManager.bun); + return createCatalogDependencyResolverFromCatalogs( + catalog, + catalogs, + PackageManager.bun, + version, + ); } From 8d0c857dfafba39b8663658202b7c20dfbc138c2 Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 16:38:57 +0900 Subject: [PATCH 12/14] test(cli): cover managed duplicate Bun catalog entries The duplicate entry test used react, which the migrator never rewrites, so it passed without exercising the write path. Duplicate vite instead and assert that both catalogs are updated in place. Let the integrate helper take a package manager so the Yarn and Bun cases reuse it. --- .../__tests__/workspace-catalog.spec.ts | 56 ++++++------------- 1 file changed, 18 insertions(+), 38 deletions(-) diff --git a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts index 86bcdf59d9..4d00ccbef6 100644 --- a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts +++ b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts @@ -37,20 +37,23 @@ beforeEach(() => { afterEach(() => fs.rmSync(root, { recursive: true, force: true })); -function integrate(dependencies: Record = { vite: '^8.0.0' }) { +function integrate( + dependencies: Record = { vite: '^8.0.0' }, + pm: PackageManager = PackageManager.pnpm, +) { fs.writeFileSync( path.join(project, 'package.json'), JSON.stringify({ devDependencies: dependencies }), ); rewriteMonorepoProject( project, - PackageManager.pnpm, + pm, true, true, undefined, - createCatalogDependencyResolver(root, PackageManager.pnpm), + createCatalogDependencyResolver(root, pm), ); - ensureCreateCatalogEntries(root, project, PackageManager.pnpm); + ensureCreateCatalogEntries(root, project, pm); return readYamlFile(workspaceFile); } @@ -70,25 +73,14 @@ it.each([PackageManager.pnpm, PackageManager.yarn, PackageManager.bun])( }[pm], ); fs.writeFileSync(file, pm === PackageManager.bun ? JSON.stringify(config) : stringify(config)); - fs.writeFileSync( - path.join(project, 'package.json'), - JSON.stringify({ - devDependencies: { - 'vite-plus': 'catalog:tools', - '@vitest/utils': '^5.0.0', - '@vitest/spy': 'catalog:tools', - }, - }), - ); - rewriteMonorepoProject( - project, + integrate( + { + 'vite-plus': 'catalog:tools', + '@vitest/utils': '^5.0.0', + '@vitest/spy': 'catalog:tools', + }, pm, - true, - true, - undefined, - createCatalogDependencyResolver(root, pm), ); - ensureCreateCatalogEntries(root, project, pm); expect(readJsonFile(path.join(project, 'package.json')).devDependencies).toMatchObject({ '@vitest/utils': 'catalog:tools', '@vitest/spy': 'catalog:tools', @@ -157,19 +149,7 @@ describe.each([PackageManager.yarn, PackageManager.bun])('%s workspace catalogs' pm === PackageManager.yarn ? stringify(config) : JSON.stringify(contents), ); } - fs.writeFileSync( - path.join(project, 'package.json'), - JSON.stringify({ devDependencies: { vite: '^8.0.0' } }), - ); - rewriteMonorepoProject( - project, - pm, - true, - true, - undefined, - createCatalogDependencyResolver(root, pm), - ); - ensureCreateCatalogEntries(root, project, pm); + integrate(undefined, pm); const spec = kind === 'named' ? 'catalog:tools' @@ -386,16 +366,16 @@ describe.each(['root', 'nested'])('Bun %s shared default catalog', (location) => expect(fs.readFileSync(file, 'utf8')).toBe(before); }); - it('does not silently remove pre-existing duplicate entries', () => { + it('updates pre-existing duplicate entries in place without removing either', () => { const contents = readJsonFile(file); const active = (location === 'nested' ? contents.workspaces : contents) as typeof config; - Object.assign(active.catalog, { react: active.catalogs.default.react }); + Object.assign(active.catalogs.default, { vite: active.catalog.vite }); fs.writeFileSync(file, JSON.stringify(contents)); rewriteBunCatalog(root, false, new Set()); const result = readJsonFile(file); expect(location === 'nested' ? result.workspaces : result).toMatchObject({ - catalog: { react: '^19.0.0' }, - catalogs: { default: { react: '^19.0.0' } }, + catalog: { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite }, + catalogs: { default: { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } }, }); }); }); From 8a90cf51a73ca5eca79af706f18de9aecbec2248 Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 16:39:11 +0900 Subject: [PATCH 13/14] refactor(cli): reuse catalog support helpers Share versionAtLeast between the migrator and the Bun default catalog check, and add workspaceSupportsCatalog for the create and migrate call sites that read Bun's workspace state from the root package.json. Reuse the pnpm workspace resolver and the active Bun catalog configuration instead of recomputing them. --- packages/cli/src/create/bin.ts | 11 ++--- .../cli/src/migration/migrator/catalog.ts | 40 +++++++++---------- .../src/migration/migrator/orchestrators.ts | 12 ++---- packages/cli/src/utils/catalog.ts | 16 ++++++-- 4 files changed, 37 insertions(+), 42 deletions(-) diff --git a/packages/cli/src/create/bin.ts b/packages/cli/src/create/bin.ts index 01a89ecac2..50bed2f3b6 100644 --- a/packages/cli/src/create/bin.ts +++ b/packages/cli/src/create/bin.ts @@ -7,7 +7,6 @@ import * as prompts from '@voidzero-dev/vite-plus-prompts'; import { getPackageManagerOverride, parseCreateArgs, vitePlusHeader } from '../../binding/index.js'; import { addFrameworkShim, - bunSupportsCatalog, createCatalogDependencyResolver, detectEslintProject, detectFramework, @@ -24,7 +23,7 @@ import { rewriteStandaloneProject, setPackageManager, shouldSkipStagedMigrationForHooks, - supportsCatalog, + workspaceSupportsCatalog, } from '../migration/migrator.ts'; import { DependencyType, PackageManager, type WorkspaceInfo } from '../types/index.ts'; import { @@ -1319,14 +1318,10 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h shouldSetupHooks, workspaceInfo.packageManager, ); - const supportCatalog = supportsCatalog( + const supportCatalog = workspaceSupportsCatalog( + workspaceInfo.rootDir, workspaceInfo.packageManager, workspaceInfo.packageManagerVersion, - workspaceInfo.packageManager === PackageManager.bun && - bunSupportsCatalog( - readJsonFile(path.join(workspaceInfo.rootDir, 'package.json')), - workspaceInfo.packageManagerVersion, - ), ); rewriteMonorepoProject( fullPath, diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index fa4674a05b..b1aaa34448 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import tsrsPkg from 'tsrs/package.json' with { type: 'json' }; -import { coerce, isGreaterThanOrEqual, isLessThan } from 'verkit'; +import { coerce, isLessThan } from 'verkit'; import { Scalar, YAMLMap, YAMLSeq } from 'yaml'; import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; @@ -13,6 +13,7 @@ import { getYamlCatalogPath, readBunCatalogDependencyResolver, selectPreferredCatalogSpec, + versionAtLeast, type CatalogDependencyResolver, } from '../../utils/catalog.ts'; import { @@ -103,17 +104,6 @@ function hasTsrsTrustPolicyException(excludes: readonly unknown[]): boolean { return excludes.includes('tsrs') || excludes.includes(PNPM_TSRS_TRUST_POLICY_EXCLUDE); } -// Whether `version` is at least `minVersion`. A non-coercible version passes -// only when it is one of the given dist-tags, which always point at a current -// (feature-capable) release. -function versionAtLeast(version: string, minVersion: string, tags: string[]): boolean { - const coerced = coerce(version); - if (coerced) { - return isGreaterThanOrEqual(coerced, minVersion); - } - return tags.includes(version); -} - // The packages field became optional in pnpm 10.5.0. // https://github.com/pnpm/pnpm/releases/tag/v10.5.0 export function pnpmRequiresWorkspacePackages(version: string): boolean { @@ -214,6 +204,20 @@ export function supportsCatalog( } } +// `supportsCatalog` for a workspace root, reading Bun's workspace state from its package.json. +export function workspaceSupportsCatalog( + rootDir: string, + packageManager: PackageManager, + version: string, +): boolean { + return supportsCatalog( + packageManager, + version, + packageManager === PackageManager.bun && + bunSupportsCatalog(readJsonFile(path.join(rootDir, 'package.json')), version), + ); +} + // These are the root package.json#pnpm settings pnpm 10.6.2+ accepts at the // top level of pnpm-workspace.yaml. Unknown keys may belong to third-party // tooling and stay in package.json. @@ -768,15 +772,7 @@ export function createCatalogDependencyResolver( packageManagerVersion?: string, ): CatalogDependencyResolver | undefined { if (packageManager === PackageManager.pnpm) { - const pnpmWorkspaceYamlPath = path.join(projectPath, 'pnpm-workspace.yaml'); - if (!fs.existsSync(pnpmWorkspaceYamlPath)) { - return undefined; - } - const doc = readYamlFile(pnpmWorkspaceYamlPath) as { - catalog?: Record; - catalogs?: Record>; - } | null; - return createCatalogDependencyResolverFromCatalogs(doc?.catalog, doc?.catalogs, packageManager); + return readPnpmWorkspaceCatalogDependencyResolver(projectPath); } if (packageManager === PackageManager.yarn) { const yarnrcYmlPath = path.join(projectPath, '.yarnrc.yml'); @@ -1145,7 +1141,7 @@ export function rewriteBunCatalog( preferredName || mergeDefaults ? activeCatalogs.catalogs?.[preferredName || 'default'] : undefined; - const defaultCatalog = useWorkspacesCatalog ? workspacesObj?.catalog : pkg.catalog; + const defaultCatalog = activeCatalogs.catalog; const catalog: Record = { ...defaultCatalog }; rewriteCatalogObject(catalog, !namedTarget, usesVitest, vitestEcosystemPackages); diff --git a/packages/cli/src/migration/migrator/orchestrators.ts b/packages/cli/src/migration/migrator/orchestrators.ts index ab75a4c974..0280aac009 100644 --- a/packages/cli/src/migration/migrator/orchestrators.ts +++ b/packages/cli/src/migration/migrator/orchestrators.ts @@ -4,11 +4,10 @@ import path from 'node:path'; import { PackageManager, type WorkspaceInfo, type WorkspacePackage } from '../../types/index.ts'; import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; import { VITE_PLUS_NAME, VITE_PLUS_VERSION, isForceOverrideMode } from '../../utils/constants.ts'; -import { editJsonFile, readJsonFile } from '../../utils/json.ts'; +import { editJsonFile } from '../../utils/json.ts'; import { applyBuildAllowanceToPackageJsonPnpm, applyYarnWorkspaceHoistingFix, - bunSupportsCatalog, cleanupDeprecatedTsconfigOptions, collectInjectedProviderNames, collectOxlintDependencyNames, @@ -61,6 +60,7 @@ import { usesWebdriverioProvider, workspaceUsesVitestDirectly, workspaceUsesWebdriverio, + workspaceSupportsCatalog, workspaceUsesWebdriverioProvider, yarnSupportsPreapprovedPackages, wrapLazyPluginsInViteConfig, @@ -419,14 +419,10 @@ export function rewriteMonorepo( ); // Catalog support: pnpm >= 9.5.0, Yarn >= 4.10.0, bun per `bunSupportsCatalog`. // An older PM falls back to concrete. - const supportCatalog = supportsCatalog( + const supportCatalog = workspaceSupportsCatalog( + workspaceInfo.rootDir, workspaceInfo.packageManager, workspaceInfo.downloadPackageManager.version, - workspaceInfo.packageManager === PackageManager.bun && - bunSupportsCatalog( - readJsonFile(path.join(workspaceInfo.rootDir, 'package.json')), - workspaceInfo.downloadPackageManager.version, - ), ); const workspaceContext = { rootDir: workspaceInfo.rootDir, diff --git a/packages/cli/src/utils/catalog.ts b/packages/cli/src/utils/catalog.ts index 00cf2d1900..e5cd1c4ea5 100644 --- a/packages/cli/src/utils/catalog.ts +++ b/packages/cli/src/utils/catalog.ts @@ -12,12 +12,20 @@ export type CatalogDependencyResolver = (( preferredCatalogSpec: string; }; +// Whether `version` is at least `minVersion`. A non-coercible version passes +// only when it is one of the given dist-tags, which always point at a current +// (feature-capable) release. +export function versionAtLeast(version: string, minVersion: string, tags: string[]): boolean { + const coerced = coerce(version); + if (coerced) { + return isGreaterThanOrEqual(coerced, minVersion); + } + return tags.includes(version); +} + export function bunSupportsMergedDefaultCatalogs(version: string): boolean { // Bun 1.4.0 unified the default catalogs: https://github.com/oven-sh/bun/pull/38333. - const coerced = coerce(version); - return coerced - ? isGreaterThanOrEqual(coerced, '1.4.0') - : version === 'latest' || version === 'canary'; + return versionAtLeast(version, '1.4.0', ['latest', 'canary']); } export function isNamedCatalog( From 09180d72c6d070c33d0a5821a5b397cdf9b5a7ca Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Tue, 17 Nov 2026 16:48:13 +0900 Subject: [PATCH 14/14] fix(create): skip catalog completion when catalogs are unsupported A template that ships a catalog reference made creation add catalog settings to the root configuration even when the package manager cannot read them. Yarn before 4.10 rejects those settings and stops every command. Complete catalog entries only when the workspace supports catalogs, and cover Yarn 4.9 with a CLI snapshot that checks the root configuration stays readable. --- .../snapshots.toml | 14 +++++++++ ...g_yarn_template_catalog_without_support.md | 30 +++++++++++++++++++ packages/cli/src/create/bin.ts | 14 +++++---- 3 files changed, 52 insertions(+), 6 deletions(-) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_template_catalog_without_support.md diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml index 0fd7a76434..e6b7a62a64 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots.toml @@ -67,3 +67,17 @@ steps = [ { argv = ["vp", "install", "--frozen-lockfile"], snapshot = false }, { argv = ["vp", "run", "build"], cwd = "apps/web", snapshot = false }, ] + +[[case]] +name = "create_existing_yarn_template_catalog_without_support" +vp = "local" +local-registry = true +comment = "A template's catalog reference must not add catalog settings that Yarn before 4.10 rejects." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "packageManager", "yarn@4.9.0"], snapshot = false }, + { argv = ["vpt", "cp", "vitest-template.config.ts", "vite.config.ts"], snapshot = false }, + { argv = ["vpt", "write-file", ".yarnrc.yml", "nodeLinker: node-modules\n"], snapshot = false }, + { argv = ["vp", "create", "vitest-app", "--no-interactive", "--no-agent", "--no-editor", "--no-hooks"], snapshot = false, timeout = 240000 }, + ["vpt", "print-file", ".yarnrc.yml"], + { argv = ["yarn", "config", "get", "nodeLinker"], comment = "Yarn still accepts the root configuration." }, +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_template_catalog_without_support.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_template_catalog_without_support.md new file mode 100644 index 0000000000..e8db335c2f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_existing_yarn_workspace/snapshots/create_existing_yarn_template_catalog_without_support.md @@ -0,0 +1,30 @@ +# create_existing_yarn_template_catalog_without_support + +A template's catalog reference must not add catalog settings that Yarn before 4.10 rejects. + +## `vpt json-edit package.json packageManager yarn@4.9.0` + + +## `vpt cp vitest-template.config.ts vite.config.ts` + + +## `vpt write-file .yarnrc.yml 'nodeLinker: node-modules +'` + + +## `vp create vitest-app --no-interactive --no-agent --no-editor --no-hooks` + + +## `vpt print-file .yarnrc.yml` + +``` +nodeLinker: node-modules +``` + +## `yarn config get nodeLinker` + +Yarn still accepts the root configuration. + +``` +node-modules +``` diff --git a/packages/cli/src/create/bin.ts b/packages/cli/src/create/bin.ts index 50bed2f3b6..42658e2a96 100644 --- a/packages/cli/src/create/bin.ts +++ b/packages/cli/src/create/bin.ts @@ -1344,12 +1344,14 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h false, supportCatalog, ); - ensureCreateCatalogEntries( - workspaceInfo.rootDir, - fullPath, - workspaceInfo.packageManager, - workspaceInfo.packageManagerVersion, - ); + if (supportCatalog) { + ensureCreateCatalogEntries( + workspaceInfo.rootDir, + fullPath, + workspaceInfo.packageManager, + workspaceInfo.packageManagerVersion, + ); + } for (const framework of detectFramework(fullPath)) { if (!hasFrameworkShim(fullPath, framework)) { addFrameworkShim(fullPath, framework);