@verdaccio/node-api
Version:
node API
200 lines (194 loc) • 7.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createServerFactory = createServerFactory;
exports.initServer = initServer;
exports.runServer = runServer;
var _constants = _interopRequireDefault(require("constants"));
var _debug = _interopRequireDefault(require("debug"));
var _fs = _interopRequireDefault(require("fs"));
var _http = _interopRequireDefault(require("http"));
var _https = _interopRequireDefault(require("https"));
var _lodash = _interopRequireWildcard(require("lodash"));
var _url = _interopRequireDefault(require("url"));
var _config = require("@verdaccio/config");
var _core = require("@verdaccio/core");
var _logger = require("@verdaccio/logger");
var _server = _interopRequireDefault(require("@verdaccio/server"));
var _serverFastify = _interopRequireDefault(require("@verdaccio/server-fastify"));
var _cliUtils = require("./cli-utils");
var _experiments = require("./experiments");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable */
const debug = (0, _debug.default)('verdaccio:node-api');
function unlinkAddressPath(addr) {
if (addr.path && _fs.default.existsSync(addr.path)) {
_fs.default.unlinkSync(addr.path);
}
}
/**
* Return a native HTTP/HTTPS server instance
* @param config
* @param addr
* @param app
*/
function createServerFactory(config, addr, app) {
let serverFactory;
if (addr.proto === 'https') {
debug('https enabled');
try {
let httpsOptions = {
// disable insecure SSLv2 and SSLv3
secureOptions: _constants.default.SSL_OP_NO_SSLv2 | _constants.default.SSL_OP_NO_SSLv3
};
const keyCertConfig = config.https;
const pfxConfig = config.https;
// https must either have key and cert or a pfx and (optionally) a passphrase
if (!(keyCertConfig.key && keyCertConfig.cert || pfxConfig.pfx)) {
// logHTTPSError(configPath);
throw Error('bad format https configuration');
}
if (pfxConfig.pfx) {
const {
pfx,
passphrase
} = pfxConfig;
httpsOptions = (0, _lodash.assign)(httpsOptions, {
pfx: _fs.default.readFileSync(pfx),
passphrase: passphrase || ''
});
} else {
const {
key,
cert,
ca
} = keyCertConfig;
httpsOptions = (0, _lodash.assign)(httpsOptions, {
key: _fs.default.readFileSync(key),
cert: _fs.default.readFileSync(cert),
...(ca && {
ca: _fs.default.readFileSync(ca)
})
});
}
// TODO: enable http2 as feature
// if (config.server.http2) <-- check if force http2
serverFactory = _https.default.createServer(httpsOptions, app);
} catch (err) {
throw new Error(`cannot create https server: ${err.message}`);
}
} else {
// http
debug('http enabled');
serverFactory = _http.default.createServer(app);
}
if (config.server && typeof config.server.keepAliveTimeout !== 'undefined' &&
// @ts-ignore
config.server.keepAliveTimeout !== 'null') {
// library definition for node is not up to date (doesn't contain recent 8.0 changes)
serverFactory.keepAliveTimeout = config.server.keepAliveTimeout * 1000;
}
// FIXE: I could not find the reason of this code.
unlinkAddressPath(addr);
return serverFactory;
}
/**
* Start the server on the port defined
* @param config
* @param port
* @param version
* @param pkgName
*/
async function initServer(config, port, version, pkgName) {
return new Promise(async (resolve, reject) => {
// FIXME: get only the first match, the multiple address will be removed
const [addr] = (0, _cliUtils.getListListenAddresses)(port, config.listen);
const logger = (0, _logger.setup)(config === null || config === void 0 ? void 0 : config.log);
(0, _experiments.displayExperimentsInfoBox)(config.flags);
let app;
if (process.env.VERDACCIO_SERVER === 'fastify') {
app = await (0, _serverFastify.default)(config);
app.listen({
port: addr.port,
host: addr.host
}, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
} else {
app = await (0, _server.default)(config);
const serverFactory = createServerFactory(config, addr, app);
serverFactory.listen(addr.port || addr.path, addr.host, () => {
// send a message for test
if ((0, _lodash.isFunction)(process.send)) {
process.send({
verdaccio_started: true
});
}
const addressServer = `${addr.path ? _url.default.format({
protocol: 'unix',
pathname: addr.path
}) : _url.default.format({
protocol: addr.proto,
hostname: addr.host,
port: addr.port,
pathname: '/'
})}`;
logger.info(`http address ${addressServer}`);
logger.info(`version: ${version}`);
resolve();
}).on('error', function (err) {
reject(err);
process.exitCode = 1;
});
function handleShutdownGracefully() {
logger.info('received shutdown signal - closing server gracefully...');
serverFactory.close(() => {
logger.info('server closed.');
process.exit(0);
});
}
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
// Use once() so that receiving double signals exit the app.
process.once(signal, handleShutdownGracefully);
}
}
});
}
/**
* Exposes a server factory to be instantiated programmatically.
*
```ts
const app = await runServer(); // default configuration
const app = await runServer('./config/config.yaml');
const app = await runServer({ configuration });
app.listen(4000, (event) => {
// do something
});
```
* @param config
*/
async function runServer(config) {
let configurationParsed;
if (config === undefined || typeof config === 'string') {
const configPathLocation = (0, _config.findConfigFile)(config);
configurationParsed = (0, _config.parseConfigFile)(configPathLocation);
} else if (_lodash.default.isObject(config)) {
configurationParsed = config;
} else {
throw new Error(_core.API_ERROR.CONFIG_BAD_FORMAT);
}
(0, _logger.setup)(configurationParsed.log);
(0, _experiments.displayExperimentsInfoBox)(configurationParsed.flags);
// FIXME: get only the first match, the multiple address will be removed
const [addr] = (0, _cliUtils.getListListenAddresses)(undefined, configurationParsed.listen);
const app = await (0, _server.default)(configurationParsed);
return createServerFactory(configurationParsed, addr, app);
}
//# sourceMappingURL=server.js.map