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