From df6b9c7daed3595b795e042e12676abba113e789 Mon Sep 17 00:00:00 2001 From: mnkj0021 Date: Tue, 29 Sep 2026 12:55:37 +0000 Subject: [PATCH] feat: add Zod v4 output format --- README.md | 10 +++++- examples/zod4_compat.cddl | 3 ++ src/engines/zod.rs | 64 +++++++++++++++++++++++++++++++-------- src/main.rs | 10 ++++++ tests/zod.rs | 42 +++++++++++++++++++++++++ 5 files changed, 116 insertions(+), 13 deletions(-) create mode 100644 examples/zod4_compat.cddl diff --git a/README.md b/README.md index a3653e3..b2d8baf 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,14 @@ A commandline utility for converting CDDL to various formats. 1. Clone this repo and `cd` into it. 2. `cargo run -- path/to/file.cddl` +The default output format is TypeScript. Zod schemas can be generated for either +major version without changing their runtime schema expressions: + +```sh +cargo run -- path/to/file.cddl --format zod # Zod v3 type annotations +cargo run -- path/to/file.cddl --format zod4 # Zod v4 type annotations +``` + ## Tips ### Formatting output @@ -26,4 +34,4 @@ cargo run -- path/to/file.cddl | prettier --stdin-filepath=$outfile > $outfile ## Limitations -1. Only [`TypeScript`](https://www.typescriptlang.org/) and [`Zod v4`](https://zod.dev/) is supported at the moment. +1. Only [`TypeScript`](https://www.typescriptlang.org/) and [`Zod`](https://zod.dev/) (v3 and v4) are supported at the moment. diff --git a/examples/zod4_compat.cddl b/examples/zod4_compat.cddl new file mode 100644 index 0000000..18275e1 --- /dev/null +++ b/examples/zod4_compat.cddl @@ -0,0 +1,3 @@ +Choice = text / int +Mode = "decline" / "dedicated-worker" / "-0" +Events = [+ text] diff --git a/src/engines/zod.rs b/src/engines/zod.rs index d1c3d19..dab5091 100644 --- a/src/engines/zod.rs +++ b/src/engines/zod.rs @@ -46,6 +46,12 @@ struct PostambleOptions { print_flatten: bool, } +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +enum Version { + V3, + V4, +} + pub struct Engine where Stdout: Write, @@ -54,6 +60,7 @@ where nested_group_choices: Vec, nested_type1: Vec, is_type_mode: bool, + version: Version, cyclic_rules: std::collections::HashSet, #[allow(dead_code)] postamble_options: PostambleOptions, @@ -78,10 +85,23 @@ fn calculate_occurrence(occur: &Option>) -> (usize, us impl<'a, 'b: 'a, 'c, Stdout: Write, Stderr: Write> Engine { pub fn with_writers(stdout: Stdout, stderr: Stderr) -> Engine { + Self::with_writers_for_version(stdout, stderr, Version::V3) + } + + pub fn with_writers_zod4(stdout: Stdout, stderr: Stderr) -> Engine { + Self::with_writers_for_version(stdout, stderr, Version::V4) + } + + fn with_writers_for_version( + stdout: Stdout, + stderr: Stderr, + version: Version, + ) -> Engine { Engine { nested_group_choices: Vec::new(), nested_type1: Vec::new(), is_type_mode: false, + version, cyclic_rules: std::collections::HashSet::new(), postamble_options: PostambleOptions { #[cfg(feature = "vector_groups")] @@ -104,6 +124,13 @@ impl<'a, 'b: 'a, 'c, Stdout: Write, Stderr: Write> Engine { unimplemented!(); } } + + fn print_union_type_start(&mut self) { + match self.version { + Version::V3 => write!(self.stdout, "z.ZodUnion<["), + Version::V4 => write!(self.stdout, "z.ZodUnion) -> bool { // Special case for string enums if t.type_choices.len() > 1 @@ -113,13 +140,26 @@ impl<'a, 'b: 'a, 'c, Stdout: Write, Stderr: Write> Engine { .all(|type2| matches!(type2, cddl::ast::Type2::TextValue { .. })) { if self.is_type_mode { - write!(self.stdout, "z.ZodEnum<["); - for type2 in t.type_choices.iter().map(|choice| &choice.type1.type2) { - if let cddl::ast::Type2::TextValue { value, .. } = type2 { - write!(self.stdout, "\"{}\",", value); + match self.version { + Version::V3 => { + write!(self.stdout, "z.ZodEnum<["); + for type2 in t.type_choices.iter().map(|choice| &choice.type1.type2) { + if let cddl::ast::Type2::TextValue { value, .. } = type2 { + write!(self.stdout, "\"{}\",", value); + } + } + write!(self.stdout, "]>"); + } + Version::V4 => { + write!(self.stdout, "z.ZodEnum<{{"); + for type2 in t.type_choices.iter().map(|choice| &choice.type1.type2) { + if let cddl::ast::Type2::TextValue { value, .. } = type2 { + write!(self.stdout, "\"{}\":\"{}\";", value, value); + } + } + write!(self.stdout, "}}>"); } } - write!(self.stdout, "]>"); } else { write!(self.stdout, "z.enum(["); for type2 in t.type_choices.iter().map(|choice| &choice.type1.type2) { @@ -137,7 +177,7 @@ impl<'a, 'b: 'a, 'c, Stdout: Write, Stderr: Write> Engine { fn visit_array(&mut self, g: &'b cddl::ast::Group<'a>) -> cddl::visitor::Result { if g.group_choices.len() != 1 { if self.is_type_mode { - write!(self.stdout, "z.ZodUnion<["); + self.print_union_type_start(); } else { write!(self.stdout, "z.union(["); } @@ -369,7 +409,7 @@ impl<'a, 'b: 'a, 'c, Stdout: Write, Stderr: Write> Engine { } if upper < MAX_ARRAYS { if self.is_type_mode { - write!(self.stdout, "z.ZodUnion<["); + self.print_union_type_start(); for bound in lower..upper + 1 { if bound != 0 { write!(self.stdout, ","); @@ -404,7 +444,7 @@ impl<'a, 'b: 'a, 'c, Stdout: Write, Stderr: Write> Engine { } else if self.is_type_mode { write!(self.stdout, "z.ZodArray<"); self.visit_type(&entry.entry_type)?; - if lower == 1 { + if lower == 1 && self.version == Version::V3 { write!(self.stdout, ", \"atleastone\""); } write!(self.stdout, ">"); @@ -597,7 +637,7 @@ impl<'a, 'b: 'a, Stdout: Write, Stderr: Write> Visitor<'a, 'b, Error> for Engine } if t.type_choices.len() != 1 { if self.is_type_mode { - write!(self.stdout, "z.ZodUnion<["); + self.print_union_type_start(); } else { write!(self.stdout, "z.union(["); } @@ -688,7 +728,7 @@ impl<'a, 'b: 'a, Stdout: Write, Stderr: Write> Visitor<'a, 'b, Error> for Engine self.print_group_joiner(); if matches!(calculate_occurrence(&ge.occur), (0, max) if max > 0) { if self.is_type_mode { - write!(self.stdout, "z.ZodUnion<["); + self.print_union_type_start(); self.visit_type_groupname_entry(ge)?; write!(self.stdout, ",z.ZodObject<{{}}>]>"); } else { @@ -704,7 +744,7 @@ impl<'a, 'b: 'a, Stdout: Write, Stderr: Write> Visitor<'a, 'b, Error> for Engine self.print_group_joiner(); if matches!(calculate_occurrence(&occur), (0, max) if max > 0) { if self.is_type_mode { - write!(self.stdout, "z.ZodUnion<["); + self.print_union_type_start(); self.visit_group(group)?; write!(self.stdout, ",z.ZodObject<{{}}>]>"); } else { @@ -755,7 +795,7 @@ impl<'a, 'b: 'a, Stdout: Write, Stderr: Write> Visitor<'a, 'b, Error> for Engine fn visit_group(&mut self, g: &'b cddl::ast::Group<'a>) -> cddl::visitor::Result { if g.group_choices.len() != 1 { if self.is_type_mode { - write!(self.stdout, "z.ZodUnion<["); + self.print_union_type_start(); } else { write!(self.stdout, "z.union(["); } diff --git a/src/main.rs b/src/main.rs index 738bb7d..14c32dd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,6 +21,7 @@ use std::path::PathBuf; enum EngineType { TypeScript, Zod, + Zod4, } /// Simple program to greet a person @@ -56,6 +57,15 @@ fn main() -> Result<()> { engine.visit_cddl(&cddl)?; engine.print_postamble(); } + EngineType::Zod4 => { + let mut engine = cddlconv::engines::zod::Engine::with_writers_zod4( + std::io::stdout(), + std::io::stderr(), + ); + engine.print_preamble(); + engine.visit_cddl(&cddl)?; + engine.print_postamble(); + } }; Ok(()) diff --git a/tests/zod.rs b/tests/zod.rs index c255c62..5330f9e 100644 --- a/tests/zod.rs +++ b/tests/zod.rs @@ -45,3 +45,45 @@ test!( "examples/array_occurences.cddl" ); test!(it_works_with_enums, "examples/enums.cddl"); + +#[test] +fn zod4_uses_v4_type_annotations() { + let input = std::fs::read_to_string("examples/zod4_compat.cddl").unwrap(); + let cddl = cddl::parser::cddl_from_str(&input, true).unwrap(); + let stdout = BufWriter::new(Vec::new()); + let stderr = BufWriter::new(Vec::new()); + let mut engine = cddlconv::engines::zod::Engine::with_writers_zod4(stdout, stderr); + + engine.visit_cddl(&cddl).unwrap(); + engine.print_postamble(); + + let (stdout, stderr) = engine.into_writers(); + let stdout = String::from_utf8(stdout.into_inner().unwrap()).unwrap(); + let stderr = String::from_utf8(stderr.into_inner().unwrap()).unwrap(); + + assert!(stderr.is_empty()); + assert!(stdout.contains("z.ZodUnion")); + assert!(stdout.contains( + r#"z.ZodEnum<{"decline":"decline";"dedicated-worker":"dedicated-worker";"-0":"-0";}>"# + )); + assert!(stdout.contains("z.ZodArray")); + assert!(!stdout.contains(r#""atleastone""#)); +} + +#[test] +fn default_zod_output_remains_v3_compatible() { + let input = std::fs::read_to_string("examples/zod4_compat.cddl").unwrap(); + let cddl = cddl::parser::cddl_from_str(&input, true).unwrap(); + let stdout = BufWriter::new(Vec::new()); + let stderr = BufWriter::new(Vec::new()); + let mut engine = cddlconv::engines::zod::Engine::with_writers(stdout, stderr); + + engine.visit_cddl(&cddl).unwrap(); + + let (stdout, _) = engine.into_writers(); + let stdout = String::from_utf8(stdout.into_inner().unwrap()).unwrap(); + + assert!(stdout.contains("z.ZodUnion<[z.ZodString,z.ZodNumber]>")); + assert!(stdout.contains(r#"z.ZodEnum<["decline","dedicated-worker","-0",]>"#)); + assert!(stdout.contains(r#"z.ZodArray"#)); +}