Skip to content

The Open Standard for Generative UI

feat(lang-core): add jsonToOpenUI serializer for ElementNode → openui-lang conversion (#471)

Subham Dasac414abfd7c8
diff --git a/packages/lang-core/package.json b/packages/lang-core/package.json
index 3ad55f7c2..b3ff238cf 100644
--- a/packages/lang-core/package.json
+++ b/packages/lang-core/package.json
@@ -1,6 +1,6 @@
{
"name": "@openuidev/lang-core",
- "version": "0.2.3",
+ "version": "0.2.4",
"description": "Framework-agnostic core for OpenUI Lang: parser, prompt generation, validation, and type definitions",
"license": "MIT",
"type": "module",
diff --git a/packages/lang-core/src/index.ts b/packages/lang-core/src/index.ts
index 561d6b3e1..bb40ad57e 100644
--- a/packages/lang-core/src/index.ts
+++ b/packages/lang-core/src/index.ts
@@ -31,6 +31,8 @@ export { enrichErrors } from "./parser/enrich-errors";
export { mergeStatements } from "./parser/merge";
export { generatePrompt } from "./parser/prompt";
export type { ComponentPromptSpec, PromptSpec, ToolSpec } from "./parser/prompt";
+export { jsonToOpenUI } from "./parser/serialize";
+export type { SerializeOptions } from "./parser/serialize";
export { BuiltinActionType } from "./parser/types";
export type {
ActionEvent,
diff --git a/packages/lang-core/src/library.ts b/packages/lang-core/src/library.ts
index b4cf43525..f998bc5bf 100644
--- a/packages/lang-core/src/library.ts
+++ b/packages/lang-core/src/library.ts
@@ -61,6 +61,8 @@ export type SubComponentOf<P> = {
export interface ComponentRenderProps<P = Record<string, unknown>, RenderNode = unknown> {
props: P;
renderNode: (value: unknown) => RenderNode;
+ /** The statement ID from the parsed program (e.g., "header", "prose1"). Undefined for inline components. */
+ statementId?: string;
}
// ─── DefinedComponent (framework-generic) ────────────────────────────────────
diff --git a/packages/lang-core/src/parser/__tests__/serialize.test.ts b/packages/lang-core/src/parser/__tests__/serialize.test.ts
new file mode 100644
index 000000000..6652292d6
--- /dev/null
+++ b/packages/lang-core/src/parser/__tests__/serialize.test.ts
@@ -0,0 +1,590 @@
+import { describe, expect, it } from "vitest";
+import type { Library } from "../../library";
+import { mergeStatements } from "../merge";
+import { parse } from "../parser";
+import { jsonToOpenUI } from "../serialize";
+import type { ElementNode, ParamMap } from "../types";
+
+// ── Fake library for tests ──────────────────────────────────────────────────
+
+/**
+ * Minimal fake library that provides toJSONSchema() matching the test schema.
+ * Components: Stack(children), Title(text), Table(columns, rows), Card(title, subtitle)
+ */
+function createFakeLibrary(): Library {
+ return {
+ components: {},
+ componentGroups: undefined,
+ root: undefined,
+ prompt: () => "",
+ toSpec: () => ({ components: {} }),
+ toJSONSchema: () => ({
+ $defs: {
+ Stack: {
+ properties: { children: { type: "array" } },
+ required: ["children"],
+ },
+ Title: {
+ properties: { text: { type: "string" } },
+ required: ["text"],
+ },
+ Table: {
+ properties: {
+ columns: { type: "array" },
+ rows: { type: "array" },
+ },
+ required: ["columns", "rows"],
+ },
+ Card: {
+ properties: {
+ title: { type: "string" },
+ subtitle: { type: "string" },
+ },
+ required: ["title"],
+ },
+ },
+ }),
+ } as unknown as Library;
+}
+
+const library = createFakeLibrary();
+
+// Build the same ParamMap the parser uses, for parse() calls
+const schema: ParamMap = new Map([
+ ["Stack", { params: [{ name: "children", required: true }] }],
+ ["Title", { params: [{ name: "text", required: true }] }],
+ [
+ "Table",
+ {
+ params: [
+ { name: "columns", required: true },
+ { name: "rows", required: true },
+ ],
+ },
+ ],
+ [
+ "Card",
+ {
+ params: [
+ { name: "title", required: true },
+ { name: "subtitle", required: false },
+ ],
+ },
+ ],
+]);
+
+// ── Helpers ──────────────────────────────────────────────────────────────────
+
+/** Parse openui-lang, serialize back, parse again, compare root trees. */
+function roundTrip(input: string) {
+ const result1 = parse(input, schema);
+ expect(result1.root).not.toBeNull();
+ const serialized = jsonToOpenUI(result1.root!, library);
+ const result2 = parse(serialized, schema);
+ return { result1, result2, serialized };
+}
+
+function stripDynamic(node: ElementNode): object {
+ const { partial, hasDynamicProps, ...rest } = node;
+ const cleanProps: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(rest.props)) {
+ if (isElNode(v)) {
+ cleanProps[k] = stripDynamic(v);
+ } else if (Array.isArray(v)) {
+ cleanProps[k] = v.map((el) => (isElNode(el) ? stripDynamic(el) : el));
+ } else {
+ cleanProps[k] = v;
+ }
+ }
+ return { ...rest, props: cleanProps };
+}
+
+function isElNode(v: unknown): v is ElementNode {
+ return v !== null && typeof v === "object" && (v as Record<string, unknown>).type === "element";
+}
+
+// ── Basic serialization ─────────────────────────────────────────────────────
+
+describe("jsonToOpenUI", () => {
+ describe("single component", () => {
+ it("serializes a simple component", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: { text: "Hello" },
+ partial: false,
+ hasDynamicProps: false,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toBe('root = Title("Hello")');
+ });
+
+ it("uses statementId as root name", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: { text: "Hi" },
+ partial: false,
+ statementId: "header",
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toBe('header = Title("Hi")');
+ });
+ });
+
+ describe("nested components", () => {
+ it("extracts children with statementId as separate statements", () => {
+ const child: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: { text: "Hello" },
+ partial: false,
+ statementId: "header",
+ };
+ const root: ElementNode = {
+ type: "element",
+ typeName: "Stack",
+ props: { children: [child] },
+ partial: false,
+ statementId: "root",
+ };
+ const result = jsonToOpenUI(root, library);
+ expect(result).toContain("root = Stack([header])");
+ expect(result).toContain('header = Title("Hello")');
+ });
+
+ it("inlines components without statementId", () => {
+ const child: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: { text: "Inline" },
+ partial: false,
+ };
+ const root: ElementNode = {
+ type: "element",
+ typeName: "Stack",
+ props: { children: [child] },
+ partial: false,
+ };
+ const result = jsonToOpenUI(root, library);
+ expect(result).toBe('root = Stack([Title("Inline")])');
+ });
+ });
+
+ // ── Value types ──────────────────────────────────────────────────────────
+
+ describe("value types", () => {
+ it("serializes strings with escaping", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: { text: 'Hello "world"' },
+ partial: false,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toBe('root = Title("Hello \\"world\\"")');
+ });
+
+ it("serializes numbers", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Table",
+ props: { columns: [42], rows: [[3.14]] },
+ partial: false,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toContain("42");
+ expect(result).toContain("3.14");
+ });
+
+ it("serializes booleans", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Table",
+ props: { columns: [true], rows: [[false]] },
+ partial: false,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toContain("true");
+ expect(result).toContain("false");
+ });
+
+ it("serializes null", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Table",
+ props: { columns: [null], rows: [[]] },
+ partial: false,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toContain("null");
+ });
+
+ it("serializes plain objects", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Table",
+ props: {
+ columns: [{ name: "col1", key: "id" }],
+ rows: [],
+ },
+ partial: false,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toContain('{name: "col1", key: "id"}');
+ });
+ });
+
+ // ── Positional arg ordering ──────────────────────────────────────────────
+
+ describe("positional arg ordering", () => {
+ it("maps props to positional args via ParamMap", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Table",
+ props: { columns: ["A", "B"], rows: [[1, 2]] },
+ partial: false,
+ };
+ const result = jsonToOpenUI(node, library);
+ // columns first, rows second per ParamMap
+ expect(result).toBe('root = Table(["A", "B"], [[1, 2]])');
+ });
+
+ it("trims trailing optional args", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Card",
+ props: { title: "Hello" },
+ partial: false,
+ };
+ const result = jsonToOpenUI(node, library);
+ // subtitle is optional and undefined → trimmed
+ expect(result).toBe('root = Card("Hello")');
+ });
+
+ it("fills middle gaps with null", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Table",
+ props: { rows: [[1, 2]] },
+ partial: false,
+ };
+ const result = jsonToOpenUI(node, library);
+ // columns is required but missing → null, rows follows
+ expect(result).toBe("root = Table(null, [[1, 2]])");
+ });
+ });
+
+ // ── AST node serialization ─────────────────────────────────────────────
+
+ describe("AST nodes in dynamic props", () => {
+ it("serializes StateRef", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: { text: { k: "StateRef", n: "$name" } },
+ partial: false,
+ hasDynamicProps: true,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toBe("root = Title($name)");
+ });
+
+ it("serializes RuntimeRef", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: { text: { k: "RuntimeRef", n: "queryData", refType: "query" } },
+ partial: false,
+ hasDynamicProps: true,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toBe("root = Title(queryData)");
+ });
+
+ it("serializes BinOp with correct precedence", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: {
+ text: {
+ k: "BinOp",
+ op: "*",
+ left: {
+ k: "BinOp",
+ op: "+",
+ left: { k: "StateRef", n: "$a" },
+ right: { k: "StateRef", n: "$b" },
+ },
+ right: { k: "StateRef", n: "$c" },
+ },
+ },
+ partial: false,
+ hasDynamicProps: true,
+ };
+ const result = jsonToOpenUI(node, library);
+ // + has lower precedence than * → needs parens
+ expect(result).toBe("root = Title(($a + $b) * $c)");
+ });
+
+ it("serializes Ternary", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: {
+ text: {
+ k: "Ternary",
+ cond: { k: "StateRef", n: "$active" },
+ then: { k: "Str", v: "Yes" },
+ else: { k: "Str", v: "No" },
+ },
+ },
+ partial: false,
+ hasDynamicProps: true,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toBe('root = Title($active ? "Yes" : "No")');
+ });
+
+ it("serializes Member access", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: {
+ text: {
+ k: "Member",
+ obj: { k: "RuntimeRef", n: "data", refType: "query" as const },
+ field: "name",
+ },
+ },
+ partial: false,
+ hasDynamicProps: true,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toBe("root = Title(data.name)");
+ });
+
+ it("serializes Index access", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: {
+ text: {
+ k: "Index",
+ obj: { k: "RuntimeRef", n: "items", refType: "query" as const },
+ index: { k: "Num", v: 0 },
+ },
+ },
+ partial: false,
+ hasDynamicProps: true,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toBe("root = Title(items[0])");
+ });
+
+ it("serializes UnaryOp", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: {
+ text: {
+ k: "UnaryOp",
+ op: "!",
+ operand: { k: "StateRef", n: "$flag" },
+ },
+ },
+ partial: false,
+ hasDynamicProps: true,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toBe("root = Title(!$flag)");
+ });
+ });
+
+ // ── Builtin serialization ──────────────────────────────────────────────
+
+ describe("builtins", () => {
+ it("serializes builtins with @ prefix", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: {
+ text: {
+ k: "Comp",
+ name: "Count",
+ args: [{ k: "RuntimeRef", n: "items", refType: "query" as const }],
+ },
+ },
+ partial: false,
+ hasDynamicProps: true,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toBe("root = Title(@Count(items))");
+ });
+
+ it("serializes Action without @ prefix", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: {
+ text: {
+ k: "Comp",
+ name: "Action",
+ args: [
+ {
+ k: "Arr",
+ els: [
+ {
+ k: "Comp",
+ name: "Run",
+ args: [{ k: "Ref", n: "myQuery" }],
+ },
+ ],
+ },
+ ],
+ },
+ },
+ partial: false,
+ hasDynamicProps: true,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toContain("Action([@Run(myQuery)])");
+ });
+ });
+
+ // ── State declarations ─────────────────────────────────────────────────
+
+ describe("state declarations", () => {
+ it("includes non-null state declarations", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: { text: "Hi" },
+ partial: false,
+ };
+ const result = jsonToOpenUI(node, library, {
+ stateDeclarations: { $count: 0, $name: "default" },
+ });
+ expect(result).toContain("$count = 0");
+ expect(result).toContain('$name = "default"');
+ });
+
+ it("omits null state declarations", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: { text: "Hi" },
+ partial: false,
+ };
+ const result = jsonToOpenUI(node, library, {
+ stateDeclarations: { $filter: null },
+ });
+ expect(result).not.toContain("$filter");
+ });
+ });
+
+ // ── Round-trip tests ───────────────────────────────────────────────────
+
+ describe("round-trip", () => {
+ it("round-trips a simple component", () => {
+ const { result1, result2 } = roundTrip('root = Title("Hello")');
+ expect(stripDynamic(result2.root!)).toEqual(stripDynamic(result1.root!));
+ });
+
+ it("round-trips nested components", () => {
+ const input =
+ 'root = Stack([header, tbl])\nheader = Title("Hi")\ntbl = Table(["A", "B"], [[1, 2]])';
+ const { result1, result2 } = roundTrip(input);
+ expect(stripDynamic(result2.root!)).toEqual(stripDynamic(result1.root!));
+ });
+
+ it("round-trips with optional args", () => {
+ const { result1, result2 } = roundTrip('root = Card("Main Title")');
+ expect(stripDynamic(result2.root!)).toEqual(stripDynamic(result1.root!));
+ });
+ });
+
+ // ── Integration with mergeStatements ───────────────────────────────────
+
+ describe("mergeStatements integration", () => {
+ it("serialized output works as a merge patch", () => {
+ const existing = 'root = Stack([header])\nheader = Title("Old")';
+
+ // Build a modified tree
+ const modifiedChild: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: { text: "New" },
+ partial: false,
+ statementId: "header",
+ };
+ const modifiedRoot: ElementNode = {
+ type: "element",
+ typeName: "Stack",
+ props: { children: [modifiedChild] },
+ partial: false,
+ statementId: "root",
+ };
+
+ const patch = jsonToOpenUI(modifiedRoot, library);
+ const merged = mergeStatements(existing, patch);
+
+ expect(merged).toBe('root = Stack([header])\nheader = Title("New")');
+
+ // Parse the merged result to verify
+ const result = parse(merged, schema);
+ expect(result.root).not.toBeNull();
+ expect(result.root!.typeName).toBe("Stack");
+ // The child should have the new text
+ const children = result.root!.props.children as ElementNode[];
+ expect(children[0].props.text).toBe("New");
+ });
+ });
+
+ // ── Edge cases ─────────────────────────────────────────────────────────
+
+ describe("edge cases", () => {
+ it("handles empty children array", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Stack",
+ props: { children: [] },
+ partial: false,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toBe("root = Stack([])");
+ });
+
+ it("handles partial nodes", () => {
+ const node: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: { text: "Streaming" },
+ partial: true,
+ };
+ const result = jsonToOpenUI(node, library);
+ expect(result).toBe('root = Title("Streaming")');
+ });
+
+ it("handles duplicate statementIds without infinite loop", () => {
+ const child: ElementNode = {
+ type: "element",
+ typeName: "Title",
+ props: { text: "Same" },
+ partial: false,
+ statementId: "shared",
+ };
+ const root: ElementNode = {
+ type: "element",
+ typeName: "Stack",
+ props: { children: [child, child] },
+ partial: false,
+ };
+ const result = jsonToOpenUI(root, library);
+ // Should reference "shared" twice but only define once
+ expect(result).toContain("Stack([shared, shared])");
+ const matches = result.match(/shared = Title/g);
+ expect(matches).toHaveLength(1);
+ });
+ });
+});
diff --git a/packages/lang-core/src/parser/index.ts b/packages/lang-core/src/parser/index.ts
index c447a066d..13c2138bb 100644
--- a/packages/lang-core/src/parser/index.ts
+++ b/packages/lang-core/src/parser/index.ts
@@ -23,6 +23,11 @@ export type { ComponentGroup, ComponentPromptSpec, PromptSpec, ToolSpec } from "
export { mergeStatements } from "./merge";
+export { jsonToOpenUI } from "./serialize";
+export type { SerializeOptions } from "./serialize";
+
+export { compileSchema } from "./parser";
+
// Shared builtin registry
export { BUILTINS, BUILTIN_NAMES, isBuiltin } from "./builtins";
export type { BuiltinDef } from "./builtins";
diff --git a/packages/lang-core/src/parser/parser.ts b/packages/lang-core/src/parser/parser.ts
index beae85b57..b76b6240f 100644
--- a/packages/lang-core/src/parser/parser.ts
+++ b/packages/lang-core/src/parser/parser.ts
@@ -595,7 +595,7 @@ function getSchemaDefaultValue(property: unknown): unknown {
return (property as { default?: unknown }).default;
}
-function compileSchema(schema: LibraryJSONSchema): ParamMap {
+export function compileSchema(schema: LibraryJSONSchema): ParamMap {
const map: ParamMap = new Map();
const defs = schema.$defs ?? {};
diff --git a/packages/lang-core/src/parser/serialize.ts b/packages/lang-core/src/parser/serialize.ts
new file mode 100644
index 000000000..c8da15856
--- /dev/null
+++ b/packages/lang-core/src/parser/serialize.ts
@@ -0,0 +1,279 @@
+// ─────────────────────────────────────────────────────────────────────────────
+// ElementNode → openui-lang source text serializer
+// Inverse of the parse + materialize pipeline.
+// ─────────────────────────────────────────────────────────────────────────────
+
+import type { Library } from "../library";
+import type { ASTNode } from "./ast";
+import { isASTNode } from "./ast";
+import { isBuiltin } from "./builtins";
+import { compileSchema } from "./parser";
+import { isElementNode, type ElementNode, type ParamMap } from "./types";
+
+// ─── Operator precedence (mirrors expressions.ts) ────────────────────────────
+
+const PRECEDENCE: Record<string, number> = {
+ "||": 2,
+ "&&": 3,
+ "==": 4,
+ "!=": 4,
+ ">": 5,
+ "<": 5,
+ ">=": 5,
+ "<=": 5,
+ "+": 6,
+ "-": 6,
+ "*": 7,
+ "/": 7,
+ "%": 7,
+};
+
+// ─── Statement collector ─────────────────────────────────────────────────────
+
+interface CollectedStatement {
+ id: string;
+ text: string;
+}
+
+class StatementCollector {
+ private statements: CollectedStatement[] = [];
+ private registered = new Set<string>();
+
+ /** Register an ElementNode as a named statement. Returns the statementId for use as a reference. */
+ register(id: string, text: string): void {
+ if (this.registered.has(id)) return;
+ this.registered.add(id);
+ this.statements.push({ id, text });
+ }
+
+ has(id: string): boolean {
+ return this.registered.has(id);
+ }
+
+ getStatements(): CollectedStatement[] {
+ return this.statements;
+ }
+}
+
+// ─── AST node serializer ─────────────────────────────────────────────────────
+
+function serializeASTNode(node: ASTNode): string {
+ switch (node.k) {
+ case "Str":
+ return JSON.stringify(node.v);
+ case "Num":
+ return String(node.v);
+ case "Bool":
+ return node.v ? "true" : "false";
+ case "Null":
+ return "null";
+ case "Ph":
+ return node.n;
+ case "StateRef":
+ return node.n; // already includes $ prefix
+ case "RuntimeRef":
+ return node.n;
+ case "Arr":
+ return "[" + node.els.map(serializeASTNode).join(", ") + "]";
+ case "Obj":
+ return "{" + node.entries.map(([k, v]) => `${k}: ${serializeASTNode(v)}`).join(", ") + "}";
+ case "BinOp": {
+ const left = serializeBinOpChild(node.left, node.op, "left");
+ const right = serializeBinOpChild(node.right, node.op, "right");
+ return `${left} ${node.op} ${right}`;
+ }
+ case "UnaryOp":
+ return `${node.op}${serializeASTNode(node.operand)}`;
+ case "Ternary":
+ return `${serializeASTNode(node.cond)} ? ${serializeASTNode(node.then)} : ${serializeASTNode(node.else)}`;
+ case "Member":
+ return `${serializeASTNode(node.obj)}.${node.field}`;
+ case "Index":
+ return `${serializeASTNode(node.obj)}[${serializeASTNode(node.index)}]`;
+ case "Assign":
+ return `${node.target} = ${serializeASTNode(node.value)}`;
+ case "Comp": {
+ const args = node.args.map(serializeASTNode).join(", ");
+ // Builtin (not Action) → @-prefix
+ if (isBuiltin(node.name) && node.name !== "Action") {
+ return `@${node.name}(${args})`;
+ }
+ // Action, reserved calls (Query/Mutation), catalog components → no prefix
+ return `${node.name}(${args})`;
+ }
+ // Ref nodes should not appear after materialization, but handle defensively
+ case "Ref":
+ return node.n;
+ default:
+ return "null";
+ }
+}
+
+/** Wrap a BinOp child in parens if its precedence is lower than the parent's. */
+function serializeBinOpChild(child: ASTNode, parentOp: string, _side: "left" | "right"): string {
+ const inner = serializeASTNode(child);
+ if (child.k !== "BinOp") return inner;
+ const parentPrec = PRECEDENCE[parentOp] ?? 0;
+ const childPrec = PRECEDENCE[child.op] ?? 0;
+ if (childPrec < parentPrec) return `(${inner})`;
+ return inner;
+}
+
+// ─── Value serializer ────────────────────────────────────────────────────────
+
+function serializeValue(value: unknown, paramMap: ParamMap, collector: StatementCollector): string {
+ if (value === null || value === undefined) return "null";
+ if (typeof value === "string") return JSON.stringify(value);
+ if (typeof value === "number") return String(value);
+ if (typeof value === "boolean") return value ? "true" : "false";
+
+ // ElementNode — check before isASTNode (they don't overlap, but order is clear)
+ if (isElementNode(value)) {
+ return serializeElementValue(value, paramMap, collector);
+ }
+
+ // ASTNode (surviving runtime expressions in dynamic props)
+ if (isASTNode(value)) {
+ return serializeASTNode(value);
+ }
+
+ // Array
+ if (Array.isArray(value)) {
+ const items = value.map((el) => serializeValue(el, paramMap, collector));
+ return "[" + items.join(", ") + "]";
+ }
+
+ // Plain object
+ if (typeof value === "object") {
+ const obj = value as Record<string, unknown>;
+ const entries = Object.entries(obj).map(
+ ([k, v]) => `${k}: ${serializeValue(v, paramMap, collector)}`,
+ );
+ return "{" + entries.join(", ") + "}";
+ }
+
+ return "null";
+}
+
+/** Serialize an ElementNode — either as a reference (if it has statementId) or inline. */
+function serializeElementValue(
+ node: ElementNode,
+ paramMap: ParamMap,
+ collector: StatementCollector,
+): string {
+ if (node.statementId) {
+ // Register as separate statement if not already registered
+ if (!collector.has(node.statementId)) {
+ // Serialize the expression first (depth-first → children registered before parent)
+ const expr = serializeElementExpr(node, paramMap, collector);
+ collector.register(node.statementId, `${node.statementId} = ${expr}`);
+ }
+ // Emit bare reference
+ return node.statementId;
+ }
+ // Inline (no statementId)
+ return serializeElementExpr(node, paramMap, collector);
+}
+
+// ─── ElementNode → expression string ─────────────────────────────────────────
+
+function serializeElementExpr(
+ node: ElementNode,
+ paramMap: ParamMap,
+ collector: StatementCollector,
+): string {
+ const def = paramMap.get(node.typeName);
+
+ if (def) {
+ // Map named props back to positional args using ParamMap order
+ const args: string[] = [];
+ for (const param of def.params) {
+ const val = node.props[param.name];
+ args.push(serializeValue(val, paramMap, collector));
+ }
+
+ // Trim trailing null/undefined/default args
+ while (args.length > 0) {
+ const last = args[args.length - 1];
+ if (last !== "null") break;
+ const paramIdx = args.length - 1;
+ const param = def.params[paramIdx];
+ if (!param) break;
+ // Only trim if the param is optional or has a default matching null
+ if (param.required) break;
+ args.pop();
+ }
+
+ return `${node.typeName}(${args.join(", ")})`;
+ }
+
+ // Unknown component — fallback to Object.keys() order
+ const fallbackArgs = Object.values(node.props).map((v) => serializeValue(v, paramMap, collector));
+ return `${node.typeName}(${fallbackArgs.join(", ")})`;
+}
+
+// ─── State declaration serializer ────────────────────────────────────────────
+
+function serializeStateDeclarations(
+ stateDeclarations: Record<string, unknown>,
+ paramMap: ParamMap,
+ collector: StatementCollector,
+): string[] {
+ const lines: string[] = [];
+ for (const [name, value] of Object.entries(stateDeclarations)) {
+ // Auto-declared null defaults ($var = null) can be omitted for cleaner output
+ if (value === null) continue;
+ lines.push(`${name} = ${serializeValue(value, paramMap, collector)}`);
+ }
+ return lines;
+}
+
+// ─── Public API ──────────────────────────────────────────────────────────────
+
+export interface SerializeOptions {
+ /** $variable declarations to include (e.g. from ParseResult.stateDeclarations). */
+ stateDeclarations?: Record<string, unknown>;
+}
+
+/**
+ * Convert an ElementNode tree back to openui-lang source text.
+ * Output is compatible with `mergeStatements()` for patching existing programs.
+ *
+ * @param json - The root ElementNode tree
+ * @param library - The component Library (for positional arg ordering)
+ * @param options - Optional state declarations
+ * @returns openui-lang source text (multiple statements joined by newlines)
+ */
+export function jsonToOpenUI(
+ json: ElementNode,
+ library: Library,
+ options?: SerializeOptions,
+): string {
+ const paramMap = compileSchema(library.toJSONSchema());
+ const collector = new StatementCollector();
+
+ // Serialize root — this recursively registers all child statements
+ const rootExpr = serializeElementExpr(json, paramMap, collector);
+ const rootId = json.statementId || "root";
+
+ // Build output: root first, then children (depth-first post-order), then state
+ const lines: string[] = [];
+
+ // Root statement
+ lines.push(`${rootId} = ${rootExpr}`);
+
+ // Child statements (already in depth-first post-order from collector)
+ for (const stmt of collector.getStatements()) {
+ // Skip root if it was also registered in collector
+ if (stmt.id === rootId) continue;
+ lines.push(stmt.text);
+ }
+
+ // State declarations
+ if (options?.stateDeclarations) {
+ const stateLines = serializeStateDeclarations(options.stateDeclarations, paramMap, collector);
+ lines.push(...stateLines);
+ }
+
+ return lines.join("\n");
+}
diff --git a/packages/react-lang/package.json b/packages/react-lang/package.json
index b1c963fab..14b00d115 100644
--- a/packages/react-lang/package.json
+++ b/packages/react-lang/package.json
@@ -1,6 +1,6 @@
{
"name": "@openuidev/react-lang",
- "version": "0.2.3",
+ "version": "0.2.4",
"description": "Define component libraries, generate LLM system prompts, and render streaming OpenUI Lang output in React — the core runtime for OpenUI generative UI",
"license": "MIT",
"type": "module",
diff --git a/packages/react-lang/src/Renderer.tsx b/packages/react-lang/src/Renderer.tsx
index 80d1a6251..0c06a8c93 100644
--- a/packages/react-lang/src/Renderer.tsx
+++ b/packages/react-lang/src/Renderer.tsx
@@ -165,7 +165,7 @@ function RenderNode({ node }: { node: ElementNode }) {
*/
function RenderNodeInner({ el, Comp }: { el: ElementNode; Comp: ComponentRenderer<any> }) {
const renderNode = useRenderNode();
- return <Comp props={el.props} renderNode={renderNode} />;
+ return <Comp props={el.props} renderNode={renderNode} statementId={el.statementId} />;
}
// ─── Loading style injection (once per document) ───