Unverified Commit 3d018005 authored by dan's avatar dan Committed by GitHub

Turbopack: stop copying sourcesContent into every serialized source map (#95934)

This reduces peak memory consumption with the original repro case in
[vercel/next.js#81161](https://github.com/vercel/next.js/issues/81161).

If you walk the 15 routes in a quick succession and capture vmmap
--summary at the end of each fast sweep (before memory is released),
with this change the number reliably goes down from 3 GB to 2.6 GB:

```
before	1	3.0G	17
after	1	2.6G	16
before	2	3.0G	16
after	2	2.6G	16
before	3	3.1G	18
after	3	2.6G	17
before	4	3.1G	17
after	4	2.6G	16
before	5	3.1G	17
after	5	2.6G	17
before	6	3.0G	17
after	6	2.5G	17
before	7	3.1G	17
after	7	2.6G	17
before	8	3.0G	25
after	8	2.6G	24
before: [3.0, 3.0, 3.1, 3.1, 3.1, 3.0, 3.1, 3.0] 
after:  [2.6, 2.6, 2.6, 2.6, 2.6, 2.5, 2.6, 2.6]
mean before=3.050G after=2.587G  diff=0.462G (-15.2%)
exact permutation test: p = 2/12870 = 0.00016
```

More runs on this app:

<img width="938" height="623" alt="Screenshot 2026-07-22 at 20 59 12"
src="https://github.com/user-attachments/assets/01c41656-eb5a-41f9-8871-b4ce262c54d5"
/>

And here's an internal app showing ~20% dev memory win at peak (although
reclaiming memory settles it):

<img width="832" height="402" alt="Screenshot 2026-07-22 at 16 45 34"
src="https://github.com/user-attachments/assets/8c39f668-d431-43f9-b533-d39dfaa97c15"
/>

---

<details>

Module source maps are serialized to a JSON rope right after code
generation and treated as opaque bytes from then on. Since
`sourcesContent` — the full original source text — is inlined into that
JSON, every later step that modifies the map has to copy all of it:
rewriting the `sources` URLs for each chunking context copies the entire
map per context, and embedding the module map into a chunk's sectioned
map copies it again, once per layer that includes the module. In a dev
session on a dependency-heavy app, each module's source text ends up
resident ~5 times over, and source maps end up dominating the memory the
task store holds for codegen output (in one measured app, maps were 57%
of module factory bytes, and `sourcesContent` alone was 36%).

This PR stops copying the text. `StructuredSourceMap` keeps a map in
field form until the moment it is actually emitted:

- Fields we never touch (`mappings`, `names`, `version`, ...) are stored
as verbatim raw JSON snippets, so producers' bytes round-trip untouched
and re-emission is rope sharing rather than re-serialization.
- `sources` is the one field rewrites modify, so it is stored typed, and
the per-chunking-context "fileify" rewrites become a plain string
rewrite of that field instead of a parse–modify–reserialize of the whole
map.
- `sourcesContent` entries are individual, already-JSON-escaped ropes.
Rewritten maps and chunk maps share them; the source text is escaped
once per module and never copied again.

Two construction paths, chosen by where the bytes come from: maps we
generate ourselves are built directly from the `swc_sourcemap` object
(`from_swc_map` takes the contents out, serializes the small remainder,
and never round-trips source text through JSON), while maps that arrive
as bytes (prebuilt maps next to external code, the
single-complete-original fast path) go through `from_json`. The emitter
writes fields in exactly `swc_sourcemap`'s order and format, pinned by
golden tests that assert byte-identity with `to_writer` — so emitted
chunks and maps are byte-for-byte unchanged, and no snapshot fixtures
change. The CSS pipeline gets the same treatment; the single-file output
path is left alone since it serializes straight into the final artifact
and there is nothing to share.

The win is proportional to how much duplicated source-map text an app
holds, so results range accordingly. On a dependency-heavy reproduction
app (13 routes sharing large wallet SDKs; rapid route sweep in `next
dev`, macOS physical footprint, 8 interleaved cold runs per side): 3.05
GB → 2.59 GB mean (−15%), with zero overlap between the two
distributions (exact permutation test p ≈ 0.00016) and per-route
latencies unchanged. On `bench/basic-app` (small first-party modules): a
full sweep of all 42 routes drops the post-sweep footprint 3.4–3.5 GB →
2.4–2.5 GB (−29%, interleaved runs); cold compile −4%, idle footprint
identical (eviction reclaims both sides equally at idle). On
`bench/heavy-npm-deps` (heavy deps disabled in its default config) and
on very large first-party apps whose memory is dominated by the JS heap
and application state rather than map text, the change measures flat —
as expected, since there is little duplicated text for sharing to
recover. `small_apps` build benchmarks are flat except `date-fns-all` at
+1–2% (~2.5 ms): that app is 1000+ tiny modules and `from_swc_map` adds
one small-skeleton JSON parse per module, with no redundancy to win back
in a single-context one-shot build. The single-complete-original fast
path (per prebuilt module with a shipped map, and per minified chunk) is
cost-neutral: the structured map is built by splitting the raw map's
serde fields directly (`from_serialize`), so the serialized document is
never materialized or re-parsed — 93 ms per 5 iterations on a synthetic
21.7 MB map, matching the pre-PR baseline exactly, with byte-identical
output pinned by a property test. Serialized task-store size is
unchanged (bincode expands sharing back out), so this is purely a
live-memory change.

Verified: snapshot suite passes with zero fixture changes, execution
suite matches canary (the single pre-existing failure reproduces on the
base tag), unit suites pass including new golden byte-identity tests,
and emitted `.map` files were validated end-to-end in a running dev
server (multi-section chunk maps, fileified `file://` sources,
`sourcesContent` present and byte-identical between base and this
branch).

</details>
parent 99cf207a
......@@ -22,7 +22,7 @@ use turbopack_core::{
module_graph::ModuleGraph,
reference_type::ReferenceType,
source::{OptionSource, Source},
source_map::GenerateSourceMap,
source_map::{GenerateSourceMap, structured::StructuredSourceMap},
};
use turbopack_ecmascript::{
EcmascriptInputTransforms,
......@@ -258,6 +258,9 @@ impl EcmascriptChunkPlaceable for RawEcmascriptModule {
None
};
let source_map = source_map
.map(|map| StructuredSourceMap::from_json(&map))
.transpose()?;
Ok(EcmascriptChunkItemContent {
source_map,
inner_code: code.into_source_code(),
......
......@@ -9,22 +9,66 @@ use anyhow::Result;
use bincode::{Decode, Encode};
use tracing::instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, trace::TraceRawVcs};
use turbo_tasks_fs::{
File, FileContent,
rope::{Rope, RopeBuilder},
};
use turbo_tasks_hash::hash_xxh3_hash128;
use turbo_tasks_hash::{DeterministicHash, DeterministicHasher, hash_xxh3_hash128};
use crate::{
debug_id::generate_debug_id,
output::OutputAsset,
source_map::{GenerateSourceMap, SourceMap, SourceMapAsset},
source_map::{GenerateSourceMap, SourceMap, SourceMapAsset, structured::StructuredSourceMap},
source_pos::SourcePos,
};
/// A per-section source map: either an opaque serialized map or a structured one whose
/// `sourcesContent` is shared rather than copied when the section is embedded.
#[derive(Clone, Debug, PartialEq, Eq, Encode, Decode, TraceRawVcs, NonLocalValue)]
pub enum SectionMap {
Raw(Rope),
Structured(Box<StructuredSourceMap>),
}
impl From<Rope> for SectionMap {
fn from(map: Rope) -> Self {
SectionMap::Raw(map)
}
}
impl From<StructuredSourceMap> for SectionMap {
fn from(map: StructuredSourceMap) -> Self {
SectionMap::Structured(Box::new(map))
}
}
impl DeterministicHash for SectionMap {
fn deterministic_hash<H: DeterministicHasher>(&self, state: &mut H) {
match self {
SectionMap::Raw(map) => {
state.write_u8(0);
map.deterministic_hash(state);
}
SectionMap::Structured(map) => {
state.write_u8(1);
map.deterministic_hash(state);
}
}
}
}
impl SectionMap {
pub fn to_rope(&self) -> Rope {
match self {
SectionMap::Raw(map) => map.clone(),
SectionMap::Structured(map) => map.to_rope(),
}
}
}
/// A mapping of byte-offset in the code string to an associated source map.
pub type Mapping = (usize, Option<Rope>);
pub type Mapping = (usize, Option<SectionMap>);
/// Code stores combined output code and the source map of that output code.
#[turbo_tasks::value(shared, serialization = "hash")]
......@@ -166,8 +210,8 @@ impl CodeBuilder {
/// Pushes original user code with an optional source map if one is
/// available. If it's not, this is no different than pushing Synthetic
/// code.
pub fn push_source(&mut self, code: &Rope, map: Option<Rope>) {
self.push_map(map);
pub fn push_source<M: Into<SectionMap>>(&mut self, code: &Rope, map: Option<M>) {
self.push_map(map.map(Into::into));
self.code += code;
}
......@@ -205,7 +249,7 @@ impl CodeBuilder {
/// original code section. By inserting an empty source map when reaching a
/// synthetic section directly after an original section, we tell Chrome
/// that the previous map ended at this point.
fn push_map(&mut self, map: Option<Rope>) {
fn push_map(&mut self, map: Option<SectionMap>) {
let Some(mappings) = self.mappings.as_mut() else {
return;
};
......@@ -339,7 +383,7 @@ impl Code {
last_byte_pos = *byte_pos;
if let Some(map) = map {
sections.push((pos, map.clone()))
sections.push((pos, map.to_rope()))
} else {
// We don't need an empty source map when column is 0 or the next char is a newline.
if pos.column != 0
......
......@@ -31,6 +31,7 @@ use crate::{
};
pub(crate) mod source_map_asset;
pub mod structured;
pub mod utils;
pub use source_map_asset::SourceMapAsset;
......
//! A source map kept in structured form until it is actually emitted, so that rewriting or
//! embedding a map shares its ropes instead of copying its bytes. `sourcesContent` in
//! particular (the full original source text) would otherwise be copied for every chunking
//! context that rewrites the `sources` URLs and for every chunk source map that embeds the
//! module's map.
//!
//! Fields are stored as verbatim raw JSON snippets ([`Rope`]s) and only decoded when something
//! actually needs their values: `sources` is decoded lazily by
//! [`StructuredSourceMap::rewrite_sources`] when a rewrite changes an entry, and `sourcesContent`
//! of maps built from swc objects is a list of individually pre-escaped [`Rope`]s that are shared
//! into every map that embeds them.
//!
//! [`StructuredSourceMap::to_rope`] emits fields in the same order as `swc_sourcemap`'s
//! serializer, so maps built via [`StructuredSourceMap::from_swc_map`] serialize byte-for-byte
//! identically to what `swc_sourcemap::SourceMap::to_writer` would have produced (pinned by the
//! golden tests below).
use std::sync::LazyLock;
use anyhow::Result;
use bincode::{Decode, Encode};
use serde::Deserialize;
use serde_json::value::RawValue;
use turbo_tasks::{NonLocalValue, trace::TraceRawVcs};
use turbo_tasks_fs::rope::{Rope, RopeBuilder};
use turbo_tasks_hash::{DeterministicHash, DeterministicHasher};
/// A single source map in structured form. See the module documentation.
#[derive(Clone, Debug, Default, PartialEq, Eq, Encode, Decode, TraceRawVcs, NonLocalValue)]
pub struct StructuredSourceMap {
// Raw snippet fields hold the field's verbatim JSON value (e.g. `3`, `"..."`, `[...]`).
// Declaration order mirrors `swc_sourcemap`'s `RawSourceMap`, which is the emission order.
version: Option<Rope>,
file: Option<Rope>,
sources: Option<SourcesField>,
source_root: Option<Rope>,
sources_content: Option<SourcesContentField>,
sections: Option<Rope>,
names: Option<Rope>,
scopes: Option<Rope>,
range_mappings: Option<Rope>,
mappings: Option<Rope>,
ignore_list: Option<Rope>,
x_facebook_offsets: Option<Rope>,
x_metro_module_paths: Option<Rope>,
x_facebook_sources: Option<Rope>,
debug_id_old: Option<Rope>,
debug_id: Option<Rope>,
}
/// The `sources` field. Kept verbatim until a rewrite actually changes an entry, so maps whose
/// `sources` cannot be decoded (or are never rewritten) round-trip byte-for-byte.
#[derive(Clone, Debug, PartialEq, Eq, Encode, Decode, TraceRawVcs, NonLocalValue)]
enum SourcesField {
/// The field's verbatim JSON value.
Raw(Rope),
/// Decoded form, produced only by [`StructuredSourceMap::rewrite_sources`] when an entry
/// changed.
Rewritten(Vec<Option<String>>),
}
/// The `sourcesContent` field.
#[derive(Clone, Debug, PartialEq, Eq, Encode, Decode, TraceRawVcs, NonLocalValue)]
enum SourcesContentField {
/// The field's verbatim JSON value (maps parsed from external bytes). Never decoded — this
/// tolerates content JSON that does not decode into Rust strings, e.g. lone surrogate
/// escapes.
Raw(Rope),
/// One entry per source: the pre-escaped JSON value of the source's content — a string
/// literal (including quotes) or the literal `null`. Shared into every emitted map (maps
/// built via [`StructuredSourceMap::from_swc_map`]).
Escaped(Vec<Rope>),
}
/// Deserialization mirror of [`StructuredSourceMap`]. Unknown fields are dropped.
#[derive(Deserialize)]
struct RawFields {
version: Option<Box<RawValue>>,
file: Option<Box<RawValue>>,
sources: Option<Box<RawValue>>,
#[serde(rename = "sourceRoot")]
source_root: Option<Box<RawValue>>,
#[serde(rename = "sourcesContent")]
sources_content: Option<Box<RawValue>>,
sections: Option<Box<RawValue>>,
names: Option<Box<RawValue>>,
scopes: Option<Box<RawValue>>,
#[serde(rename = "rangeMappings")]
range_mappings: Option<Box<RawValue>>,
mappings: Option<Box<RawValue>>,
#[serde(rename = "ignoreList")]
ignore_list: Option<Box<RawValue>>,
x_facebook_offsets: Option<Box<RawValue>>,
x_metro_module_paths: Option<Box<RawValue>>,
x_facebook_sources: Option<Box<RawValue>>,
#[serde(rename = "debug_id")]
debug_id_old: Option<Box<RawValue>>,
#[serde(rename = "debugId")]
debug_id: Option<Box<RawValue>>,
}
fn into_rope(value: Option<Box<RawValue>>) -> Option<Rope> {
value.map(|v| Rope::from(v.get().as_bytes().to_vec()))
}
/// JSON-escapes a source's content into the string-literal form stored in `sources_content`.
fn escape_content(content: Option<&str>) -> Rope {
match content {
Some(text) => {
Rope::from(serde_json::to_vec(text).expect("string serialization is infallible"))
}
None => {
static NULL: LazyLock<Rope> = LazyLock::new(|| Rope::from("null"));
NULL.clone()
}
}
}
/// A serde [`Serializer`](serde::Serializer) that splits a struct into its top-level fields,
/// each serialized to its own JSON value. This lets [`StructuredSourceMap::from_serialize`]
/// capture a source map's fields directly from its `Serialize` implementation without
/// materializing — and then re-parsing — the whole serialized document.
struct FieldSplit;
#[derive(Debug)]
struct FieldSplitError(String);
impl std::fmt::Display for FieldSplitError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for FieldSplitError {}
impl serde::ser::Error for FieldSplitError {
fn custom<T: std::fmt::Display>(msg: T) -> Self {
FieldSplitError(msg.to_string())
}
}
struct FieldSplitStruct {
fields: Vec<(&'static str, Vec<u8>)>,
}
impl serde::ser::SerializeStruct for FieldSplitStruct {
type Ok = Vec<(&'static str, Vec<u8>)>;
type Error = FieldSplitError;
fn serialize_field<T: ?Sized + serde::Serialize>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), FieldSplitError> {
let bytes = serde_json::to_vec(value).map_err(serde::ser::Error::custom)?;
self.fields.push((key, bytes));
Ok(())
}
fn end(self) -> Result<Self::Ok, FieldSplitError> {
Ok(self.fields)
}
}
macro_rules! not_a_struct {
($($f:ident($($arg:ty),*) -> $ret:ty;)*) => {
$(fn $f(self, $(_: $arg),*) -> Result<$ret, FieldSplitError> {
Err(serde::ser::Error::custom("expected a struct"))
})*
};
}
impl serde::Serializer for FieldSplit {
type Ok = Vec<(&'static str, Vec<u8>)>;
type Error = FieldSplitError;
type SerializeSeq = serde::ser::Impossible<Self::Ok, Self::Error>;
type SerializeTuple = serde::ser::Impossible<Self::Ok, Self::Error>;
type SerializeTupleStruct = serde::ser::Impossible<Self::Ok, Self::Error>;
type SerializeTupleVariant = serde::ser::Impossible<Self::Ok, Self::Error>;
type SerializeMap = serde::ser::Impossible<Self::Ok, Self::Error>;
type SerializeStruct = FieldSplitStruct;
type SerializeStructVariant = serde::ser::Impossible<Self::Ok, Self::Error>;
fn serialize_struct(
self,
_name: &'static str,
len: usize,
) -> Result<FieldSplitStruct, FieldSplitError> {
Ok(FieldSplitStruct {
fields: Vec::with_capacity(len),
})
}
not_a_struct! {
serialize_bool(bool) -> Self::Ok;
serialize_i8(i8) -> Self::Ok;
serialize_i16(i16) -> Self::Ok;
serialize_i32(i32) -> Self::Ok;
serialize_i64(i64) -> Self::Ok;
serialize_u8(u8) -> Self::Ok;
serialize_u16(u16) -> Self::Ok;
serialize_u32(u32) -> Self::Ok;
serialize_u64(u64) -> Self::Ok;
serialize_f32(f32) -> Self::Ok;
serialize_f64(f64) -> Self::Ok;
serialize_char(char) -> Self::Ok;
serialize_str(&str) -> Self::Ok;
serialize_bytes(&[u8]) -> Self::Ok;
serialize_none() -> Self::Ok;
serialize_unit() -> Self::Ok;
serialize_unit_struct(&'static str) -> Self::Ok;
serialize_unit_variant(&'static str, u32, &'static str) -> Self::Ok;
serialize_seq(Option<usize>) -> Self::SerializeSeq;
serialize_tuple(usize) -> Self::SerializeTuple;
serialize_tuple_struct(&'static str, usize) -> Self::SerializeTupleStruct;
serialize_tuple_variant(&'static str, u32, &'static str, usize) -> Self::SerializeTupleVariant;
serialize_map(Option<usize>) -> Self::SerializeMap;
serialize_struct_variant(&'static str, u32, &'static str, usize) -> Self::SerializeStructVariant;
}
fn serialize_some<T: ?Sized + serde::Serialize>(
self,
_value: &T,
) -> Result<Self::Ok, FieldSplitError> {
Err(serde::ser::Error::custom("expected a struct"))
}
fn serialize_newtype_struct<T: ?Sized + serde::Serialize>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, FieldSplitError> {
value.serialize(self)
}
fn serialize_newtype_variant<T: ?Sized + serde::Serialize>(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_value: &T,
) -> Result<Self::Ok, FieldSplitError> {
Err(serde::ser::Error::custom("expected a struct"))
}
}
impl StructuredSourceMap {
/// Builds from a [`swc_sourcemap::SourceMap`], taking the `sourcesContent` entries out of
/// the map before serializing the (now small) remainder. This is the cheap constructor for
/// all internally generated maps: the source text is escaped exactly once and never
/// round-trips through JSON parsing.
pub fn from_swc_map(mut map: swc_sourcemap::SourceMap) -> Result<Self> {
let contents: Vec<Rope> = map
.source_contents()
.map(|content| escape_content(content.map(|c| c.as_str())))
.collect();
let has_contents = contents.iter().any(|c| c.to_bytes().as_ref() != b"null");
for idx in 0..map.get_source_count() {
map.set_source_contents(idx, None);
}
let mut skeleton = Vec::new();
map.to_writer(&mut skeleton)?;
let mut result = Self::from_json_slice(&skeleton)?;
result.sources_content = has_contents.then_some(SourcesContentField::Escaped(contents));
Ok(result)
}
/// Parses an arbitrary serialized source map, e.g. one shipped alongside external code.
pub fn from_json(map: &Rope) -> Result<Self> {
Self::from_json_slice(&map.to_bytes())
}
/// Parses a serialized source map from a byte slice.
pub fn from_json_slice(map: &[u8]) -> Result<Self> {
let fields: RawFields = serde_json::from_slice(map)?;
Ok(StructuredSourceMap {
version: into_rope(fields.version),
file: into_rope(fields.file),
sources: into_rope(fields.sources).map(SourcesField::Raw),
source_root: into_rope(fields.source_root),
sources_content: into_rope(fields.sources_content).map(SourcesContentField::Raw),
sections: into_rope(fields.sections),
names: into_rope(fields.names),
scopes: into_rope(fields.scopes),
range_mappings: into_rope(fields.range_mappings),
mappings: into_rope(fields.mappings),
ignore_list: into_rope(fields.ignore_list),
x_facebook_offsets: into_rope(fields.x_facebook_offsets),
x_metro_module_paths: into_rope(fields.x_metro_module_paths),
x_facebook_sources: into_rope(fields.x_facebook_sources),
debug_id_old: into_rope(fields.debug_id_old),
debug_id: into_rope(fields.debug_id),
})
}
/// Builds directly from a value's [`serde::Serialize`] implementation (e.g.
/// `swc_sourcemap::lazy::RawSourceMap`), capturing each top-level field's serialized JSON
/// value without materializing — and then re-parsing — the whole document. The result is
/// byte-equivalent to `Self::from_json_slice(&serde_json::to_vec(value)?)`.
///
/// Errors if the value does not serialize as a struct or contains a field this type does
/// not know about; callers should fall back to serializing and [`Self::from_json`] then.
pub fn from_serialize<T: serde::Serialize>(value: &T) -> Result<Self> {
let fields = value
.serialize(FieldSplit)
.map_err(|error| anyhow::anyhow!("failed to split source map fields: {error}"))?;
let mut result = StructuredSourceMap::default();
for (key, bytes) in fields {
let rope = Rope::from(bytes);
match key {
"version" => result.version = Some(rope),
"file" => result.file = Some(rope),
"sources" => result.sources = Some(SourcesField::Raw(rope)),
"sourceRoot" => result.source_root = Some(rope),
"sourcesContent" => result.sources_content = Some(SourcesContentField::Raw(rope)),
"sections" => result.sections = Some(rope),
"names" => result.names = Some(rope),
"scopes" => result.scopes = Some(rope),
"rangeMappings" => result.range_mappings = Some(rope),
"mappings" => result.mappings = Some(rope),
"ignoreList" => result.ignore_list = Some(rope),
"x_facebook_offsets" => result.x_facebook_offsets = Some(rope),
"x_metro_module_paths" => result.x_metro_module_paths = Some(rope),
"x_facebook_sources" => result.x_facebook_sources = Some(rope),
"debug_id" => result.debug_id_old = Some(rope),
"debugId" => result.debug_id = Some(rope),
other => anyhow::bail!("unknown source map field `{other}`"),
}
}
Ok(result)
}
/// Rewrites each `sources` entry, keeping every other field (including the shared
/// `sourcesContent` ropes) intact. `rewrite` returns `None` to leave an entry unchanged.
///
/// `sources` is only decoded if a rewrite actually changes an entry; if it cannot be decoded
/// (e.g. non-string entries in an external map) the map is returned unchanged.
pub fn rewrite_sources(
&self,
mut rewrite: impl FnMut(&str) -> Result<Option<String>>,
) -> Result<Self> {
let mut result = self.clone();
let mut sources: Vec<Option<String>> = match &self.sources {
None => return Ok(result),
Some(SourcesField::Rewritten(sources)) => sources.clone(),
Some(SourcesField::Raw(raw)) => match serde_json::from_slice(&raw.to_bytes()) {
Ok(sources) => sources,
Err(_) => return Ok(result),
},
};
let mut changed = false;
for source in sources.iter_mut().flatten() {
if let Some(new_source) = rewrite(source)? {
*source = new_source;
changed = true;
}
}
if changed {
result.sources = Some(SourcesField::Rewritten(sources));
}
Ok(result)
}
/// Serializes the map. Field order matches `swc_sourcemap`'s serializer; `sourcesContent`
/// and `mappings` ropes are shared, not copied, into the result.
pub fn to_rope(&self) -> Rope {
// `key` is a literal identifier and `raw_json` holds a complete, valid JSON value
// (parsed as `RawValue` or produced by `serde_json` serialization), so neither needs
// escaping here.
fn field(
builder: &mut RopeBuilder,
first: &mut bool,
key: &'static str,
raw_json: Option<&Rope>,
) {
if let Some(value) = raw_json {
if !*first {
*builder += ",";
}
*first = false;
*builder += "\"";
*builder += key;
*builder += "\":";
*builder += value;
}
}
let mut builder = RopeBuilder::default();
let mut first = true;
builder += "{";
field(&mut builder, &mut first, "version", self.version.as_ref());
field(&mut builder, &mut first, "file", self.file.as_ref());
match &self.sources {
None => {}
Some(SourcesField::Raw(raw)) => {
field(&mut builder, &mut first, "sources", Some(raw));
}
Some(SourcesField::Rewritten(sources)) => {
if !first {
builder += ",";
}
first = false;
builder += "\"sources\":";
builder += &Rope::from(
serde_json::to_vec(sources).expect("string serialization is infallible"),
);
}
}
field(
&mut builder,
&mut first,
"sourceRoot",
self.source_root.as_ref(),
);
match &self.sources_content {
None => {}
Some(SourcesContentField::Raw(raw)) => {
field(&mut builder, &mut first, "sourcesContent", Some(raw));
}
Some(SourcesContentField::Escaped(contents)) => {
if !first {
builder += ",";
}
first = false;
builder += "\"sourcesContent\":[";
for (i, content) in contents.iter().enumerate() {
if i > 0 {
builder += ",";
}
builder += content;
}
builder += "]";
}
}
field(&mut builder, &mut first, "sections", self.sections.as_ref());
field(&mut builder, &mut first, "names", self.names.as_ref());
field(&mut builder, &mut first, "scopes", self.scopes.as_ref());
field(
&mut builder,
&mut first,
"rangeMappings",
self.range_mappings.as_ref(),
);
field(&mut builder, &mut first, "mappings", self.mappings.as_ref());
field(
&mut builder,
&mut first,
"ignoreList",
self.ignore_list.as_ref(),
);
field(
&mut builder,
&mut first,
"x_facebook_offsets",
self.x_facebook_offsets.as_ref(),
);
field(
&mut builder,
&mut first,
"x_metro_module_paths",
self.x_metro_module_paths.as_ref(),
);
field(
&mut builder,
&mut first,
"x_facebook_sources",
self.x_facebook_sources.as_ref(),
);
field(
&mut builder,
&mut first,
"debug_id",
self.debug_id_old.as_ref(),
);
field(&mut builder, &mut first, "debugId", self.debug_id.as_ref());
builder += "}";
builder.build()
}
}
impl DeterministicHash for StructuredSourceMap {
fn deterministic_hash<H: DeterministicHasher>(&self, state: &mut H) {
// Hashing the serialized form covers every field.
self.to_rope().deterministic_hash(state);
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `to_rope(from_swc_map(m))` must be byte-identical to `m.to_writer()` — this pins the
/// emitter to `swc_sourcemap`'s format so emitted maps (and snapshot fixtures) don't change.
#[test]
fn golden_matches_swc_serializer() -> Result<()> {
let mut builder = swc_sourcemap::SourceMapBuilder::new(None);
let src_a = builder.add_source("turbopack:///[project]/a.js".into());
let src_b = builder.add_source("turbopack:///[project]/dir/b\u{2028}c\"d\\e.js".into());
builder.set_source_contents(
src_a,
Some("let a = 1;\nconsole.log(\"hi\\n\", '\u{1F980}', `\u{2028}\u{0000}`);".into()),
);
builder.set_source_contents(src_b, None);
let name = builder.add_name("console".into());
builder.add_raw(0, 0, 0, 0, Some(src_a), Some(name), false);
builder.add_raw(0, 10, 1, 0, Some(src_b), None, false);
let map = builder.into_sourcemap();
let mut expected = Vec::new();
map.clone().to_writer(&mut expected)?;
let structured = StructuredSourceMap::from_swc_map(map)?;
assert_eq!(structured.to_rope().to_bytes().as_ref(), &expected[..]);
Ok(())
}
/// Same, for a map without any source contents.
#[test]
fn golden_matches_swc_serializer_no_contents() -> Result<()> {
let mut builder = swc_sourcemap::SourceMapBuilder::new(None);
let src = builder.add_source("turbopack:///[project]/a.js".into());
builder.add_raw(0, 0, 0, 0, Some(src), None, false);
let map = builder.into_sourcemap();
let mut expected = Vec::new();
map.clone().to_writer(&mut expected)?;
let structured = StructuredSourceMap::from_swc_map(map)?;
assert_eq!(structured.to_rope().to_bytes().as_ref(), &expected[..]);
Ok(())
}
/// `from_json` → `to_rope` round-trips maps produced by serde-style serializers.
#[test]
fn roundtrips_serialized_map() -> Result<()> {
let input = r#"{"version":3,"sources":["a.js",null],"sourcesContent":["let a = \"x\";\n",null],"names":["a"],"mappings":"AAAA"}"#;
let structured = StructuredSourceMap::from_json(&Rope::from(input))?;
assert_eq!(structured.to_rope().to_bytes().as_ref(), input.as_bytes());
Ok(())
}
/// External maps may contain JSON that does not decode into Rust strings — lone surrogate
/// escapes (produced by transpilers slicing source text mid-code-point) or non-string
/// entries. These passed through the pre-structured pipeline verbatim and must not become
/// parse errors or be rewritten.
#[test]
fn tolerates_undecodable_sources_and_contents() -> Result<()> {
let input = r#"{"version":3,"sources":["a.js",7],"sourcesContent":["x\ud800y",42,null],"mappings":"AAAA"}"#;
let structured = StructuredSourceMap::from_json(&Rope::from(input))?;
assert_eq!(structured.to_rope().to_bytes().as_ref(), input.as_bytes());
Ok(())
}
/// Non-canonical (but valid) escaping in external maps must round-trip byte-for-byte.
#[test]
fn preserves_noncanonical_escaping() -> Result<()> {
let input =
r#"{"version":3,"sources":["a\/b.js"],"sourcesContent":["c\/dé"],"mappings":"AAAA"}"#;
let structured = StructuredSourceMap::from_json(&Rope::from(input))?;
assert_eq!(structured.to_rope().to_bytes().as_ref(), input.as_bytes());
Ok(())
}
/// A rewrite over a map whose `sources` cannot be decoded leaves the map untouched instead
/// of failing, matching the previous rewriters which silently skipped unparsable maps.
#[test]
fn rewrite_leaves_undecodable_sources_untouched() -> Result<()> {
let input =
r#"{"version":3,"sources":[{"weird":1}],"sourcesContent":["text"],"mappings":"AAAA"}"#;
let structured = StructuredSourceMap::from_json(&Rope::from(input))?;
let rewritten = structured.rewrite_sources(|_| Ok(Some("nope".to_string())))?;
assert_eq!(rewritten.to_rope().to_bytes().as_ref(), input.as_bytes());
Ok(())
}
/// A rewrite that changes nothing must keep the map byte-identical (the verbatim `sources`
/// bytes are retained rather than re-serialized).
#[test]
fn noop_rewrite_is_byte_identical() -> Result<()> {
let input =
r#"{"version":3,"sources":["a\/b.js"],"sourcesContent":["text"],"mappings":"AAAA"}"#;
let structured = StructuredSourceMap::from_json(&Rope::from(input))?;
let rewritten = structured.rewrite_sources(|_| Ok(None))?;
assert_eq!(rewritten.to_rope().to_bytes().as_ref(), input.as_bytes());
Ok(())
}
/// `from_serialize` must produce exactly what serializing the value and parsing it back
/// would — including undecodable raw values that swc's lazy decoder passes through.
#[test]
fn from_serialize_matches_serialized_roundtrip() -> Result<()> {
let cases: &[&str] = &[
r#"{"version":3,"sources":["a.js",7],"sourcesContent":["x\ud800y",42,null],"names":["n"],"mappings":"AAAA"}"#,
r#"{"version":3,"sources":[],"mappings":""}"#,
r#"{"version":3,"file":"out.js","sources":["a\/b.js"],"sourceRoot":"","sourcesContent":["c\/d"],"names":[],"mappings":"AAAA;;AACA","ignoreList":[0]}"#,
];
for case in cases {
let lazy = swc_sourcemap::lazy::decode(case.as_bytes())?.into_source_map()?;
let raw = lazy.into_raw_sourcemap();
let expected = serde_json::to_vec(&raw)?;
let split = StructuredSourceMap::from_serialize(&raw)?;
assert_eq!(
split.to_rope().to_bytes().as_ref(),
&expected[..],
"case: {case}"
);
let reparsed = StructuredSourceMap::from_json_slice(&expected)?;
assert_eq!(split, reparsed, "field-level equality, case: {case}");
}
Ok(())
}
#[test]
fn rewrite_sources_keeps_contents_shared() -> Result<()> {
let input = r#"{"version":3,"sources":["turbopack:///[project]/a.js"],"sourcesContent":["text"],"mappings":"AAAA"}"#;
let structured = StructuredSourceMap::from_json(&Rope::from(input))?;
let rewritten = structured.rewrite_sources(|source| {
Ok(source
.strip_prefix("turbopack:///[project]/")
.map(|rest| format!("file:///root/{rest}")))
})?;
let json: serde_json::Value = serde_json::from_slice(&rewritten.to_rope().to_bytes())?;
assert_eq!(json["sources"][0], "file:///root/a.js");
assert_eq!(json["sourcesContent"][0], "text");
Ok(())
}
}
......@@ -10,7 +10,7 @@ use turbo_tasks::{ResolvedVc, turbofmt};
use turbo_tasks_fs::{DiskFileSystem, FileContent, FileSystemPath, rope::Rope};
use url::Url;
use crate::SOURCE_URL_PROTOCOL_STR;
use crate::{SOURCE_URL_PROTOCOL_STR, source_map::structured::StructuredSourceMap};
pub fn add_default_ignore_list(map: &mut swc_sourcemap::SourceMap) {
let mut ignored_ids = HashSet::new();
......@@ -223,27 +223,23 @@ fn unencoded_str_to_raw_value(unencoded: &str) -> Box<RawValue> {
.expect("serde_json::to_string should produce valid JSON")
}
/// Helper function to transform turbopack:/// file references in a sourcemap.
/// Handles parsing the sourcemap, resolving the filesystem, applying transformations, and
/// serializing back.
/// The transform function is given the source string as found in the sourcemap (i.e. a URI).
fn uri_encode_path(path: &str) -> String {
path.split('/')
.map(|s| urlencoding::encode(s))
.collect::<Vec<_>>()
.join("/")
}
/// Applies the standard `turbopack:///[fs]/` source-URL transform to a structured map,
/// sharing every other field (notably `sourcesContent`) with the input.
async fn transform_relative_files<F>(
map: Option<&Rope>,
map: &StructuredSourceMap,
context_path: &FileSystemPath,
mut transform: F,
) -> Result<Option<Rope>>
) -> Result<StructuredSourceMap>
where
F: FnMut(&DiskFileSystem, &str) -> Result<String>,
{
let Some(map) = map else {
return Ok(None);
};
let Ok(mut map): serde_json::Result<SourceMapJson> = serde_json::from_reader(map.read()) else {
// Silently ignore invalid sourcemaps
return Ok(None);
};
let context_fs = context_path.fs;
let context_fs = &*ResolvedVc::try_downcast_type::<DiskFileSystem>(context_fs)
.context("Expected the chunking context to have a DiskFileSystem")?
......@@ -251,32 +247,21 @@ where
let prefix = format!("{}///[{}]/", SOURCE_URL_PROTOCOL_STR, context_fs.name());
let mut apply_transform = |src: &mut String| -> Result<()> {
map.rewrite_sources(|src| {
if let Some(src_rest) = src.strip_prefix(&prefix) {
*src = transform(context_fs, src_rest)?;
}
Ok(())
};
for src in map.sources.iter_mut().flatten().flatten() {
apply_transform(src)?;
}
for section in map.sections.iter_mut().flatten() {
for src in section.map.sources.iter_mut().flatten().flatten() {
apply_transform(src)?;
Ok(Some(transform(context_fs, src_rest)?))
} else {
Ok(None)
}
}
Ok(Some(Rope::from(serde_json::to_vec(&map)?)))
})
}
/// Turns `turbopack:///[project]` references in sourcemap sources into absolute `file://` uris. This
/// is useful for debugging environments.
/// Turns `turbopack:///[project]` references in the map's sources into absolute `file://` uris.
pub async fn absolute_fileify_source_map(
map: Option<&Rope>,
map: &StructuredSourceMap,
context_path: FileSystemPath,
) -> Result<Option<Rope>> {
transform_relative_files(map, &context_path, |context_fs, src_rest| {
) -> Result<StructuredSourceMap> {
transform_relative_files(map, &context_path.clone(), |context_fs, src_rest| {
let path = context_path.join(src_rest)?;
// `to_sys_path` returns a win32 path on Windows. `Url::from_file_path` can also handle
......@@ -291,36 +276,23 @@ pub async fn absolute_fileify_source_map(
.await
}
fn uri_encode_path(path: &str) -> String {
path.split('/')
.map(|s| urlencoding::encode(s))
.collect::<Vec<_>>()
.join("/")
}
/// Turns `turbopack:///[project]` references in sourcemap sources into relative './' prefixed uris.
/// This is useful in server environments and especially build environments.
/// Turns `turbopack:///[project]` references in the map's sources into `./`-relative uris.
pub async fn relative_fileify_source_map(
map: Option<&Rope>,
map: &StructuredSourceMap,
context_path: FileSystemPath,
relative_path_to_output_root: RcStr,
) -> Result<Option<Rope>> {
) -> Result<StructuredSourceMap> {
let relative_path_to_output_root = relative_path_to_output_root
.split('/')
.map(|s| urlencoding::encode(s))
.collect::<Vec<_>>()
.join("/");
transform_relative_files(map, &context_path, |_context_fs, src_rest| {
// NOTE: we just include the relative path prefix here instead of using `sourceRoot`
// since the spec on sourceRoot is broken.
// TODO(bgw): this shouldn't be necessary to uri encode since the strings we get out of the
// source map should already be uri encoded, however in the case of the turbopack scheme in
// particular we are inconsistent so be defensive here.
let src_rest = uri_encode_path(src_rest);
if relative_path_to_output_root.is_empty() {
Ok(src_rest.to_string())
} else {
Ok(format!("{relative_path_to_output_root}/{src_rest}",))
Ok(format!("{relative_path_to_output_root}/{src_rest}"))
}
})
.await
......
......@@ -347,7 +347,7 @@ impl CssChunkItem for CssModuleChunkItem {
inner_code: output_code.to_owned().into(),
imports,
import_context: self.module.await?.import_context,
source_map: *source_map,
source_map: source_map.clone(),
}
.cell())
} else {
......@@ -358,7 +358,7 @@ impl CssChunkItem for CssModuleChunkItem {
.into(),
imports: vec![],
import_context: None,
source_map: FileContent::NotFound.resolved_cell(),
source_map: None,
}
.cell())
}
......
......@@ -31,6 +31,7 @@ use turbopack_core::{
server_fs::ServerFileSystem,
source_map::{
GenerateSourceMap,
structured::StructuredSourceMap,
utils::{absolute_fileify_source_map, relative_fileify_source_map},
},
};
......@@ -97,28 +98,26 @@ impl CssChunk {
let close = write_import_context(&mut body, content.import_context).await?;
let chunking_context = self.chunking_context();
let source_map = content.source_map.await?;
let source_map = source_map.as_content().map(|f| f.content());
let source_map = match *chunking_context.source_map_source_type().await? {
SourceMapSourceType::AbsoluteFileUri => {
absolute_fileify_source_map(
source_map,
chunking_context.root_path().owned().await?,
)
.await?
}
SourceMapSourceType::RelativeUri => {
let source_map = match (
*chunking_context.source_map_source_type().await?,
&content.source_map,
) {
(SourceMapSourceType::AbsoluteFileUri, Some(map)) => Some(
absolute_fileify_source_map(map, chunking_context.root_path().owned().await?)
.await?,
),
(SourceMapSourceType::RelativeUri, Some(map)) => Some(
relative_fileify_source_map(
source_map,
map,
chunking_context.root_path().owned().await?,
chunking_context
.relative_path_from_chunk_root_to_project_root()
.owned()
.await?,
)
.await?
}
SourceMapSourceType::TurbopackUri => source_map.cloned(),
.await?,
),
(_, map) => map.clone(),
};
body.push_source(&content.inner_code, source_map);
......@@ -452,7 +451,7 @@ pub struct CssChunkItemContent {
pub import_context: Option<ResolvedVc<ImportContext>>,
pub imports: Vec<CssImport>,
pub inner_code: Rope,
pub source_map: ResolvedVc<FileContent>,
pub source_map: Option<StructuredSourceMap>,
}
#[turbo_tasks::value_trait]
......
......@@ -66,14 +66,7 @@ impl SingleItemCssChunk {
let content = this.item.content().await?;
let close = write_import_context(&mut code, content.import_context).await?;
code.push_source(
&content.inner_code,
content
.source_map
.await?
.as_content()
.map(|f| f.content().clone()),
);
code.push_source(&content.inner_code, content.source_map.clone());
write!(code, "{close}")?;
let c = code.build().cell();
......
......@@ -5,7 +5,7 @@ use lightningcss::css_modules::CssModuleReference;
use swc_core::common::{BytePos, FileName, LineCol, SourceMap};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, ResolvedVc, Vc, turbofmt};
use turbo_tasks_fs::{FileSystemPath, rope::Rope};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
chunk::{AsyncModuleInfo, ChunkableModule, ChunkingContext, ModuleChunkItemIdExt},
context::{AssetContext, ProcessResult},
......@@ -16,6 +16,7 @@ use turbopack_core::{
reference_type::{CssReferenceSubType, ReferenceType},
resolve::{origin::ResolveOrigin, parse::Request},
source::{OptionSource, Source},
source_map::structured::StructuredSourceMap,
};
use turbopack_ecmascript::{
chunk::{
......@@ -369,7 +370,7 @@ impl ResolveOrigin for EcmascriptCssModule {
}
}
fn generate_minimal_source_map(filename: String, source: String) -> Result<Rope> {
fn generate_minimal_source_map(filename: String, source: String) -> Result<StructuredSourceMap> {
let mut mappings = vec![];
// Start from 1 because 0 is reserved for dummy spans in SWC.
let mut pos = 1;
......
......@@ -19,7 +19,7 @@ use swc_core::base::sourcemap::SourceMapBuilder;
use tracing::Instrument;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::{File, FileContent, FileSystemPath, rope::Rope};
use turbo_tasks_fs::{FileContent, FileSystemPath};
use turbopack_core::{
SOURCE_URL_PROTOCOL,
asset::{Asset, AssetContent},
......@@ -33,7 +33,7 @@ use turbopack_core::{
reference_type::ImportContext,
resolve::origin::ResolveOrigin,
source::Source,
source_map::utils::add_default_ignore_list,
source_map::{structured::StructuredSourceMap, utils::add_default_ignore_list},
source_pos::SourcePos,
};
......@@ -46,7 +46,7 @@ use crate::{
},
};
pub type CssOutput = (ToCssResult, Option<Rope>);
pub type CssOutput = (ToCssResult, Option<StructuredSourceMap>);
#[turbo_tasks::value(transparent)]
struct LightningCssTargets(
......@@ -191,12 +191,13 @@ pub enum CssWithPlaceholderResult {
}
#[turbo_tasks::value(shared, serialization = "skip")]
#[allow(clippy::large_enum_variant)] // This is a turbo-tasks value
pub enum FinalCssResult {
Ok {
#[turbo_tasks(trace_ignore)]
output_code: String,
source_map: ResolvedVc<FileContent>,
source_map: Option<StructuredSourceMap>,
},
Unparsable,
NotFound,
......@@ -329,11 +330,7 @@ pub async fn finalize_css(
Ok(FinalCssResult::Ok {
output_code: result.code,
source_map: if let Some(srcmap) = srcmap {
FileContent::Content(File::from(srcmap)).resolved_cell()
} else {
FileContent::NotFound.resolved_cell()
},
source_map: srcmap,
}
.cell())
}
......@@ -733,7 +730,9 @@ impl lightningcss::visitor::Visitor<'_> for CssValidator {
}
}
fn generate_css_source_map(source_map: &parcel_sourcemap::SourceMap) -> Result<Rope> {
fn generate_css_source_map(
source_map: &parcel_sourcemap::SourceMap,
) -> Result<StructuredSourceMap> {
let mut builder = SourceMapBuilder::new(None);
for src in source_map.get_sources() {
......@@ -758,9 +757,7 @@ fn generate_css_source_map(source_map: &parcel_sourcemap::SourceMap) -> Result<R
let mut map = builder.into_sourcemap();
add_default_ignore_list(&mut map);
let mut result = vec![];
map.to_writer(&mut result)?;
Ok(Rope::from(result))
StructuredSourceMap::from_swc_map(map)
}
#[turbo_tasks::value]
......
......@@ -20,7 +20,10 @@ use turbopack_core::{
module::Module,
module_graph::ModuleGraph,
output::OutputAssetsReference,
source_map::utils::{absolute_fileify_source_map, relative_fileify_source_map},
source_map::{
structured::StructuredSourceMap,
utils::{absolute_fileify_source_map, relative_fileify_source_map},
},
};
use crate::{
......@@ -46,7 +49,7 @@ pub enum RewriteSourcePath {
#[derive(Default, Clone)]
pub struct EcmascriptChunkItemContent {
pub inner_code: Rope,
pub source_map: Option<Rope>,
pub source_map: Option<StructuredSourceMap>,
pub additional_ids: SmallVec<[ModuleId; 1]>,
pub options: EcmascriptChunkItemOptions,
pub rewrite_source_path: RewriteSourcePath,
......@@ -165,19 +168,14 @@ impl EcmascriptChunkItemContent {
code += " try {\n";
}
let source_map = match &self.rewrite_source_path {
RewriteSourcePath::AbsoluteFilePath(path) => {
absolute_fileify_source_map(self.source_map.as_ref(), path.clone()).await?
let source_map = match (&self.rewrite_source_path, &self.source_map) {
(RewriteSourcePath::AbsoluteFilePath(path), Some(map)) => {
Some(absolute_fileify_source_map(map, path.clone()).await?)
}
RewriteSourcePath::RelativeFilePath(path, relative_path) => {
relative_fileify_source_map(
self.source_map.as_ref(),
path.clone(),
relative_path.clone(),
)
.await?
(RewriteSourcePath::RelativeFilePath(path, relative_path), Some(map)) => {
Some(relative_fileify_source_map(map, path.clone(), relative_path.clone()).await?)
}
RewriteSourcePath::None => self.source_map.clone(),
(_, map) => map.clone(),
};
code.push_source(&self.inner_code, source_map);
......
......@@ -98,7 +98,7 @@ use turbopack_core::{
reference_type::InnerAssets,
resolve::{FindContextFileResult, find_context_file, origin::ResolveOrigin, package_json},
source::Source,
source_map::GenerateSourceMap,
source_map::{GenerateSourceMap, structured::StructuredSourceMap},
};
use crate::{
......@@ -933,7 +933,7 @@ impl ResolveOrigin for EcmascriptModuleAsset {
#[turbo_tasks::value(shared)]
pub struct EcmascriptModuleContent {
pub inner_code: Rope,
pub source_map: Option<Rope>,
pub source_map: Option<StructuredSourceMap>,
pub is_esm: bool,
pub strict: bool,
pub additional_ids: SmallVec<[ModuleId; 1]>,
......
......@@ -163,7 +163,7 @@ pub fn minify(code: Code, source_maps: bool, mangle: Option<MangleType>) -> Resu
)?),
);
} else {
builder.push_source(&src.into(), None);
builder.push_source(&src.into(), None::<turbo_tasks_fs::rope::Rope>);
}
Ok(builder.build())
}
......
......@@ -40,7 +40,7 @@ use turbopack_core::{
asset::{Asset, AssetContent},
issue::{Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, StyledString},
source::Source,
source_map::utils::add_default_ignore_list,
source_map::{structured::StructuredSourceMap, utils::add_default_ignore_list},
};
use turbopack_swc_utils::emitter::IssueEmitter;
......@@ -171,6 +171,11 @@ pub enum ParseResult {
NotFound,
}
/// Generates a [`StructuredSourceMap`] for the transformed code, whose `sourcesContent`
/// entries are individual shared ropes instead of being embedded in the serialized JSON. This
/// keeps later `sources` URL rewrites and map embedding from copying the source text of every
/// module. Serialize with [`StructuredSourceMap::to_rope`] where raw bytes are needed.
///
/// `original_source_maps_complete` indicates whether the `original_source_maps` cover the whole
/// map, i.e. whether every module that ended up in `mappings` had an original sourcemap.
#[instrument(level = "info", name = "generate source map", skip_all)]
......@@ -181,7 +186,7 @@ pub fn generate_js_source_map<'a>(
original_source_maps_complete: bool,
inline_sources_content: bool,
names: FxHashMap<BytePos, Atom>,
) -> Result<Rope> {
) -> Result<StructuredSourceMap> {
let original_source_maps = original_source_maps
.into_iter()
.map(|map| map.to_bytes())
......@@ -211,14 +216,8 @@ pub fn generate_js_source_map<'a>(
);
if original_source_maps.is_empty() {
// We don't convert sourcemap::SourceMap into raw_sourcemap::SourceMap because we don't
// need to adjust mappings
add_default_ignore_list(&mut new_mappings);
let mut result = vec![];
new_mappings.to_writer(&mut result)?;
Ok(Rope::from(result))
StructuredSourceMap::from_swc_map(new_mappings)
} else if fast_path_single_original_source_map {
let mut map = original_source_maps.into_iter().next().unwrap();
// TODO: Make this more efficient
......@@ -227,16 +226,15 @@ pub fn generate_js_source_map<'a>(
// TODO: Enable this when we have a way to handle the ignore list
// add_default_ignore_list(&mut map);
let map = map.into_raw_sourcemap();
let result = serde_json::to_vec(&map)?;
Ok(Rope::from(result))
// The fallback covers raw maps with fields the structured form does not know.
StructuredSourceMap::from_serialize(&map)
.or_else(|_| StructuredSourceMap::from_json_slice(&serde_json::to_vec(&map)?))
} else {
let mut map = new_mappings.adjust_mappings_from_multiple(original_source_maps);
add_default_ignore_list(&mut map);
let mut result = vec![];
map.to_writer(&mut result)?;
Ok(Rope::from(result))
StructuredSourceMap::from_swc_map(map)
}
}
......
......@@ -121,7 +121,7 @@ impl GenerateSourceMap for SingleFileEcmascriptOutput {
true,
Default::default(),
)?;
Ok(FileContent::Content(File::from(map)).cell())
Ok(FileContent::Content(File::from(map.to_rope())).cell())
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment