@xmachines/json-render-react 0.19.0-xm.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,762 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { ReactNode, ComponentType } from 'react';
3
+ import { StateStore, StateModel, VisibilityCondition, VisibilityContext, ActionHandler, ResolvedAction, ActionBinding, ActionConfirm, ValidationFunction, ValidationResult, ValidationConfig, Catalog, InferCatalogComponents, InferComponentProps, InferCatalogActions, InferActionParams, RenderErrorHandler, UIElement, SchemaDefinition, Spec, ComputedFunction, DirectiveDefinition, FlatElement } from '@xmachines/json-render-core';
4
+ export { RenderErrorHandler, Spec, StateModel, StateStore, createStateStore } from '@xmachines/json-render-core';
5
+ export { ElementTreeSchema, ElementTreeSpec, ReactSchema, ReactSpec, elementTreeSchema, schema } from './schema.js';
6
+
7
+ /**
8
+ * State context value
9
+ */
10
+ interface StateContextValue {
11
+ /** The current state model */
12
+ state: StateModel;
13
+ /** Get a value by path */
14
+ get: (path: string) => unknown;
15
+ /** Set a value by path */
16
+ set: (path: string, value: unknown) => void;
17
+ /** Update multiple values at once */
18
+ update: (updates: Record<string, unknown>) => void;
19
+ /** Return the live state snapshot from the underlying store (not the React render snapshot). */
20
+ getSnapshot: () => StateModel;
21
+ }
22
+ /**
23
+ * Props for StateProvider
24
+ */
25
+ interface StateProviderProps {
26
+ /**
27
+ * External store that owns the state. When provided, the provider operates
28
+ * in **controlled mode** — `initialState` and `onStateChange` are ignored
29
+ * and the store is the single source of truth.
30
+ */
31
+ store?: StateStore;
32
+ /** Initial state model (used only in uncontrolled mode) */
33
+ initialState?: StateModel;
34
+ /**
35
+ * Callback when state changes (used only in uncontrolled mode).
36
+ * Called once per `set` or `update` with all changed entries.
37
+ */
38
+ onStateChange?: (changes: Array<{
39
+ path: string;
40
+ value: unknown;
41
+ }>) => void;
42
+ children: ReactNode;
43
+ }
44
+ /**
45
+ * Provider for state model context.
46
+ *
47
+ * Supports two modes:
48
+ * - **Controlled**: pass a `store` prop (e.g. backed by Redux / Zustand).
49
+ * - **Uncontrolled** (default): omit `store` and optionally pass
50
+ * `initialState` / `onStateChange`.
51
+ */
52
+ declare function StateProvider({ store: externalStore, initialState, onStateChange, children, }: StateProviderProps): react_jsx_runtime.JSX.Element;
53
+ /**
54
+ * Hook to access the state context
55
+ */
56
+ declare function useStateStore(): StateContextValue;
57
+ /**
58
+ * Hook to get a value from the state model
59
+ */
60
+ declare function useStateValue<T>(path: string): T | undefined;
61
+ /**
62
+ * Hook to get and set a value from the state model (like useState).
63
+ *
64
+ * @deprecated Use {@link useBoundProp} with `$bindState` expressions instead.
65
+ * `useStateBinding` takes a raw state path string, while `useBoundProp` works
66
+ * with the renderer's `bindings` map and supports both `$bindState` and
67
+ * `$bindItem` expressions.
68
+ */
69
+ declare function useStateBinding<T>(path: string): [T | undefined, (value: T) => void];
70
+
71
+ /**
72
+ * Visibility context value
73
+ */
74
+ interface VisibilityContextValue {
75
+ /** Evaluate a visibility condition */
76
+ isVisible: (condition: VisibilityCondition | undefined) => boolean;
77
+ /** The underlying visibility context */
78
+ ctx: VisibilityContext;
79
+ }
80
+ /**
81
+ * Props for VisibilityProvider
82
+ */
83
+ interface VisibilityProviderProps {
84
+ children: ReactNode;
85
+ }
86
+ /**
87
+ * Provider for visibility evaluation
88
+ */
89
+ declare function VisibilityProvider({ children }: VisibilityProviderProps): react_jsx_runtime.JSX.Element;
90
+ /**
91
+ * Hook to access visibility evaluation
92
+ */
93
+ declare function useVisibility(): VisibilityContextValue;
94
+ /**
95
+ * Hook to check if a condition is visible
96
+ */
97
+ declare function useIsVisible(condition: VisibilityCondition | undefined): boolean;
98
+
99
+ /**
100
+ * Pending confirmation state
101
+ */
102
+ interface PendingConfirmation {
103
+ /** The resolved action */
104
+ action: ResolvedAction;
105
+ /** The action handler */
106
+ handler: ActionHandler;
107
+ /** Resolve callback */
108
+ resolve: () => void;
109
+ /** Reject callback */
110
+ reject: () => void;
111
+ }
112
+ /**
113
+ * Action context value
114
+ */
115
+ interface ActionContextValue {
116
+ /** Registered action handlers */
117
+ handlers: Record<string, ActionHandler>;
118
+ /** Currently loading action names */
119
+ loadingActions: Set<string>;
120
+ /** Pending confirmation dialog */
121
+ pendingConfirmation: PendingConfirmation | null;
122
+ /** Execute an action binding */
123
+ execute: (binding: ActionBinding) => Promise<void>;
124
+ /** Confirm the pending action */
125
+ confirm: () => void;
126
+ /** Cancel the pending action */
127
+ cancel: () => void;
128
+ /** Register an action handler */
129
+ registerHandler: (name: string, handler: ActionHandler) => void;
130
+ }
131
+ /**
132
+ * Props for ActionProvider
133
+ */
134
+ interface ActionProviderProps {
135
+ /** Initial action handlers */
136
+ handlers?: Record<string, ActionHandler>;
137
+ /** Navigation function */
138
+ navigate?: (path: string) => void;
139
+ children: ReactNode;
140
+ }
141
+ /**
142
+ * Provider for action execution
143
+ */
144
+ declare function ActionProvider({ handlers: initialHandlers, navigate, children, }: ActionProviderProps): react_jsx_runtime.JSX.Element;
145
+ /**
146
+ * Hook to access action context
147
+ */
148
+ declare function useActions(): ActionContextValue;
149
+ /**
150
+ * Hook to execute an action binding
151
+ */
152
+ declare function useAction(binding: ActionBinding): {
153
+ execute: () => Promise<void>;
154
+ isLoading: boolean;
155
+ };
156
+ /**
157
+ * Props for ConfirmDialog component
158
+ */
159
+ interface ConfirmDialogProps {
160
+ /** The confirmation config */
161
+ confirm: ActionConfirm;
162
+ /** Called when confirmed */
163
+ onConfirm: () => void;
164
+ /** Called when cancelled */
165
+ onCancel: () => void;
166
+ }
167
+ /**
168
+ * Default confirmation dialog component
169
+ */
170
+ declare function ConfirmDialog({ confirm, onConfirm, onCancel, }: ConfirmDialogProps): react_jsx_runtime.JSX.Element;
171
+
172
+ /**
173
+ * Field validation state
174
+ */
175
+ interface FieldValidationState {
176
+ /** Whether the field has been touched */
177
+ touched: boolean;
178
+ /** Whether the field has been validated */
179
+ validated: boolean;
180
+ /** Validation result */
181
+ result: ValidationResult | null;
182
+ }
183
+ /**
184
+ * Validation context value
185
+ */
186
+ interface ValidationContextValue {
187
+ /** Custom validation functions from catalog */
188
+ customFunctions: Record<string, ValidationFunction>;
189
+ /** Validation state by field path */
190
+ fieldStates: Record<string, FieldValidationState>;
191
+ /** Validate a field */
192
+ validate: (path: string, config: ValidationConfig) => ValidationResult;
193
+ /** Mark field as touched */
194
+ touch: (path: string) => void;
195
+ /** Clear validation for a field */
196
+ clear: (path: string) => void;
197
+ /** Validate all fields */
198
+ validateAll: () => boolean;
199
+ /** Register field config */
200
+ registerField: (path: string, config: ValidationConfig) => void;
201
+ }
202
+ /**
203
+ * Props for ValidationProvider
204
+ */
205
+ interface ValidationProviderProps {
206
+ /** Custom validation functions from catalog */
207
+ customFunctions?: Record<string, ValidationFunction>;
208
+ children: ReactNode;
209
+ }
210
+ /**
211
+ * Provider for validation
212
+ */
213
+ declare function ValidationProvider({ customFunctions, children, }: ValidationProviderProps): react_jsx_runtime.JSX.Element;
214
+ /**
215
+ * Hook to access validation context
216
+ */
217
+ declare function useValidation(): ValidationContextValue;
218
+ /**
219
+ * Non-throwing variant of useValidation.
220
+ * Returns null when no ValidationProvider is present.
221
+ */
222
+ declare function useOptionalValidation(): ValidationContextValue | null;
223
+ /**
224
+ * Hook to get validation state for a field
225
+ */
226
+ declare function useFieldValidation(path: string, config?: ValidationConfig): {
227
+ state: FieldValidationState;
228
+ validate: () => ValidationResult;
229
+ touch: () => void;
230
+ clear: () => void;
231
+ errors: string[];
232
+ isValid: boolean;
233
+ };
234
+
235
+ /**
236
+ * Repeat scope value provided to child elements inside a repeated element.
237
+ */
238
+ interface RepeatScopeValue {
239
+ /** The current array item object */
240
+ item: unknown;
241
+ /** Index of the current item in the array */
242
+ index: number;
243
+ /** Absolute state path to the current array item (e.g. "/todos/0") — used for statePath two-way binding */
244
+ basePath: string;
245
+ }
246
+ /**
247
+ * Provides repeat scope to child elements so $item and $index expressions resolve correctly.
248
+ */
249
+ declare function RepeatScopeProvider({ item, index, basePath, children, }: RepeatScopeValue & {
250
+ children: ReactNode;
251
+ }): react_jsx_runtime.JSX.Element;
252
+ /**
253
+ * Read the current repeat scope (or null if not inside a repeated element).
254
+ */
255
+ declare function useRepeatScope(): RepeatScopeValue | null;
256
+
257
+ /**
258
+ * State setter function for updating application state
259
+ */
260
+ type SetState = (updater: (prev: Record<string, unknown>) => Record<string, unknown>) => void;
261
+ /**
262
+ * Handle returned by the `on()` function for a specific event.
263
+ * Provides metadata about the event binding and a method to fire it.
264
+ *
265
+ * @example
266
+ * ```ts
267
+ * const press = on("press");
268
+ * if (press.shouldPreventDefault) e.preventDefault();
269
+ * press.emit();
270
+ * ```
271
+ */
272
+ interface EventHandle {
273
+ /** Fire the event (resolve action bindings) */
274
+ emit: () => void;
275
+ /** Whether any binding requested preventDefault */
276
+ shouldPreventDefault: boolean;
277
+ /** Whether any handler is bound to this event */
278
+ bound: boolean;
279
+ }
280
+ /**
281
+ * Catalog-agnostic base type for component render function arguments.
282
+ * Use this when building reusable component libraries (e.g. `@xmachines/json-render-shadcn`)
283
+ * that are not tied to a specific catalog.
284
+ *
285
+ * @example
286
+ * ```ts
287
+ * const Card = ({ props, children }: BaseComponentProps<{ title?: string }>) => (
288
+ * <div>{props.title}{children}</div>
289
+ * );
290
+ * ```
291
+ */
292
+ interface BaseComponentProps<P = Record<string, unknown>> {
293
+ props: P;
294
+ children?: ReactNode;
295
+ /** Simple event emitter (shorthand). Fires the event and returns void. */
296
+ emit: (event: string) => void;
297
+ /** Get an event handle with metadata. Use when you need shouldPreventDefault or bound checks. */
298
+ on: (event: string) => EventHandle;
299
+ /**
300
+ * Two-way binding paths resolved from `$bindState` / `$bindItem` expressions.
301
+ * Maps prop name → absolute state path for write-back.
302
+ */
303
+ bindings?: Record<string, string>;
304
+ loading?: boolean;
305
+ }
306
+ /**
307
+ * Context passed to component render functions
308
+ * @example
309
+ * const Button: ComponentFn<typeof catalog, 'Button'> = (ctx) => {
310
+ * return <button onClick={() => ctx.emit("press")}>{ctx.props.label}</button>
311
+ * }
312
+ */
313
+ interface ComponentContext<C extends Catalog, K extends keyof InferCatalogComponents<C>> extends BaseComponentProps<InferComponentProps<C, K>> {
314
+ }
315
+ /**
316
+ * Component render function type for React
317
+ * @example
318
+ * const Button: ComponentFn<typeof catalog, 'Button'> = ({ props, emit }) => (
319
+ * <button onClick={() => emit("press")}>{props.label}</button>
320
+ * );
321
+ */
322
+ type ComponentFn<C extends Catalog, K extends keyof InferCatalogComponents<C>> = (ctx: ComponentContext<C, K>) => ReactNode;
323
+ /**
324
+ * Registry of all component render functions for a catalog
325
+ * @example
326
+ * const components: Components<typeof myCatalog> = {
327
+ * Button: ({ props }) => <button>{props.label}</button>,
328
+ * Input: ({ props }) => <input placeholder={props.placeholder} />,
329
+ * };
330
+ */
331
+ type Components<C extends Catalog> = {
332
+ [K in keyof InferCatalogComponents<C>]: ComponentFn<C, K>;
333
+ };
334
+ /**
335
+ * Action handler function type
336
+ * @example
337
+ * const viewCustomers: ActionFn<typeof catalog, 'viewCustomers'> = async (params, setState) => {
338
+ * const data = await fetch('/api/customers');
339
+ * setState(prev => ({ ...prev, customers: data }));
340
+ * };
341
+ */
342
+ type ActionFn<C extends Catalog, K extends keyof InferCatalogActions<C>> = (params: InferActionParams<C, K> | undefined, setState: SetState, state: StateModel) => Promise<void>;
343
+ /**
344
+ * Registry of all action handlers for a catalog
345
+ * @example
346
+ * const actions: Actions<typeof myCatalog> = {
347
+ * viewCustomers: async (params, setState) => { ... },
348
+ * createCustomer: async (params, setState) => { ... },
349
+ * };
350
+ */
351
+ type Actions<C extends Catalog> = {
352
+ [K in keyof InferCatalogActions<C>]: ActionFn<C, K>;
353
+ };
354
+ /**
355
+ * True when the catalog declares at least one action, false otherwise.
356
+ * Used by defineRegistry to conditionally require the `actions` field.
357
+ */
358
+ type CatalogHasActions<C extends Catalog> = [
359
+ InferCatalogActions<C>
360
+ ] extends [never] ? false : [keyof InferCatalogActions<C>] extends [never] ? false : true;
361
+
362
+ /**
363
+ * Props passed to component renderers
364
+ */
365
+ interface ComponentRenderProps<P = Record<string, unknown>> {
366
+ /** The element being rendered */
367
+ element: UIElement<string, P>;
368
+ /** Rendered children */
369
+ children?: ReactNode;
370
+ /** Emit a named event. The renderer resolves the event to action binding(s) from the element's `on` field. Always provided by the renderer. */
371
+ emit: (event: string) => void;
372
+ /** Get an event handle with metadata (shouldPreventDefault, bound). Use when you need to inspect event bindings. */
373
+ on: (event: string) => EventHandle;
374
+ /**
375
+ * Two-way binding paths resolved from `$bindState` / `$bindItem` expressions.
376
+ * Maps prop name → absolute state path for write-back.
377
+ * Only present when at least one prop uses `{ $bindState: "..." }` or `{ $bindItem: "..." }`.
378
+ */
379
+ bindings?: Record<string, string>;
380
+ /** Whether the parent is loading */
381
+ loading?: boolean;
382
+ }
383
+ /**
384
+ * Component renderer type
385
+ */
386
+ type ComponentRenderer<P = Record<string, unknown>> = ComponentType<ComponentRenderProps<P>>;
387
+ /**
388
+ * Registry of component renderers
389
+ */
390
+ type ComponentRegistry = Record<string, ComponentRenderer<any>>;
391
+ /**
392
+ * Props for the Renderer component
393
+ */
394
+ interface RendererProps {
395
+ /** The UI spec to render */
396
+ spec: Spec | null;
397
+ /** Component registry */
398
+ registry: ComponentRegistry;
399
+ /** Whether the spec is currently loading/streaming */
400
+ loading?: boolean;
401
+ /** Fallback component for unknown types */
402
+ fallback?: ComponentRenderer;
403
+ /** Callback for element render errors caught by the inner boundary */
404
+ onRenderError?: RenderErrorHandler;
405
+ }
406
+ /**
407
+ * Main renderer component
408
+ */
409
+ declare function Renderer({ spec, registry, loading, fallback, onRenderError, }: RendererProps): react_jsx_runtime.JSX.Element | null;
410
+ /**
411
+ * Props for JSONUIProvider
412
+ */
413
+ interface JSONUIProviderProps {
414
+ /** Component registry */
415
+ registry: ComponentRegistry;
416
+ /**
417
+ * External store (controlled mode). When provided, `initialState` and
418
+ * `onStateChange` are ignored.
419
+ */
420
+ store?: StateStore;
421
+ /** Initial state model (uncontrolled mode) */
422
+ initialState?: Record<string, unknown>;
423
+ /** Action handlers */
424
+ handlers?: Record<string, (params: Record<string, unknown>) => Promise<unknown> | unknown>;
425
+ /** Navigation function */
426
+ navigate?: (path: string) => void;
427
+ /** Custom validation functions */
428
+ validationFunctions?: Record<string, (value: unknown, args?: Record<string, unknown>) => boolean>;
429
+ /** Named functions for `$computed` expressions in props */
430
+ functions?: Record<string, ComputedFunction>;
431
+ /** Custom directives for user-defined `$`-prefixed dynamic values */
432
+ directives?: DirectiveDefinition[];
433
+ /** Callback when state changes (uncontrolled mode) */
434
+ onStateChange?: (changes: Array<{
435
+ path: string;
436
+ value: unknown;
437
+ }>) => void;
438
+ children: ReactNode;
439
+ }
440
+ /**
441
+ * Combined provider for all JSONUI contexts
442
+ */
443
+ declare function JSONUIProvider({ registry, store, initialState, handlers, navigate, validationFunctions, functions, directives, onStateChange, children, }: JSONUIProviderProps): react_jsx_runtime.JSX.Element;
444
+ /**
445
+ * Result returned by defineRegistry
446
+ */
447
+ interface DefineRegistryResult {
448
+ /** Component registry for `<Renderer registry={...} />` */
449
+ registry: ComponentRegistry;
450
+ /**
451
+ * Create ActionProvider-compatible handlers.
452
+ * Accepts getter functions so handlers always read the latest state/setState
453
+ * (e.g. from React refs).
454
+ */
455
+ handlers: (getSetState: () => SetState | undefined, getState: () => StateModel) => Record<string, (params: Record<string, unknown>) => Promise<void>>;
456
+ /**
457
+ * Execute an action by name imperatively
458
+ * (for use outside the React tree, e.g. initial state loading).
459
+ */
460
+ executeAction: (actionName: string, params: Record<string, unknown> | undefined, setState: SetState, state?: StateModel) => Promise<void>;
461
+ }
462
+ /**
463
+ * Options for defineRegistry.
464
+ *
465
+ * When the catalog declares actions, the `actions` field is required.
466
+ * When the catalog has no actions (or `actions: {}`), the field is optional.
467
+ */
468
+ type DefineRegistryOptions<C extends Catalog> = {
469
+ components?: Components<C>;
470
+ onRenderError?: RenderErrorHandler;
471
+ } & (CatalogHasActions<C> extends true ? {
472
+ actions: Actions<C>;
473
+ } : {
474
+ actions?: Actions<C>;
475
+ });
476
+ /**
477
+ * Create a registry from a catalog with components and/or actions.
478
+ *
479
+ * When the catalog declares actions, the `actions` field is required.
480
+ *
481
+ * @example
482
+ * ```tsx
483
+ * // Components only (catalog has no actions)
484
+ * const { registry } = defineRegistry(catalog, {
485
+ * components: {
486
+ * Card: ({ props, children }) => (
487
+ * <div className="card">{props.title}{children}</div>
488
+ * ),
489
+ * },
490
+ * });
491
+ *
492
+ * // Both (catalog declares actions)
493
+ * const { registry, handlers, executeAction } = defineRegistry(catalog, {
494
+ * components: { ... },
495
+ * actions: { ... },
496
+ * });
497
+ * ```
498
+ */
499
+ declare function defineRegistry<C extends Catalog>(_catalog: C, options: DefineRegistryOptions<C>): DefineRegistryResult;
500
+ /**
501
+ * Props for renderers created with createRenderer
502
+ */
503
+ interface CreateRendererProps {
504
+ /** The spec to render (AI-generated JSON) */
505
+ spec: Spec | null;
506
+ /**
507
+ * External store (controlled mode). When provided, `state` and
508
+ * `onStateChange` are ignored.
509
+ */
510
+ store?: StateStore;
511
+ /** State context for dynamic values (uncontrolled mode) */
512
+ state?: Record<string, unknown>;
513
+ /** Action handler */
514
+ onAction?: (actionName: string, params?: Record<string, unknown>) => void;
515
+ /** Callback when state changes (uncontrolled mode) */
516
+ onStateChange?: (changes: Array<{
517
+ path: string;
518
+ value: unknown;
519
+ }>) => void;
520
+ /** Named functions for `$computed` expressions in props */
521
+ functions?: Record<string, ComputedFunction>;
522
+ /** Custom directives for user-defined `$`-prefixed dynamic values */
523
+ directives?: DirectiveDefinition[];
524
+ /** Whether the spec is currently loading/streaming */
525
+ loading?: boolean;
526
+ /** Fallback component for unknown types */
527
+ fallback?: ComponentRenderer;
528
+ /** Callback for element render errors caught by the inner boundary */
529
+ onRenderError?: RenderErrorHandler;
530
+ }
531
+ /**
532
+ * Component map type - maps component names to React components
533
+ */
534
+ type ComponentMap<TComponents extends Record<string, {
535
+ props: unknown;
536
+ }>> = {
537
+ [K in keyof TComponents]: ComponentType<ComponentRenderProps<TComponents[K]["props"] extends {
538
+ _output: infer O;
539
+ } ? O : Record<string, unknown>>>;
540
+ };
541
+ /**
542
+ * Create a renderer from a catalog
543
+ *
544
+ * @example
545
+ * ```typescript
546
+ * const DashboardRenderer = createRenderer(dashboardCatalog, {
547
+ * Card: ({ element, children }) => <div className="card">{children}</div>,
548
+ * Metric: ({ element }) => <span>{element.props.value}</span>,
549
+ * });
550
+ *
551
+ * // Usage
552
+ * <DashboardRenderer spec={aiGeneratedSpec} state={state} />
553
+ * ```
554
+ */
555
+ declare function createRenderer<TDef extends SchemaDefinition, TCatalog extends {
556
+ components: Record<string, {
557
+ props: unknown;
558
+ }>;
559
+ }>(catalog: Catalog<TDef, TCatalog>, components: ComponentMap<TCatalog["components"]>): ComponentType<CreateRendererProps>;
560
+
561
+ /**
562
+ * Token usage metadata from AI generation
563
+ */
564
+ interface TokenUsage {
565
+ promptTokens: number;
566
+ completionTokens: number;
567
+ totalTokens: number;
568
+ }
569
+ /**
570
+ * Options for useUIStream
571
+ */
572
+ interface UseUIStreamOptions {
573
+ /** API endpoint */
574
+ api: string;
575
+ /** Callback when complete */
576
+ onComplete?: (spec: Spec) => void;
577
+ /** Callback on error */
578
+ onError?: (error: Error) => void;
579
+ }
580
+ /**
581
+ * Return type for useUIStream
582
+ */
583
+ interface UseUIStreamReturn {
584
+ /** Current UI spec */
585
+ spec: Spec | null;
586
+ /** Whether currently streaming */
587
+ isStreaming: boolean;
588
+ /** Error if any */
589
+ error: Error | null;
590
+ /** Token usage from the last generation */
591
+ usage: TokenUsage | null;
592
+ /** Raw JSONL lines received from the stream (JSON patch lines) */
593
+ rawLines: string[];
594
+ /** Send a prompt to generate UI */
595
+ send: (prompt: string, context?: Record<string, unknown>) => Promise<void>;
596
+ /** Clear the current spec */
597
+ clear: () => void;
598
+ }
599
+ /**
600
+ * Hook for streaming UI generation
601
+ */
602
+ declare function useUIStream({ api, onComplete, onError, }: UseUIStreamOptions): UseUIStreamReturn;
603
+ /**
604
+ * Convert a flat element list to a Spec.
605
+ * Input elements use key/parentKey to establish identity and relationships.
606
+ * Output spec uses the map-based format where key is the map entry key
607
+ * and parent-child relationships are expressed through children arrays.
608
+ */
609
+ declare function flatToTree(elements: FlatElement[]): Spec;
610
+ /**
611
+ * Hook for two-way bound props. Returns `[value, setValue]` where:
612
+ *
613
+ * - `value` is the already-resolved prop value (passed through from render props)
614
+ * - `setValue` writes back to the bound state path (no-op if not bound)
615
+ *
616
+ * Designed to work with the `bindings` map that the renderer provides when
617
+ * a prop uses `{ $bindState: "/path" }` or `{ $bindItem: "field" }`.
618
+ *
619
+ * @example
620
+ * ```tsx
621
+ * import { useBoundProp } from "@xmachines/json-render-react";
622
+ *
623
+ * const Input: ComponentRenderer = ({ props, bindings }) => {
624
+ * const [value, setValue] = useBoundProp<string>(props.value, bindings?.value);
625
+ * return <input value={value ?? ""} onChange={(e) => setValue(e.target.value)} />;
626
+ * };
627
+ * ```
628
+ */
629
+ declare function useBoundProp<T>(propValue: T | undefined, bindingPath: string | undefined): [T | undefined, (value: T) => void];
630
+ /**
631
+ * A single part from the AI SDK's `message.parts` array. This is a minimal
632
+ * structural type so that library helpers do not depend on the AI SDK.
633
+ * Fields are optional because different part types carry different data:
634
+ * - Text parts have `text`
635
+ * - Data parts have `data`
636
+ */
637
+ interface DataPart {
638
+ type: string;
639
+ text?: string;
640
+ data?: unknown;
641
+ }
642
+ declare function buildSpecFromParts(parts: DataPart[]): Spec | null;
643
+ /**
644
+ * Extract and join all text content from a message's parts array.
645
+ *
646
+ * Filters for parts with `type === "text"`, trims each one, and joins them
647
+ * with double newlines so that text from separate agent steps renders as
648
+ * distinct paragraphs in markdown.
649
+ *
650
+ * Has no AI SDK dependency — operates on a generic `DataPart[]`.
651
+ *
652
+ * @example
653
+ * ```tsx
654
+ * const text = getTextFromParts(message.parts);
655
+ * if (text) {
656
+ * return <Streamdown>{text}</Streamdown>;
657
+ * }
658
+ * ```
659
+ */
660
+ declare function getTextFromParts(parts: DataPart[]): string;
661
+ /**
662
+ * Hook that extracts both the json-render spec and text content from a
663
+ * message's parts array. Combines `buildSpecFromParts` and `getTextFromParts`
664
+ * into a single call with memoized results.
665
+ *
666
+ * **Memoization behavior:** Results are recomputed only when the `parts` array
667
+ * reference changes **and** either the length differs or the last element is a
668
+ * different object. This is optimized for the typical AI SDK streaming pattern
669
+ * where parts are appended incrementally. Mid-array edits (e.g. replacing an
670
+ * earlier part without appending) may not trigger recomputation. If you need to
671
+ * force a recompute after such edits, pass a new array reference with a
672
+ * different last element.
673
+ *
674
+ * @example
675
+ * ```tsx
676
+ * import { useJsonRenderMessage } from "@xmachines/json-render-react";
677
+ *
678
+ * function MessageBubble({ message }) {
679
+ * const { spec, text, hasSpec } = useJsonRenderMessage(message.parts);
680
+ *
681
+ * return (
682
+ * <div>
683
+ * {text && <Markdown>{text}</Markdown>}
684
+ * {hasSpec && <MyRenderer spec={spec} />}
685
+ * </div>
686
+ * );
687
+ * }
688
+ * ```
689
+ */
690
+ declare function useJsonRenderMessage(parts: DataPart[]): {
691
+ spec: Spec | null;
692
+ text: string;
693
+ hasSpec: boolean;
694
+ };
695
+ /**
696
+ * A single message in the chat, which may contain text, a rendered UI spec, or both.
697
+ */
698
+ interface ChatMessage {
699
+ /** Unique message ID */
700
+ id: string;
701
+ /** Who sent this message */
702
+ role: "user" | "assistant";
703
+ /** Text content (conversational prose) */
704
+ text: string;
705
+ /** json-render Spec built from JSONL patches (null if no UI was generated) */
706
+ spec: Spec | null;
707
+ }
708
+ /**
709
+ * Options for useChatUI
710
+ */
711
+ interface UseChatUIOptions {
712
+ /** API endpoint that accepts `{ messages: Array<{ role, content }> }` and returns a text stream */
713
+ api: string;
714
+ /** Callback when streaming completes for a message */
715
+ onComplete?: (message: ChatMessage) => void;
716
+ /** Callback on error */
717
+ onError?: (error: Error) => void;
718
+ }
719
+ /**
720
+ * Return type for useChatUI
721
+ */
722
+ interface UseChatUIReturn {
723
+ /** All messages in the conversation */
724
+ messages: ChatMessage[];
725
+ /** Whether currently streaming an assistant response */
726
+ isStreaming: boolean;
727
+ /** Error from the last request, if any */
728
+ error: Error | null;
729
+ /** Send a user message */
730
+ send: (text: string) => Promise<void>;
731
+ /** Clear all messages and reset the conversation */
732
+ clear: () => void;
733
+ }
734
+ /**
735
+ * Hook for chat + GenUI experiences.
736
+ *
737
+ * Manages a multi-turn conversation where each assistant message can contain
738
+ * both conversational text and a json-render UI spec. The hook sends the full
739
+ * message history to the API endpoint, reads the streamed response, and
740
+ * separates text lines from JSONL patch lines using `createMixedStreamParser`.
741
+ *
742
+ * @example
743
+ * ```tsx
744
+ * const { messages, isStreaming, send, clear } = useChatUI({
745
+ * api: "/api/chat",
746
+ * });
747
+ *
748
+ * // Send a message
749
+ * await send("Compare weather in NYC and Tokyo");
750
+ *
751
+ * // Render messages
752
+ * {messages.map((msg) => (
753
+ * <div key={msg.id}>
754
+ * {msg.text && <p>{msg.text}</p>}
755
+ * {msg.spec && <MyRenderer spec={msg.spec} />}
756
+ * </div>
757
+ * ))}
758
+ * ```
759
+ */
760
+ declare function useChatUI({ api, onComplete, onError, }: UseChatUIOptions): UseChatUIReturn;
761
+
762
+ export { type ActionContextValue, type ActionFn, ActionProvider, type ActionProviderProps, type Actions, type BaseComponentProps, type ChatMessage, type ComponentContext, type ComponentFn, type ComponentMap, type ComponentRegistry, type ComponentRenderProps, type ComponentRenderer, type Components, ConfirmDialog, type ConfirmDialogProps, type CreateRendererProps, type DataPart, type DefineRegistryResult, type EventHandle, type FieldValidationState, JSONUIProvider, type JSONUIProviderProps, type PendingConfirmation, Renderer, type RendererProps, RepeatScopeProvider, type RepeatScopeValue, type SetState, type StateContextValue, StateProvider, type StateProviderProps, type TokenUsage, type UseChatUIOptions, type UseChatUIReturn, type UseUIStreamOptions, type UseUIStreamReturn, type ValidationContextValue, ValidationProvider, type ValidationProviderProps, type VisibilityContextValue, VisibilityProvider, type VisibilityProviderProps, buildSpecFromParts, createRenderer, defineRegistry, flatToTree, getTextFromParts, useAction, useActions, useBoundProp, useChatUI, useFieldValidation, useIsVisible, useJsonRenderMessage, useOptionalValidation, useRepeatScope, useStateBinding, useStateStore, useStateValue, useUIStream, useValidation, useVisibility };