Skip to content

feat: support source root #83

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 29 additions & 4 deletions src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,15 @@ pub fn stream_chunks_of_source_map(
}
}

fn get_source(source_map: &SourceMap, source: &str) -> String {
let source_root = source_map.source_root();
match source_root {
Some(root) if root.ends_with('/') => format!("{}{}", root, source),
Some(root) => format!("{}/{}", root, source),
None => source.to_string(),
}
}

fn stream_chunks_of_source_map_final(
source: &str,
source_map: &SourceMap,
Expand All @@ -607,7 +616,11 @@ fn stream_chunks_of_source_map_final(
return result;
}
for (i, source) in source_map.sources().iter().enumerate() {
on_source(i as u32, source, source_map.get_source_content(i))
on_source(
i as u32,
&get_source(source_map, source),
source_map.get_source_content(i),
)
}
for (i, name) in source_map.names().iter().enumerate() {
on_name(i as u32, name);
Expand Down Expand Up @@ -665,7 +678,11 @@ fn stream_chunks_of_source_map_full(
};
}
for (i, source) in source_map.sources().iter().enumerate() {
on_source(i as u32, source, source_map.get_source_content(i))
on_source(
i as u32,
&get_source(source_map, source),
source_map.get_source_content(i),
)
}
for (i, name) in source_map.names().iter().enumerate() {
on_name(i as u32, name);
Expand Down Expand Up @@ -807,7 +824,11 @@ fn stream_chunks_of_source_map_lines_final(
};
}
for (i, source) in source_map.sources().iter().enumerate() {
on_source(i as u32, source, source_map.get_source_content(i))
on_source(
i as u32,
&get_source(source_map, source),
source_map.get_source_content(i),
)
}
let final_line = if result.generated_column == 0 {
result.generated_line - 1
Expand Down Expand Up @@ -858,7 +879,11 @@ fn stream_chunks_of_source_map_lines_full(
};
}
for (i, source) in source_map.sources().iter().enumerate() {
on_source(i as u32, source, source_map.get_source_content(i))
on_source(
i as u32,
&get_source(source_map, source),
source_map.get_source_content(i),
)
}
let mut current_generated_line = 1;
let mut on_mapping = |mapping: &Mapping| {
Expand Down
50 changes: 22 additions & 28 deletions src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ pub struct SourceMap {
sources: Vec<Cow<'static, str>>,
sources_content: Vec<Cow<'static, str>>,
names: Vec<Cow<'static, str>>,
source_root: Option<String>,
}

impl SourceMap {
Expand All @@ -195,6 +196,7 @@ impl SourceMap {
sources,
sources_content,
names,
source_root: None,
}
}

Expand Down Expand Up @@ -286,6 +288,16 @@ impl SourceMap {
) -> Option<&mut Cow<'static, str>> {
self.names.get_mut(index)
}

/// Get the source_root field in [SourceMap].
pub fn source_root(&self) -> Option<&str> {
self.source_root.as_deref()
}

/// Set the source_root field in [SourceMap].
pub fn set_source_root(&mut self, source_root: Option<String>) {
self.source_root = source_root;
}
}

#[derive(Debug, Default, Serialize, Deserialize)]
Expand Down Expand Up @@ -364,32 +376,13 @@ impl TryFrom<RawSourceMap> for SourceMap {
type Error = crate::Error;

fn try_from(raw: RawSourceMap) -> Result<Self> {
let sources = raw.sources.unwrap_or_default();
let sources = match raw.source_root {
Some(ref source_root) if !source_root.is_empty() => {
let source_root = source_root.trim_end_matches('/');
sources
.into_iter()
.map(|x| {
let x = x.unwrap_or_default();
let is_valid = !x.is_empty()
&& (x.starts_with('/')
|| x.starts_with("http:")
|| x.starts_with("https:"));
if is_valid {
x
} else {
format!("{source_root}/{x}").into()
}
})
.collect()
}
_ => sources
.into_iter()
.map(Option::unwrap_or_default)
.map(Cow::from)
.collect(),
};
let sources = raw
.sources
.unwrap_or_default()
.into_iter()
.map(Option::unwrap_or_default)
.map(Cow::from)
.collect();
let sources_content = raw
.sources_content
.unwrap_or_default()
Expand All @@ -410,6 +403,7 @@ impl TryFrom<RawSourceMap> for SourceMap {
sources,
sources_content,
names,
source_root: raw.source_root,
})
}
}
Expand All @@ -430,7 +424,7 @@ impl From<SourceMap> for RawSourceMap {
.map(|s| (!s.is_empty()).then_some(s))
.collect(),
),
source_root: None,
source_root: map.source_root,
sources_content: sources_content
.clone()
.any(|s| s.is_some())
Expand Down Expand Up @@ -547,7 +541,7 @@ mod tests {
RawSource::from("g").boxed().hash(&mut state);
(&RawSource::from("h") as &dyn Source).hash(&mut state);
ReplaceSource::new(RawSource::from("i").boxed()).hash(&mut state);
assert_eq!(format!("{:x}", state.finish()), "fb814b430ddd31e0");
assert_eq!(format!("{:x}", state.finish()), "8163b42b7cb1d8f0");
}

#[test]
Expand Down
54 changes: 53 additions & 1 deletion src/source_map_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ mod tests {

let mut hasher = twox_hash::XxHash64::default();
sms1.hash(&mut hasher);
assert_eq!(format!("{:x}", hasher.finish()), "60180dd058e3cdd7");
assert_eq!(format!("{:x}", hasher.finish()), "d136621583d4618c");
}

#[test]
Expand Down Expand Up @@ -578,4 +578,56 @@ mod tests {
let map = source.map(&MapOptions::new(false)).unwrap();
assert_eq!(map.mappings(), ";;;AAAA");
}

#[test]
fn source_root_is_correctly_applied_to_mappings() {
let inner_source_code = "Hello World\nis a test string\n";
let inner_source = ConcatSource::new([
OriginalSource::new(inner_source_code, "hello-world.txt").boxed(),
OriginalSource::new("Translate: ", "header.txt").boxed(),
RawSource::from("Other text").boxed(),
]);
let source_r_code =
"Translated: Hallo Welt\nist ein test Text\nAnderer Text";
let source_r_map = SourceMap::from_json(
r#"{
"version": 3,
"sources": [ "text" ],
"names": [ "Hello", "World", "nope" ],
"mappings": "YAAAA,K,CAAMC;AACNC,O,MAAU;AACC,O,CAAM",
"file": "translated.txt",
"sourcesContent": [ "Hello World\nis a test string\n" ]
}"#,
)
.unwrap();
let inner_source_map =
inner_source.map(&MapOptions::default()).map(|mut map| {
map.set_source_root(Some("/path/to/folder/".to_string()));
map
});
let sms = SourceMapSource::new(SourceMapSourceOptions {
value: source_r_code,
name: "text",
source_map: source_r_map.clone(),
original_source: Some(inner_source.source().to_string()),
inner_source_map,
remove_original_source: false,
});
assert_eq!(
sms.map(&MapOptions::default()).unwrap(),
SourceMap::from_json(
r#"{
"mappings": "YAAAA,K,CAAMC;AACN,O,MAAU;ACCC,O,CAAM",
"names": ["Hello", "World"],
"sources": ["/path/to/folder/hello-world.txt", "text"],
"sourcesContent": [
"Hello World\nis a test string\n",
"Hello World\nis a test string\nTranslate: Other text"
],
"version": 3
}"#
)
.unwrap(),
);
}
}