@featurevisor/core 3.0.1 → 3.2.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 (208) 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/tester/testFeature.js +17 -16
  13. package/lib/tester/testFeature.js.map +1 -1
  14. package/package.json +10 -7
  15. package/CHANGELOG.md +0 -2238
  16. package/coverage/clover.xml +0 -5456
  17. package/coverage/coverage-final.json +0 -64
  18. package/coverage/lcov-report/base.css +0 -224
  19. package/coverage/lcov-report/block-navigation.js +0 -87
  20. package/coverage/lcov-report/favicon.png +0 -0
  21. package/coverage/lcov-report/index.html +0 -371
  22. package/coverage/lcov-report/prettify.css +0 -1
  23. package/coverage/lcov-report/prettify.js +0 -2
  24. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  25. package/coverage/lcov-report/sorter.js +0 -210
  26. package/coverage/lcov-report/src/assess-distribution/index.html +0 -116
  27. package/coverage/lcov-report/src/assess-distribution/index.ts.html +0 -754
  28. package/coverage/lcov-report/src/benchmark/index.html +0 -116
  29. package/coverage/lcov-report/src/benchmark/index.ts.html +0 -793
  30. package/coverage/lcov-report/src/builder/allocator.ts.html +0 -220
  31. package/coverage/lcov-report/src/builder/applyContextToConditions.ts.html +0 -502
  32. package/coverage/lcov-report/src/builder/applyContextToDatafile.ts.html +0 -772
  33. package/coverage/lcov-report/src/builder/applyContextToSegments.ts.html +0 -580
  34. package/coverage/lcov-report/src/builder/buildDatafile.ts.html +0 -2053
  35. package/coverage/lcov-report/src/builder/buildProject.ts.html +0 -1117
  36. package/coverage/lcov-report/src/builder/buildRuntimeDatafiles.ts.html +0 -256
  37. package/coverage/lcov-report/src/builder/getFeatureRanges.ts.html +0 -268
  38. package/coverage/lcov-report/src/builder/hashes.ts.html +0 -412
  39. package/coverage/lcov-report/src/builder/index.html +0 -311
  40. package/coverage/lcov-report/src/builder/index.ts.html +0 -91
  41. package/coverage/lcov-report/src/builder/mutateVariables.ts.html +0 -421
  42. package/coverage/lcov-report/src/builder/mutator.ts.html +0 -796
  43. package/coverage/lcov-report/src/builder/revision.ts.html +0 -151
  44. package/coverage/lcov-report/src/builder/traffic.ts.html +0 -661
  45. package/coverage/lcov-report/src/cli/cli.ts.html +0 -400
  46. package/coverage/lcov-report/src/cli/index.html +0 -131
  47. package/coverage/lcov-report/src/cli/plugins.ts.html +0 -214
  48. package/coverage/lcov-report/src/config/index.html +0 -131
  49. package/coverage/lcov-report/src/config/index.ts.html +0 -88
  50. package/coverage/lcov-report/src/config/projectConfig.ts.html +0 -925
  51. package/coverage/lcov-report/src/datasource/adapter.ts.html +0 -253
  52. package/coverage/lcov-report/src/datasource/datasource.ts.html +0 -1000
  53. package/coverage/lcov-report/src/datasource/filesystemAdapter.ts.html +0 -1576
  54. package/coverage/lcov-report/src/datasource/index.html +0 -161
  55. package/coverage/lcov-report/src/datasource/index.ts.html +0 -94
  56. package/coverage/lcov-report/src/evaluate/index.html +0 -116
  57. package/coverage/lcov-report/src/evaluate/index.ts.html +0 -814
  58. package/coverage/lcov-report/src/find-duplicate-segments/findDuplicateSegments.ts.html +0 -313
  59. package/coverage/lcov-report/src/find-duplicate-segments/index.html +0 -131
  60. package/coverage/lcov-report/src/find-duplicate-segments/index.ts.html +0 -307
  61. package/coverage/lcov-report/src/find-usage/index.html +0 -116
  62. package/coverage/lcov-report/src/find-usage/index.ts.html +0 -1780
  63. package/coverage/lcov-report/src/generate-code/index.html +0 -131
  64. package/coverage/lcov-report/src/generate-code/index.ts.html +0 -403
  65. package/coverage/lcov-report/src/generate-code/typescript.ts.html +0 -1909
  66. package/coverage/lcov-report/src/index.html +0 -131
  67. package/coverage/lcov-report/src/info/index.html +0 -116
  68. package/coverage/lcov-report/src/info/index.ts.html +0 -472
  69. package/coverage/lcov-report/src/init/index.html +0 -116
  70. package/coverage/lcov-report/src/init/index.ts.html +0 -280
  71. package/coverage/lcov-report/src/linter/attributeSchema.ts.html +0 -1963
  72. package/coverage/lcov-report/src/linter/checkCircularDependency.ts.html +0 -220
  73. package/coverage/lcov-report/src/linter/checkPercentageExceedingSlot.ts.html +0 -268
  74. package/coverage/lcov-report/src/linter/conditionSchema.ts.html +0 -2224
  75. package/coverage/lcov-report/src/linter/featureSchema.ts.html +0 -5851
  76. package/coverage/lcov-report/src/linter/groupSchema.ts.html +0 -226
  77. package/coverage/lcov-report/src/linter/index.html +0 -326
  78. package/coverage/lcov-report/src/linter/index.ts.html +0 -88
  79. package/coverage/lcov-report/src/linter/lintProject.ts.html +0 -2704
  80. package/coverage/lcov-report/src/linter/mutationNotation.ts.html +0 -1411
  81. package/coverage/lcov-report/src/linter/printError.ts.html +0 -289
  82. package/coverage/lcov-report/src/linter/schema.ts.html +0 -1558
  83. package/coverage/lcov-report/src/linter/segmentSchema.ts.html +0 -139
  84. package/coverage/lcov-report/src/linter/targetSchema.ts.html +0 -223
  85. package/coverage/lcov-report/src/linter/testSchema.ts.html +0 -529
  86. package/coverage/lcov-report/src/linter/zodHelpers.ts.html +0 -133
  87. package/coverage/lcov-report/src/list/index.html +0 -131
  88. package/coverage/lcov-report/src/list/index.ts.html +0 -2065
  89. package/coverage/lcov-report/src/list/matrix.ts.html +0 -721
  90. package/coverage/lcov-report/src/promoter/index.html +0 -116
  91. package/coverage/lcov-report/src/promoter/index.ts.html +0 -3883
  92. package/coverage/lcov-report/src/sets.ts.html +0 -313
  93. package/coverage/lcov-report/src/targeting.ts.html +0 -403
  94. package/coverage/lcov-report/src/tester/cliFormat.ts.html +0 -133
  95. package/coverage/lcov-report/src/tester/helpers.ts.html +0 -313
  96. package/coverage/lcov-report/src/tester/index.html +0 -206
  97. package/coverage/lcov-report/src/tester/prettyDuration.ts.html +0 -187
  98. package/coverage/lcov-report/src/tester/printTestResult.ts.html +0 -337
  99. package/coverage/lcov-report/src/tester/testFeature.ts.html +0 -1186
  100. package/coverage/lcov-report/src/tester/testProject.ts.html +0 -1018
  101. package/coverage/lcov-report/src/tester/testSegment.ts.html +0 -316
  102. package/coverage/lcov-report/src/utils/extractKeys.ts.html +0 -493
  103. package/coverage/lcov-report/src/utils/git.ts.html +0 -559
  104. package/coverage/lcov-report/src/utils/index.html +0 -161
  105. package/coverage/lcov-report/src/utils/index.ts.html +0 -94
  106. package/coverage/lcov-report/src/utils/pretty.ts.html +0 -121
  107. package/coverage/lcov.info +0 -11615
  108. package/jest.config.js +0 -22
  109. package/json-schema/README.md +0 -5
  110. package/json-schema/attribute.json +0 -40
  111. package/json-schema/feature.json +0 -394
  112. package/json-schema/segment.json +0 -137
  113. package/src/assess-distribution/index.ts +0 -223
  114. package/src/benchmark/index.ts +0 -236
  115. package/src/builder/allocator.spec.ts +0 -105
  116. package/src/builder/allocator.ts +0 -45
  117. package/src/builder/applyContextToConditions.spec.ts +0 -2677
  118. package/src/builder/applyContextToConditions.ts +0 -139
  119. package/src/builder/applyContextToDatafile.spec.ts +0 -2626
  120. package/src/builder/applyContextToDatafile.ts +0 -229
  121. package/src/builder/applyContextToSegments.spec.ts +0 -1593
  122. package/src/builder/applyContextToSegments.ts +0 -165
  123. package/src/builder/buildDatafile.spec.ts +0 -445
  124. package/src/builder/buildDatafile.ts +0 -656
  125. package/src/builder/buildProject.ts +0 -344
  126. package/src/builder/buildRuntimeDatafiles.ts +0 -57
  127. package/src/builder/getFeatureRanges.ts +0 -61
  128. package/src/builder/hashes.ts +0 -109
  129. package/src/builder/index.ts +0 -2
  130. package/src/builder/mutateVariables.spec.ts +0 -1179
  131. package/src/builder/mutateVariables.ts +0 -112
  132. package/src/builder/mutator.spec.ts +0 -413
  133. package/src/builder/mutator.ts +0 -237
  134. package/src/builder/revision.spec.ts +0 -22
  135. package/src/builder/revision.ts +0 -22
  136. package/src/builder/traffic.spec.ts +0 -946
  137. package/src/builder/traffic.ts +0 -192
  138. package/src/cli/cli.ts +0 -105
  139. package/src/cli/index.ts +0 -2
  140. package/src/cli/plugins.ts +0 -43
  141. package/src/config/index.ts +0 -1
  142. package/src/config/projectConfig.spec.ts +0 -194
  143. package/src/config/projectConfig.ts +0 -280
  144. package/src/datasource/adapter.ts +0 -56
  145. package/src/datasource/datasource.ts +0 -305
  146. package/src/datasource/filesystemAdapter.spec.ts +0 -212
  147. package/src/datasource/filesystemAdapter.ts +0 -497
  148. package/src/datasource/index.ts +0 -3
  149. package/src/dependencies.ts +0 -13
  150. package/src/evaluate/index.ts +0 -243
  151. package/src/find-duplicate-segments/findDuplicateSegments.ts +0 -76
  152. package/src/find-duplicate-segments/index.ts +0 -74
  153. package/src/find-usage/index.ts +0 -565
  154. package/src/generate-code/index.ts +0 -106
  155. package/src/generate-code/typescript.spec.ts +0 -214
  156. package/src/generate-code/typescript.ts +0 -608
  157. package/src/index.ts +0 -20
  158. package/src/info/index.ts +0 -129
  159. package/src/init/index.ts +0 -65
  160. package/src/linter/attributeSchema.spec.ts +0 -342
  161. package/src/linter/attributeSchema.ts +0 -626
  162. package/src/linter/checkCircularDependency.ts +0 -45
  163. package/src/linter/checkPercentageExceedingSlot.ts +0 -61
  164. package/src/linter/conditionSchema.spec.ts +0 -510
  165. package/src/linter/conditionSchema.ts +0 -713
  166. package/src/linter/featureSchema.spec.ts +0 -1985
  167. package/src/linter/featureSchema.ts +0 -1922
  168. package/src/linter/groupSchema.ts +0 -47
  169. package/src/linter/index.ts +0 -1
  170. package/src/linter/lintProject.spec.ts +0 -336
  171. package/src/linter/lintProject.ts +0 -873
  172. package/src/linter/mutationNotation.spec.ts +0 -704
  173. package/src/linter/mutationNotation.ts +0 -442
  174. package/src/linter/printError.ts +0 -68
  175. package/src/linter/schema.spec.ts +0 -690
  176. package/src/linter/schema.ts +0 -491
  177. package/src/linter/segmentSchema.spec.ts +0 -358
  178. package/src/linter/segmentSchema.ts +0 -18
  179. package/src/linter/targetSchema.spec.ts +0 -159
  180. package/src/linter/targetSchema.ts +0 -46
  181. package/src/linter/testSchema.spec.ts +0 -258
  182. package/src/linter/testSchema.ts +0 -148
  183. package/src/linter/zodHelpers.ts +0 -16
  184. package/src/list/index.spec.ts +0 -135
  185. package/src/list/index.ts +0 -660
  186. package/src/list/matrix.spec.ts +0 -49
  187. package/src/list/matrix.ts +0 -212
  188. package/src/promoter/index.spec.ts +0 -617
  189. package/src/promoter/index.ts +0 -1266
  190. package/src/sets.ts +0 -76
  191. package/src/targeting.spec.ts +0 -74
  192. package/src/targeting.ts +0 -106
  193. package/src/tester/cliFormat.ts +0 -16
  194. package/src/tester/helpers.spec.ts +0 -149
  195. package/src/tester/helpers.ts +0 -76
  196. package/src/tester/index.ts +0 -2
  197. package/src/tester/prettyDuration.ts +0 -34
  198. package/src/tester/printTestResult.ts +0 -84
  199. package/src/tester/testFeature.ts +0 -367
  200. package/src/tester/testProject.spec.ts +0 -50
  201. package/src/tester/testProject.ts +0 -311
  202. package/src/tester/testSegment.ts +0 -77
  203. package/src/utils/extractKeys.ts +0 -136
  204. package/src/utils/git.ts +0 -158
  205. package/src/utils/index.ts +0 -3
  206. package/src/utils/pretty.ts +0 -12
  207. package/tsconfig.cjs.json +0 -13
  208. 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";