Skip to main content

provenant/utils/
sourcemap.rs

1// SPDX-FileCopyrightText: nexB Inc. and others
2// SPDX-FileCopyrightText: Provenant contributors
3// SPDX-License-Identifier: Apache-2.0
4// Derived from ScanCode Toolkit (Apache-2.0); modified. See NOTICE.
5
6//! Source map file processing for scanner text detection.
7//!
8//! Source map files (.js.map, .css.map) are JSON files containing embedded
9//! source code in a `sourcesContent` array. This module extracts that content
10//! so the scanner can detect licenses and parties from the embedded sources
11//! instead of from the raw source map JSON wrapper.
12
13use std::borrow::Cow;
14use std::path::Path;
15
16/// Check if a file is a source map file based on extension.
17pub fn is_sourcemap(path: &Path) -> bool {
18    path.file_name()
19        .and_then(|name| name.to_str())
20        .map(|name| {
21            let name_lower = name.to_lowercase();
22            name_lower.ends_with(".js.map") || name_lower.ends_with(".css.map")
23        })
24        .unwrap_or(false)
25}
26
27/// Extract source content from a source map JSON file.
28///
29/// Parses the JSON and extracts all entries from `sourcesContent`,
30/// combining them with newlines for license detection.
31///
32/// Returns `Some(combined_text)` if successfully parsed with content.
33/// Returns `None` if JSON parsing fails or no sourcesContent exists.
34pub fn extract_sourcemap_content(json_text: &str) -> Option<String> {
35    let json: serde_json::Value = serde_json::from_str(json_text).ok()?;
36    let sources = json.get("sourcesContent")?.as_array()?;
37
38    let combined: String = sources
39        .iter()
40        .filter_map(|v| v.as_str())
41        .map(replace_verbatim_cr_lf_chars)
42        .collect::<Vec<_>>()
43        .join("\n");
44
45    if combined.is_empty() {
46        None
47    } else {
48        Some(combined)
49    }
50}
51
52/// Return the text scanners should inspect for this file.
53pub fn detection_text<'a>(path: &Path, text: &'a str) -> Cow<'a, str> {
54    if !is_sourcemap(path) {
55        return Cow::Borrowed(text);
56    }
57
58    extract_sourcemap_content(text)
59        .map(Cow::Owned)
60        .unwrap_or_else(|| Cow::Borrowed(text))
61}
62
63/// Replace verbatim escaped CR/LF characters with actual newlines.
64///
65/// This matches Python's `replace_verbatim_cr_lf_chars()` behavior exactly:
66/// - Double-escaped (e.g., source had literal `\r` that was escaped again):
67///   - `\\r\\n` (backslash-backslash-r-backslash-backslash-n) → newline
68///   - `\\r` (backslash-backslash-r) → newline
69///   - `\\n` (backslash-backslash-n) → newline
70/// - Single-escaped (e.g., JSON-escaped newlines):
71///   - `\r\n` (backslash-r-backslash-n) → newline
72///   - `\r` (backslash-r) → newline
73///   - `\n` (backslash-n) → newline
74fn replace_verbatim_cr_lf_chars(s: &str) -> String {
75    s.replace("\\\\r\\\\n", "\n")
76        .replace("\\r\\n", "\n")
77        .replace("\\\\r", "\n")
78        .replace("\\\\n", "\n")
79        .replace("\\r", "\n")
80        .replace("\\n", "\n")
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86    use std::path::PathBuf;
87
88    #[test]
89    fn test_is_sourcemap_js_map() {
90        assert!(is_sourcemap(&PathBuf::from("app.js.map")));
91        assert!(is_sourcemap(&PathBuf::from("APP.JS.MAP")));
92    }
93
94    #[test]
95    fn test_is_sourcemap_css_map() {
96        assert!(is_sourcemap(&PathBuf::from("style.css.map")));
97        assert!(is_sourcemap(&PathBuf::from("STYLE.CSS.MAP")));
98    }
99
100    #[test]
101    fn test_is_sourcemap_not_map() {
102        assert!(!is_sourcemap(&PathBuf::from("app.js")));
103        assert!(!is_sourcemap(&PathBuf::from("data.json")));
104        assert!(!is_sourcemap(&PathBuf::from("other.map")));
105    }
106
107    #[test]
108    fn test_extract_sourcemap_content_basic() {
109        let json = r#"{"version":3,"sourcesContent":["hello\nworld"]}"#;
110        let result = extract_sourcemap_content(json);
111        assert!(result.is_some());
112        let content = result.unwrap();
113        assert!(content.contains("hello"));
114        assert!(content.contains("world"));
115    }
116
117    #[test]
118    fn test_extract_sourcemap_content_mit_license() {
119        let json = r#"{"version":3,"sourcesContent":["Use of this source code is governed by an MIT-style license\nthat can be found in the LICENSE file"]}"#;
120        let result = extract_sourcemap_content(json);
121        assert!(result.is_some());
122        let content = result.unwrap();
123        assert!(content.contains("MIT-style license"));
124        assert!(content.contains("LICENSE file"));
125        assert!(content.contains("\n"));
126    }
127
128    #[test]
129    fn test_extract_sourcemap_content_multiple_entries() {
130        let json = r#"{"version":3,"sourcesContent":["first\nfile","second\nfile"]}"#;
131        let result = extract_sourcemap_content(json);
132        assert!(result.is_some());
133        let content = result.unwrap();
134        assert!(content.contains("first"));
135        assert!(content.contains("second"));
136    }
137
138    #[test]
139    fn test_extract_sourcemap_content_no_sources() {
140        let json = r#"{"version":3,"sources":[]}"#;
141        let result = extract_sourcemap_content(json);
142        assert!(result.is_none());
143    }
144
145    #[test]
146    fn test_extract_sourcemap_content_invalid_json() {
147        let json = r#"not valid json"#;
148        let result = extract_sourcemap_content(json);
149        assert!(result.is_none());
150    }
151
152    #[test]
153    fn test_extract_sourcemap_content_null_entries() {
154        let json = r#"{"version":3,"sourcesContent":[null,"actual\ncontent"]}"#;
155        let result = extract_sourcemap_content(json);
156        assert!(result.is_some());
157        let content = result.unwrap();
158        assert!(content.contains("actual"));
159    }
160
161    #[test]
162    fn test_detection_text_prefers_embedded_sources_for_sourcemaps() {
163        let path = PathBuf::from("bundle.js.map");
164        let raw = r#"{"version":3,"comment":"Copyright 1999 Wrong Corp.","sourcesContent":["/* Copyright 2024 Example Corp. */\n"]}"#;
165
166        let result = detection_text(&path, raw);
167
168        assert_eq!(result.as_ref(), "/* Copyright 2024 Example Corp. */\n");
169    }
170
171    #[test]
172    fn test_replace_verbatim_cr_lf_chars() {
173        // Single-escaped (backslash-n, backslash-r in the string)
174        assert_eq!(replace_verbatim_cr_lf_chars("a\\nb"), "a\nb");
175        assert_eq!(replace_verbatim_cr_lf_chars("a\\rb"), "a\nb");
176        assert_eq!(replace_verbatim_cr_lf_chars("a\\r\\nb"), "a\nb");
177        // Double-escaped (literal backslash-backslash-n in the string)
178        assert_eq!(replace_verbatim_cr_lf_chars("a\\\\nb"), "a\nb");
179        assert_eq!(replace_verbatim_cr_lf_chars("a\\\\rb"), "a\nb");
180        assert_eq!(replace_verbatim_cr_lf_chars("a\\\\r\\\\nb"), "a\nb");
181    }
182
183    #[test]
184    fn test_ar_er_js_map_detection() {
185        let path = PathBuf::from("testdata/license-golden/datadriven/lic2/ar-ER.js.map");
186        if !path.exists() {
187            eprintln!("Skipping test: test file not found");
188            return;
189        }
190
191        let text = std::fs::read_to_string(&path).expect("Failed to read file");
192        eprintln!("Raw text length: {}", text.len());
193
194        let json: serde_json::Value = serde_json::from_str(&text).expect("JSON parse failed");
195        let sources = json
196            .get("sourcesContent")
197            .expect("No sourcesContent")
198            .as_array()
199            .expect("Not array");
200        eprintln!("Sources array length: {}", sources.len());
201
202        if let Some(first) = sources.first().and_then(|v| v.as_str()) {
203            eprintln!("First source length: {}", first.len());
204            eprintln!("First 100 chars: {:?}", &first[..100.min(first.len())]);
205        }
206
207        let result = extract_sourcemap_content(&text);
208        assert!(result.is_some(), "Should extract content from ar-ER.js.map");
209
210        let content = result.unwrap();
211        eprintln!("Extracted content length: {}", content.len());
212        assert!(
213            content.contains("MIT-style license"),
214            "Should contain MIT license text"
215        );
216    }
217}