Skip to content
Merged
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
4 changes: 2 additions & 2 deletions docs/guide/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ const dbFileItems = [
name: "migrations/",
description: "Generated SQL migration files",
children: [
{ name: "0000_initial.sql" },
{ name: "0000_*.sql" },
{ name: "0001_add_posts.sql" },
],
},
{ name: "seed.ts", description: "Seed script (optional)" },
{ name: "seed.sql", description: "Seed SQL for local development (optional)" },
],
},
]
Expand Down
2 changes: 1 addition & 1 deletion docs/guide/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ Your `package.json` will then contain an alias like:

In an empty directory, `void init` adds the matching Pages adapter and starter dependencies after you choose a framework. Use the same alias pattern for `@void/react`, `@void/vue`, `@void/svelte`, `@void/solid`, and `@void/md` when you add them manually later.

As part of `void init`, you'll choose a Pages framework (React, Vue, Svelte, or Solid) and a starter type. D1 is the default top option and scaffolds a DB-backed page loader, schema, migration, and API route. PostgreSQL scaffolds the same starter and writes `"database": "pg"` to `void.json`. Static Pages skips the database and server starter files so you can start with static content and add Void features later.
As part of `void init`, you'll choose a Pages framework (React, Vue, Svelte, or Solid) and a starter type. D1 is the default top option and scaffolds a DB-backed page loader, schema, generated migration, `db/seed.sql`, and API route. PostgreSQL scaffolds the same starter and writes `"database": "pg"` to `void.json`. Static Pages skips the database and server starter files so you can start with static content and add Void features later.

After installation, run the setup flow:

Expand Down
2 changes: 1 addition & 1 deletion docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ void init [--tsconfig] [--github] [--agents]

Setup wizard for void projects (new or existing).

If run in a scaffoldable empty directory, `void init` scaffolds a Pages starter. If a single Pages adapter is already installed, it reuses that framework; otherwise it asks which framework to scaffold (React, Vue, Svelte, or Solid). It then asks which starter you want: D1, PostgreSQL, or Static Pages. The D1 and PostgreSQL starters write a framework-specific `vite.config.ts`, a `pages/` home page plus `.server.ts` loader, `db/schema.ts`, `db/migrations/0000_initial.sql`, and `routes/api/hello.ts`. The Static Pages starter writes just the framework-specific `vite.config.ts` and a `pages/` home page so you can add server features later.
If run in a scaffoldable empty directory, `void init` scaffolds a Pages starter. If a single Pages adapter is already installed, it reuses that framework; otherwise it asks which framework to scaffold (React, Vue, Svelte, or Solid). It then asks which starter you want: D1, PostgreSQL, or Static Pages. The D1 and PostgreSQL starters write a framework-specific `vite.config.ts`, a `pages/` home page plus `.server.ts` loader, `db/schema.ts`, `db/seed.sql`, a generated initial migration under `db/migrations/`, and `routes/api/hello.ts`. The Static Pages starter writes just the framework-specific `vite.config.ts` and a `pages/` home page so you can add server features later.

After that, the full interactive flow walks through:

Expand Down
49 changes: 47 additions & 2 deletions packages/void/src/cli/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ import {
} from "node:fs";
import { spawnSync } from "node:child_process";
import { basename, dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { parse, type ParseError } from "jsonc-parser";
import { parseArgs } from "node:util";
import { intro, outro, log, confirm, isCancel, cancel, note, select } from "@clack/prompts";
import { ensureProjectTsconfig } from "../codegen/project-tsconfig";
import { getDatabaseDialect, readConfig, type DatabaseDialect } from "../config";
import { writeDrizzleConfig } from "../drizzle/config";
import { detectFramework, type DetectedFramework } from "../plugin-inference";
import {
createPagesStarterTemplate,
Expand Down Expand Up @@ -104,6 +106,7 @@ const EMPTY_PROJECT_ALLOWED_ENTRIES = new Set([
]);

const PNPM_ONLY_BUILT_DEPENDENCIES = ["better-sqlite3", "esbuild", "workerd"] as const;
const drizzleKitBin = join(fileURLToPath(import.meta.resolve("drizzle-kit")), "..", "bin.cjs");

const EMPTY_PROJECT_ALLOWED_PACKAGES = new Set([
"void",
Expand Down Expand Up @@ -593,12 +596,12 @@ async function promptStarterMode(): Promise<ScaffoldStarterMode> {
{
value: "sqlite",
label: "D1 (SQLite)",
hint: "Recommended starter. Scaffolds a DB-backed page, schema, migration, and API route.",
hint: "Recommended starter. Scaffolds a DB-backed page, schema, generated migration, seed file, and API route.",
},
{
value: "postgresql",
label: "PostgreSQL",
hint: 'Scaffolds the same starter with PostgreSQL and writes "database": "pg" to void.json.',
hint: 'Scaffolds the same starter with PostgreSQL, a generated migration, a seed file, and writes "database": "pg" to void.json.',
},
{
value: "static",
Expand Down Expand Up @@ -864,6 +867,41 @@ function installProjectDependencies(
log.success(`Installed dependencies with ${packageManager}`);
}

export function generateStarterMigration(
root: string,
starterMode: Exclude<ScaffoldStarterMode, "static">,
): void {
const dialect = starterMode === "postgresql" ? "postgresql" : "sqlite";
const configPath = writeDrizzleConfig(
root,
dialect === "postgresql" ? "postgresql://dummy" : ":memory:",
dialect,
);

log.step("Generating initial Drizzle migration");
const result = spawnSync(process.execPath, [drizzleKitBin, "generate", "--config", configPath], {
cwd: root,
stdio: "pipe",
encoding: "utf-8",
shell: process.platform === "win32",
});

if (result.error) {
throw result.error;
}

if (result.status !== 0) {
const detail = [result.stderr, result.stdout].filter(Boolean).join("\n").trim();
throw new Error(
["Failed to generate the starter database migration.", ...(detail ? [detail] : [])].join(
"\n\n",
),
);
}

log.success("Generated initial Drizzle migration");
}

function scaffoldPagesApp(
root: string,
packageManager: ProjectState["packageManager"],
Expand Down Expand Up @@ -1261,6 +1299,7 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise
const preScaffoldState = detectProjectState(root);
const detectedPagesFramework = detectPagesFramework(root);
let scaffoldedPagesFramework: ScaffoldFramework | undefined;
let scaffoldedStarterMode: Exclude<ScaffoldStarterMode, "static"> | undefined;
let didScaffoldStarter = false;
let scaffoldAddedDependencies = false;

Expand All @@ -1285,6 +1324,9 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise
scaffoldedPagesFramework,
starterMode,
);
if (starterMode !== "static") {
scaffoldedStarterMode = starterMode;
}
didScaffoldStarter = true;
}

Expand Down Expand Up @@ -1381,6 +1423,9 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise
if (scaffoldAddedDependencies) {
installProjectDependencies(root, state.packageManager);
}
if (scaffoldedStarterMode) {
generateStarterMigration(root, scaffoldedStarterMode);
}

outro(`Run \`${getDevCommand(root, framework)}\` to start developing`);
}
103 changes: 56 additions & 47 deletions packages/void/src/cli/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export function createPagesStarterTemplate(options: {
files["pages/index.server.ts"] = getIndexServer();
files["routes/api/hello.ts"] = getHelloRoute(config.label, starterMode);
files["db/schema.ts"] = getSchemaFile(starterMode);
files["db/migrations/0000_initial.sql"] = getMigrationFile(starterMode);
files["db/seed.sql"] = getSeedFile();
}

return {
Expand Down Expand Up @@ -243,24 +243,8 @@ export const messages = sqliteTable("messages", {
`;
}

function getMigrationFile(starterMode: Exclude<ScaffoldStarterMode, "static">): string {
if (starterMode === "postgresql") {
return `CREATE TABLE IF NOT EXISTS messages (
id SERIAL PRIMARY KEY,
text TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT now()
);

INSERT INTO messages (text) VALUES ('Hello from Void');
`;
}

return `CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

function getSeedFile(): string {
return `-- Seed starter content for local development.
INSERT INTO messages (text) VALUES ('Hello from Void');
`;
}
Expand Down Expand Up @@ -336,15 +320,22 @@ export default function HomePage({ messages }: Props) {
<p>
API example: <a href="/api/hello">/api/hello</a>
</p>
<ul>
{messages.map((message) => (
<li key={message.id}>
<strong>{message.text}</strong>
<br />
<small>{String(message.createdAt)}</small>
</li>
))}
</ul>
{messages.length === 0 ? (
<p>
No messages yet. Run <code>void db seed</code> to load the sample row from
<code> db/seed.sql</code>.
</p>
) : (
<ul>
{messages.map((message) => (
<li key={message.id}>
<strong>{message.text}</strong>
<br />
<small>{String(message.createdAt)}</small>
</li>
))}
</ul>
)}
</main>
);
}
Expand All @@ -366,7 +357,11 @@ defineProps<Props>();
<p>
API example: <a href="/api/hello">/api/hello</a>
</p>
<ul>
<p v-if="messages.length === 0">
No messages yet. Run <code>void db seed</code> to load the sample row from
<code>db/seed.sql</code>.
</p>
<ul v-else>
<li v-for="message in messages" :key="message.id">
<strong>{{ message.text }}</strong>
<br />
Expand All @@ -392,15 +387,22 @@ defineProps<Props>();
<p>
API example: <a href="/api/hello">/api/hello</a>
</p>
<ul>
{#each messages as message (message.id)}
<li>
<strong>{message.text}</strong>
<br />
<small>{String(message.createdAt)}</small>
</li>
{/each}
</ul>
{#if messages.length === 0}
<p>
No messages yet. Run <code>void db seed</code> to load the sample row from
<code>db/seed.sql</code>.
</p>
{:else}
<ul>
{#each messages as message (message.id)}
<li>
<strong>{message.text}</strong>
<br />
<small>{String(message.createdAt)}</small>
</li>
{/each}
</ul>
{/if}
</main>
`;
case "solid":
Expand All @@ -417,15 +419,22 @@ export default function HomePage(props: Props) {
<p>
API example: <a href="/api/hello">/api/hello</a>
</p>
<ul>
{props.messages.map((message) => (
<li>
<strong>{message.text}</strong>
<br />
<small>{String(message.createdAt)}</small>
</li>
))}
</ul>
{props.messages.length === 0 ? (
<p>
No messages yet. Run <code>void db seed</code> to load the sample row from
<code> db/seed.sql</code>.
</p>
) : (
<ul>
{props.messages.map((message) => (
<li>
<strong>{message.text}</strong>
<br />
<small>{String(message.createdAt)}</small>
</li>
))}
</ul>
)}
</main>
);
}
Expand Down
94 changes: 94 additions & 0 deletions packages/void/test/unit/init-starter-migrations.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import {
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it, vi } from "vitest";
import { hasDeploySchemaDrift } from "../../src/cli/deploy";
import { generateStarterMigration } from "../../src/cli/init";
import { createPagesStarterTemplate, type ScaffoldStarterMode } from "../../src/cli/template";

vi.mock("@clack/prompts", () => ({
intro: vi.fn(),
outro: vi.fn(),
note: vi.fn(),
cancel: vi.fn(),
confirm: vi.fn(),
isCancel: vi.fn(),
select: vi.fn(),
text: vi.fn(),
spinner: () => ({ start: vi.fn(), stop: vi.fn(), message: vi.fn() }),
log: { success: vi.fn(), warn: vi.fn(), error: vi.fn(), info: vi.fn(), step: vi.fn() },
}));

const packageRoot = fileURLToPath(new URL("../..", import.meta.url));
const tempDirs: string[] = [];

afterEach(() => {
while (tempDirs.length > 0) {
rmSync(tempDirs.pop()!, { recursive: true, force: true });
}
});

describe("starter migration generation", () => {
it("creates a sqlite starter migration that deploy sees as drift-free", () => {
const root = createStarterApp("sqlite");

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", () => {
const root = createStarterApp("postgresql");

generateStarterMigration(root, "postgresql");

expect(readSqlMigrations(root)).toHaveLength(1);
expect(existsSync(join(root, "db", "migrations", "meta", "_journal.json"))).toBe(true);
expect(hasDeploySchemaDrift(root, "postgresql")).toBe(false);
});
});

function createStarterApp(starterMode: Exclude<ScaffoldStarterMode, "static">): string {
const root = mkdtempSync(join(packageRoot, ".tmp-init-starter-"));
tempDirs.push(root);

const template = createPagesStarterTemplate({
framework: "react",
starterMode,
voidPackageSpec: "workspace:*",
adapterPackageSpec: "workspace:*",
});

for (const [filePath, content] of Object.entries(template.files)) {
const fullPath = join(root, filePath);
mkdirSync(fullPath.slice(0, fullPath.lastIndexOf("/")), { recursive: true });
writeFileSync(fullPath, content);
}

const nodeModulesDir = join(root, "node_modules");
mkdirSync(nodeModulesDir, { recursive: true });
symlinkSync(packageRoot, join(nodeModulesDir, "void"), "dir");

return root;
}

function readSqlMigrations(root: string): string[] {
const migrationsDir = join(root, "db", "migrations");
if (!existsSync(migrationsDir)) {
return [];
}

return readdirSync(migrationsDir)
.filter((entry) => entry.endsWith(".sql"))
.sort();
}
Loading
Loading