mcp-swagger-parser
Version:
Enterprise-grade OpenAPI/Swagger specification parser for Model Context Protocol (MCP) projects
64 lines • 2.65 kB
JavaScript
;
/**
* File parser for OpenAPI specifications
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileParser = void 0;
const fs_1 = require("fs");
const path_1 = require("path");
const index_1 = require("../errors/index");
const base_parser_1 = require("./base-parser");
class FileParser extends base_parser_1.BaseParser {
/**
* Parse OpenAPI specification from file
*/
async parse(filePath, options = {}) {
const resolvedPath = (0, path_1.resolve)(filePath);
// Check if file exists
if (!(0, fs_1.existsSync)(resolvedPath)) {
throw new index_1.OpenAPIFileError(`File not found: ${resolvedPath}`, resolvedPath);
}
// Validate file extension if specified
const allowedExtensions = options.allowedExtensions || FileParser.DEFAULT_ALLOWED_EXTENSIONS;
const ext = (0, path_1.extname)(resolvedPath).toLowerCase();
if (allowedExtensions.length > 0 && !allowedExtensions.includes(ext)) {
throw new index_1.OpenAPIParseError(`Unsupported file extension: ${ext}. Allowed extensions: ${allowedExtensions.join(', ')}`, index_1.ERROR_CODES.INVALID_FORMAT, resolvedPath);
}
try {
// Read file content
const content = (0, fs_1.readFileSync)(resolvedPath, {
encoding: options.encoding || 'utf8'
});
// Parse based on file extension
let spec;
if (ext === '.yaml' || ext === '.yml') {
spec = await this.parseYaml(content);
}
else if (ext === '.json') {
spec = this.parseJson(content);
}
else {
// Auto-detect format for unknown extensions
const format = this.detectFormat(content);
if (format === 'json') {
spec = this.parseJson(content);
}
else {
spec = await this.parseYaml(content);
}
}
// Validate basic structure
this.validateBasicStructure(spec);
return spec;
}
catch (error) {
if (error instanceof index_1.OpenAPIParseError) {
throw error;
}
throw new index_1.OpenAPIFileError(`Failed to parse file: ${error instanceof Error ? error.message : String(error)}`, resolvedPath, error instanceof Error ? error : undefined);
}
}
}
exports.FileParser = FileParser;
FileParser.DEFAULT_ALLOWED_EXTENSIONS = ['.json', '.yaml', '.yml'];
//# sourceMappingURL=file-parser.js.map