Skip to content

Commit 4ec350d

Browse files
committed
fix: rm RawSourceMap
1 parent 1004eb2 commit 4ec350d

File tree

2 files changed

+69
-89
lines changed

2 files changed

+69
-89
lines changed

src/replace_source.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1044,14 +1044,14 @@ Line 2"#
10441044
#[test]
10451045
fn should_allow_replacements_at_the_start() {
10461046
let map = SourceMap::from_slice(
1047-
r#"{
1047+
&mut r#"{
10481048
"version":3,
10491049
"sources":["abc"],
10501050
"names":["StaticPage","data","foo"],
10511051
"mappings":";;AAAA,eAAe,SAASA,UAAT,OAA8B;AAAA,MAARC,IAAQ,QAARA,IAAQ;AAC3C,sBAAO;AAAA,cAAMA,IAAI,CAACC;AAAX,IAAP;AACD",
10521052
"sourcesContent":["export default function StaticPage({ data }) {\nreturn <div>{data.foo}</div>\n}\n"],
10531053
"file":"x"
1054-
}"#.as_bytes(),
1054+
}"#.as_bytes().to_vec(),
10551055
).unwrap();
10561056

10571057
let code = r#"import { jsx as _jsx } from "react/jsx-runtime";

src/source.rs

Lines changed: 67 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
use std::{
22
any::{Any, TypeId},
33
borrow::Cow,
4-
convert::{TryFrom, TryInto},
54
fmt,
65
hash::{Hash, Hasher},
76
sync::Arc,
87
};
98

109
use dyn_clone::DynClone;
11-
use serde::{Deserialize, Serialize};
10+
use serde::Serialize;
11+
use simd_json::{
12+
base::ValueAsScalar,
13+
derived::{ValueObjectAccessAsArray, ValueObjectAccessAsScalar},
14+
};
1215

1316
use crate::{
1417
helpers::{decode_mappings, StreamChunks},
@@ -193,7 +196,21 @@ fn is_all_empty(val: &Arc<[String]>) -> bool {
193196
val.iter().all(|s| s.is_empty())
194197
}
195198

196-
/// The source map created by [Source::map].
199+
/// Source map representation and utilities.
200+
///
201+
/// This struct serves multiple purposes in the source mapping ecosystem:
202+
///
203+
/// 1. **Source Map Generation**: Created by the `map()` method of various `Source`
204+
/// implementations to provide mapping information between generated and original code
205+
///
206+
/// 2. **JSON Deserialization**: Can be constructed from JSON strings via `from_json()`,
207+
/// enabling integration with external source map files and `SourceMapSource` usage
208+
///
209+
/// 3. **Caching Optimization**: Used by `CachedSource` to store computed source maps,
210+
/// preventing expensive recomputation of mapping data during repeated access
211+
///
212+
/// The source map follows the [Source Map Specification v3](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit)
213+
/// and provides efficient serialization/deserialization capabilities.
197214
#[derive(Clone, PartialEq, Eq, Serialize)]
198215
pub struct SourceMap {
199216
version: u8,
@@ -353,58 +370,64 @@ impl SourceMap {
353370
}
354371
}
355372

356-
#[derive(Debug, Default, Deserialize)]
357-
struct RawSourceMap {
358-
pub file: Option<String>,
359-
pub sources: Option<Vec<Option<String>>>,
360-
#[serde(rename = "sourceRoot")]
361-
pub source_root: Option<String>,
362-
#[serde(rename = "sourcesContent")]
363-
pub sources_content: Option<Vec<Option<String>>>,
364-
pub names: Option<Vec<Option<String>>>,
365-
pub mappings: String,
366-
#[serde(rename = "debugId")]
367-
pub debug_id: Option<String>,
368-
}
369-
370-
impl RawSourceMap {
371-
pub fn from_reader<R: std::io::Read>(r: R) -> Result<Self> {
372-
let raw: RawSourceMap = simd_json::serde::from_reader(r)?;
373-
Ok(raw)
374-
}
375-
376-
pub fn from_slice(val: &[u8]) -> Result<Self> {
377-
let mut v = val.to_vec();
378-
let raw: RawSourceMap = simd_json::serde::from_slice(&mut v)?;
379-
Ok(raw)
380-
}
381-
382-
pub fn from_json(val: &str) -> Result<Self> {
383-
let mut v = val.as_bytes().to_vec();
384-
let raw: RawSourceMap = simd_json::serde::from_slice(&mut v)?;
385-
Ok(raw)
386-
}
387-
}
388-
389373
impl SourceMap {
390374
/// Create a [SourceMap] from json string.
391-
pub fn from_json(s: &str) -> Result<Self> {
392-
RawSourceMap::from_json(s)?.try_into()
375+
pub fn from_json(json: impl Into<String>) -> Result<Self> {
376+
let mut json_bytes = json.into().into_bytes();
377+
Self::from_slice(&mut json_bytes)
393378
}
394379

395-
/// Create a [SourceMap] from [&[u8]].
396-
pub fn from_slice(s: &[u8]) -> Result<Self> {
397-
RawSourceMap::from_slice(s)?.try_into()
380+
/// Create a [SourceMap] from [&mut [u8]].
381+
pub fn from_slice(json_bytes: &mut [u8]) -> Result<Self> {
382+
let value = simd_json::to_borrowed_value(json_bytes)?;
383+
Ok(Self {
384+
version: 3,
385+
file: value.get_str("file").map(|v| Arc::from(v.to_string())),
386+
sources: value
387+
.get_array("sources")
388+
.map(|v| {
389+
v.into_iter()
390+
.map(|s| s.as_str().map(|s| s.to_string()).unwrap_or_default())
391+
.collect::<Vec<_>>()
392+
.into()
393+
})
394+
.unwrap_or_default(),
395+
sources_content: value
396+
.get_array("sourcesContent")
397+
.map(|v| {
398+
v.into_iter()
399+
.map(|s| s.as_str().map(|s| s.to_string()).unwrap_or_default())
400+
.collect::<Vec<_>>()
401+
.into()
402+
})
403+
.unwrap_or_default(),
404+
names: value
405+
.get_array("names")
406+
.map(|v| {
407+
v.into_iter()
408+
.map(|s| s.as_str().map(|s| s.to_string()).unwrap_or_default())
409+
.collect::<Vec<_>>()
410+
.into()
411+
})
412+
.unwrap_or_default(),
413+
mappings: value.get_str("mappings").unwrap_or_default().into(),
414+
source_root: value
415+
.get_str("sourceRoot")
416+
.map(|v| Arc::from(v.to_string())),
417+
debug_id: value.get_str("debugId").map(|v| Arc::from(v.to_string())),
418+
})
398419
}
399420

400421
/// Create a [SourceMap] from reader.
401-
pub fn from_reader<R: std::io::Read>(s: R) -> Result<Self> {
402-
RawSourceMap::from_reader(s)?.try_into()
422+
pub fn from_reader<R: std::io::Read>(mut s: R) -> Result<Self> {
423+
let mut json_bytes = vec![];
424+
let _ = s.read_to_end(&mut json_bytes);
425+
Self::from_slice(&mut json_bytes)
403426
}
404427

405428
/// Generate source map to a json string.
406429
pub fn to_json(self) -> Result<String> {
407-
let json = simd_json::serde::to_string(&self)?;
430+
let json = simd_json::to_string(&self)?;
408431
Ok(json)
409432
}
410433

@@ -415,49 +438,6 @@ impl SourceMap {
415438
}
416439
}
417440

418-
impl TryFrom<RawSourceMap> for SourceMap {
419-
type Error = crate::Error;
420-
421-
fn try_from(raw: RawSourceMap) -> Result<Self> {
422-
let file = raw.file.map(Into::into);
423-
let mappings = raw.mappings.into();
424-
let sources = raw
425-
.sources
426-
.unwrap_or_default()
427-
.into_iter()
428-
.map(Option::unwrap_or_default)
429-
.collect::<Vec<_>>()
430-
.into();
431-
let sources_content = raw
432-
.sources_content
433-
.unwrap_or_default()
434-
.into_iter()
435-
.map(Option::unwrap_or_default)
436-
.collect::<Vec<_>>()
437-
.into();
438-
let names = raw
439-
.names
440-
.unwrap_or_default()
441-
.into_iter()
442-
.map(Option::unwrap_or_default)
443-
.collect::<Vec<_>>()
444-
.into();
445-
let source_root = raw.source_root.map(Into::into);
446-
let debug_id = raw.debug_id.map(Into::into);
447-
448-
Ok(Self {
449-
version: 3,
450-
file,
451-
mappings,
452-
sources,
453-
sources_content,
454-
names,
455-
source_root,
456-
debug_id,
457-
})
458-
}
459-
}
460-
461441
/// Represent a [Mapping] information of source map.
462442
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
463443
pub struct Mapping {

0 commit comments

Comments
 (0)