@cdxgen/cdx-proto

中文文档
2.3.0发布于 2026/09/20MITTypeScriptES Module构建来源已验证近 30 天下载 72万

Library to serialize/deserialize CycloneDX BOM with protocol buffers

原始使用文档
文档目录8 节
  1. 2.0.0 highlights
  2. Sample usage
  3. Helper API
  4. Canonical JSON guarantees
  5. Version-specific imports
  6. Node-only file helpers
  7. CLI
  8. License

cdx-proto

Runtime library to serialize/deserialize CycloneDX BOM with protocol buffers. The project was generated using protoc-gen-es from the official proto specification.

2.0.0 highlights

  • version-specific subpath exports: @cdxgen/cdx-proto/v1.5, v1.6, and v1.7
  • helper APIs for schema selection and BOM encode/decode workflows
  • leaner npm package contents that no longer publish generated docs/

Sample usage

import {
  createBom,
  decodeBomBinary,
  encodeBomBinary,
  encodeBomJson,
  getBomSchema,
  parseBomJson,
} from "@cdxgen/cdx-proto";
import { BomSchema as BomSchema16 } from "@cdxgen/cdx-proto/v1.6";
import { fromJson } from "@bufbuild/protobuf";

// Use version-specific entrypoints when you only need one schema version.
const bom16 = fromJson(BomSchema16, {
  specVersion: "1.6",
  version: 1,
});

// Or use the helper API to auto-select schemas and encode/decode BOMs.
const bom = createBom("1.7", {
  version: 1,
  serialNumber: "urn:uuid:11111111-1111-1111-1111-111111111111",
});

const binary = encodeBomBinary(bom, {
  writeUnknownFields: true,
});

const decoded = decodeBomBinary("1.7", binary, {
  readUnknownFields: true,
});

const json = encodeBomJson(decoded, {
  alwaysEmitImplicit: true,
});

const parsed = parseBomJson({
  specVersion: "1.6",
  version: 1,
});

const schema = getBomSchema(parsed.specVersion);

Helper API

  • getBomSchema(specVersion) returns the matching BomSchema for CycloneDX 1.5, 1.6, or 1.7.
  • createBom(specVersion, init) creates a BOM message and automatically sets specVersion.
  • parseBomJson(json) and parseBomJsonString(json) auto-detect the schema from specVersion / spec_version.
  • decodeBomBinary(specVersion, bytes) decodes a protobuf BOM when the schema version is known.
  • encodeBomBinary(bom), encodeBomJson(bom), and encodeBomJsonString(bom) choose the correct schema from the BOM itself.
  • toBomMessage(value, specVersion?, options?) is the single entry point for "turn whatever I have into a BOM message": decoded messages pass through (see isBomMessage), JSON strings are parsed, canonical JSON objects are dispatched by embedded version (or the fallback version, which defaults to the latest supported), and absent input yields an empty BOM. This replaces the input-dispatch re-implementations consumers previously carried.
  • isBomMessage(value) is a type guard for a decoded BOM message of any supported spec version, keyed on $typeName rather than duck-typed shape.
  • convertBom(bom, targetSpecVersion) cross-converts between spec versions. Returns { bom, warnings } where warnings lists field paths dropped during a lossy downgrade. Fields that change cardinality between versions (metadata.licenses and components[].evidence.identity, singular in 1.5 and an array since 1.6) are reshaped automatically — wrapped on upgrade, collapsed to their first entry on downgrade with the dropped siblings reported in warnings — so conversions across the 1.5/1.6 boundary no longer throw. Upgrades typically produce no warnings.
  • bomStats(bom) returns component/dependency counts and JSON/binary byte sizes with the compression ratio.
  • detectBomSpecVersion(value) reads the spec version from a BOM object or message.
  • normalizeSpecVersion(specVersion) normalizes "v1.6", 1.6, and "1.6.0" spellings to a canonical supported version, throwing for anything else; isSupportedSpecVersion(value) is its non-throwing probe.
  • encodeBomBase64(bom) produces a base64 string of the protobuf binary, for contexts that cannot carry raw bytes (OCI labels, in-toto predicates, environment variables). decodeBomBase64(specVersion, string) decodes with a known version and parseBomBase64(string) auto-detects it, mirroring the binary helpers.

Canonical JSON guarantees

The helper layer is designed to work with canonical CycloneDX JSON rather than protobuf-flavored JSON.

  • parseBomJson() and decodeBomJson() accept canonical CycloneDX input such as:
    • root fields like bomFormat and specVersion
    • dashed aliases such as bom-ref, mime-type, and x-trust-boundary
    • canonical hash content fields like hashes[].content
    • canonical standards/declarations objects instead of protobuf list wrappers
  • Undefined object properties and undefined array entries are sanitized before protobuf parsing so callers can pass ordinary JavaScript objects without manually stripping undefined values first.
  • encodeBomJson() and encodeBomJsonString() restore canonical CycloneDX JSON on output, including:
    • bomFormat: "CycloneDX"
    • the BOM specVersion
    • canonical enum values instead of protobuf enum names such as CLASSIFICATION_*, HASH_ALG_*, or EXTERNAL_REFERENCE_TYPE_*
    • canonical object shapes for definitions and declarations
    • flat dependencies[].dependsOn: string[] instead of the protobuf nested dependencies tree (see below)
  • parseBomBinary() auto-detects the embedded supported schema version (1.5, 1.6, or 1.7) and can be paired with encodeBomJson() to read protobuf BOMs back as canonical CycloneDX JSON.

Corrected proto field names, and interop with tools that use the released ones

Three fields are named differently in the released CycloneDX protobuf schemas than in the CycloneDX JSON schema they are supposed to mirror. The schemas vendored here correct all three, so a protobuf BOM produced by this library uses the same names as its JSON counterpart:

version(s)released proto namecorrected proto namecanonical JSON
1.6, 1.7postalCodeuepostalCodepostalCode
1.5, 1.6, 1.7graphiccollectioncollection
1.6, 1.7cryptoRefcryptoRefArraycryptoRefArray

Interoperability is preserved in both directions:

  • Binary needs no special handling. Every field number is unchanged, so the wire format is byte-identical whichever schema produced it.
  • Both JSON spellings are accepted on input. Protobuf-JSON emitted by a tool generated from a released schema still uses the old names, so those decode too. Output always uses the canonical JSON name.

If you read these fields directly off a typed message (cdx_16.*, cdx_17.*) rather than through the canonical JSON helpers, use the corrected names.

Dependency graph bridging

Canonical CycloneDX JSON expresses the dependency graph as a flat array of { ref, dependsOn: [ref, ...], provides: [ref, ...] } entries. The protobuf mirrors the XML model and nests children as repeated Dependency dependencies, so without this library's bridge the dependsOn key is unknown to protobuf-es and is either rejected (default options) or silently dropped (ignoreUnknownFields: true), which empties the dependency graph.

The helper layer converts between the two forms automatically:

  • JSON -> protobuf: each dependsOn string becomes a nested { ref } child under dependencies. Already-proto-shaped dependencies arrays and mixed arrays of strings/objects are also accepted.
  • protobuf -> JSON: nested dependencies are flattened back into dependsOn. If a nested entry carries its own edges (its own dependencies or provides), it is hoisted to a sibling top-level entry so transitive edges are never lost. Entries are de-duplicated by ref.

In short: if you provide canonical CycloneDX JSON to the helper API, you should get canonical CycloneDX JSON back after binary or message round-trips.

Version-specific imports

Use subpath exports to avoid loading schema versions you do not need:

import { BomSchema as BomSchema15 } from "@cdxgen/cdx-proto/v1.5";
import { BomSchema as BomSchema16 } from "@cdxgen/cdx-proto/v1.6";
import { BomSchema as BomSchema17 } from "@cdxgen/cdx-proto/v1.7";

Node-only file helpers

@cdxgen/cdx-proto/node adds filesystem convenience wrappers without polluting the main (browser-safe) entry with node: imports:

import {
  isProtoBomFile,
  readBomFile,
  writeBomFile,
} from "@cdxgen/cdx-proto/node";

// Format is auto-detected from the extension: `.json` for canonical JSON,
// `.b64`/`.base64` for base64 protobuf payloads, and anything else
// (`.cdx`, `.cdx.bin`, `.proto`, `.bin`, ...) as raw protobuf binary.
const bom = readBomFile("bom.cdx");
const bomJson = readBomFile("bom.cdx", { asJson: true });

writeBomFile("bom.json", bom); // pretty canonical JSON
writeBomFile("bom.cdx", bomJson); // coerced back to a message, then binary
writeBomFile("bom.b64", bom); // base64 protobuf payload

isProtoBomFile("bom.CDX.BIN"); // true — the extension list lives here once

CLI

The package ships a zero-dependency cdx-proto CLI for converting, inspecting, and validating BOMs from the shell. The format is auto-detected by file extension (.json for canonical JSON, .b64/.base64 for base64 protobuf, anything else for protobuf binary).

# Convert JSON to protobuf binary (~2x smaller for typical BOMs)
npx cdx-proto convert bom.json bom.bin

# Downgrade a 1.7 BOM to 1.5, warning about dropped fields
npx cdx-proto convert bom.json bom-1.5.json --to 1.5

# Convert to a base64 payload for embedding in labels or predicates
npx cdx-proto convert bom.json bom.b64

# Inspect component/dependency counts and byte sizes
npx cdx-proto inspect bom.bin

# Validate that a file parses cleanly
npx cdx-proto validate bom.json

License

MIT

版本与发布记录

@cdxgen/cdx-proto 共发布 5 个版本,首次发布于 2026/06/08;过去 12 个月发布了 5 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.3.0latest2026/09/201 个月前
2.2.02026/08/112 个月前
2.1.02026/08/063 个月前
2.0.32026/06/085 个月前
2.0.22026/06/085 个月前

关于 @cdxgen/cdx-proto 的常见问题

@cdxgen/cdx-proto 是什么?

Library to serialize/deserialize CycloneDX BOM with protocol buffers

如何安装 @cdxgen/cdx-proto?

在项目目录运行 npm install @cdxgen/cdx-proto,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 cdx-proto,可以用 npx cdx-proto 直接运行。

@cdxgen/cdx-proto 支持 TypeScript 吗?

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

@cdxgen/cdx-proto 支持 ESM 还是 CommonJS?

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

@cdxgen/cdx-proto 需要什么版本的 Node.js?

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

@cdxgen/cdx-proto 可以商用吗?

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

@cdxgen/cdx-proto 的下载量有多少?

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

@cdxgen/cdx-proto 还在维护吗?

最新版本 2.3.0 发布于 2026/09/20(1 个月前);至今共发布 5 个版本,其中过去 12 个月发布了 5 个;首次发布于 2026/06/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。