@featurevisor/core 3.1.0 → 3.3.0

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 (213) hide show
  1. package/lib/datasource/datasource.d.ts +1 -1
  2. package/lib/datasource/datasource.js +4 -14
  3. package/lib/datasource/datasource.js.map +1 -1
  4. package/lib/datasource/requiredFeatures.d.ts +7 -0
  5. package/lib/datasource/requiredFeatures.js +38 -0
  6. package/lib/datasource/requiredFeatures.js.map +1 -0
  7. package/lib/linter/checkCircularDependency.d.ts +1 -1
  8. package/lib/linter/checkCircularDependency.js +3 -22
  9. package/lib/linter/checkCircularDependency.js.map +1 -1
  10. package/lib/linter/conditionSchema.js +27 -3
  11. package/lib/linter/conditionSchema.js.map +1 -1
  12. package/lib/linter/testSchema.d.ts +4 -0
  13. package/lib/linter/testSchema.js +46 -4
  14. package/lib/linter/testSchema.js.map +1 -1
  15. package/lib/promoter/index.js +62 -1
  16. package/lib/promoter/index.js.map +1 -1
  17. package/lib/tester/testFeature.js +17 -16
  18. package/lib/tester/testFeature.js.map +1 -1
  19. package/package.json +10 -7
  20. package/CHANGELOG.md +0 -2246
  21. package/coverage/clover.xml +0 -5456
  22. package/coverage/coverage-final.json +0 -64
  23. package/coverage/lcov-report/base.css +0 -224
  24. package/coverage/lcov-report/block-navigation.js +0 -87
  25. package/coverage/lcov-report/favicon.png +0 -0
  26. package/coverage/lcov-report/index.html +0 -371
  27. package/coverage/lcov-report/prettify.css +0 -1
  28. package/coverage/lcov-report/prettify.js +0 -2
  29. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  30. package/coverage/lcov-report/sorter.js +0 -210
  31. package/coverage/lcov-report/src/assess-distribution/index.html +0 -116
  32. package/coverage/lcov-report/src/assess-distribution/index.ts.html +0 -754
  33. package/coverage/lcov-report/src/benchmark/index.html +0 -116
  34. package/coverage/lcov-report/src/benchmark/index.ts.html +0 -793
  35. package/coverage/lcov-report/src/builder/allocator.ts.html +0 -220
  36. package/coverage/lcov-report/src/builder/applyContextToConditions.ts.html +0 -502
  37. package/coverage/lcov-report/src/builder/applyContextToDatafile.ts.html +0 -772
  38. package/coverage/lcov-report/src/builder/applyContextToSegments.ts.html +0 -580
  39. package/coverage/lcov-report/src/builder/buildDatafile.ts.html +0 -2053
  40. package/coverage/lcov-report/src/builder/buildProject.ts.html +0 -1117
  41. package/coverage/lcov-report/src/builder/buildRuntimeDatafiles.ts.html +0 -256
  42. package/coverage/lcov-report/src/builder/getFeatureRanges.ts.html +0 -268
  43. package/coverage/lcov-report/src/builder/hashes.ts.html +0 -412
  44. package/coverage/lcov-report/src/builder/index.html +0 -311
  45. package/coverage/lcov-report/src/builder/index.ts.html +0 -91
  46. package/coverage/lcov-report/src/builder/mutateVariables.ts.html +0 -421
  47. package/coverage/lcov-report/src/builder/mutator.ts.html +0 -796
  48. package/coverage/lcov-report/src/builder/revision.ts.html +0 -151
  49. package/coverage/lcov-report/src/builder/traffic.ts.html +0 -661
  50. package/coverage/lcov-report/src/cli/cli.ts.html +0 -400
  51. package/coverage/lcov-report/src/cli/index.html +0 -131
  52. package/coverage/lcov-report/src/cli/plugins.ts.html +0 -214
  53. package/coverage/lcov-report/src/config/index.html +0 -131
  54. package/coverage/lcov-report/src/config/index.ts.html +0 -88
  55. package/coverage/lcov-report/src/config/projectConfig.ts.html +0 -925
  56. package/coverage/lcov-report/src/datasource/adapter.ts.html +0 -253
  57. package/coverage/lcov-report/src/datasource/datasource.ts.html +0 -1000
  58. package/coverage/lcov-report/src/datasource/filesystemAdapter.ts.html +0 -1576
  59. package/coverage/lcov-report/src/datasource/index.html +0 -161
  60. package/coverage/lcov-report/src/datasource/index.ts.html +0 -94
  61. package/coverage/lcov-report/src/evaluate/index.html +0 -116
  62. package/coverage/lcov-report/src/evaluate/index.ts.html +0 -814
  63. package/coverage/lcov-report/src/find-duplicate-segments/findDuplicateSegments.ts.html +0 -313
  64. package/coverage/lcov-report/src/find-duplicate-segments/index.html +0 -131
  65. package/coverage/lcov-report/src/find-duplicate-segments/index.ts.html +0 -307
  66. package/coverage/lcov-report/src/find-usage/index.html +0 -116
  67. package/coverage/lcov-report/src/find-usage/index.ts.html +0 -1780
  68. package/coverage/lcov-report/src/generate-code/index.html +0 -131
  69. package/coverage/lcov-report/src/generate-code/index.ts.html +0 -403
  70. package/coverage/lcov-report/src/generate-code/typescript.ts.html +0 -1909
  71. package/coverage/lcov-report/src/index.html +0 -131
  72. package/coverage/lcov-report/src/info/index.html +0 -116
  73. package/coverage/lcov-report/src/info/index.ts.html +0 -472
  74. package/coverage/lcov-report/src/init/index.html +0 -116
  75. package/coverage/lcov-report/src/init/index.ts.html +0 -280
  76. package/coverage/lcov-report/src/linter/attributeSchema.ts.html +0 -1963
  77. package/coverage/lcov-report/src/linter/checkCircularDependency.ts.html +0 -220
  78. package/coverage/lcov-report/src/linter/checkPercentageExceedingSlot.ts.html +0 -268
  79. package/coverage/lcov-report/src/linter/conditionSchema.ts.html +0 -2224
  80. package/coverage/lcov-report/src/linter/featureSchema.ts.html +0 -5851
  81. package/coverage/lcov-report/src/linter/groupSchema.ts.html +0 -226
  82. package/coverage/lcov-report/src/linter/index.html +0 -326
  83. package/coverage/lcov-report/src/linter/index.ts.html +0 -88
  84. package/coverage/lcov-report/src/linter/lintProject.ts.html +0 -2704
  85. package/coverage/lcov-report/src/linter/mutationNotation.ts.html +0 -1411
  86. package/coverage/lcov-report/src/linter/printError.ts.html +0 -289
  87. package/coverage/lcov-report/src/linter/schema.ts.html +0 -1558
  88. package/coverage/lcov-report/src/linter/segmentSchema.ts.html +0 -139
  89. package/coverage/lcov-report/src/linter/targetSchema.ts.html +0 -223
  90. package/coverage/lcov-report/src/linter/testSchema.ts.html +0 -529
  91. package/coverage/lcov-report/src/linter/zodHelpers.ts.html +0 -133
  92. package/coverage/lcov-report/src/list/index.html +0 -131
  93. package/coverage/lcov-report/src/list/index.ts.html +0 -2065
  94. package/coverage/lcov-report/src/list/matrix.ts.html +0 -721
  95. package/coverage/lcov-report/src/promoter/index.html +0 -116
  96. package/coverage/lcov-report/src/promoter/index.ts.html +0 -3883
  97. package/coverage/lcov-report/src/sets.ts.html +0 -313
  98. package/coverage/lcov-report/src/targeting.ts.html +0 -403
  99. package/coverage/lcov-report/src/tester/cliFormat.ts.html +0 -133
  100. package/coverage/lcov-report/src/tester/helpers.ts.html +0 -313
  101. package/coverage/lcov-report/src/tester/index.html +0 -206
  102. package/coverage/lcov-report/src/tester/prettyDuration.ts.html +0 -187
  103. package/coverage/lcov-report/src/tester/printTestResult.ts.html +0 -337
  104. package/coverage/lcov-report/src/tester/testFeature.ts.html +0 -1186
  105. package/coverage/lcov-report/src/tester/testProject.ts.html +0 -1018
  106. package/coverage/lcov-report/src/tester/testSegment.ts.html +0 -316
  107. package/coverage/lcov-report/src/utils/extractKeys.ts.html +0 -493
  108. package/coverage/lcov-report/src/utils/git.ts.html +0 -559
  109. package/coverage/lcov-report/src/utils/index.html +0 -161
  110. package/coverage/lcov-report/src/utils/index.ts.html +0 -94
  111. package/coverage/lcov-report/src/utils/pretty.ts.html +0 -121
  112. package/coverage/lcov.info +0 -11615
  113. package/jest.config.js +0 -22
  114. package/json-schema/README.md +0 -5
  115. package/json-schema/attribute.json +0 -40
  116. package/json-schema/feature.json +0 -394
  117. package/json-schema/segment.json +0 -137
  118. package/src/assess-distribution/index.ts +0 -223
  119. package/src/benchmark/index.ts +0 -236
  120. package/src/builder/allocator.spec.ts +0 -105
  121. package/src/builder/allocator.ts +0 -45
  122. package/src/builder/applyContextToConditions.spec.ts +0 -2677
  123. package/src/builder/applyContextToConditions.ts +0 -139
  124. package/src/builder/applyContextToDatafile.spec.ts +0 -2626
  125. package/src/builder/applyContextToDatafile.ts +0 -229
  126. package/src/builder/applyContextToSegments.spec.ts +0 -1593
  127. package/src/builder/applyContextToSegments.ts +0 -165
  128. package/src/builder/buildDatafile.spec.ts +0 -445
  129. package/src/builder/buildDatafile.ts +0 -656
  130. package/src/builder/buildProject.ts +0 -344
  131. package/src/builder/buildRuntimeDatafiles.ts +0 -57
  132. package/src/builder/getFeatureRanges.ts +0 -61
  133. package/src/builder/hashes.ts +0 -109
  134. package/src/builder/index.ts +0 -2
  135. package/src/builder/mutateVariables.spec.ts +0 -1179
  136. package/src/builder/mutateVariables.ts +0 -112
  137. package/src/builder/mutator.spec.ts +0 -413
  138. package/src/builder/mutator.ts +0 -237
  139. package/src/builder/revision.spec.ts +0 -22
  140. package/src/builder/revision.ts +0 -22
  141. package/src/builder/traffic.spec.ts +0 -946
  142. package/src/builder/traffic.ts +0 -192
  143. package/src/cli/cli.ts +0 -105
  144. package/src/cli/index.ts +0 -2
  145. package/src/cli/plugins.ts +0 -43
  146. package/src/config/index.ts +0 -1
  147. package/src/config/projectConfig.spec.ts +0 -194
  148. package/src/config/projectConfig.ts +0 -280
  149. package/src/datasource/adapter.ts +0 -56
  150. package/src/datasource/datasource.ts +0 -305
  151. package/src/datasource/filesystemAdapter.spec.ts +0 -212
  152. package/src/datasource/filesystemAdapter.ts +0 -497
  153. package/src/datasource/index.ts +0 -3
  154. package/src/dependencies.ts +0 -13
  155. package/src/evaluate/index.ts +0 -243
  156. package/src/find-duplicate-segments/findDuplicateSegments.ts +0 -76
  157. package/src/find-duplicate-segments/index.ts +0 -74
  158. package/src/find-usage/index.ts +0 -565
  159. package/src/generate-code/index.ts +0 -106
  160. package/src/generate-code/typescript.spec.ts +0 -214
  161. package/src/generate-code/typescript.ts +0 -608
  162. package/src/index.ts +0 -20
  163. package/src/info/index.ts +0 -129
  164. package/src/init/index.ts +0 -65
  165. package/src/linter/attributeSchema.spec.ts +0 -342
  166. package/src/linter/attributeSchema.ts +0 -626
  167. package/src/linter/checkCircularDependency.ts +0 -45
  168. package/src/linter/checkPercentageExceedingSlot.ts +0 -61
  169. package/src/linter/conditionSchema.spec.ts +0 -510
  170. package/src/linter/conditionSchema.ts +0 -713
  171. package/src/linter/featureSchema.spec.ts +0 -1985
  172. package/src/linter/featureSchema.ts +0 -1922
  173. package/src/linter/groupSchema.ts +0 -47
  174. package/src/linter/index.ts +0 -1
  175. package/src/linter/lintProject.spec.ts +0 -336
  176. package/src/linter/lintProject.ts +0 -873
  177. package/src/linter/mutationNotation.spec.ts +0 -704
  178. package/src/linter/mutationNotation.ts +0 -442
  179. package/src/linter/printError.ts +0 -68
  180. package/src/linter/schema.spec.ts +0 -690
  181. package/src/linter/schema.ts +0 -491
  182. package/src/linter/segmentSchema.spec.ts +0 -358
  183. package/src/linter/segmentSchema.ts +0 -18
  184. package/src/linter/targetSchema.spec.ts +0 -159
  185. package/src/linter/targetSchema.ts +0 -46
  186. package/src/linter/testSchema.spec.ts +0 -258
  187. package/src/linter/testSchema.ts +0 -148
  188. package/src/linter/zodHelpers.ts +0 -16
  189. package/src/list/index.spec.ts +0 -135
  190. package/src/list/index.ts +0 -660
  191. package/src/list/matrix.spec.ts +0 -49
  192. package/src/list/matrix.ts +0 -212
  193. package/src/promoter/index.spec.ts +0 -617
  194. package/src/promoter/index.ts +0 -1266
  195. package/src/sets.ts +0 -76
  196. package/src/targeting.spec.ts +0 -74
  197. package/src/targeting.ts +0 -106
  198. package/src/tester/cliFormat.ts +0 -16
  199. package/src/tester/helpers.spec.ts +0 -149
  200. package/src/tester/helpers.ts +0 -76
  201. package/src/tester/index.ts +0 -2
  202. package/src/tester/prettyDuration.ts +0 -34
  203. package/src/tester/printTestResult.ts +0 -84
  204. package/src/tester/testFeature.ts +0 -367
  205. package/src/tester/testProject.spec.ts +0 -50
  206. package/src/tester/testProject.ts +0 -311
  207. package/src/tester/testSegment.ts +0 -77
  208. package/src/utils/extractKeys.ts +0 -136
  209. package/src/utils/git.ts +0 -158
  210. package/src/utils/index.ts +0 -3
  211. package/src/utils/pretty.ts +0 -12
  212. package/tsconfig.cjs.json +0 -13
  213. package/tsconfig.typecheck.json +0 -9
@@ -1,608 +0,0 @@
1
- import * as fs from "fs";
2
- import * as path from "path";
3
-
4
- import type {
5
- Attribute,
6
- ParsedFeature,
7
- Schema,
8
- VariableSchema,
9
- VariableSchemaWithInline,
10
- } from "@featurevisor/types";
11
- import { Dependencies } from "../dependencies";
12
- import { normalizeOptionValues, resolveTargets, targetIncludesFeature } from "../targeting";
13
-
14
- export interface TypeScriptGenerationOptions {
15
- tag?: string | string[];
16
- target?: string | string[];
17
- react?: boolean;
18
- }
19
-
20
- function shouldWrapArrayItemType(typeName: string): boolean {
21
- const trimmed = typeName.trim();
22
- return trimmed.includes("|") || trimmed.includes("&");
23
- }
24
-
25
- function formatObjectKey(key: string): string {
26
- return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
27
- }
28
-
29
- function buildObjectTypeFromSchema(
30
- schema: Schema,
31
- schemasByKey: Record<string, Schema>,
32
- schemaTypeNames?: Record<string, string>,
33
- ): string {
34
- const props = schema.properties;
35
- const additional = schema.additionalProperties;
36
- const hasProps = props && typeof props === "object" && Object.keys(props).length > 0;
37
- const hasAdditional = additional && typeof additional === "object";
38
-
39
- if (hasProps && hasAdditional) {
40
- const requiredSet = new Set(schema.required || []);
41
- const propEntries = Object.entries(props as Record<string, Schema>).map(([k, v]) => {
42
- const propType = schemaToTypeScriptType(v as Schema, schemasByKey, schemaTypeNames);
43
- const optional = !requiredSet.has(k);
44
- return optional
45
- ? `${formatObjectKey(k)}?: ${propType}`
46
- : `${formatObjectKey(k)}: ${propType}`;
47
- });
48
- const propUnion = Object.entries(props as Record<string, Schema>)
49
- .map(([, v]) => schemaToTypeScriptType(v as Schema, schemasByKey, schemaTypeNames))
50
- .join(" | ");
51
- const additionalType = schemaToTypeScriptType(
52
- additional as Schema,
53
- schemasByKey,
54
- schemaTypeNames,
55
- );
56
- const indexType = [additionalType, propUnion].filter(Boolean).join(" | ");
57
- return `{ ${propEntries.join("; ")}; [key: string]: ${indexType} }`;
58
- }
59
-
60
- if (hasProps) {
61
- const requiredSet = new Set(schema.required || []);
62
- const entries = Object.entries(props as Record<string, Schema>)
63
- .map(([k, v]) => {
64
- const propType = schemaToTypeScriptType(v as Schema, schemasByKey, schemaTypeNames);
65
- const optional = !requiredSet.has(k);
66
- return optional
67
- ? `${formatObjectKey(k)}?: ${propType}`
68
- : `${formatObjectKey(k)}: ${propType}`;
69
- })
70
- .join("; ");
71
- return `{ ${entries} }`;
72
- }
73
-
74
- if (hasAdditional) {
75
- const additionalType = schemaToTypeScriptType(
76
- additional as Schema,
77
- schemasByKey,
78
- schemaTypeNames,
79
- );
80
- return `Record<string, ${additionalType}>`;
81
- }
82
-
83
- return "Record<string, unknown>";
84
- }
85
-
86
- function formatTypeImport(typeNames: string[], fromPath: string): string {
87
- if (typeNames.length === 0) {
88
- return "";
89
- }
90
-
91
- return `import type {\n${typeNames.map((name) => ` ${name},`).join("\n")}\n} from "${fromPath}";\n\n`;
92
- }
93
-
94
- /**
95
- * Resolve a schema to its full definition, following schema references (schema: key).
96
- */
97
- function resolveSchema(schema: Schema, schemasByKey: Record<string, Schema>): Schema {
98
- if (schema.schema && schemasByKey[schema.schema]) {
99
- return resolveSchema(schemasByKey[schema.schema], schemasByKey);
100
- }
101
- return schema;
102
- }
103
-
104
- /** Emit a TypeScript literal type for a primitive const value, or null if not a primitive. */
105
- function constToLiteralType(constVal: unknown): string | null {
106
- if (constVal === null || constVal === undefined) return null;
107
- if (typeof constVal === "string") return JSON.stringify(constVal);
108
- if (typeof constVal === "number") return String(constVal);
109
- if (typeof constVal === "boolean") return constVal ? "true" : "false";
110
- return null;
111
- }
112
-
113
- /** Emit a TypeScript union of literal types for an enum array (primitives only), or null. */
114
- function enumToUnionType(enumArr: unknown[]): string | null {
115
- if (enumArr.length === 0) return null;
116
- const literals: string[] = [];
117
- for (const v of enumArr) {
118
- const lit = constToLiteralType(v);
119
- if (lit === null) return null;
120
- literals.push(lit);
121
- }
122
- return literals.join(" | ");
123
- }
124
-
125
- /**
126
- * Converts a Schema (items or properties entry) to a TypeScript type string.
127
- * Handles nested object/array and resolves schema references recursively.
128
- * When schema has `oneOf`, emits a union of each branch type. When schema has primitive `const` or `enum`, emits a literal or union type.
129
- * When schemaTypeNames is provided and schema is a reference (schema: key), returns that type name instead of inlining.
130
- */
131
- function schemaToTypeScriptType(
132
- schema: Schema,
133
- schemasByKey: Record<string, Schema>,
134
- schemaTypeNames?: Record<string, string>,
135
- ): string {
136
- if (schema?.schema && schemaTypeNames?.[schema.schema]) {
137
- return schemaTypeNames[schema.schema];
138
- }
139
- const resolved = resolveSchema(schema, schemasByKey);
140
- if (resolved.oneOf && Array.isArray(resolved.oneOf) && resolved.oneOf.length > 0) {
141
- const parts = resolved.oneOf.map((branch) =>
142
- schemaToTypeScriptType(branch as Schema, schemasByKey, schemaTypeNames),
143
- );
144
- return parts.join(" | ");
145
- }
146
- const literalFromConst = resolved.const !== undefined ? constToLiteralType(resolved.const) : null;
147
- const unionFromEnum =
148
- resolved.enum && Array.isArray(resolved.enum) && resolved.enum.length > 0
149
- ? enumToUnionType(resolved.enum)
150
- : null;
151
- const type = resolved.type as string | undefined;
152
- if (!type) {
153
- return literalFromConst ?? unionFromEnum ?? "unknown";
154
- }
155
- switch (type) {
156
- case "boolean":
157
- return literalFromConst ?? unionFromEnum ?? "boolean";
158
- case "string":
159
- case "semver":
160
- return literalFromConst ?? unionFromEnum ?? "string";
161
- case "date":
162
- return literalFromConst ?? unionFromEnum ?? "Date | string";
163
- case "integer":
164
- case "double":
165
- return literalFromConst ?? unionFromEnum ?? "number";
166
- case "array":
167
- if (resolved.items) {
168
- const itemType = schemaToTypeScriptType(resolved.items, schemasByKey, schemaTypeNames);
169
- return shouldWrapArrayItemType(itemType) ? `(${itemType})[]` : `${itemType}[]`;
170
- }
171
- return "string[]";
172
- case "object": {
173
- return buildObjectTypeFromSchema(resolved, schemasByKey, schemaTypeNames);
174
- }
175
- default:
176
- return "unknown";
177
- }
178
- }
179
-
180
- /**
181
- * Resolve variable schema to the schema shape used for code gen (inline or from schema reference).
182
- */
183
- function getEffectiveVariableSchema(
184
- variableSchema: VariableSchema,
185
- schemasByKey: Record<string, Schema>,
186
- ): VariableSchemaWithInline | Schema | undefined {
187
- if ("schema" in variableSchema && variableSchema.schema) {
188
- return schemasByKey[variableSchema.schema];
189
- }
190
- return variableSchema as VariableSchemaWithInline;
191
- }
192
-
193
- function getPascalCase(str) {
194
- // Remove special characters and split the string into an array of words
195
- const words = str.replace(/[^a-zA-Z0-9]/g, " ").split(" ");
196
-
197
- // Capitalize the first letter of each word and join them together
198
- const pascalCased = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
199
-
200
- return pascalCased;
201
- }
202
-
203
- function getRelativePath(from, to) {
204
- const relativePath = path.relative(from, to);
205
-
206
- if (relativePath.startsWith("..")) {
207
- return path.join(".", relativePath);
208
- }
209
-
210
- return relativePath;
211
- }
212
-
213
- function getVariationUnionFromFeature(parsedFeature: ParsedFeature): string | null {
214
- if (!parsedFeature.variations || parsedFeature.variations.length === 0) {
215
- return null;
216
- }
217
-
218
- const values = Array.from(
219
- new Set(parsedFeature.variations.map((variation) => JSON.stringify(variation.value))),
220
- );
221
-
222
- return values.length > 0 ? values.join(" | ") : null;
223
- }
224
-
225
- function getVariableTypeForFeaturesMap(
226
- variableSchema: VariableSchema,
227
- schemasByKey: Record<string, Schema>,
228
- schemaTypeNames?: Record<string, string>,
229
- ): { typeName: string; schemaTypesUsed: string[] } {
230
- const schemaTypesUsed: string[] = [];
231
- const addSchemaUsed = (name: string) => {
232
- if (name && !schemaTypesUsed.includes(name)) {
233
- schemaTypesUsed.push(name);
234
- }
235
- };
236
-
237
- if (
238
- schemaTypeNames &&
239
- "schema" in variableSchema &&
240
- variableSchema.schema &&
241
- schemasByKey[variableSchema.schema]
242
- ) {
243
- const schemaTypeName = schemaTypeNames[variableSchema.schema];
244
- addSchemaUsed(schemaTypeName);
245
- return { typeName: schemaTypeName, schemaTypesUsed };
246
- }
247
-
248
- const effective = getEffectiveVariableSchema(variableSchema, schemasByKey);
249
- if (!effective) {
250
- return { typeName: "unknown", schemaTypesUsed };
251
- }
252
-
253
- if ("type" in effective && effective.type === "json") {
254
- return { typeName: "unknown", schemaTypesUsed };
255
- }
256
-
257
- const typeName = schemaToTypeScriptType(effective as Schema, schemasByKey, schemaTypeNames);
258
-
259
- if (schemaTypeNames) {
260
- Object.values(schemaTypeNames).forEach((name) => {
261
- if (typeName.includes(name)) {
262
- addSchemaUsed(name);
263
- }
264
- });
265
- }
266
-
267
- return { typeName, schemaTypesUsed };
268
- }
269
-
270
- /**
271
- * Generates the content of Schemas.ts: one exported type per schema key, using schema refs between schemas.
272
- */
273
- function generateSchemasFileContent(
274
- schemaKeys: string[],
275
- schemasByKey: Record<string, Schema>,
276
- ): string {
277
- const schemaTypeNames: Record<string, string> = {};
278
- for (const k of schemaKeys) {
279
- schemaTypeNames[k] = getPascalCase(k) + "Schema";
280
- }
281
- const lines: string[] = [];
282
- for (const key of schemaKeys) {
283
- const schema = schemasByKey[key];
284
- if (!schema) continue;
285
- const name = schemaTypeNames[key];
286
- const typeStr = schemaToTypeScriptType(schema, schemasByKey, schemaTypeNames);
287
- lines.push(`export type ${name} = ${typeStr};`);
288
- }
289
- return lines.join("\n") + "\n";
290
- }
291
-
292
- function generateAttributesFileContent(
293
- attributes: Array<Attribute & { key: string; typescriptType: string }>,
294
- schemaTypeNames: Record<string, string>,
295
- ): string {
296
- const schemaTypesUsed = new Set<string>();
297
-
298
- for (const attribute of attributes) {
299
- Object.values(schemaTypeNames).forEach((typeName) => {
300
- if (attribute.typescriptType.includes(typeName)) {
301
- schemaTypesUsed.add(typeName);
302
- }
303
- });
304
- }
305
-
306
- const importLine = formatTypeImport(Array.from(schemaTypesUsed).sort(), "./schemas");
307
- const lines = attributes.map((attribute) => {
308
- const typeName = `${getPascalCase(attribute.key)}Attribute`;
309
- return `export type ${typeName} = ${attribute.typescriptType};`;
310
- });
311
-
312
- return `${importLine}${lines.join("\n")}\n`;
313
- }
314
-
315
- const INDENT_NS = " ";
316
- const INDENT_NS_BODY = " ";
317
-
318
- const instanceSnippet = `
319
- import type { Featurevisor } from "@featurevisor/sdk";
320
-
321
- let _instance: Featurevisor;
322
-
323
- export function setInstance(instance: Featurevisor) {
324
- _instance = instance;
325
- }
326
-
327
- export function getInstance(): Featurevisor {
328
- return _instance as Featurevisor;
329
- }
330
- `.trimStart();
331
-
332
- export async function generateTypeScriptCodeForProject(
333
- deps: Dependencies,
334
- outputPath: string,
335
- options: TypeScriptGenerationOptions = {},
336
- ) {
337
- const { rootDirectoryPath, projectConfig, datasource } = deps;
338
- const selectedTags = normalizeOptionValues(options.tag);
339
- const shouldGenerateReact = Boolean(options.react);
340
-
341
- const unknownTag = selectedTags.find((tag) => !projectConfig.tags.includes(tag));
342
- if (unknownTag) {
343
- throw new Error(
344
- `Unknown tag "${unknownTag}". Available tags: ${projectConfig.tags.join(", ") || "none"}.`,
345
- );
346
- }
347
-
348
- const selectedTargets = await resolveTargets(datasource, options.target, {
349
- defaultToAll: false,
350
- requireTargets: false,
351
- });
352
-
353
- console.log("\nGenerating TypeScript code...\n");
354
-
355
- // Load schemas for resolving variable schema references
356
- const schemaListKeys = await datasource.listSchemas();
357
- const schemasByKey: Record<string, Schema> = {};
358
- for (const key of schemaListKeys) {
359
- try {
360
- schemasByKey[key] = await datasource.readSchema(key);
361
- } catch {
362
- // Schema file may be invalid; skip for code gen
363
- }
364
- }
365
- const schemaKeys = Object.keys(schemasByKey);
366
- const hasSchemasFile = schemaKeys.length > 0;
367
- if (hasSchemasFile) {
368
- const schemasContent = generateSchemasFileContent(schemaKeys, schemasByKey);
369
- const schemasFilePath = path.join(outputPath, "schemas.ts");
370
- fs.writeFileSync(schemasFilePath, schemasContent);
371
- console.log(
372
- `Schemas type file written at: ${getRelativePath(rootDirectoryPath, schemasFilePath)}`,
373
- );
374
- }
375
-
376
- const schemaTypeNames: Record<string, string> = {};
377
- for (const k of schemaKeys) {
378
- schemaTypeNames[k] = getPascalCase(k) + "Schema";
379
- }
380
-
381
- // instance
382
- const instanceFilePath = path.join(outputPath, "instance.ts");
383
- fs.writeFileSync(instanceFilePath, instanceSnippet);
384
- console.log(`Instance file written at: ${getRelativePath(rootDirectoryPath, instanceFilePath)}`);
385
-
386
- // attributes
387
- const attributeFiles = await datasource.listAttributes();
388
- const attributes: (Attribute & { typescriptType: string })[] = [];
389
- const attributeTypeNames: Record<string, string> = {};
390
-
391
- for (const attributeKey of attributeFiles) {
392
- const parsedAttribute = await datasource.readAttribute(attributeKey);
393
-
394
- if (parsedAttribute.archived) {
395
- continue;
396
- }
397
-
398
- const typescriptType = schemaToTypeScriptType(
399
- parsedAttribute as Schema,
400
- schemasByKey,
401
- hasSchemasFile ? schemaTypeNames : undefined,
402
- );
403
-
404
- attributes.push({
405
- ...parsedAttribute,
406
- key: attributeKey,
407
- typescriptType,
408
- });
409
- attributeTypeNames[attributeKey] = `${getPascalCase(attributeKey)}Attribute`;
410
- }
411
-
412
- const attributesFileContent = generateAttributesFileContent(
413
- attributes as Array<Attribute & { key: string; typescriptType: string }>,
414
- hasSchemasFile ? schemaTypeNames : {},
415
- );
416
- const attributesFilePath = path.join(outputPath, "attributes.ts");
417
- fs.writeFileSync(attributesFilePath, attributesFileContent);
418
- console.log(
419
- `Attributes type file written at: ${getRelativePath(rootDirectoryPath, attributesFilePath)}`,
420
- );
421
-
422
- // context
423
- const contextImport = formatTypeImport(Object.values(attributeTypeNames).sort(), "./attributes");
424
- const attributeProperties = attributes
425
- .map((attribute) => {
426
- return ` ${formatObjectKey(attribute.key)}?: ${attributeTypeNames[attribute.key]};`;
427
- })
428
- .join("\n");
429
- const contextContent = `
430
- import type { AttributeKey, AttributeValue } from "@featurevisor/sdk";
431
- ${contextImport}export interface Context {
432
- ${attributeProperties}
433
- [key: AttributeKey]: AttributeValue;
434
- }
435
- `.trimStart();
436
-
437
- const contextTypeFilePath = path.join(outputPath, "context.ts");
438
- fs.writeFileSync(contextTypeFilePath, contextContent);
439
- console.log(
440
- `Context type file written at: ${getRelativePath(rootDirectoryPath, contextTypeFilePath)}`,
441
- );
442
-
443
- // features
444
- const featureFiles = await datasource.listFeatures();
445
-
446
- const parsedFeatures: {
447
- featureKey: string;
448
- parsedFeature: ParsedFeature;
449
- }[] = [];
450
-
451
- for (const featureKey of featureFiles) {
452
- const parsedFeature = (await datasource.readFeature(featureKey)) as ParsedFeature;
453
-
454
- if (typeof parsedFeature.archived !== "undefined" && parsedFeature.archived) {
455
- continue;
456
- }
457
-
458
- const featureTags = Array.isArray(parsedFeature.tags) ? parsedFeature.tags : [];
459
- const matchesSelectedTag = selectedTags.some((tag) => featureTags.includes(tag));
460
- const matchesSelectedTarget = selectedTargets.some((target) =>
461
- targetIncludesFeature(target, featureKey, parsedFeature),
462
- );
463
- if (
464
- (selectedTags.length > 0 || selectedTargets.length > 0) &&
465
- !matchesSelectedTag &&
466
- !matchesSelectedTarget
467
- ) {
468
- continue;
469
- }
470
-
471
- parsedFeatures.push({ featureKey, parsedFeature });
472
- }
473
-
474
- const featuresTypeSchemasUsed = new Set<string>();
475
- const featureTypeEntries = parsedFeatures
476
- .map(({ featureKey, parsedFeature }) => {
477
- const featureLines: string[] = [];
478
- const variationUnion = getVariationUnionFromFeature(parsedFeature);
479
-
480
- if (variationUnion) {
481
- featureLines.push(`${INDENT_NS_BODY}variation: ${variationUnion};`);
482
- }
483
-
484
- if (parsedFeature.variablesSchema) {
485
- for (const [variableKey, variableSchema] of Object.entries(parsedFeature.variablesSchema)) {
486
- const { typeName, schemaTypesUsed } = getVariableTypeForFeaturesMap(
487
- variableSchema,
488
- schemasByKey,
489
- hasSchemasFile ? schemaTypeNames : undefined,
490
- );
491
- schemaTypesUsed.forEach((name) => featuresTypeSchemasUsed.add(name));
492
- featureLines.push(`${INDENT_NS_BODY}${formatObjectKey(variableKey)}: ${typeName};`);
493
- }
494
- }
495
-
496
- if (featureLines.length === 0) {
497
- return `${INDENT_NS}${formatObjectKey(featureKey)}: null;`;
498
- }
499
-
500
- return `${INDENT_NS}${formatObjectKey(featureKey)}: {\n${featureLines.join("\n")}\n${INDENT_NS}};`;
501
- })
502
- .join("\n");
503
-
504
- const featuresSchemasImportLine = formatTypeImport(
505
- [...featuresTypeSchemasUsed].sort(),
506
- "./schemas",
507
- );
508
-
509
- const featuresFileContent = `
510
- ${featuresSchemasImportLine}export type Features = {
511
- ${featureTypeEntries}
512
- };
513
-
514
- export type FeatureKey = keyof Features;
515
- export type VariableKey<F extends FeatureKey> = Features[F] extends Record<string, unknown>
516
- ? Extract<Exclude<keyof Features[F], "variation">, string>
517
- : never;
518
- export type VariableType<F extends FeatureKey, V extends VariableKey<F>> = Features[F] extends Record<string, unknown>
519
- ? Features[F][V]
520
- : never;
521
- export type Variation<F extends FeatureKey> = Features[F] extends { variation: infer V }
522
- ? V
523
- : never;
524
- `.trimStart();
525
- const featuresFilePath = path.join(outputPath, "features.ts");
526
- fs.writeFileSync(featuresFilePath, featuresFileContent);
527
- console.log(`Features file written at: ${getRelativePath(rootDirectoryPath, featuresFilePath)}`);
528
-
529
- const functionsFileContent = `
530
- import { FeatureKey, Variation, VariableKey, VariableType } from "./features";
531
- import { Context } from "./context";
532
- import { getInstance } from "./instance";
533
-
534
- export function isEnabled(featureKey: FeatureKey, context: Context = {}): boolean {
535
- return getInstance().isEnabled(featureKey, context);
536
- }
537
-
538
- export function getVariation<F extends FeatureKey>(
539
- featureKey: F,
540
- context: Context = {},
541
- ): Variation<F> | null {
542
- return getInstance().getVariation(featureKey, context) as Variation<F> | null;
543
- }
544
-
545
- export function getVariable<F extends FeatureKey, V extends VariableKey<F>>(
546
- featureKey: F,
547
- variableKey: V,
548
- context: Context = {},
549
- ): VariableType<F, V> | null {
550
- return getInstance().getVariable(featureKey, variableKey, context) as VariableType<F, V> | null;
551
- }
552
- `.trimStart();
553
- const functionsFilePath = path.join(outputPath, "functions.ts");
554
- fs.writeFileSync(functionsFilePath, functionsFileContent);
555
- console.log(
556
- `Functions file written at: ${getRelativePath(rootDirectoryPath, functionsFilePath)}`,
557
- );
558
-
559
- if (shouldGenerateReact) {
560
- const reactFileContent = `
561
- import {
562
- useFlag as useFlagOriginal,
563
- useVariation as useVariationOriginal,
564
- useVariable as useVariableOriginal,
565
- } from "@featurevisor/react";
566
-
567
- import type { FeatureKey, Variation, VariableKey, VariableType } from "./features";
568
- import type { Context } from "./context";
569
-
570
- export function useFlag(featureKey: FeatureKey, context: Context = {}): boolean {
571
- return useFlagOriginal(featureKey, context);
572
- }
573
-
574
- export function useVariation<F extends FeatureKey>(
575
- featureKey: F,
576
- context: Context = {},
577
- ): Variation<F> | null {
578
- return useVariationOriginal(featureKey, context) as Variation<F> | null;
579
- }
580
-
581
- export function useVariable<F extends FeatureKey, V extends VariableKey<F>>(
582
- featureKey: F,
583
- variableKey: V,
584
- context: Context = {},
585
- ): VariableType<F, V> | null {
586
- return useVariableOriginal(featureKey, variableKey, context) as VariableType<F, V> | null;
587
- }
588
- `.trimStart();
589
- const reactFilePath = path.join(outputPath, "react.ts");
590
- fs.writeFileSync(reactFilePath, reactFileContent);
591
- console.log(`React file written at: ${getRelativePath(rootDirectoryPath, reactFilePath)}`);
592
- }
593
-
594
- // index
595
- const indexContent =
596
- [
597
- `export * from "./attributes";`,
598
- `export * from "./context";`,
599
- `export * from "./instance";`,
600
- ...(hasSchemasFile ? [`export * from "./schemas";`] : []),
601
- `export * from "./features";`,
602
- `export * from "./functions";`,
603
- ...(shouldGenerateReact ? [`export * from "./react";`] : []),
604
- ].join("\n") + "\n";
605
- const indexFilePath = path.join(outputPath, "index.ts");
606
- fs.writeFileSync(indexFilePath, indexContent);
607
- console.log(`Index file written at: ${getRelativePath(rootDirectoryPath, indexFilePath)}`);
608
- }
package/src/index.ts DELETED
@@ -1,20 +0,0 @@
1
- export * from "./config";
2
- export * from "./linter";
3
- export * from "./builder";
4
- export * from "./tester";
5
- export * from "./init";
6
- export * from "./generate-code";
7
- export * from "./find-duplicate-segments";
8
- export * from "./find-usage";
9
- export * from "./dependencies";
10
- export * from "./datasource";
11
- export * from "./benchmark";
12
- export * from "./evaluate";
13
- export * from "./assess-distribution";
14
- export * from "./info";
15
- export * from "./list";
16
- export * from "./sets";
17
- export * from "./promoter";
18
- export * from "./cli";
19
-
20
- export * from "@featurevisor/parsers";