core

core

热门

用于定义模式、目录和AI提示生成的核心包,适用于@json-render/core,定义模式、创建目录或构建用于UI/视频生成的JSON规范。

1.6万Star
849Fork
更新于 2026/7/8
SKILL.md
readonly只读
name
core
description

Core package for defining schemas, catalogs, and AI prompt generation for json-render. Use when working with @json-render/core, defining schemas, creating catalogs, or building JSON specs for UI/video generation.

@json-render/core

用于模式定义、目录创建和规范流式处理的核心包。

关键概念

  • Schema(模式):定义规范和目录的结构(使用 defineSchema
  • Catalog(目录):将组件/动作名称映射到其定义(使用 defineCatalog
  • Spec(规范):AI输出的符合模式的JSON
  • SpecStream(规范流):用于渐进式规范构建的JSONL流格式

定义模式

import { defineSchema } from "@json-render/core";

export const schema = defineSchema((s) => ({
  spec: s.object({
    // 定义规范结构
  }),
  catalog: s.object({
    components: s.map({
      props: s.zod(),
      description: s.string(),
    }),
  }),
}), {
  promptTemplate: myPromptTemplate, // 可选的自定义AI提示
});

创建目录

import { defineCatalog } from "@json-render/core";
import { schema } from "./schema";
import { z } from "zod";

export const catalog = defineCatalog(schema, {
  components: {
    Button: {
      props: z.object({
        label: z.string(),
        variant: z.enum(["primary", "secondary"]).nullable(),
      }),
      description: "可点击的按钮组件",
    },
  },
});

生成AI提示

const systemPrompt = catalog.prompt(); // 使用模式的 promptTemplate
const systemPrompt = catalog.prompt({ customRules: ["规则1", "规则2"] });

SpecStream 工具函数

用于流式AI响应(JSONL补丁):

import { createSpecStreamCompiler } from "@json-render/core";

const compiler = createSpecStreamCompiler<MySpec>();

// 处理流式块
const { result, newPatches } = compiler.push(chunk);

// 获取最终结果
const finalSpec = compiler.getResult();

动态属性表达式

任何属性值都可以是在渲染时解析的动态表达式:

  • { "$state": "/state/key" } - 从状态模型中读取值(单向读取)
  • { "$bindState": "/path" } - 双向绑定:从状态读取并允许写回。用于表单组件的自然值属性(value、checked、pressed等)。
  • { "$bindItem": "field" } - 双向绑定到重复项字段。在重复作用域内使用。
  • { "$cond": <condition>, "$then": <value>, "$else": <value> } - 评估可见性条件并选择一个分支
  • { "$template": "Hello, ${/user/name}!" } - 将 ${/path} 引用与状态值插值
  • { "$computed": "fnName", "args": { "key": <expression> } } - 使用解析后的参数调用注册函数

$cond 使用与可见性条件相同的语法($stateeqneqnot、数组表示AND)。$then$else 本身可以是表达式(递归)。

组件不使用 statePath 属性进行双向绑定。相反,在自然值属性(例如 valuecheckedpressed)上使用 { "$bindState": "/path" }

{
  "color": {
    "$cond": { "$state": "/activeTab", "eq": "home" },
    "$then": "#007AFF",
    "$else": "#8E8E93"
  },
  "label": { "$template": "Welcome, ${/user/name}!" },
  "fullName": {
    "$computed": "fullName",
    "args": {
      "first": { "$state": "/form/firstName" },
      "last": { "$state": "/form/lastName" }
    }
  }
}
import { resolvePropValue, resolveElementProps } from "@json-render/core";

const resolved = resolveElementProps(element.props, { stateModel: myState });

状态监听器

元素可以声明 watch 字段(顶层,与 type/props/children 同级),以在状态值变化时触发动作:

{
  "type": "Select",
  "props": { "value": { "$bindState": "/form/country" }, "options": ["US", "Canada"] },
  "watch": {
    "/form/country": { "action": "loadCities", "params": { "country": { "$state": "/form/country" } } }
  },
  "children": []
}

监听器仅在值变化时触发,不在初始渲染时触发。

验证

内置验证函数:requiredemailurlnumericminLengthmaxLengthminmaxpatternmatchesequalTolessThangreaterThanrequiredIf

跨字段验证使用参数中的 $state 表达式:

import { check } from "@json-render/core";

check.required("字段必填");
check.matches("/form/password", "密码必须匹配");
check.lessThan("/form/endDate", "必须在结束日期之前");
check.greaterThan("/form/startDate", "必须在开始日期之后");
check.requiredIf("/form/enableNotifications", "启用时必填");

用户提示构建器

构建结构化的用户提示,支持可选的规范细化和状态上下文:

import { buildUserPrompt } from "@json-render/core";

// 全新生成
buildUserPrompt({ prompt: "创建一个待办事项应用" });

// 带编辑模式的细化(默认:仅补丁)
buildUserPrompt({ prompt: "添加一个开关", currentSpec: spec, editModes: ["patch", "merge"] });

// 带运行时状态
buildUserPrompt({ prompt: "显示数据", state: { todos: [] } });

可用的编辑模式:"patch"(RFC 6902 JSON Patch)、"merge"(RFC 7396 Merge Patch)、"diff"(统一差异)。

规范验证

验证规范结构并自动修复常见问题:

import { validateSpec, autoFixSpec } from "@json-render/core";

const { valid, issues } = validateSpec(spec);
// issues 包括:missing_child、invalid_visible(格式错误的条件)、
// repeat_without_children、repeat_state_mismatch(statePath 在状态中不是数组)

const { spec: fixed, fixDetails } = autoFixSpec(spec);
// fixDetails 条目为 { message, lossy }。无损修复会重新定位
// 错位的字段;有损修复会修剪悬空的子引用。
// 在修复循环中,在重试耗尽之前保留有损修复:
const attempt = autoFixSpec(spec, { lossy: retriesExhausted });

可见性条件

使用基于状态的条件控制元素可见性。VisibilityContext{ stateModel: StateModel }

import { visibility } from "@json-render/core";

// 语法
{ "$state": "/path" }                    // 真值
{ "$state": "/path", "not": true }      // 假值
{ "$state": "/path", "eq": value }      // 相等
[ cond1, cond2 ]                         // 隐式 AND

// 辅助函数
visibility.when("/path")                 // { $state: "/path" }
visibility.unless("/path")               // { $state: "/path", not: true }
visibility.eq("/path", val)              // { $state: "/path", eq: val }
visibility.and(cond1, cond2)             // { $and: [cond1, cond2] }
visibility.or(cond1, cond2)              // { $or: [cond1, cond2] }
visibility.always                        // true
visibility.never                         // false

模式中的内置动作

模式可以声明 builtInActions —— 在运行时始终可用并自动注入到提示中的动作:

const schema = defineSchema(builder, {
  builtInActions: [
    { name: "setState", description: "更新状态模型中的值" },
  ],
});

这些在提示中显示为 [built-in],不需要在 defineRegistry 中定义处理程序。

StateStore

StateStore 接口允许外部状态管理库(Redux、Zustand、XState 等)接入 json-render 渲染器。createStateStore 工厂创建一个简单的内存实现:

import { createStateStore, type StateStore } from "@json-render/core";

const store = createStateStore({ count: 0 });

store.get("/count");         // 0
store.set("/count", 1);      // 更新并通知订阅者
store.update({ "/a": 1, "/b": 2 }); // 批量更新

store.subscribe(() => {
  console.log(store.getSnapshot()); // { count: 1 }
});

StateStore 接口:get(path)set(path, value)update(updates)getSnapshot()subscribe(listener)

关键导出

导出 用途
defineSchema 创建新模式
defineCatalog 从模式创建目录
createStateStore 创建框架无关的内存 StateStore
resolvePropValue 针对数据解析单个属性表达式
resolveElementProps 解析元素中的所有属性表达式
buildUserPrompt 构建带细化和状态上下文的用户提示
buildEditUserPrompt 构建用于编辑现有规范的用户提示
buildEditInstructions 生成可用编辑模式的提示部分
isNonEmptySpec 检查规范是否有根和至少一个元素
deepMergeSpec RFC 7396 深度合并(null 删除,数组替换,对象递归)
diffToPatches 从对象差异生成 RFC 6902 JSON Patch 操作
EditMode 类型:"patch" | "merge" | "diff"
validateSpec 验证规范结构
autoFixSpec 自动修复常见规范问题;将修复分类为有损/无损,{ lossy: false } 保留修剪
createSpecStreamCompiler 将 JSONL 补丁流式编译为规范
createJsonRenderTransform 在混合流中分离文本和 JSONL 的 TransformStream
parseSpecStreamLine 解析单行 JSONL
applySpecStreamPatch 将补丁应用到对象
StateStore 用于接入外部状态管理的接口
ComputedFunction $computed 表达式的函数签名
check 用于创建验证检查的 TypeScript 辅助函数
BuiltInAction 内置动作定义的类型(name + description
ActionBinding 动作绑定类型(包含 preventDefault 字段)