oclif-web-ui
Version:
A Web UI for any CLI written with oclif
77 lines (76 loc) • 2.83 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const fastify_1 = tslib_1.__importDefault(require("fastify"));
const fastify_static_1 = tslib_1.__importDefault(require("fastify-static"));
const path = tslib_1.__importStar(require("path"));
const command_1 = tslib_1.__importDefault(require("../command"));
class Server {
constructor(cliConfig, cliCommands) {
this.cliConfig = cliConfig;
this.cliCommands = cliCommands;
this.server = fastify_1.default({ logger: false });
this.setupFastify();
}
setupFastify() {
this.server.register(fastify_static_1.default, {
root: path.join(__dirname, '../web-cli/dist')
});
this.server.setNotFoundHandler((request, reply) => {
if (request.raw.method !== 'GET') {
return reply.status(404);
}
else if (!request.headers || typeof request.headers.accept !== 'string') {
return reply.status(404);
}
else if (request.headers.accept.indexOf('application/json') === 0) {
return reply.status(404);
}
else if (!this.acceptsHtml(request.headers.accept)) {
return reply.status(404);
}
reply.sendFile('index.html');
});
this.server.get('/data/config', async (request, reply) => {
return this.cliConfig;
});
this.server.get('/data/commands', async (request, reply) => {
return this.cliCommands;
});
this.server.get('/end', async (request, reply) => {
process.exit(1);
});
this.server.post('/data/run', async (request, reply) => {
const { commandId } = request.body;
const c = this.cliConfig.findCommand(commandId);
if (!c) {
// await this.runHook('command_not_found', {id})
// throw new CLIError(`command ${id} not found`)
throw new Error('command not found');
}
const command = c.load();
// await this.runHook('prerun', {Command: command, argv})
await command.run();
return command_1.default.getAndClearLogs();
});
}
acceptsHtml(header) {
const htmlAcceptHeaders = ['text/html', '*/*'];
for (let i = 0; i < htmlAcceptHeaders.length; i += 1) {
if (header.indexOf(htmlAcceptHeaders[i]) !== -1) {
return true;
}
}
return false;
}
async startServer() {
try {
await this.server.listen(3000);
}
catch (err) {
this.server.log.error(err);
process.exit(1);
}
}
}
exports.Server = Server;