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

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