"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

var parser = require("@babel/parser");

var _require = require("@babel/traverse"),
    babelTraverse = _require["default"];

var getPackageName = require("require-package-name");

var relative = require("relative-require-regex");

var isRelative = function isRelative(value) {
  return relative().test(value);
};

var get = require("lodash.get");

var chalk = require("chalk");

var STD_NODE_TYPES = ["ImportDeclaration", "ExportNamedDeclaration", "ExportAllDeclaration"];

module.exports = function (_ref) {
  var src = _ref.src,
      path = _ref.path,
      _ref$config = _ref.config,
      config = _ref$config === void 0 ? {} : _ref$config;

  try {
    var ast = parser.parse(src, _objectSpread({
      sourceType: "module"
    }, config.parser));
    var dependencies = {};

    var push = function push(value) {
      if (value && !isRelative(value)) {
        dependencies[getPackageName(value)] = true;
      }
    };

    var traverse = get(config, "traverse");
    babelTraverse(ast, {
      enter: function enter(path) {
        var node = path.node;

        if (STD_NODE_TYPES.includes(node.type)) {
          return push(get(node, "source.value"));
        }

        if (node.type === "CallExpression" && get(node, "callee.name") === "require") {
          return push(get(node, "arguments.0.value"));
        }

        typeof traverse === "function" && traverse({
          path: path,
          isRelative: isRelative,
          push: push
        });
      }
    });
    return Object.keys(dependencies);
  } catch (e) {
    console.log(chalk.red("Error occurred while parsing the file (".concat(path, "):")));
    console.log(e.stack);
    process.exit(1);
  }
};
//# sourceMappingURL=parse.js.map