@xmachines/json-render-core 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.
package/dist/index.js ADDED
@@ -0,0 +1,3056 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ActionBindingSchema: () => ActionBindingSchema,
24
+ ActionConfirmSchema: () => ActionConfirmSchema,
25
+ ActionOnErrorSchema: () => ActionOnErrorSchema,
26
+ ActionOnSuccessSchema: () => ActionOnSuccessSchema,
27
+ ActionSchema: () => ActionSchema,
28
+ DynamicBooleanSchema: () => DynamicBooleanSchema,
29
+ DynamicNumberSchema: () => DynamicNumberSchema,
30
+ DynamicStringSchema: () => DynamicStringSchema,
31
+ DynamicValueSchema: () => DynamicValueSchema,
32
+ SPEC_DATA_PART: () => SPEC_DATA_PART,
33
+ SPEC_DATA_PART_TYPE: () => SPEC_DATA_PART_TYPE,
34
+ ValidationCheckSchema: () => ValidationCheckSchema,
35
+ ValidationConfigSchema: () => ValidationConfigSchema,
36
+ VisibilityConditionSchema: () => VisibilityConditionSchema,
37
+ action: () => action,
38
+ actionBinding: () => actionBinding,
39
+ addByPath: () => addByPath,
40
+ applySpecPatch: () => applySpecPatch,
41
+ applySpecStreamPatch: () => applySpecStreamPatch,
42
+ autoFixSpec: () => autoFixSpec,
43
+ buildEditInstructions: () => buildEditInstructions,
44
+ buildEditUserPrompt: () => buildEditUserPrompt,
45
+ buildUserPrompt: () => buildUserPrompt,
46
+ builtInValidationFunctions: () => builtInValidationFunctions,
47
+ check: () => check,
48
+ compileSpecStream: () => compileSpecStream,
49
+ createDirectiveRegistry: () => createDirectiveRegistry,
50
+ createJsonRenderTransform: () => createJsonRenderTransform,
51
+ createMixedStreamParser: () => createMixedStreamParser,
52
+ createSpecStreamCompiler: () => createSpecStreamCompiler,
53
+ createStateStore: () => createStateStore,
54
+ deepMergeSpec: () => deepMergeSpec,
55
+ defineCatalog: () => defineCatalog,
56
+ defineDirective: () => defineDirective,
57
+ defineSchema: () => defineSchema,
58
+ diffToPatches: () => diffToPatches,
59
+ evaluateVisibility: () => evaluateVisibility,
60
+ executeAction: () => executeAction,
61
+ findDirective: () => findDirective,
62
+ findFormValue: () => findFormValue,
63
+ formatSpecIssues: () => formatSpecIssues,
64
+ getByPath: () => getByPath,
65
+ interpolateString: () => interpolateString,
66
+ isDevtoolsActive: () => isDevtoolsActive,
67
+ isNonEmptySpec: () => isNonEmptySpec,
68
+ markDevtoolsActive: () => markDevtoolsActive,
69
+ nestedToFlat: () => nestedToFlat,
70
+ nextActionDispatchId: () => nextActionDispatchId,
71
+ notifyActionDispatch: () => notifyActionDispatch,
72
+ notifyActionSettle: () => notifyActionSettle,
73
+ parseSpecStreamLine: () => parseSpecStreamLine,
74
+ pipeJsonRender: () => pipeJsonRender,
75
+ registerActionObserver: () => registerActionObserver,
76
+ removeByPath: () => removeByPath,
77
+ resolveAction: () => resolveAction,
78
+ resolveActionParam: () => resolveActionParam,
79
+ resolveBindings: () => resolveBindings,
80
+ resolveDynamicValue: () => resolveDynamicValue,
81
+ resolveElementProps: () => resolveElementProps,
82
+ resolvePropValue: () => resolvePropValue,
83
+ runValidation: () => runValidation,
84
+ runValidationCheck: () => runValidationCheck,
85
+ setByPath: () => setByPath,
86
+ subscribeDevtoolsActive: () => subscribeDevtoolsActive,
87
+ validateSpec: () => validateSpec,
88
+ visibility: () => visibility
89
+ });
90
+ module.exports = __toCommonJS(index_exports);
91
+
92
+ // src/types.ts
93
+ var import_zod = require("zod");
94
+ var DynamicValueSchema = import_zod.z.union([
95
+ import_zod.z.string(),
96
+ import_zod.z.number(),
97
+ import_zod.z.boolean(),
98
+ import_zod.z.null(),
99
+ import_zod.z.object({ $state: import_zod.z.string() })
100
+ ]);
101
+ var DynamicStringSchema = import_zod.z.union([
102
+ import_zod.z.string(),
103
+ import_zod.z.object({ $state: import_zod.z.string() })
104
+ ]);
105
+ var DynamicNumberSchema = import_zod.z.union([
106
+ import_zod.z.number(),
107
+ import_zod.z.object({ $state: import_zod.z.string() })
108
+ ]);
109
+ var DynamicBooleanSchema = import_zod.z.union([
110
+ import_zod.z.boolean(),
111
+ import_zod.z.object({ $state: import_zod.z.string() })
112
+ ]);
113
+ function resolveDynamicValue(value, stateModel) {
114
+ if (value === null || value === void 0) {
115
+ return void 0;
116
+ }
117
+ if (typeof value === "object" && "$state" in value) {
118
+ return getByPath(stateModel, value.$state);
119
+ }
120
+ return value;
121
+ }
122
+ function unescapeJsonPointer(token) {
123
+ return token.replace(/~1/g, "/").replace(/~0/g, "~");
124
+ }
125
+ function parseJsonPointer(path) {
126
+ const raw = path.startsWith("/") ? path.slice(1).split("/") : path.split("/");
127
+ return raw.map(unescapeJsonPointer);
128
+ }
129
+ function getByPath(obj, path) {
130
+ if (!path || path === "/") {
131
+ return obj;
132
+ }
133
+ const segments = parseJsonPointer(path);
134
+ let current = obj;
135
+ for (const segment of segments) {
136
+ if (current === null || current === void 0) {
137
+ return void 0;
138
+ }
139
+ if (Array.isArray(current)) {
140
+ const index = parseInt(segment, 10);
141
+ current = current[index];
142
+ } else if (typeof current === "object") {
143
+ current = current[segment];
144
+ } else {
145
+ return void 0;
146
+ }
147
+ }
148
+ return current;
149
+ }
150
+ function isNumericIndex(str) {
151
+ return /^\d+$/.test(str);
152
+ }
153
+ function setByPath(obj, path, value) {
154
+ const segments = parseJsonPointer(path);
155
+ if (segments.length === 0) return;
156
+ let current = obj;
157
+ for (let i = 0; i < segments.length - 1; i++) {
158
+ const segment = segments[i];
159
+ const nextSegment = segments[i + 1];
160
+ const nextIsNumeric = nextSegment !== void 0 && (isNumericIndex(nextSegment) || nextSegment === "-");
161
+ if (Array.isArray(current)) {
162
+ const index = parseInt(segment, 10);
163
+ if (current[index] === void 0 || typeof current[index] !== "object") {
164
+ current[index] = nextIsNumeric ? [] : {};
165
+ }
166
+ current = current[index];
167
+ } else {
168
+ if (!(segment in current) || typeof current[segment] !== "object") {
169
+ current[segment] = nextIsNumeric ? [] : {};
170
+ }
171
+ current = current[segment];
172
+ }
173
+ }
174
+ const lastSegment = segments[segments.length - 1];
175
+ if (Array.isArray(current)) {
176
+ if (lastSegment === "-") {
177
+ current.push(value);
178
+ } else {
179
+ const index = parseInt(lastSegment, 10);
180
+ current[index] = value;
181
+ }
182
+ } else {
183
+ current[lastSegment] = value;
184
+ }
185
+ }
186
+ function addByPath(obj, path, value) {
187
+ const segments = parseJsonPointer(path);
188
+ if (segments.length === 0) return;
189
+ let current = obj;
190
+ for (let i = 0; i < segments.length - 1; i++) {
191
+ const segment = segments[i];
192
+ const nextSegment = segments[i + 1];
193
+ const nextIsNumeric = nextSegment !== void 0 && (isNumericIndex(nextSegment) || nextSegment === "-");
194
+ if (Array.isArray(current)) {
195
+ const index = parseInt(segment, 10);
196
+ if (current[index] === void 0 || typeof current[index] !== "object") {
197
+ current[index] = nextIsNumeric ? [] : {};
198
+ }
199
+ current = current[index];
200
+ } else {
201
+ if (!(segment in current) || typeof current[segment] !== "object") {
202
+ current[segment] = nextIsNumeric ? [] : {};
203
+ }
204
+ current = current[segment];
205
+ }
206
+ }
207
+ const lastSegment = segments[segments.length - 1];
208
+ if (Array.isArray(current)) {
209
+ if (lastSegment === "-") {
210
+ current.push(value);
211
+ } else {
212
+ const index = parseInt(lastSegment, 10);
213
+ current.splice(index, 0, value);
214
+ }
215
+ } else {
216
+ current[lastSegment] = value;
217
+ }
218
+ }
219
+ function removeByPath(obj, path) {
220
+ const segments = parseJsonPointer(path);
221
+ if (segments.length === 0) return;
222
+ let current = obj;
223
+ for (let i = 0; i < segments.length - 1; i++) {
224
+ const segment = segments[i];
225
+ if (Array.isArray(current)) {
226
+ const index = parseInt(segment, 10);
227
+ if (current[index] === void 0 || typeof current[index] !== "object") {
228
+ return;
229
+ }
230
+ current = current[index];
231
+ } else {
232
+ if (!(segment in current) || typeof current[segment] !== "object") {
233
+ return;
234
+ }
235
+ current = current[segment];
236
+ }
237
+ }
238
+ const lastSegment = segments[segments.length - 1];
239
+ if (Array.isArray(current)) {
240
+ const index = parseInt(lastSegment, 10);
241
+ if (index >= 0 && index < current.length) {
242
+ current.splice(index, 1);
243
+ }
244
+ } else {
245
+ delete current[lastSegment];
246
+ }
247
+ }
248
+ function deepEqual(a, b) {
249
+ if (a === b) return true;
250
+ if (a === null || b === null) return false;
251
+ if (typeof a !== typeof b) return false;
252
+ if (typeof a !== "object") return false;
253
+ if (Array.isArray(a)) {
254
+ if (!Array.isArray(b)) return false;
255
+ if (a.length !== b.length) return false;
256
+ return a.every((item, i) => deepEqual(item, b[i]));
257
+ }
258
+ const aObj = a;
259
+ const bObj = b;
260
+ const aKeys = Object.keys(aObj);
261
+ const bKeys = Object.keys(bObj);
262
+ if (aKeys.length !== bKeys.length) return false;
263
+ return aKeys.every((key) => deepEqual(aObj[key], bObj[key]));
264
+ }
265
+ function findFormValue(fieldName, params, state) {
266
+ if (params?.[fieldName] !== void 0) {
267
+ const val = params[fieldName];
268
+ if (typeof val !== "string" || !val.includes(".")) {
269
+ return val;
270
+ }
271
+ }
272
+ if (params) {
273
+ for (const key of Object.keys(params)) {
274
+ if (key.endsWith(`.${fieldName}`)) {
275
+ const val = params[key];
276
+ if (typeof val !== "string" || !val.includes(".")) {
277
+ return val;
278
+ }
279
+ }
280
+ }
281
+ }
282
+ if (state) {
283
+ for (const key of Object.keys(state)) {
284
+ if (key === fieldName || key.endsWith(`.${fieldName}`)) {
285
+ return state[key];
286
+ }
287
+ }
288
+ const val = getByPath(state, fieldName);
289
+ if (val !== void 0) {
290
+ return val;
291
+ }
292
+ }
293
+ return void 0;
294
+ }
295
+ function parseSpecStreamLine(line) {
296
+ const trimmed = line.trim();
297
+ if (!trimmed || !trimmed.startsWith("{")) return null;
298
+ try {
299
+ const patch = JSON.parse(trimmed);
300
+ if (patch.op && patch.path !== void 0) {
301
+ return patch;
302
+ }
303
+ return null;
304
+ } catch {
305
+ return null;
306
+ }
307
+ }
308
+ function applySpecStreamPatch(obj, patch) {
309
+ switch (patch.op) {
310
+ case "add":
311
+ addByPath(obj, patch.path, patch.value);
312
+ break;
313
+ case "replace":
314
+ setByPath(obj, patch.path, patch.value);
315
+ break;
316
+ case "remove":
317
+ removeByPath(obj, patch.path);
318
+ break;
319
+ case "move": {
320
+ if (!patch.from) break;
321
+ const moveValue = getByPath(obj, patch.from);
322
+ removeByPath(obj, patch.from);
323
+ addByPath(obj, patch.path, moveValue);
324
+ break;
325
+ }
326
+ case "copy": {
327
+ if (!patch.from) break;
328
+ const copyValue = getByPath(obj, patch.from);
329
+ addByPath(obj, patch.path, copyValue);
330
+ break;
331
+ }
332
+ case "test": {
333
+ const actual = getByPath(obj, patch.path);
334
+ if (!deepEqual(actual, patch.value)) {
335
+ throw new Error(
336
+ `Test operation failed: value at "${patch.path}" does not match`
337
+ );
338
+ }
339
+ break;
340
+ }
341
+ }
342
+ return obj;
343
+ }
344
+ function applySpecPatch(spec, patch) {
345
+ applySpecStreamPatch(spec, patch);
346
+ return spec;
347
+ }
348
+ function nestedToFlat(nested) {
349
+ const elements = {};
350
+ let counter = 0;
351
+ function walk(node) {
352
+ const key = `el-${counter++}`;
353
+ const { type, props, children: rawChildren, ...rest } = node;
354
+ const childKeys = [];
355
+ if (Array.isArray(rawChildren)) {
356
+ for (const child of rawChildren) {
357
+ if (child && typeof child === "object" && "type" in child) {
358
+ childKeys.push(walk(child));
359
+ }
360
+ }
361
+ }
362
+ const element = {
363
+ type: type ?? "unknown",
364
+ props: props ?? {},
365
+ children: childKeys
366
+ };
367
+ for (const [k, v] of Object.entries(rest)) {
368
+ if (k !== "state" && v !== void 0) {
369
+ element[k] = v;
370
+ }
371
+ }
372
+ elements[key] = element;
373
+ return key;
374
+ }
375
+ const root = walk(nested);
376
+ const spec = { root, elements };
377
+ if (nested.state && typeof nested.state === "object" && !Array.isArray(nested.state)) {
378
+ spec.state = nested.state;
379
+ }
380
+ return spec;
381
+ }
382
+ function compileSpecStream(stream, initial = {}) {
383
+ const lines = stream.split("\n");
384
+ const result = { ...initial };
385
+ for (const line of lines) {
386
+ const patch = parseSpecStreamLine(line);
387
+ if (patch) {
388
+ applySpecStreamPatch(result, patch);
389
+ }
390
+ }
391
+ return result;
392
+ }
393
+ function createSpecStreamCompiler(initial = {}) {
394
+ let result = { ...initial };
395
+ let buffer = "";
396
+ const appliedPatches = [];
397
+ const processedLines = /* @__PURE__ */ new Set();
398
+ return {
399
+ push(chunk) {
400
+ buffer += chunk;
401
+ const newPatches = [];
402
+ const lines = buffer.split("\n");
403
+ buffer = lines.pop() || "";
404
+ for (const line of lines) {
405
+ const trimmed = line.trim();
406
+ if (!trimmed || processedLines.has(trimmed)) continue;
407
+ processedLines.add(trimmed);
408
+ const patch = parseSpecStreamLine(trimmed);
409
+ if (patch) {
410
+ applySpecStreamPatch(result, patch);
411
+ appliedPatches.push(patch);
412
+ newPatches.push(patch);
413
+ }
414
+ }
415
+ if (newPatches.length > 0) {
416
+ result = { ...result };
417
+ }
418
+ return { result, newPatches };
419
+ },
420
+ getResult() {
421
+ if (buffer.trim()) {
422
+ const patch = parseSpecStreamLine(buffer);
423
+ if (patch && !processedLines.has(buffer.trim())) {
424
+ processedLines.add(buffer.trim());
425
+ applySpecStreamPatch(result, patch);
426
+ appliedPatches.push(patch);
427
+ result = { ...result };
428
+ }
429
+ buffer = "";
430
+ }
431
+ return result;
432
+ },
433
+ getPatches() {
434
+ return [...appliedPatches];
435
+ },
436
+ reset(newInitial = {}) {
437
+ result = { ...newInitial };
438
+ buffer = "";
439
+ appliedPatches.length = 0;
440
+ processedLines.clear();
441
+ }
442
+ };
443
+ }
444
+ function createMixedStreamParser(callbacks) {
445
+ let buffer = "";
446
+ let inSpecFence = false;
447
+ function processLine(line) {
448
+ const trimmed = line.trim();
449
+ if (!inSpecFence && trimmed.startsWith("```spec")) {
450
+ inSpecFence = true;
451
+ return;
452
+ }
453
+ if (inSpecFence && trimmed === "```") {
454
+ inSpecFence = false;
455
+ return;
456
+ }
457
+ if (!trimmed) return;
458
+ if (inSpecFence) {
459
+ const patch2 = parseSpecStreamLine(trimmed);
460
+ if (patch2) {
461
+ callbacks.onPatch(patch2);
462
+ }
463
+ return;
464
+ }
465
+ const patch = parseSpecStreamLine(trimmed);
466
+ if (patch) {
467
+ callbacks.onPatch(patch);
468
+ } else {
469
+ callbacks.onText(line);
470
+ }
471
+ }
472
+ return {
473
+ push(chunk) {
474
+ buffer += chunk;
475
+ const lines = buffer.split("\n");
476
+ buffer = lines.pop() || "";
477
+ for (const line of lines) {
478
+ processLine(line);
479
+ }
480
+ },
481
+ flush() {
482
+ if (buffer.trim()) {
483
+ processLine(buffer);
484
+ }
485
+ buffer = "";
486
+ }
487
+ };
488
+ }
489
+ var SPEC_FENCE_OPEN = "```spec";
490
+ var SPEC_FENCE_CLOSE = "```";
491
+ function createJsonRenderTransform() {
492
+ let lineBuffer = "";
493
+ let currentTextId = "";
494
+ let buffering = false;
495
+ let inSpecFence = false;
496
+ let inTextBlock = false;
497
+ let textIdCounter = 0;
498
+ function closeTextBlock(controller) {
499
+ if (inTextBlock) {
500
+ controller.enqueue({ type: "text-end", id: currentTextId });
501
+ inTextBlock = false;
502
+ }
503
+ }
504
+ function ensureTextBlock(controller) {
505
+ if (!inTextBlock) {
506
+ textIdCounter++;
507
+ currentTextId = String(textIdCounter);
508
+ controller.enqueue({ type: "text-start", id: currentTextId });
509
+ inTextBlock = true;
510
+ }
511
+ }
512
+ function emitTextDelta(delta, controller) {
513
+ ensureTextBlock(controller);
514
+ controller.enqueue({ type: "text-delta", id: currentTextId, delta });
515
+ }
516
+ function emitPatch(patch, controller) {
517
+ closeTextBlock(controller);
518
+ controller.enqueue({
519
+ type: SPEC_DATA_PART_TYPE,
520
+ data: { type: "patch", patch }
521
+ });
522
+ }
523
+ function flushBuffer(controller) {
524
+ if (!lineBuffer) return;
525
+ const trimmed = lineBuffer.trim();
526
+ if (inSpecFence) {
527
+ if (trimmed) {
528
+ const patch = parseSpecStreamLine(trimmed);
529
+ if (patch) emitPatch(patch, controller);
530
+ }
531
+ lineBuffer = "";
532
+ buffering = false;
533
+ return;
534
+ }
535
+ if (trimmed) {
536
+ const patch = parseSpecStreamLine(trimmed);
537
+ if (patch) {
538
+ emitPatch(patch, controller);
539
+ } else {
540
+ emitTextDelta(lineBuffer, controller);
541
+ }
542
+ } else {
543
+ emitTextDelta(lineBuffer, controller);
544
+ }
545
+ lineBuffer = "";
546
+ buffering = false;
547
+ }
548
+ function processCompleteLine(line, controller) {
549
+ const trimmed = line.trim();
550
+ if (!inSpecFence && trimmed.startsWith(SPEC_FENCE_OPEN)) {
551
+ inSpecFence = true;
552
+ return;
553
+ }
554
+ if (inSpecFence && trimmed === SPEC_FENCE_CLOSE) {
555
+ inSpecFence = false;
556
+ return;
557
+ }
558
+ if (inSpecFence) {
559
+ if (trimmed) {
560
+ const patch2 = parseSpecStreamLine(trimmed);
561
+ if (patch2) emitPatch(patch2, controller);
562
+ }
563
+ return;
564
+ }
565
+ if (!trimmed) {
566
+ emitTextDelta("\n", controller);
567
+ return;
568
+ }
569
+ const patch = parseSpecStreamLine(trimmed);
570
+ if (patch) {
571
+ emitPatch(patch, controller);
572
+ } else {
573
+ emitTextDelta(line + "\n", controller);
574
+ }
575
+ }
576
+ return new TransformStream({
577
+ transform(chunk, controller) {
578
+ switch (chunk.type) {
579
+ case "text-start": {
580
+ const id = chunk.id;
581
+ const idNum = parseInt(id, 10);
582
+ if (!isNaN(idNum) && idNum >= textIdCounter) {
583
+ textIdCounter = idNum;
584
+ }
585
+ currentTextId = id;
586
+ inTextBlock = true;
587
+ controller.enqueue(chunk);
588
+ break;
589
+ }
590
+ case "text-delta": {
591
+ const delta = chunk;
592
+ const text = delta.delta;
593
+ for (let i = 0; i < text.length; i++) {
594
+ const ch = text.charAt(i);
595
+ if (ch === "\n") {
596
+ if (buffering) {
597
+ processCompleteLine(lineBuffer, controller);
598
+ lineBuffer = "";
599
+ buffering = false;
600
+ } else {
601
+ if (!inSpecFence) {
602
+ emitTextDelta("\n", controller);
603
+ }
604
+ }
605
+ } else if (lineBuffer.length === 0 && !buffering) {
606
+ if (inSpecFence || ch === "{" || ch === "`") {
607
+ buffering = true;
608
+ lineBuffer += ch;
609
+ } else {
610
+ emitTextDelta(ch, controller);
611
+ }
612
+ } else if (buffering) {
613
+ lineBuffer += ch;
614
+ } else {
615
+ emitTextDelta(ch, controller);
616
+ }
617
+ }
618
+ break;
619
+ }
620
+ case "text-end": {
621
+ flushBuffer(controller);
622
+ if (inTextBlock) {
623
+ controller.enqueue({ type: "text-end", id: currentTextId });
624
+ inTextBlock = false;
625
+ }
626
+ break;
627
+ }
628
+ default: {
629
+ controller.enqueue(chunk);
630
+ break;
631
+ }
632
+ }
633
+ },
634
+ flush(controller) {
635
+ flushBuffer(controller);
636
+ closeTextBlock(controller);
637
+ }
638
+ });
639
+ }
640
+ var SPEC_DATA_PART = "spec";
641
+ var SPEC_DATA_PART_TYPE = `data-${SPEC_DATA_PART}`;
642
+ function pipeJsonRender(stream) {
643
+ return stream.pipeThrough(
644
+ createJsonRenderTransform()
645
+ );
646
+ }
647
+
648
+ // src/state-store.ts
649
+ function immutableSetByPath(root, path, value) {
650
+ const segments = parseJsonPointer(path);
651
+ if (segments.length === 0) return root;
652
+ const result = { ...root };
653
+ let current = result;
654
+ for (let i = 0; i < segments.length - 1; i++) {
655
+ const seg = segments[i];
656
+ const child = current[seg];
657
+ if (Array.isArray(child)) {
658
+ current[seg] = [...child];
659
+ } else if (child !== null && typeof child === "object") {
660
+ current[seg] = { ...child };
661
+ } else {
662
+ const nextSeg = segments[i + 1];
663
+ current[seg] = nextSeg !== void 0 && /^\d+$/.test(nextSeg) ? [] : {};
664
+ }
665
+ current = current[seg];
666
+ }
667
+ const lastSeg = segments[segments.length - 1];
668
+ if (Array.isArray(current)) {
669
+ if (lastSeg === "-") {
670
+ current.push(value);
671
+ } else {
672
+ current[parseInt(lastSeg, 10)] = value;
673
+ }
674
+ } else {
675
+ current[lastSeg] = value;
676
+ }
677
+ return result;
678
+ }
679
+ function createStateStore(initialState = {}) {
680
+ let state = { ...initialState };
681
+ const listeners2 = /* @__PURE__ */ new Set();
682
+ function notify() {
683
+ for (const listener of listeners2) {
684
+ listener();
685
+ }
686
+ }
687
+ return {
688
+ get(path) {
689
+ return getByPath(state, path);
690
+ },
691
+ set(path, value) {
692
+ if (getByPath(state, path) === value) return;
693
+ state = immutableSetByPath(state, path, value);
694
+ notify();
695
+ },
696
+ update(updates) {
697
+ let changed = false;
698
+ let next = state;
699
+ for (const [path, value] of Object.entries(updates)) {
700
+ if (getByPath(next, path) !== value) {
701
+ next = immutableSetByPath(next, path, value);
702
+ changed = true;
703
+ }
704
+ }
705
+ if (!changed) return;
706
+ state = next;
707
+ notify();
708
+ },
709
+ getSnapshot() {
710
+ return state;
711
+ },
712
+ getServerSnapshot() {
713
+ return state;
714
+ },
715
+ subscribe(listener) {
716
+ listeners2.add(listener);
717
+ return () => {
718
+ listeners2.delete(listener);
719
+ };
720
+ }
721
+ };
722
+ }
723
+
724
+ // src/visibility.ts
725
+ var import_zod2 = require("zod");
726
+ var numericOrStateRef = import_zod2.z.union([
727
+ import_zod2.z.number(),
728
+ import_zod2.z.object({ $state: import_zod2.z.string() })
729
+ ]);
730
+ var comparisonOps = {
731
+ eq: import_zod2.z.unknown().optional(),
732
+ neq: import_zod2.z.unknown().optional(),
733
+ gt: numericOrStateRef.optional(),
734
+ gte: numericOrStateRef.optional(),
735
+ lt: numericOrStateRef.optional(),
736
+ lte: numericOrStateRef.optional(),
737
+ not: import_zod2.z.literal(true).optional()
738
+ };
739
+ var StateConditionSchema = import_zod2.z.object({
740
+ $state: import_zod2.z.string(),
741
+ ...comparisonOps
742
+ });
743
+ var ItemConditionSchema = import_zod2.z.object({
744
+ $item: import_zod2.z.string(),
745
+ ...comparisonOps
746
+ });
747
+ var IndexConditionSchema = import_zod2.z.object({
748
+ $index: import_zod2.z.literal(true),
749
+ ...comparisonOps
750
+ });
751
+ var SingleConditionSchema = import_zod2.z.union([
752
+ StateConditionSchema,
753
+ ItemConditionSchema,
754
+ IndexConditionSchema
755
+ ]);
756
+ var VisibilityConditionSchema = import_zod2.z.lazy(
757
+ () => import_zod2.z.union([
758
+ import_zod2.z.boolean(),
759
+ SingleConditionSchema,
760
+ import_zod2.z.array(SingleConditionSchema),
761
+ import_zod2.z.object({ $and: import_zod2.z.array(VisibilityConditionSchema) }),
762
+ import_zod2.z.object({ $or: import_zod2.z.array(VisibilityConditionSchema) })
763
+ ])
764
+ );
765
+ function resolveComparisonValue(value, ctx) {
766
+ if (typeof value === "object" && value !== null) {
767
+ if ("$state" in value && typeof value.$state === "string") {
768
+ return getByPath(ctx.stateModel, value.$state);
769
+ }
770
+ }
771
+ return value;
772
+ }
773
+ function isItemCondition(cond) {
774
+ return "$item" in cond;
775
+ }
776
+ function isIndexCondition(cond) {
777
+ return "$index" in cond;
778
+ }
779
+ function resolveConditionValue(cond, ctx) {
780
+ if (isIndexCondition(cond)) {
781
+ return ctx.repeatIndex;
782
+ }
783
+ if (isItemCondition(cond)) {
784
+ if (ctx.repeatItem === void 0) return void 0;
785
+ return cond.$item === "" ? ctx.repeatItem : getByPath(ctx.repeatItem, cond.$item);
786
+ }
787
+ return getByPath(ctx.stateModel, cond.$state);
788
+ }
789
+ function evaluateCondition(cond, ctx) {
790
+ const value = resolveConditionValue(cond, ctx);
791
+ let result;
792
+ if (cond.eq !== void 0) {
793
+ const rhs = resolveComparisonValue(cond.eq, ctx);
794
+ result = value === rhs;
795
+ } else if (cond.neq !== void 0) {
796
+ const rhs = resolveComparisonValue(cond.neq, ctx);
797
+ result = value !== rhs;
798
+ } else if (cond.gt !== void 0) {
799
+ const rhs = resolveComparisonValue(cond.gt, ctx);
800
+ result = typeof value === "number" && typeof rhs === "number" ? value > rhs : false;
801
+ } else if (cond.gte !== void 0) {
802
+ const rhs = resolveComparisonValue(cond.gte, ctx);
803
+ result = typeof value === "number" && typeof rhs === "number" ? value >= rhs : false;
804
+ } else if (cond.lt !== void 0) {
805
+ const rhs = resolveComparisonValue(cond.lt, ctx);
806
+ result = typeof value === "number" && typeof rhs === "number" ? value < rhs : false;
807
+ } else if (cond.lte !== void 0) {
808
+ const rhs = resolveComparisonValue(cond.lte, ctx);
809
+ result = typeof value === "number" && typeof rhs === "number" ? value <= rhs : false;
810
+ } else {
811
+ result = Boolean(value);
812
+ }
813
+ return cond.not === true ? !result : result;
814
+ }
815
+ function isAndCondition(condition) {
816
+ return typeof condition === "object" && condition !== null && !Array.isArray(condition) && "$and" in condition;
817
+ }
818
+ function isOrCondition(condition) {
819
+ return typeof condition === "object" && condition !== null && !Array.isArray(condition) && "$or" in condition;
820
+ }
821
+ function evaluateVisibility(condition, ctx) {
822
+ if (condition === void 0) {
823
+ return true;
824
+ }
825
+ if (typeof condition === "boolean") {
826
+ return condition;
827
+ }
828
+ if (Array.isArray(condition)) {
829
+ return condition.every((c) => evaluateCondition(c, ctx));
830
+ }
831
+ if (isAndCondition(condition)) {
832
+ return condition.$and.every((child) => evaluateVisibility(child, ctx));
833
+ }
834
+ if (isOrCondition(condition)) {
835
+ return condition.$or.some((child) => evaluateVisibility(child, ctx));
836
+ }
837
+ return evaluateCondition(condition, ctx);
838
+ }
839
+ var visibility = {
840
+ /** Always visible */
841
+ always: true,
842
+ /** Never visible */
843
+ never: false,
844
+ /** Visible when state path is truthy */
845
+ when: (path) => ({ $state: path }),
846
+ /** Visible when state path is falsy */
847
+ unless: (path) => ({ $state: path, not: true }),
848
+ /** Equality check */
849
+ eq: (path, value) => ({
850
+ $state: path,
851
+ eq: value
852
+ }),
853
+ /** Not equal check */
854
+ neq: (path, value) => ({
855
+ $state: path,
856
+ neq: value
857
+ }),
858
+ /** Greater than */
859
+ gt: (path, value) => ({
860
+ $state: path,
861
+ gt: value
862
+ }),
863
+ /** Greater than or equal */
864
+ gte: (path, value) => ({
865
+ $state: path,
866
+ gte: value
867
+ }),
868
+ /** Less than */
869
+ lt: (path, value) => ({
870
+ $state: path,
871
+ lt: value
872
+ }),
873
+ /** Less than or equal */
874
+ lte: (path, value) => ({
875
+ $state: path,
876
+ lte: value
877
+ }),
878
+ /** AND multiple conditions */
879
+ and: (...conditions) => ({
880
+ $and: conditions
881
+ }),
882
+ /** OR multiple conditions */
883
+ or: (...conditions) => ({
884
+ $or: conditions
885
+ })
886
+ };
887
+
888
+ // src/directives.ts
889
+ var BUILT_IN_KEYS = /* @__PURE__ */ new Set([
890
+ "$state",
891
+ "$item",
892
+ "$index",
893
+ "$bindState",
894
+ "$bindItem",
895
+ "$cond",
896
+ "$computed",
897
+ "$template"
898
+ ]);
899
+ function defineDirective(definition) {
900
+ if (!definition.name.startsWith("$")) {
901
+ throw new Error(
902
+ `Directive name must start with "$": got "${definition.name}"`
903
+ );
904
+ }
905
+ if (BUILT_IN_KEYS.has(definition.name)) {
906
+ throw new Error(
907
+ `Directive name "${definition.name}" conflicts with a built-in prop expression key`
908
+ );
909
+ }
910
+ return definition;
911
+ }
912
+ function createDirectiveRegistry(directives) {
913
+ const registry = /* @__PURE__ */ new Map();
914
+ for (const d of directives) {
915
+ registry.set(d.name, d);
916
+ }
917
+ return registry;
918
+ }
919
+ function findDirective(value, directives) {
920
+ if (!directives || directives.size === 0) return void 0;
921
+ let match;
922
+ for (const [key, def] of directives) {
923
+ if (key in value) {
924
+ if (match) {
925
+ throw new Error(
926
+ `Ambiguous directive: object has multiple directive keys ("${match.name}" and "${key}")`
927
+ );
928
+ }
929
+ match = def;
930
+ }
931
+ }
932
+ return match;
933
+ }
934
+
935
+ // src/props.ts
936
+ function isStateExpression(value) {
937
+ return typeof value === "object" && value !== null && "$state" in value && typeof value.$state === "string";
938
+ }
939
+ function isItemExpression(value) {
940
+ return typeof value === "object" && value !== null && "$item" in value && typeof value.$item === "string";
941
+ }
942
+ function isIndexExpression(value) {
943
+ return typeof value === "object" && value !== null && "$index" in value && value.$index === true;
944
+ }
945
+ function isBindStateExpression(value) {
946
+ return typeof value === "object" && value !== null && "$bindState" in value && typeof value.$bindState === "string";
947
+ }
948
+ function isBindItemExpression(value) {
949
+ return typeof value === "object" && value !== null && "$bindItem" in value && typeof value.$bindItem === "string";
950
+ }
951
+ function isCondExpression(value) {
952
+ return typeof value === "object" && value !== null && "$cond" in value && "$then" in value && "$else" in value;
953
+ }
954
+ function isComputedExpression(value) {
955
+ return typeof value === "object" && value !== null && "$computed" in value && typeof value.$computed === "string";
956
+ }
957
+ function isTemplateExpression(value) {
958
+ return typeof value === "object" && value !== null && "$template" in value && typeof value.$template === "string";
959
+ }
960
+ var WARNED_COMPUTED_MAX = 100;
961
+ var warnedComputedFns = /* @__PURE__ */ new Set();
962
+ function resolveBindItemPath(itemPath, ctx) {
963
+ if (ctx.repeatBasePath == null) {
964
+ console.warn(`$bindItem used outside repeat scope: "${itemPath}"`);
965
+ return void 0;
966
+ }
967
+ if (itemPath === "") return ctx.repeatBasePath;
968
+ return ctx.repeatBasePath + "/" + itemPath;
969
+ }
970
+ function resolvePropValue(value, ctx) {
971
+ if (value === null || value === void 0) {
972
+ return value;
973
+ }
974
+ if (isStateExpression(value)) {
975
+ return getByPath(ctx.stateModel, value.$state);
976
+ }
977
+ if (isItemExpression(value)) {
978
+ if (ctx.repeatItem === void 0) return void 0;
979
+ return value.$item === "" ? ctx.repeatItem : getByPath(ctx.repeatItem, value.$item);
980
+ }
981
+ if (isIndexExpression(value)) {
982
+ return ctx.repeatIndex;
983
+ }
984
+ if (isBindStateExpression(value)) {
985
+ return getByPath(ctx.stateModel, value.$bindState);
986
+ }
987
+ if (isBindItemExpression(value)) {
988
+ const resolvedPath = resolveBindItemPath(value.$bindItem, ctx);
989
+ if (resolvedPath === void 0) return void 0;
990
+ return getByPath(ctx.stateModel, resolvedPath);
991
+ }
992
+ if (isCondExpression(value)) {
993
+ const result = evaluateVisibility(value.$cond, ctx);
994
+ return resolvePropValue(result ? value.$then : value.$else, ctx);
995
+ }
996
+ if (isComputedExpression(value)) {
997
+ const fn = ctx.functions?.[value.$computed];
998
+ if (!fn) {
999
+ if (!warnedComputedFns.has(value.$computed)) {
1000
+ if (warnedComputedFns.size < WARNED_COMPUTED_MAX) {
1001
+ warnedComputedFns.add(value.$computed);
1002
+ }
1003
+ console.warn(`Unknown $computed function: "${value.$computed}"`);
1004
+ }
1005
+ return void 0;
1006
+ }
1007
+ const resolvedArgs = {};
1008
+ if (value.args) {
1009
+ for (const [key, arg] of Object.entries(value.args)) {
1010
+ resolvedArgs[key] = resolvePropValue(arg, ctx);
1011
+ }
1012
+ }
1013
+ return fn(resolvedArgs);
1014
+ }
1015
+ if (isTemplateExpression(value)) {
1016
+ return value.$template.replace(
1017
+ /\$\{([^}]+)\}/g,
1018
+ (_match, rawPath) => {
1019
+ if (rawPath.startsWith("/")) {
1020
+ const resolved2 = getByPath(ctx.stateModel, rawPath);
1021
+ return resolved2 != null ? String(resolved2) : "";
1022
+ }
1023
+ if (ctx.repeatItem !== void 0) {
1024
+ const fromItem = getByPath(ctx.repeatItem, rawPath);
1025
+ if (fromItem != null) return String(fromItem);
1026
+ }
1027
+ const resolved = getByPath(ctx.stateModel, "/" + rawPath);
1028
+ return resolved != null ? String(resolved) : "";
1029
+ }
1030
+ );
1031
+ }
1032
+ if (Array.isArray(value)) {
1033
+ return value.map((item) => resolvePropValue(item, ctx));
1034
+ }
1035
+ if (typeof value === "object") {
1036
+ const directive = findDirective(
1037
+ value,
1038
+ ctx.directives
1039
+ );
1040
+ if (directive) {
1041
+ return directive.resolve(value, ctx);
1042
+ }
1043
+ const resolved = {};
1044
+ for (const [key, val] of Object.entries(value)) {
1045
+ resolved[key] = resolvePropValue(val, ctx);
1046
+ }
1047
+ return resolved;
1048
+ }
1049
+ return value;
1050
+ }
1051
+ function resolveElementProps(props, ctx) {
1052
+ const resolved = {};
1053
+ for (const [key, value] of Object.entries(props)) {
1054
+ resolved[key] = resolvePropValue(value, ctx);
1055
+ }
1056
+ return resolved;
1057
+ }
1058
+ function resolveBindings(props, ctx) {
1059
+ let bindings;
1060
+ for (const [key, value] of Object.entries(props)) {
1061
+ if (isBindStateExpression(value)) {
1062
+ if (!bindings) bindings = {};
1063
+ bindings[key] = value.$bindState;
1064
+ } else if (isBindItemExpression(value)) {
1065
+ const resolved = resolveBindItemPath(value.$bindItem, ctx);
1066
+ if (resolved !== void 0) {
1067
+ if (!bindings) bindings = {};
1068
+ bindings[key] = resolved;
1069
+ }
1070
+ }
1071
+ }
1072
+ return bindings;
1073
+ }
1074
+ function resolveActionParam(value, ctx) {
1075
+ if (isItemExpression(value)) {
1076
+ return resolveBindItemPath(value.$item, ctx);
1077
+ }
1078
+ if (isIndexExpression(value)) {
1079
+ return ctx.repeatIndex;
1080
+ }
1081
+ return resolvePropValue(value, ctx);
1082
+ }
1083
+
1084
+ // src/action-observer.ts
1085
+ var observers = /* @__PURE__ */ new Set();
1086
+ function registerActionObserver(observer) {
1087
+ observers.add(observer);
1088
+ return () => {
1089
+ observers.delete(observer);
1090
+ };
1091
+ }
1092
+ function notifyActionDispatch(evt) {
1093
+ for (const o of observers) {
1094
+ const fn = o.onDispatch;
1095
+ if (!fn) continue;
1096
+ try {
1097
+ fn(evt);
1098
+ } catch (err) {
1099
+ if (process.env.NODE_ENV !== "production") {
1100
+ console.error(
1101
+ "[json-render] action observer threw in onDispatch:",
1102
+ err
1103
+ );
1104
+ }
1105
+ }
1106
+ }
1107
+ }
1108
+ function notifyActionSettle(evt) {
1109
+ for (const o of observers) {
1110
+ const fn = o.onSettle;
1111
+ if (!fn) continue;
1112
+ try {
1113
+ fn(evt);
1114
+ } catch (err) {
1115
+ if (process.env.NODE_ENV !== "production") {
1116
+ console.error("[json-render] action observer threw in onSettle:", err);
1117
+ }
1118
+ }
1119
+ }
1120
+ }
1121
+ var dispatchCounter = 0;
1122
+ function nextActionDispatchId() {
1123
+ dispatchCounter += 1;
1124
+ return `${Date.now()}-${dispatchCounter}`;
1125
+ }
1126
+
1127
+ // src/devtools-flag.ts
1128
+ var activeCount = 0;
1129
+ var listeners = /* @__PURE__ */ new Set();
1130
+ function markDevtoolsActive() {
1131
+ activeCount += 1;
1132
+ notifyDevtoolsActiveChange();
1133
+ let released = false;
1134
+ return () => {
1135
+ if (released) return;
1136
+ released = true;
1137
+ activeCount = Math.max(0, activeCount - 1);
1138
+ notifyDevtoolsActiveChange();
1139
+ };
1140
+ }
1141
+ function isDevtoolsActive() {
1142
+ return activeCount > 0;
1143
+ }
1144
+ function subscribeDevtoolsActive(listener) {
1145
+ listeners.add(listener);
1146
+ return () => {
1147
+ listeners.delete(listener);
1148
+ };
1149
+ }
1150
+ function notifyDevtoolsActiveChange() {
1151
+ for (const l of listeners) {
1152
+ try {
1153
+ l();
1154
+ } catch (err) {
1155
+ if (process.env.NODE_ENV !== "production") {
1156
+ console.error("[json-render] devtools-active listener threw:", err);
1157
+ }
1158
+ }
1159
+ }
1160
+ }
1161
+
1162
+ // src/actions.ts
1163
+ var import_zod3 = require("zod");
1164
+ var ActionConfirmSchema = import_zod3.z.object({
1165
+ title: import_zod3.z.string(),
1166
+ message: import_zod3.z.string(),
1167
+ confirmLabel: import_zod3.z.string().optional(),
1168
+ cancelLabel: import_zod3.z.string().optional(),
1169
+ variant: import_zod3.z.enum(["default", "danger"]).optional()
1170
+ });
1171
+ var ActionOnSuccessSchema = import_zod3.z.union([
1172
+ import_zod3.z.object({ navigate: import_zod3.z.string() }),
1173
+ import_zod3.z.object({ set: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()) }),
1174
+ import_zod3.z.object({ action: import_zod3.z.string() })
1175
+ ]);
1176
+ var ActionOnErrorSchema = import_zod3.z.union([
1177
+ import_zod3.z.object({ set: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()) }),
1178
+ import_zod3.z.object({ action: import_zod3.z.string() })
1179
+ ]);
1180
+ var ActionBindingSchema = import_zod3.z.object({
1181
+ action: import_zod3.z.string(),
1182
+ params: import_zod3.z.record(import_zod3.z.string(), DynamicValueSchema).optional(),
1183
+ confirm: ActionConfirmSchema.optional(),
1184
+ onSuccess: ActionOnSuccessSchema.optional(),
1185
+ onError: ActionOnErrorSchema.optional(),
1186
+ preventDefault: import_zod3.z.boolean().optional()
1187
+ });
1188
+ var ActionSchema = ActionBindingSchema;
1189
+ function resolveAction(binding, stateModel) {
1190
+ const resolvedParams = {};
1191
+ if (binding.params) {
1192
+ for (const [key, value] of Object.entries(binding.params)) {
1193
+ resolvedParams[key] = resolveDynamicValue(value, stateModel);
1194
+ }
1195
+ }
1196
+ let confirm = binding.confirm;
1197
+ if (confirm) {
1198
+ confirm = {
1199
+ ...confirm,
1200
+ message: interpolateString(confirm.message, stateModel),
1201
+ title: interpolateString(confirm.title, stateModel)
1202
+ };
1203
+ }
1204
+ return {
1205
+ action: binding.action,
1206
+ params: resolvedParams,
1207
+ confirm,
1208
+ onSuccess: binding.onSuccess,
1209
+ onError: binding.onError
1210
+ };
1211
+ }
1212
+ function interpolateString(template, stateModel) {
1213
+ return template.replace(/\$\{([^}]+)\}/g, (_, path) => {
1214
+ const value = resolveDynamicValue({ $state: path }, stateModel);
1215
+ return String(value ?? "");
1216
+ });
1217
+ }
1218
+ async function executeAction(ctx) {
1219
+ const { action: action2, handler, setState, navigate, executeAction: executeAction2 } = ctx;
1220
+ try {
1221
+ await handler(action2.params);
1222
+ if (action2.onSuccess) {
1223
+ if ("navigate" in action2.onSuccess && navigate) {
1224
+ navigate(action2.onSuccess.navigate);
1225
+ } else if ("set" in action2.onSuccess) {
1226
+ for (const [path, value] of Object.entries(action2.onSuccess.set)) {
1227
+ setState(path, value);
1228
+ }
1229
+ } else if ("action" in action2.onSuccess && executeAction2) {
1230
+ await executeAction2(action2.onSuccess.action);
1231
+ }
1232
+ }
1233
+ } catch (error) {
1234
+ if (action2.onError) {
1235
+ if ("set" in action2.onError) {
1236
+ for (const [path, value] of Object.entries(action2.onError.set)) {
1237
+ const resolvedValue = typeof value === "string" && value === "$error.message" ? error.message : value;
1238
+ setState(path, resolvedValue);
1239
+ }
1240
+ } else if ("action" in action2.onError && executeAction2) {
1241
+ await executeAction2(action2.onError.action);
1242
+ }
1243
+ } else {
1244
+ throw error;
1245
+ }
1246
+ }
1247
+ }
1248
+ var actionBinding = {
1249
+ /** Create a simple action binding */
1250
+ simple: (actionName, params) => ({
1251
+ action: actionName,
1252
+ params
1253
+ }),
1254
+ /** Create an action binding with confirmation */
1255
+ withConfirm: (actionName, confirm, params) => ({
1256
+ action: actionName,
1257
+ params,
1258
+ confirm
1259
+ }),
1260
+ /** Create an action binding with success handler */
1261
+ withSuccess: (actionName, onSuccess, params) => ({
1262
+ action: actionName,
1263
+ params,
1264
+ onSuccess
1265
+ })
1266
+ };
1267
+ var action = actionBinding;
1268
+
1269
+ // src/validation.ts
1270
+ var import_zod4 = require("zod");
1271
+ var ValidationCheckSchema = import_zod4.z.object({
1272
+ type: import_zod4.z.string(),
1273
+ args: import_zod4.z.record(import_zod4.z.string(), DynamicValueSchema).optional(),
1274
+ message: import_zod4.z.string()
1275
+ });
1276
+ var ValidationConfigSchema = import_zod4.z.object({
1277
+ checks: import_zod4.z.array(ValidationCheckSchema).optional(),
1278
+ validateOn: import_zod4.z.enum(["change", "blur", "submit"]).optional(),
1279
+ enabled: VisibilityConditionSchema.optional()
1280
+ });
1281
+ var matchesImpl = (value, args) => {
1282
+ const other = args?.other;
1283
+ return value === other;
1284
+ };
1285
+ var builtInValidationFunctions = {
1286
+ /**
1287
+ * Check if value is not null, undefined, or empty string
1288
+ */
1289
+ required: (value) => {
1290
+ if (value === null || value === void 0) return false;
1291
+ if (typeof value === "string") return value.trim().length > 0;
1292
+ if (Array.isArray(value)) return value.length > 0;
1293
+ return true;
1294
+ },
1295
+ /**
1296
+ * Check if value is a valid email address
1297
+ */
1298
+ email: (value) => {
1299
+ if (typeof value !== "string") return false;
1300
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
1301
+ },
1302
+ /**
1303
+ * Check minimum string length
1304
+ */
1305
+ minLength: (value, args) => {
1306
+ if (typeof value !== "string") return false;
1307
+ const min = args?.min;
1308
+ if (typeof min !== "number") return false;
1309
+ return value.length >= min;
1310
+ },
1311
+ /**
1312
+ * Check maximum string length
1313
+ */
1314
+ maxLength: (value, args) => {
1315
+ if (typeof value !== "string") return false;
1316
+ const max = args?.max;
1317
+ if (typeof max !== "number") return false;
1318
+ return value.length <= max;
1319
+ },
1320
+ /**
1321
+ * Check if string matches a regex pattern
1322
+ */
1323
+ pattern: (value, args) => {
1324
+ if (typeof value !== "string") return false;
1325
+ const pattern = args?.pattern;
1326
+ if (typeof pattern !== "string") return false;
1327
+ try {
1328
+ return new RegExp(pattern).test(value);
1329
+ } catch {
1330
+ return false;
1331
+ }
1332
+ },
1333
+ /**
1334
+ * Check minimum numeric value
1335
+ */
1336
+ min: (value, args) => {
1337
+ if (typeof value !== "number") return false;
1338
+ const min = args?.min;
1339
+ if (typeof min !== "number") return false;
1340
+ return value >= min;
1341
+ },
1342
+ /**
1343
+ * Check maximum numeric value
1344
+ */
1345
+ max: (value, args) => {
1346
+ if (typeof value !== "number") return false;
1347
+ const max = args?.max;
1348
+ if (typeof max !== "number") return false;
1349
+ return value <= max;
1350
+ },
1351
+ /**
1352
+ * Check if value is a number
1353
+ */
1354
+ numeric: (value) => {
1355
+ if (typeof value === "number") return !isNaN(value);
1356
+ if (typeof value === "string") return !isNaN(parseFloat(value));
1357
+ return false;
1358
+ },
1359
+ /**
1360
+ * Check if value is a valid URL
1361
+ */
1362
+ url: (value) => {
1363
+ if (typeof value !== "string") return false;
1364
+ try {
1365
+ new URL(value);
1366
+ return true;
1367
+ } catch {
1368
+ return false;
1369
+ }
1370
+ },
1371
+ /**
1372
+ * Check if value matches another field
1373
+ */
1374
+ matches: matchesImpl,
1375
+ /**
1376
+ * Alias for matches with a more descriptive name for cross-field equality
1377
+ */
1378
+ equalTo: matchesImpl,
1379
+ /**
1380
+ * Check if value is less than another field's value.
1381
+ * Supports numbers, strings (useful for ISO date comparison), and
1382
+ * cross-type numeric coercion (e.g. string "3" vs number 5).
1383
+ */
1384
+ lessThan: (value, args) => {
1385
+ const other = args?.other;
1386
+ if (value == null || other == null || value === "" || other === "")
1387
+ return false;
1388
+ if (typeof value === "number" && typeof other === "number")
1389
+ return value < other;
1390
+ if (typeof value === "string" && typeof other === "string")
1391
+ return value < other;
1392
+ const numVal = Number(value);
1393
+ const numOther = Number(other);
1394
+ if (!isNaN(numVal) && !isNaN(numOther)) return numVal < numOther;
1395
+ return false;
1396
+ },
1397
+ /**
1398
+ * Check if value is greater than another field's value.
1399
+ * Supports numbers, strings (useful for ISO date comparison), and
1400
+ * cross-type numeric coercion (e.g. string "7" vs number 5).
1401
+ */
1402
+ greaterThan: (value, args) => {
1403
+ const other = args?.other;
1404
+ if (value == null || other == null || value === "" || other === "")
1405
+ return false;
1406
+ if (typeof value === "number" && typeof other === "number")
1407
+ return value > other;
1408
+ if (typeof value === "string" && typeof other === "string")
1409
+ return value > other;
1410
+ const numVal = Number(value);
1411
+ const numOther = Number(other);
1412
+ if (!isNaN(numVal) && !isNaN(numOther)) return numVal > numOther;
1413
+ return false;
1414
+ },
1415
+ /**
1416
+ * Required only when a condition is met.
1417
+ * Uses JS truthiness: 0, false, "", null, and undefined are all
1418
+ * treated as "condition not met" (field not required), matching
1419
+ * the visibility system's bare-condition semantics.
1420
+ */
1421
+ requiredIf: (value, args) => {
1422
+ const condition = args?.field;
1423
+ if (!condition) return true;
1424
+ if (value === null || value === void 0) return false;
1425
+ if (typeof value === "string") return value.trim().length > 0;
1426
+ if (Array.isArray(value)) return value.length > 0;
1427
+ return true;
1428
+ }
1429
+ };
1430
+ function runValidationCheck(check2, ctx) {
1431
+ const { value, stateModel, customFunctions } = ctx;
1432
+ const resolvedArgs = {};
1433
+ if (check2.args) {
1434
+ for (const [key, argValue] of Object.entries(check2.args)) {
1435
+ resolvedArgs[key] = resolvePropValue(argValue, { stateModel });
1436
+ }
1437
+ }
1438
+ const validationFn = builtInValidationFunctions[check2.type] ?? customFunctions?.[check2.type];
1439
+ if (!validationFn) {
1440
+ console.warn(`Unknown validation function: ${check2.type}`);
1441
+ return {
1442
+ type: check2.type,
1443
+ valid: true,
1444
+ // Don't fail on unknown functions
1445
+ message: check2.message
1446
+ };
1447
+ }
1448
+ const valid = validationFn(value, resolvedArgs);
1449
+ return {
1450
+ type: check2.type,
1451
+ valid,
1452
+ message: check2.message
1453
+ };
1454
+ }
1455
+ function runValidation(config, ctx) {
1456
+ const checks = [];
1457
+ const errors = [];
1458
+ if (config.enabled) {
1459
+ const enabled = evaluateVisibility(config.enabled, {
1460
+ stateModel: ctx.stateModel
1461
+ });
1462
+ if (!enabled) {
1463
+ return { valid: true, errors: [], checks: [] };
1464
+ }
1465
+ }
1466
+ if (config.checks) {
1467
+ for (const check2 of config.checks) {
1468
+ const result = runValidationCheck(check2, ctx);
1469
+ checks.push(result);
1470
+ if (!result.valid) {
1471
+ errors.push(result.message);
1472
+ }
1473
+ }
1474
+ }
1475
+ return {
1476
+ valid: errors.length === 0,
1477
+ errors,
1478
+ checks
1479
+ };
1480
+ }
1481
+ var check = {
1482
+ required: (message = "This field is required") => ({
1483
+ type: "required",
1484
+ message
1485
+ }),
1486
+ email: (message = "Invalid email address") => ({
1487
+ type: "email",
1488
+ message
1489
+ }),
1490
+ minLength: (min, message) => ({
1491
+ type: "minLength",
1492
+ args: { min },
1493
+ message: message ?? `Must be at least ${min} characters`
1494
+ }),
1495
+ maxLength: (max, message) => ({
1496
+ type: "maxLength",
1497
+ args: { max },
1498
+ message: message ?? `Must be at most ${max} characters`
1499
+ }),
1500
+ pattern: (pattern, message = "Invalid format") => ({
1501
+ type: "pattern",
1502
+ args: { pattern },
1503
+ message
1504
+ }),
1505
+ min: (min, message) => ({
1506
+ type: "min",
1507
+ args: { min },
1508
+ message: message ?? `Must be at least ${min}`
1509
+ }),
1510
+ max: (max, message) => ({
1511
+ type: "max",
1512
+ args: { max },
1513
+ message: message ?? `Must be at most ${max}`
1514
+ }),
1515
+ url: (message = "Invalid URL") => ({
1516
+ type: "url",
1517
+ message
1518
+ }),
1519
+ numeric: (message = "Must be a number") => ({
1520
+ type: "numeric",
1521
+ message
1522
+ }),
1523
+ matches: (otherPath, message = "Fields must match") => ({
1524
+ type: "matches",
1525
+ args: { other: { $state: otherPath } },
1526
+ message
1527
+ }),
1528
+ equalTo: (otherPath, message = "Fields must match") => ({
1529
+ type: "equalTo",
1530
+ args: { other: { $state: otherPath } },
1531
+ message
1532
+ }),
1533
+ lessThan: (otherPath, message) => ({
1534
+ type: "lessThan",
1535
+ args: { other: { $state: otherPath } },
1536
+ message: message ?? "Must be less than the compared field"
1537
+ }),
1538
+ greaterThan: (otherPath, message) => ({
1539
+ type: "greaterThan",
1540
+ args: { other: { $state: otherPath } },
1541
+ message: message ?? "Must be greater than the compared field"
1542
+ }),
1543
+ requiredIf: (fieldPath, message = "This field is required") => ({
1544
+ type: "requiredIf",
1545
+ args: { field: { $state: fieldPath } },
1546
+ message
1547
+ })
1548
+ };
1549
+
1550
+ // src/spec-validator.ts
1551
+ function validateSpec(spec, options = {}) {
1552
+ const { checkOrphans = false } = options;
1553
+ const issues = [];
1554
+ if (!spec.root) {
1555
+ issues.push({
1556
+ severity: "error",
1557
+ message: "Spec has no root element defined.",
1558
+ code: "missing_root"
1559
+ });
1560
+ return { valid: false, issues };
1561
+ }
1562
+ if (!spec.elements[spec.root]) {
1563
+ issues.push({
1564
+ severity: "error",
1565
+ message: `Root element "${spec.root}" not found in elements map.`,
1566
+ code: "root_not_found"
1567
+ });
1568
+ }
1569
+ if (Object.keys(spec.elements).length === 0) {
1570
+ issues.push({
1571
+ severity: "error",
1572
+ message: "Spec has no elements.",
1573
+ code: "empty_spec"
1574
+ });
1575
+ return { valid: false, issues };
1576
+ }
1577
+ for (const [key, element] of Object.entries(spec.elements)) {
1578
+ if (element.children) {
1579
+ for (const childKey of element.children) {
1580
+ if (!spec.elements[childKey]) {
1581
+ issues.push({
1582
+ severity: "error",
1583
+ message: `Element "${key}" references child "${childKey}" which does not exist in the elements map.`,
1584
+ elementKey: key,
1585
+ code: "missing_child"
1586
+ });
1587
+ }
1588
+ }
1589
+ }
1590
+ const props = element.props;
1591
+ if (props && "visible" in props && props.visible !== void 0) {
1592
+ issues.push({
1593
+ severity: "error",
1594
+ message: `Element "${key}" has "visible" inside "props". It should be a top-level field on the element (sibling of type/props/children).`,
1595
+ elementKey: key,
1596
+ code: "visible_in_props"
1597
+ });
1598
+ }
1599
+ if (props && "on" in props && props.on !== void 0) {
1600
+ issues.push({
1601
+ severity: "error",
1602
+ message: `Element "${key}" has "on" inside "props". It should be a top-level field on the element (sibling of type/props/children).`,
1603
+ elementKey: key,
1604
+ code: "on_in_props"
1605
+ });
1606
+ }
1607
+ if (props && "repeat" in props && props.repeat !== void 0) {
1608
+ issues.push({
1609
+ severity: "error",
1610
+ message: `Element "${key}" has "repeat" inside "props". It should be a top-level field on the element (sibling of type/props/children).`,
1611
+ elementKey: key,
1612
+ code: "repeat_in_props"
1613
+ });
1614
+ }
1615
+ if (props && "watch" in props && props.watch !== void 0) {
1616
+ issues.push({
1617
+ severity: "error",
1618
+ message: `Element "${key}" has "watch" inside "props". It should be a top-level field on the element (sibling of type/props/children).`,
1619
+ elementKey: key,
1620
+ code: "watch_in_props"
1621
+ });
1622
+ }
1623
+ }
1624
+ if (checkOrphans) {
1625
+ const reachable = /* @__PURE__ */ new Set();
1626
+ const walk = (key) => {
1627
+ if (reachable.has(key)) return;
1628
+ reachable.add(key);
1629
+ const el = spec.elements[key];
1630
+ if (el?.children) {
1631
+ for (const childKey of el.children) {
1632
+ if (spec.elements[childKey]) {
1633
+ walk(childKey);
1634
+ }
1635
+ }
1636
+ }
1637
+ };
1638
+ if (spec.elements[spec.root]) {
1639
+ walk(spec.root);
1640
+ }
1641
+ for (const key of Object.keys(spec.elements)) {
1642
+ if (!reachable.has(key)) {
1643
+ issues.push({
1644
+ severity: "warning",
1645
+ message: `Element "${key}" is not reachable from root "${spec.root}".`,
1646
+ elementKey: key,
1647
+ code: "orphaned_element"
1648
+ });
1649
+ }
1650
+ }
1651
+ }
1652
+ const hasErrors = issues.some((i) => i.severity === "error");
1653
+ return { valid: !hasErrors, issues };
1654
+ }
1655
+ function autoFixSpec(spec) {
1656
+ const fixes = [];
1657
+ const fixedElements = {};
1658
+ for (const [key, element] of Object.entries(spec.elements)) {
1659
+ const props = element.props;
1660
+ let fixed = element;
1661
+ if (props && "visible" in props && props.visible !== void 0) {
1662
+ const { visible, ...restProps } = fixed.props;
1663
+ fixed = {
1664
+ ...fixed,
1665
+ props: restProps,
1666
+ visible
1667
+ };
1668
+ fixes.push(`Moved "visible" from props to element level on "${key}".`);
1669
+ }
1670
+ let currentProps = fixed.props;
1671
+ if (currentProps && "on" in currentProps && currentProps.on !== void 0) {
1672
+ const { on, ...restProps } = currentProps;
1673
+ fixed = {
1674
+ ...fixed,
1675
+ props: restProps,
1676
+ on
1677
+ };
1678
+ fixes.push(`Moved "on" from props to element level on "${key}".`);
1679
+ }
1680
+ currentProps = fixed.props;
1681
+ if (currentProps && "repeat" in currentProps && currentProps.repeat !== void 0) {
1682
+ const { repeat, ...restProps } = currentProps;
1683
+ fixed = {
1684
+ ...fixed,
1685
+ props: restProps,
1686
+ repeat
1687
+ };
1688
+ fixes.push(`Moved "repeat" from props to element level on "${key}".`);
1689
+ }
1690
+ currentProps = fixed.props;
1691
+ if (currentProps && "watch" in currentProps && currentProps.watch !== void 0) {
1692
+ const { watch, ...restProps } = currentProps;
1693
+ fixed = {
1694
+ ...fixed,
1695
+ props: restProps,
1696
+ watch
1697
+ };
1698
+ fixes.push(`Moved "watch" from props to element level on "${key}".`);
1699
+ }
1700
+ fixedElements[key] = fixed;
1701
+ }
1702
+ return {
1703
+ spec: { root: spec.root, elements: fixedElements, state: spec.state },
1704
+ fixes
1705
+ };
1706
+ }
1707
+ function formatSpecIssues(issues) {
1708
+ const errors = issues.filter((i) => i.severity === "error");
1709
+ if (errors.length === 0) return "";
1710
+ const lines = ["The generated UI spec has the following errors:"];
1711
+ for (const issue of errors) {
1712
+ lines.push(`- ${issue.message}`);
1713
+ }
1714
+ return lines.join("\n");
1715
+ }
1716
+
1717
+ // src/schema.ts
1718
+ var import_zod5 = require("zod");
1719
+
1720
+ // src/edit-modes.ts
1721
+ var DEFAULT_MODES = ["patch"];
1722
+ function normalizeModes(config) {
1723
+ if (!config?.modes?.length) return DEFAULT_MODES;
1724
+ return config.modes;
1725
+ }
1726
+ function jsonPatchInstructions() {
1727
+ return [
1728
+ "PATCH MODE (RFC 6902 JSON Patch):",
1729
+ "Output one JSON object per line. Each line is a patch operation.",
1730
+ '- Add: {"op":"add","path":"/elements/new-key","value":{...}}',
1731
+ '- Replace: {"op":"replace","path":"/elements/existing-key","value":{...}}',
1732
+ '- Remove: {"op":"remove","path":"/elements/old-key"}',
1733
+ "Only output patches for what needs to change."
1734
+ ].join("\n");
1735
+ }
1736
+ function jsonMergeInstructions() {
1737
+ return [
1738
+ "MERGE MODE (RFC 7396 JSON Merge Patch):",
1739
+ "Output a single JSON object on one line with __json_edit set to true.",
1740
+ "Include only the keys that changed. Unmentioned keys are preserved.",
1741
+ "Set a key to null to delete it.",
1742
+ "",
1743
+ "Example (update a title and add an element):",
1744
+ '{"__json_edit":true,"elements":{"main":{"props":{"title":"New Title"}},"new-el":{"type":"Card","props":{},"children":[]}}}',
1745
+ "",
1746
+ "Example (delete an element):",
1747
+ '{"__json_edit":true,"elements":{"old-widget":null}}'
1748
+ ].join("\n");
1749
+ }
1750
+ function jsonDiffInstructions() {
1751
+ return [
1752
+ "DIFF MODE (unified diff):",
1753
+ "Output a unified diff inside a ```diff code fence.",
1754
+ "The diff applies against the JSON-serialized current spec.",
1755
+ "",
1756
+ "Example:",
1757
+ "```diff",
1758
+ "--- a/spec.json",
1759
+ "+++ b/spec.json",
1760
+ "@@ -3,1 +3,1 @@",
1761
+ '- "title": "Login"',
1762
+ '+ "title": "Welcome Back"',
1763
+ "```"
1764
+ ].join("\n");
1765
+ }
1766
+ function yamlPatchInstructions() {
1767
+ return [
1768
+ "PATCH MODE (RFC 6902 JSON Patch):",
1769
+ "Output RFC 6902 JSON Patch lines inside a ```yaml-patch code fence.",
1770
+ "Each line is one JSON patch operation.",
1771
+ "",
1772
+ "Example:",
1773
+ "```yaml-patch",
1774
+ '{"op":"replace","path":"/elements/main/props/title","value":"New Title"}',
1775
+ '{"op":"add","path":"/elements/new-el","value":{"type":"Card","props":{},"children":[]}}',
1776
+ "```"
1777
+ ].join("\n");
1778
+ }
1779
+ function yamlMergeInstructions() {
1780
+ return [
1781
+ "MERGE MODE (RFC 7396 JSON Merge Patch):",
1782
+ "Output only the changed parts in a ```yaml-edit code fence.",
1783
+ "Uses deep merge semantics: only keys you include are updated. Unmentioned elements and props are preserved.",
1784
+ "Set a key to null to delete it.",
1785
+ "",
1786
+ "Example edit (update title, add a new element):",
1787
+ "```yaml-edit",
1788
+ "elements:",
1789
+ " main:",
1790
+ " props:",
1791
+ " title: Updated Title",
1792
+ " new-chart:",
1793
+ " type: Card",
1794
+ " props: {}",
1795
+ " children: []",
1796
+ "```",
1797
+ "",
1798
+ "Example deletion:",
1799
+ "```yaml-edit",
1800
+ "elements:",
1801
+ " old-widget: null",
1802
+ "```"
1803
+ ].join("\n");
1804
+ }
1805
+ function yamlDiffInstructions() {
1806
+ return [
1807
+ "DIFF MODE (unified diff):",
1808
+ "Output a unified diff inside a ```diff code fence.",
1809
+ "The diff applies against the YAML-serialized current spec.",
1810
+ "",
1811
+ "Example:",
1812
+ "```diff",
1813
+ "--- a/spec.yaml",
1814
+ "+++ b/spec.yaml",
1815
+ "@@ -6,1 +6,1 @@",
1816
+ "- title: Login",
1817
+ "+ title: Welcome Back",
1818
+ "```"
1819
+ ].join("\n");
1820
+ }
1821
+ function modeSelectionGuidance(modes) {
1822
+ if (modes.length === 1) return "";
1823
+ const parts = ["Choose the best edit strategy for the requested change:"];
1824
+ if (modes.includes("patch")) {
1825
+ parts.push("- PATCH: best for precise, targeted single-field updates");
1826
+ }
1827
+ if (modes.includes("merge")) {
1828
+ parts.push(
1829
+ "- MERGE: best for structural changes (add/remove elements, reparent children, update multiple props at once)"
1830
+ );
1831
+ }
1832
+ if (modes.includes("diff")) {
1833
+ parts.push(
1834
+ "- DIFF: best for small text-level changes when you can see the exact lines to change"
1835
+ );
1836
+ }
1837
+ return parts.join("\n");
1838
+ }
1839
+ function buildEditInstructions(config, format) {
1840
+ const modes = normalizeModes(config);
1841
+ const sections = [];
1842
+ sections.push("EDITING EXISTING SPECS:");
1843
+ sections.push("");
1844
+ const guidance = modeSelectionGuidance(modes);
1845
+ if (guidance) {
1846
+ sections.push(guidance);
1847
+ sections.push("");
1848
+ }
1849
+ for (const mode of modes) {
1850
+ if (format === "json") {
1851
+ switch (mode) {
1852
+ case "patch":
1853
+ sections.push(jsonPatchInstructions());
1854
+ break;
1855
+ case "merge":
1856
+ sections.push(jsonMergeInstructions());
1857
+ break;
1858
+ case "diff":
1859
+ sections.push(jsonDiffInstructions());
1860
+ break;
1861
+ }
1862
+ } else {
1863
+ switch (mode) {
1864
+ case "patch":
1865
+ sections.push(yamlPatchInstructions());
1866
+ break;
1867
+ case "merge":
1868
+ sections.push(yamlMergeInstructions());
1869
+ break;
1870
+ case "diff":
1871
+ sections.push(yamlDiffInstructions());
1872
+ break;
1873
+ }
1874
+ }
1875
+ sections.push("");
1876
+ }
1877
+ return sections.join("\n");
1878
+ }
1879
+ function addLineNumbers(text) {
1880
+ const lines = text.split("\n");
1881
+ const width = String(lines.length).length;
1882
+ return lines.map((line, i) => `${String(i + 1).padStart(width)}| ${line}`).join("\n");
1883
+ }
1884
+ function isNonEmptySpec(spec) {
1885
+ if (!spec || typeof spec !== "object") return false;
1886
+ const s = spec;
1887
+ return typeof s.root === "string" && typeof s.elements === "object" && s.elements !== null && Object.keys(s.elements).length > 0;
1888
+ }
1889
+ function buildEditUserPrompt(options) {
1890
+ const { prompt, currentSpec, config, format, maxPromptLength, serializer } = options;
1891
+ let userText = String(prompt || "");
1892
+ if (maxPromptLength !== void 0 && maxPromptLength > 0) {
1893
+ userText = userText.slice(0, maxPromptLength);
1894
+ }
1895
+ if (!isNonEmptySpec(currentSpec)) {
1896
+ return userText;
1897
+ }
1898
+ const modes = normalizeModes(config);
1899
+ const showLineNumbers = modes.includes("diff");
1900
+ const serialize = serializer ?? ((s) => JSON.stringify(s, null, 2));
1901
+ const specText = serialize(currentSpec);
1902
+ const parts = [];
1903
+ if (showLineNumbers) {
1904
+ parts.push("CURRENT UI STATE (line numbers for reference):");
1905
+ parts.push("```");
1906
+ parts.push(addLineNumbers(specText));
1907
+ parts.push("```");
1908
+ } else {
1909
+ parts.push(
1910
+ "CURRENT UI STATE (already loaded, DO NOT recreate existing elements):"
1911
+ );
1912
+ parts.push("```");
1913
+ parts.push(specText);
1914
+ parts.push("```");
1915
+ }
1916
+ parts.push("");
1917
+ parts.push(`USER REQUEST: ${userText}`);
1918
+ parts.push("");
1919
+ if (modes.length === 1) {
1920
+ const mode = modes[0];
1921
+ switch (mode) {
1922
+ case "patch":
1923
+ parts.push(
1924
+ format === "yaml" ? "Output ONLY the patches in a ```yaml-patch fence." : "Output ONLY the JSON Patch lines needed for the change."
1925
+ );
1926
+ break;
1927
+ case "merge":
1928
+ parts.push(
1929
+ format === "yaml" ? "Output ONLY the changes in a ```yaml-edit fence. Include only keys that need to change." : "Output ONLY a single JSON merge line with __json_edit set to true. Include only keys that need to change."
1930
+ );
1931
+ break;
1932
+ case "diff":
1933
+ parts.push("Output ONLY the unified diff in a ```diff fence.");
1934
+ break;
1935
+ }
1936
+ } else {
1937
+ const modeNames = modes.map((m) => {
1938
+ switch (m) {
1939
+ case "patch":
1940
+ return format === "yaml" ? "```yaml-patch fence" : "JSON Patch lines";
1941
+ case "merge":
1942
+ return format === "yaml" ? "```yaml-edit fence" : "JSON merge line (__json_edit)";
1943
+ case "diff":
1944
+ return "```diff fence";
1945
+ }
1946
+ });
1947
+ parts.push(
1948
+ `Choose the best edit strategy and output using one of: ${modeNames.join(", ")}`
1949
+ );
1950
+ }
1951
+ return parts.join("\n");
1952
+ }
1953
+
1954
+ // src/schema.ts
1955
+ function createBuilder() {
1956
+ return {
1957
+ string: () => ({ kind: "string" }),
1958
+ number: () => ({ kind: "number" }),
1959
+ boolean: () => ({ kind: "boolean" }),
1960
+ array: (item) => ({ kind: "array", inner: item }),
1961
+ object: (shape) => ({ kind: "object", inner: shape }),
1962
+ record: (value) => ({ kind: "record", inner: value }),
1963
+ any: () => ({ kind: "any" }),
1964
+ zod: () => ({ kind: "zod" }),
1965
+ ref: (path) => ({ kind: "ref", inner: path }),
1966
+ propsOf: (path) => ({ kind: "propsOf", inner: path }),
1967
+ map: (entryShape) => ({ kind: "map", inner: entryShape }),
1968
+ optional: () => ({ optional: true })
1969
+ };
1970
+ }
1971
+ function defineSchema(builder, options) {
1972
+ const s = createBuilder();
1973
+ const definition = builder(s);
1974
+ return {
1975
+ definition,
1976
+ promptTemplate: options?.promptTemplate,
1977
+ defaultRules: options?.defaultRules,
1978
+ builtInActions: options?.builtInActions,
1979
+ createCatalog(catalog) {
1980
+ return createCatalogFromSchema(this, catalog);
1981
+ }
1982
+ };
1983
+ }
1984
+ function createCatalogFromSchema(schema, catalogData) {
1985
+ const components = catalogData.components;
1986
+ const actions = catalogData.actions;
1987
+ const componentNames = components ? Object.keys(components) : [];
1988
+ const actionNames = actions ? Object.keys(actions) : [];
1989
+ const zodSchema = buildZodSchemaFromDefinition(
1990
+ schema.definition,
1991
+ catalogData
1992
+ );
1993
+ return {
1994
+ schema,
1995
+ data: catalogData,
1996
+ componentNames,
1997
+ actionNames,
1998
+ prompt(options = {}) {
1999
+ return generatePrompt(this, options);
2000
+ },
2001
+ jsonSchema(options = {}) {
2002
+ return zodToJsonSchema(zodSchema, options.strict ?? false);
2003
+ },
2004
+ validate(spec) {
2005
+ const result = zodSchema.safeParse(spec);
2006
+ if (result.success) {
2007
+ return {
2008
+ success: true,
2009
+ data: result.data
2010
+ };
2011
+ }
2012
+ return { success: false, error: result.error };
2013
+ },
2014
+ zodSchema() {
2015
+ return zodSchema;
2016
+ },
2017
+ get _specType() {
2018
+ throw new Error("_specType is only for type inference");
2019
+ }
2020
+ };
2021
+ }
2022
+ function buildZodSchemaFromDefinition(definition, catalogData) {
2023
+ return buildZodType(definition.spec, catalogData);
2024
+ }
2025
+ function buildZodType(schemaType, catalogData) {
2026
+ switch (schemaType.kind) {
2027
+ case "string":
2028
+ return import_zod5.z.string();
2029
+ case "number":
2030
+ return import_zod5.z.number();
2031
+ case "boolean":
2032
+ return import_zod5.z.boolean();
2033
+ case "any":
2034
+ return import_zod5.z.any();
2035
+ case "array": {
2036
+ const inner = buildZodType(schemaType.inner, catalogData);
2037
+ return import_zod5.z.array(inner);
2038
+ }
2039
+ case "object": {
2040
+ const shape = schemaType.inner;
2041
+ const zodShape = {};
2042
+ for (const [key, value] of Object.entries(shape)) {
2043
+ let zodType = buildZodType(value, catalogData);
2044
+ if (value.optional) {
2045
+ zodType = zodType.optional();
2046
+ }
2047
+ zodShape[key] = zodType;
2048
+ }
2049
+ return import_zod5.z.object(zodShape);
2050
+ }
2051
+ case "record": {
2052
+ const inner = buildZodType(schemaType.inner, catalogData);
2053
+ return import_zod5.z.record(import_zod5.z.string(), inner);
2054
+ }
2055
+ case "ref": {
2056
+ const path = schemaType.inner;
2057
+ const keys = getKeysFromPath(path, catalogData);
2058
+ if (keys.length === 0) {
2059
+ return import_zod5.z.string();
2060
+ }
2061
+ if (keys.length === 1) {
2062
+ return import_zod5.z.literal(keys[0]);
2063
+ }
2064
+ return import_zod5.z.enum(keys);
2065
+ }
2066
+ case "propsOf": {
2067
+ const path = schemaType.inner;
2068
+ const propsSchemas = getPropsFromPath(path, catalogData);
2069
+ if (propsSchemas.length === 0) {
2070
+ return import_zod5.z.record(import_zod5.z.string(), import_zod5.z.unknown());
2071
+ }
2072
+ if (propsSchemas.length === 1) {
2073
+ return propsSchemas[0];
2074
+ }
2075
+ return import_zod5.z.record(import_zod5.z.string(), import_zod5.z.unknown());
2076
+ }
2077
+ default:
2078
+ return import_zod5.z.unknown();
2079
+ }
2080
+ }
2081
+ function getKeysFromPath(path, catalogData) {
2082
+ const parts = path.split(".");
2083
+ let current = { catalog: catalogData };
2084
+ for (const part of parts) {
2085
+ if (current && typeof current === "object") {
2086
+ current = current[part];
2087
+ } else {
2088
+ return [];
2089
+ }
2090
+ }
2091
+ if (current && typeof current === "object") {
2092
+ return Object.keys(current);
2093
+ }
2094
+ return [];
2095
+ }
2096
+ function getPropsFromPath(path, catalogData) {
2097
+ const parts = path.split(".");
2098
+ let current = { catalog: catalogData };
2099
+ for (const part of parts) {
2100
+ if (current && typeof current === "object") {
2101
+ current = current[part];
2102
+ } else {
2103
+ return [];
2104
+ }
2105
+ }
2106
+ if (current && typeof current === "object") {
2107
+ return Object.values(current).map((entry) => entry.props).filter((props) => props !== void 0);
2108
+ }
2109
+ return [];
2110
+ }
2111
+ function generatePrompt(catalog, options) {
2112
+ if (catalog.schema.promptTemplate) {
2113
+ const context = {
2114
+ catalog: catalog.data,
2115
+ componentNames: catalog.componentNames,
2116
+ actionNames: catalog.actionNames,
2117
+ options,
2118
+ formatZodType
2119
+ };
2120
+ return catalog.schema.promptTemplate(context);
2121
+ }
2122
+ const {
2123
+ system = "You are a UI generator that outputs JSON.",
2124
+ customRules = [],
2125
+ mode: rawMode = "standalone"
2126
+ } = options;
2127
+ const mode = rawMode === "chat" ? (console.warn(
2128
+ '[json-render] mode "chat" is deprecated, use "inline" instead'
2129
+ ), "inline") : rawMode === "generate" ? (console.warn(
2130
+ '[json-render] mode "generate" is deprecated, use "standalone" instead'
2131
+ ), "standalone") : rawMode;
2132
+ const lines = [];
2133
+ lines.push(system);
2134
+ lines.push("");
2135
+ if (mode === "inline") {
2136
+ lines.push("OUTPUT FORMAT (text + JSONL, RFC 6902 JSON Patch):");
2137
+ lines.push(
2138
+ "You respond conversationally. When generating UI, first write a brief explanation (1-3 sentences), then output JSONL patch lines wrapped in a ```spec code fence."
2139
+ );
2140
+ lines.push(
2141
+ "The JSONL lines use RFC 6902 JSON Patch operations to build a UI tree. Always wrap them in a ```spec fence block:"
2142
+ );
2143
+ lines.push(" ```spec");
2144
+ lines.push(' {"op":"add","path":"/root","value":"main"}');
2145
+ lines.push(
2146
+ ' {"op":"add","path":"/elements/main","value":{"type":"Card","props":{"title":"Hello"},"children":[]}}'
2147
+ );
2148
+ lines.push(" ```");
2149
+ lines.push(
2150
+ "If the user's message does not require a UI (e.g. a greeting or clarifying question), respond with text only \u2014 no JSONL."
2151
+ );
2152
+ } else {
2153
+ lines.push("OUTPUT FORMAT (JSONL, RFC 6902 JSON Patch):");
2154
+ lines.push(
2155
+ "Output JSONL (one JSON object per line) using RFC 6902 JSON Patch operations to build a UI tree."
2156
+ );
2157
+ }
2158
+ lines.push(
2159
+ "Each line is a JSON patch operation (add, remove, replace). Start with /root, then stream /elements and /state patches interleaved so the UI fills in progressively as it streams."
2160
+ );
2161
+ lines.push("");
2162
+ lines.push("Example output (each line is a separate JSON object):");
2163
+ lines.push("");
2164
+ const allComponents = catalog.data.components;
2165
+ const cn = catalog.componentNames;
2166
+ const comp1 = cn[0] || "Component";
2167
+ const comp2 = cn.length > 1 ? cn[1] : comp1;
2168
+ const comp1Def = allComponents?.[comp1];
2169
+ const comp2Def = allComponents?.[comp2];
2170
+ const comp1Props = comp1Def ? getExampleProps(comp1Def) : {};
2171
+ const comp2Props = comp2Def ? getExampleProps(comp2Def) : {};
2172
+ const dynamicPropName = comp2Def?.props ? findFirstStringProp(comp2Def.props) : null;
2173
+ const dynamicProps = dynamicPropName ? { ...comp2Props, [dynamicPropName]: { $item: "title" } } : comp2Props;
2174
+ const exampleOutput = [
2175
+ JSON.stringify({ op: "add", path: "/root", value: "main" }),
2176
+ JSON.stringify({
2177
+ op: "add",
2178
+ path: "/elements/main",
2179
+ value: {
2180
+ type: comp1,
2181
+ props: comp1Props,
2182
+ children: ["child-1", "list"]
2183
+ }
2184
+ }),
2185
+ JSON.stringify({
2186
+ op: "add",
2187
+ path: "/elements/child-1",
2188
+ value: { type: comp2, props: comp2Props, children: [] }
2189
+ }),
2190
+ JSON.stringify({
2191
+ op: "add",
2192
+ path: "/elements/list",
2193
+ value: {
2194
+ type: comp1,
2195
+ props: comp1Props,
2196
+ repeat: { statePath: "/items", key: "id" },
2197
+ children: ["item"]
2198
+ }
2199
+ }),
2200
+ JSON.stringify({
2201
+ op: "add",
2202
+ path: "/elements/item",
2203
+ value: { type: comp2, props: dynamicProps, children: [] }
2204
+ }),
2205
+ JSON.stringify({ op: "add", path: "/state/items", value: [] }),
2206
+ JSON.stringify({
2207
+ op: "add",
2208
+ path: "/state/items/0",
2209
+ value: { id: "1", title: "First Item" }
2210
+ }),
2211
+ JSON.stringify({
2212
+ op: "add",
2213
+ path: "/state/items/1",
2214
+ value: { id: "2", title: "Second Item" }
2215
+ })
2216
+ ].join("\n");
2217
+ lines.push(`${exampleOutput}
2218
+
2219
+ Note: state patches appear right after the elements that use them, so the UI fills in as it streams. ONLY use component types from the AVAILABLE COMPONENTS list below.`);
2220
+ lines.push("");
2221
+ lines.push("INITIAL STATE:");
2222
+ lines.push(
2223
+ "Specs include a /state field to seed the state model. Components with { $bindState } or { $bindItem } read from and write to this state, and $state expressions read from it."
2224
+ );
2225
+ lines.push(
2226
+ "CRITICAL: You MUST include state patches whenever your UI displays data via $state, $bindState, $bindItem, $item, or $index expressions, or uses repeat to iterate over arrays. Without state, these references resolve to nothing and repeat lists render zero items."
2227
+ );
2228
+ lines.push(
2229
+ "Output state patches right after the elements that reference them, so the UI fills in progressively as it streams."
2230
+ );
2231
+ lines.push(
2232
+ "Stream state progressively - output one patch per array item instead of one giant blob:"
2233
+ );
2234
+ lines.push(
2235
+ ' For arrays: {"op":"add","path":"/state/posts/0","value":{"id":"1","title":"First Post",...}} then /state/posts/1, /state/posts/2, etc.'
2236
+ );
2237
+ lines.push(
2238
+ ' For scalars: {"op":"add","path":"/state/newTodoText","value":""}'
2239
+ );
2240
+ lines.push(
2241
+ ' Initialize the array first if needed: {"op":"add","path":"/state/posts","value":[]}'
2242
+ );
2243
+ lines.push(
2244
+ 'When content comes from the state model, use { "$state": "/some/path" } dynamic props to display it instead of hardcoding the same value in both state and props. The state model is the single source of truth.'
2245
+ );
2246
+ lines.push(
2247
+ "Include realistic sample data in state. For blogs: 3-4 posts with titles, excerpts, authors, dates. For product lists: 3-5 items with names, prices, descriptions. Never leave arrays empty."
2248
+ );
2249
+ lines.push("");
2250
+ lines.push("DYNAMIC LISTS (repeat field):");
2251
+ lines.push(
2252
+ 'Any element can have a top-level "repeat" field to render its children once per item in a state array: { "repeat": { "statePath": "/arrayPath", "key": "id" } }.'
2253
+ );
2254
+ lines.push(
2255
+ '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.'
2256
+ );
2257
+ lines.push(
2258
+ `Example: ${JSON.stringify({ type: comp1, props: comp1Props, repeat: { statePath: "/todos", key: "id" }, children: ["todo-item"] })}`
2259
+ );
2260
+ lines.push(
2261
+ 'Inside children of a repeated element, use { "$item": "field" } to read a field from the current item, and { "$index": true } to get the current array index. For two-way binding to an item field use { "$bindItem": "completed" } on the appropriate prop.'
2262
+ );
2263
+ lines.push(
2264
+ "ALWAYS use the repeat field for lists backed by state arrays. NEVER hardcode individual elements for each array item."
2265
+ );
2266
+ lines.push(
2267
+ 'IMPORTANT: "repeat" is a top-level field on the element (sibling of type/props/children), NOT inside props.'
2268
+ );
2269
+ lines.push("");
2270
+ lines.push("ARRAY STATE ACTIONS:");
2271
+ lines.push(
2272
+ 'Use action "pushState" to append items to arrays. Params: { statePath: "/arrayPath", value: { ...item }, clearStatePath: "/inputPath" }.'
2273
+ );
2274
+ lines.push(
2275
+ 'Values inside pushState can contain { "$state": "/statePath" } references to read current state (e.g. the text from an input field).'
2276
+ );
2277
+ lines.push(
2278
+ 'Use "$id" inside a pushState value to auto-generate a unique ID.'
2279
+ );
2280
+ lines.push(
2281
+ 'Example: on: { "press": { "action": "pushState", "params": { "statePath": "/todos", "value": { "id": "$id", "title": { "$state": "/newTodoText" }, "completed": false }, "clearStatePath": "/newTodoText" } } }'
2282
+ );
2283
+ lines.push(
2284
+ `Use action "removeState" to remove items from arrays by index. Params: { statePath: "/arrayPath", index: N }. Inside a repeated element's children, use { "$index": true } for the current item index. Action params support the same expressions as props: { "$item": "field" } resolves to the absolute state path, { "$index": true } resolves to the index number, and { "$state": "/path" } reads a value from state.`
2285
+ );
2286
+ lines.push(
2287
+ "For lists where users can add/remove items (todos, carts, etc.), use pushState and removeState instead of hardcoding with setState."
2288
+ );
2289
+ lines.push("");
2290
+ lines.push(
2291
+ 'IMPORTANT: State paths use RFC 6901 JSON Pointer syntax (e.g. "/todos/0/title"). Do NOT use JavaScript-style dot notation (e.g. "/todos.length" is WRONG). To generate unique IDs for new items, use "$id" instead of trying to read array length.'
2292
+ );
2293
+ lines.push("");
2294
+ const components = allComponents;
2295
+ if (components) {
2296
+ lines.push(`AVAILABLE COMPONENTS (${catalog.componentNames.length}):`);
2297
+ lines.push("");
2298
+ for (const [name, def] of Object.entries(components)) {
2299
+ const propsStr = def.props ? formatZodType(def.props) : "{}";
2300
+ const hasChildren = def.slots && def.slots.length > 0;
2301
+ const childrenStr = hasChildren ? " [accepts children]" : "";
2302
+ const eventsStr = def.events && def.events.length > 0 ? ` [events: ${def.events.join(", ")}]` : "";
2303
+ const descStr = def.description ? ` - ${def.description}` : "";
2304
+ lines.push(`- ${name}: ${propsStr}${descStr}${childrenStr}${eventsStr}`);
2305
+ }
2306
+ lines.push("");
2307
+ }
2308
+ const actions = catalog.data.actions;
2309
+ const builtInActions = catalog.schema.builtInActions ?? [];
2310
+ const hasCustomActions = actions && catalog.actionNames.length > 0;
2311
+ const hasBuiltInActions = builtInActions.length > 0;
2312
+ if (hasCustomActions || hasBuiltInActions) {
2313
+ lines.push("AVAILABLE ACTIONS:");
2314
+ lines.push("");
2315
+ for (const action2 of builtInActions) {
2316
+ lines.push(`- ${action2.name}: ${action2.description} [built-in]`);
2317
+ }
2318
+ if (hasCustomActions) {
2319
+ for (const [name, def] of Object.entries(actions)) {
2320
+ lines.push(`- ${name}${def.description ? `: ${def.description}` : ""}`);
2321
+ }
2322
+ }
2323
+ lines.push("");
2324
+ }
2325
+ lines.push("EVENTS (the `on` field):");
2326
+ lines.push(
2327
+ "Elements can have an optional `on` field to bind events to actions. The `on` field is a top-level field on the element (sibling of type/props/children), NOT inside props."
2328
+ );
2329
+ lines.push(
2330
+ 'Each key in `on` is an event name (from the component\'s supported events), and the value is an action binding: `{ "action": "<actionName>", "params": { ... } }`.'
2331
+ );
2332
+ lines.push("");
2333
+ lines.push("Example:");
2334
+ lines.push(
2335
+ ` ${JSON.stringify({ type: comp1, props: comp1Props, on: { press: { action: "setState", params: { statePath: "/saved", value: true } } }, children: [] })}`
2336
+ );
2337
+ lines.push("");
2338
+ lines.push(
2339
+ 'Action params can use dynamic references to read from state: { "$state": "/statePath" }.'
2340
+ );
2341
+ lines.push(
2342
+ "IMPORTANT: Do NOT put action/actionParams inside props. Always use the `on` field for event bindings."
2343
+ );
2344
+ lines.push("");
2345
+ lines.push("VISIBILITY CONDITIONS:");
2346
+ lines.push(
2347
+ "Elements can have an optional `visible` field to conditionally show/hide based on state. IMPORTANT: `visible` is a top-level field on the element object (sibling of type/props/children), NOT inside props."
2348
+ );
2349
+ lines.push(
2350
+ `Correct: ${JSON.stringify({ type: comp1, props: comp1Props, visible: { $state: "/activeTab", eq: "home" }, children: ["..."] })}`
2351
+ );
2352
+ lines.push(
2353
+ '- `{ "$state": "/path" }` - visible when state at path is truthy'
2354
+ );
2355
+ lines.push(
2356
+ '- `{ "$state": "/path", "not": true }` - visible when state at path is falsy'
2357
+ );
2358
+ lines.push(
2359
+ '- `{ "$state": "/path", "eq": "value" }` - visible when state equals value'
2360
+ );
2361
+ lines.push(
2362
+ '- `{ "$state": "/path", "neq": "value" }` - visible when state does not equal value'
2363
+ );
2364
+ lines.push(
2365
+ '- `{ "$state": "/path", "gt": N }` / `gte` / `lt` / `lte` - numeric comparisons'
2366
+ );
2367
+ lines.push(
2368
+ "- Use ONE operator per condition (eq, neq, gt, gte, lt, lte). Do not combine multiple operators."
2369
+ );
2370
+ lines.push('- Any condition can add `"not": true` to invert its result');
2371
+ lines.push(
2372
+ "- `[condition, condition]` - all conditions must be true (implicit AND)"
2373
+ );
2374
+ lines.push(
2375
+ '- `{ "$and": [condition, condition] }` - explicit AND (use when nesting inside $or)'
2376
+ );
2377
+ lines.push(
2378
+ '- `{ "$or": [condition, condition] }` - at least one must be true (OR)'
2379
+ );
2380
+ lines.push("- `true` / `false` - always visible/hidden");
2381
+ lines.push("");
2382
+ lines.push(
2383
+ "Use a component with on.press bound to setState to update state and drive visibility."
2384
+ );
2385
+ lines.push(
2386
+ `Example: A ${comp1} with on: { "press": { "action": "setState", "params": { "statePath": "/activeTab", "value": "home" } } } sets state, then a container with visible: { "$state": "/activeTab", "eq": "home" } shows only when that tab is active.`
2387
+ );
2388
+ lines.push("");
2389
+ lines.push(
2390
+ 'For tab patterns where the first/default tab should be visible when no tab is selected yet, use $or to handle both cases: visible: { "$or": [{ "$state": "/activeTab", "eq": "home" }, { "$state": "/activeTab", "not": true }] }. This ensures the first tab is visible both when explicitly selected AND when /activeTab is not yet set.'
2391
+ );
2392
+ lines.push("");
2393
+ lines.push("DYNAMIC PROPS:");
2394
+ lines.push(
2395
+ "Any prop value can be a dynamic expression that resolves based on state. Three forms are supported:"
2396
+ );
2397
+ lines.push("");
2398
+ lines.push(
2399
+ '1. Read-only state: `{ "$state": "/statePath" }` - resolves to the value at that state path (one-way read).'
2400
+ );
2401
+ lines.push(
2402
+ ' Example: `"color": { "$state": "/theme/primary" }` reads the color from state.'
2403
+ );
2404
+ lines.push("");
2405
+ lines.push(
2406
+ '2. Two-way binding: `{ "$bindState": "/statePath" }` - resolves to the value at the state path AND enables write-back. Use on form input props (value, checked, pressed, etc.).'
2407
+ );
2408
+ lines.push(
2409
+ ' Example: `"value": { "$bindState": "/form/email" }` binds the input value to /form/email.'
2410
+ );
2411
+ lines.push(
2412
+ ' Inside repeat scopes: `"checked": { "$bindItem": "completed" }` binds to the current item\'s completed field.'
2413
+ );
2414
+ lines.push("");
2415
+ lines.push(
2416
+ '3. Conditional: `{ "$cond": <condition>, "$then": <value>, "$else": <value> }` - evaluates the condition (same syntax as visibility conditions) and picks the matching value.'
2417
+ );
2418
+ lines.push(
2419
+ ' Example: `"color": { "$cond": { "$state": "/activeTab", "eq": "home" }, "$then": "#007AFF", "$else": "#8E8E93" }`'
2420
+ );
2421
+ lines.push("");
2422
+ lines.push(
2423
+ "Use $bindState for form inputs (text fields, checkboxes, selects, sliders, etc.) and $state for read-only data display. Inside repeat scopes, use $bindItem for form inputs bound to the current item. Use dynamic props instead of duplicating elements with opposing visible conditions when only prop values differ."
2424
+ );
2425
+ lines.push("");
2426
+ lines.push(
2427
+ '4. Template: `{ "$template": "Hello, ${/name}!" }` - interpolates references in the string. Absolute paths like `${/path}` resolve against the state model. Bare names like `${field}` resolve against the current repeat item first, then fall back to the state model at `/<field>`.'
2428
+ );
2429
+ lines.push(
2430
+ ' Example: `"label": { "$template": "Items: ${/cart/count} | Total: ${/cart/total}" }` renders "Items: 3 | Total: 42.00" when /cart/count is 3 and /cart/total is 42.00. Inside a repeat, `{ "$template": "${name} - ${email}" }` reads name and email from each item.'
2431
+ );
2432
+ lines.push("");
2433
+ const catalogFunctions = catalog.data.functions;
2434
+ if (catalogFunctions && Object.keys(catalogFunctions).length > 0) {
2435
+ lines.push(
2436
+ '5. Computed: `{ "$computed": "<functionName>", "args": { "key": <expression> } }` - calls a registered function with resolved args and returns the result.'
2437
+ );
2438
+ lines.push(
2439
+ ' Example: `"value": { "$computed": "fullName", "args": { "first": { "$state": "/form/firstName" }, "last": { "$state": "/form/lastName" } } }`'
2440
+ );
2441
+ lines.push(" Available functions:");
2442
+ for (const name of Object.keys(
2443
+ catalogFunctions
2444
+ )) {
2445
+ lines.push(` - ${name}`);
2446
+ }
2447
+ lines.push("");
2448
+ }
2449
+ const directives = options.directives;
2450
+ if (directives && directives.length > 0) {
2451
+ lines.push("CUSTOM DYNAMIC VALUES:");
2452
+ lines.push("");
2453
+ for (const d of directives) {
2454
+ const desc = d.description ? ` (${d.description})` : "";
2455
+ lines.push(`- ${d.name}${desc}: ${formatZodType(d.schema)}`);
2456
+ }
2457
+ lines.push("");
2458
+ lines.push(
2459
+ "Directives compose: any value field can contain another directive or a $state expression, resolved inside-out."
2460
+ );
2461
+ lines.push("");
2462
+ }
2463
+ const hasChecksComponents = allComponents ? Object.entries(allComponents).some(([, def]) => {
2464
+ if (!def.props) return false;
2465
+ const formatted = formatZodType(def.props);
2466
+ return formatted.includes("checks");
2467
+ }) : false;
2468
+ if (hasChecksComponents) {
2469
+ lines.push("VALIDATION:");
2470
+ lines.push(
2471
+ "Form components that accept a `checks` prop support client-side validation."
2472
+ );
2473
+ lines.push(
2474
+ 'Each check is an object: { "type": "<name>", "message": "...", "args": { ... } }'
2475
+ );
2476
+ lines.push("");
2477
+ lines.push("Built-in validation types:");
2478
+ lines.push(" - required \u2014 value must be non-empty");
2479
+ lines.push(" - email \u2014 valid email format");
2480
+ lines.push(' - minLength \u2014 minimum string length (args: { "min": N })');
2481
+ lines.push(' - maxLength \u2014 maximum string length (args: { "max": N })');
2482
+ lines.push(' - pattern \u2014 match a regex (args: { "pattern": "regex" })');
2483
+ lines.push(' - min \u2014 minimum numeric value (args: { "min": N })');
2484
+ lines.push(' - max \u2014 maximum numeric value (args: { "max": N })');
2485
+ lines.push(" - numeric \u2014 value must be a number");
2486
+ lines.push(" - url \u2014 valid URL format");
2487
+ lines.push(
2488
+ ' - matches \u2014 must equal another field (args: { "other": { "$state": "/path" } })'
2489
+ );
2490
+ lines.push(
2491
+ ' - equalTo \u2014 alias for matches (args: { "other": { "$state": "/path" } })'
2492
+ );
2493
+ lines.push(
2494
+ ' - lessThan \u2014 value must be less than another field (args: { "other": { "$state": "/path" } })'
2495
+ );
2496
+ lines.push(
2497
+ ' - greaterThan \u2014 value must be greater than another field (args: { "other": { "$state": "/path" } })'
2498
+ );
2499
+ lines.push(
2500
+ ' - requiredIf \u2014 required only when another field is truthy (args: { "field": { "$state": "/path" } })'
2501
+ );
2502
+ lines.push("");
2503
+ lines.push("Example:");
2504
+ lines.push(
2505
+ ' "checks": [{ "type": "required", "message": "Email is required" }, { "type": "email", "message": "Invalid email" }]'
2506
+ );
2507
+ lines.push("");
2508
+ lines.push(
2509
+ "IMPORTANT: When using checks, the component must also have a { $bindState } or { $bindItem } on its value/checked prop for two-way binding."
2510
+ );
2511
+ lines.push(
2512
+ "Always include validation checks on form inputs for a good user experience (e.g. required, email, minLength)."
2513
+ );
2514
+ lines.push("");
2515
+ }
2516
+ if (hasCustomActions || hasBuiltInActions) {
2517
+ lines.push("STATE WATCHERS:");
2518
+ lines.push(
2519
+ "Elements can have an optional `watch` field to react to state changes and trigger actions. The `watch` field is a top-level field on the element (sibling of type/props/children), NOT inside props."
2520
+ );
2521
+ lines.push(
2522
+ "Maps state paths (JSON Pointers) to action bindings. When the value at a watched path changes, the bound actions fire automatically."
2523
+ );
2524
+ lines.push("");
2525
+ lines.push(
2526
+ "Example (cascading select \u2014 country changes trigger city loading):"
2527
+ );
2528
+ lines.push(
2529
+ ` ${JSON.stringify({ type: "Select", props: { value: { $bindState: "/form/country" }, options: ["US", "Canada", "UK"] }, watch: { "/form/country": { action: "loadCities", params: { country: { $state: "/form/country" } } } }, children: [] })}`
2530
+ );
2531
+ lines.push("");
2532
+ lines.push(
2533
+ "Use `watch` for cascading dependencies where changing one field should trigger side effects (loading data, resetting dependent fields, computing derived values)."
2534
+ );
2535
+ lines.push(
2536
+ "IMPORTANT: `watch` is a top-level field on the element (sibling of type/props/children), NOT inside props. Watchers only fire when the value changes, not on initial render."
2537
+ );
2538
+ lines.push("");
2539
+ }
2540
+ const editModes = options.editModes;
2541
+ if (editModes && editModes.length > 0) {
2542
+ lines.push(buildEditInstructions({ modes: editModes }, "json"));
2543
+ }
2544
+ lines.push("RULES:");
2545
+ const baseRules = mode === "inline" ? [
2546
+ "When generating UI, wrap all JSONL patches in a ```spec code fence - one JSON object per line inside the fence",
2547
+ "Write a brief conversational response before any JSONL output",
2548
+ 'First set root: {"op":"add","path":"/root","value":"<root-key>"}',
2549
+ 'Then add each element: {"op":"add","path":"/elements/<key>","value":{...}}',
2550
+ "Output /state patches right after the elements that use them, one per array item for progressive loading. REQUIRED whenever using $state, $bindState, $bindItem, $item, $index, or repeat.",
2551
+ "ONLY use components listed above",
2552
+ "Each element value needs: type, props, children (array of child keys)",
2553
+ "Use unique keys for the element map entries (e.g., 'header', 'metric-1', 'chart-revenue')"
2554
+ ] : [
2555
+ "Output ONLY JSONL patches - one JSON object per line, no markdown, no code fences",
2556
+ 'First set root: {"op":"add","path":"/root","value":"<root-key>"}',
2557
+ 'Then add each element: {"op":"add","path":"/elements/<key>","value":{...}}',
2558
+ "Output /state patches right after the elements that use them, one per array item for progressive loading. REQUIRED whenever using $state, $bindState, $bindItem, $item, $index, or repeat.",
2559
+ "ONLY use components listed above",
2560
+ "Each element value needs: type, props, children (array of child keys)",
2561
+ "Use unique keys for the element map entries (e.g., 'header', 'metric-1', 'chart-revenue')"
2562
+ ];
2563
+ const schemaRules = catalog.schema.defaultRules ?? [];
2564
+ const allRules = [...baseRules, ...schemaRules, ...customRules];
2565
+ allRules.forEach((rule, i) => {
2566
+ lines.push(`${i + 1}. ${rule}`);
2567
+ });
2568
+ return lines.join("\n");
2569
+ }
2570
+ function getExampleProps(def) {
2571
+ if (def.example && Object.keys(def.example).length > 0) {
2572
+ return def.example;
2573
+ }
2574
+ if (def.props) {
2575
+ return generateExamplePropsFromZod(def.props);
2576
+ }
2577
+ return {};
2578
+ }
2579
+ function generateExamplePropsFromZod(schema) {
2580
+ if (!schema || !schema._def) return {};
2581
+ const def = schema._def;
2582
+ const typeName = getZodTypeName(schema);
2583
+ if (typeName !== "ZodObject" && typeName !== "object") return {};
2584
+ const shape = typeof def.shape === "function" ? def.shape() : def.shape;
2585
+ if (!shape) return {};
2586
+ const result = {};
2587
+ for (const [key, value] of Object.entries(shape)) {
2588
+ const innerTypeName = getZodTypeName(value);
2589
+ if (innerTypeName === "ZodOptional" || innerTypeName === "optional" || innerTypeName === "ZodNullable" || innerTypeName === "nullable") {
2590
+ continue;
2591
+ }
2592
+ result[key] = generateExampleValue(value);
2593
+ }
2594
+ return result;
2595
+ }
2596
+ function generateExampleValue(schema) {
2597
+ if (!schema || !schema._def) return "...";
2598
+ const def = schema._def;
2599
+ const typeName = getZodTypeName(schema);
2600
+ switch (typeName) {
2601
+ case "ZodString":
2602
+ case "string":
2603
+ return "example";
2604
+ case "ZodNumber":
2605
+ case "number":
2606
+ return 0;
2607
+ case "ZodBoolean":
2608
+ case "boolean":
2609
+ return true;
2610
+ case "ZodLiteral":
2611
+ case "literal":
2612
+ return def.value;
2613
+ case "ZodEnum":
2614
+ case "enum": {
2615
+ if (Array.isArray(def.values) && def.values.length > 0)
2616
+ return def.values[0];
2617
+ if (def.entries && typeof def.entries === "object") {
2618
+ const values = Object.values(def.entries);
2619
+ return values.length > 0 ? values[0] : "example";
2620
+ }
2621
+ return "example";
2622
+ }
2623
+ case "ZodOptional":
2624
+ case "optional":
2625
+ case "ZodNullable":
2626
+ case "nullable":
2627
+ case "ZodDefault":
2628
+ case "default": {
2629
+ const inner = def.innerType ?? def.wrapped;
2630
+ return inner ? generateExampleValue(inner) : null;
2631
+ }
2632
+ case "ZodArray":
2633
+ case "array":
2634
+ return [];
2635
+ case "ZodObject":
2636
+ case "object":
2637
+ return generateExamplePropsFromZod(schema);
2638
+ case "ZodUnion":
2639
+ case "union": {
2640
+ const options = def.options;
2641
+ return options && options.length > 0 ? generateExampleValue(options[0]) : "...";
2642
+ }
2643
+ default:
2644
+ return "...";
2645
+ }
2646
+ }
2647
+ function findFirstStringProp(schema) {
2648
+ if (!schema || !schema._def) return null;
2649
+ const def = schema._def;
2650
+ const typeName = getZodTypeName(schema);
2651
+ if (typeName !== "ZodObject" && typeName !== "object") return null;
2652
+ const shape = typeof def.shape === "function" ? def.shape() : def.shape;
2653
+ if (!shape) return null;
2654
+ for (const [key, value] of Object.entries(shape)) {
2655
+ const innerTypeName = getZodTypeName(value);
2656
+ if (innerTypeName === "ZodOptional" || innerTypeName === "optional" || innerTypeName === "ZodNullable" || innerTypeName === "nullable") {
2657
+ continue;
2658
+ }
2659
+ if (innerTypeName === "ZodString" || innerTypeName === "string") {
2660
+ return key;
2661
+ }
2662
+ }
2663
+ return null;
2664
+ }
2665
+ function getZodTypeName(schema) {
2666
+ if (!schema || !schema._def) return "";
2667
+ const def = schema._def;
2668
+ return def.typeName ?? def.type ?? "";
2669
+ }
2670
+ function formatZodType(schema) {
2671
+ if (!schema || !schema._def) return "unknown";
2672
+ const def = schema._def;
2673
+ const typeName = getZodTypeName(schema);
2674
+ switch (typeName) {
2675
+ case "ZodString":
2676
+ case "string":
2677
+ return "string";
2678
+ case "ZodNumber":
2679
+ case "number":
2680
+ return "number";
2681
+ case "ZodBoolean":
2682
+ case "boolean":
2683
+ return "boolean";
2684
+ case "ZodLiteral":
2685
+ case "literal": {
2686
+ const litValues = def.values;
2687
+ const litValue = litValues?.[0] ?? def.value;
2688
+ return JSON.stringify(litValue);
2689
+ }
2690
+ case "ZodEnum":
2691
+ case "enum": {
2692
+ let values;
2693
+ if (Array.isArray(def.values)) {
2694
+ values = def.values;
2695
+ } else if (def.entries && typeof def.entries === "object") {
2696
+ values = Object.values(def.entries);
2697
+ } else {
2698
+ return "enum";
2699
+ }
2700
+ return values.map((v) => `"${v}"`).join(" | ");
2701
+ }
2702
+ case "ZodArray":
2703
+ case "array": {
2704
+ const inner = typeof def.element === "object" ? def.element : typeof def.type === "object" ? def.type : void 0;
2705
+ return inner ? `Array<${formatZodType(inner)}>` : "Array<unknown>";
2706
+ }
2707
+ case "ZodObject":
2708
+ case "object": {
2709
+ const shape = typeof def.shape === "function" ? def.shape() : def.shape;
2710
+ if (!shape) return "object";
2711
+ const props = Object.entries(shape).map(([key, value]) => {
2712
+ const innerTypeName = getZodTypeName(value);
2713
+ const isOptional = innerTypeName === "ZodOptional" || innerTypeName === "ZodNullable" || innerTypeName === "optional" || innerTypeName === "nullable";
2714
+ return `${key}${isOptional ? "?" : ""}: ${formatZodType(value)}`;
2715
+ }).join(", ");
2716
+ return `{ ${props} }`;
2717
+ }
2718
+ case "ZodOptional":
2719
+ case "optional":
2720
+ case "ZodNullable":
2721
+ case "nullable": {
2722
+ const inner = def.innerType ?? def.wrapped;
2723
+ return inner ? formatZodType(inner) : "unknown";
2724
+ }
2725
+ case "ZodUnion":
2726
+ case "union": {
2727
+ const options = def.options;
2728
+ return options ? options.map((opt) => formatZodType(opt)).join(" | ") : "unknown";
2729
+ }
2730
+ case "ZodRecord":
2731
+ case "record": {
2732
+ const keyType = def.keyType ?? void 0;
2733
+ const valueType = def.valueType ?? def.element ?? void 0;
2734
+ const keyStr = keyType ? formatZodType(keyType) : "string";
2735
+ const valueStr = valueType ? formatZodType(valueType) : "unknown";
2736
+ return `Record<${keyStr}, ${valueStr}>`;
2737
+ }
2738
+ case "ZodDefault":
2739
+ case "default": {
2740
+ const inner = def.innerType ?? def.wrapped;
2741
+ return inner ? formatZodType(inner) : "unknown";
2742
+ }
2743
+ default:
2744
+ return "unknown";
2745
+ }
2746
+ }
2747
+ function zodTypeName(def) {
2748
+ if (typeof def.type === "string") return def.type;
2749
+ if (typeof def.typeName === "string") return def.typeName;
2750
+ return "";
2751
+ }
2752
+ function normalizeTypeName(raw) {
2753
+ if (raw.startsWith("Zod")) {
2754
+ return raw.slice(3).toLowerCase();
2755
+ }
2756
+ return raw.toLowerCase();
2757
+ }
2758
+ function zodToJsonSchema(schema, strict = false) {
2759
+ const def = schema._def;
2760
+ const kind = normalizeTypeName(zodTypeName(def));
2761
+ switch (kind) {
2762
+ case "string":
2763
+ return { type: "string" };
2764
+ case "number":
2765
+ return { type: "number" };
2766
+ case "boolean":
2767
+ return { type: "boolean" };
2768
+ case "literal": {
2769
+ const values = def.values;
2770
+ const value = values ? values[0] : def.value;
2771
+ return { const: value };
2772
+ }
2773
+ case "enum": {
2774
+ const entries = def.entries;
2775
+ const values = entries ? Object.values(entries) : def.values;
2776
+ return { enum: values ?? [] };
2777
+ }
2778
+ case "array": {
2779
+ const inner = def.element ?? def.type;
2780
+ return {
2781
+ type: "array",
2782
+ items: inner ? zodToJsonSchema(inner, strict) : {}
2783
+ };
2784
+ }
2785
+ case "object": {
2786
+ const rawShape = def.shape;
2787
+ const shape = typeof rawShape === "function" ? rawShape() : rawShape;
2788
+ if (!shape) {
2789
+ if (strict) {
2790
+ return {
2791
+ type: "object",
2792
+ properties: {},
2793
+ required: [],
2794
+ additionalProperties: false
2795
+ };
2796
+ }
2797
+ return { type: "object" };
2798
+ }
2799
+ const properties = {};
2800
+ const required = [];
2801
+ for (const [key, value] of Object.entries(shape)) {
2802
+ const innerDef = value._def;
2803
+ const innerKind = normalizeTypeName(zodTypeName(innerDef));
2804
+ const isOptional = innerKind === "optional" || innerKind === "nullable";
2805
+ if (strict) {
2806
+ required.push(key);
2807
+ if (isOptional) {
2808
+ const unwrapped = zodToJsonSchema(value, strict);
2809
+ properties[key] = { anyOf: [unwrapped, { type: "null" }] };
2810
+ } else {
2811
+ properties[key] = zodToJsonSchema(value, strict);
2812
+ }
2813
+ } else {
2814
+ properties[key] = zodToJsonSchema(value);
2815
+ if (!isOptional) {
2816
+ required.push(key);
2817
+ }
2818
+ }
2819
+ }
2820
+ return {
2821
+ type: "object",
2822
+ properties,
2823
+ required: required.length > 0 ? required : void 0,
2824
+ additionalProperties: false
2825
+ };
2826
+ }
2827
+ case "record": {
2828
+ const valueType = def.valueType;
2829
+ if (strict) {
2830
+ return {
2831
+ type: "object",
2832
+ properties: {},
2833
+ required: [],
2834
+ additionalProperties: false
2835
+ };
2836
+ }
2837
+ return {
2838
+ type: "object",
2839
+ additionalProperties: valueType ? zodToJsonSchema(valueType) : true
2840
+ };
2841
+ }
2842
+ case "optional":
2843
+ case "nullable": {
2844
+ const inner = def.innerType;
2845
+ return inner ? zodToJsonSchema(inner, strict) : {};
2846
+ }
2847
+ case "union": {
2848
+ const options = def.options;
2849
+ return options ? { anyOf: options.map((o) => zodToJsonSchema(o, strict)) } : {};
2850
+ }
2851
+ case "any":
2852
+ case "unknown":
2853
+ if (strict) {
2854
+ return {
2855
+ type: "object",
2856
+ properties: {},
2857
+ required: [],
2858
+ additionalProperties: false
2859
+ };
2860
+ }
2861
+ return {};
2862
+ default:
2863
+ return {};
2864
+ }
2865
+ }
2866
+ function defineCatalog(schema, catalog) {
2867
+ return schema.createCatalog(catalog);
2868
+ }
2869
+
2870
+ // src/prompt.ts
2871
+ function buildUserPrompt(options) {
2872
+ const {
2873
+ prompt,
2874
+ currentSpec,
2875
+ state,
2876
+ maxPromptLength,
2877
+ editModes,
2878
+ format,
2879
+ serializer
2880
+ } = options;
2881
+ let userText = String(prompt || "");
2882
+ if (maxPromptLength !== void 0 && maxPromptLength > 0) {
2883
+ userText = userText.slice(0, maxPromptLength);
2884
+ }
2885
+ if (isNonEmptySpec(currentSpec)) {
2886
+ const editPrompt = buildEditUserPrompt({
2887
+ prompt: userText,
2888
+ currentSpec,
2889
+ config: { modes: editModes ?? ["patch"] },
2890
+ format: format ?? "json",
2891
+ serializer
2892
+ });
2893
+ if (state && Object.keys(state).length > 0) {
2894
+ return `${editPrompt}
2895
+
2896
+ AVAILABLE STATE:
2897
+ ${JSON.stringify(state, null, 2)}`;
2898
+ }
2899
+ return editPrompt;
2900
+ }
2901
+ const parts = [userText];
2902
+ if (state && Object.keys(state).length > 0) {
2903
+ parts.push(`
2904
+ AVAILABLE STATE:
2905
+ ${JSON.stringify(state, null, 2)}`);
2906
+ }
2907
+ if (format === "yaml") {
2908
+ parts.push(
2909
+ `
2910
+ Output the full spec in a \`\`\`yaml-spec fence. Stream progressively \u2014 output elements one at a time.`
2911
+ );
2912
+ } else {
2913
+ parts.push(
2914
+ `
2915
+ Remember: Output /root first, then interleave /elements and /state patches so the UI fills in progressively as it streams. Output each state patch right after the elements that use it, one per array item.`
2916
+ );
2917
+ }
2918
+ return parts.join("\n");
2919
+ }
2920
+
2921
+ // src/merge.ts
2922
+ function isPlainObject(value) {
2923
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2924
+ }
2925
+ function deepMergeSpec(base, patch) {
2926
+ const result = { ...base };
2927
+ for (const key of Object.keys(patch)) {
2928
+ const patchVal = patch[key];
2929
+ if (patchVal === null) {
2930
+ delete result[key];
2931
+ continue;
2932
+ }
2933
+ const baseVal = result[key];
2934
+ if (isPlainObject(patchVal) && isPlainObject(baseVal)) {
2935
+ result[key] = deepMergeSpec(baseVal, patchVal);
2936
+ } else {
2937
+ result[key] = patchVal;
2938
+ }
2939
+ }
2940
+ return result;
2941
+ }
2942
+
2943
+ // src/diff.ts
2944
+ function escapeToken(token) {
2945
+ return token.replace(/~/g, "~0").replace(/\//g, "~1");
2946
+ }
2947
+ function buildPath(basePath, key) {
2948
+ return `${basePath}/${escapeToken(key)}`;
2949
+ }
2950
+ function isPlainObject2(value) {
2951
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2952
+ }
2953
+ function arraysEqual(a, b) {
2954
+ if (a.length !== b.length) return false;
2955
+ for (let i = 0; i < a.length; i++) {
2956
+ if (a[i] !== b[i]) return false;
2957
+ }
2958
+ return true;
2959
+ }
2960
+ function diffToPatches(oldObj, newObj, basePath = "") {
2961
+ const patches = [];
2962
+ for (const key of Object.keys(newObj)) {
2963
+ const path = buildPath(basePath, key);
2964
+ const oldVal = oldObj[key];
2965
+ const newVal = newObj[key];
2966
+ if (!(key in oldObj)) {
2967
+ patches.push({ op: "add", path, value: newVal });
2968
+ continue;
2969
+ }
2970
+ if (isPlainObject2(oldVal) && isPlainObject2(newVal)) {
2971
+ patches.push(...diffToPatches(oldVal, newVal, path));
2972
+ } else if (Array.isArray(oldVal) && Array.isArray(newVal)) {
2973
+ if (!arraysEqual(oldVal, newVal)) {
2974
+ patches.push({ op: "replace", path, value: newVal });
2975
+ }
2976
+ } else if (oldVal !== newVal) {
2977
+ patches.push({ op: "replace", path, value: newVal });
2978
+ }
2979
+ }
2980
+ for (const key of Object.keys(oldObj)) {
2981
+ if (!(key in newObj)) {
2982
+ patches.push({ op: "remove", path: buildPath(basePath, key) });
2983
+ }
2984
+ }
2985
+ return patches;
2986
+ }
2987
+ // Annotate the CommonJS export names for ESM import in node:
2988
+ 0 && (module.exports = {
2989
+ ActionBindingSchema,
2990
+ ActionConfirmSchema,
2991
+ ActionOnErrorSchema,
2992
+ ActionOnSuccessSchema,
2993
+ ActionSchema,
2994
+ DynamicBooleanSchema,
2995
+ DynamicNumberSchema,
2996
+ DynamicStringSchema,
2997
+ DynamicValueSchema,
2998
+ SPEC_DATA_PART,
2999
+ SPEC_DATA_PART_TYPE,
3000
+ ValidationCheckSchema,
3001
+ ValidationConfigSchema,
3002
+ VisibilityConditionSchema,
3003
+ action,
3004
+ actionBinding,
3005
+ addByPath,
3006
+ applySpecPatch,
3007
+ applySpecStreamPatch,
3008
+ autoFixSpec,
3009
+ buildEditInstructions,
3010
+ buildEditUserPrompt,
3011
+ buildUserPrompt,
3012
+ builtInValidationFunctions,
3013
+ check,
3014
+ compileSpecStream,
3015
+ createDirectiveRegistry,
3016
+ createJsonRenderTransform,
3017
+ createMixedStreamParser,
3018
+ createSpecStreamCompiler,
3019
+ createStateStore,
3020
+ deepMergeSpec,
3021
+ defineCatalog,
3022
+ defineDirective,
3023
+ defineSchema,
3024
+ diffToPatches,
3025
+ evaluateVisibility,
3026
+ executeAction,
3027
+ findDirective,
3028
+ findFormValue,
3029
+ formatSpecIssues,
3030
+ getByPath,
3031
+ interpolateString,
3032
+ isDevtoolsActive,
3033
+ isNonEmptySpec,
3034
+ markDevtoolsActive,
3035
+ nestedToFlat,
3036
+ nextActionDispatchId,
3037
+ notifyActionDispatch,
3038
+ notifyActionSettle,
3039
+ parseSpecStreamLine,
3040
+ pipeJsonRender,
3041
+ registerActionObserver,
3042
+ removeByPath,
3043
+ resolveAction,
3044
+ resolveActionParam,
3045
+ resolveBindings,
3046
+ resolveDynamicValue,
3047
+ resolveElementProps,
3048
+ resolvePropValue,
3049
+ runValidation,
3050
+ runValidationCheck,
3051
+ setByPath,
3052
+ subscribeDevtoolsActive,
3053
+ validateSpec,
3054
+ visibility
3055
+ });
3056
+ //# sourceMappingURL=index.js.map