The Open Standard for Generative UI
Add Generate Spec to CLI & extend toSpec() (#747)
AB8ecdcfda87cf
diff --git a/docs/content/docs/api-reference/cli.mdx b/docs/content/docs/api-reference/cli.mdxindex 015a1a460..1d2b94d06 100644--- a/docs/content/docs/api-reference/cli.mdx+++ b/docs/content/docs/api-reference/cli.mdx@@ -1,9 +1,9 @@---title: "@openuidev/cli"-description: API reference for the OpenUI CLI to scaffold apps and generate system prompts.+description: API reference for the OpenUI CLI to scaffold apps and generate system prompts or library specs.----A command-line tool for scaffolding OpenUI chat apps and generating system prompts or JSON schemas from library definitions.+A command-line tool for scaffolding OpenUI chat apps and generating system prompts, JSON schemas, or serialized library specs from library definitions.## Installation@@ -86,20 +86,68 @@ Pass `--skill` or `--no-skill` to skip the prompt. In `--no-interactive` mode th**Examples**-```bash+```bash tab="pnpm" tab-group="pkg"+# Interactive — prompts for project name, AI setup, env setup, and skill installation+pnpx @openuidev/cli@latest create++# Select an AI setup explicitly+pnpx @openuidev/cli@latest create --name my-app --template openui-cloud+pnpx @openuidev/cli@latest create --name my-app --template openui-self-hosted++# Non-interactive+pnpx @openuidev/cli@latest create --no-interactive --name my-app --template openui-cloud --auth skip++# Explicitly install or skip the agent skill+pnpx @openuidev/cli@latest create --name my-app --skill+pnpx @openuidev/cli@latest create --name my-app --no-skill+```++```bash tab="bun" tab-group="pkg"+# Interactive — prompts for project name, AI setup, env setup, and skill installation+bunx @openuidev/cli@latest create++# Select an AI setup explicitly+bunx @openuidev/cli@latest create --name my-app --template openui-cloud+bunx @openuidev/cli@latest create --name my-app --template openui-self-hosted++# Non-interactive+bunx @openuidev/cli@latest create --no-interactive --name my-app --template openui-cloud --auth skip++# Explicitly install or skip the agent skill+bunx @openuidev/cli@latest create --name my-app --skill+bunx @openuidev/cli@latest create --name my-app --no-skill+```++```bash tab="yarn" tab-group="pkg"+# Interactive — prompts for project name, AI setup, env setup, and skill installation+yarn dlx @openuidev/cli@latest create++# Select an AI setup explicitly+yarn dlx @openuidev/cli@latest create --name my-app --template openui-cloud+yarn dlx @openuidev/cli@latest create --name my-app --template openui-self-hosted++# Non-interactive+yarn dlx @openuidev/cli@latest create --no-interactive --name my-app --template openui-cloud --auth skip++# Explicitly install or skip the agent skill+yarn dlx @openuidev/cli@latest create --name my-app --skill+yarn dlx @openuidev/cli@latest create --name my-app --no-skill+```++```bash tab="npm" tab-group="pkg"# Interactive — prompts for project name, AI setup, env setup, and skill installation-openui create+npx @openuidev/cli@latest create# Select an AI setup explicitly-openui create --name my-app --template openui-cloud-openui create --name my-app --template openui-self-hosted+npx @openuidev/cli@latest create --name my-app --template openui-cloud+npx @openuidev/cli@latest create --name my-app --template openui-self-hosted# Non-interactive-openui create --no-interactive --name my-app --template openui-cloud --auth skip+npx @openuidev/cli@latest create --no-interactive --name my-app --template openui-cloud --auth skip# Explicitly install or skip the agent skill-openui create --name my-app --skill-openui create --name my-app --no-skill+npx @openuidev/cli@latest create --name my-app --skill+npx @openuidev/cli@latest create --name my-app --no-skill```## `openui generate`@@ -128,18 +176,60 @@ openui generate [entry] [options]**Examples**-```bash+```bash tab="pnpm" tab-group="pkg"+# Print system prompt to stdout+pnpx @openuidev/cli@latest generate ./src/library.ts++# Write system prompt to a file+pnpx @openuidev/cli@latest generate ./src/library.ts --out ./src/generated/system-prompt.txt++# Output JSON schema instead+pnpx @openuidev/cli@latest generate ./src/library.ts --json-schema++# Explicit export names+pnpx @openuidev/cli@latest generate ./src/library.ts --export myLibrary --prompt-options myOptions+```++```bash tab="bun" tab-group="pkg"+# Print system prompt to stdout+bunx @openuidev/cli@latest generate ./src/library.ts++# Write system prompt to a file+bunx @openuidev/cli@latest generate ./src/library.ts --out ./src/generated/system-prompt.txt++# Output JSON schema instead+bunx @openuidev/cli@latest generate ./src/library.ts --json-schema++# Explicit export names+bunx @openuidev/cli@latest generate ./src/library.ts --export myLibrary --prompt-options myOptions+```++```bash tab="yarn" tab-group="pkg"# Print system prompt to stdout-openui generate ./src/library.ts+yarn dlx @openuidev/cli@latest generate ./src/library.ts# Write system prompt to a file-openui generate ./src/library.ts --out ./src/generated/system-prompt.txt+yarn dlx @openuidev/cli@latest generate ./src/library.ts --out ./src/generated/system-prompt.txt# Output JSON schema instead-openui generate ./src/library.ts --json-schema+yarn dlx @openuidev/cli@latest generate ./src/library.ts --json-schema# Explicit export names-openui generate ./src/library.ts --export myLibrary --prompt-options myOptions+yarn dlx @openuidev/cli@latest generate ./src/library.ts --export myLibrary --prompt-options myOptions+```++```bash tab="npm" tab-group="pkg"+# Print system prompt to stdout+npx @openuidev/cli@latest generate ./src/library.ts++# Write system prompt to a file+npx @openuidev/cli@latest generate ./src/library.ts --out ./src/generated/system-prompt.txt++# Output JSON schema instead+npx @openuidev/cli@latest generate ./src/library.ts --json-schema++# Explicit export names+npx @openuidev/cli@latest generate ./src/library.ts --export myLibrary --prompt-options myOptions```### Export auto-detection@@ -194,14 +284,124 @@ export const promptOptions: PromptOptions = {};```-```bash-openui generate ./src/library.ts --out src/generated/system-prompt.txt+```bash tab="pnpm" tab-group="pkg"+pnpx @openuidev/cli@latest generate ./src/library.ts --out src/generated/system-prompt.txt+```++```bash tab="bun" tab-group="pkg"+bunx @openuidev/cli@latest generate ./src/library.ts --out src/generated/system-prompt.txt+```++```bash tab="yarn" tab-group="pkg"+yarn dlx @openuidev/cli@latest generate ./src/library.ts --out src/generated/system-prompt.txt+```++```bash tab="npm" tab-group="pkg"+npx @openuidev/cli@latest generate ./src/library.ts --out src/generated/system-prompt.txt+```++## `openui generate-spec`++Generates a serialized library spec as JSON — component signatures, component groups, and the library's JSON schema — from a file that exports a `createLibrary()` result.++```+openui generate-spec [entry] [options]+```++The spec is a handover artifact: the team that owns the component library generates it once and hands the JSON to whoever configures the model server — for example as the `chatLibrary` config value in OpenUI Cloud. The server rebuilds the system prompt, response validation, and sanitization from the spec, so the model can only be prompted with components the library actually registers.++**Arguments**++| Argument | Description |+| --------- | ----------------------------------------------------------------------- |+| `[entry]` | Path to a `.ts`, `.tsx`, `.js`, or `.jsx` file that exports a `Library` |++**Options**++| Flag | Description |+| ------------------ | ---------------------------------------------------- |+| `-o, --out <file>` | Write output to a file instead of stdout |+| `--export <name>` | Name of the export to use (auto-detected by default) |+| `--no-interactive` | Fail instead of prompting for missing `entry` |++Entry bundling and library detection work the same as [`openui generate`](#export-auto-detection). `PromptOptions` exports are not folded into the spec — the spec is pure library data; consumers apply prompt customisation separately when they build the system prompt.++**Output**++{/* prettier-ignore */}+```jsonc+{+ // Optional root component the response must start with+ "root": "Page",+ // Pre-rendered signatures, for review and inspection+ "components": {+ "Metric": {+ "signature": "Metric(label: string, value: string, trend?: \"up\" | \"down\")",+ "description": "A single KPI stat"+ }+ },+ // Optional grouping, mirrored into the generated prompt+ "componentGroups": [{ "name": "Data display", "components": ["Metric"] }],+ // JSON schema of every registered component ($defs keyed by component name)+ "schema": {+ "$defs": {+ "Metric": { "type": "object", "description": "A single KPI stat", "properties": { /* … */ } }+ }+ }+}+```++**Examples**++```bash tab="pnpm" tab-group="pkg"+# Print the spec to stdout+pnpx @openuidev/cli@latest generate-spec ./src/library.ts++# Write the handover file+pnpx @openuidev/cli@latest generate-spec ./src/library.ts --out ./library-spec.json++# Explicit export name+pnpx @openuidev/cli@latest generate-spec ./src/library.ts --export myLibrary+```++```bash tab="bun" tab-group="pkg"+# Print the spec to stdout+bunx @openuidev/cli@latest generate-spec ./src/library.ts++# Write the handover file+bunx @openuidev/cli@latest generate-spec ./src/library.ts --out ./library-spec.json++# Explicit export name+bunx @openuidev/cli@latest generate-spec ./src/library.ts --export myLibrary+```++```bash tab="yarn" tab-group="pkg"+# Print the spec to stdout+yarn dlx @openuidev/cli@latest generate-spec ./src/library.ts++# Write the handover file+yarn dlx @openuidev/cli@latest generate-spec ./src/library.ts --out ./library-spec.json++# Explicit export name+yarn dlx @openuidev/cli@latest generate-spec ./src/library.ts --export myLibrary+```++```bash tab="npm" tab-group="pkg"+# Print the spec to stdout+npx @openuidev/cli@latest generate-spec ./src/library.ts++# Write the handover file+npx @openuidev/cli@latest generate-spec ./src/library.ts --out ./library-spec.json++# Explicit export name+npx @openuidev/cli@latest generate-spec ./src/library.ts --export myLibrary```## See also<Cards><Card title="@openuidev/react-lang" href="/docs/api-reference/react-lang">- `createLibrary`, `PromptOptions`, and the `Library` interface that `openui generate` reads.+ `createLibrary`, `PromptOptions`, and the `Library` interface that `openui generate` and `openui+ generate-spec` read.</Card></Cards>diff --git a/packages/lang-core/package.json b/packages/lang-core/package.jsonindex e88caa981..c7063a6d0 100644--- a/packages/lang-core/package.json+++ b/packages/lang-core/package.json@@ -1,6 +1,6 @@{"name": "@openuidev/lang-core",- "version": "0.2.7",+ "version": "0.2.8","description": "Framework-agnostic core for OpenUI Lang: parser, prompt generation, validation, and type definitions","license": "MIT","type": "module",diff --git a/packages/lang-core/src/__tests__/library.test.ts b/packages/lang-core/src/__tests__/library.test.tsindex 16e0b7e58..7c877ccc1 100644--- a/packages/lang-core/src/__tests__/library.test.ts+++ b/packages/lang-core/src/__tests__/library.test.ts@@ -136,6 +136,49 @@ describe("per-library registry", () => {const refs = JSON.stringify(childrenItems);expect(refs).toContain("#/$defs/TextContent");});++ it("toSpec carries the library JSON schema alongside signatures", () => {+ const Text = defineComponent({+ name: "TextContent",+ props: z.object({ text: z.string() }),+ description: "text",+ component: Dummy,+ });++ const Card = defineComponent({+ name: "Card",+ props: z.object({ title: z.string() }),+ description: "card",+ component: Dummy,+ });++ const lib = createLibrary({+ components: [Text, Card],+ componentGroups: [{ name: "Content", components: ["TextContent"] }],+ root: "Card",+ });+ const spec = lib.toSpec();++ // Spec is self-contained: signatures + groups + the parser schema.+ expect(spec.root).toBe("Card");+ expect(spec.components["Card"]?.signature).toContain("title");+ expect(spec.componentGroups).toEqual([{ name: "Content", components: ["TextContent"] }]);+ expect(spec.schema).toEqual(lib.toJSONSchema());+ });++ it("toJSONSchema carries defineComponent descriptions on $defs entries", () => {+ const Text = defineComponent({+ name: "TextContent",+ props: z.object({ text: z.string() }),+ description: "Plain text content",+ component: Dummy,+ });++ const lib = createLibrary({ components: [Text], root: "TextContent" });+ const schema = lib.toJSONSchema();++ expect(schema.$defs?.["TextContent"]?.description).toBe("Plain text content");+ });});// ─── getSchemaId WeakMap fallback ────────────────────────────────────────────diff --git a/packages/lang-core/src/index.ts b/packages/lang-core/src/index.tsindex bb40ad57e..dccec529e 100644--- a/packages/lang-core/src/index.ts+++ b/packages/lang-core/src/index.ts@@ -1,5 +1,5 @@// ── Library (framework-generic) ──-export { createLibrary, defineComponent, tagSchemaId } from "./library";+export { buildSignature, createLibrary, defineComponent, tagSchemaId } from "./library";export type {ComponentGroup,ComponentRenderProps,@@ -30,7 +30,7 @@ export type { BuiltinDef } from "./parser/builtins";export { enrichErrors } from "./parser/enrich-errors";export { mergeStatements } from "./parser/merge";export { generatePrompt } from "./parser/prompt";-export type { ComponentPromptSpec, PromptSpec, ToolSpec } from "./parser/prompt";+export type { ComponentPromptSpec, LibrarySpec, PromptSpec, ToolSpec } from "./parser/prompt";export { jsonToOpenUI } from "./parser/serialize";export type { SerializeOptions } from "./parser/serialize";export { BuiltinActionType } from "./parser/types";diff --git a/packages/lang-core/src/library.ts b/packages/lang-core/src/library.tsindex f998bc5bf..4008ab5bf 100644--- a/packages/lang-core/src/library.ts+++ b/packages/lang-core/src/library.ts@@ -1,6 +1,6 @@import { object as zObject } from "zod/v4";import * as z from "zod/v4/core";-import type { ComponentPromptSpec, PromptSpec, ToolSpec } from "./parser/prompt";+import type { ComponentPromptSpec, LibrarySpec, PromptSpec, ToolSpec } from "./parser/prompt";import { generatePrompt } from "./parser/prompt";import type { LibraryJSONSchema } from "./parser/types";import { isReactiveSchema } from "./reactive";@@ -302,7 +302,7 @@ function analyzeFields(shape: Record<string, z.$ZodType>, reg: SchemaRegistry):}));}-function buildSignature(componentName: string, fields: FieldInfo[]): string {+export function buildSignature(componentName: string, fields: FieldInfo[]): string {const params = fields.map((f) => {if (f.typeAnnotation) {return f.isOptional ? `${f.name}?: ${f.typeAnnotation}` : `${f.name}: ${f.typeAnnotation}`;@@ -382,21 +382,34 @@ export function createLibrary<C = unknown>(input: LibraryDefinition<C>): Libraryreturn generatePrompt(spec);},- toSpec(): PromptSpec {+ toSpec(): LibrarySpec {return {root: input.root,components: buildComponentSpecs(componentsRecord, reg),componentGroups: input.componentGroups,+ schema: buildJSONSchema(),};},toJSONSchema(): LibraryJSONSchema {- const combinedSchema = zObject(- Object.fromEntries(Object.entries(componentsRecord).map(([k, v]) => [k, v.props])) as any,- );- return z.toJSONSchema(combinedSchema, { metadata: reg }) as LibraryJSONSchema;+ return buildJSONSchema();},};+ function buildJSONSchema(): LibraryJSONSchema {+ const combinedSchema = zObject(+ Object.fromEntries(Object.entries(componentsRecord).map(([k, v]) => [k, v.props])) as any,+ );+ const schema = z.toJSONSchema(combinedSchema, { metadata: reg }) as LibraryJSONSchema;+ // zod only serializes what lives on the zod schemas / the metadata+ // registry, so component descriptions (a defineComponent field) must be+ // merged in explicitly — without this the serialized library loses them.+ for (const [name, comp] of Object.entries(componentsRecord)) {+ const def = schema.$defs?.[name];+ if (def && comp.description) def.description = comp.description;+ }+ return schema;+ }+return library;}diff --git a/packages/lang-core/src/parser/prompt.ts b/packages/lang-core/src/parser/prompt.tsindex f28ef5b25..d5dce4907 100644--- a/packages/lang-core/src/parser/prompt.ts+++ b/packages/lang-core/src/parser/prompt.ts@@ -1,4 +1,5 @@import { BUILTINS, LAZY_BUILTIN_DEFS } from "./builtins";+import type { LibraryJSONSchema } from "./types";// ─── PromptSpec types (JSON-serializable, no Zod deps) ──────────────────────@@ -25,10 +26,13 @@ export interface ComponentGroup {notes?: string[];}-export interface PromptSpec {+export interface BaseSpec {root?: string;components: Record<string, ComponentPromptSpec>;componentGroups?: ComponentGroup[];+}++export interface PromptSpec extends BaseSpec {tools?: (string | ToolSpec)[];editMode?: boolean;inlineMode?: boolean;@@ -44,6 +48,10 @@ export interface PromptSpec {additionalRules?: string[];}+export interface LibrarySpec extends BaseSpec {+ schema?: LibraryJSONSchema;+}+// ─── JSON Schema → type string helper ───────────────────────────────────────function jsonSchemaTypeStr(schema: Record<string, unknown>): string {diff --git a/packages/lang-core/src/parser/types.ts b/packages/lang-core/src/parser/types.tsindex dbe32229c..ec1d82677 100644--- a/packages/lang-core/src/parser/types.ts+++ b/packages/lang-core/src/parser/types.ts@@ -10,6 +10,7 @@ export interface LibraryJSONSchema {{properties?: Record<string, unknown>;required?: string[];+ description?: string;}>;}diff --git a/packages/openui-cli/package.json b/packages/openui-cli/package.jsonindex 7eb58a2cc..5beddc695 100644--- a/packages/openui-cli/package.json+++ b/packages/openui-cli/package.json@@ -1,6 +1,6 @@{"name": "@openuidev/cli",- "version": "0.1.6",+ "version": "0.1.7","description": "CLI for OpenUI — scaffold generative UI chat apps and generate LLM system prompts from component libraries","bin": {"openui": "dist/index.js"diff --git a/packages/openui-cli/src/commands/generate-worker.ts b/packages/openui-cli/src/commands/generate-worker.tsindex 6ae1a9cc5..cbbcf8f85 100644--- a/packages/openui-cli/src/commands/generate-worker.ts+++ b/packages/openui-cli/src/commands/generate-worker.ts@@ -1,10 +1,11 @@/*** Worker script that bundles a user's library file and outputs the system- * prompt or JSON schema. Asset imports are stubbed during bundling so React- * component modules can be evaluated without CSS/image/font loaders.+ * prompt, JSON schema, or serialized library spec. Asset imports are stubbed+ * during bundling so React component modules can be evaluated without+ * CSS/image/font loaders.*- * argv: [entryPath, exportName?, "--json-schema"?, "--prompt-options", name?]- * stdout: the prompt string or JSON schema+ * argv: [entryPath, exportName?, "--json-schema"?, "--spec"?, "--prompt-options", name?]+ * stdout: the prompt string, JSON schema, or spec JSON*/import * as fs from "fs";@@ -130,9 +131,10 @@ async function main(): Promise<void> {}const jsonSchema = args.includes("--json-schema");+ const spec = args.includes("--spec");const promptOptionsIdx = args.indexOf("--prompt-options");const promptOptionsName = promptOptionsIdx !== -1 ? args[promptOptionsIdx + 1] : undefined;- const reserved = new Set(["--json-schema", "--prompt-options"]);+ const reserved = new Set(["--json-schema", "--spec", "--prompt-options"]);if (promptOptionsName) reserved.add(promptOptionsName);const exportName = args.find((a, i) => a !== entryPath && !reserved.has(a) && !(i > 0 && args[i - 1] === "--prompt-options"),@@ -183,7 +185,9 @@ async function main(): Promise<void> {}let output: string;- if (jsonSchema) {+ if (spec) {+ output = JSON.stringify({ ...library.toSpec(), schema: library.toJSONSchema() }, null, 2);+ } else if (jsonSchema) {// Output a PromptSpec-compatible JSON with component signatures, groups, and JSON schema.output = JSON.stringify(library.toSpec(), null, 2);} else {diff --git a/packages/openui-cli/src/commands/generate.ts b/packages/openui-cli/src/commands/generate.tsindex 2f6c86a29..98381d857 100644--- a/packages/openui-cli/src/commands/generate.ts+++ b/packages/openui-cli/src/commands/generate.ts@@ -7,6 +7,8 @@ import { CreateError, telemetry } from "../lib/telemetry";export interface GenerateOptions {out?: string;jsonSchema?: boolean;+ /** Emit the serialized library spec JSON (toSpec + schema) — `generate-spec`. */+ spec?: boolean;export?: string;promptOptions?: string;}@@ -15,6 +17,7 @@ export async function runGenerate(entry: string, options: GenerateOptions): Promconst t0 = Date.now();telemetry.capture("cli_generate_started", {json_schema: !!options.jsonSchema,+ spec: !!options.spec,out_to_file: !!options.out,});const entryPath = path.resolve(process.cwd(), entry);@@ -28,6 +31,7 @@ export async function runGenerate(entry: string, options: GenerateOptions): Promconst workerArgs = [workerPath, entryPath];if (options.export) workerArgs.push(options.export);if (options.jsonSchema) workerArgs.push("--json-schema");+ if (options.spec) workerArgs.push("--spec");if (options.promptOptions) workerArgs.push("--prompt-options", options.promptOptions);let output: string;@@ -52,6 +56,7 @@ export async function runGenerate(entry: string, options: GenerateOptions): Promtelemetry.capture("cli_generate_succeeded", {json_schema: !!options.jsonSchema,+ spec: !!options.spec,out_to_file: !!options.out,duration_ms: Date.now() - t0,});diff --git a/packages/openui-cli/src/index.ts b/packages/openui-cli/src/index.tsindex 560e4e5c6..1dcead05a 100644--- a/packages/openui-cli/src/index.ts+++ b/packages/openui-cli/src/index.ts@@ -115,4 +115,42 @@ program},);+program+ .command("generate-spec")+ .description("Generate a serialized library spec JSON (signatures, groups, JSON schema)")+ .argument("[entry]", "Path to a file that exports a createLibrary() result")+ .option("-o, --out <file>", "Write output to a file instead of stdout")+ .option("--export <name>", "Name of the export to use (auto-detected by default)")+ .option("--no-interactive", "Fail with error if required args are missing")+ .action(+ async (+ entry: string | undefined,+ options: {+ out?: string;+ export?: string;+ interactive: boolean;+ },+ ) => {+ try {+ const args = await resolveArgs(+ {+ entry: entry+ ? { value: entry }+ : {+ prompt: { type: "input", message: "Entry file path?" },+ required: true,+ },+ },+ options.interactive,+ );++ await runGenerate((args as { entry: string }).entry, { ...options, spec: true });+ } catch (e) {+ handleCliError(e, "cli_generate_spec_failed");+ } finally {+ await telemetry.shutdown();+ }+ },+ );+program.parse();