From 77023a8b7dd19276eb024c313e8c8d8dd10f477e Mon Sep 17 00:00:00 2001 From: underfin <2218301630@qq.com> Date: Fri, 8 Mar 2024 16:46:13 +0800 Subject: [PATCH] feat: add SourceMap::to_data_url (#81) --- Cargo.toml | 1 + src/types.rs | 23 +++++++++++++++++++++++ tests/test_encoder.rs | 7 +++++++ 3 files changed, 31 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 6d6182f..69448ec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,7 @@ if_chain = "1.0.0" scroll = { version = "0.10.1", features = ["derive"], optional = true } data-encoding = "2.3.3" debugid = {version = "0.8.0", features = ["serde"] } +base64-simd = { version = "0.7" } [build-dependencies] rustc_version = "0.2.3" diff --git a/src/types.rs b/src/types.rs index 709c12f..ce7d22f 100644 --- a/src/types.rs +++ b/src/types.rs @@ -520,6 +520,29 @@ impl SourceMap { encode(self, w) } + /// Encode a sourcemap into a data url. + /// + /// ```rust + /// # use sourcemap::SourceMap; + /// # let input: &[_] = b"{ + /// # \"version\":3, + /// # \"sources\":[\"coolstuff.js\"], + /// # \"names\":[\"x\",\"alert\"], + /// # \"mappings\":\"AAAA,GAAIA,GAAI,EACR,IAAIA,GAAK,EAAG,CACVC,MAAM\" + /// # }"; + /// let sm = SourceMap::from_reader(input).unwrap(); + /// sm.to_data_url().unwrap(); + /// ``` + pub fn to_data_url(&self) -> Result { + let mut buf = vec![]; + encode(self, &mut buf)?; + let b64 = base64_simd::Base64::STANDARD.encode_to_boxed_str(&buf); + Ok(format!( + "data:application/json;charset=utf-8;base64,{}", + b64 + )) + } + /// Creates a sourcemap from a reader over a JSON byte slice in UTF-8 /// format. Optionally a "garbage header" as defined by the /// sourcemap draft specification is supported. In case an indexed diff --git a/tests/test_encoder.rs b/tests/test_encoder.rs index 312cdcd..d38273c 100644 --- a/tests/test_encoder.rs +++ b/tests/test_encoder.rs @@ -18,3 +18,10 @@ fn test_basic_sourcemap() { assert_eq!(tok1, tok2); } } + +#[test] +fn test_sourcemap_data_url() { + let input: &[_] = br#"{"version":3,"file":"build/foo.min.js","sources":["src/foo.js"],"names":[],"mappings":"AAAA","sourceRoot":"/"}"#; + let sm = SourceMap::from_reader(input).unwrap(); + assert_eq!(sm.to_data_url().unwrap(), "data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJzb3VyY2VSb290IjoiLyIsIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBIn0="); +}