bundler.test.ts66 lines · main
1import { test } from 'node:test';
2import { strict as assert } from 'node:assert';
3import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
4import { tmpdir } from 'node:os';
5import { join } from 'node:path';
6import { loadProjectSchema } from './bundler.js';
7
8/**
9 * Write a throwaway project and run `fn` against it.
10 *
11 * `moduleType` controls the project's package.json `type` field, which is what
12 * decides whether the loader's tsx import treats `briven/schema.ts` as
13 * CommonJS or ESM — the exact axis the CJS/ESM interop unwrap exists for.
14 */
15async function withProject(
16 source: string,
17 moduleType: 'commonjs' | 'module',
18 fn: (cwd: string) => Promise<void>,
19): Promise<void> {
20 const dir = await mkdtemp(join(tmpdir(), 'briven-bundler-'));
21 try {
22 await writeFile(
23 join(dir, 'package.json'),
24 JSON.stringify({ name: 'tmp', type: moduleType }),
25 'utf8',
26 );
27 await mkdir(join(dir, 'briven'), { recursive: true });
28 await writeFile(join(dir, 'briven', 'schema.ts'), source, 'utf8');
29 await fn(dir);
30 } finally {
31 await rm(dir, { recursive: true, force: true });
32 }
33}
34
35test('loadProjectSchema returns null when schema.ts is missing', async () => {
36 const dir = await mkdtemp(join(tmpdir(), 'briven-bundler-'));
37 try {
38 assert.equal(await loadProjectSchema(dir), null);
39 } finally {
40 await rm(dir, { recursive: true, force: true });
41 }
42});
43
44test('loadProjectSchema accepts a plain ESM default export', async () => {
45 await withProject('export default { version: 1, tables: {} };\n', 'module', async (cwd) => {
46 const schema = await loadProjectSchema(cwd);
47 assert.equal(schema?.version, 1);
48 });
49});
50
51test('loadProjectSchema unwraps the CJS/ESM double-default shape', async () => {
52 // Bug repro: in a CommonJS project, `export default schema({...})` is
53 // interop-double-wrapped to `mod.default.default`, so the loader used to
54 // reject a perfectly valid schema with "is not a valid briven schema".
55 await withProject('export default { version: 1, tables: {} };\n', 'commonjs', async (cwd) => {
56 const schema = await loadProjectSchema(cwd);
57 assert.equal(schema?.version, 1);
58 assert.deepEqual(schema?.tables, {});
59 });
60});
61
62test('loadProjectSchema rejects a non-schema default export', async () => {
63 await withProject('export default { version: 2, tables: {} };\n', 'commonjs', async (cwd) => {
64 await assert.rejects(loadProjectSchema(cwd), /not a valid briven schema/);
65 });
66});