From 21641601c6cefed7ae5891576ee3270286702af1 Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 18 Nov 2026 10:38:34 +0530 Subject: [PATCH 1/5] fix(cli): resolve tsconfig aliases in database seeds --- docs/guide/database.md | 2 + packages/void/src/cli/db.ts | 21 ++++-- packages/void/test/unit/db-seed.test.ts | 94 +++++++++++++++++++++++++ 3 files changed, 111 insertions(+), 6 deletions(-) diff --git a/docs/guide/database.md b/docs/guide/database.md index f4438ad3b..f29e17c6b 100644 --- a/docs/guide/database.md +++ b/docs/guide/database.md @@ -264,6 +264,8 @@ Use `db/seed.ts` for a programmatic seed or `db/seed.sql` for SQL. JavaScript an Use `db/seed.ts` when you want to generate seed data in code. Export a default function or a named `seed` function. +Seed files and schema modules resolve imports using the aliases configured in your project's `tsconfig.json`, such as `@schema` and `@auth-schema`. + ```ts // db/seed.ts import { defineSeed } from 'void/seed'; diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 7a5058214..68071b8ca 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -776,7 +776,7 @@ async function runSeed( const seed = resolveSeedTarget(root, file); const sql = seed.kind === 'sql' ? readFileSync(seed.path, 'utf-8') : undefined; await confirmReset(root, dialect, yes); - const seedFn = sql === undefined ? await loadSeedFunction(seed.path) : undefined; + const seedFn = sql === undefined ? await loadSeedFunction(root, seed.path) : undefined; // Reset first (drop + re-run migrations). The drop is confirmed above, so do not ask again. const migrationCount = await resetDatabase(root, dialect, true); @@ -2470,8 +2470,11 @@ async function runSeedModule( } } -async function loadSeedFunction(seedPath: string): Promise>> { - const mod = await importLocalModule(seedPath); +async function loadSeedFunction( + root: string, + seedPath: string, +): Promise>> { + const mod = await importLocalModule(root, seedPath); const seed = typeof mod.default === 'function' ? mod.default @@ -2495,14 +2498,14 @@ async function loadSeedSchema(root: string): Promise> { } if (location.type === 'file') { - const mod = await importLocalModule(location.path); + const mod = await importLocalModule(root, location.path); return Object.fromEntries( Object.entries(mod).filter(([name]) => name !== 'default' && name !== '__esModule'), ); } const files = collectSchemaModuleFiles(location.path); - const parts = await Promise.all(files.map((file) => importLocalModule(file))); + const parts = await Promise.all(files.map((file) => importLocalModule(root, file))); return Object.assign( {}, ...parts.map((mod) => @@ -2530,12 +2533,18 @@ function collectSchemaModuleFiles(dir: string): Array { return files.sort(); } -async function importLocalModule(modulePath: string): Promise> { +async function importLocalModule( + root: string, + modulePath: string, +): Promise> { // Native import() cannot resolve the extensionless re-exports that `void gen model` writes. + const tsconfigPath = join(root, 'tsconfig.json'); const jiti = createJiti(import.meta.url, { fsCache: false, moduleCache: false, interopDefault: false, + // Anchor aliases to the app rather than the installed CLI or the current directory. + tsconfigPaths: existsSync(tsconfigPath) ? tsconfigPath : false, }); return jiti.import>(modulePath); } diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index c0c0913cb..c46f711c8 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -253,6 +253,100 @@ await runDbCommand(${JSON.stringify(root)}, { action: 'seed' });`, expect(await readMessages(root)).toEqual([{ id: 1, text: 'from barrel' }]); }, 30_000); + it.each([ + { layout: 'file', importSchema: true }, + { layout: 'directory', importSchema: true }, + { layout: 'file', importSchema: false }, + { layout: 'directory', importSchema: false }, + ])( + 'resolves tsconfig paths in a schema $layout with seed imports: $importSchema', + async ({ layout, importSchema }) => { + const root = createProjectRoot({ + migration: `CREATE TABLE users (id TEXT PRIMARY KEY); +CREATE TABLE messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + text TEXT NOT NULL REFERENCES users(id) +); +`, + seedFile: { + name: 'seed.ts', + content: `import { defineSeed } from 'void/seed'; +${importSchema ? "import { messages } from '@schema';\nimport { value } from '@seed-data/message';" : ''} + +export default defineSeed(async ({ db, schema }) => { + ${importSchema ? '' : "const { value } = await import('@seed-data/message');"} + await db.insert(schema.userTable).values({ id: value }); + await db.insert(${importSchema ? 'messages' : 'schema.messages'}).values({ text: value }); +}); +`, + }, + }); + mkdirSync(join(root, '.void')); + mkdirSync(join(root, 'config')); + mkdirSync(join(root, 'fixtures')); + writeFileSync( + join(root, '.void', 'better-auth-schema.ts'), + `import { sqliteTable, text } from 'void/schema-d1'; +export const userTable = sqliteTable('users', { id: text().primaryKey() }); +`, + ); + writeFileSync(join(root, 'fixtures', 'message.ts'), "export const value = 'from alias';\n"); + const compilerOptions = { + ...(layout === 'directory' ? { baseUrl: '..' } : {}), + paths: { + '@auth-schema': ['./.void/better-auth-schema.ts'], + '@schema': ['./db/schema'], + '@seed-data/*': ['./missing/*', './fixtures/*'], + }, + }; + writeFileSync( + join(root, 'config', 'tsconfig.base.json'), + JSON.stringify({ compilerOptions }), + ); + writeFileSync( + join(root, 'tsconfig.json'), + `{ + // Support both root paths and paths inherited from another directory. + ${layout === 'directory' ? '"extends": "./config/tsconfig.base.json"' : `"compilerOptions": ${JSON.stringify(compilerOptions)}`}, +} +`, + ); + const schemaDir = layout === 'directory' ? join(root, 'db', 'schema') : join(root, 'db'); + mkdirSync(schemaDir, { recursive: true }); + writeFileSync( + join(schemaDir, layout === 'directory' ? 'index.ts' : 'schema.ts'), + `import { integer, sqliteTable, text } from 'void/schema-d1'; +import { userTable } from '@auth-schema'; +export { userTable }; + +export const messages = sqliteTable('messages', { + id: integer().primaryKey({ autoIncrement: true }), + text: text().notNull().references(() => userTable.id), +}); +`, + ); + // Loading CLI modules must not evaluate the app's Vite config. + writeFileSync(join(root, 'vite.config.ts'), "throw new Error('Vite config was loaded');\n"); + + // Use plain Node so Vitest cannot resolve the imports for the seed loader. + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + 'const { runDbCommand } = await import(process.argv[1]); await runDbCommand(process.argv[2], { action: "seed" });', + new URL('../../src/cli/db.ts', import.meta.url).href, + root, + ], + { encoding: 'utf8', timeout: 20_000 }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'from alias' }]); + }, + 30_000, + ); + it('checks the seed file before it resets the database', async () => { const root = createProjectRoot({ seedFile: { From e86f6fd95db76467a381dae160435e4b4a378215 Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 18 Nov 2026 11:10:19 +0530 Subject: [PATCH 2/5] fix(cli): exclude declaration aliases from seed imports --- packages/void/package.json | 1 + packages/void/src/cli/db.ts | 157 ++++++++++++++++-------- packages/void/test/unit/db-seed.test.ts | 76 +++++++++++- pnpm-lock.yaml | 3 + 4 files changed, 186 insertions(+), 51 deletions(-) diff --git a/packages/void/package.json b/packages/void/package.json index 040acf123..a6669fec2 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -379,6 +379,7 @@ "drizzle-valibot": "^0.4.2", "drizzle-zod": "^0.8.3", "email-validator": "^2.0.4", + "get-tsconfig": "^4.14.3", "gray-matter": "^4.0.3", "hono": "catalog:", "ignore": "catalog:", diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 68071b8ca..0a66ad262 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -2,6 +2,7 @@ import { execFileSync } from 'node:child_process'; import { existsSync, mkdirSync, + mkdtempSync, readFileSync, readdirSync, renameSync, @@ -9,8 +10,10 @@ import { writeFileSync, } from 'node:fs'; import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; import { pathToFileURL } from 'node:url'; import { confirm, isCancel, outro, log, text } from '@voidzero-dev/vite-plus-prompts'; +import { createPathsMatcher, getTsconfig } from 'get-tsconfig'; import { createJiti } from 'jiti'; import { basename, dirname, extname, join, relative, resolve } from 'pathslash'; import { @@ -776,45 +779,50 @@ async function runSeed( const seed = resolveSeedTarget(root, file); const sql = seed.kind === 'sql' ? readFileSync(seed.path, 'utf-8') : undefined; await confirmReset(root, dialect, yes); - const seedFn = sql === undefined ? await loadSeedFunction(root, seed.path) : undefined; + const loader = sql === undefined ? createSeedModuleLoader(root) : undefined; + try { + const seedFn = loader ? await loadSeedFunction(seed.path, loader.importModule) : undefined; - // Reset first (drop + re-run migrations). The drop is confirmed above, so do not ask again. - const migrationCount = await resetDatabase(root, dialect, true); - log.step(`Reset database. Applied ${formatCount(migrationCount, 'migration')}.`); + // Reset first (drop + re-run migrations). The drop is confirmed above, so do not ask again. + const migrationCount = await resetDatabase(root, dialect, true); + log.step(`Reset database. Applied ${formatCount(migrationCount, 'migration')}.`); - if (sql !== undefined) { - if (dialect === 'postgresql') { - await withPgClient(root, async (client) => { - await client.query(sql); - }); - printSuccess(`Seeded from ${seed.displayPath}.`); + if (sql !== undefined) { + if (dialect === 'postgresql') { + await withPgClient(root, async (client) => { + await client.query(sql); + }); + printSuccess(`Seeded from ${seed.displayPath}.`); - return; - } + return; + } - if (dialect === 'mysql') { - await withMySqlClient(root, async (client) => { - await client.query(sql); - }); - printSuccess(`Seeded from ${seed.displayPath}.`); + if (dialect === 'mysql') { + await withMySqlClient(root, async (client) => { + await client.query(sql); + }); + printSuccess(`Seeded from ${seed.displayPath}.`); - return; - } + return; + } - const { openSqliteDatabase } = await import('../migrations/runner.ts'); - const { databasePath: dbPath } = getLocalD1Target(root); - const db = await openSqliteDatabase(dbPath); - try { - db.exec(sql); - } finally { - db.close(); + const { openSqliteDatabase } = await import('../migrations/runner.ts'); + const { databasePath: dbPath } = getLocalD1Target(root); + const db = await openSqliteDatabase(dbPath); + try { + db.exec(sql); + } finally { + db.close(); + } + } else { + await runSeedModule(root, seedFn!, dialect, loader!.importModule); } - } else { - await runSeedModule(root, seedFn!, dialect); - } - log.info(dim("Restart your dev server if it's running.")); - printSuccess(`Seeded from ${seed.displayPath}.`); + log.info(dim("Restart your dev server if it's running.")); + printSuccess(`Seeded from ${seed.displayPath}.`); + } finally { + loader?.close(); + } } /** @@ -2426,8 +2434,9 @@ async function runSeedModule( root: string, seed: SeedFn>, dialect: DatabaseDialect, + importModule: SeedModuleImporter, ): Promise { - const schema = await loadSeedSchema(root); + const schema = await loadSeedSchema(root, importModule); const casing = getDatabaseCasing(readConfig(root)); if (dialect === 'postgresql') { @@ -2471,10 +2480,10 @@ async function runSeedModule( } async function loadSeedFunction( - root: string, seedPath: string, + importModule: SeedModuleImporter, ): Promise>> { - const mod = await importLocalModule(root, seedPath); + const mod = await importModule(seedPath); const seed = typeof mod.default === 'function' ? mod.default @@ -2489,7 +2498,10 @@ async function loadSeedFunction( return seed as SeedFn>; } -async function loadSeedSchema(root: string): Promise> { +async function loadSeedSchema( + root: string, + importModule: SeedModuleImporter, +): Promise> { const { discoverSchema } = await import('../drizzle/discover.ts'); const paths = readProjectPaths(root); const location = discoverSchema(root, paths); @@ -2498,14 +2510,14 @@ async function loadSeedSchema(root: string): Promise> { } if (location.type === 'file') { - const mod = await importLocalModule(root, location.path); + const mod = await importModule(location.path); return Object.fromEntries( Object.entries(mod).filter(([name]) => name !== 'default' && name !== '__esModule'), ); } const files = collectSchemaModuleFiles(location.path); - const parts = await Promise.all(files.map((file) => importLocalModule(root, file))); + const parts = await Promise.all(files.map((file) => importModule(file))); return Object.assign( {}, ...parts.map((mod) => @@ -2533,20 +2545,65 @@ function collectSchemaModuleFiles(dir: string): Array { return files.sort(); } -async function importLocalModule( - root: string, - modulePath: string, -): Promise> { - // Native import() cannot resolve the extensionless re-exports that `void gen model` writes. +type SeedModuleImporter = (path: string) => Promise>; + +function createSeedModuleLoader(root: string): { + importModule: SeedModuleImporter; + close: () => void; +} { const tsconfigPath = join(root, 'tsconfig.json'); - const jiti = createJiti(import.meta.url, { - fsCache: false, - moduleCache: false, - interopDefault: false, - // Anchor aliases to the app rather than the installed CLI or the current directory. - tsconfigPaths: existsSync(tsconfigPath) ? tsconfigPath : false, - }); - return jiti.import>(modulePath); + let directory: string | undefined; + const close = () => { + if (directory) { + rmSync(directory, { recursive: true, force: true }); + } + }; + try { + const project = existsSync(tsconfigPath) ? getTsconfig(tsconfigPath) : null; + const options = project?.config.compilerOptions; + let runtimeTsconfig: string | false = false; + if (project && options) { + const paths: Record> = {}; + for (const [alias, targets] of Object.entries(options.paths ?? {})) { + const runtimeTargets = targets.filter((target) => !/\.d\.[cm]?ts$/.test(target)); + if (runtimeTargets.length === 0) { + continue; + } + // Resolve each mapping independently, retaining the declaring config's + // path base and the wildcard itself when converting targets to absolute paths. + const matcher = createPathsMatcher({ + ...project, + config: { compilerOptions: { ...options, paths: { [alias]: runtimeTargets } } }, + }); + paths[alias] = matcher!(alias); + } + // Jiti accepts a config filename, not parsed options. Keep this disposable + // runtime config through execution: dynamic imports create child loaders. + directory = mkdtempSync(join(tmpdir(), 'void-seed-')); + runtimeTsconfig = join(directory, 'tsconfig.json'); + writeFileSync( + runtimeTsconfig, + JSON.stringify({ + compilerOptions: { + ...(options.baseUrl !== undefined + ? { baseUrl: resolve(dirname(project.path), options.baseUrl) } + : {}), + paths, + }, + }), + ); + } + const jiti = createJiti(import.meta.url, { + fsCache: false, + moduleCache: false, + interopDefault: false, + tsconfigPaths: runtimeTsconfig, + }); + return { importModule: (path) => jiti.import>(path), close }; + } catch (error) { + close(); + throw error; + } } /** The schema and casing that `void/db` gives drizzle, or undefined when neither is set. */ diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index c46f711c8..8f09b4d46 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -4,6 +4,7 @@ import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import * as output from '../../src/cli/output.ts'; +import { createProjectTsconfig } from '../../src/codegen/project-tsconfig.ts'; import { getMiniflareDatabasePath } from '../../src/migrations/runner.ts'; const mockIntro = vi.fn(); @@ -291,12 +292,16 @@ export const userTable = sqliteTable('users', { id: text().primaryKey() }); `, ); writeFileSync(join(root, 'fixtures', 'message.ts'), "export const value = 'from alias';\n"); + writeFileSync( + join(root, 'fixtures', 'message.d.ts'), + 'export declare const value: string;\n', + ); const compilerOptions = { ...(layout === 'directory' ? { baseUrl: '..' } : {}), paths: { '@auth-schema': ['./.void/better-auth-schema.ts'], '@schema': ['./db/schema'], - '@seed-data/*': ['./missing/*', './fixtures/*'], + '@seed-data/*': ['./fixtures/*.d.ts', './missing/*', './fixtures/*'], }, }; writeFileSync( @@ -347,6 +352,75 @@ export const messages = sqliteTable('messages', { 30_000, ); + it('keeps runtime helpers when extending generated declaration aliases', async () => { + const root = createProjectRoot({ + schema: `import { integer, sqliteTable, text } from 'void/schema-d1'; +export const messages = sqliteTable('messages', { + id: integer().primaryKey({ autoIncrement: true }), + text: text().notNull(), +}); +`, + seedFile: { + name: 'seed.ts', + content: `import { defineSeed } from 'void/seed'; +import { routeUrl } from 'void/routes'; +import { messages } from '@schema'; +export default defineSeed(async ({ db }) => { + await db.insert(messages).values({ text: routeUrl('/messages/[id]', { params: { id: 'hello world' } }) }); +}); +`, + }, + }); + mkdirSync(join(root, '.void')); + const config = createProjectTsconfig(root, true, true, true); + config.compilerOptions!.paths!['void/seed'] = ['./seed.d.mts']; + config.compilerOptions!.paths!['void/schema-d1'] = ['./schema.d.cts']; + writeFileSync(join(root, '.void', 'tsconfig.json'), JSON.stringify(config)); + writeFileSync( + join(root, '.void', 'routes.d.ts'), + 'export declare function routeUrl(): string;\n', + ); + writeFileSync(join(root, '.void', 'db.d.ts'), 'export {};\n'); + writeFileSync( + join(root, '.void', 'seed.d.mts'), + 'export declare function defineSeed(): void;\n', + ); + writeFileSync(join(root, '.void', 'schema.d.cts'), 'export {};\n'); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ extends: './.void/tsconfig.json' }), + ); + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + 'const { runDbCommand } = await import(process.argv[1]); await runDbCommand(process.argv[2], { action: "seed" });', + new URL('../../src/cli/db.ts', import.meta.url).href, + root, + ], + { encoding: 'utf8', timeout: 20_000 }, + ); + expect(result.status, result.stderr).toBe(0); + expect(await readMessages(root)).toEqual([{ id: 1, text: '/messages/hello%20world' }]); + }, 30_000); + + it('loads CommonJS JavaScript seeds', async () => { + const root = createProjectRoot({ + seedFile: { + name: 'seed.js', + content: `module.exports = async function seed({ db }) { + const { sql } = require('drizzle-orm'); + await db.run(sql\`INSERT INTO messages (text) VALUES ('from CommonJS')\`); +}; +`, + }, + }); + writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'commonjs' })); + await runDbCommand(root, { action: 'seed' }); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'from CommonJS' }]); + }); + it('checks the seed file before it resets the database', async () => { const root = createProjectRoot({ seedFile: { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9625ae931..bb68029c0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -858,6 +858,9 @@ importers: email-validator: specifier: ^2.0.4 version: 2.0.4 + get-tsconfig: + specifier: ^4.14.3 + version: 4.14.3 gray-matter: specifier: ^4.0.3 version: 4.0.3 From 86ea48491f03c0c9363d2f5714f163c1d1e95cbe Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 18 Nov 2026 15:21:51 +0530 Subject: [PATCH 3/5] fix(cli): resolve aliases in JavaScript database seeds --- docs/guide/database.md | 4 +- packages/void/src/cli/db.ts | 70 +++++++-- packages/void/test/unit/db-seed.test.ts | 199 +++++++++++++++++++----- 3 files changed, 223 insertions(+), 50 deletions(-) diff --git a/docs/guide/database.md b/docs/guide/database.md index f29e17c6b..5d28f4800 100644 --- a/docs/guide/database.md +++ b/docs/guide/database.md @@ -264,7 +264,9 @@ Use `db/seed.ts` for a programmatic seed or `db/seed.sql` for SQL. JavaScript an Use `db/seed.ts` when you want to generate seed data in code. Export a default function or a named `seed` function. -Seed files and schema modules resolve imports using the aliases configured in your project's `tsconfig.json`, such as `@schema` and `@auth-schema`. +Seed files and schema modules resolve imports using the aliases configured in your project's `tsconfig.json`, such as `@schema` and `@auth-schema`. This works in TypeScript and JavaScript files, including dynamic `import()` calls. + +If your tsconfig extends `.void/tsconfig.json`, run `void prepare` before seeding a fresh checkout. ```ts // db/seed.ts diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 0a66ad262..dfb16079f 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -9,13 +9,13 @@ import { rmSync, writeFileSync, } from 'node:fs'; -import { createRequire } from 'node:module'; +import { createRequire, isBuiltin, registerHooks } from 'node:module'; import { tmpdir } from 'node:os'; import { pathToFileURL } from 'node:url'; import { confirm, isCancel, outro, log, text } from '@voidzero-dev/vite-plus-prompts'; import { createPathsMatcher, getTsconfig } from 'get-tsconfig'; import { createJiti } from 'jiti'; -import { basename, dirname, extname, join, relative, resolve } from 'pathslash'; +import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'pathslash'; import { readConfig, getDatabaseCasing, @@ -2553,7 +2553,9 @@ function createSeedModuleLoader(root: string): { } { const tsconfigPath = join(root, 'tsconfig.json'); let directory: string | undefined; + let hooks: ReturnType | undefined; const close = () => { + hooks?.deregister(); if (directory) { rmSync(directory, { recursive: true, force: true }); } @@ -2562,6 +2564,7 @@ function createSeedModuleLoader(root: string): { const project = existsSync(tsconfigPath) ? getTsconfig(tsconfigPath) : null; const options = project?.config.compilerOptions; let runtimeTsconfig: string | false = false; + let matchPaths: ReturnType = null; if (project && options) { const paths: Record> = {}; for (const [alias, targets] of Object.entries(options.paths ?? {})) { @@ -2581,17 +2584,16 @@ function createSeedModuleLoader(root: string): { // runtime config through execution: dynamic imports create child loaders. directory = mkdtempSync(join(tmpdir(), 'void-seed-')); runtimeTsconfig = join(directory, 'tsconfig.json'); - writeFileSync( - runtimeTsconfig, - JSON.stringify({ - compilerOptions: { - ...(options.baseUrl !== undefined - ? { baseUrl: resolve(dirname(project.path), options.baseUrl) } - : {}), - paths, - }, - }), - ); + const config = { + compilerOptions: { + ...(options.baseUrl !== undefined + ? { baseUrl: resolve(dirname(project.path), options.baseUrl) } + : {}), + paths, + }, + }; + writeFileSync(runtimeTsconfig, JSON.stringify(config)); + matchPaths = createPathsMatcher({ path: runtimeTsconfig, config }); } const jiti = createJiti(import.meta.url, { fsCache: false, @@ -2599,9 +2601,51 @@ function createSeedModuleLoader(root: string): { interopDefault: false, tsconfigPaths: runtimeTsconfig, }); + // Jiti delegates .mjs and ESM .js to Node. Apply the same paths there, + // including imports made by ESM helpers and dynamic imports during the seed. + if (matchPaths) { + const jitiUrl = import.meta.resolve('jiti'); + const modules = new Set(); + hooks = registerHooks({ + resolve(specifier, context, nextResolve) { + // Only follow Jiti's native imports and their descendants. CLI imports + // made while resetting the database must keep their own resolution. + if (context.parentURL !== jitiUrl && !modules.has(context.parentURL ?? '')) { + return nextResolve(specifier, context); + } + if ( + !isBuiltin(specifier) && + !isAbsolute(specifier) && + !specifier.startsWith('.') && + !/^[\w+.-]+:/.test(specifier) + ) { + for (const target of matchPaths(specifier)) { + const resolved = jiti.esmResolve(target, { try: true }); + if (resolved) { + const result = nextResolve(resolved, context); + modules.add(result.url); + return result; + } + } + } + const result = nextResolve(specifier, context); + modules.add(result.url); + return result; + }, + }); + } return { importModule: (path) => jiti.import>(path), close }; } catch (error) { close(); + if ( + !existsSync(join(root, '.void', 'tsconfig.json')) && + error instanceof Error && + /File ['"].*[/\\]\.void[/\\]tsconfig\.json['"] not found/.test(error.message) + ) { + throw new Error('db: Missing .void/tsconfig.json. Run `void prepare` before seeding.', { + cause: error, + }); + } throw error; } } diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index 8f09b4d46..5c70f4a48 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -1,5 +1,5 @@ import { spawnSync } from 'node:child_process'; -import { existsSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; @@ -352,58 +352,185 @@ export const messages = sqliteTable('messages', { 30_000, ); - it('keeps runtime helpers when extending generated declaration aliases', async () => { - const root = createProjectRoot({ - schema: `import { integer, sqliteTable, text } from 'void/schema-d1'; + it.each(['ts', 'mjs', 'js'])( + 'keeps runtime helpers in %s seeds when extending generated declaration aliases', + async (extension) => { + const root = createProjectRoot({ + schema: `import { integer, sqliteTable, text } from 'void/schema-d1'; export const messages = sqliteTable('messages', { id: integer().primaryKey({ autoIncrement: true }), text: text().notNull(), }); `, - seedFile: { - name: 'seed.ts', - content: `import { defineSeed } from 'void/seed'; + seedFile: { + name: `seed.${extension}`, + content: `import { defineSeed } from 'void/seed'; import { routeUrl } from 'void/routes'; import { messages } from '@schema'; export default defineSeed(async ({ db }) => { await db.insert(messages).values({ text: routeUrl('/messages/[id]', { params: { id: 'hello world' } }) }); }); `, - }, + }, + }); + writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'module' })); + mkdirSync(join(root, 'node_modules')); + symlinkSync( + join(import.meta.dirname, '../..'), + join(root, 'node_modules', 'void'), + process.platform === 'win32' ? 'junction' : 'dir', + ); + mkdirSync(join(root, '.void')); + const config = createProjectTsconfig(root, true, true, true); + config.compilerOptions!.paths!['void/seed'] = ['./seed.d.mts']; + config.compilerOptions!.paths!['void/schema-d1'] = ['./schema.d.cts']; + writeFileSync(join(root, '.void', 'tsconfig.json'), JSON.stringify(config)); + writeFileSync( + join(root, '.void', 'routes.d.ts'), + 'export declare function routeUrl(): string;\n', + ); + writeFileSync(join(root, '.void', 'db.d.ts'), 'export {};\n'); + writeFileSync( + join(root, '.void', 'seed.d.mts'), + 'export declare function defineSeed(): void;\n', + ); + writeFileSync(join(root, '.void', 'schema.d.cts'), 'export {};\n'); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ extends: './.void/tsconfig.json' }), + ); + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + 'const { runDbCommand } = await import(process.argv[1]); await runDbCommand(process.argv[2], { action: "seed" });', + new URL('../../src/cli/db.ts', import.meta.url).href, + root, + ], + { encoding: 'utf8', timeout: 20_000 }, + ); + expect(result.status, result.stderr).toBe(0); + expect(await readMessages(root)).toEqual([{ id: 1, text: '/messages/hello%20world' }]); + }, + 30_000, + ); + + it.each( + ['ts', 'mjs', 'js'].flatMap((extension) => + ['static', 'dynamic'].map((importMode) => ({ extension, importMode })), + ), + )( + 'resolves $importMode aliases in $extension seeds before matching packages', + async ({ extension, importMode }) => { + const root = createProjectRoot({ + seedFile: { + name: `seed.${extension}`, + content: `import { sql } from 'drizzle-orm'; +${importMode === 'static' ? "import { value } from 'seed-fixture';" : ''} +export default async function seed({ db }) { + ${importMode === 'dynamic' ? "const { value } = await import('seed-fixture');" : ''} + await db.run(sql\`INSERT INTO messages (text) VALUES (\${value})\`); +} +`, + }, + }); + writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'module' })); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ + compilerOptions: { + baseUrl: '.', + paths: { + 'seed-fixture': ['./missing', './fixtures/message.mjs'], + 'seed-*': ['./fixtures/*.d.ts', './fixtures/*.js'], + 'better-sqlite3': ['./fixtures/not-a-driver.js'], + }, + }, + }), + ); + mkdirSync(join(root, 'fixtures')); + writeFileSync( + join(root, 'fixtures', 'message.mjs'), + `import { basename } from 'node:path'; +import { value as prefix } from 'seed-value'; +export const value = prefix + (await import('seed-value')).value; +if (basename(import.meta.url) !== 'message.mjs') throw new Error('Wrong module URL'); +`, + ); + writeFileSync(join(root, 'fixtures', 'value.js'), "export const value = 'local';\n"); + writeFileSync(join(root, 'fixtures', 'value.d.ts'), 'export declare const value: string;\n'); + writeFileSync( + join(root, 'fixtures', 'not-a-driver.js'), + "throw new Error('CLI database imports used seed aliases');\n", + ); + for (const name of ['seed-fixture', 'seed-value']) { + const directory = join(root, 'node_modules', name); + mkdirSync(directory, { recursive: true }); + writeFileSync( + join(directory, 'package.json'), + JSON.stringify({ name, type: 'module', exports: './index.js' }), + ); + writeFileSync(join(directory, 'index.js'), "export const value = 'package';\n"); + } + writeFileSync( + join(root, 'db', 'broken.mjs'), + "import 'seed-fixture';\nexport const value = 1;\n", + ); + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + `import { createRequire } from 'node:module'; +const { runDbCommand } = await import(process.argv[1]); +await runDbCommand(process.argv[2], { action: 'seed' }); +const require = createRequire(process.argv[2] + '/package.json'); +if (!require.resolve('seed-fixture').includes('node_modules')) throw new Error('Seed alias hook leaked'); +let error; +try { await runDbCommand(process.argv[2], { action: 'seed', file: 'db/broken.mjs' }); } +catch (cause) { error = cause; } +if (!error?.message.includes('must export')) throw new Error('Invalid seed was accepted'); +if (!require.resolve('seed-fixture').includes('node_modules')) throw new Error('Failed seed leaked its alias hook');`, + new URL('../../src/cli/db.ts', import.meta.url).href, + root, + ], + { encoding: 'utf8', timeout: 20_000 }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'locallocal' }]); + }, + 30_000, + ); + + it('suggests void prepare for a missing generated tsconfig before resetting data', async () => { + const root = createProjectRoot({ + seedFile: { name: 'seed.sql', content: "INSERT INTO messages (text) VALUES ('keep me');" }, }); - mkdirSync(join(root, '.void')); - const config = createProjectTsconfig(root, true, true, true); - config.compilerOptions!.paths!['void/seed'] = ['./seed.d.mts']; - config.compilerOptions!.paths!['void/schema-d1'] = ['./schema.d.cts']; - writeFileSync(join(root, '.void', 'tsconfig.json'), JSON.stringify(config)); - writeFileSync( - join(root, '.void', 'routes.d.ts'), - 'export declare function routeUrl(): string;\n', - ); - writeFileSync(join(root, '.void', 'db.d.ts'), 'export {};\n'); - writeFileSync( - join(root, '.void', 'seed.d.mts'), - 'export declare function defineSeed(): void;\n', - ); - writeFileSync(join(root, '.void', 'schema.d.cts'), 'export {};\n'); + await runDbCommand(root, { action: 'seed' }); writeFileSync( join(root, 'tsconfig.json'), JSON.stringify({ extends: './.void/tsconfig.json' }), ); - const result = spawnSync( - process.execPath, - [ - '--input-type=module', - '-e', - 'const { runDbCommand } = await import(process.argv[1]); await runDbCommand(process.argv[2], { action: "seed" });', - new URL('../../src/cli/db.ts', import.meta.url).href, - root, - ], - { encoding: 'utf8', timeout: 20_000 }, + writeFileSync(join(root, 'db', 'seed.ts'), 'export default async function seed() {}\n'); + + await expect(runDbCommand(root, { action: 'seed', file: 'db/seed.ts' })).rejects.toThrow( + /void prepare/, ); - expect(result.status, result.stderr).toBe(0); - expect(await readMessages(root)).toEqual([{ id: 1, text: '/messages/hello%20world' }]); - }, 30_000); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'keep me' }]); + }); + + it('preserves errors for unrelated missing tsconfig bases', async () => { + const root = createProjectRoot({ + seedFile: { name: 'seed.ts', content: 'export default async function seed() {}\n' }, + }); + writeFileSync(join(root, 'tsconfig.json'), JSON.stringify({ extends: './missing.json' })); + + await expect(runDbCommand(root, { action: 'seed' })).rejects.toThrow( + "File './missing.json' not found.", + ); + }); it('loads CommonJS JavaScript seeds', async () => { const root = createProjectRoot({ From 2e7a421fbd798de89b0af9d427ba4406d952a1d5 Mon Sep 17 00:00:00 2001 From: karthic Date: Wed, 18 Nov 2026 15:36:37 +0530 Subject: [PATCH 4/5] fix(cli): scope native seed imports to application modules --- packages/void/src/cli/db.ts | 40 +++++--- packages/void/test/unit/db-seed.test.ts | 129 ++++++++++++++++-------- 2 files changed, 115 insertions(+), 54 deletions(-) diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index dfb16079f..c4112c5f3 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -5,13 +5,14 @@ import { mkdtempSync, readFileSync, readdirSync, + realpathSync, renameSync, rmSync, writeFileSync, } from 'node:fs'; import { createRequire, isBuiltin, registerHooks } from 'node:module'; import { tmpdir } from 'node:os'; -import { pathToFileURL } from 'node:url'; +import { fileURLToPath, pathToFileURL } from 'node:url'; import { confirm, isCancel, outro, log, text } from '@voidzero-dev/vite-plus-prompts'; import { createPathsMatcher, getTsconfig } from 'get-tsconfig'; import { createJiti } from 'jiti'; @@ -2604,15 +2605,34 @@ function createSeedModuleLoader(root: string): { // Jiti delegates .mjs and ESM .js to Node. Apply the same paths there, // including imports made by ESM helpers and dynamic imports during the seed. if (matchPaths) { - const jitiUrl = import.meta.resolve('jiti'); - const modules = new Set(); + const appUrl = pathToFileURL(realpathSync(root) + '/').href; hooks = registerHooks({ resolve(specifier, context, nextResolve) { - // Only follow Jiti's native imports and their descendants. CLI imports - // made while resetting the database must keep their own resolution. - if (context.parentURL !== jitiUrl && !modules.has(context.parentURL ?? '')) { + // Use the importer's location for both ESM and CommonJS. Installed + // dependencies resolve their imports in their own package scope. + const parent = context.parentURL; + if ( + !parent?.startsWith(appUrl) || + parent.slice(appUrl.length - 1).includes('/node_modules/') + ) { return nextResolve(specifier, context); } + // Generated schema barrels re-export extensionless TypeScript paths. + if (specifier.startsWith('./') || specifier.startsWith('../')) { + try { + return nextResolve(specifier, context); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === 'ERR_MODULE_NOT_FOUND' || code === 'ERR_UNSUPPORTED_DIR_IMPORT') { + const target = new URL(specifier, parent); + const resolved = jiti.esmResolve(fileURLToPath(target), { try: true }); + if (resolved) { + return nextResolve(resolved + target.search + target.hash, context); + } + } + throw error; + } + } if ( !isBuiltin(specifier) && !isAbsolute(specifier) && @@ -2622,15 +2642,11 @@ function createSeedModuleLoader(root: string): { for (const target of matchPaths(specifier)) { const resolved = jiti.esmResolve(target, { try: true }); if (resolved) { - const result = nextResolve(resolved, context); - modules.add(result.url); - return result; + return nextResolve(resolved, context); } } } - const result = nextResolve(specifier, context); - modules.add(result.url); - return result; + return nextResolve(specifier, context); }, }); } diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index 5c70f4a48..18b48be69 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -1,7 +1,6 @@ import { spawnSync } from 'node:child_process'; import { existsSync, mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { pathToFileURL } from 'node:url'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import * as output from '../../src/cli/output.ts'; import { createProjectTsconfig } from '../../src/codegen/project-tsconfig.ts'; @@ -109,6 +108,22 @@ async function readMessages(root: string): Promise { let runDbCommand: typeof import('../../src/cli/db.ts').runDbCommand; @@ -236,21 +251,7 @@ export const messages = sqliteTable("messages", { }); `, ); - const dbModule = pathToFileURL(join(import.meta.dirname, '../../src/cli/db.ts')).href; - - // Plain Node, because Vitest's module runner resolves extensionless imports. - const result = spawnSync( - process.execPath, - [ - '--input-type=module', - '-e', - `const { runDbCommand } = await import(${JSON.stringify(dbModule)}); -await runDbCommand(${JSON.stringify(root)}, { action: 'seed' });`, - ], - { encoding: 'utf8', timeout: 20_000 }, - ); - - expect(result.status, result.stderr).toBe(0); + runSeedInNode(root); expect(await readMessages(root)).toEqual([{ id: 1, text: 'from barrel' }]); }, 30_000); @@ -333,20 +334,7 @@ export const messages = sqliteTable('messages', { // Loading CLI modules must not evaluate the app's Vite config. writeFileSync(join(root, 'vite.config.ts'), "throw new Error('Vite config was loaded');\n"); - // Use plain Node so Vitest cannot resolve the imports for the seed loader. - const result = spawnSync( - process.execPath, - [ - '--input-type=module', - '-e', - 'const { runDbCommand } = await import(process.argv[1]); await runDbCommand(process.argv[2], { action: "seed" });', - new URL('../../src/cli/db.ts', import.meta.url).href, - root, - ], - { encoding: 'utf8', timeout: 20_000 }, - ); - - expect(result.status, result.stderr).toBe(0); + runSeedInNode(root); expect(await readMessages(root)).toEqual([{ id: 1, text: 'from alias' }]); }, 30_000, @@ -399,18 +387,7 @@ export default defineSeed(async ({ db }) => { join(root, 'tsconfig.json'), JSON.stringify({ extends: './.void/tsconfig.json' }), ); - const result = spawnSync( - process.execPath, - [ - '--input-type=module', - '-e', - 'const { runDbCommand } = await import(process.argv[1]); await runDbCommand(process.argv[2], { action: "seed" });', - new URL('../../src/cli/db.ts', import.meta.url).href, - root, - ], - { encoding: 'utf8', timeout: 20_000 }, - ); - expect(result.status, result.stderr).toBe(0); + runSeedInNode(root); expect(await readMessages(root)).toEqual([{ id: 1, text: '/messages/hello%20world' }]); }, 30_000, @@ -504,6 +481,74 @@ if (!require.resolve('seed-fixture').includes('node_modules')) throw new Error(' 30_000, ); + it('dynamically imports a generated schema barrel from an mjs seed', async () => { + const root = createProjectRoot({ + schema: 'export * from "./schema/messages";', + seedFile: { + name: 'seed.mjs', + content: `export default async function ({ db }) { + const { messages } = await import('@schema'); + await db.insert(messages).values({ text: 'from barrel' }); +}`, + }, + }); + mkdirSync(join(root, 'db/schema')); + writeFileSync( + join(root, 'db/schema/messages.ts'), + `import { sqliteTable, text } from 'drizzle-orm/sqlite-core'; +export const messages = sqliteTable('messages', { text: text().notNull() });`, + ); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ compilerOptions: { paths: { '@schema': ['./db/schema.ts'] } } }), + ); + runSeedInNode(root); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'from barrel' }]); + }, 30_000); + + it.each(['installed package', 'local CommonJS helper'])( + 'resolves a dynamic #internal import from %s', + async (importer) => { + const installed = importer === 'installed package'; + const root = createProjectRoot({ + seedFile: { + name: installed ? 'seed.mjs' : 'seed.ts', + content: `import { sql } from 'drizzle-orm'; +${installed ? "import { readValue } from 'seed-package';" : "const { readValue } = require('./helper.cjs');"} +export default async function ({ db }) { + const value = await readValue(); + await db.run(sql\`INSERT INTO messages (text) VALUES (\${value})\`); +}`, + }, + }); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ compilerOptions: { paths: { '#internal': ['./app.mjs'] } } }), + ); + writeFileSync(join(root, 'app.mjs'), "export default 'app';"); + const helper = "async () => (await import('#internal')).default"; + if (installed) { + const directory = join(root, 'node_modules/seed-package'); + mkdirSync(directory, { recursive: true }); + writeFileSync( + join(directory, 'package.json'), + JSON.stringify({ + type: 'module', + exports: './index.js', + imports: { '#internal': './internal.js' }, + }), + ); + writeFileSync(join(directory, 'index.js'), 'export const readValue = ' + helper); + writeFileSync(join(directory, 'internal.js'), "export default 'package';"); + } else { + writeFileSync(join(root, 'db/helper.cjs'), 'exports.readValue = ' + helper); + } + runSeedInNode(root); + expect(await readMessages(root)).toEqual([{ id: 1, text: installed ? 'package' : 'app' }]); + }, + 30_000, + ); + it('suggests void prepare for a missing generated tsconfig before resetting data', async () => { const root = createProjectRoot({ seedFile: { name: 'seed.sql', content: "INSERT INTO messages (text) VALUES ('keep me');" }, From f46892910acecb04c563a39629646a2ca29daade Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Wed, 18 Nov 2026 19:49:10 +0900 Subject: [PATCH 5/5] Keep database seed imports in their package scope. --- docs/guide/database.md | 4 +- packages/void/package.json | 1 + packages/void/src/cli/db-seed-loader.ts | 202 ++++++++++++++++++++++++ packages/void/src/cli/db.ts | 137 +--------------- packages/void/test/unit/db-seed.test.ts | 96 ++++++++++- pnpm-lock.yaml | 3 + 6 files changed, 306 insertions(+), 137 deletions(-) create mode 100644 packages/void/src/cli/db-seed-loader.ts diff --git a/docs/guide/database.md b/docs/guide/database.md index 5d28f4800..e2e2ceb66 100644 --- a/docs/guide/database.md +++ b/docs/guide/database.md @@ -264,7 +264,9 @@ Use `db/seed.ts` for a programmatic seed or `db/seed.sql` for SQL. JavaScript an Use `db/seed.ts` when you want to generate seed data in code. Export a default function or a named `seed` function. -Seed files and schema modules resolve imports using the aliases configured in your project's `tsconfig.json`, such as `@schema` and `@auth-schema`. This works in TypeScript and JavaScript files, including dynamic `import()` calls. +On Node.js, seed files and schema modules use the aliases in your project's `tsconfig.json`, such as `@schema` and `@auth-schema`. This includes dynamic `import()` calls and seeds selected with `--file`. Dependencies keep their own package imports, including linked workspace packages. + +Running the CLI directly under Bun uses Bun's own resolver. Use `npx void db seed` if a seed outside your project needs the project's aliases or a workspace package uses a conflicting alias. If your tsconfig extends `.void/tsconfig.json`, run `void prepare` before seeding a fresh checkout. diff --git a/packages/void/package.json b/packages/void/package.json index a6669fec2..ed0ebeac4 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -379,6 +379,7 @@ "drizzle-valibot": "^0.4.2", "drizzle-zod": "^0.8.3", "email-validator": "^2.0.4", + "esbuild": "^0.28.2", "get-tsconfig": "^4.14.3", "gray-matter": "^4.0.3", "hono": "catalog:", diff --git a/packages/void/src/cli/db-seed-loader.ts b/packages/void/src/cli/db-seed-loader.ts new file mode 100644 index 000000000..eb34b17af --- /dev/null +++ b/packages/void/src/cli/db-seed-loader.ts @@ -0,0 +1,202 @@ +import { existsSync, readFileSync, realpathSync } from 'node:fs'; +import nodeModule, { type ResolveHookSync } from 'node:module'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { buildSync, transformSync } from 'esbuild'; +import { createPathsMatcher, getTsconfig } from 'get-tsconfig'; +import { createJiti } from 'jiti'; +import { basename, dirname, extname, isAbsolute, join, toSlash } from 'pathslash'; + +export type SeedModuleImporter = (path: string) => Promise>; + +function seedPaths(root: string) { + const path = join(root, 'tsconfig.json'); + if (!existsSync(path)) { + return null; + } + try { + const project = getTsconfig(path); + const options = project?.config.compilerOptions; + if (!project || !options) { + return null; + } + const paths = Object.fromEntries( + Object.entries(options.paths ?? {}) + .map( + ([name, targets]) => + [name, targets.filter((target) => !/\.d\.[cm]?ts$/.test(target))] as const, + ) + .filter(([, targets]) => targets.length > 0), + ); + if (!Object.keys(paths).length && options.baseUrl === undefined) { + return null; + } + return createPathsMatcher({ ...project, config: { compilerOptions: { ...options, paths } } }); + } catch (error) { + if ( + !existsSync(join(root, '.void/tsconfig.json')) && + error instanceof Error && + /File ['"].*[/\\]\.void[/\\]tsconfig\.json['"] not found/.test(error.message) + ) { + throw new Error('db: Missing .void/tsconfig.json. Run `void prepare` before seeding.', { + cause: error, + }); + } + throw error; + } +} + +function seedScope(root: string, seed: string) { + const directories = new Map([ + [toSlash(realpathSync(root)), true], + [dirname(realpathSync(seed)), true], + ]); + function ownsDirectory(directory: string): boolean { + const known = directories.get(directory); + if (known !== undefined) { + return known; + } + const parent = dirname(directory); + const owned = + parent !== directory && + basename(directory) !== 'node_modules' && + !existsSync(join(directory, 'package.json')) && + ownsDirectory(parent); + directories.set(directory, owned); + return owned; + } + return (url: string) => url.startsWith('file:') && ownsDirectory(dirname(fileURLToPath(url))); +} + +export function createSeedModuleLoader( + root: string, + seed: string, +): { + importModule: SeedModuleImporter; + close: () => void; +} { + const match = seedPaths(root); + const jiti = createJiti(import.meta.url, { + fsCache: false, + moduleCache: false, + interopDefault: false, + tsconfigPaths: false, + }); + if (!match || typeof nodeModule.registerHooks !== 'function') { + return { importModule: (path) => jiti.import>(path), close: () => {} }; + } + const owns = seedScope(root, seed); + const modules = new Set(); + + const resolveImport: ResolveHookSync = (specifier, context, nextResolve) => { + const parent = context.parentURL!; + if (specifier.startsWith('./') || specifier.startsWith('../')) { + try { + return nextResolve(specifier, context); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if ( + code === 'MODULE_NOT_FOUND' || + code === 'ERR_MODULE_NOT_FOUND' || + code === 'ERR_UNSUPPORTED_DIR_IMPORT' + ) { + const target = new URL(specifier, parent); + const resolved = jiti.esmResolve(fileURLToPath(target), { try: true }); + if (resolved) { + return { shortCircuit: true, url: resolved + target.search + target.hash }; + } + } + throw error; + } + } + if ( + owns(parent) && + !isAbsolute(specifier) && + !specifier.startsWith('.') && + !/^[\w+.-]+:/.test(specifier) + ) { + for (const target of match(specifier)) { + const resolved = jiti.esmResolve(target, { try: true }); + if (resolved) { + return { shortCircuit: true, url: resolved }; + } + } + } + return nextResolve(specifier, context); + }; + const hooks = nodeModule.registerHooks({ + resolve(specifier, context, nextResolve) { + const parent = context.parentURL; + if (!parent || !modules.has(parent) || nodeModule.isBuiltin(specifier)) { + return nextResolve(specifier, context); + } + const local = owns(parent) || /\.[cm]?ts$/.test(fileURLToPath(parent)); + const result = local + ? resolveImport(specifier, context, nextResolve) + : nextResolve(specifier, context); + if (result.url.startsWith('file:')) { + modules.add(result.url); + if ( + local && + extname(fileURLToPath(result.url)) === '.json' && + !context.importAttributes?.type + ) { + return { ...result, importAttributes: { ...context.importAttributes, type: 'json' } }; + } + } + return result; + }, + load(url, context, nextLoad) { + if (!modules.has(url)) { + return nextLoad(url, context); + } + const sourcefile = fileURLToPath(url); + if (sourcefile.endsWith('.js') && context.format === 'commonjs' && owns(url)) { + const source = readFileSync(sourcefile, 'utf8'); + const { metafile } = buildSync({ + stdin: { sourcefile, contents: source }, + write: false, + metafile: true, + platform: 'node', + target: 'node24', + }); + if (Object.values(metafile.inputs)[0]?.format === 'esm') { + return { format: 'module', source, shortCircuit: true }; + } + } + if (!/\.[cm]?ts$/.test(sourcefile)) { + return nextLoad(url, context); + } + const commonjs = sourcefile.endsWith('.cts'); + const { code } = transformSync(readFileSync(sourcefile, 'utf8'), { + sourcefile, + loader: 'ts', + target: 'node24', + platform: 'node', + format: commonjs ? 'cjs' : 'esm', + sourcemap: 'inline', + ...(commonjs + ? {} + : { + define: { + require: 'import.meta.require', + __filename: 'import.meta.filename', + __dirname: 'import.meta.dirname', + }, + banner: + "import.meta.require = globalThis.process.getBuiltinModule('node:module').createRequire(import.meta.url);", + }), + }); + return { format: commonjs ? 'commonjs' : 'module', source: code, shortCircuit: true }; + }, + }); + return { + async importModule(path) { + const url = pathToFileURL(realpathSync(path)).href; + modules.add(url); + const mod = await import(url); + const cjs = mod['module.exports']; + return cjs && typeof cjs === 'object' ? cjs : mod; + }, + close: () => hooks.deregister(), + }; +} diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index c4112c5f3..472d16d2d 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -2,21 +2,16 @@ import { execFileSync } from 'node:child_process'; import { existsSync, mkdirSync, - mkdtempSync, readFileSync, readdirSync, - realpathSync, renameSync, rmSync, writeFileSync, } from 'node:fs'; -import { createRequire, isBuiltin, registerHooks } from 'node:module'; -import { tmpdir } from 'node:os'; -import { fileURLToPath, pathToFileURL } from 'node:url'; +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; import { confirm, isCancel, outro, log, text } from '@voidzero-dev/vite-plus-prompts'; -import { createPathsMatcher, getTsconfig } from 'get-tsconfig'; -import { createJiti } from 'jiti'; -import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'pathslash'; +import { basename, dirname, extname, join, relative, resolve } from 'pathslash'; import { readConfig, getDatabaseCasing, @@ -56,6 +51,7 @@ import { quoteSqlIdentifier, quoteSqlString, } from './db-export-sequences.ts'; +import type { SeedModuleImporter } from './db-seed-loader.ts'; import { formatTimestamp } from './gen.ts'; import { printSuccess, dim, formatCount, formatUrl, getErrorMessage, pc } from './output.ts'; import { readDeploymentPlatform, readProjectConfig } from './project.ts'; @@ -780,7 +776,10 @@ async function runSeed( const seed = resolveSeedTarget(root, file); const sql = seed.kind === 'sql' ? readFileSync(seed.path, 'utf-8') : undefined; await confirmReset(root, dialect, yes); - const loader = sql === undefined ? createSeedModuleLoader(root) : undefined; + const loader = + sql === undefined + ? (await import('./db-seed-loader.ts')).createSeedModuleLoader(root, seed.path) + : undefined; try { const seedFn = loader ? await loadSeedFunction(seed.path, loader.importModule) : undefined; @@ -2546,126 +2545,6 @@ function collectSchemaModuleFiles(dir: string): Array { return files.sort(); } -type SeedModuleImporter = (path: string) => Promise>; - -function createSeedModuleLoader(root: string): { - importModule: SeedModuleImporter; - close: () => void; -} { - const tsconfigPath = join(root, 'tsconfig.json'); - let directory: string | undefined; - let hooks: ReturnType | undefined; - const close = () => { - hooks?.deregister(); - if (directory) { - rmSync(directory, { recursive: true, force: true }); - } - }; - try { - const project = existsSync(tsconfigPath) ? getTsconfig(tsconfigPath) : null; - const options = project?.config.compilerOptions; - let runtimeTsconfig: string | false = false; - let matchPaths: ReturnType = null; - if (project && options) { - const paths: Record> = {}; - for (const [alias, targets] of Object.entries(options.paths ?? {})) { - const runtimeTargets = targets.filter((target) => !/\.d\.[cm]?ts$/.test(target)); - if (runtimeTargets.length === 0) { - continue; - } - // Resolve each mapping independently, retaining the declaring config's - // path base and the wildcard itself when converting targets to absolute paths. - const matcher = createPathsMatcher({ - ...project, - config: { compilerOptions: { ...options, paths: { [alias]: runtimeTargets } } }, - }); - paths[alias] = matcher!(alias); - } - // Jiti accepts a config filename, not parsed options. Keep this disposable - // runtime config through execution: dynamic imports create child loaders. - directory = mkdtempSync(join(tmpdir(), 'void-seed-')); - runtimeTsconfig = join(directory, 'tsconfig.json'); - const config = { - compilerOptions: { - ...(options.baseUrl !== undefined - ? { baseUrl: resolve(dirname(project.path), options.baseUrl) } - : {}), - paths, - }, - }; - writeFileSync(runtimeTsconfig, JSON.stringify(config)); - matchPaths = createPathsMatcher({ path: runtimeTsconfig, config }); - } - const jiti = createJiti(import.meta.url, { - fsCache: false, - moduleCache: false, - interopDefault: false, - tsconfigPaths: runtimeTsconfig, - }); - // Jiti delegates .mjs and ESM .js to Node. Apply the same paths there, - // including imports made by ESM helpers and dynamic imports during the seed. - if (matchPaths) { - const appUrl = pathToFileURL(realpathSync(root) + '/').href; - hooks = registerHooks({ - resolve(specifier, context, nextResolve) { - // Use the importer's location for both ESM and CommonJS. Installed - // dependencies resolve their imports in their own package scope. - const parent = context.parentURL; - if ( - !parent?.startsWith(appUrl) || - parent.slice(appUrl.length - 1).includes('/node_modules/') - ) { - return nextResolve(specifier, context); - } - // Generated schema barrels re-export extensionless TypeScript paths. - if (specifier.startsWith('./') || specifier.startsWith('../')) { - try { - return nextResolve(specifier, context); - } catch (error) { - const code = (error as NodeJS.ErrnoException).code; - if (code === 'ERR_MODULE_NOT_FOUND' || code === 'ERR_UNSUPPORTED_DIR_IMPORT') { - const target = new URL(specifier, parent); - const resolved = jiti.esmResolve(fileURLToPath(target), { try: true }); - if (resolved) { - return nextResolve(resolved + target.search + target.hash, context); - } - } - throw error; - } - } - if ( - !isBuiltin(specifier) && - !isAbsolute(specifier) && - !specifier.startsWith('.') && - !/^[\w+.-]+:/.test(specifier) - ) { - for (const target of matchPaths(specifier)) { - const resolved = jiti.esmResolve(target, { try: true }); - if (resolved) { - return nextResolve(resolved, context); - } - } - } - return nextResolve(specifier, context); - }, - }); - } - return { importModule: (path) => jiti.import>(path), close }; - } catch (error) { - close(); - if ( - !existsSync(join(root, '.void', 'tsconfig.json')) && - error instanceof Error && - /File ['"].*[/\\]\.void[/\\]tsconfig\.json['"] not found/.test(error.message) - ) { - throw new Error('db: Missing .void/tsconfig.json. Run `void prepare` before seeding.', { - cause: error, - }); - } - throw error; - } -} - /** The schema and casing that `void/db` gives drizzle, or undefined when neither is set. */ function getDrizzleSchemaOptions( schema: Record, diff --git a/packages/void/test/unit/db-seed.test.ts b/packages/void/test/unit/db-seed.test.ts index 18b48be69..6f131e3ec 100644 --- a/packages/void/test/unit/db-seed.test.ts +++ b/packages/void/test/unit/db-seed.test.ts @@ -109,15 +109,16 @@ async function readMessages(root: string): Promise { - const installed = importer === 'installed package'; + const installed = importer !== 'local CommonJS helper'; const root = createProjectRoot({ seedFile: { name: installed ? 'seed.mjs' : 'seed.ts', @@ -528,17 +534,31 @@ export default async function ({ db }) { writeFileSync(join(root, 'app.mjs'), "export default 'app';"); const helper = "async () => (await import('#internal')).default"; if (installed) { - const directory = join(root, 'node_modules/seed-package'); + const linked = importer.startsWith('linked'); + const entry = importer === 'linked TypeScript package' ? 'index.ts' : 'index.js'; + const directory = join( + root, + linked ? 'packages/seed-package' : 'node_modules/seed-package', + ); mkdirSync(directory, { recursive: true }); + if (linked) { + mkdirSync(join(root, 'node_modules')); + symlinkSync(directory, join(root, 'node_modules/seed-package'), 'junction'); + } writeFileSync( join(directory, 'package.json'), JSON.stringify({ type: 'module', - exports: './index.js', + exports: './' + entry, imports: { '#internal': './internal.js' }, }), ); - writeFileSync(join(directory, 'index.js'), 'export const readValue = ' + helper); + if (entry === 'index.ts') { + writeFileSync(join(directory, entry), "export { readValue } from './helper';"); + writeFileSync(join(directory, 'helper.ts'), 'export const readValue = ' + helper); + } else { + writeFileSync(join(directory, entry), 'export const readValue = ' + helper); + } writeFileSync(join(directory, 'internal.js'), "export default 'package';"); } else { writeFileSync(join(root, 'db/helper.cjs'), 'exports.readValue = ' + helper); @@ -549,6 +569,45 @@ export default async function ({ db }) { 30_000, ); + it.each([ + { name: 'seed.mjs', external: false }, + { name: 'seed.js', external: false }, + { name: 'seed.mjs', external: true }, + ])( + 'loads a TypeScript enum via a dynamic alias from $name (external: $external)', + async ({ name, external }) => { + const root = createProjectRoot({ + seedFile: { name: 'seed.sql', content: '' }, + schema: + "import { sqliteTable, text } from 'drizzle-orm/sqlite-core'; export const messages = sqliteTable('messages', {text: text().notNull()});", + }); + writeFileSync(join(root, 'package.json'), '{"type":"module"}'); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ + compilerOptions: { paths: { '@fixture': ['./fixture.ts'] } }, + }), + ); + writeFileSync(join(root, 'fixture.ts'), "export enum Label { Local = 'local' }"); + const seedDir = external + ? mkdtempSync(join(root, '../.tmp-external-seed-')) + : join(root, 'db'); + if (external) { + roots.push(seedDir); + } + const seedPath = join(seedDir, name); + writeFileSync( + seedPath, + `export default async ({ db, schema }) => { + const { Label } = await import('@fixture'); + await db.insert(schema.messages).values({text: Label.Local}); +};`, + ); + runSeedInNode(root, seedPath); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'local' }]); + }, + ); + it('suggests void prepare for a missing generated tsconfig before resetting data', async () => { const root = createProjectRoot({ seedFile: { name: 'seed.sql', content: "INSERT INTO messages (text) VALUES ('keep me');" }, @@ -593,6 +652,29 @@ export default async function ({ db }) { expect(await readMessages(root)).toEqual([{ id: 1, text: 'from CommonJS' }]); }); + it('keeps ESM syntax in a JavaScript seed and its helpers in a CommonJS app', async () => { + const root = createProjectRoot({ + seedFile: { + name: 'seed.js', + content: `import {value} from './helper.js'; +import { sql } from 'drizzle-orm'; +export default async ({db})=>{ await db.run(sql\`INSERT INTO messages (text) VALUES (\${value})\`); };`, + }, + }); + writeFileSync(join(root, 'package.json'), '{"type":"commonjs"}'); + writeFileSync( + join(root, 'tsconfig.json'), + JSON.stringify({ compilerOptions: { paths: { '@data': ['./data.json'] } } }), + ); + writeFileSync(join(root, 'data.json'), '{"text":"from json"}'); + writeFileSync( + join(root, 'db/helper.js'), + "export const value = (await import('@data')).default.text;", + ); + runSeedInNode(root); + expect(await readMessages(root)).toEqual([{ id: 1, text: 'from json' }]); + }); + it('checks the seed file before it resets the database', async () => { const root = createProjectRoot({ seedFile: { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bb68029c0..911f174ad 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -858,6 +858,9 @@ importers: email-validator: specifier: ^2.0.4 version: 2.0.4 + esbuild: + specifier: ^0.28.2 + version: 0.28.2 get-tsconfig: specifier: ^4.14.3 version: 4.14.3