fumadocs-core
Version:
The React.js library for building a documentation website
75 lines (74 loc) • 2.7 kB
JavaScript
//#region src/source/llms.ts
function llms(loader, config = {}) {
const { TAB = " ", renderName = (node, ctx) => {
if (node.type === "page") {
const page = loader.getNodePage(node, ctx.lang);
if (page?.data.title) return page.data.title;
} else if (node.type !== "separator") {
const meta = loader.getNodeMeta(node, ctx.lang);
if (meta?.data.title) return meta.data.title;
}
return typeof node.name === "string" ? node.name : "";
}, renderDescription = (node, ctx) => {
if (node.type === "page") {
const page = loader.getNodePage(node, ctx.lang);
if (page?.data.description) return page.data.description;
} else {
const meta = loader.getNodeMeta(node, ctx.lang);
if (meta?.data.description) return meta.data.description;
}
return typeof node.description === "string" ? node.description : "";
} } = config;
function formatListItem(name, description, indent) {
const prefix = TAB.repeat(indent);
description = description.trim();
if (description.length > 0) return `${prefix}- ${name}: ${description}`;
return `${prefix}- ${name}`;
}
function formatNode(node, indent, ctx) {
switch (node.type) {
case "page": return formatListItem(formatMarkdownLink(renderName(node, ctx), node.url), renderDescription(node, ctx), indent);
case "folder": {
const out = [];
out.push(formatListItem(renderName(node, ctx), renderDescription(node, ctx), indent));
if (node.index) out.push(formatNode(node.index, indent + 1, ctx));
for (const child of node.children) out.push(formatNode(child, indent + 1, ctx));
return out.join("\n");
}
case "separator": return "\n" + formatListItem(`**${renderName(node, ctx) || "Separator"}**`, "", indent);
}
}
function index(lang) {
if (loader._i18n && lang === void 0) {
const { languages } = loader._i18n;
return languages.map(index).join("\n\n");
}
const pageTree = loader.getPageTree(lang);
const out = [];
const ctx = { lang };
out.push(`# ${renderName(pageTree, ctx)}`, "");
const description = renderDescription(pageTree, ctx);
if (description) out.push(`> ${description}`, "");
for (const child of pageTree.children) out.push(formatNode(child, 0, ctx));
return out.join("\n");
}
return {
/**
* generate `llms.txt` content in Markdown format.
*
* use `indexNode(node)` instead for more control (e.g. add extra sections to output).
*/
index,
/**
* generate `llms.txt` content for a single page tree node.
*/
indexNode(node, lang) {
return formatNode(node, 0, { lang });
}
};
}
function formatMarkdownLink(title, url) {
return `[${title.replace(/([[\]])/g, "\\$1")}](${url.replace(/([()])/g, "\\$1")})`;
}
//#endregion
export { llms };