Skip to content

Commit bfce02c

Browse files
committed
Support charset in decode_data_url
1 parent e293721 commit bfce02c

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

src/decoder.rs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@ use crate::jsontypes::RawSourceMap;
1212
use crate::types::{DecodedMap, RawToken, SourceMap, SourceMapIndex, SourceMapSection};
1313
use crate::vlq::parse_vlq_segment_into;
1414

15-
const DATA_PREAMBLE: &str = "data:application/json;base64,";
16-
1715
#[derive(PartialEq, Eq)]
1816
enum HeaderState {
1917
Undecided,
@@ -339,12 +337,22 @@ pub fn decode_slice(slice: &[u8]) -> Result<DecodedMap> {
339337
decode_common(rsm)
340338
}
341339

342-
/// Loads a sourcemap from a data URL
340+
/// Loads a sourcemap from a data URL.
341+
///
342+
/// The URL should match the regex
343+
/// `data:application/json;(charset=utf-?8;)?base64,(?<base64sourcemap>.+)`.
343344
pub fn decode_data_url(url: &str) -> Result<DecodedMap> {
344-
if !url.starts_with(DATA_PREAMBLE) {
345-
return Err(Error::InvalidDataUrl);
346-
}
347-
let data_b64 = &url[DATA_PREAMBLE.len()..];
345+
let rest = url
346+
.strip_prefix("data:application/json")
347+
.ok_or(Error::InvalidDataUrl)?;
348+
let rest = match rest.strip_prefix(";charset=") {
349+
Some(rest) => rest
350+
.strip_prefix("utf-8")
351+
.or_else(|| rest.strip_prefix("utf8"))
352+
.ok_or(Error::InvalidDataUrl)?,
353+
None => rest,
354+
};
355+
let data_b64 = rest.strip_prefix(";base64,").ok_or(Error::InvalidDataUrl)?;
348356
let data = data_encoding::BASE64
349357
.decode(data_b64.as_bytes())
350358
.map_err(|_| Error::InvalidDataUrl)?;

tests/test_decoder.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ fn test_sourcemap_data_url() {
120120
eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImNvb2xzdHVmZi5qcyJdLCJzb3VyY2VSb290I\
121121
joieCIsIm5hbWVzIjpbIngiLCJhbGVydCJdLCJtYXBwaW5ncyI6IkFBQUEsR0FBSUEsR0\
122122
FBSSxFQUNSLElBQUlBLEdBQUssRUFBRyxDQUNWQyxNQUFNIn0=";
123-
match decode_data_url(url).unwrap() {
123+
let test_url = |url| match decode_data_url(url).unwrap() {
124124
DecodedMap::Regular(sm) => {
125125
let mut iter = sm.tokens().filter(Token::has_name);
126126
assert_eq!(
@@ -140,7 +140,9 @@ fn test_sourcemap_data_url() {
140140
_ => {
141141
panic!("did not get sourcemap");
142142
}
143-
}
143+
};
144+
test_url(url);
145+
test_url(&url.replace("application/json", "application/json;charset=utf-8"))
144146
}
145147

146148
#[test]

0 commit comments

Comments
 (0)