diff --git a/.github/scripts/__tests__/agent-command-timeouts.spec.ts b/.github/scripts/__tests__/agent-command-timeouts.spec.ts index 7caf5e5ccb..c240f15642 100644 --- a/.github/scripts/__tests__/agent-command-timeouts.spec.ts +++ b/.github/scripts/__tests__/agent-command-timeouts.spec.ts @@ -14,7 +14,16 @@ function toolUse(id: string, command: string, description?: string) { }; } -function toolResult(id: string, toolUseResult: Record) { +function toolResult( + id: string, + toolUseResult: { + timedOutAfterMs?: number; + stdout?: string; + stderr?: string; + interrupted?: boolean; + backgroundTaskId?: string; + }, +) { return { type: 'user', message: { @@ -32,18 +41,18 @@ test('finds Bash calls that exceeded their timeout', () => { toolResult('fast', { stdout: 'ok', stderr: '', interrupted: false }), toolUse('slow', 'pnpm build-native --release', 'Rebuild binding'), { type: 'tool_progress', tool_use_id: 'slow-heartbeat-1', elapsed_time_seconds: 600 }, - toolResult('slow', { backgroundTaskId: 'b1', timedOutAfterMs: 600000 }), + toolResult('slow', { backgroundTaskId: 'b1', timedOutAfterMs: 600_000 }), { type: 'result', is_error: true }, ]; expect(findCommandTimeouts(messages)).toEqual([ - { command: 'pnpm build-native --release', description: 'Rebuild binding', timeoutMs: 600000 }, + { command: 'pnpm build-native --release', description: 'Rebuild binding', timeoutMs: 600_000 }, ]); }); test('keeps a timeout whose call is missing from the messages', () => { - expect(findCommandTimeouts([toolResult('unknown', { timedOutAfterMs: 120000 })])).toEqual([ - { command: '', description: undefined, timeoutMs: 120000 }, + expect(findCommandTimeouts([toolResult('unknown', { timedOutAfterMs: 120_000 })])).toEqual([ + { command: '', description: undefined, timeoutMs: 120_000 }, ]); }); @@ -54,8 +63,8 @@ test('rejects an execution file without a message array', () => { test('formats each command in a code block inside the list item', () => { expect( formatCommandTimeouts([ - { command: 'cargo check\ncargo shear', description: 'Check Rust', timeoutMs: 600000 }, - { command: 'echo ```', description: undefined, timeoutMs: 120000 }, + { command: 'cargo check\ncargo shear', description: 'Check Rust', timeoutMs: 600_000 }, + { command: 'echo ```', description: undefined, timeoutMs: 120_000 }, ]), ).toBe( [ diff --git a/.github/scripts/__tests__/docs-fork-preview.mjs b/.github/scripts/__tests__/docs-fork-preview.mjs index 59b2263b84..2bfed4f470 100644 --- a/.github/scripts/__tests__/docs-fork-preview.mjs +++ b/.github/scripts/__tests__/docs-fork-preview.mjs @@ -160,7 +160,7 @@ await test('uses the package preview build and protected deployment pattern', as deploy, /workflow_run:\n\s+workflows: \['Build Docs Fork Preview'\]\n\s+types: \[completed\]/, ); - assert.doesNotMatch(deploy, /\n approve:/); + assert.doesNotMatch(deploy, /\n {2}approve:/); const authorize = deploy.split('\n authorize:\n')[1].split('\n deploy:\n')[0]; assert.doesNotMatch(authorize, /environment:|secrets\.|: write/); const job = deploy.split('\n deploy:\n')[1]; @@ -373,7 +373,7 @@ await test('pins an artifact to the triggering build attempt', async () => { }); await test('validates build identities before making requests', async () => { - for (const value of [undefined, 0, -1, 1.5, NaN, '123', Number.MAX_SAFE_INTEGER + 1]) { + for (const value of [undefined, 0, -1, 1.5, Number.NaN, '123', Number.MAX_SAFE_INTEGER + 1]) { for (const [runId, attempt] of [ [value, 1], [123, value], @@ -888,7 +888,7 @@ await test('rejects invalid PR numbers before using them in URLs or requests', a 0, -1, 1.5, - NaN, + Number.NaN, Number.MAX_SAFE_INTEGER + 1, '2684', '2684\nother-output=true', diff --git a/.github/scripts/__tests__/publish-npm-package.spec.ts b/.github/scripts/__tests__/publish-npm-package.spec.ts index 315c1fd16b..949d43ca88 100644 --- a/.github/scripts/__tests__/publish-npm-package.spec.ts +++ b/.github/scripts/__tests__/publish-npm-package.spec.ts @@ -2,12 +2,8 @@ import { describe, expect, test, vi } from 'vitest'; -import { - type PublishCommandRunner, - type PublishNpmPackageOptions, - isAlreadyPublishedError, - publishNpmPackage, -} from '../publish-npm-package.ts'; +import type { PublishCommandRunner, PublishNpmPackageOptions } from '../publish-npm-package.ts'; +import { isAlreadyPublishedError, publishNpmPackage } from '../publish-npm-package.ts'; import type { FetchLike } from '../wait-for-npm-packages.ts'; import { response, stalledFetch } from './npm-registry.ts'; @@ -22,8 +18,8 @@ function options(fetchImpl: FetchLike, runCommand: PublishCommandRunner): Publis registry: 'https://registry.npmjs.org', fetchImpl, runCommand, - log: vi.fn(), - warn: vi.fn(), + log: vi.fn(), + warn: vi.fn(), }; } @@ -95,7 +91,7 @@ describe('publishNpmPackage', () => { onTestFinished(() => { vi.useRealTimers(); }); - const fetchImpl = vi.fn(stalledFetch); + const fetchImpl = vi.fn(stalledFetch); const runCommand = vi.fn().mockResolvedValue({ exitCode: 0, output: 'published', @@ -103,7 +99,7 @@ describe('publishNpmPackage', () => { const publishOptions = options(fetchImpl, runCommand); const result = publishNpmPackage(publishOptions); - await vi.advanceTimersByTimeAsync(9_999); + await vi.advanceTimersByTimeAsync(9999); expect(runCommand).not.toHaveBeenCalled(); await vi.advanceTimersByTimeAsync(1); @@ -131,7 +127,7 @@ describe('publishNpmPackage', () => { ]), )('resumes publication after $name fails (accepted=$accepted)', async ({ name, accepted }) => { const published = new Set(); - const uploads: string[] = []; + const uploads: Array = []; let interrupted = false; async function publishRelease() { for (const packageName of releasePackages) { diff --git a/.github/scripts/__tests__/upgrade-deps-utils.spec.ts b/.github/scripts/__tests__/upgrade-deps-utils.spec.ts index 2ffa393fdc..f4c98df60e 100644 --- a/.github/scripts/__tests__/upgrade-deps-utils.spec.ts +++ b/.github/scripts/__tests__/upgrade-deps-utils.spec.ts @@ -23,7 +23,7 @@ test('selects the latest eligible stable Node.js 24 release independently of the vi.unstubAllGlobals(); }); vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-11-12T00:00:00Z')); - const fetchMock = vi.fn().mockResolvedValue( + const fetchMock = vi.fn().mockResolvedValue( Response.json([ { version: 'v26.13.0', date: '2026-11-01', lts: 'Lithium' }, { version: 'v24.9.0', date: '2026-11-01', lts: 'Krypton' }, @@ -60,6 +60,6 @@ test.each([ onTestFinished(() => { vi.unstubAllGlobals(); }); - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response())); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response())); await expect(getLatestNodeVersion(24)).rejects.toThrow(error); }); diff --git a/.github/scripts/__tests__/upgrade-deps.spec.ts b/.github/scripts/__tests__/upgrade-deps.spec.ts index b7b1ca09c6..d722e5ad8f 100644 --- a/.github/scripts/__tests__/upgrade-deps.spec.ts +++ b/.github/scripts/__tests__/upgrade-deps.spec.ts @@ -1,6 +1,6 @@ /// -import * as childProcess from 'node:child_process'; +import { execFileSync } from 'node:child_process'; import { copyFileSync, mkdirSync, @@ -15,10 +15,9 @@ import { dirname, join, resolve } from 'node:path'; import { expect, onTestFinished, test, vi } from 'vite-plus/test'; -vi.mock('node:child_process', async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, execFileSync: vi.fn(actual.execFileSync) }; -}); +import { readJsonObject as readJson, requireJsonObject } from '../../../scripts/json.ts'; + +vi.mock('node:child_process', { spy: true }); test.each([false, true])( 'runs the upgrade pipeline and retains metadata (install fails: %s)', @@ -26,7 +25,7 @@ test.each([false, true])( const root = resolve(import.meta.dirname, '../../..'); const { root: tempDir, metaDir, corePath, pluginPath, parserPath } = createSyncFixture(); onTestFinished(() => { - vi.mocked(childProcess.execFileSync).mockReset(); + vi.mocked(execFileSync).mockReset(); vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); @@ -63,8 +62,8 @@ test.each([false, true])( writeFileSync( workspacePath, readFileSync(workspacePath, 'utf8') - .replace(/ lint-staged: .+/, ' lint-staged: ^16.2.6') - .replace(/^ oxc-(?:minify|transform): .+\n/gm, ''), + .replace(/ {2}lint-staged: .+/, ' lint-staged: ^16.2.6') + .replaceAll(/^ {2}oxc-(?:minify|transform): .+\n/gm, ''), ); vi.spyOn(process, 'cwd').mockReturnValue(tempDir); @@ -76,6 +75,7 @@ test.each([false, true])( const pinnedOxcNode = JSON.parse( readFileSync(join(tempDir, 'packages/tools/.upstream-versions.json'), 'utf8'), )['oxc-node'].hash; + const compareUrls: Array = []; vi.stubGlobal('fetch', async (url: string) => { if (url === 'https://nodejs.org/dist/index.json') { return Response.json([ @@ -87,7 +87,7 @@ test.each([false, true])( ]); } if (url.startsWith('https://api.github.com/repos/oxc-project/oxc-node/compare/')) { - expect(url).toContain(`/compare/${pinnedOxcNode}...`); + compareUrls.push(url); return Response.json({ status: failInstall ? 'diverged' : 'ahead' }); } if (url.startsWith('https://api.github.com/repos/')) { @@ -137,10 +137,14 @@ test.each([false, true])( } throw new Error(`Unexpected request: ${url}`); }); - const commands: string[][] = []; - vi.mocked(childProcess.execFileSync).mockImplementation((command, args) => { + const commands: Array> = []; + let parserAtFinalInstall; + vi.mocked(execFileSync).mockImplementation((command, args) => { expect(command).toBe('pnpm'); - commands.push(args as string[]); + if (!Array.isArray(args)) { + throw new Error('Expected pnpm command arguments'); + } + commands.push([...args]); if (failInstall) { throw new Error('Installation failed'); } @@ -152,25 +156,35 @@ test.each([false, true])( writeJson(parserPath, { version: '0.11.2' }); } if (commands.length === 4) { - expect(readJson(corePath).dependencies['yuku-parser']).toBe('0.11.2'); + parserAtFinalInstall = requireJsonObject(readJson(corePath).dependencies, corePath)[ + 'yuku-parser' + ]; } return Buffer.from(''); }); vi.resetModules(); - if (failInstall) { - await expect(import('../upgrade-deps.ts')).rejects.toThrow('Installation failed'); - expect(commands).toEqual([['install', '--no-frozen-lockfile']]); - expect(readJson(corePath).dependencies['yuku-parser']).toBe('^0.9.3'); - } else { - await import('../upgrade-deps.ts'); - expect(commands).toEqual([ - ['install', '--no-frozen-lockfile'], - ['tool', 'sync-remote'], - ['dedupe'], - ['install', '--no-frozen-lockfile'], - ]); - } + const failure = await import('../upgrade-deps.ts').then( + () => undefined, + (error: unknown) => error, + ); + expect(failure).toEqual(failInstall ? new Error('Installation failed') : undefined); + expect(commands).toEqual( + failInstall + ? [['install', '--no-frozen-lockfile']] + : [ + ['install', '--no-frozen-lockfile'], + ['tool', 'sync-remote'], + ['dedupe'], + ['install', '--no-frozen-lockfile'], + ], + ); + expect(compareUrls).toEqual([expect.stringContaining(`/compare/${pinnedOxcNode}...`)]); + expect(parserAtFinalInstall).toBe(failInstall ? undefined : '0.11.2'); + expect(readJson(corePath)).toHaveProperty( + ['dependencies', 'yuku-parser'], + failInstall ? '^0.9.3' : '0.11.2', + ); expect(readFileSync(workspacePath, 'utf8')).toContain('\n lint-staged: ^17.5.1\n'); expect(readFileSync(workspacePath, 'utf8')).toContain("\n '@oxlint/plugins': =1.88.0\n"); @@ -211,9 +225,9 @@ test.each([false, true])( ? { old: pinnedOxcNode, new: pinnedOxcNode } : { old: pinnedOxcNode, new: 'a'.repeat(40), tag: 'v1.2.3' }, ); - if (!failInstall) { - expect(versions['yuku-parser']).toEqual({ old: '^0.9.3', new: '0.11.2' }); - } + expect(versions['yuku-parser']).toEqual( + failInstall ? undefined : { old: '^0.9.3', new: '0.11.2' }, + ); expect(readFileSync(join(metaDir, 'commit-message.txt'), 'utf8')).toContain( '- lint-staged: 16.2.6 -> 17.5.1', ); @@ -231,10 +245,6 @@ function writeJson(file: string, value: unknown) { writeFileSync(file, JSON.stringify(value, null, 2) + '\n'); } -function readJson(file: string) { - return JSON.parse(readFileSync(file, 'utf8')); -} - function createSyncFixture() { const root = mkdtempSync(join(tmpdir(), 'vite-plus-sync-bundled-deps-')); onTestFinished(() => rmSync(root, { recursive: true, force: true })); @@ -281,7 +291,7 @@ function createSyncFixture() { }); writeJson(versionsPath, { oxlint: { old: '1.86.0', new: '1.87.0' } }); const run = () => - childProcess.execFileSync( + execFileSync( process.execPath, [resolve(import.meta.dirname, '../upgrade-deps.ts'), '--sync-bundled-deps'], { @@ -324,7 +334,7 @@ test('pins the bundled parser, syncs Vite ranges, and preserves upgrade metadata run(); expect(readJson(corePath).dependencies).not.toHaveProperty('yuku-ast'); expect(readJson(corePath).dependencies).not.toHaveProperty('yuku-codegen'); - expect(readJson(corePath).dependencies['yuku-parser']).toBe('0.11.2'); + expect(readJson(corePath)).toHaveProperty(['dependencies', 'yuku-parser'], '0.11.2'); expect(readJson(versionsPath)['yuku-parser']).toEqual({ old: '^0.9.3', new: '0.11.2' }); expect(readFileSync(join(metaDir, 'commit-message.txt'), 'utf8')).toContain( '- yuku-parser: ^0.9.3 -> 0.11.2', @@ -380,7 +390,7 @@ test('updates the parser pin when its installed version changes within the same run(); writeJson(parserPath, { version: '0.10.4' }); run(); - expect(readJson(corePath).dependencies['yuku-parser']).toBe('0.10.4'); + expect(readJson(corePath)).toHaveProperty(['dependencies', 'yuku-parser'], '0.10.4'); expect(readJson(versionsPath)['yuku-parser']).toEqual({ old: '^0.9.3', new: '0.10.4' }); }); @@ -405,7 +415,8 @@ test.each([ ] as const)('fails without writing core when upstream removes $name', ({ source, field, name }) => { const fixture = createSyncFixture(); const pkg = readJson(fixture[source]); - delete pkg[field][name]; + const dependencies = requireJsonObject(pkg[field], field); + delete dependencies[name]; writeJson(fixture[source], pkg); const before = readFileSync(fixture.corePath, 'utf8'); expect(fixture.run).toThrow("review core's externals"); diff --git a/.github/scripts/__tests__/wait-for-npm-packages.spec.ts b/.github/scripts/__tests__/wait-for-npm-packages.spec.ts index e57896bf47..939e93a915 100644 --- a/.github/scripts/__tests__/wait-for-npm-packages.spec.ts +++ b/.github/scripts/__tests__/wait-for-npm-packages.spec.ts @@ -2,9 +2,8 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; +import type { FetchLike, WaitForNpmPackagesOptions } from '../wait-for-npm-packages.ts'; import { - type FetchLike, - type WaitForNpmPackagesOptions, isNpmPackageAvailable, parseNpmPackageSpec, waitForNpmPackages, @@ -29,11 +28,14 @@ function options( minSeconds: 0, timeoutSeconds: 5, pollSeconds: 1, - sleep: vi.fn( - (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)), + sleep: vi.fn( + (milliseconds) => + new Promise((resolve) => { + setTimeout(resolve, milliseconds); + }), ), now: Date.now, - log: vi.fn(), + log: vi.fn(), ...overrides, }; } @@ -93,7 +95,7 @@ describe('waitForNpmPackages', () => { await result; expect(waitOptions.sleep).toHaveBeenCalledTimes(2); - expect(waitOptions.sleep).toHaveBeenNthCalledWith(1, 5_000); + expect(waitOptions.sleep).toHaveBeenNthCalledWith(1, 5000); expect(waitOptions.sleep).toHaveBeenNthCalledWith(2, 60_000); expect(vi.getTimerCount()).toBe(0); }); @@ -101,21 +103,21 @@ describe('waitForNpmPackages', () => { test('retries transient read failures until the timeout', async () => { const fetchImpl = vi.fn().mockRejectedValue(new Error('temporary failure')); const waitOptions = options(fetchImpl, { pollSeconds: 2 }); - const result = expect(waitForNpmPackages([pkg], waitOptions)).rejects.toThrow( - 'Timed out after 5s waiting for npm propagation: pkg@1.2.3', - ); - - await vi.advanceTimersByTimeAsync(5_000); - await result; + await Promise.all([ + expect(waitForNpmPackages([pkg], waitOptions)).rejects.toThrow( + 'Timed out after 5s waiting for npm propagation: pkg@1.2.3', + ), + vi.advanceTimersByTimeAsync(5000), + ]); expect(fetchImpl).toHaveBeenCalledTimes(3); - expect(waitOptions.sleep).toHaveBeenLastCalledWith(1_000); + expect(waitOptions.sleep).toHaveBeenLastCalledWith(1000); expect(vi.getTimerCount()).toBe(0); }); test('checks the deadline before each package', async () => { const fetchImpl = vi.fn(async () => { - vi.setSystemTime(Date.now() + 5_000); + vi.setSystemTime(Date.now() + 5000); return response(404); }); @@ -128,13 +130,13 @@ describe('waitForNpmPackages', () => { }); test('aborts a stalled request at the deadline and skips later packages', async () => { - const fetchImpl = vi.fn(stalledFetch); - const result = expect(waitForNpmPackages(pendingPackages, options(fetchImpl))).rejects.toThrow( - 'Timed out after 5s waiting for npm propagation: first@1.2.3, second@1.2.3', - ); - - await vi.advanceTimersByTimeAsync(5_000); - await result; + const fetchImpl = vi.fn(stalledFetch); + await Promise.all([ + expect(waitForNpmPackages(pendingPackages, options(fetchImpl))).rejects.toThrow( + 'Timed out after 5s waiting for npm propagation: first@1.2.3, second@1.2.3', + ), + vi.advanceTimersByTimeAsync(5000), + ]); expect(fetchImpl).toHaveBeenCalledTimes(1); expect(fetchImpl.mock.calls[0]?.[1]?.signal?.aborted).toBe(true); diff --git a/.github/scripts/agent-command-timeouts.ts b/.github/scripts/agent-command-timeouts.ts index cfb3288b46..0b4690d105 100644 --- a/.github/scripts/agent-command-timeouts.ts +++ b/.github/scripts/agent-command-timeouts.ts @@ -10,61 +10,79 @@ export interface CommandTimeout { timeoutMs: number; } -type ContentBlock = { +interface SdkObject { type?: unknown; + message?: unknown; + content?: unknown; id?: unknown; + input?: unknown; + command?: unknown; + description?: unknown; + tool_use_result?: unknown; + timedOutAfterMs?: unknown; tool_use_id?: unknown; - input?: { command?: unknown; description?: unknown }; -}; +} -type SdkMessage = { - type?: unknown; - message?: { content?: unknown }; - tool_use_result?: { timedOutAfterMs?: unknown }; -}; +function isSdkObject(value: unknown): value is SdkObject { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} /** * Finds Bash calls that exceeded Claude Code's per-command timeout in the SDK * messages that claude-code-action writes to its `execution_file` output. */ -export function findCommandTimeouts(messages: unknown): CommandTimeout[] { +export function findCommandTimeouts(messages: unknown): Array { if (!Array.isArray(messages)) { throw new Error('Expected the execution file to contain an array of SDK messages'); } - const inputs = new Map(); - const timeouts: CommandTimeout[] = []; - for (const message of messages as SdkMessage[]) { - const content = message?.message?.content; - if (!Array.isArray(content)) { + const inputs = new Map(); + const timeouts: Array = []; + const entries: Array = messages; + for (const entry of entries) { + if ( + !isSdkObject(entry) || + !isSdkObject(entry.message) || + !Array.isArray(entry.message.content) + ) { continue; } - const blocks = content as ContentBlock[]; - if (message.type === 'assistant') { + const blocks = entry.message.content.filter(isSdkObject); + if (entry.type === 'assistant') { for (const block of blocks) { - if (block?.type === 'tool_use') { - inputs.set(block.id, block.input); + if (block.type === 'tool_use' && typeof block.id === 'string' && isSdkObject(block.input)) { + const { command, description } = block.input; + inputs.set(block.id, { + command: typeof command === 'string' ? command : '', + description: typeof description === 'string' ? description : undefined, + }); } } continue; } - // Each tool result is sent in its own user message with the structured result. - const timeoutMs = message.tool_use_result?.timedOutAfterMs; - const result = blocks.find((block) => block?.type === 'tool_result'); - if (message.type !== 'user' || typeof timeoutMs !== 'number' || !result) { + const details = entry.tool_use_result; + if ( + entry.type !== 'user' || + !isSdkObject(details) || + typeof details.timedOutAfterMs !== 'number' + ) { continue; } - const input = inputs.get(result.tool_use_id); - timeouts.push({ - command: typeof input?.command === 'string' ? input.command : '', - description: typeof input?.description === 'string' ? input.description : undefined, - timeoutMs, - }); + const result = blocks.find((block) => block.type === 'tool_result'); + if (result) { + const input = + typeof result.tool_use_id === 'string' ? inputs.get(result.tool_use_id) : undefined; + timeouts.push({ + command: input?.command ?? '', + description: input?.description, + timeoutMs: details.timedOutAfterMs, + }); + } } return timeouts; } /** Formats the timeouts as a Markdown list with each command in a code block. */ -export function formatCommandTimeouts(timeouts: CommandTimeout[]): string { +export function formatCommandTimeouts(timeouts: Array): string { return timeouts .map(({ command, description, timeoutMs }) => { const longestBackticks = Math.max( diff --git a/.github/scripts/cli-help-diff.ts b/.github/scripts/cli-help-diff.ts index f41d1d64cd..7f29cff39d 100644 --- a/.github/scripts/cli-help-diff.ts +++ b/.github/scripts/cli-help-diff.ts @@ -13,10 +13,14 @@ import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { parseArgs, stripVTControlCharacters } from 'node:util'; +import type { JsonObject } from '../../packages/cli/src/utils/json-value.ts'; +import { isObjectValue } from '../../packages/cli/src/utils/json-value.ts'; +import { readJsonObject, requireJsonObject } from '../../scripts/json.ts'; + type ToolName = 'vite' | 'vitest' | 'oxlint' | 'oxfmt' | 'tsdown'; type Tool = { - commands: string[][]; + commands: Array>; name: ToolName; packageName: string; title: string; @@ -28,24 +32,14 @@ type ToolSnapshot = { }; type Snapshot = { - tools: Record; + tools: Record; }; -type VersionMetadata = Partial< - Record< - ToolName, - { - new: string; - tag?: string; - } - > ->; - const ROOT = process.cwd(); const WORKSPACE_PATH = join(ROOT, 'pnpm-workspace.yaml'); // Leave room for five reports plus Markdown within GitHub's 65,536-character comment limit. const MAX_DIFF_LENGTH = 12_000; -const TOOLS: Tool[] = [ +const TOOLS: Array = [ { // Vite+ mirrors the root command plus the build and preview option sets. commands: [['--help'], ['build', '--help'], ['preview', '--help']], @@ -79,14 +73,12 @@ const TOOLS: Tool[] = [ }, ]; -function readJson(filePath: string): unknown { - return JSON.parse(readFileSync(filePath, 'utf8')); -} - -function readToolVersion(tool: Tool, versions?: VersionMetadata): string { +function readToolVersion(tool: Tool, versions?: JsonObject): string { if (versions) { const change = versions[tool.name]; - const version = tool.name === 'vite' ? change?.tag?.replace(/^v/, '') : change?.new; + const value = isObjectValue(change) ? change[tool.name === 'vite' ? 'tag' : 'new'] : undefined; + const version = + typeof value === 'string' && (tool.name === 'vite' ? value.replace(/^v/, '') : value); if (!version) { throw new Error(`Upgrade metadata has no target version for ${tool.name}`); } @@ -94,7 +86,7 @@ function readToolVersion(tool: Tool, versions?: VersionMetadata): string { } if (tool.name === 'vite') { - const pkg = readJson(join(ROOT, 'vite/packages/vite/package.json')) as { version?: unknown }; + const pkg = readJsonObject(join(ROOT, 'vite/packages/vite/package.json')); if (typeof pkg.version !== 'string') { throw new TypeError('vite/packages/vite/package.json has no version'); } @@ -150,8 +142,8 @@ function captureToolHelp(tool: Tool, version: string, cwd: string): string { } function captureSnapshot(outputPath: string, versionsPath?: string): void { - const versions = versionsPath ? (readJson(versionsPath) as VersionMetadata) : undefined; - const tools = {} as Record; + const versions = versionsPath ? readJsonObject(versionsPath) : undefined; + const tools: Snapshot['tools'] = {}; // Run outside the repository so pnpm dlx does not inherit workspace overrides or patches. const cwd = mkdtempSync(join(tmpdir(), 'vite-plus-cli-help-capture-')); try { @@ -276,14 +268,31 @@ function renderReport(before: Snapshot, after: Snapshot, hasChanges: boolean): s return `${lines.join('\n').trimEnd()}\n`; } +function readSnapshot(path: string): Snapshot { + const entries = requireJsonObject(readJsonObject(path).tools, path); + const tools: Snapshot['tools'] = {}; + for (const { name } of TOOLS) { + const entry = entries[name]; + if ( + !isObjectValue(entry) || + typeof entry.help !== 'string' || + typeof entry.version !== 'string' + ) { + throw new Error(`Invalid snapshot for ${name} in ${path}`); + } + tools[name] = { help: entry.help, version: entry.version }; + } + return { tools }; +} + function generateReport( beforePath: string, afterPath: string, outputPath: string, githubOutputPath?: string, ): void { - const before = readJson(beforePath) as Snapshot; - const after = readJson(afterPath) as Snapshot; + const before = readSnapshot(beforePath); + const after = readSnapshot(afterPath); const hasChanges = hasHelpChanges(before, after); mkdirSync(dirname(outputPath), { recursive: true }); writeFileSync(outputPath, renderReport(before, after, hasChanges)); diff --git a/.github/scripts/publish-npm-package.ts b/.github/scripts/publish-npm-package.ts index 6156e0d300..26341a48d0 100644 --- a/.github/scripts/publish-npm-package.ts +++ b/.github/scripts/publish-npm-package.ts @@ -2,9 +2,8 @@ import { spawn } from 'node:child_process'; import { resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; +import type { FetchLike, NpmPackageVersion } from './wait-for-npm-packages.ts'; import { - type FetchLike, - type NpmPackageVersion, DEFAULT_NPM_REGISTRY, isNpmPackagePublished, parseNpmPackageSpec, @@ -20,14 +19,14 @@ export interface PublishCommandResult { export type PublishCommandRunner = ( command: string, - args: readonly string[], + args: ReadonlyArray, cwd: string, ) => Promise; export interface PublishNpmPackageOptions { pkg: NpmPackageVersion; command: string; - args: readonly string[]; + args: ReadonlyArray; cwd: string; registry: string; fetchImpl: FetchLike; @@ -95,7 +94,7 @@ export async function publishNpmPackage( function runPublishCommand( command: string, - args: readonly string[], + args: ReadonlyArray, cwd: string, ): Promise { return new Promise((resolveResult) => { @@ -122,7 +121,7 @@ function runPublishCommand( export async function publishNpmPackageFromEnv( pkg: NpmPackageVersion, command: string, - args: readonly string[], + args: ReadonlyArray, cwd = process.cwd(), ): Promise { return publishNpmPackage({ @@ -157,7 +156,7 @@ async function main(): Promise { const invokedPath = process.argv[1]; if (invokedPath && pathToFileURL(resolve(invokedPath)).href === import.meta.url) { - main().catch((error: unknown) => { + await main().catch((error: unknown) => { console.error(`::error::${error instanceof Error ? error.message : String(error)}`); process.exitCode = 1; }); diff --git a/.github/scripts/test-homebrew.mjs b/.github/scripts/test-homebrew.mjs index 4e5b37e7a5..44d05c77a6 100644 --- a/.github/scripts/test-homebrew.mjs +++ b/.github/scripts/test-homebrew.mjs @@ -124,7 +124,10 @@ async function registry(packagesDir) { // The private mirror also checks credentials without forwarding them upstream. async function mirrorRegistry(upstream, authenticated = false) { const requests = new Set(); - const server = createServer(async (request, response) => { + const server = createServer((request, response) => { + void forward(request, response).catch(() => response.destroy()); + }); + async function forward(request, response) { if (authenticated && request.headers.authorization !== `Bearer ${token}`) { response.writeHead(401).end('Unauthorized'); return; @@ -156,7 +159,7 @@ async function mirrorRegistry(upstream, authenticated = false) { } catch { response.writeHead(502).end('Registry fixture failed'); } - }); + } servers.push(server); server.listen(0, '127.0.0.1'); await once(server, 'listening'); diff --git a/.github/scripts/update-homebrew-formula.mjs b/.github/scripts/update-homebrew-formula.mjs index edd97dcd00..eb76044784 100644 --- a/.github/scripts/update-homebrew-formula.mjs +++ b/.github/scripts/update-homebrew-formula.mjs @@ -15,8 +15,8 @@ export const targets = [ ['linux', 'intel', 'x86_64-unknown-linux-gnu', 'linux-x64-gnu'], ]; const repository = 'voidzero-dev/vite-plus'; -const assetBlock = / # BEGIN RELEASE ASSETS\n[\s\S]*? # END RELEASE ASSETS/; -const launchGate = / # The updater removes this gate[^\n]*\n disable! [^\n]*\n\n/; +const assetBlock = / {2}# BEGIN RELEASE ASSETS\n[\s\S]*? {2}# END RELEASE ASSETS/; +const launchGate = / {2}# The updater removes this gate[^\n]*\n {2}disable! [^\n]*\n\n/; // Published-artifact tests must use the candidate's actual URLs and lockfile. // Reject mixed releases instead of deriving an expected version from the checkout. @@ -101,7 +101,7 @@ export function updateFormula(source, version, assets) { .replace(assetBlock, ` # BEGIN RELEASE ASSETS\n${blocks}\n # END RELEASE ASSETS`) .replace(launchGate, ''); if (difference > 0) { - updated = updated.replace(/^ revision \d+\n/m, ''); + updated = updated.replace(/^ {2}revision \d+\n/m, ''); } return updated; } diff --git a/.github/scripts/upgrade-deps-utils.ts b/.github/scripts/upgrade-deps-utils.ts index 8ded25dd22..842f6b71a1 100644 --- a/.github/scripts/upgrade-deps-utils.ts +++ b/.github/scripts/upgrade-deps-utils.ts @@ -2,11 +2,14 @@ import { readFileSync, writeFileSync } from 'node:fs'; import { createRequire } from 'node:module'; import { join } from 'node:path'; +import { isJsonObject, isObjectValue } from '../../packages/cli/src/utils/json-value.ts'; +import { readJsonObject } from '../../scripts/json.ts'; + type DependencyField = 'dependencies' | 'optionalDependencies'; export function getBundledDependencyRanges( root: string, -): { name: string; field: DependencyField; range: string }[] { +): Array<{ name: string; field: DependencyField; range: string }> { // Core's direct rolldown-plugin-dts can differ from the copy bundled with tsdown. const coreRequire = createRequire(join(root, 'packages/core/package.json')); const tsdownRequire = createRequire(coreRequire.resolve('tsdown/package.json')); @@ -14,32 +17,27 @@ export function getBundledDependencyRanges( const vitePath = join(root, 'vite/packages/vite/package.json'); // These packages stay external in packages/core/build.ts. Follow their // bundled consumers rather than independently selecting the latest releases. - const sources: { path: string; field: DependencyField; names: string[] }[] = [ - { path: pluginPath, field: 'dependencies', names: ['yuku-parser'] }, - { path: vitePath, field: 'dependencies', names: ['postcss'] }, - { path: vitePath, field: 'optionalDependencies', names: ['fsevents'] }, + const sources: Array<{ path: string; field: DependencyField; name: string }> = [ + { path: pluginPath, field: 'dependencies', name: 'yuku-parser' }, + { path: vitePath, field: 'dependencies', name: 'postcss' }, + { path: vitePath, field: 'optionalDependencies', name: 'fsevents' }, ]; - return sources.flatMap(({ path, field, names }) => { - const pkg = JSON.parse(readFileSync(path, 'utf8')) as Partial< - Record> - >; - return names.map((name) => { - let range = pkg[field]?.[name]; - if (typeof range !== 'string' || range.trim() === '') { - throw new Error(`Missing ${field}.${name} in ${path}; review core's externals`); - } - if (name === 'yuku-parser') { - // The AST helpers and codegen are bundled. Pin the runtime parser to - // the exact version resolved by the same plugin so it cannot drift. - const parserPath = createRequire(path).resolve('yuku-parser/package.json'); - const { version } = JSON.parse(readFileSync(parserPath, 'utf8')) as { version?: unknown }; - if (typeof version !== 'string' || version.trim() === '') { - throw new Error(`Missing version in ${parserPath}; review core's externals`); - } - range = version; + return sources.map(({ path, field, name }) => { + const dependencies = readJsonObject(path)[field]; + let range = isObjectValue(dependencies) ? dependencies[name] : undefined; + if (typeof range !== 'string' || range.trim() === '') { + throw new Error(`Missing ${field}.${name} in ${path}; review core's externals`); + } + if (name === 'yuku-parser') { + // Pin the runtime parser to the exact version resolved by the bundled plugin. + const parserPath = createRequire(path).resolve('yuku-parser/package.json'); + const { version } = readJsonObject(parserPath); + if (typeof version !== 'string' || version.trim() === '') { + throw new Error(`Missing version in ${parserPath}; review core's externals`); } - return { name, field, range }; - }); + range = version; + } + return { name, field, range }; }); } @@ -131,14 +129,11 @@ export async function getPnpmInstallerIntegrity(version: string): Promise + installer.updated = installer.updated.replaceAll(integrityPattern, (match: string) => match.replace(oldIntegrity, integrity), ); // Validate every copy before writing so a stale pattern cannot leave partial pins. diff --git a/.github/scripts/upgrade-deps.ts b/.github/scripts/upgrade-deps.ts index 5c45169e60..166f9bf24d 100644 --- a/.github/scripts/upgrade-deps.ts +++ b/.github/scripts/upgrade-deps.ts @@ -2,11 +2,14 @@ import { execFileSync } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; +import type { JsonObject } from '../../packages/cli/src/utils/json-value.ts'; +import { isObjectValue, isJsonObject } from '../../packages/cli/src/utils/json-value.ts'; import { CORE_PACKAGE_NAME, initialCoreVersion, tryDecodeCoreVersion, } from '../../packages/tools/src/core-version.ts'; +import { readJsonObject, requireJsonObject } from '../../scripts/json.ts'; import { findLatestStableVersionForMajor, getBundledDependencyRanges, @@ -24,13 +27,6 @@ type Change = { tag?: string; }; -type GitHubTag = { - name?: unknown; - commit?: { - sha?: unknown; - }; -}; - type LatestTag = { sha: string; tag: string; @@ -40,26 +36,8 @@ type LatestTagOptions = { stableOnly?: boolean; }; -type NpmVersionResponse = { - version?: unknown; - dependencies?: Record; -}; - -type NpmPackumentResponse = { - versions?: Record; -}; - -type UpstreamVersions = { - rolldown: { - hash: string; - }; - vite: { - hash: string; - }; - 'oxc-node': { - hash: string; - }; -}; +const upstreamNames = ['rolldown', 'vite', 'oxc-node'] as const; +type UpstreamVersions = Record<(typeof upstreamNames)[number], { hash: string }>; type PnpmWorkspaceVersions = { vitest: string; @@ -97,10 +75,6 @@ const isFullSha = (s: string): boolean => /^[0-9a-f]{40}$/.test(s); const changes = new Map(); -function readJsonFile(filePath: string) { - return JSON.parse(fs.readFileSync(filePath, 'utf8')); -} - function recordChange( name: string, oldValue: string | null | undefined, @@ -139,17 +113,26 @@ async function getLatestTag( if (!res.ok) { throw new Error(`Failed to fetch tags for ${owner}/${repo}: ${res.status} ${res.statusText}`); } - const tags = (await res.json()) as GitHubTag[]; + const tags: unknown = await res.json(); if (!Array.isArray(tags) || !tags.length) { throw new Error(`No tags found for ${owner}/${repo}`); } + const entries: Array = tags; const latest = options.stableOnly - ? tags.find((tag) => typeof tag.name === 'string' && STABLE_SEMVER_TAG_RE.test(tag.name)) - : tags[0]; + ? entries.find( + (tag) => + isJsonObject(tag) && typeof tag.name === 'string' && STABLE_SEMVER_TAG_RE.test(tag.name), + ) + : entries[0]; if (!latest) { throw new Error(`No stable semver tags found for ${owner}/${repo}`); } - if (typeof latest?.commit?.sha !== 'string' || typeof latest.name !== 'string') { + if ( + !isJsonObject(latest) || + !isObjectValue(latest.commit) || + typeof latest.commit.sha !== 'string' || + typeof latest.name !== 'string' + ) { throw new Error(`Invalid tag structure for ${owner}/${repo}: missing SHA or name`); } console.log(`${repo} -> ${latest.name} (${latest.commit.sha.slice(0, 7)})`); @@ -171,19 +154,19 @@ async function containsCommit( if (!res.ok) { throw new Error(`Failed to compare ${owner}/${repo} ${base}...${head}: ${res.status}`); } - const { status } = (await res.json()) as { status?: unknown }; + const { status } = requireJsonObject(await res.json(), 'GitHub comparison'); return status === 'ahead' || status === 'identical'; } // ============ npm Registry ============ -async function fetchNpmVersion(packageName: string): Promise { +async function fetchNpmVersion(packageName: string): Promise { const res = await fetch(`https://registry.npmjs.org/${packageName}/latest`); if (!res.ok) { throw new Error( `Failed to fetch npm metadata for ${packageName}: ${res.status} ${res.statusText}`, ); } - return (await res.json()) as NpmVersionResponse; + return requireJsonObject(await res.json(), packageName); } async function getNpmVersion(packageName: string): Promise { @@ -203,8 +186,11 @@ async function getLatestNpmVersionForMajor(packageName: string, major: number): `Failed to fetch npm metadata for ${packageName}: ${res.status} ${res.statusText}`, ); } - const data = (await res.json()) as NpmPackumentResponse; - const version = findLatestStableVersionForMajor(Object.keys(data.versions ?? {}), major); + const data = requireJsonObject(await res.json(), packageName); + const version = findLatestStableVersionForMajor( + Object.keys(isObjectValue(data.versions) ? data.versions : {}), + major, + ); if (!version) { throw new Error(`No stable ${major}.x version found for ${packageName}`); } @@ -220,7 +206,7 @@ async function getLatestPnpmInstaller(): Promise<{ version: string; integrity: s // e.g. the `lightningcss` range that the bundled `@tsdown/css` depends on. async function getNpmDependencyRange(packageName: string, dependencyName: string): Promise { const data = await fetchNpmVersion(packageName); - const range = data.dependencies?.[dependencyName]; + const range = isObjectValue(data.dependencies) ? data.dependencies[dependencyName] : undefined; if (typeof range !== 'string') { throw new Error( `Invalid npm response for ${packageName}: missing dependencies.${dependencyName}`, @@ -229,10 +215,20 @@ async function getNpmDependencyRange(packageName: string, dependencyName: string return range; } +function hasUpstreamHashes(data: JsonObject): data is JsonObject & UpstreamVersions { + return upstreamNames.every((name) => { + const upstream = data[name]; + return isObjectValue(upstream) && typeof upstream.hash === 'string'; + }); +} + // ============ Update .upstream-versions.json ============ async function updateUpstreamVersions(): Promise { const filePath = path.join(ROOT, 'packages/tools/.upstream-versions.json'); - const data: UpstreamVersions = readJsonFile(filePath); + const data = readJsonObject(filePath); + if (!hasUpstreamHashes(data)) { + throw new Error(`Invalid upstream hashes in ${filePath}`); + } const oldRolldownHash = data.rolldown.hash; const oldViteHash = data.vite.hash; @@ -277,13 +273,15 @@ async function updatePnpmWorkspace(versions: PnpmWorkspaceVersions): Promise ({ - name: pkg, - pattern: new RegExp(`'${pkg.replaceAll('/', '\\/')}': ([\\d.]+(?:-[\\w.]+)?)`), - replacement: `'${pkg}': ${versions.vitest}`, - newVersion: versions.vitest, - })); - const entries: PnpmWorkspaceEntry[] = [ + const vitestExactVersionEntries: Array = vitestExactVersionPackages.map( + (pkg) => ({ + name: pkg, + pattern: new RegExp(`'${pkg.replaceAll('/', String.raw`\/`)}': ([\\d.]+(?:-[\\w.]+)?)`), + replacement: `'${pkg}': ${versions.vitest}`, + newVersion: versions.vitest, + }), + ); + const entries: Array = [ { name: 'vitest', // The `@voidzero-dev/vite-plus-test` wrapper (which used to be aliased @@ -506,8 +504,7 @@ function writeMetaFiles(): void { } bodyLines.push('', '## Dependency updates', ''); if (changed.length) { - bodyLines.push('| Package | From | To |'); - bodyLines.push('| --- | --- | --- |'); + bodyLines.push('| Package | From | To |', '| --- | --- | --- |'); for (const [name, v] of changed) { bodyLines.push(`| \`${name}\` | \`${formatOld(v)}\` | \`${formatVersion(v)}\` |`); } @@ -532,23 +529,31 @@ function writeMetaFiles(): void { function syncBundledDependencies(): void { if (META_DIR) { const versionsPath = path.join(META_DIR, 'versions.json'); - const previous = readJsonFile(versionsPath) as Record; + const previous = readJsonObject(versionsPath); for (const [name, change] of Object.entries(previous)) { - changes.set(name, change); + if ( + !isObjectValue(change) || + (change.old !== null && typeof change.old !== 'string') || + typeof change.new !== 'string' || + (change.tag !== undefined && typeof change.tag !== 'string') + ) { + throw new Error(`Invalid version change for ${name} in ${versionsPath}`); + } + changes.set(name, { old: change.old, new: change.new, tag: change.tag }); } } const ranges = getBundledDependencyRanges(ROOT); const filePath = path.join(ROOT, 'packages/core/package.json'); - const pkg = readJsonFile(filePath); + const pkg = readJsonObject(filePath); for (const { name, field, range } of ranges) { - const oldRange = pkg[field]?.[name]; - if (typeof oldRange !== 'string') { + const dependencies = pkg[field]; + if (!isObjectValue(dependencies) || typeof dependencies[name] !== 'string') { throw new Error(`Missing ${field}.${name} in ${filePath}`); } // Preserve the original version if synchronization runs again after fixups. - recordChange(name, changes.get(name)?.old ?? oldRange, range); - pkg[field][name] = range; + recordChange(name, changes.get(name)?.old ?? dependencies[name], range); + dependencies[name] = range; } syncCoreVersion(pkg); fs.writeFileSync(filePath, JSON.stringify(pkg, null, 2) + '\n'); @@ -558,13 +563,16 @@ function syncBundledDependencies(): void { // The core version encodes the bundled Vite version (rfcs/core-version-alignment.md). // When the bundled Vite changes, restart the release counter at 0. The release // workflow selects the next unpublished counter. -function syncCoreVersion(pkg: { version?: unknown; bundledVersions?: Record }) { +function syncCoreVersion(pkg: JsonObject) { const vitePath = path.join(ROOT, 'vite/packages/vite/package.json'); - const viteVersion = readJsonFile(vitePath).version; + const viteVersion = readJsonObject(vitePath).version; if (typeof viteVersion !== 'string' || !viteVersion.trim()) { throw new Error(`Missing version in ${vitePath}`); } - pkg.bundledVersions = { ...pkg.bundledVersions, vite: viteVersion }; + if (!isObjectValue(pkg.bundledVersions)) { + pkg.bundledVersions = {}; + } + pkg.bundledVersions.vite = viteVersion; const current = typeof pkg.version === 'string' ? pkg.version : undefined; if (current !== undefined && tryDecodeCoreVersion(current)?.vite === viteVersion) { return; diff --git a/.github/scripts/wait-for-npm-packages.ts b/.github/scripts/wait-for-npm-packages.ts index a2a0ae770f..46dd4cb8b2 100644 --- a/.github/scripts/wait-for-npm-packages.ts +++ b/.github/scripts/wait-for-npm-packages.ts @@ -2,6 +2,9 @@ import { resolve } from 'node:path'; import { setTimeout as sleep } from 'node:timers/promises'; import { pathToFileURL } from 'node:url'; +import type { JsonValue } from '../../packages/cli/src/utils/json-value.ts'; +import { isJsonObject, isObjectValue } from '../../packages/cli/src/utils/json-value.ts'; + /** The registry used by the release workflow. */ export const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org'; @@ -16,14 +19,10 @@ export type NpmPackageVersion = { version: string; }; -interface AbbreviatedPackument { - versions?: Record; -} - export type FetchLike = ( url: string, init?: { method?: string; headers?: Record; signal?: AbortSignal }, -) => Promise<{ ok: boolean; status: number; json: () => Promise }>; +) => Promise<{ ok: boolean; status: number; json: Response['json'] }>; export interface WaitForNpmPackagesOptions { registry: string; @@ -43,22 +42,25 @@ type NpmRegistryRequestOptions = Pick { +): Promise { const registry = options.registry.replace(/\/+$/, ''); - const response = await options.fetchImpl(`${registry}/${name.replace('/', '%2f')}`, { + const response = await options.fetchImpl(`${registry}/${pkg.name.replace('/', '%2f')}`, { headers: { accept: ABBREVIATED_PACKUMENT_ACCEPT }, signal: options.signal, }); if (response.status === 404) { - return null; + return undefined; } if (!response.ok) { throw new Error(`registry returned HTTP ${response.status}`); } - return (await response.json()) as AbbreviatedPackument; + const data: unknown = await response.json(); + return isJsonObject(data) && isObjectValue(data.versions) + ? data.versions[pkg.version] + : undefined; } /** Checks whether npm has made an immutable package version visible. */ @@ -66,8 +68,7 @@ export async function isNpmPackagePublished( pkg: NpmPackageVersion, options: NpmRegistryRequestOptions, ): Promise { - const packument = await fetchNpmPackument(pkg.name, options); - return packument?.versions?.[pkg.version] !== undefined; + return (await fetchNpmVersion(pkg, options)) !== undefined; } /** @@ -78,9 +79,10 @@ export async function isNpmPackageAvailable( pkg: NpmPackageVersion, options: NpmRegistryRequestOptions, ): Promise { - const packument = await fetchNpmPackument(pkg.name, options); - const tarball = packument?.versions?.[pkg.version]?.dist?.tarball; - if (!tarball) { + const version = await fetchNpmVersion(pkg, options); + const tarball = + isObjectValue(version) && isObjectValue(version.dist) ? version.dist.tarball : undefined; + if (typeof tarball !== 'string' || !tarball) { return false; } @@ -109,7 +111,7 @@ function propagationTimeoutError( * on to a package that pins it as a dependency. */ export async function waitForNpmPackages( - packages: readonly NpmPackageVersion[], + packages: ReadonlyArray, options: WaitForNpmPackagesOptions, ): Promise { if (packages.length === 0) { @@ -204,7 +206,7 @@ function readNonNegativeInteger(name: string, fallback: number): number { /** Uses the release workflow's propagation settings. */ export async function waitForNpmPackagesFromEnv( - packages: readonly NpmPackageVersion[], + packages: ReadonlyArray, ): Promise { if (process.env.PUBLISH_SKIP_PROPAGATION_WAIT === 'true') { console.log('Skipping npm propagation wait.'); @@ -234,7 +236,7 @@ async function main(): Promise { const invokedPath = process.argv[1]; if (invokedPath && pathToFileURL(resolve(invokedPath)).href === import.meta.url) { - main().catch((error: unknown) => { + await main().catch((error: unknown) => { console.error(`::error::${error instanceof Error ? error.message : String(error)}`); process.exitCode = 1; }); diff --git a/bench/generate-monorepo.ts b/bench/generate-monorepo.ts index 76cc9da937..339a8208ae 100644 --- a/bench/generate-monorepo.ts +++ b/bench/generate-monorepo.ts @@ -1,16 +1,14 @@ -import * as fs from 'node:fs'; -import * as path from 'node:path'; -import { fileURLToPath } from 'node:url'; +import fs from 'node:fs'; +import path from 'node:path'; interface Package { name: string; - dependencies: string[]; + dependencies: Array; scripts: Record; hasVitePlusConfig: boolean; } -// oxlint-disable-next-line no-underscore-dangle -const __dirname = path.join(fileURLToPath(import.meta.url), '..'); +const benchDir = import.meta.dirname; class MonorepoGenerator { private packages: Map = new Map(); @@ -26,7 +24,7 @@ class MonorepoGenerator { return Math.floor(Math.random() * (max - min + 1)) + min; } - private getRandomElement(arr: T[]): T { + private getRandomElement(arr: Array): T { return arr[Math.floor(Math.random() * arr.length)]; } @@ -50,7 +48,7 @@ class MonorepoGenerator { // Generate command with 0-3 && concatenations const numCommands = this.getRandomInt(1, 4); - const selectedCommands: string[] = []; + const selectedCommands: Array = []; for (let i = 0; i < numCommands; i++) { selectedCommands.push(this.getRandomElement(commands)); @@ -59,8 +57,8 @@ class MonorepoGenerator { return selectedCommands.join(' && '); } - private generateScripts(packageName: string): Record { - const scripts: Record = {}; + private generateScripts(packageName: string): Package['scripts'] { + const scripts: Package['scripts'] = {}; // Each package has 2-3 scripts const numScripts = this.getRandomInt(2, 3); @@ -77,14 +75,17 @@ class MonorepoGenerator { return scripts; } - private selectDependencies(currentIndex: number, availablePackages: string[]): string[] { + private selectDependencies( + currentIndex: number, + availablePackages: Array, + ): Array { const numDeps = this.getRandomInt(this.MIN_DEPS_PER_PACKAGE, this.MAX_DEPS_PER_PACKAGE); const dependencies = new Set(); // Create a complex graph by selecting dependencies from different layers // Prefer packages with lower indices (creates deeper dependency chains) const eligiblePackages = availablePackages.filter((pkg) => { - const pkgIndex = parseInt(pkg.split('-')[1]); + const pkgIndex = Number.parseInt(pkg.split('-')[1]); return pkgIndex < currentIndex; }); @@ -114,7 +115,7 @@ class MonorepoGenerator { private generatePackages(): void { // First, create all package names - const allPackageNames: string[] = []; + const allPackageNames: Array = []; for (let i = 0; i < this.PACKAGE_COUNT; i++) { allPackageNames.push(this.generatePackageName(i)); } @@ -340,6 +341,6 @@ module.exports = { ${pkg.name.replace('-', '_')} }; } // Main execution -const outputDir = path.join(__dirname, 'fixtures', 'monorepo'); +const outputDir = path.join(benchDir, 'fixtures', 'monorepo'); const generator = new MonorepoGenerator(outputDir); generator.generate(); diff --git a/bench/vpx-script.ts b/bench/vpx-script.ts index c123805fd9..b59a3c6467 100644 --- a/bench/vpx-script.ts +++ b/bench/vpx-script.ts @@ -28,10 +28,10 @@ import { mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'nod import { createRequire } from 'node:module'; import { tmpdir } from 'node:os'; import path from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; +import { pathToFileURL } from 'node:url'; import { parseArgs } from 'node:util'; -const repo = path.join(path.dirname(fileURLToPath(import.meta.url)), '..'); +const repo = path.join(import.meta.dirname, '..'); const fixtures = path.join(tmpdir(), 'vite-plus-bench-vpx-script'); const dist = path.join(repo, 'packages/cli/dist'); const modules = 300; @@ -52,7 +52,12 @@ const tsxPackage = createRequire(path.join(repo, 'packages/core/package.json')). 'tsx/package.json', ); const tsxDir = path.dirname(tsxPackage); -const tsxVersion = (JSON.parse(readFileSync(tsxPackage, 'utf8')) as { version: string }).version; +const metadata: unknown = JSON.parse(readFileSync(tsxPackage, 'utf8')); +const tsxVersion = + metadata && typeof metadata === 'object' && 'version' in metadata ? metadata.version : undefined; +if (typeof tsxVersion !== 'string') { + throw new TypeError('Expected tsx to have a package version'); +} function write(file: string, content: string): void { mkdirSync(path.dirname(path.join(fixtures, file)), { recursive: true }); @@ -122,7 +127,7 @@ function generateFixtures(): void { // One 1.8 MB file without import/export, as CommonJS and as an ES module. let large = ''; - for (let i = 0; i < 12000; i++) { + for (let i = 0; i < 12_000; i++) { large += `interface Shape${i} { id: number; label: string }\n` + `function make${i}(id: number): Shape${i} { return { id, label: 'shape-${i}-' + id.toString(16) }; }\n`; @@ -147,11 +152,11 @@ interface Command { label: string; /** The executable; the `--node` binary when absent. */ program?: string; - args: string[]; + args: Array; env: NodeJS.ProcessEnv; } -function commands(scenario: string, entry: string, nodeVersion: string): Command[] { +function commands(scenario: string, entry: string, nodeVersion: string): Array { // `VP_HOME` stays, so a global `vpx` finds its managed runtimes. const env = Object.fromEntries( Object.entries(process.env).filter(([key]) => key === 'VP_HOME' || !/^(VP|TSX|OXC)_/.test(key)), @@ -201,7 +206,7 @@ function time(node: string, command: Command, cwd: string) { }; } -function median(sorted: number[]): number { +function median(sorted: Array): number { const middle = Math.floor(sorted.length / 2); return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2; } @@ -212,13 +217,13 @@ const nodes = values.node.map((node) => ({ node, version: spawnSync(node, ['-p', 'process.versions.node']).stdout.toString().trim(), })); -const results: { +const results: Array<{ node: string; scenario: string; command: string; median: number; - samples: number[]; -}[] = []; + samples: Array; +}> = []; for (const { node, version } of nodes) { for (const { name, entry } of scenarios) { const cwd = path.join(fixtures, name); @@ -260,7 +265,7 @@ console.log(`tsx ${tsxVersion}; median of ${runs} runs after ${warmup} warmup ru console.log(`| Scenario | Command | ${versions.map((v) => `Node.js ${v}`).join(' | ')} |`); console.log(`| --- | --- | ${versions.map(() => '--:').join(' | ')} |`); for (const { name } of scenarios) { - const labels = [...new Set(results.filter((r) => r.scenario === name).map((r) => r.command))]; + const labels = [...new Set(results.flatMap((r) => (r.scenario === name ? [r.command] : [])))]; for (const label of labels) { const cells = versions.map((version) => { const row = results.find( diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_root_vite_signals/configs/custom-app.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_root_vite_signals/configs/custom-app.ts index 055a075f10..3876a6ee7a 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_root_vite_signals/configs/custom-app.ts +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_root_vite_signals/configs/custom-app.ts @@ -1,4 +1,4 @@ -import { emitMilestone } from './milestone'; +import { emitMilestone } from './milestone.ts'; const appType = 'custom'; diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_root_vite_signals/configs/root-no-index.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_root_vite_signals/configs/root-no-index.ts index 2e81bb015e..7e6dbf8c6a 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_root_vite_signals/configs/root-no-index.ts +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_root_vite_signals/configs/root-no-index.ts @@ -1,4 +1,4 @@ -import { emitMilestone } from './milestone'; +import { emitMilestone } from './milestone.ts'; const appRoot = 'src'; diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_module_formats.global.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_module_formats.global.md index d7a2fef3d0..56eeda7269 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_module_formats.global.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_module_formats.global.md @@ -9,12 +9,12 @@ A .cts that uses export is CommonJS with ES module syntax; it fails with a clear **Exit code:** 1 ``` -/packages/cli/dist/script-preload.cjs:477 +/packages/cli/dist/script-preload.cjs:474 const result = oxcNode.load(url, context, nextLoad, HELPER_MODULE_NAME); ^ Error: Failed to transform /src/both.cts: a `.cts` file is CommonJS, but this one uses ES module syntax (`import`, `export` or `import.meta`), which oxc-node does not compile to CommonJS. Rename it to `.mts` to run it as an ES module, or write it as CommonJS with `import x = require("...")` and `export =`. - at load (/packages/cli/dist/script-preload.cjs:477:25) + at load (/packages/cli/dist/script-preload.cjs:474:25) at nextStep (node:internal/modules/customization_hooks:189:26) at loadWithHooks (node:internal/modules/customization_hooks:374:18) at #loadSync (node:internal/modules/esm/loader:865:14) @@ -37,12 +37,12 @@ Importing it reports the same error **Exit code:** 1 ``` -/packages/cli/dist/script-preload.cjs:477 +/packages/cli/dist/script-preload.cjs:474 const result = oxcNode.load(url, context, nextLoad, HELPER_MODULE_NAME); ^ Error: Failed to transform /src/both.cts: a `.cts` file is CommonJS, but this one uses ES module syntax (`import`, `export` or `import.meta`), which oxc-node does not compile to CommonJS. Rename it to `.mts` to run it as an ES module, or write it as CommonJS with `import x = require("...")` and `export =`. - at load (/packages/cli/dist/script-preload.cjs:477:25) + at load (/packages/cli/dist/script-preload.cjs:474:25) at nextStep (node:internal/modules/customization_hooks:189:26) at loadWithHooks (node:internal/modules/customization_hooks:374:18) at #loadSync (node:internal/modules/esm/loader:865:14) diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_module_formats.local.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_module_formats.local.md index d7a2fef3d0..56eeda7269 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_module_formats.local.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_module_formats.local.md @@ -9,12 +9,12 @@ A .cts that uses export is CommonJS with ES module syntax; it fails with a clear **Exit code:** 1 ``` -/packages/cli/dist/script-preload.cjs:477 +/packages/cli/dist/script-preload.cjs:474 const result = oxcNode.load(url, context, nextLoad, HELPER_MODULE_NAME); ^ Error: Failed to transform /src/both.cts: a `.cts` file is CommonJS, but this one uses ES module syntax (`import`, `export` or `import.meta`), which oxc-node does not compile to CommonJS. Rename it to `.mts` to run it as an ES module, or write it as CommonJS with `import x = require("...")` and `export =`. - at load (/packages/cli/dist/script-preload.cjs:477:25) + at load (/packages/cli/dist/script-preload.cjs:474:25) at nextStep (node:internal/modules/customization_hooks:189:26) at loadWithHooks (node:internal/modules/customization_hooks:374:18) at #loadSync (node:internal/modules/esm/loader:865:14) @@ -37,12 +37,12 @@ Importing it reports the same error **Exit code:** 1 ``` -/packages/cli/dist/script-preload.cjs:477 +/packages/cli/dist/script-preload.cjs:474 const result = oxcNode.load(url, context, nextLoad, HELPER_MODULE_NAME); ^ Error: Failed to transform /src/both.cts: a `.cts` file is CommonJS, but this one uses ES module syntax (`import`, `export` or `import.meta`), which oxc-node does not compile to CommonJS. Rename it to `.mts` to run it as an ES module, or write it as CommonJS with `import x = require("...")` and `export =`. - at load (/packages/cli/dist/script-preload.cjs:477:25) + at load (/packages/cli/dist/script-preload.cjs:474:25) at nextStep (node:internal/modules/customization_hooks:189:26) at loadWithHooks (node:internal/modules/customization_hooks:374:18) at #loadSync (node:internal/modules/esm/loader:865:14) diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_tsconfig_transforms.global.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_tsconfig_transforms.global.md index 29e1e6de6a..7ddea19362 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_tsconfig_transforms.global.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_tsconfig_transforms.global.md @@ -34,12 +34,12 @@ Decorators without experimentalDecorators fail with a clear error **Exit code:** 1 ``` -/packages/cli/dist/script-preload.cjs:477 +/packages/cli/dist/script-preload.cjs:474 const result = oxcNode.load(url, context, nextLoad, HELPER_MODULE_NAME); ^ Error: Failed to transform file:///plain/decorators.ts: decorators require `"experimentalDecorators": true` in a tsconfig.json that includes this file; standard (TC39) decorators are not supported yet - at load (/packages/cli/dist/script-preload.cjs:477:25) + at load (/packages/cli/dist/script-preload.cjs:474:25) at nextStep (node:internal/modules/customization_hooks:189:26) at loadWithHooks (node:internal/modules/customization_hooks:374:18) at #loadSync (node:internal/modules/esm/loader:865:14) diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_tsconfig_transforms.local.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_tsconfig_transforms.local.md index 29e1e6de6a..7ddea19362 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_tsconfig_transforms.local.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vpx_script/snapshots/vpx_script_tsconfig_transforms.local.md @@ -34,12 +34,12 @@ Decorators without experimentalDecorators fail with a clear error **Exit code:** 1 ``` -/packages/cli/dist/script-preload.cjs:477 +/packages/cli/dist/script-preload.cjs:474 const result = oxcNode.load(url, context, nextLoad, HELPER_MODULE_NAME); ^ Error: Failed to transform file:///plain/decorators.ts: decorators require `"experimentalDecorators": true` in a tsconfig.json that includes this file; standard (TC39) decorators are not supported yet - at load (/packages/cli/dist/script-preload.cjs:477:25) + at load (/packages/cli/dist/script-preload.cjs:474:25) at nextStep (node:internal/modules/customization_hooks:189:26) at loadWithHooks (node:internal/modules/customization_hooks:374:18) at #loadSync (node:internal/modules/esm/loader:865:14) diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/root_library_build/vite.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/root_library_build/vite.config.ts index 120a1d60fd..21902ec3a3 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/root_library_build/vite.config.ts +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/root_library_build/vite.config.ts @@ -1,4 +1,4 @@ -import { emitMilestone } from './milestone'; +import { emitMilestone } from './milestone.ts'; export default { clearScreen: false, diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/registry/archive.mjs b/crates/vp_cli_snapshots/tests/cli_snapshots/registry/archive.mjs index 003816bb23..ac7510f8a7 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/registry/archive.mjs +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/registry/archive.mjs @@ -27,7 +27,7 @@ export function createTarball(files) { blocks.push(header, contents, Buffer.alloc((512 - (contents.length % 512)) % 512)); } const archive = Buffer.concat([...blocks, Buffer.alloc(1024)]); - const padding = Buffer.alloc((10240 - (archive.length % 10240)) % 10240); + const padding = Buffer.alloc((10_240 - (archive.length % 10_240)) % 10_240); const tarball = gzipSync(Buffer.concat([archive, padding]), { level: 9 }); // The gzip OS byte must not depend on the machine that packs the fixtures. tarball[9] = 255; diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 7db39287df..59749d330c 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -2,7 +2,8 @@ import { resolve } from 'node:path'; import type { VoidZeroThemeConfig } from '@voidzero-dev/vitepress-theme'; import { extendConfig } from '@voidzero-dev/vitepress-theme/config'; -import { defineConfig, type HeadConfig } from 'vitepress'; +import type { HeadConfig } from 'vitepress'; +import { defineConfig } from 'vitepress'; import { groupIconMdPlugin, groupIconVitePlugin } from 'vitepress-plugin-group-icons'; import llmstxt from 'vitepress-plugin-llms'; import { withMermaid } from 'vitepress-plugin-mermaid'; @@ -344,37 +345,26 @@ export default extendConfig( ], }, }, - transformHead({ page, pageData }) { + transformHead({ page, pageData: { frontmatter } }): Array { const url = 'https://viteplus.dev/' + page.replace(/\.md$/, '').replace(/index$/, ''); - - const canonicalUrlEntry: HeadConfig = [ - 'link', - { - rel: 'canonical', - href: url, - }, - ]; - - const ogInfo: HeadConfig[] = [ - ['meta', { property: 'og:title', content: pageData.frontmatter.title ?? 'Vite+' }], + const title = typeof frontmatter.title === 'string' ? frontmatter.title : 'Vite+'; + const description = + typeof frontmatter.description === 'string' + ? frontmatter.description + : 'The Unified Toolchain for the Web'; + return [ + ['meta', { property: 'og:title', content: title }], [ 'meta', { property: 'og:image', - content: `https://viteplus.dev/${pageData.frontmatter.cover ?? 'og.jpg'}`, + content: `https://viteplus.dev/${frontmatter.cover ?? 'og.jpg'}`, }, ], ['meta', { property: 'og:url', content: url }], - [ - 'meta', - { - property: 'og:description', - content: pageData.frontmatter.description ?? 'The Unified Toolchain for the Web', - }, - ], + ['meta', { property: 'og:description', content: description }], + ['link', { rel: 'canonical', href: url }], ]; - - return [...ogInfo, canonicalUrlEntry]; }, markdown: { config(md) { diff --git a/docs/.vitepress/env.d.ts b/docs/.vitepress/env.d.ts index 514d964043..edac5dd93c 100644 --- a/docs/.vitepress/env.d.ts +++ b/docs/.vitepress/env.d.ts @@ -15,14 +15,14 @@ declare module '*VPSponsors.vue' { import type { DefineComponent } from 'vue'; export type Sponsors = Omit & { tier?: string }; - const component: DefineComponent<{}, {}, unknown>; + const component: DefineComponent; export default component; } // Vue SFC module declaration declare module '*.vue' { import type { DefineComponent } from 'vue'; - const component: DefineComponent<{}, {}, unknown>; + const component: DefineComponent; export default component; } diff --git a/docs/.vitepress/site-origin.ts b/docs/.vitepress/site-origin.ts index a0ea83de22..47f538df77 100644 --- a/docs/.vitepress/site-origin.ts +++ b/docs/.vitepress/site-origin.ts @@ -18,9 +18,9 @@ export function resolveDocsSiteOrigin(env: NodeJS.ProcessEnv = process.env): str // Match Wrangler's generatePreviewAlias, including its long-branch hash: // https://developers.cloudflare.com/workers/versions-and-deployments/preview-urls/ let alias = branch - .replace(/[^a-zA-Z0-9-]/g, '-') - .replace(/-+/g, '-') - .replace(/^-+|-+$/g, '') + .replaceAll(/[^a-zA-Z0-9-]/g, '-') + .replaceAll(/-+/g, '-') + .replaceAll(/^-+|-+$/g, '') .toLowerCase(); if (!/^[a-z](?:[a-z0-9-]*[a-z0-9])?$/.test(alias)) { throw new Error('Set DOCS_SITE_ORIGIN: this branch has no valid Workers preview alias.'); diff --git a/docs/.vitepress/theme/components/home/FeatureToolbar.vue b/docs/.vitepress/theme/components/home/FeatureToolbar.vue index 3316e456d4..b71eaa6a66 100644 --- a/docs/.vitepress/theme/components/home/FeatureToolbar.vue +++ b/docs/.vitepress/theme/components/home/FeatureToolbar.vue @@ -11,7 +11,7 @@ const features = [ const activeSection = ref('feature-dev-build'); const underlineStyle = ref({ left: '0px', width: '0px' }); -const listItems = ref([]); +const listItems = ref>([]); let scrollTimeout: number | null = null; const scrollToSection = (e: Event, id: string) => { @@ -86,58 +86,31 @@ const updateUnderlinePosition = () => { } }; -const determineActiveSection = () => { - // Get all sections and their positions - const sections = features - .map((feature) => { - const element = document.getElementById(feature.id); - if (!element) { - return null; - } - - const rect = element.getBoundingClientRect(); - return { - id: feature.id, - top: rect.top, - bottom: rect.bottom, - height: rect.height, - }; - }) - .filter(Boolean); +function determineActiveSection(): void { + const sections = features.flatMap(({ id }) => { + const section = document.getElementById(id); + return section ? [section] : []; + }); - // Find the section that's most visible near the top of the viewport - // We consider a section "active" if it's within 200px of the top const threshold = 200; - let activeId = activeSection.value; - - for (const section of sections) { - if (!section) { - continue; - } - - // If section top is near or above threshold and bottom is below threshold - if (section.top <= threshold && section.bottom > threshold) { - activeId = section.id; - break; - } - } + const active = sections.find((section) => { + const { top, bottom } = section.getBoundingClientRect(); + return top <= threshold && bottom > threshold; + }); + let activeId = active?.id ?? activeSection.value; - // If no section found above, check if we're at the very bottom - if (activeId === activeSection.value) { - const lastSection = sections.at(-1); - if ( - lastSection && - window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 100 - ) { - activeId = lastSection.id; - } + if ( + activeId === activeSection.value && + window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 100 + ) { + activeId = sections.at(-1)?.id ?? activeId; } if (activeId !== activeSection.value) { activeSection.value = activeId; updateUnderlinePosition(); } -}; +} const handleScroll = () => { if (scrollTimeout) { diff --git a/docs/.vitepress/theme/components/home/InstallCommand.vue b/docs/.vitepress/theme/components/home/InstallCommand.vue index fbdfa00aba..0402f7243d 100644 --- a/docs/.vitepress/theme/components/home/InstallCommand.vue +++ b/docs/.vitepress/theme/components/home/InstallCommand.vue @@ -8,7 +8,7 @@ type CommandCard = { command: string; }; -const commandCards: CommandCard[] = [ +const commandCards: Array = [ { id: 'unix', label: 'macOS / Linux', @@ -39,7 +39,9 @@ const copyCommand = async (id: string, command: string) => { try { await navigator.clipboard.writeText(command); flashCopied(id); - } catch {} + } catch { + // The clipboard can be unavailable when the browser denies access. + } }; onBeforeUnmount(() => { diff --git a/docs/.vitepress/theme/components/home/TerminalTranscript.vue b/docs/.vitepress/theme/components/home/TerminalTranscript.vue index 261803339a..397dc21f3b 100644 --- a/docs/.vitepress/theme/components/home/TerminalTranscript.vue +++ b/docs/.vitepress/theme/components/home/TerminalTranscript.vue @@ -20,7 +20,7 @@ const emit = defineEmits<{ const visibleLineCount = ref(0); const renderedPrompt = ref(''); const promptFinished = ref(false); -let timers: number[] = []; +let timers: Array = []; const promptText = computed(() => `${props.transcript.prompt ?? '$'} ${props.transcript.command}`); diff --git a/docs/.vitepress/theme/data/feature-run-transcripts.ts b/docs/.vitepress/theme/data/feature-run-transcripts.ts index 40a8de7b8a..748a77d772 100644 --- a/docs/.vitepress/theme/data/feature-run-transcripts.ts +++ b/docs/.vitepress/theme/data/feature-run-transcripts.ts @@ -1,6 +1,6 @@ import type { TerminalTranscript } from './terminal-transcripts'; -export const featureRunTranscripts: TerminalTranscript[] = [ +export const featureRunTranscripts: Array = [ { id: 'cold', label: 'Cold Cache', diff --git a/docs/.vitepress/theme/data/fetch-trusted-stack-stats.ts b/docs/.vitepress/theme/data/fetch-trusted-stack-stats.ts index 0670f06127..ba7d1437a6 100644 --- a/docs/.vitepress/theme/data/fetch-trusted-stack-stats.ts +++ b/docs/.vitepress/theme/data/fetch-trusted-stack-stats.ts @@ -1,6 +1,5 @@ import { writeFile } from 'node:fs/promises'; -import { dirname, join } from 'node:path'; -import { fileURLToPath } from 'node:url'; +import { join } from 'node:path'; /** * Fetches last-week npm download counts and GitHub star counts, then writes @@ -16,7 +15,7 @@ import type { TrustedStackStatsFile, } from './trusted-stack-stats.types'; -const currentDir = dirname(fileURLToPath(import.meta.url)); +const currentDir = import.meta.dirname; const OUT = join(currentDir, 'trusted-stack-stats.json'); interface ProjectSource { @@ -25,7 +24,7 @@ interface ProjectSource { readonly githubRepo: string; } -const PROJECTS: readonly ProjectSource[] = [ +const PROJECTS: ReadonlyArray = [ { id: 'vite', npmPackage: 'vite', githubRepo: 'vitejs/vite' }, { id: 'vitest', npmPackage: 'vitest', githubRepo: 'vitest-dev/vitest' }, /** OXC row uses `oxlint` npm weekly downloads as a concrete proxy for the Oxc toolchain. */ @@ -80,15 +79,15 @@ function parseGithubRepoJson(data: unknown, repo: string): number { async function fetchGithubStargazers(repo: string): Promise { const url = `https://api.github.com/repos/${repo}`; - const headers: Record = { + const headers = new Headers({ Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': 'voidzero-dev/vite-plus (docs/.vitepress/theme/data/fetch-trusted-stack-stats.ts)', - }; + }); const token = process.env.GITHUB_TOKEN; if (token !== undefined && token !== '') { - headers.Authorization = `Bearer ${token}`; + headers.set('Authorization', `Bearer ${token}`); } const res = await fetch(url, { headers }); if (!res.ok) { @@ -99,7 +98,7 @@ async function fetchGithubStargazers(repo: string): Promise { } async function main(): Promise { - const projects: TrustedStackStatProject[] = []; + const projects: Array = []; for (const p of PROJECTS) { const [npmWeeklyDownloads, stars] = await Promise.all([ npmLastWeekDownloads(p.npmPackage), @@ -121,7 +120,7 @@ async function main(): Promise { console.error(`Wrote ${OUT} at ${new Date().toISOString()}`); } -void main().catch((err: unknown) => { - console.error(err); +await main().catch((error: unknown) => { + console.error(error); process.exitCode = 1; }); diff --git a/docs/.vitepress/theme/data/terminal-transcripts.ts b/docs/.vitepress/theme/data/terminal-transcripts.ts index 1834aa1e74..ce62092791 100644 --- a/docs/.vitepress/theme/data/terminal-transcripts.ts +++ b/docs/.vitepress/theme/data/terminal-transcripts.ts @@ -7,7 +7,7 @@ export interface TerminalSegment { } export interface TerminalLine { - segments: TerminalSegment[]; + segments: Array; tone?: TerminalTone; } @@ -19,10 +19,10 @@ export interface TerminalTranscript { prompt?: string; lineDelay?: number; completionDelay?: number; - lines: TerminalLine[]; + lines: Array; } -export const terminalTranscripts: TerminalTranscript[] = [ +export const terminalTranscripts: Array = [ { id: 'create', label: 'create', diff --git a/docs/.vitepress/theme/data/trusted-stack-stats.ts b/docs/.vitepress/theme/data/trusted-stack-stats.ts index ac6547b2ad..b0e4bf16cd 100644 --- a/docs/.vitepress/theme/data/trusted-stack-stats.ts +++ b/docs/.vitepress/theme/data/trusted-stack-stats.ts @@ -11,7 +11,17 @@ export type { TrustedStackStatsFile, } from './trusted-stack-stats.types'; -export const trustedStackStats = raw as TrustedStackStatsFile; +function isTrustedStackProject( + project: (typeof raw.projects)[number], +): project is TrustedStackStatProject { + return project.id === 'vite' || project.id === 'vitest' || project.id === 'oxc'; +} + +const { projects } = raw; +if (!projects.every(isTrustedStackProject)) { + throw new Error('Unexpected project ID in trusted-stack-stats.json'); +} +export const trustedStackStats: TrustedStackStatsFile = { projects }; export function trustedStackById(id: TrustedStackProjectId): TrustedStackStatProject { const project = trustedStackStats.projects.find((p) => p.id === id); diff --git a/docs/.vitepress/theme/data/trusted-stack-stats.types.ts b/docs/.vitepress/theme/data/trusted-stack-stats.types.ts index eeec7b794c..6081c50c47 100644 --- a/docs/.vitepress/theme/data/trusted-stack-stats.types.ts +++ b/docs/.vitepress/theme/data/trusted-stack-stats.types.ts @@ -11,5 +11,5 @@ export interface TrustedStackStatProject { } export interface TrustedStackStatsFile { - projects: TrustedStackStatProject[]; + projects: Array; } diff --git a/docs/_data/team.ts b/docs/_data/team.ts index cc557b334e..39dc15e245 100644 --- a/docs/_data/team.ts +++ b/docs/_data/team.ts @@ -1,6 +1,6 @@ import type { DefaultTheme } from 'vitepress'; -export const core: DefaultTheme.TeamMember[] = [ +export const core: Array = [ { avatar: 'https://github.com/fengmk2.png', name: 'MK', @@ -136,4 +136,4 @@ export const core: DefaultTheme.TeamMember[] = [ }, ]; -export const emeriti: DefaultTheme.TeamMember[] = []; +export const emeriti: Array = []; diff --git a/ecosystem-ci/clone.ts b/ecosystem-ci/clone.ts index a1c0e90174..e95ff91d7c 100644 --- a/ecosystem-ci/clone.ts +++ b/ecosystem-ci/clone.ts @@ -2,13 +2,14 @@ import { execSync } from 'node:child_process'; import { existsSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; +import { hasOwnKey } from '../packages/cli/src/utils/object.ts'; import { ecosystemCiDir } from './paths.ts'; import repos from './repo.json' with { type: 'json' }; const cwd = import.meta.dirname; function exec(cmd: string, execCwd: string = cwd): string { - return execSync(cmd, { cwd: execCwd, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim(); + return execSync(cmd, { cwd: execCwd, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim(); } function getRemoteUrl(dir: string): string | null { @@ -52,12 +53,12 @@ function checkoutHash(dir: string, hash: string): void { } function cloneProject(repoName: string): void { - const repo = repos[repoName as keyof typeof repos]; - if (!repo) { + if (!hasOwnKey(repos, repoName)) { console.error(`Project ${repoName} is not defined in repo.json`); process.exit(1); } + const repo = repos[repoName]; const targetDir = join(ecosystemCiDir, repoName); if (existsSync(targetDir)) { diff --git a/ecosystem-ci/npmx.ts b/ecosystem-ci/npmx.ts index abe903229a..88751ecec0 100644 --- a/ecosystem-ci/npmx.ts +++ b/ecosystem-ci/npmx.ts @@ -5,7 +5,7 @@ export function patchNpmxVitestConfig(config: string): string { if ([...config.matchAll(nuxtProject)].length !== 1) { throw new Error('npmx.dev patch: expected the pinned Nuxt test project configuration'); } - return config.replace( + return config.replaceAll( nuxtProject, `defineVitestProject({ plugins: [liveDollarFetch(), { diff --git a/ecosystem-ci/patch-project.ts b/ecosystem-ci/patch-project.ts index 35b619caf4..bea26ce91d 100644 --- a/ecosystem-ci/patch-project.ts +++ b/ecosystem-ci/patch-project.ts @@ -7,23 +7,23 @@ import { VITEST_VERSION, VITE_PLUS_CORE_ALIAS_PREFIX, } from '../packages/cli/src/utils/constants.ts'; +import { isObjectValue, parseJsonObject } from '../packages/cli/src/utils/json-value.ts'; +import { hasOwnKey } from '../packages/cli/src/utils/object.ts'; import vitePlusCorePkg from '../packages/core/package.json' with { type: 'json' }; import { patchNpmxVitestConfig } from './npmx.ts'; import { ecosystemCiDir, tgzDir, vitePlusCoreTgzVersion, vitePlusTgzVersion } from './paths.ts'; import repos from './repo.json' with { type: 'json' }; import { prepareWebdriverioProject } from './webdriverio.ts'; -const projects = Object.keys(repos); - const project = process.argv[2]; -if (!projects.includes(project)) { +if (!hasOwnKey(repos, project)) { console.error(`Project ${project} is not defined in repo.json`); process.exit(1); } +const repoConfig = repos[project]; const repoRoot = join(ecosystemCiDir, project); -const repoConfig = repos[project as keyof typeof repos]; // Migrate and install always run at the clone root: `vp migrate` rejects // workspace member targets (#2229). The workflow's `directory` matrix value // only steers where the later project commands run (e.g. dify's `vp run ...` @@ -57,23 +57,30 @@ const registryServer = spawn( detached: true, }, ); -const registryInfo = await new Promise<{ registry: string; env: Record }>( - (resolve, reject) => { - let buffered = ''; - registryServer.stdout.on('data', (chunk: Buffer) => { - buffered += chunk.toString(); - const newline = buffered.indexOf('\n'); - if (newline !== -1) { - resolve(JSON.parse(buffered.slice(0, newline))); - } - }); - registryServer.on('error', reject); - registryServer.on('exit', (code) => reject(new Error(`registry exited early (${code})`))); - }, -); -console.log( - `Serving local Vite+ packages at ${registryInfo.registry} (vite-plus@${vitePlusVersion})`, -); +const handshake = await new Promise((resolve, reject) => { + let buffered = ''; + registryServer.stdout.on('data', (chunk: Buffer) => { + buffered += chunk.toString(); + const newline = buffered.indexOf('\n'); + if (newline !== -1) { + resolve(buffered.slice(0, newline)); + } + }); + registryServer.on('error', reject); + registryServer.on('exit', (code) => reject(new Error(`registry exited early (${code})`))); +}); +const { registry, env } = parseJsonObject(handshake, 'registry handshake'); +if (typeof registry !== 'string' || !isObjectValue(env)) { + throw new Error('Invalid registry handshake'); +} +const registryEnv: Record = {}; +for (const [key, value] of Object.entries(env)) { + if (typeof value !== 'string') { + throw new Error(`Invalid registry environment variable ${key}`); + } + registryEnv[key] = value; +} +console.log(`Serving local Vite+ packages at ${registry} (vite-plus@${vitePlusVersion})`); // The server prints nothing after the handshake; release the pipe and the // process handle so they don't keep this script's event loop alive after the // installs below finish. @@ -82,7 +89,7 @@ registryServer.unref(); if (process.env.GITHUB_ENV) { // Keep the registry reachable for the workflow's later steps. - const lines = Object.entries(registryInfo.env) + const lines = Object.entries(registryEnv) .map(([key, value]) => `${key}=${value}\n`) .join(''); await appendFile(process.env.GITHUB_ENV, lines); @@ -96,17 +103,20 @@ if (project === 'npmx.dev') { // The pinned workspace enables strict peer checks. Supply devframe's optional // cac peer explicitly so migration satisfies its ^7.0.0 requirement. const packagePath = join(repoRoot, 'package.json'); - const pkg = JSON.parse(await readFile(packagePath, 'utf-8')); + const pkg = parseJsonObject(await readFile(packagePath, 'utf8'), packagePath); + if (!isObjectValue(pkg.devDependencies)) { + throw new Error('Expected npmx.dev to have devDependencies'); + } pkg.devDependencies.cac = '7.0.0'; - await writeFile(packagePath, `${JSON.stringify(pkg, null, 2)}\n`, 'utf-8'); + await writeFile(packagePath, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8'); } if (project === 'rollipop') { - const oxfmtrc = await readFile(join(repoRoot, '.oxfmtrc.json'), 'utf-8'); + const oxfmtrc = await readFile(join(repoRoot, '.oxfmtrc.json'), 'utf8'); await writeFile( join(repoRoot, '.oxfmtrc.json'), oxfmtrc.replace(' ["ts-equals-import"],\n', ''), - 'utf-8', + 'utf8', ); } @@ -115,17 +125,17 @@ if (project === 'vinext') { // (e.g. oxc 0.129.0 published <24h ago). Disable it for the ecosystem run so // upgrade-deps PRs can install transitive deps that were just published. const workspacePath = join(repoRoot, 'pnpm-workspace.yaml'); - const workspace = await readFile(workspacePath, 'utf-8'); + const workspace = await readFile(workspacePath, 'utf8'); const patched = workspace.replace(/^minimumReleaseAge:.*$/m, 'minimumReleaseAge: 0'); if (patched === workspace) { throw new Error(`vinext patch: \`minimumReleaseAge:\` not found in ${workspacePath}`); } - await writeFile(workspacePath, patched, 'utf-8'); + await writeFile(workspacePath, patched, 'utf8'); // vinext uses standalone `void` expressions to mark intentional reads. // tsrs5 removes `void` during autofix, then no-unused-expressions flags the reads. const viteConfigPath = join(repoRoot, 'vite.config.ts'); - const viteConfig = await readFile(viteConfigPath, 'utf-8'); + const viteConfig = await readFile(viteConfigPath, 'utf8'); const lintRule = ' "typescript/consistent-type-definitions": ["error", "type"],'; if (!viteConfig.includes(lintRule)) { throw new Error(`vinext patch: expected TypeScript lint rule in ${viteConfigPath}`); @@ -136,7 +146,7 @@ if (project === 'vinext') { lintRule, `${lintRule}\n "typescript/no-meaningless-void-operator": "off",`, ), - 'utf-8', + 'utf8', ); // oxlint 1.77 applies `.gitignore` to explicitly passed paths too @@ -145,12 +155,12 @@ if (project === 'vinext') { // `.gitignore` covers the link name, so oxlint now reports "No files found to // lint". Drop the ignore entry so the rule test keeps linting its fixtures. const gitignorePath = join(repoRoot, '.gitignore'); - const gitignore = await readFile(gitignorePath, 'utf-8'); + const gitignore = await readFile(gitignorePath, 'utf8'); const patchedGitignore = gitignore.replace(/^__lint_rule_fixtures__-\*$\n?/m, ''); if (patchedGitignore === gitignore) { throw new Error(`vinext patch: \`__lint_rule_fixtures__-*\` not found in ${gitignorePath}`); } - await writeFile(gitignorePath, patchedGitignore, 'utf-8'); + await writeFile(gitignorePath, patchedGitignore, 'utf8'); } if (project === 'dify') { @@ -160,7 +170,7 @@ if (project === 'dify') { // defining `minimumReleaseAge` there activates a resolution-policy path that // vp's bundled pnpm cannot handle. const workspacePath = join(repoRoot, 'pnpm-workspace.yaml'); - const workspace = await readFile(workspacePath, 'utf-8'); + const workspace = await readFile(workspacePath, 'utf8'); if (!/^minimumReleaseAge:/m.test(workspace)) { throw new Error(`dify patch: \`minimumReleaseAge:\` not found in ${workspacePath}`); } @@ -170,7 +180,7 @@ if (project === 'dify') { const patched = workspace .replace(/^minimumReleaseAge:.*$/m, 'minimumReleaseAge: 0') .replace(/^resolutionMode:\s*time-based[ \t]*$/m, 'resolutionMode: highest'); - await writeFile(workspacePath, patched, 'utf-8'); + await writeFile(workspacePath, patched, 'utf8'); } if (project === 'nuxt-devtools') { @@ -183,7 +193,7 @@ if (project === 'nuxt-devtools') { // Align that source with vite-plus-core so pnpm resolves the core package, // kit, and optional integration peers as one compatible release family. const workspacePath = join(repoRoot, 'pnpm-workspace.yaml'); - const workspace = await readFile(workspacePath, 'utf-8'); + const workspace = await readFile(workspacePath, 'utf8'); const trustPolicy = 'trustPolicy: no-downgrade'; if (!workspace.includes(trustPolicy)) { throw new Error(`nuxt-devtools patch: \`${trustPolicy}\` not found in ${workspacePath}`); @@ -201,7 +211,7 @@ if (project === 'nuxt-devtools') { viteDevtoolsVersionSource, (_line, prefix: string) => `${prefix}${viteDevtoolsVersion}`, ); - await writeFile(workspacePath, patched, 'utf-8'); + await writeFile(workspacePath, patched, 'utf8'); } // Projects that already use vite-plus need VP_FORCE_MIGRATE=1 so @@ -240,7 +250,7 @@ const vitestOverrides = { const workspaceYamlPath = join(repoRoot, 'pnpm-workspace.yaml'); const timeBasedResolution = existsSync(workspaceYamlPath) && - /^resolutionMode:\s*time-based/m.test(readFileSync(workspaceYamlPath, 'utf-8')); + /^resolutionMode:\s*time-based/m.test(readFileSync(workspaceYamlPath, 'utf8')); const releaseAgeEnv = timeBasedResolution ? {} : { @@ -250,8 +260,7 @@ const releaseAgeEnv = timeBasedResolution const migrateEnv: NodeJS.ProcessEnv = { ...process.env, - ...registryInfo.env, - ...(forceFreshMigration ? { VP_FORCE_MIGRATE: '1' } : {}), + ...registryEnv, VP_OVERRIDE_PACKAGES: JSON.stringify({ vite: `${VITE_PLUS_CORE_ALIAS_PREFIX}${vitePlusCoreVersion}`, ...vitestOverrides, @@ -261,6 +270,9 @@ const migrateEnv: NodeJS.ProcessEnv = { VP_VERSION: vitePlusVersion, ...releaseAgeEnv, }; +if (forceFreshMigration) { + migrateEnv.VP_FORCE_MIGRATE = '1'; +} execSync(`${cli} migrate --no-agent --no-interactive`, { cwd: repoRoot, @@ -273,7 +285,7 @@ if (project === 'vue-mini') { // Remove when the pinned setup declares both Vitest 5 type parameters. // https://vitest.dev/guide/migration/#assertion-types-expose-return-and-received-types const setupPath = join(repoRoot, 'vitest.setup.ts'); - const setup = await readFile(setupPath, 'utf-8'); + const setup = await readFile(setupPath, 'utf8'); const legacyAssertion = 'interface Assertion extends CustomMatchers {}'; if (setup.split(legacyAssertion).length !== 2) { throw new Error('vue-mini patch: expected the pinned custom matcher declaration'); @@ -281,7 +293,7 @@ if (project === 'vue-mini') { await writeFile( setupPath, setup.replace(legacyAssertion, 'interface Assertion extends CustomMatchers {}'), - 'utf-8', + 'utf8', ); } @@ -292,7 +304,7 @@ if (project === 'dify') { // Remove when the pinned project provides a v5-compatible matcher augmentation. // https://vitest.dev/guide/migration/#assertion-types-expose-return-and-received-types const setupPath = join(repoRoot, 'web', 'vitest.setup.ts'); - const setup = await readFile(setupPath, 'utf-8'); + const setup = await readFile(setupPath, 'utf8'); const registration = "if (typeof expect.extend === 'function') {"; if ( setup.split(registration).length !== 2 || @@ -312,7 +324,7 @@ declare module 'vite-plus/test' { ${registration}`, ), - 'utf-8', + 'utf8', ); } @@ -320,8 +332,8 @@ if (project === 'npmx.dev') { // Nuxt loads app modules before per-file mocks; use request interception. // https://vitest.dev/config/browser/importmapmocks const viteConfigPath = join(repoRoot, 'vite.config.ts'); - const viteConfig = await readFile(viteConfigPath, 'utf-8'); - await writeFile(viteConfigPath, patchNpmxVitestConfig(viteConfig), 'utf-8'); + const viteConfig = await readFile(viteConfigPath, 'utf8'); + await writeFile(viteConfigPath, patchNpmxVitestConfig(viteConfig), 'utf8'); } if (project === 'bun-vite-template') { @@ -329,16 +341,17 @@ if (project === 'bun-vite-template') { // Vitest runtime, but allowJs: false excludes that file from type checking. // Apply the migration report's manual type-entry repair for this fixture. const tsconfigPath = join(repoRoot, 'tsconfig.json'); - const tsconfig = JSON.parse(await readFile(tsconfigPath, 'utf-8')); - const types = tsconfig.compilerOptions?.types; + const tsconfig = parseJsonObject(await readFile(tsconfigPath, 'utf8'), tsconfigPath); + const options = tsconfig.compilerOptions; if ( - !Array.isArray(types) || - !types.includes('vitest/globals') || - !types.includes('@testing-library/jest-dom') + !isObjectValue(options) || + !Array.isArray(options.types) || + !options.types.includes('vitest/globals') || + !options.types.includes('@testing-library/jest-dom') ) { throw new Error('bun-vite-template patch: expected the pinned Jest DOM type configuration'); } - tsconfig.compilerOptions.types = types.map((type) => + options.types = options.types.map((type) => type === '@testing-library/jest-dom' ? '@testing-library/jest-dom/vitest' : type, ); await writeFile(tsconfigPath, `${JSON.stringify(tsconfig, null, 2)}\n`); @@ -350,5 +363,5 @@ if (project === 'bun-vite-template') { execSync(`${cli} install --no-frozen-lockfile`, { cwd: repoRoot, stdio: 'inherit', - env: { ...process.env, ...registryInfo.env, ...releaseAgeEnv }, + env: { ...process.env, ...registryEnv, ...releaseAgeEnv }, }); diff --git a/ecosystem-ci/paths.ts b/ecosystem-ci/paths.ts index 6d4c865cf6..1bab168395 100644 --- a/ecosystem-ci/paths.ts +++ b/ecosystem-ci/paths.ts @@ -1,9 +1,8 @@ import { readdirSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { dirname, join } from 'node:path'; -import { fileURLToPath } from 'node:url'; +import { join } from 'node:path'; -const projectDir = dirname(fileURLToPath(import.meta.url)); +const projectDir = import.meta.dirname; // Use RUNNER_TEMP in GitHub Actions, otherwise use system temp directory const tempBase = process.env.RUNNER_TEMP ?? tmpdir(); diff --git a/ecosystem-ci/verify-install.ts b/ecosystem-ci/verify-install.ts index 51a22924f5..3b21c2f1be 100644 --- a/ecosystem-ci/verify-install.ts +++ b/ecosystem-ci/verify-install.ts @@ -1,7 +1,8 @@ -import { readFileSync } from 'node:fs'; import { createRequire } from 'node:module'; import path from 'node:path'; +import { isObjectValue } from '../packages/cli/src/utils/json-value.ts'; +import { readJsonObject } from '../scripts/json.ts'; import { vitePlusTgzVersion } from './paths.ts'; const require = createRequire(`${process.cwd()}/`); @@ -14,24 +15,20 @@ const expectedVersion = vitePlusTgzVersion(); try { const pkgPath = require.resolve('vite-plus/package.json'); - const pkg = require(pkgPath) as { - version: string; - name: string; - dependencies?: Record; - }; + const pkg = readJsonObject(pkgPath); if (pkg.version !== expectedVersion) { - console.error(`x vite-plus: expected version ${expectedVersion}, got ${pkg.version}`); + console.error( + `x vite-plus: expected version ${expectedVersion}, got ${JSON.stringify(pkg.version)}`, + ); process.exit(1); } - const projectPkg = JSON.parse( - readFileSync(path.join(process.cwd(), 'package.json'), 'utf-8'), - ) as { - dependencies?: Record; - devDependencies?: Record; - }; + const projectPkg = readJsonObject(path.join(process.cwd(), 'package.json')); + const prod = projectPkg.dependencies; + const dev = projectPkg.devDependencies; const vitePlusSpec = - projectPkg.dependencies?.['vite-plus'] ?? projectPkg.devDependencies?.['vite-plus']; + (isObjectValue(prod) ? prod['vite-plus'] : undefined) ?? + (isObjectValue(dev) ? dev['vite-plus'] : undefined); // The migration must pin the local version as a plain registry spec // (resolved through the local registry), exactly like a real migration, @@ -39,9 +36,12 @@ try { // pinned version through the catalog instead of an inline version; the // installed `pkg.version` assertion above already proves which version the // catalog resolved to. - if (vitePlusSpec !== expectedVersion && !vitePlusSpec?.startsWith('catalog:')) { + if ( + vitePlusSpec !== expectedVersion && + !(typeof vitePlusSpec === 'string' && vitePlusSpec.startsWith('catalog:')) + ) { console.error( - `x vite-plus: expected exact registry spec ${expectedVersion} (or a catalog reference), got ${vitePlusSpec ?? ''}`, + `x vite-plus: expected exact registry spec ${expectedVersion} (or a catalog reference), got ${typeof vitePlusSpec === 'string' ? vitePlusSpec : ''}`, ); console.error(` resolved to ${pkgPath}`); process.exit(1); @@ -49,14 +49,17 @@ try { const vitePlusRequire = createRequire(pkgPath); const oxlintPkgPath = vitePlusRequire.resolve('oxlint/package.json'); - const oxlintPkg = vitePlusRequire('oxlint/package.json') as { version: string }; - const expectedOxlint = pkg.dependencies?.oxlint?.replace(/^[=^~]/, ''); + const oxlintPkg = readJsonObject(oxlintPkgPath); + const expectedOxlint = + isObjectValue(pkg.dependencies) && + typeof pkg.dependencies.oxlint === 'string' && + pkg.dependencies.oxlint.replace(/^[=^~]/, ''); if (!expectedOxlint) { console.error('x vite-plus: package.json missing oxlint dependency'); process.exit(1); } if (oxlintPkg.version !== expectedOxlint) { - console.error(`x oxlint: expected ${expectedOxlint}, got ${oxlintPkg.version}`); + console.error(`x oxlint: expected ${expectedOxlint}, got ${JSON.stringify(oxlintPkg.version)}`); console.error(` resolved to ${oxlintPkgPath}`); process.exit(1); } diff --git a/ecosystem-ci/verify-videojs-v10.ts b/ecosystem-ci/verify-videojs-v10.ts index a96866ce26..9a49186045 100644 --- a/ecosystem-ci/verify-videojs-v10.ts +++ b/ecosystem-ci/verify-videojs-v10.ts @@ -2,11 +2,11 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { createRequire } from 'node:module'; +import { isObjectValue } from '../packages/cli/src/utils/json-value.ts'; +import { readJsonObject } from '../scripts/json.ts'; + const require = createRequire(`${process.cwd()}/`); -const pkg = JSON.parse(readFileSync('package.json', 'utf-8')) as Record< - string, - Record | undefined ->; +const pkg = readJsonObject('package.json'); // A fresh pnpm install must load the migrated plugin without direct Oxlint dependencies. for (const name of ['@oxlint/plugins', 'oxlint']) { @@ -16,7 +16,12 @@ for (const name of ['@oxlint/plugins', 'oxlint']) { 'peerDependencies', 'optionalDependencies', ]) { - assert.equal(pkg[field]?.[name], undefined, `${field} still contains ${name}`); + const dependencies = pkg[field]; + assert.equal( + isObjectValue(dependencies) ? dependencies[name] : undefined, + undefined, + `${field} still contains ${name}`, + ); } assert.throws(() => require.resolve(`${name}/package.json`), { code: 'MODULE_NOT_FOUND' }); } @@ -27,7 +32,7 @@ for (const [file, specifier] of [ ['rules/padding-line-between-statements.ts', 'vite-plus/lint/plugins'], ['rules/tests/padding-line-between-statements.test.ts', 'vite-plus/lint/plugins-dev'], ]) { - const source = readFileSync(`${pluginDir}/${file}`, 'utf-8'); + const source = readFileSync(`${pluginDir}/${file}`, 'utf8'); assert.ok( source.includes(`from "${specifier}"`) || source.includes(`from '${specifier}'`), `${file} must import from ${specifier}`, diff --git a/ecosystem-ci/webdriverio.ts b/ecosystem-ci/webdriverio.ts index 41cc0c9cc0..1143b37512 100644 --- a/ecosystem-ci/webdriverio.ts +++ b/ecosystem-ci/webdriverio.ts @@ -2,6 +2,8 @@ import { execSync } from 'node:child_process'; import { readFile, rename, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; +import { parseJsonObject } from '../packages/cli/src/utils/json-value.ts'; + async function replaceOnce(file: string, original: string, replacement: string): Promise { const source = await readFile(file, 'utf8'); if (source.split(original).length !== 2) { @@ -27,8 +29,11 @@ export async function prepareWebdriverioProject( // token is interpreted as an ast-grep variable when merging the config. // Remove this workaround when formatter migration drops unsupported options. const prettierPath = join(root, '.prettierrc.json'); - const prettier = JSON.parse(await readFile(prettierPath, 'utf8')); - if (!prettier.attributeGroups?.includes('$DEFAULT')) { + const prettier = parseJsonObject(await readFile(prettierPath, 'utf8'), prettierPath); + if ( + !Array.isArray(prettier.attributeGroups) || + !prettier.attributeGroups.includes('$DEFAULT') + ) { throw new Error('10ten-ja-reader patch: expected the pinned attributeGroups option'); } delete prettier.attributeGroups; diff --git a/package.json b/package.json index fd4ce34eb3..9fd4cd43aa 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "prepare": "vp config" }, "devDependencies": { + "@cloudflare/oxlint-config": "catalog:", "@e18e/eslint-plugin": "catalog:", "@emnapi/core": "catalog:", "@emnapi/runtime": "catalog:", diff --git a/packages/cli/build.ts b/packages/cli/build.ts index fb0f8e6425..935a0bfe99 100644 --- a/packages/cli/build.ts +++ b/packages/cli/build.ts @@ -23,17 +23,63 @@ import { existsSync, readdirSync, statSync } from 'node:fs'; import { copyFile, cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; import { createRequire } from 'node:module'; import { dirname, join, relative } from 'node:path'; -import { fileURLToPath } from 'node:url'; import { parseArgs } from 'node:util'; import { createBuildCommand, NapiCli } from '@napi-rs/cli'; import { format } from 'oxfmt'; +import { z } from 'zod'; import { generateLicenseFile } from '../../scripts/generate-license.js'; import corePkg from '../core/package.json' with { type: 'json' }; import { VITEST_VERSION } from './src/utils/constants.ts'; +import { errorMessage } from './src/utils/error.ts'; +import type { JsonObject, JsonValue } from './src/utils/json-value.ts'; +import { isObjectValue, parseJsonObject } from './src/utils/json-value.ts'; + +const toolchainConfigSchema = z.object({ + schemaVersion: z.number(), + versionExportIds: z.array(z.string()), + nodes: z.array( + z.object({ + id: z.string(), + name: z.string(), + kind: z.enum(['package', 'tool', 'engine']), + delivery: z.array(z.enum(['dependency', 'bundled', 'compiled'])), + aliases: z.array(z.string()), + versionSource: z.discriminatedUnion('type', [ + z.object({ type: z.literal('cli-package') }), + z.object({ type: z.literal('core-package') }), + z.object({ type: z.literal('core-bundled'), key: z.string() }), + z.object({ type: z.literal('npm-dependency'), package: z.string() }), + z.object({ + type: z.literal('cargo'), + package: z.string(), + revision: z.boolean().optional(), + builtAt: z.boolean().optional(), + }), + z.object({ type: z.literal('vendored'), upstream: z.string(), packageJson: z.string() }), + ]), + }), + ), + edges: z.array( + z.object({ + from: z.string(), + to: z.string(), + relationship: z.enum(['depends-on', 'bundles', 'uses', 'compiles']), + }), + ), +}); +type ToolchainConfig = z.infer; +type ToolchainConfigNode = ToolchainConfig['nodes'][number]; -const projectDir = dirname(fileURLToPath(import.meta.url)); +const cargoMetadataSchema = z.object({ + packages: z.array( + z.object({ name: z.string(), version: z.string(), source: z.string().nullable() }), + ), +}); +type CargoMetadata = z.infer; + +const projectDir = import.meta.dirname; const TEST_PACKAGE_NAME = 'vitest'; const CORE_PACKAGE_NAME = '@voidzero-dev/vite-plus-core'; const CORE_IMPORT_SPECIFIER = 'vite'; @@ -354,17 +400,20 @@ async function syncTestPackageExports() { const testDistDir = join(projectDir, 'dist/test'); // Read test package.json - const testPkg = JSON.parse(await readFile(testPkgPath, 'utf-8')); + const testPkg = parseJsonObject(await readFile(testPkgPath, 'utf8')); if (testPkg.version !== VITEST_VERSION) { - throw new Error(`Expected vitest@${VITEST_VERSION}, found ${testPkg.version}`); + throw new Error(`Expected vitest@${VITEST_VERSION}, found ${JSON.stringify(testPkg.version)}`); + } + const testExports = testPkg.exports; + if (!isObjectValue(testExports)) { + throw new Error(`Expected exports in ${testPkgPath}`); } - const testExports = testPkg.exports as Record; // Clean up previous build await rm(testDistDir, { recursive: true, force: true }); await mkdir(testDistDir, { recursive: true }); - const generatedExports: Record = {}; + const generatedExports: JsonObject = {}; for (const [exportPath, exportValue] of Object.entries(testExports)) { // Skip package.json export and wildcard exports @@ -415,13 +464,13 @@ async function syncTestPackageExports() { let providerPkgPath: string; try { providerPkgPath = require.resolve(`${pkg}/package.json`, { paths: [projectDir] }); - } catch (err) { - console.warn(` Skipping ${pkg} — not installed: ${(err as Error).message}`); + } catch (error) { + console.warn(` Skipping ${pkg} — not installed: ${errorMessage(error)}`); continue; } - const providerPkg = JSON.parse(await readFile(providerPkgPath, 'utf-8')); + const providerPkg = parseJsonObject(await readFile(providerPkgPath, 'utf8')); const providerPkgRoot = dirname(providerPkgPath); - const providerExports = (providerPkg.exports ?? {}) as Record; + const providerExports = isObjectValue(providerPkg.exports) ? providerPkg.exports : {}; for (const [providerExportPath, providerExportValue] of Object.entries(providerExports)) { if (providerExportPath === './package.json' || providerExportPath.includes('*')) { @@ -502,9 +551,11 @@ async function syncTestPackageExports() { const [scope, name, ...subpath] = importSpecifier.split('/'); const packageName = `${scope}/${name}`; const packagePath = require.resolve(`${packageName}/package.json`, { paths: [projectDir] }); - const packageJson = JSON.parse(await readFile(packagePath, 'utf8')); + const packageJson = parseJsonObject(await readFile(packagePath, 'utf8')); const exportKey = subpath.length ? `./${subpath.join('/')}` : '.'; - const exportValue = packageJson.exports?.[exportKey]; + const exportValue = isObjectValue(packageJson.exports) + ? packageJson.exports[exportKey] + : undefined; if (!exportValue) { throw new Error(`Missing public export ${importSpecifier} for ./test/plugins/${pluginName}`); } @@ -548,14 +599,14 @@ async function createBareBrowserShims( let browserPkgPath: string; try { browserPkgPath = require.resolve('@vitest/browser/package.json', { paths: [projectDir] }); - } catch (err) { + } catch (error) { console.warn( - ` Skipping bare browser shims — @vitest/browser not installed: ${(err as Error).message}`, + ` Skipping bare browser shims — @vitest/browser not installed: ${errorMessage(error)}`, ); return result; } - const browserPkg = JSON.parse(await readFile(browserPkgPath, 'utf-8')); - const browserExports = (browserPkg.exports ?? {}) as Record; + const browserPkg = parseJsonObject(await readFile(browserPkgPath, 'utf8')); + const browserExports = isObjectValue(browserPkg.exports) ? browserPkg.exports : {}; // The base browser package already resolves through vite-plus's own dependency // edge. Forward its declarations instead of copying them: relative helpers @@ -613,61 +664,19 @@ async function createBrowserCompatExport(testDistDir: string): Promise; -} - -interface CargoMetadata { - packages: Array<{ - name: string; - version: string; - source: string | null; - }>; -} - interface ResolvedToolchainNode { id: string; name: string; version?: string; revision?: string; builtAt?: string; - kind: ToolchainKind; - delivery: ToolchainDelivery[]; - aliases: string[]; + kind: ToolchainConfigNode['kind']; + delivery: ToolchainConfigNode['delivery']; + aliases: Array; } async function readPackageVersion(packageJsonPath: string, label: string): Promise { - const pkg = JSON.parse(await readFile(packageJsonPath, 'utf-8')) as { version?: unknown }; + const pkg = parseJsonObject(await readFile(packageJsonPath, 'utf8')); if (typeof pkg.version !== 'string' || pkg.version.length === 0) { throw new Error(`Expected an exact version in ${label}`); } @@ -677,7 +686,7 @@ async function readPackageVersion(packageJsonPath: string, label: string): Promi async function readCargoMetadata(): Promise { const metadataPath = process.env.VP_BUILD_CARGO_METADATA; if (metadataPath) { - return JSON.parse(await readFile(metadataPath, 'utf8')) as CargoMetadata; + return cargoMetadataSchema.parse(JSON.parse(await readFile(metadataPath, 'utf8'))); } const repoDir = join(projectDir, '..', '..'); const stdout = execFileSync('cargo', ['metadata', '--locked', '--format-version', '1'], { @@ -685,7 +694,7 @@ async function readCargoMetadata(): Promise { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, }); - return JSON.parse(stdout) as CargoMetadata; + return cargoMetadataSchema.parse(JSON.parse(stdout)); } function resolveCargoPackage(metadata: CargoMetadata, packageName: string) { @@ -711,7 +720,7 @@ function resolveBuildTime(): string { if (seconds !== undefined && !Number.isSafeInteger(seconds)) { throw new Error(`Invalid SOURCE_DATE_EPOCH: ${JSON.stringify(sourceDateEpoch)}`); } - const date = seconds === undefined ? new Date() : new Date(seconds * 1_000); + const date = seconds === undefined ? new Date() : new Date(seconds * 1000); if (Number.isNaN(date.getTime())) { throw new Error(`Invalid SOURCE_DATE_EPOCH: ${JSON.stringify(sourceDateEpoch)}`); } @@ -820,10 +829,11 @@ async function resolveToolchainNode( } case 'vendored': { const repoRoot = join(projectDir, '..', '..'); - const upstreamVersions = JSON.parse( + const upstreamVersions = parseJsonObject( await readFile(join(repoRoot, 'packages', 'tools', '.upstream-versions.json'), 'utf8'), - ) as Record; - revision = upstreamVersions[source.upstream]?.hash; + ); + const entry = upstreamVersions[source.upstream]; + revision = isObjectValue(entry) && typeof entry.hash === 'string' ? entry.hash : undefined; if (!revision) { throw new Error(`Missing ${source.upstream} in packages/tools/.upstream-versions.json`); } @@ -839,9 +849,9 @@ async function resolveToolchainNode( return { id: node.id, name: node.name, - ...(version ? { version } : {}), - ...(revision ? { revision } : {}), - ...(builtAt ? { builtAt } : {}), + version, + revision, + builtAt, kind: node.kind, delivery: node.delivery, aliases: node.aliases, @@ -854,9 +864,9 @@ async function resolveToolchainNode( async function syncToolchainExports() { console.log('\nSyncing toolchain exports...'); const distDir = join(projectDir, 'dist'); - const config = JSON.parse( - await readFile(join(projectDir, 'toolchain.config.json'), 'utf8'), - ) as ToolchainConfig; + const config = toolchainConfigSchema.parse( + JSON.parse(await readFile(join(projectDir, 'toolchain.config.json'), 'utf8')), + ); validateToolchainConfig(config); const cliVersion = await readPackageVersion(join(projectDir, 'package.json'), 'vite-plus'); @@ -1052,7 +1062,7 @@ async function ensureContextRuntimeShim( if (typeof shimExport !== 'object' || shimExport === null) { return; } - const entry = shimExport as Record; + const entry = shimExport; if (entry.default || entry.import) { return; } @@ -1100,7 +1110,7 @@ async function writeInlinedProviderDts( upstreamDtsPath: string, testDistDir: string, ): Promise { - const upstream = await readFile(upstreamDtsPath, 'utf-8'); + const upstream = await readFile(upstreamDtsPath, 'utf8'); const outDir = dirname(outDtsPath); // Resolve to the file basename appended to the relative dir, never to the // bare directory. `relative('dist/test/x/', 'dist/test/y')` returns `'../y'` @@ -1114,7 +1124,7 @@ async function writeInlinedProviderDts( }; let result = upstream; for (const [bare, sub] of VITEST_TYPE_SPECIFIER_REWRITES) { - const escaped = bare.replaceAll('/', '\\/'); + const escaped = bare.replaceAll('/', String.raw`\/`); const pattern = new RegExp(`(['"])${escaped}\\1`, 'g'); result = result.replaceAll(pattern, `'${relToShim(sub)}'`); } @@ -1128,7 +1138,7 @@ async function writeInlinedProviderDts( */ function resolveUpstreamDtsPath( providerPkgRoot: string, - exportValue: unknown, + exportValue: JsonValue | undefined, condition: 'types' | 'require-types' = 'types', ): string | null { if (typeof exportValue === 'string') { @@ -1136,29 +1146,17 @@ function resolveUpstreamDtsPath( ? join(providerPkgRoot, exportValue) : null; } - if (typeof exportValue !== 'object' || exportValue === null) { + if (!isObjectValue(exportValue)) { return null; } - const value = exportValue as Record; - if (condition === 'types') { - if (typeof value.types === 'string') { - return join(providerPkgRoot, value.types); - } - if (typeof value.import === 'object' && value.import !== null) { - const types = (value.import as Record).types; - if (typeof types === 'string') { - return join(providerPkgRoot, types); - } - } - } else { - if (typeof value.require === 'object' && value.require !== null) { - const types = (value.require as Record).types; - if (typeof types === 'string') { - return join(providerPkgRoot, types); - } - } + if (condition === 'types' && typeof exportValue.types === 'string') { + return join(providerPkgRoot, exportValue.types); } - return null; + + const branch = condition === 'types' ? exportValue.import : exportValue.require; + return isObjectValue(branch) && typeof branch.types === 'string' + ? join(providerPkgRoot, branch.types) + : null; } async function writeShimDts( @@ -1191,7 +1189,7 @@ async function writeShimDts( */ async function createShimForExport( shimBaseName: string, - exportValue: unknown, + exportValue: JsonValue | undefined, testImportSpecifier: string, distDir: string, opts: { providerPkgRoot?: string } = {}, @@ -1199,7 +1197,7 @@ async function createShimForExport( const shimDir = join(distDir, dirname(shimBaseName)); await mkdir(shimDir, { recursive: true }); - const baseFileName = shimBaseName.includes('/') ? shimBaseName.split('/').pop()! : shimBaseName; + const baseFileName = shimBaseName.slice(shimBaseName.lastIndexOf('/') + 1); const shimDirForFile = shimBaseName.includes('/') ? shimDir : distDir; // Preserve the Vite+ browser-context aliases after v5 moved the virtual // module. Keep the original type specifier for module augmentations. @@ -1224,44 +1222,42 @@ async function createShimForExport( return { default: `./dist/test/${shimBaseName}.js` }; } - if (typeof exportValue === 'object' && exportValue !== null) { - const value = exportValue as Record; - - // Check if it has import/require conditions (complex conditional export) - if ('import' in value || 'require' in value) { - return await createConditionalShim( - value, - testImportSpecifier, - shimDirForFile, - baseFileName, - shimBaseName, - distDir, - opts, - ); - } + if (!isObjectValue(exportValue)) { + return null; + } - // Simple object with types/default - const result: ExportValue = {}; + // Check if it has import/require conditions (complex conditional export) + if ('import' in exportValue || 'require' in exportValue) { + return await createConditionalShim( + exportValue, + testImportSpecifier, + shimDirForFile, + baseFileName, + shimBaseName, + distDir, + opts, + ); + } - if (value.types && typeof value.types === 'string') { - const dtsPath = join(shimDirForFile, `${baseFileName}.d.ts`); - const upstream = opts.providerPkgRoot - ? resolveUpstreamDtsPath(opts.providerPkgRoot, value, 'types') - : null; - await writeShimDts(dtsPath, testImportSpecifier, upstream, distDir); - (result as Record).types = `./dist/test/${shimBaseName}.d.ts`; - } + // Simple object with types/default + const result: ExportValue = {}; - if (value.default && typeof value.default === 'string') { - const jsPath = join(shimDirForFile, `${baseFileName}.js`); - await writeFile(jsPath, `export * from '${runtimeSpecifier}';\n`); - (result as Record).default = `./dist/test/${shimBaseName}.js`; - } + if (exportValue.types && typeof exportValue.types === 'string') { + const dtsPath = join(shimDirForFile, `${baseFileName}.d.ts`); + const upstream = opts.providerPkgRoot + ? resolveUpstreamDtsPath(opts.providerPkgRoot, exportValue, 'types') + : null; + await writeShimDts(dtsPath, testImportSpecifier, upstream, distDir); + result.types = `./dist/test/${shimBaseName}.d.ts`; + } - return Object.keys(result).length > 0 ? result : null; + if (exportValue.default && typeof exportValue.default === 'string') { + const jsPath = join(shimDirForFile, `${baseFileName}.js`); + await writeFile(jsPath, `export * from '${runtimeSpecifier}';\n`); + result.default = `./dist/test/${shimBaseName}.js`; } - return null; + return Object.keys(result).length > 0 ? result : null; } /** @@ -1278,7 +1274,7 @@ async function createShimForExport( * matching the catch-all `default` (which would point at the ESM file). */ async function createConditionalShim( - value: Record, + value: JsonObject, testImportSpecifier: string, shimDir: string, baseFileName: string, @@ -1304,13 +1300,13 @@ async function createConditionalShim( // Handle import condition if (value.import) { - const importValue = value.import as Record; + const importValue = value.import; if (typeof importValue === 'string') { const jsPath = join(shimDir, `${baseFileName}.js`); await writeFile(jsPath, `export * from '${testImportSpecifier}';\n`); entries.push(['import', `./dist/test/${shimBaseName}.js`]); - } else if (typeof importValue === 'object' && importValue !== null) { + } else if (isObjectValue(importValue)) { const importResult: Record = {}; if (importValue.types && typeof importValue.types === 'string') { @@ -1340,13 +1336,13 @@ async function createConditionalShim( // Handle require condition — emitted BEFORE `default` so CJS resolution // picks the `.cjs` shim instead of the catch-all `default` entry. if (value.require) { - const requireValue = value.require as Record; + const requireValue = value.require; if (typeof requireValue === 'string') { const cjsPath = join(shimDir, `${baseFileName}.cjs`); await writeFile(cjsPath, `module.exports = require('${testImportSpecifier}');\n`); entries.push(['require', `./dist/test/${shimBaseName}.cjs`]); - } else if (typeof requireValue === 'object' && requireValue !== null) { + } else if (isObjectValue(requireValue)) { const requireResult: Record = {}; if (requireValue.types && typeof requireValue.types === 'string') { @@ -1383,11 +1379,11 @@ async function createConditionalShim( /** * Update CLI package.json with the generated exports */ -async function updateCliPackageJson(pkgPath: string, generatedExports: Record) { - const pkg = JSON.parse(await readFile(pkgPath, 'utf-8')); +async function updateCliPackageJson(pkgPath: string, generatedExports: JsonObject) { + const pkg = parseJsonObject(await readFile(pkgPath, 'utf8')); // Remove old ./test/* exports (if any) to ensure clean sync - if (pkg.exports) { + if (isObjectValue(pkg.exports)) { for (const key of Object.keys(pkg.exports)) { if (key.startsWith('./test')) { delete pkg.exports[key]; @@ -1397,7 +1393,7 @@ async function updateCliPackageJson(pkgPath: string, generatedExports: Record | undefined, version: string, ): boolean { const tarball = resolution?.tarball; @@ -68,35 +65,53 @@ function hasValidTarball( return tarball.startsWith(prefix) && /^[a-f0-9]{40}\.tgz$/.test(tarball.slice(prefix.length)); } -export function validateInstallLockfile(content: string, version: string): void { - const lock = parse(content) as { - lockfileVersion?: string; - importers?: Record< - string, - { dependencies?: Record } - >; - packages?: Record; - } | null; - const cli = lock?.importers?.['.']?.dependencies?.['vite-plus']; - const integrity = lock?.packages?.[`vite-plus@${version}`]?.resolution?.integrity; +const resolutionSchema = z.object({ + integrity: z.string().optional(), + tarball: z.string().optional(), +}); +const lockfileSchema = z.object({ + lockfileVersion: z.union([z.string(), z.number()]), + importers: z.record( + z.string(), + z.object({ + dependencies: z + .record(z.string(), z.object({ specifier: z.string(), version: z.string() })) + .optional(), + }), + ), + packages: z.record(z.string(), z.object({ resolution: resolutionSchema.optional() })), +}); + +export function validateInstallLockfile( + content: string, + version: string, +): z.infer { + const parsed = lockfileSchema.safeParse(parse(content)); + if (!parsed.success) { + throw new Error(`Invalid global installation lockfile for vite-plus@${version}`); + } + const lock = parsed.data; + const cli = lock.importers['.']?.dependencies?.['vite-plus']; + const integrity = lock.packages[`vite-plus@${version}`]?.resolution?.integrity; if ( - String(lock?.lockfileVersion) !== '9.0' || + String(lock.lockfileVersion) !== '9.0' || cli?.specifier !== version || - (cli.version !== version && !cli.version?.startsWith(`${version}(`)) || + (cli.version !== version && !cli.version.startsWith(`${version}(`)) || !integrity || - !Object.entries(lock?.packages ?? {}).every(([key, entry]) => + !Object.entries(lock.packages).every(([key, entry]) => hasValidTarball(key, entry.resolution, version), ) ) { throw new Error(`Invalid global installation lockfile for vite-plus@${version}`); } + return lock; } /** Reuse the first published platform's lockfile after a partial release failure. */ export async function publishedInstallLockfile( version: string, registry: string, - platformPackages: string[], + platformPackages: Array, fetchImpl: typeof fetch = fetch, ): Promise { for (const name of platformPackages) { @@ -109,21 +124,19 @@ export async function publishedInstallLockfile( if (!response.ok) { throw new Error(`Could not check ${name}@${version}: HTTP ${response.status}`); } - const metadata = (await response.json()) as { - vpInstallLockfile?: boolean; - dist: { tarball: string; integrity: string }; - }; + const metadata = z + .object({ vpInstallLockfile: z.boolean().optional(), dist: z.unknown().optional() }) + .parse(await response.json()); if (!metadata.vpInstallLockfile) { throw new Error(`${name}@${version} was published without an installation lockfile`); } - const archive = await fetchImpl(metadata.dist.tarball, { signal: AbortSignal.timeout(60_000) }); + const dist = z.object({ tarball: z.string(), integrity: z.string() }).parse(metadata.dist); + const archive = await fetchImpl(dist.tarball, { signal: AbortSignal.timeout(60_000) }); if (!archive.ok) { throw new Error(`Could not download ${name}@${version}: HTTP ${archive.status}`); } const bytes = Buffer.from(await archive.arrayBuffer()); - if ( - `sha512-${createHash('sha512').update(bytes).digest('base64')}` !== metadata.dist.integrity - ) { + if (`sha512-${createHash('sha512').update(bytes).digest('base64')}` !== dist.integrity) { throw new Error(`Integrity mismatch for ${name}@${version}`); } const files = parseTar(new Uint8Array(gunzipSync(bytes))); @@ -138,7 +151,11 @@ export async function publishedInstallLockfile( return undefined; } -async function runPnpm(directory: string, args: string[], env: NodeJS.ProcessEnv): Promise { +async function runPnpm( + directory: string, + args: Array, + env: NodeJS.ProcessEnv, +): Promise { await exec( 'npm', ['exec', '--yes', `--package=pnpm@${INSTALL_PNPM_VERSION}`, '--', 'pnpm', ...args], @@ -226,7 +243,7 @@ async function main(): Promise { try { content = await readFile(join(directory, INSTALL_LOCKFILE), 'utf8'); } catch (error) { - if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { + if (errorCode(error) !== 'ENOENT') { throw error; } } @@ -242,7 +259,7 @@ async function main(): Promise { const invokedPath = process.argv[1]; if (invokedPath && pathToFileURL(resolve(invokedPath)).href === import.meta.url) { - main().catch((error: unknown) => { + await main().catch((error: unknown) => { console.error(error); process.exitCode = 1; }); diff --git a/packages/cli/generate-preview-install-lockfile.ts b/packages/cli/generate-preview-install-lockfile.ts index 4c0f08fdff..e60b960af9 100644 --- a/packages/cli/generate-preview-install-lockfile.ts +++ b/packages/cli/generate-preview-install-lockfile.ts @@ -3,7 +3,6 @@ import { join, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import { createTarGzip, parseTarGzip } from 'nanotar'; -import { parse } from 'yaml'; import { generateInstallLockfile, @@ -13,6 +12,7 @@ import { publishedInstallLockfile, validateInstallLockfile, } from './generate-install-lockfile.ts'; +import { parseJsonObject } from './src/utils/json-value.ts'; const platformPrefix = '@voidzero-dev/vite-plus-cli-'; const decoder = new TextDecoder(); @@ -35,10 +35,12 @@ export async function preparePreviewPackages( if (!manifest?.data) { throw new Error(`${file} is missing package/package.json`); } - const packageJson = JSON.parse(decoder.decode(manifest.data)); - const name = packageJson.name as string; - if (!name?.startsWith(platformPrefix) || names.has(name)) { - throw new Error(`Expected unique global CLI platform packages, found ${name}`); + const packageJson = parseJsonObject(decoder.decode(manifest.data)); + const { name } = packageJson; + if (typeof name !== 'string' || !name.startsWith(platformPrefix) || names.has(name)) { + throw new Error( + `Expected unique global CLI platform packages, found ${JSON.stringify(name)}`, + ); } names.add(name); archives.push({ file, entries, manifest, packageJson }); @@ -52,18 +54,21 @@ export async function preparePreviewPackages( const content = (await recoverLockfile(version, PREVIEW_REGISTRY, [...names])) ?? (await resolveLockfile(version, PREVIEW_REGISTRY)); - validateInstallLockfile(content, version); - const lock = parse(content) as { packages: Record }; + const lock = validateInstallLockfile(content, version); if (Object.keys(lock.packages).some((name) => name.startsWith(platformPrefix))) { throw new Error(`Installation lockfile must not depend on ${platformPrefix} packages`); } for (const { file, entries, manifest, packageJson } of archives) { + const files = packageJson.files ?? []; + if (!Array.isArray(files) || !files.every((name) => typeof name === 'string')) { + throw new TypeError(`Invalid files list in ${file}`); + } manifest.data = new TextEncoder().encode( JSON.stringify({ ...packageJson, vpInstallLockfile: true, - files: [...new Set([...((packageJson.files as string[]) ?? []), INSTALL_LOCKFILE])], + files: [...new Set([...files, INSTALL_LOCKFILE])], }), ); await writeFile( @@ -88,7 +93,7 @@ async function main(): Promise { } if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) { - main().catch((error: unknown) => { + await main().catch((error: unknown) => { console.error(error); process.exitCode = 1; }); diff --git a/packages/cli/publish-native-addons.ts b/packages/cli/publish-native-addons.ts index 31ab4386f1..1525d3a32d 100644 --- a/packages/cli/publish-native-addons.ts +++ b/packages/cli/publish-native-addons.ts @@ -8,23 +8,21 @@ import { writeFileSync, } from 'node:fs'; import { readdir } from 'node:fs/promises'; -import { dirname, join } from 'node:path'; -import { fileURLToPath } from 'node:url'; +import { join } from 'node:path'; import { NapiCli, parseTriple } from '@napi-rs/cli'; import { publishNpmPackageFromEnv } from '../../.github/scripts/publish-npm-package.ts'; -import { - type NpmPackageVersion, - waitForNpmPackagesFromEnv, -} from '../../.github/scripts/wait-for-npm-packages.ts'; +import type { NpmPackageVersion } from '../../.github/scripts/wait-for-npm-packages.ts'; +import { waitForNpmPackagesFromEnv } from '../../.github/scripts/wait-for-npm-packages.ts'; import { INSTALL_LOCKFILE, validateInstallLockfile } from './generate-install-lockfile.ts'; import pkg from './package.json' with { type: 'json' }; +import { isObjectValue } from './src/utils/json-value.ts'; import { editJsonFile, readJsonFile } from './src/utils/json.ts'; const cli = new NapiCli(); -const currentDir = dirname(fileURLToPath(import.meta.url)); +const currentDir = import.meta.dirname; const repoRoot = join(currentDir, '..', '..'); const nodeVersion = readFileSync(join(repoRoot, '.node-version'), 'utf8').trim(); if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(nodeVersion)) { @@ -106,19 +104,18 @@ if (phase !== 'cli') { for (const dir of platformDirs) { editJsonFile(join(npmDir, dir, 'package.json'), (pkgJson) => ({ ...pkgJson, - engines: { ...(pkgJson.engines as Record), node: '>=20.0.0' }, + engines: { ...(isObjectValue(pkgJson.engines) && pkgJson.engines), node: '>=20.0.0' }, })); } } // Fresh read: napi-rs prePublish rewrote this package.json on disk, so the // top-level `pkg` import is stale for injected fields. -const cliPackageJson = readJsonFile(join(currentDir, 'package.json')) as { - version: string; - repository?: unknown; - optionalDependencies?: Record; -}; +const cliPackageJson = readJsonFile(join(currentDir, 'package.json')); // Lockstep versioning: every generated platform package uses the CLI version. +if (typeof cliPackageJson.version !== 'string') { + throw new TypeError('Expected a version in packages/cli/package.json'); +} const cliVersion = cliPackageJson.version; // napi-rs prePublish injects the platform packages into this package's @@ -131,8 +128,9 @@ const cliVersion = cliPackageJson.version; const nativePlatformPins: Record = {}; for (const target of pkg.napi.targets) { const packageName = `${pkg.napi.packageName}-${parseTriple(target).platformArchABI}`; - const pin = cliPackageJson.optionalDependencies?.[packageName]; - if (!pin) { + const optional = cliPackageJson.optionalDependencies; + const pin = isObjectValue(optional) ? optional[packageName] : undefined; + if (typeof pin !== 'string' || !pin) { console.error( `napi prePublish did not inject ${packageName} into packages/cli/package.json optionalDependencies`, ); @@ -143,11 +141,11 @@ for (const target of pkg.napi.targets) { editJsonFile(join(repoRoot, 'packages', 'core', 'package.json'), (corePkgJson) => ({ ...corePkgJson, optionalDependencies: { - ...(corePkgJson.optionalDependencies as Record | undefined), + ...(isObjectValue(corePkgJson.optionalDependencies) && corePkgJson.optionalDependencies), ...nativePlatformPins, }, })); -const platformPackages: NpmPackageVersion[] = []; +const platformPackages: Array = []; // Publish each NAPI platform package (without vp binary) const npmTag = process.env.NPM_TAG || 'latest'; @@ -155,7 +153,11 @@ const publishArgs = ['publish', '--tag', npmTag, '--access', 'public']; if (!skipNpmPublish && phase !== 'cli') { for (const file of await readdir(npmDir)) { const platformDir = join(npmDir, file); - const platformPackage = readJsonFile(join(platformDir, 'package.json')) as NpmPackageVersion; + const { name, version } = readJsonFile(join(platformDir, 'package.json')); + if (typeof name !== 'string' || typeof version !== 'string') { + throw new TypeError(`Expected package name and version in ${platformDir}/package.json`); + } + const platformPackage = { name, version }; await publishNpmPackageFromEnv(platformPackage, 'npm', publishArgs, platformDir); platformPackages.push(platformPackage); } @@ -227,10 +229,10 @@ async function prepareAndPublishCliPackage(napiTarget: string): Promise { version: cliVersion, os: [platform], cpu: [arch], - ...(abi ? { libc: [abi] } : {}), + libc: abi ? [abi] : undefined, files, vpNodeVersion: nodeVersion, - ...(!skipNpmPublish ? { vpInstallLockfile: true } : {}), + vpInstallLockfile: skipNpmPublish ? undefined : true, description: `Vite+ CLI binary for ${platformArchABI}`, repository: cliPackageJson.repository, }; diff --git a/packages/cli/src/__tests__/define-config-plugins.spec.ts b/packages/cli/src/__tests__/define-config-plugins.spec.ts index 4cee890ebd..468934142b 100644 --- a/packages/cli/src/__tests__/define-config-plugins.spec.ts +++ b/packages/cli/src/__tests__/define-config-plugins.spec.ts @@ -2,10 +2,15 @@ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'nod import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import type { + ignoreInput as ignoreInputImplementation, + ignoreOutput as ignoreOutputImplementation, +} from '@voidzero-dev/vite-task-client'; import type { Plugin } from 'vite'; import { normalizePath } from 'vite'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { createVitest, type VitestPluginContext } from 'vitest/node'; +import { assert, afterEach, describe, expect, it, vi } from 'vitest'; +import type { VitestPluginContext } from 'vitest/node'; +import { createVitest } from 'vitest/node'; import { assertCoverageProviderVersionMatch, @@ -21,8 +26,8 @@ import { VITEST_VERSION } from '../utils/constants.ts'; // Capture the runner notifications so the cache-paths plugin can be asserted // without a live `vp run` around the test process. const taskClientMocks = vi.hoisted(() => ({ - ignoreInput: vi.fn(), - ignoreOutput: vi.fn(), + ignoreInput: vi.fn(), + ignoreOutput: vi.fn(), })); vi.mock('@voidzero-dev/vite-task-client', () => taskClientMocks); @@ -32,7 +37,7 @@ const CACHE_PATHS_PLUGIN_NAME = 'vite-plus:vitest-cache-paths'; function pluginName(p: unknown): string | undefined { if (p && typeof p === 'object' && 'name' in p && typeof p.name === 'string') { - return (p as { name: string }).name; + return p.name; } return undefined; } @@ -40,15 +45,15 @@ function pluginName(p: unknown): string | undefined { describe('defineConfig project plugin injection', () => { it('injects resolver + auto-inline plugins at the root plugins array', () => { const existing: Plugin = { name: 'user-existing-root-plugin' }; - const result = defineConfig({ plugins: [existing] }) as { plugins: unknown[] }; + const result = defineConfig({ plugins: [existing] }); - expect(pluginName(result.plugins[0])).toBe(RESOLVER_PLUGIN_NAME); - expect(pluginName(result.plugins[1])).toBe(AUTO_INLINE_PLUGIN_NAME); - expect(pluginName(result.plugins[2])).toBe(COVERAGE_GUARD_PLUGIN_NAME); - expect(pluginName(result.plugins[3])).toBe(CACHE_PATHS_PLUGIN_NAME); - expect(pluginName(result.plugins[4])).toBe('user-existing-root-plugin'); - expect((result.plugins[0] as Plugin).enforce).toBe('pre'); - expect((result.plugins[1] as Plugin).enforce).toBe('pre'); + expect(pluginName(result.plugins![0])).toBe(RESOLVER_PLUGIN_NAME); + expect(pluginName(result.plugins![1])).toBe(AUTO_INLINE_PLUGIN_NAME); + expect(pluginName(result.plugins![2])).toBe(COVERAGE_GUARD_PLUGIN_NAME); + expect(pluginName(result.plugins![3])).toBe(CACHE_PATHS_PLUGIN_NAME); + expect(pluginName(result.plugins![4])).toBe('user-existing-root-plugin'); + expect(result.plugins![0]).toHaveProperty('enforce', 'pre'); + expect(result.plugins![1]).toHaveProperty('enforce', 'pre'); }); it('injects resolver + auto-inline plugins into an inline-object project entry, preserving existing plugins', () => { @@ -63,10 +68,11 @@ describe('defineConfig project plugin injection', () => { }, ], }, - }) as { test: { projects: unknown[] } }; + }); - const project = result.test.projects[0] as { plugins: unknown[]; test: { name: string } }; - expect(project.test.name).toBe('unit'); + const project = result.test!.projects![0]; + assert(project && typeof project === 'object' && 'plugins' in project && project.plugins); + expect(project.test?.name).toBe('unit'); expect(pluginName(project.plugins[0])).toBe(RESOLVER_PLUGIN_NAME); expect(pluginName(project.plugins[1])).toBe(AUTO_INLINE_PLUGIN_NAME); expect(pluginName(project.plugins[2])).toBe(COVERAGE_GUARD_PLUGIN_NAME); @@ -76,7 +82,7 @@ describe('defineConfig project plugin injection', () => { expect(project.plugins[4]).toBe(existing); }); - it('injects plugins into the return value of a function-shaped project entry', () => { + it('injects plugins into the return value of a function-shaped project entry', async () => { const existing: Plugin = { name: 'user-fn-project-plugin' }; const projectFn = () => ({ extends: false, @@ -85,15 +91,17 @@ describe('defineConfig project plugin injection', () => { }); const result = defineConfig({ test: { projects: [projectFn] }, - }) as { test: { projects: unknown[] } }; + }); - const wrapped = result.test.projects[0]; + const wrapped = result.test!.projects![0]; expect(typeof wrapped).toBe('function'); // Vitest passes a `ConfigEnv` to the function; we don't depend on its // shape here, the wrapper just forwards it. const fakeEnv = { mode: 'test', command: 'serve' as const }; - const resolved = (wrapped as (env: typeof fakeEnv) => { plugins: unknown[] })(fakeEnv); + assert(typeof wrapped === 'function'); + const resolved = await wrapped(fakeEnv); + assert(resolved.plugins); expect(pluginName(resolved.plugins[0])).toBe(RESOLVER_PLUGIN_NAME); expect(pluginName(resolved.plugins[1])).toBe(AUTO_INLINE_PLUGIN_NAME); expect(pluginName(resolved.plugins[2])).toBe(COVERAGE_GUARD_PLUGIN_NAME); @@ -106,9 +114,9 @@ describe('defineConfig project plugin injection', () => { test: { projects: ['./packages/*', './apps/*'], }, - }) as { test: { projects: unknown[] } }; + }); - expect(result.test.projects).toEqual(['./packages/*', './apps/*']); + expect(result.test!.projects!).toEqual(['./packages/*', './apps/*']); }); it('handles projects with no existing plugins array', () => { @@ -121,10 +129,11 @@ describe('defineConfig project plugin injection', () => { }, ], }, - }) as { test: { projects: unknown[] } }; + }); - const project = result.test.projects[0] as { plugins: unknown[]; test: { name: string } }; - expect(project.test.name).toBe('no-plugins'); + const project = result.test!.projects![0]; + assert(project && typeof project === 'object' && 'plugins' in project && project.plugins); + expect(project.test?.name).toBe('no-plugins'); expect(project.plugins).toHaveLength(4); expect(pluginName(project.plugins[0])).toBe(RESOLVER_PLUGIN_NAME); expect(pluginName(project.plugins[1])).toBe(AUTO_INLINE_PLUGIN_NAME); @@ -156,7 +165,8 @@ describe('defineConfig project plugin injection', () => { throw new Error('Expected project function'); } expect(await fn({ command: 'serve', mode: 'test' })).toBe(inherited); - const resolved = (await promise) as { plugins: unknown[] }; + const resolved = await promise; + assert(resolved && typeof resolved === 'object' && 'plugins' in resolved && resolved.plugins); expect(resolved.plugins.map(pluginName)).toEqual([ RESOLVER_PLUGIN_NAME, AUTO_INLINE_PLUGIN_NAME, @@ -193,9 +203,9 @@ describe('defineConfig project plugin injection', () => { }, }); expect(config.plugins).toHaveLength(4); - const [independent, inherited] = config.test!.projects! as { plugins?: unknown[] }[]; - expect(independent.plugins).toHaveLength(4); - expect(inherited.plugins).toBeUndefined(); + const [independent, inherited] = config.test!.projects!; + expect(independent).toHaveProperty('plugins.length', 4); + expect(inherited).not.toHaveProperty('plugins'); }); }); @@ -203,7 +213,7 @@ const AUTO_INLINE_PLUGIN_NAME = 'vite-plus:auto-inline-matcher-deps'; /** Builds a mock require-factory where only `installedPkgs` resolve. */ function makeRequireFactory( - installedPkgs: string[], + installedPkgs: Array, ): (from: string) => { resolve: (id: string) => string } { return (_from: string) => ({ resolve(id: string) { @@ -244,7 +254,7 @@ describe('computeAutoInlineList', () => { }); it('merges with an existing user inline array, preserving order and deduplicating', () => { - const existing: (string | RegExp)[] = ['my-pkg', '@testing-library/jest-dom']; + const existing: Array = ['my-pkg', '@testing-library/jest-dom']; const result = computeAutoInlineList(existing, '/project', allInstalledFactory); expect(result).toEqual([ 'my-pkg', @@ -261,7 +271,7 @@ describe('computeAutoInlineList', () => { }); it('treats a regexp entry that matches an auto-inline pkg as already covered', () => { - const existing: (string | RegExp)[] = [/^@testing-library\//, /^@storybook\//]; + const existing: Array = [/^@testing-library\//, /^@storybook\//]; const result = computeAutoInlineList(existing, '/project', allInstalledFactory); // Both '@testing-library/jest-dom' and '@storybook/test' are covered; // only 'jest-extended' should be appended. @@ -272,12 +282,12 @@ describe('computeAutoInlineList', () => { }); it('returns null when all auto-inline packages are already in the existing list', () => { - const existing: (string | RegExp)[] = [...AUTO_INLINE_DEPS]; + const existing: Array = [...AUTO_INLINE_DEPS]; expect(computeAutoInlineList(existing, '/project', allInstalledFactory)).toBeNull(); }); it('passes the project root to the require factory', () => { - const capturedFromPaths: string[] = []; + const capturedFromPaths: Array = []; const factory = (from: string) => { capturedFromPaths.push(from); return { resolve: (_id: string) => `/mock/node_modules/${_id}/index.js` }; @@ -292,10 +302,7 @@ describe('computeAutoInlineList', () => { * packages in `installed` resolve, and reading their package.json returns the * mapped version. */ -function makeCoverageDeps(installed: Record): { - createRequire: (from: string) => { resolve: (id: string) => string }; - readFile: (path: string) => string; -} { +function makeCoverageDeps(installed: Record) { return { createRequire: (_from: string) => ({ resolve(id: string) { @@ -414,10 +421,16 @@ describe('checkCoverageProviderVersion', () => { /** Extract the cache-paths plugin from a fresh defineConfig. */ function getCachePathsPlugin(): { configureVitest: (ctx: unknown) => void } { - const result = defineConfig({}) as { plugins: unknown[] }; - const plugin = result.plugins.find( + const result = defineConfig({}); + const plugins: Array = result.plugins!; + const plugin = plugins.find( (p): p is { configureVitest: (ctx: unknown) => void } => - !!p && typeof p === 'object' && (p as { name?: unknown }).name === CACHE_PATHS_PLUGIN_NAME, + typeof p === 'object' && + p !== null && + 'name' in p && + 'configureVitest' in p && + typeof p.configureVitest === 'function' && + p.name === CACHE_PATHS_PLUGIN_NAME, ); if (!plugin) { throw new Error('cache-paths plugin not found'); @@ -538,8 +551,7 @@ describe('defineConfig vitest cache paths plugin', () => { }; }, }, - // Vitest 5.0.4's type unwraps object hooks, but its runtime accepts them. - } as unknown as Plugin, + }, ], }), ); @@ -574,10 +586,16 @@ describe('defineConfig vitest cache paths plugin', () => { /** Extract the coverage-version-guard plugin from a fresh defineConfig. */ function getCoverageGuard(): { configureVitest: (ctx: unknown) => void } { - const result = defineConfig({}) as { plugins: unknown[] }; - const plugin = result.plugins.find( + const result = defineConfig({}); + const plugins: Array = result.plugins!; + const plugin = plugins.find( (p): p is { configureVitest: (ctx: unknown) => void } => - !!p && typeof p === 'object' && (p as { name?: unknown }).name === COVERAGE_GUARD_PLUGIN_NAME, + typeof p === 'object' && + p !== null && + 'name' in p && + 'configureVitest' in p && + typeof p.configureVitest === 'function' && + p.name === COVERAGE_GUARD_PLUGIN_NAME, ); if (!plugin) { throw new Error('coverage guard plugin not found'); @@ -621,7 +639,7 @@ describe('defineConfig coverage version guard plugin', () => { const root = makeSkewedCoverageRoot(); try { const guard = getCoverageGuard(); - const original = vi.fn(async () => {}); + const original = vi.fn<() => Promise>(async () => {}); const vitest = { config: { root, coverage: { enabled: false, provider: 'v8' } }, enableCoverage: original, @@ -641,7 +659,7 @@ describe('defineConfig coverage version guard plugin', () => { const original = async () => { originalCalls += 1; }; - const vitest: Record = { + const vitest = { config: { root: '/project', coverage: { provider: 'v8' } }, enableCoverage: original, }; @@ -650,13 +668,13 @@ describe('defineConfig coverage version guard plugin', () => { expect(vitest.enableCoverage).not.toBe(original); // ...and the wrapper delegates to the original (no provider resolves from // this fake root, so the late-path check is a no-op). - await (vitest.enableCoverage as () => Promise)(); + await vitest.enableCoverage(); expect(originalCalls).toBe(1); }); it('handles the shared vitest instance once even though configureVitest runs per project', () => { const guard = getCoverageGuard(); - const vitest: Record = { + const vitest = { config: { root: '/project', coverage: {} }, enableCoverage: async () => {}, }; diff --git a/packages/cli/src/__tests__/define-config-runtime-cache.spec.ts b/packages/cli/src/__tests__/define-config-runtime-cache.spec.ts index 44350efcd4..8fc91217ae 100644 --- a/packages/cli/src/__tests__/define-config-runtime-cache.spec.ts +++ b/packages/cli/src/__tests__/define-config-runtime-cache.spec.ts @@ -3,21 +3,22 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { resolveConfig, type UserConfig } from 'vite'; +import type { UserConfig } from 'vite'; +import { resolveConfig } from 'vite'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { AUTO_INLINE_DEPS, defineConfig } from '../define-config.ts'; -const probes = vi.hoisted(() => [] as { from: string; id: string }[]); +const probes = vi.hoisted(() => [] as Array<{ from: string; id: string }>); -vi.mock('node:module', async (importOriginal) => { - const actual = await importOriginal(); +vi.mock(import('node:module'), async (importOriginal) => { + const actual = await importOriginal(); return Object.assign({}, actual, { createRequire(from: string | URL) { const require = actual.createRequire(from); const resolve = require.resolve; require.resolve = Object.assign( - (id: string, options?: { paths?: string[] }) => { + (id: string, options?: { paths?: Array }) => { probes.push({ from: String(from), id }); return resolve(id, options); }, @@ -28,10 +29,7 @@ vi.mock('node:module', async (importOriginal) => { }); }); -vi.mock('node:fs', async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, readFileSync: vi.fn(actual.readFileSync) }; -}); +vi.mock('node:fs', { spy: true }); function loadVitestConfig(root: string) { return resolveConfig( diff --git a/packages/cli/src/__tests__/define-config-test-field.spec.ts b/packages/cli/src/__tests__/define-config-test-field.spec.ts index ebbef88cea..bf8b65fd4b 100644 --- a/packages/cli/src/__tests__/define-config-test-field.spec.ts +++ b/packages/cli/src/__tests__/define-config-test-field.spec.ts @@ -1,25 +1,27 @@ -import { describe, it } from 'vitest'; +import { expect, describe, it } from 'vitest'; -import { defineConfig } from '../index.js'; +import { defineConfig } from '../index.ts'; describe('defineConfig test field typing', () => { it('accepts test config without TS error', () => { - defineConfig({ + const cfg = defineConfig({ test: { globals: true, environment: 'node', include: ['src/**/*.spec.ts'], }, }); + expect(cfg.test).toMatchObject({ globals: true, environment: 'node' }); }); it('accepts test config alongside other vite-plus fields', () => { - defineConfig({ + const cfg = defineConfig({ test: { globals: true, environment: 'jsdom', }, lint: {}, }); + expect(cfg.test).toMatchObject({ globals: true, environment: 'jsdom' }); }); }); diff --git a/packages/cli/src/__tests__/define-config-vitest-resolver.spec.ts b/packages/cli/src/__tests__/define-config-vitest-resolver.spec.ts index a8bbb99f25..9c0ec7d115 100644 --- a/packages/cli/src/__tests__/define-config-vitest-resolver.spec.ts +++ b/packages/cli/src/__tests__/define-config-vitest-resolver.spec.ts @@ -1,28 +1,59 @@ import { fileURLToPath } from 'node:url'; +import { isRegExp } from 'node:util/types'; import { preview } from '@vitest/browser-preview'; -import { - build, - resolveConfig, - type Alias, - type ConfigEnv, - type Plugin, - type UserConfig, -} from 'vite'; -import { describe, expect, it } from 'vitest'; +import type { Alias, ConfigEnv, Plugin, UserConfig } from 'vite'; +import { build, resolveConfig } from 'vite'; +import { assert, describe, expect, it } from 'vitest'; import { defineConfig, defineProject, isVitestFamilySpecifier } from '../define-config.ts'; import { VITEST_RESOLVER_PACKAGES } from '../utils/vitest-ecosystem.ts'; const RESOLVER_PLUGIN_NAME = 'vite-plus:vitest-resolver'; -function findPlugin(plugins: unknown, name: string): Plugin | undefined { +type ResolverPlugin = { + name: string; + enforce?: string; + config: { handler: (config: UserConfig, env: ConfigEnv) => void }; + resolveId: { filter: { id: RegExp }; handler: ResolveId }; +}; + +function hasHandler(hook: unknown): hook is { handler: unknown } { + return ( + hook !== null && + typeof hook === 'object' && + 'handler' in hook && + typeof hook.handler === 'function' + ); +} + +function findResolverPlugin(plugins: unknown): ResolverPlugin | undefined { if (!Array.isArray(plugins)) { return undefined; } - return plugins.find( - (p): p is Plugin => !!p && typeof p === 'object' && (p as { name?: unknown }).name === name, - ); + const entries: Array = plugins; + return entries.find((plugin): plugin is ResolverPlugin => { + if ( + !plugin || + typeof plugin !== 'object' || + !('name' in plugin) || + plugin.name !== RESOLVER_PLUGIN_NAME || + !('config' in plugin) || + !('resolveId' in plugin) + ) { + return false; + } + const { config, resolveId } = plugin; + return ( + hasHandler(config) && + hasHandler(resolveId) && + 'filter' in resolveId && + !!resolveId.filter && + typeof resolveId.filter === 'object' && + 'id' in resolveId.filter && + isRegExp(resolveId.filter.id) + ); + }); } function idOf(resolved: string | { id: string } | null | undefined): string | undefined { @@ -94,8 +125,8 @@ describe('isVitestFamilySpecifier', () => { describe('vitePlusVitestResolverPlugin', () => { it('lets every resolver package through the hook filter', () => { - const plugin = findPlugin(defineConfig({}).plugins, RESOLVER_PLUGIN_NAME)!; - const { filter } = plugin.resolveId as { filter: { id: RegExp } }; + const plugin = findResolverPlugin(defineConfig({}).plugins)!; + const { filter } = plugin.resolveId; for (const name of [...VITEST_RESOLVER_PACKAGES, 'vite-plus/test']) { expect(name).toMatch(filter.id); } @@ -111,7 +142,7 @@ describe('vitePlusVitestResolverPlugin', () => { ['@vitest/mocker', 'resolved-by-vitest'], ['vite-plus/test', 'resolved-by-vitest'], ])('dispatches %s through the native hook filter', async (specifier, expected) => { - const plugin = findPlugin(defineConfig({}).plugins, RESOLVER_PLUGIN_NAME)!; + const plugin = findResolverPlugin(defineConfig({}).plugins)!; const hook = plugin.resolveId; if (typeof hook !== 'object') { throw new Error('The resolver plugin declares resolveId as an object hook.'); @@ -185,9 +216,8 @@ describe('vitePlusVitestResolverPlugin', () => { ); it('does not add browser aliases to builds even with a Vitest environment', () => { - const plugin = findPlugin(defineConfig({}).plugins, RESOLVER_PLUGIN_NAME)!; - const hook = (plugin.config as { handler: (config: UserConfig, env: ConfigEnv) => void }) - .handler; + const plugin = findResolverPlugin(defineConfig({}).plugins)!; + const hook = plugin.config.handler; const config: UserConfig = { environments: { __vitest__: {} }, test: { browser: { enabled: true } }, @@ -197,9 +227,8 @@ describe('vitePlusVitestResolverPlugin', () => { }); it('anchors Preview optimizer dependencies without changing other providers', () => { - const plugin = findPlugin(defineConfig({}).plugins, RESOLVER_PLUGIN_NAME)!; - const hook = (plugin.config as { handler: (config: UserConfig, env: ConfigEnv) => void }) - .handler; + const plugin = findResolverPlugin(defineConfig({}).plugins)!; + const hook = plugin.config.handler; const config: UserConfig = { environments: { __vitest__: {} }, test: { @@ -210,10 +239,14 @@ describe('vitePlusVitestResolverPlugin', () => { }, }; hook(config, { command: 'serve', mode: 'test' }); - const aliases = config.resolve!.alias as Alias[]; + const configuredAliases = config.resolve!.alias; + assert(Array.isArray(configuredAliases)); + const aliases: Array = configuredAliases; expect(aliases).toHaveLength(9); for (const id of ['@testing-library/user-event', '@testing-library/dom']) { - const replacement = aliases.find(({ find }) => (find as RegExp).test(id))?.replacement; + const replacement = aliases.find( + ({ find }) => typeof find !== 'string' && find.test(id), + )?.replacement; expect(replacement?.replaceAll('\\', '/')).toContain(id); } hook(config, { command: 'serve', mode: 'test' }); @@ -221,36 +254,36 @@ describe('vitePlusVitestResolverPlugin', () => { }); it('anchors browser optimizer entries to the bundled ESM runtime', () => { - const plugin = findPlugin(defineConfig({}).plugins, RESOLVER_PLUGIN_NAME)!; - const hook = (plugin.config as { handler: (config: UserConfig, env: ConfigEnv) => void }) - .handler; + const plugin = findResolverPlugin(defineConfig({}).plugins)!; + const hook = plugin.config.handler; const config: UserConfig = { environments: { __vitest__: {} }, test: { browser: { enabled: true } }, }; hook(config, { command: 'serve', mode: 'test' }); - const aliases = config.resolve!.alias as Alias[]; + const configuredAliases = config.resolve!.alias; + assert(Array.isArray(configuredAliases)); + const aliases: Array = configuredAliases; expect(aliases).toHaveLength(7); for (const id of ['vitest', 'vitest/internal/browser', 'vitest/internal/traces']) { - expect(aliases.find(({ find }) => (find as RegExp).test(id))?.replacement).toBe( - fileURLToPath(import.meta.resolve(id)), - ); + expect( + aliases.find(({ find }) => typeof find !== 'string' && find.test(id))?.replacement, + ).toBe(fileURLToPath(import.meta.resolve(id))); } hook(config, { command: 'serve', mode: 'test' }); expect(config.resolve!.alias).toHaveLength(7); }); it('preserves explicit browser aliases and leaves Node-only configs unchanged', () => { - const plugin = findPlugin(defineConfig({}).plugins, RESOLVER_PLUGIN_NAME)!; - const hook = (plugin.config as { handler: (config: UserConfig, env: ConfigEnv) => void }) - .handler; + const plugin = findResolverPlugin(defineConfig({}).plugins)!; + const hook = plugin.config.handler; const config: UserConfig = { environments: { __vitest__: {} }, resolve: { alias: { vitest: '/custom/vitest' } }, test: { browser: { enabled: true } }, }; hook(config, { command: 'serve', mode: 'test' }); - expect((config.resolve!.alias as Alias[])[0]).toEqual({ + expect(config.resolve!.alias).toHaveProperty([0], { find: 'vitest', replacement: '/custom/vitest', }); @@ -273,11 +306,12 @@ describe('vitePlusVitestResolverPlugin', () => { }, ], }, - }) as { test: { projects: unknown[] } }; + }); - for (const project of result.test.projects) { - const plugins = (project as { plugins?: unknown }).plugins; - const plugin = findPlugin(plugins, RESOLVER_PLUGIN_NAME); + for (const project of result.test!.projects!) { + assert(project && typeof project === 'object' && 'plugins' in project); + const plugins = project.plugins; + const plugin = findResolverPlugin(plugins); expect(plugin).toBeDefined(); expect(plugin?.enforce).toBe('pre'); expect(plugin?.resolveId).toMatchObject({ handler: expect.any(Function) }); @@ -285,10 +319,8 @@ describe('vitePlusVitestResolverPlugin', () => { }); it('is injected by defineProject too (browser project configs)', () => { - const result = defineProject({ test: { browser: { enabled: true } } }) as { - plugins: unknown[]; - }; - const plugin = findPlugin(result.plugins, RESOLVER_PLUGIN_NAME); + const result = defineProject({ test: { browser: { enabled: true } } }); + const plugin = findResolverPlugin(result.plugins); expect(plugin).toBeDefined(); expect(plugin?.enforce).toBe('pre'); @@ -303,14 +335,14 @@ type ResolveIdCtx = { resolve: ( id: string, importer: string | undefined, - options: Record, + options: { skipSelf?: boolean }, ) => Promise; }; type ResolveId = ( this: ResolveIdCtx, id: string, importer: string | undefined, - options: Record, + options: { skipSelf?: boolean }, ) => Promise; interface ResolveCall { @@ -320,23 +352,20 @@ interface ResolveCall { } function getResolveId(): ResolveId { - const result = defineConfig({}) as { plugins: unknown[] }; - const plugin = findPlugin(result.plugins, RESOLVER_PLUGIN_NAME); + const result = defineConfig({}); + const plugin = findResolverPlugin(result.plugins); if (!plugin) { throw new Error(`${RESOLVER_PLUGIN_NAME} is not injected`); } - return (plugin.resolveId as { handler: ResolveId }).handler; + return plugin.resolveId.handler; } // The resolver re-resolves through `this.resolve` rooted at vite-plus's own // (bundled) anchors BEFORE the project importer. A `this.resolve` whose // `importer` is NOT the project importer is therefore a bundled-anchor probe; // `importer === PROJECT_IMPORTER` is the last-resort project fallback. -function makeCtx(resolveFor: (call: ResolveCall) => ResolveResult): { - ctx: ResolveIdCtx; - calls: ResolveCall[]; -} { - const calls: ResolveCall[] = []; +function makeCtx(resolveFor: (call: ResolveCall) => ResolveResult) { + const calls: Array = []; const ctx: ResolveIdCtx = { resolve: async (id, importer) => { const call: ResolveCall = { id, importer, fromProject: importer === PROJECT_IMPORTER }; @@ -348,10 +377,10 @@ function makeCtx(resolveFor: (call: ResolveCall) => ResolveResult): { } function resolver(command: 'serve' | 'build', vitestServer: boolean): ResolveId { - const plugin = findPlugin(defineConfig({}).plugins, RESOLVER_PLUGIN_NAME)!; - const hook = (plugin.config as { handler: (config: UserConfig, env: ConfigEnv) => void }).handler; + const plugin = findResolverPlugin(defineConfig({}).plugins)!; + const hook = plugin.config.handler; hook(vitestServer ? { environments: { __vitest__: {} } } : {}, { command, mode: 'test' }); - return (plugin.resolveId as { handler: ResolveId }).handler; + return plugin.resolveId.handler; } describe('workspace test API identity', () => { diff --git a/packages/cli/src/__tests__/exports-map.spec.ts b/packages/cli/src/__tests__/exports-map.spec.ts index 9b3432aa36..f0c36486cb 100644 --- a/packages/cli/src/__tests__/exports-map.spec.ts +++ b/packages/cli/src/__tests__/exports-map.spec.ts @@ -11,6 +11,7 @@ * `require` BEFORE `default` and that runtime resolution returns the * expected file extension for each consumer. */ + import fs from 'node:fs'; import { createRequire } from 'node:module'; import os from 'node:os'; @@ -18,27 +19,37 @@ import path from 'node:path'; import url from 'node:url'; import { isStringLiteral } from 'typescript/unstable/ast'; -import { API, type Project } from 'typescript/unstable/sync'; -import { describe, expect, it } from 'vitest'; +import type { Project } from 'typescript/unstable/sync'; +import { API } from 'typescript/unstable/sync'; +import { assert, describe, expect, it } from 'vitest'; + +import type { JsonObject, JsonValue } from '../utils/json-value.ts'; +import { isObjectValue } from '../utils/json-value.ts'; +import { readJsonFile } from '../utils/json.ts'; -const cliPkgDir = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), '../..'); +const cliPkgDir = path.resolve(import.meta.dirname, '../..'); const cliPkgJsonPath = path.join(cliPkgDir, 'package.json'); const requireFromHere = createRequire(import.meta.url); -type ExportConditions = Record; - -function isConditionObject(value: unknown): value is ExportConditions { - return typeof value === 'object' && value !== null && !Array.isArray(value); +function readExports(): JsonObject { + const { exports } = readJsonFile(cliPkgJsonPath); + assert(isObjectValue(exports), 'Expected package.json exports'); + return exports; } // `default` is a module-shape artifact, not a named export migration cares // about; only the named bindings need to survive the `vitest/config` rewrite. -function namedValueExports(mod: Record): string[] { - return Object.keys(mod).filter((key) => key !== 'default'); +function namedValueExports(keys: Array): Array { + return keys.filter((key) => key !== 'default'); +} + +function missingExports(names: Array, entries: Array<[string, unknown]>) { + const available = new Map(entries); + return names.filter((name) => available.get(name) === undefined); } function withTypeProject( - files: string[], + files: Array, check: (project: Project) => T, sources: Record = {}, ): T { @@ -72,7 +83,7 @@ function withTypeProject( } } -function projectDiagnostics({ program }: Project): string[] { +function projectDiagnostics({ program }: Project): Array { return [ ...program.getConfigFileParsingDiagnostics(), ...program.getProgramDiagnostics(), @@ -82,7 +93,7 @@ function projectDiagnostics({ program }: Project): string[] { ].map((diagnostic) => diagnostic.text); } -function typeDiagnostics(source: string, separator: string = path.sep): string[] { +function typeDiagnostics(source: string, separator: string = path.sep): Array { const filename = path.join(cliPkgDir, '__test_exports__.mts').replaceAll(/[\\/]/g, separator); return withTypeProject([filename], projectDiagnostics, { [filename.replaceAll('\\', '/')]: source, @@ -140,18 +151,20 @@ alias({ contextOptions: { reducedMotion: 'bogus' } }); }); it('keeps the reviewed Vitest v5 export surface', () => { - const pkg = JSON.parse(fs.readFileSync(cliPkgJsonPath, 'utf8')); expect( - Object.keys(pkg.exports) + Object.keys(readExports()) .filter((key) => key === './test' || key.startsWith('./test/')) .toSorted(), ).toMatchSnapshot(); }); it('resolves every runtime test export under Node ESM conditions', () => { - const pkg = JSON.parse(fs.readFileSync(cliPkgJsonPath, 'utf8')); - for (const [key, value] of Object.entries(pkg.exports as Record)) { - if (!(key === './test' || key.startsWith('./test/')) || (!value.default && !value.import)) { + for (const [key, value] of Object.entries(readExports())) { + if ( + !(key === './test' || key.startsWith('./test/')) || + !isObjectValue(value) || + (!value.default && !value.import) + ) { continue; } const resolved = import.meta.resolve(`vite-plus${key.slice(1)}`); @@ -160,11 +173,11 @@ alias({ contextOptions: { reducedMotion: 'bogus' } }); }); it.each(['/', '\\'])('compiles all typed test exports with %s path separators', (separator) => { - const pkg = JSON.parse(fs.readFileSync(cliPkgJsonPath, 'utf8')); - const entries = Object.entries(pkg.exports as Record).filter( + const entries = Object.entries(readExports()).filter( ([key, entry]) => (key === './test' || key.startsWith('./test/')) && - (entry.types || (isConditionObject(entry.import) && entry.import.types)), + isObjectValue(entry) && + (entry.types || (isObjectValue(entry.import) && entry.import.types)), ); const source = entries @@ -240,12 +253,13 @@ const invalidClick: UserEventClickOptions = { force: 'yes' }; const source = program.getSourceFile(file); expect(source, file).toBeDefined(); for (const specifier of source!.imports) { - if (isStringLiteral(specifier) && specifier.text.startsWith('.')) { - expect( - checker.getSymbolAtLocation(specifier)?.declarations?.length, - `${path.relative(directory, file)}: ${specifier.text}`, - ).toBeGreaterThan(0); + if (!isStringLiteral(specifier) || !specifier.text.startsWith('.')) { + continue; } + expect( + checker.getSymbolAtLocation(specifier)?.declarations?.length, + `${path.relative(directory, file)}: ${specifier.text}`, + ).toBeGreaterThan(0); } } }); @@ -254,8 +268,7 @@ const invalidClick: UserEventClickOptions = { force: 'yes' }; it.each(['coverage', 'reporters', 'environments', 'snapshot'])( 'does not publish the removed %s alias', (name) => { - const pkg = JSON.parse(fs.readFileSync(cliPkgJsonPath, 'utf8')); - expect(pkg.exports).not.toHaveProperty(`./test/${name}`); + expect(readExports()).not.toHaveProperty(`./test/${name}`); expect(() => requireFromHere.resolve(`vite-plus/test/${name}`)).toThrow( expect.objectContaining({ code: 'ERR_PACKAGE_PATH_NOT_EXPORTED' }), ); @@ -273,13 +286,12 @@ const invalidClick: UserEventClickOptions = { force: 'yes' }; }); it('every dual-condition entry emits `require` before `default`', () => { - const pkg = JSON.parse(fs.readFileSync(cliPkgJsonPath, 'utf-8')); - const exports = pkg.exports as Record; + const exports = readExports(); - const offenders: Array<{ path: string; order: string[] }> = []; + const offenders: Array<{ path: string; order: Array }> = []; - function walk(subpath: string, value: unknown) { - if (!isConditionObject(value)) { + function walk(subpath: string, value: JsonValue | undefined) { + if (!isObjectValue(value)) { return; } const keys = Object.keys(value); @@ -340,13 +352,11 @@ const invalidClick: UserEventClickOptions = { force: 'yes' }; it('browser-playwright declaration uses NodeNext-compatible relative specifiers', () => { // Matches quoted relative module specifiers such as './node' and '../browser.js'. const relativeModuleSpecifier = /(['"])(\.\.?\/[^'"]+)\1/g; - const pkg = JSON.parse(fs.readFileSync(cliPkgJsonPath, 'utf-8')); - const entry = (pkg.exports as Record)['./test/browser-playwright']; - expect(isConditionObject(entry)).toBe(true); - const types = (entry as ExportConditions).types; - expect(types).toBeTypeOf('string'); - - const source = fs.readFileSync(path.resolve(cliPkgDir, types as string), 'utf-8'); + const entry = readExports()['./test/browser-playwright']; + assert(isObjectValue(entry)); + const { types } = entry; + assert(typeof types === 'string'); + const source = fs.readFileSync(path.resolve(cliPkgDir, types), 'utf8'); const relativeSpecifiers = Array.from( source.matchAll(relativeModuleSpecifier), (match) => match[2], @@ -369,13 +379,11 @@ describe('Oxlint JS-plugin authoring entrypoints', () => { import('vite-plus/lint/plugins'), import('@oxlint/plugins'), ]); - const expected = namedValueExports(oxlintPlugins); + const expected = namedValueExports(Object.keys(oxlintPlugins)); expect(expected.length, 'sanity: @oxlint/plugins should expose value exports').toBeGreaterThan( 0, ); - const missing = expected.filter( - (key) => !(key in lintPlugins) || (lintPlugins as Record)[key] === undefined, - ); + const missing = missingExports(expected, Object.entries(lintPlugins)); expect(missing, '@oxlint/plugins value exports missing from vite-plus/lint/plugins').toEqual( [], ); @@ -385,7 +393,7 @@ describe('Oxlint JS-plugin authoring entrypoints', () => { // A `.cts` plugin, or a `.ts` one compiled with `module: commonjs`, emits // its import as `require()`. `@oxlint/plugins` ships CJS, so the shim does // too. `plugins-dev` instead exposes its ESM entry to both module systems. - const plugins = requireFromHere('vite-plus/lint/plugins') as Record; + const plugins = requireFromHere('vite-plus/lint/plugins'); expect(plugins.defineRule).toBeTypeOf('function'); expect(plugins.definePlugin).toBeTypeOf('function'); }); @@ -397,8 +405,8 @@ describe('Oxlint JS-plugin authoring entrypoints', () => { it('serves the same RuleTester to CommonJS', async () => { // Static imports in .cts files compile to require() after migration. - const ruleTester = requireFromHere('vite-plus/lint/plugins-dev') as Record; - const upstream = requireFromHere('oxlint/plugins-dev') as Record; + const ruleTester = requireFromHere('vite-plus/lint/plugins-dev'); + const upstream = requireFromHere('oxlint/plugins-dev'); const esm = await import('vite-plus/lint/plugins-dev'); expect(ruleTester.RuleTester).toBeTypeOf('function'); expect(ruleTester.RuleTester).toBe(upstream.RuleTester); @@ -431,22 +439,20 @@ describe('vite-plus root re-exports the full vitest/config surface', () => { import('vite-plus'), import('vitest/config'), ]); - const expected = namedValueExports(vitestConfig); + const expected = namedValueExports(Object.keys(vitestConfig)); expect(expected.length, 'sanity: vitest/config should expose value exports').toBeGreaterThan(0); - const missing = expected.filter( - (key) => !(key in vitePlus) || (vitePlus as Record)[key] === undefined, - ); + const missing = missingExports(expected, Object.entries(vitePlus)); expect(missing, 'vitest/config value exports missing from the ESM vite-plus root').toEqual([]); }); it('exposes every vitest/config value export on the CJS vite-plus root', () => { // `require('vitest/config')` -> `require('vite-plus')` resolves the package // root's `require` condition (the index.cts build), a separate manual list. - const vitePlus = requireFromHere('vite-plus') as Record; - const vitestConfig = requireFromHere('vitest/config') as Record; - const expected = namedValueExports(vitestConfig); + const vitePlus = requireFromHere('vite-plus'); + const vitestConfig = requireFromHere('vitest/config'); + const expected = namedValueExports(Object.keys(vitestConfig)); expect(expected.length, 'sanity: vitest/config should expose value exports').toBeGreaterThan(0); - const missing = expected.filter((key) => !(key in vitePlus) || vitePlus[key] === undefined); + const missing = missingExports(expected, Object.entries(vitePlus)); expect(missing, 'vitest/config value exports missing from the CJS vite-plus root').toEqual([]); }); }); diff --git a/packages/cli/src/__tests__/index.spec.ts b/packages/cli/src/__tests__/index.spec.ts index 49e1aa9ef6..64ecaf7350 100644 --- a/packages/cli/src/__tests__/index.spec.ts +++ b/packages/cli/src/__tests__/index.spec.ts @@ -2,7 +2,7 @@ import type { PluginOption } from 'vite'; import { afterEach, beforeEach, expect, test, vi } from 'vitest'; import { withConfigMetadataResolution } from '../define-config.ts'; -import { defineConfig, lazyPlugins } from '../index.js'; +import { defineConfig, lazyPlugins } from '../index.ts'; let originalMetadataEnv: string | undefined; @@ -31,14 +31,14 @@ test('lazyPlugins executes the callback by default', () => { test('lazyPlugins returns undefined during a config-metadata resolution', () => { process.env.VP_RESOLVING_CONFIG_METADATA = '1'; - const cb = vi.fn(() => [{ name: 'my-plugin' }]); + const cb = vi.fn<() => Array>(() => [{ name: 'my-plugin' }]); const result = lazyPlugins(cb); expect(result).toBeUndefined(); expect(cb).not.toHaveBeenCalled(); }); test('withConfigMetadataResolution skips plugins during the resolution and restores after', async () => { - const cb = vi.fn(() => [{ name: 'my-plugin' }]); + const cb = vi.fn<() => Array>(() => [{ name: 'my-plugin' }]); let during: ReturnType; const returned = await withConfigMetadataResolution(async () => { during = lazyPlugins(cb); @@ -112,13 +112,16 @@ const RESOLVER_PLUGIN_NAME = 'vite-plus:vitest-resolver'; const AUTO_INLINE_PLUGIN_NAME = 'vite-plus:auto-inline-matcher-deps'; const COVERAGE_GUARD_PLUGIN_NAME = 'vite-plus:coverage-version-guard'; const CACHE_PATHS_PLUGIN_NAME = 'vite-plus:vitest-cache-paths'; -const userPlugins = (plugins: unknown): unknown[] => { +const userPlugins = (plugins: unknown): Array => { expect(Array.isArray(plugins)).toBe(true); - const arr = plugins as unknown[]; - expect((arr[0] as { name?: string })?.name).toBe(RESOLVER_PLUGIN_NAME); - expect((arr[1] as { name?: string })?.name).toBe(AUTO_INLINE_PLUGIN_NAME); - expect((arr[2] as { name?: string })?.name).toBe(COVERAGE_GUARD_PLUGIN_NAME); - expect((arr[3] as { name?: string })?.name).toBe(CACHE_PATHS_PLUGIN_NAME); + if (!Array.isArray(plugins)) { + throw new TypeError('Expected a plugin array'); + } + const arr: Array = plugins; + expect(arr[0]).toHaveProperty('name', RESOLVER_PLUGIN_NAME); + expect(arr[1]).toHaveProperty('name', AUTO_INLINE_PLUGIN_NAME); + expect(arr[2]).toHaveProperty('name', COVERAGE_GUARD_PLUGIN_NAME); + expect(arr[3]).toHaveProperty('name', CACHE_PATHS_PLUGIN_NAME); return arr.slice(4); }; @@ -164,13 +167,13 @@ test('lazyPlugins with vitest configureVitest plugin satisfies plugins field', ( }); const userOnly = userPlugins(config.plugins); expect(userOnly.length).toBe(1); - expect((userOnly[0] as { name: string })?.name).toBe('vitest-plugin'); + expect(userOnly[0]).toHaveProperty('name', 'vitest-plugin'); }); // defineConfig compatibility tests test('defineConfig supports mixed PluginOption types in array', () => { - const plugins: PluginOption[] = [ + const plugins: Array = [ { name: 'sync-plugin' }, false, Promise.resolve({ name: 'promised-plugin' }), diff --git a/packages/cli/src/__tests__/init-config.spec.ts b/packages/cli/src/__tests__/init-config.spec.ts index 071378b6d4..6668e0473b 100644 --- a/packages/cli/src/__tests__/init-config.spec.ts +++ b/packages/cli/src/__tests__/init-config.spec.ts @@ -5,9 +5,9 @@ import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; import { vi } from 'vitest'; -import { applyToolInitConfigToViteConfig, inspectInitCommand } from '../init-config.js'; +import { applyToolInitConfigToViteConfig, inspectInitCommand } from '../init-config.ts'; -const tempDirs: string[] = []; +const tempDirs: Array = []; const originalVpCliBin = process.env.VP_CLI_BIN; function createTempDir() { diff --git a/packages/cli/src/__tests__/install-lockfile.spec.ts b/packages/cli/src/__tests__/install-lockfile.spec.ts index f95445734d..f03be8c302 100644 --- a/packages/cli/src/__tests__/install-lockfile.spec.ts +++ b/packages/cli/src/__tests__/install-lockfile.spec.ts @@ -61,12 +61,14 @@ describe('release installation lockfile', () => { NPM_CONFIG_PEERS_SUFFIX_MAX_LENGTH: '1000', }); // A repository workspace lockfile cannot be reused for this wrapper. - await expect(access(join(directory, 'pnpm-lock.yaml'))).rejects.toThrow(); + await expect(access(join(directory, 'pnpm-lock.yaml'))).rejects.toMatchObject({ + code: 'ENOENT', + }); await writeFile(join(directory, 'pnpm-lock.yaml'), lockfile); }, ); expect(result).toBe(lockfile); - await expect(access(temporary)).rejects.toThrow(); + await expect(access(temporary)).rejects.toMatchObject({ code: 'ENOENT' }); const rust = await readFile( new URL('../../../../crates/vp_setup/src/install.rs', import.meta.url), 'utf8', @@ -88,7 +90,7 @@ describe('release installation lockfile', () => { throw new Error('registry unavailable'); }), ).rejects.toThrow('registry unavailable'); - await expect(access(temporary)).rejects.toThrow(); + await expect(access(temporary)).rejects.toMatchObject({ code: 'ENOENT' }); }); it('rejects a lockfile for a different wrapper or without the CLI integrity', () => { diff --git a/packages/cli/src/__tests__/installation-publishing.spec.ts b/packages/cli/src/__tests__/installation-publishing.spec.ts index 23a38fbc4a..f41746ae22 100644 --- a/packages/cli/src/__tests__/installation-publishing.spec.ts +++ b/packages/cli/src/__tests__/installation-publishing.spec.ts @@ -14,16 +14,17 @@ interface Step { } interface Job { - steps: Step[]; - needs?: string | string[]; + steps: Array; + needs?: string | Array; permissions?: Record; environment?: string; } async function workflow(name: string): Promise<{ jobs: Record }> { - return parse( + const workflow: { jobs: Record } = parse( await readFile(new URL(`../../../../.github/workflows/${name}.yml`, import.meta.url), 'utf8'), ); + return workflow; } function bridge(job: Job): Step { @@ -57,29 +58,34 @@ describe('installation publishing order', () => { async (state) => { const { steps } = (await workflow('release')).jobs.Release; const check = steps.find((step) => step.id === 'github-release')!; - const getReleaseByTag = vi.fn(async () => { + const getReleaseByTag = vi.fn< + (request: { + owner: string; + repo: string; + tag: string; + }) => Promise<{ data: { draft: boolean } }> + >(async () => { if (state === 'missing' || state === 'unavailable') { throw Object.assign(new Error(state), { status: state === 'missing' ? 404 : 503 }); } return { data: { draft: state === 'draft' } }; }); - const setOutput = vi.fn(); - const result = runInNewContext(`(async () => { ${check.with!.script} })()`, { + const setOutput = vi.fn<(name: string, value: string) => void>(); + const result: Promise = runInNewContext(`(async () => { ${check.with!.script} })()`, { github: { rest: { repos: { getReleaseByTag } } }, context: { repo: { owner: 'voidzero-dev', repo: 'vite-plus' } }, core: { setOutput }, process: { env: { VERSION: '1.4.0' } }, - }) as Promise; - if (state === 'unavailable') { - await expect(result).rejects.toThrow('unavailable'); - expect(setOutput).not.toHaveBeenCalled(); - } else { - await result; - expect(setOutput).toHaveBeenCalledExactlyOnceWith( - 'published', - String(state === 'published'), - ); - } + }); + const failure = await result.then( + () => undefined, + (error: unknown) => error, + ); + const unavailable = Object.assign(new Error('unavailable'), { status: 503 }); + expect(failure).toEqual(state === 'unavailable' ? unavailable : undefined); + expect(setOutput.mock.calls).toEqual( + state === 'unavailable' ? [] : [['published', String(state === 'published')]], + ); expect(getReleaseByTag).toHaveBeenCalledExactlyOnceWith({ owner: 'voidzero-dev', repo: 'vite-plus', diff --git a/packages/cli/src/__tests__/js-command-args.spec.ts b/packages/cli/src/__tests__/js-command-args.spec.ts index 4cc3140457..6a08c13082 100644 --- a/packages/cli/src/__tests__/js-command-args.spec.ts +++ b/packages/cli/src/__tests__/js-command-args.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; +import type { CliParseError } from '../../binding/index.js'; import { - type CliParseError, parseConfigArgs, parseCreateArgs, parseHooksArgs, diff --git a/packages/cli/src/__tests__/oxlint-plugin.spec.ts b/packages/cli/src/__tests__/oxlint-plugin.spec.ts index 6f39dd75dd..34acac6d23 100644 --- a/packages/cli/src/__tests__/oxlint-plugin.spec.ts +++ b/packages/cli/src/__tests__/oxlint-plugin.spec.ts @@ -11,8 +11,8 @@ import { PREFER_VITE_PLUS_IMPORTS_RULE, PREFER_VITE_PLUS_IMPORTS_RULE_NAME, VITE_PLUS_OXLINT_PLUGIN_SPECIFIER, -} from '../oxlint-plugin-config.js'; -import { preferVitePlusImportsRule, rewriteVitePlusImportSpecifier } from '../oxlint-plugin.js'; +} from '../oxlint-plugin-config.ts'; +import { preferVitePlusImportsRule, rewriteVitePlusImportSpecifier } from '../oxlint-plugin.ts'; const nuxtTestFilename = path.join( import.meta.dirname, @@ -190,7 +190,7 @@ describe('rewriteVitePlusImportSpecifier', () => { }); }); -function checkImports(filename: string, preservedSpecifiers: readonly string[]): void { +function checkImports(filename: string, preservedSpecifiers: ReadonlyArray): void { const tests: RuleTester.TestCases = { valid: [], invalid: [] }; for (const [specifier, binding, replacement] of [ ['vitest', 'expect', 'vite-plus/test'], diff --git a/packages/cli/src/__tests__/pack.spec.ts b/packages/cli/src/__tests__/pack.spec.ts index f8e66b5c4a..a202fe58dc 100644 --- a/packages/cli/src/__tests__/pack.spec.ts +++ b/packages/cli/src/__tests__/pack.spec.ts @@ -2,9 +2,10 @@ import { expect, test } from 'vitest'; // `vite-plus/pack` re-exports the tsdown build bundled into core, so it must keep tsdown's runtime API. test('exposes every tsdown value export from vite-plus/pack', async () => { - const [pack, tsdown] = await Promise.all([import('../pack.js'), import('tsdown')]); + const [pack, tsdown] = await Promise.all([import('../pack.ts'), import('tsdown')]); const expected = Object.keys(tsdown).filter((key) => key !== 'default'); expect(expected.length, 'sanity: tsdown should expose value exports').toBeGreaterThan(0); - const missing = expected.filter((key) => (pack as Record)[key] === undefined); + const available = new Map(Object.entries(pack)); + const missing = expected.filter((key) => available.get(key) === undefined); expect(missing, 'tsdown value exports missing from vite-plus/pack').toEqual([]); }); diff --git a/packages/cli/src/__tests__/preview-install-lockfile.spec.ts b/packages/cli/src/__tests__/preview-install-lockfile.spec.ts index c43ce054ac..87d6237270 100644 --- a/packages/cli/src/__tests__/preview-install-lockfile.spec.ts +++ b/packages/cli/src/__tests__/preview-install-lockfile.spec.ts @@ -6,6 +6,10 @@ import { createTarGzip, parseTarGzip } from 'nanotar'; import { describe, expect, it, vi } from 'vitest'; import { stringify } from 'yaml'; +import type { + generateInstallLockfile as generateInstallLockfileImplementation, + publishedInstallLockfile as publishedInstallLockfileImplementation, +} from '../../generate-install-lockfile.ts'; import { INSTALL_LOCKFILE, PREVIEW_REGISTRY, @@ -71,7 +75,9 @@ async function withBatch(run: (directory: string) => Promise) { describe('preview installation lockfile', () => { it('resolves the published commit version and bundles the unchanged pnpm lockfile', async () => { await withBatch(async (directory) => { - const resolveLockfile = vi.fn(async () => lockfile); + const resolveLockfile = vi.fn( + async () => lockfile, + ); expect( await preparePreviewPackages(directory, version, resolveLockfile, noPublishedLockfile), ).toBe(lockfile); @@ -122,7 +128,9 @@ describe('preview installation lockfile', () => { { name: 'package/package.json', data: JSON.stringify({ name: 'vite-plus', version }) }, ]); await writeFile(join(directory, 'pkg-2.tgz'), archive); - const resolveLockfile = vi.fn(async () => lockfile); + const resolveLockfile = vi.fn( + async () => lockfile, + ); await expect( preparePreviewPackages(directory, version, resolveLockfile, noPublishedLockfile), ).rejects.toThrow('Expected unique global CLI platform packages'); @@ -159,8 +167,12 @@ describe('preview installation lockfile', () => { it('reuses the published lockfile after a partial publication without a saved artifact', async () => { await withBatch(async (directory) => { - const resolveLockfile = vi.fn(async () => lockfile.replace('published-cli', 'new-cli')); - const recoverLockfile = vi.fn(async () => lockfile); + const resolveLockfile = vi.fn(async () => + lockfile.replace('published-cli', 'new-cli'), + ); + const recoverLockfile = vi.fn( + async () => lockfile, + ); expect( await preparePreviewPackages(directory, version, resolveLockfile, recoverLockfile), ).toBe(lockfile); @@ -180,7 +192,9 @@ describe('preview installation lockfile', () => { it('does not resolve again when recovery of an existing publication fails', async () => { await withBatch(async (directory) => { const before = await readFile(join(directory, 'pkg-0.tgz')); - const resolveLockfile = vi.fn(async () => lockfile); + const resolveLockfile = vi.fn( + async () => lockfile, + ); await expect( preparePreviewPackages(directory, version, resolveLockfile, async () => { throw new Error('registry unavailable'); diff --git a/packages/cli/src/__tests__/publish-native-addons.spec.ts b/packages/cli/src/__tests__/publish-native-addons.spec.ts index e424249427..09ba943b73 100644 --- a/packages/cli/src/__tests__/publish-native-addons.spec.ts +++ b/packages/cli/src/__tests__/publish-native-addons.spec.ts @@ -1,18 +1,26 @@ +import type { + chmodSync as chmodSyncImplementation, + mkdirSync as mkdirSyncImplementation, + rmSync as rmSyncImplementation, +} from 'node:fs'; import { copyFileSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { afterEach, beforeEach, expect, test, vi } from 'vite-plus/test'; import { publishNpmPackageFromEnv } from '../../../../.github/scripts/publish-npm-package.ts'; +import type { waitForNpmPackagesFromEnv as waitForNpmPackagesFromEnvImplementation } from '../../../../.github/scripts/wait-for-npm-packages.ts'; +import type { validateInstallLockfile as validateInstallLockfileImplementation } from '../../generate-install-lockfile.ts'; +import type { editJsonFile as editJsonFileImplementation } from '../utils/json.ts'; vi.mock('node:fs', () => ({ - copyFileSync: vi.fn(), + copyFileSync: vi.fn(), existsSync: (path: string) => !path.endsWith('rust-cli-artifacts'), - chmodSync: vi.fn(), - mkdirSync: vi.fn(), - readFileSync: vi.fn(), - rmSync: vi.fn(), - writeFileSync: vi.fn(), + chmodSync: vi.fn(), + mkdirSync: vi.fn(), + readFileSync: vi.fn(), + rmSync: vi.fn(), + writeFileSync: vi.fn(), })); vi.mock('node:fs/promises', () => ({ readdir: async () => [] })); vi.mock('@napi-rs/cli', () => ({ @@ -29,7 +37,7 @@ vi.mock('../../package.json', () => ({ }, })); vi.mock('../utils/json.ts', () => ({ - editJsonFile: vi.fn(), + editJsonFile: vi.fn(), readJsonFile: () => ({ version: '1.4.0', optionalDependencies: { '@voidzero-dev/vite-plus-darwin-arm64': '1.4.0' }, @@ -37,13 +45,13 @@ vi.mock('../utils/json.ts', () => ({ })); vi.mock('../../generate-install-lockfile.ts', () => ({ INSTALL_LOCKFILE: 'vp-install-lock.yaml', - validateInstallLockfile: vi.fn(), + validateInstallLockfile: vi.fn(), })); vi.mock('../../../../.github/scripts/publish-npm-package.ts', () => ({ - publishNpmPackageFromEnv: vi.fn(async () => 'published'), + publishNpmPackageFromEnv: vi.fn(async () => 'published'), })); vi.mock('../../../../.github/scripts/wait-for-npm-packages.ts', () => ({ - waitForNpmPackagesFromEnv: vi.fn(), + waitForNpmPackagesFromEnv: vi.fn(), })); const originalArgv = process.argv; @@ -78,21 +86,23 @@ test.each([ expect(writeFileSync).toHaveBeenCalledOnce(); const [path, contents] = vi.mocked(writeFileSync).mock.calls[0]; expect(path).toEqual(expect.stringContaining(join('cli-npm', 'darwin-arm64', 'package.json'))); - expect(JSON.parse(contents as string)).toMatchObject({ + if (typeof contents !== 'string') { + throw new TypeError('Expected package.json text'); + } + expect(JSON.parse(contents)).toMatchObject({ name: '@voidzero-dev/vite-plus-cli-darwin-arm64', version: '1.4.0', vpNodeVersion: nodeVersion, }); - if (mode === 'npm') { - expect(publishNpmPackageFromEnv).toHaveBeenCalledWith( - expect.objectContaining({ vpNodeVersion: nodeVersion }), - 'npm', - expect.any(Array), - expect.any(String), - ); - } else { - expect(publishNpmPackageFromEnv).not.toHaveBeenCalled(); - } + const expectedCall = [ + expect.objectContaining({ vpNodeVersion: nodeVersion }), + 'npm', + expect.any(Array), + expect.any(String), + ]; + expect(vi.mocked(publishNpmPackageFromEnv).mock.calls).toEqual( + mode === 'npm' ? [expectedCall] : [], + ); }); test.each(['', 'lts', '24', '24.22', 'v24.22.1', '024.22.1', '24.22.1-rc.1', '24.22.1+build'])( diff --git a/packages/cli/src/__tests__/resolve-config-from-file.spec.ts b/packages/cli/src/__tests__/resolve-config-from-file.spec.ts index 3c0afc0860..6e0f562c70 100644 --- a/packages/cli/src/__tests__/resolve-config-from-file.spec.ts +++ b/packages/cli/src/__tests__/resolve-config-from-file.spec.ts @@ -10,7 +10,7 @@ import { promisify } from 'node:util'; import { normalizePath } from 'vite'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { resolveConfigFromFile } from '../index.js'; +import { resolveConfigFromFile } from '../index.ts'; let tempDir: string; const exec = promisify(execFile); @@ -327,20 +327,22 @@ export default ${exportValue};\n`, } // Start outside Vitest's NODE_ENV=test and cached Vite Task client state. - await exec( - process.execPath, - [ - '--input-type=module', - '--eval', - `import assert from 'node:assert/strict'; + await expect( + exec( + process.execPath, + [ + '--input-type=module', + '--eval', + `import assert from 'node:assert/strict'; import { resolveConfigFromFile } from ${JSON.stringify(new URL('../define-config.ts', import.meta.url).href)}; const first = await resolveConfigFromFile(${JSON.stringify(configFile)}); const second = await resolveConfigFromFile(${JSON.stringify(configFile)}); assert.equal(first.nodeEnv, ${JSON.stringify(expected)}); assert.equal(second.nodeEnv, ${JSON.stringify(expected)});`, - ], - { env, cwd: tempDir }, - ); + ], + { env, cwd: tempDir }, + ), + ).resolves.toBeDefined(); }, ); @@ -412,12 +414,13 @@ export default defineConfig({ });\n`, ); - await exec( - process.execPath, - [ - '--input-type=module', - '--eval', - `import assert from 'node:assert/strict'; + await expect( + exec( + process.execPath, + [ + '--input-type=module', + '--eval', + `import assert from 'node:assert/strict'; import { realpathSync } from 'node:fs'; import { createRequire } from 'node:module'; const api = ${loadApi}; @@ -440,8 +443,9 @@ for (const rootBase of [cwd, '']) { } assert.equal(process.cwd(), cwd); assert.equal(process.env.VP_RESOLVING_CONFIG_METADATA, marker);`, - ], - { cwd: launcher }, - ); + ], + { cwd: launcher }, + ), + ).resolves.toBeDefined(); }); }); diff --git a/packages/cli/src/__tests__/resolve-core.spec.ts b/packages/cli/src/__tests__/resolve-core.spec.ts index 948938944a..17464e27e0 100644 --- a/packages/cli/src/__tests__/resolve-core.spec.ts +++ b/packages/cli/src/__tests__/resolve-core.spec.ts @@ -8,12 +8,13 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import corePkg from '../../../core/package.json' with { type: 'json' }; import cliPkg from '../../package.json' with { type: 'json' }; import { resolveCore } from '../resolve-core.ts'; +import type { JsonObject } from '../utils/json-value.ts'; // The core version encodes the bundled Vite version, so it differs from the // CLI version (rfcs/core-version-alignment.md). const CORE_VERSION = corePkg.version; -function writePackageJson(directory: string, manifest: Record): void { +function writePackageJson(directory: string, manifest: JsonObject): void { mkdirSync(directory, { recursive: true }); writeFileSync(join(directory, 'package.json'), JSON.stringify(manifest)); } @@ -159,17 +160,19 @@ describe('resolveCore', () => { rmSync(bundled, { recursive: true }); // pnpm injects NODE_PATH, which can supply an unrelated Vite package. // Check the missing dependency in a process without global search paths. - execFileSync(process.execPath, [ - '--no-global-search-paths', - '--input-type=module', - '--eval', - `import { strict as assert } from 'node:assert'; + expect(() => + execFileSync(process.execPath, [ + '--no-global-search-paths', + '--input-type=module', + '--eval', + `import { strict as assert } from 'node:assert'; import { resolveCore } from ${JSON.stringify(new URL('../resolve-core.ts', import.meta.url).href)}; assert.throws( () => resolveCore('', ${JSON.stringify(project)}, ${JSON.stringify(cliModule)}), /Could not resolve the bundled Vite/, );`, - ]); + ]), + ).not.toThrow(); }); it.each(['project', 'bundled'])('rejects upstream Vite in the %s dependency', (location) => { @@ -191,6 +194,6 @@ describe('resolveCore', () => { it('reports a missing core subpath instead of selecting a project copy', () => { writeCore(projectCore); rmSync(join(bundled, 'pack.js')); - expect(() => resolveCore('/pack', project, cliModule)).toThrow(); + expect(() => resolveCore('/pack', project, cliModule)).toThrow(/pack/); }); }); diff --git a/packages/cli/src/__tests__/resolve-lint.spec.ts b/packages/cli/src/__tests__/resolve-lint.spec.ts index 97eedefa40..ae2ff1e279 100644 --- a/packages/cli/src/__tests__/resolve-lint.spec.ts +++ b/packages/cli/src/__tests__/resolve-lint.spec.ts @@ -2,7 +2,7 @@ import { existsSync } from 'node:fs'; import { describe, expect, it, vi } from 'vitest'; -import { lint, resolveWindowsLintBackendExecutable } from '../resolve-lint.js'; +import { lint, resolveWindowsLintBackendExecutable } from '../resolve-lint.ts'; describe('resolve-lint', () => { it('should resolve binPath and OXLINT_TSGOLINT_PATH to existing files', async () => { @@ -24,11 +24,10 @@ describe('resolve-lint', () => { }); it('should keep the Windows tsrs-lint executable path absolute', () => { - const backendPath = - 'C:\\repo\\node_modules\\.pnpm\\vite-plus@0.1.24\\node_modules\\vite-plus\\node_modules\\.bin\\tsrs-lint.cmd'; + const backendPath = String.raw`C:\repo\node_modules\.pnpm\vite-plus@0.1.24\node_modules\vite-plus\node_modules\.bin\tsrs-lint.cmd`; const result = resolveWindowsLintBackendExecutable( [ - 'C:\\repo\\node_modules\\.pnpm\\vite-plus@0.1.24\\node_modules\\vite-plus\\node_modules\\.bin\\tsrs-lint.exe', + String.raw`C:\repo\node_modules\.pnpm\vite-plus@0.1.24\node_modules\vite-plus\node_modules\.bin\tsrs-lint.exe`, backendPath, ], { @@ -41,8 +40,13 @@ describe('resolve-lint', () => { }); it('prefers the executable wrapper without resolving Bun paths', () => { - const candidates = ['C:\\repo\\.bin\\tsrs-lint.exe', 'C:\\repo\\.bin\\tsrs-lint.cmd']; - const getRealpathCandidates = vi.fn(() => ['C:\\cache\\.bin\\tsrs-lint.exe']); + const candidates = [ + String.raw`C:\repo\.bin\tsrs-lint.exe`, + String.raw`C:\repo\.bin\tsrs-lint.cmd`, + ]; + const getRealpathCandidates = vi.fn<() => Array>(() => [ + String.raw`C:\cache\.bin\tsrs-lint.exe`, + ]); expect( resolveWindowsLintBackendExecutable(candidates, { @@ -54,10 +58,10 @@ describe('resolve-lint', () => { }); it('resolves a Bun wrapper when the symlinked paths do not exist', () => { - const backendPath = 'C:\\repo\\node_modules\\.bun\\tsrs\\node_modules\\.bin\\tsrs-lint.exe'; + const backendPath = String.raw`C:\repo\node_modules\.bun\tsrs\node_modules\.bin\tsrs-lint.exe`; expect( - resolveWindowsLintBackendExecutable(['C:\\repo\\.bin\\tsrs-lint.exe'], { + resolveWindowsLintBackendExecutable([String.raw`C:\repo\.bin\tsrs-lint.exe`], { exists: (path) => path === backendPath, getRealpathCandidates: () => [backendPath], }), @@ -74,7 +78,10 @@ describe('resolve-lint', () => { }, }, ])('reports the original candidates when the fallback is $name', ({ getRealpathCandidates }) => { - const candidates = ['C:\\repo\\.bin\\tsrs-lint.exe', 'C:\\repo\\.bin\\tsrs-lint.cmd']; + const candidates = [ + String.raw`C:\repo\.bin\tsrs-lint.exe`, + String.raw`C:\repo\.bin\tsrs-lint.cmd`, + ]; expect(() => resolveWindowsLintBackendExecutable(candidates, { diff --git a/packages/cli/src/__tests__/resolve-test.spec.ts b/packages/cli/src/__tests__/resolve-test.spec.ts index f5acc13f30..ff731bb098 100644 --- a/packages/cli/src/__tests__/resolve-test.spec.ts +++ b/packages/cli/src/__tests__/resolve-test.spec.ts @@ -4,8 +4,8 @@ import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { test } from '../resolve-test.js'; -import { resolve, resolveBundled } from '../utils/constants.js'; +import { test } from '../resolve-test.ts'; +import { resolve, resolveBundled } from '../utils/constants.ts'; describe('resolve-test', () => { it('resolves a vitest binary that exists', async () => { diff --git a/packages/cli/src/__tests__/resolve-vite-config.spec.ts b/packages/cli/src/__tests__/resolve-vite-config.spec.ts index 11ed35ee35..6be0cf9ad5 100644 --- a/packages/cli/src/__tests__/resolve-vite-config.spec.ts +++ b/packages/cli/src/__tests__/resolve-vite-config.spec.ts @@ -7,7 +7,7 @@ import path from 'node:path'; import { normalizePath } from 'vite'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { findViteConfigUp, resolveViteConfig } from '../resolve-vite-config.js'; +import { findViteConfigUp, resolveViteConfig } from '../resolve-vite-config.ts'; let tempDir: string; diff --git a/packages/cli/src/__tests__/staged/config.spec.ts b/packages/cli/src/__tests__/staged/config.spec.ts index b686b2fc05..1d655d67f2 100644 --- a/packages/cli/src/__tests__/staged/config.spec.ts +++ b/packages/cli/src/__tests__/staged/config.spec.ts @@ -1,6 +1,6 @@ import { assertType, describe, it } from 'vitest'; -import type { StagedConfig } from '../../staged-config.js'; +import type { StagedConfig } from '../../staged-config.ts'; describe('StagedConfig type', () => { it('accepts string commands', () => { @@ -17,13 +17,13 @@ describe('StagedConfig type', () => { it('accepts sync generate task functions', () => { assertType({ - '*.ts': (files: readonly string[]) => `eslint ${files.join(' ')}`, + '*.ts': (files: ReadonlyArray) => `eslint ${files.join(' ')}`, }); }); it('accepts async generate task functions', () => { assertType({ - '*.ts': async (files: readonly string[]) => `eslint ${files.join(' ')}`, + '*.ts': async (files: ReadonlyArray) => `eslint ${files.join(' ')}`, }); }); @@ -42,14 +42,14 @@ describe('StagedConfig type', () => { assertType({ '*.ts': { title: 'Run eslint', - task: (files: readonly string[]) => { - assertType(files); + task: (files: ReadonlyArray) => { + assertType>(files); }, }, }); }); it('accepts a top-level generate task function', () => { - assertType((files: readonly string[]) => [`eslint ${files.join(' ')}`]); + assertType((files: ReadonlyArray) => [`eslint ${files.join(' ')}`]); }); }); diff --git a/packages/cli/src/__tests__/toolchain.spec.ts b/packages/cli/src/__tests__/toolchain.spec.ts index c1dc6ab535..c99b467cc0 100644 --- a/packages/cli/src/__tests__/toolchain.spec.ts +++ b/packages/cli/src/__tests__/toolchain.spec.ts @@ -1,19 +1,14 @@ import fs from 'node:fs'; import path from 'node:path'; -import url from 'node:url'; import { describe, expect, it } from 'vitest'; -import type { ToolchainManifest } from '../../dist/toolchain.js'; - -const cliPkgDir = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), '../..'); +const cliPkgDir = path.resolve(import.meta.dirname, '../..'); const distDir = path.join(cliPkgDir, 'dist'); describe('toolchain export', () => { it('exports the same manifest as the JSON artifact', async () => { - const json = JSON.parse( - fs.readFileSync(path.join(distDir, 'toolchain.json'), 'utf8'), - ) as ToolchainManifest; + const json: unknown = JSON.parse(fs.readFileSync(path.join(distDir, 'toolchain.json'), 'utf8')); const module = await import('../../dist/toolchain.js'); expect(module.toolchain).toEqual(json); @@ -52,7 +47,7 @@ describe('toolchain export', () => { const sourceDateEpoch = process.env.SOURCE_DATE_EPOCH; const expectedBuildTime = sourceDateEpoch !== undefined - ? new Date(Number(sourceDateEpoch) * 1_000).toISOString().replace(/\.\d{3}Z$/, 'Z') + ? new Date(Number(sourceDateEpoch) * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z') : fs.existsSync(nativeBuildTimePath) ? fs.readFileSync(nativeBuildTimePath, 'utf8').trim() : undefined; diff --git a/packages/cli/src/__tests__/tsconfig.spec.ts b/packages/cli/src/__tests__/tsconfig.spec.ts index 4cdeb45be5..4f333affd4 100644 --- a/packages/cli/src/__tests__/tsconfig.spec.ts +++ b/packages/cli/src/__tests__/tsconfig.spec.ts @@ -8,9 +8,9 @@ import { findTsconfigFilesWithBaseUrl, fixBaseUrlInTsconfig, hasBaseUrlInTsconfig, -} from '../utils/tsconfig.js'; +} from '../utils/tsconfig.ts'; -const tempDirs: string[] = []; +const tempDirs: Array = []; const originalVpCliBin = process.env.VP_CLI_BIN; function createTempDir() { @@ -162,7 +162,10 @@ fs.writeFileSync(tsconfigPath, text.replace(/\\n\\s*"baseUrl": "\\.",?/, '')); await expect(fixBaseUrlInTsconfig(projectPath)).resolves.toBe('fixed'); - const invocations = JSON.parse(fs.readFileSync(invocationsPath, 'utf8')) as string[]; + const invocations: unknown = JSON.parse(fs.readFileSync(invocationsPath, 'utf8')); + if (!Array.isArray(invocations)) { + throw new TypeError('Expected an invocation list'); + } expect(new Set(invocations)).toEqual(new Set(['tsconfig.app.json', 'tsconfig.node.json'])); expect(invocations).toHaveLength(2); expect(hasBaseUrlInTsconfig(projectPath)).toBe(false); diff --git a/packages/cli/src/__tests__/versions.spec.ts b/packages/cli/src/__tests__/versions.spec.ts index 999e089cd9..bc18a542a3 100644 --- a/packages/cli/src/__tests__/versions.spec.ts +++ b/packages/cli/src/__tests__/versions.spec.ts @@ -1,18 +1,20 @@ +import fs from 'node:fs'; +import { createRequire } from 'node:module'; +import path from 'node:path'; + +import { globSync } from 'tinyglobby'; +import { assert, describe, expect, it } from 'vitest'; + +import { isObjectValue } from '../utils/json-value.ts'; /** * Verify that the vite-plus/versions export works correctly. * * Tests run against the already-built dist/ directory, ensuring * that syncToolchainExports() produces correct artifacts. */ -import fs from 'node:fs'; -import { createRequire } from 'node:module'; -import path from 'node:path'; -import url from 'node:url'; - -import { globSync } from 'tinyglobby'; -import { describe, expect, it } from 'vitest'; +import { readJsonFile } from '../utils/json.ts'; -const cliPkgDir = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), '../..'); +const cliPkgDir = path.resolve(import.meta.dirname, '../..'); const distDir = path.join(cliPkgDir, 'dist'); const corePkgPath = path.join(cliPkgDir, '../core/package.json'); const require = createRequire(import.meta.url); @@ -20,12 +22,12 @@ const require = createRequire(import.meta.url); describe('versions export', () => { describe('build artifacts', () => { it('dist/versions.js should export a versions object', () => { - const content = fs.readFileSync(path.join(distDir, 'versions.js'), 'utf-8'); + const content = fs.readFileSync(path.join(distDir, 'versions.js'), 'utf8'); expect(content).toContain('export const versions'); }); it('dist/versions.d.ts should declare a versions type', () => { - const content = fs.readFileSync(path.join(distDir, 'versions.d.ts'), 'utf-8'); + const content = fs.readFileSync(path.join(distDir, 'versions.d.ts'), 'utf8'); expect(content).toContain('export declare const versions'); }); }); @@ -46,10 +48,10 @@ describe('versions export', () => { const RELATIVE_VERSIONS_IMPORT = /import\(\s*(['"])(\.\.?\/[^'"]*versions\.js)\1\s*\)/g; it('every relative `import(... versions.js)` in dist resolves to an existing file', () => { - const offenders: string[] = []; + const offenders: Array = []; let matchCount = 0; for (const file of globSync('**/*.js', { cwd: distDir, absolute: true })) { - const content = fs.readFileSync(file, 'utf-8'); + const content = fs.readFileSync(file, 'utf8'); for (const match of content.matchAll(RELATIVE_VERSIONS_IMPORT)) { matchCount++; const target = path.resolve(path.dirname(file), match[2]); @@ -72,19 +74,18 @@ describe('versions export', () => { describe('bundledVersions consistency', () => { it('should contain all core bundledVersions', async () => { - const corePkg = JSON.parse(fs.readFileSync(corePkgPath, 'utf-8')); + const corePkg = readJsonFile(corePkgPath); + assert(isObjectValue(corePkg.bundledVersions)); const mod = await import('../../dist/versions.js'); const versions = mod.versions as Record; - for (const [key, value] of Object.entries( - corePkg.bundledVersions as Record, - )) { + for (const [key, value] of Object.entries(corePkg.bundledVersions)) { expect(versions[key], `versions.${key} should match core bundledVersions`).toBe(value); } }); it.each(['vitest', 'tsrs'] as const)('should match the installed %s version', async (name) => { const pkgPath = require.resolve(`${name}/package.json`); - const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')); + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); const mod = await import('../../dist/versions.js'); const versions = mod.versions as Record; expect(versions[name], `versions.${name} should match installed ${name} version`).toBe( @@ -95,7 +96,7 @@ describe('versions export', () => { describe('type declarations', () => { it('should declare every runtime field as a readonly string', async () => { - const content = fs.readFileSync(path.join(distDir, 'versions.d.ts'), 'utf-8'); + const content = fs.readFileSync(path.join(distDir, 'versions.d.ts'), 'utf8'); const { versions } = await import('../../dist/versions.js'); const fields = Array.from( content.matchAll(/readonly '([^']+)': string;/g), diff --git a/packages/cli/src/__tests__/vpx-script.spec.ts b/packages/cli/src/__tests__/vpx-script.spec.ts index 9040cd4cd5..daf2522cfe 100644 --- a/packages/cli/src/__tests__/vpx-script.spec.ts +++ b/packages/cli/src/__tests__/vpx-script.spec.ts @@ -30,7 +30,7 @@ import { WATCH_OPTIONS_WITH_VALUE, } from '../vpx-script.ts'; -const dirs: string[] = []; +const dirs: Array = []; function project(files: Record): string { const dir = mkdtempSync(path.join(tmpdir(), 'vpx-script-')); @@ -52,25 +52,28 @@ afterEach(() => { interface DetectionCase { name: string; files?: Record; - args: string[]; - expect: 'package' | { error: string } | { script: string[]; tsconfig?: string; watch?: true }; + args: Array; + expect: + | 'package' + | { error: string } + | { script: Array; tsconfig?: string; watch?: true }; } const detectionTable: { - scriptExtensions: string[]; - nodeOptionsWithValue: string[]; - nodeOptionsWithoutEntry: string[]; - watchOptionsWithValue: string[]; - packageSpecs: { spec: string; versioned: boolean; command: string }[]; - explicitPrograms: { + scriptExtensions: Array; + nodeOptionsWithValue: Array; + nodeOptionsWithoutEntry: Array; + watchOptionsWithValue: Array; + packageSpecs: Array<{ spec: string; versioned: boolean; command: string }>; + explicitPrograms: Array<{ name: string; files?: Record; - executable?: string[]; + executable?: Array; token: string; unixOnly?: boolean; expect: 'ok' | { error: string; note?: string }; - }[]; - cases: DetectionCase[]; + }>; + cases: Array; } = JSON.parse( readFileSync( path.join( @@ -85,23 +88,35 @@ describe('detectScript', () => { // The global CLI runs the same cases (`vpx_script.rs`), so both decide the same way. it.each(detectionTable.cases)('$name', ({ files = {}, args, expect: expected }) => { const cwd = project(files); - const fill = (values: string[]) => values.map((value) => value.replaceAll('{cwd}', cwd)); - if (expected === 'package') { - expect(detectScript(fill(args), cwd)).toBeUndefined(); - } else if ('error' in expected) { - expect(() => detectScript(fill(args), cwd)).toThrow(new ScriptError(expected.error)); - } else { + const fill = (values: Array) => values.map((value) => value.replaceAll('{cwd}', cwd)); + const detect = () => { const result = detectScript(fill(args), cwd); - expect({ - nodeArgs: result?.nodeArgs, - tsconfig: result?.tsconfig, - watch: result?.watch ?? false, - }).toEqual({ - nodeArgs: fill(expected.script), - tsconfig: expected.tsconfig, - watch: expected.watch ?? false, - }); - } + return ( + result && { + nodeArgs: result.nodeArgs, + tsconfig: result.tsconfig, + watch: result.watch ?? false, + } + ); + }; + const outcome = () => { + try { + return detect(); + } catch (error) { + return error; + } + }; + expect(outcome()).toEqual( + expected === 'package' + ? undefined + : 'error' in expected + ? new ScriptError(expected.error) + : { + nodeArgs: fill(expected.script), + tsconfig: expected.tsconfig, + watch: expected.watch ?? false, + }, + ); }); it('declares the lists the global CLI declares', () => { @@ -140,9 +155,13 @@ describe('parseVpxArgs', () => { }); }); -function runPackage(args: string[], cwd: string) { +function runPackage(args: Array, cwd: string) { const { flags, positional } = parseVpxArgs(args); - return packageInvocation(flags, positional as [string, ...string[]], cwd); + const [first, ...rest] = positional; + if (first === undefined) { + throw new Error('Expected a package argument'); + } + return packageInvocation(flags, [first, ...rest], cwd); } describe('checkExplicitProgram', () => { @@ -339,6 +358,6 @@ describe('script hooks', () => { ); expect(withRequireAsyncModuleCode(tla)).toMatchObject({ code: 'ERR_REQUIRE_ASYNC_MODULE' }); const other = new Error('Failed to parse /x/a.ts'); - expect((withRequireAsyncModuleCode(other) as NodeJS.ErrnoException).code).toBeUndefined(); + expect(withRequireAsyncModuleCode(other)).not.toHaveProperty('code'); }); }); diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts index e830b67354..08b0152a1b 100644 --- a/packages/cli/src/bin.ts +++ b/packages/cli/src/bin.ts @@ -9,12 +9,12 @@ * vite-plus installation using oxc_resolver and runs its dist/bin.js directly. * If no local installation is found, this global dist/bin.js is used as fallback. */ - import path from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; +import { pathToFileURL } from 'node:url'; import { isMainThread } from 'node:worker_threads'; -import { type DevCommand, ensureBlockingStdio, run } from '../binding/index.js'; +import type { DevCommand } from '../binding/index.js'; +import { ensureBlockingStdio, run } from '../binding/index.js'; import { maybePrintCommandHelp } from './help.ts'; import { applyToolInitConfigToViteConfig, inspectInitCommand } from './init-config.ts'; import { doc } from './resolve-doc.ts'; @@ -23,6 +23,8 @@ import { lint } from './resolve-lint.ts'; import { pack } from './resolve-pack.ts'; import { test } from './resolve-test.ts'; import { vite } from './resolve-vite.ts'; +import { errorMessage } from './utils/error.ts'; +import { setBlocking } from './utils/stdio.ts'; import { accent, errorMsg, log } from './utils/terminal.ts'; import { setUserAgent } from './utils/user-agent.ts'; @@ -30,14 +32,9 @@ setUserAgent(); // Node.js sets O_NONBLOCK when pipe-backed stdio is first accessed. Materialize // the output streams before restoring the blocking semantics expected by Rust. -Reflect.get(process, 'stdout'); -Reflect.get(process, 'stderr'); +const { stdout, stderr } = process; ensureBlockingStdio(); -interface StdioStream { - _handle?: { setBlocking?: (blocking: boolean) => number }; -} - /** * Loading a config through Vite imports `node:process` as ESM, and building that * namespace reads every `process` getter, so `process.stdin` is created and its @@ -50,20 +47,7 @@ function restoreBlockingStdin(): void { if (process.platform === 'win32') { return; } - /* oxlint-disable-next-line no-underscore-dangle -- Node.js has no public API for this */ - (process.stdin as StdioStream)._handle?.setBlocking?.(true); -} - -function getErrorMessage(err: unknown): string { - if (err instanceof Error) { - return err.message; - } - - if (typeof err === 'object' && err && 'message' in err && typeof err.message === 'string') { - return err.message; - } - - return String(err); + setBlocking(process.stdin, true); } /** @@ -78,10 +62,9 @@ async function runInProcess(command: DevCommand): Promise { // Vite writes through this process's stdio. Let pipe writes queue, as they // do when Vite opens its own stdio, so a slow reader cannot stall the server. if (process.platform !== 'win32') { - for (const stream of [process.stdout, process.stderr]) { + for (const stream of [stdout, stderr]) { if (!stream.isTTY) { - /* oxlint-disable-next-line no-underscore-dangle -- Node.js has no public API for this */ - (stream as StdioStream)._handle?.setBlocking?.(false); + setBlocking(stream, false); } } } @@ -114,12 +97,13 @@ if (args[0]?.startsWith('-C')) { // through one catchable path. try { process.chdir(target); - } catch (err) { - const code = typeof err === 'object' && err !== null && 'code' in err ? err.code : undefined; + } catch (error) { + const code = + typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined; if (code === 'ENOENT' || code === 'ENOTDIR') { errorMsg(`directory not found: ${dir}`); } else { - errorMsg(`cannot change directory to ${dir}: ${getErrorMessage(err)}`); + errorMsg(`cannot change directory to ${dir}: ${errorMessage(error)}`); } process.exit(1); } @@ -153,7 +137,7 @@ if (args[0] === 'help' && args[1]) { } const command = args[0]; -const cliDistDir = path.dirname(fileURLToPath(import.meta.url)); +const cliDistDir = import.meta.dirname; const vitePlusPackagePath = path.dirname(cliDistDir); if (maybePrintCommandHelp(args)) { @@ -240,8 +224,8 @@ if (maybePrintCommandHelp(args)) { `Skipped initialization: '${accent(result.configKey)}' already exists in '${accent(path.basename(result.viteConfigPath))}'.`, ); } - } catch (err) { - console.error('[Vite+] Failed to initialize config in vite.config.ts:', err); + } catch (error) { + console.error('[Vite+] Failed to initialize config in vite.config.ts:', error); finalExitCode = 1; } } @@ -252,8 +236,8 @@ if (maybePrintCommandHelp(args)) { } else { process.exit(finalExitCode); } - } catch (err) { - errorMsg(getErrorMessage(err)); + } catch (error) { + errorMsg(errorMessage(error)); process.exit(1); } } diff --git a/packages/cli/src/config/__tests__/bin.spec.ts b/packages/cli/src/config/__tests__/bin.spec.ts index 497444119b..be9158c9ec 100644 --- a/packages/cli/src/config/__tests__/bin.spec.ts +++ b/packages/cli/src/config/__tests__/bin.spec.ts @@ -1,24 +1,49 @@ import { beforeEach, expect, it, vi } from 'vitest'; +import type { parseConfigArgs as parseConfigArgsImplementation } from '../../../binding/index.js'; +import type { updateExistingAgentInstructions as updateExistingAgentInstructionsImplementation } from '../../utils/agent.ts'; +import type { + defaultInteractive as defaultInteractiveImplementation, + promptGitHooks as promptGitHooksImplementation, +} from '../../utils/prompts.ts'; +import type { + log as logImplementation, + printHeader as printHeaderImplementation, +} from '../../utils/terminal.ts'; +import type { + install as installImplementation, + isGitHooksEnvDisabled as isGitHooksEnvDisabledImplementation, + isHooksUserDisabled as isHooksUserDisabledImplementation, + resolveHooksLocation as resolveHooksLocationImplementation, +} from '../hooks.ts'; + const hooks = vi.hoisted(() => ({ - install: vi.fn(() => ({ message: '', isError: false })), - isGitHooksEnvDisabled: vi.fn(() => true), - isHooksUserDisabled: vi.fn(() => false), - resolveHooksLocation: vi.fn((): unknown => { + install: vi.fn(() => ({ message: '', isError: false })), + isGitHooksEnvDisabled: vi.fn(() => true), + isHooksUserDisabled: vi.fn(() => false), + resolveHooksLocation: vi.fn(() => { throw new Error('git command not found'); }), })); -const terminal = vi.hoisted(() => ({ log: vi.fn(), printHeader: vi.fn() })); +const terminal = vi.hoisted(() => ({ + log: vi.fn(), + printHeader: vi.fn(), +})); const binding = vi.hoisted(() => ({ - parseConfigArgs: vi.fn(() => ({ status: 'ok', value: { agent: false } })), + parseConfigArgs: vi.fn(() => ({ + status: 'ok', + value: { agent: false }, + })), })); const prompts = vi.hoisted(() => ({ - defaultInteractive: vi.fn(() => false), - promptGitHooks: vi.fn(async () => true), + defaultInteractive: vi.fn(() => false), + promptGitHooks: vi.fn(async () => true), })); vi.mock('../../../binding/index.js', () => binding); -vi.mock('../../utils/agent.ts', () => ({ updateExistingAgentInstructions: vi.fn() })); +vi.mock('../../utils/agent.ts', () => ({ + updateExistingAgentInstructions: vi.fn(), +})); vi.mock('../../utils/prompts.ts', () => prompts); vi.mock('../../utils/terminal.ts', () => terminal); vi.mock('../hooks.ts', () => hooks); diff --git a/packages/cli/src/config/__tests__/hooks.spec.ts b/packages/cli/src/config/__tests__/hooks.spec.ts index db2dace1c0..1ef129181d 100644 --- a/packages/cli/src/config/__tests__/hooks.spec.ts +++ b/packages/cli/src/config/__tests__/hooks.spec.ts @@ -29,7 +29,7 @@ import { isHooksUserDisabled, resolveHooksDir, status, -} from '../hooks.js'; +} from '../hooks.ts'; // Unmodified upstream dispatcher; retained to verify safe migration against real Husky output. const HUSKY_DISPATCHER = readFileSync(new URL('./fixtures/husky-9.1.7/h', import.meta.url), 'utf8'); @@ -37,7 +37,7 @@ const HUSKY_DISPATCHER = readFileSync(new URL('./fixtures/husky-9.1.7/h', import function runCommit( cwd: string, message = 'test', - ...gitOptions: string[] + ...gitOptions: Array ): SpawnSyncReturns { return spawnSync( 'git', @@ -221,7 +221,7 @@ describe('install', () => { writeFileSync(join(tmp, 'package.json'), manifest); const internal = join(tmp, '.husky', '_'); mkdirSync(internal, { recursive: true }); - const files: Record = { + const files = { h: HUSKY_DISPATCHER.replaceAll('\n', newline), 'husky.sh': readFileSync( new URL('./fixtures/husky-9.1.7/husky.sh', import.meta.url), @@ -583,9 +583,13 @@ describe('install', () => { } expect(install().isError).toBe(false); - if (scenario !== 'disabled hooks') { - expect(enable(undefined, { replaceHusky: true }).message).toContain('skipping'); - } + const enableMessage = + scenario === 'disabled hooks' + ? undefined + : enable(undefined, { replaceHusky: true }).message; + expect(enableMessage?.includes('skipping')).toBe( + scenario === 'disabled hooks' ? undefined : true, + ); expect( execFileSync('git', ['config', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim(), ).toBe(hooksPath); @@ -807,7 +811,9 @@ describe('install', () => { isError: false, }); expect(readFileSync(externalFile, 'utf8')).toBe('keep me\n'); - expect(() => execSync('git config --local --get core.hooksPath', { cwd: tmp })).toThrow(); + expect(() => execSync('git config --local --get core.hooksPath', { cwd: tmp })).toThrow( + /Command failed: git config/, + ); } finally { process.chdir(originalCwd); rmSync(tmp, { recursive: true, force: true }); @@ -833,7 +839,9 @@ describe('install', () => { isError: false, }); expect(readFileSync(externalFile, 'utf8')).toBe('keep me\n'); - expect(() => execSync('git config --local --get core.hooksPath', { cwd: tmp })).toThrow(); + expect(() => execSync('git config --local --get core.hooksPath', { cwd: tmp })).toThrow( + /Command failed: git config/, + ); } finally { process.chdir(originalCwd); rmSync(tmp, { recursive: true, force: true }); @@ -890,7 +898,9 @@ describe('enable / disable / status', () => { expect(disabled.message).toContain('Git hooks disabled'); expect(existsSync(join(tmp, hooksDir, '_'))).toBe(false); expect(existsSync(join(tmp, hooksDir, 'pre-commit'))).toBe(true); - expect(() => execSync('git config --get core.hooksPath', { cwd: tmp })).toThrow(); + expect(() => execSync('git config --get core.hooksPath', { cwd: tmp })).toThrow( + /Command failed: git config/, + ); expect(isHooksUserDisabled()).toBe(true); // install (as vp config would) respects the preference @@ -928,9 +938,9 @@ describe('enable / disable / status', () => { expect(enable().isError).toBe(false); expect(isHooksUserDisabled()).toBe(false); - expect(() => - execSync('git config --local --get vp.hooks.disabled', { cwd: tmp }), - ).toThrow(); + expect(() => execSync('git config --local --get vp.hooks.disabled', { cwd: tmp })).toThrow( + /Command failed: git config/, + ); } finally { process.chdir(originalCwd); rmSync(tmp, { recursive: true, force: true }); @@ -1094,7 +1104,9 @@ describe('enable / disable / status', () => { expect(result.isError).toBe(false); expect(result.message).toContain('unset core.hooksPath'); expect(existsSync(join(tmp, '.vite-hooks', '_'))).toBe(false); - expect(() => execSync('git config --get core.hooksPath', { cwd: tmp })).toThrow(); + expect(() => execSync('git config --get core.hooksPath', { cwd: tmp })).toThrow( + /Command failed: git config/, + ); } finally { process.chdir(originalCwd); rmSync(tmp, { recursive: true, force: true }); @@ -1130,7 +1142,9 @@ describe('enable / disable / status', () => { expect(result.message).toContain('unset core.hooksPath'); expect(existsSync(join(tmp, '.vite-hooks', '_'))).toBe(false); expect(existsSync(join(tmp, 'pkg', '.vite-hooks'))).toBe(false); - expect(() => execSync('git config --get core.hooksPath', { cwd: tmp })).toThrow(); + expect(() => execSync('git config --get core.hooksPath', { cwd: tmp })).toThrow( + /Command failed: git config/, + ); expect(isHooksUserDisabled()).toBe(true); expect( execSync('git config --local --get vp.hooks.prefix', { cwd: tmp }).toString().trim(), @@ -1164,7 +1178,9 @@ describe('enable / disable / status', () => { expect(result.isError).toBe(false); expect(existsSync(join(tmp, '.vite-hooks', '_'))).toBe(false); expect(existsSync(join(tmp, 'pkg', '.vite-hooks'))).toBe(false); - expect(() => execSync('git config --get core.hooksPath', { cwd: tmp })).toThrow(); + expect(() => execSync('git config --get core.hooksPath', { cwd: tmp })).toThrow( + /Command failed: git config/, + ); expect(isHooksUserDisabled()).toBe(true); } finally { process.chdir(originalCwd); @@ -1193,7 +1209,9 @@ describe('enable / disable / status', () => { const result = disable(); expect(result.isError).toBe(false); expect(existsSync(join(tmp, 'pkg', '.vite-hooks', '_'))).toBe(false); - expect(() => execSync('git config --get core.hooksPath', { cwd: tmp })).toThrow(); + expect(() => execSync('git config --get core.hooksPath', { cwd: tmp })).toThrow( + /Command failed: git config/, + ); } finally { process.chdir(originalCwd); rmSync(tmp, { recursive: true, force: true }); @@ -1219,7 +1237,9 @@ describe('enable / disable / status', () => { expect(result.isError).toBe(false); expect(isHooksUserDisabled()).toBe(true); expect(existsSync(join(tmp, '.vite-hooks', '_'))).toBe(false); - expect(() => execSync('git config --local --get core.hooksPath', { cwd: tmp })).toThrow(); + expect(() => execSync('git config --local --get core.hooksPath', { cwd: tmp })).toThrow( + /Command failed: git config/, + ); expect( execSync('git config --worktree --get core.hooksPath', { cwd: tmp }).toString().trim(), ).toBe('.husky/_'); @@ -1255,9 +1275,9 @@ describe('enable / disable / status', () => { expect( execSync('git config --local --get core.hooksPath', { cwd: tmp }).toString().trim(), ).toBe('.husky/_'); - expect(() => - execSync('git config --worktree --get core.hooksPath', { cwd: tmp }), - ).toThrow(); + expect(() => execSync('git config --worktree --get core.hooksPath', { cwd: tmp })).toThrow( + /Command failed: git config/, + ); expect(execSync('git config --get core.hooksPath', { cwd: tmp }).toString().trim()).toBe( '.husky/_', ); @@ -1329,14 +1349,14 @@ describe('hookScript', () => { }); it.skipIf(process.platform !== 'win32')('should handle Windows separators in nested dirs', () => { - const withWindowsSeparators = hookScript('.config\\husky'); + const withWindowsSeparators = hookScript(String.raw`.config\husky`); const withPosixSeparators = hookScript('.config/husky'); expect(countDirnameCalls(withWindowsSeparators)).toBe(countDirnameCalls(withPosixSeparators)); expect(countDirnameCalls(withWindowsSeparators)).toBe(4); }); it.skipIf(process.platform === 'win32')('treats a backslash as a literal POSIX filename', () => { - expect(countDirnameCalls(hookScript('.config\\husky'))).toBe(3); + expect(countDirnameCalls(hookScript(String.raw`.config\husky`))).toBe(3); }); it.skipIf(process.platform === 'win32').each([undefined, 'vp-home'])( diff --git a/packages/cli/src/config/bin.ts b/packages/cli/src/config/bin.ts index eecb7517c0..93a81a7096 100644 --- a/packages/cli/src/config/bin.ts +++ b/packages/cli/src/config/bin.ts @@ -87,4 +87,4 @@ async function main() { } } -void main(); +await main(); diff --git a/packages/cli/src/config/hooks.ts b/packages/cli/src/config/hooks.ts index 4f6df917d0..db249256de 100644 --- a/packages/cli/src/config/hooks.ts +++ b/packages/cli/src/config/hooks.ts @@ -5,13 +5,14 @@ import { lstatSync, mkdirSync, readdirSync, - readFileSync, realpathSync, rmSync, writeFileSync, } from 'node:fs'; import { isAbsolute, join, normalize, relative, resolve, sep } from 'node:path'; +import { readJsonFile } from '../utils/json.ts'; + export const SUPPORTED_GIT_HOOK_NAMES = [ 'pre-commit', 'pre-merge-commit', @@ -113,8 +114,8 @@ export interface HooksStatus { hooksPath: string | null; ownsHooksPath: boolean; dispatcherInstalled: boolean; - projectHooks: string[]; - lines: string[]; + projectHooks: Array; + lines: Array; } export function normalizeHooksPath(hooksPath: string): string { @@ -125,9 +126,9 @@ export function normalizeHooksPath(hooksPath: string): string { return normalized; } -function gitRevParse(...flags: string[]): string | InstallResult { +function gitRevParse(...flags: Array): string | InstallResult { const result = spawnSync('git', ['rev-parse', ...flags]); - if (result.status == null) { + if (result.status === null || result.status === undefined) { return { message: 'git command not found', isError: true }; } if (result.status !== 0) { @@ -244,7 +245,7 @@ function gitConfigLocalMissing(key: string): boolean { // Git 2.37+ keeps the low 8 bits on every platform, so -1 becomes 255. Older Git for // Windows can keep the full 32-bit value. // https://github.com/git/git/blob/47fdf2208c5b94c8cc01c106b8f7c85efb91c926/common-exit.c#L14-L20 -const GIT_CONFIG_LOCK_STATUSES: ReadonlySet = new Set([255, 0xffffffff]); +const GIT_CONFIG_LOCK_STATUSES: ReadonlySet = new Set([255, 0xff_ff_ff_ff]); // Git 2.56+ retries the lock for `core.configLockTimeout` (1s by default) and older Git // does not retry. Turn off the Git retry so the wait below is the same on every version. @@ -262,10 +263,7 @@ function sleepSync(ms: number): void { // First runs in linked worktrees race for the shared lock. Every worktree writes // the same values, so wait and stop as soon as another run has applied ours. -function writeGitConfig( - args: string[], - isApplied: () => boolean, -): { status: number | null; stderr: string } { +function writeGitConfig(args: Array, isApplied: () => boolean) { const gitArgs = [...GIT_CONFIG_NO_LOCK_RETRY, ...args]; let result = spawnSync('git', gitArgs); for (const delay of GIT_CONFIG_LOCK_RETRY_DELAYS_MS) { @@ -281,14 +279,14 @@ function writeGitConfig( return { status: result.status, stderr: result.stderr?.toString().trim() ?? '' }; } -function gitConfigSet(key: string, value: string): { ok: boolean; error?: string } { +function gitConfigSet(key: string, value: string) { if (gitConfigLocalHas(key, value)) { return { ok: true }; } const result = writeGitConfig(['config', '--local', key, value], () => gitConfigLocalHas(key, value), ); - if (result.status == null) { + if (result.status === null || result.status === undefined) { return { ok: false, error: 'git command not found' }; } if (result.status !== 0) { @@ -297,14 +295,14 @@ function gitConfigSet(key: string, value: string): { ok: boolean; error?: string return { ok: true }; } -function gitConfigUnset(key: string): { ok: boolean; error?: string } { +function gitConfigUnset(key: string) { if (gitConfigLocalMissing(key)) { return { ok: true }; } const result = writeGitConfig(['config', '--local', '--unset-all', key], () => gitConfigLocalMissing(key), ); - if (result.status == null) { + if (result.status === null || result.status === undefined) { return { ok: false, error: 'git command not found' }; } // status 5 = key not found @@ -332,7 +330,7 @@ export function getStoredHooksDir(): string | null { function getStoredHooksPrefix(): string | null { const value = gitConfigGet(PREFERENCE_PREFIX_KEY, { local: true }); - if (value == null) { + if (value === null || value === undefined) { return null; } if (value === ROOT_PREFIX_TOKEN) { @@ -589,16 +587,18 @@ function getHuskyReplacement( } // Include ancestor manifests when hooks are configured from a workspace package. const relativeBase = relative(location.toplevel, location.baseDir); - const directories = [location.toplevel]; + let currentDirectory = location.toplevel; + const directories = [currentDirectory]; for (const segment of relativeBase.split(sep).filter(Boolean)) { - directories.push(join(directories.at(-1)!, segment)); + currentDirectory = join(currentDirectory, segment); + directories.push(currentDirectory); } for (const directory of directories) { const manifest = join(directory, 'package.json'); if (!existsSync(manifest)) { continue; } - const pkg = JSON.parse(readFileSync(manifest, 'utf8')) as Record; + const pkg = readJsonFile(manifest); if (!pkg || typeof pkg !== 'object' || Array.isArray(pkg) || 'husky' in pkg) { return null; } @@ -635,7 +635,7 @@ function getHuskyReplacement( function unsetScopedHooksPath(scope: 'local' | 'worktree'): InstallResult | null { const result = spawnSync('git', ['config', `--${scope}`, '--unset-all', 'core.hooksPath']); - if (result.status == null) { + if (result.status === null || result.status === undefined) { return { message: 'git command not found', isError: true }; } // status 5 = key not found at that scope @@ -860,8 +860,8 @@ export function disable(dir?: string): InstallResult { const foreignHooksPath = !!existingHooksPath && !hooksPathsEqual(existingHooksPath, location.target, location.toplevel); - const actions: string[] = []; - const notes: string[] = []; + const actions: Array = []; + const notes: Array = []; // Persist preference *before* teardown so a later unset/rm failure still // blocks prepare / `vp config` from reinstalling the dispatcher. @@ -923,7 +923,7 @@ export function status(dir?: string): InstallResult & { status?: HooksStatus } { const ownsHooksPath = !!existingHooksPath && hooksPathsEqual(existingHooksPath, location.target, location.toplevel); - let projectHooks: string[] = []; + let projectHooks: Array = []; const hooksDirPath = join(location.baseDir, location.dir); if (existsSync(hooksDirPath)) { try { diff --git a/packages/cli/src/create/__tests__/builtin.spec.ts b/packages/cli/src/create/__tests__/builtin.spec.ts index d63370f272..0104b9cbf7 100644 --- a/packages/cli/src/create/__tests__/builtin.spec.ts +++ b/packages/cli/src/create/__tests__/builtin.spec.ts @@ -1,33 +1,33 @@ import { describe, expect, it, vi } from 'vitest'; -import { executeBuiltinTemplate } from '../templates/builtin.js'; +import { executeBuiltinTemplate } from '../templates/builtin.ts'; +import type { runRemoteTemplateCommand as runRemoteTemplateCommandImplementation } from '../templates/remote.ts'; +import { makeWorkspaceInfo } from './workspace-fixture.ts'; -const { mockLogError } = vi.hoisted(() => ({ mockLogError: vi.fn() })); +const { mockLogError } = vi.hoisted(() => ({ mockLogError: vi.fn<(message: string) => void>() })); -vi.mock('../templates/remote.js', () => ({ - runRemoteTemplateCommand: vi.fn(), +vi.mock('../templates/remote.ts', () => ({ + runRemoteTemplateCommand: vi.fn(), })); vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ log: { error: mockLogError }, })); -const workspaceInfo = { - rootDir: '/tmp/workspace', -} as any; +const workspaceInfo = makeWorkspaceInfo('/tmp/workspace'); const baseTemplateInfo = { packageName: 'wage-meeting', targetDir: 'wage-meeting', args: [], envs: {}, - type: 'builtin' as any, + type: 'builtin' as const, interactive: false, }; describe('executeBuiltinTemplate', () => { it('returns exitCode 1 for unknown vite: template', async () => { - const { runRemoteTemplateCommand } = await import('../templates/remote.js'); + const { runRemoteTemplateCommand } = await import('../templates/remote.ts'); const result = await executeBuiltinTemplate(workspaceInfo, { ...baseTemplateInfo, @@ -47,7 +47,7 @@ describe('executeBuiltinTemplate', () => { }); expect(mockLogError).toHaveBeenCalledOnce(); - const message = mockLogError.mock.calls[0][0] as string; + const message = mockLogError.mock.calls[0][0]; expect(message).toContain('vite:unknown'); expect(message).toContain('vp create --list'); }); diff --git a/packages/cli/src/create/__tests__/command.spec.ts b/packages/cli/src/create/__tests__/command.spec.ts index 89c9fdb05e..bca4dc8dec 100644 --- a/packages/cli/src/create/__tests__/command.spec.ts +++ b/packages/cli/src/create/__tests__/command.spec.ts @@ -4,17 +4,19 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { runCommand as runCommandImplementation } from '../../../binding/index.js'; + const { mockRunCommand } = vi.hoisted(() => ({ - mockRunCommand: vi.fn(), + mockRunCommand: vi.fn(), })); vi.mock('../../../binding/index.js', () => ({ runCommand: mockRunCommand, })); -const { runCommandAndDetectProjectDir } = await import('../command.js'); +const { runCommandAndDetectProjectDir } = await import('../command.ts'); -const tempDirs: string[] = []; +const tempDirs: Array = []; function makeTempDir() { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-create-command-')); @@ -37,7 +39,7 @@ describe('runCommandAndDetectProjectDir', () => { mockRunCommand.mockResolvedValueOnce({ exitCode: 0, pathAccesses: { - 'package.json': { write: true }, + 'package.json': { read: false, write: true, readDir: false }, }, }); @@ -55,8 +57,8 @@ describe('runCommandAndDetectProjectDir', () => { mockRunCommand.mockResolvedValueOnce({ exitCode: 0, pathAccesses: { - 'package.json': { write: true }, - 'my-app/package.json': { write: true }, + 'package.json': { read: false, write: true, readDir: false }, + 'my-app/package.json': { read: false, write: true, readDir: false }, }, }); @@ -75,7 +77,7 @@ describe('runCommandAndDetectProjectDir', () => { mockRunCommand.mockResolvedValueOnce({ exitCode: 0, pathAccesses: { - 'package.json': { write: true }, + 'package.json': { read: false, write: true, readDir: false }, }, }); diff --git a/packages/cli/src/create/__tests__/discovery.spec.ts b/packages/cli/src/create/__tests__/discovery.spec.ts index 559faf2cc5..3350465228 100644 --- a/packages/cli/src/create/__tests__/discovery.spec.ts +++ b/packages/cli/src/create/__tests__/discovery.spec.ts @@ -4,14 +4,16 @@ import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; -import type { WorkspaceInfo, WorkspaceInfoOptional } from '../../types/index.js'; +import type { WorkspaceInfo, WorkspaceInfoOptional } from '../../types/index.ts'; +import type { JsonObject } from '../../utils/json-value.ts'; import { discoverTemplate, expandCreateShorthand, inferGitHubRepoName, inferParentDir, parseGitHubUrl, -} from '../discovery.js'; +} from '../discovery.ts'; +import { makeWorkspaceInfo } from './workspace-fixture.ts'; // The local-package branch only engages for a resolved create.templates entry. function discoverLocal(workspaceInfo: WorkspaceInfo) { @@ -27,20 +29,18 @@ describe('discoverTemplate', () => { } }); - function createWorkspaceWithPackage(packageJson: Record): WorkspaceInfo { + function createWorkspaceWithPackage(packageJson: JsonObject): WorkspaceInfo { rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-discovery-spec-')); const packageDir = path.join(rootDir, 'tools/my-template'); fs.mkdirSync(packageDir, { recursive: true }); fs.writeFileSync(path.join(packageDir, 'package.json'), JSON.stringify(packageJson)); - return { - rootDir, + return makeWorkspaceInfo(rootDir, { isMonorepo: true, monorepoScope: '', workspacePatterns: ['tools/*'], parentDirs: ['tools'], - downloadPackageManager: { binPrefix: '' }, packages: [{ name: 'my-template', path: 'tools/my-template' }], - } as unknown as WorkspaceInfo; + }); } it('runs a local bingo template through its bin entry', () => { @@ -162,10 +162,10 @@ describe('discoverTemplate', () => { // inferParentDir only reads parentDirs and packages off the workspace. function inferParentDirWorkspace( - parentDirs: string[], + parentDirs: Array, packages: WorkspaceInfoOptional['packages'] = [], ): WorkspaceInfoOptional { - return { parentDirs, packages } as unknown as WorkspaceInfoOptional; + return makeWorkspaceInfo('/workspace', { parentDirs, packages }); } describe('inferParentDir', () => { @@ -272,6 +272,13 @@ describe('expandCreateShorthand', () => { }); }); +function standaloneWorkspace(): WorkspaceInfo { + const workspace = makeWorkspaceInfo('/tmp/workspace', { isMonorepo: false }); + workspace.downloadPackageManager.binPrefix = '/tmp/bin'; + workspace.downloadPackageManager.version = '10.0.0'; + return workspace; +} + describe('GitHub template helpers', () => { it('should parse GitHub shorthand URLs', () => { expect(parseGitHubUrl('github:user/repo')).toBe('user/repo'); @@ -288,37 +295,18 @@ describe('GitHub template helpers', () => { }); it('should resolve GitHub templates to degit without reusing the original URL as destination', () => { - const template = discoverTemplate('https://github.com/nkzw-tech/fate-template', ['my-app'], { - rootDir: '/tmp/workspace', - isMonorepo: false, - monorepoScope: '', - workspacePatterns: [], - parentDirs: [], - packageManager: 'pnpm', - packageManagerVersion: 'latest', - downloadPackageManager: { - binPrefix: '/tmp/bin', - version: '10.0.0', - } as never, - packages: [], - }); + const template = discoverTemplate( + 'https://github.com/nkzw-tech/fate-template', + ['my-app'], + standaloneWorkspace(), + ); expect(template.command).toBe('degit'); expect(template.args).toEqual(['nkzw-tech/fate-template', 'my-app']); }); it('should keep manifest-resolved specifiers literal when skipShorthand=true', () => { - const workspace = { - rootDir: '/tmp/workspace', - isMonorepo: false, - monorepoScope: '', - workspacePatterns: [], - parentDirs: [], - packageManager: 'pnpm', - packageManagerVersion: 'latest', - downloadPackageManager: { binPrefix: '/tmp/bin', version: '10.0.0' } as never, - packages: [], - } as never; + const workspace = standaloneWorkspace(); // A manifest entry like `{ template: '@your-org/template-web' }` must // NOT be rewritten into `@your-org/create-template-web` by the create diff --git a/packages/cli/src/create/__tests__/generator-scaffold.spec.ts b/packages/cli/src/create/__tests__/generator-scaffold.spec.ts index f1020f3938..168359ce21 100644 --- a/packages/cli/src/create/__tests__/generator-scaffold.spec.ts +++ b/packages/cli/src/create/__tests__/generator-scaffold.spec.ts @@ -5,7 +5,9 @@ import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; import { stringify } from 'yaml'; -import { PackageManager, type WorkspaceInfo } from '../../types/index.ts'; +import type { WorkspaceInfo } from '../../types/index.ts'; +import { PackageManager } from '../../types/index.ts'; +import { isStringRecord } from '../../utils/json-value.ts'; import { readJsonFile } from '../../utils/json.ts'; import { templatesDir } from '../../utils/path.ts'; import { readYamlFile } from '../../utils/yaml.ts'; @@ -33,7 +35,8 @@ async function scaffold( JSON.stringify({ private: true, workspaces: ['tools/*'], - ...(packageManager === PackageManager.bun ? catalogs : {}), + catalog: packageManager === PackageManager.bun ? catalogs.catalog : undefined, + catalogs: packageManager === PackageManager.bun ? catalogs.catalogs : undefined, }), ); if (packageManager === PackageManager.pnpm) { @@ -88,7 +91,7 @@ describe('generator scaffold dependencies', () => { [PackageManager.bun, '1.3.0'], ])('uses installable versions for %s %s without catalog entries', async (manager, version) => { const pkg = await scaffold(manager, version); - const { catalog } = readYamlFile(path.join(templatesDir, 'monorepo/pnpm-workspace.yaml')); + const catalog = readYamlFile(path.join(templatesDir, 'monorepo/pnpm-workspace.yaml'))?.catalog; expect(pkg.devDependencies).toEqual(catalog); expect(pkg.name).toBe('my-generator'); const templatePkg = readJsonFile(path.join(templatesDir, 'generator/package.json')); @@ -112,9 +115,10 @@ describe('generator scaffold dependencies', () => { [PackageManager.bun, '1.3.0'], ])('fills only missing catalog dependencies for %s %s', async (manager, version) => { const pkg = await scaffold(manager, version, { catalog: { typescript: '^5' } }); - const { catalog } = readYamlFile(path.join(templatesDir, 'monorepo/pnpm-workspace.yaml')) as { - catalog: Record; - }; + const catalog = readYamlFile(path.join(templatesDir, 'monorepo/pnpm-workspace.yaml'))?.catalog; + if (!isStringRecord(catalog)) { + throw new Error('Missing template catalog'); + } expect(pkg.devDependencies).toEqual({ '@types/node': catalog['@types/node'], typescript: 'catalog:', @@ -132,7 +136,9 @@ describe('generator scaffold dependencies', () => { const pkg = await scaffold(manager, version, { catalogs: { default: { '@types/node': '^22', typescript: '^5' } }, }); - const { catalog } = readYamlFile(path.join(templatesDir, 'monorepo/pnpm-workspace.yaml')); + const catalog = readYamlFile( + path.join(templatesDir, 'monorepo/pnpm-workspace.yaml'), + )?.catalog; expect(pkg.devDependencies).toEqual( sharedDefault ? { '@types/node': 'catalog:', typescript: 'catalog:' } : catalog, ); diff --git a/packages/cli/src/create/__tests__/initial-template-options.spec.ts b/packages/cli/src/create/__tests__/initial-template-options.spec.ts index 352e33e401..104fac67ef 100644 --- a/packages/cli/src/create/__tests__/initial-template-options.spec.ts +++ b/packages/cli/src/create/__tests__/initial-template-options.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { getInitialTemplateOptions } from '../initial-template-options.js'; -import type { CreateTemplateEntry } from '../org-manifest.js'; +import { getInitialTemplateOptions } from '../initial-template-options.ts'; +import type { CreateTemplateEntry } from '../org-manifest.ts'; describe('getInitialTemplateOptions', () => { it('shows only built-in monorepo, application, and library options outside a monorepo', () => { @@ -40,7 +40,7 @@ describe('getInitialTemplateOptions', () => { }); it('lists local create.templates entries inside a monorepo, by name', () => { - const templates: CreateTemplateEntry[] = [ + const templates: Array = [ { name: 'component', description: 'Internal UI component', @@ -65,7 +65,7 @@ describe('getInitialTemplateOptions', () => { }); it('does not include local templates outside a monorepo', () => { - const templates: CreateTemplateEntry[] = [ + const templates: Array = [ { name: 'component', description: 'Internal UI component', template: 'component-generator' }, ]; diff --git a/packages/cli/src/create/__tests__/monorepo.spec.ts b/packages/cli/src/create/__tests__/monorepo.spec.ts index 68afb0fcdc..b115755242 100644 --- a/packages/cli/src/create/__tests__/monorepo.spec.ts +++ b/packages/cli/src/create/__tests__/monorepo.spec.ts @@ -4,12 +4,14 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { PackageManager } from '../../types/index.js'; +import { PackageManager } from '../../types/index.ts'; +import { isStringRecord } from '../../utils/json-value.ts'; +import { readJsonFile } from '../../utils/json.ts'; import { alignMonorepoTypeScriptVersion, dropAliasedRuntimeDevDeps, removeNestedLibraryToolConfig, -} from '../templates/monorepo.js'; +} from '../templates/monorepo.ts'; function writePackageJson(directory: string, devDependencies: Record): void { fs.writeFileSync( @@ -19,10 +21,14 @@ function writePackageJson(directory: string, devDependencies: Record { - const pkg = JSON.parse(fs.readFileSync(path.join(directory, 'package.json'), 'utf8')) as { - devDependencies?: Record; - }; - return pkg.devDependencies ?? {}; + const { devDependencies } = readJsonFile(path.join(directory, 'package.json')); + if (devDependencies === undefined) { + return {}; + } + if (!isStringRecord(devDependencies)) { + throw new Error('Invalid devDependencies'); + } + return devDependencies; } describe('alignMonorepoTypeScriptVersion', () => { @@ -282,10 +288,14 @@ describe('dropAliasedRuntimeDevDeps', () => { } function readDevDependencies(): Record { - const pkg = JSON.parse(fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf8')) as { - devDependencies?: Record; - }; - return pkg.devDependencies ?? {}; + const { devDependencies } = readJsonFile(path.join(tmpDir, 'package.json')); + if (devDependencies === undefined) { + return {}; + } + if (!isStringRecord(devDependencies)) { + throw new Error('Invalid devDependencies'); + } + return devDependencies; } // Regression test for "vp why vite reports the override as ineffective" in a diff --git a/packages/cli/src/create/__tests__/org-manifest.spec.ts b/packages/cli/src/create/__tests__/org-manifest.spec.ts index 7d014c5bf0..6c8cc0b2b7 100644 --- a/packages/cli/src/create/__tests__/org-manifest.spec.ts +++ b/packages/cli/src/create/__tests__/org-manifest.spec.ts @@ -3,6 +3,8 @@ import { createHash } from 'node:crypto'; import { createTarGzip } from 'nanotar'; import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { JsonObject } from '../../utils/json-value.ts'; +import type { OrgTemplateEntry } from '../org-manifest.ts'; import { CreateConfigSchemaError, filterManifestForContext, @@ -10,8 +12,7 @@ import { parseOrgScopedSpec, readOrgManifest, validateCreateTemplates, - type OrgTemplateEntry, -} from '../org-manifest.js'; +} from '../org-manifest.ts'; describe('validateCreateTemplates', () => { it('returns an empty array when create.templates is absent', () => { @@ -125,7 +126,7 @@ describe('parseOrgScopedSpec', () => { }); describe('filterManifestForContext', () => { - const templates: OrgTemplateEntry[] = [ + const templates: Array = [ { name: 'monorepo', description: 'root', template: './m', monorepo: true }, { name: 'web', description: 'web', template: './w' }, { name: 'library', description: 'lib', template: './l' }, @@ -143,11 +144,7 @@ describe('filterManifestForContext', () => { const TARBALL_URL = 'https://registry.npmjs.org/@your-org/create/-/create-1.0.0.tgz'; -function packument( - vpTemplates: unknown, - extra: Record = {}, - extraVersions: Record = {}, -) { +function packument(vpTemplates: unknown, extra: JsonObject = {}, extraVersions: JsonObject = {}) { return { name: '@your-org/create', 'dist-tags': { latest: '1.0.0' }, @@ -166,19 +163,13 @@ function packument( }; } -function mockFetchJson(body: unknown, status = 200): ReturnType { - return vi.spyOn(globalThis, 'fetch').mockResolvedValue({ - status, - ok: status >= 200 && status < 300, - async json() { - return body; - }, - } as unknown as Response); +function mockFetchJson(body: unknown, status = 200) { + return vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json(body, { status })); } /** Resolve the requested URL from any of `fetch`'s accepted input shapes. */ function requestUrl(input: string | URL | Request): string { - return typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + return typeof input === 'string' ? input : 'href' in input ? input.href : input.url; } /** A real npm-pack-shaped tarball containing only a package.json. */ @@ -195,10 +186,7 @@ async function tarballWith(packageJson: unknown): Promise { * Mock fetch to serve the packument for the registry URL and a real tarball * `Response` (with a streamable body) for the `.tgz` URL. */ -function mockFetchPackumentAndTarball( - packumentBody: unknown, - tarBytes: Uint8Array, -): ReturnType { +function mockFetchPackumentAndTarball(packumentBody: unknown, tarBytes: Uint8Array) { return vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { if (requestUrl(input).endsWith('.tgz')) { return new Response(tarBytes.slice().buffer, { status: 200 }); @@ -213,7 +201,7 @@ describe('readOrgManifest', () => { }); it('returns null on 404', async () => { - vi.spyOn(globalThis, 'fetch').mockResolvedValue({ status: 404, ok: false } as Response); + vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 404 })); expect(await readOrgManifest('@your-org')).toBeNull(); }); @@ -342,10 +330,7 @@ describe('readOrgManifest', () => { }); it('throws when the registry responds with a non-404 error', async () => { - vi.spyOn(globalThis, 'fetch').mockResolvedValue({ - status: 500, - ok: false, - } as Response); + vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 500 })); await expect(readOrgManifest('@your-org')).rejects.toThrow(/500/); }); @@ -405,24 +390,14 @@ describe('readOrgManifest', () => { const body = packument([{ name: 'a', description: 'a', template: '@a/a' }]); const mockFetch = vi .spyOn(globalThis, 'fetch') - .mockResolvedValueOnce({ status: 401, ok: false } as Response) - .mockResolvedValueOnce({ - status: 200, - ok: true, - async json() { - return body; - }, - } as unknown as Response); + .mockResolvedValueOnce(new Response(null, { status: 401 })) + .mockResolvedValueOnce(Response.json(body)); await readOrgManifest('@your-org'); expect(mockFetch).toHaveBeenCalledTimes(2); - const [, firstInit] = mockFetch.mock.calls[0] as [string, RequestInit]; - expect( - (firstInit.headers as Record | undefined)?.authorization, - ).toBeUndefined(); - const [, secondInit] = mockFetch.mock.calls[1] as [string, RequestInit]; - expect((secondInit.headers as Record).authorization).toBe( - 'Bearer SECRET-TOKEN', - ); + const [, firstInit] = mockFetch.mock.calls[0]; + expect(new Headers(firstInit?.headers).get('authorization')).toBeNull(); + const [, secondInit] = mockFetch.mock.calls[1]; + expect(new Headers(secondInit?.headers).get('authorization')).toBe('Bearer SECRET-TOKEN'); } finally { for (const [k, v] of Object.entries(originals)) { if (v === undefined) { @@ -438,8 +413,8 @@ describe('readOrgManifest', () => { const mockFetch = mockFetchJson(packument([{ name: 'a', description: 'a', template: '@a/a' }])); await readOrgManifest('@your-org'); expect(mockFetch).toHaveBeenCalledTimes(1); - const [, init] = mockFetch.mock.calls[0] as [string, RequestInit]; - expect((init.headers as Record).authorization).toBeUndefined(); + const [, init] = mockFetch.mock.calls[0]; + expect(new Headers(init?.headers).has('authorization')).toBe(false); }); it('resolves a pinned version instead of dist-tags.latest', async () => { diff --git a/packages/cli/src/create/__tests__/org-picker.spec.ts b/packages/cli/src/create/__tests__/org-picker.spec.ts index 01f7f866e9..e1729187e2 100644 --- a/packages/cli/src/create/__tests__/org-picker.spec.ts +++ b/packages/cli/src/create/__tests__/org-picker.spec.ts @@ -1,16 +1,19 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; -import type { OrgManifest } from '../org-manifest.js'; +import type { OrgManifest } from '../org-manifest.ts'; import { formatManifestTable, ORG_PICKER_BUILTIN_ESCAPE, ORG_PICKER_CANCEL, pickOrgTemplate, -} from '../org-picker.js'; +} from '../org-picker.ts'; const { mockSelect, mockIsCancel } = vi.hoisted(() => ({ - mockSelect: vi.fn(), - mockIsCancel: vi.fn((value: unknown) => value === '__cancel__'), + mockSelect: + vi.fn< + (options: { options: Array<{ label: string; value: string }> }) => Promise + >(), + mockIsCancel: vi.fn<(value: unknown) => boolean>((value: unknown) => value === '__cancel__'), })); vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ @@ -44,7 +47,7 @@ describe('pickOrgTemplate', () => { mockSelect.mockResolvedValue('web'); await pickOrgTemplate(manifest(), { isMonorepo: false }); const passedOptions = mockSelect.mock.calls[0][0].options; - expect(passedOptions.map((o: { value: string }) => o.value).slice(0, -1)).toEqual([ + expect(passedOptions.map((option) => option.value).slice(0, -1)).toEqual([ 'monorepo', 'web', 'library', @@ -56,10 +59,7 @@ describe('pickOrgTemplate', () => { mockSelect.mockResolvedValue('web'); await pickOrgTemplate(manifest(), { isMonorepo: true }); const passedOptions = mockSelect.mock.calls[0][0].options; - expect(passedOptions.map((o: { value: string }) => o.value).slice(0, -1)).toEqual([ - 'web', - 'library', - ]); + expect(passedOptions.map((option) => option.value).slice(0, -1)).toEqual(['web', 'library']); expect(passedOptions.at(-1)).toMatchObject({ label: 'Vite+ built-in templates' }); }); @@ -77,7 +77,7 @@ describe('pickOrgTemplate', () => { // to its escape-hatch option. If the option isn't in the list at all, // the assertion below fails. mockSelect.mockImplementation( - async (opts: { options: { value: string; label: string }[] }) => + async (opts: { options: Array<{ value: string; label: string }> }) => opts.options.find((o) => o.label === 'Vite+ built-in templates')?.value, ); expect(await pickOrgTemplate(manifest(), { isMonorepo: false })).toBe( diff --git a/packages/cli/src/create/__tests__/org-resolve.spec.ts b/packages/cli/src/create/__tests__/org-resolve.spec.ts index b1f480f8bd..d2d605b870 100644 --- a/packages/cli/src/create/__tests__/org-resolve.spec.ts +++ b/packages/cli/src/create/__tests__/org-resolve.spec.ts @@ -4,7 +4,7 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { getConfiguredDefaultTemplate } from '../org-resolve.js'; +import { getConfiguredDefaultTemplate } from '../org-resolve.ts'; describe('getConfiguredDefaultTemplate', () => { let repoRoot: string; diff --git a/packages/cli/src/create/__tests__/org-tarball-reader.spec.ts b/packages/cli/src/create/__tests__/org-tarball-reader.spec.ts index 4416c968ca..4c8aae6e4f 100644 --- a/packages/cli/src/create/__tests__/org-tarball-reader.spec.ts +++ b/packages/cli/src/create/__tests__/org-tarball-reader.spec.ts @@ -16,7 +16,7 @@ function tarRecord({ name, data = '', type = '0' }: TestEntry): Buffer { return tar.subarray(0, 512 + Math.ceil(Buffer.byteLength(data) / 512) * 512); } -function archiveWith(files: TestEntry[]): Buffer { +function archiveWith(files: Array): Buffer { return gzipSync(Buffer.concat([...files.map(tarRecord), Buffer.alloc(1024)])); } @@ -62,7 +62,7 @@ describe('parseOrgTarball', () => { ).rejects.toThrow(/entry exceeds 63 byte size limit/); }); - it.each(['-0000000001', 'not-octal', '1000\xb0'])( + it.each(['-0000000001', 'not-octal', '1000\u00b0'])( 'rejects a malformed size field: %s', async (size) => { const tar = tarRecord({ name: 'package/a' }); @@ -177,6 +177,6 @@ describe('parseOrgTarball', () => { it('rejects a truncated gzip stream', async () => { const archive = archiveWith([{ name: 'package/a', data: 'hello' }]); - await expect(parseOrgTarball(archive.subarray(0, -8))).rejects.toThrow(); + await expect(parseOrgTarball(archive.subarray(0, -8))).rejects.toThrow(/unexpected end/i); }); }); diff --git a/packages/cli/src/create/__tests__/org-tarball.spec.ts b/packages/cli/src/create/__tests__/org-tarball.spec.ts index ffb7d1a8e8..40093a4f12 100644 --- a/packages/cli/src/create/__tests__/org-tarball.spec.ts +++ b/packages/cli/src/create/__tests__/org-tarball.spec.ts @@ -5,7 +5,7 @@ import path from 'node:path'; import { createTarGzip } from 'nanotar'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import type { OrgManifest } from '../org-manifest.js'; +import type { OrgManifest } from '../org-manifest.ts'; import { cleanupStaleStagingDirs, ensureOrgPackageExtracted, @@ -15,14 +15,14 @@ import { resolveBundledPath, resolveExtractionDir, sanitizeHostForPath, -} from '../org-tarball.js'; +} from '../org-tarball.ts'; -const { mockGetVpDirs } = vi.hoisted(() => ({ mockGetVpDirs: vi.fn() })); +const { mockGetVpDirs } = vi.hoisted(() => ({ mockGetVpDirs: vi.fn<() => { cache: string }>() })); vi.mock('../../../binding/index.js', () => ({ getVpDirs: mockGetVpDirs })); describe('resolveBundledPath', () => { - const scratchDirs: string[] = []; + const scratchDirs: Array = []; afterEach(() => { for (const dir of scratchDirs.splice(0)) { @@ -77,7 +77,7 @@ describe('normalizeEntryName', () => { it('normalizes leading `./` and backslashes to forward slashes', () => { expect(normalizeEntryName('./package/src/index.ts')).toBe('src/index.ts'); - expect(normalizeEntryName('package\\src\\index.ts')).toBe('src/index.ts'); + expect(normalizeEntryName(String.raw`package\src\index.ts`)).toBe('src/index.ts'); }); it('returns null for the root `package/` directory and empty names', () => { @@ -187,7 +187,7 @@ describe('parseEntryMode', () => { }); describe('cleanupStaleStagingDirs', () => { - const scratchDirs: string[] = []; + const scratchDirs: Array = []; afterEach(() => { for (const dir of scratchDirs.splice(0)) { @@ -195,7 +195,7 @@ describe('cleanupStaleStagingDirs', () => { } }); - function tmpDestDir(): { destDir: string; parent: string; base: string } { + function tmpDestDir() { const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-org-cleanup-')); scratchDirs.push(parent); const base = 'create-1.0.0'; @@ -241,7 +241,7 @@ describe('cleanupStaleStagingDirs', () => { }); describe('archive resource limits', () => { - const scratchDirs: string[] = []; + const scratchDirs: Array = []; afterEach(() => { vi.restoreAllMocks(); @@ -273,9 +273,11 @@ describe('archive resource limits', () => { const dest = await ensureOrgPackageExtracted(manifest); expect(fs.readFileSync(path.join(dest, 'templates/run.sh'), 'utf8')).toBe('#!/bin/sh\n'); expect(fs.readFileSync(path.join(dest, 'templates/empty.txt'), 'utf8')).toBe(''); - if (process.platform !== 'win32') { - expect(fs.statSync(path.join(dest, 'templates/run.sh')).mode & 0o7777).toBe(0o755); - } + const posixMode = + process.platform === 'win32' + ? undefined + : fs.statSync(path.join(dest, 'templates/run.sh')).mode & 0o7777; + expect(posixMode).toBe(process.platform === 'win32' ? undefined : 0o755); expect(await ensureOrgPackageExtracted(manifest)).toBe(dest); expect(fetch).toHaveBeenCalledTimes(1); }); @@ -296,10 +298,9 @@ describe('archive resource limits', () => { : ensureOrgPackageExtracted(manifest), ).rejects.toThrow(/decompressed.*limit/); - if (operation === 'extraction') { - const dest = resolveExtractionDir(path.join(cache, 'create-org'), manifest); - expect(fs.readdirSync(path.dirname(dest))).toEqual([]); - } + const parent = path.dirname(resolveExtractionDir(path.join(cache, 'create-org'), manifest)); + const remaining = fs.existsSync(parent) ? fs.readdirSync(parent) : undefined; + expect(remaining).toEqual(operation === 'extraction' ? [] : undefined); }); it('counts entries outside the package root during manifest probing', async () => { diff --git a/packages/cli/src/create/__tests__/prompts.spec.ts b/packages/cli/src/create/__tests__/prompts.spec.ts index d179bfa372..e4580fe9bf 100644 --- a/packages/cli/src/create/__tests__/prompts.spec.ts +++ b/packages/cli/src/create/__tests__/prompts.spec.ts @@ -4,9 +4,14 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { cancelAndExit as cancelAndExitImplementation } from '../../utils/prompts.ts'; + const { mockSelect, mockText } = vi.hoisted(() => ({ - mockSelect: vi.fn(), - mockText: vi.fn(), + mockSelect: vi.fn<() => Promise>(), + mockText: + vi.fn< + (options: { validate?: (value: string | undefined) => string | undefined }) => Promise + >(), })); vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ @@ -16,7 +21,7 @@ vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ })); vi.mock('../../utils/prompts.ts', () => ({ - cancelAndExit: vi.fn(() => { + cancelAndExit: vi.fn(() => { throw new Error('Operation cancelled'); }), })); @@ -26,9 +31,9 @@ vi.mock('../../utils/terminal.ts', () => ({ })); const { checkProjectDirExists, isTargetDirAvailable, promptTargetDir, suggestAvailableTargetDir } = - await import('../prompts.js'); + await import('../prompts.ts'); -const tempDirs: string[] = []; +const tempDirs: Array = []; afterEach(() => { for (const dir of tempDirs.splice(0)) { @@ -81,7 +86,7 @@ describe('target directory helpers', () => { it('rejects ".." path segments but accepts directory names that contain two dots', async () => { const cwd = makeTempDir(); let validate: ((value: string | undefined) => string | undefined) | undefined; - mockText.mockImplementation((options: { validate: typeof validate }) => { + mockText.mockImplementation((options) => { validate = options.validate; return Promise.resolve('my..lib'); }); @@ -236,9 +241,10 @@ describe('target directory helpers', () => { }), ); expect(fs.lstatSync(targetDir, { throwIfNoEntry: false })).toBeUndefined(); - if (!dangling) { - expect(fs.readFileSync(path.join(linkedDir, 'keep.txt'), 'utf8')).toBe('keep'); - } + const kept = path.join(linkedDir, 'keep.txt'); + expect(fs.existsSync(kept) ? fs.readFileSync(kept, 'utf8') : undefined).toBe( + dangling ? undefined : 'keep', + ); }, ); diff --git a/packages/cli/src/create/__tests__/register-template.spec.ts b/packages/cli/src/create/__tests__/register-template.spec.ts index c72cb0c55c..727e64c544 100644 --- a/packages/cli/src/create/__tests__/register-template.spec.ts +++ b/packages/cli/src/create/__tests__/register-template.spec.ts @@ -3,12 +3,12 @@ import { rm } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { log } from '@voidzero-dev/vite-plus-prompts'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { resolveViteConfig } from '../../resolve-vite-config.js'; -import type { CreateTemplateEntry } from '../org-manifest.js'; -import { registerLocalTemplate } from '../register-template.js'; +import { resolveViteConfig } from '../../resolve-vite-config.ts'; +import type { CreateTemplateEntry } from '../org-manifest.ts'; +import { registerLocalTemplate } from '../register-template.ts'; const ENTRY_A: CreateTemplateEntry = { name: 'my-generator', @@ -55,10 +55,10 @@ describe('registerLocalTemplate', () => { async function readCreate(): Promise<{ defaultTemplate?: string; - templates?: CreateTemplateEntry[]; + templates?: Array; }> { const config = (await resolveViteConfig(workspaceRoot)) as { - create?: { defaultTemplate?: string; templates?: CreateTemplateEntry[] }; + create?: { defaultTemplate?: string; templates?: Array }; }; return config.create ?? {}; } @@ -140,7 +140,9 @@ describe('registerLocalTemplate', () => { const original = `import { defineConfig } from 'vite-plus';\nimport 'vite-plus-nonexistent-module-xyz';\n\nexport default defineConfig({ create: { defaultTemplate: '@your-org', templates: [{ name: 'pre', description: 'p', template: './pre' }] } });\n`; fs.writeFileSync(configPath, original); - await expect(registerLocalTemplate(workspaceRoot, ENTRY_A, true)).rejects.toThrow(); + await expect(registerLocalTemplate(workspaceRoot, ENTRY_A, true)).rejects.toThrow( + /vite-plus-nonexistent-module-xyz|failed to load/i, + ); expect(fs.readFileSync(configPath, 'utf8')).toBe(original); }); @@ -149,16 +151,12 @@ describe('registerLocalTemplate', () => { await registerLocalTemplate(workspaceRoot, ENTRY_A, true); - const config = (await resolveViteConfig(workspaceRoot)) as { - run?: { cache?: boolean }; - create?: { templates?: CreateTemplateEntry[] }; - }; - expect(config.run?.cache).toBe(true); - expect(config.create?.templates).toEqual([ENTRY_A]); + const config = await resolveViteConfig(workspaceRoot); + expect(config).toMatchObject({ run: { cache: true }, create: { templates: [ENTRY_A] } }); }); it('warns when a same-name entry already points at a different template', async () => { - const warnSpy = vi.spyOn(prompts.log, 'warn').mockImplementation(() => {}); + const warnSpy = vi.spyOn(log, 'warn').mockImplementation(() => {}); writeViteConfig( `{ create: { templates: [{ name: '${ENTRY_A.name}', description: 'pre', template: './old-path' }] } }`, ); diff --git a/packages/cli/src/create/__tests__/remote.spec.ts b/packages/cli/src/create/__tests__/remote.spec.ts index ed0ab12931..b7b383a95d 100644 --- a/packages/cli/src/create/__tests__/remote.spec.ts +++ b/packages/cli/src/create/__tests__/remote.spec.ts @@ -2,15 +2,20 @@ import { fileURLToPath } from 'node:url'; import { describe, expect, it, vi } from 'vitest'; -import type { WorkspaceInfo } from '../../types/index.ts'; +import type { runCommand as runCommandImplementation } from '../../utils/command.ts'; import { runCommandSilently } from '../../utils/command.ts'; import { runRemoteTemplateCommand } from '../templates/remote.ts'; import type { TemplateInfo } from '../templates/types.ts'; +import { makeWorkspaceInfo } from './workspace-fixture.ts'; -vi.mock('../../utils/command.ts', async (importOriginal) => ({ - ...(await importOriginal()), - runCommand: vi.fn(), - runCommandSilently: vi.fn(async () => ({ exitCode: 0 })), +vi.mock(import('../../utils/command.ts'), async (importOriginal) => ({ + ...(await importOriginal()), + runCommand: vi.fn(), + runCommandSilently: vi.fn(async () => ({ + exitCode: 0, + stdout: Buffer.alloc(0), + stderr: Buffer.alloc(0), + })), })); describe('runRemoteTemplateCommand', () => { @@ -18,15 +23,16 @@ describe('runRemoteTemplateCommand', () => { // An older global `vp` in VP_CLI_BIN must not run it, so this package's CLI runs on the current Node.js. it("runs the template through this package's vp dlx with the selected package manager", async () => { vi.stubEnv('VP_CLI_BIN', '/old/global/vp'); - const workspaceInfo = { + const workspaceInfo = makeWorkspaceInfo('/workspace', { packageManager: 'pnpm', packageManagerVersion: '10.32.0', - } as unknown as WorkspaceInfo; + }); const templateInfo = { command: 'create-foo', args: ['app'], envs: {}, - } as unknown as TemplateInfo; + type: 'remote', + } satisfies TemplateInfo; await runRemoteTemplateCommand(workspaceInfo, '/workspace', templateInfo, false, true); vi.unstubAllEnvs(); @@ -41,16 +47,17 @@ describe('runRemoteTemplateCommand', () => { // The generator may run inside the new workspace, whose registry could resolve a tag differently. it('forwards the resolved override instead of the tag the user gave', async () => { - const workspaceInfo = { + const workspaceInfo = makeWorkspaceInfo('/workspace', { packageManager: 'pnpm', packageManagerVersion: '10.18.0', packageManagerOverride: 'pnpm@10.18.0+sha512.abc', - } as unknown as WorkspaceInfo; + }); const templateInfo = { command: 'create-foo', args: [], envs: { VP_PACKAGE_MANAGER: 'pnpm@latest+sha512.abc' }, - } as unknown as TemplateInfo; + type: 'remote', + } satisfies TemplateInfo; await runRemoteTemplateCommand(workspaceInfo, '/workspace', templateInfo, false, true); diff --git a/packages/cli/src/create/__tests__/utils.spec.ts b/packages/cli/src/create/__tests__/utils.spec.ts index e52df9cf0a..5ba9fa4170 100644 --- a/packages/cli/src/create/__tests__/utils.spec.ts +++ b/packages/cli/src/create/__tests__/utils.spec.ts @@ -14,7 +14,7 @@ import { getProjectDirFromPackageName, renameFiles, shouldConfigureEditorsForCreate, -} from '../utils.js'; +} from '../utils.ts'; describe('getProjectDirFromPackageName', () => { it('should get project dir from package name', () => { @@ -165,7 +165,7 @@ describe('ensureDefaultGitignoreEntries', () => { }); function gitignore(): string { - return fs.readFileSync(path.join(projectDir, '.gitignore'), 'utf-8'); + return fs.readFileSync(path.join(projectDir, '.gitignore'), 'utf8'); } const dotenvBlock = '# dotenv environment variable files\n.env\n.env.*\n!.env.example\n'; @@ -244,7 +244,7 @@ describe('ensureGitignoreVsCodeEditorConfigs', () => { }); function gitignore(): string { - return fs.readFileSync(path.join(projectDir, '.gitignore'), 'utf-8'); + return fs.readFileSync(path.join(projectDir, '.gitignore'), 'utf8'); } function writeGitignore(content: string): void { @@ -378,7 +378,7 @@ describe('renameFiles', () => { } function read(name: string): string { - return fs.readFileSync(path.join(projectDir, name), 'utf-8'); + return fs.readFileSync(path.join(projectDir, name), 'utf8'); } function exists(name: string): boolean { diff --git a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts index 4d00ccbef6..19a04b5eb2 100644 --- a/packages/cli/src/create/__tests__/workspace-catalog.spec.ts +++ b/packages/cli/src/create/__tests__/workspace-catalog.spec.ts @@ -18,6 +18,8 @@ import { VITE_PLUS_OVERRIDE_PACKAGES, VITE_PLUS_VERSION, } from '../../utils/constants.ts'; +import type { JsonObject } from '../../utils/json-value.ts'; +import { isObjectValue } from '../../utils/json-value.ts'; import { readJsonFile } from '../../utils/json.ts'; import { readYamlFile } from '../../utils/yaml.ts'; import { ensureCreateCatalogEntries } from '../utils.ts'; @@ -245,14 +247,20 @@ 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' } }, - }), + `catalog: + react: ^19.0.0 +catalogs: + default: + vite-plus: 0.3.2 +customMetadata: &metadata + timestamp: !!timestamp 2026-01-01 + self: *metadata +`, ); rewriteYarnrcYml(root, false, new Set(), new Set(), true, false); const config = readYamlFile(file); - expect(config.catalog).toEqual({ react: '^19.0.0' }); + expect(config?.catalog).toEqual({ react: '^19.0.0' }); + expect(config?.customMetadata).toHaveProperty('self', config?.customMetadata); expect(config).toMatchObject({ catalogs: { default: { 'vite-plus': VITE_PLUS_VERSION, vite: VITE_PLUS_OVERRIDE_PACKAGES.vite }, @@ -268,6 +276,14 @@ describe.each(['root', 'nested'])('Bun %s shared default catalog', (location) => }; let file: string; + function activeCatalogs(contents: JsonObject) { + const active = location === 'nested' ? contents.workspaces : contents; + if (!isObjectValue(active)) { + throw new Error('Missing workspace config'); + } + return active; + } + beforeEach(() => { file = path.join(root, 'package.json'); fs.writeFileSync( @@ -300,7 +316,7 @@ describe.each(['root', 'nested'])('Bun %s shared default catalog', (location) => ); ensureCreateCatalogEntries(root, project, PackageManager.bun); const result = readJsonFile(file); - const active = (location === 'nested' ? result.workspaces : result) as typeof config; + const active = activeCatalogs(result); expect(active.catalog).toEqual(config.catalog); expect(active.catalogs).toEqual({ default: { react: '^19.0.0', '@vitest/utils': VITEST_VERSION }, @@ -315,7 +331,7 @@ describe.each(['root', 'nested'])('Bun %s shared default catalog', (location) => 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; + const active = activeCatalogs(result); expect(active.catalog).toEqual({ vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, 'vite-plus': VITE_PLUS_VERSION, @@ -345,22 +361,14 @@ describe.each(['root', 'nested'])('Bun %s shared default catalog', (location) => ); rewriteBunCatalog(root, false, new Set()); const result = readJsonFile(file); - const active = (location === 'nested' ? result.workspaces : result) as { - catalog?: Record; - catalogs: Record>; - }; + const active = activeCatalogs(result); expect(active.catalog).toEqual( - catalog && { - ...catalog, - ...(catalog.vite ? { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } : {}), - }, + catalog?.vite ? { ...catalog, vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } : catalog, ); - expect(active.catalogs).toEqual({ - default: { - 'vite-plus': VITE_PLUS_VERSION, - ...(!catalog?.vite ? { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } : {}), - }, - }); + const expectedDefault = catalog?.vite + ? { 'vite-plus': VITE_PLUS_VERSION } + : { 'vite-plus': VITE_PLUS_VERSION, vite: VITE_PLUS_OVERRIDE_PACKAGES.vite }; + expect(active.catalogs).toEqual({ default: expectedDefault }); const before = fs.readFileSync(file, 'utf8'); rewriteBunCatalog(root, false, new Set()); expect(fs.readFileSync(file, 'utf8')).toBe(before); @@ -368,8 +376,15 @@ describe.each(['root', 'nested'])('Bun %s shared default catalog', (location) => 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.catalogs.default, { vite: active.catalog.vite }); + const active = activeCatalogs(contents); + if ( + !isObjectValue(active.catalog) || + !isObjectValue(active.catalogs) || + !isObjectValue(active.catalogs.default) + ) { + throw new Error('Missing test catalogs'); + } + active.catalogs.default.vite = active.catalog.vite; fs.writeFileSync(file, JSON.stringify(contents)); rewriteBunCatalog(root, false, new Set()); const result = readJsonFile(file); @@ -442,10 +457,9 @@ it.each(['1.2.14', '1.3.14', '1.4.0'])( private: true, workspaces: { packages: ['apps/*'], - catalog: { - vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, - ...(merged ? {} : { 'vite-plus': VITE_PLUS_VERSION }), - }, + catalog: merged + ? { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite } + : { vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, 'vite-plus': VITE_PLUS_VERSION }, catalogs: { default: { react: '^19.0.0', diff --git a/packages/cli/src/create/__tests__/workspace-fixture.ts b/packages/cli/src/create/__tests__/workspace-fixture.ts new file mode 100644 index 0000000000..1f1a477776 --- /dev/null +++ b/packages/cli/src/create/__tests__/workspace-fixture.ts @@ -0,0 +1,27 @@ +import { PackageManager } from '../../types/package.ts'; +import type { WorkspaceInfo } from '../../types/workspace.ts'; + +export function makeWorkspaceInfo( + rootDir: string, + overrides: Partial = {}, +): WorkspaceInfo { + return { + rootDir, + packageManager: PackageManager.pnpm, + packageManagerVersion: 'latest', + isMonorepo: true, + monorepoScope: '', + workspacePatterns: [], + parentDirs: [], + packages: [], + downloadPackageManager: { + name: '', + installDir: '', + binPrefix: '', + binPaths: {}, + packageName: '', + version: '', + }, + ...overrides, + }; +} diff --git a/packages/cli/src/create/bin.ts b/packages/cli/src/create/bin.ts index 59ede76b86..2cba743a71 100644 --- a/packages/cli/src/create/bin.ts +++ b/packages/cli/src/create/bin.ts @@ -2,7 +2,15 @@ import fs from 'node:fs'; import path from 'node:path'; import { styleText } from 'node:util'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { + intro, + isCancel, + log as promptLog, + multiselect, + select, + spinner, + text, +} from '@voidzero-dev/vite-plus-prompts'; import { getPackageManagerOverride, parseCreateArgs, vitePlusHeader } from '../../binding/index.js'; import { @@ -25,7 +33,9 @@ import { shouldSkipStagedMigrationForHooks, workspaceSupportsCatalog, } from '../migration/migrator.ts'; -import { DependencyType, PackageManager, type WorkspaceInfo } from '../types/index.ts'; +import type { WorkspaceInfo } from '../types/index.ts'; +import { DependencyType, PackageManager } from '../types/index.ts'; +import { isPackageManager } from '../types/package.ts'; import { COPILOT_AGENT_ID, detectExistingAgentTargetPaths, @@ -42,14 +52,16 @@ import { unwrapCliParseOutcome } from '../utils/cli-parse.ts'; import { isForceOverrideMode } from '../utils/constants.ts'; import { documentationUrl } from '../utils/documentation.ts'; import { detectExistingEditors, selectEditors, writeEditorConfigs } from '../utils/editor.ts'; +import { errorMessage } from '../utils/error.ts'; import { findGitRoot, initGitRepository } from '../utils/git.ts'; import { renderCliDoc } from '../utils/help.ts'; import { readJsonFile } from '../utils/json.ts'; +import { hasOwnKey } from '../utils/object.ts'; import { hasVitePlusDependency } from '../utils/package.ts'; import { displayRelative } from '../utils/path.ts'; +import type { CommandRunSummary } from '../utils/prompts.ts'; import { cancelAndExit, - type CommandRunSummary, defaultInteractive, downloadPackageManager, promptGitHooks, @@ -68,11 +80,12 @@ import { import type { ExecutionWithProjectDir } from './command.ts'; import { discoverTemplate, inferGitHubRepoName, inferParentDir, isGitHubUrl } from './discovery.ts'; import { getInitialTemplateOptions } from './initial-template-options.ts'; -import { CreateConfigSchemaError, type CreateTemplateEntry } from './org-manifest.ts'; +import type { CreateTemplateEntry } from './org-manifest.ts'; +import { CreateConfigSchemaError } from './org-manifest.ts'; +import type { OrgResolution } from './org-resolve.ts'; import { getConfiguredCreate, getConfiguredDefaultTemplate, - type OrgResolution, resolveOrgManifestForCreate, } from './org-resolve.ts'; import { @@ -151,7 +164,7 @@ export interface Options { interactive: boolean; list: boolean; verbose: boolean; - agent?: string | string[] | false; + agent?: string | Array | false; editor?: string | false; git?: boolean; hooks?: boolean; @@ -184,7 +197,7 @@ function parseArgs() { }; } -function describeScaffold(templateName: string, templateArgs: string[]) { +function describeScaffold(templateName: string, templateArgs: Array) { if (templateName === BuiltinTemplate.monorepo) { return 'Vite+ monorepo'; } @@ -207,7 +220,7 @@ function describeScaffold(templateName: string, templateArgs: string[]) { return undefined; } -function getTemplateOption(args: string[]) { +function getTemplateOption(args: Array) { for (let index = 0; index < args.length; index++) { const arg = args[index]; if (arg === '--template' || arg === '-t') { @@ -220,12 +233,12 @@ function getTemplateOption(args: string[]) { return undefined; } -function hasExplicitTargetDir(args: string[]) { +function hasExplicitTargetDir(args: Array) { return args[0] !== undefined && !args[0].startsWith('-'); } function formatTemplateName(templateName: string) { - const templateAliases: Record = { + const templateAliases = { lit: 'Lit', preact: 'Preact', react: 'React', @@ -237,12 +250,12 @@ function formatTemplateName(templateName: string) { }; const isTypeScript = templateName.endsWith('-ts'); const baseName = isTypeScript ? templateName.slice(0, -3) : templateName; - const frameworkName = - templateAliases[baseName] ?? - baseName - .split(/[-_]/) - .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)) - .join(' '); + const frameworkName = hasOwnKey(templateAliases, baseName) + ? templateAliases[baseName] + : baseName + .split(/[-_]/) + .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)) + .join(' '); return `${frameworkName} + ${isTypeScript ? 'TypeScript' : 'JavaScript'}`; } @@ -322,7 +335,7 @@ async function main() { // #region Prepare Stage if (options.interactive) { - prompts.intro(vitePlusHeader()); + intro(vitePlusHeader()); } // check --directory option is valid @@ -331,7 +344,7 @@ async function main() { if (options.directory) { const formatted = formatTargetDir(options.directory); if (formatted.error) { - prompts.log.error(formatted.error); + promptLog.error(formatted.error); cancelAndExit('The --directory option is invalid', 1); } targetDir = formatted.directory; @@ -361,9 +374,9 @@ async function main() { const shouldOfferCwdOption = isInSubdirectory && !cwdUnderParentDir; // Interactive mode: prompt for template if not provided - let selectedTemplateName = templateName as string; + let selectedTemplateName = templateName ?? ''; let selectedTemplateArgs = [...templateArgs]; - let selectedAgentTargetPaths: string[] | undefined; + let selectedAgentTargetPaths: Array | undefined; let shouldWriteCopilotSetupWorkflow = false; let selectedEditors: Awaited>; let selectedParentDir: string | undefined; @@ -383,7 +396,7 @@ async function main() { // error is a real misconfiguration: exit cleanly with the message. An // unevaluable config only disables local templates: warn so a registered // name does not silently fall through to an npm package. - let localTemplates: CreateTemplateEntry[] = []; + let localTemplates: Array = []; if (isMonorepo) { try { const configuredCreate = await getConfiguredCreate(workspaceInfoOptional.rootDir, { @@ -397,8 +410,8 @@ async function main() { if (error instanceof CreateConfigSchemaError) { cancelAndExit(error.message, 1); } - prompts.log.warn( - `Could not read \`create\` config from the workspace vite.config (${(error as Error).message}); local templates are unavailable`, + promptLog.warn( + `Could not read \`create\` config from the workspace vite.config (${errorMessage(error)}); local templates are unavailable`, ); } } else if (!selectedTemplateName) { @@ -460,12 +473,12 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h } if (!selectedTemplateName) { - const template = await prompts.select({ + const template = await select({ message: '', options: getInitialTemplateOptions(isMonorepo, localTemplates), }); - if (prompts.isCancel(template)) { + if (isCancel(template)) { cancelAndExit(); } @@ -504,13 +517,13 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h ); } if (selectedTemplateName === BuiltinTemplate.monorepo && isMonorepo) { - prompts.log.info( + promptLog.info( 'You are already in a monorepo workspace.\nUse a different template or run this command outside the monorepo', ); cancelAndExit('Cannot create a monorepo inside an existing monorepo', 1); } if (selectedTemplateName === BuiltinTemplate.generator && !isMonorepo) { - prompts.log.info( + promptLog.info( 'The vite:generator template requires a monorepo workspace.\nRun this command inside a Vite+ monorepo, or create one first with `vp create vite:monorepo`', ); cancelAndExit('Cannot create a generator outside a monorepo', 1); @@ -523,7 +536,7 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h } if (isInSubdirectory && !compactOutput) { - prompts.log.info(`Detected monorepo root at ${accent(workspaceInfoOptional.rootDir)}`); + promptLog.info(`Detected monorepo root at ${accent(workspaceInfoOptional.rootDir)}`); } if (isMonorepo && options.interactive && !targetDir) { @@ -531,7 +544,7 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h const hasParentDirs = workspaceInfoOptional.parentDirs.length > 0; if (hasParentDirs || isInSubdirectory) { - const dirOptions: { label: string; value: string; hint: string }[] = + const dirOptions: Array<{ label: string; value: string; hint: string }> = workspaceInfoOptional.parentDirs.map((dir) => ({ label: `${dir}/`, value: dir, @@ -557,13 +570,13 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h : (inferParentDir(selectedTemplateName, workspaceInfoOptional, isLocalTemplate) ?? workspaceInfoOptional.parentDirs[0]); - const selected = await prompts.select({ + const selected = await select({ message: 'Where should the new package be added to the monorepo:', options: dirOptions, initialValue: defaultParentDir, }); - if (prompts.isCancel(selected)) { + if (isCancel(selected)) { cancelAndExit(); } @@ -573,7 +586,7 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h } if (!parentDir) { - const customTargetDir = await prompts.text({ + const customTargetDir = await text({ message: 'Where should the new package be added to the monorepo:', placeholder: 'e.g., packages/', validate: (value) => { @@ -581,7 +594,7 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h }, }); - if (prompts.isCancel(customTargetDir)) { + if (isCancel(customTargetDir)) { cancelAndExit(); } @@ -592,7 +605,7 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h } if (isMonorepo && !options.interactive && !targetDir) { if (isInSubdirectory && !compactOutput) { - prompts.log.info(`Use ${accent('--directory')} to specify a different target location.`); + promptLog.info(`Use ${accent('--directory')} to specify a different target location.`); } const inferredParentDir = inferParentDir(selectedTemplateName, workspaceInfoOptional, isLocalTemplate) ?? @@ -610,7 +623,7 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h : workspaceInfoOptional.rootDir; const defaultTargetDir = suggestAvailableTargetDir(inferredTargetDir, remoteTargetBaseDir); if (defaultTargetDir !== inferredTargetDir && options.interactive) { - prompts.log.info( + promptLog.info( ` Target directory "${inferredTargetDir}" already exists. Suggested: ${accent(defaultTargetDir)}`, ); } @@ -657,7 +670,7 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h // so that scaffolding happens in cwd, not at the workspace root targetDir = cwdRelativeToRoot; } - prompts.log.info(`Using package name: ${accent(packageName)}`); + promptLog.info(`Using package name: ${accent(packageName)}`); } else if (selectedTemplateName === BuiltinTemplate.monorepo) { const selected = await promptPackageNameAndTargetDir( getRandomProjectName({ fallbackName: 'vite-plus-monorepo' }), @@ -688,7 +701,7 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h : (requestedPackageManager ?? detectedPackageManager); const launcherPackageManager = detectLauncherPackageManager(); const chosenPackageManager = - (packageManagerOverride?.name as PackageManager | undefined) ?? + (isPackageManager(packageManagerOverride?.name) ? packageManagerOverride.name : undefined) ?? preferredPackageManager ?? launcherPackageManager; // Only the non-interactive default is Vite+'s own choice, so only it may become npm when pnpm is unavailable. @@ -713,7 +726,10 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h packageManagerOverride?.expectedHash ?? undefined, fallbackToNpm, ); - const packageManager = downloadResult.name as PackageManager; + const packageManager = downloadResult.name; + if (!isPackageManager(packageManager)) { + throw new Error(`Unsupported package manager: ${packageManager}`); + } let resolvedPackageManagerOverride: string | undefined; if (packageManagerOverride) { resolvedPackageManagerOverride = `${packageManager}@${downloadResult.version}`; @@ -801,7 +817,7 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h } const createProgress = - options.interactive && compactOutput ? prompts.spinner({ indicator: 'timer' }) : undefined; + options.interactive && compactOutput ? spinner({ indicator: 'timer' }) : undefined; let createProgressStarted = false; let createProgressMessage = 'Scaffolding project'; const updateCreateProgress = (message: string) => { @@ -849,7 +865,7 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h // Gated builds reported by the ESLint/Prettier migration pre-install. yarn // only emits YN0004 on the first install, so the later main install won't // re-report them; carry them forward so detection still sees them. - let migratePendingBuilds: string[] = []; + let migratePendingBuilds: Array = []; const handleIgnoredBuilds = async ( projectPath: string, @@ -1140,8 +1156,8 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h ); } } catch (error) { - prompts.log.warn( - `Could not register the generator in create.templates (${(error as Error).message}).\n` + + promptLog.warn( + `Could not register the generator in create.templates (${errorMessage(error)}).\n` + `Add it by hand: { name: '${generatorName || path.basename(projectDir)}', template: '${generatorTemplatePath}' }`, ); } @@ -1254,7 +1270,7 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h if (isMonorepo) { if (!compactOutput) { - prompts.log.step('Monorepo integration...'); + promptLog.step('Monorepo integration...'); } // The package list predates scaffolding, so an overwritten target can still appear in it. @@ -1268,7 +1284,7 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h if (dependencyCandidates.length > 0) { if (options.interactive) { pauseCreateProgress(); - const selectedDepTypeOptions = await prompts.multiselect({ + const selectedDepTypeOptions = await multiselect({ message: `Add workspace dependencies to ${accent(projectDir)}?`, options: [ { @@ -1287,13 +1303,13 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h required: false, }); - let selectedDepTypes: DependencyType[] = []; - if (!prompts.isCancel(selectedDepTypeOptions)) { + let selectedDepTypes: Array = []; + if (!isCancel(selectedDepTypeOptions)) { selectedDepTypes = selectedDepTypeOptions; } for (const selectedDepType of selectedDepTypes) { - const selected = await prompts.multiselect({ + const selected = await multiselect({ message: `Which packages should be added as ${selectedDepType} to ${success( projectDir, )}?`, @@ -1303,8 +1319,8 @@ Use \`vp create --list\` to list all available templates, or run \`vp create --h })), required: false, }); - let selectedDeps: string[] = []; - if (!prompts.isCancel(selected)) { + let selectedDeps: Array = []; + if (!isCancel(selected)) { selectedDeps = selected; } @@ -1452,8 +1468,8 @@ async function showAvailableTemplates() { log(listTemplatesMessage); } -main().catch((err) => { - prompts.log.error(err.message); - console.error(err); - cancelAndExit(`Failed to generate code: ${err.message}`, 1); +await main().catch((error: unknown) => { + promptLog.error(errorMessage(error)); + console.error(error); + cancelAndExit(`Failed to generate code: ${errorMessage(error)}`, 1); }); diff --git a/packages/cli/src/create/command.ts b/packages/cli/src/create/command.ts index 85fcb39879..9851f6ed0a 100644 --- a/packages/cli/src/create/command.ts +++ b/packages/cli/src/create/command.ts @@ -30,7 +30,11 @@ export async function runCommandAndDetectProjectDir( const result = await runCommandWithFspy({ binName: options.command, args: options.args, - envs: options.envs as Record, + envs: Object.fromEntries( + Object.entries(options.envs).filter( + (entry): entry is [string, string] => entry[1] !== undefined, + ), + ), cwd, }); diff --git a/packages/cli/src/create/discovery.ts b/packages/cli/src/create/discovery.ts index ca3348676e..69705d4e9f 100644 --- a/packages/cli/src/create/discovery.ts +++ b/packages/cli/src/create/discovery.ts @@ -6,7 +6,8 @@ import { readJsonFile } from '../utils/json.ts'; import { isBingoTemplate } from '../utils/workspace.ts'; import { prependToPathToEnvs } from './command.ts'; import { isRelativePath } from './org-manifest.ts'; -import { BuiltinTemplate, type TemplateInfo, TemplateType } from './templates/types.ts'; +import type { TemplateInfo } from './templates/types.ts'; +import { BuiltinTemplate, TemplateType } from './templates/types.ts'; // Check if template name is a GitHub URL export function isGitHubUrl(templateName: string): boolean { @@ -93,7 +94,7 @@ function resolveLocalBinPath( // Discover and identify a template export function discoverTemplate( templateName: string, - templateArgs: string[], + templateArgs: Array, workspaceInfo: WorkspaceInfo, interactive?: boolean, bundledLocalPath?: string, diff --git a/packages/cli/src/create/initial-template-options.ts b/packages/cli/src/create/initial-template-options.ts index dcb11e479d..3c8ad653d5 100644 --- a/packages/cli/src/create/initial-template-options.ts +++ b/packages/cli/src/create/initial-template-options.ts @@ -9,8 +9,8 @@ export interface InitialTemplateOption { export function getInitialTemplateOptions( isMonorepo: boolean, - templates: CreateTemplateEntry[] = [], -): InitialTemplateOption[] { + templates: Array = [], +): Array { return [ ...(!isMonorepo ? [ diff --git a/packages/cli/src/create/org-manifest.ts b/packages/cli/src/create/org-manifest.ts index 7f32e178b2..7f81d3bb48 100644 --- a/packages/cli/src/create/org-manifest.ts +++ b/packages/cli/src/create/org-manifest.ts @@ -2,6 +2,8 @@ import path from 'node:path'; import { normalize } from 'verkit'; +import type { JsonObject } from '../utils/json-value.ts'; +import { isJsonObject, isObjectValue, isStringRecord } from '../utils/json-value.ts'; import { fetchNpmResource, getNpmRegistry } from '../utils/npm-config.ts'; import { readPackageJsonFromTarball } from './org-tarball.ts'; @@ -33,7 +35,7 @@ export interface OrgManifest { version: string; tarballUrl: string; integrity?: string; - templates: OrgTemplateEntry[]; + templates: Array; } /** @@ -116,9 +118,9 @@ export function validateTemplateEntry( if (!entry || typeof entry !== 'object') { throw makeError(`${label}[${index}] must be an object`); } - const raw = entry as Record; - const requireString = (field: string): string => { - const value = raw[field]; + const fields: { name?: unknown; description?: unknown; template?: unknown } = entry; + const requireString = (field: keyof CreateTemplateEntry): string => { + const value = field in fields ? fields[field] : undefined; if (typeof value !== 'string' || value.length === 0) { throw makeError(`${label}[${index}].${field} must be a non-empty string`); } @@ -153,12 +155,12 @@ export function validateTemplateEntry( * manifests and local `create.templates`. */ export function validateTemplateEntries( - templates: readonly unknown[], + templates: ReadonlyArray, label: string, makeError: (message: string) => Error, validateOne: (entry: unknown, index: number) => T, -): T[] { - const entries: T[] = []; +): Array { + const entries: Array = []; const seen = new Set(); for (let index = 0; index < templates.length; index += 1) { const entry = validateOne(templates[index], index); @@ -175,27 +177,24 @@ function validateEntry(entry: unknown, index: number, packageName: string): OrgT const makeError = (message: string) => new OrgManifestSchemaError(message, packageName); const base = validateTemplateEntry(entry, index, 'createConfig.templates', makeError); - let monorepo: boolean | undefined; - const raw = entry as Record; - if (raw.monorepo !== undefined) { - if (typeof raw.monorepo !== 'boolean') { + if (entry && typeof entry === 'object' && 'monorepo' in entry && entry.monorepo !== undefined) { + if (typeof entry.monorepo !== 'boolean') { throw makeError(`createConfig.templates[${index}].monorepo must be a boolean`); } - monorepo = raw.monorepo; + return { ...base, monorepo: entry.monorepo }; } - - return { ...base, ...(monorepo !== undefined ? { monorepo } : {}) }; + return base; } -function validateManifest(raw: unknown, packageName: string): OrgTemplateEntry[] | null { - if (!raw || typeof raw !== 'object') { +function validateManifest(raw: unknown, packageName: string): Array | null { + if (!raw || typeof raw !== 'object' || !('createConfig' in raw)) { return null; } - const createConfig = (raw as { createConfig?: unknown }).createConfig; - if (!createConfig || typeof createConfig !== 'object') { + const { createConfig } = raw; + if (!createConfig || typeof createConfig !== 'object' || !('templates' in createConfig)) { return null; } - const templates = (createConfig as { templates?: unknown }).templates; + const { templates } = createConfig; if (templates === undefined) { return null; } @@ -232,7 +231,7 @@ const makeCreateConfigError = (message: string) => new CreateConfigSchemaError(m * is absent or an empty array; throws {@link CreateConfigSchemaError} when present * but malformed. */ -export function validateCreateTemplates(templates: unknown): CreateTemplateEntry[] { +export function validateCreateTemplates(templates: unknown): Array { if (templates === undefined) { return []; } @@ -263,25 +262,7 @@ export function validateCreateTemplates(templates: unknown): CreateTemplateEntry ); } -interface RegistryPackument { - name?: string; - 'dist-tags'?: Record; - versions?: Record; -} - -interface RegistryVersionMeta { - version?: string; - createConfig?: unknown; - dist?: { - tarball?: string; - integrity?: string; - }; -} - -async function fetchPackument( - scope: string, - packageName: string, -): Promise { +async function fetchPackument(scope: string, packageName: string): Promise { // npm's registry URLs keep `@` and `/` unencoded // (`https://registry.npmjs.org/@scope/name`). Match that — private // registries often route on the literal path. @@ -296,7 +277,8 @@ async function fetchPackument( if (!response.ok) { throw new Error(`npm registry responded with ${response.status} for ${packageName}`); } - return (await response.json()) as RegistryPackument; + const value: unknown = await response.json(); + return isJsonObject(value) ? value : null; } /** @@ -331,19 +313,20 @@ export async function readOrgManifest( if (!packument) { return null; } + const tags = isStringRecord(packument['dist-tags']) ? packument['dist-tags'] : undefined; + const versions = isObjectValue(packument.versions) ? packument.versions : undefined; let resolvedVersion: string | undefined; if (requestedVersion) { resolvedVersion = - packument['dist-tags']?.[requestedVersion] ?? - (packument.versions?.[requestedVersion] ? requestedVersion : undefined); + tags?.[requestedVersion] ?? (versions?.[requestedVersion] ? requestedVersion : undefined); if (!resolvedVersion) { throw new OrgManifestSchemaError( - `version "${requestedVersion}" not found (known tags: ${Object.keys(packument['dist-tags'] ?? {}).join(', ') || 'none'})`, + `version "${requestedVersion}" not found (known tags: ${Object.keys(tags ?? {}).join(', ') || 'none'})`, packageName, ); } } else { - resolvedVersion = packument['dist-tags']?.latest; + resolvedVersion = tags?.latest; if (!resolvedVersion) { return null; } @@ -356,12 +339,15 @@ export async function readOrgManifest( packageName, ); } - const meta = packument.versions?.[resolvedVersion]; - if (!meta) { + const meta = versions?.[resolvedVersion]; + if (!isObjectValue(meta)) { return null; } + const dist = isObjectValue(meta.dist) ? meta.dist : undefined; + const tarball = typeof dist?.tarball === 'string' ? dist.tarball : undefined; + const integrity = typeof dist?.integrity === 'string' ? dist.integrity : undefined; let templates = validateManifest(meta, packageName); - if (!templates && meta.createConfig === undefined && meta.dist?.tarball) { + if (!templates && meta.createConfig === undefined && tarball) { // `createConfig` absent (not merely empty) means the registry either // stripped it from the version metadata or the package has no manifest; // probe the published tarball to tell the two apart (see @@ -370,24 +356,21 @@ export async function readOrgManifest( // `@scope/create` package still reaches the passthrough path. A manifest // that IS present but malformed still throws, because `validateManifest` // runs outside the catch. - const packageJson = await readPackageJsonFromTarball( - meta.dist.tarball, - meta.dist.integrity, - ).catch(() => null); + const packageJson = await readPackageJsonFromTarball(tarball, integrity).catch(() => null); templates = validateManifest(packageJson, packageName); } if (!templates) { return null; } - if (!meta.dist?.tarball) { + if (!tarball) { throw new OrgManifestSchemaError(`missing dist.tarball for ${resolvedVersion}`, packageName); } return { scope, packageName, version: resolvedVersion, - tarballUrl: meta.dist.tarball, - integrity: meta.dist.integrity, + tarballUrl: tarball, + integrity, templates, }; } @@ -398,9 +381,9 @@ export async function readOrgManifest( * existing monorepo, mirroring `initial-template-options.ts:9-31`. */ export function filterManifestForContext( - templates: readonly OrgTemplateEntry[], + templates: ReadonlyArray, isMonorepo: boolean, -): OrgTemplateEntry[] { +): Array { if (!isMonorepo) { return [...templates]; } diff --git a/packages/cli/src/create/org-picker.ts b/packages/cli/src/create/org-picker.ts index 5976d7b98d..76bf668320 100644 --- a/packages/cli/src/create/org-picker.ts +++ b/packages/cli/src/create/org-picker.ts @@ -1,12 +1,9 @@ import { randomUUID } from 'node:crypto'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { isCancel, select } from '@voidzero-dev/vite-plus-prompts'; -import { - filterManifestForContext, - type OrgManifest, - type OrgTemplateEntry, -} from './org-manifest.ts'; +import type { OrgManifest, OrgTemplateEntry } from './org-manifest.ts'; +import { filterManifestForContext } from './org-manifest.ts'; export const ORG_PICKER_CANCEL = Symbol('org-picker-cancel'); export const ORG_PICKER_BUILTIN_ESCAPE = Symbol('org-picker-builtin-escape'); @@ -43,7 +40,7 @@ export async function pickOrgTemplate( // they chose. const escapeValue = `__vp_builtin_escape__::${randomUUID()}`; const lookup = new Map(); - const options: { value: string; label: string; hint?: string }[] = filtered.map((entry) => { + const options: Array<{ value: string; label: string; hint?: string }> = filtered.map((entry) => { lookup.set(entry.name, entry); return { value: entry.name, label: entry.name, hint: entry.description }; }); @@ -56,12 +53,12 @@ export async function pickOrgTemplate( : 'Use defaults (monorepo / application / library)'; options.push({ value: escapeValue, label: 'Vite+ built-in templates', hint: builtinHint }); - const picked = await prompts.select({ + const picked = await select({ message: `Pick a template from ${manifest.scope}`, options, }); - if (prompts.isCancel(picked)) { + if (isCancel(picked)) { return ORG_PICKER_CANCEL; } const found = lookup.get(picked); @@ -72,7 +69,7 @@ export async function pickOrgTemplate( // Unreachable: every option's `value` was just registered in `lookup` // a few lines above. Throw rather than masquerade as a cancel — a // missing entry would mean a real internal bug. - throw new Error(`org-picker: prompts.select returned an unregistered value: ${picked}`); + throw new Error(`org-picker: select returned an unregistered value: ${picked}`); } return { kind: 'entry', entry: found }; } @@ -82,10 +79,7 @@ export async function pickOrgTemplate( * error output. Fixed column order so AI agents and scripts can recover * available template names without a `--json` flag. */ -export function formatManifestTable( - manifest: OrgManifest, - isMonorepo: boolean, -): { lines: string[]; filteredCount: number } { +export function formatManifestTable(manifest: OrgManifest, isMonorepo: boolean) { const visible = filterManifestForContext(manifest.templates, isMonorepo); const filteredCount = manifest.templates.length - visible.length; @@ -94,7 +88,7 @@ export function formatManifestTable( 'DESCRIPTION'.length, ...visible.map((entry) => entry.description.length), ); - const lines: string[] = []; + const lines: Array = []; lines.push(` ${'NAME'.padEnd(nameWidth)} ${'DESCRIPTION'.padEnd(descWidth)} TEMPLATE`); for (const entry of visible) { lines.push( diff --git a/packages/cli/src/create/org-resolve.ts b/packages/cli/src/create/org-resolve.ts index b3aa4fa29e..b6e18a789e 100644 --- a/packages/cli/src/create/org-resolve.ts +++ b/packages/cli/src/create/org-resolve.ts @@ -1,19 +1,18 @@ -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { log } from '@voidzero-dev/vite-plus-prompts'; import { findMonorepoRoot } from '../../binding/index.js'; import { hasViteConfig, resolveViteConfig } from '../resolve-vite-config.ts'; +import { errorMessage } from '../utils/error.ts'; import { cancelAndExit } from '../utils/prompts.ts'; +import type { CreateTemplateEntry, OrgManifest, OrgTemplateEntry } from './org-manifest.ts'; import { CreateConfigSchemaError, - type CreateTemplateEntry, filterManifestForContext, isRelativePath, OrgManifestSchemaError, parseOrgScopedSpec, readOrgManifest, validateCreateTemplates, - type OrgManifest, - type OrgTemplateEntry, } from './org-manifest.ts'; import { formatManifestTable, @@ -56,7 +55,7 @@ function printNonInteractiveTable( ): void { const { lines, filteredCount } = formatManifestTable(manifest, isMonorepo); const [firstVisible] = filterManifestForContext(manifest.templates, isMonorepo); - const body: string[] = [ + const body: Array = [ '', `A template name is required when running \`vp create ${orgSpec.scope}\` in non-interactive mode.`, '', @@ -90,7 +89,7 @@ function printNonInteractiveTable( function rejectMonorepoEntryInsideMonorepo(entry: OrgTemplateEntry, isMonorepo: boolean): void { if (entry.monorepo && isMonorepo) { - prompts.log.info( + log.info( 'You are already in a monorepo workspace.\nUse a different template or run this command outside the monorepo', ); cancelAndExit('Cannot create a monorepo inside an existing monorepo', 1); @@ -104,13 +103,16 @@ async function resolveEntry( if (isRelativePath(entry.template)) { const extracted = await ensureOrgPackageExtracted(manifest); const bundledLocalPath = resolveBundledPath(extracted, entry.template); - return { + const resolution: Extract = { kind: 'bundled', bundledLocalPath, entryName: entry.name, scope: manifest.scope, - ...(entry.monorepo === true ? { monorepo: true as const } : {}), }; + if (entry.monorepo === true) { + resolution.monorepo = true; + } + return resolution; } return { kind: 'replaced', templateName: entry.template }; } @@ -142,7 +144,7 @@ export async function resolveOrgManifestForCreate(args: { const message = error instanceof OrgManifestSchemaError ? error.message - : `Failed to read ${orgSpec.scope}/create manifest: ${(error as Error).message}`; + : `Failed to read ${orgSpec.scope}/create manifest: ${errorMessage(error)}`; cancelAndExit(message, 1); } @@ -157,7 +159,7 @@ export async function resolveOrgManifestForCreate(args: { // Scope-only input (`vp create @org`) strongly implies the user // expected the picker. Be explicit about why it didn't engage, so a // later `ERR_NO_BIN` from the package manager doesn't look mysterious. - prompts.log.info( + log.info( `No \`createConfig.templates\` manifest in ${orgSpec.scope}/create — running it as a normal package.`, ); return { kind: 'passthrough' }; @@ -176,7 +178,7 @@ export async function resolveOrgManifestForCreate(args: { // Only the in-monorepo filter can empty the list today; the message // stays in sync if more context-specific filters are added here. if (args.isMonorepo && manifest.templates.every((t) => t.monorepo)) { - prompts.log.info( + log.info( `No templates from ${manifest.packageName} are applicable inside a monorepo — showing Vite+ built-in templates instead.`, ); } @@ -223,7 +225,7 @@ export async function resolveOrgManifestForCreate(args: { export async function getConfiguredCreate( startDir: string, options?: { walkUp?: boolean; throwOnReadError?: boolean }, -): Promise<{ defaultTemplate?: string; templates: CreateTemplateEntry[] }> { +): Promise<{ defaultTemplate?: string; templates: Array }> { const projectRoot = options?.walkUp === false ? startDir : (findMonorepoRoot(startDir) ?? startDir); if (!hasViteConfig(projectRoot)) { @@ -249,7 +251,7 @@ export async function getConfiguredCreate( // Validation errors are intentionally NOT swallowed: a malformed // `create.templates` should be reported, not silently dropped. const templates = validateCreateTemplates(create?.templates); - return { ...(defaultTemplate !== undefined ? { defaultTemplate } : {}), templates }; + return defaultTemplate === undefined ? { templates } : { defaultTemplate, templates }; } /** diff --git a/packages/cli/src/create/org-tarball-reader.ts b/packages/cli/src/create/org-tarball-reader.ts index 41bd3fedb6..9c851f6c25 100644 --- a/packages/cli/src/create/org-tarball-reader.ts +++ b/packages/cli/src/create/org-tarball-reader.ts @@ -1,7 +1,10 @@ import { promisify } from 'node:util'; import { gunzip } from 'node:zlib'; -import { parseTar, type ParsedTarFileItem } from 'nanotar'; +import type { ParsedTarFileItem } from 'nanotar'; +import { parseTar } from 'nanotar'; + +import { errorCode } from '../utils/error.ts'; const decompress = promisify(gunzip); const TAR_BLOCK_BYTES = 512; @@ -83,7 +86,7 @@ function validateTarRecords(tar: Buffer, limits: typeof ORG_TARBALL_LIMITS): voi export async function parseOrgTarball( bytes: Uint8Array, limits = ORG_TARBALL_LIMITS, -): Promise { +): Promise> { const expandedLimit = Math.min( limits.expandedBytes, Math.max(limits.ratioAllowanceBytes, bytes.byteLength * limits.compressionRatio), @@ -93,7 +96,7 @@ export async function parseOrgTarball( // Node stops decompression as soon as its output exceeds maxOutputLength. tar = await decompress(bytes, { maxOutputLength: expandedLimit }); } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ERR_BUFFER_TOO_LARGE') { + if (errorCode(error) === 'ERR_BUFFER_TOO_LARGE') { throw new Error(`tarball exceeds ${expandedLimit} byte decompressed size limit`, { cause: error, }); @@ -105,9 +108,12 @@ export async function parseOrgTarball( const data = new Uint8Array(tar); return parseTar(data, { filter(entry) { - const attrs = entry.attrs as Record | undefined; + const attrs: unknown = entry.attrs; + const path = attrs && typeof attrs === 'object' && 'path' in attrs ? attrs.path : undefined; + const link = + attrs && typeof attrs === 'object' && 'linkpath' in attrs ? attrs.linkpath : undefined; // Also check stored extended names, before path normalization can shorten them. - for (const name of [entry.name, attrs?.path, attrs?.linkpath]) { + for (const name of [entry.name, path, link]) { if (typeof name === 'string' && Buffer.byteLength(name) > limits.pathBytes) { throw new Error(`tarball entry exceeds ${limits.pathBytes} byte path length limit`); } diff --git a/packages/cli/src/create/org-tarball.ts b/packages/cli/src/create/org-tarball.ts index 4e572bc1e8..9a2a8fba64 100644 --- a/packages/cli/src/create/org-tarball.ts +++ b/packages/cli/src/create/org-tarball.ts @@ -3,6 +3,9 @@ import fs from 'node:fs'; import path from 'node:path'; import { getVpDirs } from '../../binding/index.js'; +import { errorCode } from '../utils/error.ts'; +import type { JsonValue } from '../utils/json-value.ts'; +import { parseJsonValue } from '../utils/json-value.ts'; import { fetchNpmResource } from '../utils/npm-config.ts'; import type { OrgManifest } from './org-manifest.ts'; import { parseOrgTarball } from './org-tarball-reader.ts'; @@ -99,7 +102,7 @@ async function downloadTarball(url: string): Promise { if (!reader) { throw new Error(`tarball response has no body: ${url}`); } - const chunks: Uint8Array[] = []; + const chunks: Array = []; let total = 0; while (true) { const { done, value } = await reader.read(); @@ -136,7 +139,7 @@ async function downloadTarball(url: string): Promise { export async function readPackageJsonFromTarball( tarballUrl: string, integrity?: string, -): Promise { +): Promise { const bytes = await downloadTarball(tarballUrl); verifyIntegrity(bytes, integrity); const entries = await parseOrgTarball(bytes); @@ -146,7 +149,7 @@ export async function readPackageJsonFromTarball( } const text = new TextDecoder().decode(entry.data); try { - return JSON.parse(text) as unknown; + return parseJsonValue(text); } catch { throw new Error(`invalid package.json in tarball: ${tarballUrl}`); } @@ -179,7 +182,7 @@ export function parseEntryMode(raw: string | undefined): number | undefined { * `package/`). */ export function normalizeEntryName(rawName: string): string | null { - const name = rawName.replace(/^\.\//, '').replace(/\\/g, '/'); + const name = rawName.replace(/^\.\//, '').replaceAll('\\', '/'); if (!name || name === 'package' || name === 'package/') { return null; } @@ -238,7 +241,7 @@ async function extractTarballTo(bytes: Uint8Array, destDir: string): Promise { const parent = path.dirname(destDir); const basename = path.basename(destDir); const prefix = `${basename}${STAGING_SUFFIX_PREFIX}`; - let entries: string[]; + let entries: Array; try { entries = await fs.promises.readdir(parent); } catch { diff --git a/packages/cli/src/create/prompts.ts b/packages/cli/src/create/prompts.ts index fb8d42c661..557d7a76e8 100644 --- a/packages/cli/src/create/prompts.ts +++ b/packages/cli/src/create/prompts.ts @@ -1,7 +1,7 @@ import fs from 'node:fs'; import path from 'node:path'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { isCancel, log, select, text } from '@voidzero-dev/vite-plus-prompts'; import validateNpmPackageName from 'validate-npm-package-name'; import { cancelAndExit } from '../utils/prompts.ts'; @@ -17,12 +17,12 @@ export async function promptPackageNameAndTargetDir( let targetDir: string; if (interactive) { - const selected = await prompts.text({ + const selected = await text({ message: 'Package name:', placeholder: defaultPackageName, defaultValue: defaultPackageName, validate: (value) => { - if (value == null || value.length === 0) { + if (value === null || value === undefined || value.length === 0) { return undefined; } const result = value ? validateNpmPackageName(value) : null; @@ -32,7 +32,7 @@ export async function promptPackageNameAndTargetDir( return result?.errors?.[0] ?? result?.warnings?.[0] ?? 'Invalid package name'; }, }); - if (prompts.isCancel(selected)) { + if (isCancel(selected)) { cancelAndExit(); } packageName = selected; @@ -41,7 +41,7 @@ export async function promptPackageNameAndTargetDir( // --no-interactive: use default packageName = defaultPackageName; targetDir = getProjectDirFromPackageName(packageName); - prompts.log.info(`Using default package name: ${accent(packageName)}`); + log.info(`Using default package name: ${accent(packageName)}`); } return { packageName, targetDir }; @@ -55,19 +55,19 @@ export async function promptTargetDir( let targetDir: string; if (interactive) { - const selected = await prompts.text({ + const selected = await text({ message: 'Target directory:', placeholder: defaultTargetDir, defaultValue: defaultTargetDir, validate: (value) => validateTargetDir(value ?? defaultTargetDir, options?.cwd).error, }); - if (prompts.isCancel(selected)) { + if (isCancel(selected)) { cancelAndExit(); } targetDir = validateTargetDir(selected ?? defaultTargetDir, options?.cwd).directory; } else { targetDir = validateTargetDir(defaultTargetDir, options?.cwd).directory; - prompts.log.info(`Using default target directory: ${accent(targetDir)}`); + log.info(`Using default target directory: ${accent(targetDir)}`); } return targetDir; @@ -131,14 +131,12 @@ export async function checkProjectDirExists(projectDirFullPath: string, interact } const { description, removeLabel } = describeExistingTarget(targetPath, stats); if (!interactive) { - prompts.log.info( - 'Use --directory to specify a different location or remove the directory first', - ); + log.info('Use --directory to specify a different location or remove the directory first'); cancelAndExit(description, 1); } // Handle an existing target that cannot be reused as-is. - const overwrite = await prompts.select({ + const overwrite = await select({ message: `${description}. Please choose how to proceed:`, options: [ { @@ -152,7 +150,7 @@ export async function checkProjectDirExists(projectDirFullPath: string, interact ], }); - if (prompts.isCancel(overwrite)) { + if (isCancel(overwrite)) { cancelAndExit(); } @@ -223,7 +221,7 @@ export function isTargetDirAvailable(projectDirFullPath: string) { return !stats || (stats.isDirectory() && isEmpty(targetPath)); } -function validateTargetDir(input?: string, cwd?: string): { directory: string; error?: string } { +function validateTargetDir(input?: string, cwd?: string) { const value = input?.trim() ?? ''; if (!value) { return { directory: '', error: 'Target directory is required' }; diff --git a/packages/cli/src/create/register-template.ts b/packages/cli/src/create/register-template.ts index 232f5ea554..86eeab9668 100644 --- a/packages/cli/src/create/register-template.ts +++ b/packages/cli/src/create/register-template.ts @@ -3,7 +3,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { log } from '@voidzero-dev/vite-plus-prompts'; import { upsertJsonConfig } from '../../binding/index.js'; import { findViteConfig } from '../resolve-vite-config.ts'; @@ -59,7 +59,7 @@ export async function registerLocalTemplate( const existingEntry = existing.templates.find((t) => t.name === entry.name); if (existingEntry) { if (existingEntry.template !== entry.template) { - prompts.log.warn( + log.warn( `create.templates already has an entry named '${entry.name}' pointing at '${existingEntry.template}'; left unchanged.\n` + `Update it by hand if it should run '${entry.template}' instead.`, ); @@ -67,10 +67,8 @@ export async function registerLocalTemplate( return undefined; } - const nextCreate: { defaultTemplate?: string; templates: CreateTemplateEntry[] } = { - ...(existing.defaultTemplate !== undefined - ? { defaultTemplate: existing.defaultTemplate } - : {}), + const nextCreate = { + ...existing, templates: [...existing.templates, entry], }; @@ -90,7 +88,7 @@ function ensureViteConfig(workspaceRoot: string, silent: boolean): string { `import { defineConfig } from '${VITE_PLUS_NAME}';\n\nexport default defineConfig({});\n`, ); if (!silent) { - prompts.log.success(`✔ Created vite.config.ts in ${displayRelative(configPath)}`); + log.success(`✔ Created vite.config.ts in ${displayRelative(configPath)}`); } return configPath; } @@ -106,7 +104,10 @@ function ensureViteConfig(workspaceRoot: string, silent: boolean): string { * point at a manual edit instead of reporting a registration that never * happened. */ -function writeCreateBlock(configPath: string, create: object): void { +function writeCreateBlock( + configPath: string, + create: Awaited>, +): void { // A unique OS-temp path: a fixed name in the workspace could collide with a // user's own file and be overwritten/deleted by the merge. const tempPath = path.join(os.tmpdir(), `vite-plus-create-register-${randomUUID()}.json`); diff --git a/packages/cli/src/create/templates/builtin.ts b/packages/cli/src/create/templates/builtin.ts index ee96165cd0..c6c1c6a027 100644 --- a/packages/cli/src/create/templates/builtin.ts +++ b/packages/cli/src/create/templates/builtin.ts @@ -1,7 +1,7 @@ import assert from 'node:assert'; import path from 'node:path'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { log } from '@voidzero-dev/vite-plus-prompts'; import colors from 'picocolors'; import type { WorkspaceInfo } from '../../types/index.ts'; @@ -11,7 +11,8 @@ import { setPackageName } from '../utils.ts'; import { executeGeneratorScaffold } from './generator.ts'; import { removeNestedLibraryToolConfig } from './monorepo.ts'; import { runRemoteTemplateCommand } from './remote.ts'; -import { BuiltinTemplate, type BuiltinTemplateInfo, LibraryTemplateRepo } from './types.ts'; +import type { BuiltinTemplateInfo } from './types.ts'; +import { BuiltinTemplate, LibraryTemplateRepo } from './types.ts'; export async function executeBuiltinTemplate( workspaceInfo: WorkspaceInfo, @@ -59,7 +60,7 @@ export async function executeBuiltinTemplate( // Unknown vite: template (e.g. vite:test) — application was already rewritten to create-vite@latest if (templateInfo.command.startsWith('vite:')) { if (!options?.silent) { - prompts.log.error( + log.error( `Unknown builtin template "${templateInfo.command}". Run ${colors.yellow('vp create --list')} to see available templates.`, ); } diff --git a/packages/cli/src/create/templates/bundled.ts b/packages/cli/src/create/templates/bundled.ts index f85018f29e..b84699043e 100644 --- a/packages/cli/src/create/templates/bundled.ts +++ b/packages/cli/src/create/templates/bundled.ts @@ -2,6 +2,7 @@ import assert from 'node:assert'; import path from 'node:path'; import type { WorkspaceInfo } from '../../types/index.ts'; +import { errorCode } from '../../utils/error.ts'; import type { ExecutionWithProjectDir } from '../command.ts'; import { copyDir, renameFiles, setPackageName } from '../utils.ts'; import type { BuiltinTemplateInfo } from './types.ts'; @@ -22,7 +23,7 @@ export async function executeBundledTemplate( try { copyDir(templateInfo.localPath, destDir); } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + if (errorCode(error) === 'ENOENT') { throw new Error(`bundled template directory not found: ${templateInfo.localPath}`, { cause: error, }); diff --git a/packages/cli/src/create/templates/generator.ts b/packages/cli/src/create/templates/generator.ts index 0ef0570b36..8d60e98c9c 100644 --- a/packages/cli/src/create/templates/generator.ts +++ b/packages/cli/src/create/templates/generator.ts @@ -1,10 +1,11 @@ import fs from 'node:fs'; import path from 'node:path'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { isCancel, log, text } from '@voidzero-dev/vite-plus-prompts'; import { createCatalogDependencyResolver, supportsCatalog } from '../../migration/migrator.ts'; import type { WorkspaceInfo } from '../../types/index.ts'; +import { isStringRecord, isObjectValue } from '../../utils/json-value.ts'; import { editJsonFile } from '../../utils/json.ts'; import { templatesDir } from '../../utils/path.ts'; import { readYamlFile } from '../../utils/yaml.ts'; @@ -19,18 +20,18 @@ export async function executeGeneratorScaffold( options?: { silent?: boolean }, ): Promise { if (!options?.silent) { - prompts.log.step('Creating generator scaffold...'); + log.step('Creating generator scaffold...'); } let description: string | undefined; if (templateInfo.interactive) { const defaultDescription = 'Generate new components for our monorepo'; - const descPrompt = await prompts.text({ + const descPrompt = await text({ message: 'Description:', placeholder: defaultDescription, defaultValue: defaultDescription, }); - if (!prompts.isCancel(descPrompt)) { + if (!isCancel(descPrompt)) { description = descPrompt; } } @@ -51,14 +52,18 @@ export async function executeGeneratorScaffold( workspaceInfo.downloadPackageManager.version, ) : undefined; - const { catalog } = readYamlFile(path.join(templatesDir, 'monorepo/pnpm-workspace.yaml')) as { - catalog: Record; - }; + const { catalog } = readYamlFile(path.join(templatesDir, 'monorepo/pnpm-workspace.yaml')) ?? {}; + if (!isStringRecord(catalog)) { + throw new TypeError('Expected the monorepo template to define a package catalog'); + } editJsonFile(path.join(fullPath, 'package.json'), (pkg) => { pkg.name = templateInfo.packageName; // Keep catalog references only when the target workspace can resolve them. // Missing entries use the same ranges as the bundled monorepo template. - const devDependencies = pkg.devDependencies as Record; + const devDependencies = pkg.devDependencies; + if (!isObjectValue(devDependencies)) { + throw new TypeError('Invalid generator template devDependencies'); + } for (const [name, spec] of Object.entries(devDependencies)) { if (spec === 'catalog:' && catalogResolver?.(spec, name) === undefined && catalog[name]) { devDependencies[name] = catalog[name]; @@ -71,7 +76,7 @@ export async function executeGeneratorScaffold( }); if (!options?.silent) { - prompts.log.success('Generator scaffold created'); + log.success('Generator scaffold created'); } return { exitCode: 0, projectDir: templateInfo.targetDir }; } diff --git a/packages/cli/src/create/templates/monorepo.ts b/packages/cli/src/create/templates/monorepo.ts index bcd8694826..a0e5035d1a 100644 --- a/packages/cli/src/create/templates/monorepo.ts +++ b/packages/cli/src/create/templates/monorepo.ts @@ -2,12 +2,15 @@ import assert from 'node:assert'; import fs from 'node:fs'; import path from 'node:path'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { log } from '@voidzero-dev/vite-plus-prompts'; import { removeConfigKey } from '../../../binding/index.js'; import { rewriteMonorepoProject, supportsCatalog } from '../../migration/migrator.ts'; -import { PackageManager, type WorkspaceInfo } from '../../types/index.ts'; -import { editJsonFile } from '../../utils/json.ts'; +import type { WorkspaceInfo } from '../../types/index.ts'; +import { PackageManager } from '../../types/index.ts'; +import type { JsonObject } from '../../utils/json-value.ts'; +import { isObjectValue } from '../../utils/json-value.ts'; +import { editJsonFile, readJsonFile } from '../../utils/json.ts'; import { getScopeFromPackageName } from '../../utils/package.ts'; import { templatesDir } from '../../utils/path.ts'; import { editYamlFile, readYamlFile } from '../../utils/yaml.ts'; @@ -15,7 +18,8 @@ import type { ExecutionWithProjectDir } from '../command.ts'; import { discoverTemplate } from '../discovery.ts'; import { copyDir, formatDisplayTargetDir, renameFiles, setPackageName } from '../utils.ts'; import { runRemoteTemplateCommand } from './remote.ts'; -import { type BuiltinTemplateInfo, LibraryTemplateRepo } from './types.ts'; +import type { BuiltinTemplateInfo } from './types.ts'; +import { LibraryTemplateRepo } from './types.ts'; export const InitialMonorepoAppDir = 'apps/website'; @@ -32,8 +36,8 @@ export async function executeMonorepoTemplate( const fullPath = path.join(workspaceInfo.rootDir, templateInfo.targetDir); if (!options?.silent) { - prompts.log.info(`Target directory: ${formatDisplayTargetDir(templateInfo.targetDir)}`); - prompts.log.step('Creating Vite+ monorepo...'); + log.info(`Target directory: ${formatDisplayTargetDir(templateInfo.targetDir)}`); + log.step('Creating Vite+ monorepo...'); } // Copy template files @@ -88,12 +92,12 @@ export async function executeMonorepoTemplate( } if (!options?.silent) { - prompts.log.success('Monorepo template created'); + log.success('Monorepo template created'); } // Automatically create a default application in apps/website if (!options?.silent) { - prompts.log.step('Creating default application in apps/website...'); + log.step('Creating default application in apps/website...'); } const appTemplateInfo = discoverTemplate( @@ -110,7 +114,7 @@ export async function executeMonorepoTemplate( ); if (appResult.exitCode !== 0) { - prompts.log.error(`Failed to create default application: ${appResult.exitCode}`); + log.error(`Failed to create default application: ${appResult.exitCode}`); return appResult; } @@ -132,7 +136,7 @@ export async function executeMonorepoTemplate( // Automatically create a default library in packages/utils if (!options?.silent) { - prompts.log.step('Creating default library in packages/utils...'); + log.step('Creating default library in packages/utils...'); } const libraryDir = 'packages/utils'; const libraryTemplateInfo = discoverTemplate(LibraryTemplateRepo, [libraryDir], workspaceInfo); @@ -144,7 +148,7 @@ export async function executeMonorepoTemplate( options?.silent ?? false, ); if (libraryResult.exitCode !== 0) { - prompts.log.error(`Failed to create default library, exit code: ${libraryResult.exitCode}`); + log.error(`Failed to create default library, exit code: ${libraryResult.exitCode}`); return libraryResult; } @@ -212,13 +216,12 @@ export function alignMonorepoTypeScriptVersion( ): void { const appPackagePath = path.join(appProjectPath, 'package.json'); const libraryPackagePath = path.join(libraryProjectPath, 'package.json'); - const libraryPackage = JSON.parse(fs.readFileSync(libraryPackagePath, 'utf8')) as { - dependencies?: Record; - devDependencies?: Record; - optionalDependencies?: Record; - peerDependencies?: Record; - }; - const typescriptVersion = libraryPackage.devDependencies?.typescript; + const libraryPackage = readJsonFile(libraryPackagePath); + const devDependencies = libraryPackage.devDependencies; + const typescriptVersion = + isObjectValue(devDependencies) && typeof devDependencies.typescript === 'string' + ? devDependencies.typescript + : undefined; const catalogCapable = supportsCatalog(packageManager, packageManagerVersion, true); let nodeTypesVersion: string | undefined; @@ -228,8 +231,9 @@ export function alignMonorepoTypeScriptVersion( 'optionalDependencies', 'peerDependencies', ] as const) { - const version = libraryPackage[field]?.['@types/node']; - if (version) { + const deps = libraryPackage[field]; + const version = isObjectValue(deps) ? deps['@types/node'] : undefined; + if (typeof version === 'string' && version) { nodeTypesVersion = version; break; } @@ -264,7 +268,7 @@ export function alignMonorepoTypeScriptVersion( const catalogPath = path.join(workspaceRootPath, catalogFile); if (fs.existsSync(catalogPath)) { const workspaceConfig = readYamlFile(catalogPath) as { - catalog?: Record; + catalog?: JsonObject; } | null; for (const [name, version] of Object.entries(catalogVersions)) { if (workspaceConfig?.catalog?.[name] !== undefined) { diff --git a/packages/cli/src/create/templates/remote.ts b/packages/cli/src/create/templates/remote.ts index 07cc3e1c49..e64be4cc62 100644 --- a/packages/cli/src/create/templates/remote.ts +++ b/packages/cli/src/create/templates/remote.ts @@ -1,10 +1,11 @@ -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { log } from '@voidzero-dev/vite-plus-prompts'; import colors from 'picocolors'; import type { WorkspaceInfo } from '../../types/index.ts'; import { getLocalVpCommand, runCommand, runCommandSilently } from '../../utils/command.ts'; import { checkNpmPackageExists } from '../../utils/package.ts'; -import { type ExecutionWithProjectDir, runCommandAndDetectProjectDir } from '../command.ts'; +import type { ExecutionWithProjectDir } from '../command.ts'; +import { runCommandAndDetectProjectDir } from '../command.ts'; import type { TemplateInfo } from './types.ts'; const { gray, yellow } = colors; @@ -16,10 +17,10 @@ export async function executeRemoteTemplate( ): Promise { const silent = options?.silent ?? false; if (!silent) { - prompts.log.step('Generating project…'); + log.step('Generating project…'); } - let isGitHubTemplate = templateInfo.command === 'degit'; + const isGitHubTemplate = templateInfo.command === 'degit'; let result: ExecutionWithProjectDir; if (templateInfo.command === 'node') { // Template found locally - execute directly @@ -27,7 +28,7 @@ export async function executeRemoteTemplate( const args = templateInfo.args; const envs = templateInfo.envs; if (!silent) { - prompts.log.info(`Running: ${gray(`${command} ${args.join(' ')}`)}`); + log.info(`Running: ${gray(`${command} ${args.join(' ')}`)}`); } result = await runCommandAndDetectProjectDir( { command, args, cwd: workspaceInfo.rootDir, envs }, @@ -41,7 +42,7 @@ export async function executeRemoteTemplate( const packageExists = await checkNpmPackageExists(templateInfo.command); if (!packageExists) { if (!silent) { - prompts.log.error( + log.error( `Template "${templateInfo.command}" not found on npm. Run ${yellow('vp create --list')} to see available templates.`, ); } @@ -60,14 +61,14 @@ export async function executeRemoteTemplate( const exitCode = result.exitCode; // Provide troubleshooting tips if (exitCode === 127) { - prompts.log.info(yellow('\nTroubleshooting:')); - prompts.log.info(` ${gray('•')} Command not found. Make sure Node.js is installed`); - // prompts.log.info(` ${gray('•')} Check if ${command} is available in PATH`); + log.info(yellow('\nTroubleshooting:')); + log.info(` ${gray('•')} Command not found. Make sure Node.js is installed`); + // log.info(` ${gray('•')} Check if ${command} is available in PATH`); } else if (isGitHubTemplate && exitCode !== 0) { - prompts.log.info(yellow('\nTroubleshooting:')); - prompts.log.info(` ${gray('•')} Make sure the GitHub repository exists`); - prompts.log.info(` ${gray('•')} Check your internet connection`); - prompts.log.info(` ${gray('•')} Repository might be private (requires authentication)`); + log.info(yellow('\nTroubleshooting:')); + log.info(` ${gray('•')} Make sure the GitHub repository exists`); + log.info(` ${gray('•')} Check your internet connection`); + log.info(` ${gray('•')} Repository might be private (requires authentication)`); } return result; } @@ -95,7 +96,7 @@ export async function runRemoteTemplateCommand( // The global `vp` may be an older release and would pick its own Node.js outside a project. const { command, args } = getLocalVpCommand(dlxArgs); if (!silent) { - prompts.log.info(`Running: ${gray(`vp ${dlxArgs.join(' ')}`)}`); + log.info(`Running: ${gray(`vp ${dlxArgs.join(' ')}`)}`); } if (detectCreatedProjectDir) { return await runCommandAndDetectProjectDir( @@ -117,23 +118,21 @@ export function autoFixRemoteTemplateCommand( let packageName = templateInfo.command; const indexOfAt = packageName.indexOf('@', 2); if (indexOfAt !== -1) { - packageName = packageName.substring(0, indexOfAt); + packageName = packageName.slice(0, indexOfAt); } if (packageName === 'create-vite') { // don't run dev server after installation // https://github.com/vitejs/vite/blob/main/packages/create-vite/src/index.ts#L46 - templateInfo.args.push('--no-immediate'); - // don't present rolldown option to users - templateInfo.args.push('--no-rolldown'); + // Don't present the Rolldown option. + templateInfo.args.push('--no-immediate', '--no-rolldown'); } else if (packageName === '@tanstack/cli') { // ensure create command is used if (templateInfo.args[0] !== 'create') { templateInfo.args.unshift('create'); } // don't run npm install after project creation - templateInfo.args.push('--no-install'); - // don't setup toolchain automatically - templateInfo.args.push('--no-toolchain'); + // Skip automatic toolchain setup. + templateInfo.args.push('--no-install', '--no-toolchain'); } else if (packageName === 'sv') { // ensure create command is used if (templateInfo.args[0] !== 'create') { diff --git a/packages/cli/src/create/templates/types.ts b/packages/cli/src/create/templates/types.ts index ab03773549..3dc11ca96e 100644 --- a/packages/cli/src/create/templates/types.ts +++ b/packages/cli/src/create/templates/types.ts @@ -18,7 +18,7 @@ export type TemplateType = (typeof TemplateType)[keyof typeof TemplateType]; export interface TemplateInfo { command: string; - args: string[]; + args: Array; envs: NodeJS.ProcessEnv; type: TemplateType; // The parent directory of the generated package, only for monorepo diff --git a/packages/cli/src/create/utils.ts b/packages/cli/src/create/utils.ts index be28eacc1a..ca9b996576 100644 --- a/packages/cli/src/create/utils.ts +++ b/packages/cli/src/create/utils.ts @@ -41,7 +41,7 @@ export function ensureCreateCatalogEntries( const pkg = readJsonFile(packageJsonPath) as Partial< Record<'dependencies' | 'devDependencies' | 'optionalDependencies', Record> >; - const versions: Record = { + const versions: NonNullable = { ...VITE_PLUS_OVERRIDE_PACKAGES, [VITE_PLUS_NAME]: VITE_PLUS_VERSION, }; @@ -190,11 +190,7 @@ export function copyDir(srcDir: string, destDir: string) { * ./foo/bar/@scope/my-package -> { directory: './foo/bar/my-package', packageName: '@scope/my-package' } * ``` */ -export function formatTargetDir(input: string): { - directory: string; - packageName: string; - error?: string; -} { +export function formatTargetDir(input: string) { let targetDir = path.normalize(input.trim()); // "." or "./" means current directory — valid directory, but no package name derivable @@ -290,12 +286,12 @@ export function ensureDefaultGitignoreEntries(projectDir: string): void { const gitignorePath = path.join(projectDir, '.gitignore'); let content = ''; try { - content = fs.readFileSync(gitignorePath, 'utf-8'); + content = fs.readFileSync(gitignorePath, 'utf8'); } catch { // No existing .gitignore — we'll write a fresh one below. } - const lines: string[] = []; + const lines: Array = []; if (!hasNodeModulesGitignoreLine(content)) { lines.push('node_modules'); } @@ -325,7 +321,7 @@ function hasGitignoreLine(content: string, line: string): boolean { function appendGitignoreLines( gitignorePath: string, content: string, - lines: readonly string[], + lines: ReadonlyArray, ): void { if (lines.length === 0) { return; @@ -353,7 +349,7 @@ export function ensureGitignoreVsCodeEditorConfigs(projectDir: string): void { const gitignorePath = path.join(projectDir, '.gitignore'); let content: string; try { - content = fs.readFileSync(gitignorePath, 'utf-8'); + content = fs.readFileSync(gitignorePath, 'utf8'); } catch { return; } diff --git a/packages/cli/src/define-config.ts b/packages/cli/src/define-config.ts index 4581266d3d..504453d6da 100644 --- a/packages/cli/src/define-config.ts +++ b/packages/cli/src/define-config.ts @@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs'; import { createRequire } from 'node:module'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { types } from 'node:util'; import { ignoreInput, ignoreOutput } from '@voidzero-dev/vite-task-client'; import type { OxfmtConfig } from 'oxfmt'; @@ -15,14 +16,16 @@ import type { UserConfig, } from 'vite'; import { resolveConfig, searchForWorkspaceRoot } from 'vite'; +import type { + ConfigEnv, + TestProjectConfiguration, + UserProjectConfigExport, + UserProjectConfigFn, + UserWorkspaceConfig, +} from 'vitest/config'; import { defineConfig as viteDefineConfig, defineProject as viteDefineProject, - type ConfigEnv, - type TestProjectConfiguration, - type UserProjectConfigExport, - type UserProjectConfigFn, - type UserWorkspaceConfig, } from 'vitest/config'; import type { InlineConfig as VitestInlineConfig } from 'vitest/node'; @@ -31,6 +34,8 @@ import type { PackUserConfig } from './pack.ts'; import type { RunConfig } from './run-config.ts'; import type { StagedConfig } from './staged-config.ts'; import { CONFIG_METADATA_ENV, VITEST_VERSION } from './utils/constants.ts'; +import type { JsonObject } from './utils/json-value.ts'; +import { parseJsonObject, isObjectValue } from './utils/json-value.ts'; import { VITEST_RESOLVER_PACKAGES } from './utils/vitest-ecosystem.ts'; declare module 'vite' { @@ -62,7 +67,7 @@ declare module 'vite' { lint?: boolean; }; - pack?: PackUserConfig | PackUserConfig[]; + pack?: PackUserConfig | Array; /** * Default target directory for `vp dev` / `build` / `preview` / `pack` @@ -101,7 +106,7 @@ declare module 'vite' { * `template` resolves like any specifier (a workspace package name, a * relative `./path`, a `vite:*` builtin, a GitHub URL, or an npm package). */ - templates?: CreateTemplateEntry[]; + templates?: Array; }; /** @@ -165,6 +170,7 @@ const vitePlusRequire = createRequire( * `pathToFileURL(__filename).href` in the CJS bundle, so it is a valid file URL * in both. */ +// oxlint-disable-next-line unicorn/prefer-import-meta-properties -- The CommonJS build rewrites import.meta.url for this dual-format module. const vitePlusModuleFile = fileURLToPath(import.meta.url); /** @@ -188,23 +194,30 @@ function getVitestAnchor(): string | null { return vitestAnchor; } +function isAliasArray( + value: ReadonlyArray | Record | undefined, +): value is ReadonlyArray { + return Array.isArray(value); +} + // The bundled manifest is fixed for this module's lifetime. Share it across // browser entry points and project configs, just like the cached package path. -let vitestExports: Record | undefined; +let vitestExports: JsonObject | undefined; function getVitestImportTarget(id: string): string { const anchor = getVitestAnchor(); if (!anchor) { throw new Error('Cannot resolve the bundled Vitest package. Reinstall vite-plus.'); } - vitestExports ??= ( - JSON.parse(readFileSync(anchor, 'utf8')) as { - exports: Record; + if (!vitestExports) { + const { exports } = parseJsonObject(readFileSync(anchor, 'utf8')); + if (!isObjectValue(exports)) { + throw new Error('Expected the bundled Vitest manifest to define exports.'); } - ).exports; + vitestExports = exports; + } let target = vitestExports[id === 'vitest' ? '.' : `.${id.slice('vitest'.length)}`]; - while (target && typeof target === 'object') { - const conditions = target as Record; - target = conditions.import ?? conditions.default; + while (isObjectValue(target)) { + target = target.import ?? target.default; } if (typeof target !== 'string' || !target.startsWith('./')) { throw new Error(`The bundled Vitest has no ESM export for ${id}.`); @@ -298,10 +311,14 @@ function vitePlusVitestResolverPlugin(): PluginOption { // resolver, without user resolveId hooks. Keep its runtime entry points // on the same graph as the browser runner in isolated installs. const aliases = config.resolve?.alias; - const entries: Alias[] = Array.isArray(aliases) + const entries: Array = isAliasArray(aliases) ? [...aliases] : Object.entries(aliases ?? {}).map(([find, replacement]) => ({ find, replacement })); - const runtimeRequire = createRequire(getVitestAnchor()!); + const anchor = getVitestAnchor(); + if (!anchor) { + throw new Error('Cannot resolve the bundled Vitest package. Reinstall vite-plus.'); + } + const runtimeRequire = createRequire(anchor); const targets = new Map( [ 'vitest', @@ -347,7 +364,8 @@ function vitePlusVitestResolverPlugin(): PluginOption { // Vite merges plugin arrays from inherited and referenced configs. Remove // duplicate Vite+ hooks before it creates the server's plugin container. const seen = new Set(); - const plugins = config.plugins as Plugin[]; + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Vite exposes resolved plugins as readonly; deduplication must preserve the array identity. + const plugins = config.plugins as Array; const unique = plugins.filter((plugin) => { if (!VITE_PLUS_TEST_PLUGIN_NAMES.has(plugin.name)) { return true; @@ -440,11 +458,11 @@ export const AUTO_INLINE_DEPS: ReadonlyArray = [ * Callers may share installation results for the same root within one config load. */ export function computeAutoInlineList( - existingInline: (string | RegExp)[] | true | undefined, + existingInline: Array | true | undefined, projectRoot: string, _createRequire: (from: string) => { resolve: (id: string) => string } = createRequire, installedPackages = new Map(), -): (string | RegExp)[] | null { +): Array | null { // User opted into "inline everything" — don't touch. if (existingInline === true) { return null; @@ -454,10 +472,10 @@ export function computeAutoInlineList( let projectRequire: ReturnType | undefined; // Start from a copy of the user-supplied array (or a fresh array when // none was provided) so the originating user-config object is not mutated. - const merged: (string | RegExp)[] = Array.isArray(existingInline) ? [...existingInline] : []; + const merged: Array = Array.isArray(existingInline) ? [...existingInline] : []; for (const pkg of AUTO_INLINE_DEPS) { // Skip if already covered by a string or regexp entry. - if (merged.some((entry) => entry === pkg || (entry instanceof RegExp && entry.test(pkg)))) { + if (merged.some((entry) => entry === pkg || (types.isRegExp(entry) && entry.test(pkg)))) { continue; } let installed = installedPackages.get(pkg); @@ -489,7 +507,7 @@ function vitePlusAutoInlineMatcherPlugin(): PluginOption { let isVitestServer = false; const installedByRoot = new Map>(); type TestConfig = Pick; - function inlineList(existing: (string | RegExp)[] | true | undefined, root: string) { + function inlineList(existing: Array | true | undefined, root: string) { root = resolve(root); let installed = installedByRoot.get(root); if (!installed) { @@ -517,7 +535,7 @@ function vitePlusAutoInlineMatcherPlugin(): PluginOption { } const existing = config.resolve?.noExternal; const merged = inlineList( - typeof existing === 'string' || existing instanceof RegExp ? [existing] : existing, + typeof existing === 'string' || types.isRegExp(existing) ? [existing] : existing, projectRoot, ); if (merged !== null) { @@ -642,8 +660,8 @@ function readInstalledCoverageProviderVersion( try { const req = _createRequire(anchor); const pkgJsonPath = req.resolve(`${providerPackageName}/package.json`); - const parsed = JSON.parse(_readFile(pkgJsonPath)) as { version?: string }; - if (parsed.version) { + const parsed = parseJsonObject(_readFile(pkgJsonPath)); + if (typeof parsed.version === 'string' && parsed.version) { return parsed.version; } } catch { @@ -863,7 +881,7 @@ function withoutVitePlusTestPlugins(plugin: PluginOption): PluginOption { return plugin.filter(keepUserPlugin).map(withoutVitePlusTestPlugins); } // Injected plugins are never async, and re-wrapping with `.then` drops own props that tools like Vike look up. - if (plugin instanceof Promise) { + if (types.isPromise(plugin)) { return plugin; } return plugin && VITE_PLUS_TEST_PLUGIN_NAMES.has(plugin.name) ? false : plugin; @@ -917,14 +935,14 @@ function injectPluginIntoProject(project: TestProjectConfiguration): TestProject if (typeof project === 'function') { const wrapped: UserProjectConfigFn = (env: ConfigEnv) => { const result = project(env); - if (result instanceof Promise) { + if (types.isPromise(result)) { return result.then(injectIndependentProject); } return injectIndependentProject(result); }; return wrapped; } - if (project instanceof Promise) { + if (types.isPromise(project)) { return project.then(injectIndependentProject); } if (typeof project === 'object' && project !== null) { @@ -960,13 +978,13 @@ function injectPluginIntoConfig(config: ViteUserConfigExport): ViteUserConfigExp if (typeof config === 'function') { return (env: ConfigEnv) => { const result = config(env); - if (result instanceof Promise) { + if (types.isPromise(result)) { return result.then(injectPlugin); } return injectPlugin(result); }; } - if (config instanceof Promise) { + if (types.isPromise(config)) { return config.then(injectPlugin); } return injectPlugin(config); @@ -979,6 +997,7 @@ function injectPluginIntoConfig(config: ViteUserConfigExport): ViteUserConfigExp * Oxlint rule severity of `'warn'` becomes `string`). */ export function defineConfig(config: T): DefinedViteUserConfig { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Injection preserves the caller’s config overload while Vite returns the broader union. return viteDefineConfig(injectPluginIntoConfig(config)) as DefinedViteUserConfig; } @@ -992,10 +1011,10 @@ function injectPluginIntoProjectExport(config: UserProjectConfigExport): UserPro if (typeof config === 'function') { return (env: ConfigEnv) => { const result = config(env); - return result instanceof Promise ? result.then(injectPlugin) : injectPlugin(result); + return types.isPromise(result) ? result.then(injectPlugin) : injectPlugin(result); }; } - if (config instanceof Promise) { + if (types.isPromise(config)) { return config.then(injectPlugin); } return injectPlugin(config); @@ -1014,6 +1033,7 @@ export function defineProject(config: Promise): Promise void, - patchPlugins?: (plugins: Plugin[]) => void, + patchPlugins?: (plugins: Array) => void, internalOptions?: { rootBase?: string }, ) => Promise; @@ -1125,16 +1145,18 @@ export async function resolveConfigFromFile( ); } -export function lazyPlugins(cb: () => PluginOption[]): PluginOption[] | undefined; -export function lazyPlugins(cb: () => Promise): PluginOption[] | undefined; +export function lazyPlugins(cb: () => Array): Array | undefined; +export function lazyPlugins( + cb: () => Promise>, +): Array | undefined; export function lazyPlugins( - cb: () => PluginOption[] | Promise, -): PluginOption[] | undefined { + cb: () => Array | Promise>, +): Array | undefined { if (process.env[CONFIG_METADATA_ENV] === '1') { return undefined; } const result = cb(); - if (result instanceof Promise) { + if (types.isPromise(result)) { return [result]; } return result; diff --git a/packages/cli/src/help.ts b/packages/cli/src/help.ts index 8b4866ebf6..db101ef6c4 100644 --- a/packages/cli/src/help.ts +++ b/packages/cli/src/help.ts @@ -1,5 +1,7 @@ import { documentationUrl } from './utils/documentation.ts'; -import { renderCliDoc, type CliDoc } from './utils/help.ts'; +import type { CliDoc } from './utils/help.ts'; +import { renderCliDoc } from './utils/help.ts'; +import { hasOwnKey } from './utils/object.ts'; import { log, printHeader } from './utils/terminal.ts'; // Tool-backed docs mirror upstream even when Vite+ overrides the documented behavior. @@ -1129,13 +1131,13 @@ const commandHelpDocs = { }, } satisfies Record; -export function maybePrintCommandHelp(args: readonly string[]): boolean { +export function maybePrintCommandHelp(args: ReadonlyArray): boolean { const command = args[0] === 'format' ? 'fmt' : args[0]; - const doc = commandHelpDocs[command as keyof typeof commandHelpDocs]; - if (!doc) { + if (!hasOwnKey(commandHelpDocs, command)) { return false; } + const doc = commandHelpDocs[command]; const commandArgs = args.slice(1); const isTopLevelHelp = commandArgs.length === 1 && (commandArgs[0] === '-h' || commandArgs[0] === '--help'); diff --git a/packages/cli/src/hooks/bin.ts b/packages/cli/src/hooks/bin.ts index d21c5d8ef9..07798770ab 100644 --- a/packages/cli/src/hooks/bin.ts +++ b/packages/cli/src/hooks/bin.ts @@ -28,4 +28,4 @@ async function main() { } } -void main(); +await main(); diff --git a/packages/cli/src/index.cts b/packages/cli/src/index.cts index bb154a1da0..686df9cbe7 100644 --- a/packages/cli/src/index.cts +++ b/packages/cli/src/index.cts @@ -1,4 +1,8 @@ -const vite = require('vite'); +/* oxlint-disable typescript/no-require-imports -- This is the synchronous CommonJS entry for the require export condition. */ +import vite = require('vite'); +import vitestConfig = require('vitest/config'); +import vitePlusConfig = require('./define-config'); +/* oxlint-enable typescript/no-require-imports */ const { configDefaults, @@ -6,14 +10,9 @@ const { defaultBrowserPort, defaultExclude, defaultInclude, -} = require('vitest/config'); +} = vitestConfig; -const { - defineConfig, - defineProject, - lazyPlugins, - resolveConfigFromFile, -} = require('./define-config'); +const { defineConfig, defineProject, lazyPlugins, resolveConfigFromFile } = vitePlusConfig; module.exports = { ...vite, diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index d8f7b7fff8..6f872913dc 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -6,6 +6,7 @@ export { } from './define-config.ts'; export type { ResolveConfigFromFileOptions } from './define-config.ts'; +// oxlint-disable-next-line import/export -- The explicit Vite+ defineConfig export takes precedence over Vite's star export. export * from 'vite'; export { diff --git a/packages/cli/src/init-config.ts b/packages/cli/src/init-config.ts index eae56746a3..a527254b9a 100644 --- a/packages/cli/src/init-config.ts +++ b/packages/cli/src/init-config.ts @@ -5,15 +5,16 @@ import { hasConfigKey, mergeJsonConfig } from '../binding/index.js'; import { createDefaultVitePlusLintConfig } from './oxlint-plugin-config.ts'; import { fmt as resolveFmt } from './resolve-fmt.ts'; import { BASEURL_TSCONFIG_WARNING, VITE_CONFIG_FILES, VITE_PLUS_NAME } from './utils/constants.ts'; +import { hasOwnKey } from './utils/object.ts'; import { warnMsg } from './utils/terminal.ts'; interface InitCommandSpec { configKey: 'lint' | 'fmt'; - triggerFlags: string[]; - defaultConfigFiles: string[]; + triggerFlags: Array; + defaultConfigFiles: Array; } -const INIT_COMMAND_SPECS: Record = { +const INIT_COMMAND_SPECS = { lint: { configKey: 'lint', triggerFlags: ['--init'], @@ -24,7 +25,7 @@ const INIT_COMMAND_SPECS: Record = { triggerFlags: ['--init', '--migrate'], defaultConfigFiles: ['.oxfmtrc.json', '.oxfmtrc.jsonc'], }, -}; +} satisfies Record; function normalizeInitCommand(command: string | undefined): string | undefined { return command === 'format' ? 'fmt' : command; @@ -44,12 +45,12 @@ export interface ApplyToolInitResult { viteConfigPath?: string; } -function optionTerminatorIndex(args: string[]): number { +function optionTerminatorIndex(args: Array): number { const index = args.indexOf('--'); return index === -1 ? args.length : index; } -function hasTriggerFlag(args: string[], triggerFlags: string[]): boolean { +function hasTriggerFlag(args: Array, triggerFlags: Array): boolean { const limit = optionTerminatorIndex(args); for (let i = 0; i < limit; i++) { const arg = args[i]; @@ -60,7 +61,7 @@ function hasTriggerFlag(args: string[], triggerFlags: string[]): boolean { return false; } -function extractConfigPathArg(args: string[]): string | null { +function extractConfigPathArg(args: Array): string | null { const limit = optionTerminatorIndex(args); for (let i = 0; i < limit; i++) { const arg = args[i]; @@ -80,8 +81,8 @@ function extractConfigPathArg(args: string[]): string | null { function resolveGeneratedConfigPath( projectPath: string, - args: string[], - defaultConfigFiles: readonly string[], + args: Array, + defaultConfigFiles: ReadonlyArray, ): string | null { const configArg = extractConfigPathArg(args); if (configArg) { @@ -146,9 +147,9 @@ async function vpFmt(cwd: string, filePath: string): Promise { } } -function resolveInitSpec(command: string | undefined, args: string[]): InitCommandSpec | null { +function resolveInitSpec(command: string | undefined, args: Array): InitCommandSpec | null { const normalizedCommand = normalizeInitCommand(command); - if (!normalizedCommand) { + if (!normalizedCommand || !hasOwnKey(INIT_COMMAND_SPECS, normalizedCommand)) { return null; } const spec = INIT_COMMAND_SPECS[normalizedCommand]; @@ -160,7 +161,7 @@ function resolveInitSpec(command: string | undefined, args: string[]): InitComma export function inspectInitCommand( command: string | undefined, - args: string[], + args: Array, projectPath = process.cwd(), ): InitCommandInspection { const spec = resolveInitSpec(command, args); @@ -193,14 +194,17 @@ export function inspectInitCommand( */ export async function applyToolInitConfigToViteConfig( command: string | undefined, - args: string[], + args: Array, projectPath = process.cwd(), ): Promise { const inspection = inspectInitCommand(command, args, projectPath); if (!inspection.handled || !inspection.configKey) { return { handled: false }; } - const spec = INIT_COMMAND_SPECS[normalizeInitCommand(command) as keyof typeof INIT_COMMAND_SPECS]; + const spec = resolveInitSpec(command, args); + if (!spec) { + return { handled: false }; + } const viteConfigPath = ensureViteConfigPath(projectPath); const generatedConfigPath = resolveGeneratedConfigPath( projectPath, diff --git a/packages/cli/src/migration/__tests__/__snapshots__/migrator.spec.ts.snap b/packages/cli/src/migration/__tests__/__snapshots__/migrator.spec.ts.snap index 81cf897e63..8b6a877d03 100644 --- a/packages/cli/src/migration/__tests__/__snapshots__/migrator.spec.ts.snap +++ b/packages/cli/src/migration/__tests__/__snapshots__/migrator.spec.ts.snap @@ -1,6 +1,6 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html -exports[`rewritePackageJson > should rewrite package.json scripts and extract staged config 1`] = ` +exports[`rewritePackageJson > should rewrite package.json scripts and extract staged config > package manifest 1`] = ` { "lint-staged": { "*.js": [ @@ -56,7 +56,7 @@ exports[`rewritePackageJson > should rewrite package.json scripts and extract st } `; -exports[`rewritePackageJson > should rewrite package.json scripts and extract staged config 2`] = ` +exports[`rewritePackageJson > should rewrite package.json scripts and extract staged config > staged commands 1`] = ` { "*.js": [ "vp lint --fix --type-aware", diff --git a/packages/cli/src/migration/__tests__/bun-catalog-file-protocol.spec.ts b/packages/cli/src/migration/__tests__/bun-catalog-file-protocol.spec.ts index e86f365d4f..5e0428dbdf 100644 --- a/packages/cli/src/migration/__tests__/bun-catalog-file-protocol.spec.ts +++ b/packages/cli/src/migration/__tests__/bun-catalog-file-protocol.spec.ts @@ -4,11 +4,14 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { PackageManager, type WorkspaceInfo } from '../../types/index.js'; +import type { WorkspaceInfo } from '../../types/index.ts'; +import { PackageManager } from '../../types/index.ts'; +import { readJsonFile as readJson } from '../../utils/json.ts'; +import { fixtureObject } from './fixture-json.ts'; // Mock with file: protocol paths (simulating VP_OVERRIDE_PACKAGES in CI) -vi.mock('../../utils/constants.js', async (importOriginal) => { - const mod = await importOriginal(); +vi.mock(import('../../utils/constants.ts'), async (importOriginal) => { + const mod = await importOriginal(); return { ...mod, VITE_PLUS_VERSION: 'file:/tmp/tgz/vite-plus-0.0.0.tgz', @@ -19,7 +22,7 @@ vi.mock('../../utils/constants.js', async (importOriginal) => { }; }); -const { rewriteMonorepo, rewritePackageJson } = await import('../migrator.js'); +const { rewriteMonorepo, rewritePackageJson } = await import('../migrator.ts'); function makeWorkspaceInfo(rootDir: string, packageManager: PackageManager): WorkspaceInfo { return { @@ -42,10 +45,6 @@ function makeWorkspaceInfo(rootDir: string, packageManager: PackageManager): Wor }; } -function readJson(filePath: string): Record { - return JSON.parse(fs.readFileSync(filePath, 'utf8')); -} - describe('rewriteMonorepo bun catalog with file: protocol', () => { let tmpDir: string; @@ -71,11 +70,11 @@ describe('rewriteMonorepo bun catalog with file: protocol', () => { const pkg = readJson(path.join(tmpDir, 'package.json')); // catalog should not contain file: entries - const catalog = (pkg.catalog ?? {}) as Record; + const catalog = fixtureObject(pkg.catalog ?? {}); expect(catalog.vite).toBeUndefined(); expect(catalog.vitest).toBeUndefined(); // overrides should use file: paths directly, not catalog: - const overrides = pkg.overrides as Record; + const overrides = fixtureObject(pkg.overrides); expect(overrides.vite).toBe('file:/tmp/tgz/voidzero-dev-vite-plus-core-0.0.0.tgz'); expect(overrides.vitest).toBeUndefined(); expect(overrides['@voidzero-dev/vite-plus-core']).toBe( @@ -107,21 +106,22 @@ describe('rewriteMonorepo bun catalog with file: protocol', () => { rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.bun), true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - workspaces: { - catalog: Record; - catalogs: Record>; - }; - overrides: Record; - devDependencies: Record; - }; - expect(pkg.workspaces.catalog?.vite).toBeUndefined(); - expect(pkg.workspaces.catalog?.vitest).toBeUndefined(); - expect(pkg.workspaces.catalogs.build.vite).toBe('^7.0.0'); - expect(pkg.workspaces.catalogs.build.vitest).toBe('^4.0.0'); - expect(pkg.workspaces.catalogs.build.tsdown).toBeUndefined(); - expect(pkg.overrides.vite).toBe('file:/tmp/tgz/voidzero-dev-vite-plus-core-0.0.0.tgz'); - expect(pkg.devDependencies.vite).toBe('file:/tmp/tgz/voidzero-dev-vite-plus-core-0.0.0.tgz'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + const workspaces = fixtureObject(pkg, 'workspaces'); + const catalog = fixtureObject(workspaces.catalog ?? {}); + expect(catalog.vite).toBeUndefined(); + expect(catalog.vitest).toBeUndefined(); + expect(pkg).toHaveProperty(['workspaces', 'catalogs', 'build', 'vite'], '^7.0.0'); + expect(pkg).toHaveProperty(['workspaces', 'catalogs', 'build', 'vitest'], '^4.0.0'); + expect(fixtureObject(pkg, 'workspaces', 'catalogs', 'build').tsdown).toBeUndefined(); + expect(pkg).toHaveProperty( + ['overrides', 'vite'], + 'file:/tmp/tgz/voidzero-dev-vite-plus-core-0.0.0.tgz', + ); + expect(pkg).toHaveProperty( + ['devDependencies', 'vite'], + 'file:/tmp/tgz/voidzero-dev-vite-plus-core-0.0.0.tgz', + ); }); it('does not create bunfig.toml', () => { @@ -194,9 +194,10 @@ describe('rewriteMonorepo bun catalog with file: protocol', () => { expect(pkg.optionalDependencies.vite).toBe( 'file:/tmp/tgz/voidzero-dev-vite-plus-core-0.0.0.tgz', ); - expect( - (pkg as { devDependencies?: Record }).devDependencies?.['vite-plus'], - ).toBe('file:/tmp/tgz/vite-plus-0.0.0.tgz'); + expect(pkg).toHaveProperty( + ['devDependencies', 'vite-plus'], + 'file:/tmp/tgz/vite-plus-0.0.0.tgz', + ); }); it('does not align Vitest ecosystem packages when Vitest is unmanaged', () => { diff --git a/packages/cli/src/migration/__tests__/compat-runner.spec.ts b/packages/cli/src/migration/__tests__/compat-runner.spec.ts index 0cabb19eb2..6d48ac1ee4 100644 --- a/packages/cli/src/migration/__tests__/compat-runner.spec.ts +++ b/packages/cli/src/migration/__tests__/compat-runner.spec.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; vi.mock('../../utils/command.ts', () => ({ - runCommandSilently: vi.fn(), + runCommandSilently: vi.fn(), })); import { runCommandSilently } from '../../utils/command.ts'; diff --git a/packages/cli/src/migration/__tests__/compat.spec.ts b/packages/cli/src/migration/__tests__/compat.spec.ts index 36220d6445..b474590f73 100644 --- a/packages/cli/src/migration/__tests__/compat.spec.ts +++ b/packages/cli/src/migration/__tests__/compat.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { checkManualChunksCompat } from '../compat/manual-chunks.js'; -import { createMigrationReport } from '../report.js'; +import { checkManualChunksCompat } from '../compat/manual-chunks.ts'; +import { createMigrationReport } from '../report.ts'; describe('checkManualChunksCompat', () => { it('should warn when manualChunks is an object', () => { diff --git a/packages/cli/src/migration/__tests__/detector.spec.ts b/packages/cli/src/migration/__tests__/detector.spec.ts index b579b5b2c9..e173030eaa 100644 --- a/packages/cli/src/migration/__tests__/detector.spec.ts +++ b/packages/cli/src/migration/__tests__/detector.spec.ts @@ -4,9 +4,14 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type { JsonObject } from '../../utils/json.ts'; import { detectMigrationWarnings } from '../detector.ts'; -function writeProject(projectPath: string, packageJson: object, configFiles: string[] = []): void { +function writeProject( + projectPath: string, + packageJson: JsonObject, + configFiles: Array = [], +): void { fs.mkdirSync(projectPath, { recursive: true }); fs.writeFileSync(path.join(projectPath, 'package.json'), JSON.stringify(packageJson)); for (const configFile of configFiles) { diff --git a/packages/cli/src/migration/__tests__/fixture-json.ts b/packages/cli/src/migration/__tests__/fixture-json.ts new file mode 100644 index 0000000000..dfe8ea4180 --- /dev/null +++ b/packages/cli/src/migration/__tests__/fixture-json.ts @@ -0,0 +1,25 @@ +import type { JsonObject } from '../../utils/json.ts'; +import { isJsonObject } from '../../utils/json.ts'; + +/** Require an object at a particular path in a migrated JSON or YAML fixture. */ +export function fixtureObject(value: unknown, ...path: Array): JsonObject { + let object = value; + for (const key of path) { + if (!isJsonObject(object)) { + throw new TypeError(`Expected a fixture object before key ${key}`); + } + object = object[key]; + } + if (!isJsonObject(object)) { + throw new TypeError(`Expected a fixture object at ${path.join('.') || 'the root'}`); + } + return object; +} + +export function fixtureString(value: unknown, parent: string, key: string): string { + const item = fixtureObject(value, parent)[key]; + if (typeof item !== 'string') { + throw new TypeError(`Expected a string at ${parent}.${key}`); + } + return item; +} diff --git a/packages/cli/src/migration/__tests__/format-fallback.spec.ts b/packages/cli/src/migration/__tests__/format-fallback.spec.ts index b592edf85f..7c72da2db8 100644 --- a/packages/cli/src/migration/__tests__/format-fallback.spec.ts +++ b/packages/cli/src/migration/__tests__/format-fallback.spec.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; vi.mock('../../utils/command.ts', () => ({ - runCommandSilently: vi.fn(), + runCommandSilently: vi.fn(), })); import { runCommandSilently } from '../../utils/command.ts'; diff --git a/packages/cli/src/migration/__tests__/format.spec.ts b/packages/cli/src/migration/__tests__/format.spec.ts index 0880b0c2dc..84a01d0589 100644 --- a/packages/cli/src/migration/__tests__/format.spec.ts +++ b/packages/cli/src/migration/__tests__/format.spec.ts @@ -6,18 +6,21 @@ import { fileURLToPath } from 'node:url'; import { describe, expect, it, vi } from 'vitest'; +import type { FormatRunner } from '../format.ts'; import { canFormatWithOxfmt, collectChangedFormatPaths, formatMigratedProject } from '../format.ts'; import { createMigrationReport } from '../report.ts'; describe('formatMigratedProject', () => { it('formats the project root', async () => { - const format = vi.fn().mockResolvedValue({ + const format = vi.fn().mockResolvedValue({ durationMs: 1, exitCode: 0, status: 'formatted', }); const report = createMigrationReport(); - const collectPaths = vi.fn().mockResolvedValue(['package.json', 'vite.config.ts']); + const collectPaths = vi + .fn() + .mockResolvedValue(['package.json', 'vite.config.ts']); const excludedPaths = new Set(['notes.md']); await expect( @@ -40,7 +43,7 @@ describe('formatMigratedProject', () => { const originalCliEntry = process.argv[1]; process.argv[1] = './packages/cli/src/migration/bin.ts'; try { - const format = vi.fn().mockResolvedValue({ + const format = vi.fn().mockResolvedValue({ durationMs: 1, exitCode: 0, status: 'formatted', @@ -50,7 +53,9 @@ describe('formatMigratedProject', () => { await expect( formatMigratedProject('/different/project', false, report, { format, - collectPaths: vi.fn().mockResolvedValue(['package.json']), + collectPaths: vi + .fn() + .mockResolvedValue(['package.json']), }), ).resolves.toBe(true); expect(format).toHaveBeenCalledWith('/different/project', false, ['package.json'], { @@ -67,13 +72,15 @@ describe('formatMigratedProject', () => { }); it('splits a very large changed-file set across multiple format invocations', async () => { - const format = vi.fn().mockResolvedValue({ durationMs: 1, exitCode: 0, status: 'formatted' }); + const format = vi + .fn() + .mockResolvedValue({ durationMs: 1, exitCode: 0, status: 'formatted' }); const report = createMigrationReport(); const paths = Array.from( { length: 5000 }, (_, index) => `packages/app/src/very/deeply/nested/module-${index}.ts`, ); - const collectPaths = vi.fn().mockResolvedValue(paths); + const collectPaths = vi.fn().mockResolvedValue(paths); await expect( formatMigratedProject('/project', false, report, { format, collectPaths }), @@ -86,9 +93,9 @@ describe('formatMigratedProject', () => { }); it('skips formatting when migration changed no supported files', async () => { - const format = vi.fn(); + const format = vi.fn(); const report = createMigrationReport(); - const collectPaths = vi.fn().mockResolvedValue([]); + const collectPaths = vi.fn().mockResolvedValue([]); await expect( formatMigratedProject('/project', false, report, { format, collectPaths }), @@ -133,14 +140,14 @@ describe('formatMigratedProject', () => { }); it('reports a formatter nonzero exit without throwing', async () => { - const format = vi.fn().mockResolvedValue({ + const format = vi.fn().mockResolvedValue({ durationMs: 1, exitCode: 1, status: 'failed', }); const report = createMigrationReport(); // Non-git project: whole-project formatting. - const collectPaths = vi.fn().mockResolvedValue(undefined); + const collectPaths = vi.fn().mockResolvedValue(undefined); await expect( formatMigratedProject('/project', false, report, { format, collectPaths }), @@ -151,9 +158,9 @@ describe('formatMigratedProject', () => { }); it('reports a formatter exception without throwing', async () => { - const format = vi.fn().mockRejectedValue(new Error('could not load config')); + const format = vi.fn().mockRejectedValue(new Error('could not load config')); const report = createMigrationReport(); - const collectPaths = vi.fn().mockResolvedValue(undefined); + const collectPaths = vi.fn().mockResolvedValue(undefined); await expect( formatMigratedProject('/project', false, report, { format, collectPaths }), diff --git a/packages/cli/src/migration/__tests__/import-rule.spec.ts b/packages/cli/src/migration/__tests__/import-rule.spec.ts index ae1b01c31e..dc24e8f91e 100644 --- a/packages/cli/src/migration/__tests__/import-rule.spec.ts +++ b/packages/cli/src/migration/__tests__/import-rule.spec.ts @@ -13,7 +13,9 @@ import { } from '../migrator.ts'; import { createMigrationReport } from '../report.ts'; -vi.mock('../compat/runner.ts', () => ({ readLintConfigInWorker: vi.fn() })); +vi.mock('../compat/runner.ts', () => ({ + readLintConfigInWorker: vi.fn(), +})); describe('migration import rule settings', () => { let root: string; diff --git a/packages/cli/src/migration/__tests__/install-failure-guard.spec.ts b/packages/cli/src/migration/__tests__/install-failure-guard.spec.ts index c615095c17..99dfec587e 100644 --- a/packages/cli/src/migration/__tests__/install-failure-guard.spec.ts +++ b/packages/cli/src/migration/__tests__/install-failure-guard.spec.ts @@ -1,13 +1,12 @@ import fs from 'node:fs'; import path from 'node:path'; -import { fileURLToPath } from 'node:url'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { handleInstallResult } from '../install-result.ts'; import { createMigrationReport } from '../report.ts'; -const here = path.dirname(fileURLToPath(import.meta.url)); +const here = import.meta.dirname; const binPath = path.resolve(here, '..', 'bin.ts'); /** @@ -17,17 +16,19 @@ const binPath = path.resolve(here, '..', 'bin.ts'); * `status`, which left the project's `node_modules` desynced from a freshly * mutated `package.json` while still printing "Dependencies installed". */ +const spyConsole = () => vi.spyOn(console, 'error').mockImplementation(() => {}); + describe('handleInstallResult', () => { const rootDir = '/project'; const failureMessage = (exitCode: number) => `Dependency installation failed (exit code ${exitCode}). Run \`vp install\` manually in ${rootDir} to resync node_modules.`; let originalExitCode: typeof process.exitCode; - let consoleError: ReturnType; + let consoleError: ReturnType; beforeEach(() => { originalExitCode = process.exitCode; process.exitCode = undefined; - consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); + consoleError = spyConsole(); }); afterEach(() => { diff --git a/packages/cli/src/migration/__tests__/migrator.spec.ts b/packages/cli/src/migration/__tests__/migrator.spec.ts index ad594c34c7..b306677972 100644 --- a/packages/cli/src/migration/__tests__/migrator.spec.ts +++ b/packages/cli/src/migration/__tests__/migrator.spec.ts @@ -3,22 +3,25 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; +import type { OxlintConfig } from 'oxlint'; 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 { rewriteScripts } from '../../../binding/index.js'; -import { PackageManager, type WorkspaceInfo } from '../../types/index.js'; +import type { WorkspaceInfo } from '../../types/index.ts'; +import { PackageManager } from '../../types/index.ts'; import { SETUP_VP_VERSION, VITE_PLUS_OVERRIDE_PACKAGES, VITEST_VERSION, -} from '../../utils/constants.js'; -import { - DISABLED_IMPORT_RULE_CONFIG, - type RetainedImportDependencies, -} from '../migrator/shared.ts'; -import { createMigrationReport } from '../report.js'; +} from '../../utils/constants.ts'; +import type { JsonObject } from '../../utils/json.ts'; +import { readJsonFile as readJson } from '../../utils/json.ts'; +import type { RetainedImportDependencies } from '../migrator/shared.ts'; +import { DISABLED_IMPORT_RULE_CONFIG } from '../migrator/shared.ts'; +import { createMigrationReport } from '../report.ts'; +import { fixtureObject, fixtureString } from './fixture-json.ts'; // A different bundled version verifies that migration follows dependency updates. vi.mock('tsrs/package.json', () => ({ default: { version: '99.0.0-test' } })); @@ -26,8 +29,8 @@ vi.mock('tsrs/package.json', () => ({ default: { version: '99.0.0-test' } })); // Mock VITE_PLUS_VERSION to a stable value for snapshot tests. // When tests run via `vp test`, the env var is injected with the actual version, // which would cause snapshot mismatches. -vi.mock('../../utils/constants.js', async (importOriginal) => { - const mod = await importOriginal(); +vi.mock(import('../../utils/constants.ts'), async (importOriginal) => { + const mod = await importOriginal(); return { ...mod, VITE_PLUS_VERSION: 'latest', @@ -76,7 +79,7 @@ const { pnpmSupportsWorkspaceSettings, pnpmOverrideKey, setPackageManager, -} = await import('../migrator.js'); +} = await import('../migrator.ts'); // pnpm's managed override keys are range-qualified so they never rewrite an // importer's `catalog:` spec (issue #2309). npm/bun `overrides` and yarn @@ -84,7 +87,7 @@ const { const PNPM_VITE_OVERRIDE_KEY = pnpmOverrideKey('vite'); const PNPM_VITEST_OVERRIDE_KEY = pnpmOverrideKey('vitest'); -const { collectMigrationSetupPlan } = await import('../setup-plan.js'); +const { collectMigrationSetupPlan } = await import('../setup-plan.ts'); describe('pnpm workspace settings support', () => { it.each([ @@ -232,9 +235,21 @@ describe('rewritePackageJson', () => { }; const extractedStagedConfig = rewritePackageJson(pkg, PackageManager.npm); // lint-staged and vite-staged keys should be removed from pkg - expect(pkg).toMatchSnapshot(); + expect(pkg).toMatchSnapshot('package manifest'); // Extracted config should have rewritten commands - expect(extractedStagedConfig).toMatchSnapshot(); + expect(extractedStagedConfig).toMatchSnapshot('staged commands'); + }); + + it('preserves other JSON values alongside rewritten scripts and staged commands', () => { + const pkg: JsonObject = { + scripts: { dev: 'vite', metadata: { enabled: true } }, + 'lint-staged': { '*.ts': ['oxfmt --fix', null], metadata: 1 }, + }; + + const staged = rewritePackageJson(pkg, PackageManager.npm); + + expect(pkg.scripts).toEqual({ dev: 'vp dev', metadata: { enabled: true } }); + expect(staged).toEqual({ '*.ts': ['vp fmt --fix', null], metadata: 1 }); }); it.each([ @@ -321,39 +336,39 @@ describe('rewritePackageJson', () => { // excluded @vitest/* package drives a `vitest: catalog:` spec while the // catalog omits `vitest` — a dangling reference that breaks `pnpm install`. it('does not inject a direct vitest for an excluded @vitest/* dep', () => { - const pkg: { devDependencies: Record } = { + const pkg = { // oxlint is a managed tool → needVitePlus → the injection guard runs. // @vitest/eslint-plugin is in VITEST_DIRECT_USAGE_EXCLUDED (a lint plugin, // not a direct vitest consumer), so no direct vitest should be added. devDependencies: { oxlint: '1.0.0', '@vitest/eslint-plugin': '1.0.0' }, }; rewritePackageJson(pkg, PackageManager.pnpm, true); - expect(pkg.devDependencies.vitest).toBeUndefined(); + expect(fixtureObject(pkg, 'devDependencies').vitest).toBeUndefined(); }); // PR #1891 review: a @nuxt/test-utils package keeps its `from 'vitest'` // imports (preserveNuxtVitestImports), which need a package-local vitest under // strict pnpm/Yarn layouts where vite-plus's transitive vitest is not visible. it('injects a direct vitest for a Nuxt test-utils package', () => { - const pkg: { devDependencies: Record } = { + const pkg = { devDependencies: { '@nuxt/test-utils': '3.0.0' }, }; rewritePackageJson(pkg, PackageManager.pnpm, true); - expect(pkg.devDependencies.vitest).toBe('catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], 'catalog:'); }); // Vite+ now supplies its own Vite alias. The #1932 install-layout and cache // regression is covered by the migration_pnpm_vite_identity CLI fixture. describe('pnpm Vite dependencies', () => { it('does not add `vite` just because a package depends on vite-plus', () => { - const sub: { devDependencies: Record } = { + const sub = { devDependencies: { 'vite-plus': 'catalog:' }, }; rewritePackageJson(sub, PackageManager.pnpm, true); expect(sub.devDependencies).toEqual({ 'vite-plus': 'catalog:' }); // Standalone consumers do not need a project-level alias either. - const standalone: { devDependencies: Record } = { + const standalone = { devDependencies: { 'vite-plus': 'latest' }, }; rewritePackageJson(standalone, PackageManager.pnpm); @@ -362,24 +377,24 @@ describe('rewritePackageJson', () => { it('does not add a direct `vite` for npm/yarn/bun (they dedupe via overrides/resolutions)', () => { for (const pm of [PackageManager.npm, PackageManager.yarn, PackageManager.bun]) { - const pkg: { devDependencies: Record } = { + const pkg = { devDependencies: { 'vite-plus': pm === PackageManager.npm ? '^0.1.20' : 'catalog:' }, }; rewritePackageJson(pkg, pm, true); - expect(pkg.devDependencies.vite).toBeUndefined(); + expect(fixtureObject(pkg, 'devDependencies').vite).toBeUndefined(); } }); it('does not add `vite` for a pnpm package that does not depend on vite-plus', () => { - const pkg: { devDependencies: Record } = { + const pkg = { devDependencies: { typescript: '^5' }, }; rewritePackageJson(pkg, PackageManager.pnpm, true); - expect(pkg.devDependencies.vite).toBeUndefined(); + expect(fixtureObject(pkg, 'devDependencies').vite).toBeUndefined(); }); it('keeps an existing direct `vite` instead of overwriting it under pnpm', () => { - const pkg: { devDependencies: Record } = { + const pkg = { devDependencies: { 'vite-plus': 'catalog:', vite: 'catalog:vite7' }, }; rewritePackageJson(pkg, PackageManager.pnpm, true); @@ -389,28 +404,22 @@ describe('rewritePackageJson', () => { it('does not inject a direct vite when vite is only a peerDependency under pnpm', () => { // A vite plugin that pins `vite` as a peer must keep its own contract; // injecting vite-plus-core as a concrete devDep would conflict with it. - const pkg: { - devDependencies: Record; - peerDependencies: Record; - } = { + const pkg = { devDependencies: { 'vite-plus': 'catalog:' }, peerDependencies: { vite: '^6.0.0' }, }; rewritePackageJson(pkg, PackageManager.pnpm, true); - expect(pkg.devDependencies.vite).toBeUndefined(); + expect(fixtureObject(pkg, 'devDependencies').vite).toBeUndefined(); expect(pkg.peerDependencies.vite).toBe('^6.0.0'); }); it('does not add a second vite when an empty-string vite spec is already declared under pnpm', () => { - const pkg: { - dependencies: Record; - devDependencies: Record; - } = { + const pkg = { dependencies: { vite: '' }, devDependencies: { 'vite-plus': 'catalog:' }, }; rewritePackageJson(pkg, PackageManager.pnpm, true); - expect(pkg.devDependencies.vite).toBeUndefined(); + expect(fixtureObject(pkg, 'devDependencies').vite).toBeUndefined(); }); }); @@ -523,9 +532,7 @@ describe('rewritePackageJson', () => { expect(pkg.peerDependencies).not.toHaveProperty('tsdown'); expect(pkg.optionalDependencies.vitest).toBe('catalog:test'); expect(pkg.optionalDependencies).not.toHaveProperty('oxlint'); - expect( - (pkg as { devDependencies?: Record }).devDependencies?.['vite-plus'], - ).toBe('catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); }); it('preserves peer dependency ranges', async () => { @@ -544,9 +551,7 @@ describe('rewritePackageJson', () => { expect(pkg.peerDependencies.vite).toBe('^7.0.0'); expect(pkg.peerDependencies.vitest).toBe('^4.0.0'); expect(pkg.optionalDependencies.vite).toBe('catalog:'); - expect( - (pkg as { devDependencies?: Record }).devDependencies?.['vite-plus'], - ).toBe('catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); const npmPkg = { peerDependencies: { @@ -576,12 +581,8 @@ describe('rewritePackageJson', () => { rewritePackageJson(pkg, PackageManager.pnpm, true); expect(pkg.peerDependencies.vitest).toBe('^4.0.0'); - expect((pkg as { devDependencies?: Record }).devDependencies?.vitest).toBe( - 'catalog:', - ); - expect( - (pkg as { devDependencies?: Record }).devDependencies?.['vite-plus'], - ).toBe('catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], 'catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); }); it('keeps and normalizes @vitest/browser-playwright and ensures the playwright peer', async () => { @@ -639,7 +640,7 @@ describe('rewritePackageJson', () => { // The injected `vite` must land in SORTED position (oxfmt sorts package.json // and `vp migrate` has no later format pass), so it sits before `vitest` // rather than being appended after it. - const keys = Object.keys(pkg.devDependencies); + const keys = Object.keys(fixtureObject(pkg, 'devDependencies')); expect(keys.indexOf('vite')).toBeLessThan(keys.indexOf('vitest')); expect(keys.slice(0, 3)).toEqual(['@vitest/browser-playwright', 'playwright', 'vite']); }); @@ -659,7 +660,7 @@ describe('rewritePackageJson', () => { it('does not inject a direct vite for pnpm/yarn/bun browser projects', async () => { for (const pm of [PackageManager.pnpm, PackageManager.yarn, PackageManager.bun]) { - const pkg: { devDependencies: Record } = { + const pkg = { devDependencies: { '@vitest/browser-playwright': '^4.0.0', playwright: '^1.60.0', @@ -751,9 +752,7 @@ describe('rewritePackageJson', () => { }, }; rewritePackageJson(pkg, PackageManager.npm, false, undefined, undefined, true); - expect((pkg as { devDependencies?: Record }).devDependencies?.vitest).toBe( - VITEST_VERSION, - ); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], VITEST_VERSION); }); it('does not overwrite an existing direct vitest dep in browser mode', async () => { @@ -815,7 +814,7 @@ describe('rewriteEslintPackageJson', () => { fs.rmSync(tmpDir, { recursive: true, force: true }); }); - function writePkg(pkg: object): string { + function writePkg(pkg: JsonObject): string { const pkgPath = path.join(tmpDir, 'package.json'); fs.writeFileSync(pkgPath, JSON.stringify(pkg)); return pkgPath; @@ -1109,7 +1108,7 @@ describe('collectInstalledPackageNames', () => { fs.rmSync(tmpDir, { recursive: true, force: true }); }); - function writeRootPkg(pkg: object): void { + function writeRootPkg(pkg: JsonObject): void { fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify(pkg)); } @@ -1154,7 +1153,7 @@ describe('collectInstalledPackageNames', () => { describe('sanitizeMigratedOxlintConfig', () => { it('removes missing generated plugins without discarding inherited or local plugin rules', () => { const inherited = { jsPlugins: ['./base-plugin.mjs'] }; - const config: import('oxlint').OxlintConfig = { + const config: OxlintConfig = { extends: [inherited], jsPlugins: ['eslint-plugin-missing', './local-plugin.mjs', 'eslint-plugin-installed/subpath'], rules: { @@ -1201,7 +1200,7 @@ describe('sanitizeMigratedOxlintConfig', () => { }); it('removes unsupported rules', () => { - const config: import('oxlint').OxlintConfig = { + const config: OxlintConfig = { rules: { // unsupported camelcase: 'error', @@ -1238,7 +1237,7 @@ describe('sanitizeMigratedOxlintConfig', () => { '@next/next/no-img-element': 'error', 'filename-case': 'error', } as const; - const config: import('oxlint').OxlintConfig = { + const config: OxlintConfig = { rules: { ...rules }, }; @@ -1250,7 +1249,7 @@ describe('sanitizeMigratedOxlintConfig', () => { describe('ensureSvelteRuneGlobals', () => { it('adds all built-in runes to Svelte overrides', () => { - const config: import('oxlint').OxlintConfig = { + const config: OxlintConfig = { overrides: [{ files: ['*.svelte', '**/*.svelte.ts'] }], }; @@ -1268,7 +1267,7 @@ describe('ensureSvelteRuneGlobals', () => { }); it('preserves existing globals and explicit rune values', () => { - const config: import('oxlint').OxlintConfig = { + const config: OxlintConfig = { overrides: [ { files: ['**/*.svelte'], @@ -1287,7 +1286,7 @@ describe('ensureSvelteRuneGlobals', () => { }); it('detects Svelte in brace-expanded override patterns', () => { - const config: import('oxlint').OxlintConfig = { + const config: OxlintConfig = { overrides: [{ files: ['**/*.{js,ts,svelte}'] }], }; @@ -1299,7 +1298,7 @@ describe('ensureSvelteRuneGlobals', () => { }); it('does not modify unrelated or negated-only overrides', () => { - const config: import('oxlint').OxlintConfig = { + const config: OxlintConfig = { overrides: [{ files: ['**/*.ts'] }, { files: ['!**/*.svelte'] }], }; @@ -1348,7 +1347,7 @@ describe('mergeViteConfigFiles — Svelte rune globals', () => { }); }); -function writePkgAt(dir: string, pkg: object): string { +function writePkgAt(dir: string, pkg: JsonObject): string { fs.mkdirSync(dir, { recursive: true }); const packageJsonPath = path.join(dir, 'package.json'); fs.writeFileSync(packageJsonPath, JSON.stringify(pkg)); @@ -1419,11 +1418,7 @@ describe('setPackageManager', () => { fs.rmSync(tmpDir, { recursive: true, force: true }); }); - const readPkg = () => - JSON.parse(fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf8')) as Record< - string, - unknown - >; + const readPkg = () => readJson(path.join(tmpDir, 'package.json')); it('writes devEngines.packageManager when neither field exists', () => { fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({ name: 'x' }, null, 2)); @@ -1733,10 +1728,6 @@ function checkBootstrapPass(workspace: WorkspaceInfo, expectedChange: boolean): expect(ensureVitePlusBootstrap(workspace).changed).toBe(expectedChange); } -function readJson(filePath: string): Record { - return JSON.parse(fs.readFileSync(filePath, 'utf8')); -} - describe('first migration preserves pnpm workspace membership', () => { let project: string; @@ -1770,9 +1761,9 @@ describe('first migration preserves pnpm workspace membership', () => { rewriteMonorepo(workspace, true, true); expect(readYamlObject(workspaceFile).packages).toEqual(workspace.workspacePatterns); - if (existing !== undefined) { - expect(readYamlObject(workspaceFile).catalog).toMatchObject({ example: '^1.0.0' }); - } + expect(readYamlObject(workspaceFile).catalog).toMatchObject( + existing ? { example: '^1.0.0' } : {}, + ); const migrated = fs.readFileSync(workspaceFile, 'utf8'); rewriteMonorepo(workspace, true, true); expect(fs.readFileSync(workspaceFile, 'utf8')).toBe(migrated); @@ -1796,8 +1787,8 @@ function readYaml(filePath: string): string { return fs.readFileSync(filePath, 'utf8'); } -function readYamlObject(filePath: string): Record { - return parseYaml(readYaml(filePath)) as Record; +function readYamlObject(filePath: string): JsonObject { + return fixtureObject(parseYaml(readYaml(filePath))); } function overrideFile(manager: PackageManager, version: string) { @@ -1805,14 +1796,11 @@ function overrideFile(manager: PackageManager, version: string) { ? 'pnpm-workspace.yaml' : 'package.json'; } -function overrideMap(pkg: Record, manager: PackageManager, version: string) { +function overrideMap(pkg: JsonObject, manager: PackageManager, version: string) { if (manager === PackageManager.pnpm && !pnpmSupportsWorkspaceSettings(version)) { - return (pkg.pnpm as { overrides: Record }).overrides; + return fixtureObject(pkg.pnpm).overrides; } - return pkg[manager === PackageManager.yarn ? 'resolutions' : 'overrides'] as Record< - string, - string - >; + return fixtureObject(pkg[manager === PackageManager.yarn ? 'resolutions' : 'overrides']); } describe('WebDriverIO browser overrides', () => { @@ -1854,22 +1842,20 @@ describe('WebDriverIO browser overrides', () => { const workspace = makeWorkspaceInfo(tmpDir, manager, version); rewriteStandaloneProject(tmpDir, workspace, true, true); const key = manager === PackageManager.pnpm ? pnpmOverrideKey(browser) : browser; - expect(readOverrides(manager, version)[key]).toBe(VITEST_VERSION); + expect(readOverrides(manager, version)).toHaveProperty([key], VITEST_VERSION); expect( - (readJson(path.join(tmpDir, 'package.json')).devDependencies as Record)[ - provider - ], + fixtureObject(readJson(path.join(tmpDir, 'package.json')).devDependencies)[provider], ).toBe('^5.2.0'); expect(detectVitePlusBootstrapPending(tmpDir, manager, [], version)).toBe(false); // Only this override is stale: it must trigger existing-Vite+ reconciliation. const file = path.join(tmpDir, overrideFile(manager, version)); const pkg = file.endsWith('.yaml') ? readYamlObject(file) : readJson(file); - overrideMap(pkg, manager, version)[key] = '5.0.0'; + fixtureObject(overrideMap(pkg, manager, version))[key] = '5.0.0'; fs.writeFileSync(file, JSON.stringify(pkg)); expect(detectVitePlusBootstrapPending(tmpDir, manager, [], version)).toBe(true); expect(ensureVitePlusBootstrap(workspace).changed).toBe(true); - expect(readOverrides(manager, version)[key]).toBe(VITEST_VERSION); + expect(readOverrides(manager, version)).toHaveProperty([key], VITEST_VERSION); expect(detectVitePlusBootstrapPending(tmpDir, manager, [], version)).toBe(false); expect(ensureVitePlusBootstrap(workspace).changed).toBe(false); }); @@ -1892,10 +1878,10 @@ describe('WebDriverIO browser overrides', () => { }; rewriteMonorepo(workspace, true, true); const key = manager === PackageManager.pnpm ? pnpmOverrideKey(browser) : browser; - expect(readOverrides(manager, version)[key]).toBe(VITEST_VERSION); + expect(readOverrides(manager, version)).toHaveProperty([key], VITEST_VERSION); // Reconcile workspace package-manager fields, then check repeat-run stability. ensureVitePlusBootstrap(workspace); - expect(readOverrides(manager, version)[key]).toBe(VITEST_VERSION); + expect(readOverrides(manager, version)).toHaveProperty([key], VITEST_VERSION); expect(detectVitePlusBootstrapPending(tmpDir, manager, workspace.packages, version)).toBe( false, ); @@ -1942,14 +1928,11 @@ describe('ensureVitePlusBootstrap', () => { expect(report.packageManagerBootstrapConfigured).toBe(true); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - overrides: Record; - devEngines?: { packageManager: { name: string } }; - }; - expect(pkg.overrides.vite).toContain('@voidzero-dev/vite-plus-core'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(fixtureObject(pkg, 'overrides').vite).toContain('@voidzero-dev/vite-plus-core'); // Common case (no @vitest/* dep, no vitest source): `vitest` is NOT managed — // it arrives transitively through vite-plus, so no override is written. - expect(pkg.overrides.vitest).toBeUndefined(); + expect(fixtureObject(pkg, 'overrides').vitest).toBeUndefined(); expect(pkg.devEngines).toBeUndefined(); }); @@ -1974,11 +1957,9 @@ describe('ensureVitePlusBootstrap', () => { ); expect(result.changed).toBe(true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - expect(pkg.devDependencies['vite-plus']).toBe('catalog:'); - expect(pkg.devDependencies.vite).toBeUndefined(); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); + expect(fixtureObject(pkg, 'devDependencies').vite).toBeUndefined(); const workspaceYaml = readYaml(path.join(tmpDir, 'pnpm-workspace.yaml')); expect(workspaceYaml).toContain('vite-plus:'); expect(workspaceYaml).toContain('@voidzero-dev/vite-plus-core'); @@ -2008,21 +1989,17 @@ describe('ensureVitePlusBootstrap', () => { const result = ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.bun)); expect(result.changed).toBe(true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - overrides: Record; - catalog: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); // Bun needs `vite` as a DIRECT dependency for vitest's `vite` peer to resolve // before overrides apply (oven-sh/bun#8406). A `catalog:` edge satisfies that // (catalog refs resolve during the dependency-graph build) and keeps the // direct edge consistent with the catalog/override sinks instead of leaking a // concrete alias. Verified on bun 1.3.11. - expect(pkg.devDependencies.vite).toBe('catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], 'catalog:'); // The injected `vite` must land in SORTED position (oxfmt sorts package.json // and `vp migrate` has no later format pass), i.e. before the existing // `vite-plus` entry rather than appended after it. - const devKeys = Object.keys(pkg.devDependencies); + const devKeys = Object.keys(fixtureObject(pkg, 'devDependencies')); expect(devKeys).toEqual([...devKeys].toSorted()); // The direct `vite` edge is inserted before the existing `vite-plus` entry. // (A non-managed direct `vitest` is removed in this common case, arriving @@ -2030,7 +2007,7 @@ describe('ensureVitePlusBootstrap', () => { expect(devKeys).toEqual(['vite', 'vite-plus']); // The bootstrap path writes a bun catalog mapping `vite` -> vite-plus-core, // so the `catalog:` direct edge resolves to the managed core build. - expect(pkg.catalog.vite).toContain('@voidzero-dev/vite-plus-core'); + expect(fixtureObject(pkg, 'catalog').vite).toContain('@voidzero-dev/vite-plus-core'); }); it('keeps a bun WORKSPACE `catalog:` override instead of inlining it against a stale catalog', () => { @@ -2053,14 +2030,11 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.bun)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - overrides: Record; - catalog: Record; - }; - expect(pkg.overrides.vite).toBe('catalog:'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['overrides', 'vite'], 'catalog:'); // The catalog is rewritten off the stale core@0.1.0 alias. - expect(pkg.catalog.vite).toContain('@voidzero-dev/vite-plus-core'); - expect(pkg.catalog.vite).not.toContain('@0.1.0'); + expect(fixtureObject(pkg, 'catalog').vite).toContain('@voidzero-dev/vite-plus-core'); + expect(fixtureObject(pkg, 'catalog').vite).not.toContain('@0.1.0'); }); it('keeps a STANDALONE bun project on concrete specs (no `catalog:`, no catalog field) on upgrade', () => { @@ -2097,12 +2071,7 @@ describe('ensureVitePlusBootstrap', () => { const result = ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.bun)); expect(result.changed).toBe(true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - overrides: Record; - catalog?: Record; - workspaces?: unknown; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); // No bun catalog field is written for a standalone (non-workspace) project, // and no `workspaces` field is fabricated. expect(pkg.catalog).toBeUndefined(); @@ -2110,15 +2079,18 @@ describe('ensureVitePlusBootstrap', () => { // Managed install specs re-pin to the active toolchain target and stay // concrete: `vite` via the core alias, `vite-plus` at the version, `vitest` // at the bundled version. - expect(pkg.devDependencies.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); - expect(pkg.devDependencies['vite-plus']).toBe('latest'); - expect(pkg.devDependencies.vitest).toBe(VITEST_VERSION); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], VITE_PLUS_OVERRIDE_PACKAGES.vite); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'latest'); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], VITEST_VERSION); // Overrides stay concrete too (bun resolves these regardless, but a // `catalog:` override would still dangle without a catalog). - expect(pkg.overrides.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); - expect(pkg.overrides.vitest).toBe(VITEST_VERSION); + expect(pkg).toHaveProperty(['overrides', 'vite'], VITE_PLUS_OVERRIDE_PACKAGES.vite); + expect(pkg).toHaveProperty(['overrides', 'vitest'], VITEST_VERSION); // Nothing collapses to a dangling `catalog:` reference. - for (const spec of [...Object.values(pkg.devDependencies), ...Object.values(pkg.overrides)]) { + for (const spec of [ + ...Object.values(fixtureObject(pkg, 'devDependencies')), + ...Object.values(fixtureObject(pkg, 'overrides')), + ]) { expect(spec).not.toMatch(/^catalog:/); } // A second pass is a no-op: the standalone project is already settled. @@ -2186,10 +2158,7 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun)).toBe(false); ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.bun, '1.2.14')); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - overrides: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); expect(pkg.devDependencies).toEqual({ vite: 'catalog:', 'vite-plus': 'catalog:' }); expect(pkg.overrides).toEqual({ vite: 'catalog:' }); }); @@ -2213,18 +2182,15 @@ describe('ensureVitePlusBootstrap', () => { ); const workspace = makeWorkspaceInfo(tmpDir, PackageManager.bun, version); rewriteMonorepo(workspace, true); - const pkg = readJson(file) as { - devDependencies: Record; - workspaces: { - catalog: Record; - catalogs: Record>; - }; - }; + const pkg = readJson(file); 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( + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'react'], 'catalog:default'); + expect(fixtureObject(pkg, 'workspaces', 'catalog')['vite-plus']).toBe( + merged ? undefined : 'latest', + ); + expect(pkg).toHaveProperty( + ['workspaces', 'catalogs', 'default'], merged ? { react: '^19.0.0', 'vite-plus': 'latest' } : { react: '^19.0.0' }, ); const resolver = createCatalogDependencyResolver(tmpDir, PackageManager.bun, version)!; @@ -2254,16 +2220,16 @@ describe('ensureVitePlusBootstrap', () => { ); 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( + const pkg = readJson(file); + expect(pkg).toHaveProperty( + ['devDependencies', 'vite-plus'], version === '1.4.0' ? 'catalog:' : 'catalog:default', ); - expect(pkg.workspaces.catalog).toBeUndefined(); + expect(fixtureObject(pkg, 'workspaces').catalog).toBeUndefined(); const resolver = createCatalogDependencyResolver(tmpDir, PackageManager.bun, version)!; - expect(resolver(pkg.devDependencies['vite-plus'], 'vite-plus')).toBe('latest'); + expect(resolver(fixtureString(pkg, 'devDependencies', 'vite-plus'), 'vite-plus')).toBe( + 'latest', + ); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun)).toBe(false); const before = fs.readFileSync(file, 'utf8'); ensureVitePlusBootstrap(workspace); @@ -2278,10 +2244,7 @@ describe('ensureVitePlusBootstrap', () => { ['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>; - } = { + const catalogs = { catalog: { vite: '^8.0.0' }, catalogs: { default: { 'vite-plus': '0.3.2' } }, }; @@ -2297,17 +2260,16 @@ describe('ensureVitePlusBootstrap', () => { }), ); ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.bun, version)); - const pkg = readJson(file) as { - devDependencies: Record; - workspaces: typeof catalogs; - } & typeof catalogs; + const pkg = readJson(file); const active = location === 'nested' ? pkg.workspaces : pkg; - expect(active.catalog.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); - expect(active.catalogs.default.vite).toBe( + expect(active).toHaveProperty(['catalog', 'vite'], VITE_PLUS_OVERRIDE_PACKAGES.vite); + expect(fixtureObject(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(resolver(fixtureString(pkg, 'devDependencies', 'vite'), 'vite')).toBe( + VITE_PLUS_OVERRIDE_PACKAGES.vite, + ); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun)).toBe(false); }); @@ -2331,12 +2293,9 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.bun, '1.4.4')); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - workspaces: { catalog: Record }; - }; - expect(pkg.devDependencies['@vitest/coverage-v8']).toBe('catalog:'); - expect(pkg.workspaces.catalog['@vitest/coverage-v8']).toBe(VITEST_VERSION); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/coverage-v8'], 'catalog:'); + expect(pkg).toHaveProperty(['workspaces', 'catalog', '@vitest/coverage-v8'], VITEST_VERSION); }); it('adds an excluded @vitest/* utility to the bun catalog without a vitest entry', () => { @@ -2357,13 +2316,10 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.bun, '1.2.20')); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - workspaces: { catalog: Record }; - }; - expect(pkg.devDependencies['@vitest/utils']).toBe('catalog:'); - expect(pkg.workspaces.catalog.vitest).toBeUndefined(); - expect(pkg.workspaces.catalog['@vitest/utils']).toBe(VITEST_VERSION); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/utils'], 'catalog:'); + expect(fixtureObject(pkg, 'workspaces', 'catalog').vitest).toBeUndefined(); + expect(pkg).toHaveProperty(['workspaces', 'catalog', '@vitest/utils'], VITEST_VERSION); }); it('adds an excluded @vitest/* utility to the pnpm catalog without a vitest entry', () => { @@ -2381,15 +2337,13 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm, '10.33.0')); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - const workspace = parseYaml( - fs.readFileSync(path.join(tmpDir, 'pnpm-workspace.yaml'), 'utf8'), - ) as { catalog: Record }; - expect(pkg.devDependencies['@vitest/utils']).toBe('catalog:'); - expect(workspace.catalog.vitest).toBeUndefined(); - expect(workspace.catalog['@vitest/utils']).toBe(VITEST_VERSION); + const pkg = readJson(path.join(tmpDir, 'package.json')); + const workspace = fixtureObject( + parseYaml(fs.readFileSync(path.join(tmpDir, 'pnpm-workspace.yaml'), 'utf8')), + ); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/utils'], 'catalog:'); + expect(fixtureObject(workspace, 'catalog').vitest).toBeUndefined(); + expect(workspace).toHaveProperty(['catalog', '@vitest/utils'], VITEST_VERSION); }); it('adds vite-plus to the named bun catalog its new reference points at', () => { @@ -2408,16 +2362,10 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.bun, '1.4.4')); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - workspaces: { - catalog?: Record; - catalogs: Record>; - }; - }; - expect(pkg.devDependencies['vite-plus']).toBe('catalog:build'); - expect(pkg.workspaces.catalogs.build['vite-plus']).toBe('latest'); - expect(pkg.workspaces.catalog).toBeUndefined(); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:build'); + expect(pkg).toHaveProperty(['workspaces', 'catalogs', 'build', 'vite-plus'], 'latest'); + expect(fixtureObject(pkg, 'workspaces').catalog).toBeUndefined(); }); it('reports a stale bun catalog vite-plus value as pending', () => { @@ -2442,10 +2390,8 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun)).toBe(true); ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.bun, '1.4.4')); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - workspaces: { catalog: Record }; - }; - expect(pkg.workspaces.catalog['vite-plus']).not.toBe('0.1.20'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(fixtureObject(pkg, 'workspaces', 'catalog')['vite-plus']).not.toBe('0.1.20'); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun)).toBe(false); }); @@ -2466,10 +2412,7 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.bun, '1.2.20')); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - catalog?: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); expect(pkg.devDependencies).toEqual({ vite: VITE_PLUS_OVERRIDE_PACKAGES.vite, 'vite-plus': 'latest', @@ -2512,13 +2455,11 @@ describe('ensureVitePlusBootstrap', () => { const result = ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.bun)); expect(result.changed).toBe(true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - overrides: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); // The `catalog:` override is rewritten to the concrete core alias so // `bun install --force` resolves it without a workspace catalog. - expect(pkg.overrides.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); - expect(pkg.overrides.vite).not.toMatch(/^catalog:/); + expect(pkg).toHaveProperty(['overrides', 'vite'], VITE_PLUS_OVERRIDE_PACKAGES.vite); + expect(fixtureObject(pkg, 'overrides').vite).not.toMatch(/^catalog:/); // Settled afterward: a second detect pass is a no-op. expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.bun)).toBe(false); @@ -2547,11 +2488,9 @@ describe('ensureVitePlusBootstrap', () => { const result = ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.npm)); expect(result.changed).toBe(true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - expect(pkg.devDependencies.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); - const devKeys = Object.keys(pkg.devDependencies); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], VITE_PLUS_OVERRIDE_PACKAGES.vite); + const devKeys = Object.keys(fixtureObject(pkg, 'devDependencies')); expect(devKeys).toEqual([...devKeys].toSorted()); expect(devKeys.indexOf('vite')).toBeLessThan(devKeys.indexOf('vite-plus')); }); @@ -2570,9 +2509,7 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); expect(pkg.devDependencies).toEqual({ 'vite-plus': 'catalog:' }); }); @@ -2599,13 +2536,12 @@ describe('ensureVitePlusBootstrap', () => { // EOVERRIDE error. The project does NOT use vitest directly (no @vitest/* // dep, no vitest source), so the stale deleted wrapper override is removed. expect(result.changed).toBe(true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - overrides: Record; - }; - expect(pkg.overrides.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(pkg.overrides.vitest).toBeUndefined(); - expect(pkg.overrides['@vitest/expect']).toBeUndefined(); - expect(pkg.overrides['@vitest/coverage-v8']).toBeUndefined(); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['overrides', 'vite'], 'npm:@voidzero-dev/vite-plus-core@latest'); + const overrides = fixtureObject(pkg, 'overrides'); + expect(overrides.vitest).toBeUndefined(); + expect(overrides['@vitest/expect']).toBeUndefined(); + expect(overrides['@vitest/coverage-v8']).toBeUndefined(); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); }); @@ -2681,13 +2617,13 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(true); ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.npm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - overrides: Record; - }; - expect(pkg.devDependencies['vite-plus']).toBe('latest'); - expect(pkg.devDependencies.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(pkg.overrides.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'latest'); + expect(pkg).toHaveProperty( + ['devDependencies', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); + expect(pkg).toHaveProperty(['overrides', 'vite'], 'npm:@voidzero-dev/vite-plus-core@latest'); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); } finally { if (savedForceMigrate === undefined) { @@ -2720,14 +2656,14 @@ describe('ensureVitePlusBootstrap', () => { expect(result.changed).toBe(true); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - dependencies: Record; - }; - expect(pkg.devDependencies.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty( + ['devDependencies', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); // Common case (no @vitest/* dep, no vitest source): the direct `vitest` dep // is removed — it arrives transitively through vite-plus. - expect(pkg.dependencies.vitest).toBeUndefined(); + expect(fixtureObject(pkg, 'dependencies').vitest).toBeUndefined(); }); it('normalizes catalog vite-plus pins for npm projects', () => { @@ -2751,10 +2687,8 @@ describe('ensureVitePlusBootstrap', () => { expect(result.changed).toBe(true); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - expect(pkg.devDependencies['vite-plus']).toBe('latest'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'latest'); }); it('adds missing pnpm workspace overrides without writing optional setup files', () => { @@ -2811,13 +2745,9 @@ describe('ensureVitePlusBootstrap', () => { const first = ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); expect(first.packageManagerConfig).toBe(true); - expect( - ( - readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - blockExoticSubdeps: boolean; - } - ).blockExoticSubdeps, - ).toBe(false); + expect(readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')).blockExoticSubdeps).toBe( + false, + ); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); expect(ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)).changed).toBe( false, @@ -2855,12 +2785,11 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)), ).not.toThrow(); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - peerDependencyRules: { allowAny: string[]; allowedVersions: Record }; - }; - expect(workspace.peerDependencyRules.allowAny).toContain('react'); - expect(workspace.peerDependencyRules.allowAny).toContain('vite'); - expect(workspace.peerDependencyRules.allowedVersions.vite).toBe('*'); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + const allowAny = fixtureObject(workspace, 'peerDependencyRules').allowAny; + expect(allowAny).toContain('react'); + expect(allowAny).toContain('vite'); + expect(workspace).toHaveProperty(['peerDependencyRules', 'allowedVersions', 'vite'], '*'); }); it('detects missing pnpm workspace catalog entry for vite-plus', () => { @@ -2898,10 +2827,8 @@ describe('ensureVitePlusBootstrap', () => { expect(result.changed).toBe(true); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - }; - expect(workspace.catalog['vite-plus']).toBe('latest'); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(workspace).toHaveProperty(['catalog', 'vite-plus'], 'latest'); }); it('removes bundled tools and the old lint backend from the manifest and catalog of an existing pnpm project', () => { @@ -2935,23 +2862,21 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - expect(pkg.devDependencies.oxfmt).toBeUndefined(); - expect(pkg.devDependencies.oxlint).toBeUndefined(); - expect(pkg.devDependencies['oxlint-tsgolint']).toBeUndefined(); - expect(pkg.devDependencies.tsdown).toBeUndefined(); + const pkg = readJson(path.join(tmpDir, 'package.json')); + const devDependencies = fixtureObject(pkg, 'devDependencies'); + expect(devDependencies.oxfmt).toBeUndefined(); + expect(devDependencies.oxlint).toBeUndefined(); + expect(devDependencies['oxlint-tsgolint']).toBeUndefined(); + expect(devDependencies.tsdown).toBeUndefined(); // vite-plus itself stays a managed catalog dependency. - expect(pkg.devDependencies['vite-plus']).toBe('catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - }; - expect(workspace.catalog.oxfmt).toBeUndefined(); - expect(workspace.catalog.oxlint).toBeUndefined(); - expect(workspace.catalog['oxlint-tsgolint']).toBeUndefined(); - expect(workspace.catalog.tsdown).toBeUndefined(); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + const catalog = fixtureObject(workspace, 'catalog'); + expect(catalog.oxfmt).toBeUndefined(); + expect(catalog.oxlint).toBeUndefined(); + expect(catalog['oxlint-tsgolint']).toBeUndefined(); + expect(catalog.tsdown).toBeUndefined(); }); it('reconciles stale pnpm-workspace.yaml overrides when package.json has an empty pnpm field (urllib shape)', () => { @@ -2994,12 +2919,10 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); // The deleted wrapper alias must no longer survive in the workspace.yaml. - const workspaceRaw = fs.readFileSync(path.join(tmpDir, 'pnpm-workspace.yaml'), 'utf-8'); + const workspaceRaw = fs.readFileSync(path.join(tmpDir, 'pnpm-workspace.yaml'), 'utf8'); expect(workspaceRaw).not.toContain('@voidzero-dev/vite-plus-test'); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - expect(pkg.devDependencies.vitest).toBe('catalog:'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], 'catalog:'); expect(JSON.stringify(pkg)).not.toContain('@voidzero-dev/vite-plus-test'); // And the project must not be left pending (no stale wrapper override anywhere). @@ -3031,11 +2954,9 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(true); ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.npm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - expect(pkg.devDependencies['@vitest/coverage-v8']).toBe(VITEST_VERSION); - expect(pkg.devDependencies.vitest).toBe(VITEST_VERSION); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/coverage-v8'], VITEST_VERSION); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], VITEST_VERSION); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); }); @@ -3064,13 +2985,11 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.npm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - expect(pkg.devDependencies['@vitest/ui']).toBe(VITEST_VERSION); - expect(pkg.devDependencies['@vitest/web-worker']).toBe(VITEST_VERSION); - expect(pkg.devDependencies['@vitest/eslint-plugin']).toBe('^1.0.0'); - expect(pkg.devDependencies.vitest).toBe(VITEST_VERSION); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/ui'], VITEST_VERSION); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/web-worker'], VITEST_VERSION); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/eslint-plugin'], '^1.0.0'); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], VITEST_VERSION); }); it('prefers existing catalogs for Vitest ecosystem packages and catalog-izes the rest', () => { @@ -3137,21 +3056,16 @@ describe('ensureVitePlusBootstrap', () => { ).toBe(true); ensureVitePlusBootstrap(workspaceInfo); - const pkg = readJson(path.join(appDir, 'package.json')) as { - devDependencies: Record; - }; - expect(pkg.devDependencies['@vitest/coverage-istanbul']).toBe('catalog:'); - expect(pkg.devDependencies['@vitest/ui']).toBe('catalog:test'); + const pkg = readJson(path.join(appDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/coverage-istanbul'], 'catalog:'); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/ui'], 'catalog:test'); // #2005: web-worker had no prior catalog entry; it is catalog-ized into the default catalog. - expect(pkg.devDependencies['@vitest/web-worker']).toBe('catalog:'); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/web-worker'], 'catalog:'); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - catalogs: Record>; - }; - expect(workspace.catalog['@vitest/coverage-istanbul']).toBe(VITEST_VERSION); - expect(workspace.catalog['@vitest/web-worker']).toBe(VITEST_VERSION); - expect(workspace.catalogs.test['@vitest/ui']).toBe(VITEST_VERSION); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(workspace).toHaveProperty(['catalog', '@vitest/coverage-istanbul'], VITEST_VERSION); + expect(workspace).toHaveProperty(['catalog', '@vitest/web-worker'], VITEST_VERSION); + expect(workspace).toHaveProperty(['catalogs', 'test', '@vitest/ui'], VITEST_VERSION); expect( detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm, workspaceInfo.packages), ).toBe(false); @@ -3205,24 +3119,23 @@ describe('ensureVitePlusBootstrap', () => { packages: [{ name: 'app', path: 'packages/app' }], }); - const appPkg = readJson(path.join(appDir, 'package.json')) as { - devDependencies: Record; - }; - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - }; + const appPkg = readJson(path.join(appDir, 'package.json')); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); // The vitest-ecosystem refs stay `catalog:` (catalogs are supported here — the // sibling typescript/vue refs are untouched), rather than being inlined to a // concrete pin. - expect(appPkg.devDependencies.vitest).toBe('catalog:'); - expect(appPkg.devDependencies['@vitest/coverage-istanbul']).toBe('catalog:'); - expect(appPkg.devDependencies.typescript).toBe('catalog:'); + expect(appPkg).toHaveProperty(['devDependencies', 'vitest'], 'catalog:'); + expect(appPkg).toHaveProperty(['devDependencies', '@vitest/coverage-istanbul'], 'catalog:'); + expect(appPkg).toHaveProperty(['devDependencies', 'typescript'], 'catalog:'); // The catalog ENTRIES are rewritten: the legacy vitest wrapper alias becomes // upstream vitest, @vitest/coverage-istanbul aligns to it, and the vite alias // advances to the managed core target. - expect(workspace.catalog.vitest).toBe(VITEST_VERSION); - expect(workspace.catalog['@vitest/coverage-istanbul']).toBe(VITEST_VERSION); - expect(workspace.catalog.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); + expect(workspace).toHaveProperty(['catalog', 'vitest'], VITEST_VERSION); + expect(workspace).toHaveProperty(['catalog', '@vitest/coverage-istanbul'], VITEST_VERSION); + expect(workspace).toHaveProperty( + ['catalog', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); }); it('keeps vite-plus catalog: without adding vite for a vite-plus consumer (varlet-cli #10)', () => { @@ -3268,13 +3181,10 @@ describe('ensureVitePlusBootstrap', () => { packages: [{ name: 'cli', path: 'packages/cli' }], }); - const cliPkg = readJson(path.join(cliDir, 'package.json')) as { - dependencies: Record; - devDependencies?: Record; - }; + const cliPkg = readJson(path.join(cliDir, 'package.json')); // vite-plus stays catalog: (not inlined to the concrete toolchain version). - expect(cliPkg.dependencies['vite-plus']).toBe('catalog:'); - expect(cliPkg.devDependencies?.vite).toBeUndefined(); + expect(cliPkg).toHaveProperty(['dependencies', 'vite-plus'], 'catalog:'); + expect(fixtureObject(cliPkg.devDependencies ?? {}).vite).toBeUndefined(); }); it('keeps toolchain catalog: refs on a pnpm 9.5-10.6.1 catalog project (varlet-import-resolver #10)', () => { @@ -3323,14 +3233,12 @@ describe('ensureVitePlusBootstrap', () => { }; ensureVitePlusBootstrap(workspaceInfo); - const pkg = readJson(path.join(pkgDir, 'package.json')) as { - devDependencies: Record; - }; + const pkg = readJson(path.join(pkgDir, 'package.json')); // pnpm 9.15.9 supports catalogs (>= 9.5.0), so the reconciled toolchain edges // stay catalog: rather than being inlined to the concrete toolchain version. - expect(pkg.devDependencies['vite-plus']).toBe('catalog:'); - expect(pkg.devDependencies.vite).toBeUndefined(); - expect(pkg.devDependencies['@types/node']).toBe('catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); + expect(fixtureObject(pkg, 'devDependencies').vite).toBeUndefined(); + expect(pkg).toHaveProperty(['devDependencies', '@types/node'], 'catalog:'); }); it('pins the toolchain to concrete on pnpm < 9.5.0 (catalogs unsupported)', () => { @@ -3381,14 +3289,12 @@ describe('ensureVitePlusBootstrap', () => { }; ensureVitePlusBootstrap(workspaceInfo); - const pkg = readJson(path.join(pkgDir, 'package.json')) as { - devDependencies: Record; - }; + const pkg = readJson(path.join(pkgDir, 'package.json')); // 9.4.0 < 9.5.0: the existing toolchain edge is concrete. - expect(pkg.devDependencies['vite-plus']).not.toBe('catalog:'); - expect(pkg.devDependencies.vite).toBeUndefined(); + expect(fixtureObject(pkg, 'devDependencies')['vite-plus']).not.toBe('catalog:'); + expect(fixtureObject(pkg, 'devDependencies').vite).toBeUndefined(); // Untouched non-toolchain catalog refs are left as-is. - expect(pkg.devDependencies['@types/node']).toBe('catalog:'); + expect(pkg).toHaveProperty(['devDependencies', '@types/node'], 'catalog:'); }); it('rewrites the catalog and keeps pnpm.overrides catalog: below pnpm 10.6.2 (varlet #10)', () => { @@ -3468,11 +3374,9 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.npm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - expect(pkg.devDependencies['@vitest/coverage-c8']).toBe('^0.33.0'); - expect(pkg.devDependencies.vitest).toBe(VITEST_VERSION); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/coverage-c8'], '^0.33.0'); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], VITEST_VERSION); }); it('detects a required Vitest peer from Yarn PnP dependency metadata', () => { @@ -3521,12 +3425,9 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.yarn)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - resolutions: Record; - }; - expect(pkg.devDependencies.vitest).toBe('catalog:'); - expect(pkg.resolutions.vitest).toBe(VITEST_VERSION); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], 'catalog:'); + expect(pkg).toHaveProperty(['resolutions', 'vitest'], VITEST_VERSION); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.yarn)).toBe(false); }); @@ -3552,12 +3453,9 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.npm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - overrides: Record; - }; - expect(pkg.devDependencies.vitest).toBe(VITEST_VERSION); - expect(pkg.overrides.vitest).toBe(VITEST_VERSION); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], VITEST_VERSION); + expect(pkg).toHaveProperty(['overrides', 'vitest'], VITEST_VERSION); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); }); @@ -3613,12 +3511,9 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.npm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - overrides: Record; - }; - expect(pkg.devDependencies.vitest).toBe(VITEST_VERSION); - expect(pkg.overrides.vitest).toBe(VITEST_VERSION); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], VITEST_VERSION); + expect(pkg).toHaveProperty(['overrides', 'vitest'], VITEST_VERSION); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); }); @@ -3649,14 +3544,11 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.npm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - overrides: Record; - }; - expect(pkg.devDependencies['@vitest/eslint-plugin']).toBe('^1.6.0'); - expect(pkg.devDependencies['@vitest/utils']).toBe(VITEST_VERSION); - expect(pkg.devDependencies.vitest).toBeUndefined(); - expect(pkg.overrides.vitest).toBeUndefined(); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/eslint-plugin'], '^1.6.0'); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/utils'], VITEST_VERSION); + expect(fixtureObject(pkg, 'devDependencies').vitest).toBeUndefined(); + expect(fixtureObject(pkg, 'overrides').vitest).toBeUndefined(); }); it('keeps a declared browser peer range on the first migration', () => { @@ -3745,7 +3637,7 @@ describe('ensureVitePlusBootstrap', () => { name: 'root', private: true, workspaces: workspace.workspacePatterns, - ...(manager === PackageManager.bun ? { catalogs } : {}), + ...(manager === PackageManager.bun ? { catalogs } : undefined), }); if (manager !== PackageManager.bun) { fs.writeFileSync(catalogFile, JSON.stringify({ catalogs })); @@ -3829,16 +3721,12 @@ describe('ensureVitePlusBootstrap', () => { ).toBe(true); ensureVitePlusBootstrap(workspaceInfo); - const rootPkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - const appPkg = readJson(path.join(appDir, 'package.json')) as { - devDependencies: Record; - }; - expect(rootPkg.devDependencies.vitest).toBeUndefined(); - expect(appPkg.devDependencies['vite-plus']).toBe('catalog:'); - expect(appPkg.devDependencies['@vitest/ui']).toBe('catalog:'); - expect(appPkg.devDependencies.vitest).toBe('catalog:'); + const rootPkg = readJson(path.join(tmpDir, 'package.json')); + const appPkg = readJson(path.join(appDir, 'package.json')); + expect(fixtureObject(rootPkg, 'devDependencies').vitest).toBeUndefined(); + expect(appPkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); + expect(appPkg).toHaveProperty(['devDependencies', '@vitest/ui'], 'catalog:'); + expect(appPkg).toHaveProperty(['devDependencies', 'vitest'], 'catalog:'); expect(JSON.stringify(appPkg)).not.toContain('@voidzero-dev/vite-plus-test'); expect( detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm, workspaceInfo.packages), @@ -3905,10 +3793,8 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(workspaceInfo); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalogs: { legacy: Record }; - }; - expect(workspace.catalogs.legacy['vite-plus']).toBe('latest'); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(workspace).toHaveProperty(['catalogs', 'legacy', 'vite-plus'], 'latest'); expect( detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm, workspaceInfo.packages), ).toBe(false); @@ -3952,16 +3838,12 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(true); ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - expect(pkg.devDependencies['@vitest/browser-playwright']).toBe('catalog:'); - expect(pkg.devDependencies.playwright).toBe('*'); - expect(pkg.devDependencies.vitest).toBe('catalog:'); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - }; - expect(workspace.catalog['@vitest/browser-playwright']).toBe(VITEST_VERSION); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/browser-playwright'], 'catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'playwright'], '*'); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], 'catalog:'); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(workspace).toHaveProperty(['catalog', '@vitest/browser-playwright'], VITEST_VERSION); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); @@ -4006,12 +3888,10 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(true); ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); expect(pkg.devDependencies).not.toHaveProperty('playwright'); - expect(pkg.devDependencies.vitest).toBe('catalog:'); - expect(pkg.devDependencies['@vitest/browser-playwright']).toBe('catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], 'catalog:'); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/browser-playwright'], 'catalog:'); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); @@ -4081,23 +3961,17 @@ describe('ensureVitePlusBootstrap', () => { }; ensureVitePlusBootstrap(workspaceInfo); - const rootPkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - const appPkg = readJson(path.join(appDir, 'package.json')) as { - devDependencies: Record; - }; - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - }; + const rootPkg = readJson(path.join(tmpDir, 'package.json')); + const appPkg = readJson(path.join(appDir, 'package.json')); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); // The catalog gains the provider (added because the workspace uses it // source-only), so BOTH the injected (workspace) and the pre-installed (root) // specs must reference the catalog, not a concrete version. - expect(workspace.catalog['@vitest/browser-playwright']).toBe(VITEST_VERSION); - expect(rootPkg.devDependencies['@vitest/browser-playwright']).toBe('catalog:'); - expect(appPkg.devDependencies['@vitest/browser-playwright']).toBe('catalog:'); - expect(rootPkg.devDependencies.playwright).toBe('^1.60.0'); - expect(rootPkg.devDependencies.vitest).toBe('catalog:'); + expect(workspace).toHaveProperty(['catalog', '@vitest/browser-playwright'], VITEST_VERSION); + expect(rootPkg).toHaveProperty(['devDependencies', '@vitest/browser-playwright'], 'catalog:'); + expect(appPkg).toHaveProperty(['devDependencies', '@vitest/browser-playwright'], 'catalog:'); + expect(rootPkg).toHaveProperty(['devDependencies', 'playwright'], '^1.60.0'); + expect(rootPkg).toHaveProperty(['devDependencies', 'vitest'], 'catalog:'); }); it('resolves a Vitest peer catalog before removing its managed catalog entry', () => { @@ -4134,16 +4008,11 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(true); ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - peerDependencies: Record; - }; - expect(pkg.peerDependencies.vitest).toBe('^4.0.0'); - expect(pkg.devDependencies.vitest).toBeUndefined(); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalogs: Record>; - }; - expect(workspace.catalogs.test.vitest).toBeUndefined(); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['peerDependencies', 'vitest'], '^4.0.0'); + expect(fixtureObject(pkg, 'devDependencies').vitest).toBeUndefined(); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(fixtureObject(workspace, 'catalogs', 'test').vitest).toBeUndefined(); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); @@ -4177,21 +4046,15 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - peerDependencies: Record; - }; - expect(pkg.peerDependencies['@vitest/browser-playwright']).toBe('^4.0.0'); - expect(pkg.devDependencies['@vitest/browser-playwright']).toBe('catalog:'); - expect(pkg.devDependencies.playwright).toBe('*'); - expect(pkg.devDependencies.vitest).toBe('catalog:'); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - overrides: Record; - }; - expect(workspace.catalog['@vitest/browser-playwright']).toBe(VITEST_VERSION); - expect(workspace.catalog.vitest).toBe(VITEST_VERSION); - expect(workspace.overrides[PNPM_VITEST_OVERRIDE_KEY]).toBe('catalog:'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['peerDependencies', '@vitest/browser-playwright'], '^4.0.0'); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/browser-playwright'], 'catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'playwright'], '*'); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], 'catalog:'); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(workspace).toHaveProperty(['catalog', '@vitest/browser-playwright'], VITEST_VERSION); + expect(workspace).toHaveProperty(['catalog', 'vitest'], VITEST_VERSION); + expect(workspace).toHaveProperty(['overrides', PNPM_VITEST_OVERRIDE_KEY], 'catalog:'); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); @@ -4256,10 +4119,8 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); const result = ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.npm)); expect(result.changed).toBe(false); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - overrides: Record; - }; - expect(pkg.overrides.vitest).toEqual({ '@vitest/runner': '4.0.0' }); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['overrides', 'vitest'], { '@vitest/runner': '4.0.0' }); }); it('removes a stale vitest wrapper override for a common-case npm project (no @vitest/* dep, no vitest source)', () => { @@ -4287,11 +4148,9 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(true); ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.npm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - overrides: Record; - }; - expect(pkg.overrides.vitest).toBeUndefined(); - expect(pkg.overrides.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(fixtureObject(pkg, 'overrides').vitest).toBeUndefined(); + expect(pkg).toHaveProperty(['overrides', 'vite'], 'npm:@voidzero-dev/vite-plus-core@latest'); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); }); @@ -4320,14 +4179,11 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(true); ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.npm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - overrides: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); // vitest stays managed (the stale wrapper is re-pinned to the bundled version). - expect(pkg.overrides.vitest).toBe(VITEST_VERSION); + expect(pkg).toHaveProperty(['overrides', 'vitest'], VITEST_VERSION); // Coverage provider aligned to the same bundled vitest version. - expect(pkg.devDependencies['@vitest/coverage-v8']).toBe(VITEST_VERSION); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/coverage-v8'], VITEST_VERSION); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.npm)).toBe(false); }); @@ -4370,19 +4226,18 @@ describe('ensureVitePlusBootstrap', () => { expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(true); ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - overrides: Record; - peerDependencyRules: { allowAny: string[]; allowedVersions: Record }; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); // Managed `vitest` is gone from every sink; `vite` stays managed. - expect(workspace.catalog.vitest).toBeUndefined(); - expect(workspace.catalog.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(workspace.overrides[PNPM_VITEST_OVERRIDE_KEY]).toBeUndefined(); - expect(workspace.overrides.vitest).toBeUndefined(); - expect(workspace.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:'); - expect(workspace.peerDependencyRules.allowAny).toEqual(['vite']); - expect(workspace.peerDependencyRules.allowedVersions).toEqual({ vite: '*' }); + expect(fixtureObject(workspace, 'catalog').vitest).toBeUndefined(); + expect(workspace).toHaveProperty( + ['catalog', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); + expect(fixtureObject(workspace, 'overrides')[PNPM_VITEST_OVERRIDE_KEY]).toBeUndefined(); + expect(fixtureObject(workspace, 'overrides').vitest).toBeUndefined(); + expect(workspace).toHaveProperty(['overrides', PNPM_VITE_OVERRIDE_KEY], 'catalog:'); + expect(workspace).toHaveProperty(['peerDependencyRules', 'allowAny'], ['vite']); + expect(workspace).toHaveProperty(['peerDependencyRules', 'allowedVersions'], { vite: '*' }); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); @@ -4418,11 +4273,9 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); // vite-plus must no longer be pinned to the old 0.1.x range. - expect(pkg.devDependencies['vite-plus']).not.toContain('0.1.24'); + expect(fixtureObject(pkg, 'devDependencies')['vite-plus']).not.toContain('0.1.24'); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); @@ -4440,22 +4293,15 @@ describe('ensureVitePlusBootstrap', () => { expect(result.changed).toBe(true); expect(fs.existsSync(path.join(tmpDir, 'pnpm-workspace.yaml'))).toBe(true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - dependencies: Record; - devDependencies?: Record; - pnpm?: unknown; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); // vite-plus was declared in `dependencies`, so it is normalized in place // (to `catalog:`) and not duplicated into `devDependencies`. - expect(pkg.dependencies['vite-plus']).toBe('catalog:'); - expect(pkg.devDependencies?.['vite-plus']).toBeUndefined(); + expect(pkg).toHaveProperty(['dependencies', 'vite-plus'], 'catalog:'); + expect(fixtureObject(pkg.devDependencies ?? {})['vite-plus']).toBeUndefined(); expect(pkg.pnpm).toBeUndefined(); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - overrides: Record; - }; - expect(workspace.catalog['vite-plus']).toBe('latest'); - expect(workspace.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:'); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(workspace).toHaveProperty(['catalog', 'vite-plus'], 'latest'); + expect(workspace).toHaveProperty(['overrides', PNPM_VITE_OVERRIDE_KEY], 'catalog:'); }); it('moves existing pnpm settings to pnpm-workspace.yaml', () => { @@ -4513,19 +4359,10 @@ describe('ensureVitePlusBootstrap', () => { expect(result.changed).toBe(true); expect(fs.existsSync(path.join(tmpDir, 'pnpm-workspace.yaml'))).toBe(true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - pnpm?: unknown; - }; - expect(pkg.devDependencies['vite-plus']).toBe('catalog:'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); expect(pkg.pnpm).toBeUndefined(); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - onlyBuiltDependencies: string[]; - packageExtensions: Record; - patchedDependencies: Record; - overrides: Record; - peerDependencyRules: { allowAny: string[]; allowedVersions: Record }; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); expect(workspace.onlyBuiltDependencies).toEqual(['sharp', 'esbuild']); expect(workspace.packageExtensions).toEqual({ 'other-package@*': { peerDependencies: { vue: '*' } }, @@ -4535,9 +4372,12 @@ describe('ensureVitePlusBootstrap', () => { 'is-even@1.0.0': 'patches/is-even.patch', 'is-odd@3.0.1': 'patches/is-odd.patch', }); - expect(workspace.overrides.react).toBe('18.3.1'); - expect(workspace.peerDependencyRules.allowAny).toEqual(['react', 'vite']); - expect(workspace.peerDependencyRules.allowedVersions).toEqual({ react: '*', vite: '*' }); + expect(workspace).toHaveProperty(['overrides', 'react'], '18.3.1'); + expect(workspace).toHaveProperty(['peerDependencyRules', 'allowAny'], ['react', 'vite']); + expect(workspace).toHaveProperty(['peerDependencyRules', 'allowedVersions'], { + react: '*', + vite: '*', + }); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); @@ -4563,25 +4403,17 @@ describe('ensureVitePlusBootstrap', () => { // toolchain deps to `catalog:` and the catalog itself MUST be written // (creating pnpm-workspace.yaml when missing) or the install cannot // resolve them. The pnpm SETTINGS still stay in package.json. - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - overrides?: unknown; - peerDependencyRules?: unknown; - }; - expect(workspace.catalog['vite-plus']).toBe('latest'); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(workspace).toHaveProperty(['catalog', 'vite-plus'], 'latest'); expect(workspace.overrides).toBeUndefined(); expect(workspace.peerDependencyRules).toBeUndefined(); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - pnpm: { - overrides: Record; - peerDependencyRules: { allowAny: string[] }; - }; - }; - expect(pkg.pnpm.overrides.react).toBe('18.3.1'); - expect(pkg.pnpm.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe( + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['pnpm', 'overrides', 'react'], '18.3.1'); + expect(pkg).toHaveProperty( + ['pnpm', 'overrides', PNPM_VITE_OVERRIDE_KEY], 'npm:@voidzero-dev/vite-plus-core@latest', ); - expect(pkg.pnpm.peerDependencyRules.allowAny).toEqual(['react', 'vite']); + expect(pkg).toHaveProperty(['pnpm', 'peerDependencyRules', 'allowAny'], ['react', 'vite']); }); it('preserves unknown package.json pnpm keys while moving supported settings', () => { @@ -4599,14 +4431,10 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - pnpm: { app: { target: string }; overrides?: unknown }; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); expect(pkg.pnpm).toEqual({ app: { target: 'desktop' } }); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - overrides: Record; - }; - expect(workspace.overrides.react).toBe('18.3.1'); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(workspace).toHaveProperty(['overrides', 'react'], '18.3.1'); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); @@ -4638,17 +4466,12 @@ describe('ensureVitePlusBootstrap', () => { expect(result.changed).toBe(true); expect(fs.existsSync(path.join(tmpDir, 'pnpm-workspace.yaml'))).toBe(true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies?: Record; - dependencies: Record; - optionalDependencies: Record; - pnpm?: unknown; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); // vite-plus already lives in `dependencies` (and `optionalDependencies`), so // it is kept in place and not duplicated into `devDependencies`. - expect(pkg.devDependencies?.['vite-plus']).toBeUndefined(); - expect(pkg.dependencies['vite-plus']).toBe('catalog:'); - expect(pkg.optionalDependencies['vite-plus']).toBe('catalog:'); + expect(fixtureObject(pkg.devDependencies ?? {})['vite-plus']).toBeUndefined(); + expect(pkg).toHaveProperty(['dependencies', 'vite-plus'], 'catalog:'); + expect(pkg).toHaveProperty(['optionalDependencies', 'vite-plus'], 'catalog:'); expect(pkg.pnpm).toBeUndefined(); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); @@ -4671,15 +4494,11 @@ describe('ensureVitePlusBootstrap', () => { expect(result.changed).toBe(true); expect(fs.existsSync(path.join(tmpDir, 'pnpm-workspace.yaml'))).toBe(true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - dependencies: Record; - devDependencies?: Record; - pnpm?: unknown; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); // vite-plus was declared in `dependencies`, so it is normalized in place // (to `catalog:`) and not duplicated into `devDependencies`. - expect(pkg.dependencies['vite-plus']).toBe('catalog:'); - expect(pkg.devDependencies?.['vite-plus']).toBeUndefined(); + expect(pkg).toHaveProperty(['dependencies', 'vite-plus'], 'catalog:'); + expect(fixtureObject(pkg.devDependencies ?? {})['vite-plus']).toBeUndefined(); expect(pkg.pnpm).toBeUndefined(); }); @@ -4706,23 +4525,17 @@ describe('ensureVitePlusBootstrap', () => { expect(result.changed).toBe(true); expect(result.packageManagerConfig).toBe(true); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.yarn)).toBe(false); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - resolutions: Record; - }; - expect(pkg.devDependencies.vite).toBe('catalog:'); - expect(pkg.devDependencies['vite-plus']).toBe('catalog:'); - expect(pkg.resolutions.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')) as { - nodeLinker: string; - catalog: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], 'catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); + expect(pkg).toHaveProperty(['resolutions', 'vite'], 'npm:@voidzero-dev/vite-plus-core@latest'); + const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')); expect(yarnrc.nodeLinker).toBe('node-modules'); - expect(yarnrc.catalog.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); + expect(yarnrc).toHaveProperty(['catalog', 'vite'], 'npm:@voidzero-dev/vite-plus-core@latest'); // Common case (no @vitest/* dep, no vitest source): `vitest` is not managed, // so no catalog entry is written for it. - expect(yarnrc.catalog.vitest).toBeUndefined(); - expect(yarnrc.catalog['vite-plus']).toBe('latest'); + expect(fixtureObject(yarnrc, 'catalog').vitest).toBeUndefined(); + expect(yarnrc).toHaveProperty(['catalog', 'vite-plus'], 'latest'); }); it('completes missing pnpm workspace peer dependency rules', () => { @@ -4758,15 +4571,11 @@ describe('ensureVitePlusBootstrap', () => { // Common case (no @vitest/* dep, no vitest source): the pre-existing managed // `vitest` catalog/override/peer entries are REMOVED — only `vite` stays // managed. vitest arrives transitively through vite-plus. - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - overrides: Record; - peerDependencyRules: { allowAny: string[]; allowedVersions: Record }; - }; - expect(workspace.catalog.vitest).toBeUndefined(); - expect(workspace.overrides.vitest).toBeUndefined(); - expect(workspace.peerDependencyRules.allowAny).toEqual(['vite']); - expect(workspace.peerDependencyRules.allowedVersions).toEqual({ + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(fixtureObject(workspace, 'catalog').vitest).toBeUndefined(); + expect(fixtureObject(workspace, 'overrides').vitest).toBeUndefined(); + expect(workspace).toHaveProperty(['peerDependencyRules', 'allowAny'], ['vite']); + expect(workspace).toHaveProperty(['peerDependencyRules', 'allowedVersions'], { vite: '*', }); }); @@ -4797,9 +4606,7 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - minimumReleaseAgeExclude: string[]; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); // Vite+ pins a possibly-fresh vitest; its family must bypass the gate. expect(workspace.minimumReleaseAgeExclude).toContain('vitest'); expect(workspace.minimumReleaseAgeExclude).toContain('@vitest/*'); @@ -4834,7 +4641,7 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - minimumReleaseAgeExclude?: string[]; + minimumReleaseAgeExclude?: Array; }; // No gate present → we never introduce the exclude list. expect(workspace.minimumReleaseAgeExclude).toBeUndefined(); @@ -4867,11 +4674,11 @@ describe('ensureVitePlusBootstrap', () => { expect(workspace.trustPolicy).toBe('no-downgrade'); expect(workspace.trustPolicyExclude).toEqual([existingException, `tsrs@${tsrsPkg.version}`]); expect(workspace.trustLockfile).toBeUndefined(); - const after = fs.readFileSync(workspacePath, 'utf-8'); + const after = fs.readFileSync(workspacePath, 'utf8'); expect(after).toContain('# Keep the project exception.'); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); expect(ensureVitePlusBootstrap(workspaceInfo).changed).toBe(false); - expect(fs.readFileSync(workspacePath, 'utf-8')).toBe(after); + expect(fs.readFileSync(workspacePath, 'utf8')).toBe(after); }, ); @@ -4932,9 +4739,7 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.yarn)); - const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')) as { - npmPreapprovedPackages: string[]; - }; + const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')); expect(yarnrc.npmPreapprovedPackages).toContain('@my-org/*'); expect(yarnrc.npmPreapprovedPackages).toContain('vitest'); expect(yarnrc.npmPreapprovedPackages).toContain('@vitest/*'); @@ -4957,9 +4762,7 @@ describe('ensureVitePlusBootstrap', () => { }); expect(result.changed).toBe(true); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - packages: string[]; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); expect(workspace.packages).toEqual(['packages/*']); }); @@ -4981,13 +4784,10 @@ describe('ensureVitePlusBootstrap', () => { const firstPackageJson = fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf8'); const firstYarnrc = fs.readFileSync(path.join(tmpDir, '.yarnrc.yml'), 'utf8'); - const pkg = JSON.parse(firstPackageJson) as { - devDependencies: Record; - devEngines?: unknown; - }; - expect(pkg.devDependencies.vite).toBe('catalog:'); - expect(pkg.devDependencies['vite-plus']).toBe('catalog:'); - expect(pkg.devDependencies.vitest).toBeUndefined(); + const pkg = fixtureObject(JSON.parse(firstPackageJson)); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], 'catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); + expect(fixtureObject(pkg, 'devDependencies').vitest).toBeUndefined(); expect(pkg.devEngines).toBeUndefined(); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.yarn)).toBe(false); @@ -5029,9 +4829,7 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.yarn)); - const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')) as { - npmPreapprovedPackages: string[]; - }; + const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')); expect(yarnrc.npmPreapprovedPackages).toContain('vitest'); expect(yarnrc.npmPreapprovedPackages).toContain('@vitest/*'); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.yarn)).toBe(false); @@ -5093,9 +4891,7 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, PackageManager.pnpm)); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - minimumReleaseAgeExclude: string[]; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); expect(workspace.minimumReleaseAgeExclude).toContain('vitest'); expect(workspace.minimumReleaseAgeExclude).toContain('@vitest/*'); expect(workspace.minimumReleaseAgeExclude).toContain('vite-plus'); @@ -5147,10 +4943,8 @@ describe('ensureVitePlusBootstrap', () => { ensureVitePlusBootstrap(workspaceInfo); // The vite-plus-depending workspace still gets the direct vite edge. - const libPkg = readJson(path.join(libDir, 'package.json')) as { - devDependencies: Record; - }; - expect(libPkg.devDependencies.vite).toBe('catalog:'); + const libPkg = readJson(path.join(libDir, 'package.json')); + expect(libPkg).toHaveProperty(['devDependencies', 'vite'], 'catalog:'); // The unrelated workspace is left exactly as written (no injected vite). const utilPkg = readJson(path.join(utilDir, 'package.json')) as { @@ -5295,13 +5089,10 @@ describe('yarn catalog version gating', () => { // back to concrete specs exactly like the non-catalog (npm) path. rewriteStandaloneProject(tmpDir, yarnWorkspaceInfo('3.6.0'), true, true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - resolutions: Record; - }; - expect(pkg.devDependencies['vite-plus']).toBe('latest'); - expect(pkg.devDependencies.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); - expect(pkg.resolutions.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'latest'); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], VITE_PLUS_OVERRIDE_PACKAGES.vite); + expect(pkg).toHaveProperty(['resolutions', 'vite'], VITE_PLUS_OVERRIDE_PACKAGES.vite); // No catalog field is written into .yarnrc.yml; nodeLinker is still set. const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')); @@ -5323,16 +5114,12 @@ describe('yarn catalog version gating', () => { rewriteStandaloneProject(tmpDir, yarnWorkspaceInfo('4.12.0'), true, true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - expect(pkg.devDependencies['vite-plus']).toBe('catalog:'); - expect(pkg.devDependencies.vite).toBe('catalog:'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], 'catalog:'); - const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')) as { - catalog: Record; - }; - expect(yarnrc.catalog.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); + const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')); + expect(yarnrc).toHaveProperty(['catalog', 'vite'], VITE_PLUS_OVERRIDE_PACKAGES.vite); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.yarn, undefined, '4.12.0')).toBe( false, @@ -5357,12 +5144,10 @@ describe('yarn catalog version gating', () => { rewriteMonorepo(workspaceInfo, true); - const appPkg = readJson(path.join(appDir, 'package.json')) as { - devDependencies: Record; - }; + const appPkg = readJson(path.join(appDir, 'package.json')); // Below 4.10.0 → concrete edges, never `catalog:` references. - expect(appPkg.devDependencies['vite-plus']).toBe('latest'); - expect(appPkg.devDependencies.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); + expect(appPkg).toHaveProperty(['devDependencies', 'vite-plus'], 'latest'); + expect(appPkg).toHaveProperty(['devDependencies', 'vite'], VITE_PLUS_OVERRIDE_PACKAGES.vite); const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')); expect(yarnrc.catalog).toBeUndefined(); @@ -5387,14 +5172,10 @@ describe('yarn catalog version gating', () => { rewriteMonorepo(workspaceInfo, true); - const appPkg = readJson(path.join(appDir, 'package.json')) as { - devDependencies: Record; - }; - expect(appPkg.devDependencies.vite).toBe('catalog:'); - const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')) as { - catalog: Record; - }; - expect(yarnrc.catalog.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); + const appPkg = readJson(path.join(appDir, 'package.json')); + expect(appPkg).toHaveProperty(['devDependencies', 'vite'], 'catalog:'); + const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')); + expect(yarnrc).toHaveProperty(['catalog', 'vite'], VITE_PLUS_OVERRIDE_PACKAGES.vite); }); }); @@ -5460,7 +5241,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(pkg.pnpm).toBeUndefined(); // devDependencies should use catalog: - const devDeps = pkg.devDependencies as Record; + const devDeps = fixtureObject(pkg.devDependencies); expect(devDeps.vite).toBe('catalog:'); expect(devDeps['vite-plus']).toBe('catalog:'); @@ -5468,7 +5249,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(readYaml(path.join(tmpDir, 'pnpm-workspace.yaml'))).toBe(yaml); }); - it.each<[string, string[] | undefined]>([ + it.each<[string, Array | undefined]>([ ['9.15.9', ['.']], ['10.4.1', ['.']], ['10.5.0', undefined], @@ -5535,7 +5316,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { // package.json emits catalog: specs (this part already works today). const pkg = readJson(path.join(tmpDir, 'package.json')); - const devDeps = pkg.devDependencies as Record; + const devDeps = fixtureObject(pkg.devDependencies); expect(devDeps.vite).toBe('catalog:'); expect(devDeps['vite-plus']).toBe('catalog:'); @@ -5584,18 +5365,14 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(fs.existsSync(path.join(tmpDir, 'pnpm-workspace.yaml'))).toBe(true); const pkg = readJson(path.join(tmpDir, 'package.json')); expect(pkg.pnpm).toBeUndefined(); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - overrides: Record; - peerDependencyRules: Record; - onlyBuiltDependencies: string[]; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); const overrides = workspace.overrides; - expect(overrides['some-pkg']).toBe('1.0.0'); - expect(overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:'); + expect(overrides).toHaveProperty(['some-pkg'], '1.0.0'); + expect(overrides).toHaveProperty([PNPM_VITE_OVERRIDE_KEY], 'catalog:'); // Common case (no @vitest/* dep, no vitest source): `vitest` is not managed, // so no override is written — it arrives transitively through vite-plus. - expect(overrides[PNPM_VITEST_OVERRIDE_KEY]).toBeUndefined(); - expect(overrides.vitest).toBeUndefined(); + expect(fixtureObject(overrides)[PNPM_VITEST_OVERRIDE_KEY]).toBeUndefined(); + expect(fixtureObject(overrides).vitest).toBeUndefined(); // peerDependencyRules should be present expect(workspace.peerDependencyRules).toEqual({ @@ -5624,15 +5401,13 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { const pkg = readJson(path.join(tmpDir, 'package.json')); expect(pkg.pnpm).toBeUndefined(); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - peerDependencyRules: Record; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); const rules = workspace.peerDependencyRules; // Custom entries preserved, Vite entries merged (vitest is no longer // injected as it's not a managed override key anymore). - expect(rules.allowAny).toEqual(expect.arrayContaining(['react', 'vite'])); + expect(rules).toHaveProperty(['allowAny'], expect.arrayContaining(['react', 'vite'])); // ignoreMissing preserved - expect(rules.ignoreMissing).toEqual(['@types/node']); + expect(rules).toHaveProperty(['ignoreMissing'], ['@types/node']); }); it('writes vite overrides with catalog references to pnpm-workspace.yaml', () => { @@ -5663,18 +5438,14 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - overrides: Record; - }; - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + const pkg = readJson(path.join(tmpDir, 'package.json')); expect(PNPM_VITE_OVERRIDE_KEY).toBe('vite@*'); - expect(Object.keys(workspace.overrides)).toEqual([PNPM_VITE_OVERRIDE_KEY]); - expect(workspace.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:'); + expect(Object.keys(fixtureObject(workspace, 'overrides'))).toEqual([PNPM_VITE_OVERRIDE_KEY]); + expect(workspace).toHaveProperty(['overrides', PNPM_VITE_OVERRIDE_KEY], 'catalog:'); // The importer keeps referencing the catalog: that is what the override key // must no longer be able to rewrite. - expect(pkg.devDependencies.vite).toBe('catalog:'); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], 'catalog:'); }); it('drops a pre-#2309 bare managed pnpm override key when adding the ranged one', () => { @@ -5697,14 +5468,12 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - overrides: Record; - }; - expect(workspace.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:'); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(workspace).toHaveProperty(['overrides', PNPM_VITE_OVERRIDE_KEY], 'catalog:'); expect(workspace.overrides).not.toHaveProperty('vite'); // Unrelated user overrides are untouched — the rewrite only re-keys managed // entries. - expect(workspace.overrides.react).toBe('18.3.1'); + expect(workspace).toHaveProperty(['overrides', 'react'], '18.3.1'); // A project still on the bare key must read as pending so one `vp migrate` // repairs it; once re-keyed it converges. expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); @@ -5730,12 +5499,10 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.pnpm, '9.15.9'), true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - pnpm: { overrides: Record }; - }; - expect(pkg.pnpm.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:'); - expect(pkg.pnpm.overrides).not.toHaveProperty('vite'); - expect(pkg.pnpm.overrides.react).toBe('^18.0.0'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['pnpm', 'overrides', PNPM_VITE_OVERRIDE_KEY], 'catalog:'); + expect(fixtureObject(pkg, 'pnpm').overrides).not.toHaveProperty('vite'); + expect(pkg).toHaveProperty(['pnpm', 'overrides', 'react'], '^18.0.0'); }); it('carries a legacy named-catalog override value onto the ranged key (#2309 review P2)', () => { @@ -5761,11 +5528,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { true, ); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - pnpm: { overrides: Record }; - }; - expect(pkg.pnpm.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:toolchain'); - expect(pkg.pnpm.overrides).not.toHaveProperty('vite'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['pnpm', 'overrides', PNPM_VITE_OVERRIDE_KEY], 'catalog:toolchain'); + expect(fixtureObject(pkg, 'pnpm').overrides).not.toHaveProperty('vite'); }); it('treats a leftover bare key as pending beside a valid ranged key (#2309 review P2)', () => { @@ -5792,11 +5557,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { // One more migrate run drops the bare key and converges again. rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - overrides: Record; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); expect(workspace.overrides).not.toHaveProperty('vite'); - expect(workspace.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:'); + expect(workspace).toHaveProperty(['overrides', PNPM_VITE_OVERRIDE_KEY], 'catalog:'); }); it('leaves a user-authored ranged npm override alone (#2309 review P2)', () => { @@ -5813,10 +5576,8 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.npm), true, true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - overrides: Record; - }; - expect(pkg.overrides['vitest@*']).toBe('3.2.4'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['overrides', 'vitest@*'], '3.2.4'); }); it('rewrites named catalogs in pnpm-workspace.yaml without adding new entries', () => { @@ -5853,40 +5614,37 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - overrides: Record; - catalogs: Record>; - }; + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); // A pre-#2309 bare key hands its named-catalog choice to the range-qualified // key and is dropped, so only one managed `vite` override remains. - expect(yaml.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:vite7'); - expect(yaml.overrides.vite).toBeUndefined(); + expect(yaml).toHaveProperty(['overrides', PNPM_VITE_OVERRIDE_KEY], 'catalog:vite7'); + expect(fixtureObject(yaml, 'overrides').vite).toBeUndefined(); // Common case (no @vitest/* dep, no vitest source): `vitest` is not managed, // so no override is added and the pre-existing managed `vitest` catalog // entries (default + named) are REMOVED — it arrives transitively through // vite-plus. - expect(yaml.overrides[PNPM_VITEST_OVERRIDE_KEY]).toBeUndefined(); - expect(yaml.overrides.vitest).toBeUndefined(); - expect(yaml.catalog?.vitest).toBeUndefined(); - expect(yaml.catalogs.vite7.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(yaml.catalogs.vite7.react).toBe('^18.0.0'); - expect(yaml.catalogs.vite7['vite-plus']).toBe('latest'); - expect(yaml.catalogs.test.vitest).toBeUndefined(); - expect(yaml.catalogs.test.tsdown).toBeUndefined(); - expect(yaml.catalogs.test['vite-plus']).toBeUndefined(); + expect(fixtureObject(yaml, 'overrides')[PNPM_VITEST_OVERRIDE_KEY]).toBeUndefined(); + expect(fixtureObject(yaml, 'overrides').vitest).toBeUndefined(); + expect(fixtureObject(yaml.catalog ?? {}).vitest).toBeUndefined(); + expect(yaml).toHaveProperty( + ['catalogs', 'vite7', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); + expect(yaml).toHaveProperty(['catalogs', 'vite7', 'react'], '^18.0.0'); + expect(yaml).toHaveProperty(['catalogs', 'vite7', 'vite-plus'], 'latest'); + const testCatalog = fixtureObject(yaml, 'catalogs', 'test'); + expect(testCatalog.vitest).toBeUndefined(); + expect(testCatalog.tsdown).toBeUndefined(); + expect(testCatalog['vite-plus']).toBeUndefined(); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - peerDependencies: Record; - }; - expect(pkg.devDependencies.vite).toBe('catalog:vite7'); - expect(pkg.devDependencies['vite-plus']).toBe('catalog:vite7'); - expect(pkg.peerDependencies.vite).toBe('^7.0.0'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], 'catalog:vite7'); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:vite7'); + expect(pkg).toHaveProperty(['peerDependencies', 'vite'], '^7.0.0'); // Peer declarations do not keep the managed catalog alive. Resolve the // catalog entry to its public range before pruning it so the peer cannot // dangle after migration. - expect(pkg.peerDependencies.vitest).toBe('^4.0.0'); + expect(pkg).toHaveProperty(['peerDependencies', 'vitest'], '^4.0.0'); expect(pkg.peerDependencies).not.toHaveProperty('tsdown'); }); @@ -5926,22 +5684,19 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { } } - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog?: Record; - catalogs: Record>; - overrides: Record; - }; - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + const pkg = readJson(path.join(tmpDir, 'package.json')); expect(workspace.catalog).toBeUndefined(); - expect(workspace.catalogs.default).toEqual({ rari: '^0.14.12' }); - expect(workspace.catalogs.build.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(workspace.catalogs.build['vite-plus']).toBe('latest'); - expect(workspace.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:build'); - expect(pkg.devDependencies.vite).toBe('catalog:build'); - expect(pkg.devDependencies['vite-plus']).toBe('catalog:build'); + expect(workspace).toHaveProperty(['catalogs', 'default'], { rari: '^0.14.12' }); + expect(workspace).toHaveProperty( + ['catalogs', 'build', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); + expect(workspace).toHaveProperty(['catalogs', 'build', 'vite-plus'], 'latest'); + expect(workspace).toHaveProperty(['overrides', PNPM_VITE_OVERRIDE_KEY], 'catalog:build'); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], 'catalog:build'); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:build'); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); @@ -5972,19 +5727,16 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { 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 pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], 'catalog:legacy'); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 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(migratedResolver(fixtureString(pkg, 'devDependencies', 'vite-plus'), 'vite-plus')).toBe( + 'latest', + ); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); expect(workspace.catalog).toBeUndefined(); - expect(workspace.catalogs[second]['vite-plus']).toBeUndefined(); + expect(fixtureObject(workspace, 'catalogs', second)['vite-plus']).toBeUndefined(); }); it('writes managed dependencies into an active catalogs.default definition', () => { @@ -6022,17 +5774,16 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { } } - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog?: Record; - catalogs: Record>; - overrides: Record; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); expect(workspace.catalog).toBeUndefined(); - expect(workspace.catalogs.default.react).toBe('^19.0.0'); - expect(workspace.catalogs.default.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(workspace.catalogs.default['vite-plus']).toBe('latest'); - expect(workspace.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:'); + expect(workspace).toHaveProperty(['catalogs', 'default', 'react'], '^19.0.0'); + expect(workspace).toHaveProperty( + ['catalogs', 'default', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); + expect(workspace).toHaveProperty(['catalogs', 'default', 'vite-plus'], 'latest'); + expect(workspace).toHaveProperty(['overrides', PNPM_VITE_OVERRIDE_KEY], 'catalog:'); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); @@ -6073,22 +5824,19 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { } } - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog?: Record; - catalogs: Record>; - overrides: Record; - }; - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + const pkg = readJson(path.join(tmpDir, 'package.json')); expect(workspace.catalog).toBeUndefined(); - expect(workspace.catalogs['repo-tooling']).toEqual({ prettier: '3.8.3' }); - expect(workspace.catalogs['vite-stack'].vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(workspace.catalogs['vite-stack']['vite-plus']).toBe('latest'); - expect(workspace.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:vite-stack'); - expect(pkg.devDependencies.vite).toBe('catalog:vite-stack'); - expect(pkg.devDependencies['vite-plus']).toBe('catalog:vite-stack'); + expect(workspace).toHaveProperty(['catalogs', 'repo-tooling'], { prettier: '3.8.3' }); + expect(workspace).toHaveProperty( + ['catalogs', 'vite-stack', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); + expect(workspace).toHaveProperty(['catalogs', 'vite-stack', 'vite-plus'], 'latest'); + expect(workspace).toHaveProperty(['overrides', PNPM_VITE_OVERRIDE_KEY], 'catalog:vite-stack'); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], 'catalog:vite-stack'); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:vite-stack'); expect(detectVitePlusBootstrapPending(tmpDir, PackageManager.pnpm)).toBe(false); }); @@ -6130,9 +5878,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { const pkg = readJson(path.join(tmpDir, 'package.json')) as { pnpm?: unknown }; expect(pkg.pnpm).toBeUndefined(); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - overrides: Record; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); const overrides = workspace.overrides; // Playwright-as-TARGET: vite-plus parent and versioned global pin reach // vite-plus's own (now direct-dep) provider — dropped. @@ -6145,19 +5891,22 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(overrides).not.toHaveProperty('vite-plus>@vitest/browser-preview>@vitest/browser'); // Provider-as-TARGET selector scoped under a SPECIFIC non-vite-plus parent — // PRESERVED. - expect(overrides['some-app>@vitest/browser-playwright']).toBe('^4.0.0'); - expect(overrides['some-app>@vitest/browser-preview>@vitest/browser']).toBe('4.0.0'); + expect(overrides).toHaveProperty(['some-app>@vitest/browser-playwright'], '^4.0.0'); + expect(overrides).toHaveProperty(['some-app>@vitest/browser-preview>@vitest/browser'], '4.0.0'); // Playwright is opt-in (not a vite-plus-owned ancestor), so a chain PARENTED // by it constrains the user's own subtree — PRESERVED even with a vite-plus // prefix above it. - expect(overrides['@vitest/browser-playwright>@vitest/browser']).toBe('4.0.0'); - expect(overrides['vite-plus>@vitest/browser-playwright>@vitest/browser']).toBe('4.0.0'); + expect(overrides).toHaveProperty(['@vitest/browser-playwright>@vitest/browser'], '4.0.0'); + expect(overrides).toHaveProperty( + ['vite-plus>@vitest/browser-playwright>@vitest/browser'], + '4.0.0', + ); // A chain with an outer non-vite-plus ancestor (`a>vite-plus>…`) requires // vite-plus to sit UNDER `a`, so it never matches the root vite-plus edge — // PRESERVED. - expect(overrides['a>vite-plus>@vitest/browser-playwright']).toBe('^4.0.0'); + expect(overrides).toHaveProperty(['a>vite-plus>@vitest/browser-playwright'], '^4.0.0'); // Unrelated selector keys must survive. - expect(overrides['other>foo']).toBe('1.0.0'); + expect(overrides).toHaveProperty(['other>foo'], '1.0.0'); }); it('drops a vite-plus-scoped provider pin and prunes the emptied vite-plus parent', () => { @@ -6182,7 +5931,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.npm), true, true); const pkg = readJson(path.join(tmpDir, 'package.json')) as { - overrides?: Record; + overrides?: JsonObject; }; const overrides = pkg.overrides ?? {}; // `vite-plus` parent (with playwright-as-target child) is dropped and pruned. @@ -6261,18 +6010,15 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.npm), true, true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - overrides?: Record; - }; - expect(pkg.devDependencies['@vitest/coverage-v8']).toBe(VITEST_VERSION); - expect(pkg.devDependencies['@vitest/coverage-istanbul']).toBe(VITEST_VERSION); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/coverage-v8'], VITEST_VERSION); + expect(pkg).toHaveProperty(['devDependencies', '@vitest/coverage-istanbul'], VITEST_VERSION); // vitest itself is still pinned to the bundled version. - expect(pkg.devDependencies.vitest).toBe(VITEST_VERSION); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], VITEST_VERSION); // …and coverage is never written into the override sink. const overrides = pkg.overrides ?? {}; - expect(overrides['@vitest/coverage-v8']).toBeUndefined(); - expect(overrides['@vitest/coverage-istanbul']).toBeUndefined(); + expect(fixtureObject(overrides)['@vitest/coverage-v8']).toBeUndefined(); + expect(fixtureObject(overrides)['@vitest/coverage-istanbul']).toBeUndefined(); }); it('removes direct vitest in the same pass that rewrites ordinary vitest imports', () => { @@ -6290,12 +6036,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.npm), true, true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - overrides: Record; - }; - expect(pkg.devDependencies.vitest).toBeUndefined(); - expect(pkg.overrides.vitest).toBeUndefined(); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(fixtureObject(pkg, 'devDependencies').vitest).toBeUndefined(); + expect(fixtureObject(pkg, 'overrides').vitest).toBeUndefined(); expect(fs.readFileSync(path.join(tmpDir, 'example.spec.ts'), 'utf8')).toContain( "from 'vite-plus/test'", ); @@ -6333,12 +6076,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { report, ); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - overrides: Record; - }; - expect(pkg.devDependencies.vitest).toBe(VITEST_VERSION); - expect(pkg.overrides.vitest).toBe(VITEST_VERSION); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vitest'], VITEST_VERSION); + expect(pkg).toHaveProperty(['overrides', 'vitest'], VITEST_VERSION); const nuxtTest = fs.readFileSync(path.join(tmpDir, 'nuxt.spec.ts'), 'utf8'); expect(nuxtTest).toContain("from 'vitest'"); expect(nuxtTest).toContain("from 'vitest/config'"); @@ -6358,11 +6098,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.npm), true, true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; - expect(pkg.devDependencies['@vitest/coverage-v8']).toBeUndefined(); - expect(pkg.devDependencies['@vitest/coverage-istanbul']).toBeUndefined(); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(fixtureObject(pkg, 'devDependencies')['@vitest/coverage-v8']).toBeUndefined(); + expect(fixtureObject(pkg, 'devDependencies')['@vitest/coverage-istanbul']).toBeUndefined(); }); it('drops a vite-plus-scoped provider pin while keeping non-provider siblings', () => { @@ -6405,7 +6143,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.npm), true, true); const pkg = readJson(path.join(tmpDir, 'package.json')) as { - overrides?: Record; + overrides?: JsonObject; }; const overrides = pkg.overrides ?? {}; expect(overrides).not.toHaveProperty('@vitest/browser-playwright'); @@ -6483,7 +6221,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.npm), true, true); const pkg = readJson(path.join(tmpDir, 'package.json')) as { - overrides?: Record; + overrides?: JsonObject; }; const overrides = pkg.overrides ?? {}; expect(overrides).not.toHaveProperty('vite-plus'); @@ -6554,7 +6292,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.npm), true, true); const pkg = readJson(path.join(tmpDir, 'package.json')) as { - overrides?: Record; + overrides?: JsonObject; }; const overrides = pkg.overrides ?? {}; expect(overrides).not.toHaveProperty('@vitest/browser-playwright'); @@ -6621,9 +6359,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - overrides: Record; - }; + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); // Playwright is opt-in: vite-plus keeps it in the user's deps pinned to the // bundled vitest version, but a stale override pinning an old version (as a // TARGET — bare/versioned/global pin, or a `vite-plus`-parented selector) @@ -6635,11 +6371,11 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(yaml.overrides).not.toHaveProperty('vite-plus>@vitest/browser-playwright'); // A provider-as-TARGET selector scoped under a SPECIFIC non-vite-plus parent // only constrains that parent's subtree, so it is PRESERVED. - expect(yaml.overrides['some-app>@vitest/browser-playwright']).toBe('4.0.0'); + expect(yaml).toHaveProperty(['overrides', 'some-app>@vitest/browser-playwright'], '4.0.0'); // Community provider overrides remain user-owned. - expect(yaml.overrides['@vitest/browser-webdriverio']).toBe('4.0.0'); - expect(yaml.overrides['some-other-pkg']).toBe('1.0.0'); - expect(yaml.overrides['unrelated>some-other-pkg']).toBe('1.0.0'); + expect(yaml).toHaveProperty(['overrides', '@vitest/browser-webdriverio'], '4.0.0'); + expect(yaml).toHaveProperty(['overrides', 'some-other-pkg'], '1.0.0'); + expect(yaml).toHaveProperty(['overrides', 'unrelated>some-other-pkg'], '1.0.0'); }); it('removes ADJACENT `dependency>vite` override selectors from pnpm-workspace.yaml', () => { @@ -6667,9 +6403,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - overrides: Record; - }; + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); // BOTH adjacent `...>vite` selectors must be gone. The second one survived // before the fix because the first's deletion shifted it into the slot the // `for...of` had already advanced past. @@ -6677,7 +6411,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(yaml.overrides).not.toHaveProperty('vite-plugin-svgr>vite'); // The managed `vite` override stays and unrelated selectors survive. expect(yaml.overrides).toHaveProperty(PNPM_VITE_OVERRIDE_KEY); - expect(yaml.overrides['some-other-pkg']).toBe('1.0.0'); + expect(yaml).toHaveProperty(['overrides', 'some-other-pkg'], '1.0.0'); }); it('adds a direct vitest dep when a vite config enables browser mode', () => { @@ -6702,7 +6436,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); const pkg = readJson(path.join(tmpDir, 'package.json')); - const devDeps = pkg.devDependencies as Record; + const devDeps = fixtureObject(pkg.devDependencies); expect(devDeps.vitest).toBe('catalog:'); expect(devDeps['vite-plus']).toBe('catalog:'); }); @@ -6721,10 +6455,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const devDeps = readJson(path.join(tmpDir, 'package.json')).devDependencies as Record< - string, - string - >; + const devDeps = fixtureObject(readJson(path.join(tmpDir, 'package.json')).devDependencies); expect(devDeps.vitest).toBe('catalog:'); }); @@ -6765,10 +6496,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const devDeps = readJson(path.join(tmpDir, 'package.json')).devDependencies as Record< - string, - string - >; + const devDeps = fixtureObject(readJson(path.join(tmpDir, 'package.json')).devDependencies); // Browser mode pins a direct `vitest`… expect(devDeps.vitest).toBe('catalog:'); // …but must NOT inject any browser/provider dep the source never asked for. @@ -6803,9 +6531,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf8')).toContain( "from '@vitest/browser-webdriverio'", ); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - }; + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); expect(workspace.catalog).not.toHaveProperty('@vitest/browser-webdriverio'); }); @@ -6833,16 +6559,11 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const devDeps = readJson(path.join(tmpDir, 'package.json')).devDependencies as Record< - string, - string - >; + const devDeps = fixtureObject(readJson(path.join(tmpDir, 'package.json')).devDependencies); expect(devDeps).toHaveProperty('@vitest/browser-playwright', 'catalog:'); expect(devDeps.playwright).toBe('*'); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - }; - expect(yaml.catalog['@vitest/browser-playwright']).toBe(VITEST_VERSION); + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(yaml).toHaveProperty(['catalog', '@vitest/browser-playwright'], VITEST_VERSION); }); it.each([ @@ -6877,17 +6598,12 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const devDeps = readJson(path.join(tmpDir, 'package.json')).devDependencies as Record< - string, - string - >; + const devDeps = fixtureObject(readJson(path.join(tmpDir, 'package.json')).devDependencies); expect(devDeps[`@vitest/browser-${provider}`]).toBe('catalog:'); expect(devDeps[provider]).toBe('*'); expect(devDeps.vitest).toBe('catalog:'); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - }; - expect(workspace.catalog[`@vitest/browser-${provider}`]).toBe(VITEST_VERSION); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(workspace).toHaveProperty(['catalog', `@vitest/browser-${provider}`], VITEST_VERSION); expect(fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf8')).toContain( `from 'vite-plus/test/${subpath}'`, ); @@ -6932,17 +6648,12 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { true, ); - const devDeps = readJson(path.join(tmpDir, 'package.json')).devDependencies as Record< - string, - string - >; + const devDeps = fixtureObject(readJson(path.join(tmpDir, 'package.json')).devDependencies); expect(devDeps['@vitest/browser-playwright']).toBe('catalog:'); expect(devDeps.playwright).toBe('^1.56.1'); expect(devDeps.vitest).toBe('catalog:'); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - }; - expect(workspace.catalog['@vitest/browser-playwright']).toBe(VITEST_VERSION); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(workspace).toHaveProperty(['catalog', '@vitest/browser-playwright'], VITEST_VERSION); expect(fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf8')).toContain( "from 'vite-plus/test/browser-playwright'", ); @@ -6972,16 +6683,11 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const devDeps = readJson(path.join(tmpDir, 'package.json')).devDependencies as Record< - string, - string - >; + const devDeps = fixtureObject(readJson(path.join(tmpDir, 'package.json')).devDependencies); expect(devDeps).toHaveProperty('@vitest/browser-playwright', 'catalog:'); expect(devDeps.playwright).toBe('*'); - const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - }; - expect(workspace.catalog['@vitest/browser-playwright']).toBe(VITEST_VERSION); + const workspace = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(workspace).toHaveProperty(['catalog', '@vitest/browser-playwright'], VITEST_VERSION); }); it('keeps a peer-only catalog webdriverio provider resolvable (no dangling catalog reference)', () => { @@ -7006,20 +6712,15 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); const pkg = readJson(path.join(tmpDir, 'package.json')); - const devDeps = pkg.devDependencies as Record; + const devDeps = fixtureObject(pkg.devDependencies); expect(devDeps).not.toHaveProperty('@vitest/browser-webdriverio'); expect(devDeps).not.toHaveProperty('webdriverio'); - expect((pkg.peerDependencies as Record)['@vitest/browser-webdriverio']).toBe( - 'catalog:', - ); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - catalog: Record; - allowBuilds: Record; - }; - expect(yaml.catalog['@vitest/browser-webdriverio']).toBe('4.0.0'); - expect(yaml.catalog.vitest).toBe(VITEST_VERSION); - expect(yaml.allowBuilds.edgedriver).toBe(true); - expect(yaml.allowBuilds.geckodriver).toBe(true); + expect(fixtureObject(pkg.peerDependencies)['@vitest/browser-webdriverio']).toBe('catalog:'); + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(yaml).toHaveProperty(['catalog', '@vitest/browser-webdriverio'], '4.0.0'); + expect(yaml).toHaveProperty(['catalog', 'vitest'], VITEST_VERSION); + expect(yaml).toHaveProperty(['allowBuilds', 'edgedriver'], true); + expect(yaml).toHaveProperty(['allowBuilds', 'geckodriver'], true); }); it('preserves community WebDriverIO dependency versions and overrides', () => { @@ -7034,10 +6735,10 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.npm), true, true); const pkg = readJson(path.join(tmpDir, 'package.json')); - const overrides = pkg.overrides as Record; + const overrides = fixtureObject(pkg.overrides); expect(overrides['@vitest/browser-webdriverio']).toBe('4.0.0'); expect(overrides['some-other-pkg']).toBe('1.0.0'); - const devDeps = pkg.devDependencies as Record; + const devDeps = fixtureObject(pkg.devDependencies); expect(devDeps['@vitest/browser-webdriverio']).toBe('^4.0.0'); expect(devDeps).not.toHaveProperty('webdriverio'); }); @@ -7058,10 +6759,10 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.npm), true, true); const pkg = readJson(path.join(tmpDir, 'package.json')); - const overrides = pkg.overrides as Record; + const overrides = fixtureObject(pkg.overrides); expect(overrides).not.toHaveProperty('@vitest/browser-playwright'); expect(overrides['some-other-pkg']).toBe('1.0.0'); - const devDeps = pkg.devDependencies as Record; + const devDeps = fixtureObject(pkg.devDependencies); expect(devDeps['@vitest/browser-playwright']).toBe(VITEST_VERSION); expect(devDeps.playwright).toBe('*'); }); @@ -7087,11 +6788,11 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.npm), true, true); const pkg = readJson(path.join(tmpDir, 'package.json')); - const overrides = pkg.overrides as Record; + const overrides = fixtureObject(pkg.overrides); expect(overrides).not.toHaveProperty('@vitest/browser-playwright@>=4'); // Unrelated comparator-range override preserved. expect(overrides['some-other-pkg@>=1']).toBe('1.0.0'); - const devDeps = pkg.devDependencies as Record; + const devDeps = fixtureObject(pkg.devDependencies); expect(devDeps['@vitest/browser-playwright']).toBe(VITEST_VERSION); expect(devDeps.playwright).toBe('*'); }); @@ -7110,10 +6811,10 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.yarn), true, true); const pkg = readJson(path.join(tmpDir, 'package.json')); - const resolutions = pkg.resolutions as Record; + const resolutions = fixtureObject(pkg.resolutions); expect(resolutions).not.toHaveProperty('@vitest/browser-playwright'); expect(resolutions['some-other-pkg']).toBe('1.0.0'); - const devDeps = pkg.devDependencies as Record; + const devDeps = fixtureObject(pkg.devDependencies); expect(devDeps['@vitest/browser-playwright']).toBe('catalog:'); expect(devDeps.playwright).toBe('*'); // #2005: the catalog: ref is backed by a .yarnrc.yml catalog entry (not dangling). @@ -7157,7 +6858,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.yarn), true, true); const pkg = readJson(path.join(tmpDir, 'package.json')); - const resolutions = pkg.resolutions as Record; + const resolutions = fixtureObject(pkg.resolutions); // Glob parent matches all parents (incl. vite-plus) — dropped. expect(resolutions).not.toHaveProperty('**/@vitest/browser-playwright'); // Name glob that matches vite-plus — dropped. @@ -7182,7 +6883,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { expect(resolutions['some-parent/vite-*/@vitest/browser-playwright']).toBe('4.0.0'); // Unrelated selector resolutions survive. expect(resolutions['**/some-other-pkg']).toBe('1.0.0'); - const devDeps = pkg.devDependencies as Record; + const devDeps = fixtureObject(pkg.devDependencies); expect(devDeps['@vitest/browser-playwright']).toBe('catalog:'); expect(devDeps.playwright).toBe('*'); }); @@ -7214,7 +6915,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.yarn), true, true); const pkg = readJson(path.join(tmpDir, 'package.json')); - const resolutions = pkg.resolutions as Record; + const resolutions = fixtureObject(pkg.resolutions); // Parent-through-provider key targets some-transitive-dep — preserved. expect(resolutions['@vitest/browser-playwright@4/some-transitive-dep']).toBe('1.0.0'); // npm-alias key targets `fork` (the aliased descriptor), not the provider — preserved. @@ -7222,7 +6923,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { // The bare key DOES target the provider — pruned so it can't force the // stale provider over the migrated bundled-version dep. expect(resolutions).not.toHaveProperty('@vitest/browser-playwright'); - const devDeps = pkg.devDependencies as Record; + const devDeps = fixtureObject(pkg.devDependencies); expect(devDeps['@vitest/browser-playwright']).toBe('catalog:'); expect(devDeps.playwright).toBe('*'); }); @@ -7238,10 +6939,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const devDeps = readJson(path.join(tmpDir, 'package.json')).devDependencies as Record< - string, - string - >; + const devDeps = fixtureObject(readJson(path.join(tmpDir, 'package.json')).devDependencies); expect(devDeps).not.toHaveProperty('vitest'); }); @@ -7271,10 +6969,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const devDeps = readJson(path.join(tmpDir, 'package.json')).devDependencies as Record< - string, - string - >; + const devDeps = fixtureObject(readJson(path.join(tmpDir, 'package.json')).devDependencies); expect(devDeps.vitest).toBe('catalog:'); expect(devDeps['vite-plus']).toBe('catalog:'); // Playwright is opt-in: vite-plus keeps the provider in the user's deps, @@ -7306,18 +7001,18 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - overrides: Record; - catalogs: Record>; - }; - expect(yaml.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:vite7'); - expect(yaml.overrides.vite).toBeUndefined(); + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(yaml).toHaveProperty(['overrides', PNPM_VITE_OVERRIDE_KEY], 'catalog:vite7'); + expect(fixtureObject(yaml, 'overrides').vite).toBeUndefined(); // Common case (no @vitest/* dep, no vitest source): `vitest` is not managed, // so no `vitest` override is injected. - expect(yaml.overrides[PNPM_VITEST_OVERRIDE_KEY]).toBeUndefined(); - expect(yaml.overrides.vitest).toBeUndefined(); - expect(yaml.overrides.react).toBe('^18.0.0'); - expect(yaml.catalogs.vite7.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); + expect(fixtureObject(yaml, 'overrides')[PNPM_VITEST_OVERRIDE_KEY]).toBeUndefined(); + expect(fixtureObject(yaml, 'overrides').vitest).toBeUndefined(); + expect(yaml).toHaveProperty(['overrides', 'react'], '^18.0.0'); + expect(yaml).toHaveProperty( + ['catalogs', 'vite7', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); const pkg = readJson(path.join(tmpDir, 'package.json')) as { pnpm?: unknown; @@ -7355,15 +7050,13 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - overrides: Record; - }; - expect(yaml.overrides[PNPM_VITE_OVERRIDE_KEY]).toBe('catalog:'); - expect(yaml.overrides.vite).toBeUndefined(); + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(yaml).toHaveProperty(['overrides', PNPM_VITE_OVERRIDE_KEY], 'catalog:'); + expect(fixtureObject(yaml, 'overrides').vite).toBeUndefined(); // Common case (no @vitest/* dep, no vitest source): `vitest` is not managed, // so no `vitest` override is added. - expect(yaml.overrides[PNPM_VITEST_OVERRIDE_KEY]).toBeUndefined(); - expect(yaml.overrides.vitest).toBeUndefined(); + expect(fixtureObject(yaml, 'overrides')[PNPM_VITEST_OVERRIDE_KEY]).toBeUndefined(); + expect(fixtureObject(yaml, 'overrides').vitest).toBeUndefined(); }); it('does not resolve peer dependency catalog specs to migrated aliases', () => { @@ -7391,12 +7084,10 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - peerDependencies: Record; - }; - expect(pkg.peerDependencies.vite).toBe('*'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['peerDependencies', 'vite'], '*'); // Never expose the deleted wrapper alias as a public peer range. - expect(pkg.peerDependencies.vitest).toBe('*'); + expect(pkg).toHaveProperty(['peerDependencies', 'vitest'], '*'); }); it('adds vitest only to the monorepo package that uses browser mode', () => { @@ -7429,16 +7120,12 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { workspaceInfo.packages = [{ name: '@vibe/dashboard', path: 'apps/dashboard' }]; rewriteMonorepo(workspaceInfo, true); - const rootDeps = (readJson(path.join(tmpDir, 'package.json')).devDependencies ?? {}) as Record< - string, - string - >; + const rootDeps = fixtureObject( + readJson(path.join(tmpDir, 'package.json')).devDependencies ?? {}, + ); expect(rootDeps).not.toHaveProperty('vitest'); - const appDeps = readJson(path.join(appDir, 'package.json')).devDependencies as Record< - string, - string - >; + const appDeps = fixtureObject(readJson(path.join(appDir, 'package.json')).devDependencies); expect(appDeps.vitest).toBe('catalog:'); }); @@ -8089,11 +7776,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - allowBuilds: Record; - }; - expect(yaml.allowBuilds.edgedriver).toBe(true); - expect(yaml.allowBuilds.geckodriver).toBe(true); + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(yaml).toHaveProperty(['allowBuilds', 'edgedriver'], true); + expect(yaml).toHaveProperty(['allowBuilds', 'geckodriver'], true); }); it('allows edgedriver/geckodriver builds when only @vitest/browser-webdriverio is declared (pnpm v10)', () => { @@ -8114,11 +7799,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - allowBuilds: Record; - }; - expect(yaml.allowBuilds.edgedriver).toBe(true); - expect(yaml.allowBuilds.geckodriver).toBe(true); + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(yaml).toHaveProperty(['allowBuilds', 'edgedriver'], true); + expect(yaml).toHaveProperty(['allowBuilds', 'geckodriver'], true); }); it('allows edgedriver/geckodriver builds when @vitest/browser-webdriverio is declared only in peerDependencies (pnpm v10)', () => { @@ -8141,11 +7824,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - allowBuilds: Record; - }; - expect(yaml.allowBuilds.edgedriver).toBe(true); - expect(yaml.allowBuilds.geckodriver).toBe(true); + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(yaml).toHaveProperty(['allowBuilds', 'edgedriver'], true); + expect(yaml).toHaveProperty(['allowBuilds', 'geckodriver'], true); }); it('preserves explicit allowBuilds entries and adds nothing else on second run (idempotent)', () => { @@ -8159,18 +7840,14 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const firstPass = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - allowBuilds: Record; - }; + const firstPass = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); // explicit user choice survives; with no webdriverio the missing geckodriver entry is // left absent (vite-plus no longer writes a default deny). - expect(firstPass.allowBuilds.edgedriver).toBe(true); - expect('geckodriver' in firstPass.allowBuilds).toBe(false); + expect(firstPass).toHaveProperty(['allowBuilds', 'edgedriver'], true); + expect(firstPass.allowBuilds).not.toHaveProperty('geckodriver'); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const secondPass = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - allowBuilds: Record; - }; + const secondPass = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); expect(secondPass.allowBuilds).toEqual(firstPass.allowBuilds); }); @@ -8192,11 +7869,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - allowBuilds: Record; - }; - expect(yaml.allowBuilds.edgedriver).toBe(true); - expect(yaml.allowBuilds.geckodriver).toBe(true); + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(yaml).toHaveProperty(['allowBuilds', 'edgedriver'], true); + expect(yaml).toHaveProperty(['allowBuilds', 'geckodriver'], true); }); it('leaves a user-authored driver denial untouched on a re-migration (pnpm v10, no webdriverio)', () => { @@ -8218,11 +7893,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - allowBuilds: Record; - }; - expect(yaml.allowBuilds.edgedriver).toBe(false); - expect(yaml.allowBuilds.geckodriver).toBe(false); + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(yaml).toHaveProperty(['allowBuilds', 'edgedriver'], false); + expect(yaml).toHaveProperty(['allowBuilds', 'geckodriver'], false); }); it('preserves a user-approved (true) direct-driver dep on a re-migration (pnpm-workspace.yaml v10)', () => { @@ -8243,12 +7916,10 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - allowBuilds: Record; - }; + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); // user's approval survives; not-owned geckodriver denial stays - expect(yaml.allowBuilds.edgedriver).toBe(true); - expect(yaml.allowBuilds.geckodriver).toBe(false); + expect(yaml).toHaveProperty(['allowBuilds', 'edgedriver'], true); + expect(yaml).toHaveProperty(['allowBuilds', 'geckodriver'], false); }); it('leaves an anchored (&/*) driver denial untouched without crashing (pnpm-workspace.yaml v10, no webdriverio)', () => { @@ -8269,12 +7940,10 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - allowBuilds: Record; - }; + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); // both the anchor-owner and the alias resolve to the preserved `false`. - expect(yaml.allowBuilds.edgedriver).toBe(false); - expect(yaml.allowBuilds.geckodriver).toBe(false); + expect(yaml).toHaveProperty(['allowBuilds', 'edgedriver'], false); + expect(yaml).toHaveProperty(['allowBuilds', 'geckodriver'], false); }); it('preserves a user-approved (true) direct-driver dep on a re-migration (package.json pnpm sink, v10)', () => { @@ -8290,13 +7959,11 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { workspaceInfo.downloadPackageManager.version = '10.6.1'; rewriteStandaloneProject(tmpDir, workspaceInfo, true, true); - const pnpm = (readJson(path.join(tmpDir, 'package.json')).pnpm ?? {}) as { - allowBuilds?: Record; - }; + const pnpm = fixtureObject(readJson(path.join(tmpDir, 'package.json')).pnpm ?? {}); // No webdriverio -> vite-plus leaves the whole allowBuilds map untouched: the // user-approved geckodriver `true` and the user's edgedriver `false` both survive. - expect(pnpm.allowBuilds?.geckodriver).toBe(true); - expect(pnpm.allowBuilds?.edgedriver).toBe(false); + expect(pnpm).toHaveProperty(['allowBuilds', 'geckodriver'], true); + expect(pnpm).toHaveProperty(['allowBuilds', 'edgedriver'], false); }); it('flips a stale package.json pnpm.allowBuilds denial to true when webdriverio is added (pnpm v10)', () => { @@ -8314,11 +7981,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { workspaceInfo.downloadPackageManager.version = '10.6.1'; rewriteStandaloneProject(tmpDir, workspaceInfo, true, true); - const pnpm = (readJson(path.join(tmpDir, 'package.json')).pnpm ?? {}) as { - allowBuilds?: Record; - }; - expect(pnpm.allowBuilds?.edgedriver).toBe(true); - expect(pnpm.allowBuilds?.geckodriver).toBe(true); + const pnpm = fixtureObject(readJson(path.join(tmpDir, 'package.json')).pnpm ?? {}); + expect(pnpm).toHaveProperty(['allowBuilds', 'edgedriver'], true); + expect(pnpm).toHaveProperty(['allowBuilds', 'geckodriver'], true); }); it('does not write a pnpm.allowBuilds default-deny in package.json when webdriverio is unused (pnpm v10)', () => { @@ -8336,9 +8001,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { // No webdriverio -> nothing to manage -> no allowBuilds key added to the pnpm sink // (the webdriverio-present case still writes `true` here — see the flip test below). - const pnpm = (readJson(path.join(tmpDir, 'package.json')).pnpm ?? {}) as { - allowBuilds?: Record; - }; + const pnpm = fixtureObject(readJson(path.join(tmpDir, 'package.json')).pnpm ?? {}); expect(pnpm.allowBuilds).toBeUndefined(); }); @@ -8355,10 +8018,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { workspaceInfo.downloadPackageManager.version = '9.15.0'; rewriteStandaloneProject(tmpDir, workspaceInfo, true, true); - const pnpm = (readJson(path.join(tmpDir, 'package.json')).pnpm ?? {}) as { - onlyBuiltDependencies: string[]; - allowBuilds?: Record; - }; + const pnpm = fixtureObject(readJson(path.join(tmpDir, 'package.json')).pnpm ?? {}); expect(pnpm.onlyBuiltDependencies).toEqual( expect.arrayContaining(['edgedriver', 'geckodriver']), ); @@ -8376,10 +8036,7 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { workspaceInfo.downloadPackageManager.version = '9.15.0'; rewriteStandaloneProject(tmpDir, workspaceInfo, true, true); - const pnpm = (readJson(path.join(tmpDir, 'package.json')).pnpm ?? {}) as { - onlyBuiltDependencies?: string[]; - allowBuilds?: Record; - }; + const pnpm = fixtureObject(readJson(path.join(tmpDir, 'package.json')).pnpm ?? {}); expect(pnpm.onlyBuiltDependencies).toBeUndefined(); expect(pnpm.allowBuilds).toBeUndefined(); }); @@ -8405,11 +8062,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { workspaceInfo.packages = [{ name: '@vibe/e2e', path: 'apps/e2e' }]; rewriteMonorepo(workspaceInfo, true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - allowBuilds: Record; - }; - expect(yaml.allowBuilds.edgedriver).toBe(true); - expect(yaml.allowBuilds.geckodriver).toBe(true); + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(yaml).toHaveProperty(['allowBuilds', 'edgedriver'], true); + expect(yaml).toHaveProperty(['allowBuilds', 'geckodriver'], true); }); it('does not deny a driver the user depends on directly when webdriverio is unused (pnpm v10)', () => { @@ -8450,11 +8105,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ); rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - allowBuilds: Record; - }; - expect(yaml.allowBuilds.edgedriver).toBe(true); - expect(yaml.allowBuilds.geckodriver).toBe(true); + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(yaml).toHaveProperty(['allowBuilds', 'edgedriver'], true); + expect(yaml).toHaveProperty(['allowBuilds', 'geckodriver'], true); }); it('does not deny a driver the user depends on directly when webdriverio is unused (package.json pnpm config)', () => { @@ -8571,11 +8224,9 @@ describe('rewriteStandaloneProject pnpm workspace yaml', () => { ]; rewriteMonorepo(workspaceInfo, true); - const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')) as { - allowBuilds: Record; - }; - expect(yaml.allowBuilds.edgedriver).toBe(true); - expect(yaml.allowBuilds.geckodriver).toBe(true); + const yaml = readYamlObject(path.join(tmpDir, 'pnpm-workspace.yaml')); + expect(yaml).toHaveProperty(['allowBuilds', 'edgedriver'], true); + expect(yaml).toHaveProperty(['allowBuilds', 'geckodriver'], true); }); }); @@ -8617,25 +8268,22 @@ describe('rewriteMonorepo yarn catalog', () => { rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.yarn), true); - const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')) as { - nodeLinker: string; - catalogs: Record>; - }; + const yarnrc = readYamlObject(path.join(tmpDir, '.yarnrc.yml')); expect(yarnrc.nodeLinker).toBe('node-modules'); - expect(yarnrc.catalogs.vite7.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(yarnrc.catalogs.vite7.react).toBe('^18.0.0'); + expect(yarnrc).toHaveProperty( + ['catalogs', 'vite7', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); + expect(yarnrc).toHaveProperty(['catalogs', 'vite7', 'react'], '^18.0.0'); // Common case (no @vitest/* dep, no vitest source): `vitest` is not managed, // so the pre-existing named-catalog `vitest` entry is REMOVED. - expect(yarnrc.catalogs.test.vitest).toBeUndefined(); - expect(yarnrc.catalogs.test.oxlint).toBeUndefined(); + expect(fixtureObject(yarnrc, 'catalogs', 'test').vitest).toBeUndefined(); + expect(fixtureObject(yarnrc, 'catalogs', 'test').oxlint).toBeUndefined(); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - peerDependencies: Record; - }; - expect(pkg.devDependencies.vite).toBe('catalog:vite7'); - expect(pkg.peerDependencies.vite).toBe('^7.0.0'); - expect(pkg.peerDependencies.vitest).toBe('^4.0.0'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], 'catalog:vite7'); + expect(pkg).toHaveProperty(['peerDependencies', 'vite'], '^7.0.0'); + expect(pkg).toHaveProperty(['peerDependencies', 'vitest'], '^4.0.0'); }); }); @@ -8662,13 +8310,11 @@ describe('rewriteStandaloneProject bun direct vite (#8406)', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.bun), true, true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); // A standalone bun project never manages a catalog (rewriteBunCatalog runs // only on monorepo roots), so the direct `vite` edge bun needs for #8406 must // be the concrete core alias rather than a dangling `catalog:` reference. - expect(pkg.devDependencies.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], VITE_PLUS_OVERRIDE_PACKAGES.vite); }); }); @@ -8697,11 +8343,11 @@ describe('rewriteMonorepo bun catalog', () => { const pkg = readJson(path.join(tmpDir, 'package.json')); // catalog should be at top level - const catalog = pkg.catalog as Record; + const catalog = fixtureObject(pkg.catalog); expect(catalog.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); expect(catalog['vite-plus']).toBe('latest'); // overrides should reference catalog: - const overrides = pkg.overrides as Record; + const overrides = fixtureObject(pkg.overrides); expect(overrides.vite).toBe('catalog:'); }); @@ -8739,11 +8385,10 @@ describe('rewriteMonorepo bun catalog', () => { rewriteMonorepo(workspaceInfo, true); const vitePlusSpec = (name: string) => - ( - readJson(path.join(tmpDir, 'packages', name, 'package.json')) as { - devDependencies: Record; - } - ).devDependencies['vite-plus']; + fixtureObject( + readJson(path.join(tmpDir, 'packages', name, 'package.json')), + 'devDependencies', + )['vite-plus']; expect(vitePlusSpec('app')).toBe('latest'); // A protocol pin is a deliberate user choice and survives. expect(vitePlusSpec('linked')).toBe('workspace:*'); @@ -8762,15 +8407,11 @@ describe('rewriteMonorepo bun catalog', () => { ); rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.bun, '1.2.20'), true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - overrides: Record; - catalog?: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); expect(pkg.catalog).toBeUndefined(); - expect(pkg.devDependencies.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); - expect(pkg.devDependencies['vite-plus']).toBe('latest'); - expect(pkg.overrides.vite).toBe(VITE_PLUS_OVERRIDE_PACKAGES.vite); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], VITE_PLUS_OVERRIDE_PACKAGES.vite); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'latest'); + expect(pkg).toHaveProperty(['overrides', 'vite'], VITE_PLUS_OVERRIDE_PACKAGES.vite); }); it('writes catalog to workspaces.catalog when workspaces is an object with existing catalog', () => { @@ -8792,10 +8433,13 @@ describe('rewriteMonorepo bun catalog', () => { // No top-level catalog expect(pkg.catalog).toBeUndefined(); // workspaces.catalog should have merged entries - const workspaces = pkg.workspaces as { packages: string[]; catalog: Record }; - expect(workspaces.catalog.react).toBe('^19.0.0'); - expect(workspaces.catalog.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(workspaces.catalog['vite-plus']).toBe('latest'); + const workspaces = fixtureObject(pkg.workspaces); + expect(workspaces).toHaveProperty(['catalog', 'react'], '^19.0.0'); + expect(workspaces).toHaveProperty( + ['catalog', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); + expect(workspaces).toHaveProperty(['catalog', 'vite-plus'], 'latest'); // workspaces.packages should be preserved expect(workspaces.packages).toEqual(['packages/*']); }); @@ -8822,19 +8466,19 @@ describe('rewriteMonorepo bun catalog', () => { rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.bun), true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - catalog: Record; - workspaces: { catalog: Record }; - }; - expect(pkg.workspaces.catalog.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(pkg.workspaces.catalog['vite-plus']).toBe('latest'); - expect(pkg.catalog.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty( + ['workspaces', 'catalog', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); + expect(pkg).toHaveProperty(['workspaces', 'catalog', 'vite-plus'], 'latest'); + expect(pkg).toHaveProperty(['catalog', 'vite'], 'npm:@voidzero-dev/vite-plus-core@latest'); // Common case (no @vitest/* dep, no vitest source): `vitest` is not managed, // so the pre-existing catalog `vitest` entry is REMOVED. - expect(pkg.catalog.vitest).toBeUndefined(); - expect(pkg.catalog.tsdown).toBeUndefined(); - expect(pkg.catalog.react).toBe('^19.0.0'); - expect(pkg.catalog['vite-plus']).toBeUndefined(); + expect(fixtureObject(pkg, 'catalog').vitest).toBeUndefined(); + expect(fixtureObject(pkg, 'catalog').tsdown).toBeUndefined(); + expect(pkg).toHaveProperty(['catalog', 'react'], '^19.0.0'); + expect(fixtureObject(pkg, 'catalog')['vite-plus']).toBeUndefined(); }); it('writes catalog to top-level when workspaces is an object without catalog', () => { @@ -8853,11 +8497,11 @@ describe('rewriteMonorepo bun catalog', () => { const pkg = readJson(path.join(tmpDir, 'package.json')); // catalog should be at top level since workspaces.catalog didn't exist - const catalog = pkg.catalog as Record; + const catalog = fixtureObject(pkg.catalog); expect(catalog.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); expect(catalog['vite-plus']).toBe('latest'); // workspaces object should be preserved - const workspaces = pkg.workspaces as { packages: string[] }; + const workspaces = fixtureObject(pkg.workspaces); expect(workspaces.packages).toEqual(['packages/*']); }); @@ -8880,30 +8524,27 @@ describe('rewriteMonorepo bun catalog', () => { rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.bun), true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - catalog: Record; - catalogs: Record>; - overrides: Record; - devDependencies: Record; - peerDependencies: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); // Like pnpm, the managed `build` catalog takes the Vite+ entries, so no // default catalog is created beside it. expect(pkg.catalog).toBeUndefined(); - expect(pkg.catalogs.build.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(pkg.catalogs.build['vite-plus']).toBe('latest'); - expect(pkg.catalogs.build.react).toBe('^19.0.0'); - expect(pkg.catalogs.build.tsdown).toBeUndefined(); + expect(pkg).toHaveProperty( + ['catalogs', 'build', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); + expect(pkg).toHaveProperty(['catalogs', 'build', 'vite-plus'], 'latest'); + expect(pkg).toHaveProperty(['catalogs', 'build', 'react'], '^19.0.0'); + expect(fixtureObject(pkg, 'catalogs', 'build').tsdown).toBeUndefined(); // Common case (no @vitest/* dep, no vitest source): `vitest` is not managed, // so the pre-existing named-catalog `vitest` entry is REMOVED and no // `overrides.vitest` is injected. - expect(pkg.catalogs.test.vitest).toBeUndefined(); - expect(pkg.overrides.vite).toBe('catalog:build'); - expect(pkg.overrides.vitest).toBeUndefined(); - expect(pkg.devDependencies.vite).toBe('catalog:build'); - expect(pkg.devDependencies['vite-plus']).toBe('catalog:build'); - expect(pkg.peerDependencies.vite).toBe('^7.0.0'); - expect(pkg.peerDependencies.vitest).toBe('^4.0.0'); + expect(fixtureObject(pkg, 'catalogs', 'test').vitest).toBeUndefined(); + expect(pkg).toHaveProperty(['overrides', 'vite'], 'catalog:build'); + expect(fixtureObject(pkg, 'overrides').vitest).toBeUndefined(); + expect(pkg).toHaveProperty(['devDependencies', 'vite'], 'catalog:build'); + expect(pkg).toHaveProperty(['devDependencies', 'vite-plus'], 'catalog:build'); + expect(pkg).toHaveProperty(['peerDependencies', 'vite'], '^7.0.0'); + expect(pkg).toHaveProperty(['peerDependencies', 'vitest'], '^4.0.0'); }); it('rewrites workspaces named catalogs and adds Vite+ entries to the managed one', () => { @@ -8925,24 +8566,23 @@ describe('rewriteMonorepo bun catalog', () => { rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.bun), true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - catalog?: Record; - workspaces: { - catalog: Record; - catalogs: Record>; - }; - overrides: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); expect(pkg.catalog).toBeUndefined(); - expect(pkg.workspaces.catalog).toBeUndefined(); - expect(pkg.workspaces.catalogs.build.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(pkg.workspaces.catalogs.build['vite-plus']).toBe('latest'); - expect(pkg.workspaces.catalogs.build.oxlint).toBeUndefined(); + expect(fixtureObject(pkg, 'workspaces').catalog).toBeUndefined(); + expect(pkg).toHaveProperty( + ['workspaces', 'catalogs', 'build', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); + expect(pkg).toHaveProperty(['workspaces', 'catalogs', 'build', 'vite-plus'], 'latest'); + expect(fixtureObject(pkg, 'workspaces', 'catalogs', 'build').oxlint).toBeUndefined(); // Common case (no @vitest/* dep, no vitest source): `vitest` is not managed, // so the pre-existing named-catalog `vitest` entry is REMOVED. - expect(pkg.workspaces.catalogs.test.vitest).toBeUndefined(); - expect(pkg.workspaces.catalogs.test.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(pkg.overrides.vite).toBe('catalog:build'); + expect(fixtureObject(pkg, 'workspaces', 'catalogs', 'test').vitest).toBeUndefined(); + expect(pkg).toHaveProperty( + ['workspaces', 'catalogs', 'test', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); + expect(pkg).toHaveProperty(['overrides', 'vite'], 'catalog:build'); }); it('keeps an existing top-level default catalog when workspaces named catalogs exist', () => { @@ -8964,17 +8604,14 @@ describe('rewriteMonorepo bun catalog', () => { rewriteMonorepo(makeWorkspaceInfo(tmpDir, PackageManager.bun), true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - catalog: Record; - workspaces: { - catalog?: Record; - catalogs: Record>; - }; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); expect(pkg.catalog).toEqual({ react: '^19.0.0' }); - expect(pkg.workspaces.catalog).toBeUndefined(); - expect(pkg.workspaces.catalogs.build.vite).toBe('npm:@voidzero-dev/vite-plus-core@latest'); - expect(pkg.workspaces.catalogs.build['vite-plus']).toBe('latest'); + expect(fixtureObject(pkg, 'workspaces').catalog).toBeUndefined(); + expect(pkg).toHaveProperty( + ['workspaces', 'catalogs', 'build', 'vite'], + 'npm:@voidzero-dev/vite-plus-core@latest', + ); + expect(pkg).toHaveProperty(['workspaces', 'catalogs', 'build', 'vite-plus'], 'latest'); }); }); @@ -9062,14 +8699,14 @@ describe('framework shim', () => { it('creates src/env.d.ts with vue shim when src/ exists and no env.d.ts', () => { fs.mkdirSync(path.join(tmpDir, 'src')); addFrameworkShim(tmpDir, 'vue'); - const content = fs.readFileSync(path.join(tmpDir, 'src', 'env.d.ts'), 'utf-8'); + const content = fs.readFileSync(path.join(tmpDir, 'src', 'env.d.ts'), 'utf8'); expect(content).toContain("declare module '*.vue'"); expect(content).toContain('DefineComponent'); }); it('creates root env.d.ts with vue shim when no src/ dir', () => { addFrameworkShim(tmpDir, 'vue'); - const content = fs.readFileSync(path.join(tmpDir, 'env.d.ts'), 'utf-8'); + const content = fs.readFileSync(path.join(tmpDir, 'env.d.ts'), 'utf8'); expect(content).toContain("declare module '*.vue'"); }); @@ -9079,7 +8716,7 @@ describe('framework shim', () => { const existing = '/// \n'; fs.writeFileSync(path.join(srcDir, 'env.d.ts'), existing); addFrameworkShim(tmpDir, 'vue'); - const content = fs.readFileSync(path.join(srcDir, 'env.d.ts'), 'utf-8'); + const content = fs.readFileSync(path.join(srcDir, 'env.d.ts'), 'utf8'); expect(content).toContain('/// '); expect(content).toContain("declare module '*.vue'"); }); @@ -9093,7 +8730,7 @@ describe('framework shim', () => { it('creates root env.d.ts with astro reference when no src/ dir', () => { addFrameworkShim(tmpDir, 'astro'); - const content = fs.readFileSync(path.join(tmpDir, 'env.d.ts'), 'utf-8'); + const content = fs.readFileSync(path.join(tmpDir, 'env.d.ts'), 'utf8'); expect(content).toContain('/// '); }); @@ -9102,7 +8739,7 @@ describe('framework shim', () => { addFrameworkShim(tmpDir, 'vue'); expect(hasFrameworkShim(tmpDir, 'astro')).toBe(false); addFrameworkShim(tmpDir, 'astro'); - const content = fs.readFileSync(path.join(tmpDir, 'src', 'env.d.ts'), 'utf-8'); + const content = fs.readFileSync(path.join(tmpDir, 'src', 'env.d.ts'), 'utf8'); expect(content).toContain("declare module '*.vue'"); expect(content).toContain('/// '); }); @@ -9129,7 +8766,7 @@ describe('framework shim', () => { it('injects `create.defaultTemplate` when scope is set and no `create:` exists', () => { writeViteConfig('{ run: { cache: true } }'); injectCreateDefaultTemplate(tmpDir, '@your-org', true); - const content = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf-8'); + const content = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf8'); expect(content).toContain('create:'); expect(content).toContain('"defaultTemplate":"@your-org"'); }); @@ -9137,7 +8774,7 @@ describe('framework shim', () => { it('skips injection when scope is empty (no scope to default to)', () => { writeViteConfig('{ run: { cache: true } }'); injectCreateDefaultTemplate(tmpDir, '', true); - const content = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf-8'); + const content = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf8'); expect(content).not.toContain('create:'); expect(content).not.toContain('defaultTemplate'); }); @@ -9145,7 +8782,7 @@ describe('framework shim', () => { it('preserves an existing `create:` block instead of overwriting it', () => { writeViteConfig("{ create: { defaultTemplate: '@other' }, run: { cache: true } }"); injectCreateDefaultTemplate(tmpDir, '@your-org', true); - const content = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf-8'); + const content = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf8'); expect(content).toContain("'@other'"); expect(content).not.toContain('@your-org'); }); @@ -9188,22 +8825,22 @@ export default defineConfig(({ mode }) => { it('does not inject a duplicate `fmt` key when one exists as a shorthand property', () => { writeShorthandViteConfig(); - const before = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf-8'); + const before = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf8'); injectFmtDefaults(tmpDir, true); - const after = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf-8'); + const after = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf8'); expect(after).toBe(before); expect(after).not.toContain('fmt: {'); }); it('does not inject a duplicate `lint` key when one exists as a shorthand property', () => { writeShorthandViteConfig(); - const before = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf-8'); + const before = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf8'); injectLintTypeCheckDefaults(tmpDir, true); - const after = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf-8'); + const after = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf8'); expect(after).toBe(before); expect(after).not.toContain('jsPlugins'); expect(after).not.toContain('prefer-vite-plus-imports'); @@ -9249,7 +8886,7 @@ export default defineConfig({ const viteConfig = fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf8'); expect(viteConfig).toContain("import { defineConfig, lazyPlugins } from 'vite-plus'"); expect(viteConfig).toContain( - 'plugins: lazyPlugins(() => [react(), nitro({ rollupConfig: { external: [/^@sentry\\//] } })])', + String.raw`plugins: lazyPlugins(() => [react(), nitro({ rollupConfig: { external: [/^@sentry\//] } })])`, ); expect(viteConfig).not.toContain('plugins: [react(), nitro('); expect(report.wrappedPluginConfigCount).toBe(1); @@ -9474,10 +9111,8 @@ describe('rewriteStandaloneProject — tsconfig types rewriting', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); const tsconfig = readJson(path.join(tmpDir, 'tsconfig.json')); - expect((tsconfig.compilerOptions as { types: string[] }).types).toContain( - 'vite-plus/pack/client', - ); - expect((tsconfig.compilerOptions as { types: string[] }).types).not.toContain('tsdown/client'); + expect(fixtureObject(tsconfig.compilerOptions).types).toContain('vite-plus/pack/client'); + expect(fixtureObject(tsconfig.compilerOptions).types).not.toContain('tsdown/client'); }); it('preserves vite/client in tsconfig.json (issue #2004: tsconfig is not a vite.config)', () => { @@ -9489,7 +9124,7 @@ describe('rewriteStandaloneProject — tsconfig types rewriting', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); const tsconfig = readJson(path.join(tmpDir, 'tsconfig.json')); - expect((tsconfig.compilerOptions as { types: string[] }).types).toEqual(['vite/client']); + expect(fixtureObject(tsconfig.compilerOptions).types).toEqual(['vite/client']); }); it('rewrites types in tsconfig.node.json as well', () => { @@ -9501,14 +9136,12 @@ describe('rewriteStandaloneProject — tsconfig types rewriting', () => { rewriteStandaloneProject(tmpDir, makeWorkspaceInfo(tmpDir, PackageManager.pnpm), true, true); const tsconfig = readJson(path.join(tmpDir, 'tsconfig.node.json')); - expect((tsconfig.compilerOptions as { types: string[] }).types).toContain( - 'vite-plus/pack/client', - ); + expect(fixtureObject(tsconfig.compilerOptions).types).toContain('vite-plus/pack/client'); }); }); -function ruleIds(yaml: string): unknown[] { - return parseAllDocuments(yaml).map((document) => (document.toJS() as { id?: unknown })?.id); +function ruleIds(yaml: string): Array { + return parseAllDocuments(yaml).map((document) => fixtureObject(document.toJS()).id); } describe('script rules YAML', () => { @@ -9530,7 +9163,7 @@ describe('script rules YAML', () => { const rewritten = rewriteScripts(JSON.stringify(scripts), getScriptRulesYaml(true)); - expect(JSON.parse(rewritten!) as Record).toEqual({ + expect(fixtureObject(JSON.parse(rewritten!))).toEqual({ test: 'vp test', staged: 'lint-staged', }); @@ -9594,11 +9227,7 @@ describe('existing Vite+ core migration finalization', () => { taskCacheWarnings: [], }); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - scripts: Record; - devDependencies: Record; - overrides?: Record; - }; + const pkg = readJson(path.join(tmpDir, 'package.json')); expect(pkg.scripts).toMatchObject({ dev: 'vp dev', build: 'tsc -b && vp build', @@ -9613,9 +9242,7 @@ describe('existing Vite+ core migration finalization', () => { "from 'vite-plus'", ); const tsconfig = readJson(path.join(tmpDir, 'tsconfig.app.json')); - expect((tsconfig.compilerOptions as { types: string[] }).types).toEqual([ - 'vite-plus/pack/client', - ]); + expect(fixtureObject(tsconfig.compilerOptions).types).toEqual(['vite-plus/pack/client']); expect(detectPendingCoreMigration(workspaceInfo)).toEqual({ scripts: false, tsconfigTypes: false, @@ -9641,10 +9268,8 @@ describe('existing Vite+ core migration finalization', () => { expect(detectPendingCoreMigration(workspaceInfo).scripts).toBe(true); expect(finalizeCoreMigrationForExistingVitePlus(workspaceInfo, true).scripts).toBe(true); - const appPkg = readJson(path.join(appDir, 'package.json')) as { - scripts: Record; - }; - expect(appPkg.scripts.dev).toBe('vp dev'); + const appPkg = readJson(path.join(appDir, 'package.json')); + expect(appPkg).toHaveProperty(['scripts', 'dev'], 'vp dev'); }); it('makes a leftover tsdown config discoverable in an existing Vite+ project', () => { @@ -10183,13 +9808,9 @@ describe('Git hook setup policy', () => { 'npm test\n', ); expect(fs.existsSync(path.join(tmpDir, 'vite.config.ts'))).toBe(false); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - scripts: Record; - devDependencies: Record; - 'lint-staged': Record; - }; - expect(pkg.scripts.prepare).toBe('vp config'); - expect(pkg.devDependencies['lint-staged']).toBe('^16.2.7'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['scripts', 'prepare'], 'vp config'); + expect(pkg).toHaveProperty(['devDependencies', 'lint-staged'], '^16.2.7'); expect(pkg['lint-staged']).toEqual({ '*.ts': 'eslint --fix' }); }); @@ -10220,11 +9841,8 @@ describe('Git hook setup policy', () => { expect(fs.readFileSync(path.join(tmpDir, 'vite.config.ts'), 'utf8')).toContain( '"*.ts": "eslint --fix"', ); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - 'lint-staged'?: Record; - }; - expect(pkg.devDependencies['lint-staged']).toBeUndefined(); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(fixtureObject(pkg, 'devDependencies')['lint-staged']).toBeUndefined(); expect(pkg['lint-staged']).toBeUndefined(); }); @@ -10244,11 +9862,8 @@ describe('Git hook setup policy', () => { expect(installGitHooks(tmpDir, true)).toBe(false); expect(fs.statSync(hookPath).isDirectory()).toBe(true); expect(fs.existsSync(path.join(tmpDir, 'vite.config.ts'))).toBe(false); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - 'lint-staged': Record; - }; - expect(pkg.devDependencies['lint-staged']).toBe('^16.2.7'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'lint-staged'], '^16.2.7'); expect(pkg['lint-staged']).toEqual({ '*.ts': 'eslint --fix' }); }); @@ -10273,11 +9888,8 @@ describe('Git hook setup policy', () => { rewriteStandaloneProject(tmpDir, workspaceInfo, skipStagedMigration, true); expect(skipStagedMigration).toBe(true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - 'lint-staged': Record; - }; - expect(pkg.devDependencies['lint-staged']).toBe('^16.2.7'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'lint-staged'], '^16.2.7'); expect(pkg['lint-staged']).toEqual({ '*.ts': 'eslint --fix' }); expect(fs.readFileSync(path.join(tmpDir, '.husky', 'pre-commit'), 'utf8')).toBe( 'npx lint-staged\n', @@ -10354,11 +9966,8 @@ describe('Git hook setup policy', () => { rewriteMonorepo(workspaceInfo, skipStagedMigration, true); expect(skipStagedMigration).toBe(true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - 'lint-staged': Record; - }; - expect(pkg.devDependencies['lint-staged']).toBe('^16.2.7'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'lint-staged'], '^16.2.7'); expect(pkg['lint-staged']).toEqual({ '*.ts': 'eslint --fix' }); expect(fs.readFileSync(path.join(tmpDir, '.vite-hooks', 'pre-commit'), 'utf8')).toBe( 'npx lint-staged\n', @@ -10404,12 +10013,9 @@ describe('Git hook setup policy', () => { rewriteMonorepo(workspaceInfo, skipStagedMigration, true); expect(skipStagedMigration).toBe(true); - const pkg = readJson(path.join(appDir, 'package.json')) as { - devDependencies: Record; - 'lint-staged': Record; - }; - expect(pkg.devDependencies.husky).toBe('^9.1.7'); - expect(pkg.devDependencies['lint-staged']).toBe('^16.2.7'); + const pkg = readJson(path.join(appDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'husky'], '^9.1.7'); + expect(pkg).toHaveProperty(['devDependencies', 'lint-staged'], '^16.2.7'); expect(pkg['lint-staged']).toEqual({ '*.ts': 'eslint --fix' }); expect(fs.readFileSync(path.join(appDir, '.husky', 'pre-commit'), 'utf8')).toBe( 'npx lint-staged\n', @@ -10461,11 +10067,8 @@ describe('Git hook setup policy', () => { rewriteMonorepoProject(tmpDir, PackageManager.pnpm, skipStagedMigration, true); expect(skipStagedMigration).toBe(true); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - devDependencies: Record; - 'lint-staged': Record; - }; - expect(pkg.devDependencies['lint-staged']).toBe('^16.2.7'); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(pkg).toHaveProperty(['devDependencies', 'lint-staged'], '^16.2.7'); expect(pkg['lint-staged']).toEqual({ '*.ts': 'eslint --fix' }); expect(fs.existsSync(path.join(tmpDir, 'vite.config.ts'))).toBe(false); }); diff --git a/packages/cli/src/migration/__tests__/npm-reinstall.spec.ts b/packages/cli/src/migration/__tests__/npm-reinstall.spec.ts index 881bb9fe89..cca765e390 100644 --- a/packages/cli/src/migration/__tests__/npm-reinstall.spec.ts +++ b/packages/cli/src/migration/__tests__/npm-reinstall.spec.ts @@ -4,9 +4,11 @@ import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; +import { readJsonFile } from '../../utils/json.ts'; import { prepareNpmViteAliasReinstall } from '../npm-reinstall.ts'; +import { fixtureObject } from './fixture-json.ts'; -const tempDirs: string[] = []; +const tempDirs: Array = []; function createTempDir(): string { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vite-plus-npm-reinstall-')); @@ -61,12 +63,11 @@ describe('prepareNpmViteAliasReinstall', () => { .changed, ).toBe(true); - const lock = JSON.parse(fs.readFileSync(path.join(rootDir, 'package-lock.json'), 'utf8')) as { - packages: Record; - }; - expect(lock.packages['node_modules/vite']).toBeUndefined(); - expect(lock.packages['node_modules/consumer/node_modules/vite']).toBeUndefined(); - expect(lock.packages['packages/app/node_modules/vite']).toBeDefined(); + const lock = readJsonFile(path.join(rootDir, 'package-lock.json')); + const packages = fixtureObject(lock, 'packages'); + expect(packages['node_modules/vite']).toBeUndefined(); + expect(packages['node_modules/consumer/node_modules/vite']).toBeUndefined(); + expect(packages['packages/app/node_modules/vite']).toBeDefined(); expect(fs.existsSync(staleRootVite)).toBe(false); expect(fs.existsSync(staleNestedVite)).toBe(false); expect(fs.existsSync(coreVite)).toBe(true); diff --git a/packages/cli/src/migration/__tests__/oxlint-extends.spec.ts b/packages/cli/src/migration/__tests__/oxlint-extends.spec.ts index 18a36adfee..c4c516ecdc 100644 --- a/packages/cli/src/migration/__tests__/oxlint-extends.spec.ts +++ b/packages/cli/src/migration/__tests__/oxlint-extends.spec.ts @@ -7,6 +7,7 @@ import { loadConfigFromFile } from 'vite'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { PackageManager } from '../../types/index.ts'; +import type { JsonObject } from '../../utils/json.ts'; import { injectLintTypeCheckDefaults, mergeViteConfigFiles, @@ -20,7 +21,7 @@ import { createMigrationReport } from '../report.ts'; describe('Oxlint JSON extends migration', () => { let project: string; - function write(filename: string, content: string | object) { + function write(filename: string, content: string | JsonObject) { const filenamePath = path.join(project, filename); fs.mkdirSync(path.dirname(filenamePath), { recursive: true }); fs.writeFileSync(filenamePath, typeof content === 'string' ? content : JSON.stringify(content)); @@ -192,11 +193,10 @@ describe('Oxlint JSON extends migration', () => { expect(migrated.rules).not.toHaveProperty('vp-missing/custom'); expect(migrated.rules).toHaveProperty('base/custom', 'warn'); expect(migrated.extends![0].rules).toHaveProperty('base/custom', 'error'); - if (shared) { - expect((await loadConfig(path.join(project, 'packages/a'))).lint!.extends![0]).toEqual( - migrated, - ); - } + const child = shared + ? (await loadConfig(path.join(project, 'packages/a'))).lint?.extends?.[0] + : undefined; + expect(child).toEqual(shared ? migrated : undefined); }, ); @@ -421,7 +421,7 @@ describe('Oxlint JSON extends migration', () => { createWorkspace(); const root = write('.oxlintrc.json', { rules: { 'no-console': 'off' } }); const shared = write('shared/lint.json', { - ...(extendsRoot ? { extends: [root] } : {}), + ...(extendsRoot ? { extends: [root] } : undefined), rules: { 'no-console': 'error' }, options: { typeAware: false, typeCheck: false }, }); @@ -442,18 +442,14 @@ describe('Oxlint JSON extends migration', () => { expect(lint!.rules!['no-console']).toBe('error'); expect(lint!.options).toEqual({ typeAware: false, typeCheck: false }); expect(fs.existsSync(path.join(directory, '.oxlintrc.json'))).toBe(false); - if (extendsRoot) { - expect(lint!.extends![0].rules!['no-console']).toBe('off'); - } + expect(lint?.extends?.[0]?.rules?.['no-console']).toBe(extendsRoot ? 'off' : undefined); } expect(fs.readFileSync(shared, 'utf8')).toBe(original); // Removing the links leaves their target on disk, so its dependencies must remain too. expect(fs.existsSync(root)).toBe(extendsRoot); - if (extendsRoot) { - expect(resolveOxlintConfigExtends(shared).config.extends![0].rules!['no-console']).toBe( - 'off', - ); - } + expect(resolveOxlintConfigExtends(shared).config.extends?.[0]?.rules?.['no-console']).toBe( + extendsRoot ? 'off' : undefined, + ); }, ); @@ -656,13 +652,13 @@ describe('Oxlint JSON extends migration', () => { it.skipIf(process.platform === 'win32')( 'preserves literal backslashes in plugin filenames', async () => { - write('base.json', { jsPlugins: ['./plugin\\name.mjs'] }); + write('base.json', { jsPlugins: [String.raw`./plugin\name.mjs`] }); write('.oxlintrc.json', { extends: ['./base.json'] }); mergeViteConfigFiles(project, true); expect((await loadConfig()).lint!.extends![0].jsPlugins).toEqual([ - path.join(project, 'plugin\\name.mjs'), + path.join(project, String.raw`plugin\name.mjs`), ]); }, ); @@ -829,10 +825,14 @@ describe('Oxlint JSON extends migration', () => { const firstReport = createMigrationReport(); mergeViteConfigFiles(project, true, firstReport); expect(firstReport.warnings).toHaveLength(1); + const pendingReport = createMigrationReport(); + const pending = + failure === 'missing source' + ? retryPreservedOxlintConfigs(project, true, pendingReport) + : undefined; + expect(pending).toBe(failure === 'missing source' ? false : undefined); + expect(pendingReport.warnings).toHaveLength(failure === 'missing source' ? 1 : 0); if (failure === 'missing source') { - const pendingReport = createMigrationReport(); - expect(retryPreservedOxlintConfigs(project, true, pendingReport)).toBe(false); - expect(pendingReport.warnings).toHaveLength(1); write('base.json', { rules: { 'no-debugger': 'error' } }); } else { fs.unlinkSync(path.join(project, 'base.ts')); diff --git a/packages/cli/src/migration/__tests__/oxlint-plugin-dependency.spec.ts b/packages/cli/src/migration/__tests__/oxlint-plugin-dependency.spec.ts index 244b8b7550..a25a90d576 100644 --- a/packages/cli/src/migration/__tests__/oxlint-plugin-dependency.spec.ts +++ b/packages/cli/src/migration/__tests__/oxlint-plugin-dependency.spec.ts @@ -4,8 +4,10 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { PackageManager, type WorkspaceInfo } from '../../types/index.ts'; +import type { WorkspaceInfo } from '../../types/index.ts'; +import { PackageManager } from '../../types/index.ts'; import { readJsonFile, writeJsonFile } from '../../utils/json.ts'; +import type { DependencyBag } from '../migrator.ts'; import { collectOxlintOwnerDirs, detectVitePlusBootstrapPending, @@ -19,7 +21,6 @@ import { rewriteStandaloneProject, sourceTreeReferencesOxlintPluginsPackage, usesVitestBrowserMode, - type DependencyBag, } from '../migrator.ts'; describe('Oxlint plugin dependency cleanup', () => { @@ -614,7 +615,7 @@ describe('Oxlint plugin dependency cleanup', () => { }); }); -function packument(versions: string[]): Response { +function packument(versions: Array): Response { return new Response( JSON.stringify({ versions: Object.fromEntries(versions.map((v) => [v, {}])) }), { status: 200, headers: { 'content-type': 'application/json' } }, diff --git a/packages/cli/src/migration/__tests__/oxlint-rule-alias.spec.ts b/packages/cli/src/migration/__tests__/oxlint-rule-alias.spec.ts index aad94febf3..f917e2a8a2 100644 --- a/packages/cli/src/migration/__tests__/oxlint-rule-alias.spec.ts +++ b/packages/cli/src/migration/__tests__/oxlint-rule-alias.spec.ts @@ -1,4 +1,4 @@ -import { type OxlintConfig } from 'oxlint'; +import type { OxlintConfig } from 'oxlint'; import { describe, expect, it } from 'vitest'; import { sanitizeMigratedOxlintConfig } from '../migrator/eslint.ts'; diff --git a/packages/cli/src/migration/__tests__/oxnode.spec.ts b/packages/cli/src/migration/__tests__/oxnode.spec.ts index 6151d94849..c3a18e8c9f 100644 --- a/packages/cli/src/migration/__tests__/oxnode.spec.ts +++ b/packages/cli/src/migration/__tests__/oxnode.spec.ts @@ -2,10 +2,18 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; +import type { log as promptLog } from '@voidzero-dev/vite-plus-prompts'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { JsonObject } from '../../utils/json.ts'; +import { readJsonFile } from '../../utils/json.ts'; + vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ - log: { info: vi.fn(), success: vi.fn(), warn: vi.fn() }, + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + }, })); import { @@ -262,13 +270,13 @@ describe('oxnode inline code', () => { describe('oxnode migration', () => { let root: string; - const write = (file: string, content: string | object) => { + const write = (file: string, content: string | JsonObject) => { const target = path.join(root, file); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, typeof content === 'string' ? content : JSON.stringify(content)); }; const read = (file: string) => fs.readFileSync(path.join(root, file), 'utf8'); - const readJson = (file: string) => JSON.parse(read(file)); + const readJson = (file: string) => readJsonFile(path.join(root, file)); beforeEach(() => { root = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-test-oxnode-')); @@ -368,7 +376,7 @@ describe('oxnode migration', () => { const report = createMigrationReport(); expect(migrateOxnodeToVpx(root, undefined, report).dependencyRemoved).toBe(false); - expect(readJson('package.json').scripts.build).toBe('vpx ./build.ts'); + expect(readJson('package.json')).toHaveProperty(['scripts', 'build'], 'vpx ./build.ts'); expect(readJson('package.json').devDependencies).toEqual({ '@oxc-node/cli': '^1.0.0', '@oxc-node/core': '^1.0.0', @@ -450,7 +458,8 @@ describe('oxnode migration', () => { ); expect(migrateOxnodeToVpx(root)).toEqual({ changed: true, dependencyRemoved: true }); - expect(readJson('package.json').scripts.release).toBe( + expect(readJson('package.json')).toHaveProperty( + ['scripts', 'release'], 'node --import vite-plus/register scripts/release.ts', ); expect(read('scripts/release.ts')).toBe( @@ -571,7 +580,7 @@ describe('oxnode migration', () => { const report = createMigrationReport(); expect(detectOxnodeProject(root)).toBe(true); expect(migrateOxnodeToVpx(root, undefined, report).changed).toBe(false); - expect(readJson('package.json').scripts.start).toBe('oxnode a.ts'); + expect(readJson('package.json')).toHaveProperty(['scripts', 'start'], 'oxnode a.ts'); expect(report.warnings).toContainEqual(expect.stringContaining('listed in dependencies')); }, ); @@ -595,7 +604,8 @@ describe('oxnode migration', () => { }); expect(detectOxnodeProject(root)).toBe(true); expect(migrateOxnodeToVpx(root)).toEqual({ changed: true, dependencyRemoved: true }); - expect(readJson('package.json').scripts.build).toBe( + expect(readJson('package.json')).toHaveProperty( + ['scripts', 'build'], 'node --import vite-plus/register build.ts', ); }); @@ -633,9 +643,18 @@ describe('oxnode migration', () => { { name: 'b', path: 'packages/b' }, ]; expect(migrateOxnodeToVpx(root, packages).dependencyRemoved).toBe(false); - expect(readJson('packages/a/package.json').scripts.build).toBe('vpx build.ts'); - expect(readJson('packages/b/package.json').scripts.build).toBe('oxnode --watch build.ts'); - expect(readJson('package.json').devDependencies['@oxc-node/core']).toBe('^1.0.0'); + expect(readJson('packages/a/package.json')).toHaveProperty( + ['scripts', 'build'], + 'vpx build.ts', + ); + expect(readJson('packages/b/package.json')).toHaveProperty( + ['scripts', 'build'], + 'oxnode --watch build.ts', + ); + expect(readJson('package.json')).toHaveProperty( + ['devDependencies', '@oxc-node/core'], + '^1.0.0', + ); }); it('retains the loader referenced by an env file of a separate Node.js command', () => { @@ -649,7 +668,10 @@ describe('oxnode migration', () => { build: 'vpx build.ts', run: 'node --env-file=.env.local run.ts', }); - expect(readJson('package.json').devDependencies['@oxc-node/core']).toBe('^1.0.0'); + expect(readJson('package.json')).toHaveProperty( + ['devDependencies', '@oxc-node/core'], + '^1.0.0', + ); }); it.each([ diff --git a/packages/cli/src/migration/__tests__/prettier.spec.ts b/packages/cli/src/migration/__tests__/prettier.spec.ts index 078beb2efe..1b958a9497 100644 --- a/packages/cli/src/migration/__tests__/prettier.spec.ts +++ b/packages/cli/src/migration/__tests__/prettier.spec.ts @@ -2,14 +2,19 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; +import type { log as promptLog } from '@voidzero-dev/vite-plus-prompts'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ - log: { info: vi.fn(), success: vi.fn(), warn: vi.fn() }, + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + }, })); vi.mock(import('../../utils/command.ts'), async (importOriginal) => ({ ...(await importOriginal()), - runCommandSilently: vi.fn(), + runCommandSilently: vi.fn(), })); import { runCommandSilently } from '../../utils/command.ts'; diff --git a/packages/cli/src/migration/__tests__/react-refresh-options.spec.ts b/packages/cli/src/migration/__tests__/react-refresh-options.spec.ts index ea64342de3..b4c82ae43e 100644 --- a/packages/cli/src/migration/__tests__/react-refresh-options.spec.ts +++ b/packages/cli/src/migration/__tests__/react-refresh-options.spec.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; -import { type OxlintConfig } from 'oxlint'; +import type { OxlintConfig } from 'oxlint'; import { describe, expect, it } from 'vitest'; import { sanitizeMigratedOxlintConfig } from '../migrator.ts'; @@ -37,7 +37,7 @@ describe('React Refresh option migration', () => { }, }, ], - } as unknown as OxlintConfig; + } satisfies OxlintConfig; const expected = structuredClone(config); const report = createMigrationReport(); diff --git a/packages/cli/src/migration/__tests__/renovate.spec.ts b/packages/cli/src/migration/__tests__/renovate.spec.ts index 6ca388f657..03a09a1112 100644 --- a/packages/cli/src/migration/__tests__/renovate.spec.ts +++ b/packages/cli/src/migration/__tests__/renovate.spec.ts @@ -102,16 +102,18 @@ describe('Renovate configuration', () => { "{extends: ['first'], limit: 1_000}", '{extends: [], limit: 0b10}', '{extends: [], enabled: (true)}', - "{extends: ['\\u{61}']}", + String.raw`{extends: ['\u{61}']}`, "{extends: ['first'], extends: []}", "{extends: ['group:vitePlus']}", "{extends: ['first'", ])('skips unsupported or ineligible JSON5 configs: %s', async (source) => { + expect.hasAssertions(); const file = await config('.gitlab/renovate.json5', source); await expectSkipped(file, source); }); it('accepts JSON5-only syntax only in a .json5 file', async () => { + expect.hasAssertions(); const source = "{extends: ['config:recommended']}"; const file = await config('renovate.jsonc', source); await expectSkipped(file, source); @@ -176,8 +178,8 @@ describe('Renovate configuration', () => { }); it.each([ - ['renovate.jsonc', '"extends"', '"config:recomm\\u0065nded"', '"group:vitePlus"'], - ['renovate.json5', 'extends', "'config:recomm\\x65nded'", "'group:vitePlus'"], + ['renovate.jsonc', '"extends"', String.raw`"config:recomm\u0065nded"`, '"group:vitePlus"'], + ['renovate.json5', 'extends', String.raw`'config:recomm\x65nded'`, "'group:vitePlus'"], ])( 'preserves the shorthand literal and surrounding comments in %s', async (name, key, literal, group) => { @@ -193,14 +195,16 @@ describe('Renovate configuration', () => { it.each([ ['renovate.json', '{"extends":"group:vitePlus"}'], - ['renovate.json5', "{extends:'group:vite\\x50lus'}"], + ['renovate.json5', String.raw`{extends:'group:vite\x50lus'}`], ['package.json', '{"renovate":"group:vitePlus"}'], ['package.json', '{"renovate":{"extends":"group:vitePlus"}}'], ])('skips an already enabled shorthand in %s: %s', async (name, source) => { + expect.hasAssertions(); await expectSkipped(await config(name, source), source); }); it('ignores an empty Renovate shorthand in package.json', async () => { + expect.hasAssertions(); const source = '{"renovate":""}'; await expectSkipped(await config('package.json', source), source); }); @@ -216,6 +220,7 @@ describe('Renovate configuration', () => { ])( 'skips an ineligible active config without touching a lower-priority config: %s', async (source) => { + expect.hasAssertions(); const file = await config('renovate.json', source); await config('.github/renovate.json', '{}'); await expectSkipped(file, source); diff --git a/packages/cli/src/migration/__tests__/setup-plan-git-hooks.spec.ts b/packages/cli/src/migration/__tests__/setup-plan-git-hooks.spec.ts index f3f0340042..52b65c4705 100644 --- a/packages/cli/src/migration/__tests__/setup-plan-git-hooks.spec.ts +++ b/packages/cli/src/migration/__tests__/setup-plan-git-hooks.spec.ts @@ -3,53 +3,64 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { + confirm as promptConfirm, + log as promptLog, + select as promptSelect, +} from '@voidzero-dev/vite-plus-prompts'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { HOOK_STUB_SCRIPT, hookScript } from '../../config/hooks.ts'; import { PackageManager } from '../../types/index.ts'; +import type { JsonObject } from '../../utils/json.ts'; +import { readJsonFile } from '../../utils/json.ts'; import { log } from '../../utils/terminal.ts'; import { installGitHooks, isViteHooksSetupComplete } from '../migrator.ts'; -import { collectMigrationSetupPlan, type MigrationSetupPlan } from '../setup-plan.ts'; +import type { MigrationSetupPlan } from '../setup-plan.ts'; +import { collectMigrationSetupPlan } from '../setup-plan.ts'; vi.mock('@voidzero-dev/vite-plus-prompts', async (importOriginal) => { - const mod = await importOriginal(); + const mod = await importOriginal<{ + select: typeof promptSelect; + confirm: typeof promptConfirm; + log: typeof promptLog; + }>(); return { ...mod, - select: vi.fn(), - confirm: vi.fn(), - log: { ...mod.log, info: vi.fn(), warn: vi.fn() }, + select: vi.fn(), + confirm: vi.fn(), + log: { ...mod.log, info: vi.fn(), warn: vi.fn() }, }; }); -vi.mock('../../utils/terminal.ts', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, log: vi.fn() }; +vi.mock(import('../../utils/terminal.ts'), async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, log: vi.fn() }; }); -const mockSelect = vi.mocked(prompts.select); -const mockConfirm = vi.mocked(prompts.confirm); +const mockSelect = vi.mocked(promptSelect); +const mockConfirm = vi.mocked(promptConfirm); const mockLog = vi.mocked(log); const skipMessage = expect.stringContaining('Git hooks already configured, skipping'); -function git(cwd: string, ...args: string[]): void { +function git(cwd: string, ...args: Array): void { const result = spawnSync('git', args, { cwd, stdio: 'pipe' }); if (result.status !== 0) { throw new Error(`git ${args.join(' ')} failed: ${result.stderr.toString()}`); } } -function writePackageJson(dir: string, pkg: Record): void { +function writePackageJson(dir: string, pkg: JsonObject): void { fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkg)); } function readPackageJson(dir: string): { scripts?: Record } { - return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')); + return readJsonFile(path.join(dir, 'package.json')); } /** Simulate what `vp config` leaves behind: dispatcher files and core.hooksPath. */ -function installDispatcher(dir: string, hookNames: string[]): void { +function installDispatcher(dir: string, hookNames: Array): void { const dispatcherDir = path.join(dir, '.vite-hooks', '_'); fs.mkdirSync(dispatcherDir, { recursive: true }); function writeScript(name: string, content: string): void { @@ -367,7 +378,7 @@ describe('collectMigrationSetupPlan existing Vite+ hooks', () => { expect(plan.shouldSetupHooks).toBe(false); expectNoHooksPrompt(); - expect(prompts.log.warn).toHaveBeenCalledWith( + expect(promptLog.warn).toHaveBeenCalledWith( expect.stringContaining('core.hooksPath is already set to ".githooks"'), ); }); @@ -383,7 +394,7 @@ describe('collectMigrationSetupPlan existing Vite+ hooks', () => { expect(plan.shouldSetupHooks).toBe(false); expectNoHooksPrompt(); - expect(prompts.log.warn).toHaveBeenCalledWith( + expect(promptLog.warn).toHaveBeenCalledWith( expect.stringContaining( `Git hook dispatcher path "${path.join('.vite-hooks', '_')}" is unsafe`, ), diff --git a/packages/cli/src/migration/__tests__/toolchain-version-changes.spec.ts b/packages/cli/src/migration/__tests__/toolchain-version-changes.spec.ts index 1ae3fdc358..2d81b9ae64 100644 --- a/packages/cli/src/migration/__tests__/toolchain-version-changes.spec.ts +++ b/packages/cli/src/migration/__tests__/toolchain-version-changes.spec.ts @@ -1,11 +1,10 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import url from 'node:url'; import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { VITE_PLUS_VERSION, VITEST_VERSION } from '../../utils/constants.js'; +import { VITE_PLUS_VERSION, VITEST_VERSION } from '../../utils/constants.ts'; // `collectToolchainVersionChanges` reads the bundled raw Vite version via // `await import('../versions.js')`. In the built CLI that resolves to @@ -13,7 +12,7 @@ import { VITE_PLUS_VERSION, VITEST_VERSION } from '../../utils/constants.js'; // source-mode tests the file does not exist, so create a stub at the resolved // source path (src/migration/versions.ts) for the duration of this spec. const STUB_BUNDLED_VITE = '8.1.0'; -const here = path.dirname(url.fileURLToPath(import.meta.url)); +const here = import.meta.dirname; const versionsSourcePath = path.resolve(here, '../versions.ts'); const createdVersionsStub = !fs.existsSync(versionsSourcePath); if (createdVersionsStub) { @@ -23,7 +22,7 @@ if (createdVersionsStub) { ); } -const { collectToolchainVersionChanges } = await import('../migrator.js'); +const { collectToolchainVersionChanges } = await import('../migrator.ts'); afterAll(() => { if (createdVersionsStub && fs.existsSync(versionsSourcePath)) { diff --git a/packages/cli/src/migration/__tests__/ts-node-config.spec.ts b/packages/cli/src/migration/__tests__/ts-node-config.spec.ts index 86018daf98..e423b60018 100644 --- a/packages/cli/src/migration/__tests__/ts-node-config.spec.ts +++ b/packages/cli/src/migration/__tests__/ts-node-config.spec.ts @@ -23,7 +23,7 @@ describe('prepareTsNodeRun', () => { fs.writeFileSync(path.join(cwd, file), JSON.stringify(value)); } - function prepare(args: string[], environment: string[] = [], executable = 'ts-node') { + function prepare(args: Array, environment: Array = [], executable = 'ts-node') { return prepareTsNodeRun(args, { cwd, environment, diff --git a/packages/cli/src/migration/__tests__/ts-node.spec.ts b/packages/cli/src/migration/__tests__/ts-node.spec.ts index 7b23180d2f..1ca0b57d39 100644 --- a/packages/cli/src/migration/__tests__/ts-node.spec.ts +++ b/packages/cli/src/migration/__tests__/ts-node.spec.ts @@ -2,10 +2,18 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; +import type { log as promptLog } from '@voidzero-dev/vite-plus-prompts'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { JsonObject } from '../../utils/json.ts'; +import { readJsonFile } from '../../utils/json.ts'; + vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ - log: { info: vi.fn(), success: vi.fn(), warn: vi.fn() }, + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + }, })); import { @@ -17,13 +25,13 @@ import { createMigrationReport } from '../report.ts'; describe('ts-node migration', () => { let root: string; - const write = (file: string, content: string | object) => { + const write = (file: string, content: string | JsonObject) => { const target = path.join(root, file); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, typeof content === 'string' ? content : JSON.stringify(content)); }; const read = (file: string) => fs.readFileSync(path.join(root, file), 'utf8'); - const readJson = (file: string) => JSON.parse(read(file)); + const readJson = (file: string) => readJsonFile(path.join(root, file)); const expectRetained = () => { const command = 'ts-node -T a.ts'; @@ -39,8 +47,8 @@ describe('ts-node migration', () => { }); } expect(migrateTsNodeToVpx(root, undefined, report).dependencyRemoved).toBe(false); - expect(readJson('package.json').scripts.run).toBe(command); - expect(readJson('package.json').devDependencies['ts-node']).toBe('10.9.2'); + expect(readJson('package.json')).toHaveProperty(['scripts', 'run'], command); + expect(readJson('package.json')).toHaveProperty(['devDependencies', 'ts-node'], '10.9.2'); expect(report.warnings).toContainEqual(expect.stringContaining('CommonJS interop')); }; @@ -87,6 +95,7 @@ describe('ts-node migration', () => { "import value from 'node:fs'; console.log(value);", "import * as dependency from 'node:fs'; console.log(dependency);", ])('retains runtime bindings in %s', (source) => { + expect.hasAssertions(); write('a.ts', source); expectRetained(); }); @@ -94,6 +103,7 @@ describe('ts-node migration', () => { it.each([undefined, false, true])( 'retains default bindings with esModuleInterop=%s', (esModuleInterop) => { + expect.hasAssertions(); write('tsconfig.json', { compilerOptions: { module: 'CommonJS', target: 'ES2022', esModuleInterop }, }); @@ -124,6 +134,7 @@ describe('ts-node migration', () => { ['./nested', 'nested/index.js', {}], ['./nested/dep.cts', 'nested/dep.cts', {}], ])('resolves CommonJS target %s', (specifier, file, pkg) => { + expect.hasAssertions(); write(file, 'module.exports = Object.assign({}, { value: 42 });\n'); write(path.join(path.dirname(file), 'package.json'), pkg); write('a.ts', `import { value } from '${specifier}'; console.log(value);`); @@ -131,6 +142,7 @@ describe('ts-node migration', () => { }); it('retains a dependency whose import and require conditions select different modules', () => { + expect.hasAssertions(); write('node_modules/dependency/package.json', { exports: { import: './import.mjs', require: './require.mjs' }, }); @@ -141,6 +153,7 @@ describe('ts-node migration', () => { }); it('resolves imports relative to the real entry behind a symlink', () => { + expect.hasAssertions(); write('package.json', { ...readJson('package.json'), type: 'module' }); write('dep.js', 'export const value = 1;'); write('actual/package.json', { type: 'commonjs' }); @@ -154,6 +167,7 @@ describe('ts-node migration', () => { it.each(['./missing.js', 'missing-package', './invalid/dep.js'])( 'retains a binding when the target cannot be checked: %s', (specifier) => { + expect.hasAssertions(); write('invalid/package.json', '{'); write('invalid/dep.js', 'exports.value = 42;'); write('a.ts', `import { value } from '${specifier}'; console.log(value);`); @@ -569,8 +583,8 @@ describe('ts-node migration', () => { write(file, content); const report = createMigrationReport(); expect(migrateTsNodeToVpx(root, undefined, report).dependencyRemoved).toBe(false); - expect(readJson('package.json').scripts.seed).toBe('vpx a.ts'); - expect(readJson('package.json').devDependencies['ts-node']).toBe('^10.9.2'); + expect(readJson('package.json')).toHaveProperty(['scripts', 'seed'], 'vpx a.ts'); + expect(readJson('package.json')).toHaveProperty(['devDependencies', 'ts-node'], '^10.9.2'); expect(report.warnings).toContainEqual(expect.stringContaining(`${file} still uses ts-node`)); }); @@ -583,7 +597,7 @@ describe('ts-node migration', () => { }); expect(detectTsNodeProject(root)).toBe(true); expect(migrateTsNodeToVpx(root).changed).toBe(false); - expect(readJson('package.json').scripts.seed).toBe('ts-node -T a.ts'); + expect(readJson('package.json')).toHaveProperty(['scripts', 'seed'], 'ts-node -T a.ts'); }, ); @@ -614,9 +628,12 @@ describe('ts-node migration', () => { { name: 'b', path: 'packages/b' }, ]; expect(migrateTsNodeToVpx(root, packages).dependencyRemoved).toBe(false); - expect(readJson('packages/a/package.json').scripts.seed).toBe('vpx a.ts'); - expect(readJson('packages/b/package.json').scripts.seed).toBe('ts-node a.ts'); - expect(readJson('packages/a/package.json').devDependencies['ts-node']).toBe('^10.9.2'); - expect(readJson('package.json').devDependencies['ts-node']).toBe('^10.9.2'); + expect(readJson('packages/a/package.json')).toHaveProperty(['scripts', 'seed'], 'vpx a.ts'); + expect(readJson('packages/b/package.json')).toHaveProperty(['scripts', 'seed'], 'ts-node a.ts'); + expect(readJson('packages/a/package.json')).toHaveProperty( + ['devDependencies', 'ts-node'], + '^10.9.2', + ); + expect(readJson('package.json')).toHaveProperty(['devDependencies', 'ts-node'], '^10.9.2'); }); }); diff --git a/packages/cli/src/migration/__tests__/tsup.spec.ts b/packages/cli/src/migration/__tests__/tsup.spec.ts index b824b0f7d1..39a89adf94 100644 --- a/packages/cli/src/migration/__tests__/tsup.spec.ts +++ b/packages/cli/src/migration/__tests__/tsup.spec.ts @@ -2,16 +2,20 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; +import type { log as promptLog, confirm as promptConfirm } from '@voidzero-dev/vite-plus-prompts'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { cancelAndExit } from '../../utils/prompts.ts'; +import { fixtureObject, fixtureString } from './fixture-json.ts'; + vi.mock('vite/package.json', () => ({ default: { bundledVersions: { tsdown: '0.99.0' } }, })); const { mockConfirm, mockInfo, mockWarn } = vi.hoisted(() => ({ - mockConfirm: vi.fn(), - mockInfo: vi.fn(), - mockWarn: vi.fn(), + mockConfirm: vi.fn(), + mockInfo: vi.fn(), + mockWarn: vi.fn(), })); vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ @@ -19,17 +23,17 @@ vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ isCancel: () => false, log: { info: mockInfo, - success: vi.fn(), + success: vi.fn(), warn: mockWarn, }, })); vi.mock(import('../../utils/command.ts'), async (importOriginal) => ({ ...(await importOriginal()), - runCommandSilently: vi.fn(), + runCommandSilently: vi.fn(), })); vi.mock('../../utils/prompts.ts', () => ({ - cancelAndExit: vi.fn(), + cancelAndExit: vi.fn(), })); import { PackageManager } from '../../types/index.ts'; @@ -50,7 +54,7 @@ function manualMigrationOptions(targetLabel = 'the project root'): string { ].join('\n'); } -function migrationSkillGuidance(instructions: string[]): string { +function migrationSkillGuidance(instructions: Array): string { return [ ...instructions, '', @@ -446,9 +450,10 @@ describe('tsup migration', () => { } mockRunCommandSilently.mockImplementation(async ({ cwd }) => { const packageJsonPath = path.join(cwd, 'package.json'); - const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); - packageJson.devDependencies.tsdown = '0.22.14'; - delete packageJson.devDependencies.tsup; + const packageJson = readJsonFile(packageJsonPath); + const devDependencies = fixtureObject(packageJson, 'devDependencies'); + devDependencies.tsdown = '0.22.14'; + delete devDependencies.tsup; fs.writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`); fs.writeFileSync(path.join(cwd, 'tsdown.config.ts'), 'export default {};\n'); fs.unlinkSync(path.join(cwd, 'tsup.config.ts')); @@ -510,9 +515,10 @@ describe('tsup migration', () => { fs.writeFileSync(path.join(packagePath, 'tsup.config.ts'), originalConfig); mockRunCommandSilently.mockImplementation(async ({ cwd }) => { const packageJsonPath = path.join(cwd, 'package.json'); - const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); - packageJson.devDependencies.tsdown = '0.22.14'; - delete packageJson.devDependencies.tsup; + const packageJson = readJsonFile(packageJsonPath); + const devDependencies = fixtureObject(packageJson, 'devDependencies'); + devDependencies.tsdown = '0.22.14'; + delete devDependencies.tsup; fs.writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`); fs.writeFileSync(path.join(cwd, 'tsdown.config.ts'), 'export default {};\n'); fs.unlinkSync(path.join(cwd, 'tsup.config.ts')); @@ -581,15 +587,17 @@ describe('tsup migration', () => { } mockRunCommandSilently.mockImplementation(async ({ cwd }) => { const packageJsonPath = path.join(cwd, 'package.json'); - const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); - for (const scriptName of Object.keys(packageJson.scripts)) { - packageJson.scripts[scriptName] = packageJson.scripts[scriptName].replaceAll( + const packageJson = readJsonFile(packageJsonPath); + const scripts = fixtureObject(packageJson, 'scripts'); + const devDependencies = fixtureObject(packageJson, 'devDependencies'); + for (const scriptName of Object.keys(scripts)) { + scripts[scriptName] = fixtureString(packageJson, 'scripts', scriptName).replaceAll( 'tsup', 'tsdown', ); } - packageJson.devDependencies.tsdown = '0.22.14'; - delete packageJson.devDependencies.tsup; + devDependencies.tsdown = '0.22.14'; + delete devDependencies.tsup; fs.writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`); fs.writeFileSync(path.join(cwd, 'tsdown.config.ts'), 'export default {};\n'); fs.unlinkSync(path.join(cwd, 'tsup.config.ts')); @@ -641,12 +649,14 @@ describe('tsup migration', () => { ); mockRunCommandSilently.mockImplementation(async () => { const packageJsonPath = path.join(projectPath, 'package.json'); - const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); - for (const name of Object.keys(packageJson.scripts)) { - packageJson.scripts[name] = packageJson.scripts[name].replace('tsup', 'tsdown'); + const packageJson = readJsonFile(packageJsonPath); + const scripts = fixtureObject(packageJson, 'scripts'); + const devDependencies = fixtureObject(packageJson, 'devDependencies'); + for (const name of Object.keys(scripts)) { + scripts[name] = fixtureString(packageJson, 'scripts', name).replace('tsup', 'tsdown'); } - packageJson.devDependencies.tsdown = '0.22.14'; - delete packageJson.devDependencies.tsup; + devDependencies.tsdown = '0.22.14'; + delete devDependencies.tsup; fs.writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`); fs.writeFileSync(path.join(projectPath, 'tsdown.config.ts'), 'export default {};\n'); fs.unlinkSync(path.join(projectPath, 'tsup.config.ts')); diff --git a/packages/cli/src/migration/__tests__/tsx.spec.ts b/packages/cli/src/migration/__tests__/tsx.spec.ts index fce8d0d3ff..bafcec5981 100644 --- a/packages/cli/src/migration/__tests__/tsx.spec.ts +++ b/packages/cli/src/migration/__tests__/tsx.spec.ts @@ -3,10 +3,18 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; +import type { log as promptLog } from '@voidzero-dev/vite-plus-prompts'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { JsonObject } from '../../utils/json.ts'; +import { readJsonFile } from '../../utils/json.ts'; + vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ - log: { info: vi.fn(), success: vi.fn(), warn: vi.fn() }, + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + }, })); import { detectTsxProject, migrateTsxToVpx, rewriteTsxCommand } from '../migrator/tsx.ts'; @@ -175,7 +183,7 @@ describe('rewriteTsxCommand', () => { ['tsx ./a.ts | tee log', 'shell syntax'], ['tsx $ENTRY', 'shell syntax'], ['tsx %ENTRY%.ts', 'shell syntax'], - ['.\\node_modules\\.bin\\tsx.cmd scripts/a.ts', 'shell syntax'], + [String.raw`.\node_modules\.bin\tsx.cmd scripts/a.ts`, 'shell syntax'], // A quoted argument of a program that does not run commands is data. ['echo "tsx scripts/build.ts"', 'does not rewrite this use of tsx'], // Only the value of `-c` is a command; the next argument is the shell's `$0`. @@ -497,7 +505,7 @@ describe('rewriteTsxCommand', () => { describe('migrateTsxToVpx', () => { let root: string; - const write = (file: string, content: string | object) => { + const write = (file: string, content: string | JsonObject) => { const target = path.join(root, file); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync( @@ -506,7 +514,7 @@ describe('migrateTsxToVpx', () => { ); }; const read = (file: string) => fs.readFileSync(path.join(root, file), 'utf8'); - const readJson = (file: string) => JSON.parse(read(file)); + const readJson = (file: string) => readJsonFile(path.join(root, file)); beforeEach(() => { root = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-test-tsx-')); @@ -619,7 +627,8 @@ describe('migrateTsxToVpx', () => { changed: true, dependencyRemoved: false, }); - expect(readJson('package.json').scripts.seed).toBe( + expect(readJson('package.json')).toHaveProperty( + ['scripts', 'seed'], 'node --import=vite-plus/register scripts/seed.ts', ); expect(readJson('package.json').ava).toEqual({ nodeArguments: ['--import=tsx'] }); @@ -671,7 +680,7 @@ describe('migrateTsxToVpx', () => { }); expect(migrateTsxToVpx(root).dependencyRemoved).toBe(false); - expect(readJson('package.json').scripts.build).toBe(build); + expect(readJson('package.json')).toHaveProperty(['scripts', 'build'], build); }, ); @@ -711,7 +720,7 @@ describe('migrateTsxToVpx', () => { }); expect(migrateTsxToVpx(root).dependencyRemoved).toBe(false); - expect(readJson('package.json').scripts.build).toBe(build); + expect(readJson('package.json')).toHaveProperty(['scripts', 'build'], build); }, ); @@ -733,7 +742,7 @@ describe('migrateTsxToVpx', () => { const report = createMigrationReport(); expect(migrateTsxToVpx(root, undefined, report).dependencyRemoved).toBe(false); - expect(readJson('package.json').scripts.build).toBe(build); + expect(readJson('package.json')).toHaveProperty(['scripts', 'build'], build); expect(report.warnings).toContainEqual( expect.stringContaining('child command that vp migrate cannot check'), ); @@ -781,7 +790,7 @@ describe('migrateTsxToVpx', () => { changed: false, dependencyRemoved: false, }); - expect(readJson('package.json').scripts.build).toBe(build); + expect(readJson('package.json')).toHaveProperty(['scripts', 'build'], build); expect(report.warnings).toContainEqual(expect.stringContaining('Kept tsx in')); }); @@ -793,7 +802,8 @@ describe('migrateTsxToVpx', () => { }); expect(migrateTsxToVpx(root).dependencyRemoved).toBe(true); - expect(readJson('package.json').scripts.build).toBe( + expect(readJson('package.json')).toHaveProperty( + ['scripts', 'build'], 'NODE_OPTIONS=--import=vite-plus/register env MODE=test node scripts/seed.ts', ); }); @@ -816,10 +826,11 @@ describe('migrateTsxToVpx', () => { expect(migrateTsxToVpx(root, [{ name: 'a', path: 'packages/a' }]).dependencyRemoved).toBe( false, ); - expect(readJson('package.json').scripts.build).toBe( + expect(readJson('package.json')).toHaveProperty( + ['scripts', 'build'], 'NODE_OPTIONS=--import=vite-plus/register node --run generate', ); - expect(readJson('packages/a/package.json').scripts.build).toBe(build); + expect(readJson('packages/a/package.json')).toHaveProperty(['scripts', 'build'], build); }); it.each([ @@ -1044,7 +1055,7 @@ describe('migrateTsxToVpx', () => { write('package.json', { scripts: { dev: 'tsx watch src/server.ts', - ...(content === undefined ? { repl: 'tsx' } : {}), + ...(content === undefined ? { repl: 'tsx' } : undefined), }, devDependencies: { tsx: '^4.20.0' }, }); @@ -1054,7 +1065,10 @@ describe('migrateTsxToVpx', () => { const report = createMigrationReport(); expect(migrateTsxToVpx(root, undefined, report).dependencyRemoved).toBe(false); - expect(readJson('package.json').scripts.dev).toBe('vpx --watch src/server.ts'); + expect(readJson('package.json')).toHaveProperty( + ['scripts', 'dev'], + 'vpx --watch src/server.ts', + ); expect(readJson('package.json').devDependencies).toEqual({ tsx: '^4.20.0' }); expect(report.warnings).toContain(`Kept the tsx devDependency in package.json: ${user}.`); }); @@ -1107,7 +1121,7 @@ describe('migrateTsxToVpx', () => { const report = createMigrationReport(); expect(migrateTsxToVpx(root, undefined, report).dependencyRemoved).toBe(false); - expect(readJson('package.json').scripts.start).toBe('vpx src/server.ts'); + expect(readJson('package.json')).toHaveProperty(['scripts', 'start'], 'vpx src/server.ts'); expect(readJson('package.json').devDependencies).toEqual({ tsx: '^4.20.0' }); expect(report.warnings).toEqual([ `Kept the tsx devDependency in package.json: src/options.${extension} still uses tsx.`, @@ -1125,7 +1139,7 @@ describe('migrateTsxToVpx', () => { expect(detectTsxProject(root)).toBe(false); expect(migrateTsxToVpx(root, undefined, report).changed).toBe(false); - expect(readJson('package.json').scripts.start).toBe('tsx src/server.ts'); + expect(readJson('package.json')).toHaveProperty(['scripts', 'start'], 'tsx src/server.ts'); expect(report.warnings).toEqual([expect.stringContaining('Kept tsx in package.json')]); }, ); @@ -1164,7 +1178,10 @@ describe('migrateTsxToVpx', () => { const report = createMigrationReport(); expect(migrateTsxToVpx(root, undefined, report).dependencyRemoved).toBe(false); - expect(readJson('package.json').scripts.dev).toBe('vpx --watch src/server.ts'); + expect(readJson('package.json')).toHaveProperty( + ['scripts', 'dev'], + 'vpx --watch src/server.ts', + ); expect(report.warnings).toEqual([ `Kept the tsx devDependency in package.json: \`${field}\` in package.json still uses tsx.`, ]); @@ -1194,6 +1211,16 @@ describe('migrateTsxToVpx', () => { expect(detectTsxProject(root)).toBe(false); }); + it('leaves a non-object lint-staged config alone when rewriting scripts', () => { + write('package.json', { scripts: { build: 'tsx scripts/check.ts' } }); + write('.lintstagedrc.json', 'null'); + + expect(detectTsxProject(root)).toBe(true); + migrateTsxToVpx(root); + expect(readJson('package.json')).toHaveProperty('scripts.build', 'vpx scripts/check.ts'); + expect(read('.lintstagedrc.json')).toBe('null'); + }); + it('rewrites shebang options as it rewrites commands', () => { write('package.json', { type: 'module' }); write('scripts/a.ts', '#!/usr/bin/env -S tsx --no-cache --tsconfig cli.json\nexport {};\n'); @@ -1244,7 +1271,7 @@ describe('migrateTsxToVpx', () => { expect(detectTsxProject(root)).toBe(false); migrateTsxToVpx(root, undefined, report); - expect(readJson('package.json').scripts.build).toBe('tsx scripts/build.ts'); + expect(readJson('package.json')).toHaveProperty(['scripts', 'build'], 'tsx scripts/build.ts'); expect(read('scripts/release.ts')).toMatch(/^#!\/usr\/bin\/env tsx\n/); expect(report.warnings).toEqual([ expect.stringContaining( @@ -1268,8 +1295,11 @@ describe('migrateTsxToVpx', () => { migrateTsxToVpx(root, packages, report); - expect(readJson('packages/a/package.json').scripts.gen).toBe('vpx gen.ts'); - expect(readJson('packages/b/package.json').scripts.calc).toBe("tsx -e 'run()'"); + expect(readJson('packages/a/package.json')).toHaveProperty(['scripts', 'gen'], 'vpx gen.ts'); + expect(readJson('packages/b/package.json')).toHaveProperty( + ['scripts', 'calc'], + "tsx -e 'run()'", + ); expect(readJson('package.json').devDependencies).toEqual({ tsx: '^4.20.0' }); expect(report.warnings).toEqual([ expect.stringContaining('Kept tsx in packages/b/package.json scripts "calc"'), diff --git a/packages/cli/src/migration/__tests__/vite-peer-dependency-rule.spec.ts b/packages/cli/src/migration/__tests__/vite-peer-dependency-rule.spec.ts index ea531c0b2b..d23b0f822e 100644 --- a/packages/cli/src/migration/__tests__/vite-peer-dependency-rule.spec.ts +++ b/packages/cli/src/migration/__tests__/vite-peer-dependency-rule.spec.ts @@ -5,14 +5,17 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { parse as parseYaml } from 'yaml'; -import { PackageManager, type WorkspaceInfo } from '../../types/index.js'; -import { VITE_PLUS_OVERRIDE_PACKAGES } from '../../utils/constants.js'; -import type { PnpmPeerDependencyRules as PeerDependencyRules } from '../migrator/shared.js'; -import { createMigrationReport } from '../report.js'; +import type { WorkspaceInfo } from '../../types/index.ts'; +import { PackageManager } from '../../types/index.ts'; +import { VITE_PLUS_OVERRIDE_PACKAGES } from '../../utils/constants.ts'; +import { readJsonFile as readJson } from '../../utils/json.ts'; +import type { PnpmPeerDependencyRules as PeerDependencyRules } from '../migrator/shared.ts'; +import { createMigrationReport } from '../report.ts'; +import { fixtureObject } from './fixture-json.ts'; // Keep the vite-plus spec stable; each test selects the core alias it needs. -vi.mock('../../utils/constants.js', async (importOriginal) => { - const mod = await importOriginal(); +vi.mock(import('../../utils/constants.ts'), async (importOriginal) => { + const mod = await importOriginal(); return { ...mod, VITE_PLUS_VERSION: 'latest', @@ -25,7 +28,7 @@ const { ensureVitePlusBootstrap, rewriteStandaloneProject, vitePeerDependencyRuleRequired, -} = await import('../migrator.js'); +} = await import('../migrator.ts'); const STABLE_CORE = 'npm:@voidzero-dev/vite-plus-core@8.3.5000'; const PREVIEW_CORE = 'npm:@voidzero-dev/vite-plus-core@0.0.0-commit.0c515e3'; @@ -51,14 +54,10 @@ function makeWorkspaceInfo(rootDir: string, version = '10.33.0'): WorkspaceInfo }; } -function readJson(filePath: string): Record { - return JSON.parse(fs.readFileSync(filePath, 'utf8')); -} - -function readWorkspaceRules(projectPath: string): PeerDependencyRules | undefined { - const workspace = parseYaml( - fs.readFileSync(path.join(projectPath, 'pnpm-workspace.yaml'), 'utf8'), - ) as { peerDependencyRules?: PeerDependencyRules }; +function readWorkspaceRules(projectPath: string) { + const workspace = fixtureObject( + parseYaml(fs.readFileSync(path.join(projectPath, 'pnpm-workspace.yaml'), 'utf8')), + ); return workspace.peerDependencyRules; } @@ -69,7 +68,7 @@ function readPackageJsonRules(projectPath: string): PeerDependencyRules | undefi return pkg.pnpm?.peerDependencyRules; } -function writeVitePlusProject(projectPath: string, peerDependencyRules: string[]) { +function writeVitePlusProject(projectPath: string, peerDependencyRules: Array) { fs.writeFileSync( path.join(projectPath, 'package.json'), JSON.stringify({ @@ -295,11 +294,9 @@ describe('pnpm vite peer rule', () => { ensureVitePlusBootstrap(makeWorkspaceInfo(tmpDir, '10.6.1')); - const pkg = readJson(path.join(tmpDir, 'package.json')) as { - pnpm: Record; - }; - expect(pkg.pnpm.peerDependencyRules).toBeUndefined(); - expect(pkg.pnpm.overrides).toEqual({ 'vite@*': STABLE_CORE }); + const pkg = readJson(path.join(tmpDir, 'package.json')); + expect(fixtureObject(pkg, 'pnpm').peerDependencyRules).toBeUndefined(); + expect(pkg).toHaveProperty(['pnpm', 'overrides'], { 'vite@*': STABLE_CORE }); }); it('removes a vite rule during the full migration', () => { diff --git a/packages/cli/src/migration/__tests__/vitest-v5-ast.spec.ts b/packages/cli/src/migration/__tests__/vitest-v5-ast.spec.ts index 8ae7afbd6b..e8964a5d82 100644 --- a/packages/cli/src/migration/__tests__/vitest-v5-ast.spec.ts +++ b/packages/cli/src/migration/__tests__/vitest-v5-ast.spec.ts @@ -25,7 +25,7 @@ describe('Oxc migration analysis', () => { expect(() => parseSource('test.js', '// @flow\nconst value: string = "x";')).toThrow( 'Flow is not supported', ); - expect(() => parseSource('test.ts', 'const = ;')).toThrow(); + expect(() => parseSource('test.ts', 'const = ;')).toThrow(/expected|parse|unexpected/i); }); it.each([ diff --git a/packages/cli/src/migration/__tests__/vitest-v5-benchmark-output.spec.ts b/packages/cli/src/migration/__tests__/vitest-v5-benchmark-output.spec.ts index 27926dd1ba..fecf88710a 100644 --- a/packages/cli/src/migration/__tests__/vitest-v5-benchmark-output.spec.ts +++ b/packages/cli/src/migration/__tests__/vitest-v5-benchmark-output.spec.ts @@ -4,14 +4,19 @@ import { describe, expect, it } from 'vitest'; import { migrateVitestV5Command } from '../vitest-v5/commands.ts'; import { migrateVitestV5Config } from '../vitest-v5/config.ts'; +import { fixtureObject } from './fixture-json.ts'; const config = (test: string) => migrateVitestV5Config('vitest.config.js', `export default { test: { ${test} } };`, { preserveV4: true, }); -function resolved(content: string): Record { - return runInNewContext(content.replace('export default', 'result ='), {}).test; +function resolved(content: string) { + const result: unknown = runInNewContext(content.replace('export default', 'result ='), {}); + if (typeof result !== 'object' || !result || !('test' in result)) { + throw new TypeError('Expected the fixture to export a test configuration'); + } + return fixtureObject(structuredClone(result.test)); } describe('Vitest v5 benchmark output config migration', () => { diff --git a/packages/cli/src/migration/__tests__/vitest-v5-benchmark-plans.spec.ts b/packages/cli/src/migration/__tests__/vitest-v5-benchmark-plans.spec.ts index 568e779cd2..e6213d8fc2 100644 --- a/packages/cli/src/migration/__tests__/vitest-v5-benchmark-plans.spec.ts +++ b/packages/cli/src/migration/__tests__/vitest-v5-benchmark-plans.spec.ts @@ -13,7 +13,7 @@ import { } from '../migrator.ts'; import { SourceEditor } from '../vitest-v5/ast.ts'; -const directories: string[] = []; +const directories: Array = []; afterEach(() => { vi.restoreAllMocks(); for (const directory of directories.splice(0)) { diff --git a/packages/cli/src/migration/__tests__/vitest-v5-benchmarks.spec.ts b/packages/cli/src/migration/__tests__/vitest-v5-benchmarks.spec.ts index bc4978038a..7d2693a2e8 100644 --- a/packages/cli/src/migration/__tests__/vitest-v5-benchmarks.spec.ts +++ b/packages/cli/src/migration/__tests__/vitest-v5-benchmarks.spec.ts @@ -32,7 +32,9 @@ describe('Vitest v5 benchmark migration', () => { }; const script = result.content.replaceAll('import.meta.vitest', '__vitest'); // Production evaluation must not import or register any test APIs. - expect(() => runInNewContext(script, { __vitest: undefined, work })).not.toThrow(); + expect(() => { + runInNewContext(script, { __vitest: undefined, work }); + }).not.toThrow(); runInNewContext(script, { work, __vitest: { @@ -195,7 +197,7 @@ measure('plain', () => results.push('plain'));`); expect(result.content).toContain(`import { test as _test } from 'vitest';`); expect(result.content).toContain(`_test('scope', async ({ bench: _bench })`); expect(result.content).toContain(`_test('plain', async ({ bench })`); - const results: unknown[] = []; + const results: Array = []; const tests: Array<(context: unknown) => Promise> = []; runInNewContext(result.content.replace(/^import[^\n]+\n/, ''), { results, @@ -300,7 +302,7 @@ bench('comments', /* workload */ () => { /* inside */ work(); }, /* trailing */) true, ); expect(result.findings).toEqual([]); - const events: string[] = []; + const events: Array = []; const tests: Array<{ name: string; fn: (context: unknown) => Promise }> = []; const context = { events, @@ -334,8 +336,8 @@ bench('comments', /* workload */ () => { /* inside */ work(); }, /* trailing */) it('retains argument evaluation order and temporal dead zones', () => { const result = migrate(`bench(getName(), workload); const workload = () => {};`, true); expect(result.findings).toEqual([]); - const events: string[] = []; - expect(() => + const events: Array = []; + expect(() => { runInNewContext(result.content, { getName: () => { events.push('name'); @@ -344,8 +346,8 @@ bench('comments', /* workload */ () => { /* inside */ work(); }, /* trailing */) test: () => { events.push('test'); }, - }), - ).toThrow(/before initialization/); + }); + }).toThrow(/before initialization/); expect(events).toEqual(['name']); }); @@ -415,7 +417,7 @@ function helper(bench) { bench('local', () => work()); }`; });`; const result = migrate(input, true); expect(result.findings).toEqual([]); - const results: number[] = []; + const results: Array = []; const tests: Array<{ name: string; fn: (context: unknown) => Promise }> = []; runInNewContext(result.content, { results, diff --git a/packages/cli/src/migration/__tests__/vitest-v5-compatibility.spec.ts b/packages/cli/src/migration/__tests__/vitest-v5-compatibility.spec.ts index a30ee20a90..43e6e8e380 100644 --- a/packages/cli/src/migration/__tests__/vitest-v5-compatibility.spec.ts +++ b/packages/cli/src/migration/__tests__/vitest-v5-compatibility.spec.ts @@ -9,7 +9,10 @@ import { migrateVitestV5Config } from '../vitest-v5/config.ts'; const options = { preserveV4: true, temporalPolyfill: true }; const migrate = (source: string) => migrateVitestV5Config('vitest.config.mjs', source, options); -const evaluate = (source: string) => runInNewContext(source.replace('export default', '')); +const evaluate = (source: string) => { + const result: unknown = runInNewContext(source.replace('export default', '')); + return result; +}; describe('Vitest v4 compatibility comments', () => { it.each([ @@ -66,7 +69,7 @@ describe('Vitest v4 compatibility comments', () => { expect( migrateVitestV5Config('vitest.config.mjs', result.content, { preserveV4: false }), ).toEqual(result); - const withoutComments = result.content.replace(/^[\t ]*\/\/.*(?:\r?\n|$)/gm, ''); + const withoutComments = result.content.replaceAll(/^[\t ]*\/\/.*(?:\r?\n|$)/gm, ''); expect(migrate(withoutComments)).toEqual({ content: withoutComments, findings: [] }); const guide = fs.readFileSync( new URL('../../../../../docs/guide/vitest-v5.md', import.meta.url), @@ -86,7 +89,7 @@ describe('Vitest v4 compatibility comments', () => { expect(result.content).toContain('Report consumer.'); expect(result.content).toContain(`reporters: [${reporter}]`); expect(result.content).not.toContain('stdout'); - expect(evaluate(result.content).test.reporters).toEqual([['json']]); + expect(evaluate(result.content)).toHaveProperty(['test', 'reporters'], [['json']]); expect(migrate(result.content)).toEqual(result); }); @@ -105,9 +108,7 @@ describe('Vitest v4 compatibility comments', () => { const result = migrate(input); expect(result.findings).toEqual([]); expect(result.content).toContain('// Keep this project comment.'); - if (newline === '\r\n') { - expect(result.content.replaceAll('\r\n', '')).not.toContain('\n'); - } + expect(result.content.replaceAll(newline, '')).not.toMatch(/[\r\n]/); expect(evaluate(result.content)).toEqual({ test: { clearMocks: false, @@ -174,7 +175,7 @@ describe('Vitest v4 compatibility comments', () => { const input = 'export default ({ test: { value: `first\n second` } });'; const result = migrate(input); expect(result.findings).toEqual([]); - expect(evaluate(result.content).test.value).toBe('first\n second'); + expect(evaluate(result.content)).toHaveProperty(['test', 'value'], 'first\n second'); const editor = new SourceEditor('vitest.config.mjs', 'export default ({});'); editor.visit({ ObjectExpression(node) { @@ -183,6 +184,6 @@ describe('Vitest v4 compatibility comments', () => { }); const added = editor.finish(); expect(added.findings).toEqual([]); - expect(evaluate(added.content).copied).toBe('first\n second'); + expect(evaluate(added.content)).toHaveProperty('copied', 'first\n second'); }); }); diff --git a/packages/cli/src/migration/__tests__/vitest-v5-config-scopes.spec.ts b/packages/cli/src/migration/__tests__/vitest-v5-config-scopes.spec.ts index 73b0e597f1..1c8551e9a4 100644 --- a/packages/cli/src/migration/__tests__/vitest-v5-config-scopes.spec.ts +++ b/packages/cli/src/migration/__tests__/vitest-v5-config-scopes.spec.ts @@ -14,7 +14,7 @@ import { import { migrateVitestV5Config } from '../vitest-v5/config.ts'; import { migrateVitestV5Source } from '../vitest-v5/source.ts'; -const directories: string[] = []; +const directories: Array = []; afterEach(() => { for (const directory of directories.splice(0)) { fs.rmSync(directory, { recursive: true, force: true }); @@ -245,11 +245,8 @@ describe('In-source test ownership', () => { expect(plan.findings).toEqual([]); applyVitestV5Migration(plan); expect(read('web/extra/add.ts')).toContain('concurrent: false'); - if (inherits) { - expect(read('web/src/add.ts')).toContain('concurrent: false'); - } else { - expect(read('web/src/add.ts')).toBe(source); - } + const migrated = expect.stringContaining('concurrent: false'); + expect(read('web/src/add.ts')).toEqual(inherits ? migrated : source); expect(finishVitestV5Migration(plan)).toEqual([]); }); diff --git a/packages/cli/src/migration/__tests__/vitest-v5-lockfile.spec.ts b/packages/cli/src/migration/__tests__/vitest-v5-lockfile.spec.ts index f4d4b36d76..0caf9a9834 100644 --- a/packages/cli/src/migration/__tests__/vitest-v5-lockfile.spec.ts +++ b/packages/cli/src/migration/__tests__/vitest-v5-lockfile.spec.ts @@ -10,16 +10,16 @@ import { PackageManager } from '../../types/index.ts'; import { applyVitestV5Migration, planVitestV5Migration } from '../migrator.ts'; vi.mock('yaml', async (importOriginal) => { - const yaml = await importOriginal(); - return { ...yaml, parseDocument: vi.fn(yaml.parseDocument) }; + const yaml = await importOriginal<{ parseDocument: typeof parseDocument }>(); + return { ...yaml, parseDocument: vi.fn(yaml.parseDocument) }; }); -vi.mock('jsonc-parser', async (importOriginal) => { - const jsonc = await importOriginal(); - return { ...jsonc, parse: vi.fn(jsonc.parse) }; +vi.mock(import('jsonc-parser'), async (importOriginal) => { + const jsonc = await importOriginal(); + return { ...jsonc, parse: vi.fn(jsonc.parse) }; }); -const directories: string[] = []; +const directories: Array = []; afterEach(() => { vi.clearAllMocks(); vi.restoreAllMocks(); @@ -108,6 +108,22 @@ describe('Vitest source versions from lockfiles', () => { }, ); + it('resolves a pnpm importer alongside unrelated YAML aliases', () => { + const fixture = project('pnpm'); + fs.writeFileSync( + fixture.file, + `lockfileVersion: '9.0' +importers: + '.': + devDependencies: + vitest: { specifier: '^4 || ^5', version: 4.1.11 } +metadata: &metadata + reference: *metadata +`, + ); + expect(fixture.plan().projects[0].sourceVersion).toBe('4.1.11'); + }); + it.each(formats)('rejects stale %s importer/descriptor edges', (format) => { const plan = project(format, '^4 || ^5', '4.1.11', '^4.0.0').plan(); expect(plan.findings).toContainEqual( @@ -225,15 +241,13 @@ describe('Vitest source versions from lockfiles', () => { expect(plan.projects.map(({ sourceVersion }) => sourceVersion)).toEqual(['4.1.11', '4.1.11']); // One read captures the input snapshot and one parses the lockfile. expect(reads.mock.calls.filter(([file]) => file === fixture.file)).toHaveLength(2); - if (fixture.manager === PackageManager.npm) { - expect(json.mock.calls.filter(([source]) => source === before)).toHaveLength(1); - } else if (format === 'bun') { - expect(vi.mocked(parseJsonc).mock.calls.filter(([source]) => source === before)).toHaveLength( - 1, - ); - } else { - expect(parseDocument).toHaveBeenCalledTimes(1); - } + const parses = + fixture.manager === PackageManager.npm + ? json.mock.calls.filter(([source]) => source === before) + : format === 'bun' + ? vi.mocked(parseJsonc).mock.calls.filter(([source]) => source === before) + : vi.mocked(parseDocument).mock.calls; + expect(parses).toHaveLength(1); const after = before.replaceAll('4.1.11', '5.0.0'); fs.writeFileSync(fixture.file, after); diff --git a/packages/cli/src/migration/__tests__/vitest-v5-webdriverio.spec.ts b/packages/cli/src/migration/__tests__/vitest-v5-webdriverio.spec.ts index 71870e3668..00089cceb0 100644 --- a/packages/cli/src/migration/__tests__/vitest-v5-webdriverio.spec.ts +++ b/packages/cli/src/migration/__tests__/vitest-v5-webdriverio.spec.ts @@ -7,6 +7,7 @@ import { afterEach, describe, expect, it } from 'vitest'; import { parse as yaml } from 'yaml'; import { PackageManager } from '../../types/index.ts'; +import type { JsonObject } from '../../utils/json.ts'; import { applyVitestV5Migration, finishVitestV5Migration, @@ -14,15 +15,16 @@ import { vitestV5NeedsMigration, } from '../migrator.ts'; import { webdriverioMigrationSpec } from '../vitest-v5/webdriverio.ts'; +import { fixtureObject, fixtureString } from './fixture-json.ts'; const provider = '@vitest/browser-webdriverio'; -const directories: string[] = []; +const directories: Array = []; afterEach(() => { for (const dir of directories.splice(0)) { fs.rmSync(dir, { recursive: true, force: true }); } }); -function project(pkg: Record, files: Record = {}) { +function project(pkg: JsonObject, files: Record = {}) { const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-webdriverio-migrate-')); directories.push(rootDir); for (const [file, text] of Object.entries({ @@ -37,12 +39,12 @@ function project(pkg: Record, files: Record = { } function read(root: string, file = 'package.json') { const text = fs.readFileSync(path.join(root, file), 'utf8'); - return file.endsWith('.json') ? JSON.parse(text) : yaml(text); + return fixtureObject(file.endsWith('.json') ? JSON.parse(text) : yaml(text)); } function migrate( rootDir: string, packageManager: PackageManager = PackageManager.pnpm, - packages?: { name: string; path: string }[], + packages?: Array<{ name: string; path: string }>, ) { const workspace = { rootDir, packageManager, packages }; const plan = planVitestV5Migration(workspace); @@ -85,10 +87,10 @@ describe('WebDriverIO migration floor', () => { }); migrate(root, manager); const pkg = read(root); - expect(pkg.devDependencies[provider]).toBe('^5.0.0'); - expect(pkg.devDependencies.webdriverio).toBe('^9.0.0'); - expect(pkg.devEngines.runtime.version).not.toBe('20.19.0'); - expect(pkg.scripts.bench).toBe('vitest bench --run'); + expect(pkg).toHaveProperty(['devDependencies', provider], '^5.0.0'); + expect(pkg).toHaveProperty(['devDependencies', 'webdriverio'], '^9.0.0'); + expect(fixtureObject(pkg, 'devEngines', 'runtime').version).not.toBe('20.19.0'); + expect(pkg).toHaveProperty(['scripts', 'bench'], 'vitest bench --run'); }, ); it.each(['dependencies', 'devDependencies', 'optionalDependencies'])( @@ -96,7 +98,7 @@ describe('WebDriverIO migration floor', () => { (field) => { const root = project({ [field]: { [provider]: '4.1.11', webdriverio: '^9.0.0' } }); migrate(root); - expect(read(root)[field][provider]).toBe('^5.0.0'); + expect(read(root)).toHaveProperty([field, provider], '^5.0.0'); }, ); it('migrates a Vite+ 0.x source-only import and reuses a WebDriverIO sibling version', () => { @@ -131,8 +133,10 @@ describe('WebDriverIO migration floor', () => { devDependencies: { webdriverio: '^9' }, }); migrate(root); - expect(read(root).peerDependencies[provider]).toBe('^4 || ^5'); - expect(isRangeSubset(read(root).devDependencies[provider], '>=5.0.0')).toBe(true); + expect(read(root)).toHaveProperty(['peerDependencies', provider], '^4 || ^5'); + expect(isRangeSubset(fixtureString(read(root), 'devDependencies', provider), '>=5.0.0')).toBe( + true, + ); }); it('reuses a newer peer-only provider without downgrading it', () => { const root = project({ @@ -140,7 +144,7 @@ describe('WebDriverIO migration floor', () => { devDependencies: { webdriverio: '^9' }, }); migrate(root); - expect(read(root).devDependencies[provider]).toBe('^6.2.0'); + expect(read(root)).toHaveProperty(['devDependencies', provider], '^6.2.0'); }); it('reuses a root provider catalog for a source-only workspace member', () => { const root = project( @@ -155,10 +159,14 @@ describe('WebDriverIO migration floor', () => { }, ); migrate(root, PackageManager.pnpm, [{ name: 'child', path: 'packages/app' }]); - expect(read(root, 'packages/app/package.json').devDependencies[provider]).toBe( + expect(read(root, 'packages/app/package.json')).toHaveProperty( + ['devDependencies', provider], 'catalog:browser', ); - expect(read(root, 'pnpm-workspace.yaml').catalogs.browser[provider]).toBe('^6.2.0'); + expect(read(root, 'pnpm-workspace.yaml')).toHaveProperty( + ['catalogs', 'browser', provider], + '^6.2.0', + ); }); it('keeps a compatible npm override unchanged', () => { const root = project({ @@ -166,7 +174,7 @@ describe('WebDriverIO migration floor', () => { overrides: { [provider]: '5.2.0' }, }); const plan = migrate(root, PackageManager.npm); - expect(read(root).overrides[provider]).toBe('5.2.0'); + expect(read(root)).toHaveProperty(['overrides', provider], '5.2.0'); expect(plan.findings).toEqual([]); }); it('updates npm long-form pins without changing unrelated children', () => { @@ -175,7 +183,7 @@ describe('WebDriverIO migration floor', () => { overrides: { [provider]: { '.': '4.1.11', other: '1.0.0' } }, }); migrate(root, PackageManager.npm); - expect(read(root).overrides[provider]).toEqual({ other: '1.0.0' }); + expect(read(root)).toHaveProperty(['overrides', provider], { other: '1.0.0' }); }); it.each([PackageManager.pnpm, PackageManager.yarn, PackageManager.bun])( 'updates referenced catalogs on %s', @@ -190,10 +198,12 @@ describe('WebDriverIO migration floor', () => { devDependencies: { [provider]: 'catalog:', webdriverio: '^9' }, ...(manager === PackageManager.bun ? { workspaces: { packages: ['packages/*'], ...catalogs } } - : {}), + : undefined), }, { - ...(manager === PackageManager.bun ? {} : { [configFile]: JSON.stringify(catalogs) }), + ...(manager === PackageManager.bun + ? undefined + : { [configFile]: JSON.stringify(catalogs) }), 'packages/browser/package.json': JSON.stringify({ name: 'browser', devDependencies: { [provider]: 'catalog:browser', webdriverio: '^9' }, @@ -203,11 +213,12 @@ describe('WebDriverIO migration floor', () => { migrate(root, manager, [{ name: 'browser', path: 'packages/browser' }]); const output = manager === PackageManager.bun ? read(root).workspaces : read(root, configFile); - expect(output.catalog[provider]).toBe('^5.0.0'); - expect(output.catalogs.browser[provider]).toBe('^5.0.0'); - expect(output.catalogs.unused[provider]).toBe('4.0.0'); - expect(read(root).devDependencies[provider]).toBe('catalog:'); - expect(read(root, 'packages/browser/package.json').devDependencies[provider]).toBe( + expect(output).toHaveProperty(['catalog', provider], '^5.0.0'); + expect(output).toHaveProperty(['catalogs', 'browser', provider], '^5.0.0'); + expect(output).toHaveProperty(['catalogs', 'unused', provider], '4.0.0'); + expect(read(root)).toHaveProperty(['devDependencies', provider], 'catalog:'); + expect(read(root, 'packages/browser/package.json')).toHaveProperty( + ['devDependencies', provider], 'catalog:browser', ); }, @@ -228,11 +239,11 @@ describe('WebDriverIO migration floor', () => { }); migrate(root, manager); const output = read(root)[field]; - expect(output[provider]).toBeUndefined(); - expect(output[`app>${provider}`]).toBeUndefined(); - expect(output[`unrelated>${provider}`]).toBe('4.0.0'); - expect(output.unrelated[provider]).toBe('4.0.0'); - expect(read(root).devDependencies[provider]).toBe('^5.2.0'); + expect(fixtureObject(output)[provider]).toBeUndefined(); + expect(fixtureObject(output)[`app>${provider}`]).toBeUndefined(); + expect(output).toHaveProperty([`unrelated>${provider}`], '4.0.0'); + expect(output).toHaveProperty(['unrelated', provider], '4.0.0'); + expect(read(root)).toHaveProperty(['devDependencies', provider], '^5.2.0'); }, ); it.each([PackageManager.npm, PackageManager.pnpm])( @@ -243,8 +254,8 @@ describe('WebDriverIO migration floor', () => { overrides: { [provider]: `npm:${provider}@4.1.11` }, }); migrate(root, manager); - expect(read(root).overrides[provider]).toBeUndefined(); - expect(read(root).devDependencies[provider]).toBe('^6'); + expect(fixtureObject(read(root), 'overrides')[provider]).toBeUndefined(); + expect(read(root)).toHaveProperty(['devDependencies', provider], '^6'); }, ); it('removes scoped pnpm catalog overrides without downgrading a newer provider', () => { @@ -261,10 +272,18 @@ describe('WebDriverIO migration floor', () => { }, ); migrate(root); - expect(read(root, 'pnpm-workspace.yaml').catalogs.old[provider]).toBe('4.1.11'); - expect(read(root, 'pnpm-workspace.yaml').overrides[`app>${provider}`]).toBeUndefined(); - expect(read(root, 'pnpm-workspace.yaml').overrides[`unrelated>${provider}`]).toBe('4.0.0'); - expect(read(root).devDependencies[provider]).toBe('^6'); + expect(read(root, 'pnpm-workspace.yaml')).toHaveProperty( + ['catalogs', 'old', provider], + '4.1.11', + ); + expect( + fixtureObject(read(root, 'pnpm-workspace.yaml'), 'overrides')[`app>${provider}`], + ).toBeUndefined(); + expect(read(root, 'pnpm-workspace.yaml')).toHaveProperty( + ['overrides', `unrelated>${provider}`], + '4.0.0', + ); + expect(read(root)).toHaveProperty(['devDependencies', provider], '^6'); }); it('retains an override that shares the upgraded dependency catalog', () => { const root = project( @@ -277,8 +296,14 @@ describe('WebDriverIO migration floor', () => { }, ); migrate(root); - expect(read(root, 'pnpm-workspace.yaml').catalogs.browser[provider]).toBe('^5.0.0'); - expect(read(root, 'pnpm-workspace.yaml').overrides[provider]).toBe('catalog:browser'); + expect(read(root, 'pnpm-workspace.yaml')).toHaveProperty( + ['catalogs', 'browser', provider], + '^5.0.0', + ); + expect(read(root, 'pnpm-workspace.yaml')).toHaveProperty( + ['overrides', provider], + 'catalog:browser', + ); }); it.each(['latest', 'git+https://example.com/provider.git', 'catalog:missing', 'file:./missing'])( 'blocks unverified %s before any writes', @@ -319,6 +344,6 @@ describe('WebDriverIO migration floor', () => { ); const plan = migrate(root); expect(plan.changes).toEqual([]); - expect(read(root).devDependencies[provider]).toBeUndefined(); + expect(fixtureObject(read(root), 'devDependencies')[provider]).toBeUndefined(); }); }); diff --git a/packages/cli/src/migration/__tests__/vitest-v5.spec.ts b/packages/cli/src/migration/__tests__/vitest-v5.spec.ts index 7fc546f4be..4c14fd8b14 100644 --- a/packages/cli/src/migration/__tests__/vitest-v5.spec.ts +++ b/packages/cli/src/migration/__tests__/vitest-v5.spec.ts @@ -21,7 +21,7 @@ import { migrateVitestV5Config } from '../vitest-v5/config.ts'; import { migrateVitestV5Source } from '../vitest-v5/source.ts'; const v4 = { preserveV4: true, browser: true }; -const directories: string[] = []; +const directories: Array = []; afterEach(() => { for (const directory of directories.splice(0)) { fs.rmSync(directory, { recursive: true, force: true }); @@ -83,14 +83,11 @@ test('clock', () => { vi.setSystemTime(0); });`, }); const plan = planProject(root); expect(plan.projects[0].options.temporalPolyfill).toBe(true); - const expected = vitest.startsWith('4') - ? [ - expect.objectContaining({ - code: 'temporal-system-time', - file: path.join(root, 'clock.test.ts'), - }), - ] - : []; + const temporalFinding = expect.objectContaining({ + code: 'temporal-system-time', + file: path.join(root, 'clock.test.ts'), + }); + const expected = vitest.startsWith('4') ? [temporalFinding] : []; expect(plan.findings.filter(({ code }) => code === 'temporal-system-time')).toEqual(expected); applyVitestV5Migration(plan); expect( @@ -503,7 +500,7 @@ test('async', () => { expect(Promise.resolve(1)).resolves.toBe(1); });`, expect(plan.changes.find(({ file }) => file.endsWith('example.test.ts'))?.after).toContain( 'await expect(', ); - expect(() => applyVitestV5Migration(plan)).toThrow(); + expect(() => applyVitestV5Migration(plan)).toThrow(/Vitest/i); }); }); @@ -1629,12 +1626,12 @@ describe('Vitest v5 source migration', () => { ); expect(result.findings).toEqual([]); expect(source(result.content).content).toBe(result.content); - const calls: unknown[][] = []; + const calls: Array> = []; runInNewContext(result.content.replace(/^import[^;]+;/, ''), { - [api]: (...args: unknown[]) => calls.push(args), + [api]: (...args: Array) => calls.push(args), }); expect(calls[0]).toHaveLength(3); - expect(calls[0][1]).toEqual({ concurrent: false, timeout: 15000 }); + expect(calls[0][1]).toEqual({ concurrent: false, timeout: 15_000 }); } }); @@ -3267,16 +3264,17 @@ export default defineConfig(CONFIG);`, '.git': 'gitdir: external', '.gitignore': '.vitest/\n', 'packages/unit/package.json': JSON.stringify({ devDependencies: { vitest: '4.1.11' } }), - ...(nested ? { 'packages/unit/.git': 'gitdir: nested' } : {}), + ...(nested ? { 'packages/unit/.git': 'gitdir: nested' } : undefined), }); const directory = path.join(root, 'packages/unit'); const plan = planProject(directory); applyVitestV5Migration(plan); expect(finishVitestV5Migration(plan)).toEqual([]); expect(fs.existsSync(path.join(directory, '.gitignore'))).toBe(nested); - if (nested) { - expect(fs.readFileSync(path.join(directory, '.gitignore'), 'utf8')).toBe('.vitest/\n'); - } + const ignored = nested + ? fs.readFileSync(path.join(directory, '.gitignore'), 'utf8') + : undefined; + expect(ignored).toBe(nested ? '.vitest/\n' : undefined); }); it('preserves defaults in a config created by another migration step', () => { diff --git a/packages/cli/src/migration/ast-utils.ts b/packages/cli/src/migration/ast-utils.ts index fef4beef84..069445efc7 100644 --- a/packages/cli/src/migration/ast-utils.ts +++ b/packages/cli/src/migration/ast-utils.ts @@ -1,32 +1,41 @@ -import type * as t from '@oxc-project/types'; +import type { + BooleanLiteral, + Node, + ObjectExpression, + ObjectProperty, + Program, + RegExpLiteral, + Span, + StringLiteral, +} from '@oxc-project/types'; import { analyzeMigrationSource } from '../../binding/index.js'; interface SourceAnalysis { - ast: { node: t.Program }; - comments: t.Span[]; - bindings: Array<{ start: number; references: number[]; constant: boolean }>; + ast: { node: Program }; + comments: Array; + bindings: Array<{ start: number; references: Array; constant: boolean }>; } interface ParsedSource { - program: t.Program; + program: Program; bindings: SourceAnalysis['bindings']; - comments: t.Span[]; + comments: Array; } -export function isString(node: t.Node | null | undefined): node is t.StringLiteral { +export function isString(node: Node | null | undefined): node is StringLiteral { return node?.type === 'Literal' && typeof node.value === 'string'; } -export function isBoolean(node: t.Node | null | undefined): node is t.BooleanLiteral { +export function isBoolean(node: Node | null | undefined): node is BooleanLiteral { return node?.type === 'Literal' && typeof node.value === 'boolean'; } -export function isRegExp(node: t.Node | null | undefined): node is t.RegExpLiteral { +export function isRegExp(node: Node | null | undefined): node is RegExpLiteral { return node?.type === 'Literal' && 'regex' in node; } -export function propertyName(node: t.Node | null | undefined): string | undefined { +export function propertyName(node: Node | null | undefined): string | undefined { if (node?.type === 'Identifier') { return node.name; } @@ -36,7 +45,7 @@ export function propertyName(node: t.Node | null | undefined): string | undefine return undefined; } -export function memberName(node: t.Node | null | undefined): string | undefined { +export function memberName(node: Node | null | undefined): string | undefined { if (node?.type !== 'MemberExpression') { return undefined; } @@ -46,12 +55,9 @@ export function memberName(node: t.Node | null | undefined): string | undefined return propertyName(node.property); } -export function objectProperty( - object: t.ObjectExpression, - key: string, -): t.ObjectProperty | undefined { +export function objectProperty(object: ObjectExpression, key: string): ObjectProperty | undefined { return object.properties.find( - (prop): prop is t.ObjectProperty => + (prop): prop is ObjectProperty => prop.type === 'Property' && prop.kind === 'init' && !prop.computed && @@ -60,9 +66,9 @@ export function objectProperty( } export function staticObject( - node: t.Node | null | undefined, + node: Node | null | undefined, allowMethods = false, -): node is t.ObjectExpression { +): node is ObjectExpression { if (node?.type !== 'ObjectExpression') { return false; } @@ -87,7 +93,7 @@ export function staticObject( /** Compare data literals without evaluating config code or invoking getters. * Property order and spelling do not change the value of a plain config object. */ -export function sameStaticValue(left: t.Node, right: t.Node): boolean { +export function sameStaticValue(left: Node, right: Node): boolean { if (left.type === 'Literal' && right.type === 'Literal') { return ( !('regex' in left || 'regex' in right || 'bigint' in left || 'bigint' in right) && @@ -116,9 +122,12 @@ export function sameStaticValue(left: t.Node, right: t.Node): boolean { return ( left.properties.length === right.properties.length && left.properties.every((property) => { - const prop = property as t.ObjectProperty; - const other = objectProperty(right, propertyName(prop.key)!); - return !!other && sameStaticValue(prop.value, other.value); + if (property.type !== 'Property') { + return false; + } + const key = propertyName(property.key); + const other = key === undefined ? undefined : objectProperty(right, key); + return !!other && sameStaticValue(property.value, other.value); }) ); } @@ -128,9 +137,11 @@ export function sameStaticValue(left: t.Node, right: t.Node): boolean { export function parseSource(file: string, source: string): ParsedSource { // Native errors (including unsupported Flow) reach the existing preflight // diagnostic path, which preserves the original file for manual review. - const { ast, bindings, comments } = JSON.parse( + // The native migration binding serializes exactly SourceAnalysis. + // oxlint-disable-next-line typescript/no-unsafe-assignment + const { ast, bindings, comments }: SourceAnalysis = JSON.parse( analyzeMigrationSource(file, source), - ) as SourceAnalysis; + ); // Migration uses source spelling and regex metadata, not the JS-only fixes // that reconstruct RegExp/BigInt values in Oxc's serialized AST. return { program: ast.node, bindings, comments }; diff --git a/packages/cli/src/migration/bin.ts b/packages/cli/src/migration/bin.ts index 397c80aaa7..ff7c6b4cbf 100644 --- a/packages/cli/src/migration/bin.ts +++ b/packages/cli/src/migration/bin.ts @@ -2,16 +2,18 @@ import fs from 'node:fs'; import path from 'node:path'; import { isDeepStrictEqual, styleText } from 'node:util'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { + confirm as promptConfirm, + isCancel, + log as promptLog, + outro as promptOutro, + spinner as promptSpinner, +} from '@voidzero-dev/vite-plus-prompts'; import { satisfies } from 'verkit'; import { parseMigrateArgs } from '../../binding/index.js'; -import { - PackageManager, - type WorkspaceInfo, - type WorkspaceInfoOptional, - type WorkspacePackage, -} from '../types/index.ts'; +import type { WorkspaceInfo, WorkspaceInfoOptional, WorkspacePackage } from '../types/index.ts'; +import { PackageManager } from '../types/index.ts'; import { writeAgentInstructions } from '../utils/agent.ts'; import { unwrapCliParseOutcome } from '../utils/cli-parse.ts'; import { isForceOverrideMode, SETUP_VP_VERSION, VITE_PLUS_VERSION } from '../utils/constants.ts'; @@ -42,6 +44,12 @@ import { checkRolldownCompatibility } from './compat/runner.ts'; import { detectMigrationWarnings } from './detector.ts'; import { canFormatWithOxfmt, collectChangedFormatPaths, formatMigratedProject } from './format.ts'; import { handleInstallResult } from './install-result.ts'; +import type { + Framework, + NodeVersionManagerDetection, + VitestV5MigrationPlan, + RetainedImportDependencies, +} from './migrator.ts'; import { addFrameworkShim, applyVitestV5Migration, @@ -101,20 +109,14 @@ import { warnPackageLevelPrettier, warnUnresolvedImportRuleConfig, vitestV5NeedsMigration, - type Framework, - type NodeVersionManagerDetection, - type VitestV5MigrationPlan, - type RetainedImportDependencies, } from './migrator.ts'; import { prepareNpmViteAliasReinstall } from './npm-reinstall.ts'; import type { MigrationOptions } from './options.ts'; import { addVitePlusRenovatePreset, findRenovateConfigToUpdate } from './renovate.ts'; -import { addMigrationWarning, createMigrationReport, type MigrationReport } from './report.ts'; -import { - collectMigrationSetupPlan, - collectTsupMigrationDecision, - type MigrationSetupPlan, -} from './setup-plan.ts'; +import type { MigrationReport } from './report.ts'; +import { addMigrationWarning, createMigrationReport } from './report.ts'; +import type { MigrationSetupPlan } from './setup-plan.ts'; +import { collectMigrationSetupPlan, collectTsupMigrationDecision } from './setup-plan.ts'; async function confirmNodeVersionFileMigration( interactive: boolean, @@ -126,11 +128,11 @@ async function confirmNodeVersionFileMigration( const message = confirmMessageByFile[detection.file]; if (interactive) { - const confirmed = await prompts.confirm({ + const confirmed = await promptConfirm({ message, initialValue: true, }); - if (prompts.isCancel(confirmed)) { + if (isCancel(confirmed)) { cancelAndExit(); } return confirmed; @@ -142,7 +144,7 @@ async function confirmFrameworkShim(framework: Framework, interactive: boolean): const frameworkNames: Record = { vue: 'Vue', astro: 'Astro' }; const name = frameworkNames[framework]; if (interactive) { - const confirmed = await prompts.confirm({ + const confirmed = await promptConfirm({ message: `Add TypeScript shim for ${name} component files (*.${framework})?\n ` + styleText( @@ -151,7 +153,7 @@ async function confirmFrameworkShim(framework: Framework, interactive: boolean): ), initialValue: true, }); - if (prompts.isCancel(confirmed)) { + if (isCancel(confirmed)) { cancelAndExit(); } return confirmed; @@ -167,14 +169,14 @@ async function confirmRenovatePreset( if (!configPath || !interactive) { return configPath; } - const confirmed = await prompts.confirm({ + const confirmed = await promptConfirm({ message: 'Group Vite+ and Vitest updates in Renovate?\n ' + muted(`Adds group:vitePlus to ${displayRelative(configPath, rootDir)}.`), initialValue: true, testId: 'renovate', }); - if (prompts.isCancel(confirmed)) { + if (isCancel(confirmed)) { cancelAndExit(); } return confirmed ? configPath : undefined; @@ -195,7 +197,7 @@ async function confirmYarnNodeModulesMode( return false; } - prompts.log.warn(`⚠ Vite+ does not currently support Yarn Plug'n'Play (PnP).`); + promptLog.warn(`⚠ Vite+ does not currently support Yarn Plug'n'Play (PnP).`); if (pnp.source === 'environment') { cancelAndExit( 'YARN_NODE_LINKER=pnp overrides project configuration. Set it to node-modules or unset it, then re-run `vp migrate`.', @@ -204,11 +206,11 @@ async function confirmYarnNodeModulesMode( } if (interactive) { - const confirmed = await prompts.confirm({ + const confirmed = await promptConfirm({ message: 'Switch this project to Yarn node-modules mode and continue?', initialValue: true, }); - if (prompts.isCancel(confirmed)) { + if (isCancel(confirmed)) { cancelAndExit(); } if (!confirmed) { @@ -220,16 +222,16 @@ async function confirmYarnNodeModulesMode( } async function fixBaseUrlForWorkspace( - workspaceInfo: { rootDir: string; packages?: WorkspacePackage[] }, + workspaceInfo: { rootDir: string; packages?: Array }, fixBaseUrl: boolean, updateProgress?: (message: string) => void, report?: MigrationReport, -): Promise { +): Promise> { if (!fixBaseUrl) { return []; } - const fixedProjectPaths: string[] = []; + const fixedProjectPaths: Array = []; for (const projectPath of getWorkspaceProjectPaths(workspaceInfo)) { if (!hasBaseUrlInTsconfig(projectPath)) { continue; @@ -262,7 +264,7 @@ async function fixBaseUrlForWorkspace( function hasBaseUrlInWorkspace(workspaceInfo: { rootDir: string; - packages?: WorkspacePackage[]; + packages?: Array; }): boolean { return getWorkspaceProjectPaths(workspaceInfo).some(hasBaseUrlInTsconfig); } @@ -273,7 +275,7 @@ function hasBaseUrlInWorkspace(workspaceInfo: { // the running counter + package path keeps the spinner moving instead of // stalling on a stale message. async function checkWorkspaceRolldownCompatibility( - workspaceInfo: { rootDir: string; packages?: WorkspacePackage[] }, + workspaceInfo: { rootDir: string; packages?: Array }, report: MigrationReport, updateProgress?: (message: string) => void, ): Promise { @@ -319,10 +321,13 @@ interface MigrationPlan extends MigrationSetupPlan { fixBaseUrl: boolean; migrateNodeVersionFile: boolean; nodeVersionDetection?: NodeVersionManagerDetection; - frameworkShimFrameworks?: Framework[]; + frameworkShimFrameworks?: Array; } -function getFrameworkShimCandidates(rootDir: string, packages?: WorkspacePackage[]): Framework[] { +function getFrameworkShimCandidates( + rootDir: string, + packages?: Array, +): Array { const allDetectedFrameworks = new Set(detectFramework(rootDir)); for (const pkg of packages ?? []) { for (const framework of detectFramework(path.join(rootDir, pkg.path))) { @@ -344,9 +349,9 @@ function getFrameworkShimCandidates(rootDir: string, packages?: WorkspacePackage async function collectFrameworkShimFrameworks( rootDir: string, options: MigrationOptions, - packages?: WorkspacePackage[], -): Promise { - const frameworkShimFrameworks: Framework[] = []; + packages?: Array, +): Promise | undefined> { + const frameworkShimFrameworks: Array = []; for (const framework of getFrameworkShimCandidates(rootDir, packages)) { const addShim = await confirmFrameworkShim(framework, options.interactive); if (addShim) { @@ -358,8 +363,8 @@ async function collectFrameworkShimFrameworks( function addFrameworkShimsForWorkspace( rootDir: string, - frameworks: Framework[] | undefined, - packages: WorkspacePackage[] | undefined, + frameworks: Array | undefined, + packages: Array | undefined, report: MigrationReport, updateMigrationProgress: (message: string) => void, ): boolean { @@ -385,9 +390,9 @@ function addFrameworkShimsForWorkspace( return changed; } -function hasEnabledOption(value: string | string[] | false | undefined): boolean { +function hasEnabledOption(value: string | Array | false | undefined): boolean { if (Array.isArray(value)) { - return value.some((item) => Boolean(item)); + return value.some(Boolean); } return value !== undefined && value !== false && value !== ''; } @@ -590,7 +595,7 @@ function showMigrationSummary(options: { ); } if (configUpdates > 0 || report.rewrittenImportFileCount > 0) { - const parts: string[] = []; + const parts: Array = []; if (configUpdates > 0) { parts.push( `${configUpdates} ${configUpdates === 1 ? 'config update' : 'config updates'} applied`, @@ -674,7 +679,7 @@ function showMigrationSummary(options: { } } -function showMigrationWarnings(warnings: readonly string[]): void { +function showMigrationWarnings(warnings: ReadonlyArray): void { if (warnings.length === 0) { return; } @@ -721,7 +726,7 @@ async function downloadSupportedPackageManager(options: { satisfies(downloadResult.version, '< 9.5.0') ) { failMigrationProgress('Migration failed'); - prompts.log.error( + promptLog.error( `✘ pnpm@${downloadResult.version} is not supported by auto migration, please upgrade pnpm to >=9.5.0 first`, ); cancelAndExit('Vite+ cannot automatically migrate this project yet.', 1); @@ -730,7 +735,7 @@ async function downloadSupportedPackageManager(options: { satisfies(downloadResult.version, '< 8.3.0') ) { failMigrationProgress('Migration failed'); - prompts.log.error( + promptLog.error( `✘ npm@${downloadResult.version} is not supported by auto migration, please upgrade npm to >=8.3.0 first`, ); cancelAndExit('Vite+ cannot automatically migrate this project yet.', 1); @@ -751,7 +756,7 @@ function completeVitestV5Migration(plan: VitestV5MigrationPlan, report: Migratio function applyRefreshedVitestV5Migration(plan: VitestV5MigrationPlan): VitestV5MigrationPlan { const refreshed = refreshVitestV5Migration(plan); if (refreshed.findings.some((finding) => finding.severity === 'block')) { - prompts.log.warn(formatVitestV5Findings(refreshed)); + promptLog.warn(formatVitestV5Findings(refreshed)); cancelAndExit( 'Resolve the blocking Vitest v5 findings, then re-run `vp migrate`. Earlier setup steps may have changed project files; Vitest v5 edits were not applied.', 1, @@ -777,7 +782,7 @@ async function executeMigrationPlan( report.warnings.push( ...detectMigrationWarnings(workspaceInfoOptional.rootDir, workspaceInfoOptional.packages), ); - const migrationProgress = interactive ? prompts.spinner({ indicator: 'timer' }) : undefined; + const migrationProgress = interactive ? promptSpinner({ indicator: 'timer' }) : undefined; let migrationProgressStarted = false; const updateMigrationProgress = (message: string) => { if (!migrationProgress) { @@ -825,7 +830,7 @@ async function executeMigrationPlan( updateMigrationProgress('Configuring Yarn node-modules mode'); report.packageManagerBootstrapConfigured = configureYarnNodeModulesMode(workspaceInfo.rootDir); if (report.packageManagerBootstrapConfigured) { - prompts.log.success('✔ Switched Yarn to node-modules mode'); + promptLog.success('✔ Switched Yarn to node-modules mode'); } } @@ -1102,7 +1107,7 @@ async function main() { let vitestV5Plan = planVitestV5Migration(workspaceInfoOptional); const vitestV5Preflight = formatVitestV5Findings(vitestV5Plan); if (vitestV5Plan.findings.some((finding) => finding.severity === 'block')) { - prompts.log.warn(vitestV5Preflight); + promptLog.warn(vitestV5Preflight); cancelAndExit( 'Resolve the blocking Vitest v5 findings, then re-run `vp migrate`. No project files were changed.', 1, @@ -1115,7 +1120,7 @@ async function main() { | (PackageDependencies & { packageManager?: unknown; devEngines?: unknown }) | null; if (workspaceInfoOptional.packageManager && !hasPackageManagerDeclaration(rootPkg)) { - prompts.log.warn( + promptLog.warn( `No package manager is declared in package.json; using ${workspaceInfoOptional.packageManager} for this migration without adding a pin. Run \`vp env pin\` to declare it explicitly.`, ); } @@ -1146,7 +1151,7 @@ async function main() { // report until then so review-only items do not force an up-to-date project // through dependency reconciliation on every run. const migrationProgress = options.interactive - ? prompts.spinner({ indicator: 'timer' }) + ? promptSpinner({ indicator: 'timer' }) : undefined; let migrationProgressStarted = false; const updateMigrationProgress = (message: string) => { @@ -1326,15 +1331,15 @@ async function main() { ) { showMigrationWarnings(migrationWarnings); if (vitestV5Preflight) { - prompts.log.warn(vitestV5Preflight); + promptLog.warn(vitestV5Preflight); } for (const warning of coreMigrationResult.taskCacheWarnings) { - prompts.log.warn(warning); + promptLog.warn(warning); } if (skippedSetupCandidates) { log(FULL_MIGRATION_HINT); } - prompts.outro(`This project is already using Vite+! ${accent('Happy coding!')}`); + promptOutro(`This project is already using Vite+! ${accent('Happy coding!')}`); return; } report.warnings.push(...migrationWarnings); @@ -1573,7 +1578,7 @@ async function main() { updateMigrationProgress('Configuring Yarn node-modules mode'); const yarnPnpConverted = configureYarnNodeModulesMode(workspaceInfoOptional.rootDir); if (yarnPnpConverted) { - prompts.log.success('✔ Switched Yarn to node-modules mode'); + promptLog.success('✔ Switched Yarn to node-modules mode'); report.packageManagerBootstrapConfigured = true; didMigrate = true; needsInstall = true; @@ -1803,7 +1808,7 @@ async function main() { if (skippedSetupCandidates) { log(FULL_MIGRATION_HINT); } - prompts.outro(`This project is already using Vite+! ${accent('Happy coding!')}`); + promptOutro(`This project is already using Vite+! ${accent('Happy coding!')}`); } return; } @@ -1829,8 +1834,10 @@ async function main() { }); } -main().catch((err) => { - prompts.log.error(err.message); - console.error(err); +try { + await main(); +} catch (error) { + promptLog.error(error instanceof Error ? error.message : String(error)); + console.error(error); process.exit(1); -}); +} diff --git a/packages/cli/src/migration/compat/manual-chunks.ts b/packages/cli/src/migration/compat/manual-chunks.ts index cd275e1ce5..6c03fc667d 100644 --- a/packages/cli/src/migration/compat/manual-chunks.ts +++ b/packages/cli/src/migration/compat/manual-chunks.ts @@ -1,12 +1,20 @@ -import { addMigrationWarning, type MigrationReport } from '../report.ts'; +import type { MigrationReport } from '../report.ts'; +import { addMigrationWarning } from '../report.ts'; /** * Check for Rolldown-incompatible manualChunks config patterns. */ export function checkManualChunksCompat(output: unknown, report: MigrationReport): void { - const outputs = Array.isArray(output) ? output : output ? [output] : []; + const outputs: Array = Array.isArray(output) ? output : output ? [output] : []; for (const out of outputs) { - if (out.manualChunks != null && typeof out.manualChunks !== 'function') { + if ( + out !== null && + typeof out === 'object' && + 'manualChunks' in out && + out.manualChunks !== undefined && + out.manualChunks !== null && + typeof out.manualChunks !== 'function' + ) { addMigrationWarning( report, 'Object-form `build.rollupOptions.output.manualChunks` is not supported by Rolldown. ' + diff --git a/packages/cli/src/migration/compat/runner.ts b/packages/cli/src/migration/compat/runner.ts index 006fd4fe44..4233babf0b 100644 --- a/packages/cli/src/migration/compat/runner.ts +++ b/packages/cli/src/migration/compat/runner.ts @@ -4,7 +4,10 @@ import { fileURLToPath } from 'node:url'; import type { OxlintConfig } from 'oxlint'; import { runCommandSilently } from '../../utils/command.ts'; -import { addMigrationWarning, type MigrationReport } from '../report.ts'; +import { parseJsonValue, isObjectValue } from '../../utils/json-value.ts'; +import type { JsonObject } from '../../utils/json.ts'; +import type { MigrationReport } from '../report.ts'; +import { addMigrationWarning } from '../report.ts'; import { LINT_CONFIG_RESULT_PREFIX, ROLLDOWN_COMPAT_RESULT_PREFIX } from './protocol.ts'; export { ROLLDOWN_COMPAT_RESULT_PREFIX }; @@ -29,7 +32,7 @@ function resolveWorkerPath(): string { // A project's config can crash or block. Both probes use the same child process // settings and timeout, and their callers decide how to handle failure. -async function runConfigWorker(rootDir: string, ...args: string[]): Promise { +async function runConfigWorker(rootDir: string, ...args: Array): Promise { const { exitCode, stdout } = await runCommandSilently({ command: process.execPath, args: [resolveWorkerPath(), rootDir, ...args], @@ -43,7 +46,7 @@ async function runConfigWorker(rootDir: string, ...args: string[]): Promise | undefined { +function parseWorkerResult(stdout: Buffer, prefix: string): JsonObject | undefined { const output = stdout.toString(); const markerIndex = output.lastIndexOf(prefix); if (markerIndex === -1) { @@ -55,8 +58,8 @@ function parseWorkerResult(stdout: Buffer, prefix: string): Record }, +): void { writeSync(process.stdout.fd, `${prefix}${JSON.stringify(result)}\n`); } @@ -55,4 +58,8 @@ async function main(): Promise { // Exit even if project plugins left active handles. On failure, the parent // detects the missing result and applies the policy for the requested probe. -void main().finally(() => process.exit(0)); +try { + await main(); +} finally { + process.exit(0); +} diff --git a/packages/cli/src/migration/detector.ts b/packages/cli/src/migration/detector.ts index e4065fd1d9..9cd04505c6 100644 --- a/packages/cli/src/migration/detector.ts +++ b/packages/cli/src/migration/detector.ts @@ -3,6 +3,9 @@ import path from 'node:path'; import type { WorkspacePackage } from '../types/index.ts'; import { VITE_CONFIG_FILES } from '../utils/constants.ts'; +import type { JsonObject } from '../utils/json.ts'; +import { parseJsonValue, isJsonObject } from '../utils/json.ts'; +import { readJsonFile } from '../utils/json.ts'; export interface ConfigFiles { viteConfig?: string; @@ -97,7 +100,7 @@ const MIGRATION_WARNING_DETECTIONS = [ }, ] as const; -function hasDependency(packageJson: Record, packageName: string): boolean { +function hasDependency(packageJson: JsonObject, packageName: string): boolean { return ['dependencies', 'devDependencies', 'optionalDependencies'].some((field) => { const dependencies = packageJson[field]; return typeof dependencies === 'object' && dependencies !== null && packageName in dependencies; @@ -109,14 +112,14 @@ function hasDependency(packageJson: Record, packageName: string */ export function detectMigrationWarnings( projectPath: string, - packages: readonly WorkspacePackage[] = [], -): string[] { + packages: ReadonlyArray = [], +): Array { const projectPaths = [ projectPath, ...packages.map((workspacePackage) => path.join(projectPath, workspacePackage.path)), ]; const detected = new Set(); - let rootPackageJson: Record | undefined; + let rootPackageJson: JsonObject | undefined; for (const currentPath of projectPaths) { const packageJsonPath = path.join(currentPath, 'package.json'); @@ -124,9 +127,9 @@ export function detectMigrationWarnings( continue; } - let packageJson: Record; + let packageJson: JsonObject; try { - packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as Record; + packageJson = readJsonFile(packageJsonPath); } catch { continue; } @@ -155,8 +158,8 @@ export function detectMigrationWarnings( } } - return MIGRATION_WARNING_DETECTIONS.map(({ warning }) => warning).filter((warning) => - detected.has(warning), + return MIGRATION_WARNING_DETECTIONS.flatMap(({ warning }) => + detected.has(warning) ? [warning] : [], ); } @@ -294,7 +297,8 @@ export function detectConfigs(projectPath: string): ConfigFiles { if (fs.existsSync(packageJsonPath)) { try { const content = fs.readFileSync(packageJsonPath, 'utf8'); - const pkg = JSON.parse(content); + const parsed = parseJsonValue(content); + const pkg = isJsonObject(parsed) ? parsed : {}; if (!configs.prettierConfig && pkg.prettier) { configs.prettierConfig = PRETTIER_PACKAGE_JSON_CONFIG; @@ -304,7 +308,7 @@ export function detectConfigs(projectPath: string): ConfigFiles { configs.tsupConfig = TSUP_PACKAGE_JSON_CONFIG; } - const voltaNode = pkg.volta?.node; + const voltaNode = isJsonObject(pkg.volta) ? pkg.volta.node : undefined; if (typeof voltaNode === 'string') { configs.voltaNode = voltaNode; } diff --git a/packages/cli/src/migration/format.ts b/packages/cli/src/migration/format.ts index 4b3dd806fb..962919ac67 100644 --- a/packages/cli/src/migration/format.ts +++ b/packages/cli/src/migration/format.ts @@ -2,21 +2,23 @@ import fs from 'node:fs'; import path from 'node:path'; import { runCommandSilently } from '../utils/command.ts'; -import { type CommandRunSummary, runViteFmt } from '../utils/prompts.ts'; +import type { CommandRunSummary } from '../utils/prompts.ts'; +import { runViteFmt } from '../utils/prompts.ts'; import { STANDALONE_RENOVATE_CONFIG_FILES } from './renovate.ts'; -import { addMigrationWarning, type MigrationReport } from './report.ts'; +import type { MigrationReport } from './report.ts'; +import { addMigrationWarning } from './report.ts'; -type FormatRunner = ( +export type FormatRunner = ( cwd: string, interactive?: boolean, - paths?: string[], - options?: { silent?: boolean; command?: string; commandArgs?: string[] }, + paths?: Array, + options?: { silent?: boolean; command?: string; commandArgs?: Array }, ) => Promise; type FormatPathCollector = ( cwd: string, excludedPaths?: ReadonlySet, -) => Promise; +) => Promise | undefined>; interface FormatMigratedProjectOptions { format?: FormatRunner; @@ -35,9 +37,9 @@ const FORMAT_FAILURE_MESSAGE = // command line at 32,767 characters (shared with the node path and CLI entry). const MAX_FORMAT_ARG_BYTES = process.platform === 'win32' ? 24_000 : 100_000; -function chunkPathsByArgLength(paths: string[]): string[][] { - const chunks: string[][] = []; - let current: string[] = []; +function chunkPathsByArgLength(paths: Array): Array> { + const chunks: Array> = []; + let current: Array = []; let currentBytes = 0; for (const filePath of paths) { const bytes = Buffer.byteLength(filePath) + 1; // +1 for the argument separator @@ -55,7 +57,7 @@ function chunkPathsByArgLength(paths: string[]): string[][] { return chunks; } -function parseNullDelimitedPaths(output: Buffer): string[] { +function parseNullDelimitedPaths(output: Buffer): Array { return output.toString().split('\0').filter(Boolean); } @@ -68,7 +70,7 @@ function isExistingFile(projectRoot: string, relativePath: string): boolean { } } -function wholeProjectFormatPaths(projectRoot: string): string[] | undefined { +function wholeProjectFormatPaths(projectRoot: string): Array | undefined { // Anchor the exclusions so nested files with the same name still get formatted. const exclusions = STANDALONE_RENOVATE_CONFIG_FILES.filter((file) => isExistingFile(projectRoot, file), @@ -87,9 +89,9 @@ function wholeProjectFormatPaths(projectRoot: string): string[] | undefined { export async function collectChangedFormatPaths( projectRoot: string, excludedPaths?: ReadonlySet, -): Promise { +): Promise | undefined> { try { - const git = (args: string[]) => + const git = (args: Array) => runCommandSilently({ command: 'git', args, cwd: projectRoot, envs: process.env }); // Only fall back to whole-project formatting when the project is genuinely @@ -184,7 +186,7 @@ export async function formatMigratedProject( silent: false, ...(cliEntry ? { command: process.execPath, commandArgs: [...process.execArgv, cliEntry] } - : {}), + : undefined), }; // `undefined` means "format the whole project" (single invocation); a path // list is batched so a huge monorepo cannot overflow the command line. diff --git a/packages/cli/src/migration/migrator/catalog.ts b/packages/cli/src/migration/migrator/catalog.ts index e6e703e453..a50edc4c3f 100644 --- a/packages/cli/src/migration/migrator/catalog.ts +++ b/packages/cli/src/migration/migrator/catalog.ts @@ -3,9 +3,11 @@ import path from 'node:path'; import tsrsPkg from 'tsrs/package.json' with { type: 'json' }; import { coerce, isLessThan } from 'verkit'; -import { Scalar, YAMLMap, YAMLSeq } from 'yaml'; +import { isMap, isScalar, isSeq, Scalar, YAMLMap, YAMLSeq } from 'yaml'; -import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; +import type { WorkspacePackage } from '../../types/index.ts'; +import { PackageManager } from '../../types/index.ts'; +import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; import { bunSupportsMergedDefaultCatalogs, createCatalogDependencyResolverFromCatalogs, @@ -14,7 +16,6 @@ import { readBunCatalogDependencyResolver, selectPreferredCatalogSpec, versionAtLeast, - type CatalogDependencyResolver, } from '../../utils/catalog.ts'; import { VITEST_AGE_GATE_EXEMPT_PACKAGES, @@ -24,9 +25,15 @@ import { VITE_PLUS_VERSION, isForceOverrideMode, } from '../../utils/constants.ts'; +import { isObjectValue } from '../../utils/json-value.ts'; +import type { JsonObject, JsonValue } from '../../utils/json.ts'; +import { isJsonObject } from '../../utils/json.ts'; import { editJsonFile, readJsonFile } from '../../utils/json.ts'; -import { type NpmWorkspaces } from '../../utils/workspace.ts'; -import { editYamlFile, readYamlFile, scalarString, type YamlDocument } from '../../utils/yaml.ts'; +import type { NpmWorkspaces } from '../../utils/workspace.ts'; +import type { YamlMapping } from '../../utils/yaml-value.ts'; +import { isYamlMapping } from '../../utils/yaml-value.ts'; +import type { YamlDocument } from '../../utils/yaml.ts'; +import { editYamlFile, readYamlFile, scalarString } from '../../utils/yaml.ts'; import { dropRemovePackageOverrideKeys, ensurePackageJsonOverrides, @@ -46,22 +53,25 @@ import { pnpmPeerDependencyRuleKeys, workspaceUsesWebdriverioProvider, } from '../migrator.ts'; -import { type MigrationReport } from '../report.ts'; +import type { MigrationReport } from '../report.ts'; +import type { + PreparedOxlintConfigs, + RetainedImportDependencies, + PackageJsonDependencyField, + PnpmPackageJsonSettings, +} from './shared.ts'; +import { lookupSetting } from './shared.ts'; import { - type PreparedOxlintConfigs, LEGACY_WRAPPER_FALLBACK_VERSIONS, PROVIDER_OVERRIDE_DROP_NAMES, OPT_IN_BROWSER_PROVIDERS, bundledPackagesToRemove, - type RetainedImportDependencies, VITEST_IS_MANAGED_OVERRIDE, isPlainRecord, pinnedPackageManagerVersion, pnpmOverrideKey, readPackageJsonIfExists, vitePeerDependencyRuleRequired, - type PackageJsonDependencyField, - type PnpmPackageJsonSettings, } from './shared.ts'; // Transitive packages with postinstall scripts that vite-plus's deps drag in @@ -71,7 +81,7 @@ import { // webdriverio), allow when the user actually depends on webdriverio. const BROWSER_PROVIDER_POSTINSTALL_PACKAGES = ['edgedriver', 'geckodriver'] as const; -const PUBLIC_PEER_DEPENDENCY_FALLBACKS: Record = { +const PUBLIC_PEER_DEPENDENCY_FALLBACKS = { vite: '*', vitest: '*', }; @@ -101,7 +111,7 @@ const PNPM_MINIMUM_RELEASE_AGE_EXCLUDES = [ // https://github.com/oxc-project/tsrs/issues/945 const PNPM_TSRS_TRUST_POLICY_EXCLUDE = `tsrs@${tsrsPkg.version}`; -function hasTsrsTrustPolicyException(excludes: readonly unknown[]): boolean { +function hasTsrsTrustPolicyException(excludes: ReadonlyArray): boolean { return excludes.includes('tsrs') || excludes.includes(PNPM_TSRS_TRUST_POLICY_EXCLUDE); } @@ -175,7 +185,7 @@ const BUN_TOP_LEVEL_CATALOG_MIN_VERSION = '1.2.21'; // resolve", so the toolchain edges must stay concrete. export function bunSupportsCatalog(pkg: { workspaces?: NpmWorkspaces }, version: string): boolean { const { workspaces } = pkg; - if (workspaces == null) { + if (workspaces === undefined || workspaces === null) { return false; } const writesNestedCatalog = getBunCatalogConfig(pkg) !== pkg; @@ -257,11 +267,11 @@ export function pnpmPackageJsonSettingsPending(pkg: { pnpm?: PnpmPackageJsonSett export function takePnpmWorkspaceSettings(pkg: { pnpm?: PnpmPackageJsonSettings; -}): Record | undefined { +}): JsonObject | undefined { if (!pkg.pnpm) { return undefined; } - const settings: Record = {}; + const settings: JsonObject = {}; for (const key of PNPM_WORKSPACE_SETTING_KEYS) { if (!Object.hasOwn(pkg.pnpm, key)) { continue; @@ -281,10 +291,11 @@ export function takePnpmWorkspaceSettings(pkg: { * while objects merge recursively and arrays retain unique entries from both * locations. */ -function mergePnpmWorkspaceSetting(existing: unknown, incoming: unknown): unknown { +function mergePnpmWorkspaceSetting(existing: unknown, incoming: JsonValue | undefined) { if (Array.isArray(existing) && Array.isArray(incoming)) { const seen = new Set(); - return [...existing, ...incoming].filter((value) => { + const current: Array = existing; + return [...current, ...incoming].filter((value) => { const key = JSON.stringify(value); if (seen.has(key)) { return false; @@ -293,8 +304,8 @@ function mergePnpmWorkspaceSetting(existing: unknown, incoming: unknown): unknow return true; }); } - if (isPlainRecord(existing) && isPlainRecord(incoming)) { - const merged: Record = { ...existing }; + if (isYamlMapping(existing) && isPlainRecord(incoming)) { + const merged: YamlMapping = { ...existing }; for (const [key, value] of Object.entries(incoming)) { merged[key] = Object.hasOwn(existing, key) ? mergePnpmWorkspaceSetting(existing[key], value) @@ -307,7 +318,7 @@ function mergePnpmWorkspaceSetting(existing: unknown, incoming: unknown): unknow export function migratePnpmSettingsToWorkspaceYaml( projectPath: string, - settings: Record | undefined, + settings: JsonObject | undefined, ): void { if (!settings || Object.keys(settings).length === 0) { return; @@ -317,7 +328,8 @@ export function migratePnpmSettingsToWorkspaceYaml( fs.writeFileSync(pnpmWorkspaceYamlPath, ''); } editYamlFile(pnpmWorkspaceYamlPath, (doc) => { - const workspace = (doc.toJS() ?? {}) as Record; + const output: unknown = doc.toJS(); + const workspace = isYamlMapping(output) ? output : {}; for (const [key, value] of Object.entries(settings)) { // package.json#pnpm was the effective source before migration. Preserve // that precedence at conflicting leaves while retaining workspace-only @@ -378,12 +390,11 @@ export function rewritePnpmWorkspaceYaml( // non-vite-plus parent (e.g. `some-app>@vitest/browser-playwright`) only // constrains that parent's subtree, so it is preserved — see // `shouldDropProviderOverrideKey`. - if (overrides instanceof YAMLMap) { + if (isMap(overrides)) { const keysSnapshot = overrides.items.map((item) => item.key); for (const keyNode of keysSnapshot) { - const rawKey = - keyNode instanceof Scalar ? String(keyNode.value ?? '') : String(keyNode ?? ''); - if (shouldDropProviderOverrideKey(rawKey)) { + const rawKey = isScalar(keyNode) ? keyNode.value : keyNode; + if (typeof rawKey === 'string' && shouldDropProviderOverrideKey(rawKey)) { overrides.delete(keyNode); } } @@ -411,7 +422,7 @@ export function rewritePnpmWorkspaceYaml( : getCatalogDependencySpec(currentVersion, managed[key], true, { preferredCatalogSpec, }); - if (overrides instanceof YAMLMap) { + if (isMap(overrides)) { overrides.delete(key); } doc.setIn(['overrides', scalarString(overrideKey)], scalarString(version)); @@ -421,25 +432,26 @@ export function rewritePnpmWorkspaceYaml( // YAMLMap.delete splices `.items`, so iterating the live array would shift // the next entry into the current slot and skip it (two ADJACENT `...>vite` // selectors would leave the second behind). - const updatedOverrides = doc.getIn(['overrides']) as YAMLMap, Scalar>; - const updatedOverrideKeys = updatedOverrides.items.map((item) => item.key); - for (const key of updatedOverrideKeys) { - if (key.value.includes('>')) { - const splits = key.value.split('>'); - if (splits.at(-1)!.trim() === 'vite') { - updatedOverrides.delete(key); + const updatedOverrides = doc.getIn(['overrides']); + if (isMap(updatedOverrides)) { + const updatedOverrideKeys = updatedOverrides.items.map((item) => item.key); + for (const key of updatedOverrideKeys) { + if (isScalar(key) && typeof key.value === 'string' && key.value.includes('>')) { + const splits = key.value.split('>'); + if (splits.at(-1)?.trim() === 'vite') { + updatedOverrides.delete(key); + } } } } - // peerDependencyRules.allowAny // `getIn` unwraps scalar values, so a malformed scalar-valued `allowAny:` // (`allowAny: react`) arrives as a string here; coerce it into a sequence // entry instead of crashing on `.items` below. const allowAnyNode = doc.getIn(['peerDependencyRules', 'allowAny']); - let allowAny: YAMLSeq>; - if (allowAnyNode instanceof YAMLSeq) { - allowAny = allowAnyNode as YAMLSeq>; + let allowAny: YAMLSeq; + if (isSeq(allowAnyNode)) { + allowAny = allowAnyNode; } else { allowAny = new YAMLSeq>(); if (typeof allowAnyNode === 'string' && allowAnyNode.length > 0) { @@ -449,8 +461,10 @@ export function rewritePnpmWorkspaceYaml( // Drop lingering managed `vitest` and stale `vite` entries. const peerRuleKeys = pnpmPeerDependencyRuleKeys(usesVitest, pnpmVersion); const stalePeerRuleKeys = peerRuleKeys.stale; - allowAny.items = allowAny.items.filter((n) => !stalePeerRuleKeys.includes(n.value)); - const existing = new Set(allowAny.items.map((n) => n.value)); + allowAny.items = allowAny.items.filter( + (n) => !(isScalar(n) && typeof n.value === 'string' && stalePeerRuleKeys.includes(n.value)), + ); + const existing = yamlSequenceValues(allowAny); for (const key of peerRuleKeys.managed) { if (!existing.has(key)) { allowAny.add(scalarString(key)); @@ -462,9 +476,9 @@ export function rewritePnpmWorkspaceYaml( // Same guard as above: a malformed non-map `allowedVersions:` value (pnpm // expects a map, so it carries no usable data) is replaced outright. const allowedVersionsNode = doc.getIn(['peerDependencyRules', 'allowedVersions']); - let allowedVersions: YAMLMap, Scalar>; - if (allowedVersionsNode instanceof YAMLMap) { - allowedVersions = allowedVersionsNode as YAMLMap, Scalar>; + let allowedVersions: YAMLMap; + if (isMap(allowedVersionsNode)) { + allowedVersions = allowedVersionsNode; } else { allowedVersions = new YAMLMap, Scalar>(); } @@ -482,13 +496,12 @@ export function rewritePnpmWorkspaceYaml( // minimumReleaseAgeExclude: exempt the Vite+-managed packages (vite-plus, // @voidzero-dev/*, the ox* family, and the vitest family) from the age gate. if (doc.has('minimumReleaseAge')) { - let minimumReleaseAgeExclude = doc.getIn(['minimumReleaseAgeExclude']) as YAMLSeq< - Scalar - >; - if (!minimumReleaseAgeExclude) { - minimumReleaseAgeExclude = new YAMLSeq(); + const existingExclude = doc.getIn(['minimumReleaseAgeExclude']); + if (existingExclude && !isSeq(existingExclude)) { + throw new Error('pnpm-workspace.yaml: minimumReleaseAgeExclude must be a sequence'); } - const existing = new Set(minimumReleaseAgeExclude.items.map((n) => n.value)); + const minimumReleaseAgeExclude = isSeq(existingExclude) ? existingExclude : new YAMLSeq(); + const existing = yamlSequenceValues(minimumReleaseAgeExclude); for (const exclude of PNPM_MINIMUM_RELEASE_AGE_EXCLUDES) { if (!existing.has(exclude)) { minimumReleaseAgeExclude.add(scalarString(exclude)); @@ -499,7 +512,7 @@ export function rewritePnpmWorkspaceYaml( if (doc.get('trustPolicy') === 'no-downgrade') { const node = doc.get('trustPolicyExclude'); - if (node != null && !(node instanceof YAMLSeq)) { + if (node !== undefined && node !== null && !isSeq(node)) { throw new Error('pnpm-workspace.yaml: trustPolicyExclude must be a sequence'); } const excludes = node ?? new YAMLSeq>(); @@ -533,7 +546,7 @@ export function migratePnpmOverridesToWorkspaceYaml( export function applyBuildAllowanceToPackageJsonPnpm( pnpm: { allowBuilds?: Record; - onlyBuiltDependencies?: string[]; + onlyBuiltDependencies?: Array; }, major: number, shouldAllow: boolean, @@ -582,10 +595,8 @@ function applyBuildAllowanceToWorkspaceYaml( // blocked). Mutate an existing map in place (preserving its document position); // only attach a freshly created one. const existing = doc.getIn(['allowBuilds']); - const isNew = !(existing instanceof YAMLMap); - const allowBuilds = isNew - ? new YAMLMap, Scalar>() - : (existing as YAMLMap, Scalar>); + const isNew = !isMap(existing); + const allowBuilds = isNew ? new YAMLMap() : existing; for (const name of BROWSER_PROVIDER_POSTINSTALL_PACKAGES) { allowBuilds.set(scalarString(name), new Scalar(true)); } @@ -598,11 +609,9 @@ function applyBuildAllowanceToWorkspaceYaml( // The drivers reach the tree only via the opt-in webdriverio provider, so a project // that does not use it never installs them and there is nothing to allow or deny. } else if (shouldAllow) { - let onlyBuiltDependencies = doc.getIn(['onlyBuiltDependencies']) as YAMLSeq>; - if (!(onlyBuiltDependencies instanceof YAMLSeq)) { - onlyBuiltDependencies = new YAMLSeq>(); - } - const existing = new Set(onlyBuiltDependencies.items.map((n) => n.value)); + const node = doc.getIn(['onlyBuiltDependencies']); + const onlyBuiltDependencies = isSeq(node) ? node : new YAMLSeq(); + const existing = yamlSequenceValues(onlyBuiltDependencies); for (const name of BROWSER_PROVIDER_POSTINSTALL_PACKAGES) { if (!existing.has(name)) { onlyBuiltDependencies.add(scalarString(name)); @@ -665,7 +674,9 @@ export function getCatalogDependencySpec( if (resolved && !isVitePlusOverrideSpec(resolved)) { return resolved; } - return PUBLIC_PEER_DEPENDENCY_FALLBACKS[options.dependencyName] ?? currentValue; + return ( + lookupSetting(PUBLIC_PEER_DEPENDENCY_FALLBACKS, options.dependencyName) ?? currentValue + ); } return currentValue ?? version; } @@ -717,7 +728,7 @@ export function setDirectViteEdge( ); // Drop any existing `vite` entry first so an out-of-order one (appended after // `vite-plus`) is re-placed, then splice the new entry in sorted position. - const entries: [string, string][] = Object.entries(pkg.devDependencies ?? {}).filter( + const entries: Array<[string, string]> = Object.entries(pkg.devDependencies ?? {}).filter( ([name]) => name !== 'vite', ); const insertAt = entries.findIndex(([name]) => name > 'vite'); @@ -806,15 +817,19 @@ export function createCatalogDependencyResolver( return undefined; } +function yamlSequenceValues(sequence: YAMLSeq): Set { + return new Set(sequence.items.map((item) => (isScalar(item) ? item.value : item))); +} + function getYamlMapScalarStringValue(map: unknown, key: string): string | undefined { - if (!(map instanceof YAMLMap)) { + if (!isMap(map)) { return undefined; } for (const item of map.items) { if ( - item.key instanceof Scalar && + isScalar(item.key) && item.key.value === key && - item.value instanceof Scalar && + isScalar(item.value) && typeof item.value.value === 'string' ) { return item.value.value; @@ -848,7 +863,7 @@ function getYamlMapScalarStringValue(map: unknown, key: string): string | undefi export function mergeManagedPnpmOverrides( overrides: Record | undefined, managed: Record, -): Record { +) { const next = { ...overrides }; for (const [dependencyName, managedSpec] of Object.entries(managed)) { const overrideKey = pnpmOverrideKey(dependencyName); @@ -864,16 +879,21 @@ export function mergeManagedPnpmOverrides( } function pruneYamlMapLegacyWrapperAliases(map: unknown): void { - if (!(map instanceof YAMLMap)) { + if (!isMap(map)) { return; } - const stale: Array<{ key: Scalar; fallback: string | undefined }> = []; + const stale: Array<{ key: Scalar; fallback: string | undefined }> = []; for (const item of map.items) { - const value = item.value instanceof Scalar ? item.value.value : undefined; - if (typeof value === 'string' && isLegacyWrapperSpec(value) && item.key instanceof Scalar) { + const value = isScalar(item.value) ? item.value.value : undefined; + if ( + typeof value === 'string' && + isLegacyWrapperSpec(value) && + isScalar(item.key) && + typeof item.key.value === 'string' + ) { stale.push({ key: item.key, - fallback: LEGACY_WRAPPER_FALLBACK_VERSIONS[item.key.value], + fallback: lookupSetting(LEGACY_WRAPPER_FALLBACK_VERSIONS, item.key.value), }); } } @@ -893,13 +913,19 @@ export function rewriteCatalog( catalogAdditions: ReadonlySet, packageManager: PackageManager, ): string { - const parsed = doc.toJS() as { - catalog?: Record; - catalogs?: Record>; - } | null; + const parsed: unknown = doc.toJS(); + const settings = isYamlMapping(parsed) ? parsed : {}; + const namedCatalogs: Record = {}; + if (isYamlMapping(settings.catalogs)) { + for (const [name, entries] of Object.entries(settings.catalogs)) { + if (isYamlMapping(entries)) { + namedCatalogs[name] = entries; + } + } + } const preferredCatalogSpec = selectPreferredCatalogSpec( - parsed?.catalog, - parsed?.catalogs, + isYamlMapping(settings.catalog) ? settings.catalog : undefined, + namedCatalogs, packageManager, ); const targetPath = getYamlCatalogPath(doc, preferredCatalogSpec, packageManager); @@ -925,12 +951,12 @@ export function rewriteCatalog( } const catalogs = doc.getIn(['catalogs']); - if (catalogs instanceof YAMLMap) { + if (isMap(catalogs)) { for (const item of catalogs.items) { - const catalogName = item.key instanceof Scalar ? item.key.value : undefined; + const catalogName = isScalar(item.key) ? item.key.value : undefined; if ( typeof catalogName !== 'string' || - !(item.value instanceof YAMLMap) || + !isMap(item.value) || (targetPath[0] === 'catalogs' && targetPath[1] === catalogName) ) { continue; @@ -951,22 +977,21 @@ export function rewriteCatalog( function rewriteYamlCatalogAtPath( doc: YamlDocument, - catalogPath: readonly string[], + catalogPath: ReadonlyArray, addMissing: boolean, usesVitest: boolean, vitestEcosystemPackages: ReadonlySet, catalogAdditions: ReadonlySet, ): void { const managed = managedOverridePackages(usesVitest); - let catalogNode = doc.getIn(catalogPath); - if (!(catalogNode instanceof YAMLMap)) { + const catalogNode = doc.getIn(catalogPath); + const catalog = isMap(catalogNode) ? catalogNode : new YAMLMap(); + if (catalog !== catalogNode) { if (!addMissing) { return; } - catalogNode = new YAMLMap(); - doc.setIn(catalogPath, catalogNode); + doc.setIn(catalogPath, catalog); } - const catalog = catalogNode as YAMLMap; // Common case (no direct vitest): remove any lingering managed `vitest` // catalog entry so it resolves transitively through vite-plus. @@ -1009,11 +1034,11 @@ function rewriteVitestEcosystemYamlCatalog( catalog: unknown, vitestEcosystemPackages: ReadonlySet, ): void { - if (!VITEST_IS_MANAGED_OVERRIDE || !(catalog instanceof YAMLMap)) { + if (!VITEST_IS_MANAGED_OVERRIDE || !isMap(catalog)) { return; } for (const item of catalog.items) { - const name = item.key instanceof Scalar ? item.key.value : undefined; + const name = isScalar(item.key) ? item.key.value : undefined; if ( typeof name === 'string' && vitestEcosystemPackages.has(name) && @@ -1124,7 +1149,7 @@ export function rewriteBunCatalog( workspaces?: NpmWorkspaces; catalog?: Record; catalogs?: Record>; - overrides?: Record; + overrides?: JsonObject; }>(packageJsonPath, (pkg) => { // Bun supports catalogs in both workspaces.catalog and top-level catalog; // prefer the location the user already chose to avoid moving their config. @@ -1188,7 +1213,7 @@ export function rewriteRootWorkspacePackageJson( // Forwarded to `rewriteMonorepoProject` so the per-root lint-config // sanitizer can see hoisted deps in sibling workspace packages, not // just the root's own `package.json`. - packages?: WorkspacePackage[], + packages?: Array, pnpmMajorVersion?: number, pnpmVersion?: string, shouldAllowBrowserBuilds = false, @@ -1212,10 +1237,10 @@ export function rewriteRootWorkspacePackageJson( workspaceUsesWebdriverioProvider(projectPath, packages), ); - let movedPnpmSettings: Record | undefined; + let movedPnpmSettings: JsonObject | undefined; editJsonFile<{ resolutions?: Record; - overrides?: Record; + overrides?: JsonObject; devDependencies?: Record; dependencies?: Record; peerDependencies?: Record; @@ -1289,7 +1314,7 @@ export function rewriteRootWorkspacePackageJson( for (const key in pkg.pnpm?.overrides) { if (key.includes('>')) { const splits = key.split('>'); - if (splits.at(-1)!.trim() === 'vite') { + if (splits.at(-1)?.trim() === 'vite') { delete pkg.pnpm.overrides[key]; } } @@ -1383,7 +1408,7 @@ export function pnpmWorkspaceMinimumReleaseAgeExemptionsPending(projectPath: str } const doc = readYamlFile(pnpmWorkspaceYamlPath) as { minimumReleaseAge?: unknown; - minimumReleaseAgeExclude?: string[]; + minimumReleaseAgeExclude?: Array; } | null; if (!doc || doc.minimumReleaseAge === undefined) { return false; @@ -1427,20 +1452,20 @@ function setPeerDependencyRulesField( doc.deleteIn(['peerDependencyRules', field]); } const rules = doc.get('peerDependencyRules'); - if (rules instanceof YAMLMap && rules.items.length === 0) { + if (isMap(rules) && rules.items.length === 0) { doc.delete('peerDependencyRules'); } } export function readPnpmWorkspacePeerDependencyRules( projectPath: string, -): { allowAny?: string[]; allowedVersions?: Record } | undefined { +): { allowAny?: Array; allowedVersions?: Record } | undefined { const pnpmWorkspaceYamlPath = path.join(projectPath, 'pnpm-workspace.yaml'); if (!fs.existsSync(pnpmWorkspaceYamlPath)) { return undefined; } const doc = readYamlFile(pnpmWorkspaceYamlPath) as { - peerDependencyRules?: { allowAny?: string[]; allowedVersions?: Record }; + peerDependencyRules?: { allowAny?: Array; allowedVersions?: Record }; } | null; return doc?.peerDependencyRules; } @@ -1453,10 +1478,10 @@ function hasVitePeerDependencyRule(projectPath: string): boolean { ) { return true; } - const pkg = readPackageJsonIfExists(path.join(projectPath, 'package.json')) as - | { pnpm?: PnpmPackageJsonSettings } - | undefined; - return peerDependencyRulesHaveStaleEntry(pkg?.pnpm?.peerDependencyRules, ['vite']); + const pkg = readPackageJsonIfExists(path.join(projectPath, 'package.json')); + const pnpm = pkg && 'pnpm' in pkg && isJsonObject(pkg.pnpm) ? pkg.pnpm : undefined; + const rules = pnpm?.peerDependencyRules; + return peerDependencyRulesHaveStaleEntry(isObjectValue(rules) ? rules : undefined, ['vite']); } // Capture the `vite` peer rule before a migration step. Call the returned @@ -1485,7 +1510,7 @@ export function trackVitePeerDependencyRuleRemoval( export function ensurePnpmWorkspacePackages( projectPath: string, - workspacePatterns: string[], + workspacePatterns: Array, ): boolean { if (workspacePatterns.length === 0) { return false; diff --git a/packages/cli/src/migration/migrator/core-finalization.ts b/packages/cli/src/migration/migrator/core-finalization.ts index 49f2cf9e4c..29bece7961 100644 --- a/packages/cli/src/migration/migrator/core-finalization.ts +++ b/packages/cli/src/migration/migrator/core-finalization.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { rewriteScripts } from '../../../binding/index.js'; -import { type WorkspacePackage } from '../../types/index.ts'; +import type { WorkspacePackage } from '../../types/index.ts'; import { editJsonFile, readJsonFile } from '../../utils/json.ts'; import { rulesDir } from '../../utils/path.ts'; import { @@ -14,7 +14,8 @@ import { rewriteAllImports, rewriteTsconfigTypes, } from '../migrator.ts'; -import { type MigrationReport } from '../report.ts'; +import type { MigrationReport } from '../report.ts'; +import { rewriteScriptMap } from './shared.ts'; const RULES_YAML_PATH = path.join(rulesDir, 'vite-tools.yml'); @@ -33,9 +34,9 @@ export function readRulesYaml(): string { // Each rule is one YAML document introduced by a `---` separator line. Split on the // separators instead of on blank lines, which a formatter is free to collapse. Comment // lines directly above a separator describe the rule below it, so they move with it. -function splitRuleDocuments(yaml: string): string[] { +function splitRuleDocuments(yaml: string): Array { const lines = yaml.split('\n'); - const documents: string[] = []; + const documents: Array = []; let start = 0; for (const [index, line] of lines.entries()) { if (line.trimEnd() !== '---') { @@ -72,7 +73,7 @@ export function readPrepareRulesYaml(): string { type CoreMigrationWorkspace = { rootDir: string; - packages?: WorkspacePackage[]; + packages?: Array; }; export type PendingCoreMigration = { @@ -89,7 +90,7 @@ export type CoreMigrationFinalizationResult = { taskCacheConfig: boolean; // Kept out of the report so that review items alone do not make an // up-to-date project run the rest of the migration. - taskCacheWarnings: string[]; + taskCacheWarnings: Array; }; function hasCorePackageScriptRewrites(projectPath: string): boolean { @@ -115,11 +116,13 @@ function rewriteCorePackageScripts(projectPath: string): boolean { if (!pkg.scripts) { return undefined; } - const updated = rewriteScripts(JSON.stringify(pkg.scripts), getScriptRulesYaml(true)); + const updated = rewriteScriptMap(pkg.scripts, (serialized) => + rewriteScripts(serialized, getScriptRulesYaml(true)), + ); if (!updated) { return undefined; } - pkg.scripts = JSON.parse(updated); + pkg.scripts = updated; changed = true; return pkg; }); diff --git a/packages/cli/src/migration/migrator/eslint.ts b/packages/cli/src/migration/migrator/eslint.ts index bf9231d0e1..0cacc3fe48 100644 --- a/packages/cli/src/migration/migrator/eslint.ts +++ b/packages/cli/src/migration/migrator/eslint.ts @@ -3,13 +3,19 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { styleText } from 'node:util'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; -import { type OxlintConfig } from 'oxlint'; +import { + confirm as promptConfirm, + isCancel, + log as promptLog, +} from '@voidzero-dev/vite-plus-prompts'; +import type { OxlintConfig } from 'oxlint'; import { compareReversed, isLessThanOrEqual, normalize } from 'verkit'; import { ResolverFactory, rewriteEslint } from '../../../binding/index.js'; -import { type WorkspacePackage } from '../../types/index.ts'; +import type { WorkspacePackage } from '../../types/index.ts'; import { getVpCommand, runCommandSilently } from '../../utils/command.ts'; +import { isJsonObject, isObjectValue } from '../../utils/json-value.ts'; +import type { JsonObject } from '../../utils/json.ts'; import { editJsonFile, isJsonFile, readJsonFile } from '../../utils/json.ts'; import { fetchNpmResource, getNpmRegistry } from '../../utils/npm-config.ts'; import { displayRelative } from '../../utils/path.ts'; @@ -17,10 +23,12 @@ import { cancelAndExit } from '../../utils/prompts.ts'; import { getSilentSpinner, getSpinner } from '../../utils/spinner.ts'; import { hasBaseUrlInTsconfig } from '../../utils/tsconfig.ts'; import { detectConfigs } from '../detector.ts'; -import { type MigrationReport } from '../report.ts'; +import type { MigrationReport } from '../report.ts'; import { LINT_STAGED_JSON_CONFIG_FILES, LINT_STAGED_OTHER_CONFIG_FILES, + rewritePackageScriptFields, + rewriteScriptMap, warnMigration, } from './shared.ts'; @@ -51,16 +59,16 @@ const OXLINT_SCHEMA_PATH = fileURLToPath( new URL('configuration_schema.json', import.meta.resolve('oxlint/package.json')), ); -const OXLINT_SCHEMA = readJsonFile(OXLINT_SCHEMA_PATH) as { - definitions: { DummyRuleMap: { properties: Record } }; -}; +const schemaDefinitions = readJsonFile(OXLINT_SCHEMA_PATH).definitions; +const ruleMap = isObjectValue(schemaDefinitions) ? schemaDefinitions.DummyRuleMap : undefined; +if (!isObjectValue(ruleMap) || !isObjectValue(ruleMap.properties)) { + throw new Error('The Oxlint schema is missing its built-in rules'); +} // Oxlint generates `DummyRuleMap.properties` from its built-in `RULES` table. // Defined in `oxc_linter/src/generated/rules_enum.rs`; // schema generation is in `oxc_linter/src/config/rules.rs`. -const OXLINT_BUILTIN_RULES = new Set( - Object.keys(OXLINT_SCHEMA.definitions.DummyRuleMap.properties), -); +const OXLINT_BUILTIN_RULES = new Set(Object.keys(ruleMap.properties)); // Oxlint accepts these TypeScript rule names as aliases for the corresponding // built-in ESLint rules. Keep this list aligned with @@ -86,14 +94,7 @@ const TYPESCRIPT_COMPATIBLE_ESLINT_RULES = new Set([ 'no-useless-constructor', ]); -export function detectEslintProject( - projectPath: string, - packages?: WorkspacePackage[], -): { - hasDependency: boolean; - configFile?: string; - legacyConfigFile?: string; -} { +export function detectEslintProject(projectPath: string, packages?: Array) { const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { return { hasDependency: false }; @@ -104,7 +105,7 @@ export function detectEslintProject( }; let hasDependency = !!(pkg.devDependencies?.eslint || pkg.dependencies?.eslint); const configs = detectConfigs(projectPath); - let configFile = configs.eslintConfig; + const configFile = configs.eslintConfig; const legacyConfigFile = configs.eslintLegacyConfig; // If root doesn't have eslint dependency, check workspace packages @@ -162,11 +163,13 @@ export async function resolveOxlintMigrateVersion(oxlintVersion: string): Promis if (!response.ok) { return oxlintVersion; } - const packument = (await response.json()) as { versions?: Record }; - if (packument.versions && Object.hasOwn(packument.versions, oxlintVersion)) { + const packument: unknown = await response.json(); + const available = + isJsonObject(packument) && isObjectValue(packument.versions) ? packument.versions : {}; + if (Object.hasOwn(available, oxlintVersion)) { return oxlintVersion; } - const candidates = Object.keys(packument.versions ?? {}).filter( + const candidates = Object.keys(available).filter( (version) => normalize(version) && isLessThanOrEqual(version, oxlintVersion), ); return candidates.length > 0 ? candidates.toSorted(compareReversed)[0] : oxlintVersion; @@ -182,7 +185,7 @@ export async function resolveOxlintMigrateVersion(oxlintVersion: string): Promis async function runOxlintMigrateStep( cwd: string, migratePackage: string, - args: string[], + args: Array, spinner: ReturnType, failMessage: string, manualHint: string, @@ -197,15 +200,15 @@ async function runOxlintMigrateStep( spinner.stop(failMessage); const stderr = result.stderr.toString().trim(); if (stderr) { - prompts.log.warn(`⚠ ${stderr}`); + promptLog.warn(`⚠ ${stderr}`); } - prompts.log.info(manualHint); + promptLog.info(manualHint); return { ok: false }; } return { ok: true, skippedRules: extractSkippedRules(result.stdout) }; } catch { spinner.stop(failMessage); - prompts.log.info(manualHint); + promptLog.info(manualHint); return { ok: false }; } } @@ -214,7 +217,7 @@ export async function migrateEslintToOxlint( projectPath: string, interactive: boolean, eslintConfigFile?: string, - packages?: WorkspacePackage[], + packages?: Array, options?: { silent?: boolean; report?: MigrationReport }, ): Promise { const spinner = options?.silent ? getSilentSpinner() : getSpinner(interactive); @@ -224,7 +227,6 @@ export async function migrateEslintToOxlint( // Pin @oxlint/migrate to the bundled oxlint version when the registry // has it; the package trails oxlint releases, so resolve the newest // published version that is not newer than the pin. - // @ts-expect-error — resolved at runtime from dist/ → dist/versions.js const { versions } = await import('../versions.js'); const migratePackage = `@oxlint/migrate@${await resolveOxlintMigrateVersion(versions.oxlint)}`; const migrateArgs = [ @@ -355,7 +357,7 @@ function deleteEslintConfigFiles(basePath: string, report?: MigrationReport, sil report.removedConfigCount++; } if (!silent) { - prompts.log.success(`✔ Removed ${displayRelative(configPath)}`); + promptLog.success(`✔ Removed ${displayRelative(configPath)}`); } } } @@ -449,7 +451,7 @@ export function rewriteEslintPackageJson( peerDependencies?: Record; optionalDependencies?: Record; scripts?: Record; - 'lint-staged'?: Record; + 'lint-staged'?: Record>; }>(packageJsonPath, (pkg) => { let changed = false; for (const field of [ @@ -479,21 +481,8 @@ export function rewriteEslintPackageJson( delete pkg[field]; } } - if (pkg.scripts) { - const updated = rewriteEslint(JSON.stringify(pkg.scripts)); - if (updated) { - pkg.scripts = JSON.parse(updated); - changed = true; - } - } - if (pkg['lint-staged']) { - const updated = rewriteEslint(JSON.stringify(pkg['lint-staged'])); - if (updated) { - pkg['lint-staged'] = JSON.parse(updated); - changed = true; - } - } - return changed ? pkg : undefined; + const scriptsChanged = rewritePackageScriptFields(pkg, rewriteEslint); + return changed || scriptsChanged ? pkg : undefined; }); } @@ -519,13 +508,9 @@ export function rewriteToolLintStagedConfigFiles( ); continue; } - editJsonFile>(configPath, (config) => { - const updated = rewriteFn(JSON.stringify(config)); - if (updated) { - return JSON.parse(updated); - } - return undefined; - }); + editJsonFile>>(configPath, (config) => + rewriteScriptMap(config, rewriteFn), + ); } for (const filename of LINT_STAGED_OTHER_CONFIG_FILES) { const configPath = path.join(projectPath, filename); @@ -578,7 +563,7 @@ function deriveJsPluginNamespace(packageName: string): string { */ export function collectInstalledPackageNames( projectPath: string, - packages?: WorkspacePackage[], + packages?: Array, ): Set { const names = new Set(); const paths = [projectPath, ...(packages ?? []).map((p) => path.join(projectPath, p.path))]; @@ -587,9 +572,9 @@ export function collectInstalledPackageNames( if (!fs.existsSync(pkgJsonPath)) { continue; } - let pkg: Record | undefined>; + let pkg: JsonObject; try { - pkg = readJsonFile(pkgJsonPath) as typeof pkg; + pkg = readJsonFile(pkgJsonPath); } catch { continue; } @@ -599,7 +584,7 @@ export function collectInstalledPackageNames( // must not count as available here. for (const field of ['devDependencies', 'dependencies', 'optionalDependencies'] as const) { const deps = pkg[field]; - if (deps) { + if (isJsonObject(deps)) { for (const name of Object.keys(deps)) { names.add(name); } @@ -687,19 +672,21 @@ function hasBuiltinOxlintNamespace(key: string): boolean { /** Filter a rules object to Oxlint rules or rules under a configured JS plugin namespace. */ function filterRulesAgainstNamespaces( - rules: Record, + rules: NonNullable, jsPluginNamespaces: Set, droppedRules: Set, -): Record { - const out: Record = {}; - for (const [key, value] of Object.entries(rules)) { +) { + const out = { ...rules }; + for (const key of Object.keys(rules)) { if ( isBuiltinOxlintRule(key) || ruleKeyMatchesNamespace(key, jsPluginNamespaces) || ruleKeyMatchesNamespace(normalizeOxlintRuleNamespace(key), jsPluginNamespaces) ) { - out[key] = value; - } else if (hasBuiltinOxlintNamespace(key)) { + continue; + } + delete out[key]; + if (hasBuiltinOxlintNamespace(key)) { droppedRules.add(key); } } @@ -716,12 +703,9 @@ function filterRulesAgainstNamespaces( function partitionJsPlugins( entries: NonNullable, availablePackages: Set, -): { - kept: NonNullable; - dropped: string[]; -} { +) { const kept: NonNullable = []; - const dropped: string[] = []; + const dropped: Array = []; for (const entry of entries) { if (typeof entry !== 'string') { kept.push(entry); @@ -822,7 +806,7 @@ export function sanitizeInheritedJsPlugins( } for (const rule of Object.keys(layer.rules ?? {})) { if (ruleKeyMatchesNamespace(rule, droppedNamespaces) && !isBuiltinOxlintRule(rule)) { - delete layer.rules![rule]; + delete layer.rules?.[rule]; } } return droppedNamespaces; @@ -881,7 +865,7 @@ export function sanitizeMigratedOxlintConfig( // 3. Sanitize base-level plugins[] against base namespaces. if (config.plugins) { type PluginEntry = NonNullable[number]; - const keptPlugins: PluginEntry[] = []; + const keptPlugins: Array = []; for (const p of config.plugins) { if (baseNamespaces.has(p)) { keptPlugins.push(p); @@ -904,7 +888,7 @@ export function sanitizeMigratedOxlintConfig( allDroppedRules, ); if (Object.keys(filtered).length !== Object.keys(config.rules).length) { - config.rules = filtered as typeof config.rules; + config.rules = filtered; } } @@ -941,7 +925,7 @@ export function sanitizeMigratedOxlintConfig( // Override plugins[]. if (override.plugins) { type OverridePluginEntry = NonNullable[number]; - const keptOverridePlugins: OverridePluginEntry[] = []; + const keptOverridePlugins: Array = []; for (const p of override.plugins) { if (overrideNamespaces.has(p)) { keptOverridePlugins.push(p); @@ -962,7 +946,7 @@ export function sanitizeMigratedOxlintConfig( allDroppedRules, ); if (Object.keys(filtered).length !== Object.keys(override.rules).length) { - override.rules = filtered as typeof override.rules; + override.rules = filtered; } } } @@ -996,7 +980,7 @@ export function sanitizeMigratedOxlintConfig( } export function warnPackageLevelEslint() { - prompts.log.warn( + promptLog.warn( 'ESLint detected in workspace packages but no root config found. Package-level ESLint must be migrated manually.', ); } @@ -1022,7 +1006,7 @@ const INCOMPATIBLE_ESLINT_INTEGRATIONS = ['@nuxt/eslint'] as const; */ export function detectIncompatibleEslintIntegration( projectPath: string, - packages?: WorkspacePackage[], + packages?: Array, ): string | undefined { const candidates = [projectPath, ...(packages ?? []).map((p) => path.join(projectPath, p.path))]; for (const candidate of candidates) { @@ -1046,7 +1030,7 @@ export function detectIncompatibleEslintIntegration( } export function warnIncompatibleEslintIntegration(name: string): void { - prompts.log.warn( + promptLog.warn( `${name} detected — automatic ESLint migration is skipped. ` + `${name} wires ESLint into a framework-specific flow that Vite+ cannot migrate cleanly yet. ` + 'Your ESLint setup is preserved. ' + @@ -1055,7 +1039,7 @@ export function warnIncompatibleEslintIntegration(name: string): void { } export function warnLegacyEslintConfig(legacyConfigFile: string) { - prompts.log.warn( + promptLog.warn( `Legacy ESLint configuration detected (${legacyConfigFile}). ` + 'Automatic migration to Oxlint requires ESLint v9+ with flat config format (eslint.config.*). ' + 'Please upgrade to ESLint v9 first: https://eslint.org/docs/latest/use/migrate-to-9.0.0', @@ -1064,7 +1048,7 @@ export function warnLegacyEslintConfig(legacyConfigFile: string) { export async function confirmEslintMigration(interactive: boolean): Promise { if (interactive) { - const confirmed = await prompts.confirm({ + const confirmed = await promptConfirm({ message: 'Migrate ESLint rules to Oxlint using @oxlint/migrate?\n ' + styleText( @@ -1073,7 +1057,7 @@ export async function confirmEslintMigration(interactive: boolean): Promise, ): Promise { const incompatible = detectIncompatibleEslintIntegration(projectPath, packages); if (incompatible) { diff --git a/packages/cli/src/migration/migrator/framework-shim.ts b/packages/cli/src/migration/migrator/framework-shim.ts index 9d2333a517..80034b26f1 100644 --- a/packages/cli/src/migration/migrator/framework-shim.ts +++ b/packages/cli/src/migration/migrator/framework-shim.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { readJsonFile } from '../../utils/json.ts'; -import { type MigrationReport } from '../report.ts'; +import type { MigrationReport } from '../report.ts'; // .svelte files are handled by @sveltejs/vite-plugin-svelte (transpilation) // and svelte-check / Svelte Language Server (type checking). @@ -28,7 +28,7 @@ const FRAMEWORK_SHIMS: Record = { astro: '/// ', }; -export function detectFramework(projectPath: string): Framework[] { +export function detectFramework(projectPath: string): Array { const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { return []; @@ -58,7 +58,7 @@ export function hasFrameworkShim(projectPath: string, framework: Framework): boo if (!fs.existsSync(dir)) { continue; } - let entries: string[]; + let entries: Array; try { entries = fs.readdirSync(dir); } catch { @@ -68,7 +68,7 @@ export function hasFrameworkShim(projectPath: string, framework: Framework): boo if (!entry.endsWith('.d.ts')) { continue; } - const content = fs.readFileSync(path.join(dir, entry), 'utf-8'); + const content = fs.readFileSync(path.join(dir, entry), 'utf8'); if (framework === 'astro') { if (content.includes('astro/client')) { return true; @@ -89,11 +89,11 @@ export function addFrameworkShim( const envDtsPath = getEnvDtsPath(projectPath); const shim = FRAMEWORK_SHIMS[framework]; if (fs.existsSync(envDtsPath)) { - const existing = fs.readFileSync(envDtsPath, 'utf-8'); - fs.writeFileSync(envDtsPath, `${existing.trimEnd()}\n\n${shim}\n`, 'utf-8'); + const existing = fs.readFileSync(envDtsPath, 'utf8'); + fs.writeFileSync(envDtsPath, `${existing.trimEnd()}\n\n${shim}\n`, 'utf8'); } else { fs.mkdirSync(path.dirname(envDtsPath), { recursive: true }); - fs.writeFileSync(envDtsPath, `${shim}\n`, 'utf-8'); + fs.writeFileSync(envDtsPath, `${shim}\n`, 'utf8'); } if (report) { report.frameworkShimAdded = true; diff --git a/packages/cli/src/migration/migrator/git-hooks.ts b/packages/cli/src/migration/migrator/git-hooks.ts index 7273b40d4c..7a22d8e533 100644 --- a/packages/cli/src/migration/migrator/git-hooks.ts +++ b/packages/cli/src/migration/migrator/git-hooks.ts @@ -1,15 +1,11 @@ import fs from 'node:fs'; import path from 'node:path'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { log as promptLog } from '@voidzero-dev/vite-plus-prompts'; import spawn from 'cross-spawn'; -import { - type LiteralCommandToken, - parseConfigArgs, - parseLiteralCommands, - rewriteScripts, -} from '../../../binding/index.js'; +import type { LiteralCommandToken } from '../../../binding/index.js'; +import { parseConfigArgs, parseLiteralCommands, rewriteScripts } from '../../../binding/index.js'; import { findUnsafeHookInstallPath, HOOK_STUB_SCRIPT, @@ -20,6 +16,7 @@ import type { PackageManager, WorkspacePackage } from '../../types/index.ts'; import { getVpCommand } from '../../utils/command.ts'; import { documentationUrl } from '../../utils/documentation.ts'; import { findGitRoot } from '../../utils/git.ts'; +import { isObjectValue } from '../../utils/json-value.ts'; import { editJsonFile, isJsonFile, readJsonFile } from '../../utils/json.ts'; import { hasStagedConfigInViteConfig, @@ -27,7 +24,8 @@ import { readRulesYaml, removeLintStagedFromPackageJson, } from '../migrator.ts'; -import { type MigrationReport } from '../report.ts'; +import type { MigrationReport } from '../report.ts'; +import { rewriteScriptMap } from './shared.ts'; import { getCommandStartIndex, LINT_STAGED_ALL_CONFIG_FILES, @@ -102,7 +100,7 @@ export function hasExistingViteHooksPolicy(projectPath: string): boolean { /** * List the supported hook files present in `.vite-hooks/`, in canonical order. */ -export function listExistingViteHookNames(projectPath: string): string[] { +export function listExistingViteHookNames(projectPath: string): Array { const hooksDir = path.join(projectPath, '.vite-hooks'); return SUPPORTED_GIT_HOOK_NAMES.filter((hookName) => fs.lstatSync(path.join(hooksDir, hookName), { throwIfNoEntry: false })?.isFile(), @@ -160,13 +158,13 @@ function hasVpConfigLifecycleScript(scripts: Record | undefined) } interface VpConfigHookCommand { - args: LiteralCommandToken[]; + args: Array; hooksEnabled: boolean; } /** Only recognize literal invocations in the project directory. Text passed * to echo, node, or another command must not count as a dispatcher refresh. */ -function vpConfigHookCommands(script: string | undefined): VpConfigHookCommand[] { +function vpConfigHookCommands(script: string | undefined): Array { if (!script) { return []; } @@ -181,7 +179,7 @@ function vpConfigHookCommands(script: string | undefined): VpConfigHookCommand[] if (!commands) { return []; } - const result: VpConfigHookCommand[] = []; + const result: Array = []; for (const tokens of commands) { const values = tokens.map(({ value }) => value); if (/^[A-Za-z_]\w*=/.test(values[0] ?? '')) { @@ -243,7 +241,7 @@ function findNonRegularViteHookPath(projectPath: string): string | null { function findWorkspacePackageHookPolicy( workspaceRoot: string, - packages: readonly WorkspacePackage[], + packages: ReadonlyArray, ): string | null { for (const pkg of packages) { const packagePath = path.join(workspaceRoot, pkg.path); @@ -256,8 +254,8 @@ function findWorkspacePackageHookPolicy( if (hasHuskySetup(packagePath, pkgContent)) { return `Detected Husky in workspace package "${pkg.path}" — leaving its hooks, configuration, and dependencies unchanged.`; } - const deps = pkgContent.devDependencies as Record | undefined; - const prodDeps = pkgContent.dependencies as Record | undefined; + const deps = isObjectValue(pkgContent.devDependencies) ? pkgContent.devDependencies : undefined; + const prodDeps = isObjectValue(pkgContent.dependencies) ? pkgContent.dependencies : undefined; for (const tool of OTHER_HOOK_TOOLS) { if (deps?.[tool] || prodDeps?.[tool] || pkgContent[tool]) { return `Detected ${tool} in workspace package "${pkg.path}" — leaving the existing hook setup unchanged.`; @@ -303,7 +301,7 @@ function normalizeGitHooksPath(hooksPath: string): string { export function preflightGitHooksSetup( projectPath: string, _packageManager?: PackageManager, - packages: readonly WorkspacePackage[] = [], + packages: ReadonlyArray = [], ): string | null { const gitRoot = findGitRoot(projectPath); if (gitRoot && path.resolve(projectPath) !== path.resolve(gitRoot)) { @@ -314,8 +312,8 @@ export function preflightGitHooksSetup( return null; // silently skip } const pkgContent = readJsonFile(packageJsonPath); - const deps = pkgContent.devDependencies as Record | undefined; - const prodDeps = pkgContent.dependencies as Record | undefined; + const deps = isObjectValue(pkgContent.devDependencies) ? pkgContent.devDependencies : undefined; + const prodDeps = isObjectValue(pkgContent.dependencies) ? pkgContent.dependencies : undefined; const configuredHooksPath = gitRoot ? getConfiguredHooksPath(projectPath) : ''; const normalizedHooksPath = normalizeGitHooksPath(configuredHooksPath); if ( @@ -366,7 +364,7 @@ export function shouldSkipStagedMigrationForHooks( projectPath: string, shouldSetupHooks: boolean, packageManager?: PackageManager, - packages: readonly WorkspacePackage[] = [], + packages: ReadonlyArray = [], ): boolean { return ( !shouldSetupHooks || @@ -385,7 +383,7 @@ export function installGitHooks( silent = false, report?: MigrationReport, packageManager?: PackageManager, - packages: readonly WorkspacePackage[] = [], + packages: ReadonlyArray = [], ): boolean { const reason = preflightGitHooksSetup(projectPath, packageManager, packages); if (reason) { @@ -430,13 +428,13 @@ export function installGitHooks( if (!hasExistingHookPolicy && !stagedMerged && !hasStandaloneConfig) { // Use lint-staged config from package.json if available, otherwise use default const pkgData = readJsonFile(packageJsonPath) as { - 'lint-staged'?: Record; + 'lint-staged'?: Record>; }; const stagedConfig = pkgData?.['lint-staged'] ?? DEFAULT_STAGED_CONFIG; - const updated = rewriteScripts(JSON.stringify(stagedConfig), readRulesYaml()); - const finalConfig: Record = updated - ? JSON.parse(updated) - : stagedConfig; + const updated = rewriteScriptMap(stagedConfig, (serialized) => + rewriteScripts(serialized, readRulesYaml()), + ); + const finalConfig = updated ?? stagedConfig; stagedMerged = mergeStagedConfigToViteConfig(projectPath, finalConfig, silent, report); } @@ -484,7 +482,7 @@ export function installGitHooks( report.gitHooksConfigured = true; } if (!silent) { - prompts.log.success('✔ Git hooks configured'); + promptLog.success('✔ Git hooks configured'); } return true; } @@ -517,7 +515,7 @@ function hasUnsupportedLintStagedConfig(projectPath: string): boolean { return false; } -const DEFAULT_STAGED_CONFIG: Record = { '*': 'vp check --fix' }; +const DEFAULT_STAGED_CONFIG = { '*': 'vp check --fix' }; export function createPreCommitHook(projectPath: string, dir = '.vite-hooks'): void { const huskyDir = path.join(projectPath, dir); diff --git a/packages/cli/src/migration/migrator/orchestrators.ts b/packages/cli/src/migration/migrator/orchestrators.ts index 8187fc03da..093bff699d 100644 --- a/packages/cli/src/migration/migrator/orchestrators.ts +++ b/packages/cli/src/migration/migrator/orchestrators.ts @@ -1,9 +1,11 @@ import fs from 'node:fs'; import path from 'node:path'; -import { PackageManager, type WorkspaceInfo, type WorkspacePackage } from '../../types/index.ts'; +import type { WorkspaceInfo, WorkspacePackage } from '../../types/index.ts'; +import { PackageManager } from '../../types/index.ts'; import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; import { VITE_PLUS_NAME, VITE_PLUS_VERSION, isForceOverrideMode } from '../../utils/constants.ts'; +import type { JsonObject } from '../../utils/json.ts'; import { editJsonFile } from '../../utils/json.ts'; import { applyBuildAllowanceToPackageJsonPnpm, @@ -68,14 +70,13 @@ import { yarnSupportsPreapprovedPackages, wrapLazyPluginsInViteConfig, } from '../migrator.ts'; -import { type MigrationReport } from '../report.ts'; -import { - PROVIDER_OVERRIDE_DROP_NAMES, - pnpmMajor, - type PnpmPackageJsonSettings, - type PreparedOxlintConfigs, - type RetainedImportDependencies, +import type { MigrationReport } from '../report.ts'; +import type { + PnpmPackageJsonSettings, + PreparedOxlintConfigs, + RetainedImportDependencies, } from './shared.ts'; +import { PROVIDER_OVERRIDE_DROP_NAMES, pnpmMajor } from './shared.ts'; export function rewriteStandaloneProject( projectPath: string, @@ -132,8 +133,8 @@ export function rewriteStandaloneProject( new Map([[projectPath, providerSourceModes]]), ); const pnpmMajorVersion = pnpmMajor(workspaceInfo.downloadPackageManager.version); - let extractedStagedConfig: Record | null = null; - let movedPnpmSettings: Record | undefined; + let extractedStagedConfig: Record> | null = null; + let movedPnpmSettings: JsonObject | undefined; let shouldAddPnpmWorkspaceVitePlusOverride = false; let shouldAllowBrowserProviderBuilds = false; // Whether the project uses vitest directly (a required-peer consumer, an @@ -157,7 +158,7 @@ export function rewriteStandaloneProject( workspaceInfo.downloadPackageManager.version, ); editJsonFile<{ - overrides?: Record; + overrides?: JsonObject; resolutions?: Record; devDependencies?: Record; dependencies?: Record; @@ -241,7 +242,7 @@ export function rewriteStandaloneProject( for (const key in pkg.pnpm?.overrides) { if (key.includes('>')) { const splits = key.split('>'); - if (splits.at(-1)!.trim() === 'vite') { + if (splits.at(-1)?.trim() === 'vite') { delete pkg.pnpm.overrides[key]; } } @@ -579,7 +580,7 @@ export function rewriteMonorepoProject( catalogDependencyResolver?: CatalogDependencyResolver, workspaceContext?: { rootDir: string; - packages: WorkspacePackage[]; + packages: Array; oxlintConfigs?: PreparedOxlintConfigs; retainedImportDependencies?: RetainedImportDependencies; }, @@ -618,7 +619,7 @@ export function rewriteMonorepoProject( ? findYarnWorkspaceHoisting(workspaceContext?.rootDir ?? projectPath) : undefined; - let extractedStagedConfig: Record | null = null; + let extractedStagedConfig: Record> | null = null; editJsonFile<{ devDependencies?: Record; dependencies?: Record; diff --git a/packages/cli/src/migration/migrator/oxlint-config.ts b/packages/cli/src/migration/migrator/oxlint-config.ts index b971d3fd49..7ac381a8dd 100644 --- a/packages/cli/src/migration/migrator/oxlint-config.ts +++ b/packages/cli/src/migration/migrator/oxlint-config.ts @@ -2,22 +2,20 @@ import { createHash } from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; -import type { Program } from '@oxc-project/types'; -import { parse as parseJsonc, type ParseError } from 'jsonc-parser'; +import type { ParseError } from 'jsonc-parser'; +import { parse as parseJsonc } from 'jsonc-parser'; import type { OxlintConfig } from 'oxlint'; import { analyzeMigrationSource, ResolverFactory } from '../../../binding/index.js'; +import { isJsonObject, isObjectValue } from '../../utils/json-value.ts'; +import type { JsonValue, JsonObject } from '../../utils/json.ts'; import { detectConfigs } from '../detector.ts'; import { ensureSvelteRuneGlobals } from '../migrator.ts'; -import { - OXLINT_OWNER_CONFIG_KEYS, - type OxlintConfigFile, - type OxlintModulePlan, - type PreparedOxlintConfigs, -} from './shared.ts'; +import type { OxlintConfigFile, OxlintModulePlan, PreparedOxlintConfigs } from './shared.ts'; +import { OXLINT_OWNER_CONFIG_KEYS } from './shared.ts'; interface OxlintConfigCache { - sources: Map>; + sources: Map; files: Map; } @@ -32,7 +30,7 @@ function createConfigCache(): OxlintConfigCache { export function resolveOxlintConfigExtends( configPath: string, cache = createConfigCache(), - stack: string[] = [], + stack: Array = [], ): OxlintConfigFile { // Windows collapses parent components before following directory junctions. // POSIX follows the directory link first, so its physical parent is the context. @@ -48,13 +46,14 @@ export function resolveOxlintConfigExtends( } let source = cache.sources.get(sourcePath); if (!source) { - const errors: ParseError[] = []; - source = parseJsonc(fs.readFileSync(sourcePath, 'utf8'), errors, { + const errors: Array = []; + const parsed: unknown = parseJsonc(fs.readFileSync(sourcePath, 'utf8'), errors, { allowTrailingComma: true, - }) as Record; - if (errors.length > 0 || !source || typeof source !== 'object' || Array.isArray(source)) { + }); + if (errors.length > 0 || !isJsonObject(parsed)) { throw new Error(`Invalid Oxlint JSON config: ${filename}`); } + source = parsed; cache.sources.set(sourcePath, source); } // Parsing is shared by source identity, but relative paths belong to each declaring config. @@ -63,11 +62,11 @@ export function resolveOxlintConfigExtends( const inherited = config.extends; if ( inherited !== undefined && - (!Array.isArray(inherited) || inherited.some((entry) => typeof entry !== 'string')) + (!Array.isArray(inherited) || !inherited.every((entry) => typeof entry === 'string')) ) { throw new Error(`Expected an array of file paths in ${filename}: extends`); } - const extendsPaths = ((inherited ?? []) as string[]).map((entry) => + const extendsPaths = (inherited ?? []).map((entry) => path.resolve(path.dirname(filename), entry), ); const children = extendsPaths.map((childPath) => { @@ -75,12 +74,12 @@ export function resolveOxlintConfigExtends( child.shared = true; return child; }); - if (inherited !== undefined) { - config.extends = children.map((child) => child.config); - } const file: OxlintConfigFile = { filename, - config, + config: + inherited === undefined + ? config + : { ...config, extends: children.map((child) => child.config) }, extends: children, extendsPaths, }; @@ -88,7 +87,7 @@ export function resolveOxlintConfigExtends( return file; } -export function prepareOxlintConfigs(projectPaths: string[]): PreparedOxlintConfigs { +export function prepareOxlintConfigs(projectPaths: Array): PreparedOxlintConfigs { const configs: PreparedOxlintConfigs = new Map(); const cache = createConfigCache(); for (const projectPath of projectPaths) { @@ -105,9 +104,9 @@ export function prepareOxlintConfigs(projectPaths: string[]): PreparedOxlintConf } // An owner must also import its source when another consumer reaches it through an alias. const sharedSources = new Set( - [...cache.files.values()] - .filter((file) => file.shared) - .map((file) => fs.realpathSync(file.filename)), + [...cache.files.values()].flatMap((file) => + file.shared ? [fs.realpathSync(file.filename)] : [], + ), ); // An unreadable consumer can still refer to any workspace's own config. // Keep those owners in modules so a later repair cannot create an inline copy. @@ -147,14 +146,14 @@ export function oxlintMigrationMarker( } const files = new Set(); collectConfigFiles(root, files); - const inputs: unknown[] = [relative(filename)]; + const inputs: Array = [relative(filename)]; for (const file of files) { const config = { ...file.config }; delete config.extends; inputs.push([relative(file.filename), config, file.extendsPaths.map(relative)]); } - const serialized = JSON.stringify(inputs, (_key, value) => { - if (value && typeof value === 'object' && !Array.isArray(value)) { + const serialized = JSON.stringify(inputs, (_key, value: JsonValue) => { + if (isObjectValue(value)) { return Object.fromEntries( Object.keys(value) .toSorted() @@ -270,7 +269,7 @@ function relativeImport(from: string, to: string): string { function printConfig( config: OxlintConfig, - inheritedNames: string[], + inheritedNames: Array, { pluginExpression, ownerConfigName, @@ -343,15 +342,23 @@ export function prepareOxlintConfigModules( const viteConfigDir = path.dirname(viteConfigPath); const source = fs.readFileSync(viteConfigPath, 'utf8'); const names = new Set(); - const { ast } = JSON.parse(analyzeMigrationSource(viteConfigPath, source), (key, value) => { - if (key === 'name' && typeof value === 'string') { - names.add(value); - } - return value; - }) as { ast: { node: Program } }; + const analysis: unknown = JSON.parse( + analyzeMigrationSource(viteConfigPath, source), + (key, value: unknown) => { + if (key === 'name' && typeof value === 'string') { + names.add(value); + } + return value; + }, + ); + const ast = + isJsonObject(analysis) && isObjectValue(analysis.ast) && isObjectValue(analysis.ast.node) + ? analysis.ast.node + : undefined; if ( /\.c[jt]s$/.test(viteConfigPath) || - !ast.node.body.some((node) => node.type === 'ExportDefaultDeclaration') + !Array.isArray(ast?.body) || + !ast.body.some((node) => isObjectValue(node) && node.type === 'ExportDefaultDeclaration') ) { throw new Error('Shared Oxlint configs require a Vite config with an ESM default export'); } @@ -428,7 +435,7 @@ export function prepareOxlintConfigModules( const inherited = file.extends.map((child, index) => { const name = `oxlintConfig${index + 1}`; imports.push( - `import ${name} from ${JSON.stringify(relativeImport(filename, generate(child, sourceConfig.extends![index])))};`, + `import ${name} from ${JSON.stringify(relativeImport(filename, generate(child, sourceConfig.extends?.[index] ?? child.config)))};`, ); return name; }); @@ -454,7 +461,7 @@ export function prepareOxlintConfigModules( return filename; } - const imports: string[] = []; + const imports: Array = []; let nextName = 1; const inherited = importedFiles.map((file, index) => { let name: string; @@ -463,7 +470,7 @@ export function prepareOxlintConfigModules( } while (names.has(name)); names.add(name); imports.push( - `import ${name} from ${JSON.stringify(relativeImport(viteConfigPath, generate(file, config.extends![index])))};`, + `import ${name} from ${JSON.stringify(relativeImport(viteConfigPath, generate(file, config.extends?.[index] ?? file.config)))};`, ); return name; }); diff --git a/packages/cli/src/migration/migrator/oxnode.ts b/packages/cli/src/migration/migrator/oxnode.ts index cb1311873e..5d32ac770f 100644 --- a/packages/cli/src/migration/migrator/oxnode.ts +++ b/packages/cli/src/migration/migrator/oxnode.ts @@ -3,19 +3,22 @@ import os from 'node:os'; import path from 'node:path'; import { styleText } from 'node:util'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { + confirm as promptConfirm, + isCancel, + log as promptLog, +} from '@voidzero-dev/vite-plus-prompts'; -import { type WorkspacePackage } from '../../types/index.ts'; +import type { WorkspacePackage } from '../../types/index.ts'; import { cancelAndExit } from '../../utils/prompts.ts'; import { WATCH_OPTIONS_WITH_VALUE } from '../../vpx-script.ts'; +import type { ScriptRunnerCommandRewrite, ScriptRunnerMigration } from '../migrator.ts'; import { detectScriptRunnerProject, migrateScriptRunnerToVpx, rewriteScriptRunnerCommand, - type ScriptRunnerCommandRewrite, - type ScriptRunnerMigration, } from '../migrator.ts'; -import { type MigrationReport } from '../report.ts'; +import type { MigrationReport } from '../report.ts'; // Match commands and every core subpath conservatively. Only --import register is // converted; other loaders and APIs still need the standalone packages. @@ -59,7 +62,7 @@ function isOxnodeRegister(option: string, value: string): boolean { return option === '--import' && /^@oxc-node\/core\/register(?:\.mjs)?$/.test(value); } -function oxnodeEnvironmentReason(assignments: readonly string[]): string | undefined { +function oxnodeEnvironmentReason(assignments: ReadonlyArray): string | undefined { for (const assignment of assignments) { const separator = assignment.indexOf('='); const name = assignment.slice(0, separator).toUpperCase(); @@ -178,16 +181,16 @@ export function rewriteOxnodeCommand(command: string, cwd?: string): ScriptRunne export function detectOxnodeProject( rootDir: string, - packages?: readonly WorkspacePackage[], + packages?: ReadonlyArray, ): boolean { return detectScriptRunnerProject(OXNODE_RUNNER, rootDir, packages); } export function migrateOxnodeToVpx( rootDir: string, - packages?: readonly WorkspacePackage[], + packages?: ReadonlyArray, report?: MigrationReport, -): { changed: boolean; dependencyRemoved: boolean } { +) { const result = migrateScriptRunnerToVpx(OXNODE_RUNNER, rootDir, packages, report); if (report && result.scriptsChanged) { report.oxnodeMigrated = true; @@ -197,7 +200,7 @@ export function migrateOxnodeToVpx( export async function confirmOxnodeMigration(interactive: boolean): Promise { if (interactive) { - const confirmed = await prompts.confirm({ + const confirmed = await promptConfirm({ message: 'Migrate oxnode scripts to Vite+?\n ' + styleText( @@ -206,11 +209,11 @@ export async function confirmOxnodeMigration(interactive: boolean): Promise; - 'lint-staged'?: Record; + 'lint-staged'?: Record>; devDependencies?: Record; dependencies?: Record; peerDependencies?: Record; @@ -70,31 +71,32 @@ export function rewritePackageJson( browserCatalogAdditions: ReadonlySet = new Set(), // Bundled browser packages that this package still imports. retainedBrowserPackages?: ReadonlySet, -): Record | null { +): Record> | null { if (pkg.scripts) { - const updated = rewriteScripts( - JSON.stringify(pkg.scripts), - getScriptRulesYaml(skipStagedMigration), + const updated = rewriteScriptMap(pkg.scripts, (serialized) => + rewriteScripts(serialized, getScriptRulesYaml(skipStagedMigration)), ); if (updated) { - pkg.scripts = JSON.parse(updated); + pkg.scripts = updated; } } // Extract staged config from package.json (lint-staged) → will be merged into vite.config.ts. // The lint-staged key is NOT deleted here — it's removed by the caller only after // the merge into vite.config.ts succeeds, to avoid losing config on merge failure. - let extractedStagedConfig: Record | null = null; + let extractedStagedConfig: Record> | null = null; if (!skipStagedMigration && pkg['lint-staged']) { const config = pkg['lint-staged']; - const updated = rewriteScripts(JSON.stringify(config), readRulesYaml()); - extractedStagedConfig = updated ? JSON.parse(updated) : config; + const updated = rewriteScriptMap(config, (serialized) => + rewriteScripts(serialized, readRulesYaml()), + ); + extractedStagedConfig = updated ?? config; } const supportCatalog = !!isMonorepo && packageManager !== PackageManager.npm; let needVitePlus = false; - const dependencyGroups: { + const dependencyGroups: Array<{ dependencyField: PackageJsonDependencyField; dependencies: Record | undefined; - }[] = [ + }> = [ { dependencyField: 'devDependencies', dependencies: pkg.devDependencies }, { dependencyField: 'dependencies', dependencies: pkg.dependencies }, { dependencyField: 'peerDependencies', dependencies: pkg.peerDependencies }, @@ -199,7 +201,7 @@ export function rewritePackageJson( if ( ownsOxlintApi && (dependencyField === 'peerDependencies' || dependencyField === 'dependencies') && - (OXLINT_PLUGIN_API_PACKAGES as readonly string[]).includes(name) + (OXLINT_PLUGIN_API_PACKAGES as ReadonlyArray).includes(name) ) { // A `catalog:` reference would dangle once the catalog entry for a // REMOVE_PACKAGES name is dropped, and the next install fails. Resolve diff --git a/packages/cli/src/migration/migrator/prettier.ts b/packages/cli/src/migration/migrator/prettier.ts index 2c501aa15b..72ae8afc36 100644 --- a/packages/cli/src/migration/migrator/prettier.ts +++ b/packages/cli/src/migration/migrator/prettier.ts @@ -2,10 +2,14 @@ import fs from 'node:fs'; import path from 'node:path'; import { styleText } from 'node:util'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { + confirm as promptConfirm, + isCancel, + log as promptLog, +} from '@voidzero-dev/vite-plus-prompts'; import { hasConfigKey, removeConfigKey, rewritePrettier } from '../../../binding/index.js'; -import { type WorkspacePackage } from '../../types/index.ts'; +import type { WorkspacePackage } from '../../types/index.ts'; import { getVpCommand, runCommandSilently } from '../../utils/command.ts'; import { editJsonFile, readJsonFile } from '../../utils/json.ts'; import { displayRelative } from '../../utils/path.ts'; @@ -13,16 +17,10 @@ import { cancelAndExit } from '../../utils/prompts.ts'; import { getSilentSpinner, getSpinner } from '../../utils/spinner.ts'; import { PRETTIER_CONFIG_FILES, PRETTIER_PACKAGE_JSON_CONFIG, detectConfigs } from '../detector.ts'; import { hasOnlyInjectedDefaults, rewriteToolLintStagedConfigFiles } from '../migrator.ts'; -import { type MigrationReport } from '../report.ts'; -import { warnMigration } from './shared.ts'; +import type { MigrationReport } from '../report.ts'; +import { rewritePackageScriptFields, warnMigration } from './shared.ts'; -export function detectPrettierProject( - projectPath: string, - packages?: WorkspacePackage[], -): { - hasDependency: boolean; - configFile?: string; -} { +export function detectPrettierProject(projectPath: string, packages?: Array) { const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { return { hasDependency: false }; @@ -81,21 +79,21 @@ async function runPrettierMigrateStep( stderr.includes('Only JSON format is supported for `.prettierrc`.')); spinner.stop(unsupportedConfig ? 'Prettier migration skipped' : failMessage); if (stderr) { - prompts.log.warn(`⚠ ${stderr}`); + promptLog.warn(`⚠ ${stderr}`); } if (unsupportedConfig) { - prompts.log.info( + promptLog.info( 'Keeping Prettier. Convert its config to JSON or JS and run `vp migrate --full` to migrate it later.', ); return 'skipped'; } - prompts.log.info(manualHint); + promptLog.info(manualHint); return 'failed'; } return 'migrated'; } catch { spinner.stop(failMessage); - prompts.log.info(manualHint); + promptLog.info(manualHint); return 'failed'; } } @@ -104,7 +102,7 @@ export async function migratePrettierToOxfmt( projectPath: string, interactive: boolean, prettierConfigFile?: string, - packages?: WorkspacePackage[], + packages?: Array, options?: { silent?: boolean; report?: MigrationReport }, ): Promise<'migrated' | 'skipped' | 'failed'> { const spinner = options?.silent ? getSilentSpinner() : getSpinner(interactive); @@ -168,7 +166,9 @@ export async function migratePrettierToOxfmt( if (tempPrettierConfig) { try { fs.unlinkSync(tempPrettierConfig); - } catch {} + } catch { + // A failed conversion may already have removed its temporary config. + } } } } @@ -220,7 +220,7 @@ function deletePrettierConfigFiles( report.removedConfigCount++; } if (!silent) { - prompts.log.success(`✔ Removed ${displayRelative(configPath)}`); + promptLog.success(`✔ Removed ${displayRelative(configPath)}`); } } } @@ -237,7 +237,7 @@ function deletePrettierConfigFiles( report.removedConfigCount++; } if (!silent) { - prompts.log.success(`✔ Removed ${displayRelative(configPath)}`); + promptLog.success(`✔ Removed ${displayRelative(configPath)}`); } } } @@ -259,7 +259,7 @@ function rewritePrettierPackageJson(packageJsonPath: string): void { devDependencies?: Record; dependencies?: Record; scripts?: Record; - 'lint-staged'?: Record; + 'lint-staged'?: Record>; }>(packageJsonPath, (pkg) => { let changed = false; // Remove prettier and prettier-plugin-* dependencies @@ -279,21 +279,8 @@ function rewritePrettierPackageJson(packageJsonPath: string): void { } } } - if (pkg.scripts) { - const updated = rewritePrettier(JSON.stringify(pkg.scripts)); - if (updated) { - pkg.scripts = JSON.parse(updated); - changed = true; - } - } - if (pkg['lint-staged']) { - const updated = rewritePrettier(JSON.stringify(pkg['lint-staged'])); - if (updated) { - pkg['lint-staged'] = JSON.parse(updated); - changed = true; - } - } - return changed ? pkg : undefined; + const scriptsChanged = rewritePackageScriptFields(pkg, rewritePrettier); + return changed || scriptsChanged ? pkg : undefined; }); } @@ -302,14 +289,14 @@ function rewritePrettierLintStagedConfigFiles(projectPath: string, report?: Migr } export function warnPackageLevelPrettier() { - prompts.log.warn( + promptLog.warn( 'Prettier detected in workspace packages but no root config found. Package-level Prettier must be migrated manually.', ); } export async function confirmPrettierMigration(interactive: boolean): Promise { if (interactive) { - const confirmed = await prompts.confirm({ + const confirmed = await promptConfirm({ message: 'Migrate Prettier to Oxfmt?\n ' + styleText( @@ -318,19 +305,19 @@ export async function confirmPrettierMigration(interactive: boolean): Promise, ): Promise { const prettierProject = detectPrettierProject(projectPath, packages); if (!prettierProject.hasDependency) { diff --git a/packages/cli/src/migration/migrator/script-runner.ts b/packages/cli/src/migration/migrator/script-runner.ts index 8d68ee0894..69f465ee9b 100644 --- a/packages/cli/src/migration/migrator/script-runner.ts +++ b/packages/cli/src/migration/migrator/script-runner.ts @@ -3,16 +3,18 @@ import path from 'node:path'; import { parse as parseJsonc } from 'jsonc-parser'; -import { type LiteralCommandToken, parseLiteralCommands } from '../../../binding/index.js'; -import { type WorkspacePackage } from '../../types/index.ts'; -import { editJsonFile, isJsonFile, readJsonFile } from '../../utils/json.ts'; +import type { LiteralCommandToken } from '../../../binding/index.js'; +import { parseLiteralCommands } from '../../../binding/index.js'; +import type { WorkspacePackage } from '../../types/index.ts'; +import type { JsonObject, JsonValue } from '../../utils/json.ts'; +import { editJsonFile, isJsonFile, readJsonValue, writeJsonFile } from '../../utils/json.ts'; import { readNearestPackageJson } from '../../utils/package.ts'; import { displayRelative } from '../../utils/path.ts'; import { NODE_OPTIONS_WITH_VALUE, SCRIPT_EXTENSIONS } from '../../vpx-script.ts'; import { sourceTreeMatches } from '../migrator.ts'; -import { type MigrationReport } from '../report.ts'; +import type { MigrationReport } from '../report.ts'; +import type { DependencyBag } from './shared.ts'; import { - type DependencyBag, getCommandStartIndex, isPlainRecord, LINT_STAGED_JSON_CONFIG_FILES, @@ -25,9 +27,9 @@ import { /** Runner-specific behavior; parsing, file edits, and dependency retention are shared. */ export interface ScriptRunnerMigration { name: string; - aliases?: readonly string[]; + aliases?: ReadonlyArray; watchSubcommand?: boolean; - dependencies: readonly string[]; + dependencies: ReadonlyArray; commandPattern: RegExp; loaderPattern: RegExp; envShebang: RegExp; @@ -43,35 +45,35 @@ export interface ScriptRunnerMigration { dropOptions?: ReadonlySet; optionsWithValue?: ReadonlySet; testWithoutFilesReason: string; - envKeepReason: (assignments: readonly string[]) => string | undefined; + envKeepReason: (assignments: ReadonlyArray) => string | undefined; scriptKeepReason?: (cwd: string | undefined, script: string) => string | undefined; isLoader?: (option: string, value: string) => boolean; /** Loader imports that can keep Node.js and use the public registration entry. */ isRegister?: (option: string, value: string) => boolean; - registerEnvKeepReason?: (assignments: readonly string[]) => string | undefined; + registerEnvKeepReason?: (assignments: ReadonlyArray) => string | undefined; registerKeepOptions?: ReadonlyMap; registerPreloadKeepReason?: (option: string, value: string) => string | undefined; registerInlineCodeKeepReason?: (code: string) => string | undefined; /** Require a literal Node.js invocation when configuration preflight depends on its argv. */ registerEnvRequiresNode?: boolean; prepareRun?: ( - args: readonly string[], + args: ReadonlyArray, context: { cwd: string | undefined; - environment: readonly string[]; + environment: ReadonlyArray; nodeLoader: boolean; executable: string; shebang?: boolean; publicRegister?: boolean; /** Original literal NODE_OPTIONS arguments, or undefined when they cannot be parsed. */ - nodeOptionsArgs?: readonly string[]; + nodeOptionsArgs?: ReadonlyArray; }, ) => { keepReason?: string; /** Argument indices after the executable; no value removes that argument. */ - edits?: readonly { index: number; value?: string }[]; + edits?: ReadonlyArray<{ index: number; value?: string }>; /** Options to add before the existing arguments, without changing their source ranges. */ - prependArgs?: readonly string[]; + prependArgs?: ReadonlyArray; }; /** Report unsupported uses even when no command can be converted. */ detectKeptUses?: boolean; @@ -164,7 +166,7 @@ const COMMAND_LAUNCHERS = new Map boolean>([ export interface ScriptRunnerCommandRewrite { command: string; /** Why the runner stays in part of the command. */ - kept: string[]; + kept: Array; } interface Edit { @@ -175,11 +177,11 @@ interface Edit { interface Rewrite { command: string; - environment: readonly string[]; + environment: ReadonlyArray; /** The directory the next segment runs in, or undefined when it is not known. */ cwd?: string; - edits: Edit[]; - kept: string[]; + edits: Array; + kept: Array; /** Package scripts already being checked through an inherited preload. */ checkingScripts: ReadonlySet; } @@ -192,7 +194,7 @@ export function rewriteScriptRunnerCommand( runner: ScriptRunnerMigration, command: string, cwd?: string, - environment: readonly string[] = [], + environment: ReadonlyArray = [], checkingScripts: ReadonlySet = new Set(), ): ScriptRunnerCommandRewrite { if (!runner.commandPattern.test(command) && !runner.envKeepReason(environment)) { @@ -223,7 +225,7 @@ export function rewriteScriptRunnerCommand( function rewriteSegment( runner: ScriptRunnerMigration, rewrite: Rewrite, - tokens: LiteralCommandToken[], + tokens: Array, ): void { const values = tokens.map(({ value }) => value); // Environment assignments and cross-env stay in front of the command. @@ -294,7 +296,7 @@ function rewriteSegment( } else if (shell || launcher) { const commands = shell ? tokens.slice(start) - : tokens.slice(start + 1).filter((_, index) => launcher!(values[start + index])); + : tokens.slice(start + 1).filter((_, index) => launcher?.(values[start + index])); let checked = commands.length > 0; for (const token of commands) { if (!rewriteQuotedCommand(runner, rewrite, token, assignments)) { @@ -346,7 +348,7 @@ function taskKeepReason( runner: ScriptRunnerMigration, rewrite: Rewrite, name: string | undefined, - inherited: readonly string[], + inherited: ReadonlyArray, lifecycle: boolean, ): string | undefined { if (!name || !rewrite.cwd) { @@ -384,8 +386,8 @@ function taskKeepReason( function packageTaskKeepReason( runner: ScriptRunnerMigration, rewrite: Rewrite, - values: readonly string[], - inherited: readonly string[], + values: ReadonlyArray, + inherited: ReadonlyArray, ): string | undefined { const [manager, command] = values; if (!['npm', 'pnpm', 'yarn', 'bun'].includes(manager)) { @@ -405,10 +407,10 @@ function packageTaskKeepReason( return taskKeepReason(runner, rewrite, name, inherited, true); } -function applyEdits(command: string, pending: readonly Edit[]): string { +function applyEdits(command: string, pending: ReadonlyArray): string { let rewritten = command; // An option normalization and a loader removal can cover the same whitespace. - const edits: Edit[] = []; + const edits: Array = []; for (const edit of pending.toSorted((a, b) => b.start - a.start || b.end - a.end)) { const previous = edits.at(-1); if (previous?.text === '' && edit.text === '' && edit.end >= previous.start) { @@ -433,24 +435,24 @@ function literalEdit(command: string, token: LiteralCommandToken, value: string) const preserveQuote = prefix !== '' || raw.endsWith(quote); let content = value.slice(prefix.length); if (quote === "'" && preserveQuote) { - content = `'${content.replaceAll("'", "'\\''")}'`; + content = `'${content.replaceAll("'", String.raw`'\''`)}'`; } else if ((quote === '"' && preserveQuote) || !/^[\w./=:-]+$/.test(content)) { - content = `"${content.replaceAll(/[\\"$`]/g, '\\$&')}"`; + content = `"${content.replaceAll(/[\\"$`]/g, String.raw`\$&`)}"`; } return { start: token.start, end: token.end, text: `${prefix}${content}` }; } interface EnvironmentOptions { - replacements: { index: number; value: string }[]; - preloads: string[]; - args?: string[]; + replacements: Array<{ index: number; value: string }>; + preloads: Array; + args?: Array; keepReason?: string; } /** NODE_OPTIONS uses double quotes and spaces, not shell single quotes or tab separators. */ function scanEnvironmentOptions( runner: ScriptRunnerMigration, - assignments: readonly string[], + assignments: ReadonlyArray, ): EnvironmentOptions { const result: EnvironmentOptions = { replacements: [], preloads: [], args: [] }; for (const [index, assignment] of assignments.entries()) { @@ -501,7 +503,7 @@ function optionName(arg: string): string { } /** Remove `tokens[index]` with the space before it. */ -function removal(tokens: LiteralCommandToken[], index: number): Edit { +function removal(tokens: Array, index: number): Edit { return { start: tokens[index - 1]?.end ?? tokens[index].start, end: tokens[index].end, text: '' }; } @@ -514,8 +516,8 @@ function runKeepReason( runner: ScriptRunnerMigration, cwd: string | undefined, test: boolean, - positionals: readonly string[], - preloads: readonly string[], + positionals: ReadonlyArray, + preloads: ReadonlyArray, ): string | undefined { const [entry] = positionals; if (entry === undefined) { @@ -538,11 +540,11 @@ function runKeepReason( function rewriteRunner( runner: ScriptRunnerMigration, rewrite: Rewrite, - tokens: LiteralCommandToken[], + tokens: Array, first: number, start: number, keepReason: string | undefined, - environment: readonly string[], + environment: ReadonlyArray, ): void { if (keepReason) { rewrite.kept.push(keepReason); @@ -575,11 +577,11 @@ function rewriteRunner( function rewriteNodeLoader( runner: ScriptRunnerMigration, rewrite: Rewrite, - tokens: LiteralCommandToken[], + tokens: Array, first: number, start: number, keepReason: string | undefined, - environment: readonly string[], + environment: ReadonlyArray, environmentOptions: EnvironmentOptions, ): void { const original = scanOptions(runner, tokens, start + 1, false); @@ -667,12 +669,12 @@ function rewriteNodeLoader( function prepareRun( runner: ScriptRunnerMigration, rewrite: Rewrite, - tokens: LiteralCommandToken[], + tokens: Array, start: number, - environment: readonly string[], + environment: ReadonlyArray, nodeLoader: boolean, publicRegister?: EnvironmentOptions, -): { tokens: LiteralCommandToken[]; edits: Edit[]; keepReason?: string } { +) { const prepared = runner.prepareRun?.( tokens.slice(start + 1).map(({ value }) => value), { @@ -684,7 +686,7 @@ function prepareRun( nodeOptionsArgs: publicRegister?.args, }, ); - const edits: Edit[] = []; + const edits: Array = []; const added = prepared?.prependArgs?.map(quoteArgument) ?? []; if ( added.some((value) => value === undefined) || @@ -708,7 +710,10 @@ function prepareRun( edits.push(removal(tokens, index)); return []; } - const text = quoteArgument(change.value)!; + const text = quoteArgument(change.value); + if (text === undefined) { + throw new Error('Expected a validated shell argument'); + } edits.push({ start: token.start, end: token.end, text }); return [{ ...token, value: change.value }]; }); @@ -746,22 +751,22 @@ interface ScannedOptions { /** Where the entry, or with `--test` the test files, start. */ entryIndex: number; /** Runner-specific options and loader flags to remove. */ - removals: Edit[]; + removals: Array; loaders: number; runnerLoader: boolean; - imports: { token: LiteralCommandToken; value: string; option?: LiteralCommandToken }[]; + imports: Array<{ token: LiteralCommandToken; value: string; option?: LiteralCommandToken }>; registerKeepReason?: string; inlineCode: boolean; runScript?: string; /** Local `--require` and `--import` modules, which load before the scripts. */ - preloads: string[]; + preloads: Array; keepReason?: string; test: boolean; watch: boolean; } -function importEdits(command: string, scanned: ScannedOptions): Edit[] { - const edits: Edit[] = []; +function importEdits(command: string, scanned: ScannedOptions): Array { + const edits: Array = []; for (const { token, value, option } of scanned.imports) { if (option) { edits.push(literalEdit(command, option, '--import')); @@ -774,7 +779,7 @@ function importEdits(command: string, scanned: ScannedOptions): Edit[] { /** Read options from the executable to the entry file. */ function scanOptions( runner: ScriptRunnerMigration, - tokens: LiteralCommandToken[], + tokens: Array, index: number, directRunner: boolean, ): ScannedOptions { @@ -873,7 +878,7 @@ function scanOptions( function runReason( runner: ScriptRunnerMigration, cwd: string | undefined, - tokens: LiteralCommandToken[], + tokens: Array, scanned: ScannedOptions, watch: boolean, ): string | undefined { @@ -897,7 +902,7 @@ function rewriteQuotedCommand( runner: ScriptRunnerMigration, rewrite: Rewrite, token: LiteralCommandToken, - environment: readonly string[], + environment: ReadonlyArray, ): boolean { const raw = rewrite.command.slice(token.start, token.end); const quote = raw[0]; @@ -919,7 +924,7 @@ function rewriteQuotedCommand( } /** The commands in a scripts or lint-staged record. */ -function recordCommands(record: unknown): string[] { +function recordCommands(record: JsonValue | undefined): Array { if (!isPlainRecord(record)) { return []; } @@ -929,11 +934,11 @@ function recordCommands(record: unknown): string[] { } /** The commands a package.json runs: its scripts and lint-staged tasks. */ -function packageCommands(pkg: Record): string[] { +function packageCommands(pkg: JsonObject): Array { return [...recordCommands(pkg.scripts), ...recordCommands(pkg['lint-staged'])]; } -function lintStagedJsonFiles(dir: string): string[] { +function lintStagedJsonFiles(dir: string): Array { return LINT_STAGED_JSON_CONFIG_FILES.map((name) => path.join(dir, name)).filter( (file) => fs.existsSync(file) && isJsonFile(file), ); @@ -952,7 +957,7 @@ function ownsRunnerAtRuntime(runner: ScriptRunnerMigration, pkg: DependencyBag): ); } -function packageDirs(rootDir: string, packages?: readonly WorkspacePackage[]): string[] { +function packageDirs(rootDir: string, packages?: ReadonlyArray): Array { return [rootDir, ...(packages ?? []).map((pkg) => path.join(rootDir, pkg.path))]; } @@ -962,7 +967,7 @@ function packageDirs(rootDir: string, packages?: readonly WorkspacePackage[]): s export function detectScriptRunnerProject( runner: ScriptRunnerMigration, rootDir: string, - packages?: readonly WorkspacePackage[], + packages?: ReadonlyArray, ): boolean { return packageDirs(rootDir, packages).some((dir) => { const pkg = readPackageJsonIfExists(path.join(dir, 'package.json')); @@ -971,7 +976,7 @@ export function detectScriptRunnerProject( } const commands = [ ...packageCommands(pkg), - ...lintStagedJsonFiles(dir).flatMap((file) => recordCommands(readJsonFile(file))), + ...lintStagedJsonFiles(dir).flatMap((file) => recordCommands(readJsonValue(file))), ]; return ( commands.some((command) => @@ -1003,14 +1008,17 @@ export function detectScriptRunnerProject( /** Rewrite each command of a scripts or lint-staged record; returns whether one changed. */ function rewriteCommandRecord( runner: ScriptRunnerMigration, - record: Record, + record: JsonObject, label: string, cwd: string, report?: MigrationReport, ): boolean { let edited = false; for (const [key, value] of Object.entries(record)) { - const commands: unknown[] = Array.isArray(value) ? value : [value]; + if (value === undefined) { + continue; + } + const commands = Array.isArray(value) ? value : [value]; const rewritten = commands.map((command) => { if (typeof command !== 'string') { return command; @@ -1048,16 +1056,17 @@ function rewriteRunnerShebang( if (entry === undefined) { return { reason: 'the script path needs shell escaping that vp migrate does not support' }; } - const shebangRunner = runner.prepareRun + const prepareRun = runner.prepareRun; + const shebangRunner = prepareRun ? { ...runner, prepareRun: ( - args: readonly string[], + args: ReadonlyArray, context: Parameters>[1], ) => // Inspect entry-relative configuration; shebang mode rejects settings // that would need a path pinned relative to the caller. - runner.prepareRun!(args, { ...context, cwd: path.dirname(file), shebang: true }), + prepareRun(args, { ...context, cwd: path.dirname(file), shebang: true }), } : runner; // The caller supplies the runtime working directory, not the script's location. @@ -1308,7 +1317,9 @@ function jsonUsesRunner(runner: ScriptRunnerMigration, value: unknown, commands: ([key, item]) => jsonUsesRunner(runner, item, commands) || (LOADER_SETTINGS.has(key) && - [item].flat().some((loader) => runner.loaderPattern.test(String(loader)))), + [item] + .flat() + .some((loader) => typeof loader === 'string' && runner.loaderPattern.test(loader))), ) ); } @@ -1317,11 +1328,11 @@ function jsonUsesRunner(runner: ScriptRunnerMigration, value: unknown, commands: export function migrateScriptRunnerToVpx( runner: ScriptRunnerMigration, rootDir: string, - packages?: readonly WorkspacePackage[], + packages?: ReadonlyArray, report?: MigrationReport, -): { changed: boolean; dependencyRemoved: boolean; scriptsChanged: boolean } { +) { let changed = false; - const migrated: string[] = []; + const migrated: Array = []; for (const dir of packageDirs(rootDir, packages)) { const packageJsonPath = path.join(dir, 'package.json'); const pkg = readPackageJsonIfExists(packageJsonPath); @@ -1359,11 +1370,14 @@ export function migrateScriptRunnerToVpx( return edited ? json : undefined; }); for (const file of lintStagedJsonFiles(dir)) { - editJsonFile(file, (config) => { - const edited = rewriteCommandRecord(runner, config, displayRelative(file), dir, report); - changed ||= edited; - return edited ? config : undefined; - }); + const config = readJsonValue(file); + if ( + isPlainRecord(config) && + rewriteCommandRecord(runner, config, displayRelative(file), dir, report) + ) { + writeJsonFile(file, config); + changed = true; + } } if (rewriteRunnerShebangs(runner, dir, report)) { changed = true; @@ -1389,7 +1403,7 @@ export function migrateScriptRunnerToVpx( } editJsonFile(packageJsonPath, (json) => { for (const dependency of runner.dependencies) { - delete json.devDependencies![dependency]; + delete json.devDependencies?.[dependency]; } return json; }); diff --git a/packages/cli/src/migration/migrator/setup.ts b/packages/cli/src/migration/migrator/setup.ts index a124ba8f25..d6f98791a1 100644 --- a/packages/cli/src/migration/migrator/setup.ts +++ b/packages/cli/src/migration/migrator/setup.ts @@ -1,16 +1,17 @@ import fs from 'node:fs'; import path from 'node:path'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { log as promptLog } from '@voidzero-dev/vite-plus-prompts'; import { globSync } from 'tinyglobby'; import { normalize } from 'verkit'; import { parse as parseYaml } from 'yaml'; -import { type DownloadPackageManagerResult } from '../../../binding/index.js'; +import type { DownloadPackageManagerResult } from '../../../binding/index.js'; import { SETUP_VP_VERSION } from '../../utils/constants.ts'; +import type { JsonObject } from '../../utils/json.ts'; import { editJsonFile } from '../../utils/json.ts'; import { detectConfigs } from '../detector.ts'; -import { type MigrationReport } from '../report.ts'; +import type { MigrationReport } from '../report.ts'; import { isPlainRecord, warnMigration } from './shared.ts'; export function setPackageManager( @@ -23,7 +24,7 @@ export function setPackageManager( // is written to `devEngines.packageManager` (the recommended standard field). editJsonFile<{ packageManager?: string; - devEngines?: { packageManager?: unknown; [key: string]: unknown }; + devEngines?: JsonObject; }>(path.join(projectDir, 'package.json'), (pkg) => { if (!pkg.packageManager && !pkg.devEngines?.packageManager) { // Only spread a well-formed object: spreading a malformed devEngines value @@ -89,7 +90,7 @@ function isCompositeActionFile(filePath: string): boolean { * Action metadata must declare `runs.using: composite`. Paths are absolute, and * filename matching is case-insensitive. */ -function collectGithubActionFiles(projectPath: string): string[] { +function collectGithubActionFiles(projectPath: string): Array { const globOptions = { cwd: path.join(projectPath, '.github'), absolute: true, @@ -122,14 +123,17 @@ const SETUP_VP_V1_RE = * * Returns the project-relative paths of the updated files. */ -export function migrateSetupVpVersion(projectPath: string, report?: MigrationReport): string[] { - const updatedFiles: string[] = []; +export function migrateSetupVpVersion( + projectPath: string, + report?: MigrationReport, +): Array { + const updatedFiles: Array = []; for (const filePath of collectGithubActionFiles(projectPath)) { const relativePath = path.relative(projectPath, filePath); try { const original = fs.readFileSync(filePath, 'utf8'); - const rewritten = original.replace( + const rewritten = original.replaceAll( SETUP_VP_V1_RE, `$1$2voidzero-dev/setup-vp@${SETUP_VP_VERSION}$2`, ); @@ -182,7 +186,7 @@ export function migrateNodeVersionManagerFile( report.manualSteps.push('Remove the "volta" field from package.json'); report.nodeVersionFileMigrated = true; } else { - prompts.log.info('You can now remove the "volta" field from package.json manually.'); + promptLog.info('You can now remove the "volta" field from package.json manually.'); } return true; } diff --git a/packages/cli/src/migration/migrator/shared.ts b/packages/cli/src/migration/migrator/shared.ts index d26c3a057c..f136365131 100644 --- a/packages/cli/src/migration/migrator/shared.ts +++ b/packages/cli/src/migration/migrator/shared.ts @@ -1,7 +1,7 @@ import fs from 'node:fs'; import path from 'node:path'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { log as promptLog } from '@voidzero-dev/vite-plus-prompts'; import type { OxlintConfig } from 'oxlint'; import { coerce, isLessThan, satisfies, tryParse } from 'verkit'; @@ -11,10 +11,15 @@ import { VITE_PLUS_OVERRIDE_PACKAGES, coreAliasVersion, } from '../../utils/constants.ts'; +import { parseJsonObject } from '../../utils/json-value.ts'; +import type { JsonObject, JsonValue } from '../../utils/json.ts'; import { readJsonFile } from '../../utils/json.ts'; import { detectPackageMetadata } from '../../utils/package.ts'; import { displayRelative } from '../../utils/path.ts'; -import { addManualStep, addMigrationWarning, type MigrationReport } from '../report.ts'; +import type { YamlMapping } from '../../utils/yaml.ts'; +import { isYamlMapping } from '../../utils/yaml.ts'; +import type { MigrationReport } from '../report.ts'; +import { addManualStep, addMigrationWarning } from '../report.ts'; export interface RetainedImportDependencies { /** Package directories that need a direct Vitest dependency. */ @@ -26,7 +31,7 @@ export interface RetainedImportDependencies { export const DISABLED_IMPORT_RULE_CONFIG = JSON.stringify({ enabled: false, overrides: [] }); // Commands whose effects prevent literal analysis of later invocations. -export const SHELL_STATE_COMMANDS: readonly string[] = [ +export const SHELL_STATE_COMMANDS: ReadonlyArray = [ 'cd', 'pushd', 'popd', @@ -39,7 +44,7 @@ export const SHELL_STATE_COMMANDS: readonly string[] = [ ]; /** Locate the executable after a supported package-manager wrapper. */ -export function getCommandStartIndex(argv: readonly string[]): number { +export function getCommandStartIndex(argv: ReadonlyArray): number { if (!['pnpm', 'npm', 'yarn', 'bun', 'npx', 'bunx'].includes(argv[0])) { return 0; } @@ -72,9 +77,9 @@ export const OXLINT_OWNER_CONFIG_KEYS = new Set(['env', 'globals', 'settings', ' export interface OxlintConfigFile { filename: string; config: OxlintConfig; - extends: OxlintConfigFile[]; + extends: Array; // Keep declared paths as well as canonical sources for JSON fallback cleanup. - extendsPaths: string[]; + extendsPaths: Array; // A dependency must use the same generated module in its owning workspace. shared?: boolean; // A committed or previously generated module that workspace consumers can reuse. @@ -91,7 +96,7 @@ export type PreparedOxlintConfigs = Map; export interface OxlintModulePlan { configContent: string; - imports: string[]; + imports: Array; completionMarker?: string; modules: Map; } @@ -133,7 +138,7 @@ export const REMOVE_PACKAGES = [ ] as const; // A preserved browser import still needs its original dependency and catalog entry. -export function bundledPackagesToRemove(retained?: ReadonlySet): readonly string[] { +export function bundledPackagesToRemove(retained?: ReadonlySet): ReadonlyArray { return retained?.size ? REMOVE_PACKAGES.filter((name) => !retained.has(name)) : REMOVE_PACKAGES; } @@ -163,12 +168,12 @@ export const PROVIDER_OVERRIDE_DROP_NAMES = [ // When a browser provider package is removed, its runtime peer dependency // must be preserved in devDependencies so browser tests continue to work. -export const BROWSER_PROVIDER_PEER_DEPS: Record = { +export const BROWSER_PROVIDER_PEER_DEPS = { '@vitest/browser-playwright': 'playwright', }; // Packages that include runtime peer as a dependency. -const RUNTIME_PEER_INCLUDED_BY: Record = { +const RUNTIME_PEER_INCLUDED_BY = { playwright: ['@playwright/test'], }; @@ -187,7 +192,7 @@ export function findDeclaredSpec(pkg: DependencyBag, name: string): string | und export function hasProviderPeerDependency(pkg: DependencyBag, runtimePeer: string): boolean { return ( findDeclaredSpec(pkg, runtimePeer) !== undefined || - (RUNTIME_PEER_INCLUDED_BY[runtimePeer] ?? []).some( + (lookupSetting(RUNTIME_PEER_INCLUDED_BY, runtimePeer) ?? []).some( (packageName) => findDeclaredSpec(pkg, packageName) !== undefined, ) ); @@ -282,7 +287,7 @@ export function vitePeerDependencyRuleRequired( // ranges (e.g. `vitest: ^3.0.0`) are preserved — only the wrapper alias is // rewritten. For `vitest`, we substitute the vitest version vite-plus // bundles so any `catalog:` reference the user still has resolves cleanly. -export const LEGACY_WRAPPER_FALLBACK_VERSIONS: Record = { +export const LEGACY_WRAPPER_FALLBACK_VERSIONS = { vitest: VITEST_VERSION, }; @@ -352,14 +357,14 @@ export type PackageJsonDependencyField = export function warnMigration(message: string, report?: MigrationReport) { addMigrationWarning(report, message); if (!report) { - prompts.log.warn(message); + promptLog.warn(message); } } export function infoMigration(message: string, report?: MigrationReport) { addManualStep(report, message); if (!report) { - prompts.log.info(message); + promptLog.info(message); } } @@ -383,33 +388,35 @@ function checkPackageVersion(projectPath: string, name: string, minVersion: stri if (!metadata || metadata.name !== name) { return true; } - if (satisfies(metadata.version, `<${minVersion}`)) { + if (metadata.version && satisfies(metadata.version, `<${minVersion}`)) { const packageJsonFilePath = path.join(projectPath, 'package.json'); - prompts.log.error( + promptLog.error( `✘ ${name}@${metadata.version} in ${displayRelative(packageJsonFilePath)} is not supported by auto migration`, ); - prompts.log.info(`Please upgrade ${name} to version >=${minVersion} first`); + promptLog.info(`Please upgrade ${name} to version >=${minVersion} first`); return false; } return true; } export type PnpmPeerDependencyRules = { - allowAny?: string[]; + allowAny?: Array; allowedVersions?: Record; - [key: string]: unknown; + [key: string]: JsonValue | undefined; }; export type PnpmPackageJsonSettings = { overrides?: Record; peerDependencyRules?: PnpmPeerDependencyRules; allowBuilds?: Record; - onlyBuiltDependencies?: string[]; - [key: string]: unknown; + onlyBuiltDependencies?: Array; + [key: string]: JsonValue | undefined; }; -export function isPlainRecord(value: unknown): value is Record { - return value !== null && typeof value === 'object' && !Array.isArray(value); +export function isPlainRecord(value: JsonValue | undefined): value is JsonObject; +export function isPlainRecord(value: unknown): value is YamlMapping; +export function isPlainRecord(value: unknown): value is YamlMapping { + return isYamlMapping(value); } export type DependencyBag = { @@ -485,9 +492,9 @@ export function packageOwnsOxlintApi(pkg: DependencyBag): boolean { */ export function collectOxlintOwnerDirs( rootDir: string, - packages?: readonly { path: string }[], -): string[] { - const owners: string[] = []; + packages?: ReadonlyArray<{ path: string }>, +): Array { + const owners: Array = []; const candidates = [rootDir, ...(packages ?? []).map((pkg) => path.join(rootDir, pkg.path))]; for (const dir of candidates) { const pkg = readPackageJsonIfExists(path.join(dir, 'package.json')); @@ -497,3 +504,50 @@ export function collectOxlintOwnerDirs( } return owners; } + +// String keys come from project files and need not name a supported tool. +export function lookupSetting(table: Readonly>, key: string): T | undefined { + return Object.hasOwn(table, key) ? table[key] : undefined; +} + +type NativeScriptRewrite = (serialized: string) => string | null | undefined; +type Scripts = Record; +type StagedCommands = Record>; + +// The native script rewriters change strings in place and preserve all other +// JSON values, including non-command entries in user-authored configuration. +export function rewriteScriptMap( + commands: Scripts, + rewrite: NativeScriptRewrite, +): Scripts | undefined; +export function rewriteScriptMap( + commands: StagedCommands, + rewrite: NativeScriptRewrite, +): StagedCommands | undefined; +export function rewriteScriptMap( + commands: JsonObject, + rewrite: NativeScriptRewrite, +): JsonObject | undefined; +export function rewriteScriptMap( + commands: JsonObject, + rewrite: NativeScriptRewrite, +): JsonObject | undefined { + const updated = rewrite(JSON.stringify(commands)); + return updated ? parseJsonObject(updated) : undefined; +} + +/** Rewrite the command fields that both ESLint and Prettier can appear in. */ +export function rewritePackageScriptFields( + pkg: { scripts?: Scripts; 'lint-staged'?: StagedCommands }, + rewrite: NativeScriptRewrite, +): boolean { + const scripts = pkg.scripts && rewriteScriptMap(pkg.scripts, rewrite); + if (scripts) { + pkg.scripts = scripts; + } + const staged = pkg['lint-staged'] && rewriteScriptMap(pkg['lint-staged'], rewrite); + if (staged) { + pkg['lint-staged'] = staged; + } + return Boolean(scripts || staged); +} diff --git a/packages/cli/src/migration/migrator/source-scan.ts b/packages/cli/src/migration/migrator/source-scan.ts index 01f2f96a59..4f8a80e47a 100644 --- a/packages/cli/src/migration/migrator/source-scan.ts +++ b/packages/cli/src/migration/migrator/source-scan.ts @@ -2,12 +2,14 @@ import fs from 'node:fs'; import path from 'node:path'; import { findRetainedVitestPackages } from '../../../binding/index.js'; -import { type WorkspacePackage } from '../../types/index.ts'; +import type { WorkspacePackage } from '../../types/index.ts'; import { VITE_PLUS_NAME } from '../../utils/constants.ts'; +import { parseJsonObject } from '../../utils/json-value.ts'; import { editJsonFile, readJsonFile } from '../../utils/json.ts'; import { detectPackageMetadata } from '../../utils/package.ts'; import { hasVitestTypesInTsconfig } from '../../utils/tsconfig.ts'; import { projectUsesVitestDirectly } from '../migrator.ts'; +import type { DependencyBag, RetainedImportDependencies } from './shared.ts'; import { DISABLED_IMPORT_RULE_CONFIG, OPT_IN_BROWSER_PROVIDERS, @@ -16,13 +18,11 @@ import { PLAYWRIGHT_PROVIDER, readPackageJsonIfExists, RETENTION_SCAN_SKIP_DIRS, - type DependencyBag, - type RetainedImportDependencies, } from './shared.ts'; -type WorkspaceProjects = { rootDir: string; packages?: readonly WorkspacePackage[] }; +type WorkspaceProjects = { rootDir: string; packages?: ReadonlyArray }; -export function getWorkspaceProjectPaths({ rootDir, packages }: WorkspaceProjects): string[] { +export function getWorkspaceProjectPaths({ rootDir, packages }: WorkspaceProjects): Array { return [rootDir, ...(packages ?? []).map((pkg) => path.join(rootDir, pkg.path))]; } @@ -88,7 +88,7 @@ export function collectRetainedImportDependencies( // `projectUsesVitestDirectly`. export function workspaceUsesVitestDirectly( rootDir: string, - packages: WorkspacePackage[] | undefined, + packages: Array | undefined, preserveNuxtVitestImports = true, protectedVitestImportOwners?: ReadonlySet, ): boolean { @@ -193,7 +193,7 @@ const PLAYWRIGHT_PROVIDER_SPECIFIER_HINTS = [ // Per-provider source-scan hint lists, used to build the `providerSourceModes` // map passed to `rewritePackageJson`. -const BROWSER_PROVIDER_SPECIFIER_HINTS: Record = { +const BROWSER_PROVIDER_SPECIFIER_HINTS = { [PLAYWRIGHT_PROVIDER]: PLAYWRIGHT_PROVIDER_SPECIFIER_HINTS, }; @@ -269,7 +269,7 @@ export function sourceTreeMatches( const skipDirs = options.skipDirs ?? VITEST_SCAN_SKIP_DIRS; const extensions = options.extensions ?? VITEST_SCAN_EXTENSIONS; function scanDir(dir: string, isRoot: boolean): boolean { - let entries: fs.Dirent[]; + let entries: Array; try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { @@ -306,10 +306,7 @@ export function sourceTreeMatches( if (entry.name === 'package.json') { // Check alias targets and inline scripts without counting dependency // declarations as uses. Serialization includes conditional targets. - const pkg = JSON.parse(content) as DependencyBag & { - imports?: unknown; - scripts?: unknown; - }; + const pkg = parseJsonObject(content); if (options.matchesPackage?.(dir, pkg)) { return true; } @@ -329,14 +326,14 @@ export function sourceTreeMatches( return scanDir(projectPath, true); } -function sourceTreeReferencesAny(projectPath: string, hints: readonly string[]): boolean { +function sourceTreeReferencesAny(projectPath: string, hints: ReadonlyArray): boolean { return sourceTreeMatches(projectPath, (content) => hints.some((hint) => content.includes(hint))); } -function findPackageTsconfigFiles(projectPath: string): string[] { - const files: string[] = []; +function findPackageTsconfigFiles(projectPath: string): Array { + const files: Array = []; const scanDir = (dir: string, isRoot: boolean): void => { - let entries: fs.Dirent[]; + let entries: Array; try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { @@ -399,7 +396,7 @@ export function usesWebdriverioProvider(projectPath: string): boolean { // no-longer-bundled) provider + its framework peer even when no dep is declared // yet (e.g. a `vite.config.ts` importing the provider via a `vite-plus/test` // shim). Mirrors `usesWebdriverioProvider`'s scan for each provider. -export function collectProviderSourceModes(projectPath: string): Record { +export function collectProviderSourceModes(projectPath: string) { const modes: Record = {}; for (const provider of OPT_IN_BROWSER_PROVIDERS) { modes[provider] = sourceTreeReferencesAny( @@ -500,7 +497,7 @@ export function collectInstallDependencyNames(pkg?: DependencyBag): Set // newly injected packages are not installed until after source cleanup. export function collectOxlintDependencyNames( rootDir: string, - packages?: readonly { path: string }[], + packages?: ReadonlyArray<{ path: string }>, ): Map> { const names = new Map>(); for (const dir of [rootDir, ...(packages ?? []).map((pkg) => path.join(rootDir, pkg.path))]) { @@ -519,7 +516,7 @@ export function collectOxlintDependencyNames( */ export function dropDeadOxlintPluginsDependency( rootDir: string, - packages?: readonly { path: string }[], + packages?: ReadonlyArray<{ path: string }>, originalDependencies: ReadonlyMap> = collectOxlintDependencyNames( rootDir, packages, diff --git a/packages/cli/src/migration/migrator/ts-node-config.ts b/packages/cli/src/migration/migrator/ts-node-config.ts index a483cad146..a99a6df493 100644 --- a/packages/cli/src/migration/migrator/ts-node-config.ts +++ b/packages/cli/src/migration/migrator/ts-node-config.ts @@ -1,26 +1,29 @@ import fs from 'node:fs'; import path from 'node:path'; -import { type ParseError, parse as parseJsonc } from 'jsonc-parser'; +import type { ParseError } from 'jsonc-parser'; +import { parse as parseJsonc } from 'jsonc-parser'; +import type { JsonObject } from '../../utils/json.ts'; +import { isJsonObject } from '../../utils/json.ts'; import { NODE_OPTIONS_WITH_VALUE } from '../../vpx-script.ts'; import { isPlainRecord } from './shared.ts'; interface TsNodeRunContext { cwd?: string; - environment: readonly string[]; + environment: ReadonlyArray; nodeLoader: boolean; executable: string; shebang?: boolean; publicRegister?: boolean; - nodeOptionsArgs?: readonly string[]; + nodeOptionsArgs?: ReadonlyArray; } interface TsNodeRunPreparation { keepReason?: string; /** Indices refer to args, excluding the executable. An absent value removes a token. */ - edits?: { index: number; value?: string }[]; - prependArgs?: string[]; + edits?: Array<{ index: number; value?: string }>; + prependArgs?: Array; } interface TsNodeOptions { @@ -123,11 +126,14 @@ function readTsNodeEnvironment( return { options, project }; } +interface ResolvedTsNodeOptions { + options?: TsNodeOptions; + compilerOptions?: JsonObject; + keepReason?: string; +} + /** Read only data; migration must not load ts-node or a project's compiler. */ -function readTsNodeOptions( - file: string, - ancestors = new Set(), -): { options?: TsNodeOptions; compilerOptions?: Record; keepReason?: string } { +function readTsNodeOptions(file: string, ancestors = new Set()): ResolvedTsNodeOptions { const keepConfig = (reason: string) => ({ keepReason: `the ts-node configuration in \`${file}\` ${reason}`, }); @@ -137,16 +143,16 @@ function readTsNodeOptions( const chain = new Set(ancestors).add(file); let config: unknown; try { - const errors: ParseError[] = []; + const errors: Array = []; config = parseJsonc(fs.readFileSync(file, 'utf8'), errors, { allowTrailingComma: true }); - if (errors.length || !isPlainRecord(config)) { + if (errors.length || !isJsonObject(config)) { return keepConfig('cannot be parsed'); } } catch { return keepConfig('cannot be read'); } let inherited: TsNodeOptions = {}; - let compilerOptions: Record = {}; + let compilerOptions: JsonObject = {}; if (config.extends !== undefined) { if ( typeof config.extends !== 'string' || @@ -195,7 +201,7 @@ function readTsNodeOptions( * transpileOnly. Keep all other compiler behavior for manual migration. */ export function prepareTsNodeRun( - args: readonly string[], + args: ReadonlyArray, context: TsNodeRunContext, ): TsNodeRunPreparation { const { cwd, nodeLoader, executable } = context; @@ -409,7 +415,7 @@ export function prepareTsNodeRun( } if ( configFile && - config.compilerOptions?.target == null && + (config.compilerOptions?.target === undefined || config.compilerOptions?.target === null) && typeof config.compilerOptions?.useDefineForClassFields !== 'boolean' ) { // An existing config disables ts-node's Node-version defaults. It then supplies diff --git a/packages/cli/src/migration/migrator/ts-node.ts b/packages/cli/src/migration/migrator/ts-node.ts index ced1b783cb..a633c9bb85 100644 --- a/packages/cli/src/migration/migrator/ts-node.ts +++ b/packages/cli/src/migration/migrator/ts-node.ts @@ -3,22 +3,25 @@ import os from 'node:os'; import path from 'node:path'; import { styleText } from 'node:util'; -import type { Program } from '@oxc-project/types'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { + confirm as promptConfirm, + isCancel, + log as promptLog, +} from '@voidzero-dev/vite-plus-prompts'; -import { analyzeMigrationSource, ResolverFactory } from '../../../binding/index.js'; -import { type WorkspacePackage } from '../../types/index.ts'; +import { ResolverFactory } from '../../../binding/index.js'; +import type { WorkspacePackage } from '../../types/index.ts'; import { cancelAndExit } from '../../utils/prompts.ts'; +import { parseSource } from '../ast-utils.ts'; +import type { ScriptRunnerCommandRewrite, ScriptRunnerMigration } from '../migrator.ts'; import { detectScriptRunnerProject, migrateScriptRunnerToVpx, prepareTsNodeRun, rewriteScriptRunnerCommand, - type ScriptRunnerCommandRewrite, - type ScriptRunnerMigration, typescriptScriptKeepReason, } from '../migrator.ts'; -import { type MigrationReport } from '../report.ts'; +import type { MigrationReport } from '../report.ts'; // Include unsupported entrypoints and package subpaths in retention scans. const TS_NODE_REFERENCE = @@ -28,12 +31,10 @@ const TS_NODE_LOADERS = /^ts-node(?:\/.*)?$/; /** Check module metadata only; migration must not execute a project's dependencies. */ function incompatibleModuleSource(file: string, source: string): string | undefined { file = fs.realpathSync(file); - const { ast } = JSON.parse(analyzeMigrationSource(file, source)) as { - ast: { node: Program }; - }; + const { program } = parseSource(file, source); let requireResolver: ResolverFactory | undefined; let importResolver: ResolverFactory | undefined; - for (const node of ast.node.body) { + for (const node of program.body) { let specifier: string; let namedOnly = false; if (node.type === 'ImportDeclaration' && node.importKind !== 'type') { @@ -197,16 +198,16 @@ export function rewriteTsNodeCommand(command: string, cwd?: string): ScriptRunne export function detectTsNodeProject( rootDir: string, - packages?: readonly WorkspacePackage[], + packages?: ReadonlyArray, ): boolean { return detectScriptRunnerProject(TS_NODE_RUNNER, rootDir, packages); } export function migrateTsNodeToVpx( rootDir: string, - packages?: readonly WorkspacePackage[], + packages?: ReadonlyArray, report?: MigrationReport, -): { changed: boolean; dependencyRemoved: boolean } { +) { const result = migrateScriptRunnerToVpx(TS_NODE_RUNNER, rootDir, packages, report); if (report && result.scriptsChanged) { report.tsNodeMigrated = true; @@ -216,7 +217,7 @@ export function migrateTsNodeToVpx( export async function confirmTsNodeMigration(interactive: boolean): Promise { if (interactive) { - const confirmed = await prompts.confirm({ + const confirmed = await promptConfirm({ message: 'Migrate ts-node scripts to Vite+?\n ' + styleText( @@ -225,11 +226,11 @@ export async function confirmTsNodeMigration(interactive: boolean): Promise): void { + promptLog.info( [ ...instructions, '', @@ -43,14 +50,7 @@ function showTsdownMigrationSkillGuidance(instructions: string[]): void { ); } -export function detectTsupProject( - projectPath: string, - packages?: WorkspacePackage[], -): { - hasDependency: boolean; - hasConfig: boolean; - configFile?: string; -} { +export function detectTsupProject(projectPath: string, packages?: Array) { const packageJsonPath = path.join(projectPath, 'package.json'); let hasDependency = false; if (fs.existsSync(packageJsonPath)) { @@ -92,7 +92,7 @@ const TSDOWN_MIGRATION_FILES = [ ]; function escapeRegExp(value: string): string { - return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + return value.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); } const STANDARD_TSUP_CONFIG_FILE_PATTERN = TSUP_CONFIG_FILES.flatMap((file) => [ @@ -129,17 +129,17 @@ interface UnsupportedTsupConfigConsumer { } function removeStandardTsdownConfigOption(script: string): string { - return script.replace(TSDOWN_STANDARD_CONFIG_OPTION_RE, '$1'); + return script.replaceAll(TSDOWN_STANDARD_CONFIG_OPTION_RE, '$1'); } function resolveScriptConfigPath(packagePath: string, configPath: string): string { - return path.resolve(packagePath, configPath.replace(/[\\/]/g, path.sep)); + return path.resolve(packagePath, configPath.replaceAll(/[\\/]/g, path.sep)); } function collectSharedTsupConfigs( projectPath: string, - packages: WorkspacePackage[] | undefined, - tsupTargets: string[], + packages: Array | undefined, + tsupTargets: Array, ): Map { const migratedConfigPaths = new Set( tsupTargets.flatMap((target) => @@ -170,11 +170,13 @@ function collectSharedTsupConfigs( if (!migratedConfigPaths.has(configPath) || path.dirname(configPath) === packagePath) { continue; } - const sharedConfig = sharedConfigs.get(configPath) ?? { consumers: new Map() }; + const sharedConfig = sharedConfigs.get(configPath) ?? { + consumers: new Map(), + }; const consumer = sharedConfig.consumers.get(packagePath) ?? { label, packagePath, - scriptNames: new Set(), + scriptNames: new Set(), }; consumer.scriptNames.add(scriptName); sharedConfig.consumers.set(packagePath, consumer); @@ -186,8 +188,8 @@ function collectSharedTsupConfigs( return sharedConfigs; } -function collectTsupConfigCollisions(tsupTargets: string[]): TsupConfigLocation[] { - const collisions: TsupConfigLocation[] = []; +function collectTsupConfigCollisions(tsupTargets: Array): Array { + const collisions: Array = []; for (const target of tsupTargets) { const tsdownConfig = detectConfigs(target).tsdownConfig; if (tsdownConfig) { @@ -204,7 +206,7 @@ function collectTsupConfigCollisions(tsupTargets: string[]): TsupConfigLocation[ return collisions; } -function collectInlineTsupConfigs(tsupTargets: string[]): TsupConfigLocation[] { +function collectInlineTsupConfigs(tsupTargets: Array): Array { return tsupTargets.flatMap((target) => { const packageJsonPath = path.join(target, 'package.json'); if (!fs.existsSync(packageJsonPath) || !Object.hasOwn(readJsonFile(packageJsonPath), 'tsup')) { @@ -224,8 +226,8 @@ function isRemovableDefaultConfigArgument(configArgument: string, defaultConfig? } function collectUnsupportedTsupConfigConsumers( - tsupTargets: string[], -): UnsupportedTsupConfigConsumer[] { + tsupTargets: Array, +): Array { const migratedConfigPaths = new Set( tsupTargets.flatMap((target) => TSUP_CONFIG_FILES.map((file) => path.join(target, file)).filter((file) => @@ -233,7 +235,7 @@ function collectUnsupportedTsupConfigConsumers( ), ), ); - const unsupported: UnsupportedTsupConfigConsumer[] = []; + const unsupported: Array = []; for (const target of tsupTargets) { const packageJsonPath = path.join(target, 'package.json'); @@ -295,11 +297,7 @@ function restoreSharedTsupUsage( if (!originalPackageJson || !fs.existsSync(packageJsonPath)) { continue; } - const original = JSON.parse(originalPackageJson.toString()) as { - scripts?: Record; - devDependencies?: Record; - dependencies?: Record; - }; + const original = parseJsonObject(originalPackageJson.toString()); editJsonFile<{ scripts?: Record; devDependencies?: Record; @@ -307,16 +305,17 @@ function restoreSharedTsupUsage( }>(packageJsonPath, (pkg) => { let changed = false; for (const field of ['devDependencies', 'dependencies'] as const) { - const spec = original[field]?.tsup; - if (spec && pkg[field]?.tsup !== spec) { + const group = original[field]; + const spec = isObjectValue(group) ? group.tsup : undefined; + if (typeof spec === 'string' && spec && pkg[field]?.tsup !== spec) { pkg[field] ??= {}; pkg[field].tsup = spec; changed = true; } } for (const scriptName of restoredScripts.get(target) ?? []) { - const script = original.scripts?.[scriptName]; - if (script !== undefined && pkg.scripts?.[scriptName] !== script) { + const script = isObjectValue(original.scripts) ? original.scripts[scriptName] : undefined; + if (typeof script === 'string' && pkg.scripts?.[scriptName] !== script) { pkg.scripts ??= {}; pkg.scripts[scriptName] = script; changed = true; @@ -329,7 +328,7 @@ function restoreSharedTsupUsage( return preservedDependencyTargets; } -function snapshotTsupMigrationTargets(targets: string[]): Map { +function snapshotTsupMigrationTargets(targets: Array): Map { const snapshots = new Map(); for (const target of targets) { for (const file of TSDOWN_MIGRATION_FILES) { @@ -340,8 +339,8 @@ function snapshotTsupMigrationTargets(targets: string[]): Map): string[] { - const failures: string[] = []; +function restoreTsupMigrationTargets(snapshots: Map): Array { + const failures: Array = []; for (const [filePath, contents] of snapshots) { try { if (contents === undefined) { @@ -356,7 +355,7 @@ function restoreTsupMigrationTargets(snapshots: Map) return failures; } -function extractTsdownMigrationWarnings(output: Buffer): string[] { +function extractTsdownMigrationWarnings(output: Buffer): Array { return output .toString() .replaceAll('\r\n', '\n') @@ -374,7 +373,7 @@ function extractTsdownMigrationWarnings(output: Buffer): string[] { async function runTsdownMigrateStep( cwd: string, packageManager: PackageManager, -): Promise<{ ok: boolean; warnings: string[] }> { +): Promise<{ ok: boolean; warnings: Array }> { try { const result = await runCommandSilently({ ...getVpCommand([ @@ -391,7 +390,7 @@ async function runTsdownMigrateStep( if (result.exitCode !== 0) { const stderr = result.stderr.toString().trim(); if (stderr) { - prompts.log.warn(`⚠ ${stderr}`); + promptLog.warn(`⚠ ${stderr}`); } return { ok: false, warnings: [] }; } @@ -412,7 +411,7 @@ export async function migrateTsupToTsdown( interactive: boolean, packageManager: PackageManager, tsupConfigFile?: string, - packages?: WorkspacePackage[], + packages?: Array, options?: { silent?: boolean; report?: MigrationReport }, ): Promise { const spinner = options?.silent ? getSilentSpinner() : getSpinner(interactive); @@ -430,7 +429,7 @@ export async function migrateTsupToTsdown( ); const configCollisions = collectTsupConfigCollisions(tsupTargets); if (configCollisions.length > 0) { - prompts.log.warn( + promptLog.warn( `Automatic tsup migration was skipped because these tsdown configs already exist:\n${configCollisions .map(({ configPath }) => ` ${displayRelative(configPath, projectPath)}`) .join('\n')}`, @@ -444,7 +443,7 @@ export async function migrateTsupToTsdown( } const inlineTsupConfigs = collectInlineTsupConfigs(tsupTargets); if (inlineTsupConfigs.length > 0) { - prompts.log.warn( + promptLog.warn( `Automatic tsup migration was skipped because these inline tsup configs cannot be migrated automatically:\n${inlineTsupConfigs .map(({ configPath }) => ` ${displayRelative(configPath, projectPath)}`) .join('\n')}`, @@ -458,7 +457,7 @@ export async function migrateTsupToTsdown( } const unsupportedConfigConsumers = collectUnsupportedTsupConfigConsumers(tsupTargets); if (unsupportedConfigConsumers.length > 0) { - prompts.log.warn( + promptLog.warn( `Automatic tsup migration was skipped because these scripts use configs that cannot be migrated automatically:\n${unsupportedConfigConsumers .map( ({ configArgument, packagePath, scriptName }) => @@ -483,7 +482,7 @@ export async function migrateTsupToTsdown( // finds. Preserve those files across all targets so a later failure can // roll the complete workspace back to its pre-migration state. const snapshots = snapshotTsupMigrationTargets(tsupTargets); - const migrationWarnings: { targetLabel: string; warning: string }[] = []; + const migrationWarnings: Array<{ targetLabel: string; warning: string }> = []; spinner.start('Migrating tsup config to tsdown...'); for (const target of tsupTargets) { const targetLabel = @@ -493,7 +492,7 @@ export async function migrateTsupToTsdown( spinner.stop(); const restoreFailures = restoreTsupMigrationTargets(snapshots); if (restoreFailures.length > 0) { - prompts.log.warn( + promptLog.warn( `Could not restore these files after the failed migration:\n${restoreFailures .map((file) => ` ${file}`) .join('\n')}`, @@ -521,7 +520,7 @@ export async function migrateTsupToTsdown( if (options?.report) { addMigrationWarning(options.report, message); } else { - prompts.log.warn(message); + promptLog.warn(message); } } for (const [configPath, sharedConfig] of sharedConfigs) { @@ -534,7 +533,7 @@ export async function migrateTsupToTsdown( if (options?.report) { addMigrationWarning(options.report, message); } else { - prompts.log.warn(message); + promptLog.warn(message); } } } @@ -579,7 +578,7 @@ function deleteTsupConfigFiles( report.removedConfigCount++; } if (!silent) { - prompts.log.success(`✔ Removed ${displayRelative(configPath)}`); + promptLog.success(`✔ Removed ${displayRelative(configPath)}`); } } } @@ -596,7 +595,7 @@ function deleteTsupConfigFiles( report.removedConfigCount++; } if (!silent) { - prompts.log.success(`✔ Removed ${displayRelative(configPath)}`); + promptLog.success(`✔ Removed ${displayRelative(configPath)}`); } } } @@ -626,8 +625,8 @@ function rewriteTsupPackageJson(packageJsonPath: string, preserveTsupDependency // remove that redundant option before the generic tsdown -> vp pack rule. for (const [name, script] of Object.entries(pkg.scripts ?? {})) { const rewritten = removeStandardTsdownConfigOption(script); - if (rewritten !== script) { - pkg.scripts![name] = rewritten; + if (rewritten !== script && pkg.scripts) { + pkg.scripts[name] = rewritten; changed = true; } } @@ -647,14 +646,14 @@ function rewriteTsupPackageJson(packageJsonPath: string, preserveTsupDependency } export function warnMissingTsupConfig() { - prompts.log.warn( + promptLog.warn( 'tsup detected, but no tsup config was found. The tsup setup must be migrated manually.', ); } export async function confirmTsupMigration(interactive: boolean): Promise { if (interactive) { - const confirmed = await prompts.confirm({ + const confirmed = await promptConfirm({ message: 'Migrate tsup config to tsdown using tsdown-migrate?\n ' + styleText( @@ -663,7 +662,7 @@ export async function confirmTsupMigration(interactive: boolean): Promise, ): Promise { const tsupProject = detectTsupProject(projectPath, packages); if (!tsupProject.hasDependency) { diff --git a/packages/cli/src/migration/migrator/tsx.ts b/packages/cli/src/migration/migrator/tsx.ts index b8bcf6736c..a84c7fd49f 100644 --- a/packages/cli/src/migration/migrator/tsx.ts +++ b/packages/cli/src/migration/migrator/tsx.ts @@ -3,21 +3,26 @@ import os from 'node:os'; import path from 'node:path'; import { styleText } from 'node:util'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { + confirm as promptConfirm, + isCancel, + log as promptLog, +} from '@voidzero-dev/vite-plus-prompts'; import { parseSync } from '../../../binding/index.js'; -import { type WorkspacePackage } from '../../types/index.ts'; +import type { WorkspacePackage } from '../../types/index.ts'; +import { errorCode } from '../../utils/error.ts'; import { readNearestPackageJson } from '../../utils/package.ts'; import { cancelAndExit } from '../../utils/prompts.ts'; import { SCRIPT_EXTENSIONS, WATCH_OPTIONS_WITH_VALUE } from '../../vpx-script.ts'; +import type { ScriptRunnerCommandRewrite, ScriptRunnerMigration } from '../migrator.ts'; import { detectScriptRunnerProject, migrateScriptRunnerToVpx, rewriteScriptRunnerCommand, - type ScriptRunnerCommandRewrite, - type ScriptRunnerMigration, } from '../migrator.ts'; -import { type MigrationReport } from '../report.ts'; +import type { MigrationReport } from '../report.ts'; +import { lookupSetting } from './shared.ts'; // tsx in command position: `tsx a.ts`, `npx tsx`, `--import tsx`, `--import=tsx`, // `-r tsx/cjs`, `node_modules\.bin\tsx.cmd`, or inside a quoted command, in any case, as @@ -121,7 +126,7 @@ const EXPORT_ASSIGNMENT = /(?:^|;)\s*export\s*=/m; // A relative `require()` of a JavaScript path, which tsx also resolves to TypeScript. const RELATIVE_REQUIRE = /(? = { +const TYPESCRIPT_EXTENSIONS = { js: ['ts', 'tsx'], cjs: ['cts'], mjs: ['mts'], @@ -153,15 +158,18 @@ export function rewriteTsxCommand(command: string, cwd?: string): TsxCommandRewr return rewriteScriptRunnerCommand(TSX_RUNNER, command, cwd); } -export function detectTsxProject(rootDir: string, packages?: readonly WorkspacePackage[]): boolean { +export function detectTsxProject( + rootDir: string, + packages?: ReadonlyArray, +): boolean { return detectScriptRunnerProject(TSX_RUNNER, rootDir, packages); } export function migrateTsxToVpx( rootDir: string, - packages?: readonly WorkspacePackage[], + packages?: ReadonlyArray, report?: MigrationReport, -): { changed: boolean; dependencyRemoved: boolean } { +) { const result = migrateScriptRunnerToVpx(TSX_RUNNER, rootDir, packages, report); if (report && result.scriptsChanged) { report.tsxMigrated = true; @@ -173,7 +181,7 @@ export function migrateTsxToVpx( * Why environment assignments keep tsx for the command they apply to, or undefined. * Names match in any case, as on Windows. */ -function envKeepReason(assignments: readonly string[]): string | undefined { +function envKeepReason(assignments: ReadonlyArray): string | undefined { if ( assignments.some((value) => /^NODE_OPTIONS=/i.test(value) && TSX_COMMAND.test(value.slice(13))) ) { @@ -210,7 +218,7 @@ export function typescriptScriptKeepReason( source = fs.readFileSync(file, 'utf8'); } catch (error) { // A file that an earlier command generates cannot be checked yet. - return (error as NodeJS.ErrnoException).code === 'ENOENT' + return errorCode(error) === 'ENOENT' ? `\`${script}\` does not exist yet, so vp migrate cannot check it` : undefined; } @@ -219,7 +227,9 @@ export function typescriptScriptKeepReason( const resolve = (ext: string) => path.resolve(path.dirname(file), `${base}.${ext}`); const typescript = fs.existsSync(resolve(extension)) ? undefined - : TYPESCRIPT_EXTENSIONS[extension].find((ext) => fs.existsSync(resolve(ext))); + : lookupSetting(TYPESCRIPT_EXTENSIONS, extension)?.find((ext) => + fs.existsSync(resolve(ext)), + ); if (typescript) { return `\`${script}\` requires \`${base}.${extension}\`, which only ${runner} resolves to \`${base}.${typescript}\`; write the TypeScript extension`; } @@ -409,7 +419,7 @@ function codeUsesTsx(content: string, file: string): boolean { export async function confirmTsxMigration(interactive: boolean): Promise { if (interactive) { - const confirmed = await prompts.confirm({ + const confirmed = await promptConfirm({ message: 'Migrate tsx scripts to Vite+?\n ' + styleText( @@ -418,11 +428,11 @@ export async function confirmTsxMigration(interactive: boolean): Promise; -function oxlintConfigLayers(config: OxlintConfig): OxlintConfig[] { +function oxlintConfigLayers(config: OxlintConfig): Array { return [...(config.extends ?? []).flatMap(oxlintConfigLayers), config]; } @@ -93,13 +94,16 @@ export function ensureSvelteRuneGlobals(config: OxlintConfig): void { // Remove the "lint-staged" key from package.json after config has been // successfully merged into vite.config.ts. export function removeLintStagedFromPackageJson(packageJsonPath: string): void { - editJsonFile<{ 'lint-staged'?: Record }>(packageJsonPath, (pkg) => { - if (pkg['lint-staged']) { - delete pkg['lint-staged']; - return pkg; - } - return undefined; - }); + editJsonFile<{ 'lint-staged'?: Record> }>( + packageJsonPath, + (pkg) => { + if (pkg['lint-staged']) { + delete pkg['lint-staged']; + return pkg; + } + return undefined; + }, + ); } // Migrate standalone lint-staged config files into staged in vite.config.ts. @@ -124,8 +128,10 @@ export function rewriteLintStagedConfigFile(projectPath: string, report?: Migrat // Skip if staged already exists in vite.config.ts (already migrated by rewritePackageJson). if (!hasStagedConfigInViteConfig(projectPath)) { const config = readJsonFile(configPath); - const updated = rewriteScripts(JSON.stringify(config), readRulesYaml()); - const finalConfig = updated ? JSON.parse(updated) : config; + const updated = rewriteScriptMap(config, (serialized) => + rewriteScripts(serialized, readRulesYaml()), + ); + const finalConfig = updated ?? config; if (!mergeStagedConfigToViteConfig(projectPath, finalConfig, true, report)) { // Merge failed — preserve the original config file so the user doesn't lose their rules continue; @@ -185,7 +191,7 @@ export default defineConfig({}); report.createdViteConfigCount++; } if (!silent) { - prompts.log.success(`✔ Created vite.config.ts in ${displayRelative(viteConfigPath)}`); + promptLog.success(`✔ Created vite.config.ts in ${displayRelative(viteConfigPath)}`); } } return configs.viteConfig; @@ -249,7 +255,7 @@ export function mergeTsdownConfigFile( report.tsdownImportCount++; } if (!silent) { - prompts.log.success( + promptLog.success( `✔ Added import for ${displayRelative(fullTsdownConfigPath)} in ${displayRelative(fullViteConfigPath)}`, ); } @@ -269,7 +275,7 @@ export function mergeViteConfigFiles( projectPath: string, silent = false, report?: MigrationReport, - packages?: WorkspacePackage[], + packages?: Array, // For per-sub-package callers: the workspace root that `packages[].path` // is relative to. When undefined we resolve relative to `projectPath` // (correct for the top-level standalone/monorepo callers, where @@ -309,7 +315,7 @@ export function retryPreservedOxlintConfigs( workspaceRoot: string, silent = false, report?: MigrationReport, - packages?: WorkspacePackage[], + packages?: Array, ): boolean { const prepared = prepareOxlintConfigs([ workspaceRoot, @@ -354,7 +360,7 @@ function mergeOxlintConfigFile( oxlintConfig: string, silent: boolean, report?: MigrationReport, - packages?: WorkspacePackage[], + packages?: Array, workspaceRoot?: string, preparedOxlintConfigs?: PreparedOxlintConfigs, ): void { @@ -469,7 +475,7 @@ function mergeOxlintConfigFile( const normalizedOxlintConfig = ensureVitePlusImportRuleDefaults(oxlintJson); if (hasInheritedImportRule && oxlintJson.rules?.[PREFER_VITE_PLUS_IMPORTS_RULE] === undefined) { // Keep the shared rule live: copying its value into the root would mask later edits. - delete normalizedOxlintConfig.rules![PREFER_VITE_PLUS_IMPORTS_RULE]; + delete normalizedOxlintConfig.rules?.[PREFER_VITE_PLUS_IMPORTS_RULE]; } try { const plan: OxlintModulePlan = @@ -614,18 +620,15 @@ function injectConfigDefaults( } function configImportOffset(filename: string, source: string): number { - const { ast, comments } = JSON.parse(analyzeMigrationSource(filename, source)) as { - ast: { node: Program }; - comments: Array<{ start: number; end: number }>; - }; - let offset = ast.node.hashbang?.end ?? 0; - for (const statement of ast.node.body) { + const { program, comments } = parseSource(filename, source); + let offset = program.hashbang?.end ?? 0; + for (const statement of program.body) { if (statement.type !== 'ExpressionStatement' || typeof statement.directive !== 'string') { break; } offset = statement.end; } - const firstStatement = ast.node.body[0]?.start ?? source.length; + const firstStatement = program.body[0]?.start ?? source.length; for (const comment of comments) { if (comment.end > firstStatement) { break; @@ -642,6 +645,18 @@ function configImportOffset(filename: string, source: string): number { return offset; } +// The native parser supplies AST nodes tagged with their ESTree type. +function isAstObjectExpression(node: unknown): node is ObjectExpression { + return ( + typeof node === 'object' && + node !== null && + 'type' in node && + node.type === 'ObjectExpression' && + 'properties' in node && + Array.isArray(node.properties) + ); +} + function staticValue(source: string) { const statement = parseSource('value.ts', `const value = ${source};`).program.body[0]; return statement?.type === 'VariableDeclaration' ? statement.declarations[0]?.init : undefined; @@ -655,8 +670,8 @@ function followsSpread(node: unknown, offset: number): boolean | undefined { if (typeof node !== 'object' || node === null) { return undefined; } - if ((node as { type?: unknown }).type === 'ObjectExpression') { - const { properties } = node as ObjectExpression; + if (isAstObjectExpression(node)) { + const { properties } = node; const index = properties.findIndex( (property) => property.type === 'Property' && property.value.start === offset, ); @@ -695,7 +710,7 @@ export function hasOnlyInjectedDefaults(viteConfigPath: string, configKey: strin const placeholder = `"${randomUUID()}"`; const placeholderPath = path.join(os.tmpdir(), `vite-plus-config-${randomUUID()}.json`); fs.writeFileSync(placeholderPath, placeholder); - let marked: string[]; + let marked: Array; try { marked = upsertJsonConfig(viteConfigPath, placeholderPath, configKey).content.split( placeholder, @@ -776,7 +791,7 @@ function mergeAndRemoveJsonConfig( fs.unlinkSync(fullJsonConfigPath); } if (!silent) { - prompts.log.info( + promptLog.info( `${configKey} config already present in ${displayRelative(fullViteConfigPath)} — ${deferRemoval ? 'deferred removal of' : 'removed redundant'} ${displayRelative(fullJsonConfigPath)}`, ); } @@ -811,7 +826,7 @@ function mergeAndRemoveJsonConfig( } const originalViteConfig = fs.readFileSync(fullViteConfigPath, 'utf8'); - const writtenModules: string[] = []; + const writtenModules: Array = []; try { for (const [filename, module] of modulePlan?.modules ?? []) { const descriptor = fs.openSync(filename, 'wx'); @@ -861,7 +876,7 @@ function mergeAndRemoveJsonConfig( report.mergedConfigCount++; } if (!silent) { - prompts.log.success( + promptLog.success( `✔ Merged ${displayRelative(fullJsonConfigPath)} into ${displayRelative(fullViteConfigPath)}`, ); } @@ -874,7 +889,7 @@ function mergeAndRemoveJsonConfig( */ export function mergeStagedConfigToViteConfig( projectPath: string, - stagedConfig: Record, + stagedConfig: JsonObject, silent = false, report?: MigrationReport, ): boolean { @@ -899,7 +914,7 @@ export function mergeStagedConfigToViteConfig( report.mergedStagedConfigCount++; } if (!silent) { - prompts.log.success(`✔ Merged staged config into ${displayRelative(fullViteConfigPath)}`); + promptLog.success(`✔ Merged staged config into ${displayRelative(fullViteConfigPath)}`); } return true; } else { @@ -953,7 +968,7 @@ export function wrapLazyPluginsInViteConfig( report.wrappedPluginConfigCount++; } if (!silent) { - prompts.log.success( + promptLog.success( `✔ Wrapped inline Vite plugins with lazyPlugins in ${displayRelative(viteConfigPath)}`, ); } @@ -969,7 +984,7 @@ export function migrateTaskCacheConfigInViteConfig( projectPath: string, silent = false, report?: MigrationReport, - manualWarnings?: string[], + manualWarnings?: Array, ): boolean { const configs = detectConfigs(projectPath); if (!configs.viteConfig) { @@ -998,7 +1013,7 @@ export function migrateTaskCacheConfigInViteConfig( report.migratedTaskCacheConfigCount++; } if (!silent) { - prompts.log.success( + promptLog.success( `✔ Moved task cache settings under \`cache\` in ${displayRelative(viteConfigPath)}`, ); } @@ -1042,8 +1057,11 @@ export function warnUnresolvedImportRuleConfig(report?: MigrationReport): void { export async function tryResolveImportRuleConfig(projectPath: string): Promise { const extracted = readStaticLintConfig(projectPath); let lint: OxlintConfig | undefined; - if (extracted != null) { - lint = JSON.parse(extracted); + if (typeof extracted === 'string') { + const parsed = parseJsonValue(extracted); + if (isObjectValue(parsed)) { + lint = parsed; + } } else { try { lint = await readLintConfigInWorker(projectPath); @@ -1104,7 +1122,7 @@ export function rewriteAllImports( options: { preserveNuxtVitestImports?: boolean; // Capture package owners before migration removes oxlint from their manifests. - oxlintOwnerDirs?: string[]; + oxlintOwnerDirs?: Array; importRuleConfig?: string; } = {}, ): boolean { @@ -1134,8 +1152,8 @@ export function rewriteAllImports( } if (!silent && modified > 0) { - prompts.log.success(`Rewrote imports in ${modified === 1 ? 'one file' : `${modified} files`}`); - prompts.log.info(result.modifiedFiles.map((file) => ` ${displayRelative(file)}`).join('\n')); + promptLog.success(`Rewrote imports in ${modified === 1 ? 'one file' : `${modified} files`}`); + promptLog.info(result.modifiedFiles.map((file) => ` ${displayRelative(file)}`).join('\n')); } if (errors > 0) { @@ -1145,11 +1163,9 @@ export function rewriteAllImports( report, ); } else { - prompts.log.warn( - `⚠ ${errors === 1 ? 'one file had an error' : `${errors} files had errors`}:`, - ); + promptLog.warn(`⚠ ${errors === 1 ? 'one file had an error' : `${errors} files had errors`}:`); for (const error of result.errors) { - prompts.log.error(` ${displayRelative(error.path)}: ${error.message}`); + promptLog.error(` ${displayRelative(error.path)}: ${error.message}`); } } } diff --git a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts index a00ec72561..bcb0737a07 100644 --- a/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts +++ b/packages/cli/src/migration/migrator/vite-plus-bootstrap.ts @@ -1,7 +1,8 @@ import fs from 'node:fs'; import path from 'node:path'; -import { PackageManager, type WorkspaceInfo, type WorkspacePackage } from '../../types/index.ts'; +import type { WorkspaceInfo, WorkspacePackage } from '../../types/index.ts'; +import { PackageManager } from '../../types/index.ts'; import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; import { VITEST_VERSION, @@ -10,9 +11,12 @@ import { VITE_PLUS_VERSION, isForceOverrideMode, } from '../../utils/constants.ts'; +import type { JsonObject } from '../../utils/json.ts'; import { editJsonFile, readJsonFile } from '../../utils/json.ts'; -import { type NpmWorkspaces } from '../../utils/workspace.ts'; -import { editYamlFile, readYamlFile, type YamlDocument } from '../../utils/yaml.ts'; +import type { NpmWorkspaces } from '../../utils/workspace.ts'; +import type { YamlDocument } from '../../utils/yaml.ts'; +import { editYamlFile, readYamlFile } from '../../utils/yaml.ts'; +import type { PnpmPeerDependencyRuleKeys } from '../migrator.ts'; import { alignVitestEcosystemPackages, applyBuildAllowanceToPackageJsonPnpm, @@ -31,7 +35,6 @@ import { isProtocolPinnedSpec, managedOverridePackages, mergeManagedPnpmPeerDependencyRules, - type PnpmPeerDependencyRuleKeys, peerDependencyRulesHaveStaleEntry, migratePnpmSettingsToWorkspaceYaml, normalizeVitestPeerCatalogSpec, @@ -61,7 +64,12 @@ import { yarnrcSatisfiesVitePlus, yarnSupportsPreapprovedPackages, } from '../migrator.ts'; -import { type DependencyVersionChange, type MigrationReport } from '../report.ts'; +import type { DependencyVersionChange, MigrationReport } from '../report.ts'; +import type { + RetainedImportDependencies, + ManagedOverrideKeyStyle, + PnpmPackageJsonSettings, +} from './shared.ts'; import { BROWSER_PROVIDER_PEER_DEPS, hasProviderPeerDependency, @@ -70,19 +78,16 @@ import { OXLINT_PLUGIN_API_PACKAGES, packageOwnsOxlintApi, bundledPackagesToRemove, - type RetainedImportDependencies, VITEST_IS_MANAGED_OVERRIDE, managedOverrideKey, pinnedPackageManagerVersion, pnpmMajor, pnpmOverrideKey, - type ManagedOverrideKeyStyle, - type PnpmPackageJsonSettings, } from './shared.ts'; export type BootstrapPackageJson = { workspaces?: NpmWorkspaces; - overrides?: Record; + overrides?: JsonObject; resolutions?: Record; devDependencies?: Record; dependencies?: Record; @@ -90,7 +95,7 @@ export type BootstrapPackageJson = { optionalDependencies?: Record; pnpm?: PnpmPackageJsonSettings; packageManager?: string; - devEngines?: { packageManager?: unknown; [key: string]: unknown }; + devEngines?: JsonObject; }; export type VitePlusBootstrapResult = { @@ -142,7 +147,7 @@ function overrideSpecSatisfiesVitePlus( } export function overridesSatisfyVitePlus( - overrides: Record | undefined, + overrides: JsonObject | undefined, usesVitest: boolean, catalogDependencyResolver?: CatalogDependencyResolver, keyStyle: ManagedOverrideKeyStyle = 'bare', @@ -203,7 +208,7 @@ function catalogVitePlusDependencyPending( function pnpmPeerDependencyRulesSatisfyVitePlus( peerDependencyRules: - | { allowAny?: string[]; allowedVersions?: Record } + | { allowAny?: Array; allowedVersions?: Record } | undefined, { managed, stale }: PnpmPeerDependencyRuleKeys, ): boolean { @@ -255,7 +260,7 @@ function pnpmWorkspaceExoticSubdepsSettingSatisfied(projectPath: string): boolea if (!fs.existsSync(pnpmWorkspaceYamlPath)) { return false; } - const doc = readYamlFile(pnpmWorkspaceYamlPath) as { blockExoticSubdeps?: boolean } | null; + const doc = readYamlFile(pnpmWorkspaceYamlPath); return doc?.blockExoticSubdeps === false; } @@ -398,7 +403,7 @@ function reconcileVitePlusBootstrapPackage( ownsOxlintApi && dependencies !== undefined && dependencies === pkg.dependencies && - (OXLINT_PLUGIN_API_PACKAGES as readonly string[]).includes(bundledPackage) + (OXLINT_PLUGIN_API_PACKAGES as ReadonlyArray).includes(bundledPackage) ) { // A published plugin keeps the runtime dependency that supplies its // upstream imports, as the fresh path does. Its `catalog:` reference @@ -495,15 +500,15 @@ function reconcileVitePlusBootstrapPackage( export function bootstrapProjectPaths( rootDir: string, - packages: WorkspacePackage[] | undefined, -): string[] { + packages: Array | undefined, +): Array { return getWorkspaceProjectPaths({ rootDir, packages }); } /** Catalog entries needed for retained browser imports and newly installed providers. */ export function collectBrowserCatalogAdditions( rootDir: string, - packages?: WorkspacePackage[], + packages?: Array, retainedBrowserPackages?: RetainedImportDependencies['browser'], // Optional precomputed provider source-scan results keyed by absolute package // path. Lets a caller that already scanned a path reuse the result instead of @@ -543,7 +548,7 @@ export function collectBrowserCatalogAdditions( // resolves to the target version, not just the root manifest's. function someBootstrapProjectPackageJson( rootDir: string, - packages: WorkspacePackage[] | undefined, + packages: Array | undefined, predicate: (pkg: BootstrapPackageJson) => boolean, ): boolean { return bootstrapProjectPaths(rootDir, packages).some((packagePath) => { @@ -557,7 +562,7 @@ function someBootstrapProjectPackageJson( function workspaceVitestEcosystemCatalogReferencesPending( rootDir: string, - packages: WorkspacePackage[] | undefined, + packages: Array | undefined, catalogDependencyResolver?: CatalogDependencyResolver, ): boolean { return someBootstrapProjectPackageJson(rootDir, packages, (pkg) => @@ -570,7 +575,7 @@ function workspaceVitestEcosystemCatalogReferencesPending( // stale workspace slip through the "already on Vite+" early exit. function workspaceCatalogVitePlusDependencyPending( rootDir: string, - packages: WorkspacePackage[] | undefined, + packages: Array | undefined, catalogDependencyResolver?: CatalogDependencyResolver, ): boolean { return someBootstrapProjectPackageJson(rootDir, packages, (pkg) => @@ -590,7 +595,7 @@ function workspaceCatalogVitePlusDependencyPending( function yarnWorkspaceHoistingOptOutPending( rootDir: string, packageManager: PackageManager, - packages: WorkspacePackage[] | undefined, + packages: Array | undefined, ): boolean { if (packageManager !== PackageManager.yarn || !packages?.length) { return false; @@ -621,7 +626,7 @@ function yarnWorkspaceHoistingOptOutPending( export function detectVitePlusBootstrapPending( projectPath: string, packageManager: PackageManager | undefined, - packages?: WorkspacePackage[], + packages?: Array, packageManagerVersion?: string, retainedImportDependencies?: RetainedImportDependencies, ): boolean { @@ -695,7 +700,7 @@ export function detectVitePlusBootstrapPending( continue; } const childPkg = readJsonFile(childPackageJsonPath) as BootstrapPackageJson; - const candidate = JSON.parse(JSON.stringify(childPkg)) as BootstrapPackageJson; + const candidate = structuredClone(childPkg); if ( reconcileVitePlusBootstrapPackage( packagePath, @@ -901,7 +906,7 @@ function ensureVitePlusDependencySpecs( // Raw file contents, or undefined if the file does not exist. Used for // byte-level before/after change detection on pnpm-workspace.yaml / .yarnrc.yml. function readTextFileIfExists(filePath: string): string | undefined { - return fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf-8') : undefined; + return fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : undefined; } function ensureOverrideEntries( @@ -910,7 +915,7 @@ function ensureOverrideEntries( catalogDependencyResolver?: CatalogDependencyResolver, keyStyle: ManagedOverrideKeyStyle = 'bare', usesWebdriverioProvider = false, -): { overrides: Record; changed: boolean } { +) { const next = { ...overrides }; let changed = false; // Common case: drop a lingering managed `vitest` override. @@ -1035,7 +1040,7 @@ export function ensureVitePlusBootstrap( workspaceInfo.packages, retainedImportDependencies?.browser, ); - let movedPnpmSettings: Record | undefined; + let movedPnpmSettings: JsonObject | undefined; const pnpmWorkspaceYamlPath = path.join(projectPath, 'pnpm-workspace.yaml'); // Below pnpm 10.6.2 the pnpm settings (overrides) stay in package.json, so the @@ -1268,10 +1273,10 @@ export function ensureVitePlusBootstrap( supportCatalog, yarnSupportsPreapprovedPackages(workspaceInfo.downloadPackageManager.version), ); - const after = fs.readFileSync(yarnrcYmlPath, 'utf-8'); + const after = fs.readFileSync(yarnrcYmlPath, 'utf8'); result.packageManagerConfig = before !== after; } else if (isBunWorkspace) { - const before = fs.readFileSync(packageJsonPath, 'utf-8'); + const before = fs.readFileSync(packageJsonPath, 'utf8'); rewriteBunCatalog( projectPath, usesVitest, @@ -1280,7 +1285,7 @@ export function ensureVitePlusBootstrap( workspaceInfo.downloadPackageManager.version, browserCatalogAdditions, ); - const after = fs.readFileSync(packageJsonPath, 'utf-8'); + const after = fs.readFileSync(packageJsonPath, 'utf8'); result.packageJson = result.packageJson || before !== after; } @@ -1378,7 +1383,7 @@ function readInstalledRawViteVersion(projectPath: string): string | undefined { export async function collectToolchainVersionChanges( projectPath: string, hasProtectedVitestImports = false, -): Promise { +): Promise> { const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { return []; @@ -1388,9 +1393,8 @@ export async function collectToolchainVersionChanges( // The bundled raw Vite version is imported from `./versions.js` (dist root): // the tsdown `fix-versions-path` plugin rewrites this specifier and // versions.spec.ts guards that it resolves. Mirror migrator/eslint.ts EXACTLY. - // @ts-expect-error — resolved at runtime from dist/ -> dist/versions.js const { versions } = await import('../versions.js'); - const rawViteVersion = versions.vite as string | undefined; + const rawViteVersion = versions.vite; const catalogDependencyResolver = readPnpmWorkspaceCatalogDependencyResolver(projectPath) ?? @@ -1405,7 +1409,7 @@ export async function collectToolchainVersionChanges( return resolveDisplayFromSpec(spec, dependencyName, catalogDependencyResolver); }; - const changes: DependencyVersionChange[] = []; + const changes: Array = []; const pushChange = (name: string, to: string | undefined, from: string | undefined): void => { if (to === undefined || (from !== undefined && from === to)) { return; diff --git a/packages/cli/src/migration/migrator/vitest-ecosystem.ts b/packages/cli/src/migration/migrator/vitest-ecosystem.ts index 4525efe7a1..a5b05b3d67 100644 --- a/packages/cli/src/migration/migrator/vitest-ecosystem.ts +++ b/packages/cli/src/migration/migrator/vitest-ecosystem.ts @@ -1,27 +1,36 @@ import fs from 'node:fs'; import path from 'node:path'; -import { YAMLMap } from 'yaml'; +import { isMap } from 'yaml'; -import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; +import type { PackageManager } from '../../types/index.ts'; +import type { WorkspacePackage } from '../../types/index.ts'; import type { CatalogDependencyResolver } from '../../utils/catalog.ts'; import { VITEST_VERSION, VITE_PLUS_NAME, VITE_PLUS_OVERRIDE_PACKAGES, } from '../../utils/constants.ts'; +import { isObjectValue } from '../../utils/json-value.ts'; +import type { JsonObject } from '../../utils/json.ts'; import { readJsonFile } from '../../utils/json.ts'; import { extractOverrideTargetName } from '../../utils/package-overrides.ts'; import { detectPackageMetadata } from '../../utils/package.ts'; import { isAlignableVitestEcosystemPackage } from '../../utils/vitest-ecosystem.ts'; +import type { BootstrapPackageJson } from '../migrator.ts'; import { bootstrapProjectPaths, getCatalogDependencySpec, hasNuxtTestUtilsDependency, sourceTreeReferencesRetainedVitestModule, usesVitestBrowserMode, - type BootstrapPackageJson, } from '../migrator.ts'; +import type { + ManagedOverrideKeyStyle, + PackageJsonDependencyField, + PnpmPeerDependencyRules, +} from './shared.ts'; +import { lookupSetting } from './shared.ts'; import { LEGACY_WRAPPER_FALLBACK_VERSIONS, PROVIDER_OVERRIDE_DROP_NAMES, @@ -31,9 +40,6 @@ import { isPlainRecord, pnpmOverrideKey, vitePeerDependencyRuleRequired, - type ManagedOverrideKeyStyle, - type PackageJsonDependencyField, - type PnpmPeerDependencyRules, } from './shared.ts'; // Official packages that do not declare a required `vitest` peer. Keep them @@ -58,7 +64,7 @@ export { isAlignableVitestEcosystemPackage } from '../../utils/vitest-ecosystem. // PROVIDER_OVERRIDE_DROP_NAMES). Shared by the JSON-object and YAMLMap // variants below. function isRemovePackageOverrideKey(key: string): boolean { - return (PROVIDER_OVERRIDE_DROP_NAMES as readonly string[]).includes( + return (PROVIDER_OVERRIDE_DROP_NAMES as ReadonlyArray).includes( extractOverrideTargetName(key), ); } @@ -79,7 +85,7 @@ function stripSegmentVersion(segment: string): string { function parentGlobMatchesName(glob: string, name: string): boolean { const pattern = glob .split('*') - .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')) + .map((part) => part.replaceAll(/[.+?^${}()|[\]\\]/g, String.raw`\$&`)) .join('.*'); return new RegExp(`^${pattern}$`).test(name); } @@ -99,7 +105,7 @@ function ancestorSegmentMatches(segment: string, name: string): boolean { // playwright) are deliberately NOT included — vite-plus no longer ships them, so // a `@vitest/browser-playwright>…` chain constrains the user's own provider // subtree, not vite-plus's (see the ACCEPTED EDGE note below). -const OWNED_PROVIDER_ANCESTOR_NAMES = (REMOVE_PACKAGES as readonly string[]).filter((name) => +const OWNED_PROVIDER_ANCESTOR_NAMES = (REMOVE_PACKAGES as ReadonlyArray).filter((name) => name.startsWith('@vitest/'), ); @@ -118,7 +124,7 @@ const OWNED_PROVIDER_ANCESTOR_NAMES = (REMOVE_PACKAGES as readonly string[]).fil // `some-parent/**`, `some-parent/vite-*`, `some-app>@vitest/browser-playwright`) // constrains a different subtree and does NOT touch the root vite-plus provider, // so it is preserved. A chain of only `**` (`**`, `**/**`) is global and matches. -function parentChainReachesVitePlus(segments: string[]): boolean { +function parentChainReachesVitePlus(segments: Array): boolean { const concrete = segments.filter((segment) => segment !== '**'); let index = 0; if (concrete.length > 0 && ancestorSegmentMatches(concrete[0], VITE_PLUS_NAME)) { @@ -148,12 +154,12 @@ function parentChainReachesVitePlus(segments: string[]): boolean { // (scoped) segments; the remaining leading `/`-segments are the `from` chain, // with scoped ancestors (`@scope/name`) rejoined. // - bare/versioned names (`pkg`, `@scope/pkg`, `pkg@4`) have NO parent → `null`. -export function extractOverrideParentSegments(key: string): string[] | null { +export function extractOverrideParentSegments(key: string): Array | null { let rest = key.trim(); // Peel every pnpm `>` parent level. pnpm splits at a `>` whose preceding char // is NOT space, `|`, or `@` (its DELIMITER_REGEX), so semver comparators like // `pkg@>=4` are not mistaken for a parent selector. - const pnpmParents: string[] = []; + const pnpmParents: Array = []; for (let delim = rest.search(/[^ |@]>/); delim !== -1; delim = rest.search(/[^ |@]>/)) { pnpmParents.push(stripSegmentVersion(rest.slice(0, delim + 1).trim())); rest = rest.slice(delim + 2).trim(); @@ -170,7 +176,7 @@ export function extractOverrideParentSegments(key: string): string[] | null { const segments = rest.split('/'); // The trailing descriptor occupies the last 2 segments when it is a scoped // name (second-to-last segment starts with `@`), else the last 1. - const descriptorIsScoped = segments[segments.length - 2]?.startsWith('@') ?? false; + const descriptorIsScoped = segments.at(-2)?.startsWith('@') ?? false; const descriptorSegmentCount = descriptorIsScoped ? 2 : 1; const rawParents = segments.slice(0, segments.length - descriptorSegmentCount); if (rawParents.length === 0) { @@ -178,7 +184,7 @@ export function extractOverrideParentSegments(key: string): string[] | null { return null; } // Rejoin scoped ancestors (`@scope` + `name`) and strip each segment's version. - const parents: string[] = []; + const parents: Array = []; for (let i = 0; i < rawParents.length; i += 1) { const segment = rawParents[i]; if (segment.startsWith('@') && i + 1 < rawParents.length) { @@ -228,7 +234,7 @@ export function extractOverrideParentSegments(key: string): string[] | null { // PR #1588 this is left as a known, visible (the pin stays in the manifest) // limitation rather than risk over-deleting genuinely unrelated transitive // selectors (the behavior the posted P2 review asked us to keep). -function providerKeyReachesVitePlus(key: string, ancestorChain: string[]): boolean { +function providerKeyReachesVitePlus(key: string, ancestorChain: Array): boolean { if (!isRemovePackageOverrideKey(key)) { return false; } @@ -246,7 +252,7 @@ export function shouldDropProviderOverrideKey(key: string): boolean { // object value: the key's own embedded selector parents followed by its target // package name (version-stripped). For a plain npm/bun nested key (`a`) this is // just `[a]`, so the accumulated chain mirrors a flat pnpm/yarn parent chain. -function childChainContribution(key: string): string[] { +function childChainContribution(key: string): Array { const parents = extractOverrideParentSegments(key) ?? []; return [...parents, extractOverrideTargetName(key)]; } @@ -272,8 +278,8 @@ function childChainContribution(key: string): string[] { // (pnpm/yarn override values are flat strings, so the recursion is inert for those // sinks.) Returns whether any key/pin was removed. export function dropRemovePackageOverrideKeys( - overrides: Record | undefined, - ancestorChain: string[] = [], + overrides: JsonObject | undefined, + ancestorChain: Array = [], ): boolean { if (!overrides) { return false; @@ -281,10 +287,7 @@ export function dropRemovePackageOverrideKeys( let removed = false; for (const key of Object.keys(overrides)) { const value = overrides[key]; - const child = - value !== null && typeof value === 'object' && !Array.isArray(value) - ? (value as Record) - : undefined; + const child = isObjectValue(value) ? value : undefined; if (providerKeyReachesVitePlus(key, ancestorChain)) { if (child) { // Long-form provider override: drop the provider's own version pin (`.`) @@ -356,7 +359,7 @@ export function managedOverridePackages( : managed; } -function removePackageJsonVitestPin(overrides: Record): boolean { +function removePackageJsonVitestPin(overrides: JsonObject): boolean { const vitest = overrides.vitest; if (!isPlainRecord(vitest)) { return removeManagedVitestEntry(overrides); @@ -377,10 +380,10 @@ function removePackageJsonVitestPin(overrides: Record): boolean // In npm and Bun's object form, "." overrides the package itself. All other keys // constrain its children and must survive a change to the package's own pin. export function ensurePackageJsonOverrides( - overrides: Record | undefined, + overrides: JsonObject | undefined, managed: Record, selectSpec?: (name: string, current: string | undefined, target: string) => string, -): { overrides: Record; changed: boolean } { +) { const next = { ...overrides }; let changed = !('vitest' in managed) && removePackageJsonVitestPin(next); @@ -543,7 +546,7 @@ export function projectUsesVitestDirectly( // `bare`. npm also accepts a range in an override key, so a user-authored // `"vitest@*"` in npm `overrides` belongs to the user. Do not delete it. export function removeManagedVitestEntry( - record: Record | undefined, + record: JsonObject | undefined, keyStyle: ManagedOverrideKeyStyle = 'bare', ): boolean { if (!VITEST_IS_MANAGED_OVERRIDE || !record) { @@ -567,7 +570,7 @@ export function removeYamlMapVitestEntry( map: unknown, keyStyle: ManagedOverrideKeyStyle = 'bare', ): void { - if (!VITEST_IS_MANAGED_OVERRIDE || !(map instanceof YAMLMap)) { + if (!VITEST_IS_MANAGED_OVERRIDE || !isMap(map)) { return; } for (const key of managedVitestOverrideKeys(keyStyle)) { @@ -579,16 +582,16 @@ export function removeYamlMapVitestEntry( // `vitest@*` in a pnpm override sink (see `pnpmOverrideKey`). Exact key // equality keeps selector-scoped keys such as `some-app>vitest` out, and, in // bare sinks, a user-authored ranged key too. -function managedVitestOverrideKeys(keyStyle: ManagedOverrideKeyStyle): string[] { +function managedVitestOverrideKeys(keyStyle: ManagedOverrideKeyStyle): Array { return keyStyle === 'pnpm-ranged' ? ['vitest', pnpmOverrideKey('vitest')] : ['vitest']; } /** The pnpm peerDependencyRules keys for one migration step. */ export interface PnpmPeerDependencyRuleKeys { /** Keys that migration writes to `allowAny` and `allowedVersions` as `'*'`. */ - managed: string[]; + managed: Array; /** Keys that migration removes. */ - stale: string[]; + stale: Array; } // The pnpm peerDependencyRules keys vite-plus manages and removes. The managed @@ -611,7 +614,7 @@ export function pnpmPeerDependencyRuleKeys( const managed = Object.keys(managedOverridePackages(usesVitest)).filter( (key) => viteRuleRequired || key !== 'vite', ); - const stale: string[] = []; + const stale: Array = []; if (!usesVitest && VITEST_IS_MANAGED_OVERRIDE) { stale.push('vitest'); } @@ -633,10 +636,11 @@ export function isManagedAllowedVersion(key: string, value: unknown): boolean { // pnpm-workspace.yaml. export function peerDependencyRulesHaveStaleEntry( rules: { allowAny?: unknown; allowedVersions?: unknown } | null | undefined, - staleKeys: readonly string[], + staleKeys: ReadonlyArray, ): boolean { return ( - (Array.isArray(rules?.allowAny) && rules.allowAny.some((key) => staleKeys.includes(key))) || + (Array.isArray(rules?.allowAny) && + rules.allowAny.some((key: unknown) => typeof key === 'string' && staleKeys.includes(key))) || (isPlainRecord(rules?.allowedVersions) && Object.entries(rules.allowedVersions).some( ([key, value]) => staleKeys.includes(key) && isManagedAllowedVersion(key, value), @@ -709,15 +713,15 @@ export function isLegacyWrapperSpec(value: unknown): boolean { * no `{}` is left behind. Flat maps (pnpm `overrides`, yarn `resolutions`, * catalogs) hold only string values, where the recursion is inert. */ -export function pruneLegacyWrapperAliases(record: Record | undefined): boolean { +export function pruneLegacyWrapperAliases(record: JsonObject | undefined): boolean { if (!record) { return false; } let mutated = false; for (const key of Object.keys(record)) { const value = record[key]; - if (value !== null && typeof value === 'object' && !Array.isArray(value)) { - if (pruneLegacyWrapperAliases(value as Record)) { + if (isObjectValue(value)) { + if (pruneLegacyWrapperAliases(value)) { mutated = true; if (Object.keys(value).length === 0) { delete record[key]; @@ -726,7 +730,7 @@ export function pruneLegacyWrapperAliases(record: Record | unde continue; } if (isLegacyWrapperSpec(value)) { - const fallback = LEGACY_WRAPPER_FALLBACK_VERSIONS[key]; + const fallback = lookupSetting(LEGACY_WRAPPER_FALLBACK_VERSIONS, key); if (fallback !== undefined) { record[key] = fallback; } else { @@ -834,7 +838,7 @@ export function vitestEcosystemCatalogReferencesPending( export function collectVitestEcosystemInstallDependencyNames( rootDir: string, - packages?: WorkspacePackage[], + packages?: Array, ): Set { const names = new Set(); for (const packagePath of bootstrapProjectPaths(rootDir, packages)) { diff --git a/packages/cli/src/migration/migrator/vitest-v5.ts b/packages/cli/src/migration/migrator/vitest-v5.ts index 3113afaf90..cd46c944b8 100644 --- a/packages/cli/src/migration/migrator/vitest-v5.ts +++ b/packages/cli/src/migration/migrator/vitest-v5.ts @@ -2,8 +2,8 @@ import fs from 'node:fs'; import path from 'node:path'; import { applyEdits, findNodeAtLocation, parse as parseJsonc, parseTree } from 'jsonc-parser'; +import type { SemVer } from 'verkit'; import { - type SemVer, compare, findMinimumForRange, getMajor, @@ -19,9 +19,14 @@ import { isScalar, parseDocument, visit } from 'yaml'; import { isDirectoryGitignored } from '../../../binding/index.js'; import cliPackage from '../../../package.json' with { type: 'json' }; -import { PackageManager, type WorkspaceInfoOptional } from '../../types/index.ts'; +import type { WorkspaceInfoOptional } from '../../types/index.ts'; +import { PackageManager } from '../../types/index.ts'; import { findGitRoot } from '../../utils/git.ts'; +import { parseJsonObject, isObjectValue } from '../../utils/json-value.ts'; +import type { JsonObject } from '../../utils/json.ts'; +import { isJsonObject } from '../../utils/json.ts'; import { detectPackageMetadata } from '../../utils/package.ts'; +import { isYamlMapping } from '../../utils/yaml.ts'; import { createCatalogDependencyResolver } from '../migrator.ts'; import type { RewriteResult, SourceOptions, VitestV5Finding } from '../vitest-v5/ast.ts'; import { migrateVitestV5Command } from '../vitest-v5/commands.ts'; @@ -31,16 +36,10 @@ import { migrateVitestV5Config, } from '../vitest-v5/config.ts'; import { vitestV5Documentation } from '../vitest-v5/documentation.ts'; -import { - createLockfileReader, - lockedVitestVersion, - type LockfileReader, -} from '../vitest-v5/lockfile.ts'; -import { - findVitestV5ConfigEntries, - resolveVitestV5TestModes, - type VitestV5TestMode, -} from '../vitest-v5/scopes.ts'; +import type { LockfileReader } from '../vitest-v5/lockfile.ts'; +import { createLockfileReader, lockedVitestVersion } from '../vitest-v5/lockfile.ts'; +import type { VitestV5TestMode } from '../vitest-v5/scopes.ts'; +import { findVitestV5ConfigEntries, resolveVitestV5TestModes } from '../vitest-v5/scopes.ts'; import { hasVitestV5SourceUsage, migrateVitestV5Source } from '../vitest-v5/source.ts'; import { migrateWebdriverioDependencies } from '../vitest-v5/webdriverio.ts'; @@ -75,7 +74,7 @@ interface ProjectPlan { options: SourceOptions; configFiles: Set; // Retain deferred findings only through the current invocation's final scan. - pendingSourceReviews?: Record; + pendingSourceReviews?: Record>; } const DEFERRED_SOURCE_REVIEWS = new Set(['resolve-config', 'overlapping-edits', 'unsafe-syntax']); @@ -87,9 +86,9 @@ interface FileChange { export interface VitestV5MigrationPlan { rootDir: string; packageManager?: PackageManager; - projects: ProjectPlan[]; - findings: VitestV5Finding[]; - changes: FileChange[]; + projects: Array; + findings: Array; + changes: Array; inputs: ReadonlyMap; } @@ -107,18 +106,16 @@ function workspaceFromPlan(plan: VitestV5MigrationPlan): MigrationWorkspace { }; } -function readJson(file: string): Record { +function readJson(file: string): JsonObject { return parseJson(fs.readFileSync(file, 'utf8')); } function parseJson(source: string) { - return JSON.parse(source.replace(/^\uFEFF/, '')); + return parseJsonObject(source.replace(/^\uFEFF/, '')); } -function record(value: unknown): Record | undefined { - return value !== null && typeof value === 'object' && !Array.isArray(value) - ? (value as Record) - : undefined; +function record(value: unknown) { + return isYamlMapping(value) ? value : undefined; } -function dependency(pkg: Record, name: string): string | undefined { +function dependency(pkg: JsonObject, name: string): string | undefined { for (const field of [ 'dependencies', 'devDependencies', @@ -133,8 +130,8 @@ function dependency(pkg: Record, name: string): string | undefi return undefined; } -function filesInProject(directory: string): string[] { - const files: string[] = []; +function filesInProject(directory: string): Array { + const files: Array = []; const walk = (current: string) => { if (current !== directory && fs.existsSync(path.join(current, 'package.json'))) { return; @@ -183,7 +180,7 @@ function finding( function lockedSourceVersion( directory: string, root: string, - pkg: Record, + pkg: JsonObject, readLockfile: LockfileReader, manager?: PackageManager, expectedRunnerPackage?: string, @@ -195,7 +192,7 @@ function lockedSourceVersion( : undefined; } try { - const lock = readLockfile(path.join(root, 'pnpm-lock.yaml'), (source) => { + const lock = readLockfile.manifest(path.join(root, 'pnpm-lock.yaml'), (source) => { const document = parseDocument(source); return document.errors.length ? undefined : record(document.toJS()); }); @@ -290,12 +287,13 @@ function installedSourceVersion( if ( expectedRange && normalizeRange(expectedRange) && - !satisfies(installed.version, expectedRange, { includePrerelease: true }) + (!installed.version || + !satisfies(installed.version, expectedRange, { includePrerelease: true })) ) { return undefined; } if (installed.name === 'vitest') { - return normalize(installed.version) ?? undefined; + return installed.version ? (normalize(installed.version) ?? undefined) : undefined; } const pkg = readJson(path.join(installed.path, 'package.json')); if (installed.name === LEGACY_RUNNER) { @@ -326,7 +324,7 @@ function installedSourceVersion( function sourceVersion( directory: string, root: string, - pkg: Record, + pkg: JsonObject, readLockfile: LockfileReader, manager?: PackageManager, ): string | undefined { @@ -413,7 +411,7 @@ function checkNodeRange( file: string, value: string, label: string, - findings: VitestV5Finding[], + findings: Array, publicContract = false, ): string | undefined { // At the v5 upgrade baseline, both the latest LTS and Current Node releases @@ -468,7 +466,7 @@ function checkNodeRange( return undefined; } -function migrateNode(file: string, source: string, findings: VitestV5Finding[]): string { +function migrateNode(file: string, source: string, findings: Array): string { // Limit compatibility checks to project runtime declarations. Inferring // runtimes from CI workflows, containers, or other files is out of scope. const base = path.basename(file); @@ -496,12 +494,12 @@ function migrateNode(file: string, source: string, findings: VitestV5Finding[]): edits.push({ offset: node.offset, length: node.length, content: JSON.stringify(upgrade) }); } }; - if (typeof pkg.engines?.node === 'string') { + if (isObjectValue(pkg.engines) && typeof pkg.engines.node === 'string') { checkNodeRange(file, pkg.engines.node, 'engines.node', findings, true); } - const runtime = pkg.devEngines?.runtime; + const runtime = record(pkg.devEngines)?.runtime; for (const [index, entry] of (Array.isArray(runtime) ? runtime : [runtime]).entries()) { - if (entry?.name === 'node' && typeof entry.version === 'string') { + if (isJsonObject(entry) && entry.name === 'node' && typeof entry.version === 'string') { checkRuntime(entry.version, 'devEngines.runtime', [ 'devEngines', 'runtime', @@ -513,7 +511,8 @@ function migrateNode(file: string, source: string, findings: VitestV5Finding[]): // The existing setup migration uses Volta only when neither pin file // exists. Check that future .node-version before any project edits. if ( - typeof pkg.volta?.node === 'string' && + isObjectValue(pkg.volta) && + typeof pkg.volta.node === 'string' && !['.node-version', '.nvmrc'].some((name) => fs.existsSync(path.join(path.dirname(file), name)), ) @@ -532,7 +531,7 @@ function scanAndRewriteFile( testMode: VitestV5TestMode, mergedConfig: boolean, ): RewriteResult { - const findings: VitestV5Finding[] = []; + const findings: Array = []; if (!project.active) { return { content: migrateNode(file, source, findings), findings }; } @@ -700,12 +699,12 @@ export function planVitestV5Migration( originalProjects?: ReadonlyMap, ): VitestV5MigrationPlan { const readLockfile = createLockfileReader(); - const findings: VitestV5Finding[] = []; + const findings: Array = []; const directories = [ workspace.rootDir, ...(workspace.packages ?? []).map((pkg) => path.resolve(workspace.rootDir, pkg.path)), ]; - const projects: ProjectPlan[] = []; + const projects: Array = []; const projectSources = new Map( Array.from(new Set(directories), (directory) => [ directory, @@ -815,11 +814,13 @@ export function planVitestV5Migration( file, source, project, - { ...testModes.modes.get(file), ...(browserCliOverride ? { browser: undefined } : {}) }, + { + ...testModes.modes.get(file), + ...(browserCliOverride ? { browser: undefined } : undefined), + }, mergedConfigs.has(file), ); - findings.push(...testModes.findings.filter((item) => item.file === file)); - findings.push(...result.findings); + findings.push(...testModes.findings.filter((item) => item.file === file), ...result.findings); if (source !== result.content) { rewrittenSources.set(file, result.content); } @@ -834,8 +835,8 @@ export function planVitestV5Migration( projects, findings, changes: [...rewrittenSources].flatMap(([file, after]) => { - const before = allSources.get(file)!; - return before !== after ? [{ file, before, after }] : []; + const before = allSources.get(file); + return before !== undefined && before !== after ? [{ file, before, after }] : []; }), inputs, }; @@ -896,7 +897,7 @@ export function applyVitestV5Migration(plan: VitestV5MigrationPlan): number { /** Upgrade runtime declarations before installers or tool migrators start. * Keep source/config edits deferred until the tool version gates pass. */ export function applyVitestV5NodeMigration(plan: VitestV5MigrationPlan): number { - const changes: FileChange[] = []; + const changes: Array = []; for (const [file, before] of plan.inputs) { if ( before === null || @@ -933,7 +934,7 @@ export function vitestV5NeedsMigration(plan: VitestV5MigrationPlan): boolean { ); } -function currentProjectConfigs(plan: VitestV5MigrationPlan): Map { +function currentProjectConfigs(plan: VitestV5MigrationPlan): Map> { const filesByProject = new Map( plan.projects.map((project) => [project.directory, filesInProject(project.directory)]), ); @@ -955,8 +956,8 @@ function currentProjectConfigs(plan: VitestV5MigrationPlan): Map { + const findings: Array = []; const completedProjects = new Map(); const projectConfigs = currentProjectConfigs(plan); const configSources = new Map( @@ -967,7 +968,7 @@ export function finishVitestV5Migration(plan: VitestV5MigrationPlan): VitestV5Fi if (!project.active || !project.sourceVersion) { continue; } - const configs = projectConfigs.get(project.directory)!; + const configs = projectConfigs.get(project.directory) ?? []; for (const file of configs) { const before = fs.readFileSync(file, 'utf8'); try { @@ -1004,7 +1005,7 @@ export function finishVitestV5Migration(plan: VitestV5MigrationPlan): VitestV5Fi `${ignored}${ignored && !ignored.endsWith('\n') ? '\n' : ''}.vitest/\n`, ); } - const pendingSourceReviews: Record = {}; + const pendingSourceReviews: Record> = {}; for (const item of plan.findings) { if ( !DEFERRED_SOURCE_REVIEWS.has(item.code) || diff --git a/packages/cli/src/migration/migrator/yarn.ts b/packages/cli/src/migration/migrator/yarn.ts index 3717466c5d..1a2f77641a 100644 --- a/packages/cli/src/migration/migrator/yarn.ts +++ b/packages/cli/src/migration/migrator/yarn.ts @@ -3,9 +3,11 @@ import os from 'node:os'; import path from 'node:path'; import { coerce } from 'verkit'; -import { Scalar, YAMLSeq } from 'yaml'; +import { isSeq, isScalar } from 'yaml'; +import { YAMLSeq } from 'yaml'; -import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; +import type { WorkspacePackage } from '../../types/index.ts'; +import { PackageManager } from '../../types/index.ts'; import { createCatalogDependencyResolverFromCatalogs } from '../../utils/catalog.ts'; import { VITEST_AGE_GATE_EXEMPT_PACKAGES, @@ -15,13 +17,13 @@ import { import { readJsonFile } from '../../utils/json.ts'; import { editYamlFile, readYamlFile, scalarString } from '../../utils/yaml.ts'; import { overridesSatisfyVitePlus, rewriteCatalog, usesWebdriverioProvider } from '../migrator.ts'; -import { type MigrationReport } from '../report.ts'; +import type { MigrationReport } from '../report.ts'; +import type { DependencyBag } from './shared.ts'; import { WEBDRIVERIO_PROVIDER, findDeclaredSpec, readPackageJsonIfExists, warnMigration, - type DependencyBag, } from './shared.ts'; // Webdriverio is the runtime peer that drags `edgedriver` / `geckodriver` in. @@ -36,7 +38,7 @@ const WEBDRIVERIO_ALLOW_SIGNAL_DEPS = [WEBDRIVERIO_PEER_DEP, WEBDRIVERIO_PROVIDE // Only the provider (or its legacy imports) needs the shared browser override. export function workspaceUsesWebdriverioProvider( rootDir: string, - packages?: WorkspacePackage[], + packages?: Array, ): boolean { return [rootDir, ...(packages ?? []).map((pkg) => path.join(rootDir, pkg.path))].some((dir) => { const pkg = readPackageJsonIfExists(path.join(dir, 'package.json')); @@ -62,7 +64,7 @@ export function hasOwnWebdriverioDependency(pkg: DependencyBag): boolean { export function workspaceUsesWebdriverio( rootDir: string, - packages: WorkspacePackage[] | undefined, + packages: Array | undefined, ): boolean { const rootPkg = readPackageJsonIfExists(path.join(rootDir, 'package.json')); if (rootPkg && hasOwnWebdriverioDependency(rootPkg)) { @@ -116,7 +118,7 @@ function readYarnrcValue(dir: string, key: string): string | undefined { return undefined; } try { - const doc = readYamlFile(yarnrcYmlPath) as Record | null; + const doc = readYamlFile(yarnrcYmlPath); const value = doc?.[key]; return typeof value === 'string' ? value : undefined; } catch { @@ -228,7 +230,7 @@ function dirIsWorkspaceRoot(dir: string): boolean { } try { const pkg = readJsonFile(pkgJsonPath) as { workspaces?: unknown }; - return pkg.workspaces != null; + return pkg.workspaces !== undefined && pkg.workspaces !== null; } catch { return false; } @@ -375,11 +377,13 @@ export function rewriteYarnrcYml( // that already preapproves private packages) instead of skipping when set, // otherwise the gate could still reject the freshly pinned vitest. if (supportPreapproved) { - let npmPreapprovedPackages = doc.getIn(['npmPreapprovedPackages']) as YAMLSeq>; - if (!npmPreapprovedPackages) { - npmPreapprovedPackages = new YAMLSeq(); - } - const existingPreapproved = new Set(npmPreapprovedPackages.items.map((n) => n.value)); + const current = doc.getIn(['npmPreapprovedPackages']); + const npmPreapprovedPackages = isSeq(current) ? current : new YAMLSeq(); + const existingPreapproved = new Set( + npmPreapprovedPackages.items.map((item: unknown) => + isScalar(item) ? item.value : undefined, + ), + ); for (const pkg of VITEST_AGE_GATE_EXEMPT_PACKAGES) { if (!existingPreapproved.has(pkg)) { npmPreapprovedPackages.add(scalarString(pkg)); @@ -415,7 +419,7 @@ export function yarnrcSatisfiesVitePlus( } const doc = readYamlFile(yarnrcYmlPath) as { nodeLinker?: string; - npmPreapprovedPackages?: string[]; + npmPreapprovedPackages?: Array; catalog?: Record; catalogs?: Record>; } | null; diff --git a/packages/cli/src/migration/npm-reinstall.ts b/packages/cli/src/migration/npm-reinstall.ts index 6b83ed8c2d..84a5a428bc 100644 --- a/packages/cli/src/migration/npm-reinstall.ts +++ b/packages/cli/src/migration/npm-reinstall.ts @@ -34,7 +34,7 @@ interface MovedViteInstall { // installed package while it sits inside node_modules during the reinstall. const STALE_VITE_BACKUP_NAME = '.vite-plus-migrate-stale-vite'; -function removeStaleInstalledVite(packagePath: string, moved: MovedViteInstall[]): boolean { +function removeStaleInstalledVite(packagePath: string, moved: Array): boolean { const packageJsonPath = path.join(packagePath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { return false; @@ -85,10 +85,10 @@ export interface NpmViteAliasReinstallPreparation { */ export function prepareNpmViteAliasReinstall( rootDir: string, - projectPaths: string[] = [rootDir], + projectPaths: Array = [rootDir], ): NpmViteAliasReinstallPreparation { const packageLockPath = path.join(rootDir, 'package-lock.json'); - const moved: MovedViteInstall[] = []; + const moved: Array = []; let changed = false; if (fs.existsSync(packageLockPath)) { @@ -117,7 +117,7 @@ export function prepareNpmViteAliasReinstall( } if (lockChanged) { - writeJsonFile(packageLockPath, packageLock as unknown as Record); + writeJsonFile(packageLockPath, packageLock); changed = true; } } catch { diff --git a/packages/cli/src/migration/options.ts b/packages/cli/src/migration/options.ts index ecbd9a8885..35c130810c 100644 --- a/packages/cli/src/migration/options.ts +++ b/packages/cli/src/migration/options.ts @@ -1,7 +1,7 @@ /** CLI options parsed for `vp migrate`. */ export interface MigrationOptions { interactive: boolean; - agent?: string | string[] | false; + agent?: string | Array | false; editor?: string | false; hooks?: boolean; full?: boolean; diff --git a/packages/cli/src/migration/renovate-json5.ts b/packages/cli/src/migration/renovate-json5.ts index 5b7d25ba0e..0e51f260c6 100644 --- a/packages/cli/src/migration/renovate-json5.ts +++ b/packages/cli/src/migration/renovate-json5.ts @@ -1,4 +1,10 @@ -import type * as t from '@oxc-project/types'; +import type { + ArrayExpression, + Node, + ObjectExpression, + ObjectPropertyKind, + Span, +} from '@oxc-project/types'; import { detectFormattingOptions } from '../utils/json.ts'; import { isString, objectProperty, staticObject } from './ast-utils.ts'; @@ -10,7 +16,7 @@ const JSON5_NUMBER = const CODE_POINT_ESCAPE = /(?:^|[^\\])(?:\\\\)*\\u\{/; const LINE_INDENT = /(\r\n|[\r\n\u2028\u2029])([^\S\r\n\u2028\u2029]*)$/; -function isJson5Value(node: t.Node, source: string): boolean { +function isJson5Value(node: Node, source: string): boolean { switch (node.type) { case 'ObjectExpression': return ( @@ -86,22 +92,24 @@ export async function withJson5Preset(source: string, preset: string): Promise, entry: string, ): string { const items = container.type === 'ArrayExpression' ? container.elements : container.properties; @@ -147,7 +155,7 @@ function appendEntry( let spacing: string; if (newline) { let indent = lastLine?.[2]; - if (indent == null) { + if (indent === undefined || indent === null) { const { insertSpaces, tabSize } = detectFormattingOptions(source); indent = (closingLine?.[2] ?? '') + (insertSpaces ? ' '.repeat(tabSize ?? 2) : '\t'); } diff --git a/packages/cli/src/migration/renovate.ts b/packages/cli/src/migration/renovate.ts index 4beeac4401..b21254bbe8 100644 --- a/packages/cli/src/migration/renovate.ts +++ b/packages/cli/src/migration/renovate.ts @@ -1,8 +1,10 @@ import fs from 'node:fs/promises'; import path from 'node:path'; -import { findNodeAtLocation, parseTree, type Node, type ParseError } from 'jsonc-parser'; +import type { Node, ParseError } from 'jsonc-parser'; +import { findNodeAtLocation, parseTree } from 'jsonc-parser'; +import { errorCode } from '../utils/error.ts'; import { appendMissingJsoncArrayItems, detectFormattingOptions } from '../utils/json.ts'; import { withJson5Preset } from './renovate-json5.ts'; @@ -27,10 +29,15 @@ export const STANDALONE_RENOVATE_CONFIG_FILES = [ ]; const CONFIG_FILES = [...STANDALONE_RENOVATE_CONFIG_FILES, 'package.json']; +function stringValue(node: Node | undefined): string | undefined { + const value: unknown = node?.value; + return typeof value === 'string' ? value : undefined; +} + function hasDuplicateKeys(node: Node): boolean { const children = node.children ?? []; if (node.type === 'object') { - const keys = children.map((property) => property.children![0].value); + const keys = children.map((property) => stringValue(property.children?.[0])); if (keys.length !== new Set(keys).size) { return true; } @@ -43,7 +50,7 @@ async function withVitePlusPreset(file: string, source: string): Promise = []; const tree = parseTree(source, errors, { allowTrailingComma: !embedded, disallowComments: embedded, @@ -71,8 +78,8 @@ async function withVitePlusPreset(file: string, source: string): Promise item.value); - if (presets?.some((preset) => typeof preset !== 'string' || preset === PRESET)) { + const presets = extendsNode?.children?.map(stringValue); + if (presets?.some((preset) => preset === undefined || preset === PRESET)) { return undefined; } // Keep a compact config or preset list on one line. @@ -95,7 +102,7 @@ export async function findRenovateConfigToUpdate(rootDir: string): Promise try { source = await fs.readFile(file, 'utf8'); } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + if (errorCode(error) === 'ENOENT') { return false; } throw error; diff --git a/packages/cli/src/migration/report.ts b/packages/cli/src/migration/report.ts index 220d5f83a3..44813bd7c5 100644 --- a/packages/cli/src/migration/report.ts +++ b/packages/cli/src/migration/report.ts @@ -34,9 +34,9 @@ export interface MigrationReport { frameworkShimAdded: boolean; packageManagerBootstrapConfigured: boolean; vitePeerDependencyRuleRemoved: boolean; - dependencyUpgrades: DependencyVersionChange[]; - warnings: string[]; - manualSteps: string[]; + dependencyUpgrades: Array; + warnings: Array; + manualSteps: Array; } export function createMigrationReport(): MigrationReport { diff --git a/packages/cli/src/migration/setup-plan.ts b/packages/cli/src/migration/setup-plan.ts index 35cb580ee0..e0a4766e70 100644 --- a/packages/cli/src/migration/setup-plan.ts +++ b/packages/cli/src/migration/setup-plan.ts @@ -1,19 +1,20 @@ import { styleText } from 'node:util'; -import * as prompts from '@voidzero-dev/vite-plus-prompts'; +import { + isCancel, + log as promptLog, + select as promptSelect, +} from '@voidzero-dev/vite-plus-prompts'; -import { PackageManager, type WorkspacePackage } from '../types/index.ts'; +import type { PackageManager } from '../types/index.ts'; +import type { WorkspacePackage } from '../types/index.ts'; import { detectAgentConflicts, detectExistingAgentTargetPaths, selectAgentTargetPaths, } from '../utils/agent.ts'; -import { - detectEditorConflicts, - type EditorId, - isJsonLikeFile, - selectEditor, -} from '../utils/editor.ts'; +import type { EditorId } from '../utils/editor.ts'; +import { detectEditorConflicts, isJsonLikeFile, selectEditor } from '../utils/editor.ts'; import { cancelAndExit, promptGitHooks } from '../utils/prompts.ts'; import { log, muted } from '../utils/terminal.ts'; import { @@ -34,7 +35,7 @@ import type { MigrationOptions } from './options.ts'; export interface MigrationSetupPlan { shouldSetupHooks: boolean; - selectedAgentTargetPaths?: string[]; + selectedAgentTargetPaths?: Array; agentConflictDecisions: Map; selectedEditor?: EditorId; editorConflictDecisions: Map; @@ -46,7 +47,7 @@ async function collectGitHooksDecision( rootDir: string, packageManager: PackageManager | undefined, options: MigrationOptions, - packages: readonly WorkspacePackage[] = [], + packages: ReadonlyArray = [], ): Promise { const hasExistingHooks = options.hooks === undefined && hasExistingViteHooksPolicy(rootDir); if (hasExistingHooks && isViteHooksSetupComplete(rootDir)) { @@ -60,7 +61,7 @@ async function collectGitHooksDecision( } const reason = preflightGitHooksSetup(rootDir, packageManager, packages); if (reason) { - prompts.log.warn(`⚠ ${reason}`); + promptLog.warn(`⚠ ${reason}`); return false; } return true; @@ -70,7 +71,7 @@ async function collectAgentInstructionPlan( rootDir: string, options: MigrationOptions, ): Promise<{ - selectedAgentTargetPaths?: string[]; + selectedAgentTargetPaths?: Array; agentConflictDecisions: Map; }> { const existingAgentTargetPaths = @@ -93,7 +94,7 @@ async function collectAgentInstructionPlan( const agentConflictDecisions = new Map(); for (const conflict of agentConflicts) { if (options.interactive) { - const action = await prompts.select({ + const action = await promptSelect({ message: `Agent instructions already exist at ${conflict.targetPath}.\n ` + styleText( @@ -106,7 +107,7 @@ async function collectAgentInstructionPlan( ], initialValue: 'skip' as const, }); - if (prompts.isCancel(action)) { + if (isCancel(action)) { cancelAndExit(); } agentConflictDecisions.set(conflict.targetPath, action); @@ -138,7 +139,7 @@ async function collectEditorConfigPlan( const editorConflictDecisions = new Map(); for (const conflict of editorConflicts) { if (options.interactive) { - const action = await prompts.select({ + const action = await promptSelect({ message: `${conflict.displayPath} already exists.\n ` + styleText( @@ -155,7 +156,7 @@ async function collectEditorConfigPlan( ], initialValue: 'skip' as const, }); - if (prompts.isCancel(action)) { + if (isCancel(action)) { cancelAndExit(); } editorConflictDecisions.set(conflict.fileName, action); @@ -174,7 +175,7 @@ async function collectEditorConfigPlan( async function collectEslintMigrationDecision( rootDir: string, options: MigrationOptions, - packages?: WorkspacePackage[], + packages?: Array, ): Promise<{ migrateEslint: boolean; eslintConfigFile?: string }> { const eslintProject = detectEslintProject(rootDir, packages); const incompatibleEslintIntegration = detectIncompatibleEslintIntegration(rootDir, packages); @@ -204,7 +205,7 @@ async function collectEslintMigrationDecision( export async function collectTsupMigrationDecision( rootDir: string, options: MigrationOptions, - packages?: WorkspacePackage[], + packages?: Array, ): Promise<{ migrateTsup: boolean; tsupConfigFile?: string }> { const tsupProject = detectTsupProject(rootDir, packages); let migrateTsup = false; @@ -221,7 +222,7 @@ export async function collectMigrationSetupPlan( rootDir: string, packageManager: PackageManager | undefined, options: MigrationOptions, - packages?: WorkspacePackage[], + packages?: Array, includeEslint = true, ): Promise { const shouldSetupHooks = await collectGitHooksDecision( diff --git a/packages/cli/src/migration/versions.d.ts b/packages/cli/src/migration/versions.d.ts new file mode 100644 index 0000000000..fc45be17d6 --- /dev/null +++ b/packages/cli/src/migration/versions.d.ts @@ -0,0 +1,2 @@ +// The CLI build redirects the migrator's relative import to dist/versions.js. +export { versions } from 'vite-plus/versions'; diff --git a/packages/cli/src/migration/vitest-v5/ast.ts b/packages/cli/src/migration/vitest-v5/ast.ts index a8451185a6..b8960b2a35 100644 --- a/packages/cli/src/migration/vitest-v5/ast.ts +++ b/packages/cli/src/migration/vitest-v5/ast.ts @@ -1,18 +1,26 @@ -import type * as t from '@oxc-project/types'; +import type { + ArrayExpression, + ArrowFunctionExpression, + Function, + Node, + ObjectExpression, + ObjectProperty, + Program, + Span, +} from '@oxc-project/types'; import { isString, memberName, objectProperty, parseSource, propertyName } from '../ast-utils.ts'; interface Binding { - declaration: t.Node; - references: t.Node[]; + declaration: Node; + references: Array; constant: boolean; } -type Visitors = { - [Type in t.Node['type']]?: (node: Extract) => void; -}; +type NodeByType = { [Variant in Node as Variant['type']]: Variant }; +type Visitors = { [Type in keyof NodeByType]?: (node: NodeByType[Type]) => void }; -function isNode(value: unknown): value is t.Node { +function isNode(value: unknown): value is Node { return typeof value === 'object' && value !== null && 'type' in value && 'start' in value; } @@ -27,7 +35,7 @@ export interface VitestV5Finding { export interface RewriteResult { content: string; - findings: VitestV5Finding[]; + findings: Array; } export interface SourceOptions { @@ -41,7 +49,7 @@ export interface SourceOptions { temporalPolyfill?: boolean; } -export function isModuleExports(editor: SourceEditor, node: t.Node): boolean { +export function isModuleExports(editor: SourceEditor, node: Node): boolean { return ( node.type === 'MemberExpression' && !node.computed && @@ -54,8 +62,8 @@ export function isModuleExports(editor: SourceEditor, node: t.Node): boolean { /** Consider both possible project lists without evaluating environment-dependent * config code. Unknown spreads stay in the list for a localized review. */ -export function projectElements(node: t.ArrayExpression): Array { - const expand = (value: t.Node): Array | undefined => { +export function projectElements(node: ArrayExpression): Array { + const expand = (value: Node): Array | undefined => { if (value.type === 'ArrayExpression') { return projectElements(value); } @@ -83,7 +91,7 @@ export function projectElements(node: t.ArrayExpression): Array { export function importedName( editor: SourceEditor, - node: t.Node | null | undefined, + node: Node | null | undefined, sources: ReadonlySet, ): string | undefined { if ( @@ -131,7 +139,7 @@ export const NODE_SOURCES = new Set(['vitest/node', 'vite-plus/test/node']); export function testApiName( editor: SourceEditor, - node: t.Node | null | undefined, + node: Node | null | undefined, globals = false, ): string | undefined { const imported = importedName(editor, node, ROOT_TEST_SOURCES); @@ -162,7 +170,7 @@ export function testApiName( return undefined; } -export function isImportMetaVitest(node: t.Node | null | undefined): boolean { +export function isImportMetaVitest(node: Node | null | undefined): boolean { return ( node?.type === 'MemberExpression' && !node.optional && @@ -175,7 +183,7 @@ export function isImportMetaVitest(node: t.Node | null | undefined): boolean { export interface AddedProperty { key: string; - value: string | AddedProperty[]; + value: string | Array; comment?: string; } @@ -191,7 +199,11 @@ function printAddedProperty(property: AddedProperty, indent: string, newline: st } /** Format generated objects without reindenting copied expressions or string literals. */ -export function printAddedObject(properties: AddedProperty[], indent = '', newline = '\n'): string { +export function printAddedObject( + properties: Array, + indent = '', + newline = '\n', +): string { const childIndent = `${indent} `; return `{${newline}${properties .map((property) => `${childIndent}${printAddedProperty(property, childIndent, newline)}`) @@ -200,17 +212,17 @@ export function printAddedObject(properties: AddedProperty[], indent = '', newli /** Offset edits retain comments and formatting outside the precise changed span. */ export class SourceEditor { - readonly ast: t.Program; - readonly comments: t.Span[]; - readonly findings: VitestV5Finding[] = []; - private readonly nodes: t.Node[] = []; - private readonly parents = new Map(); + readonly ast: Program; + readonly comments: Array; + readonly findings: Array = []; + private readonly nodes: Array = []; + private readonly parents = new Map(); private readonly bindings = new Map(); private readonly names = new Set(); private readonly edits: Array<{ start: number; end: number; text: string }> = []; - private readonly additions = new Map>(); + private readonly additions = new Map>(); private readonly reported = new Set(); - private lineStarts?: number[]; + private lineStarts?: Array; constructor( readonly file: string, @@ -219,8 +231,8 @@ export class SourceEditor { const parsed = parseSource(file, source); this.ast = parsed.program; this.comments = parsed.comments; - const identifiers = new Map(); - const index = (node: t.Node, parent?: t.Node) => { + const identifiers = new Map(); + const index = (node: Node, parent?: Node) => { this.nodes.push(node); if (parent) { this.parents.set(node, parent); @@ -253,18 +265,19 @@ export class SourceEditor { } visit(visitors: Visitors): void { + function dispatch(type: Type, node: NodeByType[Type]) { + visitors[type]?.(node); + } for (const node of this.nodes) { - // Dispatch by the same discriminant that selects the visitor's node type. - const visitor = visitors[node.type] as ((node: t.Node) => void) | undefined; - visitor?.(node); + dispatch(node.type, node); } } - parent(node: t.Node): t.Node | undefined { + parent(node: Node): Node | undefined { return this.parents.get(node); } - functionParent(node: t.Node): t.Function | t.ArrowFunctionExpression | undefined { + functionParent(node: Node): Function | ArrowFunctionExpression | undefined { let parent = this.parent(node); while (parent) { if ( @@ -279,7 +292,7 @@ export class SourceEditor { return undefined; } - binding(node: t.Node): Binding | undefined { + binding(node: Node): Binding | undefined { return node.type === 'Identifier' ? this.bindings.get(node.start) : undefined; } @@ -293,11 +306,11 @@ export class SourceEditor { return name; } - text(node: t.Node): string { + text(node: Node): string { return this.source.slice(node.start, node.end); } - replace(node: t.Node, text: string): void { + replace(node: Node, text: string): void { this.edit(node.start, node.end, text); } @@ -314,7 +327,7 @@ export class SourceEditor { } add( - object: t.ObjectExpression, + object: ObjectExpression, key: string, value: AddedProperty['value'], comment?: string, @@ -330,7 +343,7 @@ export class SourceEditor { additions.set(key, { key, value, comment }); } - remove(object: t.ObjectExpression, prop: t.ObjectProperty): void { + remove(object: ObjectExpression, prop: ObjectProperty): void { const index = object.properties.indexOf(prop); const nextStart = object.properties[index + 1]?.start ?? object.end - 1; const previousEnd = object.properties[index - 1]?.end ?? object.start + 1; @@ -357,7 +370,7 @@ export class SourceEditor { } report( - node: t.Node | undefined, + node: Node | undefined, code: string, message: string, severity: VitestV5Finding['severity'] = 'review', diff --git a/packages/cli/src/migration/vitest-v5/benchmark-config.ts b/packages/cli/src/migration/vitest-v5/benchmark-config.ts index 4b5a8a51c8..573dbe3c5e 100644 --- a/packages/cli/src/migration/vitest-v5/benchmark-config.ts +++ b/packages/cli/src/migration/vitest-v5/benchmark-config.ts @@ -1,7 +1,7 @@ -import type * as t from '@oxc-project/types'; +import type { Node, ObjectExpression } from '@oxc-project/types'; import { isString, objectProperty, staticObject } from '../ast-utils.ts'; -import { SourceEditor } from './ast.ts'; +import type { SourceEditor } from './ast.ts'; const REPORTERS = new Set([ 'default', @@ -15,14 +15,14 @@ const REPORTERS = new Set([ 'github-actions', ]); -function reporterNames(node: t.Node): string[] | undefined { +function reporterNames(node: Node): Array | undefined { const entries = node.type === 'ArrayExpression' ? node.elements : [node]; return entries.every(isString) ? entries.map((entry) => entry.value) : undefined; } /** Move only resolved built-in output settings. The normal config pass reports * any retained legacy options as blockers; no partial output plan is applied. */ -export function migrateBenchmarkConfig(editor: SourceEditor, test: t.ObjectExpression): void { +export function migrateBenchmarkConfig(editor: SourceEditor, test: ObjectExpression): void { const benchmark = objectProperty(test, 'benchmark')?.value; if (!staticObject(benchmark)) { return; diff --git a/packages/cli/src/migration/vitest-v5/benchmarks.ts b/packages/cli/src/migration/vitest-v5/benchmarks.ts index 88b765e745..64a6edc64f 100644 --- a/packages/cli/src/migration/vitest-v5/benchmarks.ts +++ b/packages/cli/src/migration/vitest-v5/benchmarks.ts @@ -1,27 +1,28 @@ -import type * as t from '@oxc-project/types'; +import type { + BindingProperty, + CallExpression, + ImportSpecifier, + Node, + Span, +} from '@oxc-project/types'; import { isString, propertyName, memberName } from '../ast-utils.ts'; -import { SourceEditor, isImportMetaVitest, testApiName } from './ast.ts'; +import type { SourceEditor } from './ast.ts'; +import { isImportMetaVitest, testApiName } from './ast.ts'; interface BenchmarkCall { - call: t.CallExpression; + call: CallExpression; + statement: Node; modifier?: string; } /** Keep the workload as a separate callback: making it the test callback * would measure nothing, and inlining it into a new closure can change scope. */ -export function migrateBenchmarks( - editor: SourceEditor, - globals = false, -): { - imports: Set; - bindings: Set; - calls: Set; -} { - const imports = new Set(); - const bindings = new Set(); - const calls = new Set(); - const benchIdentifiers: t.Span[] = []; +export function migrateBenchmarks(editor: SourceEditor, globals = false) { + const imports = new Set(); + const bindings = new Set(); + const calls = new Set(); + const benchIdentifiers: Array = []; let fixtureAlias: string | undefined; let shadowedGlobalThis = false; editor.visit({ @@ -35,7 +36,7 @@ export function migrateBenchmarks( }, }); - function workload(node: t.Node, seen = new Set()): boolean { + function workload(node: Node, seen = new Set()): boolean { if ( node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression' || @@ -62,7 +63,7 @@ export function migrateBenchmarks( ); } - function directCall(reference: t.Node): BenchmarkCall | undefined { + function directCall(reference: Node): BenchmarkCall | undefined { let callee = reference; let modifier: string | undefined; const member = editor.parent(reference); @@ -74,12 +75,13 @@ export function migrateBenchmarks( callee = member; } const call = editor.parent(callee); + const statement = call && editor.parent(call); if ( call?.type !== 'CallExpression' || call.callee !== callee || call.optional || call.typeArguments || - editor.parent(call)?.type !== 'ExpressionStatement' || + statement?.type !== 'ExpressionStatement' || !call.arguments[0] || call.arguments[0].type === 'SpreadElement' ) { @@ -121,10 +123,10 @@ export function migrateBenchmarks( } fn = editor.functionParent(registration); } - return { call, modifier }; + return { call, modifier, statement }; } - function rewrite({ call, modifier }: BenchmarkCall, test: string) { + function rewrite({ call, modifier, statement }: BenchmarkCall, test: string) { calls.add(call); editor.replace(call.callee, `${test}${modifier ? `.${modifier}` : ''}`); const callback = call.arguments[1]; @@ -132,7 +134,7 @@ export function migrateBenchmarks( return; } let name = editor.text(call.arguments[0]); - const captures: string[] = []; + const captures: Array = []; if (!isString(call.arguments[0])) { const captured = editor.uniqueName('benchName'); captures.push(`const ${captured} = (${name});`); @@ -147,7 +149,6 @@ export function migrateBenchmarks( if (captures.length) { // Capture at registration, in the original lexical scope and argument // order. A test executes later, after names or callback bindings may change. - const statement = editor.parent(call)!; editor.edit(statement.start, statement.start, `{ ${captures.join(' ')} `); editor.edit(statement.end, statement.end, ' }'); } @@ -171,7 +172,7 @@ export function migrateBenchmarks( editor.edit(callback.end, callback.end, ').run(); }'); } - function unsupportedInSource(node: t.Node) { + function unsupportedInSource(node: Node) { editor.report( node, 'benchmark-api', @@ -197,7 +198,7 @@ export function migrateBenchmarks( !binding?.constant || node.id.properties.some((prop) => prop.type === 'RestElement') || !registrations || - registrations.some((registration) => !registration) + !registrations.every((registration) => registration !== undefined) ) { unsupportedInSource(property); continue; @@ -208,7 +209,7 @@ export function migrateBenchmarks( editor.replace(property, test === 'test' ? 'test' : `test: ${test}`); bindings.add(property); for (const registration of registrations) { - rewrite(registration!, test); + rewrite(registration, test); } } }, @@ -231,14 +232,14 @@ export function migrateBenchmarks( const registrations = binding.references.map(directCall); // Retarget an import only when all uses are understood. A callback // passed to a wrapper or a re-export must not become a test function. - if (registrations.some((registration) => !registration)) { + if (!registrations.every((registration) => registration !== undefined)) { continue; } const test = editor.uniqueName('test', true); editor.replace(specifier, test === 'test' ? 'test' : `test as ${test}`); imports.add(specifier); for (const registration of registrations) { - rewrite(registration!, test); + rewrite(registration, test); } } }, diff --git a/packages/cli/src/migration/vitest-v5/commands.ts b/packages/cli/src/migration/vitest-v5/commands.ts index 2955214cf1..47cc204cf6 100644 --- a/packages/cli/src/migration/vitest-v5/commands.ts +++ b/packages/cli/src/migration/vitest-v5/commands.ts @@ -3,12 +3,12 @@ import { getCommandStartIndex, SHELL_STATE_COMMANDS } from '../migrator/shared.t import type { RewriteResult, VitestV5Finding } from './ast.ts'; /** Read test commands without evaluating shell state or directory changes. */ -export function literalTestCommands(command: string): string[][] | undefined { +export function literalTestCommands(command: string): Array> | undefined { const commands = parseLiteralCommands(command, true); if (!commands) { return undefined; } - const result: string[][] = []; + const result: Array> = []; for (const tokens of commands) { const values = tokens.map(({ value }) => value); while (/^[A-Za-z_]\w*=/.test(values[0] ?? '')) { @@ -23,7 +23,7 @@ export function literalTestCommands(command: string): string[][] | undefined { } /** Locate the runner's arguments after a supported package-manager wrapper. */ -export function vitestCommandArgsStart(values: readonly string[]): number { +export function vitestCommandArgsStart(values: ReadonlyArray): number { const start = getCommandStartIndex(values); if (values[start] === 'vitest') { return start + 1; @@ -99,7 +99,7 @@ function migrateBenchmarkOutput(command: string): string { return command; } } - const reporters: string[] = []; + const reporters: Array = []; for (const [index, { value }] of args.entries()) { if (/^--reporters?=/.test(value)) { reporters.push(value.slice(value.indexOf('=') + 1)); @@ -125,7 +125,7 @@ export function migrateVitestV5Command( line = 1, reviewV4 = preserveV4, ): RewriteResult { - const findings: VitestV5Finding[] = []; + const findings: Array = []; const report = ( code: string, message: string, diff --git a/packages/cli/src/migration/vitest-v5/config-object.ts b/packages/cli/src/migration/vitest-v5/config-object.ts index 84e3cf216e..9a7ac0125a 100644 --- a/packages/cli/src/migration/vitest-v5/config-object.ts +++ b/packages/cli/src/migration/vitest-v5/config-object.ts @@ -1,13 +1,14 @@ -import type * as t from '@oxc-project/types'; +import type { Node, ObjectExpression } from '@oxc-project/types'; import { propertyName } from '../ast-utils.ts'; -import { CONFIG_SOURCES, SourceEditor, importedName, isModuleExports } from './ast.ts'; +import type { SourceEditor } from './ast.ts'; +import { CONFIG_SOURCES, importedName, isModuleExports } from './ast.ts'; const CONFIG_KEYS = new Set(['root', 'test', 'extends']); // A conditional spread of build/server options cannot change test ownership. // Unknown spreads (including imported objects) must still be reviewed. -function unrelatedSpread(node: t.Node): boolean { +function unrelatedSpread(node: Node): boolean { if (node.type === 'ConditionalExpression') { return unrelatedSpread(node.consequent) && unrelatedSpread(node.alternate); } @@ -26,8 +27,8 @@ function unrelatedSpread(node: t.Node): boolean { * alternative configs. Return the original object so edits keep its spans. */ export function resolveConfigObject( editor: SourceEditor, - node: t.Node | null | undefined, -): t.ObjectExpression | undefined { + node: Node | null | undefined, +): ObjectExpression | undefined { if (node?.type === 'Identifier') { const binding = editor.binding(node); if ( diff --git a/packages/cli/src/migration/vitest-v5/config.ts b/packages/cli/src/migration/vitest-v5/config.ts index 3f3ded2c14..ee859ba8bf 100644 --- a/packages/cli/src/migration/vitest-v5/config.ts +++ b/packages/cli/src/migration/vitest-v5/config.ts @@ -1,6 +1,6 @@ import path from 'node:path'; -import type * as t from '@oxc-project/types'; +import type { Node, ObjectExpression } from '@oxc-project/types'; import { minimatch } from 'minimatch'; import { @@ -11,21 +11,19 @@ import { isString, isBoolean, } from '../ast-utils.ts'; +import type { AddedProperty, RewriteResult, SourceOptions } from './ast.ts'; import { CONFIG_SOURCES, SourceEditor, importedName, projectElements, isModuleExports, - type AddedProperty, - type RewriteResult, - type SourceOptions, } from './ast.ts'; import { migrateBenchmarkConfig } from './benchmark-config.ts'; import { compatibilityProperty } from './compatibility.ts'; import { resolveConfigObject } from './config-object.ts'; -function isTrue(node: t.Node | undefined): boolean { +function isTrue(node: Node | undefined): boolean { return isBoolean(node) && node.value; } @@ -86,17 +84,17 @@ function hasTestConfigHelper(file: string, source: string): boolean { * export a raw object. Candidate files come from the owning package's scan. */ export function findVitestV5ConfigFiles( sources: ReadonlyMap, - entries: string[] = [], + entries: Array = [], ): Set { - const files = new Set( - [...sources] - .filter( - ([file, source]) => - /\.[cm]?[jt]sx?$/.test(file) && - (CONFIG_FILENAME.test(file) || hasTestConfigHelper(file, source)), - ) - .map(([file]) => file), - ); + const files = new Set(); + for (const [file, source] of sources) { + if ( + /\.[cm]?[jt]sx?$/.test(file) && + (CONFIG_FILENAME.test(file) || hasTestConfigHelper(file, source)) + ) { + files.add(file); + } + } for (const file of entries) { if (sources.has(file)) { files.add(file); @@ -104,7 +102,11 @@ export function findVitestV5ConfigFiles( } for (const file of files) { try { - const editor = new SourceEditor(file, sources.get(file)!); + const source = sources.get(file); + if (source === undefined) { + continue; + } + const editor = new SourceEditor(file, source); function addReference(reference: string): void { if (reference.startsWith('!')) { return; @@ -128,7 +130,7 @@ export function findVitestV5ConfigFiles( } } } - const collectReferences = (config: t.Node | undefined) => { + const collectReferences = (config: Node | undefined) => { const object = resolveConfigObject(editor, config); if (!object) { return; @@ -207,15 +209,19 @@ export function findVitestV5MergedConfigFiles( configFiles: ReadonlySet, ): Set { const merged = new Set(); - const imports = new Map(); + const imports = new Map>(); const extensions = ['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs', '.tsx', '.jsx']; for (const file of configFiles) { try { - const editor = new SourceEditor(file, sources.get(file)!); + const source = sources.get(file); + if (source === undefined) { + continue; + } + const editor = new SourceEditor(file, source); if (hasConfigMerge(editor)) { merged.add(file); } - const dependencies: string[] = []; + const dependencies: Array = []; for (const node of editor.ast.body) { if ( node.type !== 'ImportDeclaration' && @@ -280,7 +286,7 @@ function migrateConfig( benchmarkOnly = false, ): RewriteResult { const editor = new SourceEditor(file, source); - const visited = new Set(); + const visited = new Set(); const merged = mergedConfig || hasConfigMerge(editor); const preserveDefaults = options.preserveV4 && !merged && !benchmarkOnly; const reviewV4 = options.preserveV4 || options.reviewV4; @@ -293,10 +299,10 @@ function migrateConfig( } function nested( - object: t.ObjectExpression, + object: ObjectExpression, key: string, - additions: string | AddedProperty[], - apply: (node: t.ObjectExpression) => void, + additions: string | Array, + apply: (node: ObjectExpression) => void, ) { const prop = objectProperty(object, key); if (!prop) { @@ -313,18 +319,14 @@ function migrateConfig( } function addCompatibility( - object: t.ObjectExpression, + object: ObjectExpression, key: Parameters[0], ) { const property = compatibilityProperty(key); editor.add(object, key, property.value, property.comment); } - function testOptions( - test: t.ObjectExpression, - inherits: boolean, - parentTest?: t.ObjectExpression, - ) { + function testOptions(test: ObjectExpression, inherits: boolean, parentTest?: ObjectExpression) { if (benchmarkOnly) { // Reporters are global; do not invent destinations on inline projects or // fragments whose effective root settings depend on a merge. @@ -511,7 +513,7 @@ function migrateConfig( } } - function config(object: t.ObjectExpression, inherits = false, parentTest?: t.ObjectExpression) { + function config(object: ObjectExpression, inherits = false, parentTest?: ObjectExpression) { if (visited.has(object)) { return; } diff --git a/packages/cli/src/migration/vitest-v5/documentation.ts b/packages/cli/src/migration/vitest-v5/documentation.ts index 54ff8c87a6..ff12596b06 100644 --- a/packages/cli/src/migration/vitest-v5/documentation.ts +++ b/packages/cli/src/migration/vitest-v5/documentation.ts @@ -1,9 +1,10 @@ import { documentationUrl } from '../../utils/documentation.ts'; +import { lookupSetting } from '../migrator/shared.ts'; const guide = documentationUrl('/guide/vitest-v5'); const upstream = 'https://vitest.dev/guide/migration/'; -const sections: Record = { +const sections = { 'api-conflict': 'browser-api-is-replaced-by-the-top-level-api', 'assertion-types': 'assertion-types-expose-return-and-received-types', 'async-render': 'render-is-async-in-vitest-browser-vue-and-vitest-browser-svelte', @@ -33,7 +34,7 @@ const sections: Record = { 'worker-id': 'worker-and-concurrency-ids-are-1-based', }; -export const localSections: Record = { +export const localSections = { 'browser-provider': 'community-webdriverio-provider', 'dynamic-config': 'resolve-migration-findings', 'dynamic-project': 'resolve-migration-findings', @@ -51,8 +52,8 @@ export const localSections: Record = { /** Give future/unknown findings a useful fallback rather than omitting help. */ export function vitestV5Documentation(code: string): string { - if (sections[code]) { - return `${upstream}#${sections[code]}`; + if (lookupSetting(sections, code)) { + return `${upstream}#${lookupSetting(sections, code)}`; } - return `${guide}#${localSections[code] ?? 'resolve-migration-findings'}`; + return `${guide}#${lookupSetting(localSections, code) ?? 'resolve-migration-findings'}`; } diff --git a/packages/cli/src/migration/vitest-v5/lockfile.ts b/packages/cli/src/migration/vitest-v5/lockfile.ts index ee07925bc6..8cf5f7e0b3 100644 --- a/packages/cli/src/migration/vitest-v5/lockfile.ts +++ b/packages/cli/src/migration/vitest-v5/lockfile.ts @@ -1,24 +1,22 @@ import fs from 'node:fs'; import path from 'node:path'; -import { parse as parseJsonc, type ParseError } from 'jsonc-parser'; +import type { ParseError } from 'jsonc-parser'; +import { parse as parseJsonc } from 'jsonc-parser'; import { normalize, normalizeRange, satisfies } from 'verkit'; import { parseDocument } from 'yaml'; import { PackageManager } from '../../types/index.ts'; +import type { YamlMapping } from '../../utils/yaml-value.ts'; +import { isYamlMapping } from '../../utils/yaml-value.ts'; -function record(value: unknown): Record | undefined { - return value !== null && typeof value === 'object' && !Array.isArray(value) - ? (value as Record) - : undefined; +function record(value: unknown): YamlMapping | undefined { + return isYamlMapping(value) ? value : undefined; } -export type LockfileReader = (file: string, parse: (source: string) => T) => T | undefined; - -/** Create one reader per preflight, with a single parser for each lockfile path. */ -export function createLockfileReader(): LockfileReader { - const locks = new Map(); - return (file: string, parse: (source: string) => T): T | undefined => { +function cacheParsedFiles() { + const locks = new Map(); + return (file: string, parse: (source: string) => T) => { if (!locks.has(file)) { // Cache failed reads and parses too, until the next preflight. locks.set(file, undefined); @@ -28,9 +26,18 @@ export function createLockfileReader(): LockfileReader { // Missing or malformed locks are not evidence of a runner version. } } - return locks.get(file) as T | undefined; + return locks.get(file); + }; +} + +/** Cache parsed manifests and Yarn's different lock format for one preflight. */ +export function createLockfileReader() { + return { + manifest: cacheParsedFiles(), + yarn: cacheParsedFiles>(), }; } +export type LockfileReader = ReturnType; function parseYarnLockfile(text: string) { if (/^__metadata:/m.test(text)) { @@ -42,7 +49,7 @@ function parseYarnLockfile(text: string) { } // Classic's quoted descriptor lists are YAML flow scalars, but its entry // bodies are not YAML. Read only the exact descriptor and version field. - const entries: { keys: unknown[]; version: string | undefined }[] = []; + const entries: Array<{ keys: Array; version: string | undefined }> = []; for (const block of text.split(/\r?\n(?=[^\s#])/)) { const [header] = block.split(/\r?\n/); if (!header.endsWith(':')) { @@ -51,13 +58,13 @@ function parseYarnLockfile(text: string) { const document = parseDocument(`[${header.slice(0, -1)}]`); const keys: unknown = document.errors.length ? undefined : document.toJS(); if (Array.isArray(keys)) { - entries.push({ keys, version: /^ version "([^"]+)"\r?$/m.exec(block)?.[1] }); + entries.push({ keys, version: /^ {2}version "([^"]+)"\r?$/m.exec(block)?.[1] }); } } return { modern: false as const, entries }; } -function declaredVitest(pkg: unknown): unknown { +function declaredVitest(pkg: unknown): string | undefined { const manifest = record(pkg); for (const field of [ 'dependencies', @@ -99,7 +106,7 @@ export function lockedVitestVersion( const relative = path.relative(root, directory).replaceAll('\\', '/'); try { if (manager === PackageManager.npm) { - const lock = readLockfile( + const lock = readLockfile.manifest( path.join( root, fs.existsSync(path.join(root, 'npm-shrinkwrap.json')) @@ -132,7 +139,7 @@ export function lockedVitestVersion( } } if (manager === PackageManager.yarn) { - const lock = readLockfile(path.join(root, 'yarn.lock'), parseYarnLockfile); + const lock = readLockfile.yarn(path.join(root, 'yarn.lock'), parseYarnLockfile); if (!lock) { return undefined; } @@ -149,7 +156,7 @@ export function lockedVitestVersion( ? valid(entry.resolution.slice('vitest@npm:'.length)) : undefined; } - const matches: string[] = []; + const matches: Array = []; for (const { keys, version } of lock.entries) { if (keys.includes(`vitest@${spec}`)) { if (!version) { @@ -161,8 +168,8 @@ export function lockedVitestVersion( return matches.length === 1 ? valid(matches[0]) : undefined; } if (manager === PackageManager.bun) { - const lock = readLockfile(path.join(root, 'bun.lock'), (source) => { - const errors: ParseError[] = []; + const lock = readLockfile.manifest(path.join(root, 'bun.lock'), (source) => { + const errors: Array = []; const parsed = record(parseJsonc(source, errors, { allowTrailingComma: true })); return errors.length ? undefined : parsed; }); diff --git a/packages/cli/src/migration/vitest-v5/scopes.ts b/packages/cli/src/migration/vitest-v5/scopes.ts index 8095c2d17f..b002f2b08b 100644 --- a/packages/cli/src/migration/vitest-v5/scopes.ts +++ b/packages/cli/src/migration/vitest-v5/scopes.ts @@ -1,8 +1,9 @@ import path from 'node:path'; -import type * as t from '@oxc-project/types'; +import type { Node, ObjectExpression } from '@oxc-project/types'; import { minimatch } from 'minimatch'; +import { parseJsonValue, isObjectValue } from '../../utils/json-value.ts'; import { isString, objectProperty, @@ -11,17 +12,12 @@ import { isBoolean, memberName, } from '../ast-utils.ts'; -import { - SourceEditor, - importedName, - isModuleExports, - projectElements, - type SourceOptions, - type VitestV5Finding, -} from './ast.ts'; +import type { SourceOptions, VitestV5Finding } from './ast.ts'; +import { SourceEditor, importedName, isModuleExports, projectElements } from './ast.ts'; import { literalTestCommands, vitestCommandArgsStart } from './commands.ts'; import { resolveConfigObject } from './config-object.ts'; -import { resolveStorybookScope, type StorybookScope } from './storybook.ts'; +import type { StorybookScope } from './storybook.ts'; +import { resolveStorybookScope } from './storybook.ts'; interface ConfigEntry { implicit?: boolean; @@ -32,26 +28,26 @@ interface ConfigEntry { rootOverride?: string; dirOverride?: string; cwd?: string; - projects?: string[]; + projects?: Array; } interface TestScope { storybook?: StorybookScope; name?: string; - excludedRoots?: string[]; + excludedRoots?: Array; root: string; dir?: string; discoveryRoot?: string; - include?: string[]; + include?: Array; // An empty array disables in-source discovery; undefined requires review. - includeSource?: string[]; - exclude?: string[]; + includeSource?: Array; + exclude?: Array; benchmark?: { - include?: string[]; - exclude?: string[]; - includeSource?: string[]; + include?: Array; + exclude?: Array; + includeSource?: Array; }; - setupFiles?: string[]; + setupFiles?: Array; unresolvedSetup?: boolean; browser?: boolean; globals?: boolean; @@ -96,13 +92,15 @@ function defaultConfig(sources: ReadonlyMap, root: string): stri export function findVitestV5ConfigEntries( sources: ReadonlyMap, directories: Iterable, -): ConfigEntry[] { - const entries: ConfigEntry[] = []; +): Array { + const entries: Array = []; for (const root of directories) { - const manifest = JSON.parse( + const manifest = parseJsonValue( (sources.get(path.join(root, 'package.json')) ?? '{}').replace(/^\uFEFF/, ''), ); - const commands = Object.values(manifest.scripts ?? {}).filter( + const commands = Object.values( + isObjectValue(manifest) && isObjectValue(manifest.scripts) ? manifest.scripts : {}, + ).filter( (command): command is string => typeof command === 'string' && /\bvitest\b|\bvp\s+test\b/.test(command), ); @@ -125,7 +123,7 @@ export function findVitestV5ConfigEntries( let dirOverride: string | undefined; let uncertain = false; let browserOverride = false; - const projects: string[] = []; + const projects: Array = []; for (let index = start; index < argv.length && argv[index] !== '--'; index++) { const arg = argv[index]; const option = arg.split('=')[0]; @@ -162,7 +160,7 @@ export function findVitestV5ConfigEntries( dirOverride, projects, browserOverride, - uncertain: uncertain || (!!config && !sources.has(file!)), + uncertain: uncertain || (!!config && (file === undefined || !sources.has(file))), }); } } @@ -170,7 +168,7 @@ export function findVitestV5ConfigEntries( return entries; } -function staticPatterns(node: t.Node | undefined, editor: SourceEditor): string[] | undefined { +function staticPatterns(node: Node | undefined, editor: SourceEditor): Array | undefined { if ( node?.type === 'MemberExpression' && importedName(editor, node.object, TEST_CONFIG_SOURCES) === 'configDefaults' @@ -185,7 +183,7 @@ function staticPatterns(node: t.Node | undefined, editor: SourceEditor): string[ if (node?.type !== 'ArrayExpression') { return undefined; } - const patterns: string[] = []; + const patterns: Array = []; for (const entry of node.elements) { if (isString(entry)) { patterns.push(entry.value); @@ -202,10 +200,7 @@ function staticPatterns(node: t.Node | undefined, editor: SourceEditor): string[ return patterns.some((pattern) => pattern.startsWith('!')) ? undefined : patterns; } -function booleanOption( - node: t.Node | undefined, - fallback: boolean | undefined, -): boolean | undefined { +function booleanOption(node: Node | undefined, fallback: boolean | undefined): boolean | undefined { if (!node) { return fallback; } @@ -213,7 +208,7 @@ function booleanOption( } function benchmarkPatterns( - node: t.Node | undefined, + node: Node | undefined, inherited: TestScope['benchmark'], editor: SourceEditor, ): TestScope['benchmark'] { @@ -249,14 +244,14 @@ function matchesProject(name: string, pattern: string): boolean { // Vitest supports only '*', case-insensitively; other glob syntax is literal. const expression = pattern .split('*') - .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) + .map((part) => part.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`)) .join('.*'); return new RegExp(`^${expression}$`, 'i').test(name); } function projectSelected( - test: t.ObjectExpression | undefined, - filters: string[], + test: ObjectExpression | undefined, + filters: Array, inheritedBrowser: boolean | undefined, ): boolean | undefined { if (!filters.length) { @@ -331,17 +326,20 @@ function resolveSetupFile( .split('/') .slice(0, reference.startsWith('@') ? 2 : 1) .join('/'); - for (const parent of sources.keys()) { + for (const [parent, source] of sources) { if ( path.basename(parent) !== 'package.json' || !insideDirectory(root, path.dirname(parent)) ) { continue; } - const manifest = JSON.parse(sources.get(parent)!.replace(/^\uFEFF/, '')); + const manifest = parseJsonValue(source.replace(/^\uFEFF/, '')); if ( ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'].some( - (key) => manifest[key]?.[packageName], + (key) => { + const section = isObjectValue(manifest) ? manifest[key] : undefined; + return isObjectValue(section) && section[packageName]; + }, ) ) { return undefined; @@ -367,10 +365,10 @@ export function resolveVitestV5TestModes( sources: ReadonlyMap, configFiles: ReadonlySet, preserveV4: boolean, - entries: ConfigEntry[], -): { modes: Map; findings: VitestV5Finding[] } { - const scopes: TestScope[] = []; - const findings: VitestV5Finding[] = []; + entries: Array, +) { + const scopes: Array = []; + const findings: Array = []; const queue = [...entries]; const packageRoots = [...new Set(entries.map((entry) => entry.root))]; const visitedEntries = new Set(); @@ -385,14 +383,20 @@ export function resolveVitestV5TestModes( unknown(); continue; } - if (!entry.file) { + const configFile = entry.file; + if (!configFile) { + continue; + } + const source = sources.get(configFile); + if (source === undefined) { + unknown(); continue; } let found = false; let editor: SourceEditor; - const visited = new Set(); + const visited = new Set(); const walk = ( - object: t.Node | undefined, + object: Node | undefined, directory = entry.root, base?: TestScope, inline = false, @@ -432,7 +436,7 @@ export function resolveVitestV5TestModes( return; } const storybook = - resolveStorybookScope(editor, object, sources, entry.file!, entry.cwd ?? entry.root) ?? + resolveStorybookScope(editor, object, sources, configFile, entry.cwd ?? entry.root) ?? base?.storybook; // The addon supplies a Vite root beside its config directory. An explicit // test.root still overrides it, and test.dir controls glob exclusions. @@ -465,7 +469,7 @@ export function resolveVitestV5TestModes( const globals = test && objectProperty(test, 'globals')?.value; const benchmark = test && objectProperty(test, 'benchmark')?.value; const setup = test && objectProperty(test, 'setupFiles')?.value; - let setupFiles: string[] | undefined = []; + let setupFiles: Array | undefined = []; if (setup) { setupFiles = isString(setup) ? [setup.value] : staticPatterns(setup, editor); } @@ -480,7 +484,7 @@ export function resolveVitestV5TestModes( const projectName = test && objectProperty(test, 'name')?.value; const scope: TestScope = { storybook, - name: isString(projectName) ? projectName.value : path.basename(entry.file!), + name: isString(projectName) ? projectName.value : path.basename(configFile), // Merely discovering a workspace's tooling config does not make it a // test invocation over every child package. Explicit scripts, Vitest // configs, and ownership options still authorize cross-package scopes. @@ -489,7 +493,7 @@ export function resolveVitestV5TestModes( entry.implicit && !inline && !root && - path.basename(entry.file!).startsWith('vite.config.') && + path.basename(configFile).startsWith('vite.config.') && (!test || test.properties.every( (property) => @@ -671,7 +675,7 @@ export function resolveVitestV5TestModes( } }; try { - editor = new SourceEditor(entry.file, sources.get(entry.file)!); + editor = new SourceEditor(configFile, source); editor.visit({ ExportDefaultDeclaration(node) { walk(node.declaration); @@ -776,7 +780,7 @@ export function resolveVitestV5TestModes( { benchmark: benchmarkFile, browser: browserModes.size === 1 ? browserModes.values().next().value : undefined, - ...(ownershipReason ? { ownershipReason } : {}), + ...(ownershipReason ? { ownershipReason } : undefined), globals, reviewGlobals: !globals && matching.some(({ scope, certain }) => !certain || scope.globals !== false), diff --git a/packages/cli/src/migration/vitest-v5/source.ts b/packages/cli/src/migration/vitest-v5/source.ts index 5d3a13bdf0..086920abee 100644 --- a/packages/cli/src/migration/vitest-v5/source.ts +++ b/packages/cli/src/migration/vitest-v5/source.ts @@ -1,4 +1,9 @@ -import type * as t from '@oxc-project/types'; +import type { + BindingProperty, + CallExpression, + Node, + TSInterfaceDeclaration, +} from '@oxc-project/types'; import entryPoints from '../../vitest-v5-entry-points.json' with { type: 'json' }; import { @@ -10,6 +15,8 @@ import { isBoolean, isRegExp, } from '../ast-utils.ts'; +import { lookupSetting } from '../migrator/shared.ts'; +import type { RewriteResult, SourceOptions } from './ast.ts'; import { NODE_SOURCES, ROOT_TEST_SOURCES, @@ -17,12 +24,10 @@ import { importedName, testApiName, isImportMetaVitest, - type RewriteResult, - type SourceOptions, } from './ast.ts'; import { migrateBenchmarks } from './benchmarks.ts'; -const RUNNER_SYMBOLS: Record = { +const RUNNER_SYMBOLS = { test: 'test', it: 'it', describe: 'describe', @@ -39,7 +44,7 @@ const RUNNER_SYMBOLS: Record = { VitestRunner: 'VitestTestRunner', VitestRunnerConfig: 'TestRunnerConfig', }; -const RUNNER_METHODS: Record = { +const RUNNER_METHODS = { getCurrentSuite: 'getCurrentSuite', getCurrentTest: 'getCurrentTest', createTaskCollector: 'createTaskCollector', @@ -120,14 +125,14 @@ const ASSERTION_SOURCES = new Set(['vitest', 'vite-plus/test', ...EXPECT_SOURCES * populateGlobal. A map merely named `originals` is not a Vitest API. */ function globalRestorationOrigin( editor: SourceEditor, - node: t.Node, - seen = new Set(), + node: Node, + seen = new Set(), ): 'result' | 'originals' | 'value' | undefined { if (seen.has(node)) { return undefined; } seen.add(node); - const origin = (value: t.Node) => globalRestorationOrigin(editor, value, seen); + const origin = (value: Node) => globalRestorationOrigin(editor, value, seen); if (node.type === 'CallExpression') { if (importedName(editor, node.callee, ENVIRONMENT_SOURCES) === 'populateGlobal') { return 'result'; @@ -196,7 +201,7 @@ function globalRestorationOrigin( return undefined; } -function assertionTypeName(editor: SourceEditor, node: t.Node): string | undefined { +function assertionTypeName(editor: SourceEditor, node: Node): string | undefined { if (node.type === 'TSQualifiedName') { if ( node.left.type === 'Identifier' && @@ -226,7 +231,7 @@ function assertionTypeName(editor: SourceEditor, node: t.Node): string | undefin return node.name; } -function isJestMatchers(editor: SourceEditor, node: t.TSInterfaceDeclaration): boolean { +function isJestMatchers(editor: SourceEditor, node: TSInterfaceDeclaration): boolean { let block = editor.parent(node); if (block?.type === 'ExportNamedDeclaration') { block = editor.parent(block); @@ -242,7 +247,7 @@ function isJestMatchers(editor: SourceEditor, node: t.TSInterfaceDeclaration): b function replacementImport(source: string, name: string): string | undefined { if (RUNNER_SOURCES.has(source)) { - return RUNNER_SYMBOLS[name]; + return lookupSetting(RUNNER_SYMBOLS, name); } if (RUNNERS_SOURCES.has(source) && name === 'VitestTestRunner') { return 'TestRunner'; @@ -253,7 +258,7 @@ function replacementImport(source: string, name: string): string | undefined { return undefined; } -function processApiName(editor: SourceEditor, node: t.Node): string | undefined { +function processApiName(editor: SourceEditor, node: Node): string | undefined { const imported = importedName(editor, node, CHILD_PROCESS_SOURCES); if (imported) { return imported; @@ -305,7 +310,7 @@ export function hasVitestV5SourceUsage(file: string, source: string): boolean { source.slice(start, end), ), ); - const moduleReference = (node: t.Node | null | undefined) => { + const moduleReference = (node: Node | null | undefined) => { if ( isString(node) && /^(?:vitest(?:\/|$)|@vitest\/|vite-plus\/test(?:\/|$))/.test(node.value) @@ -355,7 +360,7 @@ export function hasVitestV5SourceUsage(file: string, source: string): boolean { return used; } -function looksLikeConstructorMock(editor: SourceEditor, node: t.CallExpression): boolean { +function looksLikeConstructorMock(editor: SourceEditor, node: CallExpression): boolean { if ( node.arguments.some( (argument) => argument.type === 'ClassExpression' || argument.type === 'FunctionExpression', @@ -382,7 +387,7 @@ function looksLikeConstructorMock(editor: SourceEditor, node: t.CallExpression): return false; } -function unwrapTypeExpression(node: t.Node): t.Node { +function unwrapTypeExpression(node: Node): Node { while ( node.type === 'TSAsExpression' || node.type === 'TSSatisfiesExpression' || @@ -396,8 +401,8 @@ function unwrapTypeExpression(node: t.Node): t.Node { /** Recognize a local promise consumed by a later statement without crossing * control flow or function boundaries. Ambiguous paths still need review. */ -function isAssertionBindingHandled(editor: SourceEditor, node: t.CallExpression): boolean { - let initializer: t.Node = node; +function isAssertionBindingHandled(editor: SourceEditor, node: CallExpression): boolean { + let initializer: Node = node; let declarator = editor.parent(initializer); while (declarator && unwrapTypeExpression(declarator) === node) { initializer = declarator; @@ -470,12 +475,9 @@ function isAssertionBindingHandled(editor: SourceEditor, node: t.CallExpression) return false; } -function chain( - node: t.Node, - isApi: (node: t.Node) => boolean, -): { root: t.Node; members: string[]; calls: t.CallExpression[] } { - const members: string[] = []; - const calls: t.CallExpression[] = []; +function chain(node: Node, isApi: (node: Node) => boolean) { + const members: Array = []; + const calls: Array = []; while (node.type === 'MemberExpression' || node.type === 'CallExpression') { if (node.optional) { break; @@ -539,17 +541,17 @@ function rewriteSource(file: string, source: string, options: SourceOptions): Re const editor = new SourceEditor(file, source); const reviewV4 = options.preserveV4 || options.reviewV4; const benchmarks = migrateBenchmarks(editor, options.globals); - const runnerAliases: string[] = []; - const asyncFunctions = new Set(); + const runnerAliases: Array = []; + const asyncFunctions = new Set(); // Import edits are offset-based, so bindings still refer to the old module // while this traversal visits the assertions that must migrate with them. - function apiName(node: t.Node): string | undefined { + function apiName(node: Node): string | undefined { return ( testApiName(editor, node, options.globals) ?? (importedName(editor, node, EXPECT_SOURCES) === 'expect' ? 'expect' : undefined) ); } - function canAwait(node: t.Node): boolean { + function canAwait(node: Node): boolean { const fn = editor.functionParent(node); if (!fn) { return false; @@ -579,7 +581,7 @@ function rewriteSource(file: string, source: string, options: SourceOptions): Re return true; } - function unsupported(node: t.Node, source: string, symbol: string, typeOnly: boolean) { + function unsupported(node: Node, source: string, symbol: string, typeOnly: boolean) { editor.report( node, 'removed-api', @@ -588,7 +590,7 @@ function rewriteSource(file: string, source: string, options: SourceOptions): Re ); } - function dynamicImport(node: t.Node, source: string): void { + function dynamicImport(node: Node, source: string): void { if (LEGACY_API_SOURCES.has(source)) { unsupported(node, source, 'dynamic/CommonJS import', false); } @@ -615,38 +617,43 @@ function rewriteSource(file: string, source: string, options: SourceOptions): Re } } } - if (source in entryPoints) { - editor.replace( - node.source, - JSON.stringify(entryPoints[source as keyof typeof entryPoints]), - ); + const entryPoint = lookupSetting(entryPoints, source); + if (entryPoint !== undefined) { + editor.replace(node.source, JSON.stringify(entryPoint)); return; } if (!LEGACY_API_SOURCES.has(source)) { return; } - const imports: string[] = []; - const constants: string[] = []; - const remaining: string[] = []; + const imports: Array = []; + const constants: Array = []; + const remaining: Array = []; let runnerName: string | undefined; for (const specifier of node.specifiers) { const typeOnly = node.importKind === 'type' || (specifier.type === 'ImportSpecifier' && specifier.importKind === 'type'); - const name = specifier.type === 'ImportSpecifier' ? propertyName(specifier.imported)! : '*'; + const name = + specifier.type === 'ImportSpecifier' + ? specifier.imported.type === 'Identifier' + ? specifier.imported.name + : specifier.imported.value + : '*'; const target = replacementImport(source, name); if (target) { imports.push( `${typeOnly ? 'type ' : ''}${target}${specifier.local.name === target ? '' : ` as ${specifier.local.name}`}`, ); - } else if (RUNNER_SOURCES.has(source) && RUNNER_METHODS[name] && !typeOnly) { + } else if (RUNNER_SOURCES.has(source) && lookupSetting(RUNNER_METHODS, name) && !typeOnly) { if (!runnerName) { runnerName = editor.uniqueName('VitestTestRunner'); imports.push(`TestRunner as ${runnerName}`); } // Static fields are the original functions, so aliases retain function // identity and also work as callback values (not only direct calls). - constants.push(`const ${specifier.local.name} = ${runnerName}.${RUNNER_METHODS[name]};`); + constants.push( + `const ${specifier.local.name} = ${runnerName}.${lookupSetting(RUNNER_METHODS, name)};`, + ); } else { unsupported(specifier, source, name, typeOnly); remaining.push(editor.text(specifier)); @@ -669,15 +676,13 @@ function rewriteSource(file: string, source: string, options: SourceOptions): Re } }, ExportNamedDeclaration(node) { - const source = node.source?.value; - if (!source) { + if (!node.source?.value) { return; } - if (source in entryPoints) { - editor.replace( - node.source!, - JSON.stringify(entryPoints[source as keyof typeof entryPoints]), - ); + const source = node.source.value; + const entryPoint = lookupSetting(entryPoints, source); + if (entryPoint !== undefined) { + editor.replace(node.source, JSON.stringify(entryPoint)); } else if (LEGACY_API_SOURCES.has(source)) { // Re-exports can expose a library contract. Do not silently replace it. for (const specifier of node.specifiers) { @@ -883,11 +888,15 @@ function rewriteSource(file: string, source: string, options: SourceOptions): Re ) { editor.replace(first, '/^$/'); } - if (reviewV4 && matcher === 'toHaveTextContent') { + if ( + reviewV4 && + node.callee.type === 'MemberExpression' && + matcher === 'toHaveTextContent' + ) { const browserAssertion = members.includes('element') || options.browser === true; const literal = isString(first) || isRegExp(first); if (options.preserveV4 && browserAssertion && literal) { - const callee = node.callee as t.MemberExpression; + const callee = node.callee; editor.replace( callee.property, callee.computed ? JSON.stringify('toMatchTextContent') : 'toMatchTextContent', @@ -980,19 +989,15 @@ function rewriteSource(file: string, source: string, options: SourceOptions): Re const props = declaration.id.properties; if ( props.every( - (prop) => + (prop): prop is BindingProperty => prop.type === 'Property' && !prop.computed && prop.value.type === 'Identifier' && ['viteConfig', 'vitestConfig'].includes(propertyName(prop.key) ?? ''), ) ) { - const vite = props.find( - (prop) => prop.type === 'Property' && propertyName(prop.key) === 'viteConfig', - ) as t.BindingProperty | undefined; - const vitest = props.find( - (prop) => prop.type === 'Property' && propertyName(prop.key) === 'vitestConfig', - ) as t.BindingProperty | undefined; + const vite = props.find((prop) => propertyName(prop.key) === 'viteConfig'); + const vitest = props.find((prop) => propertyName(prop.key) === 'vitestConfig'); const local = vite ? editor.text(vite.value) : editor.uniqueName('viteConfig'); editor.replace(declaration.id, local); if (vitest) { @@ -1018,8 +1023,8 @@ function rewriteSource(file: string, source: string, options: SourceOptions): Re } } - if (memberName(node.callee) === 'collect') { - const object = (node.callee as t.MemberExpression).object; + if (node.callee.type === 'MemberExpression' && memberName(node.callee) === 'collect') { + const object = node.callee.object; const binding = editor.binding(object); let initializer = binding?.declaration.type === 'VariableDeclarator' ? binding.declaration.init : undefined; diff --git a/packages/cli/src/migration/vitest-v5/storybook.ts b/packages/cli/src/migration/vitest-v5/storybook.ts index 79f3cb72b2..11dec73a4f 100644 --- a/packages/cli/src/migration/vitest-v5/storybook.ts +++ b/packages/cli/src/migration/vitest-v5/storybook.ts @@ -1,6 +1,6 @@ import path from 'node:path'; -import type * as t from '@oxc-project/types'; +import type { CallExpression, Node, ObjectExpression } from '@oxc-project/types'; import { isString, objectProperty, staticObject, memberName } from '../ast-utils.ts'; import { SourceEditor, importedName } from './ast.ts'; @@ -12,17 +12,17 @@ const NODE_URL = new Set(['node:url', 'url']); export interface StorybookScope { root?: string; - include?: string[]; + include?: Array; reason?: string; } -function importMeta(node: t.Node): boolean { +function importMeta(node: Node): boolean { return ( node.type === 'MetaProperty' && node.meta.name === 'import' && node.property.name === 'meta' ); } -function pathFunction(editor: SourceEditor, node: t.Node): string | undefined { +function pathFunction(editor: SourceEditor, node: Node): string | undefined { const name = importedName(editor, node, NODE_PATH); if (name) { return name; @@ -45,10 +45,10 @@ function pathFunction(editor: SourceEditor, node: t.Node): string | undefined { /** Recognize common configDir expressions, without evaluating config code. */ function configPath( editor: SourceEditor, - node: t.Node, + node: Node, file: string, cwd: string, - seen = new Set(), + seen = new Set(), ): string | undefined { if (seen.has(node)) { return undefined; @@ -99,14 +99,13 @@ function configPath( return undefined; } const args = node.arguments.map((arg) => configPath(editor, arg, file, cwd, new Set(seen))); - if (args.some((arg) => arg === undefined)) { + if (!args.every((arg) => arg !== undefined)) { return undefined; } - const values = args as string[]; if (method === 'dirname') { - return values.length === 1 ? path.dirname(values[0]) : undefined; + return args.length === 1 ? path.dirname(args[0]) : undefined; } - return method === 'resolve' ? path.resolve(cwd, ...values) : path.join(...values); + return method === 'resolve' ? path.resolve(cwd, ...args) : path.join(...args); } /** The addon replaces test.include with Storybook stories, not Vitest's default @@ -114,7 +113,7 @@ function configPath( * https://storybook.js.org/docs/writing-tests/integrations/vitest-addon */ export function resolveStorybookScope( editor: SourceEditor, - object: t.ObjectExpression, + object: ObjectExpression, sources: ReadonlyMap, file: string, cwd: string, @@ -123,7 +122,7 @@ export function resolveStorybookScope( if (!plugins) { return undefined; } - const calls: t.CallExpression[] = []; + const calls: Array = []; editor.visit({ CallExpression(node) { if ( @@ -145,7 +144,7 @@ export function resolveStorybookScope( return unknown('multiple storybookTest calls'); } const call = calls[0]; - let container: t.Node = call; + let container: Node = call; while (container !== plugins) { const parent = editor.parent(container); if (parent?.type !== 'ArrayExpression' && parent?.type !== 'AwaitExpression') { @@ -164,9 +163,11 @@ export function resolveStorybookScope( } const resolvedDir = path.resolve(cwd, directory); // Multiple main files can have loader-specific precedence. Do not guess. - const mains = ['js', 'jsx', 'ts', 'tsx', 'mjs', 'mts', 'cjs', 'cts'] - .map((extension) => path.join(resolvedDir, `main.${extension}`)) - .filter((candidate) => sources.has(candidate)); + const mains = ['js', 'jsx', 'ts', 'tsx', 'mjs', 'mts', 'cjs', 'cts'].flatMap((extension) => { + const file = path.join(resolvedDir, `main.${extension}`); + const source = sources.get(file); + return source === undefined ? [] : [{ file, source }]; + }); const label = path.relative(cwd, resolvedDir).replaceAll('\\', '/'); if (mains.length !== 1) { return unknown(`expected one readable main config in ${label}`); @@ -178,9 +179,9 @@ export function resolveStorybookScope( ) { return unknown(`custom presets in ${label}`); } - const mainFile = mains[0]; + const { file: mainFile, source } = mains[0]; try { - const mainEditor = new SourceEditor(mainFile, sources.get(mainFile)!); + const mainEditor = new SourceEditor(mainFile, source); const exported = mainEditor.ast.body.find((node) => node.type === 'ExportDefaultDeclaration'); const main = resolveConfigObject(mainEditor, exported?.declaration); if (!main || main.properties.some((property) => property.type === 'SpreadElement')) { @@ -195,7 +196,7 @@ export function resolveStorybookScope( if (stories?.type !== 'ArrayExpression') { return unknown(`dynamic stories in ${label}/main`); } - const include: string[] = []; + const include: Array = []; for (const story of stories.elements) { let pattern: string; if (isString(story)) { diff --git a/packages/cli/src/migration/vitest-v5/webdriverio.ts b/packages/cli/src/migration/vitest-v5/webdriverio.ts index fe1be6a186..ee2026f9c6 100644 --- a/packages/cli/src/migration/vitest-v5/webdriverio.ts +++ b/packages/cli/src/migration/vitest-v5/webdriverio.ts @@ -12,8 +12,12 @@ import { } from 'verkit'; import { parseDocument } from 'yaml'; -import { PackageManager, type WorkspacePackage } from '../../types/index.ts'; +import type { WorkspacePackage } from '../../types/index.ts'; +import { PackageManager } from '../../types/index.ts'; import { VITE_PLUS_OVERRIDE_PACKAGES } from '../../utils/constants.ts'; +import type { JsonValue } from '../../utils/json.ts'; +import type { JsonObject } from '../../utils/json.ts'; +import { isJsonObject } from '../../utils/json.ts'; import { extractOverrideTargetName } from '../../utils/package-overrides.ts'; import { detectPackageMetadata } from '../../utils/package.ts'; import { extractOverrideParentSegments, usesWebdriverioProvider } from '../migrator.ts'; @@ -52,20 +56,22 @@ export function webdriverioMigrationSpec(spec: string): string | undefined { return narrowed.length ? narrowed.join(' || ') : DEFAULT_SPEC; } -function object(value: unknown): Record { - return value !== null && typeof value === 'object' && !Array.isArray(value) - ? (value as Record) - : {}; +function object(value: unknown): JsonObject { + return isJsonObject(value) ? value : {}; } /** Compose dependency edits into the versioned preflight's in-memory sources. * No writes or network resolution: unresolved custom specs block before install. */ export function migrateWebdriverioDependencies( - workspace: { rootDir: string; packageManager?: PackageManager; packages?: WorkspacePackage[] }, + workspace: { + rootDir: string; + packageManager?: PackageManager; + packages?: Array; + }, sources: Map, inputs: Map, -): VitestV5Finding[] { - const findings: VitestV5Finding[] = []; +): Array { + const findings: Array = []; const rootManifest = path.join(workspace.rootDir, 'package.json'); const manifests = [ rootManifest, @@ -73,20 +79,23 @@ export function migrateWebdriverioDependencies( path.resolve(workspace.rootDir, pkg.path, 'package.json'), ), ]; - const read = (file: string): Record => { + const read = (file: string): JsonObject => { const source = sources.get(file); if (source === undefined) { return {}; } return object(file.endsWith('.json') ? parse(source) : parseDocument(source).toJS()); }; - const get = (file: string, keys: string[]): unknown => - keys.reduce((value, key) => object(value)[key], read(file)); - const set = (file: string, keys: string[], value: string | undefined) => { + const get = (file: string, keys: Array) => + keys.reduce((value, key) => object(value)[key], read(file)); + const set = (file: string, keys: Array, value: string | undefined) => { if (get(file, keys) === value) { return; } - const source = sources.get(file)!; + const source = sources.get(file); + if (source === undefined) { + throw new Error(`Missing source for ${file}`); + } if (file.endsWith('.json')) { sources.set( file, @@ -120,7 +129,7 @@ export function migrateWebdriverioDependencies( const catalogEntry = ( spec: string, name: string, - ): { file: string; keys: string[] } | undefined => { + ): { file: string; keys: Array } | undefined => { const catalog = spec.slice('catalog:'.length); const keys = catalog && catalog !== 'default' ? ['catalogs', catalog, name] : ['catalog', name]; if (workspace.packageManager === PackageManager.bun) { @@ -137,7 +146,12 @@ export function migrateWebdriverioDependencies( ); return typeof get(file, keys) === 'string' ? { file, keys } : undefined; }; - const update = (file: string, keys: string[], directory: string, seen = new Set()) => { + const update = ( + file: string, + keys: Array, + directory: string, + seen = new Set(), + ) => { const spec = get(file, keys); if (typeof spec !== 'string') { return; @@ -259,7 +273,7 @@ export function migrateWebdriverioDependencies( // An existing installed framework is another safe fallback, e.g. a // WebDriverIO CLI that brings its framework transitively. const metadata = peer === '*' ? detectPackageMetadata(directory, 'webdriverio') : undefined; - if (metadata && normalize(metadata.version)) { + if (metadata?.version && normalize(metadata.version)) { const metadataFile = path.join(metadata.path, 'package.json'); inputs.set(metadataFile, fs.readFileSync(metadataFile, 'utf8')); peer = `^${metadata.version}`; @@ -277,10 +291,11 @@ export function migrateWebdriverioDependencies( } } - const projectNames = selected - .map((file) => read(file).name) - .filter((name): name is string => typeof name === 'string'); - function matchesProject(parents: string[]): boolean { + const projectNames = selected.flatMap((file) => { + const { name } = read(file); + return typeof name === 'string' ? [name] : []; + }); + function matchesProject(parents: Array): boolean { const concrete = parents.filter((parent) => parent !== '**'); if (concrete.length === 0) { return true; @@ -290,12 +305,12 @@ export function migrateWebdriverioDependencies( } const pattern = concrete[0] .split('*') - .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')) + .map((part) => part.replaceAll(/[.+?^${}()|[\]\\]/g, String.raw`\$&`)) .join('.*'); const expression = new RegExp(`^${pattern}$`); return projectNames.some((name) => expression.test(name)); } - const overrideMap = (file: string, keys: string[], parents: string[] = []) => { + const overrideMap = (file: string, keys: Array, parents: Array = []) => { for (const [key, value] of Object.entries(object(get(file, keys)))) { const target = extractOverrideTargetName(key); const ancestors = [...parents, ...(extractOverrideParentSegments(key) ?? [])]; @@ -334,8 +349,9 @@ export function migrateWebdriverioDependencies( const after = get(file, versionPath); const field = INSTALL_FIELDS.find( (field) => get(rootManifest, [field, WEBDRIVERIO_PROVIDER]) !== undefined, - )!; + ); if ( + field !== undefined && typeof after === 'string' && !after.startsWith('$') && webdriverioMigrationSpec(after) === after diff --git a/packages/cli/src/oxlint-plugin.ts b/packages/cli/src/oxlint-plugin.ts index 8417e3e551..ea46f9be4e 100644 --- a/packages/cli/src/oxlint-plugin.ts +++ b/packages/cli/src/oxlint-plugin.ts @@ -9,6 +9,9 @@ import { PREFER_VITE_PLUS_IMPORTS_RULE_NAME, VITE_PLUS_OXLINT_PLUGIN_NAME, } from './oxlint-plugin-config.ts'; +import type { JsonObject } from './utils/json-value.ts'; +import { isObjectValue, parseJsonObject } from './utils/json-value.ts'; +import { hasOwnKey } from './utils/object.ts'; import viteConfigEntryBasenames from './vite-config-entry-basenames.json' with { type: 'json' }; import vitestV5EntryPoints from './vitest-v5-entry-points.json' with { type: 'json' }; @@ -111,8 +114,8 @@ function rewriteVitePlusImportSpecifier(specifier: string): string | null { return null; } - if (specifier in vitestV5EntryPoints) { - return vitestV5EntryPoints[specifier as keyof typeof vitestV5EntryPoints]; + if (hasOwnKey(vitestV5EntryPoints, specifier)) { + return vitestV5EntryPoints[specifier]; } if (specifier.startsWith('vitest/')) { @@ -127,14 +130,14 @@ function rewriteVitePlusImportSpecifier(specifier: string): string | null { // `@vitest/browser/context` keeps the nested path (vite-plus exports // `./test/browser/context`); the remaining subpaths are exposed only at the // bare `./test/` surface, so the `/browser/` segment is dropped. - const browserSubpathRewrites: Record = { + const browserSubpathRewrites = { '@vitest/browser/context': 'vite-plus/test/browser/context', '@vitest/browser/client': 'vite-plus/test/client', '@vitest/browser/locators': 'vite-plus/test/locators', '@vitest/browser/matchers': 'vite-plus/test/matchers', '@vitest/browser/utils': 'vite-plus/test/utils', }; - if (specifier in browserSubpathRewrites) { + if (hasOwnKey(browserSubpathRewrites, specifier)) { return browserSubpathRewrites[specifier]; } @@ -190,14 +193,6 @@ function quoteSpecifier(literal: ESTree.StringLiteral, replacement: string): str return `${quote}${replacement}${quote}`; } -type PackageDependencies = { - name?: string; - dependencies?: Record; - devDependencies?: Record; - optionalDependencies?: Record; - peerDependencies?: Record; -}; - type PackageMatchCache = Map; // Separate decisions share the same mtime-based invalidation in editor sessions. @@ -216,14 +211,14 @@ function isVitestFamilySpecifier(specifier: string): boolean { return ( isUpstreamVitestSpecifier(specifier) || specifier.startsWith('@vitest/') || - specifier in vitestV5EntryPoints + hasOwnKey(vitestV5EntryPoints, specifier) ); } function nearestPackageMatches( filename: string, cache: PackageMatchCache, - matchesPackage: (pkg: PackageDependencies) => boolean, + matchesPackage: (pkg: JsonObject) => boolean, ): boolean { if (!path.isAbsolute(filename)) { return false; @@ -244,7 +239,7 @@ function nearestPackageMatches( } let matches = false; try { - const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as PackageDependencies; + const pkg = parseJsonObject(fs.readFileSync(packageJsonPath, 'utf8')); matches = matchesPackage(pkg); } catch { // Invalid or unreadable package metadata cannot opt into the exception. @@ -265,7 +260,8 @@ function nearestPackageMatches( function nearestPackageUsesNuxtTestUtils(filename: string): boolean { return nearestPackageMatches(filename, nuxtTestUtilsPackageCache, (pkg) => [pkg.dependencies, pkg.devDependencies, pkg.optionalDependencies].some( - (dependencies) => dependencies?.['@nuxt/test-utils'] !== undefined, + (dependencies) => + isObjectValue(dependencies) && dependencies['@nuxt/test-utils'] !== undefined, ), ); } @@ -275,9 +271,9 @@ function nearestPackageUsesNuxtTestUtils(filename: string): boolean { // or as a peer, or a published Vite plugin, runs in projects that may not use // Vite+, so its imports of that tool are kept. A devDependency alone does not // keep them. -function dependsOnAtRuntime(pkg: PackageDependencies, name: string): boolean { +function dependsOnAtRuntime(pkg: JsonObject, name: string): boolean { return [pkg.dependencies, pkg.peerDependencies].some( - (dependencies) => dependencies?.[name] !== undefined, + (dependencies) => isObjectValue(dependencies) && dependencies[name] !== undefined, ); } @@ -295,7 +291,9 @@ function nearestPackageKeepsVite(filename: string): boolean { return nearestPackageMatches( filename, viteKeeperPackageCache, - (pkg) => dependsOnAtRuntime(pkg, 'vite') || isPublishedVitePluginName(pkg.name), + (pkg) => + dependsOnAtRuntime(pkg, 'vite') || + (typeof pkg.name === 'string' && isPublishedVitePluginName(pkg.name)), ); } @@ -312,11 +310,13 @@ function nearestPackageOwnsOxlintApi(filename: string): boolean { filename, oxlintOwnerPackageCache, (pkg) => - pkg.optionalDependencies?.[OXLINT_PLUGINS_PACKAGE] !== undefined || + (isObjectValue(pkg.optionalDependencies) && + pkg.optionalDependencies[OXLINT_PLUGINS_PACKAGE] !== undefined) || [pkg.dependencies, pkg.peerDependencies].some( (dependencies) => - dependencies?.[OXLINT_PACKAGE] !== undefined || - dependencies?.[OXLINT_PLUGINS_PACKAGE] !== undefined, + isObjectValue(dependencies) && + (dependencies[OXLINT_PACKAGE] !== undefined || + dependencies[OXLINT_PLUGINS_PACKAGE] !== undefined), ), ); } diff --git a/packages/cli/src/pack-bin.ts b/packages/cli/src/pack-bin.ts index cb454bccfb..f7ccba25ba 100644 --- a/packages/cli/src/pack-bin.ts +++ b/packages/cli/src/pack-bin.ts @@ -3,15 +3,8 @@ import module from 'node:module'; import path from 'node:path'; import { cac } from 'cac'; -import { - buildWithConfigs, - resolveUserConfig, - globalLogger, - enableDebug, - type InlineConfig, - type ResolvedConfig, - type TsdownHandle, -} from 'vite/pack'; +import type { InlineConfig, ResolvedConfig, TsdownHandle } from 'vite/pack'; +import { buildWithConfigs, resolveUserConfig, globalLogger, enableDebug } from 'vite/pack'; import { resolveViteConfig } from './resolve-vite-config.ts'; @@ -137,7 +130,7 @@ cli .option('--concurrency ', 'Maximum number of Rolldown builds to run in parallel') .option('-F, --filter ', 'Filter configs (cwd or name), e.g. /pkg-name$/ or pkg-name') .option('--exports', 'Generate export-related metadata for package.json (experimental)') - .action(async (input: string[], flags: InlineConfig) => { + .action(async (input: Array, flags: InlineConfig) => { if (input.length > 0) { flags.entry = input; } @@ -154,7 +147,7 @@ cli configDeps.add(path.normalize(viteConfig.configFile)); } - const configs: ResolvedConfig[] = []; + const configs: Array = []; const packConfigs = Array.isArray(viteConfig?.pack) ? viteConfig.pack : [viteConfig?.pack ?? {}]; @@ -181,7 +174,14 @@ cli export async function runCLI(): Promise { cli.parse(process.argv, { run: false }); - enableDebug(cli.options.debug); + const debug: unknown = cli.options.debug; + if ( + typeof debug === 'boolean' || + typeof debug === 'string' || + (Array.isArray(debug) && debug.every((feature: unknown) => typeof feature === 'string')) + ) { + enableDebug(debug); + } try { await cli.runMatchedCommand(); diff --git a/packages/cli/src/pack.ts b/packages/cli/src/pack.ts index 4b7f96e0ca..6a9c86e0a8 100644 --- a/packages/cli/src/pack.ts +++ b/packages/cli/src/pack.ts @@ -7,5 +7,5 @@ export interface PackUserConfig extends TsdownUserConfig { * When loading env variables from `envFile`, only include variables with these prefixes. * @default ['VITE_PACK_', 'TSDOWN_'] */ - envPrefix?: string | string[]; + envPrefix?: string | Array; } diff --git a/packages/cli/src/register.ts b/packages/cli/src/register.ts index 52464a75d5..d89c0bf4cd 100644 --- a/packages/cli/src/register.ts +++ b/packages/cli/src/register.ts @@ -3,7 +3,7 @@ * so Node.js caches registration together with the two flags passed by `vpx`. */ import { createRequire } from 'node:module'; -import * as workerThreads from 'node:worker_threads'; +import workerThreads from 'node:worker_threads'; // `NODE_OPTIONS` can also preload this module in Node.js' own loader worker. // Registering another loader there would recursively create loader workers. diff --git a/packages/cli/src/resolve-core.ts b/packages/cli/src/resolve-core.ts index 7d34692930..7a3a89a7fc 100644 --- a/packages/cli/src/resolve-core.ts +++ b/packages/cli/src/resolve-core.ts @@ -1,8 +1,10 @@ -import { readFileSync } from 'node:fs'; import { createRequire } from 'node:module'; import { join } from 'node:path'; import { VITE_PLUS_CORE_NAME, coreAliasVersion } from './utils/constants.ts'; +import { errorCode } from './utils/error.ts'; +import { isObjectValue } from './utils/json-value.ts'; +import { readJsonFile } from './utils/json.ts'; import { readNearestPackageJson } from './utils/package.ts'; /** @@ -13,10 +15,7 @@ function checkCoreVersion( packageJsonPath: string, expectedVersion: string | undefined, ): string | undefined { - const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf8')) as { - name?: string; - version?: string; - }; + const pkg = readJsonFile(packageJsonPath); if ( pkg.name !== VITE_PLUS_CORE_NAME || (expectedVersion !== undefined && pkg.version !== expectedVersion) @@ -26,11 +25,11 @@ function checkCoreVersion( ? VITE_PLUS_CORE_NAME : `${VITE_PLUS_CORE_NAME}@${expectedVersion}`; throw new Error( - `Expected ${expected}, but found ${pkg.name}@${pkg.version} at ${packageJsonPath}. ` + + `Expected ${expected}, but found ${typeof pkg.name === 'string' ? pkg.name : JSON.stringify(pkg.name)}@${typeof pkg.version === 'string' ? pkg.version : JSON.stringify(pkg.version)} at ${packageJsonPath}. ` + 'Run `vp migrate` to align the Vite alias, then run `vp install`.', ); } - return pkg.version; + return typeof pkg.version === 'string' ? pkg.version : undefined; } /** @@ -40,10 +39,12 @@ function checkCoreVersion( * `workspace:` spec into the exact alias. Any other spec pins no version. */ function readAliasCoreVersion(cliPackageJsonPath: string): string | undefined { - const { dependencies } = JSON.parse(readFileSync(cliPackageJsonPath, 'utf8')) as { - dependencies?: Record; - }; - return coreAliasVersion(dependencies?.vite); + const { dependencies } = readJsonFile(cliPackageJsonPath); + return coreAliasVersion( + isObjectValue(dependencies) && typeof dependencies.vite === 'string' + ? dependencies.vite + : undefined, + ); } function checkProjectCoreVersion( @@ -59,7 +60,10 @@ function checkProjectCoreVersion( 'devDependencies', 'optionalDependencies', 'peerDependencies', - ].some((field) => Object.hasOwn(projectPackage?.[field] ?? {}, 'vite')); + ].some((field) => { + const dependencies = projectPackage?.[field]; + return isObjectValue(dependencies) && Object.hasOwn(dependencies, 'vite'); + }); if (!declaresVite) { return; } @@ -68,9 +72,9 @@ function checkProjectCoreVersion( let projectPackageJsonPath: string | undefined; try { projectPackageJsonPath = projectRequire.resolve('vite/package.json'); - } catch (cause) { - if ((cause as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') { - throw cause; + } catch (error) { + if (errorCode(error) !== 'MODULE_NOT_FOUND') { + throw error; } } if (projectPackageJsonPath && projectPackageJsonPath !== corePackageJsonPath) { @@ -88,8 +92,10 @@ export function resolveCore( let corePackageJsonPath: string; try { corePackageJsonPath = cliRequire.resolve('vite/package.json'); - } catch (cause) { - throw new Error('Could not resolve the bundled Vite dependency. Run `vp install`.', { cause }); + } catch (error) { + throw new Error('Could not resolve the bundled Vite dependency. Run `vp install`.', { + cause: error, + }); } // Read the selected CLI's installed manifest. A static JSON import is inlined // during the build, before CI and preview packers can stamp a new version. diff --git a/packages/cli/src/resolve-doc.ts b/packages/cli/src/resolve-doc.ts index 01ff3cff7c..79d74cc28f 100644 --- a/packages/cli/src/resolve-doc.ts +++ b/packages/cli/src/resolve-doc.ts @@ -9,8 +9,7 @@ * Used for: `vite doc` command */ -import { dirname, join } from 'node:path'; -import { fileURLToPath } from 'node:url'; +import { join } from 'node:path'; import { DEFAULT_ENVS } from './utils/constants.ts'; @@ -28,7 +27,7 @@ export async function doc(): Promise<{ envs: Record; }> { // VitePress's CLI binary is located at bin/vitepress.js relative to the package root - const binPath = join(dirname(fileURLToPath(import.meta.url)), 'vitepress', 'node', 'cli.js'); + const binPath = join(import.meta.dirname, 'vitepress', 'node', 'cli.js'); return { binPath, diff --git a/packages/cli/src/resolve-test.ts b/packages/cli/src/resolve-test.ts index 42e4d6f850..666d00d272 100644 --- a/packages/cli/src/resolve-test.ts +++ b/packages/cli/src/resolve-test.ts @@ -9,15 +9,11 @@ * * Used for: `vite-plus test` command */ - -import { readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { DEFAULT_ENVS, resolveBundled } from './utils/constants.ts'; - -interface VitestPackageJson { - bin?: string | Record; -} +import { isObjectValue } from './utils/json-value.ts'; +import { readJsonFile } from './utils/json.ts'; /** * Resolves the Vitest binary path and environment variables. @@ -40,9 +36,9 @@ export async function test(): Promise<{ }> { const pkgJsonPath = resolveBundled('vitest/package.json'); const pkgRoot = dirname(pkgJsonPath); - const pkgJson = JSON.parse(readFileSync(pkgJsonPath, 'utf-8')) as VitestPackageJson; - const binRel = typeof pkgJson.bin === 'string' ? pkgJson.bin : pkgJson.bin?.vitest; - if (!binRel) { + const pkgJson = readJsonFile(pkgJsonPath); + const binRel = isObjectValue(pkgJson.bin) ? pkgJson.bin.vitest : pkgJson.bin; + if (typeof binRel !== 'string' || !binRel) { throw new Error(`Could not find 'vitest' bin entry in ${pkgJsonPath}`); } const binPath = join(pkgRoot, binRel); diff --git a/packages/cli/src/resolve-vite-config.ts b/packages/cli/src/resolve-vite-config.ts index 4e3b177e91..c10186907f 100644 --- a/packages/cli/src/resolve-vite-config.ts +++ b/packages/cli/src/resolve-vite-config.ts @@ -90,8 +90,8 @@ export async function resolveUniversalViteConfig(err: null | Error, viteConfigCw run: config.run, staged: config.staged, }); - } catch (resolveErr) { - console.error('[Vite+] resolve universal vite config error:', resolveErr); - throw resolveErr; + } catch (error) { + console.error('[Vite+] resolve universal vite config error:', error); + throw error; } } diff --git a/packages/cli/src/resolve-vite.ts b/packages/cli/src/resolve-vite.ts index 40d9308364..c6466fa7f0 100644 --- a/packages/cli/src/resolve-vite.ts +++ b/packages/cli/src/resolve-vite.ts @@ -45,9 +45,8 @@ export async function vite( throw new Error(`Could not find the bundled Vite CLI at ${binPath}. Run \`vp install\`.`); } - const envs: Record = { ...DEFAULT_ENVS }; - if (process.env.DEBUG_DISABLE_SOURCE_MAP) { - envs.DEBUG_DISABLE_SOURCE_MAP = process.env.DEBUG_DISABLE_SOURCE_MAP; - } + const envs = process.env.DEBUG_DISABLE_SOURCE_MAP + ? { ...DEFAULT_ENVS, DEBUG_DISABLE_SOURCE_MAP: process.env.DEBUG_DISABLE_SOURCE_MAP } + : { ...DEFAULT_ENVS }; return { binPath, envs }; } diff --git a/packages/cli/src/script-esm-hooks.ts b/packages/cli/src/script-esm-hooks.ts index 6a0166b7ed..01f97f4135 100644 --- a/packages/cli/src/script-esm-hooks.ts +++ b/packages/cli/src/script-esm-hooks.ts @@ -5,7 +5,8 @@ */ import type { InitializeHook, LoadHook, ResolveHook } from 'node:module'; -import { isMainThread, type MessagePort, MessageChannel } from 'node:worker_threads'; +import type { MessagePort } from 'node:worker_threads'; +import { isMainThread, MessageChannel } from 'node:worker_threads'; import type { FrozenTsconfig } from '../binding/index.js'; import { HELPER_MODULE_NAME, loadOxcNode, resolveWithOxcNode, withFlush } from './script-hooks.ts'; @@ -21,12 +22,7 @@ const resolveHook: ResolveHook = (specifier, context, nextResolve) => resolveWithOxcNode(oxcNode, specifier, context, nextResolve); const loadHook: LoadHook = (url, context, nextLoad) => - oxcNode.load( - url, - context as never, - nextLoad as never, - HELPER_MODULE_NAME, - ) as ReturnType; + oxcNode.load(url, context, nextLoad, HELPER_MODULE_NAME); /** Under watch mode, the hooks wrapped to report what each call read or looked for. */ let watchHooks: { resolve: ResolveHook; load: LoadHook } | undefined; diff --git a/packages/cli/src/script-hooks.ts b/packages/cli/src/script-hooks.ts index 2bac80fa80..978c7a4937 100644 --- a/packages/cli/src/script-hooks.ts +++ b/packages/cli/src/script-hooks.ts @@ -2,17 +2,29 @@ * Shared pieces of the `vpx