@collective-intelligence/schema-codegen
Pure generator from Draft 2020-12 JSON Schema documents to TypeScript source.
It has no runtime dependency. It does no file IO and has no CLI. Callers pass
documents in and write the returned text. The ci package codegen command of
@collective-intelligence/cli is the caller for package declarations; see the
CLI README.
Targets:
types: plain TypeScript types.zod: Zod schemas and inferred types.effect:effect/Schemaschemas and types.
Generate a module
The package exports generateSchemaModule and its types. The function is pure
and never throws. It returns the source text of one file for one target.
import { generateSchemaModule } from "@collective-intelligence/schema-codegen"
const result = generateSchemaModule({
target: "zod",
header: { packageFqn: "acme.billing", packageVersion: "1.0.0" },
schemas: [
{
name: "acme.billing.invoice#input",
document: { type: "object", properties: { id: { type: "string" } } },
fidelity: "exact"
}
]
})
if (result.errors === undefined) {
// Write result.source to <out>/acme.billing/zod.ts. result.warnings is data.
}
SchemaInput.nameis<component fqn>#<slot label>. The generator builds the export name from it: the PascalCase componentfqnwithout the packagefqn, then the PascalCase slot label. Exports are sorted by componentfqn, then slot label. A name without#<slot label>, an invalid identifier, a name that the target file already uses and two schemas with one export name are errors (reserved_name,invalid_name,name_clash). Thezodfile usesz,RegExpandInfinity; theeffectfile usesSchema,RegExpandInfinity. Thetypesfile reserves no name. This holds for the names of$defsentries too.SchemaInput.fidelityisexactorstructural. Astructuralschema can be stricter at runtime than its JSON Schema. Eachstructuralschema gives astructural_fidelitywarning.GenerateResultis{ source, warnings }or{ errors }. One run collects every error, each with a code, the schema name, a JSON Pointer and the keyword (nullwhen no single keyword is at fault).Warning.kindisstructural_fidelity,dropped_keyword,format_annotation_onlyorclosed_object_unenforced.- The output is byte-stable. The same input gives the same text: no timestamp, tool version or hash. The library does not call a formatter.
File header
Every file starts with a // comment header. The header names the target, the
package fqn and the package version, and says that the schemas are not
runtime validation authority. A blank line follows it. The effect header has
one more line about excess keys.
// @generated
// Target: zod
// Package: acme.billing
// Version: 1.0.0
// Generated schemas are a convenience and not runtime validation authority.
// The backend host validates.
The @generated marker in the leading comment is how the CLI recognizes a file
that it may overwrite.
Authority and requirements
Generated schemas are a convenience. The backend host validates; generated files never replace it. The schemas describe the wire shape: the encoded JSON, not decoded runtime values.
zodoutput needszod4.4 or later. It usesz.xorforoneOf.effectoutput needs Effect v4 and importseffect/Schema.typesoutput has no import.
Keywords
Supported keywords:
- Types and values:
type,enum,const. - String:
minLength,maxLength,pattern,format. - Number:
minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf. - Object:
properties,required,additionalProperties,minProperties,maxProperties. - Array:
items,prefixItems,minItems,maxItems,uniqueItems. - Composition:
anyOf,oneOf,allOf. - References: local
$refto a$defsentry of the same document, and a root$defs. A$defsentry becomes a local declaration that is not exported. - Annotations:
title,description,default,examples,deprecated,readOnly,writeOnly. - Ignored:
$schema,$id,$anchor,$comment,$vocabularyand every keyword that starts withx-.
A constraint keyword needs type. minLength, pattern, format, the number
bounds, properties, required, additionalProperties, minProperties,
maxProperties, items, prefixItems, minItems, maxItems and
uniqueItems only constrain values of their own type, so a schema without
type also accepts every other value, and no target can say that. The
generator does not guess a type: each such keyword fails the run with
unsupported_keyword_combination, and keyword is the constraint. This holds
in allOf, anyOf and oneOf members, and in $defs entries, too.
A name in required that properties does not declare is a property that
additionalProperties describes: any value, or the additionalProperties
schema. With additionalProperties: false no object can satisfy it, so it
fails with unsupported_keyword_combination (required+additionalProperties)
at the required entry.
prefixItems describes the positions that exist and does not make them exist.
A position is required only below minItems; later positions are optional
tuple elements ([A, B?]). A position at or beyond maxItems does not exist,
and items after the last one is dropped.
These keywords fail the run, because the generator cannot express them:
contains, dependentRequired, if, then, else, not,
patternProperties, unevaluatedItems, unevaluatedProperties,
$dynamicRef, $defs below the root, a remote $ref, a recursive $ref, and
a $ref that does not point to a $defs entry. Any other keyword that does
not start with x- is an unknown_keyword error. The generator never
degrades a shape that changes what the schema accepts.
A validation-only keyword with no equivalent in a target is dropped. It stays
as an annotation and gives a warning (dropped_keyword or
format_annotation_only).
Target limits
types: a type cannot check values. Validation keywords (minLength,maxLength,pattern,format, the number bounds, the property and item counts,uniqueItems) become JSDoc tags and givedropped_keywordwarnings.zod: objects withadditionalProperties: falsearez.strictObject. An object with no properties and noadditionalPropertiesis an open record, as in the other targets.formatis checked fordate-time,email,uuidanduri; any other format stays as.metadata and givesformat_annotation_only.uniqueItems,minPropertiesandmaxPropertiesstay as.metadata and givedropped_keyword.effect:Schema.Structhas no closed object.additionalProperties: falseis not enforced and gives oneclosed_object_unenforcedwarning per object; excess keys are rejected only with the decode optiononExcessProperty: "error". Onlyformat: uuidis a format check; any other format stays as an annotation and givesformat_annotation_only. An object that has declared keys and no extra schema cannot count its keys, sominPropertiesandmaxPropertiesstay as annotations and givedropped_keyword.allOfmerges plain objects only; other members (allof_not_plain_objects, also for a$refto one), and members that declare one property in different ways (allof_property_conflict), fail the run. Keywords of one schema object that do not merge, for example a$refwith a constraint or atypewithoneOf, fail withunsupported_keyword_combination; itskeywordlists them joined with+.
Checks
bun test tests/package-contract.test.ts
bun run type-check
bun run build
bun run test:pack