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
27 changes: 3 additions & 24 deletions packages/create-void/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
import * as p from '@voidzero-dev/vite-plus-prompts';
import { resolve } from 'pathslash';
import pc from 'picocolors';
import { parseCreateArgs, validateProjectName } from './args.ts';
import { detectPM, pmExec, pmInstall, run, writePnpmBuildPolicy } from './pm.ts';
import { detectPM, runVoidInit } from './pm.ts';

const pm = detectPM();

Expand Down Expand Up @@ -50,29 +50,8 @@ async function main() {

mkdirSync(targetDir, { recursive: true });

const pkg = {
name: appName,
private: true,
type: 'module',
devDependencies: {
void: voidVersion,
},
};

writeFileSync(resolve(targetDir, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');
// pnpm 12 fails the first install when a dependency has an unapproved build
// script. Write Void's narrow policy before installing the CLI so a fresh
// project can bootstrap without disabling pnpm's build-script protection.
writePnpmBuildPolicy(targetDir, pm);

p.log.step('Installing Void...');
await run(pmInstall(pm), targetDir);

p.log.step('Scaffolding starter...');
await run([...pmExec(pm), 'void', 'init', ...createArgs.initArgs], targetDir);

p.log.step('Installing starter dependencies...');
await run(pmInstall(pm), targetDir);
await runVoidInit(pm, voidVersion, createArgs.initArgs, targetDir);

p.outro(`\n${pc.green(`✓ Created ${appName}`)}`, { withGuide: false });
p.outro(`cd ${appName} && ${pm === 'npm' ? 'npm run' : pm} dev`);
Expand Down
56 changes: 39 additions & 17 deletions packages/create-void/src/pm.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,7 @@
import { spawn } from 'node:child_process';
import { writeFileSync } from 'node:fs';
import { join } from 'pathslash';

export type PM = 'npm' | 'pnpm' | 'yarn' | 'bun';

const VOID_PNPM_ALLOWED_BUILDS = ['esbuild', 'sharp', 'workerd'] as const;

/** Write the explicit build-script policy required by a new pnpm project. */
export function writePnpmBuildPolicy(root: string, pm: PM): void {
if (pm !== 'pnpm') {
return;
}
writeFileSync(
join(root, 'pnpm-workspace.yaml'),
// better-sqlite3 13 ships Node-API binaries and declares gypfile:false.
// Match the repository policy instead of invoking pnpm's implicit rebuild.
`allowBuilds:\n better-sqlite3: false\n${VOID_PNPM_ALLOWED_BUILDS.map((name) => ` ${name}: true`).join('\n')}\n`,
);
}

export function detectPM(): PM {
const agent = process.env.npm_config_user_agent;
if (agent) {
Expand Down Expand Up @@ -54,6 +37,45 @@ export function pmExec(pm: PM): ReadonlyArray<string> {
}
}

function isYarnClassic(userAgent = process.env.npm_config_user_agent): boolean {
return /^yarn\/1(?:\.|$)/.test(userAgent ?? '');
}

/** Run the matching Void CLI without adding it to the generated project. */
export function pmDlx(pm: PM, version: string): ReadonlyArray<string> {
const pkg = `void@${version}`;
switch (isYarnClassic() ? 'npm' : pm) {
case 'npm':
return ['npm', 'exec', '--yes', `--package=${pkg}`, '--', 'void'];
case 'pnpm':
return ['pnpm', 'dlx', pkg];
case 'yarn':
return ['yarn', 'dlx', pkg];
case 'bun':
return ['bunx', pkg];
}
}

export function pmInitCommand(
pm: PM,
version: string,
initArgs: ReadonlyArray<string>,
): ReadonlyArray<string> {
return [...pmDlx(pm, version), 'init', ...initArgs];
}

export type InitCommandRunner = (argv: ReadonlyArray<string>, cwd?: string) => Promise<void>;

export function runVoidInit(
pm: PM,
version: string,
initArgs: ReadonlyArray<string>,
cwd: string,
runner: InitCommandRunner = run,
): Promise<void> {
return runner(pmInitCommand(pm, version, initArgs), cwd);
}

export function run(argv: ReadonlyArray<string>, cwd?: string): Promise<void> {
return new Promise((resolve, reject) => {
const [cmd, ...args] = argv;
Expand Down
90 changes: 90 additions & 0 deletions packages/create-void/test/unit/delegation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vite-plus/test';
import { parseInitArgs, runInitCommand } from '../../../void/src/cli/init.ts';
import { runVoidInit } from '../../src/pm.ts';

const VOID_VERSION = JSON.parse(
readFileSync(join(import.meta.dirname, '..', '..', 'package.json'), 'utf8'),
) as { version: string };

describe('create-void delegation', () => {
it('delegates to void init in a pnpm workspace member and forwards --no-install', async () => {
const root = mkdtempSync(join(tmpdir(), 'create-void-workspace-'));
try {
const appDirectory = join(root, 'apps', 'my-app');
mkdirSync(appDirectory, { recursive: true });
writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'fixture', private: true }));
writeFileSync(
join(root, 'pnpm-workspace.yaml'),
[
'# Keep this workspace comment',
'packages:',
' - apps/*',
'allowBuilds:',
' esbuild: false # Keep this approval decision',
' custom-build: true',
'',
].join('\n'),
);

let invoked = false;
await runVoidInit(
'pnpm',
VOID_VERSION.version,
[
'--toolchain',
'vite',
'--framework',
'react',
'--starter',
'static',
'--deploy',
'none',
'--no-install',
],
appDirectory,
async (argv, cwd) => {
invoked = true;
expect(argv).toEqual([
'pnpm',
'dlx',
`void@${VOID_VERSION.version}`,
'init',
'--toolchain',
'vite',
'--framework',
'react',
'--starter',
'static',
'--deploy',
'none',
'--no-install',
]);
expect(cwd).toBe(appDirectory);
await runInitCommand(cwd!, parseInitArgs(argv.slice(4)));
},
);
expect(invoked).toBe(true);

expect(existsSync(join(appDirectory, 'package.json'))).toBe(true);
expect(existsSync(join(appDirectory, 'pages', 'index.tsx'))).toBe(true);
expect(existsSync(join(appDirectory, 'pnpm-workspace.yaml'))).toBe(false);
expect(existsSync(join(appDirectory, 'pnpm-lock.yaml'))).toBe(false);
expect(existsSync(join(appDirectory, 'package-lock.json'))).toBe(false);
expect(existsSync(join(appDirectory, 'node_modules'))).toBe(false);

const updatedWorkspaceConfig = readFileSync(join(root, 'pnpm-workspace.yaml'), 'utf8');
expect(updatedWorkspaceConfig).toContain('# Keep this workspace comment');
expect(updatedWorkspaceConfig).toContain('esbuild: false # Keep this approval decision');
expect(updatedWorkspaceConfig).toContain('custom-build: true');
expect(updatedWorkspaceConfig).toContain('better-sqlite3: false');
expect(updatedWorkspaceConfig).toContain('sharp: true');
expect(updatedWorkspaceConfig).toContain('workerd: true');
expect(existsSync(join(root, 'pnpm-lock.yaml'))).toBe(false);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});
96 changes: 68 additions & 28 deletions packages/create-void/test/unit/pm.test.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,77 @@
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it } from 'vite-plus/test';
import { writePnpmBuildPolicy } from '../../src/pm.ts';

const temporaryDirectories: Array<string> = [];

afterEach(() => {
for (const directory of temporaryDirectories.splice(0)) {
rmSync(directory, { recursive: true, force: true });
}
});
import { afterEach, describe, expect, it, vi } from 'vite-plus/test';
import { detectPM, pmDlx, pmInitCommand } from '../../src/pm.ts';

describe('create-void package manager bootstrap', () => {
it('writes the narrow Void build policy before a fresh pnpm install', () => {
const root = mkdtempSync(join(tmpdir(), 'create-void-pnpm-'));
temporaryDirectories.push(root);
describe('create-void package manager delegation', () => {
afterEach(() => vi.unstubAllEnvs());

writePnpmBuildPolicy(root, 'pnpm');
it.each([
['npm', ['npm', 'exec', '--yes', '--package=void@1.2.3', '--', 'void']],
['pnpm', ['pnpm', 'dlx', 'void@1.2.3']],
['yarn', ['yarn', 'dlx', 'void@1.2.3']],
['bun', ['bunx', 'void@1.2.3']],
] as const)('uses %s to execute the requested Void version', (pm, expected) => {
vi.stubEnv('npm_config_user_agent', '');
expect(pmDlx(pm, '1.2.3')).toEqual(expected);
});

expect(readFileSync(join(root, 'pnpm-workspace.yaml'), 'utf-8')).toBe(
'allowBuilds:\n better-sqlite3: false\n esbuild: true\n sharp: true\n workerd: true\n',
);
it('uses npm exec for Yarn Classic, which does not provide dlx', () => {
vi.stubEnv('npm_config_user_agent', 'yarn/1.22.22 npm/? node/v24.22.1');
expect(pmDlx('yarn', '1.2.3')).toEqual([
'npm',
'exec',
'--yes',
'--package=void@1.2.3',
'--',
'void',
]);
});

it('does not add pnpm policy files for other package managers', () => {
for (const manager of ['npm', 'yarn', 'bun'] as const) {
const root = mkdtempSync(join(tmpdir(), `create-void-${manager}-`));
temporaryDirectories.push(root);
it.each([
['npm', ['npm', 'exec', '--yes', '--package=void@1.2.3', '--', 'void', 'init']],
['pnpm', ['pnpm', 'dlx', 'void@1.2.3', 'init']],
['yarn', ['yarn', 'dlx', 'void@1.2.3', 'init']],
['bun', ['bunx', 'void@1.2.3', 'init']],
] as const)('builds the %s void init command', (pm, expected) => {
vi.stubEnv('npm_config_user_agent', '');
expect(pmInitCommand(pm, '1.2.3', [])).toEqual(expected);
});

writePnpmBuildPolicy(root, manager);
it('uses npm exec for void init under Yarn Classic', () => {
vi.stubEnv('npm_config_user_agent', 'yarn/1.22.22 npm/? node/v24.22.1');
expect(pmInitCommand('yarn', '1.2.3', ['--no-install'])).toEqual([
'npm',
'exec',
'--yes',
'--package=void@1.2.3',
'--',
'void',
'init',
'--no-install',
]);
});

it('forwards init options, including --no-install, without adding a package install', () => {
const command = pmInitCommand('pnpm', '1.2.3', ['--framework', 'react', '--no-install']);

expect(command).toEqual([
'pnpm',
'dlx',
'void@1.2.3',
'init',
'--framework',
'react',
'--no-install',
]);
expect(command).not.toContain('install');
});

expect(existsSync(join(root, 'pnpm-workspace.yaml'))).toBe(false);
}
it.each([
['pnpm/10.0.0 npm/? node/v24.22.1', 'pnpm'],
['npm/11.0.0 node/v24.22.1', 'npm'],
['yarn/4.5.0 npm/? node/v24.22.1', 'yarn'],
['bun/1.2.0', 'bun'],
] as const)('detects %s from npm_config_user_agent', (userAgent, expected) => {
vi.stubEnv('npm_config_user_agent', userAgent);
expect(detectPM()).toBe(expected);
});
});
1 change: 1 addition & 0 deletions packages/void/src/cli/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ const HELP_TREE: HelpTree = {
usage: ['void init [options]'],
options: [
{ command: '--tsconfig', description: 'Update tsconfig.json and set up coding agents' },
{ command: '--no-install', description: 'Skip installing dependencies after setup' },
{ command: '--git', description: 'Initialize a Git repository without prompting' },
{ command: '--no-git', description: 'Skip Git repository initialization' },
{ command: '--toolchain <name>', description: 'Scaffold with vite-plus or vite' },
Expand Down
20 changes: 17 additions & 3 deletions packages/void/src/cli/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ import {
export type InitArgs = {
tsconfig: boolean;
github: boolean;
install?: boolean;
git?: boolean;
toolchain?: ScaffoldToolchain;
framework?: ScaffoldFramework;
Expand Down Expand Up @@ -116,6 +117,7 @@ export function parseInitArgs(args: Array<string>): InitArgs {
options: {
tsconfig: { type: 'boolean' },
github: { type: 'boolean' },
install: { type: 'boolean' },
git: { type: 'boolean' },
toolchain: { type: 'string' },
framework: { type: 'string' },
Expand All @@ -133,6 +135,7 @@ export function parseInitArgs(args: Array<string>): InitArgs {
return {
tsconfig: parsed.values.tsconfig === true,
github: parsed.values.github === true,
install: parsed.values.install as boolean | undefined,
git: parsed.values.git as boolean | undefined,
toolchain: parseChoice(
'toolchain',
Expand Down Expand Up @@ -3155,7 +3158,14 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg
: './node_modules/.bin/void'
: projectVoidRunner[state.packageManager];
const manualMigration = `${voidRunner} db generate`;
if (scaffoldAddedDependencies) {
if (scaffoldAddedDependencies && initArgs?.install === false) {
const install = resolveProjectInstall(root, state.packageManager);
const manualInstall = commandInProject(root, install.manualCommand);
report.next(`Run \`${manualInstall}\` to install dependencies`);
if (migrationMode) {
report.next(`Then run \`${commandInProject(root, manualMigration)}\` to finish setup`);
}
} else if (scaffoldAddedDependencies) {
const install = resolveProjectInstall(root, state.packageManager);
const manualInstall = commandInProject(root, install.manualCommand);
report.unfinished = migrationMode
Expand All @@ -3169,7 +3179,7 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg
const manualInstall = commandInProject(root, `${installer} install`);
report.next(`Run \`${manualInstall}\` to update your lockfile`);
}
if (migrationMode) {
if (migrationMode && initArgs?.install !== false) {
report.unfinished = `Run \`${commandInProject(root, manualMigration)}\` to finish setup`;
await generateStarterMigration(root, migrationMode);
report.done('Generated the initial database migration');
Expand Down Expand Up @@ -3200,6 +3210,10 @@ async function runInitSteps(root: string, report: InitReport, initArgs?: InitArg
}
} else {
const devCommand = commandInProject(root, getDevCommand(root, framework));
printSuccess(`Project initialized. Run \`${devCommand}\` to start developing.`);
printSuccess(
initArgs?.install === false && scaffoldAddedDependencies
? 'Project initialized. Follow the next steps to finish setup.'
: `Project initialized. Run \`${devCommand}\` to start developing.`,
);
}
}
Loading