@redocly/openapi-core
Version:
See https://github.com/Redocly/redocly-cli
97 lines • 3.51 kB
JavaScript
import { parseRef } from '../../ref-utils.js';
import { isEmptyObject } from '../../utils/is-empty-object.js';
const OAS2_COMPONENT_TYPES = [
'definitions',
'parameters',
'responses',
'securityDefinitions',
];
export const RemoveUnusedComponents = () => {
const components = new Map();
function registerComponent(componentType, name) {
const key = `${componentType}/${name}`;
components.set(key, {
usedIn: components.get(key)?.usedIn ?? [],
componentType,
name,
});
}
function getComponentKey(pointer) {
if (!pointer.startsWith('#/'))
return;
const [type, name] = parseRef(pointer).pointer;
if (!type || !name)
return undefined;
if (!OAS2_COMPONENT_TYPES.includes(type))
return undefined;
return `${type}/${name}`;
}
function removeUnusedComponents(root, removedKeys = new Set()) {
const removedCountBefore = removedKeys.size;
for (const [key, { usedIn, name, componentType }] of components) {
const used = usedIn.some((sourceKey) => sourceKey !== key && !removedKeys.has(sourceKey));
if (!used && componentType) {
removedKeys.add(key);
delete root[componentType][name];
components.delete(key);
if (isEmptyObject(root[componentType])) {
delete root[componentType];
}
}
}
return removedKeys.size > removedCountBefore
? removeUnusedComponents(root, removedKeys)
: removedKeys.size;
}
return {
ref: {
leave(ref, { location, type, key }) {
if (['Schema', 'Parameter', 'Response', 'SecurityScheme'].includes(type.name)) {
const targetPointer = getComponentKey(ref.$ref);
if (!targetPointer)
return;
const sourcePointer = getComponentKey(location.pointer) ?? location.pointer;
const registered = components.get(targetPointer);
if (registered) {
registered.usedIn.push(sourcePointer);
}
else {
components.set(targetPointer, {
usedIn: [sourcePointer],
name: key.toString(),
});
}
}
},
},
Root: {
leave(root, ctx) {
const data = ctx.getVisitorData();
data.removedCount = removeUnusedComponents(root);
},
},
NamedSchemas: {
Schema(schema, { key }) {
if (!schema.allOf) {
registerComponent('definitions', key.toString());
}
},
},
NamedParameters: {
Parameter(_parameter, { key }) {
registerComponent('parameters', key.toString());
},
},
NamedResponses: {
Response(_response, { key }) {
registerComponent('responses', key.toString());
},
},
NamedSecuritySchemes: {
SecurityScheme(_securityScheme, { key }) {
registerComponent('securityDefinitions', key.toString());
},
},
};
};
//# sourceMappingURL=remove-unused-components.js.map