Unverified Commit 58b627c1 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: store serialized sourcemaps instead (#75791)

Store sourcemaps JSON-serialized (as opposed to structs containing arrays of decoded mappings), which is more memory efficient (and the main operation we perform is concatenation anyway, lookups are only used for error message locations)

This will also deduplicate sourcemaps (because cloning a `Rope` is just a reference-counted pointer).

```
testing against 0293c96cf32

canary e5fc495e
19,1 GB
TURBO_ENGINE_READ_ONLY=1 NEXT_TURBOPACK_TRACING= TURBOPACK=1 TURBOPACK_BUILD=  526.06s user 87.43s system 853% cpu 1:11.91 total
TURBO_ENGINE_READ_ONLY=1 NEXT_TURBOPACK_TRACING= TURBOPACK=1 TURBOPACK_BUILD=  510.69s user 82.93s system 835% cpu 1:11.06 total

sourcemap-rope 2dc238215a
16.94 GB

TURBO_ENGINE_READ_ONLY=1 NEXT_TURBOPACK_TRACING= TURBOPACK=1 TURBOPACK_BUILD=  535.61s user 85.04s system 855% cpu 1:12.55 total
TURBO_ENGINE_READ_ONLY=1 NEXT_TURBOPACK_TRACING= TURBOPACK=1 TURBOPACK_BUILD=  531.07s user 82.25s system 861% cpu 1:11.22 total
```
parent f2dd61da
......@@ -9695,6 +9695,7 @@ dependencies = [
"anyhow",
"async-trait",
"criterion",
"data-encoding",
"either",
"indexmap 2.7.1",
"indoc",
......
......@@ -39,7 +39,7 @@ use turbopack_core::{
diagnostics::PlainDiagnostic,
error::PrettyPrintError,
issue::PlainIssue,
source_map::{SourceMap, Token},
source_map::{OptionSourceMap, OptionStringifiedSourceMap, SourceMap, Token},
version::{PartialUpdate, TotalUpdate, Update, VersionState},
SOURCE_MAP_PREFIX,
};
......@@ -1113,10 +1113,10 @@ pub struct StackFrame {
pub method_name: Option<String>,
}
pub async fn get_source_map(
pub async fn get_source_map_rope(
container: Vc<ProjectContainer>,
file_path: String,
) -> Result<Option<ResolvedVc<SourceMap>>> {
) -> Result<Option<Vc<OptionStringifiedSourceMap>>> {
let (file, module) = match Url::parse(&file_path) {
Ok(url) => match url.scheme() {
"file" => {
......@@ -1153,20 +1153,31 @@ pub async fn get_source_map(
.client_relative_path()
.join(chunk_base.into());
let mut map = container
.get_source_map(server_path, module.clone())
.await?;
let mut map = container.get_source_map(server_path, module.clone());
if map.is_none() {
if map.await?.is_none() {
// If the chunk doesn't exist as a server chunk, try a client chunk.
// TODO: Properly tag all server chunks and use the `isServer` query param.
// Currently, this is inaccurate as it does not cover RSC server
// chunks.
map = container.get_source_map(client_path, module).await?;
map = container.get_source_map(client_path, module);
}
if map.await?.is_none() {
bail!("chunk/module is missing a sourcemap");
}
let map = map.context("chunk/module is missing a sourcemap")?;
Ok(Some(map))
}
pub async fn get_source_map(
container: Vc<ProjectContainer>,
file_path: String,
) -> Result<Option<ReadRef<OptionSourceMap>>> {
let Some(map) = get_source_map_rope(container, file_path).await? else {
return Ok(None);
};
let map = SourceMap::new_from_rope_cached(map).await?;
Ok(Some(map))
}
......@@ -1183,6 +1194,9 @@ pub async fn project_trace_source(
let Some(map) = get_source_map(container, frame.file).await? else {
return Ok(None);
};
let Some(map) = &*map else {
return Ok(None);
};
let Some(line) = frame.line else {
return Ok(None);
......@@ -1195,7 +1209,7 @@ pub async fn project_trace_source(
)
.await?;
let (original_file, line, column, name) = match &*token {
let (original_file, line, column, name) = match token {
Token::Original(token) => (
urlencoding::decode(&token.original_file)?.into_owned(),
// JS stack frames are 1-indexed, source map tokens are 0-indexed
......@@ -1307,11 +1321,13 @@ pub async fn project_get_source_map(
let source_map = turbo_tasks
.run_once(async move {
let Some(map) = get_source_map(container, file_path).await? else {
let Some(map) = get_source_map_rope(container, file_path).await? else {
return Ok(None);
};
Ok(Some(map.to_rope().await?.to_str()?.into_owned()))
let Some(map) = &*map.await? else {
return Ok(None);
};
Ok(Some(map.to_str()?.to_string()))
})
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))?;
......
......@@ -56,7 +56,7 @@ use turbopack_core::{
module_graph::{ModuleGraph, SingleModuleGraph, VisitedModules},
output::{OutputAsset, OutputAssets},
resolve::{find_context_file, FindContextFileResult},
source_map::OptionSourceMap,
source_map::OptionStringifiedSourceMap,
version::{
NotFoundVersion, OptionVersionedContent, Update, Version, VersionState, VersionedContent,
},
......@@ -493,11 +493,11 @@ impl ProjectContainer {
&self,
file_path: Vc<FileSystemPath>,
section: Option<RcStr>,
) -> Vc<OptionSourceMap> {
) -> Vc<OptionStringifiedSourceMap> {
if let Some(map) = self.versioned_content_map {
map.get_source_map(file_path, section)
} else {
OptionSourceMap::none()
OptionStringifiedSourceMap::none()
}
}
}
......
......@@ -12,7 +12,7 @@ use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
asset::Asset,
output::{OptionOutputAsset, OutputAsset, OutputAssets},
source_map::{GenerateSourceMap, OptionSourceMap},
source_map::{GenerateSourceMap, OptionStringifiedSourceMap},
version::OptionVersionedContent,
};
......@@ -189,7 +189,7 @@ impl VersionedContentMap {
self: Vc<Self>,
path: Vc<FileSystemPath>,
section: Option<RcStr>,
) -> Result<Vc<OptionSourceMap>> {
) -> Result<Vc<OptionStringifiedSourceMap>> {
let Some(asset) = &*self.get_asset(path).await? else {
return Ok(Vc::cell(None));
};
......
......@@ -247,10 +247,7 @@ impl Issue for NextSegmentConfigParsingIssue {
#[turbo_tasks::function]
async fn source(&self) -> Result<Vc<OptionIssueSource>> {
Ok(Vc::cell(Some(
self.source
.resolve_source_map(self.ident.path())
.await?
.into_owned(),
self.source.resolve_source_map().await?.into_owned(),
)))
}
}
......
......@@ -217,9 +217,7 @@ describe('app-dir - server source maps', () => {
// Node.js is fine with invalid URLs in index maps apparently.
'' +
'\nError: Boom!' +
// TODO(veil): Turbopack's sourcemap loader generates a wrong source entry here
// Should not be sourcemapped or "custom://[badhost]/app/bad-sourcemap/page.js"
'\n at Page (app/bad-sourcemap/custom:/[badhost]/app/bad-sourcemap/page.js:9:15)' +
'\n at Page (custom://[badhost]/app/bad-sourcemap/page.js:9:15)' +
// TODO: Remove blank line
'\n'
)
......
......@@ -7,7 +7,7 @@ use turbopack_core::{
chunk::{Chunk, ChunkingContext, OutputChunk, OutputChunkRuntimeInfo},
introspect::{Introspectable, IntrospectableChildren},
output::{OutputAsset, OutputAssets},
source_map::{GenerateSourceMap, OptionSourceMap, SourceMapAsset},
source_map::{GenerateSourceMap, OptionStringifiedSourceMap, SourceMapAsset},
version::VersionedContent,
};
use turbopack_ecmascript::chunk::EcmascriptChunk;
......@@ -132,12 +132,12 @@ impl Asset for EcmascriptDevChunk {
#[turbo_tasks::value_impl]
impl GenerateSourceMap for EcmascriptDevChunk {
#[turbo_tasks::function]
fn generate_source_map(self: Vc<Self>) -> Vc<OptionSourceMap> {
fn generate_source_map(self: Vc<Self>) -> Vc<OptionStringifiedSourceMap> {
self.own_content().generate_source_map()
}
#[turbo_tasks::function]
fn by_section(self: Vc<Self>, section: RcStr) -> Vc<OptionSourceMap> {
fn by_section(self: Vc<Self>, section: RcStr) -> Vc<OptionStringifiedSourceMap> {
self.own_content().by_section(section)
}
}
......
......@@ -10,7 +10,7 @@ use turbopack_core::{
chunk::{ChunkingContext, MinifyType, ModuleId},
code_builder::{Code, CodeBuilder},
output::OutputAsset,
source_map::{GenerateSourceMap, OptionSourceMap},
source_map::{GenerateSourceMap, OptionStringifiedSourceMap},
version::{MergeableVersionedContent, Version, VersionedContent, VersionedContentMerger},
};
use turbopack_ecmascript::{chunk::EcmascriptChunkContent, minify::minify, utils::StringifyJs};
......@@ -157,12 +157,12 @@ impl MergeableVersionedContent for EcmascriptDevChunkContent {
#[turbo_tasks::value_impl]
impl GenerateSourceMap for EcmascriptDevChunkContent {
#[turbo_tasks::function]
fn generate_source_map(self: Vc<Self>) -> Vc<OptionSourceMap> {
fn generate_source_map(self: Vc<Self>) -> Vc<OptionStringifiedSourceMap> {
self.code().generate_source_map()
}
#[turbo_tasks::function]
async fn by_section(&self, section: RcStr) -> Result<Vc<OptionSourceMap>> {
async fn by_section(&self, section: RcStr) -> Result<Vc<OptionStringifiedSourceMap>> {
// Weirdly, the ContentSource will have already URL decoded the ModuleId, and we
// can't reparse that via serde.
if let Ok(id) = ModuleId::parse(&section) {
......
......@@ -17,7 +17,7 @@ use turbopack_core::{
module::Module,
module_graph::ModuleGraph,
output::{OutputAsset, OutputAssets},
source_map::{GenerateSourceMap, OptionSourceMap, SourceMapAsset},
source_map::{GenerateSourceMap, OptionStringifiedSourceMap, SourceMapAsset},
};
use turbopack_ecmascript::{
chunk::{EcmascriptChunkData, EcmascriptChunkPlaceable},
......@@ -281,7 +281,7 @@ impl Asset for EcmascriptDevEvaluateChunk {
#[turbo_tasks::value_impl]
impl GenerateSourceMap for EcmascriptDevEvaluateChunk {
#[turbo_tasks::function]
fn generate_source_map(self: Vc<Self>) -> Vc<OptionSourceMap> {
fn generate_source_map(self: Vc<Self>) -> Vc<OptionStringifiedSourceMap> {
self.code().generate_source_map()
}
}
......
......@@ -83,15 +83,8 @@ struct EcmascriptModuleEntry {
impl EcmascriptModuleEntry {
async fn from_code(id: &ModuleId, code: Vc<Code>, chunk_path: &str) -> Result<Self> {
let map = match &*code.generate_source_map().await? {
Some(map) => {
// Cloning a rope is cheap.
Some(map.to_rope().owned().await?)
}
None => None,
};
Ok(Self::new(id, code.await?, map, chunk_path))
let map = &*code.generate_source_map().await?;
Ok(Self::new(id, code.await?, map.clone(), chunk_path))
}
fn new(id: &ModuleId, code: ReadRef<Code>, map: Option<Rope>, chunk_path: &str) -> Self {
......
......@@ -4,24 +4,18 @@ use std::{
ops,
};
use anyhow::{Context, Result};
use indexmap::IndexMap;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{
rope::{Rope, RopeBuilder},
util::uri_from_file,
DiskFileSystem, FileSystemPath,
};
use anyhow::Result;
use turbo_tasks::Vc;
use turbo_tasks_fs::rope::{Rope, RopeBuilder};
use turbo_tasks_hash::hash_xxh3_hash64;
use crate::{
source_map::{GenerateSourceMap, OptionSourceMap, SourceMap, SourceMapSection},
source_map::{GenerateSourceMap, OptionStringifiedSourceMap, SourceMap},
source_pos::SourcePos,
SOURCE_MAP_PREFIX,
};
/// A mapping of byte-offset in the code string to an associated source map.
pub type Mapping = (usize, Option<ResolvedVc<Box<dyn GenerateSourceMap>>>);
pub type Mapping = (usize, Option<Rope>);
/// Code stores combined output code and the source map of that output code.
#[turbo_tasks::value(shared)]
......@@ -31,13 +25,6 @@ pub struct Code {
mappings: Vec<Mapping>,
}
/// CodeBuilder provides a mutable container to append source code.
#[derive(Default)]
pub struct CodeBuilder {
code: RopeBuilder,
mappings: Vec<Mapping>,
}
impl Code {
pub fn source_code(&self) -> &Rope {
&self.code
......@@ -49,6 +36,13 @@ impl Code {
}
}
/// CodeBuilder provides a mutable container to append source code.
#[derive(Default)]
pub struct CodeBuilder {
code: RopeBuilder,
mappings: Vec<Mapping>,
}
impl CodeBuilder {
/// Pushes synthetic runtime code without an associated source map. This is
/// the default concatenation operation, but it's designed to be used
......@@ -61,11 +55,7 @@ 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<ResolvedVc<Box<dyn GenerateSourceMap>>>,
) {
pub fn push_source(&mut self, code: &Rope, map: Option<Rope>) {
self.push_map(map);
self.code += code;
}
......@@ -86,7 +76,7 @@ impl CodeBuilder {
prebuilt
.mappings
.iter()
.map(|(index, map)| (index + len, *map)),
.map(|(index, map)| (index + len, map.clone())),
);
} else {
self.push_map(None);
......@@ -100,7 +90,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<ResolvedVc<Box<dyn GenerateSourceMap>>>) {
fn push_map(&mut self, map: Option<Rope>) {
if map.is_none() && matches!(self.mappings.last(), None | Some((_, None))) {
// No reason to push an empty map directly after an empty map
return;
......@@ -160,7 +150,7 @@ impl GenerateSourceMap for Code {
/// far the simplest way to concatenate the source maps of the multiple
/// chunk items into a single map file.
#[turbo_tasks::function]
pub async fn generate_source_map(&self) -> Result<Vc<OptionSourceMap>> {
pub async fn generate_source_map(&self) -> Result<Vc<OptionStringifiedSourceMap>> {
let mut pos = SourcePos::new();
let mut last_byte_pos = 0;
......@@ -180,20 +170,11 @@ impl GenerateSourceMap for Code {
}
last_byte_pos = *byte_pos;
let encoded = match map {
None => SourceMap::empty().to_resolved().await?,
Some(map) => match *map.generate_source_map().await? {
None => SourceMap::empty().to_resolved().await?,
Some(map) => map,
},
};
sections.push(SourceMapSection::new(pos, encoded))
sections.push((pos, map.clone().unwrap_or_else(SourceMap::empty_rope)))
}
Ok(Vc::cell(Some(
SourceMap::new_sectioned(sections).resolved_cell(),
)))
let source_map = SourceMap::sections_to_rope(sections)?;
Ok(Vc::cell(Some(source_map)))
}
}
......@@ -207,49 +188,3 @@ impl Code {
Vc::cell(hash)
}
}
/// Turns `turbopack://[project]`` references in sourcemap sources into absolute
/// `file://` uris. This is useful for debugging environments.
#[turbo_tasks::function]
pub async fn fileify_source_map(
map: Vc<OptionSourceMap>,
context_path: Vc<FileSystemPath>,
) -> Result<Vc<OptionSourceMap>> {
let Some(map) = &*map.await? else {
return Ok(OptionSourceMap::none());
};
let flattened = map.await?.to_source_map().await?;
let flattened = flattened.as_regular_source_map();
let Some(flattened) = flattened else {
return Ok(OptionSourceMap::none());
};
let context_fs = context_path.fs();
let context_fs = &*Vc::try_resolve_downcast_type::<DiskFileSystem>(context_fs)
.await?
.context("Expected the chunking context to have a DiskFileSystem")?
.await?;
let prefix = format!("{}[{}]/", SOURCE_MAP_PREFIX, context_fs.name());
let mut transformed = flattened.into_owned();
let mut updates = IndexMap::new();
for (src_id, src) in transformed.sources().enumerate() {
let src = {
match src.strip_prefix(&prefix) {
Some(src) => uri_from_file(context_path, Some(src)).await?,
None => src.to_string(),
}
};
updates.insert(src_id, src);
}
for (src_id, src) in updates {
transformed.set_source(src_id as _, &src);
}
Ok(Vc::cell(Some(
SourceMap::new_decoded(sourcemap::DecodedMap::Regular(transformed)).resolved_cell(),
)))
}
......@@ -82,12 +82,7 @@ impl Issue for AnalyzeIssue {
#[turbo_tasks::function]
async fn source(&self) -> Result<Vc<OptionIssueSource>> {
Ok(Vc::cell(match &self.source {
Some(source) => Some(
source
.resolve_source_map(self.source_ident.path())
.await?
.into_owned(),
),
Some(source) => Some(source.resolve_source_map().await?.into_owned()),
None => None,
}))
}
......
......@@ -25,7 +25,7 @@ use turbo_tasks_hash::{DeterministicHash, Xxh3Hash64Hasher};
use crate::{
asset::{Asset, AssetContent},
source::Source,
source_map::{convert_to_turbopack_source_map, GenerateSourceMap, TokenWithSource},
source_map::{GenerateSourceMap, SourceMap, TokenWithSource},
source_pos::SourcePos,
};
......@@ -475,7 +475,7 @@ impl IssueSource {
}
}
pub async fn resolve_source_map(&self, origin: Vc<FileSystemPath>) -> Result<Cow<'_, Self>> {
pub async fn resolve_source_map(&self) -> Result<Cow<'_, Self>> {
if let Some(range) = &self.range {
let (start, end) = match range {
SourceRange::LineColumn(start, end) => (*start, *end),
......@@ -491,7 +491,7 @@ impl IssueSource {
};
// If we have a source map, map the line/column to the original source.
let mapped = source_pos(self.source, origin, start, end).await?;
let mapped = source_pos(self.source, start, end).await?;
if let Some((source, start, end)) = mapped {
return Ok(Cow::Owned(IssueSource {
......@@ -579,7 +579,6 @@ impl IssueSource {
async fn source_pos(
source: ResolvedVc<Box<dyn Source>>,
origin: Vc<FileSystemPath>,
start: SourcePos,
end: SourcePos,
) -> Result<Option<(ResolvedVc<Box<dyn Source>>, SourcePos, SourcePos)>> {
......@@ -588,26 +587,25 @@ async fn source_pos(
};
let srcmap = generator.generate_source_map();
let Some(srcmap) = *convert_to_turbopack_source_map(srcmap, origin).await? else {
let Some(srcmap) = &*SourceMap::new_from_rope_cached(srcmap).await? else {
return Ok(None);
};
let find = |line: u32, col: u32| async move {
let find = async |line: u32, col: u32| {
let TokenWithSource {
token,
source_content,
} = &*srcmap.lookup_token_and_source(line, col).await?;
} = &srcmap.lookup_token_and_source(line, col).await?;
match &*token.await? {
crate::source_map::Token::Synthetic(t) => Ok::<_, anyhow::Error>((
match token {
crate::source_map::Token::Synthetic(t) => anyhow::Ok((
SourcePos {
line: t.generated_line as _,
column: t.generated_column as _,
},
*source_content,
)),
crate::source_map::Token::Original(t) => Ok((
crate::source_map::Token::Original(t) => anyhow::Ok((
SourcePos {
line: t.original_line as _,
column: t.original_column as _,
......
......@@ -118,12 +118,7 @@ impl Issue for ResolvingIssue {
#[turbo_tasks::function]
async fn source(&self) -> Result<Vc<OptionIssueSource>> {
Ok(Vc::cell(match &self.source {
Some(source) => Some(
source
.resolve_source_map(*self.file_path)
.await?
.into_owned(),
),
Some(source) => Some(source.resolve_source_map().await?.into_owned()),
None => None,
}))
}
......
......@@ -8,7 +8,9 @@ use crate::{
file_source::FileSource,
raw_module::RawModule,
resolve::ModuleResolveResult,
source_map::{GenerateSourceMap, OptionSourceMap, SourceMap},
source_map::{
utils::resolve_source_map_sources, GenerateSourceMap, OptionStringifiedSourceMap,
},
};
#[turbo_tasks::value]
......@@ -56,12 +58,15 @@ impl ModuleReference for SourceMapReference {
#[turbo_tasks::value_impl]
impl GenerateSourceMap for SourceMapReference {
#[turbo_tasks::function]
async fn generate_source_map(&self) -> Result<Vc<OptionSourceMap>> {
async fn generate_source_map(&self) -> Result<Vc<OptionStringifiedSourceMap>> {
let Some(file) = self.get_file().await else {
return Ok(Vc::cell(None));
};
let source_map = SourceMap::new_from_file(file).await?;
Ok(Vc::cell(source_map.map(|m| m.resolved_cell())))
let content = file.read().await?;
let content = content.as_content().map(|file| file.content());
let source_map = resolve_source_map_sources(content, *self.from).await?;
Ok(Vc::cell(source_map))
}
}
......
......@@ -43,13 +43,13 @@ impl Asset for SourceMapAsset {
else {
bail!("asset does not support generating source maps")
};
let sm = if let Some(sm) = &*generate_source_map.generate_source_map().await? {
**sm
if let Some(sm) = &*generate_source_map.generate_source_map().await? {
Ok(AssetContent::file(File::from(sm.clone()).into()))
} else {
SourceMap::empty()
};
let sm = sm.to_rope().await?;
Ok(AssetContent::file(File::from(sm).into()))
Ok(AssetContent::file(
File::from(SourceMap::empty_rope()).into(),
))
}
}
}
......
use std::collections::HashSet;
use anyhow::{Context, Result};
use const_format::concatcp;
use sourcemap::SourceMap;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use turbo_tasks::{ValueToString, Vc};
use turbo_tasks_fs::{
rope::Rope, util::uri_from_file, DiskFileSystem, FileContent, FileSystemPath,
};
use crate::SOURCE_MAP_PREFIX;
pub fn add_default_ignore_list(map: &mut SourceMap) {
pub fn add_default_ignore_list(map: &mut sourcemap::SourceMap) {
let mut ignored_ids = HashSet::new();
for (source_id, source) in map.sources().enumerate() {
......@@ -21,3 +28,166 @@ pub fn add_default_ignore_list(map: &mut SourceMap) {
map.add_to_ignore_list(ignored_id as _);
}
}
#[derive(Serialize, Deserialize)]
struct SourceMapSectionOffsetJson {
line: u32,
offset: u32,
}
#[derive(Serialize, Deserialize)]
struct SourceMapSectionItemJson {
offset: SourceMapSectionOffsetJson,
map: SourceMapJson,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SourceMapJson {
version: u32,
#[serde(skip_serializing_if = "Option::is_none")]
file: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
source_root: Option<String>,
// Technically a required field, but we don't want to error here.
#[serde(skip_serializing_if = "Option::is_none")]
sources: Option<Vec<Option<String>>>,
#[serde(skip_serializing_if = "Option::is_none")]
sources_content: Option<Vec<Option<String>>>,
#[serde(skip_serializing_if = "Option::is_none")]
names: Option<Vec<String>>,
mappings: String,
#[serde(skip_serializing_if = "Option::is_none")]
ignore_list: Option<Vec<u32>>,
// A somewhat widespread non-standard extension
debug_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
sections: Option<Vec<SourceMapSectionItemJson>>,
}
/// Replace the origin prefix in the `sources` with `turbopack://` and read the the `sourceContent`s
/// from disk.
pub async fn resolve_source_map_sources(
map: Option<&Rope>,
origin: Vc<FileSystemPath>,
) -> Result<Option<Rope>> {
async fn resolve_source(
original_source: &mut String,
original_content: &mut Option<String>,
origin: Vc<FileSystemPath>,
) -> Result<()> {
if let Some(path) = *origin
.parent()
.try_join((&**original_source).into())
.await?
{
let path_str = path.to_string().await?;
let source = format!("{SOURCE_MAP_PREFIX}{}", path_str);
*original_source = source;
if original_content.is_none() {
if let FileContent::Content(file) = &*path.read().await? {
let text = file.content().to_str()?;
*original_content = Some(text.to_string())
} else {
*original_content = Some(format!("unable to read source {path_str}"));
}
}
} else {
let origin_str = origin.to_string().await?;
static INVALID_REGEX: Lazy<Regex> =
Lazy::new(|| Regex::new(r#"(?:^|/)(?:\.\.?(?:/|$))+"#).unwrap());
let source = INVALID_REGEX.replace_all(original_source, |s: &regex::Captures<'_>| {
s[0].replace('.', "_")
});
*original_source = format!("{SOURCE_MAP_PREFIX}{}/{}", origin_str, source);
if original_content.is_none() {
*original_content = Some(format!(
"unable to access {original_source} in {origin_str} (it's leaving the \
filesystem root)"
));
}
}
anyhow::Ok(())
}
async fn resolve_map(map: &mut SourceMapJson, origin: Vc<FileSystemPath>) -> Result<()> {
if let Some(sources) = &mut map.sources {
let mut contents = if let Some(mut contents) = map.sources_content.take() {
contents.resize(sources.len(), None);
contents
} else {
Vec::with_capacity(sources.len())
};
for (source, content) in sources.iter_mut().zip(contents.iter_mut()) {
if let Some(source) = source {
resolve_source(source, content, origin).await?;
}
}
map.sources_content = Some(contents);
}
Ok(())
}
let Some(map) = map else {
return Ok(None);
};
let mut map: SourceMapJson = serde_json::from_reader(map.read())?;
resolve_map(&mut map, origin).await?;
for section in map.sections.iter_mut().flatten() {
resolve_map(&mut section.map, origin).await?;
}
let map = Rope::from(serde_json::to_vec(&map)?);
Ok(Some(map))
}
/// Turns `turbopack://[project]` references in sourcemap sources into absolute `file://` uris. This
/// is useful for debugging environments.
pub async fn fileify_source_map(
map: Option<&Rope>,
context_path: Vc<FileSystemPath>,
) -> Result<Option<Rope>> {
let Some(map) = map else {
return Ok(None);
};
let context_fs = context_path.fs();
let context_fs = &*Vc::try_resolve_downcast_type::<DiskFileSystem>(context_fs)
.await?
.context("Expected the chunking context to have a DiskFileSystem")?
.await?;
let prefix = format!("{}[{}]/", SOURCE_MAP_PREFIX, context_fs.name());
// TODO this could be made (much) more efficient by not even de- and serializing other fields
// (apart from `sources`) and just keep storing them as strings.
let mut map: SourceMapJson = serde_json::from_reader(map.read())?;
let transform_source = async |src: &mut Option<String>| {
if let Some(src) = src {
if let Some(src_rest) = src.strip_prefix(&prefix) {
*src = uri_from_file(context_path, Some(src_rest)).await?;
}
}
anyhow::Ok(())
};
for src in map.sources.iter_mut().flatten() {
transform_source(src).await?;
}
for section in map.sections.iter_mut().flatten() {
for src in section.map.sources.iter_mut().flatten() {
transform_source(src).await?;
}
}
let map = Rope::from(serde_json::to_vec(&map)?);
Ok(Some(map))
}
......@@ -299,7 +299,7 @@ impl CssChunkItem for CssModuleChunkItem {
inner_code: output_code.to_owned().into(),
imports,
import_context: self.module.await?.import_context,
source_map: Some(*source_map),
source_map: source_map.owned().await?,
}
.into())
} else {
......
......@@ -13,7 +13,7 @@ use turbopack_core::{
round_chunk_item_size, AsyncModuleInfo, Chunk, ChunkItem, ChunkItemWithAsyncModuleInfo,
ChunkType, ChunkableModule, ChunkingContext, ModuleId, OutputChunk, OutputChunkRuntimeInfo,
},
code_builder::{fileify_source_map, Code, CodeBuilder},
code_builder::{Code, CodeBuilder},
ident::AssetIdent,
introspect::{
module::IntrospectableModule,
......@@ -24,11 +24,11 @@ use turbopack_core::{
output::{OutputAsset, OutputAssets},
reference_type::ImportContext,
server_fs::ServerFileSystem,
source_map::{GenerateSourceMap, OptionSourceMap},
source_map::{utils::fileify_source_map, GenerateSourceMap, OptionStringifiedSourceMap},
};
use self::{single_item_chunk::chunk::SingleItemCssChunk, source_map::CssChunkSourceMapAsset};
use crate::{process::ParseCssResultSourceMap, util::stringify_js, ImportAssetReference};
use crate::{util::stringify_js, ImportAssetReference};
#[turbo_tasks::value]
pub struct CssChunk {
......@@ -82,15 +82,13 @@ impl CssChunk {
.should_use_file_source_map_uris()
.await?
{
let source_map = content.source_map.map(|m| m.generate_source_map());
match source_map {
Some(map) => (*(fileify_source_map(map, self.chunking_context().root_path())
.await?))
.map(ResolvedVc::upcast),
None => None,
}
fileify_source_map(
content.source_map.as_ref(),
self.chunking_context().root_path(),
)
.await?
} else {
content.source_map.map(ResolvedVc::upcast)
content.source_map.clone()
};
body.push_source(&content.inner_code, source_map);
......@@ -344,7 +342,7 @@ impl Asset for CssChunk {
#[turbo_tasks::value_impl]
impl GenerateSourceMap for CssChunk {
#[turbo_tasks::function]
fn generate_source_map(self: Vc<Self>) -> Vc<OptionSourceMap> {
fn generate_source_map(self: Vc<Self>) -> Vc<OptionStringifiedSourceMap> {
self.code().generate_source_map()
}
}
......@@ -391,7 +389,7 @@ pub struct CssChunkItemContent {
pub import_context: Option<ResolvedVc<ImportContext>>,
pub imports: Vec<CssImport>,
pub inner_code: Rope,
pub source_map: Option<ResolvedVc<ParseCssResultSourceMap>>,
pub source_map: Option<Rope>,
}
#[turbo_tasks::value_trait]
......
......@@ -11,7 +11,7 @@ use turbopack_core::{
ident::AssetIdent,
introspect::Introspectable,
output::{OutputAsset, OutputAssets},
source_map::{GenerateSourceMap, OptionSourceMap},
source_map::{GenerateSourceMap, OptionStringifiedSourceMap},
};
use super::source_map::SingleItemCssChunkSourceMapAsset;
......@@ -57,10 +57,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.map(ResolvedVc::upcast),
);
code.push_source(&content.inner_code, content.source_map.clone());
write!(code, "{close}")?;
if *this
......@@ -146,7 +143,7 @@ impl Asset for SingleItemCssChunk {
#[turbo_tasks::value_impl]
impl GenerateSourceMap for SingleItemCssChunk {
#[turbo_tasks::function]
fn generate_source_map(self: Vc<Self>) -> Vc<OptionSourceMap> {
fn generate_source_map(self: Vc<Self>) -> Vc<OptionStringifiedSourceMap> {
self.code().generate_source_map()
}
}
......
......@@ -35,12 +35,12 @@ impl OutputAsset for SingleItemCssChunkSourceMapAsset {
impl Asset for SingleItemCssChunkSourceMapAsset {
#[turbo_tasks::function]
async fn content(&self) -> Result<Vc<AssetContent>> {
let sm = if let Some(sm) = *self.chunk.generate_source_map().await? {
*sm
if let Some(sm) = &*self.chunk.generate_source_map().await? {
Ok(AssetContent::file(File::from(sm.clone()).into()))
} else {
SourceMap::empty()
};
let sm = sm.to_rope().await?;
Ok(AssetContent::file(File::from(sm).into()))
Ok(AssetContent::file(
File::from(SourceMap::empty_rope()).into(),
))
}
}
}
......@@ -35,12 +35,12 @@ impl OutputAsset for CssChunkSourceMapAsset {
impl Asset for CssChunkSourceMapAsset {
#[turbo_tasks::function]
async fn content(&self) -> Result<Vc<AssetContent>> {
let sm = if let Some(sm) = *self.chunk.generate_source_map().await? {
*sm
if let Some(sm) = &*self.chunk.generate_source_map().await? {
Ok(AssetContent::file(File::from(sm.clone()).into()))
} else {
SourceMap::empty()
};
let sm = sm.to_rope().await?;
Ok(AssetContent::file(File::from(sm).into()))
Ok(AssetContent::file(
File::from(SourceMap::empty_rope()).into(),
))
}
}
}
......@@ -6,7 +6,7 @@ use lightningcss::css_modules::CssModuleReference;
use swc_core::common::{BytePos, FileName, LineCol, SourceMap};
use turbo_rcstr::RcStr;
use turbo_tasks::{FxIndexMap, ResolvedVc, Value, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_fs::{rope::Rope, FileSystemPath};
use turbopack_core::{
asset::{Asset, AssetContent},
chunk::{ChunkItem, ChunkItemExt, ChunkType, ChunkableModule, ChunkingContext},
......@@ -19,16 +19,16 @@ use turbopack_core::{
reference_type::{CssReferenceSubType, ReferenceType},
resolve::{origin::ResolveOrigin, parse::Request},
source::Source,
source_map::OptionSourceMap,
source_map::OptionStringifiedSourceMap,
};
use turbopack_ecmascript::{
chunk::{
EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkPlaceable,
EcmascriptChunkType, EcmascriptExports,
},
parse::generate_js_source_map,
runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_IMPORT},
utils::StringifyJs,
ParseResultSourceMap,
};
use crate::{
......@@ -410,13 +410,13 @@ impl EcmascriptChunkItem for ModuleChunkItem {
// We generate a minimal map for runtime code so that the filename is
// displayed in dev tools.
source_map: if source_map {
Some(ResolvedVc::upcast(
Some(
generate_minimal_source_map(
self.module.ident().to_string().await?.to_string(),
code,
)
.await?,
))
)
} else {
None
},
......@@ -426,10 +426,7 @@ impl EcmascriptChunkItem for ModuleChunkItem {
}
}
async fn generate_minimal_source_map(
filename: String,
source: String,
) -> Result<ResolvedVc<ParseResultSourceMap>> {
async fn generate_minimal_source_map(filename: String, source: String) -> Result<Rope> {
let mut mappings = vec![];
// Start from 1 because 0 is reserved for dummy spans in SWC.
let mut pos = 1;
......@@ -445,8 +442,13 @@ async fn generate_minimal_source_map(
}
let sm: Arc<SourceMap> = Default::default();
sm.new_source_file(FileName::Custom(filename).into(), source);
let map = ParseResultSourceMap::new(sm, mappings, OptionSourceMap::none().to_resolved().await?);
Ok(map.resolved_cell())
let map = generate_js_source_map(
sm,
mappings,
OptionStringifiedSourceMap::none().to_resolved().await?,
)
.await?;
Ok(map)
}
#[turbo_tasks::value(shared)]
......
......@@ -15,7 +15,7 @@ use swc_core::base::sourcemap::SourceMapBuilder;
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{FxIndexMap, ResolvedVc, TryJoinIterExt, ValueToString, Vc};
use turbo_tasks_fs::{FileContent, FileSystemPath};
use turbo_tasks_fs::{rope::Rope, FileContent, FileSystemPath};
use turbopack_core::{
asset::{Asset, AssetContent},
chunk::{ChunkingContext, MinifyType},
......@@ -28,7 +28,7 @@ use turbopack_core::{
reference_type::ImportContext,
resolve::origin::ResolveOrigin,
source::Source,
source_map::{utils::add_default_ignore_list, GenerateSourceMap, OptionSourceMap},
source_map::{utils::add_default_ignore_list, OptionStringifiedSourceMap},
source_pos::SourcePos,
SOURCE_MAP_PREFIX,
};
......@@ -51,7 +51,7 @@ impl PartialEq for StyleSheetLike<'_, '_> {
}
}
pub type CssOutput = (ToCssResult, Option<ParseCssResultSourceMap>);
pub type CssOutput = (ToCssResult, Option<Rope>);
impl StyleSheetLike<'_, '_> {
pub fn to_static(
......@@ -99,7 +99,12 @@ impl StyleSheetLike<'_, '_> {
srcmap.set_source_content(0, code)?;
}
Ok((result, srcmap.map(ParseCssResultSourceMap::new)))
let srcmap = match srcmap {
Some(srcmap) => Some(generate_css_source_map(&srcmap)?),
None => None,
};
Ok((result, srcmap))
}
}
......@@ -154,7 +159,7 @@ pub enum FinalCssResult {
#[turbo_tasks(trace_ignore)]
exports: Option<CssModuleExports>,
source_map: ResolvedVc<ParseCssResultSourceMap>,
source_map: ResolvedVc<OptionStringifiedSourceMap>,
},
Unparseable,
NotFound,
......@@ -259,7 +264,7 @@ pub async fn finalize_css(
Ok(FinalCssResult::Ok {
output_code: result.code,
exports: result.exports,
source_map: srcmap.unwrap().resolved_cell(),
source_map: ResolvedVc::cell(srcmap),
}
.into())
}
......@@ -572,57 +577,34 @@ impl lightningcss::visitor::Visitor<'_> for CssValidator {
}
}
#[turbo_tasks::value(shared, serialization = "none", eq = "manual")]
pub struct ParseCssResultSourceMap {
#[turbo_tasks(debug_ignore, trace_ignore)]
source_map: parcel_sourcemap::SourceMap,
}
fn generate_css_source_map(source_map: &parcel_sourcemap::SourceMap) -> Result<Rope> {
let mut builder = SourceMapBuilder::new(None);
impl PartialEq for ParseCssResultSourceMap {
fn eq(&self, _: &Self) -> bool {
false
for src in source_map.get_sources() {
builder.add_source(&format!("{SOURCE_MAP_PREFIX}{src}"));
}
}
impl ParseCssResultSourceMap {
pub fn new(source_map: parcel_sourcemap::SourceMap) -> Self {
ParseCssResultSourceMap { source_map }
for (idx, content) in source_map.get_sources_content().iter().enumerate() {
builder.set_source_contents(idx as _, Some(content));
}
}
#[turbo_tasks::value_impl]
impl GenerateSourceMap for ParseCssResultSourceMap {
#[turbo_tasks::function]
fn generate_source_map(&self) -> Vc<OptionSourceMap> {
let source_map = &self.source_map;
let mut builder = SourceMapBuilder::new(None);
for src in source_map.get_sources() {
builder.add_source(&format!("{SOURCE_MAP_PREFIX}{src}"));
}
for (idx, content) in source_map.get_sources_content().iter().enumerate() {
builder.set_source_contents(idx as _, Some(content));
}
for m in source_map.get_mappings() {
builder.add_raw(
m.generated_line,
m.generated_column,
m.original.map(|v| v.original_line).unwrap_or_default(),
m.original.map(|v| v.original_column).unwrap_or_default(),
Some(0),
None,
false,
);
}
let mut map = builder.into_sourcemap();
add_default_ignore_list(&mut map);
Vc::cell(Some(
turbopack_core::source_map::SourceMap::new_regular(map).resolved_cell(),
))
for m in source_map.get_mappings() {
builder.add_raw(
m.generated_line,
m.generated_column,
m.original.map(|v| v.original_line).unwrap_or_default(),
m.original.map(|v| v.original_column).unwrap_or_default(),
Some(0),
None,
false,
);
}
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))
}
#[turbo_tasks::value]
......@@ -652,7 +634,7 @@ impl Issue for ParsingIssue {
#[turbo_tasks::function]
async fn source(&self) -> Result<Vc<OptionIssueSource>> {
Ok(Vc::cell(match &self.source {
Some(s) => Some(s.resolve_source_map(*self.file).await?.into_owned()),
Some(s) => Some(s.resolve_source_map().await?.into_owned()),
None => None,
}))
}
......
......@@ -15,6 +15,7 @@ workspace = true
[dependencies]
anyhow = { workspace = true }
async-trait = { workspace = true }
data-encoding = "2.3.3"
either = { workspace = true }
indexmap = { workspace = true }
indoc = { workspace = true }
......
......@@ -8,10 +8,10 @@ use turbo_tasks::{
use turbo_tasks_fs::{rope::Rope, FileSystemPath};
use turbopack_core::{
chunk::{AsyncModuleInfo, ChunkItem, ChunkItemExt, ChunkItemTy, ChunkingContext},
code_builder::{fileify_source_map, Code, CodeBuilder},
code_builder::{Code, CodeBuilder},
error::PrettyPrintError,
issue::{code_gen::CodeGenerationIssue, IssueExt, IssueSeverity, StyledString},
source_map::GenerateSourceMap,
source_map::utils::fileify_source_map,
};
use crate::{
......@@ -24,7 +24,7 @@ use crate::{
#[derive(Default, Clone)]
pub struct EcmascriptChunkItemContent {
pub inner_code: Rope,
pub source_map: Option<ResolvedVc<Box<dyn GenerateSourceMap>>>,
pub source_map: Option<Rope>,
pub options: EcmascriptChunkItemOptions,
pub rewrite_source_path: Option<ResolvedVc<FileSystemPath>>,
pub placeholder_for_future_extensions: (),
......@@ -55,7 +55,7 @@ impl EcmascriptChunkItemContent {
None
},
inner_code: content.inner_code.clone(),
source_map: content.source_map,
source_map: content.source_map.clone(),
options: if content.is_esm {
EcmascriptChunkItemOptions {
strict: true,
......@@ -130,15 +130,9 @@ impl EcmascriptChunkItemContent {
}
let source_map = if let Some(rewrite_source_path) = self.rewrite_source_path {
let source_map = self.source_map.map(|m| m.generate_source_map());
match source_map {
Some(map) => fileify_source_map(map, *rewrite_source_path)
.await?
.map(ResolvedVc::upcast),
None => None,
}
fileify_source_map(self.source_map.as_ref(), *rewrite_source_path).await?
} else {
self.source_map
self.source_map.clone()
};
code.push_source(&self.inner_code, source_map);
......
......@@ -40,7 +40,6 @@ use std::fmt::{Display, Formatter};
use anyhow::Result;
use chunk::EcmascriptChunkItem;
use code_gen::{CodeGenerateable, CodeGeneration, CodeGenerationHoistedStmt};
pub use parse::ParseResultSourceMap;
use parse::{parse, ParseResult};
use path_visitor::ApplyVisitors;
use references::esm::UrlRewriteBehavior;
......@@ -82,7 +81,7 @@ use turbopack_core::{
FindContextFileResult,
},
source::Source,
source_map::{GenerateSourceMap, OptionSourceMap},
source_map::OptionStringifiedSourceMap,
};
// TODO remove this
pub use turbopack_resolve::ecmascript as resolve;
......@@ -91,6 +90,7 @@ use self::chunk::{EcmascriptChunkItemContent, EcmascriptChunkType, EcmascriptExp
use crate::{
chunk::EcmascriptChunkPlaceable,
code_gen::CodeGens,
parse::generate_js_source_map,
references::{analyse_ecmascript_module, async_module::OptionAsyncModule},
transform::remove_shebang,
};
......@@ -747,7 +747,7 @@ impl EcmascriptChunkItem for ModuleChunkItem {
#[turbo_tasks::value]
pub struct EcmascriptModuleContent {
pub inner_code: Rope,
pub source_map: Option<ResolvedVc<Box<dyn GenerateSourceMap>>>,
pub source_map: Option<Rope>,
pub is_esm: bool,
// pub refresh: bool,
}
......@@ -766,7 +766,7 @@ impl EcmascriptModuleContent {
code_generation: Vc<CodeGens>,
async_module: Vc<OptionAsyncModule>,
generate_source_map: Vc<bool>,
original_source_map: ResolvedVc<OptionSourceMap>,
original_source_map: ResolvedVc<OptionStringifiedSourceMap>,
exports: Vc<EcmascriptExports>,
async_module_info: Option<Vc<AsyncModuleInfo>>,
) -> Result<Vc<Self>> {
......@@ -822,7 +822,7 @@ impl EcmascriptModuleContent {
specified_module_type,
&[],
generate_source_map,
OptionSourceMap::none().to_resolved().await?,
OptionStringifiedSourceMap::none().to_resolved().await?,
)
.await
}
......@@ -834,7 +834,7 @@ async fn gen_content_with_code_gens(
specified_module_type: SpecifiedModuleType,
code_gens: impl IntoIterator<Item = &CodeGeneration>,
generate_source_map: Vc<bool>,
original_source_map: ResolvedVc<OptionSourceMap>,
original_source_map: ResolvedVc<OptionStringifiedSourceMap>,
) -> Result<Vc<EcmascriptModuleContent>> {
let parsed = parsed.await?;
......@@ -862,29 +862,29 @@ async fn gen_content_with_code_gens(
let mut mappings = vec![];
let comments = comments.consumable();
let generate_source_map = *generate_source_map.await?;
let mut emitter = Emitter {
cfg: swc_core::ecma::codegen::Config::default(),
cm: source_map.clone(),
comments: Some(&comments),
wr: JsWriter::new(
source_map.clone(),
"\n",
&mut bytes,
generate_source_map.then_some(&mut mappings),
),
};
emitter.emit_program(&program)?;
{
let comments = comments.consumable();
let mut emitter = Emitter {
cfg: swc_core::ecma::codegen::Config::default(),
cm: source_map.clone(),
comments: Some(&comments),
wr: JsWriter::new(
source_map.clone(),
"\n",
&mut bytes,
generate_source_map.then_some(&mut mappings),
),
};
emitter.emit_program(&program)?;
}
let source_map = if generate_source_map {
let srcmap =
ParseResultSourceMap::new(source_map.clone(), mappings, original_source_map)
.resolved_cell();
Some(ResolvedVc::upcast(srcmap))
Some(
generate_js_source_map(source_map.clone(), mappings, original_source_map)
.await?,
)
} else {
None
};
......
......@@ -19,14 +19,14 @@ use swc_core::{
transforms::base::fixer::paren_remover,
},
};
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks::Vc;
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
code_builder::{Code, CodeBuilder},
source_map::GenerateSourceMap,
};
use crate::ParseResultSourceMap;
use crate::parse::generate_js_source_map;
#[turbo_tasks::function]
pub async fn minify(
......@@ -119,10 +119,7 @@ pub async fn minify(
src_map_buf.shrink_to_fit();
builder.push_source(
&src.into(),
Some(ResolvedVc::upcast(
ParseResultSourceMap::new(cm, src_map_buf, original_map.to_resolved().await?)
.resolved_cell(),
)),
Some(generate_js_source_map(cm, src_map_buf, original_map.to_resolved().await?).await?),
);
write!(
......
......@@ -23,14 +23,14 @@ use swc_core::{
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{util::WrapFuture, ResolvedVc, Value, ValueToString, Vc};
use turbo_tasks_fs::{FileContent, FileSystemPath};
use turbo_tasks_fs::{rope::Rope, FileContent, FileSystemPath};
use turbo_tasks_hash::hash_xxh3_hash64;
use turbopack_core::{
asset::{Asset, AssetContent},
error::PrettyPrintError,
issue::{Issue, IssueExt, IssueSeverity, IssueStage, OptionStyledString, StyledString},
source::Source,
source_map::{utils::add_default_ignore_list, GenerateSourceMap, OptionSourceMap, SourceMap},
source_map::{utils::add_default_ignore_list, OptionStringifiedSourceMap},
SOURCE_MAP_PREFIX,
};
use turbopack_swc_utils::emitter::IssueEmitter;
......@@ -74,70 +74,38 @@ impl PartialEq for ParseResult {
}
}
#[turbo_tasks::value(shared, serialization = "none", eq = "manual")]
pub struct ParseResultSourceMap {
/// Confusingly, SWC's SourceMap is not a mapping of transformed locations
/// to source locations. It's a map of filesnames to file contents.
#[turbo_tasks(debug_ignore, trace_ignore)]
pub async fn generate_js_source_map(
files_map: Arc<swc_core::common::SourceMap>,
/// The position mappings that can generate a real source map.
#[turbo_tasks(debug_ignore, trace_ignore)]
mappings: Vec<(BytePos, LineCol)>,
original_source_map: ResolvedVc<OptionStringifiedSourceMap>,
) -> Result<Rope> {
let input_map = if let Some(original_source_map) = &*original_source_map.await? {
Some(match sourcemap::decode(original_source_map.read())? {
sourcemap::DecodedMap::Regular(source_map) => source_map,
// swc only accepts flattened sourcemaps as input
sourcemap::DecodedMap::Index(source_map_index) => source_map_index.flatten()?,
_ => return Err(sourcemap::Error::IncompatibleSourceMap.into()),
})
} else {
None
};
/// An input's original source map, if one exists. This will be used to
/// trace locations back to the input's pre-transformed sources.
original_source_map: ResolvedVc<OptionSourceMap>,
}
impl PartialEq for ParseResultSourceMap {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.files_map, &other.files_map) && self.mappings == other.mappings
}
}
impl ParseResultSourceMap {
pub fn new(
files_map: Arc<swc_core::common::SourceMap>,
mappings: Vec<(BytePos, LineCol)>,
original_source_map: ResolvedVc<OptionSourceMap>,
) -> Self {
ParseResultSourceMap {
files_map,
mappings,
original_source_map,
}
}
}
let mut map = files_map.build_source_map_with_config(
&mappings,
input_map.as_ref(),
InlineSourcesContentConfig {},
);
add_default_ignore_list(&mut map);
#[turbo_tasks::value_impl]
impl GenerateSourceMap for ParseResultSourceMap {
#[turbo_tasks::function]
async fn generate_source_map(&self) -> Result<Vc<OptionSourceMap>> {
let original_src_map = if let Some(input) = *self.original_source_map.await? {
Some(input.await?.to_source_map().await?)
} else {
None
};
let input_map = if let Some(map) = original_src_map.as_ref() {
map.as_regular_source_map()
} else {
None
};
let mut map = self.files_map.build_source_map_with_config(
&self.mappings,
input_map.as_deref(),
InlineSourcesContentConfig {},
);
add_default_ignore_list(&mut map);
Ok(Vc::cell(Some(SourceMap::new_regular(map).resolved_cell())))
}
let mut result = vec![];
map.to_writer(&mut result)?;
Ok(Rope::from(result))
}
/// A config to generate a source map which includes the source content of every
/// source file. SWC doesn't inline sources content by default when generating a
/// sourcemap, so we need to provide a custom config to do it.
struct InlineSourcesContentConfig {}
pub struct InlineSourcesContentConfig {}
impl SourceMapGenConfig for InlineSourcesContentConfig {
fn file_name_to_source(&self, f: &FileName) -> String {
......
......@@ -30,7 +30,6 @@ use parking_lot::Mutex;
use regex::Regex;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use sourcemap::decode_data_url;
use swc_core::{
atoms::JsWord,
common::{
......@@ -54,7 +53,7 @@ use turbo_tasks::{
trace::TraceRawVcs, FxIndexMap, FxIndexSet, NonLocalValue, ReadRef, ResolvedVc, TaskInput,
TryJoinIterExt, Upcast, Value, ValueToString, Vc,
};
use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_fs::{rope::Rope, FileSystemPath};
use turbopack_core::{
compile_time_info::{
CompileTimeInfo, DefineableNameSegment, FreeVarReference, FreeVarReferences,
......@@ -74,7 +73,9 @@ use turbopack_core::{
resolve, FindContextFileResult, ModulePart,
},
source::Source,
source_map::{convert_to_turbopack_source_map, GenerateSourceMap, OptionSourceMap, SourceMap},
source_map::{
utils::resolve_source_map_sources, GenerateSourceMap, OptionStringifiedSourceMap,
},
};
use turbopack_resolve::{
ecmascript::{apply_cjs_specific_options, cjs_resolve_source},
......@@ -164,7 +165,7 @@ pub struct AnalyzeEcmascriptModuleResult {
pub async_module: ResolvedVc<OptionAsyncModule>,
/// `true` when the analysis was successful.
pub successful: bool,
pub source_map: ResolvedVc<OptionSourceMap>,
pub source_map: ResolvedVc<OptionStringifiedSourceMap>,
}
/// A temporary analysis result builder to pass around, to be turned into an
......@@ -178,7 +179,7 @@ pub struct AnalyzeEcmascriptModuleResultBuilder {
exports: EcmascriptExports,
async_module: ResolvedVc<OptionAsyncModule>,
successful: bool,
source_map: Option<ResolvedVc<OptionSourceMap>>,
source_map: Option<ResolvedVc<OptionStringifiedSourceMap>>,
}
impl AnalyzeEcmascriptModuleResultBuilder {
......@@ -243,7 +244,7 @@ impl AnalyzeEcmascriptModuleResultBuilder {
}
/// Sets the analysis result ES export.
pub fn set_source_map(&mut self, source_map: ResolvedVc<OptionSourceMap>) {
pub fn set_source_map(&mut self, source_map: ResolvedVc<OptionStringifiedSourceMap>) {
self.source_map = Some(source_map);
}
......@@ -287,7 +288,7 @@ impl AnalyzeEcmascriptModuleResultBuilder {
let source_map = if let Some(source_map) = self.source_map {
source_map
} else {
OptionSourceMap::none().to_resolved().await?
OptionStringifiedSourceMap::none().to_resolved().await?
};
self.code_gens.shrink_to_fit();
......@@ -544,13 +545,6 @@ pub(crate) async fn analyse_ecmascript_module_internal(
}
}
// TODO This is too eagerly generating the source map. We should store a
// GenerateSourceMap instead and only actually generate the SourceMap when
// it's needed. This would allow to avoid generating the source map when a
// module is never included in the final bundle. It allows analysis to
// finish earlier which makes references available earlier which benefits
// parallelism. When SourceMaps are emitted it moves that generation work to
// the code generation phase which is more parallelizable.
let mut source_map_from_comment = false;
if let Some((_, path)) = paths_by_pos.into_iter().max_by_key(|&(pos, _)| pos) {
let origin_path = origin.origin_path();
......@@ -561,20 +555,13 @@ pub(crate) async fn analyse_ecmascript_module_internal(
.await?;
analysis.add_reference(reference);
let source_map = reference.generate_source_map();
analysis.set_source_map(
convert_to_turbopack_source_map(source_map, source_map_origin)
.to_resolved()
.await?,
);
analysis.set_source_map(source_map.to_resolved().await?);
source_map_from_comment = true;
} else if path.starts_with("data:application/json;base64,") {
let source_map_origin = origin_path;
let source_map = maybe_decode_data_url(path.into());
analysis.set_source_map(
convert_to_turbopack_source_map(source_map, source_map_origin)
.to_resolved()
.await?,
);
let source_map =
resolve_source_map_sources(source_map.as_ref(), origin_path).await?;
analysis.set_source_map(ResolvedVc::cell(source_map));
source_map_from_comment = true;
}
}
......@@ -582,14 +569,11 @@ pub(crate) async fn analyse_ecmascript_module_internal(
if let Some(generate_source_map) =
ResolvedVc::try_sidecast::<Box<dyn GenerateSourceMap>>(source)
{
let source_map_origin = source.ident().path();
analysis.set_source_map(
convert_to_turbopack_source_map(
generate_source_map.generate_source_map(),
source_map_origin,
)
.to_resolved()
.await?,
generate_source_map
.generate_source_map()
.to_resolved()
.await?,
);
}
}
......@@ -3534,11 +3518,15 @@ fn is_invoking_node_process_eval(args: &[JsValue]) -> bool {
false
}
#[turbo_tasks::function]
fn maybe_decode_data_url(url: RcStr) -> Vc<OptionSourceMap> {
if let Ok(map) = decode_data_url(&url) {
Vc::cell(Some(SourceMap::new_decoded(map).resolved_cell()))
} else {
Vc::cell(None)
fn maybe_decode_data_url(url: RcStr) -> Option<Rope> {
const DATA_PREAMBLE: &str = "data:application/json;base64,";
if !url.starts_with(DATA_PREAMBLE) {
return None;
}
let data_b64 = &url[DATA_PREAMBLE.len()..];
data_encoding::BASE64
.decode(data_b64.as_bytes())
.ok()
.map(Rope::from)
}
......@@ -59,7 +59,7 @@ impl StaticEcmascriptCode {
let mut code = CodeBuilder::default();
code.push_source(
&runtime_base_content.inner_code,
runtime_base_content.source_map,
runtime_base_content.source_map.clone(),
);
Ok(Code::cell(code.build()))
}
......
......@@ -272,7 +272,7 @@ impl Issue for MdxIssue {
#[turbo_tasks::function]
async fn source(&self) -> Result<Vc<OptionIssueSource>> {
Ok(Vc::cell(match &self.loc {
Some(loc) => Some(loc.resolve_source_map(*self.path).await?.into_owned()),
Some(loc) => Some(loc.resolve_source_map().await?.into_owned()),
None => None,
}))
}
......
......@@ -8,7 +8,7 @@ use anyhow::Result;
use const_format::concatcp;
use once_cell::sync::Lazy;
use regex::Regex;
pub use trace::{SourceMapTrace, StackFrame, TraceResult};
pub use trace::{trace_source_map, StackFrame, TraceResult};
use tracing::{instrument, Level};
use turbo_tasks::{ReadRef, Vc};
use turbo_tasks_fs::{
......@@ -16,7 +16,9 @@ use turbo_tasks_fs::{
};
use turbopack_cli_utils::source_context::format_source_context_lines;
use turbopack_core::{
output::OutputAsset, source_map::GenerateSourceMap, PROJECT_FILESYSTEM_NAME, SOURCE_MAP_PREFIX,
output::OutputAsset,
source_map::{GenerateSourceMap, SourceMap},
PROJECT_FILESYSTEM_NAME, SOURCE_MAP_PREFIX,
};
use turbopack_ecmascript::magic_identifier::unmangle_identifiers;
......@@ -222,13 +224,12 @@ async fn resolve_source_mapping(
let Some(generate_source_map) = map.get(file.as_ref()) else {
return Ok(ResolvedSourceMapping::NoSourceMap);
};
let Some(sm) = *generate_source_map.generate_source_map().await? else {
let sm = generate_source_map.generate_source_map();
let Some(sm) = &*SourceMap::new_from_rope_cached(sm).await? else {
return Ok(ResolvedSourceMapping::NoSourceMap);
};
let trace = SourceMapTrace::new(*sm, line, column, name.map(|s| s.clone().into()))
.trace()
.await?;
match &*trace {
let trace = trace_source_map(sm, line, column, name.map(|s| &**s)).await?;
match trace {
TraceResult::Found(frame) => {
let lib_code = frame.file.contains("/node_modules/");
if let Some(project_path) = frame.file.strip_prefix(concatcp!(
......
use std::{borrow::Cow, fmt::Display};
use anyhow::Result;
use mime::APPLICATION_JSON;
use serde::{Deserialize, Serialize};
use serde_json::json;
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::File;
use turbopack_core::{
asset::AssetContent,
source_map::{SourceMap, Token},
};
use turbopack_core::source_map::{SourceMap, Token};
use turbopack_ecmascript::magic_identifier::unmangle_identifiers;
/// An individual stack frame, as parsed by the stacktrace-parser npm module.
......@@ -81,93 +73,47 @@ impl Display for StackFrame<'_> {
}
}
}
/// Source Map Trace is a convenient wrapper to perform and consume a source map
/// trace's token.
#[turbo_tasks::value(shared)]
#[derive(Debug)]
pub struct SourceMapTrace {
map: ResolvedVc<SourceMap>,
line: u32,
column: u32,
name: Option<RcStr>,
}
/// The result of performing a source map trace.
#[turbo_tasks::value(shared)]
#[derive(Debug)]
pub enum TraceResult {
NotFound,
Found(#[turbo_tasks(trace_ignore)] StackFrame<'static>),
Found(StackFrame<'static>),
}
#[turbo_tasks::value_impl]
impl SourceMapTrace {
#[turbo_tasks::function]
pub fn new(
map: ResolvedVc<SourceMap>,
line: u32,
column: u32,
name: Option<RcStr>,
) -> Vc<Self> {
SourceMapTrace {
map,
line,
column,
name,
}
.cell()
}
/// Traces the line/column through the source map into its original
/// position.
///
/// This method is god-awful slow. We're getting the content
/// of a .map file, which means we're serializing all of the individual
/// sections into a string and concatenating, taking that and
/// deserializing into a DecodedMap, and then querying it. Besides being a
/// memory hog, it'd be so much faster if we could just directly access
/// the individual sections of the JS file's map without the
/// serialization.
#[turbo_tasks::function]
pub async fn trace(&self) -> Result<Vc<TraceResult>> {
let token = self
.map
.lookup_token(self.line.saturating_sub(1), self.column.saturating_sub(1))
.await?;
let result = match &*token {
Token::Original(t) => TraceResult::Found(StackFrame {
file: t.original_file.clone().into(),
line: Some(t.original_line.saturating_add(1)),
column: Some(t.original_column.saturating_add(1)),
name: t
.name
.clone()
.or_else(|| self.name.clone())
.map(|v| v.into_owned())
.map(Cow::Owned),
}),
_ => TraceResult::NotFound,
};
Ok(result.cell())
}
/// Traces the line/column through the source map into its original
/// position.
///
/// This method is god-awful slow. We're getting the content
/// of a .map file, which means we're serializing all of the individual
/// sections into a string and concatenating, taking that and
/// deserializing into a DecodedMap, and then querying it. Besides being a
/// memory hog, it'd be so much faster if we could just directly access
/// the individual sections of the JS file's map without the
/// serialization.
pub async fn trace_source_map(
map: &SourceMap,
line: u32,
column: u32,
name: Option<&str>,
) -> Result<TraceResult> {
let token = map
.lookup_token(line.saturating_sub(1), column.saturating_sub(1))
.await?;
let result = match token {
Token::Original(t) => TraceResult::Found(StackFrame {
file: t.original_file.clone().into(),
line: Some(t.original_line.saturating_add(1)),
column: Some(t.original_column.saturating_add(1)),
name: t
.name
.clone()
.map(|v| v.into_owned())
.or_else(|| name.map(ToString::to_string))
.map(Cow::Owned),
}),
_ => TraceResult::NotFound,
};
/// Takes the trace and generates a (possibly valid) JSON asset content.
#[turbo_tasks::function]
pub async fn content(self: Vc<Self>) -> Result<Vc<AssetContent>> {
let trace = self.trace().await?;
let result = match &*trace {
// purposefully invalid JSON (it can't be empty), so that the catch handler will default
// to the generated stack frame.
TraceResult::NotFound => "".to_string(),
TraceResult::Found(frame) => json!({
"originalStackFrame": frame,
// TODO
"originalCodeFrame": null,
})
.to_string(),
};
let file = File::from(result).with_content_type(APPLICATION_JSON);
Ok(AssetContent::file(file.into()))
}
Ok(result)
}
......@@ -22,7 +22,7 @@ use turbopack_core::{
reference_type::{EntryReferenceSubType, InnerAssets, ReferenceType},
resolve::{find_context_file_or_package_key, options::ImportMapping, FindContextFileResult},
source::Source,
source_map::{GenerateSourceMap, OptionSourceMap},
source_map::{GenerateSourceMap, OptionStringifiedSourceMap},
source_transform::SourceTransform,
virtual_source::VirtualSource,
};
......@@ -459,7 +459,7 @@ async fn find_config_in_location(
#[turbo_tasks::value_impl]
impl GenerateSourceMap for PostCssTransformedAsset {
#[turbo_tasks::function]
async fn generate_source_map(&self) -> Result<Vc<OptionSourceMap>> {
async fn generate_source_map(&self) -> Result<Vc<OptionStringifiedSourceMap>> {
let source = Vc::try_resolve_sidecast::<Box<dyn GenerateSourceMap>>(*self.source).await?;
match source {
Some(source) => Ok(source.generate_source_map()),
......
......@@ -14,8 +14,8 @@ use turbo_tasks::{
use turbo_tasks_bytes::stream::SingleValue;
use turbo_tasks_env::ProcessEnv;
use turbo_tasks_fs::{
glob::Glob, json::parse_json_with_source_context, DirectoryEntry, File, FileContent,
FileSystemPath, ReadGlobResult,
glob::Glob, json::parse_json_with_source_context, rope::Rope, DirectoryEntry, File,
FileContent, FileSystemPath, ReadGlobResult,
};
use turbopack_core::{
asset::{Asset, AssetContent},
......@@ -33,7 +33,9 @@ use turbopack_core::{
resolve,
},
source::Source,
source_map::{GenerateSourceMap, OptionSourceMap, SourceMap},
source_map::{
utils::resolve_source_map_sources, GenerateSourceMap, OptionStringifiedSourceMap,
},
source_transform::SourceTransform,
virtual_source::VirtualSource,
};
......@@ -168,15 +170,15 @@ impl Asset for WebpackLoadersProcessedAsset {
#[turbo_tasks::value_impl]
impl GenerateSourceMap for WebpackLoadersProcessedAsset {
#[turbo_tasks::function]
async fn generate_source_map(self: Vc<Self>) -> Result<Vc<OptionSourceMap>> {
Ok(Vc::cell(self.process().await?.source_map))
async fn generate_source_map(self: Vc<Self>) -> Result<Vc<OptionStringifiedSourceMap>> {
Ok(*self.process().await?.source_map)
}
}
#[turbo_tasks::value]
struct ProcessWebpackLoadersResult {
content: ResolvedVc<AssetContent>,
source_map: Option<ResolvedVc<SourceMap>>,
source_map: ResolvedVc<OptionStringifiedSourceMap>,
assets: Vec<ResolvedVc<VirtualSource>>,
}
......@@ -214,7 +216,7 @@ impl WebpackLoadersProcessedAsset {
return Ok(ProcessWebpackLoadersResult {
content: AssetContent::File(FileContent::NotFound.resolved_cell()).resolved_cell(),
assets: Vec::new(),
source_map: None,
source_map: ResolvedVc::cell(None),
}
.cell());
};
......@@ -264,7 +266,7 @@ impl WebpackLoadersProcessedAsset {
return Ok(ProcessWebpackLoadersResult {
content: AssetContent::File(FileContent::NotFound.resolved_cell()).resolved_cell(),
assets: Vec::new(),
source_map: None,
source_map: ResolvedVc::cell(None),
}
.cell());
};
......@@ -276,13 +278,13 @@ impl WebpackLoadersProcessedAsset {
// handle SourceMap
let source_map = if !transform.source_maps {
None
} else if let Some(source_map) = processed.map {
SourceMap::new_from_file_content(FileContent::Content(File::from(source_map)).cell())
.await?
.map(|source_map| source_map.resolved_cell())
} else {
None
processed
.map
.map(|source_map| Rope::from(source_map.into_owned()))
};
let source_map = resolve_source_map_sources(source_map.as_ref(), resource_fs_path).await?;
let file = match processed.source {
Either::Left(str) => File::from(str),
Either::Right(bytes) => File::from(bytes.binary),
......@@ -294,7 +296,7 @@ impl WebpackLoadersProcessedAsset {
Ok(ProcessWebpackLoadersResult {
content,
assets,
source_map,
source_map: ResolvedVc::cell(source_map),
}
.cell())
}
......
......@@ -7,7 +7,7 @@ use turbopack_core::{
chunk::{Chunk, ChunkingContext},
introspect::{Introspectable, IntrospectableChildren},
output::{OutputAsset, OutputAssets},
source_map::{GenerateSourceMap, OptionSourceMap, SourceMapAsset},
source_map::{GenerateSourceMap, OptionStringifiedSourceMap, SourceMapAsset},
version::VersionedContent,
};
use turbopack_ecmascript::chunk::EcmascriptChunk;
......@@ -113,7 +113,7 @@ impl Asset for EcmascriptBuildNodeChunk {
#[turbo_tasks::value_impl]
impl GenerateSourceMap for EcmascriptBuildNodeChunk {
#[turbo_tasks::function]
fn generate_source_map(self: Vc<Self>) -> Vc<OptionSourceMap> {
fn generate_source_map(self: Vc<Self>) -> Vc<OptionStringifiedSourceMap> {
self.own_content().generate_source_map()
}
}
......
......@@ -9,7 +9,7 @@ use turbopack_core::{
chunk::{ChunkItemExt, ChunkingContext, MinifyType, ModuleId},
code_builder::{Code, CodeBuilder},
output::OutputAsset,
source_map::{GenerateSourceMap, OptionSourceMap},
source_map::{GenerateSourceMap, OptionStringifiedSourceMap},
version::{Version, VersionedContent},
};
use turbopack_ecmascript::{
......@@ -131,7 +131,7 @@ impl EcmascriptBuildNodeChunkContent {
#[turbo_tasks::value_impl]
impl GenerateSourceMap for EcmascriptBuildNodeChunkContent {
#[turbo_tasks::function]
fn generate_source_map(self: Vc<Self>) -> Vc<OptionSourceMap> {
fn generate_source_map(self: Vc<Self>) -> Vc<OptionStringifiedSourceMap> {
self.code().generate_source_map()
}
}
......
......@@ -11,7 +11,7 @@ use turbopack_core::{
code_builder::{Code, CodeBuilder},
module_graph::ModuleGraph,
output::{OutputAsset, OutputAssets},
source_map::{GenerateSourceMap, OptionSourceMap, SourceMapAsset},
source_map::{GenerateSourceMap, OptionStringifiedSourceMap, SourceMapAsset},
};
use turbopack_ecmascript::{chunk::EcmascriptChunkPlaceable, utils::StringifyJs};
......@@ -217,7 +217,7 @@ impl Asset for EcmascriptBuildNodeEntryChunk {
#[turbo_tasks::value_impl]
impl GenerateSourceMap for EcmascriptBuildNodeEntryChunk {
#[turbo_tasks::function]
fn generate_source_map(self: Vc<Self>) -> Vc<OptionSourceMap> {
fn generate_source_map(self: Vc<Self>) -> Vc<OptionStringifiedSourceMap> {
self.code().generate_source_map()
}
}
......@@ -11,7 +11,7 @@ use turbopack_core::{
code_builder::{Code, CodeBuilder},
ident::AssetIdent,
output::{OutputAsset, OutputAssets},
source_map::{GenerateSourceMap, OptionSourceMap, SourceMapAsset},
source_map::{GenerateSourceMap, OptionStringifiedSourceMap, SourceMapAsset},
};
use turbopack_ecmascript::utils::StringifyJs;
use turbopack_ecmascript_runtime::RuntimeType;
......@@ -148,7 +148,7 @@ impl Asset for EcmascriptBuildNodeRuntimeChunk {
#[turbo_tasks::value_impl]
impl GenerateSourceMap for EcmascriptBuildNodeRuntimeChunk {
#[turbo_tasks::function]
fn generate_source_map(self: Vc<Self>) -> Vc<OptionSourceMap> {
fn generate_source_map(self: Vc<Self>) -> Vc<OptionStringifiedSourceMap> {
self.code().generate_source_map()
}
}
......@@ -121,7 +121,7 @@ fn bench_emit(b: &mut Bencher, bench_input: &BenchInput) {
let emit_op =
emit_with_completion_operation(ResolvedVc::upcast(rebased), output_dir);
emit_op.connect().strongly_consistent().await?;
emit_op.read_strongly_consistent().await?;
apply_effects(emit_op).await?;
Ok::<Vc<()>, _>(Default::default())
......
......@@ -468,7 +468,7 @@ fn node_file_trace<B: Backend + 'static>(
let emit_op =
emit_with_completion_operation(ResolvedVc::upcast(rebased), output_dir);
emit_op.connect().strongly_consistent().await?;
emit_op.read_strongly_consistent().await?;
apply_effects(emit_op).await?;
#[cfg(not(feature = "bench_against_node_nft"))]
......
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