flagsmith-nodejs 6.1.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 (117) hide show
  1. package/.github/workflows/conventional-commit.yml +29 -0
  2. package/.github/workflows/publish.yml +20 -17
  3. package/.github/workflows/pull_request.yaml +36 -33
  4. package/.github/workflows/release-please.yml +18 -0
  5. package/.gitmodules +1 -0
  6. package/.husky/pre-commit +1 -0
  7. package/.nvmrc +1 -0
  8. package/.prettierrc.cjs +9 -1
  9. package/.release-please-manifest.json +1 -0
  10. package/CHANGELOG.md +592 -0
  11. package/CODEOWNERS +1 -0
  12. package/README.md +0 -2
  13. package/build/cjs/flagsmith-engine/environments/models.d.ts +2 -1
  14. package/build/cjs/flagsmith-engine/environments/models.js +3 -1
  15. package/build/cjs/flagsmith-engine/environments/util.js +1 -1
  16. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.d.ts +230 -0
  17. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.js +8 -0
  18. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/mappers.d.ts +5 -0
  19. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/mappers.js +156 -0
  20. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/types.d.ts +216 -0
  21. package/build/cjs/flagsmith-engine/evaluation/evaluationContext/types.js +8 -0
  22. package/build/cjs/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.d.ts +68 -0
  23. package/build/cjs/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.js +8 -0
  24. package/build/cjs/flagsmith-engine/evaluation/models.d.ts +50 -0
  25. package/build/cjs/flagsmith-engine/evaluation/models.js +26 -0
  26. package/build/cjs/flagsmith-engine/features/models.js +1 -1
  27. package/build/cjs/flagsmith-engine/features/types.d.ts +5 -0
  28. package/build/cjs/flagsmith-engine/features/types.js +9 -0
  29. package/build/cjs/flagsmith-engine/features/util.d.ts +1 -0
  30. package/build/cjs/flagsmith-engine/features/util.js +5 -1
  31. package/build/cjs/flagsmith-engine/index.d.ts +61 -9
  32. package/build/cjs/flagsmith-engine/index.js +176 -56
  33. package/build/cjs/flagsmith-engine/segments/constants.d.ts +1 -0
  34. package/build/cjs/flagsmith-engine/segments/constants.js +2 -1
  35. package/build/cjs/flagsmith-engine/segments/evaluators.d.ts +41 -7
  36. package/build/cjs/flagsmith-engine/segments/evaluators.js +136 -24
  37. package/build/cjs/flagsmith-engine/segments/models.d.ts +9 -4
  38. package/build/cjs/flagsmith-engine/segments/models.js +115 -13
  39. package/build/cjs/flagsmith-engine/utils/hashing/index.d.ts +1 -1
  40. package/build/cjs/flagsmith-engine/utils/hashing/index.js +4 -4
  41. package/build/cjs/sdk/analytics.js +3 -1
  42. package/build/cjs/sdk/index.d.ts +1 -3
  43. package/build/cjs/sdk/index.js +63 -24
  44. package/build/cjs/sdk/models.d.ts +8 -1
  45. package/build/cjs/sdk/models.js +29 -1
  46. package/build/cjs/sdk/utils.d.ts +1 -0
  47. package/build/cjs/sdk/utils.js +14 -1
  48. package/build/esm/flagsmith-engine/environments/models.d.ts +2 -1
  49. package/build/esm/flagsmith-engine/environments/models.js +3 -1
  50. package/build/esm/flagsmith-engine/environments/util.js +1 -1
  51. package/build/esm/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.d.ts +230 -0
  52. package/build/esm/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.js +7 -0
  53. package/build/esm/flagsmith-engine/evaluation/evaluationContext/mappers.d.ts +5 -0
  54. package/build/esm/flagsmith-engine/evaluation/evaluationContext/mappers.js +152 -0
  55. package/build/esm/flagsmith-engine/evaluation/evaluationContext/types.d.ts +216 -0
  56. package/build/esm/flagsmith-engine/evaluation/evaluationContext/types.js +7 -0
  57. package/build/esm/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.d.ts +68 -0
  58. package/build/esm/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.js +7 -0
  59. package/build/esm/flagsmith-engine/evaluation/models.d.ts +50 -0
  60. package/build/esm/flagsmith-engine/evaluation/models.js +9 -0
  61. package/build/esm/flagsmith-engine/features/models.js +2 -2
  62. package/build/esm/flagsmith-engine/features/types.d.ts +5 -0
  63. package/build/esm/flagsmith-engine/features/types.js +6 -0
  64. package/build/esm/flagsmith-engine/features/util.d.ts +1 -0
  65. package/build/esm/flagsmith-engine/features/util.js +3 -0
  66. package/build/esm/flagsmith-engine/index.d.ts +61 -9
  67. package/build/esm/flagsmith-engine/index.js +161 -43
  68. package/build/esm/flagsmith-engine/segments/constants.d.ts +1 -0
  69. package/build/esm/flagsmith-engine/segments/constants.js +1 -0
  70. package/build/esm/flagsmith-engine/segments/evaluators.d.ts +41 -7
  71. package/build/esm/flagsmith-engine/segments/evaluators.js +137 -25
  72. package/build/esm/flagsmith-engine/segments/models.d.ts +9 -4
  73. package/build/esm/flagsmith-engine/segments/models.js +115 -13
  74. package/build/esm/flagsmith-engine/utils/hashing/index.d.ts +1 -1
  75. package/build/esm/flagsmith-engine/utils/hashing/index.js +2 -2
  76. package/build/esm/sdk/analytics.js +3 -1
  77. package/build/esm/sdk/index.d.ts +1 -3
  78. package/build/esm/sdk/index.js +63 -24
  79. package/build/esm/sdk/models.d.ts +8 -1
  80. package/build/esm/sdk/models.js +29 -1
  81. package/build/esm/sdk/utils.d.ts +1 -0
  82. package/build/esm/sdk/utils.js +12 -0
  83. package/flagsmith-engine/environments/models.ts +3 -1
  84. package/flagsmith-engine/environments/util.ts +2 -1
  85. package/flagsmith-engine/evaluation/evaluationContext/evaluationContext.types.ts +247 -0
  86. package/flagsmith-engine/evaluation/evaluationContext/mappers.ts +204 -0
  87. package/flagsmith-engine/evaluation/evaluationContext/types.ts +233 -0
  88. package/flagsmith-engine/evaluation/evaluationResult/evaluationResult.types.ts +71 -0
  89. package/flagsmith-engine/evaluation/models.ts +96 -0
  90. package/flagsmith-engine/features/models.ts +3 -2
  91. package/flagsmith-engine/features/types.ts +5 -0
  92. package/flagsmith-engine/features/util.ts +4 -0
  93. package/flagsmith-engine/index.ts +229 -72
  94. package/flagsmith-engine/segments/constants.ts +1 -0
  95. package/flagsmith-engine/segments/evaluators.ts +178 -62
  96. package/flagsmith-engine/segments/models.ts +171 -23
  97. package/flagsmith-engine/utils/hashing/index.ts +2 -2
  98. package/package.json +13 -2
  99. package/release-please-config.json +62 -0
  100. package/sdk/analytics.ts +3 -1
  101. package/sdk/index.ts +89 -30
  102. package/sdk/models.ts +44 -2
  103. package/sdk/utils.ts +13 -0
  104. package/tests/engine/e2e/engine.test.ts +43 -38
  105. package/tests/engine/unit/engine.test.ts +306 -60
  106. package/tests/engine/unit/mappers.test.ts +353 -0
  107. package/tests/engine/unit/segments/segment_evaluators.test.ts +391 -49
  108. package/tests/engine/unit/segments/segments_model.test.ts +85 -0
  109. package/tests/engine/unit/utils/utils.test.ts +7 -7
  110. package/tests/engine/unit/utils.ts +1 -1
  111. package/tests/sdk/analytics.test.ts +6 -1
  112. package/tests/sdk/data/environment.json +1 -0
  113. package/tests/sdk/flagsmith-environment-flags.test.ts +28 -0
  114. package/tests/sdk/flagsmith-identity-flags.test.ts +11 -2
  115. package/tests/sdk/flagsmith.test.ts +190 -3
  116. package/tests/sdk/offline-handlers.test.ts +3 -1
  117. package/vitest.config.esm.ts +34 -0
@@ -1,37 +1,149 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.traitsMatchSegmentCondition = exports.evaluateIdentityInSegment = exports.getIdentitySegments = void 0;
3
+ exports.getContextValue = exports.traitsMatchSegmentCondition = exports.getIdentitySegments = void 0;
4
+ const jsonpathModule = require("jsonpath");
4
5
  const index_js_1 = require("../utils/hashing/index.js");
6
+ const models_js_1 = require("./models.js");
5
7
  const constants_js_1 = require("./constants.js");
6
- function getIdentitySegments(environment, identity, overrideTraits) {
7
- return environment.project.segments.filter(segment => evaluateIdentityInSegment(identity, segment, overrideTraits));
8
+ // Handle ESM/CJS interop - jsonpath exports default in ESM
9
+ const jsonpath = jsonpathModule.default || jsonpathModule;
10
+ /**
11
+ * Returns all segments that the identity belongs to based on segment rules evaluation.
12
+ *
13
+ * An identity belongs to a segment if it matches ALL of the segment's rules.
14
+ * If the context has no identity or segments, returns an empty array.
15
+ *
16
+ * @param context - Evaluation context containing identity and segment definitions
17
+ * @returns Array of segments that the identity matches
18
+ */
19
+ function getIdentitySegments(context) {
20
+ if (!context.identity || !context.segments)
21
+ return [];
22
+ return Object.values(context.segments).filter(segment => {
23
+ if (segment.rules.length === 0)
24
+ return false;
25
+ return segment.rules.every(rule => traitsMatchSegmentRule(rule, segment.key, context));
26
+ });
8
27
  }
9
28
  exports.getIdentitySegments = getIdentitySegments;
10
- function evaluateIdentityInSegment(identity, segment, overrideTraits) {
11
- return (segment.rules.length > 0 &&
12
- segment.rules.filter(rule => traitsMatchSegmentRule(overrideTraits || identity.identityTraits, rule, segment.id, identity.djangoID || identity.compositeKey)).length === segment.rules.length);
13
- }
14
- exports.evaluateIdentityInSegment = evaluateIdentityInSegment;
15
- function traitsMatchSegmentRule(identityTraits, rule, segmentId, identityId) {
16
- const matchesConditions = rule.conditions.length > 0
17
- ? rule.matchingFunction()(rule.conditions.map(condition => traitsMatchSegmentCondition(identityTraits, condition, segmentId, identityId)))
18
- : true;
19
- return (matchesConditions &&
20
- rule.rules.filter(rule => traitsMatchSegmentRule(identityTraits, rule, segmentId, identityId)).length === rule.rules.length);
21
- }
22
- function traitsMatchSegmentCondition(identityTraits, condition, segmentId, identityId) {
23
- if (condition.operator == constants_js_1.PERCENTAGE_SPLIT) {
24
- var hashedPercentage = (0, index_js_1.getHashedPercentateForObjIds)([segmentId, identityId]);
29
+ /**
30
+ * Evaluates whether a segment condition matches the identity's traits or context values.
31
+ *
32
+ * Handles different types of conditions:
33
+ * - PERCENTAGE_SPLIT: Deterministic percentage-based bucketing using identity key
34
+ * - IS_SET/IS_NOT_SET: Checks for trait existence
35
+ * - Standard operators: EQUAL, NOT_EQUAL, etc. via SegmentConditionModel
36
+ * - JSONPath expressions: $.identity.identifier, $.environment.name, etc.
37
+ *
38
+ * @param condition - The condition to evaluate (property, operator, value)
39
+ * @param segmentKey - Key of the segment (used for percentage split hashing)
40
+ * @param context - Evaluation context containing identity, traits, and environment
41
+ * @returns true if the condition matches
42
+ */
43
+ function traitsMatchSegmentCondition(condition, segmentKey, context) {
44
+ if (condition.operator === constants_js_1.PERCENTAGE_SPLIT) {
45
+ let splitKey;
46
+ if (!condition.property) {
47
+ splitKey = context?.identity?.key;
48
+ }
49
+ else {
50
+ splitKey = getContextValue(condition.property, context);
51
+ }
52
+ if (!splitKey) {
53
+ return false;
54
+ }
55
+ const hashedPercentage = (0, index_js_1.getHashedPercentageForObjIds)([segmentKey, splitKey]);
25
56
  return hashedPercentage <= parseFloat(String(condition.value));
26
57
  }
27
- const traits = identityTraits.filter(t => t.traitKey === condition.property_);
28
- const trait = traits.length > 0 ? traits[0] : undefined;
58
+ if (!condition.property) {
59
+ return false;
60
+ }
61
+ const traitValue = getTraitValue(condition.property, context);
29
62
  if (condition.operator === constants_js_1.IS_SET) {
30
- return !!trait;
63
+ return traitValue !== undefined && traitValue !== null;
64
+ }
65
+ if (condition.operator === constants_js_1.IS_NOT_SET) {
66
+ return traitValue === undefined || traitValue === null;
31
67
  }
32
- else if (condition.operator === constants_js_1.IS_NOT_SET) {
33
- return trait == undefined;
68
+ if (traitValue !== undefined && traitValue !== null) {
69
+ const segmentCondition = new models_js_1.SegmentConditionModel(condition.operator, condition.value, condition.property);
70
+ return segmentCondition.matchesTraitValue(traitValue);
34
71
  }
35
- return trait ? condition.matchesTraitValue(trait.traitValue) : false;
72
+ return false;
36
73
  }
37
74
  exports.traitsMatchSegmentCondition = traitsMatchSegmentCondition;
75
+ function traitsMatchSegmentRule(rule, segmentKey, context) {
76
+ const matchesConditions = evaluateConditions(rule, segmentKey, context);
77
+ const matchesSubRules = evaluateSubRules(rule, segmentKey, context);
78
+ return matchesConditions && matchesSubRules;
79
+ }
80
+ function evaluateConditions(rule, segmentKey, context) {
81
+ if (!rule.conditions || rule.conditions.length === 0)
82
+ return true;
83
+ const conditionResults = rule.conditions.map((condition) => traitsMatchSegmentCondition(condition, segmentKey, context));
84
+ return evaluateRuleConditions(rule.type, conditionResults);
85
+ }
86
+ function evaluateSubRules(rule, segmentKey, context) {
87
+ if (!rule.rules || rule.rules.length === 0)
88
+ return true;
89
+ return rule.rules.every((subRule) => traitsMatchSegmentRule(subRule, segmentKey, context));
90
+ }
91
+ function evaluateRuleConditions(ruleType, conditionResults) {
92
+ switch (ruleType) {
93
+ case 'ALL':
94
+ return conditionResults.length === 0 || conditionResults.every(result => result);
95
+ case 'ANY':
96
+ return conditionResults.length > 0 && conditionResults.some(result => result);
97
+ case 'NONE':
98
+ return conditionResults.length === 0 || conditionResults.every(result => !result);
99
+ default:
100
+ return false;
101
+ }
102
+ }
103
+ function getTraitValue(property, context) {
104
+ if (property.startsWith('$.')) {
105
+ const contextValue = getContextValue(property, context);
106
+ if (contextValue !== undefined && isPrimitive(contextValue)) {
107
+ return contextValue;
108
+ }
109
+ }
110
+ const traits = context?.identity?.traits || {};
111
+ return traits[property];
112
+ }
113
+ function isPrimitive(value) {
114
+ if (value === null || value === undefined) {
115
+ return true;
116
+ }
117
+ // Objects and arrays are non-primitive
118
+ return typeof value !== 'object';
119
+ }
120
+ /**
121
+ * Evaluates JSONPath expressions against the evaluation context.
122
+ *
123
+ * Supports accessing nested context values using JSONPath syntax.
124
+ * Commonly used paths:
125
+ * - $.identity.identifier - User's unique identifier
126
+ * - $.identity.key - User's internal key
127
+ * - $.environment.name - Environment name
128
+ * - $.environment.key - Environment key
129
+ *
130
+ * @param jsonPath - JSONPath expression starting with '$.'
131
+ * @param context - Evaluation context to query against
132
+ * @returns The resolved value, or undefined if path doesn't exist or is invalid
133
+ */
134
+ function getContextValue(jsonPath, context) {
135
+ if (!context || !jsonPath?.startsWith('$.'))
136
+ return undefined;
137
+ try {
138
+ const normalizedPath = normalizeJsonPath(jsonPath);
139
+ const results = jsonpath.query(context, normalizedPath);
140
+ return results.length > 0 ? results[0] : undefined;
141
+ }
142
+ catch (error) {
143
+ return undefined;
144
+ }
145
+ }
146
+ exports.getContextValue = getContextValue;
147
+ function normalizeJsonPath(jsonPath) {
148
+ return jsonPath.replace(/\.([^.\[\]]+)$/, "['$1']");
149
+ }
@@ -1,11 +1,13 @@
1
1
  import { FeatureStateModel } from '../features/models.js';
2
+ import { EvaluationContext } from '../evaluation/evaluationContext/evaluationContext.types.js';
3
+ import { EvaluationResultSegments } from '../evaluation/models.js';
2
4
  export declare const all: (iterable: Array<any>) => boolean;
3
5
  export declare const any: (iterable: Array<any>) => boolean;
4
6
  export declare const matchingFunctions: {
5
7
  [x: string]: (thisValue: any, otherValue: any) => any;
6
8
  };
7
9
  export declare const semverMatchingFunction: {
8
- [x: string]: ((thisValue: any, otherValue: any) => any) | ((thisValue: any, otherValue: any) => boolean);
10
+ [x: string]: ((thisValue: any, otherValue: any) => any) | ((conditionValue: any, traitValue: any) => boolean);
9
11
  };
10
12
  export declare const getMatchingFunctions: (semver: boolean) => {
11
13
  [x: string]: (thisValue: any, otherValue: any) => any;
@@ -15,9 +17,9 @@ export declare class SegmentConditionModel {
15
17
  [key: string]: string;
16
18
  };
17
19
  operator: string;
18
- value: string | null | undefined;
19
- property_: string | null | undefined;
20
- constructor(operator: string, value?: string | null | undefined, property?: string | null | undefined);
20
+ value: string | null | undefined | string[];
21
+ property: string | null | undefined;
22
+ constructor(operator: string, value?: string | null | undefined | string[], property?: string | null | undefined);
21
23
  matchesTraitValue(traitValue: any): any;
22
24
  }
23
25
  export declare class SegmentRuleModel {
@@ -34,4 +36,7 @@ export declare class SegmentModel {
34
36
  rules: SegmentRuleModel[];
35
37
  featureStates: FeatureStateModel[];
36
38
  constructor(id: number, name: string);
39
+ static fromSegmentResult(segmentResults: EvaluationResultSegments, evaluationContext: EvaluationContext): SegmentModel[];
40
+ private static createFeatureStatesFromOverrides;
41
+ private static createMultivariateValues;
37
42
  }
@@ -2,9 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SegmentModel = exports.SegmentRuleModel = exports.SegmentConditionModel = exports.getMatchingFunctions = exports.semverMatchingFunction = exports.matchingFunctions = exports.any = exports.all = void 0;
4
4
  const semver = require("semver");
5
+ const models_js_1 = require("../features/models.js");
5
6
  const index_js_1 = require("../utils/index.js");
6
7
  const constants_js_1 = require("./constants.js");
7
8
  const util_js_1 = require("./util.js");
9
+ const constants_js_2 = require("../features/constants.js");
10
+ const models_js_2 = require("../evaluation/models.js");
8
11
  const all = (iterable) => iterable.filter(e => !!e).length === iterable.length;
9
12
  exports.all = all;
10
13
  const any = (iterable) => iterable.filter(e => !!e).length > 0;
@@ -16,15 +19,33 @@ exports.matchingFunctions = {
16
19
  [constants_js_1.CONDITION_OPERATORS.LESS_THAN]: (thisValue, otherValue) => thisValue > otherValue,
17
20
  [constants_js_1.CONDITION_OPERATORS.LESS_THAN_INCLUSIVE]: (thisValue, otherValue) => thisValue >= otherValue,
18
21
  [constants_js_1.CONDITION_OPERATORS.NOT_EQUAL]: (thisValue, otherValue) => thisValue != otherValue,
19
- [constants_js_1.CONDITION_OPERATORS.CONTAINS]: (thisValue, otherValue) => !!otherValue && otherValue.includes(thisValue)
22
+ [constants_js_1.CONDITION_OPERATORS.CONTAINS]: (thisValue, otherValue) => {
23
+ try {
24
+ return !!otherValue && otherValue.includes(thisValue);
25
+ }
26
+ catch {
27
+ return false;
28
+ }
29
+ }
30
+ };
31
+ // Semver library throws an error if the version is invalid, in this case, we want to catch and return false
32
+ const safeSemverCompare = (semverMatchingFunction) => {
33
+ return (conditionValue, traitValue) => {
34
+ try {
35
+ return semverMatchingFunction(conditionValue, traitValue);
36
+ }
37
+ catch {
38
+ return false;
39
+ }
40
+ };
20
41
  };
21
42
  exports.semverMatchingFunction = {
22
43
  ...exports.matchingFunctions,
23
- [constants_js_1.CONDITION_OPERATORS.EQUAL]: (thisValue, otherValue) => semver.eq(thisValue, otherValue),
24
- [constants_js_1.CONDITION_OPERATORS.GREATER_THAN]: (thisValue, otherValue) => semver.gt(otherValue, thisValue),
25
- [constants_js_1.CONDITION_OPERATORS.GREATER_THAN_INCLUSIVE]: (thisValue, otherValue) => semver.gte(otherValue, thisValue),
26
- [constants_js_1.CONDITION_OPERATORS.LESS_THAN]: (thisValue, otherValue) => semver.gt(thisValue, otherValue),
27
- [constants_js_1.CONDITION_OPERATORS.LESS_THAN_INCLUSIVE]: (thisValue, otherValue) => semver.gte(thisValue, otherValue)
44
+ [constants_js_1.CONDITION_OPERATORS.EQUAL]: safeSemverCompare((conditionValue, traitValue) => semver.eq(traitValue, conditionValue)),
45
+ [constants_js_1.CONDITION_OPERATORS.GREATER_THAN]: safeSemverCompare((conditionValue, traitValue) => semver.gt(traitValue, conditionValue)),
46
+ [constants_js_1.CONDITION_OPERATORS.GREATER_THAN_INCLUSIVE]: safeSemverCompare((conditionValue, traitValue) => semver.gte(traitValue, conditionValue)),
47
+ [constants_js_1.CONDITION_OPERATORS.LESS_THAN]: safeSemverCompare((conditionValue, traitValue) => semver.lt(traitValue, conditionValue)),
48
+ [constants_js_1.CONDITION_OPERATORS.LESS_THAN_INCLUSIVE]: safeSemverCompare((conditionValue, traitValue) => semver.lte(traitValue, conditionValue))
28
49
  };
29
50
  const getMatchingFunctions = (semver) => semver ? exports.semverMatchingFunction : exports.matchingFunctions;
30
51
  exports.getMatchingFunctions = getMatchingFunctions;
@@ -37,11 +58,11 @@ class SegmentConditionModel {
37
58
  };
38
59
  operator;
39
60
  value;
40
- property_;
61
+ property;
41
62
  constructor(operator, value, property) {
42
63
  this.operator = operator;
43
64
  this.value = value;
44
- this.property_ = property;
65
+ this.property = property;
45
66
  }
46
67
  matchesTraitValue(traitValue) {
47
68
  const evaluators = {
@@ -51,17 +72,49 @@ class SegmentConditionModel {
51
72
  !traitValue.includes(this.value?.toString()));
52
73
  },
53
74
  evaluateRegex: (traitValue) => {
54
- return !!this.value && !!traitValue?.toString().match(new RegExp(this.value));
75
+ try {
76
+ if (!this.value) {
77
+ return false;
78
+ }
79
+ const regex = new RegExp(this.value?.toString());
80
+ return !!traitValue?.toString().match(regex);
81
+ }
82
+ catch {
83
+ return false;
84
+ }
55
85
  },
56
86
  evaluateModulo: (traitValue) => {
57
- if (isNaN(parseFloat(traitValue)) || !this.value) {
87
+ const parsedTraitValue = parseFloat(traitValue);
88
+ if (isNaN(parsedTraitValue) || !this.value) {
89
+ return false;
90
+ }
91
+ const parts = this.value.toString().split('|');
92
+ if (parts.length !== 2) {
93
+ return false;
94
+ }
95
+ const divisor = parseFloat(parts[0]);
96
+ const remainder = parseFloat(parts[1]);
97
+ if (isNaN(divisor) || isNaN(remainder) || divisor === 0) {
58
98
  return false;
59
99
  }
60
- const parts = this.value.split('|');
61
- const [divisor, reminder] = [parseFloat(parts[0]), parseFloat(parts[1])];
62
- return traitValue % divisor === reminder;
100
+ return parsedTraitValue % divisor === remainder;
63
101
  },
64
102
  evaluateIn: (traitValue) => {
103
+ if (!traitValue || typeof traitValue === 'boolean') {
104
+ return false;
105
+ }
106
+ if (Array.isArray(this.value)) {
107
+ return this.value.includes(traitValue.toString());
108
+ }
109
+ if (typeof this.value === 'string') {
110
+ try {
111
+ const parsed = JSON.parse(this.value);
112
+ if (Array.isArray(parsed)) {
113
+ return parsed.includes(traitValue.toString());
114
+ }
115
+ }
116
+ catch { }
117
+ }
65
118
  return this.value?.split(',').includes(traitValue.toString());
66
119
  }
67
120
  };
@@ -107,5 +160,54 @@ class SegmentModel {
107
160
  this.id = id;
108
161
  this.name = name;
109
162
  }
163
+ static fromSegmentResult(segmentResults, evaluationContext) {
164
+ const segmentModels = [];
165
+ if (!evaluationContext.segments) {
166
+ return [];
167
+ }
168
+ for (const segmentResult of segmentResults) {
169
+ if (segmentResult.metadata?.source === models_js_2.SegmentSource.IDENTITY_OVERRIDE) {
170
+ continue;
171
+ }
172
+ const segmentMetadataId = segmentResult.metadata?.id;
173
+ if (!segmentMetadataId) {
174
+ continue;
175
+ }
176
+ const segmentContext = evaluationContext.segments[segmentMetadataId.toString()];
177
+ if (segmentContext) {
178
+ const segment = new SegmentModel(segmentMetadataId, segmentContext.name);
179
+ segment.rules = segmentContext.rules.map(rule => new SegmentRuleModel(rule.type));
180
+ segment.featureStates = SegmentModel.createFeatureStatesFromOverrides(segmentContext.overrides || []);
181
+ segmentModels.push(segment);
182
+ }
183
+ }
184
+ return segmentModels;
185
+ }
186
+ static createFeatureStatesFromOverrides(overrides) {
187
+ if (!overrides)
188
+ return [];
189
+ return overrides
190
+ .filter(override => {
191
+ const overrideMetadataId = override?.metadata?.id;
192
+ return typeof overrideMetadataId === 'number';
193
+ })
194
+ .map(override => {
195
+ const overrideMetadataId = override.metadata.id;
196
+ const feature = new models_js_1.FeatureModel(overrideMetadataId, override.name, override.variants?.length && override.variants.length > 0
197
+ ? constants_js_2.CONSTANTS.MULTIVARIATE
198
+ : constants_js_2.CONSTANTS.STANDARD);
199
+ const featureState = new models_js_1.FeatureStateModel(feature, override.enabled, override.priority || 0);
200
+ if (override.value !== undefined) {
201
+ featureState.setValue(override.value);
202
+ }
203
+ if (override.variants && override.variants.length > 0) {
204
+ featureState.multivariateFeatureStateValues = this.createMultivariateValues(override.variants);
205
+ }
206
+ return featureState;
207
+ });
208
+ }
209
+ static createMultivariateValues(variants) {
210
+ return variants.map(variant => new models_js_1.MultivariateFeatureStateValueModel(new models_js_1.MultivariateFeatureOptionModel(variant.value, variant.id), variant.weight, variant.id));
211
+ }
110
212
  }
111
213
  exports.SegmentModel = SegmentModel;
@@ -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;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getHashedPercentateForObjIds = void 0;
3
+ exports.getHashedPercentageForObjIds = void 0;
4
4
  const node_crypto_1 = require("node:crypto");
5
5
  const md5 = (data) => (0, node_crypto_1.createHash)('md5').update(data).digest('hex');
6
6
  const makeRepeated = (arr, repeats) => Array.from({ length: repeats }, () => arr).flat();
@@ -13,7 +13,7 @@ const makeRepeated = (arr, repeats) => Array.from({ length: repeats }, () => arr
13
13
  * @param {} iterations=1 num times to include each id in the generated string to hash
14
14
  * @returns number number between 0 (inclusive) and 100 (exclusive)
15
15
  */
16
- function getHashedPercentateForObjIds(objectIds, iterations = 1) {
16
+ function getHashedPercentageForObjIds(objectIds, iterations = 1) {
17
17
  let toHash = makeRepeated(objectIds, iterations).join(',');
18
18
  const hashedValue = md5(toHash);
19
19
  const hashedInt = BigInt('0x' + hashedValue);
@@ -22,8 +22,8 @@ function getHashedPercentateForObjIds(objectIds, iterations = 1) {
22
22
  /* istanbul ignore next */
23
23
  if (value === 100) {
24
24
  /* istanbul ignore next */
25
- return getHashedPercentateForObjIds(objectIds, iterations + 1);
25
+ return getHashedPercentageForObjIds(objectIds, iterations + 1);
26
26
  }
27
27
  return value;
28
28
  }
29
- exports.getHashedPercentateForObjIds = getHashedPercentateForObjIds;
29
+ exports.getHashedPercentageForObjIds = getHashedPercentageForObjIds;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AnalyticsProcessor = exports.ANALYTICS_ENDPOINT = void 0;
4
4
  const pino_1 = require("pino");
5
+ const utils_js_1 = require("./utils.js");
5
6
  exports.ANALYTICS_ENDPOINT = './analytics/flags/';
6
7
  /** Duration in seconds to wait before trying to flush collected data after {@link trackFeature} is called. **/
7
8
  const ANALYTICS_TIMER = 10;
@@ -47,7 +48,8 @@ class AnalyticsProcessor {
47
48
  signal: AbortSignal.timeout(this.requestTimeoutMs),
48
49
  headers: {
49
50
  'Content-Type': 'application/json',
50
- 'X-Environment-Key': this.environmentKey
51
+ 'X-Environment-Key': this.environmentKey,
52
+ 'User-Agent': (0, utils_js_1.getUserAgent)()
51
53
  }
52
54
  });
53
55
  await this.currentFlush;
@@ -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,17 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Flagsmith = exports.EnvironmentDataPollingManager = exports.Flags = exports.DefaultFlag = exports.BaseFlag = exports.FlagsmithClientError = exports.FlagsmithAPIError = exports.AnalyticsProcessor = void 0;
4
- const index_js_1 = require("../flagsmith-engine/index.js");
5
4
  const util_js_1 = require("../flagsmith-engine/environments/util.js");
6
- const index_js_2 = require("../flagsmith-engine/index.js");
7
- const index_js_3 = require("../flagsmith-engine/index.js");
8
5
  const analytics_js_1 = require("./analytics.js");
9
6
  const errors_js_1 = require("./errors.js");
10
7
  const models_js_1 = require("./models.js");
11
8
  const polling_manager_js_1 = require("./polling_manager.js");
12
9
  const utils_js_1 = require("./utils.js");
13
- const evaluators_js_1 = require("../flagsmith-engine/segments/evaluators.js");
10
+ const index_js_1 = require("../flagsmith-engine/index.js");
14
11
  const pino_1 = require("pino");
12
+ const mappers_js_1 = require("../flagsmith-engine/evaluation/evaluationContext/mappers.js");
15
13
  var analytics_js_2 = require("./analytics.js");
16
14
  Object.defineProperty(exports, "AnalyticsProcessor", { enumerable: true, get: function () { return analytics_js_2.AnalyticsProcessor; } });
17
15
  var errors_js_2 = require("./errors.js");
@@ -230,7 +228,12 @@ class Flagsmith {
230
228
  key,
231
229
  value: traits?.[key]
232
230
  })));
233
- return (0, evaluators_js_1.getIdentitySegments)(environment, identityModel);
231
+ const context = (0, mappers_js_1.getEvaluationContext)(environment, identityModel);
232
+ if (!context) {
233
+ throw new errors_js_1.FlagsmithClientError('Local evaluation required to obtain identity segments');
234
+ }
235
+ const evaluationResult = (0, index_js_1.getEvaluationResult)(context);
236
+ return index_js_1.SegmentModel.fromSegmentResult(evaluationResult.segments, context);
234
237
  }
235
238
  async fetchEnvironment() {
236
239
  const deferred = new utils_js_1.Deferred();
@@ -279,6 +282,7 @@ class Flagsmith {
279
282
  if (this.environmentKey) {
280
283
  headers['X-Environment-Key'] = this.environmentKey;
281
284
  }
285
+ headers['User-Agent'] = (0, utils_js_1.getUserAgent)();
282
286
  if (this.customHeaders) {
283
287
  for (const [k, v] of Object.entries(this.customHeaders)) {
284
288
  headers[k] = v;
@@ -293,7 +297,7 @@ class Flagsmith {
293
297
  if (data.status !== 200) {
294
298
  throw new errors_js_1.FlagsmithAPIError(`Invalid request made to Flagsmith API. Response status code: ${data.status}`);
295
299
  }
296
- return data.json();
300
+ return { response: data, data: await data.json() };
297
301
  }
298
302
  /**
299
303
  * This promise ensures that the environment is retrieved before attempting to locally evaluate.
@@ -320,16 +324,52 @@ class Flagsmith {
320
324
  if (!this.environmentUrl) {
321
325
  throw new Error('`apiUrl` argument is missing or invalid.');
322
326
  }
323
- const environment_data = await this.getJSONResponse(this.environmentUrl, 'GET');
324
- return (0, util_js_1.buildEnvironmentModel)(environment_data);
327
+ const startTime = Date.now();
328
+ const documents = [];
329
+ let url = this.environmentUrl;
330
+ let loggedWarning = false;
331
+ while (true) {
332
+ try {
333
+ if (!loggedWarning) {
334
+ const elapsedMs = Date.now() - startTime;
335
+ if (elapsedMs > this.environmentRefreshIntervalSeconds * 1000) {
336
+ this.logger.warn(`Environment document retrieval exceeded the polling interval of ${this.environmentRefreshIntervalSeconds} seconds.`);
337
+ loggedWarning = true;
338
+ }
339
+ }
340
+ const { response, data } = await this.getJSONResponse(url, 'GET');
341
+ documents.push(data);
342
+ const linkHeader = response.headers.get('link');
343
+ if (linkHeader) {
344
+ const nextMatch = linkHeader.match(/<([^>]+)>;\s*rel="next"/);
345
+ if (nextMatch) {
346
+ const relativeUrl = decodeURIComponent(nextMatch[1]);
347
+ url = new URL(relativeUrl, this.apiUrl).href;
348
+ continue;
349
+ }
350
+ }
351
+ break;
352
+ }
353
+ catch (error) {
354
+ throw error;
355
+ }
356
+ }
357
+ // Compile the document
358
+ const compiledDocument = documents[0];
359
+ for (let i = 1; i < documents.length; i++) {
360
+ compiledDocument.identity_overrides = compiledDocument.identity_overrides || [];
361
+ compiledDocument.identity_overrides.push(...(documents[i].identity_overrides || []));
362
+ }
363
+ return (0, util_js_1.buildEnvironmentModel)(compiledDocument);
325
364
  }
326
365
  async getEnvironmentFlagsFromDocument() {
327
366
  const environment = await this.getEnvironment();
328
- const flags = models_js_1.Flags.fromFeatureStateModels({
329
- featureStates: (0, index_js_1.getEnvironmentFeatureStates)(environment),
330
- analyticsProcessor: this.analyticsProcessor,
331
- defaultFlagHandler: this.defaultFlagHandler
332
- });
367
+ const context = (0, mappers_js_1.getEvaluationContext)(environment, undefined, undefined, true);
368
+ if (!context) {
369
+ throw new errors_js_1.FlagsmithClientError('Unable to get flags. No environment present.');
370
+ }
371
+ const evaluationResult = (0, index_js_1.getEvaluationResult)(context);
372
+ const flags = models_js_1.Flags.fromEvaluationResult(evaluationResult);
333
373
  if (!!this.cache) {
334
374
  await this.cache.set('flags', flags);
335
375
  }
@@ -341,13 +381,12 @@ class Flagsmith {
341
381
  key,
342
382
  value: traits[key]
343
383
  })));
344
- const featureStates = (0, index_js_1.getIdentityFeatureStates)(environment, identityModel);
345
- const flags = models_js_1.Flags.fromFeatureStateModels({
346
- featureStates: featureStates,
347
- analyticsProcessor: this.analyticsProcessor,
348
- defaultFlagHandler: this.defaultFlagHandler,
349
- identityID: identityModel.djangoID || identityModel.compositeKey
350
- });
384
+ const context = (0, mappers_js_1.getEvaluationContext)(environment, identityModel);
385
+ if (!context) {
386
+ throw new errors_js_1.FlagsmithClientError('Unable to get flags. No environment present.');
387
+ }
388
+ const evaluationResult = (0, index_js_1.getEvaluationResult)(context);
389
+ const flags = models_js_1.Flags.fromEvaluationResult(evaluationResult, this.defaultFlagHandler, this.analyticsProcessor);
351
390
  if (!!this.cache) {
352
391
  await this.cache.set(`flags-${identifier}`, flags);
353
392
  }
@@ -357,7 +396,7 @@ class Flagsmith {
357
396
  if (!this.environmentFlagsUrl) {
358
397
  throw new Error('`apiUrl` argument is missing or invalid.');
359
398
  }
360
- const apiFlags = await this.getJSONResponse(this.environmentFlagsUrl, 'GET');
399
+ const { data: apiFlags } = await this.getJSONResponse(this.environmentFlagsUrl, 'GET');
361
400
  const flags = models_js_1.Flags.fromAPIFlags({
362
401
  apiFlags: apiFlags,
363
402
  analyticsProcessor: this.analyticsProcessor,
@@ -373,7 +412,7 @@ class Flagsmith {
373
412
  throw new Error('`apiUrl` argument is missing or invalid.');
374
413
  }
375
414
  const data = (0, utils_js_1.generateIdentitiesData)(identifier, traits, transient);
376
- const jsonResponse = await this.getJSONResponse(this.identitiesUrl, 'POST', data);
415
+ const { data: jsonResponse } = await this.getJSONResponse(this.identitiesUrl, 'POST', data);
377
416
  const flags = models_js_1.Flags.fromAPIFlags({
378
417
  apiFlags: jsonResponse['flags'],
379
418
  analyticsProcessor: this.analyticsProcessor,
@@ -385,13 +424,13 @@ class Flagsmith {
385
424
  return flags;
386
425
  }
387
426
  getIdentityModel(environment, identifier, traits) {
388
- const traitModels = traits.map(trait => new index_js_3.TraitModel(trait.key, trait.value));
427
+ const traitModels = traits.map(trait => new index_js_1.TraitModel(trait.key, trait.value));
389
428
  let identityWithOverrides = this.identitiesWithOverridesByIdentifier?.get(identifier);
390
429
  if (identityWithOverrides) {
391
430
  identityWithOverrides.updateTraits(traitModels);
392
431
  return identityWithOverrides;
393
432
  }
394
- return new index_js_2.IdentityModel('0', traitModels, [], environment.apiKey, identifier);
433
+ return new index_js_1.IdentityModel('0', traitModels, [], environment.apiKey, identifier);
395
434
  }
396
435
  }
397
436
  exports.Flagsmith = Flagsmith;
@@ -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;