# @botfather/units 中文文档

规范地址：https://npmcn.com/package/%40botfather/units/

版本：2\.0\.1
npm 元数据更新时间：2026-06-23T12:55:57.661Z
中文译文更新时间：2026-11-08T14:34:22.112Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40botfather/units
原文对照：https://npmcn.com/package/%40botfather/units/?lang=original
项目主页：https://github.com/Botfather/units/tree/main/packages/units
源码仓库：https://github.com/Botfather/units

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：94.3 kB，18 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：react \>=18
- 首次发布：2026-03-02T13:22:54.854Z
- 最新版本发布：2026-06-23T12:55:57.381Z
- 近 30 天下载量：1919（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：3（近 12 个月 3 个）

## 中文简介

用于构建交互式 UIs 的轻量级 DSL .

## 安装

```sh
npm install @botfather/units
```

也可以使用：`pnpm add @botfather/units`、`yarn add @botfather/units`、`bun add @botfather/units`

## README

# @ botfather/ 单位

用于 **单位 DSL** 用于描述UI树的轻量级、无依赖性声明语言 `.ui` 文档.

## 这是什么?

单位为作者的UI提供一种比JSX显著的terser的最小语法,使它非常适合代码生成(例如LLM输出)和人类编辑. A 类 `.ui` 文件被解析成一个平坦的 JSON AST,然后可以通过包含的 React 渲染器或任何自定义主机框架通过自定义渲染器 API 提供.

**主要特点:**

-   O(n) 单通解析器 — 无外部解析依赖性
-   Render- 不可知性 — 反应是选入的; 插入任意框架
-   连续相接相干物质
-   编辑器集成的递增解析助手

## 安装

```sh
npm install @botfather/units
# react is a peer dependency for the React renderer
npm install react
```

## 这个 `.ui` 语法

```
TagName (prop:'value', expr=@scopeVar, visible?=@bool) {
  text 'Literal @{interpolated}'
  @rawExpr
  #if (@cond) { ... }
  #for (item, i in @list) {
    #key (@item.id)
    ChildTag (...)
  }
  #slot (slotName)
}
```

| 语法 | 含义 |
| --- | --- |
| `Tag (props) { children }` | 元素节点 |
| `key:'string'` 编号 : `key:123` 编号 : `key:true` | 静态道具值 |
| `key=@expr` | 动态表达式道具 |
| `key?=@expr` | 有条件的布尔道具( 仅在真伪时设置) |
| `!click { handler(@event) }` | 事件处理快手 |
| `on:click={ handler(@event) }` | 事件处理长窗体 |
| `text 'literal'` | 文本节点( 支持) `@{...}` 插值) |
| `@expr` | 内含表达式节点 |
| `#if (@cond) { }` | 有条件指令 |
| `#for (item, i in @list) { }` | 有索引的循环 |
| `#for item in @list { }` | 压缩循环 |
| `#slot (name)` | 已命名槽 |
| `#key (@expr)` | 下一个标签的关键指令 |
| `// comment` | 行注释 |

## API 密码

### 分析

```js
import { parseUnits } from "@botfather/units/parser";

const ast = parseUnits(`
  Button (variant:'primary') {
    text 'Click me'
  }
`);
// → { type: 'document', body: [...] }
```

在语法错误上丢出带有源偏移的描述性错误并片段.

### 格式化

```js
import { formatUnits } from "@botfather/units/print";

const canonical = formatUnits(source);
```

行宽默认为 `100`覆盖 `UNITS_PRINT_WIDTH` 环境变量.

### 反应渲染器

```js
import { renderUnits } from "@botfather/units/runtime";
import uiAst from "./app.ui"; // via vite-plugin-units

const element = renderUnits(uiAst, scope, {
  components: { Button: MyButtonComponent },
  slots: { default: <span>content</span> },
  set: (key, value) => setState(s => ({ ...s, [key]: value })),
});
```

| 选项 | 类型 | 说明 |
| --- | --- | --- |
| `components` | `Record<string, Component>` | 标记名称 ~ react 组件映射 |
| `slots` | `Record<string, ReactNode | fn>` | 已命名槽内容 |
| `set` | `(key, value) => void` | 变异处理器 `set()` 表达式 |
| `evalExpr` | `(expr, scope) => any` | 自定义表达式评估器 |

### 自定义( 非反应) 渲染器

```js
import { createUnitsRenderer } from "@botfather/units/custom-renderer";

const renderer = createUnitsRenderer({
  element(name, props, events, children) { /* create node */ },
  text(value) { /* create text node */ },
  fragment(children) { /* group children */ },
});

const node = renderer.render(ast, scope, options);
```

自定义渲染器指令行为镜像 `#if/#elif/#else` 财务报告和审定财务报表 `#for/#key`。 。 。 .

### 表达式评价器

```js
import { createUnitsEvaluator } from "@botfather/units/runtime";

const evalExpr = createUnitsEvaluator();
const result = evalExpr("@items.length > 0", scope);
```

表达式使用 `@` 作为瞄准镜访问器的前缀。 汇编评价缓存 `Function` 每个表达式字符串的对象,而范围前缀的正态保留了文字 `@` 引用字符串中的字符.

### 递增分析

```js
import {
  findChangedRange,
  findSmallestEnclosingNode,
  incrementalParse,
} from "@botfather/units/incremental";

const range = findChangedRange(prevSource, nextSource);
const node = findSmallestEnclosingNode(ast, range.start, range.endPrev);
const newAst = incrementalParse(prevAst, prevSource, nextSource);
```

用于编辑器集成. `incrementalParse` 尝试先是附加和最小的闭合节点回放,然后在需要时安全地返回到完整的回放区.

### 树 IR 适配器

```js
import {
  normalizeDomTree,
  normalizeA11yTree,
  serializeAgentTree,
} from "@botfather/units/tree-ir";

const domIr = normalizeDomTree(rawDomLikeTree);
const a11yIr = normalizeA11yTree(rawAccessibilityTree);
const compact = serializeAgentTree(domIr);
```

`serializeAgentTree` 应用面向符号的默认值(dedups 冗余) `name`编号 :`text` ,省去角色隐含动作,如 `click` 按钮上,倒取出空文本叶,并省去文本节点代号。 传递选项, 如 `includeRedundantNameText: true`, (中文(简体) ), `includeImplicitActions: true`,或 `includeTextIds: true` 以保留那些田地.

### 变形程序

```js
import {
  compileTransformProgram,
  runTransformProgram,
} from "@botfather/units/transform";

const program = compileTransformProgram(programSource);
const result = runTransformProgram(program, irTree, { task: "summarize" });
```

变形程序使用 `.ui` 用a的语法 `Program (kind:'transform')` root 和 预留的变换标签 (`Rule`, (中文(简体) ), `Filter`, (中文(简体) ), `Merge`, (中文(简体) ), `Pass`在变换模式中.

### 奖励+核查器

```js
import { scoreProgram, verifyProgram } from "@botfather/units/reward";

const score = scoreProgram({ inputTree, outputTree, expectations });
const verification = verifyProgram(score, {
  action_recall: 1,
  name_recall: 0.98,
  text_f1: 0.95,
});
```

### 已验证库 + 合成

```js
import {
  createVerifiedProgramMetadata,
  writeVerifiedProgram,
} from "@botfather/units/library";
import { runSynthesisLoop } from "@botfather/units/synthesis";
```

### Vite 导入的脚本类型

添加 `/// <reference types="@botfather/units/ui" />` (或从 `@botfather/units/ui`获取类型 `.ui` 文件导入 :

```ts
import { ast, source } from "./app.ui";
import formatted from "./app.ui?format";
import tokens from "./app.ui?tokens";
import html from "./app.ui?highlight";
```

## 软件包出口

| 导出路径 | 说明 |
| --- | --- |
| `@botfather/units` | 再出口所有东西 |
| `@botfather/units/parser` | `parseUnits` |
| `@botfather/units/print` | `formatUnits` |
| `@botfather/units/runtime` | `renderUnits`, (中文(简体) ), `createUnitsEvaluator` |
| `@botfather/units/custom-renderer` | `createUnitsRenderer` |
| `@botfather/units/incremental` | 递增分析助手 |
| `@botfather/units/tree-ir` | DOM/AX 正常化+紧凑序列化 |
| `@botfather/units/transform` | 变形程序编译器 + 运行时间 |
| `@botfather/units/reward` | 奖励分数+核查门 |
| `@botfather/units/library` | 已验证的程序库助手 |
| `@botfather/units/synthesis` | 惯性合成循环帮助器 |
| `@botfather/units/ui` | 申报类型 `.ui` 文件导入 |

## 许可证

麻省理工学院

## 常见问题

### @botfather/units 是什么？

用于构建交互式 UIs 的轻量级 DSL \.

### 如何安装 @botfather/units？

在项目目录运行 npm install @botfather/units，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（\>=18）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @botfather/units 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @botfather/units 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @botfather/units 可以商用吗？

@botfather/units 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @botfather/units 的下载量有多少？

根据 npm 官方下载统计，@botfather/units 在 2026/10/09 – 2026/11/07 这 30 天内被下载 1,919 次，日均约 64 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @botfather/units 还在维护吗？

最新版本 2\.0\.1 发布于 2026/06/23（4 个月前）；至今共发布 3 个版本，其中过去 12 个月发布了 3 个；首次发布于 2026/03/02。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

