From fe75ca6e8585238009d3043ddc4fac426c0815c3 Mon Sep 17 00:00:00 2001 From: Shinya Fujino Date: Tue, 17 Nov 2026 15:58:33 +0900 Subject: [PATCH 1/3] feat(init): print a closing summary instead of logging each step MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Init records the files it creates or changes and prints them once, right before the success line: one line for a new starter, the changed files for an existing project, or "No files changed". Next steps such as the Git hint and the DATABASE_URL note follow as "→" lines. A run that stops early, on a cancelled prompt or a failed step, prints what it had already changed as a warning. Skills are linked once per folder, so agents that share .agents/skills are all named and a conflict warns once. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01J8F8mZkyRDommrR2VQzcuN --- packages/void/AGENTS.md | 2 +- packages/void/src/cli/init-report.ts | 146 +++++++ packages/void/src/cli/init.ts | 420 +++++++++++--------- packages/void/src/cli/output.ts | 13 + packages/void/src/cli/skills.ts | 32 +- packages/void/test/unit/init-report.test.ts | 193 +++++++++ packages/void/test/unit/init.test.ts | 322 ++++++++++++++- packages/void/test/unit/skills.test.ts | 52 +++ 8 files changed, 968 insertions(+), 212 deletions(-) create mode 100644 packages/void/src/cli/init-report.ts create mode 100644 packages/void/test/unit/init-report.test.ts create mode 100644 packages/void/test/unit/skills.test.ts diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 9ab870aec..9b8a70775 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -4,7 +4,7 @@ Core Vite plugin — routing, inference, migrations, CLI. User-facing CLI output and documentation describe Cloudflare operations through Void. Never ask users to install, authenticate, or invoke Wrangler directly. Keep `wrangler.jsonc` / `wrangler.json` and `WRANGLER_*` names only where users must recognize an actual file or environment variable; implementation details may remain in source comments, tests, and debug logs. -Completed CLI actions use `printSuccess` from `src/cli/output.ts`: a blank line, a green checkmark, and green text. Use `log.step` for intermediate work. Keep listings, no-op notices, cancellations, warnings, and checkpointed or pending operations out of the success renderer. Preserve JSON, token, and SQL stdout contracts. +Completed CLI actions use `printSuccess` from `src/cli/output.ts`: a blank line, a green checkmark, and green text. Use `log.step` for intermediate work. Keep listings, no-op notices, cancellations, warnings, and checkpointed or pending operations out of the success renderer. `void init` records its work in `InitReport` (`src/cli/init-report.ts`) instead of logging each step, and prints a summary before `printSuccess`: `printDone` (green ✓) for finished work and `printNextStep` (blue →) for what the user should do next. A run that stops early, on a failed step or a cancelled prompt, prints the same record under a warning, so record each change right where init makes it. Preserve JSON, token, and SQL stdout contracts. Human-facing URLs use `formatUrl` or `formatLink` from `src/cli/output.ts` for terminal hyperlinks with readable plain-text fallbacks. Use the shared `note` renderer for URL box titles; it pads the URL with spaces and adds the hyperlink after layout. Keep machine-readable output and copyable commands free of terminal links. diff --git a/packages/void/src/cli/init-report.ts b/packages/void/src/cli/init-report.ts new file mode 100644 index 000000000..f6b6b08f4 --- /dev/null +++ b/packages/void/src/cli/init-report.ts @@ -0,0 +1,146 @@ +import { log } from '@voidzero-dev/vite-plus-prompts'; +import { printDone, printNextStep } from './output.ts'; + +/** A file that one `void init` run created or changed. */ +export type InitFileChange = { + kind: 'created' | 'updated'; + path: string; + /** What changed in an updated file. A created file lists none. */ + details: Array; +}; + +/** + * What one `void init` run did. Init records its work here instead of logging + * each step, then prints a short summary when it finishes. + */ +export class InitReport { + readonly files: Array = []; + /** Finished work other than file changes. */ + readonly completed: Array = []; + /** What the user should do next. */ + readonly nextSteps: Array = []; + /** + * A new starter in one line, such as "Created a React Pages starter with D1 + * (SQLite)". The summary shows it alone, since listing the starter's files + * would add little. + */ + starter: string | undefined; + private printed = false; + + /** Record a new file. Later changes to it in the same run keep it a new file. */ + created(path: string): void { + const file = this.files.find((entry) => entry.path === path); + if (file) { + file.kind = 'created'; + file.details = []; + return; + } + this.files.push({ kind: 'created', path, details: [] }); + } + + /** Record a change to an existing file. A file lists each detail once. */ + updated(path: string, detail: string): void { + const file = this.files.find((entry) => entry.path === path); + if (!file) { + this.files.push({ kind: 'updated', path, details: [detail] }); + } else if (file.kind === 'updated' && !file.details.includes(detail)) { + file.details.push(detail); + } + } + + /** Record a write to `path`, which `existed` before it. */ + wrote(path: string, existed: boolean, detail: string): void { + if (existed) { + this.updated(path, detail); + } else { + this.created(path); + } + } + + done(message: string): void { + this.completed.push(message); + } + + next(message: string): void { + this.nextSteps.push(message); + } + + /** One line per file: created files first, then updated files with their details aligned. */ + fileLines(): Array { + const created = this.files.filter((file) => file.kind === 'created'); + const updated = this.files.filter((file) => file.kind === 'updated'); + const width = Math.max(0, ...updated.map((file) => file.path.length)); + return [ + ...created.map((file) => `+ ${file.path}`), + ...updated.map((file) => `~ ${file.path.padEnd(width)} ${file.details.join(', ')}`), + ]; + } + + /** + * Print the summary of a finished run: the new starter, or else the changed + * files. A `targeted` run (`--tsconfig`, `--github`) checks only part of the + * setup, so finding nothing to change there does not show that Void is set up. + */ + print(targeted = false): void { + this.printed = true; + if (this.starter) { + printDone(this.starter); + } else { + const lines = this.fileLines(); + if (lines.length > 0) { + printDone(['Configured Void', ...lines]); + } else { + printDone(targeted ? 'No files changed.' : 'Void is already set up. No files changed.'); + } + } + this.printOtherWork(); + } + + /** + * Run init's `steps`. If they stop early, print what they had recorded, so + * that the run does not leave changes it never mentioned. A failed step + * throws; a cancelled prompt exits the process, also from the modules that + * init calls, so only an exit listener sees every one. + */ + async printIfStopped(steps: () => Promise): Promise { + const onExit = (): void => this.printStopped(); + process.once('exit', onExit); + try { + await steps(); + } catch (error) { + this.printStopped(); + throw error; + } finally { + process.removeListener('exit', onExit); + } + } + + /** Print what the run did before it stopped. Prints nothing if it did nothing. */ + private printStopped(): void { + if (this.printed) { + return; + } + this.printed = true; + const lines = this.starter ? [] : this.fileLines(); + if (lines.length > 0) { + log.warn(['Setup did not finish. Files changed so far:', ...lines].join('\n')); + } else if (this.starter || this.completed.length > 0 || this.nextSteps.length > 0) { + log.warn('Setup did not finish. Done so far:'); + } else { + return; + } + if (this.starter) { + printDone(this.starter); + } + this.printOtherWork(); + } + + private printOtherWork(): void { + for (const message of this.completed) { + printDone(message); + } + for (const message of this.nextSteps) { + printNextStep(message); + } + } +} diff --git a/packages/void/src/cli/init.ts b/packages/void/src/cli/init.ts index 740dd6834..9340ad849 100644 --- a/packages/void/src/cli/init.ts +++ b/packages/void/src/cli/init.ts @@ -7,7 +7,11 @@ import type { PlatformDiscoveryDocument } from '@void/platform'; import { log, confirm, isCancel, cancel, select, text } from '@voidzero-dev/vite-plus-prompts'; import { parse, type ParseError } from 'jsonc-parser'; import { basename, dirname, isAbsolute, join, relative, resolve } from 'pathslash'; -import { materializeCloudflareConfig } from '../cloudflare-config.ts'; +import { + MATERIALIZED_CLOUDFLARE_FILE, + materializeCloudflareConfig, + VOID_LOCK_FILE, +} from '../cloudflare-config.ts'; import { createProjectTsconfig, ensureProjectTsconfig } from '../codegen/project-tsconfig.ts'; import { TYPED_CONFIG_FILE } from '../config-loader.ts'; import { canRewriteVoidProjectConfig, writeVoidProjectConfig } from '../config-write.ts'; @@ -36,6 +40,7 @@ import { maybeSetupDeployProject } from './deploy-setup.ts'; import { maybeScaffoldEnvTs } from './env-scaffold.ts'; import { migrateFrameworkAdapterPaths } from './framework-config-migrate.ts'; import { initialCommitCommand, setupGit } from './init-git.ts'; +import { InitReport } from './init-report.ts'; import { commandInProject } from './init-shell.ts'; import { configureVitePlusScaffold, resolveVitePlusBootstrapSpec } from './init-vite-plus.ts'; import { migrateLegacyVoidConfig } from './migrate.ts'; @@ -669,7 +674,6 @@ async function resolveInitRoot(root: string): Promise { const nextRoot = join(root, folder.trim()); mkdirSync(nextRoot, { recursive: true }); - log.info(`Scaffolding in ${nextRoot}`); return nextRoot; } @@ -1197,11 +1201,13 @@ function defaultPackageName(root: string): string { ); } +/** Returns whether it removed a dependency from package.json, which leaves the lockfile stale. */ function setupTsconfig( root: string, state: ProjectState, + report: InitReport, pagesFramework?: ScaffoldFramework, -): void { +): boolean { const tsconfigPath = join(root, 'tsconfig.json'); if (state.hasTsconfig) { @@ -1215,7 +1221,7 @@ function setupTsconfig( tsconfig = parsed; } catch { log.warn('Could not parse tsconfig.json, skipping'); - return; + return false; } let updated = false; @@ -1243,7 +1249,7 @@ function setupTsconfig( tsconfig.extends = target; } updated = true; - log.step('Updated tsconfig.json — added extends .void/tsconfig.json'); + report.updated('tsconfig.json', 'extends .void/tsconfig.json'); } const compilerOptions = asRecord(tsconfig.compilerOptions) ?? {}; @@ -1254,7 +1260,7 @@ function setupTsconfig( if (!types.includes('void/env')) { types.push('void/env'); updated = true; - log.step('Updated tsconfig.json — added void/env to types'); + report.updated('tsconfig.json', 'added void/env to types'); } // Remove @cloudflare/workers-types — void/env includes it @@ -1262,7 +1268,7 @@ function setupTsconfig( if (cfIdx !== -1) { types.splice(cfIdx, 1); updated = true; - log.step('Removed @cloudflare/workers-types from tsconfig types (included in void/env)'); + report.updated('tsconfig.json', 'removed @cloudflare/workers-types from types'); } compilerOptions.types = types; @@ -1273,7 +1279,7 @@ function setupTsconfig( if (JSON.stringify(tsconfig.files) !== JSON.stringify(files)) { tsconfig.files = files; updated = true; - log.step('Updated tsconfig.json — merged generated Void type files'); + report.updated('tsconfig.json', 'merged Void type files'); } } @@ -1284,7 +1290,7 @@ function setupTsconfig( if (JSON.stringify(existingPaths) !== JSON.stringify(paths)) { compilerOptions.paths = paths; updated = true; - log.step('Updated tsconfig.json — merged generated Void path aliases'); + report.updated('tsconfig.json', 'merged Void path aliases'); } } @@ -1293,11 +1299,10 @@ function setupTsconfig( const { extends: ext, ...rest } = tsconfig; const ordered = { extends: ext, ...rest }; writeFileSync(tsconfigPath, JSON.stringify(ordered, null, 2) + '\n'); - } else { - log.step('tsconfig.json looks good'); } // Remove @cloudflare/workers-types from package.json — void/env includes it + let dependencyRemoved = false; try { const pkgPath = join(root, 'package.json'); const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')); @@ -1312,12 +1317,13 @@ function setupTsconfig( } if (pkgUpdated) { writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n'); - log.step('Removed @cloudflare/workers-types from package.json (included in void/env)'); - log.info(`Re-run ${state.packageManager} install to update your lockfile`); + report.updated('package.json', 'removed @cloudflare/workers-types'); + dependencyRemoved = true; } } catch { // no package.json or parse error — skip } + return dependencyRemoved; } else { // Case B: no tsconfig — create recommended one const tsconfig = { @@ -1335,58 +1341,70 @@ function setupTsconfig( include: ['src', 'pages', 'routes', 'middleware', 'crons', 'queues', 'db'], }; writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2) + '\n'); - log.step('Created tsconfig.json'); + report.created('tsconfig.json'); if (!state.hasTypescript) { - log.info("Don't forget to install typescript"); + report.next('Install typescript as a dev dependency'); } + return false; } } -function readProjectWranglerCompatDate(root: string): string | undefined { +/** The project's Cloudflare config, or null when it is missing, unreadable or invalid. */ +function readProjectWranglerConfig(root: string): JsonObject | null { const configPath = materializeCloudflareConfig(root); if (!existsSync(configPath)) { - return undefined; + return null; } try { - const errors: Array = []; - const parsed = parse(readFileSync(configPath, 'utf-8'), errors); - if (errors.length === 0 && typeof parsed?.compatibility_date === 'string') { - return parsed.compatibility_date; - } + return parseJsoncFile(configPath); } catch { - // Ignore unreadable or invalid wrangler config and fall back to today's date. + // Unreadable. Callers fall back to their defaults. + return null; } - return undefined; +} + +function readProjectWranglerCompatDate(root: string): string | undefined { + const date = readProjectWranglerConfig(root)?.compatibility_date; + return typeof date === 'string' ? date : undefined; } /** * Ensure wrangler.jsonc exists with `compatibility_date` and `nodejs_als` flag * for class B/C meta-frameworks that need it for local dev. */ -function setupWranglerConfig(root: string, framework: DetectedFramework): void { +function setupWranglerConfig(root: string, framework: DetectedFramework, report: InitReport): void { if (framework.class === 'a') { return; } - const hadConfig = existsSync(materializeCloudflareConfig(root)); + // Without void.config.ts, this is the root Wrangler config, which may not exist yet. + const configExisted = existsSync(materializeCloudflareConfig(root)); + const lockExisted = existsSync(join(root, VOID_LOCK_FILE)); + const before = readProjectWranglerConfig(root); const result = writeProvisionedWranglerConfig(root, { compatibilityDate: LATEST_KNOWN_COMPAT_DATE, compatibilityFlags: ['nodejs_als'], }); + if (!result.modified) { + return; + } - if (result.modified) { - log.step( - hadConfig - ? 'Updated Cloudflare config with compatibility_date and nodejs_als' - : 'Created Cloudflare config with compatibility_date and nodejs_als', - ); - } else { - log.step(`${basename(result.configPath)} looks good`); + // The write adds only what the config lacked. An earlier step may have pinned the date. + const flags = before?.compatibility_flags; + const detail = [ + ...(before?.compatibility_date === undefined ? ['pinned compatibility_date'] : []), + ...(Array.isArray(flags) && flags.includes('nodejs_als') ? [] : ['added nodejs_als']), + ].join(', '); + if (basename(result.configPath) !== MATERIALIZED_CLOUDFLARE_FILE) { + report.wrote(relative(root, result.configPath), configExisted, detail); + } else if (existsSync(join(root, VOID_LOCK_FILE))) { + // The generated config is ignored; void.lock.json keeps its changes. + report.wrote(VOID_LOCK_FILE, lockExisted, detail); } } -export function ensureVoidWorkerCompatibilityDate(root: string): void { +export function ensureVoidWorkerCompatibilityDate(root: string, report: InitReport): void { const config = readConfig(root) as Record; if (typeof config.target === 'string' && config.target !== 'cloudflare') { @@ -1400,111 +1418,63 @@ export function ensureVoidWorkerCompatibilityDate(root: string): void { const compatibilityDate = readProjectWranglerCompatDate(root) ?? LATEST_KNOWN_COMPAT_DATE; if (!canRewriteVoidProjectConfig(root)) { - writeProvisionedWranglerConfig(root, { compatibilityDate }); - log.step('Pinned worker compatibility_date in void.lock.json'); + const lockExisted = existsSync(join(root, VOID_LOCK_FILE)); + if (writeProvisionedWranglerConfig(root, { compatibilityDate }).modified) { + report.wrote(VOID_LOCK_FILE, lockExisted, 'pinned compatibility_date'); + } return; } config.worker = { ...worker, compatibility_date: compatibilityDate, }; - writeVoidProjectConfig(root, config); - log.step('Pinned worker compatibility_date in void.config.ts'); + writeConfigFile(root, config, report, 'pinned compatibility_date'); } -/** Write `dialect` to the config's `database`, keeping its casing. */ -function writeDatabaseDialect(root: string, config: VoidConfig, dialect: DatabaseDialect): void { - const next: VoidConfig = { ...config }; - const database = databaseConfigValue(dialect, getDatabaseCasing(config)); - if (database === undefined) { - delete next.database; - } else { - next.database = database; - } - writeVoidProjectConfig(root, next); -} - -/** `quiet` is for a new starter, whose prompt already showed the database. */ -type DatabaseDialectOptions = { quiet?: boolean }; - -function clearConfiguredDatabase( +/** Write `void.config.ts` and record it with `detail`. */ +function writeConfigFile( root: string, - messages: { unchanged: string; updated: string }, - options: DatabaseDialectOptions, + config: VoidConfig, + report: InitReport, + detail: string, ): void { - const config = readConfig(root); - - if (getDatabaseDialect(config) === 'sqlite') { - if (!options.quiet) { - log.info(messages.unchanged); - } - return; - } - - writeDatabaseDialect(root, config, 'sqlite'); - if (!options.quiet) { - log.step(messages.updated); - } + const existed = existsSync(join(root, TYPED_CONFIG_FILE)); + writeVoidProjectConfig(root, config); + report.wrote(TYPED_CONFIG_FILE, existed, detail); } +const DATABASE_LABELS: Record = { + sqlite: 'D1 (SQLite)', + postgresql: 'PostgreSQL', + mysql: 'MySQL', +}; + /** Remove `database` entirely: its casing alone still makes Void serve `void/db`. */ -function removeDatabaseConfig(root: string): void { +function removeDatabaseConfig(root: string, report: InitReport): void { const config = readConfig(root); if (config.database === undefined) { - log.info('No database configured yet'); return; } const next: VoidConfig = { ...config }; delete next.database; - writeVoidProjectConfig(root, next); - log.step('Removed database config from void.config.ts'); + writeConfigFile(root, next, report, 'removed database'); } -function applyDatabaseDialect( - root: string, - dialect: DatabaseDialect, - options: DatabaseDialectOptions = {}, -): void { +/** Write `dialect` to the config's `database`, keeping its casing. */ +function applyDatabaseDialect(root: string, dialect: DatabaseDialect, report: InitReport): void { const config = readConfig(root); - - if (dialect === 'postgresql') { - if (getDatabaseDialect(config) === 'postgresql') { - if (!options.quiet) { - log.info('PostgreSQL already configured in void.config.ts'); - } - return; - } - - writeDatabaseDialect(root, config, 'postgresql'); - if (!options.quiet) { - log.step('Configured PostgreSQL in void.config.ts'); - } + if (getDatabaseDialect(config) === dialect) { return; } - if (dialect === 'mysql') { - if (getDatabaseDialect(config) === 'mysql') { - if (!options.quiet) { - log.info('MySQL already configured in void.config.ts'); - } - return; - } - - writeDatabaseDialect(root, config, 'mysql'); - if (!options.quiet) { - log.step('Configured MySQL in void.config.ts'); - } - return; + const next: VoidConfig = { ...config }; + const database = databaseConfigValue(dialect, getDatabaseCasing(config)); + if (database === undefined) { + delete next.database; + } else { + next.database = database; } - - clearConfiguredDatabase( - root, - { - unchanged: 'Using default D1 (SQLite) configuration', - updated: 'Updated void.config.ts to use the default D1 (SQLite) configuration', - }, - options, - ); + writeConfigFile(root, next, report, `database: ${DATABASE_LABELS[dialect]}`); } function detectDatabaseSetup(root: string): DatabaseSetupChoice { @@ -1522,13 +1492,13 @@ function detectDatabaseSetup(root: string): DatabaseSetupChoice { return 'none'; } -function applyDatabaseSetup(root: string, choice: DatabaseSetupChoice): void { +function applyDatabaseSetup(root: string, choice: DatabaseSetupChoice, report: InitReport): void { if (choice === 'none') { - removeDatabaseConfig(root); + removeDatabaseConfig(root, report); return; } - applyDatabaseDialect(root, choice); + applyDatabaseDialect(root, choice, report); } /** @@ -1924,9 +1894,12 @@ ${install} `; } +const WORKFLOW_FILE = '.github/workflows/void-deploy.yml'; + function setupGithubActions( root: string, state: ProjectState, + report: InitReport, platform: 'cloudflare' | 'void' = 'void', platformApiUrl?: string, ): void { @@ -1945,7 +1918,7 @@ function setupGithubActions( workflowPath, getWorkflowYaml(root, state.packageManager, slug, platform, platformApiUrl), ); - log.step('Created .github/workflows/void-deploy.yml'); + report.created(WORKFLOW_FILE); if (platform === 'cloudflare') { note( @@ -1974,8 +1947,8 @@ function setupGithubActions( * Replace the `vars.VOID_PROJECT` placeholder in `void-deploy.yml` with a slug * linked after the workflow was written. Returns false when there is none. */ -function patchWorkflowProjectSlug(root: string, slug: string): boolean { - const workflowPath = join(root, '.github', 'workflows', 'void-deploy.yml'); +function patchWorkflowProjectSlug(root: string, slug: string, report: InitReport): boolean { + const workflowPath = join(root, WORKFLOW_FILE); if (!existsSync(workflowPath)) { return false; } @@ -1989,24 +1962,29 @@ function patchWorkflowProjectSlug(root: string, slug: string): boolean { return false; } writeFileSync(workflowPath, yaml.replace(placeholderBlock, ` VOID_PROJECT: ${slug}`)); - log.step(`Set VOID_PROJECT: ${slug} in .github/workflows/void-deploy.yml`); + report.updated(WORKFLOW_FILE, 'set VOID_PROJECT'); return true; } -function writeFileIfMissing(root: string, filePath: string, content: string): void { +function writeFileIfMissing( + root: string, + filePath: string, + content: string, + report: InitReport, +): void { const fullPath = join(root, filePath); if (existsSync(fullPath)) { return; } mkdirSync(dirname(fullPath), { recursive: true }); writeFileSync(fullPath, content); - log.step(`Created ${filePath}`); + report.created(filePath); } -function ensureGitignore(root: string): void { +function ensureGitignore(root: string, report: InitReport): void { const existed = existsSync(join(root, '.gitignore')); if (ensureGitignoreLines(root, SCAFFOLD_GITIGNORE_LINES).length > 0) { - log.step(existed ? 'Updated .gitignore with Void defaults' : 'Created .gitignore'); + report.wrote('.gitignore', existed, 'added Void defaults'); } } @@ -2112,11 +2090,12 @@ function resolvePnpmConfigRoot(root: string, pkg: JsonObject): string { return root; } -function ensurePnpmAllowBuilds(root: string, pkg: JsonObject): void { +function ensurePnpmAllowBuilds(root: string, pkg: JsonObject, report: InitReport): void { const configRoot = resolvePnpmConfigRoot(root, pkg); const workspacePath = join(configRoot, 'pnpm-workspace.yaml'); const displayPath = configRoot === root ? 'pnpm-workspace.yaml' : relative(root, workspacePath); - const before = existsSync(workspacePath) ? readFileSync(workspacePath, 'utf-8') : ''; + const existed = existsSync(workspacePath); + const before = existed ? readFileSync(workspacePath, 'utf-8') : ''; // A same-line value such as `allowBuilds: {...}` cannot be merged line by // line, and a second `allowBuilds:` key would make the file invalid. const inline = /^allowBuilds:[ \t]*([^\s#].*)$/m.exec(before)?.[1]; @@ -2141,7 +2120,7 @@ function ensurePnpmAllowBuilds(root: string, pkg: JsonObject): void { ); if (after !== before) { writeFileSync(workspacePath, after); - log.step(`Updated ${displayPath} with approved builds`); + report.wrote(displayPath, existed, 'approved builds'); } } @@ -2253,8 +2232,10 @@ function scaffoldPagesApp( framework: ScaffoldFramework, starterMode: ScaffoldStarterMode, toolchain: ScaffoldToolchain, + report: InitReport, ): boolean { const packageJsonPath = join(root, 'package.json'); + const packageJsonExisted = existsSync(packageJsonPath); const template = createPagesStarterTemplate({ framework, starterMode, @@ -2268,7 +2249,7 @@ function scaffoldPagesApp( }); let pkg: JsonObject = {}; - if (existsSync(packageJsonPath)) { + if (packageJsonExisted) { try { pkg = asRecord(JSON.parse(readFileSync(packageJsonPath, 'utf-8'))) ?? {}; } catch { @@ -2351,7 +2332,7 @@ function scaffoldPagesApp( // `detectProjectState` reads only local markers; `isPnpmProject` also covers // pnpm workspace members, which need the root `allowBuilds`. if (packageManager === 'pnpm' || isPnpmProject(root, pkg)) { - ensurePnpmAllowBuilds(root, pkg); + ensurePnpmAllowBuilds(root, pkg, report); } if (toolchain === 'vite-plus' && !preserveVitePlus) { @@ -2363,30 +2344,21 @@ function scaffoldPagesApp( } writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\n'); - log.step('Updated package.json with starter scripts and dependencies'); + report.wrote('package.json', packageJsonExisted, 'added starter scripts and dependencies'); for (const [filePath, content] of Object.entries(template.files)) { - writeFileIfMissing(root, filePath, content); + writeFileIfMissing(root, filePath, content, report); } - ensureGitignore(root); + ensureGitignore(root, report); if (starterMode !== 'static') { - applyDatabaseDialect(root, starterMode, { quiet: true }); + applyDatabaseDialect(root, starterMode, report); } - if (starterMode === 'postgresql') { - const devCommand = getDevCommand(root); - note( - `Add DATABASE_URL to .env before running \`${devCommand}\`.\n` + - 'Void uses that direct connection for local PostgreSQL development.', - 'PostgreSQL local dev', - ); - } else if (starterMode === 'mysql') { - const devCommand = getDevCommand(root); - note( - `Add DATABASE_URL to .env before running \`${devCommand}\`.\n` + - 'Void uses that direct connection for local MySQL development.', - 'MySQL local dev', + if (starterMode === 'postgresql' || starterMode === 'mysql') { + report.next( + `Add DATABASE_URL to .env before running \`${getDevCommand(root)}\` ` + + `(Void uses it for local ${DATABASE_LABELS[starterMode]} development)`, ); } @@ -2396,6 +2368,7 @@ function scaffoldPagesApp( /** Returns whether a dependency was added. */ function ensureExistingProjectPackage( root: string, + report: InitReport, options: { plainViteSetup?: boolean } = {}, ): boolean { const packageJsonPath = join(root, 'package.json'); @@ -2416,10 +2389,15 @@ function ensureExistingProjectPackage( const fallbackName = defaultPackageName(root); let changed = !existedBefore; let dependencyAdded = false; + // What an existing package.json gained, for the summary. + const addedPackages: Array = []; + const addedScripts: Array = []; + let addedName = false; if (!pkg.name || typeof pkg.name !== 'string') { pkg.name = fallbackName; changed = true; + addedName = true; } if (!existedBefore && pkg.private === undefined) { pkg.private = true; @@ -2436,10 +2414,12 @@ function ensureExistingProjectPackage( if (typeof scripts.dev !== 'string') { scripts.dev = 'vite'; changed = true; + addedScripts.push('dev'); } if (typeof scripts.build !== 'string') { scripts.build = 'vite build'; changed = true; + addedScripts.push('build'); } } @@ -2449,28 +2429,29 @@ function ensureExistingProjectPackage( devDependencies.void = voidSpec; changed = true; dependencyAdded = true; + addedPackages.push('void'); } if (plainViteSetup && !hasPackageDependency(pkg, 'vite', DEPENDENCY_FIELDS)) { devDependencies.vite = SCAFFOLD_BASE_DEV_DEPENDENCIES.vite; changed = true; dependencyAdded = true; + addedPackages.push('vite'); } if (isPnpmProject(root, pkg)) { - ensurePnpmAllowBuilds(root, pkg); + ensurePnpmAllowBuilds(root, pkg, report); } if (changed) { writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\n'); - log.step( - existedBefore - ? plainViteSetup - ? 'Updated package.json with Void dependencies and Vite scripts' - : 'Updated package.json with Void dependency' - : plainViteSetup - ? 'Created package.json with Void dependencies and Vite scripts' - : 'Created package.json with Void dependency', - ); + const added = [ + ...addedPackages, + ...(addedScripts.length > 0 + ? [`${addedScripts.join('/')} ${addedScripts.length > 1 ? 'scripts' : 'script'}`] + : []), + ...(addedName ? ['name'] : []), + ]; + report.wrote('package.json', existedBefore, `added ${new Intl.ListFormat('en').format(added)}`); } return dependencyAdded; @@ -2567,7 +2548,11 @@ function noteManualFrameworkConfigSetup(framework: DetectedFramework): void { noteManualViteConfigSetup(); } -function ensureExistingProjectViteConfig(root: string, framework?: DetectedFramework): void { +function ensureExistingProjectViteConfig( + root: string, + report: InitReport, + framework?: DetectedFramework, +): void { if (framework?.class === 'c') { noteManualFrameworkConfigSetup(framework); return; @@ -2575,7 +2560,7 @@ function ensureExistingProjectViteConfig(root: string, framework?: DetectedFrame const configPath = findViteConfig(root); if (!configPath) { - writeFileIfMissing(root, getGeneratedViteConfigPath(root), getBasicVoidViteConfig()); + writeFileIfMissing(root, getGeneratedViteConfigPath(root), getBasicVoidViteConfig(), report); return; } @@ -2587,20 +2572,23 @@ function ensureExistingProjectViteConfig(root: string, framework?: DetectedFrame return; } if (updated === original) { - log.info(`${configPath} already includes voidPlugin()`); return; } writeFileSync(fullPath, updated); - log.step(`Added voidPlugin() to ${configPath}`); + report.updated(configPath, 'added voidPlugin()'); } /** Returns whether a dependency was added. */ -function setupExistingProject(root: string, framework?: DetectedFramework): boolean { - const dependencyAdded = ensureExistingProjectPackage(root, { +function setupExistingProject( + root: string, + report: InitReport, + framework?: DetectedFramework, +): boolean { + const dependencyAdded = ensureExistingProjectPackage(root, report, { plainViteSetup: framework?.class !== 'c', }); - ensureExistingProjectViteConfig(root, framework); + ensureExistingProjectViteConfig(root, report, framework); return dependencyAdded; } @@ -2656,14 +2644,14 @@ function demoFiles(root: string): { schema: string; route: string; client: strin * `setupExistingProject` has already declared `void` in `package.json`. * The caller skips the demo when any of its files exists, so these writes never replace user code. */ -function scaffoldDemo(root: string, dialect: DatabaseDialect): void { +function scaffoldDemo(root: string, dialect: DatabaseDialect, report: InitReport): void { const devCommand = getDevCommand(root); const paths = readProjectPaths(root); const files = demoFiles(root); mkdirSync(paths.dbDir, { recursive: true }); writeFileSync(files.schema, demoSchemaSource(dialect)); - log.step('Created db/schema.ts'); + report.created(relative(root, files.schema)); mkdirSync(join(paths.routesDir, 'api'), { recursive: true }); writeFileSync( @@ -2678,7 +2666,7 @@ export const GET = defineHandler(async () => { }); `, ); - log.step('Created routes/api/posts.ts'); + report.created(relative(root, files.route)); ensureProjectTsconfig(root, undefined, true, true, { paths }); // Frontend demo @@ -2697,7 +2685,7 @@ console.log(posts); // posts[0].nope ← TypeScript error `, ); - log.step('Created src/demo.ts'); + report.created(relative(root, files.client)); note( 'SQL migration → DB types → Route handler → Route types → Typed fetch\n\n' + @@ -2716,7 +2704,11 @@ const MARKER_BLOCK_RE = new RegExp( 'm', ); -async function injectAgentBlock(root: string, newProject: boolean): Promise { +async function injectAgentBlock( + root: string, + newProject: boolean, + report: InitReport, +): Promise { const filePath = 'AGENTS.md'; const fullPath = join(root, filePath); const version = getOwnVersion(); @@ -2726,7 +2718,6 @@ async function injectAgentBlock(root: string, newProject: boolean): Promise { console.log(); + // Steps record their work here. Init prints it as one summary at the end, or + // as a warning if it stops before that. + const report = new InitReport(); + await report.printIfStopped(() => runInitSteps(root, report, initArgs)); +} + +async function runInitSteps(root: string, report: InitReport, initArgs?: InitArgs): Promise { const targeted = Boolean(initArgs && (initArgs.tsconfig || initArgs.github)); + const requestedRoot = root; if (!targeted) { root = await resolveInitRoot(root); } const newProject = isScaffoldableEmptyProject(root) && !existsSync(join(root, 'AGENTS.md')); const hadTypedConfig = existsSync(join(root, TYPED_CONFIG_FILE)); + // The migration can create these files. Record them as new so that later + // steps do not list them as changed. + const missingBeforeMigration = [TYPED_CONFIG_FILE, VOID_LOCK_FILE, '.gitignore'].filter( + (file) => !existsSync(join(root, file)), + ); if (migrateLegacyVoidConfig(root)) { log.step( 'Migrated project configuration to void.config.ts. Commit void.config.ts and void.lock.json.', ); + for (const file of missingBeforeMigration) { + if (existsSync(join(root, file))) { + report.created(file); + } + } } const workspaceSubpackage = isInsideWorkspaceSubpackage(root); if (workspaceSubpackage && initArgs?.git !== undefined) { @@ -2844,6 +2867,12 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise scaffoldedPagesFramework, starterMode, scaffoldToolchain, + report, + ); + report.starter = describeStarter( + scaffoldedPagesFramework, + starterMode, + root === requestedRoot ? undefined : relative(requestedRoot, root), ); // A workspace member installs from the workspace root: a leaf install would @@ -2877,7 +2906,7 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise const pagesFramework = scaffoldedPagesFramework ?? detectPagesFramework(root); if (!targeted && !didScaffoldStarter) { - const dependencyAdded = setupExistingProject(root, framework); + const dependencyAdded = setupExistingProject(root, report, framework); const voidResolvable = isVoidResolvableFrom(root); if (dependencyAdded || !voidResolvable) { const deferral = resolveWorkspaceDeferral(root, readPackageJson(root)); @@ -2896,9 +2925,10 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise } } + let packageDependencyRemoved = false; if (!targeted || initArgs?.tsconfig) { state.typescriptWanted = true; - setupTsconfig(root, state, pagesFramework); + packageDependencyRemoved = setupTsconfig(root, state, report, pagesFramework); } // Generate .void/tsconfig.json so the root tsconfig can extend it @@ -2907,32 +2937,33 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise ensureProjectTsconfig(root, undefined, hasSchema, hasSchema); } - ensureGitignore(root); + ensureGitignore(root, report); if (!targeted) { - ensureVoidWorkerCompatibilityDate(root); + ensureVoidWorkerCompatibilityDate(root, report); } if (framework) { - setupWranglerConfig(root, framework); + setupWranglerConfig(root, framework, report); } if (!hadTypedConfig) { migrateFrameworkAdapterPaths(root); } if (!targeted && !didScaffoldStarter) { - applyDatabaseSetup(root, await promptDatabaseSetup(root)); + applyDatabaseSetup(root, await promptDatabaseSetup(root), report); } // Agent instructions and skills are part of every init. - await injectAgentBlock(root, newProject); + await injectAgentBlock(root, newProject, report); const agents = detectAgents(root); if (agents.length > 0) { const { linkSkillsForSpecificAgents } = await import('./skills.ts'); - linkSkillsForSpecificAgents(root, agents); - } else { - log.info('Bundled Void docs: node_modules/void/docs/'); + const linked = linkSkillsForSpecificAgents(root, agents).map((agent) => agent.displayName); + if (linked.length > 0) { + report.done(`Linked Void skills for ${new Intl.ListFormat('en').format(linked)}`); + } } // Demo code only in the full flow, and not for meta-frameworks or a new @@ -2957,7 +2988,7 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise if (scaffold) { // Read the dialect from config, as later `void db` commands do. const demoDialect = getDatabaseDialect(readConfig(root)); - scaffoldDemo(root, demoDialect); + scaffoldDemo(root, demoDialect, report); // The existing-project step already queued any install or workspace deferral the demo needs. const voidResolvable = isVoidResolvableFrom(root); const deferral = resolveWorkspaceDeferral(root, readPackageJson(root)); @@ -3021,6 +3052,7 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise setupGithubActions( root, state, + report, deploymentPlatform === 'cloudflare' ? 'cloudflare' : 'void', voidPlatformDiscovery?.apiUrl, ); @@ -3036,6 +3068,7 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise setupGithubActions( root, state, + report, deploymentPlatform === 'cloudflare' ? 'cloudflare' : 'void', voidPlatformDiscovery?.apiUrl, ); @@ -3051,16 +3084,20 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise const scaffoldResult = maybeScaffoldEnvTs(root); if (scaffoldResult.written) { const rel = relative(root, scaffoldResult.written) || 'env.ts'; - if (scaffoldResult.entries.length > 0) { - log.step(`Scaffolded ${rel} from .env — review inferred types before running dev.`); - } else { - log.step(`Created empty ${rel} — add your env keys with \`defineEnv({...})\`.`); - } + report.created(rel); + report.next( + scaffoldResult.entries.length > 0 + ? `Review the inferred types in ${rel}` + : `Add your environment variables to ${rel} with \`defineEnv({...})\``, + ); } } if (scaffoldAddedDependencies) { installProjectDependencies(root, state.packageManager); + } else if (packageDependencyRemoved && !workspaceSubpackageSkip) { + const install = commandInProject(root, `${state.packageManager} install`); + report.next(`Run \`${install}\` to update your lockfile`); } if (scaffoldedStarterMode && !workspaceSubpackageSkip) { generateStarterMigration(root, scaffoldedStarterMode); @@ -3070,14 +3107,15 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise const linked = await maybeSetupDeployProject(root); // The workflow was written before linking, with a placeholder slug. if (linked?.slug) { - patchWorkflowProjectSlug(root, linked.slug); + patchWorkflowProjectSlug(root, linked.slug, report); } } if (gitInitialized) { - log.info(`Git (optional): ${initialCommitCommand(root)}`); + report.next(`Git (optional): ${initialCommitCommand(root)}`); } + report.print(targeted); if (workspaceSubpackageSkip) { // The dev command cannot run before the workspace install. if (scaffoldedStarterMode) { diff --git a/packages/void/src/cli/output.ts b/packages/void/src/cli/output.ts index 5dc9bb7e2..7323d778c 100644 --- a/packages/void/src/cli/output.ts +++ b/packages/void/src/cli/output.ts @@ -34,6 +34,19 @@ export function printSuccess(message: string): void { outro(`\n${pc.green(`✓ ${stripVTControlCharacters(message)}`)}`, { withGuide: false }); } +/** + * Something a multi-step command finished, listed in its closing summary before + * `printSuccess`. Lines after the first are indented under it. + */ +export function printDone(message: string | Array): void { + log.message(message, { symbol: pc.green('✓') }); +} + +/** Something the user should do next, listed in a command's closing summary. */ +export function printNextStep(message: string): void { + log.message(message, { symbol: pc.blue('→') }); +} + export function formatCount(count: number, singular: string, plural = `${singular}s`): string { return `${count} ${count === 1 ? singular : plural}`; } diff --git a/packages/void/src/cli/skills.ts b/packages/void/src/cli/skills.ts index a09489cfd..cf6ea418a 100644 --- a/packages/void/src/cli/skills.ts +++ b/packages/void/src/cli/skills.ts @@ -65,39 +65,41 @@ function linkSkills( try { const existing = readlinkSync(linkPath); if (existing === relativeTarget) { - log.info(` ${skill.name} — already linked`); continue; } } catch { // not a symlink } - log.warn(` ${skill.name} — path exists but is not the expected symlink, skipping`); + log.warn( + `${relative(root, linkPath)} exists but is not a link to the ${skill.name} skill, skipping`, + ); continue; } symlinkSync(relativeTarget, linkPath, process.platform === 'win32' ? 'junction' : 'dir'); - log.step(` ${skill.name} — linked`); linked++; } return linked; } -export function linkSkillsForSpecificAgents(root: string, agents: Array): number { +/** Link the bundled skills for `agents`. Returns the agents whose skills folder gained a link. */ +export function linkSkillsForSpecificAgents( + root: string, + agents: Array, +): Array { const packageDir = getPackageDir(); const skillsDir = join(packageDir, 'skills'); const skills = parseSkills(skillsDir); if (skills.length === 0) { - return 0; - } - - if (agents.length === 0) { - return 0; + return []; } - let totalLinked = 0; - for (const agent of agents) { - log.info(`${agent.displayName} → ${agent.skillsDir}`); - totalLinked += linkSkills(root, skillsDir, skills, agent.skillsDir); - } - return totalLinked; + // Several agents read one folder, such as .agents/skills. Link each folder + // once: a conflict in it then warns once, and a new link counts for every + // agent that reads it. + const folders = [...new Set(agents.map((agent) => agent.skillsDir))]; + const linked = new Set( + folders.filter((folder) => linkSkills(root, skillsDir, skills, folder) > 0), + ); + return agents.filter((agent) => linked.has(agent.skillsDir)); } diff --git a/packages/void/test/unit/init-report.test.ts b/packages/void/test/unit/init-report.test.ts new file mode 100644 index 000000000..2d4a68e69 --- /dev/null +++ b/packages/void/test/unit/init-report.test.ts @@ -0,0 +1,193 @@ +import { log } from '@voidzero-dev/vite-plus-prompts'; +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { InitReport } from '../../src/cli/init-report.ts'; +import { printDone, printNextStep } from '../../src/cli/output.ts'; + +vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ log: { warn: vi.fn() } })); +vi.mock('../../src/cli/output.ts', () => ({ printDone: vi.fn(), printNextStep: vi.fn() })); + +afterEach(() => { + vi.mocked(log.warn).mockReset(); + vi.mocked(printDone).mockReset(); + vi.mocked(printNextStep).mockReset(); +}); + +describe('InitReport', () => { + it('keeps a file created in the same run as created when a later step changes it', () => { + const report = new InitReport(); + report.created('void.config.ts'); + report.updated('void.config.ts', 'pinned compatibility_date'); + report.wrote('void.config.ts', true, 'database: PostgreSQL'); + + expect(report.files).toEqual([{ kind: 'created', path: 'void.config.ts', details: [] }]); + }); + + it('lists each change to an existing file once, in order', () => { + const report = new InitReport(); + report.updated('tsconfig.json', 'extends .void/tsconfig.json'); + report.updated('package.json', 'added void'); + report.updated('tsconfig.json', 'added void/env to types'); + report.updated('tsconfig.json', 'extends .void/tsconfig.json'); + + expect(report.files).toEqual([ + { + kind: 'updated', + path: 'tsconfig.json', + details: ['extends .void/tsconfig.json', 'added void/env to types'], + }, + { kind: 'updated', path: 'package.json', details: ['added void'] }, + ]); + }); + + it('records a write as created or updated by whether the file existed', () => { + const report = new InitReport(); + report.wrote('.gitignore', false, 'added Void defaults'); + report.wrote('package.json', true, 'added void'); + + expect(report.files).toEqual([ + { kind: 'created', path: '.gitignore', details: [] }, + { kind: 'updated', path: 'package.json', details: ['added void'] }, + ]); + }); + + it('lists created files first and aligns the details of updated files', () => { + const report = new InitReport(); + report.updated('package.json', 'added void'); + report.created('void.config.ts'); + report.updated('vite.config.ts', 'added voidPlugin()'); + report.updated('.gitignore', 'added Void defaults'); + report.created('AGENTS.md'); + + expect(report.fileLines()).toEqual([ + '+ void.config.ts', + '+ AGENTS.md', + '~ package.json added void', + '~ vite.config.ts added voidPlugin()', + '~ .gitignore added Void defaults', + ]); + }); + + it('prints the changed files, the other finished work, then the next steps', () => { + const report = new InitReport(); + report.next('Git (optional): git add -A && git commit -m "chore: initial commit"'); + report.done('Linked Void skills for Claude Code'); + report.created('void.config.ts'); + + report.print(); + + expect(vi.mocked(printDone).mock.calls).toEqual([ + [['Configured Void', '+ void.config.ts']], + ['Linked Void skills for Claude Code'], + ]); + expect(vi.mocked(printNextStep).mock.calls).toEqual([ + ['Git (optional): git add -A && git commit -m "chore: initial commit"'], + ]); + expect(vi.mocked(printDone).mock.invocationCallOrder.at(-1)).toBeLessThan( + vi.mocked(printNextStep).mock.invocationCallOrder[0]!, + ); + }); + + it('describes a new starter in one line instead of its files', () => { + const report = new InitReport(); + report.created('pages/index.tsx'); + report.starter = 'Created a React Pages starter with D1 (SQLite)'; + + report.print(); + + expect(vi.mocked(printDone).mock.calls).toEqual([ + ['Created a React Pages starter with D1 (SQLite)'], + ]); + }); + + it('says when init changed no files', () => { + new InitReport().print(); + + expect(vi.mocked(printDone).mock.calls).toEqual([ + ['Void is already set up. No files changed.'], + ]); + expect(printNextStep).not.toHaveBeenCalled(); + }); + + it('does not call Void set up after a targeted run that changed no files', () => { + new InitReport().print(true); + + expect(vi.mocked(printDone).mock.calls).toEqual([['No files changed.']]); + }); +}); + +describe('an init run that stops early', () => { + it('warns with the files it changed when a step fails', async () => { + const report = new InitReport(); + const failure = new Error('npm install failed with exit code 1'); + + await expect( + report.printIfStopped(async () => { + report.created('void.config.ts'); + report.updated('package.json', 'added void'); + report.done('Linked Void skills for Claude Code'); + report.next('Install typescript as a dev dependency'); + throw failure; + }), + ).rejects.toBe(failure); + + expect(vi.mocked(log.warn).mock.calls).toEqual([ + ['Setup did not finish. Files changed so far:\n+ void.config.ts\n~ package.json added void'], + ]); + expect(vi.mocked(printDone).mock.calls).toEqual([['Linked Void skills for Claude Code']]); + expect(vi.mocked(printNextStep).mock.calls).toEqual([ + ['Install typescript as a dev dependency'], + ]); + }); + + it('warns when a cancelled prompt exits the process', async () => { + const report = new InitReport(); + const listeners = process.listeners('exit'); + let finish = (): void => {}; + const run = report.printIfStopped(async () => { + report.created('pages/index.tsx'); + report.starter = 'Created a React Pages starter with D1 (SQLite)'; + await new Promise((resolve) => { + finish = resolve; + }); + }); + + // process.exit() runs the exit listeners. Call the one this run added. + const added = process.listeners('exit').filter((listener) => !listeners.includes(listener)); + expect(added).toHaveLength(1); + added[0]!(0); + + expect(vi.mocked(log.warn).mock.calls).toEqual([['Setup did not finish. Done so far:']]); + expect(vi.mocked(printDone).mock.calls).toEqual([ + ['Created a React Pages starter with D1 (SQLite)'], + ]); + + finish(); + await run; + expect(process.listeners('exit')).toEqual(listeners); + }); + + it('prints nothing when it stops before it changes anything', async () => { + await expect( + new InitReport().printIfStopped(async () => { + throw new Error('Cancelled'); + }), + ).rejects.toThrow('Cancelled'); + + expect(log.warn).not.toHaveBeenCalled(); + expect(printDone).not.toHaveBeenCalled(); + }); + + it('prints only the summary when the run finishes', async () => { + const report = new InitReport(); + const listeners = process.listeners('exit'); + + await report.printIfStopped(async () => { + report.created('void.config.ts'); + report.print(); + }); + + expect(log.warn).not.toHaveBeenCalled(); + expect(vi.mocked(printDone).mock.calls).toEqual([[['Configured Void', '+ void.config.ts']]]); + expect(process.listeners('exit')).toEqual(listeners); + }); +}); diff --git a/packages/void/test/unit/init.test.ts b/packages/void/test/unit/init.test.ts index 42d0697e6..90b14f14a 100644 --- a/packages/void/test/unit/init.test.ts +++ b/packages/void/test/unit/init.test.ts @@ -10,8 +10,10 @@ import { } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { stripVTControlCharacters } from 'node:util'; import { toSlash } from 'pathslash'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; +import { InitReport } from '../../src/cli/init-report.ts'; import { detectProjectState, ensureVoidWorkerCompatibilityDate, @@ -40,6 +42,7 @@ const mockOutro = vi.fn(); const mockLogWarn = vi.fn(); const mockLogInfo = vi.fn(); const mockLogStep = vi.fn(); +const mockLogMessage = vi.fn(); const mockGetToken = vi.fn(); const mockGetApiUrl = vi.fn(); const mockRunLogin = vi.fn(); @@ -55,7 +58,7 @@ it('pins compatibility date in the lock without rewriting authored TypeScript', "import { defineConfig } from 'void/config';\nexport default defineConfig({ remote: process.env.REMOTE === '1' });\n"; try { writeFileSync(join(root, 'void.config.ts'), source); - ensureVoidWorkerCompatibilityDate(root); + ensureVoidWorkerCompatibilityDate(root, new InitReport()); expect(readFileSync(join(root, 'void.config.ts'), 'utf8')).toBe(source); const lock = JSON.parse(readFileSync(join(root, 'void.lock.json'), 'utf8')); expect(lock.resolved.compatibility_date).toBe(LATEST_KNOWN_COMPAT_DATE); @@ -303,6 +306,301 @@ describe('init question order', () => { }); }); +describe('init summary', () => { + const STARTER_FLAGS = [ + '--toolchain', + 'vite', + '--framework', + 'react', + '--starter', + 'sqlite', + '--deploy', + 'none', + ]; + + it('describes a new starter in one line instead of listing its files', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-starter-')); + // The user's shell is in the project, so the Git command needs no -C. + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); + try { + mkdirSync(join(root, '.claude')); + + await runInitCommand(root, parseInitArgs(['--git', ...STARTER_FLAGS])); + + expect(existsSync(join(root, 'pages', 'index.tsx'))).toBe(true); + const fileSteps = mockLogStep.mock.calls.filter(([text]) => + /^(Created|Updated|Pinned) /.test(String(text)), + ); + expect(fileSteps).toEqual([]); + expect(summaryMessages('✓')).toEqual([ + 'Created a React Pages starter with D1 (SQLite)', + 'Linked Void skills for Claude Code', + ]); + expect(summaryMessages('→')).toEqual([ + 'Git (optional): git add -A && git commit -m "chore: initial commit"', + ]); + // The summary comes last, right before the success line. + const [lastSummary] = mockLogMessage.mock.invocationCallOrder.slice(-1); + expect(lastSummary).toBeLessThan(mockOutro.mock.invocationCallOrder[0]!); + expect(mockLogStep.mock.invocationCallOrder.every((order) => order < lastSummary!)).toBe( + true, + ); + } finally { + cwd.mockRestore(); + rmSync(root, { recursive: true, force: true }); + } + }); + + it('lists the files it created and changed in an existing project', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-existing-')); + try { + writeExistingViteApp(root); + writeFileSync( + join(root, 'vite.config.ts'), + 'import { defineConfig } from "vite";\n\nexport default defineConfig({\n plugins: [],\n});\n', + ); + writeFileSync(join(root, 'tsconfig.json'), '{ "compilerOptions": { "strict": true } }\n'); + mkdirSync(join(root, '.claude')); + mockSelect.mockResolvedValue('none'); + mockConfirm.mockResolvedValue(false); + + await runInitCommand(root); + + expect(summaryMessages('✓')).toEqual([ + [ + 'Configured Void', + '+ .gitignore', + '+ void.config.ts', + '~ package.json added void and dev/build scripts', + '~ vite.config.ts added voidPlugin()', + '~ tsconfig.json extends .void/tsconfig.json, added void/env to types', + ], + 'Linked Void skills for Claude Code', + ]); + expect(summaryMessages('→')).toEqual([]); + + mockLogMessage.mockClear(); + await runInitCommand(root); + + // The skills are already linked, too. + expect(summaryMessages('✓')).toEqual(['Void is already set up. No files changed.']); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it.each([ + ['installed', true], + ['not installed', false], + ])( + 'asks for an install after removing a dependency when void is %s', + async (_name, voidInstalled) => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-lockfile-')); + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); + try { + writeFileSync( + join(root, 'package.json'), + JSON.stringify({ + name: 'app', + type: 'module', + scripts: { dev: 'vite', build: 'vite build' }, + devDependencies: { '@cloudflare/workers-types': '^4.0.0', vite: '^8.0.0', void: '*' }, + }) + '\n', + ); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ compilerOptions: { types: ['@cloudflare/workers-types'] } }) + '\n', + ); + if (voidInstalled) { + writeInstalledVoid(root); + } + mockSelect.mockResolvedValue('none'); + mockConfirm.mockResolvedValue(false); + + await runInitCommand(root); + + const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf-8')); + expect(pkg.devDependencies['@cloudflare/workers-types']).toBeUndefined(); + expect(summaryMessages('✓')[0]).toEqual( + expect.arrayContaining([ + expect.stringMatching(/^~ package\.json +removed @cloudflare\/workers-types$/), + ]), + ); + // Init's own install updates the lockfile when void still has to be installed. + expect(installCalls()).toHaveLength(voidInstalled ? 0 : 1); + expect(summaryMessages('→')).toEqual( + voidInstalled ? ['Run `npm install` to update your lockfile'] : [], + ); + } finally { + cwd.mockRestore(); + rmSync(root, { recursive: true, force: true }); + } + }, + ); + + it('lists a root Wrangler config that it creates as a new file', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-wrangler-')); + try { + // Targeted init writes no void.config.ts, so the Cloudflare config goes to the root. + writeFileSync(join(root, 'package.json'), JSON.stringify({ dependencies: { astro: '*' } })); + + await runInitCommand(root, { tsconfig: true, github: false }); + + expect(existsSync(join(root, 'void.config.ts'))).toBe(false); + expect(summaryMessages('✓')).toEqual([ + ['Configured Void', '+ tsconfig.json', '+ .gitignore', '+ wrangler.jsonc'], + ]); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it('lists the files that the config migration creates as new files', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-migration-')); + try { + writeExistingViteApp(root); + writeFileSync( + join(root, 'vite.config.ts'), + 'import { defineConfig } from "vite";\n\nexport default defineConfig({\n plugins: [],\n});\n', + ); + writeFileSync(join(root, 'tsconfig.json'), '{ "compilerOptions": { "strict": true } }\n'); + writeFileSync(join(root, 'wrangler.jsonc'), '{ "name": "app" }\n'); + mockSelect.mockResolvedValue('none'); + mockConfirm.mockResolvedValue(false); + + await runInitCommand(root); + + expect(existsSync(join(root, 'wrangler.jsonc'))).toBe(false); + // Later steps change void.config.ts and .gitignore again, and no other + // step records void.lock.json. + expect(summaryMessages('✓')).toEqual([ + [ + 'Configured Void', + '+ void.config.ts', + '+ void.lock.json', + '+ .gitignore', + '~ package.json added void and dev/build scripts', + '~ vite.config.ts added voidPlugin()', + '~ tsconfig.json extends .void/tsconfig.json, added void/env to types', + ], + ]); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it('lists what two steps added to void.lock.json without repeating it', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-lock-')); + try { + writeFileSync( + join(root, 'package.json'), + JSON.stringify({ + name: 'app', + dependencies: { astro: '*' }, + devDependencies: { void: '*' }, + }), + ); + writeInstalledVoid(root); + // Init does not rewrite authored TypeScript, so it pins the date in the + // lock. The Astro step then finds the date there and adds only its flag. + writeFileSync( + join(root, 'void.config.ts'), + "import { defineConfig } from 'void/config';\nexport default defineConfig({ remote: process.env.REMOTE === '1' });\n", + ); + writeFileSync( + join(root, 'void.lock.json'), + JSON.stringify({ version: 1, source: {}, resolved: {}, text: '{}\n' }) + '\n', + ); + mockSelect.mockResolvedValue('none'); + mockConfirm.mockResolvedValue(false); + + await runInitCommand(root); + + expect(summaryMessages('✓')[0]).toEqual( + expect.arrayContaining([ + expect.stringMatching( + /^~ void\.lock\.json +pinned compatibility_date, added nodejs_als$/, + ), + ]), + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it('names every agent whose skills it linked', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-agents-')); + try { + writeExistingViteApp(root); + // Codex and Cursor read the same skills folder. + mkdirSync(join(root, '.codex')); + mkdirSync(join(root, '.cursor')); + + await runInitCommand(root, { tsconfig: true, github: false }); + + expect(summaryMessages('✓')).toContain('Linked Void skills for Codex and Cursor'); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it('does not call Void set up after a targeted run that changed no files', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-targeted-')); + try { + // --tsconfig adds neither the void dependency nor its Vite plugin. + writeExistingViteApp(root); + + await runInitCommand(root, { tsconfig: true, github: false }); + mockLogMessage.mockClear(); + await runInitCommand(root, { tsconfig: true, github: false }); + + expect(summaryMessages('✓')).toEqual(['No files changed.']); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it('lists the files it already changed when a later question is cancelled', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-cancel-')); + // The real process.exit() runs the exit listener that init-report.test.ts covers. + // This one throws, so init reports the same way as for a failed step. + const exit = vi.spyOn(process, 'exit').mockImplementation(() => { + throw new Error('Cancelled'); + }); + try { + writeExistingViteApp(root); + writeFileSync( + join(root, 'vite.config.ts'), + 'import { defineConfig } from "vite";\n\nexport default defineConfig({\n plugins: [],\n});\n', + ); + writeFileSync(join(root, 'tsconfig.json'), '{ "compilerOptions": { "strict": true } }\n'); + // Init configures an existing project before its first question, about the database. + mockSelect.mockResolvedValue(Symbol.for('cancel')); + + await expect(runInitCommand(root)).rejects.toThrow('Cancelled'); + + expect(exit).toHaveBeenCalledWith(0); + expect(mockLogWarn.mock.calls).toEqual([ + [ + [ + 'Setup did not finish. Files changed so far:', + '+ .gitignore', + '+ void.config.ts', + '~ package.json added void and dev/build scripts', + '~ vite.config.ts added voidPlugin()', + '~ tsconfig.json extends .void/tsconfig.json, added void/env to types', + ].join('\n'), + ], + ]); + expect(mockLogMessage).not.toHaveBeenCalled(); + expect(mockOutro).not.toHaveBeenCalled(); + } finally { + exit.mockRestore(); + rmSync(root, { recursive: true, force: true }); + } + }); +}); + describe('GitHub Actions deployment workflows', () => { it('requires a selected URL for a Void deployment workflow', () => { expect(() => getWorkflowYaml('/project', 'npm', 'my-app', 'void')).toThrow('void connect'); @@ -419,6 +717,7 @@ vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ error: vi.fn(), info: (...args: Array) => mockLogInfo(...args), step: (...args: Array) => mockLogStep(...args), + message: (...args: Array) => mockLogMessage(...args), }, confirm: (...args: Array) => mockConfirm(...args), select: (...args: Array) => mockSelect(...args), @@ -578,6 +877,13 @@ function workspaceNotes() { return mockNote.mock.calls.filter((call) => call[1] === 'Workspace subpackage'); } +/** The closing summary lines init printed with `symbol`: ✓ for finished work, → for next steps. */ +function summaryMessages(symbol: '✓' | '→'): Array> { + return mockLogMessage.mock.calls + .filter(([, options]) => stripVTControlCharacters(String(options?.symbol)) === symbol) + .map(([message]) => message); +} + function writeInstalledVoid(dir: string): void { mkdirSync(join(dir, 'node_modules', 'void'), { recursive: true }); writeFileSync( @@ -707,6 +1013,7 @@ afterEach(() => { mockLogWarn.mockReset(); mockLogInfo.mockReset(); mockLogStep.mockReset(); + mockLogMessage.mockReset(); mockGetToken.mockReset(); mockGetApiUrl.mockReset(); mockRunLogin.mockReset(); @@ -1537,8 +1844,7 @@ describe('isScaffoldableEmptyProject', () => { expect(tsconfig.include).toContain('db'); expect(mockLogInfo).toHaveBeenCalledWith('Empty project detected. Creating a Pages starter.'); - // The starter prompt already showed the database, and the starter has its own pages. - expect(mockLogInfo).not.toHaveBeenCalledWith('Using default D1 (SQLite) configuration'); + // The starter has its own pages. expect(mockLogInfo).not.toHaveBeenCalledWith(expect.stringContaining('skipping demo')); } finally { rmSync(root, { recursive: true, force: true }); @@ -1586,7 +1892,10 @@ describe('isScaffoldableEmptyProject', () => { expect(readFileSync(join(root, 'db', 'migrations', '0000_generated.sql'), 'utf-8')).toContain( 'CREATE TABLE "messages"', ); - expect(mockLogStep).not.toHaveBeenCalledWith('Configured PostgreSQL in void.config.ts'); + expect(summaryMessages('✓')).toEqual(['Created a Vue Pages starter with PostgreSQL']); + expect(summaryMessages('→')).toEqual([ + 'Add DATABASE_URL to .env before running `vp dev` (Void uses it for local PostgreSQL development)', + ]); const toolchainPrompt = mockSelect.mock.calls[0]?.[0]; expect(toolchainPrompt.message).toBe('Choose a Pages scaffold toolchain:'); @@ -1931,6 +2240,9 @@ describe('isScaffoldableEmptyProject', () => { expect(existsSync(join(root, 'package.json'))).toBe(false); expect(existsSync(join(root, 'vite.config.ts'))).toBe(false); + expect(summaryMessages('✓')).toEqual([ + 'Created a static React Pages starter in ./my-new-app', + ]); const appRoot = join(root, 'my-new-app'); const pkg = JSON.parse(readFileSync(join(appRoot, 'package.json'), 'utf-8')); @@ -3168,7 +3480,7 @@ export default config; await runInitCommand(root); - expect(mockLogInfo).toHaveBeenCalledWith('PostgreSQL already configured in void.config.ts'); + expect(JSON.stringify(summaryMessages('✓'))).not.toContain('database:'); expect(readConfig(root).database).toEqual({ dialect: 'pg', casing: 'snake_case' }); } finally { rmSync(root, { recursive: true, force: true }); diff --git a/packages/void/test/unit/skills.test.ts b/packages/void/test/unit/skills.test.ts new file mode 100644 index 000000000..7f63f7bfb --- /dev/null +++ b/packages/void/test/unit/skills.test.ts @@ -0,0 +1,52 @@ +import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { log } from '@voidzero-dev/vite-plus-prompts'; +import { afterEach, beforeEach, expect, it, vi } from 'vite-plus/test'; +import { detectAgents } from '../../src/cli/agents.ts'; +import { linkSkillsForSpecificAgents } from '../../src/cli/skills.ts'; + +vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ log: { warn: vi.fn() } })); + +let root: string; + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'void-skills-')); +}); + +afterEach(() => { + vi.mocked(log.warn).mockReset(); + rmSync(root, { recursive: true, force: true }); +}); + +function linkedAgents(): Array { + return linkSkillsForSpecificAgents(root, detectAgents(root)).map((agent) => agent.displayName); +} + +it('returns every agent that reads a folder that gained a link', () => { + // Codex and Cursor both read .agents/skills. + for (const directory of ['.claude', '.codex', '.cursor']) { + mkdirSync(join(root, directory)); + } + + expect(linkedAgents()).toEqual(['Claude Code', 'Codex', 'Cursor']); + expect(existsSync(join(root, '.claude/skills/void/SKILL.md'))).toBe(true); + expect(existsSync(join(root, '.agents/skills/void/SKILL.md'))).toBe(true); + + // Nothing is left to link. + expect(linkedAgents()).toEqual([]); +}); + +it('warns once about a conflict in a folder that several agents read', () => { + mkdirSync(join(root, '.codex')); + mkdirSync(join(root, '.cursor')); + mkdirSync(join(root, '.agents/skills/void'), { recursive: true }); + + linkedAgents(); + + expect(vi.mocked(log.warn).mock.calls).toEqual([ + ['.agents/skills/void exists but is not a link to the void skill, skipping'], + ]); + // The user's folder stays as it was. + expect(existsSync(join(root, '.agents/skills/void/SKILL.md'))).toBe(false); +}); From 587b5bdaba25e741abd9eb7d2c2e96e2d00b8fc4 Mon Sep 17 00:00:00 2001 From: Shinya Fujino Date: Tue, 17 Nov 2026 17:38:29 +0900 Subject: [PATCH 2/3] fix(init): record tsconfig.json changes after writing the file setupTsconfig() recorded each change before it wrote the file, so a failed write still listed tsconfig.json as changed. It now records the changes once the write succeeds. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01J8F8mZkyRDommrR2VQzcuN --- packages/void/src/cli/init.ts | 23 +++++++++++------------ packages/void/test/unit/init.test.ts | 24 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/packages/void/src/cli/init.ts b/packages/void/src/cli/init.ts index 9340ad849..20f2f8423 100644 --- a/packages/void/src/cli/init.ts +++ b/packages/void/src/cli/init.ts @@ -1224,7 +1224,8 @@ function setupTsconfig( return false; } - let updated = false; + // Recorded only after the file is written, so that a failed write lists nothing. + const changes: Array = []; const rootPathBaseDir = effectiveConfigPathBaseDir(tsconfig, tsconfigPath); const existingPatch = collectTsconfigPatchFromConfig( tsconfig, @@ -1248,8 +1249,7 @@ function setupTsconfig( } else { tsconfig.extends = target; } - updated = true; - report.updated('tsconfig.json', 'extends .void/tsconfig.json'); + changes.push('extends .void/tsconfig.json'); } const compilerOptions = asRecord(tsconfig.compilerOptions) ?? {}; @@ -1259,16 +1259,14 @@ function setupTsconfig( : []; if (!types.includes('void/env')) { types.push('void/env'); - updated = true; - report.updated('tsconfig.json', 'added void/env to types'); + changes.push('added void/env to types'); } // Remove @cloudflare/workers-types — void/env includes it const cfIdx = types.indexOf('@cloudflare/workers-types'); if (cfIdx !== -1) { types.splice(cfIdx, 1); - updated = true; - report.updated('tsconfig.json', 'removed @cloudflare/workers-types from types'); + changes.push('removed @cloudflare/workers-types from types'); } compilerOptions.types = types; @@ -1278,8 +1276,7 @@ function setupTsconfig( const files = uniqueStrings([...existingFiles, ...voidPatch.files]); if (JSON.stringify(tsconfig.files) !== JSON.stringify(files)) { tsconfig.files = files; - updated = true; - report.updated('tsconfig.json', 'merged Void type files'); + changes.push('merged Void type files'); } } @@ -1289,16 +1286,18 @@ function setupTsconfig( const existingPaths = readPaths(compilerOptions.paths); if (JSON.stringify(existingPaths) !== JSON.stringify(paths)) { compilerOptions.paths = paths; - updated = true; - report.updated('tsconfig.json', 'merged Void path aliases'); + changes.push('merged Void path aliases'); } } - if (updated) { + if (changes.length > 0) { // Rebuild with extends first so it appears at the top of the file const { extends: ext, ...rest } = tsconfig; const ordered = { extends: ext, ...rest }; writeFileSync(tsconfigPath, JSON.stringify(ordered, null, 2) + '\n'); + for (const change of changes) { + report.updated('tsconfig.json', change); + } } // Remove @cloudflare/workers-types from package.json — void/env includes it diff --git a/packages/void/test/unit/init.test.ts b/packages/void/test/unit/init.test.ts index 90b14f14a..d0b0d2143 100644 --- a/packages/void/test/unit/init.test.ts +++ b/packages/void/test/unit/init.test.ts @@ -1,4 +1,5 @@ import { + chmodSync, existsSync, mkdtempSync, mkdirSync, @@ -560,6 +561,29 @@ describe('init summary', () => { } }); + // Root can write to a read-only file. + it.skipIf(process.getuid?.() === 0)('does not list a file that it failed to write', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-readonly-')); + const tsconfigPath = join(root, 'tsconfig.json'); + const original = '{ "compilerOptions": { "strict": true } }\n'; + try { + writeExistingViteApp(root); + // The run stops here, before it changes any other file. + writeFileSync(tsconfigPath, original); + chmodSync(tsconfigPath, 0o444); + + await expect(runInitCommand(root, { tsconfig: true, github: false })).rejects.toThrow( + /EACCES|EPERM/, + ); + + expect(readFileSync(tsconfigPath, 'utf-8')).toBe(original); + expect(mockLogWarn).not.toHaveBeenCalled(); + } finally { + chmodSync(tsconfigPath, 0o644); + rmSync(root, { recursive: true, force: true }); + } + }); + it('lists the files it already changed when a later question is cancelled', async () => { const root = mkdtempSync(join(tmpdir(), 'void-init-summary-cancel-')); // The real process.exit() runs the exit listener that init-report.test.ts covers. From ebe24a54db6249f41752f9726ccc5b61be0cb4d3 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 17 Nov 2026 18:36:43 +0900 Subject: [PATCH 3/3] Fix init test paths on macOS. --- packages/void/test/unit/init.test.ts | 2 +- packages/void/test/unit/skills.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/void/test/unit/init.test.ts b/packages/void/test/unit/init.test.ts index d0b0d2143..3f3a8fb54 100644 --- a/packages/void/test/unit/init.test.ts +++ b/packages/void/test/unit/init.test.ts @@ -353,7 +353,7 @@ describe('init summary', () => { }); it('lists the files it created and changed in an existing project', async () => { - const root = mkdtempSync(join(tmpdir(), 'void-init-summary-existing-')); + const root = realpathSync(mkdtempSync(join(tmpdir(), 'void-init-summary-existing-'))); try { writeExistingViteApp(root); writeFileSync( diff --git a/packages/void/test/unit/skills.test.ts b/packages/void/test/unit/skills.test.ts index 7f63f7bfb..29e11925a 100644 --- a/packages/void/test/unit/skills.test.ts +++ b/packages/void/test/unit/skills.test.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { log } from '@voidzero-dev/vite-plus-prompts'; @@ -11,7 +11,7 @@ vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ log: { warn: vi.fn() } })); let root: string; beforeEach(() => { - root = mkdtempSync(join(tmpdir(), 'void-skills-')); + root = realpathSync(mkdtempSync(join(tmpdir(), 'void-skills-'))); }); afterEach(() => {