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
use super::{Codegen, CodegenContext};
use crate::{format::gen_doc_string, idl_type::generate_idl_type_with_type_args, CodeText};
use anyhow::*;
use move_idl::IDLStruct;

fn generate_struct_fields(s: &IDLStruct, ctx: &CodegenContext) -> Result<CodeText> {
    Ok(s.fields
        .iter()
        .map(|field| {
            let ts = &generate_idl_type_with_type_args(
                &field.ty,
                ctx,
                &s.type_params
                    .iter()
                    .map(|t| format!("_{}", t))
                    .collect::<Vec<_>>(),
            )?;
            Ok(format!(
                "{}{}: {};",
                field
                    .doc
                    .as_ref()
                    .map(|doc| format!("\n{}", gen_doc_string(doc)))
                    .unwrap_or_default(),
                field.name,
                ts
            ))
        })
        .collect::<Result<Vec<_>>>()?
        .join("\n")
        .trim()
        .to_string()
        .into())
}

impl Codegen for IDLStruct {
    fn generate_typescript(&self, ctx: &CodegenContext) -> Result<String> {
        let generics = if self.type_params.is_empty() {
            "".to_string()
        } else {
            format!(
                "<{}>",
                self.type_params
                    .iter()
                    .map(|p| format!("_{} = unknown", p))
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        };

        Ok(format!(
            r#"{}export type {}Data{} = {{
{}
}};"#,
            self.doc
                .as_ref()
                .map(|d| gen_doc_string(d))
                .unwrap_or_default(),
            self.name,
            generics,
            generate_struct_fields(self, ctx)?.indent()
        ))
    }
}