js_source_scopes/name_resolver.rs
1use sourcemap::DecodedMap;
2
3use crate::{NameComponent, ScopeName, SourceContext};
4
5/// A structure for resolving [`ScopeName`]s in minified code to their original names
6/// using information contained in a [`DecodedMap`].
7pub struct NameResolver<'a, T> {
8 ctx: &'a SourceContext<T>,
9 sourcemap: &'a DecodedMap,
10}
11
12impl<'a, T: AsRef<str>> NameResolver<'a, T> {
13 /// Construct a new [`NameResolver`] from a [`SourceContext`] (for the minified source) and a [`DecodedMap`].
14 pub fn new(ctx: &'a SourceContext<T>, sourcemap: &'a DecodedMap) -> Self {
15 Self { ctx, sourcemap }
16 }
17
18 /// Resolves the given minified [`ScopeName`] to the original name.
19 ///
20 /// This tries to resolve each [`NameComponent`] by looking up its source
21 /// range in the [`DecodedMap`], using the token's `name` (as defined in the
22 /// sourcemap `names`) when possible.
23 pub fn resolve_name(&self, name: &ScopeName) -> String {
24 name.components()
25 .map(|c| self.try_map_token(c).unwrap_or_else(|| c.text()))
26 .collect::<String>()
27 }
28
29 fn try_map_token(&self, c: &NameComponent) -> Option<&str> {
30 let range = c.range()?;
31
32 if let Some(name) = self.lookup_name_at(range.start) {
33 return Some(name);
34 }
35
36 // Some source maps (e.g., from terser/webpack) place the name mapping
37 // on the token immediately after the identifier rather than on it.
38 // This is common for private class methods (#foo), where the name ends
39 // up on the `(` token following the method name. Fall back to looking
40 // up at the end of the range to catch these cases.
41 self.lookup_name_at(range.end)
42 }
43
44 fn lookup_name_at(&self, offset: u32) -> Option<&str> {
45 let source_position = self.ctx.offset_to_position(offset)?;
46 let token = self
47 .sourcemap
48 .lookup_token(source_position.line, source_position.column)?;
49
50 let is_exactish_match = token.get_dst_line() == source_position.line
51 && token.get_dst_col() >= source_position.column.saturating_sub(1);
52
53 if is_exactish_match {
54 if let Some(name) = token.get_name() {
55 return Some(name);
56 }
57
58 // If the token at the identifier position has no name, check the
59 // immediately preceding token. Some source map generators (e.g.
60 // TypeScript) attach the original function name to the `function`
61 // keyword token rather than the identifier that follows it.
62 // We only use the preceding token's name if it maps to the same
63 // original source position, indicating it's part of the same mapping.
64 if token.get_dst_col() > 0 {
65 if let Some(prev_token) = self
66 .sourcemap
67 .lookup_token(token.get_dst_line(), token.get_dst_col() - 1)
68 {
69 if prev_token.get_src_id() == token.get_src_id()
70 && prev_token.get_src_line() == token.get_src_line()
71 && prev_token.get_src_col() == token.get_src_col()
72 {
73 return prev_token.get_name();
74 }
75 }
76 }
77 }
78
79 None
80 }
81}