File size: 12,047 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
use std::{
    borrow::Cow,
    fmt::Write,
    path::{MAIN_SEPARATOR, Path},
};

use anyhow::Result;
use const_format::concatcp;
use once_cell::sync::Lazy;
use regex::Regex;
pub use trace::{StackFrame, TraceResult, trace_source_map};
use tracing::{Level, instrument};
use turbo_tasks::{ReadRef, Vc};
use turbo_tasks_fs::{
    FileLinesContent, FileSystemPath, source_context::get_source_context, to_sys_path,
};
use turbopack_cli_utils::source_context::format_source_context_lines;
use turbopack_core::{
    PROJECT_FILESYSTEM_NAME, SOURCE_URL_PROTOCOL,
    output::OutputAsset,
    source_map::{GenerateSourceMap, SourceMap},
};
use turbopack_ecmascript::magic_identifier::unmangle_identifiers;

use crate::{AssetsForSourceMapping, internal_assets_for_source_mapping, pool::FormattingMode};

pub mod trace;

const MAX_CODE_FRAMES: usize = 3;

pub async fn apply_source_mapping(
    text: &'_ str,
    assets_for_source_mapping: Vc<AssetsForSourceMapping>,
    root: FileSystemPath,
    project_dir: FileSystemPath,
    formatting_mode: FormattingMode,
) -> Result<Cow<'_, str>> {
    static STACK_TRACE_LINE: Lazy<Regex> =
        Lazy::new(|| Regex::new("\n    at (?:(.+) \\()?(.+):(\\d+):(\\d+)\\)?").unwrap());

    let mut it = STACK_TRACE_LINE.captures_iter(text).peekable();
    if it.peek().is_none() {
        return Ok(Cow::Borrowed(text));
    }
    let mut first_error = true;
    let mut visible_code_frames = 0;
    let mut new = String::with_capacity(text.len() * 2);
    let mut last_match = 0;
    for cap in it {
        // unwrap on 0 is OK because captures only reports matches
        let m = cap.get(0).unwrap();
        new.push_str(&text[last_match..m.start()]);
        let name = cap.get(1).map(|s| s.as_str());
        let file = cap.get(2).unwrap().as_str();
        let line = cap.get(3).unwrap().as_str();
        let column = cap.get(4).unwrap().as_str();
        let line = line.parse::<u32>()?;
        let column = column.parse::<u32>()?;
        let frame = StackFrame {
            name: name.map(|s| s.into()),
            file: file.into(),
            line: Some(line),
            column: Some(column),
        };
        let resolved = resolve_source_mapping(
            assets_for_source_mapping,
            root.clone(),
            project_dir.root().owned().await?,
            &frame,
        )
        .await;
        write_resolved(
            &mut new,
            resolved,
            &frame,
            &mut first_error,
            &mut visible_code_frames,
            formatting_mode,
        )?;
        last_match = m.end();
    }
    new.push_str(&text[last_match..]);
    Ok(Cow::Owned(new))
}

fn write_resolved(
    writable: &mut impl Write,
    resolved: Result<ResolvedSourceMapping>,
    original_frame: &StackFrame<'_>,
    first_error: &mut bool,
    visible_code_frames: &mut usize,
    formatting_mode: FormattingMode,
) -> Result<()> {
    const PADDING: &str = "\n    ";
    match resolved {
        Err(err) => {
            // There was an error resolving the source map
            write!(writable, "{PADDING}at {original_frame}")?;
            if *first_error {
                write!(writable, "{PADDING}(error resolving source map: {err})")?;
                *first_error = false;
            } else {
                write!(writable, "{PADDING}(error resolving source map)")?;
            }
        }
        Ok(ResolvedSourceMapping::NoSourceMap) | Ok(ResolvedSourceMapping::Unmapped) => {
            // There is no source map for this file or no mapping for the line
            write!(
                writable,
                "{PADDING}{}",
                formatting_mode.lowlight(&format_args!("[at {original_frame}]"))
            )?;
        }
        Ok(ResolvedSourceMapping::Mapped { frame }) => {
            // There is a mapping to something outside of the project (e. g. plugins,
            // internal code)
            write!(
                writable,
                "{PADDING}{}",
                formatting_mode.lowlight(&format_args!(
                    "at {} [{}]",
                    frame,
                    original_frame.with_name(None)
                ))
            )?;
        }
        Ok(ResolvedSourceMapping::MappedLibrary {
            frame,
            project_path,
        }) => {
            // There is a mapping to a file in the project directory, but to library code
            write!(
                writable,
                "{PADDING}{}",
                formatting_mode.lowlight(&format_args!(
                    "at {} [{}]",
                    frame.with_path(&project_path.path),
                    original_frame.with_name(None)
                ))
            )?;
        }
        Ok(ResolvedSourceMapping::MappedProject {
            frame,
            project_path,
            lines,
        }) => {
            // There is a mapping to a file in the project directory
            if let Some(name) = frame.name.as_ref() {
                write!(
                    writable,
                    "{PADDING}at {name} ({}) {}",
                    formatting_mode.highlight(&frame.with_name(None).with_path(&project_path.path)),
                    formatting_mode.lowlight(&format_args!("[{}]", original_frame.with_name(None)))
                )?;
            } else {
                write!(
                    writable,
                    "{PADDING}at {} {}",
                    formatting_mode.highlight(&frame.with_path(&project_path.path)),
                    formatting_mode.lowlight(&format_args!("[{}]", original_frame.with_name(None)))
                )?;
            }
            let (line, column) = frame.get_pos().unwrap_or((0, 0));
            let line = line.saturating_sub(1);
            let column = column.saturating_sub(1);
            if let FileLinesContent::Lines(lines) = &*lines
                && *visible_code_frames < MAX_CODE_FRAMES
            {
                let lines = lines.iter().map(|l| l.content.as_str());
                let ctx = get_source_context(lines, line, column, line, column);
                match formatting_mode {
                    FormattingMode::Plain => {
                        write!(writable, "\n{ctx}")?;
                    }
                    FormattingMode::AnsiColors => {
                        writable.write_char('\n')?;
                        format_source_context_lines(&ctx, writable);
                    }
                }
                *visible_code_frames += 1;
            }
        }
    }
    Ok(())
}

enum ResolvedSourceMapping {
    NoSourceMap,
    Unmapped,
    Mapped {
        frame: StackFrame<'static>,
    },
    MappedProject {
        frame: StackFrame<'static>,
        project_path: FileSystemPath,
        lines: ReadRef<FileLinesContent>,
    },
    MappedLibrary {
        frame: StackFrame<'static>,
        project_path: FileSystemPath,
    },
}

async fn resolve_source_mapping(
    assets_for_source_mapping: Vc<AssetsForSourceMapping>,
    root: FileSystemPath,
    project_dir: FileSystemPath,
    frame: &StackFrame<'_>,
) -> Result<ResolvedSourceMapping> {
    let Some((line, column)) = frame.get_pos() else {
        return Ok(ResolvedSourceMapping::NoSourceMap);
    };
    let name = frame.name.as_ref();
    let file = &frame.file;
    let Some(root) = to_sys_path(root).await? else {
        return Ok(ResolvedSourceMapping::NoSourceMap);
    };
    let Ok(file) = Path::new(file.as_ref()).strip_prefix(root) else {
        return Ok(ResolvedSourceMapping::NoSourceMap);
    };
    let file = file.to_string_lossy();
    let file = if MAIN_SEPARATOR != '/' {
        Cow::Owned(file.replace(MAIN_SEPARATOR, "/"))
    } else {
        file
    };
    let map = assets_for_source_mapping.await?;
    let Some(generate_source_map) = map.get(file.as_ref()) else {
        return Ok(ResolvedSourceMapping::NoSourceMap);
    };
    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 = 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!(
                SOURCE_URL_PROTOCOL,
                "///[",
                PROJECT_FILESYSTEM_NAME,
                "]/"
            )) {
                let fs_path = project_dir.join(project_path)?;
                if lib_code {
                    return Ok(ResolvedSourceMapping::MappedLibrary {
                        frame: frame.clone(),
                        project_path: fs_path.clone(),
                    });
                } else {
                    let lines = fs_path.read().lines().await?;
                    return Ok(ResolvedSourceMapping::MappedProject {
                        frame: frame.clone(),
                        project_path: fs_path.clone(),
                        lines,
                    });
                }
            }
            Ok(ResolvedSourceMapping::Mapped {
                frame: frame.clone(),
            })
        }
        TraceResult::NotFound => Ok(ResolvedSourceMapping::Unmapped),
    }
}

#[turbo_tasks::value(shared)]
#[derive(Clone, Debug)]
pub struct StructuredError {
    pub name: String,
    pub message: String,
    #[turbo_tasks(trace_ignore)]
    stack: Vec<StackFrame<'static>>,
    cause: Option<Box<StructuredError>>,
}

impl StructuredError {
    pub async fn print(
        &self,
        assets_for_source_mapping: Vc<AssetsForSourceMapping>,
        root: FileSystemPath,
        root_path: FileSystemPath,
        formatting_mode: FormattingMode,
    ) -> Result<String> {
        let mut message = String::new();

        let magic = |content| formatting_mode.magic_identifier(content);

        write!(
            message,
            "{}: {}",
            self.name,
            unmangle_identifiers(&self.message, magic)
        )?;

        let mut first_error = true;
        let mut visible_code_frames = 0;

        for frame in &self.stack {
            let frame = frame.unmangle_identifiers(magic);
            let resolved = resolve_source_mapping(
                assets_for_source_mapping,
                root.clone(),
                root_path.clone(),
                &frame,
            )
            .await;
            write_resolved(
                &mut message,
                resolved,
                &frame,
                &mut first_error,
                &mut visible_code_frames,
                formatting_mode,
            )?;
        }

        if let Some(cause) = &self.cause {
            message.write_str("\nCaused by: ")?;
            message.write_str(
                &Box::pin(cause.print(
                    assets_for_source_mapping,
                    root.clone(),
                    root_path.clone(),
                    formatting_mode,
                ))
                .await?,
            )?;
        }

        Ok(message)
    }
}

pub async fn trace_stack(
    error: StructuredError,
    root_asset: Vc<Box<dyn OutputAsset>>,
    output_path: FileSystemPath,
    project_dir: FileSystemPath,
) -> Result<String> {
    let assets_for_source_mapping =
        internal_assets_for_source_mapping(root_asset, output_path.clone());

    trace_stack_with_source_mapping_assets(
        error,
        assets_for_source_mapping,
        output_path,
        project_dir,
    )
    .await
}

#[instrument(level = Level::TRACE, skip_all)]
pub async fn trace_stack_with_source_mapping_assets(
    error: StructuredError,
    assets_for_source_mapping: Vc<AssetsForSourceMapping>,
    output_path: FileSystemPath,
    project_dir: FileSystemPath,
) -> Result<String> {
    error
        .print(
            assets_for_source_mapping,
            output_path,
            project_dir,
            FormattingMode::Plain,
        )
        .await
}