On This Page (11)
- Toolchain & Exact Commands
- Pipeline 1 — Core 30 Contracts (kicad-monkey)
- Pipeline 2 — Cruncher Standalone Config (PcbSvgConfig)
- Key Engineering Projections
- 1. Safe Integers & Decimal-String uint64 Across JS/WASM Boundaries
- 2. Out-of-Band Slot-Indexed Binary Payloads
- 3. Closed Object Enforcement Across All Three Languages
- 4. kicad-monkey-codegen Rust AST Transforms
- 5. Python Strict JSON Preflight (preflight_strict_json)
- Public Repository vs. Development Monorepo Boundary
- Related
The Multi-Language Codegen Pipeline
Writing a contract once in TypeSpec only pays off if every target language stays mechanically locked to the compiled schemas. kicad-monkey enforces that lock with deterministic generators and --check CI gates across JSON Schema, Python, TypeScript, and Rust.
Toolchain & Exact Commands
Pipeline 1 — Core 30 Contracts (kicad-monkey)
The core catalog lives under src/tsp/kicad_monkey/ (rooted at main.tsp) and compiles with @typespec/compiler and @typespec/json-schema (tspconfig.yaml sets seal-object-schemas: true and warn-as-error: true):
src/tsp/kicad_monkey/*.tsp (8 modules + main.tsp)
│
│ npm run generate:contracts
▼
contracts/generated/schema/*.json (30 Draft 2020-12 schemas)
├── npm run generate:python ──▶ src/py/kicad_monkey/contracts/generated.py (msgspec)
├── npm run generate:typescript ──▶ src/ts/kicad_monkey/contracts/generated/*.ts (strict TS)
└── cargo run -p kicad-monkey-codegen --locked
──▶ src/rs/kicad-monkey-contracts/src/generated/*.rs (serde)| Stage | Generate Command | Check Command | Generator Tooling |
|---|---|---|---|
| TypeSpec → JSON Schema | npm run generate:contracts | npm run check:typespec (compile check: --no-emit, warn-as-error) | @typespec/compiler + @typespec/json-schema (seal-object-schemas: true, warn-as-error: true) |
| JSON Schema → Python | npm run generate:python | npm run check:python-generation | scripts/generate-contract-bindings.mjs --python → msgspec.Struct |
| JSON Schema → TypeScript | npm run generate:typescript | npm run check:typescript-generation | scripts/generate-contract-bindings.mjs --typescript (json-schema-to-typescript + tsc --noEmit -p tsconfig.contracts.json) |
| JSON Schema → Rust | cargo run --package kicad-monkey-codegen --locked | cargo run --package kicad-monkey-codegen --locked -- --check | kicad-monkey-codegen (schemars + typify + syn + prettyplease + rustfmt) |
npm run check:typespec verifies TypeSpec compilation (--no-emit with warn-as-error), while the three binding --check commands above — plus node packages/kicad_cruncher/scripts/generate-svg-contracts.mjs --check for standalone PcbSvgConfig — regenerate in memory and fail with a non-zero exit code if any committed artifact differs by even one byte.
Pipeline 2 — Cruncher Standalone Config (PcbSvgConfig)
kicad-cruncher owns its own standalone TypeSpec root for pcb.svg.config without touching the core kicad-monkey contract catalog:
packages/kicad_cruncher/src/tsp/kicad_cruncher/main.tsp
│
│ node packages/kicad_cruncher/scripts/generate-svg-contracts.mjs [--check]
▼
├── packages/kicad_cruncher/docs/contracts/pcb_svg_config.a0.schema.json
├── packages/kicad_cruncher/src/ts/contracts/pcb-svg-config.ts
└── packages/kicad_cruncher/src/rs/kicad-cruncher-cli/src/pcb_svg/generated.rs
(via `cargo run --locked -p kicad-monkey-codegen -- --standalone ...`)The --standalone mode of kicad-monkey-codegen reuses the same Draft 2020-12 normalization and typify/syn machinery as the core pipeline, then runs a dedicated config projection pass (config_projection.rs) that wraps optional override fields in tri-state Field<T> structs so the native Rust k3 pcb-svg merger can distinguish omitted keys from explicit null resets. The Python pcb-svg config loader remains handwritten.
Key Engineering Projections
Raw JSON Schema code generators rarely produce sound, ergonomic bindings out of the box across Python, Rust, and TypeScript. kicad-monkey's codegen scripts and kicad-monkey-codegen apply five deliberate engineering projections so every target language enforces the same invariants.
1. Safe Integers & Decimal-String uint64 Across JS/WASM Boundaries
JavaScript numbers are IEEE-754 float64 values that silently lose integer precision outside ±(2^53 - 1) (±9,007,199,254,740,991). Two contract scalars eliminate silent truncation:
JavaScriptSafeInteger(safeintin TypeSpec): bounded to[-9007199254740991, 9007199254740991]. In Python it projects toAnnotated[int, Meta(ge=-9007199254740991, le=9007199254740991)]; in Rust it projects to the validated transparent newtypeJavaScriptSafeInteger(i64)whoseDeserializeimpl rejects out-of-range values. Nanometre coordinates up to ±9,000 km fit comfortably inside this bound.- Decimal-string 64-bit unsigned scalars: TypeSpec
uint64fields (SourcePosition,FormSpan) and theCanonicalUint64Decimalscalar (SourceBundleManifest.source_bytes) both serialize as canonical base-10 decimal strings so full 64-bit values round-trip losslessly through JSON, JavaScript, WASM, Python, and Rust.
2. Out-of-Band Slot-Indexed Binary Payloads
Real KiCad projects routinely embed megabytes of .kicad_pcb S-expressions, raster sheet images, and OpenType/TrueType font files. Inlining those bytes as base64 inside JSON envelopes multiplies memory usage, slows parsing, and bloats wire logs.
Instead, the two manifest contracts keep raw bytes out-of-band in parallel binary buffers indexed by zero-based slot: SourceBundleManifest (source-bundle-a0.tsp) carries SourceSlot indices and CanonicalUint64Decimal source_bytes lengths, while FontBundleManifest (font-text-a0.tsp) carries uint32 slot indices alongside Sha256Hex sha256 digests. JSON stays compact and fast to validate; binary payloads stay zero-copy.
3. Closed Object Enforcement Across All Three Languages
tspconfig.yaml enables seal-object-schemas: true, which causes @typespec/json-schema to emit "unevaluatedProperties": { "not": {} } on every closed model. Each language generator lowers that seal to native strictness:
- Python (
msgspec): every generated struct declaresforbid_unknown_fields=Trueandfrozen=True. Typos or unexpected keys fail immediately at decode time instead of being silently ignored. - Rust (
serde): generated structs carry#[serde(deny_unknown_fields)](stripped only on intentional extension points, if any). - TypeScript (
json-schema-to-typescript+tsc): the generator runs withunknownAny: false, asserts that no emitted.tsfile containsanyorany[], and type-checks under stricttsconfig.contracts.json(includingexactOptionalPropertyTypes).
4. kicad-monkey-codegen Rust AST Transforms
typify expects JSON Schema Draft 07 / schemars::schema::RootSchema shapes and produces verbose generic boilerplate if fed raw Draft 2020-12 output. kicad-monkey-codegen bridges that gap cleanly in three stages (schema normalization → typify::TypeSpace → syn AST rewrite + prettyplease + rustfmt):
anyOf→oneOfenum promotion: Draft 2020-12 TypeSpec unions emitanyOf;kicad-monkey-codegenrewrites tagged and nullableanyOfbranches intooneOfforms thattypifylowers into clean Rustenums rather than untypedserde_json::Value.- Validated transparent newtypes: constrained scalars map onto dedicated checked wrapper types in
kicad-monkey-contractsinstead of raw primitives:JavaScriptSafeInteger([-2^53+1, 2^53-1])SchematicDefaultLineWidthNm(>= 84_700nm effective plot pen floor)NonNegativeFiniteFloat(finitef64 >= 0.0)FiniteFloat(finitef64, rejectingNaN/Infinity)PositiveU32/NonZeroU32(strictly> 0)StableTextId(ASCII identifier syntax enforced onFromStr/Deserialize)
- Tri-state optional-vs-null presence: where a wire field distinguishes omitted from explicitly
nullfrom present value, codegen emitsOption<Option<String>>(in core contracts) orField<T>(Missing/Null/Value(T)in standalonePcbSvgConfig). - Literal
kinddeserializers: discriminated union variants wire custom#[serde(deserialize_with = "...")]helpers (deserialize_thick_segment_kind,deserialize_wire_record_kind, etc.) so a struct can never be deserialized with a mismatchedkindtag. - Deterministic map ordering: map-valued fields project to
BTreeMaprather thanHashMap, guaranteeing identical key order across platforms and runs. - Direct
cad-text-realizationtype reuse: shaping and outline transport types (ShapingInput,ShapedGlyph,OutlineCommand,Sha256Hex,OpenTypeTag, etc.) map straight ontocad_text_realization::contract::*types rather than generating duplicate parallel structs. - Zero
schemarsruntime dependency:schemarsandtypifylive only inkicad-monkey-codegen(build/dev time). The runtime librarykicad-monkey-contractsdepends only oncad-text-realization,serde,serde_json, andsha2.
5. Python Strict JSON Preflight (preflight_strict_json)
JSON parsers — including fast native decoders — often accept duplicate object keys (silently keeping the last value) or non-standard float tokens (NaN, Infinity). Before decoding generated contract payloads, Python's _generated_codecs.py runs preflight_strict_json (_strict_json.py) to reject:
- Invalid UTF-8 byte sequences or unpaired UTF-16 surrogates,
- Duplicate keys within any JSON object at any nesting depth, and
- Non-finite floating-point tokens (
NaN,Infinity,-Infinity).
Python msgspec tagged unions also handle an edge case automatically in scripts/generate-contract-bindings.mjs: because msgspec cannot assign multiple literal tag values to a single Struct, union members whose discriminator is an enum expand into one tagged Struct per tag value beneath a Union alias that preserves the published type name.
Public Repository vs. Development Monorepo Boundary
The public wavenumber-eng/kicad_monkey repository ships everything a downstream consumer needs to validate and use every contract immediately — with no Node.js or TypeSpec installation required:
- Compiled Draft 2020-12 JSON Schemas (
contracts/generated/schema/*.jsonanddocs/contracts/*.schema.json), - Published TypeSpec
.tspsources for inspection and auditing, - Pre-generated Rust (
kicad-monkey-contracts), Python (kicad_monkey.contracts.generated), and TypeScript bindings ready to compile or import.
Regenerating bindings after editing a .tsp module requires Node.js (npm + @typespec/compiler) and Cargo (kicad-monkey-codegen) in the full development workspace. Downstream users consuming kicad-monkey from PyPI or embedding the Rust crates never need to invoke TypeSpec or Node.js.
Related
- Why TypeSpec & Contract Architecture — wire-shape vs. adapter boundary and the four contract tiers.
- Complete Contract & Schema Catalog — every schema ID, wire field summary, and negative assertion.
- Rust Crates Reference —
kicad-monkey-contractsandkicad-monkey-codegencrate details.