@formspec/build 0.1.0-alpha.4 → 0.1.0-alpha.40

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.
Files changed (113) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +238 -93
  3. package/dist/analyzer/class-analyzer.d.ts +135 -0
  4. package/dist/analyzer/class-analyzer.d.ts.map +1 -0
  5. package/dist/analyzer/jsdoc-constraints.d.ts +53 -0
  6. package/dist/analyzer/jsdoc-constraints.d.ts.map +1 -0
  7. package/dist/analyzer/program.d.ts +94 -0
  8. package/dist/analyzer/program.d.ts.map +1 -0
  9. package/dist/analyzer/tsdoc-parser.d.ts +126 -0
  10. package/dist/analyzer/tsdoc-parser.d.ts.map +1 -0
  11. package/dist/browser.cjs +1904 -0
  12. package/dist/browser.cjs.map +1 -0
  13. package/dist/browser.d.ts +74 -0
  14. package/dist/browser.d.ts.map +1 -0
  15. package/dist/browser.js +1861 -0
  16. package/dist/browser.js.map +1 -0
  17. package/dist/build-alpha.d.ts +1491 -0
  18. package/dist/build-beta.d.ts +1491 -0
  19. package/dist/build-internal.d.ts +1491 -0
  20. package/dist/build.d.ts +1184 -43
  21. package/dist/canonicalize/chain-dsl-canonicalizer.d.ts +22 -0
  22. package/dist/canonicalize/chain-dsl-canonicalizer.d.ts.map +1 -0
  23. package/dist/canonicalize/index.d.ts +8 -0
  24. package/dist/canonicalize/index.d.ts.map +1 -0
  25. package/dist/canonicalize/tsdoc-canonicalizer.d.ts +38 -0
  26. package/dist/canonicalize/tsdoc-canonicalizer.d.ts.map +1 -0
  27. package/dist/cli.cjs +6579 -0
  28. package/dist/cli.cjs.map +1 -0
  29. package/dist/cli.js +6551 -103
  30. package/dist/cli.js.map +1 -1
  31. package/dist/extensions/index.d.ts +8 -0
  32. package/dist/extensions/index.d.ts.map +1 -0
  33. package/dist/extensions/registry.d.ts +83 -0
  34. package/dist/extensions/registry.d.ts.map +1 -0
  35. package/dist/generators/class-schema.d.ts +342 -0
  36. package/dist/generators/class-schema.d.ts.map +1 -0
  37. package/dist/generators/discovered-schema.d.ts +152 -0
  38. package/dist/generators/discovered-schema.d.ts.map +1 -0
  39. package/dist/generators/method-schema.d.ts +65 -0
  40. package/dist/generators/method-schema.d.ts.map +1 -0
  41. package/dist/generators/mixed-authoring.d.ts +52 -0
  42. package/dist/generators/mixed-authoring.d.ts.map +1 -0
  43. package/dist/index.cjs +6293 -0
  44. package/dist/index.cjs.map +1 -0
  45. package/dist/index.d.ts +50 -8
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +6268 -107
  48. package/dist/index.js.map +1 -1
  49. package/dist/internals.cjs +5480 -0
  50. package/dist/internals.cjs.map +1 -0
  51. package/dist/internals.d.ts +32 -0
  52. package/dist/internals.d.ts.map +1 -0
  53. package/dist/internals.js +5461 -0
  54. package/dist/internals.js.map +1 -0
  55. package/dist/json-schema/generator.d.ts +27 -6
  56. package/dist/json-schema/generator.d.ts.map +1 -1
  57. package/dist/json-schema/ir-generator.d.ts +144 -0
  58. package/dist/json-schema/ir-generator.d.ts.map +1 -0
  59. package/dist/json-schema/schema.d.ts +23 -0
  60. package/dist/json-schema/schema.d.ts.map +1 -0
  61. package/dist/json-schema/types.d.ts +76 -2
  62. package/dist/json-schema/types.d.ts.map +1 -1
  63. package/dist/metadata/collision-guards.d.ts +3 -0
  64. package/dist/metadata/collision-guards.d.ts.map +1 -0
  65. package/dist/metadata/index.d.ts +7 -0
  66. package/dist/metadata/index.d.ts.map +1 -0
  67. package/dist/metadata/policy.d.ts +11 -0
  68. package/dist/metadata/policy.d.ts.map +1 -0
  69. package/dist/metadata/resolve.d.ts +20 -0
  70. package/dist/metadata/resolve.d.ts.map +1 -0
  71. package/dist/static-build.d.ts +61 -0
  72. package/dist/static-build.d.ts.map +1 -0
  73. package/dist/ui-schema/generator.d.ts +18 -2
  74. package/dist/ui-schema/generator.d.ts.map +1 -1
  75. package/dist/ui-schema/ir-generator.d.ts +54 -0
  76. package/dist/ui-schema/ir-generator.d.ts.map +1 -0
  77. package/dist/ui-schema/schema.d.ts +429 -0
  78. package/dist/ui-schema/schema.d.ts.map +1 -0
  79. package/dist/ui-schema/types.d.ts +179 -35
  80. package/dist/ui-schema/types.d.ts.map +1 -1
  81. package/dist/validate/constraint-validator.d.ts +85 -0
  82. package/dist/validate/constraint-validator.d.ts.map +1 -0
  83. package/dist/validate/index.d.ts +9 -0
  84. package/dist/validate/index.d.ts.map +1 -0
  85. package/package.json +31 -11
  86. package/dist/__tests__/cli.test.d.ts +0 -2
  87. package/dist/__tests__/cli.test.d.ts.map +0 -1
  88. package/dist/__tests__/cli.test.js +0 -178
  89. package/dist/__tests__/cli.test.js.map +0 -1
  90. package/dist/__tests__/edge-cases.test.d.ts +0 -7
  91. package/dist/__tests__/edge-cases.test.d.ts.map +0 -1
  92. package/dist/__tests__/edge-cases.test.js +0 -217
  93. package/dist/__tests__/edge-cases.test.js.map +0 -1
  94. package/dist/__tests__/generator.test.d.ts +0 -2
  95. package/dist/__tests__/generator.test.d.ts.map +0 -1
  96. package/dist/__tests__/generator.test.js +0 -225
  97. package/dist/__tests__/generator.test.js.map +0 -1
  98. package/dist/__tests__/integration.test.d.ts +0 -8
  99. package/dist/__tests__/integration.test.d.ts.map +0 -1
  100. package/dist/__tests__/integration.test.js +0 -163
  101. package/dist/__tests__/integration.test.js.map +0 -1
  102. package/dist/__tests__/write-schemas.test.d.ts +0 -2
  103. package/dist/__tests__/write-schemas.test.d.ts.map +0 -1
  104. package/dist/__tests__/write-schemas.test.js +0 -196
  105. package/dist/__tests__/write-schemas.test.js.map +0 -1
  106. package/dist/json-schema/generator.js +0 -161
  107. package/dist/json-schema/generator.js.map +0 -1
  108. package/dist/json-schema/types.js +0 -7
  109. package/dist/json-schema/types.js.map +0 -1
  110. package/dist/ui-schema/generator.js +0 -150
  111. package/dist/ui-schema/generator.js.map +0 -1
  112. package/dist/ui-schema/types.js +0 -8
  113. package/dist/ui-schema/types.js.map +0 -1
@@ -0,0 +1,1861 @@
1
+ // src/canonicalize/chain-dsl-canonicalizer.ts
2
+ import { IR_VERSION, _getFormSpecMetadataPolicy } from "@formspec/core/internals";
3
+
4
+ // src/metadata/policy.ts
5
+ var NOOP_INFLECT = () => "";
6
+ function normalizePluralization(input) {
7
+ if (input?.mode === "infer-if-missing") {
8
+ return {
9
+ mode: "infer-if-missing",
10
+ infer: () => "",
11
+ inflect: input.inflect
12
+ };
13
+ }
14
+ if (input?.mode === "require-explicit") {
15
+ return {
16
+ mode: "require-explicit",
17
+ infer: () => "",
18
+ inflect: NOOP_INFLECT
19
+ };
20
+ }
21
+ return {
22
+ mode: "disabled",
23
+ infer: () => "",
24
+ inflect: NOOP_INFLECT
25
+ };
26
+ }
27
+ function normalizeScalarPolicy(input) {
28
+ if (input?.mode === "infer-if-missing") {
29
+ return {
30
+ mode: "infer-if-missing",
31
+ infer: input.infer,
32
+ pluralization: normalizePluralization(input.pluralization)
33
+ };
34
+ }
35
+ if (input?.mode === "require-explicit") {
36
+ return {
37
+ mode: "require-explicit",
38
+ infer: () => "",
39
+ pluralization: normalizePluralization(input.pluralization)
40
+ };
41
+ }
42
+ return {
43
+ mode: "disabled",
44
+ infer: () => "",
45
+ pluralization: normalizePluralization(input?.pluralization)
46
+ };
47
+ }
48
+ function normalizeDeclarationPolicy(input) {
49
+ return {
50
+ apiName: normalizeScalarPolicy(input?.apiName),
51
+ displayName: normalizeScalarPolicy(input?.displayName)
52
+ };
53
+ }
54
+ function normalizeMetadataPolicy(input) {
55
+ return {
56
+ type: normalizeDeclarationPolicy(input?.type),
57
+ field: normalizeDeclarationPolicy(input?.field),
58
+ method: normalizeDeclarationPolicy(input?.method)
59
+ };
60
+ }
61
+ function getDeclarationMetadataPolicy(policy, declarationKind) {
62
+ return policy[declarationKind];
63
+ }
64
+ function makeMetadataContext(surface, declarationKind, logicalName, buildContext) {
65
+ return {
66
+ surface,
67
+ declarationKind,
68
+ logicalName,
69
+ ...buildContext !== void 0 && { buildContext }
70
+ };
71
+ }
72
+
73
+ // src/metadata/resolve.ts
74
+ function toExplicitScalar(value) {
75
+ return value !== void 0 && value.trim() !== "" ? { value, source: "explicit" } : void 0;
76
+ }
77
+ function toExplicitResolvedMetadata(explicit) {
78
+ if (explicit === void 0) {
79
+ return void 0;
80
+ }
81
+ const apiName = toExplicitScalar(explicit.apiName);
82
+ const displayName = toExplicitScalar(explicit.displayName);
83
+ const apiNamePlural = toExplicitScalar(explicit.apiNamePlural);
84
+ const displayNamePlural = toExplicitScalar(explicit.displayNamePlural);
85
+ const metadata = {
86
+ ...apiName !== void 0 && { apiName },
87
+ ...displayName !== void 0 && { displayName },
88
+ ...apiNamePlural !== void 0 && { apiNamePlural },
89
+ ...displayNamePlural !== void 0 && { displayNamePlural }
90
+ };
91
+ return Object.keys(metadata).length > 0 ? metadata : void 0;
92
+ }
93
+ function resolveScalar(current, policy, context, metadataLabel) {
94
+ if (current !== void 0) {
95
+ return current;
96
+ }
97
+ if (policy.mode === "require-explicit") {
98
+ throw new Error(
99
+ `Metadata policy requires explicit ${metadataLabel} for ${context.declarationKind} "${context.logicalName}" on the ${context.surface} surface.`
100
+ );
101
+ }
102
+ if (policy.mode !== "infer-if-missing") {
103
+ return void 0;
104
+ }
105
+ const inferredValue = policy.infer(context);
106
+ return inferredValue.trim() !== "" ? { value: inferredValue, source: "inferred" } : void 0;
107
+ }
108
+ function resolvePlural(current, singular, policy, context, metadataLabel) {
109
+ if (current !== void 0) {
110
+ return current;
111
+ }
112
+ if (policy.mode === "require-explicit") {
113
+ throw new Error(
114
+ `Metadata policy requires explicit ${metadataLabel} for ${context.declarationKind} "${context.logicalName}" on the ${context.surface} surface.`
115
+ );
116
+ }
117
+ if (singular === void 0 || policy.mode !== "infer-if-missing") {
118
+ return void 0;
119
+ }
120
+ const pluralValue = policy.inflect({ ...context, singular: singular.value });
121
+ return pluralValue.trim() !== "" ? { value: pluralValue, source: "inferred" } : void 0;
122
+ }
123
+ function resolveResolvedMetadata(current, policy, context) {
124
+ const apiName = resolveScalar(current?.apiName, policy.apiName, context, "apiName");
125
+ const displayName = resolveScalar(
126
+ current?.displayName,
127
+ policy.displayName,
128
+ context,
129
+ "displayName"
130
+ );
131
+ const apiNamePlural = resolvePlural(
132
+ current?.apiNamePlural,
133
+ apiName,
134
+ policy.apiName.pluralization,
135
+ context,
136
+ "apiNamePlural"
137
+ );
138
+ const displayNamePlural = resolvePlural(
139
+ current?.displayNamePlural,
140
+ displayName,
141
+ policy.displayName.pluralization,
142
+ context,
143
+ "displayNamePlural"
144
+ );
145
+ if (apiName === void 0 && displayName === void 0 && apiNamePlural === void 0 && displayNamePlural === void 0) {
146
+ return void 0;
147
+ }
148
+ return {
149
+ ...apiName !== void 0 && { apiName },
150
+ ...displayName !== void 0 && { displayName },
151
+ ...apiNamePlural !== void 0 && { apiNamePlural },
152
+ ...displayNamePlural !== void 0 && { displayNamePlural }
153
+ };
154
+ }
155
+ function resolveMetadata(explicit, policy, context) {
156
+ return resolveResolvedMetadata(toExplicitResolvedMetadata(explicit), policy, context);
157
+ }
158
+ function getSerializedName(logicalName, metadata) {
159
+ return metadata?.apiName?.value ?? logicalName;
160
+ }
161
+ function getDisplayName(metadata) {
162
+ return metadata?.displayName?.value;
163
+ }
164
+
165
+ // src/canonicalize/chain-dsl-canonicalizer.ts
166
+ var CHAIN_DSL_PROVENANCE = {
167
+ surface: "chain-dsl",
168
+ file: "",
169
+ line: 0,
170
+ column: 0
171
+ };
172
+ function isGroup(el) {
173
+ return el._type === "group";
174
+ }
175
+ function isConditional(el) {
176
+ return el._type === "conditional";
177
+ }
178
+ function isField(el) {
179
+ return el._type === "field";
180
+ }
181
+ function canonicalizeChainDSL(form, options) {
182
+ const metadataPolicy = normalizeMetadataPolicy(
183
+ options?.metadata ?? _getFormSpecMetadataPolicy(form)
184
+ );
185
+ return {
186
+ kind: "form-ir",
187
+ irVersion: IR_VERSION,
188
+ elements: canonicalizeElements(form.elements, metadataPolicy),
189
+ rootAnnotations: [],
190
+ typeRegistry: {},
191
+ provenance: CHAIN_DSL_PROVENANCE
192
+ };
193
+ }
194
+ function canonicalizeElements(elements, metadataPolicy) {
195
+ return elements.map((element) => canonicalizeElement(element, metadataPolicy));
196
+ }
197
+ function canonicalizeElement(element, metadataPolicy) {
198
+ if (isField(element)) {
199
+ return canonicalizeField(element, metadataPolicy);
200
+ }
201
+ if (isGroup(element)) {
202
+ return canonicalizeGroup(element, metadataPolicy);
203
+ }
204
+ if (isConditional(element)) {
205
+ return canonicalizeConditional(element, metadataPolicy);
206
+ }
207
+ const _exhaustive = element;
208
+ throw new Error(`Unknown element type: ${JSON.stringify(_exhaustive)}`);
209
+ }
210
+ function canonicalizeField(field, metadataPolicy) {
211
+ switch (field._field) {
212
+ case "text":
213
+ return canonicalizeTextField(field, metadataPolicy);
214
+ case "number":
215
+ return canonicalizeNumberField(field, metadataPolicy);
216
+ case "boolean":
217
+ return canonicalizeBooleanField(field, metadataPolicy);
218
+ case "enum":
219
+ return canonicalizeStaticEnumField(field, metadataPolicy);
220
+ case "dynamic_enum":
221
+ return canonicalizeDynamicEnumField(field, metadataPolicy);
222
+ case "dynamic_schema":
223
+ return canonicalizeDynamicSchemaField(field, metadataPolicy);
224
+ case "array":
225
+ return canonicalizeArrayField(field, metadataPolicy);
226
+ case "object":
227
+ return canonicalizeObjectField(field, metadataPolicy);
228
+ default: {
229
+ const _exhaustive = field;
230
+ throw new Error(`Unknown field type: ${JSON.stringify(_exhaustive)}`);
231
+ }
232
+ }
233
+ }
234
+ function canonicalizeTextField(field, metadataPolicy) {
235
+ const type = { kind: "primitive", primitiveKind: "string" };
236
+ const constraints = [];
237
+ if (field.minLength !== void 0) {
238
+ const c = {
239
+ kind: "constraint",
240
+ constraintKind: "minLength",
241
+ value: field.minLength,
242
+ provenance: CHAIN_DSL_PROVENANCE
243
+ };
244
+ constraints.push(c);
245
+ }
246
+ if (field.maxLength !== void 0) {
247
+ const c = {
248
+ kind: "constraint",
249
+ constraintKind: "maxLength",
250
+ value: field.maxLength,
251
+ provenance: CHAIN_DSL_PROVENANCE
252
+ };
253
+ constraints.push(c);
254
+ }
255
+ if (field.pattern !== void 0) {
256
+ const c = {
257
+ kind: "constraint",
258
+ constraintKind: "pattern",
259
+ pattern: field.pattern,
260
+ provenance: CHAIN_DSL_PROVENANCE
261
+ };
262
+ constraints.push(c);
263
+ }
264
+ return buildFieldNode(
265
+ field.name,
266
+ resolveFieldMetadata(field.name, field, metadataPolicy),
267
+ type,
268
+ field.required,
269
+ buildAnnotations(getExplicitDisplayName(field), field.placeholder),
270
+ constraints
271
+ );
272
+ }
273
+ function canonicalizeNumberField(field, metadataPolicy) {
274
+ const type = { kind: "primitive", primitiveKind: "number" };
275
+ const constraints = [];
276
+ if (field.min !== void 0) {
277
+ const c = {
278
+ kind: "constraint",
279
+ constraintKind: "minimum",
280
+ value: field.min,
281
+ provenance: CHAIN_DSL_PROVENANCE
282
+ };
283
+ constraints.push(c);
284
+ }
285
+ if (field.max !== void 0) {
286
+ const c = {
287
+ kind: "constraint",
288
+ constraintKind: "maximum",
289
+ value: field.max,
290
+ provenance: CHAIN_DSL_PROVENANCE
291
+ };
292
+ constraints.push(c);
293
+ }
294
+ if (field.multipleOf !== void 0) {
295
+ const c = {
296
+ kind: "constraint",
297
+ constraintKind: "multipleOf",
298
+ value: field.multipleOf,
299
+ provenance: CHAIN_DSL_PROVENANCE
300
+ };
301
+ constraints.push(c);
302
+ }
303
+ return buildFieldNode(
304
+ field.name,
305
+ resolveFieldMetadata(field.name, field, metadataPolicy),
306
+ type,
307
+ field.required,
308
+ buildAnnotations(getExplicitDisplayName(field)),
309
+ constraints
310
+ );
311
+ }
312
+ function canonicalizeBooleanField(field, metadataPolicy) {
313
+ const type = { kind: "primitive", primitiveKind: "boolean" };
314
+ return buildFieldNode(
315
+ field.name,
316
+ resolveFieldMetadata(field.name, field, metadataPolicy),
317
+ type,
318
+ field.required,
319
+ buildAnnotations(getExplicitDisplayName(field))
320
+ );
321
+ }
322
+ function canonicalizeStaticEnumField(field, metadataPolicy) {
323
+ const members = field.options.map((opt) => {
324
+ if (typeof opt === "string") {
325
+ return { value: opt };
326
+ }
327
+ return { value: opt.id, displayName: opt.label };
328
+ });
329
+ const type = { kind: "enum", members };
330
+ return buildFieldNode(
331
+ field.name,
332
+ resolveFieldMetadata(field.name, field, metadataPolicy),
333
+ type,
334
+ field.required,
335
+ buildAnnotations(getExplicitDisplayName(field))
336
+ );
337
+ }
338
+ function canonicalizeDynamicEnumField(field, metadataPolicy) {
339
+ const type = {
340
+ kind: "dynamic",
341
+ dynamicKind: "enum",
342
+ sourceKey: field.source,
343
+ parameterFields: field.params ? [...field.params] : []
344
+ };
345
+ return buildFieldNode(
346
+ field.name,
347
+ resolveFieldMetadata(field.name, field, metadataPolicy),
348
+ type,
349
+ field.required,
350
+ buildAnnotations(getExplicitDisplayName(field))
351
+ );
352
+ }
353
+ function canonicalizeDynamicSchemaField(field, metadataPolicy) {
354
+ const type = {
355
+ kind: "dynamic",
356
+ dynamicKind: "schema",
357
+ sourceKey: field.schemaSource,
358
+ parameterFields: []
359
+ };
360
+ return buildFieldNode(
361
+ field.name,
362
+ resolveFieldMetadata(field.name, field, metadataPolicy),
363
+ type,
364
+ field.required,
365
+ buildAnnotations(getExplicitDisplayName(field))
366
+ );
367
+ }
368
+ function canonicalizeArrayField(field, metadataPolicy) {
369
+ const itemProperties = buildObjectProperties(field.items, metadataPolicy);
370
+ const itemsType = {
371
+ kind: "object",
372
+ properties: itemProperties,
373
+ additionalProperties: true
374
+ };
375
+ const type = { kind: "array", items: itemsType };
376
+ const constraints = [];
377
+ if (field.minItems !== void 0) {
378
+ const c = {
379
+ kind: "constraint",
380
+ constraintKind: "minItems",
381
+ value: field.minItems,
382
+ provenance: CHAIN_DSL_PROVENANCE
383
+ };
384
+ constraints.push(c);
385
+ }
386
+ if (field.maxItems !== void 0) {
387
+ const c = {
388
+ kind: "constraint",
389
+ constraintKind: "maxItems",
390
+ value: field.maxItems,
391
+ provenance: CHAIN_DSL_PROVENANCE
392
+ };
393
+ constraints.push(c);
394
+ }
395
+ return buildFieldNode(
396
+ field.name,
397
+ resolveFieldMetadata(field.name, field, metadataPolicy),
398
+ type,
399
+ field.required,
400
+ buildAnnotations(getExplicitDisplayName(field)),
401
+ constraints
402
+ );
403
+ }
404
+ function canonicalizeObjectField(field, metadataPolicy) {
405
+ const properties = buildObjectProperties(field.properties, metadataPolicy);
406
+ const type = {
407
+ kind: "object",
408
+ properties,
409
+ additionalProperties: true
410
+ };
411
+ return buildFieldNode(
412
+ field.name,
413
+ resolveFieldMetadata(field.name, field, metadataPolicy),
414
+ type,
415
+ field.required,
416
+ buildAnnotations(getExplicitDisplayName(field))
417
+ );
418
+ }
419
+ function canonicalizeGroup(g, metadataPolicy) {
420
+ return {
421
+ kind: "group",
422
+ label: g.label,
423
+ elements: canonicalizeElements(g.elements, metadataPolicy),
424
+ provenance: CHAIN_DSL_PROVENANCE
425
+ };
426
+ }
427
+ function canonicalizeConditional(c, metadataPolicy) {
428
+ return {
429
+ kind: "conditional",
430
+ fieldName: c.field,
431
+ // Conditional values from the chain DSL are JSON-serializable primitives
432
+ // (strings, numbers, booleans) produced by the `is()` predicate helper.
433
+ value: assertJsonValue(c.value),
434
+ elements: canonicalizeElements(c.elements, metadataPolicy),
435
+ provenance: CHAIN_DSL_PROVENANCE
436
+ };
437
+ }
438
+ function assertJsonValue(v) {
439
+ if (v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
440
+ return v;
441
+ }
442
+ if (Array.isArray(v)) {
443
+ return v.map(assertJsonValue);
444
+ }
445
+ if (typeof v === "object") {
446
+ const result = {};
447
+ for (const [key, val] of Object.entries(v)) {
448
+ result[key] = assertJsonValue(val);
449
+ }
450
+ return result;
451
+ }
452
+ throw new TypeError(`Conditional value is not a valid JsonValue: ${typeof v}`);
453
+ }
454
+ function buildFieldNode(name, metadata, type, required, annotations, constraints = []) {
455
+ return {
456
+ kind: "field",
457
+ name,
458
+ ...metadata !== void 0 && { metadata },
459
+ type,
460
+ required: required === true,
461
+ constraints,
462
+ annotations,
463
+ provenance: CHAIN_DSL_PROVENANCE
464
+ };
465
+ }
466
+ function buildAnnotations(label, placeholder) {
467
+ const annotations = [];
468
+ if (label !== void 0) {
469
+ const a = {
470
+ kind: "annotation",
471
+ annotationKind: "displayName",
472
+ value: label,
473
+ provenance: CHAIN_DSL_PROVENANCE
474
+ };
475
+ annotations.push(a);
476
+ }
477
+ if (placeholder !== void 0) {
478
+ const a = {
479
+ kind: "annotation",
480
+ annotationKind: "placeholder",
481
+ value: placeholder,
482
+ provenance: CHAIN_DSL_PROVENANCE
483
+ };
484
+ annotations.push(a);
485
+ }
486
+ return annotations;
487
+ }
488
+ function buildObjectProperties(elements, metadataPolicy, insideConditional = false) {
489
+ const properties = [];
490
+ for (const el of elements) {
491
+ if (isField(el)) {
492
+ const fieldNode = canonicalizeField(el, metadataPolicy);
493
+ properties.push({
494
+ name: fieldNode.name,
495
+ ...fieldNode.metadata !== void 0 && { metadata: fieldNode.metadata },
496
+ type: fieldNode.type,
497
+ // Fields inside a conditional branch are always optional in the
498
+ // data schema, regardless of their `required` flag — the condition
499
+ // may not be met, so the field may be absent.
500
+ optional: insideConditional || !fieldNode.required,
501
+ constraints: fieldNode.constraints,
502
+ annotations: fieldNode.annotations,
503
+ provenance: CHAIN_DSL_PROVENANCE
504
+ });
505
+ } else if (isGroup(el)) {
506
+ properties.push(...buildObjectProperties(el.elements, metadataPolicy, insideConditional));
507
+ } else if (isConditional(el)) {
508
+ properties.push(...buildObjectProperties(el.elements, metadataPolicy, true));
509
+ }
510
+ }
511
+ return properties;
512
+ }
513
+ function getExplicitDisplayName(field) {
514
+ if (field.label !== void 0 && field.displayName !== void 0) {
515
+ throw new Error('Chain DSL fields cannot specify both "label" and "displayName".');
516
+ }
517
+ return field.displayName ?? field.label;
518
+ }
519
+ function resolveFieldMetadata(logicalName, field, metadataPolicy) {
520
+ const displayName = getExplicitDisplayName(field);
521
+ return resolveMetadata(
522
+ {
523
+ ...field.apiName !== void 0 && { apiName: field.apiName },
524
+ ...displayName !== void 0 && { displayName }
525
+ },
526
+ getDeclarationMetadataPolicy(metadataPolicy, "field"),
527
+ makeMetadataContext("chain-dsl", "field", logicalName)
528
+ );
529
+ }
530
+
531
+ // src/canonicalize/tsdoc-canonicalizer.ts
532
+ import { IR_VERSION as IR_VERSION2 } from "@formspec/core/internals";
533
+
534
+ // src/metadata/collision-guards.ts
535
+ function assertUniqueSerializedNames(entries, scope) {
536
+ const seen = /* @__PURE__ */ new Map();
537
+ for (const entry of entries) {
538
+ const previous = seen.get(entry.serializedName);
539
+ if (previous !== void 0) {
540
+ if (previous.logicalName === entry.logicalName && previous.category === entry.category) {
541
+ continue;
542
+ }
543
+ throw new Error(
544
+ `Serialized name collision in ${scope}: ${previous.category} "${previous.logicalName}" and ${entry.category} "${entry.logicalName}" both resolve to "${entry.serializedName}".`
545
+ );
546
+ }
547
+ seen.set(entry.serializedName, entry);
548
+ }
549
+ }
550
+ function collectFlattenedFields(elements) {
551
+ const fields = [];
552
+ for (const element of elements) {
553
+ switch (element.kind) {
554
+ case "field":
555
+ fields.push(element);
556
+ break;
557
+ case "group":
558
+ case "conditional":
559
+ fields.push(...collectFlattenedFields(element.elements));
560
+ break;
561
+ default: {
562
+ const exhaustive = element;
563
+ void exhaustive;
564
+ }
565
+ }
566
+ }
567
+ return fields;
568
+ }
569
+ function validateObjectProperties(properties, scope) {
570
+ assertUniqueSerializedNames(
571
+ properties.map((property) => ({
572
+ logicalName: property.name,
573
+ serializedName: getSerializedName(property.name, property.metadata),
574
+ category: "object property"
575
+ })),
576
+ scope
577
+ );
578
+ for (const property of properties) {
579
+ validateTypeNode(
580
+ property.type,
581
+ `${scope}.${getSerializedName(property.name, property.metadata)}`
582
+ );
583
+ }
584
+ }
585
+ function validateTypeNode(type, scope) {
586
+ switch (type.kind) {
587
+ case "array":
588
+ validateTypeNode(type.items, `${scope}[]`);
589
+ break;
590
+ case "object":
591
+ validateObjectProperties(type.properties, scope);
592
+ break;
593
+ case "record":
594
+ validateTypeNode(type.valueType, `${scope}.*`);
595
+ break;
596
+ case "union":
597
+ type.members.forEach((member, index) => {
598
+ validateTypeNode(member, `${scope}|${String(index)}`);
599
+ });
600
+ break;
601
+ case "reference":
602
+ case "primitive":
603
+ case "enum":
604
+ case "dynamic":
605
+ case "custom":
606
+ break;
607
+ default: {
608
+ const exhaustive = type;
609
+ void exhaustive;
610
+ }
611
+ }
612
+ }
613
+ function validateTypeDefinitions(typeRegistry) {
614
+ const definitions = Object.values(typeRegistry);
615
+ assertUniqueSerializedNames(
616
+ definitions.map((definition) => ({
617
+ logicalName: definition.name,
618
+ serializedName: getSerializedName(definition.name, definition.metadata),
619
+ category: "type definition"
620
+ })),
621
+ "$defs"
622
+ );
623
+ for (const definition of definitions) {
624
+ validateTypeDefinition(definition);
625
+ }
626
+ }
627
+ function validateTypeDefinition(definition) {
628
+ validateTypeNode(
629
+ definition.type,
630
+ `type "${getSerializedName(definition.name, definition.metadata)}"`
631
+ );
632
+ }
633
+ function assertNoSerializedNameCollisions(ir) {
634
+ assertUniqueSerializedNames(
635
+ collectFlattenedFields(ir.elements).map((field) => ({
636
+ logicalName: field.name,
637
+ serializedName: getSerializedName(field.name, field.metadata),
638
+ category: "field"
639
+ })),
640
+ "form root"
641
+ );
642
+ for (const field of collectFlattenedFields(ir.elements)) {
643
+ validateTypeNode(field.type, `field "${getSerializedName(field.name, field.metadata)}"`);
644
+ }
645
+ validateTypeDefinitions(ir.typeRegistry);
646
+ }
647
+
648
+ // src/json-schema/ir-generator.ts
649
+ function makeContext(options) {
650
+ const vendorPrefix = options?.vendorPrefix ?? "x-formspec";
651
+ if (!vendorPrefix.startsWith("x-")) {
652
+ throw new Error(
653
+ `Invalid vendorPrefix "${vendorPrefix}". Extension JSON Schema keywords must start with "x-".`
654
+ );
655
+ }
656
+ return {
657
+ defs: {},
658
+ typeNameMap: {},
659
+ typeRegistry: {},
660
+ extensionRegistry: options?.extensionRegistry,
661
+ vendorPrefix
662
+ };
663
+ }
664
+ function generateJsonSchemaFromIR(ir, options) {
665
+ assertNoSerializedNameCollisions(ir);
666
+ const ctx = {
667
+ ...makeContext(options),
668
+ typeRegistry: ir.typeRegistry,
669
+ typeNameMap: Object.fromEntries(
670
+ Object.entries(ir.typeRegistry).map(([name, typeDef]) => [
671
+ name,
672
+ getSerializedName(name, typeDef.metadata)
673
+ ])
674
+ )
675
+ };
676
+ for (const [name, typeDef] of Object.entries(ir.typeRegistry)) {
677
+ const schemaName = ctx.typeNameMap[name] ?? name;
678
+ ctx.defs[schemaName] = generateTypeNode(typeDef.type, ctx);
679
+ applyResolvedMetadata(ctx.defs[schemaName], typeDef.metadata);
680
+ if (typeDef.constraints && typeDef.constraints.length > 0) {
681
+ applyConstraints(ctx.defs[schemaName], typeDef.constraints, ctx);
682
+ }
683
+ if (typeDef.annotations && typeDef.annotations.length > 0) {
684
+ applyAnnotations(ctx.defs[schemaName], typeDef.annotations, ctx);
685
+ }
686
+ }
687
+ const properties = {};
688
+ const required = [];
689
+ collectFields(ir.elements, properties, required, ctx);
690
+ const uniqueRequired = [...new Set(required)];
691
+ const result = {
692
+ $schema: "https://json-schema.org/draft/2020-12/schema",
693
+ type: "object",
694
+ properties,
695
+ ...uniqueRequired.length > 0 && { required: uniqueRequired }
696
+ };
697
+ applyResolvedMetadata(result, ir.metadata);
698
+ if (ir.annotations && ir.annotations.length > 0) {
699
+ applyAnnotations(result, ir.annotations, ctx);
700
+ }
701
+ if (Object.keys(ctx.defs).length > 0) {
702
+ result.$defs = ctx.defs;
703
+ }
704
+ return result;
705
+ }
706
+ function collectFields(elements, properties, required, ctx) {
707
+ for (const element of elements) {
708
+ switch (element.kind) {
709
+ case "field":
710
+ properties[getSerializedFieldName(element)] = generateFieldSchema(element, ctx);
711
+ if (element.required) {
712
+ required.push(getSerializedFieldName(element));
713
+ }
714
+ break;
715
+ case "group":
716
+ collectFields(element.elements, properties, required, ctx);
717
+ break;
718
+ case "conditional":
719
+ collectFields(element.elements, properties, required, ctx);
720
+ break;
721
+ default: {
722
+ const _exhaustive = element;
723
+ void _exhaustive;
724
+ }
725
+ }
726
+ }
727
+ }
728
+ function generateFieldSchema(field, ctx) {
729
+ const schema = generateTypeNode(field.type, ctx);
730
+ const itemStringSchema = schema.type === "array" && schema.items?.type === "string" ? schema.items : void 0;
731
+ const directConstraints = [];
732
+ const itemConstraints = [];
733
+ const pathConstraints = [];
734
+ for (const c of field.constraints) {
735
+ if (c.path) {
736
+ pathConstraints.push(c);
737
+ } else if (itemStringSchema !== void 0 && isStringItemConstraint(c)) {
738
+ itemConstraints.push(c);
739
+ } else {
740
+ directConstraints.push(c);
741
+ }
742
+ }
743
+ applyConstraints(schema, directConstraints, ctx);
744
+ if (itemStringSchema !== void 0) {
745
+ applyConstraints(itemStringSchema, itemConstraints, ctx);
746
+ }
747
+ const rootAnnotations = [];
748
+ const itemAnnotations = [];
749
+ for (const annotation of field.annotations) {
750
+ if (itemStringSchema !== void 0 && annotation.annotationKind === "format") {
751
+ itemAnnotations.push(annotation);
752
+ } else {
753
+ rootAnnotations.push(annotation);
754
+ }
755
+ }
756
+ applyResolvedMetadata(schema, field.metadata);
757
+ applyAnnotations(schema, rootAnnotations, ctx);
758
+ if (itemStringSchema !== void 0) {
759
+ applyAnnotations(itemStringSchema, itemAnnotations, ctx);
760
+ }
761
+ if (pathConstraints.length === 0) {
762
+ return schema;
763
+ }
764
+ return applyPathTargetedConstraints(schema, pathConstraints, ctx, field.type);
765
+ }
766
+ function isStringItemConstraint(constraint) {
767
+ switch (constraint.constraintKind) {
768
+ case "minLength":
769
+ case "maxLength":
770
+ case "pattern":
771
+ return true;
772
+ default:
773
+ return false;
774
+ }
775
+ }
776
+ function applyPathTargetedConstraints(schema, pathConstraints, ctx, typeNode) {
777
+ if (schema.type === "array" && schema.items) {
778
+ const referencedType = typeNode?.kind === "reference" ? resolveReferencedType(typeNode, ctx) : void 0;
779
+ const nestedType = typeNode?.kind === "array" ? typeNode.items : referencedType?.kind === "array" ? referencedType.items : void 0;
780
+ schema.items = applyPathTargetedConstraints(schema.items, pathConstraints, ctx, nestedType);
781
+ return schema;
782
+ }
783
+ const propertyOverrides = buildPropertyOverrides(pathConstraints, typeNode, ctx);
784
+ const nullableValueBranch = getNullableUnionValueSchema(schema);
785
+ if (nullableValueBranch !== void 0) {
786
+ const updatedNullableValueBranch = applyPathTargetedConstraints(
787
+ nullableValueBranch,
788
+ pathConstraints,
789
+ ctx,
790
+ resolveTraversableTypeNode(typeNode, ctx)
791
+ );
792
+ if (schema.oneOf !== void 0) {
793
+ schema.oneOf = schema.oneOf.map(
794
+ (branch) => branch === nullableValueBranch ? updatedNullableValueBranch : branch
795
+ );
796
+ }
797
+ return schema;
798
+ }
799
+ if (schema.$ref) {
800
+ const { $ref, ...rest } = schema;
801
+ const refPart = { $ref };
802
+ const overridePart = {
803
+ properties: propertyOverrides,
804
+ ...rest
805
+ };
806
+ return { allOf: [refPart, overridePart] };
807
+ }
808
+ if (schema.type === "object" && schema.properties) {
809
+ const missingOverrides = {};
810
+ for (const [target, overrideSchema] of Object.entries(propertyOverrides)) {
811
+ if (schema.properties[target]) {
812
+ mergeSchemaOverride(schema.properties[target], overrideSchema);
813
+ } else {
814
+ missingOverrides[target] = overrideSchema;
815
+ }
816
+ }
817
+ if (Object.keys(missingOverrides).length === 0) {
818
+ return schema;
819
+ }
820
+ return {
821
+ allOf: [schema, { properties: missingOverrides }]
822
+ };
823
+ }
824
+ if (schema.allOf) {
825
+ schema.allOf = [...schema.allOf, { properties: propertyOverrides }];
826
+ return schema;
827
+ }
828
+ return schema;
829
+ }
830
+ function generateTypeNode(type, ctx) {
831
+ switch (type.kind) {
832
+ case "primitive":
833
+ return generatePrimitiveType(type);
834
+ case "enum":
835
+ return generateEnumType(type);
836
+ case "array":
837
+ return generateArrayType(type, ctx);
838
+ case "object":
839
+ return generateObjectType(type, ctx);
840
+ case "record":
841
+ return generateRecordType(type, ctx);
842
+ case "union":
843
+ return generateUnionType(type, ctx);
844
+ case "reference":
845
+ return generateReferenceType(type, ctx);
846
+ case "dynamic":
847
+ return generateDynamicType(type);
848
+ case "custom":
849
+ return generateCustomType(type, ctx);
850
+ default: {
851
+ const _exhaustive = type;
852
+ return _exhaustive;
853
+ }
854
+ }
855
+ }
856
+ function generatePrimitiveType(type) {
857
+ return {
858
+ type: type.primitiveKind === "integer" || type.primitiveKind === "bigint" ? "integer" : type.primitiveKind
859
+ };
860
+ }
861
+ function generateEnumType(type) {
862
+ const hasDisplayNames = type.members.some((m) => m.displayName !== void 0);
863
+ if (hasDisplayNames) {
864
+ return {
865
+ oneOf: type.members.map((m) => {
866
+ const entry = { const: m.value };
867
+ if (m.displayName !== void 0) {
868
+ entry.title = m.displayName;
869
+ }
870
+ return entry;
871
+ })
872
+ };
873
+ }
874
+ return { enum: type.members.map((m) => m.value) };
875
+ }
876
+ function generateArrayType(type, ctx) {
877
+ return {
878
+ type: "array",
879
+ items: generateTypeNode(type.items, ctx)
880
+ };
881
+ }
882
+ function generateObjectType(type, ctx) {
883
+ const properties = {};
884
+ const required = [];
885
+ for (const prop of type.properties) {
886
+ const propertyName = getSerializedObjectPropertyName(prop);
887
+ properties[propertyName] = generatePropertySchema(prop, ctx);
888
+ if (!prop.optional) {
889
+ required.push(propertyName);
890
+ }
891
+ }
892
+ const schema = { type: "object", properties };
893
+ if (required.length > 0) {
894
+ schema.required = required;
895
+ }
896
+ if (!type.additionalProperties) {
897
+ schema.additionalProperties = false;
898
+ }
899
+ return schema;
900
+ }
901
+ function generateRecordType(type, ctx) {
902
+ return {
903
+ type: "object",
904
+ additionalProperties: generateTypeNode(type.valueType, ctx)
905
+ };
906
+ }
907
+ function generatePropertySchema(prop, ctx) {
908
+ const schema = generateTypeNode(prop.type, ctx);
909
+ applyConstraints(schema, prop.constraints, ctx);
910
+ applyResolvedMetadata(schema, prop.metadata);
911
+ applyAnnotations(schema, prop.annotations, ctx);
912
+ return schema;
913
+ }
914
+ function generateUnionType(type, ctx) {
915
+ if (isBooleanUnion(type)) {
916
+ return { type: "boolean" };
917
+ }
918
+ if (isNullableUnion(type)) {
919
+ return {
920
+ oneOf: type.members.map((m) => generateTypeNode(m, ctx))
921
+ };
922
+ }
923
+ return {
924
+ anyOf: type.members.map((m) => generateTypeNode(m, ctx))
925
+ };
926
+ }
927
+ function isBooleanUnion(type) {
928
+ if (type.members.length !== 2) return false;
929
+ const kinds = type.members.map((m) => m.kind);
930
+ return kinds.every((k) => k === "primitive") && type.members.every((m) => m.kind === "primitive" && m.primitiveKind === "boolean");
931
+ }
932
+ function isNullableUnion(type) {
933
+ if (type.members.length !== 2) return false;
934
+ const nullCount = type.members.filter(
935
+ (m) => m.kind === "primitive" && m.primitiveKind === "null"
936
+ ).length;
937
+ return nullCount === 1;
938
+ }
939
+ function generateReferenceType(type, ctx) {
940
+ return { $ref: `#/$defs/${getSerializedTypeName(type.name, ctx)}` };
941
+ }
942
+ function getSerializedFieldName(field) {
943
+ return getSerializedName(field.name, field.metadata);
944
+ }
945
+ function getSerializedObjectPropertyName(property) {
946
+ return getSerializedName(property.name, property.metadata);
947
+ }
948
+ function getSerializedTypeName(logicalName, ctx) {
949
+ return ctx.typeNameMap[logicalName] ?? logicalName;
950
+ }
951
+ function applyResolvedMetadata(schema, metadata) {
952
+ const displayName = getDisplayName(metadata);
953
+ if (displayName !== void 0) {
954
+ schema.title = displayName;
955
+ }
956
+ }
957
+ function resolveReferencedType(type, ctx) {
958
+ return ctx.typeRegistry[type.name]?.type;
959
+ }
960
+ function dereferenceTypeNode(typeNode, ctx) {
961
+ if (typeNode?.kind !== "reference") {
962
+ return typeNode;
963
+ }
964
+ return resolveReferencedType(typeNode, ctx);
965
+ }
966
+ function unwrapNullableTypeNode(typeNode) {
967
+ if (typeNode?.kind !== "union" || !isNullableUnion(typeNode)) {
968
+ return typeNode;
969
+ }
970
+ return typeNode.members.find(
971
+ (member) => !(member.kind === "primitive" && member.primitiveKind === "null")
972
+ );
973
+ }
974
+ function resolveTraversableTypeNode(typeNode, ctx) {
975
+ const dereferenced = dereferenceTypeNode(typeNode, ctx);
976
+ const unwrapped = unwrapNullableTypeNode(dereferenced);
977
+ if (unwrapped !== dereferenced) {
978
+ return resolveTraversableTypeNode(unwrapped, ctx);
979
+ }
980
+ return dereferenced;
981
+ }
982
+ function resolveSerializedPropertyName(logicalName, typeNode, ctx) {
983
+ const effectiveType = resolveTraversableTypeNode(typeNode, ctx);
984
+ if (effectiveType?.kind === "array") {
985
+ return resolveSerializedPropertyName(logicalName, effectiveType.items, ctx);
986
+ }
987
+ if (effectiveType?.kind === "object") {
988
+ const property = effectiveType.properties.find((candidate) => candidate.name === logicalName);
989
+ return property === void 0 ? logicalName : getSerializedObjectPropertyName(property);
990
+ }
991
+ return logicalName;
992
+ }
993
+ function resolveTargetTypeNode(logicalName, typeNode, ctx) {
994
+ const effectiveType = resolveTraversableTypeNode(typeNode, ctx);
995
+ if (effectiveType?.kind === "array") {
996
+ return resolveTargetTypeNode(logicalName, effectiveType.items, ctx);
997
+ }
998
+ if (effectiveType?.kind !== "object") {
999
+ return void 0;
1000
+ }
1001
+ return effectiveType.properties.find((candidate) => candidate.name === logicalName)?.type;
1002
+ }
1003
+ function buildPropertyOverrides(pathConstraints, typeNode, ctx) {
1004
+ const byTarget = /* @__PURE__ */ new Map();
1005
+ for (const constraint of pathConstraints) {
1006
+ const target = constraint.path?.segments[0];
1007
+ if (!target) {
1008
+ continue;
1009
+ }
1010
+ const grouped = byTarget.get(target) ?? [];
1011
+ grouped.push(constraint);
1012
+ byTarget.set(target, grouped);
1013
+ }
1014
+ const overrides = {};
1015
+ for (const [target, constraints] of byTarget) {
1016
+ overrides[resolveSerializedPropertyName(target, typeNode, ctx)] = buildPathOverrideSchema(
1017
+ constraints.map(stripLeadingPathSegment),
1018
+ resolveTargetTypeNode(target, typeNode, ctx),
1019
+ ctx
1020
+ );
1021
+ }
1022
+ return overrides;
1023
+ }
1024
+ function buildPathOverrideSchema(constraints, typeNode, ctx) {
1025
+ const schema = {};
1026
+ const directConstraints = [];
1027
+ const nestedConstraints = [];
1028
+ for (const constraint of constraints) {
1029
+ if (constraint.path === void 0 || constraint.path.segments.length === 0) {
1030
+ directConstraints.push(constraint);
1031
+ } else {
1032
+ nestedConstraints.push(constraint);
1033
+ }
1034
+ }
1035
+ applyConstraints(schema, directConstraints, ctx);
1036
+ if (nestedConstraints.length === 0) {
1037
+ return schema;
1038
+ }
1039
+ const effectiveType = resolveTraversableTypeNode(typeNode, ctx);
1040
+ if (effectiveType?.kind === "array") {
1041
+ schema.items = buildPathOverrideSchema(nestedConstraints, effectiveType.items, ctx);
1042
+ return schema;
1043
+ }
1044
+ schema.properties = buildPropertyOverrides(nestedConstraints, effectiveType, ctx);
1045
+ return schema;
1046
+ }
1047
+ function mergeSchemaOverride(target, override) {
1048
+ const nullableValueBranch = getNullableUnionValueSchema(target);
1049
+ if (nullableValueBranch !== void 0) {
1050
+ mergeSchemaOverride(nullableValueBranch, override);
1051
+ return;
1052
+ }
1053
+ if (override.properties !== void 0) {
1054
+ const mergedProperties = target.properties ?? {};
1055
+ for (const [name, propertyOverride] of Object.entries(override.properties)) {
1056
+ const existing = mergedProperties[name];
1057
+ if (existing === void 0) {
1058
+ mergedProperties[name] = propertyOverride;
1059
+ } else {
1060
+ mergeSchemaOverride(existing, propertyOverride);
1061
+ }
1062
+ }
1063
+ target.properties = mergedProperties;
1064
+ }
1065
+ if (override.items !== void 0) {
1066
+ if (target.items === void 0) {
1067
+ target.items = override.items;
1068
+ } else {
1069
+ mergeSchemaOverride(target.items, override.items);
1070
+ }
1071
+ }
1072
+ for (const [key, value] of Object.entries(override)) {
1073
+ if (key === "properties" || key === "items") {
1074
+ continue;
1075
+ }
1076
+ target[key] = value;
1077
+ }
1078
+ }
1079
+ function stripLeadingPathSegment(constraint) {
1080
+ const segments = constraint.path?.segments;
1081
+ if (segments === void 0 || segments.length === 0) {
1082
+ return constraint;
1083
+ }
1084
+ const [, ...rest] = segments;
1085
+ if (rest.length === 0) {
1086
+ const { path: _path, ...stripped } = constraint;
1087
+ return stripped;
1088
+ }
1089
+ return {
1090
+ ...constraint,
1091
+ path: { segments: rest }
1092
+ };
1093
+ }
1094
+ function getNullableUnionValueSchema(schema) {
1095
+ if (schema.oneOf?.length !== 2) {
1096
+ return void 0;
1097
+ }
1098
+ const valueSchema = schema.oneOf.find((branch) => branch.type !== "null");
1099
+ const nullSchema = schema.oneOf.find((branch) => branch.type === "null");
1100
+ return valueSchema !== void 0 && nullSchema !== void 0 ? valueSchema : void 0;
1101
+ }
1102
+ function generateDynamicType(type) {
1103
+ if (type.dynamicKind === "enum") {
1104
+ const schema = {
1105
+ type: "string",
1106
+ "x-formspec-source": type.sourceKey
1107
+ };
1108
+ if (type.parameterFields.length > 0) {
1109
+ schema["x-formspec-params"] = [...type.parameterFields];
1110
+ }
1111
+ return schema;
1112
+ }
1113
+ return {
1114
+ type: "object",
1115
+ additionalProperties: true,
1116
+ "x-formspec-schemaSource": type.sourceKey
1117
+ };
1118
+ }
1119
+ function applyConstraints(schema, constraints, ctx) {
1120
+ for (const constraint of constraints) {
1121
+ switch (constraint.constraintKind) {
1122
+ case "minimum":
1123
+ schema.minimum = constraint.value;
1124
+ break;
1125
+ case "maximum":
1126
+ schema.maximum = constraint.value;
1127
+ break;
1128
+ case "exclusiveMinimum":
1129
+ schema.exclusiveMinimum = constraint.value;
1130
+ break;
1131
+ case "exclusiveMaximum":
1132
+ schema.exclusiveMaximum = constraint.value;
1133
+ break;
1134
+ case "multipleOf": {
1135
+ const { value } = constraint;
1136
+ if (value === 1 && schema.type === "number") {
1137
+ schema.type = "integer";
1138
+ } else {
1139
+ schema.multipleOf = value;
1140
+ }
1141
+ break;
1142
+ }
1143
+ case "minLength":
1144
+ schema.minLength = constraint.value;
1145
+ break;
1146
+ case "maxLength":
1147
+ schema.maxLength = constraint.value;
1148
+ break;
1149
+ case "minItems":
1150
+ schema.minItems = constraint.value;
1151
+ break;
1152
+ case "maxItems":
1153
+ schema.maxItems = constraint.value;
1154
+ break;
1155
+ case "pattern":
1156
+ schema.pattern = constraint.pattern;
1157
+ break;
1158
+ case "uniqueItems":
1159
+ schema.uniqueItems = constraint.value;
1160
+ break;
1161
+ case "const":
1162
+ schema.const = constraint.value;
1163
+ break;
1164
+ case "allowedMembers":
1165
+ break;
1166
+ case "custom":
1167
+ applyCustomConstraint(schema, constraint, ctx);
1168
+ break;
1169
+ default: {
1170
+ const _exhaustive = constraint;
1171
+ void _exhaustive;
1172
+ }
1173
+ }
1174
+ }
1175
+ }
1176
+ function applyAnnotations(schema, annotations, ctx) {
1177
+ for (const annotation of annotations) {
1178
+ switch (annotation.annotationKind) {
1179
+ case "displayName":
1180
+ schema.title ??= annotation.value;
1181
+ break;
1182
+ case "description":
1183
+ schema.description = annotation.value;
1184
+ break;
1185
+ case "remarks":
1186
+ schema[`${ctx.vendorPrefix}-remarks`] = annotation.value;
1187
+ break;
1188
+ case "defaultValue":
1189
+ schema.default = annotation.value;
1190
+ break;
1191
+ case "format":
1192
+ schema.format = annotation.value;
1193
+ break;
1194
+ case "deprecated":
1195
+ schema.deprecated = true;
1196
+ if (annotation.message !== void 0 && annotation.message !== "") {
1197
+ schema[`${ctx.vendorPrefix}-deprecation-description`] = annotation.message;
1198
+ }
1199
+ break;
1200
+ case "placeholder":
1201
+ break;
1202
+ case "formatHint":
1203
+ break;
1204
+ case "custom":
1205
+ applyCustomAnnotation(schema, annotation, ctx);
1206
+ break;
1207
+ default: {
1208
+ const _exhaustive = annotation;
1209
+ void _exhaustive;
1210
+ }
1211
+ }
1212
+ }
1213
+ }
1214
+ function generateCustomType(type, ctx) {
1215
+ const registration = ctx.extensionRegistry?.findType(type.typeId);
1216
+ if (registration === void 0) {
1217
+ throw new Error(
1218
+ `Cannot generate JSON Schema for custom type "${type.typeId}" without a matching extension registration`
1219
+ );
1220
+ }
1221
+ return registration.toJsonSchema(type.payload, ctx.vendorPrefix);
1222
+ }
1223
+ function applyCustomConstraint(schema, constraint, ctx) {
1224
+ const registration = ctx.extensionRegistry?.findConstraint(constraint.constraintId);
1225
+ if (registration === void 0) {
1226
+ throw new Error(
1227
+ `Cannot generate JSON Schema for custom constraint "${constraint.constraintId}" without a matching extension registration`
1228
+ );
1229
+ }
1230
+ assignVendorPrefixedExtensionKeywords(
1231
+ schema,
1232
+ registration.toJsonSchema(constraint.payload, ctx.vendorPrefix),
1233
+ ctx.vendorPrefix,
1234
+ `custom constraint "${constraint.constraintId}"`
1235
+ );
1236
+ }
1237
+ function applyCustomAnnotation(schema, annotation, ctx) {
1238
+ const registration = ctx.extensionRegistry?.findAnnotation(annotation.annotationId);
1239
+ if (registration === void 0) {
1240
+ throw new Error(
1241
+ `Cannot generate JSON Schema for custom annotation "${annotation.annotationId}" without a matching extension registration`
1242
+ );
1243
+ }
1244
+ if (registration.toJsonSchema === void 0) {
1245
+ return;
1246
+ }
1247
+ assignVendorPrefixedExtensionKeywords(
1248
+ schema,
1249
+ registration.toJsonSchema(annotation.value, ctx.vendorPrefix),
1250
+ ctx.vendorPrefix,
1251
+ `custom annotation "${annotation.annotationId}"`
1252
+ );
1253
+ }
1254
+ function assignVendorPrefixedExtensionKeywords(schema, extensionSchema, vendorPrefix, source) {
1255
+ for (const [key, value] of Object.entries(extensionSchema)) {
1256
+ if (!key.startsWith(`${vendorPrefix}-`)) {
1257
+ throw new Error(
1258
+ `Cannot apply ${source}: extension hooks may only emit "${vendorPrefix}-*" JSON Schema keywords`
1259
+ );
1260
+ }
1261
+ schema[key] = value;
1262
+ }
1263
+ }
1264
+
1265
+ // src/json-schema/generator.ts
1266
+ function generateJsonSchema(form, options) {
1267
+ const ir = canonicalizeChainDSL(
1268
+ form,
1269
+ options?.metadata !== void 0 ? { metadata: options.metadata } : void 0
1270
+ );
1271
+ const internalOptions = options?.vendorPrefix === void 0 ? void 0 : { vendorPrefix: options.vendorPrefix };
1272
+ return generateJsonSchemaFromIR(ir, internalOptions);
1273
+ }
1274
+
1275
+ // src/ui-schema/schema.ts
1276
+ import { z } from "zod";
1277
+ var jsonPointerSchema = z.string();
1278
+ var ruleEffectSchema = z.enum(["SHOW", "HIDE", "ENABLE", "DISABLE"]);
1279
+ var uiSchemaElementTypeSchema = z.enum([
1280
+ "Control",
1281
+ "VerticalLayout",
1282
+ "HorizontalLayout",
1283
+ "Group",
1284
+ "Categorization",
1285
+ "Category",
1286
+ "Label"
1287
+ ]);
1288
+ var ruleConditionSchema = z.lazy(
1289
+ () => z.object({
1290
+ const: z.unknown().optional(),
1291
+ enum: z.array(z.unknown()).readonly().optional(),
1292
+ type: z.string().optional(),
1293
+ not: ruleConditionSchema.optional(),
1294
+ minimum: z.number().optional(),
1295
+ maximum: z.number().optional(),
1296
+ exclusiveMinimum: z.number().optional(),
1297
+ exclusiveMaximum: z.number().optional(),
1298
+ minLength: z.number().optional(),
1299
+ properties: z.record(z.string(), ruleConditionSchema).optional(),
1300
+ required: z.array(z.string()).optional(),
1301
+ allOf: z.array(ruleConditionSchema).optional()
1302
+ }).strict()
1303
+ );
1304
+ var schemaBasedConditionSchema = z.object({
1305
+ scope: jsonPointerSchema,
1306
+ schema: ruleConditionSchema
1307
+ }).strict();
1308
+ var ruleSchema = z.object({
1309
+ effect: ruleEffectSchema,
1310
+ condition: schemaBasedConditionSchema
1311
+ }).strict();
1312
+ var uiSchemaElementSchema = z.lazy(
1313
+ () => z.union([
1314
+ controlSchema,
1315
+ verticalLayoutSchema,
1316
+ horizontalLayoutSchema,
1317
+ groupLayoutSchema,
1318
+ categorizationSchema,
1319
+ categorySchema,
1320
+ labelElementSchema
1321
+ ])
1322
+ );
1323
+ var controlSchema = z.object({
1324
+ type: z.literal("Control"),
1325
+ scope: jsonPointerSchema,
1326
+ label: z.union([z.string(), z.literal(false)]).optional(),
1327
+ rule: ruleSchema.optional(),
1328
+ options: z.record(z.string(), z.unknown()).optional()
1329
+ }).passthrough();
1330
+ var verticalLayoutSchema = z.lazy(
1331
+ () => z.object({
1332
+ type: z.literal("VerticalLayout"),
1333
+ elements: z.array(uiSchemaElementSchema),
1334
+ rule: ruleSchema.optional(),
1335
+ options: z.record(z.string(), z.unknown()).optional()
1336
+ }).passthrough()
1337
+ );
1338
+ var horizontalLayoutSchema = z.lazy(
1339
+ () => z.object({
1340
+ type: z.literal("HorizontalLayout"),
1341
+ elements: z.array(uiSchemaElementSchema),
1342
+ rule: ruleSchema.optional(),
1343
+ options: z.record(z.string(), z.unknown()).optional()
1344
+ }).passthrough()
1345
+ );
1346
+ var groupLayoutSchema = z.lazy(
1347
+ () => z.object({
1348
+ type: z.literal("Group"),
1349
+ label: z.string(),
1350
+ elements: z.array(uiSchemaElementSchema),
1351
+ rule: ruleSchema.optional(),
1352
+ options: z.record(z.string(), z.unknown()).optional()
1353
+ }).passthrough()
1354
+ );
1355
+ var categorySchema = z.lazy(
1356
+ () => z.object({
1357
+ type: z.literal("Category"),
1358
+ label: z.string(),
1359
+ elements: z.array(uiSchemaElementSchema),
1360
+ rule: ruleSchema.optional(),
1361
+ options: z.record(z.string(), z.unknown()).optional()
1362
+ }).passthrough()
1363
+ );
1364
+ var categorizationSchema = z.lazy(
1365
+ () => z.object({
1366
+ type: z.literal("Categorization"),
1367
+ elements: z.array(categorySchema),
1368
+ label: z.string().optional(),
1369
+ rule: ruleSchema.optional(),
1370
+ options: z.record(z.string(), z.unknown()).optional()
1371
+ }).passthrough()
1372
+ );
1373
+ var labelElementSchema = z.object({
1374
+ type: z.literal("Label"),
1375
+ text: z.string(),
1376
+ rule: ruleSchema.optional(),
1377
+ options: z.record(z.string(), z.unknown()).optional()
1378
+ }).passthrough();
1379
+ var uiSchema = z.lazy(
1380
+ () => z.union([verticalLayoutSchema, horizontalLayoutSchema, groupLayoutSchema, categorizationSchema])
1381
+ );
1382
+
1383
+ // src/ui-schema/ir-generator.ts
1384
+ import { z as z2 } from "zod";
1385
+ function parseOrThrow(schema, value, label) {
1386
+ try {
1387
+ return schema.parse(value);
1388
+ } catch (error) {
1389
+ if (error instanceof z2.ZodError) {
1390
+ throw new Error(
1391
+ `Generated ${label} failed validation:
1392
+ ${error.issues.map((i) => ` ${i.path.join(".")}: ${i.message}`).join("\n")}`
1393
+ );
1394
+ }
1395
+ throw error;
1396
+ }
1397
+ }
1398
+ function fieldToScope(fieldName) {
1399
+ return `#/properties/${fieldName}`;
1400
+ }
1401
+ function createShowRule(fieldName, value) {
1402
+ return {
1403
+ effect: "SHOW",
1404
+ condition: {
1405
+ scope: fieldToScope(fieldName),
1406
+ schema: { const: value }
1407
+ }
1408
+ };
1409
+ }
1410
+ function flattenConditionSchema(scope, schema) {
1411
+ if (schema.allOf === void 0) {
1412
+ if (scope === "#") {
1413
+ return [schema];
1414
+ }
1415
+ const fieldName = scope.replace("#/properties/", "");
1416
+ return [
1417
+ {
1418
+ properties: {
1419
+ [fieldName]: schema
1420
+ }
1421
+ }
1422
+ ];
1423
+ }
1424
+ return schema.allOf.flatMap((member) => flattenConditionSchema(scope, member));
1425
+ }
1426
+ function combineRules(parentRule, childRule) {
1427
+ return {
1428
+ effect: "SHOW",
1429
+ condition: {
1430
+ scope: "#",
1431
+ schema: {
1432
+ allOf: [
1433
+ ...flattenConditionSchema(parentRule.condition.scope, parentRule.condition.schema),
1434
+ ...flattenConditionSchema(childRule.condition.scope, childRule.condition.schema)
1435
+ ]
1436
+ }
1437
+ }
1438
+ };
1439
+ }
1440
+ function getFieldDisplayName(field) {
1441
+ const resolvedDisplayName = getDisplayName(field.metadata);
1442
+ if (resolvedDisplayName !== void 0) {
1443
+ return resolvedDisplayName;
1444
+ }
1445
+ return field.annotations.find((annotation) => annotation.annotationKind === "displayName")?.value;
1446
+ }
1447
+ function fieldNodeToControl(field, fieldNameMap, parentRule) {
1448
+ const placeholderAnnotation = field.annotations.find((a) => a.annotationKind === "placeholder");
1449
+ const serializedName = fieldNameMap.get(field.name) ?? getSerializedName(field.name, field.metadata);
1450
+ const displayName = getFieldDisplayName(field);
1451
+ const control = {
1452
+ type: "Control",
1453
+ scope: fieldToScope(serializedName),
1454
+ ...displayName !== void 0 && { label: displayName },
1455
+ ...placeholderAnnotation !== void 0 && {
1456
+ options: { placeholder: placeholderAnnotation.value }
1457
+ },
1458
+ ...parentRule !== void 0 && { rule: parentRule }
1459
+ };
1460
+ return control;
1461
+ }
1462
+ function groupNodeToLayout(group, fieldNameMap, parentRule) {
1463
+ return {
1464
+ type: "Group",
1465
+ label: group.label,
1466
+ elements: irElementsToUiSchema(group.elements, fieldNameMap, parentRule),
1467
+ ...parentRule !== void 0 && { rule: parentRule }
1468
+ };
1469
+ }
1470
+ function irElementsToUiSchema(elements, fieldNameMap, parentRule) {
1471
+ const result = [];
1472
+ for (const element of elements) {
1473
+ switch (element.kind) {
1474
+ case "field": {
1475
+ result.push(fieldNodeToControl(element, fieldNameMap, parentRule));
1476
+ break;
1477
+ }
1478
+ case "group": {
1479
+ result.push(groupNodeToLayout(element, fieldNameMap, parentRule));
1480
+ break;
1481
+ }
1482
+ case "conditional": {
1483
+ const newRule = createShowRule(fieldNameMap.get(element.fieldName) ?? element.fieldName, element.value);
1484
+ const combinedRule = parentRule !== void 0 ? combineRules(parentRule, newRule) : newRule;
1485
+ const childElements = irElementsToUiSchema(element.elements, fieldNameMap, combinedRule);
1486
+ result.push(...childElements);
1487
+ break;
1488
+ }
1489
+ default: {
1490
+ const _exhaustive = element;
1491
+ void _exhaustive;
1492
+ throw new Error("Unhandled IR element kind");
1493
+ }
1494
+ }
1495
+ }
1496
+ return result;
1497
+ }
1498
+ function generateUiSchemaFromIR(ir) {
1499
+ assertNoSerializedNameCollisions(ir);
1500
+ const fieldNameMap = collectFieldNameMap(ir.elements);
1501
+ const result = {
1502
+ type: "VerticalLayout",
1503
+ elements: irElementsToUiSchema(ir.elements, fieldNameMap)
1504
+ };
1505
+ return parseOrThrow(uiSchema, result, "UI Schema");
1506
+ }
1507
+ function collectFieldNameMap(elements) {
1508
+ const map = /* @__PURE__ */ new Map();
1509
+ for (const element of elements) {
1510
+ switch (element.kind) {
1511
+ case "field":
1512
+ map.set(element.name, getSerializedName(element.name, element.metadata));
1513
+ break;
1514
+ case "group":
1515
+ case "conditional":
1516
+ for (const [key, value] of collectFieldNameMap(element.elements)) {
1517
+ map.set(key, value);
1518
+ }
1519
+ break;
1520
+ default: {
1521
+ const _exhaustive = element;
1522
+ void _exhaustive;
1523
+ }
1524
+ }
1525
+ }
1526
+ return map;
1527
+ }
1528
+
1529
+ // src/ui-schema/generator.ts
1530
+ function generateUiSchema(form, options) {
1531
+ const ir = canonicalizeChainDSL(
1532
+ form,
1533
+ options?.metadata !== void 0 ? { metadata: options.metadata } : void 0
1534
+ );
1535
+ return generateUiSchemaFromIR(ir);
1536
+ }
1537
+
1538
+ // src/json-schema/types.ts
1539
+ function setSchemaExtension(schema, key, value) {
1540
+ schema[key] = value;
1541
+ }
1542
+ function getSchemaExtension(schema, key) {
1543
+ return schema[key];
1544
+ }
1545
+
1546
+ // src/extensions/registry.ts
1547
+ import {
1548
+ BUILTIN_CONSTRAINT_DEFINITIONS,
1549
+ normalizeConstraintTagName
1550
+ } from "@formspec/core/internals";
1551
+ import {
1552
+ getTagDefinition,
1553
+ normalizeFormSpecTagName
1554
+ } from "@formspec/analysis/internal";
1555
+ var BUILTIN_METADATA_TAGS = /* @__PURE__ */ new Set(["apiName", "displayName"]);
1556
+ function buildConstraintTagSources(extensions) {
1557
+ return extensions.map((extension) => ({
1558
+ extensionId: extension.extensionId,
1559
+ ...extension.constraintTags !== void 0 ? {
1560
+ constraintTags: extension.constraintTags.map((tag) => ({
1561
+ tagName: normalizeFormSpecTagName(tag.tagName)
1562
+ }))
1563
+ } : {}
1564
+ }));
1565
+ }
1566
+ function createExtensionRegistry(extensions) {
1567
+ const reservedTagSources = buildConstraintTagSources(extensions);
1568
+ const typeMap = /* @__PURE__ */ new Map();
1569
+ const typeNameMap = /* @__PURE__ */ new Map();
1570
+ const constraintMap = /* @__PURE__ */ new Map();
1571
+ const constraintTagMap = /* @__PURE__ */ new Map();
1572
+ const builtinBroadeningMap = /* @__PURE__ */ new Map();
1573
+ const annotationMap = /* @__PURE__ */ new Map();
1574
+ const metadataSlotMap = /* @__PURE__ */ new Map();
1575
+ const metadataTagMap = /* @__PURE__ */ new Map();
1576
+ for (const ext of extensions) {
1577
+ if (ext.types !== void 0) {
1578
+ for (const type of ext.types) {
1579
+ const qualifiedId = `${ext.extensionId}/${type.typeName}`;
1580
+ if (typeMap.has(qualifiedId)) {
1581
+ throw new Error(`Duplicate custom type ID: "${qualifiedId}"`);
1582
+ }
1583
+ typeMap.set(qualifiedId, type);
1584
+ for (const sourceTypeName of type.tsTypeNames ?? [type.typeName]) {
1585
+ if (typeNameMap.has(sourceTypeName)) {
1586
+ throw new Error(`Duplicate custom type source name: "${sourceTypeName}"`);
1587
+ }
1588
+ typeNameMap.set(sourceTypeName, {
1589
+ extensionId: ext.extensionId,
1590
+ registration: type
1591
+ });
1592
+ }
1593
+ if (type.builtinConstraintBroadenings !== void 0) {
1594
+ for (const broadening of type.builtinConstraintBroadenings) {
1595
+ const key = `${qualifiedId}:${broadening.tagName}`;
1596
+ if (builtinBroadeningMap.has(key)) {
1597
+ throw new Error(`Duplicate built-in constraint broadening: "${key}"`);
1598
+ }
1599
+ builtinBroadeningMap.set(key, {
1600
+ extensionId: ext.extensionId,
1601
+ registration: broadening
1602
+ });
1603
+ }
1604
+ }
1605
+ }
1606
+ }
1607
+ if (ext.constraints !== void 0) {
1608
+ for (const constraint of ext.constraints) {
1609
+ const qualifiedId = `${ext.extensionId}/${constraint.constraintName}`;
1610
+ if (constraintMap.has(qualifiedId)) {
1611
+ throw new Error(`Duplicate custom constraint ID: "${qualifiedId}"`);
1612
+ }
1613
+ constraintMap.set(qualifiedId, constraint);
1614
+ }
1615
+ }
1616
+ if (ext.constraintTags !== void 0) {
1617
+ for (const tag of ext.constraintTags) {
1618
+ const canonicalTagName = normalizeFormSpecTagName(tag.tagName);
1619
+ if (constraintTagMap.has(canonicalTagName)) {
1620
+ throw new Error(`Duplicate custom constraint tag: "@${canonicalTagName}"`);
1621
+ }
1622
+ constraintTagMap.set(canonicalTagName, {
1623
+ extensionId: ext.extensionId,
1624
+ registration: tag
1625
+ });
1626
+ }
1627
+ }
1628
+ if (ext.annotations !== void 0) {
1629
+ for (const annotation of ext.annotations) {
1630
+ const qualifiedId = `${ext.extensionId}/${annotation.annotationName}`;
1631
+ if (annotationMap.has(qualifiedId)) {
1632
+ throw new Error(`Duplicate custom annotation ID: "${qualifiedId}"`);
1633
+ }
1634
+ annotationMap.set(qualifiedId, annotation);
1635
+ }
1636
+ }
1637
+ if (ext.metadataSlots !== void 0) {
1638
+ for (const slot of ext.metadataSlots) {
1639
+ if (metadataSlotMap.has(slot.slotId)) {
1640
+ throw new Error(`Duplicate metadata slot ID: "${slot.slotId}"`);
1641
+ }
1642
+ metadataSlotMap.set(slot.slotId, true);
1643
+ const canonicalTagName = normalizeFormSpecTagName(slot.tagName);
1644
+ if (slot.allowBare === false && (slot.qualifiers?.length ?? 0) === 0) {
1645
+ throw new Error(
1646
+ `Metadata tag "@${canonicalTagName}" must allow bare usage or declare at least one qualifier.`
1647
+ );
1648
+ }
1649
+ if (metadataTagMap.has(canonicalTagName)) {
1650
+ throw new Error(`Duplicate metadata tag: "@${canonicalTagName}"`);
1651
+ }
1652
+ if (BUILTIN_METADATA_TAGS.has(canonicalTagName)) {
1653
+ throw new Error(
1654
+ `Metadata tag "@${canonicalTagName}" conflicts with built-in metadata tags.`
1655
+ );
1656
+ }
1657
+ if (constraintTagMap.has(canonicalTagName)) {
1658
+ throw new Error(
1659
+ `Metadata tag "@${canonicalTagName}" conflicts with existing FormSpec tag "@${canonicalTagName}".`
1660
+ );
1661
+ }
1662
+ if (Object.hasOwn(BUILTIN_CONSTRAINT_DEFINITIONS, normalizeConstraintTagName(canonicalTagName))) {
1663
+ throw new Error(
1664
+ `Metadata tag "@${canonicalTagName}" conflicts with existing FormSpec tag "@${normalizeConstraintTagName(canonicalTagName)}".`
1665
+ );
1666
+ }
1667
+ const existingTag = getTagDefinition(canonicalTagName, reservedTagSources);
1668
+ if (existingTag !== null) {
1669
+ throw BUILTIN_METADATA_TAGS.has(existingTag.canonicalName) ? new Error(
1670
+ `Metadata tag "@${canonicalTagName}" conflicts with built-in metadata tags.`
1671
+ ) : new Error(
1672
+ `Metadata tag "@${canonicalTagName}" conflicts with existing FormSpec tag "@${existingTag.canonicalName}".`
1673
+ );
1674
+ }
1675
+ metadataTagMap.set(canonicalTagName, true);
1676
+ }
1677
+ }
1678
+ }
1679
+ return {
1680
+ extensions,
1681
+ findType: (typeId) => typeMap.get(typeId),
1682
+ findTypeByName: (typeName) => typeNameMap.get(typeName),
1683
+ findConstraint: (constraintId) => constraintMap.get(constraintId),
1684
+ findConstraintTag: (tagName) => constraintTagMap.get(normalizeFormSpecTagName(tagName)),
1685
+ findBuiltinConstraintBroadening: (typeId, tagName) => builtinBroadeningMap.get(`${typeId}:${tagName}`),
1686
+ findAnnotation: (annotationId) => annotationMap.get(annotationId)
1687
+ };
1688
+ }
1689
+
1690
+ // src/json-schema/schema.ts
1691
+ import { z as z3 } from "zod";
1692
+ var jsonSchemaTypeSchema = z3.enum([
1693
+ "string",
1694
+ "number",
1695
+ "integer",
1696
+ "boolean",
1697
+ "object",
1698
+ "array",
1699
+ "null"
1700
+ ]);
1701
+ var jsonSchema7Schema = z3.lazy(
1702
+ () => z3.object({
1703
+ $schema: z3.string().optional(),
1704
+ $id: z3.string().optional(),
1705
+ $ref: z3.string().optional(),
1706
+ // Metadata
1707
+ title: z3.string().optional(),
1708
+ description: z3.string().optional(),
1709
+ deprecated: z3.boolean().optional(),
1710
+ // Type
1711
+ type: z3.union([jsonSchemaTypeSchema, z3.array(jsonSchemaTypeSchema)]).optional(),
1712
+ // String validation
1713
+ minLength: z3.number().optional(),
1714
+ maxLength: z3.number().optional(),
1715
+ pattern: z3.string().optional(),
1716
+ // Number validation
1717
+ minimum: z3.number().optional(),
1718
+ maximum: z3.number().optional(),
1719
+ exclusiveMinimum: z3.number().optional(),
1720
+ exclusiveMaximum: z3.number().optional(),
1721
+ // Enum
1722
+ enum: z3.array(z3.union([z3.string(), z3.number(), z3.boolean(), z3.null()])).readonly().optional(),
1723
+ const: z3.union([z3.string(), z3.number(), z3.boolean(), z3.null()]).optional(),
1724
+ // Object
1725
+ properties: z3.record(z3.string(), jsonSchema7Schema).optional(),
1726
+ required: z3.array(z3.string()).optional(),
1727
+ additionalProperties: z3.union([z3.boolean(), jsonSchema7Schema]).optional(),
1728
+ // Array
1729
+ items: z3.union([jsonSchema7Schema, z3.array(jsonSchema7Schema)]).optional(),
1730
+ minItems: z3.number().optional(),
1731
+ maxItems: z3.number().optional(),
1732
+ // Composition
1733
+ allOf: z3.array(jsonSchema7Schema).optional(),
1734
+ anyOf: z3.array(jsonSchema7Schema).optional(),
1735
+ oneOf: z3.array(jsonSchema7Schema).optional(),
1736
+ not: jsonSchema7Schema.optional(),
1737
+ // Conditional
1738
+ if: jsonSchema7Schema.optional(),
1739
+ then: jsonSchema7Schema.optional(),
1740
+ else: jsonSchema7Schema.optional(),
1741
+ // Format
1742
+ format: z3.string().optional(),
1743
+ // Default
1744
+ default: z3.unknown().optional(),
1745
+ // FormSpec extensions
1746
+ "x-formspec-source": z3.string().optional(),
1747
+ "x-formspec-params": z3.array(z3.string()).readonly().optional(),
1748
+ "x-formspec-schemaSource": z3.string().optional()
1749
+ }).passthrough()
1750
+ );
1751
+
1752
+ // src/validate/constraint-validator.ts
1753
+ import {
1754
+ analyzeConstraintTargets
1755
+ } from "@formspec/analysis/internal";
1756
+ function validateFieldNode(ctx, field) {
1757
+ const analysis = analyzeConstraintTargets(
1758
+ field.name,
1759
+ field.type,
1760
+ field.constraints,
1761
+ ctx.typeRegistry,
1762
+ ctx.extensionRegistry === void 0 ? void 0 : {
1763
+ extensionRegistry: ctx.extensionRegistry
1764
+ }
1765
+ );
1766
+ ctx.diagnostics.push(...analysis.diagnostics);
1767
+ if (field.type.kind === "object") {
1768
+ for (const property of field.type.properties) {
1769
+ validateObjectProperty(ctx, field.name, property);
1770
+ }
1771
+ }
1772
+ }
1773
+ function validateObjectProperty(ctx, parentName, property) {
1774
+ const qualifiedName = `${parentName}.${property.name}`;
1775
+ const analysis = analyzeConstraintTargets(
1776
+ qualifiedName,
1777
+ property.type,
1778
+ property.constraints,
1779
+ ctx.typeRegistry,
1780
+ ctx.extensionRegistry === void 0 ? void 0 : {
1781
+ extensionRegistry: ctx.extensionRegistry
1782
+ }
1783
+ );
1784
+ ctx.diagnostics.push(...analysis.diagnostics);
1785
+ if (property.type.kind === "object") {
1786
+ for (const nestedProperty of property.type.properties) {
1787
+ validateObjectProperty(ctx, qualifiedName, nestedProperty);
1788
+ }
1789
+ }
1790
+ }
1791
+ function validateElement(ctx, element) {
1792
+ switch (element.kind) {
1793
+ case "field":
1794
+ validateFieldNode(ctx, element);
1795
+ break;
1796
+ case "group":
1797
+ for (const child of element.elements) {
1798
+ validateElement(ctx, child);
1799
+ }
1800
+ break;
1801
+ case "conditional":
1802
+ for (const child of element.elements) {
1803
+ validateElement(ctx, child);
1804
+ }
1805
+ break;
1806
+ default: {
1807
+ const exhaustive = element;
1808
+ throw new Error(`Unhandled element kind: ${String(exhaustive)}`);
1809
+ }
1810
+ }
1811
+ }
1812
+ function validateIR(ir, options) {
1813
+ const ctx = {
1814
+ diagnostics: [],
1815
+ extensionRegistry: options?.extensionRegistry,
1816
+ typeRegistry: ir.typeRegistry
1817
+ };
1818
+ for (const element of ir.elements) {
1819
+ validateElement(ctx, element);
1820
+ }
1821
+ return {
1822
+ diagnostics: ctx.diagnostics,
1823
+ valid: ctx.diagnostics.every((diagnostic) => diagnostic.severity !== "error")
1824
+ };
1825
+ }
1826
+
1827
+ // src/browser.ts
1828
+ function buildFormSchemas(form, options) {
1829
+ return {
1830
+ jsonSchema: generateJsonSchema(form, options),
1831
+ uiSchema: generateUiSchema(form, options)
1832
+ };
1833
+ }
1834
+ export {
1835
+ buildFormSchemas,
1836
+ canonicalizeChainDSL,
1837
+ categorizationSchema,
1838
+ categorySchema,
1839
+ controlSchema,
1840
+ createExtensionRegistry,
1841
+ generateJsonSchema,
1842
+ generateJsonSchemaFromIR,
1843
+ generateUiSchema,
1844
+ getSchemaExtension,
1845
+ groupLayoutSchema,
1846
+ horizontalLayoutSchema,
1847
+ jsonSchema7Schema,
1848
+ jsonSchemaTypeSchema,
1849
+ labelElementSchema,
1850
+ ruleConditionSchema,
1851
+ ruleEffectSchema,
1852
+ ruleSchema,
1853
+ schemaBasedConditionSchema,
1854
+ setSchemaExtension,
1855
+ uiSchemaElementSchema,
1856
+ uiSchemaElementTypeSchema,
1857
+ uiSchema as uiSchemaSchema,
1858
+ validateIR,
1859
+ verticalLayoutSchema
1860
+ };
1861
+ //# sourceMappingURL=browser.js.map