@a2ui/web_core

中文文档
0.15.0发布于 2026/11/02Apache-2.0TypeScriptES Module近 30 天下载 389.5万

A2UI Core Library

原始使用文档
文档目录11 节
  1. Features
  2. Architecture
  3. Schema & Code Generation
  4. Running Code Generation
  5. Catalog Schema Contract
  6. Catalog Serialization
  7. Specification annotations
  8. Development
  9. Building
  10. Testing
  11. Formatting & Linting

@a2ui/web_core

The @a2ui/web_core package provides state management, protocol parsing, and schema generation for the A2UI framework. It is framework-agnostic and provides the foundational engine for renderer packages such as Angular, React, and Lit.

Features

  • Protocol Handling: Implements A2UI specification message validation and state handling across all supported protocol versions.
  • State Management: Reactive data and component models using @preact/signals-core.
  • DataContext: Data binding, scoping, and function evaluation with dependency tracking.
  • Catalog System: Component and function catalogs supporting runtime validation and schema generation.
  • Schema-Driven Code Generation: Auto-generates Zod schemas and TypeScript component/function definitions directly from specification JSON schemas.

Architecture

Rendering is driven by a SurfaceGroupModel and its constituent SurfaceModel instances, with DataModel managing reactive state, DataContext providing expression evaluation, and MessageProcessor validating and applying incoming protocol messages.

Schema & Code Generation

Protocol message schemas, common types, and catalog definitions are generated directly from the JSON schemas in the specification/ directory.

Running Code Generation

To regenerate all Zod schemas and catalog APIs:

# Generate all protocol Zod schemas and versioned Basic Catalog APIs
yarn generate-zod-schemas

# Or run individual version generators directly
node src/v0_9/scripts/generate-catalog.mjs
node src/v1_0/scripts/generate-catalog.mjs

Catalog Schema Contract

The code generator uses Schema Flattening to remain version-, catalog-, and type-agnostic. Schema files adhere to the following structure:

1. Catalog JSON (catalog.json)

  • Top-Level Dictionaries:
    • components: Maps component names to JSON schema objects.
    • functions: Maps function names to JSON schema objects.
  • Discriminator:
    • Derived from catalog.discriminator.propertyName (defaults to "component").
    • The discriminator property and "id" are omitted from generated property schemas as they are handled by the runtime component envelope.
  • Inheritance & Envelopes:
    • Components may use allOf to reference common envelopes (such as ComponentCommon or CatalogComponentCommon). The generator recursively resolves $ref pointers and merges allOf branches into a flat property bag.
  • Functions:
    • Functions specify a returnType (e.g. "string", "number", "boolean", "validationResult") at the root level and define arguments inside an args or parameters object property.

2. Reusable Type Definitions (common_types.json)

  • $defs Scope:
    • Reusable type schemas reside under $defs. Definition names are not hardcoded; any definition present in $defs is resolved dynamically when referenced.
  • Reference Annotations:
    • When a component property references $defs/<DefName>, the generator maps it to <DefName>Schema and attaches a .describe('REF:#/$defs/<DefName>|<description>') annotation.
    • At runtime, generateValidationSchema inspects these markers to emit $ref pointers and tree-shake unused $defs definitions.
  • Child References:
    • Single child references and child collections are identified when their $defs reference targets or descriptions indicate a child component relationship (such as references to ComponentId, Child, or ChildList).

Catalog Serialization

A Catalog has three serialization entry points:

  • Catalog.fromJson(json, protocolVersion?, catalogId?) loads a catalog document into the catalog's model. Each entry is a JsonComponentApi or JsonFunctionApi whose model is its JSON Schema definition as written (jsonSchema); its Zod schema is derived from the definition on first use. The catalog keeps the document-level fields (metadata, named $defs, other top-level keys). protocolVersion, when given, takes precedence over the version the document declares and selects the loading rules, while toJson still writes the document's own protocolVersion; without it the document's version applies, then DEFAULT_PROTOCOL_VERSION. catalogId replaces the document's own ID.
  • catalog.toJson() assembles the unbundled catalog document from the model, computing the anyComponent and anyFunction unions. A catalog loaded with fromJson returns its document unchanged (minus any entries omitted from the document's anyComponent.oneOf or anyFunction.oneOf unions, which fromJson filters out on load). An entry defined in code whose Zod schema is annotated with spec() has its definition computed from the model in the layout of the catalog's protocol version; any other entry defined in code is generated from its Zod schema. The result is computed once per catalog; each call returns a fresh copy.
  • catalog.validationSchema is the self-contained schema used to validate payloads: common types and the catalog's own $defs are bundled into $defs and every $ref is local. It is computed once per catalog; each read returns a fresh copy.
import {Catalog} from '@a2ui/web_core';

const catalog = Catalog.fromJson(document);
const unchanged = catalog.toJson(); // deep-equals document
const schema = catalog.validationSchema; // bundled JSON Schema

The Catalog constructor takes a CatalogOptions object as its fifth argument, with the themeSchema, the document-level fields (instructions, schemaUri, schemaId, title, description, declaredProtocolVersion, declaresCatalogId, declaresComponents, functionsLayout, unions, defs, extensionFields) that toJson emits, and, for a catalog defined in code, commonTypesUri, themeLocation and defModels. catalog.withEntries(components, functions) returns a catalog with the same fields and other entries, as catalog transformers need.

catalog.derive(options) returns a new catalog under its own id, built from entries of catalog and new ones. In components and functions, a name keeps the entry of that name and an object adds an entry. The new catalog does not keep the source's $id, title, description or instructions, since the instructions of the basic catalog, for example, name its id in their examples:

const chatCatalog = basicCatalog.derive({
  catalogId: 'https://example.com/catalogs/chat.json',
  components: ['Text', 'Image', 'Row', 'Column', 'Button', carousel],
  functions: ['openUrl'],
  instructions,
});

Specification annotations

spec(schema, annotation) returns a copy of a Zod schema that records what a catalog document writes about it beyond the schema itself, without changing validation: mixins (the common types, such as 'ComponentCommon', and the specDef() models a component's definition composes with allOf), closure (additionalProperties or unevaluatedProperties), required (the order of the required list), allOf (schemas that follow the schema's own, such as a format rule) and keywords (such as format). specDef(name, schema) names a model that the document declares under $defs. The descriptions come from .describe(), and common types references from REF:#/$defs/<Name> description markers.

import {Catalog, spec, specDef} from '@a2ui/web_core/catalog';
import {z} from 'zod';

const Common = specDef('Common', z.object({weight: z.number().optional()}));
const Badge = {
  name: 'Badge',
  schema: spec(
    z
      .object({...Common.shape, label: z.string()})
      .describe('A badge.')
      .strict(),
    {mixins: ['ComponentCommon', Common]},
  ),
};
// Badge's definition composes ComponentCommon and #/$defs/Common with allOf,
// and $defs.Common is computed from the Common model.
const document = new Catalog('https://example.com/badges', '0.9', [Badge]).toJson();

The built-in basic catalogs are built this way. Their components and functions are Zod models generated from the published catalog documents by scripts/generate-catalog-schemas.mjs (v0.9 and v1) and src/v0_8/scripts/generate-catalog.mjs (v0.8), which run as part of yarn generate-zod-schemas. For every schema node, the generator predicts the JSON Schema that toJson derives from the Zod code it emits, and annotates the node with the difference from the published schema. toJson of each basic catalog computes its published document from the models; no copy of the document is kept in the package.

Development

Building

The package uses wireit for build orchestration:

yarn build

Testing

Run unit tests:

yarn test

Run conformance test suite:

node tests/conformance/conformance_test.mjs

Run the timing cases of conformance/core/message_processor_scaling.yaml, which check that processing a surface sent in many small messages takes time in proportion to its size. Times depend on the machine and its load, so yarn test leaves these cases out:

yarn test:timing

Formatting & Linting

yarn format
yarn lint

版本与发布记录

@a2ui/web_core 共发布 22 个版本,首次发布于 2026/03/05;过去 12 个月发布了 22 个版本。

版本发布日期距今
0.15.0latest2026/11/024 天前
0.14.02026/10/1720 天前
0.13.02026/10/1027 天前
0.12.02026/09/291 个月前
0.11.02026/09/121 个月前
0.10.72026/09/012 个月前

关于 @a2ui/web_core 的常见问题

@a2ui/web_core 是什么?

A2UI Core Library

如何安装 @a2ui/web_core?

在项目目录运行 npm install @a2ui/web_core,或使用 pnpm add / yarn add / bun add。

@a2ui/web_core 支持 TypeScript 吗?

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

@a2ui/web_core 支持 ESM 还是 CommonJS?

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

@a2ui/web_core 可以商用吗?

@a2ui/web_core 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@a2ui/web_core 的下载量有多少?

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

@a2ui/web_core 还在维护吗?

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