@mintlify/common
Version:
Commonly shared code within Mintlify
58 lines (57 loc) • 2.46 kB
JavaScript
import { jsx, toJs } from 'estree-util-to-js';
import { visit } from 'unist-util-visit';
import { isMdxJsEsm } from './utils.js';
/**
* Removes the YAML frontmatter node from an AST (Root) if it exists as the first child.
* Modifies the tree in place.
* @param tree The Root node of the document.
*/
export const removeFrontmatterFromAST = (tree) => {
var _a;
if (tree.children.length > 0 && ((_a = tree.children[0]) === null || _a === void 0 ? void 0 : _a.type) === 'yaml') {
tree.children.shift();
}
};
/**
* Transforms `const X = ...; export default X;` into `export const X = ...;`
* so that the content is valid MDX ESM. Modifies the tree in place.
*/
export const normalizeDefaultExportInTree = (tree) => {
visit(tree, (node) => {
var _a, _b;
if (!isMdxJsEsm(node) || !((_b = (_a = node.data) === null || _a === void 0 ? void 0 : _a.estree) === null || _b === void 0 ? void 0 : _b.body))
return;
const body = node.data.estree.body;
const defaultExportIdx = body.findIndex((n) => n.type === 'ExportDefaultDeclaration' && n.declaration.type === 'Identifier');
if (defaultExportIdx === -1)
return;
const defaultExport = body[defaultExportIdx];
if ((defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport.type) !== 'ExportDefaultDeclaration')
return;
if (defaultExport.declaration.type !== 'Identifier')
return;
const identifier = defaultExport.declaration.name;
const declIdx = body.findIndex((n) => {
var _a;
if (n.type === 'VariableDeclaration') {
return n.declarations.some((d) => d.id.type === 'Identifier' && d.id.name === identifier);
}
if (n.type === 'FunctionDeclaration' && ((_a = n.id) === null || _a === void 0 ? void 0 : _a.name) === identifier)
return true;
return false;
});
if (declIdx === -1)
return;
const decl = body[declIdx];
if (decl && decl.type !== 'VariableDeclaration' && decl.type !== 'FunctionDeclaration')
return;
body[declIdx] = {
type: 'ExportNamedDeclaration',
declaration: decl,
specifiers: [],
source: null,
};
body.splice(defaultExportIdx, 1);
node.value = toJs(node.data.estree, { handlers: jsx }).value;
});
};