fumadocs-core
Version:
The React.js library for building a documentation website
203 lines (202 loc) • 5.8 kB
JavaScript
import { replaceSource } from "./stringifier.js";
import { d as walk } from "../utils-C7sTEOQI.js";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
// src/mdx-plugins/remark-image.ts
const VALID_BLUR_EXT = [
".jpeg",
".png",
".webp",
".avif",
".jpg"
];
const EXTERNAL_URL_REGEX = /^https?:\/\//;
/**
* Turn images into Next.js Image compatible usage.
*/
function remarkImage({ placeholder = "none", external = true, useImport = true, onError = "error", publicDir = path.join(process.cwd(), "public") } = {}) {
return async (tree, file) => {
const importsToInject = [];
const promises = [];
async function updateImage(src, node) {
if (src.type === "file" && useImport) {
const variableName = `__img${importsToInject.length}`;
const hasBlur = placeholder === "blur" && VALID_BLUR_EXT.some((ext) => src.file.endsWith(ext));
if (!file.dirname) throw new Error("When `useImport` is enabled, you must specify `dirname` in the VFile passed to compiler.");
importsToInject.push({
variableName,
importPath: getImportPath(src.file, file.dirname)
});
const out = {
children: [],
type: "mdxJsxFlowElement",
name: "img",
attributes: [{
type: "mdxJsxAttribute",
name: "alt",
value: node.alt ?? "image"
}, {
type: "mdxJsxAttribute",
name: "src",
value: {
type: "mdxJsxAttributeValueExpression",
value: variableName,
data: { estree: {
body: [{
type: "ExpressionStatement",
expression: {
type: "Identifier",
name: variableName
}
}],
type: "Program",
sourceType: "script"
} }
}
}]
};
if (node.title) out.attributes.push({
type: "mdxJsxAttribute",
name: "title",
value: node.title
});
if (hasBlur) out.attributes.push({
type: "mdxJsxAttribute",
name: "placeholder",
value: "blur"
});
const { url, alt, title } = node;
if (!url.startsWith("/")) {
const markdown = `![${(alt ?? "").replace(/[\\[\]]/g, "\\$&")}](<`;
const end = title ? `> "${title.replace(/["\\]/g, "\\$&")}")` : ">)";
replaceSource(file, node, (s) => markdown + s.expression(importedUrl(variableName), url) + end);
}
delete node.url;
delete node.alt;
delete node.title;
Object.assign(node, out);
return;
}
const size = await getImageSize(src, external).catch((e) => {
throw new Error(`[Remark Image] Failed obtain image size for ${node.url} (public directory configured as ${publicDir})`, { cause: e });
});
if (!size) return;
node.data ??= {};
node.data.hProperties ??= {};
node.data.hProperties.src = src.type === "url" ? src.url.href : node.url;
node.data.hProperties.width = size.width.toString();
node.data.hProperties.height = size.height.toString();
}
walk(tree, (node, _, parent) => {
if (node.type !== "image" || !parent) return;
const src = parseSrc(decodeURI(node.url), publicDir, file.dirname);
if (!src) return;
const task = updateImage(src, node).catch((e) => {
if (onError === "ignore" || node.url.endsWith(".svg")) return;
if (onError === "hide") {
replaceSource(file, node, "");
parent.children.splice(parent.children.indexOf(node), 1);
return;
}
if (onError === "error") throw e;
onError(e);
});
promises.push(task);
});
await Promise.all(promises);
if (importsToInject.length === 0) return;
const imports = importsToInject.map(({ variableName, importPath }) => ({
type: "mdxjsEsm",
data: { estree: { body: [{
type: "ImportDeclaration",
source: {
type: "Literal",
value: importPath
},
specifiers: [{
type: "ImportDefaultSpecifier",
local: {
type: "Identifier",
name: variableName
}
}]
}] } }
}));
tree.children.unshift(...imports);
};
}
/** the URL of an imported image, like a string with Vite, or `StaticImageData` with Next.js */
function importedUrl(name) {
return {
type: "LogicalExpression",
operator: "??",
left: {
type: "MemberExpression",
object: {
type: "Identifier",
name
},
property: {
type: "Identifier",
name: "src"
},
computed: false,
optional: false
},
right: {
type: "Identifier",
name
}
};
}
function getImportPath(file, dir) {
const relative = path.relative(dir, file);
const posix = relative.replaceAll(path.sep, "/");
if (path.isAbsolute(relative) || posix.startsWith("../")) return posix;
return `./${posix}`;
}
/**
* @param src - src href
* @param publicDir - dir/url to resolve absolute paths
* @param dir - dir to resolve relative paths
*/
function parseSrc(src, publicDir, dir) {
if (src.startsWith("file:///")) return {
type: "file",
file: fileURLToPath(src)
};
if (EXTERNAL_URL_REGEX.test(src)) return {
type: "url",
url: new URL(src)
};
if (src.startsWith("/")) {
if (EXTERNAL_URL_REGEX.test(publicDir)) {
const url = new URL(publicDir);
url.pathname = `/${[...url.pathname.split("/"), ...src.split("/")].filter((v) => v.length > 0).join("/")}`;
return {
type: "url",
url
};
}
return {
type: "file",
file: path.join(publicDir, src)
};
}
if (!dir) {
console.warn(`[Remark Image] found relative path ${src} but missing 'dirname' in VFile, this image will be skipped for now.`);
return;
}
return {
type: "file",
file: path.join(dir, src)
};
}
async function getImageSize(src, onExternal) {
const { probe } = await import("@fumari/image-size");
if (src.type === "file") return probe(src.file);
if (onExternal === false) return;
const { timeout } = typeof onExternal === "object" ? onExternal : {};
return probe(src.url, { timeout });
}
export { remarkImage };