fumadocs-core
Version:
The React.js library for building a documentation website
208 lines (207 loc) • 7.84 kB
JavaScript
// src/source/llms.ts
function llms(input, config = {}) {
const { TAB = " ", filter = () => true, section = (folder) => Boolean(folder.root) } = config;
function renderName(node, ctx) {
if (config.renderName) return config.renderName(node, ctx);
if (node.type === "page") {
const page = ctx.loader.getNodePage(node, ctx.lang);
if (page?.data.title) return page.data.title;
} else if (node.type !== "separator") {
const meta = ctx.loader.getNodeMeta(node, ctx.lang);
if (meta?.data.title) return meta.data.title;
}
return typeof node.name === "string" ? node.name : "";
}
function renderDescription(node, ctx) {
if (config.renderDescription) return config.renderDescription(node, ctx);
if (node.type === "page") {
const page = ctx.loader.getNodePage(node, ctx.lang);
if (page?.data.description) return page.data.description;
} else {
const meta = ctx.loader.getNodeMeta(node, ctx.lang);
if (meta?.data.description) return meta.data.description;
}
return typeof node.description === "string" ? node.description : "";
}
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": {
const page = ctx.markdown && ctx.loader.getNodePage(node, ctx.lang);
if (page && filter(page)) node = {
...node,
url: markdownPath(page.url)
};
return formatListItem(formatMarkdownLink(renderName(node, ctx), config.renderUrl?.(node, ctx) ?? node.url), renderDescription(node, ctx), indent);
}
case "folder": {
const scope = ctx.markdown ? sectionOf(node, ctx) : void 0;
let name = renderName(node, ctx);
if (scope) name = linkFile(name, `${scope.url}/${scope.collapse ? "llms" : "llms-full"}.txt`, ctx);
const out = [formatListItem(name, renderDescription(node, ctx), indent)];
if (scope?.collapse) return out[0];
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 formatIndex(ctx) {
const { loader, lang } = ctx;
if (loader._i18n && lang === void 0) {
const out = [];
for (const language of loader._i18n.languages) out.push(formatIndex({
...ctx,
lang: language
}));
return out.join("\n\n");
}
return formatTree(loader.getPageTree(lang), ctx);
}
/** the index of a page tree or a section, `full` is the path of its `llms-full.txt` */
function formatTree(node, ctx, full) {
const out = [`# ${renderName(node, ctx)}`, ""];
const description = renderDescription(node, ctx);
if (description) out.push(`> ${description}`, "");
if (full) out.push(linkFile("All pages", full, ctx), "");
if (node.type === "folder" && node.index) out.push(formatNode(node.index, 0, ctx));
for (const child of node.children) out.push(formatNode(child, 0, ctx));
return out.join("\n");
}
/** a link to one of the files, through `renderUrl` */
function linkFile(name, path, ctx) {
const item = {
type: "page",
name,
url: path
};
return formatMarkdownLink(name, config.renderUrl?.(item, ctx) ?? path);
}
function renderPage(page) {
if (!config.renderPage) throw new Error("`renderPage` is required by `page()` and `full()`, see llms() options.");
return config.renderPage(page);
}
async function renderPages(pages) {
return (await Promise.all(pages.map(renderPage))).join("\n\n");
}
const getPages = (loader, lang) => loader.getPages(lang).filter(filter);
/** the URL, collapse and pages of a folder, when it's a section */
function sectionOf(folder, ctx) {
const options = section(folder, ctx);
if (!options) return;
const pages = [];
const visit = (node) => {
if (node.type === "page") {
const page = ctx.loader.getNodePage(node, ctx.lang);
if (page && filter(page)) pages.push(page);
} else if (node.type === "folder") {
if (node.index) visit(node.index);
for (const child of node.children) visit(child);
}
};
visit(folder);
if (pages.length === 0) return;
const { asPath, collapse } = options === true ? {} : options;
let url = asPath ?? folder.index?.url ?? pages[0].url;
if (!asPath) for (const page of pages) while (url.length > 0 && !`${page.url}/`.startsWith(`${url}/`)) url = url.slice(0, url.lastIndexOf("/"));
return {
url: url.replace(/\/$/, ""),
collapse,
pages,
folder,
ctx
};
}
/** the sections of the page trees, by URL */
function sections(loader, lang) {
const out = /* @__PURE__ */ new Map();
const visit = (node, ctx) => {
if (node.type !== "folder") return;
const scope = sectionOf(node, ctx);
if (scope && !out.has(scope.url)) out.set(scope.url, scope);
for (const child of node.children) visit(child, ctx);
};
const languages = lang === void 0 && loader._i18n ? loader._i18n.languages : [lang];
for (const language of languages) for (const child of loader.getPageTree(language).children) visit(child, {
loader,
lang: language
});
return out;
}
function withLoader(render) {
if (typeof input === "function") return Promise.resolve(input()).then(render);
return render(input);
}
async function renderFile(loader, path, lang) {
if (path === "/llms.txt") return formatIndex({
loader,
lang,
markdown: true
});
if (path === "/llms-full.txt") return renderPages(getPages(loader, lang));
if (path.endsWith(".md")) {
let url = path.slice(0, -3).replace(/(.)\/$/, "$1");
if (url === "/index") url = "/";
const page = loader.getPageByUrl(url, lang) ?? loader.getPageByUrl(`${url}/`, lang);
if (page && filter(page)) return renderPage(page);
return;
}
const scope = sections(loader, lang).get(path.slice(0, path.lastIndexOf("/")));
if (scope && path.endsWith("/llms-full.txt")) return renderPages(scope.pages);
if (scope?.collapse && path.endsWith("/llms.txt")) return formatTree(scope.folder, {
...scope.ctx,
markdown: true
}, `${scope.url}/llms-full.txt`);
}
return {
index: (lang) => withLoader((loader) => formatIndex({
loader,
lang
})),
indexNode: (node, lang) => withLoader((loader) => formatNode(node, 0, {
lang,
loader
})),
async page(page) {
return renderPage(page);
},
async full(lang) {
return withLoader((loader) => renderPages(getPages(loader, lang)));
},
async files(lang) {
return withLoader((loader) => {
const pages = getPages(loader, lang);
const out = /* @__PURE__ */ new Set(["/llms.txt", "/llms-full.txt"]);
for (const page of pages) out.add(markdownPath(page.url));
for (const [url, { collapse }] of sections(loader, lang)) {
if (collapse) out.add(`${url}/llms.txt`);
out.add(`${url}/llms-full.txt`);
}
return Array.from(out);
});
},
async serve(path, lang) {
if (!/\.(md|txt)$/.test(path)) return;
return withLoader(async (loader) => {
const encoded = encodeURI(path);
const text = await renderFile(loader, path, lang) ?? (encoded === path ? void 0 : await renderFile(loader, encoded, lang));
if (text === void 0) return;
return new Response(text, { headers: { "Content-Type": `${path.endsWith(".md") ? "text/markdown" : "text/plain"}; charset=utf-8` } });
});
}
};
}
/** the path of the `.md` file of a page: `<page>.md`, `/index.md` for `/` */
function markdownPath(url) {
return url === "/" ? "/index.md" : `${url.replace(/\/$/, "")}.md`;
}
function formatMarkdownLink(title, url) {
return `[${title.replace(/([[\]])/g, "\\$1")}](${url.replace(/([()])/g, "\\$1")})`;
}
export { llms };