The Open Standard for Generative UI
spec: OpenUI 1.0 specification (#1277)
Aditya-thesys06ecd41cec7d
diff --git a/packages/lang-core/src/__tests__/conformance.test.ts b/packages/lang-core/src/__tests__/conformance.test.tsnew file mode 100644index 000000000..280d7647f--- /dev/null+++ b/packages/lang-core/src/__tests__/conformance.test.ts@@ -0,0 +1,281 @@+// The spec/fixtures/1.0 conformance cases (spec/language.md, Appendix B; rules in spec/fixtures/1.0/README.md).+// Every case must pass. interactions.json runs in react-lang.+// OPENUI_FIXTURES points the runners at another fixture folder.+import fs from "node:fs";+import path from "node:path";+import { isDeepStrictEqual } from "node:util";+import { afterAll, describe, expect, it } from "vitest";+import * as z from "zod/v4";+import {+ createLibrary,+ createParser,+ createStore,+ createStreamingParser,+ defineComponent,+ evaluate,+ evaluateRoot,+ jsonToOpenUI,+ markReactive,+ mergeStatements,+ parseStructuredRules,+ validate,+ type ElementNode,+ type EvaluationContext,+ type LibraryJSONSchema,+ type OpenUIError,+ type ParseResult,+} from "../index";+import type { Library } from "../library";++type Dict = Record<string, unknown>;+type Call = { description?: string; params: { properties?: Dict } };++const FIXTURES_DIR = path.resolve(+ process.env.OPENUI_FIXTURES ?? path.join(__dirname, "../../../../spec/fixtures/1.0"),+);+const read = (...p: string[]) => fs.readFileSync(path.join(FIXTURES_DIR, ...p), "utf8");+const dirs = (...p: string[]) =>+ fs+ .readdirSync(path.join(FIXTURES_DIR, ...p), { withFileTypes: true })+ .filter((d) => d.isDirectory())+ .map((d) => d.name)+ .sort();++const spec: {+ root: string;+ schema: { $defs: Record<string, { properties?: Dict }>; functions?: Record<string, Call> };+ components: Record<string, { signature: string; description: string }>;+} = JSON.parse(read("library.json"));+const schema = spec.schema as unknown as LibraryJSONSchema;++// ─── The test library ───++/** Implementations of library.json's functions, which a client supplies. */+const FUNCTIONS: Record<string, (args: Dict) => unknown> = {+ Upper: ({ text }) => String(text ?? "").toUpperCase(),+};++// Parsing uses library.json's schema as it is (`toJSONSchema`). Evaluation only needs each+// component's prop keys, with the reactive mark on bindable props (signature `$binding<`).+const library: Library = {+ ...createLibrary({+ components: Object.entries(spec.components).map(([name, { signature, description }]) => {+ const bindable = new Set([...signature.matchAll(/(\w+)\??: \$binding</g)].map((m) => m[1]));+ const props = Object.keys(spec.schema.$defs[name].properties ?? {}).map((key) => {+ const s = z.any();+ if (bindable.has(key)) markReactive(s);+ return [key, s];+ });+ return defineComponent({+ name,+ description,+ props: z.object(Object.fromEntries(props)),+ component: null,+ });+ }),+ root: spec.root,+ }),+ toJSONSchema: () => schema,+};+const functions = Object.fromEntries(+ Object.entries(spec.schema.functions ?? {}).map(([name, f]) => [+ name,+ { ...f, fn: FUNCTIONS[name] },+ ]),+);+const actionParams = Object.fromEntries(+ Object.entries(schema.actions ?? {}).map(([name, a]) => [+ name,+ Object.keys((a as Call).params.properties ?? {}),+ ]),+);+const json = <T>(v: T): T => (v === undefined ? v : JSON.parse(JSON.stringify(v)));+const same = (a: unknown, b: unknown) => isDeepStrictEqual(json(a), json(b));++// ─── Summary (README, "How the tree is summarized") ───++type Ev = (ast: unknown) => unknown;++function summarizeAction(s: Dict, ev: Ev): Dict {+ switch (s.type) {+ case "continue_conversation":+ return {+ action: "ToAssistant",+ args: s.context == null ? [s.message] : [s.message, s.context],+ };+ case "open_url":+ return { action: "OpenUrl", args: [s.url] };+ case "set":+ return { action: "Set", args: [s.target, ev(s.valueAST) ?? null] };+ case "reset":+ return { action: "Reset", args: s.targets };+ case "run":+ return { action: "Run", args: [s.statementId] };+ default: {+ const params = (s.params as Dict) ?? {};+ const keys = actionParams[s.name as string] ?? Object.keys(params);+ return { action: s.name, args: keys.map((k) => summarize(params[k], ev)) };+ }+ }+}++function summarize(v: unknown, ev: Ev): unknown {+ if (v == null || typeof v !== "object") return v ?? null;+ if (Array.isArray(v)) return v.map((x) => summarize(x, ev));+ const o = v as Dict;+ if (o.type === "element") {+ const props = Object.entries(o.props as Dict)+ .map(([k, pv]) => [k, summarize(pv, ev)])+ .filter(([, s]) => s !== null);+ return { type: o.typeName, props: Object.fromEntries(props) };+ }+ if (Array.isArray(o.steps))+ return { actions: (o.steps as Dict[]).map((s) => summarizeAction(s, ev)) };+ if (o.__reactive === "assign") return { $binding: o.target };+ return Object.fromEntries(Object.entries(o).map(([k, pv]) => [k, summarize(pv, ev)]));+}++/** The canonical result at stream end, plus the evaluated tree for the roundtrip check. */+function evaluateResult(result: ParseResult) {+ const store = createStore();+ store.initialize(result.stateDeclarations ?? {}, {});+ // At stream end no fetch has returned: a query reads its defaults, a mutation is idle.+ const ctx: EvaluationContext = {+ getState: (name) => store.get(name) ?? null,+ resolveRef: (name) => {+ const q = result.queryStatements.find((s) => s.statementId === name);+ if (q) return q.defaultsAST ? evaluate(q.defaultsAST, ctx) : null;+ const m = result.mutationStatements.some((s) => s.statementId === name);+ return m ? { status: "idle", data: null, error: null } : null;+ },+ functions,+ actions: schema.actions,+ };+ const runtimeErrors: OpenUIError[] = [];+ const tree = evaluateRoot(result, { ctx, library, store, errors: runtimeErrors });+ // The error objects of language.md, section 8.3.+ const errorObjects = [+ ...result.meta.errors.map((e) => ({ source: "parser", ...e, path: e.path || undefined })),+ ...runtimeErrors,+ ];+ return {+ tree,+ root: summarize(tree, (ast) => evaluate(ast as never, ctx)),+ errors: errorObjects.map(({ code, statementId }) => ({ code, statementId })),+ errorObjects,+ unresolved: result.meta.unresolved,+ orphans: result.meta.orphaned,+ incomplete: result.meta.incomplete,+ state: json(result.stateDeclarations ?? {}),+ };+}++// ─── Comparison (README, "Comparison") ───++/**+ * Each expected entry claims its own actual entry that agrees on the keys it lists, so an+ * `errors` entry without `statementId` matches any statement. Entries listing more keys go first.+ */+function claims(expected: Dict[], actual: object[]): boolean {+ const pool = [...actual] as Dict[];+ return [...expected]+ .sort((a, b) => Object.keys(b).length - Object.keys(a).length)+ .every((e) => {+ const i = pool.findIndex((a) => Object.entries(e).every(([k, v]) => same(v, a[k] ?? null)));+ return i !== -1 && pool.splice(i, 1).length === 1;+ });+}++const asSet = (xs: unknown) => (Array.isArray(xs) ? [...new Set(xs)].sort() : xs);+const COMPARE: Record<string, (want: unknown, got: unknown) => boolean> = {+ root: same,+ errors: (w, g) =>+ (w as Dict[]).length === (g as Dict[]).length && claims(w as Dict[], g as Dict[]),+ unresolved: (w, g) => same(asSet(w), asSet(g)),+ orphans: (w, g) => same(asSet(w), asSet(g)),+ incomplete: same,+ state: same,+ statements: same,+ errorObjects: (w, g) => claims(w as Dict[], g as Dict[]),+};+const OPTIONAL = ["state", "statements", "errorObjects"];++function check(id: string, expected: Dict, result: ParseResult, statements?: string[]): string[] {+ const actual: Dict = { ...evaluateResult(result), statements };+ const diffs = Object.entries(COMPARE)+ .filter(([k, ok]) => (k in expected || !OPTIONAL.includes(k)) && !ok(expected[k], actual[k]))+ .map(+ ([k]) => `${k}: expected ${JSON.stringify(expected[k])}, got ${JSON.stringify(actual[k])}`,+ );++ if (id.includes("-roundtrip-") && actual.tree) {+ const text = jsonToOpenUI(actual.tree as ElementNode, library);+ const again = evaluateResult(parse(text)).root;+ if (!same(again, expected.root))+ diffs.push(`roundtrip: ${JSON.stringify(text)} parses to ${JSON.stringify(again)}`);+ }+ return diffs;+}++// ─── Running a case ───++const parse = (text: string) => createParser(schema, spec.root).parse(text);++function runProgram(id: string, files: Record<string, string>): string[] {+ const expected = JSON.parse(files["expected.json"]) as Dict;++ if (files["chunks.json"]) {+ const chunks = JSON.parse(files["chunks.json"]) as string[];+ const parser = createStreamingParser(schema, spec.root);+ chunks.forEach((chunk, i) => parser.push(chunk, i === chunks.length - 1));+ return [+ ...check(id, expected, parser.getResult(true)).map((d) => `streamed ${d}`),+ ...check(id, expected, parse(chunks.join(""))).map((d) => `batch ${d}`),+ ];+ }++ const patch = files["patch.oui"];+ if (patch === undefined) return check(id, expected, parse(files["input.oui"]));+ const merged = mergeStatements(files["input.oui"], patch);+ const statements = merged.split("\n").flatMap((l) => /^(\$?\w+)\s*=(?!=)/.exec(l)?.[1] ?? []);+ return check(id, expected, parse(merged), statements);+}++function runValidation(files: Record<string, string>): string[] {+ const { cases } = JSON.parse(files["validation.json"]) as {+ cases: { rules: unknown; value: unknown; valid: boolean }[];+ };+ return cases.flatMap(({ rules, value, valid }, i) => {+ const error = validate(value, parseStructuredRules(rules));+ if ((error === undefined) === valid) return [];+ return [+ `case ${i} ${JSON.stringify(rules)} ${JSON.stringify(value)}: got ${JSON.stringify(error)}`,+ ];+ });+}++// ─── Registration ───++const results: Record<string, { status: string; diffs?: string[] }> = {};++describe("OpenUI conformance fixtures", () => {+ for (const area of dirs()) {+ for (const name of dirs(area)) {+ const id = `${area}/${name}`;+ it(id, () => {+ const files = Object.fromEntries(+ fs.readdirSync(path.join(FIXTURES_DIR, id)).map((f) => [f, read(id, f)]),+ );+ const diffs = files["validation.json"] ? runValidation(files) : runProgram(id, files);+ results[id] = diffs.length ? { status: "fail", diffs } : { status: "pass" };+ if (diffs.length) expect.fail(`${id}\n ${diffs.join("\n ")}`);+ });+ }+ }++ // OPENUI_CONFORMANCE_REPORT=<file> writes `{ "<id>": { status, diffs? } }`.+ afterAll(() => {+ const report = process.env.OPENUI_CONFORMANCE_REPORT;+ if (report) fs.writeFileSync(report, JSON.stringify(results, null, 2) + "\n");+ });+});diff --git a/packages/react-lang/src/__tests__/conformance.interactions.test.tsx b/packages/react-lang/src/__tests__/conformance.interactions.test.tsxnew file mode 100644index 000000000..318b9fbda--- /dev/null+++ b/packages/react-lang/src/__tests__/conformance.interactions.test.tsx@@ -0,0 +1,239 @@+// @vitest-environment jsdom+// The interactions.json part of the spec/fixtures/1.0 conformance cases (README, "Action and form cases"),+// run through <Renderer>. lang-core's conformance.test.ts checks their expected.json.+import {+ createLibrary,+ defineAction,+ defineComponent,+ markReactive,+ type ActionEvent,+ type Store,+} from "@openuidev/lang-core";+import fs from "node:fs";+import path from "node:path";+import { isDeepStrictEqual } from "node:util";+import React, { act } from "react";+import { createRoot } from "react-dom/client";+import { afterAll, describe, expect, it } from "vitest";+import * as z from "zod/v4";+import { FormNameContext, useFormName, useOpenUI } from "../context";+import { useStateField } from "../hooks/useStateField";+import type { ComponentRenderer, Library } from "../library";+import { Renderer } from "../Renderer";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++type Dict = Record<string, unknown>;+type Params = { properties?: Dict };++const FIXTURES = path.resolve(+ process.env.OPENUI_FIXTURES ?? path.join(__dirname, "../../../../spec/fixtures/1.0"),+);+const read = (...p: string[]) => fs.readFileSync(path.join(FIXTURES, ...p), "utf8");+const dirs = (...p: string[]) =>+ fs+ .readdirSync(path.join(FIXTURES, ...p), { withFileTypes: true })+ .filter((d) => d.isDirectory())+ .map((d) => d.name)+ .sort();+const spec = JSON.parse(read("library.json")) as {+ root: string;+ schema: { $defs: Record<string, Params>; actions?: Record<string, { params: Params }> };+ components: Record<string, { signature: string; description: string }>;+};++// ─── Test renderers; each registers its handlers by statement id ───++let clicks = new Map<string, () => unknown>();+let inputs = new Map<string, (text: string) => void>();+const live: { store: Store | null } = { store: null };++/** useOpenUI, also keeping the store so the runner can read state at the end. */+function useCtx() {+ const ctx = useOpenUI();+ live.store = ctx.store;+ return ctx;+}++const Generic: ComponentRenderer<Dict> = ({ props, renderNode }) => {+ useCtx();+ return (+ <div>+ {Object.values(props).map((v, i) => (+ <React.Fragment key={i}>{renderNode(v)}</React.Fragment>+ ))}+ </div>+ );+};++const RENDERERS: Record<string, ComponentRenderer<Dict>> = {+ Form: ({ props, renderNode }) => (+ <FormNameContext.Provider value={props.name as string}>+ <form>{renderNode(props.children)}</form>+ </FormNameContext.Provider>+ ),+ Input: ({ props, statementId }) => {+ const ctx = useCtx();+ const formName = useFormName();+ const field = useStateField(props.name as string, props.value);+ // A form field records its componentType; a bound $variable takes the plain value.+ inputs.set(statementId!, (text) =>+ field.isReactive+ ? field.setValue(text)+ : ctx.setFieldValue(formName, "input", props.name as string, text),+ );+ return <input readOnly value={String(field.value ?? "")} />;+ },+ Button: ({ props, statementId }) => {+ const ctx = useCtx();+ const formName = useFormName();+ clicks.set(statementId!, () =>+ ctx.triggerAction(props.label as string, formName, props.action as never),+ );+ return <button>{String(props.label)}</button>;+ },+};++// ─── The test library from library.json ───++// Only the prop keys matter here, with the reactive mark on bindable props.+function props({ properties = {} }: Params, bindable = new Set<string>()) {+ const shape = Object.keys(properties).map((key) => {+ const s = z.any();+ if (bindable.has(key)) markReactive(s);+ return [key, s];+ });+ return z.object(Object.fromEntries(shape));+}++const library = {+ ...createLibrary({+ components: Object.entries(spec.components).map(([name, { signature, description }]) =>+ defineComponent({+ name,+ description,+ props: props(+ spec.schema.$defs[name],+ new Set([...signature.matchAll(/(\w+)\??: \$binding</g)].map((m) => m[1])),+ ),+ component: RENDERERS[name] ?? Generic,+ }),+ ),+ actions: Object.entries(spec.schema.actions ?? {}).map(([name, a]) =>+ defineAction({ name, description: "", params: props(a.params) }),+ ) as never,+ root: spec.root,+ }),+ toJSONSchema: () => spec.schema,+} as unknown as Library;++// ─── Running a case ───++const json = (v: unknown) => (v === undefined ? null : JSON.parse(JSON.stringify(v)));+const same = (a: unknown, b: unknown) => isDeepStrictEqual(json(a), json(b));+const str = JSON.stringify;++async function settle() {+ for (let i = 0; i < 5; i++) await act(() => new Promise((r) => setTimeout(r, 0)));+}++async function runInteractions(+ program: string,+ { interactions: steps, expected }: { interactions: Dict[]; expected: Dict },+) {+ clicks = new Map();+ inputs = new Map();+ live.store = null;+ const events: Dict[] = [];+ const toolCalls: Dict[] = [];+ const tools: Record<string, (args: Dict) => Promise<unknown>> = {};+ const setTool = (name: string, result: unknown) => {+ tools[name] = async (args) => (toolCalls.push({ tool: name, args: json(args) }), json(result));+ };+ // Tool steps before the first user step apply before the program mounts.+ let i = 0;+ for (; i < steps.length && "tool" in steps[i]; i++)+ setTool(steps[i].tool as string, steps[i].result);++ const root = createRoot(document.createElement("div"));+ const diffs: string[] = [];+ try {+ await act(async () =>+ root.render(+ <Renderer+ response={program}+ library={library}+ isStreaming={false}+ onAction={(e: ActionEvent) => events.push(e as unknown as Dict)}+ toolProvider={tools}+ />,+ ),+ );+ await settle();+ for (; i < steps.length; i++) {+ const s = steps[i];+ if ("tool" in s) {+ setTool(s.tool as string, s.result);+ continue;+ }+ const [id, text] = "type" in s ? (s.type as [string, string]) : [s.click as string, ""];+ const handler = "type" in s ? inputs.get(id) : clicks.get(id);+ if (!handler) {+ diffs.push(`step ${i}: nothing rendered for ${id}`);+ break;+ }+ await act(async () => void (await handler(text)));+ await settle();+ }++ // Each expected event is compared on the keys it lists; null means absent or null.+ const want = (expected.events as Dict[]) ?? [];+ const eventsOk =+ want.length === events.length &&+ want.every((w, k) => Object.entries(w).every(([key, v]) => same(v, events[k][key])));+ if (!eventsOk) diffs.push(`events: expected ${str(want)}, got ${str(json(events))}`);+ for (const [key, v] of Object.entries((expected.state as Dict) ?? {})) {+ const got = (live.store as Store | null)?.get(key); // set while rendering+ if (!same(v, got)) diffs.push(`state ${key}: expected ${str(v)}, got ${str(got)}`);+ }+ // Consecutive identical calls count once.+ const calls = toolCalls.filter((c, k) => k === 0 || !same(c, toolCalls[k - 1]));+ if (expected.toolCalls && !same(expected.toolCalls, calls))+ diffs.push(`toolCalls: expected ${str(expected.toolCalls)}, got ${str(calls)}`);+ } finally {+ await act(async () => root.unmount());+ }+ return diffs;+}++// ─── Registration ───++const results: Record<string, { status: string; diffs?: string[] }> = {};++describe("OpenUI conformance fixtures (interactions)", () => {+ for (const area of dirs()) {+ for (const name of dirs(area)) {+ if (!fs.existsSync(path.join(FIXTURES, area, name, "interactions.json"))) continue;+ const id = `${area}/${name}#interactions`;+ it(id, async () => {+ const diffs = await runInteractions(+ read(area, name, "input.oui"),+ JSON.parse(read(area, name, "interactions.json")),+ );+ results[id] = diffs.length ? { status: "fail", diffs } : { status: "pass" };+ if (diffs.length) expect.fail(`${id}\n ${diffs.join("\n ")}`);+ });+ }+ }++ // OPENUI_CONFORMANCE_REPORT=<file> writes `<file>.interactions.json`: `{ "<id>": { status, diffs? } }`.+ afterAll(() => {+ const report = process.env.OPENUI_CONFORMANCE_REPORT;+ if (report) {+ fs.writeFileSync(+ report.replace(/(\.json)?$/, ".interactions.json"),+ JSON.stringify(results, null, 2) + "\n",+ );+ }+ });+});diff --git a/spec/fixtures/1.0/README.md b/spec/fixtures/1.0/README.mdnew file mode 100644index 000000000..a6ac77227--- /dev/null+++ b/spec/fixtures/1.0/README.md@@ -0,0 +1,85 @@+# OpenUI 1.0 conformance fixtures++The layout and main file formats are in [language.md](../../language.md), Appendix B. This file lists the details Appendix B leaves open. Every expected result was written from the spec text. The suite holds only cases the reference implementation passes. A new case arrives with the fix that makes it pass.++```text+spec/fixtures/1.0/+ library.json the test library, used by every case+ <area>/<NNN-short-name>/+```++Each area folder has a `README.md` that says what the area protects and lists every case with what it checks.++## The test library++`library.json` is a LibrarySpec ([prompt.md](../../prompt.md), section 2) with `root: "Stack"`, twelve components, one custom function, `@Upper(text)`, which returns the text in upper case, and one custom action, `@CopyToClipboard(text)`. The function has no implementation in the file, so a runner supplies it.++Positional order is the key order of each component's `properties` in `$defs`, and of each function's and action's `params` in `schema.functions` and `schema.actions`. Bindable props are the ones whose signature prints `$binding<string>` (`Input.value`, `Select.value`); the schema has no marker for them. Component slots are `$ref`s to `$defs` entries: the children of `Stack`, `Card`, and `Form` take any component, `Table` columns take `Col`, and `Select` items take `SelectItem`. `Button.action` is `{ "$ref": "#/$defs/ActionExpression" }`, and `Button.share` takes only `@CopyToClipboard` or `@OpenUrl`.++## Program cases++Files: `input.oui` (streaming cases: `chunks.json`) and `expected.json`.++`expected.json` has the keys of Appendix B: `root`, `errors`, `unresolved`, `orphans`, `incomplete`. It may also have:++- `state`: the state defaults after the stream ends, `{ "$name": value }`. When present it must match exactly.+- `statements` (editing cases): the statement names of the merged program, in order.+- `errorObjects`: the structural fields of the error object (language.md, section 8.3): `source`, `code`, `statementId`, `component`, `path`. Only the listed keys are compared. `message` and `hint` are text for the model and are never compared.++How the tree is summarized:++- A component is `{ "type", "props" }`. A prop that is null or absent is left out. Array elements are kept as they are, including `null`.+- Actions are `{ "actions": [{ "action", "args" }] }`. Action names drop the `@`: `ToAssistant`, `OpenUrl`, `Set`, `Reset`, `Run`. `ToAssistant` args are the message, plus the context when there is one. `Set` args are the target and its value, evaluated with the state at stream end. `Reset` args are the targets, and `Run` args are the statement id. A custom action uses its name, and its args are the arguments in the key order of the action's `params`. Every action call is an `Action` of one action (language.md, section 6.3), so a lone action is summarized as a list of one, and a plain list of actions as a list of such lists.+- A binding is `{ "$binding": "$name" }`.+- Values come from evaluating the tree when the stream ends. No query has returned yet, so a reference to a query reads its defaults, and a reference to a mutation reads `{ "status": "idle", "data": null, "error": null }`.++Comparison:++- `errors` is compared as a multiset. An entry without `statementId` matches any statement, which is how `no-root` is written.+- `unresolved` and `orphans` are compared as sets.+- Streaming cases must match both after the last chunk plus the end of the stream, and as a batch parse of the joined chunks (language.md, section 4: streaming equals parsing).+- `*-roundtrip-*` cases also serialize the rendered tree, parse it again, and expect the same `root`.++## Testing your implementation++The cases work like [toml-test](https://github.com/toml-lang/toml-test): your implementation reads text and prints JSON, and a small harness diffs it.++There are two kinds of check, and a client can claim either level:++| Level | Files | Needs | Checks |+| --- | --- | --- | --- |+| 1. Program | `input.oui` or `chunks.json`, `patch.oui`, `validation.json`, `expected.json` | A parser and evaluator, no UI | Syntax, streaming, entry, references, evaluation, editing, errors, validation rules |+| 2. Interaction | `interactions.json` | A renderer that runs actions | What a click or typing does: the events the host receives and the final state |++Every case has a level 1 check. A case is also a level 2 check when its folder has `interactions.json`. The area READMEs mark these cases with "+ interactions". A parser, validator, or server-side checker can stop at level 1.++A case is a folder with `input.oui` (or `chunks.json`) and `expected.json`, plus `patch.oui` for editing cases, `interactions.json` for action and form cases, and `validation.json` for validation cases. To test a client:++1. Write an adapter that loads `library.json`, parses `input.oui` with it (or pushes each chunk of `chunks.json`, then ends the stream), evaluates the tree at stream end, and prints the canonical JSON: `root`, `errors` as `{ code, statementId }`, `unresolved`, `orphans`, `incomplete`, `state`, and `statements` for editing cases.+2. Run it on every case and diff its output with `expected.json` using the comparison rules above: `errors` as a multiset, `unresolved` and `orphans` as sets, everything else exactly, and for streaming cases the streamed result and a batch parse of the joined chunks must both match.+3. For `interactions.json`, mount the program with test renderers for `Form`, `Input`, and `Button`, replay the interactions, and compare the host events and the state.++The canonical form holds only spec concepts: component types and props, resolved values, error codes, unresolved names, orphans, `incomplete`, state, and statements. It never holds parser internals or message text.++The reference runners are `packages/lang-core/src/__tests__/conformance.test.ts` (program and validation cases) and `packages/react-lang/src/__tests__/conformance.interactions.test.tsx` (`interactions.json`). They run with each package's tests and fail on any case that does not pass. `OPENUI_FIXTURES` points them at another fixture folder.++## Editing cases++Files: `input.oui` (the current program), `patch.oui` (the model's reply), and `expected.json`. The runner merges the patch into the program (language.md, section 7), then parses the result as a program case. `statements` is read from the merged text: each line that starts with `name =` at column 0 starts a statement.++## Action and form cases++These cases add `interactions.json` as in Appendix B. An interaction is `{ "click": id }`, `{ "type": [id, text] }`, or `{ "tool": name, "result": json }`, where `id` is the statement name of a Button or Input.++- A `tool` interaction sets what that tool returns from then on. Tool interactions before the first user interaction apply before the program mounts.+- `expected.events` lists the host events in order. Each entry is compared on the keys it lists only. `"formName": null` means the key is absent or null.+- `expected.state` is compared key by key against the state store.+- `expected.toolCalls` is optional: `[{ "tool", "args" }]`, the tool calls in order. Consecutive identical calls count once. Appendix B has no way to check tool arguments, so this key extends it.++The test library's Input writes a form field as `{ "value", "componentType": "input" }`. `componentType` is up to each platform's components, so fixtures only use it with this library.++State cases with user input (`state/*-binding-*`, `state/*-form-*`) use `interactions.json` too.++## Validation cases++`state/*-validation-*` cases hold `validation.json` instead of a program: `{ "cases": [{ "rules", "value", "valid" }] }`. `rules` is the validation rules object (language.md, section 5.4). The runner checks each value against the rules and compares only pass or fail, not the message.diff --git a/spec/fixtures/1.0/actions/001-several-actions/expected.json b/spec/fixtures/1.0/actions/001-several-actions/expected.jsonnew file mode 100644index 000000000..1401ddc1e--- /dev/null+++ b/spec/fixtures/1.0/actions/001-several-actions/expected.json@@ -0,0 +1,63 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Button",+ "props": {+ "label": "Bump",+ "action": {+ "actions": [+ {+ "action": "Set",+ "args": [+ "$m",+ 9+ ]+ }+ ]+ }+ }+ },+ {+ "type": "Button",+ "props": {+ "label": "Go",+ "action": {+ "actions": [+ {+ "action": "Set",+ "args": [+ "$n",+ 5+ ]+ },+ {+ "action": "Reset",+ "args": [+ "$m"+ ]+ },+ {+ "action": "ToAssistant",+ "args": [+ "done"+ ]+ }+ ]+ }+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$n": 1,+ "$m": 7+ }+}diff --git a/spec/fixtures/1.0/actions/001-several-actions/input.oui b/spec/fixtures/1.0/actions/001-several-actions/input.ouinew file mode 100644index 000000000..05fdfcb34--- /dev/null+++ b/spec/fixtures/1.0/actions/001-several-actions/input.oui@@ -0,0 +1,5 @@+$n = 1+$m = 7+root = Stack([bump, go])+bump = Button("Bump", Action([@Set($m, 9)]))+go = Button("Go", Action([@Set($n, 5), @Reset($m), @ToAssistant("done")]))diff --git a/spec/fixtures/1.0/actions/001-several-actions/interactions.json b/spec/fixtures/1.0/actions/001-several-actions/interactions.jsonnew file mode 100644index 000000000..7348b4d6f--- /dev/null+++ b/spec/fixtures/1.0/actions/001-several-actions/interactions.json@@ -0,0 +1,22 @@+{+ "interactions": [+ {+ "click": "bump"+ },+ {+ "click": "go"+ }+ ],+ "expected": {+ "events": [+ {+ "type": "continue_conversation",+ "humanFriendlyMessage": "done"+ }+ ],+ "state": {+ "$n": 5,+ "$m": 7+ }+ }+}diff --git a/spec/fixtures/1.0/actions/002-one-action/expected.json b/spec/fixtures/1.0/actions/002-one-action/expected.jsonnew file mode 100644index 000000000..3b848c46a--- /dev/null+++ b/spec/fixtures/1.0/actions/002-one-action/expected.json@@ -0,0 +1,71 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Button",+ "props": {+ "label": "Save",+ "action": {+ "actions": [+ {+ "action": "ToAssistant",+ "args": [+ "Save order"+ ]+ }+ ]+ }+ }+ },+ {+ "type": "Button",+ "props": {+ "label": "Pick B",+ "action": {+ "actions": [+ {+ "action": "Set",+ "args": [+ "$sel",+ "b"+ ]+ }+ ]+ }+ }+ },+ {+ "type": "Button",+ "props": {+ "label": "Docs",+ "action": {+ "actions": [+ {+ "action": "OpenUrl",+ "args": [+ "https://openui.com"+ ]+ }+ ]+ }+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "a"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$sel": "a"+ }+}diff --git a/spec/fixtures/1.0/actions/002-one-action/input.oui b/spec/fixtures/1.0/actions/002-one-action/input.ouinew file mode 100644index 000000000..25274f6a3--- /dev/null+++ b/spec/fixtures/1.0/actions/002-one-action/input.oui@@ -0,0 +1,5 @@+$sel = "a"+root = Stack([save, pick, docs, Text($sel)])+save = Button("Save", @ToAssistant("Save order"))+pick = Button("Pick B", @Set($sel, "b"))+docs = Button("Docs", @OpenUrl("https://openui.com"))diff --git a/spec/fixtures/1.0/actions/002-one-action/interactions.json b/spec/fixtures/1.0/actions/002-one-action/interactions.jsonnew file mode 100644index 000000000..ba01ae234--- /dev/null+++ b/spec/fixtures/1.0/actions/002-one-action/interactions.json@@ -0,0 +1,31 @@+{+ "interactions": [+ {+ "click": "save"+ },+ {+ "click": "pick"+ },+ {+ "click": "docs"+ }+ ],+ "expected": {+ "events": [+ {+ "type": "continue_conversation",+ "humanFriendlyMessage": "Save order"+ },+ {+ "type": "open_url",+ "humanFriendlyMessage": "",+ "params": {+ "url": "https://openui.com"+ }+ }+ ],+ "state": {+ "$sel": "b"+ }+ }+}diff --git a/spec/fixtures/1.0/actions/003-event-context-any-value/expected.json b/spec/fixtures/1.0/actions/003-event-context-any-value/expected.jsonnew file mode 100644index 000000000..a1021902e--- /dev/null+++ b/spec/fixtures/1.0/actions/003-event-context-any-value/expected.json@@ -0,0 +1,52 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Button",+ "props": {+ "label": "Save",+ "action": {+ "actions": [+ {+ "action": "ToAssistant",+ "args": [+ "Save order",+ {+ "orderId": 42,+ "tags": [+ "rush"+ ]+ }+ ]+ }+ ]+ }+ }+ },+ {+ "type": "Button",+ "props": {+ "label": "Zero",+ "action": {+ "actions": [+ {+ "action": "ToAssistant",+ "args": [+ "Pick zero",+ 0+ ]+ }+ ]+ }+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/actions/003-event-context-any-value/input.oui b/spec/fixtures/1.0/actions/003-event-context-any-value/input.ouinew file mode 100644index 000000000..b0bc37d5a--- /dev/null+++ b/spec/fixtures/1.0/actions/003-event-context-any-value/input.oui@@ -0,0 +1,3 @@+root = Stack([save, zero])+save = Button("Save", Action([@ToAssistant("Save order", {orderId: 42, tags: ["rush"]})]))+zero = Button("Zero", Action([@ToAssistant("Pick zero", 0)]))diff --git a/spec/fixtures/1.0/actions/003-event-context-any-value/interactions.json b/spec/fixtures/1.0/actions/003-event-context-any-value/interactions.jsonnew file mode 100644index 000000000..82a7ed221--- /dev/null+++ b/spec/fixtures/1.0/actions/003-event-context-any-value/interactions.json@@ -0,0 +1,33 @@+{+ "interactions": [+ {+ "click": "save"+ },+ {+ "click": "zero"+ }+ ],+ "expected": {+ "events": [+ {+ "type": "continue_conversation",+ "humanFriendlyMessage": "Save order",+ "params": {+ "context": {+ "orderId": 42,+ "tags": [+ "rush"+ ]+ }+ }+ },+ {+ "type": "continue_conversation",+ "humanFriendlyMessage": "Pick zero",+ "params": {+ "context": 0+ }+ }+ ]+ }+}diff --git a/spec/fixtures/1.0/actions/004-event-form-state-per-action/expected.json b/spec/fixtures/1.0/actions/004-event-form-state-per-action/expected.jsonnew file mode 100644index 000000000..c9bee8e43--- /dev/null+++ b/spec/fixtures/1.0/actions/004-event-form-state-per-action/expected.json@@ -0,0 +1,39 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Button",+ "props": {+ "label": "Send",+ "action": {+ "actions": [+ {+ "action": "Set",+ "args": [+ "$note",+ "new"+ ]+ },+ {+ "action": "ToAssistant",+ "args": [+ "Send"+ ]+ }+ ]+ }+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$note": "old"+ }+}diff --git a/spec/fixtures/1.0/actions/004-event-form-state-per-action/input.oui b/spec/fixtures/1.0/actions/004-event-form-state-per-action/input.ouinew file mode 100644index 000000000..d7aa43f04--- /dev/null+++ b/spec/fixtures/1.0/actions/004-event-form-state-per-action/input.oui@@ -0,0 +1,3 @@+$note = "old"+root = Stack([send])+send = Button("Send", Action([@Set($note, "new"), @ToAssistant("Send")]))diff --git a/spec/fixtures/1.0/actions/004-event-form-state-per-action/interactions.json b/spec/fixtures/1.0/actions/004-event-form-state-per-action/interactions.jsonnew file mode 100644index 000000000..9462bdd13--- /dev/null+++ b/spec/fixtures/1.0/actions/004-event-form-state-per-action/interactions.json@@ -0,0 +1,21 @@+{+ "interactions": [+ {+ "click": "send"+ }+ ],+ "expected": {+ "events": [+ {+ "type": "continue_conversation",+ "humanFriendlyMessage": "Send",+ "formState": {+ "$note": "new"+ }+ }+ ],+ "state": {+ "$note": "new"+ }+ }+}diff --git a/spec/fixtures/1.0/actions/006-query-rerun-on-state/expected.json b/spec/fixtures/1.0/actions/006-query-rerun-on-state/expected.jsonnew file mode 100644index 000000000..bf2e788dc--- /dev/null+++ b/spec/fixtures/1.0/actions/006-query-rerun-on-state/expected.json@@ -0,0 +1,33 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Input",+ "props": {+ "name": "status",+ "placeholder": "Status",+ "value": {+ "$binding": "$status"+ }+ }+ },+ {+ "type": "Metric",+ "props": {+ "label": "Tickets",+ "value": 0+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$status": "open"+ }+}diff --git a/spec/fixtures/1.0/actions/006-query-rerun-on-state/input.oui b/spec/fixtures/1.0/actions/006-query-rerun-on-state/input.ouinew file mode 100644index 000000000..c3d710f55--- /dev/null+++ b/spec/fixtures/1.0/actions/006-query-rerun-on-state/input.oui@@ -0,0 +1,4 @@+$status = "open"+root = Stack([filter, Metric("Tickets", @Count(tickets.rows))])+filter = Input("status", "Status", $status)+tickets = Query("listTickets", {status: $status}, {rows: []})diff --git a/spec/fixtures/1.0/actions/006-query-rerun-on-state/interactions.json b/spec/fixtures/1.0/actions/006-query-rerun-on-state/interactions.jsonnew file mode 100644index 000000000..3a1d62efb--- /dev/null+++ b/spec/fixtures/1.0/actions/006-query-rerun-on-state/interactions.json@@ -0,0 +1,36 @@+{+ "interactions": [+ {+ "tool": "listTickets",+ "result": {+ "rows": []+ }+ },+ {+ "type": [+ "filter",+ "closed"+ ]+ }+ ],+ "expected": {+ "events": [],+ "state": {+ "$status": "closed"+ },+ "toolCalls": [+ {+ "tool": "listTickets",+ "args": {+ "status": "open"+ }+ },+ {+ "tool": "listTickets",+ "args": {+ "status": "closed"+ }+ }+ ]+ }+}diff --git a/spec/fixtures/1.0/actions/007-mutation-run/expected.json b/spec/fixtures/1.0/actions/007-mutation-run/expected.jsonnew file mode 100644index 000000000..8048b3db0--- /dev/null+++ b/spec/fixtures/1.0/actions/007-mutation-run/expected.json@@ -0,0 +1,38 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Button",+ "props": {+ "label": "Create",+ "action": {+ "actions": [+ {+ "action": "Run",+ "args": [+ "newTicket"+ ]+ },+ {+ "action": "ToAssistant",+ "args": [+ "Created"+ ]+ }+ ]+ }+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$title": "Bug"+ }+}diff --git a/spec/fixtures/1.0/actions/007-mutation-run/input.oui b/spec/fixtures/1.0/actions/007-mutation-run/input.ouinew file mode 100644index 000000000..3fc1cf45f--- /dev/null+++ b/spec/fixtures/1.0/actions/007-mutation-run/input.oui@@ -0,0 +1,4 @@+$title = "Bug"+root = Stack([create])+newTicket = Mutation("createTicket", {title: $title})+create = Button("Create", Action([@Run(newTicket), @ToAssistant("Created")]))diff --git a/spec/fixtures/1.0/actions/007-mutation-run/interactions.json b/spec/fixtures/1.0/actions/007-mutation-run/interactions.jsonnew file mode 100644index 000000000..1804e1e32--- /dev/null+++ b/spec/fixtures/1.0/actions/007-mutation-run/interactions.json@@ -0,0 +1,29 @@+{+ "interactions": [+ {+ "tool": "createTicket",+ "result": {+ "id": 7+ }+ },+ {+ "click": "create"+ }+ ],+ "expected": {+ "events": [+ {+ "type": "continue_conversation",+ "humanFriendlyMessage": "Created"+ }+ ],+ "toolCalls": [+ {+ "tool": "createTicket",+ "args": {+ "title": "Bug"+ }+ }+ ]+ }+}diff --git a/spec/fixtures/1.0/actions/008-tool-not-found-stops-plan/expected.json b/spec/fixtures/1.0/actions/008-tool-not-found-stops-plan/expected.jsonnew file mode 100644index 000000000..8048b3db0--- /dev/null+++ b/spec/fixtures/1.0/actions/008-tool-not-found-stops-plan/expected.json@@ -0,0 +1,38 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Button",+ "props": {+ "label": "Create",+ "action": {+ "actions": [+ {+ "action": "Run",+ "args": [+ "newTicket"+ ]+ },+ {+ "action": "ToAssistant",+ "args": [+ "Created"+ ]+ }+ ]+ }+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$title": "Bug"+ }+}diff --git a/spec/fixtures/1.0/actions/008-tool-not-found-stops-plan/input.oui b/spec/fixtures/1.0/actions/008-tool-not-found-stops-plan/input.ouinew file mode 100644index 000000000..3fc1cf45f--- /dev/null+++ b/spec/fixtures/1.0/actions/008-tool-not-found-stops-plan/input.oui@@ -0,0 +1,4 @@+$title = "Bug"+root = Stack([create])+newTicket = Mutation("createTicket", {title: $title})+create = Button("Create", Action([@Run(newTicket), @ToAssistant("Created")]))diff --git a/spec/fixtures/1.0/actions/008-tool-not-found-stops-plan/interactions.json b/spec/fixtures/1.0/actions/008-tool-not-found-stops-plan/interactions.jsonnew file mode 100644index 000000000..cb661a352--- /dev/null+++ b/spec/fixtures/1.0/actions/008-tool-not-found-stops-plan/interactions.json@@ -0,0 +1,11 @@+{+ "interactions": [+ {+ "click": "create"+ }+ ],+ "expected": {+ "events": [],+ "toolCalls": []+ }+}diff --git a/spec/fixtures/1.0/actions/009-custom-action/expected.json b/spec/fixtures/1.0/actions/009-custom-action/expected.jsonnew file mode 100644index 000000000..6b829512b--- /dev/null+++ b/spec/fixtures/1.0/actions/009-custom-action/expected.json@@ -0,0 +1,67 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Button",+ "props": {+ "label": "Copy",+ "action": {+ "actions": [+ {+ "action": "CopyToClipboard",+ "args": [+ "hello"+ ]+ }+ ]+ }+ }+ },+ {+ "type": "Button",+ "props": {+ "label": "Both",+ "action": {+ "actions": [+ {+ "action": "CopyToClipboard",+ "args": [+ "a b"+ ]+ },+ {+ "action": "ToAssistant",+ "args": [+ "Copied"+ ]+ }+ ]+ }+ }+ },+ {+ "type": "Button",+ "props": {+ "label": "Share",+ "share": {+ "actions": [+ {+ "action": "CopyToClipboard",+ "args": [+ "link"+ ]+ }+ ]+ }+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/actions/009-custom-action/input.oui b/spec/fixtures/1.0/actions/009-custom-action/input.ouinew file mode 100644index 000000000..b51b81129--- /dev/null+++ b/spec/fixtures/1.0/actions/009-custom-action/input.oui@@ -0,0 +1,4 @@+root = Stack([copy, both, share])+copy = Button("Copy", @CopyToClipboard("hello"))+both = Button("Both", Action([@CopyToClipboard("a b"), @ToAssistant("Copied")]))+share = Button("Share", null, null, @CopyToClipboard("link"))diff --git a/spec/fixtures/1.0/actions/009-custom-action/interactions.json b/spec/fixtures/1.0/actions/009-custom-action/interactions.jsonnew file mode 100644index 000000000..8bc48cbcb--- /dev/null+++ b/spec/fixtures/1.0/actions/009-custom-action/interactions.json@@ -0,0 +1,32 @@+{+ "interactions": [+ {+ "click": "copy"+ },+ {+ "click": "both"+ }+ ],+ "expected": {+ "events": [+ {+ "type": "CopyToClipboard",+ "params": {+ "text": "hello"+ },+ "humanFriendlyMessage": ""+ },+ {+ "type": "CopyToClipboard",+ "params": {+ "text": "a b"+ },+ "humanFriendlyMessage": ""+ },+ {+ "type": "continue_conversation",+ "humanFriendlyMessage": "Copied"+ }+ ]+ }+}diff --git a/spec/fixtures/1.0/actions/010-one-action-by-reference/expected.json b/spec/fixtures/1.0/actions/010-one-action-by-reference/expected.jsonnew file mode 100644index 000000000..d5de66982--- /dev/null+++ b/spec/fixtures/1.0/actions/010-one-action-by-reference/expected.json@@ -0,0 +1,48 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Button",+ "props": {+ "label": "Go",+ "action": {+ "actions": [+ {+ "action": "OpenUrl",+ "args": [+ "https://openui.com"+ ]+ }+ ]+ }+ }+ },+ {+ "type": "Button",+ "props": {+ "label": "Ask",+ "action": {+ "actions": [+ {+ "action": "ToAssistant",+ "args": [+ "Docs please"+ ]+ }+ ]+ }+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$mode": "docs"+ }+}diff --git a/spec/fixtures/1.0/actions/010-one-action-by-reference/input.oui b/spec/fixtures/1.0/actions/010-one-action-by-reference/input.ouinew file mode 100644index 000000000..b02341943--- /dev/null+++ b/spec/fixtures/1.0/actions/010-one-action-by-reference/input.oui@@ -0,0 +1,5 @@+$mode = "docs"+root = Stack([go, ask])+docsStep = @OpenUrl("https://openui.com")+go = Button("Go", docsStep)+ask = Button("Ask", $mode == "docs" ? @ToAssistant("Docs please") : null)diff --git a/spec/fixtures/1.0/actions/010-one-action-by-reference/interactions.json b/spec/fixtures/1.0/actions/010-one-action-by-reference/interactions.jsonnew file mode 100644index 000000000..20010593f--- /dev/null+++ b/spec/fixtures/1.0/actions/010-one-action-by-reference/interactions.json@@ -0,0 +1,25 @@+{+ "interactions": [+ {+ "click": "go"+ },+ {+ "click": "ask"+ }+ ],+ "expected": {+ "events": [+ {+ "type": "open_url",+ "humanFriendlyMessage": "",+ "params": {+ "url": "https://openui.com"+ }+ },+ {+ "type": "continue_conversation",+ "humanFriendlyMessage": "Docs please"+ }+ ]+ }+}diff --git a/spec/fixtures/1.0/actions/011-action-list-is-data/expected.json b/spec/fixtures/1.0/actions/011-action-list-is-data/expected.jsonnew file mode 100644index 000000000..ff611195d--- /dev/null+++ b/spec/fixtures/1.0/actions/011-action-list-is-data/expected.json@@ -0,0 +1,45 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Button",+ "props": {+ "label": "Save",+ "action": [+ {+ "actions": [+ {+ "action": "Set",+ "args": [+ "$saved",+ true+ ]+ }+ ]+ },+ {+ "actions": [+ {+ "action": "ToAssistant",+ "args": [+ "Saved"+ ]+ }+ ]+ }+ ]+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$saved": false+ }+}diff --git a/spec/fixtures/1.0/actions/011-action-list-is-data/input.oui b/spec/fixtures/1.0/actions/011-action-list-is-data/input.ouinew file mode 100644index 000000000..6bfe48c66--- /dev/null+++ b/spec/fixtures/1.0/actions/011-action-list-is-data/input.oui@@ -0,0 +1,3 @@+$saved = false+root = Stack([save])+save = Button("Save", [@Set($saved, true), @ToAssistant("Saved")])diff --git a/spec/fixtures/1.0/actions/README.md b/spec/fixtures/1.0/actions/README.mdnew file mode 100644index 000000000..38d27d015--- /dev/null+++ b/spec/fixtures/1.0/actions/README.md@@ -0,0 +1,16 @@+# actions++These cases protect a client from running actions in the wrong order, sending host events in the wrong shape, treating a lone action differently from `Action([...])`, and getting the query and mutation lifecycle wrong. They cover [language.md section 6](../../../language.md#6-data-and-actions) (6.1 to 6.4) and [prompt.md section 6.3](../../../prompt.md#63-action-events). Most cases also have `interactions.json`, which a runner replays against a mounted program. Number 005 is not used.++| Case | What it checks | Spec |+| --- | --- | --- |+| 001-several-actions (+ interactions) | `Action([...])` with @Set, @Reset, and @ToAssistant: a click runs the actions in order, so `$n` becomes 5, `$m` goes back to its default 7, and one `continue_conversation` event is sent. | [6.3](../../../language.md#63-actions) |+| 002-one-action (+ interactions) | Buttons given a lone @ToAssistant, @Set, or @OpenUrl with no `Action` wrapper: each is an Action of one action, and the clicks send `continue_conversation`, write `$sel`, and send `open_url`. | [6.3](../../../language.md#63-actions) |+| 003-event-context-any-value (+ interactions) | The second argument of @ToAssistant, an object in one button and the number 0 in the other, reaches the host unchanged in `params.context`. | [6.3](../../../language.md#63-actions), [prompt 6.3](../../../prompt.md#63-action-events) |+| 004-event-form-state-per-action (+ interactions) | `@Set($note, "new")` before @ToAssistant in one `Action([...])`: the event's form state already shows "new". | [6.3](../../../language.md#63-actions) |+| 006-query-rerun-on-state (+ interactions) | Typing into an Input bound to `$status`, which is written literally in the Query args, runs the query again with "closed". | [6.1](../../../language.md#61-query-lifecycle), [5.2](../../../language.md#52-two-way-binding) |+| 007-mutation-run (+ interactions) | `@Run(newTicket)` calls the mutation tool with the current `$title`, then the following @ToAssistant sends its event. | [6.2](../../../language.md#62-mutation-lifecycle), [6.3](../../../language.md#63-actions) |+| 008-tool-not-found-stops-plan (+ interactions) | The same program with no `createTicket` tool: the mutation fails with `tool-not-found`, nothing crashes, and the remaining @ToAssistant does not run, so there are no events and no tool calls. | [6.3](../../../language.md#63-actions), [6.4](../../../language.md#64-tool-resolution) |+| 009-custom-action (+ interactions) | The library action @CopyToClipboard alone, inside `Action([...])`, and in the restricted `share` prop: each click sends an event with `type: "CopyToClipboard"`, `params.text`, and an empty message. | [6.3](../../../language.md#63-actions), [prompt 2.5](../../../prompt.md#25-custom-functions-and-actions) |+| 010-one-action-by-reference (+ interactions) | A lone @OpenUrl bound to its own statement and passed by reference, and a lone @ToAssistant chosen by a ternary: both work as an Action of one action. | [6.3](../../../language.md#63-actions) |+| 011-action-list-is-data | `[@Set(...), @ToAssistant(...)]` without `Action` is plain data: the Button receives a list of two one-action Actions, and no error is reported. | [6.3](../../../language.md#63-actions) |diff --git a/spec/fixtures/1.0/editing/001-replace-and-add/expected.json b/spec/fixtures/1.0/editing/001-replace-and-add/expected.jsonnew file mode 100644index 000000000..b564a5183--- /dev/null+++ b/spec/fixtures/1.0/editing/001-replace-and-add/expected.json@@ -0,0 +1,37 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "A2"+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "B"+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "C"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "statements": [+ "root",+ "a",+ "b",+ "c"+ ]+}diff --git a/spec/fixtures/1.0/editing/001-replace-and-add/input.oui b/spec/fixtures/1.0/editing/001-replace-and-add/input.ouinew file mode 100644index 000000000..03241ab46--- /dev/null+++ b/spec/fixtures/1.0/editing/001-replace-and-add/input.oui@@ -0,0 +1,3 @@+root = Stack([a, b])+a = Text("A")+b = Text("B")diff --git a/spec/fixtures/1.0/editing/001-replace-and-add/patch.oui b/spec/fixtures/1.0/editing/001-replace-and-add/patch.ouinew file mode 100644index 000000000..9d41e251e--- /dev/null+++ b/spec/fixtures/1.0/editing/001-replace-and-add/patch.oui@@ -0,0 +1,3 @@+root = Stack([a, b, c])+a = Text("A2")+c = Text("C")diff --git a/spec/fixtures/1.0/editing/002-delete-and-gc/expected.json b/spec/fixtures/1.0/editing/002-delete-and-gc/expected.jsonnew file mode 100644index 000000000..54be43eb0--- /dev/null+++ b/spec/fixtures/1.0/editing/002-delete-and-gc/expected.json@@ -0,0 +1,27 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "A"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "statements": [+ "root",+ "$x",+ "a"+ ],+ "state": {+ "$x": 1+ }+}diff --git a/spec/fixtures/1.0/editing/002-delete-and-gc/input.oui b/spec/fixtures/1.0/editing/002-delete-and-gc/input.ouinew file mode 100644index 000000000..7e18876b2--- /dev/null+++ b/spec/fixtures/1.0/editing/002-delete-and-gc/input.oui@@ -0,0 +1,5 @@+root = Stack([a, b, c])+$x = 1+a = Text("A")+b = Text("B")+c = Text("C")diff --git a/spec/fixtures/1.0/editing/002-delete-and-gc/patch.oui b/spec/fixtures/1.0/editing/002-delete-and-gc/patch.ouinew file mode 100644index 000000000..9890c8cd5--- /dev/null+++ b/spec/fixtures/1.0/editing/002-delete-and-gc/patch.oui@@ -0,0 +1,2 @@+root = Stack([a])+b = nulldiff --git a/spec/fixtures/1.0/editing/003-state-delete/expected.json b/spec/fixtures/1.0/editing/003-state-delete/expected.jsonnew file mode 100644index 000000000..bd39393fd--- /dev/null+++ b/spec/fixtures/1.0/editing/003-state-delete/expected.json@@ -0,0 +1,24 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "A"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "statements": [+ "root",+ "a"+ ],+ "state": {}+}diff --git a/spec/fixtures/1.0/editing/003-state-delete/input.oui b/spec/fixtures/1.0/editing/003-state-delete/input.ouinew file mode 100644index 000000000..0ccc0b56f--- /dev/null+++ b/spec/fixtures/1.0/editing/003-state-delete/input.oui@@ -0,0 +1,3 @@+root = Stack([a])+$x = 1+a = Text("A")diff --git a/spec/fixtures/1.0/editing/003-state-delete/patch.oui b/spec/fixtures/1.0/editing/003-state-delete/patch.ouinew file mode 100644index 000000000..d65cf3a4f--- /dev/null+++ b/spec/fixtures/1.0/editing/003-state-delete/patch.oui@@ -0,0 +1 @@+$x = nulldiff --git a/spec/fixtures/1.0/editing/005-fenced-patch/expected.json b/spec/fixtures/1.0/editing/005-fenced-patch/expected.jsonnew file mode 100644index 000000000..38ce92e14--- /dev/null+++ b/spec/fixtures/1.0/editing/005-fenced-patch/expected.json@@ -0,0 +1,30 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "A2"+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "B"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "statements": [+ "root",+ "a",+ "b"+ ]+}diff --git a/spec/fixtures/1.0/editing/005-fenced-patch/input.oui b/spec/fixtures/1.0/editing/005-fenced-patch/input.ouinew file mode 100644index 000000000..03241ab46--- /dev/null+++ b/spec/fixtures/1.0/editing/005-fenced-patch/input.oui@@ -0,0 +1,3 @@+root = Stack([a, b])+a = Text("A")+b = Text("B")diff --git a/spec/fixtures/1.0/editing/005-fenced-patch/patch.oui b/spec/fixtures/1.0/editing/005-fenced-patch/patch.ouinew file mode 100644index 000000000..3f51873e4--- /dev/null+++ b/spec/fixtures/1.0/editing/005-fenced-patch/patch.oui@@ -0,0 +1,5 @@+Sure! I changed the first line, don't worry.+```openui+a = Text("A2")+```+Let me know if you want more.diff --git a/spec/fixtures/1.0/editing/006-no-root-statement-no-gc/expected.json b/spec/fixtures/1.0/editing/006-no-root-statement-no-gc/expected.jsonnew file mode 100644index 000000000..96e74f5ab--- /dev/null+++ b/spec/fixtures/1.0/editing/006-no-root-statement-no-gc/expected.json@@ -0,0 +1,30 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "A"+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "no-root"+ }+ ],+ "unresolved": [],+ "orphans": [+ "x"+ ],+ "incomplete": false,+ "statements": [+ "page",+ "a",+ "x"+ ]+}diff --git a/spec/fixtures/1.0/editing/006-no-root-statement-no-gc/input.oui b/spec/fixtures/1.0/editing/006-no-root-statement-no-gc/input.ouinew file mode 100644index 000000000..d6463e4a3--- /dev/null+++ b/spec/fixtures/1.0/editing/006-no-root-statement-no-gc/input.oui@@ -0,0 +1,3 @@+page = Stack([a])+a = Text("A")+x = Text("X")diff --git a/spec/fixtures/1.0/editing/006-no-root-statement-no-gc/patch.oui b/spec/fixtures/1.0/editing/006-no-root-statement-no-gc/patch.ouinew file mode 100644index 000000000..e33b8c715--- /dev/null+++ b/spec/fixtures/1.0/editing/006-no-root-statement-no-gc/patch.oui@@ -0,0 +1 @@+x = Text("X2")diff --git a/spec/fixtures/1.0/editing/README.md b/spec/fixtures/1.0/editing/README.mdnew file mode 100644index 000000000..8c53be710--- /dev/null+++ b/spec/fixtures/1.0/editing/README.md@@ -0,0 +1,11 @@+# editing++These cases protect a client from merging an edit-mode reply wrongly: replacing, appending, and deleting statements by name, removing what `root` no longer reaches, and merging only the fenced part of a reply. They cover [language.md section 7](../../../language.md#7-incremental-editing) and [prompt.md section 6.4](../../../prompt.md#64-edit-mode). Each case has `input.oui` (the current program), `patch.oui` (the reply), and the expected merged statements. Numbers 004 and 007 are not used.++| Case | What it checks | Spec |+| --- | --- | --- |+| 001-replace-and-add | The patch replaces `root` and `a` and adds `c`: `b` is kept, `c` is appended at the end, and the page shows A2, B, C. | [7](../../../language.md#7-incremental-editing) |+| 002-delete-and-gc | `b = null` deletes `b`, `c` is removed because `root` no longer reaches it, and the state declaration `$x` is kept. | [7](../../../language.md#7-incremental-editing) |+| 003-state-delete | `$x = null` deletes the state declaration, so the merged program has no `$x` default. | [7](../../../language.md#7-incremental-editing), [5.1](../../../language.md#51-the-state-store-and-what-is-reactive) |+| 005-fenced-patch | A reply of prose around an `openui` fence: only the fenced statement is merged, and the prose is ignored. | [7](../../../language.md#7-incremental-editing), [1.2](../../../language.md#12-source-text) |+| 006-no-root-statement-no-gc | With no `root` statement nothing is removed: `x` is replaced and kept, `page` renders as the fallback entry with a non-fatal `no-root`, and `x` is an orphan. | [7](../../../language.md#7-incremental-editing), [2.2](../../../language.md#22-entry) |diff --git a/spec/fixtures/1.0/entry/001-root-statement/expected.json b/spec/fixtures/1.0/entry/001-root-statement/expected.jsonnew file mode 100644index 000000000..4af6e1b9e--- /dev/null+++ b/spec/fixtures/1.0/entry/001-root-statement/expected.json@@ -0,0 +1,19 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "Hi"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/entry/001-root-statement/input.oui b/spec/fixtures/1.0/entry/001-root-statement/input.ouinew file mode 100644index 000000000..8aaae446a--- /dev/null+++ b/spec/fixtures/1.0/entry/001-root-statement/input.oui@@ -0,0 +1,2 @@+root = Stack([t])+t = Text("Hi")diff --git a/spec/fixtures/1.0/entry/002-first-calls-root-component/expected.json b/spec/fixtures/1.0/entry/002-first-calls-root-component/expected.jsonnew file mode 100644index 000000000..34a9bec56--- /dev/null+++ b/spec/fixtures/1.0/entry/002-first-calls-root-component/expected.json@@ -0,0 +1,23 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "Orders"+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "no-root"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/entry/002-first-calls-root-component/input.oui b/spec/fixtures/1.0/entry/002-first-calls-root-component/input.ouinew file mode 100644index 000000000..09d7dfed0--- /dev/null+++ b/spec/fixtures/1.0/entry/002-first-calls-root-component/input.oui@@ -0,0 +1,2 @@+page = Stack([title])+title = Text("Orders")diff --git a/spec/fixtures/1.0/entry/003-root-component-later/expected.json b/spec/fixtures/1.0/entry/003-root-component-later/expected.jsonnew file mode 100644index 000000000..34a9bec56--- /dev/null+++ b/spec/fixtures/1.0/entry/003-root-component-later/expected.json@@ -0,0 +1,23 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "Orders"+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "no-root"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/entry/003-root-component-later/input.oui b/spec/fixtures/1.0/entry/003-root-component-later/input.ouinew file mode 100644index 000000000..578203e95--- /dev/null+++ b/spec/fixtures/1.0/entry/003-root-component-later/input.oui@@ -0,0 +1,2 @@+title = Text("Orders")+page = Stack([title])diff --git a/spec/fixtures/1.0/entry/004-root-not-a-component/expected.json b/spec/fixtures/1.0/entry/004-root-not-a-component/expected.jsonnew file mode 100644index 000000000..178a74ef7--- /dev/null+++ b/spec/fixtures/1.0/entry/004-root-not-a-component/expected.json@@ -0,0 +1,11 @@+{+ "root": null,+ "errors": [+ {+ "code": "no-root"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/entry/004-root-not-a-component/input.oui b/spec/fixtures/1.0/entry/004-root-not-a-component/input.ouinew file mode 100644index 000000000..3e91954ac--- /dev/null+++ b/spec/fixtures/1.0/entry/004-root-not-a-component/input.oui@@ -0,0 +1 @@+root = "hello"diff --git a/spec/fixtures/1.0/entry/005-first-is-state-declaration/expected.json b/spec/fixtures/1.0/entry/005-first-is-state-declaration/expected.jsonnew file mode 100644index 000000000..c081028eb--- /dev/null+++ b/spec/fixtures/1.0/entry/005-first-is-state-declaration/expected.json@@ -0,0 +1,26 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "A"+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "no-root"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$tab": "a"+ }+}diff --git a/spec/fixtures/1.0/entry/005-first-is-state-declaration/input.oui b/spec/fixtures/1.0/entry/005-first-is-state-declaration/input.ouinew file mode 100644index 000000000..5fd638bc1--- /dev/null+++ b/spec/fixtures/1.0/entry/005-first-is-state-declaration/input.oui@@ -0,0 +1,2 @@+$tab = "a"+page = Stack([Text("A")])diff --git a/spec/fixtures/1.0/entry/006-ternary-root-multiline/expected.json b/spec/fixtures/1.0/entry/006-ternary-root-multiline/expected.jsonnew file mode 100644index 000000000..b86ab79ea--- /dev/null+++ b/spec/fixtures/1.0/entry/006-ternary-root-multiline/expected.json@@ -0,0 +1,15 @@+{+ "root": {+ "type": "Card",+ "props": {+ "title": "Light"+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$dark": false+ }+}diff --git a/spec/fixtures/1.0/entry/006-ternary-root-multiline/input.oui b/spec/fixtures/1.0/entry/006-ternary-root-multiline/input.ouinew file mode 100644index 000000000..f18716038--- /dev/null+++ b/spec/fixtures/1.0/entry/006-ternary-root-multiline/input.oui@@ -0,0 +1,6 @@+$dark = false+root = $dark+ ? darkPage+ : lightPage+darkPage = Card("Dark")+lightPage = Card("Light")diff --git a/spec/fixtures/1.0/entry/007-no-root-component-call/expected.json b/spec/fixtures/1.0/entry/007-no-root-component-call/expected.jsonnew file mode 100644index 000000000..178a74ef7--- /dev/null+++ b/spec/fixtures/1.0/entry/007-no-root-component-call/expected.json@@ -0,0 +1,11 @@+{+ "root": null,+ "errors": [+ {+ "code": "no-root"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/entry/007-no-root-component-call/input.oui b/spec/fixtures/1.0/entry/007-no-root-component-call/input.ouinew file mode 100644index 000000000..e8cd301f9--- /dev/null+++ b/spec/fixtures/1.0/entry/007-no-root-component-call/input.oui@@ -0,0 +1 @@+title = Text("Orders")diff --git a/spec/fixtures/1.0/entry/README.md b/spec/fixtures/1.0/entry/README.mdnew file mode 100644index 000000000..856f2671f--- /dev/null+++ b/spec/fixtures/1.0/entry/README.md@@ -0,0 +1,13 @@+# entry++These cases protect a client from rendering the wrong statement, or rendering nothing, when it picks the entry. The entry is the `root` statement, or else the first value statement that calls the library's root component (`Stack` in the test library), with a non-fatal `no-root`. They cover [language.md section 2.2](../../../language.md#22-entry) and the `no-root` row of [section 8.2](../../../language.md#82-error-codes).++| Case | What it checks | Spec |+| --- | --- | --- |+| 001-root-statement | `root = Stack([t])` renders with no errors. | [2.2](../../../language.md#22-entry) |+| 002-first-calls-root-component | No `root` statement: `page`, the first statement that calls `Stack`, renders with a non-fatal `no-root`. | [2.2](../../../language.md#22-entry) |+| 003-root-component-later | The same, with the `Stack` statement after a Text statement: the fallback entry is found wherever it is. | [2.2](../../../language.md#22-entry) |+| 004-root-not-a-component | `root = "hello"`: a fatal `no-root`, and nothing renders. | [2.2](../../../language.md#22-entry) |+| 005-first-is-state-declaration | A state declaration comes first and is never the entry: `page` renders with a non-fatal `no-root`, and `$tab` gets its default. | [2.2](../../../language.md#22-entry) |+| 006-ternary-root-multiline | `root` is a ternary over two component statements, written over three lines: with `$dark` false, `lightPage` renders with no errors. | [2.2](../../../language.md#22-entry), [1.4](../../../language.md#14-statements) |+| 007-no-root-component-call | The only statement calls Text, not `Stack`: a fatal `no-root`, nothing renders, and there are no orphans. | [2.2](../../../language.md#22-entry), [2.3](../../../language.md#23-references-and-hoisting) |diff --git a/spec/fixtures/1.0/errors/001-unknown-component-dropped/expected.json b/spec/fixtures/1.0/errors/001-unknown-component-dropped/expected.jsonnew file mode 100644index 000000000..52380fbcc--- /dev/null+++ b/spec/fixtures/1.0/errors/001-unknown-component-dropped/expected.json@@ -0,0 +1,24 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "a"+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "unknown-component",+ "statementId": "chart"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/errors/001-unknown-component-dropped/input.oui b/spec/fixtures/1.0/errors/001-unknown-component-dropped/input.ouinew file mode 100644index 000000000..38805ab4e--- /dev/null+++ b/spec/fixtures/1.0/errors/001-unknown-component-dropped/input.oui@@ -0,0 +1,2 @@+root = Stack([Text("a"), chart])+chart = Chart([1, 2])diff --git a/spec/fixtures/1.0/errors/002-unknown-function-null/expected.json b/spec/fixtures/1.0/errors/002-unknown-function-null/expected.jsonnew file mode 100644index 000000000..fef70e374--- /dev/null+++ b/spec/fixtures/1.0/errors/002-unknown-function-null/expected.json@@ -0,0 +1,24 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "was null"+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "unknown-function",+ "statementId": "t"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/errors/002-unknown-function-null/input.oui b/spec/fixtures/1.0/errors/002-unknown-function-null/input.ouinew file mode 100644index 000000000..25cb93c91--- /dev/null+++ b/spec/fixtures/1.0/errors/002-unknown-function-null/input.oui@@ -0,0 +1,2 @@+root = Stack([t])+t = Text(@Nope(1) == null ? "was null" : "not null")diff --git a/spec/fixtures/1.0/errors/003-no-root-unresolved-root/expected.json b/spec/fixtures/1.0/errors/003-no-root-unresolved-root/expected.jsonnew file mode 100644index 000000000..aeaaef920--- /dev/null+++ b/spec/fixtures/1.0/errors/003-no-root-unresolved-root/expected.json@@ -0,0 +1,15 @@+{+ "root": null,+ "errors": [+ {+ "code": "no-root"+ }+ ],+ "unresolved": [+ "main"+ ],+ "orphans": [+ "other"+ ],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/errors/003-no-root-unresolved-root/input.oui b/spec/fixtures/1.0/errors/003-no-root-unresolved-root/input.ouinew file mode 100644index 000000000..a53969875--- /dev/null+++ b/spec/fixtures/1.0/errors/003-no-root-unresolved-root/input.oui@@ -0,0 +1,2 @@+root = main+other = Stack([Text("x")])diff --git a/spec/fixtures/1.0/errors/005-shape-missing-required-metric/expected.json b/spec/fixtures/1.0/errors/005-shape-missing-required-metric/expected.jsonnew file mode 100644index 000000000..e976d8b1c--- /dev/null+++ b/spec/fixtures/1.0/errors/005-shape-missing-required-metric/expected.json@@ -0,0 +1,33 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "a"+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "missing-required",+ "statementId": "chart"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "errorObjects": [+ {+ "source": "parser",+ "code": "missing-required",+ "statementId": "chart",+ "component": "Metric",+ "path": "/value"+ }+ ]+}diff --git a/spec/fixtures/1.0/errors/005-shape-missing-required-metric/input.oui b/spec/fixtures/1.0/errors/005-shape-missing-required-metric/input.ouinew file mode 100644index 000000000..5404250b8--- /dev/null+++ b/spec/fixtures/1.0/errors/005-shape-missing-required-metric/input.oui@@ -0,0 +1,2 @@+root = Stack([Text("a"), chart])+chart = Metric("Revenue")diff --git a/spec/fixtures/1.0/errors/006-null-required-dropped/expected.json b/spec/fixtures/1.0/errors/006-null-required-dropped/expected.jsonnew file mode 100644index 000000000..253d3f424--- /dev/null+++ b/spec/fixtures/1.0/errors/006-null-required-dropped/expected.json@@ -0,0 +1,24 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "a"+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "null-required",+ "statementId": "bad"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/errors/006-null-required-dropped/input.oui b/spec/fixtures/1.0/errors/006-null-required-dropped/input.ouinew file mode 100644index 000000000..3922d03bd--- /dev/null+++ b/spec/fixtures/1.0/errors/006-null-required-dropped/input.oui@@ -0,0 +1,2 @@+root = Stack([Text("a"), bad])+bad = Text(null)diff --git a/spec/fixtures/1.0/errors/007-type-mismatch-enum/expected.json b/spec/fixtures/1.0/errors/007-type-mismatch-enum/expected.jsonnew file mode 100644index 000000000..dce680a21--- /dev/null+++ b/spec/fixtures/1.0/errors/007-type-mismatch-enum/expected.json@@ -0,0 +1,24 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Tag",+ "props": {+ "text": "x"+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "type-mismatch",+ "statementId": "t"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/errors/007-type-mismatch-enum/input.oui b/spec/fixtures/1.0/errors/007-type-mismatch-enum/input.ouinew file mode 100644index 000000000..05c7c3f3a--- /dev/null+++ b/spec/fixtures/1.0/errors/007-type-mismatch-enum/input.oui@@ -0,0 +1,2 @@+root = Stack([t])+t = Tag("x", "purple")diff --git a/spec/fixtures/1.0/errors/008-type-mismatch-bare-list/expected.json b/spec/fixtures/1.0/errors/008-type-mismatch-bare-list/expected.jsonnew file mode 100644index 000000000..5f5689770--- /dev/null+++ b/spec/fixtures/1.0/errors/008-type-mismatch-bare-list/expected.json@@ -0,0 +1,24 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Card",+ "props": {+ "title": "T"+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "type-mismatch",+ "statementId": "card"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/errors/008-type-mismatch-bare-list/input.oui b/spec/fixtures/1.0/errors/008-type-mismatch-bare-list/input.ouinew file mode 100644index 000000000..0e890a2ab--- /dev/null+++ b/spec/fixtures/1.0/errors/008-type-mismatch-bare-list/input.oui@@ -0,0 +1,2 @@+root = Stack([card])+card = Card("T", Text("a"))diff --git a/spec/fixtures/1.0/errors/009-excess-args-dropped/expected.json b/spec/fixtures/1.0/errors/009-excess-args-dropped/expected.jsonnew file mode 100644index 000000000..64feb7c77--- /dev/null+++ b/spec/fixtures/1.0/errors/009-excess-args-dropped/expected.json@@ -0,0 +1,25 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "a",+ "variant": "body"+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "excess-args",+ "statementId": "t"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/errors/009-excess-args-dropped/input.oui b/spec/fixtures/1.0/errors/009-excess-args-dropped/input.ouinew file mode 100644index 000000000..b6b15f1a2--- /dev/null+++ b/spec/fixtures/1.0/errors/009-excess-args-dropped/input.oui@@ -0,0 +1,2 @@+root = Stack([t])+t = Text("a", "body", "extra")diff --git a/spec/fixtures/1.0/errors/010-inline-reserved-array/expected.json b/spec/fixtures/1.0/errors/010-inline-reserved-array/expected.jsonnew file mode 100644index 000000000..e71341f7e--- /dev/null+++ b/spec/fixtures/1.0/errors/010-inline-reserved-array/expected.json@@ -0,0 +1,24 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "a"+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "inline-reserved",+ "statementId": "root"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/errors/010-inline-reserved-array/input.oui b/spec/fixtures/1.0/errors/010-inline-reserved-array/input.ouinew file mode 100644index 000000000..10be4b6d1--- /dev/null+++ b/spec/fixtures/1.0/errors/010-inline-reserved-array/input.oui@@ -0,0 +1 @@+root = Stack([Text("a"), Query("listTickets", {}, {})])diff --git a/spec/fixtures/1.0/errors/012-validate-array-elements/expected.json b/spec/fixtures/1.0/errors/012-validate-array-elements/expected.jsonnew file mode 100644index 000000000..0f54b3ef4--- /dev/null+++ b/spec/fixtures/1.0/errors/012-validate-array-elements/expected.json@@ -0,0 +1,27 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "a"+ }+ },+ null+ ]+ }+ },+ "errors": [+ {+ "code": "unknown-component",+ "statementId": "root"+ }+ ],+ "unresolved": [+ "missing"+ ],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/errors/012-validate-array-elements/input.oui b/spec/fixtures/1.0/errors/012-validate-array-elements/input.ouinew file mode 100644index 000000000..9c7e4b1d2--- /dev/null+++ b/spec/fixtures/1.0/errors/012-validate-array-elements/input.oui@@ -0,0 +1 @@+root = Stack([Text("a"), Chart(1), null, missing])diff --git a/spec/fixtures/1.0/errors/013-validate-component-slot-data/expected.json b/spec/fixtures/1.0/errors/013-validate-component-slot-data/expected.jsonnew file mode 100644index 000000000..d856c5eed--- /dev/null+++ b/spec/fixtures/1.0/errors/013-validate-component-slot-data/expected.json@@ -0,0 +1,46 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "a"+ }+ },+ {+ "type": "Card",+ "props": {+ "title": "T",+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "b"+ }+ }+ ]+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "type-mismatch",+ "statementId": "root"+ },+ {+ "code": "type-mismatch",+ "statementId": "root"+ },+ {+ "code": "type-mismatch",+ "statementId": "card"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/errors/013-validate-component-slot-data/input.oui b/spec/fixtures/1.0/errors/013-validate-component-slot-data/input.ouinew file mode 100644index 000000000..e0cecc211--- /dev/null+++ b/spec/fixtures/1.0/errors/013-validate-component-slot-data/input.oui@@ -0,0 +1,2 @@+root = Stack([Text("a"), "plain", {title: "x"}, card])+card = Card("T", [Text("b"), 5])diff --git a/spec/fixtures/1.0/errors/014-function-literal-args/expected.json b/spec/fixtures/1.0/errors/014-function-literal-args/expected.jsonnew file mode 100644index 000000000..1ffd71368--- /dev/null+++ b/spec/fixtures/1.0/errors/014-function-literal-args/expected.json@@ -0,0 +1,45 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Input",+ "props": {+ "name": "a",+ "placeholder": "X"+ }+ },+ {+ "type": "Input",+ "props": {+ "name": "b"+ }+ },+ {+ "type": "Input",+ "props": {+ "name": "c"+ }+ }+ ]+ }+ },+ "errors": [+ {+ "code": "excess-args",+ "statementId": "a"+ },+ {+ "code": "type-mismatch",+ "statementId": "b"+ },+ {+ "code": "missing-required",+ "statementId": "c"+ }+ ],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/errors/014-function-literal-args/input.oui b/spec/fixtures/1.0/errors/014-function-literal-args/input.ouinew file mode 100644index 000000000..ad30d8cbc--- /dev/null+++ b/spec/fixtures/1.0/errors/014-function-literal-args/input.oui@@ -0,0 +1,4 @@+root = Stack([a, b, c])+a = Input("a", @Upper("x", "y"))+b = Input("b", @Upper(3))+c = Input("c", @Upper())diff --git a/spec/fixtures/1.0/errors/README.md b/spec/fixtures/1.0/errors/README.mdnew file mode 100644index 000000000..159bcb05e--- /dev/null+++ b/spec/fixtures/1.0/errors/README.md@@ -0,0 +1,18 @@+# errors++These cases protect a client from crashing, dropping too much, or reporting the wrong code when a program has a mistake. A mistake removes the smallest unit (a prop, a component, or a statement), the rest renders, and each removal is reported with its code and statement. They cover [language.md section 8](../../../language.md#8-errors-and-recovery), the argument checks of [section 3.6](../../../language.md#36-custom-functions), and [prompt.md section 6.2](../../../prompt.md#62-error-feedback). Numbers 004 and 011 are not used.++| Case | What it checks | Spec |+| --- | --- | --- |+| 001-unknown-component-dropped | `Chart` is not in the library: it is dropped from the Stack, the Text still renders, and `unknown-component` is reported on `chart`. | [8.2](../../../language.md#82-error-codes), [8.4](../../../language.md#84-component-validation) |+| 002-unknown-function-null | `@Nope(1)` evaluates to null, so the Text shows "was null", and `unknown-function` is reported; the statement is kept. | [3.6](../../../language.md#36-custom-functions), [8.2](../../../language.md#82-error-codes) |+| 003-no-root-unresolved-root | `root = main` with no `main` statement: a fatal `no-root`, nothing renders, `main` is unresolved, and `other` is listed as an orphan. | [2.2](../../../language.md#22-entry), [8.2](../../../language.md#82-error-codes) |+| 005-shape-missing-required-metric | `Metric("Revenue")` has no required `value`: the Metric is dropped, and the error object has `source: "parser"`, `component: "Metric"`, and `path: "/value"`. | [8.3](../../../language.md#83-the-error-object) |+| 006-null-required-dropped | `Text(null)`: `null-required`, and the Text is dropped. | [8.2](../../../language.md#82-error-codes) |+| 007-type-mismatch-enum | `Tag("x", "purple")` with a color outside the enum: `type-mismatch`, the optional prop is removed, and the Tag renders. | [8.2](../../../language.md#82-error-codes) |+| 008-type-mismatch-bare-list | Card children given a bare Text instead of `[...]`: `type-mismatch`, the children prop is removed, and the Card renders. | [8.4](../../../language.md#84-component-validation) |+| 009-excess-args-dropped | `Text` with three arguments: the third is dropped, `excess-args` is reported, and the Text renders. | [8.2](../../../language.md#82-error-codes) |+| 010-inline-reserved-array | `Query(...)` as an array element: `inline-reserved` on `root`, and the element is left out. | [2.1](../../../language.md#21-statement-kinds), [8.2](../../../language.md#82-error-codes) |+| 012-validate-array-elements | In a children array, an unknown component is dropped with an error, an explicit `null` is kept, and an unresolved reference is left out. | [8.4](../../../language.md#84-component-validation) |+| 013-validate-component-slot-data | A string and an object in Stack children and a number in Card children: one `type-mismatch` each, and the values are left out. | [8.4](../../../language.md#84-component-validation) |+| 014-function-literal-args | Literal arguments to @Upper: an extra argument is dropped with `excess-args` (result "X"), a number gives `type-mismatch`, and no argument gives `missing-required`; the last two calls evaluate to null, so `placeholder` is absent. | [3.6](../../../language.md#36-custom-functions) |diff --git a/spec/fixtures/1.0/evaluation/001-kind-classify/expected.json b/spec/fixtures/1.0/evaluation/001-kind-classify/expected.jsonnew file mode 100644index 000000000..61a96e318--- /dev/null+++ b/spec/fixtures/1.0/evaluation/001-kind-classify/expected.json@@ -0,0 +1,47 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "Count: 2"+ }+ },+ {+ "type": "Button",+ "props": {+ "label": "Go",+ "action": {+ "actions": [+ {+ "action": "Set",+ "args": [+ "$count",+ 3+ ]+ }+ ]+ }+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "null"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [+ "unused"+ ],+ "incomplete": false,+ "state": {+ "$count": 2+ }+}diff --git a/spec/fixtures/1.0/evaluation/001-kind-classify/input.oui b/spec/fixtures/1.0/evaluation/001-kind-classify/input.ouinew file mode 100644index 000000000..7c42f3a09--- /dev/null+++ b/spec/fixtures/1.0/evaluation/001-kind-classify/input.oui@@ -0,0 +1,6 @@+root = Stack([Text(label), Button("Go", go), Text(Query("listTickets", {}, {}) == null ? "null" : "value")])+$count = 2+label = "Count: " + $count+go = Action([@Set($count, 3)])+data = Query("listTickets", {}, {rows: []})+unused = Text("x")diff --git a/spec/fixtures/1.0/evaluation/003-ref-cycle/expected.json b/spec/fixtures/1.0/evaluation/003-ref-cycle/expected.jsonnew file mode 100644index 000000000..819f93098--- /dev/null+++ b/spec/fixtures/1.0/evaluation/003-ref-cycle/expected.json@@ -0,0 +1,30 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Card",+ "props": {+ "title": "A",+ "children": [+ {+ "type": "Card",+ "props": {+ "title": "B",+ "children": []+ }+ }+ ]+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [+ "a"+ ],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/evaluation/003-ref-cycle/input.oui b/spec/fixtures/1.0/evaluation/003-ref-cycle/input.ouinew file mode 100644index 000000000..7d3357b2b--- /dev/null+++ b/spec/fixtures/1.0/evaluation/003-ref-cycle/input.oui@@ -0,0 +1,3 @@+root = Stack([a])+a = Card("A", [b])+b = Card("B", [a])diff --git a/spec/fixtures/1.0/evaluation/004-duplicate-later-wins/expected.json b/spec/fixtures/1.0/evaluation/004-duplicate-later-wins/expected.jsonnew file mode 100644index 000000000..1ce25ec6f--- /dev/null+++ b/spec/fixtures/1.0/evaluation/004-duplicate-later-wins/expected.json@@ -0,0 +1,19 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "second"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/evaluation/004-duplicate-later-wins/input.oui b/spec/fixtures/1.0/evaluation/004-duplicate-later-wins/input.ouinew file mode 100644index 000000000..0f4791020--- /dev/null+++ b/spec/fixtures/1.0/evaluation/004-duplicate-later-wins/input.oui@@ -0,0 +1,3 @@+root = Stack([t])+t = Text("first")+t = Text("second")diff --git a/spec/fixtures/1.0/evaluation/005-op-coerce-values/expected.json b/spec/fixtures/1.0/evaluation/005-op-coerce-values/expected.jsonnew file mode 100644index 000000000..3a55516ea--- /dev/null+++ b/spec/fixtures/1.0/evaluation/005-op-coerce-values/expected.json@@ -0,0 +1,56 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Table",+ "props": {+ "columns": [+ {+ "type": "Col",+ "props": {+ "label": "coerce",+ "data": [+ 10,+ 0,+ 2,+ 1,+ "a",+ true,+ true,+ false+ ]+ }+ },+ {+ "type": "Col",+ "props": {+ "label": "op",+ "data": [+ 0,+ 0,+ "a1",+ "3x",+ "fallback",+ 0,+ true,+ -3,+ true+ ]+ }+ }+ ]+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$u": null+ }+}diff --git a/spec/fixtures/1.0/evaluation/005-op-coerce-values/input.oui b/spec/fixtures/1.0/evaluation/005-op-coerce-values/input.ouinew file mode 100644index 000000000..f1d2da923--- /dev/null+++ b/spec/fixtures/1.0/evaluation/005-op-coerce-values/input.oui@@ -0,0 +1,3 @@+root = Stack([Table([c, o])])+c = Col("coerce", ["5" * 2, "abc" * 2, true + 1, null + 1, "a" + null, 5 == "5", "" == 0, null == 0])+o = Col("op", [7 / 0, 7 % 0, "a" + 1, 1 + 2 + "x", $u || "fallback", 0 && "no", !0, -"3", 3 >= "3"])diff --git a/spec/fixtures/1.0/evaluation/006-member-pluck-and-null/expected.json b/spec/fixtures/1.0/evaluation/006-member-pluck-and-null/expected.jsonnew file mode 100644index 000000000..fa98c8c2f--- /dev/null+++ b/spec/fixtures/1.0/evaluation/006-member-pluck-and-null/expected.json@@ -0,0 +1,53 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Table",+ "props": {+ "columns": [+ {+ "type": "Col",+ "props": {+ "label": "names",+ "data": [+ "a",+ "b"+ ]+ }+ },+ {+ "type": "Col",+ "props": {+ "label": "ns",+ "data": [+ 1,+ null+ ]+ }+ },+ {+ "type": "Col",+ "props": {+ "label": "misc",+ "data": [+ 2,+ "b",+ "v",+ null,+ null+ ]+ }+ }+ ]+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/evaluation/006-member-pluck-and-null/input.oui b/spec/fixtures/1.0/evaluation/006-member-pluck-and-null/input.ouinew file mode 100644index 000000000..789a6829a--- /dev/null+++ b/spec/fixtures/1.0/evaluation/006-member-pluck-and-null/input.oui@@ -0,0 +1,7 @@+root = Stack([Table([names, ns, misc])])+rows = [{name: "a", n: 1}, {name: "b"}]+o = {k: "v"}+nothing = null+names = Col("names", rows.name)+ns = Col("ns", rows.n)+misc = Col("misc", [rows.length, rows[1].name, o["k"], nothing.field, o[nothing]])diff --git a/spec/fixtures/1.0/evaluation/008-builtin-sort-locale/expected.json b/spec/fixtures/1.0/evaluation/008-builtin-sort-locale/expected.jsonnew file mode 100644index 000000000..bb804f783--- /dev/null+++ b/spec/fixtures/1.0/evaluation/008-builtin-sort-locale/expected.json@@ -0,0 +1,66 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Table",+ "props": {+ "columns": [+ {+ "type": "Col",+ "props": {+ "label": "sorted",+ "data": [+ [+ "a",+ "b",+ "B",+ "é",+ "Z"+ ],+ [+ "9",+ "10",+ "100"+ ],+ [+ {+ "n": 3,+ "id": "b"+ },+ {+ "n": 2,+ "id": "c"+ },+ {+ "n": 1,+ "id": "a"+ }+ ],+ "x",+ [+ {+ "k": null+ },+ {+ "k": "a"+ },+ {+ "k": "b"+ }+ ]+ ]+ }+ }+ ]+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/evaluation/008-builtin-sort-locale/input.oui b/spec/fixtures/1.0/evaluation/008-builtin-sort-locale/input.ouinew file mode 100644index 000000000..8c21848b7--- /dev/null+++ b/spec/fixtures/1.0/evaluation/008-builtin-sort-locale/input.oui@@ -0,0 +1,3 @@+root = Stack([Table([s])])+rows = [{n: 1, id: "a"}, {n: 3, id: "b"}, {n: 2, id: "c"}]+s = Col("sorted", [@Sort(["b", "B", "a", "é", "Z"], ""), @Sort(["10", "9", "100"], ""), @Sort(rows, "n", "desc"), @Sort("x", ""), @Sort([{k: "b"}, {k: null}, {k: "a"}], "k")])diff --git a/spec/fixtures/1.0/evaluation/010-function-registered/expected.json b/spec/fixtures/1.0/evaluation/010-function-registered/expected.jsonnew file mode 100644index 000000000..4013faa53--- /dev/null+++ b/spec/fixtures/1.0/evaluation/010-function-registered/expected.json@@ -0,0 +1,25 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "HI"+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "2"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/evaluation/010-function-registered/input.oui b/spec/fixtures/1.0/evaluation/010-function-registered/input.ouinew file mode 100644index 000000000..3749403f4--- /dev/null+++ b/spec/fixtures/1.0/evaluation/010-function-registered/input.oui@@ -0,0 +1 @@+root = Stack([Text(@Upper("hi")), Text(@Count([1, 2]) + "")])diff --git a/spec/fixtures/1.0/evaluation/011-function-null-required-arg/expected.json b/spec/fixtures/1.0/evaluation/011-function-null-required-arg/expected.jsonnew file mode 100644index 000000000..18a0f0345--- /dev/null+++ b/spec/fixtures/1.0/evaluation/011-function-null-required-arg/expected.json@@ -0,0 +1,33 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Input",+ "props": {+ "name": "a"+ }+ },+ {+ "type": "Input",+ "props": {+ "name": "b"+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "null"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [+ "missing"+ ],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/evaluation/011-function-null-required-arg/input.oui b/spec/fixtures/1.0/evaluation/011-function-null-required-arg/input.ouinew file mode 100644index 000000000..e5917e105--- /dev/null+++ b/spec/fixtures/1.0/evaluation/011-function-null-required-arg/input.oui@@ -0,0 +1,4 @@+root = Stack([a, b, t])+a = Input("a", @Upper($unset))+b = Input("b", @Upper(missing))+t = Text(@Upper($unset) == null ? "null" : "other")diff --git a/spec/fixtures/1.0/evaluation/012-kind-query-dollar-name/expected.json b/spec/fixtures/1.0/evaluation/012-kind-query-dollar-name/expected.jsonnew file mode 100644index 000000000..0da83d205--- /dev/null+++ b/spec/fixtures/1.0/evaluation/012-kind-query-dollar-name/expected.json@@ -0,0 +1,20 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Metric",+ "props": {+ "label": "n",+ "value": 0+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/evaluation/012-kind-query-dollar-name/input.oui b/spec/fixtures/1.0/evaluation/012-kind-query-dollar-name/input.ouinew file mode 100644index 000000000..38f0eb3ab--- /dev/null+++ b/spec/fixtures/1.0/evaluation/012-kind-query-dollar-name/input.oui@@ -0,0 +1,2 @@+$items = Query("listTickets", {}, {rows: []})+root = Stack([Metric("n", @Count($items.rows))])diff --git a/spec/fixtures/1.0/evaluation/README.md b/spec/fixtures/1.0/evaluation/README.mdnew file mode 100644index 000000000..01e416e86--- /dev/null+++ b/spec/fixtures/1.0/evaluation/README.md@@ -0,0 +1,15 @@+# evaluation++These cases protect a client from computing different values than other clients for the same program: how statements are classified, how references resolve, how operators coerce, and how built-in and custom functions behave. They cover [language.md sections 2.1, 2.3, and 2.4](../../../language.md#2-program-model) and [section 3](../../../language.md#3-evaluation). Numbers 002, 007, and 009 are not used.++| Case | What it checks | Spec |+| --- | --- | --- |+| 001-kind-classify | A Query inline in a computed expression is null with no error, a state default and an `Action` statement work by reference, the unused Text is an orphan, and the query statement `data` is not. | [2.1](../../../language.md#21-statement-kinds), [2.3](../../../language.md#23-references-and-hoisting) |+| 003-ref-cycle | `a` contains `b`, which contains `a`: the reference that closes the cycle is unresolved and left out of `b`'s children. | [2.3](../../../language.md#23-references-and-hoisting) |+| 004-duplicate-later-wins | `t` is defined twice: the later "second" renders. | [2.4](../../../language.md#24-duplicate-names) |+| 005-op-coerce-values | `toNumber` coercion, loose equality, `+` joining strings with null as "", division and modulo by 0 giving 0, `&&` and `||` returning the deciding operand, and unary operators on strings; the undeclared `$u` reads as null. | [3.1](../../../language.md#31-values-and-coercion), [3.2](../../../language.md#32-operators) |+| 006-member-pluck-and-null | `rows.name` plucks from every element (null where missing), `.length` counts, indexing reads arrays and objects, and member access or indexing with null gives null. | [3.3](../../../language.md#33-member-access-and-pluck) |+| 008-builtin-sort-locale | @Sort uses locale collation for strings (a, b, B, é, Z), compares numeric strings as numbers, sorts by field descending, returns a non-array unchanged, and sorts null as "". | [3.4](../../../language.md#34-built-in-functions) |+| 010-function-registered | The custom function @Upper runs ("HI"), and `@Count([1, 2]) + ""` gives "2". | [3.6](../../../language.md#36-custom-functions) |+| 011-function-null-required-arg | @Upper given an unset `$variable` or an unresolved reference evaluates to null with no error, so the prop is left out. | [3.6](../../../language.md#36-custom-functions) |+| 012-kind-query-dollar-name | `$items = Query(...)` is a query statement, and `$items.rows` reads the state store, not the result, so @Count gives 0 with no error. | [2.1](../../../language.md#21-statement-kinds) |diff --git a/spec/fixtures/1.0/grammar/003-fence-multiple-joined/expected.json b/spec/fixtures/1.0/grammar/003-fence-multiple-joined/expected.jsonnew file mode 100644index 000000000..a91af6d15--- /dev/null+++ b/spec/fixtures/1.0/grammar/003-fence-multiple-joined/expected.json@@ -0,0 +1,25 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "use ``` here"+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "B"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/grammar/003-fence-multiple-joined/input.oui b/spec/fixtures/1.0/grammar/003-fence-multiple-joined/input.ouinew file mode 100644index 000000000..611012110--- /dev/null+++ b/spec/fixtures/1.0/grammar/003-fence-multiple-joined/input.oui@@ -0,0 +1,8 @@+First part:+```openui+root = Stack([a, b])+a = Text("use ``` here")+```+And the rest, in a fence that is never closed:+```openui+b = Text("B")diff --git a/spec/fixtures/1.0/grammar/004-comment-strip/expected.json b/spec/fixtures/1.0/grammar/004-comment-strip/expected.jsonnew file mode 100644index 000000000..c1cc30658--- /dev/null+++ b/spec/fixtures/1.0/grammar/004-comment-strip/expected.json@@ -0,0 +1,31 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "a // not a comment"+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "b # not a comment either"+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "line one\n// still inside the string"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/grammar/004-comment-strip/input.oui b/spec/fixtures/1.0/grammar/004-comment-strip/input.ouinew file mode 100644index 000000000..1b5d2e083--- /dev/null+++ b/spec/fixtures/1.0/grammar/004-comment-strip/input.oui@@ -0,0 +1,6 @@+root = Stack([t, u, v]) // the page+# a note line+t = Text("a // not a comment")+u = Text('b # not a comment either')+v = Text("line one+// still inside the string")diff --git a/spec/fixtures/1.0/grammar/005-lex-escapes/expected.json b/spec/fixtures/1.0/grammar/005-lex-escapes/expected.jsonnew file mode 100644index 000000000..21c77905e--- /dev/null+++ b/spec/fixtures/1.0/grammar/005-lex-escapes/expected.json@@ -0,0 +1,31 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "q\"d\\b\ttA"+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "it's"+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "x\ny"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/grammar/005-lex-escapes/input.oui b/spec/fixtures/1.0/grammar/005-lex-escapes/input.ouinew file mode 100644index 000000000..2a5fededc--- /dev/null+++ b/spec/fixtures/1.0/grammar/005-lex-escapes/input.oui@@ -0,0 +1,4 @@+root = Stack([a, b, c])+a = Text("q\"d\\b\tt\u0041")+b = Text('it\'s')+c = Text('x\ny')diff --git a/spec/fixtures/1.0/grammar/006-lex-minus-and-skip/expected.json b/spec/fixtures/1.0/grammar/006-lex-minus-and-skip/expected.jsonnew file mode 100644index 000000000..1a0eeb1de--- /dev/null+++ b/spec/fixtures/1.0/grammar/006-lex-minus-and-skip/expected.json@@ -0,0 +1,32 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Table",+ "props": {+ "columns": [+ {+ "type": "Col",+ "props": {+ "label": "n",+ "data": [+ -1,+ 3,+ 3,+ -5+ ]+ }+ }+ ]+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/grammar/006-lex-minus-and-skip/input.oui b/spec/fixtures/1.0/grammar/006-lex-minus-and-skip/input.ouinew file mode 100644index 000000000..fe5f07cb0--- /dev/null+++ b/spec/fixtures/1.0/grammar/006-lex-minus-and-skip/input.oui@@ -0,0 +1,2 @@+root = Stack([Table([c])]);+c = Col("n", [1 -2, 3, 4 - 1, -5])diff --git a/spec/fixtures/1.0/grammar/008-expr-precedence-and-keys/expected.json b/spec/fixtures/1.0/grammar/008-expr-precedence-and-keys/expected.jsonnew file mode 100644index 000000000..5c2a86b86--- /dev/null+++ b/spec/fixtures/1.0/grammar/008-expr-precedence-and-keys/expected.json@@ -0,0 +1,57 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Table",+ "props": {+ "columns": [+ {+ "type": "Col",+ "props": {+ "label": "v",+ "data": [+ 5,+ 6,+ 3,+ 5,+ true,+ "ok",+ 1,+ 9+ ]+ }+ },+ {+ "type": "Col",+ "props": {+ "label": "o",+ "data": [+ {+ "2": "two",+ "name": "x",+ "quoted key": 1,+ "s": 3,+ "Card": 4+ }+ ]+ }+ }+ ]+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "end"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/grammar/008-expr-precedence-and-keys/input.oui b/spec/fixtures/1.0/grammar/008-expr-precedence-and-keys/input.ouinew file mode 100644index 000000000..0daf58f2a--- /dev/null+++ b/spec/fixtures/1.0/grammar/008-expr-precedence-and-keys/input.oui@@ -0,0 +1,3 @@+root = Stack([Table([c, o]) Text("end"),])+c = Col("v", [1 + 2 * 3 - 4 / 2, -2 * -3, 7 % 4, 10 - 2 - 3, 2 > 1 == true, !!"x" && "ok", 1 || 2 && 0, (1 + 2) * 3])+o = Col("o", [{name: "x", "quoted key": 1, 2: "two", $s: 3, Card: 4}])diff --git a/spec/fixtures/1.0/grammar/009-member-digits-field/expected.json b/spec/fixtures/1.0/grammar/009-member-digits-field/expected.jsonnew file mode 100644index 000000000..c99990fcf--- /dev/null+++ b/spec/fixtures/1.0/grammar/009-member-digits-field/expected.json@@ -0,0 +1,34 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Table",+ "props": {+ "columns": [+ {+ "type": "Col",+ "props": {+ "label": "d",+ "data": [+ 3,+ "zero",+ [+ 1,+ 3+ ]+ ]+ }+ }+ ]+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/grammar/009-member-digits-field/input.oui b/spec/fixtures/1.0/grammar/009-member-digits-field/input.ouinew file mode 100644index 000000000..4f6488d93--- /dev/null+++ b/spec/fixtures/1.0/grammar/009-member-digits-field/input.oui@@ -0,0 +1,4 @@+root = Stack([Table([c])])+m = [[1, 2], [3, 4]]+o = {0: "zero"}+c = Col("d", [m[1][0], o.0, m.0])diff --git a/spec/fixtures/1.0/grammar/010-roundtrip-tree/expected.json b/spec/fixtures/1.0/grammar/010-roundtrip-tree/expected.jsonnew file mode 100644index 000000000..de34beaf8--- /dev/null+++ b/spec/fixtures/1.0/grammar/010-roundtrip-tree/expected.json@@ -0,0 +1,43 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "Title",+ "variant": "heading"+ }+ },+ {+ "type": "Card",+ "props": {+ "title": "Details",+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "Body",+ "variant": "body"+ }+ },+ {+ "type": "Tag",+ "props": {+ "text": "new",+ "color": "green"+ }+ }+ ]+ }+ }+ ],+ "direction": "column"+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/grammar/010-roundtrip-tree/input.oui b/spec/fixtures/1.0/grammar/010-roundtrip-tree/input.ouinew file mode 100644index 000000000..1a54086c2--- /dev/null+++ b/spec/fixtures/1.0/grammar/010-roundtrip-tree/input.oui@@ -0,0 +1,2 @@+root = Stack([header, Card("Details", [Text("Body", "body"), Tag("new", "green")])], "column")+header = Text("Title", "heading")diff --git a/spec/fixtures/1.0/grammar/README.md b/spec/fixtures/1.0/grammar/README.mdnew file mode 100644index 000000000..f1b0dccb9--- /dev/null+++ b/spec/fixtures/1.0/grammar/README.md@@ -0,0 +1,13 @@+# grammar++These cases protect a client from reading the source text differently from other clients: where fences open and close, what counts as a comment, how strings, numbers, and minus signs lex, and how expressions group. They cover [language.md section 1](../../../language.md#1-grammar) and the round trip of [section 9.2](../../../language.md#92-serialization). Numbers 001, 002, and 007 are not used.++| Case | What it checks | Spec |+| --- | --- | --- |+| 003-fence-multiple-joined | Two fences are joined, the second runs to the end of the text with no closing fence, and three backticks inside a double-quoted string do not close the first. | [1.2](../../../language.md#12-source-text) |+| 004-comment-strip | `//` and `#` comments are removed, and comment markers inside strings, including a multi-line string, are kept. | [1.2](../../../language.md#12-source-text) |+| 005-lex-escapes | JSON escapes in double-quoted strings (`\"`, `\\`, `\t`, `\u0041`), and `\'` and `\n` in single-quoted strings. | [1.3](../../../language.md#13-lexical-elements) |+| 006-lex-minus-and-skip | `1 -2` after a value is subtraction, `-5` after a comma is a number, and an unknown character (`;`) is skipped. | [1.3](../../../language.md#13-lexical-elements) |+| 008-expr-precedence-and-keys | Operator precedence and associativity, optional and trailing commas, and object keys written as names, strings, numbers, `$` names (the `$` is dropped), and component names. | [1.5](../../../language.md#15-expressions) |+| 009-member-digits-field | `m[1][0]` indexes, `o.0` reads the key "0", and `m.0` on an array plucks. | [1.5](../../../language.md#15-expressions), [3.3](../../../language.md#33-member-access-and-pluck) |+| 010-roundtrip-tree | The rendered tree serializes to text and parses back to the same `root`. | [9.2](../../../language.md#92-serialization) |diff --git a/spec/fixtures/1.0/library.json b/spec/fixtures/1.0/library.jsonnew file mode 100644index 000000000..821de25ad--- /dev/null+++ b/spec/fixtures/1.0/library.json@@ -0,0 +1,254 @@+{+ "id": "fixtures",+ "version": "1.0.0",+ "root": "Stack",+ "schema": {+ "properties": {+ "Stack": { "$ref": "#/$defs/Stack" },+ "Card": { "$ref": "#/$defs/Card" },+ "Text": { "$ref": "#/$defs/Text" },+ "Tag": { "$ref": "#/$defs/Tag" },+ "Metric": { "$ref": "#/$defs/Metric" },+ "Button": { "$ref": "#/$defs/Button" },+ "Form": { "$ref": "#/$defs/Form" },+ "Input": { "$ref": "#/$defs/Input" },+ "Select": { "$ref": "#/$defs/Select" },+ "SelectItem": { "$ref": "#/$defs/SelectItem" },+ "Table": { "$ref": "#/$defs/Table" },+ "Col": { "$ref": "#/$defs/Col" }+ },+ "$defs": {+ "Stack": {+ "type": "object",+ "description": "Lays out children in a column or a row",+ "properties": {+ "children": { "type": "array", "items": { "anyOf": [{ "$ref": "#/$defs/Stack" }, { "$ref": "#/$defs/Card" }, { "$ref": "#/$defs/Text" }, { "$ref": "#/$defs/Tag" }, { "$ref": "#/$defs/Metric" }, { "$ref": "#/$defs/Button" }, { "$ref": "#/$defs/Form" }, { "$ref": "#/$defs/Input" }, { "$ref": "#/$defs/Select" }, { "$ref": "#/$defs/SelectItem" }, { "$ref": "#/$defs/Table" }, { "$ref": "#/$defs/Col" }] } },+ "direction": { "type": "string", "enum": ["row", "column"] }+ },+ "required": ["children"]+ },+ "Card": {+ "type": "object",+ "description": "A titled container",+ "properties": {+ "title": { "type": "string" },+ "children": { "type": "array", "items": { "anyOf": [{ "$ref": "#/$defs/Stack" }, { "$ref": "#/$defs/Card" }, { "$ref": "#/$defs/Text" }, { "$ref": "#/$defs/Tag" }, { "$ref": "#/$defs/Metric" }, { "$ref": "#/$defs/Button" }, { "$ref": "#/$defs/Form" }, { "$ref": "#/$defs/Input" }, { "$ref": "#/$defs/Select" }, { "$ref": "#/$defs/SelectItem" }, { "$ref": "#/$defs/Table" }, { "$ref": "#/$defs/Col" }] } }+ },+ "required": ["title"]+ },+ "Text": {+ "type": "object",+ "description": "A run of text",+ "properties": {+ "text": { "type": "string" },+ "variant": { "type": "string", "enum": ["body", "heading"] }+ },+ "required": ["text"]+ },+ "Tag": {+ "type": "object",+ "description": "A small colored label",+ "properties": {+ "text": { "type": "string" },+ "color": { "type": "string", "enum": ["gray", "green", "red"] }+ },+ "required": ["text"]+ },+ "Metric": {+ "type": "object",+ "description": "A labeled number",+ "properties": {+ "label": { "type": "string" },+ "value": { "type": "number" }+ },+ "required": ["label", "value"]+ },+ "Button": {+ "type": "object",+ "description": "A clickable button",+ "properties": {+ "label": { "type": "string" },+ "action": { "$ref": "#/$defs/ActionExpression" },+ "variant": { "type": "string", "enum": ["primary", "secondary"] },+ "share": { "anyOf": [{ "$ref": "#/$defs/CopyToClipboard" }, { "$ref": "#/$defs/OpenUrl" }] }+ },+ "required": ["label"]+ },+ "Form": {+ "type": "object",+ "description": "Groups its inputs under a form name",+ "properties": {+ "name": { "type": "string" },+ "children": { "type": "array", "items": { "anyOf": [{ "$ref": "#/$defs/Stack" }, { "$ref": "#/$defs/Card" }, { "$ref": "#/$defs/Text" }, { "$ref": "#/$defs/Tag" }, { "$ref": "#/$defs/Metric" }, { "$ref": "#/$defs/Button" }, { "$ref": "#/$defs/Form" }, { "$ref": "#/$defs/Input" }, { "$ref": "#/$defs/Select" }, { "$ref": "#/$defs/SelectItem" }, { "$ref": "#/$defs/Table" }, { "$ref": "#/$defs/Col" }] } }+ },+ "required": ["name", "children"]+ },+ "Input": {+ "type": "object",+ "description": "A text field",+ "properties": {+ "name": { "type": "string" },+ "placeholder": { "type": "string" },+ "value": { "type": "string" },+ "rules": { "type": "object" }+ },+ "required": ["name"]+ },+ "Select": {+ "type": "object",+ "description": "A dropdown",+ "properties": {+ "name": { "type": "string" },+ "items": { "type": "array", "items": { "$ref": "#/$defs/SelectItem" } },+ "value": { "type": "string" }+ },+ "required": ["name", "items"]+ },+ "SelectItem": {+ "type": "object",+ "description": "One option of a Select",+ "properties": {+ "value": { "type": "string" },+ "label": { "type": "string" }+ },+ "required": ["value", "label"]+ },+ "Table": {+ "type": "object",+ "description": "A table built from columns",+ "properties": {+ "columns": { "type": "array", "items": { "$ref": "#/$defs/Col" } }+ },+ "required": ["columns"]+ },+ "Col": {+ "type": "object",+ "description": "One table column: a header and its cell values",+ "properties": {+ "label": { "type": "string" },+ "data": { "type": "array" }+ },+ "required": ["label"]+ },+ "ActionExpression": {+ "anyOf": [+ {+ "type": "object",+ "properties": { "type": { "type": "string", "const": "open_url" }, "url": { "type": "string" } },+ "required": ["type", "url"]+ },+ {+ "type": "object",+ "properties": { "type": { "type": "string", "const": "continue_conversation" }, "context": { "type": "string" } },+ "required": ["type"]+ },+ {+ "type": "object",+ "properties": { "type": { "type": "string" }, "params": { "type": "object" } },+ "required": ["type"]+ }+ ]+ },+ "OpenUrl": {+ "type": "object",+ "properties": { "type": { "type": "string", "const": "open_url" }, "url": { "type": "string" } },+ "required": ["type", "url"]+ },+ "CopyToClipboard": {+ "type": "object",+ "properties": {+ "type": { "type": "string", "const": "CopyToClipboard" },+ "params": { "type": "object", "properties": { "text": { "type": "string" } }, "required": ["text"] }+ },+ "required": ["type", "params"]+ }+ },+ "functions": {+ "Upper": {+ "description": "The text in upper case",+ "params": {+ "type": "object",+ "properties": {+ "text": { "type": "string" }+ },+ "required": ["text"]+ },+ "returns": { "type": "string" }+ }+ },+ "actions": {+ "CopyToClipboard": {+ "description": "Copies text to the clipboard",+ "params": {+ "type": "object",+ "properties": {+ "text": { "type": "string" }+ },+ "required": ["text"]+ }+ }+ }+ },+ "components": {+ "Stack": {+ "signature": "Stack(children: any[], direction?: \"row\" | \"column\")",+ "description": "Lays out children in a column or a row"+ },+ "Card": {+ "signature": "Card(title: string, children?: any[])",+ "description": "A titled container"+ },+ "Text": {+ "signature": "Text(text: string, variant?: \"body\" | \"heading\")",+ "description": "A run of text"+ },+ "Tag": {+ "signature": "Tag(text: string, color?: \"gray\" | \"green\" | \"red\")",+ "description": "A small colored label"+ },+ "Metric": {+ "signature": "Metric(label: string, value: number)",+ "description": "A labeled number"+ },+ "Button": {+ "signature": "Button(label: string, action?: ActionExpression, variant?: \"primary\" | \"secondary\", share?: @CopyToClipboard | @OpenUrl)",+ "description": "A clickable button"+ },+ "Form": {+ "signature": "Form(name: string, children: any[])",+ "description": "Groups its inputs under a form name"+ },+ "Input": {+ "signature": "Input(name: string, placeholder?: string, value?: $binding<string>, rules?: {})",+ "description": "A text field"+ },+ "Select": {+ "signature": "Select(name: string, items: any[], value?: $binding<string>)",+ "description": "A dropdown"+ },+ "SelectItem": {+ "signature": "SelectItem(value: string, label: string)",+ "description": "One option of a Select"+ },+ "Table": {+ "signature": "Table(columns: any[])",+ "description": "A table built from columns"+ },+ "Col": {+ "signature": "Col(label: string, data?: any[])",+ "description": "One table column: a header and its cell values"+ }+ },+ "functions": {+ "Upper": {+ "signature": "Upper(text: string) → string",+ "description": "The text in upper case"+ }+ },+ "actions": {+ "CopyToClipboard": {+ "signature": "CopyToClipboard(text: string)",+ "description": "Copies text to the clipboard"+ }+ }+}diff --git a/spec/fixtures/1.0/state/001-store-auto-declare/expected.json b/spec/fixtures/1.0/state/001-store-auto-declare/expected.jsonnew file mode 100644index 000000000..82434e4ca--- /dev/null+++ b/spec/fixtures/1.0/state/001-store-auto-declare/expected.json@@ -0,0 +1,29 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "anon"+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "x"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$v": "x",+ "$name": null+ }+}diff --git a/spec/fixtures/1.0/state/001-store-auto-declare/input.oui b/spec/fixtures/1.0/state/001-store-auto-declare/input.ouinew file mode 100644index 000000000..187af7b36--- /dev/null+++ b/spec/fixtures/1.0/state/001-store-auto-declare/input.oui@@ -0,0 +1,2 @@+$v = "x"+root = Stack([Text($name == null ? "anon" : $name), Text($v)])diff --git a/spec/fixtures/1.0/state/002-binding-two-way/expected.json b/spec/fixtures/1.0/state/002-binding-two-way/expected.jsonnew file mode 100644index 000000000..8bf8a0d6d--- /dev/null+++ b/spec/fixtures/1.0/state/002-binding-two-way/expected.json@@ -0,0 +1,32 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Input",+ "props": {+ "name": "search",+ "placeholder": "Search",+ "value": {+ "$binding": "$query"+ }+ }+ },+ {+ "type": "Text",+ "props": {+ "text": "You typed: "+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$query": ""+ }+}diff --git a/spec/fixtures/1.0/state/002-binding-two-way/input.oui b/spec/fixtures/1.0/state/002-binding-two-way/input.ouinew file mode 100644index 000000000..205486e06--- /dev/null+++ b/spec/fixtures/1.0/state/002-binding-two-way/input.oui@@ -0,0 +1,3 @@+$query = ""+root = Stack([search, Text("You typed: " + $query)])+search = Input("search", "Search", $query)diff --git a/spec/fixtures/1.0/state/002-binding-two-way/interactions.json b/spec/fixtures/1.0/state/002-binding-two-way/interactions.jsonnew file mode 100644index 000000000..ccee77c23--- /dev/null+++ b/spec/fixtures/1.0/state/002-binding-two-way/interactions.json@@ -0,0 +1,16 @@+{+ "interactions": [+ {+ "type": [+ "search",+ "late"+ ]+ }+ ],+ "expected": {+ "events": [],+ "state": {+ "$query": "late"+ }+ }+}diff --git a/spec/fixtures/1.0/state/003-form-scope/expected.json b/spec/fixtures/1.0/state/003-form-scope/expected.jsonnew file mode 100644index 000000000..28a34be68--- /dev/null+++ b/spec/fixtures/1.0/state/003-form-scope/expected.json@@ -0,0 +1,44 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Form",+ "props": {+ "name": "contact",+ "children": [+ {+ "type": "Input",+ "props": {+ "name": "email",+ "placeholder": "Email"+ }+ },+ {+ "type": "Button",+ "props": {+ "label": "Send",+ "action": {+ "actions": [+ {+ "action": "ToAssistant",+ "args": [+ "Send"+ ]+ }+ ]+ }+ }+ }+ ]+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/state/003-form-scope/input.oui b/spec/fixtures/1.0/state/003-form-scope/input.ouinew file mode 100644index 000000000..226b91eb8--- /dev/null+++ b/spec/fixtures/1.0/state/003-form-scope/input.oui@@ -0,0 +1,3 @@+root = Stack([Form("contact", [email, send])])+email = Input("email", "Email")+send = Button("Send", Action([@ToAssistant("Send")]))diff --git a/spec/fixtures/1.0/state/003-form-scope/interactions.json b/spec/fixtures/1.0/state/003-form-scope/interactions.jsonnew file mode 100644index 000000000..5a45b05c2--- /dev/null+++ b/spec/fixtures/1.0/state/003-form-scope/interactions.json@@ -0,0 +1,30 @@+{+ "interactions": [+ {+ "type": [+ "email",+ ]+ },+ {+ "click": "send"+ }+ ],+ "expected": {+ "events": [+ {+ "type": "continue_conversation",+ "humanFriendlyMessage": "Send",+ "formName": "contact",+ "formState": {+ "contact": {+ "email": {+ "value": "[email protected]",+ "componentType": "input"+ }+ }+ }+ }+ ]+ }+}diff --git a/spec/fixtures/1.0/state/004-form-page-level/expected.json b/spec/fixtures/1.0/state/004-form-page-level/expected.jsonnew file mode 100644index 000000000..077b83c88--- /dev/null+++ b/spec/fixtures/1.0/state/004-form-page-level/expected.json@@ -0,0 +1,36 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Input",+ "props": {+ "name": "note",+ "placeholder": "Note"+ }+ },+ {+ "type": "Button",+ "props": {+ "label": "Send",+ "action": {+ "actions": [+ {+ "action": "ToAssistant",+ "args": [+ "Send"+ ]+ }+ ]+ }+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/state/004-form-page-level/input.oui b/spec/fixtures/1.0/state/004-form-page-level/input.ouinew file mode 100644index 000000000..1536d1e76--- /dev/null+++ b/spec/fixtures/1.0/state/004-form-page-level/input.oui@@ -0,0 +1,3 @@+root = Stack([note, send])+note = Input("note", "Note")+send = Button("Send", Action([@ToAssistant("Send")]))diff --git a/spec/fixtures/1.0/state/004-form-page-level/interactions.json b/spec/fixtures/1.0/state/004-form-page-level/interactions.jsonnew file mode 100644index 000000000..640566e5c--- /dev/null+++ b/spec/fixtures/1.0/state/004-form-page-level/interactions.json@@ -0,0 +1,28 @@+{+ "interactions": [+ {+ "type": [+ "note",+ "rush"+ ]+ },+ {+ "click": "send"+ }+ ],+ "expected": {+ "events": [+ {+ "type": "continue_conversation",+ "humanFriendlyMessage": "Send",+ "formName": null,+ "formState": {+ "note": {+ "value": "rush",+ "componentType": "input"+ }+ }+ }+ ]+ }+}diff --git a/spec/fixtures/1.0/state/005-validation-rules/validation.json b/spec/fixtures/1.0/state/005-validation-rules/validation.jsonnew file mode 100644index 000000000..4b8ab78cf--- /dev/null+++ b/spec/fixtures/1.0/state/005-validation-rules/validation.json@@ -0,0 +1,138 @@+{+ "cases": [+ {+ "rules": {+ "required": true+ },+ "value": "",+ "valid": false+ },+ {+ "rules": {+ "required": true+ },+ "value": [],+ "valid": false+ },+ {+ "rules": {+ "required": true+ },+ "value": "x",+ "valid": true+ },+ {+ "rules": {+ "email": true+ },+ "value": "[email protected]",+ "valid": true+ },+ {+ "rules": {+ "email": true+ },+ "value": "a [email protected]",+ "valid": false+ },+ {+ "rules": {+ "email": true+ },+ "value": "",+ "valid": true+ },+ {+ "rules": {+ "url": true+ },+ "value": "https://openui.com/x",+ "valid": true+ },+ {+ "rules": {+ "url": true+ },+ "value": "openui.com",+ "valid": false+ },+ {+ "rules": {+ "numeric": true+ },+ "value": "12abc",+ "valid": true+ },+ {+ "rules": {+ "numeric": true+ },+ "value": "abc",+ "valid": false+ },+ {+ "rules": {+ "numeric": true+ },+ "value": 3,+ "valid": true+ },+ {+ "rules": {+ "minLength": 3+ },+ "value": "ab",+ "valid": false+ },+ {+ "rules": {+ "minLength": 3+ },+ "value": [],+ "valid": true+ },+ {+ "rules": {+ "maxLength": 3+ },+ "value": "abcd",+ "valid": false+ },+ {+ "rules": {+ "min": 5+ },+ "value": 4,+ "valid": false+ },+ {+ "rules": {+ "max": 5+ },+ "value": 5,+ "valid": true+ },+ {+ "rules": {+ "pattern": "^[A-Z]{2}\\d{3}$"+ },+ "value": "AB123",+ "valid": true+ },+ {+ "rules": {+ "pattern": "^[A-Z]{2}\\d{3}$"+ },+ "value": "ab123",+ "valid": false+ },+ {+ "rules": {+ "required": true,+ "email": true+ },+ "value": "nope",+ "valid": false+ }+ ]+}diff --git a/spec/fixtures/1.0/state/README.md b/spec/fixtures/1.0/state/README.mdnew file mode 100644index 000000000..817e41be7--- /dev/null+++ b/spec/fixtures/1.0/state/README.md@@ -0,0 +1,11 @@+# state++These cases protect a client from losing or misplacing state: undeclared `$names`, two-way bindings, which form a field writes to, and which values pass validation. They cover [language.md section 5](../../../language.md#5-state-and-forms). The binding and form cases use `interactions.json`, and the validation case uses `validation.json` instead of a program.++| Case | What it checks | Spec |+| --- | --- | --- |+| 001-store-auto-declare | An undeclared `$name` is declared with null, so the Text shows "anon", and the store holds `$v` and `$name`. | [5.1](../../../language.md#51-the-state-store-and-what-is-reactive) |+| 002-binding-two-way (+ interactions) | `$query` passed to the bindable `Input.value` is a binding, and typing "late" writes it to the store. | [5.2](../../../language.md#52-two-way-binding) |+| 003-form-scope (+ interactions) | An Input inside `Form("contact", ...)`: the @ToAssistant event carries `formName: "contact"` and the field under that form. | [5.3](../../../language.md#53-form-state), [6.3](../../../language.md#63-actions) |+| 004-form-page-level (+ interactions) | An Input outside any form writes page-level state: the event has no `formName` and the field at the top level of `formState`. | [5.3](../../../language.md#53-form-state), [6.3](../../../language.md#63-actions) |+| 005-validation-rules | Pass or fail for each rule (`required`, `email`, `url`, `numeric`, `minLength`, `maxLength`, `min`, `max`, `pattern`), including that every rule but `required` skips empty values and that "12abc" is numeric. | [5.4](../../../language.md#54-validation-rules) |diff --git a/spec/fixtures/1.0/streaming/001-worked-example/chunks.json b/spec/fixtures/1.0/streaming/001-worked-example/chunks.jsonnew file mode 100644index 000000000..6322b1dd9--- /dev/null+++ b/spec/fixtures/1.0/streaming/001-worked-example/chunks.json@@ -0,0 +1,6 @@+[+ "root = Stack([header, kpis])\nheader = Te",+ "xt(\"Tickets\", \"heading\")\nkpis = Stack([open",+ ", closed])\nopen = Metric(\"Open\", @Count(@Filter(tickets.rows, \"status\", \"==\", \"open\")))\n",+ "closed = Metric(\"Closed\", 8)\ntickets = Query(\"listTickets\", {}, { rows: [] })\n"+]diff --git a/spec/fixtures/1.0/streaming/001-worked-example/expected.json b/spec/fixtures/1.0/streaming/001-worked-example/expected.jsonnew file mode 100644index 000000000..5708675b1--- /dev/null+++ b/spec/fixtures/1.0/streaming/001-worked-example/expected.json@@ -0,0 +1,41 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "Tickets",+ "variant": "heading"+ }+ },+ {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Metric",+ "props": {+ "label": "Open",+ "value": 0+ }+ },+ {+ "type": "Metric",+ "props": {+ "label": "Closed",+ "value": 8+ }+ }+ ]+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/streaming/003-multiline-ternary-across-chunks/chunks.json b/spec/fixtures/1.0/streaming/003-multiline-ternary-across-chunks/chunks.jsonnew file mode 100644index 000000000..81f19a54e--- /dev/null+++ b/spec/fixtures/1.0/streaming/003-multiline-ternary-across-chunks/chunks.json@@ -0,0 +1,5 @@+[+ "$n = 0\nroot = Stack([Text(s)])\ns = $n > 0\n",+ " ? \"some\"\n",+ " : \"none\"\n"+]diff --git a/spec/fixtures/1.0/streaming/003-multiline-ternary-across-chunks/expected.json b/spec/fixtures/1.0/streaming/003-multiline-ternary-across-chunks/expected.jsonnew file mode 100644index 000000000..c08248bf9--- /dev/null+++ b/spec/fixtures/1.0/streaming/003-multiline-ternary-across-chunks/expected.json@@ -0,0 +1,22 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "none"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false,+ "state": {+ "$n": 0+ }+}diff --git a/spec/fixtures/1.0/streaming/005-fence-arrives-late/chunks.json b/spec/fixtures/1.0/streaming/005-fence-arrives-late/chunks.jsonnew file mode 100644index 000000000..99495f71f--- /dev/null+++ b/spec/fixtures/1.0/streaming/005-fence-arrives-late/chunks.json@@ -0,0 +1,5 @@+[+ "Here you go:\n",+ "```openui\nroot = Stack([Text(\"a\")])\n",+ "```\nEnjoy."+]diff --git a/spec/fixtures/1.0/streaming/005-fence-arrives-late/expected.json b/spec/fixtures/1.0/streaming/005-fence-arrives-late/expected.jsonnew file mode 100644index 000000000..a5db618b5--- /dev/null+++ b/spec/fixtures/1.0/streaming/005-fence-arrives-late/expected.json@@ -0,0 +1,19 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "a"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": false+}diff --git a/spec/fixtures/1.0/streaming/006-truncated-string-escape/chunks.json b/spec/fixtures/1.0/streaming/006-truncated-string-escape/chunks.jsonnew file mode 100644index 000000000..151459c21--- /dev/null+++ b/spec/fixtures/1.0/streaming/006-truncated-string-escape/chunks.json@@ -0,0 +1,4 @@+[+ "root = Stack([t])\nt = Text(\"a",+ "\\"+]diff --git a/spec/fixtures/1.0/streaming/006-truncated-string-escape/expected.json b/spec/fixtures/1.0/streaming/006-truncated-string-escape/expected.jsonnew file mode 100644index 000000000..5c7fd2809--- /dev/null+++ b/spec/fixtures/1.0/streaming/006-truncated-string-escape/expected.json@@ -0,0 +1,19 @@+{+ "root": {+ "type": "Stack",+ "props": {+ "children": [+ {+ "type": "Text",+ "props": {+ "text": "a\\"+ }+ }+ ]+ }+ },+ "errors": [],+ "unresolved": [],+ "orphans": [],+ "incomplete": true+}diff --git a/spec/fixtures/1.0/streaming/README.md b/spec/fixtures/1.0/streaming/README.mdnew file mode 100644index 000000000..fa1ff5726--- /dev/null+++ b/spec/fixtures/1.0/streaming/README.md@@ -0,0 +1,10 @@+# streaming++These cases protect a client from giving a different result when text arrives in chunks than when it arrives at once. Each case gives `chunks.json`; the result after the last chunk and the end of the stream must match `expected.json` and a batch parse of the joined chunks. They cover [language.md section 4](../../../language.md#4-streaming) and [Appendix A](../../../language.md#appendix-a-a-worked-streamed-example). Numbers 002 and 004 are not used.++| Case | What it checks | Spec |+| --- | --- | --- |+| 001-worked-example | The Appendix A example with `Stack` as the root: chunks split names and calls mid-token, and the final page shows the heading and two Metrics with no errors. | [4](../../../language.md#4-streaming), [Appendix A](../../../language.md#appendix-a-a-worked-streamed-example) |+| 003-multiline-ternary-across-chunks | A ternary whose `?` and `:` lines arrive in later chunks: the statement does not complete early, and the Text shows "none". | [4](../../../language.md#4-streaming), [1.4](../../../language.md#14-statements) |+| 005-fence-arrives-late | Prose arrives first, then a fence: the client parses again from the start, and only the fenced program renders. | [4](../../../language.md#4-streaming), [1.2](../../../language.md#12-source-text) |+| 006-truncated-string-escape | The stream ends right after a `\` inside a string: a `\` is added before the string is closed, the Text shows `a\`, and `incomplete` is true. | [4](../../../language.md#4-streaming), [1.3](../../../language.md#13-lexical-elements) |diff --git a/spec/language.md b/spec/language.mdnew file mode 100644index 000000000..9f1dda70a--- /dev/null+++ b/spec/language.md@@ -0,0 +1,647 @@+# The OpenUI Language++**1.0**++The exact rules of OpenUI Lang. For a guided tour, read [overview.md](./overview.md). [prompt.md](./prompt.md) covers the LibrarySpec, the prompt, and stored responses. MUST, MUST NOT, SHOULD, and MAY are used as in RFC 2119.++The **generator** writes OpenUI Lang (in practice, a model). The **client** parses and renders it. The **host** is the app that embeds the client.++Each normative subsection ends with a "Fixtures:" line naming the conformance cases that check it (Appendix B).++## 1. Grammar++### 1.1 Notation++The grammar uses EBNF: `=` defines, `|` separates alternatives, `[ ]` is optional, `{ }` repeats zero or more times, `( )` groups, and terminals are in double quotes. The full grammar is in section 1.6.++### 1.2 Source text++The client accepts text with or without the host's `]]>openui:` marker lines ([prompt.md](./prompt.md), section 7) and renders only the content. It then prepares the text in this order:++1. **Fence extraction.** A fence opens only with three backticks at the start of a line, with or without a language tag. If the text has fences, the client joins the contents of every fence with newlines. Text outside fences is prose and is ignored. Quotes in prose outside fences do not shield anything. Inside a fence, backtick runs inside double-quoted strings do not close it. Single-quoted strings do not shield them. Comments are stripped after extraction, so backtick runs inside comments do count. An unterminated fence runs to the end of the text.+2. **Comment stripping.** `//` and `#` start a comment that runs to the end of the line. Comment markers inside strings, even multi-line ones, are not comments.+3. **Trimming.** Leading and trailing whitespace is removed.++Fixtures: `grammar/*-fence-*`, `grammar/*-comment-*`++### 1.3 Lexical elements++#### Identifiers++Identifiers match `[a-zA-Z_][a-zA-Z0-9_]*`. An uppercase first letter makes a component name. A lowercase letter or `_` makes a reference.++```ebnf+identifier = ( letter | "_" ) { letter | digit | "_" } ;+state_name = "$" identifier ;+function_name = "@" identifier ;+```++`$name` is a state variable, and the `$` is part of the name. `@name` calls a built-in, a custom function, or an action. Clients MUST NOT give `$` and `@` other meanings.++#### Keywords++The only keywords are `true`, `false`, and `null`.++#### Reserved names++| Group | Names |+| --- | --- |+| Keyword literals | `true`, `false`, `null` |+| Reserved call forms | `Query`, `Mutation`, `Action` |+| Built-in functions | `@Count`, `@First`, `@Last`, `@Sum`, `@Avg`, `@Min`, `@Max`, `@Filter`, `@Sort`, `@Round`, `@Abs`, `@Floor`, `@Ceil`, `@Each` |+| Actions | `@Set`, `@Reset`, `@Run`, `@ToAssistant`, `@OpenUrl` |+| State prefix | every `$name` |++`Query` and `Mutation` are statement forms. `Action` is an expression form (section 2.1). None of them is a component.++Library components, functions (section 3.6), and actions (section 6.3) MUST NOT use any name in this table. New built-in names are reserved when they are added ([prompt.md](./prompt.md), section 3).++#### Operators and punctuation++```text+= == != > < >= <= + - * / % && || ! ? : . , ( ) [ ] { }+```++A single `&` or `|` means `&&` or `||`.++#### String literals++Strings are double-quoted or single-quoted. Double-quoted strings use JSON escapes (`\n`, `\t`, `\"`, `\\`, `\uXXXX`). Single-quoted strings support only `\'`, `\\`, `\n`, and `\t`. Any other escaped character is kept as is. An unterminated string at the end of a streaming buffer is closed implicitly (section 4).++#### Number literals++Numbers match `-?[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?`.++- An `e` or `E` after the digits is always an exponent marker, even with no digits after it. That token is not a usable number.+- A `.` is part of a number only when a digit follows. `1.` is `1` followed by member access.+- A `-` starts a number only when a digit follows and the previous token is not a value (a literal, reference, call, `)`, or `]`, but not `}`). Otherwise it is subtraction or negation. So `[1 -2]` is one element, `1 - 2`.++#### Whitespace and other characters++Spaces and tabs separate tokens. The `newline` token is `\n`, and a `\r` before it is consumed with it. A newline ends a statement only at bracket depth zero (section 1.4). A character that matches no rule is skipped: `a;b` lexes as `a` and `b`. Lexing never fails.++Fixtures: `grammar/*-lex-*`++### 1.4 Statements++A statement is `name = expression` (section 1.6). The name is a reference, component, or state name. A line without this shape is skipped without an error.++A statement continues past a newline when:++1. the newline is inside an unclosed `(`, `[`, or `{`;+2. the newline is inside an unterminated string (strings may hold raw newlines); or+3. a ternary is open at bracket depth zero, or the next line's first non-whitespace token is `?`. A ternary is **open** from its `?` until the first complete operand after its matching `:`. A newline while either branch is still empty continues the statement.++```openui-lang+status = $count > 0+ ? "Has items"+ : "Empty"+```++The batch parser, the streaming parser, and the edit merge (section 7) MUST agree on these boundaries byte for byte. Rule 3 looks at the next line, so a boundary is provisional while streaming (section 4, rule 1).++Fixtures: `entry/*-ternary-root-multiline`, `streaming/*-multiline-ternary-*`++### 1.5 Expressions++#### Operands++Object keys may be names, strings, numbers, component names, or `$` names (the `$` is dropped). All keys are strings. Any other token is read as the key `?`.++A bare identifier in operand position is a reference, whatever its case. Only the call head makes an uppercase identifier a component.++Inside an expression, `$name = expression` parses as a binding assignment, used by the runtime for two-way binding. Generators SHOULD NOT write it.++#### Calls++A call is a component name or an `@` name followed by `( arguments )`.++- Arguments are positional. `null` skips an optional argument.+- Commas between arguments, array elements, and object entries are optional. Trailing commas are ignored.+- The name after `@` is uppercase by convention, but either case parses.+- Built-ins and custom functions need the `@`. `Count(x)` parses as the reference `Count`, and the arguments are lost. Only `Action([...])` works with or without `@`.++#### Member access and indexing++`a.field` and `a[expression]` follow any primary. A field accepts the same tokens as an object key and is read as a string key, so a number after `.` is a field name: on an array, `m.0` plucks (section 3.3), and `m.0.1` reads the field `0.1`. Index arrays with `m[0][1]`. A member access is never callable: `foo.bar(x)` is not a call.++#### Operators and precedence++From lowest to highest. Binary operators are left-associative.++1. `? :` (ternary, right-associative)+2. `||`+3. `&&`+4. `==` `!=`+5. `>` `<` `>=` `<=`+6. `+` `-`+7. `*` `/` `%`+8. unary `!` and `-` (they stack: `!!x` is valid)+9. postfix: member access and indexing (calls are primary forms)++Fixtures: `grammar/*-expr-*`, `grammar/*-member-digits-*`++### 1.6 Complete grammar++```ebnf+program = statement { newline statement } ;+statement = ( identifier | state_name ) "=" expression ;+expression = ternary ;+ternary = or [ "?" ternary ":" ternary ] ;+or = and { "||" and } ;+and = equality { "&&" equality } ;+equality = comparison { ( "==" | "!=" ) comparison } ;+comparison = additive { ( ">" | "<" | ">=" | "<=" ) additive } ;+additive = multiplicative { ( "+" | "-" ) multiplicative } ;+multiplicative = unary { ( "*" | "/" | "%" ) unary } ;+unary = { "!" | "-" } postfix ;+postfix = primary { "." field | "[" expression "]" } ;+primary = literal | array | object | call | reference+ | "(" expression ")" ;+call = ( ComponentName | function_name ) "(" [ arguments ] ")" ;+arguments = expression { [ "," ] expression } ;+array = "[" [ arguments ] "]" ;+object = "{" [ key ":" expression { [ "," ] key ":" expression } ] "}" ;+literal = string | number | "true" | "false" | "null" ;+reference = identifier | state_name ;+```++Tokens and the token sets for `key` and `field` are in sections 1.3 and 1.5.++Implementation-defined in 1.0, and untested: trailing tokens after a complete expression in one statement, the value of a number with a dangling exponent, a partly received unicode escape under implicit closing, and whether an unchanged query fetches again after a merge.++Fixtures: `grammar/`++## 2. Program model++### 2.1 Statement kinds++Each statement is classified in this order:++1. `Query(...)` as the whole right side: a **query statement**.+2. `Mutation(...)` as the whole right side: a **mutation statement**.+3. A `$` name on the left: a **state declaration**. The right side is its default.+4. Anything else: a **value statement**.++So `$x = Query(...)` is a query statement with the id `$x`, and it runs. But `$x` in an expression reads the state store and never sees the result. The same goes for `$x = Mutation(...)`. Generators SHOULD name queries and mutations without `$`.++- A **value position** is a direct argument of a component call or a direct element of an array literal, before any operator applies.+- A **computed expression** is any other context: an operand, a ternary branch, an object value.++`Query` and `Mutation` are valid only as the whole right side. In a value position they report `inline-reserved` and evaluate to nothing. In a computed expression they evaluate to null with no error. `Action(...)` is an ordinary expression. It may appear inline or be bound to a statement.++Fixtures: `evaluation/*-kind-*`++### 2.2 Entry++The entry is the statement named `root`. Its value must evaluate to a component: a component call, a reference to a statement whose value is one, or any expression that gives one. For example, `root = $t ? A : B` is a valid entry when `A` and `B` are component statements. When the value is not a component, `root` is still the entry: the client reports a fatal `no-root` at stream end, with no fallback, and statements `root` cannot reach are still orphans (section 2.3).++With no `root` statement, the first value statement whose value is a call to the library's root component (the LibrarySpec `root` field, [prompt.md](./prompt.md), section 2.2) is the entry, wherever it is in the program. It renders with a non-fatal `no-root`.++```openui-lang+title = Header("Orders")+page = Card([title])+```++If the library's root is `Card`, this renders `page` with a non-fatal `no-root`. If no statement's value were a `Card` call, nothing would render. State declarations are never the entry, so `$tab = Card([])` does not count.++In every other case, at stream end the client reports a fatal `no-root` and nothing renders. If the library has no `root` field, only a `root` statement is an entry. While streaming, a missing entry is not an error.++Fixtures: `entry/`, including `entry/*-ternary-*`++### 2.3 References and hoisting++A bare name refers to the statement with that name, wherever it is in the program.++- A reference to a missing statement is **unresolved**. It goes into the parse metadata, not the error list.+- An unresolved reference is null in an expression and renders nothing in a component position. As a direct element of an array it is left out, in value positions and computed expressions alike, so `@Count([a, b])` with `b` unresolved is 1. While streaming, clients SHOULD NOT report required-prop errors caused only by unresolved references. At stream end, section 8.4 applies.+- A reference that closes a cycle is unresolved at that point.+- A statement referenced from two places is evaluated separately at each. Only the tree is copied: the state store is shared, and a query referenced twice fetches once, with both places reading the same result.+- References to query or mutation statements resolve to their results (section 6).++Value statements the entry cannot reach are **orphans**. A statement referenced from a query's or mutation's arguments is reachable, since reachability follows that reference like any other, so it is never an orphan. When there is no `root` statement and no fallback entry, there are no orphans, and `no-root` reports the problem. Orphans go into the parse metadata and are not rendered. State, query, and mutation statements are never orphans, and a query runs whether or not the entry reaches it.++Fixtures: `evaluation/*-ref-*`++### 2.4 Duplicate names++If two statements bind the same name, the later one wins, whatever their kinds. While streaming, a pending statement that needed implicit closing never replaces a completed one (section 4, rule 3). At stream end a final redefinition wins.++Fixtures: `evaluation/*-duplicate-*`++## 3. Evaluation++### 3.1 Values and coercion++Values are strings, numbers, booleans, null, arrays, objects, and component instances.++Arithmetic and comparisons convert with `toNumber`: a number is itself, a string is parsed as a number or else 0 (NaN never appears), `true` is 1, and everything else is 0.++Truthiness follows JavaScript ToBoolean. Arrays, objects, and component instances are truthy. In an expression, a component instance acts like an object: `toNumber` gives 0 and member access gives null.++String-to-number parsing, loose equality, and number-to-string formatting follow ECMA-262 ToNumber, IsLooselyEqual, and Number::toString. Clients in other languages MUST reproduce them.++Fixtures: `evaluation/*-coerce-*`++### 3.2 Operators++- `+`: if either side is a string, it joins strings, and null becomes `""`. Otherwise it adds with `toNumber`.+- `-`, `*`, `/`, `%`: numeric with `toNumber`. A divisor of 0 gives 0.+- `==`, `!=`: loose equality per IsLooselyEqual. `5 == "5"` is true.+- `>`, `<`, `>=`, `<=`: both sides with `toNumber`.+- `&&`, `||`: short-circuit and return the deciding operand.+- `!` negates truthiness. Unary `-` negates `toNumber` of its operand.+- `cond ? a : b` chooses by the truthiness of `cond`.++In a component position, null renders nothing, and strings, numbers, and booleans render as text.++Fixtures: `evaluation/*-op-*`++### 3.3 Member access and pluck++- `a.b` on an object reads the field.+- `a.b` on an array plucks: `b` from every element, null where it is missing.+- `.length` on an array is its element count.+- Member access on null is null.+- `a[i]` indexes arrays by number and objects by string key. A null object or index gives null.++Fixtures: `evaluation/*-member-*`++### 3.4 Built-in functions++| Built-in | Signature | Meaning |+| --- | --- | --- |+| `@Count` | `(array) → number` | Element count. 0 for non-arrays. |+| `@First`, `@Last` | `(array) → value` | First or last element. Null for empty arrays and non-arrays. |+| `@Sum` | `(array) → number` | Sum with `toNumber`. 0 for non-arrays. |+| `@Avg` | `(array) → number` | Mean with `toNumber`. 0 for empty arrays and non-arrays. |+| `@Min`, `@Max` | `(array) → number` | Minimum or maximum with `toNumber`. 0 for empty arrays and non-arrays. |+| `@Filter` | `(array, field, op, value) → array` | Keeps elements whose `field` satisfies `op value`. Ops: `==`, `!=` (loose), `>`, `<`, `>=`, `<=` (numeric), `contains` (case-sensitive substring of the field as a string). An empty `field` tests the elements themselves. A missing op means `==`. An unknown op matches nothing. `[]` for non-arrays. |+| `@Sort` | `(array, field, direction?) → array` | Stable sort on `field`. An empty `field` sorts the elements themselves. When both values are numbers or strings that parse as numbers, they compare as numbers. Otherwise their string forms (null is `""`) compare with the runtime's locale collation (ECMAScript `localeCompare` with no arguments), so `a` sorts before `B`. Descending only when the third argument is `"desc"`. A non-array is returned unchanged. |+| `@Round` | `(number, decimals?) → number` | Rounds to `decimals` places, default 0, with JavaScript `Math.round` (a half rounds up). |+| `@Abs`, `@Floor`, `@Ceil` | `(number) → number` | With `toNumber`. |+| `@Each` | `(array, varName, template) → array` | Section 3.5. |++Field arguments accept dot paths (`"customer.name"`).++Fixtures: `evaluation/*-builtin-*`, including `evaluation/*-builtin-sort-*`++### 3.5 Iteration with `@Each`++`@Each(array, varName, template)` evaluates `template` once per element, with `varName` bound to it. A non-array gives `[]`.++- The loop variable exists only inside the template, where it shadows a statement of the same name. A nested `@Each` with the same `varName` shadows the outer one.+- There is no index variable.+- The element is put into the template before any deferred evaluation, so an action in the template captures its own element.++```openui-lang+rows = @Each(tickets.rows, "t", Row(t.title, Button("Close", Action([@Run(close), @Set($selected, t.id)]))))+```++Fixtures: none in `spec/fixtures/1.0/`.++### 3.6 Custom functions++A library declares extra functions in its `functions` list ([prompt.md](./prompt.md), section 2.5). Programs call them with `@`. Arguments are positional, in the key order of the function's `params` (the same rule as components).++- Built-ins are looked up first. A library MUST NOT register a function named like a built-in, an action, `Query`, `Mutation`, or one of its components.+- A `@Name` call that is not a built-in, an action, or a custom function evaluates to null and reports `unknown-function`. The statement is kept.+- Custom functions MUST be pure and synchronous. The runtime MAY cache results and MAY call them any number of times, in any order.+- Arguments are checked against `params` the same way component props are, with the same recovery (section 8.2). An invalid argument takes its default if it has one. Otherwise an invalid optional argument or array item is left out, and an invalid required argument makes the call evaluate to null. Extra arguments are dropped. Missing optional arguments take their defaults.+- Literal arguments are checked when parsing, with the same codes (`type-mismatch`, `missing-required`, `null-required`, and `excess-args` for extra arguments). Arguments that are only known at runtime are checked when the call runs, and a failed check reports `runtime-error`.+- A required argument that is null when the call runs, with no default (an unset `$variable`, an unresolved reference), makes the call evaluate to null with no error.+- A function that throws, or a return value that does not match `returns`, reports `runtime-error`, and the call evaluates to null.+- While streaming, a call runs on every update, like the built-ins. A call whose arguments are not yet valid evaluates to null, and the error is not reported until the stream ends.++Fixtures: `evaluation/*-function-*`, `errors/*-unknown-function-*`, `errors/*-function-literal-*`++## 4. Streaming++A client MUST accept input a chunk at a time and produce a valid render after every chunk.++1. **Statement completion.** A statement is complete when its ending newline has arrived and the rules of section 1.4 cannot extend it. For the ternary rule, the next line's first non-whitespace character must have arrived and not be `?`. Completed statements are parsed once and never change.+2. **The pending tail.** The text after the last completed statement is parsed on every chunk, after implicit closing. An unterminated string is closed (adding a `\` first if the text ends mid-escape). Then unclosed brackets are closed in reverse order. A closing bracket that does not match is skipped and leaves the bracket stack alone. A pending statement that still fails to parse is not produced.+3. **Pending does not overwrite completed.** A pending statement that needed implicit closing is discarded if a completed statement has the same name.+4. **Reconciliation.** If the prepared text no longer starts with the previously completed prefix (for example, a fence opener arrives), the client MUST discard its cache and parse again from the start.+5. **No placeholders.** An array element that is an unresolved reference is left out, as in section 2.3, not shown as a hole or skeleton.+6. **Interactive features wait.** Queries and mutations MUST NOT run while streaming. State declarations initialize as they arrive. A default read from a truncated statement MUST be replaced when the full statement arrives, unless the user has changed that state.+7. **The host ends the stream.** The language has no end marker. The host signals the end (in React, `isStreaming` turns false). A stored message records it with an `end` marker line ([prompt.md](./prompt.md), section 7). The signal finalizes the pending tail: implicit closing applies, and the resulting statements become completed, including a redefinition of an earlier name. Chunks after the signal are a new stream.++**Streaming equals parsing.** At stream end, the result MUST equal a batch parse of the full text: statements, entry, errors, and state defaults.++Fixtures: `streaming/`++## 5. State and forms++### 5.1 The state store and what is reactive++Every value is reactive: anything that uses a `$variable` or a query result evaluates again when that input changes. `$` marks only state the user or an action writes (input bindings, `@Set`, `@Reset`). Query results and derived values use plain names.++```openui-lang+$status = "open"+tickets = Query("listTickets", { status: $status }, { rows: [] })+openCount = @Count(tickets.rows)+```++The state store is a flat map from `$name` to value, scoped to one rendered program.++- A state declaration gives the default. An undeclared `$name` is declared automatically with the default null.+- Defaults apply only when the variable has no value yet. Parsing again, while streaming or after an edit, MUST NOT overwrite a value the user produced.+- Persisted state from the host is applied over the defaults at initialization.+- Parsing again never deletes a key.++Fixtures: `state/*-store-*`++### 5.2 Two-way binding++A `$variable` passed to a bindable prop, one whose signature prints it as `$binding<type>` ([prompt.md](./prompt.md), section 2.3), creates a two-way binding: the component shows the value and writes user changes back. A `$variable` passed to any other prop evaluates to its current value.++```openui-lang+$query = ""+search = Input("search", "Search tickets", "text", null, $query)+```++(This uses the reference library's `Input(name, placeholder, type, rules, value)`.)++Fixtures: `state/*-binding-*`++### 5.3 Form state++Fields group under the nearest enclosing form component, one that gives a form name to its subtree (like the reference library's `Form`). Inputs outside any form write into **page-level state**, the unnamed default scope.++Form values persist across parses. When an action sends a message to the model, the form state goes with the event (section 6.3). Hosts MAY persist form state and restore it when rendering a stored program again ([prompt.md](./prompt.md), section 7).++Fixtures: `state/*-form-*`++### 5.4 Validation rules++Validation rules are an object argument on input components, for example `{ required: true, email: true, maxLength: 80 }`. The rules are `required`, `email`, `url`, `numeric`, `minLength`, `maxLength`, `min`, `max`, and `pattern`.++- `email` checks the shape `[email protected]` with no spaces, with the regular expression `^[^\s@]+@[^\s@]+\.[^\s@]+$`.+- `url` checks for an absolute URL with a scheme and a host.+- `numeric` passes a number that is not NaN, or a string that is not blank and whose ECMAScript `parseFloat` is not NaN. So `"12abc"` passes.+- `pattern` is a regular expression with no flags. It uses only features common to ECMAScript and ICU: character classes, quantifiers, anchors, groups, and alternation. Lookbehind and backreferences are not required.+- Every rule except `required` skips empty values: null, `""`, an empty array, or an object with no keys.+- The first failing rule gives the field its error.+- A form submits only when every field passes.++Fixtures: `state/*-validation-*`++## 6. Data and actions++### 6.1 Query lifecycle++`name = Query(tool, args, defaults, refreshSeconds?)`: the tool name, the argument object, the result shown until data arrives, and an optional refresh interval in seconds.++- A query runs when streaming ends, and again when a `$variable` written literally in its `args` changes. State reached through a referenced statement does not trigger a fetch.+- While a fetch for changed arguments is in flight, the previous result stays visible. A result for stale arguments is discarded.+- References resolve to the latest result, or to the defaults before the first one. The reserved keys `__openui_loading`, `__openui_refetching`, and `__openui_errors` expose fetch state to the host. Expressions cannot read them.+- A refresh interval runs the query again on a timer.+- References inside Query and Mutation args resolve to their statements' values before the call, the same as anywhere else.++Fixtures: `actions/*-query-*`++### 6.2 Mutation lifecycle++`name = Mutation(tool, args)` runs only through `@Run`, never on load.++- Its `args` are evaluated when it runs, with the current state.+- References resolve to `{ status, data, error }`. `status` is `idle`, `loading`, `success`, or `error`.+- While `loading`, a second run is rejected.++Fixtures: `actions/*-mutation-*`++### 6.3 Actions++An action is a `@` call such as `@ToAssistant("Hi")` in an action position. `Action([a, b, ...])` holds several actions. A component triggers them through its action prop. An action position is a prop whose schema is a `$ref` to `ActionExpression`, or an `anyOf` of `$ref`s to action names ([prompt.md](./prompt.md), section 2.3). Such a restricted slot shapes the prompt and the schema only. In 1.0 it accepts any action or `Action([...])`. Actions run in order. A mutation run is awaited. Query fetches and host events are sent without waiting.++- `@Set($var, value)`: evaluates `value` when the action runs, and writes it.+- `@Reset($a, $b, ...)`: restores the declared defaults (null if none).+- `@Run(ref)`: runs a mutation or fetches a query again. A failed mutation stops the remaining actions. `@Run` on a query never stops them.+- `@ToAssistant(message, context?)`: sends a `continue_conversation` event with the message, the optional context, and the form state.+- `@OpenUrl(url)`: sends an `open_url` event.+- `@Name(args)`, a custom action from the library's `actions` ([prompt.md](./prompt.md), section 2.5): sends an event with `type` set to `Name`, `params` holding the arguments keyed by the action's param names, and an empty `humanFriendlyMessage`. Arguments map by position in the key order of the action's `params` and are checked like custom function arguments (section 3.6), with one difference: any invalid argument, even an optional one with a default, makes the action do nothing. A literal one is reported when parsing (for example `type-mismatch`), and one known only at runtime reports `runtime-error`. A required argument that is null when the action is built, with no default, also makes it do nothing, with no error. Extra arguments are only dropped.++`@Run`, `@Set`, and `@Reset` name their targets instead of evaluating them: `@Run` takes a query or mutation reference, `@Set` and `@Reset` take state variables. The `@Each` template is deferred the same way.++**One action.** Every action call evaluates to an `Action` of one action, wherever it is written, so one action needs no wrapper: `Button("Save", @ToAssistant("Save"))` equals `Button("Save", Action([@ToAssistant("Save")]))`. Several actions need `Action([...])`. A plain list of actions, such as `[@Set($saved, true), @ToAssistant("Saved")]`, is not an `Action`. It is plain data, a list of one-action `Action`s, and the component receives it as it is. It is not reported as an error, even though a strict JSON Schema reader would find that a list does not match `ActionExpression`.++**Context.** The `context` of `@ToAssistant` may be any value. The host receives it unchanged in `params.context` and decides how it reaches the model ([prompt.md](./prompt.md), section 6.3).++**Form state timing.** Each event carries the form state as of when its action runs, so an earlier `@Set` in the same `Action([...])` is visible.++Components MAY define a default action. The reference library's button with no action sends `continue_conversation` with its label as the message.++Events reach the host in one shape:++```json+{ "type": "continue_conversation",+ "humanFriendlyMessage": "Ticket closed",+ "params": { "context": { "ticket": "T-42" } },+ "formName": "ticket",+ "formState": { "ticket": { "status": { "value": "closed", "componentType": "input" } } } }+```++- `formName` is the nearest form around the triggering component, absent otherwise.+- Inside a form, `formState` holds that form's fields, each as `{ value, componentType }`. Outside a form, it holds the page's `$variables` with their plain values, and the page-level fields, each as `{ value, componentType }` (section 5.3).+- `open_url` events carry the same fields, with `params.url` and an empty `humanFriendlyMessage`.++Fixtures: `actions/*-several-actions`, `actions/*-one-action*`, `actions/*-event-*`, `actions/*-custom-*`, `actions/*-action-list-*`++### 6.4 Tool resolution++The host supplies tools as a map of async functions keyed by name, or as an MCP client. Tool names are case-sensitive. A missing tool fails the query or mutation with `tool-not-found` and a hint listing the tools. It MUST NOT crash the host.++Fixtures: `actions/*-tool-*`++## 7. Incremental editing++In edit mode, the model gets the current program and answers with a patch: only the changed statements. The host merges the patch into the current program by name:++- A patch statement whose name exists replaces the original. A new name is appended. Names absent from the patch are kept.+- The merged program has each name once: the last definition wins.+- A top-level `name = null` in a patch deletes the statement, state declarations included. (Inside one program it is an ordinary binding.) Deleting a state declaration never deletes its store key (section 5.1).+- After merging, statements `root` cannot reach are removed, unless there is no `root` statement. Reachability is the same as for orphans (section 2.3), so a statement referenced from a query's or mutation's arguments is never removed. State declarations are always kept.++The merge MUST read both texts with sections 1.2 and 1.4, including multi-line ternaries. The host decides when a text is a patch, and merges it once the patch has finished streaming. Merging earlier would remove statements that a half-written `root` cannot reach yet. If the reply is prose plus a fenced patch, only the fenced part is merged.++Fixtures: `editing/`++## 8. Errors and recovery++### 8.1 Drop and render++**A mistake removes the smallest possible unit, and everything else renders.** An invalid argument degrades the prop, an invalid component drops the component, and an invalid statement drops the statement. Nothing a model writes crashes the client, and every removal is reported.++Fixtures: `errors/`++### 8.2 Error codes++A **fatal** error means nothing renders. Any other error leaves the rest of the page rendering.++| Code | Source | Meaning | Recovery |+| --- | --- | --- | --- |+| `unknown-component` | parser | Component not in the library | Component dropped (section 8.4) |+| `missing-required` | parser | Required prop absent | Filled from the schema default if there is one, else the component is dropped |+| `null-required` | parser | Required prop is null | Same as `missing-required` |+| `type-mismatch` | parser | Argument does not match the prop's type or enum | Schema default if any. Otherwise the optional prop or array item is removed; a required prop drops the component |+| `excess-args` | parser | More arguments than props | Extra arguments dropped, component renders |+| `inline-reserved` | parser | `Query` or `Mutation` in a value position | Expression evaluates to nothing |+| `unknown-function` | parser | `@Name` is not a built-in, an action, or a custom function | The call evaluates to null. The statement is kept |+| `no-root` | parser, runtime | No usable entry (section 2.2), stream complete. `runtime` when a `root` expression such as a ternary gives no component | Non-fatal when the fallback entry renders. Fatal otherwise |+| `parse-failed` | parser | The response has text but yields no statements | Fatal |+| `parse-exception` | parser | The parser itself failed | Fatal. The client MUST catch it |+| `runtime-error` | runtime | Evaluating an expression threw | The prop whose evaluation threw becomes null |+| `render-error` | runtime | A component renderer threw | Contained. The last good render is kept |+| `tool-not-found` | query, mutation | Unknown tool name | A query keeps its defaults. The hint lists the tools |+| `tool-error`, `mcp-error` | query, mutation | The tool call failed | A mutation result carries the error. A query keeps its defaults or last good data |++`no-root` and enum checks wait for the stream to end. Type checks on scalars run while streaming.++Fixtures: `errors/*-<code>-*` (one folder per code, for example `errors/*-no-root-*`)++### 8.3 The error object++Errors cross the wire in one shape, ready to paste into a model conversation:++```json+{+ "source": "parser",+ "code": "missing-required",+ "statementId": "chart",+ "component": "BarChart",+ "path": "/labels",+ "message": "missing required field \"/labels\"",+ "hint": "Signature: BarChart(labels*, series*, variant). * marks required"+}+```++`hint` is a short signature from the JSON Schema (prop names only, required props starred), or the available names for an unknown name. Query and mutation errors add `toolName`. An error the page renders through, today only the non-fatal `no-root`, carries `"severity": "warning"`. Other errors have no `severity`.++- When a stream starts, the client clears its errors and emits an empty list if the last list was not empty.+- At stream end, and after each later render, the client emits the error list if it changed.+- Clients MUST NOT emit an unchanged list again. They MUST signal recovery by emitting an empty list.++Fixtures: `errors/*-shape-*`++### 8.4 Component validation++Arguments map to props by position against the library schema, then each prop is checked per section 8.2. Also:++- A list prop needs `[...]`, even for one item. A bare value is a `type-mismatch`.+- A slot that takes only components (every option of its schema is a `$ref` to a component) accepts any component. Data there (an object, array, string, number, or boolean) is a `type-mismatch`, and the value is left out.+- Inside arrays, invalid components and unresolved references are left out, in computed expressions too (section 2.3). Explicit `null` literals are kept and render nothing.+- An unknown component in a value position is dropped. In a computed expression it stays in the tree for the error to point at, but renders nothing.++Fixtures: `errors/*-validate-*`++## 9. The program tree and serialization++### 9.1 The tree++Parsing produces a tree: each statement's name and kind, and for component calls the type with arguments mapped to named props. Evaluation and rendering use the tree. The fixtures summarize it (Appendix B).++### 9.2 Serialization++A rendered tree serializes back to source text:++- The entry statement comes first. Every other named component becomes its own statement, children before parents.+- Props are written by position in schema order. `null` holds an unfilled required position. Trailing nulls for optional props are trimmed.+- Object keys are written unquoted, so they must be valid names to round-trip.+- State declarations from the host come after the component statements.+- Query and mutation statements do not round-trip.++Serialized output SHOULD parse back to an equal tree, up to the recovery rules of section 8. Serializers SHOULD add parentheses where parsing back would change the grouping, as in `a - (b - c)` and `-(a + b)`.++Fixtures: `grammar/*-roundtrip-*`++## 10. Client checklist++A conforming client:++- MUST parse the complete grammar of section 1, even parts it does not run, and drop only the statements that need a missing part.+- MUST follow sections 2.2 (entry), 4 (streaming), 7 (edit merge), and 8 (recovery and error reporting) exactly.+- MUST NOT let generated content crash the host, including renderers that throw.+- MUST resolve tools case-sensitively and keep user-entered state across parses and edits.+- SHOULD give hosts a hook for unknown components, to show a diagnostic instead of blank space.+- MAY pace the visual reveal of streamed content, as long as parsing follows section 4.++## Appendix A. A worked streamed example++Four chunks arrive. The library's root component is `Card`.++1. `root = Card([header, kpis])\nheader = Head`: `root` completes, and `header` is pending as the reference `Head`. Render: an empty Card.+2. `er("Tickets", "Today")\nkpis = Stack([open`: `header` completes. Pending `kpis` closes to `Stack([open])`, and unresolved `open` is left out. Render: Card, Header, empty Stack.+3. `, closed])\nopen = Metric("Open", @Count(@Filter(tickets.rows, "status", "==", "open")))\n`: `kpis` and `open` complete. `closed` and `tickets` are unresolved. Render: one Metric, count 0.+4. `closed = Metric("Closed", 8)\ntickets = Query("listTickets", {}, { rows: [] })\n`: the host ends the stream, and the result equals a batch parse. The query runs and the metrics update.++Every frame was a valid page, with no errors and no placeholders.++Fixtures: `streaming/001-worked-example`++## Appendix B. Conformance fixtures++A client claims conformance by passing the fixtures for its version, such as `spec/fixtures/1.0/`. If the prose and the fixtures disagree, that is a spec bug, and the next release fixes both.++```text+spec/fixtures/<version>/<area>/<NNN-short-name>/+```++The areas are `grammar`, `entry`, `streaming`, `evaluation`, `state`, `actions`, `editing`, and `errors`. Each "Fixtures:" line names a folder or a narrower pattern such as `entry/001-*`.++Each case holds:++- `input.oui`: the program text. Streaming cases use `chunks.json` instead, a JSON array of strings, the chunks in order.+- `expected.json`: the expected result after the stream ends.+- `interactions.json`: action and form cases only. User input and tool results, and what the host should see.++`expected.json`:++```json+{+ "root": {+ "type": "Card",+ "props": {+ "children": [+ { "type": "TextContent", "props": { "text": "Orders" } },+ { "type": "Input", "props": { "name": "q", "value": { "$binding": "$query" } } },+ { "type": "Button", "props": {+ "label": "Save",+ "action": { "actions": [{ "action": "ToAssistant", "args": ["Save order"] }] } } }+ ]+ }+ },+ "errors": [{ "code": "unknown-component", "statementId": "chart" }],+ "unresolved": ["footer"],+ "orphans": ["oldHeader"],+ "incomplete": false+}+```++- `root` is the rendered tree summary, or null when nothing renders. A component is `{ "type", "props" }`. Primitive props are plain values. Component props are nested summaries. Actions are `{ "actions": [ { "action", "args" } ] }`. Bindings are `{ "$binding": "$name" }`.+- `errors` lists `{ "code", "statementId" }` for each error.+- `unresolved` and `orphans` list names.+- `incomplete` is true when the input ended inside an unclosed string or bracket.++`interactions.json`:++```json+{+ "interactions": [+ { "type": ["search", "late"] },+ { "tool": "listTickets", "result": { "rows": [] } },+ { "click": "saveBtn" }+ ],+ "expected": {+ "events": [{ "type": "continue_conversation", "humanFriendlyMessage": "Save order" }],+ "state": { "$query": "late" }+ }+}+```++An interaction is `{ "click": "<statementId>" }`, `{ "type": ["<statementId>", "<text>"] }`, or `{ "tool": "<name>", "result": <json> }`. `expected.events` lists the host events in order, in the shape of section 6.3. `expected.state` is the final state.++## Appendix C. Changelog++- **2026-10-12**: 1.0, released with `@openuidev/lang-core` and `@openuidev/react-lang` 1.0.0. The entry is the `root` statement, or the first value statement whose value calls the library's root component, with a real `no-root` code. Added custom functions, custom actions, one action without a wrapper, any-value `@ToAssistant` context, form state read when the action runs, the `unknown-function` code, and the fixture layout. Streaming must equal a batch parse, and edits merge with the parser's statement boundaries.+- Earlier drafts: 0.9 community review (2026-07-22) and 1.0-beta (2026-08-05). See the git history.diff --git a/spec/overview.md b/spec/overview.mdnew file mode 100644index 000000000..d52fbcd95--- /dev/null+++ b/spec/overview.md@@ -0,0 +1,344 @@+# OpenUI Overview++**1.0**++The OpenUI specification is three documents:++- **overview.md** (this file): what OpenUI is, and a short tour of every feature with an example.+- **[language.md](./language.md)**: the exact rules of the language, for people who build parsers and renderers.+- **[prompt.md](./prompt.md)**: the LibrarySpec, the system prompt, and the message protocol.++Three roles appear throughout. The **model** writes OpenUI Lang. The **client** parses and renders it (in React, the `Renderer`). The **host** is your app around the client: it calls the model, provides tools, and stores messages.++## What's new in 1.0++1.0 makes OpenUI ready for production and for other implementations:++- **Conformance fixtures.** Plain-text cases with expected JSON results, so a client in any language can check that it parses, streams, evaluates, and runs actions the same way (`fixtures/1.0/`).+- **Message protocol.** One format for streamed and stored responses (section 4).+- **Stored UIs keep working.** Backward-compatibility rules for libraries (section 3).+- **Custom functions and actions.** A library adds its own `@` functions, like `@Percent` (section 2.11), and its own actions, which the host handles.+- **Extending a library.** `library.extend()` derives a library with components added, replaced, or removed (prompt.md, section 2.8).+- **Small conveniences.** One action needs no `Action([...])` wrapper, and any value as `@ToAssistant` context.++## 1. Introduction++### 1.1 What OpenUI is++OpenUI Lang is a compact, line-oriented language that a model writes to describe a user interface. It replaces JSON trees and raw HTML with a short program, one statement per line. The client renders the program while it streams in:++```openui-lang+root = Card([header, chart])+header = Header("Monthly Revenue", "Last 6 months")+chart = BarChart(labels, [series])+labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]+series = Series("Revenue", [12000, 15000, 14000, 18000, 21000, 25000])+```++Every line binds a name to a value. A name can be used before it is defined. The first line gives the shape of the page, and each later line fills it in.++### Quickstart++```tsx+// Server: send this as the system prompt.+import { generateSystemPrompt } from "@openuidev/lang-core";+import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui";++const systemPrompt = generateSystemPrompt({+ library: openuiLibrary.toSpec(),+ promptOptions: openuiPromptOptions,+});++// Client: render the model's text while it streams.+import { Renderer } from "@openuidev/react-lang";++<Renderer library={openuiLibrary} response={text} isStreaming={isStreaming} />+```++The full walkthrough is the [docs quickstart](https://openui.com/docs/openui-lang/quickstart).++### 1.2 Design goals++- **Few tokens.** Positional arguments and short names keep programs small, up to 67% smaller than the same UI in JSON.+- **Streams by default.** Every partial program is a valid page, so the UI builds up as the model writes.+- **Forgiving.** A mistake removes the smallest broken piece. The rest of the page still renders.+- **Interactive without the model.** State, expressions, and actions run in the client, with no round trip to the model.++### 1.3 The end-to-end flow++```mermaid+flowchart LR+ user([User]) -- "What did I spend last month?" --> app[Your app]+ app -- "system prompt from your library + message" --> llm["Model (any provider)"]+ llm -- "openui-lang stream" --> app+ app --> ren[OpenUI renderer]+ ren -- "live UI, streamed" --> user+ ren -- "queries and mutations" --> tools[Your data and tools]+ tools -- "live data" --> ren+```++Your app holds the data and the component library. The library generates a system prompt that teaches the model the language and your components. The model streams OpenUI Lang back, and the renderer draws it as it arrives. The page talks to your data through queries and mutations.++A turn looks like this:++```mermaid+sequenceDiagram+ participant App as Your app+ participant Model+ participant Renderer as OpenUI renderer+ participant User+ App->>Model: system prompt (generated from your library) + user message+ Model->>App: openui-lang, streamed token by token+ App->>Renderer: the streamed text+ Renderer->>User: page builds up as tokens arrive+ Note over App: stores the message (content, context, end)+ User->>App: action event (click, form submit, @ToAssistant)+ alt chat app+ App->>Model: follow-up with context and form state, ]]>openui: lines stripped+ Model->>Renderer: a new response, rendered as a new message+ else editing surface (canvas, dashboard, artifact)+ App->>Model: current program + the request+ Model->>Renderer: incremental edit: only the changed statements+ end+```++The app wraps each response in `]]>openui:` lines and stores it that way (section 4). The model never sees those lines. In a chat app, a click becomes a new turn and the model answers with a new message. In an editing surface, the model answers with only the changed statements, and the host merges them into the current program (section 2.6).++## 2. Features++Component names in the examples are examples only: every library defines its own.++### 2.1 Components++The model builds UI from components you define. Arguments are positional, in the order the library lists the props. Say `Button` lists `label`, `action`, `variant`:++```openui-lang+btn = Button("Save changes", saveAction, "primary")+```++The renderer receives `{ label: "Save changes", action: saveAction, variant: "primary" }`. Optional arguments at the end can be left out. `null` skips an optional argument in the middle.++Rendering starts at the statement named `root`. Everything it reaches renders. A statement nothing reaches is not rendered.++This statement is the **entry**. If there is no `root`, the first value statement (never a `$` declaration) whose value calls the library's root component is the entry, with a warning. Each library names its root component in its LibrarySpec. If `root` exists but is not a component, or there is no entry, nothing renders and the client reports `no-root` when the stream ends. Rules in language.md, section 2.2.++### 2.2 References and hoisting++A statement can use any other statement by name, wherever it appears:++```openui-lang+root = Card([title, kpis, refreshBtn])+title = Header("Support Overview")+kpis = Stack([openCount, closedCount])+openCount = Metric("Open", 12)+closedCount = Metric("Closed", 8)+refreshBtn = Button("Refresh")+```++The first line uses `title`, `kpis`, and `refreshBtn` before they exist. It lets the model write the layout first and the data last.++A name with no statement yet is unresolved. That means "not yet", not "error": the `Stack` shows one metric until `closedCount` arrives. When two statements bind the same name, the later one wins. Rules in language.md, sections 2.3 and 2.4.++### 2.3 Streaming++The client parses and renders again on every chunk, so a half-received response is always a valid page:++| Arrived so far | On screen |+| --- | --- |+| `root = Card([header, chart])` | An empty card. |+| `header = Header("Monthly Rev` | A header reading "Monthly Rev", filling in as the model types. |+| `enue", "Last 6 months")` | The full header. |+| `chart = BarChart(labels, [series])` | An empty chart. |+| `labels = [...]`, `series = Series(...)` | The bars fill in. |++The parser closes open brackets and strings for you, so `root = Card([header` already renders an empty card. When the stream ends, the result is the same as parsing the full text at once. The host tells the client when the stream ends (in React, `isStreaming` turns false). Rules in language.md, section 4.++### 2.4 Actions++An action runs when the user clicks. A button can send a message back to the model or open a link:++```openui-lang+askBtn = Button("Explain this chart", @ToAssistant("Explain the revenue chart"))+docsBtn = Button("Docs", @OpenUrl("https://example.com/docs"))+```++`@ToAssistant` takes an optional second argument, `context`. It can be any value, and the host receives it unchanged:++```openui-lang+approveBtn = Button("Approve", @ToAssistant("Approve this order", { orderId: 42 }))+```++For more than one action, wrap them in `Action([...])`. They run in order:++```openui-lang+closeBtn = Button("Close ticket", Action([@Run(save), @Set($showModal, false), @ToAssistant("Ticket closed")]))+```++There are five built-in actions: `@ToAssistant`, `@OpenUrl`, `@Set` and `@Reset` (for state, section 2.9), and `@Run` (for queries and mutations, section 2.10). A library can add its own actions, such as `@CopyToClipboard(text)`, which the host receives as events. A failed mutation stops the actions after it. Rules in language.md, section 6.3.++### 2.5 Forms and validation++Inputs carry validation rules as an object:++```openui-lang+email = Input("email", "[email protected]", "email", { required: true, email: true })+```++The renderer checks the rules, shows the messages, and blocks submit until they pass. The rules are `required`, `email`, `url`, `numeric`, `minLength`, `maxLength`, `min`, `max`, and `pattern`.++Inputs inside a form submit together. The form keeps each value under the input's `name`:++```openui-lang+contactForm = Form("contact", Buttons([submitBtn]), [nameField, emailField])+nameField = FormControl("Name", Input("name", "Your name", "text", { required: true }))+emailField = FormControl("Email", Input("email", "[email protected]", "email", { required: true, email: true }))+submitBtn = Button("Submit")+```++When a button sends a message, the form values go with it. Rules in language.md, sections 5.3 and 5.4.++### 2.6 Incremental editing++To change a page, the model sends a **patch**: only the statements that change. The host merges it into the previous program by name once the patch has finished streaming (in React, with `mergeStatements`). Merging earlier would drop statements a half-written `root` cannot reach yet. The page showing:++```openui-lang+root = Card([header, chart])+header = Header("Monthly Revenue", "Last 6 months")+chart = BarChart(labels, [series])+labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]+series = Series("Revenue", [12000, 15000, 14000, 18000, 21000, 25000])+```++The user says "show it weekly". The model answers:++```openui-lang+header = Header("Weekly Revenue", "Last 4 weeks")+chart = BarChart(weekLabels, [series])+weekLabels = ["W1", "W2", "W3", "W4"]+series = Series("Revenue", [4800, 5300, 5100, 6200])+```++Named statements are replaced, new ones are added, and `root` stays. Nothing uses `labels` any more, so it is removed. `chart = null` would delete the chart. Rules in language.md, section 7.++### 2.7 Expressions++The language has arithmetic, comparison, logic, `? :`, member access, and indexing. The client evaluates them, so derived values update without the model:++```openui-lang+status = TextContent(total > 100000 ? "On track" : "Behind target")+share = @Round(part / total * 100, 1)+```++Member access on a list gives that field of every element: if `sales.rows` is a list of objects, `sales.rows.amount` is the list of their amounts. Rules in language.md, sections 1.5, 3.2, and 3.3.++### 2.8 Built-in functions++Built-ins start with `@`:++- Aggregation: `@Count`, `@Sum`, `@Avg`, `@Min`, `@Max`, `@First`, `@Last`.+- Reshaping: `@Filter`, `@Sort`.+- Math: `@Round`, `@Abs`, `@Floor`, `@Ceil`.+- Iteration: `@Each`.++Calls nest, so a filtered, sorted list takes two lines and goes straight into a component:++```openui-lang+urgent = @Filter(tickets.rows, "priority", "==", "high")+newest = @Sort(urgent, "createdAt", "desc")+rows = @Each(newest, "t", Row(t.title, Tag(t.priority)))+```++`@Each(list, name, template)` builds the template once per element, with `name` bound to that element. Every built-in is defined in language.md, sections 3.4 and 3.5.++### 2.9 Reactive state++Variables that start with `$` hold state the user or an action changes: values bound to inputs, and values changed by `@Set` or `@Reset`. They tie components together: one component writes `$query`, others read it:++```openui-lang+$query = ""+search = Input("search", "Search tickets", "text", null, $query)+label = TextContent("Searching for " + $query)+```++Passing `$query` to an input binds it both ways. Typing updates `$query`, and everything that reads it updates too.++```openui-lang+$tab = "overview"+picker = Select("tab", [SelectItem("overview", "Overview"), SelectItem("billing", "Billing")], null, null, $tab)+body = $tab == "overview" ? overviewPanel : billingPanel+```++`$` marks what the user or an action can write. Reactivity is not limited to `$`: any statement that reads a `$` variable or a query result updates when that input changes. Tool data and derived values use plain names: `tickets = Query(...)`, `openCount = @Count(tickets.rows)`. A `$` variable with no declaration starts as `null`. Rules in language.md, section 5.++### 2.10 Queries and mutations++`Query` reads data from a tool your app provides. `Mutation` writes it. The model writes which tool to call. The host provides the tools:++```openui-lang+$days = "7"+data = Query("analytics", { days: $days }, { rows: [] })+filter = Select("days", [SelectItem("7", "7 days"), SelectItem("30", "30 days")], null, null, $days)+```++The arguments are the tool name, its arguments, and a default shown while loading. A `$variable` written directly in the arguments makes the query fetch again when it changes. A `$variable` reached only through another statement does not. An optional fourth argument refreshes on a timer in seconds.++A mutation runs only when an action runs it:++```openui-lang+createResult = Mutation("create_ticket", { title: $title })+submitBtn = Button("Create", Action([@Run(createResult), @Run(tickets), @Reset($title)]))+```++A mutation result has `status` (`idle`, `loading`, `success`, `error`), `data`, and `error`, so the page can show progress. Name queries without `$`: `tickets = Query(...)`. `$tickets = Query(...)` still runs the query, but `$tickets` in an expression reads the state store, not the result. Rules in language.md, section 6.++### 2.11 Custom functions++A library can add its own functions. The model calls them like built-ins:++```openui-lang+share = TextContent(@Percent(done, total))+```++The library declares each one with `defineFunction({ name, description, params, returns, fn })`. The program passes arguments by position, like components, and `fn` receives them as one object keyed by the `params` names. The prompt always lists custom functions. The implementation (`fn`) stays in the host's library and runs in the client, never in the prompt. Functions are pure and synchronous: same inputs, same output, no side effects. A call to an unknown `@` name evaluates to null and reports `unknown-function`. Rules in language.md, section 3.6, and prompt.md, section 2.5.++### 2.12 Error recovery++Models make mistakes, so the client removes the smallest broken piece and renders the rest. It reports each problem with the statement, the problem, and a hint:++```json+{ "source": "parser", "code": "unknown-component", "statementId": "chart",+ "message": "Unknown component PieChart", "hint": "Available components: BarChart, LineChart, Table" }+```++Send the error back to the model, and it can answer with a one-line fix through incremental editing. The full error table is in language.md, section 8.2.++## 3. Keeping stored UIs working++A stored program has no prop names. A stored call like `Button("Save", saveAction, "primary")` is only correct while `label, action, variant` is still the prop order. Three rules keep stored programs rendering as a library changes:++1. **Add props only at the end** of a component's prop list.+2. **Never reorder or remove a prop.** Leave an unused prop in place and ignore it.+3. **A new required prop needs a default**, because stored calls do not pass it.++Built-in names are reserved, so a library never uses a name like `@Count`. A library can have an `id` and a `version`. They are metadata and do not change parsing. The same rules for library authors are in prompt.md, section 3.2.++## 4. Streaming and storing responses++A response travels and is stored as plain text. The host wraps the program in a few lines of its own, each starting with `]]>openui:`:++```+]]>openui:content?library=support%401.2.0+root = Card([header, chart])+header = Header("Monthly Revenue", "Last 6 months")+]]>openui:context+{"formState": {"days": "30"}, "context": {"orderId": 42}}+]]>openui:end+```++- `content` holds the program (or prose).+- `context` holds JSON the host keeps with the message, such as form values and click data. The host defines its shape.+- `end` says the stream finished. A stored message without it was cut off. It still renders as far as it got.++The same format works while streaming and in storage. The model never writes or sees these lines: the host strips them before it sends history to the model. The client accepts text with or without them and ignores them when rendering. prompt.md, section 6.3, gives the reference format for turning a click into the next user turn.++The renderer still holds live state while the page is open. The `context` section is how that state is saved: when a stored message is loaded again, the host reads `context` and gives the form values back to the renderer. The full protocol is in prompt.md, section 7.diff --git a/spec/prompt.md b/spec/prompt.mdnew file mode 100644index 000000000..755e8df6b--- /dev/null+++ b/spec/prompt.md@@ -0,0 +1,435 @@+# The OpenUI Prompt and LibrarySpec++**1.0**++This document defines what is sent to the model: the LibrarySpec, the system prompt generated from it, and the conversation the model sees. It also defines the marker lines a host stores messages with. MUST, MUST NOT, SHOULD, and MAY are used as in RFC 2119.++For the language, see [language.md](./language.md). For the big picture, see [overview.md](./overview.md).++## 1. Overview++The model learns your UI system from two places:++1. **The system prompt.** Generated from the LibrarySpec and a set of options (section 4). It teaches the language, the component list, and only the features the client supports.+2. **The conversation.** User messages, the model's earlier OpenUI Lang responses, and context the host adds (error reports, form values, click data, the current program in edit mode).++Nothing else is sent. The prompt MUST NOT teach features the target client does not support.++## 2. The LibrarySpec++A LibrarySpec is one JSON document.++| field | meaning |+| --- | --- |+| `id` | Optional. The library name, for example `support`. `toSpec()` emits it when the library has one. A library made with `extend` does not inherit it. |+| `version` | Optional. The library version, for example `1.2.0`. `toSpec()` does not emit it. A host that versions its library adds it. |+| `root` | Optional. The root component name, for example `Card`. |+| `schema` | The validation schema (JSON Schema). Top-level `properties` names the components, `$defs` has one entry per component and per action a prop refers to, and `functions` and `actions` hold the params of the custom functions and actions (section 2.3). |+| `components` | Per component: `signature` and `description`, derived from `schema`. |+| `componentGroups` | Optional. Named groups that split the component list into titled parts. |+| `functions` | Custom functions: `signature` and `description`. |+| `actions` | Custom actions: `signature` and `description` (section 2.5). |++Example:++```json+{+ "id": "support",+ "root": "Card",+ "schema": {+ "properties": {+ "Card": { "$ref": "#/$defs/Card" },+ "Button": { "$ref": "#/$defs/Button" }+ },+ "$defs": {+ "Card": {+ "type": "object",+ "description": "A container",+ "properties": {+ "children": { "type": "array", "items": { "$ref": "#/$defs/Button" } }+ },+ "required": ["children"]+ },+ "Button": {+ "type": "object",+ "description": "A clickable button",+ "properties": {+ "label": { "type": "string" },+ "action": { "$ref": "#/$defs/ActionExpression" },+ "variant": { "type": "string", "enum": ["primary", "secondary"] }+ },+ "required": ["label"]+ },+ "ActionExpression": {+ "anyOf": [+ { "type": "object", "properties": { "type": { "const": "open_url" }, "url": { "type": "string" } }, "required": ["type", "url"] },+ { "type": "object", "properties": { "type": { "const": "continue_conversation" }, "context": { "type": "string" } }, "required": ["type"] },+ { "type": "object", "properties": { "type": { "type": "string" }, "params": { "type": "object" } }, "required": ["type"] }+ ]+ }+ },+ "functions": {+ "Percent": {+ "description": "Format part / total as a percentage",+ "params": {+ "type": "object",+ "properties": {+ "part": { "type": "number" },+ "total": { "type": "number" }+ },+ "required": ["part", "total"]+ },+ "returns": { "type": "string" }+ }+ },+ "actions": {+ "CopyToClipboard": {+ "description": "Copy text to the clipboard",+ "params": {+ "type": "object",+ "properties": { "text": { "type": "string" } },+ "required": ["text"]+ }+ }+ }+ },+ "components": {+ "Card": {+ "signature": "Card(children: Button[])",+ "description": "A container"+ },+ "Button": {+ "signature": "Button(label: string, action?: ActionExpression, variant?: \"primary\" | \"secondary\")",+ "description": "A clickable button"+ }+ },+ "functions": {+ "Percent": {+ "signature": "Percent(part: number, total: number) → string",+ "description": "Format part / total as a percentage"+ }+ },+ "actions": {+ "CopyToClipboard": {+ "signature": "CopyToClipboard(text: string)",+ "description": "Copy text to the clipboard"+ }+ }+}+```++### 2.1 `id` and `version`++`id` and `version` are metadata. A host uses them in the `library=` attribute of a stored message (section 7) and to name a prompt version. They do not change how a program is parsed.++### 2.2 `root`++`root` names the library's root component, used in the entry rule ([language.md](./language.md), section 2.2). When present, it MUST name a component in `components`. Without `root`, only a statement named `root` is an entry.++### 2.3 The validation schema++The schema is the single source of truth for a component's arguments.++- The key order of a component's `properties` in `$defs` is its positional order. `Button("Save", a, "primary")` maps `label`, `action`, `variant` in that order.+- `required` lists the props that must be present. A prop's `default` fills a missing required argument before the component is dropped.+- A prop that takes a component is a `$ref` to that component's `$defs` entry, `{ "$ref": "#/$defs/Card" }`, or an `anyOf` of such `$ref`s. A list of components puts this in its `items`.+- An action prop is `{ "$ref": "#/$defs/ActionExpression" }` and takes any action. The `ActionExpression` entry describes the legacy action objects (`{ "type": ... }`). A prop that takes only some actions is an `anyOf` of `$ref`s to action names, for example `#/$defs/CopyToClipboard` and `#/$defs/OpenUrl`, each with its own `$defs` entry.+- A reader classifies each `$ref` by its name. Components are the names in the schema's top-level `properties`. Actions are the names in `actions` plus the built-in names `ActionExpression`, `OpenUrl`, and `ToAssistant`.+- The schema has no marker for binding props. A binding prop has only its value type in the schema, for example `{ "type": "string" }`. Its `signature` prints it as `$binding<string>` (section 5.1), and that is where a reader learns it.++Readers MUST keep the key order of `properties` when they read the schema, because it is the positional order.++### 2.4 Derived signatures++Each entry in `components` has a `signature` and a `description`. The `signature` is derived from the schema. If they disagree, the schema wins, and a consumer SHOULD rebuild the signature from it. The one exception is `$binding<type>`, which only the signature carries. The format is in section 5.++### 2.5 Custom functions and actions++A library declares pure functions with `defineFunction({ name, description, params, returns, fn })`. The schema keeps its description, `params` (a JSON Schema object whose key order is the positional order, as for components), and `returns` in `schema.functions`. The LibrarySpec's `functions` keeps its signature and description. `fn` never serializes. It receives one object keyed by the `params` names. Each client implements the function itself.++A program calls a custom function like a built-in, with the `@` prefix and positional arguments in the key order of `params`:++```+share = TextContent(@Percent(done, total))+```++The prompt lists custom functions next to the built-ins. Lookup goes to built-ins first, then custom functions. A call to a name that is not a built-in, an action, or a custom function evaluates to null, like an unresolved reference, and reports `unknown-function`. The statement is not dropped ([language.md](./language.md), sections 3.6 and 8.2).++**Custom actions.** A library declares its own actions with `defineAction({ name, description, params })`. The schema keeps their description and `params` in `schema.actions`, with no `returns`. The LibrarySpec's `actions` keeps their signatures and descriptions. A program uses one like a built-in action, `@CopyToClipboard("text")`, alone or inside `Action([...])`. The client does not run it. The host receives it in `onAction` ([language.md](./language.md), section 6.3). The prompt lists custom actions with the built-in actions.++Fixtures: `evaluation/*-function-*`, `errors/*-unknown-function-*`, `actions/*-custom-*`++### 2.6 What the spec does not do++The LibrarySpec drives prompt generation and validation, not rendering. Each platform writes its components natively and decides how they look and behave, including which props bind to state and how inputs attach to forms.++### 2.7 Output from the tools++`library.toSpec()` returns the document above. `library.toJSONSchema()` returns the `schema` alone. The CLI command `npx @openuidev/cli generate` writes the system prompt and, with `--out prompt.txt`, a `prompt.spec.json` beside it. `--json-schema` prints the schema alone. `--spec` prints the full spec.++Fixtures: none. The spec shape is checked on the library, not by program fixtures.++### 2.8 Extending a library++`library.extend({ components, functions, actions })` returns a new library and leaves the base unchanged.++- `components.add` appends components. An entry `{ component, slots }` also adds the component to those slots' `$ref` unions. A slot is `"Parent.prop"`, or `"Parent"` when the parent has one content slot.+- `components.override` replaces a component by name. Every slot that referred to the old one refers to the new one.+- `components.remove` drops components from the list, from every slot union, and from `componentGroups`. Removing the root, or the only type a prop accepts, is an error.+- `functions.add` and `actions.add` add custom functions and actions (section 2.5).+- Adding a name that already exists is an error.++The result is an ordinary library. Its LibrarySpec follows this section, without the base's `id`.++Fixtures: none. Checked on the library.++## 3. Rules for libraries++### 3.1 Conformance++- Component names MUST start with an uppercase letter and match the identifier rule.+- Custom function and action names MUST start with an uppercase letter, like the built-ins (`@Percent`).+- Required props MUST come before optional props in positional order. A required prop that has a `default` counts as optional here, so it may be added at the end.+- A library MUST NOT define components named `Query`, `Mutation`, or `Action`.+- A library MUST NOT use a built-in name for a component, a function, or an action. New built-in names are reserved when added.+- Custom functions MUST be pure and synchronous. They read their arguments and return a value. They do not touch state, the network, or the clock.+- `root`, when present, and every component in `componentGroups` MUST exist in `components`.++Fixtures: none. These are definition-time checks on the library.++### 3.2 Backward compatibility++Stored programs are plain text. They stay readable as long as libraries follow these rules:++1. **Only add props at the end.** Never reorder props. Never remove a prop.+2. **New required props need a default.** An old program cannot supply it, so the `default` fills it. With a default, the prop counts as optional (section 3.1), so it goes at the end, as rule 1 says.+3. **New built-in names are reserved.** Library components and functions MUST NOT use them.++Position is the meaning of an argument, which is why rule 1 matters most. [overview.md](./overview.md), section "Keeping stored UIs working", says the same in plain words.++Fixtures: none. These are authoring rules for library owners.++## 4. Prompt generation++### 4.1 Determinism++The system prompt is a function of the LibrarySpec and the options. The same inputs give byte-identical prompts on every platform.++The entry point is `generateSystemPrompt({ library, promptOptions })`. The flat `generatePrompt(spec)` form is deprecated.++Fixtures: none in `spec/fixtures/1.0/`.++### 4.2 Options++| option | effect |+| --- | --- |+| `toolCalls` | Teaches `Query`, `Mutation`, and `@Run`. Defaults to true when `tools` is given. |+| `bindings` | Teaches `$variables`, `@Set`, `@Reset`, and `$binding<type>` props. Defaults to true when `toolCalls` is on. |+| `builtinFunctions` | Lists the built-in functions even when `toolCalls` and `bindings` are off. |+| `editMode` | Teaches editing by changed statements (section 6.4). |+| `inlineMode` | Teaches prose plus fenced code. |+| `tools` | Tool descriptors: a name string, or `{ name, description?, inputSchema, outputSchema, annotations? }`. |+| `preamble`, `examples`, `toolExamples`, `additionalRules` | Extra text the host adds to the prompt. |++The built-in function section appears when `toolCalls` or `bindings` is on, or when `builtinFunctions` is true. Custom functions are listed in the same section, which prints whenever the library has any, since they also work in plain props.++The inline mode section teaches that openui-lang goes inside fences, with prose around them, and that a question gets an answer in text only.++### 4.3 What the 1.0 prompt teaches++- The entry statement `root`, written first.+- Positional arguments only, with optional arguments left out from the end.+- One action needs no wrapper. Several go in `Action([...])`.+- Restricted action slots and `$binding<type>` props, when the library has them.++### 4.4 Order of the prompt++1. The syntax rules: statement shape, positional arguments, and the entry statement `root`.+2. The component list (section 5).+3. The built-ins and the tool section, when the options turn them on, and the custom functions, when the library has any.+4. The hoisting and streaming guidance.+5. The edit mode and inline mode sections, when the options turn them on.++Components appear in the order they are listed in `components`. `componentGroups` split the list into titled sections. A group is `{ name, components, notes? }`. Components in no group go under "Other".++Fixtures: none in `spec/fixtures/1.0/`.++## 5. Component signatures and descriptions++Each component is one line in the prompt: the signature, a separator, and the description.++```+Button(label: string, action?: ActionExpression, variant?: "primary" | "secondary")+```++The separator is a space, an em dash, and a space, followed here by `A clickable button`. The line MUST stay on one line.++### 5.1 Signature format++- Primitive types print as `string`, `number`, `boolean`, `any`.+- Enums print as quoted alternatives joined by `|`.+- Arrays print as `T[]`.+- Inline objects print as `{field: type}`.+- Unions are joined by `|`.+- An optional prop has `?` before the colon: `variant?: "primary"`.+- A prop that binds to state prints as `$binding<type>`.+- A restricted action slot prints its actions with `@`: `share?: @CopyToClipboard | @OpenUrl`.+- Names such as `ActionExpression` come from ids the library gives to shared schemas.++### 5.2 Descriptions++A description SHOULD say what the type does not: units, ranges, and when to use each enum member. It SHOULD NOT repeat the type.++### 5.3 Error hints++Error `hint` fields do not reuse the signature line. They carry a shorter form: prop names only, with required props marked by a star ([language.md](./language.md), section 8.3).++Fixtures: none in `spec/fixtures/1.0/`.++## 6. The conversation++### 6.1 History++The model's earlier responses appear in history as the OpenUI Lang text it wrote, with surrounding prose in inline mode.++The host removes every marker line (section 7) from history before the model sees it. The rules in section 3.2 keep stored programs readable across library changes.++Fixtures: none in `spec/fixtures/1.0/`.++### 6.2 Error feedback++When a response had errors, the host SHOULD send the structured error list in the next request. The wire shape is in [language.md](./language.md), section 8.3. Each error has a `hint`.++Fixtures: `errors/`++### 6.3 Action events++A user action that continues the conversation becomes the next user turn. It has three parts:++- the message, written for people (`@ToAssistant("Save order")`);+- the `context`, any value the program passed as the second argument: a string, number, object, or array;+- the form state.++The host receives `context` unchanged in `params.context`. How it reaches the model is up to the host (see "Reference format" below). The host writes the context and form state in a `context` section (section 7). The event shape is in [language.md](./language.md), section 6.3.++Form state is read when the action runs, not when the click starts. A `@Set` earlier in the same `Action([...])` is visible in the form state.++One action can stand alone in an action position:++```+Button("Save", @ToAssistant("Save order"))+```++This equals `Button("Save", Action([@ToAssistant("Save order")]))`. It works for `@ToAssistant`, `@OpenUrl`, `@Set`, `@Reset`, `@Run`, and custom actions. Several actions need `Action([...])`. A plain list of actions is data, not an `Action`.++**Reference format.** Hosts may use their own format. The reference chat client and the reference backend use this one. The user turn is stored as:++```+]]>openui:content+<message text>+]]>openui:context+["User clicked: <message>", <formState object>, <context value if any>]+```++The model receives one user message: `<message text>`, a newline, then `context and form values = <that JSON>`. All marker lines are removed. The third element, the `@ToAssistant` context, is new in 1.0. Earlier assistant turns reach the model as their program text only, with markers and stored form state removed.++Fixtures: `actions/`++### 6.4 Edit mode++With `editMode` on, the host sends the current program with the request. The model answers with a patch, only the changed statements, and the host merges it into the current program after it finishes streaming. Without `editMode`, every response is a complete program.++The merge uses the same statement boundary rules as parsing ([language.md](./language.md), section 1.4), including ternaries that span several lines. The merge rules are in [language.md](./language.md), section 7.++Fixtures: `editing/`++## 7. The message protocol++A host stores a response as text, with the program wrapped in marker lines. The model never writes or sees these lines.++### 7.1 Marker lines++```ebnf+marker = "]]>openui:" kind [ "?" attributes ] line_end ;+kind = lowercase_letter { lowercase_letter } ;+line_end = "\n" | "\r\n" | end of message ;+```++The kind ends at the first `?` or line end. Example:++```+]]>openui:content?library=support%401.2.0+```++The attributes are a query string in `application/x-www-form-urlencoded` form, as produced by `URLSearchParams`. Pairs are `key=value`, joined by `&`. `%40` is the encoded `@`, and a space is written `+`. Readers decode the string the same way and accept an unencoded `@`.++A marker counts only at the very start of a line. `]]>openui:` in the middle of a line is ordinary text, with one exception: a `content` marker (`]]>openui:content` followed by `?`, a line end, or the end of the message) in the middle of a line starts a new line there. A regenerated response is written right after the cut-off text of the failed one, and this keeps the last content winning.++Fixtures: none in `spec/fixtures/1.0/`.++### 7.2 Kinds and sections++| kind | shape | body |+| --- | --- | --- |+| `content` | Opens a section. | The program, or prose with fenced programs. |+| `context` | Opens a section. | JSON defined by the host. OpenUI requires no structure. |+| `end` | One line. No body. | The stream reached its last chunk. |++A section body starts on the line after its marker and runs up to the next marker line, or to the end of the message. The newline just before the next marker line is not part of the body.++In a stored message, a missing `end` line means the stream died before it finished. A reader still renders the content.++The reference chat client stores `[formState]` as the context of an assistant turn, and the array in section 6.3 for a user turn. That is its own usage, not a shape OpenUI requires.++Example:++```+]]>openui:content?library=support%401.2.0+root = Card([title, saveBtn])+title = TextContent("Order")+saveBtn = Button("Save", @ToAssistant("Save order", {"orderId": 42}))+]]>openui:context+{"formState":{"note":"rush"},"context":{"orderId":42}}+]]>openui:end+```++Fixtures: none in `spec/fixtures/1.0/`.++### 7.3 Reading messages++1. **Last `content` wins.** With more than one `content` section, the reader uses the last one. A `context` section or `end` line that comes before it belongs to an earlier attempt and is ignored.+2. **Text before the first marker.** It is the content when the message has no `content` marker. Otherwise the reader ignores it.+3. **Unknown attributes** are ignored.+4. **Unknown kinds.** The reader strips the marker line and its text up to the next marker line.+5. **Text after `end`.** Hosts never write it. A reader keeps it with the section the `end` line interrupted.+6. **Display.** The reader never shows marker lines, and never shows the `context` section as content.++While a response streams, the last line may be incomplete. If that line starts with `]]>openui:`, or is a prefix of it, the reader holds it back until its newline arrives or the stream ends. A partial `content` marker at the end of a line is held back the same way.++Fixtures: none in `spec/fixtures/1.0/`.++### 7.4 Writing messages++The host writes the markers. It puts a `content` line before the response and, when it has form state or click context, a `context` line before the JSON. It writes `end` when the stream finishes. To name the library, it writes `library=<id>@<version>`, with `id` and `version` from the LibrarySpec (section 2.1), encoded as in section 7.1.++The attribute tells a later reader which library wrote the message. It does not change how the program is parsed.++Fixtures: none in `spec/fixtures/1.0/`.++### 7.5 What the model sees++Nothing of this protocol. The party that builds a model request MUST strip every marker line, and every section body it does not use, before the text reaches the model. The party that shows a message MUST strip every marker line before display. The prompt never teaches the syntax.++Fixtures: none in `spec/fixtures/1.0/`.++### 7.6 Older forms++- The attribute `libraryVersion` (a version with no library id) is still written by some hosts. Readers return it like any other attribute.+- Other envelopes, such as an XML `<content>`/`<context>` wrapper or an artifact header, are host-specific. OpenUI readers do not read them; the host that writes them reads them.++Fixtures: none in `spec/fixtures/1.0/`.++## Appendix A. Changelog++- **2026-10-12: 1.0.** The LibrarySpec is one document with `id`, `version`, `root`, the schema, signatures, `functions`, and `actions`. Libraries can be extended. Prompts are deterministic. Libraries follow backward-compatibility rules. The message protocol uses `content`, `context`, and `end` marker lines.+- Earlier drafts: 0.9 community review (2026-07-22) and 1.0-beta (2026-08-05). See the git history for their changes.