@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,1266 +0,0 @@
1
- import * as fs from "fs";
2
- import * as path from "path";
3
-
4
- import type {
5
- Attribute,
6
- Condition,
7
- EntityType,
8
- GroupSegment,
9
- ParsedFeature,
10
- Rule,
11
- RulesByEnvironment,
12
- Schema,
13
- Segment,
14
- Group,
15
- Target,
16
- Test,
17
- } from "@featurevisor/types";
18
-
19
- import type { ProjectConfig } from "../config";
20
- import type { Datasource } from "../datasource";
21
- import { lintProject, type LintErrorItem } from "../linter";
22
- import {
23
- CLI_COLOR_CYAN,
24
- CLI_COLOR_DIM,
25
- CLI_COLOR_GREEN,
26
- CLI_COLOR_YELLOW,
27
- CLI_FORMAT_BOLD,
28
- CLI_FORMAT_GREEN,
29
- colorize,
30
- } from "../tester/cliFormat";
31
- import { prettyDuration } from "../tester/prettyDuration";
32
- import type { Plugin } from "../cli";
33
-
34
- type ConflictPolicy = "source" | "destination" | "fail";
35
- type PromotionAuditFormat = "json" | "markdown";
36
- type EntityValue =
37
- | Attribute
38
- | Segment
39
- | ParsedFeature
40
- | Group
41
- | Record<string, unknown>
42
- | Schema
43
- | Target
44
- | Test;
45
-
46
- interface PromotionConflict {
47
- type: EntityType;
48
- key: string;
49
- path: string;
50
- source: unknown;
51
- destination: unknown;
52
- }
53
-
54
- interface EntityPlan {
55
- type: EntityType;
56
- key: string;
57
- source: EntityValue;
58
- destination?: EntityValue;
59
- merged: EntityValue;
60
- conflicts: PromotionConflict[];
61
- }
62
-
63
- export interface PromoteProjectSetsOptions {
64
- from?: string;
65
- to?: string;
66
- includeFeatures?: string | string[];
67
- excludeFeatures?: string | string[];
68
- target?: string | string[];
69
- tag?: string | string[];
70
- conflicts?: ConflictPolicy;
71
- allowEmpty?: boolean;
72
- apply?: boolean;
73
- audit?: boolean | PromotionAuditFormat;
74
- showUnchanged?: boolean;
75
- }
76
-
77
- export interface PromoteProjectSetsResult {
78
- from: string;
79
- to: string;
80
- apply: boolean;
81
- duration: number;
82
- filters: {
83
- includeFeatures: string[];
84
- excludeFeatures: string[];
85
- targets: string[];
86
- tags: string[];
87
- conflicts: ConflictPolicy;
88
- };
89
- dependencies: Record<EntityType, number>;
90
- files: {
91
- created: string[];
92
- updated: string[];
93
- unchanged: string[];
94
- };
95
- conflicts: PromotionConflict[];
96
- auditFilePath?: string;
97
- }
98
-
99
- function isPromotable(entity: { promotable?: boolean } | undefined) {
100
- return entity?.promotable !== false;
101
- }
102
-
103
- function toArray(value: string | string[] | undefined): string[] {
104
- if (typeof value === "undefined") {
105
- return [];
106
- }
107
-
108
- return Array.isArray(value) ? value : [value];
109
- }
110
-
111
- function isPlainObject(value: unknown): value is Record<string, unknown> {
112
- return typeof value === "object" && value !== null && !Array.isArray(value);
113
- }
114
-
115
- function deepEqual(left: unknown, right: unknown): boolean {
116
- return JSON.stringify(left) === JSON.stringify(right);
117
- }
118
-
119
- function deepMergeWithPolicy(
120
- destination: unknown,
121
- source: unknown,
122
- policy: ConflictPolicy,
123
- conflicts: Array<Omit<PromotionConflict, "type" | "key">>,
124
- pathSegments: string[] = [],
125
- ): unknown {
126
- if (typeof destination === "undefined") return source;
127
- if (typeof source === "undefined") return destination;
128
-
129
- const conflictPath = pathSegments.join(".") || "<root>";
130
-
131
- if (Array.isArray(destination) && Array.isArray(source)) {
132
- if (!deepEqual(destination, source)) {
133
- conflicts.push({ path: conflictPath, source, destination });
134
- }
135
-
136
- return policy === "destination" ? destination : source;
137
- }
138
-
139
- if (isPlainObject(destination) && isPlainObject(source)) {
140
- const result: Record<string, unknown> = { ...destination };
141
-
142
- for (const key of Object.keys(source)) {
143
- result[key] = deepMergeWithPolicy(result[key], source[key], policy, conflicts, [
144
- ...pathSegments,
145
- key,
146
- ]);
147
- }
148
-
149
- return result;
150
- }
151
-
152
- if (!deepEqual(destination, source)) {
153
- conflicts.push({ path: conflictPath, source, destination });
154
- }
155
-
156
- return policy === "destination" ? destination : source;
157
- }
158
-
159
- function matchesPattern(key: string, patterns: string[]) {
160
- if (patterns.length === 0) {
161
- return false;
162
- }
163
-
164
- return patterns.some((pattern) => {
165
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
166
- return new RegExp(`^${escaped}$`).test(key);
167
- });
168
- }
169
-
170
- function matchesTags(candidateTags: string[], selector: Target["tags"]): boolean {
171
- if (!selector) return true;
172
- if (Array.isArray(selector)) {
173
- return selector.some((tag) => candidateTags.includes(tag));
174
- }
175
- if ("or" in selector) {
176
- return selector.or.some((tag) => candidateTags.includes(tag));
177
- }
178
- return selector.and.every((tag) => candidateTags.includes(tag));
179
- }
180
-
181
- function matchesTarget(featureKey: string, feature: ParsedFeature, target: Target): boolean {
182
- const featureTags = feature.tags || [];
183
- if (feature.archived === true) return false;
184
- if (target.tag && !featureTags.includes(target.tag)) return false;
185
- if (target.tags && !matchesTags(featureTags, target.tags)) return false;
186
-
187
- const included = target.includeFeatures
188
- ? matchesPattern(featureKey, toArray(target.includeFeatures))
189
- : true;
190
- const excluded = target.excludeFeatures
191
- ? matchesPattern(featureKey, toArray(target.excludeFeatures))
192
- : false;
193
-
194
- return included && !excluded;
195
- }
196
-
197
- function withoutKey<T extends Record<string, unknown>>(entity: T): T {
198
- const { key: _key, ...rest } = entity; // eslint-disable-line @typescript-eslint/no-unused-vars
199
-
200
- return rest as T;
201
- }
202
-
203
- async function safeRead<T>(
204
- keys: string[],
205
- read: (key: string) => Promise<T>,
206
- ): Promise<Record<string, T>> {
207
- const entries = await Promise.all(keys.map(async (key) => [key, await read(key)] as const));
208
- return Object.fromEntries(entries);
209
- }
210
-
211
- async function readDestination<T>(
212
- key: string,
213
- read: (key: string) => Promise<T>,
214
- ): Promise<T | undefined> {
215
- try {
216
- return await read(key);
217
- } catch {
218
- return undefined;
219
- }
220
- }
221
-
222
- function formatLintPreflightErrors(set: string, errors: LintErrorItem[]) {
223
- const preview = errors
224
- .slice(0, 5)
225
- .map((error) => `${error.filePath}: ${error.message}`)
226
- .join("\n");
227
- const suffix = errors.length > 5 ? `\n...and ${errors.length - 5} more` : "";
228
-
229
- return `Set "${set}" failed preflight lint with ${errors.length} error(s).\n${preview}${suffix}`;
230
- }
231
-
232
- async function assertSetLintsClean(
233
- set: string,
234
- projectConfig: ProjectConfig,
235
- datasource: Datasource,
236
- ) {
237
- const result = await lintProject(
238
- {
239
- rootDirectoryPath: path.resolve(projectConfig.setsDirectoryPath, ".."),
240
- projectConfig,
241
- datasource,
242
- options: {},
243
- },
244
- { json: true },
245
- );
246
-
247
- if (result.hasError) {
248
- throw new Error(formatLintPreflightErrors(set, result.errors));
249
- }
250
- }
251
-
252
- function assertAllowedPromotionFlow(projectConfig: ProjectConfig, from: string, to: string) {
253
- const allowedFlows = projectConfig.promotionFlows;
254
-
255
- if (typeof allowedFlows === "undefined") {
256
- return;
257
- }
258
-
259
- const isAllowed = allowedFlows.some((flow) => flow.from === from && flow.to === to);
260
-
261
- if (isAllowed) {
262
- return;
263
- }
264
-
265
- const allowedList = allowedFlows.map((flow) => `${flow.from} -> ${flow.to}`).join(", ") || "none";
266
-
267
- throw new Error(
268
- `Promotion from "${from}" to "${to}" is not allowed by this project's configured promotionFlows.\nAllowed flows: ${allowedList}.\nChoose one of the allowed promotion paths or update featurevisor.config.js if this flow should be permitted.`,
269
- );
270
- }
271
-
272
- function collectGroupSegmentKeys(
273
- value: GroupSegment | GroupSegment[] | "*" | undefined,
274
- result: Set<string>,
275
- ) {
276
- if (!value || value === "*") return;
277
- if (typeof value === "string") {
278
- result.add(value);
279
- return;
280
- }
281
- if (Array.isArray(value)) {
282
- value.forEach((entry) => collectGroupSegmentKeys(entry, result));
283
- return;
284
- }
285
- if ("and" in value) value.and.forEach((entry) => collectGroupSegmentKeys(entry, result));
286
- if ("or" in value) value.or.forEach((entry) => collectGroupSegmentKeys(entry, result));
287
- if ("not" in value) value.not.forEach((entry) => collectGroupSegmentKeys(entry, result));
288
- }
289
-
290
- function collectConditionDependencies(
291
- value: Condition | Condition[] | "*" | undefined,
292
- segments: Set<string>,
293
- attributes: Set<string>,
294
- ) {
295
- if (!value || value === "*") return;
296
- if (typeof value === "string") {
297
- segments.add(value);
298
- return;
299
- }
300
- if (Array.isArray(value)) {
301
- value.forEach((entry) => collectConditionDependencies(entry, segments, attributes));
302
- return;
303
- }
304
- if ("attribute" in value) {
305
- attributes.add(value.attribute.split(".")[0]);
306
- return;
307
- }
308
- if ("and" in value)
309
- value.and.forEach((entry) => collectConditionDependencies(entry, segments, attributes));
310
- if ("or" in value)
311
- value.or.forEach((entry) => collectConditionDependencies(entry, segments, attributes));
312
- if ("not" in value)
313
- value.not.forEach((entry) => collectConditionDependencies(entry, segments, attributes));
314
- }
315
-
316
- function collectSchemaReferences(value: unknown, schemas: Set<string>) {
317
- if (!value || typeof value !== "object") {
318
- return;
319
- }
320
-
321
- if (Array.isArray(value)) {
322
- value.forEach((entry) => collectSchemaReferences(entry, schemas));
323
- return;
324
- }
325
-
326
- const record = value as Record<string, unknown>;
327
-
328
- if (typeof record.schema === "string") {
329
- schemas.add(record.schema);
330
- }
331
-
332
- Object.values(record).forEach((entry) => collectSchemaReferences(entry, schemas));
333
- }
334
-
335
- function collectFeatureDependencies(
336
- feature: ParsedFeature,
337
- features: Record<string, ParsedFeature>,
338
- featureKeys: Set<string>,
339
- segmentKeys: Set<string>,
340
- attributeKeys: Set<string>,
341
- schemaKeys: Set<string>,
342
- ) {
343
- if (typeof feature.bucketBy === "string") {
344
- attributeKeys.add(feature.bucketBy);
345
- } else if (Array.isArray(feature.bucketBy)) {
346
- feature.bucketBy.forEach((attributeKey) => attributeKeys.add(attributeKey));
347
- } else if (feature.bucketBy && "or" in feature.bucketBy) {
348
- feature.bucketBy.or.forEach((attributeKey) => attributeKeys.add(attributeKey));
349
- }
350
-
351
- collectSchemaReferences(feature.variablesSchema, schemaKeys);
352
-
353
- for (const required of feature.required || []) {
354
- const requiredKey = typeof required === "string" ? required : required.key;
355
- if (!featureKeys.has(requiredKey)) {
356
- featureKeys.add(requiredKey);
357
- const requiredFeature = features[requiredKey];
358
- if (requiredFeature) {
359
- collectFeatureDependencies(
360
- requiredFeature,
361
- features,
362
- featureKeys,
363
- segmentKeys,
364
- attributeKeys,
365
- schemaKeys,
366
- );
367
- }
368
- }
369
- }
370
-
371
- for (const rules of Object.values((feature.rules || {}) as any)) {
372
- const ruleEntries = Array.isArray(rules) ? rules : [rules];
373
- for (const rule of ruleEntries) {
374
- if (!isPromotable(rule)) {
375
- continue;
376
- }
377
-
378
- collectGroupSegmentKeys(rule?.segments, segmentKeys);
379
- Object.values(rule?.variableOverrides || {}).forEach((overrides: any) => {
380
- (overrides || []).forEach((override: any) => {
381
- collectGroupSegmentKeys(override.segments, segmentKeys);
382
- collectConditionDependencies(override.conditions, segmentKeys, attributeKeys);
383
- });
384
- });
385
- }
386
- }
387
-
388
- for (const force of Object.values((feature.force || {}) as any)) {
389
- const forceEntries = Array.isArray(force) ? force : [force];
390
- for (const forceEntry of forceEntries) {
391
- collectGroupSegmentKeys(forceEntry?.segments, segmentKeys);
392
- collectConditionDependencies(forceEntry?.conditions, segmentKeys, attributeKeys);
393
- }
394
- }
395
- }
396
-
397
- function mergeRuleArray(
398
- destination: Rule[] | undefined,
399
- source: Rule[] | undefined,
400
- policy: ConflictPolicy,
401
- conflicts: Array<Omit<PromotionConflict, "type" | "key">>,
402
- pathSegments: string[],
403
- ) {
404
- if (typeof source === "undefined") return destination;
405
- if (typeof destination === "undefined") return source.filter((rule) => isPromotable(rule));
406
-
407
- const mergedRuleKeys = new Set<string>();
408
- const mergedRules: Rule[] = [];
409
-
410
- for (const sourceRule of source) {
411
- if (!isPromotable(sourceRule)) {
412
- continue;
413
- }
414
-
415
- const destinationRule = destination.find((rule) => rule.key === sourceRule.key);
416
- mergedRuleKeys.add(sourceRule.key);
417
-
418
- if (destinationRule && !isPromotable(destinationRule)) {
419
- mergedRules.push(destinationRule);
420
- continue;
421
- }
422
-
423
- mergedRules.push(
424
- deepMergeWithPolicy(destinationRule, sourceRule, policy, conflicts, [
425
- ...pathSegments,
426
- sourceRule.key,
427
- ]) as Rule,
428
- );
429
- }
430
-
431
- for (const destinationRule of destination) {
432
- if (!mergedRuleKeys.has(destinationRule.key)) {
433
- mergedRules.push(destinationRule);
434
- }
435
- }
436
-
437
- return mergedRules;
438
- }
439
-
440
- function isRulesByEnvironment(value: ParsedFeature["rules"]): value is RulesByEnvironment {
441
- return isPlainObject(value) && !Array.isArray(value);
442
- }
443
-
444
- function mergeRules(
445
- destination: ParsedFeature["rules"] | undefined,
446
- source: ParsedFeature["rules"] | undefined,
447
- policy: ConflictPolicy,
448
- conflicts: Array<Omit<PromotionConflict, "type" | "key">>,
449
- ) {
450
- if (Array.isArray(source) || Array.isArray(destination)) {
451
- return mergeRuleArray(
452
- Array.isArray(destination) ? destination : undefined,
453
- Array.isArray(source) ? source : undefined,
454
- policy,
455
- conflicts,
456
- ["rules"],
457
- );
458
- }
459
-
460
- if (isRulesByEnvironment(source) || isRulesByEnvironment(destination)) {
461
- const environmentKeys = new Set([
462
- ...Object.keys((destination || {}) as RulesByEnvironment),
463
- ...Object.keys((source || {}) as RulesByEnvironment),
464
- ]);
465
- const result: RulesByEnvironment = {};
466
-
467
- for (const environment of Array.from(environmentKeys).sort()) {
468
- const merged = mergeRuleArray(
469
- (destination as RulesByEnvironment | undefined)?.[environment],
470
- (source as RulesByEnvironment | undefined)?.[environment],
471
- policy,
472
- conflicts,
473
- ["rules", environment],
474
- );
475
-
476
- if (typeof merged !== "undefined") {
477
- result[environment] = merged;
478
- }
479
- }
480
-
481
- return Object.keys(result).length > 0 ? result : undefined;
482
- }
483
-
484
- return source;
485
- }
486
-
487
- function mergeFeature(
488
- featureKey: string,
489
- destination: ParsedFeature | undefined,
490
- source: ParsedFeature,
491
- policy: ConflictPolicy,
492
- conflicts: PromotionConflict[],
493
- ): ParsedFeature {
494
- const sourceWithoutRules = { ...source, rules: undefined };
495
- const destinationWithoutRules = destination ? { ...destination, rules: undefined } : undefined;
496
- const featureConflicts: Array<Omit<PromotionConflict, "type" | "key">> = [];
497
- const mergedFeature = deepMergeWithPolicy(
498
- destinationWithoutRules,
499
- sourceWithoutRules,
500
- policy,
501
- featureConflicts,
502
- ) as ParsedFeature;
503
- const ruleConflicts: Array<Omit<PromotionConflict, "type" | "key">> = [];
504
- const mergedRules = mergeRules(destination?.rules, source.rules, policy, ruleConflicts);
505
-
506
- conflicts.push(
507
- ...featureConflicts.map((conflict) => ({
508
- type: "feature" as const,
509
- key: featureKey,
510
- ...conflict,
511
- })),
512
- ...ruleConflicts.map((conflict) => ({
513
- type: "feature" as const,
514
- key: featureKey,
515
- ...conflict,
516
- })),
517
- );
518
-
519
- return {
520
- ...mergedFeature,
521
- rules: mergedRules,
522
- };
523
- }
524
-
525
- async function getPromotionPlan(
526
- sourceDatasource: Datasource,
527
- destinationDatasource: Datasource,
528
- options: Required<
529
- Pick<
530
- PromoteProjectSetsOptions,
531
- "includeFeatures" | "excludeFeatures" | "target" | "tag" | "allowEmpty" | "conflicts"
532
- >
533
- >,
534
- ) {
535
- const includeFeatures = toArray(options.includeFeatures);
536
- const excludeFeatures = toArray(options.excludeFeatures);
537
- const targetSelectors = toArray(options.target);
538
- const tagSelectors = toArray(options.tag);
539
- const availableTags = sourceDatasource.getConfig().tags;
540
- const unknownTag = tagSelectors.find((tag) => !availableTags.includes(tag));
541
- if (unknownTag) {
542
- throw new Error(
543
- `Unknown source tag "${unknownTag}". Available tags: ${availableTags.join(", ") || "none"}.`,
544
- );
545
- }
546
- const hasNoFilters =
547
- includeFeatures.length === 0 &&
548
- excludeFeatures.length === 0 &&
549
- targetSelectors.length === 0 &&
550
- tagSelectors.length === 0;
551
-
552
- const [featureKeys, segmentKeys, attributeKeys, groupKeys, schemaKeys, targetKeys, testKeys] =
553
- await Promise.all([
554
- sourceDatasource.listFeatures(),
555
- sourceDatasource.listSegments(),
556
- sourceDatasource.listAttributes(),
557
- sourceDatasource.listGroups(),
558
- sourceDatasource.listSchemas(),
559
- sourceDatasource.listTargets(),
560
- sourceDatasource.listTests(),
561
- ]);
562
-
563
- const [features, segments, attributes, groups, schemas, targets, tests] = await Promise.all([
564
- safeRead<ParsedFeature>(featureKeys, (key) => sourceDatasource.readFeature(key)),
565
- safeRead<Segment>(segmentKeys, (key) => sourceDatasource.readSegment(key)),
566
- safeRead<Attribute>(attributeKeys, (key) => sourceDatasource.readAttribute(key)),
567
- safeRead<Group>(groupKeys, (key) => sourceDatasource.readGroup(key)),
568
- safeRead<Schema>(schemaKeys, (key) => sourceDatasource.readSchema(key)),
569
- safeRead<Target>(targetKeys, (key) => sourceDatasource.readTarget(key)),
570
- safeRead<Test>(testKeys, (key) => sourceDatasource.readTest(key)),
571
- ]);
572
-
573
- const promotedFeatureKeys = new Set<string>();
574
- const promotedSegmentKeys = new Set<string>();
575
- const promotedAttributeKeys = new Set<string>();
576
- const promotedGroupKeys = new Set<string>();
577
- const promotedSchemaKeys = new Set<string>();
578
- const promotedTargetKeys = new Set<string>();
579
-
580
- const selectedTargets: Target[] = [];
581
- for (const key of targetSelectors) {
582
- const target = targets[key];
583
- if (!target) {
584
- throw new Error(
585
- `Unknown source target "${key}". Available targets: ${targetKeys.join(", ") || "none"}.`,
586
- );
587
- }
588
- selectedTargets.push(target);
589
- promotedTargetKeys.add(key);
590
- }
591
-
592
- if (hasNoFilters) {
593
- featureKeys.forEach((key) => promotedFeatureKeys.add(key));
594
- segmentKeys.forEach((key) => promotedSegmentKeys.add(key));
595
- attributeKeys.forEach((key) => promotedAttributeKeys.add(key));
596
- groupKeys.forEach((key) => promotedGroupKeys.add(key));
597
- schemaKeys.forEach((key) => promotedSchemaKeys.add(key));
598
- targetKeys.forEach((key) => promotedTargetKeys.add(key));
599
- } else {
600
- for (const key of featureKeys) {
601
- const feature = features[key];
602
- const matchesIncludes = includeFeatures.length === 0 || matchesPattern(key, includeFeatures);
603
- const matchesExcludes = matchesPattern(key, excludeFeatures);
604
- const matchesSelectedTags =
605
- tagSelectors.length === 0 || tagSelectors.some((tag) => (feature.tags || []).includes(tag));
606
- const matchesSelectedTargets =
607
- selectedTargets.length === 0 ||
608
- selectedTargets.some((target) => matchesTarget(key, feature, target));
609
-
610
- if (matchesIncludes && !matchesExcludes && matchesSelectedTags && matchesSelectedTargets) {
611
- promotedFeatureKeys.add(key);
612
- }
613
- }
614
-
615
- if (promotedFeatureKeys.size === 0 && !options.allowEmpty) {
616
- throw new Error("No source features matched the promotion filters.");
617
- }
618
- }
619
-
620
- let previousFeatureCount = -1;
621
- while (previousFeatureCount !== promotedFeatureKeys.size) {
622
- previousFeatureCount = promotedFeatureKeys.size;
623
-
624
- for (const key of Array.from(promotedFeatureKeys)) {
625
- const feature = features[key];
626
- if (feature) {
627
- collectFeatureDependencies(
628
- feature,
629
- features,
630
- promotedFeatureKeys,
631
- promotedSegmentKeys,
632
- promotedAttributeKeys,
633
- promotedSchemaKeys,
634
- );
635
- }
636
- }
637
-
638
- for (const key of groupKeys) {
639
- const group = groups[key];
640
- const groupFeatureKeys = group.slots
641
- .map((slot) => slot.feature)
642
- .filter((featureKey): featureKey is string => typeof featureKey === "string");
643
-
644
- if (groupFeatureKeys.some((featureKey) => promotedFeatureKeys.has(featureKey))) {
645
- promotedGroupKeys.add(key);
646
- groupFeatureKeys.forEach((featureKey) => promotedFeatureKeys.add(featureKey));
647
- }
648
- }
649
- }
650
-
651
- const pendingSegments = Array.from(promotedSegmentKeys);
652
- for (let index = 0; index < pendingSegments.length; index++) {
653
- const segmentKey = pendingSegments[index];
654
- const segment = segments[segmentKey];
655
-
656
- if (!segment) continue;
657
-
658
- const beforeSize = promotedSegmentKeys.size;
659
- collectConditionDependencies(segment.conditions, promotedSegmentKeys, promotedAttributeKeys);
660
-
661
- if (promotedSegmentKeys.size > beforeSize) {
662
- pendingSegments.push(
663
- ...Array.from(promotedSegmentKeys).filter((key) => !pendingSegments.includes(key)),
664
- );
665
- }
666
- }
667
-
668
- const pendingSchemas = Array.from(promotedSchemaKeys);
669
- for (let index = 0; index < pendingSchemas.length; index++) {
670
- const schemaKey = pendingSchemas[index];
671
- const schema = schemas[schemaKey];
672
-
673
- if (!schema) continue;
674
-
675
- const beforeSize = promotedSchemaKeys.size;
676
- collectSchemaReferences(schema, promotedSchemaKeys);
677
-
678
- if (promotedSchemaKeys.size > beforeSize) {
679
- pendingSchemas.push(
680
- ...Array.from(promotedSchemaKeys).filter((key) => !pendingSchemas.includes(key)),
681
- );
682
- }
683
- }
684
-
685
- const promotedTestKeys = testKeys.filter((key) => {
686
- const test = tests[key] as any;
687
- return promotedFeatureKeys.has(test.feature) || promotedSegmentKeys.has(test.segment);
688
- });
689
-
690
- const plans: EntityPlan[] = [];
691
-
692
- async function plan<T extends EntityValue>(
693
- type: EntityType,
694
- key: string,
695
- source: T,
696
- readDestinationEntity: (key: string) => Promise<T>,
697
- merge: (destination: T | undefined, source: T, conflicts: PromotionConflict[]) => T = (
698
- destination,
699
- sourceValue,
700
- conflicts,
701
- ) => {
702
- const entityConflicts: Array<Omit<PromotionConflict, "type" | "key">> = [];
703
- const merged = deepMergeWithPolicy(
704
- destination,
705
- sourceValue,
706
- options.conflicts,
707
- entityConflicts,
708
- ) as T;
709
-
710
- conflicts.push(...entityConflicts.map((conflict) => ({ type, key, ...conflict })));
711
-
712
- return merged;
713
- },
714
- ) {
715
- const cleanedSource = withoutKey(source as any) as T;
716
- const destination = await readDestination<T>(key, readDestinationEntity);
717
- const cleanedDestination = destination ? (withoutKey(destination as any) as T) : undefined;
718
-
719
- if (cleanedDestination && (!isPromotable(cleanedSource) || !isPromotable(cleanedDestination))) {
720
- plans.push({
721
- type,
722
- key,
723
- source: cleanedSource,
724
- destination: cleanedDestination,
725
- merged: cleanedDestination,
726
- conflicts: [],
727
- });
728
-
729
- return;
730
- }
731
-
732
- const conflicts: PromotionConflict[] = [];
733
- const merged = merge(cleanedDestination, cleanedSource, conflicts);
734
-
735
- plans.push({
736
- type,
737
- key,
738
- source: cleanedSource,
739
- destination: cleanedDestination,
740
- merged,
741
- conflicts,
742
- });
743
- }
744
-
745
- for (const key of Array.from(promotedAttributeKeys).sort()) {
746
- if (attributes[key])
747
- await plan("attribute", key, attributes[key], (entryKey) =>
748
- destinationDatasource.readAttribute(entryKey),
749
- );
750
- }
751
-
752
- for (const key of Array.from(promotedSegmentKeys).sort()) {
753
- if (segments[key])
754
- await plan("segment", key, segments[key], (entryKey) =>
755
- destinationDatasource.readSegment(entryKey),
756
- );
757
- }
758
-
759
- for (const key of Array.from(promotedGroupKeys).sort()) {
760
- if (groups[key])
761
- await plan(
762
- "group",
763
- key,
764
- groups[key] as any,
765
- (entryKey) => destinationDatasource.readGroup(entryKey) as any,
766
- );
767
- }
768
-
769
- for (const key of Array.from(promotedSchemaKeys).sort()) {
770
- if (schemas[key])
771
- await plan("schema", key, schemas[key], (entryKey) =>
772
- destinationDatasource.readSchema(entryKey),
773
- );
774
- }
775
-
776
- for (const key of Array.from(promotedFeatureKeys).sort()) {
777
- if (features[key])
778
- await plan(
779
- "feature",
780
- key,
781
- features[key],
782
- (entryKey) => destinationDatasource.readFeature(entryKey),
783
- (destination, source, conflicts) =>
784
- mergeFeature(key, destination, source, options.conflicts, conflicts),
785
- );
786
- }
787
-
788
- for (const key of Array.from(promotedTargetKeys).sort()) {
789
- if (targets[key])
790
- await plan("target", key, targets[key], (entryKey) =>
791
- destinationDatasource.readTarget(entryKey),
792
- );
793
- }
794
-
795
- for (const key of promotedTestKeys.sort()) {
796
- if (tests[key])
797
- await plan("test", key, tests[key], (entryKey) => destinationDatasource.readTest(entryKey));
798
- }
799
-
800
- return plans;
801
- }
802
-
803
- async function writePlan(destinationDatasource: Datasource, plans: EntityPlan[]) {
804
- for (const plan of plans) {
805
- if (deepEqual(plan.destination, plan.merged)) {
806
- continue;
807
- }
808
-
809
- if (plan.type === "attribute")
810
- await destinationDatasource.writeAttribute(plan.key, plan.merged as Attribute);
811
- if (plan.type === "segment")
812
- await destinationDatasource.writeSegment(plan.key, plan.merged as Segment);
813
- if (plan.type === "group")
814
- await destinationDatasource.writeGroup(
815
- plan.key,
816
- plan.merged as Record<string, unknown> as any,
817
- );
818
- if (plan.type === "schema")
819
- await destinationDatasource.writeSchema(plan.key, plan.merged as Schema);
820
- if (plan.type === "target")
821
- await destinationDatasource.writeTarget(plan.key, plan.merged as Target);
822
- if (plan.type === "feature")
823
- await destinationDatasource.writeFeature(plan.key, plan.merged as ParsedFeature);
824
- if (plan.type === "test") await destinationDatasource.writeTest(plan.key, plan.merged as Test);
825
- }
826
- }
827
-
828
- function normalizeConflictPolicy(value: unknown): ConflictPolicy {
829
- if (typeof value === "undefined" || value === false) {
830
- return "source";
831
- }
832
-
833
- if (value === "source" || value === "destination" || value === "fail") {
834
- return value;
835
- }
836
-
837
- throw new Error(
838
- `Invalid --conflicts value "${String(value)}". Use source, destination, or fail.`,
839
- );
840
- }
841
-
842
- function normalizeAuditFormat(value: unknown): PromotionAuditFormat | false {
843
- if (typeof value === "undefined" || value === false || value === "false") {
844
- return false;
845
- }
846
-
847
- if (value === true || value === "true") {
848
- return "json";
849
- }
850
-
851
- if (value === "json" || value === "markdown") {
852
- return value;
853
- }
854
-
855
- throw new Error(`Invalid --audit value "${String(value)}". Use json or markdown.`);
856
- }
857
-
858
- function getTimestamp() {
859
- const date = new Date();
860
- const pad = (value: number) => (value < 10 ? `0${value}` : String(value));
861
-
862
- return [
863
- date.getUTCFullYear(),
864
- pad(date.getUTCMonth() + 1),
865
- pad(date.getUTCDate()),
866
- "T",
867
- pad(date.getUTCHours()),
868
- pad(date.getUTCMinutes()),
869
- pad(date.getUTCSeconds()),
870
- ].join("");
871
- }
872
-
873
- function getEntityFilePath(projectConfig: ProjectConfig, type: EntityType, key: string) {
874
- const directories: Record<EntityType, string> = {
875
- attribute: projectConfig.attributesDirectoryPath,
876
- segment: projectConfig.segmentsDirectoryPath,
877
- feature: projectConfig.featuresDirectoryPath,
878
- group: projectConfig.groupsDirectoryPath,
879
- schema: projectConfig.schemasDirectoryPath,
880
- target: projectConfig.targetsDirectoryPath,
881
- test: projectConfig.testsDirectoryPath,
882
- };
883
- const extension = (projectConfig.parser as any).extension || "yml";
884
- const pathSegments = key.split(projectConfig.namespaceCharacter);
885
-
886
- if (
887
- type === "test" &&
888
- pathSegments.length > 1 &&
889
- pathSegments[pathSegments.length - 1] === "spec"
890
- ) {
891
- pathSegments[pathSegments.length - 2] = `${pathSegments[pathSegments.length - 2]}.spec`;
892
- pathSegments.pop();
893
- }
894
-
895
- return path.join(directories[type], ...pathSegments) + `.${extension}`;
896
- }
897
-
898
- function formatProjectPath(projectConfig: ProjectConfig, filePath: string) {
899
- const root = path.resolve(projectConfig.setsDirectoryPath, "..");
900
- const relative = path.relative(root, filePath);
901
-
902
- return relative.startsWith("..") ? filePath : relative;
903
- }
904
-
905
- async function getPromotionAuditFilePath(
906
- projectConfig: ProjectConfig,
907
- result: PromoteProjectSetsResult,
908
- format: PromotionAuditFormat,
909
- ) {
910
- const extension = format === "markdown" ? "md" : "json";
911
- const baseFileName = `${getTimestamp()}-${result.from}-to-${result.to}`;
912
- const directoryPath = path.join(projectConfig.stateDirectoryPath, "promotions");
913
- let suffix = 0;
914
-
915
- while (true) {
916
- const fileName = `${baseFileName}${suffix === 0 ? "" : `-${suffix}`}.${extension}`;
917
- const filePath = path.join(directoryPath, fileName);
918
-
919
- if (!fs.existsSync(filePath)) {
920
- return filePath;
921
- }
922
-
923
- suffix++;
924
- }
925
- }
926
-
927
- function getAuditPayload(result: PromoteProjectSetsResult) {
928
- return {
929
- from: result.from,
930
- to: result.to,
931
- apply: result.apply,
932
- filters: result.filters,
933
- dependencies: result.dependencies,
934
- files: result.files,
935
- conflicts: result.conflicts.map((conflict) => ({
936
- type: conflict.type,
937
- key: conflict.key,
938
- path: conflict.path,
939
- source: conflict.source,
940
- destination: conflict.destination,
941
- })),
942
- duration: result.duration,
943
- };
944
- }
945
-
946
- function stringifyMarkdownAudit(result: PromoteProjectSetsResult) {
947
- const lines = [
948
- "# Featurevisor Promotion",
949
- "",
950
- `- From: ${result.from}`,
951
- `- To: ${result.to}`,
952
- `- Mode: ${result.apply ? "apply" : "preview"}`,
953
- `- Conflicts: ${result.filters.conflicts}`,
954
- `- Duration: ${prettyDuration(result.duration)}`,
955
- "",
956
- "## Dependencies",
957
- "",
958
- `- Attributes: ${result.dependencies.attribute}`,
959
- `- Segments: ${result.dependencies.segment}`,
960
- `- Features: ${result.dependencies.feature}`,
961
- `- Groups: ${result.dependencies.group}`,
962
- `- Schemas: ${result.dependencies.schema}`,
963
- `- Targets: ${result.dependencies.target}`,
964
- `- Tests: ${result.dependencies.test}`,
965
- "",
966
- "## Files",
967
- "",
968
- ];
969
-
970
- for (const [label, files] of [
971
- ["Created", result.files.created],
972
- ["Updated", result.files.updated],
973
- ["Unchanged", result.files.unchanged],
974
- ] as const) {
975
- lines.push(`### ${label}`, "");
976
- lines.push(...(files.length > 0 ? files.map((filePath) => `- ${filePath}`) : ["- None"]));
977
- lines.push("");
978
- }
979
-
980
- if (result.conflicts.length > 0) {
981
- lines.push("## Conflicts", "");
982
- lines.push(
983
- ...result.conflicts.map(
984
- (conflict) => `- ${conflict.type} ${conflict.key} at ${conflict.path}`,
985
- ),
986
- );
987
- lines.push("");
988
- }
989
-
990
- return `${lines.join("\n")}\n`;
991
- }
992
-
993
- async function writePromotionAudit(
994
- projectConfig: ProjectConfig,
995
- result: PromoteProjectSetsResult,
996
- format: PromotionAuditFormat,
997
- ) {
998
- const filePath = await getPromotionAuditFilePath(projectConfig, result, format);
999
- await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
1000
-
1001
- const content =
1002
- format === "markdown"
1003
- ? stringifyMarkdownAudit(result)
1004
- : `${JSON.stringify(getAuditPayload(result), null, 2)}\n`;
1005
-
1006
- await fs.promises.writeFile(filePath, content);
1007
-
1008
- return formatProjectPath(projectConfig, filePath);
1009
- }
1010
-
1011
- export async function promoteProjectSets(
1012
- projectConfig: ProjectConfig,
1013
- datasource: Datasource,
1014
- options: PromoteProjectSetsOptions,
1015
- ): Promise<PromoteProjectSetsResult> {
1016
- const startTime = Date.now();
1017
- const conflictPolicy = normalizeConflictPolicy(options.conflicts);
1018
- const auditFormat = normalizeAuditFormat(options.audit);
1019
-
1020
- if (!projectConfig.sets) {
1021
- throw new Error("Promotion is only available when `sets: true` is configured.");
1022
- }
1023
- if (!options.from) throw new Error("Pass --from=<set>.");
1024
- if (!options.to) throw new Error("Pass --to=<set>.");
1025
- if (options.from === options.to) throw new Error("--from and --to must be different sets.");
1026
-
1027
- const sets = await datasource.listSets();
1028
- if (!sets.includes(options.from)) {
1029
- throw new Error(
1030
- `Unknown source set "${options.from}". Available sets: ${sets.join(", ") || "none"}.`,
1031
- );
1032
- }
1033
- if (!sets.includes(options.to)) {
1034
- throw new Error(
1035
- `Unknown destination set "${options.to}". Available sets: ${sets.join(", ") || "none"}.`,
1036
- );
1037
- }
1038
-
1039
- assertAllowedPromotionFlow(projectConfig, options.from, options.to);
1040
-
1041
- const sourceDatasource = datasource.forSet(options.from);
1042
- const destinationDatasource = datasource.forSet(options.to);
1043
-
1044
- await assertSetLintsClean(options.from, sourceDatasource.getConfig(), sourceDatasource);
1045
- await assertSetLintsClean(options.to, destinationDatasource.getConfig(), destinationDatasource);
1046
-
1047
- const plans = await getPromotionPlan(sourceDatasource, destinationDatasource, {
1048
- includeFeatures: options.includeFeatures || [],
1049
- excludeFeatures: options.excludeFeatures || [],
1050
- target: options.target || [],
1051
- tag: options.tag || [],
1052
- allowEmpty: options.allowEmpty === true,
1053
- conflicts: conflictPolicy,
1054
- });
1055
- const conflicts = plans.flatMap((plan) => plan.conflicts);
1056
-
1057
- if (conflictPolicy === "fail" && conflicts.length > 0) {
1058
- const preview = conflicts
1059
- .slice(0, 5)
1060
- .map((conflict) => `${conflict.type} "${conflict.key}" at ${conflict.path}`)
1061
- .join("\n");
1062
- const suffix = conflicts.length > 5 ? `\n...and ${conflicts.length - 5} more` : "";
1063
-
1064
- throw new Error(
1065
- `Promotion has ${conflicts.length} conflict(s) and --conflicts=fail was used.\n${preview}${suffix}`,
1066
- );
1067
- }
1068
-
1069
- if (options.apply === true) {
1070
- await writePlan(destinationDatasource, plans);
1071
- }
1072
-
1073
- const created = plans
1074
- .filter((plan) => !plan.destination)
1075
- .map((plan) =>
1076
- formatProjectPath(
1077
- projectConfig,
1078
- getEntityFilePath(destinationDatasource.getConfig(), plan.type, plan.key),
1079
- ),
1080
- );
1081
- const updated = plans
1082
- .filter((plan) => plan.destination && !deepEqual(plan.destination, plan.merged))
1083
- .map((plan) =>
1084
- formatProjectPath(
1085
- projectConfig,
1086
- getEntityFilePath(destinationDatasource.getConfig(), plan.type, plan.key),
1087
- ),
1088
- );
1089
- const unchanged = plans
1090
- .filter((plan) => plan.destination && deepEqual(plan.destination, plan.merged))
1091
- .map((plan) =>
1092
- formatProjectPath(
1093
- projectConfig,
1094
- getEntityFilePath(destinationDatasource.getConfig(), plan.type, plan.key),
1095
- ),
1096
- );
1097
-
1098
- const dependencies = {
1099
- attribute: plans.filter((plan) => plan.type === "attribute").length,
1100
- segment: plans.filter((plan) => plan.type === "segment").length,
1101
- feature: plans.filter((plan) => plan.type === "feature").length,
1102
- group: plans.filter((plan) => plan.type === "group").length,
1103
- schema: plans.filter((plan) => plan.type === "schema").length,
1104
- target: plans.filter((plan) => plan.type === "target").length,
1105
- test: plans.filter((plan) => plan.type === "test").length,
1106
- };
1107
-
1108
- const result: PromoteProjectSetsResult = {
1109
- from: options.from,
1110
- to: options.to,
1111
- apply: options.apply === true,
1112
- duration: Date.now() - startTime,
1113
- filters: {
1114
- includeFeatures: toArray(options.includeFeatures),
1115
- excludeFeatures: toArray(options.excludeFeatures),
1116
- targets: toArray(options.target),
1117
- tags: toArray(options.tag),
1118
- conflicts: conflictPolicy,
1119
- },
1120
- dependencies,
1121
- files: { created, updated, unchanged },
1122
- conflicts,
1123
- };
1124
-
1125
- if (result.apply && auditFormat) {
1126
- result.auditFilePath = await writePromotionAudit(projectConfig, result, auditFormat);
1127
- }
1128
-
1129
- return result;
1130
- }
1131
-
1132
- function printFileGroup(label: string, files: string[], color: number) {
1133
- if (files.length === 0) {
1134
- return;
1135
- }
1136
-
1137
- console.log(CLI_FORMAT_BOLD, label);
1138
- for (const filePath of files) {
1139
- console.log(` ${colorize(filePath, color)}`);
1140
- }
1141
- console.log("");
1142
- }
1143
-
1144
- function printConflictPreview(conflicts: PromotionConflict[]) {
1145
- if (conflicts.length === 0) {
1146
- return;
1147
- }
1148
-
1149
- console.log(CLI_FORMAT_BOLD, "Conflicts");
1150
- for (const conflict of conflicts.slice(0, 10)) {
1151
- console.log(
1152
- ` ${colorize(conflict.type, CLI_COLOR_YELLOW)} ${conflict.key} ${colorize(
1153
- conflict.path,
1154
- CLI_COLOR_DIM,
1155
- )}`,
1156
- );
1157
- }
1158
- if (conflicts.length > 10) {
1159
- console.log(` ${colorize(`...and ${conflicts.length - 10} more`, CLI_COLOR_DIM)}`);
1160
- }
1161
- console.log("");
1162
- }
1163
-
1164
- function printPromoteResult(
1165
- result: PromoteProjectSetsResult,
1166
- options: { showUnchanged?: boolean } = {},
1167
- ) {
1168
- console.log("");
1169
- console.log(CLI_FORMAT_BOLD, "Promoting Featurevisor set definitions");
1170
- console.log(` From: ${result.from}`);
1171
- console.log(` To: ${result.to}`);
1172
- console.log(` Mode: ${result.apply ? "apply" : "preview"}`);
1173
- if (result.filters.includeFeatures.length > 0) {
1174
- console.log(` Include features: ${result.filters.includeFeatures.join(", ")}`);
1175
- }
1176
- if (result.filters.excludeFeatures.length > 0) {
1177
- console.log(` Exclude features: ${result.filters.excludeFeatures.join(", ")}`);
1178
- }
1179
- if (result.filters.targets.length > 0) {
1180
- console.log(` Targets: ${result.filters.targets.join(", ")}`);
1181
- }
1182
- if (result.filters.tags.length > 0) {
1183
- console.log(` Tags: ${result.filters.tags.join(", ")}`);
1184
- }
1185
- console.log(` Conflict policy: ${result.filters.conflicts}`);
1186
- console.log("");
1187
- console.log(
1188
- ` Dependencies: ${result.dependencies.attribute} attributes, ${result.dependencies.segment} segments, ${result.dependencies.feature} features, ${result.dependencies.group} groups, ${result.dependencies.schema} schemas, ${result.dependencies.target} targets, ${result.dependencies.test} tests`,
1189
- );
1190
- console.log(` Created: ${result.files.created.length}`);
1191
- console.log(` Updated: ${result.files.updated.length}`);
1192
- console.log(` Unchanged: ${result.files.unchanged.length}`);
1193
- console.log(` Conflicts: ${result.conflicts.length}`);
1194
- console.log("");
1195
-
1196
- printFileGroup("Created", result.files.created, CLI_COLOR_GREEN);
1197
- printFileGroup("Updated", result.files.updated, CLI_COLOR_YELLOW);
1198
- if (options.showUnchanged === true) {
1199
- printFileGroup("Unchanged", result.files.unchanged, CLI_COLOR_DIM);
1200
- }
1201
- printConflictPreview(result.conflicts);
1202
-
1203
- if (result.auditFilePath) {
1204
- console.log(` Audit: ${colorize(result.auditFilePath, CLI_COLOR_CYAN)}`);
1205
- console.log("");
1206
- }
1207
-
1208
- console.log(CLI_FORMAT_GREEN, result.apply ? "Promotion applied" : "Promotion preview complete");
1209
- console.log(CLI_FORMAT_BOLD, `Time: ${prettyDuration(result.duration)}`);
1210
- }
1211
-
1212
- export const promotePlugin: Plugin = {
1213
- command: "promote",
1214
- handler: async ({ projectConfig, datasource, parsed }) => {
1215
- const result = await promoteProjectSets(projectConfig, datasource, {
1216
- from: parsed.from,
1217
- to: parsed.to,
1218
- includeFeatures: parsed.includeFeatures,
1219
- excludeFeatures: parsed.excludeFeatures,
1220
- target: parsed.target,
1221
- tag: parsed.tag,
1222
- conflicts: parsed.conflicts,
1223
- allowEmpty: parsed.allowEmpty === true || parsed.allowEmpty === "true",
1224
- apply: parsed.apply === true || parsed.apply === "true",
1225
- audit: parsed.audit,
1226
- });
1227
-
1228
- printPromoteResult(result, {
1229
- showUnchanged: parsed.showUnchanged === true || parsed.showUnchanged === "true",
1230
- });
1231
- },
1232
- examples: [
1233
- {
1234
- command: "promote --from=dev --to=staging",
1235
- description: "preview definitions that can be promoted from one set to another",
1236
- },
1237
- {
1238
- command: "promote --from=dev --to=staging --target=web",
1239
- description: "preview the target and every definition needed to build its datafile",
1240
- },
1241
- {
1242
- command: "promote --from=dev --to=staging --tag=web",
1243
- description: "preview definitions affecting features with a tag",
1244
- },
1245
- {
1246
- command: 'promote --from=dev --to=staging --includeFeatures="checkout*"',
1247
- description: "preview definitions affecting matching features",
1248
- },
1249
- {
1250
- command: "promote --from=dev --to=staging --conflicts=fail",
1251
- description: "fail instead of overwriting conflicting destination fields",
1252
- },
1253
- {
1254
- command: "promote --from=dev --to=staging --apply",
1255
- description: "apply a promotion and write destination files",
1256
- },
1257
- {
1258
- command: "promote --from=dev --to=staging --apply --audit=markdown",
1259
- description: "write a promotion audit file",
1260
- },
1261
- {
1262
- command: "promote --from=dev --to=staging --showUnchanged",
1263
- description: "preview a promotion and include unchanged entries",
1264
- },
1265
- ],
1266
- };