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