From 053c568c8cba41ae8e296c5bc346db6e75d7816f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Tue, 12 May 2020 17:44:25 +0200 Subject: [PATCH] fix: source maps in inspector for local files (#5245) This commit changes handling of source maps by setting proper file URLs for "file" and "sources" fields in the source map. --- cli/tsc.rs | 43 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/cli/tsc.rs b/cli/tsc.rs index db9c19afef..f71fe3747d 100644 --- a/cli/tsc.rs +++ b/cli/tsc.rs @@ -33,6 +33,7 @@ use regex::Regex; use serde::Deserialize; use serde_json::json; use serde_json::Value; +use sourcemap::SourceMap; use std::collections::HashMap; use std::collections::HashSet; use std::fs; @@ -718,10 +719,27 @@ impl TsCompiler { return Ok(()); } + let js_key = self + .disk_cache + .get_cache_filename_with_extension(module_specifier.as_url(), "js"); + let js_path = self.disk_cache.location.join(js_key); + let js_file_url = + Url::from_file_path(js_path).expect("Bad file URL for file"); + let source_map_key = self .disk_cache .get_cache_filename_with_extension(module_specifier.as_url(), "js.map"); - self.disk_cache.set(&source_map_key, contents.as_bytes()) + + let mut sm = SourceMap::from_slice(contents.as_bytes()) + .expect("Invalid source map content"); + sm.set_file(Some(&js_file_url.to_string())); + sm.set_source(0, &module_specifier.to_string()); + + let mut output: Vec = vec![]; + sm.to_writer(&mut output) + .expect("Failed to write source map"); + + self.disk_cache.set(&source_map_key, &output) } } @@ -924,6 +942,29 @@ mod tests { source_code.split('\n').map(|s| s.to_string()).collect(); let last_line = lines.pop().unwrap(); assert!(last_line.starts_with("//# sourceMappingURL=file://")); + + // Get source map file and assert it has proper URLs + let source_map = mock_state + .ts_compiler + .get_source_map_file(&specifier) + .expect("Source map not found"); + let source_str = String::from_utf8(source_map.source_code).unwrap(); + let source_json: Value = serde_json::from_str(&source_str).unwrap(); + + let js_key = mock_state + .ts_compiler + .disk_cache + .get_cache_filename_with_extension(specifier.as_url(), "js"); + let js_path = mock_state.ts_compiler.disk_cache.location.join(js_key); + let js_file_url = Url::from_file_path(js_path).unwrap(); + + let file_str = source_json.get("file").unwrap().as_str().unwrap(); + assert_eq!(file_str, js_file_url.to_string()); + + let sources = source_json.get("sources").unwrap().as_array().unwrap(); + assert_eq!(sources.len(), 1); + let source = sources.get(0).unwrap().as_str().unwrap(); + assert_eq!(source, specifier.to_string()); } #[tokio::test]