"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const events_1 = __importDefault(require("events")); const http_1 = __importDefault(require("http")); const send_1 = __importDefault(require("send")); const url_1 = __importDefault(require("url")); const promise_1 = __importDefault(require("../utils/promise")); class Server extends events_1.default.EventEmitter { running; dir; port; sockets; constructor() { super(); this.running = null; this.dir = null; this.port = 0; this.sockets = []; } /** Return true if the server is running @return {boolean} */ isRunning() { return !!this.running; } /** Stop the server @return {Promise} */ stop() { const that = this; if (!this.isRunning()) return (0, promise_1.default)(); const d = promise_1.default.defer(); this.running.close((err) => { that.running = null; that.emit("state", false); if (err) d.reject(err); else d.resolve(); }); for (let i = 0; i < this.sockets.length; i++) { this.sockets[i].destroy(); } return d.promise; } /** Start the server @return {Promise} */ start(dir, port) { const that = this; let pre = (0, promise_1.default)(); port = port || 8004; if (that.isRunning()) pre = this.stop(); return pre.then(() => { const d = promise_1.default.defer(); that.running = http_1.default.createServer((req, res) => { // Render error function error(err) { res.statusCode = err.status || 500; res.end(err.message); } // Redirect to directory's index.html function redirect() { const resultURL = urlTransform(req.url, (parsed) => { parsed.pathname += "/"; return parsed; }); res.statusCode = 301; res.setHeader("Location", resultURL); res.end(`Redirecting to ${resultURL}`); } res.setHeader("X-Current-Location", req.url); // Send file (0, send_1.default)(req, url_1.default.parse(req.url).pathname, { root: dir }) .on("error", error) .on("directory", redirect) .pipe(res); }); that.running.on("connection", (socket) => { that.sockets.push(socket); socket.setTimeout(4000); socket.on("close", () => { that.sockets.splice(that.sockets.indexOf(socket), 1); }); }); that.running.listen(port, () => { that.port = port; that.dir = dir; that.emit("state", true); d.resolve(); }); return d.promise; }); } } /** urlTransform is a helper function that allows a function to transform a url string in it's parsed form and returns the new url as a string @param {string} uri @param {Function} fn @return {string} */ function urlTransform(uri, fn) { return url_1.default.format(fn(url_1.default.parse(uri))); } exports.default = Server;