diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 65b11b079..af742cf73 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. `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 new starter prints one line instead of its files; files outside the app and later changes to files that existed before init are listed under it. 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. +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 new starter prints one line instead of its files; files outside the app and later changes to files that existed before init are listed under it. 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. Init runs its installer and drizzle-kit behind a spinner (`runBehindSpinner` in `src/cli/init-subprocess.ts`) and prints their output only when they fail. When init exits during such a step, it stops the command with the processes it started, waits until they have ended, and then calls the step's `undo`. Before such a step, set `report.unfinished` to the commands that finish it by hand; a run that stops during the step prints them. Name the install there by `resolveProjectInstall().manualCommand`, which also works for a user without `vp` on PATH. 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-git.ts b/packages/void/src/cli/init-git.ts index afc4f2f86..277bf7bf8 100644 --- a/packages/void/src/cli/init-git.ts +++ b/packages/void/src/cli/init-git.ts @@ -2,7 +2,7 @@ import { spawnSync } from 'node:child_process'; import { existsSync } from 'node:fs'; import { cancel, confirm, isCancel, log } from '@voidzero-dev/vite-plus-prompts'; import { dirname, join, resolve } from 'pathslash'; -import { quoteShellPath, shellDirectory } from './init-shell.ts'; +import { projectPathFromShell } from './init-shell.ts'; export async function setupGit(root: string, git?: boolean): Promise { if (git === false) { @@ -59,8 +59,9 @@ export async function setupGit(root: string, git?: boolean): Promise { } export function initialCommitCommand(root: string): string { - // Use the absolute path because init can create a subfolder. - const directory = resolve(root); - const git = directory === shellDirectory() ? 'git' : `git -C ${quoteShellPath(directory)}`; + // Init can create a subfolder. Like `vp create`, name it relative to the + // user's shell: the command repeats the path, and an absolute one wraps. + const path = projectPathFromShell(root); + const git = path === undefined ? 'git' : `git -C ${path}`; return `${git} add -A && ${git} commit -m "chore: initial commit"`; } diff --git a/packages/void/src/cli/init-report.ts b/packages/void/src/cli/init-report.ts index 1b21bb688..fd83ae3f8 100644 --- a/packages/void/src/cli/init-report.ts +++ b/packages/void/src/cli/init-report.ts @@ -19,6 +19,11 @@ export class InitReport { readonly completed: Array = []; /** What the user should do next. */ readonly nextSteps: Array = []; + /** + * How to finish by hand the step that init is on, such as "Run `vp install` + * to finish setup". Only a run that stops during that step prints it. + */ + unfinished: string | undefined; /** The new starter in one line. See `setStarter`. */ private starter: string | undefined; /** Files recorded by the time the starter was created. */ @@ -140,7 +145,10 @@ export class InitReport { } } - /** Print what the run did before it stopped. Prints nothing if it did nothing. */ + /** + * Print what the run did before it stopped, and how to finish the step it + * stopped in. Prints nothing if there is neither. + */ private printStopped(): void { if (this.printed) { return; @@ -154,10 +162,13 @@ export class InitReport { log.warn(['Setup did not finish. Files changed so far:', ...lines].join('\n')); } else if (this.completed.length > 0 || this.nextSteps.length > 0) { log.warn('Setup did not finish. Done so far:'); - } else { + } else if (!this.unfinished) { return; } this.printOtherWork(); + if (this.unfinished) { + printNextStep(this.unfinished); + } } private printOtherWork(): void { diff --git a/packages/void/src/cli/init-shell.ts b/packages/void/src/cli/init-shell.ts index 0dcd6e0d9..54d0980b4 100644 --- a/packages/void/src/cli/init-shell.ts +++ b/packages/void/src/cli/init-shell.ts @@ -8,22 +8,31 @@ export function shellDirectory(): string { return resolve(process.cwd()); } -/** Quote a path for the user's shell, including names containing quotes, $ or backticks. */ -export function quoteShellPath(path: string): string { - if (/^[A-Za-z0-9_@./:-]+$/.test(path)) { - return path; +/** Quote an argument for the user's shell, such as a path with spaces, quotes, $ or backticks. */ +export function quoteShellArgument(argument: string): string { + if (/^[A-Za-z0-9_@./:-]+$/.test(argument)) { + return argument; } - return process.platform === 'win32' ? `"${path}"` : `'${path.replaceAll("'", "'\\''")}'`; + return process.platform === 'win32' ? `"${argument}"` : `'${argument.replaceAll("'", "'\\''")}'`; } -/** Prefix `command` with a `cd` from the user's shell into `root` when they differ. */ -export function commandInProject(root: string, command: string): string { +/** + * The path from the user's shell to `root`, quoted as a command argument, or + * undefined when the shell is already there. + */ +export function projectPathFromShell(root: string): string | undefined { const shell = shellDirectory(); const directory = resolve(root); if (directory === shell) { - return command; + return undefined; } const path = relative(shell, directory); - // `cd` would read a leading dash as an option, and `cd -` as the previous directory. - return `cd ${quoteShellPath(path.startsWith('-') ? `./${path}` : path)} && ${command}`; + // A command would read a leading dash as an option, and `cd -` as the previous directory. + return quoteShellArgument(path.startsWith('-') ? `./${path}` : path); +} + +/** Prefix `command` with a `cd` from the user's shell into `root` when they differ. */ +export function commandInProject(root: string, command: string): string { + const path = projectPathFromShell(root); + return path === undefined ? command : `cd ${path} && ${command}`; } diff --git a/packages/void/src/cli/init-subprocess.ts b/packages/void/src/cli/init-subprocess.ts new file mode 100644 index 000000000..9170b84a0 --- /dev/null +++ b/packages/void/src/cli/init-subprocess.ts @@ -0,0 +1,248 @@ +import { spawn, spawnSync, type ChildProcess } from 'node:child_process'; +import { readdirSync, readFileSync } from 'node:fs'; +import { constants } from 'node:os'; +import { createSpinner } from './output.ts'; + +export type SubprocessResult = { + /** The exit code, or null when a signal ended the command. */ + status: number | null; + /** What the command wrote to stdout and stderr, in the order it arrived. */ + output: string; + /** How long the command ran, in milliseconds. */ + durationMs: number; + /** Why the command did not start. */ + error?: Error; +}; + +/** + * The signals that end init: Ctrl+C where no spinner reads the keyboard, and + * `kill`. SIGHUP is left alone, since listening for it would undo `nohup`. + */ +const STOP_SIGNALS = ['SIGINT', 'SIGTERM'] as const; + +/** How long a command that init stops has to end by itself before init kills it. */ +const STOP_GRACE_MS = 5_000; +/** How long init waits for the killed processes to go. */ +const KILL_WAIT_MS = 1_000; +/** How often init checks whether a stopped command has ended. */ +const STOP_POLL_MS = 25; + +/** Wait without the event loop, which an `exit` listener cannot return to. */ +function sleepSync(ms: number): void { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); +} + +/** Read the process states from /proc, which works without `ps` (slim container images have none). */ +function isRunningInProc(pgid: number): boolean | undefined { + let entries: Array; + try { + entries = readdirSync('/proc'); + } catch { + return undefined; + } + for (const entry of entries) { + if (!/^\d+$/.test(entry)) { + continue; + } + let stat: string; + try { + stat = readFileSync(`/proc/${entry}/stat`, 'latin1'); + } catch { + // The process has ended since the listing. + continue; + } + // "pid (name) state ppid pgrp …". The name can contain spaces and parentheses. + const [state, , group] = stat.slice(stat.lastIndexOf(')') + 2).split(' ', 3); + if (Number(group) === pgid && state !== 'Z' && state !== 'X') { + return true; + } + } + return false; +} + +function isRunningInPs(pgid: number): boolean | undefined { + // By its path, so that init finds it whatever the user's PATH is. One `-o` + // for each column: POSIX reads the rest of an argument after "=" as the + // column's header, so "pgid=,state=" would print the group alone. + const listed = spawnSync('/bin/ps', ['-A', '-o', 'pgid=', '-o', 'state='], { encoding: 'utf8' }); + if (listed.status !== 0) { + return undefined; + } + return listed.stdout.split('\n').some((row) => { + const [group, state] = row.trim().split(/\s+/); + return Number(group) === pgid && state !== undefined && !state.startsWith('Z'); + }); +} + +/** + * Whether a process group still has a running member. + * + * A process that has exited stays in its group until its parent collects it, + * and Node cannot collect init's own child while an `exit` listener runs. For + * such a group `kill(-pgid, 0)` keeps succeeding, so read the process states. + */ +export function isProcessGroupRunning( + pgid: number, + platform: NodeJS.Platform = process.platform, +): boolean { + const running = platform === 'linux' ? isRunningInProc(pgid) : isRunningInPs(pgid); + if (running !== undefined) { + return running; + } + try { + process.kill(-pgid, 0); + return true; + } catch { + return false; + } +} + +function signalGroup(pgid: number, signal: NodeJS.Signals): boolean { + try { + process.kill(-pgid, signal); + return true; + } catch { + // The group has already ended. + return false; + } +} + +function waitForGroupToEnd(pgid: number, timeoutMs: number): boolean { + const deadline = performance.now() + timeoutMs; + while (isProcessGroupRunning(pgid)) { + if (performance.now() >= deadline) { + return false; + } + sleepSync(STOP_POLL_MS); + } + return true; +} + +/** + * Stop a command that init started, together with the processes it started, + * and return when they have ended. Init exits next: a process that still ran + * then would go on changing the project while the user retries. + */ +export function stopCommand( + child: ChildProcess | undefined, + graceMs: number = STOP_GRACE_MS, +): void { + const pid = child?.pid; + if (!pid) { + return; + } + if (process.platform === 'win32') { + // `child.kill()` would end only the shell that runs the command. + spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { + stdio: 'ignore', + windowsHide: true, + }); + return; + } + // The command leads its own process group. + if (!signalGroup(pid, 'SIGTERM') || waitForGroupToEnd(pid, graceMs)) { + return; + } + // A process can ignore SIGTERM, but not SIGKILL. + signalGroup(pid, 'SIGKILL'); + waitForGroupToEnd(pid, KILL_WAIT_MS); +} + +/** + * Run a command behind a spinner, with its output kept for the caller instead + * of printed. `spawnSync` would block the event loop and freeze the spinner. + * The spinner goes away when the command ends. + */ +export function runBehindSpinner( + message: string, + command: string, + args: Array, + options: { + cwd: string; + env?: NodeJS.ProcessEnv; + shell?: boolean; + /** The line to leave in place of the spinner when the command fails. */ + failed?: string; + /** + * Removes what the command wrote. Runs when the command fails, and when + * init exits before the command ends, after the command has stopped. + */ + undo?: () => void; + }, +): Promise { + const { failed, undo, ...spawnOptions } = options; + return new Promise((resolve) => { + let child: ChildProcess | undefined; + const progress = createSpinner({ indicator: 'timer', cancelMessage: message }); + // A spinner reads Ctrl+C as a key press and exits the process, so the + // terminal interrupts nothing. Go before the exit listener that reports + // init's work: mark this step as stopped, then stop the command. + const onExit = (code: number): void => { + progress.cancel(message); + stopCommand(child); + undo?.(); + // The prompt library exits with 0 there. Keep the exit code of an + // interrupt, so that a caller such as create-void does not carry on. + if (code === 0) { + process.exitCode = 130; + } + }; + // The command is not one of the terminal's foreground processes, so a + // signal that ends init would leave it running. Exit instead, which runs + // the listener above. + const onSignal = (signal: NodeJS.Signals): void => { + process.exit(128 + constants.signals[signal]); + }; + const chunks: Array = []; + const startedAt = performance.now(); + let settled = false; + const settle = (status: number | null, error?: Error): void => { + if (settled) { + return; + } + settled = true; + process.removeListener('exit', onExit); + for (const signal of STOP_SIGNALS) { + process.removeListener(signal, onSignal); + } + const succeeded = !error && status === 0; + if (!succeeded) { + undo?.(); + } + if (failed && !succeeded) { + progress.error(failed); + } else { + progress.clear(); + } + resolve({ + status, + output: Buffer.concat(chunks).toString('utf8'), + durationMs: performance.now() - startedAt, + error, + }); + }; + + progress.start(message); + process.prependListener('exit', onExit); + for (const signal of STOP_SIGNALS) { + process.on(signal, onSignal); + } + try { + const spawned = spawn(command, args, { + ...spawnOptions, + // Without stdin or a terminal, a command that asks a question fails + // instead of waiting for an answer behind the spinner. + stdio: ['ignore', 'pipe', 'pipe'], + // Its own process group, so that init can stop what the command starts. + detached: process.platform !== 'win32', + }); + child = spawned; + spawned.stdout.on('data', (chunk: Buffer) => chunks.push(chunk)); + spawned.stderr.on('data', (chunk: Buffer) => chunks.push(chunk)); + spawned.once('error', (error) => settle(null, error)); + spawned.once('close', (status) => settle(status)); + } catch (error) { + settle(null, error instanceof Error ? error : new Error(String(error))); + } + }); +} diff --git a/packages/void/src/cli/init.ts b/packages/void/src/cli/init.ts index c2e381c34..888d6c12b 100644 --- a/packages/void/src/cli/init.ts +++ b/packages/void/src/cli/init.ts @@ -41,10 +41,11 @@ 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 { commandInProject, quoteShellArgument } from './init-shell.ts'; +import { runBehindSpinner } from './init-subprocess.ts'; import { configureVitePlusScaffold, resolveVitePlusBootstrapSpec } from './init-vite-plus.ts'; import { migrateLegacyVoidConfig } from './migrate.ts'; -import { formatUrl, note, printSuccess } from './output.ts'; +import { formatDuration, formatUrl, note, printSuccess } from './output.ts'; import { discoverPlatform, saveDiscoveredPlatform } from './platform-cmd.ts'; import { formatProjectCommand } from './preset.ts'; import { @@ -2123,106 +2124,154 @@ function ensurePnpmAllowBuilds(root: string, pkg: JsonObject, report: InitReport } } -export function installProjectDependencies( +/** The tool that installs a project: `vp` when it uses Vite+, else its package manager. */ +function projectInstaller( + pkg: ReturnType, + packageManager: ProjectState['packageManager'], +): 'vp' | ProjectState['packageManager'] { + return pkg !== null && hasPackageDependency(pkg, 'vite-plus') ? 'vp' : packageManager; +} + +export type ProjectInstall = { + installer: ReturnType; + /** What init runs. */ + command: string; + args: Array; + /** The same install as a command for the user to run by hand. */ + manualCommand: string; +}; + +/** Decide how to install the project's dependencies. */ +export function resolveProjectInstall( root: string, packageManager: ProjectState['packageManager'], -): void { +): ProjectInstall { const pkg = readPackageJson(root); - const useVitePlus = pkg !== null && hasPackageDependency(pkg, 'vite-plus'); - const installer = useVitePlus ? 'vp' : packageManager; - log.step(`Installing dependencies with ${installer}`); - + const installer = projectInstaller(pkg, packageManager); // Init has just changed the manifest. Refresh the lockfile even when pnpm // detects a CI host; subsequent CI builds can use frozen installs normally. - let command: string = installer; - let args = - useVitePlus || packageManager === 'pnpm' ? ['install', '--no-frozen-lockfile'] : ['install']; - if (useVitePlus) { - let localBin: string | undefined; - try { - const require = createRequire(join(root, 'package.json')); - localBin = join(dirname(require.resolve('vite-plus/package.json')), 'bin/vp'); - } catch { - // The starter's Vite+ dependency has not been installed yet. - } - if (localBin) { - command = process.execPath; - args = [localBin, ...args]; - } else { - const probe = spawnSync('vp', ['--version'], { - cwd: root, - stdio: 'ignore', - shell: process.platform === 'win32', - timeout: 5_000, - }); - if (probe.status !== 0) { - // npx void init must also work without a globally installed vp. Avoid - // asking an older pnpm to switch itself to a pinned native pnpm 12. - command = 'npx'; - const packageArg = `--package=vite-plus@${resolveVitePlusBootstrapSpec(root, pkg!)}`; - args = [ - '--yes', - // cmd.exe treats the semver caret as an escape outside quotes. - process.platform === 'win32' ? `"${packageArg}"` : packageArg, - 'vp', - ...args, - ]; - } - } + const args = + installer === 'vp' || packageManager === 'pnpm' + ? ['install', '--no-frozen-lockfile'] + : ['install']; + // The manual command leaves out the flag, which only a CI host needs. + const install: ProjectInstall = { + installer, + command: installer, + args, + manualCommand: `${installer} install`, + }; + if (installer !== 'vp') { + return install; } - const result = spawnSync(command, args, { + + let localBin: string | undefined; + try { + const require = createRequire(join(root, 'package.json')); + localBin = join(dirname(require.resolve('vite-plus/package.json')), 'bin/vp'); + } catch { + // The starter's Vite+ dependency has not been installed yet. + } + if (localBin) { + return { ...install, command: process.execPath, args: [localBin, ...args] }; + } + const probe = spawnSync('vp', ['--version'], { cwd: root, - stdio: 'inherit', - shell: command !== process.execPath && process.platform === 'win32', + stdio: 'ignore', + shell: process.platform === 'win32', + timeout: 5_000, }); + if (probe.status === 0) { + return install; + } + // npx void init must also work without a globally installed vp. Avoid + // asking an older pnpm to switch itself to a pinned native pnpm 12. + const vitePlus = `vite-plus@${resolveVitePlusBootstrapSpec(root, pkg!)}`; + const packageArg = `--package=${vitePlus}`; + return { + installer, + command: 'npx', + args: [ + '--yes', + // cmd.exe treats the semver caret as an escape outside quotes. + process.platform === 'win32' ? `"${packageArg}"` : packageArg, + 'vp', + ...args, + ], + // This user has no `vp` to run. + manualCommand: `npx -p ${quoteShellArgument(vitePlus)} vp install`, + }; +} + +/** Install the project's dependencies. Returns how long the installer ran, in milliseconds. */ +export async function installProjectDependencies( + root: string, + install: ProjectInstall, +): Promise { + const { installer, command, args } = install; + const result = await runBehindSpinner( + `Installing dependencies with ${installer}`, + command, + args, + { + cwd: root, + shell: command !== process.execPath && process.platform === 'win32', + failed: `Failed to install dependencies with ${installer}`, + }, + ); if (result.error) { throw result.error; } if (result.status !== 0) { + // Print the output here rather than in the error. The CLI rewords + // "wrangler" in error messages, which would change package names in it. + if (result.output) { + process.stdout.write(result.output.endsWith('\n') ? result.output : `${result.output}\n`); + } throw new Error(`${installer} install failed with exit code ${result.status ?? 'unknown'}`); } - log.step(`Installed dependencies with ${installer}`); + return result.durationMs; } -export function generateStarterMigration( +/** Generate the first migration for the schema that a starter or the demo created. */ +export async function generateStarterMigration( root: string, starterMode: Exclude, -): void { +): Promise { const dialect = starterMode; const configPath = writeDrizzleConfig(root, PLACEHOLDER_DB_URL[dialect], dialect); const rollBack = snapshotDrizzleOutputs(readProjectPaths(root).migrationsDir); - log.step('Generating initial Drizzle migration'); - // Adds the Yarn PnP loaders drizzle-kit needs to resolve `void/schema-d1`. - const result = spawnSync(process.execPath, [drizzleKitBin, 'generate', '--config', configPath], { - cwd: root, - stdio: 'pipe', - encoding: 'utf-8', - env: buildDrizzleKitSpawnEnv(root), - }); - - if (result.error || result.status !== 0) { - rollBack(); - } + const result = await runBehindSpinner( + 'Generating the initial database migration', + process.execPath, + [drizzleKitBin, 'generate', '--config', configPath], + { + cwd: root, + // Adds the Yarn PnP loaders drizzle-kit needs to resolve `void/schema-d1`. + env: buildDrizzleKitSpawnEnv(root), + // A journal entry without its SQL file would make `void db generate` + // report no schema changes. + undo: rollBack, + }, + ); if (result.error) { throw result.error; } if (result.status !== 0) { - const detail = [result.stderr, result.stdout].filter(Boolean).join('\n').trim(); + const detail = result.output.trim(); throw new Error( - ['Failed to generate the starter database migration.', ...(detail ? [detail] : [])].join( + ['Failed to generate the initial database migration.', ...(detail ? [detail] : [])].join( '\n\n', ), ); } - - log.step('Generated initial Drizzle migration'); } function scaffoldPagesApp( @@ -2789,6 +2838,8 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg if (!targeted) { root = await resolveInitRoot(root); } + /** The new folder for the project, when the user asked init to create one. */ + const subfolder = root === requestedRoot ? undefined : relative(requestedRoot, 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 @@ -2797,14 +2848,17 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg (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); } } + // The migration deletes the old files, which the list of files does not show. + report.done(`Migrated project configuration to ${TYPED_CONFIG_FILE}`); + const migrated = [TYPED_CONFIG_FILE, VOID_LOCK_FILE].filter((file) => + existsSync(join(root, file)), + ); + report.next(`Commit ${new Intl.ListFormat('en').format(migrated)}`); } const workspaceSubpackage = isInsideWorkspaceSubpackage(root); if (workspaceSubpackage && initArgs?.git !== undefined) { @@ -2819,7 +2873,12 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg if (framework) { log.info(`Detected ${framework.name} framework`); } else if (scaffoldStarter) { - log.info('Empty project detected. Creating a Pages starter.'); + // Init found nothing to detect in a folder it has just created. + log.info( + subfolder + ? `Creating a Pages starter in ./${subfolder}.` + : 'Empty project detected. Creating a Pages starter.', + ); } else if (!targeted) { log.info('Existing project detected. Configuring Void.'); } @@ -2868,13 +2927,7 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg scaffoldToolchain, report, ); - report.setStarter( - describeStarter( - scaffoldedPagesFramework, - starterMode, - root === requestedRoot ? undefined : relative(requestedRoot, root), - ), - ); + report.setStarter(describeStarter(scaffoldedPagesFramework, starterMode, subfolder)); // A workspace member installs from the workspace root: a leaf install would // leave a stray lockfile or reject `workspace:` specs, and drizzle-kit needs @@ -2887,11 +2940,11 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg // The static starter has no database schema to generate from. const dbFollowUp = starterMode === 'static' - ? '' - : `\nthen run \`void db generate\` from ./${relRoot} to create the initial migration.`; + ? '.' + : `,\nthen run \`void db generate\` from ./${relRoot} to create the initial migration.`; note( `Scaffolded the Pages starter in ./${relRoot}.\n\n` + - `Run your workspace install from ${deferral.workspaceRoot} to pick up the new dependencies.${dbFollowUp}`, + `Run your workspace install from ${deferral.workspaceRoot} to pick up the new dependencies${dbFollowUp}`, 'Workspace subpackage', ); } else if (scaffoldWroteDeps || !voidResolvable) { @@ -3094,15 +3147,30 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg } } + // The steps below can fail or be cancelled. `unfinished` names the commands + // that finish them by hand. Running init again would not: it would find an + // existing project and skip the migration. + const migrationMode = workspaceSubpackageSkip ? undefined : scaffoldedStarterMode; if (scaffoldAddedDependencies) { - installProjectDependencies(root, state.packageManager); + const install = resolveProjectInstall(root, state.packageManager); + const manualInstall = commandInProject(root, install.manualCommand); + report.unfinished = migrationMode + ? `Run \`${manualInstall}\`, then \`void db generate\` to finish setup` + : `Run \`${manualInstall}\` to finish setup`; + const duration = await installProjectDependencies(root, install); + report.done(`Installed dependencies in ${formatDuration(duration)}`); } else if (packageDependencyRemoved && !workspaceSubpackageSkip) { - const install = commandInProject(root, `${state.packageManager} install`); - report.next(`Run \`${install}\` to update your lockfile`); + // The project is installed, so its user has a way to run the installer. + const installer = projectInstaller(readPackageJson(root), state.packageManager); + const manualInstall = commandInProject(root, `${installer} install`); + report.next(`Run \`${manualInstall}\` to update your lockfile`); } - if (scaffoldedStarterMode && !workspaceSubpackageSkip) { - generateStarterMigration(root, scaffoldedStarterMode); + if (migrationMode) { + report.unfinished = `Run \`${commandInProject(root, 'void db generate')}\` to finish setup`; + await generateStarterMigration(root, migrationMode); + report.done('Generated the initial database migration'); } + report.unfinished = undefined; if (!targeted && deploymentPlatform === 'void') { const linked = await maybeSetupDeployProject(root); diff --git a/packages/void/src/cli/output.ts b/packages/void/src/cli/output.ts index 7323d778c..289497f18 100644 --- a/packages/void/src/cli/output.ts +++ b/packages/void/src/cli/output.ts @@ -51,6 +51,16 @@ export function formatCount(count: number, singular: string, plural = `${singula return `${count} ${count === 1 ? singular : plural}`; } +/** How long a step took, in the form `vp create` prints: "215ms", "2.4s" or "12s". */ +export function formatDuration(durationMs: number): string { + const ms = Math.round(durationMs); + if (ms < 1000) { + return `${Math.max(1, ms)}ms`; + } + const tenths = Math.round(ms / 100); + return tenths < 100 ? `${(tenths / 10).toFixed(1)}s` : `${Math.round(ms / 1000)}s`; +} + /** Keep recovery commands on the same CLI when using the local checkout launcher. */ export function cliCommandName(): 'void' | 'void-dev' { const entryName = process.argv[1]?.split(/[\\/]/).at(-1); @@ -59,7 +69,7 @@ export function cliCommandName(): 'void' | 'void-dev' { /** Keep phase updates visible in static progress output, including redirected terminals. */ export function createSpinner( - options?: Pick, + options?: Pick, isTerminal: boolean = process.stdout.isTTY === true, ): SpinnerResult { const accessible = @@ -92,7 +102,8 @@ export function createSpinner( cancel(msg = '') { cancelled = true; if (msg) { - log.warn(msg); + // The red ■ that a cancelled spinner leaves in a terminal. + log.error(msg); } }, error(msg = '') { diff --git a/packages/void/test/integration/init-install.test.ts b/packages/void/test/integration/init-install.test.ts index 96b728765..fafac1f3f 100644 --- a/packages/void/test/integration/init-install.test.ts +++ b/packages/void/test/integration/init-install.test.ts @@ -1,8 +1,9 @@ import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { stripVTControlCharacters } from 'node:util'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; -import { installProjectDependencies } from '../../src/cli/init.ts'; +import { installProjectDependencies, resolveProjectInstall } from '../../src/cli/init.ts'; import { SCAFFOLD_VITE_PLUS_DEV_DEPENDENCIES } from '../../src/cli/template.ts'; let root: string; @@ -15,6 +16,10 @@ function executable(name: string, status = 0): void { script, `const { appendFileSync } = require('node:fs'); appendFileSync(${JSON.stringify(callsFile)}, JSON.stringify({ command: ${JSON.stringify(name)}, args: process.argv.slice(2), cwd: process.cwd() }) + '\\n'); +if (!process.argv.includes('--version')) { + process.stdout.write(${JSON.stringify(`${name}: resolving packages\n`)}); + process.stderr.write(${JSON.stringify(`${name}: registry unreachable\n`)}); +} process.exitCode = process.argv.includes('--version') ? 0 : ${status}; `, ); @@ -34,7 +39,27 @@ function calls(): Array<{ command: string; args: Array; cwd: string }> { .map((line) => JSON.parse(line)); } +/** What init has printed in this test, without colors. */ +function output(): string { + return stripVTControlCharacters( + vi + .mocked(process.stdout.write) + .mock.calls.map(([chunk]) => String(chunk)) + .join(''), + ); +} + +/** Install as init does: decide how to, then run that. */ +function install( + directory: string, + packageManager: Parameters[1] = 'pnpm', +): Promise { + return installProjectDependencies(directory, resolveProjectInstall(directory, packageManager)); +} + beforeEach(() => { + // The fake installers print, and init prints their output when they fail. + vi.spyOn(process.stdout, 'write').mockReturnValue(true); root = realpathSync(mkdtempSync(join(tmpdir(), 'void-init-install-'))); bin = join(root, 'bin'); callsFile = join(root, 'calls.jsonl'); @@ -52,16 +77,17 @@ beforeEach(() => { }); afterEach(() => { + vi.restoreAllMocks(); vi.unstubAllEnvs(); rmSync(root, { recursive: true, force: true }); }); describe('init dependency installation (real subprocesses)', () => { - it('uses Vite+ instead of delegating a pnpm 12 pin to an older global pnpm', () => { + it('uses Vite+ instead of delegating a pnpm 12 pin to an older global pnpm', async () => { executable('vp'); executable('pnpm', 1); - installProjectDependencies(root, 'pnpm'); + await install(root); expect(calls()).toEqual([ { command: 'vp', args: ['--version'], cwd: root }, @@ -74,14 +100,14 @@ describe('init dependency installation (real subprocesses)', () => { it.each(['1.6.0', '^1.3.0'])( 'bootstraps the project-selected Vite+ %s without a local or global vp', - (version) => { + async (version) => { const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')); pkg.devDependencies['vite-plus'] = version; writeFileSync(join(root, 'package.json'), JSON.stringify(pkg)); executable('npx'); executable('pnpm', 1); - installProjectDependencies(root, 'pnpm'); + await install(root); // Assert the received argv: Windows cmd.exe must preserve the semver caret. expect(calls()).toEqual([ @@ -113,7 +139,7 @@ describe('init dependency installation (real subprocesses)', () => { ['yarn', 'catalog:tools', 'catalogs.tools'], ] as const)( 'bootstraps the Vite+ version from the %s workspace catalog (%s in %s)', - (manager, spec, location) => { + async (manager, spec, location) => { const member = join(root, 'packages/app'); mkdirSync(member, { recursive: true }); writeFileSync( @@ -141,7 +167,7 @@ describe('init dependency installation (real subprocesses)', () => { writeFileSync(join(root, '.yarnrc.yml'), JSON.stringify(catalogs)); } executable('npx'); - installProjectDependencies(member, manager); + await install(member, manager); expect(calls()).toEqual([ { command: 'npx', @@ -152,7 +178,7 @@ describe('init dependency installation (real subprocesses)', () => { }, ); - it('bootstraps with the CLI’s own Vite+ version when the catalog entry is missing', () => { + it('bootstraps with the CLI’s own Vite+ version when the catalog entry is missing', async () => { const member = join(root, 'packages/app'); mkdirSync(member, { recursive: true }); writeFileSync( @@ -164,7 +190,7 @@ describe('init dependency installation (real subprocesses)', () => { 'packages: [packages/*]\ncatalog: { vite-plus: "1.6.0" }\n', ); executable('npx'); - installProjectDependencies(member, 'pnpm'); + await install(member); expect(calls()).toEqual([ { command: 'npx', @@ -180,43 +206,161 @@ describe('init dependency installation (real subprocesses)', () => { ]); }); - it('reports a Vite+ install failure without retrying through another installer', () => { + it('reports a Vite+ install failure without retrying through another installer', async () => { executable('vp', 7); executable('npx'); executable('pnpm', 1); - expect(() => installProjectDependencies(root, 'pnpm')).toThrow( - 'vp install failed with exit code 7', - ); + await expect(install(root)).rejects.toThrow('vp install failed with exit code 7'); expect(calls()).toEqual([ { command: 'vp', args: ['--version'], cwd: root }, { command: 'vp', args: ['install', '--no-frozen-lockfile'], cwd: root }, ]); }); - it('uses an installed project-local Vite+ without requiring tools on PATH', () => { + it('keeps the installer output off the terminal and returns how long it ran', async () => { + executable('vp'); + + expect(await install(root)).toBeGreaterThan(0); + + expect(output()).toContain('Installing dependencies with vp'); + expect(output()).not.toContain('vp: '); + }); + + it('prints what the installer wrote to stdout and stderr when it fails', async () => { + executable('vp', 7); + + await expect(install(root)).rejects.toThrow('vp install failed with exit code 7'); + + expect(output()).toContain('vp: resolving packages\n'); + expect(output()).toContain('vp: registry unreachable\n'); + // The line that names the failed step comes before the installer's output. + expect(output().indexOf('Failed to install dependencies with vp')).toBeGreaterThan(-1); + expect(output().indexOf('Failed to install dependencies with vp')).toBeLessThan( + output().indexOf('vp: '), + ); + }); + + it('uses an installed project-local Vite+ without requiring tools on PATH', async () => { const vitePlus = join(root, 'node_modules', 'vite-plus'); mkdirSync(join(vitePlus, 'bin'), { recursive: true }); writeFileSync(join(vitePlus, 'package.json'), JSON.stringify({ name: 'vite-plus' })); executable('local-vp'); writeFileSync(join(vitePlus, 'bin', 'vp'), readFileSync(join(bin, 'local-vp.cjs'), 'utf8')); - installProjectDependencies(root, 'pnpm'); + await install(root); expect(calls()).toEqual([ { command: 'local-vp', args: ['install', '--no-frozen-lockfile'], cwd: root }, ]); }); - it('keeps plain Vite projects on their selected package manager', () => { + it('keeps plain Vite projects on their selected package manager', async () => { writeFileSync(join(root, 'package.json'), JSON.stringify({ private: true })); executable('vp', 1); executable('pnpm'); - installProjectDependencies(root, 'pnpm'); + await install(root); expect(calls()).toEqual([ { command: 'pnpm', args: ['install', '--no-frozen-lockfile'], cwd: root }, ]); }); + + describe('the command to install by hand', () => { + it('is `vp install` with a vp on PATH', () => { + executable('vp'); + + expect(resolveProjectInstall(root, 'pnpm').manualCommand).toBe('vp install'); + }); + + it('is `vp install` with a project-local vp', () => { + const vitePlus = join(root, 'node_modules', 'vite-plus'); + mkdirSync(join(vitePlus, 'bin'), { recursive: true }); + writeFileSync(join(vitePlus, 'package.json'), JSON.stringify({ name: 'vite-plus' })); + + expect(resolveProjectInstall(root, 'pnpm').manualCommand).toBe('vp install'); + }); + + it.each([ + ['1.6.0', 'vite-plus@1.6.0'], + // A shell can read the caret as a pattern or as an escape. + ['^1.3.0', process.platform === 'win32' ? '"vite-plus@^1.3.0"' : "'vite-plus@^1.3.0'"], + ])('gets Vite+ %s through npx without a local or global vp', (version, quoted) => { + const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')); + pkg.devDependencies['vite-plus'] = version; + writeFileSync(join(root, 'package.json'), JSON.stringify(pkg)); + executable('npx'); + + expect(resolveProjectInstall(root, 'pnpm').manualCommand).toBe(`npx -p ${quoted} vp install`); + }); + + it('is the package manager for a plain Vite project', () => { + writeFileSync(join(root, 'package.json'), JSON.stringify({ private: true })); + + expect(resolveProjectInstall(root, 'pnpm').manualCommand).toBe('pnpm install'); + }); + }); + + // Windows has no process groups: init stops the installer there with `taskkill`. + it.skipIf(process.platform === 'win32')( + 'stops the installer and what it started before init exits', + async () => { + // An installer that starts a lifecycle script. Both add a line to the + // beats file every 10ms while they run. + const beats = join(root, 'beats'); + const script = join(bin, 'vp.cjs'); + writeFileSync( + script, + `const { spawn } = require('node:child_process'); +const { appendFileSync } = require('node:fs'); +if (process.argv.includes('--version')) { + process.exit(0); +} +const role = process.argv[2] === 'postinstall' ? 'postinstall' : 'installer'; +if (role === 'installer') { + spawn(process.execPath, [__filename, 'postinstall'], { stdio: 'inherit' }); +} +const beat = () => appendFileSync(${JSON.stringify(beats)}, role + '\\n'); +beat(); +setInterval(beat, 10); +`, + ); + const launcher = `#!${process.execPath}\nrequire(${JSON.stringify(script)});\n`; + writeFileSync(join(bin, 'vp'), launcher, { mode: 0o755 }); + const exitListeners = process.listeners('exit'); + const exitCode = process.exitCode; + // Init exits, as on Ctrl+C at the spinner: run the listeners the install added. + const exitInit = (): void => { + for (const listener of process.listeners('exit')) { + if (!exitListeners.includes(listener)) { + listener(0); + } + } + }; + // The stopped installer fails the install, which the end of the test checks. + const outcome = install(root).then( + () => 'installed', + (error: Error) => error.message, + ); + try { + await vi.waitFor(() => expect(readFileSync(beats, 'utf8')).toContain('postinstall'), { + timeout: 10_000, + }); + + exitInit(); + + // Both processes had ended when the listeners returned. + const atExit = readFileSync(beats, 'utf8'); + await new Promise((resolve) => setTimeout(resolve, 150)); + expect(readFileSync(beats, 'utf8')).toBe(atExit); + expect(await outcome).toBe('vp install failed with exit code unknown'); + } finally { + // After a failed assertion too, so that no process of this test remains. + exitInit(); + await outcome; + process.exitCode = exitCode; + } + }, + ); }); diff --git a/packages/void/test/integration/init-subprocess.test.ts b/packages/void/test/integration/init-subprocess.test.ts new file mode 100644 index 000000000..f56626980 --- /dev/null +++ b/packages/void/test/integration/init-subprocess.test.ts @@ -0,0 +1,148 @@ +import { spawn, type ChildProcess } from 'node:child_process'; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; +import { isProcessGroupRunning, stopCommand } from '../../src/cli/init-subprocess.ts'; + +let root: string; +let beats: string; +const started: Array = []; + +/** Block this thread, so that Node cannot collect a child that has exited. */ +function sleepSync(ms: number): void { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); +} + +/** + * Start a command that starts a script, as an installer starts a lifecycle + * script. Both add a line to the beats file every 10ms while they run. A + * "stubborn" script goes on after SIGTERM. + */ +function startCommand(script: 'polite' | 'stubborn'): ChildProcess { + const file = join(root, 'command.cjs'); + writeFileSync( + file, + `const { spawn } = require('node:child_process'); +const { appendFileSync } = require('node:fs'); +const [beats, script, role = 'command'] = process.argv.slice(2); +if (role === 'command') { + spawn(process.execPath, [__filename, beats, script, 'script'], { stdio: 'inherit' }); +} else if (script === 'stubborn') { + process.on('SIGTERM', () => {}); +} +const beat = () => appendFileSync(beats, role + '\\n'); +beat(); +setInterval(beat, 10); +`, + ); + const child = spawn(process.execPath, [file, beats, script], { + detached: true, + stdio: 'ignore', + }); + started.push(child); + return child; +} + +async function commandAndScriptRun(): Promise { + await vi.waitFor( + () => { + const lines = readFileSync(beats, 'utf8'); + expect(lines).toContain('command'); + expect(lines).toContain('script'); + }, + { timeout: 10_000 }, + ); +} + +/** Whether a process still adds lines, 150ms after `stopCommand` returned. */ +async function beatsGoOn(): Promise { + const atReturn = readFileSync(beats, 'utf8'); + await new Promise((resolve) => setTimeout(resolve, 150)); + return readFileSync(beats, 'utf8') !== atReturn; +} + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'void-init-subprocess-')); + beats = join(root, 'beats'); +}); + +afterEach(() => { + for (const child of started.splice(0)) { + try { + process.kill(-child.pid!, 'SIGKILL'); + } catch { + // The test has stopped it. + } + } + rmSync(root, { recursive: true, force: true }); +}); + +// Windows has no process groups: init stops a command there with `taskkill`. +describe.skipIf(process.platform === 'win32')('stopCommand (real processes)', () => { + it('ends a command and what it started before it returns', async () => { + const child = startCommand('polite'); + await commandAndScriptRun(); + + const startedAt = performance.now(); + stopCommand(child); + const elapsed = performance.now() - startedAt; + + expect(await beatsGoOn()).toBe(false); + // It returned when the processes ended, not when the time to end ran out. + expect(elapsed).toBeLessThan(2_000); + }); + + it('kills what goes on after SIGTERM when the time to end is over', async () => { + const child = startCommand('stubborn'); + await commandAndScriptRun(); + + const startedAt = performance.now(); + stopCommand(child, 300); + const elapsed = performance.now() - startedAt; + + expect(await beatsGoOn()).toBe(false); + expect(elapsed).toBeGreaterThanOrEqual(300); + }); + + it('does nothing for a command that did not start', () => { + expect(() => stopCommand(undefined)).not.toThrow(); + }); +}); + +describe.skipIf(process.platform === 'win32')('isProcessGroupRunning (real processes)', () => { + // Linux reads /proc and other systems read `ps`. Linux has both, so cover both there. + const readers = [ + ...(process.platform === 'linux' ? [['/proc', 'linux']] : []), + ...(existsSync('/bin/ps') ? [['ps', 'darwin']] : []), + ] as Array<[string, NodeJS.Platform]>; + + it.each(readers)('finds a running process in %s', (_reader, platform) => { + const child = spawn('sleep', ['30'], { detached: true, stdio: 'ignore' }); + started.push(child); + + expect(isProcessGroupRunning(child.pid!, platform)).toBe(true); + }); + + it.each(readers)( + 'does not count in %s a process that has exited but that Node has not collected', + (_reader, platform) => { + const done = join(root, 'done'); + const child = spawn('sh', ['-c', 'echo done > "$0"', done], { + detached: true, + stdio: 'ignore', + }); + started.push(child); + // Wait without the event loop, as an `exit` listener does. + for (let waited = 0; !existsSync(done) && waited < 5_000; waited += 10) { + sleepSync(10); + } + sleepSync(100); + + // Node has not seen the exit, and the process still answers a signal. + expect(child.exitCode).toBeNull(); + expect(() => process.kill(child.pid!, 0)).not.toThrow(); + expect(isProcessGroupRunning(child.pid!, platform)).toBe(false); + }, + ); +}); diff --git a/packages/void/test/unit/init-git.test.ts b/packages/void/test/unit/init-git.test.ts index edc9330e7..9e4010590 100644 --- a/packages/void/test/unit/init-git.test.ts +++ b/packages/void/test/unit/init-git.test.ts @@ -3,7 +3,6 @@ import { existsSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node: import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { CANCEL_SYMBOL, cancel, confirm, log } from '@voidzero-dev/vite-plus-prompts'; -import { toSlash } from 'pathslash'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import { initialCommitCommand, setupGit } from '../../src/cli/init-git.ts'; @@ -141,13 +140,29 @@ describe('initial commit hint', () => { ); }); - it('targets the created subfolder, quoting shell metacharacters', () => { - const child = join(root, "app's $name `value`"); + it('targets a created subfolder by its path from the shell', () => { + // The user's shell stays in the parent directory. + vi.spyOn(process, 'cwd').mockReturnValue(root); + expect(initialCommitCommand(join(root, 'my-app'))).toBe( + 'git -C my-app add -A && git -C my-app commit -m "chore: initial commit"', + ); + }); + + it('quotes shell metacharacters in the subfolder name', () => { + vi.spyOn(process, 'cwd').mockReturnValue(root); + const name = "app's $name `value`"; const argument = - process.platform === 'win32' ? `"${toSlash(child)}"` : `'${child.replaceAll("'", "'\\''")}'`; + process.platform === 'win32' ? `"${name}"` : `'${name.replaceAll("'", "'\\''")}'`; const git = `git -C ${argument}`; - expect(initialCommitCommand(child)).toBe( + expect(initialCommitCommand(join(root, name))).toBe( `${git} add -A && ${git} commit -m "chore: initial commit"`, ); }); + + it('keeps git from reading the subfolder name as an option', () => { + vi.spyOn(process, 'cwd').mockReturnValue(root); + expect(initialCommitCommand(join(root, '-app'))).toBe( + 'git -C ./-app add -A && git -C ./-app commit -m "chore: initial commit"', + ); + }); }); diff --git a/packages/void/test/unit/init-report.test.ts b/packages/void/test/unit/init-report.test.ts index 8357908ca..b4f26813d 100644 --- a/packages/void/test/unit/init-report.test.ts +++ b/packages/void/test/unit/init-report.test.ts @@ -208,6 +208,41 @@ describe('an init run that stops early', () => { ]); }); + it('says how to finish the step it stopped in, after what it had done', async () => { + const report = new InitReport(); + const failure = new Error('vp install failed with exit code 1'); + + await expect( + report.printIfStopped(async () => { + report.setStarter('Created a React Pages starter with D1 (SQLite)'); + report.next('Add DATABASE_URL to .env'); + report.unfinished = 'Run `vp install` to finish setup'; + throw failure; + }), + ).rejects.toBe(failure); + + expect(vi.mocked(log.warn).mock.calls).toEqual([['Setup did not finish. Done so far:']]); + expect(vi.mocked(printNextStep).mock.calls).toEqual([ + ['Add DATABASE_URL to .env'], + ['Run `vp install` to finish setup'], + ]); + }); + + it('prints only how to finish a step that stopped before init changed anything', async () => { + const report = new InitReport(); + + await expect( + report.printIfStopped(async () => { + report.unfinished = 'Run `npm install` to finish setup'; + throw new Error('npm install failed with exit code 1'); + }), + ).rejects.toThrow('npm install failed'); + + // No heading: there is no finished work to list under it. + expect(log.warn).not.toHaveBeenCalled(); + expect(vi.mocked(printNextStep).mock.calls).toEqual([['Run `npm install` to finish setup']]); + }); + it('prints nothing when it stops before it changes anything', async () => { await expect( new InitReport().printIfStopped(async () => { @@ -225,11 +260,14 @@ describe('an init run that stops early', () => { await report.printIfStopped(async () => { report.created('void.config.ts'); + // The summary lists finished work, not how to finish a step by hand. + report.unfinished = 'Run `npm install` to finish setup'; report.print(); }); expect(log.warn).not.toHaveBeenCalled(); expect(vi.mocked(printDone).mock.calls).toEqual([[['Configured Void', '+ void.config.ts']]]); + expect(printNextStep).not.toHaveBeenCalled(); expect(process.listeners('exit')).toEqual(listeners); }); }); diff --git a/packages/void/test/unit/init-starter-migrations.test.ts b/packages/void/test/unit/init-starter-migrations.test.ts index d946cd8c7..5b6aa5b5a 100644 --- a/packages/void/test/unit/init-starter-migrations.test.ts +++ b/packages/void/test/unit/init-starter-migrations.test.ts @@ -22,6 +22,7 @@ vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ confirm: vi.fn(), isCancel: vi.fn(), isCI: () => false, + settings: { accessible: false }, select: vi.fn(), text: vi.fn(), spinner: () => ({ start: vi.fn(), stop: vi.fn(), message: vi.fn() }), @@ -40,20 +41,20 @@ afterEach(() => { // Each case runs real Drizzle Kit subprocesses for generation and drift checking. // Windows CI needs more than the default five seconds to start both processes. describe('starter migration generation', { timeout: 30_000 }, () => { - it('creates a sqlite starter migration that deploy sees as drift-free', () => { + it('creates a sqlite starter migration that deploy sees as drift-free', async () => { const root = createStarterApp('sqlite'); - generateStarterMigration(root, 'sqlite'); + await generateStarterMigration(root, 'sqlite'); expect(readSqlMigrations(root)).toHaveLength(1); expect(existsSync(join(root, 'db', 'migrations', 'meta', '_journal.json'))).toBe(true); expect(hasDeploySchemaDrift(root, 'sqlite')).toBe(false); }); - it('creates a postgresql starter migration that deploy sees as drift-free', () => { + it('creates a postgresql starter migration that deploy sees as drift-free', async () => { const root = createStarterApp('postgresql'); - generateStarterMigration(root, 'postgresql'); + await generateStarterMigration(root, 'postgresql'); expect(readSqlMigrations(root)).toHaveLength(1); expect(existsSync(join(root, 'db', 'migrations', 'meta', '_journal.json'))).toBe(true); diff --git a/packages/void/test/unit/init.test.ts b/packages/void/test/unit/init.test.ts index 5cdb8a6a1..8b5ee0474 100644 --- a/packages/void/test/unit/init.test.ts +++ b/packages/void/test/unit/init.test.ts @@ -35,12 +35,16 @@ import { buildDrizzleKitSpawnEnv } from '../../src/cli/yarn-pnp.ts'; import { readConfig } from '../../src/config.ts'; const mockSpawnSync = vi.fn(); +/** Ends each mocked `spawn` whose result sets `hang`. */ +const hangingCommands: Array<() => void> = []; +const HANGING_COMMAND_PID = 0x7fffffff; const mockSelect = vi.fn(); const mockConfirm = vi.fn(); const mockText = vi.fn(); const mockNote = vi.fn(); const mockOutro = vi.fn(); const mockLogWarn = vi.fn(); +const mockLogError = vi.fn(); const mockLogInfo = vi.fn(); const mockLogStep = vi.fn(); const mockLogMessage = vi.fn(); @@ -336,6 +340,8 @@ describe('init summary', () => { expect(summaryMessages('✓')).toEqual([ 'Created a React Pages starter with D1 (SQLite)', 'Linked Void skills for Claude Code', + INSTALLED, + 'Generated the initial database migration', ]); expect(summaryMessages('→')).toEqual([ 'Git (optional): git add -A && git commit -m "chore: initial commit"', @@ -352,6 +358,333 @@ describe('init summary', () => { } }); + it('keeps the output of the install and of drizzle-kit off the terminal', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-quiet-')); + const write = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + try { + mockSpawnSync.mockImplementation((command, args, options) => { + const generateCwd = drizzleGenerateCwd(command, args, options); + if (generateCwd) { + writeMockGeneratedMigration(generateCwd); + } + return { status: 0, stdout: 'added 181 packages\n', stderr: 'npm warn deprecated\n' }; + }); + + await runInitCommand(root, parseInitArgs(STARTER_FLAGS)); + + // Without a terminal there is no spinner. Each step logs one line when it starts. + expect(mockLogStep.mock.calls).toEqual([ + ['Installing dependencies with npm'], + ['Generating the initial database migration'], + ]); + expect(write).not.toHaveBeenCalled(); + expect(mockLogError).not.toHaveBeenCalled(); + expect(summaryMessages('✓')).toEqual([ + 'Created a React Pages starter with D1 (SQLite)', + INSTALLED, + 'Generated the initial database migration', + ]); + } finally { + write.mockRestore(); + rmSync(root, { recursive: true, force: true }); + } + }); + + it.each([ + [ + 'sqlite', + 'Created a React Pages starter with D1 (SQLite)', + 'Run `npm install`, then `void db generate` to finish setup', + ], + ['static', 'Created a static React Pages starter', 'Run `npm install` to finish setup'], + ])( + 'prints the output of a failed install and what is left to run for the %s starter', + async (starter, created, nextStep) => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-install-fails-')); + // The user's shell is in the project, so the commands need no `cd`. + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); + const write = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + try { + mockSpawnSync.mockImplementation((_command, args) => + Array.isArray(args) && args[0] === 'install' + ? { status: 1, stdout: 'resolving packages\n', stderr: 'ERR registry unreachable' } + : { status: 0, stdout: '', stderr: '' }, + ); + + await expect( + runInitCommand( + root, + parseInitArgs([ + '--toolchain', + 'vite', + '--framework', + 'react', + '--starter', + starter, + '--deploy', + 'none', + ]), + ), + ).rejects.toThrow('npm install failed with exit code 1'); + + expect(mockLogError.mock.calls).toEqual([['Failed to install dependencies with npm']]); + expect(write.mock.calls).toEqual([['resolving packages\nERR registry unreachable\n']]); + expect(mockLogWarn.mock.calls).toEqual([['Setup did not finish. Done so far:']]); + // The failed step, its output, then what init had done. + expect(mockLogError.mock.invocationCallOrder[0]).toBeLessThan( + write.mock.invocationCallOrder[0]!, + ); + expect(write.mock.invocationCallOrder[0]).toBeLessThan( + mockLogWarn.mock.invocationCallOrder[0]!, + ); + expect(summaryMessages('✓')).toEqual([created]); + expect(summaryMessages('→')).toEqual([nextStep]); + expect(drizzleGenerateCalls()).toEqual([]); + expect(mockOutro).not.toHaveBeenCalled(); + } finally { + write.mockRestore(); + cwd.mockRestore(); + rmSync(root, { recursive: true, force: true }); + } + }, + ); + + it('names the command that creates the migration when drizzle-kit fails', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-migration-fails-')); + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); + try { + mockSpawnSync.mockImplementation((command, args, options) => + drizzleGenerateCwd(command, args, options) + ? { status: 1, stdout: '', stderr: 'drizzle-kit: simulated crash\n' } + : { status: 0, stdout: '', stderr: '' }, + ); + + await expect(runInitCommand(root, parseInitArgs(STARTER_FLAGS))).rejects.toThrow( + 'Failed to generate the initial database migration.\n\ndrizzle-kit: simulated crash', + ); + + // The error carries drizzle-kit's output, so no line takes the spinner's place. + expect(mockLogError).not.toHaveBeenCalled(); + expect(mockLogWarn.mock.calls).toEqual([['Setup did not finish. Done so far:']]); + expect(summaryMessages('✓')).toEqual([ + 'Created a React Pages starter with D1 (SQLite)', + INSTALLED, + ]); + expect(summaryMessages('→')).toEqual(['Run `void db generate` to finish setup']); + } finally { + cwd.mockRestore(); + rmSync(root, { recursive: true, force: true }); + } + }); + + it('stops the install and says how to finish it when init exits during it', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-install-exit-')); + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); + const kill = vi.spyOn(process, 'kill').mockReturnValue(true); + const exitListeners = process.listeners('exit'); + const interruptListeners = process.listeners('SIGINT'); + const exitCode = process.exitCode; + let run: Promise | undefined; + try { + mockSpawnSync.mockImplementation((_command, args) => + Array.isArray(args) && args[0] === 'install' + ? { status: 0, hang: true } + : { status: 0, stdout: '', stderr: '' }, + ); + run = runInitCommand(root, parseInitArgs(STARTER_FLAGS)); + await vi.waitFor(() => expect(hangingCommands).toHaveLength(1)); + + // Ctrl+C at a spinner exits the process with 0, which runs the exit + // listeners in order. Call the ones this run added. + for (const listener of process.listeners('exit')) { + if (!exitListeners.includes(listener)) { + listener(0); + } + } + + // An interrupted install is not a success for the caller. + expect(process.exitCode).toBe(130); + + // The stopped step comes first. Without a terminal it is a red ■ line, + // as a cancelled spinner is in a terminal. + expect(mockLogError.mock.calls).toEqual([['Installing dependencies with npm']]); + expect(mockLogWarn.mock.calls).toEqual([['Setup did not finish. Done so far:']]); + expect(mockLogError.mock.invocationCallOrder[0]).toBeLessThan( + mockLogWarn.mock.invocationCallOrder[0]!, + ); + // The installer runs in its own process group, which init stops as a whole. + if (process.platform === 'win32') { + expect(mockSpawnSync).toHaveBeenCalledWith( + 'taskkill', + ['/PID', String(HANGING_COMMAND_PID), '/T', '/F'], + expect.anything(), + ); + } else { + expect(mockSpawnSync).toHaveBeenCalledWith( + 'npm', + ['install'], + expect.objectContaining({ detached: true }), + ); + expect(kill.mock.calls).toEqual([[-HANGING_COMMAND_PID, 'SIGTERM']]); + } + // A signal to init does not reach that group, so init listens for it + // while the installer runs. + expect(process.listeners('SIGINT')).toHaveLength(interruptListeners.length + 1); + expect(summaryMessages('✓')).toEqual(['Created a React Pages starter with D1 (SQLite)']); + expect(summaryMessages('→')).toEqual([ + 'Run `npm install`, then `void db generate` to finish setup', + ]); + + // The run removes its listeners when the command ends. + hangingCommands.pop()!(); + await run; + expect(process.listeners('exit')).toEqual(exitListeners); + expect(process.listeners('SIGINT')).toEqual(interruptListeners); + } finally { + // After a failed assertion too, so that no listener of this run remains. + for (const finish of hangingCommands.splice(0)) { + finish(); + } + await run?.catch(() => {}); + process.exitCode = exitCode; + kill.mockRestore(); + cwd.mockRestore(); + rmSync(root, { recursive: true, force: true }); + } + }); + + it('removes what drizzle-kit wrote when init exits during it', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-migration-exit-')); + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); + const kill = vi.spyOn(process, 'kill').mockReturnValue(true); + const exitListeners = process.listeners('exit'); + const exitCode = process.exitCode; + const migrations = join(root, 'db', 'migrations'); + let run: Promise | undefined; + try { + mockSpawnSync.mockImplementation((command, args, options) => { + const generateCwd = drizzleGenerateCwd(command, args, options); + if (!generateCwd) { + return { status: 0, stdout: '', stderr: '' }; + } + // drizzle-kit has written the journal entry, and not the SQL file yet. + writeMockGeneratedMigration(generateCwd); + rmSync(join(migrations, '0000_generated.sql')); + return { status: null, hang: true }; + }); + run = runInitCommand(root, parseInitArgs(STARTER_FLAGS)); + await vi.waitFor(() => expect(hangingCommands).toHaveLength(1)); + expect(existsSync(join(migrations, 'meta', '_journal.json'))).toBe(true); + + for (const listener of process.listeners('exit')) { + if (!exitListeners.includes(listener)) { + listener(0); + } + } + + // With the journal entry left behind, `void db generate` would find no + // schema changes and never write the SQL file. + expect(existsSync(join(migrations, 'meta'))).toBe(false); + expect(listMigrationSqlFiles(root)).toEqual([]); + if (process.platform !== 'win32') { + expect(kill.mock.calls).toEqual([[-HANGING_COMMAND_PID, 'SIGTERM']]); + } + expect(mockLogError.mock.calls).toEqual([['Generating the initial database migration']]); + expect(mockLogWarn.mock.calls).toEqual([['Setup did not finish. Done so far:']]); + expect(summaryMessages('✓')).toEqual([ + 'Created a React Pages starter with D1 (SQLite)', + INSTALLED, + ]); + expect(summaryMessages('→')).toEqual(['Run `void db generate` to finish setup']); + + // The stopped drizzle-kit ends without an exit code. + hangingCommands.pop()!(); + await expect(run).rejects.toThrow('Failed to generate the initial database migration.'); + } finally { + for (const finish of hangingCommands.splice(0)) { + finish(); + } + await run?.catch(() => {}); + process.exitCode = exitCode; + kill.mockRestore(); + cwd.mockRestore(); + rmSync(root, { recursive: true, force: true }); + } + }); + + it.each([ + ['a vp on PATH', 0, 'vp install'], + // `vp install` would not run for this user. The starter pins a Vite+ version. + ['no vp', 1, expect.stringMatching(/^npx -p vite-plus@\d+\.\d+\.\d+ vp install$/)], + ])( + 'names an install that the user can run with %s when a Vite+ install fails', + async (_vp, probeStatus, manualCommand) => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-vite-plus-install-fails-')); + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); + const write = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + try { + mockSpawnSync.mockImplementation((command, args) => { + if (command === 'vp' && Array.isArray(args) && args[0] === '--version') { + return { status: probeStatus }; + } + return Array.isArray(args) && args.includes('install') + ? { status: 1, stdout: '', stderr: '' } + : { status: 0, stdout: '', stderr: '' }; + }); + + await expect( + runInitCommand( + root, + parseInitArgs([ + '--toolchain', + 'vite-plus', + '--framework', + 'react', + '--starter', + 'sqlite', + '--deploy', + 'none', + ]), + ), + ).rejects.toThrow('vp install failed with exit code 1'); + + const [nextStep, ...others] = summaryMessages('→'); + expect(others).toEqual([]); + const command = /^Run `(.+)`, then `void db generate` to finish setup$/.exec( + String(nextStep), + )?.[1]; + expect(command).toEqual(manualCommand); + } finally { + write.mockRestore(); + cwd.mockRestore(); + rmSync(root, { recursive: true, force: true }); + } + }, + ); + + it('points the Git command at a new subfolder by its path from the shell', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-subfolder-')); + // The user's shell stays in the parent directory. + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); + try { + mkdirSync(join(root, 'existing-project')); + mockSelect.mockResolvedValueOnce('subfolder'); + mockText.mockResolvedValueOnce('my-new-app'); + + await runInitCommand(root, parseInitArgs(['--git', ...STARTER_FLAGS])); + + expect(summaryMessages('→')).toEqual([ + 'Git (optional): git -C my-new-app add -A && git -C my-new-app commit -m "chore: initial commit"', + ]); + expect(String(mockOutro.mock.calls.at(-1)?.[0])).toContain( + 'Run `cd my-new-app && vite dev` to start developing.', + ); + } finally { + cwd.mockRestore(); + rmSync(root, { recursive: true, force: true }); + } + }); + it('lists the files it created and changed in an existing project', async () => { const root = realpathSync(mkdtempSync(join(tmpdir(), 'void-init-summary-existing-'))); try { @@ -377,9 +710,12 @@ describe('init summary', () => { '~ tsconfig.json extends .void/tsconfig.json, added void/env to types', ], 'Linked Void skills for Claude Code', + INSTALLED, ]); expect(summaryMessages('→')).toEqual([]); + // The mocked install left nothing in node_modules. + writeInstalledVoid(root); mockLogMessage.mockClear(); await runInitCommand(root); @@ -391,11 +727,13 @@ describe('init summary', () => { }); it.each([ - ['installed', true], - ['not installed', false], + ['installed', true, 'npm'], + ['not installed', false, 'npm'], + // Init installs a Vite+ project with vp, so it asks for the same command. + ['installed in a Vite+ project', true, 'vp'], ])( 'asks for an install after removing a dependency when void is %s', - async (_name, voidInstalled) => { + async (_name, voidInstalled, installer) => { const root = mkdtempSync(join(tmpdir(), 'void-init-summary-lockfile-')); const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); try { @@ -405,7 +743,12 @@ describe('init summary', () => { name: 'app', type: 'module', scripts: { dev: 'vite', build: 'vite build' }, - devDependencies: { '@cloudflare/workers-types': '^4.0.0', vite: '^8.0.0', void: '*' }, + devDependencies: { + '@cloudflare/workers-types': '^4.0.0', + vite: '^8.0.0', + void: '*', + ...(installer === 'vp' ? { 'vite-plus': '*' } : {}), + }, }) + '\n', ); writeFileSync( @@ -430,7 +773,7 @@ describe('init summary', () => { // 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'] : [], + voidInstalled ? [`Run \`${installer} install\` to update your lockfile`] : [], ); } finally { cwd.mockRestore(); @@ -484,7 +827,30 @@ describe('init summary', () => { '~ vite.config.ts added voidPlugin()', '~ tsconfig.json extends .void/tsconfig.json, added void/env to types', ], + // The list of files does not show that the migration deleted wrangler.jsonc. + 'Migrated project configuration to void.config.ts', + INSTALLED, ]); + expect(summaryMessages('→')).toEqual(['Commit void.config.ts and void.lock.json']); + expect(mockLogStep).not.toHaveBeenCalledWith(expect.stringContaining('Migrated')); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it('asks to commit only void.config.ts when the migration wrote no lock file', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-init-summary-migration-json-')); + try { + writeExistingViteApp(root); + // Only a Cloudflare config gives the migration something to lock. + writeFileSync(join(root, 'void.json'), '{ "routing": { "prerender": ["/"] } }\n'); + + await runInitCommand(root, { tsconfig: true, github: false }); + + expect(existsSync(join(root, 'void.json'))).toBe(false); + expect(existsSync(join(root, 'void.lock.json'))).toBe(false); + expect(summaryMessages('✓')).toContain('Migrated project configuration to void.config.ts'); + expect(summaryMessages('→')).toContain('Commit void.config.ts'); } finally { rmSync(root, { recursive: true, force: true }); } @@ -738,7 +1104,7 @@ vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ log: { success: vi.fn(), warn: (...args: Array) => mockLogWarn(...args), - error: vi.fn(), + error: (...args: Array) => mockLogError(...args), info: (...args: Array) => mockLogInfo(...args), step: (...args: Array) => mockLogStep(...args), message: (...args: Array) => mockLogMessage(...args), @@ -791,9 +1157,51 @@ vi.mock('../../src/cli/client', () => ({ }, })); -vi.mock('node:child_process', () => ({ - spawnSync: (...args: Array) => mockSpawnSync(...args), -})); +vi.mock('node:child_process', async () => { + const { EventEmitter } = await import('node:events'); + return { + spawnSync: (...args: Array) => mockSpawnSync(...args), + // Init runs installs and drizzle-kit with `spawn`, behind a spinner. Answer + // them from the same mock, so a test sets one result for both kinds of call. + spawn: (...args: Array) => { + const result = mockSpawnSync(...args) as + | { + status?: number | null; + stdout?: string; + stderr?: string; + error?: Error; + hang?: boolean; + } + | undefined; + const child = Object.assign(new EventEmitter(), { + stdout: new EventEmitter(), + stderr: new EventEmitter(), + // No process has this id, so a signal to it reaches nothing. + pid: result?.hang ? HANGING_COMMAND_PID : undefined, + }); + const finish = (): void => { + if (result?.error) { + child.emit('error', result.error); + return; + } + if (result?.stdout) { + child.stdout.emit('data', Buffer.from(result.stdout)); + } + if (result?.stderr) { + child.stderr.emit('data', Buffer.from(result.stderr)); + } + child.emit('close', result?.status ?? null); + }; + if (result?.hang) { + // The command keeps running until the test ends it. + hangingCommands.push(finish); + } else { + queueMicrotask(finish); + } + return child; + }, + }; +}); function withTempDir(run: (root: string) => void): void { const root = mkdtempSync(join(tmpdir(), 'void-init-')); @@ -804,6 +1212,15 @@ function withTempDir(run: (root: string) => void): void { } } +async function withTempDirAsync(run: (root: string) => Promise): Promise { + const root = mkdtempSync(join(tmpdir(), 'void-init-')); + try { + await run(root); + } finally { + rmSync(root, { recursive: true, force: true }); + } +} + function writeMockGeneratedMigration(root: string): void { const schema = readFileSync(join(root, 'db', 'schema.ts'), 'utf-8'); const isPostgres = schema.includes('from "void/schema-pg"'); @@ -908,6 +1325,9 @@ function summaryMessages(symbol: '✓' | '→'): Array> { .map(([message]) => message); } +/** The summary line for an install. The mocked installer finishes at once. */ +const INSTALLED = expect.stringMatching(/^Installed dependencies in (\d+ms|\d\.\ds|\d+s)$/); + function writeInstalledVoid(dir: string): void { mkdirSync(join(dir, 'node_modules', 'void'), { recursive: true }); writeFileSync( @@ -1035,6 +1455,7 @@ afterEach(() => { mockNote.mockReset(); mockOutro.mockReset(); mockLogWarn.mockReset(); + mockLogError.mockReset(); mockLogInfo.mockReset(); mockLogStep.mockReset(); mockLogMessage.mockReset(); @@ -1916,7 +2337,11 @@ describe('isScaffoldableEmptyProject', () => { expect(readFileSync(join(root, 'db', 'migrations', '0000_generated.sql'), 'utf-8')).toContain( 'CREATE TABLE "messages"', ); - expect(summaryMessages('✓')).toEqual(['Created a Vue Pages starter with PostgreSQL']); + expect(summaryMessages('✓')).toEqual([ + 'Created a Vue Pages starter with PostgreSQL', + INSTALLED, + 'Generated the initial database migration', + ]); expect(summaryMessages('→')).toEqual([ 'Add DATABASE_URL to .env before running `vp dev` (Void uses it for local PostgreSQL development)', ]); @@ -2264,8 +2689,12 @@ describe('isScaffoldableEmptyProject', () => { expect(existsSync(join(root, 'package.json'))).toBe(false); expect(existsSync(join(root, 'vite.config.ts'))).toBe(false); + // Init created the folder, so it does not report detecting an empty project. + expect(mockLogInfo).toHaveBeenCalledWith('Creating a Pages starter in ./my-new-app.'); + expect(mockLogInfo).not.toHaveBeenCalledWith(expect.stringContaining('detected')); expect(summaryMessages('✓')).toEqual([ 'Created a static React Pages starter in ./my-new-app', + INSTALLED, ]); const appRoot = join(root, 'my-new-app'); @@ -2302,7 +2731,7 @@ describe('isScaffoldableEmptyProject', () => { ['install', '--no-frozen-lockfile'], expect.objectContaining({ cwd: toSlash(appRoot), - stdio: 'inherit', + stdio: ['ignore', 'pipe', 'pipe'], shell: process.platform === 'win32', }), ); @@ -2367,7 +2796,7 @@ describe('isScaffoldableEmptyProject', () => { ['install'], expect.objectContaining({ cwd: root, - stdio: 'inherit', + stdio: ['ignore', 'pipe', 'pipe'], shell: process.platform === 'win32', }), ); @@ -2714,7 +3143,7 @@ export default defineConfig({ ['install'], expect.objectContaining({ cwd: root, - stdio: 'inherit', + stdio: ['ignore', 'pipe', 'pipe'], shell: process.platform === 'win32', }), ); @@ -3418,7 +3847,7 @@ export default config; ['install', '--no-frozen-lockfile'], expect.objectContaining({ cwd: root, - stdio: 'inherit', + stdio: ['ignore', 'pipe', 'pipe'], shell: process.platform === 'win32', }), ); @@ -4734,8 +5163,8 @@ describe('generateStarterMigration', () => { ); } - it('rolls back partial artifacts when drizzle-kit fails and migrations/ did not exist before', () => { - withTempDir((root) => { + it('rolls back partial artifacts when drizzle-kit fails and migrations/ did not exist before', async () => { + await withTempDirAsync(async (root) => { seedStarterSchema(root); mockSpawnSync.mockImplementationOnce((command, args, options) => { const cwd = drizzleGenerateCwd(command, args, options); @@ -4757,8 +5186,8 @@ describe('generateStarterMigration', () => { }; }); - expect(() => generateStarterMigration(root, 'sqlite')).toThrow( - /Failed to generate the starter database migration/, + await expect(generateStarterMigration(root, 'sqlite')).rejects.toThrow( + /Failed to generate the initial database migration/, ); expect(existsSync(join(root, 'db', 'migrations', 'meta', '_journal.json'))).toBe(false); @@ -4773,8 +5202,8 @@ describe('generateStarterMigration', () => { }); }); - it('restores the journal and keeps prior entries when drizzle-kit fails and a journal existed before', () => { - withTempDir((root) => { + it('restores the journal and keeps prior entries when drizzle-kit fails and a journal existed before', async () => { + await withTempDirAsync(async (root) => { seedStarterSchema(root); const migrationsDir = join(root, 'db', 'migrations'); const metaDir = join(migrationsDir, 'meta'); @@ -4816,8 +5245,8 @@ describe('generateStarterMigration', () => { }; }); - expect(() => generateStarterMigration(root, 'sqlite')).toThrow( - /Failed to generate the starter database migration/, + await expect(generateStarterMigration(root, 'sqlite')).rejects.toThrow( + /Failed to generate the initial database migration/, ); expect(readFileSync(join(metaDir, '_journal.json'), 'utf-8')).toBe(originalJournal); @@ -4829,18 +5258,18 @@ describe('generateStarterMigration', () => { }); // cmd.exe would split `C:\Program Files\nodejs\node.exe` and paths with spaces. - it('runs drizzle-kit and the Yarn PnP probe without a shell on Windows', () => { + it('runs drizzle-kit and the Yarn PnP probe without a shell on Windows', async () => { const platform = Object.getOwnPropertyDescriptor(process, 'platform')!; Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }); try { - withTempDir((root) => { + await withTempDirAsync(async (root) => { seedStarterSchema(root); writeFileSync(join(root, '.pnp.cjs'), '// pnp stub\n'); mkdirSync(join(root, '.yarn'), { recursive: true }); writeFileSync(join(root, '.yarn', 'install-state.gz'), ''); mockSpawnSync.mockReturnValue({ status: 0, stdout: '', stderr: '' }); - generateStarterMigration(root, 'sqlite'); + await generateStarterMigration(root, 'sqlite'); expect(isVoidResolvableFrom(root)).toBe(true); const nodeSpawns = mockSpawnSync.mock.calls.filter( diff --git a/packages/void/test/unit/output-duration.test.ts b/packages/void/test/unit/output-duration.test.ts new file mode 100644 index 000000000..223e4fea7 --- /dev/null +++ b/packages/void/test/unit/output-duration.test.ts @@ -0,0 +1,15 @@ +import { expect, it } from 'vite-plus/test'; +import { formatDuration } from '../../src/cli/output.ts'; + +it.each([ + [0, '1ms'], + [215, '215ms'], + [999.6, '1.0s'], + [2449, '2.4s'], + [9940, '9.9s'], + // One decimal would round these up to "10.0s". + [9960, '10s'], + [63_400, '63s'], +])('formats %sms as vp create does', (durationMs, expected) => { + expect(formatDuration(durationMs)).toBe(expected); +}); diff --git a/packages/void/test/unit/output-spinner.test.ts b/packages/void/test/unit/output-spinner.test.ts index 945ba8168..0a0a48f5c 100644 --- a/packages/void/test/unit/output-spinner.test.ts +++ b/packages/void/test/unit/output-spinner.test.ts @@ -30,6 +30,36 @@ it('passes interactive cancellation through to the native spinner', () => { expect(mocks.spinner).toHaveBeenCalledWith({ onCancel }); }); +it('passes the elapsed-time indicator through to the native spinner', () => { + mocks.ci.mockReturnValue(false); + mocks.spinner.mockReturnValue({ start: vi.fn() }); + const options = { indicator: 'timer', cancelMessage: 'Installing dependencies' } as const; + createSpinner(options, true); + expect(mocks.spinner).toHaveBeenCalledWith(options); +}); + +it('keeps a cleared or failed step visible without a terminal', () => { + mocks.ci.mockReturnValue(false); + const progress = createSpinner({ indicator: 'timer' }, false); + progress.start('Installing dependencies'); + progress.clear(); + progress.error('Failed to install dependencies'); + expect(mocks.spinner).not.toHaveBeenCalled(); + expect(mocks.log.step.mock.calls).toEqual([['Installing dependencies']]); + expect(mocks.log.error.mock.calls).toEqual([['Failed to install dependencies']]); +}); + +it('marks a cancelled step without a terminal as a cancelled spinner does in one', () => { + mocks.ci.mockReturnValue(true); + const progress = createSpinner({ indicator: 'timer' }, true); + progress.start('Installing dependencies'); + progress.cancel('Installing dependencies'); + // `log.error` draws the red ■ of a cancelled spinner. A warning is a yellow ▲. + expect(mocks.log.error.mock.calls).toEqual([['Installing dependencies']]); + expect(mocks.log.warn).not.toHaveBeenCalled(); + expect(progress.isCancelled).toBe(true); +}); + it('uses plain progress messages in CI without starting an animated spinner', () => { mocks.ci.mockReturnValue(true); const progress = createSpinner(undefined, true);