@nuxt/content
Version:
Write your content inside your Nuxt app
56 lines (54 loc) • 1.89 kB
JavaScript
import { withBase } from "ufo";
import { pascalCase } from "scule";
import { toHast } from "minimark/hast";
import manifest from "#content/manifest";
const linkProps = ["href", "src", "to"];
const importExternalPackage = async (name) => await import(name);
export async function createDocumentGenerator() {
const visit = await importExternalPackage("unist-util-visit").then((res) => res.visit);
const stringifyMarkdown = await importExternalPackage("@nuxtjs/mdc/runtime").then((res) => res.stringifyMarkdown);
return generateDocument;
async function generateDocument(doc, options) {
const hastTree = refineDocumentBody(doc.body, options);
let markdown = await stringifyMarkdown(hastTree, {});
if (!markdown?.trim().startsWith("# ")) {
const title = doc.title || doc.seo?.title || "";
if (title) {
markdown = `# ${title}
${markdown}`;
}
}
return markdown;
}
function refineDocumentBody(body, options) {
const hastTree = toHast(body);
visit(hastTree, (node) => !!node.props?.to || !!node.props?.href || !!node.props?.src, (node) => {
for (const prop of linkProps) {
if (node.props?.[prop]) {
node.props[prop] = withBase(node.props[prop], options.domain);
}
}
});
return hastTree;
}
}
export function prepareContentSections(sections) {
const contentSections = sections.filter((section) => section.contentCollection);
if (contentSections.length) {
return;
}
const pageCollecitons = Object.keys(manifest).filter((c) => manifest[c].type === "page");
const autoGeneratedSections = pageCollecitons.map((c) => ({
__nuxt_content_auto_generate: true,
title: pascalCase(c),
contentCollection: c,
contentFilters: [
{
field: "extension",
operator: "=",
value: "md"
}
]
}));
sections.push(...autoGeneratedSections);
}