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
// Copyright 2020 nest.land core team.

use crate::swc_util::{AstParser, SwcDiagnosticBuffer};
use swc_ecma_ast::{CallExpr, ExportAll, ImportDecl, NamedExport};
use swc_ecma_parser::Syntax;
use swc_ecma_parser::TsConfig;
use swc_ecma_visit::Node;
use swc_ecma_visit::Visit;

struct DependencyVisitor {
  dependencies: Vec<String>,
  analyze_dynamic_imports: bool,
}

impl Visit for DependencyVisitor {
  fn visit_import_decl(
    &mut self,
    import_decl: &ImportDecl,
    _parent: &dyn Node,
  ) {
    let src_str = import_decl.src.value.to_string();
    self.dependencies.push(src_str);
  }

  fn visit_named_export(
    &mut self,
    named_export: &NamedExport,
    _parent: &dyn Node,
  ) {
    if let Some(src) = &named_export.src {
      let src_str = src.value.to_string();
      self.dependencies.push(src_str);
    }
  }

  fn visit_export_all(&mut self, export_all: &ExportAll, _parent: &dyn Node) {
    let src_str = export_all.src.value.to_string();
    self.dependencies.push(src_str);
  }

  fn visit_call_expr(&mut self, call_expr: &CallExpr, _parent: &dyn Node) {
    use swc_ecma_ast::{
      Expr::*, ExprOrSpread, ExprOrSuper::*, Ident, Lit::Str,
    };
    if !self.analyze_dynamic_imports {
      return;
    }

    match call_expr.callee.clone() {
      Expr(box Ident(Ident { sym, .. })) =>
      {
        #[allow(clippy::cmp_owned)]
        if sym.to_string() != "import" {
          return;
        }
      }
      _ => return,
    };

    if let Some(ExprOrSpread {
      expr: box Lit(Str(src)),
      ..
    }) = call_expr.args.get(0)
    {
      self.dependencies.push(src.value.to_string());
    }
  }
}

// Analyze the dependencies of a source file
pub fn analyze_dependencies(
  filename: &str,
  source_code: &str,
  analyze_dynamic_imports: bool,
) -> Result<Vec<String>, SwcDiagnosticBuffer> {
  let parser = AstParser::new();
  let mut ts_config = TsConfig::default();
  ts_config.dynamic_import = true;
  let syntax = Syntax::Typescript(ts_config);
  let parse_result = parser.parse_module(filename, syntax, source_code)?;
  let mut collector = DependencyVisitor {
    dependencies: vec![],
    analyze_dynamic_imports,
  };
  collector.visit_module(&parse_result, &parse_result);
  Ok(collector.dependencies)
}

#[test]
fn test_analyze_dependencies() {
  let source = r#"
import * as spam from "./spam.ts";
import { foo } from "./foo.ts";
export { bar } from "./foo.ts";
export * from "./bar.ts";
"#;

  let dependencies =
    analyze_dependencies("index.ts", source, false).expect("Failed to parse");
  assert_eq!(
    dependencies,
    vec![
      "./spam.ts".to_string(),
      "./foo.ts".to_string(),
      "./foo.ts".to_string(),
      "./bar.ts".to_string(),
    ]
  );
}

#[test]
fn test_analyze_dependencies_dyn_imports() {
  let source = r#"
import { foo } from "./foo.ts";
export { bar } from "./foo.ts";
export * from "./bar.ts";
const a = await import("./fizz.ts");
const b = await import("./" + "buzz.ts");
const c = await import("hello" + "world");
const d = call("yo");
"#;

  let dependencies =
    analyze_dependencies("index.ts", source, true).expect("Failed to parse");
  assert_eq!(
    dependencies,
    vec![
      "./foo.ts".to_string(),
      "./foo.ts".to_string(),
      "./bar.ts".to_string(),
      "./fizz.ts".to_string(),
    ]
  );
}