@featurevisor/core 4.3.0 → 4.5.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 (148) hide show
  1. package/lib/cli/cli.d.ts +2 -1
  2. package/lib/cli/cli.js +9 -6
  3. package/lib/cli/cli.js.map +1 -1
  4. package/lib/cli/options.js +69 -0
  5. package/lib/cli/options.js.map +1 -1
  6. package/lib/cli/plugins.js +7 -1
  7. package/lib/cli/plugins.js.map +1 -1
  8. package/lib/config/projectConfig.d.ts +10 -0
  9. package/lib/config/projectConfig.js +14 -0
  10. package/lib/config/projectConfig.js.map +1 -1
  11. package/lib/convert/check.d.ts +33 -0
  12. package/lib/convert/check.js +411 -0
  13. package/lib/convert/check.js.map +1 -0
  14. package/lib/convert/config.d.ts +20 -0
  15. package/lib/convert/config.js +147 -0
  16. package/lib/convert/config.js.map +1 -0
  17. package/lib/convert/documents.d.ts +40 -0
  18. package/lib/convert/documents.js +154 -0
  19. package/lib/convert/documents.js.map +1 -0
  20. package/lib/convert/index.d.ts +7 -0
  21. package/lib/convert/index.js +47 -0
  22. package/lib/convert/index.js.map +1 -0
  23. package/lib/convert/plan.d.ts +53 -0
  24. package/lib/convert/plan.js +669 -0
  25. package/lib/convert/plan.js.map +1 -0
  26. package/lib/convert/project.d.ts +29 -0
  27. package/lib/convert/project.js +109 -0
  28. package/lib/convert/project.js.map +1 -0
  29. package/lib/convert/run.d.ts +3 -0
  30. package/lib/convert/run.js +241 -0
  31. package/lib/convert/run.js.map +1 -0
  32. package/lib/convert/tests.d.ts +22 -0
  33. package/lib/convert/tests.js +267 -0
  34. package/lib/convert/tests.js.map +1 -0
  35. package/lib/datasource/conditionLocations.d.ts +9 -0
  36. package/lib/datasource/conditionLocations.js +70 -0
  37. package/lib/datasource/conditionLocations.js.map +1 -0
  38. package/lib/datasource/datasource.d.ts +11 -0
  39. package/lib/datasource/datasource.js +26 -6
  40. package/lib/datasource/datasource.js.map +1 -1
  41. package/lib/datasource/expressions.d.ts +36 -0
  42. package/lib/datasource/expressions.js +118 -0
  43. package/lib/datasource/expressions.js.map +1 -0
  44. package/lib/datasource/parseError.d.ts +11 -0
  45. package/lib/datasource/parseError.js +33 -19
  46. package/lib/datasource/parseError.js.map +1 -1
  47. package/lib/diff/conditions.d.ts +23 -0
  48. package/lib/diff/conditions.js +86 -0
  49. package/lib/diff/conditions.js.map +1 -0
  50. package/lib/diff/details.d.ts +7 -1
  51. package/lib/diff/details.js +54 -25
  52. package/lib/diff/details.js.map +1 -1
  53. package/lib/diff/index.d.ts +5 -0
  54. package/lib/diff/index.js +17 -2
  55. package/lib/diff/index.js.map +1 -1
  56. package/lib/evaluate/explain.d.ts +4 -1
  57. package/lib/evaluate/explain.js +35 -14
  58. package/lib/evaluate/explain.js.map +1 -1
  59. package/lib/evaluate/index.js +9 -5
  60. package/lib/evaluate/index.js.map +1 -1
  61. package/lib/formatter/expressions.d.ts +21 -0
  62. package/lib/formatter/expressions.js +79 -0
  63. package/lib/formatter/expressions.js.map +1 -0
  64. package/lib/formatter/formatDefinition.d.ts +46 -0
  65. package/lib/formatter/formatDefinition.js +201 -0
  66. package/lib/formatter/formatDefinition.js.map +1 -0
  67. package/lib/formatter/formatProject.d.ts +70 -0
  68. package/lib/formatter/formatProject.js +186 -0
  69. package/lib/formatter/formatProject.js.map +1 -0
  70. package/lib/formatter/index.d.ts +6 -0
  71. package/lib/formatter/index.js +53 -0
  72. package/lib/formatter/index.js.map +1 -0
  73. package/lib/formatter/layout.d.ts +26 -0
  74. package/lib/formatter/layout.js +175 -0
  75. package/lib/formatter/layout.js.map +1 -0
  76. package/lib/formatter/printFormatResult.d.ts +9 -0
  77. package/lib/formatter/printFormatResult.js +100 -0
  78. package/lib/formatter/printFormatResult.js.map +1 -0
  79. package/lib/formatter/run.d.ts +6 -0
  80. package/lib/formatter/run.js +97 -0
  81. package/lib/formatter/run.js.map +1 -0
  82. package/lib/formatter/simplify.d.ts +14 -0
  83. package/lib/formatter/simplify.js +21 -0
  84. package/lib/formatter/simplify.js.map +1 -0
  85. package/lib/formatter/since.d.ts +6 -0
  86. package/lib/formatter/since.js +80 -0
  87. package/lib/formatter/since.js.map +1 -0
  88. package/lib/formatter/style.d.ts +105 -0
  89. package/lib/formatter/style.js +248 -0
  90. package/lib/formatter/style.js.map +1 -0
  91. package/lib/linter/conditionKinds.js +2 -54
  92. package/lib/linter/conditionKinds.js.map +1 -1
  93. package/lib/linter/conditionSchema.js +42 -13
  94. package/lib/linter/conditionSchema.js.map +1 -1
  95. package/lib/linter/diagnostics.d.ts +14 -14
  96. package/lib/linter/expressionDiagnostics.d.ts +28 -0
  97. package/lib/linter/expressionDiagnostics.js +127 -0
  98. package/lib/linter/expressionDiagnostics.js.map +1 -0
  99. package/lib/linter/featureSchema.d.ts +2 -2
  100. package/lib/linter/featureSchema.js +14 -13
  101. package/lib/linter/featureSchema.js.map +1 -1
  102. package/lib/linter/lintProject.d.ts +7 -0
  103. package/lib/linter/lintProject.js +300 -52
  104. package/lib/linter/lintProject.js.map +1 -1
  105. package/lib/linter/listTypes.d.ts +7 -0
  106. package/lib/linter/listTypes.js +19 -0
  107. package/lib/linter/listTypes.js.map +1 -0
  108. package/lib/linter/printError.d.ts +2 -0
  109. package/lib/linter/printError.js +1 -0
  110. package/lib/linter/printError.js.map +1 -1
  111. package/lib/linter/requiredVariablesSchema.js +129 -13
  112. package/lib/linter/requiredVariablesSchema.js.map +1 -1
  113. package/lib/migrate/definitions.d.ts +46 -0
  114. package/lib/migrate/definitions.js +488 -0
  115. package/lib/migrate/definitions.js.map +1 -0
  116. package/lib/migrate/index.d.ts +6 -0
  117. package/lib/migrate/index.js +30 -0
  118. package/lib/migrate/index.js.map +1 -0
  119. package/lib/migrate/migrateProject.d.ts +33 -0
  120. package/lib/migrate/migrateProject.js +195 -0
  121. package/lib/migrate/migrateProject.js.map +1 -0
  122. package/lib/migrate/project.d.ts +31 -0
  123. package/lib/migrate/project.js +153 -0
  124. package/lib/migrate/project.js.map +1 -0
  125. package/lib/migrate/run.d.ts +3 -0
  126. package/lib/migrate/run.js +81 -0
  127. package/lib/migrate/run.js.map +1 -0
  128. package/lib/migrate/write.d.ts +10 -0
  129. package/lib/migrate/write.js +150 -0
  130. package/lib/migrate/write.js.map +1 -0
  131. package/lib/promoter/index.js +85 -4
  132. package/lib/promoter/index.js.map +1 -1
  133. package/lib/rewrite/conditions.d.ts +73 -0
  134. package/lib/rewrite/conditions.js +485 -0
  135. package/lib/rewrite/conditions.js.map +1 -0
  136. package/lib/rewrite/diff.d.ts +2 -0
  137. package/lib/rewrite/diff.js +76 -0
  138. package/lib/rewrite/diff.js.map +1 -0
  139. package/lib/rewrite/documents.d.ts +25 -0
  140. package/lib/rewrite/documents.js +54 -0
  141. package/lib/rewrite/documents.js.map +1 -0
  142. package/lib/rewrite/files.d.ts +6 -0
  143. package/lib/rewrite/files.js +66 -0
  144. package/lib/rewrite/files.js.map +1 -0
  145. package/lib/rewrite/lines.d.ts +56 -0
  146. package/lib/rewrite/lines.js +205 -0
  147. package/lib/rewrite/lines.js.map +1 -0
  148. package/package.json +5 -4
@@ -0,0 +1,669 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.CONDITION_FORMS = void 0;
37
+ exports.isConditionForm = isConditionForm;
38
+ exports.leaveConfigByHand = leaveConfigByHand;
39
+ exports.planConversion = planConversion;
40
+ const fs = __importStar(require("node:fs"));
41
+ const path = __importStar(require("node:path"));
42
+ const yaml_1 = require("yaml");
43
+ const config_1 = require("../config");
44
+ const filesystemAdapter_1 = require("../datasource/filesystemAdapter");
45
+ const lines_1 = require("../rewrite/lines");
46
+ const config_2 = require("./config");
47
+ const documents_1 = require("./documents");
48
+ const conditions_1 = require("../rewrite/conditions");
49
+ const project_1 = require("./project");
50
+ const tests_1 = require("./tests");
51
+ const expressions_1 = require("../formatter/expressions");
52
+ exports.CONDITION_FORMS = ["expressions", "trees"];
53
+ function isConditionForm(target) {
54
+ return exports.CONDITION_FORMS.includes(target);
55
+ }
56
+ const DIRECTORY_OPTIONS = [
57
+ "attributesDirectoryPath",
58
+ "schemasDirectoryPath",
59
+ "segmentsDirectoryPath",
60
+ "featuresDirectoryPath",
61
+ "variablesDirectoryPath",
62
+ "targetsDirectoryPath",
63
+ "testsDirectoryPath",
64
+ ];
65
+ /** The keys grouped by lane in each kind of definition */
66
+ const LANE_KEYS = {
67
+ feature: ["rules", "force", "expose"],
68
+ variable: ["overrides"],
69
+ };
70
+ const SHARED = ["attribute", "schema", "segment", "target"];
71
+ /** Leaves the configuration for the user to change after converting, saying why */
72
+ function leaveConfigByHand(config, reason) {
73
+ config.byHand = reason;
74
+ config.edits = [
75
+ ...config.remove.map((name) => `removes ${name}`),
76
+ ...config.add.map(([, , says]) => says),
77
+ ];
78
+ }
79
+ /** The lanes a project without either gets, as init's example with environments has */
80
+ const DEFAULT_LANES = ["staging", "production"];
81
+ const files = (count) => `${count} ${count === 1 ? "file" : "files"}`;
82
+ class Builder {
83
+ constructor(project, from, to, lanes) {
84
+ this.project = project;
85
+ /** Files whose aliases were written out in full */
86
+ this.expanded = new Set();
87
+ /** Files of a custom format written as its parser writes them, which may lose comments */
88
+ this.rewritten = new Set();
89
+ /** Whether fmt leaves each file as it is, asked once however many lanes it is written to */
90
+ this.wasFormatted = new Map();
91
+ this.plan = {
92
+ from,
93
+ to,
94
+ lanes,
95
+ writes: new Map(),
96
+ removes: new Set(),
97
+ config: { edits: [], remove: [], add: [] },
98
+ conflicts: [],
99
+ differences: [],
100
+ next: [],
101
+ };
102
+ this.configPath = path.join(project.rootDirectoryPath, config_1.CONFIG_MODULE_NAME);
103
+ }
104
+ get parser() {
105
+ return this.project.parser;
106
+ }
107
+ /** How fmt formats this project's files, its expressions included */
108
+ get format() {
109
+ return { expressions: (0, expressions_1.getFormatExpressionOptions)(this.project.config) };
110
+ }
111
+ /** featurevisor.config.js as it is written */
112
+ get configSource() {
113
+ return (this.configText ?? (this.configText = fs.readFileSync(this.configPath, "utf8")));
114
+ }
115
+ relative(filePath) {
116
+ return path.relative(this.project.rootDirectoryPath, filePath);
117
+ }
118
+ write(filePath, content) {
119
+ this.plan.writes.set(filePath, content);
120
+ this.plan.removes.delete(filePath);
121
+ }
122
+ /** Removes a file, when there is one */
123
+ remove(filePath) {
124
+ if (!this.plan.writes.has(filePath) && fs.existsSync(filePath))
125
+ this.plan.removes.add(filePath);
126
+ }
127
+ /** The directory of a kind at the top level, or in a set */
128
+ directory(kind, set) {
129
+ const config = set ? (0, config_1.getProjectConfigForSet)(this.project.config, set) : this.project.config;
130
+ return (0, project_1.directoriesOf)(config)[kind];
131
+ }
132
+ /** The state file of a lane, as an environment or a set, or of a flat project */
133
+ state(lane, as) {
134
+ const config = this.project.config;
135
+ if (as === "sets")
136
+ return (0, filesystemAdapter_1.getExistingStateFilePath)((0, config_1.getProjectConfigForSet)(config, lane), false);
137
+ return (0, filesystemAdapter_1.getExistingStateFilePath)(config, as === "environments" ? lane : false);
138
+ }
139
+ /** Moves or copies a state file, when there is one */
140
+ moveState(from, to) {
141
+ if (!fs.existsSync(from))
142
+ return;
143
+ const content = fs.readFileSync(from, "utf8");
144
+ this.remove(from);
145
+ for (const target of to)
146
+ this.write(target, content);
147
+ }
148
+ load(file) {
149
+ const { doc, expanded } = (0, documents_1.load)(file.source, this.parser);
150
+ if (expanded)
151
+ this.expanded.add(this.relative(file.filePath));
152
+ return doc;
153
+ }
154
+ /**
155
+ * The file's new text, or a conflict when it would not read back as converted. A file that
156
+ * was formatted comes out formatted, so a project fmt keeps clean stays clean.
157
+ */
158
+ rendered(file, doc) {
159
+ const result = (0, documents_1.render)(file.source, doc, this.parser);
160
+ if (!result) {
161
+ this.plan.conflicts.push(`The ${file.kind} ${this.relative(file.filePath)} would not read back as converted.`);
162
+ return file.source;
163
+ }
164
+ if (!result.merged && !lines_1.BUILT_IN_PARSERS.has(this.parser)) {
165
+ this.rewritten.add(this.relative(file.filePath));
166
+ }
167
+ if (result.text === file.source)
168
+ return result.text;
169
+ // conversion moves assertions and lanes, never what kind of spec a file holds
170
+ const entityType = file.kind === "test" && (0, tests_1.specKind)(file.value) === "scenario" ? "scenario" : file.kind;
171
+ if (!this.wasFormatted.has(file)) {
172
+ this.wasFormatted.set(file, (0, documents_1.isFormatted)(entityType, file.source, this.parser, this.format));
173
+ }
174
+ return this.wasFormatted.get(file)
175
+ ? (0, documents_1.formatted)(entityType, result.text, this.parser, this.format)
176
+ : result.text;
177
+ }
178
+ /**
179
+ * Edits the configuration, and says what changed. When the file sets a setting the new shape
180
+ * cannot have where convert cannot edit it, the file is left for the user to edit after
181
+ * converting, and a setting the new shape only ignores is left where it is.
182
+ */
183
+ config({ remove = [], tidy = [], add = [] }) {
184
+ this.plan.config = { edits: [], remove, add };
185
+ const { text, restore } = (0, lines_1.lineEndings)(this.configSource);
186
+ const result = (0, config_2.editConfig)(text, {
187
+ remove: [...remove, ...tidy.map(([name]) => name)],
188
+ add: add.map(([name, value]) => [name, value]),
189
+ });
190
+ const missing = remove.filter((name) => !result?.removed.includes(name));
191
+ if (!result || missing.length > 0) {
192
+ leaveConfigByHand(this.plan.config, result
193
+ ? `it sets ${missing.join(" and ")} where convert cannot edit it, such as in an object spread into its settings`
194
+ : "it does not set module.exports to an object convert can edit");
195
+ return;
196
+ }
197
+ this.write(this.configPath, restore(result.text));
198
+ const removed = [...remove, ...tidy.filter(([, why]) => !why).map(([name]) => name)].filter((name) => result.removed.includes(name));
199
+ this.plan.config.edits.push(...(removed.length > 0 ? [`removes ${removed.join(" and ")}`] : []), ...add.map(([, , says]) => says), ...tidy
200
+ .filter(([name, why]) => why && result.removed.includes(name))
201
+ .map(([name, why]) => `removes ${name}, ${why}`));
202
+ }
203
+ lanesValue() {
204
+ return `[${this.plan.lanes.map((lane) => (0, config_2.quote)(this.configSource, lane)).join(", ")}]`;
205
+ }
206
+ /** One flow from each set to the next, on one line, or one per line when there are several */
207
+ flowsValue() {
208
+ const { lanes } = this.plan;
209
+ const value = (lane) => (0, config_2.quote)(this.configSource, lane);
210
+ const flows = lanes
211
+ .slice(1)
212
+ .map((to, index) => `{ from: ${value(lanes[index])}, to: ${value(to)} }`);
213
+ return flows.length > 1 ? flows : `[${flows.join(", ")}]`;
214
+ }
215
+ /** Turns sets on, with promotions from each to the next, without settings sets ignore */
216
+ configureSets(remove) {
217
+ const { lanes } = this.plan;
218
+ const add = [["sets", "true", "adds sets: true"]];
219
+ if (lanes.length > 1) {
220
+ add.push(["promotionFlows", this.flowsValue(), `adds promotionFlows ${lanes.join(" to ")}`]);
221
+ }
222
+ this.config({
223
+ remove,
224
+ tidy: DIRECTORY_OPTIONS.map((name) => [name, "which does not apply inside sets"]),
225
+ add,
226
+ });
227
+ }
228
+ /** Says where datafiles go now, which applications must follow */
229
+ moveDatafiles(where) {
230
+ this.plan.next.push(`Datafiles move ${where}. Point applications at them, and clear datafiles/ before the next build.`);
231
+ }
232
+ }
233
+ /** Whether a segment depends on a feature or a variable, directly or through other segments */
234
+ function dependsOnEntities(key, segments, seen = new Set()) {
235
+ if (seen.has(key))
236
+ return false;
237
+ seen.add(key);
238
+ const visit = (value) => {
239
+ if (typeof value === "string")
240
+ return segments.has(value) && dependsOnEntities(value, segments, seen);
241
+ if (Array.isArray(value))
242
+ return value.some(visit);
243
+ if (!value || typeof value !== "object")
244
+ return false;
245
+ const record = value;
246
+ if ("feature" in record || "variable" in record)
247
+ return true;
248
+ return ["and", "or", "not"].some((group) => visit(record[group]));
249
+ };
250
+ return visit(segments.get(key)?.conditions);
251
+ }
252
+ /** Segments by key, from their paths in the segments directory */
253
+ function segmentsOf(files, extension, namespace) {
254
+ return new Map(files
255
+ .filter((file) => file.kind === "segment")
256
+ .map((file) => [
257
+ file.relative
258
+ .slice(0, -(extension.length + 1))
259
+ .split(path.sep)
260
+ .join(namespace),
261
+ file.value,
262
+ ]));
263
+ }
264
+ /** Whether a spec's assertions need an environment once the project has environments */
265
+ function needsEnvironment(value, segments) {
266
+ if ((0, tests_1.specKind)(value) !== "segment")
267
+ return true;
268
+ return dependsOnEntities(String(value.segment), segments);
269
+ }
270
+ // Environments to sets
271
+ function environmentsToSets(builder, project) {
272
+ const { lanes } = builder.plan;
273
+ for (const file of project.files) {
274
+ for (const lane of lanes) {
275
+ const target = path.join(builder.directory(file.kind, lane), file.relative);
276
+ if (SHARED.includes(file.kind)) {
277
+ builder.write(target, file.source);
278
+ continue;
279
+ }
280
+ const doc = builder.load(file);
281
+ if (file.kind === "test") {
282
+ const spec = (0, tests_1.specForLane)(doc, lane);
283
+ if (spec)
284
+ builder.write(target, builder.rendered(file, spec));
285
+ continue;
286
+ }
287
+ const map = (0, documents_1.rootMap)(doc);
288
+ if (map) {
289
+ for (const key of LANE_KEYS[file.kind] || []) {
290
+ // a feature with no rules in an environment keeps no rules in its set
291
+ (0, documents_1.takeLane)(map, key, lane, key === "rules" ? [] : undefined);
292
+ }
293
+ }
294
+ builder.write(target, builder.rendered(file, doc));
295
+ }
296
+ builder.remove(file.filePath);
297
+ }
298
+ for (const lane of lanes) {
299
+ builder.moveState(builder.state(lane, "environments"), [builder.state(lane, "sets")]);
300
+ }
301
+ builder.configureSets(["environments"]);
302
+ builder.plan.next.push("Pass --set=<name> where CI and scripts passed --environment=<name>. Applications load the same datafile paths.");
303
+ }
304
+ // Sets to environments
305
+ /** The top level keys whose values differ between files, as `: a, b` */
306
+ function differingKeys(entries, valueOf) {
307
+ const values = entries.map((file) => (valueOf(file) || {}));
308
+ const keys = [...new Set(values.flatMap((value) => Object.keys(value)))].filter((key) => !values.every((value) => (0, lines_1.same)(value[key], values[0][key])));
309
+ return keys.length > 0 ? `: ${keys.join(", ")}` : "";
310
+ }
311
+ function setsToEnvironments(builder, project) {
312
+ const { lanes } = builder.plan;
313
+ const groups = new Map();
314
+ for (const file of project.files) {
315
+ const id = `${file.kind}:${file.relative}`;
316
+ if (!groups.has(id))
317
+ groups.set(id, []);
318
+ groups.get(id).push(file);
319
+ }
320
+ const byLane = (entries) => lanes
321
+ .map((lane) => entries.find((file) => file.set === lane))
322
+ .filter(Boolean);
323
+ const name = (file) => `${file.kind} ${file.relative}`;
324
+ const segments = new Map();
325
+ const segmentsIn = (set) => {
326
+ if (!segments.has(set)) {
327
+ const inSet = project.files.filter((file) => file.set === set);
328
+ segments.set(set, segmentsOf(inSet, project.parser.extension, project.config.namespaceCharacter));
329
+ }
330
+ return segments.get(set);
331
+ };
332
+ for (const [, unordered] of groups) {
333
+ const entries = byLane(unordered);
334
+ const [first] = entries;
335
+ const target = path.join(builder.directory(first.kind), first.relative);
336
+ entries.forEach((file) => builder.remove(file.filePath));
337
+ const setsOf = (list) => list.map((file) => file.set).join(", ");
338
+ if (SHARED.includes(first.kind)) {
339
+ if (!entries.every((file) => (0, lines_1.same)(file.value, first.value))) {
340
+ builder.plan.conflicts.push(`The ${name(first)} differs between sets ${setsOf(entries)}${differingKeys(entries, (file) => file.value)}.`);
341
+ continue;
342
+ }
343
+ if (first.kind === "target" && entries.length < lanes.length) {
344
+ builder.plan.differences.push(`The target ${first.relative} is only in sets ${setsOf(entries)}, so every environment builds it.`);
345
+ }
346
+ builder.write(target, first.source);
347
+ continue;
348
+ }
349
+ if (first.kind === "test") {
350
+ const merged = (0, tests_1.mergeSpecs)(entries.map((file) => ({ lane: file.set, doc: builder.load(file) })), lanes, needsEnvironment(first.value, segmentsIn(first.set)));
351
+ if (merged.conflict) {
352
+ builder.plan.conflicts.push(`The ${name(first)}: ${merged.conflict}.`);
353
+ continue;
354
+ }
355
+ if (merged.renamed.length > 0) {
356
+ builder.plan.differences.push(`Assertions in ${first.relative} sharing a key across sets got the sets' names after it: ${merged.renamed.join(", ")}.`);
357
+ }
358
+ builder.write(target, builder.rendered(first, merged.doc));
359
+ continue;
360
+ }
361
+ const keys = LANE_KEYS[first.kind] || [];
362
+ const outside = (file) => Object.fromEntries(Object.entries(file.value).filter(([key]) => !keys.includes(key)));
363
+ if (!entries.every((file) => (0, lines_1.same)(outside(file), outside(first)))) {
364
+ builder.plan.conflicts.push(`The ${name(first)} differs between sets ${setsOf(entries)} outside its lanes${differingKeys(entries, outside)}.`);
365
+ continue;
366
+ }
367
+ if (first.kind === "variable" && entries.length < lanes.length) {
368
+ builder.plan.conflicts.push(`The global variable ${first.relative} is only in sets ${setsOf(entries)}. With environments, it would reach every environment's datafiles.`);
369
+ continue;
370
+ }
371
+ const docs = new Map(entries.map((file) => [file.set, builder.load(file)]));
372
+ const doc = docs.get(first.set);
373
+ const map = (0, documents_1.rootMap)(doc);
374
+ const laneNode = (lane, key) => {
375
+ const laneDoc = docs.get(lane);
376
+ return laneDoc ? (0, documents_1.nodeAt)((0, documents_1.rootMap)(laneDoc), key) : undefined;
377
+ };
378
+ for (const key of keys) {
379
+ const values = lanes.map((lane) => {
380
+ const node = laneNode(lane, key);
381
+ // an empty list of rules is a lane left out
382
+ if (key === "rules" && (0, yaml_1.isSeq)(node) && node.items.length === 0)
383
+ return [lane, undefined];
384
+ // a feature missing from a set leaves that environment's datafiles without it
385
+ if (key === "expose" && !docs.has(lane))
386
+ return [lane, new yaml_1.Scalar(false)];
387
+ return [lane, node];
388
+ });
389
+ const grouped = (0, documents_1.laneMap)(values, (0, documents_1.isSpaced)(map));
390
+ if (key === "rules")
391
+ (0, documents_1.setKey)(map, key, grouped || new yaml_1.YAMLMap());
392
+ else
393
+ (0, documents_1.setKey)(map, key, grouped, first.kind === "feature" ? ["rules", "force"] : undefined);
394
+ }
395
+ builder.write(target, builder.rendered(first, doc));
396
+ }
397
+ for (const lane of lanes) {
398
+ builder.moveState(builder.state(lane, "sets"), [builder.state(lane, "environments")]);
399
+ }
400
+ builder.config({
401
+ remove: ["sets"],
402
+ tidy: [["promotionFlows"]],
403
+ add: [["environments", builder.lanesValue(), `adds environments ${lanes.join(", ")}`]],
404
+ });
405
+ builder.plan.next.push("Pass --environment=<name> where CI and scripts passed --set=<name>. Applications load the same datafile paths. Promotions need sets, so they end.");
406
+ }
407
+ // Flat to environments or sets
408
+ function flatToEnvironments(builder, project) {
409
+ const { lanes } = builder.plan;
410
+ const segments = segmentsOf(project.files, project.parser.extension, project.config.namespaceCharacter);
411
+ for (const file of project.files) {
412
+ if (SHARED.includes(file.kind))
413
+ continue;
414
+ const doc = builder.load(file);
415
+ let result = doc;
416
+ if (file.kind === "test") {
417
+ result = (0, tests_1.specForLanes)(doc, lanes, needsEnvironment(file.value, segments));
418
+ }
419
+ else {
420
+ const map = (0, documents_1.rootMap)(doc);
421
+ if (map) {
422
+ for (const key of LANE_KEYS[file.kind] || [])
423
+ (0, documents_1.spreadLanes)(map, key, lanes, (0, documents_1.isSpaced)(map));
424
+ }
425
+ }
426
+ const output = builder.rendered(file, result);
427
+ if (output !== file.source)
428
+ builder.write(file.filePath, output);
429
+ }
430
+ builder.moveState(builder.state(undefined, "flat"), lanes.map((lane) => builder.state(lane, "environments")));
431
+ builder.config({
432
+ add: [["environments", builder.lanesValue(), `adds environments ${lanes.join(", ")}`]],
433
+ });
434
+ builder.moveDatafiles(`to datafiles/<environment>/, such as datafiles/${lanes[lanes.length - 1]}/`);
435
+ }
436
+ function flatToSets(builder, project) {
437
+ const { lanes } = builder.plan;
438
+ for (const file of project.files) {
439
+ for (const lane of lanes) {
440
+ builder.write(path.join(builder.directory(file.kind, lane), file.relative), file.source);
441
+ }
442
+ builder.remove(file.filePath);
443
+ }
444
+ builder.moveState(builder.state(undefined, "flat"), lanes.map((lane) => builder.state(lane, "sets")));
445
+ builder.configureSets([]);
446
+ builder.moveDatafiles(`to datafiles/<set>/, such as datafiles/${lanes[lanes.length - 1]}/`);
447
+ }
448
+ // Back to flat
449
+ function environmentsToFlat(builder, project, keep) {
450
+ const dropped = new Map();
451
+ for (const file of project.files) {
452
+ if (SHARED.includes(file.kind))
453
+ continue;
454
+ const doc = builder.load(file);
455
+ let result = doc;
456
+ if (file.kind === "test") {
457
+ result = (0, tests_1.specForLane)(doc, keep);
458
+ // assertions for the other environments, or a scenario for one of them
459
+ const count = (value) => {
460
+ const spec = (value || {});
461
+ return Array.isArray(spec.assertions) ? spec.assertions.length : 1;
462
+ };
463
+ if (!result || count(result.toJS()) < count(file.value)) {
464
+ dropped.set("test assertions", (dropped.get("test assertions") || 0) + 1);
465
+ }
466
+ }
467
+ else {
468
+ const map = (0, documents_1.rootMap)(doc);
469
+ for (const key of (map && LANE_KEYS[file.kind]) || []) {
470
+ const lanes = map.get(key);
471
+ if ((0, yaml_1.isMap)(lanes) && lanes.items.length > (lanes.has(keep) ? 1 : 0)) {
472
+ dropped.set(key, (dropped.get(key) || 0) + 1);
473
+ }
474
+ (0, documents_1.takeLane)(map, key, keep, key === "rules" ? [] : undefined);
475
+ }
476
+ }
477
+ if (!result)
478
+ builder.remove(file.filePath);
479
+ else {
480
+ const output = builder.rendered(file, result);
481
+ if (output !== file.source)
482
+ builder.write(file.filePath, output);
483
+ }
484
+ }
485
+ const others = builder.plan.lanes.filter((lane) => lane !== keep);
486
+ for (const lane of others)
487
+ builder.remove(builder.state(lane, "environments"));
488
+ builder.moveState(builder.state(keep, "environments"), [builder.state(undefined, "flat")]);
489
+ for (const [what, count] of dropped) {
490
+ builder.plan.differences.push(`Drops ${others.join(", ")} from ${what} in ${files(count)}, keeping ${keep}.`);
491
+ }
492
+ builder.config({ remove: ["environments"] });
493
+ builder.moveDatafiles(`from datafiles/${keep}/ to datafiles/`);
494
+ }
495
+ function setsToFlat(builder, project, keep) {
496
+ const counts = new Map();
497
+ for (const file of project.files) {
498
+ builder.remove(file.filePath);
499
+ if (file.set === keep) {
500
+ builder.write(path.join(builder.directory(file.kind), file.relative), file.source);
501
+ }
502
+ else {
503
+ counts.set(file.set, (counts.get(file.set) || 0) + 1);
504
+ }
505
+ }
506
+ const others = builder.plan.lanes.filter((lane) => lane !== keep);
507
+ for (const lane of others)
508
+ builder.remove(builder.state(lane, "sets"));
509
+ builder.moveState(builder.state(keep, "sets"), [builder.state(undefined, "flat")]);
510
+ for (const [set, count] of counts) {
511
+ builder.plan.differences.push(`Drops the set ${set}, ${files(count)}, keeping ${keep}.`);
512
+ }
513
+ builder.config({ remove: ["sets"], tidy: [["promotionFlows"]] });
514
+ builder.moveDatafiles(`from datafiles/${keep}/ to datafiles/`);
515
+ }
516
+ // Conditions as expressions or as trees
517
+ const SETTING = "conditionExpressions";
518
+ function convertConditions(builder, project, to, exact) {
519
+ const { plan } = builder;
520
+ const options = { namespaceCharacter: project.config.namespaceCharacter };
521
+ const allowed = project.config.conditionExpressions === true;
522
+ const kept = new Set();
523
+ const unmarked = new Set();
524
+ let count = 0;
525
+ let simplified = 0;
526
+ for (const file of project.files) {
527
+ if (!conditions_1.CONDITION_KINDS.includes(file.kind))
528
+ continue;
529
+ const doc = builder.load(file);
530
+ const write = to === "expressions" ? conditions_1.writeTreesAsExpressions : conditions_1.writeExpressionsAsTrees;
531
+ const result = write(doc, file.kind, file.value, options);
532
+ const relative = builder.relative(file.filePath);
533
+ for (const at of result.invalid) {
534
+ plan.conflicts.push(`The expression at ${at.join(".")} in ${relative} has errors, so it has no tree to write. Run lint and fix it first.`);
535
+ }
536
+ if (result.kept.length > 0)
537
+ kept.add(relative);
538
+ if (result.unmarked.length > 0)
539
+ unmarked.add(relative);
540
+ // then each condition in its simplest form, as fmt --simplify writes it, unless asked to
541
+ // keep every datafile byte identical
542
+ const simpler = to === "expressions" && !exact
543
+ ? (0, conditions_1.simplifyConditions)(doc, file.kind, doc.toJS(), options).changed
544
+ : 0;
545
+ if (result.changed + simpler === 0) {
546
+ // only files convert writes have their aliases written out
547
+ builder.expanded.delete(relative);
548
+ continue;
549
+ }
550
+ count += result.changed;
551
+ simplified += simpler;
552
+ const output = builder.rendered(file, doc);
553
+ if (output !== file.source)
554
+ builder.write(file.filePath, output);
555
+ }
556
+ if (to === "expressions" && !allowed) {
557
+ builder.config({
558
+ tidy: [[SETTING]],
559
+ add: [[SETTING, "true", `sets ${SETTING}: true`]],
560
+ });
561
+ if (!plan.config.byHand)
562
+ plan.config.edits = [`sets ${SETTING}: true`];
563
+ }
564
+ else if (to === "trees" && allowed) {
565
+ builder.config({ remove: [SETTING] });
566
+ }
567
+ if (count + simplified === 0 && plan.config.edits.length === 0) {
568
+ plan.conflicts.push(to === "trees"
569
+ ? "The project has no condition expressions to write as trees."
570
+ : exact
571
+ ? "Every condition tree that can be an expression is one already."
572
+ : "Every condition is an expression already, in its simplest form, wherever it can be.");
573
+ return;
574
+ }
575
+ plan.conditions = count;
576
+ if (simplified > 0) {
577
+ plan.simplified = simplified;
578
+ plan.differences.push(`Datafiles change shape, since ${simplified === 1 ? "a condition is" : `${simplified} conditions are`} written in ${simplified === 1 ? "its" : "their"} simplest form, such as a list of one condition as that condition. Features' hashes change with them, and every evaluation stays the same.`);
579
+ }
580
+ if (kept.size > 0) {
581
+ plan.differences.push(`Leaves that have no expression form stay trees, such as a disabled feature's variation, in ${[...kept].join(", ")}.`);
582
+ }
583
+ if (unmarked.size > 0) {
584
+ plan.differences.push(`Expressions kept as written with # featurevisor-ignore-line are written as trees too, without that comment, in ${[...unmarked].join(", ")}.`);
585
+ }
586
+ }
587
+ function planConversion(project, options) {
588
+ if (isConditionForm(options.to)) {
589
+ const to = options.to;
590
+ const builder = new Builder(project, to === "expressions" ? "trees" : "expressions", to, []);
591
+ if (options.lanes || options.keep) {
592
+ builder.plan.conflicts.push(`--to=${to} changes how conditions are written, not the project's shape, so leave out --environments, --sets and --keep.`);
593
+ return builder.plan;
594
+ }
595
+ if (options.exact && to !== "expressions") {
596
+ builder.plan.conflicts.push("--exact applies only to --to=expressions. --to=trees always builds the same datafiles.");
597
+ return builder.plan;
598
+ }
599
+ convertConditions(builder, project, to, options.exact === true);
600
+ if (builder.rewritten.size > 0) {
601
+ builder.plan.differences.push(`${[...builder.rewritten].join(", ")} are written as the parser writes them, since convert could not keep their own lines. Check them for comments.`);
602
+ }
603
+ if (builder.expanded.size > 0) {
604
+ builder.plan.differences.push(`Aliases are written out in full in ${[...builder.expanded].join(", ")}.`);
605
+ }
606
+ return builder.plan;
607
+ }
608
+ const from = project.shape;
609
+ if (from === "sets and environments") {
610
+ const plan = new Builder(project, from, options.to, []).plan;
611
+ plan.conflicts.push("This project uses sets and environments together. convert changes projects with one of them, or neither.");
612
+ return plan;
613
+ }
614
+ let lanes = from === "flat" ? options.lanes || DEFAULT_LANES : project.lanes;
615
+ const builder = new Builder(project, from, options.to, lanes);
616
+ const { plan } = builder;
617
+ if (from === options.to) {
618
+ plan.conflicts.push(`The project already has ${from === "flat" ? "no environments and no sets" : from}.`);
619
+ return plan;
620
+ }
621
+ if (from !== "flat" && options.lanes) {
622
+ const given = [...options.lanes].sort();
623
+ if (from === "sets" && options.to === "environments" && (0, lines_1.same)(given, [...lanes].sort())) {
624
+ lanes = plan.lanes = options.lanes;
625
+ }
626
+ else {
627
+ plan.conflicts.push(from === "sets" && options.to === "environments"
628
+ ? `--environments must list the sets, in the order you want: ${lanes.join(", ")}.`
629
+ : `The project's ${from} name the lanes, so leave out --${from === "sets" ? "sets" : "environments"}.`);
630
+ return plan;
631
+ }
632
+ }
633
+ if (new Set(lanes).size !== lanes.length || lanes.some((lane) => !/^[\w-]+$/.test(lane))) {
634
+ plan.conflicts.push(`Lane names must be unique and use letters, numbers, _ or -: ${lanes.join(", ")}.`);
635
+ return plan;
636
+ }
637
+ if (options.to === "flat") {
638
+ if (!options.keep || !lanes.includes(options.keep)) {
639
+ plan.conflicts.push(`Name the lane to keep with --keep, one of: ${lanes.join(", ")}.`);
640
+ return plan;
641
+ }
642
+ plan.keep = options.keep;
643
+ }
644
+ else if (options.keep) {
645
+ plan.conflicts.push("--keep applies only to --to=flat.");
646
+ return plan;
647
+ }
648
+ if (options.exact) {
649
+ plan.conflicts.push("--exact applies only to --to=expressions.");
650
+ return plan;
651
+ }
652
+ const conversions = {
653
+ "environments:sets": () => environmentsToSets(builder, project),
654
+ "sets:environments": () => setsToEnvironments(builder, project),
655
+ "flat:environments": () => flatToEnvironments(builder, project),
656
+ "flat:sets": () => flatToSets(builder, project),
657
+ "environments:flat": () => environmentsToFlat(builder, project, options.keep),
658
+ "sets:flat": () => setsToFlat(builder, project, options.keep),
659
+ };
660
+ conversions[`${from}:${options.to}`]();
661
+ if (builder.rewritten.size > 0) {
662
+ plan.differences.push(`${[...builder.rewritten].join(", ")} are written as the parser writes them, since convert could not keep their own lines. Check them for comments.`);
663
+ }
664
+ if (builder.expanded.size > 0) {
665
+ plan.differences.push(`Aliases are written out in full in ${[...builder.expanded].join(", ")}, since lanes no longer share them.`);
666
+ }
667
+ return plan;
668
+ }
669
+ //# sourceMappingURL=plan.js.map