From d12561ad4f24f33cd5ca34f0164451819e10bc04 Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Sat, 28 Nov 2026 12:33:49 +0800 Subject: [PATCH] fix: Handle closed stdin in void init --- docs/reference/cli/setup.md | 4 +- packages/void/src/cli/deploy-setup.ts | 6 + packages/void/src/cli/init.ts | 69 +++-- packages/void/test/unit/init-stdin.test.ts | 315 +++++++++++++++++++++ 4 files changed, 377 insertions(+), 17 deletions(-) create mode 100644 packages/void/test/unit/init-stdin.test.ts diff --git a/docs/reference/cli/setup.md b/docs/reference/cli/setup.md index 76a9d9faa..6f7ad1bb1 100644 --- a/docs/reference/cli/setup.md +++ b/docs/reference/cli/setup.md @@ -51,7 +51,9 @@ npm create void@latest my-app -- --toolchain vite-plus --framework react --start `npm create void ` takes a single directory name and creates it inside the current directory. Use up to 63 characters from `a-z`, `0-9`, and `-`, with a letter or digit at each end. -For non-interactive scaffolding, choose `--deploy none` and run `void connect` later to sign in. +When stdin is not a terminal, init ignores piped answers and keeps existing database settings. For full init, pass `--deploy` unless the project already has a saved deployment target. Use `--deploy none` for local setup, or run `void connect --no-login` before choosing a Void platform. + +Use a terminal to add demo code through init. For a supported deployment target, see [GitHub Actions deployment](../../guide/deployment.md#github). To associate your app with a Void platform project, see [project linking](./project.md#void-project-link-name). Vite+ is the recommended toolchain. Vite+ starters include [`@cloudflare/oxlint-config`](https://github.com/cloudflare/oxlint-config). Run `vp lint` to check your code. diff --git a/packages/void/src/cli/deploy-setup.ts b/packages/void/src/cli/deploy-setup.ts index 67efa2ab2..0db0869aa 100644 --- a/packages/void/src/cli/deploy-setup.ts +++ b/packages/void/src/cli/deploy-setup.ts @@ -13,6 +13,12 @@ export async function maybeSetupDeployProject(root: string): Promise`.', + ); + return null; + } const existingToken = getToken(root); const shouldSetup = await confirm({ diff --git a/packages/void/src/cli/init.ts b/packages/void/src/cli/init.ts index 742d48a61..0fd461b02 100644 --- a/packages/void/src/cli/init.ts +++ b/packages/void/src/cli/init.ts @@ -638,6 +638,11 @@ async function resolveInitRoot(root: string): Promise { if (!shouldPromptForInitLocation(root)) { return root; } + if (!process.stdin.isTTY) { + throw new Error( + 'init: Run from the app root or an empty directory, or use a terminal to choose a project folder.', + ); + } const choice = await select({ message: 'This folder is not empty. Where should Void initialize?', @@ -1385,6 +1390,7 @@ async function askDeploymentPlatform( export async function ensureVoidPlatformConnection( root: string, + activate = true, ): Promise { let selectedApiUrl: string | null = null; let promptedForPlatform = false; @@ -1399,6 +1405,11 @@ export async function ensureVoidPlatformConnection( // A genuinely new user must identify the company platform before login. } if (!selectedApiUrl) { + if (!process.stdin.isTTY) { + throw new Error( + 'init: Run `void connect --no-login` before choosing Void, or pass `--deploy none`.', + ); + } promptedForPlatform = true; const value = await text({ message: 'Void platform API URL:', @@ -1411,7 +1422,9 @@ export async function ensureVoidPlatformConnection( selectedApiUrl = String(value); } const discovery = await discoverPlatform(selectedApiUrl); - saveDiscoveredPlatform(discovery); + if (activate) { + saveDiscoveredPlatform(discovery); + } if (promptedForPlatform) { log.step(`Connected to ${discovery.displayName} at ${formatUrl(discovery.apiUrl)}.`); } @@ -1420,7 +1433,7 @@ export async function ensureVoidPlatformConnection( async function setupCloudflareDeployment(root: string): Promise { try { - await connectCloudflare(root, true); + await connectCloudflare(root); } catch (error) { log.warn(error instanceof Error ? error.message : String(error)); note( @@ -2532,10 +2545,33 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise async function runInitSteps(root: string, report: InitReport, initArgs?: InitArgs): Promise { const targeted = Boolean(initArgs && (initArgs.tsconfig || initArgs.github)); + const interactive = process.stdin.isTTY; const requestedRoot = root; if (!targeted) { root = await resolveInitRoot(root); } + const workspaceSubpackage = isInsideWorkspaceSubpackage(root); + if (workspaceSubpackage && initArgs?.git !== undefined) { + throw new Error( + 'init: The --git/--no-git options are not available when adding a package to an existing monorepo.', + ); + } + let deploymentPlatform: DeploymentPlatform | null = null; + let voidPlatformDiscovery: PlatformDiscoveryDocument | null = null; + if (!targeted && !interactive) { + if (!detectFramework(root) && isScaffoldableEmptyProject(root)) { + await promptScaffoldToolchain(initArgs?.toolchain); + await promptScaffoldFramework(detectPagesFramework(root) ?? initArgs?.framework); + await promptStarterMode(initArgs?.starter); + } + deploymentPlatform = await askDeploymentPlatform( + root, + initArgs?.deploy ?? readDeploymentPlatform(root) ?? undefined, + ); + if (deploymentPlatform === 'void') { + voidPlatformDiscovery = await ensureVoidPlatformConnection(root, false); + } + } /** 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')); @@ -2558,12 +2594,6 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg ); report.next(`Commit ${new Intl.ListFormat('en').format(migrated)}`); } - const workspaceSubpackage = isInsideWorkspaceSubpackage(root); - if (workspaceSubpackage && initArgs?.git !== undefined) { - throw new Error( - 'init: The --git/--no-git options are not available when adding a package to an existing monorepo.', - ); - } // Say what init will do before its first question. `.git` is allowed in an // empty project, so detecting before `git init` gives the same result. const framework = detectFramework(root); @@ -2588,7 +2618,6 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg const detectedPagesFramework = detectPagesFramework(root); let scaffoldedPagesFramework: ScaffoldFramework | undefined; let scaffoldedStarterMode: Exclude | undefined; - let starterDeploymentPlatform: DeploymentPlatform | undefined; let didScaffoldStarter = false; let scaffoldAddedDependencies = false; let workspaceSubpackageSkip = false; @@ -2606,7 +2635,7 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg const starterMode = await promptStarterMode(initArgs?.starter); // A partial starter takes the existing-project path on retry, so ask every // question before creating its files. The deployment choice is saved below. - starterDeploymentPlatform = await askDeploymentPlatform(root, initArgs?.deploy); + deploymentPlatform ??= await askDeploymentPlatform(root, initArgs?.deploy); const existingPackageJson = readPackageJson(root); const hasPackageManager = hasLocalLockfile(root) || @@ -2702,7 +2731,7 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg migrateFrameworkAdapterPaths(root); } - if (!targeted && !didScaffoldStarter) { + if (!targeted && !didScaffoldStarter && interactive) { applyDatabaseSetup(root, await promptDatabaseSetup(root), report); } @@ -2729,6 +2758,8 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg } else if (existingDemoFiles.length > 0) { const names = existingDemoFiles.map((file) => relative(root, file)).join(', '); log.info(`Project already has ${names}, skipping demo`); + } else if (!interactive) { + log.info('Run `void init` in a terminal to scaffold demo code.'); } else { const scaffold = await confirm({ message: 'Scaffold demo code? (migration + API route + frontend fetch)', @@ -2758,22 +2789,19 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg } } - let deploymentPlatform: DeploymentPlatform | null; if (targeted) { // Targeted runs keep the saved deployment preference without prompting. deploymentPlatform = readDeploymentPlatform(root); } else { - deploymentPlatform = - starterDeploymentPlatform ?? (await askDeploymentPlatform(root, initArgs?.deploy)); + deploymentPlatform ??= await askDeploymentPlatform(root, initArgs?.deploy); writeDeploymentPlatform(root, deploymentPlatform); } - let voidPlatformDiscovery: PlatformDiscoveryDocument | null = null; if (!targeted && deploymentPlatform === 'cloudflare') { await setupCloudflareDeployment(root); } if (!targeted && deploymentPlatform === 'void') { - voidPlatformDiscovery = await ensureVoidPlatformConnection(root); + voidPlatformDiscovery ??= await ensureVoidPlatformConnection(root); } // GitHub reads workflows only from the repository root, so skip every @@ -2808,6 +2836,12 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg deploymentPlatform === 'cloudflare' ? 'cloudflare' : 'void', voidPlatformDiscovery?.apiUrl, ); + } else if (!interactive) { + if (!existsSync(join(root, WORKFLOW_FILE))) { + const url = process.env.VOID_API_URL && voidPlatformDiscovery?.apiUrl; + const prefix = url ? `VOID_API_URL=${quoteShellArgument(url)} ` : ''; + log.info(`Run \`${prefix}void init --github\` to set up GitHub Actions.`); + } } else { const setupGha = await confirm({ message: 'Create .github/workflows/void-deploy.yml to deploy on pushes to main?', @@ -2890,6 +2924,9 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg if (gitInitialized) { report.next(`Git (optional): ${initialCommitCommand(root)}`); } + if (!targeted && !interactive && voidPlatformDiscovery) { + saveDiscoveredPlatform(voidPlatformDiscovery); + } report.print(targeted); if (workspaceSubpackageSkip) { diff --git a/packages/void/test/unit/init-stdin.test.ts b/packages/void/test/unit/init-stdin.test.ts new file mode 100644 index 000000000..cad6608c3 --- /dev/null +++ b/packages/void/test/unit/init-stdin.test.ts @@ -0,0 +1,315 @@ +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { + existsSync, + mkdirSync, + readFileSync, + readdirSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { createServer } from 'node:http'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import type { PlatformDiscoveryDocument } from '@void/platform'; +import { expect, it } from 'vite-plus/test'; +import { savePlatformConnection } from '../../src/cli/platform-registry.ts'; +import { listen, systemEnv, temporaryDirectory } from '../helpers/cloudflare-operation-process.ts'; +import { platformDiscoveryResponse } from '../helpers/platform-discovery.ts'; + +const sdk = fileURLToPath(new URL('../..', import.meta.url)); +const cli = join(sdk, 'dist/cli/cli.mjs'); + +function project(): string { + const root = join(temporaryDirectory('void-init-stdin-'), 'app'); + mkdirSync(root); + return root; +} + +async function init(root: string, args: Array, overrides: NodeJS.ProcessEnv = {}) { + const child = spawn(process.execPath, [cli, 'init', ...args], { + cwd: root, + env: { + ...systemEnv, + CI: '1', + HOME: dirname(root), + USERPROFILE: dirname(root), + VOID_PLATFORM_REGISTRY_DIR: join(dirname(root), 'registry'), + ...overrides, + }, + stdio: ['ignore', 'pipe', 'pipe'], + timeout: 10_000, + }); + let output = ''; + for (const stream of [child.stdout, child.stderr]) { + stream.setEncoding('utf8').on('data', (chunk: string) => { + output += chunk; + }); + } + const [status] = (await once(child, 'close')) as [number | null]; + return { status, output }; +} + +function existingProject(root: string): void { + mkdirSync(join(root, 'node_modules')); + symlinkSync(sdk, join(root, 'node_modules/void'), 'junction'); + writeFileSync( + join(root, 'package.json'), + JSON.stringify({ + name: 'init-stdin-test', + type: 'module', + devDependencies: { void: '*', vite: '*' }, + }), + ); +} + +function savePlatform(apiUrl: string, registry: string) { + return savePlatformConnection( + { + accountId: null, + apiUrl, + applicationDomain: 'void.app', + displayName: new URL(apiUrl).host, + installationId: null, + kind: 'connected', + proxyUrl: apiUrl, + }, + registry, + ); +} + +async function servePlatform(): Promise { + let discovery = ''; + const origin = await listen( + createServer((_, response) => { + response.writeHead(200, { 'Content-Type': 'application/json' }).end(discovery); + }), + ); + const document = await platformDiscoveryResponse(origin).json(); + discovery = JSON.stringify({ + ...document, + capabilities: { ...document.capabilities, githubActions: true }, + }); + return origin; +} + +const starter = ['--toolchain', 'vite', '--framework', 'react', '--starter', 'sqlite']; + +it.each([ + ['toolchain', []], + ['framework', starter.slice(0, 2)], + ['starter', starter.slice(0, 4)], + ['deploy', starter], +] as const)('requires --%s before Git init when stdin is closed', async (flag, args) => { + const root = project(); + const { status, output } = await init(root, ['--git', ...args]); + expect(output).toContain(`Pass --${flag}`); + expect(status).toBe(1); + expect(readdirSync(root)).toEqual([]); +}); + +it('rejects an ambiguous project folder before writes when stdin is closed', async () => { + const root = project(); + const notes = join(root, 'notes.txt'); + writeFileSync(notes, 'Keep these notes.\n'); + const { status, output } = await init(root, ['--no-git', '--deploy', 'none']); + expect(status, output).toBe(1); + expect(output).toContain('empty directory'); + expect(readdirSync(root)).toEqual(['notes.txt']); + expect(readFileSync(notes, 'utf8')).toBe('Keep these notes.\n'); +}); + +it('requires a Void platform connection before scaffolding', async () => { + const root = project(); + const { status, output } = await init(root, ['--no-git', ...starter, '--deploy', 'void']); + expect(status, output).toBe(1); + expect(output).toContain('void connect --no-login'); + expect(output).toContain('--deploy none'); + expect(readdirSync(root)).toEqual([]); +}); + +it('reports an unreadable registry before scaffolding', async () => { + const root = project(); + const registry = join(dirname(root), 'registry'); + mkdirSync(registry); + writeFileSync(join(registry, 'registry.json'), '{'); + const result = await init(root, ['--no-git', ...starter, '--deploy', 'void']); + expect(result.status, result.output).toBe(1); + expect(result.output).toContain('Could not read'); + expect(result.output).toContain('registry.json'); + expect(result.output).not.toContain('void connect'); + expect(readdirSync(root)).toEqual([]); +}); + +it.each([ + { workspace: false, message: 'HTTP 503' }, + { workspace: true, message: '--git/--no-git options are not available' }, +])('leaves a D1 starter untouched when init reports "$message"', async ({ workspace, message }) => { + const root = project(); + if (workspace) { + writeFileSync(join(dirname(root), 'package.json'), JSON.stringify({ workspaces: ['app'] })); + } + const paths: Array = []; + const apiUrl = await listen( + createServer((request, response) => { + paths.push(request.url); + response + .writeHead(503, { 'Content-Type': 'application/json' }) + .end('{"error":"Platform disabled"}'); + }), + ); + const registry = join(dirname(root), 'registry'); + savePlatform(apiUrl, registry); + savePlatform('https://other.example.test', registry); + const projectFile = JSON.stringify({ platform: 'void', platformUrl: apiUrl }); + mkdirSync(join(root, '.void')); + writeFileSync(join(root, '.void/project.json'), projectFile); + const before = new Set(readdirSync(root, { encoding: 'utf8', recursive: true })); + const result = await init(root, ['--no-git', ...starter, '--deploy', 'void']); + expect(result.status, result.output).toBe(1); + expect(result.output).toContain(message); + expect(paths).toEqual(workspace ? [] : ['/.well-known/void-platform']); + expect(new Set(readdirSync(root, { encoding: 'utf8', recursive: true }))).toEqual(before); + expect(readFileSync(join(root, '.void/project.json'), 'utf8')).toBe(projectFile); +}); + +it.each(['home', 'project'] as const)( + 'keeps the %s platform registry unchanged when local validation fails', + async (location) => { + const root = project(); + const registry = join(location === 'home' ? dirname(root) : root, '.void', 'platforms'); + const registryFile = join(registry, 'registry.json'); + const apiUrl = await servePlatform(); + savePlatform(apiUrl, registry); + savePlatform('https://other.example.test', registry); + const before = readFileSync(registryFile); + mkdirSync(join(root, '.void'), { recursive: true }); + writeFileSync( + join(root, '.void/project.json'), + JSON.stringify({ platform: 'void', platformUrl: apiUrl }), + ); + writeFileSync(join(root, 'package.json'), '{"name":"toml-app"}'); + writeFileSync(join(root, 'wrangler.toml'), 'name = "toml-app"\n'); + + const result = await init(root, ['--no-git', '--deploy', 'void'], { + VOID_PLATFORM_REGISTRY_DIR: location === 'project' ? registry : undefined, + }); + expect(result.status, result.output).toBe(1); + expect(result.output).toContain('Cloudflare tooling TOML is not supported'); + expect(readFileSync(registryFile)).toEqual(before); + }, +); + +it('keeps the selected Void platform in the headless workflow follow-up', async () => { + const root = project(); + existingProject(root); + const alpha = await servePlatform(); + const beta = await servePlatform(); + const registry = join(dirname(root), 'registry'); + const selected = savePlatform(alpha, registry); + savePlatform(beta, registry); + mkdirSync(join(root, '.void')); + const projectFile = join(root, '.void/project.json'); + writeFileSync(projectFile, JSON.stringify({ platform: 'void', platformUrl: beta })); + + const result = await init(root, ['--no-git', '--deploy', 'void'], { VOID_API_URL: alpha + '/' }); + expect(result.status, result.output).toBe(0); + expect(result.output).toContain(`VOID_API_URL=${alpha} void init --github`); + expect(result.output).toContain('void account login'); + expect(result.output).toContain('void project link '); + expect(readFileSync(projectFile, 'utf8')).toContain(`"platformUrl": "${beta}"`); + const workflow = join(root, '.github/workflows/void-deploy.yml'); + expect(existsSync(workflow)).toBe(false); + expect(readFileSync(join(registry, 'registry.json'), 'utf8')).toContain( + `"activeConnectionId": "${selected.id}"`, + ); + + const followUp = await init(root, ['--github'], { VOID_API_URL: alpha }); + expect(followUp.status, followUp.output).toBe(0); + expect(readFileSync(workflow, 'utf8')).toContain(alpha); +}); + +it.each([false, true])( + 'continues with multiple Cloudflare accounts, workflow present: %s', + async (hasWorkflow) => { + const root = project(); + existingProject(root); + const workflow = join(root, '.github/workflows/void-deploy.yml'); + const workflowText = 'name: Existing deployment\n'; + if (hasWorkflow) { + mkdirSync(dirname(workflow), { recursive: true }); + writeFileSync(workflow, workflowText); + } + const id = '1'.repeat(32); + const responses: Record = { + '/client/v4/accounts': [ + { id, name: 'First' }, + { id: '2'.repeat(32), name: 'Second' }, + ], + '/client/v4/user/tokens/verify': { id, status: 'active' }, + '/client/v4/user': { id, email: 'mock@example.test' }, + }; + const url = await listen( + createServer((request, response) => { + const result = responses[request.url?.split('?')[0] ?? '']; + if (!result) { + response + .writeHead(404, { 'Content-Type': 'application/json' }) + .end( + '{"success":false,"errors":[{"code":10000,"message":"Unexpected path in probe"}]}', + ); + return; + } + response.writeHead(200, { 'Content-Type': 'application/json' }).end( + JSON.stringify({ + success: true, + result, + result_info: { + page: 1, + per_page: 50, + total_pages: 1, + count: Array.isArray(result) ? result.length : 1, + total_count: Array.isArray(result) ? result.length : 1, + }, + }), + ); + }), + ); + const result = await init(root, ['--no-git', '--deploy', 'cloudflare'], { + CLOUDFLARE_API_BASE_URL: url + '/client/v4', + CLOUDFLARE_API_TOKEN: 'synthetic-token', + }); + expect(result.status, result.output).toBe(0); + expect(result.output).toContain('Multiple Cloudflare accounts are available'); + expect(result.output).toContain('CLOUDFLARE_ACCOUNT_ID'); + expect(result.output.includes('void init --github')).toBe(!hasWorkflow); + if (hasWorkflow) { + expect(readFileSync(workflow, 'utf8')).toBe(workflowText); + } + }, +); + +it.each([ + ['the saved target', 'none', []], + ['an explicit target', 'void', ['--deploy', 'none']], +] as const)( + 'keeps authored SQLite configuration with %s and closed stdin', + async (_, saved, args) => { + const root = project(); + existingProject(root); + const configPath = join(root, 'void.config.ts'); + const config = + 'export default { database: { dialect: "sqlite", casing: "camelCase" }, compatibilityDate: "2026-01-01" };\n'; + writeFileSync(configPath, config); + mkdirSync(join(root, '.void')); + writeFileSync(join(root, '.void/project.json'), JSON.stringify({ platform: saved })); + const { status, output } = await init(root, ['--toolchain', 'vite', '--no-git', ...args]); + expect(status, output).toBe(0); + expect(readFileSync(configPath, 'utf8')).toBe(config); + expect(readdirSync(root)).not.toContain('db'); + expect(output).toContain('in a terminal to scaffold demo code'); + expect(JSON.parse(readFileSync(join(root, '.void/project.json'), 'utf8'))).toEqual({ + platform: 'none', + }); + }, +);