1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
use std::{fs::File, io::BufReader, path::Path};

use anyhow::Result;
use serde::Deserialize;
use serde_yaml::Value;

pub fn generate_typescript_types(file: &Path) -> Result<String> {
    match parse_yaml(file)? {
        Parsed::One(document) => Ok(format!(
            "declare type {} = {:#}",
            file_name_to_type_name(
                file.file_stem()
                    .expect("couldn't parse a filename from input")
                    .to_str()
                    .expect("path given should be in utf-8")
            ),
            introspect_typescript_types(document)
        )),
        Parsed::Many(documents) => {
            let type_strings = documents
                .into_iter()
                .map(introspect_typescript_types)
                .collect::<Vec<_>>();

            let number_of_types = type_strings.len();

            Ok(format!(
                "declare namespace {} {{ {:#};\n export type All = [{:#}] }}",
                file_name_to_type_name(
                    file.file_stem()
                        .expect("couldn't parse a filename from input")
                        .to_str()
                        .expect("path given should be in utf-8")
                ),
                type_strings
                    .into_iter()
                    .enumerate()
                    .map(|(idx, text)| format!("export type Document{idx} = {text}"))
                    .collect::<Vec<_>>()
                    .join(";\n"),
                (0..number_of_types)
                    .map(|idx| format!("Document{idx}"))
                    .collect::<Vec<_>>()
                    .join(",")
            ))
        }
    }
}

enum Parsed {
    One(Value),
    Many(Vec<Value>),
}

fn parse_yaml(file: &Path) -> Result<Parsed> {
    let rdr = BufReader::new(File::open(file)?);
    let mut values = vec![];

    for doc in serde_yaml::Deserializer::from_reader(rdr) {
        let value = Value::deserialize(doc)?;
        values.push(value);
    }

    if values.len() == 1 {
        return Ok(Parsed::One(values[0].clone()));
    }

    Ok(Parsed::Many(values))
}

fn introspect_typescript_types(value: Value) -> String {
    match value {
        Value::Null => "null".to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        Value::String(s) => format!("'{s}'"),
        Value::Sequence(s) => {
            let mut buf = String::new();
            buf.push('[');

            let elements: Vec<_> = s.into_iter().map(introspect_typescript_types).collect();

            buf.push_str(&elements.join(","));

            buf.push(']');
            buf
        }
        Value::Mapping(m) => {
            let mut buf = String::new();
            buf.push('{');

            let kvs: Vec<_> = m
                .into_iter()
                .map(|(key, value)| {
                    format!(
                        "{}: {}",
                        &introspect_typescript_types(key),
                        &introspect_typescript_types(value)
                    )
                })
                .collect();

            buf.push_str(&kvs.join(","));

            buf.push('}');
            buf
        }
        Value::Tagged(tv) => introspect_typescript_types(tv.value),
    }
}

fn file_name_to_type_name(fname: &str) -> String {
    fname
        .split(['-', '.'])
        .map(to_first_uppercase)
        .collect::<Vec<_>>()
        .join("")
}

fn to_first_uppercase(n: &str) -> String {
    let mut buf = n.to_owned();
    let fc = buf.get(0..1).unwrap_or_default().to_owned().to_uppercase();
    buf.replace_range(0..1, &fc);
    buf
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use insta::assert_display_snapshot;

    use super::{file_name_to_type_name, generate_typescript_types};

    #[test]
    fn file_name_to_type_name_conversion() {
        assert_eq!(file_name_to_type_name("test"), "Test".to_string());
        assert_eq!(
            file_name_to_type_name("test.config"),
            "TestConfig".to_string()
        );
        assert_eq!(
            file_name_to_type_name("test-config"),
            "TestConfig".to_string()
        );
        assert_eq!(
            file_name_to_type_name("test-config-tee.prod"),
            "TestConfigTeeProd".to_string()
        );
    }

    #[test]
    fn introspect_typescript_types_gen() {
        let output = generate_typescript_types(Path::new("src/test.yaml")).unwrap();
        assert_display_snapshot!(output);

        let output = generate_typescript_types(Path::new("src/test.multiple.yaml")).unwrap();
        assert_display_snapshot!(output)
    }
}