Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion typescript/examples/basic/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"description": "Basic example: compile fixtures and migrate between versions",
"type": "module",
"scripts": {
"build": "vbare-compiler ../../../fixtures/tests/basic/",
"build": "node ../../vbare-compiler/dist/cli.js ../../../fixtures/tests/basic/",
"check-types": "tsc --noEmit",
"test": "pnpm build && vitest run",
"test:watch": "pnpm build && vitest watch"
Expand Down
25 changes: 18 additions & 7 deletions typescript/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion typescript/vbare-compiler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"prepublishOnly": "pnpm build"
},
"dependencies": {
"@bare-ts/tools": "^0.16.0",
"@bare-ts/tools": "^0.13.0",
"commander": "^11.1.0"
},
"devDependencies": {
Expand Down
52 changes: 11 additions & 41 deletions typescript/vbare-compiler/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { Command } from "commander";
import * as path from "path";
import * as fs from "node:fs/promises";
import { compileSchema } from "./index";
import { compileSchema, compileSchemaDirectory } from "./index";

const program = new Command();

Expand All @@ -21,57 +21,26 @@ async function isDirectory(p: string): Promise<boolean> {
}
}

async function compileFolder(inputDir: string, outputDir: string, opts: { pedantic?: boolean; generator?: string }) {
const resolvedInput = path.resolve(inputDir);
const resolvedOut = path.resolve(outputDir);

await fs.mkdir(resolvedOut, { recursive: true });

const entries = await fs.readdir(resolvedInput, { withFileTypes: true });
const bareFiles = entries
.filter((e) => e.isFile() && e.name.endsWith(".bare"))
.map((e) => e.name)
.sort();

if (bareFiles.length === 0) {
console.error(`No .bare files found in ${resolvedInput}`);
process.exit(1);
}

for (const file of bareFiles) {
const schemaPath = path.join(resolvedInput, file);
const base = file.replace(/\.bare$/, "");
const outputPath = path.join(resolvedOut, `${base}.ts`);

await compileSchema({
schemaPath,
outputPath,
config: {
pedantic: opts.pedantic ?? false,
generator: (opts.generator as any) ?? "ts",
// Support legacy 'string' in fixtures without extra flags
legacy: true,
},
});

console.log(`Compiled ${schemaPath} -> ${outputPath}`);
}
}

// Default usage: vbare-compiler <input>
program
.argument("<input>", "Input .bare file or folder containing .bare files")
.option("-o, --output <file>", "Output file path (when input is file)")
.option("-d, --out-dir <dir>", "Output directory (when input is a folder)", "dist")
.option("--pedantic", "Enable pedantic mode", false)
.option("--generator <type>", "Generator type (ts, js, dts, bare)", "ts")
.option("--runtime-import <specifier>", "Rewrite @bare-ts/lib imports to this runtime package")
.action(async (input: string, options) => {
try {
const inputPath = path.resolve(input);
if (await isDirectory(inputPath)) {
await compileFolder(inputPath, options.outDir, {
pedantic: options.pedantic,
generator: options.generator,
await compileSchemaDirectory({
inputDir: inputPath,
outputDir: options.outDir,
config: {
pedantic: options.pedantic,
generator: options.generator,
},
runtimeImportPath: options.runtimeImport,
});
return;
}
Expand All @@ -88,6 +57,7 @@ program
generator: options.generator,
legacy: true,
},
runtimeImportPath: options.runtimeImport,
});

console.log(`Compiled ${schemaPath} -> ${outputPath}`);
Expand Down
34 changes: 33 additions & 1 deletion typescript/vbare-compiler/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { compileSchema } from "./index";
import { compileSchema, compileSchemaDirectory } from "./index";
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { tmpdir } from "node:os";
Expand Down Expand Up @@ -48,6 +48,7 @@ describe("compileSchema", () => {
expect(output).toContain("export");
expect(output).toContain("Todo");
expect(output).toContain("App");
expect(output).toContain("export const SCHEMA_VERSION = 1 as const");
});

it("should handle custom config options using fixtures", async () => {
Expand All @@ -67,4 +68,35 @@ describe("compileSchema", () => {
expect(output).toContain("readTodo");
expect(output).toContain("writeTodo");
});

it("should rewrite the runtime import when requested", async () => {
await compileSchema({
schemaPath: v1Schema,
outputPath,
config: {
legacy: true,
},
runtimeImportPath: "@rivetkit/bare-ts",
});

const output = await fs.readFile(outputPath, "utf-8");
expect(output).toContain('@rivetkit/bare-ts');
expect(output).not.toContain('@bare-ts/lib');
});

it("should generate latest.ts for folder compiles", async () => {
const outDir = path.join(tempDir, "folder-out");

await compileSchemaDirectory({
inputDir: fixturesDir,
outputDir: outDir,
config: {
legacy: true,
},
});

const latest = await fs.readFile(path.join(outDir, "latest.ts"), "utf-8");
expect(latest).toContain('export * from "./v3"');
expect(latest).toContain("export const CURRENT_VERSION = 3 as const");
});
});
115 changes: 109 additions & 6 deletions typescript/vbare-compiler/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,18 @@ export interface CompileOptions {
schemaPath: string;
outputPath: string;
config?: Partial<Config>;
runtimeImportPath?: string;
}

export interface CompileDirectoryOptions {
inputDir: string;
outputDir: string;
config?: Partial<Config>;
runtimeImportPath?: string;
}

export async function compileSchema(options: CompileOptions): Promise<void> {
const { schemaPath, outputPath, config = {} } = options;
const { schemaPath, outputPath, config = {}, runtimeImportPath } = options;

let schema = await fs.readFile(schemaPath, "utf-8");

Expand Down Expand Up @@ -45,11 +53,65 @@ export async function compileSchema(options: CompileOptions): Promise<void> {

let result = transform(schema, defaultConfig);

result = postProcessAssert(result);
result = postProcessGeneratedTs(result, {
schemaVersion: parseSchemaVersion(schemaPath),
runtimeImportPath,
});

await fs.writeFile(outputPath, result);
}

export async function compileSchemaDirectory(
options: CompileDirectoryOptions,
): Promise<void> {
const { inputDir, outputDir, config = {}, runtimeImportPath } = options;
const resolvedInput = path.resolve(inputDir);
const resolvedOutput = path.resolve(outputDir);

await fs.mkdir(resolvedOutput, { recursive: true });

const entries = await fs.readdir(resolvedInput, { withFileTypes: true });
const bareFiles = entries
.filter((entry) => entry.isFile() && entry.name.endsWith(".bare"))
.map((entry) => entry.name)
.sort();

if (bareFiles.length === 0) {
throw new Error(`No .bare files found in ${resolvedInput}`);
}

let latestVersion: number | null = null;

for (const file of bareFiles) {
const schemaPath = path.join(resolvedInput, file);
const base = file.replace(/\.bare$/, "");
const outputPath = path.join(resolvedOutput, `${base}.ts`);

await compileSchema({
schemaPath,
outputPath,
config: {
pedantic: config.pedantic ?? false,
generator: (config.generator as any) ?? "ts",
legacy: config.legacy ?? true,
},
runtimeImportPath,
});

const schemaVersion = parseSchemaVersion(schemaPath);
if (schemaVersion !== null) {
latestVersion = latestVersion === null ? schemaVersion : Math.max(latestVersion, schemaVersion);
}
}

if (latestVersion !== null) {
await fs.writeFile(
path.join(resolvedOutput, "latest.ts"),
createLatestModule(latestVersion),
);
}
}

const ASSERT_FUNCTION = `
function assert(condition: boolean, message?: string): asserts condition {
if (!condition) throw new Error(message ?? "Assertion failed")
Expand All @@ -58,16 +120,57 @@ function assert(condition: boolean, message?: string): asserts condition {
`;

/**
* Remove Node.js assert import and inject a custom assert function
* Post-process generated TypeScript to remove Node.js-only imports, optionally
* rewrite the runtime package import, and expose version metadata for vN schemas.
*/
function postProcessAssert(code: string): string {
function postProcessGeneratedTs(
code: string,
options: {
schemaVersion: number | null;
runtimeImportPath?: string;
},
): string {
const { schemaVersion, runtimeImportPath } = options;

// Remove Node.js assert import
code = code.replace(/^import assert from "node:assert\/strict"/m, "");
code = code.replace(/^import assert from "node:assert"/m, "");
code = code.replace(/^import assert from "assert"/m, "");

if (runtimeImportPath) {
code = code.replace(/@bare-ts\/lib/g, runtimeImportPath);
}

if (schemaVersion !== null) {
const configPattern =
/(const\s+\w+\s*=\s*\/\* @__PURE__ \*\/ bare\.Config\(\{\}\)\n)/;
if (!configPattern.test(code)) {
throw new Error("Failed to find bare.Config while injecting SCHEMA_VERSION");
}

// INject new assert function
code += "\n" + ASSERT_FUNCTION;
code = code.replace(
configPattern,
`$1\nexport const SCHEMA_VERSION = ${schemaVersion} as const\n`,
);
}

// Inject new assert function
code += "\n" + ASSERT_FUNCTION;

return code;
}

function parseSchemaVersion(schemaPath: string): number | null {
const match = path.basename(schemaPath).match(/^v(\d+)\.bare$/);
return match ? Number.parseInt(match[1], 10) : null;
}

function createLatestModule(latestVersion: number): string {
return `// @generated by @vbare/compiler
export * from "./v${latestVersion}";

export const CURRENT_VERSION = ${latestVersion} as const;
`;
}

export { type Config, transform } from "@bare-ts/tools";
Loading