"use strict";

var _hmrClient = _interopRequireDefault(require("hmr-client"));

var _lodash = _interopRequireDefault(require("lodash"));

var _formatWebpackMessages = _interopRequireDefault(require("react-dev-utils/formatWebpackMessages"));

var _stripAnsi = _interopRequireDefault(require("strip-ansi"));

var _reactErrorOverlay = require("react-error-overlay");

var _core = require("@reactant/core");

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

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

if (_core.config.options.debug) window.module = module;
let hadServerError = false;
let hadError = false;
let hash = null;
let isFirstCompilation = true;
(0, _reactErrorOverlay.startReportingRuntimeErrors)({
  onError: () => {
    hadError = true;
    return true;
  },
  filename: `${_core.config.paths.distWebPublic}/scripts/bundle.js`
});

if (module.hot && _lodash.default.isFunction(module.hot.dispose)) {
  module.hot.dispose(() => (0, _reactErrorOverlay.stopReportingRuntimeErrors)());
}

const client = new _hmrClient.default({
  port: _core.config.ports.dev
});
client.onConnected =
/*#__PURE__*/
_asyncToGenerator(function* () {
  _core.log.silly('connected');
});

client.onHash =
/*#__PURE__*/
function () {
  var _ref2 = _asyncToGenerator(function* (message) {
    if (hash) _core.log.silly('hot reloading');

    _core.log.silly('hash', hash);

    hash = message.data;
  });

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

client.onStillOk =
/*#__PURE__*/
_asyncToGenerator(function* () {
  _core.log.silly('still-ok');
});
client.onOk =
/*#__PURE__*/
_asyncToGenerator(function* () {
  _core.log.silly('ok');

  yield handleSuccess();
});

client.onContentChanged = () => {
  _core.log.silly('content-changed');

  windowReload();
};

client.onWarngins = message => {
  _core.log.silly('warnings');

  handleWarnings(message.data);
};

client.onErrors = message => {
  _core.log.silly('errors');

  handleErrors(message.data);
};

client.onClose = () => {
  _core.log.silly('close');

  _core.log.debug('The development server has disconnected.\n' + 'Refresh the page if necessary.');
};

function handleSuccess() {
  return _handleSuccess.apply(this, arguments);
}

function _handleSuccess() {
  _handleSuccess = _asyncToGenerator(function* () {
    clearErrors();
    const isHotUpdate = !isFirstCompilation;

    try {
      if (isHotUpdate) {
        yield applyUpdates();
        (0, _reactErrorOverlay.dismissBuildError)();
      }
    } catch (err) {
      (0, _reactErrorOverlay.reportBuildError)(err.stack);

      _core.log.error(err);

      hadError = true;
    }

    isFirstCompilation = false;
  });
  return _handleSuccess.apply(this, arguments);
}

function handleErrors(_x2) {
  return _handleErrors.apply(this, arguments);
}

function _handleErrors() {
  _handleErrors = _asyncToGenerator(function* (errors) {
    clearErrors();
    const formatted = (0, _formatWebpackMessages.default)({
      errors,
      warnings: []
    });
    (0, _reactErrorOverlay.reportBuildError)(formatted.errors[0]);

    _lodash.default.each(formatted.errors, (error, index) => {
      if (index < formatted.errors.length) {
        if (index === 5) {
          _core.log.error('There were more errors in other files.\n' + 'You can find a complete log in the terminal.');
        }

        _core.log.error((0, _stripAnsi.default)(error));

        return true;
      }

      return false;
    });

    hadServerError = true;
    hadError = true;
    isFirstCompilation = false;
  });
  return _handleErrors.apply(this, arguments);
}

function handleWarnings(_x3) {
  return _handleWarnings.apply(this, arguments);
}

function _handleWarnings() {
  _handleWarnings = _asyncToGenerator(function* (warnings) {
    clearErrors();
    const isHotUpdate = !isFirstCompilation;

    function printWarnings() {
      const formatted = (0, _formatWebpackMessages.default)({
        warnings,
        errors: []
      });

      _lodash.default.each(formatted.warnings, (warning, index) => {
        if (index < formatted.warnings.length) {
          if (index === 5) {
            _core.log.warn('There were more warnings in other files.\n' + 'You can find a complete log in the terminal.');
          }

          _core.log.warn((0, _stripAnsi.default)(warning));
        }
      });
    }

    printWarnings();

    try {
      if (isHotUpdate) {
        yield applyUpdates();
        (0, _reactErrorOverlay.dismissBuildError)();
      }
    } catch (err) {
      (0, _reactErrorOverlay.reportBuildError)(err.stack);

      _core.log.error(err);

      hadError = true;
    }

    isFirstCompilation = false;
  });
  return _handleWarnings.apply(this, arguments);
}

window.hothot = module.hot;

function applyUpdates() {
  return _applyUpdates.apply(this, arguments);
}

function _applyUpdates() {
  _applyUpdates = _asyncToGenerator(function* () {
    if (!module.hot) return windowReload();
    if (!isUpdateAvailable() || module.hot.status() !== 'idle') return false;
    return new Promise((resolve, reject) => {
      function handleApplyUpdates(err, _updatedModules) {
        if (err && !hadServerError) return reject(err);
        if (hadServerError) hadServerError = false;
        if (isUpdateAvailable()) applyUpdates().then(() => resolve());
        return resolve();
      }

      const result = module.hot.check(true, handleApplyUpdates);

      if (result && result.then) {
        return result.then(updatedModules => handleApplyUpdates(null, updatedModules)).catch(err => handleApplyUpdates(err, null));
      }

      return result;
    });
  });
  return _applyUpdates.apply(this, arguments);
}

function isUpdateAvailable() {
  return hash !== __webpack_hash__;
}

function clearErrors() {
  if (module.hot.status() === 'fail') {
    windowReload();
  } else if (hadError) {
    hadError = false;
    consoleClear();
    (0, _reactErrorOverlay.dismissBuildError)();
  }
}

function windowReload() {
  if (_core.config.options.debug) {
    _core.log.debug('reloading window');
  } else {
    window.location.reload();
  }
}

function consoleClear() {
  if (_core.config.options.debug) {
    _core.log.debug('cleared console');
  } else {
    // eslint-disable-next-line no-console
    console.clear();
  }
}