@featurevisor/core 3.11.0 → 4.0.1

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 (292) hide show
  1. package/README.md +20 -2
  2. package/lib/assess-distribution/index.js +9 -3
  3. package/lib/assess-distribution/index.js.map +1 -1
  4. package/lib/benchmark/index.d.ts +1 -1
  5. package/lib/benchmark/index.js +18 -11
  6. package/lib/benchmark/index.js.map +1 -1
  7. package/lib/builder/applyContextToConditions.d.ts +5 -4
  8. package/lib/builder/applyContextToConditions.js +84 -89
  9. package/lib/builder/applyContextToConditions.js.map +1 -1
  10. package/lib/builder/applyContextToDatafile.d.ts +2 -2
  11. package/lib/builder/applyContextToDatafile.js +45 -149
  12. package/lib/builder/applyContextToDatafile.js.map +1 -1
  13. package/lib/builder/applyContextToSegments.d.ts +6 -4
  14. package/lib/builder/applyContextToSegments.js +9 -98
  15. package/lib/builder/applyContextToSegments.js.map +1 -1
  16. package/lib/builder/buildDatafile.d.ts +15 -6
  17. package/lib/builder/buildDatafile.js +320 -220
  18. package/lib/builder/buildDatafile.js.map +1 -1
  19. package/lib/builder/buildProject.d.ts +2 -1
  20. package/lib/builder/buildProject.js +36 -37
  21. package/lib/builder/buildProject.js.map +1 -1
  22. package/lib/builder/buildRuntimeDatafiles.js +2 -0
  23. package/lib/builder/buildRuntimeDatafiles.js.map +1 -1
  24. package/lib/builder/environments.d.ts +3 -0
  25. package/lib/builder/environments.js +26 -0
  26. package/lib/builder/environments.js.map +1 -0
  27. package/lib/builder/hashes.d.ts +5 -5
  28. package/lib/builder/hashes.js +82 -100
  29. package/lib/builder/hashes.js.map +1 -1
  30. package/lib/builder/inflate.d.ts +7 -0
  31. package/lib/builder/inflate.js +26 -0
  32. package/lib/builder/inflate.js.map +1 -0
  33. package/lib/builder/mutateVariables.d.ts +6 -2
  34. package/lib/builder/mutateVariables.js +26 -18
  35. package/lib/builder/mutateVariables.js.map +1 -1
  36. package/lib/builder/mutationEntries.d.ts +5 -0
  37. package/lib/builder/mutationEntries.js +23 -0
  38. package/lib/builder/mutationEntries.js.map +1 -0
  39. package/lib/builder/mutator.d.ts +4 -2
  40. package/lib/builder/mutator.js +20 -209
  41. package/lib/builder/mutator.js.map +1 -1
  42. package/lib/builder/traffic.d.ts +2 -4
  43. package/lib/builder/traffic.js +48 -19
  44. package/lib/builder/traffic.js.map +1 -1
  45. package/lib/builder/variableOverrideProgram.d.ts +9 -0
  46. package/lib/builder/variableOverrideProgram.js +147 -0
  47. package/lib/builder/variableOverrideProgram.js.map +1 -0
  48. package/lib/catalog.d.ts +23 -0
  49. package/lib/catalog.js +117 -0
  50. package/lib/catalog.js.map +1 -0
  51. package/lib/cli/cli.d.ts +2 -0
  52. package/lib/cli/cli.js +38 -13
  53. package/lib/cli/cli.js.map +1 -1
  54. package/lib/cli/options.js +72 -17
  55. package/lib/cli/options.js.map +1 -1
  56. package/lib/cli/plugins.js +11 -3
  57. package/lib/cli/plugins.js.map +1 -1
  58. package/lib/cli/suggestions.d.ts +4 -0
  59. package/lib/cli/suggestions.js +61 -0
  60. package/lib/cli/suggestions.js.map +1 -0
  61. package/lib/config/allowedConditions.d.ts +9 -0
  62. package/lib/config/allowedConditions.js +44 -0
  63. package/lib/config/allowedConditions.js.map +1 -0
  64. package/lib/config/index.d.ts +1 -0
  65. package/lib/config/index.js +1 -0
  66. package/lib/config/index.js.map +1 -1
  67. package/lib/config/projectConfig.d.ts +9 -3
  68. package/lib/config/projectConfig.js +68 -11
  69. package/lib/config/projectConfig.js.map +1 -1
  70. package/lib/config/removedGroups.d.ts +5 -0
  71. package/lib/config/removedGroups.js +62 -0
  72. package/lib/config/removedGroups.js.map +1 -0
  73. package/lib/datasource/adapter.d.ts +10 -1
  74. package/lib/datasource/adapter.js.map +1 -1
  75. package/lib/datasource/attributeNamespaces.d.ts +14 -0
  76. package/lib/datasource/attributeNamespaces.js +70 -0
  77. package/lib/datasource/attributeNamespaces.js.map +1 -0
  78. package/lib/datasource/composition.d.ts +5 -0
  79. package/lib/datasource/composition.js +19 -0
  80. package/lib/datasource/composition.js.map +1 -0
  81. package/lib/datasource/conditions.d.ts +20 -0
  82. package/lib/datasource/conditions.js +113 -0
  83. package/lib/datasource/conditions.js.map +1 -0
  84. package/lib/datasource/datasource.d.ts +18 -12
  85. package/lib/datasource/datasource.js +137 -76
  86. package/lib/datasource/datasource.js.map +1 -1
  87. package/lib/datasource/dependencies.d.ts +52 -0
  88. package/lib/datasource/dependencies.js +347 -0
  89. package/lib/datasource/dependencies.js.map +1 -0
  90. package/lib/datasource/filesystemAdapter.d.ts +31 -1
  91. package/lib/datasource/filesystemAdapter.js +581 -99
  92. package/lib/datasource/filesystemAdapter.js.map +1 -1
  93. package/lib/datasource/index.d.ts +3 -0
  94. package/lib/datasource/index.js +3 -0
  95. package/lib/datasource/index.js.map +1 -1
  96. package/lib/datasource/parseError.d.ts +5 -0
  97. package/lib/datasource/parseError.js +68 -0
  98. package/lib/datasource/parseError.js.map +1 -0
  99. package/lib/datasource/testSpecs.d.ts +4 -0
  100. package/lib/datasource/testSpecs.js +40 -0
  101. package/lib/datasource/testSpecs.js.map +1 -0
  102. package/lib/diff/details.js +31 -0
  103. package/lib/diff/details.js.map +1 -1
  104. package/lib/diff/index.d.ts +1 -1
  105. package/lib/diff/index.js +11 -4
  106. package/lib/diff/index.js.map +1 -1
  107. package/lib/error.d.ts +1 -0
  108. package/lib/error.js +6 -0
  109. package/lib/error.js.map +1 -1
  110. package/lib/evaluate/explain.d.ts +15 -2
  111. package/lib/evaluate/explain.js +273 -79
  112. package/lib/evaluate/explain.js.map +1 -1
  113. package/lib/evaluate/index.js +128 -17
  114. package/lib/evaluate/index.js.map +1 -1
  115. package/lib/evaluate/probeConditions.d.ts +30 -0
  116. package/lib/evaluate/probeConditions.js +165 -0
  117. package/lib/evaluate/probeConditions.js.map +1 -0
  118. package/lib/evaluate/validateExplanation.js +175 -16
  119. package/lib/evaluate/validateExplanation.js.map +1 -1
  120. package/lib/find-duplicate-segments/findDuplicateSegments.js +20 -1
  121. package/lib/find-duplicate-segments/findDuplicateSegments.js.map +1 -1
  122. package/lib/find-usage/index.d.ts +14 -1
  123. package/lib/find-usage/index.js +359 -155
  124. package/lib/find-usage/index.js.map +1 -1
  125. package/lib/generate-code/typescript.js +156 -60
  126. package/lib/generate-code/typescript.js.map +1 -1
  127. package/lib/info/index.js +11 -5
  128. package/lib/info/index.js.map +1 -1
  129. package/lib/init/index.js +234 -28
  130. package/lib/init/index.js.map +1 -1
  131. package/lib/linter/attributeSchema.d.ts +6 -11
  132. package/lib/linter/attributeSchema.js +59 -53
  133. package/lib/linter/attributeSchema.js.map +1 -1
  134. package/lib/linter/comparisonOperators.d.ts +18 -0
  135. package/lib/linter/comparisonOperators.js +82 -0
  136. package/lib/linter/comparisonOperators.js.map +1 -0
  137. package/lib/linter/composedOverrideSchema.d.ts +5 -0
  138. package/lib/linter/composedOverrideSchema.js +243 -0
  139. package/lib/linter/composedOverrideSchema.js.map +1 -0
  140. package/lib/linter/compositionWarnings.d.ts +8 -0
  141. package/lib/linter/compositionWarnings.js +212 -0
  142. package/lib/linter/compositionWarnings.js.map +1 -0
  143. package/lib/linter/conditionKinds.d.ts +12 -0
  144. package/lib/linter/conditionKinds.js +129 -0
  145. package/lib/linter/conditionKinds.js.map +1 -0
  146. package/lib/linter/conditionSchema.d.ts +8 -2
  147. package/lib/linter/conditionSchema.js +253 -52
  148. package/lib/linter/conditionSchema.js.map +1 -1
  149. package/lib/linter/contextWarnings.d.ts +13 -0
  150. package/lib/linter/contextWarnings.js +241 -0
  151. package/lib/linter/contextWarnings.js.map +1 -0
  152. package/lib/linter/definitionReferences.d.ts +39 -0
  153. package/lib/linter/definitionReferences.js +234 -0
  154. package/lib/linter/definitionReferences.js.map +1 -0
  155. package/lib/linter/dependencyDepth.d.ts +14 -0
  156. package/lib/linter/dependencyDepth.js +106 -0
  157. package/lib/linter/dependencyDepth.js.map +1 -0
  158. package/lib/linter/diagnostics.d.ts +129 -0
  159. package/lib/linter/diagnostics.js +84 -0
  160. package/lib/linter/diagnostics.js.map +1 -0
  161. package/lib/linter/featureSchema.d.ts +191 -74
  162. package/lib/linter/featureSchema.js +415 -214
  163. package/lib/linter/featureSchema.js.map +1 -1
  164. package/lib/linter/lintProject.d.ts +4 -1
  165. package/lib/linter/lintProject.js +449 -143
  166. package/lib/linter/lintProject.js.map +1 -1
  167. package/lib/linter/mutationNotation.d.ts +7 -1
  168. package/lib/linter/mutationNotation.js +40 -20
  169. package/lib/linter/mutationNotation.js.map +1 -1
  170. package/lib/linter/mutationOrder.d.ts +6 -0
  171. package/lib/linter/mutationOrder.js +105 -0
  172. package/lib/linter/mutationOrder.js.map +1 -0
  173. package/lib/linter/mutationResultPaths.d.ts +4 -0
  174. package/lib/linter/mutationResultPaths.js +131 -0
  175. package/lib/linter/mutationResultPaths.js.map +1 -0
  176. package/lib/linter/mutationSchema.d.ts +3 -0
  177. package/lib/linter/mutationSchema.js +32 -0
  178. package/lib/linter/mutationSchema.js.map +1 -0
  179. package/lib/linter/printError.d.ts +3 -0
  180. package/lib/linter/printError.js +38 -25
  181. package/lib/linter/printError.js.map +1 -1
  182. package/lib/linter/regexSafety.d.ts +19 -0
  183. package/lib/linter/regexSafety.js +307 -0
  184. package/lib/linter/regexSafety.js.map +1 -0
  185. package/lib/linter/removedConditionFields.d.ts +10 -0
  186. package/lib/linter/removedConditionFields.js +47 -0
  187. package/lib/linter/removedConditionFields.js.map +1 -0
  188. package/lib/linter/requiredFeaturesSchema.d.ts +2 -2
  189. package/lib/linter/requiredFeaturesSchema.js +32 -28
  190. package/lib/linter/requiredFeaturesSchema.js.map +1 -1
  191. package/lib/linter/requiredVariableCost.d.ts +5 -0
  192. package/lib/linter/requiredVariableCost.js +60 -0
  193. package/lib/linter/requiredVariableCost.js.map +1 -0
  194. package/lib/linter/requiredVariablesSchema.d.ts +13 -0
  195. package/lib/linter/requiredVariablesSchema.js +498 -0
  196. package/lib/linter/requiredVariablesSchema.js.map +1 -0
  197. package/lib/linter/reservedNames.d.ts +12 -0
  198. package/lib/linter/reservedNames.js +52 -0
  199. package/lib/linter/reservedNames.js.map +1 -0
  200. package/lib/linter/schema.d.ts +12 -15
  201. package/lib/linter/schema.js +108 -26
  202. package/lib/linter/schema.js.map +1 -1
  203. package/lib/linter/schemaFormats.d.ts +35 -0
  204. package/lib/linter/schemaFormats.js +66 -0
  205. package/lib/linter/schemaFormats.js.map +1 -0
  206. package/lib/linter/segmentSchema.d.ts +11 -1
  207. package/lib/linter/segmentSchema.js +12 -2
  208. package/lib/linter/segmentSchema.js.map +1 -1
  209. package/lib/linter/testSchema.d.ts +394 -2
  210. package/lib/linter/testSchema.js +565 -34
  211. package/lib/linter/testSchema.js.map +1 -1
  212. package/lib/linter/variableSchema.d.ts +60 -43
  213. package/lib/linter/variableSchema.js +459 -60
  214. package/lib/linter/variableSchema.js.map +1 -1
  215. package/lib/linter/zodHelpers.d.ts +8 -1
  216. package/lib/linter/zodHelpers.js +9 -1
  217. package/lib/linter/zodHelpers.js.map +1 -1
  218. package/lib/list/index.js +384 -66
  219. package/lib/list/index.js.map +1 -1
  220. package/lib/list/matrix.d.ts +2 -2
  221. package/lib/list/matrix.js +60 -39
  222. package/lib/list/matrix.js.map +1 -1
  223. package/lib/list/scenarios.d.ts +8 -0
  224. package/lib/list/scenarios.js +84 -0
  225. package/lib/list/scenarios.js.map +1 -0
  226. package/lib/promoter/index.d.ts +1 -1
  227. package/lib/promoter/index.js +469 -210
  228. package/lib/promoter/index.js.map +1 -1
  229. package/lib/sets.js +14 -5
  230. package/lib/sets.js.map +1 -1
  231. package/lib/tester/checks.d.ts +12 -0
  232. package/lib/tester/checks.js +418 -0
  233. package/lib/tester/checks.js.map +1 -0
  234. package/lib/tester/coverage.d.ts +16 -0
  235. package/lib/tester/coverage.js +64 -0
  236. package/lib/tester/coverage.js.map +1 -0
  237. package/lib/tester/datafileKey.d.ts +4 -0
  238. package/lib/tester/datafileKey.js +18 -0
  239. package/lib/tester/datafileKey.js.map +1 -0
  240. package/lib/tester/diagnostics.d.ts +5 -0
  241. package/lib/tester/diagnostics.js +32 -0
  242. package/lib/tester/diagnostics.js.map +1 -0
  243. package/lib/tester/index.d.ts +2 -0
  244. package/lib/tester/printTestResult.d.ts +3 -2
  245. package/lib/tester/printTestResult.js +53 -8
  246. package/lib/tester/printTestResult.js.map +1 -1
  247. package/lib/tester/provenance.d.ts +21 -0
  248. package/lib/tester/provenance.js +98 -0
  249. package/lib/tester/provenance.js.map +1 -0
  250. package/lib/tester/report.d.ts +78 -0
  251. package/lib/tester/report.js +246 -0
  252. package/lib/tester/report.js.map +1 -0
  253. package/lib/tester/segments.d.ts +23 -0
  254. package/lib/tester/segments.js +103 -0
  255. package/lib/tester/segments.js.map +1 -0
  256. package/lib/tester/testFeature.d.ts +2 -0
  257. package/lib/tester/testFeature.js +17 -8
  258. package/lib/tester/testFeature.js.map +1 -1
  259. package/lib/tester/testProject.d.ts +15 -3
  260. package/lib/tester/testProject.js +198 -83
  261. package/lib/tester/testProject.js.map +1 -1
  262. package/lib/tester/testSegment.d.ts +2 -4
  263. package/lib/tester/testSegment.js +89 -7
  264. package/lib/tester/testSegment.js.map +1 -1
  265. package/lib/tester/testVariable.d.ts +2 -2
  266. package/lib/tester/testVariable.js +195 -24
  267. package/lib/tester/testVariable.js.map +1 -1
  268. package/lib/utils/conditionReferences.d.ts +5 -0
  269. package/lib/utils/conditionReferences.js +30 -0
  270. package/lib/utils/conditionReferences.js.map +1 -0
  271. package/lib/utils/extractKeys.d.ts +7 -3
  272. package/lib/utils/extractKeys.js +32 -113
  273. package/lib/utils/extractKeys.js.map +1 -1
  274. package/lib/utils/git.d.ts +7 -2
  275. package/lib/utils/git.js +87 -72
  276. package/lib/utils/git.js.map +1 -1
  277. package/package.json +11 -8
  278. package/lib/builder/getFeatureRanges.d.ts +0 -11
  279. package/lib/builder/getFeatureRanges.js +0 -70
  280. package/lib/builder/getFeatureRanges.js.map +0 -1
  281. package/lib/datasource/requiredFeatures.d.ts +0 -14
  282. package/lib/datasource/requiredFeatures.js +0 -75
  283. package/lib/datasource/requiredFeatures.js.map +0 -1
  284. package/lib/linter/checkCircularDependency.d.ts +0 -3
  285. package/lib/linter/checkCircularDependency.js +0 -8
  286. package/lib/linter/checkCircularDependency.js.map +0 -1
  287. package/lib/linter/checkPercentageExceedingSlot.d.ts +0 -3
  288. package/lib/linter/checkPercentageExceedingSlot.js +0 -45
  289. package/lib/linter/checkPercentageExceedingSlot.js.map +0 -1
  290. package/lib/linter/groupSchema.d.ts +0 -11
  291. package/lib/linter/groupSchema.js +0 -31
  292. package/lib/linter/groupSchema.js.map +0 -1
@@ -37,11 +37,16 @@ exports.promotePlugin = void 0;
37
37
  exports.promoteProjectSets = promoteProjectSets;
38
38
  const fs = __importStar(require("fs"));
39
39
  const path = __importStar(require("path"));
40
+ const datasource_1 = require("../datasource");
40
41
  const linter_1 = require("../linter");
41
42
  const cliFormat_1 = require("../tester/cliFormat");
42
43
  const prettyDuration_1 = require("../tester/prettyDuration");
44
+ const checks_1 = require("../tester/checks");
45
+ const matrix_1 = require("../list/matrix");
43
46
  const schemaReferences_1 = require("../utils/schemaReferences");
44
- const requiredFeatures_1 = require("../datasource/requiredFeatures");
47
+ const testSpecs_1 = require("../datasource/testSpecs");
48
+ const conditionReferences_1 = require("../utils/conditionReferences");
49
+ const dependencies_1 = require("../datasource/dependencies");
45
50
  function isPromotable(entity) {
46
51
  return entity?.promotable !== false;
47
52
  }
@@ -57,12 +62,18 @@ function isPlainObject(value) {
57
62
  function deepEqual(left, right) {
58
63
  return JSON.stringify(left) === JSON.stringify(right);
59
64
  }
60
- function deepMergeWithPolicy(destination, source, policy, conflicts, pathSegments = []) {
65
+ function deepMergeWithPolicy(destination, source, policy, conflicts, pathSegments = [], selectorFields = true, conditionExpression = false) {
61
66
  if (typeof destination === "undefined")
62
67
  return source;
63
68
  if (typeof source === "undefined")
64
69
  return destination;
65
70
  const conflictPath = pathSegments.join(".") || "<root>";
71
+ // A selector is a complete boolean expression, never a partial object patch.
72
+ if (conditionExpression) {
73
+ if (!deepEqual(destination, source))
74
+ conflicts.push({ path: conflictPath, source, destination });
75
+ return policy === "destination" ? destination : source;
76
+ }
66
77
  if (Array.isArray(destination) && Array.isArray(source)) {
67
78
  if (!deepEqual(destination, source)) {
68
79
  conflicts.push({ path: conflictPath, source, destination });
@@ -72,10 +83,20 @@ function deepMergeWithPolicy(destination, source, policy, conflicts, pathSegment
72
83
  if (isPlainObject(destination) && isPlainObject(source)) {
73
84
  const result = { ...destination };
74
85
  for (const key of Object.keys(source)) {
75
- result[key] = deepMergeWithPolicy(result[key], source[key], policy, conflicts, [
76
- ...pathSegments,
77
- key,
78
- ]);
86
+ result[key] = deepMergeWithPolicy(result[key], source[key], policy, conflicts, [...pathSegments, key], selectorFields &&
87
+ ![
88
+ "value",
89
+ "defaultValue",
90
+ "disabledValue",
91
+ "mutate",
92
+ "variables",
93
+ "variablesSchema",
94
+ "compose",
95
+ "properties",
96
+ "items",
97
+ "enum",
98
+ "const",
99
+ ].includes(key), selectorFields && key === "conditions");
79
100
  }
80
101
  return result;
81
102
  }
@@ -84,6 +105,29 @@ function deepMergeWithPolicy(destination, source, policy, conflicts, pathSegment
84
105
  }
85
106
  return policy === "destination" ? destination : source;
86
107
  }
108
+ /** Switching an override's form replaces that form, rather than combining selectors or actions. */
109
+ function mergeOverrideBody(destination, source, policy, conflicts, pathSegments) {
110
+ if (!isPlainObject(destination) || !isPlainObject(source))
111
+ return deepMergeWithPolicy(destination, source, policy, conflicts, pathSegments);
112
+ const from = { ...source };
113
+ const to = { ...destination };
114
+ for (const names of [["value", "mutate"]]) {
115
+ const sourceField = names.find((name) => from[name] !== undefined);
116
+ const destinationField = names.find((name) => to[name] !== undefined);
117
+ if (sourceField && destinationField && sourceField !== destinationField) {
118
+ conflicts.push({
119
+ path: [...pathSegments, sourceField].join("."),
120
+ source: { [sourceField]: from[sourceField] },
121
+ destination: { [destinationField]: to[destinationField] },
122
+ });
123
+ if (policy === "destination")
124
+ delete from[sourceField];
125
+ else
126
+ delete to[destinationField];
127
+ }
128
+ }
129
+ return deepMergeWithPolicy(to, from, policy, conflicts, pathSegments);
130
+ }
87
131
  function matchesPattern(key, patterns) {
88
132
  if (patterns.length === 0) {
89
133
  return false;
@@ -165,7 +209,7 @@ function mergeVariableOverrideArray(destination, source, policy, conflicts, vari
165
209
  const sourceWithoutOverrides = { ...sourceOverride, overrides: undefined };
166
210
  const destinationWithoutOverrides = index === -1 ? undefined : { ...result[index], overrides: undefined };
167
211
  const localConflicts = [];
168
- const merged = deepMergeWithPolicy(destinationWithoutOverrides, sourceWithoutOverrides, policy, localConflicts, [...pathSegments, sourceOverride.key]);
212
+ const merged = mergeOverrideBody(destinationWithoutOverrides, sourceWithoutOverrides, policy, localConflicts, [...pathSegments, sourceOverride.key]);
169
213
  merged.overrides = mergeVariableOverrideArray(index === -1 ? undefined : result[index].overrides, sourceOverride.overrides, policy, conflicts, variableKey, [...pathSegments, sourceOverride.key, "overrides"]);
170
214
  conflicts.push(...localConflicts.map((conflict) => ({
171
215
  type: "variable",
@@ -177,6 +221,34 @@ function mergeVariableOverrideArray(destination, source, policy, conflicts, vari
177
221
  else
178
222
  result[index] = merged;
179
223
  }
224
+ const movable = source.filter((entry) => isPromotable(entry) && isPromotable(destination?.find((item) => item.key === entry.key)));
225
+ const movableKeys = new Set(movable.map((entry) => entry.key));
226
+ const previousOrder = (destination || [])
227
+ .filter((entry) => movableKeys.has(entry.key))
228
+ .map((entry) => entry.key);
229
+ const sourceOrder = movable
230
+ .filter((entry) => destination?.some((item) => item.key === entry.key))
231
+ .map((entry) => entry.key);
232
+ if (!deepEqual(previousOrder, sourceOrder)) {
233
+ conflicts.push({
234
+ type: "variable",
235
+ key: variableKey,
236
+ path: [...pathSegments, "order"].join("."),
237
+ source: sourceOrder,
238
+ destination: previousOrder,
239
+ });
240
+ }
241
+ if (policy !== "destination") {
242
+ const byKey = new Map(result.map((entry) => [entry.key, entry]));
243
+ const ordered = movable.map((entry) => byKey.get(entry.key));
244
+ let index = 0;
245
+ // Protected and destination only entries keep their positions. The remaining
246
+ // slots follow source order, including newly introduced overrides.
247
+ for (let position = 0; position < result.length; position++) {
248
+ if (movableKeys.has(result[position].key))
249
+ result[position] = ordered[index++];
250
+ }
251
+ }
180
252
  return result;
181
253
  }
182
254
  function mergeVariable(key, destination, source, policy, conflicts) {
@@ -184,8 +256,31 @@ function mergeVariable(key, destination, source, policy, conflicts) {
184
256
  const destinationWithoutOverrides = destination
185
257
  ? { ...destination, overrides: undefined }
186
258
  : undefined;
259
+ if (source.compose !== undefined) {
260
+ sourceWithoutOverrides.compose = undefined;
261
+ if (destinationWithoutOverrides)
262
+ destinationWithoutOverrides.compose = undefined;
263
+ }
187
264
  const localConflicts = [];
188
265
  const merged = deepMergeWithPolicy(destinationWithoutOverrides, sourceWithoutOverrides, policy, localConflicts);
266
+ if (typeof source.compose === "string") {
267
+ merged.compose = deepMergeWithPolicy(destination?.compose, source.compose, policy, localConflicts, ["compose"]);
268
+ }
269
+ else if (source.compose !== undefined) {
270
+ const compose = { ...(typeof destination?.compose === "object" ? destination.compose : {}) };
271
+ for (const [alias, reference] of Object.entries(source.compose)) {
272
+ if (compose[alias] !== undefined && !deepEqual(compose[alias], reference)) {
273
+ localConflicts.push({
274
+ path: `compose.${alias}`,
275
+ source: reference,
276
+ destination: compose[alias],
277
+ });
278
+ }
279
+ if (compose[alias] === undefined || policy !== "destination")
280
+ compose[alias] = reference;
281
+ }
282
+ merged.compose = compose;
283
+ }
189
284
  conflicts.push(...localConflicts.map((conflict) => ({ type: "variable", key, ...conflict })));
190
285
  if (Array.isArray(source.overrides) || Array.isArray(destination?.overrides)) {
191
286
  merged.overrides = mergeVariableOverrideArray(Array.isArray(destination?.overrides) ? destination.overrides : undefined, Array.isArray(source.overrides) ? source.overrides : undefined, policy, conflicts, key);
@@ -239,6 +334,47 @@ async function assertSetLintsClean(set, projectConfig, datasource) {
239
334
  throw new Error(formatLintPreflightErrors(set, result.errors));
240
335
  }
241
336
  }
337
+ async function assertPromotionLintsClean(set, destination, plans) {
338
+ const config = destination.getConfig();
339
+ const OriginalAdapter = config.adapter;
340
+ const definitions = plans.map((plan) => ({
341
+ ...plan,
342
+ type: plan.type === "test" || plan.type === "scenario"
343
+ ? ((0, testSpecs_1.classifyTestSpec)(plan.merged) === "scenario" ? "scenario" : "test")
344
+ : plan.type,
345
+ }));
346
+ const entries = new Map(definitions.map((plan) => [JSON.stringify([plan.type, plan.key]), plan.merged]));
347
+ const replacedSpec = (type, key) => (type === "test" || type === "scenario") &&
348
+ entries.has(JSON.stringify([type === "test" ? "scenario" : "test", key]));
349
+ class PlannedAdapter extends OriginalAdapter {
350
+ async listEntities(type) {
351
+ return [
352
+ ...new Set([
353
+ ...(await super.listEntities(type)).filter((key) => !replacedSpec(type, key)),
354
+ ...definitions.filter((plan) => plan.type === type).map((plan) => plan.key),
355
+ ]),
356
+ ].sort();
357
+ }
358
+ async entityExists(type, key) {
359
+ if (replacedSpec(type, key))
360
+ return false;
361
+ return entries.has(JSON.stringify([type, key])) || super.entityExists(type, key);
362
+ }
363
+ async readEntity(type, key) {
364
+ const id = JSON.stringify([type, key]);
365
+ if (!entries.has(id))
366
+ return super.readEntity(type, key);
367
+ // Lint what will be written, not the in memory plan. Serialize and parse
368
+ // it the way writeEntity will, so a value the parser cannot represent,
369
+ // such as undefined, is checked in its written form.
370
+ const parser = config.parser;
371
+ const filePath = this.getEntityPath?.(type, key);
372
+ return parser.parse(parser.stringify(structuredClone(entries.get(id)), filePath), filePath);
373
+ }
374
+ }
375
+ const planned = new datasource_1.Datasource({ ...config, adapter: PlannedAdapter }, destination.getRootDirectoryPath());
376
+ await assertSetLintsClean(`${set} (promotion result)`, config, planned);
377
+ }
242
378
  function assertAllowedPromotionFlow(projectConfig, from, to) {
243
379
  const allowedFlows = projectConfig.promotionFlows;
244
380
  if (typeof allowedFlows === "undefined") {
@@ -251,124 +387,51 @@ function assertAllowedPromotionFlow(projectConfig, from, to) {
251
387
  const allowedList = allowedFlows.map((flow) => `${flow.from} -> ${flow.to}`).join(", ") || "none";
252
388
  throw new Error(`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.`);
253
389
  }
254
- function collectGroupSegmentKeys(value, result) {
255
- if (!value || value === "*")
256
- return;
257
- if (typeof value === "string") {
258
- result.add(value);
259
- return;
260
- }
261
- if (Array.isArray(value)) {
262
- value.forEach((entry) => collectGroupSegmentKeys(entry, result));
263
- return;
264
- }
265
- if ("and" in value)
266
- value.and.forEach((entry) => collectGroupSegmentKeys(entry, result));
267
- if ("or" in value)
268
- value.or.forEach((entry) => collectGroupSegmentKeys(entry, result));
269
- if ("not" in value)
270
- value.not.forEach((entry) => collectGroupSegmentKeys(entry, result));
271
- }
272
390
  function collectConditionDependencies(value, segments, attributes) {
273
- if (!value || value === "*")
274
- return;
275
- if (typeof value === "string") {
276
- segments.add(value);
277
- return;
278
- }
279
- if (Array.isArray(value)) {
280
- value.forEach((entry) => collectConditionDependencies(entry, segments, attributes));
281
- return;
282
- }
283
- if ("attribute" in value) {
284
- attributes.add(value.attribute.split(".")[0]);
285
- return;
391
+ for (const leaf of (0, conditionReferences_1.conditionLeaves)(value)) {
392
+ if (typeof leaf === "string")
393
+ segments.add(leaf);
394
+ else if ("attribute" in leaf)
395
+ attributes.add(leaf.attribute.split(".")[0]);
286
396
  }
287
- if ("and" in value)
288
- value.and.forEach((entry) => collectConditionDependencies(entry, segments, attributes));
289
- if ("or" in value)
290
- value.or.forEach((entry) => collectConditionDependencies(entry, segments, attributes));
291
- if ("not" in value)
292
- value.not.forEach((entry) => collectConditionDependencies(entry, segments, attributes));
293
397
  }
294
- function collectFeatureDependencies(feature, features, featureKeys, segmentKeys, attributeKeys, schemaKeys) {
295
- if (typeof feature.bucketBy === "string") {
398
+ function collectFeatureDependencies(feature, _features, _featureKeys, segmentKeys, attributeKeys, schemaKeys) {
399
+ if (typeof feature.bucketBy === "string")
296
400
  attributeKeys.add(feature.bucketBy);
297
- }
298
- else if (Array.isArray(feature.bucketBy)) {
299
- feature.bucketBy.forEach((attributeKey) => attributeKeys.add(attributeKey));
300
- }
301
- else if (feature.bucketBy && "or" in feature.bucketBy) {
302
- feature.bucketBy.or.forEach((attributeKey) => attributeKeys.add(attributeKey));
303
- }
304
- Object.values(feature.variablesSchema || {}).forEach((schema) => {
305
- (0, schemaReferences_1.extractSchemaReferences)(schema).forEach((key) => schemaKeys.add(key));
306
- });
307
- for (const required of (0, requiredFeatures_1.normalizeFeatureRequirements)(feature)) {
308
- const requiredKey = (0, requiredFeatures_1.getRequiredFeatureKey)(required);
309
- if (!featureKeys.has(requiredKey)) {
310
- featureKeys.add(requiredKey);
311
- const requiredFeature = features[requiredKey];
312
- if (requiredFeature) {
313
- collectFeatureDependencies(requiredFeature, features, featureKeys, segmentKeys, attributeKeys, schemaKeys);
314
- }
315
- }
316
- }
317
- for (const rules of Object.values((feature.rules || {}))) {
318
- const ruleEntries = Array.isArray(rules) ? rules : [rules];
319
- for (const rule of ruleEntries) {
320
- if (!isPromotable(rule)) {
321
- continue;
322
- }
323
- collectGroupSegmentKeys(rule?.segments, segmentKeys);
324
- Object.values(rule?.variableOverrides || {}).forEach((overrides) => {
325
- (overrides || []).forEach((override) => {
326
- if (!isPromotable(override))
327
- return;
328
- collectGroupSegmentKeys(override.segments, segmentKeys);
329
- collectConditionDependencies(override.conditions, segmentKeys, attributeKeys);
330
- (0, requiredFeatures_1.normalizeRequiredFeatures)(override.requiredFeatures).forEach((required) => {
331
- const requiredKey = (0, requiredFeatures_1.getRequiredFeatureKey)(required);
332
- if (!featureKeys.has(requiredKey)) {
333
- featureKeys.add(requiredKey);
334
- const requiredFeature = features[requiredKey];
335
- if (requiredFeature) {
336
- collectFeatureDependencies(requiredFeature, features, featureKeys, segmentKeys, attributeKeys, schemaKeys);
337
- }
338
- }
339
- });
340
- });
341
- });
342
- }
343
- }
344
- for (const variation of feature.variations || []) {
345
- Object.values(variation.variableOverrides || {}).forEach((overrides) => {
346
- overrides.forEach((override) => {
347
- if (!isPromotable(override))
348
- return;
349
- collectGroupSegmentKeys(override.segments, segmentKeys);
350
- collectConditionDependencies(override.conditions, segmentKeys, attributeKeys);
351
- (0, requiredFeatures_1.normalizeRequiredFeatures)(override.requiredFeatures).forEach((required) => {
352
- const requiredKey = (0, requiredFeatures_1.getRequiredFeatureKey)(required);
353
- if (!featureKeys.has(requiredKey)) {
354
- featureKeys.add(requiredKey);
355
- const requiredFeature = features[requiredKey];
356
- if (requiredFeature) {
357
- collectFeatureDependencies(requiredFeature, features, featureKeys, segmentKeys, attributeKeys, schemaKeys);
358
- }
359
- }
360
- });
361
- });
362
- });
363
- }
364
- for (const force of Object.values((feature.force || {}))) {
365
- const forceEntries = Array.isArray(force) ? force : [force];
366
- for (const forceEntry of forceEntries) {
367
- collectGroupSegmentKeys(forceEntry?.segments, segmentKeys);
368
- collectConditionDependencies(forceEntry?.conditions, segmentKeys, attributeKeys);
369
- }
401
+ else if (Array.isArray(feature.bucketBy))
402
+ feature.bucketBy.forEach((key) => attributeKeys.add(key));
403
+ else
404
+ feature.bucketBy?.or.forEach((key) => attributeKeys.add(key));
405
+ Object.values(feature.variablesSchema || {}).forEach((schema) => (0, schemaReferences_1.extractSchemaReferences)(schema).forEach((key) => schemaKeys.add(key)));
406
+ for (const leaf of (0, conditionReferences_1.definitionConditionLeaves)(promotableFeature(feature))) {
407
+ if (typeof leaf === "string")
408
+ segmentKeys.add(leaf);
409
+ else if ("attribute" in leaf)
410
+ attributeKeys.add(leaf.attribute.split(".")[0]);
370
411
  }
371
412
  }
413
+ /** Protection applies before the structural graph visits rules and their overrides. */
414
+ function promotableFeature(feature) {
415
+ const overrides = (value) => value &&
416
+ Object.fromEntries(Object.entries(value).map(([key, entries]) => [key, entries.filter(isPromotable)]));
417
+ const rules = (entries) => entries.filter(isPromotable).map((rule) => ({
418
+ ...rule,
419
+ variableOverrides: overrides(rule.variableOverrides),
420
+ }));
421
+ const groups = (value, filter) => Array.isArray(value)
422
+ ? filter(value)
423
+ : value &&
424
+ Object.fromEntries(Object.entries(value).map(([key, entries]) => [key, filter(entries)]));
425
+ return {
426
+ ...feature,
427
+ rules: groups(feature.rules, rules),
428
+ force: groups(feature.force, (entries) => entries.filter(isPromotable)),
429
+ variations: feature.variations?.map((variation) => ({
430
+ ...variation,
431
+ variableOverrides: overrides(variation.variableOverrides),
432
+ })),
433
+ };
434
+ }
372
435
  function hasOverridePromotion(overrides) {
373
436
  return Object.values(overrides || {}).some((entries) => entries.some((entry) => typeof entry.promotable !== "undefined"));
374
437
  }
@@ -390,7 +453,7 @@ function mergeFeatureVariableOverrideArray(destination, source, policy, conflict
390
453
  const index = result.findIndex((entry) => entry.key === sourceOverride.key);
391
454
  if (index !== -1 && !isPromotable(result[index]))
392
455
  continue;
393
- const merged = deepMergeWithPolicy(index === -1 ? undefined : result[index], sourceOverride, policy, conflicts, [...pathSegments, sourceOverride.key]);
456
+ const merged = mergeOverrideBody(index === -1 ? undefined : result[index], sourceOverride, policy, conflicts, [...pathSegments, sourceOverride.key]);
394
457
  if (index === -1)
395
458
  result.push(merged);
396
459
  else
@@ -427,26 +490,77 @@ function mergeRuleArray(destination, source, policy, conflicts, pathSegments) {
427
490
  .filter((rule) => isPromotable(rule))
428
491
  .map((rule) => mergeRule(undefined, rule, policy, conflicts, [...pathSegments, rule.key]));
429
492
  }
430
- const mergedRuleKeys = new Set();
431
- const mergedRules = [];
493
+ // Start from the destination's order. Rules only the destination has, and
494
+ // protected destination rules, keep their slots, because the first matching
495
+ // rule decides and moving one changes who gets the feature.
496
+ const result = [...destination];
497
+ const added = new Set();
432
498
  for (const sourceRule of source) {
433
- if (!isPromotable(sourceRule)) {
499
+ if (!isPromotable(sourceRule))
434
500
  continue;
435
- }
436
- const destinationRule = destination.find((rule) => rule.key === sourceRule.key);
437
- mergedRuleKeys.add(sourceRule.key);
438
- if (destinationRule && !isPromotable(destinationRule)) {
439
- mergedRules.push(destinationRule);
501
+ const index = result.findIndex((rule) => rule.key === sourceRule.key);
502
+ if (index !== -1) {
503
+ if (!isPromotable(result[index]))
504
+ continue;
505
+ result[index] = mergeRule(result[index], sourceRule, policy, conflicts, [
506
+ ...pathSegments,
507
+ sourceRule.key,
508
+ ]);
440
509
  continue;
441
510
  }
442
- mergedRules.push(mergeRule(destinationRule, sourceRule, policy, conflicts, [...pathSegments, sourceRule.key]));
443
- }
444
- for (const destinationRule of destination) {
445
- if (!mergedRuleKeys.has(destinationRule.key)) {
446
- mergedRules.push(destinationRule);
511
+ // A new rule goes before the next source rule the result already has, so
512
+ // it keeps its place relative to the source and never lands after a
513
+ // catch all it preceded. Without one, it follows the previous such rule.
514
+ const merged = mergeRule(undefined, sourceRule, policy, conflicts, [
515
+ ...pathSegments,
516
+ sourceRule.key,
517
+ ]);
518
+ const sourceIndex = source.indexOf(sourceRule);
519
+ const next = source
520
+ .slice(sourceIndex + 1)
521
+ .find((rule) => result.some((entry) => entry.key === rule.key));
522
+ const previous = source
523
+ .slice(0, sourceIndex)
524
+ .reverse()
525
+ .find((rule) => result.some((entry) => entry.key === rule.key));
526
+ if (next) {
527
+ result.splice(result.findIndex((entry) => entry.key === next.key), 0, merged);
528
+ }
529
+ else if (previous) {
530
+ result.splice(result.findIndex((entry) => entry.key === previous.key) + 1, 0, merged);
531
+ }
532
+ else {
533
+ result.push(merged);
534
+ }
535
+ added.add(sourceRule.key);
536
+ }
537
+ // Rules both sides have, and may move, follow the conflict policy. A change
538
+ // in their relative order is a conflict, as it is for global overrides.
539
+ const movable = source.filter((rule) => !added.has(rule.key) &&
540
+ isPromotable(rule) &&
541
+ destination.some((entry) => entry.key === rule.key && isPromotable(entry)));
542
+ const movableKeys = new Set(movable.map((rule) => rule.key));
543
+ const previousOrder = destination
544
+ .filter((rule) => movableKeys.has(rule.key))
545
+ .map((rule) => rule.key);
546
+ const sourceOrder = movable.map((rule) => rule.key);
547
+ if (!deepEqual(previousOrder, sourceOrder)) {
548
+ conflicts.push({
549
+ path: [...pathSegments, "order"].join("."),
550
+ source: sourceOrder,
551
+ destination: previousOrder,
552
+ });
553
+ if (policy !== "destination") {
554
+ const byKey = new Map(result.map((rule) => [rule.key, rule]));
555
+ const ordered = sourceOrder.map((key) => byKey.get(key));
556
+ let next = 0;
557
+ for (let position = 0; position < result.length; position++) {
558
+ if (movableKeys.has(result[position].key))
559
+ result[position] = ordered[next++];
560
+ }
447
561
  }
448
562
  }
449
- return mergedRules;
563
+ return result;
450
564
  }
451
565
  function isRulesByEnvironment(value) {
452
566
  return isPlainObject(value) && !Array.isArray(value);
@@ -518,11 +632,60 @@ function mergeFeature(featureKey, destination, source, policy, conflicts) {
518
632
  key: featureKey,
519
633
  ...conflict,
520
634
  })));
521
- return {
522
- ...mergedFeature,
523
- rules: mergedRules,
524
- variations: mergedVariations,
525
- };
635
+ const result = { ...mergedFeature };
636
+ // Leave absent fields out rather than writing them as undefined
637
+ if (typeof mergedRules !== "undefined")
638
+ result.rules = mergedRules;
639
+ if (typeof mergedVariations !== "undefined")
640
+ result.variations = mergedVariations;
641
+ return result;
642
+ }
643
+ function getTestCheckReferences(test) {
644
+ if (!("variable" in test)) {
645
+ return [];
646
+ }
647
+ const owner = test.variable;
648
+ return test.assertions.flatMap((assertion) => {
649
+ const combinations = assertion.matrix ? (0, matrix_1.getMatrixCombinations)(assertion.matrix) : [{}];
650
+ return combinations.flatMap((combination) => {
651
+ const expanded = (0, matrix_1.applyCombinationToValue)(assertion, combination);
652
+ return [
653
+ ...(expanded.checks ? (0, checks_1.getCheckReferences)(expanded.checks, owner) : []),
654
+ ...(expanded.children || []).flatMap((child) => child.checks ? (0, checks_1.getCheckReferences)(child.checks, owner) : []),
655
+ ];
656
+ });
657
+ });
658
+ }
659
+ function getScenarioCheckReferences(scenario) {
660
+ const combinations = scenario.matrix ? (0, matrix_1.getMatrixCombinations)(scenario.matrix) : [{}];
661
+ return combinations.flatMap((combination) => {
662
+ const expanded = (0, matrix_1.applyCombinationToValue)(scenario, combination);
663
+ return [
664
+ ...(0, checks_1.getCheckReferences)(expanded.checks),
665
+ ...(expanded.children || []).flatMap((child) => (0, checks_1.getCheckReferences)(child.checks)),
666
+ ];
667
+ });
668
+ }
669
+ function getTestTargetReferences(test) {
670
+ return test.assertions.flatMap((assertion) => {
671
+ const combinations = assertion.matrix ? (0, matrix_1.getMatrixCombinations)(assertion.matrix) : [{}];
672
+ return combinations.flatMap((combination) => {
673
+ const expanded = (0, matrix_1.applyCombinationToValue)(assertion, combination);
674
+ return "target" in expanded && typeof expanded.target === "string" ? [expanded.target] : [];
675
+ });
676
+ });
677
+ }
678
+ function getScenarioTargetReferences(scenario) {
679
+ const combinations = scenario.matrix ? (0, matrix_1.getMatrixCombinations)(scenario.matrix) : [{}];
680
+ return combinations.flatMap((combination) => {
681
+ const expanded = (0, matrix_1.applyCombinationToValue)(scenario, combination);
682
+ return typeof expanded.target === "string" ? [expanded.target] : [];
683
+ });
684
+ }
685
+ function getSpecTargetReferences(spec) {
686
+ return (0, testSpecs_1.classifyTestSpec)(spec) === "scenario"
687
+ ? getScenarioTargetReferences(spec)
688
+ : getTestTargetReferences(spec);
526
689
  }
527
690
  function assertionsAreKeyed(assertions) {
528
691
  return (assertions.length > 0 && assertions.every((assertion) => typeof assertion.key === "string"));
@@ -599,30 +762,29 @@ async function getPromotionPlan(sourceDatasource, destinationDatasource, options
599
762
  excludeFeatures.length === 0 &&
600
763
  targetSelectors.length === 0 &&
601
764
  tagSelectors.length === 0;
602
- const [featureKeys, segmentKeys, attributeKeys, groupKeys, schemaKeys, targetKeys, variableKeys, testKeys,] = await Promise.all([
765
+ const [featureKeys, segmentKeys, attributeKeys, schemaKeys, targetKeys, variableKeys, testKeys, scenarioKeys,] = await Promise.all([
603
766
  sourceDatasource.listFeatures(),
604
767
  sourceDatasource.listSegments(),
605
768
  sourceDatasource.listAttributes(),
606
- sourceDatasource.listGroups(),
607
769
  sourceDatasource.listSchemas(),
608
770
  sourceDatasource.listTargets(),
609
771
  sourceDatasource.listVariables(),
610
772
  sourceDatasource.listTests(),
773
+ sourceDatasource.listScenarios(),
611
774
  ]);
612
- const [features, segments, attributes, groups, schemas, targets, variables, tests] = await Promise.all([
775
+ const [features, segments, attributes, schemas, targets, variables, tests, scenarios] = await Promise.all([
613
776
  safeRead(featureKeys, (key) => sourceDatasource.readFeature(key)),
614
777
  safeRead(segmentKeys, (key) => sourceDatasource.readSegment(key)),
615
778
  safeRead(attributeKeys, (key) => sourceDatasource.readAttribute(key)),
616
- safeRead(groupKeys, (key) => sourceDatasource.readGroup(key)),
617
779
  safeRead(schemaKeys, (key) => sourceDatasource.readSchema(key)),
618
780
  safeRead(targetKeys, (key) => sourceDatasource.readTarget(key)),
619
781
  safeRead(variableKeys, (key) => sourceDatasource.readVariable(key)),
620
782
  safeRead(testKeys, (key) => sourceDatasource.readTest(key)),
783
+ safeRead(scenarioKeys, (key) => sourceDatasource.readScenario(key)),
621
784
  ]);
622
785
  const promotedFeatureKeys = new Set();
623
786
  const promotedSegmentKeys = new Set();
624
787
  const promotedAttributeKeys = new Set();
625
- const promotedGroupKeys = new Set();
626
788
  const promotedSchemaKeys = new Set();
627
789
  const promotedTargetKeys = new Set();
628
790
  const promotedVariableKeys = new Set();
@@ -639,7 +801,6 @@ async function getPromotionPlan(sourceDatasource, destinationDatasource, options
639
801
  featureKeys.forEach((key) => promotedFeatureKeys.add(key));
640
802
  segmentKeys.forEach((key) => promotedSegmentKeys.add(key));
641
803
  attributeKeys.forEach((key) => promotedAttributeKeys.add(key));
642
- groupKeys.forEach((key) => promotedGroupKeys.add(key));
643
804
  schemaKeys.forEach((key) => promotedSchemaKeys.add(key));
644
805
  targetKeys.forEach((key) => promotedTargetKeys.add(key));
645
806
  variableKeys.forEach((key) => promotedVariableKeys.add(key));
@@ -667,19 +828,34 @@ async function getPromotionPlan(sourceDatasource, destinationDatasource, options
667
828
  promotedVariableKeys.add(key);
668
829
  }
669
830
  }
831
+ const promotionGraph = await (0, dependencies_1.buildDependencyGraph)({
832
+ listFeatures: async () => featureKeys,
833
+ readFeature: async (key) => promotableFeature(features[key]),
834
+ listSegments: async () => segmentKeys,
835
+ readSegment: async (key) => segments[key],
836
+ listVariables: async () => variableKeys,
837
+ readVariable: async (key) => ({
838
+ ...variables[key],
839
+ overrides: getAllPromotableVariableOverrides(variables[key]).map((override) => ({
840
+ ...override,
841
+ overrides: undefined,
842
+ })),
843
+ }),
844
+ }, { includeOverride: isPromotable });
845
+ const structural = await (0, dependencies_1.collectDependencyClosure)(sourceDatasource, [
846
+ ...Array.from(promotedFeatureKeys, dependencies_1.featureFlagNode),
847
+ ...Array.from(promotedVariableKeys, dependencies_1.variableNode),
848
+ ], { graph: promotionGraph });
849
+ structural.features.forEach((key) => promotedFeatureKeys.add(key));
850
+ structural.variables.forEach((key) => promotedVariableKeys.add(key));
851
+ structural.segments.forEach((key) => promotedSegmentKeys.add(key));
670
852
  for (const key of promotedVariableKeys) {
671
853
  const variable = variables[key];
672
- const promotableOverrides = getAllPromotableVariableOverrides(variable);
673
- const required = [
674
- ...(0, requiredFeatures_1.normalizeRequiredFeatures)(variable.requiredFeatures),
675
- ...promotableOverrides.flatMap((override) => (0, requiredFeatures_1.normalizeRequiredFeatures)(override.requiredFeatures)),
676
- ];
677
- required.forEach((entry) => promotedFeatureKeys.add((0, requiredFeatures_1.getRequiredFeatureKey)(entry)));
678
- (0, schemaReferences_1.extractSchemaReferences)(variable).forEach((schemaKey) => promotedSchemaKeys.add(schemaKey));
679
- promotableOverrides.forEach((override) => {
680
- collectGroupSegmentKeys(override.segments, promotedSegmentKeys);
681
- collectConditionDependencies(override.conditions, promotedSegmentKeys, promotedAttributeKeys);
682
- });
854
+ if (!variable)
855
+ continue;
856
+ (0, schemaReferences_1.extractSchemaReferences)(variable).forEach((schema) => promotedSchemaKeys.add(schema));
857
+ collectConditionDependencies(variable.conditions, promotedSegmentKeys, promotedAttributeKeys);
858
+ getAllPromotableVariableOverrides(variable).forEach((override) => collectConditionDependencies(override.conditions, promotedSegmentKeys, promotedAttributeKeys));
683
859
  }
684
860
  if (promotedFeatureKeys.size === 0 && promotedVariableKeys.size === 0 && !options.allowEmpty) {
685
861
  throw new Error("No source features or variables matched the promotion filters.");
@@ -694,16 +870,6 @@ async function getPromotionPlan(sourceDatasource, destinationDatasource, options
694
870
  collectFeatureDependencies(feature, features, promotedFeatureKeys, promotedSegmentKeys, promotedAttributeKeys, promotedSchemaKeys);
695
871
  }
696
872
  }
697
- for (const key of groupKeys) {
698
- const group = groups[key];
699
- const groupFeatureKeys = group.slots
700
- .map((slot) => slot.feature)
701
- .filter((featureKey) => typeof featureKey === "string");
702
- if (groupFeatureKeys.some((featureKey) => promotedFeatureKeys.has(featureKey))) {
703
- promotedGroupKeys.add(key);
704
- groupFeatureKeys.forEach((featureKey) => promotedFeatureKeys.add(featureKey));
705
- }
706
- }
707
873
  }
708
874
  const pendingSegments = Array.from(promotedSegmentKeys);
709
875
  for (let index = 0; index < pendingSegments.length; index++) {
@@ -729,11 +895,61 @@ async function getPromotionPlan(sourceDatasource, destinationDatasource, options
729
895
  pendingSchemas.push(...Array.from(promotedSchemaKeys).filter((key) => !pendingSchemas.includes(key)));
730
896
  }
731
897
  }
898
+ const [destinationFeatureKeys, destinationVariableKeys, destinationSegmentKeys, destinationTargetKeys,] = hasNoFilters
899
+ ? [[], [], [], []]
900
+ : await Promise.all([
901
+ destinationDatasource.listFeatures(),
902
+ destinationDatasource.listVariables(),
903
+ destinationDatasource.listSegments(),
904
+ destinationDatasource.listTargets(),
905
+ ]);
906
+ const destinationFeatures = hasNoFilters
907
+ ? {}
908
+ : await safeRead(destinationFeatureKeys, (key) => destinationDatasource.readFeature(key));
909
+ const destinationVariables = new Set(destinationVariableKeys);
910
+ const destinationSegments = new Set(destinationSegmentKeys);
911
+ const destinationTargets = new Set(destinationTargetKeys);
912
+ const referenceIsPromoted = (reference, owner) => reference.segment
913
+ ? promotedSegmentKeys.has(reference.segment)
914
+ : reference.feature
915
+ ? promotedFeatureKeys.has(reference.feature)
916
+ : promotedVariableKeys.has(reference.variable || owner);
917
+ const referenceExistsInDestination = (reference, owner) => {
918
+ if (reference.segment)
919
+ return destinationSegments.has(reference.segment);
920
+ if (reference.feature) {
921
+ if (reference.variable === undefined) {
922
+ return Object.prototype.hasOwnProperty.call(destinationFeatures, reference.feature);
923
+ }
924
+ return Boolean(Object.prototype.hasOwnProperty.call(destinationFeatures[reference.feature]?.variablesSchema || {}, reference.variable));
925
+ }
926
+ const variableKey = reference.variable || owner;
927
+ return Boolean(variableKey && destinationVariables.has(variableKey));
928
+ };
732
929
  const promotedTestKeys = testKeys.filter((key) => {
930
+ if (hasNoFilters)
931
+ return true;
733
932
  const test = tests[key];
734
- return (promotedFeatureKeys.has(test.feature) ||
735
- promotedSegmentKeys.has(test.segment) ||
736
- promotedVariableKeys.has(test.variable));
933
+ const ownerIsPromoted = ("feature" in test && promotedFeatureKeys.has(test.feature)) ||
934
+ ("segment" in test && promotedSegmentKeys.has(test.segment)) ||
935
+ ("variable" in test && promotedVariableKeys.has(test.variable));
936
+ if (!ownerIsPromoted)
937
+ return false;
938
+ const owner = "variable" in test ? test.variable : undefined;
939
+ const references = getTestCheckReferences(test);
940
+ return references.every((reference) => referenceIsPromoted(reference, owner) || referenceExistsInDestination(reference, owner));
941
+ });
942
+ const promotedScenarioKeys = scenarioKeys.filter((key) => {
943
+ const scenario = scenarios[key];
944
+ if (!isPromotable(scenario))
945
+ return false;
946
+ if (hasNoFilters)
947
+ return true;
948
+ const references = getScenarioCheckReferences(scenario);
949
+ if (!references.some((reference) => referenceIsPromoted(reference))) {
950
+ return false;
951
+ }
952
+ return references.every((reference) => referenceIsPromoted(reference) || referenceExistsInDestination(reference));
737
953
  });
738
954
  const plans = [];
739
955
  async function plan(type, key, source, readDestinationEntity, merge = (destination, sourceValue, conflicts) => {
@@ -746,59 +962,96 @@ async function getPromotionPlan(sourceDatasource, destinationDatasource, options
746
962
  const destination = await readDestination(key, readDestinationEntity);
747
963
  const cleanedDestination = destination ? withoutKey(destination) : undefined;
748
964
  if (cleanedDestination && (!isPromotable(cleanedSource) || !isPromotable(cleanedDestination))) {
749
- plans.push({
965
+ return {
750
966
  type,
751
967
  key,
752
968
  source: cleanedSource,
753
969
  destination: cleanedDestination,
754
970
  merged: cleanedDestination,
755
971
  conflicts: [],
756
- });
757
- return;
972
+ };
758
973
  }
759
974
  const conflicts = [];
760
- const merged = merge(cleanedDestination, cleanedSource, conflicts);
761
- plans.push({
975
+ const changesTestKind = (type === "test" || type === "scenario") &&
976
+ cleanedDestination &&
977
+ (0, testSpecs_1.classifyTestSpec)(cleanedDestination) !== (0, testSpecs_1.classifyTestSpec)(cleanedSource);
978
+ const variableKind = (variable) => variable.compose === undefined
979
+ ? "ordinary"
980
+ : typeof variable.compose === "string"
981
+ ? "alias"
982
+ : "map";
983
+ const changesVariableKind = type === "variable" &&
984
+ cleanedDestination &&
985
+ variableKind(cleanedDestination) !==
986
+ variableKind(cleanedSource);
987
+ let merged;
988
+ if (changesTestKind || changesVariableKind) {
989
+ // Distinct definition kinds must never be merged into a hybrid spec.
990
+ conflicts.push({
991
+ type,
992
+ key,
993
+ path: "",
994
+ source: cleanedSource,
995
+ destination: cleanedDestination,
996
+ });
997
+ merged = options.conflicts === "source" ? cleanedSource : cleanedDestination;
998
+ }
999
+ else {
1000
+ merged = merge(cleanedDestination, cleanedSource, conflicts);
1001
+ }
1002
+ return {
762
1003
  type,
763
1004
  key,
764
1005
  source: cleanedSource,
765
1006
  destination: cleanedDestination,
766
1007
  merged,
767
1008
  conflicts,
768
- });
1009
+ };
769
1010
  }
770
1011
  for (const key of Array.from(promotedAttributeKeys).sort()) {
771
1012
  if (attributes[key])
772
- await plan("attribute", key, attributes[key], (entryKey) => destinationDatasource.readAttribute(entryKey));
1013
+ plans.push(await plan("attribute", key, attributes[key], (entryKey) => destinationDatasource.readAttribute(entryKey)));
773
1014
  }
774
1015
  for (const key of Array.from(promotedSegmentKeys).sort()) {
775
1016
  if (segments[key])
776
- await plan("segment", key, segments[key], (entryKey) => destinationDatasource.readSegment(entryKey));
777
- }
778
- for (const key of Array.from(promotedGroupKeys).sort()) {
779
- if (groups[key])
780
- await plan("group", key, groups[key], (entryKey) => destinationDatasource.readGroup(entryKey));
1017
+ plans.push(await plan("segment", key, segments[key], (entryKey) => destinationDatasource.readSegment(entryKey)));
781
1018
  }
782
1019
  for (const key of Array.from(promotedSchemaKeys).sort()) {
783
1020
  if (schemas[key])
784
- await plan("schema", key, schemas[key], (entryKey) => destinationDatasource.readSchema(entryKey));
1021
+ plans.push(await plan("schema", key, schemas[key], (entryKey) => destinationDatasource.readSchema(entryKey)));
785
1022
  }
786
1023
  for (const key of Array.from(promotedFeatureKeys).sort()) {
787
1024
  if (features[key])
788
- await plan("feature", key, features[key], (entryKey) => destinationDatasource.readFeature(entryKey), (destination, source, conflicts) => mergeFeature(key, destination, source, options.conflicts, conflicts));
1025
+ plans.push(await plan("feature", key, features[key], (entryKey) => destinationDatasource.readFeature(entryKey), (destination, source, conflicts) => mergeFeature(key, destination, source, options.conflicts, conflicts)));
789
1026
  }
790
1027
  for (const key of Array.from(promotedVariableKeys).sort()) {
791
1028
  if (variables[key])
792
- await plan("variable", key, variables[key], (entryKey) => destinationDatasource.readVariable(entryKey), (destination, source, conflicts) => mergeVariable(key, destination, source, options.conflicts, conflicts));
793
- }
794
- for (const key of Array.from(promotedTargetKeys).sort()) {
795
- if (targets[key])
796
- await plan("target", key, targets[key], (entryKey) => destinationDatasource.readTarget(entryKey));
1029
+ plans.push(await plan("variable", key, variables[key], (entryKey) => destinationDatasource.readVariable(entryKey), (destination, source, conflicts) => mergeVariable(key, destination, source, options.conflicts, conflicts)));
797
1030
  }
1031
+ const testPlans = [];
1032
+ const scenarioPlans = [];
798
1033
  for (const key of promotedTestKeys.sort()) {
799
1034
  if (tests[key])
800
- await plan("test", key, tests[key], (entryKey) => destinationDatasource.readTest(entryKey), (destination, source, conflicts) => mergeTest(key, destination, source, options.conflicts, conflicts));
1035
+ testPlans.push(await plan("test", key, tests[key], (entryKey) => destinationDatasource.readTest(entryKey), (destination, source, conflicts) => mergeTest(key, destination, source, options.conflicts, conflicts)));
1036
+ }
1037
+ for (const key of promotedScenarioKeys.sort()) {
1038
+ if (scenarios[key])
1039
+ scenarioPlans.push(await plan("scenario", key, scenarios[key], (entryKey) => destinationDatasource.readScenario(entryKey)));
1040
+ }
1041
+ const targetReferences = [...testPlans, ...scenarioPlans].flatMap((entry) => getSpecTargetReferences(entry.merged).map((target) => ({ entry, target })));
1042
+ for (const { entry, target } of targetReferences) {
1043
+ if (destinationTargets.has(target))
1044
+ continue;
1045
+ if (!targets[target]) {
1046
+ throw new Error(`Cannot promote ${entry.type} "${entry.key}" because target "${target}" is missing from both source and destination.`);
1047
+ }
1048
+ promotedTargetKeys.add(target);
1049
+ }
1050
+ for (const key of Array.from(promotedTargetKeys).sort()) {
1051
+ if (targets[key])
1052
+ plans.push(await plan("target", key, targets[key], (entryKey) => destinationDatasource.readTarget(entryKey)));
801
1053
  }
1054
+ plans.push(...testPlans, ...scenarioPlans);
802
1055
  return plans;
803
1056
  }
804
1057
  async function writePlan(destinationDatasource, plans) {
@@ -810,8 +1063,6 @@ async function writePlan(destinationDatasource, plans) {
810
1063
  await destinationDatasource.writeAttribute(plan.key, plan.merged);
811
1064
  if (plan.type === "segment")
812
1065
  await destinationDatasource.writeSegment(plan.key, plan.merged);
813
- if (plan.type === "group")
814
- await destinationDatasource.writeGroup(plan.key, plan.merged);
815
1066
  if (plan.type === "schema")
816
1067
  await destinationDatasource.writeSchema(plan.key, plan.merged);
817
1068
  if (plan.type === "target")
@@ -822,6 +1073,8 @@ async function writePlan(destinationDatasource, plans) {
822
1073
  await destinationDatasource.writeVariable(plan.key, plan.merged);
823
1074
  if (plan.type === "test")
824
1075
  await destinationDatasource.writeTest(plan.key, plan.merged);
1076
+ if (plan.type === "scenario")
1077
+ await destinationDatasource.writeScenario(plan.key, plan.merged);
825
1078
  }
826
1079
  }
827
1080
  function normalizeConflictPolicy(value) {
@@ -858,20 +1111,24 @@ function getTimestamp() {
858
1111
  pad(date.getUTCSeconds()),
859
1112
  ].join("");
860
1113
  }
861
- function getEntityFilePath(projectConfig, type, key) {
1114
+ function getEntityFilePath(projectConfig, type, key, datasource) {
1115
+ if (type === "scenario" && datasource)
1116
+ return datasource.getScenarioSourcePath(key);
1117
+ if (type === "test" && datasource)
1118
+ return datasource.getTestSourcePath(key);
862
1119
  const directories = {
863
1120
  attribute: projectConfig.attributesDirectoryPath,
864
1121
  segment: projectConfig.segmentsDirectoryPath,
865
1122
  feature: projectConfig.featuresDirectoryPath,
866
- group: projectConfig.groupsDirectoryPath,
867
1123
  schema: projectConfig.schemasDirectoryPath,
868
1124
  target: projectConfig.targetsDirectoryPath,
869
1125
  variable: projectConfig.variablesDirectoryPath,
870
1126
  test: projectConfig.testsDirectoryPath,
1127
+ scenario: projectConfig.testsDirectoryPath,
871
1128
  };
872
1129
  const extension = projectConfig.parser.extension || "yml";
873
1130
  const pathSegments = key.split(projectConfig.namespaceCharacter);
874
- if (type === "test" &&
1131
+ if ((type === "test" || type === "scenario") &&
875
1132
  pathSegments.length > 1 &&
876
1133
  pathSegments[pathSegments.length - 1] === "spec") {
877
1134
  pathSegments[pathSegments.length - 2] = `${pathSegments[pathSegments.length - 2]}.spec`;
@@ -932,10 +1189,10 @@ function stringifyMarkdownAudit(result) {
932
1189
  `- Segments: ${result.dependencies.segment}`,
933
1190
  `- Features: ${result.dependencies.feature}`,
934
1191
  `- Variables: ${result.dependencies.variable}`,
935
- `- Groups: ${result.dependencies.group}`,
936
1192
  `- Schemas: ${result.dependencies.schema}`,
937
1193
  `- Targets: ${result.dependencies.target}`,
938
1194
  `- Tests: ${result.dependencies.test}`,
1195
+ `- Scenarios: ${result.dependencies.scenario}`,
939
1196
  "",
940
1197
  "## Files",
941
1198
  "",
@@ -1007,27 +1264,28 @@ async function promoteProjectSets(projectConfig, datasource, options) {
1007
1264
  const suffix = conflicts.length > 5 ? `\n...and ${conflicts.length - 5} more` : "";
1008
1265
  throw new Error(`Promotion has ${conflicts.length} conflict(s) and --conflicts=fail was used.\n${preview}${suffix}`);
1009
1266
  }
1267
+ await assertPromotionLintsClean(options.to, destinationDatasource, plans);
1010
1268
  if (options.apply === true) {
1011
1269
  await writePlan(destinationDatasource, plans);
1012
1270
  }
1013
1271
  const created = plans
1014
1272
  .filter((plan) => !plan.destination)
1015
- .map((plan) => formatProjectPath(projectConfig, getEntityFilePath(destinationDatasource.getConfig(), plan.type, plan.key)));
1273
+ .map((plan) => formatProjectPath(projectConfig, getEntityFilePath(destinationDatasource.getConfig(), plan.type, plan.key, destinationDatasource)));
1016
1274
  const updated = plans
1017
1275
  .filter((plan) => plan.destination && !deepEqual(plan.destination, plan.merged))
1018
- .map((plan) => formatProjectPath(projectConfig, getEntityFilePath(destinationDatasource.getConfig(), plan.type, plan.key)));
1276
+ .map((plan) => formatProjectPath(projectConfig, getEntityFilePath(destinationDatasource.getConfig(), plan.type, plan.key, destinationDatasource)));
1019
1277
  const unchanged = plans
1020
1278
  .filter((plan) => plan.destination && deepEqual(plan.destination, plan.merged))
1021
- .map((plan) => formatProjectPath(projectConfig, getEntityFilePath(destinationDatasource.getConfig(), plan.type, plan.key)));
1279
+ .map((plan) => formatProjectPath(projectConfig, getEntityFilePath(destinationDatasource.getConfig(), plan.type, plan.key, destinationDatasource)));
1022
1280
  const dependencies = {
1023
1281
  attribute: plans.filter((plan) => plan.type === "attribute").length,
1024
1282
  segment: plans.filter((plan) => plan.type === "segment").length,
1025
1283
  feature: plans.filter((plan) => plan.type === "feature").length,
1026
- group: plans.filter((plan) => plan.type === "group").length,
1027
1284
  schema: plans.filter((plan) => plan.type === "schema").length,
1028
1285
  target: plans.filter((plan) => plan.type === "target").length,
1029
1286
  variable: plans.filter((plan) => plan.type === "variable").length,
1030
1287
  test: plans.filter((plan) => plan.type === "test").length,
1288
+ scenario: plans.filter((plan) => plan.type === "scenario").length,
1031
1289
  };
1032
1290
  const result = {
1033
1291
  from: options.from,
@@ -1093,7 +1351,7 @@ function printPromoteResult(result, options = {}) {
1093
1351
  }
1094
1352
  console.log(` Conflict policy: ${result.filters.conflicts}`);
1095
1353
  console.log("");
1096
- console.log(` Dependencies: ${result.dependencies.attribute} attributes, ${result.dependencies.segment} segments, ${result.dependencies.feature} features, ${result.dependencies.variable} variables, ${result.dependencies.group} groups, ${result.dependencies.schema} schemas, ${result.dependencies.target} targets, ${result.dependencies.test} tests`);
1354
+ console.log(` Dependencies: ${result.dependencies.attribute} attributes, ${result.dependencies.segment} segments, ${result.dependencies.feature} features, ${result.dependencies.variable} variables, ${result.dependencies.schema} schemas, ${result.dependencies.target} targets, ${result.dependencies.test} tests, ${result.dependencies.scenario} scenarios`);
1097
1355
  console.log(` Created: ${result.files.created.length}`);
1098
1356
  console.log(` Updated: ${result.files.updated.length}`);
1099
1357
  console.log(` Unchanged: ${result.files.unchanged.length}`);
@@ -1114,6 +1372,7 @@ function printPromoteResult(result, options = {}) {
1114
1372
  }
1115
1373
  exports.promotePlugin = {
1116
1374
  command: "promote",
1375
+ description: "Preview or apply a promotion between project sets",
1117
1376
  handler: async ({ projectConfig, datasource, parsed }) => {
1118
1377
  const result = await promoteProjectSets(projectConfig, datasource, {
1119
1378
  from: parsed.from,
@@ -1134,35 +1393,35 @@ exports.promotePlugin = {
1134
1393
  examples: [
1135
1394
  {
1136
1395
  command: "promote --from=dev --to=staging",
1137
- description: "preview definitions that can be promoted from one set to another",
1396
+ description: "Preview definitions that can be promoted from one set to another",
1138
1397
  },
1139
1398
  {
1140
1399
  command: "promote --from=dev --to=staging --target=web",
1141
- description: "preview the target and every definition needed to build its datafile",
1400
+ description: "Preview the target and every definition needed to build its datafile",
1142
1401
  },
1143
1402
  {
1144
1403
  command: "promote --from=dev --to=staging --tag=web",
1145
- description: "preview definitions affecting features with a tag",
1404
+ description: "Preview definitions affecting features with a tag",
1146
1405
  },
1147
1406
  {
1148
- command: 'promote --from=dev --to=staging --includeFeatures="checkout*"',
1149
- description: "preview definitions affecting matching features",
1407
+ command: 'promote --from=dev --to=staging --include-features="checkout*"',
1408
+ description: "Preview definitions affecting matching features",
1150
1409
  },
1151
1410
  {
1152
1411
  command: "promote --from=dev --to=staging --conflicts=fail",
1153
- description: "fail instead of overwriting conflicting destination fields",
1412
+ description: "Fail instead of overwriting conflicting destination fields",
1154
1413
  },
1155
1414
  {
1156
1415
  command: "promote --from=dev --to=staging --apply",
1157
- description: "apply a promotion and write destination files",
1416
+ description: "Apply a promotion and write destination files",
1158
1417
  },
1159
1418
  {
1160
1419
  command: "promote --from=dev --to=staging --apply --audit=markdown",
1161
- description: "write a promotion audit file",
1420
+ description: "Write a promotion audit file",
1162
1421
  },
1163
1422
  {
1164
- command: "promote --from=dev --to=staging --showUnchanged",
1165
- description: "preview a promotion and include unchanged entries",
1423
+ command: "promote --from=dev --to=staging --show-unchanged",
1424
+ description: "Preview a promotion and include unchanged entries",
1166
1425
  },
1167
1426
  ],
1168
1427
  };