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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
use std::{
    borrow::Cow,
    env::current_dir,
    fs::canonicalize,
    io,
    path::{Component, Path, PathBuf},
    sync::Arc,
};

use anyhow::{anyhow, Context, Error};
use path_clean::PathClean;
use pathdiff::diff_paths;
use swc_atoms::JsWord;
use swc_common::{FileName, Mark, Span, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_loader::resolve::{Resolution, Resolve};
use swc_ecma_utils::{quote_ident, ExprFactory};
use tracing::{debug, info, warn, Level};

pub(crate) enum Resolver {
    Real {
        base: FileName,
        resolver: Box<dyn ImportResolver>,
    },
    Default,
}

impl Resolver {
    pub(crate) fn resolve(&self, src: JsWord) -> JsWord {
        match self {
            Self::Real { resolver, base } => resolver
                .resolve_import(base, &src)
                .with_context(|| format!("failed to resolve import `{}`", src))
                .unwrap(),
            Self::Default => src,
        }
    }

    pub(crate) fn make_require_call(
        &self,
        unresolved_mark: Mark,
        src: JsWord,
        src_span: Span,
    ) -> Expr {
        let src = self.resolve(src);

        Expr::Call(CallExpr {
            span: DUMMY_SP,
            callee: quote_ident!(DUMMY_SP.apply_mark(unresolved_mark), "require").as_callee(),
            args: vec![Lit::Str(Str {
                span: src_span,
                raw: None,
                value: src,
            })
            .as_arg()],

            type_args: Default::default(),
        })
    }
}

pub trait ImportResolver {
    /// Resolves `target` as a string usable by the modules pass.
    ///
    /// The returned string will be used as a module specifier.
    fn resolve_import(&self, base: &FileName, module_specifier: &str) -> Result<JsWord, Error>;
}

/// [ImportResolver] implementation which just uses original source.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoopImportResolver;

impl ImportResolver for NoopImportResolver {
    fn resolve_import(&self, _: &FileName, module_specifier: &str) -> Result<JsWord, Error> {
        Ok(module_specifier.into())
    }
}

/// [ImportResolver] implementation for node.js
///
/// Supports [FileName::Real] and [FileName::Anon] for `base`, [FileName::Real]
/// and [FileName::Custom] for `target`. ([FileName::Custom] is used for core
/// modules)
#[derive(Debug, Clone, Default)]
pub struct NodeImportResolver<R>
where
    R: Resolve,
{
    resolver: R,
    config: Config,
}

#[derive(Debug, Clone, Default)]
pub struct Config {
    pub base_dir: Option<PathBuf>,
    pub resolve_fully: bool,
}

impl<R> NodeImportResolver<R>
where
    R: Resolve,
{
    #[deprecated(note = "Use `with_config`")]
    pub fn new(resolver: R) -> Self {
        Self::with_config(resolver, Default::default())
    }

    #[deprecated(note = "Use `with_config`")]
    pub fn with_base_dir(resolver: R, base_dir: Option<PathBuf>) -> Self {
        Self::with_config(
            resolver,
            Config {
                base_dir,
                ..Default::default()
            },
        )
    }

    pub fn with_config(resolver: R, config: Config) -> Self {
        #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
        if let Some(base_dir) = &config.base_dir {
            assert!(
                base_dir.is_absolute(),
                "base_dir(`{}`) must be absolute. Please ensure that `jsc.baseUrl` is specified \
                 correctly. This cannot be deduced by SWC itself because SWC is a transpiler and \
                 it does not try to resolve project details. In other words, SWC does not know \
                 which directory should be used as a base directory. It can be deduced if \
                 `.swcrc` is used, but if not, there are many candidates. e.g. the directory \
                 containing `package.json`, or the current working directory. Because of that, \
                 the caller (typically the developer of the JavaScript package) should specify \
                 it. If you see this error, please report an issue to the package author.",
                base_dir.display()
            );
        }

        Self { resolver, config }
    }
}

impl<R> NodeImportResolver<R>
where
    R: Resolve,
{
    fn to_specifier(&self, mut target_path: PathBuf, orig_filename: Option<&str>) -> JsWord {
        debug!(
            "Creating a specifier for `{}` with original filename `{:?}`",
            target_path.display(),
            orig_filename
        );

        if let Some(orig_filename) = orig_filename {
            let is_resolved_as_index = if let Some(stem) = target_path.file_stem() {
                stem == "index"
            } else {
                false
            };

            let is_resolved_as_non_js = if let Some(ext) = target_path.extension() {
                ext != "js"
            } else {
                false
            };

            let is_resolved_as_js = if let Some(ext) = target_path.extension() {
                ext == "js"
            } else {
                false
            };

            let is_exact = if let Some(filename) = target_path.file_name() {
                filename == orig_filename
            } else {
                false
            };

            if self.config.resolve_fully && is_resolved_as_js {
            } else if orig_filename == "index" {
                // Import: `./foo/index`
                // Resolved: `./foo/index.js`

                if self.config.resolve_fully {
                    target_path.set_file_name("index.js");
                } else {
                    target_path.set_file_name("index");
                }
            } else if is_resolved_as_index && is_resolved_as_js && orig_filename != "index.js" {
                // Import: `./foo`
                // Resolved: `./foo/index.js`

                target_path.pop();
            } else if !is_resolved_as_js && !is_resolved_as_index && !is_exact {
                target_path.set_file_name(orig_filename);
            } else if is_resolved_as_non_js && is_exact {
                if let Some(ext) = Path::new(orig_filename).extension() {
                    target_path.set_extension(ext);
                } else {
                    target_path.set_extension("js");
                }
            } else if self.config.resolve_fully && is_resolved_as_non_js {
                target_path.set_extension("js");
            } else if is_resolved_as_non_js && is_resolved_as_index {
                if orig_filename == "index" {
                    target_path.set_extension("");
                } else {
                    target_path.pop();
                }
            }
        } else {
            target_path.set_extension("");
        }

        if cfg!(target_os = "windows") {
            target_path.display().to_string().replace('\\', "/").into()
        } else {
            target_path.display().to_string().into()
        }
    }

    fn try_resolve_import(&self, base: &FileName, module_specifier: &str) -> Result<JsWord, Error> {
        let _tracing = if cfg!(debug_assertions) {
            Some(
                tracing::span!(
                    Level::ERROR,
                    "resolve_import",
                    base = tracing::field::display(base),
                    module_specifier = tracing::field::display(module_specifier),
                )
                .entered(),
            )
        } else {
            None
        };

        let orig_slug = module_specifier.split('/').last();

        let target = self.resolver.resolve(base, module_specifier);
        let mut target = match target {
            Ok(v) => v,
            Err(err) => {
                warn!("import rewriter: failed to resolve: {}", err);
                return Ok(module_specifier.into());
            }
        };

        // Bazel uses symlink
        //
        // https://github.com/swc-project/swc/issues/8265
        if let FileName::Real(resolved) = &target.filename {
            if let Ok(orig) = canonicalize(resolved) {
                target.filename = FileName::Real(orig);
            }
        }

        let Resolution {
            filename: target,
            slug,
        } = target;
        let slug = slug.as_deref().or(orig_slug);

        info!("Resolved as {target:?} with slug = {slug:?}");

        let mut target = match target {
            FileName::Real(v) => v,
            FileName::Custom(s) => return Ok(self.to_specifier(s.into(), slug)),
            _ => {
                unreachable!(
                    "Node path provider does not support using `{:?}` as a target file name",
                    target
                )
            }
        };
        let mut base = match base {
            FileName::Real(v) => Cow::Borrowed(
                v.parent()
                    .ok_or_else(|| anyhow!("failed to get parent of {:?}", v))?,
            ),
            FileName::Anon => match &self.config.base_dir {
                Some(v) => Cow::Borrowed(&**v),
                None => {
                    if cfg!(target_arch = "wasm32") {
                        panic!("Please specify `filename`")
                    } else {
                        Cow::Owned(current_dir().expect("failed to get current directory"))
                    }
                }
            },
            _ => {
                unreachable!(
                    "Node path provider does not support using `{:?}` as a base file name",
                    base
                )
            }
        };

        if base.is_absolute() != target.is_absolute() {
            base = Cow::Owned(absolute_path(self.config.base_dir.as_deref(), &base)?);
            target = absolute_path(self.config.base_dir.as_deref(), &target)?;
        }

        debug!(
            "Comparing values (after normalizing absoluteness)\nbase={}\ntarget={}",
            base.display(),
            target.display()
        );

        let rel_path = diff_paths(&target, &*base);

        let rel_path = match rel_path {
            Some(v) => v,
            None => return Ok(self.to_specifier(target, slug)),
        };

        debug!("Relative path: {}", rel_path.display());

        {
            // Check for `node_modules`.

            for component in rel_path.components() {
                match component {
                    Component::Prefix(_) => {}
                    Component::RootDir => {}
                    Component::CurDir => {}
                    Component::ParentDir => {}
                    Component::Normal(c) => {
                        if c == "node_modules" {
                            return Ok(module_specifier.into());
                        }
                    }
                }
            }
        }

        let s = rel_path.to_string_lossy();
        let s = if s.starts_with('.') || s.starts_with('/') || rel_path.is_absolute() {
            s
        } else {
            Cow::Owned(format!("./{}", s))
        };

        Ok(self.to_specifier(s.into_owned().into(), slug))
    }
}

impl<R> ImportResolver for NodeImportResolver<R>
where
    R: Resolve,
{
    fn resolve_import(&self, base: &FileName, module_specifier: &str) -> Result<JsWord, Error> {
        self.try_resolve_import(base, module_specifier)
            .or_else(|err| {
                warn!("Failed to resolve import: {}", err);
                Ok(module_specifier.into())
            })
    }
}

macro_rules! impl_ref {
    ($P:ident, $T:ty) => {
        impl<$P> ImportResolver for $T
        where
            $P: ImportResolver,
        {
            fn resolve_import(&self, base: &FileName, target: &str) -> Result<JsWord, Error> {
                (**self).resolve_import(base, target)
            }
        }
    };
}

impl_ref!(P, &'_ P);
impl_ref!(P, Box<P>);
impl_ref!(P, Arc<P>);

fn absolute_path(base_dir: Option<&Path>, path: &Path) -> io::Result<PathBuf> {
    let absolute_path = if path.is_absolute() {
        path.to_path_buf()
    } else {
        match base_dir {
            Some(base_dir) => base_dir.join(path),
            None => current_dir()?.join(path),
        }
    }
    .clean();

    Ok(absolute_path)
}