UNPKG

mcp-quiz-server

Version:

🧠 AI-Powered Quiz Management via Model Context Protocol (MCP) - Create, manage, and take quizzes directly from VS Code, Claude, and other AI agents.

212 lines (211 loc) 7.86 kB
"use strict"; /** * @fileoverview Simplified Server Application for OSS Version * @module ServerApplication * @description Lightweight HTTP server without authentication/SSE complexity * @version 2.2.0 * @since 2025-08-05 * @contributors GitHub Copilot (OSS Simplification) * @dependencies Express, RouteRegistry, Database * @requirements Basic HTTP server, Quiz CRUD operations */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ServerApplication = void 0; const cors_1 = __importDefault(require("cors")); const express_1 = __importDefault(require("express")); const helmet_1 = __importDefault(require("helmet")); const morgan_1 = __importDefault(require("morgan")); const path_1 = __importDefault(require("path")); require("reflect-metadata"); // Required for TypeORM decorators const init_1 = require("../../database/init"); const audit_logger_1 = require("../../shared/audit-logger"); const error_handler_1 = require("../../shared/error-handler"); const openapi_generator_1 = require("../../utils/openapi-generator"); const ServiceRegistry_1 = require("../di/ServiceRegistry"); const RouteRegistry_1 = require("./routes/RouteRegistry"); /** * Simplified Server Application for OSS Version * Provides basic HTTP server functionality without authentication complexity */ class ServerApplication { constructor(config = {}) { this.app = (0, express_1.default)(); this.config = { port: 3000, enableCors: true, enableHelmet: true, enableLogging: true, staticPath: path_1.default.join(process.cwd(), 'public'), enableSwagger: true, ...config, }; error_handler_1.Logger.info('🏗️ Initializing ServerApplication (OSS Version)', { config: this.config }); } /** * Initialize server components */ async initialize() { try { error_handler_1.Logger.info('🚀 Initializing ServerApplication components...'); // Initialize database const databaseInitializer = new init_1.DatabaseInitializer(); const dataSource = await databaseInitializer.initialize(); error_handler_1.Logger.info('✅ Database initialized'); // Initialize audit logging this.auditLogger = await (0, audit_logger_1.initializeAuditLogger)(); error_handler_1.Logger.info('✅ Audit logging initialized'); // Setup dependency injection const container = (0, ServiceRegistry_1.createContainer)(dataSource); error_handler_1.Logger.info('✅ DI Container created'); // Configure Express middleware await this.configureMiddleware(); error_handler_1.Logger.info('✅ Middleware configured'); // Setup routes await this.setupRoutes(); error_handler_1.Logger.info('✅ Routes configured'); // Setup error handling this.setupErrorHandling(); error_handler_1.Logger.info('✅ Error handling configured'); error_handler_1.Logger.info('🎉 ServerApplication initialization complete'); } catch (error) { error_handler_1.Logger.error('❌ Failed to initialize ServerApplication:', error instanceof Error ? error : new Error(String(error))); throw error; } } /** * Start the HTTP server */ async start() { return new Promise((resolve, reject) => { try { this.server = this.app.listen(this.config.port, () => { this.startTime = new Date(); error_handler_1.Logger.info(`🚀 Server started on http://localhost:${this.config.port}`); resolve(); }); this.server.on('error', (error) => { error_handler_1.Logger.error('❌ Server error:', error); reject(error); }); } catch (error) { error_handler_1.Logger.error('❌ Failed to start server:', error instanceof Error ? error : new Error(String(error))); reject(error); } }); } /** * Stop the HTTP server */ async stop() { return new Promise((resolve) => { if (this.server) { this.server.close(() => { error_handler_1.Logger.info('🛑 Server stopped'); resolve(); }); } else { resolve(); } }); } /** * Get server status */ getStatus() { var _a; return { isRunning: !!this.server, port: this.config.port, routes: (_a = this.routeRegistry) === null || _a === void 0 ? void 0 : _a.getStatus(), uptime: this.startTime ? Date.now() - this.startTime.getTime() : 0, version: '2.2.0-oss', }; } /** * Get Express app instance */ getApp() { return this.app; } /** * Configure Express middleware */ async configureMiddleware() { // Security middleware if (this.config.enableHelmet) { this.app.use((0, helmet_1.default)({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], styleSrc: ["'self'", "'unsafe-inline'"], scriptSrc: ["'self'"], imgSrc: ["'self'", "data:", "https:"], }, }, })); } // CORS middleware if (this.config.enableCors) { this.app.use((0, cors_1.default)({ origin: ['http://localhost:3000', 'http://127.0.0.1:3000'], credentials: true, })); } // Logging middleware if (this.config.enableLogging) { this.app.use((0, morgan_1.default)('combined')); } // Body parsing middleware this.app.use(express_1.default.json({ limit: '10mb' })); this.app.use(express_1.default.urlencoded({ extended: true, limit: '10mb' })); // Audit middleware if (this.auditLogger) { this.app.use((0, audit_logger_1.createAuditMiddleware)(this.auditLogger)); } // Static file serving if (this.config.staticPath) { this.app.use(express_1.default.static(this.config.staticPath)); } } /** * Setup application routes */ async setupRoutes() { const routeConfig = { app: this.app, auditLogger: this.auditLogger, environment: 'oss', // Authentication disabled for OSS version }; this.routeRegistry = new RouteRegistry_1.RouteRegistry(routeConfig); await this.routeRegistry.registerAllRoutes(); // Setup Swagger UI if (this.config.enableSwagger) { (0, openapi_generator_1.setupSwaggerUI)(this.app); } error_handler_1.Logger.info('✅ Routes registered successfully'); } /** * Setup error handling middleware */ setupErrorHandling() { // 404 handler this.app.use('*', (req, res) => { res.status(404).json({ success: false, error: 'Endpoint not found', path: req.originalUrl, method: req.method, }); }); // Global error handler this.app.use(error_handler_1.errorHandler); } } exports.ServerApplication = ServerApplication;