# blade47/fumadocs Wiki ## Technical docs: Overview URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/overview
Relevant source files The following files were used as context for generating this wiki page: - [packages/core/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json) - [packages/preview/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json) - [packages/api-docs/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json) - [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts) - [packages/python/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json) - [packages/basehub/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/package.json) - [packages/openapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json) - [packages/local-md/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/package.json) - [packages/content/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json) - [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/base-ui/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json) - [packages/content/src/runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts) - [packages/epub/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/package.json) - [packages/obsidian/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/package.json) - [packages/radix-ui/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json) - [packages/cli/src/commands/shared.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts) - [packages/typescript/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json) - [packages/shared/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/package.json) - [packages/cli/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts) - [packages/twoslash/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json) - [packages/doc-gen/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/asyncapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json) - [packages/create-app/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json) - [packages/sanity/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/index.ts) - [packages/story/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/package.json) - [packages/mdx/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json) - [packages/python/pyproject.toml](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml) - [packages/preview/fumadocs.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/fumadocs.config.ts)
## Overview Fumadocs is a modern, framework-agnostic documentation ecosystem designed for React applications, providing a modular architecture that separates core document processing, source loading, and layout presentation [packages/core/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L2-L4). It addresses the complexity of building documentation sites by decoupling headless primitives and build-time content compilation from opinionated styling layers and frontend frameworks. The project is organized as a monorepo workspace containing runtime engines, bundler integration plugins, and user interface implementations [[packages/core/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L2-L4), [packages/radix-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L2-L4). Fumadocs integrates closely with tools like [BaseHub Integration](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/basehub-integration) and [MDX Runtime Compilation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-runtime-compilation) to support flexible content workflows and dynamic rendering [[packages/basehub/package.json:4-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/package.json#L4-L4), [packages/mdx/src/runtime/server.ts:1-2](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts#L1-L2). ## Architecture and Design Philosophy Fumadocs is architected around a strict separation of concerns, decoupling framework-agnostic document processing, source loading, and state management from concrete UI implementations [packages/core/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L2-L4). The core runtime library (`fumadocs-core`) delivers navigation tree generation, internationalization negotiation, [search server indexing](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-server-indexing), [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting), and remark/rehype markdown AST transformations without depending on a specific frontend framework or bundler [[packages/core/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L2-L4), [packages/core/package.json:42-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L42-L87). The ecosystem provides explicit [framework routing adapters](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/framework-routing-adapters) and runtime provider packages for Next.js, React Router, TanStack, Waku, and Vite [[packages/core/package.json:29-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L29-L33), [packages/radix-ui/package.json:104-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L104-L108). This modular layer separation allows documentation content models and source schemas to be compiled independently of presentation components, which are supplied separately through accessible UI packages like `fumadocs-ui` backed by [Radix UI primitives](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/radix-ui-primitives) [[packages/radix-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L2-L4), [packages/radix-ui/package.json:134-143](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L134-L143). | Layer Category | Primary Package | Export Modules & Target Responsibilities | | :--- | :--- | :--- | | Core Engine | `fumadocs-core` | `./source`, `./page-tree`, `./i18n`, `./search`, `./highlight`, `./mdx-plugins` | | Content Compilation | `fumadocs-mdx` | `./node`, `./vite`, `./next`, `./rolldown`, `./webpack/mdx`, `./runtime/server` | | UI & Layouts | `fumadocs-ui` | `./layouts/docs`, `./layouts/flux`, `./components/codeblock`, `./components/dialog/search` | | Content Adapter | `@fumadocs/content` | `.` (index), `./runtime` for standard-schema type-safe document fetching | | Shared Utilities | `shared` | Internal helper workspace for CLI tooling, translation specs, and glob file scanning | Sources: [packages/core/package.json:20-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L20-L88), [packages/content/package.json:17-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L17-L21), [packages/radix-ui/package.json:18-117](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L18-L117), [packages/shared/package.json:4-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/package.json#L4-L8), [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44) > [!NOTE] > The `@fumadocs/content` adapter depends on `@standard-schema/spec` and `fuma-content` to decouple validation schemas from specific file-system loaders [[packages/content/package.json:32-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L32-L34), [packages/content/package.json:43-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L43-L46). Sources: [packages/content/package.json:32-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L32-L46) > [!IMPORTANT] > Framework integration is completely decoupled via dedicated export entry points in `fumadocs-core` (such as `./framework/next`, `./framework/react-router`, `./framework/tanstack`, and `./framework/waku`), preventing runtime coupling to Next.js [packages/core/package.json:29-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L29-L33). Sources: [packages/core/package.json:29-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L29-L33) ## Monorepo Package Structure and Roles ### Core Runtime and Content Compilers The Fumadocs workspace organizes its source code into specialized packages, separating the framework-agnostic runtime engine from build-time content compilation and UI layers. The core runtime package, `fumadocs-core`, provides foundational services including source file discovery, page tree calculations, internationalization negotiation, search server indexing, syntax highlighting, and unified remark/rehype markdown AST transformations [packages/core/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L2-L4), [packages/core/package.json:42-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L42-L87). Build-time processing is handled by `fumadocs-mdx`, which exposes integration entry points for bundlers and runtime loaders, including Next.js, Vite, Webpack, Rolldown, and Bun [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44). Content validation and schema mapping across standard schemas are delegated to `@fumadocs/content`, which relies on `fuma-content` and `@standard-schema/spec` [packages/content/package.json:32-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L32-L46). Sources: [packages/core/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L2-L4), [packages/core/package.json:42-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L42-L87), [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44), [packages/content/package.json:32-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L32-L46) > [!IMPORTANT] > The `fumadocs-mdx` package maintains separate sub-exports for static node compilation (`./node`, `./node/loader`) and client/server runtimes (`./runtime/server`, `./runtime/browser`, `./runtime/dynamic`), preventing server-only modules from leaking into browser bundles [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44). Sources: [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44) ### UI Implementations and Layouts Presentation components are factored into distinct UI packages that target specific primitive ecosystems. The two primary UI design implementations are `fumadocs-ui` (backed by Radix UI primitives) and `@fumadocs/base-ui` (built for Base UI) [packages/base-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L2-L4), [packages/radix-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L2-L4), [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4). Both packages provide identical export paths for documentation layouts, navigation slots, code blocks, search dialogs, and interactive UI widgets [packages/base-ui/package.json:18-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L18-L114), [packages/radix-ui/package.json:18-117](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L18-L117). | Package Name | Primary Dependency Stack | Target UI Library & Layout Exports | | :--- | :--- | :--- | | `fumadocs-ui` (`radix-ui`) | Radix Primitives (`@radix-ui/react-*`), `motion`, `next-themes` | `./layouts/docs`, `./layouts/flux`, `./layouts/notebook`, `./layouts/home` [packages/radix-ui/package.json:58-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L58-L90), [packages/radix-ui/package.json:134-153](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L134-L153) | | `@fumadocs/base-ui` | Base UI primitives, `motion`, `next-themes` | `./layouts/docs`, `./layouts/flux`, `./layouts/notebook`, `./layouts/home` [packages/base-ui/package.json:58-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L58-L90) | | `@fumadocs/api-docs` | Radix Accordion/Dialog/Select, `@fumari/stf` | `./schema`, `./codegen`, `./components/schema`, `./components/dialog` [packages/api-docs/package.json:18-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L18-L42), [packages/api-docs/package.json:56-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L56-L67) | Sources: [packages/base-ui/package.json:18-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L18-L114), [packages/radix-ui/package.json:18-117](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L18-L117), [packages/api-docs/package.json:18-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L18-L67), [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4)] > [!NOTE] > The CLI utility references UI registries via the configuration mapping in `UIRegistries`, associating `'base-ui'` with `fumadocs/base-ui` and `'radix-ui'` with `fumadocs/radix-ui` [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4). Sources: [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4) ### Tooling, Extensibility, and Preview Packages Specialized plugins and developer tooling are isolated into independent workspace packages to keep runtime footprints minimal [packages/preview/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L2-L4), [packages/typescript/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L2-L4), [packages/twoslash/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L2-L4), [packages/doc-gen/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L2-L4), [packages/create-app/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L2-L4). These include `fumadocs-typescript` for type table extractions via `ts-morph` [packages/typescript/package.json:39-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L39-L49), `fumadocs-twoslash` for Shiki-based compiler diagnostics [packages/twoslash/package.json:45-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L45-L53), `fumadocs-docgen` for remark utilities like `remark-ts2js` [packages/doc-gen/package.json:26-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L26-L30), [packages/doc-gen/package.json:41-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L41-L50), `fumadocs-preview` for Waku-backed fast content previews with AI search features [packages/preview/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L2-L4), [packages/preview/package.json:35-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L35-L88), and `create-fumadocs-app` for project scaffolding [packages/create-app/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L2-L4), [packages/create-app/package.json:43-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L43-L52). Sources: [packages/preview/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L2-L4), [packages/preview/package.json:35-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L35-L88), [packages/typescript/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L2-L4), [packages/typescript/package.json:39-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L39-L49), [packages/twoslash/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L2-L4), [packages/twoslash/package.json:45-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L45-L53), [packages/doc-gen/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L2-L4), [packages/doc-gen/package.json:26-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L26-L30), [packages/doc-gen/package.json:41-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L41-L50), [packages/create-app/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L2-L4), [packages/create-app/package.json:43-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L43-L52) ## Content Compilation and Source Processing ### Document Schemas and Collection Configuration Document parsing and type-safe frontmatter validation rely on `@standard-schema/spec` [[packages/content/package.json:32-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L32-L34), [packages/mdx/package.json:56-58](https://github.com/blade47/fumadocs/package.json#L56-L58)]. The `@fumadocs/content` package provides helper utilities like `docsMdxCollection` and `docsCollection` to structure directories containing MDX documents and metadata files [packages/content/src/index.ts:16-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L53). By default, `docsMdxCollection` integrates `mdxPreset` configurations with remark include plugins for content composition [packages/content/src/index.ts:24-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L24-L32). Sources: [packages/content/package.json:32-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L32-L34), [packages/content/src/index.ts:16-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L53), [packages/mdx/package.json:56-58](https://github.com/blade47/fumadocs/package.json#L56-L58)] > [!NOTE] > The `docsMdxCollection` builder automatically falls back to `pageSchema` for frontmatter validation when a custom schema is omitted [packages/content/src/index.ts:16-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L19). Sources: [packages/content/src/index.ts:16-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L19)] ### Runtime and Dynamic MDX Compilation The `fumadocs-mdx` package supports runtime compilation and dynamic execution of MDX files through its runtime modules [[packages/mdx/package.json:37-40](https://github.com/blade47/fumadocs/package.json#L37-L40)]. The `dynamic` utility resolves collections and compiles raw content entries into hydrated properties [packages/mdx/src/runtime/dynamic.ts:47-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L47-L95). ```typescript async function executeMdx(compiled: string, options: ExecuteOptions = {}) { const { opts: scopeOpts, ...scope } = options.scope ?? {}; const fullScope = { opts: { ...(scopeOpts as object), ...(options.jsxRuntime ?? jsxRuntimeDefault), baseUrl: options.baseUrl, }, ...scope, }; const hydrateFn = new AsyncFunction(...Object.keys(fullScope), compiled); return await hydrateFn.apply(hydrateFn, Object.values(fullScope)); } ``` Sources: [packages/mdx/src/runtime/dynamic.ts:32-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L32-L45)] The `DocsCollection` class manages code generation by listening to emission hooks and constructing virtual code modules that link back to stores [packages/content/src/index.ts:55-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L55-L70). Concurrently, `toFumadocsSource` maps underlying file collection stores into structured static sources containing page and metadata entries [packages/content/src/runtime.ts:12-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L12-L42). Sources: [packages/content/src/index.ts:55-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L55-L70), [packages/content/src/runtime.ts:12-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L12-L42)] ## Presentation Primitives and Layout Systems ### Headless UI Implementations and UI Registries Fumadocs separates visual styling and component layout architectures into two alternative UI implementations: `@fumadocs/base-ui` and `fumadocs-ui` (backed by Radix UI primitives) [packages/base-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L2-L4), [packages/radix-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L2-L4). These UI variants share identical export paths for foundational primitives, layout slots, and navigation contexts while consuming distinct underlying primitives. The command line utility references these two packages under the identifiers `base-ui` and `radix-ui` [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4). | UI Package | Package Name | Registry Key | Primary Dependencies | | :--- | :--- | :--- | :--- | | Base UI Version | `@fumadocs/base-ui` | `base-ui` | Tailored base primitives and CSS exports | | Radix UI Version | `fumadocs-ui` | `radix-ui` | `@radix-ui/react-*`, `motion`, `next-themes` | Sources: [packages/base-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L2-L4), [packages/radix-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L2-L4), [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4), [packages/radix-ui/package.json:131-154](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L131-L154)] > [!IMPORTANT] > Both UI packages expose identical module entry points for layouts (`./layouts/docs`, `./layouts/flux`, `./layouts/notebook`, `./layouts/home`), search dialogs, and component slots, enabling seamless switching between Radix and Base UI runtimes without altering layout consumption code [packages/base-ui/package.json:18-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L18-L114), [packages/radix-ui/package.json:18-117](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L18-L117). Sources: [packages/base-ui/package.json:18-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L18-L114), [packages/radix-ui/package.json:18-117](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L18-L117)] ### Layout Presets and Markdown Compilation Pipeline Layout presets determine how documentation pages and structural containers render[packages/preview/src/pages/[...slugs].tsx:80-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L80-L96). The [preview server](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/preview-server) configuration supports dynamic markdown rendering pipelines incorporating remark and rehype plugins for math, headings, GFM, code tabs, package manager persistence, and Mermaid diagrams[packages/preview/src/pages/[...slugs].tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46). ```tsx const compiler = createMarkdownCompiler({ remarkPlugins: [ remarkGfm, remarkMath, remarkMdxMermaid, plugin(remarkHeading, { generateToc: false }), plugin(remarkNpm, { persist: { id: 'package-manager' } }), remarkCodeTab, ], remarkRehypeOptions: { passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement'], }, rehypePlugins: [ rehypeKatex, plugin(rehypeCode, { lazy: true, fallbackLanguage: 'text' }), plugin(rehypeToc, { exportToc: { as: 'data' } }), ], }); ``` Sources: [packages/preview/src/pages/...slugs.tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46)] The dynamic page renderer inspects the layout preset configuration (`docs` or `flux`) to load corresponding layout modules and page components dynamically[packages/preview/src/pages/[...slugs].tsx:80-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L80-L96). When rendering documentation containers, AI search widgets are conditionally injected alongside layout slots if AI support is enabled[packages/preview/src/pages/[...slugs].tsx:113-138](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L113-L138). Sources: [packages/preview/src/pages/...slugs.tsx:80-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L80-L96), [packages/preview/src/pages/...slugs.tsx:113-138](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L113-L138)] ## Tooling and Extensibility Ecosystem ### Specification Generators and Language Integration Plugins Fumadocs provides specialized packages that ingest specification files and foreign source code, transforming them into documentation structures. The `fumadocs-openapi` package parses OpenAPI v3 and Swagger definitions to generate MDX documentation pages, client request generators, and interactive UI components, with exports for C#, cURL, Go, Java, JavaScript, and Python request generators[packages/openapi/package.json:2-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L2-L37). Similarly, `@fumadocs/asyncapi` processes AsyncAPI specifications to generate documentation for asynchronous message-driven architectures with dedicated server and internationalization entry points[packages/asyncapi/package.json:2-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json#L2-L25). For Python codebases, `fumadocs-python` and the underlying `fumapy` module inspect source code and docstrings using Griffe and Griffe typing extensions to extract API documentation[packages/python/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json#L2-L4), [packages/python/pyproject.toml:2-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L2-L8). | Tool / Plugin Package | Package Identifier | Primary Purpose | Key Export Endpoints | | :--- | :--- | :--- | :--- | | OpenAPI Generator | `fumadocs-openapi` | OpenAPI v3/Swagger MDX doc generation & request building | `.`, `./ui`, `./scalar`, `./requests/generators/*` | | AsyncAPI Generator | `@fumadocs/asyncapi` | AsyncAPI event-driven messaging documentation | `.`, `./ui`, `./server`, `./i18n` | | Python Docgen | `fumadocs-python` | Python docstring extraction and component presets | `.`, `./components`, `./preset.css` | | Story Integration | `@fumadocs/story` | Component prop parsing and interactive playgrounds | `.`, `./next`, `./vite`, `./type-tree` | Sources: [packages/python/package.json:2-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json#L2-L32), [packages/openapi/package.json:2-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L2-L37), [packages/asyncapi/package.json:2-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json#L2-L25), [packages/python/pyproject.toml:2-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L2-L8), [packages/story/package.json:2-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/package.json#L2-L24)] > [!NOTE] > The `@fumadocs/story` package supports multiple build systems and frameworks, offering dedicated entry points for Next.js (`./next`, `./next/client`), Vite (`./vite`, `./vite/client`), and Webpack (`./webpack/story`) alongside type-tree extraction[packages/story/package.json:14-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/package.json#L14-L24). Sources: [packages/story/package.json:14-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/package.json#L14-L24)] ### Standalone Content Sources and Export Utilities Additional packages extend content ingestion and distribution capabilities beyond standard Markdown and MDX files. The `@fumadocs/local-md` package parses local Markdown files and executes embedded expressions in Node and browser runtimes, exposing execution targets such as `executor`, `executor-native`, and `executor-virtual`[packages/local-md/package.json:2-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/package.json#L2-L30). For offline reading, `fumadocs-epub` bundles compiled documentation pages, assets, and tables of contents into EPUB ebooks[packages/epub/package.json:2-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/package.json#L2-L26). Integration with headless CMS platforms is supported by registry modules like `fumadocs/sanity`, which provides installable component snippets for rendering portable text collections [packages/sanity/registry/index.ts:1-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/index.ts#L1-L100). Sources: [packages/local-md/package.json:2-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/package.json#L2-L30), [packages/epub/package.json:2-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/package.json#L2-L26), [packages/sanity/registry/index.ts:1-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/index.ts#L1-L100)] ### Developer CLI Workflows The [Fumadocs CLI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/fumadocs-cli) (`@fumadocs/cli`) and site scaffolding tool (`create-fumadocs-app`) orchestrate project initialization, component management, and export actions[packages/cli/src/index.ts:1-116](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L1-L116), [packages/create-app/package.json:2-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L2-L31). The CLI runner initializes configuration files, customizes UI layouts, downloads registry components via local or HTTP connectors, exports documentation to EPUB format, and converts file tree structures into JavaScript or MDX modules[packages/cli/src/index.ts:17-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L17-L114). ```typescript program .command('add') .description('add a new component to your docs') .argument('[components...]', 'components to download') .option('--dir ', 'the root url or directory to resolve registry') .action(async (input: string[], options: { config?: string; dir?: string }) => { const config = await createOrLoadConfig(options.config); const client = createClientFromDir(options.dir); await add(input, client, config); }); const exportCmd = program.command('export').description('export documentation to various formats'); exportCmd .command('epub') .description('export documentation to EPUB format (run after production build)') .requiredOption('--framework ', 'React framework: next, tanstack-start, react-router, waku') .option('--output ', 'output file path', 'docs.epub') .option('--scaffold-only', 'only scaffold the EPUB route, do not copy') .action(async (options: { output?: string; framework: string; scaffoldOnly?: boolean }) => { await exportEpub({ output: options.output, framework: options.framework, scaffoldOnly: options.scaffoldOnly, }); }); ``` Sources: [packages/cli/src/index.ts:44-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L44-L69)] > [!WARNING] > The EPUB export command (`fumadocs export epub`) must be run after a successful production build, and requires specifying the target React framework via the required `--framework` option[packages/cli/src/index.ts:57-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L57-L69). Sources: [packages/cli/src/index.ts:57-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L57-L69)] ## Where to go next | I want to… | Read | | --- | --- | | How do you scaffold and run a minimal Fumadocs documentation site from scratch? | [Quick Start](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/quick-start) | | What are the responsibilities and dependencies across the packages in the Fumadocs workspace? | [Project Structure](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/project-structure) | | How does Fumadocs discover, parse, validate, and manage collections of documents and meta files into structured sources? | [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) | | How are hierarchical navigation trees built, transformed, sorted, and decorated with status badges and icons? | [Page Tree Generation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/page-tree-generation) | | How are documents scanned, structured, and indexed on the server using Orama, Flexsearch, or Algolia engines? | [Search Server Indexing](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-server-indexing) | | How do client dialogs query search backends including local endpoints, Orama Cloud, Algolia, and Mixedbread? | [Search Client Integrations](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-client-integrations) | | How does Shiki integration format code blocks, manage themes, parse meta attributes, and handle transformer tokens? | [Syntax Highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting) | | What remark and rehype AST transformations occur for admonitions, headings, steps, LLM exports, and mermaid diagrams? | [Markdown AST Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/markdown-ast-plugins) | | How are framework-agnostic navigation, dynamic links, and router abstractions provided for Next.js, Vite, React Router, and Waku? | [Framework Routing Adapters](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/framework-routing-adapters) | | How does Fumadocs handle locale switching, fallback languages, language negotiation, and translated page trees? | [Internationalization Support](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/internationalization-support) | | How does fumadocs-mdx compile MDX documents, track file metadata, and integrate with build tools via unified plugins? | [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline) | | How do the Webpack, Next.js, Vite, and Rolldown loader plugins intercept and transform documentation source files? | [Bundler Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/bundler-plugins) | | How do plugins generate type-safe schema validation, last-modified git timestamps, and virtual index files for documentation? | [Content Compiler Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/content-compiler-plugins) | | How are MDX strings compiled and evaluated dynamically on the server and in the browser for remote content? | [MDX Runtime Compilation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-runtime-compilation) | | What foundational primitive components does fumadocs-ui/base-ui provide for dialogs, navigation, cards, and forms? | [Base UI Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/base-ui-components) | | How does fumadocs-ui/radix-ui implement accessible primitives like popovers, collapsibles, scroll areas, and search dialogs? | [Radix UI Primitives](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/radix-ui-primitives) | | How do sidebar slots, headers, containers, footers, and page actions compose documentation layouts across frameworks? | [Shared Layout Architecture](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture) | | How does the Flux layout arrange the modern dual-sidebar, responsive navbar, and article structure? | [Ui Layouts Layout](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/ui-layouts-layout) | | How are table of contents trees extracted, highlighted dynamically on scroll, and displayed in sidebars or inline components? | [Table of Contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) | | How do interactive client and server code blocks handle syntax styling, copy actions, dynamic tab groups, and file trees? | [Code Block Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/code-block-components) | | How do CSS presets, Tailwind typography plugins, and theme variations (such as Catppuccin, Shadcn, and Vitepress) apply styling? | [Theme Styles and CSS](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/theme-styles-and-css) | | How does the shared fumadocs-api-docs package handle schema dereferencing, mock sampling, and reusable UI widgets? | [API Docs Primitives](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/api-docs-primitives) | | How are OpenAPI v3 and Swagger specifications parsed, validated, and converted into static MDX documentation pages? | [OpenAPI Document Generation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/openapi-document-generation) | | How does the OpenAPI renderer render interactive API endpoint cards, request parameters, response schemas, and curl try-it-out widgets? | [OpenAPI Interactive UI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/openapi-interactive-ui) | | How does Fumadocs automatically generate code snippets for cURL, JavaScript, Python, Go, and C# from OpenAPI endpoint schemas? | [Code Sample Generators](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/code-sample-generators) | | How are AsyncAPI specifications loaded, dereferenced, and converted into asynchronous messaging documentation? | [AsyncAPI Document Processing](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/asyncapi-document-processing) | | How does Fumadocs render protocol-specific message configurations for Kafka, MQTT, WebSockets, AMQP, and SQS? | [AsyncAPI Protocol Bindings](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/asyncapi-protocol-bindings) | | How does Fumadocs read Obsidian vaults and convert wikilinks, callouts, block IDs, and comments to standard MDX? | [Obsidian Vault Integration](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/obsidian-vault-integration) | | How does fumadocs-local-md parse pure markdown and execute embedded expressions with Node and browser clients? | [Local Markdown Runtime](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/local-markdown-runtime) | | How does Fumadocs integrate with Content Collections for static type-safe document fetching and metadata mapping? | [Content Collections Adapter](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/content-collections-adapter) | | How does the fumapy Python module inspect docstrings and generate structured documentation data for Fumadocs? | [Python Docstring Extractor](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/python-docstring-extractor) | | How does Fumadocs ingest structured portable text and document trees from Sanity headless CMS into docs pages? | [Sanity CMS Integration](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/sanity-cms-integration) | | How does Fumadocs fetch and render documentation collections stored within BaseHub headless CMS? | [BaseHub Integration](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/basehub-integration) | | How does Fumadocs provide manual and automated installations of documentation components compatible with shadcn/ui? | [shadcn/ui Docs Registry](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/shadcn-ui-docs-registry) | | How do the CLI commands customize components, add registry snippets, export EPUB documents, and inspect file trees? | [Fumadocs CLI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/fumadocs-cli) | | How does create-fumadocs-app scaffold projects across frameworks (Next.js, React Router, TanStack Start) and linters? | [Create App Generator](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/create-app-generator) | | How does the built-in Waku-based preview server provide live hot reloading, AI chat search, and dynamic OG image generation? | [Preview Server](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/preview-server) | | How does Fumadocs extract TypeScript AST interfaces, type aliases, and JSDoc tags to build interactive type tables? | [TypeScript Type Table Extraction](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/typescript-type-table-extraction) | | How does fumadocs-twoslash integrate with Shiki to display compiler diagnostics, type hints, and hover popups? | [Twoslash Type Hover](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/twoslash-type-hover) | | How does the fumadocs-story package parse component props and render live interactive playground controls inside documentation? | [Interactive Component Playground](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/interactive-component-playground) | | How does STF parse, format, and render structured documentation payloads across server and client boundaries? | [Structured Text Format](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/structured-text-format) | | How does fumadocs-epub bundle documentation pages, assets, stylesheets, and tables of contents into EPUB ebooks? | [EPUB Book Export](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/epub-book-export) | | How do fumadocs-vite and vite-data provide HMR and data resolution for non-Next.js build tools? | [Vite Integration Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/vite-integration-plugins) | ## Related - [Quick Start](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/quick-start) - [Project Structure](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/project-structure) - [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) --- ## Technical docs: Search Query Regex Compilation URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/how-it-works/search-query-regex-compilation
Relevant source files The following files were used as context for generating this wiki page: - [packages/core/src/search/orama/create-server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts) - [packages/core/src/search/orama/search/simple.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts) - [packages/core/src/search/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts)
## Overview ### Introduction The execution flow from `createFromSource` down to `buildRegexFromQuery` represents the core lifecycle of a search request in Fumadocs, transitioning from document loader outputs to indexed search servers, execution against an Orama database instance, and finally result post-processing with dynamic search term highlighting. ```mermaid sequenceDiagram participant Source as create-server.ts participant Simple as simple.ts participant Index as index.ts Source->>Source: createFromSource() Source->>Source: getCurrentServer() Source->>Source: initServer() Source->>Source: createI18nSearchAPI() / initAdvancedSearch() Source->>Source: initSearchServers() Source->>Simple: initSimpleSearch() / searchSimple() Simple->>Index: createContentHighlighter() Index->>Index: buildRegexFromQuery() Index-->>Simple: RegExp | null Simple-->>Source: SortedResult[] ``` Sources: [packages/core/src/search/orama/create-server.ts:273-324](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L273-L324), [packages/core/src/search/orama/search/simple.ts:5-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts#L5-L27), [packages/core/src/search/index.ts:36-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L43) ```mermaid flowchart TD A[createFromSource] --> B[getCurrentServer] B --> C[initServer] C --> D{Has i18n?} D -- Yes --> E[createI18nSearchAPI] D -- No --> F[initAdvancedSearch] E --> G[initSearchServers] G --> H[initSimpleSearch] H --> I[searchSimple] I --> J[createContentHighlighter] J --> K[buildRegexFromQuery] ``` Sources: [packages/core/src/search/orama/create-server.ts:187-324](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L187-L324), [packages/core/src/search/orama/search/simple.ts:5-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts#L5-L19), [packages/core/src/search/index.ts:36-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L48) ### Step 1: createFromSource `createFromSource` initiates the search server configuration using a document loader or an asynchronous loader function. It sets up a WeakMap-based cache linked to specific loader outputs to optimize server initialization and handle re-indexing when loader instances change. Sources: [packages/core/src/search/orama/create-server.ts:273-279](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L273-L279) ### Step 2: getCurrentServer `getCurrentServer` resolves the current loader output—evaluating it if passed as a function—and checks the internal cache for an existing server promise. If a cached server instance does not exist for the current loader reference, it triggers server initialization and stores the resulting promise in the cache. Sources: [packages/core/src/search/orama/create-server.ts:306-314](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L306-L314) ### Step 3: initServer `initServer` processes all pages retrieved from the loader. It maps each page through `buildIndex` to create searchable index records, generates missing breadcrumbs automatically, assigns locale metadata, and inspects whether internationalization (`_i18n`) is configured. Sources: [packages/core/src/search/orama/create-server.ts:280-304](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L280-L304) ### Step 4: createI18nSearchAPI When internationalization is enabled (`loader._i18n`), `createI18nSearchAPI` wraps search operations across multiple language contexts. It initiates background server setup per language via `initSearchServers` and routes queries to the appropriate language handler based on user options or defaults. Sources: [packages/core/src/search/orama/create-server.ts:178-259](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L178-L259) ### Step 5: initSearchServers `initSearchServers` iterates through all configured languages in the internationalization settings, filters document indexes matching the current locale, maps locale codes to compatible stemmers or tokenizers, and instantiates language-specific search servers. Sources: [packages/core/src/search/orama/create-server.ts:190-237](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L190-L237) ### Step 6: initSimpleSearch `initSimpleSearch` constructs a simple search server instance over an Orama database (`createDBSimple`). It exposes export capabilities for static bundle generation and a `search` method that queries the underlying database instance using `searchSimple`. Sources: [packages/core/src/search/orama/create-server.ts:78-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L78-L98) ### Step 7: searchSimple `searchSimple` executes the search query against the Orama database with tolerance and term boosting configured. Upon receiving search hits, it invokes `createContentHighlighter` to generate highlighted content strings for presentation. Sources: [packages/core/src/search/orama/search/simple.ts:5-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts#L5-L27) ### Step 8: createContentHighlighter `createContentHighlighter` accepts a query string or precompiled regular expression. If given a string, it hands the query to `buildRegexFromQuery` to generate a case-insensitive matching pattern, returning helper methods for text and Markdown highlighting. Sources: [packages/core/src/search/index.ts:47-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L47-L49) ### Step 9: buildRegexFromQuery `buildRegexFromQuery` cleans and splits the query string into distinct search terms, escapes special regular expression characters via `escapeRegExp`, deduplicates terms, and builds a combined case-insensitive `RegExp` matching group for highlighting matches. If the query trims down to an empty string, it returns `null`. Sources: [packages/core/src/search/index.ts:36-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L43) ## Key Observations - **Cross-Module Boundaries:** The flow bridges higher-level content source loading (`@/source/loader`) with Orama indexing infrastructure (`@orama/orama`), routing through server endpoint wrappers and text processing utilities in `@/search`. - **Caching Strategy:** Server instances are cached using a `WeakMap` mapped to loader output references. This ensures memory efficiency while preventing redundant re-indexing unless a fresh loader instance is produced. - **Robust Query Normalization:** Query strings undergo trimming, whitespace splitting, deduplication, and regex escaping inside `buildRegexFromQuery` to safely handle arbitrary user inputs without crashing parser or highlighter steps. --- ## Technical docs: MDX Configuration Preset Loading URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/how-it-works/mdx-configuration-preset-loading
Relevant source files The following files were used as context for generating this wiki page: - [packages/mdx/src/next/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) - [packages/mdx/src/config/load-from-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/load-from-file.ts) - [packages/mdx/src/config/build.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/build.ts) - [packages/mdx/src/config/preset.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts)
## Overview The execution flow from `createMDX` through `applyMdxPreset` bridges Next.js configuration integration with Fumadocs' content management engine. When initializing MDX for a Next.js project, the core framework compiles user-defined source configurations, builds collections, and automatically configures remark and rehype processor options. This ensures that markdown and MDX files are parsed correctly across different build environments (bundler vs. runtime). Sources: [packages/mdx/src/next/index.ts:30-122](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L122) ## Execution Flow ### Step 1: createMDX The process begins when `createMDX` is invoked with optional configuration options (`CreateMDXOptions`). It sets up the Next.js core environment using `createNextCore` and `applyDefaults`, and ensures that initialization occurs only once by checking the `_FUMADOCS_MDX` environment variable. It returns a curried function that injects custom Webpack and Turbopack rules for `.mdx`, `.md`, `.json`, and `.yaml` files into the Next.js configuration. Sources: [packages/mdx/src/next/index.ts:30-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L38) ### Step 2: init Invoked asynchronously during setup, the `init` function manages core initialization and coordinates the development server lifecycle. It defines internal helper routines (`initOrReload` and `devServer`) to load configurations and watch file changes during local development. Sources: [packages/mdx/src/next/index.ts:124-182](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L124-L182) ### Step 3: devServer If running in a development environment, `devServer` sets up a file watcher using `chokidar`. It monitors the configuration file and all registered collection directories. When the configuration file changes, the watcher safely closes itself, reloads the configuration, restarts the development server routine, and re-initializes the server watcher. Sources: [packages/mdx/src/next/index.ts:132-176](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L132-L176) ### Step 4: initOrReload The `initOrReload` function orchestrates core startup by calling `core.init` with the result of loading the configuration file. Once initialized, it instructs the core to emit generated artifacts (such as index files or type definitions) with writing enabled (`write: true`). Sources: [packages/mdx/src/next/index.ts:125-130](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L125-L130) ### Step 5: loadConfig The `loadConfig` function handles compiling and importing the source configuration file. When the `build` flag is set to true, it triggers `compileConfig` using `esbuild` to bundle the source configuration into a portable ESM module (`.mjs`). It then appends a timestamp query parameter to bust module cache before dynamically importing the compiled config and passing the raw exports to `buildConfig`. Sources: [packages/mdx/src/config/load-from-file.ts:35-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/load-from-file.ts#L35-L44) ### Step 6: buildConfig The `buildConfig` function parses raw configuration exports, mapping collection objects and global settings. It constructs collection instances and exposes a `getMDXOptions` method. When MDX options are requested for a specific collection or environment, it evaluates global or collection-level options and delegates preset generation to `applyMdxPreset`. Sources: [packages/mdx/src/config/build.ts:118-180](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/build.ts#L118-L180) ### Step 7: applyMdxPreset Finally, `applyMdxPreset` takes the user's MDX options and returns an asynchronous function that resolves processor options for the specified build environment (`bundler` or `runtime`). If the preset is set to `'minimal'`, it returns the options unchanged. Otherwise, it loads `fumadocs-core/mdx-plugins` and configures standard remark plugins (such as `remarkGfm`, `remarkHeading`, `remarkImage`, and `remarkStructure`) and rehype plugins (such as `rehypeCode` and `rehypeToc`), adjusting options based on whether it is targeting a bundler or runtime environment. Sources: [packages/mdx/src/config/preset.ts:50-132](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L50-L132) --- ## Architecture Diagrams ### Sequence Diagram ```mermaid sequenceDiagram participant Next as Next.js Config participant Index as packages/mdx/next participant Core as Core Engine participant Loader as loadConfig participant Builder as buildConfig participant Preset as applyMdxPreset Next->>Index: createMDX(options) Index->>Index: init(isDev, core) Index->>Core: initOrReload() Core->>Loader: loadConfig(core, true) Loader->>Loader: compileConfig(core) Loader->>Builder: buildConfig(loaded, cwd) Builder->>Preset: applyMdxPreset(options) Preset-->>Builder: ProcessorOptions Builder-->>Loader: LoadedConfig Loader-->>Core: Resolved config Core-->>Index: Initialized ``` Sources: [packages/mdx/src/next/index.ts:30-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L38), [packages/mdx/src/config/load-from-file.ts:35-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/load-from-file.ts#L35-L44), [packages/mdx/src/config/build.ts:118-180](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/build.ts#L118-L180), [packages/mdx/src/config/preset.ts:50-132](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L50-L132) ### Flowchart ```mermaid flowchart TD A[createMDX] --> B[init] B --> C{isDev?} C -->|Yes| D[devServer & initOrReload] C -->|No| E[initOrReload] D --> F[loadConfig] E --> F[loadConfig] F --> G[compileConfig with esbuild] G --> H[buildConfig] H --> I[applyMdxPreset] I --> J[Return ProcessorOptions] ``` Sources: [packages/mdx/src/next/index.ts:30-182](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L182), [packages/mdx/src/config/load-from-file.ts:6-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/load-from-file.ts#L6-L44), [packages/mdx/src/config/build.ts:118-180](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/build.ts#L118-L180), [packages/mdx/src/config/preset.ts:50-132](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L50-L132) --- ## Key Observations - **Cross-Module Boundaries:** The flow bridges Next.js integration hooks (`packages/mdx/src/next/index.ts`) with configuration building (`packages/mdx/src/config/load-from-file.ts` and `build.ts`) and unified plugin management (`packages/mdx/src/config/preset.ts`). - **Error Handling:** Configuration compilation checks `transformed.errors.length` and throws an error if `esbuild` fails. Dynamic imports and file watcher logic ensure that updates to config files gracefully restart the development environment. - **Caching & Dynamic Reloading:** `loadConfig` invalidates import caches by appending a millisecond timestamp hash query parameter to the file URL, ensuring fresh configuration loads during development reloads. Sources: [packages/mdx/src/config/load-from-file.ts:25-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/load-from-file.ts#L25-L41) --- ## Technical docs: Quick Start URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/quick-start
Relevant source files The following files were used as context for generating this wiki page: - [packages/cli/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts) - [packages/create-app/src/bin.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/bin.ts) - [packages/preview/src/cli/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/index.ts) - [packages/python/pyproject.toml](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml) - [packages/python/fumapy/__init__.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/__init__.py) - [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx) - [packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/preview/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json) - [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/create-app/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json) - [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts) - [packages/create-app/scripts/sync.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/scripts/sync.ts) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/local-md/src/dev/react-client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/react-client.ts) - [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts) - [packages/preview/fumadocs.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/fumadocs.config.ts) - [packages/content/src/runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts) - [packages/cli/src/commands/export-epub.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/export-epub.ts) - [packages/mdx/src/next/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) - [packages/python/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json) - [packages/create-app/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/index.ts) - [packages/core/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json) - [packages/cli/src/commands/add.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/add.ts) - [packages/openapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json) - [packages/local-md/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/package.json) - [packages/preview/src/cli/commands.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/commands.ts) - [packages/asyncapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json) - [packages/python/fumapy/mksource/__init__.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/__init__.py)
## Overview Getting started with Fumadocs involves bootstrapping a dedicated documentation workspace, configuring content collections, rendering routing hierarchies, and managing development environments. The initialization workflow is powered by [Create App Generator](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/create-app-generator) and the [Fumadocs CLI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/fumadocs-cli), which scaffold template applications, install dependencies, and configure linters across supported frameworks. Sources: [packages/create-app/src/bin.ts:22-54](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/bin.ts#L22-L54), [packages/cli/src/index.ts:17-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L17-L27) ## Bootstrapping with CLI tooling ### Scaffolding Workspaces and Command Options Fumadocs provides dedicated command-line utilities to initialize documentation projects, manage configuration files, and interact with component registries. The primary package for scaffolding workspaces is `create-fumadocs-app`, which is versioned at `16.0.123` and bundles dependencies such as `@clack/prompts`, `tinyexec`, and `ts-morph`. Sources: [packages/create-app/package.json:3-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L3-L52) Once inside a workspace, the `fumadocs` CLI (`@fumadocs/cli`) offers core routines for workspace initialization, layout customization, component downloads, and tree transformations. The CLI is powered by `commander` and `picocolors`. Sources: [packages/cli/src/index.ts:4-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L4-L20) | Command | Aliases | Options | Description | | :--- | :--- | :--- | :--- | | `fumadocs` (default) | none | `--config ` | Initializes a `./cli.json` configuration file if one does not already exist | | `customise` | `customize` | `--dir `, `--config ` | Simple way to customize layouts with Fumadocs UI | | `add` | none | `--dir `, `--config ` | Downloads and adds new components to your docs | | `export epub` | none | `--framework `, `--output `, `--scaffold-only` | Exports documentation to EPUB format | | `tree` | none | `--js`, `--no-root`, `--import-name ` | Generates JavaScript or MDX file trees from JSON or directory arguments | Sources: [packages/cli/src/index.ts:17-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L17-L83) > [!NOTE] > The default action of the `fumadocs` binary checks for the existence of `./cli.json`. If it does not exist, it initializes the file and logs a success message; if it already exists, it emits a notice indicating that the config file is already present. > Sources: [packages/cli/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L21-L27) ### Registry Connectors and Framework Targets When executing commands that fetch remote or local components or layouts, the CLI resolves registry sources using `createClientFromDir`. Short-form directory shortcuts map specific keywords to designated endpoints. ```typescript const dirShortcuts: Record = { ':preview': 'https://preview.fumadocs.dev/registry', ':dev': 'http://localhost:3000/registry', }; ``` Sources: [packages/cli/src/index.ts:39-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L39-L42) The `createClientFromDir` function inspects the directory path or shortcut. If the destination begins with `http://` or `https://`, it instantiates an `HttpRegistryConnector`; otherwise, it returns a `LocalRegistryConnector`. ```typescript function createClientFromDir(dir = 'https://fumadocs.dev/registry') { if (dir in dirShortcuts) dir = dirShortcuts[dir]; return dir.startsWith('http://') || dir.startsWith('https://') ? new HttpRegistryConnector(dir) : new LocalRegistryConnector(dir); } ``` Sources: [packages/cli/src/index.ts:108-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L108-L114) > [!WARNING] > When executing `fumadocs export epub`, the `--framework` option is required. The supported framework names accepted by the command parser are `next`, `tanstack-start`, `react-router`, and `waku`. > Sources: [packages/cli/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L57-L63) ## Configuring content collections and schemas ### Declaring Document Collections Documentation sources are structured through collection configuration helpers provided by `@fumadocs/content`. The `docsCollection` function binds MDX documentation documents and metadata files into a unified store, accepting directory paths and custom validation schemas for both types of content. ```typescript export interface DocsCollectionConfig< FrontmatterSchema extends StandardSchemaV1 | undefined, MetaSchema extends StandardSchemaV1 | undefined, > { dir: string; docs: Omit, 'dir'>; meta: Omit, 'dir'>; } export function docsCollection< FrontmatterSchema extends StandardSchemaV1 | typeof pageSchema = typeof pageSchema, MetaSchema extends StandardSchemaV1 | typeof metaSchema = typeof metaSchema, >(config: DocsCollectionConfig) { return { index: new DocsCollection(), meta: dataCollection({ dir: config.dir, ...config.meta }), doc: docsMdxCollection({ dir: config.dir, ...config.docs }), }; } ``` Sources: [packages/content/src/index.ts:35-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L35-L53) The underlying `DocsCollection` class extends the base `Collection` implementation from `fuma-content/collections`. During its emit lifecycle (`onEmit.pipe`), it dynamically generates code files for code generation workflows, writing module imports and export definitions for runtime stores. ```typescript export class DocsCollection extends Collection { constructor() { super(); this.onEmit.pipe(async (data, ctx) => { const file = await ctx.createCodeGenerator(`${this.name}.ts`, ({ codegen }) => { const docName = `${this.name}$doc`; const metaName = `${this.name}$meta`; codegen.addNamedImport([docName], `./${docName}`); codegen.addNamedImport([metaName], `./${metaName}`); codegen.addNamedImport(['docsStore'], '@fumadocs/content/runtime'); codegen.push(`export const ${this.name} = docsStore(${docName}, ${metaName})`); }); data.push(file); return data; }); } ``` Sources: [packages/content/src/index.ts:55-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L55-L70) > [!NOTE] > The `DocsCollection` generator creates code files named `.ts` that import the respective document and metadata files, import `docsStore` from `@fumadocs/content/runtime`, and export a combined store constant. > Sources: [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L59-L65) ### Defining Content Schemas and Runtime Stores Content schemas validate frontmatter attributes against standard schema specifications such as `@Standard-schema/spec`. By default, `docsMdxCollection` and `docsCollection` fall back to `pageSchema` and `metaSchema` imported from `fumadocs-core/source/schema`. ```typescript export function docsMdxCollection< FrontmatterSchema extends StandardSchemaV1 | typeof pageSchema = typeof pageSchema, >(config: DocsMDXCollectionConfig) { const { options = {}, frontmatter = pageSchema, ...rest } = config; return mdxCollection({ ...rest, frontmatter: frontmatter as never, async options() { const mdxOptions = typeof options === 'object' ? options : await options(); const { remarkInclude } = await import('fuma-content/plugins/remark/include'); return mdxPreset({ ...mdxOptions, _include: remarkInclude, }); }, }); } ``` Sources: [packages/content/src/index.ts:16-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L33) The runtime integration layer converts raw MDX and metadata file stores into static source representations consumed by Fumadocs routing and layout utilities. The `toFumadocsSource` function iterates over the list of pages and metadata files, normalizing paths and combining compiled frontmatter properties. ```typescript export function toFumadocsSource< Mdx extends MDXStoreData | MDXStoreLazyData = MDXStoreData< PageData, unknown >, Meta extends { data: MetaData } = { data: MetaData }, >(mdxStore?: FileCollectionStore, metaStore?: FileCollectionStore) { const out: StaticSource<{ pageData: ToPageData; metaData: Meta['data']; }> = { files: [] }; for (const page of mdxStore?.list() ?? []) { out.files.push({ type: 'page', data: ('compiled' in page ? { ...page, ...page.compiled.frontmatter } : { ...page, ...page.frontmatter }) as unknown as ToPageData, path: page.path, absolutePath: page.fullPath, }); } for (const file of metaStore?.list() ?? []) { out.files.push({ type: 'meta', data: file.data, path: file.path, absolutePath: file.fullPath, }); } return out; } ``` Sources: [packages/content/src/runtime.ts:12-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L12-L42) | Function / Class | Parameters | Return Type | Description | | :--- | :--- | :--- | :--- | | `docsMdxCollection` | `config: DocsMDXCollectionConfig` | MDX collection instance | Configures MDX collections with preset options and remark include plugins | | `docsCollection` | `config: DocsCollectionConfig` | `{ index, meta, doc }` | Combines metadata and MDX collections into a unified documentation workspace | | `DocsCollection` | none | `DocsCollection` class instance | Extends base collections to emit code generator output files during build pipelines | | `toFumadocsSource` | `mdxStore`, `metaStore` | `StaticSource` | Transforms file collection stores into standard Fumadocs static source structures | | `docsStore` | `mdxStore`, `metaStore` | `{ toFumadocsSource() }` | Wraps file stores with a method to export static source data | Sources: [packages/content/src/index.ts:16-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L53), [packages/content/src/index.ts:55-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L55-L70), [packages/content/src/runtime.ts:12-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L12-L56) > [!WARNING] > When defining custom options for `docsMdxCollection`, the options parameter can be passed directly as an object or as an asynchronous factory function returning `MDXBundlerPresetOptions`. The runtime automatically injects the `remarkInclude` plugin into the bundler preset. > Sources: [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L11-L31) ## Mounting documentation pages and layouts ### Layout and Preset Resolution Documentation routes are handled by dynamic page components receiving URL slugs. The [preview server](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/preview-server) loads the runtime configuration and resolves the metadata source before determining whether to use the default `docs` layout preset or the alternative `flux` preset. ```tsx export default async function DocPage({ slugs }: PageProps<'/docs/[...slugs]'>) { const config = await getConfigRuntime(); const source = await getSource(config); const page = source.getPage(slugs); const mdPreset = config.layout.presets?.md ?? 'docs'; let mdPresetComponents: MdPresetComponents; if (mdPreset === 'docs') { mdPresetComponents = { layout: await import('fumadocs-ui/layouts/docs'), page: await import('fumadocs-ui/layouts/docs/page'), }; } else { mdPresetComponents = { layout: await import('fumadocs-ui/layouts/flux'), page: await import('fumadocs-ui/layouts/flux/page'), }; } return ; } ``` Sources: [packages/preview/src/pages/...slugs.tsx:76-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L76-L96) | Layout Preset | Layout Component Import | Page Component Import | | :--- | :--- | :--- | | `docs` | `fumadocs-ui/layouts/docs` | `fumadocs-ui/layouts/docs/page` | | `flux` | `fumadocs-ui/layouts/flux` | `fumadocs-ui/layouts/flux/page` | Sources: [packages/preview/src/pages/...slugs.tsx:83-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L83-L93) > [!NOTE] > The layout preset is read directly from `config.layout.presets?.md`. If it is not explicitly configured, it defaults to the standard `docs` layout. > Sources: [packages/preview/src/pages/[...slugs].tsx:80-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/[...slugs].tsx#L80-L88) ### Markdown Compilation and Container Rendering The `MdContent` component builds the surrounding container structure, integrating AI search capabilities if supported by the environment. It checks if the requested page exists in the source tree; if missing, it either presents a home overview cards listing or a standard 404 Not Found view. ```tsx async function MdContent({ slugs, page, components, }: { slugs: string[]; page?: SourcePage; components: MdPresetComponents; }) { const config = await getConfigRuntime(); const source = await getSource(config); const layout = layoutConfig(config); const { DocsLayout } = components.layout; const { DocsBody, DocsTitle, DocsPage, DocsDescription } = components.page; async function renderContainer(children: ReactNode) { const hasAI = await isAISupported(); return ( {hasAI && ( Ask AI )} {children} ); } ``` Sources: [packages/preview/src/pages/...slugs.tsx:98-138](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L98-L138) Markdown strings are processed through a configured compiler instance equipped with remark and rehype plugins for GitHub-Flavored Markdown, math equations, diagrams, heading anchors, package managers, code tabs, and [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting). ```tsx const compiler = createMarkdownCompiler({ remarkPlugins: [ remarkGfm, remarkMath, remarkMdxMermaid, plugin(remarkHeading, { generateToc: false }), plugin(remarkNpm, { persist: { id: 'package-manager' } }), remarkCodeTab, ], remarkRehypeOptions: { passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement'], }, rehypePlugins: [ rehypeKatex, plugin(rehypeCode, { lazy: true, fallbackLanguage: 'text' }), plugin(rehypeToc, { exportToc: { as: 'data' } }), ], }); ``` Sources: [packages/preview/src/pages/...slugs.tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46) > [!CAUTION] > If compilation fails, the catch block intercepts the error and renders a dedicated error view displaying the error message and its stack trace inside a code block. > Sources: [packages/preview/src/pages/[...slugs].tsx:170-194](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/[...slugs].tsx#L170-L194) ## Running the live preview server ### Standalone CLI Execution and Port Allocation The preview runtime is executed via the `fumadocs-preview` command-line interface, defined using the `commander` package. The CLI provides two primary commands: `init`, which scaffolds a default configuration file named `fumadocs.config.ts`, and `start`, which serves as the default action for starting the live preview server. ```typescript program .command('init') .description('create configuration file') .action(async () => { if ((await findConfigPath()) === null) { await fs.writeFile( 'fumadocs.config.ts', `import { defineConfig } from "fumadocs-preview/config";\n\nexport default defineConfig();`, ); console.log('note: make sure to install `fumadocs-preview` as a dev dependency too.'); } }); program .command('start', { isDefault: true }) .description('start Fumapress') .argument('[dirs...]', 'a list of content directories to view') .option('-p, --port ') .option('-h, --host ') .action(async (dirs: string[] | undefined, options: { port?: string; host?: string }) => { await runStart({ ...options, dirs }); }); ``` Sources: [packages/preview/src/cli/index.ts:8-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/index.ts#L8-L30) | Command | Description | Arguments / Options | | :--- | :--- | :--- | | `init` | Create configuration file | None | | `start` | Start Fumapress | `[dirs...]`, `-p, --port `, `-h, --host ` | Sources: [packages/preview/src/cli/index.ts:8-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/index.ts#L8-L30) When the `start` command executes, `runStart` loads environment variables via `loadEnv()` and overrides `NODE_ENV` to `production`. It invokes `getFreePort` starting from a default port of `8080` (or a custom port specified via options) to find an available TCP port by probing network sockets with `net.createServer()`. If the port is occupied with an `EADDRINUSE` error, it automatically increments the port number until an open socket is secured. ```typescript async function getFreePort(startPort: number): Promise { for (let port = startPort; ; port++) { try { await new Promise((resolve, reject) => { const srv = net .createServer() .once('error', reject) .once('listening', () => srv.close(() => resolve())) .listen(port); }); return port; } catch (err) { if ((err as NodeJS.ErrnoException).code !== 'EADDRINUSE') { throw err; } } } } ``` Sources: [packages/preview/src/cli/commands.ts:36-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/commands.ts#L36-L53) > [!WARNING] > If `getFreePort` encounters any socket error other than `EADDRINUSE`, it does not retry and immediately rejects with that error. > Sources: [packages/preview/src/cli/commands.ts:47-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/commands.ts#L47-L51) ### Environment Setup and Server Bootstrapping Prior to launching the server bundle, `runStart` configures several required process environment variables to pass parameters down to the Waku server runtime. ```typescript if (host) { process.env.HOST = host; } process.env.PORT = String(port); process.env.ROOT_DIR = process.cwd(); if (!dirs || dirs.length === 0) { dirs = ['']; } process.env.DEFAULT_PROJECT_DIR = JSON.stringify(dirs.map((v) => path.resolve(v))); process.env.HOT_RELOAD = '1'; process.chdir(baseDir); await import(serveFileUrl); console.log(`ready: Listening on http://${host || 'localhost'}:${port}/`); } ``` Sources: [packages/preview/src/cli/commands.ts:20-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/commands.ts#L20-L34) | Environment Variable | Assigned Value / Logic | Purpose | | :--- | :--- | :--- | | `HOST` | `host` option parameter (if provided) | Binds the server to a specific network host address | | `PORT` | `String(port)` | Sets the listening port resolved by `getFreePort` | | `ROOT_DIR` | `process.cwd()` | Establishes the root directory context for project file resolution | | `DEFAULT_PROJECT_DIR` | JSON string of `dirs` mapped via `path.resolve()` | Specifies content directories to view; defaults to `['']` if empty | | `HOT_RELOAD` | `'1'` | Enables dynamic hot-reloading behavior in the preview environment | Sources: [packages/preview/src/cli/commands.ts:20-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/commands.ts#L20-L29) > [!TIP] > After configuring environment variables, `runStart` changes the working directory to `baseDir` and dynamically imports the compiled Node server entry point (`dist/waku/serve-node.js`) using `pathToFileURL`. > Sources: [packages/preview/src/cli/commands.ts:5-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/commands.ts#L5-L31) ## Enabling dynamic local markdown updates ### Local Markdown Source Configuration and Compilation The `@fumadocs/local-md` package provides the `localMd` factory function to manage local markdown and metadata files as a content source. It accepts a `LocalMarkdownConfig` object defining the root content directory (`dir`), glob patterns (`include`), frontmatter and metadata schemas, and optional compiler settings. ```typescript export interface LocalMarkdownConfig< FrontmatterSchema extends StandardSchemaV1, MetaSchema extends StandardSchemaV1, > extends MarkdownCompilerOptions { /** * root directory for content files. */ dir: string; /** * a list of glob patterns, customize the content files to be scanned. */ include?: string[]; rendererOptions?: Pick; frontmatterSchema?: FrontmatterSchema; metaSchema?: MetaSchema; } ``` Sources: [packages/local-md/src/index.ts:24-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L24-L40) | Configuration Property | Type | Default / Purpose | | :--- | :--- | :--- | | `dir` | `string` | Root directory for content files | | `include` | `string[]` | Glob patterns to scan content files | | `frontmatterSchema` | `StandardSchemaV1` | Validation schema for page frontmatter | | `metaSchema` | `StandardSchemaV1` | Validation schema for metadata files | Sources: [packages/local-md/src/index.ts:24-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L24-L40) When `staticSource` or `dynamicSource` is invoked, `createFiles` reads pages and metadata via internal storage and builds virtual files. Each page includes a `load` function that checks a weak map cache (`compilerCache`) or compiles the markdown content using `createMarkdownCompiler`. Depending on the compiler result type, it delegates to `fromAst` or `fromJS` to generate the final renderer. ```typescript async load() { let promise = compilerCache.get(page); if (!promise) { promise = compiler.compile({ path: page.absolutePath, value: page.content, data: { frontmatter: page.frontmatter }, }); } const res = await promise; return res.type === 'ast' ? fromAst({ tree: res.tree, filePath: res.file.path, rehypeToc: res.file.data.rehypeToc, structuredData: res.file.data.structuredData, ...config.rendererOptions, }) : fromJS({ code: res.code, filePath: res.file.path, baseUrl: pathToFileURL(res.file.path).href, structuredData: res.file.data.structuredData, }); }, ``` Sources: [packages/local-md/src/index.ts:125-150](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L125-L150) > [!NOTE] > The `compilerCache` uses a `WeakMap, Promise>` to memoize compilation promises per raw page object and prevent redundant parsing during development. > Sources: [packages/local-md/src/index.ts:90-92](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L90-L92) ### Hot-Reloading via Development Server and WebSocket Clients To support real-time editing, the `localMd` instance exposes a `devServer` method and an `invalidateFile` mechanism. When `devServer` is called, it connects to a WebSocket server, sends a `watch-dir` message with the configured directory and glob patterns, and listens for change events to invalidate modified files. ```typescript async devServer(url = getDevServerUrlFromEnv()) { if (!url) { console.warn( `[@fumadocs/local-md] dev server URL could not be found, try passing the URL to devServer() explicitly instead`, ); return; } const { connectDevServer } = await import('@/dev/node-client'); const conn = connectDevServer(url); conn.send({ type: 'watch-dir', dir: path.resolve(config.dir), includes: config.include ?? defaultInclude, }); conn.subscribe((event) => { if (event.type === 'change') { this.invalidateFile(event.absolutePath); } }); }, ``` Sources: [packages/local-md/src/index.ts:174-195](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L174-L195) The React client component `DevClient` establishes a WebSocket connection to the development server using the URL resolved by `getDevServerUrlFromEnv`. Upon receiving an incoming message, it decodes the event using `decodeDevEvent`. If the decoded event type is a `change`, it logs the update and calls `router.refresh()` to trigger an immediate page reload in the framework router. ```typescript export function DevClient(): ReactNode { const router = useRouter(); const onUpdate = useEffectEvent((event: DevServerEvent) => { if (event.type === 'change') { console.log(`[@fumadocs/local-md] "${event.absolutePath}" updated`); router.refresh(); } }); useEffect(() => { const url = getDevServerUrlFromEnv(); if (!url) return; const ws = new WebSocket(url); ws.onopen = () => { console.log(`[@fumadocs/local-md] connected to dev server at ${url}`); }; ws.onmessage = (event) => { const decoded = decodeDevEvent(String(event.data)); if (decoded) onUpdate(decoded); }; ws.onclose = () => { console.log(`[@fumadocs/local-md] disconnected from dev server at ${url}`); }; return () => { ws.close(); }; }, []); ``` Sources: [packages/local-md/src/dev/react-client.ts:6-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/react-client.ts#L6-L38) > [!WARNING] > If `getDevServerUrlFromEnv` returns no URL during client initialization or inside `devServer()`, the connection attempt is aborted with a warning message or early return. > Sources: [packages/local-md/src/index.ts:174-180](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L174-L180), [packages/local-md/src/dev/react-client.ts:16-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/react-client.ts#L16-L18) ## Related - [Overview](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/overview) - [Project Structure](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/project-structure) - [Create App Generator](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/create-app-generator) --- ## Technical docs: Project Structure URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/project-structure
Relevant source files The following files were used as context for generating this wiki page: - [packages/python/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json) - [packages/api-docs/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json) - [packages/preview/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json) - [packages/python/pyproject.toml](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml) - [packages/core/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json) - [packages/openapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json) - [packages/content/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json) - [packages/base-ui/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json) - [packages/asyncapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json) - [packages/obsidian/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/package.json) - [packages/basehub/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/package.json) - [packages/radix-ui/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json) - [packages/vite-data/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/vite-data/package.json) - [packages/shared/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/package.json) - [packages/sanity/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/package.json) - [packages/python/fumapy/mksource/__init__.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/__init__.py) - [packages/twoslash/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json) - [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts) - [packages/typescript/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json) - [packages/python/fumapy/mksource/models.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/models.py) - [packages/epub/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/package.json) - [packages/doc-gen/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json) - [packages/create-app-versions/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app-versions/package.json) - [packages/create-app/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json) - [packages/local-md/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/package.json) - [packages/python/src/components/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx) - [packages/story/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/package.json) - [packages/language/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json) - [packages/sanity/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/index.ts) - [packages/mdx/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json)
## Overview The Fumadocs monorepo is organized into specialized packages that power documentation generation, processing, and rendering. Workspace packages such as `fumadocs-core`, `fumadocs-ui`, `@fumadocs/base-ui`, `fumadocs-mdx`, and `@fumadocs/openapi` collaborate across build and runtime phases to support content transformation, UI layouts, and API spec tooling. Sources: [packages/core/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L1-L4), [packages/radix-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L1-L4), [packages/base-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L1-L4), [packages/mdx/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L1-L4), [packages/openapi/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L1-L4) ## Core Architecture and Shared Utilities ### Core Package Responsibilities The foundational runtime and processing logic of the workspace resides in `fumadocs-core` (`packages/core`), published under version `16.10.2` as an ES module package. It provides public entrypoints for breadcrumbs, content transformers, dynamic linking, framework adapters, code highlighters, internationalization, page trees, search indexers, and source loaders [packages/core/package.json:1-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L1-L97). The package exports framework-specific routing and rendering adapters for Next.js, React Router, TanStack, and Waku through its framework entrypoints [packages/core/package.json:29-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L29-L33). Search capabilities span client-side search engines and server integrations for Algolia, Flexsearch, Mixedbread, and Orama Cloud [packages/core/package.json:66-80](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L66-L80). Sources: [packages/core/package.json:1-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json#L1-L97) ### Shared Utilities and Workspace Workspace Dependencies Workspace configuration and tooling rely on private shared packages such as `shared` (`packages/shared`), which coordinates utility libraries and CLI dependencies across builds [packages/shared/package.json:1-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/package.json#L1-L15). > [!NOTE] > The `shared` package is marked as `"private": true` and uses ES module imports, depending on `fuma-cli` and `tinyglobby` for file globbing and command execution during workspace operations. Sources: [packages/shared/package.json:1-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/package.json#L1-L8) ## User Interface Packages ### Radix UI and Base UI Packages Fumadocs provides two distinct UI implementation packages for its presentation layer: `fumadocs-ui` (`packages/radix-ui`), which serves as the Radix UI version of Fumadocs UI under version `16.10.2`, and `@fumadocs/base-ui` (`packages/base-ui`), which implements the Base UI version under the same version [packages/radix-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L1-L4), [packages/base-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L1-L4). Both packages share identical public export paths for components, layouts, contexts, and providers, but differ in their underlying primitive dependencies. The Radix UI implementation relies on specific `@radix-ui/react-*` primitive packages for accessibility and state management, whereas the Base UI variant depends on `@base-ui/react` for its unstyled component primitives [packages/radix-ui/package.json:131-154](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L131-L154), [packages/base-ui/package.json:127-141](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L127-L141). Sources: [packages/radix-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L1-L4), [packages/base-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L1-L4), [packages/radix-ui/package.json:131-154](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L131-L154), [packages/base-ui/package.json:127-141](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L127-L141)] ### Component Exports and Framework Providers Both UI packages export extensive sets of component entrypoints, framework providers, and layout slots. The provider entrypoints support multiple frontend architectures, including Next.js, React Router, TanStack, and Waku [packages/radix-ui/package.json:104-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L104-L108), [packages/base-ui/package.json:102-106](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L102-L106). | Export Path | Target File (`dist/`) | Description | | :--- | :--- | :--- | | `./provider/base` | `./dist/provider/base.js` | Base UI/Radix provider implementation | | `./provider/next` | `./dist/provider/next.js` | Next.js framework provider integration | | `./provider/react-router` | `./dist/provider/react-router.js` | React Router framework provider | | `./provider/tanstack` | `./dist/provider/tanstack.js` | TanStack framework provider | | `./provider/waku` | `./dist/provider/waku.js` | Waku framework provider integration | Sources: [packages/radix-ui/package.json:104-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L104-L108), [packages/base-ui/package.json:102-106](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L102-L106)] > [!WARNING] > While `fumadocs-ui` includes legacy compatibility exports (`./legacy/layout` and `./legacy/sidebar`) alongside standard UI elements, `@fumadocs/base-ui` omits these legacy paths entirely in favor of its modern layout and slot structure [packages/radix-ui/package.json:94-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L94-L95), [packages/base-ui/package.json:18-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L18-L114). Sources: [packages/radix-ui/package.json:94-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L94-L95), [packages/base-ui/package.json:18-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L18-L114)] ## Content Processing and Schema Bundling ### Content Collection Schema Configuration The `@fumadocs/content` package acts as the content adapter for Fumadocs, integrating with `fuma-content` and standard schema specifications via `@standard-schema/spec` [packages/content/package.json:2-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/package.json#L2-L33). It configures MDX collections and metadata data collections through specialized builder functions such as `docsMdxCollection` and `docsCollection` [packages/content/src/index.ts:16-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L53). | Function / Class | Parameter / Return Type | Purpose | | :--- | :--- | :--- | | `docsMdxCollection` | `DocsMDXCollectionConfig` | Creates an MDX collection wrapping `mdxCollection` with preset options and remark include plugins [packages/content/src/index.ts:16-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L33). | | `docsCollection` | `DocsCollectionConfig` | Returns an object containing `index`, `meta`, and `doc` collection handles [packages/content/src/index.ts:44-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L44-L53). | | `DocsCollection` | Extends `Collection` | Subclass that registers code generators via `onEmit.pipe` to output store bindings [packages/content/src/index.ts:55-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L55-L70). | Sources: [packages/content/src/index.ts:16-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L16-L70)] > [!NOTE] > The `docsMdxCollection` utility dynamically evaluates option configurations (whether provided as a static object or an asynchronous factory function) and injects the `remarkInclude` plugin into the MDX bundler preset [packages/content/src/index.ts:24-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L24-L31). Sources: [packages/content/src/index.ts:24-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L24-L31)] ### MDX Transformations and Bundler Integration The `fumadocs-mdx` package (`packages/mdx/package.json`) provides the built-in content source and bundler integrations across multiple target environments and build systems [packages/mdx/package.json:2-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L2-L45). It exposes explicit subpath exports for Node, Next.js, Vite, Bun, Rolldown, and Webpack loaders and plugins [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44). | Export Subpath | Target File (`dist/`) | Purpose | | :--- | :--- | :--- | | `.` | `./dist/index.js` | Main entry point | | `./bin` | `./dist/bin.js` | CLI binary execution entry | | `./bun` | `./dist/bun/index.js` | Bun runtime integration | | `./config` | `./dist/config/index.js` | Configuration loader helpers | | `./next` | `./dist/next/index.js` | Next.js source integration | | `./node` | `./dist/node/index.js` | Node.js source bindings | | `./node/loader` | `./dist/node/loader.js` | Node module loader | | `./rolldown` | `./dist/rolldown/index.js` | Rolldown bundler plugin | | `./vite` | `./dist/vite/index.js` | Vite bundler plugin | | `./webpack/mdx` | `./dist/webpack/mdx.js` | Webpack MDX loader | | `./webpack/meta` | `./dist/webpack/meta.js` | Webpack meta loader | Sources: [packages/mdx/package.json:24-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L24-L44)] > [!WARNING] > [Bundler plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/bundler-plugins) and loaders such as `rolldown`, `vite`, and `webpack` are declared as optional peer dependencies alongside `next` and `mdast-util-directive`, allowing consumer projects to install only the toolchain integrations they require [packages/mdx/package.json:96-132](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L96-L132). Sources: [packages/mdx/package.json:96-132](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json#L96-L132)] ## API Specification Tooling ### OpenAPI and AsyncAPI Processing Packages The API specification ecosystem in Fumadocs is powered by three specialized packages: `@fumadocs/api-docs` (`packages/api-docs/package.json`), `fumadocs-openapi` (`packages/openapi/package.json`), and `@fumadocs/asyncapi` (`packages/asyncapi/package.json`) [packages/api-docs/package.json:2-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L2-L45), [packages/openapi/package.json:2-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L2-L37), [packages/asyncapi/package.json:2-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json#L2-L25). These packages supply shared utility modules, server bindings, request code generators, and UI presentation components for machine-readable API specifications. | Package Name | Version | Description | Key Subpath Exports | | :--- | :--- | :--- | :--- | | `@fumadocs/api-docs` | `0.0.2` | Shared utils for API docs generation | `./schema`, `./schema/bundle`, `./schema/dereference`, `./components/schema` [packages/api-docs/package.json:2-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L2-L38) | | `fumadocs-openapi` | `11.0.2` | Generate MDX docs for your OpenAPI spec | `.`, `./i18n`, `./scalar`, `./server`, `./ui`, `./requests/generators/all` [packages/openapi/package.json:2-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L2-L36) | | `@fumadocs/asyncapi` | `0.0.2` | Generate docs for your AsyncAPI spec | `.`, `./i18n`, `./server`, `./ui` [packages/asyncapi/package.json:2-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json#L2-L24) | Sources: [packages/api-docs/package.json:2-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L2-L38), [packages/openapi/package.json:2-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L2-L36), [packages/asyncapi/package.json:2-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json#L2-L24)] > [!NOTE] > `@fumadocs/api-docs` bundles and inlines critical JSON Schema processing tools such as `@apidevtools/json-schema-ref-parser`, `@fastify/deepmerge`, and `ajv` directly within its distribution configuration [packages/api-docs/package.json:97-104](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L97-L104). Sources: [packages/api-docs/package.json:97-104](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L97-L104)] ### Request Generators and Code Generation Modules The `fumadocs-openapi` package exposes modular request code generators under its `./requests/generators/*` export paths, enabling automatic generation of client request snippets across multiple target languages [packages/openapi/package.json:22-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L22-L29). | Export Subpath | Target File (`dist/`) | Purpose | | :--- | :--- | :--- | | `./requests/generators` | `./dist/requests/generators/index.js` | Main generators dispatcher entry point [packages/openapi/package.json:22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L22) | | `./requests/generators/all` | `./dist/requests/generators/all.js` | Bundle aggregator for all supported languages [packages/openapi/package.json:23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L23) | | `./requests/generators/csharp` | `./dist/requests/generators/csharp.js` | C# HTTP request snippet generator [packages/openapi/package.json:24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L24) | | `./requests/generators/curl` | `./dist/requests/generators/curl.js` | cURL command-line snippet generator [packages/openapi/package.json:25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L25) | | `./requests/generators/go` | `./dist/requests/generators/go.js` | Go `net/http` request generator [packages/openapi/package.json:26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L26) | | `./requests/generators/java` | `./dist/requests/generators/java.js` | Java HTTP request generator [packages/openapi/package.json:27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L27) | | `./requests/generators/javascript` | `./dist/requests/generators/javascript.js` | JavaScript `fetch` snippet generator [packages/openapi/package.json:28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L28) | | `./requests/generators/python` | `./dist/requests/generators/python.js` | Python `requests` snippet generator [packages/openapi/package.json:29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L29) | Sources: [packages/openapi/package.json:22-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L22-L29)] > [!WARNING] > Optional peer dependencies such as `@scalar/api-client-react` and `json-schema-typed` must be explicitly installed by consuming applications when utilizing interactive Scalar API playground components or strict schema typing [packages/openapi/package.json:79-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L79-L98). Sources: [packages/openapi/package.json:79-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json#L79-L98)] ## Language Analysis and Code Generation ### TypeScript and Twoslash Integrations The workspace provides dedicated tooling for TypeScript code analysis, interactive type annotations, and documentation generation through `fumadocs-typescript`, `fumadocs-twoslash`, and `fumadocs-docgen`. These packages integrate syntax analysis, tree transformations, and build-time code transformations. | Package Name | Main Entry Point (`dist/`) | Primary Export Subpaths | Description | | :--- | :--- | :--- | :--- | | `fumadocs-twoslash` | `./dist/index.js` [packages/twoslash/package.json:18-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L18-L18) | `./twoslash.css`, `/.`, `./ui`, `./cache-fs` [packages/twoslash/package.json:21-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L21-L33) | TypeScript Twoslash integration with Shiki and UI popover support [packages/twoslash/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L2-L4), [packages/twoslash/package.json:46-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L46-L52) | | `fumadocs-typescript` | `./dist/index.js` [packages/typescript/package.json:17-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L17-L17) | `.`, `./ui` [packages/typescript/package.json:20-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L20-L27) | TypeScript code intelligence and AST utilities via `ts-morph` [packages/typescript/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L2-L4), [packages/typescript/package.json:46-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L46-L46) | | `fumadocs-docgen` | `./dist/index.js` [packages/doc-gen/package.json:19-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L19-L19) | `.`, `./remark-ts2js` [packages/doc-gen/package.json:22-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L22-L29) | Remark plugins and utilities including TypeScript-to-JavaScript code transformation [packages/doc-gen/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L2-L4), [packages/doc-gen/package.json:26-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L26-L29) | | `@fumadocs/language` | Not applicable (exports individual translation files) [packages/language/package.json:17-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L17-L21) | `./zh-cn`, `./zh-tw`, `./package.json` [packages/language/package.json:18-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L18-L20) | Common localized language packs and integration metadata for Fumadocs packages [packages/language/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L2-L4), [packages/language/package.json:17-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L17-L21) | Sources: [packages/twoslash/package.json:2-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L2-L34), [packages/typescript/package.json:2-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L2-L28), [packages/doc-gen/package.json:2-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L2-L30), [packages/language/package.json:2-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L2-L21)] > [!WARNING] > `@fumadocs/language` declares peer dependencies on several workspace API and story components (`@fumadocs/api-docs`, `@fumadocs/asyncapi`, `@fumadocs/story`, `fumadocs-core`, `fumadocs-openapi`, `fumadocs-ui`) marked as optional, meaning consuming projects must provide the specific packages corresponding to the desired localized documentation tools [packages/language/package.json:43-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L43-L70). Sources: [packages/language/package.json:43-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/package.json#L43-L70)] ### Transformation Dependencies and Syntax Processing Code analysis modules rely on syntax transformers and AST parsers to manipulate Markdown and code structures. `fumadocs-typescript` integrates `ts-morph` alongside `estree-util-value-to-estree`, `hast-util-to-estree`, and `hast-util-to-jsx-runtime` [packages/typescript/package.json:39-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L39-L49). Similarly, `fumadocs-docgen` leverages `oxc-transform` and `zod` schema parsing to process and convert code snippets [packages/doc-gen/package.json:41-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L41-L50). > [!TIP] > When configuring `fumadocs-twoslash`, consumers can import cache layers via the `./cache-fs` export path alongside `@shikijs/twoslash` and `twoslash` dependencies to persist type check results across builds [packages/twoslash/package.json:30-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L30-L33), [packages/twoslash/package.json:47-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L47-L47), [packages/twoslash/package.json:52-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L52-L52). Sources: [packages/twoslash/package.json:30-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L30-L33), [packages/twoslash/package.json:47-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L47-L47), [packages/twoslash/package.json:52-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/package.json#L52-L52), [packages/typescript/package.json:39-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/package.json#L39-L49), [packages/doc-gen/package.json:41-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json#L41-L50)] ## Python Tooling and Components ### Fumapy Core Package Configuration The `fumapy` Python library (`fumadocs-python`) extracts API documentation from source code and docstrings, serving as the back-end extraction engine for Fumadocs [packages/python/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json#L2-L4), [packages/python/pyproject.toml:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L2-L4). Managed via Hatchling as its build-backend, it requires Python 3.10 or newer and depends on `griffe` and `griffe_typingdoc` to inspect Python code structures [packages/python/pyproject.toml:7-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L7-L8), [packages/python/pyproject.toml:13-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L13-L15). The command-line script entrypoint `fumapy-generate` points directly to the `generate` function inside the package [packages/python/pyproject.toml:10-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L10-L11). Sources: [packages/python/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json#L2-L4), [packages/python/pyproject.toml:2-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L2-L15)] > [!NOTE] > `fumapy` relies strictly on `griffe` (versions `>=1.13.0, <2.0.0`) and `griffe_typingdoc` (versions `>=0.2.8, <1.0.0`) for static analysis and docstring typing support [packages/python/pyproject.toml:8-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L8-L8). Sources: [packages/python/pyproject.toml:8-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L8-L8)] ### Module and Type Models The `fumapy.mksource` subpackage exports core parsing helpers and typed model structures that define how Python symbols are represented [packages/python/fumapy/mksource/__init__.py:1-9](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/__init__.py#L1-9). The models utilize TypedDict definitions to represent modules, classes, functions, parameters, attributes, and docstring sections [packages/python/fumapy/mksource/models.py:6-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/models.py#L6-60). | Model | Key Fields | Description | | :--- | :--- | :--- | | `Module` | `name`, `path`, `filepath`, `description`, `docstring`, `attributes`, `modules`, `classes`, `functions`, `version` | Represents a parsed Python module container holding nested modules, classes, and functions. | | `Class` | `name`, `path`, `description`, `parameters`, `attributes`, `docstring`, `functions`, `source` | Represents a Python class declaration including its source string and member functions. | | `Function` | `name`, `path`, `signature`, `description`, `parameters`, `returns`, `docstring`, `source` | Represents a function or method signature, return annotations, and source code. | | `Parameter` | `name`, `annotation`, `description`, `value` | Describes an individual function parameter or class argument with type annotations and defaults. | | `Attribute` | `name`, `annotation`, `description`, `value` | Captures class or module-level attributes and field assignments. | | `DocstringSection` | `kind`, `value` | Represents structural sections parsed out of docstrings. | Sources: [packages/python/fumapy/mksource/__init__.py:1-9](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/__init__.py#L1-L9), [packages/python/fumapy/mksource/models.py:6-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/models.py#L6-L60)] ### React Presentation Components The front-end package `fumadocs-python` exposes UI presentation components under its `./components` export path to render Python API documentation [packages/python/package.json:28-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json#L28-31), [packages/python/src/components/index.tsx:25-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L25-133). These components use Tailwind CSS, class-variance-authority, and Fumadocs UI primitives to display code symbols, badges, parameters, and collapsible source blocks. | Component | Props | Purpose | | :--- | :--- | :--- | | `PyFunction` | `name`, `type`, `children` | Renders a function symbol card with a specialized `func` badge and type signature [packages/python/src/components/index.tsx:25-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L25-40). | | `PyAttribute` | `name`, `type`, `value`, `children` | Displays an attribute card featuring an `attribute` badge, type, and default value [packages/python/src/components/index.tsx:42-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L42-69). | | `PyParameter` | `name`, `type`, `value`, `children` | Formats function parameters inside a secondary container with a `param` badge [packages/python/src/components/index.tsx:71-101](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L71-101). | | `PySourceCode` | `children` | Wraps raw source code blocks in a collapsible element with a toggle trigger [packages/python/src/components/index.tsx:103-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L103-121). | | `PyFunctionReturn` | `type`, `children` | Presents function return types and descriptions within a structured box [packages/python/src/components/index.tsx:123-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L123-133). | Sources: [packages/python/package.json:28-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json#L28-L31), [packages/python/src/components/index.tsx:25-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L25-L133)] ## Scaffolding and Authoring Integrations ### Project Scaffolding and Preview CLI The package `create-fumadocs-app` initializes and scaffolds new documentation sites, relying on dependency version tracking managed by `create-fumadocs-versions` [packages/create-app/package.json:2-6](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json#L2-6), [packages/create-app-versions/package.json:2-5](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app-versions/package.json#L2-5). Concurrently, `fumadocs-preview` provides an opinionated framework for fast content previews using Waku and Hono [packages/preview/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L2-4), [packages/preview/package.json:29-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json#L29-32), [packages/preview/package.json:43-65](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f560770 ## Related - [Overview](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/overview) - [Quick Start](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/getting-started/quick-start) --- ## Technical docs: Flexsearch Query Regex Building URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/how-it-works/flexsearch-query-regex-building
Relevant source files The following files were used as context for generating this wiki page: - [packages/core/src/search/flexsearch.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts) - [packages/core/src/search/flexsearch/utils.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts) - [packages/core/src/search/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts)
## Overview ### Introduction The `flexsearchI18n` to `buildRegexFromQuery` execution flow handles multi-language document searching and result highlighting in Fumadocs. When a user submits a search query with internationalization (i18n) enabled, the request is routed through language-specific FlexSearch document indices, executed against the search engine, and post-processed with content highlighters that convert terms into regular expressions. This pipeline ensures that search results respect locale boundaries and feature appropriately highlighted matched terms. Sources: [packages/core/src/search/flexsearch.ts:72-129](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L72-L129), [packages/core/src/search/flexsearch/utils.ts:7-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L7-L68), [packages/core/src/search/index.ts:36-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L43) ## Execution Flow ### Step 1: flexsearchI18n The execution begins when `flexsearchI18n` is invoked with `I18nOptions`. This function acts as the public entrypoint for setting up an internationalized search endpoint. It wraps the core `serverI18n` implementation inside an endpoint creator and returns a `SearchAPI` interface. Sources: [packages/core/src/search/flexsearch.ts:135-137](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L135-L137) ### Step 2: serverI18n `serverI18n` takes the i18n configuration options and initializes search servers for each locale. It defines the `export` and `search` handlers. When a `search` request arrives, it resolves the appropriate language server using `searchOptions.locale` or falls back to `options.i18n.defaultLanguage`. If a matching language handler is found, it delegates the query to that specific server instance. Sources: [packages/core/src/search/flexsearch.ts:72-129](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L72-L129) ### Step 3: initSearchServers Inside `serverI18n`, the asynchronous `initSearchServers` function groups the provided document indexes by their locale. If `inputIndexes` is provided as an asynchronous function, it awaits the result. It then iterates over the grouped indexes, applies any locale-specific overrides (such as CJK character encoding options), and instantiates a standard single-language `server` for each locale, storing them in a `Map`. Sources: [packages/core/src/search/flexsearch.ts:75-105](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L75-L105) ### Step 4: server The single-language `server` function manages the FlexSearch document index for a specific locale. It initializes the search index via `createDocument`, populates it with documents, and exposes `export` and `search` methods. When `search` is called, it awaits the index initialization promise and passes the query and options to the search utility. Sources: [packages/core/src/search/flexsearch.ts:41-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L41-L70) ### Step 5: search The `search` utility function in `flexsearch/utils.ts` executes `index.searchAsync()` against the FlexSearch document store. If results are returned, it invokes `createContentHighlighter(query)` to prepare highlighters. It then groups matching sections by page ID, builds formatted results including page metadata, and highlights matching content markdown before returning the final sorted results array. Sources: [packages/core/src/search/flexsearch/utils.ts:7-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L7-L68) ### Step 6: createContentHighlighter `createContentHighlighter` accepts the search query (or a prebuilt RegExp) and returns highlighting utilities. If a string query is passed, it delegates immediately to `buildRegexFromQuery` to compile the search terms into a case-insensitive regular expression. Sources: [packages/core/src/search/index.ts:47-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L47-L49) ### Step 7: buildRegexFromQuery `buildRegexFromQuery` takes the raw query string, trims whitespace, and splits it into unique terms by whitespace. It escapes any special regular expression characters in each term using `escapeRegExp`, joins them with the alternation operator (`|`), and returns a compiled global, case-insensitive `RegExp` object (or `null` if the query is empty). Sources: [packages/core/src/search/index.ts:36-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L43) ## Architecture Diagrams ### Sequence Diagram ```mermaid sequenceDiagram participant Client participant FlexsearchI18n as flexsearchI18n (flexsearch.ts) participant ServerI18n as serverI18n (flexsearch.ts) participant InitServers as initSearchServers (flexsearch.ts) participant Server as server (flexsearch.ts) participant SearchUtil as search (flexsearch/utils.ts) participant Highlighter as createContentHighlighter (index.ts) participant RegexBuilder as buildRegexFromQuery (index.ts) Client->>FlexsearchI18n: flexsearchI18n(options) FlexsearchI18n->>ServerI18n: serverI18n(options) Note over ServerI18n,InitServers: Search request triggers server initialization ServerI18n->>InitServers: initSearchServers() InitServers->>Server: server(localeOptions) Client->>ServerI18n: search(query, searchOptions) ServerI18n->>Server: search(query, searchOptions) Server->>SearchUtil: search(index, query, tag, limit) SearchUtil->>Highlighter: createContentHighlighter(query) Highlighter->>RegexBuilder: buildRegexFromQuery(query) RegexBuilder-->>Highlighter: RegExp Highlighter-->>SearchUtil: highlighter instance SearchUtil-->>Server: SortedResult[] Server-->>ServerI18n: SortedResult[] ServerI18n-->>Client: SortedResult[] ``` Sources: [packages/core/src/search/flexsearch.ts:41-137](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L41-L137), [packages/core/src/search/flexsearch/utils.ts:7-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L7-L68), [packages/core/src/search/index.ts:36-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L49) ### Flowchart ```mermaid flowchart TD A[flexsearchI18n] --> B[serverI18n] B --> C[initSearchServers] C -->|Group by locale & override| D[server] D -->|Execute search| E[search util] E -->|Create highlighter| F[createContentHighlighter] F -->|Parse query string| G[buildRegexFromQuery] G -->|Valid terms?| H{Yes / No} H -->|Yes| I[Return RegExp] H -->|No| J[Return null] I --> K[Highlight Markdown / Text] J --> K K --> L[Return Sorted Results] ``` Sources: [packages/core/src/search/flexsearch.ts:41-137](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L41-L137), [packages/core/src/search/flexsearch/utils.ts:7-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L7-L68), [packages/core/src/search/index.ts:36-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L36-L49) ## Key Observations - **Cross-Module Boundaries:** The flow bridges higher-level i18n server orchestration (`flexsearch.ts`), low-level FlexSearch execution and document grouping (`flexsearch/utils.ts`), and text/Markdown parsing utilities (`index.ts`). - **Locale Resolution and Fallback:** If a requested locale is missing during a search query, `serverI18n` gracefully falls back to `options.i18n.defaultLanguage`, or returns an empty array if no matching server handler exists. - **Robust Query Normalization:** `buildRegexFromQuery` automatically filters out empty terms, deduplicates search keywords via `Set`, and escapes regular expression special characters to prevent syntax crashes on malformed queries. Sources: [packages/core/src/search/flexsearch.ts:121-127](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L121-L127), [packages/core/src/search/flexsearch/utils.ts:7-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L7-L24), [packages/core/src/search/index.ts:32-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/index.ts#L32-L43) --- ## Technical docs: Source Loader URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader
Relevant source files The following files were used as context for generating this wiki page: - [packages/preview/src/lib/source/storage.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/storage.ts) - [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts) - [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts) - [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/content-collections/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts) - [packages/content/src/runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/mdx/src/loaders/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts) - [packages/core/src/source/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts) - [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx) - [packages/preview/src/lib/source/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/index.ts) - [packages/local-md/src/storage.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts) - [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts) - [packages/mdx/src/webpack/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts) - [packages/core/src/source/storage/content.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts) - [packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts) - [packages/sanity/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/openapi/src/utils/document/load.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/document/load.ts) - [packages/core/src/source/client/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx) - [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts) - [packages/mdx/src/loaders/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts) - [packages/obsidian/src/build-storage.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/build-storage.ts) - [packages/core/src/source/source.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts) - [packages/core/src/source/plugins/slugs.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts) - [packages/python/fumapy/mksource/__init__.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/__init__.py) - [packages/story/src/webpack/story.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/webpack/story.ts) - [packages/mdx/src/core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts) - [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts)
## Overview Fumadocs source loaders ingest, normalize, and index document collections from diverse sources like local disk storage, Content Collections, and remote OpenAPI or AsyncAPI specs into a unified virtual file system. They expose public contracts and virtual file definitions via `source` and `StaticSource`, mapping files to typed page and metadata objects. Sources: [packages/core/src/source/source.ts:1-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L1-L114), [packages/core/src/source/storage/content.ts:1-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L1-L42) The core loader pipeline parses frontmatter, handles internationalization directories or extension codes, applies loader plugins for slugs and builds hierarchical page trees and search indices. Sources: [packages/core/src/source/loader.ts:268-315](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L268-L315), [packages/core/src/source/storage/content.ts:50-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L50-L126), [packages/core/src/source/plugins/slugs.ts:15-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts#L15-L42) Through dynamic loaders and client-side deserialization hooks, Fumadocs supports runtime revalidation, hot reloading, and preloaded remote document integration. Sources: [packages/core/src/source/dynamic.ts:27-119](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L27-L119), [packages/core/src/source/client/index.tsx:14-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L14-L60), [packages/local-md/src/index.ts:84-208](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L84-L208) ## Unified source interface and contracts ### Core data structures and virtual file contracts Fumadocs source loaders rely on a shared type architecture defined by `SourceUnion`, distinguishing between `StaticSource` and `DynamicSource` objects via guard functions `isStaticSource` and `isDynamicSource`. Static sources maintain an array of `VirtualFile` items directly, whereas dynamic sources supply an asynchronous or synchronous builder function `files: () => Awaitable[]>` alongside an optional `configure` hook accepting a `DynamicLoader`. Sources: [packages/core/src/source/source.ts:5-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L5-L21), [packages/core/src/source/source.ts:172-178](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L172-L178) Every virtual file extends `BaseVirtualFile`, holding a virtualized relative path and an optional absolute path on disk. Depending on its `type` discriminant, a file resolves to either a `VirtualPage` carrying `slugs` and typed `pageData`, or a `VirtualMeta` carrying typed `metaData`. Sources: [packages/core/src/source/source.ts:48-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L48-L78) | Property / Type | Field Type | Purpose & Description | | :--- | :--- | :--- | | `path` | `string` | Virtualized path relative to the content directory (e.g. `docs/page.mdx`). | | `absolutePath` | `string` (optional) | Absolute path of the underlying file on disk. | | `type` | `'page' \| 'meta'` | Discriminant property identifying whether the virtual file is a page or metadata file. | | `slugs` | `string[]` (optional) | Explicit route segments assigned to a virtual page. | | `data` | `PageData \| MetaData` | Payload containing frontmatter attributes, titles, icons, or navigation controls. | Sources: [packages/core/src/source/source.ts:52-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L52-L78) > [!NOTE] > The `multiple` helper utility is deprecated in favor of passing a record of source objects directly to the main `loader()` function, which automatically scopes namespaces and injects type tags. > Sources: [packages/core/src/source/source.ts:80-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L80-L82) ### Metadata schemas and builder utilities The base metadata structures define standard properties supported across documentation nodes. `MetaData` configures folder navigation and display parameters such as `icon`, `title`, `root`, `pages`, `pagesIndex`, `defaultOpen`, `collapsible`, and `description`. `PageData` configures individual document attributes including `icon`, `title`, `description`, and `structuredData` (which accepts search index payloads or asynchronous generators). Sources: [packages/core/src/source/source.ts:28-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L28-L46) ```typescript export function source(config: { pages: VirtualPage[]; metas: VirtualMeta[]; }): StaticSource<{ pageData: Page; metaData: Meta; }> { return { files: [...config.pages, ...config.metas], }; } interface SourceUpdater { files: ( fn: (files: VirtualFile[]) => (VirtualPage | VirtualMeta)[], ) => SourceUpdater<{ pageData: Page; metaData: Meta; }>; page: ( fn: (page: VirtualPage) => VirtualPage, ) => SourceUpdater<{ pageData: V; metaData: Config['metaData']; }>; meta: ( fn: (meta: VirtualMeta) => VirtualMeta, ) => SourceUpdater<{ pageData: Config['pageData']; metaData: V; }>; build: () => StaticSource; } /** * update a source object in-place. */ export function update( source: StaticSource, ): SourceUpdater { return { files(fn) { source.files = fn(source.files); return this as SourceUpdater; }, page(fn) { for (let i = 0; i < source.files.length; i++) { const file = source.files[i]; if (file.type === 'page') source.files[i] = fn(file); } return this as SourceUpdater; }, meta(fn) { for (let i = 0; i < source.files.length; i++) { const file = source.files[i]; if (file.type === 'meta') source.files[i] = fn(file); } return this as SourceUpdater; }, build() { return source; }, }; } ``` Sources: [packages/core/src/source/source.ts:104-170](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L104-L170) ### External adapters and runtime transformation External integrations bridge third-party content providers into the standard Fumadocs source contract. The [Content Collections Adapter](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/content-collections-adapter) maps `allDocs` and `allMetas` arrays into `VirtualPage` and `VirtualMeta` structures via `createMDXSource`, binding `_meta.filePath` directly to file paths. Sources: [packages/content-collections/src/index.ts:4-35](https://github.com/packages/content-collections/src/index.ts#L4-L35) Similarly, runtime content stores convert compiled MDX collections and metadata stores into standard `StaticSource` objects through `toFumadocsSource` and `docsStore`. Frontmatter properties are merged directly into page data objects alongside absolute path tracking. Sources: [packages/content/src/runtime.ts:12-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L12-L56) > [!WARNING] > When integrating custom runtime stores, ensure frontmatter properties do not overwrite core `VirtualPage` discriminatory fields (`type`, `path`, `absolutePath`) during object spreading. > Sources: [packages/content/src/runtime.ts:23-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L23-L32) ## In-memory filesystem and content storage ### Storage construction and plugin transformation The `createContentStorageBuilder` function transforms raw static or multi-namespace content inputs into an indexed virtual file system. When internationalization is enabled, parser routines strip locale codes from file paths based on either directory structures or filename extensions, mapping entries into a shared `fileMap` indexed by target language or an `EmptyLang` symbol. Sources: [packages/core/src/source/storage/content.ts:43-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L43-L93) ```typescript export function createContentStorageBuilder(loaderConfig: ResolvedLoaderConfig) { const { input, plugins, i18n } = loaderConfig; let parser: (normalizedPath: string) => [string, (string | string[])?]; if (!i18n) { parser = (path) => [path]; } else if (i18n.parser === 'dir') { const langSet = new Set(i18n.languages); parser = (path) => { const [locale, ...segs] = path.split('/'); if (!locale || segs.length === 0) return [path]; if (langSet.has(locale)) return [segs.join('/'), locale]; if (locale === '$') return [segs.join('/'), i18n.languages]; return [path]; }; } else { const langSet = new Set(i18n.languages); parser = (path) => { const segs = path.split('/'); const base = segs.pop(); if (!base) return [path]; const parts = base.split('.'); if (parts.length < 3) return [path]; const [locale] = parts.splice(parts.length - 2, 1); segs.push(parts.join('.')); if (langSet.has(locale)) return [segs.join('/'), locale]; if (locale === '$') return [segs.join('/'), i18n.languages]; return [path]; }; } ``` Sources: [packages/core/src/source/storage/content.ts:50-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L50-L87) During the scanning phase, input files are categorized as either page or metadata files. Each file receives a normalized path, format descriptor, source type, and underlying data payload before being inserted into the storage map. Sources: [packages/core/src/source/storage/content.ts:94-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L94-L126) | Storage File Type | Format Discriminant | Required Properties | Optional Properties | | :--- | :--- | :--- | :--- | | `ContentStoragePageFile` | `'page'` | `format`, `path`, `slugs`, `data` | `type`, `absolutePath` | | `ContentStorageMetaFile` | `'meta'` | `format`, `path`, `data` | `type`, `absolutePath` | Sources: [packages/core/src/source/storage/content.ts:17-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L17-L41) > [!NOTE] > When evaluating language parsers, if a file path segment equals `$`, the parser maps the file across all configured internationalization languages simultaneously. > Sources: [packages/core/src/source/storage/content.ts:64-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L64-L83) Once files are indexed within `fileMap`, `makeStorage` instantiates a `FileSystem` instance for a given locale. It populates the filesystem with corresponding storage entries and executes any registered plugin storage transformation hooks. Sources: [packages/core/src/source/storage/content.ts:134-146](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L134-L146) ```typescript function makeStorage(locale: string | typeof EmptyLang, inherit?: ContentStorage) { const storage = new FileSystem(inherit) as ContentStorage; for (const [storageKey, file] of fileMap.get(locale) ?? []) { storage.write(storageKey, file); } const context = { storage }; for (const plugin of plugins) { plugin.transformStorage?.(context); } return storage; } ``` Sources: [packages/core/src/source/storage/content.ts:134-146](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts#L134-L146) ## Dynamic loader resolution and caching ```mermaid sequenceDiagram participant dynamicLoader as dynamic.ts participant resolveSources as dynamic.ts participant resolveSource as dynamic.ts participant isStaticSource as source.ts dynamicLoader->>resolveSources: get() resolveSources->>resolveSource: map input items resolveSource->>isStaticSource: check static vs dynamic ``` Sources: [packages/core/src/source/dynamic.ts:52-79](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L52-L79), [packages/core/src/source/source.ts:172-174](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/source.ts#L172-L174) The `dynamicLoader` factory handles runtime content resolution, source configuration, and memoization for dynamic and static documentation sources. During initialization, `configureSources` iterates over input sources and executes `v.configure?.(dynamicLoader)` when an input matches dynamic source criteria. Sources: [packages/core/src/source/dynamic.ts:40-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L40-L50), [packages/core/src/source/dynamic.ts:116-116](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L116-L116) The resolution pipeline follows a strict call chain: `dynamicLoader` invokes `resolveSources`, which calls `resolveSource` on each source object, delegating to `isStaticSource` for type discrimination. Sources: [packages/core/src/source/dynamic.ts:52-79](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L52-L79) ```typescript async function resolveSources(skipCache = false): Promise { if (isStaticSource(input) || isDynamicSource(input)) { return resolveSource(input, skipCache); } const entries = await Promise.all( Object.entries(input).map(async ([k, v]) => [k, await resolveSource(v, skipCache)]), ); return Object.fromEntries(entries); } ``` Sources: [packages/core/src/source/dynamic.ts:52-62](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L52-L62) > [!WARNING] > Bypassing cache via `skipCache = true` forces `resolveSource` to re-execute `v.files()` and overwrite existing entries in `sourceCache`, discarding previously memoized virtual file arrays. > Sources: [packages/core/src/source/dynamic.ts:64-79](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L64-L79) Source equality is evaluated by `isEqual`, which checks reference identity for static sources or compares key counts and strict reference equality for multi-source records. Sources: [packages/core/src/source/dynamic.ts:121-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L121-L133) ```typescript function isEqual(a: ResolvedSource, b: ResolvedSource): boolean { if (isStaticSource(a) && isStaticSource(b)) { return a === b; } if (!isStaticSource(a) && !isStaticSource(b)) { const aKeys = Object.keys(a); const bKeys = Object.keys(b); return aKeys.length === bKeys.length && aKeys.every((k) => a[k] === b[k]); } return false; } ``` Sources: [packages/core/src/source/dynamic.ts:121-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L121-L133) ## Loader configuration, plugin pipeline, and execution walkthrough ```mermaid sequenceDiagram participant dynamicLoader as dynamic.ts participant loader as loader.ts participant resolveConfig as loader.ts dynamicLoader->>loader: dynamicLoader invokes loader(resolved, options) loader->>resolveConfig: loader calls resolveConfig(source, options) resolveConfig-->>loader: returns resolved config containing plugins ``` Sources: [packages/core/src/source/dynamic.ts:90-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L90-L93), [packages/core/src/source/loader.ts:287-301](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L287-L301), [packages/core/src/source/loader.ts:474-499](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L474-L499) The execution walkthrough for building plugins and resolving configurations traces through `dynamicLoader` → `loader` → `resolveConfig`. When `dynamicLoader` computes its cache via `get()`, it invokes `loader()` with the resolved source and options. The `loader` function immediately delegates to `resolveConfig()`, which merges base settings, slugs options, icons, and plugins into a unified `ResolvedLoaderConfig`. Sources: [packages/core/src/source/dynamic.ts:27-119](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/dynamic.ts#L27-L119), [packages/core/src/source/loader.ts:287-499](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L287-L499) ```typescript export function loader( ...args: | [ LoaderOptions & { source: I; }, ] | [I, LoaderOptions] ): LoaderOutput<{ meta: GenerateMeta; page: GeneratePage; i18n: I18n; }> { const loaderConfig = args.length === 2 ? resolveConfig(args[0], args[1]) : resolveConfig(args[0].source, args[0]); ``` Sources: [packages/core/src/source/loader.ts:287-301](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L287-L301) > [!NOTE] > `resolveConfig` unpacks base loader configurations and validates internationalization parameters before content storage builder initialization. > Sources: [packages/core/src/source/loader.ts:474-479](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L474-L479) The slugs plugin (`slugsPlugin`) inspects files via `storage.getFiles()`, processing non-page items or files with pre-existing slugs. When a custom `slugFn` is absent, it identifies index files via `isIndex`, pushing them to an index queue to prevent collision conflicts between `dir/index.mdx` and `dir.mdx`. Sources: [packages/core/src/source/plugins/slugs.ts:15-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts#L15-L35) ```typescript transformStorage({ storage }) { const indexFiles: string[] = []; const taken = new Set(); for (const path of storage.getFiles()) { const file = storage.read(path); if (!file || file.format !== 'page' || file.slugs) continue; const customSlugs = slugFn?.(file); // for custom slugs function, don't handle conflicting cases like `dir/index.mdx` vs `dir.mdx` if (customSlugs === undefined && isIndex(path)) { indexFiles.push(path); continue; } file.slugs = customSlugs ?? getSlugs(path); const key = file.slugs.join('/'); if (taken.has(key)) throw new Error(`Duplicated slugs: ${key}`); taken.add(key); } ``` Sources: [packages/core/src/source/plugins/slugs.ts:22-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts#L22-L41) > [!WARNING] > Duplicate slug keys detected across storage entries trigger an immediate error throw via `if (taken.has(key)) throw new Error(...)`. > Sources: [packages/core/src/source/plugins/slugs.ts:38-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts#L38-L40) Path segregation filters out empty directory names and folder groups matching `GroupRegex` (`/^\(.+\)$/`). Any attempt to use a folder group directly inside a file name throws an error. Sources: [packages/core/src/source/plugins/slugs.ts:69-85](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts#L69-L85) ```typescript export function getSlugs(file: string): string[] { const dir = dirname(file); const name = basename(file, extname(file)); const slugs: string[] = []; for (const seg of dir.split('/')) { // filter empty names and file groups like (group_name) if (seg.length > 0 && !GroupRegex.test(seg)) slugs.push(encodeURI(seg)); } if (GroupRegex.test(name)) throw new Error(`Cannot use folder group in file names: ${file}`); if (name !== 'index') { slugs.push(encodeURI(name)); } return slugs; ``` Sources: [packages/core/src/source/plugins/slugs.ts:74-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts#L74-L90) ## Local markdown and disk storage ### File scanning and storage implementation ```mermaid graph TD subgraph Storage Flow A[glob include patterns] -->|cwd: dir| B[chunked file promises] B -->|CHUNK_SIZE: 100| C[buildFile] C -->|extname: .json| D[json meta parser] C -->|extname: .md or .mdx| E[md frontmatter parser] end ``` Sources: [packages/local-md/src/storage.ts:23-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L23-L56), [packages/local-md/src/storage.ts:110-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L110-L126) Local markdown collections are managed by `createStorage`, which scans content directories using `tinyglobby` with configurable include patterns. Discovered files are batched into chunks of 100 items (`CHUNK_SIZE`) and processed concurrently via `buildFile`. Files are discriminated by extension: `.json` files are parsed as metadata collections, while `.md` and `.mdx` files are processed for frontmatter and body content. Sources: [packages/local-md/src/storage.ts:23-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L23-L56), [packages/local-md/src/storage.ts:110-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L110-L126) ```typescript async getPages() { const files = await glob(include, { cwd: dir, }); const chunks: Promise<($Page | $Meta | undefined)[]>[] = []; for (let i = 0; i < files.length; i += CHUNK_SIZE) { const promises: Promise<$Page | $Meta | undefined>[] = []; const L = Math.min(files.length, i + CHUNK_SIZE); for (let j = i; j < L; j++) { promises.push(buildFile(files[j])); } chunks.push(Promise.all(promises)); } const pages: $Page[] = []; const metas: $Meta[] = []; for await (const chunk of chunks) { for (const item of chunk) { if (!item) continue; if ('frontmatter' in item) pages.push(item); else metas.push(item); } } return { pages, metas }; }, ``` Sources: [packages/local-md/src/storage.ts:110-138](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L110-L138) > [!WARNING] > If building a file throws an error, the catch block logs the failure to the console and deletes the corresponding absolute path entry from `filesCache`. > Sources: [packages/local-md/src/storage.ts:62-66](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L62-L66) ### Frontmatter parsing and schema validation ```typescript async function md(absolutePath: string, file: string): Promise<$Page> { const content = await fs.readFile(absolutePath, 'utf-8'); const parsed = parseFrontmatter(content); const frontmatterResult = await frontmatterSchema['~standard'].validate(parsed.data); if (frontmatterResult.issues) { const message = frontmatterResult.issues .map((issue) => (issue.path ? `${issue.path}: ${issue.message}` : issue.message)) .join('\n'); throw new Error(`invalid frontmatter in "${absolutePath}": ${message}`); } return { path: file, absolutePath, content: parsed.content, frontmatter: frontmatterResult.value, }; } ``` Sources: [packages/local-md/src/storage.ts:68-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L68-L86) Markdown and MDX files are read from disk and processed with `parseFrontmatter` to separate content from metadata headers. The extracted frontmatter object is validated against standard schemas using `frontmatterSchema['~standard'].validate()`. If validation fails, issues are mapped into a detailed multi-line error string reporting path and message specifics. Sources: [packages/local-md/src/storage.ts:68-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L68-L86) | Extension | Target Interface | Validation Schema | Parser Utility | | :--- | :--- | :--- | :--- | | `.md`, `.mdx` | `RawPage` | `frontmatterSchema` | `parseFrontmatter` | | `.json` | `RawMeta` | `metaSchema` | `JSON.parse` | Sources: [packages/local-md/src/storage.ts:10-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L10-L21), [packages/local-md/src/storage.ts:72-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L72-L97) > [!CAUTION] > Schema validation errors halt execution immediately by throwing an `Error` containing formatted validation issues for either invalid frontmatter or invalid JSON data. > Sources: [packages/local-md/src/storage.ts:73-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L73-L78), [packages/local-md/src/storage.ts:92-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts#L92-L97) ### Runtime adapters and dev server integration ```typescript export function localMd< FrontmatterSchema extends StandardSchemaV1 = typeof defaultSchemas.pageSchema, MetaSchema extends StandardSchemaV1 = typeof defaultSchemas.metaSchema, >( config: LocalMarkdownConfig, ): LocalMarkdown { const storage = createStorage(config); const compiler = createMarkdownCompiler(config); const compilerCache = new WeakMap, Promise>(); const registeredLoaders = new Set(); let cachedStaticSource: Promise< StaticSource<{ pageData: LocalMarkdownPage, never>; metaData: StandardSchemaV1.InferOutput & MetaData; }> > | null = null; async function createFiles(options?: SourceOptions) { const { metas, pages } = await storage.getPages(); const baseDir = options?.baseDir; const files: VirtualFile<{ pageData: LocalMarkdownPage, never>; metaData: StandardSchemaV1.InferOutput & MetaData; }>[] = []; for (const page of pages) { const frontmatter = page.frontmatter as PageData & { _openapi?: unknown }; files.push({ type: 'page', path: baseDir ? path.join(baseDir, page.path) : page.path, absolutePath: page.absolutePath, data: { title: frontmatter.title ?? path.basename(page.path, path.extname(page.path)), description: frontmatter.description, icon: frontmatter.icon, // for Fumadocs OpenAPI ['_openapi' as never]: frontmatter._openapi, content: page.content, frontmatter: page.frontmatter, async load() { let promise = compilerCache.get(page); if (!promise) { promise = compiler.compile({ path: page.absolutePath, value: page.content, data: { frontmatter: page.frontmatter }, }); } const res = await promise; return res.type === 'ast' ? fromAst({ tree: res.tree, filePath: res.file.path, rehypeToc: res.file.data.rehypeToc, structuredData: res.file.data.structuredData, ...config.rendererOptions, }) : fromJS({ code: res.code, filePath: res.file.path, baseUrl: pathToFileURL(res.file.path).href, structuredData: res.file.data.structuredData, }); }, }, }); } ``` Sources: [packages/local-md/src/index.ts:84-153](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L84-L153) The `localMd` function exposes `staticSource` and `dynamicSource` runtime adapters that transform raw storage entities into virtual files consumed by core loaders. Each page object provides an asynchronous `load` method that compiles content via a markdown compiler instance, utilizing `compilerCache` to memoize compilation promises per page. When connected to a development server via `devServer`, the runner watches the target directory and dispatches file invalidation events. Sources: [packages/local-md/src/index.ts:84-153](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L84-L153), [packages/local-md/src/index.ts:174-195](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L174-L195) > [!NOTE] > Calling `invalidateFile` resets `cachedStaticSource` to `null`, evicts the path from `storage`, and triggers invalidation callbacks on all registered dynamic loaders. > Sources: [packages/local-md/src/index.ts:168-173](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L168-L173) ## Client deserialization and preview runtime ### Client-side page tree consumption ```tsx export function deserializePageTree(serialized: SerializedPageTree): PageTree.Root { const root = serialized.data as PageTree.Root; visit(root, (item) => { if ('icon' in item && typeof item.icon === 'string') { item.icon = ( ); } if (typeof item.name === 'string') { item.name = ( ); } }); return root; } ``` Sources: [packages/core/src/source/client/index.tsx:14-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L14-L39) The client package handles serialized navigation trees generated by the server-side loader through `deserializePageTree`. It inspects incoming objects using `isSerializedPageTree`, verifying that `$fumadocs_loader` is set to `'page-tree'`. Once validated, `visit` traverses the tree nodes, parsing raw HTML strings for item icons and names into React span elements configured with `dangerouslySetInnerHTML`. Sources: [packages/core/src/source/client/index.tsx:5-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L5-L8), [packages/core/src/source/client/index.tsx:14-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L14-L39), [packages/core/src/source/client/index.tsx:62-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L62-L69) ```tsx export function useFumadocsLoader(serialized: V): Serialized { return useMemo(() => { const out: Record = {}; for (const k in serialized) { const v = serialized[k]; if (isSerializedPageTree(v)) { out[k] = deserializePageTree(v); } else { out[k] = v; } } return out as Serialized; }, [serialized]); } ``` Sources: [packages/core/src/source/client/index.tsx:47-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L47-L60) The `useFumadocsLoader` hook memoizes deserialization across re-renders. It iterates over the properties of the provided serialized object, converting matching page tree structures while preserving all unrelated properties in the output. Sources: [packages/core/src/source/client/index.tsx:47-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L47-L60) > [!NOTE] > `useFumadocsLoader` preserves any non-loader properties present on the input object alongside the freshly parsed page tree elements. > Sources: [packages/core/src/source/client/index.tsx:42-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L42-L46), [packages/core/src/source/client/index.tsx:54-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L54-L56) ### Preview revalidation hooks and route rendering ```typescript export const getSource = revalidable({ async create(config: ParsedAppConfig) { return loader({ source: source(await getPages(config.content)), plugins: [lucideIconsPlugin()], baseUrl: '/', }); }, }); ``` Sources: [packages/preview/src/lib/source/index.ts:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/index.ts#L7-L15) The preview application defines `getSource` via a revalidable wrapper that instantiates a content loader using `source` with local page data and the `lucideIconsPlugin`. Document paths and page image routes are managed by `getPageImage`, which appends `image.webp` segments to the URL path array. Sources: [packages/preview/src/lib/source/index.ts:7-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/index.ts#L7-L27) ```tsx export default async function DocPage({ slugs }: PageProps<'/docs/[...slugs]'>) { const config = await getConfigRuntime(); const source = await getSource(config); const page = source.getPage(slugs); const mdPreset = config.layout.presets?.md ?? 'docs'; let mdPresetComponents: MdPresetComponents; if (mdPreset === 'docs') { mdPresetComponents = { layout: await import('fumadocs-ui/layouts/docs'), page: await import('fumadocs-ui/layouts/docs/page'), }; } else { mdPresetComponents = { layout: await import('fumadocs-ui/layouts/flux'), page: await import('fumadocs-ui/layouts/flux/page'), }; } return ; } ``` Sources: [packages/preview/src/pages/...slugs.tsx:76-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L76-L96) The dynamic route component `DocPage` resolves runtime configurations and dynamic layout presets (`docs` or `flux`) before rendering document contents. During compilation, remark and rehype plugins process markdown tables, mathematics, mermaid diagrams, code blocks, and [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) data. Sources: [packages/preview/src/pages/...slugs.tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46), [packages/preview/src/pages/...slugs.tsx:76-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L76-L96) | Preset Name | Layout Import | Page Import | | :--- | :--- | :--- | | `docs` | `fumadocs-ui/layouts/docs` | `fumadocs-ui/layouts/docs/page` | | Other | `fumadocs-ui/layouts/flux` | `fumadocs-ui/layouts/flux/page` | Sources: [packages/preview/src/pages/...slugs.tsx:83-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L83-L93) > [!WARNING] > If markdown compilation encounters an error, `DocPage` catches the exception and renders a fallback error view containing the exception message and stack trace inside a code block. > Sources: [packages/preview/src/pages/[...slugs].tsx:169-194](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/[...slugs].tsx#L169-L194) ## Related - [Page Tree Generation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/page-tree-generation) - [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline) --- ## Technical docs: Page Tree Generation URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/page-tree-generation
Relevant source files The following files were used as context for generating this wiki page: - [packages/core/src/source/page-tree/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts) - [packages/radix-ui/src/components/sidebar/page-tree.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/page-tree.tsx) - [packages/base-ui/src/components/sidebar/page-tree.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/page-tree.tsx) - [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/base-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/base-ui/src/components/sidebar/tabs/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/tabs/index.tsx) - [packages/radix-ui/src/components/sidebar/tabs/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/tabs/index.tsx) - [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts) - [packages/core/src/source/plugins/status-badges.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/status-badges.tsx) - [packages/radix-ui/src/utils/use-footer-items.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts) - [packages/base-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/slots/sidebar.tsx) - [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx) - [packages/core/src/source/llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/llms.ts) - [packages/cli/src/commands/file-tree.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/file-tree.ts) - [packages/base-ui/src/utils/use-footer-items.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/utils/use-footer-items.ts) - [packages/radix-ui/src/contexts/tree.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx) - [packages/core/src/source/client/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx) - [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx) - [packages/base-ui/src/contexts/tree.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/tree.tsx) - [packages/core/src/source/page-tree/transformer-fallback.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/transformer-fallback.ts) - [packages/core/src/page-tree/utils.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts) - [packages/openapi/src/generate-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts) - [packages/core/src/breadcrumb.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/breadcrumb.tsx) - [packages/epub/src/toc-builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/src/toc-builder.ts) - [packages/openapi/src/utils/pages/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/builder.ts) - [packages/asyncapi/src/utils/pages/preset-auto.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/preset-auto.ts) - [packages/base-ui/src/components/sidebar/link-item.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/link-item.tsx) - [packages/radix-ui/src/components/sidebar/link-item.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/link-item.tsx) - [packages/radix-ui/src/layouts/shared/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/index.tsx)
## Overview Page tree generation constructs and manages the hierarchical navigation models that organize documentation content across the Fumadocs framework ecosystem. By parsing content files, resolving directory structures, and processing metadata, the builder turns raw file storage into structured node primitives including roots, folders, items, and separators. Sources: [packages/core/src/source/page-tree/builder.ts:72-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L72-L87), [packages/core/src/source/loader.ts:1-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L1-L15) ## Page Tree Data Structures ### Node Types and Primitives The core page tree architecture represents documentation structures through a set of primitive node schemas and symbols. Internal builder structures attach metadata such as `SymbolUnfinished`, `SymbolName`, and `SymbolOwner` to track ownership priority and resolve references when multiple folders claim the same node. Sources: [packages/core/src/source/page-tree/builder.ts:74-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L74-L82) The builder interface exposes path resolution and root generation capabilities through the `PageTreeBuilder` contract. ```typescript export interface PageTreeBuilder { resolveFlattenPath(name: string, format: string): string; root(id?: string, path?: string): PageTree.Root; } ``` Sources: [packages/core/src/source/page-tree/builder.ts:84-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L84-L87) Tree traversal utilities operate on nodes and roots, flattening hierarchical structures into ordered arrays of page items, locating neighboring nodes for pagination, and discovering parent containers via depth-first searches. Sources: [packages/core/src/page-tree/utils.ts:6-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L6-L19), [packages/core/src/page-tree/utils.ts:24-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L24-L33), [packages/core/src/page-tree/utils.ts:105-119](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L105-L119) ## Hierarchical Tree Builder ### File Scanning and Path Resolution The builder initializes by scanning storage instances via `createPageTreeBuilder`, mapping every file and its content format into a flattened path lookup table. The `excludePrefix` constant (`!`) identifies excluded items during tree construction, while internal symbols track state: `SymbolUnfinished` marks incomplete nodes, `SymbolName` stores display identifiers, and `SymbolOwner` records ownership objects consisting of an owner path and priority. ```typescript const excludePrefix = '!'; const SymbolUnfinished = Symbol('unfinished'); const SymbolName = Symbol('name'); const SymbolOwner = Symbol('owner'); interface Attached { [SymbolName]?: string; [SymbolUnfinished]?: boolean; [SymbolOwner]?: { owner: string; priority: number }; } ``` Sources: [packages/core/src/source/page-tree/builder.ts:72-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L72-L82) Content storages are iterated to register file paths by stripping their extensions and concatenating format extensions into `flattenPathToFullPath` mapping entries. The `resolveFlattenPath` method retrieves the full file path from a given name and format or falls back to the original name. ```typescript for (const file of storage.getFiles()) { const content = storage.read(file)!; const flattenPath = file.substring(0, file.length - extname(file).length); flattenPathToFullPath.set(flattenPath + '.' + content.format, file); } function resolveFlattenPath(name: string, format: string) { return flattenPathToFullPath.get(name + '.' + format) ?? name; } ``` Sources: [packages/core/src/source/page-tree/builder.ts:140-149](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L140-L149) ### Ownership Tracking and Transfer When multiple folders reference the same node, ownership tracking determines container assignment based on priority values. The `own` function checks if a node is unfinished, evaluates existing ownership, updates matching ownership priorities, or revokes ownership from lower-priority folders by splicing nodes out of their children lists and clearing folder index references. ```typescript function own(ownerPath: string, node: PageTree.Node & Attached, priority: number): boolean { if (node[SymbolUnfinished]) return false; const existing = node[SymbolOwner]; if (!existing) { node[SymbolOwner] = { owner: ownerPath, priority }; return true; } if (existing.owner === ownerPath) { existing.priority = Math.max(existing.priority, priority); return true; } if (existing.priority >= priority) return false; // return ownership const folder = pathToNode.get(existing.owner); if (folder && folder.type === 'folder') { if (folder.index === node) { delete folder.index; } else { const idx = folder.children.indexOf(node); if (idx !== -1) folder.children.splice(idx, 1); } } existing.owner = ownerPath; existing.priority = priority; return true; } function transferOwner(ownerPath: string, node: PageTree.Node & Attached) { const existing = node[SymbolOwner]; if (existing) existing.owner = ownerPath; } ``` Sources: [packages/core/src/source/page-tree/builder.ts:158-190](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L158-L190) > [!NOTE] > Lower priority owners attempting to claim a node already owned by a higher priority parent will have their claim rejected, returning `false` without modifying existing ownership boundaries. Sources: [packages/core/src/source/page-tree/builder.ts:169-169](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts#L169-L169) ### Fallback Transformation The fallback mechanism implemented in `transformerFallback` captures unreferenced files and directories that were not visited during standard tree building. It isolates remaining storage items and generates a secondary fallback page tree prefixed with `fallback`. ```typescript export function transformerFallback(): PageTreeTransformer { const addedFiles = new Set(); function shouldIgnore(context: PageTreeBuilderContext) { return context.custom?._fallback === true; } return { root(root) { if (shouldIgnore(this)) return root; const isolatedStorage = new FileSystem() as ContentStorage; if (addedFiles.size === this.storage.files.size) return root; for (const file of this.storage.getFiles()) { if (addedFiles.has(file)) continue; isolatedStorage.write(file, this.storage.read(file)!); } root.fallback = createPageTreeBuilder(isolatedStorage, { ...this.options, idPrefix: this.options.idPrefix ? `fallback:${this.options.idPrefix}` : 'fallback', generateFallback: false, context: { ...this.custom, _fallback: true }, }).root(); addedFiles.clear(); return root; }, file(node, file) { if (shouldIgnore(this)) return node; if (file) addedFiles.add(file); return node; }, folder(node, _dir, metaPath) { if (shouldIgnore(this)) return node; if (metaPath) addedFiles.add(metaPath); return node; }, }; } ``` Sources: [packages/core/src/source/page-tree/transformer-fallback.ts:5-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/transformer-fallback.ts#L5-L45) ## Tree Navigation and Traversal Utilities ### Depth-First Tree Visitation and Mutation The `visit` function executes a depth-first search across a page tree or node collection, invoking a visitor callback for each encountered node. The visitor callback can return `'skip'` to bypass children of the current node, `'break'` to terminate the search entirely via a thrown `VisitBreak` symbol caught internally, or a modified node object to perform in-place tree transformations. ```typescript export function visit( root: Root, visitor: ( node: T, parent?: PageTree.Root | PageTree.Folder, ) => 'skip' | 'break' | T | void, ): Root { function onNode( node: T, parent?: PageTree.Root | PageTree.Folder, ): T { const result = visitor(node, parent); switch (result) { case 'skip': return node; case 'break': throw VisitBreak; default: if (result) node = result; } if ('index' in node && node.index) { node.index = onNode(node.index, node); } if ('fallback' in node && node.fallback) { node.fallback = onNode(node.fallback, node); } if ('children' in node) { for (let i = 0; i < node.children.length; i++) { node.children[i] = onNode(node.children[i], node); } } return node; } try { return onNode(root); } catch (e) { if (e === VisitBreak) return root; throw e; } } ``` Sources: [packages/core/src/page-tree/utils.ts:176-220](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L176-L220) > [!WARNING] > Returning `'break'` from a visitor callback throws an internal `VisitBreak` symbol that is intercepted by `visit` to cleanly return the unmodified root reference, avoiding unhandled exceptions during traversal aborts. Sources: [packages/core/src/page-tree/utils.ts:168-175](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L168-L175), [packages/core/src/page-tree/utils.ts:214-219](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L214-L219) ### Path Lookup and Neighbor Resolution Path lookup and list flattening utilities transform hierarchical tree structures into linear arrays or specific ancestor trails. The `flattenTree` function iterates over nodes, extracting folder indices and nested children recursively into a flat list of page items. ```typescript export function flattenTree(nodes: PageTree.Node[]): PageTree.Item[] { const out: PageTree.Item[] = []; for (const node of nodes) { if (node.type === 'folder') { if (node.index) out.push(node.index); out.push(...flattenTree(node.children)); } else if (node.type === 'page') { out.push(node); } } return out; } ``` Sources: [packages/core/src/page-tree/utils.ts:6-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L6-L19) The `findPath` function searches for a node matching a predicate, optionally including separators in the returned path array. Breadcrumb generation leverages `searchPath` to resolve the current URL against normalized tree paths. ```typescript export function findPath( nodes: PageTree.Node[], matcher: (node: PageTree.Node) => boolean, options: { includeSeparator?: boolean; } = {}, ): PageTree.Node[] | null { const { includeSeparator = true } = options; function run(nodes: PageTree.Node[]): PageTree.Node[] | undefined { let separator: PageTree.Separator | undefined; for (const node of nodes) { if (matcher(node)) { const items: PageTree.Node[] = []; if (separator) items.push(separator); items.push(node); return items; } if (node.type === 'separator' && includeSeparator) { separator = node; continue; } if (node.type === 'folder') { const items = node.index && matcher(node.index) ? [node.index] : run(node.children); if (items) { items.unshift(node); if (separator) items.unshift(separator); return items; } } } } return run(nodes) ?? null; } ``` Sources: [packages/core/src/page-tree/utils.ts:126-166](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L126-L166) | Utility Function | Parameters | Return Type | Description | | :--- | :--- | :--- | :--- | | `flattenTree` | `nodes: PageTree.Node[]` | `PageTree.Item[]` | Flattens folders, index nodes, and pages into a single sequential list. | | `findNeighbour` | `tree: PageTree.Root`, `url: string`, `options?: { separateRoot?: boolean }` | `{ previous?: PageTree.Item, next?: PageTree.Item }` | Resolves adjacent previous and next page items for pagination controls. | | `getPageTreeRoots` | `pageTree: PageTree.Root \| PageTree.Folder` | `(PageTree.Root \| PageTree.Folder)[]` | Collects all root nodes and nested root folders. | | `getPageTreePeers` | `treeOrTrees: PageTree.Root \| Record`, `url: string` | `PageTree.Item[]` | Retrieves peer page nodes residing under the same parent container. | | `findSiblings` | `treeOrTrees: PageTree.Root \| Record`, `url: string` | `PageTree.Node[]` | Retrieves all sibling tree nodes under the same parent. | | `findParent` | `from: PageTree.Root \| PageTree.Folder`, `url: string` | `PageTree.Root \| PageTree.Folder \| undefined` | Locates the parent container of a page matched by its URL. | | `findPath` | `nodes: PageTree.Node[]`, `matcher: (node: PageTree.Node) => boolean`, `options?: { includeSeparator?: boolean }` | `PageTree.Node[] \| null` | Finds the array of nodes forming the path to a matched node. | Sources: [packages/core/src/page-tree/utils.ts:6-166](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/page-tree/utils.ts#L6-L166) ## Status Badges and Tree Transformation ### Status Badges Plugin Architecture The `statusBadgesPlugin` function returns a loader plugin named `fumadocs:status-badges` that decorates navigation items with status indicators by inspecting document frontmatter. When processing a file node, the transformer checks whether the file format is `'page'` and whether a string-typed `status` property exists within `file.data`. ```tsx export function statusBadgesPlugin( options: { renderBadge?: (status: string) => ReactNode; } = {}, ): LoaderPlugin { const { renderBadge = (status) => {status} } = options; return { name: 'fumadocs:status-badges', transformPageTree: { file(node, filePath) { if (!filePath) return node; const file = this.storage.read(filePath); if ( file?.format === 'page' && 'status' in file.data && typeof file.data.status === 'string' ) { const status = file.data.status; node.name = ( <> {node.name} {renderBadge(status)} ); (node as Item).status = status; } return node; }, }, }; ``` Sources: [packages/core/src/source/plugins/status-badges.tsx:50-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/status-badges.tsx#L50-L83) If a valid status string is located, the plugin modifies `node.name` by appending a rendered badge element alongside the original node name, and assigns the raw status string directly to `(node as Item).status`. Consumers can customize badge rendering by passing a `renderBadge` callback option; if omitted, the plugin defaults to rendering a `` element equipped with a `data-status` attribute. ```tsx const { renderBadge = (status) => {status} } = options; return { name: 'fumadocs:status-badges', transformPageTree: { file(node, filePath) { if (!filePath) return node; const file = this.storage.read(filePath); if ( file?.format === 'page' && 'status' in file.data && typeof file.data.status === 'string' ) { const status = file.data.status; node.name = ( <> {node.name} {renderBadge(status)} ); (node as Item).status = status; } ``` Sources: [packages/core/src/source/plugins/status-badges.tsx:55-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/status-badges.tsx#L55-L78) > [!NOTE] > The `statusBadgesPlugin` strictly requires `filePath` to be defined on the node and relies on `this.storage.read(filePath)` to access document frontmatter during tree transformation. Sources: [packages/core/src/source/plugins/status-badges.tsx:60-63](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/status-badges.tsx#L60-L63) ### Fallback Tree Transformation The `transformerFallback` function constructs a secondary fallback page tree builder by intercepting root, file, and folder transformation hooks. It tracks processed files in an internal `addedFiles` set and inspects the builder context via `shouldIgnore` to verify whether `context.custom?._fallback` is enabled, preventing recursive fallback generation loops. ```typescript export function transformerFallback(): PageTreeTransformer { const addedFiles = new Set(); function shouldIgnore(context: PageTreeBuilderContext) { return context.custom?._fallback === true; } return { root(root) { if (shouldIgnore(this)) return root; const isolatedStorage = new FileSystem() as ContentStorage; if (addedFiles.size === this.storage.files.size) return root; for (const file of this.storage.getFiles()) { if (addedFiles.has(file)) continue; isolatedStorage.write(file, this.storage.read(file)!); } root.fallback = createPageTreeBuilder(isolatedStorage, { ...this.options, idPrefix: this.options.idPrefix ? `fallback:${this.options.idPrefix}` : 'fallback', generateFallback: false, context: { ...this.custom, _fallback: true }, }).root(); addedFiles.clear(); return root; }, file(node, file) { if (shouldIgnore(this)) return node; if (file) addedFiles.add(file); return node; }, folder(node, _dir, metaPath) { if (shouldIgnore(this)) return node; if (metaPath) addedFiles.add(metaPath); return node; }, }; ``` Sources: [packages/core/src/source/page-tree/transformer-fallback.ts:5-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/transformer-fallback.ts#L5-L45) When the root transformer executes, it initializes an isolated file system storage instance, copies unindexed files that are absent from `addedFiles`, and instantiates a nested page tree builder with a modified `idPrefix` and a restricted context where `_fallback` is set to `true`. ```typescript root(root) { if (shouldIgnore(this)) return root; const isolatedStorage = new FileSystem() as ContentStorage; if (addedFiles.size === this.storage.files.size) return root; for (const file of this.storage.getFiles()) { if (addedFiles.has(file)) continue; isolatedStorage.write(file, this.storage.read(file)!); } root.fallback = createPageTreeBuilder(isolatedStorage, { ...this.options, idPrefix: this.options.idPrefix ? `fallback:${this.options.idPrefix}` : 'fallback', generateFallback: false, context: { ...this.custom, _fallback: true }, }).root(); ``` Sources: [packages/core/src/source/page-tree/transformer-fallback.ts:12-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/transformer-fallback.ts#L12-L29) > [!WARNING] > The fallback transformer clears `addedFiles` immediately after constructing the fallback tree root, ensuring subsequent transformation passes evaluate file additions correctly. Sources: [packages/core/src/source/page-tree/transformer-fallback.ts:30-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/transformer-fallback.ts#L30-L31) ## Client Serialization and State Contexts ### Serialization and Hydration Page trees generated by server-side loaders are serialized into a standard format before transmission across client-server boundaries. The `SerializedPageTree` interface wraps data using the `$fumadocs_loader` discriminator set to `'page-tree'`. ```tsx export interface SerializedPageTree { $fumadocs_loader: 'page-tree'; data: object; } ``` Sources: [packages/core/src/source/client/index.tsx:5-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L5-L8) The `useFumadocsLoader` hook processes serialized loader data, identifying serialized page trees and passing them to `deserializePageTree` for hydration. ```tsx export function useFumadocsLoader(serialized: V): Serialized { return useMemo(() => { const out: Record = {}; for (const k in serialized) { const v = serialized[k]; if (isSerializedPageTree(v)) { out[k] = deserializePageTree(v); } else { out[k] = v; } } return out as Serialized; }, [serialized]); } ``` Sources: [packages/core/src/source/client/index.tsx:47-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L47-L60) During deserialization, `visit` traverses the page tree nodes to parse and inject HTML strings for `icon` and `name` properties via `dangerouslySetInnerHTML`. ```tsx export function deserializePageTree(serialized: SerializedPageTree): PageTree.Root { const root = serialized.data as PageTree.Root; visit(root, (item) => { if ('icon' in item && typeof item.icon === 'string') { item.icon = ( ); } if (typeof item.name === 'string') { item.name = ( ); } }); return root; } ``` Sources: [packages/core/src/source/client/index.tsx:14-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L14-L39) > [!NOTE] > `deserializePageTree` inspects every visited node and converts string-based icons and names into React element structures containing `dangerouslySetInnerHTML` wrappers. Sources: [packages/core/src/source/client/index.tsx:16-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L16-L35) ### Tree Contexts and Path Tracking The `TreeContextProvider` component manages active tree state, path breadcrumbs, and unique root identifiers across client navigation. It computes the active breadcrumb path by searching the tree and its fallback children against the current pathname. Sources: [packages/radix-ui/src/contexts/tree.tsx:17-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L17-L47) | Context/Hook | Return Type | Purpose | | --- | --- | --- | | `TreeContext` | `TreeContextType` | Holds the active root node (`root`) and the complete page tree (`full`). | | `PathContext` | `PageTree.Node[]` | Tracks the hierarchical node path leading to the current active pathname. | | `useTreePath()` | `PageTree.Node[]` | Retrieves the current path node array from `PathContext`. | | `useTreeContext()` | `TreeContextType` | Retrieves the active tree context, throwing an error if uninitialized. | Sources: [packages/radix-ui/src/contexts/tree.tsx:9-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L9-L12), [packages/radix-ui/src/contexts/tree.tsx:15-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L15-L15), [packages/radix-ui/src/contexts/tree.tsx:49-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L49-L57) > [!WARNING] > `useTreeContext` throws an explicit error if invoked outside of a component wrapped under ``. Sources: [packages/radix-ui/src/contexts/tree.tsx:53-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L53-L57) ## Sidebar Node Rendering and Navigation ### Recursive Folder Hierarchies and Active States The `createPageTreeRenderer` function generates React component trees from page tree structures by recursively traversing nodes via `renderList` and `PageTreeNode`. It evaluates each node type—separator, folder, or page item—and dispatches rendering to either custom user-supplied components or default UI primitives. ```tsx export function createPageTreeRenderer({ SidebarFolder, SidebarFolderContent, SidebarFolderLink, SidebarFolderTrigger, SidebarSeparator, SidebarItem, }: InternalComponents) { function renderList(nodes: PageTree.Node[]) { return nodes.map((node, i) => ); } function PageTreeNode({ node }: { node: PageTree.Node }) { const { Separator, Item, Folder, pathname } = use(RendererContext)!; if (node.type === 'separator') { if (Separator) return ; return ( {node.icon} {node.name} ); } if (node.type === 'folder') { // eslint-disable-next-line react-hooks/rules-of-hooks -- assume node type unchanged const path = useTreePath(); if (Folder) return {renderList(node.children)}; return ( {node.index ? ( {node.icon} {node.name} ) : ( {node.icon} {node.name} )} {renderList(node.children)} ); } if (Item) return ; return ( {node.name} ); } ``` Sources: [packages/radix-ui/src/components/sidebar/page-tree.tsx:31-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/page-tree.tsx#L31-L98) Active states for individual items and index links are determined by comparing their target URLs against the current router pathname using the `isActive` utility. For folders, the `useTreePath` hook checks whether the folder is included in the current branch path to set expansion and highlight states. ```tsx if (node.type === 'folder') { // eslint-disable-next-line react-hooks/rules-of-hooks -- assume node type unchanged const path = useTreePath(); if (Folder) return {renderList(node.children)}; return ( {node.index ? ( {node.icon} {node.name} ) : ( {node.icon} {node.name} )} {renderList(node.children)} ); } if (Item) return ; return ( {node.name} ); ``` Sources: [packages/radix-ui/src/components/sidebar/page-tree.tsx:56-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/page-tree.tsx#L56-L97) > [!NOTE] > `RendererContext` caches the active pathname alongside custom component overrides using `useMemo`, ensuring minimal re-renders during client-side navigation. Sources: [packages/radix-ui/src/components/sidebar/page-tree.tsx:14-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/page-tree.tsx#L14-L19), [packages/radix-ui/src/components/sidebar/page-tree.tsx:109-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/page-tree.tsx#L109-L114) ### Tab Partitioning and Folder Scanning The `getSidebarTabs` utility extracts layout tabs from root page trees by scanning folders recursively. It identifies root-level sections and builds a collection of valid navigation endpoints. ```tsx export function getSidebarTabs( tree: PageTree.Root, { transform = defaultTransform }: GetSidebarTabsOptions = {}, ): SidebarTab[] { const results: SidebarTab[] = []; function scanOptions(node: PageTree.Root | PageTree.Folder, unlisted?: boolean) { if ('root' in node && node.root) { const urls = getFolderUrls(node); if (urls.size > 0) { const option: SidebarTab = { url: urls.values().next().value ?? '', title: node.name, icon: node.icon, unlisted, description: node.description, urls, }; const mapped = transform ? transform(option, node) : option; if (mapped) results.push(mapped); } } for (const child of node.children) { if (child.type === 'folder') scanOptions(child, unlisted); } } scanOptions(tree); if (tree.fallback) scanOptions(tree.fallback, true); return results; } ``` Sources: [packages/base-ui/src/components/sidebar/tabs/index.tsx:23-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/tabs/index.tsx#L23-L57) | Helper Function | Input Parameters | Return Type | Description | | --- | --- | --- | --- | | `getSidebarTabs` | `tree: PageTree.Root, options?: GetSidebarTabsOptions` | `SidebarTab[]` | Scans root nodes and fallback trees to construct partition tabs. | | `getFolderUrls` | `folder: PageTree.Folder, output?: Set` | `Set` | Collects all non-external page URLs and folder index links within a branch. | Sources: [packages/base-ui/src/components/sidebar/tabs/index.tsx:23-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/tabs/index.tsx#L23-L26), [packages/base-ui/src/components/sidebar/tabs/index.tsx:59-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/tabs/index.tsx#L59-L67) > [!WARNING] > If a scanned folder contains no resolvable child pages or index URLs, it is omitted from the resulting sidebar tabs array. Sources: [packages/base-ui/src/components/sidebar/tabs/index.tsx:30-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/tabs/index.tsx#L30-L45) ### Sequential Footer Item Navigation The `useFooterItems` hook produces a flattened, linear array of page tree items suitable for generating footer pagination and sequential next/previous navigation links. ```typescript export function useFooterItems(): PageTree.Item[] { const { root } = useTreeContext(); const cached = footerCache.get(root); if (cached) return cached; const list: PageTree.Item[] = []; function onNode(node: PageTree.Node) { if (node.type === 'folder') { if (node.index) onNode(node.index); for (const child of node.children) onNode(child); } else if (node.type === 'page' && !node.external) { list.push(node); } } for (const child of root.children) onNode(child); footerCache.set(root, list); return list; ``` Sources: [packages/radix-ui/src/utils/use-footer-items.ts:10-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts#L10-L27) During traversal, `onNode` processes folders by recursively inspecting folder index nodes and child elements, while filtering out external links and non-page entries before pushing items onto the linear list. ```typescript function onNode(node: PageTree.Node) { if (node.type === 'folder') { if (node.index) onNode(node.index); for (const child of node.children) onNode(child); } else if (node.type === 'page' && !node.external) { list.push(node); } } ``` Sources: [packages/radix-ui/src/utils/use-footer-items.ts:16-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts#L16-L23) > [!TIP] > `useFooterItems` caches generated item lists per root reference using a `WeakMap`, avoiding redundant tree traversals across repeated hook calls. Sources: [packages/radix-ui/src/utils/use-footer-items.ts:5-5](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts#L5-L5), [packages/radix-ui/src/utils/use-footer-items.ts:12-13](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts#L12-L13), [packages/radix-ui/src/utils/use-footer-items.ts:26-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts#L26-L26) ## Related - [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) - [Shared Layout Architecture](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture) --- ## Technical docs: Search Server Indexing URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-server-indexing
Relevant source files The following files were used as context for generating this wiki page: - [packages/core/src/search/orama/create-server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts) - [packages/base-ui/src/components/dialog/search-orama.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-orama.tsx) - [packages/radix-ui/src/components/dialog/search-orama.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-orama.tsx) - [packages/core/src/search/orama-cloud-legacy.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud-legacy.ts) - [packages/core/src/search/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts) - [packages/core/src/search/client/orama-cloud-legacy.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud-legacy.ts) - [packages/core/src/search/client/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud.ts) - [packages/core/src/search/orama/create-db.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-db.ts) - [packages/core/src/search/flexsearch.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/core/src/search/algolia.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts) - [packages/create-app/src/plugins/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/orama-cloud.ts) - [packages/preview/src/pages/_api/api/search.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/_api/api/search.ts) - [packages/core/src/search/client/orama-static.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-static.ts) - [packages/create-app/template/+orama-cloud/@app/lib/export-static-indexes.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/template/%2Borama-cloud/%40app/lib/export-static-indexes.ts) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/core/src/search/server/build-index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-index.ts) - [packages/core/src/search/server/build-doc.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-doc.ts) - [packages/core/src/search/client/flexsearch-static.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts) - [packages/core/src/search/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server.ts) - [packages/core/src/search/flexsearch/utils.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts) - [packages/core/src/search/mixedbread.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts) - [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/core/src/search/orama/search/simple.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts) - [packages/core/src/search/orama/search/advanced.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/advanced.ts) - [packages/create-app/template/+orama-cloud/@app/components/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/template/%2Borama-cloud/%40app/components/search.tsx) - [packages/core/src/search/client/algolia.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts) - [packages/core/src/search/orama/_stemmers.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/_stemmers.ts) - [packages/core/src/search/client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts)
## Overview Search Server Indexing transforms raw MDX documentation and source collections into structured, searchable records and indexes for search backends like local databases, Orama Cloud, Algolia, and Mixedbread. It extracts document content, headings, descriptions, and breadcrumbs, supplying consistent search endpoints across localized page trees. Sources: [packages/core/src/search/server/build-index.ts:6-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-index.ts#L6-L48), [packages/core/src/search/orama/create-server.ts:78-134](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L78-L134) ## Document extraction and structured indexing ### SharedIndex and SharedDocument interfaces The search indexing pipeline transforms page collections into search-ready payloads using two foundational data structures: `SharedIndex` and `SharedDocument`. A `SharedIndex` captures page-level metadata alongside preprocessed `StructuredData`, while `SharedDocument` decomposes that record into granular searchable entries categorized by type (`page`, `heading`, or `text`). ```typescript export interface SharedIndex { id: string; title: string; description?: string; breadcrumbs?: string[]; tag?: string | string[]; structuredData: StructuredData; url: string; } export interface SharedDocument { id: string; content: string; page_id: string; type: 'page' | 'heading' | 'text'; breadcrumbs?: string[]; tags: string[]; url: string; } ``` Sources: [packages/core/src/search/server/build-index.ts:6-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-index.ts#L6-L22), [packages/core/src/search/server/build-doc.ts:3-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-doc.ts#L3-L11) ### Page index building and resolution The `buildIndexDefault` function resolves structured data from a `Page` object by checking `page.data.structuredData` (evaluating it if defined as a function) or falling back to invoking `page.data.load()` if present. If neither source yields structured data, an error is thrown. Titles default to `page.data.title` or fall back to the filename derived via `basename` and `extname`. ```typescript export async function buildIndexDefault(page: Page): Promise { let structuredData: StructuredData | undefined; if (page.data.structuredData) { structuredData = typeof page.data.structuredData === 'function' ? await page.data.structuredData() : page.data.structuredData; } else if ('load' in page.data && typeof page.data.load === 'function') { structuredData = (await page.data.load()).structuredData; } if (!structuredData) throw new Error( 'Cannot find structured data from page, please define the page to index function.', ); return { title: page.data.title ?? basename(page.path, extname(page.path)), description: page.data.description, url: page.url, id: page.url, structuredData, }; } ``` Sources: [packages/core/src/search/server/build-index.ts:24-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-index.ts#L24-L48) > [!WARNING] > Omitting structured data preprocessing on a page without a `load` method or static `structuredData` property causes `buildIndexDefault` to throw an explicit runtime error during index compilation. Sources: [packages/core/src/search/server/build-index.ts:36-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-index.ts#L36-L39) ### Breadcrumb path resolution The `buildBreadcrumbs` utility constructs hierarchical navigation paths for search records by querying the localized page tree obtained via `source.getPageTree(page.locale)`. It uses `findPath` to locate the target node, pops the final page segment, and collects valid non-empty string names from parent nodes and the page tree root. ```typescript function isBreadcrumbItem(item: unknown): item is string { return typeof item === 'string' && item.length > 0; } export function buildBreadcrumbs( source: LoaderOutput, page: C['page'], ): string[] | undefined { const pageTree = source.getPageTree(page.locale); const path = findPath(pageTree.children, (node) => node.type === 'page' && node.url === page.url); if (path) { const breadcrumbs: string[] = []; path.pop(); if (isBreadcrumbItem(pageTree.name)) { breadcrumbs.push(pageTree.name); } for (const segment of path) { if (!isBreadcrumbItem(segment.name)) continue; breadcrumbs.push(segment.name); } return breadcrumbs; } } ``` Sources: [packages/core/src/search/server/build-index.ts:50-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-index.ts#L50-L76) ### Document flattening and record generation The `buildDocuments` function iterates over an array of `SharedIndex` objects to produce a flat list of `SharedDocument` records. Each page generates a primary document record (`type: 'page'`), an optional description record (`type: 'text'`), multiple heading records (`type: 'heading'`), and body text content chunks (`type: 'text'`). | Document Type | ID Format | URL Format | Content Source | | --- | --- | --- | --- | | `page` | `page.id` | `page.url` | `page.title` | | `text` (description) | `${page.id}-${id++}` | `page.url` | `page.description` | | `heading` | `${page.id}-${id++}` | `${page.url}#${heading.id}` | `heading.content` | | `text` (content chunk) | `${page.id}-${id++}` | `${page.url}#${content.heading}` or `page.url` | `content.content` | Sources: [packages/core/src/search/server/build-doc.ts:13-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-doc.ts#L13-L68) ## Local Orama database instantiation ### Database Schemas and Document Types The Orama search engine supports two distinct schema configurations depending on whether simple or advanced search servers are initialized. The simple schema defines fields for `url`, `title`, `breadcrumbs`, `description`, `content`, and `keywords`. The advanced schema incorporates granular fields including `content`, `page_id`, `type`, `breadcrumbs`, an `enum[]` for `tags`, `url`, and a 512-dimensional vector field `embeddings`. ```typescript export type SimpleDocument = TypedDocument>; export const simpleSchema = { url: 'string', title: 'string', breadcrumbs: 'string[]', description: 'string', content: 'string', keywords: 'string', } as const; export type AdvancedDocument = TypedDocument>; export const advancedSchema = { content: 'string', page_id: 'string', type: 'string', breadcrumbs: 'string[]', tags: 'enum[]', url: 'string', embeddings: 'vector[512]', } as const; ``` Sources: [packages/core/src/search/orama/create-db.ts:11-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-db.ts#L11-L30) > [!NOTE] > Advanced search vector queries require installing `@orama/plugin-embeddings` separately; invoking vector mode without this plugin throws an explicit runtime configuration error. Sources: [packages/core/src/search/orama/create-server.ts:121-128](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L121-L128) ### Database Creation and Index Insertion The `createDB` and `createDBSimple` functions instantiate in-memory Orama databases and populate them with records. If `indexes` is supplied as a dynamic function, it is awaited before index processing. Custom tokenizers take precedence when passed in configuration options, falling back to existing component tokenizers. ```typescript export async function createDB({ indexes, tokenizer, search: _, ...rest }: AdvancedOptions): Promise> { const items = typeof indexes === 'function' ? await indexes() : indexes; const db = create({ schema: advancedSchema, ...rest, components: { ...rest.components, tokenizer: tokenizer ?? rest.components?.tokenizer, }, }) as Orama; const mapTo: PartialSchemaDeep[] = buildDocuments(items); await insertMultiple(db, mapTo); return db; } ``` Sources: [packages/core/src/search/orama/create-db.ts:32-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-db.ts#L32-L52) ```typescript export async function createDBSimple({ indexes, tokenizer, ...rest }: SimpleOptions): Promise> { const items = typeof indexes === 'function' ? await indexes() : indexes; const db = create({ schema: simpleSchema, ...rest, components: { ...rest.components, tokenizer: tokenizer ?? rest.components?.tokenizer, }, }) as Orama; await insertMultiple( db, items.map((page) => ({ title: page.title, description: page.description, breadcrumbs: page.breadcrumbs, url: page.url, content: page.content, keywords: page.keywords, })), ); return db; } ``` Sources: [packages/core/src/search/orama/create-db.ts:54-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-db.ts#L54-L82) ### Stemmers and Internationalized Tokenizer Resolution Internationalized search servers resolve language stemmers using a predefined mapping of full language names to language codes. The `STEMMERS` dictionary defines 32 supported language mappings for tokenization and stemming. | Language Name | Code | Language Name | Code | Language Name | Code | | --- | --- | --- | --- | --- | --- | | `arabic` | `ar` | `irish` | `ie` | `slovenian` | `ru` | | `armenian` | `am` | `italian` | `it` | `spanish` | `es` | | `bulgarian` | `bg` | `lithuanian` | `lt` | `swedish` | `se` | | `czech` | `cz` | `nepali` | `np` | `tamil` | `ta` | | `danish` | `dk` | `norwegian` | `no` | `turkish` | `tr` | | `dutch` | `nl` | `portuguese` | `pt` | `ukrainian` | `uk` | | `english` | `en` | `romanian` | `ro` | `vietnamese` | `vi` | | `finnish` | `fi` | `russian` | `ru` | `sanskrit` | `sk` | | `french` | `fr` | `serbian` | `rs` | | | | `german` | `de` | | | | | | `greek` | `gr` | | | | | | `hungarian` | `hu` | | | | | | `indian` | `in` | | | | | | `indonesian` | `id` | | | | | Sources: [packages/core/src/search/orama/_stemmers.ts:2-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/_stemmers.ts#L2-L33) The `getTokenizer` helper checks if a given locale string matches a registered stemmer key, returning the corresponding language code or falling back directly to the input locale string. ```typescript function getTokenizer(locale: string): { language: string } | { tokenizer: Tokenizer } { return { language: Object.keys(STEMMERS).find((lang) => STEMMERS[lang] === locale) ?? locale, }; } ``` Sources: [packages/core/src/search/orama/create-server.ts:172-176](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts#L172-L176) ## Flexsearch index generation and routing ### Initialization and Execution Walkthrough Multi-locale Flexsearch indices are constructed and served by navigating through a strict call chain. The process executes through the following steps: `flexsearchI18n` calls `serverI18n`, which invokes `initSearchServers` to group indexes by locale and initialize per-locale servers via `server`. Each `server` call invokes `initIndex`, which builds documents via `buildDocuments` and generates unique identifiers using `nextId`. ```mermaid sequenceDiagram participant flexsearchI18n as flexsearch.ts participant serverI18n as flexsearch.ts participant initSearchServers as flexsearch.ts participant server as flexsearch.ts participant initIndex as flexsearch.ts participant buildDocuments as build-doc.ts participant nextId as build-doc.ts flexsearchI18n->>serverI18n: flexsearchI18n(options) serverI18n->>initSearchServers: initSearchServers() initSearchServers->>server: server({ indexes: list, document }) server->>initIndex: initIndex(indexes) initIndex->>buildDocuments: buildDocuments(indexes) buildDocuments->>nextId: nextId() ``` Sources: [packages/core/src/search/flexsearch.ts:41-137](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L41-L137), [packages/core/src/search/server/build-doc.ts:13-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server/build-doc.ts#L13-L68) > [!NOTE] > When `flexsearchFromSource` evaluates a loader function, it caches the resulting promise in a `WeakMap` mapped to the specific loader output instance. Re-indexing occurs automatically once a distinct loader instance is returned. Sources: [packages/core/src/search/flexsearch.ts:149-186](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L149-L186) ### Document Construction and Search Options The Flexsearch document schema configures tokenization, indexed fields, and storage options. By default, `createDocument` sets `tokenize` to `'full'`, indexes the `content` field, tags records using `tags`, and enables `store`. ```typescript export function createDocument(options?: DocumentOptions) { return new Search.Document({ tokenize: 'full', ...options, document: { id: 'id', index: ['content'], tag: ['tags'], store: true, ...options?.document, }, }); ``` Sources: [packages/core/src/search/flexsearch/utils.ts:70-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L70-L81) | Parameter / Property | Type | Default Value | Purpose | | --- | --- | --- | --- | | `tokenize` | string | `'full'` | Sets the string tokenization strategy for indexing. | | `document.id` | string | `'id'` | Specifies the unique document identifier field. | | `document.index` | string[] | `['content']` | Defines the document fields included in the search index. | | `document.tag` | string[] | `['tags']` | Defines the fields used for tag-based filtering. | | `document.store` | boolean | `true` | Enables field storage within the index for retrieval. | Sources: [packages/core/src/search/flexsearch/utils.ts:70-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch/utils.ts#L70-L81) > [!WARNING] > Setting a `localeMap` entry to the literal string `'cjk'` automatically forces the document encoder configuration to `Search.Charset.CJK`. Any custom document options passed alongside are overridden or merged depending on the locale map specification. Sources: [packages/core/src/search/flexsearch.ts:31-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L31-L39), [packages/core/src/search/flexsearch.ts:96-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts#L96-L100) ## Algolia search index synchronization ### Synchronization Flow and Settings Configuration Synchronization is executed by the `sync` function, which calls `setIndexSettings` followed by `updateDocuments`. The `indexName` defaults to `'document'` when omitted in `SyncOptions`. ```typescript export async function sync(client: Algoliasearch, options: SyncOptions): Promise { const { indexName = 'document', documents } = options; await setIndexSettings(client, indexName); await updateDocuments(client, indexName, documents); } ``` Sources: [packages/core/src/search/algolia.ts:49-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L49-L53) The index settings are configured via `client.setSettings` with specific attributes for retrieval, faceting, searchability, and distinct filtering. ```typescript export async function setIndexSettings(client: Algoliasearch, indexName: string): Promise { await client.setSettings({ indexName, indexSettings: { attributeForDistinct: 'page_id', attributesToRetrieve: ['title', 'section', 'content', 'url', 'section_id', 'breadcrumbs'], searchableAttributes: ['title', 'section', 'content'], attributesToSnippet: [], attributesForFaceting: ['tag'], }, }); } ``` Sources: [packages/core/src/search/algolia.ts:55-66](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L55-L66) | Setting Field | Target Value / Type | Purpose | | --- | --- | --- | | `attributeForDistinct` | `'page_id'` | Groups search results by page identifier using distinct records. | | `attributesToRetrieve` | `['title', 'section', 'content', 'url', 'section_id', 'breadcrumbs']` | Specifies the record attributes returned in search queries. | | `searchableAttributes` | `['title', 'section', 'content']` | Defines attributes included in search ranking and matching. | | `attributesToSnippet` | `[]` | Configures snippet generation for retrieved records. | | `attributesForFaceting` | `['tag']` | Enables tag-based faceting and filtering on records. | Sources: [packages/core/src/search/algolia.ts:58-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L58-L64) > [!NOTE] > The `sync` function replaces all objects in the target index rather than performing incremental updates, ensuring stale records are purged during synchronization. Sources: [packages/core/src/search/algolia.ts:49-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L49-L53), [packages/core/src/search/algolia.ts:119-122](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L119-L122) ### Record Batch Transformation The `toIndex` function processes each `DocumentRecord` to generate an array of `BaseIndex` objects. If a page contains a description, an initial record is created with `undefined` for `section` and `section_id`. ```typescript function toIndex(page: DocumentRecord): BaseIndex[] { let id = 0; const indexes: BaseIndex[] = []; const scannedHeadings = new Set(); function createIndex( section: string | undefined, sectionId: string | undefined, content: string, ): BaseIndex { return { objectID: `${page._id}-${(id++).toString()}`, breadcrumbs: page.breadcrumbs, title: page.title, url: page.url, page_id: page._id, tag: page.tag, section, section_id: sectionId, content, ...page.extra_data, }; } if (page.description) indexes.push(createIndex(undefined, undefined, page.description)); ``` Sources: [packages/core/src/search/algolia.ts:68-92](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L68-L92) For each content item in `page.structured`, matching headings are resolved. When a heading is encountered for the first time, a dedicated heading index record is created and added before the content record. ```typescript const { headings, contents } = page.structured; for (const p of contents) { const heading = p.heading ? headings.find((h) => p.heading === h.id) : null; const index = createIndex(heading?.content, heading?.id, p.content); if (heading && !scannedHeadings.has(heading.id)) { scannedHeadings.add(heading.id); indexes.push(createIndex(heading.content, heading.id, heading.content)); } indexes.push(index); } ``` Sources: [packages/core/src/search/algolia.ts:93-107](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L93-L107) ```typescript return indexes; } ``` Sources: [packages/core/src/search/algolia.ts:108-110](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L108-L110) > [!WARNING] > Object identifiers are constructed by appending an incrementing index counter to `page._id` separated by a hyphen (`${page._id}-${(id++).toString()}`). Collisions will occur if multiple documents share the same `_id`. Sources: [packages/core/src/search/algolia.ts:78-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/algolia.ts#L78-L90) ## Orama Cloud integration and export ### Structured Document Export and Index Transformation The `exportSearchIndexes` function extracts pages from the source collection and maps each entry into an `OramaDocument` containing its unique identifier, URL, title, description, and structured data. ```typescript export async function exportSearchIndexes() { return source.getPages().map((page) => { return { id: page.url, structured: page.data.structuredData, url: page.url, title: page.data.title, description: page.data.description, } satisfies OramaDocument; }); } ``` Sources: [packages/create-app/template/+orama-cloud/@app/lib/export-static-indexes.ts:4-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/template/%2Borama-cloud/%40app/lib/export-static-indexes.ts#L4-L14) The `toIndex` function converts each `OramaDocument` into an array of `OramaIndex` records by iterating over structured contents and matching headings. If a page description exists, an initial record is created with undefined section identifiers. ```typescript function toIndex(page: OramaDocument): OramaIndex[] { let id = 0; const indexes: OramaIndex[] = []; const scannedHeadings = new Set(); function createIndex( section: string | undefined, sectionId: string | undefined, content: string, ): OramaIndex { return { id: `${page.id}-${(id++).toString()}`, title: page.title, url: page.url, page_id: page.id, tag: page.tag, section, section_id: sectionId, content, breadcrumbs: page.breadcrumbs, ...page.extra_data, }; } if (page.description) indexes.push(createIndex(undefined, undefined, page.description)); ``` Sources: [packages/core/src/search/orama-cloud.ts:118-143](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts#L118-L143) ```typescript page.structured.contents.forEach((p) => { const heading = p.heading ? page.structured.headings.find((h) => p.heading === h.id) : null; const index = createIndex(heading?.content, heading?.id, p.content); if (heading && !scannedHeadings.has(heading.id)) { scannedHeadings.add(heading.id); indexes.push(createIndex(heading.content, heading.id, heading.content)); } indexes.push(index); }); return indexes; ``` Sources: [packages/core/src/search/orama-cloud.ts:144-158](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts#L144-L158) > [!WARNING] > Unique index identifiers are generated by combining the document ID with an incrementing counter separated by a hyphen (``${page.id}-${(id++).toString()}``). Sources: [packages/core/src/search/orama-cloud.ts:123-140](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts#L123-L140) ### Remote Synchronization and Framework Endpoints The `sync` function opens a transaction on the specified Orama Cloud index, inserts the flattened document records, and commits the transaction if `autoDeploy` is enabled. ```typescript export async function sync(orama: OramaCloud, options: SyncOptions): Promise { const { autoDeploy = true } = options; const index = orama.index.set(options.index); await index.transaction.open(); await index.transaction.insertDocuments( options.documents.flatMap(toIndex) as unknown as AnyObject[], ); if (autoDeploy) await index.transaction.commit(); } ``` Sources: [packages/core/src/search/orama-cloud.ts:89-99](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts#L89-L99) Internationalized synchronization is handled by `syncI18n`, which maps document locales to corresponding index identifiers and executes concurrent synchronization tasks for each locale. ```typescript export async function syncI18n(orama: OramaCloud, options: I18nSyncOptions): Promise { const { autoDeploy = true, indexes } = options; const tasks = options.documents.map(async (document) => { const index = orama.index.set(indexes[document.locale]); await index.transaction.open(); await index.transaction.insertDocuments( document.items.flatMap(toIndex) as unknown as AnyObject[], ); if (autoDeploy) await index.transaction.commit(); }); await Promise.all(tasks); } ``` Sources: [packages/core/src/search/orama-cloud.ts:101-116](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts#L101-L116) Framework routing plugins configure static JSON export endpoints across different application routers. | Framework Target | Route Path | Implementation Handler | | --- | --- | --- | | Next.js App Router | `/static.json` | `Response.json(await exportSearchIndexes())` | | React Router / SPA | `static.json` | `loader` returning `Response.json(await exportSearchIndexes())` | | Tanstack Start | `/static.json` | Server file route with `GET` handler returning `Response.json(await exportSearchIndexes())` | | Waku | `/static.json` | `GET` handler with static configuration | Sources: [packages/create-app/src/plugins/orama-cloud.ts:37-65](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/orama-cloud.ts#L37-L65), [packages/create-app/src/plugins/orama-cloud.ts:109-140](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/orama-cloud.ts#L109-L140) ## Mixedbread vector and semantic indexing ### Semantic Chunk Transformation and Endpoint Configuration The `createMixedbreadSearchAPI` factory constructs a search endpoint that queries Mixedbread vector stores using `@mixedbread/sdk` clients. Options allow configuring client instances, store identifiers, top-k limits, and semantic options like re-ranking and query rewriting. ```typescript export interface MixedbreadSearchOptions { /** * The Mixedbread SDK client instance */ client: Mixedbread; /** * The identifier of the store to search in */ storeIdentifier: string; /** * Maximum number of results to return * * @defaultValue 10 */ topK?: number; /** * Re-rank search results for improved relevance (this adds latency to the search) */ rerank?: boolean; /** * Rewrite the query for better search results (this adds latency to the search) */ rewriteQuery?: boolean; /** * Minimum score threshold for results */ scoreThreshold?: number; /** * Custom transform function for search results */ transform?: (results: StoreSearchResult[], query: string) => SortedResult[]; } ``` Sources: [packages/core/src/search/mixedbread.ts:20-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts#L20-L57) ```typescript export function createMixedbreadSearchAPI(options: MixedbreadSearchOptions): SearchAPI { const { client, storeIdentifier, topK = 10, rerank, rewriteQuery, scoreThreshold, transform, } = options; ``` Sources: [packages/core/src/search/mixedbread.ts:113-123](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts#L113-L123) > [!CAUTION] > Exporting search indexes is explicitly unsupported for Mixedbread endpoints; attempting to invoke `export()` throws an error instructing administrators to use the Mixedbread dashboard for store management. Sources: [packages/core/src/search/mixedbread.ts:167-172](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts#L167-L172) ### Result Formatting and Filtering The default transformation engine processes raw store search results by extracting document metadata such as URLs and titles, producing structured page and heading entries. Headings are cleaned using `remove-markdown` and converted into URL anchor links via `github-slugger`. ```typescript function defaultTransform(results: StoreSearchResult[]): SortedResult[] { return results.flatMap((item) => { const metadata = item.generated_metadata; const url = metadata.url || '#'; const title = metadata.title || 'Untitled'; const chunkResults: SortedResult[] = [ { id: `${item.file_id}-${item.chunk_index}-page`, type: 'page', content: title, url, }, ]; const headingTitle = item.type === 'text' && item.text ? extractHeadingTitle(item.text) : ''; if (headingTitle) { slugger.reset(); chunkResults.push({ id: `${item.file_id}-${item.chunk_index}-heading`, type: 'heading', content: headingTitle, url: `${url}#${slugger.slug(headingTitle)}`, }); } return chunkResults; }); } ``` Sources: [packages/core/src/search/mixedbread.ts:80-111](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts#L80-L111) Search requests support optional tag filters applied directly to generated metadata fields within store queries. ```typescript const { tag, limit } = searchOptions; let filters: StoreSearchParams['filters'] | undefined; if (Array.isArray(tag) && tag.length > 0) { filters = { key: 'generated_metadata.tag', operator: 'in', value: tag, }; } else if (typeof tag === 'string') { filters = { key: 'generated_metadata.tag', operator: 'eq', value: tag, }; } ``` Sources: [packages/core/src/search/mixedbread.ts:130-144](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts#L130-L144) ## Related - [Search Client Integrations](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-client-integrations) --- ## Technical docs: Search Client Integrations URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-client-integrations
Relevant source files The following files were used as context for generating this wiki page: - [packages/core/src/search/client/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud.ts) - [packages/base-ui/src/components/dialog/search-orama.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-orama.tsx) - [packages/radix-ui/src/components/dialog/search-orama.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-orama.tsx) - [packages/base-ui/src/components/dialog/search-algolia.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-algolia.tsx) - [packages/radix-ui/src/components/dialog/search-algolia.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-algolia.tsx) - [packages/base-ui/src/components/dialog/search-default.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-default.tsx) - [packages/radix-ui/src/components/dialog/search-default.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-default.tsx) - [packages/core/src/search/client/orama-cloud-legacy.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud-legacy.ts) - [packages/core/src/search/client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts) - [packages/core/src/search/orama/create-server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-server.ts) - [packages/core/src/search/client/mixedbread.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts) - [packages/core/src/search/mixedbread.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/mixedbread.ts) - [packages/core/src/search/client/orama-static.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-static.ts) - [packages/create-app/template/+orama-cloud/@app/components/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/template/%2Borama-cloud/%40app/components/search.tsx) - [packages/base-ui/src/components/dialog/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search.tsx) - [packages/radix-ui/src/components/dialog/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search.tsx) - [packages/core/src/search/client/fetch.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/fetch.ts) - [packages/preview/src/components/ai/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/ai/search.tsx) - [packages/core/src/search/client/flexsearch-static.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts) - [packages/core/src/search/client/algolia.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts) - [packages/create-app/src/plugins/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/orama-cloud.ts) - [packages/core/src/search/flexsearch.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/flexsearch.ts) - [packages/base-ui/src/contexts/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx) - [packages/radix-ui/src/contexts/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/search.tsx) - [packages/core/src/search/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/server.ts) - [packages/core/src/search/orama-cloud-legacy.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud-legacy.ts) - [packages/core/src/search/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts) - [packages/core/src/search/orama/create-db.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/create-db.ts) - [packages/core/src/search/orama/search/advanced.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/advanced.ts) - [packages/core/src/search/orama/search/simple.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts)
## Overview Search Client Integrations provide client-side query execution, state coordination, and UI bindings for documentation search across multiple search engines. They bridge the gap between user input inside search dialogs and backend or in-browser search indexes, handling debouncing, result caching, dependency tracking, and asynchronous client loading. Sources: [packages/core/src/search/client.ts:78-197](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L78-L197) ## Search Client React Hook Architecture ### Hook API and State Structure The `useDocsSearch` hook manages user search input, debounced query execution, error handling, loading states, and result caching across different search provider backends. It accepts `clientOptions` containing preset configurations or a direct `SearchClient` instance, alongside an optional `customDeps` dependency list. ```typescript export function useDocsSearch( clientOptions: ClientPreset & { /** * The debounced delay for performing a search (in ms). * . * @defaultValue 100 */ delayMs?: number; /** * still perform search even if query is empty. * * @defaultValue false */ allowEmpty?: boolean; }, customDeps?: DependencyList, ): UseDocsSearch { ``` Sources: [packages/core/src/search/client.ts:83-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L83-L100) The return value conforms to the `UseDocsSearch` interface, exposing the raw input string, its setter, and a query status object holding loading flags, result arrays, or errors. ```typescript interface UseDocsSearch { search: string; setSearch: (v: string) => void; query: { isLoading: boolean; data?: SortedResult[] | 'empty'; error?: Error; }; } ``` Sources: [packages/core/src/search/client.ts:14-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L14-L22) ### Client Preset Resolution and Deprecation `ClientPreset` supports both legacy string-keyed configuration types and modern direct `SearchClient` references. When a legacy `type` string is provided, `useDocsSearch` dynamically imports the respective client module and constructs the search client asynchronously. ```typescript export type ClientPreset = | ({ /** * @deprecated Pass `client: fetchClient(...)` instead. */ type: 'fetch'; } & FetchOptions) | ({ /** * @deprecated Pass `client: oramaStaticClient(...)` instead. */ type: 'static'; } & StaticOptions) | ({ /** * @deprecated Pass `client: algoliaClient(...)` instead. */ type: 'algolia'; } & AlgoliaOptions) | ({ /** * @deprecated Pass `client: oramaCloudClient(...)` instead. */ type: 'orama-cloud'; } & OramaCloudOptions) | ({ /** * @deprecated Pass `client: oramaCloudLegacyClient(...)` instead. */ type: 'orama-cloud-legacy'; } & OramaCloudLegacyOptions) | ({ /** * @deprecated Pass `client: flexsearchStaticClient(...)` instead. */ type: 'flexsearch-static'; } & FlexsearchStaticOptions) | ({ /** * @deprecated Use `createMixedbreadSearchAPI` from `fumadocs-core/search/mixedbread` instead. * This client-side approach exposes your API key in the browser. * The server-side approach keeps the key secure and uses `client: fetchClient(...)` on the client. */ type: 'mixedbread'; } & MixedbreadOptions) | { client: SearchClient; }; ``` Sources: [packages/core/src/search/client.ts:24-71](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L24-L71) | Preset Type | Module Import Path | Options Interface | | :--- | :--- | :--- | | `fetch` | `@/search/client/fetch` | `FetchOptions` | | `static` | `@/search/client/orama-static` | `StaticOptions` | | `algolia` | `@/search/client/algolia` | `AlgoliaOptions` | | `orama-cloud` | `@/search/client/orama-cloud` | `OramaCloudOptions` | | `orama-cloud-legacy` | `@/search/client/orama-cloud-legacy` | `OramaCloudLegacyOptions` | | `flexsearch-static` | `./client/flexsearch-static` | `FlexsearchStaticOptions` | | `mixedbread` | `@/search/client/mixedbread` | `MixedbreadOptions` | Sources: [packages/core/src/search/client.ts:110-143](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L110-L143) > [!WARNING] > Using string-keyed presets like `type: 'fetch'` is deprecated. Pass a pre-instantiated client such as `client: fetchClient(...)` directly to avoid runtime dynamic imports and ensure type-safe dependency tracking. Sources: [packages/core/src/search/client.ts:24-71](https://github.com/blade47/fumadopos/blob/HEAD/packages/core/src/search/client.ts#L24-L71) ### Debouncing and Task Interruption Search input is processed through `useDebounce` with a configurable `delayMs` defaulting to `100` milliseconds. Setting `allowEmpty` to `true` forces search execution even when the query string is empty. ```typescript const { delayMs = 100, allowEmpty = false, ...clientRest } = clientOptions; const [search, setSearch] = useState(''); const [results, setResults] = useState('empty'); const [error, setError] = useState(); const [isLoading, setIsLoading] = useState(false); const debouncedValue = useDebounce(search, delayMs); ``` Sources: [packages/core/src/search/client.ts:101-106](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L101-L106) Active search tasks are tracked via `activeTaskRef`. When dependencies or debounced values change before an in-flight search resolves, the previous task is immediately marked as interrupted, preventing stale responses from overwriting newer query results. ```typescript const [activeDeps, setActiveDeps] = useState(null); const activeTaskRef = useRef<{ deps: DependencyList; start: () => void; interrupt: boolean; } | null>(null); if ( !isEqualShallow(activeDeps, deps) && (!activeTaskRef.current || !isEqualShallow(activeTaskRef.current.deps, deps)) ) { if (activeTaskRef.current) activeTaskRef.current.interrupt = true; activeTaskRef.current = { deps, interrupt: false, async start() { try { setIsLoading(true); let res: SortedResult[] | 'empty'; if (debouncedValue.length === 0 && !allowEmpty) res = 'empty'; else res = await (await client).search(debouncedValue); if (!this.interrupt) { setActiveDeps(deps); setError(undefined); setResults(res); } } catch (err) { if (!this.interrupt) setError(err as Error); } finally { if (!this.interrupt) setIsLoading(false); } }, }; void activeTaskRef.current.start(); } ``` Sources: [packages/core/src/search/client.ts:154-191](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L154-L191) > [!NOTE] > If `allowEmpty` is `false` and the debounced query length is zero, the hook bypasses the search client call entirely and sets the result data directly to `'empty'`. Sources: [packages/core/src/search/client.ts:174-176](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client.ts#L174-L176) ### Query Caching via Fetch Client The built-in `fetchClient` utilizes an internal `Map` cache (`globalCache` by default, or a custom map passed via `FetchOptions`) keyed by the fully constructed request URL string. Before executing a network request, it checks for a cached `SortedResult[]` entry. ```typescript const globalCache = new Map(); export function fetchClient({ api = '/api/search', locale, tag, cache = globalCache, }: FetchOptions = {}): SearchClient { return { deps: [api, locale, tag], async search(query) { const url = new URL(api, window.location.origin); url.searchParams.set('query', query); if (locale) url.searchParams.set('locale', locale); if (tag) url.searchParams.set('tag', Array.isArray(tag) ? tag.join(',') : tag); const key = url.toString(); const cached = cache.get(key); if (cached) return cached; const res = await fetch(url); if (!res.ok) throw new Error(await res.text()); const result = (await res.json()) as SortedResult[]; cache.set(key, result); return result; }, }; ``` Sources: [packages/core/src/search/client/fetch.ts:25-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/fetch.ts#L25-L51) ## Default Route Querying via Fetch ### Fetch Client Configuration and Parameters The `fetchClient` factory function constructs a client adhering to the `SearchClient` interface by querying an API endpoint over HTTP. It accepts `FetchOptions` to customize the network request behavior and parameter serialization. | Option Key | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `api` | `string` | `'/api/search'` | API route for the search endpoint, supporting absolute URLs. | | `tag` | `string \| string[]` | `undefined` | Filter results with one or more tags (comma-joined if an array). | | `locale` | `string` | `undefined` | Filter search results by language locale. | | `cache` | `Map` | `globalCache` | Storage map used for query caching across searches. | Sources: [packages/core/src/search/client/fetch.ts:4-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/fetch.ts#L4-L23), [packages/core/src/search/client/fetch.ts:25-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/fetch.ts#L25-L32) When `search(query)` is invoked, `fetchClient` builds a `URL` instance using `window.location.origin` as the base, appending query parameters for `query`, `locale`, and `tag`. If `tag` is provided as an array, its elements are joined with commas. ```typescript async search(query) { const url = new URL(api, window.location.origin); url.searchParams.set('query', query); if (locale) url.searchParams.set('locale', locale); if (tag) url.searchParams.set('tag', Array.isArray(tag) ? tag.join(',') : tag); ``` Sources: [packages/core/src/search/client/fetch.ts:35-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/fetch.ts#L35-L40) > [!WARNING] > If the fetch response status is not OK (`!res.ok`), `fetchClient` reads the response body as text and throws it immediately as an `Error`. Sources: [packages/core/src/search/client/fetch.ts:45-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/fetch.ts#L45-L46) ### Default Search Dialog Integration The `DefaultSearchDialog` component integrates `fetchClient` with [Base UI Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/base-ui-components) and Radix primitives, wrapping `useDocsSearch` to power accessible search dialogs. ```tsx export default function DefaultSearchDialog({ defaultTag, tags = [], api, delayMs, allowClear = false, links = [], footer, ...props }: DefaultSearchDialogProps) { const { locale } = useI18n(); const [tag, setTag] = useState(defaultTag); const { search, setSearch, query } = useDocsSearch({ client: fetchClient({ api, locale, tag, }), delayMs, }); ``` Sources: [packages/radix-ui/src/components/dialog/search-default.tsx:50-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-default.tsx#L50-L69) | Prop Name | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `links` | `SearchLink[]` | `[]` | Default fallback links displayed when no search query is active. | | `defaultTag` | `string` | `undefined` | Initial active filter tag. | | `tags` | `TagItem[]` | `[]` | Available filter tags rendered in the dialog footer. | | `api` | `string` | `undefined` | Custom search API URL passed to `fetchClient`. | | `delayMs` | `number` | `undefined` | Debounce delay for executing search requests. | | `allowClear` | `boolean` | `false` | Allows users to clear active tag filters. | | `footer` | `ReactNode` | `undefined` | Custom React node rendered alongside the tag list in the footer. | Sources: [packages/radix-ui/src/components/dialog/search-default.tsx:25-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-default.tsx#L25-L48) `DefaultSearchDialog` synchronizes the dialog's tag state with locale changes and passes the resulting query items to `SearchDialogList`. When the query data evaluates to `'empty'`, it falls back to rendering the memoized default `links` converted into `SortedResult` items. ```tsx const defaultItems = useMemo(() => { if (links.length === 0) return null; return links.map(([name, link]) => ({ type: 'page', id: name, content: name, url: link, })); }, [links]); ``` Sources: [packages/radix-ui/src/components/dialog/search-default.tsx:70-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-default.tsx#L70-L78) ```tsx ``` Sources: [packages/radix-ui/src/components/dialog/search-default.tsx:93-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-default.tsx#L93-L93) > [!TIP] > If `tags` array length is greater than zero, `DefaultSearchDialog` automatically renders a `TagsList` component inside `SearchDialogFooter` equipped with tag selection handlers and clear options. Sources: [packages/radix-ui/src/components/dialog/search-default.tsx:96-104](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search-default.tsx#L96-L104) ## Orama Cloud Client Adapters ### Query Pipeline and Index Modes Fumadocs provides client adapters for both modern Orama Cloud (`@orama/core`) and legacy Orama clients (`@oramacloud/client`) via `oramaCloudClient` and `oramaCloudLegacyClient`. Each adapter constructs a `SearchClient` configured with dependencies and an asynchronous `search(query)` execution pipeline. ```typescript export function oramaCloudClient(options: OramaCloudOptions): SearchClient { const { index = 'default', client, params: extraParams, tag } = options; return { deps: [index, client, tag], ``` Sources: [packages/core/src/search/client/orama-cloud.ts:40-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud.ts#L40-L44) ```typescript export function oramaCloudLegacyClient(options: OramaCloudLegacyOptions): SearchClient { const { index = 'default', client, params: extraParams = {}, tag } = options; return { deps: [index, client, tag], ``` Sources: [packages/core/src/search/client/orama-cloud-legacy.ts:40-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud-legacy.ts#L40-L44) The client supports two indexing strategies: `default` (structured Fumadocs JSON indexes) and `crawler` (web crawler indexes). When `index` is set to `'crawler'`, search queries target the web crawler datasource, grouping results into page and text items. ```typescript if (index === 'crawler') { const result = await client.search({ datasources: [], ...extraParams, term: query, where: { category: tag ? { eq: tag.slice(0, 1).toUpperCase() + tag.slice(1), } : undefined, ...extraParams?.where, }, limit: 10, }); ``` Sources: [packages/core/src/search/client/orama-cloud.ts:49-63](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud.ts#L49-L63) In `default` mode, queries invoke `client.search` with a maximum limit of 20 results, grouping matches by `page_id` with up to 7 results per group. The resulting grouped hits are mapped into `SortedResult` objects using `createContentHighlighter` to process markdown highlights. ```typescript const result = await client.search({ datasources: [], ...extraParams, term: query, limit: 20, where: removeUndefined({ tag, ...extraParams?.where, }), groupBy: { properties: ['page_id'], max_results: 7, ...extraParams?.groupBy, }, }); ``` Sources: [packages/core/src/search/client/orama-cloud.ts:88-102](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud.ts#L88-L102) > [!WARNING] > In `oramaCloudClient`, if the total mapped result list exceeds 80 items, the client slices the array to a maximum length of 80 before returning. Sources: [packages/core/src/search/client/orama-cloud.ts:131-131](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud.ts#L131-L131) ### Orama Search Dialog Integration The `OramaSearchDialog` component integrates Orama Cloud search into application dialogs using [Base UI Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/base-ui-components), accepting client instances, parameters, and tag configurations. ```tsx export default function OramaSearchDialog({ client, searchOptions, tags = [], defaultTag, showOrama = true, allowClear = false, index, footer, links = [], ...props }: OramaSearchDialogProps) { const { locale } = useI18n(); const [tag, setTag] = useState(defaultTag); const { search, setSearch, query } = useDocsSearch({ client: oramaCloudClient({ client, index, params: searchOptions, locale, tag, }), }); ``` Sources: [packages/base-ui/src/components/dialog/search-orama.tsx:54-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-orama.tsx#L54-L76) | Prop Name | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `client` | `OramaCloudOptions['client']` | — | Orama Cloud client instance. | | `searchOptions` | `OramaCloudOptions['params']` | `undefined` | Additional search parameters. | | `index` | `OramaCloudOptions['index']` | `undefined` | Index type (`'default'` or `'crawler'`). | | `tags` | `TagItem[]` | `[]` | List of filter tags for the dialog footer. | | `defaultTag` | `string` | `undefined` | Initial active filter tag. | | `showOrama` | `boolean` | `true` | Controls the visibility of the "Search powered by Orama" branding label. | | `allowClear` | `boolean` | `false` | Allows users to clear active tag filters. | | `links` | `SearchLink[]` | `[]` | Fallback links when no search query is active. | Sources: [packages/base-ui/src/components/dialog/search-orama.tsx:25-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-orama.tsx#L25-L49) ## Static Orama and Flexsearch Engines ### Static Orama Client Implementation Fumadocs provides client execution for in-browser static search indices through `oramaStaticClient`. The client accepts `StaticOptions` configuration parameters governing index fetching, schema initialization, tag filtering, and localized database management. ```typescript export interface StaticOptions { /** * Where to download exported search indexes (URL) * * @defaultValue '/api/search' */ from?: string; initOrama?: (locale?: string) => AnyOrama | Promise; /** * Filter results with specific tag(s). */ tag?: string | string[]; /** * Filter by locale (unsupported at the moment) */ locale?: string; /** * extra options for search */ search?: Partial>>; } ``` Sources: [packages/core/src/search/client/orama-static.ts:8-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-static.ts#L8-L32) | Option Name | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `from` | `string` | `'/api/search'` | URL endpoint to download exported search indexes. | | `initOrama` | `(locale?: string) => AnyOrama \| Promise` | `create({ schema: { _: 'string' }, language: locale })` | Custom Orama instance initializer per locale. | | `tag` | `string \| string[]` | `undefined` | Filter results by specific tag(s). | | `locale` | `string` | `undefined` | Filter by locale. | | `search` | `Partial>>` | `undefined` | Extra parameters for search execution. | Sources: [packages/core/src/search/client/orama-static.ts:8-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-static.ts#L8-L32) Database loading is handled asynchronously via `loadDB`, which fetches exported index payloads and populates an in-memory database map cache keyed by locale. When internationalization data types are encountered, instances are built per locale entry, whereas single-index payloads initialize a default empty locale key. ```typescript async function loadDB( from: string, initOrama: StaticOptions['initOrama'] = (locale) => create({ schema: { _: 'string' }, language: locale }), ): Promise { const res = await fetch(from); if (!res.ok) throw new Error( `failed to fetch exported search indexes from ${from}, make sure the search database is exported and available for client.`, ); const data = (await res.json()) as ExportedData; const dbs: Database = new Map(); if (data.type === 'i18n') { await Promise.all( Object.entries(data.data).map(async ([k, v]) => { const db = await initOrama(k); load(db, v); dbs.set(k, { type: v.type, db, }); }), ); } else { const db = await initOrama(); load(db, data); dbs.set('', { type: data.type, db, }); } return dbs; } ``` Sources: [packages/core/src/search/client/orama-static.ts:45-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-static.ts#L45-L82) > [!WARNING] > If a requested locale is missing from the loaded database collection, `oramaStaticClient` logs a warning message and falls back to the first available database value in the map. Sources: [packages/core/src/search/client/orama-static.ts:104-109](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-static.ts#L104-L109) Execution branches between simple and advanced search helpers depending on the database type property (`'simple'` or `'advanced'`). Simple searches delegate to `searchSimple` with tolerance and title boost configurations, while advanced searches use `searchAdvanced` with `groupBy` page ID properties and tag filters. ```typescript export async function searchSimple( db: Orama, query: string, params: Partial, SimpleDocument>> = {}, ): Promise { const highlighter = createContentHighlighter(query); const result = await search(db, { term: query, tolerance: 1, ...params, boost: { title: 2, ...('boost' in params ? params.boost : undefined), }, }); ``` Sources: [packages/core/src/search/orama/search/simple.ts:5-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/simple.ts#L5-L19) ```typescript export async function searchAdvanced( db: Orama, query: string, tag: string | string[] = [], { mode = 'fulltext', ...override }: Partial, AdvancedDocument>> = {}, ): Promise { if (typeof tag === 'string') tag = [tag]; const params = { limit: 60, mode, ...override, where: removeUndefined({ tags: tag.length > 0 ? { containsAll: tag, } : undefined, ...override.where, }), groupBy: { properties: ['page_id'], maxResult: 8, ...override.groupBy, }, properties: mode === 'fulltext' ? ['content'] : ['content', 'embeddings'], } as SearchParams; ``` Sources: [packages/core/src/search/orama/search/advanced.ts:6-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama/search/advanced.ts#L6-L36) ### Static Flexsearch Client Implementation Local in-browser client execution using Flexsearch is provided by `flexsearchStaticClient`. The client accepts `FlexsearchStaticOptions` to configure endpoint fetching, default locales, and tags. ```typescript export interface FlexsearchStaticOptions { /** * @defaultValue `/api/search` */ from?: string; locale?: string; tag?: string | string[]; } ``` Sources: [packages/core/src/search/client/flexsearch-static.ts:6-13](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts#L6-L13) | Option Name | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `from` | `string` | `'/api/search'` | URL endpoint to download exported Flexsearch indexes. | | `locale` | `string` | `''` | Target locale key for querying. | | `tag` | `string \| string[]` | `undefined` | Optional tag filter for search queries. | Sources: [packages/core/src/search/client/flexsearch-static.ts:6-13](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts#L6-L13) The initialization routine checks whether `window` is defined before executing the asynchronous fetch function `init`. It parses exported JSON payloads, iterating over internationalized raw records or standard document maps to instantiate Flexsearch document wrappers via `initDocument`. ```typescript function initDocument(data: Record) { const document = createDocument(); for (const [k, v] of Object.entries(data)) document.import(k, v); return document; } ``` Sources: [packages/core/src/search/client/flexsearch-static.ts:15-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts#L15-L19) ```typescript async function init(from: string) { const res = await fetch(from); if (!res.ok) throw new Error( `failed to fetch exported search indexes from ${from}, make sure the search database is exported and available for client.`, ); const data = (await res.json()) as ExportedData; const dbs = new Map>(); if (data.type === 'i18n') { for (const [locale, map] of Object.entries(data.raw)) { dbs.set(locale, initDocument(map)); } return dbs; } else { dbs.set('', initDocument(data.raw)); } return dbs; ``` Sources: [packages/core/src/search/client/flexsearch-static.ts:43-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts#L43-L64) > [!NOTE] > `flexsearchStaticClient` registers dependency tracking for `from`, `locale`, and `tag`, returning an empty array if the requested locale database has not been loaded into the map cache. Sources: [packages/core/src/search/client/flexsearch-static.ts:33-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/flexsearch-static.ts#L33-L39) ## Algolia Search Client and Grouping ### Algolia Lite Client Adapter The Algolia client implementation provides search integration via `algoliaClient`, accepting `AlgoliaOptions` to configure the target index, search client instance, tag filters, locale, and an optional custom `onSearch` handler function. ```typescript export interface AlgoliaOptions { indexName: string; client: LiteClient; /** * Filter results with specific tag. */ tag?: string; locale?: string; onSearch?: ( query: string, tag?: string, locale?: string, ) => Promise<{ results: SearchResponse[]; }>; } ``` Sources: [packages/core/src/search/client/algolia.ts:6-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts:6-24) | Option Name | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `indexName` | `string` | *required* | Target Algolia index name. | | `client` | `LiteClient` | *required* | Algolia lite client instance. | | `tag` | `string` | `undefined` | Optional tag filter string (`tag:${tag}`). | | `locale` | `string` | `undefined` | Optional locale identifier passed to custom search handlers. | | `onSearch` | `Function` | `undefined` | Custom search function overriding default requests. | Sources: [packages/core/src/search/client/algolia.ts:6-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts:6-24) > [!WARNING] > If the search query string contains only whitespace or is empty after trimming (`query.trim().length === 0`), `algoliaClient` immediately returns an empty array without executing a network request. Sources: [packages/core/src/search/client/algolia.ts:58-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts:58-59) ### Hierarchical Hit Grouping and Execution Flow When executing a search request, `algoliaClient` checks whether a custom `onSearch` function is provided; otherwise, it invokes `client.searchForHits` with a request configuration containing a distinct value of `5`, `hitsPerPage` set to `10`, and an optional tag filter. The resulting hits are processed by `groupResults` to construct a hierarchical list of pages, headings, and text blocks. ```typescript const result = onSearch ? await onSearch(query, tag, locale) : await client.searchForHits({ requests: [ { type: 'default', indexName, query, distinct: 5, hitsPerPage: 10, filters: tag ? `tag:${tag}` : undefined, }, ], }); ``` Sources: [packages/core/src/search/client/algolia.ts:61-75](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts:61-75) ```mermaid sequenceDiagram participant AlgoliaSearchDialog as AlgoliaSearchDialog participant algoliaClient as algoliaClient participant groupResults as groupResults AlgoliaSearchDialog->>algoliaClient: search(query) algoliaClient->>groupResults: groupResults(hits) groupResults-->>algoliaClient: SortedResult[] algoliaClient-->>AlgoliaSearchDialog: highlighted results ``` Sources: [packages/base-ui/src/components/dialog/search-algolia.tsx:61-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search-algolia.tsx#L61-L67), [packages/core/src/search/client/algolia.ts:26-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts#L26-L52), [packages/core/src/search/client/algolia.ts:58-87](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts#L58-L87) The grouping function `groupResults` tracks scanned URLs in a `Set`. For each unique URL encountered, it pushes a parent page result into the accumulator array before appending individual section or text hits with constructed anchor URLs. ```typescript function groupResults(hits: Hit[]): SortedResult[] { const grouped: SortedResult[] = []; const scannedUrls = new Set(); for (const hit of hits) { if (!scannedUrls.has(hit.url)) { scannedUrls.add(hit.url); grouped.push({ id: hit.url, type: 'page', breadcrumbs: hit.breadcrumbs, url: hit.url, content: hit.title, }); } grouped.push({ id: hit.objectID, type: hit.content === hit.section ? 'heading' : 'text', url: hit.section_id ? `${hit.url}#${hit.section_id}` : hit.url, content: hit.content, }); } return grouped; } ``` Sources: [packages/core/src/search/client/algolia.ts:26-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/algolia.ts:26-52) ## Mixedbread Client Vector Retrieval ### Mixedbread Options and Heading Transformations The Mixedbread client integration supports vector search queries against a remote store via `mixedbreadClient` or server-side endpoints through `createMixedbreadSearchAPI`. `MixedbreadOptions` defines the configuration required to connect to a store instance using the Mixedbread SDK client. ```typescript export interface MixedbreadOptions { /** * The identifier of the store to search in */ storeIdentifier: string; /** * The Mixedbread SDK client instance */ client: Mixedbread; /** * Filter results with specific tag. */ tag?: string; /** * Filter by locale (unsupported at the moment) */ locale?: string; } ``` Sources: [packages/core/src/search/client/mixedbread.ts:8-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:8-28) | Option Name | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `storeIdentifier` | `string` | *required* | The identifier of the store to search in. | | `client` | `Mixedbread` | *required* | The Mixedbread SDK client instance. | | `tag` | `string` | `undefined` | Filter results with a specific tag. | | `locale` | `string` | `undefined` | Filter by locale (unsupported at the moment). | Sources: [packages/core/src/search/client/mixedbread.ts:8-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:8-28) > [!WARNING] > `mixedbreadClient` is deprecated because running client-side SDK queries exposes your API key in the browser. The recommended approach is to use `createMixedbreadSearchAPI` on the server and connect with a fetch client on the client. Sources: [packages/core/src/search/client/mixedbread.ts:63-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:63-67) ### Search Execution and Chunk Processing When a search query is submitted, `mixedbreadClient` queries `client.stores.search` requesting a top-k limit of 10 items with metadata enabled and tag filtering applied via `generated_metadata.tag`. Each returned search result chunk is expanded into structured page and heading results. ```typescript async search(query) { if (!query.trim()) { return []; } const res = await client.stores.search({ query, store_identifiers: [storeIdentifier], top_k: 10, filters: { key: 'generated_metadata.tag', operator: 'eq', value: tag, }, search_options: { return_metadata: true, }, }); ``` Sources: [packages/core/src/search/client/mixedbread.ts:73-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:73-90) ```typescript return (res.data as StoreSearchResult[]).flatMap((item) => { const metadata = item.generated_metadata; const url = metadata.url || '#'; const title = metadata.title || 'Untitled'; const chunkResults: SortedResult[] = [ { id: `${item.file_id}-${item.chunk_index}-page`, type: 'page', content: title, url, }, ]; const headingTitle = item.type === 'text' && item.text ? extractHeadingTitle(item.text) : ''; if (headingTitle) { slugger.reset(); chunkResults.push({ id: `${item.file_id}-${item.chunk_index}-heading`, type: 'heading', content: headingTitle, url: `${url}#${slugger.slug(headingTitle)}`, }); } return chunkResults; }); ``` Sources: [packages/core/src/search/client/mixedbread.ts:92-122](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:92-122) The helper function `extractHeadingTitle` inspects text content to verify whether it starts with a markdown heading indicator (`#`). If it does, the first line is split, cleaned with `removeMarkdown` with image alt text disabled, and slugified using `github-slugger` for anchor URL generation. ```typescript function extractHeadingTitle(text: string): string { const trimmedText = text.trim(); if (!trimmedText.startsWith('#')) { return ''; } const lines = trimmedText.split('\n'); const firstLine = lines[0]?.trim(); if (firstLine) { // Use remove-markdown to convert to plain text and remove colons return removeMd(firstLine, { useImgAltText: false, }); } return ''; } ``` Sources: [packages/core/src/search/client/mixedbread.ts:43-61](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:43-61) > [!NOTE] > `slugger.reset()` is invoked before processing each heading title to ensure deterministic slug generation across chunk result iterations. Sources: [packages/core/src/search/client/mixedbread.ts:111-111](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/mixedbread.ts:111-111) ## Search Context and Keyboard Shortcuts ### Global Search Context and Provider Architecture The `SearchProvider` component establishes global search state using `SearchContext`, exposing options for dialog preloading, custom empty-state links, and hotkey bindings. When `preload` is enabled (defaulting to `true`), the search dialog state is initialized to `undefined` until the dialog is opened, triggering lazy loading of `DefaultSearchDialog`. ```tsx export function SearchProvider({ SearchDialog = DefaultSearchDialog, children, preload = true, options, hotKey = DEFAULT_HOT_KEYS, links, }: SearchProviderProps) { const [isOpen, setIsOpen] = useState(preload ? false : undefined); const onKeyDown = useEffectEvent((e: KeyboardEvent) => { if (hotKey.every((v) => (typeof v.key === 'string' ? e.key === v.key : v.key(e)))) { setIsOpen((open) => !open); e.preventDefault(); } }); useEffect(() => { window.addEventListener('keydown', onKeyDown); return () => { window.removeEventListener('keydown', onKeyDown); }; }, []); return ( ({ enabled: true, open: isOpen ?? false, hotKey, setOpenSearch: setIsOpen, }), [isOpen, hotKey], )} > {isOpen !== undefined && ( )} {children} ); } ``` Sources: [packages/base-ui/src/contexts/search.tsx:112-162](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx#L112-L162) | Property | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `preload` | `boolean` | `true` | Preload search dialog before opening it. | | `links` | `SearchLink[]` | `undefined` | Custom links to be displayed if search is empty. | | `hotKey` | `HotKey[]` | `DEFAULT_HOT_KEYS` | Hotkeys for triggering the search dialog. | | `SearchDialog` | `ComponentType` | `DefaultSearchDialog` | Replace default search dialog (e.g. Algolia Search). | | `options` | `Partial>` | `undefined` | Additional properties passed to the dialog. | Sources: [packages/base-ui/src/contexts/search.tsx:36-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx#L36-L69) > [!NOTE] > The `SearchOnly` wrapper component inspects `search.enabled` from the context and renders its children only when search has been successfully initialized via a provider. Sources: [packages/base-ui/src/contexts/search.tsx:164-171](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx#L164-L171) ### Hotkey Bindings and Platform Detection Keyboard shortcuts are managed via global window event listeners registered inside `SearchProvider`. The default hotkey configuration `DEFAULT_HOT_KEYS` combines a modifier key condition with the `k` key. ```tsx const DEFAULT_HOT_KEYS: HotKey[] = [ { key: (e) => e.metaKey || e.ctrlKey, display: , }, { key: 'k', display: 'K', }, ]; ``` Sources: [packages/base-ui/src/contexts/search.tsx:99-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx#L99-L108) The `MetaOrControl` helper component checks `window.navigator.userAgent` against a regular expression testing for Windows or Linux platforms to dynamically switch the displayed shortcut symbol between `⌘` and `Ctrl`. ```tsx function MetaOrControl() { const [key, setKey] = useState('⌘'); useEffect(() => { if (/Windows|Linux/i.test(window.navigator.userAgent)) setKey('Ctrl'); }, []); return key; } ``` Sources: [packages/base-ui/src/contexts/search.tsx:89-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx#L89-L97) > [!WARNING] > `onKeyDown` evaluates every configured hotkey item in `hotKey` using `.every()`. If `v.key` is a function, it receives the native `KeyboardEvent`; otherwise, it matches `e.key === v.key`. When all match, `setIsOpen` toggles the dialog state and `e.preventDefault()` is invoked. Sources: [packages/base-ui/src/contexts/search.tsx:121-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/search.tsx#L121-L126) ### AI Search Context and Preview Trigger Integration The `AISearch` component provides a separate React context specifically for AI chat search integration, wrapping state for `open`, `setOpen`, and `chat` helpers initialized via `@ai-sdk/react`. ```tsx export function AISearch({ children }: { children: ReactNode }) { const [open, setOpen] = useState(false); const chat = useChat({ id: 'search', transport: new DefaultChatTransport({ api: '/api/chat', }), }); return ( ({ chat, open, setOpen }), [chat, open])}>{children} ); } ``` Sources: [packages/preview/src/components/ai/search.tsx:292-304](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/ai/search.tsx#L292-L304) Trigger components such as `AISearchTrigger` consume this context to toggle visibility and update `data-state` attributes (`open` or `closed`). When `position` is set to `float`, the trigger button fixes its layout at the bottom corner with transition animations. ```tsx export function AISearchTrigger({ position = 'default', className, ...props }: ComponentProps<'button'> & { position?: 'default' | 'float' }) { const { open, setOpen } = useAISearchContext(); return ( ); } ``` Sources: [packages/preview/src/components/ai/search.tsx:306-329](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/ai/search.tsx#L306-L329) ## Related - [Search Server Indexing](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/search-server-indexing) - [Base UI Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/base-ui-components) --- ## Technical docs: Syntax Highlighting URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting
Relevant source files The following files were used as context for generating this wiki page: - [packages/core/src/mdx-plugins/rehype-code/shiki.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts) - [packages/core/src/highlight/shiki/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/index.ts) - [packages/core/src/mdx-plugins/rehype-code.core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code.core.ts) - [packages/twoslash/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/src/index.ts) - [packages/core/src/mdx-plugins/transformer-icon.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/transformer-icon.ts) - [packages/base-ui/css/lib/shiki.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css) - [packages/radix-ui/css/lib/shiki.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/lib/shiki.css) - [packages/core/src/highlight/shiki/full.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/full.ts) - [packages/core/src/mdx-plugins/remark-code-tab.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts) - [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts) - [packages/core/src/mdx-plugins/rehype-code.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code.ts) - [packages/shadcn/src/manual-installation.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts) - [packages/typescript/src/lib/remark-auto-type-table.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/src/lib/remark-auto-type-table.ts) - [packages/core/src/highlight/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/index.ts) - [packages/core/src/highlight/shiki/react.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/react.ts) - [packages/base-ui/src/components/codeblock.rsc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.rsc.tsx) - [packages/core/src/mdx-plugins/rehype-code/parsers.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/parsers.ts) - [packages/mdx/src/webpack/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts) - [packages/core/src/mdx-plugins/codeblock-utils.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/codeblock-utils.ts) - [packages/core/src/mdx-plugins/remark-llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts) - [packages/radix-ui/src/components/dynamic-codeblock.core.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx) - [packages/typescript/src/markdown.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/src/markdown.ts) - [packages/core/src/mdx-plugins/remark-structure.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts) - [packages/core/src/highlight/client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/client.ts) - [packages/obsidian/src/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts) - [packages/preview/src/components/markdown.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/markdown.tsx) - [packages/base-ui/src/components/dynamic-codeblock.core.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dynamic-codeblock.core.tsx) - [packages/radix-ui/src/components/codeblock.rsc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.rsc.tsx) - [packages/core/src/mdx-plugins/remark-mdx-files.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-files.ts) - [packages/core/src/mdx-plugins/stringifier.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/stringifier.ts)
## Overview Syntax Highlighting provides robust code block and inline syntax highlighting in Fumadocs by integrating Shiki into unified and remark-rehype processing pipelines. It intercepts code and pre elements during AST traversal, parses meta string attributes such as line numbers and titles, applies transformers for diffing, focusing, and file icons, and supports asynchronous client-side highlighting via React hooks and runtime state management. Sources: [packages/core/src/mdx-plugins/rehype-code/shiki.ts:116-222](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L116-L222), [packages/core/src/mdx-plugins/rehype-code.core.ts:19-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code.core.ts#L19-L46), [packages/core/src/highlight/shiki/react.ts:27-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/react.ts#L27-L59) ## Unified Rehype Shiki Pipeline ### Rehype AST Visitor and Element Interception The processor traverses the HAST tree using `unist-util-visit` to locate specific elements targeted for syntax highlighting. When the visitor encounters an element node matching `pre` or an inline `code` element where inline parsing is enabled, it delegates parsing to specialized parsers such as `PreParser` or `InlineCodeParsers`. Each candidate node must possess a valid parent and index to permit safe HAST node replacement. ```typescript return async (tree) => { const queue: Promise[] = []; visit(tree, 'element', (node, index, parent) => { let parsed: ShikiParsedData | undefined; // needed for hast node replacement if (!parent || index == null) return; if (node.tagName === 'pre') { parsed = PreParser(tree, node); } else if (node.tagName === 'code' && inline) { parsed = InlineCodeParsers[inline](tree, node); ``` Sources: [packages/core/src/mdx-plugins/rehype-code/shiki.ts:210-222](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L210-L222) > [!WARNING] > Nodes lacking a parent or index in the HAST tree are silently skipped during the AST traversal visitor callback. This safeguard prevents runtime reference errors when mutating the syntax tree structure. Sources: [packages/core/src/mdx-plugins/rehype-code/shiki.ts:216-217](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L216-L217) ### Highlighter Core Delegation and Caching Once a code element or pre block is intercepted, `onNode` extracts its metadata string, language identifier, and raw code content. If the designated language is not currently loaded in the core highlighter instance and lazy loading is active, it attempts to load the grammar dynamically from bundled languages or apply a fallback language. Before invoking the high-cost highlighter engine, the pipeline constructs a cache key incorporating the language, filtered meta string, and raw code. If a matching entry exists in the custom cache map, the cached HAST fragment is returned directly. Otherwise, transformers configured with post-enforcement extract asynchronous post-processing tasks, option mappings are assembled, trailing newlines are stripped when enabled, and `highlighter.codeToHast` is executed. ```typescript async function onNode( tree: Root, node: Element, parsed: ShikiParsedData, ): Promise { let { meta: metaString = '', lang = defaultLanguage, code } = parsed; if (!lang) return; if (!isLanguageLoaded(lang)) { if (lazy && lang in highlighter.getBundledLanguages()) { await highlighter.loadLanguage(lang as never); } else if (fallbackLanguage) { lang = fallbackLanguage; if (!isLanguageLoaded(fallbackLanguage)) await highlighter.loadLanguage(fallbackLanguage as never); } } if (filterMetaString) { metaString = filterMetaString(metaString); } const cacheKey = `${lang}:${metaString}:${code}`; const cachedValue = cache?.get(cacheKey); if (cachedValue) { return cachedValue; } const transformers = rest.transformers ? [...rest.transformers] : []; let _fd_postprocess: ShikiTransformerContextMeta['_fd_postprocess']; transformers.push({ enforce: 'post', root() { _fd_postprocess = this.meta._fd_postprocess; }, }); if (addLanguageClass) transformers.push(transformerAddLanguage(lang)); const codeOptions: CodeToHastOptions = { ...rest, lang, structure: parsed.structure, transformers, meta: { ...rest.meta, __raw: metaString, ...parseMetaString?.(metaString, node, tree), }, }; if (stripEndNewline && code.endsWith('\n')) code = code.slice(0, -1); const fragment = highlighter.codeToHast(code, codeOptions); if (_fd_postprocess && _fd_postprocess.length > 0) { const ctx = { highlighter }; await Promise.all(_fd_postprocess.map((v) => v(ctx))); } cache?.set(cacheKey, fragment); if (parsed.structure === 'classic') return fragment; return { type: 'element', tagName: 'code', properties: { class: 'shiki', }, children: fragment.children as ElementContent[], }; } ``` Sources: [packages/core/src/mdx-plugins/rehype-code/shiki.ts:138-208](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L138-L208) > [!NOTE] > When `stripEndNewline` is set to `true`, trailing newline characters added by `mdast-util-to-hast` are automatically removed from the source string prior to passing it into Shiki's highlighter engine. Sources: [packages/core/src/mdx-plugins/rehype-code/shiki.ts:54-61](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L54-L61), [packages/core/src/mdx-plugins/rehype-code/shiki.ts:189-189](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L189-L189) ### Extra Configuration Options Reference The `RehypeShikiExtraOptions` interface governs behavior flags for language resolution, meta parsing, caching, and error handling during pipeline execution. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `addLanguageClass` | `boolean` | `false` | Add `language-*` class to code element. | | `defaultLanguage` | `string` | `undefined` | The default language to use when not specified. | | `fallbackLanguage` | `string` | `undefined` | The fallback language to use when specified language is not loaded or bundled. | | `lazy` | `boolean` | `true` | Load languages and themes on-demand. | | `stripEndNewline` | `boolean` | `true` | Strip trailing newline added by `mdast-util-to-hast`. | | `parseMetaString` | `Function` | `undefined` | Custom meta string parser returning an object to merge with `meta`. | | `filterMetaString` | `Function` | `undefined` | Filter meta string before processing. | | `inline` | `InlineCodeParser \| false` | `false` | Highlight inline code blocks (e.g., `tailing-curly-colon`). | | `cache` | `MapLike` | `undefined` | Custom map to cache transformed `codeToHast` results. | | `onError` | `Function` | `undefined` | Error handler callback; throws if not provided. | Sources: [packages/core/src/mdx-plugins/rehype-code/shiki.ts:28-101](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/shiki.ts#L28-L101) ## Theme Resolution and Highlighting Engine ### Highlighter Factory Lifecycle The management and initialization of Shiki instances are coordinated through the `ShikiFactory` interface and `createShikiFactory` builder function. The factory pattern holds a cached instance or awaits initialization when `getOrInit` is called, ensuring that highlighter instances are instantiated on demand without redundant creation overhead. Two predefined factories are supplied: `defaultShikiFactory`, which provisions a standard highlighter instance utilizing the JavaScript regular expression engine, and `wasmShikiFactory`, which initializes a highlighter powered by the Oniguruma WebAssembly regex engine via `createOnigurumaEngine(import('shiki/wasm'))`. Both factories initialize with empty language and theme arrays, letting callers register grammars dynamically. ```typescript /** * A factory for Fumadocs to manage Shiki instances. */ export interface ShikiFactory { init: (options?: InitOptions) => Awaitable; getOrInit: () => Awaitable; } export function createShikiFactory(config: Pick): ShikiFactory { let instance: Awaitable | undefined; return { init(options) { return (instance = config.init(options)); }, getOrInit() { return instance ?? this.init(); }, }; } ``` Sources: [packages/core/src/highlight/shiki/index.ts:17-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/index.ts#L17-L36) ```typescript export const defaultShikiFactory = createShikiFactory({ async init(options) { const { createHighlighter, createJavaScriptRegexEngine } = await import('shiki'); return createHighlighter({ langs: [], themes: [], langAlias: options?.langAlias, engine: createJavaScriptRegexEngine(), }); }, }); /** factory using the WASM powered Regex engine */ export const wasmShikiFactory = createShikiFactory({ async init(options) { const { createHighlighter, createOnigurumaEngine } = await import('shiki'); return createHighlighter({ langs: [], themes: [], langAlias: options?.langAlias, engine: createOnigurumaEngine(import('shiki/wasm')), }); }, ``` Sources: [packages/core/src/highlight/shiki/full.ts:3-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/full.ts#L3-L27) > [!NOTE] > The `getOrInit` method returns the cached highlighter instance if available, falling back to invoking `init()` if the internal instance variable is undefined. Sources: [packages/core/src/highlight/shiki/index.ts:32-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/index.ts#L32-L34) ### Theme and Language Loading Theme resolution and grammar loading inspect incoming options against the active highlighter core. The high-level `highlight` and `highlightHast` functions accept `HighlightHastOptions`, which allow selecting the regex engine via the `engine` property (`'js'` or `'oniguruma'`). 1. `ServerCodeBlock` invokes `highlight` with the code string and options. 2. `highlight` retrieves or initializes the appropriate highlighter core via `factory.getOrInit()`. 3. `highlightHast` (base implementation) resolves the target language, checking special language status and verifying if it is present in bundled or loaded languages; if missing, it falls back to `fallbackLanguage` (defaulting to `'text'`). 4. `highlightHast` resolves missing themes using `loadMissingTheme` and loads the required language asynchronously using `highlighter.loadLanguage()`, before invoking `highlighter.codeToHast` to produce the HAST root tree. ```typescript export async function highlightHast( highlighter: HighlighterCore, code: string, options: HighlightHastOptions, ): Promise { const { fallbackLanguage = 'text', ...resolved } = options; const { isSpecialLang } = await import('shiki/core'); if ( !isSpecialLang(resolved.lang) && !(resolved.lang in highlighter.getBundledLanguages()) && !highlighter.getLoadedLanguages().includes(resolved.lang) ) { resolved.lang = fallbackLanguage; } await Promise.all([ loadMissingTheme(highlighter, getRequiredThemes(resolved)), highlighter.loadLanguage(resolved.lang as never), ]); return highlighter.codeToHast(code, resolved); ``` Sources: [packages/core/src/highlight/shiki/index.ts:44-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/index.ts#L44-L64) ```typescript export async function highlightHast(code: string, options: HighlightHastOptions): Promise { const engine = options.engine ?? 'js'; const factory = engine === 'js' ? defaultShikiFactory : wasmShikiFactory; const instance = await factory.getOrInit(); return highlightHastBase(instance, code, applyDefaultThemes(options)); } ``` Sources: [packages/core/src/highlight/index.ts:33-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/index.ts#L33-L39) ```mermaid sequenceDiagram participant ServerCodeBlock as packages/radix-ui/src/components/codeblock.rsc.tsx participant highlight as packages/core/src/highlight/index.ts participant highlightHastBase as packages/core/src/highlight/shiki/index.ts ServerCodeBlock->>highlight: highlight(code, options) highlight->>highlightHastBase: highlightHast(instance, code, options) highlightHastBase->>highlightHastBase: highlightHast(highlighter, code, options) ``` Sources: [packages/radix-ui/src/components/codeblock.rsc.tsx:16-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.rsc.tsx#L16-L32), [packages/core/src/highlight/index.ts:33-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/index.ts#L33-L39), [packages/core/src/highlight/shiki/index.ts:44-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/index.ts#L44-L64) > [!CAUTION] > If a requested language is neither a special language, present in bundled languages, nor loaded in the highlighter instance, it is silently overridden with the `fallbackLanguage`. Sources: [packages/core/src/highlight/shiki/index.ts:51-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/index.ts#L51-L57) ### AST Formatting and React Node Rendering Once `codeToHast` returns the HAST `Root` node, `highlight` transforms the syntax tree into React nodes using `toJsxRuntime`. The formatting pipeline integrates the JSX runtime elements with custom component overrides supplied via `options.components`, which map pre elements to specialized wrapper components such as `ServerCodeBlock`. ```typescript export async function highlight(code: string, options: HighlightOptions): Promise { return toJsxRuntime(await highlightHast(code, options), { ...JsxRuntime, development: false, components: options.components, }); ``` Sources: [packages/core/src/highlight/index.ts:64-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/index.ts#L64-L69) ```tsx export async function ServerCodeBlock({ code, codeblock, ...options }: ServerCodeBlockProps) { return await highlight(code, { defaultColor: false, ...options, components: { pre: (props) => (
{props.children}
), ...options.components, }, }); ``` Sources: [packages/radix-ui/src/components/codeblock.rsc.tsx:16-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.rsc.tsx#L16-L32) ## Code Block Attribute Parsing ### Pre Block Metadata and Inline Code Parsing The parsing pipeline inspects HAST nodes to extract code block metadata, language tags, and raw content from both classic fenced code blocks and inline code expressions. The `PreParser` function examines the first child element of a pre node, verifying that its tag name is `code` and that it possesses valid properties. It searches `head.properties.className` for any class string starting with `language-`, slicing off the prefix to determine the language identifier. Concurrently, it extracts metadata by checking `head.data?.meta` or falling back to `head.properties.metastring` as a string, defaulting to an empty string if neither exists. ```typescript export const PreParser: ShikiParser = (_tree, node) => { const head = node.children[0]; if (!head || head.type !== 'element' || head.tagName !== 'code' || !head.properties) { return; } const classes = head.properties.className; const languageClass = Array.isArray(classes) ? classes.find((d) => typeof d === 'string' && d.startsWith(languagePrefix)) : undefined; return { structure: 'classic', lang: typeof languageClass === 'string' ? languageClass.slice(languagePrefix.length) : undefined, code: flattenNodeHast(head), meta: head.data?.meta ?? head.properties.metastring?.toString() ?? '', }; ``` Sources: [packages/core/src/mdx-plugins/rehype-code/parsers.ts:33-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/parsers.ts#L33-L51) For inline code elements, the `InlineCodeParsers` record provides the `'tailing-curly-colon'` parser. This parser flattens the HAST node into a raw string and matches it against the regular expression `RE_TAILING_CURLY_COLON` (`/(+)\{:([\w-]+)\}$/`). When a match occurs, it yields an inline structure type, extracts the code content from the first capture group, and retrieves the language identifier from the second capture group using `match.at(2)`. ```typescript const RE_TAILING_CURLY_COLON = /(.+)\{:([\w-]+)\}$/; export interface ShikiParsedData { meta?: string; lang?: string; code: string; structure: 'inline' | 'classic'; } export type ShikiParser = (tree: Root, node: Element) => ShikiParsedData | undefined; export type InlineCodeParser = 'tailing-curly-colon'; export const InlineCodeParsers: Record = { 'tailing-curly-colon': (_tree, node) => { const raw = flattenNodeHast(node); const match = raw.match(RE_TAILING_CURLY_COLON); if (!match) return; return { structure: 'inline', code: match[1] ?? raw, lang: match.at(2), }; }, }; ``` Sources: [packages/core/src/mdx-plugins/rehype-code/parsers.ts:4-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/parsers.ts#L4-L29) > [!WARNING] > If a pre element contains no children, or if its first child is not a code element, `PreParser` returns undefined without extracting any language or metadata. Sources: [packages/core/src/mdx-plugins/rehype-code/parsers.ts:33-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/parsers.ts#L33-L38) ### Meta String Attribute Extraction Fumadocs-style attributes embedded within code block meta strings—such as `title="hello world"`—are parsed via `parseCodeBlockAttributes`. This utility uses `AttributeRegex` (`/(?<=^|\s)(?[a-zA-Z0-9_-]+)(?:=(?:"([^"]*)"|'([^']*)'))?/g`) to scan the meta string. It extracts attribute names alongside double-quoted or single-quoted string values, storing them in an attributes dictionary while stripping matched attributes from the remaining string output (`rest`). If `allowedNames` are specified, any attribute whose name is absent from the allowed list is ignored and left in the rest string. ```typescript export interface CodeBlockAttributes { attributes: Partial>; rest: string; } const AttributeRegex = /(?<=^|\s)(?[a-zA-Z0-9_-]+)(?:=(?:"([^"]*)"|'([^']*)'))?/g; /** * Parse Fumadocs-style code block attributes from meta string, like `title="hello world"` */ export function parseCodeBlockAttributes( meta: string, allowedNames?: Name[], ): CodeBlockAttributes { const attributes: CodeBlockAttributes['attributes'] = {}; const rest = meta.replaceAll(AttributeRegex, (match, name, value_1, value_2) => { if (allowedNames && !allowedNames.includes(name)) return match; attributes[name] = value_1 ?? value_2 ?? null; return ''; }); return { rest, attributes, }; } ``` Sources: [packages/core/src/mdx-plugins/codeblock-utils.ts:89-115](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/codeblock-utils.ts#L89-L115) | Function / Parser | Target Input | Return Structure | Key Behavior | | :--- | :--- | :--- | :--- | | `PreParser` | HAST `Element` (`pre`) | `ShikiParsedData` (`classic`) | Scans child code element classes for `language-` prefix and extracts `metastring` or `meta` data. | | `InlineCodeParsers['tailing-curly-colon']` | HAST `Element` (`code`) | `ShikiParsedData` (`inline`) | Matches trailing `{:lang}` syntax to separate code content from inline language specifiers. | | `parseCodeBlockAttributes` | Meta string (`string`) | `CodeBlockAttributes` | Parses key-value attributes via regex, optionally filtering against `allowedNames`, and returns unparsed remainder (`rest`). | Sources: [packages/core/src/mdx-plugins/rehype-code/parsers.ts:6-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code/parsers.ts#L6-L51), [packages/core/src/mdx-plugins/codeblock-utils.ts:89-115](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/codeblock-utils.ts#L89-L115) ## AST Transformers and Tab Grouping ### File Icon Mapping and Shortcut Resolution Shiki code block decoration relies on language identifier translation and icon extraction. The transformer maps shorthand language aliases to normalized identifiers using `defaultShortcuts`. For example, `js` maps to `javascript`, `jsx` and `tsx` map to `react`, `ts` maps to `typescript`, `c#` and `cs` map to `csharp`, `gql` maps to `graphql`, `py` maps to `python`, and `bash`, `sh`, `shell`, and `zsh` all map to `shellscript`. C++ maps to `cpp`. ```typescript const defaultShortcuts: Record = { js: 'javascript', jsx: 'react', ts: 'typescript', tsx: 'react', 'c#': 'csharp', cs: 'csharp', gql: 'graphql', py: 'python', bash: 'shellscript', sh: 'shellscript', shell: 'shellscript', zsh: 'shellscript', 'c++': 'cpp', }; ``` Sources: [packages/core/src/mdx-plugins/transformer-icon.ts:11-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/transformer-icon.ts#L11-L25) The `CodeBlockIcon` type permits either an SVG path configuration object containing `viewBox`, `fill`, and `d` properties or a raw string identifier. Default icons sourced from Simple Icons are defined for languages including `react`, `shellscript`, `c`, `graphql`, `python`, `md`, `kotlin`, and `rust`. ```typescript export type CodeBlockIcon = | { viewBox: string; fill: string; d: string; } | string; const defaultShortcuts: Record = { js: 'javascript', jsx: 'react', ts: 'typescript', tsx: 'react', 'c#': 'csharp', cs: 'csharp', gql: 'graphql', py: 'python', bash: 'shellscript', sh: 'shellscript', shell: 'shellscript', zsh: 'shellscript', 'c++': 'cpp', }; // From https://simpleicons.org // Java - Not supported, https://github.com/simple-icons/simple-icons/issues/7374 const defaultIcons: Record = { react: { viewBox: '0 0 24 24', fill: 'currentColor', d: 'M14.23 12.004a2.236 2.236 0 0 1-2.235 2.236 2.236 2.236 0 0 1-2.236-2.236 2.236 2.236 0 0 1 2.235-2.236 2.236 2.236 0 0 1 2.236 2.236zm2.648-10.69c-1.346 0-3.107.96-4.888 2.622-1.78-1.653-3.542-2.602-4.887-2.602-.41 0-.783.093-1.106.278-1.375.793-1.683 3.264-.973 6.365C1.98 8.917 0 10.42 0 12.004c0 1.59 1.99 3.097 5.043 4.03-.704 3.113-.39 5.588.988 6.38.32.187.69.275 1.102.275 1.345 0 3.107-.96 4.888-2.624 1.78 1.654 3.542 2.603 4.887 2.603.41 0 .783-.09 1.106-.275 1.374-.792 1.683-3.263.973-6.365C22.02 15.096 24 13.59 24 12.004c0-1.59-1.99-3.097-5.043-4.032.704-3.11.39-5.587-.988-6.38-.318-.184-.688-.277-1.092-.278zm-.005 1.09v.006c.225 0 .406.044.558.127.666.382.955 1.835.73 3.704-.054.46-.142.945-.25 1.44-.96-.236-2.006-.417-3.107-.534-.66-.905-1.345-1.727-2.035-2.447 1.592-1.48 3.087-2.292 4.105-2.295zm-9.77.02c1.012 0 2.514.808 4.11 2.28-.686.72-1.37 1.537-2.02 2.442-1.107.117-2.154.298-3.113.538-.112-.49-.195-.964-.254-1.42-.23-1.868.054-3.32.714-3.707.19-.09.4-.127.563-.132zm4.882 3.05c.455.468.91.992 1.36 1.564-.44-.02-.89-.034-1.345-.034-.46 0-.915.01-1.36.034.44-.572.895-1.096 1.345-1.565zM12 8.1c.74 0 1.477.034 2.202.093.406.582.802 1.203 1.183 1.86.372.64.71 1.29 1.018 1.946-.308.655-.646 1.31-1.013 1.95-.38.66-.773 1.288-1.18 1.87-.728.063-1.466.098-2.21.098-.74 0-1.477-.035-2.202-.093-.406-.582-.802-1.204-1.183-1.86-.372-.64-.71-1.29-1.018-1.946.303-.657.646-1.313 1.013-1.954.38-.66.773-1.286 1.18-1.868.728-.064 1.466-.098 2.21-.098zm-3.635.254c-.24.377-.48.763-.704 1.16-.225.39-.435.782-.635 1.174-.265-.656-.49-1.31-.676-1.947.64-.15 1.315-.283 2.015-.386zm7.26 0c.695.103 1.365.23 2.006.387-.18.632-.405 1.282-.66 1.933-.2-.39-.41-.783-.64-1.174-.225-.392-.465-.774-.705-1.146zm3.063.675c.484.15.944.317 1.375.498 1.732.74 2.852 1.708 2.852 2.476-.005.768-1.125 1.74-2.857 2.475-.42.18-.88.342-1.355.493-.28-.958-.646-1.956-1.1-2.98.45-1.017.81-2.01 1.085-2.964zm-13.395.004c.278.96.645 1.957 1.1 2.98-.45 1.017-.812 2.01-1.086 2.964-.484-.15-.944-.318-1.37-.5-1.732-.737-2.852-1.706-2.852-2.474 0-.768 1.12-1.742 2.852-2.476.42-.18.88-.342 1.356-.494zm11.678 4.28c.265.657.49 1.312.676 1.948-.64.157-1.316.29-2.016.39.24-.375.48-.762.705-1.158.225-.39.435-.788.636-1.18zm-9.945.02c.2.392.41.783.64 1.175.23.39.465.772.705 1.143-.695-.102-1.365-.23-2.006-.386.18-.63.406-1.282.66-1.933zM17.92 16.32c.112.493.2.968.254 1.423.23 1.868-.054 3.32-.714 3.708-.147.09-.338.128-.563.128-1.012 0-2.514-.807-4.11-2.28.686-.72 1.37-1.536 2.02-2.44 1.107-.118 2.154-.3 3.113-.54zm-11.83.01c.96.234 2.006.415 3.107.532.66.905 1.345 1.727 2.035 2.446-1.595 1.483-3.092 2.295-4.11 2.295-.22-.005-.406-.05-.553-.132-.666-.38-.955-1.834-.73-3.703.054-.46.142-.944.25-1.438zm4.56.64c.44.02.89.034 1.345.034.46 0 .915-.01 1.36-.034-.44.572-.895 1.095-1.345 1.565-.455-.47-.91-.993-1.36-1.565z', }, vue: { viewBox: '0 0 24 24', fill: 'currentColor', d: 'M24,1.61H14.06L12,5.16,9.94,1.61H0L12,22.39ZM12,14.08,5.16,2.23H9.59L12,6.41l2.41-4.18h4.43Z', }, ruby: { viewBox: '0 0 24 24', fill: 'currentColor', d: 'M20.156.083c3.033.525 3.893 2.598 3.829 4.77L24 4.822 22.635 22.71 4.89 23.926h.016C3.433 23.864.15 23.729 0 19.139l1.645-3 2.819 6.586.503 1.172 2.805-9.144-.03.007.016-.03 9.255 2.956-1.396-5.431-.99-3.9 8.82-.569-.615-.51L16.5 2.114 20.159.073l-.003.01zM0 19.089zM5.13 5.073c3.561-3.533 8.157-5.621 9.922-3.84 1.762 1.777-.105 6.105-3.673 9.636-3.563 3.532-8.103 5.734-9.864 3.957-1.766-1.777.045-6.217 3.612-9.75l.003-.003z', }, zig: { viewBox: '0 0 24 24', fill: 'currentColor', d: 'm23.53 1.02-7.686 3.45h-7.06l-2.98 3.452h7.173L.47 22.98l7.681-3.607h7.065v-.002l2.978-3.45-7.148-.001 12.482-14.9zM0 4.47v14.901h1.883l2.98-3.45H3.451v-8h.942l2.824-3.45H0zm22.117 0-2.98 3.608h1.412v7.844h-.942l-2.98 3.45H24V4.47h-1.883z', }, swift: { viewBox: '0 0 24 24', fill: 'currentColor', d: 'M7.508 0c-.287 0-.573 0-.86.002-.241.002-.483.003-.724.01-.132.003-.263.009-.395.015A9.154 9.154 0 0 0 4.348.15 5.492 5.492 0 0 0 2.85.645 5.04 5.04 0 0 0 .645 2.848c-.245.48-.4.972-.495 1.5-.093.52-.122 1.05-.136 1.576a35.2 35.2 0 0 0-.012.724C0 6.935 0 7.221 0 7.508v8.984c0 .287 0 .575.002.862.002.24.005.481.012.722.014.526.043 1.057.136 1.576.095.528.25 1.02.495 1.5a5.03 5.03 0 0 0 2.205 2.203c.48.244.97.4 1.498.495.52.093 1.05.124 1.576.138.241.007.483.009.724.01.287.002.573.002.86.002h8.984c.287 0 .573 0 .86-.002.241-.001.483-.003.724-.01a10.523 10.523 0 0 0 1.578-.138 5.322 5.322 0 0 0 1.498-.495 5.035 5.035 0 0 0 2.203-2.203c.245-.48.4-.972.495-1.5.093-.52.124-1.05.138-1.576.007-.241.009-.481.01-.722.002-.287.002-.575.002-.862V7.508c0-.287 0-.573-.002-.86a33.662 33.662 0 0 0-.01-.724 10.5 10.5 0 0 0-.138-1.576 5.328 5.328 0 0 0-.495-1.5A5.039 5.039 0 0 0 21.152.645 5.32 5.32 0 0 0 19.654.15a10.493 10.493 0 0 0-1.578-.138 34.98 34.98 0 0 0-.722-.01C17.067 0 16.779 0 16.492 0H7.508zm6.035 3.41c4.114 2.47 6.545 7.162 5.549 11.131-.024.093-.05.181-.076.272l.002.001c2.062 2.538 1.5 5.258 1.236 4.745-1.072-2.086-3.066-1.568-4.088-1.043a6.803 6.803 0 0 1-.281.158l-.02.012-.002.002c-2.115 1.123-4.957 1.205-7.812-.022a12.568 12.568 0 0 1-5.64-4.838c.649.48 1.35.902 2.097 1.252 3.019 1.414 6.051 1.311 8.197-.002C9.651 12.73 7.101 9.67 5.146 7.191a10.628 10.628 0 0 1-1.005-1.384c2.34 2.142 6.038 4.83 7.365 5.576C8.69 8.408 6.208 4.743 6.324 4.86c4.436 4.47 8.528 6.996 8.528 6.996.154.085.27.154.36.213.085-.215.16-.437.224-.668.708-2.588-.09-5.548-1.893-7.992z', }, prisma: { viewBox: '0 0 24 24', fill: 'currentColor', d: 'M21.8068 18.2848L13.5528.7565c-.207-.4382-.639-.7273-1.1286-.7541-.5023-.0293-.9523.213-1.2062.6253L2.266 15.1271c-.2773.4518-.2718 1.0091.0158 1.4555l4.3759 6.7786c.2608.4046.7127.6388 1.1823.6388.1332 0 .267-.0188.3987-.0577l12.7019-3.7568c.3891-.1151.7072-.3904.8737-.7553s.1633-.7828-.0075-1.1454zm-1.8481.7519L9.1814 22.2242c-.3292.0975-.6448-.1873-.5756-.5194l3.8501-18.4386c.072-.3448.5486-.3996.699-.0803l7.1288 15.138c.1344.2856-.019.6224-.325.7128z', }, typescript: { viewBox: '0 0 24 24', fill: 'currentColor', d: 'M1.125 0C.502 0 0 .502 0 1.125v21.75C0 23.498.502 24 1.125 24h21.75c.623 0 1.125-.502 1.125-1.125V1.125C24 .502 23.498 0 22.875 0zm17.363 9.75c.612 0 1.154.037 1.627.111a6.38 6.38 0 0 1 1.306.34v2.458a3.95 3.95 0 0 0-.643-.361 5.093 5.093 0 0 0-.717-.26 5.453 5.453 0 0 0-1.426-.2c-.3 0-.573.028-.819.086a2.1 2.1 0 0 0-.623.242c-.17.104-.3.229-.393.374a.888.888 0 0 0-.14.49c0 .196.053.373.156.529.104.156.252.304.443.444s.423.276.696.41c.273.135.582.274.926.416.47.197.892.407 1.266.628.374.222.695.473.963.753.268.279.472.598.614.957.142.359.214.776.214 1.253 0 .657-.125 1.21-.373 1.656a3.033 3.033 0 0 1-1.012 1.085 4.38 4.38 0 0 1-1.487.596c-.566.12-1.163.18-1.79.18a9.916 9.916 0 0 1-1.84-.164 5.544 5.544 0 0 1-1.512-.493v-2.63a5.033 5.033 0 0 0 3.237 1.2c.333 0 .624-.03.872-.09.249-.06.456-.144.623-.25.166-.108.29-.234.373-.38a1.023 1.023 0 0 0-.074-1.089 2.12 2.12 0 0 0-.537-.5 5.597 5.597 0 0 0-.807-.444 27.72 27.72 0 0 0-1.007-.436c-.918-.383-1.602-.852-2.053-1.405-.45-.553-.676-1.222-.676-2.005 0-.614.123-1.141.369-1.582.246-.441.58-.804 1.004-1.089a4.494 4.494 0 0 1 1.47-.629 7.536 7.536 0 0 1 1.77-.201zm-15.113.188h9.563v2.166H9.506v9.646H6.789v-9.646H3.375z', }, javascript: { viewBox: '0 0 24 24', fill: 'currentColor', d: 'M0 0h24v24H0V0zm22.034 18.276c-.175-1.095-.888-2.015-3.003-2.873-.736-.345-1.554-.585-1.797-1.14-.091-.33-.105-.51-.046-.705.15-.646.915-.84 1.515-.66.39.12.75.42.976.9 1.034-.676 1.034-.676 1.755-1.125-.27-.42-.404-.601-.586-.78-.63-.705-1.469-1.065-2.834-1.034l-.705.089c-.676.165-1.32.525-1.71 1.005-1.14 1.291-.811 3.541.569 4.471 1.365 1.02 3.361 1.244 3.616 2.205.24 1.17-.87 1.545-1.966 1.41-.811-.18-1.26-.586-1.755-1.336l-1.83 1.051c.21.48.45.689.81 1.109 1.74 1.756 6.09 1.666 6.871-1.004.029-.09.24-.705.074-1.65l.046.067zm-8.983-7.245h-2.248c0 1.938-.009 3.864-.009 5.805 0 1.232.063 2.363-.138 2.711-.33.689-1.18.601-1.566.48-.396-.196-.597-.466-.83-.855-.063-.105-.11-.196-.127-.196l-1.825 1.125c.305.63.75 1.172 1.324 1.517.855.51 2.004.675 3.207.405.783-.226 1.458-.691 1.811-1.411.51-.93.402-2.07.397-3.346.012-2.054 0-4.109 0-6.179l.004-.056z', }, php: { viewBox: '0 0 24 24', fill: 'currentColor', d: 'M7.01 10.207h-.944l-.515 2.648h.838c.556 0 .97-.105 1.242-.314.272-.21.455-.559.55-1.049.092-.47.05-.802-.124-.995-.175-.193-.523-.29-1.047-.29zM12 5.688C5.373 5.688 0 8.514 0 12s5.373 6.313 12 6.313S24 15.486 24 12c0-3.486-5.373-6.312-12-6.312zm-3.26 7.451c-.261.25-.575.438-.917.551-.336.108-.765.164-1.285.164H5.357l-.327 1.681H3.652l1.23-6.326h2.65c.797 0 1.378.209 1.744.628.366.418.476 1.002.33 1.752a2.836 2.836 0 0 1-.305.847c-.143.255-.33.49-.561.703zm4.024.715l.543-2.799c.063-.318.039-.536-.068-.651-.107-.116-.336-.174-.687-.174H11.46l-.704 3.625H9.388l1.23-6.327h1.367l-.327 1.682h1.218c.767 0 1.295.134 1.586.401s.378.7.263 1.299l-.572 2.944h-1.389zm7.597-2.265a2.782 2.782 0 0 1-.305.847c-.143.255-.33.49-.561.703a2.44 2.44 0 0 1-.917.551c-.336.108-.765.164-1.286.164h-1.18l-.327 1.682h-1.378l1.23-6.326h2.649c.797 0 1.378.209 1.744.628.366.417.477 1.001.331 1.751zM17.766 10.207h-.943l-.516 2.648h.838c.557 0 .971-.105 1.242-.314.272-.21.455-.559.551-1.049.092-.47.049-.802-.125-.995s-.524-.29-1.047-.29z', }, shellscript: { viewBox: '0 0 24 24', fill: 'currentColor', d: 'm 4,4 a 1,1 0 0 0 -0.7070312,0.2929687 1,1 0 0 0 0,1.4140625 L 8.5859375,11 3.2929688,16.292969 a 1,1 0 0 0 0,1.414062 1,1 0 0 0 1.4140624,0 l 5.9999998,-6 a 1.0001,1.0001 0 0 0 0,-1.414062 L 4.7070312,4.2929687 A 1,1 0 0 0 4,4 Z m 8,14 a 1,1 0 0 0 -1,1 1,1 0 0 0 1,1 h 8 a 1,1 0 0 0 1,-1 1,1 0 0 0 -1,-1 z', }, c: { viewBox: '0 0 24 24', fill: 'currentColor', ``` Sources: [packages/core/src/mdx-plugins/transformer-icon.ts:3-115](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/transformer-icon.ts#L3-L115) > [!NOTE] > Java is not supported in the default icon set due to upstream limitations in Simple Icons. Sources: [packages/core/src/mdx-plugins/transformer-icon.ts:27-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/transformer-icon.ts#L27-L28) ### Tab Metadata Extraction and Multi-Tab Grouping The `remarkCodeTab` unified transformer scans Markdown AST nodes for contiguous code blocks carrying `tab` attributes in their meta strings. It processes these sequences via `parseCodeBlockAttributes`, extracting `tab` and `tab-group` metadata and populating `child.data.tab` and `child.data.tabGroup` properties. ```typescript if (child.type !== 'code' || !child.meta) { close(); continue; } const meta = parseCodeBlockAttributes(child.meta, ['tab', 'tab-group']); if (!meta.attributes.tab) { close(); continue; } if (start === -1) start = end; child.meta = meta.rest; child.data ??= {}; child.data.tab = meta.attributes.tab; if (meta.attributes['tab-group']) { child.data.tabGroup = meta.attributes['tab-group']; } } ``` Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:250-268](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L250-L268) The transformation delegates rendering to the `Types` handler record based on the configured `TabType`, which supports either `CodeBlockTabs` or `Tabs`. | Tab Handler Type | Target Node Structure | Persistence Support | MDX Parsing Support | | :--- | :--- | :--- | :--- | | `CodeBlockTabs` | `CodeBlockTabsOptions` via `generateCodeBlockTabs` | Optional `persist: { id: tagGroup }` derived from the first tab's `tabGroup` | Optional via `mdxToAst` processor when `parseMdx` is enabled | | `Tabs` | `MdxJsxFlowElement` (`Tabs`, `TabsList`, `TabsTrigger`, `TabsContent`) | None (relies on component props) | Full MDX element generation or simple attribute items mode | Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:11-200](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L11-L200) > [!WARNING] > When `Tabs` operates in simple mode without MDX parsing (`withMdx` set to false), it does not support rich MDX tab names and emits comma-joined literal arrays into the `items` attribute. Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:92-146](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L92-L146) ## Client-Side Dynamic Highlighting Hooks ### Asynchronous Shiki Execution and React Hooks Browser-side syntax highlighting in Fumadocs relies on React state and suspense hooks that transform code strings into JSX nodes via Shiki and `hast-util-to-jsx-runtime`. The `useShikiDynamic` hook manages asynchronous highlighting tasks using `useEffect`, maintaining a task reference to prevent race conditions during rapid state changes. When a highlighting promise resolves, it checks whether `lastTask.current` matches the running promise before updating the node state. ```typescript export function useShikiDynamic( highlighter: HighlighterCore | (() => Awaitable), code: string, options: UseShikiOptions & { defaultValue?: ReactNode }, deps: DependencyList, ): ReactNode { const [node, setNode] = useState(options.defaultValue); const lastTask = useRef | null>(null); useEffect(() => { async function task() { const instance = typeof highlighter === 'function' ? await highlighter() : highlighter; return toJsxRuntime(await highlightHast(instance, code, options), { ...JsxRuntime, components: options.components, }); } const promise = task(); lastTask.current = promise; void promise.then((res) => { if (lastTask.current === promise) setNode(res); }); return () => { lastTask.current = null; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, deps); return node; } ``` Sources: [packages/core/src/highlight/shiki/react.ts:27-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/react.ts#L27-L59) The `useShiki` hook integrates with the React `use` API for suspenseful data fetching. It caches compiled results using JSON-serialized dependency arrays derived from language identifiers and code contents by default, or custom dependency lists when specified. ```typescript export function useShiki( highlighter: HighlighterCore | (() => Awaitable), code: string, options: UseShikiOptions, deps: DependencyList = [options.lang, code], ): ReactNode { const key = useMemo(() => JSON.stringify(deps), [deps]); async function run() { const instance = typeof highlighter === 'function' ? await highlighter() : highlighter; return toJsxRuntime(await highlightHast(instance, code, options), { ...JsxRuntime, components: options.components, }); } return use((promises[key] ??= run())); } ``` Sources: [packages/core/src/highlight/shiki/react.ts:66-84](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/react.ts#L66-L84) A client-specific wrapper for `useShiki` initializes default themes automatically using `defaultShikiFactory.getOrInit()` combined with `applyDefaultThemes`. ```typescript export function useShiki( code: string, options: HighlightOptions, deps?: DependencyList, ): ReactNode { return useShikiBase( () => defaultShikiFactory.getOrInit(), code, applyDefaultThemes(options), deps, ); } ``` Sources: [packages/core/src/highlight/client.ts:13-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/client.ts#L13-L24) > [!NOTE] > Results in `useShiki` are cached using `(lang, code)` pairs as keys unless an explicit dependency list overrides the memoization key. Sources: [packages/core/src/highlight/shiki/react.ts:64-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/highlight/shiki/react.ts#L64-L64) ### Dynamic Code Block Component Integration The `DynamicCodeBlock` component wraps dynamic client highlighting in a structured UI container. It accepts a highlighter instance or factory function, target language, raw code string, and optional configuration props. ```tsx export function DynamicCodeBlock({ lang, code, codeblock, options, wrapInSuspense = true, highlighter, }: DynamicCodeblockProps) { const id = useId(); const shikiOptions: UseShikiOptions = { lang, defaultColor: false, ...options, components: { pre: DefaultPre, ...options.components, }, }; let node = useShikiDynamic(highlighter, code, shikiOptions, [id, lang, code]); if (wrapInSuspense) node ??= ; return {node}; } ``` Sources: [packages/radix-ui/src/components/dynamic-codeblock.core.tsx:45-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx#L45-L67) | Property | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `highlighter` | `HighlighterCore \| (() => HighlighterCore \| PromiseLike)` | *Required* | Shiki core instance or asynchronous initialization factory. | | `lang` | `string` | *Required* | Target programming language identifier for syntax grammar selection. | | `code` | `string` | *Required* | Raw source code text content to highlight. | | `codeblock` | `CodeBlockProps` | `undefined` | Extra properties passed to the underlying `CodeBlock` component. | | `wrapInSuspense` | `boolean` | `true` | Toggles automatic wrapping in a React `Suspense` boundary with a fallback placeholder. | | `options` | `DistributiveOmit` | *Required* | Highlighting configuration options excluding language. | Sources: [packages/radix-ui/src/components/dynamic-codeblock.core.tsx:8-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx#L8-L25) When `wrapInSuspense` is enabled and the dynamic node has not yet resolved, a `Placeholder` component splits the raw code into individual line spans using `code.split('\n')` rendered inside `pre` and `code` elements. ```tsx function Placeholder({ code, components = {}, }: { code: string; components: UseShikiOptions['components']; }) { const { pre: Pre = 'pre', code: Code = 'code' } = components as Record; return (
      
        {code.split('\n').map((line, i) => (
          
            {line}
          
        ))}
      
    
); ``` Sources: [packages/radix-ui/src/components/dynamic-codeblock.core.tsx:69-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx#L69-L88) > [!WARNING] > Defining a custom `pre` component inside `options.components` ignores extra `codeblock` properties passed to `DynamicCodeBlock`. Sources: [packages/radix-ui/src/components/dynamic-codeblock.core.tsx:13-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx#L13-L16) ## Code Block Styling Architecture ### CSS Custom Properties and Layout Code blocks rely on CSS custom properties defined in package stylesheets to manage horizontal spacing and alignment. The padding variables `--padding-left` and `--padding-right` are calculated as four times the spacing scale token. ```css .shiki:not(.not-fumadocs-codeblock *) { --padding-left: calc(var(--spacing) * 4); --padding-right: calc(var(--spacing) * 4); ``` Sources: [packages/base-ui/css/lib/shiki.css:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L1-L4) Each line element within a Shiki block establishes a relative positioning context and applies these padding rules. Empty lines are explicitly sized using line height units to preserve vertical rhythm. ```css .line { position: relative; padding-left: var(--padding-left); padding-right: var(--padding-right); } .line:empty { height: 1lh; } ``` Sources: [packages/base-ui/css/lib/shiki.css:10-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L10-L18) > [!NOTE] > Empty lines set `height: 1lh` to ensure they maintain the exact height of populated text lines. Sources: [packages/base-ui/css/lib/shiki.css:16-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L16-L18) ### Token Color Containment Token coloring is scoped through CSS variables generated by Shiki for light and dark themes. Under standard selector rules, `code span` elements pull their color and font style properties directly from `--shiki-light` and `--shiki-light-font-style`. ```css code span { color: var(--shiki-light); font-style: var(--shiki-light-font-style); } ``` Sources: [packages/base-ui/css/lib/shiki.css:5-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L5-L8) When the `.dark` class is present on an ancestor container, token colors override the light variables by binding to `--shiki-dark` and `--shiki-dark-font-style`. Inline code elements follow an identical scoping strategy via `code.shiki`. ```css .dark .shiki:not(.not-fumadocs-codeblock *) { code span { color: var(--shiki-dark); font-style: var(--shiki-dark-font-style); } } ``` Sources: [packages/base-ui/css/lib/shiki.css:92-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L92-L97) ### Interactive Line States and Modifiers Code blocks support specialized line decorations including diff indicators, focus blur effects, line numbering, and custom word highlighting. When `.has-focused` is active on the container, unselected lines receive a 2px blur filter that transitions smoothly over 200 milliseconds unless hovered. ```css &.has-focused .line:not(.focused) { filter: blur(2px); transition: filter 200ms; } &.has-focused:hover .line:not(.focused) { filter: blur(0); } ``` Sources: [packages/base-ui/css/lib/shiki.css:20-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L20-L27) | Class Selector | Applied Styles / Tailwind Mixins | Purpose | | :--- | :--- | :--- | | `.diff.remove` | `opacity: 0.7; bg-fd-diff-remove` | Styles removed lines in diff views with an opacity drop and background tint. | | `.diff.add` | `bg-fd-diff-add` | Applies an addition background tint to newly introduced lines. | | `.highlighted` | `bg-fd-primary/10` with primary border accent | Highlights specific target lines and renders an absolute left accent bar. | | `.highlighted-word` | `border border-fd-primary/30 bg-fd-primary/10 rounded-md font-medium` | Outlines and backgrounds individual token words within code lines. | Sources: [packages/base-ui/css/lib/shiki.css:34-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L34-L69) When data line numbering is enabled (`[data-line-numbers]`), lines increment a CSS counter and prepend a pseudo-element displaying the current line index aligned to a fixed 7-spacing-unit column width. ```css &[data-line-numbers] .line { counter-increment: line; padding-left: calc(var(--padding-left) + 7 * var(--spacing)); } &[data-line-numbers] .line::after { position: absolute; content: counter(line); color: color-mix( in oklab, var(--fd-counter-color, var(--color-fd-muted-foreground)) 60%, transparent ); @apply inset-y-0 left-0 w-7 text-right; } ``` Sources: [packages/base-ui/css/lib/shiki.css:75-89](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L75-L89) ## Related - [Code Block Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/code-block-components) - [Twoslash Type Hover](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/twoslash-type-hover) --- ## Technical docs: Markdown AST Plugins URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/markdown-ast-plugins
Relevant source files The following files were used as context for generating this wiki page: - [packages/core/src/mdx-plugins/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/index.ts) - [packages/obsidian/src/remark/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/index.ts) - [packages/core/src/mdx-plugins/remark-llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts) - [packages/mdx/src/loaders/mdx/remark-postprocess.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-postprocess.ts) - [packages/core/src/mdx-plugins/remark-structure.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts) - [packages/core/src/content/mdx/preset-bundler.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts) - [packages/core/src/mdx-plugins/rehype-toc.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts) - [packages/preview/src/lib/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/md.ts) - [packages/core/src/mdx-plugins/remark-steps.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts) - [packages/doc-gen/src/remark-docgen.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-docgen.ts) - [packages/mdx/src/rolldown/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts) - [packages/core/src/content/mdx/preset-runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts) - [packages/obsidian/src/remark/remark-convert.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-convert.ts) - [packages/doc-gen/src/remark-install.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-install.ts) - [packages/core/src/mdx-plugins/remark-mdx-files.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-files.ts) - [packages/typescript/src/lib/remark-auto-type-table.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/src/lib/remark-auto-type-table.ts) - [packages/core/src/mdx-plugins/remark-directive-admonition.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-directive-admonition.ts) - [packages/obsidian/src/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts) - [packages/core/src/mdx-plugins/remark-gfm.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-gfm.ts) - [packages/core/src/mdx-plugins/remark-npm.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-npm.ts) - [packages/core/src/mdx-plugins/remark-heading.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts) - [packages/core/src/mdx-plugins/remark-mdx-mermaid.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-mermaid.ts) - [packages/core/src/mdx-plugins/remark-code-tab.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts) - [packages/mdx/src/config/preset.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts) - [packages/local-md/src/md/compiler.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts) - [packages/core/src/mdx-plugins/rehype-code.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code.ts) - [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts) - [packages/core/src/mdx-plugins/remark-admonition.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-admonition.ts) - [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts) - [packages/core/src/content/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/md.ts)
## Overview Fumadocs processes documentation through an extensible pipeline of remark and rehype plugins that transform abstract syntax trees to support features like admonitions, code tabs, and [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) generation. These plugins integrate directly with [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline), [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader), and [Content Collections Adapter](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/content-collections-adapter) to standardize markdown compilation across build tools and runtimes. Sources: [packages/core/src/mdx-plugins/index.ts:1-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/index.ts#L1-L16), [packages/core/src/content/mdx/preset-bundler.ts:23-92](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L23-L92), [packages/content-collections/src/configuration.ts:58-124](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts#L58-L124) ## Admonition parsing and directive transformations ### Directive-Based Admonition Containers The `remarkDirectiveAdmonition` plugin processes `containerDirective` nodes within the [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline) to support standard callout syntaxes, particularly for migrations from Docusaurus. It inspects tree nodes using `unist-util-visit`, checking whether a node name matches any entry in the configured `types` mapping. When a match is found, the plugin transforms the AST node into an `mdxJsxFlowElement` representing a callout container. ```typescript export function remarkDirectiveAdmonition({ tags: { CalloutContainer = 'CalloutContainer', CalloutTitle = 'CalloutTitle', CalloutDescription = 'CalloutDescription', } = {}, types = { note: 'info', tip: 'info', info: 'info', warn: 'warning', warning: 'warning', danger: 'error', success: 'success', }, }: RemarkDirectiveAdmonitionOptions = {}): Transformer { ``` Sources: [packages/core/src/mdx-plugins/remark-directive-admonition.ts:29-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-directive-admonition.ts#L29-L44) The mapping between input directive names and target callout types defaults to specific standard identifiers. | Directive Name | Target Callout Type | | -------------- | ------------------- | | `note` | `info` | | `tip` | `info` | | `info` | `info` | | `warn` | `warning` | | `warning` | `warning` | | `danger` | `error` | | `success` | `success` | Sources: [packages/core/src/mdx-plugins/remark-directive-admonition.ts:35-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-directive-admonition.ts#L35-L43) During transformation, any directive attributes present on the container are extracted into `mdxJsxAttribute` objects, alongside the primary `type` attribute. Children of the container are partitioned: paragraphs flagged with `directiveLabel` are routed into a title element named via `CalloutTitle`, while all remaining content blocks form the children of a description element named via `CalloutDescription`. ```typescript const titleNodes: PhrasingContent[] = []; const descriptionNodes: (BlockContent | DefinitionContent)[] = []; for (const item of node.children) { if (item.type === 'paragraph' && item.data?.directiveLabel) { titleNodes.push(...item.children); } else { descriptionNodes.push(item); } } const children: MdxJsxFlowElement[] = []; if (titleNodes.length > 0) { children.push({ type: 'mdxJsxFlowElement', name: CalloutTitle, attributes: [], children: titleNodes as BlockContent[], }); } if (descriptionNodes.length > 0) { children.push({ type: 'mdxJsxFlowElement', name: CalloutDescription, attributes: [], children: descriptionNodes, }); } ``` Sources: [packages/core/src/mdx-plugins/remark-directive-admonition.ts:65-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-directive-admonition.ts#L65-L95) > [!NOTE] > `remarkDirectiveAdmonition` requires `remark-directive` to be configured beforehand in the unified pipeline to parse container directive syntax correctly. > Sources: [packages/core/src/mdx-plugins/remark-directive-admonition.ts:26-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-directive-admonition.ts#L26-L28) ### Legacy Admonition Syntax Rewriting The legacy `remarkAdmonition` plugin provides backward compatibility for custom admonition tags (defaulting to `:::`) by scanning paragraph nodes, flattening their contents, and searching for matching type keys. While deprecated in favor of directive-based parsing, it maps alternative type names and extracts bracketed title meta strings into JSX attributes for standard `Callout` elements. ```typescript export function remarkAdmonition(options: RemarkAdmonitionOptions = {}): Transformer { const tag = options.tag ?? ':::'; // compatible with Docusaurus const typeMap = options.typeMap ?? { info: 'info', warn: 'warn', note: 'info', tip: 'info', warning: 'warn', danger: 'error', }; ``` Sources: [packages/core/src/mdx-plugins/remark-admonition.ts:22-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-admonition.ts#L22-L34) > [!WARNING] > Using nested admonitions with the legacy `remarkAdmonition` parser sets an `hasIntercept` flag that recursively invokes `replaceNodes` on inner child slices. > Sources: [packages/core/src/mdx-plugins/remark-admonition.ts:40-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-admonition.ts#L40-L41), [packages/core/src/mdx-plugins/remark-admonition.ts:80|80](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-admonition.ts#L80-L80) ## Heading slugs and table generation ### Heading Slug Assignment and TOC Extraction The `remarkHeading` plugin processes markdown trees using `unist-util-visit` to locate heading nodes and assign unique URL-safe identifiers via `github-slugger`. By default, it supports custom heading IDs through a regular expression that inspects the final text node of a heading for a bracketed slug pattern (`[#slug]`). When a custom ID is matched, the plugin assigns it to `heading.data.hProperties.id` and strips the trailing tag from the node value. If no custom ID is present, it flattens the node content and passes it to the configured slug function. ```typescript const regex = /\s*\[#(?[^]+?)]\s*$/; ``` Sources: [packages/core/src/mdx-plugins/remark-heading.ts:16-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts#L16-L16), [packages/core/src/mdx-plugins/remark-heading.ts:63-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts#L63-L95) When `generateToc` is enabled, the plugin constructs an array of `TOCItemType` entries storing the title text, hash URL, and heading depth, attaching the resulting collection directly to `file.data.toc`. ```typescript if (generateToc) { toc.push({ title: flattened ?? flattenNode(heading), url: `#${props.id}`, depth: heading.depth, }); } ``` Sources: [packages/core/src/mdx-plugins/remark-heading.ts:86-92](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts#L86-L92), [packages/core/src/mdx-plugins/remark-heading.ts:97-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts#L97-L97) > [!NOTE] > `remarkHeading` initializes a fresh `Slugger` instance and resets it on each transformer execution to guarantee deterministic ID generation across builds. > Sources: [packages/core/src/mdx-plugins/remark-heading.ts:53-62](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts#L53-L62) ### Structured Data Extraction The `remarkStructure` plugin parses MDAST trees to build searchable structured data containing headings and content blocks. It scans nodes matching specified types, defaulting to paragraphs, blockquotes, table cells, headings, and leaf MDX flow elements. ```typescript export const remarkStructureDefaultOptions = { types: ['heading', 'paragraph', 'blockquote', 'tableCell', 'mdxJsxFlowElement'], mdxTypes(node) { return !node.children || node.children.length === 0; }, exportAs: false, } satisfies StructureOptions; ``` Sources: [packages/core/src/mdx-plugins/remark-structure.ts:94-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts#L94-L100) If a heading node lacks an `hProperties.id`, `remarkStructure` emits a warning and skips it, requiring `remarkHeading` to run beforehand in the pipeline. ```typescript if (typeof id !== 'string') { console.warn( '[remark-structure] hProperties.id is missing in heading node, it is required to generate heading data. You can add remark-heading prior to remark-structure to generate heading IDs.', ); return 'skip'; } ``` Sources: [packages/core/src/mdx-plugins/remark-structure.ts:173-178](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts#L173-L178) Collected blocks associate their content with the most recently encountered heading ID, storing the structured output in `file.data.structuredData` or serializing it as an MDX export when `exportAs` is configured. ```typescript file.data.structuredData = data; if (exportAs) { tree.children.unshift( toMdxExport(typeof exportAs === 'string' ? exportAs : 'structuredData', data), ); } ``` Sources: [packages/core/src/mdx-plugins/remark-structure.ts:204-209](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts#L204-L209) ### Rehype Table of Contents Generation The `rehypeToc` plugin inspects HTML element trees for heading tags (`h1` through `h6`) to build a table of contents directly from HAST nodes. It recognizes control tags appended to heading text to alter behavior: `[!toc]` suppresses the heading from the table of contents and strips the tag, while `[toc]` includes the heading but removes the tag from the rendered output. ```typescript const TocOnlyTag = '[toc]'; const NoTocTag = '[!toc]'; const HeadingTags = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']); ``` Sources: [packages/core/src/mdx-plugins/rehype-toc.ts:51-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts#L51-L53), [packages/core/src/mdx-plugins/rehype-toc.ts:77-91](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts#L77-L91) | Configuration Property | Type | Default Value | Purpose | | ---------------------- | ---- | ------------- | ------- | | `exportToc` | `boolean \| { as: 'data' } \| { as: 'esm', name: string }` | `true` | Determines whether the table of contents is exported as an ESM variable or stored in virtual file data. | Sources: [packages/core/src/mdx-plugins/rehype-toc.ts:8-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts#L8-L30), [packages/core/src/mdx-plugins/rehype-toc.ts:55-61](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts#L55-L61) When `exportToc` is configured as an ESM export (defaulting to the name `toc`), the plugin converts HAST heading nodes into ESTree JSX fragments using `hast-util-to-estree`. ```typescript if (exportToc.as === 'esm') { const esmItems: { title: JSXElement; url: string; depth: number; _step?: number; }[] = []; for (const item of items) { const root = toEstree(item.title, { elementAttributeNameCase: 'react', stylePropertyNameCase: 'dom', }).body[0]; if (root.type === 'ExpressionStatement' && root.expression.type === 'JSXElement') { esmItems.push({ ...item, title: root.expression, }); } ``` Sources: [packages/core/src/mdx-plugins/rehype-toc.ts:110-128](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts#L110-L128) > [!WARNING] > Headings without a valid string identifier in their properties are skipped by `rehypeToc` and omitted from the generated table of contents. > Sources: [packages/core/src/mdx-plugins/rehype-toc.ts:73-74](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts#L73-L74) ## Sequential step list conversion ### Step Detection and Parsing The `remarkSteps` plugin transforms consecutive step headings and their accompanying content into structured MDX JSX flow elements. It accepts an options object to customize CSS class names for both the outer steps container and individual step items. | Configuration Property | Type | Default Value | Purpose | | ---------------------- | ---- | ------------- | ------- | | `steps` | `string` | `'fd-steps'` | Class name assigned to the outer wrapper container div element. | | `step` | `string` | `'fd-step'` | Class name assigned to each individual step item container div element. | Sources: [packages/core/src/mdx-plugins/remark-steps.ts:7-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts#L7-L21), [packages/core/src/mdx-plugins/remark-steps.ts:29-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts#L29-L32) To identify step headings, the plugin evaluates heading text against a regular expression pattern matching numeric prefixes like `1. Hello World`, or checks for the trailing tag `[step]` via `handleTag`. When a valid step pattern matches, the plugin strips the marker from the text node and injects a `data-fd-step` property containing the incremental step index onto the heading's data properties. ```typescript const StepRegex = /^(\d+)\.\s(.+)$/; const StepTag = '[step]'; ``` Sources: [packages/core/src/mdx-plugins/remark-steps.ts:23-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts#L23-L24), [packages/core/src/mdx-plugins/remark-steps.ts:70-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts#L70-L90), [packages/core/src/mdx-plugins/remark-steps.ts:124-132](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts#L124-L132) > [!WARNING] > If a heading has a mismatched depth or fails step parsing while a sequence is actively collecting, the plugin immediately terminates the current step group via `onEnd()`. > Sources: [packages/core/src/mdx-plugins/remark-steps.ts:118-127](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts#L118-L127) ## Code tabs and command generation ### Package Manager Conversion and Tabs Generation Fumadocs provides remark plugins to rewrite code blocks into multi-tab package manager interfaces. The core pipeline includes `remarkNpm` and `remarkCodeTab`, alongside legacy support from `remarkInstall`. | Plugin Name | Target Language / Marker | Output Element | | ----------- | ------------------------ | -------------- | | `remarkNpm` | `package-install`, `npm` | CodeBlockTabs / custom triggers | | `remarkInstall` | `package-install` | Tabs, Tab | | `remarkCodeTab` | Code blocks with `tab` attribute | CodeBlockTabs or Tabs / Tab | Sources: [packages/core/src/mdx-plugins/remark-npm.ts:60-73](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-npm.ts#L60-L73), [packages/doc-gen/src/remark-install.ts:60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-install.ts#L60), [packages/core/src/mdx-plugins/remark-code-tab.ts:255-259](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L255-L259) The `remarkNpm` plugin visits code blocks in the Markdown AST and detects nodes where the language is `package-install` or `npm`. For `package-install` blocks, if the text does not start with `npm` or `npx`, it automatically prepends `npm install`. It then maps over configured package managers to translate commands and generate code block tabs. ```typescript export function remarkNpm({ persist = false, packageManagers = [ { command: (cmd) => cmd, name: 'npm' }, { command: (cmd) => convertLines(cmd, 'pnpm'), name: 'pnpm' }, { command: (cmd) => convertLines(cmd, 'yarn'), name: 'yarn' }, { command: (cmd) => convertLines(cmd, 'bun'), name: 'bun' }, ], }: RemarkNpmOptions = {}): Transformer { ``` Sources: [packages/core/src/mdx-plugins/remark-npm.ts:46-54](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-npm.ts#L46-L54) > [!NOTE] > `remarkInstall` from `@fumadocs/doc-gen` is deprecated in favor of `remarkNpm` from `fumadocs-core/mdx-plugins`, which serves as a drop-in replacement. > Sources: [packages/doc-gen/src/remark-install.ts:45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-install.ts#L45) ### Custom Code Tabs and Attribute Parsing The `remarkCodeTab` plugin processes adjacent code blocks decorated with meta attributes like `tab` and `tab-group`. It supports two layout handlers defined in `Types`: `CodeBlockTabs` and `Tabs`. | Option Property | Type | Default Value | Purpose | | --------------- | ---- | ------------- | ------- | | `Tabs` | `'CodeBlockTabs' \| 'Tabs'` | `'CodeBlockTabs'` | Determines the component name used for rendering grouped tab containers. | | `parseMdx` | `boolean` | `false` | Enables parsing of embedded MDX inside tab trigger values. | Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:11-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L11-L21), [packages/core/src/mdx-plugins/remark-code-tab.ts:206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L206) During visitation, `remarkCodeTab` uses `parseCodeBlockAttributes` to extract `tab` and `tab-group` metadata from code block strings, assigns them to node data properties, and strips them from the raw meta string so syntax highlighters do not receive unknown flags. ```typescript for (; end < node.children.length; end++) { const child = node.children[end]; if (child.type !== 'code' || !child.meta) { close(); continue; } const meta = parseCodeBlockAttributes(child.meta, ['tab', 'tab-group']); if (!meta.attributes.tab) { close(); continue; } if (start === -1) start = end; child.meta = meta.rest; child.data ??= {}; child.data.tab = meta.attributes.tab; if (meta.attributes['tab-group']) { child.data.tabGroup = meta.attributes['tab-group']; } } ``` Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:248-268](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L248-L268) > [!WARNING] > When processing `Tabs` in simple mode with `parseMdx` enabled, the plugin checks whether the existing node attributes contain an `items` property before attempting to parse tab names as MDX. > Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:220-224](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L220-L224) ## Mermaid diagram code block conversion ### Remark Transformer and AST Replacement The `remarkMdxMermaid` plugin transforms fenced code blocks containing diagram specifications into dynamic MDX JSX flow elements. It exports an options interface that accepts a custom language identifier. | Option Property | Type | Default Value | Purpose | | --------------- | ---- | ------------- | ------- | | `lang` | `string` | `'mermaid'` | Specifies the target code block language identifier to match during AST visitation. | Sources: [packages/core/src/mdx-plugins/remark-mdx-mermaid.ts:21-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-mermaid.ts#L21-L26) The plugin returns a unified transformer function that traverses the markdown abstract syntax tree using `unist-util-visit`. It targets nodes of type `code`, validates their positional indices and parent references, and compares their language property against the configured target language. ```typescript export function remarkMdxMermaid(options: RemarkMdxMermaidOptions = {}): Transformer { const { lang = 'mermaid' } = options; return (tree) => { visit(tree, 'code', (node, idx, parent) => { if (node.lang !== lang || !node.value || typeof idx !== 'number' || !parent) return; parent.children[idx] = toMDX(node.value); }); }; ``` Sources: [packages/core/src/mdx-plugins/remark-mdx-mermaid.ts:31-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-mermaid.ts#L31-L40) > [!CAUTION] > The visitor function skips code block nodes where `idx` is not a number or where `parent` is undefined, preventing out-of-bounds mutations on root or unattached AST nodes. > Sources: [packages/core/src/mdx-plugins/remark-mdx-mermaid.ts:36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-mermaid.ts#L36) ### MDX JSX Node Generation When a matching code block is identified, the plugin delegates conversion to the `toMDX` helper function. This function constructs an `MdxJsxFlowElement` node configured to render the `` component. ```typescript function toMDX(code: string): MdxJsxFlowElement { return { type: 'mdxJsxFlowElement', name: 'Mermaid', attributes: [ { type: 'mdxJsxAttribute', name: 'chart', value: code.trim(), }, ], children: [], }; } ``` Sources: [packages/core/src/mdx-plugins/remark-mdx-mermaid.ts:6-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-mermaid.ts#L6-L19) > [!NOTE] > The source code inside the matched code block is trimmed via `code.trim()` before being assigned to the `chart` attribute of the generated JSX element, removing leading and trailing whitespace from the diagram definition. > Sources: [packages/core/src/mdx-plugins/remark-mdx-mermaid.ts:14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-mermaid.ts#L14) ## LLM exports and postprocessing pipeline ### Remark LLM Stringification and Placeholder Transformation The `remarkLLMs` plugin processes markdown trees to generate clean plain-text representations and exportable string constants suitable for large language model ingestion. It accepts an options interface extending stringifier configurations with export name, heading identifier inclusion, element filtering, and placeholder conversion settings. | Option Property | Type | Default Value | Purpose | | --------------- | ---- | ------------- | ------- | | `as` | `string` | `'_markdown'` | Defines the variable name for the exported markdown string. | | `headingIds` | `boolean` | `true` | Appends explicit heading anchors (`[#id]`) to output headings when present. | | `filterElement` | `StringifyOptions['filterElement']` | Custom function | Filters elements; excludes `mdxjsEsm` by default while retaining others. | | `mdxAsPlaceholder` | `string[]` | `undefined` | Target MDX component tag names to stringify as runtime placeholders. | | `_data` | `boolean` | `false` | Stores the generated markdown string inside `file.data.markdown`. | Sources: [packages/core/src/mdx-plugins/remark-llms.ts:9-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts#L9-L55) The internal stringifier customizes node serialization by invoking `placeholder` for matching `mdxJsxFlowElement` and `mdxJsxTextElement` nodes listed in `mdxAsPlaceholder`. ```typescript stringify(node, parent, state, info, ctx) { if (mdxAsPlaceholder) { switch (node.type) { case 'mdxJsxFlowElement': case 'mdxJsxTextElement': if (node.name && mdxAsPlaceholder.includes(node.name)) return placeholder(node, parent, state, info); } } return rest.stringify?.(node, parent, state, info, ctx); }, ``` Sources: [packages/core/src/mdx-plugins/remark-llms.ts:80-91](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts#L80-L91) > [!NOTE] > The `placeholder` helper extracts valid non-expression attributes, formats element phrasing children, and serializes the resulting payload into a null-delimited JSON string format conforming to `PlaceholderData`. > Sources: [packages/core/src/mdx-plugins/remark-llms.ts:112-129](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts#L112-L129) ### Postprocessing Pipeline and Frontmatter Extraction The `remarkPostprocess` transformer orchestrates document metadata generation, reference extraction, and optional LLM string export. It inspects configuration options to determine which values to extract and export into the module AST. | Option Property | Type | Default Value | Purpose | | --------------- | ---- | ------------- | ------- | | `_format` | `'md' \| 'mdx'` | Required | Specifies the underlying document format. | | `valueToExport` | `string[]` | `[]` | Additional property keys from `file.data` to export as named variables. | | `includeProcessedMarkdown` | `boolean \| LLMsOptions` | `false` | Enables `remarkLLMs` processing and exports the resulting string. | | `extractLinkReferences` | `boolean` | `false` | Collects link href values and exports them via `extractedReferences`. | | `includeMDAST` | `boolean \| { removePosition?: boolean }` | `false` | Serializes and exports the document MDAST via `_mdast`. | Sources: [packages/mdx/src/loaders/mdx/remark-postprocess.ts:14-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-postprocess.ts#L14-L40) > [!WARNING] > If `frontmatter.title` is missing, the postprocessor traverses the AST to find the first level-1 heading and flattens its text nodes to auto-populate the document title. > Sources: [packages/mdx/src/loaders/mdx/remark-postprocess.ts:56-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-postprocess.ts#L56-L64) Exported declarations are injected into the AST by converting JavaScript values into estree nodes using `valueToEstree`, wrapped in an `mdxjsEsm` node via `getMdastExport`, and prepended to the tree's children array. ```typescript function getMdastExport(name: string, value: unknown): RootContent { return { type: 'mdxjsEsm', value: '', data: { estree: { type: 'Program', sourceType: 'module', body: [ { type: 'ExportNamedDeclaration', attributes: [], specifiers: [], source: null, declaration: { type: 'VariableDeclaration', kind: 'let', declarations: [ { type: 'VariableDeclarator', id: { type: 'Identifier', name, }, init: valueToEstree(value), }, ], }, }, ], }, }, }; } ``` Sources: [packages/mdx/src/loaders/mdx/remark-postprocess.ts:128-161](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-postprocess.ts#L128-L161) ## Plugin presets and runtime aggregation ### Pipeline Composition and Resolution Fumadocs provides unified configuration presets that compose default remark and rehype plugin pipelines across different build environments and runtimes. The core package exports bundler and runtime preset factories (`mdxPreset`) alongside an MDX configuration preset (`applyMdxPreset`) that handles environments such as bundler or runtime. | Preset Function | Package | Environment Context | Default Output Format | | --------------- | ------- | ------------------- | --------------------- | | `mdxPreset` | `fumadocs-core/content/mdx/preset-bundler` | Bundler build tools (Next.js, Vite, Webpack) | Unmodified / default | | `mdxPreset` | `fumadocs-core/content/mdx/preset-runtime` | Local or runtime execution | `function-body` | | `applyMdxPreset` | `fumadocs/config/preset` | Configurable (`bundler` or `runtime`) | `function-body` (for runtime) | Sources: [packages/core/src/content/mdx/preset-bundler.ts:26-92](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L26-L92), [packages/core/src/content/mdx/preset-runtime.ts:23-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts#L23-L83), [packages/mdx/src/config/preset.ts:50-131](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L50-L131) The plugin resolution layer accepts user-defined arrays or functions, conditionally appending default remark plugins like `remarkGfm`, `remarkHeading`, `remarkImage`, `remarkCodeTab`, `remarkNpm`, and `remarkStructure`, as well as rehype plugins like `rehypeCode` and `rehypeToc`. ```typescript const remarkPlugins = await resolvePlugins( (v) => [ import('remark-gfm').then((mod) => mod.default), remarkHeadingOptions !== false && import('@/mdx-plugins/remark-heading').then((mod) => [ mod.remarkHeading, { generateToc: false, ...remarkHeadingOptions, }, ]), _include ?? false, remarkImageOptions !== false && import('@/mdx-plugins/remark-image').then((mod) => [ mod.remarkImage, { ...remarkImageOptions, useImport: remarkImageOptions?.useImport ?? true, }, ]), remarkCodeTabOptions !== false && import('@/mdx-plugins/remark-code-tab').then((mod) => [ mod.remarkCodeTab, remarkCodeTabOptions, ]), remarkNpmOptions !== false && import('@/mdx-plugins/remark-npm').then((mod) => [mod.remarkNpm, remarkNpmOptions]), ...v, remarkStructureOptions !== false && import('@/mdx-plugins/remark-structure').then((mod) => [ mod.remarkStructure, { exportAs: 'structuredData', ...remarkStructureOptions, } satisfies Plugins.StructureOptions, ]), ], mdxOptions.remarkPlugins, ); const rehypePlugins = await resolvePlugins( (v) => [ rehypeCodeOptions !== false && import('@/mdx-plugins/rehype-code').then((mod) => [mod.rehypeCode, rehypeCodeOptions]), ...v, import('@/mdx-plugins/rehype-toc').then((mod) => mod.rehypeToc), ], mdxOptions.rehypePlugins, ); ``` Sources: [packages/core/src/content/mdx/preset-bundler.ts:38-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L38-L86) > [!TIP] > Setting any preset option to `false` (such as `remarkImageOptions: false` or `rehypeCodeOptions: false`) explicitly disables that specific plugin from the unified pipeline. > Sources: [packages/core/src/content/mdx/preset-bundler.ts:15-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L15-L20), [packages/core/src/content/mdx/preset-bundler.ts:41-73](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L41-L73) ### Alternative Runtimes and Vault Compilers For lightweight markdown rendering and preview components, `createMarkdownCompiler` and `createMarkdownRenderer` instantiate standalone unified processors using `remark`, `remarkRehype`, and user-supplied plugin lists without full MDX compilation baggage. ```typescript const processor = remark() .use(remarkPlugins) .use(remarkRehype, remarkRehypeOptions) .use(rehypePlugins); ``` Sources: [packages/preview/src/lib/md.ts:37-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/md.ts#L37-L40), [packages/core/src/content/md.ts:35-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/md.ts#L35-L38) Similarly, the Obsidian integration builds a localized unified processor combining vault-specific remark plugins (`remarkWikilinks`, `remarkConvert`, `remarkObsidianComment`, and `remarkBlockId`) to transform vault files into compatible AST structures. ```typescript export function getRemarkPlugins(storage: VaultStorage, resolver: VaultResolver): PluggableList { return [ [remarkWikilinks, { resolver, storage }], [remarkConvert, { resolver, storage }], remarkObsidianComment, remarkBlockId, ]; ``` Sources: [packages/obsidian/src/remark/index.ts:9-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/index.ts#L9-L15), [packages/obsidian/src/mdx/index.ts:24-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts#L24-L24) ## Related - [Syntax Highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting) - [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline) --- ## Technical docs: Framework Routing Adapters URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/framework-routing-adapters
Relevant source files The following files were used as context for generating this wiki page: - [packages/core/src/framework/waku.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/waku.tsx) - [packages/core/src/framework/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx) - [packages/core/src/framework/react-router.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/react-router.tsx) - [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/core/src/framework/tanstack.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/tanstack.tsx) - [packages/base-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/base-ui/src/provider/waku.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/waku.tsx) - [packages/core/src/framework/next.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/next.tsx) - [packages/radix-ui/src/provider/react-router.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/react-router.tsx) - [packages/radix-ui/src/provider/waku.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/waku.tsx) - [packages/base-ui/src/provider/react-router.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/react-router.tsx) - [packages/create-app/src/transform/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/transform/index.ts) - [packages/core/src/dynamic-link.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/dynamic-link.tsx) - [packages/preview/src/waku.server.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/waku.server.tsx) - [packages/mdx/src/loaders/adapter.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/adapter.ts) - [packages/base-ui/src/provider/tanstack.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/tanstack.tsx) - [packages/create-app/src/transform/react-router.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/transform/react-router.ts) - [packages/radix-ui/src/provider/tanstack.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/tanstack.tsx) - [packages/base-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/slots/sidebar.tsx) - [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx) - [packages/mdx/src/runtime/browser.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx) - [packages/preview/src/components/provider.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/provider.tsx) - [packages/core/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json) - [packages/base-ui/src/provider/next.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/next.tsx) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/radix-ui/src/layouts/shared/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/index.tsx) - [packages/radix-ui/src/provider/next.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/next.tsx) - [packages/asyncapi/src/ui/contexts/api.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/contexts/api.tsx) - [packages/create-app/src/constants.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/constants.ts) - [packages/base-ui/src/layouts/shared/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/shared/index.tsx)
## Overview Framework Routing Adapters provide a unified abstraction layer that decouples Fumadocs UI components from underlying framework-specific routing and navigation primitives. By defining a common contract for path resolution, parameter extraction, and navigation hooks, Fumadocs supports multiple meta-frameworks without binding its core logic to any single ecosystem. Sources: [packages/core/src/framework/index.tsx:29-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L29-L41) ## Core Framework Abstraction Interface ### Public API Contract and Framework Context The core abstraction layer defines the structural contract for framework integration in `fumadocs-core`. The `Framework` interface specifies required navigation and routing functions alongside optional component overrides for links and images. A React context initialized via `createContext` stores this interface, defaulting to `notImplemented` stubs that throw an error prompting developers to wrap their application inside `FrameworkProvider`. ```tsx export interface Router { push: (url: string) => void | Promise; refresh: () => void | Promise; } export interface Framework { usePathname: () => string; useParams: () => Record; useRouter: () => Router; Link?: FC< ComponentProps<'a'> & { prefetch?: boolean; } >; Image?: FC; } const notImplemented = () => { throw new Error('You need to wrap your application inside `FrameworkProvider`.'); }; const FrameworkContext = createContext({ useParams: notImplemented, useRouter: notImplemented, usePathname: notImplemented, }); ``` Sources: [packages/core/src/framework/index.tsx:24-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L24-L51) | Member | Type | Purpose | | :--- | :--- | :--- | | `usePathname` | `() => string` | Returns the current URL pathname string | | `useParams` | `() => Record` | Extracts dynamic route parameters as a key-value record | | `useRouter` | `() => Router` | Provides navigation primitives (`push` and `refresh`) | | `Link` | `FC & { prefetch?: boolean }>` | Optional framework-specific anchor component override | | `Image` | `FC` | Optional framework-specific image component override | Sources: [packages/core/src/framework/index.tsx:29-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L29-L41) > [!WARNING] > Failing to wrap component trees in `FrameworkProvider` triggers a runtime error when any hook or core component attempts to access framework context, because the default stub functions throw immediately upon invocation. > > Sources: [packages/core/src/framework/index.tsx:43-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L43-L51) ### Provider Memoization and Routing Hooks The `FrameworkProvider` component accepts `Link`, `useRouter`, `useParams`, `usePathname`, `Image`, and `children`. It wraps its children with `FrameworkContext.Provider` (rendered as ``) utilizing `useMemo` to memoize the context object based on its provider dependencies. Individual custom hooks (`usePathname`, `useRouter`, `useParams`) consume this context using React's `use` hook to extract the active framework implementation. ```tsx export function FrameworkProvider({ Link, useRouter, useParams, usePathname, Image, children, }: Framework & { children: ReactNode }) { const framework = useMemo( () => ({ usePathname, useRouter, Link, Image, useParams, }), [Link, usePathname, useRouter, useParams, Image], ); return {children}; } export function usePathname() { return use(FrameworkContext).usePathname(); } export function useRouter() { return use(FrameworkContext).useRouter(); } export function useParams() { return use(FrameworkContext).useParams(); } ``` Sources: [packages/core/src/framework/index.tsx:53-85](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L53-L85) > [!TIP] > The framework context consumption relies on React's `use` API, allowing hooks to be safely called within consumer components as long as a valid `FrameworkProvider` exists higher in the tree. > > Sources: [packages/core/src/framework/index.tsx:75-85](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L75-L85) ### Component Fallbacks for Images and Links The core package provides robust fallback implementations for `Image` and `Link` components when no framework-specific override is supplied through the context. The `Image` component checks for a registered context `Image` component; if absent, it falls back to a standard `` element mapping the `priority` boolean prop to a `fetchPriority` attribute (`high` or `auto`). Similarly, the `Link` component falls back to a standard `` element when no framework link implementation is provided, destructuring out the `prefetch` prop to prevent invalid DOM attribute warnings. ```tsx export function Image(props: ImageProps) { const { Image } = use(FrameworkContext); if (!Image) { const { src, alt, priority, ...rest } = props; return ( {alt} ); } return ; } export function Link(props: LinkProps) { const { Link } = use(FrameworkContext); if (!Link) { const { href, prefetch: _, ...rest } = props; return ; } return ; } ``` Sources: [packages/core/src/framework/index.tsx:87-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/index.tsx#L87-L108) ## Next.js Routing Adapter Implementation ### NextProvider and App Router Primitives The Next.js framework adapter bridges Next.js App Router navigation hooks and UI components into the core framework context. Defined in `packages/core/src/framework/next.tsx`, the `NextProvider` component marks itself with `'use client'` and passes Next.js routing hooks—`usePathname`, `useRouter`, and `useParams` from `next/navigation`—directly into the underlying `FrameworkProvider`. It also accepts optional custom overrides for `Link` and `Image`, defaulting to `next/link` and `next/image` when custom components are omitted. ```tsx 'use client'; import { type Framework, FrameworkProvider } from '@/framework/index'; import type { ReactNode } from 'react'; import { useParams, usePathname, useRouter } from 'next/navigation'; import Link from 'next/link'; import Image from 'next/image'; export function NextProvider({ children, Link: CustomLink, Image: CustomImage, }: { children: ReactNode; Link?: Framework['Link']; Image?: Framework['Image']; }) { return ( {children} ); ``` Sources: [packages/core/src/framework/next.tsx:1-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/next.tsx#L1-L27) | Prop | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `children` | `ReactNode` | (Required) | React subtree wrapped by the provider | | `Link` | `Framework['Link']` | `next/link` | Custom anchor component override | | `Image` | `Framework['Image']` | `next/image` | Custom image component override | Sources: [packages/core/src/framework/next.tsx:8-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/next.tsx#L8-L27) > [!NOTE] > `NextProvider` relies on Next.js client-side navigation modules (`next/navigation`, `next/link`, `next/image`), requiring all consuming tree branches to execute within a Client Component boundary (`'use client'`). > > Sources: [packages/core/src/framework/next.tsx:1-6](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/next.tsx#L1-L6) ### UI Package Integration Wrappers The Radix UI and Base UI packages provide their own `RootProvider` components that encapsulate `NextProvider` alongside their respective design system providers (`BaseProvider`). Both `packages/base-ui/src/provider/next.tsx` and `packages/radix-ui/src/provider/next.tsx` accept `RootProviderProps` containing a `components` object with optional `Link` and `Image` overrides, forwarding them to `NextProvider` while spreading remaining props into `BaseProvider`. ```tsx 'use client'; import type { ComponentProps } from 'react'; import { RootProvider as BaseProvider } from '@/provider/base'; import { NextProvider } from 'fumadocs-core/framework/next'; import type { Framework } from 'fumadocs-core/framework'; export interface RootProviderProps extends ComponentProps { /** * Custom framework components to override Next.js defaults */ components?: { Link?: Framework['Link']; Image?: Framework['Image']; }; } export function RootProvider({ components, ...props }: RootProviderProps) { return ( {props.children} ); } ``` Sources: [packages/radix-ui/src/provider/next.tsx:1-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/next.tsx#L1-L23), [packages/base-ui/src/provider/next.tsx:1-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/next.tsx#L1-L22) > [!TIP] > By nesting `BaseProvider` inside `NextProvider`, UI packages ensure that design system primitives and documentation layouts access active Next.js routing context and custom component overrides simultaneously. > > Sources: [packages/radix-ui/src/provider/next.tsx:17-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/next.tsx#L17-L22), [packages/base-ui/src/provider/next.tsx:17-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/next.tsx#L17-L21) ## React Router Framework Integration ### Core Bridge and Navigation Hooks The core React Router adapter translates React Router hooks into the Fumadocs framework interface contract. Located in `packages/core/src/framework/react-router.tsx`, the adapter extracts the current path via `useLocation().pathname` and retrieves route parameters through `useParams()`, casting them to `Record`. ```tsx const framework: Framework = { usePathname() { return useLocation().pathname; }, useParams() { return useParams() as Record; }, ``` Sources: [packages/core/src/framework/react-router.tsx:5-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/react-router.tsx#L5-L11) Navigation actions are wrapped inside a memoized `useRouter` hook that combines `useNavigate` and `useRevalidator`. The `push` method delegates directly to `navigate(url)`, while `refresh` triggers `void revalidator.revalidate()`, with both actions dependent on `[navigate, revalidator]`. ```tsx useRouter() { const navigate = useNavigate(); const revalidator = useRevalidator(); return useMemo( () => ({ push(url) { navigate(url); }, refresh() { void revalidator.revalidate(); }, }), [navigate, revalidator], ); }, ``` Sources: [packages/core/src/framework/react-router.tsx:12-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/react-router.tsx#L12-L27) The framework's `Link` implementation maps the generic `href` property to React Router's `to` prop and converts boolean `prefetch` flags into `'intent'` or `'none'` string values. ```tsx Link({ href, prefetch, ...props }) { return ( {props.children} ); }, ``` Sources: [packages/core/src/framework/react-router.tsx:28-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/react-router.tsx#L28-L34) > [!NOTE] > React Router's `useRevalidator` returns a revalidation state object where `revalidate()` is an asynchronous function; the adapter explicitly voids the returned promise to satisfy lint rules within synchronous callback contexts. > > Sources: [packages/core/src/framework/react-router.tsx:21-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/react-router.tsx#L21-L23) ### Provider Wrappers and UI Package Integration The `ReactRouterProvider` component accepts children alongside optional custom `Link` and `Image` overrides, supplying them to the underlying `FrameworkProvider` by falling back to the default framework implementation when custom components are omitted. ```tsx export function ReactRouterProvider({ children, Link: CustomLink, Image: CustomImage, }: { children: ReactNode; Link?: Framework['Link']; Image?: Framework['Image']; }) { return ( {children} ); } ``` Sources: [packages/core/src/framework/react-router.tsx:37-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/react-router.tsx#L37-L55) Both Radix UI and Base UI provide specialized `RootProvider` components that bridge React Router into their respective design system providers. Found in `packages/radix-ui/src/provider/react-router.tsx` and `packages/base-ui/src/provider/react-router.tsx`, these providers accept `RootProviderProps` containing an optional `components` object with `Link` and `Image` properties, forwarding them into `ReactRouterProvider` while spreading remaining props into `BaseProvider`. ```tsx export interface RootProviderProps extends ComponentProps { /** * Custom framework components to override React Router defaults */ components?: { Link?: Framework['Link']; Image?: Framework['Image']; }; } export function RootProvider({ components, ...props }: RootProviderProps) { return ( {props.children} ); ``` Sources: [packages/radix-ui/src/provider/react-router.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/react-router.tsx#L7-L22), [packages/base-ui/src/provider/react-router.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/react-router.tsx#L7-L22) | Prop | Type | Purpose | | :--- | :--- | :--- | | `components` | `{ Link?: Framework['Link']; Image?: Framework['Image']; }` | Custom framework components to override React Router defaults | | `children` | `ReactNode` | React subtree rendered inside the base design system provider | Sources: [packages/radix-ui/src/provider/react-router.tsx:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/react-router.tsx#L7-L15), [packages/base-ui/src/provider/react-router.tsx:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/react-router.tsx#L7-L15) > [!WARNING] > UI package root providers for React Router require the `'use client'` directive at the module boundary to ensure React context hooks operate correctly in client-side routing environments. > > Sources: [packages/radix-ui/src/provider/react-router.tsx:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/react-router.tsx#L1-L1), [packages/base-ui/src/provider/react-router.tsx:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/react-router.tsx#L1-L1) ## TanStack Start Provider Layer ### TanStack Router Hooks and State Ref Caching The TanStack Start framework integration bridges TanStack Router primitives into Fumadocs via core definitions in `fumadocs-core`. The framework object configures a custom `Link` component mapping `href` to `to` and setting prefetch behavior to `'intent'` when enabled. ```tsx const framework: Framework = { Link({ href, prefetch = true, ...props }) { return ( {props.children} ); }, ``` Sources: [packages/core/src/framework/tanstack.tsx:5-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/tanstack.tsx#L5-L12) The `usePathname` hook leverages `useRouterState` to select both loading status and location pathname. To prevent layout flickering during route transitions, pathname updates use a persistent `useRef` combined with `useMemo` to return the cached active pathname while loading state is true. ```tsx usePathname() { const { isLoading, pathname } = useRouterState({ select: (state) => ({ isLoading: state.isLoading, pathname: state.location.pathname, }), }); const activePathname = useRef(pathname); return useMemo(() => { if (isLoading) { return activePathname.current; } activePathname.current = pathname; return pathname; }, [isLoading, pathname]); }, ``` Sources: [packages/core/src/framework/tanstack.tsx:13-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/tanstack.tsx#L13-L30) > [!NOTE] > During route transitions when `isLoading` is active, `usePathname` returns the cached reference value rather than the incoming intermediate pathname to maintain stable navigation highlighting. > > Sources: [packages/core/src/framework/tanstack.tsx:21-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/tanstack.tsx#L21-L29) Router actions are wrapped inside a memoized `useRouter` hook that invokes TanStack Router's `useRouter`. The `push` method delegates to `router.navigate({ href: url })` while `refresh` calls `router.invalidate()`. ```tsx useRouter() { const router = useRouter(); return useMemo( () => ({ push(url) { void router.navigate({ href: url, }); }, refresh() { void router.invalidate(); }, }), [router], ); }, ``` Sources: [packages/core/src/framework/tanstack.tsx:31-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/tanstack.tsx#L31-L47) Parameter extraction is handled by `useParams({ strict: false })`, and the entire definition is wrapped by `TanstackProvider` to supply context descendants with framework bindings. ```tsx useParams() { return useParams({ strict: false }); }, }; /** * Fumadocs adapter for Tanstack Router/Start */ export function TanstackProvider({ children, Link: CustomLink, Image: CustomImage, }: { children: ReactNode; Link?: Framework['Link']; Image?: Framework['Image']; }) { return ( {children} ); } ``` Sources: [packages/core/src/framework/tanstack.tsx:48-74](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/tanstack.tsx#L48-L74) ### UI Package Root Providers Both Base UI and Radix UI expose client-side `RootProvider` components that incorporate `TanstackProvider` from `fumadocs-core`. These providers accept optional component overrides for `Link` and `Image` within a `components` prop. ```tsx export interface RootProviderProps extends ComponentProps { /** * Custom framework components to override Tanstack Router defaults */ components?: { Link?: Framework['Link']; Image?: Framework['Image']; }; } export function RootProvider({ components, ...props }: RootProviderProps) { return ( {props.children} ); ``` Sources: [packages/base-ui/src/provider/tanstack.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/tanstack.tsx#L7-L22), [packages/radix-ui/src/provider/tanstack.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/tanstack.tsx#L7-L22) | Prop | Type | Purpose | | :--- | :--- | :--- | | `components` | `{ Link?: Framework['Link']; Image?: Framework['Image']; }` | Custom framework components to override TanStack Router defaults | | `children` | `ReactNode` | React subtree rendered inside the design system provider | Sources: [packages/base-ui/src/provider/tanstack.tsx:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/tanstack.tsx#L7-L15), [packages/radix-ui/src/provider/tanstack.tsx:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/tanstack.tsx#L7-L15) > [!WARNING] > Both package root provider files require the `'use client'` directive at the top of the module to operate correctly within React client component trees. > > Sources: [packages/base-ui/src/provider/tanstack.tsx:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/tanstack.tsx#L1-L1), [packages/radix-ui/src/provider/tanstack.tsx:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/tanstack.tsx#L1-L1) ## Waku Minimal Router Adapter ### Waku Router Context Bindings and Framework Definitions The Waku minimal router adapter connects Waku routing primitives into Fumadocs through core definitions in `fumadocs-core`. The framework object implements `usePathname` by calling Waku's `useRouter().path`, while `useParams` returns an empty object memoized with `useMemo` accompanied by a console warning. ```tsx const framework: Framework = { usePathname() { return useRouter().path; }, useParams() { console.warn('[Fumadocs] useParams() is not supported on Waku'); return useMemo(() => ({}), []); }, ``` Sources: [packages/core/src/framework/waku.tsx:7-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/waku.tsx#L7-L14) > [!WARNING] > The `useParams` hook on Waku emits a console warning (`[Fumadocs] useParams() is not supported on Waku`) and returns an empty object because route parameters are accessed directly via page props rather than context hooks. > > Sources: [packages/core/src/framework/waku.tsx:11-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/waku.tsx#L11-L14) Navigation actions are wrapped inside a memoized `useRouter` hook that caches the router instance using a `useRef`. The returned object provides `push(url)` delegating to `routerRef.current.push(url)` and `refresh()` calling `routerRef.current.reload()`. ```tsx useRouter() { const router = useRouter(); const routerRef = useRef(router); routerRef.current = router; return useMemo( () => ({ push(url: string) { return routerRef.current.push(url); }, refresh() { return routerRef.current.reload(); }, }), [], ); }, ``` Sources: [packages/core/src/framework/waku.tsx:15-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/waku.tsx#L15-L31) The framework `Link` component maps Fumadocs link properties to Waku's `Link` element, translating `href` to `to` and setting `unstable_prefetchOnEnter` to the `prefetch` boolean value defaulting to `true`. ```tsx Link({ href, prefetch = true, ...props }) { return ( {props.children} ); }, }; ``` Sources: [packages/core/src/framework/waku.tsx:32-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/waku.tsx#L32-L39) The `WakuProvider` component wraps `FrameworkProvider`, accepting optional custom `Link` and `Image` overrides and falling back to the framework defaults. ```tsx export function WakuProvider({ children, Link: CustomLink, Image: CustomImage, }: { children: ReactNode; Link?: Framework['Link']; Image?: Framework['Image']; }) { return ( {children} ); } ``` Sources: [packages/core/src/framework/waku.tsx:41-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/waku.tsx#L41-L59) ### UI Provider Wrappers and Preview Integration Both Base UI and Radix UI expose client-side `RootProvider` components specifically adapted for Waku. These components wrap children with `WakuProvider` and `BaseProvider`, accepting an optional `components` object to override `Link` and `Image`. ```tsx export interface RootProviderProps extends ComponentProps { /** * Custom framework components to override Waku defaults */ components?: { Link?: Framework['Link']; Image?: Framework['Image']; }; } export function RootProvider({ components, ...props }: RootProviderProps) { return ( {props.children} ); ``` Sources: [packages/base-ui/src/provider/waku.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/waku.tsx#L7-L22), [packages/radix-ui/src/provider/waku.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/waku.tsx#L7-L22) | Prop | Type | Purpose | | :--- | :--- | :--- | | `components` | `{ Link?: Framework['Link']; Image?: Framework['Image']; }` | Custom framework components to override Waku defaults | | `children` | `ReactNode` | React subtree rendered inside the design system provider | Sources: [packages/base-ui/src/provider/waku.tsx:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/waku.tsx#L7-L15), [packages/radix-ui/src/provider/waku.tsx:7-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/waku.tsx#L7-L15) The preview application leverages `fumadocs-ui/provider/waku` within its client provider component and configures dynamic routing inside `[...slugs].tsx`. The markdown compiler processes documents with remark plugins including `remarkGfm`, `remarkMath`, `remarkMdxMermaid`, `remarkHeading`, `remarkNpm`, and `remarkCodeTab`, alongside rehype plugins for `rehypeKatex`, `rehypeCode`, and `rehypeToc`. ```tsx const compiler = createMarkdownCompiler({ remarkPlugins: [ remarkGfm, remarkMath, remarkMdxMermaid, plugin(remarkHeading, { generateToc: false }), plugin(remarkNpm, { persist: { id: 'package-manager' } }), remarkCodeTab, ], remarkRehypeOptions: { passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement'], }, rehypePlugins: [ rehypeKatex, plugin(rehypeCode, { lazy: true, fallbackLanguage: 'text' }), plugin(rehypeToc, { exportToc: { as: 'data' } }), ], }); ``` Sources: [packages/preview/src/pages/...slugs.tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46) > [!NOTE] > The preview application uses dynamic configuration (`getConfig` returning `render: 'dynamic'`) and dynamically selects between `docs` and `flux` layout presets based on runtime configuration settings. > > Sources: [packages/preview/src/pages/[...slugs].tsx:76-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/[...slugs].tsx#L76-L96), [packages/preview/src/pages/[...slugs].tsx:225-229](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/[...slugs].tsx#L225-L229) ## Dynamic Links and Active Navigation ### Dynamic Link Href Resolution The `DynamicLink` component extends standard navigation links by substituting route parameters into templated path strings at runtime. By retrieving active route parameters through the `useParams` hook, `DynamicLink` computes updated URLs via `useMemo` before rendering the underlying `Link` element. ```tsx export const DynamicLink = forwardRef( ({ href, ...props }, ref) => { const params = useParams(); const url = useMemo(() => (href ? updateHref(href, params) : href), [params, href]); return ; }, ); ``` Sources: [packages/core/src/dynamic-link.tsx:15-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/dynamic-link.tsx#L15-L23) The underlying `updateHref` function parses parameter placeholders using regular expressions. If a matching key exists within the parameter dictionary, it substitutes the value—joining array segments with slashes if necessary—and preserves trailing slashes from the template pattern. ```tsx export function updateHref(href: string, params: Record) { return href.replace(/\[(.*)]\/?/, (match, key) => { const hasEndingSlash = match[match.length - 1] === '/'; const value = key in params ? params[key] : undefined; if (!value) return ''; const replacement = typeof value === 'string' ? value : value.join('/'); return hasEndingSlash ? `${replacement}/` : replacement; }); } ``` Sources: [packages/core/src/dynamic-link.tsx:27-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/dynamic-link.tsx#L27-L36) > [!WARNING] > If a route parameter placeholder lacks a matching key in the `params` record, `updateHref` evaluates `value` as undefined and returns an empty string for that segment. > > Sources: [packages/core/src/dynamic-link.tsx:30-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/dynamic-link.tsx#L30-L31) ### Active Navigation and Layout Tabs Layout structures determine active states for navigation links and folder tabs by evaluating the current pathname against registered URLs and page tree nodes. The `isLinkItemActive` function inspects link configuration objects, immediately returning `false` for custom item types or entries configured with `active: 'none'`. ```tsx export function updateHref(href: string, params: Record) { return href.replace(/\[(.*)]\/?/, (match, key) => { const hasEndingSlash = match[match.length - 1] === '/'; const value = key in params ? params[key] : undefined; if (!value) return ''; const replacement = typeof value === 'string' ? value : value.join('/'); return hasEndingSlash ? `${replacement}/` : replacement; }); } ``` Sources: [packages/core/src/dynamic-link.tsx:27-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/dynamic-link.tsx#L27-L36) Layout tabs generated from page tree structures evaluate active states by searching folder hierarchies for matching child page URLs or checking explicit URL sets and normalized path comparisons. ```tsx export function isLayoutTabActive(tab: LayoutTab, pathname: string) { if (tab.$folder) { return ( PageTree.findPath( tab.$folder.children, (node) => node.type === 'page' && isActive(node.url, pathname), ) !== null ); } if (tab.urls) { return tab.urls.has(normalize(pathname)); } return isActive(tab.url, pathname, true); } ``` Sources: [packages/radix-ui/src/layouts/shared/index.tsx:146-161](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/index.tsx#L146-L161) | Property | Type | Default | Purpose | | :--- | :--- | :--- | :--- | | `active` | `'url' \| 'nested-url' \| 'none'` | `'url'` | Defines active state matching criteria for navigation items | | `url` | `string` | — | Target destination URL for navigation and link resolution | | `external` | `boolean` | `false` | Indicates whether the link points to an external resource | | `on` | `'menu' \| 'nav' \| 'all'` | `'all'` | Restricts where link items are rendered within the layout | Sources: [packages/radix-ui/src/layouts/shared/index.tsx:163-181](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/index.tsx#L163-L181) ## Related - [Shared Layout Architecture](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture) --- ## Technical docs: Internationalization Support URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/internationalization-support
Relevant source files The following files were used as context for generating this wiki page: - [packages/base-ui/src/contexts/i18n.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/i18n.tsx) - [packages/language/src/zh-tw.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/src/zh-tw.ts) - [packages/radix-ui/src/contexts/i18n.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/i18n.tsx) - [packages/base-ui/src/i18n.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/i18n.tsx) - [packages/language/src/zh-cn.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/src/zh-cn.ts) - [packages/radix-ui/src/i18n.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/i18n.tsx) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/base-ui/src/contexts/tree.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/tree.tsx) - [packages/core/src/source/page-tree/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/builder.ts) - [packages/base-ui/src/layouts/flux/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/index.tsx) - [packages/core/src/source/llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/llms.ts) - [packages/radix-ui/src/layouts/flux/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx) - [packages/core/src/source/client/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx) - [packages/core/src/i18n/middleware.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts) - [packages/base-ui/src/layouts/shared/slots/language-select.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/shared/slots/language-select.tsx) - [packages/base-ui/src/layouts/flux/page/slots/footer.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/footer.tsx) - [packages/radix-ui/src/contexts/tree.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx) - [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts) - [packages/base-ui/src/utils/use-footer-items.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/utils/use-footer-items.ts) - [packages/radix-ui/src/utils/use-footer-items.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts) - [packages/api-docs/src/i18n.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/i18n.ts) - [packages/radix-ui/src/layouts/shared/slots/language-select.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/slots/language-select.tsx) - [packages/core/src/source/page-tree/transformer-fallback.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/page-tree/transformer-fallback.ts) - [packages/openapi/src/i18n.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/i18n.ts) - [packages/preview/src/components/provider.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/provider.tsx) - [packages/epub/src/toc-builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/src/toc-builder.ts) - [packages/preview/src/layouts/config.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/layouts/config.tsx) - [packages/asyncapi/src/i18n.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/i18n.ts) - [packages/base-ui/src/layouts/home/not-found.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/home/not-found.tsx) - [packages/radix-ui/src/layouts/home/not-found.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/home/not-found.tsx)
## Overview Fumadocs provides comprehensive internationalization support for multi-language documentation projects, coordinating server-side locale negotiation, request proxy middleware, and client React context providers. It bridges server-rendered storage collections with reactive UI components, enabling seamless language switching, localized navigation trees, and extensible translation dictionaries across base and Radix UI layouts. Sources: [packages/core/src/i18n/middleware.ts:56-110](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts#L56-L110), [packages/base-ui/src/contexts/i18n.tsx:33-72](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/i18n.tsx#L33-L72), [packages/radix-ui/src/contexts/i18n.tsx:49-89](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/i18n.tsx#L49-L89), [packages/base-ui/src/i18n.tsx:52-71](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/i18n.tsx#L52-L71), [packages/core/src/source/loader.ts:303-346](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts#L303-L346) ## Routing Middleware and Negotiation ### Middleware Options and URL Formatting The `createI18nMiddleware` function generates a Next.js proxy middleware to handle internationalization routing, language detection, and header negotiation based on `MiddlewareOptions` and core `I18nConfig`. ```typescript interface MiddlewareOptions extends I18nConfig { format?: URLFormatter | ((locale: string, pathname: string) => string); cookieName?: string; } export interface URLFormatter { get: (url: NextURL) => string | undefined; add: (url: NextURL, locale: string) => URL; remove: (url: NextURL) => URL; } ``` Sources: [packages/core/src/i18n/middleware.ts:7-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts#L7-L36) | Option / Method | Type | Default | Purpose | | :--- | :--- | :--- | :--- | | `languages` | `string[]` | *Required* | Supported language codes for the project | | `defaultLanguage` | `string` | *Required* | Fallback language used when negotiation fails or matches defaults | | `format` | `URLFormatter \| Function` | `DefaultFormatter` | Formatter object or custom function to add, remove, or retrieve locale prefixes | | `cookieName` | `string` | `'FD_LOCALE'` | Cookie key storing the active locale when `hideLocale` is set to `'always'` | | `hideLocale` | `'never' \| 'always' \| 'default-locale'` | `'never'` | Strategy for hiding locale segments in the request pathname | | `URLFormatter.get` | `(url: NextURL) => string \| undefined` | *DefaultFormatter* | Extracts the locale segment from the request URL pathname | | `URLFormatter.add` | `(url: NextURL, locale: string) => URL` | *DefaultFormatter* | Inserts the locale prefix and project base path into the URL | | `URLFormatter.remove` | `(url: NextURL) => URL` | *DefaultFormatter* | Strips the explicit locale segment from the URL pathname | Sources: [packages/core/src/i18n/middleware.ts:38-75](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts#L38-L75) ### Request Routing and Negotiation Flow When a request enters the proxy middleware, the handler extracts the current path locale using `formatter.get(url)`. If the extracted segment is not present in the configured `languages` array, it is treated as undefined. ```typescript export const DefaultFormatter: URLFormatter = { get(url) { const segs = url.pathname.split('/'); if (segs.length > 1 && segs[1]) return segs[1]; }, add(url, locale) { const next = new URL(url); next.pathname = `${url.basePath}/${locale}/${url.pathname}`.replaceAll(/\/+/g, '/'); return next; }, remove(url) { const next = new URL(url); const pathname = url.pathname.split('/').slice(2).join('/'); next.pathname = `${url.basePath}/${pathname}`.replaceAll(/\/+/g, '/'); return next; }, }; ``` Sources: [packages/core/src/i18n/middleware.ts:38-54](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts#L38-L54) Depending on the configured `hideLocale` strategy, requests without a valid path locale trigger different routing behaviors: - If `hideLocale` is `'default-locale'`, the middleware rewrites the request to the URL formatted with `defaultLanguage`. - If `hideLocale` is `'always'`, it retrieves the locale from the request cookie specified by `cookieName`, falling back to language negotiation via `@formatjs/intl-localematcher` and `getNegotiator`, then rewrites to the formatted URL. - Otherwise, it issues an HTTP redirect to the preferred negotiated locale URL. ```typescript if (!pathLocale) { if (hideLocale === 'default-locale') { return NextResponse.rewrite(formatter.add(url, defaultLanguage)); } const finalLanguages = getNegotiator(request).languages(languages); const preferred = matchLocale(finalLanguages, languages, defaultLanguage); if (hideLocale === 'always') { const locale = request.cookies.get(cookieName)?.value ?? preferred; return NextResponse.rewrite(formatter.add(url, locale)); } return NextResponse.redirect(formatter.add(url, preferred)); } ``` Sources: [packages/core/src/i18n/middleware.ts:82-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts#L82-L96) > [!WARNING] > When `hideLocale` is set to `'always'` or `'default-locale'` (when matching the default language), explicit locale prefixes in the URL are stripped via `formatter.remove(url)` and a redirect response is returned while simultaneously persisting the active locale code into the `cookieName` cookie. Sources: [packages/core/src/i18n/middleware.ts:98-106](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/i18n/middleware.ts#L98-L106) ## Client Context and Localization Hooks ### Translation APIs and Configuration Helpers Client-side internationalization relies on React context providers and navigation hooks implemented identically across both `packages/base-ui` and `packages/radix-ui`. The `LocaleContext` supplies active locale state, available language items, and an `onChange` updater function accessed through the `useI18n` hook. ```typescript interface LocaleItem { name: string; locale: string; } interface LocaleContextType { locale?: string; onChange?: (v: string) => void; locales?: LocaleItem[]; } const LocaleContext = createContext({}); export function useI18n(): LocaleContextType { return use(LocaleContext); } ``` Sources: [packages/base-ui/src/contexts/i18n.tsx:6-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/i18n.tsx#L6-L21), [packages/radix-ui/src/contexts/i18n.tsx:6-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/i18n.tsx#L6-L21) The `I18nProvider` component wraps application trees with both `LocaleContext` and `@fuma-translate/react`'s `TranslationProvider`. When `onLocaleChange` is omitted, the provider's built-in locale switcher mutates the current pathname by replacing or prepending the target language segment before calling `router.push`. ```typescript export function I18nProvider({ locales = [], locale, onLocaleChange, children, translations = Empty, }: I18nProviderProps) { const router = useRouter(); const pathname = usePathname(); const onChange = (value: string) => { if (onLocaleChange) { return onLocaleChange(value); } const segments = pathname.split('/').filter((v) => v.length > 0); if (segments.length === 0 || segments[0] !== locale) { segments.unshift(value); } else { segments[0] = value; } router.push(`/${segments.join('/')}`); }; ``` Sources: [packages/base-ui/src/contexts/i18n.tsx:33-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/i18n.tsx#L33-L55), [packages/radix-ui/src/contexts/i18n.tsx:49-72](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/i18n.tsx#L49-L72) > [!NOTE] > `I18nProvider` maintains an `onChangeRef` synchronized with the latest `onChange` callback on every render, ensuring stable memoized context references passed to descendant components. Sources: [packages/base-ui/src/contexts/i18n.tsx:56-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/i18n.tsx#L56-L69), [packages/radix-ui/src/contexts/i18n.tsx:73-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/i18n.tsx#L73-L86) Helper functions in `packages/base-ui/src/i18n.tsx` and `packages/radix-ui/src/i18n.tsx` bridge core translation dictionaries with UI provider properties. The `uiTranslations` extension injects localized UI keys, while `i18nProvider` resolves language fallbacks and maps supported language codes to display names. | Function / Helper | Signature | Purpose | | :--- | :--- | :--- | | `uiTranslations` | `() => TranslationExtension` | Returns compiled UI translation keys from package assets | | `i18nProvider` | `(translations, lang?) => I18nProviderProps` | Generates provider properties including locale, translations, and mapped `locales` array | | `defineI18nUI` | `(config, localeTranslations) => I18nUIConfig` | Extends an `I18nConfig` object with a custom `provider` factory method | Sources: [packages/base-ui/src/i18n.tsx:12-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/i18n.tsx#L12-L46), [packages/radix-ui/src/i18n.tsx:12-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/i18n.tsx#L12-L46) > [!WARNING] > When resolving language display names in `i18nProvider`, the implementation defaults to `'English'` if `t.get(code).displayName` is undefined. Sources: [packages/base-ui/src/i18n.tsx:35-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/i18n.tsx#L35-L39), [packages/radix-ui/src/i18n.tsx:35-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/i18n.tsx#L35-L39) ## Language Selection Interface Components ### Language Switcher and Popover Presentation The `LanguageSelect` component provides an interactive dropdown interface using primitive popover components. It retrieves the active language context via `useI18n()` and throws an error if `context.locales` is uninitialized. The trigger element renders with configurable button variants and applies an accessibility label through `@fuma-translate/react`. ```tsx export function LanguageSelect({ className, variant = 'ghost', children, ...rest }: LanguageSelectProps): React.ReactElement { const context = useI18n(); const t = useTranslations({ note: 'language switcher' }); if (!context.locales) throw new Error('Missing ``'); const chooseLanguage = t('Choose a language'); return ( cn(buttonVariants({ variant }), 'gap-1.5 p-1.5', s.open && 'bg-fd-accent', className) } {...rest} > {children}

{chooseLanguage}

``` Sources: [packages/base-ui/src/layouts/shared/slots/language-select.tsx:14-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/shared/slots/language-select.tsx#L14-L38) ```tsx export function LanguageSelect({ className, variant = 'ghost', children, ...rest }: LanguageSelectProps): React.ReactElement { const context = useI18n(); const t = useTranslations({ note: 'language switcher' }); if (!context.locales) throw new Error('Missing ``'); const chooseLanguage = t('Choose a language'); return ( {children}

{chooseLanguage}

``` Sources: [packages/radix-ui/src/layouts/shared/slots/language-select.tsx:14-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/slots/language-select.tsx#L14-L40) > [!WARNING] > Both package implementations require a parent ``; omitting the provider causes `LanguageSelect` to throw an error immediately during render when `context.locales` is missing. Sources: [packages/base-ui/src/layouts/shared/slots/language-select.tsx:22-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/shared/slots/language-select.tsx#L22-L22), [packages/radix-ui/src/layouts/shared/slots/language-select.tsx:22-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/slots/language-select.tsx#L22-L22) ### Locale Selection and Text Display Inside the popover content, available locales are mapped into interactive buttons. Clicking an item triggers `context.onChange?.(item.locale)` to update the active language. The currently active locale receives distinct styling (`bg-fd-primary/10 text-fd-primary`), while unselected options display muted foreground colors with hover states. ```tsx

{chooseLanguage}

{context.locales.map((item) => ( ))}
``` Sources: [packages/base-ui/src/layouts/shared/slots/language-select.tsx:37-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/shared/slots/language-select.tsx#L37-L56) ```tsx

{chooseLanguage}

{context.locales.map((item) => ( ))}
``` Sources: [packages/radix-ui/src/layouts/shared/slots/language-select.tsx:39-58](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/slots/language-select.tsx#L39-L58) The companion `LanguageSelectText` component extracts the display name of the currently active locale from the i18n context and renders it inside a span element. ```tsx export type LanguageSelectTextProps = ComponentProps<'span'>; export function LanguageSelectText(props: LanguageSelectTextProps) { const { locales, locale } = useI18n(); const text = locales?.find((item) => item.locale === locale)?.name; return {text}; } ``` Sources: [packages/base-ui/src/layouts/shared/slots/language-select.tsx:61-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/shared/slots/language-select.tsx#L61-L68) ```tsx export type LanguageSelectTextProps = ComponentProps<'span'>; export function LanguageSelectText(props: LanguageSelectTextProps) { const { locales, locale } = useI18n(); const text = locales?.find((item) => item.locale === locale)?.name; return {text}; } ``` Sources: [packages/radix-ui/src/layouts/shared/slots/language-select.tsx:63-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/slots/language-select.tsx#L63-L70) ## Translation Presets and Extension Schemas ### Structured Dictionary Bundles and Extension Extensions Fumadocs structures internationalization dictionaries by combining base UI translations with extension tokens from specialized domain packages. Packages like `@fumadocs/api-docs`, `fumadocs-openapi`, and `@fumadocs/asyncapi` export dedicated translation extension functions that load compiled JSON translation keys and return a `TranslationExtension` object matching `keyof Translations`. For instance, `apiDocsTranslations()` reads from `@/.translations/keys.json` to yield typed translation keys for schema UIs and playgrounds. ```typescript import translationKeys from '@/.translations/keys.json'; import type { TranslationExtension } from 'fumadocs-core/i18n'; import type { Translations } from '@/.translations'; export type { Translations }; export function apiDocsTranslations(): TranslationExtension { return { keys: translationKeys as never }; } ``` Sources: [packages/api-docs/src/i18n.ts:1-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/i18n.ts#L1-L8) Domain-specific packages such as `openapiTranslations()` and `asyncapiTranslations()` compose their own translation keys with shared schema UI keys by invoking `apiDocsTranslations()` internally and spreading both key arrays into a unified extension object. ```typescript import translationKeys from '@/.translations/keys.json'; import type { TranslationExtension } from 'fumadocs-core/i18n'; import type { Translations } from '@/.translations'; import { type Translations as SharedTranslations, apiDocsTranslations, } from '@fumadocs/api-docs/i18n'; export type { Translations }; export function openapiTranslations(): TranslationExtension< keyof Translations | keyof SharedTranslations > { const shared = apiDocsTranslations(); return { keys: [...shared.keys, ...translationKeys] as never }; } ``` Sources: [packages/openapi/src/i18n.ts:1-16](https://github.com/blade47/fumadox/blob/HEAD/packages/openapi/src/i18n.ts#L1-L16), [packages/asyncapi/src/i18n.ts:1-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/i18n.ts#L1-L15) > [!NOTE] > The `openapiTranslations()` function merges shared schema translation keys from `@fumadocs/api-docs` with OpenAPI-specific keys, ensuring schema UI components and playground controls resolve their labels correctly in multilingual builds. > Sources: [packages/openapi/src/i18n.ts:11-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/i18n.ts#L11-L16) ### Multilingual Bundling and Legacy Configuration Multilingual dictionary bundling is illustrated by comprehensive locale definitions such as Traditional Chinese (`zh-tw.ts`) and Simplified Chinese (`zh-cn.ts`). These language files aggregate type definitions across all dependent packages and supply localized strings for user interfaces, API playgrounds, OpenAPI operations, and AsyncAPI channels. ```typescript import type { TranslationPreset } from 'fumadocs-core/i18n'; import type { Translations as UITranslations } from 'fumadocs-ui/i18n'; import type { Translations as OpenAPITranslations } from 'fumadocs-openapi/i18n'; import type { Translations as AsyncAPITranslations } from '@fumadocs/asyncapi/i18n'; import type { Translations as StoryTranslations } from '@fumadocs/story/i18n'; import type { Translations as APIDocsTranslations } from '@fumadocs/api-docs/i18n'; type Translations = UITranslations & OpenAPITranslations & AsyncAPITranslations & StoryTranslations & APIDocsTranslations; ``` Sources: [packages/language/src/zh-tw.ts:1-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/src/zh-tw.ts#L1-L12), [packages/language/src/zh-cn.ts:1-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/language/src/zh-cn.ts#L1-L12) For backward compatibility with legacy setups, `defineI18nOpenAPI` wraps an existing `I18nUIConfig` instance, overriding its `provider` method to inject partial translation dictionaries for specific locales dynamically during runtime localization lookup. ```typescript export function defineI18nOpenAPI( config: I18nUIConfig, translations: Partial, Partial>>, ): I18nUIConfig { return { ...config, provider(locale = config.defaultLanguage) { const out = config.provider(locale); const data = translations[locale as Languages]; if (data) { out.translations = { ...out.translations, ...data }; } return out; }, }; } ``` Sources: [packages/openapi/src/i18n.ts:19-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/i18n.ts#L19-L33) > [!WARNING] > The `defineI18nOpenAPI` helper is marked as deprecated; developers are advised to use `i18n.translations()` combined with `openapiTranslations()` instead of wrapping the i18n UI configuration object. > Sources: [packages/openapi/src/i18n.ts:18-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/i18n.ts#L18-L18) ## Localized Tree Navigation and Pagination ### Tree Context Resolution and Active Page Traversal The `TreeContextProvider` component initializes tree navigation by wrapping raw page trees and resolving active hierarchies. It tracks the current location via `usePathname()` and computes the active breadcrumb path by invoking `searchPath(tree.children, pathname)`, falling back to `tree.fallback?.children` if necessary. ```typescript export function TreeContextProvider({ tree: rawTree, children, }: { tree: PageTree.Root; children: ReactNode; }) { const nextIdRef = useRef(0); const pathname = usePathname(); const tree = useMemo(() => rawTree, [rawTree.$id]); const path = useMemo(() => { return ( searchPath(tree.children, pathname) ?? (tree.fallback ? searchPath(tree.fallback.children, pathname) : null) ?? [] ); }, [tree, pathname]); const root = path.findLast((item) => item.type === 'folder' && item.root) ?? tree; root.$id ??= String(nextIdRef.current++); return ( ({ root, full: tree }) as TreeContextType, [root, tree])}> {children} ); } ``` Sources: [packages/base-ui/src/contexts/tree.tsx:17-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/tree.tsx#L17-L47), [packages/radix-ui/src/contexts/tree.tsx:17-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L17-L47) > [!NOTE] > Object-typed tree props passed from Server Components can be re-constructed across renders, breaking hook dependencies. `TreeContextProvider` mitigates this by memoizing on `rawTree.$id` and assigning a fallback identifier using `nextIdRef` if `$id` is uninitialized. > Sources: [packages/base-ui/src/contexts/tree.tsx:27-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/tree.tsx#L27-L40), [packages/radix-ui/src/contexts/tree.tsx:27-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/contexts/tree.tsx#L27-L40) ### Footer Pagination Linking Across Page Trees The `useFooterItems()` hook flattens the active tree root into a linear sequence of non-external page nodes, caching the result in a `WeakMap` indexed by `PageTree.Root` or `PageTree.Folder`. Folder index nodes are traversed first before processing child entries. ```typescript const footerCache = new WeakMap(); export function useFooterItems(): PageTree.Item[] { const { root } = useTreeContext(); const cached = footerCache.get(root); if (cached) return cached; const list: PageTree.Item[] = []; function onNode(node: PageTree.Node) { if (node.type === 'folder') { if (node.index) onNode(node.index); for (const child of node.children) onNode(child); } else if (node.type === 'page' && !node.external) { list.push(node); } } for (const child of root.children) onNode(child); footerCache.set(root, list); return list; } ``` Sources: [packages/base-ui/src/utils/use-footer-items.ts:5-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/utils/use-footer-items.ts#L5-L27), [packages/radix-ui/src/utils/use-footer-items.ts:5-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/utils/use-footer-items.ts#L5-L27) The `Footer` component consumes this flattened array, locating the active index via `isActive(item.url, pathname)` to supply previous and next page references for pagination links. ```typescript export function Footer({ items, children, className, ...props }: FooterProps) { const footerList = useFooterItems(); const pathname = usePathname(); const { previous, next } = useMemo(() => { if (items) return items; const idx = footerList.findIndex((item) => isActive(item.url, pathname)); if (idx === -1) return {}; return { previous: footerList[idx - 1], next: footerList[idx + 1], }; }, [footerList, items, pathname]); return ( <>
{previous && } {next && }
{children} ); } ``` Sources: [packages/base-ui/src/layouts/flux/page/slots/footer.tsx:25-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/footer.tsx#L25-L56) ## Related - [Page Tree Generation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/page-tree-generation) - [Shared Layout Architecture](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture) --- ## Technical docs: MDX Loader Pipeline URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline
Relevant source files The following files were used as context for generating this wiki page: - [packages/mdx/src/loaders/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts) - [packages/mdx/src/core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts) - [packages/mdx/src/bun/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts) - [packages/mdx/src/rolldown/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts) - [packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts) - [packages/mdx/src/loaders/mdx/build-mdx.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts) - [packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts) - [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts) - [packages/mdx-remote/src/compile.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts) - [packages/mdx/src/webpack/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts) - [packages/mdx/src/next/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) - [packages/mdx/src/node/_loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts) - [packages/mdx/src/webpack/mdx.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/mdx.ts) - [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/local-md/src/md/compiler.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/obsidian/src/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts) - [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts) - [packages/mdx/src/loaders/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts) - [packages/mdx/src/node/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/loader.ts) - [packages/mdx/src/config/preset.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts) - [packages/mdx/src/runtime/browser.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx) - [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts) - [packages/mdx/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json) - [packages/preview/src/lib/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/md.ts) - [packages/core/src/content/mdx/preset-runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts) - [packages/core/src/mdx-plugins/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/index.ts)
## Overview The MDX loader pipeline handles content transformation and bundling within [Bundler Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/bundler-plugins), [Content Compiler Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/content-compiler-plugins), and [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) integrations. It processes documentation source files through unified processors, applying remark and rehype transformations to generate type-safe modules and structured outputs. Sources: [packages/mdx/src/loaders/mdx/index.ts:25-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L25-L108), [packages/mdx/src/loaders/mdx/build-mdx.ts:74-122](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L74-L122) ## MDX Loader Factory and Entrypoints ### Loader Factory and Query Validation The `createMdxLoader` factory function receives a `ConfigLoader` and returns a standard `Loader` object that tests files against `mdxLoaderGlob`. During the `load` execution, query parameters are validated via `querySchema`, which parses loose objects with default options: `only` (`frontmatter` or `all`), `collection`, and `workspace`. If a workspace identifier is provided, the core instance is retrieved from `core.getWorkspaces()`. ```typescript const querySchema = z.looseObject({ only: z.literal(['frontmatter', 'all']).default('all'), collection: z.string().optional(), workspace: z.string().optional(), }); ``` Sources: [packages/mdx/src/loaders/mdx/index.ts:11-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L11-L15) > [!NOTE] > When `only` is set to `frontmatter`, the loader skips MDX compilation entirely and returns a serialized export of the parsed frontmatter data directly. Sources: [packages/mdx/src/loaders/mdx/index.ts:81-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L81-L86) Build caching can be enabled under production environments when `experimentalBuildCache` is set in global configuration. The loader checks disk cache entries using an MD5 hash of the file path and compares content hashes to avoid redundant compilations. Sources: [packages/mdx/src/loaders/mdx/index.ts:39-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L39-L60) Sources: [packages/mdx/src/loaders/mdx/index.ts:25-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L25-L60) ### Node Entrypoints and Execution Sequence Node.js module loading integration is provided via `initialize` and `load` hooks in `packages/mdx/src/node/_loader.ts`, as well as a deprecated legacy loader export in `packages/mdx/src/node/loader.ts`. The modern module loader initializes a core instance with the `node-loader` environment and builds standalone configuration loaders before wrapping MDX and meta loaders for Node. Sources: [packages/mdx/src/node/_loader.ts:11-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L11-L29), [packages/mdx/src/node/loader.ts:8-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/loader.ts#L8-L27) ```mermaid sequenceDiagram participant _loader.ts participant index.ts (mdx) participant build-mdx.ts _loader.ts->>index.ts (mdx): 1. initialize() index.ts (mdx)->>index.ts (mdx): 2. createMdxLoader() index.ts (mdx)->>build-mdx.ts: 3. buildMDX() build-mdx.ts->>build-mdx.ts: 4. getProcessor() ``` Sources: [packages/mdx/src/loaders/mdx/index.ts:25-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L25-L28), [packages/mdx/src/node/_loader.ts:11-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L11-L25), [packages/mdx/src/loaders/mdx/build-mdx.ts:74-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L74-L81) The pipeline execution sequence flows through specific functions during document loading: 1. `initialize` — Sets up the core configuration and hooks in `packages/mdx/src/node/_loader.ts`. Sources: [packages/mdx/src/node/_loader.ts:11-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L11-L29) 2. `createMdxLoader` — Instantiates the loader object and parses query parameters and frontmatter in `packages/mdx/src/loaders/mdx/index.ts`. Sources: [packages/mdx/src/loaders/mdx/index.ts:25-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L25-L32) 3. `buildMDX` — Coordinates VFile preparation, custom transformations, and compiler invocation in `packages/mdx/src/loaders/mdx/build-mdx.ts`. Sources: [packages/mdx/src/loaders/mdx/build-mdx.ts:74-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L74-L121) 4. `getProcessor` — Retrieves or creates a cached Unified processor instance configured with remark and postprocess plugins in `packages/mdx/src/loaders/mdx/build-mdx.ts`. Sources: [packages/mdx/src/loaders/mdx/build-mdx.ts:81-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L81-L108) Sources: [packages/mdx/src/loaders/mdx/index.ts:25-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L25-L32), [packages/mdx/src/node/_loader.ts:11-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L11-L29), [packages/mdx/src/loaders/mdx/build-mdx.ts:74-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L74-L121) ## MDX Compilation with Unified Processors ### Call-Chain Execution Walkthrough and Sequence The execution trace for building and compiling MDX content flows through four primary stages, invoking specific functions in sequence: `loader` → `createMdxLoader` → `buildMDX` → `getProcessor`. 1. `loader` — The Webpack or bundler adapter receives raw file content and calls the asynchronous loader callback function. Sources: [packages/mdx/src/webpack/mdx.ts:9-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/mdx.ts#L9-L28) 2. `createMdxLoader` — Parses query parameters, reads frontmatter, checks build caches, and calls `buildMDX` with the adjusted source string and compiler context. Sources: [packages/mdx/src/loaders/mdx/index.ts:28-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L28-L97) 3. `buildMDX` — Initializes a `VFile` instance with the source string, file path, and embedded custom properties like `_getProcessor`, applies collection-level transforms via `transformVFile`, and invokes the processor. Sources: [packages/mdx/src/loaders/mdx/build-mdx.ts:74-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L74-L121) 4. `getProcessor` — Retrieves or instantiates a cached Unified processor using `@mdx-js/mdx` configured with `remarkInclude`, user remark plugins, and `remarkPostprocess`. Sources: [packages/mdx/src/loaders/mdx/build-mdx.ts:81-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L81-L108) ```mermaid sequenceDiagram participant mdx.ts (webpack) participant index.ts (mdx) participant build-mdx.ts mdx.ts (webpack)->>index.ts (mdx): loader() index.ts (mdx)->>build-mdx.ts: buildMDX() build-mdx.ts->>build-mdx.ts: getProcessor() ``` Sources: [packages/mdx/src/webpack/mdx.ts:9-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/mdx.ts#L9-L28), [packages/mdx/src/loaders/mdx/index.ts:88-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L88-L97), [packages/mdx/src/loaders/mdx/build-mdx.ts:74-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L74-L121) ### Compiler Options and Data Types | Property | Type | Purpose | | :--- | :--- | :--- | | `filePath` | `string` | Specifies the absolute or relative file path for the source document being compiled. | | `source` | `string` | Raw markdown or MDX content string, offset by frontmatter newline counts. | | `environment` | `'bundler' \| 'runtime'` | Defines the target execution environment for MDX configuration loading. | | `isDevelopment` | `boolean` | Flags whether development mode is active, toggling debug features in `@mdx-js/mdx`. | | `_compiler` | `CompilerOptions` | Optional compiler reference supplying an `addDependency` method for file watchers. | Sources: [packages/mdx/src/loaders/mdx/build-mdx.ts:14-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts#L14-L29) > [!WARNING] > When compiling documents, `buildMDX` prepends newline characters corresponding to the exact length of the stripped frontmatter block. This ensures that line numbers reported in parser or compilation errors match the original source file line numbers precisely. Sources: [packages/mdx/src/loaders/mdx/index.ts:88-92](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts#L88-L92) ## Preset Plugins and Processor Configuration ### Preset Application and Options Architecture The configuration pipeline provides two main preset options: `fumadocs` and `minimal`. The `applyMdxPreset` function accepts `MDXPresetOptions` and returns an asynchronous function resolving to `@mdx-js/mdx` `ProcessorOptions`. When set to `minimal`, options are returned directly without plugin injections. The `mdxPreset` function in the core package similarly builds processor options with a default `outputFormat` of `'function-body'` for server or runtime evaluation. | Option Key | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `preset` | `'fumadocs' \| 'minimal'` | `'fumadocs'` | Selects the processor preset strategy. | | `valueToExport` | `string[]` | `[]` | Specifies property names to export from `vfile.data`. | | `remarkStructureOptions` | `Plugins.StructureOptions \| false` | `{ exportAs: 'structuredData' }` | Configures headings and structure extraction. | | `remarkHeadingOptions` | `Plugins.RemarkHeadingOptions` | `{ generateToc: false }` | Configures heading parsing without TOC generation. | | `remarkImageOptions` | `Plugins.RemarkImageOptions \| false` | Dynamic (`useImport` true for bundlers) | Configures image processing behaviors. | | `remarkCodeTabOptions` | `Plugins.RemarkCodeTabOptions \| false` | `undefined` | Enables or configures code tab remark processing. | | `remarkNpmOptions` | `Plugins.RemarkNpmOptions \| false` | `undefined` | Enables or configures package manager code block transformations. | | `rehypeCodeOptions` | `Plugins.RehypeCodeOptions \| false` | `undefined` | Configures [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting) and code block enhancements. | Sources: [packages/mdx/src/config/preset.ts:8-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L8-L46), [packages/core/src/content/mdx/preset-runtime.ts:5-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts#L5-L18) > [!NOTE] > In bundler environments, `remarkImage` defaults `useImport` to `true`, ensuring image sources are correctly imported as module assets. In runtime environments, bundler-specific outputs shift to function bodies. Sources: [packages/mdx/src/config/preset.ts:82-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L82-L82), [packages/mdx/src/config/preset.ts:127-127](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L127-L127) ### Remark and Rehype Plugin Pipeline The remark plugin pipeline integrates `remarkGfm`, `remarkHeading`, `remarkImage`, `remarkCodeTab`, `remarkNpm`, and `remarkStructure`. It also processes custom `valueToExport` arrays by reading matching keys from `file.data` and pushing them into `file.data['mdx-export']`. The rehype pipeline integrates `rehypeCode` and `rehypeToc`. Both pipelines support custom Pluggable arrays or modifier functions via `pluginOption` or `resolvePlugins`. ```typescript export * from './remark-gfm'; export * from './rehype-code'; export * from './remark-image'; export * from './remark-structure'; export * from './remark-heading'; export * from './remark-admonition'; export * from './remark-directive-admonition'; export * from './rehype-toc'; export * from './remark-code-tab'; export * from './remark-steps'; export * from './remark-npm'; export * from './codeblock-utils'; export { remarkMdxFiles, type RemarkMdxFilesOptions } from './remark-mdx-files'; export * from './remark-mdx-mermaid'; export * from './remark-feedback-block'; export type { LLMsOptions } from './remark-llms'; ``` Sources: [packages/core/src/mdx-plugins/index.ts:1-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/index.ts#L1-L16) > [!WARNING] > Setting individual remark or rehype option flags explicitly to `false` (such as `remarkImageOptions: false` or `rehypeCodeOptions: false`) completely disables the corresponding plugin from being appended to the unified pipeline array. Sources: [packages/mdx/src/config/preset.ts:78-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L78-L88), [packages/mdx/src/config/preset.ts:116-123](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/preset.ts#L116-L123) ## Meta and Configuration Loaders ### Metadata File Loader Parsing and Transformation Metadata loaders intercept JSON and YAML source files matching collection patterns, applying Zod schema validation over query parameters to extract `collection` and `workspace` identifiers. The `parse` function handles file extensions by invoking `JSON.parse` for JSON files and `js-yaml`'s `load` for YAML files, wrapping failures with detailed error context. ```typescript function parse(filePath: string, source: string) { try { if (filePath.endsWith('.json')) return JSON.parse(source); if (filePath.endsWith('.yaml')) return load(source); } catch (e) { throw new Error(`invalid data in ${filePath}`, { cause: e }); } throw new Error('Unknown file type ' + filePath); } ``` Sources: [packages/mdx/src/loaders/meta.ts:25-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts#L25-L34) > [!NOTE] > When the `collection` query parameter is omitted or fails validation, the metadata loader falls back to bundler built-in plugins by returning `null`, allowing default file resolution to take over. Sources: [packages/mdx/src/loaders/meta.ts:37-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts#L37-L38) ### Adapter Transformation and Output Generation The loader produces output modules based on the resolved file type and configuration options. For JSON files, the `moduleType` can be configured as either `'json'` or `'js'`, whereas YAML files always transpile to JavaScript default exports. | Resolve Option Key | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `json` | `'json' \| 'js'` | `'js'` | Specifies module output format for JSON meta files. | | `yaml` | `'js'` | `'js'` | Specifies module output format for YAML meta files. | Sources: [packages/mdx/src/loaders/meta.ts:18-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts#L18-L23) ```typescript if (input.filePath.endsWith('.json')) { return { moduleType: resolveJson, code: resolveJson === 'json' ? JSON.stringify(data) : `export default ${JSON.stringify(data)}`, }; } else { return { moduleType: 'js', code: `export default ${JSON.stringify(data)}`, }; } ``` Sources: [packages/mdx/src/loaders/meta.ts:80-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts#L80-L93) > [!WARNING] > If a metadata collection item is defined in the source config, raw parsed data passes through `core.transformMeta` before export generation, altering the final structure returned to consumers. Sources: [packages/mdx/src/loaders/meta.ts:61-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts#L61-L69) ## Core Plugin Pipeline Lifecycle ### Initialization and Execution Call Chain The core plugin pipeline lifecycle manages core instance initialization, workspace discovery, and plugin hook execution. The process begins with `createMDX`, which invokes `createNextCore` and subsequently `createCore` to instantiate the core context and resolve plugins via `getPlugins`. 1. `createMDX` — Initializes the core instance by wrapping configuration options. Sources: [packages/mdx/src/next/index.ts:30-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L31) 2. `createNextCore` — Generates a core instance with specific environment defaults and the index plugin. Sources: [packages/mdx/src/next/index.ts:200-206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L200-L206) 3. `createCore` — Instantiates the core object, setting up internal caches, workspaces, and transformation methods. Sources: [packages/mdx/src/core.ts:148-152](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L148-L152) 4. `getPlugins` — Flattens and aggregates plugin option arrays asynchronously into a unified array of plugins. Sources: [packages/mdx/src/core.ts:136-146](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L136-L146) ```mermaid sequenceDiagram participant index.ts as packages/mdx/src/next/index.ts participant core.ts as packages/mdx/src/core.ts index.ts->>index.ts: createMDX() index.ts->>index.ts: createNextCore() index.ts->>core.ts: createCore() core.ts->>core.ts: getPlugins() ``` Sources: [packages/mdx/src/next/index.ts:30-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L31), [packages/mdx/src/next/index.ts:200-206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L200-L206), [packages/mdx/src/core.ts:136-152](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L136-L152) > [!WARNING] > During core initialization (`core.init`), caches and workspaces are cleared, and config plugins are executed sequentially, allowing each plugin to mutate the loaded configuration before workspace resolution occurs. Sources: [packages/mdx/src/core.ts:176-185](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L176-L185) ### Plugin Hook Dispatch and Transformation Methods The core instance exposes explicit methods to invoke lifecycle hooks across registered plugins. When emitting files or transforming content, `emit`, `transformMeta`, `transformFrontmatter`, and `transformVFile` iterate through the plugins sequentially. ```typescript async emit(emitOptions: EmitOptions = {}): Promise { const { filterPlugin, filterWorkspace, write = false } = emitOptions; const start = performance.now(); const ctx = this.getPluginContext(); const added = new Set(); const out: EmitOutput = { entries: [], workspaces: {}, }; for (const li of await Promise.all( plugins.map((plugin) => { if ((filterPlugin && !filterPlugin(plugin)) || !plugin.emit) return; return plugin.emit.call(ctx); }), )) { if (!li) continue; for (const item of li) { if (added.has(item.path)) continue; out.entries.push(item); added.add(item.path); } } ``` Sources: [packages/mdx/src/core.ts:244-266](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L244-L266) | Hook Method | Context Passed | Iteration Behavior | Purpose | | :--- | :--- | :--- | :--- | | `config` | PluginContext | Sequential override | Modifies or replaces loaded configuration. | | `emit` | PluginContext | Parallel execution via `Promise.all` | Generates virtual or persistent output entries. | | `configureServer` | ServerContext | Sequential execution | Sets up development server watchers or middleware. | | `meta.transform` | TransformOptions & PluginContext | Sequential pipe | Transforms metadata collection items after validation. | | `doc.frontmatter` | TransformOptions & PluginContext | Sequential pipe | Transforms document frontmatter after schema validation. | | `doc.vfile` | TransformOptions & PluginContext | Sequential pipe | Modifies the virtual file container for documents. | Sources: [packages/mdx/src/core.ts:182-185](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L182-L185), [packages/mdx/src/core.ts:237-239](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L237-L239), [packages/mdx/src/core.ts:254-258](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L254-L258), [packages/mdx/src/core.ts:302-304](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L302-L304), [packages/mdx/src/core.ts:318-320](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L318-L320), [packages/mdx/src/core.ts:333-335](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L333-L335) > [!CAUTION] > Workspace instantiation supports a maximum depth of 1; child workspaces recursively invoke `createCore` with prefixed output directories, and failing to respect this depth limitation results in unhandled configuration loops. Sources: [packages/mdx/src/core.ts:187-203](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L187-L203) ## Related - [Bundler Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/bundler-plugins) - [Content Compiler Plugins](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/content-compiler-plugins) --- ## Technical docs: Bundler Plugins URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/bundler-plugins
Relevant source files The following files were used as context for generating this wiki page: - [packages/mdx/src/loaders/adapter.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/adapter.ts) - [packages/mdx/src/rolldown/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts) - [packages/mdx/src/bun/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts) - [packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/mdx/src/loaders/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts) - [packages/mdx/src/next/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) - [packages/mdx/src/webpack/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts) - [packages/doc-gen/src/remark-docgen.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-docgen.ts) - [packages/mdx/src/node/_loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts) - [packages/mdx/src/loaders/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts) - [packages/mdx/src/webpack/mdx.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/mdx.ts) - [packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts) - [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts) - [packages/mdx/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/tsdown.config.ts) - [packages/mdx/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/package.json) - [packages/core/src/mdx-plugins/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/index.ts) - [packages/story/src/webpack/story.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/webpack/story.ts) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/core/src/content/mdx/preset-bundler.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts) - [packages/mdx/src/node/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/loader.ts) - [packages/story/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/vite/index.ts) - [packages/doc-gen/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/tsdown.config.ts) - [packages/mdx/src/bin.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bin.ts) - [packages/api-docs/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/tsdown.config.ts) - [packages/mdx/src/core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts) - [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts) - [packages/core/src/mdx-plugins/remark-llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts) - [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts) - [packages/asyncapi/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/tsdown.config.ts)
## Overview Fumadocs provides a set of bundler plugins and low-level adapters that integrate content compilation pipelines into modern build tools and JavaScript runtimes [packages/mdx/src/loaders/adapter.ts:1-223](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/adapter.ts), [packages/mdx/src/core.ts:1-340](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts). These integrations handle document parsing, frontmatter validation, configuration reloading, and virtual entry point generation across Next.js, Vite, Rolldown, Webpack, Node.js, and Bun [packages/mdx/src/next/index.ts:1-207](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts), [packages/mdx/src/vite/index.ts:1-160](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts), [packages/mdx/src/rolldown/index.ts:1-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts), [packages/mdx/src/bun/index.ts:1-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts). By abstracting environment-specific module loading and transformation hooks behind a unified core, the packages maintain consistent document behavior during development and production builds [packages/mdx/src/loaders/adapter.ts:35-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/adapter.ts), [packages/mdx/src/core.ts:148-340](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts). Sources: [packages/mdx/src/loaders/adapter.ts:1-223](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/adapter.ts), [packages/mdx/src/rolldown/index.ts:1-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts), [packages/mdx/src/bun/index.ts:1-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts), [packages/mdx/src/vite/index.ts:1-160](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts), [packages/mdx/src/next/index.ts:1-207](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts), [packages/mdx/src/core.ts:1-340](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts) ## Next.js Integration and Core Lifecycle ### Initialization and Execution Flow The Next.js integration initializes through `createMDX`, which sets up core compilation options and checks the `_FUMADOCS_MDX` environment variable to prevent duplicate initialization passes. When invoked, `createMDX` executes `createNextCore` using options normalized by `applyDefaults`. The call-chain sequence `createMDX` → `init` → `devServer` → `initOrReload` proceeds by instantiating the core via `createMDX`, handing control to `init` to evaluate development flags, invoking `devServer` when `isDev` is true to watch configuration files and collections, and finally triggering `initOrReload` to load the configuration and emit compiled outputs. ```mermaid sequenceDiagram participant Index as packages/mdx/src/next/index.ts Index->>Index: createMDX() Index->>Index: init() Index->>Index: devServer() Index->>Index: initOrReload() ``` Sources: [packages/mdx/src/next/index.ts:30-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) 1. `createMDX`: Accepts `CreateMDXOptions`, establishes default environment variables, and delegates core creation. Sources: [packages/mdx/src/next/index.ts:30-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) 2. `init`: Manages asynchronous bootstrap and checks the `dev` boolean flag to determine whether to spin up file system watchers. Sources: [packages/mdx/src/next/index.ts:124-182](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) 3. `devServer`: Instantiates a `chokidar` `FSWatcher` instance ignoring the output directory, tracks configuration files and collection directories, and handles hot-reloading on configuration changes. Sources: [packages/mdx/src/next/index.ts:132-176](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) 4. `initOrReload`: Loads configuration files via `loadConfig(core, true)` and invokes `core.emit({ write: true })`. Sources: [packages/mdx/src/next/index.ts:125-130](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) > [!WARNING] > If `process.env._FUMADOCS_MDX` is already set to `'1'`, subsequent calls to `init` are bypassed during module evaluation to prevent concurrent watcher duplication across Next.js worker threads. Sources: [packages/mdx/src/next/index.ts:34-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) ### Configuration Options and Default Values The integration relies on `CreateMDXOptions` to configure source paths, output targets, and index generation plugins. These options are processed by `applyDefaults` to guarantee defined parameters. | Option Key | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `configPath` | `string` | `_Defaults.configPath` | Path to source configuration file. | | `outDir` | `string` | `_Defaults.outDir` | Directory for output files. | | `index` | `IndexFilePluginOptions \| false` | `{}` | Index file plugin options or `false` to disable. | Sources: [packages/mdx/src/next/index.ts:12-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts), [packages/mdx/src/next/index.ts:192-198](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) > [!NOTE] > `createNextCore` constructs the underlying core instance with environment set to `'next'` and registers the index plugin if enabled. Sources: [packages/mdx/src/next/index.ts:200-207](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) ## MDX Compiler Preset Configuration ### Preset Options and Remark/Rehype Registration The `mdxPreset` function asynchronous builder resolves and registers remark and rehype plugins into standard MDX processor options. It takes `MDXBundlerPresetOptions` which omits standard remark and rehype options in favor of resolver structures and specific plugin toggles. ```typescript export type MDXBundlerPresetOptions = Omit< NonNullable, 'rehypePlugins' | 'remarkPlugins' > & { rehypePlugins?: ResolvePlugins; remarkPlugins?: ResolvePlugins; /** @private for `remark-include` */ _include?: Pluggable; remarkStructureOptions?: Plugins.StructureOptions | false; remarkHeadingOptions?: Plugins.RemarkHeadingOptions | false; remarkImageOptions?: Plugins.RemarkImageOptions | false; remarkCodeTabOptions?: Plugins.RemarkCodeTabOptions | false; remarkNpmOptions?: Plugins.RemarkNpmOptions | false; rehypeCodeOptions?: Plugins.RehypeCodeOptions | false; }; ``` Sources: [packages/core/src/content/mdx/preset-bundler.ts:6-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L6-L21) ```typescript export async function mdxPreset(options: MDXBundlerPresetOptions = {}): Promise { const { rehypeCodeOptions, remarkImageOptions, remarkHeadingOptions, remarkStructureOptions, remarkCodeTabOptions, remarkNpmOptions, _include, ...mdxOptions } = options; ``` Sources: [packages/core/src/content/mdx/preset-bundler.ts:26-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L26-L36) > [!NOTE] > Each remark and rehype plugin can be explicitly disabled by passing `false` to its corresponding option key, or customized by passing an object containing plugin-specific parameters. Sources: [packages/core/src/content/mdx/preset-bundler.ts:15-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L15-L20) ### Plugin Integration Pipeline The preset registration pipeline resolves plugins asynchronously through `resolvePlugins`, combining standard defaults with custom user configurations. The pipeline processes remark plugins starting with GitHub Flavored Markdown and conditional expansions. ```typescript const remarkPlugins = await resolvePlugins( (v) => [ import('remark-gfm').then((mod) => mod.default), remarkHeadingOptions !== false && import('@/mdx-plugins/remark-heading').then((mod) => [ mod.remarkHeading, { generateToc: false, ...remarkHeadingOptions, }, ]), _include ?? false, remarkImageOptions !== false && import('@/mdx-plugins/remark-image').then((mod) => [ mod.remarkImage, { ...remarkImageOptions, useImport: remarkImageOptions?.useImport ?? true, }, ]), remarkCodeTabOptions !== false && import('@/mdx-plugins/remark-code-tab').then((mod) => [ mod.remarkCodeTab, remarkCodeTabOptions, ]), remarkNpmOptions !== false && import('@/mdx-plugins/remark-npm').then((mod) => [mod.remarkNpm, remarkNpmOptions]), ...v, remarkStructureOptions !== false && import('@/mdx-plugins/remark-structure').then((mod) => [ mod.remarkStructure, { exportAs: 'structuredData', ...remarkStructureOptions, } satisfies Plugins.StructureOptions, ]), ], mdxOptions.remarkPlugins, ); ``` Sources: [packages/core/src/content/mdx/preset-bundler.ts:38-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L38-L76) ```typescript const rehypePlugins = await resolvePlugins( (v) => [ rehypeCodeOptions !== false && import('@/mdx-plugins/rehype-code').then((mod) => [mod.rehypeCode, rehypeCodeOptions]), ...v, import('@/mdx-plugins/rehype-toc').then((mod) => mod.rehypeToc), ], mdxOptions.rehypePlugins, ); ``` Sources: [packages/core/src/content/mdx/preset-bundler.ts:78-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L78-L86) > [!WARNING] > Disabling `remarkHeadingOptions`, `remarkImageOptions`, `remarkCodeTabOptions`, `remarkNpmOptions`, `remarkStructureOptions`, or `rehypeCodeOptions` by setting them to `false` prevents their dynamic imports from executing during the preset build. Sources: [packages/core/src/content/mdx/preset-bundler.ts:41-73](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L41-L73), [packages/core/src/content/mdx/preset-bundler.ts:80-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L80-L81) ### Preset Configuration Options Reference | Option Key | Type | Default Behavior / Mapping | Description | | :--- | :--- | :--- | :--- | | `remarkPlugins` | `ResolvePlugins` | Combined via `resolvePlugins` | Custom remark plugins appended to the preset. | | `rehypePlugins` | `ResolvePlugins` | Combined via `resolvePlugins` | Custom rehype plugins appended to the preset. | | `_include` | `Pluggable` | `undefined` | Private plugin hook for `remark-include`. | | `remarkStructureOptions` | `Plugins.StructureOptions \| false` | `{ exportAs: 'structuredData' }` | Options for the structure extraction remark plugin. | | `remarkHeadingOptions` | `Plugins.RemarkHeadingOptions \| false` | `{ generateToc: false }` | Options for heading extraction and [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) generation. | | `remarkImageOptions` | `Plugins.RemarkImageOptions \| false` | `{ useImport: true }` | Options for remark image optimization and imports. | | `remarkCodeTabOptions` | `Plugins.RemarkCodeTabOptions \| false` | `undefined` | Options for code tab grouping transformations. | | `remarkNpmOptions` | `Plugins.RemarkNpmOptions \| false` | `undefined` | Options for package manager command translation. | | `rehypeCodeOptions` | `Plugins.RehypeCodeOptions \| false` | `undefined` | Options for [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting) and code block processing. | Sources: [packages/core/src/content/mdx/preset-bundler.ts:6-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L6-L21), [packages/core/src/content/mdx/preset-bundler.ts:41-73](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-bundler.ts#L41-L73) ## Index File Codegen Coordination ### Execution Pipeline and Sequence Architecture The coordination of index file generation begins at the core layer where configuration options are evaluated. The explicit call chain starts with `createMDX`, which delegates through `createNextCore`, initializes the `indexFile` plugin, and executes `generateConfigs` to assemble server options and type definitions. ```typescript export function createMDX(createOptions: CreateMDXOptions = {}) { const core = createNextCore(applyDefaults(createOptions)); ``` Sources: [packages/mdx/src/next/index.ts:30-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L31) ```typescript function createNextCore(options: Required): Core { return createCore({ environment: 'next', outDir: options.outDir, configPath: options.configPath, plugins: [options.index && indexFile(options.index)], }); ``` Sources: [packages/mdx/src/next/index.ts:200-206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L200-L206) ```typescript export default function indexFile(options: IndexFilePluginOptions = {}): Plugin { const { target = 'default', addJsExtension, browser = true, dynamic = true } = options; let dynamicCollections: CollectionItem[]; function isDynamic(collection: CollectionItem) { return ( (collection.type === 'docs' && collection.docs.dynamic) || (collection.type === 'doc' && collection.dynamic) ); } function generateConfigs(core: Core): { serverOptions: ServerOptions; tc: string; } { const serverOptions: ServerOptions = {}; const typeConfigs: string[] = ['import("fumadocs-mdx/runtime/types").InternalTypeConfig']; const ctx = core.getPluginContext(); for (const plugin of core.getPlugins()) { const indexFilePlugin = plugin['index-file']; if (!indexFilePlugin) continue; indexFilePlugin.serverOptions?.call(ctx, serverOptions); const config = indexFilePlugin.generateTypeConfig?.call(ctx); if (config) typeConfigs.push(config); } return { serverOptions, tc: typeConfigs.join(' & '), }; } ``` Sources: [packages/mdx/src/plugins/index-file.ts:51-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L51-L83) ```mermaid sequenceDiagram participant IndexNext as packages/mdx/src/next/index.ts participant IndexPlugin as packages/mdx/src/plugins/index-file.ts IndexNext->>IndexNext: createMDX() IndexNext->>IndexNext: createNextCore() IndexNext->>IndexPlugin: indexFile() IndexPlugin->>IndexPlugin: generateConfigs() ``` Sources: [packages/mdx/src/next/index.ts:30-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L30-L31), [packages/mdx/src/next/index.ts:200-206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts#L200-L206), [packages/mdx/src/plugins/index-file.ts:51-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L51-L83) > [!NOTE] > The function `generateConfigs` iterates over registered core plugins to extract custom `serverOptions` and append any module type configurations (`generateTypeConfig`) into a combined intersection type string. Sources: [packages/mdx/src/plugins/index-file.ts:62-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L62-L83) ### Plugin Options and Configuration Reference The plugin behavior is governed by `IndexFilePluginOptions`, which controls compilation targets, extension resolution, and output file entry generation. ```typescript export interface IndexFilePluginOptions { target?: 'default' | 'vite'; /** * add `.js` extensions to imports, needed for ESM without bundler resolution */ addJsExtension?: boolean; /** * Generate entry point for browser * @defaultValue true */ browser?: boolean; /** * Generate entry point for dynamic compilation * @defaultValue true */ dynamic?: boolean; } ``` Sources: [packages/mdx/src/plugins/index-file.ts:13-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L13-L32) | Option Key | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `target` | `'default' \| 'vite'` | `'default'` | Target bundler environment for codegen paths and glob resolution. | | `addJsExtension` | `boolean` | `undefined` | Appends `.js` extensions to imports for ESM without bundler resolution. | | `browser` | `boolean` | `true` | Generates a browser entry point module (`browser.ts`). | | `dynamic` | `boolean` | `true` | Generates an entry point for dynamic content compilation (`dynamic.ts`). | Sources: [packages/mdx/src/plugins/index-file.ts:13-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L13-L32) ## Webpack Loader Interception ### Standalone MDX and Meta Loaders The package exposes standalone Webpack loaders for processing MDX documents and collection metadata files outside of the Next.js plugin wrapper. Both loaders utilize a lazy-initialized singleton instance via `toWebpack` to bind core loader logic, while declaring dependencies on compiled configuration paths via Webpack's `this.addDependency()`. ```typescript const loader: LoaderDefinitionFunction = function loader(source) { const callback = this.async(); const options = this.getOptions(); this.cacheable(true); this.addDependency(options.absoluteCompiledConfigPath); if (!instance) { instance = toWebpack( createMdxLoader( createStandaloneConfigLoader({ core: getCore(options), buildConfig: false, mode: options.isDev ? 'dev' : 'production', }), ), ); } void instance.call(this, source, callback); }; ``` Sources: [packages/mdx/src/webpack/mdx.ts:9-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/mdx.ts#L9-L28) ```typescript const loader: LoaderDefinitionFunction = function (source) { const callback = this.async(); const options = this.getOptions(); this.cacheable(true); this.addDependency(options.absoluteCompiledConfigPath); if (!instance) { instance = toWebpack( createMetaLoader( createStandaloneConfigLoader({ core: getCore(options), buildConfig: false, mode: options.isDev ? 'dev' : 'production', }), { json: 'json', yaml: 'js', }, ), ); } void instance.call(this, source, callback); }; ``` Sources: [packages/mdx/src/webpack/meta.ts:9-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts#L9-L32) > [!NOTE] > The meta loader configures `createMetaLoader` with mapping values `{ json: 'json', yaml: 'js' }`, passing an options object to `createStandaloneConfigLoader` where `buildConfig` is disabled and `mode` is derived from `options.isDev`. Sources: [packages/mdx/src/webpack/meta.ts:17-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts#L17-L27) ### Story File Transformation Loader The story loader handles component documentation files by leveraging `ts-morph` projects and file transformation utilities. It accepts options via `StoryLoaderOptions` and manages asynchronous execution pools through `projectPromise`. ```typescript export interface StoryLoaderOptions { /** * Path to `tsconfig.json`. * * @default "tsconfig.json" */ tsconfigPath?: string; } let projectPromise: Promise | undefined; const loader: LoaderDefinitionFunction = function (source) { const callback = this.async(); const options = this.getOptions(); this.cacheable(true); const run = async () => { if (!projectPromise) { const resolvedTsconfig = options.tsconfigPath ?? path.join(this.rootContext, 'tsconfig.json'); projectPromise = createControlsProject(resolvedTsconfig); } try { const transformed = transformStoryFile( '@fumadocs/story/next/client', source, this.resourcePath, await projectPromise!, ); callback(undefined, transformed ?? source); } catch (error) { if (!(error instanceof Error)) throw error; callback(error); } }; void run(); }; ``` Sources: [packages/story/src/webpack/story.ts:7-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/webpack/story.ts#L7-L44) | Option Key | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `tsconfigPath` | `string` | `"tsconfig.json"` | Path to the `tsconfig.json` configuration file used for `ts-morph` project initialization. | Sources: [packages/story/src/webpack/story.ts:7-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/webpack/story.ts#L7-L14), [packages/story/src/webpack/story.ts:25-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/webpack/story.ts#L25-L25) > [!WARNING] > If `projectPromise` has not been initialized when a story file is processed, the loader resolves `tsconfigPath` relative to `this.rootContext` before creating the controls project. Sources: [packages/story/src/webpack/story.ts:23-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/webpack/story.ts#L23-L27) ## Vite and Rolldown Adapters ### Vite Plugin Architecture and Server Lifecycle The Vite plugin wrapper orchestrates core compilation lifecycle hooks, configuration building, and development server file watching. It exposes `PluginOptions` to control index generation, configuration paths, module resolution updates, and output directories. ```typescript export interface PluginOptions { /** * Generate index files for accessing content. * * @defaultValue true */ index?: boolean | IndexFilePluginOptions; /** * @defaultValue source.config.ts */ configPath?: string; /** * Update Vite config to fix module resolution of Fumadocs * * @defaultValue true */ updateViteConfig?: boolean; /** * Output directory of generated files * * @defaultValue '.source' */ outDir?: string; } ``` Sources: [packages/mdx/src/vite/index.ts:12-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L12-L38) | Option Key | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `index` | `boolean \| IndexFilePluginOptions` | `true` | Generates index files for accessing content or configures index file options. | | `configPath` | `string` | `'source.config.ts'` | Path to the content source configuration file. | | `updateViteConfig` | `boolean` | `true` | Updates Vite config to fix module resolution of Fumadocs. | | `outDir` | `string` | `'.source'` | Output directory of generated files. | Sources: [packages/mdx/src/vite/index.ts:12-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L12-L38) During the `config` hook, the plugin initializes core functionality via `createViteCore` and runs `core.init()`. It registers `pre`-ordered transform hooks for MDX and meta loaders while establishing file watchers on the configuration path. > [!CAUTION] > When Vite RSC processes client references, it passes compiled MDX client modules with IDs matching `virtual:vite-rsc`. The plugin explicitly intercepts and ignores these IDs to prevent JavaScript content formatting from breaking the MDX compiler. Sources: [packages/mdx/src/vite/index.ts:83-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L83-L86) ```typescript return [ { name: 'fumadocs-mdx', async config(config) { root = config.root ?? process.cwd(); options = applyDefaults(root, pluginOptions); core = createViteCore(options); await core.init({ config: buildConfig( forcedConfig ? await forcedConfig : (await runnerImport>(options.configPath)).module, root, ), }); const configLoader = createIntegratedConfigLoader(core); const mdxLoader = toVite(createMdxLoader(configLoader)); const metaLoader = toVite( createMetaLoader(configLoader, { // vite has built-in plugin for JSON files json: 'json', }), ); mdxPlugin.transform = { filter: mdxLoader.filter, order: 'pre', handler(code, id) { // Vite RSC will pass the compiled MDX file's client module with ID `virtual:vite-rsc/client-references/group/facade:xxx.mdx`. // The format of `value` becomes JavaScript, which will break the MDX compiler. // We have to ignore them. if (id.includes('virtual:vite-rsc')) return null; if (!forcedConfig) this.addWatchFile(options.configPath); return mdxLoader.transform.call(this, code, id); }, }; metaPlugin.transform = { filter: metaLoader.filter, order: 'pre', handler(code, id) { if (!forcedConfig) this.addWatchFile(options.configPath); return metaLoader.transform.call(this, code, id); }, }; if ('_fumadocs_skipViteConfig' in config && config._fumadocs_skipViteConfig) return; if (!options.updateViteConfig) return; const { getConfig } = await import('@fumadocs/vite'); return getConfig({ root }); }, ``` Sources: [packages/mdx/src/vite/index.ts:54-105](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L54-L105) ### Rolldown Plugin Configuration and File Loading The Rolldown plugin wrapper configures core compilation with a `rolldown` environment parameter. It constructs integrated configuration and loaders, returning a set of Rolldown plugins that handle raw file loading and transformation. ```typescript export interface PluginOptions { configPath?: string; outDir?: string; } export default async function mdx( config: Record | Promise>, options?: PluginOptions, ): Promise { const core = createCore({ configPath: options?.configPath ?? _Defaults.configPath, outDir: options?.outDir ?? _Defaults.outDir, environment: 'rolldown', }); await core.init({ config: buildConfig(await config, process.cwd()), }); const configLoader = createIntegratedConfigLoader(core); const mdxLoader = toVite(createMdxLoader(configLoader)); const metaLoader = toVite( createMetaLoader(configLoader, { // rolldown has built-in plugin for JSON files json: 'json', }), ); ``` Sources: [packages/mdx/src/rolldown/index.ts:11-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts#L11-L37) | Option Key | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `configPath` | `string` | `_Defaults.configPath` | Path to the content source configuration file. | | `outDir` | `string` | `_Defaults.outDir` | Output directory of generated files. | Sources: [packages/mdx/src/rolldown/index.ts:11-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts#L11-L14), [packages/mdx/src/rolldown/index.ts:21-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts#L21-L22) > [!NOTE] > Because Rolldown cannot read the correct file path when query parameters exist on module IDs, a dedicated load handler strips query strings using `id.lastIndexOf('?')` before reading the file contents from disk via `fs.readFile`. Sources: [packages/mdx/src/rolldown/index.ts:41-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts#L41-L50) ```typescript return [ { name: 'fumadocs-mdx', load: { filter: { id: [metaLoaderGlob, mdxLoaderGlob] }, // Rolldown couldn't read the correct file path when query params exist. async handler(id) { const idx = id.lastIndexOf('?'); if (idx === -1) return null; return fs.readFile(id.slice(0, idx), 'utf-8'); }, }, }, { name: 'fumadocs-mdx:mdx', transform: { filter: mdxLoader.filter, handler: mdxLoader.transform, }, }, { name: 'fumadocs-mdx:meta', transform: { filter: metaLoader.filter, handler: metaLoader.transform, }, }, ]; ``` Sources: [packages/mdx/src/rolldown/index.ts:38-66](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/rolldown/index.ts#L38-L66) ### Story File Transformation Plugin The story plugin provides a Vite-compatible transformation pipeline for component stories, leveraging `ts-morph` projects and filtering file IDs against regular expressions. ```typescript export interface StoryPluginOptions { /** * Path to `tsconfig.json`. * * @default "tsconfig.json" */ tsconfigPath?: string; /** * Filter story files to transform by id (regex) * * @default `/\.story\.(js|jsx|ts|tsx)$/` */ filter?: RegExp; } ``` Sources: [packages/story/src/vite/index.ts:7-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/vite/index.ts#L7-L21) | Option Key | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `tsconfigPath` | `string` | `"tsconfig.json"` | Path to the `tsconfig.json` configuration file. | | `filter` | `RegExp` | `/\.story\.(js\|jsx\|ts\|tsx)$/` | Filter story files to transform by ID regex. | Sources: [packages/story/src/vite/index.ts:7-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/vite/index.ts#L7-L21) ```typescript export default function story(pluginOptions: StoryPluginOptions = {}): Plugin { const { filter = /\.story\.(js|jsx|ts|tsx)$/ } = pluginOptions; let tsconfigPath: string; let projectPromise: Promise | undefined; return { name: 'fumadocs:story', enforce: 'pre', configResolved(resolved) { tsconfigPath = pluginOptions.tsconfigPath ?? path.join(resolved.root, 'tsconfig.json'); }, transform: { filter: { id: filter }, async handler(code, id) { projectPromise ??= createControlsProject(tsconfigPath); return transformStoryFile('@fumadocs/story/vite/client', code, id, await projectPromise); }, }, }; ``` Sources: [packages/story/src/vite/index.ts:23-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/vite/index.ts#L23-L42) ## Node and Bun Runtime Loaders ### Bun Plugin Module Interception The Bun plugin integration configures core settings and exposes module loading hooks tailored for the Bun runtime environment. It implements the `BunPlugin` interface through `createMdxPlugin`, accepting options that extend partial core configurations alongside custom plugin toggles. | Option Key | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `environment` | `string` | `'bun'` | Runtime execution environment identifier. | | `outDir` | `string` | `_Defaults.outDir` | Output directory path for generated files. | | `configPath` | `string` | `_Defaults.configPath` | Path to the content source configuration file. | | `disableMetaFile` | `boolean` | `false` | Disables the automatic meta file transformation step. | Sources: [packages/mdx/src/bun/index.ts:10-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts#L10-L23) During the `setup` lifecycle hook, the plugin initializes core functionality by transforming the configuration path into a file URL and invoking `core.init()`. It establishes integrated configuration loading and assigns MDX and meta loaders using the Bun adapter utility. ```typescript return { name: 'bun-plugin-fumadocs-mdx', async setup(build) { const importPath = pathToFileURL(configPath).href; const core = createCore({ environment, outDir, configPath, }); await core.init({ config: buildConfig(await import(importPath), process.cwd()), }); const configLoader = createIntegratedConfigLoader(core); toBun(createMdxLoader(configLoader))(build); if (!disableMetaFile) toBun(createMetaLoader(configLoader))(build); }, }; } ``` Sources: [packages/mdx/src/bun/index.ts:25-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts#L25-L44) > [!NOTE] > The meta loader step can be entirely bypassed by passing `disableMetaFile: true` in the plugin options, preventing unnecessary processing of metadata files when only core MDX compilation is required. Sources: [packages/mdx/src/bun/index.ts:14-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts#L14-L22), [packages/mdx/src/bun/index.ts:41-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/bun/index.ts#L41-L41) ### Native Node.js Module Loaders Native Node.js environments utilize custom module loading hooks conforming to Node's module customization hooks specification. The modern initialization implementation defines an `initialize` hook that sets up standalone configuration loaders for production mode. | Option Key | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `environment` | `string` | `'node-loader'` | Execution environment assigned during core creation. | | `configPath` | `string` | `_Defaults.configPath` | Path to the content source configuration file. | | `outDir` | `string` | `_Defaults.outDir` | Output directory path for generated content. | | `disableMetaFile` | `boolean` | `undefined` | Conditionally skips pushing the meta loader into the loader cache. | Sources: [packages/mdx/src/node/_loader.ts:11-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L11-L29) ```typescript export const initialize: InitializeHook = (options) => { const core = createCore({ environment: 'node-loader', ...options, configPath: options.configPath ?? _Defaults.configPath, outDir: options.outDir ?? _Defaults.outDir, }); const configLoader = createStandaloneConfigLoader({ core, buildConfig: true, mode: 'production', }); cachedLoaders = [toNode(createMdxLoader(configLoader))]; if (!options.disableMetaFile) { cachedLoaders.push(toNode(createMetaLoader(configLoader))); } }; ``` Sources: [packages/mdx/src/node/_loader.ts:11-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L11-L30) The accompanying `load` hook iterates sequentially through cached Node module loaders using a recursive runner function, falling back to the standard `nextLoad` function when all custom hooks have executed. ```typescript export const load: LoadHook = async (url, context, nextLoad) => { if (!cachedLoaders) throw new Error('not initialized'); const hooks = cachedLoaders; function run( i: number, url: string, context: LoadHookContext, ): LoadFnOutput | Promise { if (i >= hooks.length) { return nextLoad(url, context); } return hooks[i](url, context, (url, ctx) => run(i + 1, url, { ...context, ...ctx })); } return run(0, url, context); }; ``` Sources: [packages/mdx/src/node/_loader.ts:31-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L31-L48) > [!WARNING] > Attempting to invoke the `load` hook before the module loader has been properly initialized via `initialize` triggers an immediate runtime error stating `not initialized`. Sources: [packages/mdx/src/node/_loader.ts:31-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/node/_loader.ts#L31-L32) ## Related - [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline) --- ## Technical docs: Content Compiler Plugins URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/content-compiler-plugins
Relevant source files The following files were used as context for generating this wiki page: - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/mdx/src/plugins/last-modified.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts) - [packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts) - [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts) - [packages/mdx/src/plugins/json-schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts) - [packages/mdx/src/core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts) - [packages/preview/src/lib/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/md.ts) - [packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts) - [packages/doc-gen/src/remark-docgen.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-docgen.ts) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts) - [packages/local-md/src/md/compiler.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts) - [packages/asyncapi/src/generate-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/generate-file.ts) - [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts) - [packages/mdx/src/webpack/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/meta.ts) - [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts) - [packages/core/src/source/storage/content.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts) - [packages/openapi/src/utils/pages/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/builder.ts) - [packages/python/src/convert.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/convert.ts) - [packages/openapi/src/generate-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts) - [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts) - [packages/obsidian/src/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts) - [packages/shadcn/src/manual-installation.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts) - [packages/core/src/mdx-plugins/remark-structure.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts) - [packages/shared/compile-package-translations.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/compile-package-translations.ts) - [packages/mdx-remote/src/compile.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts) - [packages/story/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/vite/index.ts) - [packages/core/src/source/plugins/slugs.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/plugins/slugs.ts) - [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts) - [packages/content-collections/src/resolve-plugins.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/resolve-plugins.ts)
## Overview Fumadocs compiler plugins extend the core build pipeline[packages/mdx/src/core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L176-L185) to transform documentation source collections, inject metadata, and emit virtual assets for bundlers. By intercepting lifecycle hooks across unified processors and bundler configurations, these plugins coordinate everything from static index generation and frontmatter validation to version control timestamp extraction and schema serialization. Sources: [packages/mdx/src/core.ts:176-185](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts#L176-L185) ## Compiler Plugin Architecture ### Plugin Interfaces and Execution Lifecycle Hooks Fumadocs MDX compiler plugins implement structured contracts defined across core plugin modules[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L34-L39), [packages/mdx/src/plugins/last-modified.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L40-L93). The `IndexFilePlugin` interface allows plugins like last-modified to inject custom type configurations and server options directly into the compilation context[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L34-L39), [packages/mdx/src/plugins/last-modified.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L46-L65). Plugins hook into document parsing via `vfile` handlers, intercept collection config initialization, and configure watcher behaviors on development servers. Sources: [packages/mdx/src/plugins/index-file.ts:34-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L34-L39), [packages/mdx/src/plugins/last-modified.ts:40-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L40-L93) | Plugin Hook | Target Context / Argument | Purpose in Compiler Pipeline | | :--- | :--- | :--- | | `config` | `PluginContext` | Initializes collection filters, dynamic collection lists, and version control functions. | | `configureServer` | Vite Dev Server | Sets up file watchers, invalidates filesystem caches, and triggers targeted re-emits on file additions or deletions[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L90-L120), [packages/mdx/src/plugins/json-schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L27-L67). | | `emit` | `PluginContext` | Asynchronously generates virtual file entries, schema files, or index outputs for bundler resolution[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155), [packages/mdx/src/plugins/json-schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L68-L98). | | `generateTypeConfig` | `PluginContext` | Returns TypeScript type definition strings for internal type config merging. | | `serverOptions` | `ServerOptions` | Mutates runtime server configurations, such as registering passthrough properties like `lastModified`[packages/mdx/src/plugins/last-modified.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L60-L65). | | `doc.vfile` | Unified `VFile` | Inspects and transforms document virtual files during compilation, injecting metadata or frontmatter exports[packages/mdx/src/plugins/last-modified.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L78-L91). | Sources: [packages/mdx/src/plugins/index-file.ts:34-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L34-L39), [packages/mdx/src/plugins/json-schema.ts:27-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L27-L98), [packages/mdx/src/plugins/last-modified.ts:40-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L40-L93) > [!IMPORTANT] > During server configuration watchers, plugins inspect dynamic collections via `isDynamic` to decide whether change events trigger full re-emits or skip file generation depending on the active `target` (`default` or `vite`)[[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L55-L120). Sources: [packages/mdx/src/plugins/index-file.ts:55-120](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L55-L120) ### Emit Entry Contracts and Virtual Output Generation Plugins coordinate asset generation through the `EmitEntry` contract, returning a target file path and stringified content[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155), [packages/mdx/src/plugins/json-schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L68-L98). The `index-file` plugin builds server, dynamic, and browser entry points by evaluating collection structures and invoking code generators[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155). Simultaneously, the `jsonSchema` plugin iterates over collections to serialize Zod schemas into JSON schema representations[packages/mdx/src/plugins/json-schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L68-L98). Sources: [packages/mdx/src/plugins/index-file.ts:121-155](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155), [packages/mdx/src/plugins/json-schema.ts:68-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L68-L98)] ## Virtual Index File Code Generation ### Plugin Options and Configuration Generation The `indexFile` plugin accepts options defined by `IndexFilePluginOptions`, supporting properties such as `target` (`'default'` or `'vite'`), `addJsExtension` (appending `.js` extensions to imports for ESM without bundler resolution), `browser` (generating browser entry points, defaulting to `true`), and `dynamic` (generating dynamic compilation entry points, defaulting to `true`). ```typescript export interface IndexFilePluginOptions { target?: 'default' | 'vite'; addJsExtension?: boolean; browser?: boolean; dynamic?: boolean; } ``` Sources: [packages/mdx/src/plugins/index-file.ts:13-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L13-L32) During setup, `generateConfigs` iterates through registered core plugins, invoking optional `serverOptions` hooks and accumulating TypeScript type definitions into an intersection string (`tc`) anchored by `import("fumadocs-mdx/runtime/types").InternalTypeConfig`. ```typescript function generateConfigs(core: Core): { serverOptions: ServerOptions; tc: string; } { const serverOptions: ServerOptions = {}; const typeConfigs: string[] = ['import("fumadocs-mdx/runtime/types").InternalTypeConfig']; const ctx = core.getPluginContext(); for (const plugin of core.getPlugins()) { const indexFilePlugin = plugin['index-file']; if (!indexFilePlugin) continue; indexFilePlugin.serverOptions?.call(ctx, serverOptions); const config = indexFilePlugin.generateTypeConfig?.call(ctx); if (config) typeConfigs.push(config); } return { serverOptions, tc: typeConfigs.join(' & '), }; } ``` Sources: [packages/mdx/src/plugins/index-file.ts:62-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L62-L83) ### Call-Chain Execution Walkthrough The virtual index generation pipeline executes sequentially across modular compiler layers to emit output targets. 1. `mdx`: Initializes the Vite plugin wrapper, resolves workspace roots, and provisions the Vite core configuration[packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L40-L68). 2. `createViteCore`: Instantiates the core builder environment with `environment: 'vite'` and registers the `indexFile` plugin configured with the `'vite'` target[packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L144-L159). 3. `indexFile`: Evaluates active documentation and meta collections during its `emit` lifecycle hook, orchestrating file generation tasks[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155). 4. `toEmitEntry`: Wraps content generators by instantiating code generator instances via `createCodegen` and yielding serialized `EmitEntry` objects containing file paths and stringified outputs[packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L125-L146). Sources: [packages/mdx/src/plugins/index-file.ts:121-155](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155), [packages/mdx/src/vite/index.ts:40-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L40-L68), [packages/mdx/src/vite/index.ts:144-159](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L144-L159) ```mermaid sequenceDiagram participant mdx as mdx (vite/index.ts) participant createViteCore as createViteCore (vite/index.ts) participant indexFile as indexFile (plugins/index-file.ts) participant toEmitEntry as toEmitEntry (plugins/index-file.ts) mdx->>createViteCore: createViteCore(options) createViteCore->>indexFile: indexFile({...}) indexFile->>toEmitEntry: toEmitEntry(path, content) toEmitEntry-->>indexFile: EmitEntry { path, content } ``` Sources: [packages/mdx/src/plugins/index-file.ts:121-155](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L121-L155), [packages/mdx/src/vite/index.ts:40-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L40-L68), [packages/mdx/src/vite/index.ts:144-159](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts#L144-L159) > [!WARNING] > Dynamic collections are evaluated at runtime by checking `isDynamic`, which returns true if a collection type equals `'docs'` with `collection.docs.dynamic` set, or if type equals `'doc'` with `collection.dynamic` enabled. Changes to these collections bypass standard Vite glob caching and force full file re-emissions. Sources: [packages/mdx/src/plugins/index-file.ts:55-120](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L55-L120) ### Dynamic Compilation and Runtime Execution The runtime dynamic module manages lazy entries through `dynamic`, accepting config exports, core options, and server configurations to provision collection loaders[packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L47-L58). ```typescript export async function dynamic( configExports: Config, coreOptions: CoreOptions, serverOptions?: ServerOptions, ) { const core = createCore(coreOptions); await core.init({ config: buildConfig(configExports as Record, process.cwd()), }); const create = server(serverOptions); // ... ``` Sources: [packages/mdx/src/runtime/dynamic.ts:47-58](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L47-L58) The `convertLazyEntries` helper maps incoming lazy entries by reading file contents from `info.fullPath`, stripping frontmatter via the `frontmatter` utility, building MDX AST outputs through `buildMDX`, and hydrating compiled modules using `executeMdx` with an asynchronous function constructor[packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L67-L95). ```typescript async function compile({ info, data }: LazyEntry) { let content = await fs.readFile(info.fullPath, 'utf-8'); content = frontmatter(content).content; const compiled = await buildMDX(core, collection, { filePath: info.fullPath, source: content, frontmatter: data as Record, isDevelopment: false, environment: 'runtime', }); return (await executeMdx(String(compiled.value), { baseUrl: pathToFileURL(info.fullPath), })) as CompiledMDXProperties; } ``` Sources: [packages/mdx/src/runtime/dynamic.ts:71-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L71-L86) ## Git Last Modified Timestamps ### Plugin Configuration and Version Control Resolution The last-modified plugin injects a `lastModified` property into document page exports by resolving timestamps through version control systems or custom handler functions. The `LastModifiedPluginOptions` interface accepts a `versionControl` option, which can be explicitly set to `'git'` or provided as a custom `VersionControlFn` callback accepting a file path and returning a promise resolving to a `Date`, `null`, or `undefined`. An optional `filter` predicate limits timestamp injection to specified collections by name. ```typescript export interface LastModifiedPluginOptions { versionControl?: 'git' | VersionControlFn; filter?: (collection: string) => boolean; } ``` Sources: [packages/mdx/src/plugins/last-modified.ts:9-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L9-L27) During the plugin initialization and configuration lifecycle, the current working directory (`cwd`) is resolved from workspace configuration or the process current directory. When `versionControl` is configured as `'git'`, the internal function `fn` binds to `getGitTimestamp`, passing both the target file path and the resolved working directory. ```typescript config() { const { workspace } = this.core.getOptions(); const cwd = workspace ? path.resolve(workspace.dir) : process.cwd(); switch (versionControl) { case 'git': fn = (v) => getGitTimestamp(v, cwd); break; default: fn = versionControl; } }, ``` Sources: [packages/mdx/src/plugins/last-modified.ts:66-77](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L66-L77) > [!NOTE] > When executing git-based timestamp resolution within containerized CI or deployment environments such as Vercel, shallow clones will omit commit history. Users must configure the `VERCEL_DEEP_CLONE` environment variable to `true` to ensure full commit logs are available for extraction. Sources: [packages/mdx/src/plugins/last-modified.ts:12-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L12-L16) ### Child Process Execution and Caching To prevent redundant filesystem and process execution overhead across repeated document compilation passes, `getGitTimestamp` maintains a module-scoped cache mapping file paths to promises of `Date | null`. When a file lookup occurs, the cache is checked first before spawning a child process. ```typescript const cache = new Map>(); ``` Sources: [packages/mdx/src/plugins/last-modified.ts:6-6](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L6-L6) When a cache miss occurs, the function executes the `git` command via `tinyexec` (`x`), requesting the single latest commit (`-1`) with pretty formatting (`--ai`) for the path relative to the working directory. If the process exits with a non-zero exit code, or if the resulting date string parses to an invalid time, `null` is returned and cached accordingly. ```typescript async function getGitTimestamp(file: string, cwd: string): Promise { const cached = cache.get(file); if (cached) return cached; const timePromise = (async () => { const out = await x('git', ['log', '-1', '--pretty="%ai"', path.relative(cwd, file)], { nodeOptions: { cwd, }, }); if (out.exitCode !== 0) return null; const date = new Date(out.stdout); return isNaN(date.getTime()) ? null : date; })(); cache.set(file, timePromise); return timePromise; } ``` Sources: [packages/mdx/src/plugins/last-modified.ts:95-113](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L95-L113) During virtual file processing (`vfile`), the plugin evaluates the collection filter, retrieves the resolved timestamp for `this.filePath`, and populates `file.data['mdx-export']` with an export object defining `name: 'lastModified'` and the corresponding `value` date. Concurrently, index file generation hooks push `lastModified` into server option passthroughs and emit TypeScript type definitions extending `DocData` with an optional `lastModified?: Date` property for all matching collections. ```typescript doc: { async vfile(file) { if (!filter(this.collection.name)) return; const timestamp = await fn(this.filePath); if (timestamp) { file.data['mdx-export'] ??= []; file.data['mdx-export'].push({ name: 'lastModified', value: timestamp, }); } }, }, ``` Sources: [packages/mdx/src/plugins/last-modified.ts:78-91](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L78-L91) ## JSON Schema Generation ### Schema Definition and Path Resolution The `jsonSchema` plugin generates local JSON schema definitions for collection frontmatter and meta structures, relying exclusively on Zod for schema parsing. The plugin accepts a single options object defined by `JSONSchemaOptions`, containing the `insert` boolean flag which controls whether a `$schema` property is injected into newly created JSON files. Sources: [packages/mdx/src/plugins/json-schema.ts:7-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L7-L21) Schema paths are resolved uniformly using the internal `getSchemaPath` function, which maps a given schema identifier string into a standard relative output path under the `json-schema/` directory. Sources: [packages/mdx/src/plugins/json-schema.ts:22-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L22-L24) | Option Key | Type | Default | Purpose | | :--- | :--- | :--- | :--- | | `insert` | `boolean` | `false` | Inserts the `$schema` field pointing to the generated schema file when new JSON or meta files are created | Sources: [packages/mdx/src/plugins/json-schema.ts:7-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L7-L14) ```typescript function getSchemaPath(name: string) { return `json-schema/${name}.json`; } ``` Sources: [packages/mdx/src/plugins/json-schema.ts:22-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L22-L24) ### Server Watcher and File Injection When the development server is configured and `insert` is enabled, the plugin registers a file watcher listener for the `'add'` event. Upon detecting a newly added file, the watcher iterates through all registered collections to identify whether the file belongs to a standalone `meta` collection or the meta schema of a `docs` collection. Sources: [packages/mdx/src/plugins/json-schema.ts:27-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L27-L44) > [!WARNING] > If a newly created JSON file already contains an existing `$schema` property, the watcher aborts execution and skips file modification entirely to prevent overwriting user-defined schema references. Sources: [packages/mdx/src/plugins/json-schema.ts:55-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L55-L55) If a match is found and parsing succeeds without errors, the watcher computes a relative path from the target file's directory to the absolute JSON schema file location. It then injects the `$schema` property at the root of the parsed JSON object and writes the formatted result back to the filesystem. Sources: [packages/mdx/src/plugins/json-schema.ts:45-66](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L45-L66) ```typescript if ('$schema' in obj) return; const schemaPath = path.join( outDir, getSchemaPath(parent ? `${parent.name}.meta` : match.name), ); const updated = { $schema: path.relative(path.dirname(file), schemaPath), ...obj, }; await fs.writeFile(file, JSON.stringify(updated, null, 2)); ``` Sources: [packages/mdx/src/plugins/json-schema.ts:55-65](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L55-L65) ### Emit Hook and Schema Serialization The `emit()` lifecycle hook iterates across all core collections to harvest Zod schemas defined on documentation items and metadata files, serializing them into emitter entry objects. Sources: [packages/mdx/src/plugins/json-schema.ts:68-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L68-L98) ```typescript for (const collection of this.core.getCollections()) { if (collection.type === 'docs') { if (collection.meta.schema instanceof z.ZodType) { onSchema(`${collection.name}.meta`, collection.meta.schema); } if (collection.docs.schema instanceof z.ZodType) { onSchema(`${collection.name}.docs`, collection.docs.schema); } } else if (collection.schema instanceof z.ZodType) { onSchema(collection.name, collection.schema); } } ``` Sources: [packages/mdx/src/plugins/json-schema.ts:83-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L83-L95) The internal `onSchema` helper invokes `z.toJSONSchema` with configured options forcing input mode (`io: 'input'`) and setting unrepresentable types to `'any'`, then stores the resulting stringified JSON schemas inside the emitted file collection. Sources: [packages/mdx/src/plugins/json-schema.ts:71-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L71-L81) ```typescript function onSchema(name: string, schema: z.ZodSchema) { files.push({ path: getSchemaPath(name), content: JSON.stringify( z.toJSONSchema(schema, { io: 'input', unrepresentable: 'any', }), ), }); } ``` Sources: [packages/mdx/src/plugins/json-schema.ts:71-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/json-schema.ts#L71-L81) ## Filesystem Caching and Codegen Utilities Compiler plugins manage incremental updates and file invalidation using dedicated caching utilities and version control timestamp maps. For example, the `index-file` plugin maintains a filesystem cache instance (`indexFileCache`) to track file modifications and invalidate entries when filesystem watchers trigger change events. Sources: [packages/mdx/src/plugins/index-file.ts:6-6](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L6-L6), [packages/mdx/src/plugins/index-file.ts:49-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L49-L49), [packages/mdx/src/plugins/index-file.ts:93-94](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L93-L94) Similarly, the git last-modified plugin uses a module-level `Map` to cache asynchronous timestamp promises for each file path, preventing redundant process spawns during document compilation. Sources: [packages/mdx/src/plugins/last-modified.ts:6-6](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L6-L6), [packages/mdx/src/plugins/last-modified.ts:95-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L95-L96), [packages/mdx/src/plugins/last-modified.ts:111-112](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/last-modified.ts#L111-L112) ```typescript server.watcher.on('all', async (event, file) => { indexFileCache.delete(file); ``` Sources: [packages/mdx/src/plugins/index-file.ts:93-94](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L93-L94) Code generation and path normalization helpers abstract away target-specific output differences and import specifier formatting. The `indexFile` plugin constructs an emitter context using a configurable code generator that accepts target options, output directories, and extension preferences for ESM environments. Sources: [packages/mdx/src/plugins/index-file.ts:13-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L13-L32), [packages/mdx/src/plugins/index-file.ts:129-134](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L129-L134) > [!NOTE] > When generating server index files, the compiler formats configuration import paths using `codegen.formatImportPath` to ensure correct resolution across different bundler targets and workspace layouts. Sources: [packages/mdx/src/plugins/index-file.ts:162-163](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts#L162-L163) ## Related - [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline) --- ## Technical docs: MDX Runtime Compilation URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-runtime-compilation
Relevant source files The following files were used as context for generating this wiki page: - [packages/mdx-remote/src/render.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts) - [packages/mdx-remote/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/index.ts) - [packages/local-md/src/eval-estree-expression/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/eval-estree-expression/index.ts) - [packages/mdx-remote/src/client/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/client/index.ts) - [packages/mdx-remote/src/compile.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts) - [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts) - [packages/mdx/src/runtime/browser.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx) - [packages/core/src/content/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/md.ts) - [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts) - [packages/local-md/src/md/compiler.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts) - [packages/local-md/src/md/renderer.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/renderer.ts) - [packages/mdx/src/webpack/mdx.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/webpack/mdx.ts) - [packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts) - [packages/mdx/src/loaders/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts) - [packages/core/src/mdx-plugins/remark-llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts) - [packages/local-md/src/js/executor-native.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/js/executor-native.ts) - [packages/preview/src/lib/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/md.ts) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/radix-ui/src/mdx.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/mdx.tsx) - [packages/mdx/src/loaders/mdx/build-mdx.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/build-mdx.ts) - [packages/local-md/src/client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/client.ts) - [packages/mdx/src/next/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) - [packages/core/src/content/mdx/preset-runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/preview/src/components/markdown.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/markdown.tsx) - [packages/base-ui/src/mdx.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/mdx.tsx) - [packages/core/src/mdx-plugins/remark-mdx-files.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-files.ts) - [packages/base-ui/src/mdx.server.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/mdx.server.tsx) - [packages/core/src/mdx-plugins/remark-llms.runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.runtime.ts) - [packages/radix-ui/src/mdx.server.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/mdx.server.tsx)
## Overview MDX Runtime Compilation facilitates the parsing, frontmatter extraction, compilation, and evaluation of MDX documents on demand across server and browser runtimes. It leverages the MDX processor, Unified transformation pipelines, and custom runtime execution functions to convert raw string inputs into executable React components, structured table-of-contents data, and metadata exports. By coordinating dynamic doc collections, standard schema validation, and custom component binding, the system enables flexible documentation rendering across diverse UI frameworks and bundlers. Sources: [packages/mdx-remote/src/compile.ts:60-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts#L60-L121), [packages/mdx-remote/src/render.ts:17-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L17-L33), [packages/mdx/src/runtime/dynamic.ts:47-122](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L47-L122), [packages/mdx/src/runtime/browser.tsx:58-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L58-L76), [packages/mdx/src/runtime/server.ts:72-241](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts#L72-L241) ## Remote Compilation Architecture ### Compiler Factory and Processor Initialization The `createCompiler` function initializes and caches a unified MDX processor instance configured via `createProcessor`. It accepts either a minimal configuration or a full preset configuration through `CompilerOptions`. If format options are omitted or set to `'detect'`, the processor defaults to MDX format. ```typescript export function createCompiler(mdxOptions?: CompilerOptions) { let instance: ReturnType | undefined; function getProcessor() { if (instance) return instance; let format = mdxOptions?.format; if (!format || format === 'detect') format = 'mdx'; return (instance = createProcessor({ ...(mdxOptions?.preset === 'minimal' ? mdxOptions : getCompileOptions(mdxOptions)), format, })); } ``` Sources: [packages/mdx-remote/src/compile.ts:60-73](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts#L60-L73) The compilation pipeline processes raw source strings by first extracting frontmatter via `parseFrontmatter`. It then feeds the content body into the cached processor along with the file path and extracted frontmatter data. ```typescript async compile>( options: CompileMDXOptions, ): Promise> { const { scope = {}, skipRender } = options; const { frontmatter, content } = parseFrontmatter(options.source); const file = await this.compileFile({ value: content, path: options.filePath, data: { frontmatter, }, }); const compiled = String(file); ``` Sources: [packages/mdx-remote/src/compile.ts:89-102](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts#L60-L102) > [!WARNING] > Setting `skipRender` to `true` on `CompileMDXOptions` will bypass the execution phase, leaving `exports` as `null` and throwing an error if the resulting `body` function is invoked. Sources: [packages/mdx-remote/src/compile.ts:44-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts#L44-L48), [packages/mdx-remote/src/compile.ts:109-115](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts#L109-L115) ### Execution Scope and Function Hydration Once the MDX text is compiled into function body string output, `executeMdx` constructs a dynamic asynchronous function via `AsyncFunction`. It merges scope options, JSX runtimes, and base URLs into an `opts` object, exposing remaining scope properties as arguments to the generated function. ```typescript export async function executeMdx(compiled: string, options: Options = {}) { const { opts: scopeOpts, ...scope } = options.scope ?? {}; const fullScope = { opts: { ...(scopeOpts as object), ...(options.jsxRuntime ?? jsxRuntimeDefault), baseUrl: options.baseUrl, }, ...scope, }; const hydrateFn = new AsyncFunction(...Object.keys(fullScope), compiled); return (await hydrateFn.apply(hydrateFn, Object.values(fullScope))) as { default: MdxContent; toc?: TOCItemType[]; }; } ``` Sources: [packages/mdx-remote/src/render.ts:17-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L17-L33) | Option Key | Default / Source | Purpose | | :--- | :--- | :--- | | `scope` | `{}` | Custom variables and context injected into the MDX execution scope. | | `baseUrl` | `pathToFileURL(filePath)` | Resolves relative file paths for remote compilation contexts. | | `jsxRuntime` | `react/jsx-runtime` (or dev runtime) | Supplies JSX element creation functions during component hydration. | Sources: [packages/mdx-remote/src/render.ts:8-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L8-L12), [packages/mdx-remote/src/compile.ts:76-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts#L76-L81) > [!NOTE] > The synchronous counterpart `executeMdxSync` uses a standard synchronous `Function` constructor instead of `AsyncFunction`, evaluating compiled outputs immediately when asynchronous evaluation is not required. Sources: [packages/mdx-remote/src/render.ts:35-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L35-L52) ## Client-Side Evaluation and Component Injection ### Asynchronous and Synchronous Hydration Functions Client runtimes execute compiled MDX bundle strings by constructing dynamic functions via `executeMdx` and `executeMdxSync`. The `executeMdx` function uses an asynchronous function constructor derived from `executeMdx0` or `executeMdx`, while `executeMdxSync` utilizes a standard `Function` constructor to evaluate bundles synchronously. ```typescript const AsyncFunction: new (...args: string[]) => (...args: unknown[]) => Promise = Object.getPrototypeOf(executeMdx).constructor; export async function executeMdx(compiled: string, options: Options = {}) { const { opts: scopeOpts, ...scope } = options.scope ?? {}; const fullScope = { opts: { ...(scopeOpts as object), ...(options.jsxRuntime ?? jsxRuntimeDefault), baseUrl: options.baseUrl, }, ...scope, }; const hydrateFn = new AsyncFunction(...Object.keys(fullScope), compiled); return (await hydrateFn.apply(hydrateFn, Object.values(fullScope))) as { default: MdxContent; toc?: TOCItemType[]; }; } ``` Sources: [packages/mdx-remote/src/render.ts:14-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L17-L33) | Hydration Function | Constructor Type | Return Signature | | :--- | :--- | :--- | | `executeMdx` | `AsyncFunction` | `Promise<{ default: MdxContent; toc?: TOCItemType[] }>` | | `executeMdxSync` | `Function` | `{ default: MdxContent; toc?: TOCItemType[] }` | Sources: [packages/mdx-remote/src/render.ts:14-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L14-L15), [packages/mdx-remote/src/render.ts:28-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L28-L32), [packages/mdx-remote/src/render.ts:46-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L46-L51) > [!NOTE] > The legacy `executeMdx` implementation in `packages/mdx-remote/src/index.ts` automatically selects between `react/jsx-runtime` and `react/jsx-dev-runtime` based on `process.env.NODE_ENV === 'production'`. Sources: [packages/mdx-remote/src/index.ts:10-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/index.ts#L10-L17) ### Scope Merging and Component Bindings Both `executeMdx` and `executeMdxSync` accept an `Options` object containing scope variables, base URLs, and custom JSX runtimes. The options merge property values into an `opts` object, exposing remaining scope properties as arguments to the generated hydration function. ```typescript export async function executeMdx(compiled: string, options: Options = {}) { const { opts: scopeOpts, ...scope } = options.scope ?? {}; const fullScope = { opts: { ...(scopeOpts as object), ...(options.jsxRuntime ?? jsxRuntimeDefault), baseUrl: options.baseUrl, }, ...scope, }; ``` Sources: [packages/mdx-remote/src/render.ts:17-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L17-L26) > [!WARNING] > Failing to supply a valid `jsxRuntime` option defaults execution to `jsxRuntimeDefault` (`react/jsx-runtime`), which may cause runtime errors if development-only JSX annotations are required by the compiled bundle. Sources: [packages/mdx-remote/src/render.ts:4-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L4-L4), [packages/mdx-remote/src/render.ts:22-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L22-L22), [packages/mdx-remote/src/render.ts:40-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L40-L40) The resulting `MdxContent` component accepts optional `components` bindings matching `MDXComponents` alongside table-of-contents data structured as `TOCItemType[]`. ```typescript import type { MDXComponents } from 'mdx/types'; import type { TOCItemType } from 'fumadocs-core/toc'; import type { FC } from 'react'; import jsxRuntimeDefault from 'react/jsx-runtime'; export type MdxContent = FC<{ components?: MDXComponents }>; ``` Sources: [packages/mdx-remote/src/render.ts:1-6](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L1-L6), [packages/mdx-remote/src/render.ts:29-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts#L29-L32) ## Dynamic Doc Collection Runtime ### On-Demand Collection Initialization and Execution The runtime compilation engine initializes dynamic documentation collections using `dynamic` and `server` modules. The `dynamic` function initializes core configurations via `createCore` and builds configuration exports from the working directory using `buildConfig`. ```typescript export async function dynamic( configExports: Config, coreOptions: CoreOptions, serverOptions?: ServerOptions, ) { const core = createCore(coreOptions); await core.init({ config: buildConfig(configExports as Record, process.cwd()), }); ``` Sources: [packages/mdx/src/runtime/dynamic.ts:47-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L47-L55) > [!NOTE] > The `getDocCollection` utility validates collection existence, retrieving either standard documentation arrays or single documentation entries based on the collection type definition. Sources: [packages/mdx/src/runtime/dynamic.ts:59-65](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L59-L65) Lazy entry compilation reads raw file content via `node:fs/promises`, strips frontmatter metadata using the `frontmatter` utility, and compiles MDX through `buildMDX` in runtime environment mode. The compiled output string is then evaluated using an asynchronous function constructor initialized by `executeMdx`. ```typescript async function compile({ info, data }: LazyEntry) { let content = await fs.readFile(info.fullPath, 'utf-8'); content = frontmatter(content).content; const compiled = await buildMDX(core, collection, { filePath: info.fullPath, source: content, frontmatter: data as Record, isDevelopment: false, environment: 'runtime', }); return (await executeMdx(String(compiled.value), { baseUrl: pathToFileURL(info.fullPath), })) as CompiledMDXProperties; } ``` Sources: [packages/mdx/src/runtime/dynamic.ts:71-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L71-L86) | Execute Option | Type | Purpose | | :--- | :--- | :--- | | `scope` | `Record` | Injected variables and options scope for MDX execution | | `baseUrl` | `string \| URL` | File URL reference for relative asset resolution | | `jsxRuntime` | `unknown` | Custom JSX runtime fallback overriding default imports | Sources: [packages/mdx/src/runtime/dynamic.ts:22-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L22-L26), [packages/mdx/src/runtime/dynamic.ts:33-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L33-L39) ### Server Document Mapping and Lazy Collections The `server` module provides utility factories including `fileInfo`, `mapDocData`, and `createDocMethods` to construct document metadata and method bindings for file entries. Passthrough properties defined in server options are explicitly mapped into document data records alongside body contents, table-of-contents trees, and structured data extracts. ```typescript export function server(options: ServerOptions = {}) { const { doc: { passthroughs: docPassthroughs = [] } = {} } = options; function fileInfo(file: string, base: string): FileInfo { if (file.startsWith('./')) { file = file.slice(2); } return { path: file, fullPath: path.join(base, file), }; } function mapDocData(entry: CompiledMDXProperties): DocData { const data: DocData = { body: entry.default, toc: entry.toc, structuredData: entry.structuredData, _exports: entry as unknown as Record, }; for (const key of docPassthroughs) { // @ts-expect-error -- handle passthrough properties data[key] = entry[key]; } return data; } ``` Sources: [packages/mdx/src/runtime/server.ts:72-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts#L72-L100) > [!WARNING] > Calling `getText('processed')` or `getMDAST()` on document methods throws an error unless `includeProcessedMarkdown` or `includeMDAST` are enabled in the collection configuration. Sources: [packages/mdx/src/runtime/server.ts:296-310](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts#L296-L310) Collections support both eager and lazy loading variants through `doc`, `docLazy`, `docs`, `docsLazy`, and `meta` methods. Lazy execution caches compilation promises per entry, preventing redundant file reads and MDX build steps during subsequent document retrievals. ```typescript for (const entry of entries) { head[entry.info.path] = () => entry.data; let cachedResult: Promise | undefined; body[entry.info.path] = () => (cachedResult ??= compile(entry)); } return { head, body }; } ``` Sources: [packages/mdx/src/runtime/dynamic.ts:88-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts#L88-L95), [packages/mdx/src/runtime/server.ts:126-155](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts#L126-L155) The `toFumadocsSource` function aggregates page and metadata items into a unified virtual file structure for downstream source consumers, applying optional base directory paths to all registered virtual file entries. ```typescript export function toFumadocsSource< Page extends DocMethods & PageData, Meta extends MetaMethods & MetaData, >( pages: Page[], metas: Meta[], options?: ToFumadocsSourceOptions, ): Source<{ pageData: Page; metaData: Meta; }> { const baseDir = options?.baseDir; const files: VirtualFile<{ pageData: Page; metaData: Meta; }>[] = []; for (const entry of pages) { files.push({ type: 'page', path: baseDir ? path.join(baseDir, entry.info.path) : entry.info.path, absolutePath: entry.info.fullPath, data: entry, }); } for (const entry of metas) { files.push({ type: 'meta', path: baseDir ? path.join(baseDir, entry.info.path) : entry.info.path, absolutePath: entry.info.fullPath, data: entry, }); } return { files, }; } ``` Sources: [packages/mdx/src/runtime/server.ts:243-281](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts#L243-L281) ## Browser Execution and Client Loaders ### Client Loader Creation and Cache Sharing The browser runtime exports the `browser` factory and `createClientLoader` utility to manage compiled MDX file entries and render components within React client environments. To prevent duplicate chunks generated by code-splitting frameworks such as Tanstack Start from fracturing state, `createClientLoader` accepts an optional `id` configuration option to share document preloads across multiple instances through a global `loaderStore` map. ```tsx const loaderStore = new Map< string, { preloaded: Map; } >(); export function createClientLoader< Doc = CompiledMDXProperties, Props extends object | undefined = undefined, >( globEntries: Record Promise>, options: ClientLoaderOptions, ): ClientLoader { const { id = '', component: useRenderer } = options; const renderers: Record> = {}; const loaders = new Map Promise>(); const store = loaderStore.get(id) ?? { preloaded: new Map(), }; loaderStore.set(id, store); ``` Sources: [packages/mdx/src/runtime/browser.tsx:78-99](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L78-L99) > [!NOTE] > File path keys registered in glob entries are normalized by stripping leading `./` prefixes to ensure consistent cache lookups regardless of glob path syntax. Sources: [packages/mdx/src/runtime/browser.tsx:100-102](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L100-L102) ### Standard Schema Integration and Renderer Methods The `doc` method on the browser collection entry infers frontmatter output types via `@standard-schema/spec` while wrapping raw glob entries and forwarding options to `createClientLoader`. ```tsx export function browser() { return { doc( _name: Name, glob: Record Promise>, ) { const out: DocCollectionEntry = { raw: glob as DocCollectionEntry['raw'], createClientLoader({ id = _name as string, ...options }) { return createClientLoader(this.raw, { id, ...options }); }, }; return out as Config[Name] extends DocCollection | DocsCollection ? DocCollectionEntry, TC> : never; }, ``` Sources: [packages/mdx/src/runtime/browser.tsx:58-74](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L58-L74) Client loaders return an interface containing three core methods for retrieving and rendering documentation entries: `preload`, `getComponent`, and `useContent`. | Method | Parameters | Return Type | Description | | :--- | :--- | :--- | :--- | | `preload` | `path: string` | `Promise` | Asynchronously fetches and caches raw document content into the store | | `getComponent` | `path: string` | `FC` | Returns a React functional component that renders the document using React's `use()` hook | | `useContent` | `path: string, props?: Props` | `ReactNode` | Directly renders the document component populated with the provided properties | Sources: [packages/mdx/src/runtime/browser.tsx:28-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L28-L40), [packages/mdx/src/runtime/browser.tsx:125-138](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L125-L138) > [!WARNING] > Requesting a path that does not exist in the available glob entries throws an error directly from `getLoader` during resolution. Sources: [packages/mdx/src/runtime/browser.tsx:104-109](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx#L104-L109) ## Runtime Plugin Presets and Execution ### MDX Preset Configuration and Default Plugins The `mdxPreset` function asynchronous helper builds and configures `ProcessorOptions` for unified and MDX pipelines by resolving default remark and rehype plugins alongside custom overrides. By default, the output format is set to `function-body`, and standard plugins can be disabled by passing `false` to their respective option flags in `MDXRuntimePresetOptions`. | Preset Option | Default State | Associated Module / Plugin | Configuration Object | | :--- | :--- | :--- | :--- | | `remarkHeadingOptions` | Enabled (unless `false`) | `@/mdx-plugins/remark-heading` | `{ generateToc: false, ...remarkHeadingOptions }` | | `remarkImageOptions` | Enabled (unless `false`) | `@/mdx-plugins/remark-image` | `remarkImageOptions` | | `remarkCodeTabOptions` | Enabled (unless `false`) | `@/mdx-plugins/remark-code-tab` | `remarkCodeTabOptions` | | `remarkNpmOptions` | Enabled (unless `false`) | `@/mdx-plugins/remark-npm` | `remarkNpmOptions` | | `remarkStructureOptions` | Enabled (unless `false`) | `@/mdx-plugins/remark-structure` | `{ exportAs: 'structuredData', ...remarkStructureOptions }` | | `rehypeCodeOptions` | Enabled (unless `false`) | `@/mdx-plugins/rehype-code` | `rehypeCodeOptions` | | `remarkPlugins` / `rehypePlugins` | Resolves `v` | `remark-gfm` (remark), `@/mdx-plugins/rehype-toc` (rehype) | User-defined or resolved via `resolvePlugins` | ```typescript export async function mdxPreset(options: MDXRuntimePresetOptions = {}): Promise { const { rehypeCodeOptions, remarkImageOptions, remarkHeadingOptions, remarkStructureOptions, remarkCodeTabOptions, remarkNpmOptions, outputFormat = 'function-body', ...mdxOptions } = options; const remarkPlugins = await resolvePlugins( (v) => [ import('remark-gfm').then((mod) => mod.default), remarkHeadingOptions !== false && import('@/mdx-plugins/remark-heading').then((mod) => [ mod.remarkHeading, { generateToc: false, ...remarkHeadingOptions, }, ]), remarkImageOptions !== false && import('@/mdx-plugins/remark-image').then((mod) => [mod.remarkImage, remarkImageOptions]), remarkCodeTabOptions !== false && import('@/mdx-plugins/remark-code-tab').then((mod) => [ mod.remarkCodeTab, remarkCodeTabOptions, ]), remarkNpmOptions !== false && import('@/mdx-plugins/remark-npm').then((mod) => [mod.remarkNpm, remarkNpmOptions]), ...v, remarkStructureOptions !== false && import('@/mdx-plugins/remark-structure').then((mod) => [ mod.remarkStructure, { exportAs: 'structuredData', ...remarkStructureOptions, } satisfies Plugins.StructureOptions, ]), ], mdxOptions.remarkPlugins, ); const rehypePlugins = await resolvePlugins( (v) => [ rehypeCodeOptions !== false && import('@/mdx-plugins/rehype-code').then((mod) => [mod.rehypeCode, rehypeCodeOptions]), ...v, import('@/mdx-plugins/rehype-toc').then((mod) => mod.rehypeToc), ], mdxOptions.rehypePlugins, ); return { ...mdxOptions, outputFormat, remarkPlugins, rehypePlugins, }; } ``` Sources: [packages/core/src/content/mdx/preset-runtime.ts:23-84](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts#L23-L84) > [!NOTE] > The remark heading plugin explicitly forces `generateToc: false` by default within the preset runtime, separating table-of-contents generation into the rehype TOC pipeline. Sources: [packages/core/src/content/mdx/preset-runtime.ts:38-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts#L38-L45) ### File Tree Transformation and Auto-Files Parsing The `remarkMdxFiles` transformer parses code blocks with the `files` language identifier or `auto-files` JSX flow elements into MDX component structures (``, ``, and ``). The `parseFileTree` helper splits code lines, tracks indentation depth using standard Unix or Windows line endings, and builds hierarchical folder-file relationships. When encountering `` elements, the transformer extracts `dir`, `pattern`, and `defaultOpenAll` attributes, utilizing `tinyglobby` to scan directories relative to the virtual file's parent directory or CWD. ```typescript function parseFileTree(code: string) { const lines = code.split(/\r?\n/); const stack = new Map(); for (const line of lines) { let depth = 0; let name = line; let match: RegExpMatchArray | null; while ((match = /(?:├──|│|└──)\s*/.exec(name))) { name = name.slice(match[0].length); depth++; } if (!name) continue; const node: Node = name.endsWith('/') ? { type: 'folder', name, children: [], depth } : { type: 'file', name, depth }; let parent: Node | undefined; for (let i = depth - 1; i >= 0 && !parent; i--) { parent = stack.get(i); } stack.set(depth, node); if (!parent) continue; if (parent.type === 'file') { Object.assign(parent, { type: 'folder', children: [], }); } (parent as FolderNode).children.push(node); } return stack.get(0); } function defaultToMDX(node: Node, options: ToMdxOptions, depth = 0): MdxJsxFlowElement { if (depth === 0) { return { type: 'mdxJsxFlowElement', name: 'Files', attributes: [], children: [defaultToMDX(node, options, depth + 1)], }; } const attributes: MdxJsxAttribute[] = [ { type: 'mdxJsxAttribute', name: 'name', value: node.name }, ]; if (node.type === 'file') { return { type: 'mdxJsxFlowElement', attributes, children: [], name: 'File', }; } if (options.defaultOpenAll) { attributes.push({ type: 'mdxJsxAttribute', name: 'defaultOpen', value: null, }); } return { type: 'mdxJsxFlowElement', attributes, name: 'Folder', children: node.children.map((item) => defaultToMDX(item, options, depth + 1)), }; } /** * ``` Sources: [packages/core/src/mdx-plugins/remark-mdx-files.ts:40-162](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-files.ts#L40-L162) > [!WARNING] > Omitting the `pattern` attribute on an `` element triggers an immediate failure on the virtual file (`file.fail`) at the node's exact AST position. Sources: [packages/core/src/mdx-plugins/remark-mdx-files.ts:146-156](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-files.ts#L146-L156) ### Placeholder Rendering and Serialization The `renderPlaceholder` runtime function evaluates delimited control strings matching the control regex `/\0(.+?)\0/gs`, parsing inner JSON payloads into `PlaceholderData` objects containing `name`, `attributes`, and `children`. If nested child blocks contain text, `renderPlaceholder` executes recursively. If a matching renderer exists in the `renderers` dictionary, the placeholder output is replaced with the renderer's return value; otherwise, it falls back to the raw child text or the original match block upon a JSON parsing error. ```typescript const regex = /\0(.+?)\0/gs; export async function renderPlaceholder( text: string, renderers: Record Awaitable>, ): Promise { let out = ''; let idx = 0; for (const match of text.matchAll(regex)) { out += text.slice(idx, match.index); const inner = match[1]; try { const data = JSON.parse(inner) as PlaceholderData; const renderer = data.name && renderers[data.name]; if (data.children.trim()) { data.children = await renderPlaceholder(data.children, renderers); } if (renderer) { out += await renderer(data); } else { out += data.children; } } catch { out += match[0]; } idx = match.index + match[0].length; } out += text.slice(idx); return out; ``` Sources: [packages/core/src/mdx-plugins/remark-llms.runtime.ts:10-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.runtime.ts#L10-L42) ## Preview and Dynamic Rendering Integration ### Markdown Compiler Setup and Plugin Pipelines The markdown compiler pipeline is configured via `createMarkdownCompiler`, which accepts `remarkPlugins`, `rehypePlugins`, and `remarkRehypeOptions`. In preview environments, the processor integrates `remarkGfm`, `remarkMath`, `remarkMdxMermaid`, `remarkHeading`, `remarkNpm`, and `remarkCodeTab`, alongside `rehypeKatex`, `rehypeCode`, and `rehypeToc` with `{ exportToc: { as: 'data' } }`. ```tsx const compiler = createMarkdownCompiler({ remarkPlugins: [ remarkGfm, remarkMath, remarkMdxMermaid, plugin(remarkHeading, { generateToc: false }), plugin(remarkNpm, { persist: { id: 'package-manager' } }), remarkCodeTab, ], remarkRehypeOptions: { passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement'], }, rehypePlugins: [ rehypeKatex, plugin(rehypeCode, { lazy: true, fallbackLanguage: 'text' }), plugin(rehypeToc, { exportToc: { as: 'data' } }), ], }); ``` Sources: [packages/preview/src/pages/...slugs.tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46) | Compiler Option | Configured Plugins / Options | Purpose | | :--- | :--- | :--- | | `remarkPlugins` | `remarkGfm`, `remarkMath`, `remarkMdxMermaid`, `remarkHeading`, `remarkNpm`, `remarkCodeTab` | Extends markdown parsing with tables, math, mermaid diagrams, headings, package managers, and code tabs. | | `remarkRehypeOptions` | `passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement']` | Preserves JSX flow and text elements during AST conversion. | | `rehypePlugins` | `rehypeKatex`, `rehypeCode`, `rehypeToc` | Applies KaTeX math formatting, code [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting), and [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) extraction. | Sources: [packages/preview/src/pages/...slugs.tsx:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L29-L46) > [!CAUTION] > The markdown compilation renderer throws an explicit error when encountering disallowed evaluation nodes, disallowing program evaluation and limiting identifier lookup strictly to override component bindings. Sources: [packages/preview/src/lib/md.ts:45-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/md.ts#L45-L55) ### Component Injection and Rendering Handlers The `DocPage` routing component loads layout and page structures based on configuration presets (`docs` or `flux`), resolving page slugs through source loaders. When rendering content inside `MdContent`, `ServerImage` intercepts non-absolute image sources and rewrites them into query parameters containing `page`, `project`, and `src`. ```tsx function useMdxComponents(page: SourcePage) { function ServerImage({ src, ...rest }: ComponentProps<'img'>) { // resolve non-absolute src if (src && !URL.canParse(src)) { const params = new URLSearchParams(); params.set('page', page.absolutePath!); params.set('project', page.data.project.dir); params.set('src', src); src = `/img?${params}`; } return ; } return { ...defaultMdxComponents, Mermaid, img: ServerImage, }; } ``` Sources: [packages/preview/src/pages/...slugs.tsx:48-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L48-L67) > [!NOTE] > When page compilation fails, the preview layout catches the error and formats the stack trace inside a code block component rather than crashing the request. Sources: [packages/preview/src/pages/...slugs.tsx:170-194](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx#L170-L194) ## Related - [MDX Loader Pipeline](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/mdx-pipeline/mdx-loader-pipeline) --- ## Technical docs: Base UI Components URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/base-ui-components
Relevant source files The following files were used as context for generating this wiki page: - [packages/base-ui/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts) - [packages/radix-ui/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts) - [packages/base-ui/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json) - [packages/base-ui/src/components/dialog/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search.tsx) - [packages/api-docs/src/components/dialog.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/dialog.tsx) - [packages/base-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/sanity/registry/base.component.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/base.component.tsx) - [packages/base-ui/src/components/tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/tabs.tsx) - [packages/base-ui/src/components/card.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/card.tsx) - [packages/base-ui/src/components/accordion.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/accordion.tsx) - [packages/cli/src/commands/shared.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts) - [packages/radix-ui/src/components/dialog/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search.tsx) - [packages/base-ui/src/components/sidebar/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/base.tsx) - [packages/base-ui/src/layouts/home/navbar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/home/navbar.tsx) - [packages/base-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/slots/sidebar.tsx) - [packages/base-ui/src/components/toc/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/index.tsx) - [packages/radix-ui/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json) - [packages/python/src/components/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx) - [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx) - [packages/base-ui/src/provider/waku.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/waku.tsx) - [packages/radix-ui/src/components/card.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/card.tsx) - [packages/radix-ui/src/components/sidebar/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/base.tsx) - [packages/base-ui/src/layouts/shared/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/shared/client.tsx) - [packages/base-ui/src/provider/react-router.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/react-router.tsx) - [packages/base-ui/src/provider/next.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/next.tsx) - [packages/base-ui/src/provider/tanstack.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/tanstack.tsx) - [packages/base-ui/src/components/ui/navigation-menu.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/ui/navigation-menu.tsx) - [packages/base-ui/src/components/ui/accordion.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/ui/accordion.tsx) - [packages/base-ui/src/layouts/flux/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/index.tsx)
## Overview Base UI Components provides the core interactive building blocks, layout primitives, and styling integration for Fumadocs UI, enabling flexible documentation site construction across multiple JavaScript UI toolkits and routing frameworks. Built around modular registry architectures and headless design patterns, the package supports dual distribution via `@fumadocs/base-ui` and `@fumadocs/radix-ui` registries. It solves the challenge of maintaining accessible, framework-agnostic documentation layouts, keyboard-navigable search dialogs, collapsible navigation trees, and synchronized tab containers through encapsulated React components and utility hooks. Sources: [packages/base-ui/registry/index.ts:9-10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts#L9-L10), [packages/radix-ui/registry/index.ts:9-10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts#L9-L10), [packages/base-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L2-L4), [packages/radix-ui/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L2-L4), [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4) ## Package Architecture and Registry Discovery ### Registry Mapping and Package Configuration The CLI command configuration maps UI registries to specific identifier strings through the `UIRegistries` object, binding `'base-ui'` to `'fumadocs/base-ui'` and `'radix-ui'` to `'fumadocs/radix-ui'`. Sources: [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4) ```typescript export const UIRegistries = { 'base-ui': 'fumadocs/base-ui', 'radix-ui': 'fumadocs/radix-ui', }; ``` Sources: [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4) Both packages share version `16.10.2` and export modular entry points, yet their distribution layouts diverge based on underlying primitive dependencies. `@fumadocs/base-ui` defines package exports for base UI components, providers, and layout slots while targeting `@fumadocs/base-ui`. Sources: [packages/base-ui/package.json:2-3](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L2-L3), [packages/base-ui/package.json:18-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L18-L114) ```json { "name": "@fumadocs/base-ui", "version": "16.10.2", "description": "The Base UI version of Fumadocs UI" } ``` Sources: [packages/base-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json#L1-L4) Conversely, `@fumadocs-ui` (published from the `radix-ui` package directory) exposes legacy layout and sidebar entries alongside equivalent Radix UI primitive paths such as `./utils/get-sidebar-tabs` and `./components/tabs.unstyled`. Sources: [packages/radix-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L1-L4), [packages/radix-ui/package.json:94-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L94-L95), [packages/radix-ui/package.json:116-117](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L116-L117) ```json { "name": "fumadocs-ui", "version": "16.10.2", "description": "The Radix UI version of Fumadocs UI" } ``` Sources: [packages/radix-ui/package.json:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json#L1-L4) ### Component Registries and Layout Definitions The registry definitions for both `base-ui` and `radix-ui` construct a component collection by spreading `commonComponents` and evaluating `findSlotComponents(dir)`, subsequently registering unlisted layout blocks including `layouts/sidebar`, `layouts/shared`, `layouts/docs`, `layouts/flux`, `layouts/notebook`, `layouts/home`, and modular component entries like `accordion`, `github-info`, `banner`, `callout`, `card`, `codeblock`, `files`, `heading`, `image-zoom`, `inline-toc`, `steps`, and `tabs`. Sources: [packages/base-ui/registry/index.ts:9-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts#L9-L14), [packages/base-ui/registry/index.ts:15-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts#L15-L35), [packages/base-ui/registry/index.ts:159-272](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts#L159-L272), [packages/radix-ui/registry/index.ts:9-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts#L9-L14), [packages/radix-ui/registry/index.ts:15-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts#L15-L35), [packages/radix-ui/registry/index.ts:159-272](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts#L159-L272) ```typescript export const registry: Registry = { name: 'fumadocs/base-ui', dir, components: [ ...commonComponents, ...(await findSlotComponents(dir)), { name: 'layouts/sidebar', unlisted: true, files: [ { type: 'components', path: 'components/sidebar/base.tsx', target: '
/docs-sidebar/base.tsx', }, { type: 'components', path: 'components/sidebar/page-tree.tsx', target: '/docs-sidebar/page-tree.tsx', }, { type: 'components', path: 'components/sidebar/link-item.tsx', target: '/docs-sidebar/link-item.tsx', }, ], }, ``` Sources: [packages/base-ui/registry/index.ts:9-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts#L9-L34) > [!NOTE] > File order matters in the shadcn CLI registry configuration when writing import paths on consumer codebases, making the sequence of layout and component registrations critical for proper module resolution. > Sources: [packages/base-ui/registry/index.ts:8-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts#L8-L14), [packages/radix-ui/registry/index.ts:8-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts#L8-L14) ## Search Dialog Component Primitives ### List Virtualization and Keyboard Navigation The search dialog lifecycle and presentation are composed around primitive wrappers, including `SearchDialogOverlay`, `SearchDialogContent`, `SearchDialogList`, and `SearchDialogListItem`. These components manage portal mounting, backdrop blur effects, animated height adjustments via `ResizeObserver`, and keyboard navigation handlers. Sources: [packages/base-ui/src/components/dialog/search.tsx:268-283](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search.tsx#L268-L283) `SearchDialogContent` wraps content inside `Dialog.Portal` and `Dialog.Popup`, fixing the container's position to the center of the screen with responsive top offset calculations (`md:top-[calc(50%-250px)]`), maximum width sizing (`max-w-screen-sm`), overflow clipping, and entrance/exit animation hooks (`data-open:animate-fd-dialog-in`, `data-closed:animate-fd-dialog-out`). ```tsx export function SearchDialogContent({ children, className, ...props }: ComponentProps) { const t = useTranslations({ note: 'search dialog' }); return ( cn( 'fixed left-1/2 top-4 md:top-[calc(50%-250px)] z-50 w-[calc(100%-1rem)] max-w-screen-sm -translate-x-1/2 rounded-xl border bg-fd-popover text-fd-popover-foreground shadow-2xl overflow-hidden data-closed:animate-fd-dialog-out data-open:animate-fd-dialog-in focus-visible:outline-none', '*:border-b *:has-[+:last-child[data-empty=true]]:border-b-0 *:data-[empty=true]:border-b-0 *:last:border-b-0', typeof className === 'function' ? className(s) : className, ) } > {t('Search')} {children} ); } ``` Sources: [packages/base-ui/src/components/dialog/search.tsx:285-311](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search.tsx#L285-L311) > [!NOTE] > `SearchDialogContent` explicitly forces `aria-describedby={undefined}` on the underlying `Dialog.Popup` component to suppress screen reader warnings regarding missing descriptive node elements when rendering dynamic search records. > Sources: [packages/base-ui/src/components/dialog/search.tsx:295-296](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search.tsx#L295-L296) `SearchDialogList` manages active item selection state, observes container dimensions via `ResizeObserver` to dynamically apply a `--fd-animated-height` CSS property for height transitions, and binds window- or content-level keydown listeners for keyboard traversal. ```tsx export function SearchDialogList({ items = null, Empty = () => (
), Item = (props) => , ...props }: Omit, 'children'> & { items: SearchItemType[] | null | undefined; /** * Renderer for empty list UI */ Empty?: () => ReactNode; /** * Renderer for items */ Item?: (props: { item: SearchItemType; onClick: () => void }) => ReactNode; }) { const ref = useRef(null); const { onSelect } = useSearch(); const [active, setActive] = useState(() => items && items.length > 0 ? items[0].id : null, ); const onKey = useEffectEvent((e: KeyboardEvent) => { if (!items || e.isComposing) return; if (e.key === 'ArrowDown' || e.key == 'ArrowUp') { let idx = items.findIndex((item) => item.id === active); if (idx === -1) idx = 0; else if (e.key === 'ArrowDown') idx++; else idx--; setActive(items.at(idx % items.length)?.id ?? null); e.preventDefault(); } if (e.key === 'Enter') { const selected = items.find((item) => item.id === active); if (selected) onSelect(selected); e.preventDefault(); } }); useEffect(() => { ``` Sources: [packages/base-ui/src/components/dialog/search.tsx:313-360](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search.tsx#L313-L360) The keyboard event handler processes specific navigation keys to modify the active selection index modulo the total item length, and triggers selection upon pressing `Enter`. | Key | Action | Behavior | | :--- | :--- | :--- | | `ArrowDown` | Increment Index | Moves active focus down; wraps to index `0` at the end of the list. | | `ArrowUp` | Decrement Index | Moves active focus up; wraps to the last item when reaching the top. | | `Enter` | Select Item | Invokes `onSelect` with the currently active search item object. | Sources: [packages/base-ui/src/components/dialog/search.tsx:342-358](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search.tsx#L342-L358) > [!WARNING] > Keyboard listeners check `e.isComposing` before evaluating arrow keys or enter inputs to prevent capturing keystrokes while users are actively composing characters via an Input Method Editor (IME). > Sources: [packages/base-ui/src/components/dialog/search.tsx:340](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search.tsx#L340) ## Collapsible Accordions and Trigger Controls ### Accordion Structure and State Synchronization The accordion components are built on top of `@base-ui/react/accordion` primitives, providing accessible disclosure containers with animated height transitions and hash-based anchor linking. The exported `Accordions` wrapper component maintains the expanded item values in local state while reading the initial `window.location.hash` on mount to automatically expand targeted items. ```tsx export function Accordions({ ref, className, defaultValue, ...props }: ComponentProps) { const rootRef = useRef(null); const composedRef = mergeRefs(ref, rootRef); const [value, setValue] = useState(defaultValue ?? []); useEffect(() => { const id = window.location.hash.substring(1); const element = rootRef.current; if (!element || id.length === 0) return; const selected = document.getElementById(id); if (!selected || !element.contains(selected)) return; const value = selected.getAttribute('data-accordion-value'); if (value) setValue((prev) => [value, ...prev]); }, []); ``` Sources: [packages/base-ui/src/components/accordion.tsx:18-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/accordion.tsx#L18-L38) > [!NOTE] > When an element ID matches the URL hash upon initial page load, the accordion component verifies that the target DOM element exists inside the accordion container before prepending its `data-accordion-value` into the expanded state array. > Sources: [packages/base-ui/src/components/accordion.tsx:28-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/accordion.tsx#L28-L38) The styling and layout structure for the accordion components are mapped through UI wrapper functions defined in the UI layer. | Component | Base UI Primitive | CSS Classes and Styling Behavior | | :--- | :--- | :--- | | `Accordion` | `Primitive.Root` | `divide-y divide-fd-border overflow-hidden rounded-lg border bg-fd-card` | | `AccordionItem` | `Primitive.Item` | Passes props directly without extra wrapper classes. | | `AccordionHeader` | `Primitive.Header` | `scroll-m-24 not-prose flex flex-row items-center text-fd-card-foreground font-medium has-focus-visible:bg-fd-accent` | | `AccordionTrigger` | `Primitive.Trigger` | `group flex flex-1 items-center gap-2 px-3 py-2.5 text-start focus-visible:outline-none` | | `AccordionContent` | `Primitive.Panel` | `h-(--accordion-panel-height) overflow-hidden transition-[height] ease-out data-[ending-style]:h-0 data-[starting-style]:h-0` | Sources: [packages/base-ui/src/components/ui/accordion.tsx:8-84](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/ui/accordion.tsx#L8-L84) ### Triggers, Content Panels, and Copy Actions Individual `Accordion` sections combine an `AccordionItem`, `AccordionHeader`, `AccordionTrigger`, and `AccordionContent` with an optional link-copy button. The trigger incorporates a rotating chevron indicator that reacts to panel opening states via group data attributes. ```tsx export function AccordionTrigger({ className, children, ...props }: ComponentProps) { return ( cn( 'group flex flex-1 items-center gap-2 px-3 py-2.5 text-start focus-visible:outline-none', typeof className === 'function' ? className(s) : className, ) } {...props} > {children} ); ``` Sources: [packages/base-ui/src/components/ui/accordion.tsx:46-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/ui/accordion.tsx#L46-L64) ```tsx export function AccordionContent({ className, children, ...props }: ComponentProps) { return ( cn( 'h-(--accordion-panel-height) overflow-hidden transition-[height] ease-out data-[ending-style]:h-0 data-[starting-style]:h-0', typeof className === 'function' ? className(s) : className, ) } {...props} > {children} ); ``` Sources: [packages/base-ui/src/components/ui/accordion.tsx:67-84](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/ui/accordion.tsx#L67-L84) When an `id` prop is supplied to the `Accordion` component, a `CopyButton` is rendered inside the header alongside the trigger. This button uses `useCopyButton` to write a direct URL hash link to the clipboard and temporarily toggles a check icon upon successful copying. ```tsx export function Accordion({ title, id, value = String(title), children, ...props }: Omit, 'value' | 'title'> & { title: string | ReactNode; value?: string; }) { return ( {title} {id ? : null}
{children}
); } ``` Sources: [packages/base-ui/src/components/accordion.tsx:56-79](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/accordion.tsx#L56-L79) ```tsx function CopyButton({ id }: { id: string }) { const t = useTranslations({ note: 'accordion' }); const [checked, onClick] = useCopyButton(() => { const url = new URL(window.location.href); url.hash = id; return navigator.clipboard.writeText(url.toString()); }); return ( ); } ``` Sources: [packages/base-ui/src/components/accordion.tsx:81-105](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/accordion.tsx#L81-L105) > [!CAUTION] > `AccordionContent` specifies `hiddenUntilFound` to allow browser find-in-page features to automatically reveal text content hidden inside collapsed accordion panels. > Sources: [packages/base-ui/src/components/accordion.tsx:72](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/accordion.tsx#L72) ## Tabs Containers and Active State Sync ### State Synchronization and Simple Mode The `Tabs` component supports both advanced Radix-style usage and simple mode via the `items` property. In simple mode, string identifiers passed to `items` are transformed into normalized values using the `escapeValue` helper function, which converts strings to lowercase and replaces whitespace characters with hyphens. ```tsx function escapeValue(v: string): string { return v.toLowerCase().replace(/\s/, '-'); } ``` Sources: [packages/base-ui/src/components/tabs.tsx:202-204](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/tabs.tsx#L202-L204) The `Tabs` root component initializes its state using `defaultIndex` or `defaultValue`, validating any value updates against the item collection when simple mode `items` are defined. ```tsx export function Tabs({ ref, className, items, label, defaultIndex = 0, defaultValue = items ? escapeValue(items[defaultIndex]) : undefined, ...props }: TabsProps) { const [value, setValue] = useState(defaultValue); const collection = useMemo(() => [], []); return ( cn( 'flex flex-col overflow-hidden rounded-xl border bg-fd-secondary my-4', typeof className === 'function' ? className(s) : className, ) } value={value} onValueChange={(v: string) => { if (items && !items.some((item) => escapeValue(item) === v)) return; setValue(v); }} {...props} > ``` Sources: [packages/base-ui/src/components/tabs.tsx:86-113](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/tabs.tsx#L86-L113) > [!WARNING] > When `items` are provided, `onValueChange` explicitly blocks value updates if the incoming value does not match an escaped item string in the collection list. > Sources: [packages/base-ui/src/components/tabs.tsx:108-111](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/tabs.tsx#L108-L111) ### Collection Index Tracking and Context Child panels coordinate their active states through a React context that holds the `items` array and a mutable `collection` key array. The `useCollectionIndex` hook registers component render order to automatically assign indices for tab items lacking explicit value props. ```tsx const TabsContext = createContext<{ items?: string[]; collection: CollectionKey[]; } | null>(null); function useTabContext() { const ctx = useContext(TabsContext); if (!ctx) throw new Error('You must wrap your component in '); return ctx; } ``` Sources: [packages/base-ui/src/components/tabs.tsx:41-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/tabs.tsx#L41-L50) ```tsx function useCollectionIndex() { const key = useId(); const { collection } = useTabContext(); useEffect(() => { return () => { const idx = collection.indexOf(key); if (idx !== -1) collection.splice(idx, 1); }; }, [key, collection]); if (!collection.includes(key)) collection.push(key); return collection.indexOf(key); } ``` Sources: [packages/base-ui/src/components/tabs.tsx:184-197](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/tabs.tsx#L184-L197) The `Tab` component resolves its target value by falling back to the collection index position within the `items` list if no explicit `value` prop is supplied. ```tsx export function Tab({ value, ...props }: TabProps) { const { items } = useTabContext(); const resolved = value ?? // eslint-disable-next-line react-hooks/rules-of-hooks -- `value` is not supposed to change items?.at(useCollectionIndex()); if (!resolved) throw new Error( 'Failed to resolve tab `value`, please pass a `value` prop to the Tab component.', ); return ( {props.children} ); } ``` Sources: [packages/base-ui/src/components/tabs.tsx:138-154](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/tabs.tsx#L138-L154) > [!NOTE] > `TabsContent` forces `keepMounted` to maintain DOM nodes while inactive, and hides unselected panels using the `data-[inactive]:hidden` attribute selector. > Sources: [packages/base-ui/src/components/tabs.tsx:156-176](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/tabs.tsx#L156-L176) ## Interactive Cards and Grid Layouts ### Cards Grid Collection and Container Queries The `Cards` wrapper component organizes card collections into a responsive two-column grid layout utilizing container query units. It renders a standard `div` element spreading all inbound `HTMLAttributes` props while applying utility classes for grid placement, column count, and container query context. ```tsx export function Cards(props: HTMLAttributes) { return (
{props.children}
); } ``` Sources: [packages/base-ui/src/components/card.tsx:5-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/card.tsx#L5-L11) > [!NOTE] > The `@container` class on `Cards` enables container query breakpoints so child cards can respond dynamically to the grid container width rather than the global viewport width. > Sources: [packages/base-ui/src/components/card.tsx:7](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/card.tsx#L7) ### Card Presentation and Anchor Link Integration Individual `Card` components switch their underlying HTML tag dynamically based on the presence of an `href` property. When `href` is supplied, the card uses `fumadocs-core/link` (`Link`); otherwise, it defaults to a standard `'div'` element. ```tsx export function Card({ icon, title, description, ...props }: CardProps) { const E = props.href ? Link : 'div'; ``` Sources: [packages/base-ui/src/components/card.tsx:22-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/card.tsx#L22-L24) ```tsx return ( ``` Sources: [packages/base-ui/src/components/card.tsx:25-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/card.tsx#L25-L34) | Property | Type | Description | | --- | --- | --- | | `icon` | `ReactNode` | Optional visual indicator rendered inside a styled container block above the title | | `title` | `ReactNode` | Primary card heading text rendered within an `h3` element | | `description` | `ReactNode` | Optional secondary description text rendered in muted styling | | `href` | `string` | Target URL for anchor navigation, transforming the container into a link component | | `external` | `boolean` | Flag indicating whether the link targets an external destination | Sources: [packages/base-ui/src/components/card.tsx:13-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/card.tsx#L13-L20) > [!WARNING] > Cards configured with an `href` automatically gain hover background styles (`hover:bg-fd-accent/80`) and span the full grid width when container queries drop below large viewports (`@max-lg:col-span-full`). > Sources: [packages/base-ui/src/components/card.tsx:30-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/card.tsx#L30-L31) ## Table of Contents Integration Primitives ### Anchor Providers and Scroll Observer Bindings The [Table of Contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) implementation centers on `TOCProvider`, which wraps `fumadocs-core/toc`'s `AnchorProvider` while concurrently exposing the parsed table of contents items array through a React context called `TOCContext`. Consumer components access these structured items via the `useTOCItems` hook, or consume active tracking primitives such as `useActiveAnchor`, `useActiveAnchors`, and `useItems` re-exported directly from the core primitive. ```tsx const TOCContext = createContext([]); export function useTOCItems(): Primitive.TOCItemType[] { return use(TOCContext); } export type TOCProviderProps = Primitive.AnchorProviderProps; export const { useActiveAnchor, useActiveAnchors, useItems } = Primitive; export function TOCProvider({ toc, children, ...props }: TOCProviderProps) { return ( {children} ); } ``` Sources: [packages/base-ui/src/components/toc/index.tsx:7-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/index.tsx#L7-L25) ### Scroll Areas and Element Ref Merging The `TOCScrollArea` component manages scrollable viewport containers for sidebars by establishing a local `viewRef` bound to a styled `div`. It uses `mergeRefs` to combine this internal view reference with any inbound `ref` prop from parent consumers, ensuring that scroll observers and DOM bindings attach correctly without overwriting user-provided ref objects. ```tsx export function TOCScrollArea({ ref, className, ...props }: ComponentProps<'div'>) { const viewRef = useRef(null); return (
{props.children}
); ``` Sources: [packages/base-ui/src/components/toc/index.tsx:27-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/index.tsx#L27-L41) | Function / Component | Return Type / Signature | Description | | --- | --- | --- | | `useTOCItems` | `Primitive.TOCItemType[]` | Consumes `TOCContext` to return the array of table of contents items | | `TOCProvider` | `(props: TOCProviderProps) => ReactNode` | Context provider wrapping `AnchorProvider` and `TOCContext` | | `TOCScrollArea` | `(props: ComponentProps<'div'>) => ReactNode` | Scrollable container linking `viewRef` to `Primitive.ScrollProvider` via `mergeRefs` | Sources: [packages/base-ui/src/components/toc/index.tsx:9-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/index.tsx#L9-L41) > [!NOTE] > `TOCScrollArea` hides native scrollbars using `[scrollbar-width:none]` and applies a vertical linear gradient mask to fade out overflowing heading items smoothly at the top and bottom edges. > Sources: [packages/base-ui/src/components/toc/index.tsx:34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/index.tsx#L34) ## Related - [Radix UI Primitives](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/radix-ui-primitives) - [Shared Layout Architecture](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture) --- ## Technical docs: Radix UI Primitives URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/radix-ui-primitives
Relevant source files The following files were used as context for generating this wiki page: - [packages/radix-ui/src/components/dialog/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search.tsx) - [packages/radix-ui/src/components/ui/scroll-area.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/scroll-area.tsx) - [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/api-docs/src/components/accordion.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/accordion.tsx) - [packages/radix-ui/src/layouts/flux/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx) - [packages/radix-ui/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts) - [packages/base-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/radix-ui/src/components/sidebar/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/base.tsx) - [packages/radix-ui/src/components/ui/popover.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/popover.tsx) - [packages/base-ui/src/components/dialog/search.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dialog/search.tsx) - [packages/radix-ui/src/components/toc/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/index.tsx) - [packages/radix-ui/src/layouts/flux/page/slots/toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/page/slots/toc.tsx) - [packages/api-docs/src/components/dialog.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/dialog.tsx) - [packages/api-docs/src/components/select.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/select.tsx) - [packages/base-ui/src/layouts/flux/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/index.tsx) - [packages/radix-ui/src/layouts/notebook/page/slots/toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/page/slots/toc.tsx) - [packages/radix-ui/src/components/toc/clerk.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/clerk.tsx) - [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx) - [packages/base-ui/src/layouts/flux/page/slots/toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/toc.tsx) - [packages/radix-ui/src/components/ui/accordion.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/accordion.tsx) - [packages/api-docs/src/components/schema/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx) - [packages/story/src/client/components/select.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/client/components/select.tsx) - [packages/base-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/slots/sidebar.tsx) - [packages/radix-ui/src/components/accordion.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/accordion.tsx) - [packages/radix-ui/src/components/ui/collapsible.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/collapsible.tsx) - [packages/base-ui/src/components/sidebar/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/base.tsx) - [packages/radix-ui/src/components/ui/navigation-menu.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/navigation-menu.tsx) - [packages/base-ui/src/components/ui/scroll-area.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/ui/scroll-area.tsx) - [packages/base-ui/src/components/toc/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/index.tsx) - [packages/base-ui/src/components/ui/popover.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/ui/popover.tsx)
## Overview Radix UI primitives form the accessible foundation of the documentation interface, wrapping underlying `@radix-ui/react-*` libraries to provide styled components for custom scrollable viewports, contextual floating popovers, and interactive collapsible or accordion panels. By encapsulating core behavior, these components manage complex UI states such as keyboard navigation, modal focus traps, and smooth CSS animations across search dialogs and navigation menus. Sources: [packages/radix-ui/src/components/dialog/search.tsx:268-296](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search.tsx#L268-L296), [packages/radix-ui/src/components/ui/scroll-area.tsx:1-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/scroll-area.tsx#L1-L17), [packages/radix-ui/src/components/ui/popover.tsx:1-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/popover.tsx#L1-L30), [packages/radix-ui/src/components/ui/accordion.tsx:1-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/accordion.tsx#L1-L17), [packages/radix-ui/src/components/ui/collapsible.tsx:1-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/collapsible.tsx#L1-L34), [packages/radix-ui/src/components/ui/navigation-menu.tsx:1-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/navigation-menu.tsx#L1-L69) ## Scroll area primitive and viewport scrolling ### Component API and DOM Structure The scroll area primitive wraps `@radix-ui/react-scroll-area` primitives to construct custom styled viewports and scrollbars across documentation sidebars and scrollable containers. The public exports consist of `ScrollArea`, `ScrollViewport`, and `ScrollBar`, along with helper abstractions such as `SidebarViewport` that structure vertical lists and page trees with fade masks and containment rules. ```typescript export function ScrollArea({ className, children, ...props }: React.ComponentPropsWithRef) { return ( {children} ); } ``` Sources: [packages/radix-ui/src/components/ui/scroll-area.tsx:5-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/scroll-area.tsx#L5-L17) The underlying component renders a root container with hidden overflow, automatically appending a corner piece and a vertical scrollbar instance. Inside this structure, `ScrollViewport` manages the inner scrolling container with full sizing, inherited border radius, and utility modifier classes. ```typescript export function ScrollViewport({ className, children, ...props }: React.ComponentPropsWithRef) { return ( {children} ); } ``` Sources: [packages/radix-ui/src/components/ui/scroll-area.tsx:19-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/scroll-area.tsx#L19-L29) The scrollbar sub-component supports both vertical and horizontal orientations, applying dynamic width or height constraints and fade-out transition animations via data states. ```typescript export function ScrollBar({ className, orientation = 'vertical', ...props }: React.ComponentPropsWithRef) { return ( ); } ``` Sources: [packages/radix-ui/src/components/ui/scroll-area.tsx:31-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/scroll-area.tsx#L31-L50) | Component Name | Radix Underlying Primitive | Default Class Names / Styles | Purpose | | --- | --- | --- | --- | | `ScrollArea` | `Primitive.Root` | `overflow-hidden` | Root wrapper providing scroll context, corner element, and default vertical scrollbar. | | `ScrollViewport` | `Primitive.Viewport` | `size-full rounded-[inherit]` | Scrollable content container matching parent boundaries and inheritance. | | `ScrollBar` | `Primitive.Scrollbar` | `flex select-none data-[state=hidden]:animate-fd-fade-out` | Track container handling orientation styles and thumb rendering. | | `ScrollAreaThumb` | `Primitive.ScrollAreaThumb` | `relative flex-1 rounded-full bg-fd-border` | Draggable thumb indicator inside the scrollbar track. | Sources: [packages/radix-ui/src/components/ui/scroll-area.tsx:1-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/scroll-area.tsx#L1-L50) > [!NOTE] > `ScrollViewport` applies `overscroll-contain` and linear gradient mask utilities when composed inside `SidebarViewport`, preventing scroll chaining to the main document body while fading overflowing edge contents. > Sources: [packages/radix-ui/src/components/sidebar/base.tsx:185-207](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/base.tsx#L185-L207) ### Execution Walkthrough and Component Composition ```mermaid sequenceDiagram participant Sidebar as Sidebar participant SidebarViewport as SidebarViewport participant ScrollArea as ScrollArea participant ScrollBar as ScrollBar Sidebar->>SidebarViewport: Renders menu items and page tree inside container SidebarViewport->>ScrollArea: Wraps children with ScrollArea->>ScrollBar: Appends and ScrollBar->>ScrollBar: Renders and ``` Sources: [packages/radix-ui/src/components/sidebar/base.tsx:185-207](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/base.tsx#L185-L207), [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx:64-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx#L64-L81) The rendering pipeline flows through structured sidebar components down to the primitive scrollbar. 1. `Sidebar` initiates composition by rendering banners, navigation links, and page trees. Sources: [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx:64-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx#L64-L81) 2. `SidebarViewport` receives the elements and injects them into `ScrollArea` with flex sizing. Sources: [packages/radix-ui/src/components/sidebar/base.tsx:185-207](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/base.tsx#L185-L207) 3. `ScrollArea` encapsulates the viewport with `Primitive.Root`, establishing overflow rules and default corner elements. Sources: [packages/radix-ui/src/components/ui/scroll-area.tsx:5-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/scroll-area.tsx#L5-L17) 4. `ScrollBar` configures orientation (`vertical` or `horizontal`) and populates the track with a styled `Primitive.ScrollAreaThumb`. Sources: [packages/radix-ui/src/components/ui/scroll-area.tsx:31-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/scroll-area.tsx#L31-L50) > [!WARNING] > Omitting `SidebarViewport` in custom sidebar layouts breaks vertical flex constraints (`min-h-0 flex-1`), causing long documentation trees to overflow outside visible viewport bounds. > Sources: [packages/radix-ui/src/components/sidebar/base.tsx:185-207](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/base.tsx#L185-L207) ## Popover primitive for contextual overlays ### Component API and Primitives The popover component architecture builds upon `@radix-ui/react-popover` primitives, supplying wrapper exports and customized content rendering. The exposed exports map directly to root, trigger, content, and close subcomponents. | Component Export | Underlying Radix Primitive | Default Configuration / Props | Purpose | | --- | --- | --- | --- | | `Popover` | `PopoverPrimitive.Root` | None | Root context provider managing open and closed state for the popover layer. | | `PopoverTrigger` | `PopoverPrimitive.Trigger` | None | Interactive toggle element that opens or closes the popover panel. | | `PopoverContent` | `PopoverPrimitive.Content` | `align = 'center'`, `sideOffset = 4`, `side = 'bottom'` | Portal-wrapped floating overlay panel containing customized positioning and styling. | | `PopoverClose` | `PopoverPrimitive.PopoverClose` | None | Action element that triggers closing of the active popover panel. | Sources: [packages/radix-ui/src/components/ui/popover.tsx:1-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/popover.tsx#L1-L32) ### Styling and Content Layout `PopoverContent` wraps its elements in `PopoverPrimitive.Portal` and `PopoverPrimitive.Content`, applying default alignment and offset settings. The styling uses utility classes for z-index stacking, layout constraints, backdrop filters, and open/closed animations. ```tsx className={cn( 'z-50 origin-(--radix-popover-content-transform-origin) overflow-y-auto max-h-(--radix-popover-content-available-height) min-w-[240px] max-w-[98vw] rounded-xl border bg-fd-popover/60 backdrop-blur-lg p-2 text-sm text-fd-popover-foreground shadow-lg focus-visible:outline-none data-[state=closed]:animate-fd-popover-out data-[state=open]:animate-fd-popover-in', className, )} {...props} ``` Sources: [packages/radix-ui/src/components/ui/popover.tsx:22-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/popover.tsx#L22-L26) > [!NOTE] > `PopoverContent` forces `side="bottom"` by default while inheriting custom `align` and `sideOffset` props, ensuring predictable dropdown placement beneath trigger buttons across documentation overlays. > Sources: [packages/radix-ui/src/components/ui/popover.tsx:10-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/popover.tsx#L10-L21) > [!WARNING] > Omitting `PopoverPrimitive.Portal` when wrapping custom popover structures causes content panels to clip within parent containers that have `overflow: hidden` or restricted bounding boxes. > Sources: [packages/radix-ui/src/components/ui/popover.tsx:17-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/popover.tsx#L17-L28) ## Collapsible triggers and expandable sections ### Primitive Exports and Component API The collapsible component architecture builds upon `@radix-ui/react-collapsible` primitives to drive accessible disclosure panels and folder hierarchies within documentation sidebars. The components exported by the wrapper module expose underlying Radix primitives while injecting custom animation classes and mounting states. | Component Export | Underlying Radix Primitive | Purpose | | --- | --- | --- | | `Collapsible` | `Primitive.Root` | Root container managing open and closed state for expandable sections. | | `CollapsibleTrigger` | `Primitive.CollapsibleTrigger` | Interactive control element toggling the expanded or collapsed state. | | `CollapsibleContent` | `Primitive.CollapsibleContent` | Animated container wrapper holding collapsible content sections. | Sources: [packages/radix-ui/src/components/ui/collapsible.tsx:7-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/collapsible.tsx#L7-L14) ### Animation and Mounting State `CollapsibleContent` manages client-side hydration and enter/exit animations by tracking a local `mounted` state via `useState` and `useEffect`. Once mounted, the component applies conditional keyframe animations (`animate-fd-collapsible-up` and `animate-fd-collapsible-down`) governed by the current `data-[state]` attribute. ```tsx export function CollapsibleContent({ children, ...props }: React.ComponentPropsWithRef) { const [mounted, setMounted] = useState(false); useEffect(() => { setMounted(true); }, []); return ( {children} ); } ``` Sources: [packages/radix-ui/src/components/ui/collapsible.tsx:11-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/collapsible.tsx#L11-L34) > [!NOTE] > `CollapsibleContent` delays application of collapse and expand animations until after initial client mount, preventing unwanted transition flashes during SSR hydration. > Sources: [packages/radix-ui/src/components/ui/collapsible.tsx:15-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/collapsible.tsx#L15-29) > [!WARNING] > Omitting `overflow-hidden` on `CollapsibleContent` causes inner child elements to overflow their bounds during the collapse and expansion height transition phases. > Sources: [packages/radix-ui/src/components/ui/collapsible.tsx:24-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/collapsible.tsx#L24-L26) ## Accordion wrappers and expandable panels ### Component Composition and Primitives The accordion architecture builds upon `@radix-ui/react-accordion` primitives to provide multi-item expandable panels with copy-link capabilities, keyboard navigation support, and hash-based anchor integration. The base primitives are re-exported and wrapped across specialized UI files to configure styling, layout, and interaction handlers. | Component Export | Underlying Primitive / Module | Purpose | | --- | --- | --- | | `Accordions` | `Primitive.Root` | Root container managing single or multiple selection modes and state synchronization. | | `Accordion` | `AccordionItem` wrapper | High-level wrapper combining an item, header, trigger, optional copy button, and content block. | | `AccordionItem` | `Primitive.Item` | Individual collapsible container section with scroll margin alignment. | | `AccordionHeader` | `Primitive.Header` | Header element managing layout, typography, and focus ring styling. | | `AccordionTrigger` | `Primitive.Trigger` | Interactive toggle control featuring a rotating chevron icon and accessible triggers. | | `AccordionContent` | `Primitive.Content` | Animated container holding collapsible panel contents with height transition classes. | Sources: [packages/radix-ui/src/components/ui/accordion.tsx:8-84](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/accordion.tsx#L8-L84), [packages/radix-ui/src/components/accordion.tsx:11-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/accordion.tsx#L11-L81) ### State Management and Hash Navigation `Accordions` initializes its state based on the configured `type` prop, defaulting to `'single'` with collapsible behavior enabled. On initial mount, an effect inspects `window.location.hash`, matches the element ID against the accordion tree, reads its `data-accordion-value` attribute, and automatically expands the corresponding panel. ```tsx export function Accordions({ type = 'single', ref, className, defaultValue, ...props }: ComponentProps) { const rootRef = useRef(null); const composedRef = mergeRefs(ref, rootRef); const [value, setValue] = useState(() => type === 'single' ? (defaultValue ?? '') : (defaultValue ?? []), ); useEffect(() => { const id = window.location.hash.substring(1); const element = rootRef.current; if (!element || id.length === 0) return; const selected = document.getElementById(id); if (!selected || !element.contains(selected)) return; const value = selected.getAttribute('data-accordion-value'); if (value) setValue((prev) => (typeof prev === 'string' ? value : [value, ...prev])); }, []); ``` Sources: [packages/radix-ui/src/components/accordion.tsx:18-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/accordion.tsx#L18-L41) > [!NOTE] > When `type` is set to `'single'`, `Accordions` forces `collapsible={true}` on the root primitive, allowing users to collapse all open panels by clicking the active trigger again. > Sources: [packages/radix-ui/src/components/accordion.tsx:45-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/accordion.tsx#L45-L50) > [!WARNING] > Omitting the `data-accordion-value` attribute on `AccordionHeader` prevents hash-based URL navigation from automatically expanding target panels on page load. > Sources: [packages/radix-ui/src/components/accordion.tsx:32-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/accordion.tsx#L32-L40) ## Search dialog modal structure ### Search Dialog Modal Structure and Primitives The search dialog modal architecture relies on `@radix-ui/react-dialog` primitives alongside specialized components to render accessible modal overlays, dialog content wrappers, animated list containers, and keyboard-navigational list items. | Component Export | Underlying Primitive / Module | Purpose | | --- | --- | --- | | `SearchDialogContent` | `DialogContent` wrapper | Renders the primary search container with centered positioning, width clamping, and entrance/exit animation hooks. | | `SearchDialogOverlay` | `DialogOverlay` wrapper | Provides a fixed backdrop layer featuring blur styling and open/closed fade animations. | | `SearchDialogList` | DOM `div` container | Manages active item indexes, keyboard arrow navigation, enter key selection, and dynamic height observers. | | `SearchDialogListItem` | DOM `button` element | Renders individual search result options, supporting custom markdown formatting, icons, and breadcrumb trails. | | `SearchDialogFooter` | DOM `div` container | Renders a styled container at the bottom of the dialog that hides itself automatically when empty. | Sources: [packages/radix-ui/src/components/dialog/search.tsx:264-417](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search.tsx#L264-L417), [packages/api-docs/src/components/dialog.tsx:3-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/dialog.tsx#L3-L17) ### Keyboard Navigation and Focus Management `SearchDialogList` registers a global keydown event listener through an effect event hook (`onKey`) to capture keyboard navigation events without re-subscribing on every render change. When `ArrowDown` or `ArrowUp` events fire, it computes the newly active item identifier based on the current index relative to the total items length, while `Enter` triggers the selection callback for the active item. ```tsx const onKey = useEffectEvent((e: KeyboardEvent) => { if (!items || e.isComposing) return; if (e.key === 'ArrowDown' || e.key == 'ArrowUp') { let idx = items.findIndex((item) => item.id === active); if (idx === -1) idx = 0; else if (e.key === 'ArrowDown') idx++; else idx--; setActive(items.at(idx % items.length)?.id ?? null); e.preventDefault(); } if (e.key === 'Enter') { const selected = items.find((item) => item.id === active); if (selected) onSelect(selected); e.preventDefault(); } }); ``` Sources: [packages/radix-ui/src/components/dialog/search.tsx:325-344](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search.tsx#L325-L344) > [!NOTE] > `SearchDialogContent` explicitly sets `aria-describedby={undefined}` and injects a hidden `DialogTitle` component containing translated search strings to satisfy accessibility requirements without disrupting visual layouts. > Sources: [packages/radix-ui/src/components/dialog/search.tsx:283-294](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search.tsx#L283-294) > [!WARNING] > Ignoring `e.isComposing` inside the keyboard handler can cause unintended list item cycling while users are actively typing composition characters with an Input Method Editor (IME). > Sources: [packages/radix-ui/src/components/dialog/search.tsx:326-326](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dialog/search.tsx#L326-L326) ## Select dropdowns and navigation menus ### Select Dropdown Component Architecture Form selection controls are built on top of `@radix-ui/react-select` primitives, offering robust keyboard navigation, dropdown portals, scrollable item viewports, and item indicators. The component architecture exposes granular parts including root, group, value, trigger, content, label, item, separator, and scroll buttons. | Component Export | Underlying Primitive | Purpose | | --- | --- | --- | | `Select` | `SelectPrimitive.Root` | Manages selection state and context for the entire dropdown control. | | `SelectGroup` | `SelectPrimitive.Group` | Groups related select items together semantically. | | `SelectValue` | `SelectPrimitive.Value` | Renders the currently selected option inside the trigger. | | `SelectTrigger` | `SelectPrimitive.Trigger` | Renders the interactive button wrapper with layout styling, focus rings, disabled states, and a trailing `ChevronDown` icon. | | `SelectContent` | `SelectPrimitive.Content` | Portals and wraps dropdown options in a popover container complete with viewport clipping and scroll buttons. | | `SelectItem` | `SelectPrimitive.Item` | Represents an individual selectable option, pairing item text with an option check indicator. | | `SelectSeparator` | `SelectPrimitive.Separator` | Renders a styled divider line between option groups or items. | | `SelectScrollUpButton` / `SelectScrollDownButton` | `SelectPrimitive.ScrollUpButton` / `ScrollDownButton` | Provides scroll navigation triggers equipped with chevron icons when content overflows the viewport height. | Sources: [packages/api-docs/src/components/select.tsx:6-124](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/select.tsx#L6-L124), [packages/story/src/client/components/select.tsx:7-139](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/story/src/client/components/select.tsx#L7-L139) ### Navigation Menu Integration and Motion Variants Responsive header navigation utilizes `@radix-ui/react-navigation-menu` primitives to deliver accessible dropdown panels and menu links. `NavigationMenuContent` applies absolute positioning, `fd-scroll-container` scroll handling, a maximum height constraint of `80svh`, and motion-driven data attributes for directional entry and exit animations (`data-[motion=from-end]`, `data-[motion=from-start]`, `data-[motion=to-end]`, `data-[motion=to-start]`). ```tsx export function NavigationMenuContent({ className, ...props }: React.ComponentPropsWithRef) { return ( ); } ``` Sources: [packages/radix-ui/src/components/ui/navigation-menu.tsx:37-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/navigation-menu.tsx#L37-L50) > [!NOTE] > `NavigationMenuViewport` wraps the Radix viewport primitive inside a centered flex container and binds height transition variables to `--radix-navigation-menu-viewport-height` alongside open and closed animation classes. > Sources: [packages/radix-ui/src/components/ui/navigation-menu.tsx:54-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/navigation-menu.tsx#L54-69) > [!WARNING] > Failing to wrap navigation menu content items in list-none item containers can introduce unexpected bullet point styling and layout distortions across different browser engines. > Sources: [packages/radix-ui/src/components/ui/navigation-menu.tsx:13-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/navigation-menu.tsx#L13-23) ## Related - [Base UI Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/base-ui-components) - [Shared Layout Architecture](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture) --- ## Technical docs: Shared Layout Architecture URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture
Relevant source files The following files were used as context for generating this wiki page: - [packages/radix-ui/src/layouts/notebook/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/page/index.tsx) - [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/base-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/base-ui/src/layouts/notebook/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/page/index.tsx) - [packages/base-ui/src/layouts/flux/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/index.tsx) - [packages/radix-ui/src/layouts/flux/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx) - [packages/base-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/slots/sidebar.tsx) - [packages/base-ui/src/layouts/flux/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/index.tsx) - [packages/radix-ui/src/layouts/flux/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/page/index.tsx) - [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx) - [packages/openapi/src/ui/operation/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/index.tsx) - [packages/radix-ui/src/layouts/notebook/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/client.tsx) - [packages/radix-ui/src/layouts/notebook/slots/header.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/header.tsx) - [packages/base-ui/src/layouts/notebook/slots/header.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/header.tsx) - [packages/base-ui/src/layouts/notebook/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/client.tsx) - [packages/base-ui/src/layouts/flux/page/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/container.tsx) - [packages/base-ui/src/layouts/home/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/home/index.tsx) - [packages/base-ui/src/layouts/flux/page/slots/footer.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/footer.tsx) - [packages/base-ui/src/components/sidebar/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/base.tsx) - [packages/radix-ui/src/layouts/notebook/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/container.tsx) - [packages/radix-ui/src/layouts/home/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/home/index.tsx) - [packages/radix-ui/src/components/sidebar/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/base.tsx) - [packages/radix-ui/src/layouts/notebook/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/index.tsx) - [packages/base-ui/src/layouts/notebook/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/container.tsx) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/base-ui/src/layouts/notebook/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/index.tsx) - [packages/base-ui/src/layouts/notebook/page/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/page/slots/container.tsx) - [packages/radix-ui/src/layouts/notebook/page/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/page/slots/container.tsx) - [packages/radix-ui/src/layouts/flux/page/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/page/slots/container.tsx) - [packages/cli/src/commands/customise.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/customise.ts)
## Overview Fumadocs provides a modular layout architecture built around customizable slot components, context providers, and responsive structural containers across package implementations like [Radix UI Primitives](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/radix-ui-primitives) and [Base UI Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/base-ui-components). This architecture decomposes complex documentation interfaces—such as the notebook and [Ui Layouts Layout](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/ui-layouts-layout) variants—into discrete, swappable parts including sidebars, headers, navigation panels, and page containers. By managing state centrally through React context hooks and supporting flexible slot overrides via the [Fumadocs CLI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/fumadocs-cli), developers can easily customize individual layout pieces or construct tailored documentation experiences from the ground up without modifying core logic. Sources: [packages/radix-ui/src/layouts/notebook/page/index.tsx:77-124](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/page/index.tsx#L77-L124), [packages/radix-ui/src/layouts/flux/index.tsx:33-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx#L33-L42), [packages/cli/src/commands/customise.ts:116-160](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/customise.ts#L116-L160) ## Layout Composition and Slot Contract ### Slot Interfaces and Component Bindings Layout composition across UI implementations relies on typed slot contracts that permit developers to override structural sub-components without breaking internal context bindings. In the Flux layout, the `DocsSlots` interface extends `BaseSlots` by defining custom component types for `container`, `tabDropdown`, and a structured `sidebar` object containing `provider`, `trigger`, `root`, and `useSidebar` hooks. ```typescript export interface DocsSlots extends BaseSlots { container: FC>; tabDropdown: FC; sidebar: { provider: FC; trigger: FC>; root: FC; useSidebar: () => { collapsed: boolean; open: boolean; setOpen: (v: boolean) => void }; }; } ``` Sources: [packages/radix-ui/src/layouts/flux/index.tsx:33-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx#L33-L42) Similarly, the Home layout defines `HomeSlots` extending `BaseSlots` with header and container slots, bound directly to React context via `createContext` and consumed through custom hooks like `useHomeLayout`. ```typescript export interface HomeSlots extends BaseSlots { header: FC>; container: FC>; } ``` Sources: [packages/radix-ui/src/layouts/home/index.tsx:22-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/home/index.tsx#L22-L25) | Layout Variant | Primary Container Slot | Header / Navigation Slot | Sidebar Slot Structure | | :--- | :--- | :--- | :--- | | **Flux Layout** | `slots.container` (`Container`) | `renderNavigationPanel` / `tabDropdown` | `slots.sidebar` (`provider`, `root`, `trigger`, `useSidebar`) | | **Home Layout** | `slots.container` (`Container`) | `slots.header` (`Header`) | Not applicable (nav enabled via `nav.enabled`) | | **Notebook Layout** | Resolved via `LayoutBody` / `containerProps` | `tabMode` (`sidebar` or `navbar`) | Sidebar options and tab resolution | Sources: [packages/radix-ui/src/layouts/flux/index.tsx:33-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx#L33-L41), [packages/radix-ui/src/layouts/home/index.tsx:22-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/home/index.tsx#L22-L25), [packages/radix-ui/src/layouts/notebook/index.tsx:13-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/index.tsx#L13-L21) > [!NOTE] > Layout contexts enforce strict tree containment; attempting to consume layout hooks outside their respective provider wrappers throws an explicit runtime error instructing developers to verify component nesting. Sources: [packages/radix-ui/src/layouts/flux/index.tsx:69-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx#L69-L76), [packages/radix-ui/src/layouts/home/index.tsx:34-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/home/index.tsx#L34-L39) ### Tab Resolution and Layout Options The Notebook and Flux layouts accept flexible tab configurations through the `tabs` property, which can be provided as an explicit array of `LayoutTab` objects, a `GetLayoutTabsOptions` configuration object, or set to `false` to disable tabs entirely. When passed as an object or omitted entirely, `getLayoutTabs` dynamically extracts tab structures from the page tree. ```typescript const resolvedTabs = useMemo(() => { if (Array.isArray(tabs)) { return tabs; } if (typeof tabs === 'object') { return getLayoutTabs(tree, tabs); } if (tabs !== false) { return getLayoutTabs(tree); } return []; }, [tabs, tree]); ``` Sources: [packages/radix-ui/src/layouts/notebook/index.tsx:38-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/index.tsx#L38-L49) > [!WARNING] > Defining `tabs` inside `sidebar` options is deprecated across notebook and flux layouts; configure layout-level `tabs` directly on the root layout props to prevent fallback warnings. Sources: [packages/radix-ui/src/layouts/flux/index.tsx:56-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx#L56-L59), [packages/radix-ui/src/layouts/notebook/index.tsx:23-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/index.tsx#L23-L28) ## Sidebar Primitive Architecture ### Provider Contexts and Mode Detection The sidebar architecture relies on provider contexts and reactive state hooks to manage visibility across viewports. `SidebarProvider` initializes state variables for `open` and `collapsed`, while determining the active display mode via media query evaluation. ```typescript type Mode = 'drawer' | 'full'; interface SidebarContext { open: boolean; setOpen: React.Dispatch>; collapsed: boolean; setCollapsed: React.Dispatch>; closeOnRedirect: RefObject; defaultOpenLevel: number; prefetch?: boolean; mode: Mode; } ``` Sources: [packages/base-ui/src/components/sidebar/base.tsx:32-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/base.tsx#L32-L64), [packages/radix-ui/src/components/sidebar/base.tsx:32-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/base.tsx#L32-L64) The active layout mode switches between `'drawer'` and `'full'` based on a screen width breakpoint of `768px`. | Mode Value | Viewport Condition | Behavior | | :--- | :--- | :--- | | `drawer` | `(width < 768px)` | Mobile overlay drawer controlled by `SidebarDrawerOverlay` and `SidebarDrawerContent` | | `full` | `(width >= 768px)` | Persistent desktop sidebar supporting collapsing and hover peek states | Sources: [packages/base-ui/src/components/sidebar/base.tsx:84-84](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/base.tsx#L84-L84), [packages/radix-ui/src/components/sidebar/base.tsx:84-84](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/base.tsx#L84-L84) > [!IMPORTANT] > Consuming `useSidebar` outside of a component wrapped in `SidebarProvider` throws an explicit runtime error requiring a parent layout context such as ``. Sources: [packages/base-ui/src/components/sidebar/base.tsx:114-122](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/base.tsx#L114-L122), [packages/radix-ui/src/components/sidebar/base.tsx:114-122](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/base.tsx#L114-L122) ### Viewport and Scroll Management Sidebar content is rendered within `SidebarViewport`, which nests a `ScrollArea` and `ScrollViewport` component combined with overflow containment and vertical fade gradient mask utility classes. ```typescript export function SidebarViewport({ className, ...props }: ScrollAreaProps) { return ( cn('min-h-0 flex-1', typeof className === 'function' ? className(s) : className) } {...props} > {props.children} ); } ``` Sources: [packages/base-ui/src/components/sidebar/base.tsx:222-235](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/base.tsx#L222-L235) > [!TIP] > `SidebarContent` monitors pointer entry and leave events to handle collapsible sidebar peek behavior on desktop, applying a `500ms` close delay when the mouse pointer leaves towards the page body rather than the viewport edge. Sources: [packages/base-ui/src/components/sidebar/base.tsx:170-180](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/base.tsx#L170-L180), [packages/radix-ui/src/components/sidebar/base.tsx:172-182](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/base.tsx#L172-L182) ## Navigation Sidebar Slot Wiring ### Notebook Layout Sidebar Assembly The notebook layout sidebar implementation structures its contents using base primitives, link item renderers, and page tree configurations. `SidebarProps` accepts optional page tree components, banner elements, footer nodes, and a desktop collapsing flag. Sources: [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx:50-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx#L50-L60) ```typescript export interface SidebarProps extends ComponentProps<'aside'> { components?: Partial; banner?: ReactNode | FC>; footer?: ReactNode | FC>; /** * Support collapsing the sidebar on desktop mode * * @defaultValue true */ collapsible?: boolean; } ``` Sources: [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx:50-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx#L50-L60) The `SidebarContent` component checks `useNotebookLayout()` to determine navigation mode settings, evaluating whether `navMode` is set to `'auto'` or alternative layout parameters to calculate sticky positioning offsets against top row heights. Sources: [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx:78-84](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx#L78-L84) > [!WARNING] > `SidebarContent` inside the notebook layout applies fixed positioning calculations that depend directly on `--fd-docs-row-1` or `--fd-docs-row-2` CSS variables; altering top row heights without matching these variable definitions breaks vertical alignment. Sources: [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx:92-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx#L92-L95) Mobile drawer toggles are governed by `SidebarDrawer`, which pairs `Base.SidebarDrawerOverlay` featuring backdrop blur effects with `Base.SidebarDrawerContent` styled as a fixed right- or left-hand panel constrained to `85%` width up to a maximum of `380px`. Sources: [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx:128-146](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx#L128-L146) ### Flux Layout Sidebar Integration The `Flux` layout implements its sidebar slot by pulling menu items from `useFluxLayout()`, filtering out icon-only entries, and passing remaining items through `SidebarLinkItem` alongside page tree renderers and viewport wrappers. Sources: [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx:64-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx#L64-L81) ```tsx export function Sidebar({ footer, banner, components, ...rest }: SidebarProps) { const { menuItems } = useFluxLayout(); return (
{banner}
{menuItems .filter((v) => v.type !== 'icon') .map((item, i, list) => ( ))} {footer}
); } ``` Sources: [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx:64-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx#L64-L81) Animated sidebar triggers switch between open and closed state icons using motion transitions: Sources: [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx:83-109](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx#L83-L109) | State | Icon Component | Animation Transition | | :--- | :--- | :--- | | Open | `XIcon` | `y: '100%'` initial, `duration: 0.2` | | Closed | `SidebarIcon` | `y: '100%'` initial, `duration: 0.2` | Sources: [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx:83-109](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx#L83-L109) > [!TIP] > The `Flux` sidebar modal registers a global `keydown` event listener via `useEffectEvent` that intercepts the `Escape` key when `open` is true, immediately dismissing the drawer and preventing default event propagation. Sources: [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx:116-127](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx#L116-L127) ## Header and Navbar Interactions ### Header Orchestration and Layout Tabs The `Header` component implements sticky header navigation under the grid area `#nd-subnav`, incorporating backdrop blur styling and dynamic background transparency based on `isNavTransparent` and sidebar open states. Navigation modes are evaluated through `nav.mode`, defaulting to `'auto'`, while sidebar collapse triggers adapt their visibility depending on whether collapse rules and top navigation modes are active. ```tsx
``` Sources: [packages/radix-ui/src/layouts/notebook/slots/header.tsx:36-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/header.tsx#L36-L45) Layout tabs are rendered via `LayoutHeaderTabs` when `tabMode` is set to `'navbar'` and `tabs.length` exceeds zero. Active tabs are resolved against the current route pathname using `isLayoutTabActive`, applying primary border styling to matching route entries while supporting unlisted route filtering. | Tab Property | Type / Behavior | Purpose | | :--- | :--- | :--- | | `title` | `ReactNode` | Display label inside the navbar tab anchor | | `url` | `string` | Target destination route for the layout tab | | `unlisted` | `boolean` | Hides the tab when inactive if set to true | | `props` | `ComponentProps<'a'>` | Additional custom attributes or className overrides | Sources: [packages/radix-ui/src/layouts/notebook/slots/header.tsx:161-196](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/header.tsx#L161-L196) > [!WARNING] > When `tabMode` is configured as `'navbar'`, the header height definition automatically scales from `--spacing(14)` up to `--spacing(24)` on large viewports (`lg:layout:[--fd-header-height:--spacing(24)]`), which directly impacts sticky offset calculations for content containers and sidebars. Sources: [packages/radix-ui/src/layouts/notebook/slots/header.tsx:40-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/header.tsx#L40-L42) ### Navbar Link Items and Device Pointer Controls Navbar link items are processed by filtering out icon-only entries for desktop display while mapping icon items to ghost button variants with muted text styling. Custom items bypass standard rendering to execute their embedded children directly, whereas menu items delegate to popover dropdown subcomponents. ```tsx
{navItems .filter((item) => item.type !== 'icon') .map((item, i) => ( ))}
{navItems .filter((item) => item.type === 'icon') .map((item, i) => ( {item.icon} ))} ``` Sources: [packages/radix-ui/src/layouts/notebook/slots/header.tsx:86-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/header.tsx#L86-L108) Mobile layouts hide desktop link items and search triggers in favor of compact search buttons (`slots.searchTrigger.sm`) and sidebar drawer toggles (`slots.sidebar.trigger`). On desktop viewports, language selection components (`slots.languageSelect.root`), theme switches (`slots.themeSwitch`), and collapsible sidebar triggers are aligned within an end-oriented flex container. > [!TIP] > Custom navigation components can completely bypass the default header layout by passing a custom React element directly to `nav.component`, triggering an immediate return statement before standard CSS classes or DOM nodes are evaluated. Sources: [packages/radix-ui/src/layouts/notebook/slots/header.tsx:33-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/header.tsx#L33-L33) ## Page Content and Container Structures ### Notebook Layout Container and Grid Template The `Container` component within the notebook layout establishes a CSS grid container (`#nd-notebook-layout`) that manages column and row dimensions for sidebars, headers, [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) popovers, and main article areas. It tracks sidebar collapse state via `slots.sidebar?.useSidebar?.()` and applies a temporary transition attribute `data-column-changed={isCollapseChanged}` whenever collapse toggles occur. ```tsx export function Container(props: ComponentProps<'div'>) { const { props: { nav }, slots, } = useNotebookLayout(); const pageCol = 'calc(var(--fd-layout-width,97rem) - var(--fd-sidebar-col) - var(--fd-toc-width))'; const { collapsed } = slots.sidebar?.useSidebar?.() ?? {}; const [previousCollapsed, setPreviousCollapsed] = useState(collapsed); const isCollapseChanged = previousCollapsed !== collapsed; // will only set data attribute for an instant useEffect(() => { if (isCollapseChanged) setPreviousCollapsed(collapsed); }, [collapsed, isCollapseChanged]); ``` Sources: [packages/radix-ui/src/layouts/notebook/slots/container.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/container.tsx#L7-L22), [packages/base-ui/src/layouts/notebook/slots/container.tsx:7-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/container.tsx#L7-L22) The grid layout geometry calculates column widths using `var(--fd-layout-width, 97rem)`, subtracting sidebar and TOC widths to resolve the central page column (`pageCol`). The template columns string enforces minimum content sizing alongside explicit widths for sidebars (`var(--fd-sidebar-col)`), article bounds, and table of contents columns (`var(--fd-toc-width)`). Depending on `nav.mode`, header positions swap between top grid areas and standard placement. | Grid Variable | Source Formula / Value | Purpose | | :--- | :--- | :--- | | `pageCol` | `calc(var(--fd-layout-width,97rem) - var(--fd-sidebar-col) - var(--fd-toc-width))` | Dynamic column span for the central document area | | `--fd-sidebar-col` | `collapsed ? '0px' : 'var(--fd-sidebar-width)'` | Active width allocated to the navigation sidebar column | | `--fd-docs-row-1` | `var(--fd-banner-height, 0px)` | Top vertical offset tracking optional banner height | | `--fd-docs-row-2` | `calc(var(--fd-docs-row-1) + var(--fd-header-height))` | Vertical row boundary tracking sticky header placement | | `--fd-docs-row-3` | `calc(var(--fd-docs-row-2) + var(--fd-toc-popover-height))` | Vertical boundary for TOC mobile popover regions | Sources: [packages/radix-ui/src/layouts/notebook/slots/container.tsx:12-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/container.tsx#L12-L42), [packages/base-ui/src/layouts/notebook/slots/container.tsx:12-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/container.tsx#L12-L42) > [!WARNING] > The container enables grid template transitions only when `data-column-changed` is active (`data-[column-changed=true]:transition-[grid-template-columns]`). Direct mutation of `collapsed` without updating `previousCollapsed` via the layout effect will skip the column width animation frame. Sources: [packages/radix-ui/src/layouts/notebook/slots/container.tsx:19-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/container.tsx#L19-L47), [packages/base-ui/src/layouts/notebook/slots/container.tsx:19-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/container.tsx#L19-L47) ### Article Wrapper and Slot Integration The page container slot (`
`) structures individual documentation pages across notebook and flux layouts, binding `[grid-area:main]` to position itself correctly inside the CSS grid. It reads `full` boolean state from `useDocsPage()` to govern maximum width constraints, applying standard typography padding and responsive gaps. ```tsx export function Container(props: ComponentProps<'article'>) { const { full } = useDocsPage(); return (
[!TIP] > Setting `full={true}` on `DocsPage` overrides standard child constraints, expanding maximum child widths up to `1285px` in notebook layouts and `1200px` in flux layouts while automatically disabling default desktop TOC rendering unless explicitly re-enabled. Sources: [packages/radix-ui/src/layouts/notebook/page/index.tsx:103-104](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/page/index.tsx#L103-L104), [packages/radix-ui/src/layouts/notebook/page/slots/container.tsx:15-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/page/slots/container.tsx#L15-L18), [packages/radix-ui/src/layouts/flux/page/slots/container.tsx:16-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/page/slots/container.tsx#L16-L17) ## Article Footers and Pagination Controls ### Footer Item Resolution and Active Route Matching The pagination footer system is driven by the `Footer` component, which accepts explicit pagination items or automatically discovers them using `useFooterItems()` and the current router `pathname`. When explicit `items` are not passed as props, the component finds the active index within the footer list by matching items against the current pathname using `isActive(item.url, pathname)`. ```tsx export function Footer({ items, children, className, ...props }: FooterProps) { const footerList = useFooterItems(); const pathname = usePathname(); const { previous, next } = useMemo(() => { if (items) return items; const idx = footerList.findIndex((item) => isActive(item.url, pathname)); if (idx === -1) return {}; return { previous: footerList[idx - 1], next: footerList[idx + 1], }; }, [footerList, items, pathname]); ``` Sources: [packages/base-ui/src/layouts/flux/page/slots/footer.tsx:25-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/footer.tsx#L25-L38) If no matching route is found (`idx === -1`), pagination objects are omitted entirely. Otherwise, `previous` maps to `footerList[idx - 1]` and `next` maps to `footerList[idx + 1]`. > [!WARNING] > If `isActive` fails to resolve the current pathname against any entry in `footerList`, both previous and next pagination slots remain undefined, rendering an empty container grid unless explicit items are provided via props. Sources: [packages/base-ui/src/layouts/flux/page/slots/footer.tsx:28-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/footer.tsx#L28-L38) ### Container Layout and Pagination Item Rendering The footer wrapper applies a container query (`@container`) and dynamically toggles CSS grid columns based on the presence of adjacent navigation links. When both previous and next items exist, it assigns `grid-cols-2`; otherwise, it falls back to a single column layout (`grid-cols-1`). ```tsx return ( <>
{previous && } {next && }
{children} ); } ``` Sources: [packages/base-ui/src/layouts/flux/page/slots/footer.tsx:40-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/footer.tsx#L40-L56) Individual footer links are rendered through the `FooterItem` subcomponent, which uses `useTranslations({ note: 'pagination' })` to supply localized fallback text (`Previous Page` or `Next Page`) when an item lacks an explicit description. The icon and text layout adapt based on the index: index `0` (previous) renders a left chevron (`ChevronLeft`) with standard alignment, while index `1` (next) reverses the flex-row direction, right-aligns the text, and renders a right chevron (`ChevronRight`). | Index | Direction | Icon | Default Description Fallback | CSS Alignment Classes | | :--- | :--- | :--- | :--- | :--- | | `0` (Previous) | Standard | `ChevronLeft` | `t('Previous Page')` | `flex flex-col gap-2` | | `1` (Next) | Reversed (`flex-row-reverse`) | `ChevronRight` | `t('Next Page')` | `flex flex-col gap-2 text-end` | Sources: [packages/base-ui/src/layouts/flux/page/slots/footer.tsx:58-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/footer.tsx#L58-L83) ## Related - [Ui Layouts Layout](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/ui-layouts-layout) --- ## Technical docs: Ui Layouts Layout URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/ui-layouts-layout
Relevant source files The following files were used as context for generating this wiki page: - [packages/radix-ui/src/layouts/flux/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx) - [packages/base-ui/src/layouts/flux/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/index.tsx) - [packages/base-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/base-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/slots/sidebar.tsx) - [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx) - [packages/base-ui/src/layouts/flux/page/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/container.tsx) - [packages/radix-ui/src/layouts/home/slots/header.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/home/slots/header.tsx) - [packages/radix-ui/src/layouts/flux/page/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/page/slots/container.tsx) - [packages/radix-ui/src/layouts/notebook/slots/header.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/header.tsx) - [packages/base-ui/src/layouts/flux/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/slots/container.tsx) - [packages/radix-ui/src/layouts/notebook/page/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/page/slots/container.tsx) - [packages/base-ui/src/layouts/notebook/slots/header.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/header.tsx) - [packages/radix-ui/src/layouts/flux/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/container.tsx) - [packages/radix-ui/src/layouts/notebook/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/container.tsx) - [packages/base-ui/src/layouts/notebook/page/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/page/slots/container.tsx) - [packages/base-ui/src/layouts/notebook/slots/container.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/container.tsx) - [packages/radix-ui/src/layouts/notebook/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/client.tsx) - [packages/base-ui/src/layouts/notebook/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/client.tsx) - [packages/radix-ui/src/layouts/flux/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/page/index.tsx) - [packages/radix-ui/src/components/sidebar/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/sidebar/base.tsx) - [packages/base-ui/src/components/sidebar/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/sidebar/base.tsx) - [packages/base-ui/src/layouts/flux/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/index.tsx) - [packages/radix-ui/src/layouts/home/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/home/index.tsx) - [packages/base-ui/src/layouts/home/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/home/index.tsx) - [packages/radix-ui/src/layouts/shared/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/index.tsx) - [packages/radix-ui/src/layouts/notebook/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/page/index.tsx) - [packages/radix-ui/css/preset-legacy.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/preset-legacy.css) - [packages/base-ui/src/layouts/shared/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/shared/index.tsx) - [packages/base-ui/src/layouts/notebook/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/page/index.tsx)
## Overview Fumadocs layout subsystems establish a robust architectural foundation for documentation and marketing applications, sharing common link-resolution mechanisms ([Shared Layout Architecture](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture)), tree context providers, and design tokens across different user interface frameworks. The system centers on composable slots, context providers, and dynamic link resolution via `resolveLinkItems` and `useLinkItems`, allowing developers to structure navigation items into designated menu buckets or inline header links. Sources: [packages/radix-ui/src/layouts/shared/index.tsx:33-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/index.tsx#L33-L52) The application packages provide three distinct layout variants—Flux, Home, and Notebook—that consume these shared primitives to organize sidebars, responsive navigation bars, and article viewports. Sources: [packages/radix-ui/src/layouts/shared/index.tsx:256-301](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/index.tsx#L256-L301) ```mermaid graph TD A["BaseLayoutProps"] --> B["resolveLinkItems"] B --> C["useLinkItems"] C --> D["LayoutContext"] D --> E["Flux Layout"] D --> F["Home Layout"] D --> G["Notebook Layout"] ``` Sources: [packages/radix-ui/src/layouts/shared/index.tsx:33-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/index.tsx#L33-L52), [packages/radix-ui/src/layouts/shared/index.tsx:256-301](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/shared/index.tsx#L256-L301) ## Flux Documentation Layout The Flux layout arranges a modern documentation experience featuring a responsive navigation panel, a customizable sidebar drawer system, and a centered article container. The layout entry point `DocsLayout` initializes a `LayoutContext` carrying resolved menu items, base layout properties, and slot mappings, wrapping its descendants in a `TreeContextProvider` and a sidebar provider. Sources: [packages/radix-ui/src/layouts/flux/index.tsx:84-196](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx#L84-L196) ```mermaid graph TD A["DocsLayout"] --> B["TreeContextProvider"] B --> C["sidebar.provider"] C --> D["slots.container"] D --> E["sidebar.root"] D --> F["children / DocsPage"] C --> G["NavigationPanel"] ``` Sources: [packages/radix-ui/src/layouts/flux/index.tsx:84-196](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx#L84-L196) Layout tabs are derived dynamically from the page tree using `getLayoutTabs`, or passed explicitly as an array of `LayoutTab` objects. The `NavigationPanel` renders header elements, language selectors, search triggers, theme switches, and icon links within a motion-animated header container. Sources: [packages/radix-ui/src/layouts/flux/index.tsx:44-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx#L44-L52) ```typescript export interface DocsLayoutProps extends BaseLayoutProps { tree: PageTree.Root; sidebar?: SidebarOptions; tabs?: LayoutTab[] | GetLayoutTabsOptions | false; slots?: Partial; renderNavigationPanel?: (props: NavigationPanelProps) => ReactNode; containerProps?: ComponentProps<'div'>; } ``` Sources: [packages/radix-ui/src/layouts/flux/index.tsx:44-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/index.tsx#L44-L52) The Flux sidebar component uses `SidebarContent` with `RemoveScroll` to manage keyboard escape event listeners, backdrop blurs, and animated entrance/exit states when toggled open. Sources: [packages/radix-ui/src/layouts/flux/slots/sidebar.tsx:111-186](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/slots/sidebar.tsx#L111-L186) ## Home Layout The Home layout provides a marketing or landing page structure via `HomeLayout`, rendering a top navigation header and a main content container. It resolves navigation links through `useLinkItems` and makes them available via `useHomeLayout`. Sources: [packages/radix-ui/src/layouts/home/index.tsx:47-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/home/index.tsx#L47-L81) ```mermaid graph TD A["HomeLayout"] --> B["HomeSlots Context"] B --> C["slots.container"] C --> D["slots.header"] C --> E["children"] ``` Sources: [packages/radix-ui/src/layouts/home/index.tsx:47-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/home/index.tsx#L47-L81) The header slot utilizes `HeaderNavigationMenu` to support transparent mode variants (`always`, `top`, or `none`). When `transparentMode` is set to `top`, it monitors scroll position via `useIsScrollTop` to toggle background opacities dynamically. Sources: [packages/radix-ui/src/layouts/home/slots/header.tsx:144-173](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/home/slots/header.tsx#L144-L173) ```typescript export interface HomeLayoutProps extends BaseLayoutProps, ComponentProps<'main'> { nav?: Nav; slots?: Partial; } ``` Sources: [packages/radix-ui/src/layouts/home/index.tsx:10-13](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/home/index.tsx#L10-L13) Mobile viewports automatically switch to a collapsible navigation menu dropdown triggered by a chevron button, which renders both primary and secondary link items alongside language selectors and theme switches. Sources: [packages/radix-ui/src/layouts/home/slots/header.tsx:89-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/home/slots/header.tsx#L89-L133) ## Notebook Layout The Notebook layout implements a multi-column CSS grid architecture containing a sidebar, a sticky subheader, a [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents), and a central article viewport. The grid columns are dynamically computed based on sidebar collapse states and layout width variables. Sources: [packages/radix-ui/src/layouts/notebook/client.tsx:67-124](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/client.tsx#L67-L124) ```mermaid graph TD A["LayoutBody"] --> B["TreeContextProvider"] B --> C["SidebarProvider"] C --> D["Container (CSS Grid)"] D --> E["Header / Subnav"] D --> F["Sidebar Root"] D --> G["Page Children"] ``` Sources: [packages/radix-ui/src/layouts/notebook/client.tsx:67-124](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/client.tsx#L67-L124) The header execution flow for `Header` coordinates touch detection, responsive menus, and navigation items. When evaluating `Header`, it delegates item rendering to `NavbarLinkItem` and `NavbarLinkItemMenu`. Sources: [packages/base-ui/src/layouts/notebook/slots/header.tsx:21-159](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/header.tsx#L21-L159), [packages/base-ui/src/layouts/notebook/slots/header.tsx:199-301](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/header.tsx#L199-L301) ```mermaid sequenceDiagram participant Header as Header participant Item as NavbarLinkItem participant Menu as NavbarLinkItemMenu Header->>Item: Render navItems alt item.type === 'menu' Item->>Menu: Delegate item rendering Menu->>Menu: Handle pointer events & popover state else item.type === 'main' or standard link Item->>Item: Render LinkItem component end ``` Sources: [packages/base-ui/src/layouts/notebook/slots/header.tsx:21-159](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/header.tsx#L21-L159), [packages/base-ui/src/layouts/notebook/slots/header.tsx:199-301](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/header.tsx#L199-L301) The grid template adapts depending on whether `nav.mode` is set to `top` or `auto`: Sources: [packages/radix-ui/src/layouts/notebook/slots/container.tsx:31-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/container.tsx#L31-L38) ```typescript gridTemplate: nav?.mode === 'top' ? `". header header header ." "sidebar sidebar toc-popover toc-popover ." "sidebar sidebar main toc ." 1fr / minmax(min-content, 1fr) var(--fd-sidebar-col) minmax(0, ${pageCol}) var(--fd-toc-width) minmax(min-content, 1fr)` : `"sidebar sidebar header header ." "sidebar sidebar toc-popover toc-popover ." "sidebar sidebar main toc ." 1fr / minmax(min-content, 1fr) var(--fd-sidebar-col) minmax(0, ${pageCol}) var(--fd-toc-width) minmax(min-content, 1fr)` ``` Sources: [packages/radix-ui/src/layouts/notebook/slots/container.tsx:31-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/container.tsx#L31-L38) > [!NOTE] > During sidebar collapse state transitions, `Container` sets `data-column-changed=true` for an instant to trigger smooth CSS grid template column transitions. Sources: [packages/radix-ui/src/layouts/notebook/slots/container.tsx:18-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/container.tsx#L18-L21) ## Related - [Shared Layout Architecture](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture) --- ## Technical docs: Table of Contents URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents
Relevant source files The following files were used as context for generating this wiki page: - [packages/base-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/core/src/toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx) - [packages/base-ui/src/components/toc/clerk.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/clerk.tsx) - [packages/base-ui/src/components/toc/default.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/default.tsx) - [packages/radix-ui/src/components/toc/default.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/default.tsx) - [packages/base-ui/src/layouts/flux/page/slots/toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/toc.tsx) - [packages/radix-ui/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts) - [packages/radix-ui/src/components/toc/clerk.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/clerk.tsx) - [packages/base-ui/src/layouts/notebook/page/slots/toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/page/slots/toc.tsx) - [packages/core/src/mdx-plugins/rehype-toc.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts) - [packages/radix-ui/src/layouts/flux/page/slots/toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/page/slots/toc.tsx) - [packages/base-ui/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts) - [packages/radix-ui/src/layouts/notebook/page/slots/toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/page/slots/toc.tsx) - [packages/api-docs/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/tsdown.config.ts) - [packages/base-ui/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/tsdown.config.ts) - [packages/radix-ui/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/tsdown.config.ts) - [packages/base-ui/src/components/toc/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/index.tsx) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/base-ui/src/layouts/flux/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/slots/sidebar.tsx) - [packages/radix-ui/src/components/toc/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/index.tsx) - [packages/core/src/mdx-plugins/remark-structure.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts) - [packages/core/src/mdx-plugins/remark-heading.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts) - [packages/basehub/src/toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx) - [packages/radix-ui/src/components/inline-toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/inline-toc.tsx) - [packages/base-ui/src/components/inline-toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/inline-toc.tsx) - [packages/core/src/content/toc.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/toc.ts) - [packages/openapi/src/utils/pages/to-static-data.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-static-data.ts) - [packages/sanity/src/client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/client.ts) - [packages/base-ui/src/contexts/tree.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/contexts/tree.tsx)
## Overview Fumadocs provides a table of contents (TOC) architecture that extracts heading hierarchies from Markdown ASTs, headless CMS content, and OpenAPI sources, and renders interactive, synchronized navigation lists across documentation layouts. The system handles active heading observation via `IntersectionObserver`, drives scroll-into-view behavior, and powers dynamic SVG thumb indicators and collapsible inline elements. Sources: [packages/core/src/toc.tsx:1-237](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L1-L237), [packages/core/src/mdx-plugins/remark-heading.ts:1-99](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-heading.ts#L1-L99), [packages/base-ui/src/components/toc/default.tsx:30-143](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/default.tsx#L30-L143) ## TOC extraction and data structures ### Data Models and Core Types The foundational data model for table of contents entries in Fumadocs is defined by the `TOCItemType` interface, which represents an individual heading or navigation link. A complete table of contents collection is typed as `TableOfContents`, representing an array of these items. ```typescript export interface TOCItemType { title: ReactNode; url: string; depth: number; /** [remark-steps] the step number */ _step?: number; } export type TableOfContents = TOCItemType[]; ``` Sources: [packages/core/src/toc.tsx:18-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L18-L26) Additionally, runtime tracking wraps these static items into `TOCItemInfo` objects to manage intersection state, timestamps, and viewport fallbacks. | Property | Type | Default | Purpose | | :--- | :--- | :--- | :--- | | `id` | `string` | required | Unique DOM identifier extracted from the URL anchor | | `active` | `boolean` | required | Indicates whether the heading is currently active in the viewport | | `t` | `number` | required | Timestamp of the last time the item state was updated | | `fallback` | `boolean` | required | Flags items that are currently active but not actively intersecting in the viewport | | `original` | `TOCItemType` | required | Reference to the underlying static TOC item definition | Sources: [packages/core/src/toc.tsx:28-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L28-L36) > [!NOTE] > The `_step` optional property on `TOCItemType` allows remark-steps plugins to attach sequential numbering directly to TOC nodes, enabling specialized step-based navigation renderers. Sources: [packages/core/src/toc.tsx:18-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L18-L24) ### Markdown AST Extraction Pipeline Table of contents extraction from Markdown and MDX documents is driven by the remark ecosystem via `getTableOfContents`. The extraction function accepts content and optional remark plugins, processing them synchronously or asynchronously while applying `remarkHeading` to harvest heading nodes from the syntax tree. ```typescript export function getTableOfContents( content: Compatible, remarkPlugins?: PluggableList, ): TOCItemType[] | Promise { if (remarkPlugins) { return remark() .use(remarkPlugins) .use(remarkHeading) .process(content) .then((result) => { if ('toc' in result.data) return result.data.toc as TOCItemType[]; return []; }); } const result = remark().use(remarkHeading).processSync(content); if ('toc' in result.data) return result.data.toc as TOCItemType[]; return []; } ``` Sources: [packages/core/src/content/toc.ts:25-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/toc.ts#L25-L46) > [!WARNING] > If the processed VFile `result.data` object does not contain a `toc` property populated by `remarkHeading`, `getTableOfContents` silently returns an empty array instead of throwing an error. Sources: [packages/core/src/content/toc.ts:34-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/toc.ts#L34-L45) ### CMS and OpenAPI Source Adapters Fumadocs also normalizes table of contents data structures from external sources such as Sanity CMS and OpenAPI specifications. The `renderToc` utility transforms Portable Text blocks into standard `TOCItemType` entries by mapping block levels, generating anchor keys, and rendering block titles. ```typescript export function renderToc(opts: { toc: PortableTextBlock[]; render: (body: PortableTextBlock) => ReactNode; }): TOCItemType[] { const { render, toc } = opts; return toc.map( (item): TOCItemType => ({ depth: Number(item.level ?? 0), title: render({ ...item, style: undefined }), url: `#${item._key}`, }), ); } ``` Sources: [packages/sanity/src/client.ts:5-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/client.ts#L5-L18) For API documentation generated from OpenAPI schemas, `toStaticData` iterates through page operations and webhooks, building structured headings and table of contents entries using GitHub sluggers. ```typescript export function toStaticData( page: GeneratedPageProps, doc: Document, ): { toc: TOCItemType[]; structuredData: StructuredData; } { const slugger = new Slugger(); const toc: TOCItemType[] = []; const structuredData: StructuredData = { headings: [], contents: [] }; function pathItem(item: OperationObject, defaultTitle: string) { if (page.showTitle && item.operationId) { const title = item.summary || (item.operationId ? idToTitle(item.operationId) : defaultTitle); const id = slugger.slug(title); toc.push({ depth: 2, title, url: `#${id}`, }); structuredData.headings.push({ content: title, id, }); } ``` Sources: [packages/openapi/src/utils/pages/to-static-data.ts:9-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-static-data.ts#L9-L35) ## Active heading observation primitives ### Active Anchor Hooks and Selectors Core observer mechanisms, scroll listeners, and active anchor tracking hooks manage the runtime intersection of document headings. The `Observer` class maintains the collection of items, observer instances, and change listeners, while React hooks wrap state subscriptions and auto-scroll behaviors. ```mermaid sequenceDiagram participant TOCItem as TOCItem participant useTOCListener as useTOCListener participant useObserver as useObserver participant Observer as Observer TOCItem->>TOCItem: useTOCListener TOCItem->>useTOCListener: useTOCListener useTOCListener->>useObserver: useObserver useObserver->>Observer: observer.listen(callback) ``` Sources: [packages/core/src/toc.tsx:122-130](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L122-L130), [packages/core/src/toc.tsx:140-144](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L140-L144), [packages/core/src/toc.tsx:162-170](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L162-L170) The observation lifecycle begins within `AnchorProvider`, which instantiates a single `Observer` via `useMemo` and configures its single-item mode and intersection threshold. ```typescript export function AnchorProvider({ toc, single = false, children }: AnchorProviderProps) { const observer = useMemo(() => new Observer(), []); observer.single = single; useEffect(() => { observer.setItems(toc); }, [observer, toc]); useEffect(() => { observer.watch({ threshold: 0.9, }); return () => observer.unwatch(); }, [observer]); return {children}; } ``` Sources: [packages/core/src/toc.tsx:66-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L66-L83) > [!CAUTION] > Attempting to use any table of contents hook or `TOCItem` outside of an active `` component will trigger an invariant error thrown by `useObserver()`. Sources: [packages/core/src/toc.tsx:140-144](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L140-L144) The `useTOCSelector` primitive subscribes components to state updates emitted by the `Observer` instance, running selector functions and memoizing equality checks via `isEqualShallow`. Specific hooks like `useActiveAnchor`, `useActiveAnchors`, and `useItems` derive targeted state views from the primary item collection. | Hook Name | Return Type | Selection Logic | | :--- | :--- | :--- | | `useActiveAnchor()` | `string \| undefined` | Returns the ID of the most recently updated active heading (`item.t > out.t`) | | `useActiveAnchors()` | `string[]` | Collects an array of all IDs where `item.active` evaluates to true | | `useItems()` | `TOCItemInfo[]` | Returns the complete array of `TOCItemInfo` tracking items | Sources: [packages/core/src/toc.tsx:172-219](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L172-L219) > [!TIP] > When implementing custom sidebar highlighting or custom rendering widgets, prefer `useTOCSelector` with a custom equality function to prevent unnecessary React re-renders on every scroll tick. Sources: [packages/core/src/toc.tsx:172-184](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L172-L184) ## TOC component hierarchy and providers ### Core and UI Provider Layer The architecture divides table of contents management into core calculation logic in `fumadocs-core/toc` and framework-specific wrapper components in `fumadocs-ui/base-ui` and `fumadocs-ui/radix-ui`. Both UI packages re-export identical provider structures and scroll area primitives that bridge `Primitive.AnchorProvider` with React context propagation for static item arrays. ```tsx const TOCContext = createContext([]); export function useTOCItems(): Primitive.TOCItemType[] { return use(TOCContext); } export type TOCProviderProps = Primitive.AnchorProviderProps; export const { useActiveAnchor, useActiveAnchors, useItems } = Primitive; export function TOCProvider({ toc, children, ...props }: TOCProviderProps) { return ( {children} ); } ``` Sources: [packages/base-ui/src/components/toc/index.tsx:7-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/index.tsx#L7-L25), [packages/radix-ui/src/components/toc/index.tsx:7-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/index.tsx#L7-L25) The `TOCProvider` component accepts `toc` items and optional properties such as `single`, injecting both a local `TOCContext` containing raw items and a `Primitive.AnchorProvider` context down the React component tree. ```typescript export function TOCProvider({ toc, children, ...props }: TOCProviderProps) { return ( {children} ); } ``` Sources: [packages/base-ui/src/components/toc/index.tsx:17-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/index.tsx#L17-L25), [packages/radix-ui/src/components/toc/index.tsx:17-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/index.tsx#L17-L25) > [!NOTE] > `useTOCItems()` consumes `TOCContext` to retrieve the static `TOCItemType[]` array directly, whereas core hooks like `useItems()` derive state from the active `Observer` instance. Sources: [packages/base-ui/src/components/toc/index.tsx:7-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/index.tsx#L7-L11), [packages/radix-ui/src/components/toc/index.tsx:7-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/index.tsx#L7-L11) ### Scroll Areas and Context Binding The layout incorporates `TOCScrollArea` to manage container-based auto-scrolling when active headings change. It establishes a `viewRef` reference on the scrollable container div and forwards it to `Primitive.ScrollProvider`. ```tsx export function TOCScrollArea({ ref, className, ...props }: ComponentProps<'div'>) { const viewRef = useRef(null); return (
{props.children}
); ``` Sources: [packages/base-ui/src/components/toc/index.tsx:27-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/index.tsx#L27-L41), [packages/radix-ui/src/components/toc/index.tsx:27-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/index.tsx#L27-L41) The table below lists the components, providers, and shared hooks exported across the core and UI packages: | Identifier | Source Package | Role & Description | | :--- | :--- | :--- | | `AnchorProvider` | `fumadocs-core/toc` | Initializes the `Observer` class, manages single-item selection modes, and supplies `ObserverContext` | | `ScrollProvider` | `fumadocs-core/toc` | Supplies `ScrollContext` with the container reference for auto-scrolling active items into view | | `TOCProvider` | `fumadocs-ui/*` | Combines `TOCContext` array storage with `Primitive.AnchorProvider` wrapping | | `TOCScrollArea` | `fumadocs-ui/*` | Renders the styled container (`overflow-auto`, `[scrollbar-width:none]`, mask gradients) hosting `ScrollProvider` | | `useTOCItems()` | `fumadocs-ui/*` | Accesses the static array of `TOCItemType` objects from `TOCContext` | Sources: [packages/core/src/toc.tsx:61-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L61-L83), [packages/base-ui/src/components/toc/index.tsx:7-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/index.tsx#L7-L41), [packages/radix-ui/src/components/toc/index.tsx:7-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/index.tsx#L7-L41) > [!WARNING] > `TOCScrollArea` applies `[scrollbar-width:none]` and vertical CSS mask gradients (`mask-[linear-gradient(to_bottom,transparent,white_16px,white_calc(100%-16px),transparent)]`); overriding overflow properties without preserving the container reference will break `scrollIntoView` auto-centering. Sources: [packages/base-ui/src/components/toc/index.tsx:31-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/index.tsx#L31-L40), [packages/radix-ui/src/components/toc/index.tsx:31-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/index.tsx#L31-L40) ## Indicator thumb tracking and rendering ### SVG Layout Calculations and Path Generation ```mermaid sequenceDiagram participant TOCItems as TOCItems participant ThumbTrack as ThumbTrack participant useTOC as useTOC participant useObserver as useObserver TOCItems->>ThumbTrack: compute SVG and render component ThumbTrack->>useTOC: call tocInfo.get() useTOC->>useObserver: read observer.items ``` Sources: [packages/base-ui/src/components/toc/clerk.tsx:28-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/clerk.tsx#L28-L126), [packages/base-ui/src/components/toc/clerk.tsx:137-185](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/clerk.tsx#L137-L185), [packages/core/src/toc.tsx:147-160](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L147-L160), [packages/core/src/toc.tsx:140-144](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/toc.tsx#L140-L144) The table of contents indicator renders dynamic SVG track lines alongside active item thumbs using layout measurements derived from container DOM queries. Within `TOCItems`, an `onPrint` callback measures each item element via `container.querySelector('a[href="' + item.url + '"]')` and computes layout coordinates. ```tsx for (let i = 0; i < items.length; i++) { const item = items[i]; const element: HTMLElement | null = container.querySelector(`a[href="${item.url}"]`); if (!element) continue; const styles = getComputedStyle(element); const x = getLineOffset(item.depth) + 0.5; const top = element.offsetTop + parseFloat(styles.paddingTop); const bottom = element.offsetTop + element.clientHeight - parseFloat(styles.paddingBottom); w = Math.max(x + 8, w); h = Math.max(h, bottom); if (i === 0) { d += ` M${x} ${top} L${x} ${bottom}`; } else { const [, upperBottom, upperX] = i > 0 ? positions[i - 1] : [0, 0, 0]; d += ` C ${upperX} ${top - 4} ${x} ${upperBottom + 4} ${x} ${top} L${x} ${bottom}`; } if (item._step !== undefined) { output.push( {item._step} , ); } positions.push([top, bottom, x]); } ``` Sources: [packages/base-ui/src/components/toc/default.tsx:48-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/default.tsx#L48-L88), [packages/radix-ui/src/components/toc/default.tsx:48-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/default.tsx#L48-L88) > [!NOTE] > The default variant path uses cubic bezier commands to smoothly bridge line segments across varying heading depths, whereas the Clerk variant employs straight line segments. Sources: [packages/base-ui/src/components/toc/default.tsx:63-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/default.tsx#L63-L67), [packages/base-ui/src/components/toc/clerk.tsx:61-65](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/clerk.tsx#L61-L65), [packages/radix-ui/src/components/toc/default.tsx:63-67](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/default.tsx#L63-L67), [packages/radix-ui/src/components/toc/clerk.tsx:61-65](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/clerk.tsx#L61-L65) ### Thumb Track Clip Paths and Variants The `ThumbTrack` subcomponent reads active states via `Primitive.useTOC()` and `Primitive.useTOCListener()`, dynamically updating CSS custom properties `--track-top` and `--track-bottom` on the container element. ```tsx function ThumbTrack({ computed }: { computed: ComputedSVG }) { const ref = useRef(null); const tocInfo = Primitive.useTOC(); function calculate(items: Primitive.TOCItemInfo[]) { const out: Record = {}; const startIdx = items.findIndex((item) => item.active); if (startIdx === -1) return out; const endIdx = items.findLastIndex((item) => item.active); out['--track-top'] = `${computed.positions[startIdx][0]}px`; out['--track-bottom'] = `${computed.positions[endIdx][1]}px`; return out; } Primitive.useTOCListener((items) => { const element = ref.current; if (!element) return; for (const [k, v] of Object.entries(calculate(items))) { element.style.setProperty(k, v); } }); return (
{computed.content}
); } ``` Sources: [packages/base-ui/src/components/toc/clerk.tsx:137-185](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/clerk.tsx#L137-L185), [packages/radix-ui/src/components/toc/clerk.tsx:137-185](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/clerk.tsx#L137-L185) | Variant Package / File | Computed SVG Feature | Path Command / Styling Method | Step Numbering Support | | :--- | :--- | :--- | :--- | | `packages/base-ui/src/components/toc/default.tsx` | Cubic path smoothing with optional `thumbBox` lengths | Cubic bezier path calculation | Yes (`item._step !== undefined`) | | `packages/base-ui/src/components/toc/clerk.tsx` | Straight line segment transitions with polygon clipping | Straight line segment path calculation | Yes (`item._step !== undefined`) | | `packages/radix-ui/src/components/toc/default.tsx` | Cubic path smoothing with optional `thumbBox` lengths | Cubic bezier path calculation | Yes (`item._step !== undefined`) | | `packages/radix-ui/src/components/toc/clerk.tsx` | Straight line segment transitions with polygon clipping | Straight line segment path calculation | Yes (`item._step !== undefined`) | Sources: [packages/base-ui/src/components/toc/default.tsx:63-85](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/default.tsx#L63-L85), [packages/base-ui/src/components/toc/clerk.tsx:61-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/clerk.tsx#L61-L83), [packages/radix-ui/src/components/toc/default.tsx:63-85](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/default.tsx#L63-L85), [packages/radix-ui/src/components/toc/clerk.tsx:61-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/clerk.tsx#L61-L83) > [!CAUTION] > When `thumbBox` is enabled in the default variant, the component calculates path lengths using `path.getTotalLength()` and `path.getPointAtLength(l)`. If container heights resize to zero or headings have no corresponding DOM elements, `onPrint` returns early and sets the SVG state to `null`, disabling the indicator thumb entirely. Sources: [packages/base-ui/src/components/toc/default.tsx:35-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/default.tsx#L35-L41), [packages/base-ui/src/components/toc/default.tsx:96-109](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/toc/default.tsx#L96-L109), [packages/radix-ui/src/components/toc/default.tsx:35-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/default.tsx#L35-L41), [packages/radix-ui/src/components/toc/default.tsx:96-109](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/toc/default.tsx#L96-L109) ## Inline collapsible TOC components ### Component Implementation and Styling The inline table of contents presentation is implemented through framework-specific UI components across packages, rendered as client components utilizing `@fuma-translate/react` translations and Lucide icons. ```tsx 'use client'; import { ChevronDown } from 'lucide-react'; import type { TOCItemType } from 'fumadocs-core/toc'; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from './ui/collapsible'; import type { ComponentProps } from 'react'; import { cn } from '@/utils/cn'; import { useTranslations } from '@fuma-translate/react'; export interface InlineTocProps extends ComponentProps { items: TOCItemType[]; } ``` Sources: [packages/radix-ui/src/components/inline-toc.tsx:1-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/inline-toc.tsx#L1-L12), [packages/base-ui/src/components/inline-toc.tsx:1-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/inline-toc.tsx#L1-L12) The `InlineTOC` component accepts an array of `TOCItemType` objects alongside standard component properties, wrapping content inside collapsible primitives with a customizable header trigger. ```tsx export function InlineTOC({ items, ...props }: InlineTocProps) { const t = useTranslations({ note: 'inline table of contents' }); return ( {props.children ?? t('Table of Contents')}
); ``` Sources: [packages/radix-ui/src/components/inline-toc.tsx:14-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/inline-toc.tsx#L14-L46), [packages/base-ui/src/components/inline-toc.tsx:14-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/inline-toc.tsx#L14-L48) | Package Path | Class Name Handling | Trigger Chevron Animation | Translation Key | | :--- | :--- | :--- | :--- | | `packages/radix-ui/src/components/inline-toc.tsx` | `cn('not-prose rounded-lg border bg-fd-card text-fd-card-foreground', props.className)` | `group-data-[state=open]:rotate-180` | `Table of Contents` | | `packages/base-ui/src/components/inline-toc.tsx` | `cn(..., typeof className === 'function' ? className(s) : className)` | `group-data-open:rotate-180` | `Table of Contents` | Sources: [packages/radix-ui/src/components/inline-toc.tsx:20-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/inline-toc.tsx#L20-L27), [packages/base-ui/src/components/inline-toc.tsx:20-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/inline-toc.tsx#L20-L29) > [!NOTE] > Indentation for nested TOC items inside `InlineTOC` is calculated dynamically via inline styles using `12 * Math.max(item.depth - 1, 0)` for `paddingInlineStart`, coupled with a vertical border border-s on each anchor element. Sources: [packages/radix-ui/src/components/inline-toc.tsx:31-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/inline-toc.tsx#L31-L41), [packages/base-ui/src/components/inline-toc.tsx:33-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/inline-toc.tsx#L33-L43) ## Layout slot integration and popovers ### Flux and Notebook TOC Slot Implementation Documentation layouts integrate table of contents elements into specialized layout slots and collapsible popovers. In the Flux layout architecture, `TOC` mounts via a React portal targeting the DOM element with the ID `#flux-layout-slot`, wrapping its contents within `PageTOCPopover` and `PageTOCPopoverPhysical` to manage click-outside events and expansion states. ```tsx function PageTOCPopover(props: ComponentProps<'div'>) { const [container, setContainer] = useState(null); useEffect(() => { const element = document.getElementById('flux-layout-slot'); if (!element) return; setContainer(element); }, []); if (!container) return; return createPortal(, container); } ``` Sources: [packages/base-ui/src/layouts/flux/page/slots/toc.tsx:92-103](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/toc.tsx#L92-L103), [packages/radix-ui/src/layouts/flux/page/slots/toc.tsx:92-103](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/page/slots/toc.tsx#L92-L103) The notebook layout splits table of contents handling into a desktop sticky sidebar container (`#nd-toc`) and a collapsible mobile popover (`TOCPopover`). When no table of contents items, headers, or footers are present, the desktop layout returns a hidden placeholder div with fixed grid width configuration. ```tsx export function TOC({ container, header, footer, style = 'normal', list }: TOCProps) { const t = useTranslations({ note: 'table of contents' }); const items = Base.useTOCItems(); const { TOCItems, TOCEmpty, TOCItem } = style === 'clerk' ? TocClerk : TocDefault; if (items.length === 0 && !footer && !header) { return
; } ``` Sources: [packages/base-ui/src/layouts/notebook/page/slots/toc.tsx:51-58](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/page/slots/toc.tsx#L51-L58), [packages/radix-ui/src/layouts/notebook/page/slots/toc.tsx:51-58](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/page/slots/toc.tsx#L51-L58) ### Popover Triggers and Progress Indicators Layout popover triggers incorporate progress circles and animated text transitions using `motion.span` components. The progress calculation evaluates the active item index relative to total list items, ensuring smooth visual tracking of reading position. ```tsx item.active) + 1) / Math.max(1, items.length)} max={1} className={cn('shrink-0', open && 'text-fd-primary')} /> ``` Sources: [packages/base-ui/src/layouts/flux/page/slots/toc.tsx:188-192](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/toc.tsx#L188-L192), [packages/radix-ui/src/layouts/flux/page/slots/toc.tsx:188-192](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/page/slots/toc.tsx#L188-L192) > [!WARNING] > In `PageTOCPopoverPhysical`, window click listeners check whether target elements fall outside `ref.current`. If a portal-rendered trigger or external custom menu sits outside the popover header element, clicking it triggers an immediate collapse via `setOpen(false)`. Sources: [packages/base-ui/src/layouts/flux/page/slots/toc.tsx:109-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/slots/toc.tsx#L109-L121), [packages/radix-ui/src/layouts/flux/page/slots/toc.tsx:109-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/page/slots/toc.tsx#L109-L121) ## Related - [Shared Layout Architecture](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/shared-layout-architecture) --- ## Technical docs: Code Block Components URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/code-block-components
Relevant source files The following files were used as context for generating this wiki page: - [packages/base-ui/src/components/codeblock.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx) - [packages/radix-ui/src/components/codeblock.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.tsx) - [packages/base-ui/src/components/codeblock.rsc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.rsc.tsx) - [packages/asyncapi/src/ui/operation/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/operation/index.tsx) - [packages/shadcn/src/rsc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/rsc.tsx) - [packages/openapi/src/ui/operation/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/index.tsx) - [packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/asyncapi/src/ui/components/codeblock.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/components/codeblock.tsx) - [packages/base-ui/src/layouts/notebook/slots/sidebar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/slots/sidebar.tsx) - [packages/radix-ui/src/components/codeblock.rsc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.rsc.tsx) - [packages/openapi/src/ui/components/codeblock.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/components/codeblock.tsx) - [packages/openapi/src/ui/operation/usage-tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/usage-tabs.tsx) - [packages/asyncapi/src/ui/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/index.tsx) - [packages/core/src/mdx-plugins/remark-code-tab.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts) - [packages/api-docs/src/components/schema/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx) - [packages/python/src/components/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx) - [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx) - [packages/base-ui/src/components/dynamic-codeblock.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dynamic-codeblock.tsx) - [packages/base-ui/src/components/dynamic-codeblock.core.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dynamic-codeblock.core.tsx) - [packages/base-ui/src/layouts/notebook/page/slots/toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/page/slots/toc.tsx) - [packages/asyncapi/src/ui/operation/message-examples.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/operation/message-examples.tsx) - [packages/radix-ui/src/layouts/notebook/page/slots/toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/page/slots/toc.tsx) - [packages/radix-ui/src/components/dynamic-codeblock.core.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx) - [packages/sanity/registry/tabs.component.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/tabs.component.tsx) - [packages/radix-ui/src/components/dynamic-codeblock.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.tsx) - [packages/core/src/mdx-plugins/codeblock-utils.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/codeblock-utils.ts) - [packages/shadcn/src/manual-installation.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts) - [packages/core/src/mdx-plugins/rehype-code.core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code.core.ts) - [packages/openapi/src/ui/operation/request-tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/request-tabs.tsx) - [packages/radix-ui/src/layouts/notebook/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/index.tsx)
## Overview Code block components provide versatile, interactive rendering pipelines for syntax-highlighted code snippets, supporting both client-side and server-rendered execution environments across Base UI and Radix UI packages. They solve the complexities of static code representation by offering responsive viewports, line numbering, copy-to-clipboard actions, and integrated tab grouping for multi-file snippets. Through unified remark and rehype transformations, markdown code blocks automatically convert into interactive tabbed structures while parsing custom metadata attributes. Furthermore, specialized integrations in OpenAPI and AsyncAPI leverage these dynamic code block components to render interactive protocol schemas, request examples, and message payloads seamlessly. Sources: [packages/base-ui/src/components/codeblock.tsx:20-146](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx#L20-L146), [packages/radix-ui/src/components/codeblock.tsx:21-147](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.tsx#L21-L147), [packages/base-ui/src/components/codeblock.rsc.tsx:5-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.rsc.tsx#L5-L32) ## Interactive Client Code Block Architecture ### Public API and Component Contracts The client code block architecture exposes a set of React primitives centered around `CodeBlock`, `Pre`, `CodeBlockTabs`, and `CodeBlockTabsList`. These components manage state transitions for copy actions, tab context propagation, and DOM virtualization for scrollable viewports. The `CodeBlockProps` interface configures options such as titles, icons, copy availability, background retention, and custom toolbar actions. ```typescript export interface CodeBlockProps extends ComponentProps<'figure'> { icon?: ReactNode; allowCopy?: boolean; keepBackground?: boolean; viewportProps?: HTMLAttributes; 'data-line-numbers'?: boolean; 'data-line-numbers-start'?: number; Actions?: (props: { className?: string; children?: ReactNode }) => ReactNode; } ``` Sources: [packages/base-ui/src/components/codeblock.tsx:20-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx#L20-L55), [packages/radix-ui/src/components/codeblock.tsx:21-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.tsx#L21-L56) The component API accepts specific props to control container behavior, styling overrides, and line numbering offsets as detailed in the reference table below. | Prop | Type | Default | Purpose | | :--- | :--- | :--- | :--- | | `icon` | `ReactNode \| string` | `undefined` | Renders a custom icon or HTML string within the header. | | `allowCopy` | `boolean` | `true` | Enables or disables the clipboard copy action button. | | `keepBackground` | `boolean` | `false` | Preserves Shiki or Rehype Code generated background colors. | | `viewportProps` | `HTMLAttributes` | `{}` | Passes extra properties directly to the scrollable viewport container. | | `data-line-numbers` | `boolean` | `undefined` | Toggles CSS line number counters on the code block viewport. | | `data-line-numbers-start` | `number` | `1` | Sets the starting integer for line number counters. | | `Actions` | `(props: { className?: string; children?: ReactNode }) => ReactNode` | Custom renderer | Injects custom toolbar action elements or customizes the toolbar wrapper. | Sources: [packages/base-ui/src/components/codeblock.tsx:20-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx#L20-L55), [packages/radix-ui/src/components/codeblock.tsx:21-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.tsx#L21-L56) > [!NOTE] > When `icon` is passed as a string, `CodeBlock` evaluates it as raw HTML using `dangerouslySetInnerHTML` inside a container with scoped SVG sizing rules (`[&_svg]:size-3.5`), whereas React nodes are rendered directly. Sources: [packages/base-ui/src/components/codeblock.tsx:99-109](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx#L99-L109), [packages/radix-ui/src/components/codeblock.tsx:99-110](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.tsx#L99-L110) ### DOM Structure and Clipboard Pipeline The underlying DOM hierarchy maps HTML semantic elements to layout structures. `CodeBlock` renders a `figure` container, enclosing an optional title header with a `figcaption`, an actions toolbar slot, and a scrollable `div` viewport (`role="region"`, `tabIndex={0}`) holding the `Pre` component. ```typescript export function Pre(props: ComponentProps<'pre'>) { return (
      {props.children}
    
); } ``` Sources: [packages/base-ui/src/components/codeblock.tsx:62-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx#L62-L68), [packages/radix-ui/src/components/codeblock.tsx:63-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.tsx#L63-L69) The clipboard copy workflow interacts with the DOM by querying the inner `pre` element from the container reference, cloning the node, stripping elements matched by `.nd-copy-ignore` by replacing them with newline characters, and writing `clone.textContent` to `navigator.clipboard`. ```typescript const [checked, onClick] = useCopyButton(() => { const pre = containerRef.current?.getElementsByTagName('pre').item(0); if (!pre) return; const clone = pre.cloneNode(true) as HTMLElement; clone.querySelectorAll('.nd-copy-ignore').forEach((node) => { node.replaceWith('\n'); }); void navigator.clipboard.writeText(clone.textContent ?? ''); }); ``` Sources: [packages/base-ui/src/components/codeblock.tsx:157-167](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx#L157-L167), [packages/radix-ui/src/components/codeblock.tsx:158-168](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.tsx#L158-L168) > [!WARNING] > Elements tagged with the `.nd-copy-ignore` CSS class inside a `Pre` block are automatically transformed into newline characters during clipboard serialization; forgetting to include this class on non-text visual artifacts like line number pseudo-elements will pollute the copied clipboard payload. Sources: [packages/base-ui/src/components/codeblock.tsx:162-164](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx#L162-L164), [packages/radix-ui/src/components/codeblock.tsx:163-165](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.tsx#L163-L165) ### Context Propagation and Tab Grouping Code block tab integration relies on `TabsContext` to coordinate styling and nesting between `CodeBlockTabs`, `CodeBlockTabsList`, and child `CodeBlock` instances. The context tracks whether a code block resides within a tab container and whether the tab container itself is nested. ```typescript const TabsContext = createContext<{ containerRef: RefObject; nested: boolean; } | null>(null); ``` Sources: [packages/base-ui/src/components/codeblock.tsx:57-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx#L57-L60), [packages/radix-ui/src/components/codeblock.tsx:58-61](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.tsx#L58-L61) When `inTab` evaluates to `true` via `use(TabsContext) !== null`, `CodeBlock` applies modifier classes (`bg-fd-secondary -mx-px -mb-px last:rounded-b-xl`) instead of standalone card styling (`my-4 bg-fd-card rounded-xl`), ensuring seamless visual integration inside tabbed viewports. Sources: [packages/base-ui/src/components/codeblock.tsx:81-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx#L81-L96), [packages/radix-ui/src/components/codeblock.tsx:82-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.tsx#L82-L97) ## Server Code Blocks and Highlighting ### RSC Highlighting Integration The `ServerCodeBlock` component provides server-side rendering for code blocks by integrating `fumadocs-core/highlight` within React Server Components. It accepts `ServerCodeBlockProps`, combining `HighlightOptions` with raw source code strings and optional configurations for the underlying client component. ```tsx export type ServerCodeBlockProps = HighlightOptions & { code: string; /** * Extra props for the underlying `` component. * * Ignored if you defined your own `pre` component in `components`. */ codeblock?: CodeBlockProps; }; ``` Sources: [packages/base-ui/src/components/codeblock.rsc.tsx:5-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.rsc.tsx#L5-L14), [packages/radix-ui/src/components/codeblock.rsc.tsx:5-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.rsc.tsx#L5-L14) Execution passes raw source strings directly into the highlighter core, overriding default color behavior and injecting a customized `pre` component implementation into the options tree. ```tsx export async function ServerCodeBlock({ code, codeblock, ...options }: ServerCodeBlockProps) { return await highlight(code, { defaultColor: false, ...options, components: { pre: (props) => (
{props.children}
), ...options.components, }, }); ``` Sources: [packages/base-ui/src/components/codeblock.rsc.tsx:16-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.rsc.tsx#L16-L32), [packages/radix-ui/src/components/codeblock.rsc.tsx:16-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.rsc.tsx#L16-L32) > [!WARNING] > Defining a custom `pre` component directly within `options.components` suppresses any extra props passed via the `codeblock` property on `ServerCodeBlockProps`. Sources: [packages/base-ui/src/components/codeblock.rsc.tsx:8-13](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.rsc.tsx#L8-L13), [packages/radix-ui/src/components/codeblock.rsc.tsx:8-13](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.rsc.tsx#L8-L13) ### Execution Trace and Sequence The rendering and interaction flow operates across server and client boundaries by delegating highlighted output into interactive component wrappers. 1. `ServerCodeBlock` invokes `highlight()` from `fumadocs-core/highlight` with custom syntax options and a wrapped `pre` component renderer. Sources: [packages/base-ui/src/components/codeblock.rsc.tsx:16-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.rsc.tsx#L16-L32), [packages/radix-ui/src/components/codeblock.rsc.tsx:16-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.rsc.tsx#L16-L32) 2. `CodeBlock` receives properties from the generated `pre` handler, manages viewport containers, titles, toolbar actions, and copy triggers. Sources: [packages/base-ui/src/components/codeblock.tsx:70-147](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx#L70-L147) 3. `CopyButton` mounts inside the actions toolbar, referencing the viewport container to extract, clean, and write text content to the clipboard. Sources: [packages/base-ui/src/components/codeblock.tsx:149-189](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx#L149-L189) ```mermaid sequenceDiagram participant RSC as ServerCodeBlock participant CB as CodeBlock participant BTN as CopyButton RSC->>CB: Renders highlighted syntax inside CodeBlock and Pre CB->>BTN: Mounts CopyButton with containerRef pointing to viewport BTN->>CB: Queries inner pre element and copies text payload on click ``` Sources: [packages/base-ui/src/components/codeblock.rsc.tsx:16-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.rsc.tsx#L16-L32), [packages/base-ui/src/components/codeblock.tsx:70-147](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx#L70-L147), [packages/base-ui/src/components/codeblock.tsx:149-189](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.tsx#L149-L189) ### Server Code Block Configuration Options | Property | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `code` | `string` | *Required* | Raw source code text string supplied for server-side [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting). | | `codeblock` | `CodeBlockProps` | `undefined` | Additional configuration props passed down to the underlying `CodeBlock` component instance. | | `defaultColor` | `boolean` | `false` | Explicitly configured when invoking `highlight` inside `ServerCodeBlock`. | Sources: [packages/base-ui/src/components/codeblock.rsc.tsx:5-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/codeblock.rsc.tsx#L5-L18), [packages/radix-ui/src/components/codeblock.rsc.tsx:5-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/codeblock.rsc.tsx#L5-L18) ## Dynamic Client-Side Syntax Highlighting ### Core Implementation and Dynamic Execution The client-side syntax highlighting system is powered by the `DynamicCodeBlock` component defined in `dynamic-codeblock.core.tsx` and wrapped for specific UI packages in `dynamic-codeblock.tsx`. It relies on `useShikiDynamic` from `fumadocs-core/highlight/shiki/react` to execute Shiki on the client on-demand, accepting a `highlighter` instance or factory function, a target language (`lang`), and source `code`. ```tsx export interface DynamicCodeblockProps { highlighter: HighlighterCore | (() => HighlighterCore | PromiseLike); lang: string; code: string; /** * Extra props for the underlying `` component. * * Ignored if you defined your own `pre` component in `options.components`. */ codeblock?: CodeBlockProps; /** * Wrap in React `` and provide a fallback. * * @defaultValue true */ wrapInSuspense?: boolean; options: DistributiveOmit; } ``` Sources: [packages/base-ui/src/components/dynamic-codeblock.core.tsx:8-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dynamic-codeblock.core.tsx#L8-L25), [packages/radix-ui/src/components/dynamic-codeblock.core.tsx:8-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx#L8-L25) The component merges user-supplied options with defaults, setting `defaultColor` to `false` and injecting a `DefaultPre` component into `options.components`. `DefaultPre` uses `PropsContext` to pass extra properties down to the underlying `CodeBlock` component while maintaining zero top margins via class name concatenation with `cn`. ```tsx function DefaultPre(props: ComponentProps<'pre'>) { const extraProps = use(PropsContext); return (
{props.children}
); } ``` Sources: [packages/base-ui/src/components/dynamic-codeblock.core.tsx:31-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dynamic-codeblock.core.tsx#L31-L43), [packages/radix-ui/src/components/dynamic-codeblock.core.tsx:31-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx#L31-L43) > [!WARNING] > Defining a custom `pre` component inside `options.components` overrides `DefaultPre`, which disables the propagation of `codeblock` properties through `PropsContext`. Sources: [packages/base-ui/src/components/dynamic-codeblock.core.tsx:12-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dynamic-codeblock.core.tsx#L12-L17), [packages/radix-ui/src/components/dynamic-codeblock.core.tsx:12-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx#L12-L17) ### Placeholder Lifecycle and Bundles When highlighting is pending or asynchronous, `wrapInSuspense` controls whether the component falls back to a structural placeholder. If `wrapInSuspense` is enabled and the Shiki node evaluates to null or undefined, the component renders a `Placeholder` element that splits the raw code string by newline characters and wraps each line in a `span` with the `line` class name. ```tsx function Placeholder({ code, components = {}, }: { code: string; components: UseShikiOptions['components']; }) { const { pre: Pre = 'pre', code: Code = 'code' } = components as Record; return (
      
        {code.split('\n').map((line, i) => (
          
            {line}
          
        ))}
      
    
); ``` Sources: [packages/base-ui/src/components/dynamic-codeblock.core.tsx:69-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dynamic-codeblock.core.tsx#L69-L88), [packages/radix-ui/src/components/dynamic-codeblock.core.tsx:69-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx#L69-L88) Package-specific bundles configure default highlighters and color themes out of the box. Both `packages/base-ui/src/components/dynamic-codeblock.tsx` and `packages/radix-ui/src/components/dynamic-codeblock.tsx` supply `defaultShikiFactory.getOrInit()` as the highlighter callback and default light and dark theme mappings to `github-light` and `github-dark`. ```tsx export function DynamicCodeBlock(props: DynamicCodeblockProps) { return ( defaultShikiFactory.getOrInit()} options={{ themes: { light: 'github-light', dark: 'github-dark' } }} {...props} /> ); } ``` Sources: [packages/base-ui/src/components/dynamic-codeblock.tsx:9-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dynamic-codeblock.tsx#L9-L17), [packages/radix-ui/src/components/dynamic-codeblock.tsx:9-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.tsx#L9-L17) ### Dynamic Code Block Properties | Property | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `highlighter` | `HighlighterCore \| (() => HighlighterCore \| PromiseLike)` | *Required* | Shiki highlighter instance or a factory function returning or resolving to one. | | `lang` | `string` | *Required* | Language identifier used for syntax parsing and highlighting rules. | | `code` | `string` | *Required* | Raw source code string to be highlighted or rendered inside placeholders. | | `codeblock` | `CodeBlockProps` | `undefined` | Extra properties passed to the underlying `` component wrapper. | | `wrapInSuspense` | `boolean` | `true` | Determines whether to wrap the node and display a line-split fallback placeholder while loading. | | `options` | `DistributiveOmit` | *Required* | Shiki configuration options excluding the language specifier. | Sources: [packages/base-ui/src/components/dynamic-codeblock.core.tsx:8-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/components/dynamic-codeblock.core.tsx#L8-L25), [packages/radix-ui/src/components/dynamic-codeblock.core.tsx:8-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/dynamic-codeblock.core.tsx#L8-L25) ## Markdown Transformation and Tab Grouping ### AST Transformation and Attribute Parsing The `remarkCodeTab` unified transformer processes Markdown syntax trees to convert adjacent fenced code blocks carrying specific attributes into tabbed component structures. It inspects nodes containing child elements, skipping any node marked with `_code_tab_visited`. When visiting container elements or MDX JSX flow elements whose names match registered tab handlers, it groups consecutive code blocks that contain a `tab` attribute extracted via `parseCodeBlockAttributes`. ```typescript export function remarkCodeTab( this: Processor, options: RemarkCodeTabOptions = {}, ): Transformer { const { parseMdx = false, Tabs = 'CodeBlockTabs' } = options; return (tree) => { visit(tree, (node) => { if (!('children' in node) || node.data?._code_tab_visited) return 'skip'; let localTabs: TabType = Tabs; let localParseMdx = parseMdx; let withParent = true; if (node.type === 'mdxJsxFlowElement' && node.name && node.name in Types) { withParent = false; localTabs = node.name as TabType; // for `Tabs` in simple mode, it doesn't support MDX tab names if (node.name === 'Tabs' && localParseMdx) { localParseMdx = node.attributes.every( (attribute) => attribute.type !== 'mdxJsxAttribute' || attribute.name !== 'items', ); } } let start = -1; let end = 0; const close = () => { if (start === -1 || start === end) return; const replacement = Types[localTabs]( this, node.children.slice(start, end) as Code[], localParseMdx, withParent, ); for (const element of replacement) { element.data ??= {}; element.data._code_tab_visited = true; } node.children.splice(start, end - start, ...replacement); end = start; start = -1; }; for (; end < node.children.length; end++) { const child = node.children[end]; if (child.type !== 'code' || !child.meta) { close(); continue; } const meta = parseCodeBlockAttributes(child.meta, ['tab', 'tab-group']); if (!meta.attributes.tab) { close(); continue; } if (start === -1) start = end; child.meta = meta.rest; child.data ??= {}; child.data.tab = meta.attributes.tab; if (meta.attributes['tab-group']) { child.data.tabGroup = meta.attributes['tab-group']; } } close(); }); }; } ``` Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:202-273](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L202-L273) The utility function `parseCodeBlockAttributes` uses a regular expression `AttributeRegex` to scan meta strings for space-separated key-value pairs matching attribute names, supporting both double-quoted and single-quoted values as well as boolean flags. It accepts an optional list of allowed attribute names and returns an object containing the parsed attributes dictionary and the remaining unparsed meta string. ```typescript export interface CodeBlockAttributes { attributes: Partial>; rest: string; } const AttributeRegex = /(?<=^|\s)(?[a-zA-Z0-9_-]+)(?:=(?:"([^"]*)"|'([^']*)'))?/g; /** * Parse Fumadocs-style code block attributes from meta string, like `title="hello world"` */ export function parseCodeBlockAttributes( meta: string, allowedNames?: Name[], ): CodeBlockAttributes { const attributes: CodeBlockAttributes['attributes'] = {}; const rest = meta.replaceAll(AttributeRegex, (match, name, value_1, value_2) => { if (allowedNames && !allowedNames.includes(name)) return match; attributes[name] = value_1 ?? value_2 ?? null; return ''; }); return { rest, attributes, }; } ``` Sources: [packages/core/src/mdx-plugins/codeblock-utils.ts:89-115](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/codeblock-utils.ts#L89-L115) > [!WARNING] > Using the legacy `tab` meta string parameter inside Shiki transformers triggers a console warning instructing authors to migrate to the `remarkCodeTab` remark plugin instead. Sources: [packages/core/src/mdx-plugins/rehype-code.core.ts:144-171](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-code.core.ts#L144-L171) ### Tab Handler Strategies and Group Generation The plugin supports two distinct tab generation strategies defined in the `Types` record: `CodeBlockTabs` and `Tabs`. The `CodeBlockTabs` strategy collects grouped code blocks and delegates to `generateCodeBlockTabs` to construct an MDX JSX flow element representing optimized tab wrappers. ```typescript const Types: Record = { CodeBlockTabs(processor, nodes, withMdx, withParent) { const tabs = processTabValue(nodes); let isFirstTab = true; const options: CodeBlockTabsOptions = { triggers: [], tabs: [], }; for (const [value, list] of tabs) { if (isFirstTab) { const tagGroup = list[0].data?.tabGroup; options.defaultValue = value; if (tagGroup) options.persist = { id: tagGroup }; isFirstTab = false; } options.triggers.push({ value, children: withMdx ? (mdxToAst(processor, value).children as BlockContent[]) : [ { type: 'text', value, }, ], }); options.tabs.push({ value, children: list, }); } const node = generateCodeBlockTabs(options); if (!withParent) return node.children; return [node]; }, ``` Sources: [packages/core/src/mdx-plugins/remark-code-tab.ts:50-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-code-tab.ts#L50-L88) The `generateCodeBlockTabs` builder accepts configuration options to assemble tab lists, triggers, and tab panels with optional state persistence and default values. ```typescript export interface CodeBlockTabsOptions { attributes?: MdxJsxAttribute[]; defaultValue?: string; persist?: | { id: string; } | false; triggers: { value: string; children: (BlockContent | Text)[]; }[]; tabs: { value: string; children: BlockContent[]; }[]; } ``` Sources: [packages/core/src/mdx-plugins/codeblock-utils.ts:4-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/codeblock-utils.ts#L4-L20) | Option Property | Type | Purpose | | :--- | :--- | :--- | | `attributes` | `MdxJsxAttribute[]` | Additional JSX attributes applied to the root element. | | `defaultValue` | `string` | The initial active tab value selected on render. | | `persist` | `{ id: string } \| false` | Configures client-side selection persistence using the specified group identifier. | | `triggers` | `{ value: string; children: (BlockContent \| Text)[] }[]` | List of trigger buttons rendered in the tab navigation header. | | `tabs` | `{ value: string; children: BlockContent[] }[]` | List of tab content panels containing the grouped code blocks. | Sources: [packages/core/src/mdx-plugins/codeblock-utils.ts:4-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/codeblock-utils.ts#L4-L20) ## Specialized Protocol Code Block Integration ### AsyncAPI Message Examples and Payload Tabs The `MessageExamples` component inspects asynchronous message definitions to generate protocol schema examples and test payloads. It utilizes `getExampleMessages` to extract relevant items, filtering for entries containing `payload`, `headers`, or `description`. ```tsx const items = useMemo( () => getExampleMessages({ message }).filter( (item) => item.payload !== undefined || item.headers !== undefined || item.description, ), [message], ); ``` Sources: [packages/asyncapi/src/ui/operation/message-examples.tsx:28-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/operation/message-examples.tsx#L28-L34) When multiple message examples exist, `MessageExamples` renders a selectable tab group using `SelectTabs` and `SelectTabTrigger`. Each individual example content block splits headers and payloads into separate interactive code blocks via `MessageExampleContent`. ```tsx const items: { label: string; value: string; content: ReactNode }[] = []; if (headers) items.push({ label: t('Headers'), value: 'headers', content: , }); if (payload) items.push({ label: t('Payload'), value: 'payload', content: , }); ``` Sources: [packages/asyncapi/src/ui/operation/message-examples.tsx:87-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/operation/message-examples.tsx#L87-L100) These content blocks wrap JSON-serialized headers and payloads inside `CodeBlockTabs`, utilizing `ClientCodeBlock` components with the language set to `json`. ```tsx {items.map((item) => ( {item.label} ))} {items.map((item) => ( {item.content} ))} ``` Sources: [packages/asyncapi/src/ui/operation/message-examples.tsx:103-116](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/operation/message-examples.tsx#L103-L116) > [!NOTE] > `ClientCodeBlock` in AsyncAPI pages first checks for a user-supplied custom `CodeBlock` component in the render context, falling back to `DynamicCodeBlock` with Shiki initialization if none is provided. Sources: [packages/asyncapi/src/ui/components/codeblock.tsx:8-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/components/codeblock.tsx#L8-L14) ### Python Package Component Code Highlighting The Python documentation package defines structured UI components such as `PyFunction`, `PyAttribute`, and `PyParameter` that integrate inline code formatting and syntax highlighting via `InlineCode`. ```tsx export function PyFunction(props: { name: string; type: string; children?: ReactNode }) { return (
func {props.name}
{props.children}
); } ``` Sources: [packages/python/src/components/index.tsx:25-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L25-L40) The `InlineCode` helper asynchronously invokes the core `highlight` function, targeting the `python` language and overriding the pre element tag to render lightweight styled inline spans. ```tsx async function InlineCode({ lang, code, ...rest }: ComponentProps<'span'> & { lang: string; code: string; }) { return highlight(code, { lang, components: { pre: (props) => , }, }); } ``` Sources: [packages/python/src/components/index.tsx:135-149](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L135-L149) | Component Name | Primary Badge Variant | Highlight Language | Purpose | | :--- | :--- | :--- | :--- | | `PyFunction` | `func` | `python` | Renders Python function signatures with return types and descriptions. | | `PyAttribute` | `attribute` | `python` | Renders class or module attributes with optional types and default values. | | `PyParameter` | `primary` | `python` | Renders parameter definitions inside function documentation cards. | | `PyFunctionReturn` | *None* | `python` | Displays function return type annotations inside styled containers. | Sources: [packages/python/src/components/index.tsx:14-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L14-L133) ## Related - [Syntax Highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting) --- ## Technical docs: Theme Styles and CSS URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/theme-styles-and-css
Relevant source files The following files were used as context for generating this wiki page: - [packages/base-ui/css/preset.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/preset.css) - [packages/radix-ui/css/preset.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/preset.css) - [packages/radix-ui/css/vitepress.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/vitepress.css) - [packages/base-ui/css/vitepress.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/vitepress.css) - [packages/tailwind/src/typography/styles.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/styles.ts) - [packages/shadcn/src/manual-installation.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts) - [packages/tailwind/src/typography/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts) - [packages/preview/src/styles/globals.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/styles/globals.css) - [packages/radix-ui/css/preset-legacy.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/preset-legacy.css) - [packages/openapi/css/preset.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/css/preset.css) - [packages/base-ui/css/style.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/style.css) - [packages/radix-ui/css/style.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/style.css) - [packages/api-docs/css/preset.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/css/preset.css) - [packages/base-ui/css/solar.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/solar.css) - [packages/preview/src/pages/_root.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/_root.tsx) - [packages/radix-ui/css/solar.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/solar.css) - [packages/asyncapi/css/preset.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/css/preset.css) - [packages/radix-ui/css/catppuccin.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/catppuccin.css) - [packages/base-ui/css/shadcn.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/shadcn.css) - [packages/python/styles/preset.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/styles/preset.css) - [packages/radix-ui/css/shadcn.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/shadcn.css) - [packages/radix-ui/css/lib/shiki.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/lib/shiki.css) - [packages/base-ui/css/catppuccin.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/catppuccin.css) - [packages/base-ui/css/lib/shiki.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css) - [packages/preview/waku.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/waku.config.ts) - [packages/base-ui/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/tsdown.config.ts) - [packages/radix-ui/src/tailwind/typography.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/tailwind/typography.ts) - [packages/base-ui/src/tailwind/typography.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/tailwind/typography.ts) - [packages/radix-ui/css/ruby.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/ruby.css) - [packages/base-ui/css/lib/base.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/base.css)
## Overview Fumadocs provides a comprehensive styling system built around Tailwind CSS, custom design tokens, and modular stylesheets that configure layouts, typography, and code blocks across base-ui and radix-ui packages. This architecture bridges component primitives with preconfigured or custom theme variants such as Catppuccin, Shadcn, Vitepress, Solar, and Ruby. Sources: [packages/base-ui/css/preset.css:1-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/preset.css#L1-L11), [packages/radix-ui/css/preset.css:1-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/preset.css#L1-L11), [packages/radix-ui/css/vitepress.css:1-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/vitepress.css#L1-L40), [packages/radix-ui/css/catppuccin.css:1-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/catppuccin.css#L1-L39), [packages/radix-ui/css/solar.css:1-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/solar.css#L1-L16), [packages/radix-ui/css/ruby.css:1-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/ruby.css#L1-L39), [packages/radix-ui/css/shadcn.css:1-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/shadcn.css#L1-L21) ## Preset Stylesheets and Base CSS ### Preset CSS Structures The styling architecture relies on preset stylesheets located inside the `base-ui` and `radix-ui` packages [packages/base-ui/css/preset.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/preset.css#L1-L11), [packages/radix-ui/css/preset.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/preset.css#L1-L11). Each preset consolidates base imports, typography plugins, and generated layout modules into a single entry point. | Preset File | Primary Imports & Plugins | Layout / Generated Modules | | :--- | :--- | :--- | | `packages/base-ui/css/preset.css` | `./lib/base.css`, `./lib/shiki.css`, `../dist/tailwind/typography.js` | `flux.css`, `docs.css`, `home.css`, `notebook.css`, `shared.css` | | `packages/radix-ui/css/preset.css` | `./lib/base.css`, `./lib/shiki.css`, `../dist/tailwind/typography.js` | `docs.css`, `home.css`, `notebook.css`, `flux.css`, `shared.css` | | `packages/radix-ui/css/preset-legacy.css` | `./lib/base.css`, `./lib/shiki.css`, `../dist/tailwind/typography.js` | `docs.css`, `home.css`, `notebook.css`, `flux.css`, `shared.css`, legacy theme block | Sources: [packages/base-ui/css/preset.css:1-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/preset.css#L1-L11), [packages/radix-ui/css/preset.css:1-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/preset.css#L1-L11), [packages/radix-ui/css/preset-legacy.css:1-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/preset-legacy.css#L1-L22) ### Base CSS Primitives and Animation Keyframes The core imported primitives in `packages/base-ui/css/lib/base.css` define direction-aware drawer offsets, theme variables, and custom animation keyframes [packages/base-ui/css/lib/base.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/base.css#L1-L85). ```css @theme { --animate-fd-fade-in: fd-fade-in 300ms ease; --animate-fd-fade-out: fd-fade-out 300ms ease; --animate-fd-dialog-in: fd-dialog-in 300ms cubic-bezier(0.16, 1, 0.3, 1); --animate-fd-dialog-out: fd-dialog-out 300ms cubic-bezier(0.16, 1, 0.3, 1); --animate-fd-popover-in: fd-popover-in 100ms ease; --animate-fd-popover-out: fd-popover-out 100ms ease; --animate-fd-sidebar-in: fd-sidebar-in 250ms ease; --animate-fd-sidebar-out: fd-sidebar-out 250ms ease; @keyframes fd-sidebar-in { from { transform: translateX(var(--fd-sidebar-drawer-offset)); } } @keyframes fd-sidebar-out { to { transform: translateX(var(--fd-sidebar-drawer-offset)); } } @keyframes fd-dialog-in { from { transform: scale(1.06); opacity: 0; } to { transform: scale(1); } } @keyframes fd-dialog-out { from { transform: scale(1); } to { transform: scale(1.04); opacity: 0; } } @keyframes fd-popover-in { from { opacity: 0; transform: scale(0.9); } } @keyframes fd-popover-out { to { opacity: 0; transform: scale(0.9); } } @keyframes fd-fade-in { from { opacity: 0; } to { opacity: 1; } } @keyframes fd-fade-out { from { opacity: 1; } to { opacity: 0; } } } ``` Sources: [packages/base-ui/css/lib/base.css:9-85](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/base.css#L9-L85) > [!NOTE] > The sidebar drawer offset variable `--fd-sidebar-drawer-offset` switches dynamically between `100%` and `-100%` based on the document direction attribute `[dir='rtl']` to ensure slide transitions occur in the correct inline orientation. Sources: [packages/base-ui/css/lib/base.css:1-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/base.css#L1-L8) ### Legacy Custom Theme Variables and Utilities The legacy Radix UI preset provides specific theme tokens and utilities that define container widths, layout offsets, and custom scrollbar or step counters [packages/radix-ui/css/preset-legacy.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/preset-legacy.css#L13-L43), [packages/base-ui/css/lib/base.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/base.css#L102-L153). ```css @theme { --spacing-fd-container: 1400px; --fd-page-width: 1200px; --fd-sidebar-width: 0px; --fd-toc-width: 0px; --fd-layout-width: 1600px; --fd-banner-height: 0px; --fd-nav-height: 0px; --fd-tocnav-height: 0px; } @layer base { :root, #nd-docs-layout { --fd-layout-offset: max(calc(50vw - var(--fd-layout-width) / 2), 0px); } } @utility container { margin-inline: auto; padding-inline: 1rem; @apply 2xl:max-w-(--spacing-fd-container); } /* Apply styles to :root */ @custom-variant on-root { :root:has(&) { @slot; } } ``` Sources: [packages/radix-ui/css/preset-legacy.css:13-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/preset-legacy.css#L13-L43) > [!WARNING] > When using legacy layout definitions, the root layout offset calculation utilizes `calc(50vw - var(--fd-layout-width) / 2)`, clamping values at `0px` to handle wide-screen alignment correctly. Sources: [packages/radix-ui/css/preset-legacy.css:24-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/preset-legacy.css#L24-L29) ## Theme Color Palettes ### Catppuccin Theme The Catppuccin theme variant establishes distinct pastel and deep background color tokens inside both `packages/base-ui/css/catppuccin.css` and `packages/radix-ui/css/catppuccin.css` [packages/base-ui/css/catppuccin.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/catppuccin.css#L1-L49), [packages/radix-ui/css/catppuccin.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/catppuccin.css#L1-L49). Each variant imports `./lib/default-colors.css` and configures custom HSL color properties for both light mode (`@theme`) and dark mode (`.dark`) along with specialized sidebar variables [packages/base-ui/css/catppuccin.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/catppuccin.css#L1-L49), [packages/radix-ui/css/catppuccin.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/catppuccin.css#L1-L49). ```css @theme { --color-fd-popover: hsl(220, 22%, 92%); --color-fd-popover-foreground: hsl(234, 16%, 35%); --color-fd-secondary-foreground: hsl(234, 16%, 35%); --color-fd-border: hsl(223, 16%, 83%); --color-fd-primary: hsl(266, 85%, 58%); --color-fd-primary-foreground: hsl(220, 22%, 92%); --color-fd-muted: hsl(220, 22%, 92%); --color-fd-card: hsl(220, 22%, 92%); --color-fd-accent: hsl(223, 16%, 83%); --color-fd-accent-foreground: hsl(234, 16%, 35%); --color-fd-card-foreground: hsl(234, 16%, 35%); --color-fd-muted-foreground: hsl(233, 10%, 47%); --color-fd-foreground: hsl(234, 16%, 35%); --color-fd-secondary: hsl(220, 22%, 92%); --color-fd-background: hsl(220, 23%, 95%); --color-fd-ring: hsl(267, 84%, 81%); } ``` Sources: [packages/base-ui/css/catppuccin.css:3-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/catppuccin.css#L3-L20) > [!NOTE] > In Catppuccin dark mode, `#nd-sidebar` overrides both `--color-fd-secondary` and `--color-fd-muted` to `hsl(237, 16%, 23%)`, matching the dark border and accent tone. Sources: [packages/base-ui/css/catppuccin.css:46-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/catppuccin.css#L46-L49), [packages/radix-ui/css/catppuccin.css:46-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/catppuccin.css#L46-L49) ### Shadcn and Vitepress Themes The Shadcn theme variant maps Fumadocs CSS variables directly to underlying `--background`, `--foreground`, `--muted`, `--popover`, `--card`, `--border`, `--primary`, `--secondary`, `--accent`, and `--ring` properties across `:root` and `.dark` selectors [packages/base-ui/css/shadcn.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/shadcn.css#L3-L21), [packages/radix-ui/css/shadcn.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/shadcn.css#L3-L21). Additionally, it configures `#nd-sidebar` bindings and declares a static theme variable `--color-fd-error: var(--destructive);` [packages/base-ui/css/shadcn.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/shadcn.css#L23-L36), [packages/radix-ui/css/shadcn.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/shadcn.css#L23-L36). ```css #nd-sidebar { background-color: var(--sidebar); color: var(--sidebar-foreground); border-color: var(--sidebar-border); --color-fd-accent: var(--sidebar-accent); --color-fd-accent-foreground: var(--sidebar-accent-foreground); --color-fd-ring: var(--sidebar-ring); --color-fd-primary-foreground: var(--sidebar-primary-foreground); } @theme static { --color-fd-error: var(--destructive); } ``` Sources: [packages/base-ui/css/shadcn.css:23-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/shadcn.css#L23-L36), [packages/radix-ui/css/shadcn.css:23-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/shadcn.css#L23-L36) The Vitepress theme variant defines explicit neutral HSL values for light and dark modes, customizes prose links and code background color-mix styles, and modifies `#nd-sidebar` background colors [packages/base-ui/css/vitepress.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/vitepress.css#L3-L61), [packages/radix-ui/css/vitepress.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/vitepress.css#L3-L61). ```css --color-fd-background: hsl(0, 0%, 100%); --color-fd-card: hsl(0, 0%, 100%); --color-fd-foreground: hsl(240, 6%, 25%); --color-fd-muted-foreground: hsl(240, 6%, 50%); --color-fd-secondary: hsl(240, 6%, 97%); --color-fd-accent-foreground: hsl(240, 6%, 25%); --color-fd-primary: hsl(226, 55%, 45%); } ``` Sources: [packages/base-ui/css/vitepress.css:14-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/vitepress.css#L14-L21), [packages/radix-ui/css/vitepress.css:14-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/vitepress.css#L14-L21) ### Solar and Ruby Themes The Solar theme variant utilizes OKLCH color definitions for primary and article tokens alongside strict letter-spacing adjustments and responsive layout rules [packages/base-ui/css/solar.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/solar.css#L3-L16), [packages/radix-ui/css/solar.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/solar.css#L3-L16). Under `@variant md`, Solar injects absolute pseudo-elements before `#nd-page` with rounded borders, shadows, and margins for both `#nd-docs-layout` and `#nd-notebook-layout` [packages/base-ui/css/solar.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/solar.css#L18-L70), [packages/radix-ui/css/solar.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/solar.css#L18-L70). ```css .dark { --color-fd-primary: oklch(0.902 0.0461 259.51); --color-fd-article: hsl(0, 0%, 7.04%); --color-fd-background: hsl(0, 0%, 5.04%); } ``` Sources: [packages/base-ui/css/solar.css:12-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/solar.css#L12-L16), [packages/radix-ui/css/solar.css:12-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/solar.css#L12-L16) The Ruby theme variant implements deep crimson, rose, and pink palettes tailored for light and dark environments [packages/radix-ui/css/ruby.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/ruby.css#L3-L39). It establishes primary colors using `hsl(348, 85%, 45%)` in light mode and `hsl(348, 90%, 62%)` in dark mode, with custom translucent border alphas set to `0.25` [packages/radix-ui/css/ruby.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/ruby.css#L3-L39). ```css @theme { --color-fd-background: hsl(0, 0%, 98%); --color-fd-foreground: hsl(350, 45%, 14%); --color-fd-primary: hsl(348, 85%, 45%); --color-fd-primary-foreground: hsl(0, 0%, 100%); --color-fd-border: hsla(348, 40%, 60%, 0.25); --color-fd-ring: hsl(348, 85%, 45%); --color-fd-accent: hsl(348, 70%, 95%); --color-fd-accent-foreground: hsl(348, 70%, 22%); --color-fd-muted: hsl(0, 0%, 94%); --color-fd-muted-foreground: hsl(348, 25%, 42%); --color-fd-secondary: hsl(348, 55%, 92%); --color-fd-secondary-foreground: hsl(348, 50%, 20%); --color-fd-card: hsl(0, 0%, 100%); --color-fd-card-foreground: hsl(350, 45%, 14%); --color-fd-popover: hsl(0, 0%, 100%); --color-fd-popover-foreground: hsl(350, 45%, 14%); } ``` Sources: [packages/radix-ui/css/ruby.css:3-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/ruby.css#L3-L20) > [!CAUTION] > When integrating the Solar theme, ensure that [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) popover positioning rules calculate top offsets using `--fd-docs-row-1` or `--fd-docs-row-2` variables plus `2.5 * var(--spacing)`, or popover headers will detach from trigger elements. Sources: [packages/base-ui/css/solar.css:34-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/solar.css#L34-L68), [packages/radix-ui/css/solar.css:34-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/solar.css#L34-L68) ## Tailwind Typography Plugin Engine ### Selector Manipulation and Scoping The typography plugin architecture in `packages/tailwind` dynamically generates scoped prose component styles and custom Tailwind variants [packages/tailwind/src/typography/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L149-L184). Built with Tailwind's `plugin.withOptions`, the plugin accepts an optional configuration object specifying a custom CSS class name (defaulting to `prose`) and a `disableRoundedTable` boolean flag [packages/tailwind/src/typography/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L150-L150). It registers variants across a defined set of selectors using `addVariant` and injects component styles via `addComponents` [packages/tailwind/src/typography/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L158-L182). ```typescript export const typography: ReturnType> = plugin.withOptions(({ className = 'prose', ...styleOptions } = {}) => { return ({ addVariant, addComponents, ...rest }) => { const prefix = (rest as unknown as { prefix: Context['prefix'] }).prefix; for (const [name, ...values] of SELECTORS) { const selectors = values.length === 0 ? [name] : values; const selector = selectors.join(', '); addVariant( `${className}-${name}`, `& :is(${inWhere(selector, { prefix, className, })})`, ); } addComponents({ [`.${className}`]: configToCss( { ...styles.DEFAULT, css: [ ...(styles.DEFAULT.css ?? []), styleOptions.disableRoundedTable ? styles.normalTable : styles.roundedTable, ], }, { className, modifier: 'DEFAULT', prefix, }, ), }); }; }); ``` Sources: [packages/tailwind/src/typography/index.ts:149-184](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L149-L184) Selector generation relies on `inWhere` and `commonTrailingPseudos` to construct robust CSS rules [packages/tailwind/src/typography/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L21-L35), [packages/tailwind/src/typography/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L68-L115). The `commonTrailingPseudos` function parses selectors with `postcss-selector-parser`, extracts pseudo-elements into a column-major 2D array, and hoists identical trailing pseudo elements to the end of the selector [packages/tailwind/src/typography/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L68-L115). The `inWhere` wrapper wraps the selector in a `:where()` pseudo-class and appends a `:not(:where([class~="not-className"],[class~="not-className"] *))` exclusion to support nested unprose exceptions [packages/tailwind/src/typography/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L21-L35). ```typescript function inWhere(selector: string, { className, prefix, modifier }: Options & Context) { const prefixedNot = prefix(`.not-${className}`).slice(1); const selectorPrefix = selector.startsWith('>') ? `${modifier === 'DEFAULT' ? `.${className}` : `.${className}-${modifier}`} ` : ''; // Parse the selector, if every component ends in the same pseudo element(s) then move it to the end const [trailingPseudo, rebuiltSelector] = commonTrailingPseudos(selector); if (trailingPseudo) { return `:where(${selectorPrefix}${rebuiltSelector}):not(:where([class~="${prefixedNot}"],[class~="${prefixedNot}"] *))${trailingPseudo}`; } return `:where(${selectorPrefix}${selector}):not(:where([class~="${prefixedNot}"],[class~="${prefixedNot}"] *))`; } ``` Sources: [packages/tailwind/src/typography/index.ts:21-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L21-L35) The plugin registers variants for thirty distinct target identifiers using `SELECTORS` [packages/tailwind/src/typography/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L117-L147), [packages/tailwind/src/typography/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L154-L165). | Variant Name | Target Elements / Selectors | | :--- | :--- | | `prose-headings` | `h1`, `h2`, `h3`, `h4`, `h5`, `h6`, `th` | | `prose-h1` | `h1` | | `prose-h2` | `h2` | | `prose-h3` | `h3` | | `prose-h4` | `h4` | | `prose-h5` | `h5` | | `prose-h6` | `h6` | | `prose-p` | `p` | | `prose-a` | `a` | | `prose-blockquote` | `blockquote` | | `prose-figure` | `figure` | | `prose-figcaption` | `figcaption` | | `prose-strong` | `strong` | | `prose-em` | `em` | | `prose-kbd` | `kbd` | | `prose-code` | `code` | | `prose-pre` | `pre` | | `prose-ol` | `ol` | | `prose-ul` | `ul` | | `prose-li` | `li` | | `prose-table` | `table` | | `prose-thead` | `thead` | | `prose-tr` | `tr` | | `prose-th` | `th` | | `prose-td` | `td` | | `prose-img` | `img` | | `prose-video` | `video` | | `prose-hr` | `hr` | | `prose-lead` | `[class~="lead"]` | ```typescript const SELECTORS = [ ['headings', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'th'], ['h1'], ['h2'], ['h3'], ['h4'], ['h5'], ['h6'], ['p'], ['a'], ['blockquote'], ['figure'], ['figcaption'], ['strong'], ['em'], ['kbd'], ['code'], ['pre'], ['ol'], ['ul'], ['li'], ['table'], ['thead'], ['tr'], ['th'], ['td'], ['img'], ['video'], ['hr'], ['lead', '[class~="lead"]'], ]; ``` Sources: [packages/tailwind/src/typography/index.ts:117-147](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L117-L147) ### Calculated Styles and Tables Calculated typographic styles use helper functions `round`, `rem`, and `em` defined in `packages/tailwind/src/typography/styles.ts` to convert pixel values into relative `rem` and `em` units [packages/tailwind/src/typography/styles.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/styles.ts#L1-L14). The engine merges default typography configurations with either `roundedTable` or `normalTable` based on the `disableRoundedTable` option [packages/tailwind/src/typography/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L167-L182). The `roundedTable` export configures separated borders, background colors using `var(--color-fd-card)`, border radii from `var(--radius-lg)`, and custom inline border start styles [packages/tailwind/src/typography/styles.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/styles.ts#L35-L72). ```typescript export const roundedTable = { table: { borderCollapse: 'separate', borderSpacing: '0', background: 'var(--color-fd-card)', borderRadius: 'var(--radius-lg)', border: '1px solid var(--color-fd-border)', overflow: 'hidden', }, th: { textAlign: 'start', padding: 'calc(var(--spacing) * 2.5)', 'border-inline-start': '1px solid var(--color-fd-border)', background: 'var(--color-fd-muted)', }, 'th:first-child': { 'border-inline-start': 'none', }, 'th:not(tr:last-child *), td:not(tr:last-child *)': { 'border-bottom': '1px solid var(--color-fd-border)', }, td: { textAlign: 'start', 'border-inline-start': '1px solid var(--color-fd-border)', padding: 'calc(var(--spacing) * 2.5)', }, 'td:first-child': { 'border-inline-start': 'none', }, 'tfoot th, tfoot td': { borderTopWidth: '1px', borderTopColor: 'var(--tw-prose-th-borders)', }, 'thead th, thead td': { borderBottomWidth: '1px', borderBottomColor: 'var(--tw-prose-th-borders)', }, }; ``` Sources: [packages/tailwind/src/typography/styles.ts:35-72](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/styles.ts#L35-L72) > [!NOTE] > When `disableRoundedTable` is enabled, the plugin applies `normalTable` rules instead of `roundedTable`, setting explicit bottom borders on table headers and alternating body rows while omitting explicit card background wrappers. Sources: [packages/tailwind/src/typography/index.ts:167-182](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/index.ts#L167-L182), [packages/tailwind/src/typography/styles.ts:74-113](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/tailwind/src/typography/styles.ts#L74-L113) ## Syntax Highlighting and Shiki Styling ### Shiki Theme Variables and Selectors Fumadocs formats code blocks and inline code using Shiki via CSS stylesheets located in `packages/radix-ui/css/lib/shiki.css` and `packages/base-ui/css/lib/shiki.css`. The engine maps [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting) tokens to CSS variables for light and dark themes. For block-level code elements matching `.shiki:not(.not-fumadocs-codeblock *)`, token spans inherit `--shiki-light` colors and `--shiki-light-font-style` in light mode, while `.dark .shiki:not(.not-fumadocs-codeblock *)` selectors assign `--shiki-dark` colors and `--shiki-dark-font-style`. Inline code elements matching `code.shiki:not(.not-fumadocs-code *)` apply the identical theme variable mapping for both light and dark contexts. ```css .shiki:not(.not-fumadocs-codeblock *) { --padding-left: calc(var(--spacing) * 4); --padding-right: calc(var(--spacing) * 4); code span { color: var(--shiki-light); font-style: var(--shiki-light-font-style); } ``` Sources: [packages/radix-ui/css/lib/shiki.css:1-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/lib/shiki.css#L1-L8), [packages/base-ui/css/lib/shiki.css:1-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L1-L8) ```css .dark .shiki:not(.not-fumadocs-codeblock *) { code span { color: var(--shiki-dark); font-style: var(--shiki-dark-font-style); } } /* inline code */ code.shiki:not(.not-fumadocs-code *) span { color: var(--shiki-light); font-style: var(--shiki-light-font-style); } .dark code.shiki:not(.not-fumadocs-code *) span { color: var(--shiki-dark); font-style: var(--shiki-dark-font-style); } ``` Sources: [packages/radix-ui/css/lib/shiki.css:92-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/lib/shiki.css#L92-L108), [packages/base-ui/css/lib/shiki.css:92-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L92-L108) > [!NOTE] > The `:not(.not-fumadocs-codeblock *)` and `:not(.not-fumadocs-code *)` exclusions prevent Shiki theme overrides from applying inside custom blocks that opt out of Fumadocs styling. Sources: [packages/radix-ui/css/lib/shiki.css:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/lib/shiki.css#L1-L1), [packages/radix-ui/css/lib/shiki.css:100-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/lib/shiki.css#L100-L100) ### Line Decoration and Code Block Features Code block layout is governed by variables setting padding-left and padding-right to 4 times the spacing scale (`--padding-left` and `--padding-right`). Empty code lines are forced to a height of `1lh`. Advanced features like line focus states, git diff markers, line highlights, and line numbers are implemented through specific CSS classes and pseudo-elements. | Class Selector | Applied Styles & Variables | Purpose | | :--- | :--- | :--- | | `&.has-focused .line:not(.focused)` | `filter: blur(2px); transition: filter 200ms;` | Applies blur to non-focused lines when focus mode is active. | | `&.has-focused:hover .line:not(.focused)` | `filter: blur(0);` | Clears blur when hovering over a code block with active focus lines. | | `.diff.remove` | `--fd-counter-color: var(--color-fd-diff-remove-symbol); @apply bg-fd-diff-remove; opacity: 0.7;` | Styles deleted diff lines with background color and opacity. | | `.diff.remove::before` | `content: '-'; @apply text-fd-diff-remove-symbol;` | Inserts the minus symbol before removed lines. | | `.diff.add` | `--fd-counter-color: var(--color-fd-diff-add-symbol); @apply bg-fd-diff-add;` | Styles added diff lines with background color. | | `.diff.add::before` | `content: '+'`; `@apply text-fd-diff-add-symbol;` | Inserts the plus symbol before added lines. | | `.highlighted` | `--fd-counter-color: var(--color-fd-primary); @apply bg-fd-primary/10;` | Highlights entire code lines with primary theme tint. | | `.highlighted::after` | `position: absolute; content: ''; @apply inset-y-0 left-0 border-l-2 border-fd-primary/50;` | Renders a left accent border on highlighted lines. | | `.highlighted-word` | `padding: 1px; @apply border -my-px border-fd-primary/30 bg-fd-primary/10 rounded-md font-medium;` | Styles specific inline highlighted words within code spans. | ```css .line { position: relative; padding-left: var(--padding-left); padding-right: var(--padding-right); } .line:empty { height: 1lh; } &.has-focused .line:not(.focused) { filter: blur(2px); transition: filter 200ms; } &.has-focused:hover .line:not(.focused) { filter: blur(0); } .diff::before { position: absolute; left: calc(var(--spacing) * 1.5); } .diff.remove { opacity: 0.7; --fd-counter-color: var(--color-fd-diff-remove-symbol); @apply bg-fd-diff-remove; } .diff.remove::before { content: '-'; @apply text-fd-diff-remove-symbol; } .diff.add { --fd-counter-color: var(--color-fd-diff-add-symbol); @apply bg-fd-diff-add; } .diff.add::before { content: '+'; @apply text-fd-diff-add-symbol; } .highlighted { --fd-counter-color: var(--color-fd-primary); @apply bg-fd-primary/10; } .highlighted::after { position: absolute; content: ''; @apply inset-y-0 left-0 border-l-2 border-fd-primary/50; } .highlighted-word { padding: 1px; @apply border -my-px border-fd-primary/30 bg-fd-primary/10 rounded-md font-medium; } ``` Sources: [packages/radix-ui/css/lib/shiki.css:10-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/lib/shiki.css#L10-L69), [packages/base-ui/css/lib/shiki.css:10-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L10-L69) When `data-line-numbers` is present on the container, line numbers are generated using CSS counters (`counter-increment: line`), positioning counter values inside a 7-space left column with a color mixed in oklab between `--fd-counter-color` and transparent. ```css &[data-line-numbers] .twoslash-meta-line { padding-left: calc(var(--padding-left) + 7 * var(--spacing)); } &[data-line-numbers] .line { counter-increment: line; padding-left: calc(var(--padding-left) + 7 * var(--spacing)); } &[data-line-numbers] .line::after { position: absolute; content: counter(line); color: color-mix( in oklab, var(--fd-counter-color, var(--color-fd-muted-foreground)) 60%, transparent ); @apply inset-y-0 left-0 w-7 text-right; } } ``` Sources: [packages/radix-ui/css/lib/shiki.css:70-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/lib/shiki.css#L70-L90), [packages/base-ui/css/lib/shiki.css:70-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/lib/shiki.css#L70-L90) ## Specialized Extension Stylesheets ### OpenAPI, AsyncAPI, and API Documentation Presets Supplementary preset stylesheets configure styling rules for API documentation packages by importing shared base definitions and companion package styles. The OpenAPI preset (`packages/openapi/css/preset.css`) imports `./generated/shared.css` and `@import '@fumadocs/api-docs/css/preset.css'`. Similarly, the AsyncAPI preset (`packages/asyncapi/css/preset.css`) imports `./generated/shared.css` and `@import '@fumadocs/api-docs/css/preset.css'`. The core API docs preset (`packages/api-docs/css/preset.css`) imports only `./generated/shared.css`. ```css @import './generated/shared.css'; @import '@fumadocs/api-docs/css/preset.css'; ``` Sources: [packages/openapi/css/preset.css:1-2](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/css/preset.css#L1-L2), [packages/api-docs/css/preset.css:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/css/preset.css#L1-L1), [packages/asyncapi/css/preset.css:1-2](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/css/preset.css#L1-L2) > [!NOTE] > Both OpenAPI and AsyncAPI stylesheets reuse `@fumadocs/api-docs/css/preset.css`, ensuring uniform presentation across all API specification rendering packages. Sources: [packages/openapi/css/preset.css:2-2](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/css/preset.css#L2-L2), [packages/asyncapi/css/preset.css:2-2](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/css/preset.css#L2-L2) ### Python Module Theme Configuration The Python module preset (`packages/python/styles/preset.css`) sets up Tailwind scanning paths and defines custom inline theme variables for Python syntax elements. It scans distribution output files via `@source '../dist/**/*.js'` and configures color variables inside an `@theme inline` block. | Theme Variable | Value | Purpose | | :--- | :--- | :--- | | `--color-fdpy-func` | `oklch(79.2% 0.209 151.711)` | Defines the color token for Python functions. | | `--color-fdpy-class` | `red` | Defines the color token for Python classes. | | `--color-fdpy-attribute` | `oklch(74% 0.238 322.16)` | Defines the color token for Python attributes. | | `--color-fdpy-method` | `blue` | Defines the color token for Python methods. | ```css @source '../dist/**/*.js'; @theme inline { --color-fdpy-func: oklch(79.2% 0.209 151.711); --color-fdpy-class: red; --color-fdpy-attribute: oklch(74% 0.238 322.16); --color-fdpy-method: blue; } ``` Sources: [packages/python/styles/preset.css:1-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/styles/preset.css#L1-L8) ## Tailwind V4 Integration and Bundling ### Global Style Entry Points and Imports Tailwind CSS v4 integration across Fumadocs relies on `@import 'tailwindcss'` statements coupled with layout presets and neutralization layers. The preview package style entry point (`packages/preview/src/styles/globals.css`) imports Tailwind alongside neutral and preset configurations. ```css @import 'tailwindcss'; @import 'fumadocs-ui/css/neutral.css'; @import 'fumadocs-ui/css/preset.css'; ``` Sources: [packages/preview/src/styles/globals.css:1-3](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/styles/globals.css#L1-L3) Both `packages/base-ui/css/style.css` and `packages/radix-ui/css/style.css` follow an identical import structure while additionally defining a base layer rule that configures the body element for flex column layout with a minimum height spanning the viewport. ```css @import 'tailwindcss'; @import './neutral.css'; @import './preset.css'; @layer base { body { @apply flex flex-col min-h-screen; } } ``` Sources: [packages/base-ui/css/style.css:1-9](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/css/style.css#L1-L9), [packages/radix-ui/css/style.css:1-9](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/css/style.css#L1-L9) > [!NOTE] > The root application layout (`packages/preview/src/pages/_root.tsx`) imports `globals.css` and attaches the identical flex column layout utility classes directly to the body element alongside hydration warning suppressions. Sources: [packages/preview/src/pages/_root.tsx:3-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/_root.tsx#L3-L11) ### Vite and Waku Configuration Build tooling for the preview package is handled via Waku configuration (`packages/preview/waku.config.ts`), which integrates Vite plugins including `@tailwindcss/vite` and an internal Fumadocs configuration loader. ```typescript vite: { resolve: { tsconfigPaths: true, }, plugins: [ tailwindcss(), { name: 'internal', config() { return getConfig({ root: process.cwd() }); }, }, ], }, ``` Sources: [packages/preview/waku.config.ts:7-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/waku.config.ts#L7-L21) ### Oxide Scanner and Dynamic CSS Compilation The `tsdown` build configuration for `packages/base-ui/tsdown.config.ts` incorporates `@tailwindcss/oxide` via a programmatic `Scanner` implementation in `compileInline()`. This scanner extracts utility names from source code patterns and generates layout-specific inline source stylesheets inside `css/generated/`. ```typescript export async function compileInline() { await mkdir('css/generated', { recursive: true }); const scanner = new Scanner({ sources: [ { base: path.resolve('src'), pattern: 'components/**/*.{ts,tsx}', negated: false, }, { base: path.resolve('src'), pattern: 'layouts/shared/**/*.{ts,tsx}', negated: false, }, { base: path.resolve('src'), pattern: '*.{ts,tsx}', negated: false, }, ], }); const commonNames = scanner.scan(); await writeFile('css/generated/shared.css', namesToFile(commonNames)); ``` Sources: [packages/base-ui/tsdown.config.ts:50-74](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/tsdown.config.ts#L50-L74) The compilation loop iterates through distinct layout identifiers (`flux`, `notebook`, `home`, and `docs`), filters out utilities already included in the shared scanner results, and writes out individual layout CSS files. ```typescript const layouts = ['flux', 'notebook', 'home', 'docs']; const commonNameSet = new Set(commonNames); for (const layout of layouts) { const scanner = new Scanner({ sources: [ { base: path.resolve('src'), pattern: `layouts/${layout}/**/*.{ts,tsx}`, negated: false, }, ], }); await writeFile( `css/generated/${layout}.css`, namesToFile(scanner.scan().filter((name) => !commonNameSet.has(name))), ); } console.log('generated CSS files'); } ``` Sources: [packages/base-ui/tsdown.config.ts:75-96](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/tsdown.config.ts#L75-L96) > [!CAUTION] > The Oxide scanner explicitly excludes negated patterns and separates layout components so that shared utility names are compiled once into `shared.css` while layout-specific classes remain isolated in their respective generated files. Sources: [packages/base-ui/tsdown.config.ts:52-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/tsdown.config.ts#L52-L70), [packages/base-ui/tsdown.config.ts:78-92](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/tsdown.config.ts#L78-L92) ## Related - [Base UI Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/base-ui-components) --- ## Technical docs: API Docs Primitives URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/api-docs-primitives
Relevant source files The following files were used as context for generating this wiki page: - [packages/api-docs/src/schema/sample.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/sample.ts) - [packages/api-docs/src/components/schema/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx) - [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx) - [packages/openapi/src/ui/operation/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/index.tsx) - [packages/api-docs/src/components/schema/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/index.tsx) - [packages/asyncapi/src/ui/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/index.tsx) - [packages/api-docs/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json) - [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx) - [packages/cli/src/commands/shared.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts) - [packages/api-docs/src/schema/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/index.ts) - [packages/openapi/src/utils/document/dereference.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/document/dereference.ts) - [packages/openapi/src/utils/schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/schema.ts) - [packages/asyncapi/src/ui/bindings/shared.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx) - [packages/openapi/src/utils/get-example-requests.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/openapi/src/ui/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/index.tsx) - [packages/openapi/src/ui/operation/response-tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/response-tabs.tsx) - [packages/api-docs/src/schema/to-string.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/to-string.ts) - [packages/asyncapi/src/utils/document/dereference.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/document/dereference.ts) - [packages/openapi/src/types.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/types.ts) - [packages/python/src/components/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx) - [packages/openapi/src/scalar/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/scalar/client.tsx) - [packages/asyncapi/src/utils/schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/schema.ts) - [packages/openapi/css/preset.css](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/css/preset.css) - [packages/openapi/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/index.ts) - [packages/base-ui/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts) - [packages/openapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json) - [packages/api-docs/src/codegen.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/codegen.ts) - [packages/api-docs/src/schema/bundle.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/bundle.ts) - [packages/api-docs/src/auto-anchor/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/auto-anchor/index.ts)
## Overview API Docs Primitives (`@fumadocs/api-docs`) provides the underlying schema parsing, type formatting, mocking, rendering, and navigation infrastructure shared across Fumadocs API documentation packages like [OpenAPI Interactive UI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/openapi-interactive-ui) and [AsyncAPI Document Processing](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/asyncapi-document-processing). By establishing a unified runtime foundation, it solves the fragmentation of handling complex JSON Schema specifications across different protocol adapters and frontend layouts. Key design decisions include synchronous reference resolution, recursive AST generation for hierarchical properties, and decoupled client-server component splitting that maintains interactive deep-linking and state preservation. It interfaces directly with specification document parsers and UI layout renderers to power interactive schema property exploration, code sample integration, and deep-linkable slug generation. Sources: [packages/api-docs/package.json:1-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L1-L45), [packages/api-docs/src/components/schema/client.tsx:73-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx#L73-L114), [packages/api-docs/src/components/schema/index.tsx:89-112](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/index.tsx#L89-L112) ## Package architecture and shared contracts ### Package exports and module layout The `@fumadocs/api-docs` package exposes a modular export structure defined in `package.json`, mapping internal build outputs to explicit subpath imports for schema processing, interactive components, code generation, and utilities. ```json "exports": { "./auto-anchor": "./dist/auto-anchor/index.js", "./auto-anchor/client": "./dist/auto-anchor/client.js", "./codegen": "./dist/codegen.js", "./components/accordion": "./dist/components/accordion.js", "./components/dialog": "./dist/components/dialog.js", "./components/input": "./dist/components/input.js", "./components/playground/inputs": "./dist/components/playground/inputs.js", "./components/playground/schema": "./dist/components/playground/schema.js", "./components/schema": "./dist/components/schema/index.js", "./components/schema/client": "./dist/components/schema/client.js", "./components/select": "./dist/components/select.js", "./components/select-tab": "./dist/components/select-tab.js", "./components/spinner": "./dist/components/spinner.js", "./i18n": "./dist/i18n.js", "./schema": "./dist/schema/index.js", "./schema/bundle": "./dist/schema/bundle.js", "./schema/dereference": "./dist/schema/dereference.js", "./schema/merge": "./dist/schema/merge.js", "./schema/ref": "./dist/schema/ref.js", "./schema/resolve-ref": "./dist/schema/resolve-ref.js", "./schema/sample": "./dist/schema/sample.js", "./schema/to-string": "./dist/schema/to-string.js", "./utils/id-to-title": "./dist/utils/id-to-title.js", "./utils/url": "./dist/utils/url.js", "./package.json": "./package.json", "./css/*": "./css/*" }, ``` Sources: [packages/api-docs/package.json:18-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json#L18-L45) ### Core type definitions and runtime contracts The core schema architecture relies on utility types and type guards that handle JSON Schema definitions (following draft 2020-12) and reference stripping. `NoReference` recursively eliminates `$ref` reference objects from arbitrary types, while `ParsedSchema` unions standard JSON Schema definitions with extension properties such as `x-playground-lazy` and discriminator mappings. ```typescript import type { JSONSchema } from 'json-schema-typed/draft-2020-12'; type ReferenceObject = { $ref: string }; export type NoReference = T extends (infer I)[] ? NoReference[] : T extends ReferenceObject ? Exclude : T extends object ? { [K in keyof T]: NoReference; } : T; export type NoReferenceSwallow = T extends ReferenceObject ? Exclude : T; export type ParsedSchema = | (JSONSchema & { 'x-playground-lazy'?: boolean; discriminator?: { propertyName?: string; mapping?: Record; }; }) | boolean; ``` Sources: [packages/api-docs/src/schema/index.ts:1-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/index.ts#L1-L25) The `SchemaResolver` contract defines the shape for functions that take a `ParsedSchema` and return a shallowly dereferenced schema alongside an optional `$ref` string. ```typescript export type SchemaResolver = (schema: ParsedSchema) => { /** shallowly dereferenced schema */ dereferenced: ParsedSchema; /** the ref value (if dereferenced) */ $ref?: string; }; ``` Sources: [packages/api-docs/src/schema/index.ts:27-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/index.ts#L27-L32) > [!NOTE] > `SchemaResolver` performs a shallow dereference step rather than a deep recursive unrolling, preserving reference boundaries until explicit traversal or sampling occurs. ### Bundling primitives and code generation registries Schema bundling relies on re-exporting the `bundle` function directly from `@apidevtools/json-schema-ref-parser` to combine external JSON reference files into a unified document structure. ```typescript export { bundle } from '@apidevtools/json-schema-ref-parser'; ``` Sources: [packages/api-docs/src/schema/bundle.ts:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/bundle.ts#L1-L1) To support [Code Sample Generators](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/code-sample-generators), the package provides `CodeUsageGeneratorRegistry` and `createCodeUsageGeneratorRegistry`, managing language-specific code generators through registration, retrieval, inline definition, and removal operations. ```typescript export interface CodeUsageGeneratorRegistry { add: (id: string, generator: CodeUsageGenerator) => void; get: (id: string) => CodeUsageGenerator | undefined; addInline: (generator: InlineCodeUsageGenerator) => void; /** * @returns if the generator is removed */ remove: (id: string) => boolean; map: () => Map>; } /** * Generate code example for given programming language */ export interface CodeUsageGenerator { generate: (data: Data, context: Context) => string; lang: string; label?: string; } /** * Generate code example for given programming language */ export interface InlineCodeUsageGenerator { id?: string; lang: string; label?: string; /** * either: * - code * - a function imported from a file with "use client" directive * - false (disabled) */ source?: string | CodeUsageGeneratorFn | false; } export function createCodeUsageGeneratorRegistry( inherit?: CodeUsageGeneratorRegistry, ): CodeUsageGeneratorRegistry { ``` Sources: [packages/api-docs/src/codegen.ts:1-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/codegen.ts#L1-L39) > [!IMPORTANT] > When adding inline code usage generators via `addInline`, if the source property evaluates to falsy or `false`, the registry automatically deletes the generator entry matching the language or identifier. ## Synchronous schema dereferencing ### Dereferencing mechanics in OpenAPI documents OpenAPI document processing relies on synchronous schema dereferencing via `dereferenceBundledDocument`, which converts a bundled specification document into a fully resolved structure devoid of local or external reference pointers. This function initializes a `Map` instance to track original reference strings (`$ref`) mapped to their corresponding schema objects. ```typescript export function dereferenceBundledDocument(bundled: Document): DereferencedDocument { const dereferenceMap = new Map(); return { bundled, dereferenced: dereferenceSync(bundled as JSONSchema, { setOriginalRef(schema, ref) { dereferenceMap.set(schema as object, ref); }, }) as NoReference, getRawRef(obj: object) { return dereferenceMap.get(obj); }, }; } ``` Sources: [packages/openapi/src/utils/document/dereference.ts:20-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/document/dereference.ts#L20-L34) The underlying dereference implementation uses `dereferenceSync` from `@apidevtools/json-schema-ref-parser` (re-exported via `@fumadocs/api-docs/schema/dereference`) cast to `JSONSchema` from `json-schema-typed/draft-2020-12`. During this traversal, the `setOriginalRef` callback intercepts each resolved schema node and populates the tracking map with `dereferenceMap.set(schema as object, ref)`, enabling downstream lookups of raw reference identifiers via `getRawRef(obj)`. ```typescript export interface DereferencedDocument { /** * dereferenced document */ dereferenced: NoReference; /** * Get raw $ref from dereferenced object */ getRawRef: (obj: object) => string | undefined; bundled: Document; } ``` Sources: [packages/openapi/src/utils/document/dereference.ts:6-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/document/dereference.ts#L6-L18) > [!NOTE] > `DereferencedDocument` exposes three properties: `bundled` for the original specification, `dereferenced` typed as `NoReference` for the fully unrolled AST, and `getRawRef` to retrieve original reference strings from any dereferenced object instance. ### AsyncAPI document dereferencing contracts AsyncAPI document processing adopts an identical architectural pattern for synchronous reference resolution through `packages/asyncapi/src/utils/document/dereference.ts`. It wraps `dereferenceSync` to process `AsyncAPIObject` definitions, maintaining a dedicated `dereferenceMap` to track source references across asynchronous message schemas and protocol components. ```typescript export function dereferenceBundledDocument(bundled: AsyncAPIObject): DereferencedDocument { const dereferenceMap = new Map(); return { bundled, dereferenced: dereferenceSync(bundled as JSONSchema, { setOriginalRef(schema, ref) { dereferenceMap.set(schema as object, ref); }, }) as NoReference, getRawRef(obj: object) { return dereferenceMap.get(obj); }, }; } ``` Sources: [packages/asyncapi/src/utils/document/dereference.ts:20-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/document/dereference.ts#L20-L34) The resulting `DereferencedDocument` interface for AsyncAPI returns `NoReference` alongside the raw reference lookup utility and the original bundled specification object. ```typescript export interface DereferencedDocument { /** * dereferenced document */ dereferenced: NoReference; /** * Get raw $ref from dereferenced object */ getRawRef: (obj: object) => string | undefined; bundled: AsyncAPIObject; } ``` Sources: [packages/asyncapi/src/utils/document/dereference.ts:6-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/document/dereference.ts#L6-L18) > [!WARNING] > Both OpenAPI and AsyncAPI dereference pipelines cast their respective document types to `JSONSchema` during `dereferenceSync` invocation, requiring structural compatibility with JSON Schema Draft 2020-12 definitions. ### Reference bundling primitives Underpinning both protocol dereferencing utilities, reference bundling relies on the core `bundle` export from `@apidevtools/json-schema-ref-parser` to aggregate distributed references into a cohesive self-contained specification file prior to synchronous traversal. ```typescript export { bundle } from '@apidevtools/json-schema-ref-parser'; ``` Sources: [packages/api-docs/src/schema/bundle.ts:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/bundle.ts#L1-L1) > [!IMPORTANT] > Bundling must precede synchronous dereferencing whenever specification files reference external file paths or network URIs, as `dereferenceSync` operates entirely in-memory on the consolidated document structure. ## Mock data sampling and traversal ### Sample options and type inference Mock data generation converts JSON schema definitions into concrete payloads through `sample` and internal traversal routines. The configuration accepts specific flags defined in `JsonSchemaSampleOptions`, governing object traversal depths, schema property omissions, and pattern generation. | Option | Type | Default | Purpose | | :--- | :--- | :--- | :--- | | `skipNonRequired` | boolean | — | Omits schema properties not marked as required | | `skipReadOnly` | boolean | `false` | Omits properties designated as read-only | | `skipWriteOnly` | boolean | — | Omits properties designated as write-only | | `quiet` | boolean | — | Suppresses warnings during sampling | | `enablePatterns` | boolean | — | Enables generation from regular expressions | | `maxSampleDepth` | number | `15` | Limits recursion depth during traversal | Sources: [packages/api-docs/src/schema/sample.ts:21-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/sample.ts#L21-L37) When schemas omit explicit type declarations, `inferType` inspects validation keywords to deduce the expected data type. It maps attributes like `multipleOf`, `maximum`, `minimum`, `maxLength`, `pattern`, `items`, `properties`, and `required` to primitive types such as `'number'`, `'string'`, `'array'`, or `'object'`. ```typescript function inferType(schema: SchemaDoc): string | null { if (schema.type !== undefined) { const t = schema.type; return Array.isArray(t) ? (t.length === 0 ? null : String(t[0])) : String(t); } const keywordTypes: Record = { multipleOf: 'number', maximum: 'number', exclusiveMaximum: 'number', minimum: 'number', exclusiveMinimum: 'number', maxLength: 'string', minLength: 'string', pattern: 'string', items: 'array', maxItems: 'array', minItems: 'array', uniqueItems: 'array', additionalItems: 'array', maxProperties: 'object', minProperties: 'object', required: 'object', additionalProperties: 'object', properties: 'object', patternProperties: 'object', dependencies: 'object', }; for (const [kw, ty] of Object.entries(keywordTypes)) { if (schema[kw] !== undefined) return ty; } return null; } ``` Sources: [packages/api-docs/src/schema/sample.ts:51-84](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/sample.ts#L51-L84) > [!NOTE] > If a schema defines an array of types, `inferType` evaluates the first array element after checking for empty type arrays, returning `null` if no type determination is possible. ### Request example generation workflow Request example generation uses `getExampleRequests` to construct client payloads from operation definitions, parameter lists, and request bodies. It extracts media types using `getPreferredType` and populates path, query, header, and cookie parameters by resolving examples or invoking `sample` on parameter schemas. ```typescript export function getExampleRequests({ path, method, ctx, operation, pathItem, }: { path: string; pathItem: NoReference; method: HttpMethods; operation: NoReference; ctx: RenderContext; }): ExampleRequestItem[] { const requestBody = operation.requestBody; const media = requestBody?.content ? getPreferredType(requestBody.content) : null; const bodyOfType = media ? requestBody!.content![media] : null; const parameters = [...(operation.parameters ?? []), ...(pathItem.parameters ?? [])]; if (bodyOfType?.examples) { const result: ExampleRequestItem[] = []; for (const [key, value] of Object.entries(bodyOfType.examples)) { const data = getRequestData({ path, body: operation.requestBody, parameters, sampleKey: key, method, }); result.push({ id: key, name: value.summary || key, description: value.description, data, encoded: encodeRequestData(data, ctx.mediaAdapters, parameters), }); } if (result.length > 0) return result; } const data = getRequestData({ path, body: operation.requestBody, method, parameters }); return [ { id: '_default', name: 'Default', description: typeof bodyOfType?.schema === 'object' ? bodyOfType.schema.description : undefined, data, encoded: encodeRequestData(data, ctx.mediaAdapters, parameters), }, ]; } ``` Sources: [packages/openapi/src/utils/get-example-requests.ts:23-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L23-L76) When processing request bodies, `getRequestData` checks for explicit examples or individual example values before falling back to programmatic sampling via `sample`. HTTP methods dictate the read-only and write-only sampling flags passed to the sampler. ```typescript function getRequestData({ method, path, parameters, sampleKey, body, }: { path: string; sampleKey?: string; method: HttpMethods; parameters: NoReference[]; body?: NoReference; }): RawRequestData { const result: RawRequestData = { path: {}, cookie: {}, header: {}, query: {}, method: method, }; for (const param of parameters) { let value = pickExample(param as never); if (value === undefined && param.required) { if (param.schema) { value = sample(param.schema as object); } else if (param.content) { const type = getPreferredType(param.content); const content = type ? param.content[type] : undefined; if (!content || !content.schema) throw new Error( `Cannot find "${param.name}" parameter info for media type "${type}" in ${path} ${method}`, ); value = sample(content.schema as object); } } switch (param.in) { case 'cookie': result.cookie[param.name!] = value; break; case 'header': result.header[param.name!] = value; break; case 'query': result.query[param.name!] = value; break; default: result.path[param.name!] = value; } } if (body?.content) { const type = getPreferredType(body.content); if (!type) throw new Error(`Cannot find body schema for ${path} ${method}: missing media type`); result.bodyMediaType = type as RawRequestData['bodyMediaType']; const bodyOfType = body.content[type]; if (bodyOfType.examples && sampleKey) { result.body = bodyOfType.examples[sampleKey].value; } else if (bodyOfType.example) { result.body = bodyOfType.example; } else { result.body = sample((bodyOfType?.schema ?? {}) as object, { skipReadOnly: method !== 'get', skipWriteOnly: method === 'get', skipNonRequired: true, }); } } return result; } ``` Sources: [packages/openapi/src/utils/get-example-requests.ts:78-152](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L78-L152) > [!WARNING] > For HTTP `GET` requests, `getRequestData` explicitly configures `skipReadOnly: false` and `skipWriteOnly: true`, while mutating these flags inversely for methods that transmit write payloads. ## Schema string conversion and formatting ### Format flags and string conversion logic The `schemaToString` utility transforms parsed schema objects into readable string representations. It accepts an optional `SchemaResolver` function and formatting flags defined in `FormatFlags`. ```typescript export enum FormatFlags { None = 0, UseAlias = 1 << 0, } export function schemaToString( value: ParsedSchema, resolver?: SchemaResolver, flags: FormatFlags = FormatFlags.None, ): string { ``` Sources: [packages/api-docs/src/schema/to-string.ts:3-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/to-string.ts#L3-L12) | Constant | Value | Purpose | | :--- | :--- | :--- | | `FormatFlags.None` | `0` | Default formatting without special alias resolution | | `FormatFlags.UseAlias` | `1` | Resolves schema titles or reference identifiers | Sources: [packages/api-docs/src/schema/to-string.ts:3-6](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/to-string.ts#L3-L6) > [!NOTE] > When `FormatFlags.UseAlias` is active, `schemaToString` checks for a `schema.title` property or parses the trailing segment of a raw `$ref` string before falling back to type-level serialization. ### Type resolution and composition rules The internal `run` function handles boolean schemas, returning `'any'` for `true` and `'never'` for `false`. Array types are formatted recursively into `array` structures where inner item types are evaluated with alias resolution enabled. ```typescript if (schema.type === 'array') return `array<${schema.items ? run(schema.items, flags | FormatFlags.UseAlias) : 'unknown'}>`; ``` Sources: [packages/api-docs/src/schema/to-string.ts:59-61](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/to-string.ts#L59-L61) Composed schemas like `oneOf`, `anyOf`, and `allOf` utilize a helper `union` function to aggregate distinct member types. When both `oneOf` and `anyOf` are present on a schema, they combine with an intersection operator. ```typescript if (schema.oneOf && schema.anyOf) { return `(${union(schema.oneOf, ' | ', flags)}) & (${union(schema.anyOf, ' | ', flags)})`; } ``` Sources: [packages/api-docs/src/schema/to-string.ts:62-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/to-string.ts#L62-L64) > [!WARNING] > Binary string formats (`schema.type === 'string'` and `schema.format === 'binary'`) are explicitly converted to the `'file'` type keyword rather than retaining their underlying schema representation. ## Interactive schema renderer components ### Server and client component tree generation The interactive schema renderer architecture is split between server-side generation utilities and client-side tree navigation components. The server entry point invokes `generateSchemaUI` to build a normalized schema record (`SchemaUIGeneratedData`) containing a root reference pointer `$root` and a dictionary of dereferenced types `refs`. During this phase, property visibility flags like `readOnly` and `writeOnly` dictate which fields are included in object property lists, while `scanRefs` recursively traverses object properties, array items, and union types. ```tsx export interface SchemaUIGeneratedData { $root: string; refs: Record; } export function Schema({ client, root, readOnly, writeOnly, resolver, showExample, renderMarkdown, }: SchemaUIOptions) { const translations = useTranslations().translations; const generated = useMemo(() => { return generateSchemaUI({ root, resolver, readOnly, writeOnly, showExample, renderMarkdown, translations, }); }, [root, readOnly, writeOnly, resolver, showExample, renderMarkdown, translations]); return ; } export function generateSchemaUI({ root, resolver, renderMarkdown, readOnly = false, writeOnly = false, showExample = false, translations = {}, }: Omit & { translations?: Partial>; }): SchemaUIGeneratedData { ``` Sources: [packages/api-docs/src/components/schema/index.tsx:84-124](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/index.tsx#L84-L124) The generated schema record is passed into the `SchemaUI` client component, which manages the active navigation path (`PathItemType[]`) and anchor state. When rendered via AsyncAPI or OpenAPI bindings, the execution flows through specific integration wrappers that resolve schema identifiers and translation contexts. ```mermaid sequenceDiagram participant AsyncAPI as createAsyncAPIPage participant OpenAPI as createOpenAPIPageBase participant SchemaComp as Schema participant GenUI as generateSchemaUI AsyncAPI->>SchemaComp: invokes Schema OpenAPI->>SchemaComp: invokes Schema SchemaComp->>GenUI: generates SchemaUIGeneratedData ``` Sources: [packages/api-docs/src/components/schema/client.tsx:73-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx#L73-L114), [packages/asyncapi/src/ui/index.tsx:197-203](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/index.tsx#L197-L203), [packages/openapi/src/ui/base.tsx:118-125](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx#L118-L125) 1. `createAsyncAPIPage` or `createOpenAPIPageBase` initializes the rendering context and delegates to the `Schema` component. 2. `Schema` executes `generateSchemaUI` to produce the normalized reference dictionary and root identifier. 3. `SchemaUI` mounts the client state provider, initializing the path stack with the root schema reference and root anchor ID. Sources: [packages/api-docs/src/components/schema/client.tsx:83-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx#L83-L114), [packages/api-docs/src/components/schema/index.tsx:89-112](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/index.tsx#L89-L112), [packages/asyncapi/src/ui/index.tsx:197-203](https://github.com/blade47/fumadocs/bin/../src/ui/index.tsx), [packages/openapi/src/ui/base.tsx:118-125](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx#L118-L125) > [!NOTE] > `SchemaUI` registers an `useEffect` hook that inspects `window.location.search` for a `path` parameter and `s-highlight` slug, automatically decoding the traversal stack and scrolling the target property container into view upon initial hydration. ### Schema property visibility and filtering Object schema property generation incorporates strict filtering rules based on visibility flags and property types. When iterating over schema properties, pattern properties, and additional properties, `generateSchemaUI` evaluates each candidate property against visibility criteria. ```tsx if (schema.type === 'object') { const out: SchemaData = { type: 'object', props: [], ...base(schema), }; refs[id] = out; const { properties = {}, patternProperties, additionalProperties } = schema; const props = Object.entries(properties); if (patternProperties) props.push(...Object.entries(patternProperties)); for (const [key, prop] of props) { if (!prop || !isVisible(prop)) continue; const $type = getSchemaId(prop); scanRefs($type, prop); out.props.push({ $type, name: key, required: schema.required?.includes(key) ?? false, }); } if (additionalProperties && isVisible(additionalProperties)) { const $type = getSchemaId(additionalProperties); scanRefs($type, additionalProperties); out.props.push({ $type, name: '[key: string]', required: false, }); } return; ``` Sources: [packages/api-docs/src/components/schema/index.tsx:351-384](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/index.tsx#L351-L384) | Property Type / Field | Inclusion Condition | Default Behavior | | :--- | :--- | :--- | | Standard Properties (`properties`) | `prop` is defined and `isVisible(prop)` returns `true` | Evaluated and pushed to object properties | | Pattern Properties (`patternProperties`) | Appended to property entries when present | Evaluated alongside standard properties | | Additional Properties (`additionalProperties`) | `additionalProperties` is truthy and visible | Appended as `[key: string]` with `required: false` | Sources: [packages/api-docs/src/components/schema/index.tsx:359-383](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/index.tsx#L359-L383) > [!WARNING] > If a property schema evaluates to invisible under current `readOnly` or `writeOnly` configurations, it is skipped entirely during reference scanning, preventing hidden data fields from populating client popovers and generated type trees. ## Navigation anchoring and UI controls ### Anchor slug generation and prefixing Fumadocs api-docs uses `github-slugger` to produce deep-link anchor slugs for schema components and properties. The `anchorSegments` utility function accepts an arbitrary list of string segments, applying `slug()` mapping to each non-empty segment unless prefixed with a null character (`\0`), which forces the segment to be preserved verbatim. ```typescript import { slug } from 'github-slugger'; /** slugify segments, append `\0` to keep segment as-is */ export function anchorSegments(...segs: string[]): string { const mapped: string[] = []; for (const seg of segs) { if (seg.startsWith('\0')) { mapped.push(seg.slice(1)); } else if (seg.length > 0) { mapped.push(slug(seg)); } } return mapped.join('.'); } ``` Sources: [packages/api-docs/src/auto-anchor/index.ts:1-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/auto-anchor/index.ts#L1-L14) | Function / Helper | Signature | Description | | :--- | :--- | :--- | | `anchorSegments` | `(...segs: string[]) => string` | Slugifies segments, joining them with dots (`.`), while verbatim segments are unmasked via `\0` prefix slicing. | | `anchorIdStartsWith` | `(id1: string, id2: string) => boolean` | Evaluates hierarchical prefix matches between anchor IDs, returning `true` if `id1` equals `id2` or starts with `id2.`. | Sources: [packages/api-docs/src/auto-anchor/index.ts:4-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/auto-anchor/index.ts#L4-L21) > [!NOTE] > When `SchemaUI` mounts, it registers its root identifier using `useAnchorId([name])`. It tracks `ExcludedFromAutoAnchor` caches to ensure initial URL deep-link parameters (`path` and `s-highlight`) trigger smooth scrolling into view only on the first hydration pass. ### Interactive popover state and scroll management The interactive schema renderer uses a React context provider (`StateContextType`) to manage the current traversal path (`path` array of `PathItemType` objects), root anchor ID, and popover triggers. When users click nested object types, `renderTypeInfoTrigger` controls a Radix UI `Popover` whose open state depends on whether the path length exceeds 1, matching the target reference and name while the root container is not closed. ```tsx interface PathItemType { name: string; $ref: string; scrollTop?: number; /** property name of highlighted field, only applicable for objects */ highlighted?: string; tabValues?: string[]; /** popover state, only applicable for root */ closed?: boolean; } interface StateContextType { rootId: string; /** the first tiem will always be the root item */ path: PathItemType[]; setPath: (path: PathItemType[]) => void; generated: SchemaUIGeneratedData; renderTypeInfoTrigger: (props: { pathName: string; $ref: string; children: ReactNode; }) => ReactNode; } ``` Sources: [packages/api-docs/src/components/schema/client.tsx:34-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx#L34-L56) > [!WARNING] > Popover elements attach a `popoverRef` callback that preserves container scroll positions (`scrollTop`) across nested view switches, enforcing a dynamic minimum height of `200px` (or higher based on client height calculations) and autofocusing inputs marked with `data-object-search-input`. ### Protocol bindings and helper controls AsyncAPI protocol binding UI modules share a common set of layout primitives, formatting utilities, and summary builders to render message headers, channel targets, and operation properties consistently. ```tsx export function formatBindingScalar(value: unknown): string { if (value === null || value === undefined) return ''; if (typeof value === 'boolean') return value ? 'Yes' : 'No'; if (typeof value === 'number') return String(value); if (typeof value === 'string') return value; if (Array.isArray(value)) { return value.map((item) => formatBindingScalar(item)).join(', '); } return JSON.stringify(value); } export function hasBindingFields( binding: Record, ignore: string[] = ['bindingVersion'], ): boolean { return Object.keys(binding).some( (key) => !ignore.includes(key) && !key.startsWith('x-') && binding[key] !== undefined, ); } export function joinBindingSummary( ...parts: (string | undefined | null | false)[] ): string | undefined { const filtered = parts.filter((part): part is string => Boolean(part)); return filtered.length > 0 ? filtered.join(' · ') : undefined; } ``` Sources: [packages/asyncapi/src/ui/bindings/shared.tsx:24-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L24-L50) | Utility Function | Parameter Type | Return Type | Behavior | | :--- | :--- | :--- | :--- | | `formatBindingScalar` | `unknown` | `string` | Converts booleans to `'Yes'` / `'No'`, serializes arrays recursively, or falls back to `JSON.stringify`. | | `hasBindingFields` | `Record, string[]` | `boolean` | Verifies object keys exist while ignoring fields like `'bindingVersion'` and `x-*` extensions. | | `joinBindingSummary` | `(string \| undefined \| null \| false)[]` | `string \| undefined` | Filters falsy items and joins summary segments using `' · '` separators. | Sources: [packages/asyncapi/src/ui/bindings/shared.tsx:24-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L24-L50) > [!TIP] > Components such as `BindingGroup`, `BindingFieldRow`, and `BindingScalarValue` automatically adapt boolean state badges (rendering emerald styles for true values and muted styles for false) and wrap scalar codes inside responsive definition lists (`
`). ## Related - [OpenAPI Document Generation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/openapi-document-generation) - [AsyncAPI Document Processing](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/asyncapi-document-processing) --- ## Technical docs: OpenAPI Document Generation URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/openapi-document-generation
Relevant source files The following files were used as context for generating this wiki page: - [packages/openapi/src/utils/pages/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/builder.ts) - [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx) - [packages/openapi/src/utils/pages/to-text.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-text.ts) - [packages/openapi/src/utils/pages/preset-auto.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/preset-auto.ts) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/asyncapi/src/utils/pages/to-text.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/to-text.ts) - [packages/asyncapi/src/ui/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/index.tsx) - [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx) - [packages/asyncapi/src/utils/pages/preset-auto.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/preset-auto.ts) - [packages/openapi/src/generate-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts) - [packages/asyncapi/src/generate-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/generate-file.ts) - [packages/openapi/src/utils/pages/to-static-data.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-static-data.ts) - [packages/python/src/convert.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/convert.ts) - [packages/asyncapi/src/utils/pages/to-static-data.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/to-static-data.ts) - [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts) - [packages/asyncapi/src/utils/pages/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/builder.ts) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/mdx/src/next/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) - [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts) - [packages/sanity/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts) - [packages/openapi/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/index.ts) - [packages/doc-gen/src/remark-docgen.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-docgen.ts) - [packages/openapi/src/ui/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/index.tsx) - [packages/api-docs/src/components/schema/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/index.tsx) - [packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts) - [packages/openapi/src/utils/document/load.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/document/load.ts) - [packages/mdx/src/core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts) - [packages/asyncapi/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/index.ts) - [packages/obsidian/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/index.ts)
## Overview OpenAPI Document Generation automates the transformation of OpenAPI specifications into structured, type-safe MDX documentation pages for [OpenAPI Interactive UI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/openapi-interactive-ui). By combining document loading, bundling, and schema upgrading through `@scalar/openapi-upgrader` and `@fumadocs/api-docs/schema/bundle`, the package processes input definitions into intermediate entry trees that organize paths, operations, tags, and webhooks. Sources: [packages/openapi/src/utils/document/load.ts:1-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/document/load.ts#L1-L19), [packages/openapi/src/utils/pages/builder.ts:1-61](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/builder.ts#L1-L61) It integrates with server loaders and file generation workflows to serialize static metadata, build table-of-contents trees, and output `.mdx` files alongside navigation manifests. Sources: [packages/openapi/src/server/index.tsx:149-206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx#L149-L206), [packages/openapi/src/generate-file.ts:122-173](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts#L122-L173) ## OpenAPI Specification Ingestion and Upgrading ### Document Loading and Upgrading Pipeline The public API surface for OpenAPI document loading and upgrading processes raw specification inputs through bundling and normalization pipelines. Exported types expose specification versions (`OpenAPIV2`, `OpenAPIV3`, `OpenAPIV3_1`, `OpenAPIV3_2`, and the union `OpenAPI`) alongside media adapters and builder configurations. ```typescript export * from './generate-file'; export type { MediaAdapter } from '@/requests/media/adapter'; export type { RenderContext } from './types'; export type { OperationOutput, OutputEntry, OutputGroup, PageOutput, PagesBuilder, PagesBuilderConfig, WebhookOutput, OperationItem, WebhookItem, GeneratedPageProps, } from './utils/pages/builder'; export type { SchemaToPagesOptions } from './utils/pages/preset-auto'; export type { OpenAPIV3_2, OpenAPIV3_1, OpenAPIV3, OpenAPIV2, OpenAPI } from '@/types/openapi'; ``` Sources: [packages/openapi/src/index.ts:1-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/index.ts#L1-L17) The asynchronous `loadDocument` function accepts either a file path string or a pre-parsed document object. It resolves and bundles external references via `bundle` from `@fumadocs/api-docs/schema/bundle`, then normalizes the resulting structure to target version `3.2` using `upgrade` from `@scalar/openapi-upgrader`. Any resolution or upgrade failure catches the error and throws a descriptive `[OpenAPI] Failed to resolve input` error containing the original cause. ```typescript export async function loadDocument(input: string | Document): Promise<{ bundled: Document; }> { try { let bundled = await bundle(input); bundled = upgrade(bundled, '3.2') as Document; return { bundled }; } catch (e) { throw new Error(`[OpenAPI] Failed to resolve input: ${input}`, { cause: e, }); } } ``` Sources: [packages/openapi/src/utils/document/load.ts:8-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/document/load.ts#L8-L20) > [!WARNING] > If an OpenAPI specification contains circular references or unresolvable external `$ref` pointers, `bundle` throws during `loadDocument` execution, which aborts the loading process before the upgrade step can run. Sources: [packages/openapi/src/utils/document/load.ts:11-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/document/load.ts#L11-L19) ## Document Parsing and Hierarchy Construction ### Intermediate Document Structures and Entry Types The schema parsing engine decomposes bundled OpenAPI documents into structured intermediate outputs using the `fromSchema` function. It provides a `PagesBuilder` context that exposes helper methods like `extract`, `dereferenceShallow`, `fromExtractedOperation`, and `routePathToFilePath` to customize output generation. ```typescript interface BaseEntry { path: string; schemaId: string; info: { title: string; description?: string; deprecated?: boolean; }; } export interface OperationOutput extends BaseEntry { type: 'operation'; item: OperationItem; } export interface WebhookOutput extends BaseEntry { type: 'webhook'; item: WebhookItem; } export interface PageOutput extends BaseEntry { type: 'page'; operations: OperationItem[]; webhooks: WebhookItem[]; /** tag info if the page is generated from a tag. */ tag?: TagObject; } export interface OutputGroup extends BaseEntry { type: 'group'; entries: OutputEntry[]; /** tag info if the group is generated from a tag. */ tag?: TagObject; } export interface WebhookItem { /** * webhook name in `webhooks` */ name: string; method: HttpMethods; } export interface OperationItem { /** * the path of operation in `paths` */ path: string; /** * the HTTP method of operation */ method: HttpMethods; } export type OutputEntry = PageOutput | OperationOutput | WebhookOutput | OutputGroup; ``` Sources: [packages/openapi/src/utils/pages/builder.ts:7-61](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/builder.ts#L7-L61) The parser iterates over `bundled.paths` and `bundled.webhooks` across all supported `methodKeys` to populate extracted operations and webhooks. The `routePathToFilePath` utility transforms route paths by converting characters to lowercase, replacing dots with hyphens, stripping surrounding curly braces from parameter segments, and joining segments with slashes. ```typescript export function fromSchema( schemaId: string, bundled: Document, config: PagesBuilderConfig, ): OutputEntry[] { const files: OutputEntry[] = []; const { toPages } = config; toPages({ id: schemaId, document: bundled, dereferenceShallow: (s) => dereferenceShallow(s, bundled), create(entry) { files.push(entry); }, extract() { const result: ExtractedInfo = { webhooks: [], operations: [] }; for (const [path, pathItem] of Object.entries(bundled.paths ?? {})) { if (!pathItem) continue; for (const methodKey of methodKeys) { if (!pathItem[methodKey]) continue; result.operations.push({ method: methodKey, path, tags: pathItem[methodKey]?.tags, }); } } for (const [name, _pathItem] of Object.entries(bundled.webhooks ?? {})) { const pathItem = dereferenceShallow(_pathItem, bundled); if (!pathItem) continue; for (const methodKey of methodKeys) { if (!pathItem[methodKey]) continue; result.webhooks.push({ method: methodKey, name, tags: pathItem[methodKey]?.tags, }); } } return result; }, routePathToFilePath(path) { return path .toLowerCase() .replaceAll('.', '-') .split('/') .flatMap((v) => { if (v.startsWith('{') && v.endsWith('}')) return v.slice(1, -1); if (v.length === 0) return []; return v; }) .join('/'); }, ``` Sources: [packages/openapi/src/utils/pages/builder.ts:121-181](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/builder.ts#L121-L181) | Output Entry Type | Interface Name | Description | | :--- | :--- | :--- | | `operation` | `OperationOutput` | Represents a single API operation endpoint entry. | | `webhook` | `WebhookOutput` | Represents an event-driven webhook endpoint entry. | | `page` | `PageOutput` | Contains multiple operations and webhooks, with optional tag metadata. | | `group` | `OutputGroup` | Holds a nested collection of child output entries and optional tag info. | Sources: [packages/openapi/src/utils/pages/builder.ts:17-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/builder.ts#L17-L40) > [!NOTE] > When resolving display names for operations, `fromExtractedOperation` evaluates `operation.summary`, then `pathItem.summary`, and falls back to a title-cased `operation.operationId` or the raw path string if neither summary is present. Sources: [packages/openapi/src/utils/pages/builder.ts:195-211](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/builder.ts#L195-L211) ### Execution Walkthrough and Sequence Diagram The hierarchy construction and virtual file translation pipeline processes output entries through a multi-stage call chain. 1. `createOpenAPI` initializes the server state and triggers schema loading. 2. `getVirtualFiles` calls `fromSchema` to generate the raw entry list and invokes `onEntries`. 3. `onEntries` recursively iterates through entry collections or builds `meta.json` navigation lists when meta generation is enabled. 4. `onEntry` receives individual non-group entries and invokes `getPageProps` for each. 5. `getPageProps` constructs the final page property payloads for documentation rendering. ```tsx export function createOpenAPI(options: OpenAPIOptions = {}): OpenAPIServer { const { disableCache = false } = options; const schemaMap = new Map>(); let resolvedInput: SchemaRecord = {}; if (Array.isArray(options.input)) { for (const item of options.input) resolvedInput[item] = item; } else if (options.input) { resolvedInput = options.input; } function getSchema(schemaId: string): Promise { if (!(schemaId in resolvedInput)) { console.warn( `[Fumadocs OpenAPI] the document "${schemaId}" is not listed in the input array, this may be unexpected and won't be cached properly.`, ); // do not cache unlisted documents return loadDocument(schemaId); } if (!disableCache) { const cached = schemaMap.get(schemaId); if (cached) return cached; } const raw = resolvedInput[schemaId]; const output = Promise.resolve(typeof raw === 'function' ? raw() : raw).then(loadDocument); if (!disableCache) schemaMap.set(schemaId, output); return output; } async function getSchemas(): Promise> { const entries = await Promise.all( Object.keys(resolvedInput).map(async (k) => [k, await getSchema(k)]), ); return Object.fromEntries(entries); } async function getVirtualFiles(server: OpenAPIServer, options: OpenAPISourceOptions) { const { baseDir = '', meta = false } = options; const { createAutoPreset } = await import('@/utils/pages/preset-auto'); const { fromSchema } = await import('@/utils/pages/builder'); const files: VirtualFile<{ pageData: OpenAPIPageData; metaData: MetaData; }>[] = []; const schemas = await server.getSchemas(); const builderOptions = createAutoPreset(options); for (const [id, schema] of Object.entries(schemas)) { const list = fromSchema(id, schema.bundled, builderOptions); onEntries(list); function onEntry(entry: PageOutput | OperationOutput | WebhookOutput) { const props = getPageProps(entry); files.push({ type: 'page', path: `${baseDir}/${entry.path}`, data: { ...entry.info, getAPIPageProps() { return this.getOpenAPIPageProps(); }, getClientAPIPageProps() { return this.getOpenAPIPageProps(); }, getOpenAPIPageProps() { return { payload: { bundled: schema.bundled, proxyUrl: server.options.proxyUrl, }, ...props, }; }, getSchema() { return { ``` Sources: [packages/openapi/src/server/index.tsx:111-206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx#L111-L206) ```mermaid sequenceDiagram participant Server as createOpenAPI participant Files as getVirtualFiles participant Entries as onEntries participant Entry as onEntry participant Props as getPageProps Server->>Files: getVirtualFiles(server, options) Files->>Entries: onEntries(list) Entries->>Entry: onEntry(entry) Entry->>Props: getPageProps(entry) ``` Sources: [packages/openapi/src/server/index.tsx:111-206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx#L111-L206) > [!CAUTION] > If `meta` is configured with folder styles, `onEntries` computes relative paths using `path.relative` between parent and child entries; omitting valid parent relationships causes malformed `meta.json` page arrays. Sources: [packages/openapi/src/server/index.tsx:221-252](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx#L221-L252) ## Static Data and Table Extraction ### Slugged Metadata Generation The `toStaticData` utility function builds [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) items (`TOCItemType[]`) and structured metadata (`StructuredData`) for generated documentation pages. It accepts a `GeneratedPageProps` page configuration and an OpenAPI `Document`, iterating through both configured operations and webhooks. ```typescript export function toStaticData( page: GeneratedPageProps, doc: Document, ): { toc: TOCItemType[]; structuredData: StructuredData; } { ``` Sources: [packages/openapi/src/utils/pages/to-static-data.ts:9-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-static-data.ts#L9-L15) For each operation or webhook entry, `toStaticData` resolves the operation object by shallow dereferencing path or webhook maps against the root document. If `page.showTitle` is enabled and `item.operationId` exists, it calculates a heading title using `item.summary`, falls back to `idToTitle(item.operationId)`, or defaults to the path string. The `Slugger` utility from `github-slugger` generates URL-safe anchors (`#id`) for the table of contents and heading arrays. ```typescript const slugger = new Slugger(); const toc: TOCItemType[] = []; const structuredData: StructuredData = { headings: [], contents: [] }; function pathItem(item: OperationObject, defaultTitle: string) { if (page.showTitle && item.operationId) { const title = item.summary || (item.operationId ? idToTitle(item.operationId) : defaultTitle); const id = slugger.slug(title); toc.push({ depth: 2, title, url: `#${id}`, }); structuredData.headings.push({ content: title, id, }); } if (item.description) structuredData.contents.push({ content: item.description, heading: structuredData.headings.at(-1)?.id, }); } ``` Sources: [packages/openapi/src/utils/pages/to-static-data.ts:16-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-static-data.ts#L16-L41) > [!NOTE] > If an operation defines a `description`, it is automatically appended to `structuredData.contents` linked to the immediately preceding heading identifier. Sources: [packages/openapi/src/utils/pages/to-static-data.ts:36-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-static-data.ts#L36-L41) ### Operation and Webhook Iteration Pipeline The function processes collection loops for both HTTP path operations and asynchronous webhooks, resolving references through `dereferenceShallow`. ```typescript for (const item of page.operations ?? []) { const operation = dereferenceShallow(doc.paths?.[item.path], doc)?.[item.method]; if (!operation) continue; pathItem(operation, item.path); } for (const item of page.webhooks ?? []) { const webhook = dereferenceShallow(doc.webhooks?.[item.name], doc)?.[item.method]; if (!webhook) continue; pathItem(webhook, item.name); } return { toc, structuredData }; ``` Sources: [packages/openapi/src/utils/pages/to-static-data.ts:43-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-static-data.ts#L43-L57) | Collection Source | Lookup Target | Dereference Source | Fallback Title Key | | :--- | :--- | :--- | :--- | | `page.operations` | `doc.paths?.[item.path]` | `doc` | `item.path` | | `page.webhooks` | `doc.webhooks?.[item.name]` | `doc` | `item.name` | Sources: [packages/openapi/src/utils/pages/to-static-data.ts:43-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-static-data.ts#L43-L55) > [!WARNING] > If `dereferenceShallow` returns a falsy operation or webhook object, the iteration skips the entry entirely without adding entries to the table of contents or structured metadata. Sources: [packages/openapi/src/utils/pages/to-static-data.ts:44-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-static-data.ts#L44-L45), [packages/openapi/src/utils/pages/to-static-data.ts:51-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-static-data.ts#L51-L52) ## Virtual File Routing and Presets ### Preset Algorithms and Path Generation The automatic page generation preset configures how endpoint schemas translate into virtual routes. The `createAutoPreset` function inspects `options.name` to determine naming behavior, supporting either custom naming functions or configuration objects with an `algorithm` property set to either `'v1'` or `'v2'`. ```typescript /** * The version of algorithm used to generate file paths. * * v1: Fumadocs OpenAPI v8 * v2: Fumadocs OpenAPI v9 * * @defaultValue v2 */ algorithm?: 'v2' | 'v1'; } ``` Sources: [packages/openapi/src/utils/pages/preset-auto.ts:81-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/preset-auto.ts#L81-L90) When `result.type` is an operation, algorithm `'v2'` uses `operation.operationId` when available. If `algorithm` is `'v1'` or `operationId` is omitted, it falls back to joining `this.routePathToFilePath(result.item.path)` with `result.item.method.toLowerCase()`. For webhooks, algorithm `'v2'` similarly inspects `hook.operationId` via `dereferenceShallow`, falling back to `slugify(result.item.name)`. ```typescript if (result.type === 'operation') { const operation = this.document.paths![result.item.path]![result.item.method]!; if (algorithm === 'v2' && operation.operationId) { return operation.operationId; } return path.join( this.routePathToFilePath(result.item.path), result.item.method.toLowerCase(), ); } const hook = dereferenceShallow(this.document.webhooks![result.item.name], this.document)[ result.item.method ]!; if (algorithm === 'v2' && hook.operationId) { return hook.operationId; } return slugify(result.item.name); }; ``` Sources: [packages/openapi/src/utils/pages/preset-auto.ts:125-147](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/preset-auto.ts#L125-L147) > [!WARNING] > Relying on algorithm `'v2'` without explicit `operationId` definitions on operations or webhooks causes path generation to fall back directly to route path joining or slugified names. Sources: [packages/openapi/src/utils/pages/preset-auto.ts:128-135](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/preset-auto.ts#L128-L135), [packages/openapi/src/utils/pages/preset-auto.ts:142-146](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/preset-auto.ts#L142-L146) ### Virtual File Resolution Workflow The virtual file generation workflow converts loaded schema documents into structured file representations for server integrations. The execution walkthrough follows this exact sequence: `createOpenAPI` instantiates the server instance, which invokes `getVirtualFiles` to iterate over schemas, and passes output lists to `onEntries`. ```mermaid sequenceDiagram participant Server as createOpenAPI participant Files as getVirtualFiles participant Entries as onEntries participant Entry as onEntry Server->>Files: createOpenAPI -> getVirtualFiles Files->>Entries: getVirtualFiles -> onEntries Entries->>Entry: onEntries -> onEntry ``` Sources: [packages/openapi/src/server/index.tsx:111-216](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx#L111-L216) 1. `createOpenAPI` — Initializes `schemaMap` caches and returns the server object containing `getVirtualFiles`. 2. `getVirtualFiles` — Retrieves bundled schemas via `server.getSchemas()`, builds builder options using `createAutoPreset`, and invokes `fromSchema`. 3. `onEntries` — Recursively flattens or structures output entries, respecting `meta` options and `folderStyle` configurations. 4. `onEntry` — Maps each leaf entry into a virtual file object carrying `OpenAPIPageData` props, metadata, and static data handlers. Sources: [packages/openapi/src/server/index.tsx:111-206](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx#L111-L206) > [!NOTE] > If `meta` is enabled as an object with `folderStyle: 'separator'`, group entries push title separators (`---title---`) alongside path references (`...relativePath`) into the emitted `meta.json` pages array. Sources: [packages/openapi/src/server/index.tsx:221-242](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx#L221-L242) ## MDX Document Serialization ### String Template Conversion and Component Layouts The `toText` function converts page outputs, operations, and webhooks into serialized MDX documents by orchestrating frontmatter formatting, metadata insertion, and component layout templates. It accepts an `entry`, a `doc` document object, and `options` of type `PagesToTextOptions`. ```typescript export function toText( entry: PageOutput | OperationOutput | WebhookOutput, doc: Document, options: PagesToTextOptions = {}, ) { const { frontmatter, includeDescription = false } = options; const extend = frontmatter?.( entry.info.title, entry.info.description, entry.type === 'page' ? entry.tag ? { type: 'tag', tag: entry.tag } : { type: 'file' } : { type: 'operation' }, ); const pageProps = getPageProps(entry); if (!includeDescription) { pageProps.showDescription = false; } let meta: InternalOpenAPIMeta = { preload: [entry.schemaId], }; if (entry.type === 'operation' || entry.type === 'webhook') { const operation = entry.item; meta.method = operation.method.toUpperCase(); meta.webhook = entry.type === 'webhook'; meta.deprecated = entry.info.deprecated; } const data = toStaticData(pageProps, doc); return generateDocument( { title: entry.info.title, description: !includeDescription ? entry.info.description : undefined, full: true, ...extend, _openapi: { ...meta, ...data, ...(extend?._openapi as object | undefined), }, }, pageContent(pageProps), options, ); } ``` Sources: [packages/openapi/src/utils/pages/to-text.ts:57-105](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-text.ts#L57-L105) The `pageContent` function generates a React layout component string that exposes `APIPage` and `OpenAPIPage` components for backward compatibility, forwarding `document`, `webhooks`, and `operations` props. ```typescript function pageContent({ showTitle, showDescription, document, webhooks, operations, }: GeneratedPageProps): string { const propStrs: string[] = [`document=${doubleQuote(document)}`]; // filter extra properties in props if (webhooks) { propStrs.push( `webhooks={${JSON.stringify( webhooks.map( (item) => ({ name: item.name, method: item.method, }) satisfies WebhookItem, ), )}}`, ); } if (operations) { propStrs.push( `operations={${JSON.stringify( operations.map( (item) => ({ path: item.path, method: item.method, }) satisfies OperationItem, ), )}}`, ); } if (showTitle) { propStrs.push(`showTitle`); } if (showDescription) { propStrs.push(`showDescription`); } return `export default function Layout(props) { const { APIPage, OpenAPIPage } = props.components ?? {}; // "APIPage" is the old name from v10, this allows both for backward compatibility const Comp = OpenAPIPage ?? APIPage; return ( <> {props.children} ); }`; } ``` Sources: [packages/openapi/src/utils/pages/to-text.ts:153-207](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-text.ts#L153-L207) > [!NOTE] > The `APIPage` component name is preserved from v10 for backward compatibility; if `props.components.OpenAPIPage` is undefined, the layout falls back to `APIPage`. Sources: [packages/openapi/src/utils/pages/to-text.ts:197-199](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-text.ts#L197-L199) ### Frontmatter Formatting and Options The `generateDocument` utility serializes YAML frontmatter using the `js-yaml` `dump` function after stripping undefined properties via `removeUndefined`. It appends auto-generated comments and user-defined MDX component imports. ```typescript export function generateDocument( frontmatter: unknown, content: string, options: PagesToTextOptions, ): string { const { addGeneratedComment = true, imports } = options; const out: string[] = []; const banner = dump(removeUndefined(frontmatter as object)).trimEnd(); if (banner.length > 0) out.push(`---\n${banner}\n---`); if (addGeneratedComment) { let commentContent = 'This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again.'; if (typeof addGeneratedComment === 'string') { commentContent = addGeneratedComment; } commentContent = commentContent.replaceAll('/', '\\/'); out.push(`{/* ${commentContent} */}`); } if (imports) { out.push( ...imports .map((item) => `import { ${item.names.join(', ')} } from ${doubleQuote(item.from)};`) .join('\n'), ); } out.push(content); return out.join('\n\n'); } ``` Sources: [packages/openapi/src/utils/pages/to-text.ts:107-139](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-text.ts#L107-L139) | Option Key | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `imports` | `{ names: string[]; from: string; }[]` | `undefined` | Additional imports of custom MDX components for the generated page. | | `frontmatter` | `(title, description, context) => Record` | `undefined` | Customizes frontmatter fields; a `full: true` property is added by default. | | `includeDescription` | `boolean` | `false` | Controls whether description text is added to the document body instead of frontmatter. | | `addGeneratedComment` | `boolean \| string` | `true` | Adds a comment at the top of generated files indicating they are auto-generated. | Sources: [packages/openapi/src/utils/pages/to-text.ts:17-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-text.ts#L17-L55) > [!WARNING] > `includeDescription` is disabled by default because certain OpenAPI schemas contain invalid descriptions that break Markdown syntax during rendering. Sources: [packages/openapi/src/utils/pages/to-text.ts:38-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-text.ts#L38-L44) ## Static Page File Generation ### Disk Writing Workflow and Watch Mode The `generateFiles` function manages the end-to-end process of writing generated documentation files to the local disk. It accepts a `Config` object, invokes `generateFilesOnly` to resolve output buffers, and recursively creates destination directories using `node:fs/promises` before writing each file. ```typescript export async function generateFiles(options: Config): Promise { if (options.watch) { const { watch } = await import('chokidar'); const subOptions: Config = { ...options, watch: false }; await generateFiles(subOptions); const targets = options.input._getWatchPaths(); console.log(`[Fumadocs OpenAPI] watching ${targets.join(', ')}`); watch(targets, { ignoreInitial: true, }).on('all', () => generateFiles(subOptions)); return; } const files = await generateFilesOnly(options); await Promise.all( files.map(async (file) => { const filePath = path.join(options.output, file.path); await mkdir(path.dirname(filePath), { recursive: true }); await writeFile(filePath, file.content); console.log(`Generated: ${filePath}`); }), ); } ``` Sources: [packages/openapi/src/generate-file.ts:95-120](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts#L95-L120) When `options.watch` is enabled, `generateFiles` spawns a `chokidar` file watcher targeting paths retrieved from `options.input._getWatchPaths()`. Whenever a schema file changes, the watcher triggers a regeneration cycle while setting `watch: false` on suboptions to prevent recursive watcher instantiation. ```typescript if (options.watch) { const { watch } = await import('chokidar'); const subOptions: Config = { ...options, watch: false }; await generateFiles(subOptions); const targets = options.input._getWatchPaths(); console.log(`[Fumadocs OpenAPI] watching ${targets.join(', ')}`); watch(targets, { ignoreInitial: true, }).on('all', () => generateFiles(subOptions)); return; } ``` Sources: [packages/openapi/src/generate-file.ts:96-107](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts#L96-L107) > [!WARNING] > The built-in `watch` flag in `generateFiles` is intended only for simple development cases; it ignores custom input functions and URLs, and it is recommended to configure `chokidar` manually for advanced setups. Sources: [packages/openapi/src/generate-file.ts:83-88](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts#L83-L88) ### Manifest Generation and File Collection The `generateFilesOnly` function iterates over schemas fetched from the OpenAPI server instance, creates auto presets via `createAutoPreset`, and transforms schema entries into `OutputFile` objects. It aggregates generated entries into a `BeforeWriteContext` containing `generated` record maps and `generatedEntries` records. ```typescript export async function generateFilesOnly( options: DistributiveOmit, ): Promise { const schemas = await options.input.getSchemas(); const files: OutputFile[] = []; const generated: Record = {}; const generatedEntries: Record = {}; const entries = Object.entries(schemas); if (entries.length === 0) { throw new Error('No input files found.'); } const preset = createAutoPreset(options); for (const [id, schema] of entries) { const entries = fromSchema(id, schema.bundled, preset); const schemaFiles: OutputFile[] = []; generatedEntries[id] = entries; function scan(entry: OutputEntry) { if (entry.type === 'group') { for (const child of entry.entries) scan(child); return; } schemaFiles.push({ path: entry.path, content: toText(entry, schema.bundled, options), }); } for (const entry of entries) scan(entry); generated[id] = schemaFiles; files.push(...schemaFiles); } const context: BeforeWriteContext = { generated, generatedEntries, }; if (options.index) { files.push(...writeIndexFiles(context, options)); } if (options.meta) { files.push(...generateMeta(context, options.meta === true ? {} : options.meta)); } await options.beforeWrite?.call(context, files); return files; } ``` Sources: [packages/openapi/src/generate-file.ts:122-173](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts#L122-L173) If `options.meta` is configured, `generateMeta` emits `meta.json` manifests for content folders. The `folderStyle` option determines how nested groups are structured within the manifest's `pages` array. ```typescript function generateMeta(context: BeforeWriteContext, options: MetaOptions): OutputFile[] { const files: OutputFile[] = []; const folderStyle = options.folderStyle ?? 'folder'; function scan(entries: OutputEntry[], parent?: OutputGroup) { const pages: string[] = []; for (const entry of entries) { const relativePath = PathUtils.slash( parent ? path.relative(parent.path, entry.path) : entry.path, ); if (entry.type === 'group') { scan(entry.entries, entry); if (folderStyle === 'folder') { pages.push(relativePath); } else { pages.push(`---${entry.info.title}---`, `...${relativePath}`); } } else { pages.push(relativePath.slice(0, -path.extname(entry.path).length)); } } if (pages.length === 0) return; files.push({ path: parent ? path.join(parent.path, 'meta.json') : 'meta.json', content: JSON.stringify( { title: parent?.info.title, description: parent?.info.description, pages, }, null, 2, ), }); } for (const entries of Object.values(context.generatedEntries)) { scan(entries); } return files; } ``` Sources: [packages/openapi/src/generate-file.ts:175-220](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts#L175-L220) | Option Key | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `input` | `OpenAPIServer` | Required | The OpenAPI server object providing schema definitions. | | `output` | `string` | Required | Target output directory path on the file system. | | `index` | `IndexConfig` | `undefined` | Configuration for generating index files with cards linking to generated pages. | | `meta` | `boolean \| MetaOptions` | `undefined` | Enables or configures `meta.json` file generation for navigation structures. | | `beforeWrite` | `(files: OutputFile[]) => void \| Promise` | `undefined` | Lifecycle hook to add, change, or remove output files before disk persistence. | Sources: [packages/openapi/src/generate-file.ts:47-74](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts#L47-L74) > [!NOTE] > When `folderStyle` is set to `'separator'` in `MetaOptions`, group entries emit custom title headers and path references using the format `---title---` and `...relativePath` in the generated `meta.json` file. Sources: [packages/openapi/src/generate-file.ts:177-195](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts#L177-L195) ## Related - [OpenAPI Interactive UI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/openapi-interactive-ui) - [Code Sample Generators](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/code-sample-generators) --- ## Technical docs: OpenAPI Interactive UI URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/openapi-interactive-ui
Relevant source files The following files were used as context for generating this wiki page: - [packages/openapi/src/ui/operation/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/index.tsx) - [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx) - [packages/asyncapi/src/ui/operation/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/operation/index.tsx) - [packages/api-docs/src/components/schema/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx) - [packages/asyncapi/src/ui/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/index.tsx) - [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx) - [packages/openapi/src/ui/operation/usage-tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/usage-tabs.tsx) - [packages/openapi/src/scalar/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/scalar/client.tsx) - [packages/openapi/src/ui/operation/request-tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/request-tabs.tsx) - [packages/openapi/src/ui/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/index.tsx) - [packages/api-docs/src/components/schema/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/index.tsx) - [packages/openapi/src/ui/operation/response-tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/response-tabs.tsx) - [packages/asyncapi/src/ui/api-page.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/api-page.tsx) - [packages/openapi/src/scalar/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/scalar/index.tsx) - [packages/asyncapi/src/ui/bindings/protocols/http.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/openapi/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/index.ts) - [packages/asyncapi/src/ui/bindings/shared.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx) - [packages/asyncapi/src/ui/contexts/api.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/contexts/api.tsx) - [packages/asyncapi/src/ui/bindings/accordion-bindings.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/accordion-bindings.tsx) - [packages/openapi/src/ui/components/markdown.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/components/markdown.tsx) - [packages/openapi/src/ui/contexts/api.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/contexts/api.tsx) - [packages/openapi/src/utils/get-example-requests.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts) - [packages/openapi/src/ui/components/codeblock.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/components/codeblock.tsx) - [packages/asyncapi/src/ui/components/markdown.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/components/markdown.tsx) - [packages/openapi/src/ui/operation/context.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/context.tsx) - [packages/openapi/src/types.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/types.ts) - [packages/openapi/src/requests/media/encode.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/encode.ts) - [packages/radix-ui/src/components/ui/popover.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/popover.tsx)
## Overview OpenAPI Interactive UI provides a component-based documentation rendering layer built on top of parsed OpenAPI and Swagger specifications, parsing Markdown processors, server state providers, and customizable page layouts into interactive API documentation pages. Sources: [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx#L59-L80), [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx#L149-L233), [packages/openapi/src/ui/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/index.tsx#L109-L154) By leveraging [API Docs Primitives](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/api-docs-primitives) and [Code Sample Generators](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/code-sample-generators), the system parses endpoint operations, request bodies, response status codes, and security schemes into rich interactive cards, tabbed request and response viewers, and copy-enabled code blocks. Sources: [packages/openapi/src/ui/operation/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/index.tsx#L42-L255), [packages/openapi/src/ui/operation/request-tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/request-tabs.tsx#L30-L149), [packages/openapi/src/ui/operation/response-tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/response-tabs.tsx#L53-L159) ## Page Creation and Runtime Context ### Initialization and Rendering Pipeline OpenAPI documentation pages initialize their rendering contexts, Markdown processors, and server state by invoking base factory functions that construct client components. The primary initialization sequence proceeds through the following call chain: `createOpenAPIPageBase` → `Schema` → `SchemaUI`. 1. `createOpenAPIPageBase` establishes the base React component, sets up the remark and rehype Markdown processing pipeline with `remarkGfm` and `remarkRehype`, dereferences bundled documents using `dereferenceBundledDocument`, and configures the `RenderContext`. Sources: [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx#L38-L98) 2. `Schema` receives the resolved schema and user options, invokes `generateSchemaUI` to compute schema hierarchies and reference tables, and passes the generated data to the client component. Sources: [packages/api-docs/src/components/schema/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/index.tsx#L89-L112) 3. `SchemaUI` establishes anchor identifiers using `useAnchorId`, tracks object inspection navigation paths via component state, and hydrates interactive popovers or object property trees. Sources: [packages/api-docs/src/components/schema/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx#L83-L184) ```mermaid sequenceDiagram participant base.tsx participant index.tsx (api-docs) participant client.tsx base.tsx->>base.tsx: createOpenAPIPageBase() base.tsx->>index.tsx (api-docs): Schema() index.tsx (api-docs)->>client.tsx: SchemaUI() ``` Sources: [packages/openapi/src/ui/base.tsx:38-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx#L38-L98), [packages/api-docs/src/components/schema/index.tsx:89-112](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/index.tsx#L89-L112), [packages/api-docs/src/components/schema/client.tsx:83-184](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx#L83-L184) > [!NOTE] > `createOpenAPIPageBase` accepts an optional `shiki` factory for [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting) alongside custom options for generating TypeScript definitions via `compile` from `@fumari/json-schema-ts`. Sources: [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx#L38-L56) ### Server State and Context Providers Server state management is coordinated through `ServerProvider` and `RenderContextProvider`, which manage active API servers, URL variables, and local storage persistence. The context infrastructure relies on specific React contexts to supply runtime options across operation cards and schema renderers. | Context Provider | Hook | Purpose | | :--- | :--- | :--- | | `RenderContextProvider` | `useRenderContext()` | Supplies the global `RenderContext` containing schema references, proxy URLs, Shiki options, and code usage generators. | | `ServerProvider` | `useServerContext()` | Manages active server selection, server variables, and persists selected configurations in local storage. | Sources: [packages/openapi/src/ui/contexts/api.tsx:20-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/contexts/api.tsx#L20-L45), [packages/openapi/src/ui/base.tsx:32-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx#L32-L32) > [!WARNING] > Both `useRenderContext` and `useServerContext` throw an error if called outside of their respective provider hierarchy, requiring components to be nested under `` or the corresponding provider wrapper. Sources: [packages/openapi/src/ui/contexts/api.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/contexts/api.tsx#L23-L35) > [!TIP] > `ServerProvider` initializes the active server configuration using `storageKeyPrefix` (defaulting to `fumadocs-openapi-` when using `useStorageKey`) to prevent state conflicts when multiple OpenAPI instances are mounted on the same origin. Sources: [packages/openapi/src/ui/contexts/api.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/contexts/api.tsx#L54-L64), [packages/openapi/src/ui/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/index.tsx#L211-L218) ## Interactive Operation Cards ### Structural Decomposition and Operation Rendering The `Operation` component serves as the core layout engine for individual HTTP endpoint cards and webhooks. It accepts properties defining the operation structure, including `path`, `method`, `operation`, `pathItem`, `type`, and `headingLevel`. When `showTitle` is enabled, the component computes the endpoint title using `operation.summary`, `pathItem.summary`, a humanized version of `operation.operationId` via `idToTitle`, or falls back to the raw `path`. If `operation.deprecated` is true alongside a title, a yellow status badge is rendered; when titles are hidden, deprecation warnings render as an inline callout. ```tsx export function Operation({ type = 'operation', path, operation, pathItem, method, showTitle, showDescription, headingLevel = 2, }: { type?: 'webhook' | 'operation'; path: string; method: HttpMethods; operation: NoReference; pathItem: NoReference; showTitle?: boolean; showDescription?: boolean; headingLevel?: number; }) { const t = useTranslations({ note: 'operation page' }); const ctx = useRenderContext(); const { schema: { dereferenced }, } = ctx; const body = operation.requestBody; let headNode: ReactNode = null; const operationDescription = operation.description ?? pathItem.description; const descriptionNode = showDescription && operationDescription && ( ); let bodyNode: ReactNode = null; let authNode: ReactNode = null; let responseNode: ReactNode = null; let callbacksNode: ReactNode = null; const exampleRequests = useMemo( () => getExampleRequests({ path, operation, method, pathItem, ctx }), [ctx, operation, method, pathItem, path], ); if (showTitle) { const title = operation.summary || pathItem.summary || (operation.operationId ? idToTitle(operation.operationId) : path); headNode = (
{title} {operation.deprecated && ( {t('Deprecated')} )}
); headingLevel++; } else if (operation.deprecated) { headNode = ; } ``` Sources: [packages/openapi/src/ui/operation/index.tsx:42-104](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/index.tsx#L42-L104) > [!WARNING] > Media types defined within `operation.requestBody` are validated against registered media adapters via `isMediaTypeSupported(type, ctx.mediaAdapters)`. If an unsupported media type is encountered, an immediate error is thrown: `Media type ${type} is not supported (in ${path})`. Sources: [packages/openapi/src/ui/operation/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/index.tsx#L125-L130) ### Authentication Schemes and Security Contexts Operations evaluate security requirements by checking `operation.security` with a fallback to `dereferenced.security`. Empty security object entries are filtered out. When securities are present on standard operations (`type === 'operation'`), they populate a tabbed selection interface driven by `SelectTabs`, mapping each security definition entry to its configured scopes and credential schemes retrieved from `dereferenced.components?.securitySchemes`. ```tsx const securities = (operation.security ?? dereferenced.security ?? []).filter( (v) => Object.keys(v).length > 0, ); if (type === 'operation' && securities.length > 0) { const securitySchemes = dereferenced.components?.securitySchemes; const items = securities.map((security, i) => { return { value: String(i), label: (
{Object.entries(security).map(([key, scopes]) => ( {key}{' '} {scopes.length > 0 && ( {scopes.join(', ')} )} ))}
), }; }); authNode = (
{t('Authorization')} {items.length > 1 ? ( ) : (
{items[0].label}
)}
{securities.map((security, i) => ( {Object.entries(security).map(([key, scopes]) => { const scheme = securitySchemes?.[key]; if (!scheme) return; return ; })} ))}
); ``` Sources: [packages/openapi/src/ui/operation/index.tsx:208-255](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/index.tsx#L208-L255) > [!NOTE] > The `Markdown` component delegates parsing to `processMarkdown(md)` from `useRenderContext()` wrapped in a `useMemo` hook, supporting custom `Markdown` component overrides or direct return values from `renderMarkdown`. Sources: [packages/openapi/src/ui/components/markdown.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/components/markdown.tsx#L1-L14) ### Operation Context and State Management The `OperationProvider` component wraps interactive operation components, maintaining local state for selected examples and dispatching updates through a listener registry (`ExampleUpdateListener[]`). When `setExample` or `setExampleData` is invoked, registered listeners receive raw request payload data and encoded request representations to synchronize preview tabs and code generators. ```tsx export function OperationProvider({ route, examples, defaultExampleId, children, }: { route: string; examples: ExampleRequestItem[]; defaultExampleId?: string; children: ReactNode; }) { const [example, setExample] = useState(() => defaultExampleId ?? examples.at(0)?.id); const listeners = useRef([]); return ( ({ example, route, setExample(newKey: string) { const example = examples.find((example) => example.id === newKey); if (!example) return; setExample(newKey); for (const listener of listeners.current) { listener(example.data, example.encoded); } }, examples, setExampleData(data, encoded) { for (const item of examples) { if (item.id === example) { // persistent changes item.data = data; item.encoded = encoded; break; } } for (const listener of listeners.current) { listener(data, encoded); } }, removeListener(listener) { listeners.current = listeners.current.filter((item) => item !== listener); }, addListener(listener) { // initial call to listeners to ensure their data is the latest // this is necessary to avoid race conditions between `useEffect()` const active = examples.find((item) => item.id === example)!; listener(active.data, active.encoded); listeners.current.push(listener); }, }), [example, route, examples], )} > {children} ); } ``` Sources: [packages/openapi/src/ui/operation/context.tsx:20-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/context.tsx#L20-L82) > [!TIP] > `OperationProvider` calls all registered listeners immediately upon registration in `addListener` using the currently active example configuration, preventing race conditions with asynchronous `useEffect` hooks. Sources: [packages/openapi/src/ui/operation/context.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/context.tsx#L67-L74) ## Interactive Schema Viewer Popovers ### Call-Chain Execution Walkthrough Schema inspection relies on an anchored popover architecture defined across shared packages. The trace order begins at page initialization and terminates at the popover container: 1. `createOpenAPIPageBase` builds the render context and passes the resolved document schema. Sources: [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx#L38-L127) 2. `Schema` receives `root`, `resolver`, and `renderMarkdown` options, memoizing generated schema structures. Sources: [packages/api-docs/src/components/schema/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/index.tsx#L89-L112) 3. `SchemaUI` establishes anchor identifiers via `useAnchorId` and manages the current path inspection stack. Sources: [packages/api-docs/src/components/schema/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx#L83-L185) 4. `PopoverContent` renders the floating inspection container using accessible primitives from [Radix UI Primitives](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/radix-ui-primitives). Sources: [packages/radix-ui/src/components/ui/popover.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/popover.tsx#L10-L30) ```mermaid sequenceDiagram participant base as createOpenAPIPageBase participant schema as Schema participant schemaUI as SchemaUI participant popover as PopoverContent base->>schema: Render root schema schema->>schemaUI: Pass generated data & client props schemaUI->>popover: Open inspection popover via trigger state ``` Sources: [packages/openapi/src/ui/base.tsx:38-127](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx#L38-L127), [packages/api-docs/src/components/schema/index.tsx:89-112](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/index.tsx#L89-L112), [packages/api-docs/src/components/schema/client.tsx:83-185](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx#L83-L185), [packages/radix-ui/src/components/ui/popover.tsx:10-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/components/ui/popover.tsx#L10-L30) > [!NOTE] > `ExcludedFromAutoAnchor` tracks parsed root identifiers in a global `Set` to prevent infinite loops when matching hash parameters in URL search strings against active component paths. Sources: [packages/api-docs/src/components/schema/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx#L81-L113) ### State Management and Popover Configuration The interactive schema viewer utilizes shared state context (`StateContextType`) to track root identifiers, traversal paths, and generated schema references. The table below outlines the core properties managed by path items during interactive inspection. | Property | Type | Description | | :--- | :--- | :--- | | `name` | `string` | The property or field name being inspected. | | `$ref` | `string` | Reference identifier pointing to the schema definition. | | `scrollTop` | `number` (optional) | Scroll position preserved across popover transitions. | | `highlighted` | `string` (optional) | Property name of the highlighted field for object structures. | | `tabValues` | `string[]` (optional) | Active tab values for nested representations. | | `closed` | `boolean` (optional) | Explicit popover closure state for the root item. | Sources: [packages/api-docs/src/components/schema/client.tsx:34-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx#L34-L56) > [!TIP] > When `PopoverContent` mounts or updates, `popoverRef` calculates a minimum height threshold using `element.clientHeight + 2` and restores the prior `scrollTop` coordinate from the active path node. Sources: [packages/api-docs/src/components/schema/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/client.tsx#L87-L95) ## Request Parameter Encoding ### Execution Walkthrough and Sequence Request parameters and query strings are prepared during the initial rendering cycle of each operation component OpenAPI Interactive UI. The serialization workflow follows a strict execution path starting from the component and passing through request generation, encoding wrappers, and specific parameter serializers: 1. `Operation` initiates parameter collection from `operation.parameters` and `pathItem.parameters`, passing them along with context to `getExampleRequests`. Sources: [packages/openapi/src/ui/operation/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/index.tsx#L77-L80,L157) 2. `getExampleRequests` calls `getRequestData` to construct raw request objects via example picking or schema sampling, and then invokes `encodeRequestData`. Sources: [packages/openapi/src/utils/get-example-requests.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L45-L59,L65-L74) 3. `encodeRequestData` loops over parameter locations (`cookie`, `query`, `header`, `path`), resolves media encoders, and dispatches parameters to type-specific formatters. Sources: [packages/openapi/src/requests/media/encode.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/encode.ts#L17-L67) 4. `serializeQueryParameter` inspects the parameter style and explosion rules, processing `spaceDelimited`, `pipeDelimited`, `deepObject`, arrays, and objects into final query representations. Sources: [packages/openapi/src/requests/media/encode.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/encode.ts#L164-L222) ```mermaid sequenceDiagram participant op as Operation participant ex as getExampleRequests participant enc as encodeRequestData participant qenc as serializeQueryParameter op->>ex: Pass path, operation, method, pathItem, ctx ex->>enc: Pass raw request data, media adapters, parameters enc->>qenc: Dispatch query parameter object & field configuration ``` Sources: [packages/openapi/src/ui/operation/index.tsx:77-80](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/index.tsx#L77-L80), [packages/openapi/src/utils/get-example-requests.ts:45-74](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L45-L74), [packages/openapi/src/requests/media/encode.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/encode.ts#L17-L67,L164-L222) > [!WARNING] > When `deepObject` style is evaluated for query parameters, nested array behaviors are explicitly treated as undefined by wrapping values with `Array.isArray(v) ? v : [String(v)]` to prevent unexpected formatting edge cases. Sources: [packages/openapi/src/requests/media/encode.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/encode.ts#L186-L194) ### Parameter Serialization Strategies The encoding module handles distinct parameter locations and styles according to OpenAPI specifications. The table below lists the serialization rules and style handlers implemented in the encoder. | Parameter Type / Style | Explode Default | Behavior Description | | :--- | :--- | :--- | | `path` / `label` | `false` | Prefixes the encoded string with a period (`.`) using comma or dotted separators. | | `path` / `matrix` | `false` | Prefixes parameters with semicolon specifiers (`;name=`) for URI path matrix variables. | | `query` / `spaceDelimited` | `false` | Joins array elements using a single space character (` `) when explosion is disabled. | | `query` / `pipeDelimited` | `false` | Joins array elements using a pipe character (`|`) when explosion is disabled. | | `query` / `deepObject` | `true` | Expands nested object properties into bracketed query keys (`param[key]=value`). | | `header` / `simple` | `false` | Joins array and object values using comma delimiters based on the explode flag. | Sources: [packages/openapi/src/requests/media/encode.ts:83-252](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/encode.ts#L83-L252) > [!TIP] > If a parameter defines custom media adapters via its `content` field, `getMediaEncoder` resolves and executes the matching adapter rather than falling back to standard style serialization routines. Sources: [packages/openapi/src/requests/media/encode.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/encode.ts#L42-L47,L72-L81) ## Request and Response Tabs ### Request Tab Rendering and Data Display The `RequestTabs` component checks whether an operation defines a `requestBody` object before rendering. If a request body is present, it delegates to `renderRequestTabs`, falling back to `renderRequestTabsDefault`. When multiple example items exist, it wraps them in a Fumadocs UI `Tabs` component using each item's unique identifier as its value key. For single items, it renders the item directly, and when no examples are found, it outputs an empty state text. Sources: [packages/openapi/src/ui/operation/request-tabs.tsx:30-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/request-tabs.tsx#L30-L97) The `RequestTabsItem` component extracts `requestData` from each example item and populates a map of display names for parameter categories and bodies. | Request Data Field | Display Label / Source | | :--- | :--- | | `body` | Request Body (with badge showing `requestData.bodyMediaType`) | | `cookie` | Cookie Parameters | | `header` | Header Parameters | | `query` | Query Parameters | | `path` | Path Parameters | Sources: [packages/openapi/src/ui/operation/request-tabs.tsx:106-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/request-tabs.tsx#L106-L121) Each available parameter or body category renders inside an accordion item containing a syntax-highlighted JSON code block. Sources: [packages/openapi/src/ui/operation/request-tabs.tsx:131-148](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/request-tabs.tsx#L131-L148) > [!NOTE] > If a request data category contains no keys or evaluates to falsy, `RequestTabsItem` skips rendering that accordion section entirely. Sources: [packages/openapi/src/ui/operation/request-tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/request-tabs.tsx#L133-L135) ### Response Tabs and Schema Sampling The `ResponseTabs` component iterates over all response objects defined on an operation, extracting preferred media types and generating example payloads using schema sampling or pre-defined examples. Sources: [packages/openapi/src/ui/operation/response-tabs.tsx:53-103](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/response-tabs.tsx#L53-L103) | Property | Type | Description | | :--- | :--- | :--- | | `code` | `string` | HTTP response code (e.g., `200`, `400`). | | `response` | `NoReference` | The underlying OpenAPI response specification object. | | `mediaType` | `string \| null` | Preferred media type resolved via `getPreferredType`. | | `examples` | `ResponseExample[]` | Array of generated or defined response example items. | Sources: [packages/openapi/src/ui/operation/response-tabs.tsx:20-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/response-tabs.tsx#L20-L33) Response tabs render as a group of tabs keyed by HTTP status code. When a response defines multiple examples, they are organized within a single-selection accordion component defaulting to the first index. Sources: [packages/openapi/src/ui/operation/response-tabs.tsx:115-159](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/response-tabs.tsx#L115-L159) > [!WARNING] > If a response object specifies neither explicit examples nor a schema, response tab generation yields an empty array, causing `ResponseTabs` to return `null`. Sources: [packages/openapi/src/ui/operation/response-tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/response-tabs.tsx#L90-L96,L104) ### Client Code Blocks and Usage Generation The `UsageTabs` component initializes a code usage generator registry using `createCodeUsageGeneratorRegistry`, appending inline generators from context samples and `x-codeSamples` extensions on the operation object. Sources: [packages/openapi/src/ui/operation/usage-tabs.tsx:30-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/usage-tabs.tsx#L30-L90) The `ClientCodeBlock` component abstracts syntax highlighting by checking render context overrides before falling back to `DynamicCodeBlock` with Shiki initialization. Sources: [packages/openapi/src/ui/components/codeblock.tsx:8-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/components/codeblock.tsx#L8-L21) ## Alternative Scalar Client Integration ### The `withScalar` Wrapper and Client Component Fumadocs supports delegating endpoint interaction and testing to the `@scalar/api-client-react` library by wrapping page generation options inside `withScalar`. The function requires `@scalar/api-client-react` to be installed in the project, automatically importing its style sheet from `@scalar/api-client-react/style.css` and loading the client component lazily. Sources: [packages/openapi/src/scalar/client.tsx:10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/scalar/client.tsx#L10), [packages/openapi/src/scalar/index.tsx:5-10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/scalar/index.tsx#L5-L10) | Option Property | Return / Action | Description | | :--- | :--- | :--- | | `playground.provider` | `props.children` | Bypasses default playground provider wrappers to use Scalar context. | | `playground.render` | `` | Renders the lazy-loaded `ScalarPlayground` client component for each endpoint. | Sources: [packages/openapi/src/scalar/index.tsx:15-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/scalar/index.tsx#L15-L23) > [!NOTE] > The `withScalar` function overrides `playground.provider` to pass children directly and assigns `playground.render` to mount `ScalarPlayground` with the bundled OpenAPI specification schema. Sources: [packages/openapi/src/scalar/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/scalar/index.tsx#L15-L23) ### Playground Rendering and Execution The `ScalarPlayground` component renders an interactive card containing an HTTP method label, the request path, and a submit trigger button that opens the Scalar client modal with the specified path and method. Sources: [packages/openapi/src/scalar/client.tsx:12-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/scalar/client.tsx#L12-L53) ```tsx const client = useApiClient({ configuration: { content: spec as never, }, }); ``` Sources: [packages/openapi/src/scalar/client.tsx:24-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/scalar/client.tsx#L24-L28) The component utilizes `useTheme` from `fumadocs-ui/provider/base` to resolve the current application theme and synchronize light or dark mode styling for the Scalar client wrapper div once mounted on the client. Sources: [packages/openapi/src/scalar/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/scalar/client.tsx#L6-L8,L21-L39) > [!WARNING] > `ScalarPlayground` is marked with `'use client'` and relies on `useState` and `useEffect` hooks to track mounting status before applying resolved theme mode class names to avoid server-side hydration mismatches. Sources: [packages/openapi/src/scalar/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/scalar/client.tsx#L1-L8,L21-L32) ## Related - [OpenAPI Document Generation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/openapi-document-generation) - [Code Sample Generators](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/code-sample-generators) --- ## Technical docs: Code Sample Generators URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/code-sample-generators
Relevant source files The following files were used as context for generating this wiki page: - [packages/openapi/src/requests/generators/all.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/all.ts) - [packages/openapi/src/requests/generators/curl.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/curl.ts) - [packages/openapi/src/requests/generators/csharp.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/csharp.ts) - [packages/openapi/src/ui/operation/usage-tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/usage-tabs.tsx) - [packages/openapi/src/requests/generators/python.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/python.ts) - [packages/openapi/src/requests/generators/go.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/go.ts) - [packages/api-docs/src/schema/sample.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/sample.ts) - [packages/openapi/src/ui/operation/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/index.tsx) - [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx) - [packages/openapi/src/requests/generators/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/index.ts) - [packages/openapi/src/requests/generators/javascript.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/javascript.ts) - [packages/openapi/src/requests/media/adapter.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts) - [packages/api-docs/src/codegen.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/codegen.ts) - [packages/openapi/src/ui/operation/response-tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/response-tabs.tsx) - [packages/openapi/src/requests/generators/java.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/java.ts) - [packages/openapi/src/utils/get-example-requests.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts) - [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx) - [packages/openapi/src/ui/operation/request-tabs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/request-tabs.tsx) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/openapi/src/scalar/client.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/scalar/client.tsx) - [packages/asyncapi/src/ui/operation/message-examples.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/operation/message-examples.tsx) - [packages/openapi/src/generate-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts) - [packages/openapi/src/utils/pages/to-text.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-text.ts) - [packages/asyncapi/src/utils/get-example-messages.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/get-example-messages.ts) - [packages/openapi/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/index.ts) - [packages/cli/src/commands/export-epub.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/export-epub.ts) - [packages/asyncapi/src/utils/pages/to-text.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/to-text.ts) - [packages/create-app/scripts/sync.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/scripts/sync.ts) - [packages/openapi/src/utils/schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/schema.ts) - [packages/doc-gen/src/remark-docgen.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-docgen.ts)
## Overview Code sample generators translate normalized API request data, headers, cookies, and payloads into executable client code snippets across multiple programming languages and scripting environments. By transforming parsed OpenAPI operation objects and media adapters into formatted target syntax, the generator suite powers interactive API documentation tabs and dynamic code preview widgets. Sources: [packages/openapi/src/requests/generators/all.ts:9-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/all.ts#L9-L16), [packages/openapi/src/ui/operation/usage-tabs.tsx:137-181](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/usage-tabs.tsx#L137-L181) ## Code Generator Registry ### Registry Interface and Types The registry relies on types imported from `@fumadocs/api-docs/codegen`, instantiating them with specific type arguments for OpenAPI request payloads. `CodeUsageGeneratorRegistry` is defined as a registry mapping language identifiers to generator functions that accept `RequestData & { url: string }` and a context containing `mediaAdapters` (a record of string keys to `MediaAdapter` objects) and a `custom` configuration property. ```typescript export type CodeUsageGeneratorRegistry = Shared.CodeUsageGeneratorRegistry< RequestData & { url: string }, { mediaAdapters: Record; custom: unknown } >; ``` Sources: [packages/openapi/src/requests/generators/index.ts:35-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/index.ts#L35-L38) `CodeUsageGenerator` and `InlineCodeUsageGenerator` represent single generator functions for specified programming languages, where the inline variant permits generic customization typing for the `custom` context field. ```typescript export type CodeUsageGenerator = Shared.CodeUsageGenerator< RequestData & { url: string }, { mediaAdapters: Record; custom: unknown } >; export type InlineCodeUsageGenerator = Shared.InlineCodeUsageGenerator< RequestData & { url: string }, { mediaAdapters: Record; custom: T } >; ``` Sources: [packages/openapi/src/requests/generators/index.ts:43-54](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/index.ts#L43-L54) `createCodeUsageGeneratorRegistry` wraps the shared factory function to produce new registry instances, optionally accepting an inherited registry parameter for scoping or fallback behaviors. ```typescript export function createCodeUsageGeneratorRegistry( inherit?: CodeUsageGeneratorRegistry, ): CodeUsageGeneratorRegistry { return Shared.createCodeUsageGeneratorRegistry(inherit); } ``` Sources: [packages/openapi/src/requests/generators/index.ts:56-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/index.ts#L56-L60) > [!NOTE] > `CodeUsageGeneratorFn` explicitly types generator callbacks as functions taking `RequestData & { url: string }` and a context record, returning a generated string snippet. > Sources: [packages/openapi/src/requests/generators/index.ts:62-65](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/index.ts#L62-L65) ### Default Generator Registration The `registerDefault` function populates a `CodeUsageGeneratorRegistry` instance by binding default language generator modules to specific string keys. It registers six built-in target generators before returning the modified registry instance. | Language Key | Generator Module | Target Output | | :--- | :--- | :--- | | `curl` | `curl` | cURL CLI command snippet | | `js` | `javascript` | JavaScript fetch or client code | | `go` | `go` | Go HTTP request snippet | | `python` | `python` | Python requests snippet | | `java` | `java` | Java HTTP client snippet | | `csharp` | `csharp` | C# HTTP client snippet | Sources: [packages/openapi/src/requests/generators/all.ts:2-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/all.ts#L2-L16) ```typescript export function registerDefault(registry: CodeUsageGeneratorRegistry) { registry.add('curl', curl); registry.add('js', javascript); registry.add('go', go); registry.add('python', python); registry.add('java', java); registry.add('csharp', csharp); return registry; } ``` Sources: [packages/openapi/src/requests/generators/all.ts:9-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/all.ts#L9-L16) > [!TIP] > When building custom documentation pipelines alongside [OpenAPI Document Generation](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/openapi-document-generation), pass an existing registry to `createCodeUsageGeneratorRegistry` as an inheritance argument to extend default language generators with domain-specific targets. > Sources: [packages/openapi/src/requests/generators/index.ts:56-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/index.ts#L56-L60) ## Request Data Extraction ### Example Resolution and Parameter Locations Extracting and preparing request information for code sample generation involves resolving parameters across operations and path items, picking schema examples, and sampling body contents. The process starts by gathering parameters from both `operation.parameters` and `pathItem.parameters`, and identifying the preferred request media type via `getPreferredType`. Sources: [packages/openapi/src/utils/get-example-requests.ts:36-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L36-L39) ```typescript export function getPreferredType(body: Record): string | undefined { if ('application/json' in body) return 'application/json'; return Object.keys(body)[0]; } ``` Sources: [packages/openapi/src/utils/schema.ts:8-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/schema.ts#L8-L12) When constructing example requests through `getExampleRequests`, the utility checks whether explicit body examples are defined under `bodyOfType.examples`. If present, each entry generates a distinct `ExampleRequestItem` containing its assigned identifier, summary or key name, optional description, raw request data, and encoded request data produced by `encodeRequestData`. If no named examples exist, a default example item is created using schema sampling or fallback heuristics. Sources: [packages/openapi/src/utils/get-example-requests.ts:41-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L41-L76) Parameters are iterated and assigned to distinct transport containers in `getRequestData` based on their `in` property value. Sources: [packages/openapi/src/utils/get-example-requests.ts:99-130](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L99-L130) | Parameter Location (`param.in`) | Target Container Object | Source Lines | | :--- | :--- | :--- | | `cookie` | `result.cookie[param.name!]` | [packages/openapi/src/utils/get-example-requests.ts:118-120](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L118-L120) | | `header` | `result.header[param.name!]` | [packages/openapi/src/utils/get-example-requests.ts:121-123](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L121-L123) | | `query` | `result.query[param.name!]` | [packages/openapi/src/utils/get-example-requests.ts:124-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L124-L126) | | default (path) | `result.path[param.name!]` | [packages/openapi/src/utils/get-example-requests.ts:127-129](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L127-L129) | Sources: [packages/openapi/src/utils/get-example-requests.ts:117-130](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L117-L130) > [!WARNING] > If a parameter value is undefined but marked as `required`, `getRequestData` attempts to generate a mock value using `@fumadocs/api-docs/schema/sample`. If neither a schema nor content definition exists for a required parameter, an explicit Error is thrown detailing the missing parameter name and media type. > Sources: [packages/openapi/src/utils/get-example-requests.ts:102-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L102-L114) ### Example Extraction Helpers The helper function `pickExample` inspects input schemas and media objects for static examples or nested content objects, prioritizing explicit `example` definitions over mapped examples or sampled media types. Sources: [packages/openapi/src/utils/schema.ts:32-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/schema.ts#L32-L51) ```typescript export function pickExample(value: ExampleLike): unknown | undefined { if (value.example !== undefined) { return value.example; } if (value.content) { const type = getPreferredType(value.content); const content = type ? value.content[type] : undefined; if (type && content) { const out = value.examples?.[type].value ?? pickExample(content); if (out !== undefined) return out; } } if (value.examples) { const examples = Object.values(value.examples); if (examples.length > 0) return examples[0].value; } } ``` Sources: [packages/openapi/src/utils/schema.ts:32-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/schema.ts#L32-L51) > [!NOTE] > When sampling request bodies, read-only properties are skipped when the HTTP method is not `get`, whereas write-only properties are skipped specifically when the method is `get`. Non-required properties are skipped by default during sampling. > Sources: [packages/openapi/src/utils/get-example-requests.ts:143-147](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/get-example-requests.ts#L143-L147) ## Media Type Adapters ### Encoding Handlers and Supported Formats Fumadocs OpenAPI uses media type adapters to encode request body payloads into standard `BodyInit` objects for runtime requests and to translate body structures into language-specific initialization snippets. Each adapter implements the `MediaAdapter` interface, which mandates an `encode` function and a `generateExample` function receiving a `MediaContext` object. Sources: [packages/openapi/src/requests/media/adapter.ts:33-58](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L33-L58) The `defaultAdapters` record supports five standard media types as well as raw octet streams. Sources: [packages/openapi/src/requests/media/adapter.ts:60-219](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L60-L219) | Media Type | Encoding Behavior | Example Generation Behavior | Source Lines | | :--- | :--- | :--- | :--- | | `application/json` | Serializes body via `JSON.stringify(data.body)` | Delegates to `str(data.body, 'application/json', ctx)` | [packages/openapi/src/requests/media/adapter.ts:61-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L61-L68) | | `application/xml` | Converts object via `js2xml` with compact formatting and 2-space indentation | Delegates to `str(data.body, 'application/xml', ctx)` | [packages/openapi/src/requests/media/adapter.ts:69-79](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L69-L79) | | `application/x-ndjson` | Maps array items to newline-delimited JSON strings or single stringify | Delegates to `str(data.body, 'application/x-ndjson', ctx)` | [packages/openapi/src/requests/media/adapter.ts:80-91](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L80-L91) | | `application/x-www-form-urlencoded` | Constructs `URLSearchParams` from object entries | Returns `URLSearchParams` JS instantiation or delegates to `str` | [packages/openapi/src/requests/media/adapter.ts:92-111](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L92-L111) | | `multipart/form-data` | Appends or sets `File`, `Blob`, array items, or stringified objects into `FormData` | Builds language-specific multipart builders for JS, Go, Java, C#, and Python | [packages/openapi/src/requests/media/adapter.ts:112-209](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L112-L209) | | `application/octet-stream` | Casts `data.body` directly as `BodyInit` | Returns `undefined` (not supported) | [packages/openapi/src/requests/media/adapter.ts:210-218](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L210-L218) | Sources: [packages/openapi/src/requests/media/adapter.ts:60-219](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L60-L219) > [!CAUTION] > The `application/x-www-form-urlencoded` encoder validates that `data.body` is an object type, throwing an explicit `Error` if non-object inputs are passed. Similarly, the `multipart/form-data` encoder checks for valid non-null object structures before iterating over properties. > Sources: [packages/openapi/src/requests/media/adapter.ts:94-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L94-L95), [packages/openapi/src/requests/media/adapter.ts:117-119](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L117-L119) ### Language Code Generation and Contexts The `str` helper formats string-serializable bodies across target programming languages by inspecting `ctx.lang`. Supported context interfaces include `GoContext`, `JavaScriptContext`, `JavaContext`, and `CSharpContext`, which provide `addImport` utilities to inject required packages. Sources: [packages/openapi/src/requests/media/adapter.ts:13-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L13-L38), [packages/openapi/src/requests/media/adapter.ts:221-258](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L221-L258) ```typescript if (ctx.lang === 'js') { if (mediaType === 'application/json') { return `const body = JSON.stringify(${JSON.stringify(init, null, 2)})`; } return `const body = ${backtickQuote(inputToString(init, mediaType))}`; } if (ctx.lang === 'python') { return `body = ${tripleDoubleQuote(inputToString(init, mediaType))}`; } if (ctx.lang === 'go') { const { addImport } = ctx as GoContext; addImport('strings'); return `body := strings.NewReader(${backtickQuote(inputToString(init, mediaType))})`; } if (ctx.lang === 'java') { const { addImport } = ctx as JavaContext; addImport('java.net.http.HttpRequest.BodyPublishers'); return `var body = BodyPublishers.ofString(${tripleDoubleQuote(inputToString(init, mediaType))});`; } if (ctx.lang === 'csharp') { const input = `\n${inputToString(init, mediaType)}\n`; return `var body = new StringContent(${tripleDoubleQuote(input)}, Encoding.UTF8, "${mediaType}");`; } ``` Sources: [packages/openapi/src/requests/media/adapter.ts:230-257](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L230-L257) > [!TIP] > When generating Go examples for `multipart/form-data`, the adapter automatically invokes `addImport('mime/multipart')` and `addImport('bytes')` to register necessary buffer and multipart writer dependencies in the output scope. > Sources: [packages/openapi/src/requests/media/adapter.ts:179-183](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L179-L183) > [!WARNING] > Null, undefined, and NaN properties within `multipart/form-data` request objects are explicitly skipped during `FormData` iteration, preventing invalid literal conversions. > Sources: [packages/openapi/src/requests/media/adapter.ts:124](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/media/adapter.ts#L124) ## Shell and Scripting Generators ### cURL Invocation Generation The `curl` code usage generator builds standard POSIX shell commands by assembling HTTP methods, target URLs, request headers, cookies, and payload arguments. The generator initializes the command array with the upper-case HTTP method and target URL, iterates over header entries to append `-H` flags, and serializes cookie parameters with `--cookie` flags using double quotes. Sources: [packages/openapi/src/requests/generators/curl.ts:4-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/curl.ts#L4-L22) ```typescript if (data.body && data.bodyMediaType === 'multipart/form-data') { if (typeof data.body !== 'object') throw new Error('[CURL] request body must be an object.'); for (const [key, value] of Object.entries(data.body)) { s.push(`-F ${key}=${doubleQuote(inputToString(value))}`); } } else if (data.body && data.bodyMediaType) { const escaped = singleQuote( inputToString( data.body, // @ts-expect-error -- assume the body media type is supported data.bodyMediaType, ), ); s.push(`-H "Content-Type: ${data.bodyMediaType}"`); s.push(`-d ${escaped}`); } return s.flatMap((v, i) => indent(v, i > 0 ? 1 : 0)).join(' \\\n'); }, ``` Sources: [packages/openapi/src/requests/generators/curl.ts:23-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/curl.ts#L23-L43) > [!CAUTION] > When processing `multipart/form-data` request bodies, the cURL generator verifies that `data.body` is an object type and throws an explicit `[CURL] request body must be an object.` error if non-object inputs are passed. > Sources: [packages/openapi/src/requests/generators/curl.ts:23-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/curl.ts#L23-L25) ### JavaScript Fetch Generation The `javascript` code usage generator constructs browser-compatible `fetch()` API snippets, managing request configuration options, headers, cookies, and media type adaptations. It collects configuration properties in an internal `Map` and populates a header record with content types, custom headers, and combined cookie strings separated by semicolons. Sources: [packages/openapi/src/requests/generators/javascript.ts:5-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/javascript.ts#L5-L26) ```typescript if (Object.keys(headers).length > 0) { options.set('headers', JSON.stringify(headers, null, 2)); } let body: string | undefined; if (data.body && data.bodyMediaType) { const adapter = resolveMediaAdapter(data.bodyMediaType, mediaAdapters); body = adapter?.generateExample(data as { body: unknown }, { lang: 'js', addImport(from, name) { s.unshift(`import { ${name} } from "${from}"`); }, }); } if (body) { s.push(body); options.set('body', 'body'); } const params = [doubleQuote(data.url)]; if (options.size > 0) { const str = Array.from(options.entries()) .map(([k, v]) => indent(k === v ? k : `${k}: ${v}`)) .join(',\n'); params.push(`{\n${str}\n}`); } s.push(`fetch(${params.join(', ')})`); return s.join('\n\n'); }, ``` Sources: [packages/openapi/src/requests/generators/javascript.ts:27-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/javascript.ts#L27-L59) > [!TIP] > The JavaScript generator resolves media adapters for request bodies when `data.bodyMediaType` is present, supporting dynamic import injection into the snippet scope (such as module imports for form data or specialized binary parsers) via the `addImport` callback. > Sources: [packages/openapi/src/requests/generators/javascript.ts:31-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/javascript.ts#L31-L40) ## Compiled Language Generators ### Go, C#, and Java Client Snippets The compiled language generators construct strongly typed HTTP client snippets for Go, C#, and Java, mapping request configurations, headers, cookies, and media type adapters into native execution patterns. The Go generator populates an `imports` array with `fmt`, `net/http`, and `io/ioutil`, maps custom headers and cookie strings into a `req.Header` collection, and builds the request using `http.NewRequest` with `http.DefaultClient.Do`. Sources: [packages/openapi/src/requests/generators/go.ts:5-62](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/go.ts#L5-L62) | Generator | Language Tag | Default Imports / Namespaces | Core Client Class | | :--- | :--- | :--- | :--- | | **Go** | `go` | `fmt`, `net/http`, `io/ioutil` | `http.DefaultClient` | | **C#** | `csharp` | `System`, `System.Net.Http`, `System.Text` | `HttpClient` | | **Java** | `java` | `java.net.URI`, `java.net.http.HttpClient`, `java.net.http.HttpRequest`, `java.net.http.HttpResponse`, `java.net.http.HttpResponse.BodyHandlers`, `java.time.Duration` | `HttpClient` | Sources: [packages/openapi/src/requests/generators/go.ts:9](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/go.ts#L9), [packages/openapi/src/requests/generators/csharp.ts:10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/csharp.ts#L10), [packages/openapi/src/requests/generators/java.ts:11-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/java.ts#L11-L18) > [!NOTE] > The C# generator transforms incoming HTTP methods by capitalizing the first character, lowercasing the remainder, and appending `Async` (e.g., `GetAsync`, `PostAsync`) to match `HttpClient` method signatures. > Sources: [packages/openapi/src/requests/generators/csharp.ts:57-63](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/csharp.ts#L57-L63) ### Request Body and Media Adaptation When a request body and `bodyMediaType` are present, each compiled generator resolves a media adapter to output payload examples and inject language-specific package imports into the snippet scope via the `addImport` callback. The Java generator configures an `HttpClient` builder with a 10-second connect timeout using `Duration.ofSeconds(10)`, constructs an `HttpRequest` via `HttpRequest.newBuilder()`, appends headers and cookie strings, and invokes the dynamic HTTP method builder. Sources: [packages/openapi/src/requests/generators/java.ts:21-72](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/java.ts#L21-L72) ```typescript // Add response handling s.push('try {'); s.push( indent( 'HttpResponse response = client.send(requestBuilder.build(), BodyHandlers.ofString());', ), ); s.push(indent('System.out.println("Status code: " + response.statusCode());')); s.push(indent('System.out.println("Response body: " + response.body());')); s.push('} catch (Exception e) {'); s.push(indent('e.printStackTrace();')); s.push('}'); ``` Sources: [packages/openapi/src/requests/generators/java.ts:74-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/java.ts#L74-L86) > [!WARNING] > The Java generator wraps client execution inside a `try-catch` block that catches general `Exception` instances and outputs stack traces via `e.printStackTrace();` during response handling. > Sources: [packages/openapi/src/requests/generators/java.ts:75-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/java.ts#L75-L86) ## Python Requests Generation ### Constructing Python Requests Syntax The Python requests generator builds executable HTTP request snippets using the `requests` library, incorporating dynamic method calls, URL strings, and dictionary literals for headers and cookies. The generator initializes an `imports` set with `requests`, evaluates any request body and media type adapter, and appends keyword arguments to a `params` array containing the uppercase HTTP method and target URL. Sources: [packages/openapi/src/requests/generators/python.ts:5-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/python.ts#L5-L27) | Parameter / Component | Data Structure | Python Output Format | Source Package Import Added | | :--- | :--- | :--- | :--- | | **Method & URL** | `data.method`, `data.url` | `["GET", url]` | `requests` | | **Request Body** | `data.body`, `bodyMediaType` | `data = body` | None (handled by adapter) | | **Headers** | `Record` | `headers = { ... }` | None | | **Cookies** | `Record` | `cookies = { ... }` | None | | **Date Field** | `Date` instance | `datetime.datetime(...)` | `datetime` | Sources: [packages/openapi/src/requests/generators/python.ts:9-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/python.ts#L9-L46), [packages/openapi/src/requests/generators/python.ts:72-74](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/python.ts#L72-L74) > [!NOTE] > When request headers or cookies contain entries, the generator serializes them into indented dictionary literals via `generatePythonObject` before appending them to the `requests.request` parameter list. > Sources: [packages/openapi/src/requests/generators/python.ts:29-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/python.ts#L29-L46) ### Object Serialization and Type Mapping The `generatePythonObject` utility recursively converts arbitrary JavaScript values into valid Python syntax literals, managing null, boolean, numeric, string, array, date, and object types. Sources: [packages/openapi/src/requests/generators/python.ts:60-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/python.ts#L60-L82) ```typescript if (v === null) { return 'None'; } else if (typeof v === 'boolean') { return v ? 'True' : 'False'; } else if (typeof v === 'string') { return doubleQuote(v); } else if (typeof v === 'number') { return v.toString(); } else if (Array.isArray(v)) { const items = v.map((item) => generatePythonObject(item, imports)); return `[${items.join(', ')}]`; } else if (v instanceof Date) { imports.add('datetime'); return `datetime.datetime(${v.getFullYear()}, ${v.getMonth() + 1}, ${v.getDate()}, ${v.getHours()}, ${v.getMinutes()}, ${v.getSeconds()}, ${v.getMilliseconds()})`; } else if (typeof v === 'object') { const entries = Object.entries(v).map( ([key, value]) => ` ${doubleQuote(key)}: ${generatePythonObject(value, imports)}`, ); return `{\n${entries.join(', \n')}\n}`; } else { throw new Error(`Unsupported type: ${typeof v}`); } ``` Sources: [packages/openapi/src/requests/generators/python.ts:61-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/python.ts#L61-L82) > [!WARNING] > Encountering an unsupported JavaScript type during object serialization throws an immediate error with the message `Unsupported type: ${typeof v}`, halting snippet generation. > Sources: [packages/openapi/src/requests/generators/python.ts:80-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/requests/generators/python.ts#L80-L82) ## Related - [OpenAPI Interactive UI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/openapi-interactive-ui) --- ## Technical docs: AsyncAPI Document Processing URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/asyncapi-document-processing
Relevant source files The following files were used as context for generating this wiki page: - [packages/asyncapi/src/utils/document/dereference.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/document/dereference.ts) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/asyncapi/src/utils/document/load.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/document/load.ts) - [packages/asyncapi/src/ui/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/index.tsx) - [packages/openapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/server/index.tsx) - [packages/openapi/src/utils/document/load.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/document/load.ts) - [packages/openapi/src/utils/document/dereference.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/document/dereference.ts) - [packages/asyncapi/src/generate-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/generate-file.ts) - [packages/asyncapi/src/utils/schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/schema.ts) - [packages/asyncapi/src/utils/pages/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/builder.ts) - [packages/asyncapi/src/utils/pages/preset-auto.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/preset-auto.ts) - [packages/python/src/convert.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/convert.ts) - [packages/api-docs/src/components/schema/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/components/schema/index.tsx) - [packages/asyncapi/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/index.ts) - [packages/asyncapi/src/utils/pages/to-text.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/to-text.ts) - [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/api-docs/src/schema/dereference.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/dereference.ts) - [packages/openapi/src/generate-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts) - [packages/openapi/src/utils/pages/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/builder.ts) - [packages/mdx/src/core.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/core.ts) - [packages/api-docs/src/schema/bundle.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/bundle.ts) - [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts) - [packages/asyncapi/src/utils/pages/to-static-data.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/to-static-data.ts) - [packages/asyncapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/package.json) - [packages/python/fumapy/mksource/document_module.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/document_module.py) - [packages/doc-gen/src/remark-docgen.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/src/remark-docgen.ts) - [packages/asyncapi/src/utils/traits.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/traits.ts)
## Overview The AsyncAPI document processing pipeline ingest, bundles, and transforms AsyncAPI specifications into structured Fumadocs virtual files, navigation hierarchies, and standalone documentation pages. By combining reference bundling, shallow and deep schema dereferencing, automated page generation presets, and trait merging utilities, the framework standardizes event-driven API documentation for message channels and operations. Sources: [packages/asyncapi/src/utils/document/load.ts:7-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/document/load.ts#L7-L16), [packages/asyncapi/src/server/index.tsx:110-203](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx#L110-L203), [packages/asyncapi/src/utils/pages/preset-auto.ts:56-279](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/preset-auto.ts#L56-L279) ## Document Loading and Bundling ### Ingestion and Bundling Pipeline AsyncAPI documents are ingested and prepared for processing via `loadDocument`, which accepts either a file path, a URL, or an inline `AsyncAPIObject` specification. The ingestion utility invokes `bundle` from `@apidevtools/json-schema-ref-parser` to resolve external and internal `$ref` pointers into a single unified JSON schema structure. ```typescript export async function loadDocument(input: string | AsyncAPIObject): Promise<{ bundled: AsyncAPIObject; }> { try { const bundled = await bundle(input); if (!bundled.asyncapi) { throw new Error('Missing required `asyncapi` field.'); } return { bundled }; } catch (e) { throw new Error(`[AsyncAPI] Failed to resolve input: ${input}`, { cause: e, }); } ``` Sources: [packages/asyncapi/src/utils/document/load.ts:7-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/document/load.ts#L7-L21), [packages/api-docs/src/schema/bundle.ts:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/bundle.ts#L1-L1) > [!WARNING] > If a loaded specification lacks a root `asyncapi` field after bundling, `loadDocument` throws an explicit error indicating a missing required property. > Sources: [packages/asyncapi/src/utils/document/load.ts:12-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/document/load.ts#L12-L14) ### Server Options and Document Caching The `createAsyncAPI` server manages inputs supplied either as an array of path strings or as a `SchemaRecord` mapping identifiers to static objects or async loader functions. Caching behavior can be controlled using the `disableCache` option. ```tsx type SchemaRecord = Record< string, string | AsyncAPIObject | (() => Awaitable) >; interface LoadedDocument { bundled: AsyncAPIObject; } export interface AsyncAPIOptions { input?: string[] | SchemaRecord; disableCache?: boolean; } ``` Sources: [packages/asyncapi/src/server/index.tsx:28-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx#L28-L39) When caching is active, loaded document promises are stored in a local `schemaMap` to prevent redundant disk reads or network requests across schema queries. ```tsx export function createAsyncAPI(options: AsyncAPIOptions = {}): AsyncAPIServer { const { disableCache = false } = options; const schemaMap = new Map>(); let resolvedInput: SchemaRecord = {}; if (Array.isArray(options.input)) { for (const item of options.input) resolvedInput[item] = item; } else if (options.input) { resolvedInput = options.input; } function getSchema(schemaId: string): Promise { if (!(schemaId in resolvedInput)) { console.warn( `[Fumadocs AsyncAPI] the document "${schemaId}" is not listed in the input array, this may be unexpected and won't be cached properly.`, ); return loadDocument(schemaId); } if (!disableCache) { const cached = schemaMap.get(schemaId); if (cached) return cached; } const raw = resolvedInput[schemaId]; const output = Promise.resolve(typeof raw === 'function' ? raw() : raw).then(loadDocument); if (!disableCache) schemaMap.set(schemaId, output); return output; } ``` Sources: [packages/asyncapi/src/server/index.tsx:73-101](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx#L73-L101) > [!NOTE] > If a requested `schemaId` is not pre-registered in `resolvedInput`, `getSchema` emits a console warning that the document will not be cached properly before falling back to direct execution of `loadDocument(schemaId)`. > Sources: [packages/asyncapi/src/server/index.tsx:85-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx#L85-L90) ## Document Dereferencing Architecture ### Synchronized and Shallow Dereferencing Mechanisms The framework provides specialized routines to resolve `$ref` pointers within bundled AsyncAPI and JSON schema documents. The `dereferenceBundledDocument` utility wraps `dereferenceSync` from [API Docs Primitives](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/api-docs-primitives), constructing a `DereferencedDocument` container that holds the original bundled document, the fully dereferenced specification tree, and a `getRawRef` lookup function that retrieves original reference pointers for objects. ```typescript export function dereferenceBundledDocument(bundled: AsyncAPIObject): DereferencedDocument { const dereferenceMap = new Map(); return { bundled, dereferenced: dereferenceSync(bundled as JSONSchema, { setOriginalRef(schema, ref) { dereferenceMap.set(schema as object, ref); }, }) as NoReference, getRawRef(obj: object) { return dereferenceMap.get(obj); }, }; ``` Sources: [packages/asyncapi/src/utils/document/dereference.ts:20-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/document/dereference.ts#L20-L33) > [!NOTE] > The `dereferenceBundledDocument` function registers a `setOriginalRef` callback during synchronous traversal, mapping both resolved target schemas and modified parent objects back to their original `$ref` strings in an internal `Map`. > Sources: [packages/asyncapi/src/utils/document/dereference.ts:25-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/document/dereference.ts#L25-L32) ### Dereference Options and Resolution Flow The core synchronization engine operates via `dereferenceSync`, which clones the input schema structure using `structuredClone` and traverses nodes recursively with pointer path tracking via `appendInternalRefPath`. It supports options to control preservation and original reference tracking during traversal. | Option | Type | Default | Purpose | | :--- | :--- | :--- | :--- | | `preserveRef` | `(pointer: string) => boolean` | `undefined` | Returns `true` to keep the Reference Object at a specific pointer without inlining. | | `setOriginalRef` | `(schema: JSONSchema, ref: string) => void` | `() => {}` | Callback invoked with the resolved schema and its original reference pointer. | ```typescript export interface DereferenceOptions { /** * Return `true` to keep the Reference Object at `pointer` without inlining. */ preserveRef?: (pointer: string) => boolean; setOriginalRef?: (schema: JSONSchema, ref: string) => void; } ``` Sources: [packages/api-docs/src/schema/dereference.ts:7-13](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/dereference.ts#L7-L13) For non-recursive or single-level resolution, `dereferenceShallow` inspects individual plain objects, extracts local properties while removing `$ref`, and resolves referenced definitions against a full document root using `resolveRefSync`. ```typescript export function dereferenceShallow(schema: T, full: unknown): NoReferenceShallow { if (isPlainObject(schema)) { if (typeof schema.$ref !== 'string') return schema as never; const { $ref, ...rest } = schema; const resolved = dereferenceShallow(resolveRefSync($ref, full), full); if (typeof resolved !== 'object') throw new Error(`invalid schema referenced via "${$ref}"`); return { ...resolved, ...rest } as never; } return schema as never; ``` Sources: [packages/api-docs/src/schema/dereference.ts:67-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/dereference.ts#L67-L78) > [!CAUTION] > If a referenced target resolves to a boolean instead of an object during deep synchronization, `dereferenceSync` throws an explicit `'invalid schema'` error. > Sources: [packages/api-docs/src/schema/dereference.ts:48-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/schema/dereference.ts#L48-L48) ## Virtual File and Route Generation ### Virtual File Construction Pipeline The transformation of loaded AsyncAPI specifications into Fumadocs virtual files is driven by a precise execution sequence. The framework coordinates file generation starting from server initialization, traversing schemas, processing entries, and constructing page properties. 1. `createAsyncAPI` — Initializes server configurations, schema maps, and resolves input sources. 2. `getVirtualFiles` — Asynchronously retrieves all bundled schemas and initializes builder configurations via `createAutoPreset`. 3. `onEntries` — Recursively evaluates generated output entries, handling directory groups and meta configuration files when `meta` options are enabled. 4. `onEntry` — Processes individual page and operation entries, generating page props and assigning static [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) and structured data. 5. `getPageProps` — Extracts generated metadata, document identifiers, and operations associated with the specific entry item. ```tsx async function getVirtualFiles(server: AsyncAPIServer, options: AsyncAPISourceOptions) { const { baseDir = '', meta = false } = options; const { createAutoPreset } = await import('@/utils/pages/preset-auto'); const { fromSchema } = await import('@/utils/pages/builder'); const files: VirtualFile<{ pageData: AsyncAPIPageData; metaData: MetaData; }>[] = []; const schemas = await server.getSchemas(); const builderOptions = createAutoPreset(options); for (const [id, schema] of Object.entries(schemas)) { const list = fromSchema(id, schema.bundled, builderOptions); onEntries(list); function onEntry(entry: PageOutput | OperationOutput) { const props = getPageProps(entry); files.push({ type: 'page', path: `${baseDir}/${entry.path}`, data: { ...entry.info, getAsyncAPIPageProps() { return { payload: { bundled: schema.bundled, }, ...props, }; }, getSchema() { return { id, bundled: schema.bundled, }; }, ...toStaticData(props, schema.bundled), _asyncapi: { action: entry.type === 'operation' ? entry.item.action : undefined, deprecated: entry.info.deprecated, }, }, }); } ``` Sources: [packages/asyncapi/src/server/index.tsx:110-156](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx#L110-L156) ```mermaid sequenceDiagram participant Server as createAsyncAPI participant Files as getVirtualFiles participant Entries as onEntries participant Entry as onEntry participant Props as getPageProps Server->>Files: getVirtualFiles(server, options) Files->>Entries: onEntries(list) Entries->>Entry: onEntry(entry) Entry->>Props: getPageProps(entry) ``` > [!NOTE] > During `onEntries` execution, path normalization uses `PathUtils.slash` to compute relative paths between parent groups and child entries. > Sources: [packages/asyncapi/src/server/index.tsx:174-177](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx#L174-L177) ### Schema Builders and Static Data Mapping The `fromSchema` builder function accepts a schema identifier, a bundled `AsyncAPIObject`, and a configuration object containing a `toPages` callback. It exposes a `PagesBuilder` interface that executes custom page generation logic and provides a `routePathToFilePath` utility function to clean route paths into filesystem-compatible slugs. | Property / Method | Type | Purpose | | :--- | :--- | :--- | | `id` | `string` | The unique schema identifier. | | `document` | `AsyncAPIObject` | The bundled AsyncAPI specification object. | | `dereferenceShallow` | `(schema: T) => NoReferenceSwallow` | Resolves shallow references against the document root. | | `create` | `(entry: OutputEntry) => void` | Appends a generated entry to the output list. | | `routePathToFilePath` | `(path: string) => string` | Sanitizes route paths into filesystem paths. | ```typescript export interface PagesBuilder { id: string; document: AsyncAPIObject; dereferenceShallow: (schema: T) => NoReferenceSwallow; create: (entry: OutputEntry) => void; routePathToFilePath: (path: string) => string; } export function fromSchema( schemaId: string, bundled: AsyncAPIObject, config: PagesBuilderConfig, ): OutputEntry[] { const files: OutputEntry[] = []; const { toPages } = config; toPages({ id: schemaId, document: bundled, dereferenceShallow: (s) => dereferenceShallow(s, bundled), create(entry) { files.push(entry); }, routePathToFilePath(path) { return path .toLowerCase() .replaceAll('.', '-') .split('/') .flatMap((v) => { if (v.startsWith('{') && v.endsWith('}')) return v.slice(1, -1); if (v.length === 0) return []; return v; }) .join('/'); }, }); ``` Sources: [packages/asyncapi/src/utils/pages/builder.ts:49-84](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/builder.ts#L49-L84) > [!CAUTION] > The `routePathToFilePath` utility converts paths to lowercase, replaces periods (`.`) with hyphens (`-`), strips curly brace parameters like `{id}` to their inner values, and filters out empty path segments. > Sources: [packages/asyncapi/src/utils/pages/builder.ts:72-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/builder.ts#L72-L82) Once entries are mapped, `toStaticData` iterates over page operations, generating slugged table of contents items and structured data headings using `github-slugger`. ```typescript export function toStaticData( page: GeneratedPageProps, doc: AsyncAPIObject, ): { toc: TOCItemType[]; structuredData: StructuredData; } { const slugger = new Slugger(); const toc: TOCItemType[] = []; const structuredData: StructuredData = { headings: [], contents: [] }; for (const item of page.operations ?? []) { const operation = dereferenceShallow(doc.operations?.[item.id], doc); if (!operation) continue; if (page.showTitle) { const title = getOperationDisplayName(item.id, operation); const id = slugger.slug(title); toc.push({ depth: 2, title, url: `#${id}`, }); structuredData.headings.push({ content: title, id, }); } if (operation.description) { structuredData.contents.push({ content: operation.description, heading: structuredData.headings.at(-1)?.id, }); } } return { toc, structuredData }; ``` Sources: [packages/asyncapi/src/utils/pages/to-static-data.ts:9-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/to-static-data.ts#L9-L47) ## Automated Page Structuring Presets ### Configuration Options and Preset Types The automatic page structuring pipeline is configured via `createAutoPreset`, which accepts `SchemaToPagesOptions` to determine how AsyncAPI documents are parsed into pages, tags, files, or custom groupings. By default, slugification replaces whitespace characters with hyphens and converts strings to lowercase. | Option | Type | Default | Purpose | | :--- | :--- | :--- | :--- | | `per` | `'file' \| 'tag' \| 'operation' \| 'custom'` | `'operation'` | Determines the partitioning granularity for generated documentation entries. | | `groupBy` | `'tag' \| 'channel' \| 'none' \| function` | `'none'` | Groups operation entries by tag, channel address, or a custom mapper function. | | `name` | `NameFn \| NameFnOptions` | `{ algorithm: 'v2' }` | Customizes file naming using algorithm version `'v1'` or `'v2'`, or a custom name function. | | `slugify` | `(name: string) => string` | `s => s.replace(/\s+/g, '-').toLowerCase()` | Converts titles or identifiers into URL-safe slugs. | ```typescript interface OperationConfig extends BaseConfig { per?: 'operation'; groupBy?: | 'tag' | 'channel' | 'none' | ((entry: DistributiveOmit) => string); name?: NameFn | NameFnOptions; } interface TagConfig extends BaseConfig { per: 'tag'; name?: NameFn | NameFnOptions; } interface SchemaConfig extends BaseConfig { per: 'file'; name?: NameFn | NameFnOptions; } export type SchemaToPagesOptions = | SchemaConfig | TagConfig | OperationConfig | ({ per: 'custom'; } & PagesBuilderConfig); type NameFn = ( this: PagesBuilder, output: DistributiveOmit, ) => string; interface NameFnOptions { algorithm?: 'v2' | 'v1'; } interface BaseConfig { slugify?: (name: string) => string; } ``` Sources: [packages/asyncapi/src/utils/pages/preset-auto.ts:15-54](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/preset-auto.ts#L15-L54) > [!NOTE] > When `per` is set to `'custom'`, `createAutoPreset` bypasses internal generation logic and returns the user-provided `PagesBuilderConfig` object directly. > Sources: [packages/asyncapi/src/utils/pages/preset-auto.ts:56-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/preset-auto.ts#L56-L57) ### Generation Algorithms and Grouping Logic When processing documents under an operation-level preset, the `group` function iterates through operations and organizes them based on the `groupBy` parameter. If `groupBy` is set to `'channel'`, operations resolve their associated channel address to construct group titles and file paths. If set to `'tag'`, operations inspect their `tags` array; if an operation lacks tags, it logs a warning and assigns an `'unknown'` tag fallback before registering entries under corresponding tag directories. ```typescript function group( builder: PagesBuilder, entries: DistributiveOmit[], ): OutputEntry[] { const groups = new Map(); const rest: OutputEntry[] = []; const doc = builder.document; const { groupBy = 'none' } = options as OperationConfig; for (const entry of entries) { switch (groupBy) { case 'channel': { const operation = dereferenceShallow(doc.operations?.[entry.item.id], doc); const channel = operation ? dereferenceShallow(operation.channel, doc) : undefined; const groupName = slugify(channel?.address || entry.item.id); let group = groups.get(groupName); if (!group) { group = { type: 'group', info: { title: channel?.title || channel?.address || groupName, description: channel?.description, }, entries: [], schemaId: builder.id, path: groupName, }; groups.set(groupName, group); } group.entries.push({ ...entry, path: path.join(groupName, `${entry.item.action}.mdx`), }); break; } case 'tag': { const operation = dereferenceShallow(doc.operations?.[entry.item.id], doc)!; let tags = operation.tags?.map((t) => dereferenceShallow(t, doc)); if (!tags || tags.length === 0) { console.warn( 'When `groupBy` is set to `tag`, make sure a `tags` is defined for every operation schema.', ); tags = [{ name: 'unknown' }]; } for (const tag of tags) { const groupId = slugify(tag.name); let group = groups.get(groupId); if (!group) { group = { type: 'group', info: { title: getTagDisplayName(tag), description: tag.description }, tag, entries: [], schemaId: builder.id, path: groupId, }; groups.set(groupId, group); } group.entries.push({ ...entry, path: path.join(groupId, `${nameFn.call(builder, entry)}.mdx`), }); } break; } ``` Sources: [packages/asyncapi/src/utils/pages/preset-auto.ts:88-158](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/preset-auto.ts#L88-L158) > [!WARNING] > When `groupBy` is configured as `'tag'`, ensure that every operation schema defines a `tags` array; otherwise, operations fall back to an `'unknown'` group with a console warning. > Sources: [packages/asyncapi/src/utils/pages/preset-auto.ts:129-134](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/preset-auto.ts#L129-L134) Name resolution algorithms distinguish between file-level and operation-level outputs. Page outputs default to their tag name or extract the base name of the schema file, whereas operation outputs use algorithm `'v2'` to return the operation identifier directly, or algorithm `'v1'` to join the sanitized route path with the operation action (`send` or `receive`). ```typescript let nameFn: NameFn; if (typeof options.name === 'function') { nameFn = options.name as NameFn; } else { const { algorithm = 'v2' } = options.name ?? {}; nameFn = function (result) { if (result.type === 'page') { if (result.tag) return slugify(result.tag.name); const schemaId = result.schemaId; return schemaId.startsWith('http://') || schemaId.startsWith('https://') ? 'index' : path.basename(schemaId, path.extname(schemaId)); } if (algorithm === 'v2') { return result.item.id; } return path.join(this.routePathToFilePath(result.item.id), result.item.action); }; } ``` Sources: [packages/asyncapi/src/utils/pages/preset-auto.ts:63-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/preset-auto.ts#L63-L86) ## Static File and MDX Output ### Execution Flow and Disk Generation Walkthrough The disk generation pipeline transforms generated page structures into serialized MDX files on disk, supporting optional file watching, metadata generation, and custom pre-write hooks. The process begins by calling `generateFiles`, which delegates the core generation work and handles asynchronous file writing or sets up a file watcher via `chokidar`. ```mermaid sequenceDiagram participant generate-file.ts as generate-file.ts participant to-text.ts as to-text.ts generate-file.ts->>generate-file.ts: generateFilesOnly generate-file.ts->>generate-file.ts: writeIndexFiles generate-file.ts->>to-text.ts: fileContent ``` Sources: [packages/asyncapi/src/generate-file.ts:56-134](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/generate-file.ts#L56-L134) 1. `generateFilesOnly` extracts input schemas, invokes `createAutoPreset`, and iterates through entries using `fromSchema` to produce virtual files and metadata objects. Sources: [packages/asyncapi/src/generate-file.ts:83-117](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/generate-file.ts#L83-L117) 2. `writeIndexFiles` constructs index or overview files if an index configuration is specified, mapping relative paths and checking available schema keys. Sources: [packages/asyncapi/src/generate-file.ts:183-209](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/generate-file.ts#L183-L209) 3. `fileContent` builds the card layout containing hyperlinks and descriptions for output entries before passing the accumulated content to `generateDocument`. Sources: [packages/asyncapi/src/generate-file.ts:210-252](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/generate-file.ts#L210-L252) > [!NOTE] > When `options.watch` is enabled, `generateFiles` recursively invokes itself with `watch: false` and registers a chokidar watcher on `input._getWatchPaths()` to trigger regeneration on file changes. > Sources: [packages/asyncapi/src/generate-file.ts:57-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/generate-file.ts#L57-L68) ### YAML Frontmatter Serialization and MDX Generation Document serialization is handled by `toText` and `generateDocument`, which serialize metadata into YAML frontmatter and format the resulting MDX document. Frontmatter properties are processed using `js-yaml`'s `dump` function alongside `removeUndefined`, while optional comments warn consumers against manual file modification. | Option Key | Type | Default | Purpose | | :--- | :--- | :--- | :--- | | `imports` | `Array<{ names: string[]; from: string }>` | `undefined` | Custom import statements prepended to the generated MDX document. | | `frontmatter` | `(title: string, description: string \| undefined, context: DocumentContext) => Record` | `undefined` | Extends or customizes generated YAML frontmatter attributes. | | `includeDescription` | `boolean` | `false` | Controls whether descriptions appear in frontmatter or within page props. | | `addGeneratedComment` | `boolean \| string` | `true` | Appends an automated generation warning comment or a custom string to the file banner. | ```typescript export interface PagesToTextOptions { imports?: { names: string[]; from: string; }[]; frontmatter?: ( title: string, description: string | undefined, context: DocumentContext, ) => Record; includeDescription?: boolean; addGeneratedComment?: boolean | string; } ``` Sources: [packages/asyncapi/src/utils/pages/to-text.ts:15-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/to-text.ts#L15-L27) ```typescript export function generateDocument( frontmatter: unknown, content: string, options: PagesToTextOptions, ): string { const { addGeneratedComment = true, imports } = options; const out: string[] = []; const banner = dump(removeUndefined(frontmatter as object)).trimEnd(); if (banner.length > 0) out.push(`---\n${banner}\n---`); if (addGeneratedComment) { let commentContent = 'This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again.'; if (typeof addGeneratedComment === 'string') { commentContent = addGeneratedComment; } commentContent = commentContent.replaceAll('/', '\\/'); out.push(`{/* ${commentContent} */}`); } if (imports) { out.push( ...imports .map((item) => `import { ${item.names.join(', ')} } from ${doubleQuote(item.from)};`) .join('\n'), ); } out.push(content); return out.join('\n\n'); } ``` Sources: [packages/asyncapi/src/utils/pages/to-text.ts:76-108](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/to-text.ts#L76-L108) > [!WARNING] > Generated comment strings automatically replace all forward slashes with escaped backslashes (`replaceAll('/', '\\/')`) to preserve valid comment syntax in MDX outputs. > Sources: [packages/asyncapi/src/utils/pages/to-text.ts:94-94](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/to-text.ts#L94-L94) ## Operation Traits and Schema Merging AsyncAPI definitions often use reusable traits to share common attributes, metadata, and configurations across operations and messages. The trait merging implementation processes these reusable layers according to the AsyncAPI specification, flattening trait arrays into base objects while omitting the `traits` property itself from the final merged output. The merging engine is driven by `mergeTraits` and `mergeTraitLayer`, which iterate through an array of trait dictionaries and shallow-copy or deep-merge plain objects property by property. When an operation or message object contains a `traits` array, `applyOperationTraits` and `applyMessageTraits` extract the base properties by destructuring away the `traits` field and passing the remaining properties along with the trait layers into `mergeTraits`. | Function Name | Input Parameters | Return Type | Description | | :--- | :--- | :--- | :--- | | `mergeTraits` | `target: T`, `traits: Record[]` | `T` | Sequentially folds multiple trait object layers into a target record. | | `mergeTraitLayer` | `target: Record`, `trait: Record` | `Record` | Recursively merges a single trait layer into a target record, ignoring the `traits` key. | | `applyOperationTraits` | `operation: NoReference` | `NoReference` | Strips the `traits` property from an operation object and merges any declared traits. | | `applyMessageTraits` | `message: NoReference` | `NoReference` | Strips the `traits` property from a message object and merges any declared traits. | ```typescript export function mergeTraits>( target: T, traits: Record[], ): T { let result: Record = { ...target }; for (const trait of traits) { result = mergeTraitLayer(result, trait); } return result as T; } function mergeTraitLayer( target: Record, trait: Record, ): Record { const result: Record = { ...target }; for (const [key, traitValue] of Object.entries(trait)) { if (key === 'traits') continue; const targetValue = result[key]; if (targetValue === undefined) { result[key] = traitValue; } else if (isPlainObject(targetValue) && isPlainObject(traitValue)) { result[key] = mergeTraitLayer(targetValue, traitValue); } } return result; } ``` Sources: [packages/asyncapi/src/utils/traits.ts:9-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/traits.ts#L9-L38) ```typescript export function applyOperationTraits( operation: NoReference, ): NoReference { const traits = operation.traits; if (!traits || traits.length === 0) return operation; const { traits: _, ...base } = operation; return mergeTraits(base, traits); } export function applyMessageTraits( message: NoReference, ): NoReference { const traits = message.traits; if (!traits || traits.length === 0) return message; const { traits: _, ...base } = message; return mergeTraits(base, traits); } ``` Sources: [packages/asyncapi/src/utils/traits.ts:40-58](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/traits.ts#L40-L58) > [!NOTE] > During trait layer merging, the algorithm explicitly checks `if (key === 'traits') continue;` to prevent nested or recursive trait declarations from re-triggering trait application loops. > Sources: [packages/asyncapi/src/utils/traits.ts:26-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/traits.ts#L26-L28) > [!WARNING] > If an operation or message object defines no traits or an empty traits array (`traits.length === 0`), `applyOperationTraits` and `applyMessageTraits` return the original object instance without modification. > Sources: [packages/asyncapi/src/utils/traits.ts:43-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/traits.ts#L43-L44), [packages/asyncapi/src/utils/traits.ts:53-54](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/traits.ts#L53-L54) ## Related - [AsyncAPI Protocol Bindings](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/asyncapi-protocol-bindings) - [API Docs Primitives](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/api-docs-primitives) --- ## Technical docs: AsyncAPI Protocol Bindings URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/asyncapi-protocol-bindings
Relevant source files The following files were used as context for generating this wiki page: - [packages/asyncapi/src/ui/bindings/protocols/amqp.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp.tsx) - [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx) - [packages/asyncapi/src/ui/operation/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/operation/index.tsx) - [packages/asyncapi/src/ui/bindings/protocols/ibmmq.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/ibmmq.tsx) - [packages/asyncapi/src/ui/bindings/protocols/anypointmq.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/anypointmq.tsx) - [packages/asyncapi/src/ui/bindings/protocols/pulsar.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/pulsar.tsx) - [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx) - [packages/asyncapi/src/ui/bindings/protocols/solace.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/solace.tsx) - [packages/openapi/src/ui/operation/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/operation/index.tsx) - [packages/asyncapi/src/ui/bindings/protocols/jms.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/jms.tsx) - [packages/asyncapi/src/ui/bindings/shared.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx) - [packages/asyncapi/src/types/asyncapi-3.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/types/asyncapi-3.ts) - [packages/asyncapi/src/ui/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/index.tsx) - [packages/asyncapi/src/ui/bindings/protocols/sqs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/sqs.tsx) - [packages/asyncapi/src/ui/bindings/protocols/mqtt5.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt5.tsx) - [packages/asyncapi/src/ui/bindings/protocols/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts) - [packages/asyncapi/src/ui/bindings/protocols/googlepubsub.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/googlepubsub.tsx) - [packages/asyncapi/src/ui/bindings/protocols/ws.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/ws.tsx) - [packages/asyncapi/src/ui/operation/message-examples.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/operation/message-examples.tsx) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/asyncapi/src/ui/bindings/protocols/http.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx) - [packages/asyncapi/src/ui/bindings/protocols/sns.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/sns.tsx) - [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx) - [packages/asyncapi/src/ui/bindings/protocols/nats.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/nats.tsx) - [packages/asyncapi/src/ui/bindings/accordion-bindings.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/accordion-bindings.tsx) - [packages/asyncapi/src/ui/bindings/protocols/unknown.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/unknown.tsx) - [packages/asyncapi/src/ui/bindings/protocols/amqp1.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp1.tsx) - [packages/asyncapi/src/ui/bindings/protocols/stomp.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/stomp.tsx) - [packages/asyncapi/src/ui/bindings/protocols/redis.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/redis.tsx) - [packages/asyncapi/src/utils/schema.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/schema.ts)
## Overview The protocol bindings package provides a modular architecture for rendering protocol-specific metadata across servers, channels, operations, and messages in [AsyncAPI Document Processing](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/asyncapi-document-processing) specifications. It translates raw protocol configuration objects into structured user interface components with protocol labels, version badges, summaries, and field rows. Sources: [packages/asyncapi/src/ui/bindings/accordion-bindings.tsx:40-94](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/accordion-bindings.tsx#L40-L94), [packages/asyncapi/src/ui/bindings/shared.tsx:181-203](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L181-L203) ## Protocol binding architecture ### Protocol Registry and Binding Definitions The public API surface revolves around the `protocolBindings` registry and registration helpers [packages/asyncapi/src/ui/bindings/protocols/index.ts:25-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L25-L45), which map bound transport protocols to strongly typed ProtocolBindingDefinition interfaces [packages/asyncapi/src/ui/bindings/shared.tsx:12-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L12-L22). Every protocol entry defines React components for the four AsyncAPI specification levels (`Server`, `Channel`, `Operation`, and `Message`) alongside optional summary generator functions (`getServerSummary`, `getChannelSummary`, `getOperationSummary`, and `getMessageSummary`) [packages/asyncapi/src/ui/bindings/shared.tsx:12-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L12-L22). The protocol registry contains the exact runtime identifiers supported by the rendering layer, mapping each string key to its corresponding configuration module [packages/asyncapi/src/ui/bindings/protocols/index.ts:25-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L25-L45). | Protocol Key | Module Definition | | :--- | :--- | | `kafka` | `kafkaBinding` | | `amqp` | `amqpBinding` | | `amqp1` | `amqp1Binding` | | `http` | `httpBinding` | | `ws` | `wsBinding` | | `mqtt` | `mqttBinding` | | `mqtt5` | `mqtt5Binding` | | `nats` | `natsBinding` | | `anypointmq` | `anypointmqBinding` | | `googlepubsub` | `googlepubsubBinding` | | `ibmmq` | `ibmmqBinding` | | `jms` | `jmsBinding` | | `sns` | `snsBinding` | | `sqs` | `sqsBinding` | | `solace` | `solaceBinding` | | `pulsar` | `pulsarBinding` | | `stomp` | `stompBinding` | | `redis` | `redisBinding` | | `mercure` | `mercureBinding` | Sources: [packages/asyncapi/src/ui/bindings/protocols/index.ts:25-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L25-L45), [packages/asyncapi/src/ui/bindings/shared.tsx:12-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L12-L22) ### Fallback Resolution and Extension Parsing When a protocol string is absent from the static `protocolBindings` record, `getProtocolBinding` falls back to `unknownBinding` while dynamically injecting the raw protocol string as the display label [packages/asyncapi/src/ui/bindings/protocols/index.ts:47-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L47-L55). ```typescript export function getProtocolBinding(protocol: string): ProtocolBindingDefinition { const v = protocolBindings[protocol as never]; if (v) return v; return { ...unknownBinding, label: protocol, }; } ``` Sources: [packages/asyncapi/src/ui/bindings/protocols/index.ts:47-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L47-L55) Simultaneously, `getBindingEntries` inspects raw binding dictionaries, filtering out non-plain objects and separating standard protocol objects from custom vendor extensions prefixed with `x-` [packages/asyncapi/src/ui/bindings/protocols/index.ts:62-77](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L62-L77). > [!NOTE] > Vendor extensions starting with `x-` are separated from standard protocol keys and rendered via `ExtensionContent`, which formats the raw extension payload inside a `ClientCodeBlock` component using JSON syntax [packages/asyncapi/src/ui/bindings/accordion-bindings.tsx:122-154](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/accordion-bindings.tsx#L122-L154). Sources: [packages/asyncapi/src/ui/bindings/protocols/index.ts:62-77](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L62-L77), [packages/asyncapi/src/ui/bindings/accordion-bindings.tsx:122-154](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/accordion-bindings.tsx#L122-L154) ## Shared binding UI primitives ### Core Rendering Helpers and Scalar Formatting The core formatting functions and layout components normalize raw record values into structured definition lists, labels, and tagged elements. The `formatBindingScalar` function handles primitive JavaScript types, converting `null` and `undefined` to empty strings, booleans to `'Yes'` or `'No'`, arrays recursively, and serializing complex objects via `JSON.stringify` [packages/asyncapi/src/ui/bindings/shared.tsx:24-34](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L24-L34). The `hasBindingFields` helper checks if a binding dictionary contains actionable configuration keys, explicitly ignoring `bindingVersion` and any vendor extensions starting with `x-` [packages/asyncapi/src/ui/bindings/shared.tsx:36-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L36-L43). ```tsx export function formatBindingScalar(value: unknown): string { if (value === null || value === undefined) return ''; if (typeof value === 'boolean') return value ? 'Yes' : 'No'; if (typeof value === 'number') return String(value); if (typeof value === 'string') return value; if (Array.isArray(value)) { return value.map((item) => formatBindingScalar(item)).join(', '); } return JSON.stringify(value); } export function hasBindingFields( binding: Record, ignore: string[] = ['bindingVersion'], ): boolean { return Object.keys(binding).some( (key) => !ignore.includes(key) && !key.startsWith('x-') && binding[key] !== undefined, ); } ``` Sources: [packages/asyncapi/src/ui/bindings/shared.tsx:24-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L24-L43) > [!NOTE] > `hasBindingFields` evaluates object keys using `Object.keys(binding).some(...)`, ignoring keys present in the `ignore` array (defaulting to `['bindingVersion']`) and filtering out any keys beginning with `x-` or where values equal `undefined` [packages/asyncapi/src/ui/bindings/shared.tsx:36-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L36-L43). Sources: [packages/asyncapi/src/ui/bindings/shared.tsx:36-43](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L36-L43) ### UI Layout Components and Value Primitives Layout rendering relies on specialized components that structure fields into definition lists and groups. `BindingFields` renders a `dl` element with the `not-prose` class [packages/asyncapi/src/ui/bindings/shared.tsx:52-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L52-L60), while `BindingFieldRow` constructs a responsive CSS grid separating terms (`dt`) from descriptions (`dd`) with bottom border dividers [packages/asyncapi/src/ui/bindings/shared.tsx:81-101](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L81-L101). Additional specialized wrappers handle scalar values, tag lists, schema definitions, and empty states. | Component Name | Description | | :--- | :--- | | `BindingFields` | Wraps children inside a `dl` element with `not-prose` styling [packages/asyncapi/src/ui/bindings/shared.tsx:52-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L52-L60) | | `BindingEmpty` | Displays translated text `'No additional configuration for this binding.'` in muted font [packages/asyncapi/src/ui/bindings/shared.tsx:62-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L62-L70) | | `BindingGroup` | Container card with a rounded border, secondary background, and an optional title header [packages/asyncapi/src/ui/bindings/shared.tsx:72-79](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L72-L79) | | `BindingFieldRow` | Two-column grid component aligning definition labels and descriptive values [packages/asyncapi/src/ui/bindings/shared.tsx:81-101](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L81-L101) | | `BindingScalarValue` | Formats scalars with code styling for strings/numbers, or emerald/muted badges for booleans [packages/asyncapi/src/ui/bindings/shared.tsx:103-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L103-L126) | | `BindingTagList` | Renders a flex-wrap container of key-value tag badge elements [packages/asyncapi/src/ui/bindings/shared.tsx:128-145](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L128-L145) | | `BindingSchema` | Injects schema objects into context-provided schema rendering components [packages/asyncapi/src/ui/bindings/shared.tsx:147-166](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L147-L166) | Sources: [packages/asyncapi/src/ui/bindings/shared.tsx:52-166](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/shared.tsx#L52-L166) ## Kafka messaging and operation bindings ### Server and Channel Configuration The Kafka protocol binding implementation processes server, channel, operation, and message bindings to render specific metadata [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:189-199](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L189-L199). The `KafkaServerBinding` component inspects server binding definitions for registry metadata [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:75-94](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L75-L94). If fields are missing, it falls back to `BindingEmpty` [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L76). Otherwise, it outputs rows for `schemaRegistryUrl` and `schemaRegistryVendor` [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:80-91](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L80-L91). Summary generation via `getKafkaServerSummary` joins these registry properties using `joinBindingSummary` [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:23-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L23-L25). ```tsx function getKafkaServerSummary(binding: NoReference): string | undefined { return joinBindingSummary(binding.schemaRegistryUrl, binding.schemaRegistryVendor); } function getKafkaChannelSummary(binding: NoReference): string | undefined { const parts: string[] = []; if (binding.topic) parts.push(binding.topic); if (typeof binding.partitions === 'number') { parts.push(`${binding.partitions} partition${binding.partitions === 1 ? '' : 's'}`); } if (typeof binding.replicas === 'number') { parts.push(`${binding.replicas} replica${binding.replicas === 1 ? '' : 's'}`); } return parts.length > 0 ? parts.join(' · ') : undefined; } ``` Sources: [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:23-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L23-L37) The `KafkaChannelBinding` component renders topic details, partition counts, replica counts, and nested topic settings [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:96-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L96-L133). When `topicConfiguration` is present, it constructs a `BindingGroup` titled `'Kafka topic settings'` containing key-value pairs rendered through `BindingScalarValue` [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:113-130](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L113-L130). | Kafka Channel Field | Source Property | Render Component / Formatting | | :--- | :--- | :--- | | Topic | `binding.topic` | `{binding.topic}` [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:101-103](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L101-L103) | | Partitions | `binding.partitions` | `` [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:104-109](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L104-L109) | | Replicas | `binding.replicas` | `` [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:110-112](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L110-L112) | | Topic Configuration | `binding.topicConfiguration` | `` [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:113-130](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L113-L130) | Sources: [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:96-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:96-L133) > [!NOTE] > `getKafkaChannelSummary` formats partition and replica counts dynamically, handling singular and plural forms based on whether the numeric value equals `1` (e.g., `1 partition` versus `2 partitions`) and joining all non-empty parts with `·` [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:27-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L27-L37). Sources: [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:27-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L27-L37) ### Operation and Message Bindings Operation bindings manage consumer group identifiers and client configurations [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:135-154](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L135-L154). The `KafkaOperationBinding` component renders `groupId` and `clientId` schemas using the `BindingSchema` component [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:140-152](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L140-L152). ```tsx function getKafkaOperationSummary(binding: NoReference): string | undefined { const parts: string[] = []; const groupId = getBindingSchemaSummary(binding.groupId); const clientId = getBindingSchemaSummary(binding.clientId); if (binding.groupId) parts.push(`group: ${groupId}`); if (clientId) parts.push(`client: ${clientId}`); return parts.length > 0 ? parts.join(' · ') : undefined; } ``` Sources: [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:39-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L39-L46) Message bindings configure message keys and serialization schemas [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:156-187](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L156-L187). `KafkaMessageBinding` inspects four specific properties to build its field rows [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:156-187](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L156-L187). | Message Binding Property | Field Label | Render Strategy | | :--- | :--- | :--- | | `binding.key` | Message Key | `` [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:161-166](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L161-L166) | | `binding.schemaIdLocation` | Schema ID Location | `` [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:167-172](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L167-L172) | | `binding.schemaIdPayloadEncoding` | Schema ID Payload Encoding | `{binding.schemaIdPayloadEncoding}` [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:173-178](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L173-L178) | | `binding.schemaLookupStrategy` | Schema Lookup Strategy | `{binding.schemaLookupStrategy}` [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:179-185](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L179-L185) | Sources: [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:156-187](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:156-L187) > [!WARNING] > `getBindingSchemaSummary` extracts summaries for schema objects by checking properties in a strict priority order: first returning comma-separated enumeration values (`schema.enum`), then constant values (`schema.const`), default values (`schema.default`), and finally falling back to the raw `schema.type` string [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:48-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L48-L68). Sources: [packages/asyncapi/src/ui/bindings/protocols/kafka.tsx:48-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/kafka.tsx#L48-L68) ## MQTT protocol binding configurations ### MQTT Server, Operation, and Message Bindings The MQTT protocol binding renderer manages configuration parameters across servers, operations, and messages through dedicated binding components defined in `mqtt.tsx` and `mqtt5.tsx`. For servers, fields such as `clientId`, `cleanSession`, `keepAlive`, `sessionExpiryInterval`, and `maximumPacketSize` are evaluated and rendered using scalar values or schema components depending on their type [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:48-94](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L48-L94). The `lastWill` property creates a nested binding group containing its own topic, quality of service, message, and retain flags [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:95-129](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L95-L129). Additionally, `mqtt5Binding` supplies an isolated server binding component that processes `sessionExpiryInterval` fields for MQTT 5 specifications [packages/asyncapi/src/ui/bindings/protocols/mqtt5.tsx:14-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt5.tsx#L14-L33). Sources: [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:48-129](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L48-L129), [packages/asyncapi/src/ui/bindings/protocols/mqtt5.tsx:14-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt5.tsx#L14-L33) > [!NOTE] > The `formatQos` helper function translates numeric quality of service codes into descriptive strings: `0` maps to `At most once (0)`, `1` maps to `At least once (1)`, and `2` maps to `Exactly once (2)` [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:20-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L20-L25). Sources: [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:20-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L20-L25) ### Quality of Service and Payload Formats Operation bindings handle MQTT delivery guarantees and retention settings, exposing quality of service levels, retain flags, and message expiry intervals [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:134-164](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L134-L164). Message bindings format payload characteristics, supporting payload format indicators via `formatPayloadFormatIndicator`, correlation data, content types, and response topics [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:167-207](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L167-L207). | MQTT Binding Type | Property Name | Formatting / Component Strategy | | :--- | :--- | :--- | | Server | `binding.clientId` | `{binding.clientId}` [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:53-58](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L53-L58) | | Server | `binding.lastWill` | `` with nested topic, QoS, message, and retain fields [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:95-128](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L95-L128) | | Operation | `binding.qos` | `{formatQos(binding.qos)}` [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:139-144](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L139-L144) | | Operation | `binding.messageExpiryInterval` | Conditional `` or `` [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:151-162](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L151-L162) | | Message | `binding.payloadFormatIndicator` | `{formatPayloadFormatIndicator(...)}` [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:172-181](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L172-L181) | | Message | `binding.responseTopic` | Conditional `` or `` [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:194-204](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L194-L204) | Sources: [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:53-204](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L53-L204) > [!WARNING] > `formatPayloadFormatIndicator` checks if the numeric value equals `1` to return `UTF-8 (1)` and `0` for `Unspecified bytes (0)`, falling back to the raw string representation for any other numeric input [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:27-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L27-L31). Sources: [packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx:27-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/mqtt.tsx#L27-L31) ## AMQP and SQS messaging bindings ### AMQP Channel, Operation, and Message Bindings The AMQP protocol binding renderer manages configuration parameters across channels, operations, and messages through dedicated components defined in `amqp.tsx`. Channel bindings process binding targets, exchanges, and queues via helper functions like `formatAmqpIs` and `getAmqpChannelSummary` [packages/asyncapi/src/ui/bindings/protocols/amqp.tsx:19-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp.tsx#L19-L37). Exchange fields evaluate names, types, durability, auto-deletion, and virtual hosts, while queue fields handle name, durability, exclusivity, auto-deletion, and virtual host settings [packages/asyncapi/src/ui/bindings/protocols/amqp.tsx:46-103](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp.tsx#L46-L103). Operation bindings expose message TTL, user ID, CC, BCC, priority, delivery mode, mandatory flags, timestamps, and acknowledgements, utilizing `formatAmqpDeliveryMode` to map values `1` and `2` to non-persistent and persistent modes packages/asyncapi/src/ui/bindings/protocols/amqp.tsx:25-29, 141-192. Message bindings process content encoding and message types, combining them into summary strings via `getAmqpMessageSummary` packages/asyncapi/src/ui/bindings/protocols/amqp.tsx:39-44, 195-214. Sources: [packages/asyncapi/src/ui/bindings/protocols/amqp.tsx:19-214](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp.tsx#L19-L214) > [!NOTE] > The `amqp1Binding` export utilizes the shared `createBinding` helper with a label of `AMQP 1.0`, providing a lightweight entry point without custom rendering extensions [packages/asyncapi/src/ui/bindings/protocols/amqp1.tsx:1-3](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp1.tsx#L1-L3). Sources: [packages/asyncapi/src/ui/bindings/protocols/amqp1.tsx:1-3](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp1.tsx#L1-L3) ### Amazon SQS Channel and Operation Bindings The Amazon SQS protocol binding renderer configures queues and dead-letter queues across channels and operations through `sqs.tsx`. Channel bindings check for standard queues and dead-letter queues, rendering each through `SqsQueueFields` inside binding field rows [packages/asyncapi/src/ui/bindings/protocols/sqs.tsx:62-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/sqs.tsx#L62-L81). Operation bindings map over an array of queues, rendering each queue dynamically based on its index and name [packages/asyncapi/src/ui/bindings/protocols/sqs.tsx:83-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/sqs.tsx#L83-L97). Queue configuration properties include name, FIFO queue status, visibility timeout, message retention period, and custom tags rendered via `BindingTagList` [packages/asyncapi/src/ui/bindings/protocols/sqs.tsx:17-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/sqs.tsx#L17-L47). Summary generators extract queue names for channels, while operations format multiple queues by appending overflow counts such as `${first.name} +${queues.length - 1}` [packages/asyncapi/src/ui/bindings/protocols/sqs.tsx:50-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/sqs.tsx#L50-L60). Sources: [packages/asyncapi/src/ui/bindings/protocols/sqs.tsx:17-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/sqs.tsx#L17-L97) | Protocol Binding | Binding Type | Property Name | Formatting / Component Strategy | | :--- | :--- | :--- | :--- | | AMQP | Channel | `binding.is` | `{formatAmqpIs(binding.is)}` [packages/asyncapi/src/ui/bindings/protocols/amqp.tsx:111-116](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp.tsx#L111-L116) | | AMQP | Channel | `binding.exchange` | `` with `AmqpExchangeFields` [packages/asyncapi/src/ui/bindings/protocols/amqp.tsx:117-125](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp.tsx#L117-L125) | | AMQP | Operation | `binding.deliveryMode` | `{formatAmqpDeliveryMode(binding.deliveryMode)}` [packages/asyncapi/src/ui/bindings/protocols/amqp.tsx:167-172](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp.tsx#L167-L172) | | AMQP | Message | `binding.contentEncoding` | `{binding.contentEncoding}` [packages/asyncapi/src/ui/bindings/protocols/amqp.tsx:200-205](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp.tsx#L200-L205) | | Amazon SQS | Channel | `binding.deadLetterQueue` | `` component instance [packages/asyncapi/src/ui/bindings/protocols/sqs.tsx:73-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/sqs.tsx#L73-L78) | | Amazon SQS | Operation | `binding.queues` | Mapped array using `` and `` [packages/asyncapi/src/ui/bindings/protocols/sqs.tsx:88-94](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/sqs.tsx#L88-L94) | Sources: [packages/asyncapi/src/ui/bindings/protocols/amqp.tsx:111-205](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp.tsx#L111-L205), [packages/asyncapi/src/ui/bindings/protocols/sqs.tsx:73-94](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/sqs.tsx#L73-L94) > [!WARNING] > `formatAmqpIs` strictly expects `queue` or `routingKey` to output `Queue` or `Routing Key`, returning any other unhandled string directly without transformation [packages/asyncapi/src/ui/bindings/protocols/amqp.tsx:19-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp.tsx#L19-L23). Sources: [packages/asyncapi/src/ui/bindings/protocols/amqp.tsx:19-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/amqp.tsx#L19-L23) ## WebSockets and HTTP network bindings ### WebSocket Channel Configuration The WebSocket protocol binding renderer handles channel configurations through `ws.tsx`, exporting `wsBinding` with a label of `WebSocket` [packages/asyncapi/src/ui/bindings/protocols/ws.tsx:42-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/ws.tsx#L42-L46). The `getWsChannelSummary` function extracts the HTTP/WebSocket method directly from the binding object [packages/asyncapi/src/ui/bindings/protocols/ws.tsx:14-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/ws.tsx#L14-L16). The `WsChannelBinding` component checks for active fields via `hasBindingFields`; if none exist, it renders `BindingEmpty` [packages/asyncapi/src/ui/bindings/protocols/ws.tsx:18-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/ws.tsx#L18-L20). When fields are present, it wraps them in `BindingFields` and populates optional properties including `method`, `query`, and `headers` [packages/asyncapi/src/ui/bindings/protocols/ws.tsx:21-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/ws.tsx#L21-L39). Query parameters and headers are rendered using the `BindingSchema` component, while scalar methods use `BindingScalarValue` [packages/asyncapi/src/ui/bindings/protocols/ws.tsx:23-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/ws.tsx#L23-L37). Sources: [packages/asyncapi/src/ui/bindings/protocols/ws.tsx:1-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/ws.tsx#L1-L46) ### HTTP Operation and Message Bindings The HTTP protocol binding renderer processes operations and messages via `http.tsx`, exporting `httpBinding` with an `HTTP` label [packages/asyncapi/src/ui/bindings/protocols/http.tsx:63-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx#L63-L69). Operation bindings utilize `getHttpOperationSummary` to return the HTTP method string [packages/asyncapi/src/ui/bindings/protocols/http.tsx:14-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx#L14-L16), while message bindings use `getHttpMessageSummary` to convert numeric status codes into strings [packages/asyncapi/src/ui/bindings/protocols/http.tsx:18-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx#L18-L20). `HttpOperationBinding` renders `method` and `query` parameters through `BindingScalarValue` and `BindingSchema` [packages/asyncapi/src/ui/bindings/protocols/http.tsx:22-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx#L22-L41). `HttpMessageBinding` processes `headers` schema definitions and checks whether `statusCode` is explicitly defined before rendering scalar status codes [packages/asyncapi/src/ui/bindings/protocols/http.tsx:43-62](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx#L43-L62). Sources: [packages/asyncapi/src/ui/bindings/protocols/http.tsx:1-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx#L1-L69) | Protocol | Binding Target | Property Name | Component / Handler | | :--- | :--- | :--- | :--- | | WebSocket | Channel | `binding.method` | `BindingScalarValue` [packages/asyncapi/src/ui/bindings/protocols/ws.tsx:23-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/ws.tsx#L23-L25) | | WebSocket | Channel | `binding.query` | `BindingSchema` (`name="query"`) [packages/asyncapi/src/ui/bindings/protocols/ws.tsx:26-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/ws.tsx#L26-L31) | | WebSocket | Channel | `binding.headers` | `BindingSchema` (`name="headers"`) [packages/asyncapi/src/ui/bindings/protocols/ws.tsx:32-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/ws.tsx#L32-L37) | | HTTP | Operation | `binding.method` | `BindingScalarValue` [packages/asyncapi/src/ui/bindings/protocols/http.tsx:27-32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx#L27-L32) | | HTTP | Operation | `binding.query` | `BindingSchema` (`name="query"`) [packages/asyncapi/src/ui/bindings/protocols/http.tsx:33-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx#L33-L38) | | HTTP | Message | `binding.headers` | `BindingSchema` (`name="headers"`) [packages/asyncapi/src/ui/bindings/protocols/http.tsx:48-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx#L48-L53) | | HTTP | Message | `binding.statusCode` | `BindingScalarValue` [packages/asyncapi/src/ui/bindings/protocols/http.tsx:54-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx#L54-L59) | Sources: [packages/asyncapi/src/ui/bindings/protocols/ws.tsx:23-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/ws.tsx#L23-L37), [packages/asyncapi/src/ui/bindings/protocols/http.tsx:27-59](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx#L27-L59) > [!NOTE] > `getHttpMessageSummary` validates that `binding.statusCode` is strictly of type `'number'` before casting it via `String()`, returning `undefined` for any non-numeric status code values [packages/asyncapi/src/ui/bindings/protocols/http.tsx:18-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx#L18-L20). Sources: [packages/asyncapi/src/ui/bindings/protocols/http.tsx:18-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/http.tsx#L18-L20) ## Unsupported and fallback protocol rendering ### Fallback Protocol Resolution When a protocol identifier specified in an AsyncAPI document does not match any entry in the built-in `protocolBindings` registry, the UI falls back to a generic renderer [packages/asyncapi/src/ui/bindings/protocols/index.ts:47-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L47-L55). The lookup function `getProtocolBinding` checks the protocol key against the supported record, and if it is absent, returns a copy of `unknownBinding` with its label overridden by the unrecognized protocol string [packages/asyncapi/src/ui/bindings/protocols/index.ts:47-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L47-L55). Sources: [packages/asyncapi/src/ui/bindings/protocols/index.ts:47-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L47-L55) ### Unknown Binding Content and Extensions The fallback handler `unknownBinding` defines `Server`, `Channel`, `Operation`, and `Message` handlers using `UnknownBindingContent` [packages/asyncapi/src/ui/bindings/protocols/unknown.tsx:11-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/unknown.tsx#L11-L17). This component serializes the raw binding object into a formatted JSON code block via `JSON.stringify`, wrapped in a `ClientCodeBlock` component [packages/asyncapi/src/ui/bindings/protocols/unknown.tsx:6-9](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/unknown.tsx#L6-L9). Similarly, `getBindingEntries` separates custom vendor extensions starting with `x-` from standard protocol bindings, allowing both unknown protocols and extensions to be inspected as raw structured data [packages/asyncapi/src/ui/bindings/protocols/index.ts:62-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L62-L78). Sources: [packages/asyncapi/src/ui/bindings/protocols/unknown.tsx:6-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/unknown.tsx#L6-L17), [packages/asyncapi/src/ui/bindings/protocols/index.ts:62-78](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L62-L78) > [!WARNING] > `getBindingEntries` relies on `isPlainObject` validation for every entry in the bindings record, silently discarding non-object values before partitioning them into protocols and vendor extensions [packages/asyncapi/src/ui/bindings/protocols/index.ts:69-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L69-L76). Sources: [packages/asyncapi/src/ui/bindings/protocols/index.ts:69-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/bindings/protocols/index.ts#L69-L76) ## Related - [AsyncAPI Document Processing](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/api-documentation/asyncapi-document-processing) --- ## Technical docs: Obsidian Vault Integration URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/obsidian-vault-integration
Relevant source files The following files were used as context for generating this wiki page: - [packages/obsidian/src/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts) - [packages/obsidian/src/convert.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/convert.ts) - [packages/obsidian/src/remark/remark-convert.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-convert.ts) - [packages/obsidian/src/remark/remark-wikilinks.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-wikilinks.ts) - [packages/obsidian/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/index.ts) - [packages/obsidian/src/build-storage.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/build-storage.ts) - [packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts) - [packages/python/src/convert.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/convert.ts) - [packages/obsidian/src/remark/remark-obsidian-comment.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-obsidian-comment.ts) - [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts) - [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts) - [packages/core/src/mdx-plugins/remark-llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts) - [packages/mdx/src/loaders/mdx/remark-postprocess.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-postprocess.ts) - [packages/asyncapi/src/utils/pages/to-text.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/to-text.ts) - [packages/core/src/mdx-plugins/remark-structure.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts) - [packages/obsidian/src/remark/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/index.ts) - [packages/obsidian/src/remark/remark-block-id.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-block-id.ts) - [packages/core/src/mdx-plugins/rehype-toc.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/rehype-toc.ts) - [packages/sanity/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts) - [packages/preview/src/lib/source/storage.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/storage.ts) - [packages/core/src/mdx-plugins/remark-mdx-files.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-mdx-files.ts) - [packages/openapi/src/utils/pages/to-text.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-text.ts) - [packages/twoslash/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/src/index.ts) - [packages/basehub/src/toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx) - [packages/core/src/mdx-plugins/remark-steps.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-steps.ts) - [packages/preview/src/components/markdown.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/markdown.tsx) - [packages/core/src/source/llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/llms.ts) - [packages/content/src/runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts)
## Overview Obsidian Vault Integration empowers Fumadocs to ingest, parse, and transform raw Obsidian vaults directly into standards-compliant MDX content, assets, and structured metadata. By bridging proprietary Obsidian markdown features with modern documentation tooling, it resolves critical incompatibilities surrounding internal referencing and block formatting. The integration embodies design decisions focused on unified processor pipelines, virtual vault storage, and robust AST transformations that make interconnected knowledge bases fully compatible with [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) and [Local Markdown Runtime](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/local-markdown-runtime). Sources: [packages/obsidian/src/convert.ts:57-118](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/convert.ts#L57-L118), [packages/obsidian/src/mdx/index.ts:16-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts#L16-L44), [packages/obsidian/src/build-storage.ts:73-138](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/build-storage.ts#L73-L138) ## Public vault processing interface ### Public API functions and configuration options The public interface for the Obsidian integration centers around the `fromVault` function and `writeVaultFiles`, supported by structured configuration types. The `Options` interface extends `ReadFilesOptions` by incorporating optional `convert` properties via `ConvertOptions` and output parameters via `WriteFilesOptions`. Executing `fromVault` invokes `readVaultFiles` with the provided configuration, passes the resulting files to `convertVaultFiles`, and finally writes out the serialized artifacts using `writeVaultFiles`. ```typescript export interface Options extends ReadFilesOptions { convert?: ConvertOptions; out?: WriteFilesOptions; } export async function fromVault(options: Options) { const files = await readVaultFiles(options); const converted = await convertVaultFiles(files, options.convert); await writeVaultFiles(converted, options.out); } ``` Sources: [packages/obsidian/src/index.ts:10-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/index.ts#L10-L20) | Option Property | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `publicDir` | `string` | `'public'` | Target directory for asset outputs mapped from media files. | | `contentDir` | `string` | `'content/docs/vault'` | Target directory for parsed content and data files. | | `remarkPlugins` | `PluggableList` | `[]` | Extra remark plugins added to the parsing processor pipeline. | | `transformFrontmatter` | `function` | `undefined` | Callback hook to modify generated frontmatter data per file. | Sources: [packages/obsidian/src/index.ts:28-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/index.ts#L28-L28), [packages/obsidian/src/convert.ts:34-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/convert.ts#L34-L49) > [!NOTE] > The `convertVaultFiles` processor integrates `remarkParse`, `remarkGfm`, `remarkMath`, user-supplied `remarkPlugins`, and internal storage plugins before initializing stringification via `remarkMdx` and `remarkStringify`. > Sources: [packages/obsidian/src/convert.ts:65-71](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/convert.ts#L65-L71) ### Output serialization and directory mapping The file writing mechanism handles discrete output categories produced during vault conversion. The `writeVaultFiles` function accepts an array of `OutputFile` objects alongside `WriteFilesOptions`, mapping each file type to a designated base directory. ```typescript export async function writeVaultFiles(files: OutputFile[], options: WriteFilesOptions = {}) { const { publicDir = 'public', contentDir = 'content/docs/vault' } = options; const map = { asset: publicDir, content: contentDir, data: contentDir, custom: '', } as const; await Promise.all( files.map(async (file) => { const mappedPath = path.join(map[file.type], file.path); await fs.mkdir(path.dirname(mappedPath), { recursive: true }); await fs.writeFile(mappedPath, file.content); }), ); } ``` Sources: [packages/obsidian/src/index.ts:27-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/index.ts#L27-L44) > [!WARNING] > When `file.type` is set to `'custom'`, `map['custom']` resolves to an empty string, causing the target file path to be written directly relative to the current working directory unless absolute path resolution is managed upstream. > Sources: [packages/obsidian/src/index.ts:34-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/index.ts#L34-L39) ## Vault storage and path normalization ### File discovery and path normalization The storage engine processes raw vault inputs through path normalization and classification. The `buildStorage` function accepts an array of `VaultFile` objects and optional configuration, iterating through each file to normalize paths, resolve output destinations via rename presets or custom functions, and categorize files into distinct formats (`content`, `data`, or `media`). ```typescript export function buildStorage( rawFiles: VaultFile[], options: VaultStorageOptions = {}, ): VaultStorage { const { url = (file) => { const segs = normalize(file) .split('/') .filter((v) => v.length > 0); return `/${segs.join('/')}`; }, outputPath: outputPathOption = 'simple', enforceMdx = true, } = options; const getOutputPath = typeof outputPathOption === 'function' ? outputPathOption : createRenameOutput(outputPathOption); const storage = new Map(); for (const rawFile of rawFiles) { const normalizedPath = normalize(rawFile.path); let outPath = getOutputPath(normalizedPath, rawFile); let parsed: ParsedFile; const ext = path.extname(normalizedPath); if (['.json', '.yaml', '.yml', '.toml'].includes(ext)) { parsed = { format: 'data', path: normalizedPath, _raw: rawFile._raw, outPath, content: rawFile.content, }; } else if (['.md', '.mdx'].includes(ext)) { const { data, content } = frontmatter(String(rawFile.content)); if (enforceMdx) { outPath = outPath.slice(0, -path.extname(outPath).length) + '.mdx'; } parsed = { format: 'content', _raw: rawFile._raw, path: normalizedPath, outPath, frontmatter: frontmatterSchema.parse(data), content, }; } else { parsed = { format: 'media', path: normalizedPath, _raw: rawFile._raw, outPath, content: rawFile.content, url: url(outPath, rawFile), }; } storage.set(normalizedPath, parsed); } return { files: storage }; } ``` Sources: [packages/obsidian/src/build-storage.ts:73-138](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/build-storage.ts#L73-L138) Path normalization is handled by the `normalize` helper, which enforces directory traversal security by throwing an error if a path points outside the vault. It normalizes directory separators using `slash` and strips leading `./` relative prefixes. ```typescript function normalize(filePath: string): string { filePath = slash(filePath); if (filePath.startsWith('../')) throw new Error(`${filePath} points outside of vault folder`); return filePath.startsWith('./') ? filePath.slice(2) : filePath; } ``` Sources: [packages/obsidian/src/build-storage.ts:160-165](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/build-storage.ts#L160-L165) > [!CAUTION] > Any file path beginning with `../` triggers an immediate error during path normalization, preventing unauthorized traversal outside the designated vault folder boundary. > Sources: [packages/obsidian/src/build-storage.ts:162-162](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/build-storage.ts#L162-L162) ### Call-chain execution walkthrough The initialization sequence for processing vault files through `remarkObsidian` executes the following call chain: 1. `remarkObsidian` — Receives `files` and initializes `buildStorage` with custom options. 2. `buildStorage` — Iterates over raw files and invokes path handling. 3. `normalize` — Sanitizes path separators and checks for directory traversal violations. ```mermaid sequenceDiagram participant remarkObsidian as remarkObsidian (mdx/index.ts) participant buildStorage as buildStorage (build-storage.ts) participant normalize as normalize (build-storage.ts) remarkObsidian->>buildStorage: buildStorage(files, options) loop For each rawFile buildStorage->>normalize: normalize(rawFile.path) normalize-->>buildStorage: normalizedPath end ``` Sources: [packages/obsidian/src/mdx/index.ts:16-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts#L16-L22), [packages/obsidian/src/build-storage.ts:73-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/build-storage.ts#L73-L95), [packages/obsidian/src/build-storage.ts:160-165](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/build-storage.ts#L160-L165) ### Storage configuration options and parsed file formats | Option Parameter | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `outputPath` | `RenameOutputFn \| RenameOutputPreset` | `'simple'` | Strategy or function used to transform output file paths (`'simple'` or `'ignore'`). | | `url` | `function` | `(file) => /{normalized}` | Generates URLs for media files based on output paths. | | `enforceMdx` | `boolean` | `true` | Forces all Markdown documents to use the `.mdx` extension. | Sources: [packages/obsidian/src/build-storage.ts:11-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/build-storage.ts#L11-L30) > [!NOTE] > When `enforceMdx` is active, content files ending in `.md` have their output extension rewritten to `.mdx` after frontmatter extraction. > Sources: [packages/obsidian/src/build-storage.ts:111-113](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/build-storage.ts#L111-L113) ## Wikilink resolution and ref linking ### AST traversal and text replacement The `remarkWikilinks` transformer uses `unist-util-visit` to traverse the Markdown Abstract Syntax Tree (AST), targeting `paragraph` nodes to locate and replace Obsidian wikilink syntax. When processing a paragraph, it recursively visits child elements to inspect text nodes while maintaining parent stack references. ```typescript visit(tree, 'paragraph', (node, index, parent) => { if (typeof index !== 'number' || !parent) return; const replaceParagraph: RootContent[] = [node]; let parents: Parent[] = []; function traverse(cur: RootContent) { if (cur.type === 'text') { const output = resolveParagraphText(cur.value, sourceFile, resolver); const idx = parents[0].children.indexOf(cur); let insertIdx = idx; parents[0].children.splice(insertIdx, 1); for (const item of output) { if (item.inParagraph) { parents[0].children.splice(insertIdx, 0, ...item.children); insertIdx += item.children.length; } else { replaceParagraph.push(...item.children); // clone parents parents = structuredClone(parents); // removed inserted elements parents[0].children.splice(idx, insertIdx - idx); insertIdx = idx; replaceParagraph.push(parents.at(-1) as Paragraph); } } return; } if ('children' in cur && Array.isArray(cur.children)) { parents.unshift(cur); for (const child of cur.children) { traverse(child); } parents.shift(); } } traverse(node); parent.children.splice(index, 1, ...replaceParagraph); }); ``` Sources: [packages/obsidian/src/remark/remark-wikilinks.ts:28-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-wikilinks.ts#L28-L70) The text content of paragraphs is parsed using regular expressions designed to capture standard wikilinks and embedded assets. The `RegexWikilink` pattern matches both standard and embedded bracketed references across text strings. ```typescript const RegexWikilink = /!?\[\[(?([^\]]|\\])+)]]/g; const RegexContent = /^(?(?:\\#|\\\||[^#|])*)(?:#(?(?:\\\||[^|])+))?(?:\|(?.+))?$/; ``` Sources: [packages/obsidian/src/remark/remark-wikilinks.ts:15-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-wikilinks.ts#L15-L17) > [!WARNING] > Matching unescaped pipes or hash characters inside wikilink syntax incorrectly splits target paths, headings, and aliases. The `RegexContent` parser strictly separates name, heading, and alias parts using explicit group boundaries. > Sources: [packages/obsidian/src/remark/remark-wikilinks.ts:16-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-wikilinks.ts#L16-L17) ### Wikilink parsing and resolution rules The `resolveWikilink` function processes extracted wikilink components based on whether the reference is an embedded asset (prefixed with `!`) or a standard hyperlink. It handles heading-only references, media files, and link aliases. ```typescript function resolveWikilink( isEmbed: boolean, content: string, sourceFile: ParsedFile, resolver: VaultResolver, ): RootContent | undefined { const match = RegexContent.exec(content); if (!match?.groups) return; const { name, heading, alias } = match.groups as { name: string; heading?: string; alias?: string; }; const isHeadingOnly = name.length === 0 && heading; if (isEmbed) { const ref = isHeadingOnly ? sourceFile : resolver.resolveAny(name, sourceFile.path); if (!ref || ref.format === 'data') { console.warn(`failed to resolve ${name} wikilink`); return; } if (ref.format === 'content') { console.warn( 'some features of embed content blocks are not supported yet, use at your own risk.', ); return { type: 'mdxJsxFlowElement', name: 'include', attributes: [], children: [ { type: 'paragraph', children: [ { type: 'text', value: getFileHref(ref, sourceFile, heading), }, ], }, ], } satisfies MdxJsxFlowElement; } if (alias) console.warn('we do not support specifying image size like `![[image.png|300]].'); return { type: 'image', url: ref.url ?? getFileHref(ref, sourceFile, heading), alt: name, }; } let url: string; if (isHeadingOnly) { url = `#${getHeadingHash(heading)}`; } else { const ref = resolver.resolveAny(name, sourceFile.path); if (!ref) { console.warn(`failed to resolve ${name} wikilink`); return; } url = getFileHref(ref, sourceFile, heading); } return { type: 'link', url, data: { isWikiLink: true, }, children: [ { ``` Sources: [packages/obsidian/src/remark/remark-wikilinks.ts:139-224](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-wikilinks.ts#L139-L224) | Link Property / Parameter | Regular Expression Group | Behavior & Fallback | | :--- | :--- | :--- | | `name` | `name` | Resolves target file via `resolver.resolveAny`. Defaults to `sourceFile` if heading-only. | | `heading` | `heading` | Appends hash anchor via `getHeadingHash` or `getFileHref`. | | `alias` | `alias` | Sets display text for links (`alias ?? content`). Warns if image size syntax is specified. | Sources: [packages/obsidian/src/remark/remark-wikilinks.ts:145-152](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-wikilinks.ts#L145-L152), [packages/obsidian/src/remark/remark-wikilinks.ts:187-221](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-wikilinks.ts#L187-L221) > [!NOTE] > When resolving an embed content block (`ref.format === 'content'`), the transformer generates an MDX JSX flow element with the name `'include'`, wrapping the file reference in a paragraph. > Sources: [packages/obsidian/src/remark/remark-wikilinks.ts:164-184](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-wikilinks.ts#L164-L184) ## Callout and block reference translation ### Obsidian callout transformation The `remarkConvert` transformer checks blockquote nodes to translate Obsidian-style callout blocks into structured components. It extracts the callout type and optional collapsible indicator using the `RegexCalloutHead` pattern. ```typescript const RegexCalloutHead = /^\[!(?\w+)](?\+)?/; ``` Sources: [packages/obsidian/src/remark/remark-convert.ts:10-10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-convert.ts#L10-L10) The `resolveCallout` function inspects the first child paragraph of a blockquote for callout syntax. If matched, it strips the prefix, separates the title from the body content across newlines, and constructs a callout node via `createCallout`. ```typescript function resolveCallout(node: Blockquote) { const head = node.children[0]; if (!head || head.type !== 'paragraph') return; const textNode = head.children[0]; if (!textNode || textNode.type !== 'text') return; const match = RegexCalloutHead.exec(textNode.value); if (!match) return; textNode.value = textNode.value.slice(match[0].length).trimStart(); const [title, rest] = separate(/\r?\n/, head.children) ?? [head.children]; const body = node.children.slice(1); if (rest) { body.unshift({ type: 'paragraph', children: rest as PhrasingContent[], }); } return createCallout( match[1], [ { type: 'paragraph', children: title as PhrasingContent[], }, ], body, ); } ``` Sources: [packages/obsidian/src/remark/remark-convert.ts:16-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-convert.ts#L11-L46) > [!WARNING] > Blockquotes lacking a paragraph as their initial child or missing the `[!type]` header format are ignored by `resolveCallout` and remain standard blockquotes. > Sources: [packages/obsidian/src/remark/remark-convert.ts:17-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-convert.ts#L17-L23) ### Block ID parsing and section wrapping The `remarkBlockId` plugin traverses paragraph nodes to extract Obsidian block references matching the trailing caret identifier pattern. ```typescript const Regex = /(?\w+)$/m; ``` Sources: [packages/obsidian/src/remark/remark-block-id.ts:7-7](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-block-id.ts#L7-L7) It visits child text nodes in reverse order, searching for block identifiers. When a valid ID is isolated, the plugin trims the trailing identifier string from the text node value and wraps the paragraph inside an MDX JSX flow element representing a `section` tag with an `id` attribute. ```typescript visit(tree, 'paragraph', (node) => { let id: string | undefined; visit( node, ['link', 'text', 'mdxJsxFlowElement'], (textNode) => { if (textNode.type !== 'text') return 'skip'; const value = textNode.value; const match = Regex.exec(value); // if last text node isn't a block id, skip if (!match) return false; id = match[1]; textNode.value = value.slice(0, match.index).trimEnd() + value.slice(match.index + match[0].length); return false; }, true, ); if (id) { replace(node, { type: 'mdxJsxFlowElement', name: 'section', attributes: [ { type: 'mdxJsxAttribute', name: 'id', value: `^${id}`, }, ], children: [ { ...node, }, ], } satisfies MdxJsxFlowElement); } return 'skip'; }); ``` Sources: [packages/obsidian/src/remark/remark-block-id.ts:11-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-block-id.ts#L11-L53) > [!TIP] > Escaped carets (`\^`) are excluded by negative lookbehind in the regex, ensuring literal carets inside paragraph text do not inadvertently trigger block ID extraction. > Sources: [packages/obsidian/src/remark/remark-block-id.ts:7-7](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-block-id.ts#L7-L7) ## Comment stripping and remark pipeline ### Comment stripping mechanism The `remarkObsidianComment` function implements a unified transformer that purges Obsidian comment syntax from the Abstract Syntax Tree. It uses a negative lookbehind regular expression delimiter `/(? [!CAUTION] > If an opening comment delimiter lacks a corresponding closing delimiter in the node stream, `removeComment` halts processing and returns the original node array unmodified, preventing partial document truncation. > Sources: [packages/obsidian/src/remark/remark-obsidian-comment.ts:13-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/remark-obsidian-comment.ts#L13-L14) ### Remark transformation plugin suite The `getRemarkPlugins` function composes the complete array of unified plugins used to transform Obsidian markdown vaults, accepting storage and resolver arguments to build the full processing pipeline. Sources: [packages/obsidian/src/remark/index.ts:9-9](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/index.ts#L9-L9) | Plugin Function | Required Options | Processing Role | | :--- | :--- | :--- | | `remarkWikilinks` | `{ resolver, storage }` | Resolves internal wikilinks and embedded content references. | | `remarkConvert` | None | Translates Obsidian callout syntax within blockquotes. | | `remarkObsidianComment` | None | Strips `%%` comment blocks from document nodes. | | `remarkBlockId` | None | Extracts trailing caret block identifiers and wraps sections. | Sources: [packages/obsidian/src/remark/index.ts:9-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/remark/index.ts#L9-L15) ## Related - [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) --- ## Technical docs: Local Markdown Runtime URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/local-markdown-runtime
Relevant source files The following files were used as context for generating this wiki page: - [packages/local-md/src/client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/client.ts) - [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts) - [packages/local-md/src/md/compiler.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts) - [packages/mdx-remote/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/index.ts) - [packages/local-md/src/md/renderer.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/renderer.ts) - [packages/local-md/src/js/executor-native.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/js/executor-native.ts) - [packages/local-md/src/js/executor-virtual.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/js/executor-virtual.ts) - [packages/core/src/content/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/md.ts) - [packages/mdx-remote/src/render.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/render.ts) - [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts) - [packages/local-md/src/dev/react-client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/react-client.ts) - [packages/local-md/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/package.json) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/obsidian/src/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/obsidian/src/mdx/index.ts) - [packages/mdx-remote/src/compile.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx-remote/src/compile.ts) - [packages/preview/src/components/markdown.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/markdown.tsx) - [packages/local-md/src/dev/node-server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/node-server.ts) - [packages/typescript/src/markdown.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/src/markdown.ts) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/local-md/src/eval-estree-expression/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/eval-estree-expression/index.ts) - [packages/twoslash/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/src/index.ts) - [packages/local-md/src/bin.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/bin.ts) - [packages/core/src/mdx-plugins/remark-llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.ts) - [packages/core/src/mdx-plugins/remark-llms.runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-llms.runtime.ts) - [packages/mdx/src/loaders/mdx/remark-include.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-include.ts) - [packages/mdx/src/runtime/browser.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx) - [packages/preview/src/lib/md.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/md.ts) - [packages/mdx/src/loaders/mdx/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/index.ts) - [packages/local-md/src/dev/node-client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/node-client.ts) - [packages/core/src/content/mdx/preset-runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/content/mdx/preset-runtime.ts)
## Overview The `@fumadocs/local-md` package provides a content source for Fumadocs that scans, compiles, and renders local Markdown and MDX files on the fly. It integrates directly with Fumadocs source loaders by discovering content directories, mapping frontmatter schemas via Standard Schema validators, and exposing both static and dynamic source generators for documentation pages. Sources: [packages/local-md/src/index.ts:1-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L1-L64) ## Local source integration ### Configuration and factory options The `localMd` factory function accepts a configuration object conforming to `LocalMarkdownConfig`, which extends markdown compiler options with directory paths, file glob patterns, validation schemas, and renderer options. The configuration maps strongly typed frontmatter and meta schemas using the `@standard-schema/spec` standard. | Option | Type | Default | Purpose | | :--- | :--- | :--- | :--- | | `dir` | `string` | — | Root directory for content files scanned by the storage layer. | | `include` | `string[]` | `defaultInclude` | List of glob patterns customizing content files to be scanned. | | `rendererOptions` | `Pick` | — | Options passed directly to the markdown renderer, such as custom script executors. | | `frontmatterSchema` | `FrontmatterSchema` | `defaultSchemas.pageSchema` | Standard Schema validator for page frontmatter objects. | | `metaSchema` | `MetaSchema` | `defaultSchemas.metaSchema` | Standard Schema validator for meta files. | Sources: [packages/local-md/src/index.ts:24-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L24-L40), [packages/local-md/src/index.ts:84-89](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L84-L89) ### File loading and virtual source pipeline The `localMd` return object exposes methods for generating `staticSource` and `dynamicSource` collections, managing file invalidation, and connecting to development servers [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader). The internal `createFiles` helper function retrieves raw pages and meta files from the storage layer, constructs `VirtualFile` objects with computed base directories, and attaches lazy `load()` functions to each page. ```mermaid sequenceDiagram participant Source as staticSource / dynamicSource participant Storage as storage.getPages() participant Compiler as compiler.compile() participant Renderer as fromAst / fromJS Source->>Storage: Fetch raw pages and meta files Storage-->>Source: Return pages & metas arrays Source->>Source: Build VirtualFile list with baseDir paths Note over Source,Renderer: Page.load() invoked lazily Source->>Compiler: Compile markdown content & frontmatter Compiler-->>Source: Return CompileResult (ast or code) Source->>Renderer: Generate MarkdownRenderer (fromAst or fromJS) Renderer-->>Source: Return rendered result ``` Sources: [packages/local-md/src/index.ts:42-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L42-L64), [packages/local-md/src/index.ts:101-165](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L101-L165) ### Hot reload and cache invalidation When a file changes, `invalidateFile` resolves the absolute file path, resets the cached static source promise to `null`, invalidates the underlying storage cache, and iterates over all registered dynamic loaders to trigger `v.invalidate()`. The `devServer` method attempts to establish a WebSocket connection using an environment URL or explicit parameter, sends a `watch-dir` event configured with `config.dir` and `config.include` (falling back to `defaultInclude`), and listens for change events to invoke `invalidateFile`. > [!NOTE] > The `compilerCache` `WeakMap` stores compilation promises keyed by raw page references, ensuring that repeated calls to `load()` on the same page reuse ongoing or completed compilation tasks without redundant disk reads. Sources: [packages/local-md/src/index.ts:90-93](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L90-L93), [packages/local-md/src/index.ts:125-133](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L125-L133), [packages/local-md/src/index.ts:168-195](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L168-L195) ## Markdown compilation pipeline ### Compiler factory and execution trace The compilation engine in `packages/local-md/src/md/compiler.ts` exports `createMarkdownCompiler`, which returns an object with a `compile` method supporting both standard markdown and MDX inputs. Depending on whether the file extension is `.mdx`, the compiler dispatches processing through specific pipeline builders. The call-chain execution walkthrough for compiling local documents follows this exact sequence: 1. `localMd` invokes `createMarkdownCompiler(config)` to instantiate the compiler engine. Sources: [packages/local-md/src/index.ts:91-91](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts#L91-L91) 2. `createMarkdownCompiler` sets up lazy helper functions and returns the compiler object containing the `compile(input)` method. Sources: [packages/local-md/src/md/compiler.ts:62-161](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts#L62-L161) 3. When `.mdx` files are processed, `compile()` invokes `createMdxCompiler()` to construct and cache the MDX processor using `@mdx-js/mdx`. Sources: [packages/local-md/src/md/compiler.ts:105-118](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts#L105-L118), [packages/local-md/src/md/compiler.ts:143-145](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts#L143-L145) ```mermaid sequenceDiagram participant LocalMd as localMd participant Compiler as createMarkdownCompiler participant MdxCompiler as createMdxCompiler LocalMd->>Compiler: createMarkdownCompiler(config) Compiler-->>LocalMd: Return MarkdownCompiler LocalMd->>Compiler: compile(input) Compiler->>MdxCompiler: createMdxCompiler() [if .mdx] MdxCompiler-->>Compiler: Return Mdx Processor Compiler-->>LocalMd: Return CompileResult (js or ast) ``` Sources: [packages/local-md/src/md/compiler.ts:62-65](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts#L62-L65), [packages/local-md/src/md/compiler.ts:105-118](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts#L105-L118), [packages/local-md/src/md/compiler.ts:141-160](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts#L141-L160) ### Syntax plugin resolution and processor options Both Markdown and MDX compilers integrate a standard suite of remark and rehype plugins. These include `remarkGfm` for GitHub-Flavored Markdown support, `remarkHeading`, `remarkNpm`, `remarkCodeTab`, `remarkStructure`, `rehypeCode`, and `rehypeToc`. Each plugin can be conditionally disabled or customized by passing explicit option flags in `MarkdownCompilerOptions`. | Plugin Option Property | Default Value / Behavior | Target Plugin | | :--- | :--- | :--- | | `remarkHeadingOptions` | `{ generateToc: false, ...remarkHeadingOptions }` | `remarkHeading` | | `remarkNpmOptions` | Passed directly if not `false` | `remarkNpm` | | `remarkCodeTabOptions` | Passed directly if not `false` | `remarkCodeTab` | | `remarkStructureOptions` | Passed directly if not `false` | `remarkStructure` | | `rehypeCodeOptions` | Passed directly if not `false` | `rehypeCode` | | `rehypeTocOptions` | `{ exportToc: { as: 'data' }, ...rehypeTocOptions }` (MDX uses `{ as: 'esm', name: 'toc' }`) | `rehypeToc` | > [!NOTE] > Setting any of the plugin options to explicit boolean `false` (e.g., `remarkHeadingOptions: false`) completely disables that specific syntax transformation during pipeline initialization. Sources: [packages/local-md/src/md/compiler.ts:66-103](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts#L66-L103), [packages/local-md/src/md/compiler.ts:105-137](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/compiler.ts#L105-L137) ## AST and serialized rendering ### MarkdownRenderer Interface and Options The rendering layer defined in `packages/local-md/src/md/renderer.ts` provides unified interfaces for managing compiled outputs, whether executed via native JavaScript compilation or abstract syntax tree transformation. The core abstraction is the `MarkdownRenderer` interface, which normalizes structured data retrieval, synchronous and asynchronous rendering passes, and serialization options. ```typescript export interface MarkdownRenderer> { structuredData: StructuredData; render: ( components?: MDXComponents, context?: Record, ) => Promise>; renderSync: ( components?: MDXComponents, context?: Record, ) => MarkdownRendererResult; serialize: () => MarkdownRendererSerializedOptions; } ``` Sources: [packages/local-md/src/md/renderer.ts:11-22](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/renderer.ts#L11-L22) The engine supports two primary serialization options via `MarkdownRendererSerializedOptions`, discriminating between JavaScript execution outputs and AST trees. | Option Type Property | Configuration Interface | Purpose / Fields | | :--- | :--- | :--- | | `type: 'js'` | `MarkdownRendererJSOptions` | Code string execution containing `code`, `filePath`, optional `baseUrl`, and `structuredData`. | | `type: 'ast'` | `MarkdownRendererASTOptions` | HAST syntax tree processing containing `tree`, `filePath`, optional `structuredData`, `rehypeToc`, and an optional `executor`. | > [!NOTE] > The `executor` option in `MarkdownRendererASTOptions` is ignored for MDX files, as MDX always utilizes the native JavaScript runtime engine. Sources: [packages/local-md/src/md/renderer.ts:30-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/renderer.ts#L30-L57) ### Structured Data and AST-to-React Transformation When rendering from an Abstract Syntax Tree using `fromAst`, the engine maps [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) items generated by rehype plugins into React nodes while executing through `hast-util-to-jsx-runtime`. ```typescript export function fromAst(options: MarkdownRendererASTOptions): MarkdownRenderer { const { executor: getExecutor = executorVirtual, filePath, structuredData = { headings: [], contents: [], }, rehypeToc = [], tree, } = options; function renderSync(components?: MDXComponents, userContext?: Record) { const context = { ...components, ...userContext }; const executor = getExecutor({ jsx: JsxRuntime, filePath, }); const evaluater = toEvaluater(executor, context); function render(tree: Root): ReactNode { return toJsxRuntime(tree, { filePath, components, development: false, createEvaluater() { return evaluater; }, ...JsxRuntime, }); } const toc = rehypeToc.map( (item): TOCItemType => ({ ...item, title: render({ type: 'root', children: item.title.children, }), }), ); return { toc, body: render(tree), exports: executor.getExports() as M, }; } ``` Sources: [packages/local-md/src/md/renderer.ts:59-106](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/renderer.ts#L59-L106) > [!TIP] > The `rendererFromSerialized` helper exported from `packages/local-md/src/client.ts` proxies directly to `fromSerialized`, checking the payload type to instantiate either `fromJS` or `fromAst` dynamically. Sources: [packages/local-md/src/client.ts:1-1](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/client.ts#L1-L1), [packages/local-md/src/md/renderer.ts:188-191](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/md/renderer.ts#L188-L191) ## Virtual expression evaluation ### Sandbox Engine and Executor Configuration The virtual expression execution layer provides a lightweight sandboxed JavaScript evaluation engine specifically designed to function within constrained environments like Cloudflare's workerd runtime. Defined in `packages/local-md/src/js/executor-virtual.ts`, the `executorVirtual` function accepts a `JSExecutorConfig` options object and instantiates an `ExpressionSync` class from `packages/local-md/src/eval-estree-expression/index.ts`. It returns a standardized `JSExecutor` interface supporting expression evaluation, program execution, and export retrieval. ```typescript export function executorVirtual(options: JSExecutorConfig): JSExecutor { const sync = new ExpressionSync(options); return { expression(expression, context) { return sync.evaluate(expression, context); }, program(expression, context) { return sync.evaluate(expression, context); }, getExports() { return sync.getExports(); }, }; } ``` Sources: [packages/local-md/src/js/executor-virtual.ts:7-20](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/js/executor-virtual.ts#L7-L20) ### Expression Tree Traversal and Security Boundaries The `ExpressionSync` class manages export maps and handles AST node evaluation through a dynamic visitor pattern. To prevent prototype pollution and unauthorized access to constructor or prototype chains during property lookups, the engine maintains strict key validation checks. | Security Constant / Helper | Target Values / Types | Purpose / Constraint | | :--- | :--- | :--- | | `UNSAFE_KEYS` | `'constructor'`, `'prototype'`, `'__proto__'`, `'__defineGetter__'` | Set of blocked property names prohibited during key resolution. | | `isSafeKey` | `string \| number` | Validates that property keys are strings or numbers and do not belong to `UNSAFE_KEYS`. | | `isReturnValue` | Object where `type === RETURN` | Internal symbol marker used to handle return statement unwrapping across block scopes. | | `EvaluateOptions` | Optional object with `jsx?: Pick` | Optional configuration mapping React JSX runtime methods for evaluation. | Sources: [packages/local-md/src/eval-estree-expression/index.ts:49-80](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/eval-estree-expression/index.ts#L49-L80) > [!CAUTION] > Property access checking via `isSafeKey` actively blocks lookups involving `constructor`, `prototype`, and `__proto__`. Attempting to evaluate expressions containing these keys will reject property resolution to secure the evaluation sandbox against prototype manipulation. Sources: [packages/local-md/src/eval-estree-expression/index.ts:49-68](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/eval-estree-expression/index.ts#L49-L68) > [!NOTE] > The `ExpressionSync` constructor accepts optional evaluation parameters (`EvaluateOptions`) which inject JSX runtime functions required when rendering JSX elements inside evaluated AST expressions. Sources: [packages/local-md/src/eval-estree-expression/index.ts:55-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/eval-estree-expression/index.ts#L55-L57), [packages/local-md/src/eval-estree-expression/index.ts:82-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/eval-estree-expression/index.ts#L82-L86) ## Native JavaScript execution ### ESTree JSX Lowering and Context Initialization The native execution engine implemented in `packages/local-md/src/js/executor-native.ts` provides server-side execution of JavaScript and JSX statements using `new Function()`. The `executorNative` function accepts a `JSExecutorConfig` options object containing the file path and JSX runtime hooks. It initializes an `exports` dictionary alongside a `globalContext` map bound to internal runtime variables. ```typescript const INTERNAL_VAR_NAMES = { jsx: '_jsx', jsxs: '_jsxs', fragment: '_Fragment', exports: '__fumadocs_exports', } as const; /** * Execute JavaScript with `new Function()`, this is unsafe. */ export function executorNative(options: JSExecutorConfig): JSExecutor { const { filePath, jsx } = options; const exports: Record = {}; const globalContext: Record = { [INTERNAL_VAR_NAMES.exports]: exports, [INTERNAL_VAR_NAMES.jsx]: jsx.jsx, [INTERNAL_VAR_NAMES.jsxs]: jsx.jsxs, [INTERNAL_VAR_NAMES.fragment]: jsx.Fragment, }; ``` Sources: [packages/local-md/src/js/executor-native.ts:6-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/js/executor-native.ts#L6-L24) > [!WARNING] > Because `executorNative` evaluates code via `new Function()`, it is unsafe for untrusted user input and should only be utilized in trusted server environments where dynamic code evaluation is explicitly permitted. Sources: [packages/local-md/src/js/executor-native.ts:13-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/js/executor-native.ts#L13-L15) ### Pattern Matching and Export Transformation Before converting AST programs to JavaScript strings via `toJs`, statements are processed using `buildJsx` with an automatic runtime configuration. The visitor pattern extracts binding names from complex variable declarations and handles various export declarations through explicit assignment generation. ```typescript function allNames(pattern: Pattern): string[] { switch (pattern.type) { case 'Identifier': return [pattern.name]; case 'ArrayPattern': { const out: string[] = []; for (const element of pattern.elements) { if (element) out.push(...allNames(element)); } return out; } case 'AssignmentPattern': return allNames(pattern.left); case 'MemberExpression': return []; case 'ObjectPattern': { const out: string[] = []; for (const prop of pattern.properties) { if (prop.type === 'Property') { if ('value' in prop && typeof prop.value === 'string') out.push(prop.value); else if ('name' in prop && typeof prop.name === 'string') out.push(prop.name); } else { out.push(...allNames(prop.argument)); } } return out; } case 'RestElement': return allNames(pattern.argument); } } ``` Sources: [packages/local-md/src/js/executor-native.ts:44-74](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/js/executor-native.ts#L44-L74) The `program` handler inspects statement types to map exports and rewrite declarations into valid assignment expressions. | Statement Type | Supported Action / Transformation | Error or Fallback Behavior | | :--- | :--- | :--- | | `ExportAllDeclaration` | Throws an error since star-exports are unsupported. | Throws `Error: ${statement.type} is not supported` | | `ExportDefaultDeclaration` | Rewrites class and function declarations into expressions, assigning them to `__fumadocs_exports.default`. | Throws if initializer is missing. | | `ExportNamedDeclaration` | Appends assignment statements for declared classes, functions, or variable patterns. | Throws if initializer is missing. | Sources: [packages/local-md/src/js/executor-native.ts:98-153](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/js/executor-native.ts#L98-L153) > [!IMPORTANT] > When processing `ExportNamedDeclaration` with `VariableDeclaration` nodes, the engine recursively traverses identifier patterns using `allNames` to generate individual export assignments for every destructured or bound identifier. Sources: [packages/local-md/src/js/executor-native.ts:140-148](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/js/executor-native.ts#L140-L148) ## Development server synchronization ### CLI Launcher and Environment Configuration The command-line interface provided by `local-md` exposes the `dev` command via `commander` to initialize the development server and spawn a user-defined child command, such as a local development server runner. It validates port inputs, injects the running WebSocket development server URL into the process environment using `setDevServerUrlInEnv`, and forwards system signals like `SIGINT` and `SIGTERM` to the active child process. ```typescript program .command('dev') .description('start the local-md dev server and run a command') .argument('', 'command to run') .option('-p, --port ', 'port for the dev server', parsePort, 8000) .allowUnknownOption() .passThroughOptions() .action(async (command: string[], options: { port: number }) => { const handle = await startDevServer({ port: options.port, }); setDevServerUrlInEnv(handle.url); const child = spawn(command[0], command.slice(1), { stdio: 'inherit', shell: true, env: process.env, }); const forwardSignal = (signal: NodeJS.Signals) => { if (child.exitCode === null && child.signalCode === null) { child.kill(signal); } }; process.on('SIGINT', forwardSignal); process.on('SIGTERM', forwardSignal); let exitCode = 1; try { exitCode = await new Promise((resolve, reject) => { child.once('error', reject); child.once('exit', (code, signal) => { if (signal) { resolve(signalToExitCode(signal)); return; } resolve(code ?? 0); }); }); } finally { process.off('SIGINT', forwardSignal); process.off('SIGTERM', forwardSignal); await handle.close().catch(() => undefined); } process.exit(exitCode); }); ``` Sources: [packages/local-md/src/bin.ts:14-62](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/bin.ts#L14-L62) | Signal / Option | Action or Handled Behavior | Resulting Exit Code | | :--- | :--- | :--- | | `--port ` | Parses and validates the numeric port option (default is `8000`). | Throws if invalid. | | `SIGINT` | Forwards the signal to the spawned child process if it is still running. | Exits with `130`. | | `SIGTERM` | Forwards the signal to the spawned child process if it is still running. | Exits with `143`. | | General exit | Resolves exit code or signal equivalent when the child process terminates. | Default exit `1` on error. | Sources: [packages/local-md/src/bin.ts:18-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/bin.ts#L18-L18), [packages/local-md/src/bin.ts:33-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/bin.ts#L33-L41), [packages/local-md/src/bin.ts:78-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/bin.ts#L78-L86) > [!NOTE] > The helper function `signalToExitCode` maps incoming POSIX process signals (`SIGINT` to `130` and `SIGTERM` to `143`) to standard shell exit codes before terminating the CLI process. Sources: [packages/local-md/src/bin.ts:78-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/bin.ts#L78-L86) ### WebSocket File Watching and Node Server The Node.js development server manages file system monitoring with `chokidar` and handles client synchronization via a `ws` WebSocket server. `startDevServer` sets up default watch parameters ignoring non-file stats and matching paths registered across active clients using `picomatch`. ```typescript export async function startDevServer(options: DevServerOptions): Promise { const { host = '127.0.0.1', port } = options; const url = `ws://${host}:${port}${LOCAL_MD_DEV_PATH}`; let watchOptions: ChokidarOptions = { ignoreInitial: true, followSymlinks: false, ignored(file, _stats) { if (!_stats || !_stats.isFile()) return false; for (const client of clients) { for (const [dir, { matcher }] of client.watching) { if (matcher(path.relative(dir, file))) return false; } } return true; }, }; if (options.watchOptions) { watchOptions = options.watchOptions(watchOptions); } const watcher = watch([], watchOptions); ``` Sources: [packages/local-md/src/dev/node-server.ts:33-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/node-server.ts#L33-L56) File watcher events (`add`, `addDir`, `change`, `unlink`, and `unlinkDir`) captured by Chokidar are filtered through `WATCH_EVENTS` and broadcast to all connected clients as change notification payloads. ```typescript watcher.on('all', (event, filePath) => { if (!WATCH_EVENTS.has(event as DevWatchEvent)) return; console.log(`[@fumadocs/local-md] ${event} at "${filePath}"`); broadcast({ type: 'change', event: event as DevWatchEvent, absolutePath: filePath, timestamp: Date.now(), }); }); ``` Sources: [packages/local-md/src/dev/node-server.ts:101-111](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/node-server.ts#L101-L111) > [!WARNING] > When a WebSocket client connection closes, the server automatically cleans up associated watches by verifying whether any remaining active clients still reference the watched directory before calling `watcher.unwatch(dir)`. Sources: [packages/local-md/src/dev/node-server.ts:95-98](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/node-server.ts#L95-L98), [packages/local-md/src/dev/node-server.ts:150-162](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/node-server.ts#L150-L162) ### Client Live-Reload Communication Client connections are managed in the browser and Node environments. The React client component `DevClient` reads the development server URL from the environment, establishes a WebSocket connection, and refreshes the Next.js router whenever a file change event is decoded. ```typescript export function DevClient(): ReactNode { const router = useRouter(); const onUpdate = useEffectEvent((event: DevServerEvent) => { if (event.type === 'change') { console.log(`[@fumadocs/local-md] "${event.absolutePath}" updated`); router.refresh(); } }); useEffect(() => { const url = getDevServerUrlFromEnv(); if (!url) return; const ws = new WebSocket(url); ws.onopen = () => { console.log(`[@fumadocs/local-md] connected to dev server at ${url}`); }; ws.onmessage = (event) => { const decoded = decodeDevEvent(String(event.data)); if (decoded) onUpdate(decoded); }; ws.onclose = () => { console.log(`[@fumadocs/local-md] disconnected from dev server at ${url}`); }; return () => { ws.close(); }; }, []); return null; ``` Sources: [packages/local-md/src/dev/react-client.ts:6-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/react-client.ts#L6-L39) For server-side or non-React consumers, `connectDevServer` maintains a singleton map of `DevServerConnection` instances. It queues pending client messages if the socket is not yet open and dispatches incoming decoded events to registered subscribers. ```typescript export function connectDevServer(url: string): DevServerConnection { let connection = store.get(url); if (!connection) { connection = new DevServerConnection(url); store.set(url, connection); } return connection; } export class DevServerConnection { private readonly listeners = new Set<(event: DevServerEvent) => void>(); private pendingEvents: DevClientEvent[] = []; private socket?: WebSocket; readonly url: string; constructor(url: string) { this.url = url; this.connect(); } subscribe(listener: (event: DevServerEvent) => void) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; } ``` Sources: [packages/local-md/src/dev/node-client.ts:11-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/dev/node-client.ts#L11-L39) ## Related - [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) --- ## Technical docs: Content Collections Adapter URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/content-collections-adapter
Relevant source files The following files were used as context for generating this wiki page: - [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/content/src/runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts) - [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts) - [packages/content-collections/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts) - [packages/core/src/source/loader.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/loader.ts) - [packages/content-collections/src/types.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/types.ts) - [packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts) - [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/content-collections/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/package.json) - [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts) - [packages/preview/src/lib/source/storage.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/storage.ts) - [packages/core/src/source/storage/content.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/storage/content.ts) - [packages/sanity/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts) - [packages/content-collections/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/tsdown.config.ts) - [packages/core/src/source/client/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx) - [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/create-app/template/+orama-cloud/@app/lib/export-static-indexes.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/template/%2Borama-cloud/%40app/lib/export-static-indexes.ts) - [packages/local-md/src/storage.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/storage.ts) - [packages/mdx/src/runtime/types.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/types.ts) - [packages/mdx/src/runtime/browser.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/browser.tsx) - [packages/core/src/search/client/orama-cloud-legacy.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/client/orama-cloud-legacy.ts) - [packages/core/src/search/orama-cloud-legacy.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud-legacy.ts) - [packages/mdx/src/config/define.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/define.ts) - [packages/mdx/src/loaders/meta.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/meta.ts) - [packages/core/src/source/llms.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/llms.ts) - [packages/preview/src/lib/source/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/index.ts) - [packages/core/src/search/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/search/orama-cloud.ts)
## Overview The Content Collections Adapter (`@fumadocs/content-collections`) bridges Content Collections data layers with Fumadocs by supplying factory functions and transformation pipelines that translate content entries into compatible virtual files and sources. Sources: [packages/content-collections/package.json:2-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/package.json#L2-L4), [packages/content-collections/src/index.ts:4-10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L4-L10) By normalizing schemas, unifying metadata extensions, and configuring remark/rehype pipelines such as heading generation and code block formatting, the package enables type-safe content management and rendering across Fumadocs applications. Sources: [packages/content-collections/src/types.ts:4-9](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/types.ts#L4-L9), [packages/content-collections/src/configuration.ts:58-71](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts#L58-L71) ## Package architecture and integration entry ### Public Exports and Bundle Configuration The `@fumadocs/content-collections` package (`@fumadocs/content-collections`) is structured as an ESM-only module targeting Node 22, configured via `tsdown` with TypeScript declaration generation enabled (`dts: true`) and fixed file extensions disabled. The package exposes two public entry points mapped in package exports: the root entry `.` resolving to `./dist/index.js` (with type definitions at `./dist/index.d.ts`) and `./configuration` resolving to `./dist/configuration.js` (with type definitions at `./dist/configuration.d.ts`). ```typescript import { defineConfig } from 'tsdown'; export default defineConfig({ dts: true, fixedExtension: false, target: 'node22', format: 'esm', entry: ['src/{index,configuration}.ts'], deps: { onlyBundle: [], }, }); ``` Sources: [packages/content-collections/tsdown.config.ts:1-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/tsdown.config.ts#L1-L12) ```json "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" }, "./configuration": { "types": "./dist/configuration.d.ts", "import": "./dist/configuration.js" } }, ``` Sources: [packages/content-collections/package.json:17-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/package.json#L17-L29) ### Package Dependencies and Peer Requirements Package execution relies on runtime dependencies for unified document processing and schema validation, alongside peer dependencies that couple the adapter directly with Content Collections core packages and Fumadocs core. | Dependency Name | Type | Version / Range | Purpose | | :--- | :--- | :--- | :--- | | `unified` | dependencies | `^11.0.5` | AST processing and plugin pipeline integration | | `zod` | dependencies | `^4.4.3` | Schema definition and type validation | | `@content-collections/core` | devDependencies / peerDependencies | `0.15.1` / `0.x.x` | Core collection management and document building | | `@content-collections/mdx` | devDependencies / peerDependencies | `^0.2.2` / `0.x.x` | MDX compilation bindings for Content Collections | | `fumadocs-core` | devDependencies / peerDependencies | `workspace:*` / `15.x.x \|\| 16.x.x` | Virtual file types and source abstractions | | `@types/node` | devDependencies | `25.9.2` | Node.js type definitions | | `tsconfig` | devDependencies | `workspace:*` | Shared TypeScript configuration | | `tsdown` | devDependencies | `0.22.2` | Bundle compilation and build tool | > [!NOTE] > The peer dependency range for `fumadocs-core` explicitly requires major version `15.x.x` or `16.x.x`, ensuring interface compatibility with Fumadocs [source loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) definitions. Sources: [packages/content-collections/package.json:40-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/package.json#L40-L56) ## Data contract and schema inheritance ### Interface Definitions The data contract between Content Collections and Fumadocs relies on two core TypeScript interfaces: `BaseMetaData` and `BaseDocsData`. These interfaces extend Fumadocs core metadata and page data types by injecting the `_meta` property defined by `@content-collections/core`. ```typescript export interface BaseMetaData extends MetaData { _meta: Meta; } export interface BaseDocsData extends PageData { _meta: Meta; } ``` Sources: [packages/content-collections/src/types.ts:4-10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/types.ts#L4-L10) | Interface Name | Extending Type | Additional Property | Target Source Mapping | | :--- | :--- | :--- | :--- | | `BaseMetaData` | `MetaData` | `_meta: Meta` | `VirtualFile<{ metaData: Meta; pageData: Docs }>` | | `BaseDocsData` | `PageData` | `_meta: Meta` | `VirtualFile<{ metaData: Meta; pageData: Docs }>` | > [!IMPORTANT] > Both `BaseMetaData` and `BaseDocsData` require the presence of `_meta` containing Content Collections core metadata (`Meta`), which supplies file path tracking (`_meta.filePath`) utilized when generating virtual file entries. Sources: [packages/content-collections/src/index.ts:23-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L23-L31), [packages/content-collections/src/types.ts:4-10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/types.ts#L4-L10) ### Type Parameter Constraints The `createMDXSource` factory function enforces schema inheritance through generic type constraints bounded by `BaseDocsData` and `BaseMetaData`. Documents (`allDocs`) and metadata files (`allMetas`) must conform to these extended data models to produce a typed `Source` containing `metaData` and `pageData`. ```typescript export function createMDXSource( allDocs: Docs[], allMetas: Meta[], ): Source<{ metaData: Meta; pageData: Docs; }> { ``` Sources: [packages/content-collections/src/index.ts:4-10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L4-L10) ## Plugin configuration and remark pipelines ### Transform Options and Default Processors The `transformMDX` function processes documents by invoking `baseCompileMDX` from `@content-collections/mdx` while applying a customized pipeline of remark and rehype plugins [[packages/content-collections/src/configuration.ts:58-97](https://github.com/blade47/blade47/blob/HEAD/packages/content-collections/src/configuration.ts#L58-L97)]. The transformation accepts `TransformOptions`, which inherit from core MDX options while omitting raw plugin arrays in favor of customizable `ResolvePlugins` inputs for both `remarkPlugins` and `rehypePlugins` [packages/content-collections/src/configuration.ts:13-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts#L13-L15). ```typescript export interface TransformOptions extends Omit { remarkPlugins?: ResolvePlugins; rehypePlugins?: ResolvePlugins; /** * Generate `structuredData` * * @defaultValue true * @deprecated use `remarkStructureOptions` instead */ generateStructuredData?: boolean; remarkStructureOptions?: Plugins.StructureOptions | boolean; remarkHeadingOptions?: Plugins.RemarkHeadingOptions | boolean; rehypeCodeOptions?: Plugins.RehypeCodeOptions | boolean; remarkImageOptions?: Plugins.RemarkImageOptions | boolean; remarkCodeTabOptions?: Plugins.RemarkCodeTabOptions | boolean; } ``` Sources: [packages/content-collections/src/configuration.ts:13-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts#L13-L30) | Option Name | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `remarkStructureOptions` | `Plugins.StructureOptions \| boolean` | `generateStructuredData ?? true` | Configures document structure extraction for search indexes | | `rehypeCodeOptions` | `Plugins.RehypeCodeOptions \| boolean` | `true` | Enables code block [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting) and processing | | `remarkHeadingOptions` | `Plugins.RemarkHeadingOptions \| boolean` | `true` | Extracts headings to construct [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) data | | `remarkImageOptions` | `Plugins.RemarkImageOptions \| boolean` | `true` | Processes Markdown images (configured with `useImport: false`) | | `remarkCodeTabOptions` | `Plugins.RemarkCodeTabOptions \| boolean` | `true` | Parses code tab syntax extensions if present in plugins | | `generateStructuredData` | `boolean` | `undefined` | Legacy flag for `structuredData`; maps to `remarkStructureOptions` | > [!NOTE] > The `remarkImageOptions` plugin is hardcoded to set `useImport: false`, ensuring images are parsed inline rather than transformed into ES module imports during compilation. Sources: [packages/content-collections/src/configuration.ts:72-80](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts#L72-L80), [packages/content-collections/src/configuration.ts:108-110](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts#L108-L110) ### Resolution Pipeline and File Data Extraction Plugins are resolved using `resolvePlugins` and `resolvePlugin`, merging user-provided options with Fumadocs defaults [packages/content-collections/src/configuration.ts:100-122](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts#L100-L122). A final custom visitor function is appended to the remark pipeline to capture runtime `file.data` properties generated by plugins like table of contents extraction and structured data processing [packages/content-collections/src/configuration.ts:114-120](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts#L114-L120). ```typescript rehypePlugins: resolvePlugins( (plugins) => [resolvePlugin(Plugins.rehypeCode, rehypeCodeOptions), ...plugins], rest.rehypePlugins, ), remarkPlugins: resolvePlugins( (plugins) => [ Plugins.remarkGfm, resolvePlugin(Plugins.remarkHeading, remarkHeadingOptions), resolvePlugin(Plugins.remarkImage, remarkImageOptions, { useImport: false, }), 'remarkCodeTab' in Plugins && resolvePlugin(Plugins.remarkCodeTab, remarkCodeTabOptions), ...plugins, resolvePlugin(Plugins.remarkStructure, remarkStructureOptions), () => { return (_, file) => { data = file.data; }; }, ], rest.remarkPlugins, ), }, ); ``` Sources: [packages/content-collections/src/configuration.ts:100-124](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts#L100-L124) > [!CAUTION] > The nested caching mechanism inside `baseCompileMDX` is explicitly overridden (`cache: async (input, fn) => fn(input)`) to prevent recursive caching conflicts between Content Collections and the MDX compiler [packages/content-collections/src/configuration.ts:90-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts#L90-L95). Sources: [packages/content-collections/src/configuration.ts:90-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts#L90-L95) ## Virtual file mapping and sources ### Creating MDX Sources The `createMDXSource` function bridges raw Content Collections arrays into a structured Fumadocs source object [packages/content-collections/src/index.ts:4-10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L4-L10). It accepts `allDocs` and `allMetas` collections conforming to `BaseDocsData` and `BaseMetaData` respectively, returning a unified `Source` object containing typed `metaData` and `pageData` generics [packages/content-collections/src/index.ts:4-10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L4-L10). ```typescript export function createMDXSource( allDocs: Docs[], allMetas: Meta[], ): Source<{ metaData: Meta; pageData: Docs; }> { ``` Sources: [packages/content-collections/src/index.ts:4-10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L4-L10)] ```typescript type File = VirtualFile<{ metaData: Meta; pageData: Docs; }>; ``` Sources: [packages/content-collections/src/index.ts:11-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L11-L15)] ### File Mapping Structure The returned source maps each document and metadata record into a typed `VirtualFile` array [packages/content-collections/src/index.ts:16-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L16-L35). Document entries are mapped with a `'page'` type, retaining their original data and path derived from `v._meta.filePath` [packages/content-collections/src/index.ts:18-25](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L18-L25). Metadata entries are mapped with a `'meta'` type using the same path extraction strategy [packages/content-collections/src/index.ts:26-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L26-L33). ```typescript return { files: [ ...allDocs.map( (v) => ({ type: 'page', data: v, path: v._meta.filePath, }) satisfies File, ), ...allMetas.map( (v) => ({ type: 'meta', data: v, path: v._meta.filePath, }) satisfies File, ), ], }; ``` Sources: [packages/content-collections/src/index.ts:16-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L16-L35)] | Virtual File Property | Mapping Source | Type Definition | Purpose | | :--- | :--- | :--- | :--- | | `type` | Literal string `'page'` / `'meta'` | `'page'` \| `'meta'` | Discriminates document content from folder metadata files | | `data` | `v` (from `allDocs` or `allMetas`) | `Docs` \| `Meta` | Holds the validated collection record payload | | `path` | `v._meta.filePath` | `string` | Defines the virtual file path used for routing and tree building | Sources: [packages/content-collections/src/index.ts:18-33](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L18-L33), [packages/content-collections/src/types.ts:4-10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/types.ts#L4-L10) > [!NOTE] > The TypeScript `satisfies` operator is used during array mapping to ensure every virtual file strictly adheres to the local `File` type without widening inferred literal types [packages/content-collections/src/index.ts:24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L24), [packages/content-collections/src/index.ts:32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L32). Sources: [packages/content-collections/src/index.ts:24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L24), [packages/content-collections/src/index.ts:32](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts#L32) ## Collection definition and schema spec ### Collection Definition Primitives Fumadocs provides content definition helpers such as `defineDocs`, `defineCollections`, and `docsCollection` to structure documentation workspaces. The `defineDocs` helper accepts a target directory and configuration overrides for documentation and metadata collections, defaulting to `content/docs` when no directory is specified [packages/mdx/src/config/define.ts:112-144](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/define.ts#L112-L144). ```typescript export function defineDocs< DocSchema extends StandardSchemaV1 = typeof pageSchema, MetaSchema extends StandardSchemaV1 = typeof metaSchema, >(options: { dir?: string; docs?: Omit, 'dir' | 'type'>; meta?: Omit, 'dir' | 'type'>; }): DocsCollection { const dir = options.dir ?? 'content/docs'; return { type: 'docs', dir, docs: defineCollections({ type: 'doc', dir, schema: pageSchema as any, ...options?.docs, }), meta: defineCollections({ type: 'meta', dir, schema: metaSchema as any, ...options?.meta, }), }; } ``` Sources: [packages/mdx/src/config/define.ts:112-144](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/define.ts#L112-L144)] ### Standard Schema Validation Specifications Collections enforce runtime data integrity using the Standard Schema specification (`StandardSchemaV1`), supporting static schemas or context-aware schema generator functions [packages/content/src/index.ts:1-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L1-L14), [packages/mdx/src/config/define.ts:9-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/define.ts#L9-L12). The `docsCollection` factory constructs combined MDX document collections and JSON/YAML metadata collections backed by `pageSchema` and `metaSchema` defaults [packages/content/src/index.ts:35-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L35-L53). | Collection Property | Type / Signature | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `dir` | `string` | `'content/docs'` | Root filesystem directory scanned for collection files | | `docs` | `DocsMDXCollectionConfig` | `pageSchema` | Configuration and validation schema for MDX page frontmatter | | `meta` | `DataCollectionConfig` | `metaSchema` | Configuration and validation schema for folder metadata files | | `schema` | `Schema \| ((ctx) => Schema)` | `pageSchema` / `metaSchema` | Standard Schema validator or dynamic factory function | Sources: [packages/content/src/index.ts:35-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts#L35-L53), [packages/mdx/src/config/define.ts:9-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/define.ts#L9-L12), [packages/mdx/src/config/define.ts:112-144](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/define.ts#L112-L144)] > [!IMPORTANT] > When defining a collection schema using a function, the context parameter provides file-specific metadata `{ path: string; source: string }`, allowing validation rules to adapt dynamically based on file location or content structure. Sources: [packages/mdx/src/config/define.ts:9-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/config/define.ts#L9-L12)] ## Related - [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) --- ## Technical docs: Python Docstring Extractor URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/python-docstring-extractor
Relevant source files The following files were used as context for generating this wiki page: - [packages/python/fumapy/mksource/document_module.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/document_module.py) - [packages/python/fumapy/mksource/simplify_docstring.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/simplify_docstring.py) - [packages/python/fumapy/mksource/models.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/models.py) - [packages/python/fumapy/mksource/__init__.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/__init__.py) - [packages/python/fumapy/__init__.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/__init__.py) - [packages/python/fumapy/mksource/utils.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/utils.py) - [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts) - [packages/python/src/convert.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/convert.ts) - [packages/python/pyproject.toml](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/core/src/mdx-plugins/remark-structure.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts) - [packages/typescript/src/lib/base.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/src/lib/base.ts) - [packages/python/src/components/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx) - [packages/python/src/generated.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/generated.ts) - [packages/content/src/runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts) - [packages/python/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json) - [packages/mdx/src/loaders/mdx/remark-postprocess.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/loaders/mdx/remark-postprocess.ts) - [packages/openapi/src/utils/document/load.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/document/load.ts) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts) - [packages/mdx/src/runtime/types.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/types.ts) - [packages/sanity/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts) - [packages/twoslash/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/twoslash/src/index.ts) - [packages/openapi/src/utils/pages/to-static-data.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-static-data.ts) - [packages/python/fumapy/mksource/json_encoder.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/json_encoder.py) - [packages/cli/src/commands/file-tree.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/file-tree.ts) - [packages/doc-gen/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/doc-gen/package.json) - [packages/asyncapi/src/utils/pages/to-static-data.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/to-static-data.ts) - [packages/api-docs/src/i18n.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/src/i18n.ts) - [packages/preview/src/lib/source/storage.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/storage.ts)
## Overview The `fumapy` Python package provides built-in docgen capabilities for extracting API documentation from Python source code and docstrings, serving as the official Python extension for Fumadocs. It bridges raw Python modules and documentation frontends by inspecting AST structures, simplifying docstring content, and serializing parsed metadata into JSON format for static site generation. Sources: [packages/python/pyproject.toml:4-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L4-L4), [packages/python/package.json:4-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json#L4-L4) ## Command Line and Execution Workflow ### CLI Entrypoint and Argument Configuration The package registers a command-line script named `fumapy-generate` through `pyproject.toml`, pointing directly to the `generate` function within the main package module. ```toml [project.scripts] fumapy-generate = "fumapy:generate" ``` Sources: [packages/python/pyproject.toml:10-11](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml#L10-L11) The `generate` function builds an `argparse.ArgumentParser` configured with positional and optional parameters to control target selection and output paths. | Argument / Flag | Type | Default | Description | | :--- | :--- | :--- | :--- | | `module` | `str` | (Required) | The target Python module name to generate documentation for. | | `--dir`, `-d` | `str` | `"."` | The target directory where the resulting JSON documentation file is saved. | Sources: [packages/python/fumapy/__init__.py:30-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/__init__.py#L30-L41) ### Execution Lifecycle and Serialization Once command-line arguments are parsed, the execution workflow initializes `griffe` with the `TypingDocExtension` extension. It loads the target module using `griffe.load`, setting `docstring_parser="auto"` and `store_source=True` based on module-level constants `DOCSTRING_TYPE` and `STORE_SOURCE`. ```python extensions = griffe.load_extensions(TypingDocExtension) pkg = parse_module( griffe.load( args.module, docstring_parser="auto", store_source=STORE_SOURCE, extensions=extensions ) ) api_filename = f"{args.module}.json" with open(os.path.join(args.dir, api_filename), "w") as file: json.dump(pkg, file, cls=CustomEncoder, indent=2, full=True) ``` Sources: [packages/python/fumapy/__init__.py:10-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/__init__.py#L10-L12), [packages/python/fumapy/__init__.py:43-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/__init__.py#L43-L52) > [!NOTE] > The generated documentation file is written as `{module}.json` inside the directory specified by `--dir`. The serialization process leverages `CustomEncoder` and enables `full=True` during `json.dump` to capture complete AST and docstring metadata. Sources: [packages/python/fumapy/__init__.py:49-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/__init__.py#L49-L52) ## Griffe Inspection and AST Traversal ### Module AST Parsing The `parse_module` function accepts a `griffe.Object` and verifies that it is an instance of `griffe.Module`, raising a `ValueError` otherwise. It processes module docstrings via `simplify_docstring` and builds a structured `Module` dictionary containing name, path, filepath, description, remaining docstring, attributes, submodules, classes, and functions while filtering out any aliases (`if not value.is_alias`). ```python def parse_module(m: griffe.Object) -> Module: if not isinstance(m, griffe.Module): raise ValueError("Module must be a module") out = simplify_docstring(m.docstring, m) res: Module = { "name": m.name, "path": m.path, "filepath": m.filepath, "description": out.description, "docstring": out.remainder, "attributes": out.attributes, "modules": { name: parse_module(value) for name, value in m.modules.items() if not value.is_alias }, "classes": { name: parse_class(value) for name, value in m.classes.items() if not value.is_alias }, "functions": { name: parse_function(value) for name, value in m.functions.items() if not value.is_alias }, } if m.is_package: try: res["version"] = version(m.name) except AttributeError: res["version"] = "unknown" return res ``` Sources: [packages/python/fumapy/mksource/document_module.py:12-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/document_module.py#L12-L46) > [!NOTE] > When `m.is_package` evaluates to true, `parse_module` attempts to dynamically retrieve the package version via `importlib.metadata.version(m.name)`, falling back to `"unknown"` if an `AttributeError` occurs. Sources: [packages/python/fumapy/mksource/document_module.py:40-44](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/document_module.py#L40-L44) ### Class and Function AST Extraction The `parse_class` function processes a `griffe.Class` object to extract its name, path, description, parameters, attributes, docstring, source code, non-alias functions, and inherited members. It parses inherited members by inspecting `c.inherited_members.values()`, extracting their canonical paths and kinds, and grouping them by their parent paths. ```python def parse_class(c: griffe.Class) -> Class: out = simplify_docstring(c.docstring, c) res: Class = { "name": c.name, "path": c.path, "description": out.description, "parameters": out.parameters, "attributes": out.attributes, "docstring": out.remainder, "functions": { name: parse_function(value) for name, value in c.functions.items() if not value.is_alias }, "source": c.source, "inherited_members": {}, } for member in c.inherited_members.values(): parent_path = ".".join(member.canonical_path.split(".")[:-1]) member_info = {"kind": member.kind, "path": member.canonical_path} if parent_path not in res["inherited_members"]: res["inherited_members"][parent_path] = [] res["inherited_members"][parent_path].append(member_info) return res ``` Sources: [packages/python/fumapy/mksource/document_module.py:49-72](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/document_module.py#L49-L72) The `parse_function` function inspects a `griffe.Function` object, generating its signature via `build_signature(f)` and extracting its name, path, description, parameters, return annotations, docstring remainder, and source code. ```python def parse_function(f: griffe.Function) -> Function: out = simplify_docstring(f.docstring, f) res: Function = { "name": f.name, "path": f.path, "signature": build_signature(f), "description": out.description, "parameters": out.parameters, "returns": out.returns, "docstring": out.remainder, "source": f.source, } return res ``` Sources: [packages/python/fumapy/mksource/document_module.py:75-86](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/document_module.py#L75-L86) ### Utility Functions and Helpers Utility helpers support AST inspection by filtering non-imported objects, stringifying expressions, and building accurate Python callable signatures. | Function | Parameters | Return Type | Description | | :--- | :--- | :--- | :--- | | `build_signature` | `func: griffe.Function` | `str` | Constructs a full function signature string, handling positional-only (`/`), keyword-only (`*`), varargs (`*args`), kwargs (`**kwargs`), defaults, and return annotations. | | `filter_non_imported` | `d: dict[str, griffe.Object]` | `dict` | Filters a dictionary of Griffe objects to retain only those where `not v.is_imported`. | | `stringify_expr` | `expr: griffe.Expr \| str` | `str` | Converts a Griffe expression into its string path representation or returns the string as-is. | Sources: [packages/python/fumapy/mksource/utils.py:4-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/utils.py#L4-L49) ## Docstring Simplification and Signature Normalization ### Simplified Docstring Structure and Processing The docstring transformation pipeline converts raw Griffe docstrings and AST inspection objects into structured dictionaries and named tuples via `simplify_docstring`. The `SimplifiedDocstring` named tuple contains five core fields: `description`, `parameters`, `returns`, `attributes`, and `remainder`. ```python class SimplifiedDocstring(t.NamedTuple): description: str | None parameters: list[dict[str, str | None]] returns: dict[str, str | None] attributes: list[dict[str, str | None]] remainder: list[griffe.DocstringSection] ``` Sources: [packages/python/fumapy/mksource/simplify_docstring.py:6-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/simplify_docstring.py#L6-L12) When processing a module, class, or function, helper routines initialize fields directly from the parent AST signatures before parsing individual docstring sections. Parameter annotations, default values, and attribute visibility filters are established during this initial signature pass. ```python def get_parameters_from_signature(parent: griffe.Class | griffe.Function): return [ { "name": p.name, "annotation": p.annotation, "description": None, "value": p.default, } for p in parent.parameters ] def get_returns_from_signature(parent: griffe.Function): return { "name": "", "annotation": ( parent.returns if isinstance(parent.returns, (str, type(None))) else "".join( elem if isinstance(elem, str) else elem.canonical_path for elem in parent.returns.iterate(flat=True) ) ), "description": None, } def get_attributes_from_signature(parent: griffe.Module | griffe.Class): return [ { "name": attr.name, "annotation": attr.annotation, "description": attr.docstring.parsed if attr.docstring else None, "value": attr.value, } for attr in parent.attributes.values() if (not attr.is_alias and not attr.is_private) ] ``` Sources: [packages/python/fumapy/mksource/simplify_docstring.py:17-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/simplify_docstring.py#L17-L52) > [!WARNING] > When iterating over parent attributes in `get_attributes_from_signature`, both `attr.is_alias` and `attr.is_private` items are explicitly excluded from the resulting list to prevent duplicate or private documentation entries. Sources: [packages/python/fumapy/mksource/simplify_docstring.py:50-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/simplify_docstring.py#L50-L52) ### Section Parsing and AST Merging As `simplify_docstring` iterates through `doc.parsed`, it handles specific section kinds (`text`, `parameters`, `returns`, and `attributes`) while appending unhandled sections to `remainder`. Text sections appearing at index 0 populate the main description. Parameter and attribute sections merge docstring descriptions with runtime signature data by matching names against dictionaries constructed from parsed docstring section values. ```python for i, sec in enumerate(doc.parsed): if sec.kind == "text" and i == 0: description = sec.value continue # Sort the parameters with the real signature if sec.kind == "parameters": map = {i.name: i for i in sec.value} params_list = [] for param in parent.parameters: if param.name in map: docstring = map[param.name] try: docstring.description = griffe.parse_google( griffe.Docstring(docstring.description) ) except AttributeError: pass params_list.append(docstring) else: params_list.append( { "name": param.name, "annotation": param.annotation, "description": None, "value": param.default, } ) parameters = params_list continue if sec.kind == "returns": returns: griffe.DocstringReturn = sec.value[0] returns.annotation = ( returns.annotation.canonical_path if isinstance(returns.annotation, griffe.Expr) else returns.annotation ) continue ``` Sources: [packages/python/fumapy/mksource/simplify_docstring.py:76-115](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/simplify_docstring.py#L76-L115) > [!TIP] > Parameter and attribute descriptions extracted from docstrings are re-parsed using `griffe.parse_google(griffe.Docstring(...))` to normalize Google-style formatting within individual item docstrings. Sources: [packages/python/fumapy/mksource/simplify_docstring.py:89-91](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/simplify_docstring.py#L89-L91), [packages/python/fumapy/mksource/simplify_docstring.py:135-137](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/simplify_docstring.py#L135-L137) TypedDict definitions in `models.py` mirror these structures for downstream serialization and documentation rendering, ensuring strict type safety for parameters, attributes, functions, classes, and modules. | Type Definition | Fields | Description | | :--- | :--- | :--- | | `Parameter` | `name`, `annotation`, `description`, `value` | Represents a single function or method parameter. | | `Attribute` | `name`, `annotation`, `description`, `value` | Represents a class or module attribute. | | `DocstringSection` | `kind`, `value` | Represents an unparsed or remaining docstring section. | | `Function` | `name`, `path`, `signature`, `description`, `parameters`, `returns`, `docstring`, `source` | Typed dictionary capturing function metadata. | Sources: [packages/python/fumapy/mksource/models.py:30-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/models.py#L30-L60) ## Serialization Models and JSON Encoding ### TypedDict Schema Models TypedDict schemas define the structure for serialized Python modules, classes, and functions, mapping documentation metadata into strict dictionary types. The `Module` schema aggregates nested modules, classes, functions, attributes, and docstrings alongside metadata fields. The `Class` and `Function` schemas capture signature information, source code strings, parameters, and return mappings. ```python class Module(t.TypedDict): name: str path: str filepath: str description: str | None docstring: Docstring attributes: list[Attribute] modules: dict[str, Module] classes: dict[str, Class] functions: dict[str, Function] version: str | None class Class(t.TypedDict): name: str path: str description: str | None parameters: list[Parameter] attributes: list[Attribute] docstring: Docstring functions: dict[str, Function] source: str class Function(t.TypedDict): name: str path: str signature: str description: str | None parameters: list[Parameter] returns: dict[str, str | None] docstring: Docstring source: str ``` Sources: [packages/python/fumapy/mksource/models.py:6-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/models.py#L6-L39) > [!NOTE] > `Docstring` is defined as a list of `DocstringSection` typed dictionaries, where each section holds a specific `kind` string and a `value` containing either plain text or a list of parameters. Sources: [packages/python/fumapy/mksource/models.py:41-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/models.py#L41-L46) ### Custom JSON Encoder The `CustomEncoder` class extends `griffe.JSONEncoder` to serialize Python path objects and expressions during export. A mapping table (`_json_encoder_map`) directs `Path`, `PosixPath`, and `WindowsPath` instances to `str` conversion, and Python `set` objects to sorted lists. ```python _json_encoder_map: dict[type, t.Callable[[t.Any], t.Any]] = { Path: str, PosixPath: str, WindowsPath: str, set: sorted, } ``` Sources: [packages/python/fumapy/mksource/json_encoder.py:5-10](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/json_encoder.py#L5-L10) Within `CustomEncoder.default`, objects matching `griffe.Expr` are converted directly to strings via `str(obj)`, while standard inspected nodes invoke `obj.as_dict(full=self.full)`. Unrecognized types fall back to `_json_encoder_map` lookups or `super().default`. ```python class CustomEncoder(griffe.JSONEncoder): def default(self, obj: t.Any) -> t.Any: """Return a serializable representation of the given object. Parameters: obj: The object to serialize. Returns: A serializable representation. """ try: if isinstance(obj, griffe.Expr): return str(obj) return obj.as_dict(full=self.full) except AttributeError: return _json_encoder_map.get(type(obj), super().default)(obj) ``` Sources: [packages/python/fumapy/mksource/json_encoder.py:13-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/json_encoder.py#L13-L29) > [!CAUTION] > If `obj.as_dict()` raises an `AttributeError`, the encoder catches the exception and attempts fallback serialization through `_json_encoder_map` before resorting to the parent encoder. Sources: [packages/python/fumapy/mksource/json_encoder.py:24-29](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/mksource/json_encoder.py#L24-L29) ## Frontend Type Mapping and Rendering ### MDX Element Conversion and Layout The `convert` function processes structured module objects into an array of output files by evaluating descriptions, attributes, nested classes, functions, and submodules. When classes or submodules are present, it dynamically builds layout structures using `Tabs` and `Cards` components, mapping entity paths with custom URL builders. | Function / Utility | Target Element | Purpose | | :--- | :--- | :--- | | `convert` | `Tabs`, `Tab`, `Cards`, `Card` | Assembles module documentation into tabbed layouts and card grids. | | `convertClass` | Markdown file (`.mdx`) | Generates standalone class documentation files with attribute and function sections. | | `convertFunction` | `PyFunction` | Wraps function definitions, signatures, source code blocks, parameters, and return types. | | `convertParameter` | `PyParameter` | Renders parameter entries with type annotations and default values. | | `convertAttribute` | `PyAttribute` | Renders module or class attributes with optional annotations and default values. | Sources: [packages/python/src/convert.ts:20-94](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/convert.ts#L20-L94), [packages/python/src/convert.ts:96-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/convert.ts#L96-L126), [packages/python/src/convert.ts:128-157](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/convert.ts#L128-L157), [packages/python/src/convert.ts:159-171](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/convert.ts#L159-L171), [packages/python/src/convert.ts:173-183](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/convert.ts#L173-L183) > [!WARNING] > Text encoding performed by `encodeText` explicitly escapes less-than characters and curly braces to prevent syntax collision with MDX expressions during string serialization. Sources: [packages/python/src/convert.ts:249-251](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/convert.ts#L249-L251) ### React Documentation Components The rendering layer defines specialized React components styled with Tailwind CSS and class-variance-authority variants. Badge variants distinguish component categories using color themes for functions, attributes, classes, and primary parameters. ```tsx const cardVariants = cva('bg-fd-card rounded-lg text-sm my-6 p-3 border'); const badgeVariants = cva('text-xs font-medium border p-1 rounded-lg not-prose', { variants: { color: { func: 'bg-fdpy-func/10 text-fdpy-func border-fdpy-func/50', attribute: 'bg-fdpy-attribute/10 text-fdpy-attribute border-fdpy-attribute/50', class: 'bg-fdpy-class/10 text-fdpy-class border-fdpy-class/50', primary: 'bg-fd-primary/10 text-fd-primary border-fd-primary/10', }, }, }); ``` Sources: [packages/python/src/components/index.tsx:13-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L13-L23) The `PySourceCode` component encapsulates function source blocks within collapsible containers that expose toggle triggers with chevron rotation indicators. ```tsx export function PySourceCode({ children }: { children: ReactNode }) { return ( Source Code {children} ); } ``` Sources: [packages/python/src/components/index.tsx:103-121](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L103-L121) > [!TIP] > The `InlineCode` helper leverages [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting) on python code strings, customising pre-formatted spans to render inline type signatures cleanly. Sources: [packages/python/src/components/index.tsx:135-149](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx#L135-L149) ## Related - [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) --- ## Technical docs: Sanity CMS Integration URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/sanity-cms-integration
Relevant source files The following files were used as context for generating this wiki page: - [packages/sanity/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts) - [packages/sanity/src/client.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/client.ts) - [packages/content/src/runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/sanity/registry/steps.component.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/steps.component.tsx) - [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts) - [packages/sanity/registry/tabs.component.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/tabs.component.tsx) - [packages/sanity/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/index.ts) - [packages/core/src/source/client/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx) - [packages/shadcn/src/rsc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/rsc.tsx) - [packages/sanity/registry/files.component.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/files.component.tsx) - [packages/sanity/registry/accordion.component.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/accordion.component.tsx) - [packages/preview/src/lib/source/storage.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/storage.ts) - [packages/sanity/registry/base.component.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/base.component.tsx) - [packages/asyncapi/src/ui/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/index.tsx) - [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/sanity/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/package.json) - [packages/asyncapi/src/utils/pages/to-text.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/to-text.ts) - [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts) - [packages/core/src/mdx-plugins/remark-structure.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/mdx-plugins/remark-structure.ts) - [packages/content-collections/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts) - [packages/openapi/src/utils/pages/to-text.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/to-text.ts) - [packages/preview/src/lib/source/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/index.ts) - [packages/preview/src/components/provider.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/provider.tsx) - [packages/base-ui/src/layouts/flux/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/index.tsx) - [packages/base-ui/src/layouts/notebook/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/page/index.tsx) - [packages/cli/src/commands/file-tree.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/file-tree.ts) - [packages/radix-ui/src/layouts/flux/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/page/index.tsx) - [packages/radix-ui/src/layouts/notebook/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/notebook/page/index.tsx)
## Overview The Sanity CMS Integration package (`@fumadocs/sanity`) connects documents and Portable Text blocks stored in Sanity CMS to Fumadocs source abstractions and UI components. It provides a dynamic source factory that queries documents, constructs virtual file paths, and maps structured data and [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) trees for documentation projects. Sources: [packages/sanity/src/index.ts:1-161](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts#L1-L161), [packages/sanity/package.json:1-73](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/package.json#L1-L73) ## Sanity Source Factory Architecture ### Factory Contracts and Options The `createSanitySource` function instantiates a dynamic [source loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) for Fumadocs by accepting either a generic Sanity client configuration or a `next-sanity` live fetcher. Document types must conform to `BaseDoc`, which defines the mandatory identifiers and optional metadata fields. | Option Key | Type | Description | | :--- | :--- | :--- | | `docType` | `string` | Document type matching the `_type` field in Sanity CMS. | | `generatePath` | `(doc: ShallowDoc) => string` | Optional custom generator for virtual file paths. | | `baseDir` | `string` | Base directory prefix applied to all virtual file paths. | | `client` | `SanityClient` | An instance of the official Sanity client. | | `sanityFetch` | `DefinedFetchType` | Live query fetcher provided by `next-sanity`. | Sources: [packages/sanity/src/index.ts:12-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts#L12-L36), [packages/sanity/src/index.ts:63-82](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts#L63-L82) > [!WARNING] > When configuring `NextSanityOptions`, providing a `client` is optional if `sanityFetch` is supplied, but omitting both will fail query resolution during file discovery. Sources: [packages/sanity/src/index.ts:33-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts#L33-L36), [packages/sanity/src/index.ts:72-81](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts#L72-L81) ### Virtual Path Resolution and Data Loading The source factory queries shallow document summaries using GROQ filters to construct virtual file paths and lazy-load full document payloads. Slugs are parsed by splitting current slug strings on forward slashes, defaulting root entries to `index.mdx`. ```typescript export function createSanitySource( options: SanityOptions, ): DynamicSource<{ pageData: DocToPage; metaData: MetaData; }> { // ... } ``` Sources: [packages/sanity/src/index.ts:63-100](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts#L63-L100) > [!TIP] > The `load` function fetches complete document bodies and extracts heading blocks matching styles `h1` through `h6` into `_toc`, while `structuredData` compiles text nodes for search indexing. Sources: [packages/sanity/src/index.ts:106-153](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts#L106-L153) ## Portable Text Client and Navigation Parsing ### Table of Contents Generation from Portable Text Blocks The package provides client utilities to process Portable Text blocks and construct navigation structures compatible with Fumadocs core types. The `renderToc` function iterates over an array of `PortableTextBlock` items, transforming heading elements into standard `TOCItemType` entries for sidebar or floating table of contents renderers. ```typescript export function renderToc(opts: { toc: PortableTextBlock[]; render: (body: PortableTextBlock) => ReactNode; }): TOCItemType[] { const { render, toc } = opts; return toc.map( (item): TOCItemType => ({ depth: Number(item.level ?? 0), title: render({ ...item, style: undefined }), url: `#${item._key}`, }), ); } ``` Sources: [packages/sanity/src/client.ts:5-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/client.ts#L5-L18) | Property | Expression / Transformation | Target Type | | :--- | :--- | :--- | | `depth` | `Number(item.level ?? 0)` | `number` | | `title` | `render({ ...item, style: undefined })` | `ReactNode` | | `url` | `#${item._key}` | `string` | Sources: [packages/sanity/src/client.ts:11-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/client.ts#L11-L17) > [!NOTE] > When rendering table of contents items, `renderToc` clones each block item with its `style` property stripped to prevent duplicate heading styles while generating anchor targets from the Sanity document key (`_key`). Sources: [packages/sanity/src/client.ts:13-16](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/client.ts#L13-L16) ### Page Tree Deserialization and Hook Utilities Client-side integration also handles page tree hydration via `useFumadocsLoader` and `deserializePageTree`. These utilities inspect serialized page trees marked with the `$fumadocs_loader` identifier and inject raw HTML into tree node icons and item names using `dangerouslySetInnerHTML`. ```tsx export function deserializePageTree(serialized: SerializedPageTree): PageTree.Root { const root = serialized.data as PageTree.Root; visit(root, (item) => { if ('icon' in item && typeof item.icon === 'string') { item.icon = ( ); } if (typeof item.name === 'string') { item.name = ( ); } }); return root; } ``` Sources: [packages/core/src/source/client/index.tsx:14-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L14-L39) > [!IMPORTANT] > The `deserializePageTree` function visits every node in the tree, checking whether `icon` or `name` properties contain string values, and wraps them in `` elements with inner HTML bindings. Sources: [packages/core/src/source/client/index.tsx:16-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx#L16-L35) ## Core Element and Admonition Components ### Portable Text Node Renderers and Block Configurations Fumadocs provides React component definitions and type interfaces to render Sanity Portable Text blocks into standard Fumadocs UI elements. The `baseBlocks` record maps block styles to heading and paragraph components, where `baseHeading` renders elements from `h1` through `h6` using `Heading` components from `fumadocs-ui/components/heading` with IDs derived from block keys (`_key`). Inline paragraphs are wrapped in `` elements, while block-level paragraphs render as ``. ```tsx const baseHeading: PortableTextBlockComponent = (props) => { return ( {props.children} ); }; export const baseBlocks: Record< 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'normal', PortableTextBlockComponent > = { normal(props) { return props.isInline ? {props.children} :

{props.children}

; }, h1: baseHeading, h2: baseHeading, h3: baseHeading, h4: baseHeading, h5: baseHeading, h6: baseHeading, }; ``` Sources: [packages/sanity/registry/base.component.tsx:14-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/base.component.tsx#L14-L35) | Block Style / Type | Target UI Component | Key Properties | | :--- | :--- | :--- | | `h1` – `h6` | `Heading` (`fumadocs-ui/components/heading`) | `id={props.value._key}`, `as={props.value.style}` | | `normal` | `span` or `p` | `isInline` conditional wrapping | | `code` | `DynamicCodeBlock` (`fumadocs-ui/components/dynamic-codeblock`) | `lang={props.value.language ?? 'text'}`, `code={props.value.code ?? ''}` | | `callout` | `Callout` (`fumadocs-ui/components/callout`) | `title`, `type` | | `cards` / `card` | `Cards` / `Card` (`fumadocs-ui/components/card`) | `title`, `href`, nested body blocks | | `links` (mark) | `Link` (`fumadocs-core/link`) | `href={props.value.href}` | Sources: [packages/sanity/registry/base.component.tsx:14-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/base.component.tsx#L14-L35), [packages/sanity/registry/base.component.tsx:77-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/base.component.tsx#L77-L114), [packages/sanity/registry/base.component.tsx:117-124](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/base.component.tsx#L117-L124) > [!NOTE] > The `renderInlines` and `renderBlocks` helper functions recursively process nested Portable Text arrays, passing `isInline: true` or `isInline: false` down to the `@portabletext/react` node renderer context. Sources: [packages/sanity/registry/base.component.tsx:63-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/base.component.tsx#L63-L69) ### Specialized Component Values and Mark Definitions Custom types like code blocks, callouts, and cards are strongly typed via TypeScript interfaces that define the expected Sanity document structures. The `CodeValue` interface accepts an optional `language` and `code` string, defaulting to `'text'` and empty strings respectively when rendered inside `DynamicCodeBlock`. ```tsx export interface CodeValue { _type: 'code'; language?: string; code?: string; } export interface CalloutValue { _type: 'callout'; title?: PortableTextBlock[]; body?: PortableTextBlock[]; type?: CalloutType; } export interface CardsValue { _type: 'cards'; items?: CardValue[]; } export interface CardValue { _type: 'card'; _key?: string; title?: PortableTextBlock[]; body?: PortableTextBlock[]; url?: string; } ``` Sources: [packages/sanity/registry/base.component.tsx:37-61](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/base.component.tsx#L37-L61) > [!WARNING] > When rendering individual `card` items within a `cards` container, fallback keys use index iteration (`i`) only if item key (`_key`) is undefined on the incoming block value. Sources: [packages/sanity/registry/base.component.tsx:93-95](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/base.component.tsx#L93-L95) ## Interactive Layout and Container Components ### Multi-Step Flows and Procedural Steps Fumadocs processes Sanity Portable Text blocks to render multi-step guides and sequential procedures via `stepsComponents`. The `StepValue` interface defines individual step items containing an optional `_key` and an array of Portable Text body blocks (`body`), while `StepsValue` defines a collection container holding multiple `StepValue` items. ```tsx export interface StepValue { _key?: string; _type: 'step'; body?: PortableTextBlock[]; } export interface StepsValue { _type: 'steps'; items?: StepValue[]; } ``` Sources: [packages/sanity/registry/steps.component.tsx:8-17](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/steps.component.tsx#L8-L17) The `stepsComponents` record maps the `step` and `steps` Sanity types to `Step` and `Steps` components from `fumadocs-ui/components/steps`. When rendering a standalone `step`, the renderer invokes `renderBlocks` on `value.body` and wraps the output in a single `` component. The `steps` renderer maps over `value.items`, generating `` elements for each item with keys falling back from `item._key` to array indices `index`. ```tsx export const stepsComponents: { step: PortableTextTypeComponent; steps: PortableTextTypeComponent; } = { step({ value, renderNode }) { return {renderBlocks(value.body, renderNode)}; }, steps({ value, renderNode }) { return ( {value.items?.map((item, index) => ( {renderBlocks(item.body, renderNode)} ))} ); }, }; ``` Sources: [packages/sanity/registry/steps.component.tsx:25-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/steps.component.tsx#L25-L41) > [!NOTE] > The `renderBlocks` helper function iterates over `PortableTextBlock` arrays, invoking the `@portabletext/react` node renderer with `isInline: false` for every child block. Sources: [packages/sanity/registry/steps.component.tsx:19-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/steps.component.tsx#L19-L23) ### Tab Panels and Content Switchers Structured tab interfaces are generated from Sanity documents using the `tabsComponents` implementation. The `TabValue` interface accepts an optional `_key`, `title` string, and `body` blocks, whereas `TabsValue` aggregates these into an `items` array. ```tsx export interface TabValue { _key?: string; _type: 'tab'; title?: string; body?: PortableTextBlock[]; } export interface TabsValue { _type: 'tabs'; items?: TabValue[]; } ``` Sources: [packages/sanity/registry/tabs.component.tsx:8-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/tabs.component.tsx#L8-L18) | Component Key | Target UI Component | Key Properties and Fallbacks | | :--- | :--- | :--- | | `tab` | Direct child renderer | Renders `value.body` via `renderBlocks` | | `tabs` | `Tabs` (`fumadocs-ui/components/tabs`) | Wraps `TabsList`, `TabsTrigger`, and `Tab` elements | | `TabsTrigger` | `TabsTrigger` (`fumadocs-ui/components/tabs`) | `value={item._key ?? i.toString()}`, title defaults to `Tab ${i + 1}` | | `Tab` | `Tab` (`fumadocs-ui/components/tabs`) | `value={item._key ?? i.toString()}` | Sources: [packages/sanity/registry/tabs.component.tsx:26-54](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/tabs.component.tsx#L26-L54) > [!WARNING] > If a `tabs` block contains an empty items array (`items.length === 0`), the renderer immediately returns `null` and renders no output markup. Sources: [packages/sanity/registry/tabs.component.tsx:34-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/tabs.component.tsx#L34-L36) ### Accordion and Collapsible Groups Accordions and expandable container blocks are structured via `accordionComponents`, supporting both single-item wrappers and multi-item collapsible groups. The `AccordionValue` interface supports an optional `title` array, `id`, `value`, and `body` blocks, while `AccordionsValue` accepts a `type` property constrained to `'single'` or `'multiple'`. ```tsx export interface AccordionValue { _key?: string; _type: 'accordion'; title?: PortableTextBlock[]; id?: string; value?: string; body?: PortableTextBlock[]; } export interface AccordionsValue { _type: 'accordions'; type?: 'single' | 'multiple'; items?: AccordionValue[]; } ``` Sources: [packages/sanity/registry/accordion.component.tsx:8-21](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/accordion.component.tsx#L8-L21) The `accordionComponents` record delegates rendering to `Accordion` and `Accordions` from `fumadocs-ui/components/accordion`. A standalone `accordion` block wraps itself in an `` container, whereas the `accordions` renderer applies `value.type` defaulting to `'single'` if undefined. ```tsx export const accordionComponents: { accordion: PortableTextTypeComponent; accordions: PortableTextTypeComponent; } = { accordion({ value, renderNode }) { return ( {renderBlocks(value.body, renderNode)} ); }, accordions({ value, renderNode }) { return ( {value.items?.map((item) => ( {renderBlocks(item.body, renderNode)} ))} ); }, ``` Sources: [packages/sanity/registry/accordion.component.tsx:29-61](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/accordion.component.tsx#L29-L61) > [!TIP] > Accordion item identifiers fall back from explicitly defined `value` properties to Sanity's `_key` property via `item.value ?? item._key`. Sources: [packages/sanity/registry/accordion.component.tsx:38-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/accordion.component.tsx#L38-L40), [packages/sanity/registry/accordion.component.tsx:53-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/accordion.component.tsx#L53-L55) ## File Hierarchy and Virtual Tree Representation Fumadocs provides directory tree visualization components through Sanity CMS adapters by integrating with `fumadocs-ui/components/files`. The registry definition for files specifies file and component targets under the `files` registry item. ```typescript name: 'files', files: [ { type: 'lib', path: 'files.ts', target: '/sanity/files.ts', }, { type: 'components', path: 'files.component.tsx', target: '/sanity/files.tsx', }, ], }, ``` Sources: [packages/sanity/registry/index.ts:35-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/index.ts#L35-L48) The underlying schema data types for file trees are defined in `packages/sanity/registry/files.component.tsx`. These interfaces capture individual files, nested folders with optional expansion state, and root file collections. ```tsx export interface FileValue { _key?: string; _type: 'file'; name?: string; } export interface FolderValue { _key?: string; _type: 'folder'; name?: string; defaultOpen?: boolean; items?: FileTreeItem[]; } export interface FilesValue { _type: 'files'; items?: FileTreeItem[]; } type FileTreeItem = FileValue | FolderValue; ``` Sources: [packages/sanity/registry/files.component.tsx:4-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/files.component.tsx#L4-L23) | Interface Name | CMS Block Type (`_type`) | Key Properties | Target UI Component | | :--- | :--- | :--- | :--- | | `FileValue` | `file` | `_key`, `name` | `File` (`fumadocs-ui/components/files`) | | `FolderValue` | `folder` | `_key`, `name`, `defaultOpen`, `items` | `Folder` (`fumadocs-ui/components/files`) | | `FilesValue` | `files` | `items` | `Files` (`fumadocs-ui/components/files`) | Sources: [packages/sanity/registry/files.component.tsx:4-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/files.component.tsx#L4-L23), [packages/sanity/registry/files.component.tsx:46-58](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/files.component.tsx#L46-L58) The recursive helper function `renderFileTree` traverses arrays of `FileTreeItem` elements, resolving keys from `item._key` or falling back to the array index. When an item has `_type` set to `'folder'`, it renders a nested `` component with its child items and propagates the `defaultOpen` property. ```tsx function renderFileTree(items: FileTreeItem[] | undefined) { return items?.map((item, index) => { const key = item._key ?? index; if (item._type === 'folder') { return ( {renderFileTree(item.items)} ); } return ; }); } ``` Sources: [packages/sanity/registry/files.component.tsx:25-39](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/files.component.tsx#L25-L39) > [!NOTE] > If a folder or file name is undefined in the Sanity document payload, the component defaults the name property to an empty string `''`. Sources: [packages/sanity/registry/files.component.tsx:31-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/files.component.tsx#L31-L37), [packages/sanity/registry/files.component.tsx:47-51](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/files.component.tsx#L47-L51) ## Related - [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) - [BaseHub Integration](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/basehub-integration) --- ## Technical docs: BaseHub Integration URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/basehub-integration
Relevant source files The following files were used as context for generating this wiki page: - [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts) - [packages/mdx/src/runtime/server.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/server.ts) - [packages/content/src/runtime.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx) - [packages/mdx/src/runtime/dynamic.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/runtime/dynamic.ts) - [packages/mdx/src/plugins/index-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/plugins/index-file.ts) - [packages/content-collections/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/index.ts) - [packages/basehub/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/package.json) - [packages/local-md/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/index.ts) - [packages/sanity/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/base-ui/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts) - [packages/preview/src/lib/source/storage.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/storage.ts) - [packages/content-collections/src/types.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/types.ts) - [packages/create-app/template/+orama-cloud/@app/lib/export-static-indexes.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/template/%2Borama-cloud/%40app/lib/export-static-indexes.ts) - [packages/base-ui/src/provider/waku.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/waku.tsx) - [packages/openapi/src/utils/pages/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/utils/pages/builder.ts) - [packages/preview/src/lib/source/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/lib/source/index.ts) - [packages/base-ui/src/layouts/flux/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/flux/page/index.tsx) - [packages/base-ui/src/utils/use-footer-items.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/utils/use-footer-items.ts) - [packages/content-collections/src/configuration.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content-collections/src/configuration.ts) - [packages/preview/src/components/provider.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/provider.tsx) - [packages/base-ui/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json) - [packages/basehub/src/toc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx) - [packages/base-ui/src/layouts/notebook/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/layouts/notebook/page/index.tsx) - [packages/preview/src/layouts/config.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/layouts/config.tsx) - [packages/asyncapi/src/utils/pages/builder.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/utils/pages/builder.ts) - [packages/preview/src/pages/_api/api/search.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/_api/api/search.ts) - [packages/radix-ui/src/layouts/flux/page/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/layouts/flux/page/index.tsx)
## Overview The `@fumadocs/basehub` package provides official integration tools to connect BaseHub content services with Fumadocs documentation projects. It exports [table of contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) parsers and utilities that bridge BaseHub data structures with core Fumadocs [source loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) conventions. Sources: [packages/basehub/package.json:1-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/package.json#L1-L48), [packages/basehub/src/toc.tsx:1-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx#L1-L49) ## Package Architecture and Dependencies ### Manifest Configuration The `@fumadocs/basehub` package configures its build output as an ECMAScript module (`type: "module"`) with public publishing access. Its exports map entry points standardizing consumer imports, exposing the table of contents module at `./dist/toc.mjs` and the package manifest at `./package.json`. | Export Path | Target File | Purpose | | :--- | :--- | :--- | | `.` | `./dist/toc.mjs` | Main compiled entry point for table of contents parsing utilities | | `./package.json` | `./package.json` | Package metadata definition for module resolution | Sources: [packages/basehub/package.json:1-23](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/package.json#L1-L23) ### Development and Build Scripts The package uses `tsdown` driven by modern build pipelines and `oxlint` for linting. The build configuration leverages workspace dependencies for shared tooling and core Fumadocs packages. | Script Name | Command | Purpose | | :--- | :--- | :--- | | `build` | `tsdown` | Compiles source files into distribution artifacts | | `clean` | `rimraf dist` | Removes built distribution files | | `dev` | `tsdown --watch --clean false` | Runs the build tool in continuous watch mode | | `lint` | `oxlint .` | Executes linter checks across the package | | `types:check` | `tsc --noEmit` | Verifies TypeScript type correctness without emitting outputs | Sources: [packages/basehub/package.json:24-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/package.json#L24-L30) ### Dependencies and Peer Relationships Dependencies are split between build-time development tools and runtime peer requirements. The package relies on `basehub` for upstream API definitions and `fumadocs-core` for structural table of contents types. | Dependency Name | Version Specifier | Dependency Type | Purpose | | :--- | :--- | :--- | :--- | | `@types/node` | `25.9.2` | `devDependencies` | TypeScript definitions for Node.js runtime APIs | | `@types/react` | `^19.2.17` / `*` | `devDependencies` / `peerDependencies` | TypeScript definitions and types for React components | | `basehub` | `9.6.0` / `9.x.x` | `devDependencies` / `peerDependencies` | Upstream BaseHub client and API transaction types | | `fuma-cli` | `^0.1.1` | `devDependencies` | CLI toolset for Fuma workspace utilities | | `fumadocs-core` | `workspace:*` / `^16.8.0` | `devDependencies` / `peerDependencies` | Core Fumadocs framework utilities and TOC types | | `fumadocs-ui` | `workspace:*` | `devDependencies` | UI component library for Fumadocs themes | | `react` | `^19.2.7` / `^19.2.0` | `devDependencies` / `peerDependencies` | React library runtime dependency | | `tsconfig` | `workspace:*` | `devDependencies` | Shared workspace TypeScript configurations | | `tsdown` | `0.22.2` | `devDependencies` | Bundling tool built on esbuild | | `typescript` | `^6.0.3` | `devDependencies` | TypeScript compiler | Sources: [packages/basehub/package.json:31-48](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/package.json#L31-L48) > [!NOTE] > The `@types/react` peer dependency is marked as optional in `peerDependenciesMeta`, allowing consuming projects flexibility in their React typing setups while enforcing the `basehub` 9.x.x and `fumadocs-core` ^16.8.0 runtime contracts. > Sources: [packages/basehub/package.json:43-53](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/package.json#L43-L53) ## Table of Contents Transformation ### Options Configuration and Interface The `parseToc` function extracts table of contents entries from BaseHub rich-text structures. It accepts an options object conforming to the `ParseTOCOptions` interface, which defines the input node structures, starting nesting level, and a rendering callback for rich text nodes. | Option Property | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `node` | `RichTextTocNode \| RichTextTocNode[]` | *none* (required) | Root AST node or array of nodes representing the table of contents data from BaseHub | | `initialLevel` | `number` | `0` | Base heading depth offset applied during recursive tree traversal | | `render` | `(node: RichTextNode) => ReactNode` | *none* (required) | Callback function responsible for rendering rich text child nodes into React nodes | Sources: [packages/basehub/src/toc.tsx:5-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx#L5-L12) ```tsx export interface ParseTOCOptions { node: RichTextTocNode | RichTextTocNode[]; /** @default 0 */ initialLevel?: number; /** render rich text node */ render: (node: RichTextNode) => ReactNode; } ``` Sources: [packages/basehub/src/toc.tsx:5-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx#L5-L12) ### Recursive Traversal and Node Processing The traversal algorithm processes root nodes, accepting either a single `RichTextTocNode` or an array of nodes. It invokes an internal `next` function recursively, incrementing levels when encountering list items or ordered lists while ignoring nodes without content or text types. ```tsx export function parseToc(options: ParseTOCOptions): TOCItemType[] { const { node: root, render, initialLevel = 0 } = options; const results: TOCItemType[] = []; function next(node: RichTextTocNode, level = initialLevel) { if (node.type === 'text' || !node.content) return; for (const item of node.content) { if (item.type === 'orderedList' || item.type === 'listItem') { next(item, level + 1); continue; } if (item.type !== 'paragraph' || !item.content || item.content.length === 0) continue; for (const text of findTextNode(item.content[0])) { const mark = text.marks?.find((m) => m.type === 'link'); if (!mark) continue; results.push({ depth: level + 1, url: mark.attrs.href, title: render({ ...text, marks: text.marks?.filter((m) => m.type !== 'link'), } as RichTextNode), }); } } } if (Array.isArray(root)) for (const item of root) next(item); else next(root); return results; } ``` Sources: [packages/basehub/src/toc.tsx:14-49](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx#L14-L49) > [!WARNING] > Paragraph items without link marks are skipped during tree traversal. Each target TOC item requires a valid link mark inside its text node structure to supply the `url` attribute for Fumadocs navigation. > Sources: [packages/basehub/src/toc.tsx:27-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx#L27-L35) ### Text Node Extraction and Filtering Text nodes are flattened using the `findTextNode` helper utility, which recursively unpacks nested node content into an array of text leaf nodes. The parser inspects the marks of each extracted text node for link types, strips the link mark before passing the node to the `render` callback, and constructs the final `TOCItemType` entry with the calculated depth and anchor URL. ```tsx function findTextNode(n: RichTextTocNode): Extract[] { if (n.type === 'text') { return [n]; } return n.content?.flatMap(findTextNode) ?? []; } ``` Sources: [packages/basehub/src/toc.tsx:51-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx#L51-L57) > [!TIP] > When filtering marks during title rendering, `parseToc` removes only the `link` mark type from the text node so that other formatting marks like bold or italic remain intact for the rendering callback. > Sources: [packages/basehub/src/toc.tsx:36-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx#L36-L40) ## Rich Text Structure Mapping ### AST Node Parsing and Flattening The extraction of table of contents entries from BaseHub abstract syntax trees relies on recursive AST node traversal and flattening helpers. The `findTextNode` function processes incoming `RichTextTocNode` items, checking if an individual node matches the `text` type or traversing nested content arrays via `flatMap`. ```tsx function findTextNode(n: RichTextTocNode): Extract[] { if (n.type === 'text') { return [n]; } return n.content?.flatMap(findTextNode) ?? []; } ``` Sources: [packages/basehub/src/toc.tsx:51-57](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx#L51-L57) > [!NOTE] > When `findTextNode` encounters a node without a `content` property or a non-text node lacking nested children, it safely returns an empty array to prevent runtime traversal errors during deep AST recursion. > Sources: [packages/basehub/src/toc.tsx:56-56](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx#L56-L56) ### Heading Hierarchy and Depth Resolution The parser builds heading depth hierarchies by tracking nesting levels across ordered lists, list items, and paragraph blocks. The `parseToc` routine handles root inputs as either single node objects or arrays, iterating through child collections to assign appropriate depth offsets. | AST Node Type / Check | Condition | Action Taken | | :--- | :--- | :--- | | `Array.isArray(root)` | Root input is an array | Iterates over each item, invoking `next(item)` | | `node.type === 'text' \|\| !node.content` | Leaf node or empty container | Terminates current traversal branch immediately | | `item.type === 'orderedList' \|\| item.type === 'listItem'` | List container or list item | Recursively invokes `next(item, level + 1)` | | `item.type !== 'paragraph' \|\| !item.content \|\| length === 0` | Non-paragraph or empty block | Skips item iteration via `continue` | Sources: [packages/basehub/src/toc.tsx:18-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx#L18-L28) ```tsx function next(node: RichTextTocNode, level = initialLevel) { if (node.type === 'text' || !node.content) return; for (const item of node.content) { if (item.type === 'orderedList' || item.type === 'listItem') { next(item, level + 1); continue; } if (item.type !== 'paragraph' || !item.content || item.content.length === 0) continue; ``` Sources: [packages/basehub/src/toc.tsx:18-28](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx#L18-L28) > [!WARNING] > Paragraph blocks that contain empty content arrays are bypassed during text extraction. The parser explicitly verifies that `item.content.length > 0` before attempting to access nested text children. > Sources: [packages/basehub/src/toc.tsx:27-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/basehub/src/toc.tsx#L27-L27) ## Source Loader Integration Patterns ### Content Source Adapters and Collection Stores Fumadocs manages remote headless CMS queries and static document files by bridging collection adapters into standardized source trees. The `toFumadocsSource` helper function transforms active file collection stores—specifically MDX stores and metadata stores—into a uniform `StaticSource` structure containing explicit page and metadata file entries. ```typescript export function toFumadocsSource< Mdx extends MDXStoreData | MDXStoreLazyData = MDXStoreData< PageData, unknown >, Meta extends { data: MetaData } = { data: MetaData }, >(mdxStore?: FileCollectionStore, metaStore?: FileCollectionStore) { const out: StaticSource<{ pageData: ToPageData; metaData: Meta['data']; }> = { files: [] }; for (const page of mdxStore?.list() ?? []) { out.files.push({ type: 'page', data: ('compiled' in page ? { ...page, ...page.compiled.frontmatter } : { ...page, ...page.frontmatter }) as unknown as ToPageData, path: page.path, absolutePath: page.fullPath, }); } for (const file of metaStore?.list() ?? []) { out.files.push({ type: 'meta', data: file.data, path: file.path, absolutePath: file.fullPath, }); } return out; } ``` Sources: [packages/content/src/runtime.ts:12-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L12-L42) > [!NOTE] > During collection store iteration, `toFumadocsSource` inspects page objects for a `compiled` property, merging frontmatter attributes from either `page.compiled.frontmatter` or `page.frontmatter` depending on the compilation state of the underlying store item. > Sources: [packages/content/src/runtime.ts:26-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/runtime.ts#L26-L31) ### Dynamic Sanity and Content Collection Routing Headless CMS platforms like Sanity map remote document structures to virtual file paths by resolving document slugs and types through client fetch options. The `createSanitySource` function queries documents filtered by document type, constructs filesystem-like paths via `generatePath` or slug arrays, and attaches lazy loading handlers and structured data extraction routines to each page record. ```typescript export function createSanitySource( options: SanityOptions, ): DynamicSource<{ pageData: DocToPage; metaData: MetaData; }> { const { docType, baseDir, generatePath } = options; let sanityFetch: (query: string, params?: QueryParams) => Promise; if ('sanityFetch' in options) { const fn = options.sanityFetch; sanityFetch = async (query, params) => { const res = await fn({ query, params }); return res.data as never; }; } else { const client = options.client; sanityFetch = client.fetch.bind(client); } return { async files() { const data = await sanityFetch[]>( `*[_type == $docType]{ _id, _type, title, slug, description }`, { docType, }, ); return data.map((file) => { const slugs = file.slug?.current?.split('/').filter((v) => v.length > 0) ?? []; let filePath = generatePath ? generatePath(file) : slugs.length === 0 ? 'index.mdx' : `${slugs.join('/')}.mdx`; if (baseDir) filePath = path.join(baseDir, filePath); return { type: 'page', data: { ...file, title: file.title ?? file._id, async load() { const data = await sanityFetch( `*[_type == $docType && _id == $id][0]{ ..., "_toc": body[style in ["h1", "h2", "h3", "h4", "h5", "h6"]] }`, { id: file._id, docType, }, ); return { ...data, _toc: data._toc ?? [], renderToc(opts) { if (!data._toc) return []; return renderToc({ toc: data._toc, ...opts }); }, }; }, async structuredData() { const data = await sanityFetch<{ structuredBody: StructuredBlock[] } | undefined>( `*[_type == $docType && _id == $id][0]{ "structuredBody": body[]{ ..., _type == "block" => { "heading": select( style == "h1" => "h1", style == "h2" => "h2", style == "h3" => "h3", style == "h4" => "h4", style == "h5" => "h5", style == "h6" => "h6", null ), "content": pt::text(@) ``` Sources: [packages/sanity/src/index.ts:63-161](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts#L63-L161) | Configuration Option | Type | Purpose | | :--- | :--- | :--- | | `docType` | `string` | CMS document type identifier for filtering queries | | `generatePath` | `(doc: ShallowDoc) => string` | Custom virtual file path generator function | | `baseDir` | `string` | Base directory prefix applied to virtual file paths | | `client` | `SanityClient` | Direct Sanity client instance for fetching queries | | `sanityFetch` | `DefinedFetchType` | Live or custom fetch handler for Next.js Sanity integrations | Sources: [packages/sanity/src/index.ts:16-36](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts#L16-L36) > [!TIP] > When slug arrays evaluate to an empty collection during Sanity source ingestion, the loader defaults the virtual file path to `index.mdx` before applying any configured `baseDir` offsets. > Sources: [packages/sanity/src/index.ts:93-99](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/src/index.ts#L93-L99) ## Page Tree and Navigation Synthesis ### Hierarchical Tree Traversal and Footer Item Resolution Fumadocs builds sequential page navigation and linear document flows by traversing root and folder nodes in the standard page tree structure. The `useFooterItems` utility accesses the active page tree context, walking down folder collections to extract inner index pages and child items while systematically ignoring external links and non-page nodes. ```typescript export function useFooterItems(): PageTree.Item[] { const { root } = useTreeContext(); const cached = footerCache.get(root); if (cached) return cached; const list: PageTree.Item[] = []; function onNode(node: PageTree.Node) { if (node.type === 'folder') { if (node.index) onNode(node.index); for (const child of node.children) onNode(child); } else if (node.type === 'page' && !node.external) { list.push(node); } } for (const child of root.children) onNode(child); footerCache.set(root, list); return list; ``` Sources: [packages/base-ui/src/utils/use-footer-items.ts:10-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/utils/use-footer-items.ts#L10-L27) > [!NOTE] > Performance is optimized across tree rendering cycles by caching computed footer lists in a `WeakMap` keyed directly against the `PageTree.Root` or `PageTree.Folder` instance. > Sources: [packages/base-ui/src/utils/use-footer-items.ts:5-13](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/utils/use-footer-items.ts#L5-L13) ### Navigation Context and Layout Configuration Layout configuration functions assemble complete navigation models by merging global application settings with dynamic source loaders. The `layoutConfig` module initializes documentation layouts by retrieving generated page trees from source loaders and injecting them alongside custom base navigation branding and logo elements. ```tsx async docs(): Promise { const config = await getConfigRuntime(); const source = await getSource(config); return { tree: source.getPageTree(), ...(await this.base()), }; }, ``` Sources: [packages/preview/src/layouts/config.tsx:31-38](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/layouts/config.tsx#L31-L38) | Layout Property | Return Type | Purpose | | :--- | :--- | :--- | | `base()` | `Promise` | Resolves default navigation branding and logo parameters | | `docs()` | `Promise` | Combines source page trees with base layout configurations | | `home()` | `Promise` | Returns landing page configuration settings | Sources: [packages/preview/src/layouts/config.tsx:13-41](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/layouts/config.tsx#L13-L41) > [!WARNING] > When traversing folder nodes during footer synthesis, the recursive walker checks for the existence of `node.index` before iterating over `node.children`, ensuring index documents are always positioned ahead of standard sibling entries. > Sources: [packages/base-ui/src/utils/use-footer-items.ts:17-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/utils/use-footer-items.ts#L17-L19) ## Related - [Source Loader](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/source-loader) - [Sanity CMS Integration](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/sanity-cms-integration) --- ## Technical docs: shadcn/ui Docs Registry URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/content-sources/shadcn-ui-docs-registry
Relevant source files The following files were used as context for generating this wiki page: - [packages/base-ui/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts) - [packages/radix-ui/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts) - [packages/cli/src/commands/shared.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts) - [packages/shadcn/src/manual-installation.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts) - [packages/shadcn/src/rsc.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/rsc.tsx) - [packages/shadcn/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/index.ts) - [packages/cli/src/commands/add.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/add.ts) - [packages/sanity/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/index.ts) - [packages/shadcn/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/package.json) - [packages/radix-ui/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/package.json) - [packages/shared/registry.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/registry.ts) - [packages/asyncapi/src/ui/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/ui/index.tsx) - [packages/cli/src/registry/installer.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/installer.ts) - [packages/cli/src/commands/customise.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/customise.ts) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts) - [packages/cli/src/registry/plugins/preserve.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/plugins/preserve.ts) - [packages/openapi/src/ui/base.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/ui/base.tsx) - [packages/base-ui/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/package.json) - [packages/create-app/src/plugins/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/orama-cloud.ts) - [packages/cli/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts) - [packages/create-app/src/plugins/ai.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/ai.ts) - [packages/preview/src/components/provider.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/components/provider.tsx) - [packages/api-docs/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/api-docs/package.json) - [packages/base-ui/src/provider/waku.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/waku.tsx) - [packages/preview/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json) - [packages/create-app/scripts/sync.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/scripts/sync.ts) - [packages/core/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/package.json) - [packages/python/src/components/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx) - [packages/openapi/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/package.json)
## Overview The `@fumadocs/shadcn` package provides an integration layer that connects `shadcn` UI registry definitions with Fumadocs documentation projects. It resolves component files, dependencies, and configuration snippets for manual or automated installation. Sources: [packages/shadcn/package.json:1-8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/package.json#L1-L8), [packages/shadcn/src/index.ts:10-24](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/index.ts#L10-L24) By parsing built registry items and processing component collections across multiple UI libraries like `fumadocs/base-ui` and `fumadocs/radix-ui`, it enables seamless component discovery and code generation. Sources: [packages/base-ui/registry/index.ts:9-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts#L9-L14), [packages/radix-ui/registry/index.ts:9-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts#L9-L14), [packages/shadcn/src/manual-installation.ts:58-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts#L58-L64) ## Registry Item Schema and Definitions ### Built Registry Structure and Component Metadata Documentation and UI components within the integration are modeled through built registry item types, file specifications, and common utility definitions. Each entry in the registry maps specific file paths, targets, and internal component types such as layout slots or shared utilities. | Component / File Type | Identifier / Path | Target Location | Description | | :--- | :--- | :--- | :--- | | Slot Component | `slots/*` | `/layouts/**/slots/*` | Discovered layout slot components from layout directories | | URL Utility | `urls` | `utils/urls.ts` | Common URL helper utility | | Class Name Utility | `cn` | `utils/cn.ts` | Class merging utility | | Reference Merger | `merge-refs` | `utils/merge-refs.ts` | DOM ref merging utility | | [Table of Contents](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/table-of-contents) | `toc` | `/toc/*.tsx` | Clerk, default, and index Table of Contents components | Sources: [packages/shared/registry.ts:5-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/registry.ts#L5-L83) ### Registry Types and Manual Installation Snippets The manual installation system defines union types for generated documentation snippets, file payloads, and package manager commands. Snippets are categorized by their kind, determining how they render in documentation views. ```typescript export type ManualInstallationSnippet = | { lang: string; code: string; path: string; title: string; kind: 'file'; } | { kind: 'docs'; content: string; } | { kind: 'cssVars' | 'css' | 'tailwind' | 'envVars'; lang: string; code: string; } | { kind: 'dependencies' | 'devDependencies' | 'registryDependencies'; lang: string; codeTabs: Record; dependencies: string[]; }; ``` Sources: [packages/shadcn/src/manual-installation.ts:12-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts#L12-L42) > [!NOTE] > The `includeRegistryDependencies` option defaults to `true` when fetching installation options, automatically queueing and resolving local registry dependencies alongside primary items. Sources: [packages/shadcn/src/manual-installation.ts:51-63](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts#L51-L63) ## Component Discovery Across UI Libraries ### Glob Discovery and Slot Collection The shared registry logic uses `tinyglobby` to scan the local filesystem for layout slot components within layout subdirectories. By executing a glob pattern against the target components directory, it discovers custom layout slots and dynamically constructs corresponding registry components with unlisted flags. ```typescript export async function findSlotComponents(dir: string): Promise { const slots: Component[] = []; for (const file of await glob('layouts/**/slots/*', { cwd: dir })) { const relativePath = path.relative('layouts', file); const name = relativePath .split(path.sep) .filter((v) => v !== 'slots') .join('/') .slice(0, -path.extname(relativePath).length); slots.push({ name: `slots/${name}`, unlisted: true, files: [ { path: file, type: 'layout', target: path.join('', relativePath), }, ], }); } return slots; } ``` Sources: [packages/shared/registry.ts:1-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/registry.ts#L1-L30) > [!NOTE] > The dynamic slot discovery function transforms file paths by removing intermediate segment markers such as `slots` and stripping file extensions, producing standardized slot identifiers like `slots/docs/header`. Sources: [packages/shared/registry.ts:8-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/registry.ts#L8-L15) ### Library Registry Integration Both the `fumadocs/base-ui` and `fumadocs/radix-ui` registries resolve their base component directory relative to the current file URL using Node's path utilities. Each library registry aggregates common shared utilities, dynamically evaluated slot components from `findSlotComponents`, and unlisted layout groups or individual UI components. | Registry Package | Registry Name Property | Base Source Directory (`dir`) | Core Shared Components Included | | :--- | :--- | :--- | :--- | | `packages/base-ui/registry/index.ts` | `fumadocs/base-ui` | `../src` | `urls`, `cn`, `merge-refs`, `toc` | | `packages/radix-ui/registry/index.ts` | `fumadocs/radix-ui` | `../src` | `urls`, `cn`, `merge-refs`, `toc` | Sources: [packages/base-ui/registry/index.ts:1-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts#L1-L14), [packages/radix-ui/registry/index.ts:1-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts#L1-L14), [packages/shared/registry.ts:32-83](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/registry.ts#L32-L83) > [!WARNING] > In the shadcn CLI integration, the exact order of entries within the component array matters because it dictates the sequence in which import paths and dependencies are written to the consumer codebase. Sources: [packages/base-ui/registry/index.ts:8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts#L8), [packages/radix-ui/registry/index.ts:8](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts#L8) ## Manual Installation Pipeline and Formatting ### Resolving Dependencies and Collecting Items The manual installation pipeline is initialized via `createShadcnDocs`, which binds a `RegistryContext` containing the `registryPath` and root directory. When `getManualInstallation` executes with a given registry item name, it delegates to `collectItems` to recursively traverse and resolve local dependencies, accumulating items into a collection queue. ```typescript export async function getManualInstallation( this: RegistryContext, options: GetManualInstallationOptions, ): Promise { const { name, includeRegistryDependencies = true } = options; const items = await collectItems.call(this, name, includeRegistryDependencies); if (items.length === 0) return []; const snippets: ManualInstallationSnippet[] = []; const dependencies = new Set(); const devDependencies = new Set(); const registryDependencies = new Set(); ``` Sources: [packages/shadcn/src/manual-installation.ts:58-69](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts#L58-L69) > [!WARNING] > If a registry item file cannot be read from the filesystem during queue traversal, `collectItems` catches the error and assigns a `null` value in the lookup map, safely skipping broken or missing paths without halting execution. Sources: [packages/shadcn/src/manual-installation.ts:141-158](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts#L141-L158) ### Formatting Snippets and Display Paths Once item collection finishes, the pipeline iterates through each registry item to extract documentation notes, environment variables, CSS variables, CSS rules, Tailwind configurations, and constituent file contents. File display paths are normalized according to their specific registry type classification. | Registry File Type | Default Target Path Prefix | Example Resolved Output | | :--- | :--- | :--- | | `registry:ui` | `components/ui/` | `components/ui/button.tsx` | | `registry:component` | `components/` | `components/card.tsx` | | `registry:hook` | `lib/hooks/` | `lib/hooks/use-mobile.ts` | | `registry:lib` | `lib/` | `lib/utils.ts` | | `registry:block` | `components/` | `components/hero.tsx` | Sources: [packages/shadcn/src/manual-installation.ts:218-236](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts#L218-L236) > [!TIP] > If a registry file defines an explicit `target` property starting with `~/`, the leading tilde and slash are sliced off to produce a clean relative display path for the generated code snippet. Sources: [packages/shadcn/src/manual-installation.ts:218-221](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/manual-installation.ts#L218-L221) ## Server Components for Code Snippets ### Rendering Syntax-Highlighted Code Blocks and Documentation Notes The `Snippet` asynchronous React Server Component handles the presentation of individual `ManualInstallationSnippet` objects by evaluating their item types and rendering appropriate UI elements. When an item has a `kind` of `'docs'`, it bypasses [syntax highlighting](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/core-architecture/syntax-highlighting) and outputs the descriptive text directly inside a paragraph styled with text colors and preserved whitespace. ```tsx export async function Snippet({ item }: { item: ManualInstallationSnippet }) { if (item.kind === 'docs') { return

{item.content}

; } ``` Sources: [packages/shadcn/src/rsc.tsx:28-31](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/rsc.tsx#L28-L31) > [!NOTE] > Standard code snippets receive syntax highlighting through `ServerCodeBlock` alongside an array of pre-configured Shiki transformers consisting of `transformerNotationDiff()` and `transformerIcon()`. Sources: [packages/shadcn/src/rsc.tsx:10-12](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/rsc.tsx:10-12), [packages/shadcn/src/rsc.tsx:59-66](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/rsc.tsx#L59-L66) ### File Title Mapping and Dependency Tabs To provide contextual headers for standard code snippets, the `getTitle` helper function inspects item kinds and maps them to fixed filenames or dynamic file paths. For dependency and package installation snippets containing multiple tabs, `Snippet` renders interactive code block tabs via `CodeBlockTabs` and `CodeBlockTabsTrigger` components. | Item Kind | Mapped Title or Filename | | :--- | :--- | | `file` | `item.path` | | `cssVars` / `css` | `globals.css` | | `envVars` | `.env.local` | | `tailwind` | `tailwind.config.js` | Sources: [packages/shadcn/src/rsc.tsx:14-26](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/rsc.tsx:14-26), [packages/shadcn/src/rsc.tsx:57-65](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/rsc.tsx:57-65) ```tsx switch (item.kind) { case 'dependencies': case 'devDependencies': case 'registryDependencies': const tabs = Object.entries(item.codeTabs); return ( {tabs.map(([t]) => ( {t} ))} {tabs.map(([k, v]) => ( ))} ); } ``` Sources: [packages/shadcn/src/rsc.tsx:33-55](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/rsc.tsx:33-55) > [!TIP] > Dependency and devDependency code blocks utilize `Object.entries(item.codeTabs)` to populate multi-package installer tabs, setting the default active tab to the first entry in the collection. Sources: [packages/shadcn/src/rsc.tsx:37-40](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/rsc.tsx:37-40) ## CLI Automated Installation Integration ### UI Registry Endpoint Mapping and Client Resolution The [Fumadocs CLI](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/fumadocs-cli) defines default UI registry mappings in shared configuration modules, mapping identifiers such as `'base-ui'` to `'fumadocs/base-ui'` and `'radix-ui'` to `'fumadocs/radix-ui'`. Sources: [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4) During command execution, the `createClientFromDir` utility function resolves registry directory parameters against predefined shortcuts, instantiating either an `HttpRegistryConnector` or a `LocalRegistryConnector` depending on whether the target path begins with an HTTP protocol schema. | Shortcut Key | Resolved URL Target | | :--- | :--- | | `:preview` | `https://preview.fumadocs.dev/registry` | | `:dev` | `http://localhost:3000/registry` | | *default* | `https://fumadocs.dev/registry` | Sources: [packages/cli/src/index.ts:39-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L39-L42), [packages/cli/src/index.ts:108-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L108-L114) ```mermaid flowchart TD A[Input Dir Option] --> B{Matches Shortcut?} B -- Yes --> C[Resolve Shortcut URL] B -- No --> D{Starts with http:// or https://?} C --> D D -- Yes --> E[HttpRegistryConnector] D -- No --> F[LocalRegistryConnector] ``` Sources: [packages/cli/src/index.ts:108-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L108-L114) ### Template Plugin and Installer Integration The application creation toolkit integrates registry components directly into newly scaffolded projects via asynchronous template plugins. For instance, the AI search plugin initializes a `FumadocsComponentInstaller` coupled with an `HttpRegistryConnector` pointing to the main registry endpoint to fetch and install required components like `ai/${provider}`. ```typescript export function ai(provider: 'openrouter' | 'llmgateway' | 'inkeep'): TemplatePlugin { return { async afterWrite() { const config = await getDefaultConfig(this.dest); const installer = new FumadocsComponentInstaller( new HttpRegistryConnector('https://fumadocs.dev/registry'), config, this.dest, ); try { const deps = await installer.install(`ai/${provider}`).then((res) => res.deps()); if (deps.hasRequired()) await deps.writeRequired(); await addAIChat(this); await fs.writeFile(path.join(this.dest, '.env.local'), `${envKey[provider]}=`); } catch (e) { console.error(e); } }, }; } ``` Sources: [packages/create-app/src/plugins/ai.ts:16-37](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/ai.ts#L16-L37) > [!NOTE] > Environment variables for AI providers are programmatically mapped through the `envKey` record, linking `'openrouter'`, `'llmgateway'`, and `'inkeep'` directly to `OPENROUTER_API_KEY`, `LLM_GATEWAY_API_KEY`, and `INKEEP_API_KEY` respectively. Sources: [packages/create-app/src/plugins/ai.ts:10-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/ai.ts#L10-L14) Layout preservation plugins intercept component installation stacks to maintain references to standard layout specifications unless explicitly requested via direct installation. The `pluginPreserveLayouts` hook filters out child sub-components matching predefined layout names and rewrites local file imports to point directly to package-level UI modules like `fumadocs-ui/layouts/docs`. ```typescript export function pluginPreserveLayouts(): InstallerPlugin { const layoutNames = [ 'layouts/home', 'layouts/flux', 'layouts/notebook', 'layouts/docs', 'layouts/shared', ]; ``` Sources: [packages/cli/src/registry/plugins/preserve.ts:6-13](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/plugins/preserve.ts#L6-L13), [packages/cli/src/registry/plugins/preserve.ts:43-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/plugins/preserve.ts#L43-L50) ## Related - [Base UI Components](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/ui-layouts/base-ui-components) --- ## Technical docs: Fumadocs CLI URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/fumadocs-cli
Relevant source files The following files were used as context for generating this wiki page: - [packages/cli/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts) - [packages/preview/src/cli/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/index.ts) - [packages/cli/src/commands/add.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/add.ts) - [packages/cli/src/commands/customise.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/customise.ts) - [packages/cli/src/commands/file-tree.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/file-tree.ts) - [packages/cli/src/commands/export-epub.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/export-epub.ts) - [packages/create-app/src/bin.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/bin.ts) - [packages/sanity/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/index.ts) - [packages/cli/src/commands/shared.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts) - [packages/base-ui/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/registry/index.ts) - [packages/cli/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/package.json) - [packages/python/fumapy/__init__.py](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/fumapy/__init__.py) - [packages/core/src/source/client/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/source/client/index.tsx) - [packages/epub/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/src/index.ts) - [packages/radix-ui/registry/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts) - [packages/asyncapi/src/server/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/asyncapi/src/server/index.tsx) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/create-app/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json) - [packages/sanity/registry/files.component.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/sanity/registry/files.component.tsx) - [packages/shared/registry.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/registry.ts) - [packages/python/pyproject.toml](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/pyproject.toml) - [packages/python/src/convert.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/convert.ts) - [packages/preview/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/package.json) - [packages/cli/src/registry/installer.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/installer.ts) - [packages/cli/src/registry/plugins/preserve.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/plugins/preserve.ts) - [packages/python/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/package.json) - [packages/python/src/components/index.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/python/src/components/index.tsx) - [packages/epub/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/epub/package.json) - [packages/shadcn/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shadcn/src/index.ts) - [packages/local-md/src/bin.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/local-md/src/bin.ts)
## Overview The Fumadocs CLI (`@fumadocs/cli`) is an operational tool designed to scaffold projects, manage component installations, customize documentation layouts, and process documentation structures. Operating through the `commander` package, it offers commands for configuration initialization, component downloads via `add`, interactive layout modifications via `customise`, [EPUB Book Export](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/epub-book-export)ing, and directory tree parsing into MDX or JavaScript components. Sources: [packages/cli/package.json:2-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/package.json#L2-L15), [packages/cli/src/index.ts:15-106](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L15-L106) ## CLI Architecture and Command Dispatch ### Entry Point and Command Registration The Fumadocs CLI executable is defined in `packages/cli/src/index.ts` and configured as a Node.js command-line tool via the `bin` field in `packages/cli/package.json`. It instantiates a root `Command` object from `commander`, reads its version metadata from `packageJson.version`, and registers global options such as `--config `. When executed without arguments, the root action invokes `initConfig()`, which checks for or creates a `./cli.json` configuration file and logs status messages using `picocolors`. ```json "bin": { "cli": "./dist/index.js" }, ``` Sources: [packages/cli/package.json:13-15](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/package.json#L13-L15) ```typescript const program = new Command().option('--config '); program .name('fumadocs') .description('CLI to setup Fumadocs, init a config') .version(packageJson.version) .action(async () => { if (await initConfig()) { console.log(picocolors.green('Initialized a `./cli.json` config file.')); } else { console.log(picocolors.redBright('A config file already exists.')); } }); ``` Sources: [packages/cli/src/index.ts:15-27](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L15-L106) Subcommands are registered directly on the `program` instance or nested under parent command groups. The available CLI commands, their aliases, arguments, options, and actions are structured as follows: | Command | Aliases | Arguments | Options | Action / Handler | | :--- | :--- | :--- | :--- | :--- | | `fumadocs` (default) | — | — | `--config ` | Initializes `./cli.json` via `initConfig()`. | | `customise` | `customize` | — | `--dir `, `--config ` | Loads config and runs `customise` with a registry client. | | `add` | — | `[components...]` | `--dir `, `--config ` | Downloads components using a registry client and config. | | `export epub` | — | — | `--framework `, `--output `, `--scaffold-only` | Exports documentation to EPUB format via `exportEpub`. | | `tree` | — | `[json_or_args]`, `[output]` | `--js`, `--no-root`, `--import-name `, `--config ` | Parses directory trees or JSON nodes into MDX or JS formats. | Sources: [packages/cli/src/index.ts:17-106](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L17-L106) ### Registry Connector Resolution and Configuration Registry source resolution is handled by `createClientFromDir`, which maps shortcut keywords to predefined remote URLs or distinguishes between HTTP endpoints and local filesystem paths. ```typescript const dirShortcuts: Record = { ':preview': 'https://preview.fumadocs.dev/registry', ':dev': 'http://localhost:3000/registry', }; ``` Sources: [packages/cli/src/index.ts:39-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L39-L42) The shortcut mapping supports the following expansion values: | Shortcut | Target URL | | :--- | :--- | | `:preview` | `https://preview.fumadocs.dev/registry` | | `:dev` | `http://localhost:3000/registry` | Sources: [packages/cli/src/index.ts:39-42](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L39-L42) > [!NOTE] > If the directory parameter does not match `:preview` or `:dev`, `createClientFromDir` evaluates whether the string begins with `http://` or `https://`. If it does, it instantiates an `HttpRegistryConnector`; otherwise, it falls back to a `LocalRegistryConnector`. ```typescript function createClientFromDir(dir = 'https://fumadocs.dev/registry') { if (dir in dirShortcuts) dir = dirShortcuts[dir]; return dir.startsWith('http://') || dir.startsWith('https://') ? new HttpRegistryConnector(dir) : new LocalRegistryConnector(dir); } ``` Sources: [packages/cli/src/index.ts:108-114](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L108-L114) ## Registry Component Installation Flow ### Component Selection and Interactive Prompts The component addition command (`add`) managed in `packages/cli/src/commands/add.ts` facilitates downloading and integrating UI elements, layouts, and integration components into a project. When invoked without explicit component arguments (`input.length === 0`), the CLI displays a loading spinner and fetches registry information using `connector.fetchRegistryInfo(subRegistry)`. It constructs a list of selectable items by scanning across three distinct sources: common components (`undefined` sub-registry with prefix `common`), Sanity components (`fumadocs/sanity` with prefix `sanity`), and the UI library registry configured by `config.uiLibrary` (mapped via `UIRegistries`) with prefix `ui`. ```typescript const subRegistry = UIRegistries[config.uiLibrary]; if (input.length === 0) { const spin = spinner(); spin.start('fetching registry'); async function scan(subRegistry?: string, prefix?: string): Promise { const info = await connector.fetchRegistryInfo(subRegistry); return info.indexes.map((item) => ({ label: `${prefix ? `${picocolors.bold(prefix)} - ` : ''}${item.title ?? item.name}`, value: { name: item.name, subRegistry }, hint: item.description, })); } spin.stop(picocolors.bold(picocolors.greenBright('registry fetched'))); const value = await autocompleteMultiselect({ message: 'Select components to install', options: [ ...(await scan(undefined, 'common')), ...(await scan('fumadocs/sanity', 'sanity')), ...(await scan(subRegistry, 'ui')), ].sort((a, b) => a.label.localeCompare(b.label)), }); ``` Sources: [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4), [packages/cli/src/commands/add.ts:22-46](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/add.ts#L22-L46) The UI registries mapping defines the sub-registry paths associated with supported UI libraries: | UI Library Key | Sub-Registry Path | | :--- | :--- | | `base-ui` | `fumadocs/base-ui` | | `radix-ui` | `fumadocs/radix-ui` | Sources: [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4) Presented through `@clack/prompts`'s `autocompleteMultiselect`, the sorted options allow users to select multiple components simultaneously. If the user cancels the prompt via `isCancel(value)`, the command outputs an ending message and exits gracefully. When components are provided directly as arguments via the command line, the CLI checks each item against `connector.hasComponent(item)` to assign the appropriate sub-registry or defaults to the configured UI registry. ```typescript if (isCancel(value)) { outro('Ended'); return; } targets = value; } else { targets = await Promise.all( input.map(async (item) => (await connector.hasComponent(item)) ? { name: item } : { subRegistry, name: item }, ), ); } ``` Sources: [packages/cli/src/commands/add.ts:48-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/add.ts#L48-L60) > [!WARNING] > If a concurrent installation is attempted while `this.interactive` is already populated in `FumadocsComponentInstaller`, an error stating `cannot install while installing another component` is thrown, preventing race conditions during file writing. ```typescript async installInteractive(name: string, subRegistry?: string): Promise { if (this.interactive) { throw new Error(`cannot install while installing another component`); } ``` Sources: [packages/cli/src/registry/installer.ts:54-58](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/installer.ts#L54-L58) ### Installer Configuration and Layout Preservation `FumadocsComponentInstaller` extends `ComponentInstaller` from `fuma-cli/registry/installer`, binding output directories to configuration aliases and registering plugins such as `pluginPreserveLayouts()`. ```typescript export class FumadocsComponentInstaller extends ComponentInstaller { private interactive: { name: string; spin: SpinnerResult; } | null = null; constructor(connector: RegistryConnector, config: LoadedConfig, cwd?: string) { super(connector, { cwd, framework: config.framework, outDir: { base: config.baseDir, components: config.aliases.componentsDir, css: config.aliases.cssDir, layout: config.aliases.layoutDir, lib: config.aliases.libDir, ui: config.aliases.uiDir, }, io: { onWarn: (message) => { this.interactive?.spin.message(message); }, confirmFileOverride: async (options) => { if (!this.interactive) return true; const { name, spin } = this.interactive; spin.clear(); const value = await confirm({ message: `Do you want to override ${options.path}?`, initialValue: false, }); if (isCancel(value)) { outro('Installation terminated'); process.exit(0); } spin.start(picocolors.bold(picocolors.cyanBright(`Installing ${name}`))); return value; }, onFileDownloaded: (options) => { this.interactive?.spin.message(options.path); }, }, plugins: [pluginPreserveLayouts()], }); } ``` Sources: [packages/cli/src/registry/installer.ts:9-52](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/installer.ts#L9-L52) The `pluginPreserveLayouts` plugin defined in `packages/cli/src/registry/plugins/preserve.ts` intercepts sub-component trees and import statements to maintain references to built-in layout packages unless a layout itself is being installed directly. The tracked layout components include: | Layout Identifier | Mapped Package / Specifier | | :--- | :--- | | `layouts/home` | `fumadocs-ui/layouts/home` | | `layouts/flux` | `fumadocs-ui/layouts/flux` | | `layouts/notebook` | `fumadocs-ui/layouts/notebook` | | `layouts/docs` | `fumadocs-ui/layouts/docs` | | `layouts/shared` | `fumadocs-ui/layouts/shared` | Sources: [packages/cli/src/registry/plugins/preserve.ts:7-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/plugins/preserve.ts#L7-L30), [packages/cli/src/registry/plugins/preserve.ts:43-50](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/plugins/preserve.ts#L43-L50) > [!NOTE] > When downloading files, `FumadocsComponentInstaller` hooks into `confirmFileOverride` to prompt the user via `@clack/prompts` if an existing file conflicts with a downloaded registry asset, terminating the process if cancelled. ```typescript confirmFileOverride: async (options) => { if (!this.interactive) return true; const { name, spin } = this.interactive; spin.clear(); const value = await confirm({ message: `Do you want to override ${options.path}?`, initialValue: false, }); if (isCancel(value)) { outro('Installation terminated'); process.exit(0); } spin.start(picocolors.bold(picocolors.cyanBright(`Installing ${name}`))); return value; }, ``` Sources: [packages/cli/src/registry/installer.ts:31-45](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/installer.ts#L31-L45) ### Dependency Resolution and Package Manager Execution After downloading target components, `installInteractive` evaluates required dependencies through `deps.hasRequired()`. If missing dependencies or devDependencies are identified, they are displayed inside a boxed prompt using `@clack/prompts`. ```typescript try { this.interactive = { name, spin }; const deps = await super.install(name, subRegistry).then((res) => res.deps()); spin.stop(picocolors.bold(picocolors.greenBright(`${name} installed`))); if (deps.hasRequired()) { log.message(); box([...deps.dependencies, ...deps.devDependencies].join('\n'), 'New Dependencies'); const pm = (await detectPackageManager())?.name ?? 'npm'; ``` Sources: [packages/cli/src/registry/installer.ts:62-70](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/installer.ts#L62-L70) The CLI detects the local project's package manager via `detectPackageManager()`, defaulting to `npm` if no manager is found. Users are prompted to confirm whether they want to install the packages immediately with the detected manager. ```typescript const pm = (await detectPackageManager())?.name ?? 'npm'; const value = await confirm({ message: `Do you want to install with ${pm}?`, }); if (isCancel(value)) { outro('Installation terminated'); process.exit(0); } ``` Sources: [packages/cli/src/registry/installer.ts:70-79](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/installer.ts#L70-L79) If confirmed, the installer starts a spinner and invokes `deps.installRequired(pm)` to execute the installation. If declined, it invokes `deps.writeRequired()` to write declarations without running the package manager. ```typescript if (value) { const spin = spinner({ errorMessage: 'Failed to install dependencies', }); spin.start('Installing dependencies'); await deps.installRequired(pm); spin.stop('Dependencies installed'); } else { await deps.writeRequired(); } } ``` Sources: [packages/cli/src/registry/installer.ts:80-90](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/registry/installer.ts#L80-L90) ## Interactive Layout and Slot Customization ### Layout Selection and Customization Targets The `customise` command guides users through interactive selection prompts using `@clack/prompts` to choose a UI layout and target parts for customization based on the configured UI library registry. The available layout targets and their identifiers are defined with specific integration hints. | Layout Option | Identifier (`id`) | Target Registry Path | Description | | :--- | :--- | :--- | :--- | | Docs Layout | `docs` | `layouts/docs` | The default documentation layout | | Notebook Layout | `notebook` | `layouts/notebook` | A more compact variant of the docs layout | | Flux Layout | `flux` | `layouts/flux` | The experimental variant of the docs layout | | Home Layout | `home` | `layouts/home` | The layout for non-documentation pages | Sources: [packages/cli/src/commands/customise.ts:31-89](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/customise.ts#L31-L89), [packages/cli/src/commands/shared.ts:1-4](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/shared.ts#L1-L4) When a layout other than `home` is selected, users can choose between installing the entire layout, replacing and rewriting from minimal styles via `layouts/docs-min`, or customizing specific component slots by parsing unlisted registry indexes matching `slots/${selected.id}`. ```typescript return select({ message: 'Which part do you want to customize?', options: [ { label: 'All', hint: 'install the entire layout', value: selected, }, { label: 'Replace & rewrite from minimal styles', hint: 'for those who want to build their own UI from ground up', value: { id: 'docs-min', targets: [{ name: 'layouts/docs-min' }], print() { printLayout( ['fumadocs-ui/layouts/docs', '@/layouts/docs'], ['fumadocs-ui/layouts/docs/page', '@/layouts/docs/page'], ); }, }, }, ...info.unlistedIndexes.flatMap((index) => { const prefix = `slots/${selected.id}`; if (!index.name.startsWith(prefix)) return []; let name = index.name.slice(prefix.length + 1); if (name.startsWith('page/')) { name = name.slice('page/'.length); return { label: `Page: ${name}`, hint: "only replace a part of layout's page, useful for adjusting details", value: { id: index.name, targets: [{ subRegistry, name: index.name }], print() { printSlot({ at: `@/layouts/${selected.id}/page/slots/${name}`, layoutId: selected.id, name, isPage: true, }); }, } as TargetInfo, }; } return { label: `Layout: ${name}`, hint: 'only replace a part of layout, useful for adjusting details', value: { id: index.name, targets: [{ subRegistry, name: index.name }], print() { printSlot({ at: `@/layouts/${selected.id}/slots/${name}`, layoutId: selected.id, name, isPage: false, }); }, } as TargetInfo, }; }), ], }); ``` Sources: [packages/cli/src/commands/customise.ts:94-160](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/customise.ts#L94-L160) > [!NOTE] > For non-home layouts, slot customization paths distinguish between page-level parts prefixed with `page/` and general layout slots, generating import mapping advice for either `` or `` components accordingly. ```typescript if (name.startsWith('page/')) { name = name.slice('page/'.length); return { label: `Page: ${name}`, hint: "only replace a part of layout's page, useful for adjusting details", value: { id: index.name, targets: [{ subRegistry, name: index.name }], print() { printSlot({ at: `@/layouts/${selected.id}/page/slots/${name}`, layoutId: selected.id, name, isPage: true, }); }, } as TargetInfo, }; } return { label: `Layout: ${name}`, hint: 'only replace a part of layout, useful for adjusting details', value: { id: index.name, targets: [{ subRegistry, name: index.name }], print() { printSlot({ at: `@/layouts/${selected.id}/slots/${name}`, layoutId: selected.id, name, isPage: false, }); }, } as TargetInfo, }; ``` Sources: [packages/cli/src/commands/customise.ts:121-157](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/customise.ts#L121-L157) ## File Tree Inspection and Formatting ### Directory Parsing and JsonTreeNode Schema The `tree` command processes directory structures by accepting either a raw JSON string argument or scanning a target directory via `runTree`. The underlying AST nodes are defined by the `JsonTreeNode` union type, supporting files, directories, reports, and links. ```typescript export type JsonTreeNode = | { type: 'file'; name: string; } | { type: 'directory'; name: string; contents: JsonTreeNode[]; } | { type: 'report'; } | { type: 'link'; name: string; }; ``` Sources: [packages/cli/src/commands/file-tree.ts:1-18](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/file-tree.ts#L1-L18) When parsing inputs, valid nodes are filtered against a known scanned list containing `file`, `directory`, and `link` node types. | Node Type (`type`) | Properties | Description | | :--- | :--- | :--- | | `file` | `name: string` | Represents an individual file within the tree | | `directory` | `name: string`, `contents: JsonTreeNode[]` | Represents a folder containing nested child nodes | | `link` | `name: string` | Represents a symbolic or external link node | | `report` | *None* | Represents an execution report or diagnostic entry | Sources: [packages/cli/src/commands/file-tree.ts:1-19](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/file-tree.ts#L1-L19) > [!NOTE] > If a directory node contains a single nested directory child, the parser flattens the path by combining their names (e.g., `item.name/child.name`) to avoid rendering redundant single-child nesting levels. ```typescript if (item.type === 'directory') { if (item.contents.length === 1 && 'name' in item.contents[0]) { const child = item.contents[0]; return toNode({ ...child, name: `${item.name}/${child.name}`, }); } ``` Sources: [packages/cli/src/commands/file-tree.ts:27-35](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/file-tree.ts#L27-L35) ### Conversion to MDX and JavaScript Structures The `treeToMdx` function recursively transforms `JsonTreeNode` arrays into MDX component syntax utilizing ``, ``, and `` tags. When the `noRoot` option is enabled and the root input consists of a single directory, the top-level container is unwrapped so that its internal contents become the primary children. ```typescript export function treeToMdx(input: JsonTreeNode[], noRoot = false): string { function toNode(item: JsonTreeNode): string { if (item.type === 'file' || item.type === 'link') { return ``; } if (item.type === 'directory') { if (item.contents.length === 1 && 'name' in item.contents[0]) { const child = item.contents[0]; return toNode({ ...child, name: `${item.name}/${child.name}`, }); } return ` ${item.contents.map(toNode).filter(Boolean).join('\n')} `; } return ''; } let children = input.filter((v) => scanned.includes(v.type)); if (noRoot && children.length === 1 && input[0].type === 'directory') { children = input[0].contents; } return ` ${children.map(toNode).filter(Boolean).join('\n')} `; } ``` Sources: [packages/cli/src/commands/file-tree.ts:21-54](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/file-tree.ts#L21-L54) ```typescript export function treeToJavaScript( input: JsonTreeNode[], noRoot?: boolean, importName = 'fumadocs-ui/components/files', ): string { return `import { File, Files, Folder } from ${JSON.stringify(importName)} export default (${treeToMdx(input, noRoot)})`; } ``` Sources: [packages/cli/src/commands/file-tree.ts:56-64](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/file-tree.ts#L56-L64) > [!WARNING] > The CLI automatically selects JavaScript output format if the `--js` flag is passed or if the output file path extension matches `.js`, `.tsx`, or `.jsx`; otherwise, it outputs raw MDX components. ```typescript const jsExtensions = ['.js', '.tsx', '.jsx']; const noRoot = !root; let nodes: JsonTreeNode[]; try { nodes = JSON.parse(str ?? '') as JsonTreeNode[]; } catch { nodes = await runTree(str ?? './'); } const out = js || (output && jsExtensions.includes(path.extname(output))) ? treeToJavaScript(nodes, noRoot, importName) : treeToMdx(nodes, noRoot); ``` Sources: [packages/cli/src/index.ts:84-97](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts#L84-L97) ## Registry Source Organization and Indexing ### UI Library Catalog Structures Fumadocs manages component registries across different UI packages, including `fumadocs/radix-ui`, `fumadocs/base-ui`, and `fumadocs/sanity`. Each registry defines an export structure containing its registry name, source directory (`dir`), a catalog of components with associated files and targets, and package dependencies. ```typescript export const registry: Registry = { name: 'fumadocs/radix-ui', dir, components: [ ...commonComponents, ...(await findSlotComponents(dir)), // ... layout and component definitions ], dependencies: { 'fumadocs-core': null, 'fumadocs-ui': null, react: null, }, }; ``` Sources: [packages/radix-ui/registry/index.ts:9-345](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts#L9-L345) Shared utilities and common components—such as URL handlers, class-name merging, and table-of-contents clerks—are reused across libraries through modular registry shares. Slot components are dynamically discovered using `tinyglobby` scanning over layout directories. ```typescript export async function findSlotComponents(dir: string): Promise { const slots: Component[] = []; for (const file of await glob('layouts/**/slots/*', { cwd: dir })) { const relativePath = path.relative('layouts', file); const name = relativePath .split(path.sep) .filter((v) => v !== 'slots') .join('/') .slice(0, -path.extname(relativePath).length); slots.push({ name: `slots/${name}`, unlisted: true, files: [ { path: file, type: 'layout', target: path.join('', relativePath), }, ], }); } return slots; } ``` Sources: [packages/shared/registry.ts:5-30](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/shared/registry.ts#L5-L30) > [!NOTE] > The order of files matters when writing import paths on the consumer's codebase, ensuring that common utilities and slot components precede layout and UI primitives in the registry array. ```typescript // in shadcn cli, the order of files matters when writing import paths on consumer's codebase export const registry: Registry = { name: 'fumadocs/radix-ui', dir, components: [ ...commonComponents, ...(await findSlotComponents(dir)), ``` Sources: [packages/radix-ui/registry/index.ts:8-14](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts#L8-L14) ### Component Manifest Definitions Component entries within a registry specify metadata, file types, source paths, and installation targets. Unlisted components, such as low-level UI primitives (`button`, `popover`, `scroll-area`, `collapsible`) and internal layout variations (`layouts/sidebar`, `layouts/shared`, `layouts/docs`, `layouts/flux`, `layouts/notebook`, `layouts/home`), are omitted from public component listings while remaining installable by the CLI. | Component Name | File Types | Target/Preserve Settings | Description / Notes | | :--- | :--- | :--- | :--- | | `github-info` | `components` | Default target | A card to display GitHub repo info | | `image-zoom` | `components`, `css` | Default target | Zoomable Image component with styles | | `layouts/shared` | `layout` | `/shared/index.tsx`, `client.tsx` (preserveAs: `layouts/shared`) | Unlisted shared layout files | | `layouts/docs` | `layout` | `/docs/index.tsx`, `client.tsx`, `page/index.tsx` | Unlisted documentation layout files | | `ai/page-actions` | `components` | `/ai/page-actions.tsx` | Common page actions for AI search integration | Sources: [packages/radix-ui/registry/index.ts:36-339](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts#L36-L339) > [!WARNING] > Registry entries that include layout files must specify metadata with `preserveAs` rules to prevent incorrect path rewriting during consumer project scaffolding. ```typescript meta: { preserveAs: 'layouts/shared', }, }, ``` Sources: [packages/radix-ui/registry/index.ts:44-47](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/registry/index.ts#L44-L47) ## Related - [Create App Generator](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/create-app-generator) - [EPUB Book Export](https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/epub-book-export) --- ## Technical docs: Create App Generator URL: https://www.doc0.dev/docs/e8872a72-1909-479c-b585-dc74c6e26726/technical/developer-tooling/create-app-generator
Relevant source files The following files were used as context for generating this wiki page: - [packages/create-app/src/bin.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/bin.ts) - [packages/create-app/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/index.ts) - [packages/create-app/src/constants.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/constants.ts) - [packages/mdx/src/next/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/next/index.ts) - [packages/cli/src/commands/export-epub.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/export-epub.ts) - [packages/create-app/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/package.json) - [packages/create-app/scripts/sync.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/scripts/sync.ts) - [packages/mdx/src/vite/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/mdx/src/vite/index.ts) - [packages/create-app/src/plugins/orama-cloud.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/orama-cloud.ts) - [packages/create-app/src/plugins/ai.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/ai.ts) - [packages/create-app/src/transform/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/transform/index.ts) - [packages/cli/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/index.ts) - [packages/base-ui/src/provider/tanstack.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/base-ui/src/provider/tanstack.tsx) - [packages/create-app-versions/package.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app-versions/package.json) - [packages/typescript/src/lib/base.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/typescript/src/lib/base.ts) - [packages/create-app/src/plugins/next-use-takumi.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/next-use-takumi.ts) - [packages/create-app/src/plugins/biome.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/biome.ts) - [packages/create-app/src/plugins/oxlint.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/oxlint.ts) - [packages/radix-ui/src/provider/tanstack.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/radix-ui/src/provider/tanstack.tsx) - [packages/openapi/src/generate-file.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/openapi/src/generate-file.ts) - [packages/content/src/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/content/src/index.ts) - [packages/create-app/src/plugins/eslint.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/eslint.ts) - [packages/preview/src/pages/...slugs.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/pages/%5B...slugs%5D.tsx) - [packages/create-app/src/transform/tanstack-start.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/transform/tanstack-start.ts) - [packages/cli/src/commands/add.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/commands/add.ts) - [packages/create-app/src/plugins/biome.next.json](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/plugins/biome.next.json) - [packages/cli/src/config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/cli/src/config.ts) - [packages/preview/src/cli/index.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/preview/src/cli/index.ts) - [packages/create-app/tsdown.config.ts](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/tsdown.config.ts) - [packages/core/src/framework/tanstack.tsx](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/core/src/framework/tanstack.tsx)
## Overview The `create-fumadocs-app` package provides an automated CLI scaffolding tool to set up new documentation projects configured with Fumadocs, supporting frameworks including Next.js, Waku, React Router, and TanStack Start. It addresses the complexity of configuring build-time MDX compilation, router integration, layout providers, and peripheral developer tooling by orchestrating interactive prompt groups, template asset copying, workspace dependency version alignment, and AST-based code transformations. Design decisions center around modular template plugins and AST manipulation via `ts-morph` to programmatically inject search integrations, AI chat components, and linter configurations directly into generated project structures without manual boilerplate intervention. Sources: [packages/create-app/src/bin.ts:1-60](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/bin.ts#L1-L60), [packages/create-app/src/index.ts:1-126](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/index.ts#L1-L126), [packages/create-app/src/constants.ts:34-80](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/constants.ts#L34-L80), [packages/create-app/src/transform/index.ts:1-174](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/transform/index.ts#L1-L174) ## Interactive Prompts and Scaffolding Execution ### CLI Configuration and Argument Parsing The CLI entry point uses `@commander-js/extra-typings` to define positional arguments and option flags before initiating interactive prompts. The root command accepts an optional `[name]` argument for the target project and configures flags for build options, templates, package managers, and tool integrations. ```typescript const command = program .argument('[name]', 'the project name') .option('--src', '(Next.js only) enable `src/` directory') .option('--install', 'install packages automatically') .option('--no-git', 'disable auto Git repository initialization') .addOption( new Option( '--linter ', 'configure a linter/formatter, ESLint is currently Next.js only.', ).choices(['eslint', 'oxlint', 'biome']), ) .addOption( new Option('--search ', 'configure a search solution').choices(['orama', 'orama-cloud']), ) .addOption( new Option('--og-image ', 'configure OG image generation').choices(['next-og', 'takumi']), ) .addOption( new Option('--ai-chat ', 'configure AI chat').choices([ 'openrouter', 'llmgateway', 'inkeep', ]), ) .addOption( new Option('--template ', 'choose a template').choices( templates.map((item) => item.value), ), ) .addOption( new Option('--pm ', 'choose a package manager') .choices(managers) .default(getPackageManager()), ); ``` Sources: [packages/create-app/src/bin.ts:21-54](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/bin.ts#L21-L54) The command line options govern project parameters such as framework features, linters, search providers, and package managers. | Option Flag | Argument Type | Choices / Default | Purpose | | :--- | :--- | :--- | :--- | | `--src` | boolean | `undefined` | Enable `src/` directory (Next.js only) | | `--install` | boolean | `undefined` | Install packages automatically | | `--no-git` | boolean | `undefined` | Disable auto Git repository initialization | | `--linter ` | string | `eslint`, `oxlint`, `biome` | Configure a linter or formatter | | `--search ` | string | `orama`, `orama-cloud` | Configure a search solution | | `--og-image ` | string | `next-og`, `takumi` | Configure Open Graph image generation | | `--ai-chat ` | string | `openrouter`, `llmgateway`, `inkeep` | Configure AI chat integration | | `--template ` | string | Dynamic template list | Choose a starter template | | `--pm ` | string | Detected package manager | Choose a package manager | Sources: [packages/create-app/src/bin.ts:23-54](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/bin.ts#L23-L54) > [!NOTE] > When executing in a CI environment detected via `isCI`, interactive prompts are bypassed entirely, falling back to default values such as `untitled` for project name and `+next+fuma-docs-mdx` for the template. Sources: [packages/create-app/src/bin.ts:65-76](https://github.com/blade47/fumadocs/blob/a9f988897e7dc4ef3d62b2865d80da2f5607701e/packages/create-app/src/bin.ts#L65-L76) ### Interactive Prompt Groups Using `@clack/prompts`, the CLI prompts the user through a structured group flow if flags are omitted from the command line execution. Each prompt checks for existing configuration values or CI flags before rendering interactive selectors or text inputs. ```typescript const options = await group( { name: async () => { if (defaultName) return defaultName; if (isCI) return 'untitled'; return text({ message: 'Project name', placeholder: 'my-app', defaultValue: 'my-app', }); }, template: async () => { if (config.template) return config.template; if (isCI) return '+next+fuma-docs-mdx'; return select