关于 json-render-core
@json-render/core 为 json-render 提供模式、目录和规范流处理能力,面向定义 AI 生成界面结构的开发者。它还包含动态属性解析、验证及可接入外部状态管理的存储接口。
主要功能
- 01定义模式与组件目录
- 02生成 AI 提示词
- 03流式解析 JSONL 规范补丁
- 04解析状态驱动的动态属性
- 05验证并自动修复规范
- 06提供可插拔状态存储接口
适用场景
- 01为 AI 生成界面定义数据结构
- 02逐步处理流式规范输出
- 03验证或修复生成的规范
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ vercel-labs/ json-render --skill json-render-core安装后在 Claude Code 中输入/json-render-core确认已加载。
详细介绍
@json-render/core
用于定义 Schema、创建目录和流式传输规范的核心包。
核心概念
- Schema:定义规范和目录的结构(使用
defineSchema) - 目录:将组件/操作名称映射到其定义(使用
defineCatalog) - 规范:符合 Schema 的 AI JSON 输出
- SpecStream:用于渐进式构建规范的 JSONL 流式传输格式
定义 Schema
import { defineSchema } from "@json-render/core";
export const schema = defineSchema((s) => ({
spec: s.object({
// Define spec structure
}),
catalog: s.object({
components: s.map({
props: s.zod(),
description: s.string(),
}),
}),
}), {
promptTemplate: myPromptTemplate, // Optional custom AI prompt
});
创建目录
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: "Clickable button component",
},
},
});
生成 AI 提示词
const systemPrompt = catalog.prompt(); // Uses schema's promptTemplate
const systemPrompt = catalog.prompt({ customRules: ["Rule 1", "Rule 2"] });
SpecStream 实用工具
用于流式传输 AI 响应(JSONL 补丁):
import { createSpecStreamCompiler } from "@json-render/core";
const compiler = createSpecStreamCompiler<MySpec>();
// Process streaming chunks
const { result, newPatches } = compiler.push(chunk);
// Get final result
const finalSpec = compiler.getResult();
动态 Prop 表达式
任何 prop 值都可以是一个在渲染时求值的动态表达式:
{ "$state": "/state/key" }- 从状态模型读取值(单向读取){ "$bindState": "/path" }- 双向绑定:从状态读取并支持写回。用于表单组件的自然值 prop(value、checked、pressed 等)。{ "$bindItem": "field" }- 双向绑定到重复项字段。用于重复作用域内。{ "$cond": <condition>, "$then": <value>, "$else": <value> }- 对可见性条件求值并选择一个分支{ "$template": "Hello, ${/user/name}!" }- 使用状态值插入${/path}引用{ "$computed": "fnName", "args": { "key": <expression> } }- 使用解析后的参数调用已注册函数
$cond 使用与可见性条件相同的语法($state、eq、neq、not,以及表示 AND 的数组)。$then 和 $else 本身也可以是表达式(递归求值)。
组件不使用 statePath prop 进行双向绑定。请改为在自然值 prop(例如 value、checked、pressed)上使用 { "$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": []
}
监听器仅在值发生变化时触发,不会在初次渲染时触发。
验证
内置验证函数:required、email、url、numeric、minLength、maxLength、min、max、pattern、matches、equalTo、lessThan、greaterThan、requiredIf。
跨字段验证会在参数中使用 $state 表达式:
import { check } from "@json-render/core";
check.required("Field is required");
check.matches("/form/password", "Passwords must match");
check.lessThan("/form/endDate", "Must be before end date");
check.greaterThan("/form/startDate", "Must be after start date");
check.requiredIf("/form/enableNotifications", "Required when enabled");
用户提示词构建器
构建结构化的用户提示词,并可选择优化规范和添加状态上下文:
import { buildUserPrompt } from "@json-render/core";
// Fresh generation
buildUserPrompt({ prompt: "create a todo app" });
// Refinement (patch-only mode)
buildUserPrompt({ prompt: "add a toggle", currentSpec: spec });
// With runtime state
buildUserPrompt({ prompt: "show data", state: { todos: [] } });
规范验证
验证规范结构并自动修复常见问题:
import { validateSpec, autoFixSpec } from "@json-render/core";
const { valid, issues } = validateSpec(spec);
const fixed = autoFixSpec(spec);
可见性条件
使用基于状态的条件控制元素可见性。VisibilityContext 为 { stateModel: StateModel }。
import { visibility } from "@json-render/core";
// Syntax
{ "$state": "/path" } // truthiness
{ "$state": "/path", "not": true } // falsy
{ "$state": "/path", "eq": value } // equality
[ cond1, cond2 ] // implicit AND
// Helpers
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
Schema 中的内置操作
Schema 可以声明 builtInActions——这些操作在运行时始终可用,并会自动注入提示词:
const schema = defineSchema(builder, {
builtInActions: [
{ name: "setState", description: "Update a value in the state model" },
],
});
这些操作会在提示词中显示为 [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); // updates and notifies subscribers
store.update({ "/a": 1, "/b": 2 }); // batch update
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 | 构建包含细化内容和状态上下文的用户提示词 |
validateSpec | 验证规范结构 |
autoFixSpec | 自动修复常见的规范问题 |
createSpecStreamCompiler | 将 JSONL 补丁流式编译到规范中 |
createJsonRenderTransform | 创建 TransformStream,将混合流中的文本与 JSONL 分离 |
parseSpecStreamLine | 解析单行 JSONL |
applySpecStreamPatch | 将补丁应用到对象 |
StateStore | 用于接入外部状态管理的接口 |
ComputedFunction | $computed 表达式的函数签名 |
check | 用于创建验证检查项的 TypeScript 辅助函数 |
BuiltInAction | 内置操作定义的类型(name + description) |
ActionBinding | 操作绑定类型(包含 preventDefault 字段) |