cviz 2.0.1

A CLI tool to visualize WebAssembly component composition structure.
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
pub mod ascii;
pub mod json;
pub mod mermaid;

use crate::model::{
    short_interface_name, CompositionGraph, ExportInfo, FuncSignature, InterfaceConnection,
    InterfaceType, InternedId, TypeArena, SYNTHETIC_COMPONENT,
};

/// Format a function signature as `(param-type, ...) -> result-type`.
///
/// Uses [`TypeArena::display_val`] so that large complex types (variants with
/// many cases, records with many fields, etc.) are summarised rather than
/// expanded in full.  Fingerprinting is unaffected — it always uses the
/// lossless [`TypeArena::canonical_val`].
pub(crate) fn format_func_sig(sig: &FuncSignature, arena: &TypeArena) -> String {
    let params: Vec<String> = sig.params.iter().map(|id| arena.display_val(*id)).collect();
    let results: Vec<String> = sig
        .results
        .iter()
        .map(|id| arena.display_val(*id))
        .collect();
    let result_str = match results.as_slice() {
        [] => "()".to_string(),
        [single] => single.clone(),
        _ => format!("({})", results.join(", ")),
    };
    format!("({}) -> {}", params.join(", "), result_str)
}

/// Return type lines for an [`InterfaceConnection`], or an empty vec when
/// `show_types` is false or the connection carries no type information.
pub(crate) fn connection_type_lines(
    conn: &InterfaceConnection,
    arena: &TypeArena,
    show_types: bool,
) -> Vec<String> {
    if !show_types {
        return vec![];
    }
    conn.interface_type
        .as_ref()
        .map(|t| format_interface_type_lines(t, arena))
        .unwrap_or_default()
}

/// Return type lines for an [`ExportInfo`], or an empty vec when `show_types`
/// is false or the export carries no interface type.
pub(crate) fn export_type_lines(
    export_info: &ExportInfo,
    arena: &TypeArena,
    show_types: bool,
) -> Vec<String> {
    if !show_types {
        return vec![];
    }
    match export_info.ty {
        Some(InternedId::Interface(id)) => {
            format_interface_type_lines(arena.lookup_interface(id), arena)
        }
        _ => vec![],
    }
}

/// Return one display line per exported function in the interface.
///
/// - `Instance` interfaces produce `"fn-name: (params) -> result"` per function.
/// - `Func` interfaces produce a single `"(params) -> result"` line.
pub(crate) fn format_interface_type_lines(iface: &InterfaceType, arena: &TypeArena) -> Vec<String> {
    match iface {
        InterfaceType::Func(sig) => vec![format_func_sig(sig, arena)],
        InterfaceType::Instance(inst) => inst
            .functions
            .iter()
            .map(|(name, sig)| format!("`{}`: {}", name, format_func_sig(sig, arena)))
            .collect(),
    }
}

const SYMBOL_POOL: &[char] = &[
    '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
    '',
];

/// Compute the symbol string for a given assignment index using base-N encoding
/// over [`SYMBOL_POOL`].
///
/// - Indices `0..N` produce single-character identifiers (`"✦"`, `"✧"`, …).
/// - Indices `N..N+N²` produce two-character identifiers (`"✦✦"`, `"✦✧"`, …).
/// - Indices beyond that produce three-character identifiers, and so on.
///
/// This guarantees an unbounded, collision-free sequence of compact identifiers
/// without ever reusing a symbol string.
fn symbol_at(index: usize) -> String {
    let n = SYMBOL_POOL.len();
    // Find which "length tier" this index falls into and the offset within it.
    // Tier 1 covers [0, n), tier 2 covers [n, n + n²), tier 3 covers [n + n², n + n² + n³), …
    let mut tier_size = n;
    let mut offset = index;
    let mut len = 1;
    while offset >= tier_size {
        offset -= tier_size;
        tier_size *= n;
        len += 1;
    }
    // Decode `offset` as a base-N number of `len` digits (most-significant first).
    let mut digits = vec![0usize; len];
    let mut remainder = offset;
    for d in digits.iter_mut().rev() {
        *d = remainder % n;
        remainder /= n;
    }
    digits.iter().map(|&d| SYMBOL_POOL[d]).collect()
}

/// Assigns a unique identifier to each distinct interface type encountered
/// during rendering and collects a display key.
///
/// Types are distinguished by fingerprint, so structurally identical interfaces
/// always receive the same symbol within one diagram.  Identifiers are drawn
/// from [`SYMBOL_POOL`] via [`symbol_at`]: single glyphs first, then
/// two-glyph combinations, then three-glyph, and so on — so the pool never
/// truly exhausts.
pub(crate) struct SymbolMap {
    /// `(fingerprint, symbol string, formatted type lines)`
    entries: Vec<(String, String, Vec<String>)>,
}

impl SymbolMap {
    pub(crate) fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Return (or assign) the symbol for a connection's interface type.
    /// Returns `None` if the connection carries no type info.
    pub(crate) fn symbol_for_conn(
        &mut self,
        conn: &InterfaceConnection,
        arena: &TypeArena,
    ) -> Option<&str> {
        let fp = conn.fingerprint.as_ref()?;
        let iface = conn.interface_type.as_ref()?;
        Some(self.get_or_insert(fp, iface, arena))
    }

    /// Return (or assign) the symbol for an export's interface type.
    /// Returns `None` if the export carries no interface type.
    pub(crate) fn symbol_for_export(
        &mut self,
        export_info: &ExportInfo,
        arena: &TypeArena,
    ) -> Option<&str> {
        let fp = export_info.fingerprint.as_ref()?;
        let id = match export_info.ty {
            Some(InternedId::Interface(id)) => id,
            _ => return None,
        };
        Some(self.get_or_insert(fp, arena.lookup_interface(id), arena))
    }

    fn get_or_insert(&mut self, fp: &str, iface: &InterfaceType, arena: &TypeArena) -> &str {
        if let Some(pos) = self.entries.iter().position(|(f, _, _)| f == fp) {
            return &self.entries[pos].1;
        }
        let symbol = symbol_at(self.entries.len());
        let lines = format_interface_type_lines(iface, arena);
        self.entries.push((fp.to_string(), symbol, lines));
        &self.entries.last().unwrap().1
    }

    /// Return (or assign) the symbol for a pre-computed fingerprint + type lines,
    /// or an empty string when `show_types` is false or no fingerprint is present.
    ///
    /// This is the primary entry point for AllInterfaces/Full renderers that
    /// receive type data from the [`DiagramEdge`]/[`DiagramExport`] IR.
    pub(crate) fn assign(
        &mut self,
        show_types: bool,
        fingerprint: Option<&str>,
        type_lines: Vec<String>,
    ) -> String {
        if !show_types {
            return String::new();
        }
        let Some(fp) = fingerprint else {
            return String::new();
        };
        if let Some(pos) = self.entries.iter().position(|(f, _, _)| f == fp) {
            return self.entries[pos].1.clone();
        }
        let symbol = symbol_at(self.entries.len());
        self.entries.push((fp.to_string(), symbol, type_lines));
        self.entries.last().unwrap().1.clone()
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Return key lines: `"✦ fn-name: sig"` per unique symbol, with
    /// continuation lines for multi-function interfaces indented.
    pub(crate) fn key_lines(&self) -> Vec<String> {
        let mut out = Vec::new();
        for (_, symbol, type_lines) in &self.entries {
            for (i, line) in type_lines.iter().enumerate() {
                if i == 0 {
                    out.push(format!("{} {}", symbol, line));
                } else {
                    out.push(format!("  {}", line));
                }
            }
        }
        out
    }
}

// ---------------------------------------------------------------------------
// Intermediate representation — shared graph traversal
// ---------------------------------------------------------------------------

/// A node to be rendered in the diagram.
pub(crate) struct DiagramNode {
    pub name: String,
    pub display: String,
    pub is_synthetic: bool,
    pub component_index: u32,
}

/// A directed edge between two nodes.
pub(crate) struct DiagramEdge {
    /// Raw name of the source (interface_name for host imports, node.name otherwise).
    /// Renderers that need sanitized IDs (Mermaid) apply their own transform.
    pub from_name: String,
    pub from_display: String,
    pub to_name: String,
    pub to_display: String,
    /// Ready-to-use edge label (short interface name or full name, depending on mode).
    pub label: String,
    /// Pre-formatted type lines for this connection (empty when show_types=false).
    pub type_lines: Vec<String>,
    /// Fingerprint for deduplication in a [`SymbolMap`] (None when no type info).
    pub fingerprint: Option<String>,
    /// true if host import
    pub is_dashed: bool,
}

/// An exported interface.
pub(crate) struct DiagramExport {
    pub from_name: String,
    pub from_display: String,
    pub full_name: String,
    pub short_name: String,
    /// Pre-formatted type lines for this export (empty when show_types=false).
    pub type_lines: Vec<String>,
    /// Fingerprint for deduplication in a [`SymbolMap`] (None when no type info).
    pub fingerprint: Option<String>,
}

/// Pre-computed graph data for rendering, independent of output format.
pub(crate) struct ConnectionsView {
    /// Raw host interface names (AllInterfaces only; empty for Full).
    pub host_names: Vec<String>,
    pub nodes: Vec<DiagramNode>,
    pub edges: Vec<DiagramEdge>,
    pub exports: Vec<DiagramExport>,
}

/// Build a [`ConnectionsView`] for `AllInterfaces` detail level.
///
/// Includes real (non-synthetic) component nodes, host-import edges (dashed),
/// inter-component edges (solid), and exported interfaces.  Edge labels use
/// the short interface name.
pub(crate) fn build_all_interfaces_view(
    graph: &CompositionGraph,
    show_types: bool,
) -> ConnectionsView {
    let component_nodes = graph.real_nodes();

    let nodes = component_nodes
        .iter()
        .map(|n| DiagramNode {
            name: n.name.clone(),
            display: n.display_label().to_string(),
            is_synthetic: false,
            component_index: n.component_index,
        })
        .collect();

    let mut edges = Vec::new();
    for node in &component_nodes {
        for import in &node.imports {
            if import.is_host_import {
                edges.push(DiagramEdge {
                    from_name: import.interface_name.clone(),
                    from_display: short_interface_name(&import.interface_name),
                    to_name: node.name.clone(),
                    to_display: node.display_label().to_string(),
                    label: import.short_label(),
                    type_lines: connection_type_lines(import, &graph.arena, show_types),
                    fingerprint: import.fingerprint.clone(),
                    is_dashed: true,
                });
            } else if let Some(src) = import.source_instance.and_then(|id| graph.get_node(id)) {
                if src.component_index != SYNTHETIC_COMPONENT {
                    edges.push(DiagramEdge {
                        from_name: src.name.clone(),
                        from_display: src.display_label().to_string(),
                        to_name: node.name.clone(),
                        to_display: node.display_label().to_string(),
                        label: import.short_label(),
                        type_lines: connection_type_lines(import, &graph.arena, show_types),
                        fingerprint: import.fingerprint.clone(),
                        is_dashed: false,
                    });
                }
            }
        }
    }

    let mut exports = Vec::new();
    for (export_name, export_info) in &graph.component_exports {
        if let Some(node) = graph.get_node(export_info.source_instance) {
            if node.component_index != SYNTHETIC_COMPONENT {
                exports.push(DiagramExport {
                    from_name: node.name.clone(),
                    from_display: node.display_label().to_string(),
                    full_name: export_name.clone(),
                    short_name: short_interface_name(export_name),
                    type_lines: export_type_lines(export_info, &graph.arena, show_types),
                    fingerprint: export_info.fingerprint.clone(),
                });
            }
        }
    }

    ConnectionsView {
        host_names: graph.host_interfaces(),
        nodes,
        edges,
        exports,
    }
}

/// Build a [`ConnectionsView`] for `Full` detail level.
///
/// Includes all nodes (including synthetic), all non-host-import edges with
/// full interface names, and all exported interfaces.
pub(crate) fn build_full_view(graph: &CompositionGraph, show_types: bool) -> ConnectionsView {
    let nodes = graph
        .nodes
        .values()
        .map(|n| DiagramNode {
            name: n.name.clone(),
            display: n.display_label().to_string(),
            is_synthetic: n.component_index == SYNTHETIC_COMPONENT,
            component_index: n.component_index,
        })
        .collect();

    let mut edges = Vec::new();
    for node in graph.nodes.values() {
        for import in &node.imports {
            if !import.is_host_import {
                if let Some(src) = import.source_instance.and_then(|id| graph.get_node(id)) {
                    edges.push(DiagramEdge {
                        from_name: src.name.clone(),
                        from_display: src.display_label().to_string(),
                        to_name: node.name.clone(),
                        to_display: node.display_label().to_string(),
                        label: import.interface_name.clone(),
                        type_lines: connection_type_lines(import, &graph.arena, show_types),
                        fingerprint: import.fingerprint.clone(),
                        is_dashed: false,
                    });
                }
            }
        }
    }

    let mut exports = Vec::new();
    for (export_name, export_info) in &graph.component_exports {
        if let Some(node) = graph.get_node(export_info.source_instance) {
            exports.push(DiagramExport {
                from_name: node.name.clone(),
                from_display: node.display_label().to_string(),
                full_name: export_name.clone(),
                short_name: short_interface_name(export_name),
                type_lines: export_type_lines(export_info, &graph.arena, show_types),
                fingerprint: export_info.fingerprint.clone(),
            });
        }
    }

    ConnectionsView {
        host_names: vec![],
        nodes,
        edges,
        exports,
    }
}

/// Output format for visualization
#[derive(Debug, Clone, Copy, Default)]
pub enum OutputFormat {
    #[default]
    Ascii,
    Mermaid,
    Json,
    JsonPretty,
}

impl std::str::FromStr for OutputFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "ascii" => Ok(OutputFormat::Ascii),
            "mermaid" => Ok(OutputFormat::Mermaid),
            "json" => Ok(OutputFormat::Json),
            "json-pretty" => Ok(OutputFormat::JsonPretty),
            _ => Err(format!(
                "Invalid output format: {}. Valid values: ascii, mermaid, json, json-pretty",
                s
            )),
        }
    }
}

/// Diagram direction (applies to Mermaid only)
#[derive(Debug, Clone, Copy, Default)]
pub enum Direction {
    #[default]
    LeftToRight,
    TopDown,
}

impl Direction {
    pub fn to_mermaid(self) -> &'static str {
        match self {
            Direction::LeftToRight => "LR",
            Direction::TopDown => "TD",
        }
    }
}

impl std::str::FromStr for Direction {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "lr" | "left-to-right" => Ok(Direction::LeftToRight),
            "td" | "top-down" => Ok(Direction::TopDown),
            _ => Err(format!("Invalid direction: {}", s)),
        }
    }
}

/// Detail level for the diagram
#[derive(Debug, Clone, Copy, Default)]
pub enum DetailLevel {
    /// Only show the HTTP handler chain
    #[default]
    HandlerChain,
    /// Show all interfaces
    AllInterfaces,
    /// Show everything including internal details
    Full,
}

impl std::str::FromStr for DetailLevel {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "handler-chain" | "handler" => Ok(DetailLevel::HandlerChain),
            "all-interfaces" | "all" => Ok(DetailLevel::AllInterfaces),
            "full" => Ok(DetailLevel::Full),
            _ => Err(format!("Invalid detail level: {}", s)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_output_format_parse() {
        assert!(matches!(
            "ascii".parse::<OutputFormat>().unwrap(),
            OutputFormat::Ascii
        ));
        assert!(matches!(
            "mermaid".parse::<OutputFormat>().unwrap(),
            OutputFormat::Mermaid
        ));
        assert!(matches!(
            "json".parse::<OutputFormat>().unwrap(),
            OutputFormat::Json
        ));
        assert!("invalid".parse::<OutputFormat>().is_err());
    }

    #[test]
    fn test_direction_parse() {
        assert!(matches!(
            "lr".parse::<Direction>().unwrap(),
            Direction::LeftToRight
        ));
        assert!(matches!(
            "td".parse::<Direction>().unwrap(),
            Direction::TopDown
        ));
    }

    #[test]
    fn test_detail_level_parse() {
        assert!(matches!(
            "handler-chain".parse::<DetailLevel>().unwrap(),
            DetailLevel::HandlerChain
        ));
        assert!(matches!(
            "all-interfaces".parse::<DetailLevel>().unwrap(),
            DetailLevel::AllInterfaces
        ));
        assert!(matches!(
            "full".parse::<DetailLevel>().unwrap(),
            DetailLevel::Full
        ));
    }

    #[test]
    fn test_symbol_at_tier_boundaries() {
        let n = SYMBOL_POOL.len();

        // Last single-char symbol
        assert_eq!(symbol_at(n - 1).chars().count(), 1);
        // First two-char symbol
        assert_eq!(symbol_at(n).chars().count(), 2);
        // Last two-char symbol
        assert_eq!(symbol_at(n + n * n - 1).chars().count(), 2);
        // First three-char symbol
        assert_eq!(symbol_at(n + n * n).chars().count(), 3);
    }

    #[test]
    fn test_symbol_at_no_duplicates() {
        let n = SYMBOL_POOL.len();
        // Verify the first n + n² symbols are all distinct
        let symbols: Vec<String> = (0..n + n * n).map(symbol_at).collect();
        let unique: std::collections::HashSet<&String> = symbols.iter().collect();
        assert_eq!(symbols.len(), unique.len(), "symbol_at produced duplicates");
    }

    // -----------------------------------------------------------------------
    // format_func_sig edge cases
    // -----------------------------------------------------------------------

    use crate::model::{FuncSignature, InterfaceType, ValueType};

    fn make_arena() -> crate::model::TypeArena {
        crate::model::TypeArena::default()
    }

    #[test]
    fn test_format_func_sig_no_params() {
        let mut arena = make_arena();
        let bool_id = arena.intern_val(ValueType::Bool);
        let sig = FuncSignature {
            is_async: false,
            param_names: vec![],
            params: vec![],
            results: vec![bool_id],
        };
        assert_eq!(format_func_sig(&sig, &arena), "() -> bool");
    }

    #[test]
    fn test_format_func_sig_no_results() {
        let mut arena = make_arena();
        let u32_id = arena.intern_val(ValueType::U32);
        let sig = FuncSignature {
            is_async: false,
            param_names: vec![],
            params: vec![u32_id],
            results: vec![],
        };
        assert_eq!(format_func_sig(&sig, &arena), "(u32) -> ()");
    }

    #[test]
    fn test_format_func_sig_multiple_results() {
        let mut arena = make_arena();
        let u32_id = arena.intern_val(ValueType::U32);
        let str_id = arena.intern_val(ValueType::String);
        let bool_id = arena.intern_val(ValueType::Bool);
        let sig = FuncSignature {
            is_async: false,
            param_names: vec![],
            params: vec![u32_id, str_id],
            results: vec![bool_id, str_id],
        };
        assert_eq!(
            format_func_sig(&sig, &arena),
            "(u32, string) -> (bool, string)"
        );
    }

    #[test]
    fn test_format_interface_type_lines_func_variant() {
        let mut arena = make_arena();
        let u32_id = arena.intern_val(ValueType::U32);
        let bool_id = arena.intern_val(ValueType::Bool);
        let sig = FuncSignature {
            is_async: false,
            param_names: vec![],
            params: vec![u32_id],
            results: vec![bool_id],
        };
        // Func variant: single bare sig line, no backtick-name prefix
        let iface = InterfaceType::Func(sig);
        let lines = format_interface_type_lines(&iface, &arena);
        assert_eq!(lines, vec!["(u32) -> bool"]);
    }

    #[test]
    fn test_connection_type_lines_missing_type_info() {
        use crate::model::InterfaceConnection;
        let arena = make_arena();
        let conn = InterfaceConnection {
            interface_name: "wasi:http/handler@0.3.0".to_string(),
            source_instance: None,
            is_host_import: true,
            interface_type: None, // no type info
            fingerprint: None,
        };
        // show_types=true but no type info → should return empty, not panic
        let lines = connection_type_lines(&conn, &arena, true);
        assert!(
            lines.is_empty(),
            "missing type info should produce no type lines"
        );
    }

    // -----------------------------------------------------------------------
    // ConnectionsView IR tests
    // -----------------------------------------------------------------------

    use crate::test_utils::*;

    #[test]
    fn test_view_all_interfaces_node_count() {
        let graph = simple_chain_graph();
        let view = build_all_interfaces_view(&graph, false);
        // $srv and $middleware are real; no synthetic nodes in this graph
        assert_eq!(view.nodes.len(), 2);
        assert!(view.nodes.iter().any(|n| n.display.contains("srv")));
        assert!(view.nodes.iter().any(|n| n.display.contains("middleware")));
    }

    #[test]
    fn test_view_all_interfaces_host_names() {
        let graph = simple_chain_graph();
        let view = build_all_interfaces_view(&graph, false);
        // Two distinct host interfaces: handler (from srv) and log (from middleware)
        assert_eq!(view.host_names.len(), 2);
        assert!(view.host_names.iter().any(|n| n.contains("handler")));
        assert!(view.host_names.iter().any(|n| n.contains("log")));
    }

    #[test]
    fn test_view_all_interfaces_edge_dashed() {
        let graph = simple_chain_graph();
        let view = build_all_interfaces_view(&graph, false);
        // 2 host-import edges (dashed) + 1 component edge (solid)
        let dashed: Vec<_> = view.edges.iter().filter(|e| e.is_dashed).collect();
        let solid: Vec<_> = view.edges.iter().filter(|e| !e.is_dashed).collect();
        assert_eq!(
            dashed.len(),
            2,
            "two host imports should produce dashed edges"
        );
        assert_eq!(
            solid.len(),
            1,
            "one inter-component import should produce a solid edge"
        );
    }

    #[test]
    fn test_view_all_interfaces_edge_endpoints() {
        let graph = simple_chain_graph();
        let view = build_all_interfaces_view(&graph, false);
        let solid = view.edges.iter().find(|e| !e.is_dashed).unwrap();
        assert!(
            solid.from_display.contains("srv"),
            "solid edge should come from srv"
        );
        assert!(
            solid.to_display.contains("middleware"),
            "solid edge should go to middleware"
        );
        assert_eq!(
            solid.label, "handler",
            "edge label should be short interface name"
        );
    }

    #[test]
    fn test_view_all_interfaces_export() {
        let graph = simple_chain_graph();
        let view = build_all_interfaces_view(&graph, false);
        assert_eq!(view.exports.len(), 1);
        let exp = &view.exports[0];
        assert!(exp.from_display.contains("middleware"));
        assert_eq!(exp.short_name, "handler");
        assert!(exp.full_name.contains("wasi:http/handler"));
    }

    #[test]
    fn test_view_all_interfaces_non_http_chain() {
        // Verify the IR works for a non-http chain (keyvalue/store)
        let graph = two_chain_graph();
        let view = build_all_interfaces_view(&graph, false);
        let kv_export = view
            .exports
            .iter()
            .find(|e| e.full_name.contains("keyvalue"));
        assert!(kv_export.is_some(), "should have a keyvalue export");
        assert_eq!(kv_export.unwrap().short_name, "store");

        let kv_solid = view
            .edges
            .iter()
            .find(|e| !e.is_dashed && e.label == "store");
        assert!(kv_solid.is_some(), "should have solid keyvalue/store edge");
        let kv_solid = kv_solid.unwrap();
        assert!(kv_solid.from_display.contains("db"));
        assert!(kv_solid.to_display.contains("cache"));
    }

    #[test]
    fn test_view_all_interfaces_excludes_synthetic_source() {
        // A synthetic node as the *source* of an import should not produce an
        // edge in AllInterfaces mode (only real component sources are shown).
        use crate::model::{ComponentNode, InterfaceConnection, SYNTHETIC_COMPONENT};

        let mut graph = CompositionGraph::new();

        // A real component that imports from a synthetic source
        let mut real = ComponentNode::new("$real".to_string(), 0, 0);
        real.add_import(InterfaceConnection {
            interface_name: "wasi:http/handler@0.3.0".to_string(),
            source_instance: Some(99), // will be a synthetic node
            is_host_import: false,
            interface_type: None,
            fingerprint: None,
        });
        graph.add_node(1, real);

        // The synthetic node at idx 99
        let synthetic = ComponentNode::new(
            "$synthetic".to_string(),
            SYNTHETIC_COMPONENT,
            SYNTHETIC_COMPONENT,
        );
        graph.add_node(99, synthetic);

        let view = build_all_interfaces_view(&graph, false);

        // The edge from the synthetic source should be dropped
        assert!(
            view.edges.is_empty(),
            "edges from synthetic source nodes should be excluded, got: {:?}",
            view.edges
                .iter()
                .map(|e| (&e.from_display, &e.to_display))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_view_full_includes_all_nodes() {
        let graph = simple_chain_graph();
        let view = build_full_view(&graph, false);
        // Full includes all nodes; host_names is empty
        assert!(view.nodes.len() >= 2);
        assert!(
            view.host_names.is_empty(),
            "Full mode has no host node list"
        );
    }

    #[test]
    fn test_view_full_no_dashed_edges() {
        let graph = simple_chain_graph();
        let view = build_full_view(&graph, false);
        assert!(
            view.edges.iter().all(|e| !e.is_dashed),
            "Full mode skips host imports so no edge should be dashed"
        );
    }

    #[test]
    fn test_view_full_edge_uses_full_name() {
        let graph = simple_chain_graph();
        let view = build_full_view(&graph, false);
        let edge = view
            .edges
            .iter()
            .find(|e| e.label.contains("handler"))
            .unwrap();
        assert!(
            edge.label.contains("wasi:http/handler@0.3.0"),
            "Full mode should use full interface name as label, got: {}",
            edge.label
        );
    }

    #[test]
    fn test_view_all_interfaces_two_chains() {
        let graph = two_chain_graph();
        let view = build_all_interfaces_view(&graph, false);
        // 4 real nodes: srv-http, mw-http, db, cache
        assert_eq!(view.nodes.len(), 4);
        // 2 solid edges (one per chain) + 2 host-import edges (one per inner node)
        let solid: Vec<_> = view.edges.iter().filter(|e| !e.is_dashed).collect();
        assert_eq!(solid.len(), 2, "two inter-component edges expected");
        // 2 exports
        assert_eq!(view.exports.len(), 2);
        let names: Vec<&str> = view.exports.iter().map(|e| e.short_name.as_str()).collect();
        assert!(names.contains(&"handler"), "should have handler export");
        assert!(names.contains(&"store"), "should have store export");
    }

    #[test]
    fn test_view_full_synthetic_node_included() {
        use crate::model::{ComponentNode, SYNTHETIC_COMPONENT};
        let mut graph = CompositionGraph::new();

        let real = ComponentNode::new("$real".to_string(), 0, 0);
        graph.add_node(1, real);
        let synthetic = ComponentNode::new(
            "$synth".to_string(),
            SYNTHETIC_COMPONENT,
            SYNTHETIC_COMPONENT,
        );
        graph.add_node(99, synthetic);

        let view = build_full_view(&graph, false);
        assert_eq!(
            view.nodes.len(),
            2,
            "Full mode should include synthetic nodes"
        );
        assert!(
            view.nodes.iter().any(|n| n.is_synthetic),
            "synthetic flag should be set"
        );
        assert!(view.nodes.iter().any(|n| n.display.contains("synth")));
    }

    #[test]
    fn test_view_host_interfaces_deduplicated() {
        use crate::model::{ComponentNode, InterfaceConnection};
        let mut graph = CompositionGraph::new();

        // Two real nodes both importing the same host interface
        let mut a = ComponentNode::new("$a".to_string(), 0, 0);
        a.add_import(InterfaceConnection {
            interface_name: "wasi:logging/log@0.1.0".to_string(),
            source_instance: None,
            is_host_import: true,
            interface_type: None,
            fingerprint: None,
        });
        graph.add_node(1, a);

        let mut b = ComponentNode::new("$b".to_string(), 1, 1);
        b.add_import(InterfaceConnection {
            interface_name: "wasi:logging/log@0.1.0".to_string(),
            source_instance: None,
            is_host_import: true,
            interface_type: None,
            fingerprint: None,
        });
        graph.add_node(2, b);

        let view = build_all_interfaces_view(&graph, false);
        assert_eq!(
            view.host_names.len(),
            1,
            "same host interface imported by two nodes should appear once"
        );
        assert_eq!(view.host_names[0], "wasi:logging/log@0.1.0");
    }
}