use serde_json::Value;
pub fn to_zod<S>(schema: &S) -> String
where
S: crate::openapi::JsonSchema,
{
convert(Zod, &schema.json_schema())
}
pub fn to_valibot<S>(schema: &S) -> String
where
S: crate::openapi::JsonSchema,
{
convert(Valibot, &schema.json_schema())
}
pub fn to_zod4<S>(schema: &S) -> String
where
S: crate::openapi::JsonSchema,
{
convert(Zod4, &schema.json_schema())
}
pub fn to_ts_type<S>(schema: &S) -> String
where
S: crate::openapi::JsonSchema,
{
ts_type(&schema.json_schema()).0
}
pub fn to_openapi<S>(schema: &S) -> Value
where
S: crate::openapi::JsonSchema,
{
schema.json_schema()
}
pub fn openapi_refs(schema: &Value) -> Vec<String> {
collect_ref_paths(schema)
}
pub trait ToZod {
fn to_zod() -> String;
fn zod_name() -> String {
short_type_name::<Self>()
}
fn to_zod_export() -> String {
zod_export(&Self::zod_name(), &Self::to_zod())
}
}
pub trait ToValibot {
fn to_valibot() -> String;
fn valibot_name() -> String {
short_type_name::<Self>()
}
fn to_valibot_export() -> String {
valibot_export(&Self::valibot_name(), &Self::to_valibot())
}
}
pub trait ToZod4 {
fn to_zod4() -> String;
fn zod4_name() -> String {
short_type_name::<Self>()
}
fn to_zod4_export() -> String {
zod4_export(&Self::zod4_name(), &Self::to_zod4())
}
}
pub trait ToTsType {
fn to_ts_type() -> String;
fn ts_type_name() -> String {
short_type_name::<Self>()
}
fn to_ts_type_export() -> String {
ts_type_export(&Self::ts_type_name(), &Self::to_ts_type())
}
}
pub fn zod_export(name: &str, expr: &str) -> String {
format!(
"export const {0}Schema = {1};\nexport type {0} = z.infer<typeof {0}Schema>;\n",
name, expr
)
}
pub fn zod4_export(name: &str, expr: &str) -> String {
zod_export(name, expr)
}
pub fn ts_type_export(name: &str, expr: &str) -> String {
format!("export type {} = {};\n", name, expr)
}
pub fn valibot_export(name: &str, expr: &str) -> String {
format!(
"export const {0}Schema = {1};\nexport type {0} = v.InferOutput<typeof {0}Schema>;\n",
name, expr
)
}
fn short_type_name<T: ?Sized>() -> String {
let full = std::any::type_name::<T>();
let base = full.split('<').next().unwrap_or(full);
base.rsplit("::").next().unwrap_or(base).to_string()
}
pub trait ToOpenApi {
fn to_openapi() -> Value;
}
pub trait ToRefs {
fn to_refs() -> Vec<String>;
}
#[doc(hidden)]
#[macro_export]
macro_rules! __ts_impl_to_zod {
($ty:ty $(, $name:expr)?) => {
impl $crate::ts::ToZod for $ty {
fn to_zod() -> ::std::string::String {
$crate::ts::__to_zod_from_value(&<$ty>::json_schema())
}
$(
fn zod_name() -> ::std::string::String {
::std::string::String::from($name)
}
)?
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __ts_impl_to_zod4 {
($ty:ty $(, $name:expr)?) => {
impl $crate::ts::ToZod4 for $ty {
fn to_zod4() -> ::std::string::String {
$crate::ts::__to_zod4_from_value(&<$ty>::json_schema())
}
$(
fn zod4_name() -> ::std::string::String {
::std::string::String::from($name)
}
)?
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __ts_impl_to_ts_type {
($ty:ty $(, $name:expr)?) => {
impl $crate::ts::ToTsType for $ty {
fn to_ts_type() -> ::std::string::String {
$crate::ts::__to_ts_type_from_value(&<$ty>::json_schema())
}
$(
fn ts_type_name() -> ::std::string::String {
::std::string::String::from($name)
}
)?
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __ts_impl_to_openapi {
($ty:ty $(, $name:expr)?) => {
impl $crate::ts::ToOpenApi for $ty {
fn to_openapi() -> $crate::serde_json::Value {
<$ty>::json_schema()
}
}
impl $crate::ts::ToRefs for $ty {
fn to_refs() -> ::std::vec::Vec<::std::string::String> {
$crate::ts::openapi_refs(&<$ty>::json_schema())
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __ts_impl_to_valibot {
($ty:ty $(, $name:expr)?) => {
impl $crate::ts::ToValibot for $ty {
fn to_valibot() -> ::std::string::String {
$crate::ts::__to_valibot_from_value(&<$ty>::json_schema())
}
$(
fn valibot_name() -> ::std::string::String {
::std::string::String::from($name)
}
)?
}
};
}
#[doc(inline)]
pub use crate::__ts_impl_to_openapi as impl_to_openapi;
#[doc(inline)]
pub use crate::__ts_impl_to_ts_type as impl_to_ts_type;
#[doc(inline)]
pub use crate::__ts_impl_to_valibot as impl_to_valibot;
#[doc(inline)]
pub use crate::__ts_impl_to_zod as impl_to_zod;
#[doc(inline)]
pub use crate::__ts_impl_to_zod4 as impl_to_zod4;
#[derive(Clone, Copy, PartialEq)]
enum Target {
Zod,
Zod4,
Valibot,
}
use Target::{Valibot, Zod, Zod4};
enum Act {
Plain(String),
Check(String, String),
Note(String),
}
fn plain(s: impl Into<String>) -> Act {
Act::Plain(s.into())
}
fn check(f: &str, msg: &str) -> Act {
Act::Check(f.to_string(), msg.to_string())
}
const TIME_RE: &str = r"([01]\d|2[0-3]):[0-5]\d(:[0-5]\d(\.\d{1,9})?)?";
const DATETIME_TIME_RE: &str = r"([01]\d|2[0-3]):[0-5]\d:[0-5]\d(\.\d{1,9})?";
const CALENDAR_FN: &str = "(s) => { const d = new Date(s.slice(0, 10) + \"T00:00:00Z\"); return !isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s.slice(0, 10); }";
const LUHN_FN: &str = "(s) => { if (!/^[\\d -]*$/.test(s)) return false; const d = s.replace(/\\D/g, \"\"); if (d.length < 12 || d.length > 19) return false; let sum = 0; for (let i = 0; i < d.length; i++) { let n = +d[d.length - 1 - i]; if (i % 2) { n *= 2; if (n > 9) n -= 9; } sum += n; } return sum % 10 === 0; }";
const JSON_FN: &str = "(s) => { try { JSON.parse(s); return true; } catch { return false; } }";
const LABEL_RE: &str = "[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?";
fn format_acts(t: Target, fmt: &str) -> Vec<Act> {
if t == Zod4 {
if let Some((base, mut extra)) = zod4_format(fmt) {
extra.push(check(
&format!("(s) => {}.safeParse(s).success", base),
&format!("Invalid {}", fmt),
));
return extra;
}
}
let both = |zod: &str, valibot: &str| match t {
Zod | Zod4 => plain(zod),
Valibot => plain(valibot),
};
let re = |r: String| plain(format!("regex({})", r));
let host = format!("(?=.{{1,253}}$){0}(\\.{0})*", LABEL_RE);
let http = || re("/^https?:\\/\\/\\S+$/".to_string());
let uuid_v = |n: u8| {
vec![
both("uuid()", "uuid()"),
re(format!("/^[0-9a-fA-F]{{8}}-[0-9a-fA-F]{{4}}-{}/", n)),
]
};
let is_ip = |n: u8| match t {
Zod => format!(
"z.string().ip({{ version: \"v{}\" }}).safeParse(a).success",
n
),
Zod4 => format!("z.ipv{}().safeParse(a).success", n),
Valibot => format!("v.safeParse(v.pipe(v.string(), v.ipv{}()), a).success", n),
};
match fmt {
"email" => vec![both("email()", "email()")],
"uri" | "url" | "url-strict" => vec![both("url()", "url()"), http()],
"uuid" => vec![both("uuid()", "uuid()")],
"uuid-v1" => uuid_v(1),
"uuid-v4" => uuid_v(4),
"uuid-v7" => uuid_v(7),
"ipv4" => vec![both("ip({ version: \"v4\" })", "ipv4()")],
"ipv6" => vec![both("ip({ version: \"v6\" })", "ipv6()")],
"ip" if t == Zod4 => vec![check(
"(s) => z.ipv4().safeParse(s).success || z.ipv6().safeParse(s).success",
"Invalid IP",
)],
"ip" => vec![both("ip()", "ip()")],
"cidr" => vec![check(
&format!(
"(s) => {{ const i = s.indexOf(\"/\"); if (i < 0) return false; const a = s.slice(0, i), p = s.slice(i + 1); if (!/^(0|[1-9]\\d{{0,2}})$/.test(p)) return false; return {} ? +p <= 32 : {} && +p <= 128; }}",
is_ip(4),
is_ip(6)
),
"Invalid CIDR",
)],
"date" => vec![
re("/^\\d{4}-\\d{2}-\\d{2}$/".to_string()),
check(CALENDAR_FN, "Invalid date"),
],
"date-time" => vec![
re(format!(
"/^\\d{{4}}-\\d{{2}}-\\d{{2}}[Tt]{}([Zz]|[+-]([01]\\d|2[0-3]):[0-5]\\d)?$/",
DATETIME_TIME_RE
)),
check(CALENDAR_FN, "Invalid datetime"),
],
"time" => vec![re(format!("/^{}$/", TIME_RE))],
"hostname" => vec![re(format!("/^{}$/", host))],
"mac" => vec![re("/^[0-9A-Fa-f]{2}(:[0-9A-Fa-f]{2}){5}$/".to_string())],
"hex" => vec![re("/^[0-9A-Fa-f]+$/".to_string())],
"slug" => vec?$/".to_string())],
"semver" => vec![re(
"/^v?\\d+\\.\\d+\\.\\d+(?:[-+][\\s\\S]*)?$/".to_string(),
)],
"jwt" => vec![re(
"/^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/".to_string(),
)],
"ascii" => vec![re("/^[\\x00-\\x7F]*$/".to_string())],
"alpha" => vec![re("/^[A-Za-z]*$/".to_string())],
"alphanumeric" => vec![re("/^[A-Za-z0-9]*$/".to_string())],
"lowercase" => vec![check("(s) => s === s.toLowerCase()", "Must be lowercase")],
"uppercase" => vec![check("(s) => s === s.toUpperCase()", "Must be uppercase")],
"locale" => vec![re("/^[a-z]{2}(-[A-Z]{2})?$/".to_string())],
"country-code" => vec![re("/^[A-Z]{2}$/".to_string())],
"currency-code" => vec![re("/^[A-Z]{3}$/".to_string())],
"cron" => vec![re(
"/^\\s*[\\d*\\/,?-]+(\\s+[\\d*\\/,?-]+){4,5}\\s*$/".to_string(),
)],
"credit-card" => vec![check(LUHN_FN, "Invalid credit card")],
"phone" => vec![re(
"/^\\+(?=(?:\\D*\\d){8,15}\\D*$)[\\d ()-]*$/".to_string(),
)],
"phone-e164" => vec![re("/^\\+[1-9]\\d{1,14}$/".to_string())],
"color" => {
let n8 = "\\s*\\+?0*(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\s*";
let pct = "\\s*\\+?0*(?:100|[1-9]?\\d)%\\s*";
let hue = "\\s*\\+?0*(?:360|3[0-5]\\d|[12]?\\d?\\d)\\s*";
vec![re(format!(
"/^(?:#(?:[0-9a-f]{{6}}|[0-9a-f]{{8}})|rgb\\({0},{0},{0}\\)|hsl\\({1},{2},{2}\\))$/i",
n8, hue, pct
))]
}
"byte" => vec![re(
"/^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{4}|[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)$/"
.to_string(),
)],
"base64url" => vec![re(
"/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{4}|[A-Za-z0-9_-]{2}(?:==?)?|[A-Za-z0-9_-]{3}=?)$/"
.to_string(),
)],
"json" => vec![check(JSON_FN, "Invalid JSON")],
"cuid2" => vec![re("/^[a-z][a-z0-9]{1,31}$/".to_string())],
"ulid" => vec![re("/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i".to_string())],
"nanoid" => vec![re("/^[A-Za-z0-9_-]+$/".to_string())],
"emoji" => vec![re(
"/^[\\u{1F600}-\\u{1F64F}\\u{1F300}-\\u{1F5FF}\\u{1F680}-\\u{1F6FF}\\u{1F1E0}-\\u{1F1FF}\\u{2702}-\\u{27B0}\\u{2600}-\\u{26FF}\\u{FE00}-\\u{FE0F}\\u{1F900}-\\u{1F9FF}\\u{1FA00}-\\u{1FAFF}\\u{231A}-\\u{231B}\\u{23E9}-\\u{23F3}\\u{23F8}-\\u{23FA}\\u{E0020}-\\u{E007F}\\u{20E3}\\u{200D}\\u{2B50}]+$/u"
.to_string(),
)],
_ => vec![],
}
}
fn zod4_format(fmt: &str) -> Option<(String, Vec<Act>)> {
let uuid_v = |n: u8| {
Some((
"z.guid()".to_string(),
vec![plain(format!(
"regex(/^[0-9a-fA-F]{{8}}-[0-9a-fA-F]{{4}}-{}/)",
n
))],
))
};
let base = match fmt {
"email" => "z.email()",
"uuid" => "z.guid()",
"uuid-v1" => return uuid_v(1),
"uuid-v4" => return uuid_v(4),
"uuid-v7" => return uuid_v(7),
"uri" | "url" | "url-strict" => {
return Some((
"z.url()".to_string(),
vec![plain("regex(/^https?:\\/\\/\\S+$/)")],
));
}
"ipv4" => "z.ipv4()",
"ipv6" => "z.ipv6()",
"date" => "z.iso.date()",
"time" => {
return Some((
"z.iso.time()".to_string(),
vec![plain(format!("regex(/^{}$/)", TIME_RE))],
));
}
_ => return None,
};
Some((base.to_string(), vec![]))
}
fn js_regex(p: &str) -> Option<(String, String)> {
let mut flags = String::new();
let mut rest = p;
while let Some(r) = rest.strip_prefix("(?") {
let Some(end) = r.find(')') else { break };
let f = &r[..end];
if f.is_empty() || !f.chars().all(|c| matches!(c, 'i' | 'm' | 's')) {
break;
}
for c in f.chars() {
if !flags.contains(c) {
flags.push(c);
}
}
rest = &r[end + 1..];
}
let mut out = String::with_capacity(rest.len());
let mut chars = rest.chars().peekable();
let mut in_class = false;
while let Some(c) = chars.next() {
match c {
'\\' => {
let n = chars.next()?;
match n {
'A' if !in_class => out.push('^'),
'z' if !in_class => out.push('$'),
'b' | 'x' | 'u' if chars.peek() == Some(&'{') => return None,
'd' | 'D' | 'w' | 'W' | 's' | 'S' | 'b' | 'B' | 'n' | 't' | 'r' | 'f' | 'v'
| 'x' | 'u' => {
out.push('\\');
out.push(n);
}
n if n.is_ascii_alphanumeric() || n == '<' || n == '>' => return None,
n => {
out.push('\\');
out.push(n);
}
}
}
'[' if in_class => return None,
'[' => {
in_class = true;
out.push('[');
if chars.peek() == Some(&'^') {
out.push(chars.next()?);
}
if chars.peek() == Some(&']') {
return None;
}
}
']' if in_class => {
in_class = false;
out.push(']');
}
'&' | '-' | '~' if in_class && chars.peek() == Some(&c) => return None,
'(' if !in_class && chars.peek() == Some(&'?') => {
chars.next();
match chars.next()? {
':' => out.push_str("(?:"),
'P' if chars.peek() == Some(&'<') => {
chars.next();
out.push_str("(?<");
}
'<' => out.push_str("(?<"),
_ => return None,
}
}
c => out.push(c),
}
}
(!in_class).then_some((out, flags))
}
fn pattern_act(p: &str) -> Act {
match js_regex(p) {
Some((src, flags)) if flags.is_empty() => {
plain(format!("regex(new RegExp({}))", js_str(&src)))
}
Some((src, flags)) => plain(format!(
"regex(new RegExp({}, {}))",
js_str(&src),
js_str(&flags)
)),
None => Act::Note(format!(
"pattern not portable to JS, not checked: {}",
js_str(p)
)),
}
}
impl Target {
fn ns(self) -> &'static str {
match self {
Zod | Zod4 => "z",
Valibot => "v",
}
}
fn act(self, zod: &str, valibot: &str, arg: impl std::fmt::Display) -> Act {
match self {
Zod | Zod4 => plain(format!("{}({})", zod, arg)),
Valibot => plain(format!("{}({})", valibot, arg)),
}
}
fn pipe(self, mut base: String, acts: Vec<Act>) -> String {
let mut actions = Vec::new();
let mut checks = Vec::new();
for a in acts {
match a {
Act::Plain(s) => actions.push(s),
Act::Check(f, msg) => checks.push(match self {
Zod => format!("refine({}, {})", f, js_str(&msg)),
Zod4 => format!("refine({}, {{ error: {} }})", f, js_str(&msg)),
Valibot => format!("check({}, {})", f, js_str(&msg)),
}),
Act::Note(n) => {
base.push_str(&format!(" /* {} */", n.replace("*/", "*\\/")));
}
}
}
actions.extend(checks);
if actions.is_empty() {
return base;
}
match self {
Zod | Zod4 => actions.iter().fold(base, |acc, a| format!("{}.{}", acc, a)),
Valibot => {
let actions: Vec<String> = actions.iter().map(|a| format!("v.{}", a)).collect();
format!("v.pipe({}, {})", base, actions.join(", "))
}
}
}
fn nullable(self, e: String) -> String {
match self {
Zod | Zod4 => format!("{}.nullable()", e),
Valibot => format!("v.nullable({})", e),
}
}
fn optional(self, e: String) -> String {
match self {
Zod | Zod4 => format!("{}.optional()", e),
Valibot => format!("v.optional({})", e),
}
}
fn with_default(self, e: String, default: &Value) -> String {
match self {
Zod | Zod4 => format!("{}.nullish().transform((v) => v ?? {})", e, default),
Valibot => format!("v.nullish({}, {})", e, default),
}
}
fn union(self, mut variants: Vec<String>) -> String {
if variants.len() == 1 {
return variants.remove(0);
}
format!("{}.union([{}])", self.ns(), variants.join(", "))
}
fn intersection(self, mut parts: Vec<String>) -> String {
match (self, parts.len()) {
(_, 0) => format!("{}.unknown()", self.ns()),
(_, 1) => parts.remove(0),
(Zod | Zod4, _) => parts[1..].iter().fold(parts[0].clone(), |acc, p| {
format!("z.intersection({}, {})", acc, p)
}),
(Valibot, _) => format!("v.intersect([{}])", parts.join(", ")),
}
}
fn literal(self, v: &Value) -> String {
let ns = self.ns();
match v {
Value::Null => format!("{}.null()", ns),
Value::String(_) | Value::Number(_) | Value::Bool(_) => {
format!("{}.literal({})", ns, v)
}
_ => format!("{}.unknown()", ns),
}
}
}
fn js_str(s: &str) -> String {
Value::String(s.to_string()).to_string()
}
fn js_key(k: &str) -> String {
let mut chars = k.chars();
let ident = matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
if ident { k.to_string() } else { js_str(k) }
}
#[doc(hidden)]
pub fn __to_zod_from_value(schema: &Value) -> String {
convert(Zod, schema)
}
#[doc(hidden)]
pub fn __to_valibot_from_value(schema: &Value) -> String {
convert(Valibot, schema)
}
#[doc(hidden)]
pub fn __to_zod4_from_value(schema: &Value) -> String {
convert(Zod4, schema)
}
#[doc(hidden)]
pub fn __to_ts_type_from_value(schema: &Value) -> String {
ts_type(schema).0
}
fn convert(t: Target, schema: &Value) -> String {
let (base, mut actions) = convert_core(t, schema);
if let Some(desc) = schema.get("description").and_then(Value::as_str) {
actions.push(t.act("describe", "description", js_str(desc)));
}
let e = t.pipe(base, actions);
match schema.get("default") {
Some(d) => t.with_default(e, d),
None => e,
}
}
const STRUCTURAL: &[&str] = &[
"type",
"$ref",
"allOf",
"anyOf",
"oneOf",
"not",
"properties",
"items",
"prefixItems",
"enum",
"const",
];
fn convert_core(t: Target, schema: &Value) -> (String, Vec<Act>) {
let ns = t.ns();
match schema {
Value::Bool(true) => return (format!("{}.unknown()", ns), vec![]),
Value::Bool(false) => return (format!("{}.never()", ns), vec![]),
_ => {}
}
if let Some(name) = schema
.get("$ref")
.and_then(Value::as_str)
.and_then(extract_ref_name)
{
return (format!("{}.lazy(() => {}Schema)", ns, name), vec![]);
}
if matches!(schema.get("not"), Some(Value::Bool(true)))
|| schema
.get("not")
.and_then(Value::as_object)
.is_some_and(|o| o.is_empty())
{
return (format!("{}.never()", ns), vec![]);
}
if let Some(all_of) = schema.get("allOf").and_then(Value::as_array) {
let mut rest = schema.clone();
if let Some(o) = rest.as_object_mut() {
o.remove("allOf");
o.remove("description");
o.remove("default");
}
if !rest.as_object().is_some_and(|o| !o.is_empty()) {
return (
t.intersection(all_of.iter().map(|v| convert(t, v)).collect()),
vec![],
);
}
let (base, mut acts) = convert_core(t, &rest);
let ty = rest.get("type").and_then(Value::as_str);
let mut others = Vec::new();
for part in all_of {
let fragment = part
.as_object()
.is_some_and(|o| !STRUCTURAL.iter().any(|k| o.contains_key(*k)));
match ty {
Some(ty) if fragment => acts.extend(constraint_acts(t, ty, part, false)),
_ => others.push(convert(t, part)),
}
}
if others.is_empty() {
return (base, acts);
}
others.insert(0, t.pipe(base, acts));
return (t.intersection(others), vec![]);
}
for key in ["oneOf", "anyOf"] {
if let Some(variants) = schema.get(key).and_then(Value::as_array) {
let is_null = |v: &Value| v.get("type").and_then(Value::as_str) == Some("null");
let mut siblings = schema.as_object().cloned().unwrap_or_default();
for k in [key, "description", "default", "title", "discriminator"] {
siblings.remove(k);
}
let options: Vec<Value> = variants
.iter()
.filter(|v| !is_null(v))
.map(|v| match v.as_object() {
Some(o) if !siblings.is_empty() => {
let mut m = siblings.clone();
m.extend(o.clone());
Value::Object(m)
}
_ => v.clone(),
})
.collect();
let declared = schema
.pointer("/discriminator/propertyName")
.and_then(Value::as_str);
let tag = discriminator(t, declared, &options);
let rest = options.iter().map(|v| convert(t, v)).collect();
let has_null = variants.iter().any(is_null);
return (union_nullable(t, rest, has_null, tag.as_deref()), vec![]);
}
}
if let Some(c) = schema.get("const") {
return (t.literal(c), vec![]);
}
if let Some(values) = schema.get("enum").and_then(Value::as_array) {
return (
t.union(values.iter().map(|v| t.literal(v)).collect()),
vec![],
);
}
match schema.get("type") {
Some(Value::String(ty)) => convert_typed(t, ty, schema),
Some(Value::Array(types)) => {
let mut has_null = false;
let mut rest = Vec::new();
for ty in types.iter().filter_map(Value::as_str) {
if ty == "null" {
has_null = true;
} else {
let (base, actions) = convert_typed(t, ty, schema);
rest.push(t.pipe(base, actions));
}
}
(union_nullable(t, rest, has_null, None), vec![])
}
_ => (format!("{}.unknown()", ns), vec![]),
}
}
fn union_nullable(t: Target, variants: Vec<String>, nullable: bool, tag: Option<&str>) -> String {
if variants.is_empty() {
return format!("{}.{}()", t.ns(), if nullable { "null" } else { "never" });
}
let e = match tag {
Some(tag) if variants.len() > 1 => match t {
Zod | Zod4 => format!(
"z.discriminatedUnion({}, [{}])",
js_str(tag),
variants.join(", ")
),
Valibot => format!("v.variant({}, [{}])", js_str(tag), variants.join(", ")),
},
_ => t.union(variants),
};
if nullable { t.nullable(e) } else { e }
}
fn discriminator(t: Target, declared: Option<&str>, options: &[Value]) -> Option<String> {
const NOT_PLAIN: &[&str] = &[
"default",
"minProperties",
"maxProperties",
"allOf",
"anyOf",
"oneOf",
"not",
"$ref",
"enum",
"const",
];
let plain_object = |o: &Value| {
o.get("type").and_then(Value::as_str) == Some("object")
&& o.get("properties").is_some_and(Value::is_object)
&& !NOT_PLAIN.iter().any(|k| o.get(*k).is_some())
&& (t != Valibot || o.get("description").is_none())
};
let tag_value = |o: &Value, k: &str| -> Option<String> {
if !o.get("required")?.as_array()?.iter().any(|r| r == k) {
return None;
}
let p = o.get("properties")?.get(k)?;
if p.get("default").is_some() {
return None;
}
match (
p.get("const"),
p.get("enum").and_then(Value::as_array).map(Vec::as_slice),
) {
(Some(c), _) => c.as_str(),
(None, Some([one])) => one.as_str(),
_ => None,
}
.map(str::to_string)
};
let fits = |k: &str| {
let mut seen = std::collections::HashSet::new();
options
.iter()
.all(|o| plain_object(o) && tag_value(o, k).is_some_and(|v| seen.insert(v)))
};
match declared {
Some(k) => fits(k).then(|| k.to_string()),
None => options
.first()?
.get("required")?
.as_array()?
.iter()
.filter_map(Value::as_str)
.find(|k| fits(k))
.map(str::to_string),
}
}
fn convert_typed(t: Target, ty: &str, schema: &Value) -> (String, Vec<Act>) {
let ns = t.ns();
let mut acts = Vec::new();
let zod4_fmt = match (t, ty) {
(Zod4, "string") => schema
.get("format")
.and_then(Value::as_str)
.and_then(zod4_format),
_ => None,
};
let format_in_base = zod4_fmt.is_some();
let base = match ty {
"string" => match zod4_fmt {
Some((base, extra)) => {
acts.extend(extra);
base
}
None => format!("{}.string()", ns),
},
"number" => format!("{}.number()", ns),
"integer" if t == Zod4 => "z.int()".to_string(),
"integer" => {
acts.push(t.act("int", "integer", ""));
format!("{}.number()", ns)
}
"boolean" => format!("{}.boolean()", ns),
"null" => format!("{}.null()", ns),
"array" => match schema.get("prefixItems").and_then(Value::as_array) {
Some(prefix) => convert_tuple(t, prefix, schema.get("items")),
None => {
let items = schema
.get("items")
.map(|i| convert(t, i))
.unwrap_or_else(|| format!("{}.unknown()", ns));
format!("{}.array({})", ns, items)
}
},
"object" => convert_object(t, schema),
_ => return (format!("{}.unknown()", ns), acts),
};
acts.extend(constraint_acts(t, ty, schema, format_in_base));
(base, acts)
}
fn convert_tuple(t: Target, prefix: &[Value], items: Option<&Value>) -> String {
let parts = prefix
.iter()
.map(|p| convert(t, p))
.collect::<Vec<_>>()
.join(", ");
let rest = match items {
Some(Value::Bool(false)) => None,
Some(i @ Value::Object(_)) => Some(convert(t, i)),
_ => Some(format!("{}.unknown()", t.ns())),
};
match (t, rest) {
(Zod, None) => format!("z.tuple([{}])", parts),
(Zod, Some(r)) => format!("z.tuple([{}]).rest({})", parts, r),
(Zod4, None) => format!("z.tuple([{}])", parts),
(Zod4, Some(r)) => format!("z.tuple([{}], {})", parts, r),
(Valibot, None) => format!("v.strictTuple([{}])", parts),
(Valibot, Some(r)) => format!("v.tupleWithRest([{}], {})", parts, r),
}
}
fn js_eq(c: &Value) -> String {
match c {
Value::Object(_) | Value::Array(_) => {
format!("JSON.stringify(x) === {}", js_str(&c.to_string()))
}
_ => format!("x === {}", c),
}
}
const DISTINCT: &str = "new Set(a.map((x) => JSON.stringify(x))).size";
fn constraint_acts(t: Target, ty: &str, schema: &Value, format_in_base: bool) -> Vec<Act> {
let u64_of = |k: &str| schema.get(k).and_then(Value::as_u64);
let mut acts = Vec::new();
match ty {
"string" => {
if let Some(n) = u64_of("minLength") {
acts.push(t.act("min", "minLength", n));
}
if let Some(n) = u64_of("maxLength") {
acts.push(t.act("max", "maxLength", n));
}
if let Some(fmt) = schema.get("format").and_then(Value::as_str) {
if !format_in_base {
acts.extend(format_acts(t, fmt));
}
}
if let Some(p) = schema.get("pattern").and_then(Value::as_str) {
acts.push(pattern_act(p));
}
let fmt = schema.get("format").and_then(Value::as_str);
for (key, op) in [("formatMinimum", ">="), ("formatMaximum", "<=")] {
if let Some(b) = schema.get(key).and_then(Value::as_str) {
acts.push(match fmt {
Some("date-time") => check(
&format!("(s) => Date.parse(s) {} Date.parse({})", op, js_str(b)),
&format!("Must be {} {}", op, b),
),
_ => check(
&format!("(s) => s {} {}", op, js_str(b)),
&format!("Must be {} {}", op, b),
),
});
}
}
for (key, op, word) in [("x-past", "<", "past"), ("x-future", ">", "future")] {
if schema.get(key).and_then(Value::as_bool) == Some(true) {
acts.push(check(
&format!("(s) => Date.parse(s) {} Date.now()", op),
&format!("Must be in the {}", word),
));
}
}
}
"number" | "integer" => {
for (key, zod, valibot) in [
("minimum", "min", "minValue"),
("maximum", "max", "maxValue"),
("exclusiveMinimum", "gt", "gtValue"),
("exclusiveMaximum", "lt", "ltValue"),
("multipleOf", "multipleOf", "multipleOf"),
] {
if let Some(n) = schema.get(key).and_then(Value::as_f64) {
acts.push(t.act(zod, valibot, format_number(n)));
}
}
}
"array" => {
if schema.get("prefixItems").is_none() {
match (u64_of("minItems"), u64_of("maxItems")) {
(Some(min), Some(max)) if min == max => {
acts.push(t.act("length", "length", min));
}
(min, max) => {
if let Some(n) = min {
acts.push(t.act("min", "minLength", n));
}
if let Some(n) = max {
acts.push(t.act("max", "maxLength", n));
}
}
}
}
if schema.get("uniqueItems").and_then(Value::as_bool) == Some(true) {
acts.push(check(
&format!("(a) => {} === a.length", DISTINCT),
"Items must be unique",
));
}
if let Some(n) = u64_of("x-minUniqueItems") {
acts.push(check(
&format!("(a) => {} >= {}", DISTINCT, n),
&format!("At least {} unique items", n),
));
}
if let Some(n) = u64_of("x-maxUniqueItems") {
acts.push(check(
&format!("(a) => {} <= {}", DISTINCT, n),
&format!("At most {} unique items", n),
));
}
if let Some(c) = schema.get("contains").and_then(|c| c.get("const")) {
let min = u64_of("minContains").unwrap_or(1);
let count = format!("a.filter((x) => {}).length", js_eq(c));
let mut cond = format!("{} >= {}", count, min);
if let Some(max) = u64_of("maxContains") {
cond = format!("(n => n >= {} && n <= {})({})", min, max, count);
}
acts.push(check(
&format!("(a) => {}", cond),
&format!("Must contain {}", c),
));
}
}
"object" => {
for (key, op, valibot) in [
("minProperties", ">=", "minEntries"),
("maxProperties", "<=", "maxEntries"),
] {
if let Some(n) = u64_of(key) {
acts.push(match t {
Zod | Zod4 => check(
&format!("(o) => Object.keys(o).length {} {}", op, n),
&format!("Must have {} {} keys", op, n),
),
Valibot => plain(format!("{}({})", valibot, n)),
});
}
}
}
_ => {}
}
acts
}
fn convert_object(t: Target, schema: &Value) -> String {
let required: Vec<&str> = schema
.get("required")
.and_then(Value::as_array)
.map(|arr| arr.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
let additional = schema.get("additionalProperties");
let props = match schema.get("properties").and_then(Value::as_object) {
Some(p) => p,
None => {
let names = schema.get("propertyNames");
if names.is_some() || matches!(additional, Some(Value::Object(_))) {
let key = match names {
Some(n @ Value::Object(o)) if !o.contains_key("type") => {
let mut n = n.clone();
n["type"] = Value::from("string");
convert(t, &n)
}
Some(n) => convert(t, n),
None => format!("{}.string()", t.ns()),
};
let value = match additional {
Some(a @ Value::Object(_)) => convert(t, a),
_ => format!("{}.unknown()", t.ns()),
};
return format!("{}.record({}, {})", t.ns(), key, value);
}
return match (t, additional) {
(Zod, Some(Value::Bool(false))) => "z.object({}).strict()".to_string(),
(Valibot, Some(Value::Bool(false))) => "v.strictObject({})".to_string(),
(Zod, _) => "z.object({}).passthrough()".to_string(),
(Zod4, Some(Value::Bool(false))) => "z.strictObject({})".to_string(),
(Zod4, _) => "z.looseObject({})".to_string(),
(Valibot, _) => "v.objectWithRest({}, v.unknown())".to_string(),
};
}
};
let mut declared = required.iter().filter(|k| props.contains_key(**k));
let keys: Vec<&str> = props
.keys()
.map(|k| match required.contains(&k.as_str()) {
true => declared.next().copied().unwrap_or(k),
false => k,
})
.collect();
let fields: Vec<String> = keys
.into_iter()
.map(|key| {
let prop = &props[key];
let mut e = convert(t, prop);
if !required.contains(&key) && prop.get("default").is_none() {
e = t.optional(e);
}
format!(" {}: {}", js_key(key), e)
})
.collect();
let entries = if fields.is_empty() {
"{}".to_string()
} else {
format!("{{\n{}\n}}", fields.join(",\n"))
};
match (t, additional) {
(Zod, Some(Value::Bool(false))) => format!("z.object({}).strict()", entries),
(Zod, Some(a @ Value::Object(_))) => {
format!("z.object({}).catchall({})", entries, convert(t, a))
}
(Zod, _) => format!("z.object({})", entries),
(Zod4, Some(Value::Bool(false))) => format!("z.strictObject({})", entries),
(Zod4, Some(a @ Value::Object(_))) => {
format!("z.object({}).catchall({})", entries, convert(t, a))
}
(Zod4, _) => format!("z.object({})", entries),
(Valibot, Some(Value::Bool(false))) => format!("v.strictObject({})", entries),
(Valibot, Some(a @ Value::Object(_))) => {
format!("v.objectWithRest({}, {})", entries, convert(t, a))
}
(Valibot, _) => format!("v.object({})", entries),
}
}
#[derive(Clone, Copy, PartialEq, PartialOrd)]
enum Prec {
Union,
Inter,
Atom,
}
fn ts_wrap((e, p): (String, Prec), min: Prec) -> String {
if p < min { format!("({})", e) } else { e }
}
fn ts_union(parts: Vec<(String, Prec)>) -> (String, Prec) {
let mut out: Vec<(String, Prec)> = Vec::new();
for p in parts {
if !out.iter().any(|o| o.0 == p.0) {
out.push(p);
}
}
match out.len() {
0 => ts_atom("never"),
1 => out.remove(0),
_ => (
out.into_iter()
.map(|p| ts_wrap(p, Prec::Union))
.collect::<Vec<_>>()
.join(" | "),
Prec::Union,
),
}
}
fn ts_inter(mut parts: Vec<(String, Prec)>) -> (String, Prec) {
match parts.len() {
0 => ("unknown".to_string(), Prec::Atom),
1 => parts.remove(0),
_ => (
parts
.into_iter()
.map(|p| ts_wrap(p, Prec::Inter))
.collect::<Vec<_>>()
.join(" & "),
Prec::Inter,
),
}
}
fn ts_atom(s: impl Into<String>) -> (String, Prec) {
(s.into(), Prec::Atom)
}
fn ts_type(schema: &Value) -> (String, Prec) {
match schema {
Value::Bool(true) => return ts_atom("unknown"),
Value::Bool(false) => return ts_atom("never"),
_ => {}
}
if let Some(name) = schema
.get("$ref")
.and_then(Value::as_str)
.and_then(extract_ref_name)
{
return ts_atom(name);
}
if matches!(schema.get("not"), Some(Value::Bool(true)))
|| schema
.get("not")
.and_then(Value::as_object)
.is_some_and(|o| o.is_empty())
{
return ts_atom("never");
}
if let Some(all_of) = schema.get("allOf").and_then(Value::as_array) {
let mut rest = schema.clone();
if let Some(o) = rest.as_object_mut() {
o.remove("allOf");
}
let mut parts = Vec::new();
if rest.get("type").is_some() {
parts.push(ts_type(&rest));
}
for part in all_of {
let fragment = part
.as_object()
.is_some_and(|o| !STRUCTURAL.iter().any(|k| o.contains_key(*k)));
if !fragment {
parts.push(ts_type(part));
}
}
return ts_inter(parts);
}
for key in ["oneOf", "anyOf"] {
if let Some(variants) = schema.get(key).and_then(Value::as_array) {
let ty = schema.get("type");
let parts = variants
.iter()
.map(|v| match (ty, v.as_object()) {
(Some(ty), Some(o)) if !o.contains_key("type") && !o.contains_key("$ref") => {
let mut v = v.clone();
v["type"] = ty.clone();
ts_type(&v)
}
_ => ts_type(v),
})
.collect();
return ts_union(parts);
}
}
if let Some(c) = schema.get("const") {
return ts_literal(c);
}
if let Some(values) = schema.get("enum").and_then(Value::as_array) {
return ts_union(values.iter().map(ts_literal).collect());
}
match schema.get("type") {
Some(Value::String(ty)) => ts_typed(ty, schema),
Some(Value::Array(types)) => ts_union(
types
.iter()
.filter_map(Value::as_str)
.map(|ty| ts_typed(ty, schema))
.collect(),
),
_ => ts_atom("unknown"),
}
}
fn ts_literal(v: &Value) -> (String, Prec) {
match v {
Value::Null | Value::String(_) | Value::Number(_) | Value::Bool(_) => {
ts_atom(v.to_string())
}
_ => ts_atom("unknown"),
}
}
fn ts_typed(ty: &str, schema: &Value) -> (String, Prec) {
match ty {
"string" => ts_atom("string"),
"number" | "integer" => ts_atom("number"),
"boolean" => ts_atom("boolean"),
"null" => ts_atom("null"),
"array" => match schema.get("prefixItems").and_then(Value::as_array) {
Some(prefix) => {
let mut parts: Vec<String> = prefix.iter().map(|p| ts_type(p).0).collect();
match schema.get("items") {
Some(Value::Bool(false)) => {}
Some(i @ Value::Object(_)) => {
parts.push(format!("...{}[]", ts_wrap(ts_type(i), Prec::Atom)))
}
_ => parts.push("...unknown[]".to_string()),
}
ts_atom(format!("[{}]", parts.join(", ")))
}
None => {
let items = schema
.get("items")
.map_or_else(|| ts_atom("unknown"), ts_type);
ts_atom(format!("{}[]", ts_wrap(items, Prec::Atom)))
}
},
"object" => ts_object(schema),
_ => ts_atom("unknown"),
}
}
fn ts_object(schema: &Value) -> (String, Prec) {
let required: Vec<&str> = schema
.get("required")
.and_then(Value::as_array)
.map(|arr| arr.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
let record = match schema.get("additionalProperties") {
Some(Value::Bool(false)) => None,
Some(a @ Value::Object(_)) => Some(ts_type(a).0),
_ => Some("unknown".to_string()),
};
let props = schema.get("properties").and_then(Value::as_object);
let Some(props) = props.filter(|p| !p.is_empty()) else {
return match record {
Some(v) => ts_atom(format!("Record<string, {}>", v)),
None => ts_atom("Record<string, never>"),
};
};
let mut declared = required.iter().filter(|k| props.contains_key(**k));
let fields: Vec<String> = props
.keys()
.map(|k| match required.contains(&k.as_str()) {
true => declared.next().copied().unwrap_or(k),
false => k,
})
.map(|key| {
let opt = if required.contains(&key) { "" } else { "?" };
let ty = ts_type(&props[key]).0.replace('\n', "\n ");
format!(" {}{}: {};", js_key(key), opt, ty)
})
.collect();
let obj = format!("{{\n{}\n}}", fields.join("\n"));
match record {
Some(v)
if schema
.get("additionalProperties")
.is_some_and(Value::is_object) =>
{
ts_inter(vec![
ts_atom(obj),
ts_atom(format!("Record<string, {}>", v)),
])
}
_ => ts_atom(obj),
}
}
fn format_number(n: f64) -> String {
if n == n.floor() && n.abs() < 1e15 {
format!("{}", n as i64)
} else {
format!("{}", n)
}
}
fn extract_ref_name(ref_path: &str) -> Option<&str> {
ref_path
.strip_prefix("#/components/schemas/")
.or_else(|| ref_path.strip_prefix("#/$defs/"))
.or_else(|| ref_path.strip_prefix("#/definitions/"))
}
fn collect_ref_paths(schema: &Value) -> Vec<String> {
let mut out = std::collections::BTreeSet::new();
collect_ref_paths_rec(schema, &mut out);
out.into_iter().collect()
}
fn collect_ref_paths_rec(value: &Value, out: &mut std::collections::BTreeSet<String>) {
match value {
Value::Object(map) => {
if let Some(Value::String(ref_path)) = map.get("$ref") {
out.insert(ref_path.clone());
}
for v in map.values() {
collect_ref_paths_rec(v, out);
}
}
Value::Array(items) => {
for v in items {
collect_ref_paths_rec(v, out);
}
}
_ => {}
}
}