fumadocs-openapi
Version:
Generate MDX docs for your OpenAPI spec
52 lines (51 loc) • 1.59 kB
JavaScript
import { dereference, upgrade } from '@scalar/openapi-parser';
import { bundle } from '@scalar/json-magic/bundle';
import { fetchUrls, readFiles } from '@scalar/json-magic/bundle/plugins/node';
const cache = new Map();
export async function processDocumentCached(input) {
if (typeof input !== 'string')
return processDocument(input);
const cached = cache.get(input);
if (cached)
return cached;
const processed = await processDocument(input);
cache.set(input, processed);
return processed;
}
/**
* process & reference input document to a Fumadocs OpenAPI compatible format
*/
export async function processDocument(input) {
const document = await bundle(input, {
plugins: [fetchUrls(), readFiles()],
treeShake: true,
urlMap: true,
hooks: {
onResolveError(node) {
throw new Error(`Failed to resolve ${node.$ref}`);
},
},
})
.then((v) => upgrade(v).specification)
.catch((e) => {
throw new Error(`[OpenAPI] Failed to resolve input: ${input}`, {
cause: e,
});
});
/**
* Dereferenced value and its original `$ref` value
*/
const dereferenceMap = new WeakMap();
return {
dereferenced: (await dereference(document, {
throwOnError: true,
onDereference({ schema, ref }) {
dereferenceMap.set(schema, ref);
},
})).schema,
getRawRef(obj) {
return dereferenceMap.get(obj);
},
bundled: document,
};
}