flagsmith-nodejs 6.2.0 → 7.0.2

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 (100) hide show
  1. package/.github/workflows/publish.yml +8 -5
  2. package/.github/workflows/pull_request.yaml +3 -0
  3. package/.gitmodules +1 -1
  4. package/.husky/pre-commit +1 -0
  5. package/.nvmrc +1 -0
  6. package/.release-please-manifest.json +1 -1
  7. package/CHANGELOG.md +40 -0
  8. package/build/cjs/flagsmith-engine/environments/models.d.ts +2 -1
  9. package/build/cjs/flagsmith-engine/environments/models.js +3 -1
  10. package/build/cjs/flagsmith-engine/environments/util.js +1 -1
  11. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.d.ts +230 -0
  12. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.js +8 -0
  13. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/mappers.d.ts +5 -0
  14. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/mappers.js +156 -0
  15. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/types.d.ts +216 -0
  16. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/types.js +8 -0
  17. package/build/cjs/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.d.ts +68 -0
  18. package/build/cjs/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.js +8 -0
  19. package/build/cjs/flagsmith-engine/evaluation/models.d.ts +50 -0
  20. package/build/cjs/flagsmith-engine/evaluation/models.js +26 -0
  21. package/build/cjs/flagsmith-engine/features/models.js +1 -1
  22. package/build/cjs/flagsmith-engine/features/types.d.ts +5 -0
  23. package/build/cjs/flagsmith-engine/features/types.js +9 -0
  24. package/build/cjs/flagsmith-engine/features/util.d.ts +1 -0
  25. package/build/cjs/flagsmith-engine/features/util.js +5 -1
  26. package/build/cjs/flagsmith-engine/index.d.ts +61 -9
  27. package/build/cjs/flagsmith-engine/index.js +176 -56
  28. package/build/cjs/flagsmith-engine/segments/constants.d.ts +1 -0
  29. package/build/cjs/flagsmith-engine/segments/constants.js +2 -1
  30. package/build/cjs/flagsmith-engine/segments/evaluators.d.ts +41 -7
  31. package/build/cjs/flagsmith-engine/segments/evaluators.js +136 -24
  32. package/build/cjs/flagsmith-engine/segments/models.d.ts +9 -4
  33. package/build/cjs/flagsmith-engine/segments/models.js +115 -13
  34. package/build/cjs/flagsmith-engine/utils/hashing/index.d.ts +1 -1
  35. package/build/cjs/flagsmith-engine/utils/hashing/index.js +4 -4
  36. package/build/cjs/sdk/index.d.ts +1 -3
  37. package/build/cjs/sdk/index.js +22 -19
  38. package/build/cjs/sdk/models.d.ts +8 -1
  39. package/build/cjs/sdk/models.js +29 -1
  40. package/build/esm/flagsmith-engine/environments/models.d.ts +2 -1
  41. package/build/esm/flagsmith-engine/environments/models.js +3 -1
  42. package/build/esm/flagsmith-engine/environments/util.js +1 -1
  43. package/build/esm/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.d.ts +230 -0
  44. package/build/esm/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.js +7 -0
  45. package/build/esm/flagsmith-engine/evaluation/evaluationContext/mappers.d.ts +5 -0
  46. package/build/esm/flagsmith-engine/evaluation/evaluationContext/mappers.js +152 -0
  47. package/build/esm/flagsmith-engine/evaluation/evaluationContext/types.d.ts +216 -0
  48. package/build/esm/flagsmith-engine/evaluation/evaluationContext/types.js +7 -0
  49. package/build/esm/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.d.ts +68 -0
  50. package/build/esm/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.js +7 -0
  51. package/build/esm/flagsmith-engine/evaluation/models.d.ts +50 -0
  52. package/build/esm/flagsmith-engine/evaluation/models.js +9 -0
  53. package/build/esm/flagsmith-engine/features/models.js +2 -2
  54. package/build/esm/flagsmith-engine/features/types.d.ts +5 -0
  55. package/build/esm/flagsmith-engine/features/types.js +6 -0
  56. package/build/esm/flagsmith-engine/features/util.d.ts +1 -0
  57. package/build/esm/flagsmith-engine/features/util.js +3 -0
  58. package/build/esm/flagsmith-engine/index.d.ts +61 -9
  59. package/build/esm/flagsmith-engine/index.js +161 -43
  60. package/build/esm/flagsmith-engine/segments/constants.d.ts +1 -0
  61. package/build/esm/flagsmith-engine/segments/constants.js +1 -0
  62. package/build/esm/flagsmith-engine/segments/evaluators.d.ts +41 -7
  63. package/build/esm/flagsmith-engine/segments/evaluators.js +137 -25
  64. package/build/esm/flagsmith-engine/segments/models.d.ts +9 -4
  65. package/build/esm/flagsmith-engine/segments/models.js +115 -13
  66. package/build/esm/flagsmith-engine/utils/hashing/index.d.ts +1 -1
  67. package/build/esm/flagsmith-engine/utils/hashing/index.js +2 -2
  68. package/build/esm/sdk/index.d.ts +1 -3
  69. package/build/esm/sdk/index.js +21 -18
  70. package/build/esm/sdk/models.d.ts +8 -1
  71. package/build/esm/sdk/models.js +29 -1
  72. package/flagsmith-engine/environments/models.ts +3 -1
  73. package/flagsmith-engine/environments/util.ts +2 -1
  74. package/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.ts +247 -0
  75. package/flagsmith-engine/evaluation/evaluationContext/mappers.ts +204 -0
  76. package/flagsmith-engine/evaluation/evaluationContext/types.ts +233 -0
  77. package/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.ts +71 -0
  78. package/flagsmith-engine/evaluation/models.ts +96 -0
  79. package/flagsmith-engine/features/models.ts +3 -2
  80. package/flagsmith-engine/features/types.ts +5 -0
  81. package/flagsmith-engine/features/util.ts +4 -0
  82. package/flagsmith-engine/index.ts +229 -72
  83. package/flagsmith-engine/segments/constants.ts +1 -0
  84. package/flagsmith-engine/segments/evaluators.ts +178 -62
  85. package/flagsmith-engine/segments/models.ts +171 -23
  86. package/flagsmith-engine/utils/hashing/index.ts +2 -2
  87. package/package.json +13 -2
  88. package/sdk/index.ts +36 -23
  89. package/sdk/models.ts +44 -2
  90. package/tests/engine/e2e/engine.test.ts +43 -38
  91. package/tests/engine/unit/engine.test.ts +306 -59
  92. package/tests/engine/unit/mappers.test.ts +353 -0
  93. package/tests/engine/unit/segments/segment_evaluators.test.ts +391 -49
  94. package/tests/engine/unit/segments/segments_model.test.ts +85 -0
  95. package/tests/engine/unit/utils/utils.test.ts +7 -7
  96. package/tests/engine/unit/utils.ts +1 -1
  97. package/tests/sdk/data/environment.json +1 -0
  98. package/tests/sdk/flagsmith.test.ts +29 -3
  99. package/tests/sdk/offline-handlers.test.ts +3 -1
  100. package/vitest.config.esm.ts +34 -0
@@ -1,7 +1,10 @@
1
1
  import * as semver from 'semver';
2
+ import { FeatureModel, FeatureStateModel, MultivariateFeatureOptionModel, MultivariateFeatureStateValueModel } from '../features/models.js';
2
3
  import { getCastingFunction as getCastingFunction } from '../utils/index.js';
3
4
  import { ALL_RULE, ANY_RULE, NONE_RULE, NOT_CONTAINS, REGEX, MODULO, IN, CONDITION_OPERATORS } from './constants.js';
4
5
  import { isSemver } from './util.js';
6
+ import { CONSTANTS } from '../features/constants.js';
7
+ import { SegmentSource } from '../evaluation/models.js';
5
8
  export const all = (iterable) => iterable.filter(e => !!e).length === iterable.length;
6
9
  export const any = (iterable) => iterable.filter(e => !!e).length > 0;
7
10
  export const matchingFunctions = {
@@ -11,15 +14,33 @@ export const matchingFunctions = {
11
14
  [CONDITION_OPERATORS.LESS_THAN]: (thisValue, otherValue) => thisValue > otherValue,
12
15
  [CONDITION_OPERATORS.LESS_THAN_INCLUSIVE]: (thisValue, otherValue) => thisValue >= otherValue,
13
16
  [CONDITION_OPERATORS.NOT_EQUAL]: (thisValue, otherValue) => thisValue != otherValue,
14
- [CONDITION_OPERATORS.CONTAINS]: (thisValue, otherValue) => !!otherValue && otherValue.includes(thisValue)
17
+ [CONDITION_OPERATORS.CONTAINS]: (thisValue, otherValue) => {
18
+ try {
19
+ return !!otherValue && otherValue.includes(thisValue);
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }
25
+ };
26
+ // Semver library throws an error if the version is invalid, in this case, we want to catch and return false
27
+ const safeSemverCompare = (semverMatchingFunction) => {
28
+ return (conditionValue, traitValue) => {
29
+ try {
30
+ return semverMatchingFunction(conditionValue, traitValue);
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ };
15
36
  };
16
37
  export const semverMatchingFunction = {
17
38
  ...matchingFunctions,
18
- [CONDITION_OPERATORS.EQUAL]: (thisValue, otherValue) => semver.eq(thisValue, otherValue),
19
- [CONDITION_OPERATORS.GREATER_THAN]: (thisValue, otherValue) => semver.gt(otherValue, thisValue),
20
- [CONDITION_OPERATORS.GREATER_THAN_INCLUSIVE]: (thisValue, otherValue) => semver.gte(otherValue, thisValue),
21
- [CONDITION_OPERATORS.LESS_THAN]: (thisValue, otherValue) => semver.gt(thisValue, otherValue),
22
- [CONDITION_OPERATORS.LESS_THAN_INCLUSIVE]: (thisValue, otherValue) => semver.gte(thisValue, otherValue)
39
+ [CONDITION_OPERATORS.EQUAL]: safeSemverCompare((conditionValue, traitValue) => semver.eq(traitValue, conditionValue)),
40
+ [CONDITION_OPERATORS.GREATER_THAN]: safeSemverCompare((conditionValue, traitValue) => semver.gt(traitValue, conditionValue)),
41
+ [CONDITION_OPERATORS.GREATER_THAN_INCLUSIVE]: safeSemverCompare((conditionValue, traitValue) => semver.gte(traitValue, conditionValue)),
42
+ [CONDITION_OPERATORS.LESS_THAN]: safeSemverCompare((conditionValue, traitValue) => semver.lt(traitValue, conditionValue)),
43
+ [CONDITION_OPERATORS.LESS_THAN_INCLUSIVE]: safeSemverCompare((conditionValue, traitValue) => semver.lte(traitValue, conditionValue))
23
44
  };
24
45
  export const getMatchingFunctions = (semver) => semver ? semverMatchingFunction : matchingFunctions;
25
46
  export class SegmentConditionModel {
@@ -31,11 +52,11 @@ export class SegmentConditionModel {
31
52
  };
32
53
  operator;
33
54
  value;
34
- property_;
55
+ property;
35
56
  constructor(operator, value, property) {
36
57
  this.operator = operator;
37
58
  this.value = value;
38
- this.property_ = property;
59
+ this.property = property;
39
60
  }
40
61
  matchesTraitValue(traitValue) {
41
62
  const evaluators = {
@@ -45,17 +66,49 @@ export class SegmentConditionModel {
45
66
  !traitValue.includes(this.value?.toString()));
46
67
  },
47
68
  evaluateRegex: (traitValue) => {
48
- return !!this.value && !!traitValue?.toString().match(new RegExp(this.value));
69
+ try {
70
+ if (!this.value) {
71
+ return false;
72
+ }
73
+ const regex = new RegExp(this.value?.toString());
74
+ return !!traitValue?.toString().match(regex);
75
+ }
76
+ catch {
77
+ return false;
78
+ }
49
79
  },
50
80
  evaluateModulo: (traitValue) => {
51
- if (isNaN(parseFloat(traitValue)) || !this.value) {
81
+ const parsedTraitValue = parseFloat(traitValue);
82
+ if (isNaN(parsedTraitValue) || !this.value) {
83
+ return false;
84
+ }
85
+ const parts = this.value.toString().split('|');
86
+ if (parts.length !== 2) {
87
+ return false;
88
+ }
89
+ const divisor = parseFloat(parts[0]);
90
+ const remainder = parseFloat(parts[1]);
91
+ if (isNaN(divisor) || isNaN(remainder) || divisor === 0) {
52
92
  return false;
53
93
  }
54
- const parts = this.value.split('|');
55
- const [divisor, reminder] = [parseFloat(parts[0]), parseFloat(parts[1])];
56
- return traitValue % divisor === reminder;
94
+ return parsedTraitValue % divisor === remainder;
57
95
  },
58
96
  evaluateIn: (traitValue) => {
97
+ if (!traitValue || typeof traitValue === 'boolean') {
98
+ return false;
99
+ }
100
+ if (Array.isArray(this.value)) {
101
+ return this.value.includes(traitValue.toString());
102
+ }
103
+ if (typeof this.value === 'string') {
104
+ try {
105
+ const parsed = JSON.parse(this.value);
106
+ if (Array.isArray(parsed)) {
107
+ return parsed.includes(traitValue.toString());
108
+ }
109
+ }
110
+ catch { }
111
+ }
59
112
  return this.value?.split(',').includes(traitValue.toString());
60
113
  }
61
114
  };
@@ -99,4 +152,53 @@ export class SegmentModel {
99
152
  this.id = id;
100
153
  this.name = name;
101
154
  }
155
+ static fromSegmentResult(segmentResults, evaluationContext) {
156
+ const segmentModels = [];
157
+ if (!evaluationContext.segments) {
158
+ return [];
159
+ }
160
+ for (const segmentResult of segmentResults) {
161
+ if (segmentResult.metadata?.source === SegmentSource.IDENTITY_OVERRIDE) {
162
+ continue;
163
+ }
164
+ const segmentMetadataId = segmentResult.metadata?.id;
165
+ if (!segmentMetadataId) {
166
+ continue;
167
+ }
168
+ const segmentContext = evaluationContext.segments[segmentMetadataId.toString()];
169
+ if (segmentContext) {
170
+ const segment = new SegmentModel(segmentMetadataId, segmentContext.name);
171
+ segment.rules = segmentContext.rules.map(rule => new SegmentRuleModel(rule.type));
172
+ segment.featureStates = SegmentModel.createFeatureStatesFromOverrides(segmentContext.overrides || []);
173
+ segmentModels.push(segment);
174
+ }
175
+ }
176
+ return segmentModels;
177
+ }
178
+ static createFeatureStatesFromOverrides(overrides) {
179
+ if (!overrides)
180
+ return [];
181
+ return overrides
182
+ .filter(override => {
183
+ const overrideMetadataId = override?.metadata?.id;
184
+ return typeof overrideMetadataId === 'number';
185
+ })
186
+ .map(override => {
187
+ const overrideMetadataId = override.metadata.id;
188
+ const feature = new FeatureModel(overrideMetadataId, override.name, override.variants?.length && override.variants.length > 0
189
+ ? CONSTANTS.MULTIVARIATE
190
+ : CONSTANTS.STANDARD);
191
+ const featureState = new FeatureStateModel(feature, override.enabled, override.priority || 0);
192
+ if (override.value !== undefined) {
193
+ featureState.setValue(override.value);
194
+ }
195
+ if (override.variants && override.variants.length > 0) {
196
+ featureState.multivariateFeatureStateValues = this.createMultivariateValues(override.variants);
197
+ }
198
+ return featureState;
199
+ });
200
+ }
201
+ static createMultivariateValues(variants) {
202
+ return variants.map(variant => new MultivariateFeatureStateValueModel(new MultivariateFeatureOptionModel(variant.value, variant.id), variant.weight, variant.id));
203
+ }
102
204
  }
@@ -6,4 +6,4 @@
6
6
  * @param {} iterations=1 num times to include each id in the generated string to hash
7
7
  * @returns number number between 0 (inclusive) and 100 (exclusive)
8
8
  */
9
- export declare function getHashedPercentateForObjIds(objectIds: Array<any>, iterations?: number): number;
9
+ export declare function getHashedPercentageForObjIds(objectIds: Array<any>, iterations?: number): number;
@@ -10,7 +10,7 @@ const makeRepeated = (arr, repeats) => Array.from({ length: repeats }, () => arr
10
10
  * @param {} iterations=1 num times to include each id in the generated string to hash
11
11
  * @returns number number between 0 (inclusive) and 100 (exclusive)
12
12
  */
13
- export function getHashedPercentateForObjIds(objectIds, iterations = 1) {
13
+ export function getHashedPercentageForObjIds(objectIds, iterations = 1) {
14
14
  let toHash = makeRepeated(objectIds, iterations).join(',');
15
15
  const hashedValue = md5(toHash);
16
16
  const hashedInt = BigInt('0x' + hashedValue);
@@ -19,7 +19,7 @@ export function getHashedPercentateForObjIds(objectIds, iterations = 1) {
19
19
  /* istanbul ignore next */
20
20
  if (value === 100) {
21
21
  /* istanbul ignore next */
22
- return getHashedPercentateForObjIds(objectIds, iterations + 1);
22
+ return getHashedPercentageForObjIds(objectIds, iterations + 1);
23
23
  }
24
24
  return value;
25
25
  }
@@ -1,10 +1,8 @@
1
1
  import { Dispatcher } from 'undici-types';
2
- import { EnvironmentModel } from '../flagsmith-engine/index.js';
3
- import { IdentityModel } from '../flagsmith-engine/index.js';
4
2
  import { BaseOfflineHandler } from './offline_handlers.js';
5
3
  import { DefaultFlag, Flags } from './models.js';
6
4
  import { EnvironmentDataPollingManager } from './polling_manager.js';
7
- import { SegmentModel } from '../flagsmith-engine/index.js';
5
+ import { SegmentModel, EnvironmentModel, IdentityModel } from '../flagsmith-engine/index.js';
8
6
  import { FlagsmithConfig, FlagsmithTraitValue, TraitConfig } from './types.js';
9
7
  export { AnalyticsProcessor, AnalyticsProcessorOptions } from './analytics.js';
10
8
  export { FlagsmithAPIError, FlagsmithClientError } from './errors.js';
@@ -1,14 +1,12 @@
1
- import { getEnvironmentFeatureStates, getIdentityFeatureStates } from '../flagsmith-engine/index.js';
2
1
  import { buildEnvironmentModel } from '../flagsmith-engine/environments/util.js';
3
- import { IdentityModel } from '../flagsmith-engine/index.js';
4
- import { TraitModel } from '../flagsmith-engine/index.js';
5
2
  import { ANALYTICS_ENDPOINT, AnalyticsProcessor } from './analytics.js';
6
- import { FlagsmithAPIError } from './errors.js';
3
+ import { FlagsmithAPIError, FlagsmithClientError } from './errors.js';
7
4
  import { Flags } from './models.js';
8
5
  import { EnvironmentDataPollingManager } from './polling_manager.js';
9
6
  import { Deferred, generateIdentitiesData, getUserAgent, retryFetch } from './utils.js';
10
- import { getIdentitySegments } from '../flagsmith-engine/segments/evaluators.js';
7
+ import { SegmentModel, IdentityModel, TraitModel, getEvaluationResult } from '../flagsmith-engine/index.js';
11
8
  import { pino } from 'pino';
9
+ import { getEvaluationContext } from '../flagsmith-engine/evaluation/evaluationContext/mappers.js';
12
10
  export { AnalyticsProcessor } from './analytics.js';
13
11
  export { FlagsmithAPIError, FlagsmithClientError } from './errors.js';
14
12
  export { BaseFlag, DefaultFlag, Flags } from './models.js';
@@ -220,7 +218,12 @@ export class Flagsmith {
220
218
  key,
221
219
  value: traits?.[key]
222
220
  })));
223
- return getIdentitySegments(environment, identityModel);
221
+ const context = getEvaluationContext(environment, identityModel);
222
+ if (!context) {
223
+ throw new FlagsmithClientError('Local evaluation required to obtain identity segments');
224
+ }
225
+ const evaluationResult = getEvaluationResult(context);
226
+ return SegmentModel.fromSegmentResult(evaluationResult.segments, context);
224
227
  }
225
228
  async fetchEnvironment() {
226
229
  const deferred = new Deferred();
@@ -351,11 +354,12 @@ export class Flagsmith {
351
354
  }
352
355
  async getEnvironmentFlagsFromDocument() {
353
356
  const environment = await this.getEnvironment();
354
- const flags = Flags.fromFeatureStateModels({
355
- featureStates: getEnvironmentFeatureStates(environment),
356
- analyticsProcessor: this.analyticsProcessor,
357
- defaultFlagHandler: this.defaultFlagHandler
358
- });
357
+ const context = getEvaluationContext(environment, undefined, undefined, true);
358
+ if (!context) {
359
+ throw new FlagsmithClientError('Unable to get flags. No environment present.');
360
+ }
361
+ const evaluationResult = getEvaluationResult(context);
362
+ const flags = Flags.fromEvaluationResult(evaluationResult);
359
363
  if (!!this.cache) {
360
364
  await this.cache.set('flags', flags);
361
365
  }
@@ -367,13 +371,12 @@ export class Flagsmith {
367
371
  key,
368
372
  value: traits[key]
369
373
  })));
370
- const featureStates = getIdentityFeatureStates(environment, identityModel);
371
- const flags = Flags.fromFeatureStateModels({
372
- featureStates: featureStates,
373
- analyticsProcessor: this.analyticsProcessor,
374
- defaultFlagHandler: this.defaultFlagHandler,
375
- identityID: identityModel.djangoID || identityModel.compositeKey
376
- });
374
+ const context = getEvaluationContext(environment, identityModel);
375
+ if (!context) {
376
+ throw new FlagsmithClientError('Unable to get flags. No environment present.');
377
+ }
378
+ const evaluationResult = getEvaluationResult(context);
379
+ const flags = Flags.fromEvaluationResult(evaluationResult, this.defaultFlagHandler, this.analyticsProcessor);
377
380
  if (!!this.cache) {
378
381
  await this.cache.set(`flags-${identifier}`, flags);
379
382
  }
@@ -1,6 +1,7 @@
1
+ import { EvaluationResultWithMetadata } from '../flagsmith-engine/evaluation/models.js';
1
2
  import { FeatureStateModel } from '../flagsmith-engine/features/models.js';
2
3
  import { AnalyticsProcessor } from './analytics.js';
3
- type FlagValue = string | number | boolean | undefined;
4
+ type FlagValue = string | number | boolean | undefined | null;
4
5
  /**
5
6
  * A Flagsmith feature. It has an enabled/disabled state, and an optional {@link FlagValue}.
6
7
  */
@@ -38,12 +39,17 @@ export declare class Flag extends BaseFlag {
38
39
  * The programmatic name for this feature, unique per Flagsmith project.
39
40
  */
40
41
  featureName: string;
42
+ /**
43
+ * The reason for this feature, unique per Flagsmith project.
44
+ */
45
+ reason?: string;
41
46
  constructor(params: {
42
47
  value: FlagValue;
43
48
  enabled: boolean;
44
49
  isDefault?: boolean;
45
50
  featureId: number;
46
51
  featureName: string;
52
+ reason?: string;
47
53
  });
48
54
  static fromFeatureStateModel(fsm: FeatureStateModel, identityId: number | string | undefined): Flag;
49
55
  static fromAPIFlag(flagData: any): Flag;
@@ -61,6 +67,7 @@ export declare class Flags {
61
67
  defaultFlagHandler?: (v: string) => DefaultFlag;
62
68
  analyticsProcessor?: AnalyticsProcessor;
63
69
  });
70
+ static fromEvaluationResult(evaluationResult: EvaluationResultWithMetadata, defaultFlagHandler?: (v: string) => DefaultFlag, analyticsProcessor?: AnalyticsProcessor): Flags;
64
71
  static fromFeatureStateModels(data: {
65
72
  featureStates: FeatureStateModel[];
66
73
  analyticsProcessor?: AnalyticsProcessor;
@@ -41,10 +41,15 @@ export class Flag extends BaseFlag {
41
41
  * The programmatic name for this feature, unique per Flagsmith project.
42
42
  */
43
43
  featureName;
44
+ /**
45
+ * The reason for this feature, unique per Flagsmith project.
46
+ */
47
+ reason;
44
48
  constructor(params) {
45
49
  super(params.value, params.enabled, !!params.isDefault);
46
50
  this.featureId = params.featureId;
47
51
  this.featureName = params.featureName;
52
+ this.reason = params.reason;
48
53
  }
49
54
  static fromFeatureStateModel(fsm, identityId) {
50
55
  return new Flag({
@@ -59,7 +64,8 @@ export class Flag extends BaseFlag {
59
64
  enabled: flagData['enabled'],
60
65
  value: flagData['feature_state_value'] ?? flagData['value'],
61
66
  featureId: flagData['feature']['id'],
62
- featureName: flagData['feature']['name']
67
+ featureName: flagData['feature']['name'],
68
+ reason: flagData['feature']['reason']
63
69
  });
64
70
  }
65
71
  }
@@ -72,6 +78,28 @@ export class Flags {
72
78
  this.defaultFlagHandler = data.defaultFlagHandler;
73
79
  this.analyticsProcessor = data.analyticsProcessor;
74
80
  }
81
+ static fromEvaluationResult(evaluationResult, defaultFlagHandler, analyticsProcessor) {
82
+ const flags = {};
83
+ for (const flag of Object.values(evaluationResult.flags)) {
84
+ const flagMetadataId = flag.metadata?.id;
85
+ if (!flagMetadataId) {
86
+ throw new Error(`FlagResult metadata.id is missing for feature "${flag.name}". ` +
87
+ `This indicates a bug in the SDK, please report it.`);
88
+ }
89
+ flags[flag.name] = new Flag({
90
+ enabled: flag.enabled,
91
+ value: flag.value ?? null,
92
+ featureId: flagMetadataId,
93
+ featureName: flag.name,
94
+ reason: flag.reason
95
+ });
96
+ }
97
+ return new Flags({
98
+ flags: flags,
99
+ defaultFlagHandler: defaultFlagHandler,
100
+ analyticsProcessor: analyticsProcessor
101
+ });
102
+ }
75
103
  static fromFeatureStateModels(data) {
76
104
  const flags = {};
77
105
  for (const fs of data.featureStates) {
@@ -38,10 +38,12 @@ export class EnvironmentModel {
38
38
  project: ProjectModel;
39
39
  featureStates: FeatureStateModel[] = [];
40
40
  identityOverrides: IdentityModel[] = [];
41
+ name: string;
41
42
 
42
- constructor(id: number, apiKey: string, project: ProjectModel) {
43
+ constructor(id: number, apiKey: string, project: ProjectModel, name: string) {
43
44
  this.id = id;
44
45
  this.apiKey = apiKey;
45
46
  this.project = project;
47
+ this.name = name;
46
48
  }
47
49
  }
@@ -11,7 +11,8 @@ export function buildEnvironmentModel(environmentJSON: any) {
11
11
  const environmentModel = new EnvironmentModel(
12
12
  environmentJSON.id,
13
13
  environmentJSON.api_key,
14
- project
14
+ project,
15
+ environmentJSON.name
15
16
  );
16
17
  environmentModel.featureStates = featureStates;
17
18
  if (!!environmentJSON.identity_overrides) {
@@ -0,0 +1,247 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * This file was automatically generated by json-schema-to-typescript.
4
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
5
+ * and run json-schema-to-typescript to regenerate this file.
6
+ */
7
+
8
+ /**
9
+ * Unique environment key. May be used for selecting a value for a multivariate feature, or for % split segmentation.
10
+ */
11
+ export type Key = string;
12
+ /**
13
+ * An environment's human-readable name.
14
+ */
15
+ export type Name = string;
16
+ /**
17
+ * A unique identifier for an identity as displayed in the Flagsmith UI.
18
+ */
19
+ export type Identifier = string;
20
+ /**
21
+ * Key used when selecting a value for a multivariate feature, or for % split segmentation. Set to an internal identifier or a composite value based on the environment key and identifier, depending on Flagsmith implementation.
22
+ */
23
+ export type Key1 = string;
24
+ /**
25
+ * Unique segment key used for % split segmentation.
26
+ */
27
+ export type Key2 = string;
28
+ /**
29
+ * The name of the segment.
30
+ */
31
+ export type Name1 = string;
32
+ /**
33
+ * Segment rule type. Represents a logical quantifier for the conditions and sub-rules.
34
+ */
35
+ export type Type = 'ALL' | 'ANY' | 'NONE';
36
+ export type SegmentCondition = SegmentCondition1 | InSegmentCondition;
37
+ /**
38
+ * A reference to the identity trait or value in the evaluation context.
39
+ */
40
+ export type Property = string;
41
+ /**
42
+ * The operator to use for evaluating the condition.
43
+ */
44
+ export type Operator =
45
+ | 'EQUAL'
46
+ | 'GREATER_THAN'
47
+ | 'LESS_THAN'
48
+ | 'LESS_THAN_INCLUSIVE'
49
+ | 'CONTAINS'
50
+ | 'GREATER_THAN_INCLUSIVE'
51
+ | 'NOT_CONTAINS'
52
+ | 'NOT_EQUAL'
53
+ | 'REGEX'
54
+ | 'PERCENTAGE_SPLIT'
55
+ | 'MODULO'
56
+ | 'IS_SET'
57
+ | 'IS_NOT_SET'
58
+ | 'IN';
59
+ /**
60
+ * The value to compare against the trait or context value.
61
+ */
62
+ export type Value = string;
63
+ /**
64
+ * A reference to the identity trait or value in the evaluation context.
65
+ */
66
+ export type Property1 = string;
67
+ /**
68
+ * The operator to use for evaluating the condition.
69
+ */
70
+ export type Operator1 = 'IN';
71
+ /**
72
+ * The values to compare against the trait or context value.
73
+ */
74
+ export type Value1 = string[];
75
+ /**
76
+ * Conditions that must be met for the rule to apply.
77
+ */
78
+ export type Conditions = SegmentCondition[];
79
+ /**
80
+ * Sub-rules nested within the segment rule.
81
+ */
82
+ export type SubRules = SegmentRule[];
83
+ /**
84
+ * Rules that define the segment.
85
+ */
86
+ export type Rules = SegmentRule[];
87
+ /**
88
+ * Unique feature key used when selecting a variant if the feature is multivariate. Set to an internal identifier or a UUID, depending on Flagsmith implementation.
89
+ */
90
+ export type Key3 = string;
91
+ /**
92
+ * Feature name.
93
+ */
94
+ export type Name2 = string;
95
+ /**
96
+ * Indicates whether the feature is enabled in the environment.
97
+ */
98
+ export type Enabled = boolean;
99
+ /**
100
+ * A default environment value for the feature. If the feature is multivariate, this will be the control value.
101
+ */
102
+ export type Value2 = string | number | boolean | null;
103
+ /**
104
+ * The value of the feature.
105
+ */
106
+ export type Value3 = string | number | boolean | null;
107
+ /**
108
+ * The weight of the feature value variant, as a percentage number (i.e. 100.0).
109
+ */
110
+ export type Weight = number;
111
+ /**
112
+ * Priority of the feature flag variant. Lower values indicate a higher priority when multiple variants apply to the same context key.
113
+ */
114
+ export type VariantPriority = number;
115
+ /**
116
+ * An array of environment default values associated with the feature. Empty for standard features, or contains multiple values for multivariate features.
117
+ */
118
+ export type Variants = FeatureValue[];
119
+ /**
120
+ * Priority of the feature context. Lower values indicate a higher priority when multiple contexts apply to the same feature.
121
+ */
122
+ export type FeaturePriority = number;
123
+ /**
124
+ * Feature overrides for the segment.
125
+ */
126
+ export type Overrides = FeatureContext[];
127
+
128
+ /**
129
+ * A context object containing the necessary information to evaluate Flagsmith feature flags.
130
+ */
131
+ export interface EvaluationContext {
132
+ environment: EnvironmentContext;
133
+ /**
134
+ * Identity context used for identity-based evaluation.
135
+ */
136
+ identity?: IdentityContext | null;
137
+ segments?: Segments;
138
+ features?: Features;
139
+ [k: string]: unknown;
140
+ }
141
+ /**
142
+ * Environment context required for evaluation.
143
+ */
144
+ export interface EnvironmentContext {
145
+ key: Key;
146
+ name: Name;
147
+ [k: string]: unknown;
148
+ }
149
+ /**
150
+ * Represents an identity context for feature flag evaluation.
151
+ */
152
+ export interface IdentityContext {
153
+ identifier: Identifier;
154
+ key?: Key1;
155
+ traits?: Traits;
156
+ [k: string]: unknown;
157
+ }
158
+ /**
159
+ * A map of traits associated with the identity, where the key is the trait name and the value is the trait value.
160
+ */
161
+ export interface Traits {
162
+ [k: string]: string | number | boolean | null;
163
+ }
164
+ /**
165
+ * Segments applicable to the evaluation context.
166
+ */
167
+ export interface Segments {
168
+ [k: string]: SegmentContext;
169
+ }
170
+ /**
171
+ * Represents a segment context for feature flag evaluation.
172
+ */
173
+ export interface SegmentContext {
174
+ key: Key2;
175
+ name: Name1;
176
+ rules: Rules;
177
+ overrides?: Overrides;
178
+ metadata?: SegmentMetadata;
179
+ [k: string]: unknown;
180
+ }
181
+ /**
182
+ * Represents a rule within a segment for feature flag evaluation.
183
+ */
184
+ export interface SegmentRule {
185
+ type: Type;
186
+ conditions?: Conditions;
187
+ rules?: SubRules;
188
+ [k: string]: unknown;
189
+ }
190
+ /**
191
+ * Represents a condition within a segment rule for feature flag evaluation.
192
+ */
193
+ export interface SegmentCondition1 {
194
+ property: Property;
195
+ operator: Operator;
196
+ value: Value;
197
+ [k: string]: unknown;
198
+ }
199
+ /**
200
+ * Represents an IN condition within a segment rule for feature flag evaluation.
201
+ */
202
+ export interface InSegmentCondition {
203
+ property: Property1;
204
+ operator: Operator1;
205
+ value: Value1;
206
+ [k: string]: unknown;
207
+ }
208
+ /**
209
+ * Represents a feature context for feature flag evaluation.
210
+ */
211
+ export interface FeatureContext {
212
+ key: Key3;
213
+ name: Name2;
214
+ enabled: Enabled;
215
+ value: Value2;
216
+ variants?: Variants;
217
+ priority?: FeaturePriority;
218
+ metadata?: FeatureMetadata;
219
+ [k: string]: unknown;
220
+ }
221
+ /**
222
+ * Represents a multivariate value for a feature flag.
223
+ */
224
+ export interface FeatureValue {
225
+ value: Value3;
226
+ weight: Weight;
227
+ priority: VariantPriority;
228
+ [k: string]: unknown;
229
+ }
230
+ /**
231
+ * Additional metadata associated with the feature.
232
+ */
233
+ export interface FeatureMetadata {
234
+ [k: string]: unknown;
235
+ }
236
+ /**
237
+ * Additional metadata associated with the segment.
238
+ */
239
+ export interface SegmentMetadata {
240
+ [k: string]: unknown;
241
+ }
242
+ /**
243
+ * Features to be evaluated in the context.
244
+ */
245
+ export interface Features {
246
+ [k: string]: FeatureContext;
247
+ }