"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

function _chalk() {
  const data = _interopRequireDefault(require("chalk"));

  _chalk = function () {
    return data;
  };

  return data;
}

function _chalkBox() {
  const data = require("./chalk-box");

  _chalkBox = function () {
    return data;
  };

  return data;
}

function _hashErrorObject() {
  const data = _interopRequireDefault(require("../error/hash-error-object"));

  _hashErrorObject = function () {
    return data;
  };

  return data;
}

function _exceptions() {
  const data = require("../bit-id/exceptions");

  _exceptions = function () {
    return data;
  };

  return data;
}

function _exceptions2() {
  const data = require("../consumer/exceptions");

  _exceptions2 = function () {
    return data;
  };

  return data;
}

function _driver() {
  const data = require("../driver");

  _driver = function () {
    return data;
  };

  return data;
}

function _componentNotFoundInPath() {
  const data = _interopRequireDefault(require("../consumer/component/exceptions/component-not-found-in-path"));

  _componentNotFoundInPath = function () {
    return data;
  };

  return data;
}

function _missingFilesFromComponent() {
  const data = _interopRequireDefault(require("../consumer/component/exceptions/missing-files-from-component"));

  _missingFilesFromComponent = function () {
    return data;
  };

  return data;
}

function _pluginNotFound() {
  const data = _interopRequireDefault(require("../consumer/component/exceptions/plugin-not-found"));

  _pluginNotFound = function () {
    return data;
  };

  return data;
}

function _permissionDenied() {
  const data = _interopRequireDefault(require("../scope/network/exceptions/permission-denied"));

  _permissionDenied = function () {
    return data;
  };

  return data;
}

function _exceptions3() {
  const data = require("../scope/network/exceptions");

  _exceptions3 = function () {
    return data;
  };

  return data;
}

function _remoteNotFound() {
  const data = _interopRequireDefault(require("../remotes/exceptions/remote-not-found"));

  _remoteNotFound = function () {
    return data;
  };

  return data;
}

function _exceptions4() {
  const data = require("../scope/exceptions");

  _exceptions4 = function () {
    return data;
  };

  return data;
}

function _invalidBitJson() {
  const data = _interopRequireDefault(require("../consumer/config/exceptions/invalid-bit-json"));

  _invalidBitJson = function () {
    return data;
  };

  return data;
}

function _invalidPackageJson() {
  const data = _interopRequireDefault(require("../consumer/config/exceptions/invalid-package-json"));

  _invalidPackageJson = function () {
    return data;
  };

  return data;
}

function _invalidVersion() {
  const data = _interopRequireDefault(require("../api/consumer/lib/exceptions/invalid-version"));

  _invalidVersion = function () {
    return data;
  };

  return data;
}

function _noIdMatchWildcard() {
  const data = _interopRequireDefault(require("../api/consumer/lib/exceptions/no-id-match-wildcard"));

  _noIdMatchWildcard = function () {
    return data;
  };

  return data;
}

function _nothingToCompareTo() {
  const data = _interopRequireDefault(require("../api/consumer/lib/exceptions/nothing-to-compare-to"));

  _nothingToCompareTo = function () {
    return data;
  };

  return data;
}

function _promptCanceled() {
  const data = _interopRequireDefault(require("../prompts/exceptions/prompt-canceled"));

  _promptCanceled = function () {
    return data;
  };

  return data;
}

function _idExportedAlready() {
  const data = _interopRequireDefault(require("../api/consumer/lib/exceptions/id-exported-already"));

  _idExportedAlready = function () {
    return data;
  };

  return data;
}

function _fileSourceNotFound() {
  const data = _interopRequireDefault(require("../consumer/component/exceptions/file-source-not-found"));

  _fileSourceNotFound = function () {
    return data;
  };

  return data;
}

function _exceptions5() {
  const data = require("../consumer/bit-map/exceptions");

  _exceptions5 = function () {
    return data;
  };

  return data;
}

function _logger() {
  const data = _interopRequireDefault(require("../logger/logger"));

  _logger = function () {
    return data;
  };

  return data;
}

function _remoteUndefined() {
  const data = _interopRequireDefault(require("./commands/exceptions/remote-undefined"));

  _remoteUndefined = function () {
    return data;
  };

  return data;
}

function _addTestsWithoutId() {
  const data = _interopRequireDefault(require("./commands/exceptions/add-tests-without-id"));

  _addTestsWithoutId = function () {
    return data;
  };

  return data;
}

function _componentIssuesTemplate() {
  const data = _interopRequireDefault(require("./templates/component-issues-template"));

  _componentIssuesTemplate = function () {
    return data;
  };

  return data;
}

function _newerVersionTemplate() {
  const data = _interopRequireDefault(require("./templates/newer-version-template"));

  _newerVersionTemplate = function () {
    return data;
  };

  return data;
}

function _exceptions6() {
  const data = require("../consumer/component-ops/add-components/exceptions");

  _exceptions6 = function () {
    return data;
  };

  return data;
}

function _analytics() {
  const data = require("../analytics/analytics");

  _analytics = function () {
    return data;
  };

  return data;
}

function _externalTestErrors() {
  const data = _interopRequireDefault(require("../consumer/component/exceptions/external-test-errors"));

  _externalTestErrors = function () {
    return data;
  };

  return data;
}

function _externalBuildErrors() {
  const data = _interopRequireDefault(require("../consumer/component/exceptions/external-build-errors"));

  _externalBuildErrors = function () {
    return data;
  };

  return data;
}

function _invalidCompilerInterface() {
  const data = _interopRequireDefault(require("../consumer/component/exceptions/invalid-compiler-interface"));

  _invalidCompilerInterface = function () {
    return data;
  };

  return data;
}

function _extensionFileNotFound() {
  const data = _interopRequireDefault(require("../extensions/exceptions/extension-file-not-found"));

  _extensionFileNotFound = function () {
    return data;
  };

  return data;
}

function _extensionNameNotValid() {
  const data = _interopRequireDefault(require("../extensions/exceptions/extension-name-not-valid"));

  _extensionNameNotValid = function () {
    return data;
  };

  return data;
}

function _generalError() {
  const data = _interopRequireDefault(require("../error/general-error"));

  _generalError = function () {
    return data;
  };

  return data;
}

function _validationError() {
  const data = _interopRequireDefault(require("../error/validation-error"));

  _validationError = function () {
    return data;
  };

  return data;
}

function _abstractError() {
  const data = _interopRequireDefault(require("../error/abstract-error"));

  _abstractError = function () {
    return data;
  };

  return data;
}

function _exceptions7() {
  const data = require("../consumer/login/exceptions");

  _exceptions7 = function () {
    return data;
  };

  return data;
}

function _extensionLoadError() {
  const data = _interopRequireDefault(require("../extensions/exceptions/extension-load-error"));

  _extensionLoadError = function () {
    return data;
  };

  return data;
}

function _extensionGetDynamicPackagesError() {
  const data = _interopRequireDefault(require("../extensions/exceptions/extension-get-dynamic-packages-error"));

  _extensionGetDynamicPackagesError = function () {
    return data;
  };

  return data;
}

function _extensionGetDynamicConfigError() {
  const data = _interopRequireDefault(require("../extensions/exceptions/extension-get-dynamic-config-error"));

  _extensionGetDynamicConfigError = function () {
    return data;
  };

  return data;
}

function _extensionInitError() {
  const data = _interopRequireDefault(require("../extensions/exceptions/extension-init-error"));

  _extensionInitError = function () {
    return data;
  };

  return data;
}

function _mainFileRemoved() {
  const data = _interopRequireDefault(require("../consumer/component/exceptions/main-file-removed"));

  _mainFileRemoved = function () {
    return data;
  };

  return data;
}

function _invalidConfigDir() {
  const data = _interopRequireDefault(require("../consumer/bit-map/exceptions/invalid-config-dir"));

  _invalidConfigDir = function () {
    return data;
  };

  return data;
}

function _ejectToWorkspace() {
  const data = _interopRequireDefault(require("../consumer/component/exceptions/eject-to-workspace"));

  _ejectToWorkspace = function () {
    return data;
  };

  return data;
}

function _ejectBoundToWorkspace() {
  const data = _interopRequireDefault(require("../consumer/component/exceptions/eject-bound-to-workspace"));

  _ejectBoundToWorkspace = function () {
    return data;
  };

  return data;
}

function _ejectNoDir() {
  const data = _interopRequireDefault(require("../consumer/component-ops/exceptions/eject-no-dir"));

  _ejectNoDir = function () {
    return data;
  };

  return data;
}

function _constants() {
  const data = require("../constants");

  _constants = function () {
    return data;
  };

  return data;
}

function _injectNonEjected() {
  const data = _interopRequireDefault(require("../consumer/component/exceptions/inject-non-ejected"));

  _injectNonEjected = function () {
    return data;
  };

  return data;
}

function _extensionSchemaError() {
  const data = _interopRequireDefault(require("../extensions/exceptions/extension-schema-error"));

  _extensionSchemaError = function () {
    return data;
  };

  return data;
}

function _gitNotFound() {
  const data = _interopRequireDefault(require("../utils/git/exceptions/git-not-found"));

  _gitNotFound = function () {
    return data;
  };

  return data;
}

function _objectsWithoutConsumer() {
  const data = _interopRequireDefault(require("../api/consumer/lib/exceptions/objects-without-consumer"));

  _objectsWithoutConsumer = function () {
    return data;
  };

  return data;
}

function _invalidConfigPropPath() {
  const data = _interopRequireDefault(require("../consumer/config/exceptions/invalid-config-prop-path"));

  _invalidConfigPropPath = function () {
    return data;
  };

  return data;
}

function _diagnosisNotFound() {
  const data = _interopRequireDefault(require("../api/consumer/lib/exceptions/diagnosis-not-found"));

  _diagnosisNotFound = function () {
    return data;
  };

  return data;
}

function _missingDiagnosisName() {
  const data = _interopRequireDefault(require("../api/consumer/lib/exceptions/missing-diagnosis-name"));

  _missingDiagnosisName = function () {
    return data;
  };

  return data;
}

function _remoteResolverError() {
  const data = _interopRequireDefault(require("../scope/network/exceptions/remote-resolver-error"));

  _remoteResolverError = function () {
    return data;
  };

  return data;
}

function _exportAnotherOwnerPrivate() {
  const data = _interopRequireDefault(require("../scope/network/exceptions/export-another-owner-private"));

  _exportAnotherOwnerPrivate = function () {
    return data;
  };

  return data;
}

function _componentsPendingImport() {
  const data = _interopRequireDefault(require("../consumer/component-ops/exceptions/components-pending-import"));

  _componentsPendingImport = function () {
    return data;
  };

  return data;
}

function _statusCmd() {
  const data = require("./commands/public-cmds/status-cmd");

  _statusCmd = function () {
    return data;
  };

  return data;
}

// all errors that the command does not handle comes to this switch statement
// if you handle the error, then return true
const reportIssueToGithubMsg = 'This error should have never happened. Please report this issue on Github https://github.com/teambit/bit/issues';
const errorsMap = [[_remoteUndefined().default, () => _chalk().default.red('error: remote url must be defined. please use: `ssh://`, `file://` or `bit://` protocols to define remote access')], [_addTestsWithoutId().default, () => _chalk().default.yellow(`please specify a component ID to add test files to an existing component. \n${_chalk().default.bold('example: bit add --tests [test_file_path] --id [component_id]')}`)], [_exceptions2().ConsumerAlreadyExists, () => 'workspace already exists'], [_generalError().default, err => `${err.msg}`], [_exceptions4().VersionAlreadyExists, err => `error: version ${err.version} already exists for ${err.componentId}`], [_exceptions2().ConsumerNotFound, () => 'workspace not found. to initiate a new workspace, please use `bit init`'], [_exceptions2().LoginFailed, () => 'error: there was a problem with web authentication'], // [
//   PluginNotFound,
//   err => `error: The compiler "${err.plugin}" is not installed, please use "bit install ${err.plugin}" to install it.`
// ],
[_fileSourceNotFound().default, err => `file or directory "${err.path}" was not found`], [_extensionFileNotFound().default, err => `file "${err.path}" was not found`], [_extensionNameNotValid().default, err => `error: the extension name "${err.name}" is not a valid component id (it must contain a scope name) fix it on your bit.json file`], [_exceptions3().ProtocolNotSupported, () => 'error: remote scope protocol is not supported, please use: `ssh://`, `file://` or `bit://`'], [_exceptions3().RemoteScopeNotFound, err => `error: remote scope "${_chalk().default.bold(err.name)}" was not found.`], [_exceptions().InvalidBitId, () => 'error: component ID is invalid, please use the following format: [scope]/<name>'], [_invalidConfigDir().default, err => `error: the eject path is already part of "${_chalk().default.bold(err.compId)}" path`], [_ejectToWorkspace().default, () => 'error: could not eject config to the workspace root please provide a valid path'], [_ejectBoundToWorkspace().default, () => 'error: could not eject config for authored component which are bound to the workspace configuration'], [_injectNonEjected().default, () => 'error: could not inject config for already injected component'], [_componentsPendingImport().default, () => _statusCmd().importPendingMsg], [_ejectNoDir().default, err => `error: could not eject config for ${_chalk().default.bold(err.compId)}, please provide path which doesn't contain {${_constants().COMPONENT_DIR}} to eject`], [_exceptions4().ComponentNotFound, err => {
  const msg = err.dependentId ? `error: the component dependency "${_chalk().default.bold(err.id)}" required by "${_chalk().default.bold(err.dependentId)}" was not found` : `error: component "${_chalk().default.bold(err.id)}" was not found`;
  return msg;
}], [_exceptions4().CorruptedComponent, err => `error: the model representation of "${_chalk().default.bold(err.id)}" is corrupted, the object of version ${err.version} is missing.\n${reportIssueToGithubMsg}`], [_exceptions4().DependencyNotFound, err => `error: dependency "${_chalk().default.bold(err.id)}" was not found. please track this component or use --ignore-unresolved-dependencies flag (not recommended)`], [_exceptions6().EmptyDirectory, () => _chalk().default.yellow('directory is empty, no files to add')], [_validationError().default, err => `${err.message}\n${reportIssueToGithubMsg}`], [_componentNotFoundInPath().default, err => `error: component in path "${_chalk().default.bold(err.path)}" was not found`], [_permissionDenied().default, err => `error: permission to scope ${err.scope} was denied\nsee troubleshooting at https://${_constants().BASE_DOCS_DOMAIN}/docs/authentication-issues.html`], [_remoteNotFound().default, err => `error: remote "${_chalk().default.bold(err.name)}" was not found`], [_exceptions3().NetworkError, err => `error: remote failed with error the following error:\n "${_chalk().default.bold(err.remoteErr)}"`], [_exceptions4().HashMismatch, err => `found hash mismatch of ${_chalk().default.bold(err.id)}, version ${_chalk().default.bold(err.version)}.
  originalHash: ${_chalk().default.bold(err.originalHash)}.
  currentHash: ${_chalk().default.bold(err.currentHash)}
  this usually happens when a component is old and the migration script was not running or interrupted`], [_exceptions4().HashNotFound, err => `hash ${_chalk().default.bold(err.hash)} not found`], [_exceptions4().MergeConflict, err => `error: merge conflict occurred while importing the component ${err.id}. conflict version(s): ${err.versions.join(', ')}
to resolve it and merge your local and remote changes, please do the following:
1) bit untag ${err.id} ${err.versions.join(' ')}
2) bit import
3) bit checkout ${err.versions.join(' ')} ${err.id}
once your changes are merged with the new remote version, you can tag and export a new version of the component to the remote scope.`], [_exceptions4().MergeConflictOnRemote, err => `error: merge conflict occurred when exporting the component(s) ${err.idsAndVersions.map(i => `${_chalk().default.bold(i.id)} (version(s): ${i.versions.join(', ')})`).join(', ')} to the remote scope.
to resolve this conflict and merge your remote and local changes, please do the following:
1) bit untag [id] [version]
2) bit import
3) bit checkout [version] [id]
once your changes are merged with the new remote version, please tag and export a new version of the component to the remote scope.`], [_exceptions4().OutdatedIndexJson, err => `error: component ${_chalk().default.bold(err.componentId)} found in the index.json file, however, is missing from the scope.
to get the file rebuild, please delete it at "${err.indexJsonPath}".\n${reportIssueToGithubMsg}
`], [_exceptions4().CyclicDependencies, err => `${err.msg.toString().toLocaleLowerCase()}`], [_exceptions3().UnexpectedNetworkError, err => `error: unexpected network error has occurred. ${err.message ? ` original message: ${err.message}` : ''}`], [_remoteResolverError().default, err => `error: ${err.message ? `${err.message}` : 'unexpected remote resolver error has occurred'}`], [_exportAnotherOwnerPrivate().default, err => `error: unable to export components to ${err.destinationScope} because they have dependencies on components in ${err.sourceScope}.
bit does not allow setting dependencies between components in private collections managed by different owners.

see troubleshooting at https://${_constants().BASE_DOCS_DOMAIN}/docs/bitdev-permissions.html`], [_exceptions3().SSHInvalidResponse, () => `error: received an invalid response from the remote SSH server.
to see the invalid response, have a look at the log, located at ${_constants().DEBUG_LOG}`], [_exceptions4().InvalidIndexJson, err => `fatal: your .bit/index.json is not a valid JSON file.
To rebuild the file, please run ${_chalk().default.bold('bit init --reset')}.
Original Error: ${err.message}`], [_exceptions4().ScopeNotFound, err => `error: scope not found at ${_chalk().default.bold(err.scopePath)}`], [_exceptions4().ScopeJsonNotFound, err => `error: scope.json file was not found at ${_chalk().default.bold(err.path)}, please use ${_chalk().default.bold('bit init')} to recreate the file`], [_missingDiagnosisName().default, err => 'error: please provide a diagnosis name'], [_diagnosisNotFound().default, err => `error: diagnosis ${_chalk().default.bold(err.diagnosisName)} not found`], [_exceptions2().ComponentSpecsFailed, err => formatComponentSpecsFailed(err.id, err.specsResults)], [_exceptions2().ComponentOutOfSync, err => `component ${_chalk().default.bold(err.id)} is not in-sync between the consumer and the scope.
if it is originated from another git branch, go back to that branch to continue working on the component.
if possible, remove the component using "bit remove" and re-import or re-create it.
to re-start Bit from scratch, deleting all objects from the scope, use "bit init --reset-hard"`], [_exceptions2().MissingDependencies, err => {
  const missingDepsColored = (0, _componentIssuesTemplate().default)(err.components);
  return `error: issues found with the following component dependencies\n${missingDepsColored}`;
}], [_exceptions2().NothingToImport, () => _chalk().default.yellow('nothing to import. please use `bit import [component_id]`')], [_exceptions().InvalidIdChunk, err => `error: "${_chalk().default.bold(err.id)}" is invalid, component IDs can only contain alphanumeric, lowercase characters, and the following ["-", "_", "$", "!"]`], [_exceptions().InvalidName, err => `error: "${_chalk().default.bold(err.componentName)}" is invalid, component names can only contain alphanumeric, lowercase characters, and the following ["-", "_", "$", "!", "/"]`], [_exceptions().InvalidScopeName, err => `error: "${_chalk().default.bold(err.scopeName)}" is invalid, component scope names can only contain alphanumeric, lowercase characters, and the following ["-", "_", "$", "!"]`], [_invalidBitJson().default, err => `error: invalid bit.json: ${_chalk().default.bold(err.path)} is not a valid JSON file.
consider running ${_chalk().default.bold('bit init --reset')} to recreate the file`], [_invalidPackageJson().default, err => `error: package.json at ${_chalk().default.bold(err.path)} is not a valid JSON file.
please fix the file in order to run bit commands`], [_invalidConfigPropPath().default, err => `error: the path "${_chalk().default.bold(err.fieldValue)}" of "${_chalk().default.bold(err.fieldName)}" in your bit.json or package.json file is invalid.
please make sure it's not absolute and doesn't contain invalid characters`], [_driver().DriverNotFound, err => `error: a client-driver ${_chalk().default.bold(err.driver)} is missing for the language ${_chalk().default.bold(err.lang)} set in your bit.json file.`], [_exceptions5().MissingMainFile, err => `error: the component ${_chalk().default.bold(err.componentId)} does not contain a main file.\nplease either use --id to group all added files as one component or use our DSL to define the main file dynamically.\nsee troubleshooting at https://${_constants().BASE_DOCS_DOMAIN}/docs/isolating-and-tracking-components.html#define-a-components-main-file`], [_exceptions6().MissingMainFileMultipleComponents, err => `error: the components ${_chalk().default.bold(err.componentIds.join(', '))} does not contain a main file.\nplease either use --id to group all added files as one component or use our DSL to define the main file dynamically.\nsee troubleshooting at https://${_constants().BASE_DOCS_DOMAIN}/docs/isolating-and-tracking-components.html#define-a-components-main-file`], [_exceptions5().InvalidBitMap, err => `error: unable to parse your bitMap file at ${_chalk().default.bold(err.path)}, due to an error ${_chalk().default.bold(err.errorMessage)}.
      consider running ${_chalk().default.bold('bit init --reset')} to recreate the file`], [_exceptions6().ExcludedMainFile, err => `error: main file ${_chalk().default.bold(err.mainFile)} was excluded from file list`], [_mainFileRemoved().default, err => `error: main file ${_chalk().default.bold(err.mainFile)} was removed from ${_chalk().default.bold(err.id)}.
please use "bit remove" to delete the component or "bit add" with "--main" and "--id" flags to add a new mainFile`], [_exceptions6().VersionShouldBeRemoved, err => `please remove the version part from the specified id ${_chalk().default.bold(err.id)} and try again`], [_exceptions6().TestIsDirectory, err => `error: the specified test path ${_chalk().default.bold(err.path)} is a directory, please specify a file or a pattern DSL`], [_exceptions6().MainFileIsDir, err => `error: the specified main path ${_chalk().default.bold(err.mainFile)} is a directory, please specify a file or a pattern DSL`], [_missingFilesFromComponent().default, err => {
  return `component ${err.id} is invalid as part or all of the component files were deleted. please use \'bit remove\' to resolve the issue`;
}], [_exceptions5().MissingBitMapComponent, err => `error: component "${_chalk().default.bold(err.id)}" was not found on your local workspace.\nplease specify a valid component ID or track the component using 'bit add' (see 'bit add --help' for more information)`], [_exceptions6().PathsNotExist, err => `error: file or directory "${_chalk().default.bold(err.paths.join(', '))}" was not found.`], [_exceptions6().PathOutsideConsumer, err => `error: file or directory "${_chalk().default.bold(err.path)}" is located outside of the workspace.`], [_exceptions7().WriteToNpmrcError, err => `unable to add @bit as a scoped registry at "${_chalk().default.bold(err.path)}"`], [_exceptions7().PathToNpmrcNotExist, err => `error: file or directory "${_chalk().default.bold(err.path)}" was not found.`], [_exceptions4().VersionNotFound, err => `error: version "${_chalk().default.bold(err.version)}" was not found.`], [_exceptions6().MissingComponentIdForImportedComponent, err => `error: unable to add new files to the component "${_chalk().default.bold(err.id)}" without specifying a component ID. please define the component ID using the --id flag.`], [_exceptions6().IncorrectIdForImportedComponent, err => `error: trying to add a file ${_chalk().default.bold(err.filePath)} to a component-id "${_chalk().default.bold(err.newId)}", however, this file already belong to "${_chalk().default.bold(err.importedId)}"`], [_exceptions6().NoFiles, err => _chalk().default.yellow('warning: no files to add') + _chalk().default.yellow(err.ignoredFiles ? `, the following files were ignored: ${_chalk().default.bold(err.ignoredFiles)}` : '')], [_exceptions6().DuplicateIds, err => Object.keys(err.componentObject).map(key => {
  return `unable to add ${Object.keys(err.componentObject[key]).length} components with the same ID: ${_chalk().default.bold(key)} : ${err.componentObject[key]}\n`;
}).join(' ')], [_idExportedAlready().default, err => `component ${_chalk().default.bold(err.id)} has been already exported to ${_chalk().default.bold(err.remote)}`], [_invalidVersion().default, err => `error: version ${_chalk().default.bold(err.version)} is not a valid semantic version. learn more: https://semver.org`], [_noIdMatchWildcard().default, err => `unable to find component ids that match the following: ${err.idsWithWildcards.join(', ')}`], [_nothingToCompareTo().default, err => 'no previous versions to compare'], [_exceptions2().NewerVersionFound, // err => JSON.stringify(err.newerVersions)
err => (0, _newerVersionTemplate().default)(err.newerVersions)], [_promptCanceled().default, err => _chalk().default.yellow('operation aborted')], [_externalTestErrors().default, err => `error: bit failed to test ${err.id} with the following exception:\n${getExternalErrorsMessageAndStack(err.originalErrors)}`], [_externalBuildErrors().default, err => `error: bit failed to build ${err.id} with the following exception:\n${getExternalErrorsMessageAndStack(err.originalErrors)}`], [_extensionLoadError().default, err => `error: bit failed to load ${err.compName} with the following exception:\n${getExternalErrorMessage(err.originalError)}.\n${err.printStack ? err.originalError.stack : ''}`], [_extensionSchemaError().default, err => `error: configuration passed to extension ${_chalk().default.bold(err.extensionName)} is invalid:\n${err.errors}`], [_extensionInitError().default, err => `error: bit failed to initialized ${err.compName} with the following exception:\n${getExternalErrorMessage(err.originalError)}.\n${err.originalError.stack}`], [_extensionGetDynamicPackagesError().default, err => `error: bit failed to get the dynamic packages from ${err.compName} with the following exception:\n${err.originalError.message}.\n${err.originalError.stack}`], [_extensionGetDynamicConfigError().default, err => `error: bit failed to get the config from ${err.compName} with the following exception:\n${err.originalError.message}.\n${err.originalError.stack}`], [_invalidCompilerInterface().default, err => `"${err.compilerName}" does not have a valid compiler interface, it has to expose a compile method`], [_exceptions4().ResolutionException, err => `error: bit failed to require ${err.filePath} due to the following exception:\n${getExternalErrorMessage(err.originalError)}.\n${err.originalError.stack}`], [_gitNotFound().default, err => "error: unable to run command because git executable not found. please ensure git is installed and/or git_path is configured using the 'bit config set git_path <GIT_PATH>'"], [_exceptions3().AuthenticationFailed, err => `authentication failed. see troubleshooting at https://${_constants().BASE_DOCS_DOMAIN}/docs/authentication-issues.html\n\n${err.debugInfo}`], [_objectsWithoutConsumer().default, err => `error: unable to initialize a bit workspace. bit has found undeleted local objects at ${_chalk().default.bold(err.scopePath)}.
1. use the ${_chalk().default.bold('--reset-hard')} flag to clear all data and initialize an empty workspace.
2. if deleted by mistake, please restore .bitmap and bit.json.
3. force workspace initialization without clearing data use the ${_chalk().default.bold('--force')} flag.`]];

function formatComponentSpecsFailed(id, specsResults) {
  // $FlowFixMe this.specsResults is not null at this point
  const specsResultsPretty = specsResults ? (0, _chalkBox().paintSpecsResults)(specsResults).join('\n') : '';
  const componentIdPretty = id ? _chalk().default.bold.white(id) : '';
  const specsResultsAndIdPretty = `${componentIdPretty}${specsResultsPretty}\n`;
  const additionalInfo = 'component tests failed. please make sure all tests pass before tagging a new version or use the "--force" flag to force-tag components.\nto view test failures, please use the "--verbose" flag or use the "bit test" command';
  const res = `${specsResultsAndIdPretty}${additionalInfo}`;
  return res;
}

function findErrorDefinition(err) {
  const error = errorsMap.find(([ErrorType]) => {
    return err instanceof ErrorType || err.name === ErrorType.name; // in some cases, such as forked process, the received err is serialized.
  });
  return error;
}

function getErrorFunc(errorDefinition) {
  if (!errorDefinition) return null;
  const [, func] = errorDefinition;
  return func;
}

function getErrorMessage(error, func) {
  if (!error || !func) return '';
  let errorMessage = func(error);

  if (error.showDoctorMessage) {
    errorMessage = `${errorMessage}

run 'bit doctor' to get detailed workspace diagnosis and issue resolution.`;
  }

  return errorMessage;
}

function getExternalErrorMessage(externalError) {
  if (!externalError) return ''; // In case an error is not a real error

  if (!(externalError instanceof Error)) {
    return externalError;
  } // In case it's not a bit error


  if (externalError.message) {
    return externalError.message;
  }

  const errorDefinition = findErrorDefinition(externalError);
  const func = getErrorFunc(errorDefinition);
  const errorMessage = getErrorMessage(externalError, func);
  return errorMessage;
}

function getExternalErrorsMessageAndStack(errors) {
  const result = errors.map(e => {
    const msg = getExternalErrorMessage(e);
    const stack = e.stack || '';
    return `${msg}\n${stack}\n`;
  }).join('~~~~~~~~~~~~~\n');
  return result;
}
/**
 * if err.userError is set, it inherits from AbstractError, which are user errors not Bit errors
 * and should not be reported to Sentry.
 * reason why we don't check (err instanceof AbstractError) is that it could be thrown from a fork,
 * in which case, it loses its class and has only the fields.
 */


function sendToAnalyticsAndSentry(err) {
  const possiblyHashedError = (0, _hashErrorObject().default)(err); // only level FATAL are reported to Sentry.
  // $FlowFixMe

  const level = err.isUserError ? _analytics().LEVEL.INFO : _analytics().LEVEL.FATAL;

  _analytics().Analytics.setError(level, possiblyHashedError);
}

var _default = err => {
  const errorDefinition = findErrorDefinition(err);
  sendToAnalyticsAndSentry(err);

  if (!errorDefinition) {
    return _chalk().default.red(err.message || err);
  }

  const func = getErrorFunc(errorDefinition);
  const errorMessage = getErrorMessage(err, func) || 'unknown error';
  err.message = errorMessage;

  _logger().default.error(`User gets the following error: ${errorMessage}`);

  return _chalk().default.red(errorMessage);
};

exports.default = _default;