logcompact_builtins/diagnostics/javascript/
node.rs1use std::collections::BTreeSet;
2
3use crate::{Diagnostic, DiagnosticClass, Location, Severity};
4
5use super::super::common::normalize_path;
6
7pub(crate) fn reduce(
8 input: &str,
9 diagnostics: &mut Vec<Diagnostic>,
10 messages: &mut BTreeSet<String>,
11) {
12 let mut parser = JavaScriptTestDiagnosticParser::default();
13 for line in input.lines() {
14 if let Some(diagnostic) = parser.observe_line(line) {
15 messages.insert(diagnostic.message.clone());
16 diagnostics.push(diagnostic);
17 }
18 }
19 if let Some(diagnostic) = parser.finish() {
20 messages.insert(diagnostic.message.clone());
21 diagnostics.push(diagnostic);
22 }
23}
24
25#[derive(Debug, Default)]
27pub struct JavaScriptTestDiagnosticParser {
28 leading_location: Option<Location>,
29 pending: Option<Diagnostic>,
30 frames_seen: usize,
31}
32
33impl JavaScriptTestDiagnosticParser {
34 const MAX_STACK_FRAMES: usize = 64;
35
36 pub fn observe_line(&mut self, line: &str) -> Option<Diagnostic> {
39 if !line.trim_start().starts_with("at ")
40 && let Some(location) = parse_location(line.trim())
41 {
42 let previous = self.take_confirmed();
43 self.leading_location = Some(location);
44 return previous;
45 }
46 if let Some(message) = exception_message(line) {
47 let leading_location = self.leading_location.take();
48 let previous = self.take_confirmed();
49 self.pending = Some(Diagnostic {
50 severity: Severity::Error,
51 class: DiagnosticClass::Test,
52 code: None,
53 provenance: None,
54 message: message.to_owned(),
55 location: leading_location,
56 quality: crate::EvidenceQuality::Structured,
57 repetition_count: 1,
58 });
59 self.frames_seen = 0;
60 return previous;
61 }
62 self.pending.as_ref()?;
63 if let Some(location) = parse_stack_frame(line) {
64 self.frames_seen = self.frames_seen.saturating_add(1);
65 if let Some(location) = location {
66 let mut diagnostic = self.pending.take()?;
67 diagnostic.location = Some(location);
68 self.frames_seen = 0;
69 return Some(diagnostic);
70 }
71 if self.frames_seen >= Self::MAX_STACK_FRAMES {
72 return self.take_confirmed();
73 }
74 return None;
75 }
76 if line.trim().is_empty() {
77 return None;
78 }
79 self.take_confirmed()
80 }
81
82 pub fn finish(&mut self) -> Option<Diagnostic> {
84 self.take_confirmed()
85 }
86
87 fn take_confirmed(&mut self) -> Option<Diagnostic> {
88 let confirmed = self
89 .pending
90 .as_ref()
91 .is_some_and(|diagnostic| diagnostic.location.is_some())
92 || self.frames_seen > 0;
93 self.frames_seen = 0;
94 self.leading_location = None;
95 if confirmed {
96 self.pending.take()
97 } else {
98 self.pending = None;
99 None
100 }
101 }
102}
103
104pub(crate) fn exception_message(line: &str) -> Option<&str> {
105 let line = line.trim();
106 let exception_type = line.split_once(':').map_or(line, |(name, _)| name);
107 let class_name = exception_type.split_whitespace().next()?;
108 (!class_name.is_empty()
109 && class_name
110 .bytes()
111 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'$'))
112 && (class_name.ends_with("Error") || class_name.ends_with("Exception")))
113 .then_some(line)
114}
115
116fn parse_stack_frame(line: &str) -> Option<Option<Location>> {
117 let frame = line.trim().strip_prefix("at ")?;
118 let source = if let Some((_, source)) = frame.rsplit_once('(') {
119 source.strip_suffix(')')?
120 } else {
121 frame.split_whitespace().last()?
122 };
123 if source.starts_with("node:") || matches!(source, "native" | "<anonymous>") {
124 return Some(None);
125 }
126 let location = parse_location(source)?;
127 let framework = location.path.contains("/node_modules/")
128 || location.path.starts_with("node_modules/")
129 || location.path.contains("/external/");
130 Some((!framework).then_some(location))
131}
132
133fn parse_location(value: &str) -> Option<Location> {
134 let value = value.trim().trim_matches('"');
135 let path_end = path_end(value)?;
136 let coordinates = value[path_end..].strip_prefix(':')?;
137 let (line_number, column) = if let Some((line_number, column)) = coordinates.split_once(':') {
138 (
139 line_number.parse::<u32>().ok()?,
140 Some(column.parse::<u32>().ok()?),
141 )
142 } else {
143 (coordinates.parse::<u32>().ok()?, None)
144 };
145 Some(Location {
146 path: compact_path(&value[..path_end]),
147 line: Some(line_number),
148 column,
149 end_line: None,
150 end_column: None,
151 })
152}
153
154fn path_end(value: &str) -> Option<usize> {
155 const EXTENSIONS: [&str; 8] = [".tsx", ".mts", ".cts", ".ts", ".jsx", ".mjs", ".cjs", ".js"];
156 EXTENSIONS
157 .iter()
158 .filter_map(|extension| {
159 value.rmatch_indices(extension).find_map(|(index, _)| {
160 let path_end = index + extension.len();
161 value[path_end..].starts_with(':').then_some(path_end)
162 })
163 })
164 .max()
165}
166
167pub(crate) fn compact_path(path: &str) -> String {
168 let path = path
169 .trim_matches('"')
170 .strip_prefix("file://")
171 .unwrap_or(path)
172 .to_owned();
173 normalize_path(&path)
174}