# @asyncapi/protobuf-schema-parser 中文文档

规范地址：https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/

版本：4\.0\.0
npm 元数据更新时间：2026-11-02T09:37:02.364Z
中文译文更新时间：2026-11-07T01:36:26.930Z
软件包许可：Apache-2\.0

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

原始 npm 页面：https://www.npmjs.com/package/%40asyncapi/protobuf-schema-parser
原文对照：https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/?lang=original
项目主页：https://github.com/asyncapi/protobuf-schema-parser#readme
源码仓库：https://github.com/asyncapi/protobuf-schema-parser

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

- 包体积（解压后）：194 kB，31 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=18
- 运行依赖：3 个
- 首次发布：2023-04-11T14:10:28.180Z
- 最新版本发布：2026-11-02T09:37:02.031Z
- 近 30 天下载量：1293669（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：44（近 12 个月 9 个）

## 中文简介

用于协议缓冲数据类型的 AsyncAPI schema 解析器 .

## 安装

```sh
npm install @asyncapi/protobuf-schema-parser
```

也可以使用：`pnpm add @asyncapi/protobuf-schema-parser`、`yarn add @asyncapi/protobuf-schema-parser`、`bun add @asyncapi/protobuf-schema-parser`

## README

# ProtoBuff 数据类型 Schema 解析器

[![npm version](https://img.shields.io/npm/v/@asyncapi/protobuf-schema-parser.svg)](https://www.npmjs.com/package/@asyncapi/protobuf-schema-parser) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/LICENSE) [![Node](https://img.shields.io/badge/node-%3E%3D18-brightgreen.svg)](https://nodejs.org/)

用于 [协议缓冲](https://protobuf.dev/) 数据类型。 它会插入 [`@asyncapi/parser`](https://github.com/asyncapi/parser-js) 让你嵌入 `.proto` 消息 定义 `payload` (或 `schema`asyncAPI 文档中的 在解析期间 Protobuf定义被转换成基于JSON Schema的AsyncAPI(基于JSON Schema)计划,所以其余的 AsyncAPI工具可以和任何其他消息有效载荷一样工作.

## 概览

AsyncAPI消息可以携带以不同语种描述的有效载荷. `@asyncapi/parser` 代表任何有效载荷 `schemaFormat` 它不理解 本地注册 _策略解析器_。这个软件包是协议缓冲的策略:您注册一次,以及 每个信件的有效载荷都贴上Protobuf标签 `schemaFormat` 解析并扩展为 等同 AsyncAPI 计划.

-   与 **Protobuf 2和Protobuf 3号** 计划.
-   计划格式的注册 `application/vnd.google.protobuf;version=2` 财务报告和审定财务报表 `application/vnd.google.protobuf;version=3`。 。 。 .
-   地图 Protobuf 消息, scalars, enums, `repeated` 字段,则, `oneof` 和巢型给JSON Schema.
-   将主要评论理解为说明和一套 `@`\- 用于验证的说明,默认 和实例.
-   可选地图 [原型验证](https://github.com/bufbuild/protoc-gen-validate) 财务报告和审定财务报表 [缩写](https://github.com/bufbuild/protovalidate) 规则给 JSON Schema 验证器.
-   与浏览器相兼容的和同时建造了CommonJS和ES模块.

> Protobuf 2和3没有严格的区分. 声明 `schemaFormat` 作为 `application/vnd.google.protobuf;version=2` 提供原型3计划(反之亦然)时 本身不会造成错误.
> 
> 版本 `>= 2.0.0` 本软件包需要 `@asyncapi/parser` `>= 2.0.0`; 数据 `3.x` 目标 `@asyncapi/parser` `>= 3.6.0`。 。 。 .

-   [安装](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-installation)
-   [使用量](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-usage)
-   [支持的投入](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-supported-input)
-   [如何运作](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-how-it-works)
-   [Scalar 类型格式](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-scalar-type-formats)
-   [评论和说明](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-comments-and-annotations)
    -   [每个字段注释](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-per-field-annotation)
    -   [每个信件注释](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-per-message-annotation)
    -   [头条注释](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-head-annotation)
    -   [首注"可选"](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-head-annotation-option)
-   [支持的验证框架](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-supported-validation-frameworks)
-   [发展](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-development)
-   [捐款](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-contributing)
-   [许可证](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-license)

## 安装

```sh
npm install @asyncapi/protobuf-schema-parser
# or
yarn add @asyncapi/protobuf-schema-parser
```

`@asyncapi/parser` 要使用此软件包。 需要节点.js `>= 18`。 。 。 .

## 使用量

创建一个 `Parser`,然后分析 AsyncAPI 文档 使用Protobuf软件 `schemaFormat`。Protobuf 源到消息中 `payload` 作为弦.

```ts
import { Parser } from '@asyncapi/parser';
import { ProtoBuffSchemaParser } from '@asyncapi/protobuf-schema-parser';

const parser = new Parser();
parser.registerSchemaParser(ProtoBuffSchemaParser());

const asyncapiWithProto = `
asyncapi: 2.0.0
info:
  title: Example with ProtoBuff
  version: 0.1.0
channels:
  example:
    publish:
      message:
        schemaFormat: 'application/vnd.google.protobuf;version=3'
        payload: |
          message Point {
            required int32 x = 1;
            required int32 y = 2;
            optional string label = 3;
          }

          message Line {
            required Point start = 1;
            required Point end = 2;
            optional string label = 3;
          }
`;

const { document, diagnostics } = await parser.parse(asyncapiWithProto);
```

同样的工作是与CommonJS:

```js
const { Parser } = require('@asyncapi/parser');
const { ProtoBuffSchemaParser } = require('@asyncapi/protobuf-schema-parser');

const parser = new Parser();
parser.registerSchemaParser(ProtoBuffSchemaParser());
```

注释:

-   `ProtoBuffSchemaParser` 既作为命名导出,又作为默认导出。 调用它 获取解析器实例,然后将该实例传递给 `registerSchemaParser`。 。 。 .
-   将您的 Protobuf 计划作为字符串放入信件 `payload` (AsyncAPI 2.x)或者在计划中 对象的 `schema` 关键词( AsyncAPI 3. x) 以获得解析. 见下面的固定装置 [`test/documents`](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/test/documents) 对于两个变体.
-   解析后,信件有效载荷输入 `document` 是已转换的 AsyncAPI 计划.

## 支持的投入

-   **Protobuf 2和Protobuf 3号** 消息定义.
-   两种注册计划格式:
    -   `application/vnd.google.protobuf;version=2`
    -   `application/vnd.google.protobuf;version=3`

参考资料为 **没有** 支持:

-   无支持 `$ref` 在普罗托布夫的有效载荷内.
-   无支持 [`import`](https://protobuf.dev/programming-guides/proto3/#importing-definitions), (中文(简体) ), 除捆绑的知名定义外:
    -   `google/protobuf/*` (以千美元计) `protobufjs`(中文(简体) )
    -   `google/type/*` (与本包捆绑在一起)
    -   审定定义 `validate/validate.proto` 财务报告和审定财务报表 `buf/validate/validate.proto`

任何其他 `import` 解析时丢出错误.

## 如何运作

每个AsyncAPI文件可能包含数个消息有效载荷. 对于每个有效载荷: `schemaFormat` 匹配已注册的 MIME 类型之一,解析器将原始 Protobuf 字符串交给转换器, 用于 [`protobufjs`](https://github.com/protobufjs/protobuf.js) 来分析 然后走 消息树,释放一个基于JSON Schema的 AsyncAPI schema.

因为一个JSON Schema有一个单一的根,转换器首先决定 **根消息**页:1 信件中未被任何其他信件作为字段类型引用。 如果有几个候选人留下来, 注释要用 `@RootNode`; 否则解析失败 `Found more than one root proto messages`。如果找不到根,解析失败 `Not found a root proto messages`。 。 。 .

主要绘图规则:

| Protobuf 构造 | AsyncAPI / JSON Schema 输出 |
| --- | --- |
| `message` | `{ "title": <name>, "type": "object", "properties": { ... } }`外加一个 `required` 列表 |
| 斯卡拉球场(如:. `int32`, (中文(简体) ), `string`(中文(简体) ) | `type` + 键 `format` 从 [平面图](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-scalar-type-formats)附加时 `x-primitive` (和 `minimum`编号 :`maximum` 数字类型) |
| 信件类型字段 | 引用信件已编译入内, + `x-type` 设置为 Protobuf 类型名称 |
| `enum` | `{ "type": "string", "enum": [<names>], "x-enum-mapping": { <name>: <number> } }` |
| `repeated` 字段 | `{ "type": "array", "items": <field schema> }` |
| `oneof` 2名以上成员 | 以 `oneof` 持有 `{ "oneOf": [ ... ] }`; 每种变体携带 `x-oneof-item` 带有字段名称 |
| 字段/ 信件注释 | `description` (与 `@`\- 解开注释 字段注释取代它引用的消息的注释,该注释将移动到 `x-type-description` |

一个球场在 `required` 列表,如果附加了注释 `@Required`,是一种原型2 `required` 字段,或 携带 `required` 规则a [审定框架](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-supported-validation-frameworks)原生的3字段 从来不需要自己, `optional` 否:原型3没有 `required` 标签,和 a 字段中,没有明确存在的字段会从电线和ProtoJSON中省略,当它持有默认值时 数值。 A 类 `required` proto3 文件中的标签无效 proto3; 解析器忽略它并登录警告 命名字段.

递归信件被支持: 当当前两次遇到相同的信件类型时 分支,转换器停止下降以避免无限循环.

非标准`x-`)关键词用于保存没有直接JSON Schema的Protobuf信息 等量: `x-primitive` (原始 scalar 类型), `x-type` (参考消息/enum名称), `x-type-description` (当一个字段注释取代了引用的电文时的评论), `x-enum-mapping` (数字名称为数值),和 `x-oneof-item` (单位:千美元) `oneof` 字段已出现变体 从.

## Scalar 类型格式

每个Protobuf scalar 类型被映射到一个 JSON Schema `type` 加一个 `format` 保留 原始的Protobuf线型. 举个例子 `int64` 变成 `{"type": "integer", "format": "int64"}` 财务报告和审定财务报表 `bytes` 变成 `{"type": "string", "format": "bytes"}`。另外保留了Protobuf型号 非标准 `x-primitive` 关键词 默认数字类型也带有 `minimum`编号 :`maximum` 限制(参见 `primitiveTypesWithLimits` 选项).

## 评论和说明

一个消息的每个字段都可能有一个评论,反应为JSON Schema `description`。 。 。 . 此外,评论还可包含以下说明:

```proto
message Point {
    /*
     * The coordinate on the x axis.
     * @Default 99
     * @Min 0
     * @Max 100
     */
    required int32 x = 1;

    /*
     * The coordinate on the y axis.
     * @Default 12
     * @Min 0
     * @Max 100
     */
    required int32 y = 2;
    optional string label = 3;
}
```

### 每个字段注释

| 注释 | 说明 |
| --- | --- |
| @ 例举 | 杰森·斯克马 `examples` 关键词 可以出现多次。 如果使用复杂类型,必须使用单行JSON对象. |
| @ min 或 @ 最小值 | 杰森·斯克马 [数字验证符](https://json-schema.org/understanding-json-schema/reference/numeric#range) |
| @ max 或 @ Maximum | 杰森·斯克马 [数字验证符](https://json-schema.org/understanding-json-schema/reference/numeric#range) |
| @ 派特尔 | 杰森·斯克马 [字符串验证符](https://json-schema.org/understanding-json-schema/reference/string#regexp) |
| @ exclusive 最小值 | 杰森·斯克马 [数字验证符](https://json-schema.org/understanding-json-schema/reference/numeric#range) |
| @ exclusive Maximum (特写) | 杰森·斯克马 [数字验证符](https://json-schema.org/understanding-json-schema/reference/numeric#range) |
| @ multiplof (多维) | 杰森·斯克马 [数字验证符](https://json-schema.org/understanding-json-schema/reference/numeric#multiples) |
| @ 明伦斯 | 杰森·斯克马 [字符串验证符](https://json-schema.org/understanding-json-schema/reference/string#length) |
| @maxLength (英语) | 杰森·斯克马 [字符串验证符](https://json-schema.org/understanding-json-schema/reference/string#length) |
| @ Min 项目 | 杰森·斯克马 [数组校验符](https://json-schema.org/understanding-json-schema/reference/array#length) |
| @ max 项目 | 杰森·斯克马 [数组校验符](https://json-schema.org/understanding-json-schema/reference/array#length) |
| @ 过失 | 杰森·斯克马 [默认值](https://json-schema.org/understanding-json-schema/reference/annotations) |
| @ required (必须) | 将字段添加到 JSON Schema `required` 列表中选择一个选项。 在原型3,这个和 `required` 规则a [审定框架](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/#readme-supported-validation-frameworks) 是按要求标出字段的唯一方法. |

### 每个信件注释

| 注释 | 说明 |
| --- | --- |
| @ rootNode (英语) | 如果有多个类型没有父目录,您可以通过此注释给根节点提示. |

### 头条注释

| 注释 | 说明 |
| --- | --- |
| @ 选项 | 在您的文件中, 您可以为 parser 设置选项 . |

### 首注"可选"

这个 `@Option` 后面必须有一个空间分隔的选项键和一个空间分隔的值.

```proto
// @Option primitiveTypesWithLimits false

message Point {

}
```

可能的选择是:

| 选项 | 说明 | 默认 |
| --- | --- | :-- |
| 原始Types WithLimits (英语) | 如果您不希望默认 `minimum`编号 :`maximum` 原始类型限制,设置此选项为 `false`。 。 。 . | 真实 |

## 支持的验证框架

如果您想要在您的原始文件中添加额外的验证, 您可以使用以下其中之一 : 验证框架。 他们的规则翻译为 JSON Schema 验证关键词 解析.

-   [原型验证](https://github.com/bufbuild/protoc-gen-validate) 清单的验证不是 百分之百的支持.
-   [缩写](https://github.com/bufbuild/protovalidate)

这个 `required` 任意框架的规则将字段添加到 JSON Schema `required` 列表 : `(buf.validate.field).required = true`,或 `(validate.rules).<type>.required = true` 类型 `message`, (中文(简体) ), `duration`, (中文(简体) ), `timestamp` 财务报告和审定财务报表 `any`。 。 。 .

## 发展

这个项目用 TypeScript 写成,并同时构建一个ES模块(`esm/`)和一个共同JS(`cjs/`(中文(简体) ) 输出。 测试使用情况 [欢乐](https://jestjs.io/) 与快照式固定装置相对应 `test/documents`。 。 。 .

```sh
npm install          # install dependencies

npm run build        # build both esm/ and cjs/ (build:esm, build:cjs)
npm test             # run the Jest test suite with coverage
npm run lint         # run ESLint (use lint:fix to auto-fix)
```

来源布局 :

| 路径 | 目的 |
| --- | --- |
| `src/index.ts` | 解析器工厂; 执行 `@asyncapi/parser` 计划-parser合同(`parse`, (中文(简体) ), `validate`, (中文(简体) ), `getMimeTypes`) (中文(简体) ). |
| `src/protoj2jsonSchema.ts` | 将Protobuf schema转化为AsyncAPI schema的核心转换器. |
| `src/primitive-types.ts` | Scalar Protobuf 类型为 JSON Schema `type`编号 :`format` 地图. |
| `src/google-types.ts` | 捆绑 `google/type/*` 众所周知的定义. |
| `src/pathUtils.ts` | 导入路径解析器 . |
| `src/protoc-gen-validate.ts` | 地图 `(validate.rules)` 选项. |
| `src/protovalidate.ts` | 地图 `(buf.validate.field)` 选项. |
| `test/documents/*.yaml` | AsyncAPI 输入固定装置; `*.result.json` 是预期的解析产出. |

## 捐款

读取 [捐款](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/CONTRIBUTING.md) 了解贡献过程和AsyncAPI [行为守则](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/CODE_OF_CONDUCT.md)欢迎提出问题和拉动请求.

## 许可证

[阿帕奇 - 2.0](https://npmcn.com/package/%40asyncapi/protobuf-schema-parser/LICENSE)

## 常见问题

### @asyncapi/protobuf-schema-parser 是什么？

用于协议缓冲数据类型的 AsyncAPI schema 解析器 \.

### 如何安装 @asyncapi/protobuf-schema-parser？

在项目目录运行 npm install @asyncapi/protobuf-schema-parser，或使用 pnpm add / yarn add / bun add。

### @asyncapi/protobuf-schema-parser 支持 TypeScript 吗？

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

### @asyncapi/protobuf-schema-parser 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @asyncapi/protobuf-schema-parser 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=18。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @asyncapi/protobuf-schema-parser 可以商用吗？

@asyncapi/protobuf-schema-parser 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @asyncapi/protobuf-schema-parser 的下载量有多少？

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

### @asyncapi/protobuf-schema-parser 还在维护吗？

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

