fumadocs-mdx
Version:
The built-in source for Fumadocs
91 lines (89 loc) • 2.97 kB
JavaScript
import { t as fumaMatter } from "./fuma-matter-CHgJa_-B.js";
import { t as mdxLoaderGlob } from "./loaders-BVwYfelL.js";
import { z } from "zod";
import fs from "node:fs/promises";
import path from "node:path";
import { createHash } from "node:crypto";
//#region src/loaders/mdx/index.ts
const querySchema = z.looseObject({
only: z.literal(["frontmatter", "all"]).default("all"),
collection: z.string().optional(),
workspace: z.string().optional()
});
const cacheEntry = z.object({
code: z.string(),
map: z.any().optional(),
hash: z.string().optional()
});
function createMdxLoader({ getCore }) {
return {
test: mdxLoaderGlob,
async load({ getSource, development: isDevelopment, query, compiler, filePath }) {
let core = await getCore();
const value = await getSource();
const matter = fumaMatter(value);
const { collection: collectionName, workspace, only } = querySchema.parse(query);
if (workspace) core = core.getWorkspaces().get(workspace) ?? core;
let after;
const { experimentalBuildCache = false } = core.getConfig().global;
if (!isDevelopment && experimentalBuildCache) {
const cacheDir = experimentalBuildCache;
const cacheKey = `${collectionName ?? "global"}_${generateCacheHash(filePath)}`;
const cached = await fs.readFile(path.join(cacheDir, cacheKey)).then((content) => cacheEntry.parse(JSON.parse(content.toString()))).catch(() => null);
if (cached && cached.hash === generateCacheHash(value)) return cached;
after = async () => {
await fs.mkdir(cacheDir, { recursive: true });
await fs.writeFile(path.join(cacheDir, cacheKey), JSON.stringify({
...out,
hash: generateCacheHash(value)
}));
};
}
const collection = collectionName ? core.getCollection(collectionName) : void 0;
let docCollection;
switch (collection?.type) {
case "doc":
docCollection = collection;
break;
case "docs":
docCollection = collection.docs;
break;
}
if (docCollection) matter.data = await core.transformFrontmatter({
collection: docCollection,
filePath,
source: value
}, matter.data);
if (only === "frontmatter") return {
code: `export const frontmatter = ${JSON.stringify(matter.data)}`,
map: null
};
const { buildMDX } = await import("./build-mdx-EzuL9Bt0.js");
const compiled = await buildMDX(core, docCollection, {
isDevelopment,
source: "\n".repeat(countLines(matter.matter)) + matter.content,
filePath,
frontmatter: matter.data,
_compiler: compiler,
environment: "bundler"
});
const out = {
code: String(compiled.value),
map: compiled.map
};
await after?.();
return out;
}
};
}
function generateCacheHash(input) {
return createHash("md5").update(input).digest("hex");
}
function countLines(s) {
let num = 0;
for (const c of s) if (c === "\n") num++;
return num;
}
//#endregion
export { createMdxLoader as t };
//# sourceMappingURL=mdx-CPnL-Edm.js.map