"use strict";

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

require("@babel/polyfill");

var _express = _interopRequireDefault(require("express"));

var _log = _interopRequireWildcard(require("@reactant/core/log"));

var _ora = _interopRequireDefault(require("ora"));

var _path = _interopRequireDefault(require("path"));

var _ejs = require("ejs");

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

var _http = require("http");

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

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.verbose) (0, _log.setLevel)('verbose');
if (_core.config.options.debug) (0, _log.setLevel)('debug');
let errorApp = null;
let serverError = false;
let serverSpinner = (0, _ora.default)('starting server').start();

if (module.hot) {
  errorApp = (0, _express.default)();
  errorApp.disable('x-powered-by');
  errorApp.set('views', _path.default.resolve(__dirname, 'views'));
  errorApp.set('view engine', 'ejs');
  errorApp.engine('.ejs', _ejs.__express);
  errorApp.use(_express.default.static(_path.default.resolve(__dirname, 'views')));
  errorApp.use((req, res) => {
    return res.render('error', {
      config: _core.config,
      errStack: req.err.stack
    });
  });
}

function init() {
  return _init.apply(this, arguments);
}

function _init() {
  _init = _asyncToGenerator(function* () {
    const app = yield createApp();
    const server = (0, _http.createServer)(app);
    startServer(server);
    return app;
  });
  return _init.apply(this, arguments);
}

function createApp() {
  return _createApp.apply(this, arguments);
}

function _createApp() {
  _createApp = _asyncToGenerator(function* () {
    const _ref = yield require('@reactant/web-isomorphic/server').default,
          app = _ref.app;

    app.disable('x-powered-by');
    app.use((err, req, res, _next) => {
      if (err) {
        _log.default.error(err.stack);

        if (module.hot) {
          serverError = true;
          req.err = err;
          return errorApp.handle(req, res);
        }

        return res.status(500).send('Server error');
      }

      return res.status(404).send('Page not found');
    });
    return app;
  });
  return _createApp.apply(this, arguments);
}

function startServer(server) {
  const platform = _core.config.platform;
  server.listen(_core.config.port, _core.config.host, err => {
    if (err) throw err;
    serverSpinner.succeed(`server listening on port ${_core.config.port}`);

    if (module.hot) {
      module.hot.accept(`~/../${platform}/server.js`, () => {
        _log.default.info('[HMR] updating HMR');

        if (serverError) {
          serverError = false;
          serverSpinner = (0, _ora.default)('restarting server');
          server.close(() => {
            const app = createApp();
            const newServer = (0, _http.createServer)(app);
            startServer(newServer);
          });
        }
      });

      _log.default.info('[HMR] server HMR enabled');
    }
  });
}

var _default = init();

exports.default = _default;