UNPKG

@aimee-blue/ab-service-kit

Version:
161 lines (130 loc) 5.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.startCore = startCore; require("source-map-support/register"); var http = _interopRequireWildcard(require("http")); var https = _interopRequireWildcard(require("https")); var _fsExtra = _interopRequireDefault(require("fs-extra")); var _yargs = _interopRequireDefault(require("yargs")); var _path = require("path"); var _env = require("./shared/env"); var _setup = require("./setup"); var _initializeLogger = require("./setup/initializeLogger"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } const buildArgumentsParser = config => _yargs.default.option('http', { boolean: true, description: 'Disable encryption', default: false }).option('watch', { boolean: true, description: 'Watch code for changes', default: false }).option('port', { number: true, description: 'port to listen on', default: config.defaultPort }).option('host', { string: true, description: 'address to listen on' }).option('cert', { string: true, description: 'Path to an HTTPS certificate (must be full chain certificate)' }).option('key', { string: true, description: 'Path to an HTTPS private-key' }); async function startCore(config, args, optLogger) { var _config$shouldLoadEnv; const parser = buildArgumentsParser(config); const effectiveParser = config.argsBuilder ? config.argsBuilder(parser) : parser; const params = args || effectiveParser.parse(); const logger = optLogger !== null && optLogger !== void 0 ? optLogger : await (0, _initializeLogger.initializeLoggerOrFallback)(config); const shouldLoadEnvFiles = (_config$shouldLoadEnv = config.shouldLoadEnvFiles) !== null && _config$shouldLoadEnv !== void 0 ? _config$shouldLoadEnv : true; if (shouldLoadEnvFiles) { await (0, _env.loadEnv)({ envFile: params.envFile, logger }); } const certPath = params.cert || process.env.HTTPS_CERT_PATH; const keyPath = params.cert || process.env.HTTPS_KEY_PATH; const host = params.host || process.env.SERVER_HOSTNAME; const port = process.env.PORT || params.port; if (!params.http) { if (!certPath) { throw new Error('No certificate path provided. Please generate HTTPS certificate and key, or use --http option'); } if (!keyPath) { throw new Error('No private key path provided. Please generate HTTPS certificate and key, or use --http option'); } const certExist = await _fsExtra.default.pathExists(certPath); if (!certExist) { throw new Error(`Cannot find file at path '${certPath}'`); } const keyExist = await _fsExtra.default.pathExists(keyPath); if (!keyExist) { throw new Error(`Cannot find file at path '${keyPath}'`); } } const server = params.http ? http.createServer() : https.createServer({ cert: certPath && _fsExtra.default.readFileSync(certPath, 'utf8'), key: keyPath && _fsExtra.default.readFileSync(keyPath, 'utf8'), passphrase: process.env.HTTPS_PASSPHRASE }); const handleServerRequestsWithDevTools = async () => { if (params.watch) { const { serviceSetupInWatchMode } = await Promise.resolve().then(() => _interopRequireWildcard(require('./setup/watchServerCode'))); const configFile = config.serviceConfigModuleId || './lib/config.js'; const configFilePath = (0, _path.resolve)(configFile); const exists = await _fsExtra.default.pathExists(configFilePath); if (!exists) { throw new Error(`Cannot resolve service configuration module (${configFilePath}), setup is required for watch mode to work`); } return await serviceSetupInWatchMode(configFilePath, async newConfig => { return await (0, _setup.serviceSetup)(server, newConfig, params, logger); }); } else { return await (0, _setup.serviceSetup)(server, config, params, logger); } }; const teardown = await handleServerRequestsWithDevTools(); await new Promise((res, rej) => { let handled = false; server.on('error', err => { if (handled) { return; } handled = true; rej(err); }); server.listen({ port, host }, () => { if (handled) { return; } handled = true; const mode = params.http ? '(un-encrypted http/ws)' : "(https/wss) - Pass '--http' argument to disable encryption"; logger.log(`👍 PID ${process.pid}; Currently listening on ${[host, port].filter(Boolean).join(':')} ${mode}`); res(); }); }); return async () => { await teardown('destroy'); await new Promise((res, rej) => server.close(err => { if (err) { rej(err); } else { res(); } })); }; } //# sourceMappingURL=startCore.js.map