import fs from 'node:fs/promises'; import type { ShikiTransformer } from 'shiki'; import type { Highlighter } from 'fumadocs-core/highlight'; import { rehypeCode, type RehypeCodeOptions } from 'fumadocs-core/mdx-plugins/rehype-code'; import { rehypeCodeFromHighlighter, type RehypeCodeFromHighlighterOptions, } from 'fumadocs-core/mdx-plugins/rehype-code.core'; import { rehypeToc } from 'fumadocs-core/mdx-plugins/rehype-toc'; import { remarkHeading } from 'fumadocs-core/mdx-plugins/remark-heading'; import { remarkStructure } from 'fumadocs-core/mdx-plugins/remark-structure'; import type { StructuredData } from 'fumadocs-core/mdx-plugins'; import type { DynamicSource, LoaderOutput, LoaderPlugin, MetaData, PageData, StaticSource, VirtualFile, } from 'fumadocs-core/source'; import type { Root } from 'hast'; import remarkRehype from 'remark-rehype'; import { unified, type PluggableList } from 'unified'; import { VFile } from 'vfile'; import { buildPages, mdx, type BuiltPage } from './build'; import type { ModuleInterface } from './generated'; import { pythonPlugin } from './plugin'; import { createRenderer, type PythonRenderer } from './renderer'; export type PythonConfig = { /** path to the JSON file generated by `fumapy-generate` */ file: string; /** * group generated pages in a directory: * * - `module`: the name of the root module * - `none`: place them at the root of the source * * @defaultValue 'module' */ groupBy?: PythonGroupBy; /** additional remark plugins, applied before the structured data is collected */ remarkPlugins?: PluggableList; /** additional rehype plugins, applied before the TOC is collected */ rehypePlugins?: PluggableList; } & ( | { /** options for Shiki, `false` to leave code blocks as they are */ rehypeCodeOptions?: Partial | false; highlighter?: undefined; } | { /** options for code blocks, `false` to leave them as they are */ rehypeCodeOptions?: RehypeCodeFromHighlighterOptions | false; /** highlight code with your own highlighter instead of Shiki, a function is created with the transformers of code blocks */ highlighter?: Highlighter | ((options: { transformers: ShikiTransformer[] }) => Highlighter); } ); export type PythonPageKind = 'module' | 'class'; export type PythonGroupBy = 'module' | 'none'; export interface PythonPage extends PageData { title: string; /** compile the page, at most once until the source is invalidated */ load: () => Promise; structuredData: () => Promise; _python: { kind: PythonPageKind }; } export interface PythonSource { staticSource: (options?: SourceOptions) => Promise>; dynamicSource: (options?: SourceOptions) => DynamicSource; /** decorates generated pages in the page tree with a `module`/`class` badge */ loaderPlugin: () => LoaderPlugin; } export interface SourceOptions { /** base directory for virtual file paths */ baseDir?: string; } type PythonSourceConfig = { pageData: PythonPage; metaData: MetaData }; /** Create a runtime Fumadocs content source from the JSON generated by `fumapy-generate`. */ export function createPython(config: PythonConfig): PythonSource { // components highlight types, without the transformers of code blocks const componentHighlighter = typeof config.highlighter === 'function' ? config.highlighter({ transformers: [] }) : config.highlighter; const processor = unified() .use(remarkHeading, { generateToc: false }) .use(config.remarkPlugins ?? []) .use(remarkStructure) .use(remarkRehype, { passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement'] }) .use( config.rehypeCodeOptions === false ? [] : config.highlighter ? [[rehypeCodeFromHighlighter, config.highlighter, config.rehypeCodeOptions]] : [[rehypeCode, { fallbackLanguage: 'plaintext', ...config.rehypeCodeOptions }]], ) .use(config.rehypePlugins ?? []) .use(rehypeToc, { exportToc: { as: 'data' } }); async function compile( page: BuiltPage, href: (target: BuiltPage) => string, ): Promise { // compile the MDX the CLI would write, so Markdown output and search records have a source const file = new VFile({ path: page.path, value: mdx.stringify(page.build(href)) }); const tree = (await processor.run(mdx.parse(file), file)) as Root; return createRenderer({ tree, structuredData: file.data.structuredData, rehypeToc: file.data.rehypeToc, highlighter: componentHighlighter, }); } function createSource({ baseDir }: SourceOptions = {}) { let loader: LoaderOutput | undefined; // links resolve through the loader the source is attached to, so pages // build lazily on compile rather than when files are listed function href(target: BuiltPage): string { const resolved = loader?.getPageByHref(`./${target.path}`, { dir: baseDir }); if (!resolved) throw new Error(`cannot resolve the URL of ${target.path}`); return resolved.page.url; } async function files(): Promise[]> { const mod: ModuleInterface = JSON.parse(await fs.readFile(config.file, 'utf-8')); return buildPages(mod, config.groupBy).map((page) => { let loaded: Promise | undefined; const load = () => (loaded ??= compile(page, href)); return { type: 'page', path: page.path, data: { title: page.title, load, structuredData: async () => (await load()).structuredData, _python: { kind: page.kind }, }, }; }); } return { baseDir, files, configureStatic(options: { loader: LoaderOutput }) { loader = options.loader; }, }; } return { dynamicSource: (options) => createSource(options), async staticSource(options) { const { files, ...source } = createSource(options); return { ...source, files: await files() }; }, loaderPlugin: pythonPlugin, }; }