@formspec/build 0.1.0-alpha.10 → 0.1.0-alpha.12

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 (210) hide show
  1. package/README.md +51 -15
  2. package/dist/__tests__/chain-dsl-canonicalizer.test.d.ts +2 -0
  3. package/dist/__tests__/chain-dsl-canonicalizer.test.d.ts.map +1 -0
  4. package/dist/__tests__/constraint-validator.test.d.ts +2 -0
  5. package/dist/__tests__/constraint-validator.test.d.ts.map +1 -0
  6. package/dist/__tests__/extension-api.test.d.ts +2 -0
  7. package/dist/__tests__/extension-api.test.d.ts.map +1 -0
  8. package/dist/__tests__/fixtures/example-a-builtins.d.ts +18 -0
  9. package/dist/__tests__/fixtures/example-a-builtins.d.ts.map +1 -1
  10. package/dist/__tests__/ir-analyzer.test.d.ts +11 -0
  11. package/dist/__tests__/ir-analyzer.test.d.ts.map +1 -0
  12. package/dist/__tests__/ir-jsdoc-constraints.test.d.ts +12 -0
  13. package/dist/__tests__/ir-jsdoc-constraints.test.d.ts.map +1 -0
  14. package/dist/__tests__/ir-json-schema-generator.test.d.ts +11 -0
  15. package/dist/__tests__/ir-json-schema-generator.test.d.ts.map +1 -0
  16. package/dist/__tests__/ir-ui-schema-generator.test.d.ts +2 -0
  17. package/dist/__tests__/ir-ui-schema-generator.test.d.ts.map +1 -0
  18. package/dist/__tests__/jsdoc-constraints.test.d.ts +4 -4
  19. package/dist/__tests__/parity/fixtures/address/chain-dsl.d.ts +9 -0
  20. package/dist/__tests__/parity/fixtures/address/chain-dsl.d.ts.map +1 -0
  21. package/dist/__tests__/parity/fixtures/address/expected-ir.d.ts +9 -0
  22. package/dist/__tests__/parity/fixtures/address/expected-ir.d.ts.map +1 -0
  23. package/dist/__tests__/parity/fixtures/address/tsdoc.d.ts +19 -0
  24. package/dist/__tests__/parity/fixtures/address/tsdoc.d.ts.map +1 -0
  25. package/dist/__tests__/parity/fixtures/product-config/chain-dsl.d.ts +13 -0
  26. package/dist/__tests__/parity/fixtures/product-config/chain-dsl.d.ts.map +1 -0
  27. package/dist/__tests__/parity/fixtures/product-config/expected-ir.d.ts +9 -0
  28. package/dist/__tests__/parity/fixtures/product-config/expected-ir.d.ts.map +1 -0
  29. package/dist/__tests__/parity/fixtures/product-config/tsdoc.d.ts +28 -0
  30. package/dist/__tests__/parity/fixtures/product-config/tsdoc.d.ts.map +1 -0
  31. package/dist/__tests__/parity/fixtures/user-registration/chain-dsl.d.ts +12 -0
  32. package/dist/__tests__/parity/fixtures/user-registration/chain-dsl.d.ts.map +1 -0
  33. package/dist/__tests__/parity/fixtures/user-registration/expected-ir.d.ts +9 -0
  34. package/dist/__tests__/parity/fixtures/user-registration/expected-ir.d.ts.map +1 -0
  35. package/dist/__tests__/parity/fixtures/user-registration/tsdoc.d.ts +19 -0
  36. package/dist/__tests__/parity/fixtures/user-registration/tsdoc.d.ts.map +1 -0
  37. package/dist/__tests__/parity/parity.test.d.ts +14 -0
  38. package/dist/__tests__/parity/parity.test.d.ts.map +1 -0
  39. package/dist/__tests__/parity/utils.d.ts +139 -0
  40. package/dist/__tests__/parity/utils.d.ts.map +1 -0
  41. package/dist/analyzer/class-analyzer.d.ts +54 -99
  42. package/dist/analyzer/class-analyzer.d.ts.map +1 -1
  43. package/dist/analyzer/jsdoc-constraints.d.ts +78 -30
  44. package/dist/analyzer/jsdoc-constraints.d.ts.map +1 -1
  45. package/dist/analyzer/tsdoc-parser.d.ts +61 -0
  46. package/dist/analyzer/tsdoc-parser.d.ts.map +1 -0
  47. package/dist/browser.cjs +1200 -0
  48. package/dist/browser.cjs.map +1 -0
  49. package/dist/browser.d.ts +12 -6
  50. package/dist/browser.d.ts.map +1 -1
  51. package/dist/browser.js +1147 -44
  52. package/dist/browser.js.map +1 -1
  53. package/dist/build.d.ts +385 -160
  54. package/dist/canonicalize/chain-dsl-canonicalizer.d.ts +18 -0
  55. package/dist/canonicalize/chain-dsl-canonicalizer.d.ts.map +1 -0
  56. package/dist/canonicalize/index.d.ts +8 -0
  57. package/dist/canonicalize/index.d.ts.map +1 -0
  58. package/dist/canonicalize/tsdoc-canonicalizer.d.ts +34 -0
  59. package/dist/canonicalize/tsdoc-canonicalizer.d.ts.map +1 -0
  60. package/dist/cli.cjs +2028 -0
  61. package/dist/cli.cjs.map +1 -0
  62. package/dist/cli.js +1978 -101
  63. package/dist/cli.js.map +1 -1
  64. package/dist/extensions/index.d.ts +8 -0
  65. package/dist/extensions/index.d.ts.map +1 -0
  66. package/dist/extensions/registry.d.ts +55 -0
  67. package/dist/extensions/registry.d.ts.map +1 -0
  68. package/dist/generators/class-schema.d.ts +28 -47
  69. package/dist/generators/class-schema.d.ts.map +1 -1
  70. package/dist/generators/method-schema.d.ts +6 -8
  71. package/dist/generators/method-schema.d.ts.map +1 -1
  72. package/dist/index.cjs +1832 -0
  73. package/dist/index.cjs.map +1 -0
  74. package/dist/index.d.ts +8 -8
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +1779 -114
  77. package/dist/index.js.map +1 -1
  78. package/dist/internals.cjs +2125 -0
  79. package/dist/internals.cjs.map +1 -0
  80. package/dist/internals.d.ts +12 -2
  81. package/dist/internals.d.ts.map +1 -1
  82. package/dist/internals.js +2084 -21
  83. package/dist/internals.js.map +1 -1
  84. package/dist/json-schema/generator.d.ts +10 -5
  85. package/dist/json-schema/generator.d.ts.map +1 -1
  86. package/dist/json-schema/ir-generator.d.ts +84 -0
  87. package/dist/json-schema/ir-generator.d.ts.map +1 -0
  88. package/dist/json-schema/schema.d.ts +16 -0
  89. package/dist/json-schema/schema.d.ts.map +1 -0
  90. package/dist/json-schema/types.d.ts +5 -6
  91. package/dist/json-schema/types.d.ts.map +1 -1
  92. package/dist/ui-schema/generator.d.ts +5 -0
  93. package/dist/ui-schema/generator.d.ts.map +1 -1
  94. package/dist/ui-schema/ir-generator.d.ts +53 -0
  95. package/dist/ui-schema/ir-generator.d.ts.map +1 -0
  96. package/dist/ui-schema/schema.d.ts +357 -0
  97. package/dist/ui-schema/schema.d.ts.map +1 -0
  98. package/dist/ui-schema/types.d.ts +8 -73
  99. package/dist/ui-schema/types.d.ts.map +1 -1
  100. package/dist/validate/constraint-validator.d.ts +66 -0
  101. package/dist/validate/constraint-validator.d.ts.map +1 -0
  102. package/dist/validate/index.d.ts +9 -0
  103. package/dist/validate/index.d.ts.map +1 -0
  104. package/package.json +15 -9
  105. package/dist/__tests__/analyzer-edge-cases.test.d.ts +0 -13
  106. package/dist/__tests__/analyzer-edge-cases.test.d.ts.map +0 -1
  107. package/dist/__tests__/analyzer-edge-cases.test.js +0 -376
  108. package/dist/__tests__/analyzer-edge-cases.test.js.map +0 -1
  109. package/dist/__tests__/analyzer.test.d.ts +0 -5
  110. package/dist/__tests__/analyzer.test.d.ts.map +0 -1
  111. package/dist/__tests__/analyzer.test.js +0 -190
  112. package/dist/__tests__/analyzer.test.js.map +0 -1
  113. package/dist/__tests__/cli.test.js +0 -178
  114. package/dist/__tests__/cli.test.js.map +0 -1
  115. package/dist/__tests__/codegen.test.d.ts +0 -5
  116. package/dist/__tests__/codegen.test.d.ts.map +0 -1
  117. package/dist/__tests__/codegen.test.js +0 -506
  118. package/dist/__tests__/codegen.test.js.map +0 -1
  119. package/dist/__tests__/decorator-pipeline.test.d.ts +0 -11
  120. package/dist/__tests__/decorator-pipeline.test.d.ts.map +0 -1
  121. package/dist/__tests__/decorator-pipeline.test.js +0 -460
  122. package/dist/__tests__/decorator-pipeline.test.js.map +0 -1
  123. package/dist/__tests__/edge-cases.test.js +0 -215
  124. package/dist/__tests__/edge-cases.test.js.map +0 -1
  125. package/dist/__tests__/fixtures/edge-cases.js +0 -137
  126. package/dist/__tests__/fixtures/edge-cases.js.map +0 -1
  127. package/dist/__tests__/fixtures/example-a-builtins.js +0 -100
  128. package/dist/__tests__/fixtures/example-a-builtins.js.map +0 -1
  129. package/dist/__tests__/fixtures/example-b-decorators.d.ts +0 -5
  130. package/dist/__tests__/fixtures/example-b-decorators.d.ts.map +0 -1
  131. package/dist/__tests__/fixtures/example-b-decorators.js +0 -5
  132. package/dist/__tests__/fixtures/example-b-decorators.js.map +0 -1
  133. package/dist/__tests__/fixtures/example-b-extended.d.ts +0 -5
  134. package/dist/__tests__/fixtures/example-b-extended.d.ts.map +0 -1
  135. package/dist/__tests__/fixtures/example-b-extended.js +0 -60
  136. package/dist/__tests__/fixtures/example-b-extended.js.map +0 -1
  137. package/dist/__tests__/fixtures/example-c-custom.d.ts +0 -5
  138. package/dist/__tests__/fixtures/example-c-custom.d.ts.map +0 -1
  139. package/dist/__tests__/fixtures/example-c-custom.js +0 -61
  140. package/dist/__tests__/fixtures/example-c-custom.js.map +0 -1
  141. package/dist/__tests__/fixtures/example-c-decorators.d.ts +0 -5
  142. package/dist/__tests__/fixtures/example-c-decorators.d.ts.map +0 -1
  143. package/dist/__tests__/fixtures/example-c-decorators.js +0 -4
  144. package/dist/__tests__/fixtures/example-c-decorators.js.map +0 -1
  145. package/dist/__tests__/fixtures/example-d-mixed-decorators.d.ts +0 -6
  146. package/dist/__tests__/fixtures/example-d-mixed-decorators.d.ts.map +0 -1
  147. package/dist/__tests__/fixtures/example-d-mixed-decorators.js +0 -75
  148. package/dist/__tests__/fixtures/example-d-mixed-decorators.js.map +0 -1
  149. package/dist/__tests__/fixtures/example-e-decorators.d.ts +0 -11
  150. package/dist/__tests__/fixtures/example-e-decorators.d.ts.map +0 -1
  151. package/dist/__tests__/fixtures/example-e-decorators.js +0 -10
  152. package/dist/__tests__/fixtures/example-e-decorators.js.map +0 -1
  153. package/dist/__tests__/fixtures/example-e-no-namespace.d.ts +0 -5
  154. package/dist/__tests__/fixtures/example-e-no-namespace.d.ts.map +0 -1
  155. package/dist/__tests__/fixtures/example-e-no-namespace.js +0 -61
  156. package/dist/__tests__/fixtures/example-e-no-namespace.js.map +0 -1
  157. package/dist/__tests__/fixtures/example-interface-types.js +0 -8
  158. package/dist/__tests__/fixtures/example-interface-types.js.map +0 -1
  159. package/dist/__tests__/fixtures/example-jsdoc-constraints.d.ts +0 -16
  160. package/dist/__tests__/fixtures/example-jsdoc-constraints.d.ts.map +0 -1
  161. package/dist/__tests__/fixtures/example-jsdoc-constraints.js +0 -98
  162. package/dist/__tests__/fixtures/example-jsdoc-constraints.js.map +0 -1
  163. package/dist/__tests__/fixtures/example-nested-class.d.ts +0 -45
  164. package/dist/__tests__/fixtures/example-nested-class.d.ts.map +0 -1
  165. package/dist/__tests__/fixtures/example-nested-class.js +0 -248
  166. package/dist/__tests__/fixtures/example-nested-class.js.map +0 -1
  167. package/dist/__tests__/fixtures/sample-forms.js +0 -78
  168. package/dist/__tests__/fixtures/sample-forms.js.map +0 -1
  169. package/dist/__tests__/generator.test.js +0 -234
  170. package/dist/__tests__/generator.test.js.map +0 -1
  171. package/dist/__tests__/integration.test.js +0 -161
  172. package/dist/__tests__/integration.test.js.map +0 -1
  173. package/dist/__tests__/interface-types.test.d.ts +0 -11
  174. package/dist/__tests__/interface-types.test.d.ts.map +0 -1
  175. package/dist/__tests__/interface-types.test.js +0 -404
  176. package/dist/__tests__/interface-types.test.js.map +0 -1
  177. package/dist/__tests__/jsdoc-constraints.test.js +0 -465
  178. package/dist/__tests__/jsdoc-constraints.test.js.map +0 -1
  179. package/dist/__tests__/write-schemas.test.js +0 -198
  180. package/dist/__tests__/write-schemas.test.js.map +0 -1
  181. package/dist/analyzer/class-analyzer.js +0 -377
  182. package/dist/analyzer/class-analyzer.js.map +0 -1
  183. package/dist/analyzer/decorator-extractor.d.ts +0 -78
  184. package/dist/analyzer/decorator-extractor.d.ts.map +0 -1
  185. package/dist/analyzer/decorator-extractor.js +0 -336
  186. package/dist/analyzer/decorator-extractor.js.map +0 -1
  187. package/dist/analyzer/jsdoc-constraints.js +0 -153
  188. package/dist/analyzer/jsdoc-constraints.js.map +0 -1
  189. package/dist/analyzer/program.js +0 -114
  190. package/dist/analyzer/program.js.map +0 -1
  191. package/dist/analyzer/type-converter.d.ts +0 -75
  192. package/dist/analyzer/type-converter.d.ts.map +0 -1
  193. package/dist/analyzer/type-converter.js +0 -474
  194. package/dist/analyzer/type-converter.js.map +0 -1
  195. package/dist/codegen/index.d.ts +0 -75
  196. package/dist/codegen/index.d.ts.map +0 -1
  197. package/dist/codegen/index.js +0 -597
  198. package/dist/codegen/index.js.map +0 -1
  199. package/dist/generators/class-schema.js +0 -140
  200. package/dist/generators/class-schema.js.map +0 -1
  201. package/dist/generators/method-schema.js +0 -108
  202. package/dist/generators/method-schema.js.map +0 -1
  203. package/dist/json-schema/generator.js +0 -166
  204. package/dist/json-schema/generator.js.map +0 -1
  205. package/dist/json-schema/types.js +0 -33
  206. package/dist/json-schema/types.js.map +0 -1
  207. package/dist/ui-schema/generator.js +0 -148
  208. package/dist/ui-schema/generator.js.map +0 -1
  209. package/dist/ui-schema/types.js +0 -8
  210. package/dist/ui-schema/types.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,119 +1,1784 @@
1
- /**
2
- * `@formspec/build` - Build tools for FormSpec
3
- *
4
- * This package provides generators to compile FormSpec forms into:
5
- * - JSON Schema (for validation)
6
- * - JSON Forms UI Schema (for rendering)
7
- *
8
- * @example
9
- * ```typescript
10
- * import { buildFormSchemas } from "@formspec/build";
11
- * import { formspec, field, group } from "@formspec/dsl";
12
- *
13
- * const form = formspec(
14
- * group("Customer",
15
- * field.text("name", { label: "Name", required: true }),
16
- * field.text("email", { label: "Email" }),
17
- * ),
18
- * );
19
- *
20
- * const { jsonSchema, uiSchema } = buildFormSchemas(form);
21
- * ```
22
- *
23
- * @packageDocumentation
24
- */
25
- import { generateJsonSchema } from "./json-schema/generator.js";
26
- import { generateUiSchema } from "./ui-schema/generator.js";
27
- import * as fs from "node:fs";
28
- import * as path from "node:path";
29
- export { setSchemaExtension, getSchemaExtension } from "./json-schema/types.js";
30
- // =============================================================================
31
- // Chain DSL Generators
32
- // =============================================================================
33
- export { generateJsonSchema } from "./json-schema/generator.js";
34
- export { generateUiSchema } from "./ui-schema/generator.js";
35
- // =============================================================================
36
- // Decorator DSL: High-Level Entry Points
37
- // =============================================================================
38
- export { generateSchemasFromClass, generateSchemas } from "./generators/class-schema.js";
39
- // generateSchemas is the recommended entry point — it auto-detects class/interface/type alias.
40
- // generateSchemasFromClass is retained for backwards compatibility.
41
- export { findDecoratedClasses, generateCodegenOutput, runCodegen } from "./codegen/index.js";
42
- /**
43
- * Builds both JSON Schema and UI Schema from a FormSpec.
44
- *
45
- * This is a convenience function that combines `generateJsonSchema`
46
- * and `generateUiSchema`.
47
- *
48
- * @example
49
- * ```typescript
50
- * const form = formspec(
51
- * field.text("name", { required: true }),
52
- * field.number("age", { min: 0 }),
53
- * );
54
- *
55
- * const { jsonSchema, uiSchema } = buildFormSchemas(form);
56
- *
57
- * // Use with JSON Forms renderer
58
- * <JsonForms
59
- * schema={jsonSchema}
60
- * uischema={uiSchema}
61
- * data={formData}
62
- * renderers={materialRenderers}
63
- * />
64
- * ```
65
- *
66
- * @param form - The FormSpec to build schemas from
67
- * @returns Object containing both jsonSchema and uiSchema
68
- */
69
- export function buildFormSchemas(form) {
1
+ // src/canonicalize/chain-dsl-canonicalizer.ts
2
+ import { IR_VERSION } from "@formspec/core";
3
+ var CHAIN_DSL_PROVENANCE = {
4
+ surface: "chain-dsl",
5
+ file: "",
6
+ line: 0,
7
+ column: 0
8
+ };
9
+ function isGroup(el) {
10
+ return el._type === "group";
11
+ }
12
+ function isConditional(el) {
13
+ return el._type === "conditional";
14
+ }
15
+ function isField(el) {
16
+ return el._type === "field";
17
+ }
18
+ function canonicalizeChainDSL(form) {
19
+ return {
20
+ kind: "form-ir",
21
+ irVersion: IR_VERSION,
22
+ elements: canonicalizeElements(form.elements),
23
+ typeRegistry: {},
24
+ provenance: CHAIN_DSL_PROVENANCE
25
+ };
26
+ }
27
+ function canonicalizeElements(elements) {
28
+ return elements.map(canonicalizeElement);
29
+ }
30
+ function canonicalizeElement(element) {
31
+ if (isField(element)) {
32
+ return canonicalizeField(element);
33
+ }
34
+ if (isGroup(element)) {
35
+ return canonicalizeGroup(element);
36
+ }
37
+ if (isConditional(element)) {
38
+ return canonicalizeConditional(element);
39
+ }
40
+ const _exhaustive = element;
41
+ throw new Error(`Unknown element type: ${JSON.stringify(_exhaustive)}`);
42
+ }
43
+ function canonicalizeField(field) {
44
+ switch (field._field) {
45
+ case "text":
46
+ return canonicalizeTextField(field);
47
+ case "number":
48
+ return canonicalizeNumberField(field);
49
+ case "boolean":
50
+ return canonicalizeBooleanField(field);
51
+ case "enum":
52
+ return canonicalizeStaticEnumField(field);
53
+ case "dynamic_enum":
54
+ return canonicalizeDynamicEnumField(field);
55
+ case "dynamic_schema":
56
+ return canonicalizeDynamicSchemaField(field);
57
+ case "array":
58
+ return canonicalizeArrayField(field);
59
+ case "object":
60
+ return canonicalizeObjectField(field);
61
+ default: {
62
+ const _exhaustive = field;
63
+ throw new Error(`Unknown field type: ${JSON.stringify(_exhaustive)}`);
64
+ }
65
+ }
66
+ }
67
+ function canonicalizeTextField(field) {
68
+ const type = { kind: "primitive", primitiveKind: "string" };
69
+ return buildFieldNode(
70
+ field.name,
71
+ type,
72
+ field.required,
73
+ buildAnnotations(field.label, field.placeholder)
74
+ );
75
+ }
76
+ function canonicalizeNumberField(field) {
77
+ const type = { kind: "primitive", primitiveKind: "number" };
78
+ const constraints = [];
79
+ if (field.min !== void 0) {
80
+ const c = {
81
+ kind: "constraint",
82
+ constraintKind: "minimum",
83
+ value: field.min,
84
+ provenance: CHAIN_DSL_PROVENANCE
85
+ };
86
+ constraints.push(c);
87
+ }
88
+ if (field.max !== void 0) {
89
+ const c = {
90
+ kind: "constraint",
91
+ constraintKind: "maximum",
92
+ value: field.max,
93
+ provenance: CHAIN_DSL_PROVENANCE
94
+ };
95
+ constraints.push(c);
96
+ }
97
+ return buildFieldNode(
98
+ field.name,
99
+ type,
100
+ field.required,
101
+ buildAnnotations(field.label),
102
+ constraints
103
+ );
104
+ }
105
+ function canonicalizeBooleanField(field) {
106
+ const type = { kind: "primitive", primitiveKind: "boolean" };
107
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
108
+ }
109
+ function canonicalizeStaticEnumField(field) {
110
+ const members = field.options.map((opt) => {
111
+ if (typeof opt === "string") {
112
+ return { value: opt };
113
+ }
114
+ return { value: opt.id, displayName: opt.label };
115
+ });
116
+ const type = { kind: "enum", members };
117
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
118
+ }
119
+ function canonicalizeDynamicEnumField(field) {
120
+ const type = {
121
+ kind: "dynamic",
122
+ dynamicKind: "enum",
123
+ sourceKey: field.source,
124
+ parameterFields: field.params ? [...field.params] : []
125
+ };
126
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
127
+ }
128
+ function canonicalizeDynamicSchemaField(field) {
129
+ const type = {
130
+ kind: "dynamic",
131
+ dynamicKind: "schema",
132
+ sourceKey: field.schemaSource,
133
+ parameterFields: []
134
+ };
135
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
136
+ }
137
+ function canonicalizeArrayField(field) {
138
+ const itemProperties = buildObjectProperties(field.items);
139
+ const itemsType = {
140
+ kind: "object",
141
+ properties: itemProperties,
142
+ additionalProperties: false
143
+ };
144
+ const type = { kind: "array", items: itemsType };
145
+ const constraints = [];
146
+ if (field.minItems !== void 0) {
147
+ const c = {
148
+ kind: "constraint",
149
+ constraintKind: "minItems",
150
+ value: field.minItems,
151
+ provenance: CHAIN_DSL_PROVENANCE
152
+ };
153
+ constraints.push(c);
154
+ }
155
+ if (field.maxItems !== void 0) {
156
+ const c = {
157
+ kind: "constraint",
158
+ constraintKind: "maxItems",
159
+ value: field.maxItems,
160
+ provenance: CHAIN_DSL_PROVENANCE
161
+ };
162
+ constraints.push(c);
163
+ }
164
+ return buildFieldNode(
165
+ field.name,
166
+ type,
167
+ field.required,
168
+ buildAnnotations(field.label),
169
+ constraints
170
+ );
171
+ }
172
+ function canonicalizeObjectField(field) {
173
+ const properties = buildObjectProperties(field.properties);
174
+ const type = {
175
+ kind: "object",
176
+ properties,
177
+ additionalProperties: false
178
+ };
179
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
180
+ }
181
+ function canonicalizeGroup(g) {
182
+ return {
183
+ kind: "group",
184
+ label: g.label,
185
+ elements: canonicalizeElements(g.elements),
186
+ provenance: CHAIN_DSL_PROVENANCE
187
+ };
188
+ }
189
+ function canonicalizeConditional(c) {
190
+ return {
191
+ kind: "conditional",
192
+ fieldName: c.field,
193
+ // Conditional values from the chain DSL are JSON-serializable primitives
194
+ // (strings, numbers, booleans) produced by the `is()` predicate helper.
195
+ value: assertJsonValue(c.value),
196
+ elements: canonicalizeElements(c.elements),
197
+ provenance: CHAIN_DSL_PROVENANCE
198
+ };
199
+ }
200
+ function assertJsonValue(v) {
201
+ if (v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
202
+ return v;
203
+ }
204
+ if (Array.isArray(v)) {
205
+ return v.map(assertJsonValue);
206
+ }
207
+ if (typeof v === "object") {
208
+ const result = {};
209
+ for (const [key, val] of Object.entries(v)) {
210
+ result[key] = assertJsonValue(val);
211
+ }
212
+ return result;
213
+ }
214
+ throw new TypeError(`Conditional value is not a valid JsonValue: ${typeof v}`);
215
+ }
216
+ function buildFieldNode(name, type, required, annotations, constraints = []) {
217
+ return {
218
+ kind: "field",
219
+ name,
220
+ type,
221
+ required: required === true,
222
+ constraints,
223
+ annotations,
224
+ provenance: CHAIN_DSL_PROVENANCE
225
+ };
226
+ }
227
+ function buildAnnotations(label, placeholder) {
228
+ const annotations = [];
229
+ if (label !== void 0) {
230
+ const a = {
231
+ kind: "annotation",
232
+ annotationKind: "displayName",
233
+ value: label,
234
+ provenance: CHAIN_DSL_PROVENANCE
235
+ };
236
+ annotations.push(a);
237
+ }
238
+ if (placeholder !== void 0) {
239
+ const a = {
240
+ kind: "annotation",
241
+ annotationKind: "placeholder",
242
+ value: placeholder,
243
+ provenance: CHAIN_DSL_PROVENANCE
244
+ };
245
+ annotations.push(a);
246
+ }
247
+ return annotations;
248
+ }
249
+ function buildObjectProperties(elements, insideConditional = false) {
250
+ const properties = [];
251
+ for (const el of elements) {
252
+ if (isField(el)) {
253
+ const fieldNode = canonicalizeField(el);
254
+ properties.push({
255
+ name: fieldNode.name,
256
+ type: fieldNode.type,
257
+ // Fields inside a conditional branch are always optional in the
258
+ // data schema, regardless of their `required` flag — the condition
259
+ // may not be met, so the field may be absent.
260
+ optional: insideConditional || !fieldNode.required,
261
+ constraints: fieldNode.constraints,
262
+ annotations: fieldNode.annotations,
263
+ provenance: CHAIN_DSL_PROVENANCE
264
+ });
265
+ } else if (isGroup(el)) {
266
+ properties.push(...buildObjectProperties(el.elements, insideConditional));
267
+ } else if (isConditional(el)) {
268
+ properties.push(...buildObjectProperties(el.elements, true));
269
+ }
270
+ }
271
+ return properties;
272
+ }
273
+
274
+ // src/canonicalize/tsdoc-canonicalizer.ts
275
+ import { IR_VERSION as IR_VERSION2 } from "@formspec/core";
276
+ function canonicalizeTSDoc(analysis, source) {
277
+ const file = source?.file ?? "";
278
+ const provenance = {
279
+ surface: "tsdoc",
280
+ file,
281
+ line: 1,
282
+ column: 0
283
+ };
284
+ const elements = assembleElements(analysis.fields, analysis.fieldLayouts, provenance);
285
+ return {
286
+ kind: "form-ir",
287
+ irVersion: IR_VERSION2,
288
+ elements,
289
+ typeRegistry: analysis.typeRegistry,
290
+ provenance
291
+ };
292
+ }
293
+ function assembleElements(fields, layouts, provenance) {
294
+ const elements = [];
295
+ const groupMap = /* @__PURE__ */ new Map();
296
+ const topLevelOrder = [];
297
+ for (let i = 0; i < fields.length; i++) {
298
+ const field = fields[i];
299
+ const layout = layouts[i];
300
+ if (!field || !layout) continue;
301
+ const element = wrapInConditional(field, layout, provenance);
302
+ if (layout.groupLabel !== void 0) {
303
+ const label = layout.groupLabel;
304
+ let groupElements = groupMap.get(label);
305
+ if (!groupElements) {
306
+ groupElements = [];
307
+ groupMap.set(label, groupElements);
308
+ topLevelOrder.push({ type: "group", label });
309
+ }
310
+ groupElements.push(element);
311
+ } else {
312
+ topLevelOrder.push({ type: "element", element });
313
+ }
314
+ }
315
+ for (const entry of topLevelOrder) {
316
+ if (entry.type === "group") {
317
+ const groupElements = groupMap.get(entry.label);
318
+ if (groupElements) {
319
+ const groupNode = {
320
+ kind: "group",
321
+ label: entry.label,
322
+ elements: groupElements,
323
+ provenance
324
+ };
325
+ elements.push(groupNode);
326
+ groupMap.delete(entry.label);
327
+ }
328
+ } else {
329
+ elements.push(entry.element);
330
+ }
331
+ }
332
+ return elements;
333
+ }
334
+ function wrapInConditional(field, layout, provenance) {
335
+ if (layout.showWhen === void 0) {
336
+ return field;
337
+ }
338
+ const conditional = {
339
+ kind: "conditional",
340
+ fieldName: layout.showWhen.field,
341
+ value: layout.showWhen.value,
342
+ elements: [field],
343
+ provenance
344
+ };
345
+ return conditional;
346
+ }
347
+
348
+ // src/json-schema/ir-generator.ts
349
+ function makeContext() {
350
+ return { defs: {} };
351
+ }
352
+ function generateJsonSchemaFromIR(ir) {
353
+ const ctx = makeContext();
354
+ for (const [name, typeDef] of Object.entries(ir.typeRegistry)) {
355
+ ctx.defs[name] = generateTypeNode(typeDef.type, ctx);
356
+ }
357
+ const properties = {};
358
+ const required = [];
359
+ collectFields(ir.elements, properties, required, ctx);
360
+ const uniqueRequired = [...new Set(required)];
361
+ const result = {
362
+ $schema: "https://json-schema.org/draft/2020-12/schema",
363
+ type: "object",
364
+ properties,
365
+ ...uniqueRequired.length > 0 && { required: uniqueRequired }
366
+ };
367
+ if (Object.keys(ctx.defs).length > 0) {
368
+ result.$defs = ctx.defs;
369
+ }
370
+ return result;
371
+ }
372
+ function collectFields(elements, properties, required, ctx) {
373
+ for (const element of elements) {
374
+ switch (element.kind) {
375
+ case "field":
376
+ properties[element.name] = generateFieldSchema(element, ctx);
377
+ if (element.required) {
378
+ required.push(element.name);
379
+ }
380
+ break;
381
+ case "group":
382
+ collectFields(element.elements, properties, required, ctx);
383
+ break;
384
+ case "conditional":
385
+ collectFields(element.elements, properties, required, ctx);
386
+ break;
387
+ default: {
388
+ const _exhaustive = element;
389
+ void _exhaustive;
390
+ }
391
+ }
392
+ }
393
+ }
394
+ function generateFieldSchema(field, ctx) {
395
+ const schema = generateTypeNode(field.type, ctx);
396
+ applyConstraints(schema, field.constraints);
397
+ applyAnnotations(schema, field.annotations);
398
+ return schema;
399
+ }
400
+ function generateTypeNode(type, ctx) {
401
+ switch (type.kind) {
402
+ case "primitive":
403
+ return generatePrimitiveType(type);
404
+ case "enum":
405
+ return generateEnumType(type);
406
+ case "array":
407
+ return generateArrayType(type, ctx);
408
+ case "object":
409
+ return generateObjectType(type, ctx);
410
+ case "union":
411
+ return generateUnionType(type, ctx);
412
+ case "reference":
413
+ return generateReferenceType(type);
414
+ case "dynamic":
415
+ return generateDynamicType(type);
416
+ case "custom":
417
+ return generateCustomType(type);
418
+ default: {
419
+ const _exhaustive = type;
420
+ return _exhaustive;
421
+ }
422
+ }
423
+ }
424
+ function generatePrimitiveType(type) {
425
+ return { type: type.primitiveKind };
426
+ }
427
+ function generateEnumType(type) {
428
+ const hasDisplayNames = type.members.some((m) => m.displayName !== void 0);
429
+ if (hasDisplayNames) {
70
430
  return {
71
- jsonSchema: generateJsonSchema(form),
72
- uiSchema: generateUiSchema(form),
431
+ oneOf: type.members.map((m) => {
432
+ const entry = { const: m.value };
433
+ if (m.displayName !== void 0) {
434
+ entry.title = m.displayName;
435
+ }
436
+ return entry;
437
+ })
438
+ };
439
+ }
440
+ return { enum: type.members.map((m) => m.value) };
441
+ }
442
+ function generateArrayType(type, ctx) {
443
+ return {
444
+ type: "array",
445
+ items: generateTypeNode(type.items, ctx)
446
+ };
447
+ }
448
+ function generateObjectType(type, ctx) {
449
+ const properties = {};
450
+ const required = [];
451
+ for (const prop of type.properties) {
452
+ properties[prop.name] = generatePropertySchema(prop, ctx);
453
+ if (!prop.optional) {
454
+ required.push(prop.name);
455
+ }
456
+ }
457
+ const schema = { type: "object", properties };
458
+ if (required.length > 0) {
459
+ schema.required = required;
460
+ }
461
+ if (!type.additionalProperties) {
462
+ schema.additionalProperties = false;
463
+ }
464
+ return schema;
465
+ }
466
+ function generatePropertySchema(prop, ctx) {
467
+ const schema = generateTypeNode(prop.type, ctx);
468
+ applyConstraints(schema, prop.constraints);
469
+ applyAnnotations(schema, prop.annotations);
470
+ return schema;
471
+ }
472
+ function generateUnionType(type, ctx) {
473
+ if (isBooleanUnion(type)) {
474
+ return { type: "boolean" };
475
+ }
476
+ return {
477
+ anyOf: type.members.map((m) => generateTypeNode(m, ctx))
478
+ };
479
+ }
480
+ function isBooleanUnion(type) {
481
+ if (type.members.length !== 2) return false;
482
+ const kinds = type.members.map((m) => m.kind);
483
+ return kinds.every((k) => k === "primitive") && type.members.every((m) => m.kind === "primitive" && m.primitiveKind === "boolean");
484
+ }
485
+ function generateReferenceType(type) {
486
+ return { $ref: `#/$defs/${type.name}` };
487
+ }
488
+ function generateDynamicType(type) {
489
+ if (type.dynamicKind === "enum") {
490
+ const schema = {
491
+ type: "string",
492
+ "x-formspec-source": type.sourceKey
493
+ };
494
+ if (type.parameterFields.length > 0) {
495
+ schema["x-formspec-params"] = [...type.parameterFields];
496
+ }
497
+ return schema;
498
+ }
499
+ return {
500
+ type: "object",
501
+ additionalProperties: true,
502
+ "x-formspec-schemaSource": type.sourceKey
503
+ };
504
+ }
505
+ function generateCustomType(_type) {
506
+ return { type: "object" };
507
+ }
508
+ function applyConstraints(schema, constraints) {
509
+ for (const constraint of constraints) {
510
+ switch (constraint.constraintKind) {
511
+ case "minimum":
512
+ schema.minimum = constraint.value;
513
+ break;
514
+ case "maximum":
515
+ schema.maximum = constraint.value;
516
+ break;
517
+ case "exclusiveMinimum":
518
+ schema.exclusiveMinimum = constraint.value;
519
+ break;
520
+ case "exclusiveMaximum":
521
+ schema.exclusiveMaximum = constraint.value;
522
+ break;
523
+ case "multipleOf": {
524
+ const { value } = constraint;
525
+ if (value === 1 && schema.type === "number") {
526
+ schema.type = "integer";
527
+ } else {
528
+ schema.multipleOf = value;
529
+ }
530
+ break;
531
+ }
532
+ case "minLength":
533
+ schema.minLength = constraint.value;
534
+ break;
535
+ case "maxLength":
536
+ schema.maxLength = constraint.value;
537
+ break;
538
+ case "minItems":
539
+ schema.minItems = constraint.value;
540
+ break;
541
+ case "maxItems":
542
+ schema.maxItems = constraint.value;
543
+ break;
544
+ case "pattern":
545
+ schema.pattern = constraint.pattern;
546
+ break;
547
+ case "uniqueItems":
548
+ schema.uniqueItems = constraint.value;
549
+ break;
550
+ case "allowedMembers":
551
+ break;
552
+ case "custom":
553
+ break;
554
+ default: {
555
+ const _exhaustive = constraint;
556
+ void _exhaustive;
557
+ }
558
+ }
559
+ }
560
+ }
561
+ function applyAnnotations(schema, annotations) {
562
+ for (const annotation of annotations) {
563
+ switch (annotation.annotationKind) {
564
+ case "displayName":
565
+ schema.title = annotation.value;
566
+ break;
567
+ case "description":
568
+ schema.description = annotation.value;
569
+ break;
570
+ case "defaultValue":
571
+ schema.default = annotation.value;
572
+ break;
573
+ case "deprecated":
574
+ schema.deprecated = true;
575
+ break;
576
+ case "placeholder":
577
+ break;
578
+ case "formatHint":
579
+ break;
580
+ case "custom":
581
+ break;
582
+ default: {
583
+ const _exhaustive = annotation;
584
+ void _exhaustive;
585
+ }
586
+ }
587
+ }
588
+ }
589
+
590
+ // src/json-schema/generator.ts
591
+ function generateJsonSchema(form) {
592
+ const ir = canonicalizeChainDSL(form);
593
+ return generateJsonSchemaFromIR(ir);
594
+ }
595
+
596
+ // src/ui-schema/schema.ts
597
+ import { z } from "zod";
598
+ var jsonPointerSchema = z.string();
599
+ var ruleEffectSchema = z.enum(["SHOW", "HIDE", "ENABLE", "DISABLE"]);
600
+ var uiSchemaElementTypeSchema = z.enum([
601
+ "Control",
602
+ "VerticalLayout",
603
+ "HorizontalLayout",
604
+ "Group",
605
+ "Categorization",
606
+ "Category",
607
+ "Label"
608
+ ]);
609
+ var ruleConditionSchema = z.lazy(
610
+ () => z.object({
611
+ const: z.unknown().optional(),
612
+ enum: z.array(z.unknown()).readonly().optional(),
613
+ type: z.string().optional(),
614
+ not: ruleConditionSchema.optional(),
615
+ minimum: z.number().optional(),
616
+ maximum: z.number().optional(),
617
+ exclusiveMinimum: z.number().optional(),
618
+ exclusiveMaximum: z.number().optional(),
619
+ minLength: z.number().optional(),
620
+ properties: z.record(z.string(), ruleConditionSchema).optional(),
621
+ required: z.array(z.string()).optional(),
622
+ allOf: z.array(ruleConditionSchema).optional()
623
+ }).strict()
624
+ );
625
+ var schemaBasedConditionSchema = z.object({
626
+ scope: jsonPointerSchema,
627
+ schema: ruleConditionSchema
628
+ }).strict();
629
+ var ruleSchema = z.object({
630
+ effect: ruleEffectSchema,
631
+ condition: schemaBasedConditionSchema
632
+ }).strict();
633
+ var uiSchemaElementSchema = z.lazy(
634
+ () => z.union([
635
+ controlSchema,
636
+ verticalLayoutSchema,
637
+ horizontalLayoutSchema,
638
+ groupLayoutSchema,
639
+ categorizationSchema,
640
+ categorySchema,
641
+ labelElementSchema
642
+ ])
643
+ );
644
+ var controlSchema = z.object({
645
+ type: z.literal("Control"),
646
+ scope: jsonPointerSchema,
647
+ label: z.union([z.string(), z.literal(false)]).optional(),
648
+ rule: ruleSchema.optional(),
649
+ options: z.record(z.string(), z.unknown()).optional()
650
+ }).passthrough();
651
+ var verticalLayoutSchema = z.lazy(
652
+ () => z.object({
653
+ type: z.literal("VerticalLayout"),
654
+ elements: z.array(uiSchemaElementSchema),
655
+ rule: ruleSchema.optional(),
656
+ options: z.record(z.string(), z.unknown()).optional()
657
+ }).passthrough()
658
+ );
659
+ var horizontalLayoutSchema = z.lazy(
660
+ () => z.object({
661
+ type: z.literal("HorizontalLayout"),
662
+ elements: z.array(uiSchemaElementSchema),
663
+ rule: ruleSchema.optional(),
664
+ options: z.record(z.string(), z.unknown()).optional()
665
+ }).passthrough()
666
+ );
667
+ var groupLayoutSchema = z.lazy(
668
+ () => z.object({
669
+ type: z.literal("Group"),
670
+ label: z.string(),
671
+ elements: z.array(uiSchemaElementSchema),
672
+ rule: ruleSchema.optional(),
673
+ options: z.record(z.string(), z.unknown()).optional()
674
+ }).passthrough()
675
+ );
676
+ var categorySchema = z.lazy(
677
+ () => z.object({
678
+ type: z.literal("Category"),
679
+ label: z.string(),
680
+ elements: z.array(uiSchemaElementSchema),
681
+ rule: ruleSchema.optional(),
682
+ options: z.record(z.string(), z.unknown()).optional()
683
+ }).passthrough()
684
+ );
685
+ var categorizationSchema = z.lazy(
686
+ () => z.object({
687
+ type: z.literal("Categorization"),
688
+ elements: z.array(categorySchema),
689
+ label: z.string().optional(),
690
+ rule: ruleSchema.optional(),
691
+ options: z.record(z.string(), z.unknown()).optional()
692
+ }).passthrough()
693
+ );
694
+ var labelElementSchema = z.object({
695
+ type: z.literal("Label"),
696
+ text: z.string(),
697
+ rule: ruleSchema.optional(),
698
+ options: z.record(z.string(), z.unknown()).optional()
699
+ }).passthrough();
700
+ var uiSchema = z.lazy(
701
+ () => z.union([verticalLayoutSchema, horizontalLayoutSchema, groupLayoutSchema, categorizationSchema])
702
+ );
703
+
704
+ // src/ui-schema/ir-generator.ts
705
+ import { z as z2 } from "zod";
706
+ function parseOrThrow(schema, value, label) {
707
+ try {
708
+ return schema.parse(value);
709
+ } catch (error) {
710
+ if (error instanceof z2.ZodError) {
711
+ throw new Error(
712
+ `Generated ${label} failed validation:
713
+ ${error.issues.map((i) => ` ${i.path.join(".")}: ${i.message}`).join("\n")}`
714
+ );
715
+ }
716
+ throw error;
717
+ }
718
+ }
719
+ function fieldToScope(fieldName) {
720
+ return `#/properties/${fieldName}`;
721
+ }
722
+ function createShowRule(fieldName, value) {
723
+ return {
724
+ effect: "SHOW",
725
+ condition: {
726
+ scope: fieldToScope(fieldName),
727
+ schema: { const: value }
728
+ }
729
+ };
730
+ }
731
+ function combineRules(parentRule, childRule) {
732
+ const parentCondition = parentRule.condition;
733
+ const childCondition = childRule.condition;
734
+ return {
735
+ effect: "SHOW",
736
+ condition: {
737
+ scope: "#",
738
+ schema: {
739
+ allOf: [
740
+ {
741
+ properties: {
742
+ [parentCondition.scope.replace("#/properties/", "")]: parentCondition.schema
743
+ }
744
+ },
745
+ {
746
+ properties: {
747
+ [childCondition.scope.replace("#/properties/", "")]: childCondition.schema
748
+ }
749
+ }
750
+ ]
751
+ }
752
+ }
753
+ };
754
+ }
755
+ function fieldNodeToControl(field, parentRule) {
756
+ const displayNameAnnotation = field.annotations.find((a) => a.annotationKind === "displayName");
757
+ const control = {
758
+ type: "Control",
759
+ scope: fieldToScope(field.name),
760
+ ...displayNameAnnotation !== void 0 && { label: displayNameAnnotation.value },
761
+ ...parentRule !== void 0 && { rule: parentRule }
762
+ };
763
+ return control;
764
+ }
765
+ function groupNodeToLayout(group, parentRule) {
766
+ return {
767
+ type: "Group",
768
+ label: group.label,
769
+ elements: irElementsToUiSchema(group.elements, parentRule),
770
+ ...parentRule !== void 0 && { rule: parentRule }
771
+ };
772
+ }
773
+ function irElementsToUiSchema(elements, parentRule) {
774
+ const result = [];
775
+ for (const element of elements) {
776
+ switch (element.kind) {
777
+ case "field": {
778
+ result.push(fieldNodeToControl(element, parentRule));
779
+ break;
780
+ }
781
+ case "group": {
782
+ result.push(groupNodeToLayout(element, parentRule));
783
+ break;
784
+ }
785
+ case "conditional": {
786
+ const newRule = createShowRule(element.fieldName, element.value);
787
+ const combinedRule = parentRule !== void 0 ? combineRules(parentRule, newRule) : newRule;
788
+ const childElements = irElementsToUiSchema(element.elements, combinedRule);
789
+ result.push(...childElements);
790
+ break;
791
+ }
792
+ default: {
793
+ const _exhaustive = element;
794
+ void _exhaustive;
795
+ throw new Error("Unhandled IR element kind");
796
+ }
797
+ }
798
+ }
799
+ return result;
800
+ }
801
+ function generateUiSchemaFromIR(ir) {
802
+ const result = {
803
+ type: "VerticalLayout",
804
+ elements: irElementsToUiSchema(ir.elements)
805
+ };
806
+ return parseOrThrow(uiSchema, result, "UI Schema");
807
+ }
808
+
809
+ // src/ui-schema/generator.ts
810
+ function generateUiSchema(form) {
811
+ const ir = canonicalizeChainDSL(form);
812
+ return generateUiSchemaFromIR(ir);
813
+ }
814
+
815
+ // src/index.ts
816
+ import * as fs from "fs";
817
+ import * as path2 from "path";
818
+
819
+ // src/json-schema/types.ts
820
+ function setSchemaExtension(schema, key, value) {
821
+ schema[key] = value;
822
+ }
823
+ function getSchemaExtension(schema, key) {
824
+ return schema[key];
825
+ }
826
+
827
+ // src/json-schema/schema.ts
828
+ import { z as z3 } from "zod";
829
+ var jsonSchemaTypeSchema = z3.enum([
830
+ "string",
831
+ "number",
832
+ "integer",
833
+ "boolean",
834
+ "object",
835
+ "array",
836
+ "null"
837
+ ]);
838
+ var jsonSchema7Schema = z3.lazy(
839
+ () => z3.object({
840
+ $schema: z3.string().optional(),
841
+ $id: z3.string().optional(),
842
+ $ref: z3.string().optional(),
843
+ // Metadata
844
+ title: z3.string().optional(),
845
+ description: z3.string().optional(),
846
+ deprecated: z3.boolean().optional(),
847
+ // Type
848
+ type: z3.union([jsonSchemaTypeSchema, z3.array(jsonSchemaTypeSchema)]).optional(),
849
+ // String validation
850
+ minLength: z3.number().optional(),
851
+ maxLength: z3.number().optional(),
852
+ pattern: z3.string().optional(),
853
+ // Number validation
854
+ minimum: z3.number().optional(),
855
+ maximum: z3.number().optional(),
856
+ exclusiveMinimum: z3.number().optional(),
857
+ exclusiveMaximum: z3.number().optional(),
858
+ // Enum
859
+ enum: z3.array(z3.union([z3.string(), z3.number(), z3.boolean(), z3.null()])).readonly().optional(),
860
+ const: z3.union([z3.string(), z3.number(), z3.boolean(), z3.null()]).optional(),
861
+ // Object
862
+ properties: z3.record(z3.string(), jsonSchema7Schema).optional(),
863
+ required: z3.array(z3.string()).optional(),
864
+ additionalProperties: z3.union([z3.boolean(), jsonSchema7Schema]).optional(),
865
+ // Array
866
+ items: z3.union([jsonSchema7Schema, z3.array(jsonSchema7Schema)]).optional(),
867
+ minItems: z3.number().optional(),
868
+ maxItems: z3.number().optional(),
869
+ // Composition
870
+ allOf: z3.array(jsonSchema7Schema).optional(),
871
+ anyOf: z3.array(jsonSchema7Schema).optional(),
872
+ oneOf: z3.array(jsonSchema7Schema).optional(),
873
+ not: jsonSchema7Schema.optional(),
874
+ // Conditional
875
+ if: jsonSchema7Schema.optional(),
876
+ then: jsonSchema7Schema.optional(),
877
+ else: jsonSchema7Schema.optional(),
878
+ // Format
879
+ format: z3.string().optional(),
880
+ // Default
881
+ default: z3.unknown().optional(),
882
+ // FormSpec extensions
883
+ "x-formspec-source": z3.string().optional(),
884
+ "x-formspec-params": z3.array(z3.string()).readonly().optional(),
885
+ "x-formspec-schemaSource": z3.string().optional()
886
+ }).passthrough()
887
+ );
888
+
889
+ // src/analyzer/program.ts
890
+ import * as ts from "typescript";
891
+ import * as path from "path";
892
+ function createProgramContext(filePath) {
893
+ const absolutePath = path.resolve(filePath);
894
+ const fileDir = path.dirname(absolutePath);
895
+ const configPath = ts.findConfigFile(fileDir, ts.sys.fileExists.bind(ts.sys), "tsconfig.json");
896
+ let compilerOptions;
897
+ let fileNames;
898
+ if (configPath) {
899
+ const configFile = ts.readConfigFile(configPath, ts.sys.readFile.bind(ts.sys));
900
+ if (configFile.error) {
901
+ throw new Error(
902
+ `Error reading tsconfig.json: ${ts.flattenDiagnosticMessageText(configFile.error.messageText, "\n")}`
903
+ );
904
+ }
905
+ const parsed = ts.parseJsonConfigFileContent(
906
+ configFile.config,
907
+ ts.sys,
908
+ path.dirname(configPath)
909
+ );
910
+ if (parsed.errors.length > 0) {
911
+ const errorMessages = parsed.errors.map((e) => ts.flattenDiagnosticMessageText(e.messageText, "\n")).join("\n");
912
+ throw new Error(`Error parsing tsconfig.json: ${errorMessages}`);
913
+ }
914
+ compilerOptions = parsed.options;
915
+ fileNames = parsed.fileNames.includes(absolutePath) ? parsed.fileNames : [...parsed.fileNames, absolutePath];
916
+ } else {
917
+ compilerOptions = {
918
+ target: ts.ScriptTarget.ES2022,
919
+ module: ts.ModuleKind.NodeNext,
920
+ moduleResolution: ts.ModuleResolutionKind.NodeNext,
921
+ strict: true,
922
+ skipLibCheck: true,
923
+ declaration: true
73
924
  };
925
+ fileNames = [absolutePath];
926
+ }
927
+ const program = ts.createProgram(fileNames, compilerOptions);
928
+ const sourceFile = program.getSourceFile(absolutePath);
929
+ if (!sourceFile) {
930
+ throw new Error(`Could not find source file: ${absolutePath}`);
931
+ }
932
+ return {
933
+ program,
934
+ checker: program.getTypeChecker(),
935
+ sourceFile
936
+ };
937
+ }
938
+ function findNodeByName(sourceFile, name, predicate, getName) {
939
+ let result = null;
940
+ function visit(node) {
941
+ if (result) return;
942
+ if (predicate(node) && getName(node) === name) {
943
+ result = node;
944
+ return;
945
+ }
946
+ ts.forEachChild(node, visit);
947
+ }
948
+ visit(sourceFile);
949
+ return result;
950
+ }
951
+ function findClassByName(sourceFile, className) {
952
+ return findNodeByName(sourceFile, className, ts.isClassDeclaration, (n) => n.name?.text);
953
+ }
954
+ function findInterfaceByName(sourceFile, interfaceName) {
955
+ return findNodeByName(sourceFile, interfaceName, ts.isInterfaceDeclaration, (n) => n.name.text);
956
+ }
957
+ function findTypeAliasByName(sourceFile, aliasName) {
958
+ return findNodeByName(sourceFile, aliasName, ts.isTypeAliasDeclaration, (n) => n.name.text);
959
+ }
960
+
961
+ // src/analyzer/class-analyzer.ts
962
+ import * as ts4 from "typescript";
963
+
964
+ // src/analyzer/jsdoc-constraints.ts
965
+ import * as ts3 from "typescript";
966
+ import {
967
+ BUILTIN_CONSTRAINT_DEFINITIONS as BUILTIN_CONSTRAINT_DEFINITIONS2
968
+ } from "@formspec/core";
969
+
970
+ // src/analyzer/tsdoc-parser.ts
971
+ import * as ts2 from "typescript";
972
+ import {
973
+ TSDocParser,
974
+ TSDocConfiguration,
975
+ TSDocTagDefinition,
976
+ TSDocTagSyntaxKind,
977
+ DocPlainText,
978
+ DocSoftBreak,
979
+ TextRange
980
+ } from "@microsoft/tsdoc";
981
+ import {
982
+ BUILTIN_CONSTRAINT_DEFINITIONS
983
+ } from "@formspec/core";
984
+ var NUMERIC_CONSTRAINT_MAP = {
985
+ Minimum: "minimum",
986
+ Maximum: "maximum",
987
+ ExclusiveMinimum: "exclusiveMinimum",
988
+ ExclusiveMaximum: "exclusiveMaximum"
989
+ };
990
+ var LENGTH_CONSTRAINT_MAP = {
991
+ MinLength: "minLength",
992
+ MaxLength: "maxLength"
993
+ };
994
+ var TAGS_REQUIRING_RAW_TEXT = /* @__PURE__ */ new Set(["Pattern", "EnumOptions"]);
995
+ function isBuiltinConstraintName(tagName) {
996
+ return tagName in BUILTIN_CONSTRAINT_DEFINITIONS;
997
+ }
998
+ function createFormSpecTSDocConfig() {
999
+ const config = new TSDocConfiguration();
1000
+ for (const tagName of Object.keys(BUILTIN_CONSTRAINT_DEFINITIONS)) {
1001
+ config.addTagDefinition(
1002
+ new TSDocTagDefinition({
1003
+ tagName: "@" + tagName,
1004
+ syntaxKind: TSDocTagSyntaxKind.BlockTag,
1005
+ allowMultiple: true
1006
+ })
1007
+ );
1008
+ }
1009
+ return config;
1010
+ }
1011
+ var sharedParser;
1012
+ function getParser() {
1013
+ sharedParser ??= new TSDocParser(createFormSpecTSDocConfig());
1014
+ return sharedParser;
1015
+ }
1016
+ function parseTSDocTags(node, file = "") {
1017
+ const constraints = [];
1018
+ const annotations = [];
1019
+ const sourceFile = node.getSourceFile();
1020
+ const sourceText = sourceFile.getFullText();
1021
+ const commentRanges = ts2.getLeadingCommentRanges(sourceText, node.getFullStart());
1022
+ if (commentRanges) {
1023
+ for (const range of commentRanges) {
1024
+ if (range.kind !== ts2.SyntaxKind.MultiLineCommentTrivia) {
1025
+ continue;
1026
+ }
1027
+ const commentText = sourceText.substring(range.pos, range.end);
1028
+ if (!commentText.startsWith("/**")) {
1029
+ continue;
1030
+ }
1031
+ const parser = getParser();
1032
+ const parserContext = parser.parseRange(
1033
+ TextRange.fromStringRange(sourceText, range.pos, range.end)
1034
+ );
1035
+ const docComment = parserContext.docComment;
1036
+ for (const block of docComment.customBlocks) {
1037
+ const tagName = block.blockTag.tagName.substring(1);
1038
+ if (TAGS_REQUIRING_RAW_TEXT.has(tagName)) continue;
1039
+ const text = extractBlockText(block).trim();
1040
+ if (text === "") continue;
1041
+ const provenance = provenanceForComment(range, sourceFile, file, tagName);
1042
+ const constraintNode = parseConstraintValue(tagName, text, provenance);
1043
+ if (constraintNode) {
1044
+ constraints.push(constraintNode);
1045
+ }
1046
+ }
1047
+ if (docComment.deprecatedBlock !== void 0) {
1048
+ annotations.push({
1049
+ kind: "annotation",
1050
+ annotationKind: "deprecated",
1051
+ provenance: provenanceForComment(range, sourceFile, file, "deprecated")
1052
+ });
1053
+ }
1054
+ }
1055
+ }
1056
+ const jsDocTagsAll = ts2.getJSDocTags(node);
1057
+ for (const tag of jsDocTagsAll) {
1058
+ const tagName = tag.tagName.text;
1059
+ if (!TAGS_REQUIRING_RAW_TEXT.has(tagName)) continue;
1060
+ const commentText = getTagCommentText(tag);
1061
+ if (commentText === void 0 || commentText.trim() === "") continue;
1062
+ const text = commentText.trim();
1063
+ const provenance = provenanceForJSDocTag(tag, file);
1064
+ const constraintNode = parseConstraintValue(tagName, text, provenance);
1065
+ if (constraintNode) {
1066
+ constraints.push(constraintNode);
1067
+ }
1068
+ }
1069
+ let displayName;
1070
+ let description;
1071
+ let displayNameTag;
1072
+ let descriptionTag;
1073
+ for (const tag of jsDocTagsAll) {
1074
+ const tagName = tag.tagName.text;
1075
+ const commentText = getTagCommentText(tag);
1076
+ if (commentText === void 0 || commentText.trim() === "") {
1077
+ continue;
1078
+ }
1079
+ const trimmed = commentText.trim();
1080
+ if (tagName === "Field_displayName") {
1081
+ displayName = trimmed;
1082
+ displayNameTag = tag;
1083
+ } else if (tagName === "Field_description") {
1084
+ description = trimmed;
1085
+ descriptionTag = tag;
1086
+ }
1087
+ }
1088
+ if (displayName !== void 0 && displayNameTag) {
1089
+ annotations.push({
1090
+ kind: "annotation",
1091
+ annotationKind: "displayName",
1092
+ value: displayName,
1093
+ provenance: provenanceForJSDocTag(displayNameTag, file)
1094
+ });
1095
+ }
1096
+ if (description !== void 0 && descriptionTag) {
1097
+ annotations.push({
1098
+ kind: "annotation",
1099
+ annotationKind: "description",
1100
+ value: description,
1101
+ provenance: provenanceForJSDocTag(descriptionTag, file)
1102
+ });
1103
+ }
1104
+ return { constraints, annotations };
1105
+ }
1106
+ function extractBlockText(block) {
1107
+ return extractPlainText(block.content);
1108
+ }
1109
+ function extractPlainText(node) {
1110
+ let result = "";
1111
+ if (node instanceof DocPlainText) {
1112
+ return node.text;
1113
+ }
1114
+ if (node instanceof DocSoftBreak) {
1115
+ return " ";
1116
+ }
1117
+ if (typeof node.getChildNodes === "function") {
1118
+ for (const child of node.getChildNodes()) {
1119
+ result += extractPlainText(child);
1120
+ }
1121
+ }
1122
+ return result;
1123
+ }
1124
+ function parseConstraintValue(tagName, text, provenance) {
1125
+ if (!isBuiltinConstraintName(tagName)) {
1126
+ return null;
1127
+ }
1128
+ const expectedType = BUILTIN_CONSTRAINT_DEFINITIONS[tagName];
1129
+ if (expectedType === "number") {
1130
+ const value = Number(text);
1131
+ if (Number.isNaN(value)) {
1132
+ return null;
1133
+ }
1134
+ const numericKind = NUMERIC_CONSTRAINT_MAP[tagName];
1135
+ if (numericKind) {
1136
+ return {
1137
+ kind: "constraint",
1138
+ constraintKind: numericKind,
1139
+ value,
1140
+ provenance
1141
+ };
1142
+ }
1143
+ const lengthKind = LENGTH_CONSTRAINT_MAP[tagName];
1144
+ if (lengthKind) {
1145
+ return {
1146
+ kind: "constraint",
1147
+ constraintKind: lengthKind,
1148
+ value,
1149
+ provenance
1150
+ };
1151
+ }
1152
+ return null;
1153
+ }
1154
+ if (expectedType === "json") {
1155
+ try {
1156
+ const parsed = JSON.parse(text);
1157
+ if (!Array.isArray(parsed)) {
1158
+ return null;
1159
+ }
1160
+ const members = [];
1161
+ for (const item of parsed) {
1162
+ if (typeof item === "string" || typeof item === "number") {
1163
+ members.push(item);
1164
+ } else if (typeof item === "object" && item !== null && "id" in item) {
1165
+ const id = item["id"];
1166
+ if (typeof id === "string" || typeof id === "number") {
1167
+ members.push(id);
1168
+ }
1169
+ }
1170
+ }
1171
+ return {
1172
+ kind: "constraint",
1173
+ constraintKind: "allowedMembers",
1174
+ members,
1175
+ provenance
1176
+ };
1177
+ } catch {
1178
+ return null;
1179
+ }
1180
+ }
1181
+ return {
1182
+ kind: "constraint",
1183
+ constraintKind: "pattern",
1184
+ pattern: text,
1185
+ provenance
1186
+ };
1187
+ }
1188
+ function provenanceForComment(range, sourceFile, file, tagName) {
1189
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(range.pos);
1190
+ return {
1191
+ surface: "tsdoc",
1192
+ file,
1193
+ line: line + 1,
1194
+ column: character,
1195
+ tagName: "@" + tagName
1196
+ };
1197
+ }
1198
+ function provenanceForJSDocTag(tag, file) {
1199
+ const sourceFile = tag.getSourceFile();
1200
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(tag.getStart());
1201
+ return {
1202
+ surface: "tsdoc",
1203
+ file,
1204
+ line: line + 1,
1205
+ column: character,
1206
+ tagName: "@" + tag.tagName.text
1207
+ };
1208
+ }
1209
+ function getTagCommentText(tag) {
1210
+ if (tag.comment === void 0) {
1211
+ return void 0;
1212
+ }
1213
+ if (typeof tag.comment === "string") {
1214
+ return tag.comment;
1215
+ }
1216
+ return ts2.getTextOfJSDocComment(tag.comment);
1217
+ }
1218
+
1219
+ // src/analyzer/jsdoc-constraints.ts
1220
+ function extractJSDocConstraintNodes(node, file = "") {
1221
+ const result = parseTSDocTags(node, file);
1222
+ return [...result.constraints];
1223
+ }
1224
+ function extractJSDocAnnotationNodes(node, file = "") {
1225
+ const result = parseTSDocTags(node, file);
1226
+ return [...result.annotations];
1227
+ }
1228
+ function extractDefaultValueAnnotation(initializer, file = "") {
1229
+ if (!initializer) return null;
1230
+ let value;
1231
+ if (ts3.isStringLiteral(initializer)) {
1232
+ value = initializer.text;
1233
+ } else if (ts3.isNumericLiteral(initializer)) {
1234
+ value = Number(initializer.text);
1235
+ } else if (initializer.kind === ts3.SyntaxKind.TrueKeyword) {
1236
+ value = true;
1237
+ } else if (initializer.kind === ts3.SyntaxKind.FalseKeyword) {
1238
+ value = false;
1239
+ } else if (initializer.kind === ts3.SyntaxKind.NullKeyword) {
1240
+ value = null;
1241
+ } else if (ts3.isPrefixUnaryExpression(initializer)) {
1242
+ if (initializer.operator === ts3.SyntaxKind.MinusToken && ts3.isNumericLiteral(initializer.operand)) {
1243
+ value = -Number(initializer.operand.text);
1244
+ }
1245
+ }
1246
+ if (value === void 0) return null;
1247
+ const sourceFile = initializer.getSourceFile();
1248
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(initializer.getStart());
1249
+ return {
1250
+ kind: "annotation",
1251
+ annotationKind: "defaultValue",
1252
+ value,
1253
+ provenance: {
1254
+ surface: "tsdoc",
1255
+ file,
1256
+ line: line + 1,
1257
+ column: character
1258
+ }
1259
+ };
1260
+ }
1261
+
1262
+ // src/analyzer/class-analyzer.ts
1263
+ function isObjectType(type) {
1264
+ return !!(type.flags & ts4.TypeFlags.Object);
1265
+ }
1266
+ function isTypeReference(type) {
1267
+ return !!(type.flags & ts4.TypeFlags.Object) && !!(type.objectFlags & ts4.ObjectFlags.Reference);
1268
+ }
1269
+ function analyzeClassToIR(classDecl, checker, file = "") {
1270
+ const name = classDecl.name?.text ?? "AnonymousClass";
1271
+ const fields = [];
1272
+ const fieldLayouts = [];
1273
+ const typeRegistry = {};
1274
+ const visiting = /* @__PURE__ */ new Set();
1275
+ const instanceMethods = [];
1276
+ const staticMethods = [];
1277
+ for (const member of classDecl.members) {
1278
+ if (ts4.isPropertyDeclaration(member)) {
1279
+ const fieldNode = analyzeFieldToIR(member, checker, file, typeRegistry, visiting);
1280
+ if (fieldNode) {
1281
+ fields.push(fieldNode);
1282
+ fieldLayouts.push({});
1283
+ }
1284
+ } else if (ts4.isMethodDeclaration(member)) {
1285
+ const methodInfo = analyzeMethod(member, checker);
1286
+ if (methodInfo) {
1287
+ const isStatic = member.modifiers?.some((m) => m.kind === ts4.SyntaxKind.StaticKeyword);
1288
+ if (isStatic) {
1289
+ staticMethods.push(methodInfo);
1290
+ } else {
1291
+ instanceMethods.push(methodInfo);
1292
+ }
1293
+ }
1294
+ }
1295
+ }
1296
+ return { name, fields, fieldLayouts, typeRegistry, instanceMethods, staticMethods };
1297
+ }
1298
+ function analyzeInterfaceToIR(interfaceDecl, checker, file = "") {
1299
+ const name = interfaceDecl.name.text;
1300
+ const fields = [];
1301
+ const typeRegistry = {};
1302
+ const visiting = /* @__PURE__ */ new Set();
1303
+ for (const member of interfaceDecl.members) {
1304
+ if (ts4.isPropertySignature(member)) {
1305
+ const fieldNode = analyzeInterfacePropertyToIR(member, checker, file, typeRegistry, visiting);
1306
+ if (fieldNode) {
1307
+ fields.push(fieldNode);
1308
+ }
1309
+ }
1310
+ }
1311
+ const fieldLayouts = fields.map(() => ({}));
1312
+ return { name, fields, fieldLayouts, typeRegistry, instanceMethods: [], staticMethods: [] };
1313
+ }
1314
+ function analyzeTypeAliasToIR(typeAlias, checker, file = "") {
1315
+ if (!ts4.isTypeLiteralNode(typeAlias.type)) {
1316
+ const sourceFile = typeAlias.getSourceFile();
1317
+ const { line } = sourceFile.getLineAndCharacterOfPosition(typeAlias.getStart());
1318
+ const kindDesc = ts4.SyntaxKind[typeAlias.type.kind] ?? "unknown";
1319
+ return {
1320
+ ok: false,
1321
+ error: `Type alias "${typeAlias.name.text}" at line ${String(line + 1)} is not an object type literal (found ${kindDesc})`
1322
+ };
1323
+ }
1324
+ const name = typeAlias.name.text;
1325
+ const fields = [];
1326
+ const typeRegistry = {};
1327
+ const visiting = /* @__PURE__ */ new Set();
1328
+ for (const member of typeAlias.type.members) {
1329
+ if (ts4.isPropertySignature(member)) {
1330
+ const fieldNode = analyzeInterfacePropertyToIR(member, checker, file, typeRegistry, visiting);
1331
+ if (fieldNode) {
1332
+ fields.push(fieldNode);
1333
+ }
1334
+ }
1335
+ }
1336
+ return {
1337
+ ok: true,
1338
+ analysis: {
1339
+ name,
1340
+ fields,
1341
+ fieldLayouts: fields.map(() => ({})),
1342
+ typeRegistry,
1343
+ instanceMethods: [],
1344
+ staticMethods: []
1345
+ }
1346
+ };
1347
+ }
1348
+ function analyzeFieldToIR(prop, checker, file, typeRegistry, visiting) {
1349
+ if (!ts4.isIdentifier(prop.name)) {
1350
+ return null;
1351
+ }
1352
+ const name = prop.name.text;
1353
+ const tsType = checker.getTypeAtLocation(prop);
1354
+ const optional = prop.questionToken !== void 0;
1355
+ const provenance = provenanceForNode(prop, file);
1356
+ const type = resolveTypeNode(tsType, checker, file, typeRegistry, visiting);
1357
+ const constraints = [];
1358
+ if (prop.type) {
1359
+ constraints.push(...extractTypeAliasConstraintNodes(prop.type, checker, file));
1360
+ }
1361
+ constraints.push(...extractJSDocConstraintNodes(prop, file));
1362
+ const annotations = [];
1363
+ annotations.push(...extractJSDocAnnotationNodes(prop, file));
1364
+ const defaultAnnotation = extractDefaultValueAnnotation(prop.initializer, file);
1365
+ if (defaultAnnotation) {
1366
+ annotations.push(defaultAnnotation);
1367
+ }
1368
+ return {
1369
+ kind: "field",
1370
+ name,
1371
+ type,
1372
+ required: !optional,
1373
+ constraints,
1374
+ annotations,
1375
+ provenance
1376
+ };
1377
+ }
1378
+ function analyzeInterfacePropertyToIR(prop, checker, file, typeRegistry, visiting) {
1379
+ if (!ts4.isIdentifier(prop.name)) {
1380
+ return null;
1381
+ }
1382
+ const name = prop.name.text;
1383
+ const tsType = checker.getTypeAtLocation(prop);
1384
+ const optional = prop.questionToken !== void 0;
1385
+ const provenance = provenanceForNode(prop, file);
1386
+ const type = resolveTypeNode(tsType, checker, file, typeRegistry, visiting);
1387
+ const constraints = [];
1388
+ if (prop.type) {
1389
+ constraints.push(...extractTypeAliasConstraintNodes(prop.type, checker, file));
1390
+ }
1391
+ constraints.push(...extractJSDocConstraintNodes(prop, file));
1392
+ const annotations = [];
1393
+ annotations.push(...extractJSDocAnnotationNodes(prop, file));
1394
+ return {
1395
+ kind: "field",
1396
+ name,
1397
+ type,
1398
+ required: !optional,
1399
+ constraints,
1400
+ annotations,
1401
+ provenance
1402
+ };
1403
+ }
1404
+ function resolveTypeNode(type, checker, file, typeRegistry, visiting) {
1405
+ if (type.flags & ts4.TypeFlags.String) {
1406
+ return { kind: "primitive", primitiveKind: "string" };
1407
+ }
1408
+ if (type.flags & ts4.TypeFlags.Number) {
1409
+ return { kind: "primitive", primitiveKind: "number" };
1410
+ }
1411
+ if (type.flags & ts4.TypeFlags.Boolean) {
1412
+ return { kind: "primitive", primitiveKind: "boolean" };
1413
+ }
1414
+ if (type.flags & ts4.TypeFlags.Null) {
1415
+ return { kind: "primitive", primitiveKind: "null" };
1416
+ }
1417
+ if (type.flags & ts4.TypeFlags.Undefined) {
1418
+ return { kind: "primitive", primitiveKind: "null" };
1419
+ }
1420
+ if (type.isStringLiteral()) {
1421
+ return {
1422
+ kind: "enum",
1423
+ members: [{ value: type.value }]
1424
+ };
1425
+ }
1426
+ if (type.isNumberLiteral()) {
1427
+ return {
1428
+ kind: "enum",
1429
+ members: [{ value: type.value }]
1430
+ };
1431
+ }
1432
+ if (type.isUnion()) {
1433
+ return resolveUnionType(type, checker, file, typeRegistry, visiting);
1434
+ }
1435
+ if (checker.isArrayType(type)) {
1436
+ return resolveArrayType(type, checker, file, typeRegistry, visiting);
1437
+ }
1438
+ if (isObjectType(type)) {
1439
+ return resolveObjectType(type, checker, file, typeRegistry, visiting);
1440
+ }
1441
+ return { kind: "primitive", primitiveKind: "string" };
1442
+ }
1443
+ function resolveUnionType(type, checker, file, typeRegistry, visiting) {
1444
+ const allTypes = type.types;
1445
+ const nonNullTypes = allTypes.filter(
1446
+ (t) => !(t.flags & (ts4.TypeFlags.Null | ts4.TypeFlags.Undefined))
1447
+ );
1448
+ const hasNull = allTypes.some((t) => t.flags & ts4.TypeFlags.Null);
1449
+ const isBooleanUnion2 = nonNullTypes.length === 2 && nonNullTypes.every((t) => t.flags & ts4.TypeFlags.BooleanLiteral);
1450
+ if (isBooleanUnion2) {
1451
+ const boolNode = { kind: "primitive", primitiveKind: "boolean" };
1452
+ if (hasNull) {
1453
+ return {
1454
+ kind: "union",
1455
+ members: [boolNode, { kind: "primitive", primitiveKind: "null" }]
1456
+ };
1457
+ }
1458
+ return boolNode;
1459
+ }
1460
+ const allStringLiterals = nonNullTypes.every((t) => t.isStringLiteral());
1461
+ if (allStringLiterals && nonNullTypes.length > 0) {
1462
+ const stringTypes = nonNullTypes.filter((t) => t.isStringLiteral());
1463
+ const enumNode = {
1464
+ kind: "enum",
1465
+ members: stringTypes.map((t) => ({ value: t.value }))
1466
+ };
1467
+ if (hasNull) {
1468
+ return {
1469
+ kind: "union",
1470
+ members: [enumNode, { kind: "primitive", primitiveKind: "null" }]
1471
+ };
1472
+ }
1473
+ return enumNode;
1474
+ }
1475
+ const allNumberLiterals = nonNullTypes.every((t) => t.isNumberLiteral());
1476
+ if (allNumberLiterals && nonNullTypes.length > 0) {
1477
+ const numberTypes = nonNullTypes.filter((t) => t.isNumberLiteral());
1478
+ const enumNode = {
1479
+ kind: "enum",
1480
+ members: numberTypes.map((t) => ({ value: t.value }))
1481
+ };
1482
+ if (hasNull) {
1483
+ return {
1484
+ kind: "union",
1485
+ members: [enumNode, { kind: "primitive", primitiveKind: "null" }]
1486
+ };
1487
+ }
1488
+ return enumNode;
1489
+ }
1490
+ if (nonNullTypes.length === 1 && nonNullTypes[0]) {
1491
+ const inner = resolveTypeNode(nonNullTypes[0], checker, file, typeRegistry, visiting);
1492
+ if (hasNull) {
1493
+ return {
1494
+ kind: "union",
1495
+ members: [inner, { kind: "primitive", primitiveKind: "null" }]
1496
+ };
1497
+ }
1498
+ return inner;
1499
+ }
1500
+ const members = nonNullTypes.map(
1501
+ (t) => resolveTypeNode(t, checker, file, typeRegistry, visiting)
1502
+ );
1503
+ if (hasNull) {
1504
+ members.push({ kind: "primitive", primitiveKind: "null" });
1505
+ }
1506
+ return { kind: "union", members };
1507
+ }
1508
+ function resolveArrayType(type, checker, file, typeRegistry, visiting) {
1509
+ const typeArgs = isTypeReference(type) ? type.typeArguments : void 0;
1510
+ const elementType = typeArgs?.[0];
1511
+ const items = elementType ? resolveTypeNode(elementType, checker, file, typeRegistry, visiting) : { kind: "primitive", primitiveKind: "string" };
1512
+ return { kind: "array", items };
1513
+ }
1514
+ function resolveObjectType(type, checker, file, typeRegistry, visiting) {
1515
+ if (visiting.has(type)) {
1516
+ return { kind: "object", properties: [], additionalProperties: false };
1517
+ }
1518
+ visiting.add(type);
1519
+ const typeName = getNamedTypeName(type);
1520
+ if (typeName && typeName in typeRegistry) {
1521
+ visiting.delete(type);
1522
+ return { kind: "reference", name: typeName, typeArguments: [] };
1523
+ }
1524
+ const properties = [];
1525
+ const fieldInfoMap = getNamedTypeFieldNodeInfoMap(type, checker, file, typeRegistry, visiting);
1526
+ for (const prop of type.getProperties()) {
1527
+ const declaration = prop.valueDeclaration ?? prop.declarations?.[0];
1528
+ if (!declaration) continue;
1529
+ const propType = checker.getTypeOfSymbolAtLocation(prop, declaration);
1530
+ const optional = !!(prop.flags & ts4.SymbolFlags.Optional);
1531
+ const propTypeNode = resolveTypeNode(propType, checker, file, typeRegistry, visiting);
1532
+ const fieldNodeInfo = fieldInfoMap?.get(prop.name);
1533
+ properties.push({
1534
+ name: prop.name,
1535
+ type: propTypeNode,
1536
+ optional,
1537
+ constraints: fieldNodeInfo?.constraints ?? [],
1538
+ annotations: fieldNodeInfo?.annotations ?? [],
1539
+ provenance: fieldNodeInfo?.provenance ?? provenanceForFile(file)
1540
+ });
1541
+ }
1542
+ visiting.delete(type);
1543
+ const objectNode = {
1544
+ kind: "object",
1545
+ properties,
1546
+ additionalProperties: false
1547
+ };
1548
+ if (typeName) {
1549
+ typeRegistry[typeName] = {
1550
+ name: typeName,
1551
+ type: objectNode,
1552
+ provenance: provenanceForFile(file)
1553
+ };
1554
+ return { kind: "reference", name: typeName, typeArguments: [] };
1555
+ }
1556
+ return objectNode;
1557
+ }
1558
+ function getNamedTypeFieldNodeInfoMap(type, checker, file, typeRegistry, visiting) {
1559
+ const symbols = [type.getSymbol(), type.aliasSymbol].filter(
1560
+ (s) => s?.declarations != null && s.declarations.length > 0
1561
+ );
1562
+ for (const symbol of symbols) {
1563
+ const declarations = symbol.declarations;
1564
+ if (!declarations) continue;
1565
+ const classDecl = declarations.find(ts4.isClassDeclaration);
1566
+ if (classDecl) {
1567
+ const map = /* @__PURE__ */ new Map();
1568
+ for (const member of classDecl.members) {
1569
+ if (ts4.isPropertyDeclaration(member) && ts4.isIdentifier(member.name)) {
1570
+ const fieldNode = analyzeFieldToIR(member, checker, file, typeRegistry, visiting);
1571
+ if (fieldNode) {
1572
+ map.set(fieldNode.name, {
1573
+ constraints: [...fieldNode.constraints],
1574
+ annotations: [...fieldNode.annotations],
1575
+ provenance: fieldNode.provenance
1576
+ });
1577
+ }
1578
+ }
1579
+ }
1580
+ return map;
1581
+ }
1582
+ const interfaceDecl = declarations.find(ts4.isInterfaceDeclaration);
1583
+ if (interfaceDecl) {
1584
+ return buildFieldNodeInfoMap(interfaceDecl.members, checker, file, typeRegistry, visiting);
1585
+ }
1586
+ const typeAliasDecl = declarations.find(ts4.isTypeAliasDeclaration);
1587
+ if (typeAliasDecl && ts4.isTypeLiteralNode(typeAliasDecl.type)) {
1588
+ return buildFieldNodeInfoMap(
1589
+ typeAliasDecl.type.members,
1590
+ checker,
1591
+ file,
1592
+ typeRegistry,
1593
+ visiting
1594
+ );
1595
+ }
1596
+ }
1597
+ return null;
1598
+ }
1599
+ function buildFieldNodeInfoMap(members, checker, file, typeRegistry, visiting) {
1600
+ const map = /* @__PURE__ */ new Map();
1601
+ for (const member of members) {
1602
+ if (ts4.isPropertySignature(member)) {
1603
+ const fieldNode = analyzeInterfacePropertyToIR(member, checker, file, typeRegistry, visiting);
1604
+ if (fieldNode) {
1605
+ map.set(fieldNode.name, {
1606
+ constraints: [...fieldNode.constraints],
1607
+ annotations: [...fieldNode.annotations],
1608
+ provenance: fieldNode.provenance
1609
+ });
1610
+ }
1611
+ }
1612
+ }
1613
+ return map;
1614
+ }
1615
+ function extractTypeAliasConstraintNodes(typeNode, checker, file) {
1616
+ if (!ts4.isTypeReferenceNode(typeNode)) return [];
1617
+ const symbol = checker.getSymbolAtLocation(typeNode.typeName);
1618
+ if (!symbol?.declarations) return [];
1619
+ const aliasDecl = symbol.declarations.find(ts4.isTypeAliasDeclaration);
1620
+ if (!aliasDecl) return [];
1621
+ if (ts4.isTypeLiteralNode(aliasDecl.type)) return [];
1622
+ return extractJSDocConstraintNodes(aliasDecl, file);
1623
+ }
1624
+ function provenanceForNode(node, file) {
1625
+ const sourceFile = node.getSourceFile();
1626
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1627
+ return {
1628
+ surface: "tsdoc",
1629
+ file,
1630
+ line: line + 1,
1631
+ column: character
1632
+ };
1633
+ }
1634
+ function provenanceForFile(file) {
1635
+ return { surface: "tsdoc", file, line: 0, column: 0 };
1636
+ }
1637
+ function getNamedTypeName(type) {
1638
+ const symbol = type.getSymbol();
1639
+ if (symbol?.declarations) {
1640
+ const decl = symbol.declarations[0];
1641
+ if (decl && (ts4.isClassDeclaration(decl) || ts4.isInterfaceDeclaration(decl) || ts4.isTypeAliasDeclaration(decl))) {
1642
+ const name = ts4.isClassDeclaration(decl) ? decl.name?.text : decl.name.text;
1643
+ if (name) return name;
1644
+ }
1645
+ }
1646
+ const aliasSymbol = type.aliasSymbol;
1647
+ if (aliasSymbol?.declarations) {
1648
+ const aliasDecl = aliasSymbol.declarations.find(ts4.isTypeAliasDeclaration);
1649
+ if (aliasDecl) {
1650
+ return aliasDecl.name.text;
1651
+ }
1652
+ }
1653
+ return null;
1654
+ }
1655
+ function analyzeMethod(method, checker) {
1656
+ if (!ts4.isIdentifier(method.name)) {
1657
+ return null;
1658
+ }
1659
+ const name = method.name.text;
1660
+ const parameters = [];
1661
+ for (const param of method.parameters) {
1662
+ if (ts4.isIdentifier(param.name)) {
1663
+ const paramInfo = analyzeParameter(param, checker);
1664
+ parameters.push(paramInfo);
1665
+ }
1666
+ }
1667
+ const returnTypeNode = method.type;
1668
+ const signature = checker.getSignatureFromDeclaration(method);
1669
+ const returnType = signature ? checker.getReturnTypeOfSignature(signature) : checker.getTypeAtLocation(method);
1670
+ return { name, parameters, returnTypeNode, returnType };
1671
+ }
1672
+ function analyzeParameter(param, checker) {
1673
+ const name = ts4.isIdentifier(param.name) ? param.name.text : "param";
1674
+ const typeNode = param.type;
1675
+ const type = checker.getTypeAtLocation(param);
1676
+ const formSpecExportName = detectFormSpecReference(typeNode);
1677
+ const optional = param.questionToken !== void 0 || param.initializer !== void 0;
1678
+ return { name, typeNode, type, formSpecExportName, optional };
1679
+ }
1680
+ function detectFormSpecReference(typeNode) {
1681
+ if (!typeNode) return null;
1682
+ if (!ts4.isTypeReferenceNode(typeNode)) return null;
1683
+ const typeName = ts4.isIdentifier(typeNode.typeName) ? typeNode.typeName.text : ts4.isQualifiedName(typeNode.typeName) ? typeNode.typeName.right.text : null;
1684
+ if (typeName !== "InferSchema" && typeName !== "InferFormSchema") return null;
1685
+ const typeArg = typeNode.typeArguments?.[0];
1686
+ if (!typeArg || !ts4.isTypeQueryNode(typeArg)) return null;
1687
+ if (ts4.isIdentifier(typeArg.exprName)) {
1688
+ return typeArg.exprName.text;
1689
+ }
1690
+ if (ts4.isQualifiedName(typeArg.exprName)) {
1691
+ return typeArg.exprName.right.text;
1692
+ }
1693
+ return null;
1694
+ }
1695
+
1696
+ // src/generators/class-schema.ts
1697
+ function generateClassSchemas(analysis, source) {
1698
+ const ir = canonicalizeTSDoc(analysis, source);
1699
+ return {
1700
+ jsonSchema: generateJsonSchemaFromIR(ir),
1701
+ uiSchema: generateUiSchemaFromIR(ir)
1702
+ };
1703
+ }
1704
+ function generateSchemasFromClass(options) {
1705
+ const ctx = createProgramContext(options.filePath);
1706
+ const classDecl = findClassByName(ctx.sourceFile, options.className);
1707
+ if (!classDecl) {
1708
+ throw new Error(`Class "${options.className}" not found in ${options.filePath}`);
1709
+ }
1710
+ const analysis = analyzeClassToIR(classDecl, ctx.checker, options.filePath);
1711
+ return generateClassSchemas(analysis, { file: options.filePath });
1712
+ }
1713
+ function generateSchemas(options) {
1714
+ const ctx = createProgramContext(options.filePath);
1715
+ const source = { file: options.filePath };
1716
+ const classDecl = findClassByName(ctx.sourceFile, options.typeName);
1717
+ if (classDecl) {
1718
+ const analysis = analyzeClassToIR(classDecl, ctx.checker, options.filePath);
1719
+ return generateClassSchemas(analysis, source);
1720
+ }
1721
+ const interfaceDecl = findInterfaceByName(ctx.sourceFile, options.typeName);
1722
+ if (interfaceDecl) {
1723
+ const analysis = analyzeInterfaceToIR(interfaceDecl, ctx.checker, options.filePath);
1724
+ return generateClassSchemas(analysis, source);
1725
+ }
1726
+ const typeAlias = findTypeAliasByName(ctx.sourceFile, options.typeName);
1727
+ if (typeAlias) {
1728
+ const result = analyzeTypeAliasToIR(typeAlias, ctx.checker, options.filePath);
1729
+ if (result.ok) {
1730
+ return generateClassSchemas(result.analysis, source);
1731
+ }
1732
+ throw new Error(result.error);
1733
+ }
1734
+ throw new Error(
1735
+ `Type "${options.typeName}" not found as a class, interface, or type alias in ${options.filePath}`
1736
+ );
1737
+ }
1738
+
1739
+ // src/index.ts
1740
+ function buildFormSchemas(form) {
1741
+ return {
1742
+ jsonSchema: generateJsonSchema(form),
1743
+ uiSchema: generateUiSchema(form)
1744
+ };
74
1745
  }
75
- /**
76
- * Builds and writes both JSON Schema and UI Schema files to disk.
77
- *
78
- * This is a convenience function for build-time schema generation.
79
- * It creates the output directory if it doesn't exist.
80
- *
81
- * @example
82
- * ```typescript
83
- * import { formspec, field } from "formspec";
84
- * import { writeSchemas } from "@formspec/build";
85
- *
86
- * const ProductForm = formspec(
87
- * field.text("name", { required: true }),
88
- * field.enum("status", ["draft", "active"]),
89
- * );
90
- *
91
- * // Write schemas to ./generated/product-schema.json and ./generated/product-uischema.json
92
- * const { jsonSchemaPath, uiSchemaPath } = writeSchemas(ProductForm, {
93
- * outDir: "./generated",
94
- * name: "product",
95
- * });
96
- *
97
- * console.log(`Generated: ${jsonSchemaPath}, ${uiSchemaPath}`);
98
- * ```
99
- *
100
- * @param form - The FormSpec to build schemas from
101
- * @param options - Output options (directory, file name, indentation)
102
- * @returns Object containing paths to the generated files
103
- */
104
- export function writeSchemas(form, options) {
105
- const { outDir, name = "schema", indent = 2 } = options;
106
- // Build schemas
107
- const { jsonSchema, uiSchema } = buildFormSchemas(form);
108
- // Ensure output directory exists
109
- if (!fs.existsSync(outDir)) {
110
- fs.mkdirSync(outDir, { recursive: true });
111
- }
112
- // Write files
113
- const jsonSchemaPath = path.join(outDir, `${name}-schema.json`);
114
- const uiSchemaPath = path.join(outDir, `${name}-uischema.json`);
115
- fs.writeFileSync(jsonSchemaPath, JSON.stringify(jsonSchema, null, indent));
116
- fs.writeFileSync(uiSchemaPath, JSON.stringify(uiSchema, null, indent));
117
- return { jsonSchemaPath, uiSchemaPath };
1746
+ function writeSchemas(form, options) {
1747
+ const { outDir, name = "schema", indent = 2 } = options;
1748
+ const { jsonSchema, uiSchema: uiSchema2 } = buildFormSchemas(form);
1749
+ if (!fs.existsSync(outDir)) {
1750
+ fs.mkdirSync(outDir, { recursive: true });
1751
+ }
1752
+ const jsonSchemaPath = path2.join(outDir, `${name}-schema.json`);
1753
+ const uiSchemaPath = path2.join(outDir, `${name}-uischema.json`);
1754
+ fs.writeFileSync(jsonSchemaPath, JSON.stringify(jsonSchema, null, indent));
1755
+ fs.writeFileSync(uiSchemaPath, JSON.stringify(uiSchema2, null, indent));
1756
+ return { jsonSchemaPath, uiSchemaPath };
118
1757
  }
1758
+ export {
1759
+ buildFormSchemas,
1760
+ categorizationSchema,
1761
+ categorySchema,
1762
+ controlSchema,
1763
+ generateJsonSchema,
1764
+ generateSchemas,
1765
+ generateSchemasFromClass,
1766
+ generateUiSchema,
1767
+ getSchemaExtension,
1768
+ groupLayoutSchema,
1769
+ horizontalLayoutSchema,
1770
+ jsonSchema7Schema,
1771
+ jsonSchemaTypeSchema,
1772
+ labelElementSchema,
1773
+ ruleConditionSchema,
1774
+ ruleEffectSchema,
1775
+ ruleSchema,
1776
+ schemaBasedConditionSchema,
1777
+ setSchemaExtension,
1778
+ uiSchemaElementSchema,
1779
+ uiSchemaElementTypeSchema,
1780
+ uiSchema as uiSchemaSchema,
1781
+ verticalLayoutSchema,
1782
+ writeSchemas
1783
+ };
119
1784
  //# sourceMappingURL=index.js.map