mcp-openapi-schema-explorer
Version:
MCP OpenAPI schema explorer
75 lines • 2.83 kB
JavaScript
import { buildComponentDetailUri } from '../utils/uri-builder.js'; // Added .js extension
export class ReferenceTransformService {
constructor() {
this.transformers = new Map();
}
registerTransformer(format, transformer) {
this.transformers.set(format, transformer);
}
transformDocument(document, context) {
const transformer = this.transformers.get(context.format);
if (!transformer) {
throw new Error(`No transformer registered for format: ${context.format}`);
}
return transformer.transformRefs(document, context);
}
}
export class OpenAPITransformer {
// Handle nested objects recursively
transformObject(obj, _context) {
if (!obj || typeof obj !== 'object') {
return obj;
}
// Handle arrays
if (Array.isArray(obj)) {
return obj.map(item => this.transformObject(item, _context));
}
// Handle references
if (this.isReferenceObject(obj)) {
return this.transformReference(obj.$ref);
}
// Recursively transform object properties
const result = {};
if (typeof obj === 'object') {
for (const [key, value] of Object.entries(obj)) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
Object.defineProperty(result, key, {
value: this.transformObject(value, _context),
enumerable: true,
writable: true,
configurable: true,
});
}
}
}
return result;
}
isReferenceObject(obj) {
return typeof obj === 'object' && obj !== null && '$ref' in obj;
}
transformReference(ref) {
// Handle only internal references for now
if (!ref.startsWith('#/')) {
return { $ref: ref }; // Keep external refs as-is
}
// Example ref: #/components/schemas/MySchema
const parts = ref.split('/');
// Check if it's an internal component reference
if (parts[0] === '#' && parts[1] === 'components' && parts.length === 4) {
const componentType = parts[2];
const componentName = parts[3];
// Use the centralized builder to create the correct URI
const newUri = buildComponentDetailUri(componentType, componentName);
return {
$ref: newUri,
};
}
// Keep other internal references (#/paths/...) and external references as-is
return { $ref: ref };
}
transformRefs(document, context) {
const transformed = this.transformObject(document, context);
return transformed;
}
}
//# sourceMappingURL=reference-transform.js.map