hyprstream_ts_codegen/ts_codegen/
interfaces.rs1use hyprstream_rpc_build::schema::types::{
4 EnumDef, FieldDef, FieldSection, ParsedSchema, StructDef,
5};
6use hyprstream_rpc_build::util::to_camel_case;
7
8use super::capnp_to_ts_type;
9
10pub fn generate_interfaces(out: &mut String, schema: &ParsedSchema) {
12 for e in &schema.enums {
14 emit_enum(out, e);
15 }
16
17 for s in &schema.structs {
19 emit_struct_interface(out, s, schema);
20 }
21}
22
23fn emit_enum(out: &mut String, e: &EnumDef) {
25 out.push_str(&format!("export type {} =", e.name));
26 for (i, (name, _ord)) in e.variants.iter().enumerate() {
27 if i == 0 {
28 out.push('\n');
29 }
30 let sep = if i + 1 < e.variants.len() { "" } else { ";" };
31 out.push_str(&format!(" | '{}'{}\n", to_camel_case(name), sep));
32 }
33 out.push('\n');
34}
35
36fn emit_group_interface(out: &mut String, name: &str, leaves: &[FieldDef]) {
41 out.push_str(&format!("export interface {name} {{\n"));
42 for leaf in leaves {
43 let ts = capnp_to_ts_type(&leaf.type_name);
44 let nullable = if matches!(leaf.section, FieldSection::Pointer)
45 && !matches!(leaf.type_name.as_str(), "Text" | "Data")
46 && !leaf.type_name.starts_with("List(")
47 && !leaf.type_name.starts_with("Option")
48 {
49 " | null"
50 } else {
51 ""
52 };
53 out.push_str(&format!(
54 " {}: {}{};\n",
55 to_camel_case(&leaf.name),
56 ts,
57 nullable
58 ));
59 }
60 out.push_str("}\n\n");
61}
62
63fn emit_struct_interface(out: &mut String, s: &StructDef, schema: &ParsedSchema) {
75 if super::emits_union_alias(schema, s) {
76 let union_fields: Vec<_> = s.union_fields().collect();
77 for f in &union_fields {
82 if let Some(leaves) = super::group_arm_leaves(s, f) {
83 emit_group_interface(out, &super::group_arm_type_name(&s.name, &f.name), leaves);
84 }
85 }
86 let shared_fields = super::shared_union_fields(s);
87 let arms: Vec<(String, String)> = union_fields
88 .iter()
89 .map(|f| (f.name.clone(), super::union_arm_data_type(s, f)))
92 .collect();
93 super::emit_union_alias(out, &s.name, &shared_fields, &arms);
94 return;
95 }
96
97 let non_union_fields: Vec<_> = s.non_union_fields().collect();
98
99 out.push_str(&format!("export interface {} {{\n", s.name));
100 for f in &non_union_fields {
101 let ts = capnp_to_ts_type(&f.type_name);
102 let opt = if f.optional { "?" } else { "" };
103 let nullable = if matches!(f.section, FieldSection::Pointer)
106 && !matches!(f.type_name.as_str(), "Text" | "Data")
107 && !f.type_name.starts_with("List(")
108 && !f.type_name.starts_with("Option")
109 {
110 " | null"
111 } else {
112 ""
113 };
114 out.push_str(&format!(
115 " {}{}: {}{};\n",
116 to_camel_case(&f.name),
117 opt,
118 ts,
119 nullable
120 ));
121 }
122 out.push_str("}\n\n");
123}