'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports.restoreGlobalErrorHandlers = exports.injectGlobalErrorHandlers = void 0;

var _state = require('./state');

var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;

const uncaught = error => {
  (0, _state.dispatch)({
    error,
    name: 'error'
  });
};

const injectGlobalErrorHandlers = parentProcess => {
  const uncaughtException = process.listeners('uncaughtException').slice();
  const unhandledRejection = process.listeners('unhandledRejection').slice();
  parentProcess.removeAllListeners('uncaughtException');
  parentProcess.removeAllListeners('unhandledRejection');
  parentProcess.on('uncaughtException', uncaught);
  parentProcess.on('unhandledRejection', uncaught);
  return {
    uncaughtException,
    unhandledRejection
  };
};

exports.injectGlobalErrorHandlers = injectGlobalErrorHandlers;

const restoreGlobalErrorHandlers = (parentProcess, originalErrorHandlers) => {
  parentProcess.removeListener('uncaughtException', uncaught);
  parentProcess.removeListener('unhandledRejection', uncaught);
  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (
      var _iterator = originalErrorHandlers.uncaughtException[
          Symbol.iterator
        ](),
        _step;
      !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
      _iteratorNormalCompletion = true
    ) {
      const listener = _step.value;
      parentProcess.on('uncaughtException', listener);
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return != null) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  var _iteratorNormalCompletion2 = true;
  var _didIteratorError2 = false;
  var _iteratorError2 = undefined;

  try {
    for (
      var _iterator2 = originalErrorHandlers.unhandledRejection[
          Symbol.iterator
        ](),
        _step2;
      !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done);
      _iteratorNormalCompletion2 = true
    ) {
      const listener = _step2.value;
      parentProcess.on('unhandledRejection', listener);
    }
  } catch (err) {
    _didIteratorError2 = true;
    _iteratorError2 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
        _iterator2.return();
      }
    } finally {
      if (_didIteratorError2) {
        throw _iteratorError2;
      }
    }
  }
};

exports.restoreGlobalErrorHandlers = restoreGlobalErrorHandlers;
