mproto_codegen/codegen/js/
package.rs1use std::fs;
2use std::io::Write;
3use std::path::Path;
4
5use genco::{self, quote_in};
6
7use crate::{ast::TypeDef, codegen, Database, Module};
8
9const PACKAGE_JSON: &'static str = include_str!("templates/package.json");
10const TSCONFIG_JSON: &'static str = include_str!("templates/tsconfig.json");
11
12pub fn js_package_gen(
13 root_dir: impl AsRef<Path>,
14 pkg_name: &str,
15 type_defs: &[TypeDef],
16) -> std::io::Result<()> {
17 let local_module = Module::from_type_defs(type_defs.into());
18 let db = Database::new(local_module);
19
20 let pkg_root = root_dir.as_ref().join(pkg_name).join("typescript");
21 let src_dir = pkg_root.join("src");
22
23 fs::create_dir_all(&pkg_root)?;
24 fs::create_dir_all(&src_dir)?;
25
26 let mut package_json_file = fs::File::create(pkg_root.join("package.json"))?;
28 package_json_file.write_all(PACKAGE_JSON.replace("PKG_NAME", pkg_name).as_bytes())?;
29
30 let mut tsconfig_json_file = fs::File::create(pkg_root.join("tsconfig.json"))?;
32 tsconfig_json_file.write_all(TSCONFIG_JSON.as_bytes())?;
33
34 let fmt = genco::fmt::Config::from_lang::<genco::lang::JavaScript>()
36 .with_indentation(genco::fmt::Indentation::Space(4));
37 let config = genco::lang::js::Config::default();
38 let index_file = fs::File::create(src_dir.join("index.ts"))?;
39 let mut w = genco::fmt::IoWriter::new(index_file);
40 let mut tokens = genco::lang::js::Tokens::new();
41
42 let codegen_cx = codegen::CodegenCx::new(&db, None, true);
43
44 for type_def in type_defs {
45 let struct_tokens = codegen::js::js_type_def(&codegen_cx, type_def);
46 quote_in! { tokens => $struct_tokens$("\n\n") };
47 }
48
49 tokens
50 .format_file(&mut w.as_formatter(&fmt), &config)
51 .expect("format js struct");
52
53 Ok(())
54}
55
56pub fn js_module_gen(path: impl AsRef<Path>, type_defs: &[TypeDef]) -> std::io::Result<()> {
57 let local_module = Module::from_type_defs(type_defs.into());
58 let db = Database::new(local_module);
59
60 let fmt = genco::fmt::Config::from_lang::<genco::lang::Rust>()
61 .with_indentation(genco::fmt::Indentation::Space(4));
62 let config = genco::lang::js::Config::default();
63 let proto_ts_file = fs::File::create(path)?;
64
65 let mut w = genco::fmt::IoWriter::new(proto_ts_file);
66 let mut tokens = genco::lang::js::Tokens::new();
67
68 let codegen_cx = codegen::CodegenCx::new(&db, None, false);
69
70 for type_def in type_defs {
71 let type_tokens = codegen::js::js_type_def(&codegen_cx, type_def);
72 quote_in! { tokens => $type_tokens$("\n\n") };
73 }
74
75 tokens
76 .format_file(&mut w.as_formatter(&fmt), &config)
77 .expect("format typescript file");
78
79 Ok(())
80}