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