Skip to main content

fallow_engine/health/coverage_v8/
source_map_cache.rs

1//! The `source-map-cache` of a V8 coverage dump: its entries, and the rules
2//! that turn a source of a map into a file path. The health coverage reader
3//! and the runtime-coverage remapper of the CLI both use these rules.
4
5use std::path::{Path, PathBuf};
6
7use fallow_types::path_util::{is_absolute_path_any_platform, looks_like_windows_absolute_path};
8use rustc_hash::FxHashMap;
9use serde::Deserialize;
10use url::Url;
11
12/// One `source-map-cache` entry of a V8 dump.
13#[derive(Debug, Clone, Deserialize)]
14pub struct SourceMapCacheEntry {
15    /// The URL of an external map. Node writes `null` when it loaded the map.
16    #[serde(default)]
17    pub url: Option<String>,
18    /// The source map as JSON.
19    pub data: serde_json::Value,
20    /// UTF-16 length of each line of the generated code.
21    #[serde(default, rename = "lineLengths")]
22    pub line_lengths: Vec<u32>,
23}
24
25/// Decodes each entry of a `source-map-cache` object on its own, keyed by
26/// script URL. An entry that does not decode is left out, so one bad entry
27/// does not remove the other maps. A value that is not an object gives an
28/// empty map.
29pub fn parse_source_map_cache(raw: &serde_json::Value) -> FxHashMap<String, SourceMapCacheEntry> {
30    let Some(entries) = raw.as_object() else {
31        return FxHashMap::default();
32    };
33    entries
34        .iter()
35        .filter_map(|(url, entry)| {
36            Some((url.clone(), SourceMapCacheEntry::deserialize(entry).ok()?))
37        })
38        .collect()
39}
40
41/// The path of a `file://` URL or of an absolute path. `None` for each other
42/// URL and for a relative path.
43pub fn file_url_to_path(value: &str) -> Option<PathBuf> {
44    if let Ok(url) = Url::parse(value) {
45        return if url.scheme() == "file" {
46            url.to_file_path().ok()
47        } else {
48            None
49        };
50    }
51    let path = PathBuf::from(value);
52    (is_absolute_path_any_platform(&path) || looks_like_windows_absolute_path(value))
53        .then_some(path)
54}
55
56/// The directory that relative and virtual sources resolve from: the
57/// directory of the external map when the entry names one, else the
58/// directory of the generated script. `None` when the script is not a local
59/// file or the map is remote.
60pub fn source_map_base_dir(generated_url: &str, source_map_url: Option<&str>) -> Option<PathBuf> {
61    let generated_path = file_url_to_path(generated_url)?;
62    let generated_dir = generated_path.parent()?.to_path_buf();
63    let Some(source_map_url) = source_map_url.filter(|url| !url.is_empty()) else {
64        return Some(generated_dir);
65    };
66    if let Some(path) = file_url_to_path(source_map_url) {
67        return path.parent().map(Path::to_path_buf);
68    }
69    let candidate = PathBuf::from(source_map_url);
70    if is_absolute_path_any_platform(&candidate) || looks_like_windows_absolute_path(source_map_url)
71    {
72        return candidate.parent().map(Path::to_path_buf);
73    }
74    if Url::parse(source_map_url).is_ok() {
75        return None;
76    }
77    generated_dir
78        .join(candidate)
79        .parent()
80        .map(Path::to_path_buf)
81}
82
83/// The file path of one source of a map. A `file://` URL and an absolute
84/// path resolve without a base directory. A relative path joins the base
85/// directory. A `webpack://` or `vite://` source resolves to the first
86/// existing file in the base directory or one of its ancestors. Each other
87/// URL gives `None`.
88pub fn resolve_original_source(raw_source: &str, base_dir: Option<&Path>) -> Option<PathBuf> {
89    if raw_source.is_empty() {
90        return None;
91    }
92    if let Some(path) = file_url_to_path(raw_source) {
93        return Some(path);
94    }
95    let source_path = PathBuf::from(raw_source);
96    // `C:/repo/a.ts` also parses as a URL with the scheme `c`.
97    if is_absolute_path_any_platform(&source_path) || looks_like_windows_absolute_path(raw_source) {
98        return Some(source_path);
99    }
100    if let Ok(url) = Url::parse(raw_source) {
101        return match url.scheme() {
102            "webpack" | "vite" => {
103                resolve_virtual_candidate(&virtual_source_candidates(&url), base_dir?)
104            }
105            _ => None,
106        };
107    }
108    Some(base_dir?.join(source_path))
109}
110
111/// The relative paths that a virtual source can name, in lookup order: the
112/// namespace plus the path, then the path alone. The decoded form of the
113/// path comes first. The raw form follows, for a file name that holds a
114/// literal `%XX`.
115fn virtual_source_candidates(url: &Url) -> Vec<PathBuf> {
116    let raw = url.path().trim_start_matches('/');
117    let namespace = url
118        .host_str()
119        .map(|host| host.trim_matches('/'))
120        .filter(|host| !host.is_empty() && !matches!(*host, "." | "_N_E"));
121    let decoded = decoded_virtual_path(raw);
122    let mut candidates = Vec::new();
123    for path in [decoded.as_deref(), Some(raw)].into_iter().flatten() {
124        if let Some(namespace) = namespace {
125            push_candidate(&mut candidates, PathBuf::from(namespace).join(path));
126        }
127        push_candidate(&mut candidates, PathBuf::from(path));
128    }
129    candidates
130}
131
132fn push_candidate(candidates: &mut Vec<PathBuf>, candidate: PathBuf) {
133    if !candidate.as_os_str().is_empty() && !candidates.contains(&candidate) {
134        candidates.push(candidate);
135    }
136}
137
138/// The path of a virtual source with its `%XX` escapes decoded. `None` when
139/// a decoded segment is not UTF-8 or holds a path separator, so an escape
140/// cannot name a file outside its segment.
141fn decoded_virtual_path(path: &str) -> Option<String> {
142    let segments = path
143        .split('/')
144        .map(|segment| {
145            let decoded = percent_encoding::percent_decode_str(segment)
146                .decode_utf8()
147                .ok()?;
148            (!decoded.contains(['/', '\\'])).then(|| decoded.into_owned())
149        })
150        .collect::<Option<Vec<String>>>()?;
151    Some(segments.join("/"))
152}
153
154fn resolve_virtual_candidate(candidates: &[PathBuf], base_dir: &Path) -> Option<PathBuf> {
155    for base in base_dir.ancestors() {
156        for candidate in candidates {
157            let resolved = base.join(candidate);
158            if resolved.is_file() {
159                return Some(resolved);
160            }
161        }
162    }
163    None
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    fn file_url(path: &Path) -> String {
171        Url::from_file_path(path).unwrap().to_string()
172    }
173
174    fn resolve(source: &str, generated: &str, map_url: Option<&str>) -> Option<PathBuf> {
175        resolve_original_source(source, source_map_base_dir(generated, map_url).as_deref())
176    }
177
178    /// A tempdir with an empty `dist` directory and each file of `files`.
179    fn project(files: &[&str]) -> tempfile::TempDir {
180        let dir = tempfile::tempdir().unwrap();
181        std::fs::create_dir_all(dir.path().join("dist")).unwrap();
182        for file in files {
183            let path = dir.path().join(file);
184            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
185            std::fs::write(path, "export const a = 1;\n").unwrap();
186        }
187        dir
188    }
189
190    fn resolve_virtual(dir: &tempfile::TempDir, source: &str) -> Option<PathBuf> {
191        resolve_original_source(source, Some(&dir.path().join("dist")))
192    }
193
194    #[test]
195    fn preserves_windows_absolute_source_map_sources() {
196        let generated = "file:///C:/repo/dist/bundle.js";
197        assert_eq!(
198            resolve("C:/repo/src/app.ts", generated, Some("bundle.js.map")),
199            Some(PathBuf::from("C:/repo/src/app.ts"))
200        );
201        assert_eq!(
202            resolve(r"C:\repo\src\app.ts", generated, Some("bundle.js.map")),
203            Some(PathBuf::from(r"C:\repo\src\app.ts"))
204        );
205    }
206
207    #[test]
208    fn file_url_to_path_accepts_file_urls_and_absolute_paths_only() {
209        let dir = tempfile::tempdir().unwrap();
210        let path = dir.path().join("app.js");
211        assert_eq!(file_url_to_path(&file_url(&path)), Some(path));
212        assert_eq!(file_url_to_path("https://example.com/app.js"), None);
213        assert_eq!(file_url_to_path("relative/app.js"), None);
214    }
215
216    #[test]
217    fn resolve_source_map_base_handles_inline_relative_and_remote_urls() {
218        let dir = tempfile::tempdir().unwrap();
219        let generated = file_url(&dir.path().join("app.js"));
220        assert_eq!(
221            source_map_base_dir(&generated, None),
222            Some(dir.path().to_path_buf())
223        );
224        assert_eq!(
225            source_map_base_dir(&generated, Some("app.js.map")),
226            Some(dir.path().to_path_buf())
227        );
228        assert_eq!(
229            source_map_base_dir(&generated, Some("https://cdn.example.com/app.js.map")),
230            None
231        );
232    }
233
234    #[test]
235    fn resolve_original_source_path_handles_file_absolute_and_relative_sources() {
236        let dir = tempfile::tempdir().unwrap();
237        let source = dir.path().join("src/app.ts");
238        let generated = file_url(&dir.path().join("dist/app.js"));
239        assert_eq!(resolve("", &generated, None), None);
240        assert_eq!(
241            resolve(&file_url(&source), &generated, None),
242            Some(source.clone())
243        );
244        assert_eq!(
245            resolve(source.to_str().unwrap(), &generated, None),
246            Some(source)
247        );
248        assert_eq!(
249            resolve("src/app.ts", &generated, None),
250            Some(dir.path().join("dist/src/app.ts"))
251        );
252    }
253
254    #[test]
255    fn resolve_original_source_path_resolves_virtual_sources_from_ancestors() {
256        let dir = project(&["src/app.ts"]);
257        let generated = file_url(&dir.path().join("dist/chunks/app.js"));
258        assert_eq!(
259            resolve("webpack://app/src/app.ts", &generated, None),
260            Some(dir.path().join("src/app.ts"))
261        );
262    }
263
264    #[test]
265    fn virtual_source_candidates_strip_known_pseudo_hosts() {
266        let url = Url::parse("webpack://_N_E/./src/app.ts").unwrap();
267        let candidates = virtual_source_candidates(&url);
268        // The `_N_E` pseudo-host is dropped and the url crate normalizes the
269        // `/.` segment, leaving the path-only candidate.
270        assert!(
271            candidates.contains(&PathBuf::from("src/app.ts")),
272            "got: {candidates:?}"
273        );
274        assert!(!candidates.iter().any(|c| c.starts_with("_N_E")));
275    }
276
277    #[test]
278    fn resolve_virtual_source_path_ignores_non_virtual_schemes() {
279        let dir = tempfile::tempdir().unwrap();
280        assert_eq!(
281            resolve_original_source("https://example.com/app.ts", Some(dir.path())),
282            None
283        );
284    }
285
286    #[test]
287    fn parse_keeps_good_entries_beside_a_bad_one() {
288        let raw = serde_json::json!({
289            "file:///good.js": { "data": { "version": 3 }, "lineLengths": [1] },
290            "file:///string.js": "oops",
291            "file:///lengths.js": { "data": {}, "lineLengths": "x" },
292        });
293        let cache = parse_source_map_cache(&raw);
294        let keys: Vec<&String> = cache.keys().collect();
295        assert_eq!(keys, vec!["file:///good.js"]);
296        assert!(parse_source_map_cache(&serde_json::json!("not a cache object")).is_empty());
297    }
298
299    #[test]
300    fn entry_without_line_lengths_or_url_decodes() {
301        let bare: SourceMapCacheEntry =
302            serde_json::from_value(serde_json::json!({ "data": { "version": 3 } })).unwrap();
303        assert!(bare.line_lengths.is_empty());
304        assert_eq!(bare.url, None);
305        let full: SourceMapCacheEntry = serde_json::from_value(
306            serde_json::json!({ "url": null, "data": {}, "lineLengths": [1] }),
307        )
308        .unwrap();
309        assert_eq!(full.line_lengths, vec![1]);
310    }
311
312    #[test]
313    fn base_dir_follows_an_external_map_in_another_directory() {
314        let dir = tempfile::tempdir().unwrap();
315        let generated = file_url(&dir.path().join("dist/app.js"));
316        let base = source_map_base_dir(&generated, Some("../maps/app.js.map"));
317        let expected = dir.path().join("dist").join("../maps");
318        assert_eq!(base.as_deref(), Some(expected.as_path()));
319        assert_eq!(
320            resolve_original_source("../src/a.ts", base.as_deref()),
321            Some(expected.join("../src/a.ts"))
322        );
323    }
324
325    #[test]
326    fn virtual_source_with_an_escaped_space_resolves() {
327        let dir = project(&["src dir/my file.ts"]);
328        assert_eq!(
329            resolve_virtual(&dir, "webpack://app/src%20dir/my%20file.ts"),
330            Some(dir.path().join("src dir/my file.ts"))
331        );
332    }
333
334    #[test]
335    fn virtual_source_with_a_plain_space_resolves() {
336        let dir = project(&["src dir/my file.ts"]);
337        assert_eq!(
338            resolve_virtual(&dir, "webpack://app/./src dir/my file.ts"),
339            Some(dir.path().join("src dir/my file.ts"))
340        );
341    }
342
343    #[test]
344    fn virtual_source_with_a_literal_percent_resolves() {
345        let dir = project(&["src/100%.ts", "src/a%20b.ts"]);
346        for file in ["src/100%.ts", "src/a%20b.ts"] {
347            assert_eq!(
348                resolve_virtual(&dir, &format!("webpack://app/{file}")),
349                Some(dir.path().join(file))
350            );
351        }
352    }
353
354    #[test]
355    fn virtual_source_with_an_escaped_separator_is_not_resolved() {
356        let dir = project(&["src/a.ts"]);
357        assert_eq!(resolve_virtual(&dir, "webpack://app/src%2Fa.ts"), None);
358    }
359}