'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _regenerator;

function _load_regenerator() {
  return _regenerator = _interopRequireDefault(require('babel-runtime/regenerator'));
}

var _bluebird;

function _load_bluebird() {
  return _bluebird = require('bluebird');
}

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _fsExtra;

function _load_fsExtra() {
  return _fsExtra = _interopRequireDefault(require('fs-extra'));
}

var _ramda;

function _load_ramda() {
  return _ramda = _interopRequireDefault(require('ramda'));
}

var _abstractConfig;

function _load_abstractConfig() {
  return _abstractConfig = _interopRequireDefault(require('./abstract-config'));
}

var _exceptions;

function _load_exceptions() {
  return _exceptions = require('./exceptions');
}

var _constants;

function _load_constants() {
  return _constants = require('../../constants');
}

var _filterObject;

function _load_filterObject() {
  return _filterObject = _interopRequireDefault(require('../../utils/filter-object'));
}

var _logger;

function _load_logger() {
  return _logger = _interopRequireDefault(require('../../logger/logger'));
}

var _utils;

function _load_utils() {
  return _utils = require('../../utils');
}

var _invalidConfigPropPath;

function _load_invalidConfigPropPath() {
  return _invalidConfigPropPath = _interopRequireDefault(require('./exceptions/invalid-config-prop-path'));
}

var _consumerOverrides;

function _load_consumerOverrides() {
  return _consumerOverrides = _interopRequireDefault(require('./consumer-overrides'));
}

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var DEFAULT_USE_WORKSPACES = false;
var DEFAULT_MANAGE_WORKSPACES = true;
var DEFAULT_SAVE_DEPENDENCIES_AS_COMPONENTS = false;

var WorkspaceConfig = function (_AbstractConfig) {
  _inherits(WorkspaceConfig, _AbstractConfig);

  // manage workspaces with yarn
  // package manager process options
  // package manager client to use
  // path where to store build artifacts
  // path to remove while storing build artifacts. If, for example the code is in 'src' directory, and the component
  // is-string is in src/components/is-string, the dists files will be in dists/component/is-string (without the 'src')
  function WorkspaceConfig(_ref) {
    var compiler = _ref.compiler,
        tester = _ref.tester,
        _ref$saveDependencies = _ref.saveDependenciesAsComponents,
        saveDependenciesAsComponents = _ref$saveDependencies === undefined ? DEFAULT_SAVE_DEPENDENCIES_AS_COMPONENTS : _ref$saveDependencies,
        lang = _ref.lang,
        distTarget = _ref.distTarget,
        distEntry = _ref.distEntry,
        _ref$componentsDefaul = _ref.componentsDefaultDirectory,
        componentsDefaultDirectory = _ref$componentsDefaul === undefined ? (_constants || _load_constants()).DEFAULT_COMPONENTS_DIR_PATH : _ref$componentsDefaul,
        _ref$dependenciesDire = _ref.dependenciesDirectory,
        dependenciesDirectory = _ref$dependenciesDire === undefined ? (_constants || _load_constants()).DEFAULT_DEPENDENCIES_DIR_PATH : _ref$dependenciesDire,
        _ref$ejectedEnvsDirec = _ref.ejectedEnvsDirectory,
        ejectedEnvsDirectory = _ref$ejectedEnvsDirec === undefined ? (_constants || _load_constants()).DEFAULT_EJECTED_ENVS_DIR_PATH : _ref$ejectedEnvsDirec,
        bindingPrefix = _ref.bindingPrefix,
        extensions = _ref.extensions,
        _ref$packageManager = _ref.packageManager,
        packageManager = _ref$packageManager === undefined ? (_constants || _load_constants()).DEFAULT_PACKAGE_MANAGER : _ref$packageManager,
        packageManagerArgs = _ref.packageManagerArgs,
        packageManagerProcessOptions = _ref.packageManagerProcessOptions,
        _ref$useWorkspaces = _ref.useWorkspaces,
        useWorkspaces = _ref$useWorkspaces === undefined ? DEFAULT_USE_WORKSPACES : _ref$useWorkspaces,
        _ref$manageWorkspaces = _ref.manageWorkspaces,
        manageWorkspaces = _ref$manageWorkspaces === undefined ? DEFAULT_MANAGE_WORKSPACES : _ref$manageWorkspaces,
        resolveModules = _ref.resolveModules,
        _ref$overrides = _ref.overrides,
        overrides = _ref$overrides === undefined ? (_consumerOverrides || _load_consumerOverrides()).default.load() : _ref$overrides;

    _classCallCheck(this, WorkspaceConfig);

    var _this = _possibleConstructorReturn(this, (WorkspaceConfig.__proto__ || Object.getPrototypeOf(WorkspaceConfig)).call(this, { compiler, tester, lang, bindingPrefix, extensions }));

    _this.distTarget = distTarget;
    _this.distEntry = distEntry;
    _this.componentsDefaultDirectory = componentsDefaultDirectory;
    _this.dependenciesDirectory = dependenciesDirectory;
    _this.ejectedEnvsDirectory = ejectedEnvsDirectory;
    _this.saveDependenciesAsComponents = saveDependenciesAsComponents;
    _this.packageManager = packageManager;
    _this.packageManagerArgs = packageManagerArgs;
    _this.packageManagerProcessOptions = packageManagerProcessOptions;
    _this.useWorkspaces = useWorkspaces;
    _this.manageWorkspaces = manageWorkspaces;
    _this.resolveModules = resolveModules;
    _this.overrides = overrides;
    return _this;
  } // Enables integration with Yarn Workspaces
  // package manager client to use
  // save hub dependencies as bit components rather than npm packages


  _createClass(WorkspaceConfig, [{
    key: 'toPlainObject',
    value: function toPlainObject() {
      var superObject = _get(WorkspaceConfig.prototype.__proto__ || Object.getPrototypeOf(WorkspaceConfig.prototype), 'toPlainObject', this).call(this);
      var consumerObject = (_ramda || _load_ramda()).default.merge(superObject, {
        componentsDefaultDirectory: this.componentsDefaultDirectory,
        dependenciesDirectory: this.dependenciesDirectory,
        ejectedEnvsDirectory: this.ejectedEnvsDirectory,
        saveDependenciesAsComponents: this.saveDependenciesAsComponents,
        packageManager: this.packageManager,
        packageManagerArgs: this.packageManagerArgs,
        packageManagerProcessOptions: this.packageManagerProcessOptions,
        useWorkspaces: this.useWorkspaces,
        manageWorkspaces: this.manageWorkspaces,
        resolveModules: this.resolveModules,
        overrides: this.overrides.overrides
      });
      if (this.distEntry || this.distTarget) {
        var dist = {};
        if (this.distEntry) dist.entry = this.distEntry;
        if (this.distTarget) dist.target = this.distTarget;
        consumerObject = (_ramda || _load_ramda()).default.merge(consumerObject, { dist });
      }

      var isPropDefault = function isPropDefault(val, key) {
        if (key === 'dependenciesDirectory') return val !== (_constants || _load_constants()).DEFAULT_DEPENDENCIES_DIR_PATH;
        if (key === 'ejectedEnvsDirectory') return val !== (_constants || _load_constants()).DEFAULT_EJECTED_ENVS_DIR_PATH;
        if (key === 'useWorkspaces') return val !== DEFAULT_USE_WORKSPACES;
        if (key === 'manageWorkspaces') return val !== DEFAULT_MANAGE_WORKSPACES;
        if (key === 'saveDependenciesAsComponents') return val !== DEFAULT_SAVE_DEPENDENCIES_AS_COMPONENTS;
        if (key === 'resolveModules') return !(_ramda || _load_ramda()).default.isEmpty(val);
        if (key === 'overrides') return !(_ramda || _load_ramda()).default.isEmpty(val);
        return true;
      };

      return (0, (_filterObject || _load_filterObject()).default)(consumerObject, isPropDefault);
    }
  }], [{
    key: 'create',
    value: function create() {
      return new WorkspaceConfig({});
    }
  }, {
    key: 'ensure',
    value: function () {
      var _ref2 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(dirPath, standAlone) {
        var workspaceConfig, consumerBitJson, packageJsonExists;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.prev = 0;
                _context.next = 3;
                return this.load(dirPath);

              case 3:
                workspaceConfig = _context.sent;
                return _context.abrupt('return', workspaceConfig);

              case 7:
                _context.prev = 7;
                _context.t0 = _context['catch'](0);

                if (!(_context.t0 instanceof (_exceptions || _load_exceptions()).BitConfigNotFound || _context.t0 instanceof (_exceptions || _load_exceptions()).InvalidBitJson)) {
                  _context.next = 16;
                  break;
                }

                consumerBitJson = this.create();
                _context.next = 13;
                return (_abstractConfig || _load_abstractConfig()).default.pathHasPackageJson(dirPath);

              case 13:
                packageJsonExists = _context.sent;

                if (packageJsonExists && !standAlone) {
                  consumerBitJson.writeToPackageJson = true;
                } else {
                  consumerBitJson.writeToBitJson = true;
                }
                return _context.abrupt('return', consumerBitJson);

              case 16:
                throw _context.t0;

              case 17:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this, [[0, 7]]);
      }));

      function ensure(_x, _x2) {
        return _ref2.apply(this, arguments);
      }

      return ensure;
    }()
  }, {
    key: 'reset',
    value: function () {
      var _ref3 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(dirPath, resetHard) {
        var _this2 = this;

        var deleteBitJsonFile;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                deleteBitJsonFile = function () {
                  var _ref4 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2() {
                    var bitJsonPath;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
                      while (1) {
                        switch (_context2.prev = _context2.next) {
                          case 0:
                            bitJsonPath = (_abstractConfig || _load_abstractConfig()).default.composeBitJsonPath(dirPath);

                            (_logger || _load_logger()).default.info(`deleting the consumer bit.json file at ${bitJsonPath}`);
                            _context2.next = 4;
                            return (_fsExtra || _load_fsExtra()).default.remove(bitJsonPath);

                          case 4:
                          case 'end':
                            return _context2.stop();
                        }
                      }
                    }, _callee2, _this2);
                  }));

                  return function deleteBitJsonFile() {
                    return _ref4.apply(this, arguments);
                  };
                }();

                if (!resetHard) {
                  _context3.next = 4;
                  break;
                }

                _context3.next = 4;
                return deleteBitJsonFile();

              case 4:
              case 'end':
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function reset(_x3, _x4) {
        return _ref3.apply(this, arguments);
      }

      return reset;
    }()
  }, {
    key: 'fromPlainObject',
    value: function fromPlainObject(object) {
      WorkspaceConfig.validate(object);
      var env = object.env,
          lang = object.lang,
          componentsDefaultDirectory = object.componentsDefaultDirectory,
          dependenciesDirectory = object.dependenciesDirectory,
          ejectedEnvsDirectory = object.ejectedEnvsDirectory,
          dist = object.dist,
          bindingPrefix = object.bindingPrefix,
          extensions = object.extensions,
          saveDependenciesAsComponents = object.saveDependenciesAsComponents,
          packageManager = object.packageManager,
          packageManagerArgs = object.packageManagerArgs,
          packageManagerProcessOptions = object.packageManagerProcessOptions,
          useWorkspaces = object.useWorkspaces,
          manageWorkspaces = object.manageWorkspaces,
          resolveModules = object.resolveModules,
          overrides = object.overrides;


      return new WorkspaceConfig({
        compiler: (_ramda || _load_ramda()).default.propOr(undefined, 'compiler', env),
        tester: (_ramda || _load_ramda()).default.propOr(undefined, 'tester', env),
        lang,
        bindingPrefix,
        extensions,
        saveDependenciesAsComponents,
        componentsDefaultDirectory,
        dependenciesDirectory,
        ejectedEnvsDirectory,
        packageManager,
        packageManagerArgs,
        packageManagerProcessOptions,
        useWorkspaces,
        manageWorkspaces,
        resolveModules,
        distTarget: (_ramda || _load_ramda()).default.propOr(undefined, 'target', dist),
        distEntry: (_ramda || _load_ramda()).default.propOr(undefined, 'entry', dist),
        overrides: (_consumerOverrides || _load_consumerOverrides()).default.load(overrides)
      });
    }
  }, {
    key: 'load',
    value: function () {
      var _ref5 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee4(dirPath) {
        var bitJsonPath, packageJsonPath, _ref6, _ref7, bitJsonFile, packageJsonFile, bitJsonConfig, packageJsonHasConfig, packageJsonConfig, config, workspaceConfig;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                bitJsonPath = (_abstractConfig || _load_abstractConfig()).default.composeBitJsonPath(dirPath);
                packageJsonPath = (_abstractConfig || _load_abstractConfig()).default.composePackageJsonPath(dirPath);
                _context4.next = 4;
                return Promise.all([this.loadBitJson(bitJsonPath), // $FlowFixMe
                this.loadPackageJson(packageJsonPath)]);

              case 4:
                _ref6 = _context4.sent;
                _ref7 = _slicedToArray(_ref6, 2);
                bitJsonFile = _ref7[0];
                packageJsonFile = _ref7[1];
                bitJsonConfig = bitJsonFile || {};
                packageJsonHasConfig = packageJsonFile && packageJsonFile.bit;
                packageJsonConfig = packageJsonHasConfig ? packageJsonFile.bit : {};

                if (!((_ramda || _load_ramda()).default.isEmpty(bitJsonConfig) && (_ramda || _load_ramda()).default.isEmpty(packageJsonConfig))) {
                  _context4.next = 13;
                  break;
                }

                throw new (_exceptions || _load_exceptions()).BitConfigNotFound();

              case 13:
                // in case of conflicts, bit.json wins package.json
                config = Object.assign(packageJsonConfig, bitJsonConfig);
                workspaceConfig = this.fromPlainObject(config);

                workspaceConfig.path = bitJsonPath;
                workspaceConfig.writeToBitJson = Boolean(bitJsonFile);
                workspaceConfig.writeToPackageJson = packageJsonHasConfig;
                return _context4.abrupt('return', workspaceConfig);

              case 19:
              case 'end':
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

      function load(_x5) {
        return _ref5.apply(this, arguments);
      }

      return load;
    }()
  }, {
    key: 'loadBitJson',
    value: function () {
      var _ref8 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee5(bitJsonPath) {
        var file;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                _context5.prev = 0;
                _context5.next = 3;
                return (_abstractConfig || _load_abstractConfig()).default.loadJsonFileIfExist(bitJsonPath);

              case 3:
                file = _context5.sent;
                return _context5.abrupt('return', file);

              case 7:
                _context5.prev = 7;
                _context5.t0 = _context5['catch'](0);
                throw new (_exceptions || _load_exceptions()).InvalidBitJson(bitJsonPath);

              case 10:
              case 'end':
                return _context5.stop();
            }
          }
        }, _callee5, this, [[0, 7]]);
      }));

      function loadBitJson(_x6) {
        return _ref8.apply(this, arguments);
      }

      return loadBitJson;
    }()
  }, {
    key: 'loadPackageJson',
    value: function () {
      var _ref9 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee6(packageJsonPath) {
        var file;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                _context6.prev = 0;
                _context6.next = 3;
                return (_abstractConfig || _load_abstractConfig()).default.loadJsonFileIfExist(packageJsonPath);

              case 3:
                file = _context6.sent;
                return _context6.abrupt('return', file);

              case 7:
                _context6.prev = 7;
                _context6.t0 = _context6['catch'](0);
                throw new (_exceptions || _load_exceptions()).InvalidPackageJson(packageJsonPath);

              case 10:
              case 'end':
                return _context6.stop();
            }
          }
        }, _callee6, this, [[0, 7]]);
      }));

      function loadPackageJson(_x7) {
        return _ref9.apply(this, arguments);
      }

      return loadPackageJson;
    }()
  }, {
    key: 'validate',
    value: function validate(object) {
      var componentsDefaultDirectory = object.componentsDefaultDirectory,
          dependenciesDirectory = object.dependenciesDirectory,
          ejectedEnvsDirectory = object.ejectedEnvsDirectory;

      var pathsToValidate = { componentsDefaultDirectory, dependenciesDirectory, ejectedEnvsDirectory };
      Object.keys(pathsToValidate).forEach(function (field) {
        return throwForInvalidPath(field, pathsToValidate[field]);
      });
      function throwForInvalidPath(fieldName, pathToValidate) {
        if (pathToValidate && !(0, (_utils || _load_utils()).isValidPath)(pathToValidate)) {
          throw new (_invalidConfigPropPath || _load_invalidConfigPropPath()).default(fieldName, pathToValidate);
        }
      }
      (_consumerOverrides || _load_consumerOverrides()).default.validate(object.overrides);
    }
  }]);

  return WorkspaceConfig;
}((_abstractConfig || _load_abstractConfig()).default);

exports.default = WorkspaceConfig;