> For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt.

# unified

```ts
import { wikitextParse, wikitextRehype, wikitextFinalize } from "react-wikitext/unified";
```

`/unified` 不加载默认解析器，也不加载 React。它把处理管线拆成三个 unified 插件，适合已经有处理器、需要在中间插入自定义转换的场景。

:::warning
raw 模式不会自动补上安全阶段，也不会替你安排插件顺序。需要固定的安全顺序时，优先使用 [`prepareWikitext`](/zh/api/prepare.md)。
:::

## 典型处理器

```ts
import { unified } from "unified";
import { createWikiparser } from "react-wikitext/parse";
import { wikitextParse, wikitextRehype, wikitextFinalize } from "react-wikitext/unified";

const parser = createWikiparser();

const processor = unified()
  .use(wikitextParse({ parser }))
  .use(semanticPlugin) // 在 wiki 语义树上运行
  .use(wikitextRehype({ resolveLink })) // 语义树 → HAST，尚未清洗
  .use(rehypePlugin) // 自定义 HAST 转换
  .use(wikitextFinalize()); // 清洗 + 最终整理 + 渲染快照
```

## wikitextParse

```ts
wikitextParse({ parser, parseOptions? }): WikitextUnifiedPlugin<WikitextRoot, WikitextRoot>
```

- 把源码解析为 `WikitextDocument`，写入 VFile。
- 返回一份独立的工作树；同一个 VFile 再次解析会重置库字段，不清空调用方其他 `data`。
- 必须显式提供解析器；`/unified` 不会隐式加载 `wikiparser-node`。

## wikitextRehype

```ts
wikitextRehype(options?): WikitextUnifiedPlugin<WikitextRoot, Root>
```

- 读取 VFile 中的解析结果，使用处理器实际传入的树，而不是缓存的旧树。
- 校验工作树结构与预算、重新分配 id、转换为 HAST。
- 保存尚未执行安全阶段的准备上下文。
- 选项只包含准备设置（解析函数、`policy`、`labels`、`headingIdStrategy` 与 `handlers`）。
- **不执行** `wikitextPlugins` / `rehypePlugins`；显式传入这两个字段（包括空数组）会抛 `PREPARE_FAILED`。插件应通过外层处理器的 `.use(...)` 注册。

## wikitextFinalize

```ts
wikitextFinalize({ headingIdStrategy? }): WikitextUnifiedPlugin<Root, Root>
```

- 必须在所有 rehype 插件之后调用。
- 完成清洗与最终整理，并把 `wikitextRenderDocument` 写入 VFile。
- 显式 `headingIdStrategy` 优先于准备设置，并同时用于最终标题与快照 meta。
- 之后不能再插入内容；跳过它的 HAST 不能作为渲染文档。

## 错误与前置条件

- 缺少 `wikitextParse` 时，`wikitextRehype` 抛 `WikitextPrepareError("INVALID_DOCUMENT")`，`stage` 为 `prepare`。
- 缺少 `wikitextRehype` 时，`wikitextFinalize` 抛 `WikitextPrepareError("PREPARE_FAILED")`。
- 这些错误不会自动修复插件顺序；请检查处理器链。

## 什么时候不用 raw 模式

| 需求                | 建议                                         |
| ----------------- | ------------------------------------------ |
| 只需要插入语义树或 HAST 插件 | `prepareWikitext` 的插件选项                    |
| 需要固定的清洗顺序         | `prepareWikitext` / `prepareWikitextAsync` |
| 需要展开模板            | `/expand` + `/hast`                        |
| 需要视图组件            | `/view` 或根入口                               |

## 相关

- [准备 `/hast`](/zh/api/prepare.md)：固定安全顺序、解析函数与策略。
- [AST `/ast`](/zh/api/ast.md)：语义节点与查询。
- [错误与诊断](/zh/api/errors.md)：`WikitextPrepareError` 的字段。
