@web/dev-server-core
Version:
94 lines • 3.7 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DevServer = void 0;
const chokidar_1 = __importDefault(require("chokidar"));
const util_1 = require("util");
const createServer_js_1 = require("./createServer.js");
const WebSocketsManager_js_1 = require("../web-sockets/WebSocketsManager.js");
class DevServer {
constructor(config, logger, fileWatcher = chokidar_1.default.watch([], config.chokidarOptions)) {
this.config = config;
this.logger = logger;
this.fileWatcher = fileWatcher;
this.started = false;
this.connections = new Set();
if (!config)
throw new Error('Missing config.');
if (!logger)
throw new Error('Missing logger.');
const { app, server } = (0, createServer_js_1.createServer)(this.logger, this.config, this.fileWatcher, !!config.middlewareMode);
this.koaApp = app;
if (server) {
this.server = server;
this.webSockets = new WebSocketsManager_js_1.WebSocketsManager(this.server);
this.server.on('connection', connection => {
this.connections.add(connection);
connection.on('close', () => {
this.connections.delete(connection);
});
});
}
else if (typeof this.config.middlewareMode === 'object' &&
this.config.middlewareMode.server) {
this.webSockets = new WebSocketsManager_js_1.WebSocketsManager(this.config.middlewareMode.server);
}
}
async start() {
var _a, _b;
this.started = true;
if (this.server && this.config.hostname) {
await (0, util_1.promisify)(this.server.listen).bind(this.server)({
port: this.config.port,
// in case of localhost the host should be undefined, otherwise some browsers
// connect to it via local network. for example safari on browserstack
host: ['localhost', '127.0.0.1'].includes(this.config.hostname)
? undefined
: this.config.hostname,
});
}
for (const plugin of (_a = this.config.plugins) !== null && _a !== void 0 ? _a : []) {
await ((_b = plugin.serverStart) === null || _b === void 0 ? void 0 : _b.call(plugin, {
config: this.config,
app: this.koaApp,
server: this.server,
logger: this.logger,
webSockets: this.webSockets,
fileWatcher: this.fileWatcher,
}));
}
}
closeServer() {
if (!this.server) {
return;
}
// close all open connections
for (const connection of this.connections) {
connection.destroy();
}
return new Promise(resolve => {
this.server.close(err => {
if (err) {
console.error(err);
}
resolve();
});
});
}
async stop() {
var _a;
if (!this.started) {
return;
}
this.started = false;
return Promise.all([
this.fileWatcher.close(),
...((_a = this.config.plugins) !== null && _a !== void 0 ? _a : []).map(p => { var _a; return (_a = p.serverStop) === null || _a === void 0 ? void 0 : _a.call(p); }),
this.closeServer(),
]);
}
}
exports.DevServer = DevServer;
//# sourceMappingURL=DevServer.js.map