Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/void/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion packages/void/src/cli/cli-main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ if (helpPath) {
}
runInitCommand(root, initArgs).catch((err) => {
log.error(formatCloudflareUserMessage(err.message ?? String(err)));
process.exit(1);
process.exitCode = 1;
});
});
} else if (command === 'migrate') {
Expand Down
9 changes: 5 additions & 4 deletions packages/void/src/cli/init-git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
if (git === false) {
Expand Down Expand Up @@ -59,8 +59,9 @@ export async function setupGit(root: string, git?: boolean): Promise<boolean> {
}

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"`;
}
15 changes: 13 additions & 2 deletions packages/void/src/cli/init-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ export class InitReport {
readonly completed: Array<string> = [];
/** What the user should do next. */
readonly nextSteps: Array<string> = [];
/**
* 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. */
Expand Down Expand Up @@ -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;
Expand All @@ -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, { wrap: false });
}
}

private printOtherWork(): void {
Expand Down
29 changes: 19 additions & 10 deletions packages/void/src/cli/init-shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`;
}
266 changes: 266 additions & 0 deletions packages/void/src/cli/init-subprocess.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
import { once } from 'node:events';
import {
closeSync,
createReadStream,
mkdtempSync,
openSync,
readdirSync,
readFileSync,
rmSync,
statSync,
} from 'node:fs';
import { constants, tmpdir } from 'node:os';
import { join } from 'pathslash';
import { createSpinner } from './output.ts';

type SubprocessResult = {
/** The exit code, or null when a signal ended the command. */
status: number | null;
/** How long the command ran, in milliseconds. */
durationMs: number;
};

// On POSIX, a terminal hangup does not reach the detached command group.
const STOP_SIGNALS: Array<NodeJS.Signals> =
process.platform === 'win32' ? ['SIGINT', 'SIGTERM'] : ['SIGINT', 'SIGTERM', 'SIGHUP'];

/** 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<string>;
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);
}

async function replayOutput(path: string): Promise<void> {
const { size } = statSync(path);
if (size === 0) {
return;
}
// Stop at the size on exit even if a background child is still writing.
const output = createReadStream(path, { encoding: 'utf8', end: size - 1 });
let endsWithNewline = true;
for await (const chunk of output) {
endsWithNewline = chunk.endsWith('\n');
if (!process.stdout.write(chunk)) {
await once(process.stdout, 'drain');
}
}
if (!endsWithNewline) {
process.stdout.write('\n');
}
}

/** Run a command behind a spinner and print its output if it fails. */
export async function runBehindSpinner(
message: string,
command: string,
args: Array<string>,
options: {
cwd: string;
env?: NodeJS.ProcessEnv;
shell?: boolean;
/** The line to leave in place of the spinner when the command fails. */
failed?: string;
/** Removes partial changes after a failure or interruption. */
undo?: () => void;
},
): Promise<SubprocessResult> {
const { failed, undo, ...spawnOptions } = options;
const directory = mkdtempSync(join(tmpdir(), 'void-init-'));
const path = join(directory, 'output.log');
const cleanup = (): void => rmSync(directory, { recursive: true, force: true });
let child: ChildProcess | undefined;
const progress = createSpinner({ indicator: 'timer', cancelMessage: message });
// A spinner reads Ctrl+C as a key press and exits the process. Mark the step
// as stopped and finish rollback before the exit listener that reports init's work.
const onExit = (code: number): void => {
if (child) {
progress.cancel(message);
stopCommand(child);
undo?.();
// The prompt library exits with 0. A caller such as create-void should
// see a cancellation and stop, too.
if (code === 0) {
process.exitCode = 130;
}
}
cleanup();
};
const onSignal = (signal: NodeJS.Signals): void => {
process.exit(128 + constants.signals[signal]);
};

try {
progress.start(message);
process.prependListener('exit', onExit);
for (const signal of STOP_SIGNALS) {
process.on(signal, onSignal);
}

const startedAt = performance.now();
let status: number | null = null;
try {
status = await new Promise<number | null>((resolve, reject) => {
// Both writers share the same file offset. Inheriting a file instead
// of a pipe lets init finish even if a background child keeps it open.
const fd = openSync(path, 'wx');
try {
child = spawn(command, args, {
...spawnOptions,
stdio: ['ignore', fd, fd],
detached: process.platform !== 'win32',
});
child.once('error', reject);
child.once('exit', resolve);
} finally {
closeSync(fd);
}
});
} finally {
if (status !== 0 && !progress.isCancelled && undo) {
// A failed generator can still have children writing its outputs.
stopCommand(child);
undo();
}
child = undefined;
if (status === 0 || !failed) {
progress.clear();
} else if (!progress.isCancelled) {
progress.error(failed);
}
}
const durationMs = performance.now() - startedAt;
if (status !== 0 && !progress.isCancelled) {
await replayOutput(path);
}
return { status, durationMs };
} finally {
process.removeListener('exit', onExit);
for (const signal of STOP_SIGNALS) {
process.removeListener(signal, onSignal);
}
cleanup();
}
}
Loading
Loading