@xmachines/json-render-react 0.21.0-xm.5 → 0.21.0-xm.6

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.
package/dist/index.js CHANGED
@@ -40,7 +40,7 @@ __export(index_exports, {
40
40
  VisibilityProvider: () => VisibilityProvider,
41
41
  buildSpecFromParts: () => buildSpecFromParts,
42
42
  createRenderer: () => createRenderer,
43
- createStateStore: () => import_core8.createStateStore,
43
+ createStateStore: () => import_core11.createStateStore,
44
44
  defineRegistry: () => defineRegistry,
45
45
  elementTreeSchema: () => elementTreeSchema,
46
46
  flatToTree: () => flatToTree,
@@ -222,14 +222,65 @@ function useIsVisible(condition) {
222
222
  }
223
223
 
224
224
  // src/contexts/actions.tsx
225
- var import_react4 = require("react");
226
- var import_core4 = require("@xmachines/json-render-core");
225
+ var import_react6 = require("react");
226
+ var import_core5 = require("@xmachines/json-render-core");
227
227
 
228
228
  // src/contexts/validation.tsx
229
- var import_react3 = __toESM(require("react"));
229
+ var import_react4 = require("react");
230
230
  var import_core3 = require("@xmachines/json-render-core");
231
+
232
+ // src/xm/field-registration.ts
233
+ var import_react3 = __toESM(require("react"));
234
+ var useIsomorphicLayoutEffect = typeof document !== "undefined" ? import_react3.default.useLayoutEffect : import_react3.default.useEffect;
235
+ function useFieldConfigs(fieldStatesRef, configEqual) {
236
+ const [fieldConfigs, setFieldConfigs] = (0, import_react3.useState)({});
237
+ const fieldConfigsRef = (0, import_react3.useRef)({});
238
+ const registrationCounts = (0, import_react3.useRef)({});
239
+ const registerField = (0, import_react3.useCallback)(
240
+ (path, config) => {
241
+ registrationCounts.current[path] = (registrationCounts.current[path] ?? 0) + 1;
242
+ const existing = fieldConfigsRef.current[path];
243
+ if (existing && configEqual(existing, config)) return;
244
+ fieldConfigsRef.current = { ...fieldConfigsRef.current, [path]: config };
245
+ setFieldConfigs(fieldConfigsRef.current);
246
+ },
247
+ [configEqual]
248
+ );
249
+ const unregisterField = (0, import_react3.useCallback)(
250
+ (path) => {
251
+ const next = (registrationCounts.current[path] ?? 0) - 1;
252
+ if (next > 0) {
253
+ registrationCounts.current[path] = next;
254
+ return;
255
+ }
256
+ delete registrationCounts.current[path];
257
+ delete fieldStatesRef.current[path];
258
+ if (!(path in fieldConfigsRef.current)) return;
259
+ const { [path]: _removed, ...rest } = fieldConfigsRef.current;
260
+ fieldConfigsRef.current = rest;
261
+ setFieldConfigs(rest);
262
+ },
263
+ [fieldStatesRef]
264
+ );
265
+ return { fieldConfigs, fieldConfigsRef, registerField, unregisterField };
266
+ }
267
+ function useFieldRegistration(path, config, registerField, unregisterField) {
268
+ const configKey = config === void 0 ? void 0 : JSON.stringify(config);
269
+ const configRef = (0, import_react3.useRef)(config);
270
+ configRef.current = config;
271
+ useIsomorphicLayoutEffect(() => {
272
+ const current = configRef.current;
273
+ if (path && current) {
274
+ registerField(path, current);
275
+ return () => unregisterField(path);
276
+ }
277
+ return void 0;
278
+ }, [path, configKey, registerField, unregisterField]);
279
+ }
280
+
281
+ // src/contexts/validation.tsx
231
282
  var import_jsx_runtime3 = require("react/jsx-runtime");
232
- var ValidationContext = (0, import_react3.createContext)(null);
283
+ var ValidationContext = (0, import_react4.createContext)(null);
233
284
  var EMPTY_VALIDATION_FUNCTIONS = {};
234
285
  function dynamicArgsEqual(a, b) {
235
286
  if (a === b) return true;
@@ -270,38 +321,10 @@ function ValidationProvider({
270
321
  children
271
322
  }) {
272
323
  const { state, getSnapshot } = useStateStore();
273
- const [fieldStates, setFieldStates] = (0, import_react3.useState)({});
274
- const fieldStatesRef = (0, import_react3.useRef)({});
275
- const [fieldConfigs, setFieldConfigs] = (0, import_react3.useState)({});
276
- const registrationCounts = (0, import_react3.useRef)({});
277
- const registerField = (0, import_react3.useCallback)(
278
- (path, config) => {
279
- registrationCounts.current[path] = (registrationCounts.current[path] ?? 0) + 1;
280
- setFieldConfigs((prev) => {
281
- const existing = prev[path];
282
- if (existing && validationConfigEqual(existing, config)) {
283
- return prev;
284
- }
285
- return { ...prev, [path]: config };
286
- });
287
- },
288
- []
289
- );
290
- const unregisterField = (0, import_react3.useCallback)((path) => {
291
- const next = (registrationCounts.current[path] ?? 0) - 1;
292
- if (next > 0) {
293
- registrationCounts.current[path] = next;
294
- return;
295
- }
296
- delete registrationCounts.current[path];
297
- delete fieldStatesRef.current[path];
298
- setFieldConfigs((prev) => {
299
- if (!(path in prev)) return prev;
300
- const { [path]: _removed, ...rest } = prev;
301
- return rest;
302
- });
303
- }, []);
304
- const validate = (0, import_react3.useCallback)(
324
+ const [fieldStates, setFieldStates] = (0, import_react4.useState)({});
325
+ const fieldStatesRef = (0, import_react4.useRef)({});
326
+ const { fieldConfigs, fieldConfigsRef, registerField, unregisterField } = useFieldConfigs(fieldStatesRef, validationConfigEqual);
327
+ const validate = (0, import_react4.useCallback)(
305
328
  (path, config) => {
306
329
  const currentState = getSnapshot();
307
330
  const segments = path.split("/").filter(Boolean);
@@ -333,7 +356,7 @@ function ValidationProvider({
333
356
  },
334
357
  [customFunctions, getSnapshot]
335
358
  );
336
- const touch = (0, import_react3.useCallback)((path) => {
359
+ const touch = (0, import_react4.useCallback)((path) => {
337
360
  fieldStatesRef.current = {
338
361
  ...fieldStatesRef.current,
339
362
  [path]: {
@@ -345,22 +368,22 @@ function ValidationProvider({
345
368
  };
346
369
  setFieldStates(fieldStatesRef.current);
347
370
  }, []);
348
- const clear = (0, import_react3.useCallback)((path) => {
371
+ const clear = (0, import_react4.useCallback)((path) => {
349
372
  const { [path]: _, ...rest } = fieldStatesRef.current;
350
373
  fieldStatesRef.current = rest;
351
374
  setFieldStates(rest);
352
375
  }, []);
353
- const validateAll = (0, import_react3.useCallback)(() => {
376
+ const validateAll = (0, import_react4.useCallback)(() => {
354
377
  let allValid = true;
355
- for (const [path, config] of Object.entries(fieldConfigs)) {
378
+ for (const [path, config] of Object.entries(fieldConfigsRef.current)) {
356
379
  const result = validate(path, config);
357
380
  if (!result.valid) {
358
381
  allValid = false;
359
382
  }
360
383
  }
361
384
  return allValid;
362
- }, [fieldConfigs, validate]);
363
- const value = (0, import_react3.useMemo)(
385
+ }, [validate]);
386
+ const value = (0, import_react4.useMemo)(
364
387
  () => ({
365
388
  customFunctions,
366
389
  // Getter returns the mutable ref so callers that read fieldStates
@@ -380,6 +403,7 @@ function ValidationProvider({
380
403
  // fieldStates (React state) stays in deps so the context value object
381
404
  // is recreated on re-render, triggering downstream consumers.
382
405
  fieldStates,
406
+ fieldConfigs,
383
407
  validate,
384
408
  touch,
385
409
  clear,
@@ -391,16 +415,15 @@ function ValidationProvider({
391
415
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ValidationContext.Provider, { value, children });
392
416
  }
393
417
  function useValidation() {
394
- const ctx = (0, import_react3.useContext)(ValidationContext);
418
+ const ctx = (0, import_react4.useContext)(ValidationContext);
395
419
  if (!ctx) {
396
420
  throw new Error("useValidation must be used within a ValidationProvider");
397
421
  }
398
422
  return ctx;
399
423
  }
400
424
  function useOptionalValidation() {
401
- return (0, import_react3.useContext)(ValidationContext);
425
+ return (0, import_react4.useContext)(ValidationContext);
402
426
  }
403
- var useIsomorphicLayoutEffect = typeof document !== "undefined" ? import_react3.default.useLayoutEffect : import_react3.default.useEffect;
404
427
  function useFieldValidation(path, config) {
405
428
  const {
406
429
  fieldStates,
@@ -410,28 +433,18 @@ function useFieldValidation(path, config) {
410
433
  registerField,
411
434
  unregisterField
412
435
  } = useValidation();
413
- const configKey = config === void 0 ? void 0 : JSON.stringify(config);
414
- const configRef = import_react3.default.useRef(config);
415
- configRef.current = config;
416
- useIsomorphicLayoutEffect(() => {
417
- const current = configRef.current;
418
- if (path && current) {
419
- registerField(path, current);
420
- return () => unregisterField(path);
421
- }
422
- return void 0;
423
- }, [path, configKey, registerField, unregisterField]);
436
+ useFieldRegistration(path, config, registerField, unregisterField);
424
437
  const state = fieldStates[path] ?? {
425
438
  touched: false,
426
439
  validated: false,
427
440
  result: null
428
441
  };
429
- const validate = (0, import_react3.useCallback)(
442
+ const validate = (0, import_react4.useCallback)(
430
443
  () => validateField(path, config ?? { checks: [] }),
431
444
  [path, config, validateField]
432
445
  );
433
- const touch = (0, import_react3.useCallback)(() => touchField(path), [path, touchField]);
434
- const clear = (0, import_react3.useCallback)(() => clearField(path), [path, clearField]);
446
+ const touch = (0, import_react4.useCallback)(() => touchField(path), [path, touchField]);
447
+ const clear = (0, import_react4.useCallback)(() => clearField(path), [path, clearField]);
435
448
  return {
436
449
  state,
437
450
  validate,
@@ -442,6 +455,34 @@ function useFieldValidation(path, config) {
442
455
  };
443
456
  }
444
457
 
458
+ // src/xm/action-handlers.ts
459
+ var import_react5 = require("react");
460
+ var import_core4 = require("@xmachines/json-render-core");
461
+ var ANY_NAME_PROBE = "\0json-render:any-name";
462
+ function useActionHandlers(handlersProp) {
463
+ const propRef = (0, import_react5.useRef)(handlersProp);
464
+ propRef.current = handlersProp;
465
+ const [registered, setRegistered] = (0, import_react5.useState)(
466
+ {}
467
+ );
468
+ const propNames = JSON.stringify([
469
+ Object.keys(handlersProp),
470
+ Reflect.has(handlersProp, ANY_NAME_PROBE)
471
+ ]);
472
+ const handlers = (0, import_react5.useMemo)(
473
+ () => (0, import_core4.mergeActionHandlers)(() => propRef.current, registered),
474
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- propNames is the change signal
475
+ [registered, propNames]
476
+ );
477
+ const registerHandler = (0, import_react5.useCallback)(
478
+ (name, handler) => {
479
+ setRegistered((prev) => ({ ...prev, [name]: handler }));
480
+ },
481
+ []
482
+ );
483
+ return { handlers, registerHandler };
484
+ }
485
+
445
486
  // src/contexts/actions.tsx
446
487
  var import_jsx_runtime4 = require("react/jsx-runtime");
447
488
  var idCounter = 0;
@@ -476,7 +517,7 @@ function deepResolveValue(value, get) {
476
517
  }
477
518
  return value;
478
519
  }
479
- var ActionContext = (0, import_react4.createContext)(null);
520
+ var ActionContext = (0, import_react6.createContext)(null);
480
521
  function ActionProvider({
481
522
  handlers: handlersProp = {},
482
523
  navigate,
@@ -484,35 +525,16 @@ function ActionProvider({
484
525
  }) {
485
526
  const { get, set, getSnapshot } = useStateStore();
486
527
  const validation = useOptionalValidation();
487
- const propRef = (0, import_react4.useRef)(handlersProp);
488
- propRef.current = handlersProp;
489
- const [registered, setRegistered] = (0, import_react4.useState)(
490
- {}
491
- );
492
- const propNames = JSON.stringify([
493
- Object.keys(handlersProp),
494
- Reflect.has(handlersProp, "\0json-render:any-name")
495
- ]);
496
- const handlers = (0, import_react4.useMemo)(
497
- () => (0, import_core4.mergeActionHandlers)(() => propRef.current, registered),
498
- // eslint-disable-next-line react-hooks/exhaustive-deps -- propNames is the change signal
499
- [registered, propNames]
500
- );
501
- const [loadingActions, setLoadingActions] = (0, import_react4.useState)(/* @__PURE__ */ new Set());
502
- const [pendingConfirmation, setPendingConfirmation] = (0, import_react4.useState)(null);
503
- const pendingRef = (0, import_react4.useRef)(null);
504
- const registerHandler = (0, import_react4.useCallback)(
505
- (name, handler) => {
506
- setRegistered((prev) => ({ ...prev, [name]: handler }));
507
- },
508
- []
509
- );
510
- const execute = (0, import_react4.useCallback)(
528
+ const { handlers, registerHandler } = useActionHandlers(handlersProp);
529
+ const [loadingActions, setLoadingActions] = (0, import_react6.useState)(/* @__PURE__ */ new Set());
530
+ const [pendingConfirmation, setPendingConfirmation] = (0, import_react6.useState)(null);
531
+ const pendingRef = (0, import_react6.useRef)(null);
532
+ const execute = (0, import_react6.useCallback)(
511
533
  async (binding) => {
512
- const resolved = (0, import_core4.resolveAction)(binding, getSnapshot());
513
- const dispatchId = (0, import_core4.nextActionDispatchId)();
534
+ const resolved = (0, import_core5.resolveAction)(binding, getSnapshot());
535
+ const dispatchId = (0, import_core5.nextActionDispatchId)();
514
536
  const dispatchedAt = Date.now();
515
- (0, import_core4.notifyActionDispatch)({
537
+ (0, import_core5.notifyActionDispatch)({
516
538
  id: dispatchId,
517
539
  name: resolved.action,
518
540
  params: resolved.params,
@@ -524,7 +546,7 @@ function ActionProvider({
524
546
  let __confirmMs = void 0;
525
547
  try {
526
548
  const handler = handlers[resolved.action];
527
- if (!handler && !(0, import_core4.isBuiltInAction)(resolved.action)) {
549
+ if (!handler && !(0, import_core5.isBuiltInAction)(resolved.action)) {
528
550
  console.warn(`No handler registered for action: ${resolved.action}`);
529
551
  return;
530
552
  }
@@ -639,7 +661,7 @@ function ActionProvider({
639
661
  if (!handler) return;
640
662
  setLoadingActions((prev) => new Set(prev).add(resolved.action));
641
663
  try {
642
- await (0, import_core4.executeAction)({
664
+ await (0, import_core5.executeAction)({
643
665
  action: resolved,
644
666
  handler,
645
667
  setState: set,
@@ -661,7 +683,7 @@ function ActionProvider({
661
683
  throw err;
662
684
  } finally {
663
685
  const now = Date.now();
664
- (0, import_core4.notifyActionSettle)({
686
+ (0, import_core5.notifyActionSettle)({
665
687
  id: dispatchId,
666
688
  name: resolved.action,
667
689
  ok: __ok,
@@ -675,13 +697,13 @@ function ActionProvider({
675
697
  },
676
698
  [handlers, get, set, getSnapshot, navigate, validation]
677
699
  );
678
- const confirm = (0, import_react4.useCallback)(() => {
700
+ const confirm = (0, import_react6.useCallback)(() => {
679
701
  pendingRef.current?.resolve();
680
702
  }, []);
681
- const cancel = (0, import_react4.useCallback)(() => {
703
+ const cancel = (0, import_react6.useCallback)(() => {
682
704
  pendingRef.current?.reject();
683
705
  }, []);
684
- const value = (0, import_react4.useMemo)(
706
+ const value = (0, import_react6.useMemo)(
685
707
  () => ({
686
708
  handlers,
687
709
  loadingActions,
@@ -704,7 +726,7 @@ function ActionProvider({
704
726
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ActionContext.Provider, { value, children });
705
727
  }
706
728
  function useActions() {
707
- const ctx = (0, import_react4.useContext)(ActionContext);
729
+ const ctx = (0, import_react6.useContext)(ActionContext);
708
730
  if (!ctx) {
709
731
  throw new Error("useActions must be used within an ActionProvider");
710
732
  }
@@ -713,7 +735,7 @@ function useActions() {
713
735
  function useAction(binding) {
714
736
  const { execute, loadingActions } = useActions();
715
737
  const isLoading = loadingActions.has(binding.action);
716
- const executeAction2 = (0, import_react4.useCallback)(() => execute(binding), [execute, binding]);
738
+ const executeAction2 = (0, import_react6.useCallback)(() => execute(binding), [execute, binding]);
717
739
  return { execute: executeAction2, isLoading };
718
740
  }
719
741
  function ConfirmDialog({
@@ -818,9 +840,9 @@ function ConfirmDialog({
818
840
  }
819
841
 
820
842
  // src/contexts/repeat-scope.tsx
821
- var import_react5 = require("react");
843
+ var import_react7 = require("react");
822
844
  var import_jsx_runtime5 = require("react/jsx-runtime");
823
- var RepeatScopeContext = (0, import_react5.createContext)(null);
845
+ var RepeatScopeContext = (0, import_react7.createContext)(null);
824
846
  function RepeatScopeProvider({
825
847
  item,
826
848
  index,
@@ -830,12 +852,12 @@ function RepeatScopeProvider({
830
852
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(RepeatScopeContext.Provider, { value: { item, index, basePath }, children });
831
853
  }
832
854
  function useRepeatScope() {
833
- return (0, import_react5.useContext)(RepeatScopeContext);
855
+ return (0, import_react7.useContext)(RepeatScopeContext);
834
856
  }
835
857
 
836
858
  // src/schema.ts
837
- var import_core5 = require("@xmachines/json-render-core");
838
- var schema = (0, import_core5.defineSchema)(
859
+ var import_core6 = require("@xmachines/json-render-core");
860
+ var schema = (0, import_core6.defineSchema)(
839
861
  (s) => ({
840
862
  // What the AI-generated SPEC looks like
841
863
  spec: s.object({
@@ -881,24 +903,7 @@ var schema = (0, import_core5.defineSchema)(
881
903
  })
882
904
  }),
883
905
  {
884
- builtInActions: [
885
- {
886
- name: "setState",
887
- description: "Update a value in the state model at the given statePath. Params: { statePath: string, value: any }"
888
- },
889
- {
890
- name: "pushState",
891
- description: 'Append an item to an array in state. Params: { statePath: string, value: any, clearStatePath?: string }. Value can contain {"$state":"/path"} refs and "$id" for auto IDs.'
892
- },
893
- {
894
- name: "removeState",
895
- description: "Remove an item from an array in state by index. Params: { statePath: string, index: number }"
896
- },
897
- {
898
- name: "validateForm",
899
- description: "Validate all registered form fields and write the result to state. Params: { statePath?: string }. Defaults to /formValidation. Result: { valid: boolean, errors: Record<string, string[]> }."
900
- }
901
- ],
906
+ builtInActions: [...import_core6.builtInActionDefinitions],
902
907
  defaultRules: [
903
908
  // Element integrity
904
909
  "CRITICAL INTEGRITY CHECK: Before outputting ANY element that references children, you MUST have already output (or will output) each child as its own element. If an element has children: ['a', 'b'], then elements 'a' and 'b' MUST exist. A missing child element causes that entire branch of the UI to be invisible.",
@@ -922,38 +927,162 @@ var schema = (0, import_core5.defineSchema)(
922
927
  var elementTreeSchema = schema;
923
928
 
924
929
  // src/index.ts
925
- var import_core8 = require("@xmachines/json-render-core");
930
+ var import_core11 = require("@xmachines/json-render-core");
926
931
 
927
932
  // src/renderer.tsx
928
- var import_react6 = __toESM(require("react"));
929
- var import_core6 = require("@xmachines/json-render-core");
930
- var import_jsx_runtime6 = require("react/jsx-runtime");
931
- var EMPTY_ELEMENT_PROPS = {};
933
+ var import_react10 = __toESM(require("react"));
934
+ var import_core9 = require("@xmachines/json-render-core");
935
+
936
+ // src/xm/render-errors.tsx
937
+ var import_react8 = __toESM(require("react"));
938
+ var import_core7 = require("@xmachines/json-render-core");
932
939
  function useRenderErrorRegistry(registry, onRenderError) {
933
- const handlerRef = (0, import_react6.useRef)(onRenderError);
940
+ const handlerRef = (0, import_react8.useRef)(onRenderError);
934
941
  handlerRef.current = onRenderError;
935
942
  const hasHandler = onRenderError !== void 0;
936
- return (0, import_react6.useMemo)(
937
- () => hasHandler ? (0, import_core6.withRenderErrorHandler)(registry, (error, elementType) => {
938
- handlerRef.current?.(error, elementType);
943
+ return (0, import_react8.useMemo)(
944
+ () => hasHandler ? (0, import_core7.withRenderErrorHandler)(registry, (error, name, info) => {
945
+ handlerRef.current?.(error, name, info);
939
946
  }) : registry,
940
947
  [registry, hasHandler]
941
948
  );
942
949
  }
943
- function reportRenderError(registry, elementType, error, componentStack) {
944
- const onRenderError = (0, import_core6.getRenderErrorHandler)(registry);
945
- if (onRenderError !== void 0) {
946
- onRenderError(error, elementType);
947
- return;
950
+ var objectTags = /* @__PURE__ */ new WeakMap();
951
+ var primitiveTag;
952
+ function isKeyable(value) {
953
+ return typeof value === "object" && value !== null || typeof value === "function";
954
+ }
955
+ function setTag(error, tag) {
956
+ if (isKeyable(error)) objectTags.set(error, tag);
957
+ else primitiveTag = { error, tag };
958
+ }
959
+ function takeTag(error) {
960
+ if (isKeyable(error)) {
961
+ const tag = objectTags.get(error);
962
+ objectTags.delete(error);
963
+ return tag;
948
964
  }
949
- (0, import_core6.warnUnusedRenderErrorHandler)(registry);
950
- console.error(
951
- `[json-render] Rendering error in <${elementType}>:`,
952
- error,
953
- componentStack
965
+ if (primitiveTag !== void 0 && Object.is(primitiveTag.error, error)) {
966
+ const { tag } = primitiveTag;
967
+ primitiveTag = void 0;
968
+ return tag;
969
+ }
970
+ return void 0;
971
+ }
972
+ function failsAs(kind, key, type, resolve, ...args) {
973
+ try {
974
+ return resolve(...args);
975
+ } catch (error) {
976
+ setTag(error, { kind, key, type });
977
+ throw error;
978
+ }
979
+ }
980
+ function useElementFailures(registry, key, type) {
981
+ return (0, import_react8.useMemo)(
982
+ () => ({
983
+ failsAt: (kind, resolve, ...args) => failsAs(kind, key, type, resolve, ...args),
984
+ reportChain: (error, action, kind) => (0, import_core7.reportRenderError)((0, import_core7.getRenderErrorHandler)(registry), error, action, {
985
+ kind,
986
+ action,
987
+ key,
988
+ type
989
+ })
990
+ }),
991
+ [registry, key, type]
954
992
  );
955
993
  }
956
- var ElementErrorBoundary = class extends import_react6.default.Component {
994
+ function caughtInfo(error, type, key) {
995
+ const tag = takeTag(error);
996
+ if (tag === void 0) return { kind: "element", key, type };
997
+ return { kind: tag.kind, key: tag.key ?? key, type: tag.type };
998
+ }
999
+ function reportElementFailure(registry, type, key, error) {
1000
+ const handler = (0, import_core7.getRenderErrorHandler)(registry);
1001
+ if (handler === void 0) (0, import_core7.warnUnusedRenderErrorHandler)(registry);
1002
+ (0, import_core7.reportRenderError)(handler, error, type, caughtInfo(error, type, key));
1003
+ }
1004
+ var RootErrorBoundary = class extends import_react8.default.Component {
1005
+ constructor(props) {
1006
+ super(props);
1007
+ this.state = { hasError: false };
1008
+ }
1009
+ static getDerivedStateFromError() {
1010
+ return { hasError: true };
1011
+ }
1012
+ componentDidCatch(error) {
1013
+ const handler = (0, import_core7.getRenderErrorHandler)(this.props.registry);
1014
+ if (handler === void 0)
1015
+ (0, import_core7.warnUnusedRenderErrorHandler)(this.props.registry);
1016
+ takeTag(error);
1017
+ (0, import_core7.reportRenderError)(handler, error, this.props.type, {
1018
+ kind: "root",
1019
+ key: this.props.rootKey,
1020
+ type: this.props.type
1021
+ });
1022
+ }
1023
+ componentDidUpdate(previous, previousState) {
1024
+ if (this.state.hasError && previousState.hasError && previous.resetKey !== this.props.resetKey) {
1025
+ this.setState({ hasError: false });
1026
+ }
1027
+ }
1028
+ render() {
1029
+ return this.state.hasError ? null : this.props.children;
1030
+ }
1031
+ };
1032
+ function useMissingRootWarning(spec, loading) {
1033
+ const missing = spec !== null && !loading && typeof spec.root === "string" && spec.root !== "" && spec.elements?.[spec.root] === void 0 ? spec.root : void 0;
1034
+ (0, import_react8.useEffect)(() => {
1035
+ if (missing !== void 0) (0, import_core7.warnMissingRoot)(missing);
1036
+ }, [missing]);
1037
+ }
1038
+ function useUnknownTypeWarning(registry, fallback, type, key) {
1039
+ const unknown = type !== void 0 && (fallback === void 0 || fallback === null) && (0, import_core7.getRegistryComponent)(registry, type) === void 0 ? type : void 0;
1040
+ (0, import_react8.useEffect)(() => {
1041
+ if (unknown !== void 0) (0, import_core7.warnUnknownType)(unknown, key);
1042
+ }, [unknown, key]);
1043
+ }
1044
+
1045
+ // src/xm/element-watch.ts
1046
+ var import_react9 = require("react");
1047
+ var import_core8 = require("@xmachines/json-render-core");
1048
+ function useElementWatch(watch, state, run, report) {
1049
+ const latest = { watch, run, report };
1050
+ const latestRef = (0, import_react9.useRef)(latest);
1051
+ latestRef.current = latest;
1052
+ const stableRef = (0, import_react9.useRef)(void 0);
1053
+ const previousRef = (0, import_react9.useRef)(null);
1054
+ const watchedValues = (0, import_react9.useMemo)(() => {
1055
+ const values = (0, import_core8.readWatchedValues)(watch, state, stableRef.current);
1056
+ stableRef.current = values;
1057
+ return values;
1058
+ }, [watch, state]);
1059
+ (0, import_react9.useEffect)(() => {
1060
+ const previous = previousRef.current;
1061
+ previousRef.current = watchedValues ?? null;
1062
+ const paths = (0, import_core8.changedWatchPaths)(watchedValues, previous ?? void 0);
1063
+ const current = latestRef.current.watch;
1064
+ if (!current || paths.length === 0) return;
1065
+ let cancelled = false;
1066
+ let action = "";
1067
+ void (0, import_core8.runWatchBindings)(
1068
+ current,
1069
+ paths,
1070
+ async (binding) => {
1071
+ action = binding.action;
1072
+ await latestRef.current.run(binding);
1073
+ },
1074
+ () => cancelled
1075
+ ).catch((error) => latestRef.current.report(error, action));
1076
+ return () => {
1077
+ cancelled = true;
1078
+ };
1079
+ }, [watchedValues]);
1080
+ }
1081
+
1082
+ // src/renderer.tsx
1083
+ var import_jsx_runtime6 = require("react/jsx-runtime");
1084
+ var EMPTY_ELEMENT_PROPS = {};
1085
+ var ElementErrorBoundary = class extends import_react10.default.Component {
957
1086
  constructor(props) {
958
1087
  super(props);
959
1088
  this.state = { hasError: false };
@@ -961,16 +1090,16 @@ var ElementErrorBoundary = class extends import_react6.default.Component {
961
1090
  static getDerivedStateFromError() {
962
1091
  return { hasError: true };
963
1092
  }
964
- componentDidCatch(error, info) {
965
- reportRenderError(
1093
+ componentDidCatch(error) {
1094
+ reportElementFailure(
966
1095
  this.props.registry,
967
1096
  this.props.elementType,
968
- error,
969
- info.componentStack
1097
+ this.props.elementKey,
1098
+ error
970
1099
  );
971
1100
  }
972
- componentDidUpdate(previous) {
973
- if (this.state.hasError && previous.resetKey !== this.props.resetKey) {
1101
+ componentDidUpdate(previous, previousState) {
1102
+ if (this.state.hasError && previousState.hasError && previous.resetKey !== this.props.resetKey) {
974
1103
  this.setState({ hasError: false });
975
1104
  }
976
1105
  }
@@ -982,15 +1111,15 @@ var ElementErrorBoundary = class extends import_react6.default.Component {
982
1111
  }
983
1112
  };
984
1113
  var EMPTY_FUNCTIONS = {};
985
- var FunctionsContext = import_react6.default.createContext(EMPTY_FUNCTIONS);
1114
+ var FunctionsContext = import_react10.default.createContext(EMPTY_FUNCTIONS);
986
1115
  function useFunctions() {
987
- return import_react6.default.useContext(FunctionsContext);
1116
+ return import_react10.default.useContext(FunctionsContext);
988
1117
  }
989
- var DirectivesContext = import_react6.default.createContext(
1118
+ var DirectivesContext = import_react10.default.createContext(
990
1119
  void 0
991
1120
  );
992
1121
  function useDirectives() {
993
- return import_react6.default.useContext(DirectivesContext);
1122
+ return import_react10.default.useContext(DirectivesContext);
994
1123
  }
995
1124
  function stabilizeRecord(value, ref) {
996
1125
  const previous = ref.current;
@@ -1021,11 +1150,12 @@ function structurallyEqual(previous, next) {
1021
1150
  const previousRecord = previous;
1022
1151
  const nextRecord = next;
1023
1152
  const keys = Object.keys(nextRecord);
1024
- if (previousIsArray && previous.length !== next.length || keys.length !== Object.keys(previousRecord).length) {
1153
+ const previousKeys = Object.keys(previousRecord);
1154
+ if (previousIsArray && previous.length !== next.length || keys.length !== previousKeys.length) {
1025
1155
  return false;
1026
1156
  }
1027
1157
  return keys.every(
1028
- (key) => Object.prototype.hasOwnProperty.call(previousRecord, key) && structurallyEqual(previousRecord[key], nextRecord[key])
1158
+ (key, index) => previousKeys[index] === key && structurallyEqual(previousRecord[key], nextRecord[key])
1029
1159
  );
1030
1160
  }
1031
1161
  function snapshotStructuralValue(value) {
@@ -1063,8 +1193,8 @@ function shareResolvedValue(previous, next) {
1063
1193
  return unchanged ? previous : shared;
1064
1194
  }
1065
1195
  function useElementSignatures(spec) {
1066
- const entriesRef = (0, import_react6.useRef)({});
1067
- const versionRef = (0, import_react6.useRef)(0);
1196
+ const entriesRef = (0, import_react10.useRef)({});
1197
+ const versionRef = (0, import_react10.useRef)(0);
1068
1198
  if (!spec) return {};
1069
1199
  const previous = entriesRef.current;
1070
1200
  const next = {};
@@ -1131,7 +1261,7 @@ function useElementSignatures(spec) {
1131
1261
  entriesRef.current = next;
1132
1262
  return signatures;
1133
1263
  }
1134
- var CatalogComponentBoundary = import_react6.default.memo(
1264
+ var CatalogComponentBoundary = import_react10.default.memo(
1135
1265
  function CatalogComponentBoundary2({
1136
1266
  Component,
1137
1267
  element,
@@ -1158,9 +1288,9 @@ var CatalogComponentBoundary = import_react6.default.memo(
1158
1288
  (previous, next) => previous.Component === next.Component && previous.signature === next.signature && previous.execute === next.execute && previous.actionContext?.item === next.actionContext?.item && previous.actionContext?.index === next.actionContext?.index && previous.actionContext?.basePath === next.actionContext?.basePath && previous.functions === next.functions && previous.directives === next.directives && previous.element.props === next.element.props && previous.bindings === next.bindings && previous.loading === next.loading
1159
1289
  );
1160
1290
  function useDevtoolsActive() {
1161
- return import_react6.default.useSyncExternalStore(
1162
- import_core6.subscribeDevtoolsActive,
1163
- import_core6.isDevtoolsActive,
1291
+ return import_react10.default.useSyncExternalStore(
1292
+ import_core9.subscribeDevtoolsActive,
1293
+ import_core9.isDevtoolsActive,
1164
1294
  () => false
1165
1295
  );
1166
1296
  }
@@ -1171,7 +1301,8 @@ function ReactiveElementRenderer({
1171
1301
  registry,
1172
1302
  loading,
1173
1303
  fallback,
1174
- signatures
1304
+ signatures,
1305
+ isRoot
1175
1306
  }) {
1176
1307
  const devtoolsActive = useDevtoolsActive();
1177
1308
  const repeatScope = useRepeatScope();
@@ -1180,7 +1311,12 @@ function ReactiveElementRenderer({
1180
1311
  const { getSnapshot, state: watchState } = useStateStore();
1181
1312
  const functions = useFunctions();
1182
1313
  const directives = useDirectives();
1183
- const fullCtx = (0, import_react6.useMemo)(() => {
1314
+ const { failsAt, reportChain } = useElementFailures(
1315
+ registry,
1316
+ elementKey,
1317
+ element.type
1318
+ );
1319
+ const fullCtx = (0, import_react10.useMemo)(() => {
1184
1320
  const base = repeatScope ? {
1185
1321
  ...ctx,
1186
1322
  repeatItem: repeatScope.item,
@@ -1191,11 +1327,16 @@ function ReactiveElementRenderer({
1191
1327
  base.directives = directives;
1192
1328
  return base;
1193
1329
  }, [ctx, repeatScope, functions, directives]);
1194
- const repeatVisibility = element.repeat !== void 0 && repeatScope == null ? (0, import_core6.splitRepeatVisibility)(element.visible) : { container: element.visible, itemFilter: void 0 };
1330
+ const repeatVisibility = element.repeat !== void 0 && repeatScope == null ? (0, import_core9.splitRepeatVisibility)(element.visible) : { container: element.visible, itemFilter: void 0 };
1195
1331
  const repeatItemFilter = repeatVisibility.itemFilter;
1196
- const isVisible = repeatVisibility.container === void 0 ? true : (0, import_core6.evaluateVisibility)(repeatVisibility.container, fullCtx);
1332
+ const isVisible = repeatVisibility.container === void 0 ? true : failsAt(
1333
+ "visible",
1334
+ import_core9.evaluateVisibility,
1335
+ repeatVisibility.container,
1336
+ fullCtx
1337
+ );
1197
1338
  const onBindings = element.on;
1198
- const emit = (0, import_react6.useCallback)(
1339
+ const emit = (0, import_react10.useCallback)(
1199
1340
  async (eventName) => {
1200
1341
  const binding = onBindings?.[eventName];
1201
1342
  if (!binding) return;
@@ -1205,24 +1346,19 @@ function ReactiveElementRenderer({
1205
1346
  for (const b of actionBindings) {
1206
1347
  action = b.action;
1207
1348
  await execute(
1208
- (0, import_core6.resolveBindingParams)(b, {
1349
+ (0, import_core9.resolveBindingParams)(b, {
1209
1350
  ...fullCtx,
1210
1351
  stateModel: getSnapshot()
1211
1352
  })
1212
1353
  );
1213
1354
  }
1214
1355
  } catch (err) {
1215
- (0, import_core6.reportActionError)(
1216
- (0, import_core6.getRenderErrorHandler)(registry),
1217
- err,
1218
- action,
1219
- "event"
1220
- );
1356
+ reportChain(err, action, "action");
1221
1357
  }
1222
1358
  },
1223
- [onBindings, execute, fullCtx, getSnapshot, registry]
1359
+ [onBindings, execute, fullCtx, getSnapshot, reportChain]
1224
1360
  );
1225
- const on = (0, import_react6.useCallback)(
1361
+ const on = (0, import_react10.useCallback)(
1226
1362
  (eventName) => {
1227
1363
  const binding = onBindings?.[eventName];
1228
1364
  if (!binding) {
@@ -1239,90 +1375,43 @@ function ReactiveElementRenderer({
1239
1375
  },
1240
1376
  [onBindings, emit]
1241
1377
  );
1242
- const watchConfig = element.watch;
1243
- const watchDepsRef = (0, import_react6.useRef)({
1244
- watchConfig,
1245
- fullCtx,
1246
- execute,
1247
- getSnapshot,
1248
- registry
1249
- });
1250
- watchDepsRef.current = {
1251
- watchConfig,
1252
- fullCtx,
1253
- execute,
1254
- getSnapshot,
1255
- registry
1256
- };
1257
- const prevWatchValues = (0, import_react6.useRef)(null);
1258
- const stableWatchRef = (0, import_react6.useRef)(void 0);
1259
- const stableBindingsRef = (0, import_react6.useRef)(
1378
+ const stableBindingsRef = (0, import_react10.useRef)(
1260
1379
  void 0
1261
1380
  );
1262
- const stableResolvedPropsRef = (0, import_react6.useRef)({});
1263
- const watchedValues = (0, import_react6.useMemo)(() => {
1264
- const values = (0, import_core6.readWatchedValues)(
1265
- watchConfig,
1266
- watchState,
1267
- stableWatchRef.current
1268
- );
1269
- stableWatchRef.current = values;
1270
- return values;
1271
- }, [watchConfig, watchState]);
1272
- (0, import_react6.useEffect)(() => {
1273
- const prev = prevWatchValues.current;
1274
- prevWatchValues.current = watchedValues ?? null;
1275
- const paths = (0, import_core6.changedWatchPaths)(watchedValues, prev ?? void 0);
1276
- const watch = watchDepsRef.current.watchConfig;
1277
- if (!watch || paths.length === 0) return;
1278
- let cancelled = false;
1279
- let action = "";
1280
- void (0, import_core6.runWatchBindings)(
1281
- watch,
1282
- paths,
1283
- async (b) => {
1284
- action = b.action;
1285
- const { execute: execute2, fullCtx: fullCtx2, getSnapshot: getSnapshot2 } = watchDepsRef.current;
1286
- await execute2(
1287
- (0, import_core6.resolveBindingParams)(b, {
1288
- ...fullCtx2,
1289
- stateModel: getSnapshot2()
1290
- })
1291
- );
1292
- },
1293
- () => cancelled
1294
- ).catch((err) => {
1295
- (0, import_core6.reportActionError)(
1296
- (0, import_core6.getRenderErrorHandler)(watchDepsRef.current.registry),
1297
- err,
1298
- action,
1299
- "watch"
1300
- );
1301
- });
1302
- return () => {
1303
- cancelled = true;
1304
- };
1305
- }, [watchedValues]);
1381
+ const stableResolvedPropsRef = (0, import_react10.useRef)({});
1382
+ useElementWatch(
1383
+ element.watch,
1384
+ watchState,
1385
+ (b) => execute(
1386
+ (0, import_core9.resolveBindingParams)(b, { ...fullCtx, stateModel: getSnapshot() })
1387
+ ),
1388
+ (error, action) => reportChain(error, action, "watch")
1389
+ );
1390
+ useUnknownTypeWarning(
1391
+ registry,
1392
+ fallback,
1393
+ isVisible ? element.type : void 0,
1394
+ elementKey
1395
+ );
1306
1396
  if (!isVisible) {
1307
1397
  return null;
1308
1398
  }
1309
1399
  const rawProps = element.props ?? EMPTY_ELEMENT_PROPS;
1310
1400
  const elementBindings = stabilizeRecord(
1311
- (0, import_core6.resolveBindings)(rawProps, fullCtx),
1401
+ failsAt("props", import_core9.resolveBindings, rawProps, fullCtx),
1312
1402
  stableBindingsRef
1313
1403
  );
1314
1404
  const resolvedProps = shareResolvedValue(
1315
1405
  stableResolvedPropsRef.current,
1316
- (0, import_core6.resolveElementProps)(rawProps, fullCtx)
1406
+ failsAt("props", import_core9.resolveElementProps, rawProps, fullCtx)
1317
1407
  );
1318
1408
  stableResolvedPropsRef.current = resolvedProps;
1319
1409
  const resolvedElement = resolvedProps !== element.props ? { ...element, props: resolvedProps } : element;
1320
- const Component = (0, import_core6.getRegistryComponent)(registry, resolvedElement.type) ?? fallback;
1410
+ const Component = (0, import_core9.getRegistryComponent)(registry, resolvedElement.type) ?? fallback;
1321
1411
  if (!Component) {
1322
- console.warn(`No renderer for component type: ${resolvedElement.type}`);
1323
1412
  return null;
1324
1413
  }
1325
- (0, import_core6.warnElementSlots)(registry, resolvedElement.type, resolvedElement.slots);
1414
+ (0, import_core9.warnElementSlots)(registry, resolvedElement.type, resolvedElement.slots);
1326
1415
  const renderChildKeys = (childKeys, slotName) => childKeys.map((childKey) => {
1327
1416
  const childElement = spec.elements[childKey];
1328
1417
  if (!childElement) {
@@ -1385,17 +1474,19 @@ function ReactiveElementRenderer({
1385
1474
  }
1386
1475
  );
1387
1476
  const tagged = devtoolsActive && elementKey ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { "data-jr-key": elementKey, style: { display: "contents" }, children: rendered }) : rendered;
1477
+ if (isRoot) return tagged;
1388
1478
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1389
1479
  ElementErrorBoundary,
1390
1480
  {
1391
1481
  elementType: resolvedElement.type,
1482
+ elementKey,
1392
1483
  registry,
1393
1484
  resetKey: signatures[elementKey ?? ""],
1394
1485
  children: tagged
1395
1486
  }
1396
1487
  );
1397
1488
  }
1398
- var ElementRenderer = import_react6.default.memo(
1489
+ var ElementRenderer = import_react10.default.memo(
1399
1490
  function ElementRenderer2(props) {
1400
1491
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ReactiveElementRenderer, { ...props });
1401
1492
  },
@@ -1414,7 +1505,7 @@ function RepeatChildren({
1414
1505
  const { ctx } = useVisibility();
1415
1506
  const parentScope = useRepeatScope();
1416
1507
  const repeat = element.repeat;
1417
- const statePath = (0, import_core6.resolveRepeatStatePath)(
1508
+ const statePath = (0, import_core9.resolveRepeatStatePath)(
1418
1509
  repeat.statePath,
1419
1510
  parentScope?.basePath
1420
1511
  );
@@ -1424,13 +1515,21 @@ function RepeatChildren({
1424
1515
  );
1425
1516
  return null;
1426
1517
  }
1427
- const items = (0, import_core6.getByPath)(state, statePath) ?? [];
1518
+ const raw = (0, import_core9.getByPath)(state, statePath);
1519
+ const items = Array.isArray(raw) ? raw : [];
1428
1520
  const entries = items.map((itemValue, index) => ({ itemValue, index })).filter(
1429
- ({ itemValue, index }) => itemFilter === void 0 || (0, import_core6.evaluateVisibility)(itemFilter, {
1430
- ...ctx,
1431
- repeatItem: itemValue,
1432
- repeatIndex: index
1433
- })
1521
+ ({ itemValue, index }) => itemFilter === void 0 || failsAs(
1522
+ "visible",
1523
+ void 0,
1524
+ element.type,
1525
+ import_core9.evaluateVisibility,
1526
+ itemFilter,
1527
+ {
1528
+ ...ctx,
1529
+ repeatItem: itemValue,
1530
+ repeatIndex: index
1531
+ }
1532
+ )
1434
1533
  );
1435
1534
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.Fragment, { children: entries.map(({ itemValue, index }) => {
1436
1535
  const key = repeat.key && typeof itemValue === "object" && itemValue !== null ? String(
@@ -1441,7 +1540,7 @@ function RepeatChildren({
1441
1540
  {
1442
1541
  item: itemValue,
1443
1542
  index,
1444
- basePath: (0, import_core6.resolveRepeatItemStatePath)(statePath, index),
1543
+ basePath: (0, import_core9.resolveRepeatItemStatePath)(statePath, index),
1445
1544
  children: element.children?.map((childKey) => {
1446
1545
  const childElement = spec.elements[childKey];
1447
1546
  if (!childElement) {
@@ -1480,6 +1579,7 @@ function Renderer({
1480
1579
  }) {
1481
1580
  const rendererRegistry = useRenderErrorRegistry(registry, onRenderError);
1482
1581
  const signatures = useElementSignatures(spec);
1582
+ useMissingRootWarning(spec, loading);
1483
1583
  if (!spec || !spec.root) {
1484
1584
  return null;
1485
1585
  }
@@ -1488,15 +1588,25 @@ function Renderer({
1488
1588
  return null;
1489
1589
  }
1490
1590
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1491
- ElementRenderer,
1591
+ RootErrorBoundary,
1492
1592
  {
1493
- element: rootElement,
1494
- elementKey: spec.root,
1495
- spec,
1496
1593
  registry: rendererRegistry,
1497
- loading,
1498
- fallback,
1499
- signatures
1594
+ rootKey: spec.root,
1595
+ type: rootElement.type,
1596
+ resetKey: `${spec.root}:${signatures[spec.root]}`,
1597
+ children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1598
+ ElementRenderer,
1599
+ {
1600
+ element: rootElement,
1601
+ elementKey: spec.root,
1602
+ spec,
1603
+ registry: rendererRegistry,
1604
+ loading,
1605
+ fallback,
1606
+ signatures,
1607
+ isRoot: true
1608
+ }
1609
+ )
1500
1610
  }
1501
1611
  );
1502
1612
  }
@@ -1512,8 +1622,8 @@ function JSONUIProvider({
1512
1622
  onStateChange,
1513
1623
  children
1514
1624
  }) {
1515
- const directiveRegistry = (0, import_react6.useMemo)(
1516
- () => directives ? (0, import_core6.createDirectiveRegistry)(directives) : void 0,
1625
+ const directiveRegistry = (0, import_react10.useMemo)(
1626
+ () => directives ? (0, import_core9.createDirectiveRegistry)(directives) : void 0,
1517
1627
  [directives]
1518
1628
  );
1519
1629
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
@@ -1544,7 +1654,7 @@ function ConfirmationDialogManager() {
1544
1654
  );
1545
1655
  }
1546
1656
  function defineRegistry(catalog, options) {
1547
- const registry = (0, import_core6.createComponentRegistry)(
1657
+ const registry = (0, import_core9.createComponentRegistry)(
1548
1658
  options.components
1549
1659
  );
1550
1660
  if (options.components) {
@@ -1570,7 +1680,7 @@ function defineRegistry(catalog, options) {
1570
1680
  };
1571
1681
  }
1572
1682
  }
1573
- (0, import_core6.setCatalogSlotMetadata)(registry, catalog);
1683
+ (0, import_core9.setCatalogSlotMetadata)(registry, catalog);
1574
1684
  const actionMap = options.actions ? Object.entries(options.actions) : [];
1575
1685
  const handlers = (getSetState, getState) => {
1576
1686
  const result = {};
@@ -1594,13 +1704,13 @@ function defineRegistry(catalog, options) {
1594
1704
  }
1595
1705
  };
1596
1706
  if (options.onRenderError) {
1597
- (0, import_core6.setRenderErrorHandler)(registry, options.onRenderError);
1707
+ (0, import_core9.setRenderErrorHandler)(registry, options.onRenderError);
1598
1708
  }
1599
1709
  return { registry, handlers, executeAction: executeAction2 };
1600
1710
  }
1601
1711
  function createRenderer(catalog, components) {
1602
1712
  const registry = components;
1603
- (0, import_core6.setCatalogSlotMetadata)(registry, catalog);
1713
+ (0, import_core9.setCatalogSlotMetadata)(registry, catalog);
1604
1714
  return function CatalogRenderer({
1605
1715
  spec,
1606
1716
  store,
@@ -1613,8 +1723,8 @@ function createRenderer(catalog, components) {
1613
1723
  fallback,
1614
1724
  onRenderError
1615
1725
  }) {
1616
- const directiveRegistry = (0, import_react6.useMemo)(
1617
- () => directives ? (0, import_core6.createDirectiveRegistry)(directives) : void 0,
1726
+ const directiveRegistry = (0, import_react10.useMemo)(
1727
+ () => directives ? (0, import_core9.createDirectiveRegistry)(directives) : void 0,
1618
1728
  [directives]
1619
1729
  );
1620
1730
  const rendererRegistry = useRenderErrorRegistry(registry, onRenderError);
@@ -1651,8 +1761,8 @@ function createRenderer(catalog, components) {
1651
1761
  }
1652
1762
 
1653
1763
  // src/hooks.ts
1654
- var import_react7 = require("react");
1655
- var import_core7 = require("@xmachines/json-render-core");
1764
+ var import_react11 = require("react");
1765
+ var import_core10 = require("@xmachines/json-render-core");
1656
1766
  function parseLine(line) {
1657
1767
  try {
1658
1768
  const trimmed = line.trim();
@@ -1687,7 +1797,7 @@ function setSpecValue(newSpec, path, value) {
1687
1797
  if (path.startsWith("/state/")) {
1688
1798
  if (!newSpec.state) newSpec.state = {};
1689
1799
  const statePath = path.slice("/state".length);
1690
- (0, import_core7.setByPath)(newSpec.state, statePath, value);
1800
+ (0, import_core10.setByPath)(newSpec.state, statePath, value);
1691
1801
  return;
1692
1802
  }
1693
1803
  if (path.startsWith("/elements/")) {
@@ -1701,7 +1811,7 @@ function setSpecValue(newSpec, path, value) {
1701
1811
  if (element) {
1702
1812
  const propPath = "/" + pathParts.slice(1).join("/");
1703
1813
  const newElement = { ...element };
1704
- (0, import_core7.setByPath)(
1814
+ (0, import_core10.setByPath)(
1705
1815
  newElement,
1706
1816
  propPath,
1707
1817
  value
@@ -1718,7 +1828,7 @@ function removeSpecValue(newSpec, path) {
1718
1828
  }
1719
1829
  if (path.startsWith("/state/") && newSpec.state) {
1720
1830
  const statePath = path.slice("/state".length);
1721
- (0, import_core7.removeByPath)(newSpec.state, statePath);
1831
+ (0, import_core10.removeByPath)(newSpec.state, statePath);
1722
1832
  return;
1723
1833
  }
1724
1834
  if (path.startsWith("/elements/")) {
@@ -1733,7 +1843,7 @@ function removeSpecValue(newSpec, path) {
1733
1843
  if (element) {
1734
1844
  const propPath = "/" + pathParts.slice(1).join("/");
1735
1845
  const newElement = { ...element };
1736
- (0, import_core7.removeByPath)(
1846
+ (0, import_core10.removeByPath)(
1737
1847
  newElement,
1738
1848
  propPath
1739
1849
  );
@@ -1747,9 +1857,9 @@ function getSpecValue(spec, path) {
1747
1857
  if (path === "/state") return spec.state;
1748
1858
  if (path.startsWith("/state/") && spec.state) {
1749
1859
  const statePath = path.slice("/state".length);
1750
- return (0, import_core7.getByPath)(spec.state, statePath);
1860
+ return (0, import_core10.getByPath)(spec.state, statePath);
1751
1861
  }
1752
- return (0, import_core7.getByPath)(spec, path);
1862
+ return (0, import_core10.getByPath)(spec, path);
1753
1863
  }
1754
1864
  function applyPatch(spec, patch) {
1755
1865
  const newSpec = {
@@ -1791,21 +1901,21 @@ function useUIStream({
1791
1901
  onComplete,
1792
1902
  onError
1793
1903
  }) {
1794
- const [spec, setSpec] = (0, import_react7.useState)(null);
1795
- const [isStreaming, setIsStreaming] = (0, import_react7.useState)(false);
1796
- const [error, setError] = (0, import_react7.useState)(null);
1797
- const [usage, setUsage] = (0, import_react7.useState)(null);
1798
- const [rawLines, setRawLines] = (0, import_react7.useState)([]);
1799
- const abortControllerRef = (0, import_react7.useRef)(null);
1800
- const onCompleteRef = (0, import_react7.useRef)(onComplete);
1904
+ const [spec, setSpec] = (0, import_react11.useState)(null);
1905
+ const [isStreaming, setIsStreaming] = (0, import_react11.useState)(false);
1906
+ const [error, setError] = (0, import_react11.useState)(null);
1907
+ const [usage, setUsage] = (0, import_react11.useState)(null);
1908
+ const [rawLines, setRawLines] = (0, import_react11.useState)([]);
1909
+ const abortControllerRef = (0, import_react11.useRef)(null);
1910
+ const onCompleteRef = (0, import_react11.useRef)(onComplete);
1801
1911
  onCompleteRef.current = onComplete;
1802
- const onErrorRef = (0, import_react7.useRef)(onError);
1912
+ const onErrorRef = (0, import_react11.useRef)(onError);
1803
1913
  onErrorRef.current = onError;
1804
- const clear = (0, import_react7.useCallback)(() => {
1914
+ const clear = (0, import_react11.useCallback)(() => {
1805
1915
  setSpec(null);
1806
1916
  setError(null);
1807
1917
  }, []);
1808
- const send = (0, import_react7.useCallback)(
1918
+ const send = (0, import_react11.useCallback)(
1809
1919
  async (prompt, context) => {
1810
1920
  abortControllerRef.current?.abort();
1811
1921
  abortControllerRef.current = new AbortController();
@@ -1893,7 +2003,7 @@ function useUIStream({
1893
2003
  },
1894
2004
  [api]
1895
2005
  );
1896
- (0, import_react7.useEffect)(() => {
2006
+ (0, import_react11.useEffect)(() => {
1897
2007
  return () => {
1898
2008
  abortControllerRef.current?.abort();
1899
2009
  };
@@ -1936,7 +2046,7 @@ function flatToTree(elements) {
1936
2046
  }
1937
2047
  function useBoundProp(propValue, bindingPath) {
1938
2048
  const { set } = useStateStore();
1939
- const setValue = (0, import_react7.useCallback)(
2049
+ const setValue = (0, import_react11.useCallback)(
1940
2050
  (value) => {
1941
2051
  if (bindingPath) set(bindingPath, value);
1942
2052
  },
@@ -1961,18 +2071,18 @@ function buildSpecFromParts(parts) {
1961
2071
  const spec = { root: "", elements: {} };
1962
2072
  let hasSpec = false;
1963
2073
  for (const part of parts) {
1964
- if (part.type === import_core7.SPEC_DATA_PART_TYPE) {
2074
+ if (part.type === import_core10.SPEC_DATA_PART_TYPE) {
1965
2075
  if (!isSpecDataPart(part.data)) continue;
1966
2076
  const payload = part.data;
1967
2077
  if (payload.type === "patch") {
1968
2078
  hasSpec = true;
1969
- (0, import_core7.applySpecPatch)(spec, payload.patch);
2079
+ (0, import_core10.applySpecPatch)(spec, payload.patch);
1970
2080
  } else if (payload.type === "flat") {
1971
2081
  hasSpec = true;
1972
2082
  Object.assign(spec, payload.spec);
1973
2083
  } else if (payload.type === "nested") {
1974
2084
  hasSpec = true;
1975
- const flat = (0, import_core7.nestedToFlat)(payload.spec);
2085
+ const flat = (0, import_core10.nestedToFlat)(payload.spec);
1976
2086
  Object.assign(spec, flat);
1977
2087
  }
1978
2088
  }
@@ -1985,8 +2095,8 @@ function getTextFromParts(parts) {
1985
2095
  ).map((p) => p.text.trim()).filter(Boolean).join("\n\n");
1986
2096
  }
1987
2097
  function useJsonRenderMessage(parts) {
1988
- const prevPartsRef = (0, import_react7.useRef)([]);
1989
- const prevResultRef = (0, import_react7.useRef)({
2098
+ const prevPartsRef = (0, import_react11.useRef)([]);
2099
+ const prevResultRef = (0, import_react11.useRef)({
1990
2100
  spec: null,
1991
2101
  text: ""
1992
2102
  });
@@ -2015,21 +2125,21 @@ function useChatUI({
2015
2125
  onComplete,
2016
2126
  onError
2017
2127
  }) {
2018
- const [messages, setMessages] = (0, import_react7.useState)([]);
2019
- const [isStreaming, setIsStreaming] = (0, import_react7.useState)(false);
2020
- const [error, setError] = (0, import_react7.useState)(null);
2021
- const abortControllerRef = (0, import_react7.useRef)(null);
2022
- const messagesRef = (0, import_react7.useRef)(messages);
2128
+ const [messages, setMessages] = (0, import_react11.useState)([]);
2129
+ const [isStreaming, setIsStreaming] = (0, import_react11.useState)(false);
2130
+ const [error, setError] = (0, import_react11.useState)(null);
2131
+ const abortControllerRef = (0, import_react11.useRef)(null);
2132
+ const messagesRef = (0, import_react11.useRef)(messages);
2023
2133
  messagesRef.current = messages;
2024
- const onCompleteRef = (0, import_react7.useRef)(onComplete);
2134
+ const onCompleteRef = (0, import_react11.useRef)(onComplete);
2025
2135
  onCompleteRef.current = onComplete;
2026
- const onErrorRef = (0, import_react7.useRef)(onError);
2136
+ const onErrorRef = (0, import_react11.useRef)(onError);
2027
2137
  onErrorRef.current = onError;
2028
- const clear = (0, import_react7.useCallback)(() => {
2138
+ const clear = (0, import_react11.useCallback)(() => {
2029
2139
  setMessages([]);
2030
2140
  setError(null);
2031
2141
  }, []);
2032
- const send = (0, import_react7.useCallback)(
2142
+ const send = (0, import_react11.useCallback)(
2033
2143
  async (text) => {
2034
2144
  if (!text.trim()) return;
2035
2145
  abortControllerRef.current?.abort();
@@ -2085,10 +2195,10 @@ function useChatUI({
2085
2195
  throw new Error("No response body");
2086
2196
  }
2087
2197
  const decoder = new TextDecoder();
2088
- const parser = (0, import_core7.createMixedStreamParser)({
2198
+ const parser = (0, import_core10.createMixedStreamParser)({
2089
2199
  onPatch(patch) {
2090
2200
  hasSpec = true;
2091
- (0, import_core7.applySpecPatch)(currentSpec, patch);
2201
+ (0, import_core10.applySpecPatch)(currentSpec, patch);
2092
2202
  setMessages(
2093
2203
  (prev) => prev.map(
2094
2204
  (m) => m.id === assistantId ? {
@@ -2144,7 +2254,7 @@ function useChatUI({
2144
2254
  },
2145
2255
  [api]
2146
2256
  );
2147
- (0, import_react7.useEffect)(() => {
2257
+ (0, import_react11.useEffect)(() => {
2148
2258
  return () => {
2149
2259
  abortControllerRef.current?.abort();
2150
2260
  };