Skip to content

Commit

Permalink
feat: concat sourcemap (#423)
Browse files Browse the repository at this point in the history
  • Loading branch information
underfin authored Feb 21, 2024
1 parent 5e7491e commit f10dac8
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 13 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ The Rolldown project are standing upon the shoulders of these giants:

- [rollup](https://github.com/rollup/rollup), created by [Rich-Harris](https://github.com/Rich-Harris) and maintained by [lukastaegert](https://github.com/lukastaegert).
- [esbuild](https://github.com/evanw/esbuild), created by [evanw](https://github.com/evanw).
- [parcel_sourcemap](https://github.com/parcel-bundler/source-map).

# Licenses

Expand Down
82 changes: 82 additions & 0 deletions crates/rolldown_sourcemap/src/concat_sourcemap.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
use parcel_sourcemap::SourceMap as ParcelSourcemap;

use crate::SourceMap;

pub fn concat_sourcemaps(
content_and_sourcemaps: &[(String, Option<&SourceMap>)],
) -> Result<(String, SourceMap), String> {
let mut s = String::new();
let mut map = ParcelSourcemap::new("");
let mut line_offset = 0;

for (index, (content, sourcemap)) in content_and_sourcemaps.iter().enumerate() {
s.push_str(content);
if index != content_and_sourcemaps.len() - 1 {
s.push('\n');
}

if let Some(sourcemap) = sourcemap {
map
.add_sourcemap(
&mut sourcemap.get_inner().cloned().ok_or("concat sourcemap not inner sourcemap")?,
line_offset.into(),
)
.map_err(|e| e.to_string())?;
}
line_offset += u32::try_from(content.lines().count() + 1).map_err(|e| e.to_string())?;
}

Ok((s, map.into()))
}

#[cfg(test)]
mod tests {
use parcel_sourcemap::SourceMap;
use serde_json;
#[test]
fn concat_sourcemaps_works() {
let map = SourceMap::from_json(
"",
r#"{
"version":3,
"sourceRoot":"",
"mappings":"AAAA,SAAS,QAAQ,CAAC,IAAY;IAC5B,OAAO,CAAC,GAAG,CAAC,iBAAU,IAAI,CAAE,CAAC,CAAC;AAChC,CAAC",
"sources":["index.ts"],
"sourcesContent":["function sayHello(name: string) {\n console.log(`Hello, ${name}`);\n}\n"],
"names":[]
}"#,
)
.unwrap().into();
let content_and_sourcemaps = vec![
("\nconsole.log()".to_string(), None),
(
"function sayHello(name: string) {\n console.log(`Hello, ${name}`);\n}\n".to_string(),
Some(&map),
),
];

let (content, mut map) =
super::concat_sourcemaps(&content_and_sourcemaps).expect("should not fail");

assert_eq!(
content,
"\nconsole.log()\nfunction sayHello(name: string) {\n console.log(`Hello, ${name}`);\n}\n"
);
let expected = r#"{
"version": 3,
"sources": [
"index.ts"
],
"sourceRoot": null,
"sourcesContent": [
"function sayHello(name: string) {\n console.log(`Hello, ${name}`);\n}\n"
],
"names": [],
"mappings": ";;;AAAA,SAAS,QAAQ,CAAC,IAAY;IAC5B,OAAO,CAAC,GAAG,CAAC,iBAAU,IAAI,CAAE,CAAC,CAAC;AAChC,CAAC"
}"#;
assert_eq!(
map.to_json().as_str().parse::<serde_json::Value>().unwrap(),
expected.parse::<serde_json::Value>().unwrap()
);
}
}
30 changes: 17 additions & 13 deletions crates/rolldown_sourcemap/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use parcel_sourcemap::SourceMap as ParcelSourcemap;
mod concat_sourcemap;

pub use concat_sourcemap::concat_sourcemaps;
#[derive(Debug, Default, Clone)]
pub struct SourceMap {
pub mappings: String,
Expand Down Expand Up @@ -28,6 +30,10 @@ impl SourceMap {
pub fn to_data_url(&mut self) -> String {
self.inner.as_mut().expect("should have inner").to_data_url(None).expect("should success")
}

pub fn get_inner(&self) -> Option<&ParcelSourcemap> {
self.inner.as_ref()
}
}

impl From<ParcelSourcemap> for SourceMap {
Expand All @@ -41,16 +47,16 @@ pub fn collapse_sourcemaps(sourcemap_chain: Vec<SourceMap>) -> Result<Option<Sou
.into_iter()
.map(|sourcemap| {
let mut map = ParcelSourcemap::new(sourcemap.source_root.as_deref().unwrap_or(""));
if let Err(e) = map.add_vlq_map(
sourcemap.mappings.as_bytes(),
sourcemap.sources,
sourcemap.sources_content,
sourcemap.names,
0,
0,
) {
return Err(format!("{e}"));
}
map
.add_vlq_map(
sourcemap.mappings.as_bytes(),
sourcemap.sources,
sourcemap.sources_content,
sourcemap.names,
0,
0,
)
.map_err(|e| e.to_string())?;
Ok(map)
})
.rev()
Expand All @@ -59,9 +65,7 @@ pub fn collapse_sourcemaps(sourcemap_chain: Vec<SourceMap>) -> Result<Option<Sou
let Some(mut result) = parcel_sourcemap_chain.pop() else { return Ok(None) };

for mut sourcemap in parcel_sourcemap_chain.into_iter().rev() {
if let Err(e) = sourcemap.extends(&mut result) {
return Err(format!("{e}"));
};
sourcemap.extends(&mut result).map_err(|e| e.to_string())?;
result = sourcemap;
}

Expand Down

0 comments on commit f10dac8

Please sign in to comment.