@formspec/build 0.1.0-alpha.2 → 0.1.0-alpha.21

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 (177) hide show
  1. package/README.md +120 -0
  2. package/dist/__tests__/alias-chain-propagation.test.d.ts +9 -0
  3. package/dist/__tests__/alias-chain-propagation.test.d.ts.map +1 -0
  4. package/dist/__tests__/chain-dsl-canonicalizer.test.d.ts +2 -0
  5. package/dist/__tests__/chain-dsl-canonicalizer.test.d.ts.map +1 -0
  6. package/dist/__tests__/class-schema.test.d.ts +2 -0
  7. package/dist/__tests__/class-schema.test.d.ts.map +1 -0
  8. package/dist/__tests__/constraint-validator.test.d.ts +2 -0
  9. package/dist/__tests__/constraint-validator.test.d.ts.map +1 -0
  10. package/dist/__tests__/date-extension.integration.test.d.ts +2 -0
  11. package/dist/__tests__/date-extension.integration.test.d.ts.map +1 -0
  12. package/dist/__tests__/extension-api.test.d.ts +2 -0
  13. package/dist/__tests__/extension-api.test.d.ts.map +1 -0
  14. package/dist/__tests__/extension-runtime.integration.test.d.ts +2 -0
  15. package/dist/__tests__/extension-runtime.integration.test.d.ts.map +1 -0
  16. package/dist/__tests__/fixtures/alias-chains.d.ts +37 -0
  17. package/dist/__tests__/fixtures/alias-chains.d.ts.map +1 -0
  18. package/dist/__tests__/fixtures/class-schema-regressions.d.ts +86 -0
  19. package/dist/__tests__/fixtures/class-schema-regressions.d.ts.map +1 -0
  20. package/dist/__tests__/fixtures/edge-cases.d.ts +132 -0
  21. package/dist/__tests__/fixtures/edge-cases.d.ts.map +1 -0
  22. package/dist/__tests__/fixtures/example-a-builtins.d.ts +31 -0
  23. package/dist/__tests__/fixtures/example-a-builtins.d.ts.map +1 -0
  24. package/dist/__tests__/fixtures/example-date-extension.d.ts +12 -0
  25. package/dist/__tests__/fixtures/example-date-extension.d.ts.map +1 -0
  26. package/dist/__tests__/fixtures/example-interface-types.d.ts +107 -0
  27. package/dist/__tests__/fixtures/example-interface-types.d.ts.map +1 -0
  28. package/dist/__tests__/fixtures/example-numeric-extension.d.ts +20 -0
  29. package/dist/__tests__/fixtures/example-numeric-extension.d.ts.map +1 -0
  30. package/dist/__tests__/fixtures/extension-forms.d.ts +7 -0
  31. package/dist/__tests__/fixtures/extension-forms.d.ts.map +1 -0
  32. package/dist/__tests__/fixtures/mixed-authoring-shipping-address.d.ts +31 -0
  33. package/dist/__tests__/fixtures/mixed-authoring-shipping-address.d.ts.map +1 -0
  34. package/dist/__tests__/fixtures/named-primitive-aliases.d.ts +15 -0
  35. package/dist/__tests__/fixtures/named-primitive-aliases.d.ts.map +1 -0
  36. package/dist/__tests__/fixtures/nested-array-path-constraints.d.ts +14 -0
  37. package/dist/__tests__/fixtures/nested-array-path-constraints.d.ts.map +1 -0
  38. package/dist/__tests__/fixtures/sample-forms.d.ts +65 -0
  39. package/dist/__tests__/fixtures/sample-forms.d.ts.map +1 -0
  40. package/dist/__tests__/generate-schemas.test.d.ts +2 -0
  41. package/dist/__tests__/generate-schemas.test.d.ts.map +1 -0
  42. package/dist/__tests__/guards.test.d.ts +2 -0
  43. package/dist/__tests__/guards.test.d.ts.map +1 -0
  44. package/dist/__tests__/ir-analyzer.test.d.ts +11 -0
  45. package/dist/__tests__/ir-analyzer.test.d.ts.map +1 -0
  46. package/dist/__tests__/ir-jsdoc-constraints.test.d.ts +12 -0
  47. package/dist/__tests__/ir-jsdoc-constraints.test.d.ts.map +1 -0
  48. package/dist/__tests__/ir-json-schema-generator.test.d.ts +11 -0
  49. package/dist/__tests__/ir-json-schema-generator.test.d.ts.map +1 -0
  50. package/dist/__tests__/ir-ui-schema-generator.test.d.ts +2 -0
  51. package/dist/__tests__/ir-ui-schema-generator.test.d.ts.map +1 -0
  52. package/dist/__tests__/mixed-authoring.test.d.ts +2 -0
  53. package/dist/__tests__/mixed-authoring.test.d.ts.map +1 -0
  54. package/dist/__tests__/numeric-extension.integration.test.d.ts +2 -0
  55. package/dist/__tests__/numeric-extension.integration.test.d.ts.map +1 -0
  56. package/dist/__tests__/parity/fixtures/address/chain-dsl.d.ts +9 -0
  57. package/dist/__tests__/parity/fixtures/address/chain-dsl.d.ts.map +1 -0
  58. package/dist/__tests__/parity/fixtures/address/expected-ir.d.ts +9 -0
  59. package/dist/__tests__/parity/fixtures/address/expected-ir.d.ts.map +1 -0
  60. package/dist/__tests__/parity/fixtures/address/tsdoc.d.ts +19 -0
  61. package/dist/__tests__/parity/fixtures/address/tsdoc.d.ts.map +1 -0
  62. package/dist/__tests__/parity/fixtures/plan-status/chain-dsl.d.ts +19 -0
  63. package/dist/__tests__/parity/fixtures/plan-status/chain-dsl.d.ts.map +1 -0
  64. package/dist/__tests__/parity/fixtures/plan-status/expected-ir.d.ts +6 -0
  65. package/dist/__tests__/parity/fixtures/plan-status/expected-ir.d.ts.map +1 -0
  66. package/dist/__tests__/parity/fixtures/plan-status/tsdoc.d.ts +17 -0
  67. package/dist/__tests__/parity/fixtures/plan-status/tsdoc.d.ts.map +1 -0
  68. package/dist/__tests__/parity/fixtures/product-config/chain-dsl.d.ts +13 -0
  69. package/dist/__tests__/parity/fixtures/product-config/chain-dsl.d.ts.map +1 -0
  70. package/dist/__tests__/parity/fixtures/product-config/expected-ir.d.ts +9 -0
  71. package/dist/__tests__/parity/fixtures/product-config/expected-ir.d.ts.map +1 -0
  72. package/dist/__tests__/parity/fixtures/product-config/tsdoc.d.ts +28 -0
  73. package/dist/__tests__/parity/fixtures/product-config/tsdoc.d.ts.map +1 -0
  74. package/dist/__tests__/parity/fixtures/usd-cents/chain-dsl.d.ts +9 -0
  75. package/dist/__tests__/parity/fixtures/usd-cents/chain-dsl.d.ts.map +1 -0
  76. package/dist/__tests__/parity/fixtures/usd-cents/expected-ir.d.ts +6 -0
  77. package/dist/__tests__/parity/fixtures/usd-cents/expected-ir.d.ts.map +1 -0
  78. package/dist/__tests__/parity/fixtures/usd-cents/tsdoc.d.ts +19 -0
  79. package/dist/__tests__/parity/fixtures/usd-cents/tsdoc.d.ts.map +1 -0
  80. package/dist/__tests__/parity/fixtures/user-registration/chain-dsl.d.ts +12 -0
  81. package/dist/__tests__/parity/fixtures/user-registration/chain-dsl.d.ts.map +1 -0
  82. package/dist/__tests__/parity/fixtures/user-registration/expected-ir.d.ts +9 -0
  83. package/dist/__tests__/parity/fixtures/user-registration/expected-ir.d.ts.map +1 -0
  84. package/dist/__tests__/parity/fixtures/user-registration/tsdoc.d.ts +19 -0
  85. package/dist/__tests__/parity/fixtures/user-registration/tsdoc.d.ts.map +1 -0
  86. package/dist/__tests__/parity/parity.test.d.ts +18 -0
  87. package/dist/__tests__/parity/parity.test.d.ts.map +1 -0
  88. package/dist/__tests__/parity/utils.d.ts +152 -0
  89. package/dist/__tests__/parity/utils.d.ts.map +1 -0
  90. package/dist/__tests__/path-target-parser.test.d.ts +9 -0
  91. package/dist/__tests__/path-target-parser.test.d.ts.map +1 -0
  92. package/dist/analyzer/class-analyzer.d.ts +100 -0
  93. package/dist/analyzer/class-analyzer.d.ts.map +1 -0
  94. package/dist/analyzer/jsdoc-constraints.d.ts +53 -0
  95. package/dist/analyzer/jsdoc-constraints.d.ts.map +1 -0
  96. package/dist/analyzer/program.d.ts +68 -0
  97. package/dist/analyzer/program.d.ts.map +1 -0
  98. package/dist/analyzer/tsdoc-parser.d.ts +123 -0
  99. package/dist/analyzer/tsdoc-parser.d.ts.map +1 -0
  100. package/dist/browser.cjs +1294 -0
  101. package/dist/browser.cjs.map +1 -0
  102. package/dist/browser.d.ts +73 -0
  103. package/dist/browser.d.ts.map +1 -0
  104. package/dist/browser.js +1245 -0
  105. package/dist/browser.js.map +1 -0
  106. package/dist/build.d.ts +1144 -0
  107. package/dist/canonicalize/chain-dsl-canonicalizer.d.ts +18 -0
  108. package/dist/canonicalize/chain-dsl-canonicalizer.d.ts.map +1 -0
  109. package/dist/canonicalize/index.d.ts +8 -0
  110. package/dist/canonicalize/index.d.ts.map +1 -0
  111. package/dist/canonicalize/tsdoc-canonicalizer.d.ts +34 -0
  112. package/dist/canonicalize/tsdoc-canonicalizer.d.ts.map +1 -0
  113. package/dist/cli.cjs +3859 -0
  114. package/dist/cli.cjs.map +1 -0
  115. package/dist/cli.js +3823 -103
  116. package/dist/cli.js.map +1 -1
  117. package/dist/extensions/index.d.ts +8 -0
  118. package/dist/extensions/index.d.ts.map +1 -0
  119. package/dist/extensions/registry.d.ts +83 -0
  120. package/dist/extensions/registry.d.ts.map +1 -0
  121. package/dist/generators/class-schema.d.ts +111 -0
  122. package/dist/generators/class-schema.d.ts.map +1 -0
  123. package/dist/generators/method-schema.d.ts +65 -0
  124. package/dist/generators/method-schema.d.ts.map +1 -0
  125. package/dist/generators/mixed-authoring.d.ts +51 -0
  126. package/dist/generators/mixed-authoring.d.ts.map +1 -0
  127. package/dist/index.cjs +3624 -0
  128. package/dist/index.cjs.map +1 -0
  129. package/dist/index.d.ts +45 -8
  130. package/dist/index.d.ts.map +1 -1
  131. package/dist/index.js +3584 -106
  132. package/dist/index.js.map +1 -1
  133. package/dist/internals.cjs +3368 -0
  134. package/dist/internals.cjs.map +1 -0
  135. package/dist/internals.d.ts +30 -0
  136. package/dist/internals.d.ts.map +1 -0
  137. package/dist/internals.js +3342 -0
  138. package/dist/internals.js.map +1 -0
  139. package/dist/json-schema/generator.d.ts +20 -5
  140. package/dist/json-schema/generator.d.ts.map +1 -1
  141. package/dist/json-schema/ir-generator.d.ts +114 -0
  142. package/dist/json-schema/ir-generator.d.ts.map +1 -0
  143. package/dist/json-schema/schema.d.ts +23 -0
  144. package/dist/json-schema/schema.d.ts.map +1 -0
  145. package/dist/json-schema/types.d.ts +45 -2
  146. package/dist/json-schema/types.d.ts.map +1 -1
  147. package/dist/ui-schema/generator.d.ts +7 -0
  148. package/dist/ui-schema/generator.d.ts.map +1 -1
  149. package/dist/ui-schema/ir-generator.d.ts +53 -0
  150. package/dist/ui-schema/ir-generator.d.ts.map +1 -0
  151. package/dist/ui-schema/schema.d.ts +434 -0
  152. package/dist/ui-schema/schema.d.ts.map +1 -0
  153. package/dist/ui-schema/types.d.ts +10 -73
  154. package/dist/ui-schema/types.d.ts.map +1 -1
  155. package/dist/validate/constraint-validator.d.ts +23 -0
  156. package/dist/validate/constraint-validator.d.ts.map +1 -0
  157. package/dist/validate/index.d.ts +9 -0
  158. package/dist/validate/index.d.ts.map +1 -0
  159. package/package.json +27 -7
  160. package/dist/__tests__/cli.test.js +0 -178
  161. package/dist/__tests__/cli.test.js.map +0 -1
  162. package/dist/__tests__/edge-cases.test.js +0 -217
  163. package/dist/__tests__/edge-cases.test.js.map +0 -1
  164. package/dist/__tests__/generator.test.js +0 -225
  165. package/dist/__tests__/generator.test.js.map +0 -1
  166. package/dist/__tests__/integration.test.js +0 -163
  167. package/dist/__tests__/integration.test.js.map +0 -1
  168. package/dist/__tests__/write-schemas.test.js +0 -196
  169. package/dist/__tests__/write-schemas.test.js.map +0 -1
  170. package/dist/json-schema/generator.js +0 -161
  171. package/dist/json-schema/generator.js.map +0 -1
  172. package/dist/json-schema/types.js +0 -7
  173. package/dist/json-schema/types.js.map +0 -1
  174. package/dist/ui-schema/generator.js +0 -150
  175. package/dist/ui-schema/generator.js.map +0 -1
  176. package/dist/ui-schema/types.js +0 -8
  177. package/dist/ui-schema/types.js.map +0 -1
package/dist/cli.cjs ADDED
@@ -0,0 +1,3859 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ // src/canonicalize/chain-dsl-canonicalizer.ts
34
+ function isGroup(el) {
35
+ return el._type === "group";
36
+ }
37
+ function isConditional(el) {
38
+ return el._type === "conditional";
39
+ }
40
+ function isField(el) {
41
+ return el._type === "field";
42
+ }
43
+ function canonicalizeChainDSL(form) {
44
+ return {
45
+ kind: "form-ir",
46
+ irVersion: import_core.IR_VERSION,
47
+ elements: canonicalizeElements(form.elements),
48
+ rootAnnotations: [],
49
+ typeRegistry: {},
50
+ provenance: CHAIN_DSL_PROVENANCE
51
+ };
52
+ }
53
+ function canonicalizeElements(elements) {
54
+ return elements.map(canonicalizeElement);
55
+ }
56
+ function canonicalizeElement(element) {
57
+ if (isField(element)) {
58
+ return canonicalizeField(element);
59
+ }
60
+ if (isGroup(element)) {
61
+ return canonicalizeGroup(element);
62
+ }
63
+ if (isConditional(element)) {
64
+ return canonicalizeConditional(element);
65
+ }
66
+ const _exhaustive = element;
67
+ throw new Error(`Unknown element type: ${JSON.stringify(_exhaustive)}`);
68
+ }
69
+ function canonicalizeField(field) {
70
+ switch (field._field) {
71
+ case "text":
72
+ return canonicalizeTextField(field);
73
+ case "number":
74
+ return canonicalizeNumberField(field);
75
+ case "boolean":
76
+ return canonicalizeBooleanField(field);
77
+ case "enum":
78
+ return canonicalizeStaticEnumField(field);
79
+ case "dynamic_enum":
80
+ return canonicalizeDynamicEnumField(field);
81
+ case "dynamic_schema":
82
+ return canonicalizeDynamicSchemaField(field);
83
+ case "array":
84
+ return canonicalizeArrayField(field);
85
+ case "object":
86
+ return canonicalizeObjectField(field);
87
+ default: {
88
+ const _exhaustive = field;
89
+ throw new Error(`Unknown field type: ${JSON.stringify(_exhaustive)}`);
90
+ }
91
+ }
92
+ }
93
+ function canonicalizeTextField(field) {
94
+ const type = { kind: "primitive", primitiveKind: "string" };
95
+ const constraints = [];
96
+ if (field.minLength !== void 0) {
97
+ const c = {
98
+ kind: "constraint",
99
+ constraintKind: "minLength",
100
+ value: field.minLength,
101
+ provenance: CHAIN_DSL_PROVENANCE
102
+ };
103
+ constraints.push(c);
104
+ }
105
+ if (field.maxLength !== void 0) {
106
+ const c = {
107
+ kind: "constraint",
108
+ constraintKind: "maxLength",
109
+ value: field.maxLength,
110
+ provenance: CHAIN_DSL_PROVENANCE
111
+ };
112
+ constraints.push(c);
113
+ }
114
+ if (field.pattern !== void 0) {
115
+ const c = {
116
+ kind: "constraint",
117
+ constraintKind: "pattern",
118
+ pattern: field.pattern,
119
+ provenance: CHAIN_DSL_PROVENANCE
120
+ };
121
+ constraints.push(c);
122
+ }
123
+ return buildFieldNode(
124
+ field.name,
125
+ type,
126
+ field.required,
127
+ buildAnnotations(field.label, field.placeholder),
128
+ constraints
129
+ );
130
+ }
131
+ function canonicalizeNumberField(field) {
132
+ const type = { kind: "primitive", primitiveKind: "number" };
133
+ const constraints = [];
134
+ if (field.min !== void 0) {
135
+ const c = {
136
+ kind: "constraint",
137
+ constraintKind: "minimum",
138
+ value: field.min,
139
+ provenance: CHAIN_DSL_PROVENANCE
140
+ };
141
+ constraints.push(c);
142
+ }
143
+ if (field.max !== void 0) {
144
+ const c = {
145
+ kind: "constraint",
146
+ constraintKind: "maximum",
147
+ value: field.max,
148
+ provenance: CHAIN_DSL_PROVENANCE
149
+ };
150
+ constraints.push(c);
151
+ }
152
+ if (field.multipleOf !== void 0) {
153
+ const c = {
154
+ kind: "constraint",
155
+ constraintKind: "multipleOf",
156
+ value: field.multipleOf,
157
+ provenance: CHAIN_DSL_PROVENANCE
158
+ };
159
+ constraints.push(c);
160
+ }
161
+ return buildFieldNode(
162
+ field.name,
163
+ type,
164
+ field.required,
165
+ buildAnnotations(field.label),
166
+ constraints
167
+ );
168
+ }
169
+ function canonicalizeBooleanField(field) {
170
+ const type = { kind: "primitive", primitiveKind: "boolean" };
171
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
172
+ }
173
+ function canonicalizeStaticEnumField(field) {
174
+ const members = field.options.map((opt) => {
175
+ if (typeof opt === "string") {
176
+ return { value: opt };
177
+ }
178
+ return { value: opt.id, displayName: opt.label };
179
+ });
180
+ const type = { kind: "enum", members };
181
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
182
+ }
183
+ function canonicalizeDynamicEnumField(field) {
184
+ const type = {
185
+ kind: "dynamic",
186
+ dynamicKind: "enum",
187
+ sourceKey: field.source,
188
+ parameterFields: field.params ? [...field.params] : []
189
+ };
190
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
191
+ }
192
+ function canonicalizeDynamicSchemaField(field) {
193
+ const type = {
194
+ kind: "dynamic",
195
+ dynamicKind: "schema",
196
+ sourceKey: field.schemaSource,
197
+ parameterFields: []
198
+ };
199
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
200
+ }
201
+ function canonicalizeArrayField(field) {
202
+ const itemProperties = buildObjectProperties(field.items);
203
+ const itemsType = {
204
+ kind: "object",
205
+ properties: itemProperties,
206
+ additionalProperties: true
207
+ };
208
+ const type = { kind: "array", items: itemsType };
209
+ const constraints = [];
210
+ if (field.minItems !== void 0) {
211
+ const c = {
212
+ kind: "constraint",
213
+ constraintKind: "minItems",
214
+ value: field.minItems,
215
+ provenance: CHAIN_DSL_PROVENANCE
216
+ };
217
+ constraints.push(c);
218
+ }
219
+ if (field.maxItems !== void 0) {
220
+ const c = {
221
+ kind: "constraint",
222
+ constraintKind: "maxItems",
223
+ value: field.maxItems,
224
+ provenance: CHAIN_DSL_PROVENANCE
225
+ };
226
+ constraints.push(c);
227
+ }
228
+ return buildFieldNode(
229
+ field.name,
230
+ type,
231
+ field.required,
232
+ buildAnnotations(field.label),
233
+ constraints
234
+ );
235
+ }
236
+ function canonicalizeObjectField(field) {
237
+ const properties = buildObjectProperties(field.properties);
238
+ const type = {
239
+ kind: "object",
240
+ properties,
241
+ additionalProperties: true
242
+ };
243
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
244
+ }
245
+ function canonicalizeGroup(g) {
246
+ return {
247
+ kind: "group",
248
+ label: g.label,
249
+ elements: canonicalizeElements(g.elements),
250
+ provenance: CHAIN_DSL_PROVENANCE
251
+ };
252
+ }
253
+ function canonicalizeConditional(c) {
254
+ return {
255
+ kind: "conditional",
256
+ fieldName: c.field,
257
+ // Conditional values from the chain DSL are JSON-serializable primitives
258
+ // (strings, numbers, booleans) produced by the `is()` predicate helper.
259
+ value: assertJsonValue(c.value),
260
+ elements: canonicalizeElements(c.elements),
261
+ provenance: CHAIN_DSL_PROVENANCE
262
+ };
263
+ }
264
+ function assertJsonValue(v) {
265
+ if (v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
266
+ return v;
267
+ }
268
+ if (Array.isArray(v)) {
269
+ return v.map(assertJsonValue);
270
+ }
271
+ if (typeof v === "object") {
272
+ const result = {};
273
+ for (const [key, val] of Object.entries(v)) {
274
+ result[key] = assertJsonValue(val);
275
+ }
276
+ return result;
277
+ }
278
+ throw new TypeError(`Conditional value is not a valid JsonValue: ${typeof v}`);
279
+ }
280
+ function buildFieldNode(name, type, required, annotations, constraints = []) {
281
+ return {
282
+ kind: "field",
283
+ name,
284
+ type,
285
+ required: required === true,
286
+ constraints,
287
+ annotations,
288
+ provenance: CHAIN_DSL_PROVENANCE
289
+ };
290
+ }
291
+ function buildAnnotations(label, placeholder) {
292
+ const annotations = [];
293
+ if (label !== void 0) {
294
+ const a = {
295
+ kind: "annotation",
296
+ annotationKind: "displayName",
297
+ value: label,
298
+ provenance: CHAIN_DSL_PROVENANCE
299
+ };
300
+ annotations.push(a);
301
+ }
302
+ if (placeholder !== void 0) {
303
+ const a = {
304
+ kind: "annotation",
305
+ annotationKind: "placeholder",
306
+ value: placeholder,
307
+ provenance: CHAIN_DSL_PROVENANCE
308
+ };
309
+ annotations.push(a);
310
+ }
311
+ return annotations;
312
+ }
313
+ function buildObjectProperties(elements, insideConditional = false) {
314
+ const properties = [];
315
+ for (const el of elements) {
316
+ if (isField(el)) {
317
+ const fieldNode = canonicalizeField(el);
318
+ properties.push({
319
+ name: fieldNode.name,
320
+ type: fieldNode.type,
321
+ // Fields inside a conditional branch are always optional in the
322
+ // data schema, regardless of their `required` flag — the condition
323
+ // may not be met, so the field may be absent.
324
+ optional: insideConditional || !fieldNode.required,
325
+ constraints: fieldNode.constraints,
326
+ annotations: fieldNode.annotations,
327
+ provenance: CHAIN_DSL_PROVENANCE
328
+ });
329
+ } else if (isGroup(el)) {
330
+ properties.push(...buildObjectProperties(el.elements, insideConditional));
331
+ } else if (isConditional(el)) {
332
+ properties.push(...buildObjectProperties(el.elements, true));
333
+ }
334
+ }
335
+ return properties;
336
+ }
337
+ var import_core, CHAIN_DSL_PROVENANCE;
338
+ var init_chain_dsl_canonicalizer = __esm({
339
+ "src/canonicalize/chain-dsl-canonicalizer.ts"() {
340
+ "use strict";
341
+ import_core = require("@formspec/core");
342
+ CHAIN_DSL_PROVENANCE = {
343
+ surface: "chain-dsl",
344
+ file: "",
345
+ line: 0,
346
+ column: 0
347
+ };
348
+ }
349
+ });
350
+
351
+ // src/canonicalize/tsdoc-canonicalizer.ts
352
+ function canonicalizeTSDoc(analysis, source) {
353
+ const file = source?.file ?? "";
354
+ const provenance = {
355
+ surface: "tsdoc",
356
+ file,
357
+ line: 1,
358
+ column: 0
359
+ };
360
+ const elements = assembleElements(analysis.fields, analysis.fieldLayouts, provenance);
361
+ return {
362
+ kind: "form-ir",
363
+ irVersion: import_core2.IR_VERSION,
364
+ elements,
365
+ typeRegistry: analysis.typeRegistry,
366
+ ...analysis.annotations !== void 0 && analysis.annotations.length > 0 && { rootAnnotations: analysis.annotations },
367
+ ...analysis.annotations !== void 0 && analysis.annotations.length > 0 && { annotations: analysis.annotations },
368
+ provenance
369
+ };
370
+ }
371
+ function assembleElements(fields, layouts, provenance) {
372
+ const elements = [];
373
+ const groupMap = /* @__PURE__ */ new Map();
374
+ const topLevelOrder = [];
375
+ for (let i = 0; i < fields.length; i++) {
376
+ const field = fields[i];
377
+ const layout = layouts[i];
378
+ if (!field || !layout) continue;
379
+ const element = wrapInConditional(field, layout, provenance);
380
+ if (layout.groupLabel !== void 0) {
381
+ const label = layout.groupLabel;
382
+ let groupElements = groupMap.get(label);
383
+ if (!groupElements) {
384
+ groupElements = [];
385
+ groupMap.set(label, groupElements);
386
+ topLevelOrder.push({ type: "group", label });
387
+ }
388
+ groupElements.push(element);
389
+ } else {
390
+ topLevelOrder.push({ type: "element", element });
391
+ }
392
+ }
393
+ for (const entry of topLevelOrder) {
394
+ if (entry.type === "group") {
395
+ const groupElements = groupMap.get(entry.label);
396
+ if (groupElements) {
397
+ const groupNode = {
398
+ kind: "group",
399
+ label: entry.label,
400
+ elements: groupElements,
401
+ provenance
402
+ };
403
+ elements.push(groupNode);
404
+ groupMap.delete(entry.label);
405
+ }
406
+ } else {
407
+ elements.push(entry.element);
408
+ }
409
+ }
410
+ return elements;
411
+ }
412
+ function wrapInConditional(field, layout, provenance) {
413
+ if (layout.showWhen === void 0) {
414
+ return field;
415
+ }
416
+ const conditional = {
417
+ kind: "conditional",
418
+ fieldName: layout.showWhen.field,
419
+ value: layout.showWhen.value,
420
+ elements: [field],
421
+ provenance
422
+ };
423
+ return conditional;
424
+ }
425
+ var import_core2;
426
+ var init_tsdoc_canonicalizer = __esm({
427
+ "src/canonicalize/tsdoc-canonicalizer.ts"() {
428
+ "use strict";
429
+ import_core2 = require("@formspec/core");
430
+ }
431
+ });
432
+
433
+ // src/canonicalize/index.ts
434
+ var init_canonicalize = __esm({
435
+ "src/canonicalize/index.ts"() {
436
+ "use strict";
437
+ init_chain_dsl_canonicalizer();
438
+ init_tsdoc_canonicalizer();
439
+ }
440
+ });
441
+
442
+ // src/json-schema/ir-generator.ts
443
+ function makeContext(options) {
444
+ const vendorPrefix = options?.vendorPrefix ?? "x-formspec";
445
+ if (!vendorPrefix.startsWith("x-")) {
446
+ throw new Error(
447
+ `Invalid vendorPrefix "${vendorPrefix}". Extension JSON Schema keywords must start with "x-".`
448
+ );
449
+ }
450
+ return {
451
+ defs: {},
452
+ extensionRegistry: options?.extensionRegistry,
453
+ vendorPrefix
454
+ };
455
+ }
456
+ function generateJsonSchemaFromIR(ir, options) {
457
+ const ctx = makeContext(options);
458
+ for (const [name, typeDef] of Object.entries(ir.typeRegistry)) {
459
+ ctx.defs[name] = generateTypeNode(typeDef.type, ctx);
460
+ if (typeDef.constraints && typeDef.constraints.length > 0) {
461
+ applyConstraints(ctx.defs[name], typeDef.constraints, ctx);
462
+ }
463
+ if (typeDef.annotations && typeDef.annotations.length > 0) {
464
+ applyAnnotations(ctx.defs[name], typeDef.annotations, ctx);
465
+ }
466
+ }
467
+ const properties = {};
468
+ const required = [];
469
+ collectFields(ir.elements, properties, required, ctx);
470
+ const uniqueRequired = [...new Set(required)];
471
+ const result = {
472
+ $schema: "https://json-schema.org/draft/2020-12/schema",
473
+ type: "object",
474
+ properties,
475
+ ...uniqueRequired.length > 0 && { required: uniqueRequired }
476
+ };
477
+ if (ir.annotations && ir.annotations.length > 0) {
478
+ applyAnnotations(result, ir.annotations, ctx);
479
+ }
480
+ if (Object.keys(ctx.defs).length > 0) {
481
+ result.$defs = ctx.defs;
482
+ }
483
+ return result;
484
+ }
485
+ function collectFields(elements, properties, required, ctx) {
486
+ for (const element of elements) {
487
+ switch (element.kind) {
488
+ case "field":
489
+ properties[element.name] = generateFieldSchema(element, ctx);
490
+ if (element.required) {
491
+ required.push(element.name);
492
+ }
493
+ break;
494
+ case "group":
495
+ collectFields(element.elements, properties, required, ctx);
496
+ break;
497
+ case "conditional":
498
+ collectFields(element.elements, properties, required, ctx);
499
+ break;
500
+ default: {
501
+ const _exhaustive = element;
502
+ void _exhaustive;
503
+ }
504
+ }
505
+ }
506
+ }
507
+ function generateFieldSchema(field, ctx) {
508
+ const schema = generateTypeNode(field.type, ctx);
509
+ const itemStringSchema = schema.type === "array" && schema.items?.type === "string" ? schema.items : void 0;
510
+ const directConstraints = [];
511
+ const itemConstraints = [];
512
+ const pathConstraints = [];
513
+ for (const c of field.constraints) {
514
+ if (c.path) {
515
+ pathConstraints.push(c);
516
+ } else if (itemStringSchema !== void 0 && isStringItemConstraint(c)) {
517
+ itemConstraints.push(c);
518
+ } else {
519
+ directConstraints.push(c);
520
+ }
521
+ }
522
+ applyConstraints(schema, directConstraints, ctx);
523
+ if (itemStringSchema !== void 0) {
524
+ applyConstraints(itemStringSchema, itemConstraints, ctx);
525
+ }
526
+ const rootAnnotations = [];
527
+ const itemAnnotations = [];
528
+ for (const annotation of field.annotations) {
529
+ if (itemStringSchema !== void 0 && annotation.annotationKind === "format") {
530
+ itemAnnotations.push(annotation);
531
+ } else {
532
+ rootAnnotations.push(annotation);
533
+ }
534
+ }
535
+ applyAnnotations(schema, rootAnnotations, ctx);
536
+ if (itemStringSchema !== void 0) {
537
+ applyAnnotations(itemStringSchema, itemAnnotations, ctx);
538
+ }
539
+ if (pathConstraints.length === 0) {
540
+ return schema;
541
+ }
542
+ return applyPathTargetedConstraints(schema, pathConstraints, ctx);
543
+ }
544
+ function isStringItemConstraint(constraint) {
545
+ switch (constraint.constraintKind) {
546
+ case "minLength":
547
+ case "maxLength":
548
+ case "pattern":
549
+ return true;
550
+ default:
551
+ return false;
552
+ }
553
+ }
554
+ function applyPathTargetedConstraints(schema, pathConstraints, ctx) {
555
+ if (schema.type === "array" && schema.items) {
556
+ schema.items = applyPathTargetedConstraints(schema.items, pathConstraints, ctx);
557
+ return schema;
558
+ }
559
+ const byTarget = /* @__PURE__ */ new Map();
560
+ for (const c of pathConstraints) {
561
+ const target = c.path?.segments[0];
562
+ if (!target) continue;
563
+ const group = byTarget.get(target) ?? [];
564
+ group.push(c);
565
+ byTarget.set(target, group);
566
+ }
567
+ const propertyOverrides = {};
568
+ for (const [target, constraints] of byTarget) {
569
+ const subSchema = {};
570
+ applyConstraints(subSchema, constraints, ctx);
571
+ propertyOverrides[target] = subSchema;
572
+ }
573
+ if (schema.$ref) {
574
+ const { $ref, ...rest } = schema;
575
+ const refPart = { $ref };
576
+ const overridePart = {
577
+ properties: propertyOverrides,
578
+ ...rest
579
+ };
580
+ return { allOf: [refPart, overridePart] };
581
+ }
582
+ if (schema.type === "object" && schema.properties) {
583
+ const missingOverrides = {};
584
+ for (const [target, overrideSchema] of Object.entries(propertyOverrides)) {
585
+ if (schema.properties[target]) {
586
+ Object.assign(schema.properties[target], overrideSchema);
587
+ } else {
588
+ missingOverrides[target] = overrideSchema;
589
+ }
590
+ }
591
+ if (Object.keys(missingOverrides).length === 0) {
592
+ return schema;
593
+ }
594
+ return {
595
+ allOf: [schema, { properties: missingOverrides }]
596
+ };
597
+ }
598
+ if (schema.allOf) {
599
+ schema.allOf = [...schema.allOf, { properties: propertyOverrides }];
600
+ return schema;
601
+ }
602
+ return schema;
603
+ }
604
+ function generateTypeNode(type, ctx) {
605
+ switch (type.kind) {
606
+ case "primitive":
607
+ return generatePrimitiveType(type);
608
+ case "enum":
609
+ return generateEnumType(type);
610
+ case "array":
611
+ return generateArrayType(type, ctx);
612
+ case "object":
613
+ return generateObjectType(type, ctx);
614
+ case "record":
615
+ return generateRecordType(type, ctx);
616
+ case "union":
617
+ return generateUnionType(type, ctx);
618
+ case "reference":
619
+ return generateReferenceType(type);
620
+ case "dynamic":
621
+ return generateDynamicType(type);
622
+ case "custom":
623
+ return generateCustomType(type, ctx);
624
+ default: {
625
+ const _exhaustive = type;
626
+ return _exhaustive;
627
+ }
628
+ }
629
+ }
630
+ function generatePrimitiveType(type) {
631
+ return {
632
+ type: type.primitiveKind === "integer" || type.primitiveKind === "bigint" ? "integer" : type.primitiveKind
633
+ };
634
+ }
635
+ function generateEnumType(type) {
636
+ const hasDisplayNames = type.members.some((m) => m.displayName !== void 0);
637
+ if (hasDisplayNames) {
638
+ return {
639
+ oneOf: type.members.map((m) => {
640
+ const entry = { const: m.value };
641
+ if (m.displayName !== void 0) {
642
+ entry.title = m.displayName;
643
+ }
644
+ return entry;
645
+ })
646
+ };
647
+ }
648
+ return { enum: type.members.map((m) => m.value) };
649
+ }
650
+ function generateArrayType(type, ctx) {
651
+ return {
652
+ type: "array",
653
+ items: generateTypeNode(type.items, ctx)
654
+ };
655
+ }
656
+ function generateObjectType(type, ctx) {
657
+ const properties = {};
658
+ const required = [];
659
+ for (const prop of type.properties) {
660
+ properties[prop.name] = generatePropertySchema(prop, ctx);
661
+ if (!prop.optional) {
662
+ required.push(prop.name);
663
+ }
664
+ }
665
+ const schema = { type: "object", properties };
666
+ if (required.length > 0) {
667
+ schema.required = required;
668
+ }
669
+ if (!type.additionalProperties) {
670
+ schema.additionalProperties = false;
671
+ }
672
+ return schema;
673
+ }
674
+ function generateRecordType(type, ctx) {
675
+ return {
676
+ type: "object",
677
+ additionalProperties: generateTypeNode(type.valueType, ctx)
678
+ };
679
+ }
680
+ function generatePropertySchema(prop, ctx) {
681
+ const schema = generateTypeNode(prop.type, ctx);
682
+ applyConstraints(schema, prop.constraints, ctx);
683
+ applyAnnotations(schema, prop.annotations, ctx);
684
+ return schema;
685
+ }
686
+ function generateUnionType(type, ctx) {
687
+ if (isBooleanUnion(type)) {
688
+ return { type: "boolean" };
689
+ }
690
+ if (isNullableUnion(type)) {
691
+ return {
692
+ oneOf: type.members.map((m) => generateTypeNode(m, ctx))
693
+ };
694
+ }
695
+ return {
696
+ anyOf: type.members.map((m) => generateTypeNode(m, ctx))
697
+ };
698
+ }
699
+ function isBooleanUnion(type) {
700
+ if (type.members.length !== 2) return false;
701
+ const kinds = type.members.map((m) => m.kind);
702
+ return kinds.every((k) => k === "primitive") && type.members.every((m) => m.kind === "primitive" && m.primitiveKind === "boolean");
703
+ }
704
+ function isNullableUnion(type) {
705
+ if (type.members.length !== 2) return false;
706
+ const nullCount = type.members.filter(
707
+ (m) => m.kind === "primitive" && m.primitiveKind === "null"
708
+ ).length;
709
+ return nullCount === 1;
710
+ }
711
+ function generateReferenceType(type) {
712
+ return { $ref: `#/$defs/${type.name}` };
713
+ }
714
+ function generateDynamicType(type) {
715
+ if (type.dynamicKind === "enum") {
716
+ const schema = {
717
+ type: "string",
718
+ "x-formspec-source": type.sourceKey
719
+ };
720
+ if (type.parameterFields.length > 0) {
721
+ schema["x-formspec-params"] = [...type.parameterFields];
722
+ }
723
+ return schema;
724
+ }
725
+ return {
726
+ type: "object",
727
+ additionalProperties: true,
728
+ "x-formspec-schemaSource": type.sourceKey
729
+ };
730
+ }
731
+ function applyConstraints(schema, constraints, ctx) {
732
+ for (const constraint of constraints) {
733
+ switch (constraint.constraintKind) {
734
+ case "minimum":
735
+ schema.minimum = constraint.value;
736
+ break;
737
+ case "maximum":
738
+ schema.maximum = constraint.value;
739
+ break;
740
+ case "exclusiveMinimum":
741
+ schema.exclusiveMinimum = constraint.value;
742
+ break;
743
+ case "exclusiveMaximum":
744
+ schema.exclusiveMaximum = constraint.value;
745
+ break;
746
+ case "multipleOf": {
747
+ const { value } = constraint;
748
+ if (value === 1 && schema.type === "number") {
749
+ schema.type = "integer";
750
+ } else {
751
+ schema.multipleOf = value;
752
+ }
753
+ break;
754
+ }
755
+ case "minLength":
756
+ schema.minLength = constraint.value;
757
+ break;
758
+ case "maxLength":
759
+ schema.maxLength = constraint.value;
760
+ break;
761
+ case "minItems":
762
+ schema.minItems = constraint.value;
763
+ break;
764
+ case "maxItems":
765
+ schema.maxItems = constraint.value;
766
+ break;
767
+ case "pattern":
768
+ schema.pattern = constraint.pattern;
769
+ break;
770
+ case "uniqueItems":
771
+ schema.uniqueItems = constraint.value;
772
+ break;
773
+ case "const":
774
+ schema.const = constraint.value;
775
+ break;
776
+ case "allowedMembers":
777
+ break;
778
+ case "custom":
779
+ applyCustomConstraint(schema, constraint, ctx);
780
+ break;
781
+ default: {
782
+ const _exhaustive = constraint;
783
+ void _exhaustive;
784
+ }
785
+ }
786
+ }
787
+ }
788
+ function applyAnnotations(schema, annotations, ctx) {
789
+ for (const annotation of annotations) {
790
+ switch (annotation.annotationKind) {
791
+ case "displayName":
792
+ schema.title = annotation.value;
793
+ break;
794
+ case "description":
795
+ schema.description = annotation.value;
796
+ break;
797
+ case "remarks":
798
+ schema[`${ctx.vendorPrefix}-remarks`] = annotation.value;
799
+ break;
800
+ case "defaultValue":
801
+ schema.default = annotation.value;
802
+ break;
803
+ case "format":
804
+ schema.format = annotation.value;
805
+ break;
806
+ case "deprecated":
807
+ schema.deprecated = true;
808
+ if (annotation.message !== void 0 && annotation.message !== "") {
809
+ schema[`${ctx.vendorPrefix}-deprecation-description`] = annotation.message;
810
+ }
811
+ break;
812
+ case "placeholder":
813
+ break;
814
+ case "formatHint":
815
+ break;
816
+ case "custom":
817
+ applyCustomAnnotation(schema, annotation, ctx);
818
+ break;
819
+ default: {
820
+ const _exhaustive = annotation;
821
+ void _exhaustive;
822
+ }
823
+ }
824
+ }
825
+ }
826
+ function generateCustomType(type, ctx) {
827
+ const registration = ctx.extensionRegistry?.findType(type.typeId);
828
+ if (registration === void 0) {
829
+ throw new Error(
830
+ `Cannot generate JSON Schema for custom type "${type.typeId}" without a matching extension registration`
831
+ );
832
+ }
833
+ return registration.toJsonSchema(type.payload, ctx.vendorPrefix);
834
+ }
835
+ function applyCustomConstraint(schema, constraint, ctx) {
836
+ const registration = ctx.extensionRegistry?.findConstraint(constraint.constraintId);
837
+ if (registration === void 0) {
838
+ throw new Error(
839
+ `Cannot generate JSON Schema for custom constraint "${constraint.constraintId}" without a matching extension registration`
840
+ );
841
+ }
842
+ assignVendorPrefixedExtensionKeywords(
843
+ schema,
844
+ registration.toJsonSchema(constraint.payload, ctx.vendorPrefix),
845
+ ctx.vendorPrefix,
846
+ `custom constraint "${constraint.constraintId}"`
847
+ );
848
+ }
849
+ function applyCustomAnnotation(schema, annotation, ctx) {
850
+ const registration = ctx.extensionRegistry?.findAnnotation(annotation.annotationId);
851
+ if (registration === void 0) {
852
+ throw new Error(
853
+ `Cannot generate JSON Schema for custom annotation "${annotation.annotationId}" without a matching extension registration`
854
+ );
855
+ }
856
+ if (registration.toJsonSchema === void 0) {
857
+ return;
858
+ }
859
+ assignVendorPrefixedExtensionKeywords(
860
+ schema,
861
+ registration.toJsonSchema(annotation.value, ctx.vendorPrefix),
862
+ ctx.vendorPrefix,
863
+ `custom annotation "${annotation.annotationId}"`
864
+ );
865
+ }
866
+ function assignVendorPrefixedExtensionKeywords(schema, extensionSchema, vendorPrefix, source) {
867
+ for (const [key, value] of Object.entries(extensionSchema)) {
868
+ if (!key.startsWith(`${vendorPrefix}-`)) {
869
+ throw new Error(
870
+ `Cannot apply ${source}: extension hooks may only emit "${vendorPrefix}-*" JSON Schema keywords`
871
+ );
872
+ }
873
+ schema[key] = value;
874
+ }
875
+ }
876
+ var init_ir_generator = __esm({
877
+ "src/json-schema/ir-generator.ts"() {
878
+ "use strict";
879
+ }
880
+ });
881
+
882
+ // src/json-schema/generator.ts
883
+ function generateJsonSchema(form, options) {
884
+ const ir = canonicalizeChainDSL(form);
885
+ return generateJsonSchemaFromIR(ir, options);
886
+ }
887
+ var init_generator = __esm({
888
+ "src/json-schema/generator.ts"() {
889
+ "use strict";
890
+ init_canonicalize();
891
+ init_ir_generator();
892
+ }
893
+ });
894
+
895
+ // src/ui-schema/schema.ts
896
+ var import_zod, jsonPointerSchema, ruleEffectSchema, uiSchemaElementTypeSchema, ruleConditionSchema, schemaBasedConditionSchema, ruleSchema, uiSchemaElementSchema, controlSchema, verticalLayoutSchema, horizontalLayoutSchema, groupLayoutSchema, categorySchema, categorizationSchema, labelElementSchema, uiSchema;
897
+ var init_schema = __esm({
898
+ "src/ui-schema/schema.ts"() {
899
+ "use strict";
900
+ import_zod = require("zod");
901
+ jsonPointerSchema = import_zod.z.string();
902
+ ruleEffectSchema = import_zod.z.enum(["SHOW", "HIDE", "ENABLE", "DISABLE"]);
903
+ uiSchemaElementTypeSchema = import_zod.z.enum([
904
+ "Control",
905
+ "VerticalLayout",
906
+ "HorizontalLayout",
907
+ "Group",
908
+ "Categorization",
909
+ "Category",
910
+ "Label"
911
+ ]);
912
+ ruleConditionSchema = import_zod.z.lazy(
913
+ () => import_zod.z.object({
914
+ const: import_zod.z.unknown().optional(),
915
+ enum: import_zod.z.array(import_zod.z.unknown()).readonly().optional(),
916
+ type: import_zod.z.string().optional(),
917
+ not: ruleConditionSchema.optional(),
918
+ minimum: import_zod.z.number().optional(),
919
+ maximum: import_zod.z.number().optional(),
920
+ exclusiveMinimum: import_zod.z.number().optional(),
921
+ exclusiveMaximum: import_zod.z.number().optional(),
922
+ minLength: import_zod.z.number().optional(),
923
+ properties: import_zod.z.record(import_zod.z.string(), ruleConditionSchema).optional(),
924
+ required: import_zod.z.array(import_zod.z.string()).optional(),
925
+ allOf: import_zod.z.array(ruleConditionSchema).optional()
926
+ }).strict()
927
+ );
928
+ schemaBasedConditionSchema = import_zod.z.object({
929
+ scope: jsonPointerSchema,
930
+ schema: ruleConditionSchema
931
+ }).strict();
932
+ ruleSchema = import_zod.z.object({
933
+ effect: ruleEffectSchema,
934
+ condition: schemaBasedConditionSchema
935
+ }).strict();
936
+ uiSchemaElementSchema = import_zod.z.lazy(
937
+ () => import_zod.z.union([
938
+ controlSchema,
939
+ verticalLayoutSchema,
940
+ horizontalLayoutSchema,
941
+ groupLayoutSchema,
942
+ categorizationSchema,
943
+ categorySchema,
944
+ labelElementSchema
945
+ ])
946
+ );
947
+ controlSchema = import_zod.z.object({
948
+ type: import_zod.z.literal("Control"),
949
+ scope: jsonPointerSchema,
950
+ label: import_zod.z.union([import_zod.z.string(), import_zod.z.literal(false)]).optional(),
951
+ rule: ruleSchema.optional(),
952
+ options: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
953
+ }).passthrough();
954
+ verticalLayoutSchema = import_zod.z.lazy(
955
+ () => import_zod.z.object({
956
+ type: import_zod.z.literal("VerticalLayout"),
957
+ elements: import_zod.z.array(uiSchemaElementSchema),
958
+ rule: ruleSchema.optional(),
959
+ options: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
960
+ }).passthrough()
961
+ );
962
+ horizontalLayoutSchema = import_zod.z.lazy(
963
+ () => import_zod.z.object({
964
+ type: import_zod.z.literal("HorizontalLayout"),
965
+ elements: import_zod.z.array(uiSchemaElementSchema),
966
+ rule: ruleSchema.optional(),
967
+ options: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
968
+ }).passthrough()
969
+ );
970
+ groupLayoutSchema = import_zod.z.lazy(
971
+ () => import_zod.z.object({
972
+ type: import_zod.z.literal("Group"),
973
+ label: import_zod.z.string(),
974
+ elements: import_zod.z.array(uiSchemaElementSchema),
975
+ rule: ruleSchema.optional(),
976
+ options: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
977
+ }).passthrough()
978
+ );
979
+ categorySchema = import_zod.z.lazy(
980
+ () => import_zod.z.object({
981
+ type: import_zod.z.literal("Category"),
982
+ label: import_zod.z.string(),
983
+ elements: import_zod.z.array(uiSchemaElementSchema),
984
+ rule: ruleSchema.optional(),
985
+ options: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
986
+ }).passthrough()
987
+ );
988
+ categorizationSchema = import_zod.z.lazy(
989
+ () => import_zod.z.object({
990
+ type: import_zod.z.literal("Categorization"),
991
+ elements: import_zod.z.array(categorySchema),
992
+ label: import_zod.z.string().optional(),
993
+ rule: ruleSchema.optional(),
994
+ options: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
995
+ }).passthrough()
996
+ );
997
+ labelElementSchema = import_zod.z.object({
998
+ type: import_zod.z.literal("Label"),
999
+ text: import_zod.z.string(),
1000
+ rule: ruleSchema.optional(),
1001
+ options: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
1002
+ }).passthrough();
1003
+ uiSchema = import_zod.z.lazy(
1004
+ () => import_zod.z.union([verticalLayoutSchema, horizontalLayoutSchema, groupLayoutSchema, categorizationSchema])
1005
+ );
1006
+ }
1007
+ });
1008
+
1009
+ // src/ui-schema/ir-generator.ts
1010
+ function parseOrThrow(schema, value, label) {
1011
+ try {
1012
+ return schema.parse(value);
1013
+ } catch (error) {
1014
+ if (error instanceof import_zod2.z.ZodError) {
1015
+ throw new Error(
1016
+ `Generated ${label} failed validation:
1017
+ ${error.issues.map((i) => ` ${i.path.join(".")}: ${i.message}`).join("\n")}`
1018
+ );
1019
+ }
1020
+ throw error;
1021
+ }
1022
+ }
1023
+ function fieldToScope(fieldName) {
1024
+ return `#/properties/${fieldName}`;
1025
+ }
1026
+ function createShowRule(fieldName, value) {
1027
+ return {
1028
+ effect: "SHOW",
1029
+ condition: {
1030
+ scope: fieldToScope(fieldName),
1031
+ schema: { const: value }
1032
+ }
1033
+ };
1034
+ }
1035
+ function flattenConditionSchema(scope, schema) {
1036
+ if (schema.allOf === void 0) {
1037
+ if (scope === "#") {
1038
+ return [schema];
1039
+ }
1040
+ const fieldName = scope.replace("#/properties/", "");
1041
+ return [
1042
+ {
1043
+ properties: {
1044
+ [fieldName]: schema
1045
+ }
1046
+ }
1047
+ ];
1048
+ }
1049
+ return schema.allOf.flatMap((member) => flattenConditionSchema(scope, member));
1050
+ }
1051
+ function combineRules(parentRule, childRule) {
1052
+ return {
1053
+ effect: "SHOW",
1054
+ condition: {
1055
+ scope: "#",
1056
+ schema: {
1057
+ allOf: [
1058
+ ...flattenConditionSchema(parentRule.condition.scope, parentRule.condition.schema),
1059
+ ...flattenConditionSchema(childRule.condition.scope, childRule.condition.schema)
1060
+ ]
1061
+ }
1062
+ }
1063
+ };
1064
+ }
1065
+ function fieldNodeToControl(field, parentRule) {
1066
+ const displayNameAnnotation = field.annotations.find((a) => a.annotationKind === "displayName");
1067
+ const placeholderAnnotation = field.annotations.find((a) => a.annotationKind === "placeholder");
1068
+ const control = {
1069
+ type: "Control",
1070
+ scope: fieldToScope(field.name),
1071
+ ...displayNameAnnotation !== void 0 && { label: displayNameAnnotation.value },
1072
+ ...placeholderAnnotation !== void 0 && {
1073
+ options: { placeholder: placeholderAnnotation.value }
1074
+ },
1075
+ ...parentRule !== void 0 && { rule: parentRule }
1076
+ };
1077
+ return control;
1078
+ }
1079
+ function groupNodeToLayout(group, parentRule) {
1080
+ return {
1081
+ type: "Group",
1082
+ label: group.label,
1083
+ elements: irElementsToUiSchema(group.elements, parentRule),
1084
+ ...parentRule !== void 0 && { rule: parentRule }
1085
+ };
1086
+ }
1087
+ function irElementsToUiSchema(elements, parentRule) {
1088
+ const result = [];
1089
+ for (const element of elements) {
1090
+ switch (element.kind) {
1091
+ case "field": {
1092
+ result.push(fieldNodeToControl(element, parentRule));
1093
+ break;
1094
+ }
1095
+ case "group": {
1096
+ result.push(groupNodeToLayout(element, parentRule));
1097
+ break;
1098
+ }
1099
+ case "conditional": {
1100
+ const newRule = createShowRule(element.fieldName, element.value);
1101
+ const combinedRule = parentRule !== void 0 ? combineRules(parentRule, newRule) : newRule;
1102
+ const childElements = irElementsToUiSchema(element.elements, combinedRule);
1103
+ result.push(...childElements);
1104
+ break;
1105
+ }
1106
+ default: {
1107
+ const _exhaustive = element;
1108
+ void _exhaustive;
1109
+ throw new Error("Unhandled IR element kind");
1110
+ }
1111
+ }
1112
+ }
1113
+ return result;
1114
+ }
1115
+ function generateUiSchemaFromIR(ir) {
1116
+ const result = {
1117
+ type: "VerticalLayout",
1118
+ elements: irElementsToUiSchema(ir.elements)
1119
+ };
1120
+ return parseOrThrow(uiSchema, result, "UI Schema");
1121
+ }
1122
+ var import_zod2;
1123
+ var init_ir_generator2 = __esm({
1124
+ "src/ui-schema/ir-generator.ts"() {
1125
+ "use strict";
1126
+ init_schema();
1127
+ import_zod2 = require("zod");
1128
+ }
1129
+ });
1130
+
1131
+ // src/ui-schema/generator.ts
1132
+ function generateUiSchema(form) {
1133
+ const ir = canonicalizeChainDSL(form);
1134
+ return generateUiSchemaFromIR(ir);
1135
+ }
1136
+ var init_generator2 = __esm({
1137
+ "src/ui-schema/generator.ts"() {
1138
+ "use strict";
1139
+ init_canonicalize();
1140
+ init_ir_generator2();
1141
+ }
1142
+ });
1143
+
1144
+ // src/json-schema/types.ts
1145
+ function setSchemaExtension(schema, key, value) {
1146
+ schema[key] = value;
1147
+ }
1148
+ function getSchemaExtension(schema, key) {
1149
+ return schema[key];
1150
+ }
1151
+ var init_types = __esm({
1152
+ "src/json-schema/types.ts"() {
1153
+ "use strict";
1154
+ }
1155
+ });
1156
+
1157
+ // src/extensions/registry.ts
1158
+ function createExtensionRegistry(extensions) {
1159
+ const typeMap = /* @__PURE__ */ new Map();
1160
+ const typeNameMap = /* @__PURE__ */ new Map();
1161
+ const constraintMap = /* @__PURE__ */ new Map();
1162
+ const constraintTagMap = /* @__PURE__ */ new Map();
1163
+ const builtinBroadeningMap = /* @__PURE__ */ new Map();
1164
+ const annotationMap = /* @__PURE__ */ new Map();
1165
+ for (const ext of extensions) {
1166
+ if (ext.types !== void 0) {
1167
+ for (const type of ext.types) {
1168
+ const qualifiedId = `${ext.extensionId}/${type.typeName}`;
1169
+ if (typeMap.has(qualifiedId)) {
1170
+ throw new Error(`Duplicate custom type ID: "${qualifiedId}"`);
1171
+ }
1172
+ typeMap.set(qualifiedId, type);
1173
+ for (const sourceTypeName of type.tsTypeNames ?? [type.typeName]) {
1174
+ if (typeNameMap.has(sourceTypeName)) {
1175
+ throw new Error(`Duplicate custom type source name: "${sourceTypeName}"`);
1176
+ }
1177
+ typeNameMap.set(sourceTypeName, {
1178
+ extensionId: ext.extensionId,
1179
+ registration: type
1180
+ });
1181
+ }
1182
+ if (type.builtinConstraintBroadenings !== void 0) {
1183
+ for (const broadening of type.builtinConstraintBroadenings) {
1184
+ const key = `${qualifiedId}:${broadening.tagName}`;
1185
+ if (builtinBroadeningMap.has(key)) {
1186
+ throw new Error(`Duplicate built-in constraint broadening: "${key}"`);
1187
+ }
1188
+ builtinBroadeningMap.set(key, {
1189
+ extensionId: ext.extensionId,
1190
+ registration: broadening
1191
+ });
1192
+ }
1193
+ }
1194
+ }
1195
+ }
1196
+ if (ext.constraints !== void 0) {
1197
+ for (const constraint of ext.constraints) {
1198
+ const qualifiedId = `${ext.extensionId}/${constraint.constraintName}`;
1199
+ if (constraintMap.has(qualifiedId)) {
1200
+ throw new Error(`Duplicate custom constraint ID: "${qualifiedId}"`);
1201
+ }
1202
+ constraintMap.set(qualifiedId, constraint);
1203
+ }
1204
+ }
1205
+ if (ext.constraintTags !== void 0) {
1206
+ for (const tag of ext.constraintTags) {
1207
+ if (constraintTagMap.has(tag.tagName)) {
1208
+ throw new Error(`Duplicate custom constraint tag: "@${tag.tagName}"`);
1209
+ }
1210
+ constraintTagMap.set(tag.tagName, {
1211
+ extensionId: ext.extensionId,
1212
+ registration: tag
1213
+ });
1214
+ }
1215
+ }
1216
+ if (ext.annotations !== void 0) {
1217
+ for (const annotation of ext.annotations) {
1218
+ const qualifiedId = `${ext.extensionId}/${annotation.annotationName}`;
1219
+ if (annotationMap.has(qualifiedId)) {
1220
+ throw new Error(`Duplicate custom annotation ID: "${qualifiedId}"`);
1221
+ }
1222
+ annotationMap.set(qualifiedId, annotation);
1223
+ }
1224
+ }
1225
+ }
1226
+ return {
1227
+ extensions,
1228
+ findType: (typeId) => typeMap.get(typeId),
1229
+ findTypeByName: (typeName) => typeNameMap.get(typeName),
1230
+ findConstraint: (constraintId) => constraintMap.get(constraintId),
1231
+ findConstraintTag: (tagName) => constraintTagMap.get(tagName),
1232
+ findBuiltinConstraintBroadening: (typeId, tagName) => builtinBroadeningMap.get(`${typeId}:${tagName}`),
1233
+ findAnnotation: (annotationId) => annotationMap.get(annotationId)
1234
+ };
1235
+ }
1236
+ var init_registry = __esm({
1237
+ "src/extensions/registry.ts"() {
1238
+ "use strict";
1239
+ }
1240
+ });
1241
+
1242
+ // src/extensions/index.ts
1243
+ var init_extensions = __esm({
1244
+ "src/extensions/index.ts"() {
1245
+ "use strict";
1246
+ init_registry();
1247
+ }
1248
+ });
1249
+
1250
+ // src/json-schema/schema.ts
1251
+ var import_zod3, jsonSchemaTypeSchema, jsonSchema7Schema;
1252
+ var init_schema2 = __esm({
1253
+ "src/json-schema/schema.ts"() {
1254
+ "use strict";
1255
+ import_zod3 = require("zod");
1256
+ jsonSchemaTypeSchema = import_zod3.z.enum([
1257
+ "string",
1258
+ "number",
1259
+ "integer",
1260
+ "boolean",
1261
+ "object",
1262
+ "array",
1263
+ "null"
1264
+ ]);
1265
+ jsonSchema7Schema = import_zod3.z.lazy(
1266
+ () => import_zod3.z.object({
1267
+ $schema: import_zod3.z.string().optional(),
1268
+ $id: import_zod3.z.string().optional(),
1269
+ $ref: import_zod3.z.string().optional(),
1270
+ // Metadata
1271
+ title: import_zod3.z.string().optional(),
1272
+ description: import_zod3.z.string().optional(),
1273
+ deprecated: import_zod3.z.boolean().optional(),
1274
+ // Type
1275
+ type: import_zod3.z.union([jsonSchemaTypeSchema, import_zod3.z.array(jsonSchemaTypeSchema)]).optional(),
1276
+ // String validation
1277
+ minLength: import_zod3.z.number().optional(),
1278
+ maxLength: import_zod3.z.number().optional(),
1279
+ pattern: import_zod3.z.string().optional(),
1280
+ // Number validation
1281
+ minimum: import_zod3.z.number().optional(),
1282
+ maximum: import_zod3.z.number().optional(),
1283
+ exclusiveMinimum: import_zod3.z.number().optional(),
1284
+ exclusiveMaximum: import_zod3.z.number().optional(),
1285
+ // Enum
1286
+ 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(),
1287
+ const: import_zod3.z.union([import_zod3.z.string(), import_zod3.z.number(), import_zod3.z.boolean(), import_zod3.z.null()]).optional(),
1288
+ // Object
1289
+ properties: import_zod3.z.record(import_zod3.z.string(), jsonSchema7Schema).optional(),
1290
+ required: import_zod3.z.array(import_zod3.z.string()).optional(),
1291
+ additionalProperties: import_zod3.z.union([import_zod3.z.boolean(), jsonSchema7Schema]).optional(),
1292
+ // Array
1293
+ items: import_zod3.z.union([jsonSchema7Schema, import_zod3.z.array(jsonSchema7Schema)]).optional(),
1294
+ minItems: import_zod3.z.number().optional(),
1295
+ maxItems: import_zod3.z.number().optional(),
1296
+ // Composition
1297
+ allOf: import_zod3.z.array(jsonSchema7Schema).optional(),
1298
+ anyOf: import_zod3.z.array(jsonSchema7Schema).optional(),
1299
+ oneOf: import_zod3.z.array(jsonSchema7Schema).optional(),
1300
+ not: jsonSchema7Schema.optional(),
1301
+ // Conditional
1302
+ if: jsonSchema7Schema.optional(),
1303
+ then: jsonSchema7Schema.optional(),
1304
+ else: jsonSchema7Schema.optional(),
1305
+ // Format
1306
+ format: import_zod3.z.string().optional(),
1307
+ // Default
1308
+ default: import_zod3.z.unknown().optional(),
1309
+ // FormSpec extensions
1310
+ "x-formspec-source": import_zod3.z.string().optional(),
1311
+ "x-formspec-params": import_zod3.z.array(import_zod3.z.string()).readonly().optional(),
1312
+ "x-formspec-schemaSource": import_zod3.z.string().optional()
1313
+ }).passthrough()
1314
+ );
1315
+ }
1316
+ });
1317
+
1318
+ // src/analyzer/tsdoc-parser.ts
1319
+ function createFormSpecTSDocConfig(extensionTagNames = []) {
1320
+ const config = new import_tsdoc.TSDocConfiguration();
1321
+ for (const tagName of Object.keys(import_core3.BUILTIN_CONSTRAINT_DEFINITIONS)) {
1322
+ config.addTagDefinition(
1323
+ new import_tsdoc.TSDocTagDefinition({
1324
+ tagName: "@" + tagName,
1325
+ syntaxKind: import_tsdoc.TSDocTagSyntaxKind.BlockTag,
1326
+ allowMultiple: true
1327
+ })
1328
+ );
1329
+ }
1330
+ for (const tagName of ["displayName", "format", "placeholder"]) {
1331
+ config.addTagDefinition(
1332
+ new import_tsdoc.TSDocTagDefinition({
1333
+ tagName: "@" + tagName,
1334
+ syntaxKind: import_tsdoc.TSDocTagSyntaxKind.BlockTag,
1335
+ allowMultiple: true
1336
+ })
1337
+ );
1338
+ }
1339
+ for (const tagName of extensionTagNames) {
1340
+ config.addTagDefinition(
1341
+ new import_tsdoc.TSDocTagDefinition({
1342
+ tagName: "@" + tagName,
1343
+ syntaxKind: import_tsdoc.TSDocTagSyntaxKind.BlockTag,
1344
+ allowMultiple: true
1345
+ })
1346
+ );
1347
+ }
1348
+ return config;
1349
+ }
1350
+ function sharedCommentSyntaxOptions(options, offset) {
1351
+ const extensions = options?.extensionRegistry?.extensions;
1352
+ return {
1353
+ ...offset !== void 0 ? { offset } : {},
1354
+ ...extensions !== void 0 ? { extensions } : {}
1355
+ };
1356
+ }
1357
+ function sharedTagValueOptions(options) {
1358
+ return {
1359
+ ...options?.extensionRegistry !== void 0 ? { registry: options.extensionRegistry } : {},
1360
+ ...options?.fieldType !== void 0 ? { fieldType: options.fieldType } : {}
1361
+ };
1362
+ }
1363
+ function buildSupportingDeclarations(sourceFile) {
1364
+ return sourceFile.statements.filter(
1365
+ (statement) => !ts.isImportDeclaration(statement) && !ts.isImportEqualsDeclaration(statement) && !(ts.isExportDeclaration(statement) && statement.moduleSpecifier !== void 0)
1366
+ ).map((statement) => statement.getText(sourceFile));
1367
+ }
1368
+ function renderSyntheticArgumentExpression(valueKind, argumentText) {
1369
+ const trimmed = argumentText.trim();
1370
+ if (trimmed === "") {
1371
+ return null;
1372
+ }
1373
+ switch (valueKind) {
1374
+ case "number":
1375
+ case "integer":
1376
+ case "signedInteger":
1377
+ return Number.isFinite(Number(trimmed)) ? trimmed : JSON.stringify(trimmed);
1378
+ case "string":
1379
+ return JSON.stringify(argumentText);
1380
+ case "json":
1381
+ try {
1382
+ JSON.parse(trimmed);
1383
+ return `(${trimmed})`;
1384
+ } catch {
1385
+ return JSON.stringify(trimmed);
1386
+ }
1387
+ case "boolean":
1388
+ return trimmed === "true" || trimmed === "false" ? trimmed : JSON.stringify(trimmed);
1389
+ case "condition":
1390
+ return "undefined as unknown as FormSpecCondition";
1391
+ case null:
1392
+ return null;
1393
+ default: {
1394
+ return String(valueKind);
1395
+ }
1396
+ }
1397
+ }
1398
+ function getArrayElementType(type, checker) {
1399
+ if (!checker.isArrayType(type)) {
1400
+ return null;
1401
+ }
1402
+ return checker.getTypeArguments(type)[0] ?? null;
1403
+ }
1404
+ function supportsConstraintCapability(type, checker, capability) {
1405
+ if (capability === void 0) {
1406
+ return true;
1407
+ }
1408
+ if ((0, import_internal.hasTypeSemanticCapability)(type, checker, capability)) {
1409
+ return true;
1410
+ }
1411
+ if (capability === "string-like") {
1412
+ const itemType = getArrayElementType(type, checker);
1413
+ return itemType !== null && (0, import_internal.hasTypeSemanticCapability)(itemType, checker, capability);
1414
+ }
1415
+ return false;
1416
+ }
1417
+ function makeDiagnostic(code, message, provenance) {
1418
+ return {
1419
+ code,
1420
+ message,
1421
+ severity: "error",
1422
+ primaryLocation: provenance,
1423
+ relatedLocations: []
1424
+ };
1425
+ }
1426
+ function placementLabel(placement) {
1427
+ switch (placement) {
1428
+ case "class":
1429
+ return "class declarations";
1430
+ case "class-field":
1431
+ return "class fields";
1432
+ case "class-method":
1433
+ return "class methods";
1434
+ case "interface":
1435
+ return "interface declarations";
1436
+ case "interface-field":
1437
+ return "interface fields";
1438
+ case "type-alias":
1439
+ return "type aliases";
1440
+ case "type-alias-field":
1441
+ return "type-alias properties";
1442
+ case "variable":
1443
+ return "variables";
1444
+ case "function":
1445
+ return "functions";
1446
+ case "function-parameter":
1447
+ return "function parameters";
1448
+ case "method-parameter":
1449
+ return "method parameters";
1450
+ default: {
1451
+ const exhaustive = placement;
1452
+ return String(exhaustive);
1453
+ }
1454
+ }
1455
+ }
1456
+ function capabilityLabel(capability) {
1457
+ switch (capability) {
1458
+ case "numeric-comparable":
1459
+ return "number";
1460
+ case "string-like":
1461
+ return "string";
1462
+ case "array-like":
1463
+ return "array";
1464
+ case "enum-member-addressable":
1465
+ return "enum";
1466
+ case "json-like":
1467
+ return "JSON-compatible";
1468
+ case "object-like":
1469
+ return "object";
1470
+ case "condition-like":
1471
+ return "conditional";
1472
+ case void 0:
1473
+ return "compatible";
1474
+ default:
1475
+ return capability;
1476
+ }
1477
+ }
1478
+ function getBroadenedCustomTypeId(fieldType) {
1479
+ if (fieldType?.kind === "custom") {
1480
+ return fieldType.typeId;
1481
+ }
1482
+ if (fieldType?.kind !== "union") {
1483
+ return void 0;
1484
+ }
1485
+ const customMembers = fieldType.members.filter(
1486
+ (member) => member.kind === "custom"
1487
+ );
1488
+ if (customMembers.length !== 1) {
1489
+ return void 0;
1490
+ }
1491
+ const nonCustomMembers = fieldType.members.filter((member) => member.kind !== "custom");
1492
+ const allOtherMembersAreNull = nonCustomMembers.every(
1493
+ (member) => member.kind === "primitive" && member.primitiveKind === "null"
1494
+ );
1495
+ const customMember = customMembers[0];
1496
+ return allOtherMembersAreNull && customMember !== void 0 ? customMember.typeId : void 0;
1497
+ }
1498
+ function hasBuiltinConstraintBroadening(tagName, options) {
1499
+ const broadenedTypeId = getBroadenedCustomTypeId(options?.fieldType);
1500
+ return broadenedTypeId !== void 0 && options?.extensionRegistry?.findBuiltinConstraintBroadening(broadenedTypeId, tagName) !== void 0;
1501
+ }
1502
+ function buildCompilerBackedConstraintDiagnostics(node, sourceFile, tagName, parsedTag, provenance, supportingDeclarations, options) {
1503
+ if (!(0, import_core3.isBuiltinConstraintName)(tagName)) {
1504
+ return [];
1505
+ }
1506
+ const checker = options?.checker;
1507
+ const subjectType = options?.subjectType;
1508
+ if (checker === void 0 || subjectType === void 0) {
1509
+ return [];
1510
+ }
1511
+ const placement = (0, import_internal.resolveDeclarationPlacement)(node);
1512
+ if (placement === null) {
1513
+ return [];
1514
+ }
1515
+ const definition = (0, import_internal.getTagDefinition)(tagName, options?.extensionRegistry?.extensions);
1516
+ if (definition === null) {
1517
+ return [];
1518
+ }
1519
+ if (!definition.placements.includes(placement)) {
1520
+ return [
1521
+ makeDiagnostic(
1522
+ "INVALID_TAG_PLACEMENT",
1523
+ `Tag "@${tagName}" is not allowed on ${placementLabel(placement)}.`,
1524
+ provenance
1525
+ )
1526
+ ];
1527
+ }
1528
+ const target = parsedTag?.target ?? null;
1529
+ const hasBroadening = target === null && hasBuiltinConstraintBroadening(tagName, options);
1530
+ if (target !== null) {
1531
+ if (target.kind !== "path") {
1532
+ return [
1533
+ makeDiagnostic(
1534
+ "UNSUPPORTED_TARGETING_SYNTAX",
1535
+ `Tag "@${tagName}" does not support ${target.kind} targeting syntax.`,
1536
+ provenance
1537
+ )
1538
+ ];
1539
+ }
1540
+ if (!target.valid || target.path === null) {
1541
+ return [
1542
+ makeDiagnostic(
1543
+ "UNSUPPORTED_TARGETING_SYNTAX",
1544
+ `Tag "@${tagName}" has invalid path targeting syntax.`,
1545
+ provenance
1546
+ )
1547
+ ];
1548
+ }
1549
+ const resolution = (0, import_internal.resolvePathTargetType)(subjectType, checker, target.path.segments);
1550
+ if (resolution.kind === "missing-property") {
1551
+ return [
1552
+ makeDiagnostic(
1553
+ "UNKNOWN_PATH_TARGET",
1554
+ `Target "${target.rawText}": path-targeted constraint "${tagName}" references unknown path segment "${resolution.segment}"`,
1555
+ provenance
1556
+ )
1557
+ ];
1558
+ }
1559
+ if (resolution.kind === "unresolvable") {
1560
+ const actualType = checker.typeToString(resolution.type, node, SYNTHETIC_TYPE_FORMAT_FLAGS);
1561
+ return [
1562
+ makeDiagnostic(
1563
+ "TYPE_MISMATCH",
1564
+ `Target "${target.rawText}": path-targeted constraint "${tagName}" is invalid because type "${actualType}" cannot be traversed`,
1565
+ provenance
1566
+ )
1567
+ ];
1568
+ }
1569
+ const requiredCapability = definition.capabilities[0];
1570
+ if (requiredCapability !== void 0 && !supportsConstraintCapability(resolution.type, checker, requiredCapability)) {
1571
+ const actualType = checker.typeToString(resolution.type, node, SYNTHETIC_TYPE_FORMAT_FLAGS);
1572
+ return [
1573
+ makeDiagnostic(
1574
+ "TYPE_MISMATCH",
1575
+ `Target "${target.rawText}": constraint "${tagName}" is only valid on ${capabilityLabel(requiredCapability)} targets, but field type is "${actualType}"`,
1576
+ provenance
1577
+ )
1578
+ ];
1579
+ }
1580
+ } else if (!hasBroadening) {
1581
+ const requiredCapability = definition.capabilities[0];
1582
+ if (requiredCapability !== void 0 && !supportsConstraintCapability(subjectType, checker, requiredCapability)) {
1583
+ const actualType = checker.typeToString(subjectType, node, SYNTHETIC_TYPE_FORMAT_FLAGS);
1584
+ return [
1585
+ makeDiagnostic(
1586
+ "TYPE_MISMATCH",
1587
+ `Target "${node.getText(sourceFile)}": constraint "${tagName}" is only valid on ${capabilityLabel(requiredCapability)} targets, but field type is "${actualType}"`,
1588
+ provenance
1589
+ )
1590
+ ];
1591
+ }
1592
+ }
1593
+ const argumentExpression = renderSyntheticArgumentExpression(
1594
+ definition.valueKind,
1595
+ parsedTag?.argumentText ?? ""
1596
+ );
1597
+ if (definition.requiresArgument && argumentExpression === null) {
1598
+ return [];
1599
+ }
1600
+ if (hasBroadening) {
1601
+ return [];
1602
+ }
1603
+ const subjectTypeText = checker.typeToString(subjectType, node, SYNTHETIC_TYPE_FORMAT_FLAGS);
1604
+ const hostType = options?.hostType ?? subjectType;
1605
+ const hostTypeText = checker.typeToString(hostType, node, SYNTHETIC_TYPE_FORMAT_FLAGS);
1606
+ const result = (0, import_internal.checkSyntheticTagApplication)({
1607
+ tagName,
1608
+ placement,
1609
+ hostType: hostTypeText,
1610
+ subjectType: subjectTypeText,
1611
+ ...target?.kind === "path" ? { target: { kind: "path", text: target.rawText } } : {},
1612
+ ...argumentExpression !== null ? { argumentExpression } : {},
1613
+ supportingDeclarations,
1614
+ ...options?.extensionRegistry !== void 0 ? {
1615
+ extensions: options.extensionRegistry.extensions.map((extension) => ({
1616
+ extensionId: extension.extensionId,
1617
+ ...extension.constraintTags !== void 0 ? {
1618
+ constraintTags: extension.constraintTags.map((tag) => ({ tagName: tag.tagName }))
1619
+ } : {}
1620
+ }))
1621
+ } : {}
1622
+ });
1623
+ if (result.diagnostics.length === 0) {
1624
+ return [];
1625
+ }
1626
+ const expectedLabel = definition.valueKind === null ? "compatible argument" : capabilityLabel(definition.valueKind);
1627
+ return [
1628
+ makeDiagnostic(
1629
+ "TYPE_MISMATCH",
1630
+ `Tag "@${tagName}" received an invalid argument for ${expectedLabel}.`,
1631
+ provenance
1632
+ )
1633
+ ];
1634
+ }
1635
+ function getParser(options) {
1636
+ const extensionTagNames = [
1637
+ ...options?.extensionRegistry?.extensions.flatMap(
1638
+ (extension) => (extension.constraintTags ?? []).map((tag) => tag.tagName)
1639
+ ) ?? []
1640
+ ].sort();
1641
+ const cacheKey = extensionTagNames.join("|");
1642
+ const existing = parserCache.get(cacheKey);
1643
+ if (existing) {
1644
+ return existing;
1645
+ }
1646
+ const parser = new import_tsdoc.TSDocParser(createFormSpecTSDocConfig(extensionTagNames));
1647
+ parserCache.set(cacheKey, parser);
1648
+ return parser;
1649
+ }
1650
+ function getExtensionRegistryCacheKey(registry) {
1651
+ if (registry === void 0) {
1652
+ return "";
1653
+ }
1654
+ return registry.extensions.map(
1655
+ (extension) => JSON.stringify({
1656
+ extensionId: extension.extensionId,
1657
+ typeNames: extension.types?.map((type) => type.typeName) ?? [],
1658
+ constraintTags: extension.constraintTags?.map((tag) => tag.tagName) ?? []
1659
+ })
1660
+ ).join("|");
1661
+ }
1662
+ function getParseCacheKey(node, file, options) {
1663
+ const sourceFile = node.getSourceFile();
1664
+ const checker = options?.checker;
1665
+ return JSON.stringify({
1666
+ file,
1667
+ sourceFile: sourceFile.fileName,
1668
+ sourceText: sourceFile.text,
1669
+ start: node.getFullStart(),
1670
+ end: node.getEnd(),
1671
+ fieldType: options?.fieldType ?? null,
1672
+ subjectType: checker !== void 0 && options?.subjectType !== void 0 ? checker.typeToString(options.subjectType, node, SYNTHETIC_TYPE_FORMAT_FLAGS) : null,
1673
+ hostType: checker !== void 0 && options?.hostType !== void 0 ? checker.typeToString(options.hostType, node, SYNTHETIC_TYPE_FORMAT_FLAGS) : null,
1674
+ extensions: getExtensionRegistryCacheKey(options?.extensionRegistry)
1675
+ });
1676
+ }
1677
+ function parseTSDocTags(node, file = "", options) {
1678
+ const cacheKey = getParseCacheKey(node, file, options);
1679
+ const cached = parseResultCache.get(cacheKey);
1680
+ if (cached !== void 0) {
1681
+ return cached;
1682
+ }
1683
+ const constraints = [];
1684
+ const annotations = [];
1685
+ const diagnostics = [];
1686
+ let displayName;
1687
+ let placeholder;
1688
+ let displayNameProvenance;
1689
+ let placeholderProvenance;
1690
+ const rawTextTags = [];
1691
+ const sourceFile = node.getSourceFile();
1692
+ const sourceText = sourceFile.getFullText();
1693
+ const supportingDeclarations = buildSupportingDeclarations(sourceFile);
1694
+ const commentRanges = ts.getLeadingCommentRanges(sourceText, node.getFullStart());
1695
+ const rawTextFallbacks = collectRawTextFallbacks(node, file);
1696
+ if (commentRanges) {
1697
+ for (const range of commentRanges) {
1698
+ if (range.kind !== ts.SyntaxKind.MultiLineCommentTrivia) {
1699
+ continue;
1700
+ }
1701
+ const commentText = sourceText.substring(range.pos, range.end);
1702
+ if (!commentText.startsWith("/**")) {
1703
+ continue;
1704
+ }
1705
+ const parser = getParser(options);
1706
+ const parserContext = parser.parseRange(
1707
+ import_tsdoc.TextRange.fromStringRange(sourceText, range.pos, range.end)
1708
+ );
1709
+ const docComment = parserContext.docComment;
1710
+ const parsedComment = (0, import_internal.parseCommentBlock)(
1711
+ commentText,
1712
+ sharedCommentSyntaxOptions(options, range.pos)
1713
+ );
1714
+ let parsedTagCursor = 0;
1715
+ const nextParsedTag = (normalizedTagName) => {
1716
+ while (parsedTagCursor < parsedComment.tags.length) {
1717
+ const candidate = parsedComment.tags[parsedTagCursor];
1718
+ parsedTagCursor += 1;
1719
+ if (candidate?.normalizedTagName === normalizedTagName) {
1720
+ return candidate;
1721
+ }
1722
+ }
1723
+ return null;
1724
+ };
1725
+ for (const parsedTag of parsedComment.tags) {
1726
+ if (TAGS_REQUIRING_RAW_TEXT.has(parsedTag.normalizedTagName)) {
1727
+ rawTextTags.push({ tag: parsedTag, commentText, commentOffset: range.pos });
1728
+ }
1729
+ }
1730
+ for (const block of docComment.customBlocks) {
1731
+ const tagName = (0, import_core3.normalizeConstraintTagName)(block.blockTag.tagName.substring(1));
1732
+ const parsedTag = nextParsedTag(tagName);
1733
+ if (tagName === "displayName" || tagName === "format" || tagName === "placeholder") {
1734
+ const text2 = getBestBlockPayloadText(parsedTag, commentText, range.pos, block);
1735
+ if (text2 === "") continue;
1736
+ const provenance2 = parsedTag !== null ? provenanceForParsedTag(parsedTag, sourceFile, file) : provenanceForComment(range, sourceFile, file, tagName);
1737
+ switch (tagName) {
1738
+ case "displayName":
1739
+ if (!isMemberTargetDisplayName(text2) && displayName === void 0) {
1740
+ displayName = text2;
1741
+ displayNameProvenance = provenance2;
1742
+ }
1743
+ break;
1744
+ case "format":
1745
+ annotations.push({
1746
+ kind: "annotation",
1747
+ annotationKind: "format",
1748
+ value: text2,
1749
+ provenance: provenance2
1750
+ });
1751
+ break;
1752
+ case "placeholder":
1753
+ if (placeholder === void 0) {
1754
+ placeholder = text2;
1755
+ placeholderProvenance = provenance2;
1756
+ }
1757
+ break;
1758
+ }
1759
+ continue;
1760
+ }
1761
+ if (TAGS_REQUIRING_RAW_TEXT.has(tagName)) continue;
1762
+ const text = getBestBlockPayloadText(parsedTag, commentText, range.pos, block);
1763
+ const expectedType = (0, import_core3.isBuiltinConstraintName)(tagName) ? import_core3.BUILTIN_CONSTRAINT_DEFINITIONS[tagName] : void 0;
1764
+ if (text === "" && expectedType !== "boolean") continue;
1765
+ const provenance = parsedTag !== null ? provenanceForParsedTag(parsedTag, sourceFile, file) : provenanceForComment(range, sourceFile, file, tagName);
1766
+ const compilerDiagnostics = buildCompilerBackedConstraintDiagnostics(
1767
+ node,
1768
+ sourceFile,
1769
+ tagName,
1770
+ parsedTag,
1771
+ provenance,
1772
+ supportingDeclarations,
1773
+ options
1774
+ );
1775
+ if (compilerDiagnostics.length > 0) {
1776
+ diagnostics.push(...compilerDiagnostics);
1777
+ continue;
1778
+ }
1779
+ const constraintNode = (0, import_internal.parseConstraintTagValue)(
1780
+ tagName,
1781
+ text,
1782
+ provenance,
1783
+ sharedTagValueOptions(options)
1784
+ );
1785
+ if (constraintNode) {
1786
+ constraints.push(constraintNode);
1787
+ }
1788
+ }
1789
+ if (docComment.deprecatedBlock !== void 0) {
1790
+ const message = extractBlockText(docComment.deprecatedBlock).trim();
1791
+ annotations.push({
1792
+ kind: "annotation",
1793
+ annotationKind: "deprecated",
1794
+ ...message !== "" && { message },
1795
+ provenance: provenanceForComment(range, sourceFile, file, "deprecated")
1796
+ });
1797
+ }
1798
+ {
1799
+ const summary = extractPlainText(docComment.summarySection).trim();
1800
+ if (summary !== "") {
1801
+ annotations.push({
1802
+ kind: "annotation",
1803
+ annotationKind: "description",
1804
+ value: summary,
1805
+ provenance: provenanceForComment(range, sourceFile, file, "summary")
1806
+ });
1807
+ }
1808
+ }
1809
+ if (docComment.remarksBlock !== void 0) {
1810
+ const remarksText = extractBlockText(docComment.remarksBlock).trim();
1811
+ if (remarksText !== "") {
1812
+ annotations.push({
1813
+ kind: "annotation",
1814
+ annotationKind: "remarks",
1815
+ value: remarksText,
1816
+ provenance: provenanceForComment(range, sourceFile, file, "remarks")
1817
+ });
1818
+ }
1819
+ }
1820
+ }
1821
+ }
1822
+ if (displayName !== void 0 && displayNameProvenance !== void 0) {
1823
+ annotations.push({
1824
+ kind: "annotation",
1825
+ annotationKind: "displayName",
1826
+ value: displayName,
1827
+ provenance: displayNameProvenance
1828
+ });
1829
+ }
1830
+ if (placeholder !== void 0 && placeholderProvenance !== void 0) {
1831
+ annotations.push({
1832
+ kind: "annotation",
1833
+ annotationKind: "placeholder",
1834
+ value: placeholder,
1835
+ provenance: placeholderProvenance
1836
+ });
1837
+ }
1838
+ if (rawTextTags.length > 0) {
1839
+ for (const rawTextTag of rawTextTags) {
1840
+ const fallbackQueue = rawTextFallbacks.get(rawTextTag.tag.normalizedTagName);
1841
+ const fallback = fallbackQueue?.shift();
1842
+ const text = choosePreferredPayloadText(
1843
+ getSharedPayloadText(rawTextTag.tag, rawTextTag.commentText, rawTextTag.commentOffset),
1844
+ fallback?.text ?? ""
1845
+ );
1846
+ if (text === "") continue;
1847
+ const provenance = provenanceForParsedTag(rawTextTag.tag, sourceFile, file);
1848
+ if (rawTextTag.tag.normalizedTagName === "defaultValue") {
1849
+ const defaultValueNode = (0, import_internal.parseDefaultValueTagValue)(text, provenance);
1850
+ annotations.push(defaultValueNode);
1851
+ continue;
1852
+ }
1853
+ const compilerDiagnostics = buildCompilerBackedConstraintDiagnostics(
1854
+ node,
1855
+ sourceFile,
1856
+ rawTextTag.tag.normalizedTagName,
1857
+ rawTextTag.tag,
1858
+ provenance,
1859
+ supportingDeclarations,
1860
+ options
1861
+ );
1862
+ if (compilerDiagnostics.length > 0) {
1863
+ diagnostics.push(...compilerDiagnostics);
1864
+ continue;
1865
+ }
1866
+ const constraintNode = (0, import_internal.parseConstraintTagValue)(
1867
+ rawTextTag.tag.normalizedTagName,
1868
+ text,
1869
+ provenance,
1870
+ sharedTagValueOptions(options)
1871
+ );
1872
+ if (constraintNode) {
1873
+ constraints.push(constraintNode);
1874
+ }
1875
+ }
1876
+ }
1877
+ for (const [tagName, fallbacks] of rawTextFallbacks) {
1878
+ for (const fallback of fallbacks) {
1879
+ const text = fallback.text.trim();
1880
+ if (text === "") continue;
1881
+ const provenance = fallback.provenance;
1882
+ if (tagName === "defaultValue") {
1883
+ const defaultValueNode = (0, import_internal.parseDefaultValueTagValue)(text, provenance);
1884
+ annotations.push(defaultValueNode);
1885
+ continue;
1886
+ }
1887
+ const compilerDiagnostics = buildCompilerBackedConstraintDiagnostics(
1888
+ node,
1889
+ sourceFile,
1890
+ tagName,
1891
+ null,
1892
+ provenance,
1893
+ supportingDeclarations,
1894
+ options
1895
+ );
1896
+ if (compilerDiagnostics.length > 0) {
1897
+ diagnostics.push(...compilerDiagnostics);
1898
+ continue;
1899
+ }
1900
+ const constraintNode = (0, import_internal.parseConstraintTagValue)(
1901
+ tagName,
1902
+ text,
1903
+ provenance,
1904
+ sharedTagValueOptions(options)
1905
+ );
1906
+ if (constraintNode) {
1907
+ constraints.push(constraintNode);
1908
+ }
1909
+ }
1910
+ }
1911
+ const result = { constraints, annotations, diagnostics };
1912
+ parseResultCache.set(cacheKey, result);
1913
+ return result;
1914
+ }
1915
+ function extractDisplayNameMetadata(node) {
1916
+ let displayName;
1917
+ const memberDisplayNames = /* @__PURE__ */ new Map();
1918
+ const sourceFile = node.getSourceFile();
1919
+ const sourceText = sourceFile.getFullText();
1920
+ const commentRanges = ts.getLeadingCommentRanges(sourceText, node.getFullStart());
1921
+ if (commentRanges) {
1922
+ for (const range of commentRanges) {
1923
+ if (range.kind !== ts.SyntaxKind.MultiLineCommentTrivia) continue;
1924
+ const commentText = sourceText.substring(range.pos, range.end);
1925
+ if (!commentText.startsWith("/**")) continue;
1926
+ const parsed = (0, import_internal.parseCommentBlock)(commentText);
1927
+ for (const tag of parsed.tags) {
1928
+ if (tag.normalizedTagName !== "displayName") {
1929
+ continue;
1930
+ }
1931
+ if (tag.target !== null && tag.argumentText !== "") {
1932
+ memberDisplayNames.set(tag.target.rawText, tag.argumentText);
1933
+ continue;
1934
+ }
1935
+ if (tag.argumentText !== "") {
1936
+ displayName ??= tag.argumentText;
1937
+ }
1938
+ }
1939
+ }
1940
+ }
1941
+ return {
1942
+ ...displayName !== void 0 && { displayName },
1943
+ memberDisplayNames
1944
+ };
1945
+ }
1946
+ function extractBlockText(block) {
1947
+ return extractPlainText(block.content);
1948
+ }
1949
+ function extractPlainText(node) {
1950
+ let result = "";
1951
+ if (node instanceof import_tsdoc.DocPlainText) {
1952
+ return node.text;
1953
+ }
1954
+ if (node instanceof import_tsdoc.DocSoftBreak) {
1955
+ return " ";
1956
+ }
1957
+ if (typeof node.getChildNodes === "function") {
1958
+ for (const child of node.getChildNodes()) {
1959
+ result += extractPlainText(child);
1960
+ }
1961
+ }
1962
+ return result;
1963
+ }
1964
+ function choosePreferredPayloadText(primary, fallback) {
1965
+ const preferred = primary.trim();
1966
+ const alternate = fallback.trim();
1967
+ if (preferred === "") return alternate;
1968
+ if (alternate === "") return preferred;
1969
+ if (alternate.includes("\n")) return alternate;
1970
+ if (alternate.length > preferred.length && alternate.startsWith(preferred)) {
1971
+ return alternate;
1972
+ }
1973
+ return preferred;
1974
+ }
1975
+ function getSharedPayloadText(tag, commentText, commentOffset) {
1976
+ if (tag.payloadSpan === null) {
1977
+ return "";
1978
+ }
1979
+ return (0, import_internal.sliceCommentSpan)(commentText, tag.payloadSpan, {
1980
+ offset: commentOffset
1981
+ }).trim();
1982
+ }
1983
+ function getBestBlockPayloadText(tag, commentText, commentOffset, block) {
1984
+ const sharedText = tag === null ? "" : getSharedPayloadText(tag, commentText, commentOffset);
1985
+ const blockText = extractBlockText(block).replace(/\s+/g, " ").trim();
1986
+ return choosePreferredPayloadText(sharedText, blockText);
1987
+ }
1988
+ function collectRawTextFallbacks(node, file) {
1989
+ const fallbacks = /* @__PURE__ */ new Map();
1990
+ for (const tag of ts.getJSDocTags(node)) {
1991
+ const tagName = (0, import_core3.normalizeConstraintTagName)(tag.tagName.text);
1992
+ if (!TAGS_REQUIRING_RAW_TEXT.has(tagName)) continue;
1993
+ const commentText = getTagCommentText(tag)?.trim() ?? "";
1994
+ if (commentText === "") continue;
1995
+ const entries = fallbacks.get(tagName) ?? [];
1996
+ entries.push({
1997
+ text: commentText,
1998
+ provenance: provenanceForJSDocTag(tag, file)
1999
+ });
2000
+ fallbacks.set(tagName, entries);
2001
+ }
2002
+ return fallbacks;
2003
+ }
2004
+ function isMemberTargetDisplayName(text) {
2005
+ return (0, import_internal.parseTagSyntax)("displayName", text).target !== null;
2006
+ }
2007
+ function provenanceForComment(range, sourceFile, file, tagName) {
2008
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(range.pos);
2009
+ return {
2010
+ surface: "tsdoc",
2011
+ file,
2012
+ line: line + 1,
2013
+ column: character,
2014
+ tagName: "@" + tagName
2015
+ };
2016
+ }
2017
+ function provenanceForParsedTag(tag, sourceFile, file) {
2018
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(tag.tagNameSpan.start);
2019
+ return {
2020
+ surface: "tsdoc",
2021
+ file,
2022
+ line: line + 1,
2023
+ column: character,
2024
+ tagName: "@" + tag.normalizedTagName
2025
+ };
2026
+ }
2027
+ function provenanceForJSDocTag(tag, file) {
2028
+ const sourceFile = tag.getSourceFile();
2029
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(tag.getStart());
2030
+ return {
2031
+ surface: "tsdoc",
2032
+ file,
2033
+ line: line + 1,
2034
+ column: character,
2035
+ tagName: "@" + tag.tagName.text
2036
+ };
2037
+ }
2038
+ function getTagCommentText(tag) {
2039
+ if (tag.comment === void 0) {
2040
+ return void 0;
2041
+ }
2042
+ if (typeof tag.comment === "string") {
2043
+ return tag.comment;
2044
+ }
2045
+ return ts.getTextOfJSDocComment(tag.comment);
2046
+ }
2047
+ var ts, import_internal, import_tsdoc, import_core3, TAGS_REQUIRING_RAW_TEXT, SYNTHETIC_TYPE_FORMAT_FLAGS, parserCache, parseResultCache;
2048
+ var init_tsdoc_parser = __esm({
2049
+ "src/analyzer/tsdoc-parser.ts"() {
2050
+ "use strict";
2051
+ ts = __toESM(require("typescript"), 1);
2052
+ import_internal = require("@formspec/analysis/internal");
2053
+ import_tsdoc = require("@microsoft/tsdoc");
2054
+ import_core3 = require("@formspec/core");
2055
+ TAGS_REQUIRING_RAW_TEXT = /* @__PURE__ */ new Set(["pattern", "enumOptions", "defaultValue"]);
2056
+ SYNTHETIC_TYPE_FORMAT_FLAGS = ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope;
2057
+ parserCache = /* @__PURE__ */ new Map();
2058
+ parseResultCache = /* @__PURE__ */ new Map();
2059
+ }
2060
+ });
2061
+
2062
+ // src/analyzer/jsdoc-constraints.ts
2063
+ function extractJSDocParseResult(node, file = "", options) {
2064
+ return parseTSDocTags(node, file, options);
2065
+ }
2066
+ function extractJSDocConstraintNodes(node, file = "", options) {
2067
+ const result = extractJSDocParseResult(node, file, options);
2068
+ return [...result.constraints];
2069
+ }
2070
+ function extractJSDocAnnotationNodes(node, file = "", options) {
2071
+ const result = extractJSDocParseResult(node, file, options);
2072
+ return [...result.annotations];
2073
+ }
2074
+ function extractDefaultValueAnnotation(initializer, file = "") {
2075
+ if (!initializer) return null;
2076
+ let value;
2077
+ if (ts2.isStringLiteral(initializer)) {
2078
+ value = initializer.text;
2079
+ } else if (ts2.isNumericLiteral(initializer)) {
2080
+ value = Number(initializer.text);
2081
+ } else if (initializer.kind === ts2.SyntaxKind.TrueKeyword) {
2082
+ value = true;
2083
+ } else if (initializer.kind === ts2.SyntaxKind.FalseKeyword) {
2084
+ value = false;
2085
+ } else if (initializer.kind === ts2.SyntaxKind.NullKeyword) {
2086
+ value = null;
2087
+ } else if (ts2.isPrefixUnaryExpression(initializer)) {
2088
+ if (initializer.operator === ts2.SyntaxKind.MinusToken && ts2.isNumericLiteral(initializer.operand)) {
2089
+ value = -Number(initializer.operand.text);
2090
+ }
2091
+ }
2092
+ if (value === void 0) return null;
2093
+ const sourceFile = initializer.getSourceFile();
2094
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(initializer.getStart());
2095
+ return {
2096
+ kind: "annotation",
2097
+ annotationKind: "defaultValue",
2098
+ value,
2099
+ provenance: {
2100
+ surface: "tsdoc",
2101
+ file,
2102
+ line: line + 1,
2103
+ column: character
2104
+ }
2105
+ };
2106
+ }
2107
+ var ts2;
2108
+ var init_jsdoc_constraints = __esm({
2109
+ "src/analyzer/jsdoc-constraints.ts"() {
2110
+ "use strict";
2111
+ ts2 = __toESM(require("typescript"), 1);
2112
+ init_tsdoc_parser();
2113
+ }
2114
+ });
2115
+
2116
+ // src/analyzer/class-analyzer.ts
2117
+ function isObjectType(type) {
2118
+ return !!(type.flags & ts3.TypeFlags.Object);
2119
+ }
2120
+ function isTypeReference(type) {
2121
+ return !!(type.flags & ts3.TypeFlags.Object) && !!(type.objectFlags & ts3.ObjectFlags.Reference);
2122
+ }
2123
+ function makeParseOptions(extensionRegistry, fieldType, checker, subjectType, hostType) {
2124
+ if (extensionRegistry === void 0 && fieldType === void 0 && checker === void 0 && subjectType === void 0 && hostType === void 0) {
2125
+ return void 0;
2126
+ }
2127
+ return {
2128
+ ...extensionRegistry !== void 0 && { extensionRegistry },
2129
+ ...fieldType !== void 0 && { fieldType },
2130
+ ...checker !== void 0 && { checker },
2131
+ ...subjectType !== void 0 && { subjectType },
2132
+ ...hostType !== void 0 && { hostType }
2133
+ };
2134
+ }
2135
+ function analyzeClassToIR(classDecl, checker, file = "", extensionRegistry) {
2136
+ const name = classDecl.name?.text ?? "AnonymousClass";
2137
+ const fields = [];
2138
+ const fieldLayouts = [];
2139
+ const typeRegistry = {};
2140
+ const diagnostics = [];
2141
+ const classType = checker.getTypeAtLocation(classDecl);
2142
+ const classDoc = extractJSDocParseResult(
2143
+ classDecl,
2144
+ file,
2145
+ makeParseOptions(extensionRegistry, void 0, checker, classType, classType)
2146
+ );
2147
+ const annotations = [...classDoc.annotations];
2148
+ diagnostics.push(...classDoc.diagnostics);
2149
+ const visiting = /* @__PURE__ */ new Set();
2150
+ const instanceMethods = [];
2151
+ const staticMethods = [];
2152
+ for (const member of classDecl.members) {
2153
+ if (ts3.isPropertyDeclaration(member)) {
2154
+ const fieldNode = analyzeFieldToIR(
2155
+ member,
2156
+ checker,
2157
+ file,
2158
+ typeRegistry,
2159
+ visiting,
2160
+ diagnostics,
2161
+ classType,
2162
+ extensionRegistry
2163
+ );
2164
+ if (fieldNode) {
2165
+ fields.push(fieldNode);
2166
+ fieldLayouts.push({});
2167
+ }
2168
+ } else if (ts3.isMethodDeclaration(member)) {
2169
+ const methodInfo = analyzeMethod(member, checker);
2170
+ if (methodInfo) {
2171
+ const isStatic = member.modifiers?.some((m) => m.kind === ts3.SyntaxKind.StaticKeyword);
2172
+ if (isStatic) {
2173
+ staticMethods.push(methodInfo);
2174
+ } else {
2175
+ instanceMethods.push(methodInfo);
2176
+ }
2177
+ }
2178
+ }
2179
+ }
2180
+ return {
2181
+ name,
2182
+ fields,
2183
+ fieldLayouts,
2184
+ typeRegistry,
2185
+ ...annotations.length > 0 && { annotations },
2186
+ ...diagnostics.length > 0 && { diagnostics },
2187
+ instanceMethods,
2188
+ staticMethods
2189
+ };
2190
+ }
2191
+ function analyzeInterfaceToIR(interfaceDecl, checker, file = "", extensionRegistry) {
2192
+ const name = interfaceDecl.name.text;
2193
+ const fields = [];
2194
+ const typeRegistry = {};
2195
+ const diagnostics = [];
2196
+ const interfaceType = checker.getTypeAtLocation(interfaceDecl);
2197
+ const interfaceDoc = extractJSDocParseResult(
2198
+ interfaceDecl,
2199
+ file,
2200
+ makeParseOptions(extensionRegistry, void 0, checker, interfaceType, interfaceType)
2201
+ );
2202
+ const annotations = [...interfaceDoc.annotations];
2203
+ diagnostics.push(...interfaceDoc.diagnostics);
2204
+ const visiting = /* @__PURE__ */ new Set();
2205
+ for (const member of interfaceDecl.members) {
2206
+ if (ts3.isPropertySignature(member)) {
2207
+ const fieldNode = analyzeInterfacePropertyToIR(
2208
+ member,
2209
+ checker,
2210
+ file,
2211
+ typeRegistry,
2212
+ visiting,
2213
+ diagnostics,
2214
+ interfaceType,
2215
+ extensionRegistry
2216
+ );
2217
+ if (fieldNode) {
2218
+ fields.push(fieldNode);
2219
+ }
2220
+ }
2221
+ }
2222
+ const fieldLayouts = fields.map(() => ({}));
2223
+ return {
2224
+ name,
2225
+ fields,
2226
+ fieldLayouts,
2227
+ typeRegistry,
2228
+ ...annotations.length > 0 && { annotations },
2229
+ ...diagnostics.length > 0 && { diagnostics },
2230
+ instanceMethods: [],
2231
+ staticMethods: []
2232
+ };
2233
+ }
2234
+ function analyzeTypeAliasToIR(typeAlias, checker, file = "", extensionRegistry) {
2235
+ if (!ts3.isTypeLiteralNode(typeAlias.type)) {
2236
+ const sourceFile = typeAlias.getSourceFile();
2237
+ const { line } = sourceFile.getLineAndCharacterOfPosition(typeAlias.getStart());
2238
+ const kindDesc = ts3.SyntaxKind[typeAlias.type.kind] ?? "unknown";
2239
+ return {
2240
+ ok: false,
2241
+ error: `Type alias "${typeAlias.name.text}" at line ${String(line + 1)} is not an object type literal (found ${kindDesc})`
2242
+ };
2243
+ }
2244
+ const name = typeAlias.name.text;
2245
+ const fields = [];
2246
+ const typeRegistry = {};
2247
+ const diagnostics = [];
2248
+ const aliasType = checker.getTypeAtLocation(typeAlias);
2249
+ const typeAliasDoc = extractJSDocParseResult(
2250
+ typeAlias,
2251
+ file,
2252
+ makeParseOptions(extensionRegistry, void 0, checker, aliasType, aliasType)
2253
+ );
2254
+ const annotations = [...typeAliasDoc.annotations];
2255
+ diagnostics.push(...typeAliasDoc.diagnostics);
2256
+ const visiting = /* @__PURE__ */ new Set();
2257
+ for (const member of typeAlias.type.members) {
2258
+ if (ts3.isPropertySignature(member)) {
2259
+ const fieldNode = analyzeInterfacePropertyToIR(
2260
+ member,
2261
+ checker,
2262
+ file,
2263
+ typeRegistry,
2264
+ visiting,
2265
+ diagnostics,
2266
+ aliasType,
2267
+ extensionRegistry
2268
+ );
2269
+ if (fieldNode) {
2270
+ fields.push(fieldNode);
2271
+ }
2272
+ }
2273
+ }
2274
+ return {
2275
+ ok: true,
2276
+ analysis: {
2277
+ name,
2278
+ fields,
2279
+ fieldLayouts: fields.map(() => ({})),
2280
+ typeRegistry,
2281
+ ...annotations.length > 0 && { annotations },
2282
+ ...diagnostics.length > 0 && { diagnostics },
2283
+ instanceMethods: [],
2284
+ staticMethods: []
2285
+ }
2286
+ };
2287
+ }
2288
+ function analyzeFieldToIR(prop, checker, file, typeRegistry, visiting, diagnostics, hostType, extensionRegistry) {
2289
+ if (!ts3.isIdentifier(prop.name)) {
2290
+ return null;
2291
+ }
2292
+ const name = prop.name.text;
2293
+ const tsType = checker.getTypeAtLocation(prop);
2294
+ const optional = prop.questionToken !== void 0;
2295
+ const provenance = provenanceForNode(prop, file);
2296
+ let type = resolveTypeNode(
2297
+ tsType,
2298
+ checker,
2299
+ file,
2300
+ typeRegistry,
2301
+ visiting,
2302
+ prop,
2303
+ extensionRegistry,
2304
+ diagnostics
2305
+ );
2306
+ const constraints = [];
2307
+ if (prop.type && !shouldEmitPrimitiveAliasDefinition(prop.type, checker)) {
2308
+ constraints.push(
2309
+ ...extractTypeAliasConstraintNodes(prop.type, checker, file, extensionRegistry)
2310
+ );
2311
+ }
2312
+ const docResult = extractJSDocParseResult(
2313
+ prop,
2314
+ file,
2315
+ makeParseOptions(extensionRegistry, type, checker, tsType, hostType)
2316
+ );
2317
+ constraints.push(...docResult.constraints);
2318
+ diagnostics.push(...docResult.diagnostics);
2319
+ let annotations = [];
2320
+ annotations.push(...docResult.annotations);
2321
+ const defaultAnnotation = extractDefaultValueAnnotation(prop.initializer, file);
2322
+ if (defaultAnnotation && !annotations.some((a) => a.annotationKind === "defaultValue")) {
2323
+ annotations.push(defaultAnnotation);
2324
+ }
2325
+ ({ type, annotations } = applyEnumMemberDisplayNames(type, annotations));
2326
+ return {
2327
+ kind: "field",
2328
+ name,
2329
+ type,
2330
+ required: !optional,
2331
+ constraints,
2332
+ annotations,
2333
+ provenance
2334
+ };
2335
+ }
2336
+ function analyzeInterfacePropertyToIR(prop, checker, file, typeRegistry, visiting, diagnostics, hostType, extensionRegistry) {
2337
+ if (!ts3.isIdentifier(prop.name)) {
2338
+ return null;
2339
+ }
2340
+ const name = prop.name.text;
2341
+ const tsType = checker.getTypeAtLocation(prop);
2342
+ const optional = prop.questionToken !== void 0;
2343
+ const provenance = provenanceForNode(prop, file);
2344
+ let type = resolveTypeNode(
2345
+ tsType,
2346
+ checker,
2347
+ file,
2348
+ typeRegistry,
2349
+ visiting,
2350
+ prop,
2351
+ extensionRegistry,
2352
+ diagnostics
2353
+ );
2354
+ const constraints = [];
2355
+ if (prop.type && !shouldEmitPrimitiveAliasDefinition(prop.type, checker)) {
2356
+ constraints.push(
2357
+ ...extractTypeAliasConstraintNodes(prop.type, checker, file, extensionRegistry)
2358
+ );
2359
+ }
2360
+ const docResult = extractJSDocParseResult(
2361
+ prop,
2362
+ file,
2363
+ makeParseOptions(extensionRegistry, type, checker, tsType, hostType)
2364
+ );
2365
+ constraints.push(...docResult.constraints);
2366
+ diagnostics.push(...docResult.diagnostics);
2367
+ let annotations = [];
2368
+ annotations.push(...docResult.annotations);
2369
+ ({ type, annotations } = applyEnumMemberDisplayNames(type, annotations));
2370
+ return {
2371
+ kind: "field",
2372
+ name,
2373
+ type,
2374
+ required: !optional,
2375
+ constraints,
2376
+ annotations,
2377
+ provenance
2378
+ };
2379
+ }
2380
+ function applyEnumMemberDisplayNames(type, annotations) {
2381
+ if (!annotations.some(
2382
+ (annotation) => annotation.annotationKind === "displayName" && annotation.value.trim().startsWith(":")
2383
+ )) {
2384
+ return { type, annotations: [...annotations] };
2385
+ }
2386
+ const consumed = /* @__PURE__ */ new Set();
2387
+ const nextType = rewriteEnumDisplayNames(type, annotations, consumed);
2388
+ if (consumed.size === 0) {
2389
+ return { type, annotations: [...annotations] };
2390
+ }
2391
+ return {
2392
+ type: nextType,
2393
+ annotations: annotations.filter((annotation) => !consumed.has(annotation))
2394
+ };
2395
+ }
2396
+ function rewriteEnumDisplayNames(type, annotations, consumed) {
2397
+ switch (type.kind) {
2398
+ case "enum":
2399
+ return applyEnumMemberDisplayNamesToEnum(type, annotations, consumed);
2400
+ case "union": {
2401
+ return {
2402
+ ...type,
2403
+ members: type.members.map(
2404
+ (member) => rewriteEnumDisplayNames(member, annotations, consumed)
2405
+ )
2406
+ };
2407
+ }
2408
+ default:
2409
+ return type;
2410
+ }
2411
+ }
2412
+ function applyEnumMemberDisplayNamesToEnum(type, annotations, consumed) {
2413
+ const displayNames = /* @__PURE__ */ new Map();
2414
+ for (const annotation of annotations) {
2415
+ if (annotation.annotationKind !== "displayName") continue;
2416
+ const parsed = parseEnumMemberDisplayName(annotation.value);
2417
+ if (!parsed) continue;
2418
+ consumed.add(annotation);
2419
+ const member = type.members.find((m) => String(m.value) === parsed.value);
2420
+ if (!member) continue;
2421
+ displayNames.set(String(member.value), parsed.label);
2422
+ }
2423
+ if (displayNames.size === 0) {
2424
+ return type;
2425
+ }
2426
+ return {
2427
+ ...type,
2428
+ members: type.members.map((member) => {
2429
+ const displayName = displayNames.get(String(member.value));
2430
+ return displayName !== void 0 ? { ...member, displayName } : member;
2431
+ })
2432
+ };
2433
+ }
2434
+ function parseEnumMemberDisplayName(value) {
2435
+ const trimmed = value.trim();
2436
+ const match = /^:([^\s]+)\s+([\s\S]+)$/.exec(trimmed);
2437
+ if (!match?.[1] || !match[2]) return null;
2438
+ const label = match[2].trim();
2439
+ if (label === "") return null;
2440
+ return { value: match[1], label };
2441
+ }
2442
+ function resolveRegisteredCustomType(sourceNode, extensionRegistry, checker) {
2443
+ if (sourceNode === void 0 || extensionRegistry === void 0) {
2444
+ return null;
2445
+ }
2446
+ const typeNode = extractTypeNodeFromSource(sourceNode);
2447
+ if (typeNode === void 0) {
2448
+ return null;
2449
+ }
2450
+ return resolveRegisteredCustomTypeFromTypeNode(typeNode, extensionRegistry, checker);
2451
+ }
2452
+ function resolveRegisteredCustomTypeFromTypeNode(typeNode, extensionRegistry, checker) {
2453
+ if (ts3.isParenthesizedTypeNode(typeNode)) {
2454
+ return resolveRegisteredCustomTypeFromTypeNode(typeNode.type, extensionRegistry, checker);
2455
+ }
2456
+ const typeName = getTypeNodeRegistrationName(typeNode);
2457
+ if (typeName === null) {
2458
+ return null;
2459
+ }
2460
+ const registration = extensionRegistry.findTypeByName(typeName);
2461
+ if (registration !== void 0) {
2462
+ return {
2463
+ kind: "custom",
2464
+ typeId: `${registration.extensionId}/${registration.registration.typeName}`,
2465
+ payload: null
2466
+ };
2467
+ }
2468
+ if (ts3.isTypeReferenceNode(typeNode) && ts3.isIdentifier(typeNode.typeName)) {
2469
+ const aliasDecl = checker.getSymbolAtLocation(typeNode.typeName)?.declarations?.find(ts3.isTypeAliasDeclaration);
2470
+ if (aliasDecl !== void 0) {
2471
+ return resolveRegisteredCustomTypeFromTypeNode(aliasDecl.type, extensionRegistry, checker);
2472
+ }
2473
+ }
2474
+ return null;
2475
+ }
2476
+ function extractTypeNodeFromSource(sourceNode) {
2477
+ if (ts3.isPropertyDeclaration(sourceNode) || ts3.isPropertySignature(sourceNode) || ts3.isParameter(sourceNode) || ts3.isTypeAliasDeclaration(sourceNode)) {
2478
+ return sourceNode.type;
2479
+ }
2480
+ if (ts3.isTypeNode(sourceNode)) {
2481
+ return sourceNode;
2482
+ }
2483
+ return void 0;
2484
+ }
2485
+ function getTypeNodeRegistrationName(typeNode) {
2486
+ if (ts3.isTypeReferenceNode(typeNode)) {
2487
+ return ts3.isIdentifier(typeNode.typeName) ? typeNode.typeName.text : typeNode.typeName.right.text;
2488
+ }
2489
+ if (ts3.isParenthesizedTypeNode(typeNode)) {
2490
+ return getTypeNodeRegistrationName(typeNode.type);
2491
+ }
2492
+ if (typeNode.kind === ts3.SyntaxKind.BigIntKeyword || typeNode.kind === ts3.SyntaxKind.StringKeyword || typeNode.kind === ts3.SyntaxKind.NumberKeyword || typeNode.kind === ts3.SyntaxKind.BooleanKeyword) {
2493
+ return typeNode.getText();
2494
+ }
2495
+ return null;
2496
+ }
2497
+ function resolveTypeNode(type, checker, file, typeRegistry, visiting, sourceNode, extensionRegistry, diagnostics) {
2498
+ const customType = resolveRegisteredCustomType(sourceNode, extensionRegistry, checker);
2499
+ if (customType) {
2500
+ return customType;
2501
+ }
2502
+ const primitiveAlias = tryResolveNamedPrimitiveAlias(
2503
+ type,
2504
+ checker,
2505
+ file,
2506
+ typeRegistry,
2507
+ visiting,
2508
+ sourceNode,
2509
+ extensionRegistry,
2510
+ diagnostics
2511
+ );
2512
+ if (primitiveAlias) {
2513
+ return primitiveAlias;
2514
+ }
2515
+ if (type.flags & ts3.TypeFlags.String) {
2516
+ return { kind: "primitive", primitiveKind: "string" };
2517
+ }
2518
+ if (type.flags & ts3.TypeFlags.Number) {
2519
+ return { kind: "primitive", primitiveKind: "number" };
2520
+ }
2521
+ if (type.flags & (ts3.TypeFlags.BigInt | ts3.TypeFlags.BigIntLiteral)) {
2522
+ return { kind: "primitive", primitiveKind: "bigint" };
2523
+ }
2524
+ if (type.flags & ts3.TypeFlags.Boolean) {
2525
+ return { kind: "primitive", primitiveKind: "boolean" };
2526
+ }
2527
+ if (type.flags & ts3.TypeFlags.Null) {
2528
+ return { kind: "primitive", primitiveKind: "null" };
2529
+ }
2530
+ if (type.flags & ts3.TypeFlags.Undefined) {
2531
+ return { kind: "primitive", primitiveKind: "null" };
2532
+ }
2533
+ if (type.isStringLiteral()) {
2534
+ return {
2535
+ kind: "enum",
2536
+ members: [{ value: type.value }]
2537
+ };
2538
+ }
2539
+ if (type.isNumberLiteral()) {
2540
+ return {
2541
+ kind: "enum",
2542
+ members: [{ value: type.value }]
2543
+ };
2544
+ }
2545
+ if (type.isUnion()) {
2546
+ return resolveUnionType(
2547
+ type,
2548
+ checker,
2549
+ file,
2550
+ typeRegistry,
2551
+ visiting,
2552
+ sourceNode,
2553
+ extensionRegistry,
2554
+ diagnostics
2555
+ );
2556
+ }
2557
+ if (checker.isArrayType(type)) {
2558
+ return resolveArrayType(
2559
+ type,
2560
+ checker,
2561
+ file,
2562
+ typeRegistry,
2563
+ visiting,
2564
+ sourceNode,
2565
+ extensionRegistry,
2566
+ diagnostics
2567
+ );
2568
+ }
2569
+ if (isObjectType(type)) {
2570
+ return resolveObjectType(
2571
+ type,
2572
+ checker,
2573
+ file,
2574
+ typeRegistry,
2575
+ visiting,
2576
+ extensionRegistry,
2577
+ diagnostics
2578
+ );
2579
+ }
2580
+ return { kind: "primitive", primitiveKind: "string" };
2581
+ }
2582
+ function tryResolveNamedPrimitiveAlias(type, checker, file, typeRegistry, visiting, sourceNode, extensionRegistry, diagnostics) {
2583
+ if (!(type.flags & (ts3.TypeFlags.String | ts3.TypeFlags.Number | ts3.TypeFlags.BigInt | ts3.TypeFlags.BigIntLiteral | ts3.TypeFlags.Boolean | ts3.TypeFlags.Null))) {
2584
+ return null;
2585
+ }
2586
+ const aliasDecl = type.aliasSymbol?.declarations?.find(ts3.isTypeAliasDeclaration) ?? getReferencedTypeAliasDeclaration(sourceNode, checker);
2587
+ if (!aliasDecl) {
2588
+ return null;
2589
+ }
2590
+ const aliasName = aliasDecl.name.text;
2591
+ if (!typeRegistry[aliasName]) {
2592
+ const aliasType = checker.getTypeFromTypeNode(aliasDecl.type);
2593
+ const constraints = [
2594
+ ...extractJSDocConstraintNodes(aliasDecl, file, makeParseOptions(extensionRegistry)),
2595
+ ...extractTypeAliasConstraintNodes(aliasDecl.type, checker, file, extensionRegistry)
2596
+ ];
2597
+ const annotations = extractJSDocAnnotationNodes(
2598
+ aliasDecl,
2599
+ file,
2600
+ makeParseOptions(extensionRegistry)
2601
+ );
2602
+ typeRegistry[aliasName] = {
2603
+ name: aliasName,
2604
+ type: resolveAliasedPrimitiveTarget(
2605
+ aliasType,
2606
+ checker,
2607
+ file,
2608
+ typeRegistry,
2609
+ visiting,
2610
+ extensionRegistry,
2611
+ diagnostics
2612
+ ),
2613
+ ...constraints.length > 0 && { constraints },
2614
+ ...annotations.length > 0 && { annotations },
2615
+ provenance: provenanceForDeclaration(aliasDecl, file)
2616
+ };
2617
+ }
2618
+ return { kind: "reference", name: aliasName, typeArguments: [] };
2619
+ }
2620
+ function getReferencedTypeAliasDeclaration(sourceNode, checker) {
2621
+ const typeNode = sourceNode && (ts3.isPropertyDeclaration(sourceNode) || ts3.isPropertySignature(sourceNode) || ts3.isParameter(sourceNode)) ? sourceNode.type : void 0;
2622
+ if (!typeNode || !ts3.isTypeReferenceNode(typeNode)) {
2623
+ return void 0;
2624
+ }
2625
+ return checker.getSymbolAtLocation(typeNode.typeName)?.declarations?.find(ts3.isTypeAliasDeclaration);
2626
+ }
2627
+ function shouldEmitPrimitiveAliasDefinition(typeNode, checker) {
2628
+ if (!ts3.isTypeReferenceNode(typeNode)) {
2629
+ return false;
2630
+ }
2631
+ const aliasDecl = checker.getSymbolAtLocation(typeNode.typeName)?.declarations?.find(ts3.isTypeAliasDeclaration);
2632
+ if (!aliasDecl) {
2633
+ return false;
2634
+ }
2635
+ const resolved = checker.getTypeFromTypeNode(aliasDecl.type);
2636
+ return !!(resolved.flags & (ts3.TypeFlags.String | ts3.TypeFlags.Number | ts3.TypeFlags.BigInt | ts3.TypeFlags.BigIntLiteral | ts3.TypeFlags.Boolean | ts3.TypeFlags.Null));
2637
+ }
2638
+ function resolveAliasedPrimitiveTarget(type, checker, file, typeRegistry, visiting, extensionRegistry, diagnostics) {
2639
+ const nestedAliasDecl = type.aliasSymbol?.declarations?.find(ts3.isTypeAliasDeclaration);
2640
+ if (nestedAliasDecl !== void 0) {
2641
+ return resolveAliasedPrimitiveTarget(
2642
+ checker.getTypeFromTypeNode(nestedAliasDecl.type),
2643
+ checker,
2644
+ file,
2645
+ typeRegistry,
2646
+ visiting,
2647
+ extensionRegistry,
2648
+ diagnostics
2649
+ );
2650
+ }
2651
+ return resolveTypeNode(
2652
+ type,
2653
+ checker,
2654
+ file,
2655
+ typeRegistry,
2656
+ visiting,
2657
+ void 0,
2658
+ extensionRegistry,
2659
+ diagnostics
2660
+ );
2661
+ }
2662
+ function resolveUnionType(type, checker, file, typeRegistry, visiting, sourceNode, extensionRegistry, diagnostics) {
2663
+ const typeName = getNamedTypeName(type);
2664
+ const namedDecl = getNamedTypeDeclaration(type);
2665
+ if (typeName && typeName in typeRegistry) {
2666
+ return { kind: "reference", name: typeName, typeArguments: [] };
2667
+ }
2668
+ const allTypes = type.types;
2669
+ const unionMemberTypeNodes = extractUnionMemberTypeNodes(sourceNode, checker);
2670
+ const nonNullSourceNodes = unionMemberTypeNodes.filter(
2671
+ (memberTypeNode) => !isNullishTypeNode(resolveAliasedTypeNode(memberTypeNode, checker))
2672
+ );
2673
+ const nonNullTypes = allTypes.filter(
2674
+ (memberType) => !(memberType.flags & (ts3.TypeFlags.Null | ts3.TypeFlags.Undefined))
2675
+ );
2676
+ const nonNullMembers = nonNullTypes.map((memberType, index) => ({
2677
+ memberType,
2678
+ sourceNode: nonNullSourceNodes.length === nonNullTypes.length ? nonNullSourceNodes[index] : void 0
2679
+ }));
2680
+ const hasNull = allTypes.some((t) => t.flags & ts3.TypeFlags.Null);
2681
+ const memberDisplayNames = /* @__PURE__ */ new Map();
2682
+ if (namedDecl) {
2683
+ for (const [value, label] of extractDisplayNameMetadata(namedDecl).memberDisplayNames) {
2684
+ memberDisplayNames.set(value, label);
2685
+ }
2686
+ }
2687
+ if (sourceNode) {
2688
+ for (const [value, label] of extractDisplayNameMetadata(sourceNode).memberDisplayNames) {
2689
+ memberDisplayNames.set(value, label);
2690
+ }
2691
+ }
2692
+ const registerNamed = (result) => {
2693
+ if (!typeName) {
2694
+ return result;
2695
+ }
2696
+ const annotations = namedDecl ? extractJSDocAnnotationNodes(namedDecl, file, makeParseOptions(extensionRegistry)) : void 0;
2697
+ typeRegistry[typeName] = {
2698
+ name: typeName,
2699
+ type: result,
2700
+ ...annotations !== void 0 && annotations.length > 0 && { annotations },
2701
+ provenance: provenanceForDeclaration(namedDecl ?? sourceNode, file)
2702
+ };
2703
+ return { kind: "reference", name: typeName, typeArguments: [] };
2704
+ };
2705
+ const applyMemberLabels = (members2) => members2.map((value) => {
2706
+ const displayName = memberDisplayNames.get(String(value));
2707
+ return displayName !== void 0 ? { value, displayName } : { value };
2708
+ });
2709
+ const isBooleanUnion2 = nonNullTypes.length === 2 && nonNullTypes.every((t) => t.flags & ts3.TypeFlags.BooleanLiteral);
2710
+ if (isBooleanUnion2) {
2711
+ const boolNode = { kind: "primitive", primitiveKind: "boolean" };
2712
+ const result = hasNull ? {
2713
+ kind: "union",
2714
+ members: [boolNode, { kind: "primitive", primitiveKind: "null" }]
2715
+ } : boolNode;
2716
+ return registerNamed(result);
2717
+ }
2718
+ const allStringLiterals = nonNullTypes.every((t) => t.isStringLiteral());
2719
+ if (allStringLiterals && nonNullTypes.length > 0) {
2720
+ const stringTypes = nonNullTypes.filter((t) => t.isStringLiteral());
2721
+ const enumNode = {
2722
+ kind: "enum",
2723
+ members: applyMemberLabels(stringTypes.map((t) => t.value))
2724
+ };
2725
+ const result = hasNull ? {
2726
+ kind: "union",
2727
+ members: [enumNode, { kind: "primitive", primitiveKind: "null" }]
2728
+ } : enumNode;
2729
+ return registerNamed(result);
2730
+ }
2731
+ const allNumberLiterals = nonNullTypes.every((t) => t.isNumberLiteral());
2732
+ if (allNumberLiterals && nonNullTypes.length > 0) {
2733
+ const numberTypes = nonNullTypes.filter((t) => t.isNumberLiteral());
2734
+ const enumNode = {
2735
+ kind: "enum",
2736
+ members: applyMemberLabels(numberTypes.map((t) => t.value))
2737
+ };
2738
+ const result = hasNull ? {
2739
+ kind: "union",
2740
+ members: [enumNode, { kind: "primitive", primitiveKind: "null" }]
2741
+ } : enumNode;
2742
+ return registerNamed(result);
2743
+ }
2744
+ if (nonNullMembers.length === 1 && nonNullMembers[0]) {
2745
+ const inner = resolveTypeNode(
2746
+ nonNullMembers[0].memberType,
2747
+ checker,
2748
+ file,
2749
+ typeRegistry,
2750
+ visiting,
2751
+ nonNullMembers[0].sourceNode ?? sourceNode,
2752
+ extensionRegistry,
2753
+ diagnostics
2754
+ );
2755
+ const result = hasNull ? {
2756
+ kind: "union",
2757
+ members: [inner, { kind: "primitive", primitiveKind: "null" }]
2758
+ } : inner;
2759
+ return registerNamed(result);
2760
+ }
2761
+ const members = nonNullMembers.map(
2762
+ ({ memberType, sourceNode: memberSourceNode }) => resolveTypeNode(
2763
+ memberType,
2764
+ checker,
2765
+ file,
2766
+ typeRegistry,
2767
+ visiting,
2768
+ memberSourceNode ?? sourceNode,
2769
+ extensionRegistry,
2770
+ diagnostics
2771
+ )
2772
+ );
2773
+ if (hasNull) {
2774
+ members.push({ kind: "primitive", primitiveKind: "null" });
2775
+ }
2776
+ return registerNamed({ kind: "union", members });
2777
+ }
2778
+ function resolveArrayType(type, checker, file, typeRegistry, visiting, sourceNode, extensionRegistry, diagnostics) {
2779
+ const typeArgs = isTypeReference(type) ? type.typeArguments : void 0;
2780
+ const elementType = typeArgs?.[0];
2781
+ const elementSourceNode = extractArrayElementTypeNode(sourceNode, checker);
2782
+ const items = elementType ? resolveTypeNode(
2783
+ elementType,
2784
+ checker,
2785
+ file,
2786
+ typeRegistry,
2787
+ visiting,
2788
+ elementSourceNode,
2789
+ extensionRegistry,
2790
+ diagnostics
2791
+ ) : { kind: "primitive", primitiveKind: "string" };
2792
+ return { kind: "array", items };
2793
+ }
2794
+ function tryResolveRecordType(type, checker, file, typeRegistry, visiting, extensionRegistry, diagnostics) {
2795
+ if (type.getProperties().length > 0) {
2796
+ return null;
2797
+ }
2798
+ const indexInfo = checker.getIndexInfoOfType(type, ts3.IndexKind.String);
2799
+ if (!indexInfo) {
2800
+ return null;
2801
+ }
2802
+ const valueType = resolveTypeNode(
2803
+ indexInfo.type,
2804
+ checker,
2805
+ file,
2806
+ typeRegistry,
2807
+ visiting,
2808
+ void 0,
2809
+ extensionRegistry,
2810
+ diagnostics
2811
+ );
2812
+ return { kind: "record", valueType };
2813
+ }
2814
+ function typeNodeContainsReference(type, targetName) {
2815
+ switch (type.kind) {
2816
+ case "reference":
2817
+ return type.name === targetName;
2818
+ case "array":
2819
+ return typeNodeContainsReference(type.items, targetName);
2820
+ case "record":
2821
+ return typeNodeContainsReference(type.valueType, targetName);
2822
+ case "union":
2823
+ return type.members.some((member) => typeNodeContainsReference(member, targetName));
2824
+ case "object":
2825
+ return type.properties.some(
2826
+ (property) => typeNodeContainsReference(property.type, targetName)
2827
+ );
2828
+ case "primitive":
2829
+ case "enum":
2830
+ case "dynamic":
2831
+ case "custom":
2832
+ return false;
2833
+ default: {
2834
+ const _exhaustive = type;
2835
+ return _exhaustive;
2836
+ }
2837
+ }
2838
+ }
2839
+ function resolveObjectType(type, checker, file, typeRegistry, visiting, extensionRegistry, diagnostics) {
2840
+ const typeName = getNamedTypeName(type);
2841
+ const namedTypeName = typeName ?? void 0;
2842
+ const namedDecl = getNamedTypeDeclaration(type);
2843
+ const shouldRegisterNamedType = namedTypeName !== void 0 && !(namedTypeName === "Record" && namedDecl?.getSourceFile().fileName !== file);
2844
+ const clearNamedTypeRegistration = () => {
2845
+ if (namedTypeName === void 0 || !shouldRegisterNamedType) {
2846
+ return;
2847
+ }
2848
+ Reflect.deleteProperty(typeRegistry, namedTypeName);
2849
+ };
2850
+ if (visiting.has(type)) {
2851
+ if (namedTypeName !== void 0 && shouldRegisterNamedType) {
2852
+ return { kind: "reference", name: namedTypeName, typeArguments: [] };
2853
+ }
2854
+ return { kind: "object", properties: [], additionalProperties: false };
2855
+ }
2856
+ if (namedTypeName !== void 0 && shouldRegisterNamedType && !typeRegistry[namedTypeName]) {
2857
+ typeRegistry[namedTypeName] = {
2858
+ name: namedTypeName,
2859
+ type: RESOLVING_TYPE_PLACEHOLDER,
2860
+ provenance: provenanceForDeclaration(namedDecl, file)
2861
+ };
2862
+ }
2863
+ visiting.add(type);
2864
+ if (namedTypeName !== void 0 && shouldRegisterNamedType && typeRegistry[namedTypeName]?.type !== void 0) {
2865
+ if (typeRegistry[namedTypeName].type !== RESOLVING_TYPE_PLACEHOLDER) {
2866
+ visiting.delete(type);
2867
+ return { kind: "reference", name: namedTypeName, typeArguments: [] };
2868
+ }
2869
+ }
2870
+ const recordNode = tryResolveRecordType(
2871
+ type,
2872
+ checker,
2873
+ file,
2874
+ typeRegistry,
2875
+ visiting,
2876
+ extensionRegistry,
2877
+ diagnostics
2878
+ );
2879
+ if (recordNode) {
2880
+ visiting.delete(type);
2881
+ if (namedTypeName !== void 0 && shouldRegisterNamedType) {
2882
+ const isRecursiveRecord = typeNodeContainsReference(recordNode.valueType, namedTypeName);
2883
+ if (!isRecursiveRecord) {
2884
+ clearNamedTypeRegistration();
2885
+ return recordNode;
2886
+ }
2887
+ const annotations = namedDecl ? extractJSDocAnnotationNodes(namedDecl, file, makeParseOptions(extensionRegistry)) : void 0;
2888
+ typeRegistry[namedTypeName] = {
2889
+ name: namedTypeName,
2890
+ type: recordNode,
2891
+ ...annotations !== void 0 && annotations.length > 0 && { annotations },
2892
+ provenance: provenanceForDeclaration(namedDecl, file)
2893
+ };
2894
+ return { kind: "reference", name: namedTypeName, typeArguments: [] };
2895
+ }
2896
+ return recordNode;
2897
+ }
2898
+ const properties = [];
2899
+ const fieldInfoMap = getNamedTypeFieldNodeInfoMap(
2900
+ type,
2901
+ checker,
2902
+ file,
2903
+ typeRegistry,
2904
+ visiting,
2905
+ diagnostics ?? [],
2906
+ extensionRegistry
2907
+ );
2908
+ for (const prop of type.getProperties()) {
2909
+ const declaration = prop.valueDeclaration ?? prop.declarations?.[0];
2910
+ if (!declaration) continue;
2911
+ const propType = checker.getTypeOfSymbolAtLocation(prop, declaration);
2912
+ const optional = !!(prop.flags & ts3.SymbolFlags.Optional);
2913
+ const propTypeNode = resolveTypeNode(
2914
+ propType,
2915
+ checker,
2916
+ file,
2917
+ typeRegistry,
2918
+ visiting,
2919
+ declaration,
2920
+ extensionRegistry,
2921
+ diagnostics
2922
+ );
2923
+ const fieldNodeInfo = fieldInfoMap?.get(prop.name);
2924
+ properties.push({
2925
+ name: prop.name,
2926
+ type: propTypeNode,
2927
+ optional,
2928
+ constraints: fieldNodeInfo?.constraints ?? [],
2929
+ annotations: fieldNodeInfo?.annotations ?? [],
2930
+ provenance: fieldNodeInfo?.provenance ?? provenanceForFile(file)
2931
+ });
2932
+ }
2933
+ visiting.delete(type);
2934
+ const objectNode = {
2935
+ kind: "object",
2936
+ properties,
2937
+ additionalProperties: true
2938
+ };
2939
+ if (namedTypeName !== void 0 && shouldRegisterNamedType) {
2940
+ const annotations = namedDecl ? extractJSDocAnnotationNodes(namedDecl, file, makeParseOptions(extensionRegistry)) : void 0;
2941
+ typeRegistry[namedTypeName] = {
2942
+ name: namedTypeName,
2943
+ type: objectNode,
2944
+ ...annotations !== void 0 && annotations.length > 0 && { annotations },
2945
+ provenance: provenanceForDeclaration(namedDecl, file)
2946
+ };
2947
+ return { kind: "reference", name: namedTypeName, typeArguments: [] };
2948
+ }
2949
+ return objectNode;
2950
+ }
2951
+ function getNamedTypeFieldNodeInfoMap(type, checker, file, typeRegistry, visiting, diagnostics, extensionRegistry) {
2952
+ const symbols = [type.getSymbol(), type.aliasSymbol].filter(
2953
+ (s) => s?.declarations != null && s.declarations.length > 0
2954
+ );
2955
+ for (const symbol of symbols) {
2956
+ const declarations = symbol.declarations;
2957
+ if (!declarations) continue;
2958
+ const classDecl = declarations.find(ts3.isClassDeclaration);
2959
+ if (classDecl) {
2960
+ const map = /* @__PURE__ */ new Map();
2961
+ const hostType = checker.getTypeAtLocation(classDecl);
2962
+ for (const member of classDecl.members) {
2963
+ if (ts3.isPropertyDeclaration(member) && ts3.isIdentifier(member.name)) {
2964
+ const fieldNode = analyzeFieldToIR(
2965
+ member,
2966
+ checker,
2967
+ file,
2968
+ typeRegistry,
2969
+ visiting,
2970
+ diagnostics,
2971
+ hostType,
2972
+ extensionRegistry
2973
+ );
2974
+ if (fieldNode) {
2975
+ map.set(fieldNode.name, {
2976
+ constraints: [...fieldNode.constraints],
2977
+ annotations: [...fieldNode.annotations],
2978
+ provenance: fieldNode.provenance
2979
+ });
2980
+ }
2981
+ }
2982
+ }
2983
+ return map;
2984
+ }
2985
+ const interfaceDecl = declarations.find(ts3.isInterfaceDeclaration);
2986
+ if (interfaceDecl) {
2987
+ return buildFieldNodeInfoMap(
2988
+ interfaceDecl.members,
2989
+ checker,
2990
+ file,
2991
+ typeRegistry,
2992
+ visiting,
2993
+ checker.getTypeAtLocation(interfaceDecl),
2994
+ diagnostics,
2995
+ extensionRegistry
2996
+ );
2997
+ }
2998
+ const typeAliasDecl = declarations.find(ts3.isTypeAliasDeclaration);
2999
+ if (typeAliasDecl && ts3.isTypeLiteralNode(typeAliasDecl.type)) {
3000
+ return buildFieldNodeInfoMap(
3001
+ typeAliasDecl.type.members,
3002
+ checker,
3003
+ file,
3004
+ typeRegistry,
3005
+ visiting,
3006
+ checker.getTypeAtLocation(typeAliasDecl),
3007
+ diagnostics,
3008
+ extensionRegistry
3009
+ );
3010
+ }
3011
+ }
3012
+ return null;
3013
+ }
3014
+ function extractArrayElementTypeNode(sourceNode, checker) {
3015
+ const typeNode = sourceNode === void 0 ? void 0 : extractTypeNodeFromSource(sourceNode);
3016
+ if (typeNode === void 0) {
3017
+ return void 0;
3018
+ }
3019
+ const resolvedTypeNode = resolveAliasedTypeNode(typeNode, checker);
3020
+ if (ts3.isArrayTypeNode(resolvedTypeNode)) {
3021
+ return resolvedTypeNode.elementType;
3022
+ }
3023
+ if (ts3.isTypeReferenceNode(resolvedTypeNode) && ts3.isIdentifier(resolvedTypeNode.typeName) && resolvedTypeNode.typeName.text === "Array" && resolvedTypeNode.typeArguments?.[0]) {
3024
+ return resolvedTypeNode.typeArguments[0];
3025
+ }
3026
+ return void 0;
3027
+ }
3028
+ function extractUnionMemberTypeNodes(sourceNode, checker) {
3029
+ const typeNode = sourceNode === void 0 ? void 0 : extractTypeNodeFromSource(sourceNode);
3030
+ if (!typeNode) {
3031
+ return [];
3032
+ }
3033
+ const resolvedTypeNode = resolveAliasedTypeNode(typeNode, checker);
3034
+ return ts3.isUnionTypeNode(resolvedTypeNode) ? [...resolvedTypeNode.types] : [];
3035
+ }
3036
+ function resolveAliasedTypeNode(typeNode, checker, visited = /* @__PURE__ */ new Set()) {
3037
+ if (ts3.isParenthesizedTypeNode(typeNode)) {
3038
+ return resolveAliasedTypeNode(typeNode.type, checker, visited);
3039
+ }
3040
+ if (!ts3.isTypeReferenceNode(typeNode) || !ts3.isIdentifier(typeNode.typeName)) {
3041
+ return typeNode;
3042
+ }
3043
+ const symbol = checker.getSymbolAtLocation(typeNode.typeName);
3044
+ const aliasDecl = symbol?.declarations?.find(ts3.isTypeAliasDeclaration);
3045
+ if (aliasDecl === void 0 || visited.has(aliasDecl)) {
3046
+ return typeNode;
3047
+ }
3048
+ visited.add(aliasDecl);
3049
+ return resolveAliasedTypeNode(aliasDecl.type, checker, visited);
3050
+ }
3051
+ function isNullishTypeNode(typeNode) {
3052
+ if (typeNode.kind === ts3.SyntaxKind.NullKeyword || typeNode.kind === ts3.SyntaxKind.UndefinedKeyword) {
3053
+ return true;
3054
+ }
3055
+ return ts3.isLiteralTypeNode(typeNode) && (typeNode.literal.kind === ts3.SyntaxKind.NullKeyword || typeNode.literal.kind === ts3.SyntaxKind.UndefinedKeyword);
3056
+ }
3057
+ function buildFieldNodeInfoMap(members, checker, file, typeRegistry, visiting, hostType, diagnostics, extensionRegistry) {
3058
+ const map = /* @__PURE__ */ new Map();
3059
+ for (const member of members) {
3060
+ if (ts3.isPropertySignature(member)) {
3061
+ const fieldNode = analyzeInterfacePropertyToIR(
3062
+ member,
3063
+ checker,
3064
+ file,
3065
+ typeRegistry,
3066
+ visiting,
3067
+ diagnostics,
3068
+ hostType,
3069
+ extensionRegistry
3070
+ );
3071
+ if (fieldNode) {
3072
+ map.set(fieldNode.name, {
3073
+ constraints: [...fieldNode.constraints],
3074
+ annotations: [...fieldNode.annotations],
3075
+ provenance: fieldNode.provenance
3076
+ });
3077
+ }
3078
+ }
3079
+ }
3080
+ return map;
3081
+ }
3082
+ function extractTypeAliasConstraintNodes(typeNode, checker, file, extensionRegistry, depth = 0) {
3083
+ if (!ts3.isTypeReferenceNode(typeNode)) return [];
3084
+ if (depth >= MAX_ALIAS_CHAIN_DEPTH) {
3085
+ const aliasName = typeNode.typeName.getText();
3086
+ throw new Error(
3087
+ `Type alias chain exceeds maximum depth of ${String(MAX_ALIAS_CHAIN_DEPTH)} at alias "${aliasName}" in ${file}. Simplify the alias chain or check for circular references.`
3088
+ );
3089
+ }
3090
+ const symbol = checker.getSymbolAtLocation(typeNode.typeName);
3091
+ if (!symbol?.declarations) return [];
3092
+ const aliasDecl = symbol.declarations.find(ts3.isTypeAliasDeclaration);
3093
+ if (!aliasDecl) return [];
3094
+ if (ts3.isTypeLiteralNode(aliasDecl.type)) return [];
3095
+ const aliasFieldType = resolveTypeNode(
3096
+ checker.getTypeAtLocation(aliasDecl.type),
3097
+ checker,
3098
+ file,
3099
+ {},
3100
+ /* @__PURE__ */ new Set(),
3101
+ aliasDecl.type,
3102
+ extensionRegistry
3103
+ );
3104
+ const constraints = extractJSDocConstraintNodes(
3105
+ aliasDecl,
3106
+ file,
3107
+ makeParseOptions(extensionRegistry, aliasFieldType)
3108
+ );
3109
+ constraints.push(
3110
+ ...extractTypeAliasConstraintNodes(aliasDecl.type, checker, file, extensionRegistry, depth + 1)
3111
+ );
3112
+ return constraints;
3113
+ }
3114
+ function provenanceForNode(node, file) {
3115
+ const sourceFile = node.getSourceFile();
3116
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
3117
+ return {
3118
+ surface: "tsdoc",
3119
+ file,
3120
+ line: line + 1,
3121
+ column: character
3122
+ };
3123
+ }
3124
+ function provenanceForFile(file) {
3125
+ return { surface: "tsdoc", file, line: 0, column: 0 };
3126
+ }
3127
+ function provenanceForDeclaration(node, file) {
3128
+ if (!node) {
3129
+ return provenanceForFile(file);
3130
+ }
3131
+ return provenanceForNode(node, file);
3132
+ }
3133
+ function getNamedTypeName(type) {
3134
+ const symbol = type.getSymbol();
3135
+ if (symbol?.declarations) {
3136
+ const decl = symbol.declarations[0];
3137
+ if (decl && (ts3.isClassDeclaration(decl) || ts3.isInterfaceDeclaration(decl) || ts3.isTypeAliasDeclaration(decl))) {
3138
+ const name = ts3.isClassDeclaration(decl) ? decl.name?.text : decl.name.text;
3139
+ if (name) return name;
3140
+ }
3141
+ }
3142
+ const aliasSymbol = type.aliasSymbol;
3143
+ if (aliasSymbol?.declarations) {
3144
+ const aliasDecl = aliasSymbol.declarations.find(ts3.isTypeAliasDeclaration);
3145
+ if (aliasDecl) {
3146
+ return aliasDecl.name.text;
3147
+ }
3148
+ }
3149
+ return null;
3150
+ }
3151
+ function getNamedTypeDeclaration(type) {
3152
+ const symbol = type.getSymbol();
3153
+ if (symbol?.declarations) {
3154
+ const decl = symbol.declarations[0];
3155
+ if (decl && (ts3.isClassDeclaration(decl) || ts3.isInterfaceDeclaration(decl) || ts3.isTypeAliasDeclaration(decl))) {
3156
+ return decl;
3157
+ }
3158
+ }
3159
+ const aliasSymbol = type.aliasSymbol;
3160
+ if (aliasSymbol?.declarations) {
3161
+ return aliasSymbol.declarations.find(ts3.isTypeAliasDeclaration);
3162
+ }
3163
+ return void 0;
3164
+ }
3165
+ function analyzeMethod(method, checker) {
3166
+ if (!ts3.isIdentifier(method.name)) {
3167
+ return null;
3168
+ }
3169
+ const name = method.name.text;
3170
+ const parameters = [];
3171
+ for (const param of method.parameters) {
3172
+ if (ts3.isIdentifier(param.name)) {
3173
+ const paramInfo = analyzeParameter(param, checker);
3174
+ parameters.push(paramInfo);
3175
+ }
3176
+ }
3177
+ const returnTypeNode = method.type;
3178
+ const signature = checker.getSignatureFromDeclaration(method);
3179
+ const returnType = signature ? checker.getReturnTypeOfSignature(signature) : checker.getTypeAtLocation(method);
3180
+ return { name, parameters, returnTypeNode, returnType };
3181
+ }
3182
+ function analyzeParameter(param, checker) {
3183
+ const name = ts3.isIdentifier(param.name) ? param.name.text : "param";
3184
+ const typeNode = param.type;
3185
+ const type = checker.getTypeAtLocation(param);
3186
+ const formSpecExportName = detectFormSpecReference(typeNode);
3187
+ const optional = param.questionToken !== void 0 || param.initializer !== void 0;
3188
+ return { name, typeNode, type, formSpecExportName, optional };
3189
+ }
3190
+ function detectFormSpecReference(typeNode) {
3191
+ if (!typeNode) return null;
3192
+ if (!ts3.isTypeReferenceNode(typeNode)) return null;
3193
+ const typeName = ts3.isIdentifier(typeNode.typeName) ? typeNode.typeName.text : ts3.isQualifiedName(typeNode.typeName) ? typeNode.typeName.right.text : null;
3194
+ if (typeName !== "InferSchema" && typeName !== "InferFormSchema") return null;
3195
+ const typeArg = typeNode.typeArguments?.[0];
3196
+ if (!typeArg || !ts3.isTypeQueryNode(typeArg)) return null;
3197
+ if (ts3.isIdentifier(typeArg.exprName)) {
3198
+ return typeArg.exprName.text;
3199
+ }
3200
+ if (ts3.isQualifiedName(typeArg.exprName)) {
3201
+ return typeArg.exprName.right.text;
3202
+ }
3203
+ return null;
3204
+ }
3205
+ var ts3, RESOLVING_TYPE_PLACEHOLDER, MAX_ALIAS_CHAIN_DEPTH;
3206
+ var init_class_analyzer = __esm({
3207
+ "src/analyzer/class-analyzer.ts"() {
3208
+ "use strict";
3209
+ ts3 = __toESM(require("typescript"), 1);
3210
+ init_jsdoc_constraints();
3211
+ init_tsdoc_parser();
3212
+ RESOLVING_TYPE_PLACEHOLDER = {
3213
+ kind: "object",
3214
+ properties: [],
3215
+ additionalProperties: true
3216
+ };
3217
+ MAX_ALIAS_CHAIN_DEPTH = 8;
3218
+ }
3219
+ });
3220
+
3221
+ // src/analyzer/program.ts
3222
+ function createProgramContext(filePath) {
3223
+ const absolutePath = path.resolve(filePath);
3224
+ const fileDir = path.dirname(absolutePath);
3225
+ const configPath = ts4.findConfigFile(fileDir, ts4.sys.fileExists.bind(ts4.sys), "tsconfig.json");
3226
+ let compilerOptions;
3227
+ let fileNames;
3228
+ if (configPath) {
3229
+ const configFile = ts4.readConfigFile(configPath, ts4.sys.readFile.bind(ts4.sys));
3230
+ if (configFile.error) {
3231
+ throw new Error(
3232
+ `Error reading tsconfig.json: ${ts4.flattenDiagnosticMessageText(configFile.error.messageText, "\n")}`
3233
+ );
3234
+ }
3235
+ const parsed = ts4.parseJsonConfigFileContent(
3236
+ configFile.config,
3237
+ ts4.sys,
3238
+ path.dirname(configPath)
3239
+ );
3240
+ if (parsed.errors.length > 0) {
3241
+ const errorMessages = parsed.errors.map((e) => ts4.flattenDiagnosticMessageText(e.messageText, "\n")).join("\n");
3242
+ throw new Error(`Error parsing tsconfig.json: ${errorMessages}`);
3243
+ }
3244
+ compilerOptions = parsed.options;
3245
+ fileNames = parsed.fileNames.includes(absolutePath) ? parsed.fileNames : [...parsed.fileNames, absolutePath];
3246
+ } else {
3247
+ compilerOptions = {
3248
+ target: ts4.ScriptTarget.ES2022,
3249
+ module: ts4.ModuleKind.NodeNext,
3250
+ moduleResolution: ts4.ModuleResolutionKind.NodeNext,
3251
+ strict: true,
3252
+ skipLibCheck: true,
3253
+ declaration: true
3254
+ };
3255
+ fileNames = [absolutePath];
3256
+ }
3257
+ const program = ts4.createProgram(fileNames, compilerOptions);
3258
+ const sourceFile = program.getSourceFile(absolutePath);
3259
+ if (!sourceFile) {
3260
+ throw new Error(`Could not find source file: ${absolutePath}`);
3261
+ }
3262
+ return {
3263
+ program,
3264
+ checker: program.getTypeChecker(),
3265
+ sourceFile
3266
+ };
3267
+ }
3268
+ function findNodeByName(sourceFile, name, predicate, getName) {
3269
+ let result = null;
3270
+ function visit(node) {
3271
+ if (result) return;
3272
+ if (predicate(node) && getName(node) === name) {
3273
+ result = node;
3274
+ return;
3275
+ }
3276
+ ts4.forEachChild(node, visit);
3277
+ }
3278
+ visit(sourceFile);
3279
+ return result;
3280
+ }
3281
+ function findClassByName(sourceFile, className) {
3282
+ return findNodeByName(sourceFile, className, ts4.isClassDeclaration, (n) => n.name?.text);
3283
+ }
3284
+ function findInterfaceByName(sourceFile, interfaceName) {
3285
+ return findNodeByName(sourceFile, interfaceName, ts4.isInterfaceDeclaration, (n) => n.name.text);
3286
+ }
3287
+ function findTypeAliasByName(sourceFile, aliasName) {
3288
+ return findNodeByName(sourceFile, aliasName, ts4.isTypeAliasDeclaration, (n) => n.name.text);
3289
+ }
3290
+ function analyzeNamedTypeToIR(filePath, typeName, extensionRegistry) {
3291
+ const ctx = createProgramContext(filePath);
3292
+ const classDecl = findClassByName(ctx.sourceFile, typeName);
3293
+ if (classDecl !== null) {
3294
+ return analyzeClassToIR(classDecl, ctx.checker, filePath, extensionRegistry);
3295
+ }
3296
+ const interfaceDecl = findInterfaceByName(ctx.sourceFile, typeName);
3297
+ if (interfaceDecl !== null) {
3298
+ return analyzeInterfaceToIR(interfaceDecl, ctx.checker, filePath, extensionRegistry);
3299
+ }
3300
+ const typeAlias = findTypeAliasByName(ctx.sourceFile, typeName);
3301
+ if (typeAlias !== null) {
3302
+ const result = analyzeTypeAliasToIR(typeAlias, ctx.checker, filePath, extensionRegistry);
3303
+ if (result.ok) {
3304
+ return result.analysis;
3305
+ }
3306
+ throw new Error(result.error);
3307
+ }
3308
+ throw new Error(
3309
+ `Type "${typeName}" not found as a class, interface, or type alias in ${filePath}`
3310
+ );
3311
+ }
3312
+ var ts4, path;
3313
+ var init_program = __esm({
3314
+ "src/analyzer/program.ts"() {
3315
+ "use strict";
3316
+ ts4 = __toESM(require("typescript"), 1);
3317
+ path = __toESM(require("path"), 1);
3318
+ init_class_analyzer();
3319
+ }
3320
+ });
3321
+
3322
+ // src/validate/constraint-validator.ts
3323
+ function validateFieldNode(ctx, field) {
3324
+ const analysis = (0, import_internal2.analyzeConstraintTargets)(
3325
+ field.name,
3326
+ field.type,
3327
+ field.constraints,
3328
+ ctx.typeRegistry,
3329
+ ctx.extensionRegistry === void 0 ? void 0 : {
3330
+ extensionRegistry: ctx.extensionRegistry
3331
+ }
3332
+ );
3333
+ ctx.diagnostics.push(...analysis.diagnostics);
3334
+ if (field.type.kind === "object") {
3335
+ for (const property of field.type.properties) {
3336
+ validateObjectProperty(ctx, field.name, property);
3337
+ }
3338
+ }
3339
+ }
3340
+ function validateObjectProperty(ctx, parentName, property) {
3341
+ const qualifiedName = `${parentName}.${property.name}`;
3342
+ const analysis = (0, import_internal2.analyzeConstraintTargets)(
3343
+ qualifiedName,
3344
+ property.type,
3345
+ property.constraints,
3346
+ ctx.typeRegistry,
3347
+ ctx.extensionRegistry === void 0 ? void 0 : {
3348
+ extensionRegistry: ctx.extensionRegistry
3349
+ }
3350
+ );
3351
+ ctx.diagnostics.push(...analysis.diagnostics);
3352
+ if (property.type.kind === "object") {
3353
+ for (const nestedProperty of property.type.properties) {
3354
+ validateObjectProperty(ctx, qualifiedName, nestedProperty);
3355
+ }
3356
+ }
3357
+ }
3358
+ function validateElement(ctx, element) {
3359
+ switch (element.kind) {
3360
+ case "field":
3361
+ validateFieldNode(ctx, element);
3362
+ break;
3363
+ case "group":
3364
+ for (const child of element.elements) {
3365
+ validateElement(ctx, child);
3366
+ }
3367
+ break;
3368
+ case "conditional":
3369
+ for (const child of element.elements) {
3370
+ validateElement(ctx, child);
3371
+ }
3372
+ break;
3373
+ default: {
3374
+ const exhaustive = element;
3375
+ throw new Error(`Unhandled element kind: ${String(exhaustive)}`);
3376
+ }
3377
+ }
3378
+ }
3379
+ function validateIR(ir, options) {
3380
+ const ctx = {
3381
+ diagnostics: [],
3382
+ extensionRegistry: options?.extensionRegistry,
3383
+ typeRegistry: ir.typeRegistry
3384
+ };
3385
+ for (const element of ir.elements) {
3386
+ validateElement(ctx, element);
3387
+ }
3388
+ return {
3389
+ diagnostics: ctx.diagnostics,
3390
+ valid: ctx.diagnostics.every((diagnostic) => diagnostic.severity !== "error")
3391
+ };
3392
+ }
3393
+ var import_internal2;
3394
+ var init_constraint_validator = __esm({
3395
+ "src/validate/constraint-validator.ts"() {
3396
+ "use strict";
3397
+ import_internal2 = require("@formspec/analysis/internal");
3398
+ }
3399
+ });
3400
+
3401
+ // src/validate/index.ts
3402
+ var init_validate = __esm({
3403
+ "src/validate/index.ts"() {
3404
+ "use strict";
3405
+ init_constraint_validator();
3406
+ }
3407
+ });
3408
+
3409
+ // src/generators/class-schema.ts
3410
+ function generateClassSchemas(analysis, source, options) {
3411
+ const errorDiagnostics = analysis.diagnostics?.filter(
3412
+ (diagnostic) => diagnostic.severity === "error"
3413
+ );
3414
+ if (errorDiagnostics !== void 0 && errorDiagnostics.length > 0) {
3415
+ throw new Error(formatValidationError(errorDiagnostics));
3416
+ }
3417
+ const ir = canonicalizeTSDoc(analysis, source);
3418
+ const validationResult = validateIR(ir, {
3419
+ ...options?.extensionRegistry !== void 0 && {
3420
+ extensionRegistry: options.extensionRegistry
3421
+ },
3422
+ ...options?.vendorPrefix !== void 0 && { vendorPrefix: options.vendorPrefix }
3423
+ });
3424
+ if (!validationResult.valid) {
3425
+ throw new Error(formatValidationError(validationResult.diagnostics));
3426
+ }
3427
+ return {
3428
+ jsonSchema: generateJsonSchemaFromIR(ir, options),
3429
+ uiSchema: generateUiSchemaFromIR(ir)
3430
+ };
3431
+ }
3432
+ function formatValidationError(diagnostics) {
3433
+ const lines = diagnostics.map((diagnostic) => {
3434
+ const primary = formatLocation(diagnostic.primaryLocation);
3435
+ const related = diagnostic.relatedLocations.length > 0 ? ` [related: ${diagnostic.relatedLocations.map(formatLocation).join(", ")}]` : "";
3436
+ return `${diagnostic.code}: ${diagnostic.message} (${primary})${related}`;
3437
+ });
3438
+ return `FormSpec validation failed:
3439
+ ${lines.map((line) => `- ${line}`).join("\n")}`;
3440
+ }
3441
+ function formatLocation(location) {
3442
+ return `${location.file}:${String(location.line)}:${String(location.column)}`;
3443
+ }
3444
+ function generateSchemasFromClass(options) {
3445
+ const ctx = createProgramContext(options.filePath);
3446
+ const classDecl = findClassByName(ctx.sourceFile, options.className);
3447
+ if (!classDecl) {
3448
+ throw new Error(`Class "${options.className}" not found in ${options.filePath}`);
3449
+ }
3450
+ const analysis = analyzeClassToIR(
3451
+ classDecl,
3452
+ ctx.checker,
3453
+ options.filePath,
3454
+ options.extensionRegistry
3455
+ );
3456
+ return generateClassSchemas(
3457
+ analysis,
3458
+ { file: options.filePath },
3459
+ {
3460
+ extensionRegistry: options.extensionRegistry,
3461
+ vendorPrefix: options.vendorPrefix
3462
+ }
3463
+ );
3464
+ }
3465
+ function generateSchemas(options) {
3466
+ const analysis = analyzeNamedTypeToIR(
3467
+ options.filePath,
3468
+ options.typeName,
3469
+ options.extensionRegistry
3470
+ );
3471
+ return generateClassSchemas(analysis, { file: options.filePath }, options);
3472
+ }
3473
+ var init_class_schema = __esm({
3474
+ "src/generators/class-schema.ts"() {
3475
+ "use strict";
3476
+ init_program();
3477
+ init_class_analyzer();
3478
+ init_canonicalize();
3479
+ init_ir_generator();
3480
+ init_ir_generator2();
3481
+ init_validate();
3482
+ }
3483
+ });
3484
+
3485
+ // src/generators/mixed-authoring.ts
3486
+ function buildMixedAuthoringSchemas(options) {
3487
+ const { filePath, typeName, overlays, ...schemaOptions } = options;
3488
+ const analysis = analyzeNamedTypeToIR(filePath, typeName, schemaOptions.extensionRegistry);
3489
+ const composedAnalysis = composeAnalysisWithOverlays(analysis, overlays);
3490
+ const ir = canonicalizeTSDoc(composedAnalysis, { file: filePath });
3491
+ return {
3492
+ jsonSchema: generateJsonSchemaFromIR(ir, schemaOptions),
3493
+ uiSchema: generateUiSchemaFromIR(ir)
3494
+ };
3495
+ }
3496
+ function composeAnalysisWithOverlays(analysis, overlays) {
3497
+ const overlayIR = canonicalizeChainDSL(overlays);
3498
+ const overlayFields = collectOverlayFields(overlayIR.elements);
3499
+ if (overlayFields.length === 0) {
3500
+ return analysis;
3501
+ }
3502
+ const overlayByName = /* @__PURE__ */ new Map();
3503
+ for (const field of overlayFields) {
3504
+ if (overlayByName.has(field.name)) {
3505
+ throw new Error(`Mixed-authoring overlays define "${field.name}" more than once`);
3506
+ }
3507
+ overlayByName.set(field.name, field);
3508
+ }
3509
+ const mergedFields = [];
3510
+ for (const baseField of analysis.fields) {
3511
+ const overlayField = overlayByName.get(baseField.name);
3512
+ if (overlayField === void 0) {
3513
+ mergedFields.push(baseField);
3514
+ continue;
3515
+ }
3516
+ mergedFields.push(mergeFieldOverlay(baseField, overlayField, analysis.typeRegistry));
3517
+ overlayByName.delete(baseField.name);
3518
+ }
3519
+ if (overlayByName.size > 0) {
3520
+ const unknownFields = [...overlayByName.keys()].sort().join(", ");
3521
+ throw new Error(
3522
+ `Mixed-authoring overlays reference fields that are not present in the static model: ${unknownFields}`
3523
+ );
3524
+ }
3525
+ return {
3526
+ ...analysis,
3527
+ fields: mergedFields
3528
+ };
3529
+ }
3530
+ function collectOverlayFields(elements) {
3531
+ const fields = [];
3532
+ for (const element of elements) {
3533
+ switch (element.kind) {
3534
+ case "field":
3535
+ fields.push(element);
3536
+ break;
3537
+ case "group":
3538
+ fields.push(...collectOverlayFields(element.elements));
3539
+ break;
3540
+ case "conditional":
3541
+ fields.push(...collectOverlayFields(element.elements));
3542
+ break;
3543
+ default: {
3544
+ const _exhaustive = element;
3545
+ void _exhaustive;
3546
+ }
3547
+ }
3548
+ }
3549
+ return fields;
3550
+ }
3551
+ function mergeFieldOverlay(baseField, overlayField, typeRegistry) {
3552
+ assertSupportedOverlayField(baseField, overlayField);
3553
+ return {
3554
+ ...baseField,
3555
+ type: mergeFieldType(baseField, overlayField, typeRegistry),
3556
+ annotations: mergeAnnotations(baseField.annotations, overlayField.annotations)
3557
+ };
3558
+ }
3559
+ function assertSupportedOverlayField(baseField, overlayField) {
3560
+ if (overlayField.constraints.length > 0) {
3561
+ throw new Error(
3562
+ `Mixed-authoring overlay for "${baseField.name}" cannot define constraints; keep constraints on the static model`
3563
+ );
3564
+ }
3565
+ if (overlayField.required && !baseField.required) {
3566
+ throw new Error(
3567
+ `Mixed-authoring overlay for "${baseField.name}" cannot change requiredness; keep requiredness on the static model`
3568
+ );
3569
+ }
3570
+ }
3571
+ function mergeFieldType(baseField, overlayField, typeRegistry) {
3572
+ const { type: baseType } = baseField;
3573
+ const { type: overlayType } = overlayField;
3574
+ if (overlayType.kind === "object" || overlayType.kind === "array") {
3575
+ throw new Error(
3576
+ `Mixed-authoring overlays do not support nested object or array overlays for "${baseField.name}"`
3577
+ );
3578
+ }
3579
+ if (overlayType.kind === "dynamic") {
3580
+ if (!isCompatibleDynamicOverlay(baseField, overlayField, typeRegistry)) {
3581
+ throw new Error(
3582
+ `Mixed-authoring overlay for "${baseField.name}" is incompatible with the static field type`
3583
+ );
3584
+ }
3585
+ return overlayType;
3586
+ }
3587
+ if (!isSameStaticTypeShape(baseType, overlayType)) {
3588
+ throw new Error(
3589
+ `Mixed-authoring overlay for "${baseField.name}" must preserve the static field type`
3590
+ );
3591
+ }
3592
+ return baseType;
3593
+ }
3594
+ function isCompatibleDynamicOverlay(baseField, overlayField, typeRegistry) {
3595
+ const overlayType = overlayField.type;
3596
+ if (overlayType.kind !== "dynamic") {
3597
+ return false;
3598
+ }
3599
+ const resolvedBaseType = resolveReferenceType(baseField.type, typeRegistry);
3600
+ if (resolvedBaseType === null) {
3601
+ return false;
3602
+ }
3603
+ if (overlayType.dynamicKind === "enum") {
3604
+ return resolvedBaseType.kind === "primitive" ? resolvedBaseType.primitiveKind === "string" : resolvedBaseType.kind === "enum";
3605
+ }
3606
+ return resolvedBaseType.kind === "object" || resolvedBaseType.kind === "record";
3607
+ }
3608
+ function resolveReferenceType(type, typeRegistry, seen = /* @__PURE__ */ new Set()) {
3609
+ if (type.kind !== "reference") {
3610
+ return type;
3611
+ }
3612
+ if (seen.has(type.name)) {
3613
+ return null;
3614
+ }
3615
+ const definition = typeRegistry[type.name];
3616
+ if (definition === void 0) {
3617
+ return null;
3618
+ }
3619
+ seen.add(type.name);
3620
+ return resolveReferenceType(definition.type, typeRegistry, seen);
3621
+ }
3622
+ function isSameStaticTypeShape(baseType, overlayType) {
3623
+ if (baseType.kind !== overlayType.kind) {
3624
+ return false;
3625
+ }
3626
+ switch (baseType.kind) {
3627
+ case "primitive":
3628
+ return overlayType.kind === "primitive" && baseType.primitiveKind === overlayType.primitiveKind;
3629
+ case "enum":
3630
+ return overlayType.kind === "enum";
3631
+ case "dynamic":
3632
+ return overlayType.kind === "dynamic" && baseType.dynamicKind === overlayType.dynamicKind && baseType.sourceKey === overlayType.sourceKey;
3633
+ case "record":
3634
+ return overlayType.kind === "record";
3635
+ case "reference":
3636
+ return overlayType.kind === "reference" && baseType.name === overlayType.name;
3637
+ case "union":
3638
+ return overlayType.kind === "union";
3639
+ case "custom":
3640
+ return overlayType.kind === "custom" && baseType.typeId === overlayType.typeId;
3641
+ case "object":
3642
+ case "array":
3643
+ return true;
3644
+ default: {
3645
+ const _exhaustive = baseType;
3646
+ return _exhaustive;
3647
+ }
3648
+ }
3649
+ }
3650
+ function mergeAnnotations(baseAnnotations, overlayAnnotations) {
3651
+ const baseKeys = new Set(baseAnnotations.map(annotationKey));
3652
+ const overlayOnly = overlayAnnotations.filter(
3653
+ (annotation) => !baseKeys.has(annotationKey(annotation))
3654
+ );
3655
+ return [...baseAnnotations, ...overlayOnly];
3656
+ }
3657
+ function annotationKey(annotation) {
3658
+ return annotation.annotationKind === "custom" ? `${annotation.annotationKind}:${annotation.annotationId}` : annotation.annotationKind;
3659
+ }
3660
+ var init_mixed_authoring = __esm({
3661
+ "src/generators/mixed-authoring.ts"() {
3662
+ "use strict";
3663
+ init_ir_generator();
3664
+ init_ir_generator2();
3665
+ init_canonicalize();
3666
+ init_program();
3667
+ }
3668
+ });
3669
+
3670
+ // src/index.ts
3671
+ var index_exports = {};
3672
+ __export(index_exports, {
3673
+ buildFormSchemas: () => buildFormSchemas,
3674
+ buildMixedAuthoringSchemas: () => buildMixedAuthoringSchemas,
3675
+ categorizationSchema: () => categorizationSchema,
3676
+ categorySchema: () => categorySchema,
3677
+ controlSchema: () => controlSchema,
3678
+ createExtensionRegistry: () => createExtensionRegistry,
3679
+ generateJsonSchema: () => generateJsonSchema,
3680
+ generateJsonSchemaFromIR: () => generateJsonSchemaFromIR,
3681
+ generateSchemas: () => generateSchemas,
3682
+ generateSchemasFromClass: () => generateSchemasFromClass,
3683
+ generateUiSchema: () => generateUiSchema,
3684
+ getSchemaExtension: () => getSchemaExtension,
3685
+ groupLayoutSchema: () => groupLayoutSchema,
3686
+ horizontalLayoutSchema: () => horizontalLayoutSchema,
3687
+ jsonSchema7Schema: () => jsonSchema7Schema,
3688
+ jsonSchemaTypeSchema: () => jsonSchemaTypeSchema,
3689
+ labelElementSchema: () => labelElementSchema,
3690
+ ruleConditionSchema: () => ruleConditionSchema,
3691
+ ruleEffectSchema: () => ruleEffectSchema,
3692
+ ruleSchema: () => ruleSchema,
3693
+ schemaBasedConditionSchema: () => schemaBasedConditionSchema,
3694
+ setSchemaExtension: () => setSchemaExtension,
3695
+ uiSchemaElementSchema: () => uiSchemaElementSchema,
3696
+ uiSchemaElementTypeSchema: () => uiSchemaElementTypeSchema,
3697
+ uiSchemaSchema: () => uiSchema,
3698
+ verticalLayoutSchema: () => verticalLayoutSchema,
3699
+ writeSchemas: () => writeSchemas
3700
+ });
3701
+ function buildFormSchemas(form, options) {
3702
+ return {
3703
+ jsonSchema: generateJsonSchema(form, options),
3704
+ uiSchema: generateUiSchema(form)
3705
+ };
3706
+ }
3707
+ function writeSchemas(form, options) {
3708
+ const { outDir, name = "schema", indent = 2, extensionRegistry, vendorPrefix } = options;
3709
+ const buildOptions = extensionRegistry === void 0 && vendorPrefix === void 0 ? void 0 : {
3710
+ extensionRegistry,
3711
+ vendorPrefix
3712
+ };
3713
+ const { jsonSchema, uiSchema: uiSchema2 } = buildFormSchemas(form, buildOptions);
3714
+ if (!fs.existsSync(outDir)) {
3715
+ fs.mkdirSync(outDir, { recursive: true });
3716
+ }
3717
+ const jsonSchemaPath = path2.join(outDir, `${name}-schema.json`);
3718
+ const uiSchemaPath = path2.join(outDir, `${name}-uischema.json`);
3719
+ fs.writeFileSync(jsonSchemaPath, JSON.stringify(jsonSchema, null, indent));
3720
+ fs.writeFileSync(uiSchemaPath, JSON.stringify(uiSchema2, null, indent));
3721
+ return { jsonSchemaPath, uiSchemaPath };
3722
+ }
3723
+ var fs, path2;
3724
+ var init_index = __esm({
3725
+ "src/index.ts"() {
3726
+ "use strict";
3727
+ init_generator();
3728
+ init_generator2();
3729
+ init_ir_generator();
3730
+ fs = __toESM(require("fs"), 1);
3731
+ path2 = __toESM(require("path"), 1);
3732
+ init_types();
3733
+ init_extensions();
3734
+ init_schema();
3735
+ init_schema2();
3736
+ init_generator();
3737
+ init_ir_generator();
3738
+ init_generator2();
3739
+ init_class_schema();
3740
+ init_mixed_authoring();
3741
+ }
3742
+ });
3743
+
3744
+ // src/cli.ts
3745
+ var path3 = __toESM(require("path"), 1);
3746
+ var import_node_url = require("url");
3747
+ function printHelp() {
3748
+ console.log(`
3749
+ FormSpec Build CLI - Generate JSON Schema and UI Schema
3750
+
3751
+ Usage:
3752
+ formspec-build <input-file> [options]
3753
+
3754
+ Options:
3755
+ -o, --out-dir <dir> Output directory (default: ./generated)
3756
+ -n, --name <name> Base name for output files (default: derived from input)
3757
+ -h, --help Show this help message
3758
+
3759
+ Example:
3760
+ formspec-build src/forms/product.ts -o ./schemas -n product
3761
+
3762
+ The input file should export a FormSpec as its default export or as 'form':
3763
+ // product-form.ts
3764
+ import { formspec, field } from "formspec";
3765
+ export default formspec(field.text("name"));
3766
+ // or: export const form = formspec(field.text("name"));
3767
+ `);
3768
+ }
3769
+ function parseArgs(args) {
3770
+ const positional = [];
3771
+ let outDir = "./generated";
3772
+ let name = "";
3773
+ for (let i = 0; i < args.length; i++) {
3774
+ const arg = args[i];
3775
+ if (arg === void 0) continue;
3776
+ if (arg === "-h" || arg === "--help") {
3777
+ printHelp();
3778
+ process.exit(0);
3779
+ }
3780
+ if (arg === "-o" || arg === "--out-dir") {
3781
+ const nextArg = args[i + 1];
3782
+ if (!nextArg) {
3783
+ console.error("Error: --out-dir requires a value");
3784
+ return null;
3785
+ }
3786
+ outDir = nextArg;
3787
+ i++;
3788
+ continue;
3789
+ }
3790
+ if (arg === "-n" || arg === "--name") {
3791
+ const nextArg = args[i + 1];
3792
+ if (!nextArg) {
3793
+ console.error("Error: --name requires a value");
3794
+ return null;
3795
+ }
3796
+ name = nextArg;
3797
+ i++;
3798
+ continue;
3799
+ }
3800
+ if (arg.startsWith("-")) {
3801
+ console.error(`Error: Unknown option: ${arg}`);
3802
+ return null;
3803
+ }
3804
+ positional.push(arg);
3805
+ }
3806
+ if (positional.length === 0) {
3807
+ console.error("Error: No input file specified");
3808
+ printHelp();
3809
+ return null;
3810
+ }
3811
+ const inputFile = positional[0];
3812
+ if (!inputFile) {
3813
+ console.error("Error: No input file specified");
3814
+ return null;
3815
+ }
3816
+ if (!name) {
3817
+ name = path3.basename(inputFile, path3.extname(inputFile));
3818
+ }
3819
+ return { inputFile, outDir, name };
3820
+ }
3821
+ async function main() {
3822
+ const args = process.argv.slice(2);
3823
+ const options = parseArgs(args);
3824
+ if (!options) {
3825
+ process.exit(1);
3826
+ }
3827
+ const { inputFile, outDir, name } = options;
3828
+ const absoluteInput = path3.resolve(process.cwd(), inputFile);
3829
+ try {
3830
+ const fileUrl = (0, import_node_url.pathToFileURL)(absoluteInput).href;
3831
+ const module2 = await import(fileUrl);
3832
+ const form = module2["default"] ?? module2["form"];
3833
+ if (!form || typeof form !== "object" || !("elements" in form)) {
3834
+ console.error("Error: Input file must export a FormSpec as default export or as 'form'");
3835
+ console.error("Example:");
3836
+ console.error(' export default formspec(field.text("name"));');
3837
+ console.error(" // or");
3838
+ console.error(' export const form = formspec(field.text("name"));');
3839
+ process.exit(1);
3840
+ }
3841
+ const { writeSchemas: writeSchemas2 } = await Promise.resolve().then(() => (init_index(), index_exports));
3842
+ const { jsonSchemaPath, uiSchemaPath } = writeSchemas2(
3843
+ form,
3844
+ { outDir, name }
3845
+ );
3846
+ console.log("Generated:");
3847
+ console.log(` ${jsonSchemaPath}`);
3848
+ console.log(` ${uiSchemaPath}`);
3849
+ } catch (error) {
3850
+ if (error instanceof Error) {
3851
+ console.error(`Error: ${error.message}`);
3852
+ } else {
3853
+ console.error("Error:", error);
3854
+ }
3855
+ process.exit(1);
3856
+ }
3857
+ }
3858
+ void main();
3859
+ //# sourceMappingURL=cli.cjs.map