1use std::path::Path;
13
14use rustc_hash::FxHashMap;
15use serde::Serialize;
16use serde_json::Value;
17
18use fallow_config::{ResolvedConfig, WorkspaceInfo};
19use fallow_output::HealthReport;
20use fallow_types::discover::DiscoveredFile;
21use fallow_types::duplicates::{CloneInstance, DuplicationReport};
22use fallow_types::extract::{FunctionComplexity, ModuleInfo};
23use fallow_types::results::{AnalysisResults, FeatureFlag, SecurityFinding};
24
25use crate::module_graph::RetainedModuleGraph;
26
27const HOTSPOT_CYCLOMATIC_FLOOR: u16 = 10;
29const CLONE_PREVIEW_MAX_BYTES: usize = 2000;
33const CLONE_PREVIEW_MAX_LINES: usize = 32;
37const CLONE_PREVIEW_CONTEXT: usize = 4;
42const MAX_CLONE_GROUPS: usize = 500;
46const MAX_ANALYSIS_FINDINGS: usize = 1000;
48const MAX_SECURITY_BLIND_SPOT_SAMPLES: usize = 100;
50const MAX_HEALTH_FILES: usize = 2000;
52const EDGE_FLAG_TYPE_ONLY: u32 = 1;
54const EDGE_FLAG_DYNAMIC: u32 = 2;
58const NO_RUNTIME_COVERAGE_REASON: &str = "No runtime coverage input was provided";
62
63pub struct VizBuildInput<'a> {
65 pub results: &'a AnalysisResults,
67 pub graph: &'a RetainedModuleGraph,
69 pub modules: Option<&'a [ModuleInfo]>,
71 pub files: &'a [DiscoveredFile],
73 pub duplication: &'a DuplicationReport,
75 pub workspaces: &'a [WorkspaceInfo],
77 pub config: &'a ResolvedConfig,
79 pub feature_flags: &'a [FeatureFlag],
81 pub include_analysis_details: bool,
83}
84
85#[derive(Serialize)]
87pub struct VizData {
88 pub root: String,
90 pub files: Vec<VizFile>,
92 pub edges: Vec<[u32; 3]>,
97 pub summary: VizSummary,
99 pub workspaces: Vec<VizWorkspace>,
101 pub zones: Vec<VizZone>,
103 pub cycles: Vec<Vec<u32>>,
105 pub clones: Vec<VizCloneGroup>,
107 pub violations: Vec<VizViolation>,
109 pub architecture: VizFindingAnalysis,
111 pub dependencies: VizFindingAnalysis,
113 pub health: VizHealthData,
115 pub security: VizSecurityData,
117 pub frameworks: VizFrameworkData,
119 pub styling: VizStylingData,
121 pub feature_flags: VizFindingAnalysis,
123}
124
125#[derive(Serialize, Clone, Copy, PartialEq, Eq)]
127#[serde(rename_all = "camelCase")]
128pub enum VizAvailabilityState {
129 Complete,
131 Disabled,
133 NotApplicable,
135 Unavailable,
137}
138
139#[derive(Serialize)]
146pub struct VizAvailability {
147 pub state: VizAvailabilityState,
149 pub count: usize,
151 pub unit: &'static str,
153 #[serde(skip_serializing_if = "Option::is_none")]
155 pub reason: Option<String>,
156 #[serde(skip_serializing_if = "Option::is_none")]
159 pub truncated: Option<usize>,
160}
161
162impl VizAvailability {
163 const fn complete(count: usize, unit: &'static str, truncated: Option<usize>) -> Self {
164 Self {
165 state: VizAvailabilityState::Complete,
166 count,
167 unit,
168 reason: None,
169 truncated,
170 }
171 }
172
173 fn unavailable(unit: &'static str, reason: impl Into<String>) -> Self {
174 Self {
175 state: VizAvailabilityState::Unavailable,
176 count: 0,
177 unit,
178 reason: Some(reason.into()),
179 truncated: None,
180 }
181 }
182
183 fn disabled(unit: &'static str, reason: impl Into<String>) -> Self {
184 Self {
185 state: VizAvailabilityState::Disabled,
186 count: 0,
187 unit,
188 reason: Some(reason.into()),
189 truncated: None,
190 }
191 }
192}
193
194#[derive(Serialize)]
196pub struct VizFinding {
197 kind: String,
198 title: String,
199 #[serde(skip_serializing_if = "Option::is_none")]
200 file: Option<u32>,
201 #[serde(skip_serializing_if = "Option::is_none")]
202 path: Option<String>,
203 #[serde(skip_serializing_if = "Option::is_none")]
204 line: Option<u32>,
205 #[serde(skip_serializing_if = "Vec::is_empty")]
206 files: Vec<u32>,
207 #[serde(skip_serializing_if = "Vec::is_empty")]
208 paths: Vec<String>,
209 #[serde(skip_serializing_if = "Option::is_none")]
210 description: Option<String>,
211 #[serde(skip_serializing_if = "Option::is_none")]
212 severity: Option<String>,
213 #[serde(skip_serializing_if = "Vec::is_empty")]
214 facts: Vec<VizFindingFact>,
215 actions: Vec<VizFindingAction>,
216}
217
218#[derive(Serialize)]
220pub struct VizFindingFact {
221 label: String,
222 value: String,
223}
224
225#[derive(Serialize)]
227pub struct VizFindingAction {
228 label: String,
229 #[serde(skip_serializing_if = "Option::is_none")]
230 kind: Option<String>,
231 auto_fixable: bool,
232 #[serde(skip_serializing_if = "Option::is_none")]
233 command: Option<String>,
234 #[serde(skip_serializing_if = "Option::is_none")]
235 comment: Option<String>,
236 #[serde(skip_serializing_if = "Option::is_none")]
237 config_key: Option<String>,
238 #[serde(skip_serializing_if = "Option::is_none")]
239 value: Option<Value>,
240 #[serde(skip_serializing_if = "Option::is_none")]
241 description: Option<String>,
242}
243
244#[derive(Serialize)]
246pub struct VizFindingAnalysis {
247 pub availability: VizAvailability,
249 #[serde(skip_serializing_if = "Option::is_none")]
251 pub findings_truncated: Option<usize>,
252 pub findings: Vec<VizFinding>,
254}
255
256#[derive(Serialize)]
258pub struct VizFrameworkData {
259 pub availability: VizAvailability,
261 pub detector_availability: VizAvailability,
264 #[serde(skip_serializing_if = "Option::is_none")]
266 pub findings_truncated: Option<usize>,
267 pub findings: Vec<VizFinding>,
269 pub detected_frameworks: Vec<String>,
271 pub detectors: Vec<VizFrameworkDetector>,
274}
275
276#[derive(Serialize)]
278pub struct VizFrameworkDetector {
279 id: String,
280 framework: String,
281 status: String,
282 #[serde(skip_serializing_if = "Option::is_none")]
283 reason: Option<String>,
284}
285
286#[derive(Serialize)]
288pub struct VizHealthCapabilities {
289 pub complexity: VizAvailability,
291 pub maintainability: VizAvailability,
293 pub crap: VizAvailability,
295 pub coverage: VizAvailability,
297 pub runtime: VizAvailability,
299 pub churn: VizAvailability,
301 pub hotspots: VizAvailability,
303 pub ownership: VizAvailability,
305}
306
307#[derive(Serialize)]
309pub struct VizHealthFile {
310 file: u32,
311 path: String,
312 maintainability_index: f64,
313 crap_max: f64,
314 complexity_density: f64,
315 fan_in: usize,
316 fan_out: usize,
317 #[serde(skip_serializing_if = "Option::is_none")]
318 hotspot_score: Option<f64>,
319 #[serde(skip_serializing_if = "Option::is_none")]
320 commits: Option<u32>,
321 #[serde(skip_serializing_if = "Option::is_none")]
322 ownership: Option<Value>,
323}
324
325#[derive(Serialize)]
327pub struct VizHealthData {
328 pub availability: VizAvailability,
330 pub capabilities: VizHealthCapabilities,
332 #[serde(skip_serializing_if = "Option::is_none")]
334 pub shared_parse: Option<bool>,
335 #[serde(skip_serializing_if = "Option::is_none")]
337 pub score: Option<f64>,
338 #[serde(skip_serializing_if = "Option::is_none")]
340 pub grade: Option<String>,
341 #[serde(skip_serializing_if = "Option::is_none")]
343 pub average_maintainability: Option<f64>,
344 pub files: Vec<VizHealthFile>,
346 #[serde(skip_serializing_if = "Option::is_none")]
348 pub files_truncated: Option<usize>,
349 #[serde(skip_serializing_if = "Option::is_none")]
351 pub findings_truncated: Option<usize>,
352 pub findings: Vec<VizFinding>,
354}
355
356#[derive(Serialize)]
358pub struct VizStylingData {
359 pub availability: VizAvailability,
361 #[serde(skip_serializing_if = "Option::is_none")]
363 pub findings_truncated: Option<usize>,
364 pub findings: Vec<VizFinding>,
366 #[serde(skip_serializing_if = "Option::is_none")]
368 pub score: Option<f64>,
369 #[serde(skip_serializing_if = "Option::is_none")]
371 pub grade: Option<String>,
372 #[serde(skip_serializing_if = "Option::is_none")]
374 pub confidence: Option<String>,
375 #[serde(skip_serializing_if = "Option::is_none")]
377 pub summary: Option<Value>,
378}
379
380#[derive(Serialize)]
382pub struct VizSecurityTraceHop {
383 #[serde(skip_serializing_if = "Option::is_none")]
384 file: Option<u32>,
385 path: String,
386 line: u32,
387 col: u32,
388 role: String,
389}
390
391#[derive(Serialize)]
393pub struct VizSecurityEndpoint {
394 #[serde(skip_serializing_if = "Option::is_none")]
395 file: Option<u32>,
396 path: String,
397 line: u32,
398 col: u32,
399}
400
401#[derive(Serialize)]
403pub struct VizSecurityTaintFlow {
404 source: VizSecurityEndpoint,
405 sink: VizSecurityEndpoint,
406 intra_module: bool,
407 cross_module_hops: u32,
408}
409
410#[derive(Serialize)]
413pub struct VizSecurityCandidate {
414 id: String,
415 kind: String,
416 #[serde(skip_serializing_if = "Option::is_none")]
417 category: Option<String>,
418 #[serde(skip_serializing_if = "Option::is_none")]
419 cwe: Option<u32>,
420 #[serde(skip_serializing_if = "Option::is_none")]
421 file: Option<u32>,
422 path: String,
423 line: u32,
424 col: u32,
425 evidence: String,
426 severity: String,
427 #[serde(skip_serializing_if = "Option::is_none")]
428 taint_confidence: Option<String>,
429 #[serde(skip_serializing_if = "Option::is_none")]
430 source_kind: Option<String>,
431 #[serde(skip_serializing_if = "Option::is_none")]
432 sink: Option<String>,
433 #[serde(skip_serializing_if = "Option::is_none")]
434 url_shape: Option<String>,
435 #[serde(skip_serializing_if = "Option::is_none")]
436 network_destination: Option<String>,
437 #[serde(skip_serializing_if = "Option::is_none")]
438 reachable_from_entry: Option<bool>,
439 #[serde(skip_serializing_if = "Option::is_none")]
440 reachable_from_untrusted_source: Option<bool>,
441 #[serde(skip_serializing_if = "Option::is_none")]
442 blast_radius: Option<u32>,
443 crosses_boundary: bool,
444 client_server_boundary: bool,
445 cross_module_boundary: bool,
446 #[serde(skip_serializing_if = "Option::is_none")]
447 architecture_zone: Option<String>,
448 #[serde(skip_serializing_if = "Option::is_none")]
449 dead_code: Option<Value>,
450 #[serde(skip_serializing_if = "Option::is_none")]
451 runtime: Option<Value>,
452 #[serde(skip_serializing_if = "Option::is_none")]
453 taint_flow: Option<VizSecurityTaintFlow>,
454 #[serde(skip_serializing_if = "Vec::is_empty")]
455 observed_controls: Vec<Value>,
456 #[serde(skip_serializing_if = "Option::is_none")]
457 control_verification_prompt: Option<String>,
458 trace: Vec<VizSecurityTraceHop>,
459 #[serde(skip_serializing_if = "Vec::is_empty")]
460 taint_trace: Vec<VizSecurityTraceHop>,
461 actions: Value,
462}
463
464#[derive(Serialize)]
466pub struct VizSecurityBlindSpot {
467 kind: String,
468 count: usize,
469 #[serde(skip_serializing_if = "Option::is_none")]
470 path: Option<String>,
471 #[serde(skip_serializing_if = "Option::is_none")]
472 file: Option<u32>,
473 #[serde(skip_serializing_if = "Option::is_none")]
474 line: Option<u32>,
475 #[serde(skip_serializing_if = "Option::is_none")]
476 reason: Option<String>,
477}
478
479#[derive(Serialize)]
482pub struct VizSecurityData {
483 pub availability: VizAvailability,
486 pub runtime_availability: VizAvailability,
489 pub candidates: Vec<VizSecurityCandidate>,
491 pub blind_spot_count: usize,
493 #[serde(skip_serializing_if = "Option::is_none")]
495 pub blind_spots_truncated: Option<usize>,
496 pub blind_spots: Vec<VizSecurityBlindSpot>,
498}
499
500#[derive(Serialize)]
502pub struct VizFile {
503 pub path: String,
505 pub size: u64,
507 pub status: VizFileStatus,
509 pub export_count: u16,
511 pub unused_export_count: u16,
513 pub is_entry: bool,
515 pub importer_count: u16,
517 pub import_count: u16,
519 #[serde(skip_serializing_if = "Option::is_none")]
521 pub workspace: Option<u16>,
522 #[serde(skip_serializing_if = "Option::is_none")]
524 pub zone: Option<u16>,
525 #[serde(skip_serializing_if = "Vec::is_empty")]
527 pub unused_exports: Vec<String>,
528 pub fn_count: u16,
530 pub max_cyclomatic: u16,
532 pub max_cognitive: u16,
534 pub react_hooks: u16,
536 pub jsx_depth: u16,
538 #[serde(skip_serializing_if = "Vec::is_empty")]
540 pub functions: Vec<VizFunction>,
541 pub dup_lines: u32,
543 #[serde(skip_serializing_if = "Vec::is_empty")]
545 pub clone_groups: Vec<u32>,
546 pub in_cycle: bool,
548}
549
550#[derive(Serialize, Clone, Copy, PartialEq, Eq)]
552#[serde(rename_all = "camelCase")]
553pub enum VizFileStatus {
554 Clean,
556 HasUnusedExports,
558 Unused,
560 EntryPoint,
562}
563
564#[derive(Serialize)]
566pub struct VizFunction {
567 name: String,
569 line: u32,
571 cyclomatic: u16,
573 cognitive: u16,
575 lines: u32,
577 hooks: u16,
579 jsx_depth: u16,
581 props: u16,
583}
584
585#[derive(Serialize)]
587pub struct VizSummary {
588 pub total_files: usize,
590 pub total_size: u64,
592 pub total_edges: usize,
594 pub unused_files: usize,
596 pub unused_exports: usize,
598 pub unused_types: usize,
600 pub unused_deps: usize,
602 pub unresolved_imports: usize,
604 pub circular_deps: usize,
606 pub clone_groups: usize,
608 pub duplicated_lines: usize,
610 pub boundary_violations: usize,
612 pub hotspot_files: usize,
614 #[serde(skip_serializing_if = "Option::is_none")]
617 pub clone_groups_truncated: Option<u32>,
618}
619
620#[derive(Serialize)]
622pub struct VizWorkspace {
623 name: String,
625 root: String,
627}
628
629#[derive(Serialize)]
631pub struct VizZone {
632 name: String,
634 files: u32,
636}
637
638#[derive(Serialize)]
640pub struct VizCloneGroup {
641 lines: usize,
643 tokens: usize,
645 instances: Vec<VizCloneInstance>,
647 preview: String,
651 highlight_start: u32,
654 highlight_lines: u32,
658}
659
660#[derive(Serialize)]
662pub struct VizCloneInstance {
663 file: u32,
665 start_line: u32,
667 end_line: u32,
669}
670
671#[derive(Serialize)]
673pub struct VizViolation {
674 from: u32,
676 to: u32,
678 from_zone: u16,
680 to_zone: u16,
682 line: u32,
684 specifier: String,
686}
687
688#[must_use]
690pub fn build_viz_data(input: &VizBuildInput<'_>) -> VizData {
691 let root = &input.config.root;
692 let index = FileIndex::new(input.files);
693 let workspaces = build_workspaces(input.workspaces, root);
694 let (zones, zone_by_file) = classify_zones(input, &index);
695 let (clones, clone_groups_by_file, dup_lines_by_file, clone_groups_truncated) =
696 build_clones(input.duplication, &index, MAX_CLONE_GROUPS);
697 let cycles = build_cycles(input.results, &index);
698 let violations = build_violations(input.results, &zones, &index);
699 let (architecture, dependencies, security, frameworks, feature_flags) =
700 if input.include_analysis_details {
701 (
702 build_architecture(input.results, &index, root),
703 build_dependencies(input.results, &index, root),
704 build_security(input.results, &index, root),
705 build_frameworks(input.results, &index, root),
706 build_feature_flags(input.feature_flags, &index, root),
707 )
708 } else {
709 skipped_analysis_details()
710 };
711
712 let files = build_files(
713 input,
714 &index,
715 &FilePropertyMaps {
716 zone_by_file: &zone_by_file,
717 clone_groups_by_file: &clone_groups_by_file,
718 dup_lines_by_file: &dup_lines_by_file,
719 cycles: &cycles,
720 },
721 );
722
723 let summary = build_summary(
724 input,
725 &files,
726 &clones,
727 &cycles,
728 &violations,
729 clone_groups_truncated,
730 );
731
732 VizData {
733 root: display_root(root),
734 files,
735 edges: build_edges(input.graph, &index),
736 summary,
737 workspaces,
738 zones,
739 cycles,
740 clones,
741 violations,
742 architecture,
743 dependencies,
744 health: VizHealthData {
745 availability: VizAvailability::unavailable("files", "Health analysis did not complete"),
746 capabilities: unavailable_health_capabilities("Health analysis did not complete"),
747 shared_parse: None,
748 score: None,
749 grade: None,
750 average_maintainability: None,
751 files: Vec::new(),
752 files_truncated: None,
753 findings_truncated: None,
754 findings: Vec::new(),
755 },
756 security,
757 frameworks,
758 styling: VizStylingData {
759 availability: VizAvailability::unavailable(
760 "findings",
761 "Styling analysis did not complete",
762 ),
763 findings_truncated: None,
764 findings: Vec::new(),
765 score: None,
766 grade: None,
767 confidence: None,
768 summary: None,
769 },
770 feature_flags,
771 }
772}
773
774fn skipped_analysis_details() -> (
775 VizFindingAnalysis,
776 VizFindingAnalysis,
777 VizSecurityData,
778 VizFrameworkData,
779 VizFindingAnalysis,
780) {
781 let skipped = |unit| VizFindingAnalysis {
782 availability: VizAvailability::disabled(unit, "Not needed for this Viz output format"),
783 findings_truncated: None,
784 findings: Vec::new(),
785 };
786 (
787 skipped("violations"),
788 skipped("findings"),
789 VizSecurityData {
790 availability: VizAvailability::disabled(
791 "candidates",
792 "Not needed for this Viz output format",
793 ),
794 runtime_availability: VizAvailability::disabled(
795 "observations",
796 "Not needed for this Viz output format",
797 ),
798 candidates: Vec::new(),
799 blind_spot_count: 0,
800 blind_spots_truncated: None,
801 blind_spots: Vec::new(),
802 },
803 VizFrameworkData {
804 availability: VizAvailability::disabled(
805 "findings",
806 "Not needed for this Viz output format",
807 ),
808 detector_availability: VizAvailability::disabled(
809 "detectors",
810 "Not needed for this Viz output format",
811 ),
812 findings_truncated: None,
813 findings: Vec::new(),
814 detected_frameworks: Vec::new(),
815 detectors: Vec::new(),
816 },
817 skipped("flags"),
818 )
819}
820
821struct FileIndex<'a> {
823 ordered: Vec<&'a DiscoveredFile>,
824 by_path: FxHashMap<&'a Path, u32>,
825 by_file_id: FxHashMap<u32, u32>,
826}
827
828impl<'a> FileIndex<'a> {
829 fn new(files: &'a [DiscoveredFile]) -> Self {
830 let mut ordered: Vec<&DiscoveredFile> = files.iter().collect();
831 ordered.sort_by_key(|f| f.id.0);
832 let mut by_path = FxHashMap::default();
833 let mut by_file_id = FxHashMap::default();
834 for (i, f) in ordered.iter().enumerate() {
835 let idx = clamp_u32(i);
836 by_path.insert(f.path.as_path(), idx);
837 by_file_id.insert(f.id.0, idx);
838 }
839 Self {
840 ordered,
841 by_path,
842 by_file_id,
843 }
844 }
845
846 fn index_of_path(&self, path: &Path) -> Option<u32> {
847 self.by_path.get(path).copied()
848 }
849
850 fn index_of_file_id(&self, file_id: u32) -> Option<u32> {
851 self.by_file_id.get(&file_id).copied()
852 }
853}
854
855fn analysis_from_records(
856 mut findings: Vec<VizFinding>,
857 total_findings: usize,
858 primary_count: usize,
859 unit: &'static str,
860) -> VizFindingAnalysis {
861 let findings_truncated = (total_findings > MAX_ANALYSIS_FINDINGS)
862 .then_some(total_findings.saturating_sub(MAX_ANALYSIS_FINDINGS));
863 let primary_truncated = (primary_count > MAX_ANALYSIS_FINDINGS)
864 .then_some(primary_count.saturating_sub(MAX_ANALYSIS_FINDINGS));
865 findings.truncate(MAX_ANALYSIS_FINDINGS);
866 VizFindingAnalysis {
867 availability: VizAvailability::complete(primary_count, unit, primary_truncated),
868 findings_truncated,
869 findings,
870 }
871}
872
873fn push_findings<T: Serialize>(
874 out: &mut Vec<VizFinding>,
875 kind: &str,
876 title: &str,
877 values: &[T],
878 root: &Path,
879 index: &FileIndex<'_>,
880) {
881 let remaining = MAX_ANALYSIS_FINDINGS.saturating_sub(out.len());
882 out.extend(values.iter().take(remaining).filter_map(|value| {
883 serde_json::to_value(value).ok().map(|detail| {
884 finding_from_value(kind, title, detail, root, &|path| index.index_of_path(path))
885 })
886 }));
887}
888
889fn finding_from_value(
890 kind: &str,
891 title: &str,
892 mut detail: Value,
893 root: &Path,
894 resolve_file: &dyn Fn(&Path) -> Option<u32>,
895) -> VizFinding {
896 let raw_path = find_string_key(&detail, &["path", "from_path", "consumer_path", "file"])
897 .map(str::to_owned);
898 let mut raw_paths = Vec::new();
899 collect_path_values(&detail, &mut raw_paths);
900 let mut paths = Vec::new();
901 let mut files = Vec::new();
902 for raw in raw_paths {
903 let raw_path = Path::new(&raw);
904 let absolute_path = if raw_path.has_root() {
908 raw_path.to_path_buf()
909 } else {
910 root.join(raw_path)
911 };
912 let display = relative_path(&absolute_path, root);
913 if !paths.contains(&display) {
914 paths.push(display);
915 }
916 if let Some(file) = resolve_file(&absolute_path)
917 && !files.contains(&file)
918 {
919 files.push(file);
920 }
921 }
922 let absolute = raw_path.as_deref().map(Path::new).map(|path| {
923 if path.has_root() {
924 path.to_path_buf()
925 } else {
926 root.join(path)
927 }
928 });
929 let file = absolute.as_deref().and_then(resolve_file);
930 let path = absolute.as_deref().map(|path| relative_path(path, root));
931 let line = find_u64_key(&detail, &["line", "start_line"])
932 .map(|value| u32::try_from(value).unwrap_or(u32::MAX));
933 relativize_value_paths(&mut detail, root);
934 let description =
935 find_string_key(&detail, &["message", "evidence", "reason"]).map(str::to_owned);
936 let severity = find_string_key(&detail, &["severity"]).map(str::to_owned);
937 let facts = finding_facts(&detail);
938 let actions = finding_actions(&detail);
939 VizFinding {
940 kind: kind.to_string(),
941 title: title.to_string(),
942 file,
943 path,
944 line,
945 files,
946 paths,
947 description,
948 severity,
949 facts,
950 actions,
951 }
952}
953
954fn finding_facts(detail: &Value) -> Vec<VizFindingFact> {
955 const EXCLUDED: &[&str] = &[
956 "path",
957 "from_path",
958 "to_path",
959 "consumer_path",
960 "file",
961 "files",
962 "paths",
963 "line",
964 "start_line",
965 "message",
966 "evidence",
967 "reason",
968 "severity",
969 "actions",
970 ];
971 let Some(fields) = detail.as_object() else {
972 return Vec::new();
973 };
974 fields
975 .iter()
976 .filter(|(label, _)| !EXCLUDED.contains(&label.as_str()))
977 .filter_map(|(label, value)| {
978 scalar_fact_value(value).map(|value| VizFindingFact {
979 label: label.clone(),
980 value,
981 })
982 })
983 .take(12)
984 .collect()
985}
986
987fn scalar_fact_value(value: &Value) -> Option<String> {
988 match value {
989 Value::String(value) => Some(value.clone()),
990 Value::Number(value) => Some(value.to_string()),
991 Value::Bool(value) => Some(value.to_string()),
992 Value::Array(values) if values.iter().all(Value::is_string) => Some(
993 values
994 .iter()
995 .filter_map(Value::as_str)
996 .collect::<Vec<_>>()
997 .join(", "),
998 ),
999 Value::Null | Value::Array(_) | Value::Object(_) => None,
1000 }
1001}
1002
1003fn finding_actions(detail: &Value) -> Vec<VizFindingAction> {
1004 let mut actions = Vec::new();
1005 if let Some(record) = detail.as_object() {
1006 for key in ["verify_command", "trace_command", "command"] {
1007 if let Some(command) = record.get(key).and_then(Value::as_str) {
1008 actions.push(VizFindingAction {
1009 label: "Verify".to_string(),
1010 kind: None,
1011 auto_fixable: false,
1012 command: Some(command.to_string()),
1013 comment: None,
1014 config_key: None,
1015 value: None,
1016 description: None,
1017 });
1018 }
1019 }
1020 if let Some(value) = record.get("actions") {
1021 append_projected_actions(&mut actions, value);
1022 }
1023 }
1024 actions
1025}
1026
1027fn append_projected_actions(actions: &mut Vec<VizFindingAction>, value: &Value) {
1028 match value {
1029 Value::Array(values) => {
1030 for value in values {
1031 if let Some(action) = projected_action(value) {
1032 actions.push(action);
1033 }
1034 }
1035 }
1036 Value::Object(values) => {
1037 for (label, value) in values {
1038 if let Some(command) = value.as_str() {
1039 actions.push(VizFindingAction {
1040 label: label.clone(),
1041 kind: Some(label.clone()),
1042 auto_fixable: false,
1043 command: Some(command.to_string()),
1044 comment: None,
1045 config_key: None,
1046 value: None,
1047 description: None,
1048 });
1049 }
1050 }
1051 }
1052 Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
1053 }
1054}
1055
1056fn projected_action(value: &Value) -> Option<VizFindingAction> {
1057 let action = value.as_object()?;
1058 let kind = ["kind", "type"]
1059 .iter()
1060 .find_map(|key| action.get(*key).and_then(Value::as_str))
1061 .map(str::to_owned);
1062 let label = ["label", "title"]
1063 .iter()
1064 .find_map(|key| action.get(*key).and_then(Value::as_str))
1065 .map(str::to_owned)
1066 .or_else(|| kind.clone())
1067 .unwrap_or_else(|| "Review".to_string());
1068 let command = action
1069 .get("command")
1070 .and_then(Value::as_str)
1071 .map(str::to_owned);
1072 let comment = action
1073 .get("comment")
1074 .and_then(Value::as_str)
1075 .map(str::to_owned);
1076 let auto_fixable = action
1077 .get("auto_fixable")
1078 .and_then(Value::as_bool)
1079 .unwrap_or(false);
1080 let config_key = action
1081 .get("config_key")
1082 .and_then(Value::as_str)
1083 .map(str::to_owned);
1084 let projected_value = action.get("value").cloned();
1085 let description = ["description", "note"]
1086 .iter()
1087 .find_map(|key| action.get(*key).and_then(Value::as_str))
1088 .map(str::to_owned);
1089 (command.is_some()
1090 || comment.is_some()
1091 || description.is_some()
1092 || config_key.is_some()
1093 || projected_value.is_some())
1094 .then_some(VizFindingAction {
1095 label,
1096 kind,
1097 auto_fixable,
1098 command,
1099 comment,
1100 config_key,
1101 value: projected_value,
1102 description,
1103 })
1104}
1105
1106fn collect_path_values(value: &Value, out: &mut Vec<String>) {
1107 match value {
1108 Value::Object(map) => {
1109 for (key, value) in map {
1110 if is_path_key(key)
1111 && let Some(path) = value.as_str()
1112 {
1113 out.push(path.to_string());
1114 }
1115 if is_path_collection_key(key)
1116 && let Some(values) = value.as_array()
1117 {
1118 out.extend(values.iter().filter_map(Value::as_str).map(str::to_string));
1119 }
1120 collect_path_values(value, out);
1121 }
1122 }
1123 Value::Array(values) => {
1124 for value in values {
1125 collect_path_values(value, out);
1126 }
1127 }
1128 Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
1129 }
1130}
1131
1132fn find_string_key<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {
1133 match value {
1134 Value::Object(map) => {
1135 for key in keys {
1136 if let Some(value) = map.get(*key).and_then(Value::as_str) {
1137 return Some(value);
1138 }
1139 }
1140 map.values().find_map(|value| find_string_key(value, keys))
1141 }
1142 Value::Array(values) => values.iter().find_map(|value| find_string_key(value, keys)),
1143 _ => None,
1144 }
1145}
1146
1147fn find_u64_key(value: &Value, keys: &[&str]) -> Option<u64> {
1148 match value {
1149 Value::Object(map) => {
1150 for key in keys {
1151 if let Some(value) = map.get(*key).and_then(Value::as_u64) {
1152 return Some(value);
1153 }
1154 }
1155 map.values().find_map(|value| find_u64_key(value, keys))
1156 }
1157 Value::Array(values) => values.iter().find_map(|value| find_u64_key(value, keys)),
1158 _ => None,
1159 }
1160}
1161
1162fn relativize_value_paths(value: &mut Value, root: &Path) {
1163 relativize_keyed_paths(value, root, false);
1164}
1165
1166fn relativize_keyed_paths(value: &mut Value, root: &Path, is_path: bool) {
1167 match value {
1168 Value::String(text) if is_path => {
1169 let path = Path::new(text);
1170 if path.has_root() {
1176 *text = relative_path(path, root);
1177 }
1178 }
1179 Value::Array(values) => {
1180 for value in values {
1181 relativize_keyed_paths(value, root, is_path);
1182 }
1183 }
1184 Value::Object(map) => {
1185 for (key, value) in map {
1186 let is_path = is_path_key(key) || is_path_collection_key(key);
1187 relativize_keyed_paths(value, root, is_path);
1188 }
1189 }
1190 Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
1191 }
1192}
1193
1194fn is_path_key(key: &str) -> bool {
1195 matches!(
1196 key,
1197 "path"
1198 | "file"
1199 | "from_path"
1200 | "to_path"
1201 | "consumer_path"
1202 | "source_path"
1203 | "definition_path"
1204 | "template_path"
1205 | "inherited_from"
1206 | "reachable_via"
1207 | "new_path"
1208 | "old_path"
1209 | "cycle_path"
1210 | "docs_path"
1211 | "meta_docs_path"
1212 | "full_report_path"
1213 )
1214}
1215
1216fn is_path_collection_key(key: &str) -> bool {
1217 matches!(
1218 key,
1219 "files"
1220 | "paths"
1221 | "conflicting_paths"
1222 | "used_in_workspaces"
1223 | "hardcoded_consumers"
1224 | "hot_paths"
1225 )
1226}
1227
1228fn serialized_label<T: Serialize>(value: &T) -> String {
1229 serde_json::to_value(value)
1230 .ok()
1231 .and_then(|value| value.as_str().map(str::to_owned))
1232 .unwrap_or_else(|| "unknown".to_string())
1233}
1234
1235fn build_architecture(
1236 results: &AnalysisResults,
1237 index: &FileIndex<'_>,
1238 root: &Path,
1239) -> VizFindingAnalysis {
1240 let mut findings = Vec::new();
1241 push_findings(
1242 &mut findings,
1243 "boundary-violation",
1244 "Forbidden import",
1245 &results.boundary_violations,
1246 root,
1247 index,
1248 );
1249 push_findings(
1250 &mut findings,
1251 "boundary-coverage",
1252 "File outside architecture zones",
1253 &results.boundary_coverage_violations,
1254 root,
1255 index,
1256 );
1257 push_findings(
1258 &mut findings,
1259 "boundary-call",
1260 "Forbidden call",
1261 &results.boundary_call_violations,
1262 root,
1263 index,
1264 );
1265 push_findings(
1266 &mut findings,
1267 "policy-violation",
1268 "Policy violation",
1269 &results.policy_violations,
1270 root,
1271 index,
1272 );
1273 push_findings(
1274 &mut findings,
1275 "circular-dependency",
1276 "Import cycle",
1277 &results.circular_dependencies,
1278 root,
1279 index,
1280 );
1281 push_findings(
1282 &mut findings,
1283 "re-export-cycle",
1284 "Re-export cycle",
1285 &results.re_export_cycles,
1286 root,
1287 index,
1288 );
1289 push_findings(
1290 &mut findings,
1291 "package-cycle",
1292 "Package cycle",
1293 &results.package_cycles,
1294 root,
1295 index,
1296 );
1297 let violation_count = results.boundary_violations.len()
1298 + results.boundary_coverage_violations.len()
1299 + results.boundary_call_violations.len()
1300 + results.policy_violations.len();
1301 let total_findings = violation_count
1302 + results.circular_dependencies.len()
1303 + results.re_export_cycles.len()
1304 + results.package_cycles.len();
1305 analysis_from_records(findings, total_findings, violation_count, "violations")
1306}
1307
1308fn build_dependencies(
1309 results: &AnalysisResults,
1310 index: &FileIndex<'_>,
1311 root: &Path,
1312) -> VizFindingAnalysis {
1313 let mut findings = Vec::new();
1314 let mut count = 0;
1315 macro_rules! add {
1316 ($field:ident, $kind:literal, $title:literal) => {
1317 count += results.$field.len();
1318 push_findings(&mut findings, $kind, $title, &results.$field, root, index);
1319 };
1320 }
1321 add!(unresolved_imports, "unresolved-import", "Unresolved import");
1322 add!(
1323 unlisted_dependencies,
1324 "unlisted-dependency",
1325 "Unlisted dependency"
1326 );
1327 add!(
1328 type_only_dependencies,
1329 "type-only-dependency",
1330 "Type-only dependency"
1331 );
1332 add!(
1333 test_only_dependencies,
1334 "test-only-dependency",
1335 "Test-only dependency"
1336 );
1337 add!(
1338 dev_dependencies_in_production,
1339 "dev-dependency-in-production",
1340 "Development dependency used in production"
1341 );
1342 add!(
1343 duplicate_exports,
1344 "duplicate-export",
1345 "Duplicate public export"
1346 );
1347 add!(
1348 private_type_leaks,
1349 "private-type-leak",
1350 "Private type leaked by public API"
1351 );
1352 add!(
1353 deprecated_exports_in_use,
1354 "deprecated-export-in-use",
1355 "Deprecated export still in use"
1356 );
1357 add!(
1358 unused_catalog_entries,
1359 "unused-catalog-entry",
1360 "Unused catalog entry"
1361 );
1362 add!(
1363 empty_catalog_groups,
1364 "empty-catalog-group",
1365 "Empty catalog group"
1366 );
1367 add!(
1368 unresolved_catalog_references,
1369 "unresolved-catalog-reference",
1370 "Unresolved catalog reference"
1371 );
1372 add!(
1373 unused_dependency_overrides,
1374 "unused-dependency-override",
1375 "Unused dependency override"
1376 );
1377 add!(
1378 misconfigured_dependency_overrides,
1379 "misconfigured-dependency-override",
1380 "Misconfigured dependency override"
1381 );
1382 analysis_from_records(findings, count, count, "findings")
1383}
1384
1385fn build_frameworks(
1386 results: &AnalysisResults,
1387 index: &FileIndex<'_>,
1388 root: &Path,
1389) -> VizFrameworkData {
1390 let mut findings = Vec::new();
1391 let mut count = 0;
1392 macro_rules! add {
1393 ($field:ident, $kind:literal, $title:literal) => {
1394 count += results.$field.len();
1395 push_findings(&mut findings, $kind, $title, &results.$field, root, index);
1396 };
1397 }
1398 add!(
1399 invalid_client_exports,
1400 "invalid-client-export",
1401 "Invalid client export"
1402 );
1403 add!(
1404 mixed_client_server_barrels,
1405 "mixed-client-server-barrel",
1406 "Mixed client/server barrel"
1407 );
1408 add!(
1409 misplaced_directives,
1410 "misplaced-directive",
1411 "Misplaced framework directive"
1412 );
1413 add!(
1414 unprovided_injects,
1415 "unprovided-inject",
1416 "Injected value is never provided"
1417 );
1418 add!(
1419 unrendered_components,
1420 "unrendered-component",
1421 "Component is never rendered"
1422 );
1423 add!(route_collisions, "route-collision", "Route collision");
1424 add!(
1425 dynamic_segment_name_conflicts,
1426 "dynamic-segment-conflict",
1427 "Dynamic segment conflict"
1428 );
1429 add!(
1430 unused_component_props,
1431 "unused-component-prop",
1432 "Unused component prop"
1433 );
1434 add!(
1435 unused_component_emits,
1436 "unused-component-emit",
1437 "Unused component event"
1438 );
1439 add!(
1440 unused_component_inputs,
1441 "unused-component-input",
1442 "Unused component input"
1443 );
1444 add!(
1445 unused_component_outputs,
1446 "unused-component-output",
1447 "Unused component output"
1448 );
1449 add!(
1450 unused_svelte_events,
1451 "unused-svelte-event",
1452 "Unused Svelte event"
1453 );
1454 add!(
1455 unused_server_actions,
1456 "unused-server-action",
1457 "Unused server action"
1458 );
1459 add!(
1460 unused_load_data_keys,
1461 "unused-load-data-key",
1462 "Unused load-data key"
1463 );
1464 add!(prop_drilling_chains, "prop-drilling", "Prop-drilling chain");
1465 add!(thin_wrappers, "thin-wrapper", "Thin component wrapper");
1466 add!(
1467 duplicate_prop_shapes,
1468 "duplicate-prop-shape",
1469 "Duplicate prop shape"
1470 );
1471 let mut analysis = analysis_from_records(findings, count, count, "findings");
1472 if results.unused_load_data_keys_global_abstain {
1473 analysis.availability.reason = Some(
1474 "Load-data-key analysis abstained because whole-object page data usage was detected"
1475 .to_string(),
1476 );
1477 }
1478 VizFrameworkData {
1479 availability: analysis.availability,
1480 detector_availability: VizAvailability::unavailable(
1481 "detectors",
1482 "Framework detector coverage did not complete",
1483 ),
1484 findings_truncated: analysis.findings_truncated,
1485 findings: analysis.findings,
1486 detected_frameworks: Vec::new(),
1487 detectors: Vec::new(),
1488 }
1489}
1490
1491fn build_feature_flags(
1492 flags: &[FeatureFlag],
1493 index: &FileIndex<'_>,
1494 root: &Path,
1495) -> VizFindingAnalysis {
1496 let mut findings = Vec::new();
1497 push_findings(
1498 &mut findings,
1499 "feature-flag",
1500 "Feature flag use",
1501 flags,
1502 root,
1503 index,
1504 );
1505 analysis_from_records(findings, flags.len(), flags.len(), "flags")
1506}
1507
1508fn build_security(
1509 results: &AnalysisResults,
1510 index: &FileIndex<'_>,
1511 root: &Path,
1512) -> VizSecurityData {
1513 let total = results.security_findings.len();
1514 let truncated =
1515 (total > MAX_ANALYSIS_FINDINGS).then_some(total.saturating_sub(MAX_ANALYSIS_FINDINGS));
1516 let mut sorted_findings: Vec<&SecurityFinding> = results.security_findings.iter().collect();
1517 sorted_findings.sort_by_key(|finding| {
1518 let severity = serialized_label(&crate::security::derive_security_severity(finding));
1519 let priority = match severity.as_str() {
1520 "high" => 0,
1521 "medium" => 1,
1522 _ => 2,
1523 };
1524 (priority, relative_path(&finding.path, root), finding.line)
1525 });
1526 let candidates = sorted_findings
1527 .into_iter()
1528 .take(MAX_ANALYSIS_FINDINGS)
1529 .map(|finding| build_security_candidate(finding, index, root))
1530 .collect();
1531
1532 let mut blind_spots = Vec::new();
1533 if results.security_unresolved_edge_files > 0 {
1534 blind_spots.push(VizSecurityBlindSpot {
1535 kind: "unresolved-dynamic-imports".to_string(),
1536 count: results.security_unresolved_edge_files,
1537 path: None,
1538 file: None,
1539 line: None,
1540 reason: Some("Dynamic imports prevent complete client/server reachability".to_string()),
1541 });
1542 }
1543 if results.security_unresolved_callee_sites > 0 {
1544 blind_spots.push(VizSecurityBlindSpot {
1545 kind: "unresolved-callee-sites".to_string(),
1546 count: results.security_unresolved_callee_sites,
1547 path: None,
1548 file: None,
1549 line: None,
1550 reason: Some(
1551 "Dynamic or computed callees could not be matched to the sink catalogue"
1552 .to_string(),
1553 ),
1554 });
1555 }
1556 let diagnostic_count = results.security_unresolved_callee_diagnostics.len();
1557 for diagnostic in results
1558 .security_unresolved_callee_diagnostics
1559 .iter()
1560 .take(MAX_SECURITY_BLIND_SPOT_SAMPLES)
1561 {
1562 blind_spots.push(VizSecurityBlindSpot {
1563 kind: "unresolved-callee-sample".to_string(),
1564 count: 1,
1565 path: Some(relative_path(&diagnostic.path, root)),
1566 file: index.index_of_path(&diagnostic.path),
1567 line: Some(diagnostic.line),
1568 reason: Some(serialized_label(&diagnostic.reason)),
1569 });
1570 }
1571
1572 VizSecurityData {
1573 availability: VizAvailability::complete(total, "candidates", truncated),
1574 runtime_availability: VizAvailability::unavailable(
1575 "observations",
1576 NO_RUNTIME_COVERAGE_REASON,
1577 ),
1578 candidates,
1579 blind_spot_count: results.security_unresolved_edge_files
1580 + results.security_unresolved_callee_sites,
1581 blind_spots_truncated: (diagnostic_count > MAX_SECURITY_BLIND_SPOT_SAMPLES)
1582 .then_some(diagnostic_count.saturating_sub(MAX_SECURITY_BLIND_SPOT_SAMPLES)),
1583 blind_spots,
1584 }
1585}
1586
1587fn build_security_candidate(
1588 finding: &SecurityFinding,
1589 index: &FileIndex<'_>,
1590 root: &Path,
1591) -> VizSecurityCandidate {
1592 let kind = serialized_label(&finding.kind);
1593 let path = relative_path(&finding.path, root);
1594 let severity = serialized_label(&crate::security::derive_security_severity(finding));
1595 let id = crate::security::security_finding_id(finding, Path::new(&path));
1596 let reachability = finding.reachability.as_ref();
1597 let architecture_zone = finding
1598 .candidate
1599 .boundary
1600 .architecture_zone
1601 .as_ref()
1602 .map(|zone| format!("{} -> {}", zone.from, zone.to));
1603 let dead_code = serialize_relative(finding.dead_code.as_ref(), root);
1604 let runtime = serialize_relative(finding.runtime.as_ref(), root);
1605 let taint_flow = security_taint_flow(finding, index, root);
1606 let observed_controls = security_controls(finding, root);
1607 let actions = serialize_relative_value(&finding.actions, root)
1608 .unwrap_or_else(|| Value::Array(Vec::new()));
1609 let trace = security_trace(finding, index, root);
1610 let taint_trace = finding
1611 .reachability
1612 .as_ref()
1613 .map_or_else(Vec::new, |reachability| {
1614 trace_hops(&reachability.untrusted_source_trace, index, root)
1615 });
1616 VizSecurityCandidate {
1617 id,
1618 kind,
1619 category: finding.category.clone(),
1620 cwe: finding.cwe,
1621 file: index.index_of_path(&finding.path),
1622 path,
1623 line: finding.line,
1624 col: finding.col,
1625 evidence: finding.evidence.clone(),
1626 severity,
1627 taint_confidence: reachability
1628 .and_then(|reachability| reachability.taint_confidence.as_ref())
1629 .map(serialized_label),
1630 source_kind: finding.candidate.source_kind.clone(),
1631 sink: finding.candidate.sink.callee.clone(),
1632 url_shape: finding
1633 .candidate
1634 .sink
1635 .url_shape
1636 .as_ref()
1637 .map(serialized_label),
1638 network_destination: finding
1639 .candidate
1640 .network
1641 .as_ref()
1642 .and_then(|network| network.destination.clone()),
1643 reachable_from_entry: reachability.map(|value| value.reachable_from_entry),
1644 reachable_from_untrusted_source: reachability
1645 .map(|value| value.reachable_from_untrusted_source),
1646 blast_radius: reachability.map(|value| value.blast_radius),
1647 crosses_boundary: reachability.is_some_and(|value| value.crosses_boundary)
1648 || finding.candidate.boundary.client_server
1649 || finding.candidate.boundary.cross_module
1650 || architecture_zone.is_some(),
1651 client_server_boundary: finding.candidate.boundary.client_server,
1652 cross_module_boundary: finding.candidate.boundary.cross_module,
1653 architecture_zone,
1654 dead_code,
1655 runtime,
1656 taint_flow,
1657 observed_controls,
1658 control_verification_prompt: finding
1659 .attack_surface
1660 .as_ref()
1661 .map(|surface| surface.defensive_boundary.verification_prompt.clone()),
1662 trace,
1663 taint_trace,
1664 actions,
1665 }
1666}
1667
1668fn serialize_relative<T: Serialize>(value: Option<&T>, root: &Path) -> Option<Value> {
1669 value.and_then(|value| serialize_relative_value(value, root))
1670}
1671
1672fn serialize_relative_value<T: Serialize>(value: &T, root: &Path) -> Option<Value> {
1673 let mut serialized = serde_json::to_value(value).ok()?;
1674 relativize_value_paths(&mut serialized, root);
1675 Some(serialized)
1676}
1677
1678fn security_controls(finding: &SecurityFinding, root: &Path) -> Vec<Value> {
1679 finding
1680 .attack_surface
1681 .as_ref()
1682 .map_or_else(Vec::new, |surface| {
1683 surface
1684 .defensive_boundary
1685 .controls
1686 .iter()
1687 .filter_map(|control| serialize_relative_value(control, root))
1688 .collect()
1689 })
1690}
1691
1692fn security_trace(
1693 finding: &SecurityFinding,
1694 index: &FileIndex<'_>,
1695 root: &Path,
1696) -> Vec<VizSecurityTraceHop> {
1697 trace_hops(&finding.trace, index, root)
1698}
1699
1700fn trace_hops(
1701 hops: &[fallow_types::results::TraceHop],
1702 index: &FileIndex<'_>,
1703 root: &Path,
1704) -> Vec<VizSecurityTraceHop> {
1705 hops.iter()
1706 .map(|hop| VizSecurityTraceHop {
1707 file: index.index_of_path(&hop.path),
1708 path: relative_path(&hop.path, root),
1709 line: hop.line,
1710 col: hop.col,
1711 role: serialized_label(&hop.role),
1712 })
1713 .collect()
1714}
1715
1716fn security_taint_flow(
1717 finding: &SecurityFinding,
1718 index: &FileIndex<'_>,
1719 root: &Path,
1720) -> Option<VizSecurityTaintFlow> {
1721 let flow = finding.taint_flow.as_ref()?;
1722 let endpoint = |value: &fallow_types::results::TaintEndpoint| VizSecurityEndpoint {
1723 file: index.index_of_path(&value.path),
1724 path: relative_path(&value.path, root),
1725 line: value.line,
1726 col: value.col,
1727 };
1728 Some(VizSecurityTaintFlow {
1729 source: endpoint(&flow.source),
1730 sink: endpoint(&flow.sink),
1731 intra_module: flow.path.intra_module,
1732 cross_module_hops: flow.path.cross_module_hops,
1733 })
1734}
1735
1736pub fn apply_health_report(data: &mut VizData, report: &HealthReport, root: &Path) {
1739 let by_path: FxHashMap<String, u32> = data
1740 .files
1741 .iter()
1742 .enumerate()
1743 .map(|(index, file)| (file.path.clone(), clamp_u32(index)))
1744 .collect();
1745 apply_health_data(data, report, root, &by_path);
1746 apply_framework_data(data, report);
1747 apply_styling_data(data, report, root, &by_path);
1748}
1749
1750fn apply_health_data(
1751 data: &mut VizData,
1752 report: &HealthReport,
1753 root: &Path,
1754 by_path: &FxHashMap<String, u32>,
1755) {
1756 let resolve = |path: &Path| by_path.get(&relative_path(path, root)).copied();
1757 let hotspot_by_path: FxHashMap<String, &fallow_output::HotspotFinding> = report
1758 .hotspots
1759 .iter()
1760 .map(|hotspot| (relative_path(&hotspot.path, root), hotspot))
1761 .collect();
1762 let files = health_files(report, root, by_path, &hotspot_by_path);
1763 let (findings, total_findings) = health_findings(report, root, &resolve);
1764 let concern_count = health_concern_count(report, root, by_path);
1765 data.health = VizHealthData {
1766 availability: VizAvailability::complete(concern_count, "files", None),
1767 capabilities: health_capabilities(report),
1768 shared_parse: data.health.shared_parse,
1769 score: report.health_score.as_ref().map(|score| score.score),
1770 grade: report
1771 .health_score
1772 .as_ref()
1773 .map(|score| score.grade.to_string()),
1774 average_maintainability: report.summary.average_maintainability,
1775 files_truncated: report
1776 .file_scores
1777 .len()
1778 .checked_sub(MAX_HEALTH_FILES)
1779 .filter(|count| *count > 0),
1780 findings_truncated: total_findings
1781 .checked_sub(findings.len())
1782 .filter(|count| *count > 0),
1783 files,
1784 findings,
1785 };
1786}
1787
1788fn health_concern_count(
1789 report: &HealthReport,
1790 root: &Path,
1791 by_path: &FxHashMap<String, u32>,
1792) -> usize {
1793 let mut files = rustc_hash::FxHashSet::default();
1794 let mut add = |path: &Path| {
1795 if let Some(file) = by_path.get(&relative_path(path, root)) {
1796 files.insert(*file);
1797 }
1798 };
1799 for finding in &report.findings {
1800 add(&finding.path);
1801 }
1802 for hotspot in &report.hotspots {
1803 add(&hotspot.path);
1804 }
1805 if let Some(gaps) = &report.coverage_gaps {
1806 for finding in &gaps.files {
1807 add(&finding.file.path);
1808 }
1809 for finding in &gaps.exports {
1810 add(&finding.export.path);
1811 }
1812 }
1813 files.len()
1814}
1815
1816fn health_files(
1817 report: &HealthReport,
1818 root: &Path,
1819 by_path: &FxHashMap<String, u32>,
1820 hotspots: &FxHashMap<String, &fallow_output::HotspotFinding>,
1821) -> Vec<VizHealthFile> {
1822 report
1823 .file_scores
1824 .iter()
1825 .take(MAX_HEALTH_FILES)
1826 .filter_map(|score| {
1827 let path = relative_path(&score.path, root);
1828 let file = by_path.get(&path).copied()?;
1829 let hotspot = hotspots.get(&path).copied();
1830 Some(VizHealthFile {
1831 file,
1832 path,
1833 maintainability_index: score.maintainability_index,
1834 crap_max: score.crap_max,
1835 complexity_density: score.complexity_density,
1836 fan_in: score.fan_in,
1837 fan_out: score.fan_out,
1838 hotspot_score: hotspot.map(|entry| entry.score),
1839 commits: hotspot.map(|entry| entry.commits),
1840 ownership: hotspot
1841 .and_then(|entry| serialize_relative(entry.ownership.as_ref(), root)),
1842 })
1843 })
1844 .collect()
1845}
1846
1847fn health_findings(
1848 report: &HealthReport,
1849 root: &Path,
1850 resolve: &dyn Fn(&Path) -> Option<u32>,
1851) -> (Vec<VizFinding>, usize) {
1852 let coverage_count = report
1853 .coverage_gaps
1854 .as_ref()
1855 .map_or(0, |gaps| gaps.files.len() + gaps.exports.len());
1856 let total = report.findings.len() + report.hotspots.len() + coverage_count;
1857 let mut findings = Vec::with_capacity(total.min(MAX_ANALYSIS_FINDINGS));
1858 append_findings(
1859 &mut findings,
1860 &report.findings,
1861 "health-finding",
1862 "Health threshold exceeded",
1863 root,
1864 resolve,
1865 );
1866 append_findings(
1867 &mut findings,
1868 &report.hotspots,
1869 "git-hotspot",
1870 "Complex and frequently changed file",
1871 root,
1872 resolve,
1873 );
1874 if let Some(gaps) = &report.coverage_gaps {
1875 append_findings(
1876 &mut findings,
1877 &gaps.files,
1878 "coverage-gap-file",
1879 "File has no test path",
1880 root,
1881 resolve,
1882 );
1883 append_findings(
1884 &mut findings,
1885 &gaps.exports,
1886 "coverage-gap-export",
1887 "Export has no test path",
1888 root,
1889 resolve,
1890 );
1891 }
1892 (findings, total)
1893}
1894
1895fn append_findings<T: Serialize>(
1896 out: &mut Vec<VizFinding>,
1897 values: &[T],
1898 kind: &str,
1899 title: &str,
1900 root: &Path,
1901 resolve: &dyn Fn(&Path) -> Option<u32>,
1902) {
1903 let remaining = MAX_ANALYSIS_FINDINGS.saturating_sub(out.len());
1904 out.extend(values.iter().take(remaining).filter_map(|value| {
1905 serde_json::to_value(value)
1906 .ok()
1907 .map(|detail| finding_from_value(kind, title, detail, root, resolve))
1908 }));
1909}
1910
1911fn health_capabilities(report: &HealthReport) -> VizHealthCapabilities {
1912 let file_count = report.file_scores.len();
1913 let coverage = report.coverage_gaps.as_ref().map_or_else(
1914 || VizAvailability::unavailable("gaps", "Coverage gap analysis did not produce a result"),
1915 |gaps| VizAvailability::complete(gaps.files.len() + gaps.exports.len(), "gaps", None),
1916 );
1917 let runtime = report.runtime_coverage.as_ref().map_or_else(
1918 || VizAvailability::unavailable("observations", NO_RUNTIME_COVERAGE_REASON),
1919 |runtime| {
1920 VizAvailability::complete(runtime.summary.functions_tracked, "observations", None)
1921 },
1922 );
1923 VizHealthCapabilities {
1924 complexity: VizAvailability::complete(report.findings.len(), "findings", None),
1925 maintainability: VizAvailability::complete(file_count, "files", None),
1926 crap: VizAvailability::complete(file_count, "files", None),
1927 coverage,
1928 runtime,
1929 churn: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1930 hotspots: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1931 ownership: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1932 }
1933}
1934
1935fn unavailable_health_capabilities(reason: &str) -> VizHealthCapabilities {
1936 VizHealthCapabilities {
1937 complexity: VizAvailability::unavailable("findings", reason),
1938 maintainability: VizAvailability::unavailable("files", reason),
1939 crap: VizAvailability::unavailable("files", reason),
1940 coverage: VizAvailability::unavailable("gaps", reason),
1941 runtime: VizAvailability::unavailable("observations", NO_RUNTIME_COVERAGE_REASON),
1942 churn: VizAvailability::unavailable("files", reason),
1943 hotspots: VizAvailability::unavailable("files", reason),
1944 ownership: VizAvailability::unavailable("files", reason),
1945 }
1946}
1947
1948fn apply_framework_data(data: &mut VizData, report: &HealthReport) {
1949 let count = data.frameworks.availability.count;
1950 let Some(diagnostics) = &report.framework_health else {
1951 if count == 0 {
1952 data.frameworks.detector_availability = VizAvailability {
1953 state: VizAvailabilityState::NotApplicable,
1954 count: 0,
1955 unit: "detectors",
1956 reason: Some("No supported framework was detected".to_string()),
1957 truncated: None,
1958 };
1959 data.frameworks.availability.state = VizAvailabilityState::NotApplicable;
1960 data.frameworks.availability.reason =
1961 Some("No supported framework was detected".to_string());
1962 } else {
1963 data.frameworks.detector_availability = VizAvailability::unavailable(
1964 "detectors",
1965 "Framework detector metadata was not produced",
1966 );
1967 }
1968 return;
1969 };
1970 data.frameworks
1971 .detected_frameworks
1972 .clone_from(&diagnostics.detected_frameworks);
1973 data.frameworks.detectors = diagnostics
1974 .detectors
1975 .iter()
1976 .map(|detector| VizFrameworkDetector {
1977 id: detector.id.clone(),
1978 framework: detector.framework.clone(),
1979 status: serialized_label(&detector.status),
1980 reason: detector.reason.clone(),
1981 })
1982 .collect();
1983 data.frameworks.detector_availability =
1984 VizAvailability::complete(diagnostics.detectors.len(), "detectors", None);
1985 if diagnostics.detected_frameworks.is_empty() && count == 0 {
1986 data.frameworks.availability.state = VizAvailabilityState::NotApplicable;
1987 data.frameworks.availability.reason =
1988 Some("No supported framework was detected".to_string());
1989 data.frameworks.detector_availability.state = VizAvailabilityState::NotApplicable;
1990 data.frameworks.detector_availability.reason =
1991 Some("No supported framework was detected".to_string());
1992 }
1993}
1994
1995fn apply_styling_data(
1996 data: &mut VizData,
1997 report: &HealthReport,
1998 root: &Path,
1999 by_path: &FxHashMap<String, u32>,
2000) {
2001 let resolve = |path: &Path| by_path.get(&relative_path(path, root)).copied();
2002 let count = report.styling_findings.len();
2003 let mut findings = Vec::with_capacity(count.min(MAX_ANALYSIS_FINDINGS));
2004 append_findings(
2005 &mut findings,
2006 &report.styling_findings,
2007 "styling-finding",
2008 "Styling health finding",
2009 root,
2010 &resolve,
2011 );
2012 let truncated = count.checked_sub(findings.len()).filter(|value| *value > 0);
2013 let styling = report.styling_health.as_ref();
2014 data.styling = VizStylingData {
2015 availability: report.css_analytics.as_ref().map_or_else(
2016 || VizAvailability {
2017 state: VizAvailabilityState::NotApplicable,
2018 count: 0,
2019 unit: "findings",
2020 reason: Some("No supported CSS or component styling was detected".to_string()),
2021 truncated: None,
2022 },
2023 |_| VizAvailability::complete(count, "findings", truncated),
2024 ),
2025 findings_truncated: truncated,
2026 findings,
2027 score: styling.map(|health| health.score),
2028 grade: styling.map(|health| health.grade.to_string()),
2029 confidence: styling.map(|health| serialized_label(&health.confidence)),
2030 summary: report
2031 .css_analytics
2032 .as_ref()
2033 .and_then(|analytics| serde_json::to_value(&analytics.summary).ok()),
2034 };
2035}
2036
2037struct FilePropertyMaps<'a> {
2039 zone_by_file: &'a FxHashMap<u32, u16>,
2040 clone_groups_by_file: &'a FxHashMap<u32, Vec<u32>>,
2041 dup_lines_by_file: &'a FxHashMap<u32, u32>,
2042 cycles: &'a [Vec<u32>],
2043}
2044
2045fn display_root(root: &Path) -> String {
2046 root.file_name().map_or_else(
2047 || root.to_string_lossy().into_owned(),
2048 |n| n.to_string_lossy().into_owned(),
2049 )
2050}
2051
2052fn relative_path(path: &Path, root: &Path) -> String {
2053 if let Ok(relative) = path.strip_prefix(root) {
2054 return relative.to_string_lossy().replace('\\', "/");
2055 }
2056 if path.has_root() {
2061 let name = path
2062 .file_name()
2063 .map_or_else(|| "path".into(), |name| name.to_string_lossy());
2064 return format!("<external>/{name}");
2065 }
2066 path.to_string_lossy().replace('\\', "/")
2067}
2068
2069fn build_workspaces(workspaces: &[WorkspaceInfo], root: &Path) -> Vec<VizWorkspace> {
2070 workspaces
2071 .iter()
2072 .map(|ws| VizWorkspace {
2073 name: ws.name.clone(),
2074 root: relative_path(&ws.root, root),
2075 })
2076 .collect()
2077}
2078
2079fn workspace_index_for(path: &Path, workspaces: &[WorkspaceInfo]) -> Option<u16> {
2080 let mut best: Option<(usize, usize)> = None;
2081 for (i, ws) in workspaces.iter().enumerate() {
2082 if path.starts_with(&ws.root) {
2083 let depth = ws.root.components().count();
2084 if best.is_none_or(|(_, d)| depth > d) {
2085 best = Some((i, depth));
2086 }
2087 }
2088 }
2089 best.map(|(i, _)| clamp_u16(i))
2090}
2091
2092fn classify_zones(
2093 input: &VizBuildInput<'_>,
2094 index: &FileIndex<'_>,
2095) -> (Vec<VizZone>, FxHashMap<u32, u16>) {
2096 let boundaries = &input.config.boundaries;
2097 let mut zones: Vec<VizZone> = boundaries
2098 .zones
2099 .iter()
2100 .map(|z| VizZone {
2101 name: z.name.clone(),
2102 files: 0,
2103 })
2104 .collect();
2105 let name_to_index: FxHashMap<&str, u16> = boundaries
2106 .zones
2107 .iter()
2108 .enumerate()
2109 .map(|(i, z)| (z.name.as_str(), clamp_u16(i)))
2110 .collect();
2111
2112 let mut zone_by_file = FxHashMap::default();
2113 if zones.is_empty() {
2114 return (zones, zone_by_file);
2115 }
2116
2117 for (i, file) in index.ordered.iter().enumerate() {
2118 let rel = relative_path(&file.path, &input.config.root);
2119 if let Some(zone_name) = boundaries.classify_zone(&rel)
2120 && let Some(&zone_idx) = name_to_index.get(zone_name)
2121 {
2122 zone_by_file.insert(clamp_u32(i), zone_idx);
2123 zones[zone_idx as usize].files += 1;
2124 }
2125 }
2126
2127 (zones, zone_by_file)
2128}
2129
2130type CloneMaps = (
2133 Vec<VizCloneGroup>,
2134 FxHashMap<u32, Vec<u32>>,
2135 FxHashMap<u32, u32>,
2136 u32,
2137);
2138
2139fn build_clones(
2140 duplication: &DuplicationReport,
2141 index: &FileIndex<'_>,
2142 max_groups: usize,
2143) -> CloneMaps {
2144 let mut clones = Vec::new();
2145 let mut groups_by_file: FxHashMap<u32, Vec<u32>> = FxHashMap::default();
2146 let mut dup_lines_by_file: FxHashMap<u32, u32> = FxHashMap::default();
2147 let mut truncated: usize = 0;
2148
2149 for group in &duplication.clone_groups {
2150 let instances: Vec<VizCloneInstance> = group
2151 .instances
2152 .iter()
2153 .filter_map(|inst| {
2154 index
2155 .index_of_path(&inst.file)
2156 .map(|file| VizCloneInstance {
2157 file,
2158 start_line: clamp_u32(inst.start_line),
2159 end_line: clamp_u32(inst.end_line),
2160 })
2161 })
2162 .collect();
2163 if instances.len() < 2 {
2164 continue;
2165 }
2166 if clones.len() >= max_groups {
2167 truncated += 1;
2168 continue;
2169 }
2170
2171 let group_idx = clamp_u32(clones.len());
2172 for inst in &instances {
2173 let entry = groups_by_file.entry(inst.file).or_default();
2174 if entry.last() != Some(&group_idx) {
2175 entry.push(group_idx);
2176 }
2177 *dup_lines_by_file.entry(inst.file).or_default() +=
2178 inst.end_line.saturating_sub(inst.start_line) + 1;
2179 }
2180
2181 let (preview, highlight_start, highlight_lines) = group
2182 .instances
2183 .first()
2184 .map(build_clone_preview)
2185 .unwrap_or_default();
2186
2187 clones.push(VizCloneGroup {
2188 lines: group.line_count,
2189 tokens: group.token_count,
2190 instances,
2191 preview,
2192 highlight_start,
2193 highlight_lines,
2194 });
2195 }
2196
2197 (
2198 clones,
2199 groups_by_file,
2200 dup_lines_by_file,
2201 clamp_u32(truncated),
2202 )
2203}
2204
2205fn truncate_preview(fragment: &str) -> String {
2206 let mut out = String::new();
2207 for (i, line) in fragment.lines().enumerate() {
2208 if i >= CLONE_PREVIEW_MAX_LINES || out.len() + line.len() > CLONE_PREVIEW_MAX_BYTES {
2209 out.push('\u{2026}');
2210 break;
2211 }
2212 if i > 0 {
2213 out.push('\n');
2214 }
2215 out.push_str(line);
2216 }
2217 out
2218}
2219
2220fn build_clone_preview(inst: &CloneInstance) -> (String, u32, u32) {
2230 let Ok(source) = std::fs::read_to_string(&inst.file) else {
2231 return fragment_fallback(&inst.fragment);
2232 };
2233 let lines: Vec<&str> = source.lines().collect();
2234 let total = lines.len();
2235 if total == 0 || inst.start_line == 0 || inst.start_line > total {
2236 return fragment_fallback(&inst.fragment);
2237 }
2238
2239 let block_start = inst.start_line - 1;
2242 let block_end = inst.end_line.min(total).max(inst.start_line);
2243 let mut block_lines = block_end - block_start;
2244 let mut before = block_start.min(CLONE_PREVIEW_CONTEXT);
2245 let mut after = (total - block_end).min(CLONE_PREVIEW_CONTEXT);
2246
2247 if before + block_lines + after > CLONE_PREVIEW_MAX_LINES {
2252 if before + block_lines >= CLONE_PREVIEW_MAX_LINES {
2253 after = 0;
2254 block_lines = CLONE_PREVIEW_MAX_LINES.saturating_sub(before).max(1);
2255 } else {
2256 trim_context(
2257 &mut before,
2258 &mut after,
2259 CLONE_PREVIEW_MAX_LINES - block_lines,
2260 );
2261 }
2262 }
2263
2264 enforce_byte_cap(
2265 &lines,
2266 block_start,
2267 &mut before,
2268 &mut after,
2269 &mut block_lines,
2270 );
2271
2272 let win_start = block_start - before;
2273 let win_end = win_start + before + block_lines + after;
2274 let preview = lines[win_start..win_end].join("\n");
2275 (preview, clamp_u32(before), clamp_u32(block_lines))
2276}
2277
2278fn fragment_fallback(fragment: &str) -> (String, u32, u32) {
2281 let preview = truncate_preview(fragment);
2282 let highlight_lines = if preview.is_empty() {
2283 0
2284 } else {
2285 preview.lines().count()
2286 };
2287 (preview, 0, clamp_u32(highlight_lines))
2288}
2289
2290fn trim_context(before: &mut usize, after: &mut usize, budget: usize) {
2294 while *before + *after > budget {
2295 if *before >= *after {
2296 *before -= 1;
2297 } else {
2298 *after -= 1;
2299 }
2300 }
2301}
2302
2303fn enforce_byte_cap(
2308 lines: &[&str],
2309 block_start: usize,
2310 before: &mut usize,
2311 after: &mut usize,
2312 block_lines: &mut usize,
2313) {
2314 let window_bytes = |before: usize, after: usize, block_lines: usize| -> usize {
2315 let start = block_start - before;
2316 let end = start + before + block_lines + after;
2317 let separators = (end - start).saturating_sub(1);
2318 lines[start..end].iter().map(|l| l.len()).sum::<usize>() + separators
2319 };
2320 while window_bytes(*before, *after, *block_lines) > CLONE_PREVIEW_MAX_BYTES {
2321 if *before + *after > 0 {
2322 if *before >= *after {
2323 *before -= 1;
2324 } else {
2325 *after -= 1;
2326 }
2327 } else if *block_lines > 1 {
2328 *block_lines -= 1;
2329 } else {
2330 break;
2331 }
2332 }
2333}
2334
2335fn build_cycles(results: &AnalysisResults, index: &FileIndex<'_>) -> Vec<Vec<u32>> {
2336 results
2337 .circular_dependencies
2338 .iter()
2339 .filter_map(|cd| {
2340 let ids: Vec<u32> = cd
2341 .cycle
2342 .files
2343 .iter()
2344 .filter_map(|p| index.index_of_path(p))
2345 .collect();
2346 (ids.len() == cd.cycle.files.len()).then_some(ids)
2347 })
2348 .collect()
2349}
2350
2351fn build_violations(
2352 results: &AnalysisResults,
2353 zones: &[VizZone],
2354 index: &FileIndex<'_>,
2355) -> Vec<VizViolation> {
2356 let name_to_index: FxHashMap<&str, u16> = zones
2357 .iter()
2358 .enumerate()
2359 .map(|(i, z)| (z.name.as_str(), clamp_u16(i)))
2360 .collect();
2361
2362 results
2363 .boundary_violations
2364 .iter()
2365 .filter_map(|finding| {
2366 let v = &finding.violation;
2367 let from = index.index_of_path(&v.from_path)?;
2368 let to = index.index_of_path(&v.to_path)?;
2369 let from_zone = *name_to_index.get(v.from_zone.as_str())?;
2370 let to_zone = *name_to_index.get(v.to_zone.as_str())?;
2371 Some(VizViolation {
2372 from,
2373 to,
2374 from_zone,
2375 to_zone,
2376 line: v.line,
2377 specifier: v.import_specifier.clone(),
2378 })
2379 })
2380 .collect()
2381}
2382
2383fn build_edges(graph: &RetainedModuleGraph, index: &FileIndex<'_>) -> Vec<[u32; 3]> {
2384 let graph = graph.as_graph();
2385 let mut edges = Vec::with_capacity(graph.edge_count());
2386 for node in &graph.modules {
2387 let Some(source) = index.index_of_file_id(node.file_id.0) else {
2388 continue;
2389 };
2390 for (target_id, symbols) in graph.outgoing_symbol_edges(node.file_id) {
2391 let Some(target) = index.index_of_file_id(target_id.0) else {
2392 continue;
2393 };
2394 let all_type_only = !symbols.is_empty() && symbols.iter().all(|s| s.is_type_only);
2395 let flags = if all_type_only {
2396 EDGE_FLAG_TYPE_ONLY
2397 } else if symbols.iter().any(|s| s.is_eager_value()) {
2398 0
2399 } else {
2400 EDGE_FLAG_DYNAMIC
2401 };
2402 edges.push([source, target, flags]);
2403 }
2404 }
2405 edges
2406}
2407
2408#[derive(Default)]
2410struct ComplexityRollup {
2411 fn_count: u16,
2412 max_cyclomatic: u16,
2413 max_cognitive: u16,
2414 react_hooks: u16,
2415 jsx_depth: u16,
2416 functions: Vec<VizFunction>,
2417}
2418
2419fn rollup_complexity(functions: &[FunctionComplexity]) -> ComplexityRollup {
2420 let mut rollup = ComplexityRollup {
2421 fn_count: clamp_u16(functions.len()),
2422 ..ComplexityRollup::default()
2423 };
2424 for f in functions {
2425 rollup.max_cyclomatic = rollup.max_cyclomatic.max(f.cyclomatic);
2426 rollup.max_cognitive = rollup.max_cognitive.max(f.cognitive);
2427 rollup.react_hooks = rollup.react_hooks.saturating_add(f.react_hook_count);
2428 rollup.jsx_depth = rollup.jsx_depth.max(f.react_jsx_max_depth);
2429 }
2430
2431 let mut named: Vec<&FunctionComplexity> = functions
2436 .iter()
2437 .filter(|f| !f.name.starts_with('<'))
2438 .collect();
2439 named.sort_by(|a, b| {
2440 b.cyclomatic
2441 .cmp(&a.cyclomatic)
2442 .then(b.cognitive.cmp(&a.cognitive))
2443 });
2444 rollup.functions = named
2445 .into_iter()
2446 .map(|f| VizFunction {
2447 name: f.name.clone(),
2448 line: f.line,
2449 cyclomatic: f.cyclomatic,
2450 cognitive: f.cognitive,
2451 lines: f.line_count,
2452 hooks: f.react_hook_count,
2453 jsx_depth: f.react_jsx_max_depth,
2454 props: f.react_prop_count,
2455 })
2456 .collect();
2457 rollup
2458}
2459
2460fn build_files(
2461 input: &VizBuildInput<'_>,
2462 index: &FileIndex<'_>,
2463 maps: &FilePropertyMaps<'_>,
2464) -> Vec<VizFile> {
2465 let graph = input.graph.as_graph();
2466 let unused_file_paths: rustc_hash::FxHashSet<&Path> = input
2467 .results
2468 .unused_files
2469 .iter()
2470 .map(|f| f.file.path.as_path())
2471 .collect();
2472
2473 let mut unused_exports_by_file: FxHashMap<&Path, Vec<String>> = FxHashMap::default();
2474 for export in &input.results.unused_exports {
2475 unused_exports_by_file
2476 .entry(export.export.path.as_path())
2477 .or_default()
2478 .push(export.export.export_name.clone());
2479 }
2480 for export in &input.results.unused_types {
2481 unused_exports_by_file
2482 .entry(export.export.path.as_path())
2483 .or_default()
2484 .push(export.export.export_name.clone());
2485 }
2486
2487 let mut complexity_by_file_id: FxHashMap<u32, ComplexityRollup> = FxHashMap::default();
2488 if let Some(modules) = input.modules {
2489 for module in modules {
2490 if !module.complexity.is_empty() {
2491 complexity_by_file_id
2492 .insert(module.file_id.0, rollup_complexity(&module.complexity));
2493 }
2494 }
2495 }
2496
2497 let mut in_cycle = vec![false; index.ordered.len()];
2498 for cycle in maps.cycles {
2499 for &idx in cycle {
2500 if let Some(slot) = in_cycle.get_mut(idx as usize) {
2501 *slot = true;
2502 }
2503 }
2504 }
2505
2506 index
2507 .ordered
2508 .iter()
2509 .enumerate()
2510 .map(|(i, file)| {
2511 let viz_idx = clamp_u32(i);
2512 let node_idx = file.id.0 as usize;
2513 let node = graph.modules.get(node_idx);
2514 let is_entry = node.is_some_and(|n| n.is_entry_point());
2515 let export_count = node.map_or(0, |n| clamp_u16(n.exports.len()));
2516 let import_count = clamp_u16(graph.edges_for(file.id).len());
2517 let importer_count = clamp_u16(input.graph.direct_importer_count(file.id));
2518
2519 let unused_export_names = unused_exports_by_file
2520 .remove(file.path.as_path())
2521 .unwrap_or_default();
2522 let unused_export_count = clamp_u16(unused_export_names.len());
2523
2524 let status = if unused_file_paths.contains(file.path.as_path()) {
2525 VizFileStatus::Unused
2526 } else if unused_export_count > 0 {
2527 VizFileStatus::HasUnusedExports
2528 } else if is_entry {
2529 VizFileStatus::EntryPoint
2530 } else {
2531 VizFileStatus::Clean
2532 };
2533
2534 let complexity = complexity_by_file_id.remove(&file.id.0).unwrap_or_default();
2535
2536 VizFile {
2537 path: relative_path(&file.path, &input.config.root),
2538 size: file.size_bytes,
2539 status,
2540 export_count,
2541 unused_export_count,
2542 is_entry,
2543 importer_count,
2544 import_count,
2545 workspace: workspace_index_for(&file.path, input.workspaces),
2546 zone: maps.zone_by_file.get(&viz_idx).copied(),
2547 unused_exports: unused_export_names,
2548 fn_count: complexity.fn_count,
2549 max_cyclomatic: complexity.max_cyclomatic,
2550 max_cognitive: complexity.max_cognitive,
2551 react_hooks: complexity.react_hooks,
2552 jsx_depth: complexity.jsx_depth,
2553 functions: complexity.functions,
2554 dup_lines: maps.dup_lines_by_file.get(&viz_idx).copied().unwrap_or(0),
2555 clone_groups: maps
2556 .clone_groups_by_file
2557 .get(&viz_idx)
2558 .cloned()
2559 .unwrap_or_default(),
2560 in_cycle: in_cycle[i],
2561 }
2562 })
2563 .collect()
2564}
2565
2566fn build_summary(
2567 input: &VizBuildInput<'_>,
2568 files: &[VizFile],
2569 clones: &[VizCloneGroup],
2570 cycles: &[Vec<u32>],
2571 violations: &[VizViolation],
2572 clone_groups_truncated: u32,
2573) -> VizSummary {
2574 let results = input.results;
2575 VizSummary {
2576 total_files: files.len(),
2577 total_size: files.iter().map(|f| f.size).sum(),
2578 total_edges: input.graph.edge_count(),
2579 unused_files: results.unused_files.len(),
2580 unused_exports: results.unused_exports.len() + results.unused_types.len(),
2581 unused_types: results.unused_types.len(),
2582 unused_deps: results.unused_dependencies.len()
2583 + results.unused_dev_dependencies.len()
2584 + results.unused_optional_dependencies.len(),
2585 unresolved_imports: results.unresolved_imports.len(),
2586 circular_deps: cycles.len(),
2587 clone_groups: clones.len(),
2588 duplicated_lines: clones.iter().map(|c| c.lines * c.instances.len()).sum(),
2589 boundary_violations: violations.len(),
2590 hotspot_files: files
2591 .iter()
2592 .filter(|f| f.max_cyclomatic >= HOTSPOT_CYCLOMATIC_FLOOR)
2593 .count(),
2594 clone_groups_truncated: (clone_groups_truncated > 0).then_some(clone_groups_truncated),
2595 }
2596}
2597
2598fn clamp_u16(value: usize) -> u16 {
2599 u16::try_from(value).unwrap_or(u16::MAX)
2600}
2601
2602fn clamp_u32(value: usize) -> u32 {
2603 u32::try_from(value).unwrap_or(u32::MAX)
2604}
2605
2606#[cfg(test)]
2607mod tests {
2608 use std::path::PathBuf;
2609
2610 use fallow_config::{BoundaryConfig, BoundaryZone, FallowConfig};
2611 use fallow_graph::graph::ModuleGraph;
2612 use fallow_graph::resolve::{ResolveResult, ResolvedImport, ResolvedModule};
2613 use fallow_types::duplicates::{CloneGroup, CloneInstance};
2614 use fallow_types::extract::{ImportInfo, ImportedName};
2615 use fallow_types::output_dead_code::{BoundaryViolationFinding, CircularDependencyFinding};
2616 use fallow_types::output_format::OutputFormat;
2617 use fallow_types::results::{BoundaryViolation, CircularDependency};
2618
2619 use super::*;
2620 use crate::discover::{EntryPoint, EntryPointSource, FileId};
2621
2622 struct Fixture {
2624 config: ResolvedConfig,
2625 files: Vec<DiscoveredFile>,
2626 results: AnalysisResults,
2627 graph: crate::module_graph::RetainedModuleGraph,
2628 duplication: DuplicationReport,
2629 workspaces: Vec<WorkspaceInfo>,
2630 }
2631
2632 impl Fixture {
2633 fn input(&self) -> VizBuildInput<'_> {
2634 VizBuildInput {
2635 results: &self.results,
2636 graph: &self.graph,
2637 modules: None,
2638 files: &self.files,
2639 duplication: &self.duplication,
2640 workspaces: &self.workspaces,
2641 config: &self.config,
2642 feature_flags: &[],
2643 include_analysis_details: true,
2644 }
2645 }
2646 }
2647
2648 fn project_root() -> PathBuf {
2649 PathBuf::from("/viz-project")
2650 }
2651
2652 fn discovered(id: u32, path: PathBuf, size_bytes: u64) -> DiscoveredFile {
2653 DiscoveredFile {
2654 id: FileId(id),
2655 path,
2656 size_bytes,
2657 }
2658 }
2659
2660 fn import_of(target: FileId, specifier: &str) -> ResolvedImport {
2661 ResolvedImport {
2662 info: ImportInfo {
2663 source: specifier.to_owned(),
2664 imported_name: ImportedName::Named("value".to_owned()),
2665 local_name: "value".to_owned(),
2666 is_type_only: false,
2667 is_type_only_star: false,
2668 from_style: false,
2669 span: oxc_span::Span::new(0, 0),
2670 source_span: oxc_span::Span::new(0, 0),
2671 },
2672 target: ResolveResult::InternalModule(target),
2673 }
2674 }
2675
2676 fn zone(name: &str, pattern: &str) -> BoundaryZone {
2677 BoundaryZone {
2678 name: name.to_owned(),
2679 patterns: vec![pattern.to_owned()],
2680 auto_discover: Vec::new(),
2681 root: None,
2682 }
2683 }
2684
2685 fn resolved_config(root: &Path) -> ResolvedConfig {
2686 let config = FallowConfig {
2687 boundaries: BoundaryConfig {
2688 zones: vec![zone("app", "src/**"), zone("shared", "lib/**")],
2689 ..BoundaryConfig::default()
2690 },
2691 ..FallowConfig::default()
2692 };
2693 config.resolve(root.to_path_buf(), OutputFormat::Json, 1, false, true, None)
2694 }
2695
2696 fn cycle_finding(files: Vec<PathBuf>) -> CircularDependencyFinding {
2697 let length = files.len();
2698 CircularDependencyFinding::with_actions(CircularDependency {
2699 files,
2700 length,
2701 line: 1,
2702 col: 0,
2703 edges: Vec::new(),
2704 is_cross_package: false,
2705 })
2706 }
2707
2708 fn violation_finding(from_path: PathBuf, to_path: PathBuf) -> BoundaryViolationFinding {
2709 BoundaryViolationFinding::with_actions(BoundaryViolation {
2710 from_path,
2711 to_path,
2712 from_zone: "app".to_owned(),
2713 to_zone: "shared".to_owned(),
2714 import_specifier: "../lib/c".to_owned(),
2715 line: 2,
2716 col: 0,
2717 via_path: None,
2718 })
2719 }
2720
2721 fn clone_instance(file: PathBuf, start_line: usize, end_line: usize) -> CloneInstance {
2722 CloneInstance {
2723 file,
2724 start_line,
2725 end_line,
2726 start_col: 0,
2727 end_col: 0,
2728 fragment: "const shared = 1;\nconst repeated = 2;\nconst block = 3;".to_owned(),
2729 }
2730 }
2731
2732 fn clone_group(instances: Vec<CloneInstance>) -> CloneGroup {
2733 CloneGroup {
2734 instances,
2735 token_count: 12,
2736 line_count: 3,
2737 similarity: None,
2738 }
2739 }
2740
2741 fn fixture_with(extra_graph_file: bool) -> Fixture {
2746 let root = project_root();
2747 let a = root.join("src/a.ts");
2748 let b = root.join("src/b.ts");
2749 let c = root.join("lib/c.ts");
2750 let missing = root.join("src/missing.ts");
2751
2752 let files = vec![
2753 discovered(0, a.clone(), 100),
2754 discovered(1, b.clone(), 50),
2755 discovered(2, c.clone(), 25),
2756 ];
2757
2758 let mut graph_files = files.clone();
2759 let mut imports = vec![import_of(FileId(1), "./b")];
2760 if extra_graph_file {
2761 graph_files.push(discovered(3, root.join("src/d.ts"), 10));
2762 imports.push(import_of(FileId(3), "./d"));
2763 }
2764 let resolved = vec![ResolvedModule {
2765 file_id: FileId(0),
2766 path: a.clone(),
2767 resolved_imports: imports,
2768 ..ResolvedModule::default()
2769 }];
2770 let entry_points = vec![EntryPoint {
2771 path: a.clone(),
2772 source: EntryPointSource::PackageJsonMain,
2773 }];
2774 let graph = crate::module_graph::RetainedModuleGraph::from(ModuleGraph::build(
2775 &resolved,
2776 &entry_points,
2777 &graph_files,
2778 ));
2779
2780 let results = AnalysisResults {
2781 circular_dependencies: vec![
2782 cycle_finding(vec![a.clone(), b]),
2783 cycle_finding(vec![a.clone(), missing.clone()]),
2784 ],
2785 boundary_violations: vec![
2786 violation_finding(a.clone(), c.clone()),
2787 violation_finding(a.clone(), missing),
2788 ],
2789 ..AnalysisResults::default()
2790 };
2791
2792 let duplication = DuplicationReport {
2793 clone_groups: vec![
2794 clone_group(vec![
2795 clone_instance(a.clone(), 1, 3),
2796 clone_instance(c, 10, 12),
2797 ]),
2798 clone_group(vec![
2799 clone_instance(a.clone(), 20, 22),
2800 clone_instance(root.join("outside.ts"), 1, 3),
2801 ]),
2802 clone_group(vec![
2803 clone_instance(a.clone(), 30, 32),
2804 clone_instance(a, 40, 42),
2805 ]),
2806 ],
2807 ..DuplicationReport::default()
2808 };
2809
2810 let workspaces = vec![WorkspaceInfo {
2811 root: root.join("lib"),
2812 name: "shared-lib".to_owned(),
2813 is_internal_dependency: false,
2814 }];
2815
2816 Fixture {
2817 config: resolved_config(&root),
2818 files,
2819 results,
2820 graph,
2821 duplication,
2822 workspaces,
2823 }
2824 }
2825
2826 fn fixture() -> Fixture {
2827 fixture_with(false)
2828 }
2829
2830 #[test]
2831 fn files_and_edges_use_stable_indices() {
2832 let fx = fixture();
2833 let data = build_viz_data(&fx.input());
2834
2835 let paths: Vec<&str> = data.files.iter().map(|f| f.path.as_str()).collect();
2836 assert_eq!(paths, ["src/a.ts", "src/b.ts", "lib/c.ts"]);
2837 assert_eq!(data.edges, vec![[0, 1, 0]]);
2838 assert!(data.files[0].is_entry);
2839 assert!(matches!(data.files[0].status, VizFileStatus::EntryPoint));
2840 assert!(matches!(data.files[1].status, VizFileStatus::Clean));
2841 assert_eq!(data.files[0].import_count, 1);
2842 assert_eq!(data.files[1].importer_count, 1);
2843 assert_eq!(data.files[0].workspace, None);
2844 assert_eq!(data.files[2].workspace, Some(0));
2845 assert_eq!(data.workspaces.len(), 1);
2846 assert_eq!(data.workspaces[0].root, "lib");
2847 }
2848
2849 #[test]
2850 fn a_dynamic_import_edge_carries_the_dynamic_flag() {
2851 let root = project_root();
2852 let a = root.join("src/a.ts");
2853 let files = vec![
2854 discovered(0, a.clone(), 100),
2855 discovered(1, root.join("src/b.ts"), 50),
2856 discovered(2, root.join("src/c.ts"), 25),
2857 ];
2858 let resolved = vec![ResolvedModule {
2859 file_id: FileId(0),
2860 path: a.clone(),
2861 resolved_imports: vec![import_of(FileId(1), "./b")],
2862 resolved_dynamic_imports: vec![import_of(FileId(2), "./c")],
2863 ..ResolvedModule::default()
2864 }];
2865 let entry_points = vec![EntryPoint {
2866 path: a,
2867 source: EntryPointSource::PackageJsonMain,
2868 }];
2869 let fx = Fixture {
2870 graph: crate::module_graph::RetainedModuleGraph::from(ModuleGraph::build(
2871 &resolved,
2872 &entry_points,
2873 &files,
2874 )),
2875 files,
2876 ..fixture()
2877 };
2878 let data = build_viz_data(&fx.input());
2879
2880 assert_eq!(data.edges, vec![[0, 1, 0], [0, 2, EDGE_FLAG_DYNAMIC]]);
2881 }
2882
2883 #[test]
2884 fn edges_to_files_missing_from_input_are_dropped() {
2885 let fx = fixture_with(true);
2886 let data = build_viz_data(&fx.input());
2887
2888 assert_eq!(fx.graph.edge_count(), 2);
2892 assert_eq!(data.edges, vec![[0, 1, 0]]);
2893 }
2894
2895 #[test]
2896 fn clone_groups_drop_unresolvable_and_dedup_per_file() {
2897 let fx = fixture();
2898 let data = build_viz_data(&fx.input());
2899
2900 assert_eq!(data.clones.len(), 2);
2903 assert_eq!(data.clones[0].instances.len(), 2);
2904 assert_eq!(data.clones[0].instances[0].file, 0);
2905 assert_eq!(data.clones[0].instances[1].file, 2);
2906 assert_eq!(data.clones[0].lines, 3);
2907 assert_eq!(data.clones[0].tokens, 12);
2908 assert_eq!(data.files[0].clone_groups, vec![0, 1]);
2910 assert_eq!(data.files[2].clone_groups, vec![0]);
2911 assert_eq!(data.files[0].dup_lines, 9);
2913 assert_eq!(data.files[2].dup_lines, 3);
2914 assert_eq!(data.files[1].dup_lines, 0);
2915 }
2916
2917 #[test]
2918 fn truncate_preview_caps_lines_and_bytes() {
2919 let last_kept = CLONE_PREVIEW_MAX_LINES - 1;
2922 let many_lines = (0..CLONE_PREVIEW_MAX_LINES + 5)
2923 .map(|i| format!("line {i}"))
2924 .collect::<Vec<_>>();
2925 let out = truncate_preview(&many_lines.join("\n"));
2926 assert_eq!(out.matches('\n').count(), CLONE_PREVIEW_MAX_LINES - 1);
2927 assert!(out.contains(&format!("line {last_kept}")));
2928 assert!(!out.contains(&format!("line {CLONE_PREVIEW_MAX_LINES}")));
2929 assert!(out.ends_with('\u{2026}'));
2930
2931 let big = CLONE_PREVIEW_MAX_BYTES * 3 / 4;
2934 let two_long_lines = format!("{}\n{}", "a".repeat(big), "b".repeat(big));
2935 let out = truncate_preview(&two_long_lines);
2936 assert_eq!(out, format!("{}\u{2026}", "a".repeat(big)));
2937
2938 let emoji_line = "\u{1f389}".repeat(CLONE_PREVIEW_MAX_BYTES);
2941 let out = truncate_preview(&emoji_line);
2942 assert_eq!(out, "\u{2026}");
2943 }
2944
2945 #[test]
2946 fn clone_preview_windows_context_around_the_block() {
2947 use std::io::Write as _;
2948
2949 let mut file = tempfile::NamedTempFile::new().expect("temp file");
2951 let body = (1..=20)
2952 .map(|i| format!("line {i}"))
2953 .collect::<Vec<_>>()
2954 .join("\n");
2955 file.write_all(body.as_bytes()).expect("write source");
2956 let inst = clone_instance(file.path().to_path_buf(), 8, 11);
2957
2958 let (preview, highlight_start, highlight_lines) = build_clone_preview(&inst);
2959 let preview_lines: Vec<&str> = preview.lines().collect();
2960
2961 assert_eq!(preview_lines.len(), 12);
2964 assert_eq!(highlight_start, 4);
2965 assert_eq!(highlight_lines, 4);
2966 assert_eq!(preview_lines.first(), Some(&"line 4"));
2967 let start = highlight_start as usize;
2968 let end = start + highlight_lines as usize;
2969 assert_eq!(
2970 &preview_lines[start..end],
2971 ["line 8", "line 9", "line 10", "line 11"],
2972 );
2973 assert_eq!(preview_lines[start - 1], "line 7");
2975 }
2976
2977 #[test]
2978 fn clone_preview_keeps_leading_context_when_the_block_fills_the_cap() {
2979 use std::io::Write as _;
2980
2981 let mut file = tempfile::NamedTempFile::new().expect("temp file");
2985 let body = (1..=200)
2986 .map(|i| format!("line {i}"))
2987 .collect::<Vec<_>>()
2988 .join("\n");
2989 file.write_all(body.as_bytes()).expect("write source");
2990 let inst = clone_instance(file.path().to_path_buf(), 50, 150);
2991
2992 let (preview, highlight_start, highlight_lines) = build_clone_preview(&inst);
2993 let preview_lines: Vec<&str> = preview.lines().collect();
2994
2995 assert_eq!(highlight_start, CLONE_PREVIEW_CONTEXT as u32);
2996 assert!(
2997 highlight_start > 0,
2998 "leading context must survive a huge block"
2999 );
3000 assert_eq!(preview_lines.len(), CLONE_PREVIEW_MAX_LINES);
3001 assert_eq!(
3002 highlight_lines as usize,
3003 CLONE_PREVIEW_MAX_LINES - CLONE_PREVIEW_CONTEXT,
3004 );
3005 assert_eq!(preview_lines[highlight_start as usize - 1], "line 49");
3006 assert_eq!(preview_lines[highlight_start as usize], "line 50");
3007 }
3008
3009 #[test]
3010 fn clone_preview_clamps_context_at_file_start() {
3011 use std::io::Write as _;
3012
3013 let mut file = tempfile::NamedTempFile::new().expect("temp file");
3014 file.write_all(b"line 1\nline 2\nline 3\nline 4\nline 5")
3015 .expect("write source");
3016 let inst = clone_instance(file.path().to_path_buf(), 1, 2);
3019
3020 let (preview, highlight_start, highlight_lines) = build_clone_preview(&inst);
3021 assert_eq!(highlight_start, 0);
3022 assert_eq!(highlight_lines, 2);
3023 assert_eq!(preview, "line 1\nline 2\nline 3\nline 4\nline 5");
3024 }
3025
3026 #[test]
3027 fn clone_preview_falls_back_when_source_is_unreadable() {
3028 let inst = clone_instance(project_root().join("does-not-exist.ts"), 1, 3);
3031 let (preview, highlight_start, highlight_lines) = build_clone_preview(&inst);
3032 assert_eq!(preview, inst.fragment);
3033 assert_eq!(highlight_start, 0);
3034 assert_eq!(highlight_lines as usize, preview.lines().count());
3035 }
3036
3037 #[test]
3038 fn cycles_drop_when_any_member_unresolved() {
3039 let fx = fixture();
3040 let data = build_viz_data(&fx.input());
3041
3042 assert_eq!(data.cycles, vec![vec![0, 1]]);
3045 assert!(data.files[0].in_cycle);
3046 assert!(data.files[1].in_cycle);
3047 assert!(!data.files[2].in_cycle);
3048 assert_eq!(data.summary.circular_deps, data.cycles.len());
3051 }
3052
3053 #[test]
3054 fn violations_resolve_zone_and_file_indices() {
3055 let fx = fixture();
3056 let data = build_viz_data(&fx.input());
3057
3058 assert_eq!(data.zones.len(), 2);
3059 assert_eq!(data.zones[0].name, "app");
3060 assert_eq!(data.zones[0].files, 2);
3061 assert_eq!(data.zones[1].name, "shared");
3062 assert_eq!(data.zones[1].files, 1);
3063 assert_eq!(data.files[0].zone, Some(0));
3064 assert_eq!(data.files[1].zone, Some(0));
3065 assert_eq!(data.files[2].zone, Some(1));
3066
3067 assert_eq!(data.violations.len(), 1);
3069 let v = &data.violations[0];
3070 assert_eq!((v.from, v.to), (0, 2));
3071 assert_eq!((v.from_zone, v.to_zone), (0, 1));
3072 assert_eq!(v.line, 2);
3073 assert_eq!(v.specifier, "../lib/c");
3074 }
3075
3076 #[test]
3077 fn clone_group_cap_counts_truncated_groups() {
3078 let fx = fixture();
3079 let index = FileIndex::new(&fx.files);
3080
3081 let (clones, groups_by_file, _dup_lines, truncated) =
3086 build_clones(&fx.duplication, &index, 1);
3087 assert_eq!(clones.len(), 1);
3088 assert_eq!(truncated, 1);
3089 assert!(
3090 groups_by_file
3091 .values()
3092 .all(|ids| ids.iter().all(|&id| (id as usize) < clones.len()))
3093 );
3094
3095 let data = build_viz_data(&fx.input());
3097 assert_eq!(data.clones.len(), 2);
3098 assert_eq!(data.summary.clone_groups_truncated, None);
3099 }
3100
3101 #[test]
3102 fn summary_flags_clone_truncation_only_when_nonzero() {
3103 let fx = fixture();
3104 let data = build_viz_data(&fx.input());
3105
3106 let summary = build_summary(&fx.input(), &data.files, &data.clones, &[], &[], 3);
3107 assert_eq!(summary.clone_groups_truncated, Some(3));
3108 let summary = build_summary(&fx.input(), &data.files, &data.clones, &[], &[], 0);
3109 assert_eq!(summary.clone_groups_truncated, None);
3110 }
3111
3112 #[test]
3113 fn summary_counts_match_rendered_arrays() {
3114 let fx = fixture();
3115 let data = build_viz_data(&fx.input());
3116 let s = &data.summary;
3117
3118 assert_eq!(s.total_files, data.files.len());
3119 assert_eq!(s.total_size, 175);
3120 assert_eq!(s.total_edges, data.edges.len());
3121 assert_eq!(s.clone_groups, data.clones.len());
3122 assert_eq!(s.duplicated_lines, 12);
3123 assert_eq!(s.hotspot_files, 0);
3124 assert_eq!(s.unused_files, 0);
3125 assert_eq!(s.unused_exports, 0);
3126 assert_eq!(s.circular_deps, data.cycles.len());
3129 assert_eq!(s.circular_deps, 1);
3130 assert_eq!(s.boundary_violations, data.violations.len());
3131 assert_eq!(s.boundary_violations, 1);
3132 }
3133
3134 #[test]
3135 fn payload_keeps_counts_and_availability_explicit() {
3136 let fx = fixture();
3137 let data = build_viz_data(&fx.input());
3138 let value = serde_json::to_value(&data).expect("viz data serializes");
3139
3140 assert_eq!(value["architecture"]["availability"]["unit"], "violations");
3141 assert_eq!(value["dependencies"]["availability"]["unit"], "findings");
3142 assert_eq!(value["security"]["availability"]["unit"], "candidates");
3143 assert_eq!(value["security"]["availability"]["state"], "complete");
3144 assert_eq!(
3145 value["security"]["runtime_availability"]["state"],
3146 "unavailable"
3147 );
3148 assert_eq!(value["health"]["availability"]["state"], "unavailable");
3149 assert_eq!(
3150 value["health"]["capabilities"]["coverage"]["state"],
3151 "unavailable"
3152 );
3153 assert!(value["frameworks"]["detectors"].is_array());
3154 assert_eq!(
3155 value["frameworks"]["detector_availability"]["state"],
3156 "unavailable"
3157 );
3158 assert!(value["styling"].get("score").is_none());
3159 }
3160
3161 #[test]
3165 fn health_reports_runtime_evidence_as_unavailable_without_a_runtime_input() {
3166 let fx = fixture();
3167 let mut data = build_viz_data(&fx.input());
3168 apply_health_report(&mut data, &HealthReport::default(), Path::new("/project"));
3169 let value = serde_json::to_value(&data).expect("viz data serializes");
3170
3171 assert_eq!(value["health"]["availability"]["state"], "complete");
3172 let runtime = &value["health"]["capabilities"]["runtime"];
3173 assert_eq!(runtime["state"], "unavailable");
3174 assert_eq!(runtime["unit"], "observations");
3175 assert_eq!(runtime["reason"], NO_RUNTIME_COVERAGE_REASON);
3176 assert_eq!(runtime["count"], 0);
3177 assert_eq!(
3178 value["security"]["runtime_availability"]["reason"],
3179 NO_RUNTIME_COVERAGE_REASON
3180 );
3181 }
3182
3183 #[test]
3187 fn rooted_paths_without_a_drive_are_redacted() {
3188 let root = Path::new("/project");
3189 assert_eq!(
3190 relative_path(Path::new("/Users/private/secret.ts"), root),
3191 "<external>/secret.ts"
3192 );
3193 assert_eq!(
3194 relative_path(Path::new("/etc/passwd"), root),
3195 "<external>/passwd"
3196 );
3197 assert_eq!(relative_path(Path::new("src/a.ts"), root), "src/a.ts");
3199
3200 let mut detail = serde_json::json!({ "path": "/Users/private/secret.ts" });
3202 relativize_value_paths(&mut detail, root);
3203 assert_eq!(detail["path"], "<external>/secret.ts");
3204
3205 let mut route = serde_json::json!({ "specifier": "/api/v1" });
3208 relativize_value_paths(&mut route, root);
3209 assert_eq!(route["specifier"], "/api/v1");
3210 }
3211
3212 #[test]
3213 fn external_absolute_paths_are_redacted() {
3214 let root = Path::new("/project");
3215 assert_eq!(
3216 relative_path(Path::new("/project/src/a.ts"), root),
3217 "src/a.ts"
3218 );
3219 assert_eq!(
3220 relative_path(Path::new("/Users/private/secret.ts"), root),
3221 "<external>/secret.ts"
3222 );
3223
3224 let mut detail = serde_json::json!({ "path": "/Users/private/secret.ts" });
3225 relativize_value_paths(&mut detail, root);
3226 assert_eq!(detail["path"], "<external>/secret.ts");
3227
3228 let mut route = serde_json::json!({ "specifier": "/api/v1" });
3229 relativize_value_paths(&mut route, root);
3230 assert_eq!(route["specifier"], "/api/v1");
3231
3232 let mut conflicts = serde_json::json!({
3233 "conflicting_paths": ["/project/app/a.ts", "/project/app/b.ts"]
3234 });
3235 relativize_value_paths(&mut conflicts, root);
3236 assert_eq!(conflicts["conflicting_paths"][0], "app/a.ts");
3237 assert_eq!(conflicts["conflicting_paths"][1], "app/b.ts");
3238 }
3239
3240 #[test]
3241 fn config_action_values_are_not_rendered_as_commands() {
3242 let finding = finding_from_value(
3243 "dependency",
3244 "Dependency finding",
3245 serde_json::json!({
3246 "actions": [{
3247 "kind": "add-to-config",
3248 "auto_fixable": false,
3249 "config_key": "entry",
3250 "value": "./errors",
3251 "description": "Add the entry to configuration"
3252 }]
3253 }),
3254 Path::new("/project"),
3255 &|_| None,
3256 );
3257 assert_eq!(finding.actions.len(), 1);
3258 let action = &finding.actions[0];
3259 assert_eq!(action.kind.as_deref(), Some("add-to-config"));
3260 assert!(!action.auto_fixable);
3261 assert_eq!(action.config_key.as_deref(), Some("entry"));
3262 assert_eq!(action.value, Some(Value::String("./errors".to_string())));
3263 assert!(action.command.is_none());
3264 }
3265}