Skip to main content

Compile a TypeScript schema

The compileSchema function in softschema converts a Zod schema into a canonical JSON Schema represented as a YAML file. This process generates a language-neutral fingerprint (schemaSha256) that ensures the schema remains consistent across different implementations, such as Python and TypeScript.

Compiling a Zod Schema to YAML

When you call compileSchema, softschema transforms your Zod model into a JSON Schema Draft 2020-12 compliant structure, adds metadata like the contractId, and writes the result to the specified file path. The returned CompileResult provides the generated YAML content and the unique SHA256 hash of the canonical schema.

import { z } from "zod";
import { compileSchema, CompileResult } from "softschema";

const UserProfile = z.object({
username: z.string().min(3),
email: z.string().email(),
isActive: z.boolean().default(true),
});

const result: CompileResult = compileSchema(UserProfile, "schemas/user_profile.yaml", {
contractId: "identity:user/v1",
});

console.log(`Schema written to: ${result.outPath}`);
console.log(`Canonical SHA256: ${result.schemaSha256}`);
// The result.schemaYaml contains the full YAML string written to disk

Detecting Schema Drift

You can use the checkOnly option to verify if an existing schema file matches your current Zod model without overwriting the file. This is useful in CI/CD pipelines to ensure that developers have committed the latest compiled version of their schemas. The drift boolean indicates a mismatch, and driftDiff provides a description of the discrepancy.

import { z } from "zod";
import { compileSchema, CompileResult } from "softschema";

const Order = z.object({
orderId: z.string().uuid(),
amount: z.number().positive(),
});

const result: CompileResult = compileSchema(Order, "schemas/order.yaml", {
contractId: "billing:order/v1",
checkOnly: true,
});

if (result.drift) {
console.error(`Drift detected: ${result.driftDiff}`);
// In checkOnly mode, the file at result.outPath is NOT modified.
} else {
console.log("Schema is up to date.");
}

The compileSchema function performs a content-based comparison. It parses the existing YAML file and compares its canonical structure against the newly generated schema. This ensures that minor formatting differences in the YAML text do not trigger a drift warning, while genuine changes to the schema logic or metadata are correctly identified.