hypen-engine 0.4.46

A Rust implementation of the Hypen engine
Documentation
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
//! JavaScript/WASM bindings for Hypen Engine
//!
//! This module provides JavaScript-specific bindings via wasm-bindgen.
//! For WASI/non-JS runtimes, see the `wasi` module.

use serde_wasm_bindgen::from_value;
use std::collections::HashSet;
use wasm_bindgen::prelude::*;

/// Static null value to avoid cloning state when no module exists
static NULL_STATE: serde_json::Value = serde_json::Value::Null;

/// Format parser errors into a human-readable message.
fn format_parse_errors(errors: &[hypen_parser::error::Rich<char>]) -> String {
    errors
        .iter()
        .map(|e| hypen_parser::error::format_error_simple(e))
        .collect::<Vec<_>>()
        .join("; ")
}

/// Create a structured JS error object that consumers can programmatically inspect.
///
/// Returns a JS object: `{ type: "<errorType>", message: "<humanReadable>" }`
///
/// Error types: `"parseError"`, `"stateError"`, `"actionError"`, `"renderError"`, `"componentError"`
fn structured_error(error_type: &str, message: &str) -> JsValue {
    let obj = js_sys::Object::new();
    let _ = js_sys::Reflect::set(&obj, &"type".into(), &JsValue::from_str(error_type));
    let _ = js_sys::Reflect::set(&obj, &"message".into(), &JsValue::from_str(message));
    obj.into()
}

use crate::{
    dispatch::Action,
    ir::ComponentRegistry,
    ir::{ast_to_ir_node, Element, IRNode, NodeId},
    lifecycle::{Module, ModuleInstance},
    reactive::{DependencyGraph, Scheduler},
    reconcile::{create_ir_node_tree, reconcile_ir_node, reconcile_ir_with_ds, InstanceTree, Patch},
};

/// The main Hypen engine interface for JavaScript/WASM runtimes.
///
/// `WasmEngine` manages the full lifecycle of a Hypen UI: parsing DSL source,
/// maintaining the virtual tree, tracking reactive dependencies, and emitting
/// minimal patches when state changes. It runs in a single-threaded WASM
/// environment (browsers, Node.js, Bun, Deno).
///
/// # Quick Start
///
/// ```js
/// import { WasmEngine } from "@hypen-space/core";
///
/// const engine = new WasmEngine();
///
/// // 1. Register primitives so the engine doesn't try to resolve them as components
/// engine.registerPrimitive("Text");
/// engine.registerPrimitive("Column");
///
/// // 2. Receive patches via callback
/// engine.setRenderCallback((patches) => {
///     for (const patch of patches) {
///         applyPatch(patch); // Create, SetProp, Insert, Remove, etc.
///     }
/// });
///
/// // 3. Optionally set up a module for stateful UI
/// engine.setModule("Counter", ["increment"], ["count"], { count: 0 });
///
/// // 4. Render DSL source — patches are emitted via the callback
/// engine.renderSource('Column { Text("Count: ${state.count}") }');
///
/// // 5. Update state — only affected nodes are re-rendered
/// engine.updateState({ count: 1 });
/// ```
///
/// # Patch Protocol
///
/// All UI mutations are expressed as [`Patch`] values emitted through the render
/// callback. Patches use camelCase field names for direct JavaScript consumption.
/// See [`Patch`] for the full variant list and field documentation.
///
/// # Component Resolution
///
/// Custom components (anything not registered as a primitive) are resolved lazily
/// via the component resolver callback set with [`set_component_resolver`]. The
/// resolver receives `(componentName, contextPath)` and should return
/// `{ source: string, path: string }` or `null`.
///
/// # Revision Tracking
///
/// Every render cycle (initial render or state update that produces patches)
/// increments the revision counter. Use [`get_revision`] to detect stale state
/// in async workflows.
#[wasm_bindgen]
pub struct WasmEngine {
    component_registry: ComponentRegistry,
    module: Option<ModuleInstance>,
    tree: InstanceTree,
    dependencies: DependencyGraph,
    scheduler: Scheduler,
    revision: u64,
    patch_callback: Option<js_sys::Function>,
    action_handlers: std::collections::HashMap<String, js_sys::Function>,
    root_ir_node: Option<IRNode>,
    component_resolver: Option<js_sys::Function>,
    /// Tracks visited import paths to prevent circular imports during resolution
    import_visited: HashSet<String>,
    /// O(1) index from compact node-ID strings (e.g. "1", "42") to their
    /// actual SlotMap keys.  Populated from Create patches.
    node_id_index: std::collections::HashMap<String, NodeId>,

    /// Data source states: provider name → current state.
    /// Populated by plugins via `registerDataSource` / `updateDataSource`.
    data_sources: indexmap::IndexMap<String, serde_json::Value>,

    /// Callback for data source actions (e.g., @actions.spacetime.sendMessage).
    /// Receives `{ provider, method, payload }` when a data source action is dispatched
    /// and no explicit handler is registered for the full action name.
    data_source_action_handler: Option<js_sys::Function>,
}

#[wasm_bindgen]
impl WasmEngine {
    /// Create a new engine instance with an empty tree and no module.
    ///
    /// After construction, you typically:
    /// 1. Register primitives with [`register_primitive`]
    /// 2. Set a render callback with [`set_render_callback`]
    /// 3. Optionally set a component resolver with [`set_component_resolver`]
    /// 4. Optionally initialize a module with [`set_module`]
    /// 5. Render source with [`render_source`]
    #[allow(clippy::new_without_default)]
    #[wasm_bindgen(constructor)]
    pub fn new() -> Self {
        // Enable console_error_panic_hook for better debugging
        #[cfg(feature = "console_error_panic_hook")]
        console_error_panic_hook::set_once();

        Self {
            component_registry: ComponentRegistry::new(),
            module: None,
            tree: InstanceTree::new(),
            dependencies: DependencyGraph::new(),
            scheduler: Scheduler::new(),
            revision: 0,
            patch_callback: None,
            action_handlers: std::collections::HashMap::new(),
            root_ir_node: None,
            component_resolver: None,
            import_visited: HashSet::new(),
            node_id_index: std::collections::HashMap::new(),
            data_sources: indexmap::IndexMap::new(),
            data_source_action_handler: None,
        }
    }

    /// Parse and render Hypen DSL source code, emitting patches via the render callback.
    ///
    /// Supports full document syntax including `import` statements. Imports are
    /// resolved synchronously through the component resolver callback (if set).
    ///
    /// This performs a **full reconciliation** — the existing tree is diffed against
    /// the new IR and minimal patches are emitted. Calling this multiple times with
    /// different source replaces the previous UI.
    ///
    /// # Errors
    ///
    /// Returns a `JsValue` string error if the source fails to parse.
    #[wasm_bindgen(js_name = renderSource)]
    pub fn render_source(&mut self, source: &str) -> Result<(), JsValue> {
        let doc = hypen_parser::parse_document(source)
            .map_err(|e| structured_error("parseError", &format_parse_errors(&e)))?;

        // Pre-resolve imported components before rendering
        self.import_visited.clear();
        self.resolve_imports(&doc.imports);

        // Render the first component (entry point)
        if let Some(component) = doc.components.first() {
            let ir_node = ast_to_ir_node(component);
            self.root_ir_node = Some(ir_node.clone());
            self.render(&ir_node);
        }

        Ok(())
    }

    /// Set the callback that receives UI patches after each render cycle.
    ///
    /// The callback is invoked with a single argument: a JavaScript array of
    /// [`Patch`] objects. Each patch describes one atomic DOM operation (Create,
    /// SetProp, SetText, Insert, Move, Remove, RemoveProp).
    ///
    /// The callback is called synchronously during `renderSource()`, `updateState()`,
    /// `updateStateSparse()`, and `renderInto()`.
    ///
    /// # Example (JS)
    /// ```js
    /// engine.setRenderCallback((patches) => {
    ///     for (const p of patches) {
    ///         switch (p.type) {
    ///             case "create": createElement(p.id, p.elementType, p.props); break;
    ///             case "setProp": setProperty(p.id, p.name, p.value); break;
    ///             case "insert": insertChild(p.parentId, p.id, p.beforeId); break;
    ///             // ...
    ///         }
    ///     }
    /// });
    /// ```
    #[wasm_bindgen(js_name = setRenderCallback)]
    pub fn set_render_callback(&mut self, callback: js_sys::Function) {
        self.patch_callback = Some(callback);
    }

    /// Set the component resolver callback
    /// The resolver receives (componentName, contextPath) and should return
    /// { source: string, path: string } or null
    ///
    /// contextPath is the path of the component that's referencing this component
    /// The returned path should be the resolved absolute path to the component file
    #[wasm_bindgen(js_name = setComponentResolver)]
    pub fn set_component_resolver(&mut self, resolver: js_sys::Function) {
        self.component_resolver = Some(resolver);
    }

    /// Register a primitive element (like Text, Button, etc.) to skip component resolution
    /// This prevents unnecessary resolver calls for built-in DOM elements
    #[wasm_bindgen(js_name = registerPrimitive)]
    pub fn register_primitive(&mut self, name: &str) {
        self.component_registry.register_primitive(name);
    }

    /// Register all standard Hypen primitives (Text, Column, Row, Button, etc.)
    #[wasm_bindgen(js_name = registerDefaultPrimitives)]
    pub fn register_default_primitives(&mut self) {
        self.component_registry.register_default_primitives();
    }

    /// Clear resolved components and caches, preserving primitives and resolver.
    /// Call before renderSource() during hot-reload so components are re-resolved
    /// from fresh source files instead of using stale cached definitions.
    #[wasm_bindgen(js_name = clearResolvedComponents)]
    pub fn clear_resolved_components(&mut self) {
        self.component_registry.clear_resolved();
    }

    /// Render a component source on-demand (for lazy-loaded routes).
    ///
    /// Equivalent to calling [`render_source`] — the source is parsed as a full
    /// document and replaces the current tree.
    #[wasm_bindgen(js_name = renderLazyComponent)]
    pub fn render_lazy_component(&mut self, source: &str) -> Result<(), JsValue> {
        // Parse and render the source
        self.render_source(source)
    }

    /// Render a component into a specific parent node (subtree rendering)
    /// This is used for lazy routing where components are rendered on-demand into route containers
    ///
    /// # Arguments
    /// * `source` - The Hypen DSL source to parse and render
    /// * `parent_node_id_str` - The serialized node ID string of the parent element
    /// * `state_js` - The state to use for rendering (as JsValue)
    #[wasm_bindgen(js_name = renderInto)]
    pub fn render_into(
        &mut self,
        source: &str,
        parent_node_id_str: &str,
        state_js: JsValue,
    ) -> Result<(), JsValue> {
        // Parse as document to support import statements
        let doc = hypen_parser::parse_document(source)
            .map_err(|e| structured_error("parseError", &format_parse_errors(&e)))?;

        // Pre-resolve imported components
        self.import_visited.clear();
        self.resolve_imports(&doc.imports);

        let component = doc
            .components
            .first()
            .ok_or_else(|| structured_error("parseError", "No component found in source"))?;

        // Convert to IRNode (supports first-class ForEach, When/If)
        let ir_node = ast_to_ir_node(component);

        // Resolve any unregistered components in the IR node
        self.resolve_ir_node_components(&ir_node);

        // Expand the IR node using the registry
        let expanded = self.component_registry.expand_ir_node(&ir_node);

        // Use the provided state instead of module state
        let state: serde_json::Value = if state_js.is_null() || state_js.is_undefined() {
            serde_json::Value::Null
        } else {
            from_value(state_js).map_err(|e| structured_error("stateError", &e.to_string()))?
        };

        // O(1) lookup via the node-ID index (populated from Create patches)
        let parent_id = self
            .node_id_index
            .get(parent_node_id_str)
            .copied()
            .ok_or_else(|| {
                structured_error(
                    "renderError",
                    &format!("Parent node not found: {}", parent_node_id_str),
                )
            })?;

        #[cfg(debug_assertions)]
        web_sys::console::log_1(
            &format!("[WASM] Rendering into parent node: {}", parent_node_id_str).into(),
        );

        let mut patches = Vec::new();

        // Check if parent already has children - if so, reconcile; otherwise create
        let parent_has_children = self
            .tree
            .get(parent_id)
            .map(|node| !node.children.is_empty())
            .unwrap_or(false);

        let ds = if self.data_sources.is_empty() {
            None
        } else {
            Some(&self.data_sources)
        };

        if parent_has_children {
            // Reconcile existing children with the new IR node
            #[cfg(debug_assertions)]
            web_sys::console::log_1(&"[WASM] Reconciling existing route content".into());
            if let Some(parent_node) = self.tree.get(parent_id) {
                if let Some(&first_child_id) = parent_node.children.front() {
                    reconcile_ir_node(
                        &mut self.tree,
                        first_child_id,
                        &expanded,
                        &state,
                        &mut patches,
                        &mut self.dependencies,
                        ds,
                    );
                }
            }
        } else {
            // Create the subtree under the specified parent (first render)
            #[cfg(debug_assertions)]
            web_sys::console::log_1(&"[WASM] Creating new route content".into());
            create_ir_node_tree(
                &mut self.tree,
                &expanded,
                Some(parent_id),
                &state,
                &mut patches,
                false, // Not root
                &mut self.dependencies,
                ds,
            );
        }

        // Emit patches to the renderer
        self.emit_patches(patches);

        self.revision += 1;

        Ok(())
    }

    /// Internal render method using IRNode
    fn render(&mut self, ir_node: &IRNode) {
        // Try to resolve any unregistered components in the IR node
        self.resolve_ir_node_components(ir_node);

        // Expand components in the IR node
        let expanded = self.component_registry.expand_ir_node(ir_node);

        // Get state reference (no clone needed - reconcile only borrows)
        let state: &serde_json::Value = self
            .module
            .as_ref()
            .map(|m| m.get_state())
            .unwrap_or(&NULL_STATE);

        // Clear dependencies
        self.dependencies.clear();

        // Reconcile using IRNode and generate patches (with data sources)
        let ds = if self.data_sources.is_empty() {
            None
        } else {
            Some(&self.data_sources)
        };
        let patches = reconcile_ir_with_ds(
            &mut self.tree,
            &expanded,
            None,
            state,
            &mut self.dependencies,
            ds,
        );

        // Emit patches via callback
        self.emit_patches(patches);

        self.revision += 1;
    }

    /// Pre-resolve imported components via the JS resolver callback.
    /// For each import, calls the resolver with (componentName, importSourcePath).
    /// If the resolved source itself contains imports, recurses to resolve them too.
    fn resolve_imports(&mut self, imports: &[hypen_parser::ImportStatement]) {
        let resolver = match self.component_resolver.clone() {
            Some(r) => r,
            None => return, // No resolver set — imports can't be resolved
        };

        for import in imports {
            let source_path = import.source_path();

            for name in import.imported_names() {
                // Skip if already registered
                if self
                    .component_registry
                    .get(&name, Some(source_path))
                    .is_some()
                {
                    continue;
                }

                // Prevent circular imports
                let import_key = format!("{}:{}", source_path, name);
                if self.import_visited.contains(&import_key) {
                    continue;
                }
                self.import_visited.insert(import_key);

                // Call JS resolver with (componentName, importSourcePath)
                let name_js = JsValue::from_str(&name);
                let source_path_js = JsValue::from_str(source_path);

                if let Ok(result) = resolver.call2(&JsValue::NULL, &name_js, &source_path_js) {
                    if result.is_null() || result.is_undefined() {
                        continue;
                    }

                    let source_val =
                        js_sys::Reflect::get(&result, &JsValue::from_str("source")).ok();
                    let path_val = js_sys::Reflect::get(&result, &JsValue::from_str("path")).ok();
                    let passthrough_val =
                        js_sys::Reflect::get(&result, &JsValue::from_str("passthrough")).ok();
                    let lazy_val = js_sys::Reflect::get(&result, &JsValue::from_str("lazy")).ok();

                    if let (Some(source_js), Some(path_js)) = (source_val, path_val) {
                        if let (Some(resolved_source), Some(path)) =
                            (source_js.as_string(), path_js.as_string())
                        {
                            let is_lazy = lazy_val.and_then(|v| v.as_bool()).unwrap_or(false);
                            let is_passthrough =
                                passthrough_val.and_then(|v| v.as_bool()).unwrap_or(false);

                            if is_lazy {
                                let dummy_element = Element::new(&name);
                                let component =
                                    crate::ir::Component::new(name.clone(), move |_props| {
                                        dummy_element.clone()
                                    })
                                    .with_source_path(&path)
                                    .with_lazy(true);
                                self.component_registry.register(component);
                            } else if is_passthrough {
                                let dummy_element = Element::new(&name);
                                let component =
                                    crate::ir::Component::new(name.clone(), move |_props| {
                                        dummy_element.clone()
                                    })
                                    .with_source_path(&path)
                                    .with_passthrough(true);
                                self.component_registry.register(component);
                            } else {
                                // Parse the resolved source as a document — it may have its own imports
                                if let Ok(resolved_doc) =
                                    hypen_parser::parse_document(&resolved_source)
                                {
                                    // Recursively resolve this document's imports
                                    self.resolve_imports(&resolved_doc.imports);

                                    // Register the component from the first component spec
                                    if let Some(component_spec) = resolved_doc.components.first() {
                                        let ir_node = ast_to_ir_node(component_spec);
                                        if let IRNode::Element(ir_element) = &ir_node {
                                            let ir_element = ir_element.clone();
                                            let component = crate::ir::Component::new(
                                                name.clone(),
                                                move |_props| ir_element.clone(),
                                            )
                                            .with_source_path(&path);
                                            self.component_registry.register(component);
                                        }

                                        // Also resolve any unregistered components referenced in children
                                        self.resolve_ir_node_components_with_context(
                                            &ir_node,
                                            Some(&path),
                                        );
                                    }
                                } else if let Ok(component_spec) =
                                    hypen_parser::parse_component(&resolved_source)
                                {
                                    // Fallback: try parsing as bare component (no imports)
                                    let ir_node = ast_to_ir_node(&component_spec);
                                    if let IRNode::Element(ir_element) = &ir_node {
                                        let ir_element = ir_element.clone();
                                        let component =
                                            crate::ir::Component::new(name.clone(), move |_props| {
                                                ir_element.clone()
                                            })
                                            .with_source_path(&path);
                                        self.component_registry.register(component);
                                    }

                                    self.resolve_ir_node_components_with_context(
                                        &ir_node,
                                        Some(&path),
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /// Recursively resolve components with path context
    fn resolve_components_with_context(&mut self, element: &Element, context_path: Option<&str>) {
        // Skip primitives — they are built-in and never need resolution
        if self.component_registry.is_primitive(&element.element_type) {
            // Still resolve children
            for child in &element.children {
                self.resolve_components_with_context(child, context_path);
            }
            return;
        }

        // Check if this component needs to be resolved
        if self
            .component_registry
            .get(&element.element_type, context_path)
            .is_none()
        {
            if let Some(ref resolver) = self.component_resolver.clone() {
                let name_js = JsValue::from_str(&element.element_type);
                let context_js = context_path.map(JsValue::from_str).unwrap_or(JsValue::NULL);

                if let Ok(result) = resolver.call2(&JsValue::NULL, &name_js, &context_js) {
                    if !result.is_null() && !result.is_undefined() {
                        // Expect result to be { source: string, path: string, passthrough?: boolean, lazy?: boolean }
                        let source_val =
                            js_sys::Reflect::get(&result, &JsValue::from_str("source")).ok();
                        let path_val =
                            js_sys::Reflect::get(&result, &JsValue::from_str("path")).ok();
                        let passthrough_val =
                            js_sys::Reflect::get(&result, &JsValue::from_str("passthrough")).ok();
                        let lazy_val =
                            js_sys::Reflect::get(&result, &JsValue::from_str("lazy")).ok();

                        if let (Some(source_js), Some(path_js)) = (source_val, path_val) {
                            if let (Some(source), Some(path)) =
                                (source_js.as_string(), path_js.as_string())
                            {
                                let is_lazy = lazy_val.and_then(|v| v.as_bool()).unwrap_or(false);

                                let is_passthrough =
                                    passthrough_val.and_then(|v| v.as_bool()).unwrap_or(false);

                                if is_lazy {
                                    // Lazy component: don't parse, just create a dummy component
                                    #[cfg(debug_assertions)]
                                    web_sys::console::log_1(
                                        &format!(
                                            "[WASM] Registering lazy component: {}",
                                            element.element_type
                                        )
                                        .into(),
                                    );

                                    let name = element.element_type.clone();
                                    let dummy_element = Element::new(&name);
                                    let component =
                                        crate::ir::Component::new(name.clone(), move |_props| {
                                            dummy_element.clone()
                                        })
                                        .with_source_path(&path)
                                        .with_lazy(true);

                                    self.component_registry.register(component);
                                } else if is_passthrough {
                                    // Passthrough component: don't parse, just create a dummy component
                                    #[cfg(debug_assertions)]
                                    web_sys::console::log_1(
                                        &format!(
                                            "[WASM] Registering passthrough component: {}",
                                            element.element_type
                                        )
                                        .into(),
                                    );

                                    let name = element.element_type.clone();
                                    let dummy_element = Element::new(&name);
                                    let component =
                                        crate::ir::Component::new(name.clone(), move |_props| {
                                            dummy_element.clone()
                                        })
                                        .with_source_path(&path)
                                        .with_passthrough(true);

                                    self.component_registry.register(component);
                                } else {
                                    // Regular component: parse and register
                                    if let Ok(component_spec) =
                                        hypen_parser::parse_component(&source)
                                    {
                                        let ir_node = ast_to_ir_node(&component_spec);
                                        let name = element.element_type.clone();
                                        let path_clone = path.clone();

                                        if let IRNode::Element(ir_element) = &ir_node {
                                            let ir_element = ir_element.clone();
                                            let component = crate::ir::Component::new(
                                                name.clone(),
                                                move |_props| ir_element.clone(),
                                            )
                                            .with_source_path(&path);

                                            self.component_registry.register(component);
                                        }

                                        // Recursively resolve children of this component with its path as context
                                        self.resolve_ir_node_components_with_context(
                                            &ir_node,
                                            Some(&path_clone),
                                        );
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // Recursively resolve children
        for child in &element.children {
            self.resolve_components_with_context(child, context_path);
        }
    }

    /// Recursively resolve components in an IRNode using the JS resolver
    fn resolve_ir_node_components(&mut self, node: &IRNode) {
        self.resolve_ir_node_components_with_context(node, None);
    }

    /// Recursively resolve components in an IRNode with path context
    fn resolve_ir_node_components_with_context(
        &mut self,
        node: &IRNode,
        context_path: Option<&str>,
    ) {
        match node {
            IRNode::Element(element) => {
                // Resolve the element itself
                self.resolve_components_with_context(element, context_path);
                // Also resolve ir_children if present (control-flow children)
                for child in &element.ir_children {
                    self.resolve_ir_node_components_with_context(child, context_path);
                }
            }
            IRNode::ForEach { template, .. } => {
                // Resolve components in template children
                for child in template {
                    self.resolve_ir_node_components_with_context(child, context_path);
                }
            }
            IRNode::Conditional {
                branches, fallback, ..
            } => {
                // Resolve components in branches
                for branch in branches {
                    for child in &branch.children {
                        self.resolve_ir_node_components_with_context(child, context_path);
                    }
                }
                // Resolve components in fallback
                if let Some(fb) = fallback {
                    for child in fb {
                        self.resolve_ir_node_components_with_context(child, context_path);
                    }
                }
            }
        }
    }

    /// Emit patches to the callback
    fn emit_patches(&mut self, patches: Vec<Patch>) {
        // Index newly created node IDs for O(1) lookup in render_into.
        // node_id_str() uses a global monotonic counter, so we can reverse-map
        // efficiently by scanning only the tree nodes that correspond to new patches.
        for patch in &patches {
            if let Patch::Create { id, .. } = patch {
                if !self.node_id_index.contains_key(id) {
                    // node_id_str() is deterministic — scan tree for the matching NodeId
                    for (node_id, _) in self.tree.iter() {
                        if crate::reconcile::node_id_str(node_id) == *id {
                            self.node_id_index.insert(id.clone(), node_id);
                            break;
                        }
                    }
                }
            }
        }

        if let Some(ref callback) = self.patch_callback {
            // Use json_compatible() to ensure IndexMap props serialize as plain JS objects
            // instead of ES2015 Map objects (which appear as empty {} in JS)
            let serializer = serde_wasm_bindgen::Serializer::json_compatible();
            if let Ok(patches_js) = serde::Serialize::serialize(&patches, &serializer) {
                let _ = callback.call1(&JsValue::NULL, &patches_js);
            }
        }
    }

    /// Apply a state patch and re-render affected nodes.
    ///
    /// The `state_patch` is a JavaScript object whose keys are merged into the
    /// current module state (deep merge). Only nodes whose bindings reference
    /// changed paths are re-rendered, producing minimal patches.
    ///
    /// # Example (JS)
    /// ```js
    /// // Updates state.user.name and state.count, re-renders bound nodes
    /// engine.updateState({ user: { name: "Bob" }, count: 42 });
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if `state_patch` cannot be deserialized as JSON.
    #[wasm_bindgen(js_name = updateState)]
    pub fn update_state(&mut self, state_patch: JsValue) -> Result<(), JsValue> {
        let patch: serde_json::Value = from_value(state_patch)
            .map_err(|e| structured_error("stateError", &format!("Invalid state patch: {}", e)))?;

        // Extract changed paths from the patch
        let changed_paths = super::ffi::extract_changed_paths(&patch);

        // Update module state
        if let Some(module) = &mut self.module {
            module.update_state(patch);
        }

        // Find affected nodes and mark them dirty
        let mut affected_nodes = Vec::new();
        for path in &changed_paths {
            affected_nodes.extend(self.dependencies.get_affected_nodes(path));
        }

        for &node_id in &affected_nodes {
            self.scheduler.mark_dirty(node_id);
        }

        // Render only dirty nodes (not the entire tree)
        self.render_dirty();

        Ok(())
    }

    /// Apply a sparse state update using explicit path-value pairs.
    ///
    /// More efficient than [`update_state`] for large state objects when only a
    /// few deeply-nested paths changed, because it avoids a full deep-merge.
    ///
    /// # Arguments
    /// * `paths_js` — JS array of dot-separated paths that changed (e.g. `["user.name", "count"]`)
    /// * `values_js` — JS object mapping each path to its new value (e.g. `{ "user.name": "Bob", "count": 42 }`)
    ///
    /// # Errors
    ///
    /// Returns an error if either argument cannot be deserialized.
    #[wasm_bindgen(js_name = updateStateSparse)]
    pub fn update_state_sparse(
        &mut self,
        paths_js: JsValue,
        values_js: JsValue,
    ) -> Result<(), JsValue> {
        // Parse paths array
        let paths: Vec<String> = from_value(paths_js)
            .map_err(|e| structured_error("stateError", &format!("Invalid paths array: {}", e)))?;

        // Parse values object
        let values: serde_json::Value = from_value(values_js).map_err(|e| {
            structured_error("stateError", &format!("Invalid values object: {}", e))
        })?;

        // Update module state using sparse update
        if let Some(module) = &mut self.module {
            module.update_state_sparse(&paths, &values);
        }

        // Find affected nodes and mark them dirty
        let mut affected_nodes = Vec::new();
        for path in &paths {
            affected_nodes.extend(self.dependencies.get_affected_nodes(path));
        }

        for &node_id in &affected_nodes {
            self.scheduler.mark_dirty(node_id);
        }

        // Render only dirty nodes (not the entire tree)
        self.render_dirty();

        Ok(())
    }

    /// Render only dirty nodes (optimized for state changes)
    fn render_dirty(&mut self) {
        let ds = if self.data_sources.is_empty() {
            None
        } else {
            Some(&self.data_sources)
        };
        let patches = crate::render::render_dirty_nodes_full(
            &mut self.scheduler,
            &mut self.tree,
            self.module.as_ref(),
            &mut self.dependencies,
            ds,
        );

        if !patches.is_empty() {
            self.emit_patches(patches);
            self.revision += 1;
        }
    }

    // ── Data Source Context ─────────────────────────────────────────

    /// Set (or replace) a named data source context.
    ///
    /// Registers the provider in the dependency graph (if not already known),
    /// stores the data, and re-renders every node bound to `$name.*`.
    /// Sparse merging (if needed) should happen at the SDK layer before
    /// calling this method with the merged object.
    ///
    /// # Example (JS)
    /// ```js
    /// engine.setContext("spacetime", {
    ///     message: [{ id: 1, text: "Hello" }, { id: 2, text: "World" }],
    ///     user: [{ id: 1, name: "Alice", online: true }]
    /// });
    /// ```
    #[wasm_bindgen(js_name = setContext)]
    pub fn set_context(&mut self, name: &str, data_js: JsValue) -> Result<(), JsValue> {
        let data: serde_json::Value = from_value(data_js).map_err(|e| {
            structured_error(
                "stateError",
                &format!("Invalid context data: {}", e),
            )
        })?;

        // Ensure provider is registered in the dependency graph
        self.dependencies.register_data_source_provider(name);

        // Find affected nodes using top-level keys
        let mut affected_nodes = Vec::new();
        if let Some(obj) = data.as_object() {
            for key in obj.keys() {
                let namespaced = format!("ds:{}:{}", name, key);
                affected_nodes.extend(self.dependencies.get_affected_nodes(&namespaced));
            }
        }
        // Also check for nodes bound to the provider root
        let root_key = format!("ds:{}", name);
        affected_nodes.extend(self.dependencies.get_affected_nodes(&root_key));

        // Store data (consumed directly — no clone)
        self.data_sources.insert(name.to_string(), data);

        for &node_id in &affected_nodes {
            self.scheduler.mark_dirty(node_id);
        }

        self.render_dirty();
        Ok(())
    }

    /// Remove a data source context entirely.
    ///
    /// Drops the provider's state and re-renders bound nodes (they resolve to `null`).
    #[wasm_bindgen(js_name = removeContext)]
    pub fn remove_context(&mut self, name: &str) {
        self.data_sources.shift_remove(name);

        // Find all nodes bound to ds:name or ds:name:* and mark dirty.
        // Uses dedicated scan because `:` separators aren't indexed.
        let affected = self.dependencies.get_data_source_affected_nodes(name);
        if !affected.is_empty() {
            for &node_id in &affected {
                self.scheduler.mark_dirty(node_id);
            }
            self.render_dirty();
        }
    }

    // ── Actions ─────────────────────────────────────────────────────

    /// Dispatch a named action, invoking the registered handler (if any).
    ///
    /// Actions are the primary way UI events flow from the renderer back to
    /// application logic. In Hypen DSL, buttons reference actions like
    /// `Button("@actions.submit")` — the renderer maps clicks to
    /// `engine.dispatchAction("submit", payload)`.
    ///
    /// # Arguments
    /// * `name` — Action name (e.g. `"submit"`, `"increment"`)
    /// * `payload` — Optional JS value passed to the handler. `null`/`undefined` are treated as no payload.
    ///
    /// # Errors
    ///
    /// Returns an error if the payload cannot be deserialized. Does **not** error
    /// if no handler is registered (the action is silently dropped).
    #[wasm_bindgen(js_name = dispatchAction)]
    pub fn dispatch_action(&mut self, name: &str, payload: JsValue) -> Result<(), JsValue> {
        let payload: Option<serde_json::Value> = if payload.is_undefined() || payload.is_null() {
            None
        } else {
            Some(from_value(payload).map_err(|e| {
                structured_error("actionError", &format!("Invalid action payload: {}", e))
            })?)
        };

        // 1. Try exact handler match first (e.g., "spacetime.sendMessage" or "increment")
        if let Some(handler) = self.action_handlers.get(name) {
            let action = Action::new(name).with_payload(payload.unwrap_or(serde_json::Value::Null));
            let serializer = serde_wasm_bindgen::Serializer::json_compatible();
            if let Ok(action_js) = serde::Serialize::serialize(&action, &serializer) {
                let _ = handler.call1(&JsValue::NULL, &action_js);
            }
            return Ok(());
        }

        // 2. Check if this is a data source action (e.g., "spacetime.sendMessage")
        //    If the prefix matches a registered data source and we have a handler, route it.
        if let Some(dot_pos) = name.find('.') {
            let provider = &name[..dot_pos];
            if self.data_sources.contains_key(provider) {
                if let Some(ref handler) = self.data_source_action_handler {
                    let method = &name[dot_pos + 1..];
                    let ds_action = serde_json::json!({
                        "provider": provider,
                        "method": method,
                        "payload": payload.unwrap_or(serde_json::Value::Null),
                    });
                    let serializer = serde_wasm_bindgen::Serializer::json_compatible();
                    if let Ok(action_js) = serde::Serialize::serialize(&ds_action, &serializer) {
                        let _ = handler.call1(&JsValue::NULL, &action_js);
                    }
                }
            }
        }

        Ok(())
    }

    /// Register a JavaScript function as the handler for a named action.
    ///
    /// When [`dispatch_action`] is called with a matching name, the handler
    /// receives a serialized [`Action`] object with `{ name, payload }`.
    ///
    /// Registering a handler for the same name replaces the previous one.
    #[wasm_bindgen(js_name = onAction)]
    pub fn on_action(&mut self, action_name: &str, handler: js_sys::Function) {
        self.action_handlers
            .insert(action_name.to_string(), handler);
    }

    /// Register a handler for data source actions.
    ///
    /// When [`dispatch_action`] is called with a name like `"spacetime.sendMessage"`
    /// and no explicit action handler is registered for that name, the engine checks
    /// if the prefix (`"spacetime"`) is a registered data source. If so, it calls
    /// this handler with `{ provider, method, payload }`.
    ///
    /// This enables `@actions.spacetime.sendMessage` in DSL to automatically route
    /// to the appropriate data source plugin without manual handler registration.
    #[wasm_bindgen(js_name = onDataSourceAction)]
    pub fn on_data_source_action(&mut self, handler: js_sys::Function) {
        self.data_source_action_handler = Some(handler);
    }

    /// Remove all nodes from the instance tree without emitting Remove patches.
    ///
    /// Use this when tearing down the UI entirely (e.g. navigating away or
    /// switching samples). The renderer is responsible for clearing its own
    /// DOM/canvas state separately.
    #[wasm_bindgen(js_name = clearTree)]
    pub fn clear_tree(&mut self) {
        self.tree.clear();
    }

    /// Parse a component and return a human-readable debug string.
    ///
    /// Intended for development tooling only — the output format is not stable.
    #[wasm_bindgen(js_name = debugParseComponent)]
    pub fn debug_parse_component(&self, source: &str) -> Result<String, JsValue> {
        let component = hypen_parser::parse_component(source)
            .map_err(|e| structured_error("parseError", &format_parse_errors(&e)))?;

        let debug_info = format!(
            "Component: {} with {} applicators\nApplicators: {:?}",
            component.name,
            component.applicators.len(),
            component
                .applicators
                .iter()
                .map(|a| &a.name)
                .collect::<Vec<_>>()
        );

        Ok(debug_info)
    }

    /// Initialize (or replace) the active module with the given configuration.
    ///
    /// A module provides stateful context for `${state.xxx}` bindings in the DSL.
    /// Only one module is active at a time — calling this again replaces it.
    ///
    /// # Arguments
    /// * `name` — Module identifier (e.g. `"Counter"`, `"ProfilePage"`)
    /// * `actions` — List of action names this module handles
    /// * `state_keys` — List of top-level state keys (used for validation)
    /// * `initial_state` — The starting state as a JS object
    ///
    /// # Errors
    ///
    /// Returns an error if `initial_state` cannot be deserialized as JSON.
    #[wasm_bindgen(js_name = setModule)]
    pub fn set_module(
        &mut self,
        name: &str,
        actions: Vec<String>,
        state_keys: Vec<String>,
        initial_state: JsValue,
    ) -> Result<(), JsValue> {
        let state: serde_json::Value = from_value(initial_state).map_err(|e| {
            structured_error("stateError", &format!("Invalid initial state: {}", e))
        })?;

        let module = Module::new(name)
            .with_actions(actions)
            .with_state_keys(state_keys);

        let instance = ModuleInstance::new(module, state);
        self.module = Some(instance);

        Ok(())
    }

    /// Get the current revision number.
    ///
    /// Starts at 0 and increments by 1 for each render cycle that produces
    /// patches. Useful for cache invalidation and detecting stale async results.
    #[wasm_bindgen(js_name = getRevision)]
    pub fn get_revision(&self) -> u64 {
        self.revision
    }

    /// Return a JSON snapshot of the active module's current state.
    ///
    /// Returns `null` (as a `JsValue`) if no module is set.
    /// Useful for debugging and DevTools integration.
    #[wasm_bindgen(js_name = currentState)]
    pub fn current_state(&self) -> JsValue {
        let state = self
            .module
            .as_ref()
            .map(|m| m.get_state())
            .unwrap_or(&NULL_STATE);
        let serializer = serde_wasm_bindgen::Serializer::json_compatible();
        serde::Serialize::serialize(state, &serializer).unwrap_or(JsValue::NULL)
    }

    /// Return the total number of nodes currently in the instance tree.
    ///
    /// Useful for debugging, performance monitoring, and DevTools.
    #[wasm_bindgen(js_name = treeSize)]
    pub fn tree_size(&self) -> usize {
        self.tree.len()
    }

    /// Validate that the engine is in a consistent state.
    ///
    /// Checks that:
    /// - All child references point to existing nodes
    /// - All parent back-references are correct
    /// - The root node (if any) exists in the tree
    ///
    /// Returns `null` if valid, or a string describing the first inconsistency found.
    /// Intended for testing and debugging only — not for production hot paths.
    #[wasm_bindgen(js_name = validate)]
    pub fn validate(&self) -> JsValue {
        // Check root exists if set
        if let Some(root_id) = self.tree.root() {
            if self.tree.get(root_id).is_none() {
                return JsValue::from_str("Root node ID references a non-existent node");
            }
        }

        // Check all child/parent references
        for (node_id, node) in self.tree.iter() {
            for child_id in &node.children {
                match self.tree.get(*child_id) {
                    None => {
                        return JsValue::from_str(&format!(
                            "Node {} references non-existent child {}",
                            crate::reconcile::node_id_str(node_id),
                            crate::reconcile::node_id_str(*child_id),
                        ));
                    }
                    Some(child) => {
                        if child.parent != Some(node_id) {
                            return JsValue::from_str(&format!(
                                "Child {} parent back-reference does not point to {}",
                                crate::reconcile::node_id_str(*child_id),
                                crate::reconcile::node_id_str(node_id),
                            ));
                        }
                    }
                }
            }
        }

        JsValue::NULL
    }

    /// Fully reset the engine to its initial empty state.
    ///
    /// Clears the tree, module, dependencies, scheduler, action handlers,
    /// component registry, and resets the revision to 0. The render callback
    /// and component resolver are preserved.
    #[wasm_bindgen(js_name = reset)]
    pub fn reset(&mut self) {
        self.tree.clear();
        self.module = None;
        self.dependencies.clear();
        self.scheduler = Scheduler::new();
        self.action_handlers.clear();
        self.component_registry = ComponentRegistry::new();
        self.root_ir_node = None;
        self.import_visited.clear();
        self.node_id_index.clear();
        self.revision = 0;
    }
}

/// Serialize a patches array to a pretty-printed JSON string.
///
/// Intended for debugging and logging — not for production use.
/// Accepts a JS array of patch objects and returns formatted JSON.
#[wasm_bindgen(js_name = patchesToJson)]
pub fn patches_to_json(patches: JsValue) -> Result<String, JsValue> {
    let patches: Vec<Patch> = from_value(patches)
        .map_err(|e| structured_error("stateError", &format!("Invalid patches: {}", e)))?;

    serde_json::to_string_pretty(&patches)
        .map_err(|e| structured_error("renderError", &format!("Serialization error: {}", e)))
}

/// Parse Hypen DSL source and return the AST as a pretty-printed JSON string.
///
/// Useful for tooling, syntax highlighting, and debugging the parser output.
#[wasm_bindgen(js_name = parseToJson)]
pub fn parse_to_json(source: &str) -> Result<String, JsValue> {
    let component = hypen_parser::parse_component(source)
        .map_err(|e| structured_error("parseError", &format_parse_errors(&e)))?;

    serde_json::to_string_pretty(&component)
        .map_err(|e| structured_error("renderError", &format!("Serialization error: {}", e)))
}

#[wasm_bindgen(start)]
pub fn main() {}