@featurevisor/core 3.1.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/lib/datasource/datasource.d.ts +1 -1
  2. package/lib/datasource/datasource.js +4 -14
  3. package/lib/datasource/datasource.js.map +1 -1
  4. package/lib/datasource/requiredFeatures.d.ts +7 -0
  5. package/lib/datasource/requiredFeatures.js +38 -0
  6. package/lib/datasource/requiredFeatures.js.map +1 -0
  7. package/lib/linter/checkCircularDependency.d.ts +1 -1
  8. package/lib/linter/checkCircularDependency.js +3 -22
  9. package/lib/linter/checkCircularDependency.js.map +1 -1
  10. package/lib/linter/conditionSchema.js +27 -3
  11. package/lib/linter/conditionSchema.js.map +1 -1
  12. package/lib/tester/testFeature.js +17 -16
  13. package/lib/tester/testFeature.js.map +1 -1
  14. package/package.json +10 -7
  15. package/CHANGELOG.md +0 -2246
  16. package/coverage/clover.xml +0 -5456
  17. package/coverage/coverage-final.json +0 -64
  18. package/coverage/lcov-report/base.css +0 -224
  19. package/coverage/lcov-report/block-navigation.js +0 -87
  20. package/coverage/lcov-report/favicon.png +0 -0
  21. package/coverage/lcov-report/index.html +0 -371
  22. package/coverage/lcov-report/prettify.css +0 -1
  23. package/coverage/lcov-report/prettify.js +0 -2
  24. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  25. package/coverage/lcov-report/sorter.js +0 -210
  26. package/coverage/lcov-report/src/assess-distribution/index.html +0 -116
  27. package/coverage/lcov-report/src/assess-distribution/index.ts.html +0 -754
  28. package/coverage/lcov-report/src/benchmark/index.html +0 -116
  29. package/coverage/lcov-report/src/benchmark/index.ts.html +0 -793
  30. package/coverage/lcov-report/src/builder/allocator.ts.html +0 -220
  31. package/coverage/lcov-report/src/builder/applyContextToConditions.ts.html +0 -502
  32. package/coverage/lcov-report/src/builder/applyContextToDatafile.ts.html +0 -772
  33. package/coverage/lcov-report/src/builder/applyContextToSegments.ts.html +0 -580
  34. package/coverage/lcov-report/src/builder/buildDatafile.ts.html +0 -2053
  35. package/coverage/lcov-report/src/builder/buildProject.ts.html +0 -1117
  36. package/coverage/lcov-report/src/builder/buildRuntimeDatafiles.ts.html +0 -256
  37. package/coverage/lcov-report/src/builder/getFeatureRanges.ts.html +0 -268
  38. package/coverage/lcov-report/src/builder/hashes.ts.html +0 -412
  39. package/coverage/lcov-report/src/builder/index.html +0 -311
  40. package/coverage/lcov-report/src/builder/index.ts.html +0 -91
  41. package/coverage/lcov-report/src/builder/mutateVariables.ts.html +0 -421
  42. package/coverage/lcov-report/src/builder/mutator.ts.html +0 -796
  43. package/coverage/lcov-report/src/builder/revision.ts.html +0 -151
  44. package/coverage/lcov-report/src/builder/traffic.ts.html +0 -661
  45. package/coverage/lcov-report/src/cli/cli.ts.html +0 -400
  46. package/coverage/lcov-report/src/cli/index.html +0 -131
  47. package/coverage/lcov-report/src/cli/plugins.ts.html +0 -214
  48. package/coverage/lcov-report/src/config/index.html +0 -131
  49. package/coverage/lcov-report/src/config/index.ts.html +0 -88
  50. package/coverage/lcov-report/src/config/projectConfig.ts.html +0 -925
  51. package/coverage/lcov-report/src/datasource/adapter.ts.html +0 -253
  52. package/coverage/lcov-report/src/datasource/datasource.ts.html +0 -1000
  53. package/coverage/lcov-report/src/datasource/filesystemAdapter.ts.html +0 -1576
  54. package/coverage/lcov-report/src/datasource/index.html +0 -161
  55. package/coverage/lcov-report/src/datasource/index.ts.html +0 -94
  56. package/coverage/lcov-report/src/evaluate/index.html +0 -116
  57. package/coverage/lcov-report/src/evaluate/index.ts.html +0 -814
  58. package/coverage/lcov-report/src/find-duplicate-segments/findDuplicateSegments.ts.html +0 -313
  59. package/coverage/lcov-report/src/find-duplicate-segments/index.html +0 -131
  60. package/coverage/lcov-report/src/find-duplicate-segments/index.ts.html +0 -307
  61. package/coverage/lcov-report/src/find-usage/index.html +0 -116
  62. package/coverage/lcov-report/src/find-usage/index.ts.html +0 -1780
  63. package/coverage/lcov-report/src/generate-code/index.html +0 -131
  64. package/coverage/lcov-report/src/generate-code/index.ts.html +0 -403
  65. package/coverage/lcov-report/src/generate-code/typescript.ts.html +0 -1909
  66. package/coverage/lcov-report/src/index.html +0 -131
  67. package/coverage/lcov-report/src/info/index.html +0 -116
  68. package/coverage/lcov-report/src/info/index.ts.html +0 -472
  69. package/coverage/lcov-report/src/init/index.html +0 -116
  70. package/coverage/lcov-report/src/init/index.ts.html +0 -280
  71. package/coverage/lcov-report/src/linter/attributeSchema.ts.html +0 -1963
  72. package/coverage/lcov-report/src/linter/checkCircularDependency.ts.html +0 -220
  73. package/coverage/lcov-report/src/linter/checkPercentageExceedingSlot.ts.html +0 -268
  74. package/coverage/lcov-report/src/linter/conditionSchema.ts.html +0 -2224
  75. package/coverage/lcov-report/src/linter/featureSchema.ts.html +0 -5851
  76. package/coverage/lcov-report/src/linter/groupSchema.ts.html +0 -226
  77. package/coverage/lcov-report/src/linter/index.html +0 -326
  78. package/coverage/lcov-report/src/linter/index.ts.html +0 -88
  79. package/coverage/lcov-report/src/linter/lintProject.ts.html +0 -2704
  80. package/coverage/lcov-report/src/linter/mutationNotation.ts.html +0 -1411
  81. package/coverage/lcov-report/src/linter/printError.ts.html +0 -289
  82. package/coverage/lcov-report/src/linter/schema.ts.html +0 -1558
  83. package/coverage/lcov-report/src/linter/segmentSchema.ts.html +0 -139
  84. package/coverage/lcov-report/src/linter/targetSchema.ts.html +0 -223
  85. package/coverage/lcov-report/src/linter/testSchema.ts.html +0 -529
  86. package/coverage/lcov-report/src/linter/zodHelpers.ts.html +0 -133
  87. package/coverage/lcov-report/src/list/index.html +0 -131
  88. package/coverage/lcov-report/src/list/index.ts.html +0 -2065
  89. package/coverage/lcov-report/src/list/matrix.ts.html +0 -721
  90. package/coverage/lcov-report/src/promoter/index.html +0 -116
  91. package/coverage/lcov-report/src/promoter/index.ts.html +0 -3883
  92. package/coverage/lcov-report/src/sets.ts.html +0 -313
  93. package/coverage/lcov-report/src/targeting.ts.html +0 -403
  94. package/coverage/lcov-report/src/tester/cliFormat.ts.html +0 -133
  95. package/coverage/lcov-report/src/tester/helpers.ts.html +0 -313
  96. package/coverage/lcov-report/src/tester/index.html +0 -206
  97. package/coverage/lcov-report/src/tester/prettyDuration.ts.html +0 -187
  98. package/coverage/lcov-report/src/tester/printTestResult.ts.html +0 -337
  99. package/coverage/lcov-report/src/tester/testFeature.ts.html +0 -1186
  100. package/coverage/lcov-report/src/tester/testProject.ts.html +0 -1018
  101. package/coverage/lcov-report/src/tester/testSegment.ts.html +0 -316
  102. package/coverage/lcov-report/src/utils/extractKeys.ts.html +0 -493
  103. package/coverage/lcov-report/src/utils/git.ts.html +0 -559
  104. package/coverage/lcov-report/src/utils/index.html +0 -161
  105. package/coverage/lcov-report/src/utils/index.ts.html +0 -94
  106. package/coverage/lcov-report/src/utils/pretty.ts.html +0 -121
  107. package/coverage/lcov.info +0 -11615
  108. package/jest.config.js +0 -22
  109. package/json-schema/README.md +0 -5
  110. package/json-schema/attribute.json +0 -40
  111. package/json-schema/feature.json +0 -394
  112. package/json-schema/segment.json +0 -137
  113. package/src/assess-distribution/index.ts +0 -223
  114. package/src/benchmark/index.ts +0 -236
  115. package/src/builder/allocator.spec.ts +0 -105
  116. package/src/builder/allocator.ts +0 -45
  117. package/src/builder/applyContextToConditions.spec.ts +0 -2677
  118. package/src/builder/applyContextToConditions.ts +0 -139
  119. package/src/builder/applyContextToDatafile.spec.ts +0 -2626
  120. package/src/builder/applyContextToDatafile.ts +0 -229
  121. package/src/builder/applyContextToSegments.spec.ts +0 -1593
  122. package/src/builder/applyContextToSegments.ts +0 -165
  123. package/src/builder/buildDatafile.spec.ts +0 -445
  124. package/src/builder/buildDatafile.ts +0 -656
  125. package/src/builder/buildProject.ts +0 -344
  126. package/src/builder/buildRuntimeDatafiles.ts +0 -57
  127. package/src/builder/getFeatureRanges.ts +0 -61
  128. package/src/builder/hashes.ts +0 -109
  129. package/src/builder/index.ts +0 -2
  130. package/src/builder/mutateVariables.spec.ts +0 -1179
  131. package/src/builder/mutateVariables.ts +0 -112
  132. package/src/builder/mutator.spec.ts +0 -413
  133. package/src/builder/mutator.ts +0 -237
  134. package/src/builder/revision.spec.ts +0 -22
  135. package/src/builder/revision.ts +0 -22
  136. package/src/builder/traffic.spec.ts +0 -946
  137. package/src/builder/traffic.ts +0 -192
  138. package/src/cli/cli.ts +0 -105
  139. package/src/cli/index.ts +0 -2
  140. package/src/cli/plugins.ts +0 -43
  141. package/src/config/index.ts +0 -1
  142. package/src/config/projectConfig.spec.ts +0 -194
  143. package/src/config/projectConfig.ts +0 -280
  144. package/src/datasource/adapter.ts +0 -56
  145. package/src/datasource/datasource.ts +0 -305
  146. package/src/datasource/filesystemAdapter.spec.ts +0 -212
  147. package/src/datasource/filesystemAdapter.ts +0 -497
  148. package/src/datasource/index.ts +0 -3
  149. package/src/dependencies.ts +0 -13
  150. package/src/evaluate/index.ts +0 -243
  151. package/src/find-duplicate-segments/findDuplicateSegments.ts +0 -76
  152. package/src/find-duplicate-segments/index.ts +0 -74
  153. package/src/find-usage/index.ts +0 -565
  154. package/src/generate-code/index.ts +0 -106
  155. package/src/generate-code/typescript.spec.ts +0 -214
  156. package/src/generate-code/typescript.ts +0 -608
  157. package/src/index.ts +0 -20
  158. package/src/info/index.ts +0 -129
  159. package/src/init/index.ts +0 -65
  160. package/src/linter/attributeSchema.spec.ts +0 -342
  161. package/src/linter/attributeSchema.ts +0 -626
  162. package/src/linter/checkCircularDependency.ts +0 -45
  163. package/src/linter/checkPercentageExceedingSlot.ts +0 -61
  164. package/src/linter/conditionSchema.spec.ts +0 -510
  165. package/src/linter/conditionSchema.ts +0 -713
  166. package/src/linter/featureSchema.spec.ts +0 -1985
  167. package/src/linter/featureSchema.ts +0 -1922
  168. package/src/linter/groupSchema.ts +0 -47
  169. package/src/linter/index.ts +0 -1
  170. package/src/linter/lintProject.spec.ts +0 -336
  171. package/src/linter/lintProject.ts +0 -873
  172. package/src/linter/mutationNotation.spec.ts +0 -704
  173. package/src/linter/mutationNotation.ts +0 -442
  174. package/src/linter/printError.ts +0 -68
  175. package/src/linter/schema.spec.ts +0 -690
  176. package/src/linter/schema.ts +0 -491
  177. package/src/linter/segmentSchema.spec.ts +0 -358
  178. package/src/linter/segmentSchema.ts +0 -18
  179. package/src/linter/targetSchema.spec.ts +0 -159
  180. package/src/linter/targetSchema.ts +0 -46
  181. package/src/linter/testSchema.spec.ts +0 -258
  182. package/src/linter/testSchema.ts +0 -148
  183. package/src/linter/zodHelpers.ts +0 -16
  184. package/src/list/index.spec.ts +0 -135
  185. package/src/list/index.ts +0 -660
  186. package/src/list/matrix.spec.ts +0 -49
  187. package/src/list/matrix.ts +0 -212
  188. package/src/promoter/index.spec.ts +0 -617
  189. package/src/promoter/index.ts +0 -1266
  190. package/src/sets.ts +0 -76
  191. package/src/targeting.spec.ts +0 -74
  192. package/src/targeting.ts +0 -106
  193. package/src/tester/cliFormat.ts +0 -16
  194. package/src/tester/helpers.spec.ts +0 -149
  195. package/src/tester/helpers.ts +0 -76
  196. package/src/tester/index.ts +0 -2
  197. package/src/tester/prettyDuration.ts +0 -34
  198. package/src/tester/printTestResult.ts +0 -84
  199. package/src/tester/testFeature.ts +0 -367
  200. package/src/tester/testProject.spec.ts +0 -50
  201. package/src/tester/testProject.ts +0 -311
  202. package/src/tester/testSegment.ts +0 -77
  203. package/src/utils/extractKeys.ts +0 -136
  204. package/src/utils/git.ts +0 -158
  205. package/src/utils/index.ts +0 -3
  206. package/src/utils/pretty.ts +0 -12
  207. package/tsconfig.cjs.json +0 -13
  208. package/tsconfig.typecheck.json +0 -9
@@ -1,212 +0,0 @@
1
- import * as fs from "fs";
2
- import * as os from "os";
3
- import * as path from "path";
4
-
5
- import { getProjectConfig } from "../config";
6
- import { Datasource } from "./datasource";
7
- import { getExistingStateFilePath } from "./filesystemAdapter";
8
-
9
- function writeFile(filePath: string, content: string) {
10
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
11
- fs.writeFileSync(filePath, content, "utf8");
12
- }
13
-
14
- function createProject(configBody: string) {
15
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "featurevisor-fs-adapter-"));
16
- writeFile(path.join(root, "featurevisor.config.js"), configBody);
17
-
18
- return root;
19
- }
20
-
21
- describe("core: filesystemAdapter", () => {
22
- it("lists generated datafiles as sorted relative paths", async () => {
23
- const root = createProject("module.exports = {};");
24
- writeFile(path.join(root, "datafiles", "production", "featurevisor-all.json"), "{}");
25
- writeFile(path.join(root, "datafiles", "staging", "nested", "featurevisor-web.json"), "abc");
26
- writeFile(path.join(root, "datafiles", "staging", "featurevisor-mobile.txt"), "abcd");
27
- writeFile(path.join(root, "datafiles", "REVISION"), "1");
28
- writeFile(path.join(root, "datafiles", ".DS_Store"), "");
29
-
30
- const datasource = new Datasource(getProjectConfig(root), root);
31
-
32
- await expect(datasource.listDatafiles()).resolves.toMatchObject([
33
- { path: "production/featurevisor-all.json", size: 2, gzipSize: expect.any(Number) },
34
- { path: "staging/featurevisor-mobile.txt", size: 4, gzipSize: expect.any(Number) },
35
- { path: "staging/nested/featurevisor-web.json", size: 3, gzipSize: expect.any(Number) },
36
- ]);
37
- });
38
-
39
- it("lists nested entity paths with dot namespace character by default", async () => {
40
- const root = createProject("module.exports = {};");
41
-
42
- writeFile(
43
- path.join(root, "features", "checkout", "page.yml"),
44
- [
45
- "description: Checkout page",
46
- "tags:",
47
- " - all",
48
- "bucketBy: userId",
49
- "rules:",
50
- " staging:",
51
- " - key: everyone",
52
- " segments: '*'",
53
- " percentage: 100",
54
- " production:",
55
- " - key: everyone",
56
- " segments: '*'",
57
- " percentage: 100",
58
- ].join("\n"),
59
- );
60
- writeFile(
61
- path.join(root, "segments", "countries", "germany.yml"),
62
- [
63
- "description: Germany",
64
- "conditions:",
65
- " - attribute: country",
66
- " operator: equals",
67
- " value: de",
68
- ].join("\n"),
69
- );
70
-
71
- const config = getProjectConfig(root);
72
- const datasource = new Datasource(config, root);
73
-
74
- await expect(datasource.listFeatures()).resolves.toEqual(["checkout.page"]);
75
- await expect(datasource.listSegments()).resolves.toEqual(["countries.germany"]);
76
- await datasource.writeTarget("apps.web", {
77
- description: "Web app",
78
- tags: ["all"],
79
- context: { platform: "web" },
80
- });
81
- await expect(datasource.listTargets()).resolves.toEqual(["apps.web"]);
82
- await expect(datasource.readTarget("apps.web")).resolves.toMatchObject({
83
- description: "Web app",
84
- tags: ["all"],
85
- });
86
- await datasource.deleteTarget("apps.web");
87
- await expect(datasource.listTargets()).resolves.toEqual([]);
88
- await expect(datasource.readFeature("checkout.page")).resolves.toMatchObject({
89
- description: "Checkout page",
90
- });
91
- });
92
-
93
- it("keeps slash-separated keys when namespaceCharacter is slash", async () => {
94
- const root = createProject('module.exports = { namespaceCharacter: "/" };');
95
-
96
- writeFile(
97
- path.join(root, "features", "checkout", "page.yml"),
98
- [
99
- "description: Checkout page",
100
- "tags:",
101
- " - all",
102
- "bucketBy: userId",
103
- "rules:",
104
- " staging:",
105
- " - key: everyone",
106
- " segments: '*'",
107
- " percentage: 100",
108
- " production:",
109
- " - key: everyone",
110
- " segments: '*'",
111
- " percentage: 100",
112
- ].join("\n"),
113
- );
114
-
115
- const config = getProjectConfig(root);
116
- const datasource = new Datasource(config, root);
117
-
118
- await expect(datasource.listFeatures()).resolves.toEqual(["checkout/page"]);
119
- await expect(datasource.readFeature("checkout/page")).resolves.toMatchObject({
120
- description: "Checkout page",
121
- });
122
- });
123
-
124
- it("lists sets and reads entities from selected set", async () => {
125
- const root = createProject("module.exports = { sets: true };");
126
-
127
- writeFile(
128
- path.join(root, "sets", "storefront", "features", "banner.yml"),
129
- [
130
- "key: banner",
131
- "description: Storefront banner",
132
- "tags:",
133
- " - all",
134
- "bucketBy: userId",
135
- "rules:",
136
- " staging:",
137
- " - key: everyone",
138
- " segments: '*'",
139
- " percentage: 100",
140
- " production:",
141
- " - key: everyone",
142
- " segments: '*'",
143
- " percentage: 100",
144
- ].join("\n"),
145
- );
146
-
147
- writeFile(
148
- path.join(root, "sets", "admin", "features", "banner.yml"),
149
- [
150
- "key: banner",
151
- "description: Admin banner",
152
- "tags:",
153
- " - all",
154
- "bucketBy: userId",
155
- "rules:",
156
- " staging:",
157
- " - key: everyone",
158
- " segments: '*'",
159
- " percentage: 0",
160
- " production:",
161
- " - key: everyone",
162
- " segments: '*'",
163
- " percentage: 0",
164
- ].join("\n"),
165
- );
166
-
167
- const config = getProjectConfig(root);
168
- const datasource = new Datasource(config, root);
169
-
170
- await expect(datasource.listSets()).resolves.toEqual(["admin", "storefront"]);
171
-
172
- const storefrontDatasource = datasource.forSet("storefront");
173
- const feature = await storefrontDatasource.readFeature("banner");
174
-
175
- expect(feature.description).toBe("Storefront banner");
176
- expect(storefrontDatasource.getSet()).toBe("storefront");
177
- expect(storefrontDatasource.getConfig().featuresDirectoryPath).toBe(
178
- path.join(root, "sets", "storefront", "features"),
179
- );
180
- expect(storefrontDatasource.getConfig().targetsDirectoryPath).toBe(
181
- path.join(root, "sets", "storefront", "targets"),
182
- );
183
- await storefrontDatasource.writeTarget("web", { description: "Storefront web" });
184
- await expect(storefrontDatasource.listTargets()).resolves.toEqual(["web"]);
185
- });
186
-
187
- it("writes compact state when prettyState is disabled", async () => {
188
- const root = createProject("module.exports = { prettyState: false };");
189
- const config = getProjectConfig(root);
190
- const datasource = new Datasource(config, root);
191
- const state = { features: {} };
192
-
193
- await datasource.writeState(false, state);
194
-
195
- expect(fs.readFileSync(getExistingStateFilePath(config, false), "utf8")).toBe(
196
- JSON.stringify(state),
197
- );
198
- });
199
-
200
- it("writes formatted state when prettyState is enabled", async () => {
201
- const root = createProject("module.exports = { prettyState: true };");
202
- const config = getProjectConfig(root);
203
- const datasource = new Datasource(config, root);
204
- const state = { features: {} };
205
-
206
- await datasource.writeState(false, state);
207
-
208
- expect(fs.readFileSync(getExistingStateFilePath(config, false), "utf8")).toBe(
209
- JSON.stringify(state, null, 2),
210
- );
211
- });
212
- });
@@ -1,497 +0,0 @@
1
- import * as fs from "fs";
2
- import * as path from "path";
3
- import { execSync, spawn } from "child_process";
4
- import { gzipSync } from "zlib";
5
-
6
- import type {
7
- ExistingState,
8
- EnvironmentKey,
9
- DatafileContent,
10
- EntityType,
11
- HistoryEntry,
12
- Commit,
13
- CommitHash,
14
- HistoryEntity,
15
- } from "@featurevisor/types";
16
- import type { CustomParser } from "@featurevisor/parsers";
17
-
18
- import { Adapter, DatafileFile, DatafileOptions } from "./adapter";
19
- import { ProjectConfig } from "../config";
20
- import { getCommit } from "../utils/git";
21
- import { CLI_COLOR_CYAN, CLI_COLOR_GREEN, colorize } from "../tester/cliFormat";
22
-
23
- export function getExistingStateFilePath(
24
- projectConfig: ProjectConfig,
25
- environment: EnvironmentKey | false,
26
- ): string {
27
- const fileName = environment ? `existing-state-${environment}.json` : `existing-state.json`;
28
-
29
- return path.join(projectConfig.stateDirectoryPath, fileName);
30
- }
31
-
32
- export function getRevisionFilePath(projectConfig: ProjectConfig): string {
33
- return path.join(projectConfig.stateDirectoryPath, projectConfig.revisionFileName);
34
- }
35
-
36
- export function getAllEntityFilePathsRecursively(directoryPath, extension?: string) {
37
- let entities: string[] = [];
38
-
39
- if (!fs.existsSync(directoryPath)) {
40
- return entities;
41
- }
42
-
43
- const files = fs.readdirSync(directoryPath);
44
-
45
- for (let i = 0; i < files.length; i++) {
46
- const file = files[i];
47
- const filePath = path.join(directoryPath, file);
48
-
49
- if (fs.statSync(filePath).isDirectory()) {
50
- entities = entities.concat(getAllEntityFilePathsRecursively(filePath, extension));
51
- } else if (!extension || file.endsWith(`.${extension}`)) {
52
- entities.push(filePath);
53
- }
54
- }
55
-
56
- return entities;
57
- }
58
-
59
- function isWithinDirectory(directoryPath: string, fileDirectoryPath: string): boolean {
60
- return (
61
- fileDirectoryPath === directoryPath || fileDirectoryPath.startsWith(directoryPath + path.sep)
62
- );
63
- }
64
-
65
- function getPathSegmentsFromKey(
66
- namespaceCharacter: string,
67
- key: string,
68
- entityType?: EntityType,
69
- ): string[] {
70
- const pathSegments = namespaceCharacter ? key.split(namespaceCharacter) : [key];
71
-
72
- if (
73
- entityType === "test" &&
74
- pathSegments.length > 1 &&
75
- ["spec", "feature", "segment"].includes(pathSegments[pathSegments.length - 1])
76
- ) {
77
- const suffix = pathSegments[pathSegments.length - 1];
78
- pathSegments[pathSegments.length - 2] = `${pathSegments[pathSegments.length - 2]}.${suffix}`;
79
- pathSegments.pop();
80
- }
81
-
82
- return pathSegments;
83
- }
84
-
85
- export class FilesystemAdapter extends Adapter {
86
- private parser: CustomParser;
87
-
88
- constructor(
89
- private config: ProjectConfig,
90
- private rootDirectoryPath?: string,
91
- ) {
92
- super();
93
-
94
- this.parser = config.parser as CustomParser;
95
- }
96
-
97
- getEntityDirectoryPath(entityType: EntityType): string {
98
- if (entityType === "feature") {
99
- return this.config.featuresDirectoryPath;
100
- } else if (entityType === "group") {
101
- return this.config.groupsDirectoryPath;
102
- } else if (entityType === "segment") {
103
- return this.config.segmentsDirectoryPath;
104
- } else if (entityType === "schema") {
105
- return this.config.schemasDirectoryPath;
106
- } else if (entityType === "target") {
107
- return this.config.targetsDirectoryPath;
108
- } else if (entityType === "test") {
109
- return this.config.testsDirectoryPath;
110
- }
111
-
112
- return this.config.attributesDirectoryPath;
113
- }
114
-
115
- async listSets(): Promise<string[]> {
116
- if (!this.config.sets || !fs.existsSync(this.config.setsDirectoryPath)) {
117
- return [];
118
- }
119
-
120
- const entries = await fs.promises.readdir(this.config.setsDirectoryPath, {
121
- withFileTypes: true,
122
- });
123
-
124
- return entries
125
- .filter((entry) => entry.isDirectory())
126
- .map((entry) => entry.name)
127
- .sort();
128
- }
129
-
130
- getEntityPath(entityType: EntityType, entityKey: string): string {
131
- const basePath = this.getEntityDirectoryPath(entityType);
132
- const pathSegments = getPathSegmentsFromKey(
133
- this.config.namespaceCharacter,
134
- entityKey,
135
- entityType,
136
- );
137
- return path.join(basePath, ...pathSegments) + `.${this.parser.extension}`;
138
- }
139
-
140
- async listEntities(entityType: EntityType): Promise<string[]> {
141
- const directoryPath = this.getEntityDirectoryPath(entityType);
142
- const filePaths = getAllEntityFilePathsRecursively(directoryPath, this.parser.extension);
143
-
144
- return (
145
- filePaths
146
- // keep only the files with the right extension
147
- .filter((filterPath) => filterPath.endsWith(`.${this.parser.extension}`))
148
-
149
- // remove the entity directory path from beginning
150
- .map((filePath) => filePath.replace(directoryPath + path.sep, ""))
151
-
152
- // remove the extension from the end
153
- .map((filterPath) => filterPath.replace(`.${this.parser.extension}`, ""))
154
-
155
- // take care of windows paths and apply namespace character
156
- .map((filterPath) => filterPath.split(path.sep).join(this.config.namespaceCharacter))
157
- );
158
- }
159
-
160
- async entityExists(entityType: EntityType, entityKey: string): Promise<boolean> {
161
- const entityPath = this.getEntityPath(entityType, entityKey);
162
-
163
- return fs.existsSync(entityPath);
164
- }
165
-
166
- async readEntity<T>(entityType: EntityType, entityKey: string): Promise<T> {
167
- const filePath = this.getEntityPath(entityType, entityKey);
168
- const entityContent = fs.readFileSync(filePath, "utf8");
169
-
170
- return this.parser.parse<T>(entityContent, filePath);
171
- }
172
-
173
- async writeEntity<T>(entityType: EntityType, entityKey: string, entity: T): Promise<T> {
174
- const filePath = this.getEntityPath(entityType, entityKey);
175
-
176
- if (!fs.existsSync(path.dirname(filePath))) {
177
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
178
- }
179
-
180
- fs.writeFileSync(filePath, this.parser.stringify(entity, filePath));
181
-
182
- return entity;
183
- }
184
-
185
- async deleteEntity(entityType: EntityType, entityKey: string): Promise<void> {
186
- const filePath = this.getEntityPath(entityType, entityKey);
187
-
188
- if (!fs.existsSync(filePath)) {
189
- return;
190
- }
191
-
192
- fs.unlinkSync(filePath);
193
- }
194
-
195
- /**
196
- * State
197
- */
198
- async readState(environment: EnvironmentKey): Promise<ExistingState> {
199
- const filePath = getExistingStateFilePath(this.config, environment);
200
-
201
- if (!fs.existsSync(filePath)) {
202
- return {
203
- features: {},
204
- };
205
- }
206
-
207
- return require(filePath);
208
- }
209
-
210
- async writeState(environment: EnvironmentKey, existingState: ExistingState) {
211
- const filePath = getExistingStateFilePath(this.config, environment);
212
-
213
- if (!fs.existsSync(this.config.stateDirectoryPath)) {
214
- fs.mkdirSync(this.config.stateDirectoryPath, { recursive: true });
215
- }
216
- fs.writeFileSync(
217
- filePath,
218
- this.config.prettyState
219
- ? JSON.stringify(existingState, null, 2)
220
- : JSON.stringify(existingState),
221
- );
222
- }
223
-
224
- /**
225
- * Revision
226
- */
227
- async readRevision(): Promise<string> {
228
- const filePath = getRevisionFilePath(this.config);
229
-
230
- if (fs.existsSync(filePath)) {
231
- return fs.readFileSync(filePath, "utf8");
232
- }
233
-
234
- return "0";
235
- }
236
-
237
- async writeRevision(revision: string): Promise<void> {
238
- const filePath = getRevisionFilePath(this.config);
239
-
240
- // write to state directory
241
- if (!fs.existsSync(this.config.stateDirectoryPath)) {
242
- fs.mkdirSync(this.config.stateDirectoryPath, { recursive: true });
243
- }
244
-
245
- fs.writeFileSync(filePath, revision);
246
-
247
- // write to datafiles directory, as part of the build process
248
- fs.writeFileSync(
249
- path.join(this.config.datafilesDirectoryPath, this.config.revisionFileName),
250
- revision,
251
- );
252
- }
253
-
254
- /**
255
- * Datafile
256
- */
257
- async listDatafiles(): Promise<DatafileFile[]> {
258
- const directoryPath = this.config.datafilesDirectoryPath;
259
-
260
- return getAllEntityFilePathsRecursively(directoryPath)
261
- .filter((filePath) => path.basename(filePath) !== this.config.revisionFileName)
262
- .filter((filePath) => !path.basename(filePath).startsWith("."))
263
- .map((filePath) => {
264
- const content = fs.readFileSync(filePath);
265
-
266
- return {
267
- path: path.relative(directoryPath, filePath).split(path.sep).join("/"),
268
- size: content.length,
269
- gzipSize: gzipSync(content).length,
270
- };
271
- })
272
- .sort((a, b) => a.path.localeCompare(b.path));
273
- }
274
-
275
- getDatafilePath(options: DatafileOptions): string {
276
- const pattern = this.config.datafileNamePattern || "featurevisor-%s.json";
277
-
278
- if (!options.target) {
279
- throw new Error("Datafile target is required.");
280
- }
281
-
282
- const targetPathSegments = options.target.split(this.config.namespaceCharacter);
283
- const targetFileKey = targetPathSegments.pop() || options.target;
284
- const fileName = pattern.replace("%s", targetFileKey);
285
- const targetDirectory = targetPathSegments.length > 0 ? path.join(...targetPathSegments) : "";
286
-
287
- const dir = options.datafilesDir || this.config.datafilesDirectoryPath;
288
-
289
- if (options.environment) {
290
- return path.join(dir, options.environment, targetDirectory, fileName);
291
- }
292
-
293
- return path.join(dir, targetDirectory, fileName);
294
- }
295
-
296
- async readDatafile(options: DatafileOptions): Promise<DatafileContent> {
297
- const filePath = this.getDatafilePath(options);
298
- const content = fs.readFileSync(filePath, "utf8");
299
- const datafileContent = JSON.parse(content);
300
-
301
- return datafileContent;
302
- }
303
-
304
- async writeDatafile(datafileContent: DatafileContent, options: DatafileOptions): Promise<void> {
305
- const dir = options.datafilesDir || this.config.datafilesDirectoryPath;
306
-
307
- const outputFilePath = this.getDatafilePath(options);
308
- fs.mkdirSync(path.dirname(outputFilePath), { recursive: true });
309
-
310
- fs.writeFileSync(
311
- outputFilePath,
312
- this.config.prettyDatafile
313
- ? JSON.stringify(datafileContent, null, 2)
314
- : JSON.stringify(datafileContent),
315
- );
316
-
317
- const root = path.resolve(dir, "..");
318
-
319
- const shortPath = outputFilePath.replace(root + path.sep, "");
320
- console.log(` ${colorize("✔", CLI_COLOR_GREEN)} ${colorize(shortPath, CLI_COLOR_CYAN)}`);
321
- }
322
-
323
- /**
324
- * History
325
- */
326
- async getRawHistory(pathPatterns: string[]): Promise<string> {
327
- const gitPaths = pathPatterns.join(" ");
328
-
329
- const logCommand = `git log --name-only --pretty=format:"%h|%an|%aI" --relative --no-merges -- ${gitPaths}`;
330
- const fullCommand = `(cd ${this.rootDirectoryPath} && ${logCommand})`;
331
-
332
- return new Promise(function (resolve, reject) {
333
- const child = spawn(fullCommand, { shell: true });
334
- let result = "";
335
-
336
- child.stdout.on("data", function (data) {
337
- result += data.toString();
338
- });
339
-
340
- child.stderr.on("data", function (data) {
341
- console.error(data.toString());
342
- });
343
-
344
- child.on("close", function (code) {
345
- if (code === 0) {
346
- resolve(result);
347
- } else {
348
- reject(code);
349
- }
350
- });
351
- });
352
- }
353
-
354
- getPathPatterns(entityType?: EntityType, entityKey?: string): string[] {
355
- let pathPatterns: string[] = [];
356
-
357
- if (entityType && entityKey) {
358
- pathPatterns = [this.getEntityPath(entityType, entityKey)];
359
- } else if (entityType) {
360
- if (entityType === "attribute") {
361
- pathPatterns = [this.config.attributesDirectoryPath];
362
- } else if (entityType === "segment") {
363
- pathPatterns = [this.config.segmentsDirectoryPath];
364
- } else if (entityType === "feature") {
365
- pathPatterns = [this.config.featuresDirectoryPath];
366
- } else if (entityType === "group") {
367
- pathPatterns = [this.config.groupsDirectoryPath];
368
- } else if (entityType === "schema") {
369
- pathPatterns = [this.config.schemasDirectoryPath];
370
- } else if (entityType === "target") {
371
- pathPatterns = [this.config.targetsDirectoryPath];
372
- } else if (entityType === "test") {
373
- pathPatterns = [this.config.testsDirectoryPath];
374
- }
375
- } else {
376
- pathPatterns = [
377
- this.config.featuresDirectoryPath,
378
- this.config.attributesDirectoryPath,
379
- this.config.segmentsDirectoryPath,
380
- this.config.groupsDirectoryPath,
381
- this.config.schemasDirectoryPath,
382
- this.config.targetsDirectoryPath,
383
- this.config.testsDirectoryPath,
384
- ];
385
- }
386
-
387
- return pathPatterns.map((p) => p.replace((this.rootDirectoryPath as string) + path.sep, ""));
388
- }
389
-
390
- async listHistoryEntries(entityType?: EntityType, entityKey?: string): Promise<HistoryEntry[]> {
391
- const pathPatterns = this.getPathPatterns(entityType, entityKey);
392
- const rawHistory = await this.getRawHistory(pathPatterns);
393
-
394
- const fullHistory: HistoryEntry[] = [];
395
- const blocks = rawHistory.split("\n\n");
396
-
397
- for (let i = 0; i < blocks.length; i++) {
398
- const block = blocks[i];
399
-
400
- if (block.length === 0) {
401
- continue;
402
- }
403
-
404
- const lines = block.split("\n");
405
-
406
- const commitLine = lines[0];
407
- const [commitHash, author, timestamp] = commitLine.split("|");
408
-
409
- const entities: HistoryEntity[] = [];
410
-
411
- const filePathLines = lines.slice(1);
412
- for (let j = 0; j < filePathLines.length; j++) {
413
- const relativePath = filePathLines[j];
414
- const absolutePath = path.join(this.rootDirectoryPath as string, relativePath);
415
- const fileName = absolutePath.split(path.sep).pop() as string;
416
- const relativeDir = path.dirname(absolutePath);
417
- const extensionWithDot = "." + this.parser.extension;
418
- const key = fileName.replace(extensionWithDot, "");
419
-
420
- let type: EntityType = "attribute";
421
- if (isWithinDirectory(this.config.attributesDirectoryPath, relativeDir)) {
422
- type = "attribute";
423
- } else if (isWithinDirectory(this.config.segmentsDirectoryPath, relativeDir)) {
424
- type = "segment";
425
- } else if (isWithinDirectory(this.config.featuresDirectoryPath, relativeDir)) {
426
- type = "feature";
427
- } else if (isWithinDirectory(this.config.groupsDirectoryPath, relativeDir)) {
428
- type = "group";
429
- } else if (isWithinDirectory(this.config.schemasDirectoryPath, relativeDir)) {
430
- type = "schema";
431
- } else if (isWithinDirectory(this.config.targetsDirectoryPath, relativeDir)) {
432
- type = "target";
433
- } else if (isWithinDirectory(this.config.testsDirectoryPath, relativeDir)) {
434
- type = "test";
435
- } else {
436
- continue;
437
- }
438
-
439
- if (type === "feature" || type === "target") {
440
- const entityDirectoryPath =
441
- type === "feature"
442
- ? this.config.featuresDirectoryPath
443
- : this.config.targetsDirectoryPath;
444
- const baseRelativePath = absolutePath
445
- .replace(entityDirectoryPath + path.sep, "")
446
- .replace(extensionWithDot, "")
447
- .split(path.sep)
448
- .join(this.config.namespaceCharacter);
449
-
450
- entities.push({
451
- type,
452
- key: baseRelativePath,
453
- });
454
-
455
- continue;
456
- }
457
-
458
- entities.push({
459
- type,
460
- key,
461
- });
462
- }
463
-
464
- if (entities.length === 0) {
465
- continue;
466
- }
467
-
468
- fullHistory.push({
469
- commit: commitHash,
470
- author,
471
- timestamp,
472
- entities,
473
- });
474
- }
475
-
476
- return fullHistory;
477
- }
478
-
479
- async readCommit(
480
- commitHash: CommitHash,
481
- entityType?: EntityType,
482
- entityKey?: string,
483
- ): Promise<Commit> {
484
- const pathPatterns = this.getPathPatterns(entityType, entityKey);
485
- const gitPaths = pathPatterns.join(" ");
486
- const logCommand = `git show ${commitHash} --relative -- ${gitPaths}`;
487
- const fullCommand = `(cd ${this.rootDirectoryPath} && ${logCommand})`;
488
-
489
- const gitShowOutput = execSync(fullCommand, { encoding: "utf8" }).toString();
490
- const commit = getCommit(gitShowOutput, {
491
- rootDirectoryPath: this.rootDirectoryPath as string,
492
- projectConfig: this.config,
493
- });
494
-
495
- return commit;
496
- }
497
- }