Compile a TypeScript schema
To generate a language-neutral JSON Schema from a Zod model, use the compileSchema function. This function transforms your Zod definitions into a canonical YAML representation, ensuring that the resulting schema includes the required x-softschema metadata and a stable schema_sha256 fingerprint.
Compiling a Schema to Disk
When you call compileSchema without the checkOnly flag, softschema writes the generated YAML directly to the specified output path. The returned CompileResult provides the final YAML content and the SHA256 hash of the canonical JSON representation.
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(`SHA256 Fingerprint: ${result.schemaSha256}`);
The CompileResult contains the following fields:
outPath: The absolute or relative path where the file was written or checked.schemaYaml: The full string content of the generated YAML schema.schemaSha256: A stable hash of the canonical JSON form of the schema, used to verify parity across different language implementations.drift: A boolean indicating if the generated schema differs from the file already on disk.driftDiff: A human-readable string describing the difference ifdriftis true.
Validating Schema Drift in CI
You can use the checkOnly option to verify that a committed schema file matches the current Zod definition without overwriting the file. This is useful in CI/CD pipelines to ensure that developers have re-compiled their schemas after making changes to the Zod models.
import { z } from "zod";
import { compileSchema, CompileResult } from "softschema";
const OrderSchema = z.object({
orderId: z.string().uuid(),
amount: z.number().positive(),
status: z.enum(["pending", "shipped", "delivered"]),
});
const result: CompileResult = compileSchema(OrderSchema, "schemas/order.yaml", {
contractId: "sales:order/v1",
checkOnly: true,
});
if (result.drift) {
console.error("Schema drift detected!");
console.error(result.driftDiff);
// In a CI environment, you might call process.exit(1) here
} else {
console.log("Schema is up to date.");
}
When checkOnly is set to true, compileSchema performs a content-based comparison. If the file at outPath does not exist, drift will be true and driftDiff will indicate the missing file. If the file exists but its canonical content differs from the generated schema, drift will be true and driftDiff will contain a message describing the mismatch. If the contents match, drift will be false and driftDiff will be null.