import { F as FlatElement, S as Spec, a as StateModel, V as VisibilityCondition, b as StateCondition, A as AndCondition, O as OrCondition, c as ActionBinding, D as DynamicValue, U as UIElement, J as JsonPatch } from './store-utils-sn0EXSPG.js'; export { $ as Action, a7 as ActionBindingSchema, a0 as ActionConfirm, a9 as ActionConfirmSchema, a4 as ActionDefinition, a6 as ActionExecutionContext, a3 as ActionHandler, a2 as ActionOnError, ab as ActionOnErrorSchema, a1 as ActionOnSuccess, aa as ActionOnSuccessSchema, a8 as ActionSchema, C as ComponentSchema, f as DynamicBoolean, s as DynamicBooleanSchema, e as DynamicNumber, r as DynamicNumberSchema, d as DynamicString, q as DynamicStringSchema, p as DynamicValueSchema, g as IndexCondition, I as ItemCondition, M as MixedStreamCallbacks, m as MixedStreamParser, P as PatchOp, R as RepeatStatePath, a5 as ResolvedAction, X as SPEC_DATA_PART, Y as SPEC_DATA_PART_TYPE, h as SingleCondition, o as SpecDataPart, l as SpecStreamCompiler, k as SpecStreamLine, i as StateStore, Z as StoreAdapterConfig, n as StreamChunk, j as ValidationMode, ai as action, ah as actionBinding, y as addByPath, H as applySpecPatch, G as applySpecStreamPatch, L as compileSpecStream, T as createJsonRenderTransform, Q as createMixedStreamParser, N as createSpecStreamCompiler, _ as createStateStore, ad as executeAction, B as findFormValue, u as getByPath, af as interpolateString, ae as isBuiltInAction, ag as mergeActionHandlers, K as nestedToFlat, E as parseSpecStreamLine, W as pipeJsonRender, z as removeByPath, ac as resolveAction, t as resolveDynamicValue, w as resolveRepeatItemStatePath, v as resolveRepeatStatePath, x as setByPath } from './store-utils-sn0EXSPG.js'; import { z } from 'zod'; /** * Pure helpers for specs that arrive in parts: a flat element list, and the * parts of an AI SDK message. They read no framework, so every renderer can * use them. * * @packageDocumentation */ /** * Convert a flat element list to a Spec. * Input elements use key/parentKey to establish identity and relationships. * Output spec uses the map-based format where key is the map entry key * and parent-child relationships are expressed through children arrays. */ declare function flatToTree(elements: FlatElement[]): Spec; /** * A single part from the AI SDK's `message.parts` array. This is a minimal * structural type so that library helpers do not depend on the AI SDK. * Fields are optional because different part types carry different data: * - Text parts have `text` * - Data parts have `data` */ interface DataPart { type: string; text?: string; data?: unknown; } /** * Build a `Spec` by replaying all spec data parts from a message's * parts array. Returns `null` if no spec data parts are present. * * This function is designed to work with the AI SDK's `UIMessage.parts` array. * It picks out parts whose `type` is {@link SPEC_DATA_PART_TYPE} and processes them based * on the payload's `type` discriminator: * * - `"patch"`: Applies the JSON Patch operation incrementally via `applySpecPatch`. * - `"flat"`: Replaces the spec with the complete flat spec. * - `"nested"`: Assigns the nested spec directly (future: nested-to-flat conversion). * * The function has no AI SDK dependency — it operates on a generic array of * `{ type: string; data: unknown }` objects. * * @example * ```ts * const spec = buildSpecFromParts(message.parts); * if (spec) renderer.setSpec(spec); * ``` */ declare function buildSpecFromParts(parts: DataPart[]): Spec | null; /** * Extract and join all text content from a message's parts array. * * Filters for parts with `type === "text"`, trims each one, and joins them * with double newlines so that text from separate agent steps renders as * distinct paragraphs in markdown. * * Has no AI SDK dependency — operates on a generic `DataPart[]`. * * @example * ```ts * const text = getTextFromParts(message.parts); * if (text) output.textContent = text; * ``` */ declare function getTextFromParts(parts: DataPart[]): string; /** * Visibility condition schema. * * Lazy because `OrCondition` can recursively contain `VisibilityCondition`. */ declare const VisibilityConditionSchema: z.ZodType; /** * Strict variant for spec validation: rejects unknown keys, so malformed * conditions (e.g. mixing $state and $item in one object) are caught at * validation time instead of silently evaluating to hidden at runtime. */ /** * True when a condition references the repeat-item scope ($item or $index) * anywhere in its tree. Renderers use this to apply a repeat container's own * visible condition as a per-item filter instead of evaluating it (and * failing) outside the repeat scope. */ declare function conditionUsesItemScope(condition: VisibilityCondition | undefined): boolean; /** * Splits a repeat container's visible condition into a container-level gate * and a per-item filter. Top-level AND structures (arrays, $and) partition * cleanly: conjuncts that reference $item/$index filter items, the rest gate * the container. An $or that mixes scopes cannot be partitioned soundly and * is applied entirely per item (state parts still evaluate correctly there; * the container shell just cannot be hidden by it). */ declare function splitRepeatVisibility(condition: VisibilityCondition | undefined): { container: VisibilityCondition | undefined; itemFilter: VisibilityCondition | undefined; }; declare const VisibilityConditionStrictSchema: z.ZodType; /** * Context for evaluating visibility conditions. * * `repeatItem` and `repeatIndex` are only present inside a `repeat` scope * and enable `$item` / `$index` conditions. */ interface VisibilityContext { stateModel: StateModel; /** The current repeat item (set inside a repeat scope). */ repeatItem?: unknown; /** The current repeat array index (set inside a repeat scope). */ repeatIndex?: number; } /** * Evaluate a visibility condition. * * - `undefined` → visible * - `boolean` → that value * - `SingleCondition` → evaluate single condition * - `SingleCondition[]` → implicit AND (all must be true) * - `AndCondition` → `{ $and: [...] }`, explicit AND * - `OrCondition` → `{ $or: [...] }`, at least one must be true */ declare function evaluateVisibility(condition: VisibilityCondition | undefined, ctx: VisibilityContext): boolean; /** * Helper to create visibility conditions. */ declare const visibility: { /** Always visible */ always: true; /** Never visible */ never: false; /** Visible when state path is truthy */ when: (path: string) => StateCondition; /** Visible when state path is falsy */ unless: (path: string) => StateCondition; /** Equality check */ eq: (path: string, value: unknown) => StateCondition; /** Not equal check */ neq: (path: string, value: unknown) => StateCondition; /** Greater than */ gt: (path: string, value: number | { $state: string; }) => StateCondition; /** Greater than or equal */ gte: (path: string, value: number | { $state: string; }) => StateCondition; /** Less than */ lt: (path: string, value: number | { $state: string; }) => StateCondition; /** Less than or equal */ lte: (path: string, value: number | { $state: string; }) => StateCondition; /** AND multiple conditions */ and: (...conditions: VisibilityCondition[]) => AndCondition; /** OR multiple conditions */ or: (...conditions: VisibilityCondition[]) => OrCondition; }; /** * Definition for a custom directive — a user-defined `$`-prefixed dynamic * value that extends the spec language. * * @example * ```ts * const formatDirective = defineDirective({ * name: '$format', * description: 'Locale-aware value formatting (date, currency, number, percent).', * schema: z.object({ * $format: z.enum(['date', 'currency', 'number']), * value: z.unknown(), * }), * resolve(value, ctx) { * const resolved = resolvePropValue(value.value, ctx); * return new Intl.NumberFormat().format(resolved); * }, * }); * ``` */ interface DirectiveDefinition { /** The `$`-prefixed key that triggers this directive (e.g. `"$format"`). */ name: string; /** * Short description of the directive for the AI system prompt. * The schema fields are auto-generated; this adds behavioral context. */ description?: string; /** Zod schema for validating the directive object. */ schema: TSchema; /** * Resolver function. Receives the raw directive value and the current * {@link PropResolutionContext}. May call `resolvePropValue` on sub-values * to support composition with other dynamic expressions. */ resolve: (value: z.infer, ctx: PropResolutionContext) => unknown; } /** * A Map from directive name (e.g. `"$format"`) to its definition. * Passed through {@link PropResolutionContext} for runtime resolution. */ type DirectiveRegistry = Map; /** * Define a custom directive. * * This is an identity function that provides type checking and serves as * a documentation convention. Throws if the name collides with a built-in * prop expression key. */ declare function defineDirective(definition: DirectiveDefinition): DirectiveDefinition; /** * Convert an array of directive definitions into a {@link DirectiveRegistry}. */ declare function createDirectiveRegistry(directives: DirectiveDefinition[]): DirectiveRegistry; /** * Look up a custom directive for a plain-object value. * * Iterates the registry and checks whether the object contains a matching key. * Returns `undefined` when no match is found or when no registry is provided. * * This is only called **after** all built-in expressions (`$state`, `$cond`, * etc.) have been checked in `resolvePropValue`, so built-ins always take * precedence. {@link defineDirective} enforces this at registration time by * rejecting names that collide with built-in keys. */ declare function findDirective(value: Record, directives?: DirectiveRegistry): DirectiveDefinition | undefined; /** * A prop expression that resolves to a value based on state. * * - `{ $state: string }` reads a value from the global state model * - `{ $item: string }` reads a field from the current repeat item * (relative path into the item object; use `""` for the whole item) * - `{ $index: true }` returns the current repeat array index. Uses `true` * as a sentinel flag because the index is a scalar with no sub-path to * navigate — unlike `$item` which needs a path into the item object. * - `{ $bindState: string }` two-way binding to a global state path — * resolves to the value at the path (like `$state`) AND exposes the * resolved path so the component can write back. * - `{ $bindItem: string }` two-way binding to a field on the current * repeat item — resolves via `repeatBasePath + path` and exposes the * absolute state path for write-back. * - `{ $cond, $then, $else }` conditionally picks a value * - `{ $computed: string, args?: Record }` calls a * registered function with resolved args and returns the result * - `{ $template: string }` interpolates `${/path}` and `${field}` * references. Absolute paths (`${/path}`) resolve against the state * model. Bare names (`${field}`) resolve against the current repeat * item first, then fall back to the state model at `/`. * - Any other value is a literal (passthrough) */ type PropExpression = T | { $state: string; } | { $item: string; } | { $index: true; } | { $bindState: string; } | { $bindItem: string; } | { $cond: VisibilityCondition; $then: PropExpression; $else: PropExpression; } | { $computed: string; args?: Record; } | { $template: string; }; /** * Function signature for `$computed` expressions. * Receives a record of resolved argument values and returns a computed result. */ type ComputedFunction = (args: Record) => unknown; /** * Callback invoked when an individual catalog component throws during render. * Implemented by each framework renderer's error boundary / error capture mechanism. */ type RenderErrorHandler = (error: unknown, elementType: string) => void; /** * Context for resolving prop expressions. * Extends {@link VisibilityContext} with an optional `repeatBasePath` used * to resolve `$bindItem` paths to absolute state paths. */ interface PropResolutionContext extends VisibilityContext { /** Absolute state path to the current repeat item (e.g. "/todos/0"). Set inside repeat scopes. */ repeatBasePath?: string; /** Named functions available for `$computed` expressions. */ functions?: Record; /** Custom directive registry for user-defined `$`-prefixed dynamic values. */ directives?: DirectiveRegistry; } /** * Resolve a single prop value that may contain expressions. * Handles $state, $item, $index, $bindState, $bindItem, and $cond/$then/$else in a single pass. */ declare function resolvePropValue(value: unknown, ctx: PropResolutionContext): unknown; /** * Resolve all prop values in an element's props object. * Returns a new props object with all expressions resolved. */ declare function resolveElementProps(props: Record, ctx: PropResolutionContext): Record; /** * Scan an element's raw props for `$bindState` / `$bindItem` expressions * and return a map of prop name → resolved absolute state path. * * This is called **before** `resolveElementProps` so the component can * receive both the resolved value (in `props`) and the write-back path * (in `bindings`). * * @example * ```ts * const rawProps = { value: { $bindState: "/form/email" }, label: "Email" }; * const bindings = resolveBindings(rawProps, ctx); * // bindings = { value: "/form/email" } * ``` */ declare function resolveBindings(props: Record, ctx: PropResolutionContext): Record | undefined; /** * Resolve a single action parameter value. * * Like {@link resolvePropValue} but with special handling for path-valued * params: `{ $item: "field" }` resolves to an **absolute state path** * (e.g. `/todos/0/field`) instead of the field's value, so the path can * be passed to `setState` / `pushState` / `removeState`. * * - `{ $item: "field" }` → absolute state path via `repeatBasePath` * - `{ $index: true }` → current repeat index (number) * - Everything else delegates to `resolvePropValue` ($state, $cond, literals). */ declare function resolveActionParam(value: unknown, ctx: PropResolutionContext): unknown; /** * Resolve the params of an action binding with {@link resolveActionParam}. * * A renderer calls it just before each binding of a chain runs, with the * state of that moment in `ctx.stateModel`, so a later binding sees what an * earlier one wrote. A binding without params comes back as it is. */ declare function resolveBindingParams(binding: ActionBinding, ctx: PropResolutionContext): ActionBinding; /** * Emitted when an action begins executing. The same `id` appears on the * matching {@link ActionSettleInfo}. The provider emits that event when the * action resolves, when the action throws, and when the user cancels a * confirm gate. */ interface ActionDispatchInfo { /** Stable dispatch id; paired with the matching `onSettle`. */ id: string; /** Resolved action name. */ name: string; /** Resolved params, if any. */ params?: Record; /** Wall clock time (ms) at dispatch. */ at: number; } /** * Emitted after an action resolved, threw, or was cancelled at a confirm gate. */ interface ActionSettleInfo { /** Matches the `id` of the corresponding `onDispatch`. */ id: string; /** Resolved action name. */ name: string; /** * `true` if the handler resolved. `false` if the handler threw, and `false` * if the user cancelled a confirm gate. Read `cancelled` to tell the two * apart. */ ok: boolean; /** Wall clock time (ms) at settle. */ at: number; /** Elapsed time from dispatch to settle, in milliseconds. */ durationMs: number; /** * `true` if the user cancelled a confirm gate. The handler did not run, and * the provider changed no state. */ cancelled?: boolean; /** * Time (ms) that a confirm dialog stayed open. `durationMs` includes this * time. Subtract it to get the time that the handler used. */ confirmMs?: number; /** Return value from the handler, if any. */ result?: unknown; /** Error if the handler threw. */ error?: unknown; } /** * Observer for action lifecycle events. Either callback is optional. */ interface ActionObserver { onDispatch?: (evt: ActionDispatchInfo) => void; onSettle?: (evt: ActionSettleInfo) => void; } /** * Register an observer for action lifecycle events. Returns an unsubscribe * function. Intended for devtools integrations; safe to call from any * framework adapter. * * @example * ```ts * import { registerActionObserver } from "@xmachines/json-render-core"; * const unsub = registerActionObserver({ * onDispatch: (evt) => console.log("fired", evt.name), * onSettle: (evt) => console.log("settled", evt.name, evt.durationMs), * }); * ``` */ declare function registerActionObserver(observer: ActionObserver): () => void; /** * Emit a dispatch event to all registered observers. Called by framework * ActionProviders at the start of every action execution. * * Wrapped in try/catch per-observer so a buggy observer cannot interrupt * action execution. */ declare function notifyActionDispatch(evt: ActionDispatchInfo): void; /** * Emit a settle event to all registered observers. Called by framework * ActionProviders after every action resolves, throws, or is cancelled at a * confirm gate. */ declare function notifyActionSettle(evt: ActionSettleInfo): void; declare function nextActionDispatchId(): string; /** * Mark devtools as active. Returns a release function. Safe to call * multiple times (nested counter). * * @example * ```ts * // In a devtools adapter: * useEffect(() => markDevtoolsActive(), []); * ``` */ declare function markDevtoolsActive(): () => void; /** * True when at least one devtools adapter is mounted in the page. * Cheap to call; a plain integer comparison. */ declare function isDevtoolsActive(): boolean; /** * Subscribe to changes in the devtools-active flag. Framework renderers * that need to re-render on state change (e.g. React's `useSyncExternalStore`) * subscribe here; most can just read `isDevtoolsActive()` on render. */ declare function subscribeDevtoolsActive(listener: () => void): () => void; /** * Validation check definition */ interface ValidationCheck { /** Validation type (built-in or from catalog) */ type: string; /** Additional arguments for the validation */ args?: Record; /** Error message to display if check fails */ message: string; } /** * Validation configuration for a field */ interface ValidationConfig { /** Array of checks to run */ checks?: ValidationCheck[]; /** When to run validation */ validateOn?: "change" | "blur" | "submit"; /** Condition for when validation is enabled */ enabled?: VisibilityCondition; } /** * Schema for validation check */ declare const ValidationCheckSchema: z.ZodObject<{ type: z.ZodString; args: z.ZodOptional]>>>; message: z.ZodString; }, z.core.$strip>; /** * Schema for validation config */ declare const ValidationConfigSchema: z.ZodObject<{ checks: z.ZodOptional]>>>; message: z.ZodString; }, z.core.$strip>>>; validateOn: z.ZodOptional>; enabled: z.ZodOptional>>; }, z.core.$strip>; /** * Validation function signature */ type ValidationFunction = (value: unknown, args?: Record) => boolean; /** * Validation function definition in catalog */ interface ValidationFunctionDefinition { /** The validation function */ validate: ValidationFunction; /** Description for AI */ description?: string; } /** * Built-in validation functions */ declare const builtInValidationFunctions: Record; /** * Validation result for a single check */ interface ValidationCheckResult { type: string; valid: boolean; message: string; } /** * Full validation result for a field */ interface ValidationResult { valid: boolean; errors: string[]; checks: ValidationCheckResult[]; } /** * Context for running validation */ interface ValidationContext { /** Current value to validate */ value: unknown; /** Full data model for resolving paths */ stateModel: StateModel; /** Custom validation functions from catalog */ customFunctions?: Record; } /** * Run a single validation check */ declare function runValidationCheck(check: ValidationCheck, ctx: ValidationContext): ValidationCheckResult; /** * Run all validation checks for a field */ declare function runValidation(config: ValidationConfig, ctx: ValidationContext): ValidationResult; /** * Helper to create validation checks */ declare const check: { required: (message?: string) => ValidationCheck; email: (message?: string) => ValidationCheck; minLength: (min: number, message?: string) => ValidationCheck; maxLength: (max: number, message?: string) => ValidationCheck; pattern: (pattern: string, message?: string) => ValidationCheck; min: (min: number, message?: string) => ValidationCheck; max: (max: number, message?: string) => ValidationCheck; url: (message?: string) => ValidationCheck; numeric: (message?: string) => ValidationCheck; matches: (otherPath: string, message?: string) => ValidationCheck; equalTo: (otherPath: string, message?: string) => ValidationCheck; lessThan: (otherPath: string, message?: string) => ValidationCheck; greaterThan: (otherPath: string, message?: string) => ValidationCheck; requiredIf: (fieldPath: string, message?: string) => ValidationCheck; }; /** * Severity level for validation issues. */ type SpecIssueSeverity = "error" | "warning"; /** * A single validation issue found in a spec. */ interface SpecIssue { /** Severity: errors should be fixed, warnings are informational */ severity: SpecIssueSeverity; /** Human-readable description of the issue */ message: string; /** The element key where the issue was found (if applicable) */ elementKey?: string; /** Machine-readable issue code for programmatic handling */ code: "missing_root" | "root_not_found" | "missing_child" | "invalid_visible" | "repeat_without_children" | "repeat_item_outside_scope" | "repeat_state_mismatch" | "visible_in_props" | "orphaned_element" | "empty_spec" | "on_in_props" | "repeat_in_props" | "watch_in_props"; } /** * Result of spec structural validation. */ interface SpecValidationIssues { /** Whether the spec passed validation (no errors; warnings are OK) */ valid: boolean; /** List of issues found */ issues: SpecIssue[]; } /** * Options for validateSpec. */ interface ValidateSpecOptions { /** * Whether to check for orphaned elements (elements not reachable from root). * Defaults to false since orphans are harmless (just unused). */ checkOrphans?: boolean; } /** * Validate a spec for structural integrity. * * Checks for common AI-generation errors: * - Missing or empty root * - Root element not found in elements map * - Children referencing non-existent elements * - `visible` placed inside `props` instead of on the element * - Orphaned elements (optional) * * @example * ```ts * const result = validateSpec(spec); * if (!result.valid) { * console.log("Spec errors:", result.issues); * } * ``` */ declare function validateSpec(spec: Spec, options?: ValidateSpecOptions): SpecValidationIssues; /** * Auto-fix common spec issues in-place and return a corrected copy. * * Currently fixes: * - `visible` inside `props` → moved to element level * - `on` inside `props` → moved to element level * - `repeat` inside `props` → moved to element level * * Returns the fixed spec and a list of fixes applied. */ interface SpecFix { message: string; /** * Lossy fixes change what renders (e.g. pruning a dangling child * reference); lossless fixes only relocate misplaced fields. Callers with a * repair loop should prefer re-prompting over accepting lossy fixes, and * use the lossy-fixed spec as a last resort. */ lossy: boolean; } interface AutoFixOptions { /** * Apply lossy fixes (content pruning). Default true. Callers with a repair * loop should pass false while retries remain so the model regenerates the * missing content, then true as a last resort. */ lossy?: boolean; } declare function autoFixSpec(spec: Spec, options?: AutoFixOptions): { spec: Spec; fixes: string[]; /** Structured fix records; fixes is the plain-message projection. */ fixDetails: SpecFix[]; }; /** * Format validation issues into a human-readable string suitable for * inclusion in a repair prompt sent back to the AI. */ declare function formatSpecIssues(issues: SpecIssue[]): string; /** * Edit mode for modifying an existing spec. * * - `"patch"` — RFC 6902 JSON Patch. One operation per line. * - `"merge"` — RFC 7396 JSON Merge Patch. Partial object deep-merged; `null` deletes. * - `"diff"` — Unified diff (POSIX). Line-level text edits against the serialized spec. */ type EditMode = "patch" | "merge" | "diff"; interface EditConfig { /** Which edit modes are enabled. When >1, the AI chooses per edit. */ modes: EditMode[]; } /** * Generate the prompt section describing available edit modes. * Only documents the modes that are enabled. */ declare function buildEditInstructions(config: EditConfig | undefined, format: "json" | "yaml"): string; declare function isNonEmptySpec(spec: unknown): spec is Spec; interface BuildEditUserPromptOptions { prompt: string; currentSpec?: Spec | null; config?: EditConfig; format: "json" | "yaml"; maxPromptLength?: number; /** Serialise the spec. Defaults to JSON.stringify for json, must be provided for yaml. */ serializer?: (spec: Spec) => string; } /** * Generate the user prompt for edits, including the current spec * (with line numbers when diff mode is enabled) and mode instructions. */ declare function buildEditUserPrompt(options: BuildEditUserPromptOptions): string; /** * Schema builder primitives */ interface SchemaBuilder { /** String type */ string(): SchemaType<"string">; /** Number type */ number(): SchemaType<"number">; /** Boolean type */ boolean(): SchemaType<"boolean">; /** Array of type */ array(item: T): SchemaType<"array", T>; /** Object with shape */ object>(shape: T): SchemaType<"object", T>; /** Record/map with value type */ record(value: T): SchemaType<"record", T>; /** Any type */ any(): SchemaType<"any">; /** Placeholder for user-provided Zod schema */ zod(): SchemaType<"zod">; /** Reference to catalog key (e.g., 'catalog.components') */ ref(path: string): SchemaType<"ref", string>; /** Props from referenced catalog entry */ propsOf(path: string): SchemaType<"propsOf", string>; /** Map of named entries with shared shape */ map>(entryShape: T): SchemaType<"map", T>; /** Optional modifier */ optional(): { optional: true; }; } /** * Schema type representation */ interface SchemaType { kind: TKind; inner?: TInner; optional?: boolean; } /** * Schema definition shape */ interface SchemaDefinition { /** What the AI-generated spec looks like */ spec: TSpec; /** What the catalog must provide */ catalog: TCatalog; } /** * Schema instance with methods */ interface Schema { /** The schema definition */ readonly definition: TDef; /** Custom prompt template for this schema */ readonly promptTemplate?: PromptTemplate; /** Default rules baked into the schema (injected before customRules) */ readonly defaultRules?: string[]; /** Built-in actions always available at runtime (injected into prompts automatically) */ readonly builtInActions?: BuiltInAction[]; /** Create a catalog from this schema */ createCatalog>(catalog: TCatalog): Catalog; } /** * Catalog instance with methods */ interface Catalog { /** The schema this catalog is based on */ readonly schema: Schema; /** The catalog data */ readonly data: TCatalog; /** Component names */ readonly componentNames: string[]; /** Action names */ readonly actionNames: string[]; /** Generate system prompt for AI */ prompt(options?: PromptOptions): string; /** Export as JSON Schema for structured outputs */ jsonSchema(options?: JsonSchemaOptions): object; /** Validate a spec against this catalog */ validate(spec: unknown): SpecValidationResult>; /** Get the Zod schema for the spec */ zodSchema(): z.ZodType>; /** Type helper for the spec type */ readonly _specType: InferSpec; } /** * Options for JSON Schema export */ interface JsonSchemaOptions { /** * When true, produces a strict JSON Schema subset compatible with * LLM structured output APIs (OpenAI, Google Gemini, Anthropic, etc.). * This ensures: * - `additionalProperties: false` on every object * - All object properties listed in `required` (optionals use nullable types) * - Record/map types converted to fixed-key objects * * **Limitation:** Record types (dynamic-key maps) cannot be represented in * strict JSON Schema because `additionalProperties` must be `false`. They * are emitted as `{ type: "object", properties: {}, additionalProperties: false }`. * The LLM prompt (via `catalog.prompt()`) still describes the full structure, * so the model can produce valid output even though the JSON Schema for * record entries is opaque. */ strict?: boolean; } /** * Prompt generation options */ interface PromptOptions { /** Custom system message intro */ system?: string; /** Additional rules to append */ customRules?: string[]; /** * Output mode for the generated prompt. * * - `"standalone"` (default): The LLM should output only JSONL patches (no prose). * - `"inline"`: The LLM should respond conversationally first, then output JSONL patches. * Includes rules about interleaving text with JSONL and not wrapping in code fences. * * @deprecated `"generate"` — use `"standalone"` instead. * @deprecated `"chat"` — use `"inline"` instead. */ mode?: "standalone" | "inline" | "generate" | "chat"; /** Edit modes to document in the system prompt. Default: `["patch"]`. */ editModes?: EditMode[]; /** * Custom directives to include in the system prompt. * Each directive's schema is auto-described; the optional `description` * field adds behavioral context. Pass the same array used at runtime. */ directives?: DirectiveDefinition[]; } /** * Context provided to prompt templates */ interface PromptContext { /** The catalog data */ catalog: TCatalog; /** Component names from the catalog */ componentNames: string[]; /** Action names from the catalog (if any) */ actionNames: string[]; /** Prompt options provided by the user */ options: PromptOptions; /** Helper to format a Zod type as a human-readable string */ formatZodType: (schema: z.ZodType) => string; } /** * Prompt template function type */ type PromptTemplate = (context: PromptContext) => string; /** * A built-in action that is always available regardless of catalog configuration. * These are handled by the runtime (e.g. ActionProvider) and injected into prompts * automatically so the LLM knows about them. */ interface BuiltInAction { /** Action name (e.g. "setState") */ name: string; /** Human-readable description for the LLM */ description: string; } /** * Schema options */ interface SchemaOptions { /** Custom prompt template for this schema */ promptTemplate?: PromptTemplate; /** Default rules baked into the schema (injected before customRules in prompts) */ defaultRules?: string[]; /** * Built-in actions that are always available regardless of catalog configuration. * These are injected into prompts automatically so the LLM knows about them, * but they don't require handlers in defineRegistry because the runtime * (e.g. ActionProvider) handles them directly. */ builtInActions?: BuiltInAction[]; } /** * Spec validation result */ interface SpecValidationResult { success: boolean; data?: T; error?: z.ZodError; } /** * Extract the components map type from a catalog * @example type Components = InferCatalogComponents; */ type InferCatalogComponents = C extends Catalog ? TCatalog extends { components: infer Comps; } ? Comps : never : never; /** * Extract the actions map type from a catalog * @example type Actions = InferCatalogActions; */ type InferCatalogActions = C extends Catalog ? TCatalog extends { actions: infer Acts; } ? Acts : never : never; /** * Infer component props from a catalog by component name * @example type ButtonProps = InferComponentProps; */ type InferComponentProps> = InferCatalogComponents[K] extends { props: z.ZodType; } ? P : never; /** * Infer action params from a catalog by action name * @example type ViewCustomersParams = InferActionParams; */ type InferActionParams> = InferCatalogActions[K] extends { params: z.ZodType; } ? P : never; type InferCatalogInput = T extends SchemaType<"object", infer Shape> ? { [K in keyof Shape]: InferCatalogField; } : never; type InferCatalogField = T extends SchemaType<"map", infer EntryShape> ? Record & Partial>> : T extends SchemaType<"zod"> ? z.ZodType : T extends SchemaType<"string"> ? string : T extends SchemaType<"number"> ? number : T extends SchemaType<"boolean"> ? boolean : T extends SchemaType<"array", infer Item> ? InferCatalogField[] : T extends SchemaType<"object", infer Shape> ? { [K in keyof Shape]: InferCatalogField; } : unknown; type InferMapEntryRequired = { [K in keyof T as K extends "props" ? K : never]: InferMapEntryField; }; type InferMapEntryOptional = { [K in keyof T as K extends "props" ? never : K]: InferMapEntryField; }; type InferMapEntryField = T extends SchemaType<"zod"> ? z.ZodType : T extends SchemaType<"string"> ? string : T extends SchemaType<"number"> ? number : T extends SchemaType<"boolean"> ? boolean : T extends SchemaType<"array", infer Item> ? InferMapEntryField[] : T extends SchemaType<"object", infer Shape> ? { [K in keyof Shape]: InferMapEntryField; } : unknown; type InferSpec = TDef extends { spec: SchemaType<"object", infer Shape>; } ? InferSpecObject : unknown; type InferSpecObject = { [K in keyof Shape as Shape[K] extends { optional: true; } ? never : K]: InferSpecField; } & { [K in keyof Shape as Shape[K] extends { optional: true; } ? K : never]?: InferSpecField; }; type InferSpecField = T extends SchemaType<"string"> ? string : T extends SchemaType<"number"> ? number : T extends SchemaType<"boolean"> ? boolean : T extends SchemaType<"array", infer Item> ? InferSpecField[] : T extends SchemaType<"object", infer Shape> ? InferSpecObject : T extends SchemaType<"record", infer Value> ? Record> : T extends SchemaType<"ref", infer Path> ? InferRefType : T extends SchemaType<"propsOf", infer Path> ? InferPropsOfType : T extends SchemaType<"any"> ? any : unknown; type InferRefType = Path extends "catalog.components" ? TCatalog extends { components: infer C; } ? keyof C : string : Path extends "catalog.actions" ? TCatalog extends { actions: infer A; } ? keyof A : string : string; type InferPropsOfType = Path extends "catalog.components" ? TCatalog extends { components: infer C; } ? C extends Record; }> ? P : Record : Record : Record; /** * Define a schema using the builder pattern */ declare function defineSchema(builder: (s: SchemaBuilder) => TDef, options?: SchemaOptions): Schema; /** * Shorthand: Define a catalog directly from a schema */ declare function defineCatalog>(schema: Schema, catalog: TCatalog): Catalog; /** * Options for building a user prompt. */ interface UserPromptOptions { /** The user's text prompt */ prompt: string; /** Existing spec to refine (triggers patch-only mode) */ currentSpec?: Spec | null; /** Runtime state context to include */ state?: Record | null; /** Maximum length for the user's text prompt (applied before wrapping) */ maxPromptLength?: number; /** Edit modes to offer when refining an existing spec. Default: `["patch"]`. */ editModes?: EditMode[]; /** Wire format. Default: `"json"`. */ format?: "json" | "yaml"; /** Serialise the spec for edits. Defaults to JSON.stringify for json, must be provided for yaml. */ serializer?: (spec: Spec) => string; } /** * Build a user prompt for AI generation. * * Handles common patterns that every consuming app needs: * - Truncating the user's prompt to a max length * - Including the current spec for refinement (edit mode) * - Including runtime state context * * @example * ```ts * // Fresh generation * buildUserPrompt({ prompt: "create a todo app" }) * * // Refinement with existing spec * buildUserPrompt({ prompt: "add a dark mode toggle", currentSpec: spec }) * * // With multiple edit modes * buildUserPrompt({ prompt: "change title", currentSpec: spec, editModes: ["patch", "merge"] }) * ``` */ declare function buildUserPrompt(options: UserPromptOptions): string; /** * The error-reporting path that every renderer shares (fork module). * * Each failure in code that a renderer runs reaches the `onRenderError` * handler exactly one time, with a {@link RenderErrorInfo}. Without a * handler, the renderer writes one `[json-render]` console line in one * format. A handler that throws gives its error to `reportError`, and the * renderer fails no other element. * * The renderers call {@link reportRenderError}, {@link warnUnknownType} and * {@link warnMissingRoot}, so the console lines are the same in each one. * * @packageDocumentation */ /** * The place where a failure occurred. * * - `element`: the component threw while it rendered, in an effect or a * lifecycle hook, or in a callback that it calls in those phases. * - `props`: a prop expression of an element threw (`$computed`, a directive). * - `visible`: the `visible` condition of an element threw. * - `action`: an `on` chain failed: a handler that throws or rejects, a * built-in action, a store that refuses a write, or `validateForm`. * - `watch`: a `watch` chain failed. * - `root`: the root (its component, props or `visible`) failed, so the * renderer shows nothing. */ type RenderErrorKind = "element" | "props" | "visible" | "action" | "watch" | "root"; /** What a renderer tells the handler about a failure. */ interface RenderErrorInfo { /** The place where the failure occurred. */ kind: RenderErrorKind; /** The key of the element whose code failed. For `props` and `visible`, the child, not the boundary. */ key?: string; /** The component type of that element. */ type?: string; /** The action name, for `action` and `watch`. */ action?: string; } /** * The `onRenderError` handler of a renderer. * * The second argument stays as it was: the element type for a failure of an * element, or the action name for a failed chain. `info` tells them apart. A * handler with two parameters is still a valid handler. */ type OnRenderError = (error: unknown, name: string, info: RenderErrorInfo) => void; /** * Report an error that no caller can take, as the browser reports one: to * `reportError`, which dispatches the window `error` event. Where the * platform has no `reportError`, the error goes to `console.error`. */ declare function reportUncaughtError(error: unknown): void; /** * The single console line of a failure without a handler, before the error: * `[json-render] error in "" of "":`. */ declare function formatRenderError(name: string, info: RenderErrorInfo): string; /** * Report a failure in code that the renderer runs. * * With a handler, the function calls it one time with `(error, name, info)`. * When the handler throws, its error goes to {@link reportUncaughtError} one * time, and the function does not throw. Without a handler, the function * writes one `console.error` line ({@link formatRenderError}), then the error. */ declare function reportRenderError(handler: OnRenderError | undefined, error: unknown, name: string, info: RenderErrorInfo): void; /** Warn one time about an element whose type has no component and no `fallback`. */ declare function warnUnknownType(type: string, key?: string): void; /** Warn one time about a `root` that names no element of the spec. */ declare function warnMissingRoot(rootKey: string): void; /** * Slot metadata for named-slot validation. * * A renderer package records the slot names that each catalog component * declares when it builds a registry from a catalog. When it renders an * element with `slots`, it calls {@link warnElementSlots}, which warns about * `slots.default` (spelled `children`) and about a slot name that the * component does not declare. * * The metadata is keyed on the registry OBJECT, so a registry that a renderer * clones must carry it over with {@link copySlotMetadata}. A hand-built * registry carries no metadata, and its slot names are not validated. * * @packageDocumentation */ /** Slot names declared by one catalog component. */ interface ComponentSlotMetadata { slots?: string[]; } /** * Attach the slot declarations of a catalog to the registry that renders it. * A catalog without component data attaches nothing. */ declare function setCatalogSlotMetadata(registry: object, catalog: unknown): void; /** * Carry the slot metadata of one registry over to a clone of it. A bare * spread loses the metadata and silences named-slot validation. */ declare function copySlotMetadata(from: object, to: object): void; /** * Slot declarations for one component type, or `undefined` when the registry * carries no catalog metadata or the type is not in the catalog. */ declare function getComponentSlotMetadata(registry: object, type: string): ComponentSlotMetadata | undefined; /** * Warn about the named slots of an element of component `type`: about * `slots.default`, which is spelled `children`, and about each slot name that * the catalog does not declare for the component. The renderer still renders * an undeclared slot. Nothing is validated for a registry without catalog * metadata, or for a component that declares no slots. */ declare function warnElementSlots(registry: object, type: string, slots: Record | undefined): void; /** * Copy a registry with an `onRenderError` handler on the copy. * * The copy holds the own components of the registry, so an enumeration of * the copy lists them. It has the registry as its prototype, so it also * finds a component that the registry has from its own prototype or from a * Proxy. The handler is an own property of the copy * that is not enumerable, and it replaces a handler that the registry * holds. The copy carries the slot metadata of the registry over: the * metadata is keyed on the registry object. The registry of the caller does * not change. */ declare function withRenderErrorHandler(registry: TRegistry, onRenderError: OnRenderError): TRegistry; /** * Put an `onRenderError` handler on a registry, in place. `defineRegistry` * of each renderer calls it. The property is not enumerable, so an * enumeration of the components does not list it. The handler takes the * place of a component of the same name, which a catalog can declare, and * the function warns: an element of that type then renders the fallback. */ declare function setRenderErrorHandler(registry: object, onRenderError: OnRenderError): void; /** * Warn one time for each registry that holds an enumerable `onRenderError` * function, when a render error finds no handler: the function counts as a * component of that name, and not as the handler. A renderer calls it * before it writes a render error to `console.error`. */ declare function warnUnusedRenderErrorHandler(registry: object | undefined): void; /** * The `onRenderError` handler that a registry holds, or `undefined`. Only a * property that is not enumerable counts, as `setRenderErrorHandler` makes * it: a component named `onRenderError` is no handler. */ declare function getRenderErrorHandler(registry: object | undefined): RenderErrorHandler | undefined; /** * The entry of `key` in a map of names, such as a registry or a map of action * handlers. A name of Object.prototype, such as `toString`, `constructor` or * `__proto__`, is an entry only as an own property of the map. */ declare function getOwnEntry(map: Record, key: string): TEntry | undefined; /** * The own enumerable members of `source`, as descriptors for a copy that * takes no write through a setter of the source. A value is read through * the source, so a reactive source tracks it, and a getter reads the * source when it runs, with the source as `this`. */ declare function ownMemberDescriptors(source: object): PropertyDescriptorMap; /** * An empty registry for `components`. A component named `__proto__` gets * an own property first, so that an assignment of it sets that property and * not the prototype of the registry. `defineRegistry` of each renderer * starts from it, and the dom renderer also starts its map of action * handlers from it. */ declare function createComponentRegistry(components: object | undefined): Record; /** * The component of `type` in a registry, or `undefined`. The registry can be * a plain object, an object with a prototype, or a Proxy. The `onRenderError` * handler and the members of Object.prototype are no components. */ declare function getRegistryComponent(registry: Record, type: string): TComponent | undefined; /** * Report an action chain that failed: an `on` event or a `watch` whose * binding threw. `onRenderError` gets the error with the action name as its * second argument. Without a handler, the error goes to `console.error`, and * not to an unhandled rejection, because a component discards the promise of * `emit`. `reportRenderError` with the kind `action` or `watch` replaces it. */ declare function reportActionError(onRenderError: RenderErrorHandler | undefined, error: unknown, action: string, source: "event" | "watch"): void; /** * The prompt entries of the six actions that every renderer runs itself * (fork module). A renderer schema gives them to `defineSchema` as * `builtInActions: [...builtInActionDefinitions]`, so the generated prompt * names each built-in action that the renderer runs, `push` and `pop` too. */ declare const builtInActionDefinitions: readonly BuiltInAction[]; /** * The JSON of an element and of every element below it: its children and the * elements of its named slots. * * A renderer records it when the boundary of an element catches a failure, * and it renders the element again when the JSON changes. A child resolves * its props outside its own boundary, so the boundary of its parent catches * that failure, and a new version of the child must reset it, as the * signatures of react do. */ declare function elementSubtreeJson(spec: Spec | null | undefined, key: string | undefined, element: UIElement | null | undefined): string; /** * The values that the `watch` map of an element reads from `state`, one for * each watched path. * * The function returns `previous` when `previous` holds the same paths in the * same order with the same values, by `Object.is`, so a watched `NaN` stays * the same too. A * renderer uses the reference as its change signal: a write * to any other path gives the same object back, so it neither runs the watch * nor cancels the bindings that still run. */ declare function readWatchedValues(watch: Record | undefined, state: StateModel, previous: Record | undefined): Record | undefined; /** * The watched paths whose value changes from `previous` to `current`, in the * order of `current`. * * A path that `previous` does not hold is new: the element starts to watch it, * and its first value fires nothing, as the first render fires nothing. */ declare function changedWatchPaths(current: Record | undefined, previous: Record | undefined): string[]; /** * Run the bindings of the changed `paths` of `watch` one after another. * * Each binding waits for the previous one, so a later binding sees what an * earlier one wrote. `isCancelled` is read before each binding: a new change * of a watched value, or the unmount of the element, stops the rest of the * chain. A binding that throws stops the chain too, and the promise rejects * with its error, as the chain of an `on` event does. */ declare function runWatchBindings(watch: Record, paths: string[], run: (binding: ActionBinding) => Promise, isCancelled: () => boolean): Promise; /** * Deep-merge `patch` into `base`, returning a new object. * * Semantics (RFC 7396 JSON Merge Patch): * - `null` values in `patch` delete the corresponding key from `base` * - Arrays in `patch` replace (not concat) the corresponding array in `base` * - Plain objects recurse * - All other values replace * * Neither `base` nor `patch` is mutated. */ declare function deepMergeSpec(base: Record, patch: Record): Record; /** * Produce RFC 6902 JSON Patch operations that transform `oldObj` into `newObj`. * * - New keys → `add` * - Changed scalar/array values → `replace` * - Removed keys → `remove` * - Arrays are compared shallowly and replaced atomically (not element-diffed) * - Plain objects recurse */ declare function diffToPatches(oldObj: Record, newObj: Record, basePath?: string): JsonPatch[]; /** Experimental: may change in any release. A catalog using the flat Spec format. */ interface Experimental_CompositionCatalog { data: { components: Record; actions?: Record; }; schema?: { builtInActions?: readonly { name: string; }[]; }; validate(spec: unknown): { success: boolean; }; } /** One app-owned element recipe. The evaluator cannot modify its props or bindings. */ interface Experimental_CompositionCandidate { id: string; description: string; element: Pick; /** Whether this candidate can be the root. Defaults to true. */ root?: boolean; /** Defaults to one. Reusable layout elements can opt into a larger count. */ maxUses?: number; /** Candidates sharing a resource are mutually exclusive. */ resource?: string; } interface Experimental_ChoiceQuestion { type: "choice"; instructions: string; criteria: Record; } interface Experimental_CompositionEvaluation { answers: Record; usage?: { inputTokens?: number; }; } /** Custom adapters must return one of each question's offered criteria keys. */ type Experimental_CompositionEvaluator = (request: { state: Record; questions: Record; signal: AbortSignal; }) => Promise; interface Experimental_CompositionStep { index: number; choice: string; description: string; parent: string | null; slot: string | null; confidence: number | null; parentConfidence: number | null; elapsedMs: number; inputTokens: number | null; /** Independent answers from a batched selection or layout evaluation. */ answers?: Experimental_CompositionEvaluation["answers"]; } type Experimental_CompositionEvent = { type: "step"; spec: Spec; step: Experimental_CompositionStep; } | { type: "complete"; spec: Spec | null; steps: Experimental_CompositionStep[]; elapsedMs: number; inputTokens: number | null; stopReason: "finish" | "limit" | "unavailable"; }; interface Experimental_ComposeSpecOptions { catalog: Experimental_CompositionCatalog; candidates: readonly Experimental_CompositionCandidate[]; prompt: string; evaluate: Experimental_CompositionEvaluator; /** New trees use batched selection/layout by default. Edits remain sequential. */ strategy?: "batch" | "sequential"; /** Element budget for batched creation, including the root. Default: 32. */ maxElements?: number; /** Edit an existing tree. Cloned and validated before evaluation. */ initialSpec?: Spec; /** Descriptions explicitly shared for existing elements, keyed by element ID. */ elementDescriptions?: Record; /** Included in the spec, never sent to the evaluator. Overrides initialSpec.state. */ initialState?: Record; /** Additional app context explicitly shared with the evaluator. */ context?: Record; signal?: AbortSignal; /** Evaluation budget, including sequential terminal decisions. Default: 32. */ maxSteps?: number; /** Root has depth one. Default: 8. */ maxDepth?: number; /** App-specific guidance appended to the construction instructions. */ instructions?: { root?: string; next?: string; parent?: string; }; } /** * Experimental catalog-constrained composition. Streams detached Spec snapshots. * Throws on invalid configuration, evaluator output, provider errors, or abort. * Actions are copied into the spec; they are never executed by the composer. */ declare function experimental_composeSpec(options: Experimental_ComposeSpecOptions): AsyncGenerator; interface Experimental_EvaluatorOptions { /** Server-side Vercel AI Gateway key. Never expose this in browser code. */ apiKey: string; /** Gateway evaluation model identifier, for example typesafe-ai/jev. */ model: string; /** Per-evaluation timeout in milliseconds. Default: 10000. */ timeoutMs?: number; fetch?: typeof globalThis.fetch; } /** * Experimental server-side choice evaluator using Vercel AI Gateway's v4 evaluation * transport. No AI SDK provider constructor or additional dependency is needed. */ declare function experimental_createEvaluator(options: Experimental_EvaluatorOptions): Experimental_CompositionEvaluator; export { ActionBinding, type ActionDispatchInfo, type ActionObserver, type ActionSettleInfo, AndCondition, type BuildEditUserPromptOptions, type BuiltInAction, type Catalog, type ComponentSlotMetadata, type ComputedFunction, type DataPart, type DirectiveDefinition, type DirectiveRegistry, DynamicValue, type EditConfig, type EditMode, type Experimental_ChoiceQuestion, type Experimental_ComposeSpecOptions, type Experimental_CompositionCandidate, type Experimental_CompositionCatalog, type Experimental_CompositionEvaluation, type Experimental_CompositionEvaluator, type Experimental_CompositionEvent, type Experimental_CompositionStep, type Experimental_EvaluatorOptions, FlatElement, type InferActionParams, type InferCatalogActions, type InferCatalogComponents, type InferCatalogInput, type InferComponentProps, type InferSpec, JsonPatch, type JsonSchemaOptions, type OnRenderError, OrCondition, type PromptContext, type PromptOptions, type PromptTemplate, type PropExpression, type PropResolutionContext, type RenderErrorHandler, type RenderErrorInfo, type RenderErrorKind, type Schema, type SchemaBuilder, type SchemaDefinition, type SchemaOptions, type SchemaType, Spec, type SpecIssue, type SpecIssueSeverity, type SpecValidationIssues, type SpecValidationResult, StateCondition, StateModel, UIElement, type UserPromptOptions, type ValidateSpecOptions, type ValidationCheck, type ValidationCheckResult, ValidationCheckSchema, type ValidationConfig, ValidationConfigSchema, type ValidationContext, type ValidationFunction, type ValidationFunctionDefinition, type ValidationResult, VisibilityCondition, VisibilityConditionSchema, VisibilityConditionStrictSchema, type VisibilityContext, autoFixSpec, buildEditInstructions, buildEditUserPrompt, buildSpecFromParts, buildUserPrompt, builtInActionDefinitions, builtInValidationFunctions, changedWatchPaths, check, conditionUsesItemScope, copySlotMetadata, createComponentRegistry, createDirectiveRegistry, deepMergeSpec, defineCatalog, defineDirective, defineSchema, diffToPatches, elementSubtreeJson, evaluateVisibility, experimental_composeSpec, experimental_createEvaluator, findDirective, flatToTree, formatRenderError, formatSpecIssues, getComponentSlotMetadata, getOwnEntry, getRegistryComponent, getRenderErrorHandler, getTextFromParts, isDevtoolsActive, isNonEmptySpec, markDevtoolsActive, nextActionDispatchId, notifyActionDispatch, notifyActionSettle, ownMemberDescriptors, readWatchedValues, registerActionObserver, reportActionError, reportRenderError, reportUncaughtError, resolveActionParam, resolveBindingParams, resolveBindings, resolveElementProps, resolvePropValue, runValidation, runValidationCheck, runWatchBindings, setCatalogSlotMetadata, setRenderErrorHandler, splitRepeatVisibility, subscribeDevtoolsActive, validateSpec, visibility, warnElementSlots, warnMissingRoot, warnUnknownType, warnUnusedRenderErrorHandler, withRenderErrorHandler };