@featurevisor/core 3.0.1 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/lib/datasource/datasource.d.ts +1 -1
  2. package/lib/datasource/datasource.js +4 -14
  3. package/lib/datasource/datasource.js.map +1 -1
  4. package/lib/datasource/requiredFeatures.d.ts +7 -0
  5. package/lib/datasource/requiredFeatures.js +38 -0
  6. package/lib/datasource/requiredFeatures.js.map +1 -0
  7. package/lib/linter/checkCircularDependency.d.ts +1 -1
  8. package/lib/linter/checkCircularDependency.js +3 -22
  9. package/lib/linter/checkCircularDependency.js.map +1 -1
  10. package/lib/linter/conditionSchema.js +27 -3
  11. package/lib/linter/conditionSchema.js.map +1 -1
  12. package/lib/tester/testFeature.js +17 -16
  13. package/lib/tester/testFeature.js.map +1 -1
  14. package/package.json +10 -7
  15. package/CHANGELOG.md +0 -2238
  16. package/coverage/clover.xml +0 -5456
  17. package/coverage/coverage-final.json +0 -64
  18. package/coverage/lcov-report/base.css +0 -224
  19. package/coverage/lcov-report/block-navigation.js +0 -87
  20. package/coverage/lcov-report/favicon.png +0 -0
  21. package/coverage/lcov-report/index.html +0 -371
  22. package/coverage/lcov-report/prettify.css +0 -1
  23. package/coverage/lcov-report/prettify.js +0 -2
  24. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  25. package/coverage/lcov-report/sorter.js +0 -210
  26. package/coverage/lcov-report/src/assess-distribution/index.html +0 -116
  27. package/coverage/lcov-report/src/assess-distribution/index.ts.html +0 -754
  28. package/coverage/lcov-report/src/benchmark/index.html +0 -116
  29. package/coverage/lcov-report/src/benchmark/index.ts.html +0 -793
  30. package/coverage/lcov-report/src/builder/allocator.ts.html +0 -220
  31. package/coverage/lcov-report/src/builder/applyContextToConditions.ts.html +0 -502
  32. package/coverage/lcov-report/src/builder/applyContextToDatafile.ts.html +0 -772
  33. package/coverage/lcov-report/src/builder/applyContextToSegments.ts.html +0 -580
  34. package/coverage/lcov-report/src/builder/buildDatafile.ts.html +0 -2053
  35. package/coverage/lcov-report/src/builder/buildProject.ts.html +0 -1117
  36. package/coverage/lcov-report/src/builder/buildRuntimeDatafiles.ts.html +0 -256
  37. package/coverage/lcov-report/src/builder/getFeatureRanges.ts.html +0 -268
  38. package/coverage/lcov-report/src/builder/hashes.ts.html +0 -412
  39. package/coverage/lcov-report/src/builder/index.html +0 -311
  40. package/coverage/lcov-report/src/builder/index.ts.html +0 -91
  41. package/coverage/lcov-report/src/builder/mutateVariables.ts.html +0 -421
  42. package/coverage/lcov-report/src/builder/mutator.ts.html +0 -796
  43. package/coverage/lcov-report/src/builder/revision.ts.html +0 -151
  44. package/coverage/lcov-report/src/builder/traffic.ts.html +0 -661
  45. package/coverage/lcov-report/src/cli/cli.ts.html +0 -400
  46. package/coverage/lcov-report/src/cli/index.html +0 -131
  47. package/coverage/lcov-report/src/cli/plugins.ts.html +0 -214
  48. package/coverage/lcov-report/src/config/index.html +0 -131
  49. package/coverage/lcov-report/src/config/index.ts.html +0 -88
  50. package/coverage/lcov-report/src/config/projectConfig.ts.html +0 -925
  51. package/coverage/lcov-report/src/datasource/adapter.ts.html +0 -253
  52. package/coverage/lcov-report/src/datasource/datasource.ts.html +0 -1000
  53. package/coverage/lcov-report/src/datasource/filesystemAdapter.ts.html +0 -1576
  54. package/coverage/lcov-report/src/datasource/index.html +0 -161
  55. package/coverage/lcov-report/src/datasource/index.ts.html +0 -94
  56. package/coverage/lcov-report/src/evaluate/index.html +0 -116
  57. package/coverage/lcov-report/src/evaluate/index.ts.html +0 -814
  58. package/coverage/lcov-report/src/find-duplicate-segments/findDuplicateSegments.ts.html +0 -313
  59. package/coverage/lcov-report/src/find-duplicate-segments/index.html +0 -131
  60. package/coverage/lcov-report/src/find-duplicate-segments/index.ts.html +0 -307
  61. package/coverage/lcov-report/src/find-usage/index.html +0 -116
  62. package/coverage/lcov-report/src/find-usage/index.ts.html +0 -1780
  63. package/coverage/lcov-report/src/generate-code/index.html +0 -131
  64. package/coverage/lcov-report/src/generate-code/index.ts.html +0 -403
  65. package/coverage/lcov-report/src/generate-code/typescript.ts.html +0 -1909
  66. package/coverage/lcov-report/src/index.html +0 -131
  67. package/coverage/lcov-report/src/info/index.html +0 -116
  68. package/coverage/lcov-report/src/info/index.ts.html +0 -472
  69. package/coverage/lcov-report/src/init/index.html +0 -116
  70. package/coverage/lcov-report/src/init/index.ts.html +0 -280
  71. package/coverage/lcov-report/src/linter/attributeSchema.ts.html +0 -1963
  72. package/coverage/lcov-report/src/linter/checkCircularDependency.ts.html +0 -220
  73. package/coverage/lcov-report/src/linter/checkPercentageExceedingSlot.ts.html +0 -268
  74. package/coverage/lcov-report/src/linter/conditionSchema.ts.html +0 -2224
  75. package/coverage/lcov-report/src/linter/featureSchema.ts.html +0 -5851
  76. package/coverage/lcov-report/src/linter/groupSchema.ts.html +0 -226
  77. package/coverage/lcov-report/src/linter/index.html +0 -326
  78. package/coverage/lcov-report/src/linter/index.ts.html +0 -88
  79. package/coverage/lcov-report/src/linter/lintProject.ts.html +0 -2704
  80. package/coverage/lcov-report/src/linter/mutationNotation.ts.html +0 -1411
  81. package/coverage/lcov-report/src/linter/printError.ts.html +0 -289
  82. package/coverage/lcov-report/src/linter/schema.ts.html +0 -1558
  83. package/coverage/lcov-report/src/linter/segmentSchema.ts.html +0 -139
  84. package/coverage/lcov-report/src/linter/targetSchema.ts.html +0 -223
  85. package/coverage/lcov-report/src/linter/testSchema.ts.html +0 -529
  86. package/coverage/lcov-report/src/linter/zodHelpers.ts.html +0 -133
  87. package/coverage/lcov-report/src/list/index.html +0 -131
  88. package/coverage/lcov-report/src/list/index.ts.html +0 -2065
  89. package/coverage/lcov-report/src/list/matrix.ts.html +0 -721
  90. package/coverage/lcov-report/src/promoter/index.html +0 -116
  91. package/coverage/lcov-report/src/promoter/index.ts.html +0 -3883
  92. package/coverage/lcov-report/src/sets.ts.html +0 -313
  93. package/coverage/lcov-report/src/targeting.ts.html +0 -403
  94. package/coverage/lcov-report/src/tester/cliFormat.ts.html +0 -133
  95. package/coverage/lcov-report/src/tester/helpers.ts.html +0 -313
  96. package/coverage/lcov-report/src/tester/index.html +0 -206
  97. package/coverage/lcov-report/src/tester/prettyDuration.ts.html +0 -187
  98. package/coverage/lcov-report/src/tester/printTestResult.ts.html +0 -337
  99. package/coverage/lcov-report/src/tester/testFeature.ts.html +0 -1186
  100. package/coverage/lcov-report/src/tester/testProject.ts.html +0 -1018
  101. package/coverage/lcov-report/src/tester/testSegment.ts.html +0 -316
  102. package/coverage/lcov-report/src/utils/extractKeys.ts.html +0 -493
  103. package/coverage/lcov-report/src/utils/git.ts.html +0 -559
  104. package/coverage/lcov-report/src/utils/index.html +0 -161
  105. package/coverage/lcov-report/src/utils/index.ts.html +0 -94
  106. package/coverage/lcov-report/src/utils/pretty.ts.html +0 -121
  107. package/coverage/lcov.info +0 -11615
  108. package/jest.config.js +0 -22
  109. package/json-schema/README.md +0 -5
  110. package/json-schema/attribute.json +0 -40
  111. package/json-schema/feature.json +0 -394
  112. package/json-schema/segment.json +0 -137
  113. package/src/assess-distribution/index.ts +0 -223
  114. package/src/benchmark/index.ts +0 -236
  115. package/src/builder/allocator.spec.ts +0 -105
  116. package/src/builder/allocator.ts +0 -45
  117. package/src/builder/applyContextToConditions.spec.ts +0 -2677
  118. package/src/builder/applyContextToConditions.ts +0 -139
  119. package/src/builder/applyContextToDatafile.spec.ts +0 -2626
  120. package/src/builder/applyContextToDatafile.ts +0 -229
  121. package/src/builder/applyContextToSegments.spec.ts +0 -1593
  122. package/src/builder/applyContextToSegments.ts +0 -165
  123. package/src/builder/buildDatafile.spec.ts +0 -445
  124. package/src/builder/buildDatafile.ts +0 -656
  125. package/src/builder/buildProject.ts +0 -344
  126. package/src/builder/buildRuntimeDatafiles.ts +0 -57
  127. package/src/builder/getFeatureRanges.ts +0 -61
  128. package/src/builder/hashes.ts +0 -109
  129. package/src/builder/index.ts +0 -2
  130. package/src/builder/mutateVariables.spec.ts +0 -1179
  131. package/src/builder/mutateVariables.ts +0 -112
  132. package/src/builder/mutator.spec.ts +0 -413
  133. package/src/builder/mutator.ts +0 -237
  134. package/src/builder/revision.spec.ts +0 -22
  135. package/src/builder/revision.ts +0 -22
  136. package/src/builder/traffic.spec.ts +0 -946
  137. package/src/builder/traffic.ts +0 -192
  138. package/src/cli/cli.ts +0 -105
  139. package/src/cli/index.ts +0 -2
  140. package/src/cli/plugins.ts +0 -43
  141. package/src/config/index.ts +0 -1
  142. package/src/config/projectConfig.spec.ts +0 -194
  143. package/src/config/projectConfig.ts +0 -280
  144. package/src/datasource/adapter.ts +0 -56
  145. package/src/datasource/datasource.ts +0 -305
  146. package/src/datasource/filesystemAdapter.spec.ts +0 -212
  147. package/src/datasource/filesystemAdapter.ts +0 -497
  148. package/src/datasource/index.ts +0 -3
  149. package/src/dependencies.ts +0 -13
  150. package/src/evaluate/index.ts +0 -243
  151. package/src/find-duplicate-segments/findDuplicateSegments.ts +0 -76
  152. package/src/find-duplicate-segments/index.ts +0 -74
  153. package/src/find-usage/index.ts +0 -565
  154. package/src/generate-code/index.ts +0 -106
  155. package/src/generate-code/typescript.spec.ts +0 -214
  156. package/src/generate-code/typescript.ts +0 -608
  157. package/src/index.ts +0 -20
  158. package/src/info/index.ts +0 -129
  159. package/src/init/index.ts +0 -65
  160. package/src/linter/attributeSchema.spec.ts +0 -342
  161. package/src/linter/attributeSchema.ts +0 -626
  162. package/src/linter/checkCircularDependency.ts +0 -45
  163. package/src/linter/checkPercentageExceedingSlot.ts +0 -61
  164. package/src/linter/conditionSchema.spec.ts +0 -510
  165. package/src/linter/conditionSchema.ts +0 -713
  166. package/src/linter/featureSchema.spec.ts +0 -1985
  167. package/src/linter/featureSchema.ts +0 -1922
  168. package/src/linter/groupSchema.ts +0 -47
  169. package/src/linter/index.ts +0 -1
  170. package/src/linter/lintProject.spec.ts +0 -336
  171. package/src/linter/lintProject.ts +0 -873
  172. package/src/linter/mutationNotation.spec.ts +0 -704
  173. package/src/linter/mutationNotation.ts +0 -442
  174. package/src/linter/printError.ts +0 -68
  175. package/src/linter/schema.spec.ts +0 -690
  176. package/src/linter/schema.ts +0 -491
  177. package/src/linter/segmentSchema.spec.ts +0 -358
  178. package/src/linter/segmentSchema.ts +0 -18
  179. package/src/linter/targetSchema.spec.ts +0 -159
  180. package/src/linter/targetSchema.ts +0 -46
  181. package/src/linter/testSchema.spec.ts +0 -258
  182. package/src/linter/testSchema.ts +0 -148
  183. package/src/linter/zodHelpers.ts +0 -16
  184. package/src/list/index.spec.ts +0 -135
  185. package/src/list/index.ts +0 -660
  186. package/src/list/matrix.spec.ts +0 -49
  187. package/src/list/matrix.ts +0 -212
  188. package/src/promoter/index.spec.ts +0 -617
  189. package/src/promoter/index.ts +0 -1266
  190. package/src/sets.ts +0 -76
  191. package/src/targeting.spec.ts +0 -74
  192. package/src/targeting.ts +0 -106
  193. package/src/tester/cliFormat.ts +0 -16
  194. package/src/tester/helpers.spec.ts +0 -149
  195. package/src/tester/helpers.ts +0 -76
  196. package/src/tester/index.ts +0 -2
  197. package/src/tester/prettyDuration.ts +0 -34
  198. package/src/tester/printTestResult.ts +0 -84
  199. package/src/tester/testFeature.ts +0 -367
  200. package/src/tester/testProject.spec.ts +0 -50
  201. package/src/tester/testProject.ts +0 -311
  202. package/src/tester/testSegment.ts +0 -77
  203. package/src/utils/extractKeys.ts +0 -136
  204. package/src/utils/git.ts +0 -158
  205. package/src/utils/index.ts +0 -3
  206. package/src/utils/pretty.ts +0 -12
  207. package/tsconfig.cjs.json +0 -13
  208. package/tsconfig.typecheck.json +0 -9
@@ -1,1922 +0,0 @@
1
- import type { Schema, SchemaType } from "@featurevisor/types";
2
- import { z } from "zod";
3
-
4
- import { ProjectConfig } from "../config";
5
- import { isMutationKey, validateMutationKey } from "./mutationNotation";
6
- import {
7
- valueZodSchema,
8
- propertyTypeEnum,
9
- getSchemaZodSchema,
10
- refineEnumMatchesType,
11
- refineMinimumMaximum,
12
- refineStringLengthPattern,
13
- refineArrayItems,
14
- } from "./schema";
15
- import { refineWithMessage } from "./zodHelpers";
16
-
17
- function isArrayOfStrings(value: unknown): value is string[] {
18
- return Array.isArray(value) && value.every((v) => typeof v === "string");
19
- }
20
-
21
- function isFlatObjectValue(value: unknown): boolean {
22
- return (
23
- value === null ||
24
- typeof value === "string" ||
25
- typeof value === "number" ||
26
- typeof value === "boolean"
27
- );
28
- }
29
-
30
- function getVariableLabel(variableSchema, variableKey, path) {
31
- return (
32
- variableKey ??
33
- variableSchema?.key ??
34
- (path.length > 0 ? String(path[path.length - 1]) : "variable")
35
- );
36
- }
37
-
38
- /**
39
- * Resolve variable schema to the Schema used for value validation.
40
- * When variable has `schema` (reference), returns the parsed Schema from schemasByKey; otherwise returns the inline variable schema.
41
- */
42
- function resolveVariableSchema(
43
- variableSchema: {
44
- schema?: string;
45
- type?: string;
46
- items?: unknown;
47
- properties?: unknown;
48
- additionalProperties?: unknown;
49
- required?: string[];
50
- enum?: unknown[];
51
- const?: unknown;
52
- oneOf?: unknown[];
53
- minimum?: number;
54
- maximum?: number;
55
- minLength?: number;
56
- maxLength?: number;
57
- pattern?: string;
58
- minItems?: number;
59
- maxItems?: number;
60
- uniqueItems?: boolean;
61
- },
62
- schemasByKey?: Record<string, Schema>,
63
- ): {
64
- type?: string;
65
- items?: unknown;
66
- properties?: unknown;
67
- additionalProperties?: unknown;
68
- required?: string[];
69
- enum?: unknown[];
70
- const?: unknown;
71
- oneOf?: unknown[];
72
- minimum?: number;
73
- maximum?: number;
74
- minLength?: number;
75
- maxLength?: number;
76
- pattern?: string;
77
- minItems?: number;
78
- maxItems?: number;
79
- uniqueItems?: boolean;
80
- } | null {
81
- if (variableSchema.schema) {
82
- return schemasByKey?.[variableSchema.schema] ?? null;
83
- }
84
- return variableSchema as {
85
- type?: string;
86
- items?: unknown;
87
- properties?: unknown;
88
- additionalProperties?: unknown;
89
- required?: string[];
90
- enum?: unknown[];
91
- const?: unknown;
92
- oneOf?: unknown[];
93
- minimum?: number;
94
- maximum?: number;
95
- minLength?: number;
96
- maxLength?: number;
97
- pattern?: string;
98
- minItems?: number;
99
- maxItems?: number;
100
- uniqueItems?: boolean;
101
- };
102
- }
103
-
104
- /** Resolve a schema by following schema references (schema: key). Used for nested schemas that may have oneOf. */
105
- function resolveSchemaRefs(
106
- schema: { schema?: string; [k: string]: unknown },
107
- schemasByKey?: Record<string, Schema>,
108
- ): { [k: string]: unknown } {
109
- if (schema.schema && schemasByKey?.[schema.schema]) {
110
- return resolveSchemaRefs(
111
- schemasByKey[schema.schema] as { schema?: string; [k: string]: unknown },
112
- schemasByKey,
113
- );
114
- }
115
- return schema;
116
- }
117
-
118
- /**
119
- * Returns true if the value matches the given schema (const, enum, type, object properties, array items, or exactly one of oneOf).
120
- * Used for oneOf validation: value must match exactly one branch.
121
- */
122
- function valueMatchesSchema(
123
- schema: { [k: string]: unknown },
124
- value: unknown,
125
- schemasByKey?: Record<string, Schema>,
126
- ): boolean {
127
- const resolved = resolveSchemaRefs(schema, schemasByKey) as {
128
- type?: string;
129
- const?: unknown;
130
- enum?: unknown[];
131
- oneOf?: unknown[];
132
- properties?: Record<string, unknown>;
133
- additionalProperties?: unknown;
134
- required?: string[];
135
- items?: unknown;
136
- minimum?: number;
137
- maximum?: number;
138
- minLength?: number;
139
- maxLength?: number;
140
- pattern?: string;
141
- minItems?: number;
142
- maxItems?: number;
143
- uniqueItems?: boolean;
144
- };
145
-
146
- if (resolved.oneOf && Array.isArray(resolved.oneOf) && resolved.oneOf.length > 0) {
147
- const matchCount = resolved.oneOf.filter((branch) =>
148
- valueMatchesSchema(branch as { [k: string]: unknown }, value, schemasByKey),
149
- ).length;
150
- return matchCount === 1;
151
- }
152
-
153
- if (resolved.const !== undefined) {
154
- return valueDeepEqual(value, resolved.const);
155
- }
156
-
157
- if (resolved.enum !== undefined && Array.isArray(resolved.enum)) {
158
- return resolved.enum.some((e) => valueDeepEqual(value, e));
159
- }
160
-
161
- const type = resolved.type;
162
- if (!type) return false;
163
-
164
- if (type === "string") {
165
- if (typeof value !== "string") return false;
166
- const s = value as string;
167
- if (resolved.minLength !== undefined && s.length < resolved.minLength) return false;
168
- if (resolved.maxLength !== undefined && s.length > resolved.maxLength) return false;
169
- if (resolved.pattern !== undefined) {
170
- try {
171
- if (!new RegExp(resolved.pattern).test(s)) return false;
172
- } catch {
173
- return true;
174
- }
175
- }
176
- return true;
177
- }
178
- if (type === "boolean") return typeof value === "boolean";
179
- if (type === "integer") {
180
- if (typeof value !== "number" || !Number.isInteger(value)) return false;
181
- if (resolved.minimum !== undefined && (value as number) < resolved.minimum) return false;
182
- if (resolved.maximum !== undefined && (value as number) > resolved.maximum) return false;
183
- return true;
184
- }
185
- if (type === "double") {
186
- if (typeof value !== "number") return false;
187
- if (resolved.minimum !== undefined && (value as number) < resolved.minimum) return false;
188
- if (resolved.maximum !== undefined && (value as number) > resolved.maximum) return false;
189
- return true;
190
- }
191
- if (type === "json") return typeof value === "string";
192
-
193
- if (type === "object") {
194
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
195
- const props = resolved.properties;
196
- const additional = resolved.additionalProperties;
197
- const obj = value as Record<string, unknown>;
198
- if ((!props || typeof props !== "object") && (!additional || typeof additional !== "object")) {
199
- return true;
200
- }
201
- if (!props || typeof props !== "object") {
202
- return Object.keys(obj).every((key) =>
203
- valueMatchesSchema(additional as { [k: string]: unknown }, obj[key], schemasByKey),
204
- );
205
- }
206
- const required = new Set(resolved.required || []);
207
- for (const key of required) {
208
- if (!Object.prototype.hasOwnProperty.call(obj, key)) return false;
209
- if (!valueMatchesSchema(props[key] as { [k: string]: unknown }, obj[key], schemasByKey))
210
- return false;
211
- }
212
- for (const key of Object.keys(obj)) {
213
- const propSchema = props[key];
214
- if (propSchema) {
215
- if (!valueMatchesSchema(propSchema as { [k: string]: unknown }, obj[key], schemasByKey))
216
- return false;
217
- } else if (additional && typeof additional === "object") {
218
- if (!valueMatchesSchema(additional as { [k: string]: unknown }, obj[key], schemasByKey))
219
- return false;
220
- } else {
221
- return false;
222
- }
223
- }
224
- return true;
225
- }
226
-
227
- if (type === "array") {
228
- if (!Array.isArray(value)) return false;
229
- const arr = value as unknown[];
230
- if (resolved.minItems !== undefined && arr.length < resolved.minItems) return false;
231
- if (resolved.maxItems !== undefined && arr.length > resolved.maxItems) return false;
232
- if (resolved.uniqueItems) {
233
- for (let i = 0; i < arr.length; i++) {
234
- for (let j = i + 1; j < arr.length; j++) {
235
- if (valueDeepEqual(arr[i], arr[j])) return false;
236
- }
237
- }
238
- }
239
- const itemSchema = resolved.items;
240
- if (!itemSchema || typeof itemSchema !== "object")
241
- return arr.every((v) => typeof v === "string");
242
- return arr.every((item) =>
243
- valueMatchesSchema(itemSchema as { [k: string]: unknown }, item, schemasByKey),
244
- );
245
- }
246
-
247
- return false;
248
- }
249
-
250
- /** Deep equality for variable values (primitives, plain objects, arrays). */
251
- function valueDeepEqual(a: unknown, b: unknown): boolean {
252
- if (a === b) return true;
253
- if (typeof a !== typeof b) return false;
254
- if (a === null || b === null) return a === b;
255
- if (typeof a === "object" && typeof b === "object") {
256
- if (Array.isArray(a) !== Array.isArray(b)) return false;
257
- if (Array.isArray(a) && Array.isArray(b)) {
258
- if (a.length !== b.length) return false;
259
- return a.every((v, i) => valueDeepEqual(v, b[i]));
260
- }
261
- const keysA = Object.keys(a as object).sort();
262
- const keysB = Object.keys(b as object).sort();
263
- if (keysA.length !== keysB.length || keysA.some((k, i) => k !== keysB[i])) return false;
264
- return keysA.every((k) =>
265
- valueDeepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),
266
- );
267
- }
268
- return false;
269
- }
270
-
271
- type SchemaLikeForRequired = {
272
- type?: string;
273
- properties?: Record<string, unknown>;
274
- additionalProperties?: unknown;
275
- required?: string[];
276
- items?: unknown;
277
- schema?: string;
278
- oneOf?: unknown[];
279
- };
280
-
281
- /**
282
- * Recursively validates that every `required` array (at this level and in nested
283
- * object/array schemas) only contains keys that exist in the same level's `properties`.
284
- * Adds Zod issues with the correct path for invalid required field names.
285
- * When schemasByKey is provided, resolves schema references (schema: key) so that
286
- * referenced and nested schemas are validated too.
287
- */
288
- function refineRequiredKeysInSchema(
289
- schema: SchemaLikeForRequired,
290
- pathPrefix: (string | number)[],
291
- ctx: z.RefinementCtx,
292
- schemasByKey?: Record<string, Schema>,
293
- ): void {
294
- if (!schema || typeof schema !== "object") return;
295
-
296
- // Resolve schema reference so we validate the referenced schema (and can recurse into it)
297
- let current: SchemaLikeForRequired = schema;
298
- if (schema.schema && schemasByKey?.[schema.schema]) {
299
- current = schemasByKey[schema.schema] as SchemaLikeForRequired;
300
- refineRequiredKeysInSchema(current, pathPrefix, ctx, schemasByKey);
301
- return;
302
- }
303
-
304
- const effectiveType = current.type;
305
- const properties = current.properties;
306
- const required = current.required;
307
- const items = current.items;
308
-
309
- if (
310
- effectiveType === "object" &&
311
- Array.isArray(required) &&
312
- required.length > 0 &&
313
- properties &&
314
- typeof properties === "object"
315
- ) {
316
- const allowedKeys = Object.keys(properties);
317
- required.forEach((key, index) => {
318
- if (!allowedKeys.includes(key)) {
319
- ctx.addIssue({
320
- code: z.ZodIssueCode.custom,
321
- message: `Unknown required field "${key}". \`required\` must only contain property names defined in \`properties\`. Allowed: ${allowedKeys.length ? allowedKeys.join(", ") : "(none)"}.`,
322
- path: [...pathPrefix, "required", index],
323
- });
324
- }
325
- });
326
- }
327
-
328
- if (properties && typeof properties === "object") {
329
- for (const key of Object.keys(properties)) {
330
- const nested = properties[key];
331
- if (nested && typeof nested === "object") {
332
- refineRequiredKeysInSchema(
333
- nested as SchemaLikeForRequired,
334
- [...pathPrefix, "properties", key],
335
- ctx,
336
- schemasByKey,
337
- );
338
- }
339
- }
340
- }
341
- const additionalProperties = (current as { additionalProperties?: unknown }).additionalProperties;
342
- if (
343
- additionalProperties &&
344
- typeof additionalProperties === "object" &&
345
- !Array.isArray(additionalProperties)
346
- ) {
347
- refineRequiredKeysInSchema(
348
- additionalProperties as SchemaLikeForRequired,
349
- [...pathPrefix, "additionalProperties"],
350
- ctx,
351
- schemasByKey,
352
- );
353
- }
354
-
355
- if (items && typeof items === "object" && !Array.isArray(items)) {
356
- refineRequiredKeysInSchema(
357
- items as SchemaLikeForRequired,
358
- [...pathPrefix, "items"],
359
- ctx,
360
- schemasByKey,
361
- );
362
- }
363
-
364
- const oneOf = (current as { oneOf?: unknown[] }).oneOf;
365
- if (oneOf && Array.isArray(oneOf)) {
366
- oneOf.forEach((branch, i) => {
367
- if (branch && typeof branch === "object") {
368
- refineRequiredKeysInSchema(
369
- branch as SchemaLikeForRequired,
370
- [...pathPrefix, "oneOf", i],
371
- ctx,
372
- schemasByKey,
373
- );
374
- }
375
- });
376
- }
377
- }
378
-
379
- function typeOfValue(value: unknown): string {
380
- if (value === null) return "null";
381
- if (value === undefined) return "undefined";
382
- if (Array.isArray(value)) return "array";
383
- return typeof value;
384
- }
385
-
386
- /**
387
- * Validates a variable value against an array schema. Recursively validates each item
388
- * when the schema defines `items` (nested arrays/objects use the same refinement).
389
- * Enforces minItems, maxItems, and uniqueItems when set.
390
- */
391
- function refineVariableValueArray(
392
- projectConfig: ProjectConfig,
393
- variableSchema: {
394
- items?: unknown;
395
- type: string;
396
- minItems?: number;
397
- maxItems?: number;
398
- uniqueItems?: boolean;
399
- },
400
- variableValue: unknown[],
401
- path: (string | number)[],
402
- ctx: z.RefinementCtx,
403
- variableKey?: string,
404
- schemasByKey?: Record<string, Schema>,
405
- ): void {
406
- const label = getVariableLabel(variableSchema, variableKey, path);
407
- const minItems = variableSchema.minItems;
408
- const maxItems = variableSchema.maxItems;
409
- const uniqueItems = variableSchema.uniqueItems;
410
- if (minItems !== undefined && variableValue.length < minItems) {
411
- ctx.addIssue({
412
- code: z.ZodIssueCode.custom,
413
- message: `Variable "${label}" (type array) length (${variableValue.length}) is less than \`minItems\` (${minItems}).`,
414
- path,
415
- });
416
- }
417
- if (maxItems !== undefined && variableValue.length > maxItems) {
418
- ctx.addIssue({
419
- code: z.ZodIssueCode.custom,
420
- message: `Variable "${label}" (type array) length (${variableValue.length}) is greater than \`maxItems\` (${maxItems}).`,
421
- path,
422
- });
423
- }
424
- if (uniqueItems) {
425
- for (let i = 0; i < variableValue.length; i++) {
426
- for (let j = i + 1; j < variableValue.length; j++) {
427
- if (valueDeepEqual(variableValue[i], variableValue[j])) {
428
- ctx.addIssue({
429
- code: z.ZodIssueCode.custom,
430
- message: `Variable "${label}" (type array) has duplicate items at indices ${i} and ${j} but \`uniqueItems\` is true.`,
431
- path,
432
- });
433
- break;
434
- }
435
- }
436
- }
437
- }
438
- const itemSchema = variableSchema.items;
439
-
440
- if (itemSchema) {
441
- variableValue.forEach((item, index) => {
442
- superRefineVariableValue(
443
- projectConfig,
444
- itemSchema,
445
- item,
446
- [...path, index],
447
- ctx,
448
- variableKey,
449
- schemasByKey,
450
- );
451
- });
452
- } else {
453
- if (!isArrayOfStrings(variableValue)) {
454
- ctx.addIssue({
455
- code: z.ZodIssueCode.custom,
456
- message: `Variable "${label}" (type array): when \`items\` is not set, array must contain only strings; found non-string element.`,
457
- path,
458
- });
459
- }
460
- }
461
-
462
- if (projectConfig.maxVariableArrayStringifiedLength) {
463
- const stringified = JSON.stringify(variableValue);
464
- if (stringified.length > projectConfig.maxVariableArrayStringifiedLength) {
465
- ctx.addIssue({
466
- code: z.ZodIssueCode.custom,
467
- message: `Variable "${label}" array is too long (${stringified.length} characters), max length is ${projectConfig.maxVariableArrayStringifiedLength}`,
468
- path,
469
- });
470
- }
471
- }
472
- }
473
-
474
- /**
475
- * Validates a variable value against an object schema. Recursively validates each property
476
- * when the schema defines `properties` (nested objects/arrays use the same refinement).
477
- */
478
- function refineVariableValueObject(
479
- projectConfig: ProjectConfig,
480
- variableSchema: {
481
- properties?: Record<string, unknown>;
482
- additionalProperties?: unknown;
483
- required?: string[];
484
- type: string;
485
- },
486
- variableValue: Record<string, unknown>,
487
- path: (string | number)[],
488
- ctx: z.RefinementCtx,
489
- variableKey?: string,
490
- schemasByKey?: Record<string, Schema>,
491
- ): void {
492
- const label = getVariableLabel(variableSchema, variableKey, path);
493
- const schemaProperties = variableSchema.properties;
494
- const additionalProperties = variableSchema.additionalProperties;
495
-
496
- if (schemaProperties && typeof schemaProperties === "object") {
497
- const requiredKeys =
498
- variableSchema.required && variableSchema.required.length > 0
499
- ? variableSchema.required.filter((k) =>
500
- Object.prototype.hasOwnProperty.call(schemaProperties, k),
501
- )
502
- : Object.keys(schemaProperties);
503
-
504
- for (const key of requiredKeys) {
505
- if (!Object.prototype.hasOwnProperty.call(variableValue, key)) {
506
- ctx.addIssue({
507
- code: z.ZodIssueCode.custom,
508
- message: `Missing required property "${key}" in variable "${label}"`,
509
- path: [...path, key],
510
- });
511
- }
512
- }
513
-
514
- for (const key of Object.keys(variableValue)) {
515
- const propSchema = schemaProperties[key];
516
- if (!propSchema && additionalProperties && typeof additionalProperties === "object") {
517
- superRefineVariableValue(
518
- projectConfig,
519
- additionalProperties as Parameters<typeof superRefineVariableValue>[1],
520
- variableValue[key],
521
- [...path, key],
522
- ctx,
523
- key,
524
- schemasByKey,
525
- );
526
- } else if (!propSchema) {
527
- ctx.addIssue({
528
- code: z.ZodIssueCode.custom,
529
- message: `Unknown property "${key}" in variable "${label}" (not in schema)`,
530
- path: [...path, key],
531
- });
532
- } else {
533
- superRefineVariableValue(
534
- projectConfig,
535
- propSchema,
536
- variableValue[key],
537
- [...path, key],
538
- ctx,
539
- key,
540
- schemasByKey,
541
- );
542
- }
543
- }
544
- } else if (additionalProperties && typeof additionalProperties === "object") {
545
- for (const key of Object.keys(variableValue)) {
546
- superRefineVariableValue(
547
- projectConfig,
548
- additionalProperties as Parameters<typeof superRefineVariableValue>[1],
549
- variableValue[key],
550
- [...path, key],
551
- ctx,
552
- key,
553
- schemasByKey,
554
- );
555
- }
556
- } else {
557
- for (const key of Object.keys(variableValue)) {
558
- const propValue = variableValue[key];
559
- if (!isFlatObjectValue(propValue)) {
560
- ctx.addIssue({
561
- code: z.ZodIssueCode.custom,
562
- message: `Variable "${label}" is a flat object (no \`properties\` in schema); property "${key}" must be a primitive (string, number, boolean, or null), got: ${typeof propValue}`,
563
- path: [...path, key],
564
- });
565
- }
566
- }
567
- }
568
-
569
- if (projectConfig.maxVariableObjectStringifiedLength) {
570
- const stringified = JSON.stringify(variableValue);
571
- if (stringified.length > projectConfig.maxVariableObjectStringifiedLength) {
572
- ctx.addIssue({
573
- code: z.ZodIssueCode.custom,
574
- message: `Variable "${label}" object is too long (${stringified.length} characters), max length is ${projectConfig.maxVariableObjectStringifiedLength}`,
575
- path,
576
- });
577
- }
578
- }
579
- }
580
-
581
- /** Schema or variable schema (e.g. type "json", defaultValue); used for value validation. */
582
- type VariableSchemaLike =
583
- | (Omit<Schema, "type"> & { type?: SchemaType | "json" })
584
- | null
585
- | undefined;
586
-
587
- function superRefineVariableValue(
588
- projectConfig: ProjectConfig,
589
- variableSchema: VariableSchemaLike,
590
- variableValue: unknown,
591
- path: (string | number)[],
592
- ctx: z.RefinementCtx,
593
- variableKey?: string,
594
- schemasByKey?: Record<string, Schema>,
595
- ): void {
596
- const label = getVariableLabel(variableSchema, variableKey, path);
597
-
598
- if (!variableSchema) {
599
- const variableName =
600
- path.length > 0 && typeof path[path.length - 1] === "string"
601
- ? String(path[path.length - 1])
602
- : "variable";
603
- const message = `Variable "${variableName}" is used but not defined in variablesSchema. Define it under variablesSchema first, then use it here.`;
604
-
605
- ctx.addIssue({
606
- code: z.ZodIssueCode.custom,
607
- message,
608
- path,
609
- });
610
-
611
- return;
612
- }
613
-
614
- const effectiveSchema = resolveVariableSchema(variableSchema, schemasByKey);
615
- if (variableSchema.schema && effectiveSchema === null) {
616
- ctx.addIssue({
617
- code: z.ZodIssueCode.custom,
618
- message: `Schema "${variableSchema.schema}" could not be loaded for value validation.`,
619
- path,
620
- });
621
- return;
622
- }
623
-
624
- if (!effectiveSchema) {
625
- return;
626
- }
627
-
628
- const effectiveOneOf = (effectiveSchema as { oneOf?: unknown[] }).oneOf;
629
- if (effectiveOneOf !== undefined && Array.isArray(effectiveOneOf) && effectiveOneOf.length > 0) {
630
- const matchCount = effectiveOneOf.filter((branch) =>
631
- valueMatchesSchema(branch as { [k: string]: unknown }, variableValue, schemasByKey),
632
- ).length;
633
- if (matchCount === 0) {
634
- ctx.addIssue({
635
- code: z.ZodIssueCode.custom,
636
- message: `Variable "${label}" must match exactly one of the \`oneOf\` schemas (got ${JSON.stringify(variableValue)}; matched none).`,
637
- path,
638
- });
639
- } else if (matchCount > 1) {
640
- ctx.addIssue({
641
- code: z.ZodIssueCode.custom,
642
- message: `Variable "${label}" must match exactly one of the \`oneOf\` schemas (matched ${matchCount}).`,
643
- path,
644
- });
645
- }
646
- return;
647
- }
648
-
649
- const effectiveConst = (effectiveSchema as { const?: unknown }).const;
650
- if (effectiveConst !== undefined) {
651
- if (!valueDeepEqual(variableValue, effectiveConst)) {
652
- ctx.addIssue({
653
- code: z.ZodIssueCode.custom,
654
- message: `Variable "${label}" must equal the constant value defined in schema (got ${JSON.stringify(variableValue)}).`,
655
- path,
656
- });
657
- }
658
- return;
659
- }
660
-
661
- const effectiveEnum = (effectiveSchema as { enum?: unknown[] }).enum;
662
- if (effectiveEnum !== undefined && Array.isArray(effectiveEnum) && effectiveEnum.length > 0) {
663
- const allowed = effectiveEnum.some((v) => valueDeepEqual(variableValue, v));
664
- if (!allowed) {
665
- ctx.addIssue({
666
- code: z.ZodIssueCode.custom,
667
- message: `Variable "${label}" must be one of the allowed enum values (got ${JSON.stringify(variableValue)}).`,
668
- path,
669
- });
670
- }
671
- return;
672
- }
673
-
674
- // Require a value (no undefined) for every variable usage
675
- if (variableValue === undefined) {
676
- ctx.addIssue({
677
- code: z.ZodIssueCode.custom,
678
- message: `Variable "${label}" value is required (got undefined).`,
679
- path,
680
- });
681
- return;
682
- }
683
-
684
- const expectedType = effectiveSchema.type;
685
- const gotType = typeOfValue(variableValue);
686
-
687
- // string — only string allowed; schema minLength/maxLength/pattern applied when set
688
- if (expectedType === "string") {
689
- if (typeof variableValue !== "string") {
690
- ctx.addIssue({
691
- code: z.ZodIssueCode.custom,
692
- message: `Variable "${label}" (type string) must be a string; got ${gotType}.`,
693
- path,
694
- });
695
- return;
696
- }
697
-
698
- const strMinLen = (effectiveSchema as { minLength?: number }).minLength;
699
- const strMaxLen = (effectiveSchema as { maxLength?: number }).maxLength;
700
- const strPattern = (effectiveSchema as { pattern?: string }).pattern;
701
- if (strMinLen !== undefined && variableValue.length < strMinLen) {
702
- ctx.addIssue({
703
- code: z.ZodIssueCode.custom,
704
- message: `Variable "${label}" (type string) length (${variableValue.length}) is less than \`minLength\` (${strMinLen}).`,
705
- path,
706
- });
707
- }
708
- if (strMaxLen !== undefined && variableValue.length > strMaxLen) {
709
- ctx.addIssue({
710
- code: z.ZodIssueCode.custom,
711
- message: `Variable "${label}" (type string) length (${variableValue.length}) is greater than \`maxLength\` (${strMaxLen}).`,
712
- path,
713
- });
714
- }
715
- if (strPattern !== undefined) {
716
- try {
717
- if (!new RegExp(strPattern).test(variableValue)) {
718
- ctx.addIssue({
719
- code: z.ZodIssueCode.custom,
720
- message: `Variable "${label}" (type string) does not match \`pattern\`.`,
721
- path,
722
- });
723
- }
724
- } catch {
725
- // invalid regex already reported at schema parse time
726
- }
727
- }
728
-
729
- if (
730
- projectConfig.maxVariableStringLength &&
731
- variableValue.length > projectConfig.maxVariableStringLength
732
- ) {
733
- ctx.addIssue({
734
- code: z.ZodIssueCode.custom,
735
- message: `Variable "${label}" value is too long (${variableValue.length} characters), max length is ${projectConfig.maxVariableStringLength}`,
736
- path,
737
- });
738
- }
739
-
740
- return;
741
- }
742
-
743
- // integer — only integer number allowed (no NaN, no Infinity, no float)
744
- if (expectedType === "integer") {
745
- if (typeof variableValue !== "number") {
746
- ctx.addIssue({
747
- code: z.ZodIssueCode.custom,
748
- message: `Variable "${label}" (type integer) must be a number; got ${gotType}.`,
749
- path,
750
- });
751
- return;
752
- }
753
- if (!Number.isFinite(variableValue)) {
754
- ctx.addIssue({
755
- code: z.ZodIssueCode.custom,
756
- message: `Variable "${label}" (type integer) must be a finite number; got ${variableValue}.`,
757
- path,
758
- });
759
- return;
760
- }
761
- if (!Number.isInteger(variableValue)) {
762
- ctx.addIssue({
763
- code: z.ZodIssueCode.custom,
764
- message: `Variable "${label}" (type integer) must be an integer; got ${variableValue}.`,
765
- path,
766
- });
767
- return;
768
- }
769
- const intMin = (effectiveSchema as { minimum?: number }).minimum;
770
- const intMax = (effectiveSchema as { maximum?: number }).maximum;
771
- if (intMin !== undefined && variableValue < intMin) {
772
- ctx.addIssue({
773
- code: z.ZodIssueCode.custom,
774
- message: `Variable "${label}" (type integer) must be >= minimum (${intMin}); got ${variableValue}.`,
775
- path,
776
- });
777
- }
778
- if (intMax !== undefined && variableValue > intMax) {
779
- ctx.addIssue({
780
- code: z.ZodIssueCode.custom,
781
- message: `Variable "${label}" (type integer) must be <= maximum (${intMax}); got ${variableValue}.`,
782
- path,
783
- });
784
- }
785
- return;
786
- }
787
-
788
- // double — only finite number allowed
789
- if (expectedType === "double") {
790
- if (typeof variableValue !== "number") {
791
- ctx.addIssue({
792
- code: z.ZodIssueCode.custom,
793
- message: `Variable "${label}" (type double) must be a number; got ${gotType}.`,
794
- path,
795
- });
796
- return;
797
- }
798
- if (!Number.isFinite(variableValue)) {
799
- ctx.addIssue({
800
- code: z.ZodIssueCode.custom,
801
- message: `Variable "${label}" (type double) must be a finite number; got ${variableValue}.`,
802
- path,
803
- });
804
- return;
805
- }
806
- const doubleMin = (effectiveSchema as { minimum?: number }).minimum;
807
- const doubleMax = (effectiveSchema as { maximum?: number }).maximum;
808
- if (doubleMin !== undefined && variableValue < doubleMin) {
809
- ctx.addIssue({
810
- code: z.ZodIssueCode.custom,
811
- message: `Variable "${label}" (type double) must be >= minimum (${doubleMin}); got ${variableValue}.`,
812
- path,
813
- });
814
- }
815
- if (doubleMax !== undefined && variableValue > doubleMax) {
816
- ctx.addIssue({
817
- code: z.ZodIssueCode.custom,
818
- message: `Variable "${label}" (type double) must be <= maximum (${doubleMax}); got ${variableValue}.`,
819
- path,
820
- });
821
- }
822
- return;
823
- }
824
-
825
- // boolean — only boolean allowed
826
- if (expectedType === "boolean") {
827
- if (typeof variableValue !== "boolean") {
828
- ctx.addIssue({
829
- code: z.ZodIssueCode.custom,
830
- message: `Variable "${label}" (type boolean) must be a boolean; got ${gotType}.`,
831
- path,
832
- });
833
- }
834
- return;
835
- }
836
-
837
- // array — only array allowed; without items schema = array of strings
838
- if (expectedType === "array") {
839
- if (!Array.isArray(variableValue)) {
840
- ctx.addIssue({
841
- code: z.ZodIssueCode.custom,
842
- message: `Variable "${label}" (type array) must be an array; got ${gotType}.`,
843
- path,
844
- });
845
- return;
846
- }
847
- refineVariableValueArray(
848
- projectConfig,
849
- effectiveSchema as {
850
- items?: unknown;
851
- type: string;
852
- minItems?: number;
853
- maxItems?: number;
854
- uniqueItems?: boolean;
855
- },
856
- variableValue,
857
- path,
858
- ctx,
859
- variableKey,
860
- schemasByKey,
861
- );
862
- return;
863
- }
864
-
865
- // object — only plain object allowed (no null, no array)
866
- if (expectedType === "object") {
867
- if (
868
- typeof variableValue !== "object" ||
869
- variableValue === null ||
870
- Array.isArray(variableValue)
871
- ) {
872
- ctx.addIssue({
873
- code: z.ZodIssueCode.custom,
874
- message: `Variable "${label}" (type object) must be a plain object; got ${gotType}.`,
875
- path,
876
- });
877
- return;
878
- }
879
- refineVariableValueObject(
880
- projectConfig,
881
- effectiveSchema as {
882
- properties?: Record<string, unknown>;
883
- required?: string[];
884
- type: string;
885
- },
886
- variableValue as Record<string, unknown>,
887
- path,
888
- ctx,
889
- variableKey,
890
- schemasByKey,
891
- );
892
- return;
893
- }
894
-
895
- // json — only string containing valid JSON allowed
896
- if (expectedType === "json") {
897
- if (typeof variableValue !== "string") {
898
- ctx.addIssue({
899
- code: z.ZodIssueCode.custom,
900
- message: `Variable "${label}" (type json) must be a string (JSON string); got ${gotType}.`,
901
- path,
902
- });
903
- return;
904
- }
905
- try {
906
- JSON.parse(variableValue);
907
-
908
- if (projectConfig.maxVariableJSONStringifiedLength) {
909
- if (variableValue.length > projectConfig.maxVariableJSONStringifiedLength) {
910
- ctx.addIssue({
911
- code: z.ZodIssueCode.custom,
912
- message: `Variable "${label}" JSON is too long (${variableValue.length} characters), max length is ${projectConfig.maxVariableJSONStringifiedLength}`,
913
- path,
914
- });
915
- }
916
- }
917
- // eslint-disable-next-line
918
- } catch (e) {
919
- ctx.addIssue({
920
- code: z.ZodIssueCode.custom,
921
- message: `Variable "${label}" (type json) must be a valid JSON string; parse failed.`,
922
- path,
923
- });
924
- }
925
-
926
- return;
927
- }
928
-
929
- // Unknown variable type — schema is invalid or unsupported
930
- ctx.addIssue({
931
- code: z.ZodIssueCode.custom,
932
- message: `Variable "${label}" has unknown or unsupported type "${String(expectedType)}" in variablesSchema.`,
933
- path,
934
- });
935
- }
936
-
937
- /**
938
- * Validate a single variable entry (key + value) in variables map.
939
- * Key may be a root variable name or mutation notation (e.g. "config.width", "items[0].name").
940
- */
941
- function refineVariableEntry(
942
- projectConfig: ProjectConfig,
943
- variableSchemaByKey: Record<string, unknown>,
944
- variableKey: string,
945
- variableValue: unknown,
946
- path: (string | number)[],
947
- ctx: z.RefinementCtx,
948
- schemasByKey?: Record<string, Schema>,
949
- ): void {
950
- if (isMutationKey(variableKey)) {
951
- const validation = validateMutationKey(
952
- variableKey,
953
- variableSchemaByKey as Record<string, Schema>,
954
- schemasByKey,
955
- );
956
- if (!validation.valid && validation.error) {
957
- ctx.addIssue({
958
- code: z.ZodIssueCode.custom,
959
- message: validation.error,
960
- path,
961
- });
962
- return;
963
- }
964
- if (validation.valueSchema) {
965
- superRefineVariableValue(
966
- projectConfig,
967
- validation.valueSchema,
968
- variableValue,
969
- path,
970
- ctx,
971
- variableKey,
972
- schemasByKey,
973
- );
974
- }
975
- return;
976
- }
977
- const variableSchema = variableSchemaByKey[variableKey];
978
- if (!variableSchema) {
979
- ctx.addIssue({
980
- code: z.ZodIssueCode.custom,
981
- message: `Variable "${variableKey}" is not defined in \`variablesSchema\`.`,
982
- path,
983
- });
984
- return;
985
- }
986
- superRefineVariableValue(
987
- projectConfig,
988
- variableSchema as Parameters<typeof superRefineVariableValue>[1],
989
- variableValue,
990
- path,
991
- ctx,
992
- variableKey,
993
- schemasByKey,
994
- );
995
- }
996
-
997
- function refineVariableOverrides({
998
- ctx,
999
- variableSchemaByKey,
1000
- variableOverrides,
1001
- pathPrefix,
1002
- projectConfig,
1003
- schemasByKey,
1004
- }: {
1005
- ctx: z.RefinementCtx;
1006
- variableSchemaByKey: Record<string, unknown>;
1007
- variableOverrides: Record<string, Array<{ value?: unknown }>>;
1008
- pathPrefix: (string | number)[];
1009
- projectConfig: ProjectConfig;
1010
- schemasByKey?: Record<string, Schema>;
1011
- }) {
1012
- for (const variableKey of Object.keys(variableOverrides)) {
1013
- if (isMutationKey(variableKey)) {
1014
- ctx.addIssue({
1015
- code: z.ZodIssueCode.custom,
1016
- message:
1017
- `Variable override key "${variableKey}" must be a declared variable key, not mutation notation. ` +
1018
- "Use mutation notation inside each override's `value` object.",
1019
- path: [...pathPrefix, variableKey],
1020
- });
1021
- continue;
1022
- }
1023
-
1024
- const variableSchema = variableSchemaByKey[variableKey];
1025
- if (!variableSchema) {
1026
- ctx.addIssue({
1027
- code: z.ZodIssueCode.custom,
1028
- message: `Variable "${variableKey}" is not defined in \`variablesSchema\`.`,
1029
- path: [...pathPrefix, variableKey],
1030
- });
1031
- continue;
1032
- }
1033
-
1034
- const variableSchemaWithRef = variableSchema as { schema?: string };
1035
- const resolvedVariableSchema = resolveVariableSchema(
1036
- variableSchema as Parameters<typeof resolveVariableSchema>[0],
1037
- schemasByKey,
1038
- );
1039
- if (variableSchemaWithRef.schema) {
1040
- if (!resolvedVariableSchema) {
1041
- ctx.addIssue({
1042
- code: z.ZodIssueCode.custom,
1043
- message: `Schema "${variableSchemaWithRef.schema}" could not be loaded for variable "${variableKey}".`,
1044
- path: [...pathPrefix, variableKey],
1045
- });
1046
- continue;
1047
- }
1048
- }
1049
-
1050
- const overrides = variableOverrides[variableKey];
1051
- if (!Array.isArray(overrides)) {
1052
- continue;
1053
- }
1054
-
1055
- overrides.forEach((override, overrideN) => {
1056
- const overrideValue = override.value;
1057
- const valuePath = [...pathPrefix, variableKey, overrideN, "value"];
1058
-
1059
- if (
1060
- typeof overrideValue === "object" &&
1061
- overrideValue !== null &&
1062
- !Array.isArray(overrideValue)
1063
- ) {
1064
- const pathMap = overrideValue as Record<string, unknown>;
1065
- const pathKeys = Object.keys(pathMap);
1066
- const hasStructuredObjectSchema =
1067
- resolvedVariableSchema?.type === "object" &&
1068
- (Boolean(resolvedVariableSchema.properties) ||
1069
- Boolean(resolvedVariableSchema.additionalProperties));
1070
- const treatAsPathMap =
1071
- pathKeys.some((pathKey) => isMutationKey(pathKey)) ||
1072
- (hasStructuredObjectSchema && pathKeys.length > 0);
1073
-
1074
- if (treatAsPathMap) {
1075
- for (const pathKey of pathKeys) {
1076
- const composedMutationKey = `${variableKey}.${pathKey}`;
1077
- const validation = validateMutationKey(
1078
- composedMutationKey,
1079
- variableSchemaByKey as Record<string, Schema>,
1080
- schemasByKey,
1081
- );
1082
-
1083
- if (!validation.valid) {
1084
- ctx.addIssue({
1085
- code: z.ZodIssueCode.custom,
1086
- message:
1087
- validation.error ??
1088
- `Invalid mutation path "${pathKey}" in variableOverride for "${variableKey}".`,
1089
- path: [...valuePath, pathKey],
1090
- });
1091
- continue;
1092
- }
1093
-
1094
- if (validation.operation === "remove") {
1095
- if (pathMap[pathKey] !== null) {
1096
- ctx.addIssue({
1097
- code: z.ZodIssueCode.custom,
1098
- message: `Mutation "${pathKey}:remove" must use \`null\` as value.`,
1099
- path: [...valuePath, pathKey],
1100
- });
1101
- }
1102
- continue;
1103
- }
1104
-
1105
- const fallbackValueSchema =
1106
- validation.operation === "append" ||
1107
- validation.operation === "prepend" ||
1108
- validation.operation === "before" ||
1109
- validation.operation === "after"
1110
- ? ({ type: "string" } as Schema)
1111
- : null;
1112
- const valueSchema = validation.valueSchema ?? fallbackValueSchema;
1113
- if (!valueSchema) {
1114
- continue;
1115
- }
1116
-
1117
- superRefineVariableValue(
1118
- projectConfig,
1119
- valueSchema,
1120
- pathMap[pathKey],
1121
- [...valuePath, pathKey],
1122
- ctx,
1123
- pathKey,
1124
- schemasByKey,
1125
- );
1126
- }
1127
- } else {
1128
- superRefineVariableValue(
1129
- projectConfig,
1130
- variableSchema as Parameters<typeof superRefineVariableValue>[1],
1131
- overrideValue,
1132
- valuePath,
1133
- ctx,
1134
- variableKey,
1135
- schemasByKey,
1136
- );
1137
- }
1138
- } else {
1139
- superRefineVariableValue(
1140
- projectConfig,
1141
- variableSchema as Parameters<typeof superRefineVariableValue>[1],
1142
- overrideValue,
1143
- valuePath,
1144
- ctx,
1145
- variableKey,
1146
- schemasByKey,
1147
- );
1148
- }
1149
- });
1150
- }
1151
- }
1152
-
1153
- function refineForce({
1154
- ctx,
1155
- parsedFeature, // eslint-disable-line
1156
- variableSchemaByKey,
1157
- variationValues,
1158
- force,
1159
- pathPrefix,
1160
- projectConfig,
1161
- schemasByKey,
1162
- }) {
1163
- force.forEach((f, fN) => {
1164
- // force[n].variation
1165
- if (f.variation) {
1166
- if (variationValues.indexOf(f.variation) === -1) {
1167
- ctx.addIssue({
1168
- code: z.ZodIssueCode.custom,
1169
- message: `Unknown variation "${f.variation}" in force`,
1170
- path: [...pathPrefix, fN, "variation"],
1171
- });
1172
- }
1173
- }
1174
-
1175
- // force[n].variables[key]
1176
- if (f.variables) {
1177
- Object.keys(f.variables).forEach((variableKey) => {
1178
- refineVariableEntry(
1179
- projectConfig,
1180
- variableSchemaByKey,
1181
- variableKey,
1182
- f.variables[variableKey],
1183
- pathPrefix.concat([fN, "variables", variableKey]),
1184
- ctx,
1185
- schemasByKey,
1186
- );
1187
- });
1188
- }
1189
- });
1190
- }
1191
-
1192
- function refineRules({
1193
- ctx,
1194
- parsedFeature,
1195
- variableSchemaByKey,
1196
- variationValues,
1197
- rules,
1198
- pathPrefix,
1199
- projectConfig,
1200
- schemasByKey,
1201
- }) {
1202
- rules.forEach((rule, ruleN) => {
1203
- // rules[n].variables[key]
1204
- if (rule.variables) {
1205
- Object.keys(rule.variables).forEach((variableKey) => {
1206
- refineVariableEntry(
1207
- projectConfig,
1208
- variableSchemaByKey,
1209
- variableKey,
1210
- rule.variables[variableKey],
1211
- pathPrefix.concat([ruleN, "variables", variableKey]),
1212
- ctx,
1213
- schemasByKey,
1214
- );
1215
- });
1216
- }
1217
-
1218
- // rules[n].variableOverrides[key][].value (path-map or full value)
1219
- if (rule.variableOverrides) {
1220
- refineVariableOverrides({
1221
- ctx,
1222
- variableSchemaByKey,
1223
- variableOverrides: rule.variableOverrides,
1224
- pathPrefix: [...pathPrefix, ruleN, "variableOverrides"],
1225
- projectConfig,
1226
- schemasByKey,
1227
- });
1228
- }
1229
-
1230
- // rules[n].variationWeights
1231
- if (rule.variationWeights) {
1232
- if (!parsedFeature.variations) {
1233
- ctx.addIssue({
1234
- code: z.ZodIssueCode.custom,
1235
- message:
1236
- "Variation weights are overridden from rule, but no variations are present in feature.",
1237
- path: pathPrefix.concat([ruleN, "variationWeights"]),
1238
- });
1239
- } else {
1240
- const overriddenVariationValues = Object.keys(rule.variationWeights);
1241
- const overriddenVariationWeights: number[] = Object.values(rule.variationWeights);
1242
-
1243
- // unique keys
1244
- if (overriddenVariationValues.length !== new Set(overriddenVariationValues).size) {
1245
- ctx.addIssue({
1246
- code: z.ZodIssueCode.custom,
1247
- message:
1248
- "Duplicate variation values found in variationWeights: " +
1249
- overriddenVariationValues.join(", "),
1250
- path: pathPrefix.concat([ruleN, "variationWeights"]),
1251
- });
1252
- }
1253
-
1254
- // all original variations must be used
1255
- const missingVariations = variationValues.filter(
1256
- (v) => !overriddenVariationValues.includes(v),
1257
- );
1258
-
1259
- if (missingVariations.length > 0) {
1260
- ctx.addIssue({
1261
- code: z.ZodIssueCode.custom,
1262
- message: "Missing variations: " + missingVariations.join(", "),
1263
- path: pathPrefix.concat([ruleN, "variationWeights"]),
1264
- });
1265
- }
1266
-
1267
- // unknown variations
1268
- const unknownVariations = overriddenVariationValues.filter(
1269
- (v) => !variationValues.includes(v),
1270
- );
1271
-
1272
- if (unknownVariations.length > 0) {
1273
- ctx.addIssue({
1274
- code: z.ZodIssueCode.custom,
1275
- message:
1276
- "Variation weights contain unknown variations: " + unknownVariations.join(", "),
1277
- path: pathPrefix.concat([ruleN, "variationWeights"]),
1278
- });
1279
- }
1280
-
1281
- // weights sum must be 100
1282
- const weightsSum = overriddenVariationWeights.reduce((sum, weight) => sum + weight, 0);
1283
-
1284
- if (weightsSum !== 100) {
1285
- ctx.addIssue({
1286
- code: z.ZodIssueCode.custom,
1287
- message: "Variation weights must sum to 100",
1288
- path: pathPrefix.concat([ruleN, "variationWeights"]),
1289
- });
1290
- }
1291
- }
1292
- }
1293
- });
1294
- }
1295
-
1296
- export function getFeatureZodSchema(
1297
- projectConfig: ProjectConfig,
1298
- conditionsZodSchema,
1299
- availableAttributeKeys: [string, ...string[]],
1300
- availableSegmentKeys: [string, ...string[]],
1301
- availableFeatureKeys: [string, ...string[]],
1302
- availableSchemaKeys: string[] = [],
1303
- schemasByKey: Record<string, Schema> = {},
1304
- ) {
1305
- const schemaZodSchema = getSchemaZodSchema(availableSchemaKeys);
1306
- const variableValueZodSchema = valueZodSchema;
1307
- const variableValueOrNullZodSchema = z.union([valueZodSchema, z.null()]);
1308
- const overridePathMapValueZodSchema = z.record(z.string(), variableValueOrNullZodSchema);
1309
- const overrideValueZodSchema = z.union([
1310
- variableValueOrNullZodSchema,
1311
- overridePathMapValueZodSchema,
1312
- ]);
1313
-
1314
- const variationValueZodSchema = z.string().min(1);
1315
-
1316
- const plainGroupSegment = refineWithMessage(
1317
- z.string(),
1318
- (value) => value === "*" || availableSegmentKeys.includes(value),
1319
- (value) => `Unknown segment key "${value}"`,
1320
- );
1321
-
1322
- const andOrNotGroupSegment = z.union([
1323
- z
1324
- .object({
1325
- and: z.array(z.lazy(() => groupSegmentZodSchema)).min(1),
1326
- })
1327
- .strict(),
1328
- z
1329
- .object({
1330
- or: z.array(z.lazy(() => groupSegmentZodSchema)).min(1),
1331
- })
1332
- .strict(),
1333
- z
1334
- .object({
1335
- not: z.array(z.lazy(() => groupSegmentZodSchema)).min(1),
1336
- })
1337
- .strict(),
1338
- ]);
1339
-
1340
- const groupSegmentZodSchema = z.union([andOrNotGroupSegment, plainGroupSegment]);
1341
-
1342
- const groupSegmentsZodSchema = z.union([z.array(groupSegmentZodSchema), groupSegmentZodSchema]);
1343
-
1344
- const exposeSchema = z
1345
- .union([z.boolean(), z.array(z.string().refine((value) => projectConfig.tags.includes(value)))])
1346
- .optional();
1347
-
1348
- const rulesSchema = z
1349
- .array(
1350
- z
1351
- .object({
1352
- key: z.string(),
1353
- description: z.string().optional(),
1354
- promotable: z.boolean().optional(),
1355
- segments: groupSegmentsZodSchema,
1356
- percentage: z.number().min(0).max(100),
1357
-
1358
- enabled: z.boolean().optional(),
1359
- variation: variationValueZodSchema.optional(),
1360
- variables: z.record(z.string(), variableValueOrNullZodSchema).optional(),
1361
- variableOverrides: z
1362
- .record(
1363
- z.string(),
1364
- z.array(
1365
- z.union([
1366
- z
1367
- .object({
1368
- conditions: conditionsZodSchema,
1369
- value: overrideValueZodSchema,
1370
- })
1371
- .strict(),
1372
- z
1373
- .object({
1374
- segments: groupSegmentsZodSchema,
1375
- value: overrideValueZodSchema,
1376
- })
1377
- .strict(),
1378
- ]),
1379
- ),
1380
- )
1381
- .optional(),
1382
- variationWeights: z.record(z.string(), z.number().min(0).max(100)).optional(),
1383
- })
1384
- .strict(),
1385
- )
1386
-
1387
- // must have at least one rule
1388
- .superRefine((value, ctx) => {
1389
- if (value.length === 0) {
1390
- ctx.addIssue({
1391
- code: z.ZodIssueCode.custom,
1392
- message: "Must have at least one rule",
1393
- });
1394
- }
1395
- })
1396
-
1397
- // duplicate rules
1398
- .superRefine((value, ctx) => {
1399
- const keys = value.map((v) => v.key);
1400
- if (keys.length !== new Set(keys).size) {
1401
- ctx.addIssue({
1402
- code: z.ZodIssueCode.custom,
1403
- message: "Duplicate rule keys found: " + value.map((v) => v.key).join(", "),
1404
- });
1405
- }
1406
- })
1407
-
1408
- // enforce catch-all rule
1409
- .superRefine((value, ctx) => {
1410
- if (!projectConfig.enforceCatchAllRule) {
1411
- return;
1412
- }
1413
-
1414
- const hasCatchAllAsLastRule = value[value.length - 1].segments === "*";
1415
- if (!hasCatchAllAsLastRule) {
1416
- ctx.addIssue({
1417
- code: z.ZodIssueCode.custom,
1418
- message: `Missing catch-all rule with \`segments: "*"\` at the end`,
1419
- });
1420
- }
1421
- });
1422
-
1423
- const forceSchema = z
1424
- .array(
1425
- z.union([
1426
- z
1427
- .object({
1428
- segments: groupSegmentsZodSchema,
1429
- enabled: z.boolean().optional(),
1430
- variation: variationValueZodSchema.optional(),
1431
- variables: z.record(z.string(), variableValueOrNullZodSchema).optional(),
1432
- })
1433
- .strict(),
1434
- z
1435
- .object({
1436
- conditions: conditionsZodSchema,
1437
- enabled: z.boolean().optional(),
1438
- variation: variationValueZodSchema.optional(),
1439
- variables: z.record(z.string(), variableValueOrNullZodSchema).optional(),
1440
- })
1441
- .strict(),
1442
- ]),
1443
- )
1444
- .optional();
1445
-
1446
- const attributeKeyZodSchema = refineWithMessage(
1447
- z.string(),
1448
- (value) => value === "*" || availableAttributeKeys.includes(value),
1449
- (value) => `Unknown attribute "${value}"`,
1450
- );
1451
-
1452
- const featureKeyZodSchema = refineWithMessage(
1453
- z.string(),
1454
- (value) => availableFeatureKeys.includes(value),
1455
- (value) => `Unknown feature "${value}"`,
1456
- );
1457
-
1458
- const environmentKeys = Array.isArray(projectConfig.environments)
1459
- ? projectConfig.environments
1460
- : [];
1461
-
1462
- const featureZodSchema = z
1463
- .object({
1464
- archived: z.boolean().optional(),
1465
- deprecated: z.boolean().optional(),
1466
- promotable: z.boolean().optional(),
1467
- description: z.string(),
1468
-
1469
- tags: z
1470
- .array(
1471
- refineWithMessage(
1472
- z.string(),
1473
- (value) => projectConfig.tags.includes(value),
1474
- (value) => `Unknown tag "${value}"`,
1475
- ),
1476
- )
1477
- .superRefine((value, ctx) => {
1478
- if (value.length !== new Set(value).size) {
1479
- ctx.addIssue({
1480
- code: z.ZodIssueCode.custom,
1481
- message: "Duplicate tags found: " + value.join(", "),
1482
- });
1483
- }
1484
- })
1485
- .optional(),
1486
-
1487
- required: z
1488
- .array(
1489
- z.union([
1490
- featureKeyZodSchema,
1491
- z
1492
- .object({
1493
- key: featureKeyZodSchema,
1494
- variation: z.string().optional(),
1495
- })
1496
- .strict(),
1497
- ]),
1498
- )
1499
- .optional(),
1500
-
1501
- bucketBy: z.union([
1502
- attributeKeyZodSchema,
1503
- z.array(attributeKeyZodSchema),
1504
- z
1505
- .object({
1506
- or: z.array(attributeKeyZodSchema),
1507
- })
1508
- .strict(),
1509
- ]),
1510
-
1511
- variablesSchema: z
1512
- .record(
1513
- z.string(),
1514
- z
1515
- .object({
1516
- deprecated: z.boolean().optional(),
1517
-
1518
- // Reference to a reusable schema (mutually exclusive with type/properties/required/items)
1519
- schema: refineWithMessage(
1520
- z.string(),
1521
- (value) => availableSchemaKeys.includes(value),
1522
- (value) => `Unknown schema "${value}"`,
1523
- ).optional(),
1524
-
1525
- // Inline schema (mutually exclusive with schema)
1526
- type: z.union([z.literal("json"), propertyTypeEnum]).optional(),
1527
- items: schemaZodSchema.optional(),
1528
- properties: z.record(z.string(), schemaZodSchema).optional(),
1529
- additionalProperties: schemaZodSchema.optional(),
1530
- required: z.array(z.string()).optional(),
1531
- enum: z.array(variableValueZodSchema).optional(),
1532
- const: variableValueZodSchema.optional(),
1533
- oneOf: z.array(schemaZodSchema).min(1).optional(),
1534
- minimum: z.number().optional(),
1535
- maximum: z.number().optional(),
1536
- minLength: z.number().optional(),
1537
- maxLength: z.number().optional(),
1538
- pattern: z.string().optional(),
1539
- minItems: z.number().optional(),
1540
- maxItems: z.number().optional(),
1541
- uniqueItems: z.boolean().optional(),
1542
-
1543
- description: z.string().optional(),
1544
-
1545
- defaultValue: variableValueZodSchema,
1546
- disabledValue: variableValueZodSchema.optional(),
1547
-
1548
- useDefaultWhenDisabled: z.boolean().optional(),
1549
- })
1550
- .strict()
1551
- .superRefine((variableSchema, ctx) => {
1552
- const hasRef = "schema" in variableSchema && variableSchema.schema != null;
1553
- const hasInline =
1554
- "type" in variableSchema &&
1555
- variableSchema.type != null &&
1556
- variableSchema.type !== undefined;
1557
- const hasOneOf =
1558
- "oneOf" in variableSchema &&
1559
- Array.isArray(variableSchema.oneOf) &&
1560
- variableSchema.oneOf.length > 0;
1561
- if (hasRef && (hasInline || hasOneOf)) {
1562
- ctx.addIssue({
1563
- code: z.ZodIssueCode.custom,
1564
- message:
1565
- "Variable schema cannot have both `schema` (reference) and inline properties (`type`, `oneOf`, `properties`, `additionalProperties`, `required`, `items`). Use one or the other.",
1566
- path: [],
1567
- });
1568
- return;
1569
- }
1570
- if (hasRef) {
1571
- const hasInlineStructure =
1572
- ("type" in variableSchema && variableSchema.type != null) ||
1573
- ("properties" in variableSchema && variableSchema.properties != null) ||
1574
- ("additionalProperties" in variableSchema &&
1575
- variableSchema.additionalProperties != null) ||
1576
- ("required" in variableSchema && variableSchema.required != null) ||
1577
- ("items" in variableSchema && variableSchema.items != null) ||
1578
- ("oneOf" in variableSchema && variableSchema.oneOf != null);
1579
- const hasInlineValidation =
1580
- ("minimum" in variableSchema && variableSchema.minimum !== undefined) ||
1581
- ("maximum" in variableSchema && variableSchema.maximum !== undefined) ||
1582
- ("minLength" in variableSchema && variableSchema.minLength !== undefined) ||
1583
- ("maxLength" in variableSchema && variableSchema.maxLength !== undefined) ||
1584
- ("pattern" in variableSchema && variableSchema.pattern !== undefined) ||
1585
- ("minItems" in variableSchema && variableSchema.minItems !== undefined) ||
1586
- ("maxItems" in variableSchema && variableSchema.maxItems !== undefined) ||
1587
- ("uniqueItems" in variableSchema && variableSchema.uniqueItems !== undefined);
1588
- if (hasInlineStructure) {
1589
- ctx.addIssue({
1590
- code: z.ZodIssueCode.custom,
1591
- message:
1592
- "When `schema` is set, do not set `type`, `oneOf`, `properties`, `additionalProperties`, `required`, or `items`.",
1593
- path: [],
1594
- });
1595
- }
1596
- if (hasInlineValidation) {
1597
- ctx.addIssue({
1598
- code: z.ZodIssueCode.custom,
1599
- message:
1600
- "When `schema` is set, do not set `minimum`, `maximum`, `minLength`, `maxLength`, `pattern`, `minItems`, `maxItems`, or `uniqueItems`; use the referenced schema to define these.",
1601
- path: [],
1602
- });
1603
- }
1604
- return;
1605
- }
1606
- if (!hasInline && !hasOneOf) {
1607
- ctx.addIssue({
1608
- code: z.ZodIssueCode.custom,
1609
- message:
1610
- "Variable schema must have either `schema` (reference to a schema key), `type` (inline schema), or `oneOf` (inline oneOf schemas).",
1611
- path: [],
1612
- });
1613
- return;
1614
- }
1615
- if (hasInline && hasOneOf) {
1616
- ctx.addIssue({
1617
- code: z.ZodIssueCode.custom,
1618
- message:
1619
- "Variable schema cannot have both `type` and `oneOf` at the top level. Use one or the other.",
1620
- path: [],
1621
- });
1622
- return;
1623
- }
1624
- // Validate required ⊆ properties at this level and in all nested object schemas (resolve refs when schemasByKey provided)
1625
- refineRequiredKeysInSchema(
1626
- variableSchema as SchemaLikeForRequired,
1627
- [],
1628
- ctx,
1629
- schemasByKey,
1630
- );
1631
- }),
1632
- )
1633
- .optional(),
1634
-
1635
- disabledVariationValue: variationValueZodSchema.optional(),
1636
-
1637
- variations: z
1638
- .array(
1639
- z
1640
- .object({
1641
- description: z.string().optional(),
1642
- value: variationValueZodSchema,
1643
- weight: z.number().min(0).max(100),
1644
- variables: z.record(z.string(), variableValueOrNullZodSchema).optional(),
1645
- variableOverrides: z
1646
- .record(
1647
- z.string(),
1648
- z.array(
1649
- z.union([
1650
- z
1651
- .object({
1652
- conditions: conditionsZodSchema,
1653
- value: overrideValueZodSchema,
1654
- })
1655
- .strict(),
1656
- z
1657
- .object({
1658
- segments: groupSegmentsZodSchema,
1659
- value: overrideValueZodSchema,
1660
- })
1661
- .strict(),
1662
- ]),
1663
- ),
1664
- )
1665
- .optional(),
1666
- })
1667
- .strict(),
1668
- )
1669
- .superRefine((value, ctx) => {
1670
- const variationValues = value.map((v) => v.value);
1671
- if (variationValues.length !== new Set(variationValues).size) {
1672
- ctx.addIssue({
1673
- code: z.ZodIssueCode.custom,
1674
- message: "Duplicate variation values found: " + value.map((v) => v.value).join(", "),
1675
- });
1676
- }
1677
- })
1678
- .optional(),
1679
-
1680
- expose: !Array.isArray(projectConfig.environments)
1681
- ? exposeSchema.optional()
1682
- : z
1683
- .partialRecord(z.enum(environmentKeys as [string, ...string[]]), exposeSchema)
1684
- .optional(),
1685
-
1686
- force: !Array.isArray(projectConfig.environments)
1687
- ? forceSchema
1688
- : z.partialRecord(z.enum(environmentKeys as [string, ...string[]]), forceSchema).optional(),
1689
-
1690
- rules: !Array.isArray(projectConfig.environments)
1691
- ? rulesSchema
1692
- : z.partialRecord(z.enum(environmentKeys as [string, ...string[]]), rulesSchema),
1693
- })
1694
- .strict()
1695
- .superRefine((value, ctx) => {
1696
- // disabledVariationValue
1697
- if (value.disabledVariationValue) {
1698
- if (!value.variations) {
1699
- ctx.addIssue({
1700
- code: z.ZodIssueCode.custom,
1701
- message: "Disabled variation value is set, but no variations are present in feature.",
1702
- path: ["disabledVariationValue"],
1703
- });
1704
- } else {
1705
- const variationValues = value.variations.map((v) => v.value);
1706
-
1707
- if (variationValues.indexOf(value.disabledVariationValue) === -1) {
1708
- ctx.addIssue({
1709
- code: z.ZodIssueCode.custom,
1710
- message: `Disabled variation value "${value.disabledVariationValue}" is not one of the defined variations: ${variationValues.join(", ")}`,
1711
- path: ["disabledVariationValue"],
1712
- });
1713
- }
1714
- }
1715
- }
1716
-
1717
- // When variablesSchema is absent, variableSchemaByKey is {} so any variable key used in
1718
- // rules/force/variations will be reported as "not defined in variablesSchema".
1719
- const variableSchemaByKey = value.variablesSchema ?? {};
1720
- const variationValues: string[] = [];
1721
-
1722
- if (value.variations) {
1723
- value.variations.forEach((variation) => {
1724
- variationValues.push(variation.value);
1725
- });
1726
- }
1727
-
1728
- // variablesSchema[key] — only when feature defines variablesSchema
1729
- if (value.variablesSchema) {
1730
- const variableKeys = Object.keys(variableSchemaByKey);
1731
- variableKeys.forEach((variableKey) => {
1732
- const variableSchema = variableSchemaByKey[variableKey];
1733
-
1734
- // When variable references a schema by name, ensure it resolves and validate the referenced schema
1735
- if ("schema" in variableSchema && variableSchema.schema) {
1736
- const resolvedSchema = resolveVariableSchema(
1737
- variableSchema as Parameters<typeof resolveVariableSchema>[0],
1738
- schemasByKey,
1739
- );
1740
- if (!resolvedSchema) {
1741
- ctx.addIssue({
1742
- code: z.ZodIssueCode.custom,
1743
- message: `Schema "${variableSchema.schema}" could not be loaded for variable "${variableKey}".`,
1744
- path: ["variablesSchema", variableKey],
1745
- });
1746
- } else {
1747
- refineRequiredKeysInSchema(
1748
- resolvedSchema as SchemaLikeForRequired,
1749
- ["variablesSchema", variableKey],
1750
- ctx,
1751
- schemasByKey,
1752
- );
1753
- }
1754
- }
1755
-
1756
- // When type and enum are both present, all enum values must match the type
1757
- const effectiveSchema = resolveVariableSchema(variableSchema, schemasByKey);
1758
- if (
1759
- effectiveSchema &&
1760
- effectiveSchema.type &&
1761
- Array.isArray(effectiveSchema.enum) &&
1762
- effectiveSchema.enum.length > 0
1763
- ) {
1764
- refineEnumMatchesType(
1765
- effectiveSchema as Parameters<typeof refineEnumMatchesType>[0],
1766
- ["variablesSchema", variableKey],
1767
- ctx,
1768
- );
1769
- }
1770
-
1771
- // Inline variable schemas: validate minimum/maximum, minLength/maxLength/pattern, minItems/maxItems/uniqueItems
1772
- if (!("schema" in variableSchema) || !variableSchema.schema) {
1773
- const pathPrefix = ["variablesSchema", variableKey];
1774
- refineMinimumMaximum(
1775
- variableSchema as Parameters<typeof refineMinimumMaximum>[0],
1776
- pathPrefix,
1777
- ctx,
1778
- );
1779
- refineStringLengthPattern(
1780
- variableSchema as Parameters<typeof refineStringLengthPattern>[0],
1781
- pathPrefix,
1782
- ctx,
1783
- );
1784
- refineArrayItems(
1785
- variableSchema as Parameters<typeof refineArrayItems>[0],
1786
- pathPrefix,
1787
- ctx,
1788
- );
1789
- }
1790
-
1791
- if (variableKey === "variation") {
1792
- ctx.addIssue({
1793
- code: z.ZodIssueCode.custom,
1794
- message: `Variable key "${variableKey}" is reserved and cannot be used.`,
1795
- path: ["variablesSchema", variableKey],
1796
- });
1797
- }
1798
-
1799
- // defaultValue
1800
- superRefineVariableValue(
1801
- projectConfig,
1802
- variableSchema,
1803
- variableSchema.defaultValue,
1804
- ["variablesSchema", variableKey, "defaultValue"],
1805
- ctx,
1806
- variableKey,
1807
- schemasByKey,
1808
- );
1809
-
1810
- // disabledValue (only when present)
1811
- if (variableSchema.disabledValue !== undefined) {
1812
- superRefineVariableValue(
1813
- projectConfig,
1814
- variableSchema,
1815
- variableSchema.disabledValue,
1816
- ["variablesSchema", variableKey, "disabledValue"],
1817
- ctx,
1818
- variableKey,
1819
- schemasByKey,
1820
- );
1821
- }
1822
- });
1823
- }
1824
-
1825
- // variations: validate variation.variables and variation.variableOverrides (each value against its variable schema)
1826
- if (value.variations) {
1827
- value.variations.forEach((variation, variationN) => {
1828
- // variations[n].variables[key]
1829
- if (variation.variables) {
1830
- for (const variableKey of Object.keys(variation.variables)) {
1831
- refineVariableEntry(
1832
- projectConfig,
1833
- variableSchemaByKey,
1834
- variableKey,
1835
- variation.variables[variableKey],
1836
- ["variations", variationN, "variables", variableKey],
1837
- ctx,
1838
- schemasByKey,
1839
- );
1840
- }
1841
- }
1842
-
1843
- // variations[n].variableOverrides[key][].value (path-map or full value)
1844
- if (variation.variableOverrides) {
1845
- refineVariableOverrides({
1846
- ctx,
1847
- variableSchemaByKey,
1848
- variableOverrides: variation.variableOverrides,
1849
- pathPrefix: ["variations", variationN, "variableOverrides"],
1850
- projectConfig,
1851
- schemasByKey,
1852
- });
1853
- }
1854
- });
1855
- }
1856
-
1857
- if (environmentKeys.length > 0) {
1858
- // with environments
1859
- for (const environmentKey of environmentKeys) {
1860
- // rules
1861
- if (value.rules && value.rules[environmentKey]) {
1862
- refineRules({
1863
- parsedFeature: value,
1864
- variableSchemaByKey,
1865
- variationValues,
1866
- rules: value.rules[environmentKey],
1867
- pathPrefix: ["rules", environmentKey],
1868
- ctx,
1869
- projectConfig,
1870
- schemasByKey,
1871
- });
1872
- }
1873
-
1874
- // force
1875
- if (value.force && value.force[environmentKey]) {
1876
- refineForce({
1877
- parsedFeature: value,
1878
- variableSchemaByKey,
1879
- variationValues,
1880
- force: value.force[environmentKey],
1881
- pathPrefix: ["force", environmentKey],
1882
- ctx,
1883
- projectConfig,
1884
- schemasByKey,
1885
- });
1886
- }
1887
- }
1888
- } else {
1889
- // no environments
1890
-
1891
- // rules
1892
- if (value.rules) {
1893
- refineRules({
1894
- parsedFeature: value,
1895
- variableSchemaByKey,
1896
- variationValues,
1897
- rules: value.rules,
1898
- pathPrefix: ["rules"],
1899
- ctx,
1900
- projectConfig,
1901
- schemasByKey,
1902
- });
1903
- }
1904
-
1905
- // force
1906
- if (value.force) {
1907
- refineForce({
1908
- parsedFeature: value,
1909
- variableSchemaByKey,
1910
- variationValues,
1911
- force: value.force,
1912
- pathPrefix: ["force"],
1913
- ctx,
1914
- projectConfig,
1915
- schemasByKey,
1916
- });
1917
- }
1918
- }
1919
- });
1920
-
1921
- return featureZodSchema;
1922
- }