| 1 | use serde_json::Value; |
| 2 | use std::collections::BTreeMap; |
| 3 | use std::fmt::Write as _; |
| 4 | |
| 5 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 6 | pub enum SchemaMode { |
| 7 | Host, |
| 8 | Runtime, |
| 9 | } |
| 10 | |
| 11 | /// A field's wire type, normalized. |
| 12 | pub enum Ty { |
| 13 | Nullable(Box<Ty>), |
| 14 | String, |
| 15 | Boolean, |
| 16 | Uint, |
| 17 | Integer, |
| 18 | /// A JSON object with any keys (`Map<String, Value>`). |
| 19 | Object, |
| 20 | /// Any JSON value. |
| 21 | Json, |
| 22 | Ref(String), |
| 23 | /// A string tag inside a union member. |
| 24 | Const(String), |
| 25 | Array(Box<Ty>), |
| 26 | } |
| 27 | |
| 28 | pub struct Field { |
| 29 | pub name: String, |
| 30 | pub ty: Ty, |
| 31 | pub required: bool, |
| 32 | } |
| 33 | |
| 34 | pub enum Def { |
| 35 | Object { |
| 36 | strict: bool, |
| 37 | extra: bool, |
| 38 | fields: Vec<Field>, |
| 39 | }, |
| 40 | Enum(Vec<String>), |
| 41 | Union(Vec<Vec<Field>>), |
| 42 | } |
| 43 | |
| 44 | pub fn ref_name(schema: &Value) -> Option<String> { |
| 45 | let reference = schema.get("$ref")?.as_str()?; |
| 46 | Some( |
| 47 | reference |
| 48 | .strip_prefix("#/$defs/") |
| 49 | .unwrap_or_else(|| panic!("unexpected $ref `{reference}`")) |
| 50 | .to_string(), |
| 51 | ) |
| 52 | } |
| 53 | |
| 54 | fn parse_ty(at: &str, schema: &Value, mode: SchemaMode) -> Ty { |
| 55 | let Some(object) = schema.as_object() else { |
| 56 | assert_eq!(schema, &Value::Bool(true), "{at}: unsupported schema"); |
| 57 | return Ty::Json; |
| 58 | }; |
| 59 | if let Some(name) = ref_name(schema) { |
| 60 | return Ty::Ref(name); |
| 61 | } |
| 62 | if let Some(variants) = object.get("anyOf").and_then(Value::as_array) |
| 63 | && variants.len() == 2 |
| 64 | && variants |
| 65 | .iter() |
| 66 | .filter(|variant| variant.get("type").and_then(Value::as_str) == Some("null")) |
| 67 | .count() |
| 68 | == 1 |
| 69 | { |
| 70 | let present = parse_ty( |
| 71 | at, |
| 72 | variants |
| 73 | .iter() |
| 74 | .find(|variant| variant.get("type").and_then(Value::as_str) != Some("null")) |
| 75 | .expect("one non-null variant"), |
| 76 | mode, |
| 77 | ); |
| 78 | return if mode == SchemaMode::Runtime { |
| 79 | Ty::Nullable(Box::new(present)) |
| 80 | } else { |
| 81 | present |
| 82 | }; |
| 83 | } |
| 84 | if let Some(value) = object.get("const").and_then(Value::as_str) { |
| 85 | return Ty::Const(value.to_string()); |
| 86 | } |
| 87 | let types: Vec<&str> = match object.get("type") { |
| 88 | Some(Value::String(ty)) => vec![ty.as_str()], |
| 89 | Some(Value::Array(types)) => types |
| 90 | .iter() |
| 91 | .filter_map(Value::as_str) |
| 92 | .filter(|ty| *ty != "null") |
| 93 | .collect(), |
| 94 | // Only annotations (`default`, `description`): any value. |
| 95 | None if !["enum", "anyOf", "oneOf", "allOf", "properties", "items"] |
| 96 | .iter() |
| 97 | .any(|key| object.contains_key(*key)) => |
| 98 | { |
| 99 | return Ty::Json; |
| 100 | } |
| 101 | _ => panic!("{at}: unsupported wire schema {schema}"), |
| 102 | }; |
| 103 | let value = match types.as_slice() { |
| 104 | ["string"] => Ty::String, |
| 105 | ["boolean"] => Ty::Boolean, |
| 106 | ["integer"] if object.get("minimum").and_then(Value::as_u64) == Some(0) => Ty::Uint, |
| 107 | ["integer"] => Ty::Integer, |
| 108 | ["object"] |
| 109 | if object.get("additionalProperties") == Some(&Value::Bool(true)) |
| 110 | && !object.contains_key("properties") => |
| 111 | { |
| 112 | Ty::Object |
| 113 | } |
| 114 | ["array"] => Ty::Array(Box::new(parse_ty( |
| 115 | &format!("{at}[]"), |
| 116 | object |
| 117 | .get("items") |
| 118 | .unwrap_or_else(|| panic!("{at}: array without items")), |
| 119 | mode, |
| 120 | ))), |
| 121 | _ => panic!("{at}: unsupported wire schema {schema}"), |
| 122 | }; |
| 123 | if mode == SchemaMode::Runtime |
| 124 | && object |
| 125 | .get("type") |
| 126 | .and_then(Value::as_array) |
| 127 | .is_some_and(|types| types.iter().any(|ty| ty == "null")) |
| 128 | { |
| 129 | Ty::Nullable(Box::new(value)) |
| 130 | } else { |
| 131 | value |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | fn object_fields(at: &str, schema: &Value, mode: SchemaMode) -> Vec<Field> { |
| 136 | assert_eq!( |
| 137 | schema.get("type").and_then(Value::as_str), |
| 138 | Some("object"), |
| 139 | "{at}: expected an object schema, got {schema}" |
| 140 | ); |
| 141 | let required: Vec<&str> = schema |
| 142 | .get("required") |
| 143 | .and_then(Value::as_array) |
| 144 | .map(|names| names.iter().filter_map(Value::as_str).collect()) |
| 145 | .unwrap_or_default(); |
| 146 | schema |
| 147 | .get("properties") |
| 148 | .and_then(Value::as_object) |
| 149 | .map(|properties| { |
| 150 | properties |
| 151 | .iter() |
| 152 | .map(|(name, schema)| Field { |
| 153 | name: name.clone(), |
| 154 | ty: parse_ty(&format!("{at}.{name}"), schema, mode), |
| 155 | required: required.contains(&name.as_str()), |
| 156 | }) |
| 157 | .collect() |
| 158 | }) |
| 159 | .unwrap_or_default() |
| 160 | } |
| 161 | |
| 162 | pub fn parse_def(name: &str, schema: &Value, mode: SchemaMode) -> Def { |
| 163 | let members = schema |
| 164 | .get("oneOf") |
| 165 | .or_else(|| schema.get("anyOf")) |
| 166 | .and_then(Value::as_array); |
| 167 | if let Some(members) = members { |
| 168 | // Unit variants, with or without doc comments: a string enum. |
| 169 | let consts: Option<Vec<String>> = members |
| 170 | .iter() |
| 171 | .map(|member| { |
| 172 | member |
| 173 | .get("const") |
| 174 | .and_then(Value::as_str) |
| 175 | .map(str::to_string) |
| 176 | }) |
| 177 | .collect(); |
| 178 | return match consts { |
| 179 | Some(values) => Def::Enum(values), |
| 180 | None if members.len() == 1 => Def::Object { |
| 181 | strict: members[0].get("additionalProperties") == Some(&Value::Bool(false)), |
| 182 | extra: mode == SchemaMode::Runtime |
| 183 | && members[0].get("additionalProperties") != Some(&Value::Bool(false)), |
| 184 | fields: object_fields(name, &members[0], mode), |
| 185 | }, |
| 186 | None => Def::Union( |
| 187 | members |
| 188 | .iter() |
| 189 | .map(|member| object_fields(name, member, mode)) |
| 190 | .collect(), |
| 191 | ), |
| 192 | }; |
| 193 | } |
| 194 | if let Some(values) = schema.get("enum").and_then(Value::as_array) { |
| 195 | return Def::Enum( |
| 196 | values |
| 197 | .iter() |
| 198 | .map(|value| { |
| 199 | value |
| 200 | .as_str() |
| 201 | .unwrap_or_else(|| panic!("{name}: non-string enum value")) |
| 202 | .to_string() |
| 203 | }) |
| 204 | .collect(), |
| 205 | ); |
| 206 | } |
| 207 | Def::Object { |
| 208 | strict: schema.get("additionalProperties") == Some(&Value::Bool(false)), |
| 209 | extra: mode == SchemaMode::Runtime |
| 210 | && schema.get("additionalProperties") != Some(&Value::Bool(false)), |
| 211 | fields: object_fields(name, schema, mode), |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | pub fn quote(value: &str) -> String { |
| 216 | assert!( |
| 217 | !value.contains(['\'', '\\']), |
| 218 | "`{value}` needs escaping in TypeScript" |
| 219 | ); |
| 220 | format!("'{value}'") |
| 221 | } |
| 222 | |
| 223 | fn ts(ty: &Ty) -> String { |
| 224 | match ty { |
| 225 | Ty::Nullable(inner) => format!("({} | null)", ts(inner)), |
| 226 | Ty::String => "string".into(), |
| 227 | Ty::Boolean => "boolean".into(), |
| 228 | Ty::Uint | Ty::Integer => "number".into(), |
| 229 | Ty::Object => "{ [key: string]: Json }".into(), |
| 230 | Ty::Json => "Json".into(), |
| 231 | Ty::Ref(name) => name.clone(), |
| 232 | Ty::Const(value) => quote(value), |
| 233 | Ty::Array(item) => format!("{}[]", ts(item)), |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | /// An array's item type, however deeply nested. |
| 238 | pub fn innermost(ty: &Ty) -> &Ty { |
| 239 | match ty { |
| 240 | Ty::Array(item) => innermost(item), |
| 241 | ty => ty, |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | fn member(field: &Field) -> String { |
| 246 | let optional = if field.required { "" } else { "?" }; |
| 247 | format!("{}{optional}: {}", field.name, ts(&field.ty)) |
| 248 | } |
| 249 | |
| 250 | pub fn typescript_defs(defs: &BTreeMap<String, Def>, mode: SchemaMode) -> String { |
| 251 | let mut out = String::from(if mode == SchemaMode::Host { |
| 252 | "\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n" |
| 253 | } else { |
| 254 | "\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json | undefined }\n" |
| 255 | }); |
| 256 | for (name, def) in defs { |
| 257 | out.push('\n'); |
| 258 | match def { |
| 259 | Def::Object { fields, extra, .. } if fields.is_empty() && !extra => { |
| 260 | if mode == SchemaMode::Host { |
| 261 | let _ = writeln!(out, "export interface {name} {{}}"); |
| 262 | } else { |
| 263 | let _ = writeln!(out, "export type {name} = Record<string, never>"); |
| 264 | } |
| 265 | } |
| 266 | Def::Object { fields, extra, .. } => { |
| 267 | let declaration = if mode == SchemaMode::Host { |
| 268 | format!("export interface {name}") |
| 269 | } else { |
| 270 | format!("export type {name} =") |
| 271 | }; |
| 272 | let _ = writeln!(out, "{declaration} {{"); |
| 273 | for field in fields { |
| 274 | let _ = writeln!(out, " {}", member(field)); |
| 275 | } |
| 276 | if *extra { |
| 277 | out.push_str(" [key: string]: Json | undefined\n"); |
| 278 | } |
| 279 | out.push_str("}\n"); |
| 280 | } |
| 281 | Def::Enum(values) => { |
| 282 | let values: Vec<String> = values.iter().map(|v| quote(v)).collect(); |
| 283 | let _ = writeln!(out, "export type {name} = {}", values.join(" | ")); |
| 284 | } |
| 285 | Def::Union(members) => { |
| 286 | let members: Vec<String> = members |
| 287 | .iter() |
| 288 | .map(|fields| { |
| 289 | // Tags first, then the variant's fields in order. |
| 290 | let (tags, rest): (Vec<&Field>, Vec<&Field>) = fields |
| 291 | .iter() |
| 292 | .partition(|field| matches!(field.ty, Ty::Const(_))); |
| 293 | let parts: Vec<String> = tags.into_iter().chain(rest).map(member).collect(); |
| 294 | format!("{{ {} }}", parts.join("; ")) |
| 295 | }) |
| 296 | .collect(); |
| 297 | let _ = writeln!(out, "export type {name} = {}", members.join(" | ")); |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | out |
| 302 | } |
| 303 |