diff options
author | David Sherret <dsherret@users.noreply.github.com> | 2022-07-19 11:58:18 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-07-19 11:58:18 -0400 |
commit | 0ab262b901348e9251262a02bef17d14ed13b997 (patch) | |
tree | fc5a6e3926ea7480714cbc844098eca6c43c1ab5 /cli/text_encoding.rs | |
parent | e99d64acedb6e111d33f53599da494865978f1aa (diff) |
feat: emit files on demand and fix racy emit (#15220)
Diffstat (limited to 'cli/text_encoding.rs')
-rw-r--r-- | cli/text_encoding.rs | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/cli/text_encoding.rs b/cli/text_encoding.rs index 392bab7b8..2bb45beb0 100644 --- a/cli/text_encoding.rs +++ b/cli/text_encoding.rs @@ -54,6 +54,34 @@ pub fn strip_bom(text: &str) -> &str { } } +static SOURCE_MAP_PREFIX: &str = + "//# sourceMappingURL=data:application/json;base64,"; + +pub fn source_map_from_code(code: &str) -> Option<Vec<u8>> { + let last_line = code.rsplit(|u| u == '\n').next()?; + if last_line.starts_with(SOURCE_MAP_PREFIX) { + let input = last_line.split_at(SOURCE_MAP_PREFIX.len()).1; + let decoded_map = base64::decode(input) + .expect("Unable to decode source map from emitted file."); + Some(decoded_map) + } else { + None + } +} + +pub fn code_without_source_map(mut code: String) -> String { + if let Some(last_line_index) = code.rfind('\n') { + if code[last_line_index + 1..].starts_with(SOURCE_MAP_PREFIX) { + code.truncate(last_line_index + 1); + code + } else { + code + } + } else { + code + } +} + #[cfg(test)] mod tests { use super::*; @@ -103,4 +131,33 @@ mod tests { let err = result.expect_err("Err expected"); assert!(err.kind() == ErrorKind::InvalidData); } + + #[test] + fn test_source_without_source_map() { + run_test("", ""); + run_test("\n", "\n"); + run_test("\r\n", "\r\n"); + run_test("a", "a"); + run_test("a\n", "a\n"); + run_test("a\r\n", "a\r\n"); + run_test("a\r\nb", "a\r\nb"); + run_test("a\nb\n", "a\nb\n"); + run_test("a\r\nb\r\n", "a\r\nb\r\n"); + run_test( + "test\n//# sourceMappingURL=data:application/json;base64,test", + "test\n", + ); + run_test( + "test\r\n//# sourceMappingURL=data:application/json;base64,test", + "test\r\n", + ); + run_test( + "\n//# sourceMappingURL=data:application/json;base64,test", + "\n", + ); + + fn run_test(input: &str, output: &str) { + assert_eq!(code_without_source_map(input.to_string()), output); + } + } } |