Skip to main content

rust_css_parser/printer/
sourcemap.rs

1//! Port of `src/printer/sourcemap.ts`: generate and parse source maps.
2
3use super::lib::codec::{decode, encode};
4use crate::parser::utils::base64::to_base64;
5use crate::plain::{Plain, PlainObject};
6use base64::Engine;
7use crate::utils::fx::{HashMap, HashSet};
8use std::rc::Rc;
9
10/// `SourceMapObject`
11#[derive(Clone, Debug, Default, PartialEq)]
12pub struct SourceMapObject {
13    pub version: u32,
14    pub file: Option<String>,
15    pub source_root: Option<String>,
16    pub sources: Vec<Option<Rc<str>>>,
17    pub sources_content: Vec<Option<Rc<str>>>,
18    pub names: Option<Vec<String>>,
19    pub mappings: String,
20}
21
22impl SourceMapObject {
23    /// plain object (`toJSON()`): version, sources, sourcesContent, mappings
24    pub fn to_plain(&self) -> Plain {
25        let mut o = PlainObject::new();
26        o.set("version", self.version);
27        o.set("sources", Plain::Array(self.sources.iter().map(|s| Plain::from(s.clone())).collect()));
28        o.set("sourcesContent", Plain::Array(self.sources_content.iter().map(|s| Plain::from(s.clone())).collect()));
29        o.set("mappings", self.mappings.as_str());
30        Plain::Object(o)
31    }
32
33    pub fn to_json(&self) -> String {
34        self.to_plain().to_json()
35    }
36
37    pub fn from_json(value: &serde_json::Value) -> Self {
38        let strings = |key: &str| -> Vec<Option<Rc<str>>> {
39            value[key].as_array().map(|a| a.iter().map(|s| s.as_str().map(Rc::from)).collect()).unwrap_or_default()
40        };
41        SourceMapObject {
42            version: value["version"].as_u64().unwrap_or(3) as u32,
43            file: value["file"].as_str().map(String::from),
44            source_root: value["sourceRoot"].as_str().map(String::from),
45            sources: strings("sources"),
46            sources_content: strings("sourcesContent"),
47            names: value["names"].as_array().map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect()),
48            mappings: value["mappings"].as_str().unwrap_or("").to_string(),
49        }
50    }
51}
52
53/// a line of the map: segments, in insertion order
54type Line = Vec<Vec<i64>>;
55
56/// map keyed by line, iterated in insertion order (javascript `Map`)
57#[derive(Clone, Debug, Default)]
58struct LineMapOrdered {
59    order: Vec<i64>,
60    lines: HashMap<i64, Line>,
61}
62
63impl LineMapOrdered {
64    fn set(&mut self, line: i64, value: Line) {
65        if !self.lines.contains_key(&line) {
66            self.order.push(line);
67        }
68        self.lines.insert(line, value);
69    }
70
71    fn get(&self, line: i64) -> Option<&Line> {
72        self.lines.get(&line)
73    }
74
75    fn get_mut(&mut self, line: i64) -> Option<&mut Line> {
76        self.lines.get_mut(&line)
77    }
78
79    fn clear(&mut self) {
80        self.order.clear();
81        self.lines.clear();
82    }
83
84    fn is_empty(&self) -> bool {
85        self.lines.is_empty()
86    }
87}
88
89/// a source map: `[file, line, column, content]` lookups, json / data url output
90#[derive(Clone, Debug)]
91pub struct SourceMap {
92    keys: HashSet<(i64, i64, i64, i64, i64)>,
93    last_location: Option<(i64, i64)>,
94    version: u32,
95    sources_map: Vec<i64>,
96    sources_content: Vec<Option<Rc<str>>>,
97    sources: Vec<Option<Rc<str>>>,
98    map: LineMapOrdered,
99    reverse_map: LineMapOrdered,
100    line: i64,
101}
102
103impl Default for SourceMap {
104    fn default() -> Self {
105        Self::new()
106    }
107}
108
109/// `decodeURIComponent()`
110fn decode_uri_component(s: &str) -> String {
111    let bytes = s.as_bytes();
112    let mut out = Vec::with_capacity(bytes.len());
113    let mut i = 0;
114    while i < bytes.len() {
115        if bytes[i] == b'%' && i + 2 < bytes.len() {
116            if let Ok(b) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
117                out.push(b);
118                i += 3;
119                continue;
120            }
121        }
122        out.push(bytes[i]);
123        i += 1;
124    }
125    String::from_utf8_lossy(&out).into_owned()
126}
127
128impl SourceMap {
129    pub fn new() -> Self {
130        Self {
131            keys: HashSet::default(),
132            last_location: None,
133            version: 3,
134            sources_map: Vec::new(),
135            sources_content: Vec::new(),
136            sources: Vec::new(),
137            map: LineMapOrdered::default(),
138            reverse_map: LineMapOrdered::default(),
139            line: -1,
140        }
141    }
142
143    /// parse a source map: json, or a `data:` url (base64 or url encoded)
144    pub fn parse(source: &str) -> Result<Self, String> {
145        let mut text = source.to_string();
146        if source.starts_with("data:") {
147            let mut encoding = "";
148            let mut offset = source.find(',').map_or(0, |i| i + 1);
149            if offset == 0 {
150                offset = source.rfind(';').map_or(0, |i| i + 1);
151            } else {
152                let start = source.rfind(';').map_or(0, |i| i + 1);
153                encoding = if start <= offset - 1 { &source[start..offset - 1] } else { "" };
154            }
155            text = if encoding == "base64" {
156                let decoded = base64::engine::general_purpose::STANDARD.decode(source[offset..].trim()).map_err(|e| e.to_string())?;
157                // atob() returns latin1 characters
158                decoded.iter().map(|&b| b as char).collect()
159            } else {
160                decode_uri_component(&source[offset..])
161            };
162        }
163        let value: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
164        Ok(Self::from_object(&SourceMapObject::from_json(&value)))
165    }
166
167    /// a source map from a source map object
168    pub fn from_object(object: &SourceMapObject) -> Self {
169        let mut map = Self::new();
170        map.sources = object.sources.clone();
171        map.sources_content = object.sources_content.clone();
172        let decoded: Vec<Line> = object.mappings.split(';').map(|line| line.split(',').map(decode).collect()).collect();
173        map.line = decoded.len() as i64 - 1;
174        for (index, line) in decoded.into_iter().enumerate() {
175            if line.is_empty() || (line.len() == 1 && line[0].is_empty()) {
176                continue;
177            }
178            map.map.set(index as i64, line);
179        }
180        map.compute_positions();
181        map
182    }
183
184    /// add a source
185    pub fn add_source_content(&mut self, id: i64, file_name: Option<&str>, content: Option<&str>) {
186        if self.sources_map.contains(&id) {
187            return;
188        }
189        self.sources_map.push(id);
190        self.sources.push(file_name.filter(|f| !f.is_empty()).map(Rc::from));
191        self.sources_content.push(content.filter(|c| !c.is_empty()).map(Rc::from));
192    }
193
194    /// add mappings `[newLine, newColumn, srcId, ln, col]`
195    pub fn add(&mut self, maps: &[[i64; 5]]) -> Result<(), String> {
196        for &[new_line, new_column, src_id, ln, col] in maps {
197            let key = (src_id, ln, col, new_line, new_column);
198            if !self.keys.insert(key) {
199                continue;
200            }
201            let line = new_line - 1;
202            if line > self.line {
203                self.line = line;
204            }
205            let src_index = self
206                .sources_map
207                .iter()
208                .position(|&s| s == src_id)
209                .ok_or_else(|| format!("Source file {} not added to sourcemap", src_id))? as i64;
210            let mut record: Vec<i64> = if let Some(arr) = self.map.get(line) {
211                vec![0.max(new_column - 1) - arr[0][0], src_index - arr[0][1], ln - 1, col - 1]
212            } else {
213                vec![0.max(new_column - 1), src_index, ln - 1, col - 1]
214            };
215            if let Some((last_ln, last_col)) = self.last_location {
216                record[2] -= last_ln - 1;
217                record[3] -= last_col - 1;
218            }
219            if let Some(arr) = self.map.get_mut(line) {
220                arr.push(record);
221            } else {
222                self.map.set(line, vec![record]);
223            }
224            self.last_location = Some((ln, col));
225        }
226        Ok(())
227    }
228
229    /// compute the original positions
230    pub fn compute_positions(&mut self) {
231        self.reverse_map.clear();
232        let mut source_code_line: i64 = 0;
233        let mut source_code_column: i64 = 0;
234        for &i in &self.map.order {
235            let line = &self.map.lines[&i];
236            if line.is_empty() || (line.len() == 1 && line[0].is_empty()) {
237                continue;
238            }
239            let first: Vec<i64> = line[0].clone();
240            let mut mapped: Line = line
241                .iter()
242                .enumerate()
243                .map(|(index, segment)| {
244                    if segment.is_empty() {
245                        return Vec::new();
246                    }
247                    let generated = if index == 0 { segment[0] } else { segment[0] + first[0] };
248                    let mut result = vec![generated];
249                    if segment.len() <= 1 {
250                        return result;
251                    }
252                    let source_file_index = if index == 0 { segment[1] } else { segment[1] + first[1] };
253                    source_code_line += segment.get(2).copied().unwrap_or(0);
254                    source_code_column += segment.get(3).copied().unwrap_or(0);
255                    result.extend([source_file_index, source_code_line, source_code_column]);
256                    result
257                })
258                .collect();
259            mapped.sort_by(|a, b| {
260                let (a1, b1) = (a.get(1), b.get(1));
261                match (a1, b1) {
262                    (Some(x), Some(y)) if x != y => x.cmp(y),
263                    (Some(_), Some(_)) => a[0].cmp(&b[0]),
264                    _ => std::cmp::Ordering::Equal,
265                }
266            });
267            if mapped.is_empty() || (mapped.len() == 1 && mapped[0].is_empty()) {
268                continue;
269            }
270            self.reverse_map.set(i, mapped);
271        }
272    }
273
274    /// original sources, lines and columns of a position: `[source, line, column, content]`
275    pub fn find(&mut self, line: i64, column: i64) -> Option<Vec<(Option<Rc<str>>, i64, i64, Option<Rc<str>>)>> {
276        if self.reverse_map.is_empty() {
277            self.compute_positions();
278        }
279        let line = line - 1;
280        let records = self.reverse_map.get(line)?;
281        let column = column - 1;
282        let mut result = Vec::new();
283        for record in records {
284            if record.is_empty() || record[0] < column {
285                continue;
286            }
287            if record[0] > column {
288                break;
289            }
290            let index = record.get(1).copied().unwrap_or(0) as usize;
291            result.push((
292                self.sources.get(index).cloned().flatten(),
293                record.get(2).copied().unwrap_or(0) + 1,
294                record.get(3).copied().unwrap_or(0) + 1,
295                self.sources_content.get(index).cloned().flatten(),
296            ));
297        }
298        if result.is_empty() {
299            None
300        } else {
301            Some(result)
302        }
303    }
304
305    /// data url
306    pub fn to_url(&self) -> String {
307        format!("data:application/json;charset=utf-8;base64,{}", to_base64(&self.to_json().to_json()))
308    }
309
310    /// source map object
311    pub fn to_json(&self) -> SourceMapObject {
312        let mut mappings: Vec<String> = Vec::new();
313        for i in 0..=self.line.max(-1) {
314            if i < 0 {
315                break;
316            }
317            mappings.push(match self.map.get(i) {
318                None => String::new(),
319                Some(line) => line.iter().map(|segment| encode(segment)).collect::<Vec<_>>().join(","),
320            });
321        }
322        SourceMapObject {
323            version: self.version,
324            sources: self.sources.clone(),
325            sources_content: self.sources_content.clone(),
326            mappings: mappings.join(";"),
327            ..Default::default()
328        }
329    }
330}