@formspec/build 0.1.0-alpha.5 → 0.1.0-alpha.50

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