@xmachines/json-render-core 0.19.0-xm.3 → 0.20.0-xm.2

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.mjs CHANGED
@@ -20,8 +20,10 @@ import {
20
20
  pipeJsonRender,
21
21
  removeByPath,
22
22
  resolveDynamicValue,
23
+ resolveRepeatItemStatePath,
24
+ resolveRepeatStatePath,
23
25
  setByPath
24
- } from "./chunk-AFLK3Q4T.mjs";
26
+ } from "./chunk-7V7ZCHEJ.mjs";
25
27
 
26
28
  // src/visibility.ts
27
29
  import { z } from "zod";
@@ -64,6 +66,53 @@ var VisibilityConditionSchema = z.lazy(
64
66
  z.object({ $or: z.array(VisibilityConditionSchema) })
65
67
  ])
66
68
  );
69
+ var StrictSingleConditionSchema = z.union([
70
+ z.strictObject({ $state: z.string(), ...comparisonOps }),
71
+ z.strictObject({ $item: z.string(), ...comparisonOps }),
72
+ z.strictObject({ $index: z.literal(true), ...comparisonOps })
73
+ ]);
74
+ function conditionUsesItemScope(condition) {
75
+ if (condition === void 0 || typeof condition === "boolean") return false;
76
+ if (Array.isArray(condition)) return condition.some(conditionUsesItemScope);
77
+ if (typeof condition !== "object" || condition === null) return false;
78
+ if ("$item" in condition || "$index" in condition) return true;
79
+ if ("$and" in condition)
80
+ return condition.$and.some(
81
+ conditionUsesItemScope
82
+ );
83
+ if ("$or" in condition)
84
+ return condition.$or.some(
85
+ conditionUsesItemScope
86
+ );
87
+ return false;
88
+ }
89
+ function splitRepeatVisibility(condition) {
90
+ if (condition === void 0 || !conditionUsesItemScope(condition)) {
91
+ return { container: condition, itemFilter: void 0 };
92
+ }
93
+ const partition = (parts) => {
94
+ const container = parts.filter((part) => !conditionUsesItemScope(part));
95
+ const item = parts.filter((part) => conditionUsesItemScope(part));
96
+ return {
97
+ container: container.length > 0 ? { $and: container } : void 0,
98
+ itemFilter: item.length > 0 ? { $and: item } : void 0
99
+ };
100
+ };
101
+ if (Array.isArray(condition)) return partition(condition);
102
+ if (typeof condition === "object" && condition !== null && "$and" in condition) {
103
+ return partition(condition.$and);
104
+ }
105
+ return { container: void 0, itemFilter: condition };
106
+ }
107
+ var VisibilityConditionStrictSchema = z.lazy(
108
+ () => z.union([
109
+ z.boolean(),
110
+ StrictSingleConditionSchema,
111
+ z.array(StrictSingleConditionSchema),
112
+ z.strictObject({ $and: z.array(VisibilityConditionStrictSchema) }),
113
+ z.strictObject({ $or: z.array(VisibilityConditionStrictSchema) })
114
+ ])
115
+ );
67
116
  function resolveComparisonValue(value, ctx) {
68
117
  if (typeof value === "object" && value !== null) {
69
118
  if ("$state" in value && typeof value.$state === "string") {
@@ -473,11 +522,17 @@ var ActionConfirmSchema = z2.object({
473
522
  var ActionOnSuccessSchema = z2.union([
474
523
  z2.object({ navigate: z2.string() }),
475
524
  z2.object({ set: z2.record(z2.string(), z2.unknown()) }),
476
- z2.object({ action: z2.string() })
525
+ z2.object({
526
+ action: z2.string(),
527
+ params: z2.record(z2.string(), DynamicValueSchema).optional()
528
+ })
477
529
  ]);
478
530
  var ActionOnErrorSchema = z2.union([
479
531
  z2.object({ set: z2.record(z2.string(), z2.unknown()) }),
480
- z2.object({ action: z2.string() })
532
+ z2.object({
533
+ action: z2.string(),
534
+ params: z2.record(z2.string(), DynamicValueSchema).optional()
535
+ })
481
536
  ]);
482
537
  var ActionBindingSchema = z2.object({
483
538
  action: z2.string(),
@@ -529,7 +584,7 @@ async function executeAction(ctx) {
529
584
  setState(path, value);
530
585
  }
531
586
  } else if ("action" in action2.onSuccess && executeAction2) {
532
- await executeAction2(action2.onSuccess.action);
587
+ await executeAction2(action2.onSuccess);
533
588
  }
534
589
  }
535
590
  } catch (error) {
@@ -540,7 +595,7 @@ async function executeAction(ctx) {
540
595
  setState(path, resolvedValue);
541
596
  }
542
597
  } else if ("action" in action2.onError && executeAction2) {
543
- await executeAction2(action2.onError.action);
598
+ await executeAction2(action2.onError);
544
599
  }
545
600
  } else {
546
601
  throw error;
@@ -889,6 +944,38 @@ function validateSpec(spec, options = {}) {
889
944
  }
890
945
  }
891
946
  }
947
+ if (element.slots) {
948
+ for (const [slotName, childKeys] of Object.entries(element.slots)) {
949
+ for (const childKey of childKeys) {
950
+ if (!spec.elements[childKey]) {
951
+ issues.push({
952
+ severity: "error",
953
+ message: `Element "${key}" references child "${childKey}" in slot "${slotName}" which does not exist in the elements map.`,
954
+ elementKey: key,
955
+ code: "missing_child"
956
+ });
957
+ }
958
+ }
959
+ }
960
+ }
961
+ if (element.repeat !== void 0) {
962
+ if (!element.children || element.children.length === 0) {
963
+ issues.push({
964
+ severity: "error",
965
+ message: `Element "${key}" has "repeat" but no children. The repeated template must be a child element: add a child that renders one item (it may read fields with {"$item": "field"}).`,
966
+ elementKey: key,
967
+ code: "repeat_without_children"
968
+ });
969
+ }
970
+ }
971
+ if (element.visible !== void 0 && !VisibilityConditionStrictSchema.safeParse(element.visible).success) {
972
+ issues.push({
973
+ severity: "error",
974
+ message: `Element "${key}" has an invalid "visible" condition: ${JSON.stringify(element.visible)}. Valid forms: true, false, {"$state":"/path","eq":value}, {"$item":"field","eq":value}, {"$index":true,"eq":n}, an array of those (AND), or {"$and":[...]} / {"$or":[...]}. Use exactly one of $state, $item, or $index per condition object.`,
975
+ elementKey: key,
976
+ code: "invalid_visible"
977
+ });
978
+ }
892
979
  const props = element.props;
893
980
  if (props && "visible" in props && props.visible !== void 0) {
894
981
  issues.push({
@@ -923,6 +1010,77 @@ function validateSpec(spec, options = {}) {
923
1010
  });
924
1011
  }
925
1012
  }
1013
+ const repeatValidatedKeys = /* @__PURE__ */ new Set();
1014
+ const repeatValidatedContexts = /* @__PURE__ */ new Set();
1015
+ const validateRepeatPaths = (key, repeatBasePath, sampleAvailable, ancestors) => {
1016
+ if (ancestors.has(key)) return;
1017
+ const element = spec.elements[key];
1018
+ if (!element) return;
1019
+ repeatValidatedKeys.add(key);
1020
+ const contextKey = `${key}\0${repeatBasePath ?? ""}\0${sampleAvailable}`;
1021
+ if (repeatValidatedContexts.has(contextKey)) return;
1022
+ repeatValidatedContexts.add(contextKey);
1023
+ let childRepeatBasePath = repeatBasePath;
1024
+ let childSampleAvailable = sampleAvailable;
1025
+ if (element.repeat !== void 0) {
1026
+ const statePath = resolveRepeatStatePath(
1027
+ element.repeat.statePath,
1028
+ repeatBasePath
1029
+ );
1030
+ const displayPath = typeof element.repeat.statePath === "string" ? element.repeat.statePath : JSON.stringify(element.repeat.statePath);
1031
+ if (statePath === void 0) {
1032
+ issues.push({
1033
+ severity: "error",
1034
+ message: `Element "${key}" uses relative repeat statePath ${displayPath} outside a repeat scope.`,
1035
+ elementKey: key,
1036
+ code: "repeat_item_outside_scope"
1037
+ });
1038
+ childRepeatBasePath = void 0;
1039
+ childSampleAvailable = false;
1040
+ } else {
1041
+ const canCheckSample = spec.state !== void 0 && (typeof element.repeat.statePath === "string" || sampleAvailable);
1042
+ const value = canCheckSample ? getByPath(spec.state, statePath) : void 0;
1043
+ if (canCheckSample && !Array.isArray(value)) {
1044
+ issues.push({
1045
+ severity: "error",
1046
+ message: `Element "${key}" repeats over "${statePath}" but state${value === void 0 ? " has no value there" : ` has a ${typeof value} there`}. Repeat statePath must reference an array in state; add sample items to state at that path.`,
1047
+ elementKey: key,
1048
+ code: "repeat_state_mismatch"
1049
+ });
1050
+ }
1051
+ childRepeatBasePath = resolveRepeatItemStatePath(statePath, 0);
1052
+ childSampleAvailable = canCheckSample && Array.isArray(value) && value.length > 0;
1053
+ }
1054
+ }
1055
+ const nextAncestors = new Set(ancestors);
1056
+ nextAncestors.add(key);
1057
+ for (const childKey of element.children ?? []) {
1058
+ validateRepeatPaths(
1059
+ childKey,
1060
+ childRepeatBasePath,
1061
+ childSampleAvailable,
1062
+ nextAncestors
1063
+ );
1064
+ }
1065
+ for (const childKeys of Object.values(element.slots ?? {})) {
1066
+ for (const childKey of childKeys) {
1067
+ validateRepeatPaths(
1068
+ childKey,
1069
+ repeatBasePath,
1070
+ sampleAvailable,
1071
+ nextAncestors
1072
+ );
1073
+ }
1074
+ }
1075
+ };
1076
+ if (spec.elements[spec.root]) {
1077
+ validateRepeatPaths(spec.root, void 0, true, /* @__PURE__ */ new Set());
1078
+ }
1079
+ for (const key of Object.keys(spec.elements)) {
1080
+ if (!repeatValidatedKeys.has(key)) {
1081
+ validateRepeatPaths(key, void 0, true, /* @__PURE__ */ new Set());
1082
+ }
1083
+ }
926
1084
  if (checkOrphans) {
927
1085
  const reachable = /* @__PURE__ */ new Set();
928
1086
  const walk = (key) => {
@@ -936,6 +1094,15 @@ function validateSpec(spec, options = {}) {
936
1094
  }
937
1095
  }
938
1096
  }
1097
+ if (el?.slots) {
1098
+ for (const childKeys of Object.values(el.slots)) {
1099
+ for (const childKey of childKeys) {
1100
+ if (spec.elements[childKey]) {
1101
+ walk(childKey);
1102
+ }
1103
+ }
1104
+ }
1105
+ }
939
1106
  };
940
1107
  if (spec.elements[spec.root]) {
941
1108
  walk(spec.root);
@@ -954,8 +1121,14 @@ function validateSpec(spec, options = {}) {
954
1121
  const hasErrors = issues.some((i) => i.severity === "error");
955
1122
  return { valid: !hasErrors, issues };
956
1123
  }
957
- function autoFixSpec(spec) {
958
- const fixes = [];
1124
+ function autoFixSpec(spec, options = {}) {
1125
+ const applyLossy = options.lossy !== false;
1126
+ const fixDetails = [];
1127
+ const fixes = {
1128
+ push(message, lossy = false) {
1129
+ fixDetails.push({ message, lossy });
1130
+ }
1131
+ };
959
1132
  const fixedElements = {};
960
1133
  for (const [key, element] of Object.entries(spec.elements)) {
961
1134
  const props = element.props;
@@ -1001,9 +1174,55 @@ function autoFixSpec(spec) {
1001
1174
  }
1002
1175
  fixedElements[key] = fixed;
1003
1176
  }
1177
+ if (applyLossy)
1178
+ for (const [key, element] of Object.entries(fixedElements)) {
1179
+ if (!element.children || element.children.length === 0) continue;
1180
+ const present = element.children.filter(
1181
+ (child) => child in fixedElements
1182
+ );
1183
+ if (present.length === element.children.length) continue;
1184
+ if (element.repeat !== void 0 && present.length === 0) {
1185
+ continue;
1186
+ }
1187
+ for (const child of element.children) {
1188
+ if (!(child in fixedElements)) {
1189
+ fixes.push(
1190
+ `Removed reference to undefined element "${child}" from children of "${key}".`,
1191
+ true
1192
+ );
1193
+ }
1194
+ }
1195
+ fixedElements[key] = { ...element, children: present };
1196
+ }
1197
+ if (applyLossy)
1198
+ for (const [key, element] of Object.entries(fixedElements)) {
1199
+ if (!element.slots) continue;
1200
+ let changed = false;
1201
+ const slots = Object.fromEntries(
1202
+ Object.entries(element.slots).map(([slotName, childKeys]) => {
1203
+ const present = childKeys.filter((child) => child in fixedElements);
1204
+ if (present.length !== childKeys.length) {
1205
+ changed = true;
1206
+ for (const child of childKeys) {
1207
+ if (!(child in fixedElements)) {
1208
+ fixes.push(
1209
+ `Removed reference to undefined element "${child}" from slot "${slotName}" of "${key}".`,
1210
+ true
1211
+ );
1212
+ }
1213
+ }
1214
+ }
1215
+ return [slotName, present];
1216
+ })
1217
+ );
1218
+ if (changed) {
1219
+ fixedElements[key] = { ...element, slots };
1220
+ }
1221
+ }
1004
1222
  return {
1005
1223
  spec: { root: spec.root, elements: fixedElements, state: spec.state },
1006
- fixes
1224
+ fixes: fixDetails.map((fix) => fix.message),
1225
+ fixDetails
1007
1226
  };
1008
1227
  }
1009
1228
  function formatSpecIssues(issues) {
@@ -1464,6 +1683,12 @@ function generatePrompt(catalog, options) {
1464
1683
  lines.push("Example output (each line is a separate JSON object):");
1465
1684
  lines.push("");
1466
1685
  const allComponents = catalog.data.components;
1686
+ const specDefinition = catalog.schema.definition.spec;
1687
+ const specShape = specDefinition.kind === "object" ? specDefinition.inner : void 0;
1688
+ const elementsDefinition = specShape?.elements;
1689
+ const elementDefinition = elementsDefinition?.kind === "record" ? elementsDefinition.inner : void 0;
1690
+ const elementShape = elementDefinition?.kind === "object" ? elementDefinition.inner : void 0;
1691
+ const supportsNamedSlots = elementShape?.slots !== void 0;
1467
1692
  const cn = catalog.componentNames;
1468
1693
  const comp1 = cn[0] || "Component";
1469
1694
  const comp2 = cn.length > 1 ? cn[1] : comp1;
@@ -1556,6 +1781,9 @@ Note: state patches appear right after the elements that use them, so the UI fil
1556
1781
  lines.push(
1557
1782
  'The element itself renders once (as the container), and its children are expanded once per array item. "statePath" is the state array path. "key" is an optional field name on each item for stable React keys.'
1558
1783
  );
1784
+ lines.push(
1785
+ 'For nested lists, an inner repeat can read an array from the enclosing item with { "statePath": { "$item": "field" } }. This form is valid only inside another repeat. Use an empty field to repeat over the enclosing item itself.'
1786
+ );
1559
1787
  lines.push(
1560
1788
  `Example: ${JSON.stringify({ type: comp1, props: comp1Props, repeat: { statePath: "/todos", key: "id" }, children: ["todo-item"] })}`
1561
1789
  );
@@ -1599,11 +1827,17 @@ Note: state patches appear right after the elements that use them, so the UI fil
1599
1827
  lines.push("");
1600
1828
  for (const [name, def] of Object.entries(components)) {
1601
1829
  const propsStr = def.props ? formatZodType(def.props) : "{}";
1602
- const hasChildren = def.slots && def.slots.length > 0;
1603
- const childrenStr = hasChildren ? " [accepts children]" : "";
1830
+ const slotNames = def.slots ?? [];
1831
+ const namedSlotNames = slotNames.filter((slot) => slot !== "default");
1832
+ const acceptsChildren = slotNames.includes("default");
1833
+ const slotsStr = supportsNamedSlots ? [
1834
+ acceptsChildren ? "accepts children" : "",
1835
+ namedSlotNames.length > 0 ? `slots: ${namedSlotNames.join(", ")}` : ""
1836
+ ].filter(Boolean).join("; ") : slotNames.length > 0 ? "accepts children" : "";
1837
+ const slotsSuffix = slotsStr ? ` [${slotsStr}]` : "";
1604
1838
  const eventsStr = def.events && def.events.length > 0 ? ` [events: ${def.events.join(", ")}]` : "";
1605
1839
  const descStr = def.description ? ` - ${def.description}` : "";
1606
- lines.push(`- ${name}: ${propsStr}${descStr}${childrenStr}${eventsStr}`);
1840
+ lines.push(`- ${name}: ${propsStr}${descStr}${slotsSuffix}${eventsStr}`);
1607
1841
  }
1608
1842
  lines.push("");
1609
1843
  }
@@ -2301,6 +2535,7 @@ export {
2301
2535
  ValidationCheckSchema,
2302
2536
  ValidationConfigSchema,
2303
2537
  VisibilityConditionSchema,
2538
+ VisibilityConditionStrictSchema,
2304
2539
  action,
2305
2540
  actionBinding,
2306
2541
  addByPath,
@@ -2313,6 +2548,7 @@ export {
2313
2548
  builtInValidationFunctions,
2314
2549
  check,
2315
2550
  compileSpecStream,
2551
+ conditionUsesItemScope,
2316
2552
  createDirectiveRegistry,
2317
2553
  createJsonRenderTransform,
2318
2554
  createMixedStreamParser,
@@ -2347,9 +2583,12 @@ export {
2347
2583
  resolveDynamicValue,
2348
2584
  resolveElementProps,
2349
2585
  resolvePropValue,
2586
+ resolveRepeatItemStatePath,
2587
+ resolveRepeatStatePath,
2350
2588
  runValidation,
2351
2589
  runValidationCheck,
2352
2590
  setByPath,
2591
+ splitRepeatVisibility,
2353
2592
  subscribeDevtoolsActive,
2354
2593
  validateSpec,
2355
2594
  visibility