Skip to main content

trilean_json_shape/
typescript.rs

1//! The TypeScript declarations a shape writes.
2
3use crate::def::{Definitions, Kind, ObjectDef, ShapeDef};
4use crate::value::Value;
5
6fn literal(value: &str) -> String {
7    Value::String(value.to_owned()).to_string()
8}
9
10fn comment(description: &str, indent: &str) -> String {
11    format!("{indent}/** {} */\n", description.replace("*/", "* /"))
12}
13
14fn property_key(name: &str) -> String {
15    let identifier = name.chars().enumerate().all(|(position, letter)| {
16        letter == '_'
17            || letter == '$'
18            || letter.is_ascii_alphabetic()
19            || (position > 0 && letter.is_ascii_digit())
20    });
21    if identifier && !name.is_empty() {
22        name.to_owned()
23    } else {
24        literal(name)
25    }
26}
27
28fn object_type(object: &ObjectDef, indent: &str) -> String {
29    let mut lines = String::from("{\n");
30    let inner = format!("{indent}  ");
31    for field in &object.fields {
32        if let Some(description) = &field.shape.description {
33            lines.push_str(&comment(description, &inner));
34        }
35        let optional = if field.required { "" } else { "?" };
36        lines.push_str(&format!(
37            "{inner}{}{optional}: {};\n",
38            property_key(&field.name),
39            type_of(&field.shape, &inner)
40        ));
41    }
42    if let Some(additional) = &object.additional {
43        lines.push_str(&format!(
44            "{inner}[key: string]: {};\n",
45            type_of(additional, &inner)
46        ));
47    } else if !object.closed {
48        lines.push_str(&format!("{inner}[key: string]: unknown;\n"));
49    }
50    lines.push_str(indent);
51    lines.push('}');
52    lines
53}
54
55fn union(members: Vec<String>) -> String {
56    members.join(" | ")
57}
58
59/// The TypeScript type of a shape, with references written as the names of the declarations.
60fn type_of(shape: &ShapeDef, indent: &str) -> String {
61    match &shape.kind {
62        Kind::Any => "unknown".to_owned(),
63        Kind::Null => "null".to_owned(),
64        Kind::Bool => "boolean".to_owned(),
65        Kind::ConstBool(flag) => flag.to_string(),
66        Kind::ConstString(value) => literal(value),
67        Kind::Enum(options) => union(options.iter().map(|option| literal(option)).collect()),
68        Kind::String { .. } => "string".to_owned(),
69        Kind::Integer { .. } | Kind::Number { .. } => "number".to_owned(),
70        Kind::Array { items, .. } => {
71            let element = type_of(items, indent);
72            if element.contains(' ') {
73                format!("({element})[]")
74            } else {
75                format!("{element}[]")
76            }
77        }
78        Kind::Map { values, .. } => format!("{{ [key: string]: {} }}", type_of(values, indent)),
79        Kind::Object(object)
80            if object.fields.is_empty() && !object.closed && object.additional.is_none() =>
81        {
82            "{ [key: string]: unknown }".to_owned()
83        }
84        Kind::Object(object) => object_type(object, indent),
85        Kind::OneOf(alternatives) => union(
86            alternatives
87                .iter()
88                .map(|alternative| type_of(alternative, indent))
89                .collect(),
90        ),
91        Kind::Tagged { variants, .. } => union(
92            variants
93                .iter()
94                .map(|(_, variant)| type_of(variant, indent))
95                .collect(),
96        ),
97        Kind::Not(_) => "unknown".to_owned(),
98        Kind::AllOf(parts) => parts
99            .iter()
100            .map(|part| type_of(part, indent))
101            .collect::<Vec<_>>()
102            .join(" & "),
103        Kind::Ref(name) => name.clone(),
104    }
105}
106
107/// One `export type` declaration per definition, in the order the definitions were reached. The types describe the
108/// values a document holds once it has been validated: an object that is not closed has an index signature, and a
109/// field that may be absent is optional.
110pub fn typescript_declarations(definitions: &Definitions) -> String {
111    let mut text = String::new();
112    for (name, shape) in definitions.iter() {
113        if let Some(description) = &shape.description {
114            text.push_str(&comment(description, ""));
115        }
116        text.push_str(&format!("export type {name} = {};\n", type_of(shape, "")));
117    }
118    text
119}