hyperstack_interpreter/
typescript.rs

1use crate::ast::*;
2use std::collections::{BTreeMap, HashSet};
3
4/// Output structure for TypeScript generation
5#[derive(Debug, Clone)]
6pub struct TypeScriptOutput {
7    pub interfaces: String,
8    pub stack_definition: String,
9    pub imports: String,
10}
11
12impl TypeScriptOutput {
13    pub fn full_file(&self) -> String {
14        format!(
15            "{}\n\n{}\n\n{}",
16            self.imports, self.interfaces, self.stack_definition
17        )
18    }
19}
20
21/// Configuration for TypeScript generation
22#[derive(Debug, Clone)]
23pub struct TypeScriptConfig {
24    pub package_name: String,
25    pub generate_helpers: bool,
26    pub interface_prefix: String,
27    pub export_const_name: String,
28}
29
30impl Default for TypeScriptConfig {
31    fn default() -> Self {
32        Self {
33            package_name: "hyperstack-react".to_string(),
34            generate_helpers: true,
35            interface_prefix: "".to_string(),
36            export_const_name: "STACK".to_string(),
37        }
38    }
39}
40
41/// Trait for generating TypeScript code from AST components
42pub trait TypeScriptGenerator {
43    fn generate_typescript(&self, config: &TypeScriptConfig) -> String;
44}
45
46/// Trait for generating TypeScript interfaces
47pub trait TypeScriptInterfaceGenerator {
48    fn generate_interface(&self, name: &str, config: &TypeScriptConfig) -> String;
49}
50
51/// Trait for generating TypeScript type mappings
52pub trait TypeScriptTypeMapper {
53    fn to_typescript_type(&self) -> String;
54}
55
56/// Main TypeScript compiler for stream specs
57pub struct TypeScriptCompiler<S> {
58    spec: TypedStreamSpec<S>,
59    entity_name: String,
60    config: TypeScriptConfig,
61    idl: Option<serde_json::Value>, // IDL for enum type generation
62    handlers_json: Option<serde_json::Value>, // Raw handlers for event interface generation
63}
64
65impl<S> TypeScriptCompiler<S> {
66    pub fn new(spec: TypedStreamSpec<S>, entity_name: String) -> Self {
67        Self {
68            spec,
69            entity_name,
70            config: TypeScriptConfig::default(),
71            idl: None,
72            handlers_json: None,
73        }
74    }
75
76    pub fn with_config(mut self, config: TypeScriptConfig) -> Self {
77        self.config = config;
78        self
79    }
80
81    pub fn with_idl(mut self, idl: Option<serde_json::Value>) -> Self {
82        self.idl = idl;
83        self
84    }
85
86    pub fn with_handlers_json(mut self, handlers: Option<serde_json::Value>) -> Self {
87        self.handlers_json = handlers;
88        self
89    }
90
91    pub fn compile(&self) -> TypeScriptOutput {
92        let imports = self.generate_imports();
93        let interfaces = self.generate_interfaces();
94        let stack_definition = self.generate_stack_definition();
95
96        TypeScriptOutput {
97            imports,
98            interfaces,
99            stack_definition,
100        }
101    }
102
103    fn generate_imports(&self) -> String {
104        // No imports needed - generated file is self-contained
105        String::new()
106    }
107
108    fn generate_view_helpers(&self) -> String {
109        r#"// ============================================================================
110// View Definition Types (framework-agnostic)
111// ============================================================================
112
113/** View definition with embedded entity type */
114export interface ViewDef<T, TMode extends 'state' | 'list'> {
115  readonly mode: TMode;
116  readonly view: string;
117  /** Phantom field for type inference - not present at runtime */
118  readonly _entity?: T;
119}
120
121/** Helper to create typed state view definitions */
122function stateView<T>(view: string): ViewDef<T, 'state'> {
123  return { mode: 'state', view } as const;
124}
125
126/** Helper to create typed list view definitions */
127function listView<T>(view: string): ViewDef<T, 'list'> {
128  return { mode: 'list', view } as const;
129}"#
130        .to_string()
131    }
132
133    fn generate_interfaces(&self) -> String {
134        let mut interfaces = Vec::new();
135        let mut processed_types = HashSet::new();
136        let mut all_sections: BTreeMap<String, Vec<TypeScriptField>> = BTreeMap::new();
137
138        // Collect all interface sections from all handlers
139        for handler in &self.spec.handlers {
140            let interface_sections = self.extract_interface_sections(handler);
141
142            for (section_name, mut fields) in interface_sections {
143                all_sections
144                    .entry(section_name)
145                    .or_default()
146                    .append(&mut fields);
147            }
148        }
149
150        // Deduplicate fields within each section and generate interfaces
151        // Skip root section - its fields will be flattened into main entity interface
152        for (section_name, fields) in all_sections {
153            if !is_root_section(&section_name) && processed_types.insert(section_name.clone()) {
154                let deduplicated_fields = self.deduplicate_fields(fields);
155                let interface =
156                    self.generate_interface_from_fields(&section_name, &deduplicated_fields);
157                interfaces.push(interface);
158            }
159        }
160
161        // Generate main entity interface
162        let main_interface = self.generate_main_entity_interface();
163        interfaces.push(main_interface);
164
165        // Generate nested interfaces for resolved types (instructions, accounts, etc.)
166        let nested_interfaces = self.generate_nested_interfaces();
167        interfaces.extend(nested_interfaces);
168
169        // Generate EventWrapper interface if there are any event types
170        if self.has_event_types() {
171            interfaces.push(self.generate_event_wrapper_interface());
172        }
173
174        interfaces.join("\n\n")
175    }
176
177    fn deduplicate_fields(&self, mut fields: Vec<TypeScriptField>) -> Vec<TypeScriptField> {
178        let mut seen = HashSet::new();
179        let mut unique_fields = Vec::new();
180
181        // Sort fields by name for consistent output
182        fields.sort_by(|a, b| a.name.cmp(&b.name));
183
184        for field in fields {
185            if seen.insert(field.name.clone()) {
186                unique_fields.push(field);
187            }
188        }
189
190        unique_fields
191    }
192
193    fn extract_interface_sections(
194        &self,
195        handler: &TypedHandlerSpec<S>,
196    ) -> BTreeMap<String, Vec<TypeScriptField>> {
197        let mut sections: BTreeMap<String, Vec<TypeScriptField>> = BTreeMap::new();
198
199        for mapping in &handler.mappings {
200            let parts: Vec<&str> = mapping.target_path.split('.').collect();
201
202            if parts.len() > 1 {
203                // Nested field (e.g., "status.current")
204                let section_name = parts[0];
205                let field_name = parts[1];
206
207                let ts_field = TypeScriptField {
208                    name: field_name.to_string(),
209                    ts_type: self.mapping_to_typescript_type(mapping),
210                    optional: self.is_field_optional(mapping),
211                    description: None,
212                };
213
214                sections
215                    .entry(section_name.to_string())
216                    .or_default()
217                    .push(ts_field);
218            } else {
219                // Top-level field
220                let ts_field = TypeScriptField {
221                    name: mapping.target_path.clone(),
222                    ts_type: self.mapping_to_typescript_type(mapping),
223                    optional: self.is_field_optional(mapping),
224                    description: None,
225                };
226
227                sections
228                    .entry("Root".to_string())
229                    .or_default()
230                    .push(ts_field);
231            }
232        }
233
234        // Add any unmapped fields that exist in the original spec
235        // These are fields without #[map] or #[event] attributes
236        self.add_unmapped_fields(&mut sections);
237
238        sections
239    }
240
241    fn add_unmapped_fields(&self, sections: &mut BTreeMap<String, Vec<TypeScriptField>>) {
242        // NEW: Enhanced approach using AST type information if available
243        if !self.spec.sections.is_empty() {
244            // Use type information from the enhanced AST
245            for section in &self.spec.sections {
246                let section_fields = sections.entry(section.name.clone()).or_default();
247
248                for field_info in &section.fields {
249                    // Check if field is already mapped
250                    let already_exists = section_fields.iter().any(|f| {
251                        f.name == field_info.field_name
252                            || f.name == to_camel_case(&field_info.field_name)
253                    });
254
255                    if !already_exists {
256                        section_fields.push(TypeScriptField {
257                            name: field_info.field_name.clone(),
258                            ts_type: self.field_type_info_to_typescript(field_info),
259                            optional: field_info.is_optional,
260                            description: None,
261                        });
262                    }
263                }
264            }
265        } else {
266            // FALLBACK: Use field mappings from spec if sections aren't available yet
267            for (field_path, field_type_info) in &self.spec.field_mappings {
268                let parts: Vec<&str> = field_path.split('.').collect();
269                if parts.len() > 1 {
270                    let section_name = parts[0];
271                    let field_name = parts[1];
272
273                    let section_fields = sections.entry(section_name.to_string()).or_default();
274
275                    let already_exists = section_fields
276                        .iter()
277                        .any(|f| f.name == field_name || f.name == to_camel_case(field_name));
278
279                    if !already_exists {
280                        section_fields.push(TypeScriptField {
281                            name: field_name.to_string(),
282                            ts_type: self.base_type_to_typescript(
283                                &field_type_info.base_type,
284                                field_type_info.is_array,
285                            ),
286                            optional: field_type_info.is_optional,
287                            description: None,
288                        });
289                    }
290                }
291            }
292        }
293    }
294
295    fn generate_interface_from_fields(&self, name: &str, fields: &[TypeScriptField]) -> String {
296        // Generate more descriptive interface names
297        let interface_name = if name == "Root" {
298            format!(
299                "{}{}",
300                self.config.interface_prefix,
301                to_pascal_case(&self.entity_name)
302            )
303        } else {
304            // Create compound names like GameEvents, GameStatus, etc.
305            // Extract the base name (e.g., "Game" from "TestGame" or "SettlementGame")
306            let base_name = if self.entity_name.contains("Game") {
307                "Game"
308            } else {
309                &self.entity_name
310            };
311            format!(
312                "{}{}{}",
313                self.config.interface_prefix,
314                base_name,
315                to_pascal_case(name)
316            )
317        };
318
319        // All fields are optional (?) since we receive patches - field may not yet exist
320        // For spec-optional fields, we use `T | null` to distinguish "explicitly null" from "not received"
321        let field_definitions: Vec<String> = fields
322            .iter()
323            .map(|field| {
324                let field_name = to_camel_case(&field.name);
325                let ts_type = if field.optional {
326                    // Spec-optional: can be explicitly null
327                    format!("{} | null", field.ts_type)
328                } else {
329                    field.ts_type.clone()
330                };
331                format!("  {}?: {};", field_name, ts_type)
332            })
333            .collect();
334
335        format!(
336            "export interface {} {{\n{}\n}}",
337            interface_name,
338            field_definitions.join("\n")
339        )
340    }
341
342    fn generate_main_entity_interface(&self) -> String {
343        let entity_name = to_pascal_case(&self.entity_name);
344
345        // Extract all top-level sections from the handlers
346        let mut sections = BTreeMap::new();
347
348        for handler in &self.spec.handlers {
349            for mapping in &handler.mappings {
350                let parts: Vec<&str> = mapping.target_path.split('.').collect();
351                if parts.len() > 1 {
352                    sections.insert(parts[0], true);
353                }
354            }
355        }
356
357        if !self.spec.sections.is_empty() {
358            for section in &self.spec.sections {
359                sections.insert(&section.name, true);
360            }
361        } else {
362            for mapping in &self.spec.handlers {
363                for field_mapping in &mapping.mappings {
364                    let parts: Vec<&str> = field_mapping.target_path.split('.').collect();
365                    if parts.len() > 1 {
366                        sections.insert(parts[0], true);
367                    }
368                }
369            }
370        }
371
372        let mut fields = Vec::new();
373
374        // Add non-root sections as nested interface references
375        // All fields are optional since we receive patches
376        for section in sections.keys() {
377            if !is_root_section(section) {
378                let base_name = if self.entity_name.contains("Game") {
379                    "Game"
380                } else {
381                    &self.entity_name
382                };
383                let section_interface_name = format!("{}{}", base_name, to_pascal_case(section));
384                fields.push(format!(
385                    "  {}?: {};",
386                    to_camel_case(section),
387                    section_interface_name
388                ));
389            }
390        }
391
392        // Flatten root section fields directly into main interface
393        // All fields are optional (?) since we receive patches
394        for section in &self.spec.sections {
395            if is_root_section(&section.name) {
396                for field in &section.fields {
397                    let field_name = to_camel_case(&field.field_name);
398                    let base_ts_type = self.field_type_info_to_typescript(field);
399                    let ts_type = if field.is_optional {
400                        format!("{} | null", base_ts_type)
401                    } else {
402                        base_ts_type
403                    };
404                    fields.push(format!("  {}?: {};", field_name, ts_type));
405                }
406            }
407        }
408
409        if fields.is_empty() {
410            fields.push("  // Generated interface - extend as needed".to_string());
411        }
412
413        format!(
414            "export interface {} {{\n{}\n}}",
415            entity_name,
416            fields.join("\n")
417        )
418    }
419
420    fn generate_stack_definition(&self) -> String {
421        let stack_name = to_kebab_case(&self.entity_name);
422        let entity_pascal = to_pascal_case(&self.entity_name);
423        let export_name = format!(
424            "{}_{}",
425            self.entity_name.to_uppercase(),
426            self.config.export_const_name
427        );
428
429        let view_helpers = self.generate_view_helpers();
430
431        format!(
432            r#"{}
433
434// ============================================================================
435// Stack Definition
436// ============================================================================
437
438/** Stack definition for {} */
439export const {} = {{
440  name: '{}',
441  views: {{
442    {}: {{
443      state: stateView<{}>('{}/state'),
444      list: listView<{}>('{}/list'),
445    }},
446  }},
447}} as const;
448
449/** Type alias for the stack */
450export type {}Stack = typeof {};
451
452/** Default export for convenience */
453export default {};"#,
454            view_helpers,
455            entity_pascal,
456            export_name,
457            stack_name,
458            to_camel_case(&self.entity_name),
459            entity_pascal,
460            self.entity_name,
461            entity_pascal,
462            self.entity_name,
463            entity_pascal,
464            export_name,
465            export_name
466        )
467    }
468
469    fn mapping_to_typescript_type(&self, mapping: &TypedFieldMapping<S>) -> String {
470        // First, try to resolve from AST field mappings
471        if let Some(field_info) = self.spec.field_mappings.get(&mapping.target_path) {
472            let ts_type = self.field_type_info_to_typescript(field_info);
473
474            // If it's an Append strategy, wrap in array
475            if matches!(mapping.population, PopulationStrategy::Append) {
476                return if ts_type.ends_with("[]") {
477                    ts_type
478                } else {
479                    format!("{}[]", ts_type)
480                };
481            }
482
483            return ts_type;
484        }
485
486        // Fallback to legacy inference
487        match &mapping.population {
488            PopulationStrategy::Append => {
489                // For arrays, try to infer the element type
490                match &mapping.source {
491                    MappingSource::AsEvent { .. } => "any[]".to_string(),
492                    _ => "any[]".to_string(),
493                }
494            }
495            _ => {
496                // Infer type from source and field name
497                let base_type = match &mapping.source {
498                    MappingSource::FromSource { .. } => {
499                        self.infer_type_from_field_name(&mapping.target_path)
500                    }
501                    MappingSource::Constant(value) => value_to_typescript_type(value),
502                    MappingSource::AsEvent { .. } => "any".to_string(),
503                    _ => "any".to_string(),
504                };
505
506                // Apply transformations to type
507                if let Some(transform) = &mapping.transform {
508                    match transform {
509                        Transformation::HexEncode | Transformation::HexDecode => {
510                            "string".to_string()
511                        }
512                        Transformation::Base58Encode | Transformation::Base58Decode => {
513                            "string".to_string()
514                        }
515                        Transformation::ToString => "string".to_string(),
516                        Transformation::ToNumber => "number".to_string(),
517                    }
518                } else {
519                    base_type
520                }
521            }
522        }
523    }
524
525    /// Convert FieldTypeInfo from AST to TypeScript type string
526    fn field_type_info_to_typescript(&self, field_info: &FieldTypeInfo) -> String {
527        // If we have resolved type information (complex types from IDL), use it
528        if let Some(resolved) = &field_info.resolved_type {
529            let interface_name = self.resolved_type_to_interface_name(resolved);
530
531            // Wrap in EventWrapper if it's an event type
532            let base_type = if resolved.is_event || (resolved.is_instruction && field_info.is_array)
533            {
534                format!("EventWrapper<{}>", interface_name)
535            } else {
536                interface_name
537            };
538
539            // Handle optional and array
540            let with_array = if field_info.is_array {
541                format!("{}[]", base_type)
542            } else {
543                base_type
544            };
545
546            return with_array;
547        }
548
549        // Check if this is an event field (has BaseType::Any or BaseType::Array with Value inner type)
550        // We can detect event fields by looking for them in handlers with AsEvent mappings
551        if field_info.base_type == BaseType::Any
552            || (field_info.base_type == BaseType::Array
553                && field_info.inner_type.as_deref() == Some("Value"))
554        {
555            if let Some(event_type) = self.find_event_interface_for_field(&field_info.field_name) {
556                return if field_info.is_array {
557                    format!("{}[]", event_type)
558                } else if field_info.is_optional {
559                    format!("{} | null", event_type)
560                } else {
561                    event_type
562                };
563            }
564        }
565
566        // Use base type mapping
567        self.base_type_to_typescript(&field_info.base_type, field_info.is_array)
568    }
569
570    /// Find the generated event interface name for a given field
571    fn find_event_interface_for_field(&self, field_name: &str) -> Option<String> {
572        // Use the raw JSON handlers if available
573        let handlers = self.handlers_json.as_ref()?.as_array()?;
574
575        // Look through handlers to find event mappings for this field
576        for handler in handlers {
577            if let Some(mappings) = handler.get("mappings").and_then(|m| m.as_array()) {
578                for mapping in mappings {
579                    if let Some(target_path) = mapping.get("target_path").and_then(|t| t.as_str()) {
580                        // Check if this mapping targets our field (e.g., "events.created")
581                        let target_parts: Vec<&str> = target_path.split('.').collect();
582                        if let Some(target_field) = target_parts.last() {
583                            if *target_field == field_name {
584                                // Check if this is an event mapping
585                                if let Some(source) = mapping.get("source") {
586                                    if self.extract_event_data(source).is_some() {
587                                        // Generate the interface name (e.g., "created" -> "CreatedEvent")
588                                        return Some(format!(
589                                            "{}Event",
590                                            to_pascal_case(field_name)
591                                        ));
592                                    }
593                                }
594                            }
595                        }
596                    }
597                }
598            }
599        }
600        None
601    }
602
603    /// Generate TypeScript interface name from resolved type
604    fn resolved_type_to_interface_name(&self, resolved: &ResolvedStructType) -> String {
605        to_pascal_case(&resolved.type_name)
606    }
607
608    /// Generate nested interfaces for all resolved types in the AST
609    fn generate_nested_interfaces(&self) -> Vec<String> {
610        let mut interfaces = Vec::new();
611        let mut generated_types = HashSet::new();
612
613        // Collect all resolved types from all sections
614        for section in &self.spec.sections {
615            for field_info in &section.fields {
616                if let Some(resolved) = &field_info.resolved_type {
617                    let type_name = resolved.type_name.clone();
618
619                    // Only generate each type once
620                    if generated_types.insert(type_name) {
621                        let interface = self.generate_interface_for_resolved_type(resolved);
622                        interfaces.push(interface);
623                    }
624                }
625            }
626        }
627
628        // Generate event interfaces from instruction handlers
629        interfaces.extend(self.generate_event_interfaces(&mut generated_types));
630
631        // Also generate all enum types from the IDL (even if not directly referenced)
632        if let Some(idl_value) = &self.idl {
633            if let Some(types_array) = idl_value.get("types").and_then(|v| v.as_array()) {
634                for type_def in types_array {
635                    if let (Some(type_name), Some(type_obj)) = (
636                        type_def.get("name").and_then(|v| v.as_str()),
637                        type_def.get("type").and_then(|v| v.as_object()),
638                    ) {
639                        if type_obj.get("kind").and_then(|v| v.as_str()) == Some("enum") {
640                            // Only generate if not already generated
641                            if generated_types.insert(type_name.to_string()) {
642                                if let Some(variants) =
643                                    type_obj.get("variants").and_then(|v| v.as_array())
644                                {
645                                    let variant_names: Vec<String> = variants
646                                        .iter()
647                                        .filter_map(|v| {
648                                            v.get("name")
649                                                .and_then(|n| n.as_str())
650                                                .map(|s| s.to_string())
651                                        })
652                                        .collect();
653
654                                    if !variant_names.is_empty() {
655                                        let interface_name = to_pascal_case(type_name);
656                                        let variant_strings: Vec<String> = variant_names
657                                            .iter()
658                                            .map(|v| format!("\"{}\"", to_pascal_case(v)))
659                                            .collect();
660
661                                        let enum_type = format!(
662                                            "export type {} = {};",
663                                            interface_name,
664                                            variant_strings.join(" | ")
665                                        );
666                                        interfaces.push(enum_type);
667                                    }
668                                }
669                            }
670                        }
671                    }
672                }
673            }
674        }
675
676        interfaces
677    }
678
679    /// Generate TypeScript interfaces for event types from instruction handlers
680    fn generate_event_interfaces(&self, generated_types: &mut HashSet<String>) -> Vec<String> {
681        let mut interfaces = Vec::new();
682
683        // Use the raw JSON handlers if available
684        let handlers = match &self.handlers_json {
685            Some(h) => h.as_array(),
686            None => return interfaces,
687        };
688
689        let handlers_array = match handlers {
690            Some(arr) => arr,
691            None => return interfaces,
692        };
693
694        // Look through handlers to find instruction-based event mappings
695        for handler in handlers_array {
696            // Check if this handler has event mappings
697            if let Some(mappings) = handler.get("mappings").and_then(|m| m.as_array()) {
698                for mapping in mappings {
699                    if let Some(target_path) = mapping.get("target_path").and_then(|t| t.as_str()) {
700                        // Check if the target is an event field (contains ".events." or starts with "events.")
701                        if target_path.contains(".events.") || target_path.starts_with("events.") {
702                            // Check if the source is AsEvent
703                            if let Some(source) = mapping.get("source") {
704                                if let Some(event_data) = self.extract_event_data(source) {
705                                    // Extract instruction name from handler source
706                                    if let Some(handler_source) = handler.get("source") {
707                                        if let Some(instruction_name) =
708                                            self.extract_instruction_name(handler_source)
709                                        {
710                                            // Generate interface name from target path (e.g., "events.created" -> "CreatedEvent")
711                                            let event_field_name =
712                                                target_path.split('.').next_back().unwrap_or("");
713                                            let interface_name = format!(
714                                                "{}Event",
715                                                to_pascal_case(event_field_name)
716                                            );
717
718                                            // Only generate once
719                                            if generated_types.insert(interface_name.clone()) {
720                                                if let Some(interface) = self
721                                                    .generate_event_interface_from_idl(
722                                                        &interface_name,
723                                                        &instruction_name,
724                                                        &event_data,
725                                                    )
726                                                {
727                                                    interfaces.push(interface);
728                                                }
729                                            }
730                                        }
731                                    }
732                                }
733                            }
734                        }
735                    }
736                }
737            }
738        }
739
740        interfaces
741    }
742
743    /// Extract event field data from a mapping source
744    fn extract_event_data(
745        &self,
746        source: &serde_json::Value,
747    ) -> Option<Vec<(String, Option<String>)>> {
748        if let Some(as_event) = source.get("AsEvent") {
749            if let Some(fields) = as_event.get("fields").and_then(|f| f.as_array()) {
750                let mut event_fields = Vec::new();
751                for field in fields {
752                    if let Some(from_source) = field.get("FromSource") {
753                        if let Some(path) = from_source
754                            .get("path")
755                            .and_then(|p| p.get("segments"))
756                            .and_then(|s| s.as_array())
757                        {
758                            // Get the last segment as the field name (e.g., ["data", "game_id"] -> "game_id")
759                            if let Some(field_name) = path.last().and_then(|v| v.as_str()) {
760                                let transform = from_source
761                                    .get("transform")
762                                    .and_then(|t| t.as_str())
763                                    .map(|s| s.to_string());
764                                event_fields.push((field_name.to_string(), transform));
765                            }
766                        }
767                    }
768                }
769                return Some(event_fields);
770            }
771        }
772        None
773    }
774
775    /// Extract instruction name from handler source
776    fn extract_instruction_name(&self, source: &serde_json::Value) -> Option<String> {
777        if let Some(source_obj) = source.get("Source") {
778            if let Some(type_name) = source_obj.get("type_name").and_then(|t| t.as_str()) {
779                // Convert "CreateGameIxState" -> "create_game"
780                if let Some(instruction_part) = type_name.strip_suffix("IxState") {
781                    return Some(to_snake_case(instruction_part));
782                }
783            }
784        }
785        None
786    }
787
788    /// Generate a TypeScript interface for an event from IDL instruction data
789    fn generate_event_interface_from_idl(
790        &self,
791        interface_name: &str,
792        instruction_name: &str,
793        captured_fields: &[(String, Option<String>)],
794    ) -> Option<String> {
795        // If no fields are captured, generate an empty interface
796        if captured_fields.is_empty() {
797            return Some(format!("export interface {} {{}}", interface_name));
798        }
799
800        let idl_value = self.idl.as_ref()?;
801        let instructions = idl_value.get("instructions")?.as_array()?;
802
803        // Find the instruction in the IDL
804        for instruction in instructions {
805            if let Some(name) = instruction.get("name").and_then(|n| n.as_str()) {
806                if name == instruction_name {
807                    // Get the args
808                    if let Some(args) = instruction.get("args").and_then(|a| a.as_array()) {
809                        let mut fields = Vec::new();
810
811                        // Only include captured fields
812                        for (field_name, transform) in captured_fields {
813                            // Find this arg in the instruction
814                            for arg in args {
815                                if let Some(arg_name) = arg.get("name").and_then(|n| n.as_str()) {
816                                    if arg_name == field_name {
817                                        if let Some(arg_type) = arg.get("type") {
818                                            let ts_type = self.idl_type_to_typescript(
819                                                arg_type,
820                                                transform.as_deref(),
821                                            );
822                                            let camel_name = to_camel_case(field_name);
823                                            fields.push(format!("  {}: {};", camel_name, ts_type));
824                                        }
825                                        break;
826                                    }
827                                }
828                            }
829                        }
830
831                        if !fields.is_empty() {
832                            return Some(format!(
833                                "export interface {} {{\n{}\n}}",
834                                interface_name,
835                                fields.join("\n")
836                            ));
837                        }
838                    }
839                }
840            }
841        }
842
843        None
844    }
845
846    /// Convert an IDL type (from JSON) to TypeScript, considering transforms
847    fn idl_type_to_typescript(
848        &self,
849        idl_type: &serde_json::Value,
850        transform: Option<&str>,
851    ) -> String {
852        #![allow(clippy::only_used_in_recursion)]
853        // If there's a HexEncode transform, the result is always a string
854        if transform == Some("HexEncode") {
855            return "string".to_string();
856        }
857
858        // Handle different IDL type formats
859        if let Some(type_str) = idl_type.as_str() {
860            return match type_str {
861                "u8" | "u16" | "u32" | "u64" | "u128" | "i8" | "i16" | "i32" | "i64" | "i128" => {
862                    "number".to_string()
863                }
864                "f32" | "f64" => "number".to_string(),
865                "bool" => "boolean".to_string(),
866                "string" => "string".to_string(),
867                "pubkey" | "publicKey" => "string".to_string(),
868                "bytes" => "string".to_string(),
869                _ => "any".to_string(),
870            };
871        }
872
873        // Handle complex types (option, vec, etc.)
874        if let Some(type_obj) = idl_type.as_object() {
875            if let Some(option_type) = type_obj.get("option") {
876                let inner = self.idl_type_to_typescript(option_type, None);
877                return format!("{} | null", inner);
878            }
879            if let Some(vec_type) = type_obj.get("vec") {
880                let inner = self.idl_type_to_typescript(vec_type, None);
881                return format!("{}[]", inner);
882            }
883        }
884
885        "any".to_string()
886    }
887
888    /// Generate a TypeScript interface from a resolved struct type
889    fn generate_interface_for_resolved_type(&self, resolved: &ResolvedStructType) -> String {
890        let interface_name = to_pascal_case(&resolved.type_name);
891
892        // Handle enums as TypeScript union types
893        if resolved.is_enum {
894            let variants: Vec<String> = resolved
895                .enum_variants
896                .iter()
897                .map(|v| format!("\"{}\"", to_pascal_case(v)))
898                .collect();
899
900            return format!("export type {} = {};", interface_name, variants.join(" | "));
901        }
902
903        // Handle structs as interfaces
904        // All fields are optional since we receive patches
905        let fields: Vec<String> = resolved
906            .fields
907            .iter()
908            .map(|field| {
909                let field_name = to_camel_case(&field.field_name);
910                let base_ts_type = self.resolved_field_to_typescript(field);
911                let ts_type = if field.is_optional {
912                    format!("{} | null", base_ts_type)
913                } else {
914                    base_ts_type
915                };
916                format!("  {}?: {};", field_name, ts_type)
917            })
918            .collect();
919
920        format!(
921            "export interface {} {{\n{}\n}}",
922            interface_name,
923            fields.join("\n")
924        )
925    }
926
927    /// Convert a resolved field to TypeScript type
928    fn resolved_field_to_typescript(&self, field: &ResolvedField) -> String {
929        let base_ts = self.base_type_to_typescript(&field.base_type, false);
930
931        if field.is_array {
932            format!("{}[]", base_ts)
933        } else {
934            base_ts
935        }
936    }
937
938    /// Check if the spec has any event types
939    fn has_event_types(&self) -> bool {
940        for section in &self.spec.sections {
941            for field_info in &section.fields {
942                if let Some(resolved) = &field_info.resolved_type {
943                    if resolved.is_event || (resolved.is_instruction && field_info.is_array) {
944                        return true;
945                    }
946                }
947            }
948        }
949        false
950    }
951
952    /// Generate the EventWrapper interface
953    fn generate_event_wrapper_interface(&self) -> String {
954        r#"/**
955 * Wrapper for event data that includes context metadata.
956 * Events are automatically wrapped in this structure at runtime.
957 */
958export interface EventWrapper<T> {
959  /** Unix timestamp when the event was processed */
960  timestamp: number;
961  /** The event-specific data */
962  data: T;
963  /** Optional blockchain slot number */
964  slot?: number;
965  /** Optional transaction signature */
966  signature?: string;
967}"#
968        .to_string()
969    }
970
971    fn infer_type_from_field_name(&self, field_name: &str) -> String {
972        let lower_name = field_name.to_lowercase();
973
974        // Special case for event fields - these are typically Option<Value> and should be 'any'
975        if lower_name.contains("events.") {
976            // For fields in the events section, default to 'any' since they're typically Option<Value>
977            return "any".to_string();
978        }
979
980        // Common patterns for type inference
981        if lower_name.contains("id")
982            || lower_name.contains("count")
983            || lower_name.contains("number")
984            || lower_name.contains("timestamp")
985            || lower_name.contains("time")
986            || lower_name.contains("at")
987            || lower_name.contains("volume")
988            || lower_name.contains("amount")
989            || lower_name.contains("ev")
990            || lower_name.contains("fee")
991            || lower_name.contains("payout")
992            || lower_name.contains("distributed")
993            || lower_name.contains("claimable")
994            || lower_name.contains("total")
995            || lower_name.contains("rate")
996            || lower_name.contains("ratio")
997            || lower_name.contains("current")
998            || lower_name.contains("state")
999        {
1000            "number".to_string()
1001        } else if lower_name.contains("status")
1002            || lower_name.contains("hash")
1003            || lower_name.contains("address")
1004            || lower_name.contains("key")
1005        {
1006            "string".to_string()
1007        } else {
1008            "any".to_string()
1009        }
1010    }
1011
1012    fn is_field_optional(&self, mapping: &TypedFieldMapping<S>) -> bool {
1013        // Most fields should be optional by default since we're dealing with Option<T> types
1014        match &mapping.source {
1015            // Constants are typically non-optional
1016            MappingSource::Constant(_) => false,
1017            // Events are typically optional (Option<Value>)
1018            MappingSource::AsEvent { .. } => true,
1019            // For source fields, default to optional since most Rust fields are Option<T>
1020            MappingSource::FromSource { .. } => true,
1021            // Other cases default to optional
1022            _ => true,
1023        }
1024    }
1025
1026    /// Convert language-agnostic base types to TypeScript types
1027    fn base_type_to_typescript(&self, base_type: &BaseType, is_array: bool) -> String {
1028        let base_ts_type = match base_type {
1029            BaseType::Integer => "number",
1030            BaseType::Float => "number",
1031            BaseType::String => "string",
1032            BaseType::Boolean => "boolean",
1033            BaseType::Timestamp => "number", // Unix timestamps as numbers
1034            BaseType::Binary => "string",    // Base64 encoded strings
1035            BaseType::Pubkey => "string",    // Solana public keys as Base58 strings
1036            BaseType::Array => "any[]",      // Default array type
1037            BaseType::Object => "Record<string, any>", // Generic object
1038            BaseType::Any => "any",
1039        };
1040
1041        if is_array && !matches!(base_type, BaseType::Array) {
1042            format!("{}[]", base_ts_type)
1043        } else {
1044            base_ts_type.to_string()
1045        }
1046    }
1047}
1048
1049/// Represents a TypeScript field in an interface
1050#[derive(Debug, Clone)]
1051struct TypeScriptField {
1052    name: String,
1053    ts_type: String,
1054    optional: bool,
1055    #[allow(dead_code)]
1056    description: Option<String>,
1057}
1058
1059/// Convert serde_json::Value to TypeScript type string
1060fn value_to_typescript_type(value: &serde_json::Value) -> String {
1061    match value {
1062        serde_json::Value::Number(_) => "number".to_string(),
1063        serde_json::Value::String(_) => "string".to_string(),
1064        serde_json::Value::Bool(_) => "boolean".to_string(),
1065        serde_json::Value::Array(_) => "any[]".to_string(),
1066        serde_json::Value::Object(_) => "Record<string, any>".to_string(),
1067        serde_json::Value::Null => "null".to_string(),
1068    }
1069}
1070
1071/// Convert snake_case to PascalCase
1072fn to_pascal_case(s: &str) -> String {
1073    s.split(['_', '-', '.'])
1074        .map(|word| {
1075            let mut chars = word.chars();
1076            match chars.next() {
1077                None => String::new(),
1078                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
1079            }
1080        })
1081        .collect()
1082}
1083
1084/// Convert snake_case to camelCase
1085fn to_camel_case(s: &str) -> String {
1086    let pascal = to_pascal_case(s);
1087    let mut chars = pascal.chars();
1088    match chars.next() {
1089        None => String::new(),
1090        Some(first) => first.to_lowercase().collect::<String>() + chars.as_str(),
1091    }
1092}
1093
1094/// Convert PascalCase/camelCase to snake_case
1095fn to_snake_case(s: &str) -> String {
1096    let mut result = String::new();
1097
1098    for ch in s.chars() {
1099        if ch.is_uppercase() {
1100            if !result.is_empty() {
1101                result.push('_');
1102            }
1103            result.push(ch.to_lowercase().next().unwrap());
1104        } else {
1105            result.push(ch);
1106        }
1107    }
1108
1109    result
1110}
1111
1112/// Check if a section name is the root section (case-insensitive)
1113fn is_root_section(name: &str) -> bool {
1114    name.eq_ignore_ascii_case("root")
1115}
1116
1117/// Convert PascalCase/camelCase to kebab-case
1118fn to_kebab_case(s: &str) -> String {
1119    let mut result = String::new();
1120
1121    for ch in s.chars() {
1122        if ch.is_uppercase() && !result.is_empty() {
1123            result.push('-');
1124        }
1125        result.push(ch.to_lowercase().next().unwrap());
1126    }
1127
1128    result
1129}
1130
1131/// CLI-friendly function to generate TypeScript from a spec function
1132/// This will be used by the CLI tool to generate TypeScript from discovered specs
1133pub fn generate_typescript_from_spec_fn<F, S>(
1134    spec_fn: F,
1135    entity_name: String,
1136    config: Option<TypeScriptConfig>,
1137) -> Result<TypeScriptOutput, String>
1138where
1139    F: Fn() -> TypedStreamSpec<S>,
1140{
1141    let spec = spec_fn();
1142    let compiler =
1143        TypeScriptCompiler::new(spec, entity_name).with_config(config.unwrap_or_default());
1144
1145    Ok(compiler.compile())
1146}
1147
1148/// Write TypeScript output to a file
1149pub fn write_typescript_to_file(
1150    output: &TypeScriptOutput,
1151    path: &std::path::Path,
1152) -> Result<(), std::io::Error> {
1153    std::fs::write(path, output.full_file())
1154}
1155
1156/// Generate TypeScript from a SerializableStreamSpec (for CLI use)
1157/// This allows the CLI to compile TypeScript without needing the typed spec
1158pub fn compile_serializable_spec(
1159    spec: SerializableStreamSpec,
1160    entity_name: String,
1161    config: Option<TypeScriptConfig>,
1162) -> Result<TypeScriptOutput, String> {
1163    // Extract IDL and convert to serde_json::Value
1164    let idl = spec
1165        .idl
1166        .as_ref()
1167        .and_then(|idl_snapshot| serde_json::to_value(idl_snapshot).ok());
1168
1169    // Extract handlers as JSON
1170    let handlers = serde_json::to_value(&spec.handlers).ok();
1171
1172    // Convert SerializableStreamSpec to TypedStreamSpec
1173    // We use () as the phantom type since it won't be used
1174    let typed_spec: TypedStreamSpec<()> = TypedStreamSpec::from_serializable(spec);
1175
1176    let compiler = TypeScriptCompiler::new(typed_spec, entity_name)
1177        .with_idl(idl)
1178        .with_handlers_json(handlers)
1179        .with_config(config.unwrap_or_default());
1180
1181    Ok(compiler.compile())
1182}
1183
1184#[cfg(test)]
1185mod tests {
1186    use super::*;
1187
1188    #[test]
1189    fn test_case_conversions() {
1190        assert_eq!(to_pascal_case("settlement_game"), "SettlementGame");
1191        assert_eq!(to_camel_case("settlement_game"), "settlementGame");
1192        assert_eq!(to_kebab_case("SettlementGame"), "settlement-game");
1193    }
1194
1195    #[test]
1196    fn test_value_to_typescript_type() {
1197        assert_eq!(value_to_typescript_type(&serde_json::json!(42)), "number");
1198        assert_eq!(
1199            value_to_typescript_type(&serde_json::json!("hello")),
1200            "string"
1201        );
1202        assert_eq!(
1203            value_to_typescript_type(&serde_json::json!(true)),
1204            "boolean"
1205        );
1206        assert_eq!(value_to_typescript_type(&serde_json::json!([])), "any[]");
1207    }
1208}