From 17e6c65c46d667b73ff711d1c915957a355e4158 Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Thu, 26 Nov 2026 22:11:12 +0800 Subject: [PATCH] fix(cli): scaffold ESM configs for CommonJS projects --- docs/guide/env-vars.md | 2 + docs/reference/cli/setup.md | 2 +- packages/void/src/cli/env-scaffold.ts | 37 +++++----- packages/void/src/cli/init.ts | 38 +++++----- packages/void/src/cli/template.ts | 10 ++- packages/void/src/index.ts | 2 - packages/void/src/plugin-dev-config.ts | 36 --------- .../void/test/integration/prepare-cli.test.ts | 73 ++++++++++++++++++- packages/void/test/unit/env-scaffold.test.ts | 34 ++++++++- packages/void/test/unit/init.test.ts | 26 +++++++ 10 files changed, 180 insertions(+), 80 deletions(-) diff --git a/docs/guide/env-vars.md b/docs/guide/env-vars.md index ad9b8b53e..34def9862 100644 --- a/docs/guide/env-vars.md +++ b/docs/guide/env-vars.md @@ -10,6 +10,8 @@ Declare your environment variables in `env.ts`, then read them through `env` fro Create `env.ts` at the project root: +For a package with `"type": "commonjs"` in `package.json`, use `env.mts`. + ```ts import { defineEnv, number, string, url } from 'void/env'; diff --git a/docs/reference/cli/setup.md b/docs/reference/cli/setup.md index 6f7ad1bb1..2106e223e 100644 --- a/docs/reference/cli/setup.md +++ b/docs/reference/cli/setup.md @@ -33,7 +33,7 @@ void init [--tsconfig] [--github] [--git | --no-git] [--toolchain ] [--framework ] [--starter ] [--deploy ] ``` -Set up a new or existing Void project. In an empty directory, choose Vite+ or Vite, a framework, and a D1, PostgreSQL, MySQL, or Static Pages starter. The new app's `void.config.ts` turns on [`routing.typedRoutes`](../config.md#routing-typedroutes). +Set up a new or existing Void project. In an empty directory, choose Vite+ or Vite, a framework, and a D1, PostgreSQL, MySQL, or Static Pages starter. For a package with `"type": "commonjs"`, starters use `vite.config.mts` and inferred env schemas use `env.mts`. The new app's `void.config.ts` turns on [`routing.typedRoutes`](../config.md#routing-typedroutes). Pass your choices as flags to scaffold from a script or coding agent: diff --git a/packages/void/src/cli/env-scaffold.ts b/packages/void/src/cli/env-scaffold.ts index d50bf9e7c..967b45c3e 100644 --- a/packages/void/src/cli/env-scaffold.ts +++ b/packages/void/src/cli/env-scaffold.ts @@ -1,17 +1,17 @@ /** - * `void init` hook — when the project has no `env.ts` but has dotenv files - * on disk, scaffold an `env.ts` whose keys mirror what the user already - * has. Inference is intentionally permissive: we only upgrade from the - * default `string()` helper when the value is unambiguously a boolean, + * During `void init`, scaffold an environment schema for the keys in a + * project's existing `.env`. Use the default `string()` helper unless the value is a boolean, * URL, or small integer. Everything else stays a string and carries a * one-line banner nudging the user to tighten the schema. * * This is a best-effort DX sweetener, not a correctness boundary — a * wrong guess only costs the user a single-line edit. */ -import { existsSync, writeFileSync } from 'node:fs'; -import { join } from 'pathslash'; +import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; +import { basename, join } from 'pathslash'; +import { readProjectPaths } from '../project-paths.ts'; import { parseDotenvFile } from '../shared/dotenv.ts'; +import { readPackageJson } from '../shared/package-json.ts'; export type InferredHelper = 'string' | 'number' | 'boolean' | 'url'; @@ -61,7 +61,7 @@ export function collectInferredEntries(root: string): Array { } /** - * Render the scaffolded `env.ts` body. The imports are pulled in lazily + * Render the scaffolded schema. The imports are pulled in lazily * so only helpers we reference appear in the import statement. */ export function renderEnvTs(entries: Array): string { @@ -108,18 +108,16 @@ export type ScaffoldResult = { }; /** - * If the project has no `env.ts`, scaffold one based on the local `.env` - * user already has. Safe to call unconditionally during `void init` — it - * no-ops when `env.ts` is present. Never overwrites an existing file. + * Scaffold a schema from `.env` when the project does not already have one. */ export function maybeScaffoldEnvTs(root: string): ScaffoldResult { - // Respect `env.*` at the root or under `src/`, whichever the user already uses. - for (const dir of ['', 'src/']) { - for (const ext of ['ts', 'mts', 'js', 'mjs']) { - if (existsSync(join(root, `${dir}env.${ext}`))) { - return { written: null, skipReason: 'env-ts-exists', entries: [] }; - } - } + const commonJs = readPackageJson(root)?.type === 'commonjs'; + const { sourceDir, sourceRoot, envFileCandidates } = readProjectPaths(root); + const hasSchema = envFileCandidates.some( + (file) => existsSync(file) || (sourceDir !== '' && existsSync(join(root, basename(file)))), + ); + if (hasSchema) { + return { written: null, skipReason: 'env-ts-exists', entries: [] }; } if (!existsSync(join(root, '.env'))) { @@ -127,7 +125,10 @@ export function maybeScaffoldEnvTs(root: string): ScaffoldResult { } const entries = collectInferredEntries(root); - const target = join(root, 'env.ts'); + const target = join(sourceRoot, commonJs ? 'env.mts' : 'env.ts'); + if (sourceDir) { + mkdirSync(sourceRoot, { recursive: true }); + } writeFileSync(target, renderEnvTs(entries)); return { written: target, entries }; } diff --git a/packages/void/src/cli/init.ts b/packages/void/src/cli/init.ts index da439e1fd..877c0113c 100644 --- a/packages/void/src/cli/init.ts +++ b/packages/void/src/cli/init.ts @@ -55,6 +55,7 @@ import type { DeploymentPlatform } from './project.ts'; import { createPagesStarterTemplate, detectScaffoldFrameworkFromDependencies, + getGeneratedViteConfigPath, getScaffoldTsconfigCompilerOptions, SCAFFOLD_BASE_DEV_DEPENDENCIES, SCAFFOLD_FRAMEWORKS, @@ -2022,17 +2023,6 @@ function scaffoldPagesApp( ): boolean { const packageJsonPath = join(root, 'package.json'); const packageJsonExisted = existsSync(packageJsonPath); - const template = createPagesStarterTemplate({ - framework, - starterMode, - toolchain, - voidPackageSpec: resolveScaffoldDependencySpec(root, 'void', getOwnVersion()), - adapterPackageSpec: resolveScaffoldDependencySpec( - root, - SCAFFOLD_FRAMEWORKS[framework].adapterPackage, - getOwnVersion(), - ), - }); let pkg: JsonObject = {}; if (packageJsonExisted) { @@ -2054,6 +2044,19 @@ function scaffoldPagesApp( pkg.type = 'module'; } + const template = createPagesStarterTemplate({ + framework, + starterMode, + toolchain, + packageType: pkg.type, + voidPackageSpec: resolveScaffoldDependencySpec(root, 'void', getOwnVersion()), + adapterPackageSpec: resolveScaffoldDependencySpec( + root, + SCAFFOLD_FRAMEWORKS[framework].adapterPackage, + getOwnVersion(), + ), + }); + const scripts = asRecord(pkg.scripts) ?? {}; pkg.scripts = scripts; for (const [name, command] of Object.entries(template.scripts)) { @@ -2259,11 +2262,6 @@ export default defineConfig({ `; } -function getGeneratedViteConfigPath(root: string): 'vite.config.ts' | 'vite.config.mts' { - const pkg = readPackageJson(root); - return pkg?.type === 'module' ? 'vite.config.ts' : 'vite.config.mts'; -} - function noteManualViteConfigSetup(configPath?: string): void { const target = configPath ?? 'your framework Vite config'; note( @@ -2352,7 +2350,13 @@ function ensureExistingProjectViteConfig( const configPath = findViteConfig(root); if (!configPath) { - writeFileIfMissing(root, getGeneratedViteConfigPath(root), getBasicVoidViteConfig(), report); + const packageType = readPackageJson(root)?.type; + writeFileIfMissing( + root, + getGeneratedViteConfigPath(packageType), + getBasicVoidViteConfig(), + report, + ); return; } diff --git a/packages/void/src/cli/template.ts b/packages/void/src/cli/template.ts index fc139cf32..5a6f95cae 100644 --- a/packages/void/src/cli/template.ts +++ b/packages/void/src/cli/template.ts @@ -181,10 +181,17 @@ export function getScaffoldTsconfigCompilerOptions( return framework ? { ...SCAFFOLD_FRAMEWORKS[framework].tsconfigCompilerOptions } : {}; } +export function getGeneratedViteConfigPath( + packageType: unknown, +): 'vite.config.ts' | 'vite.config.mts' { + return packageType === 'module' ? 'vite.config.ts' : 'vite.config.mts'; +} + export function createPagesStarterTemplate(options: { framework: ScaffoldFramework; starterMode: ScaffoldStarterMode; toolchain?: ScaffoldToolchain; + packageType?: unknown; voidPackageSpec: string; adapterPackageSpec: string; }): PagesStarterTemplate { @@ -192,6 +199,7 @@ export function createPagesStarterTemplate(options: { framework, starterMode, toolchain = 'vite', + packageType = 'module', voidPackageSpec, adapterPackageSpec, } = options; @@ -203,7 +211,7 @@ export function createPagesStarterTemplate(options: { { routing: { typedRoutes: true } }, '// Generated by void init.', ), - 'vite.config.ts': getViteConfig(framework, config, toolchain), + [getGeneratedViteConfigPath(packageType)]: getViteConfig(framework, config, toolchain), [`pages/index.${config.pageExtension}`]: getIndexPage(framework, starterMode), 'pages/style.css': starterStyles, 'pages/vite-env.d.ts': '/// \n', diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index 21933e397..4d39945d1 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -41,7 +41,6 @@ import { cloudflare } from './plugin-cloudflare.ts'; import type { WorkerConfig, AuxiliaryWorkerConfig } from './plugin-cloudflare.ts'; import { afterServerReady, - warnIfPackageJsonIsNotEsm, isViteBuildOrPreview, getOrCreateDevTriggerToken, devTriggerSecretGuardPlugin, @@ -108,7 +107,6 @@ export function voidPlugin(options?: { // needs it, because build prerendering can open a remote session too. selectVoidCloudflareLogin(); } - warnIfPackageJsonIsNotEsm(root); // Token only matters in serve — the dispatch module that uses it is // DCE'd from production worker bundles. In build/preview we still need // *some* string (the wrapper embeds it for completeness), but we skip diff --git a/packages/void/src/plugin-dev-config.ts b/packages/void/src/plugin-dev-config.ts index 27872cae6..3e7c5be65 100644 --- a/packages/void/src/plugin-dev-config.ts +++ b/packages/void/src/plugin-dev-config.ts @@ -1,7 +1,6 @@ import { chmodSync, closeSync, - existsSync, mkdirSync, openSync, readFileSync, @@ -10,7 +9,6 @@ import { } from 'node:fs'; import { join } from 'pathslash'; import type { Plugin, PluginOption, ViteDevServer } from 'vite'; -import { voidWarn } from './log.ts'; /** * Whether Vite is resolving the server that Vitest creates to run tests, whatever its `--mode`. @@ -215,37 +213,3 @@ export function devTriggerSecretGuardPlugin(): Plugin { }, }; } - -/** - * Warn when the project's `package.json` does not declare `"type": "module"`. - * - * Vite's default `configLoader: "bundle"` bundles `vite.config.ts`, - * externalizes deps, and then loads the bundle. When `package.json` is non-ESM - * the bundle is written as `.js` and loaded via CJS `require()`, which throws - * `ERR_REQUIRE_ASYNC_MODULE` if any externalized dep's ESM graph contains - * top-level await. `@cloudflare/vite-plugin` (which voidPlugin pulls in) has - * exactly such a TLA, so non-ESM consumers hit this on every Vite invocation. - * - * Runs once per Vite process (factory time), single sync read. - */ -export function warnIfPackageJsonIsNotEsm(root: string): void { - const pkgPath = join(root, 'package.json'); - if (!existsSync(pkgPath)) { - return; - } - let pkg: { type?: unknown }; - try { - pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { type?: unknown }; - } catch { - return; - } - if (pkg.type === 'module') { - return; - } - voidWarn( - 'package.json is missing `"type": "module"`. Vite\'s default config loader ' + - 'will fail with ERR_REQUIRE_ASYNC_MODULE on transitive top-level await ' + - '(e.g. @cloudflare/vite-plugin). Add `"type": "module"` to package.json, ' + - 'or run vite build with `--configLoader runner`.', - ); -} diff --git a/packages/void/test/integration/prepare-cli.test.ts b/packages/void/test/integration/prepare-cli.test.ts index ec2f018ee..b167ac33b 100644 --- a/packages/void/test/integration/prepare-cli.test.ts +++ b/packages/void/test/integration/prepare-cli.test.ts @@ -1,5 +1,13 @@ import { spawnSync } from 'node:child_process'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; @@ -45,10 +53,12 @@ function createProject(options: { withSources?: boolean; sourceDir?: string } = function runVoid( root: string, args: Array, + input?: string, ): { stdout: string; stderr: string; status: number } { const res = spawnSync(process.execPath, [CLI_ENTRY, ...args], { cwd: root, encoding: 'utf8', + input, env: { PATH: process.env.PATH, HOME: root, @@ -69,6 +79,67 @@ afterEach(() => { } }); +it.each([ + ['commonjs', 'env.mts'], + ['module', 'env.ts'], +])('builds a %s app with a sourceDir env schema after init', (type, schemaFile) => { + const root = createProject(); + const vite = join(PACKAGE_ROOT, 'node_modules', 'vite'); + mkdirSync(join(root, 'node_modules')); + symlinkSync(PACKAGE_ROOT, join(root, 'node_modules', 'void'), 'junction'); + symlinkSync(vite, join(root, 'node_modules', 'vite'), 'junction'); + writeFileSync( + join(root, 'package.json'), + JSON.stringify({ + name: 'source-dir-app', + type, + devDependencies: { typescript: '*', vite: '*', void: '*' }, + }), + ); + writeFileSync(join(root, 'void.config.ts'), "export default { sourceDir: 'app' };\n"); + writeFileSync( + join(root, type === 'commonjs' ? 'vite.config.mts' : 'vite.config.ts'), + "import { voidPlugin } from 'void';\nexport default { plugins: [voidPlugin()] };\n", + ); + writeFileSync(join(root, 'index.html'), '
Source directory app
\n'); + writeFileSync(join(root, '.env'), 'TEST_GREETING=hello\n'); + mkdirSync(join(root, 'app', 'routes'), { recursive: true }); + writeFileSync( + join(root, 'app', 'routes', 'hello.ts'), + "export const GET = () => new Response('ok');\n", + ); + const envFile = join(root, 'app', schemaFile); + const schema = + "import { defineEnv, string } from 'void/env';\nexport default defineEnv({ TEST_GREETING: string() });\n"; + if (type === 'commonjs') { + writeFileSync(envFile, schema); + } + + // Select "No Database Yet" for this existing project. + const init = runVoid(root, ['init', '--deploy', 'none', '--no-git'], '\u001b[B'.repeat(3) + '\r'); + expect(init.status, init.stdout + init.stderr).toBe(0); + const envTypes = join(root, '.void', 'env.d.ts'); + rmSync(envTypes, { force: true }); + const buildSource = `import { createBuilder } from 'vite'; +const builder = await createBuilder({}); +await builder.buildApp();`; + const build = spawnSync(process.execPath, ['--input-type=module', '--eval', buildSource], { + cwd: root, + encoding: 'utf8', + timeout: 30_000, + }); + expect(build.status, build.stderr).toBe(0); + const schemaSource = readFileSync(envFile, 'utf8'); + if (type === 'commonjs') { + expect(schemaSource).toBe(schema); + } else { + expect(schemaSource).toContain('TEST_GREETING: string(),'); + } + expect(readFileSync(envTypes, 'utf8')).toContain(`typeof import("../app/${schemaFile}")`); + expect(existsSync(join(root, 'env.ts'))).toBe(false); + expect(existsSync(join(root, 'env.mts'))).toBe(false); +}); + describe('void prepare (subprocess)', () => { it('generates custom binding types and removes them when switching targets', () => { const root = createProject(); diff --git a/packages/void/test/unit/env-scaffold.test.ts b/packages/void/test/unit/env-scaffold.test.ts index 2305eb35b..739c7df12 100644 --- a/packages/void/test/unit/env-scaffold.test.ts +++ b/packages/void/test/unit/env-scaffold.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { toSlash } from 'pathslash'; @@ -111,8 +111,16 @@ describe('maybeScaffoldEnvTs', () => { expect(byKey.STRIPE_KEY).toBe('string'); }); - it('writes env.ts with the inferred schema', () => { + it.each([ + ['module', '', 'env.ts'], + ['commonjs', '', 'env.mts'], + ['commonjs', 'app', 'app/env.mts'], + ])('writes the inferred schema for a %s package with sourceDir %j', (type, sourceDir, file) => { const root = tmpProject(); + writeFileSync(join(root, 'package.json'), JSON.stringify({ type })); + if (sourceDir) { + writeFileSync(join(root, 'void.json'), JSON.stringify({ sourceDir })); + } writeFileSync( join(root, '.env'), [ @@ -124,11 +132,29 @@ describe('maybeScaffoldEnvTs', () => { ].join('\n'), ); const result = maybeScaffoldEnvTs(root); - expect(result.written).toBe(toSlash(join(root, 'env.ts'))); - const body = readFileSync(join(root, 'env.ts'), 'utf8'); + expect(result.written).toBe(toSlash(join(root, file))); + const body = readFileSync(join(root, file), 'utf8'); expect(body).toContain('STRIPE_KEY: string(),'); expect(body).toContain('PORT: number(),'); expect(body).toContain('DEBUG: boolean(),'); expect(body).toContain('WEBHOOK_URL: url(),'); + if (sourceDir) { + expect(existsSync(join(root, 'env.mts'))).toBe(false); + } }); + + it.each(['env.ts', 'env.mts', 'app/env.ts', 'app/env.mts'])( + 'preserves %s for a CommonJS package with sourceDir configured', + (file) => { + const root = tmpProject(); + writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'commonjs' })); + writeFileSync(join(root, 'void.json'), JSON.stringify({ sourceDir: 'app' })); + writeFileSync(join(root, '.env'), 'FOO=bar\n'); + mkdirSync(join(root, 'app')); + writeFileSync(join(root, file), '// authored'); + + expect(maybeScaffoldEnvTs(root).written).toBeNull(); + expect(readFileSync(join(root, file), 'utf8')).toBe('// authored'); + }, + ); }); diff --git a/packages/void/test/unit/init.test.ts b/packages/void/test/unit/init.test.ts index 1d4dfa554..f05daa0d8 100644 --- a/packages/void/test/unit/init.test.ts +++ b/packages/void/test/unit/init.test.ts @@ -287,6 +287,32 @@ describe('init scaffold arguments', () => { } }); + it.each(['vite', 'vite-plus'] as const)( + 'writes an ESM Vite config for a CommonJS starter using %s', + async (toolchain) => { + await withTempDirAsync(async (root) => { + writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'commonjs' })); + + await runInitCommand( + root, + parseInitArgs([ + `--toolchain=${toolchain}`, + '--framework=svelte', + '--starter=static', + '--deploy=none', + ]), + ); + + const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')); + expect(pkg.type).toBe('commonjs'); + const viteConfig = readFileSync(join(root, 'vite.config.mts'), 'utf8'); + expect(viteConfig).toContain(`from "${toolchain}"`); + expect(viteConfig).toContain('from "@void/svelte/plugin"'); + expect(existsSync(join(root, 'vite.config.ts'))).toBe(false); + }); + }, + ); + it('fails with the missing flag instead of prompting when stdin is not a terminal', async () => { const root = mkdtempSync(join(tmpdir(), 'void-init-flags-missing-')); try {