flagsmith-nodejs 2.0.0-beta.4 → 2.0.0-beta.5

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 (63) hide show
  1. package/.idea/flagsmith-nodejs-client.iml +12 -0
  2. package/.idea/modules.xml +8 -0
  3. package/.idea/vcs.xml +6 -0
  4. package/build/flagsmith-engine/environments/integrations/models.d.ts +4 -0
  5. package/build/flagsmith-engine/environments/integrations/models.js +8 -0
  6. package/build/flagsmith-engine/environments/models.d.ts +25 -0
  7. package/build/flagsmith-engine/environments/models.js +40 -0
  8. package/build/flagsmith-engine/environments/util.d.ts +3 -0
  9. package/build/flagsmith-engine/environments/util.js +19 -0
  10. package/build/flagsmith-engine/features/constants.d.ts +4 -0
  11. package/build/flagsmith-engine/features/constants.js +7 -0
  12. package/build/flagsmith-engine/features/models.d.ts +32 -0
  13. package/build/flagsmith-engine/features/models.js +85 -0
  14. package/build/flagsmith-engine/features/util.d.ts +3 -0
  15. package/build/flagsmith-engine/features/util.js +20 -0
  16. package/build/flagsmith-engine/identities/models.d.ts +15 -0
  17. package/build/flagsmith-engine/identities/models.js +47 -0
  18. package/build/flagsmith-engine/identities/traits/models.d.ts +5 -0
  19. package/build/flagsmith-engine/identities/traits/models.js +12 -0
  20. package/build/flagsmith-engine/identities/util.d.ts +4 -0
  21. package/build/flagsmith-engine/identities/util.js +22 -0
  22. package/build/flagsmith-engine/index.d.ts +8 -0
  23. package/build/flagsmith-engine/index.js +61 -0
  24. package/build/flagsmith-engine/organisations/models.d.ts +9 -0
  25. package/build/flagsmith-engine/organisations/models.js +21 -0
  26. package/build/flagsmith-engine/organisations/util.d.ts +2 -0
  27. package/build/flagsmith-engine/organisations/util.js +8 -0
  28. package/build/flagsmith-engine/projects/models.d.ts +10 -0
  29. package/build/flagsmith-engine/projects/models.js +17 -0
  30. package/build/flagsmith-engine/projects/util.d.ts +2 -0
  31. package/build/flagsmith-engine/projects/util.js +15 -0
  32. package/build/flagsmith-engine/segments/constants.d.ts +26 -0
  33. package/build/flagsmith-engine/segments/constants.js +31 -0
  34. package/build/flagsmith-engine/segments/evaluators.d.ts +6 -0
  35. package/build/flagsmith-engine/segments/evaluators.js +29 -0
  36. package/build/flagsmith-engine/segments/models.d.ts +31 -0
  37. package/build/flagsmith-engine/segments/models.js +83 -0
  38. package/build/flagsmith-engine/segments/util.d.ts +4 -0
  39. package/build/flagsmith-engine/segments/util.js +23 -0
  40. package/build/flagsmith-engine/utils/collections.d.ts +4 -0
  41. package/build/flagsmith-engine/utils/collections.js +16 -0
  42. package/build/flagsmith-engine/utils/errors.d.ts +2 -0
  43. package/build/flagsmith-engine/utils/errors.js +6 -0
  44. package/build/flagsmith-engine/utils/hashing/index.d.ts +9 -0
  45. package/build/flagsmith-engine/utils/hashing/index.js +54 -0
  46. package/build/flagsmith-engine/utils/index.d.ts +1 -0
  47. package/build/flagsmith-engine/utils/index.js +14 -0
  48. package/build/index.d.ts +1 -0
  49. package/build/index.js +11 -0
  50. package/build/sdk/analytics.d.ts +28 -0
  51. package/build/sdk/analytics.js +60 -0
  52. package/build/sdk/errors.d.ts +4 -0
  53. package/build/sdk/errors.js +9 -0
  54. package/build/sdk/index.d.ts +118 -0
  55. package/build/sdk/index.js +263 -0
  56. package/build/sdk/models.d.ts +55 -0
  57. package/build/sdk/models.js +101 -0
  58. package/build/sdk/polling_manager.d.ts +9 -0
  59. package/build/sdk/polling_manager.js +31 -0
  60. package/build/sdk/utils.d.ts +12 -0
  61. package/build/sdk/utils.js +45 -0
  62. package/package.json +1 -1
  63. package/.tool-versions +0 -1
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.evaluateIdentityInSegment = exports.getIdentitySegments = void 0;
4
+ const hashing_1 = require("../utils/hashing");
5
+ const constants_1 = require("./constants");
6
+ function getIdentitySegments(environment, identity, overrideTraits) {
7
+ return environment.project.segments.filter(segment => evaluateIdentityInSegment(identity, segment, overrideTraits));
8
+ }
9
+ 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.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_1.PERCENTAGE_SPLIT) {
24
+ return (0, hashing_1.getHashedPercentateForObjIds)([segmentId, identityId]) <= parseFloat(condition.value);
25
+ }
26
+ const traits = identityTraits.filter(t => t.traitKey === condition.property_);
27
+ const trait = traits.length > 0 ? traits[0] : undefined;
28
+ return trait ? condition.matchesTraitValue(trait.traitValue) : false;
29
+ }
@@ -0,0 +1,31 @@
1
+ import { FeatureStateModel } from '../features/models';
2
+ export declare const all: (iterable: Array<any>) => boolean;
3
+ export declare const any: (iterable: Array<any>) => boolean;
4
+ export declare const matchingFunctions: {
5
+ [x: string]: (thisValue: any, otherValue: any) => any;
6
+ };
7
+ export declare class SegmentConditionModel {
8
+ EXCEPTION_OPERATOR_METHODS: {
9
+ [key: string]: string;
10
+ };
11
+ operator: string;
12
+ value: string;
13
+ property_: string | undefined;
14
+ constructor(operator: string, value: string, property?: string);
15
+ matchesTraitValue(traitValue: any): any;
16
+ }
17
+ export declare class SegmentRuleModel {
18
+ type: string;
19
+ rules: SegmentRuleModel[];
20
+ conditions: SegmentConditionModel[];
21
+ constructor(type: string);
22
+ static none(iterable: Array<any>): boolean;
23
+ matchingFunction(): CallableFunction;
24
+ }
25
+ export declare class SegmentModel {
26
+ id: number;
27
+ name: string;
28
+ rules: SegmentRuleModel[];
29
+ featureStates: FeatureStateModel[];
30
+ constructor(id: number, name: string);
31
+ }
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SegmentModel = exports.SegmentRuleModel = exports.SegmentConditionModel = exports.matchingFunctions = exports.any = exports.all = void 0;
4
+ const utils_1 = require("../utils");
5
+ const constants_1 = require("./constants");
6
+ const all = (iterable) => iterable.filter(e => !!e).length === iterable.length;
7
+ exports.all = all;
8
+ const any = (iterable) => iterable.filter(e => !!e).length > 0;
9
+ exports.any = any;
10
+ exports.matchingFunctions = {
11
+ [constants_1.CONDITION_OPERATORS.EQUAL]: (thisValue, otherValue) => thisValue == otherValue,
12
+ [constants_1.CONDITION_OPERATORS.GREATER_THAN]: (thisValue, otherValue) => otherValue > thisValue,
13
+ [constants_1.CONDITION_OPERATORS.GREATER_THAN_INCLUSIVE]: (thisValue, otherValue) => otherValue >= thisValue,
14
+ [constants_1.CONDITION_OPERATORS.LESS_THAN]: (thisValue, otherValue) => thisValue > otherValue,
15
+ [constants_1.CONDITION_OPERATORS.LESS_THAN_INCLUSIVE]: (thisValue, otherValue) => thisValue >= otherValue,
16
+ [constants_1.CONDITION_OPERATORS.NOT_EQUAL]: (thisValue, otherValue) => thisValue != otherValue,
17
+ [constants_1.CONDITION_OPERATORS.CONTAINS]: (thisValue, otherValue) => otherValue.includes(thisValue),
18
+ [constants_1.CONDITION_OPERATORS.NOT_CONTAINS]: (thisValue, otherValue) => !otherValue.includes(thisValue)
19
+ };
20
+ class SegmentConditionModel {
21
+ EXCEPTION_OPERATOR_METHODS = {
22
+ [constants_1.NOT_CONTAINS]: 'evaluateNotContains',
23
+ [constants_1.REGEX]: 'evaluateRegex'
24
+ };
25
+ operator;
26
+ value;
27
+ property_;
28
+ constructor(operator, value, property) {
29
+ this.operator = operator;
30
+ this.value = value;
31
+ this.property_ = property;
32
+ }
33
+ matchesTraitValue(traitValue) {
34
+ const evaluators = {
35
+ evaluateNotContains: (traitValue) => {
36
+ return !traitValue.includes(this.value);
37
+ },
38
+ evaluateRegex: (traitValue) => {
39
+ return !!traitValue.match(new RegExp(this.value));
40
+ }
41
+ };
42
+ // TODO: move this logic to the evaluator module
43
+ if (this.EXCEPTION_OPERATOR_METHODS[this.operator]) {
44
+ const evaluatorFunction = evaluators[this.EXCEPTION_OPERATOR_METHODS[this.operator]];
45
+ return evaluatorFunction(traitValue);
46
+ }
47
+ const defaultFunction = (x, y) => false;
48
+ const matchingFunction = exports.matchingFunctions[this.operator] || defaultFunction;
49
+ const castToTypeOfTraitValue = (0, utils_1.getCastingFunction)(traitValue);
50
+ return matchingFunction(castToTypeOfTraitValue(this.value), traitValue);
51
+ }
52
+ }
53
+ exports.SegmentConditionModel = SegmentConditionModel;
54
+ class SegmentRuleModel {
55
+ type;
56
+ rules = [];
57
+ conditions = [];
58
+ constructor(type) {
59
+ this.type = type;
60
+ }
61
+ static none(iterable) {
62
+ return iterable.filter(e => !!e).length === 0;
63
+ }
64
+ matchingFunction() {
65
+ return {
66
+ [constants_1.ANY_RULE]: exports.any,
67
+ [constants_1.ALL_RULE]: exports.all,
68
+ [constants_1.NONE_RULE]: SegmentRuleModel.none
69
+ }[this.type];
70
+ }
71
+ }
72
+ exports.SegmentRuleModel = SegmentRuleModel;
73
+ class SegmentModel {
74
+ id;
75
+ name;
76
+ rules = [];
77
+ featureStates = [];
78
+ constructor(id, name) {
79
+ this.id = id;
80
+ this.name = name;
81
+ }
82
+ }
83
+ exports.SegmentModel = SegmentModel;
@@ -0,0 +1,4 @@
1
+ import { SegmentConditionModel, SegmentModel, SegmentRuleModel } from './models';
2
+ export declare function buildSegmentConditionModel(segmentConditionJSON: any): SegmentConditionModel;
3
+ export declare function buildSegmentRuleModel(ruleModelJSON: any): SegmentRuleModel;
4
+ export declare function buildSegmentModel(segmentModelJSON: any): SegmentModel;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildSegmentModel = exports.buildSegmentRuleModel = exports.buildSegmentConditionModel = void 0;
4
+ const util_1 = require("../features/util");
5
+ const models_1 = require("./models");
6
+ function buildSegmentConditionModel(segmentConditionJSON) {
7
+ return new models_1.SegmentConditionModel(segmentConditionJSON.operator, segmentConditionJSON.value, segmentConditionJSON.property_);
8
+ }
9
+ exports.buildSegmentConditionModel = buildSegmentConditionModel;
10
+ function buildSegmentRuleModel(ruleModelJSON) {
11
+ const ruleModel = new models_1.SegmentRuleModel(ruleModelJSON.type);
12
+ ruleModel.rules = ruleModelJSON.rules.map((r) => buildSegmentRuleModel(r));
13
+ ruleModel.conditions = ruleModelJSON.conditions.map((c) => buildSegmentConditionModel(c));
14
+ return ruleModel;
15
+ }
16
+ exports.buildSegmentRuleModel = buildSegmentRuleModel;
17
+ function buildSegmentModel(segmentModelJSON) {
18
+ const model = new models_1.SegmentModel(segmentModelJSON.id, segmentModelJSON.name);
19
+ model.featureStates = segmentModelJSON['feature_states'].map((fs) => (0, util_1.buildFeatureStateModel)(fs));
20
+ model.rules = segmentModelJSON['rules'].map((r) => buildSegmentRuleModel(r));
21
+ return model;
22
+ }
23
+ exports.buildSegmentModel = buildSegmentModel;
@@ -0,0 +1,4 @@
1
+ import { FeatureStateModel } from '../features/models';
2
+ export declare class IdentityFeaturesList extends Array<FeatureStateModel> {
3
+ push(...e: FeatureStateModel[]): number;
4
+ }
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IdentityFeaturesList = void 0;
4
+ class IdentityFeaturesList extends Array {
5
+ push(...e) {
6
+ for (const [_, item] of e.entries()) {
7
+ for (const [k, v] of this.entries()) {
8
+ if (v.djangoID === item.djangoID) {
9
+ throw new Error('feature state for this feature already exists');
10
+ }
11
+ }
12
+ }
13
+ return super.push(...e);
14
+ }
15
+ }
16
+ exports.IdentityFeaturesList = IdentityFeaturesList;
@@ -0,0 +1,2 @@
1
+ export declare class FeatureStateNotFound extends Error {
2
+ }
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FeatureStateNotFound = void 0;
4
+ class FeatureStateNotFound extends Error {
5
+ }
6
+ exports.FeatureStateNotFound = FeatureStateNotFound;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Given a list of object ids, get a floating point number between 0 and 1 based on
3
+ * the hash of those ids. This should give the same value every time for any list of ids.
4
+ *
5
+ * @param {Array<any>} objectIds list of object ids to calculate the has for
6
+ * @param {} iterations=1 num times to include each id in the generated string to hash
7
+ * @returns number number between 0 (inclusive) and 100 (exclusive)
8
+ */
9
+ export declare function getHashedPercentateForObjIds(objectIds: Array<any>, iterations?: number): number;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getHashedPercentateForObjIds = void 0;
7
+ const md5_1 = __importDefault(require("md5"));
8
+ const big_integer_1 = __importDefault(require("big-integer"));
9
+ const makeRepeated = (arr, repeats) => Array.from({ length: repeats }, () => arr).flat();
10
+ // https://stackoverflow.com/questions/12532871/how-to-convert-a-very-large-hex-number-to-decimal-in-javascript
11
+ function h2d(s) {
12
+ function add(x, y) {
13
+ var c = 0, r = [];
14
+ var x = x.split('').map(Number);
15
+ var y = y.split('').map(Number);
16
+ while (x.length || y.length) {
17
+ var s = (x.pop() || 0) + (y.pop() || 0) + c;
18
+ r.unshift(s < 10 ? s : s - 10);
19
+ c = s < 10 ? 0 : 1;
20
+ }
21
+ if (c)
22
+ r.unshift(c);
23
+ return r.join('');
24
+ }
25
+ var dec = '0';
26
+ s.split('').forEach(function (chr) {
27
+ var n = parseInt(chr, 16);
28
+ for (var t = 8; t; t >>= 1) {
29
+ dec = add(dec, dec);
30
+ if (n & t)
31
+ dec = add(dec, '1');
32
+ }
33
+ });
34
+ return dec;
35
+ }
36
+ /**
37
+ * Given a list of object ids, get a floating point number between 0 and 1 based on
38
+ * the hash of those ids. This should give the same value every time for any list of ids.
39
+ *
40
+ * @param {Array<any>} objectIds list of object ids to calculate the has for
41
+ * @param {} iterations=1 num times to include each id in the generated string to hash
42
+ * @returns number number between 0 (inclusive) and 100 (exclusive)
43
+ */
44
+ function getHashedPercentateForObjIds(objectIds, iterations = 1) {
45
+ let to_hash = makeRepeated(objectIds, iterations).join(',');
46
+ const hashedValue = (0, md5_1.default)(to_hash);
47
+ const hashedInt = (0, big_integer_1.default)(h2d(hashedValue));
48
+ const value = (hashedInt.mod(9999).toJSNumber() / 9998) * 100;
49
+ if (value === 100) {
50
+ return getHashedPercentateForObjIds(objectIds, iterations + 1);
51
+ }
52
+ return value;
53
+ }
54
+ exports.getHashedPercentateForObjIds = getHashedPercentateForObjIds;
@@ -0,0 +1 @@
1
+ export declare function getCastingFunction(input: any): CallableFunction;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCastingFunction = void 0;
4
+ function getCastingFunction(input) {
5
+ switch (typeof input) {
6
+ case 'boolean':
7
+ return (x) => !['False', 'false'].includes(x);
8
+ case 'number':
9
+ return (x) => parseFloat(x);
10
+ default:
11
+ return (x) => String(x);
12
+ }
13
+ }
14
+ exports.getCastingFunction = getCastingFunction;
@@ -0,0 +1 @@
1
+ export { Flagsmith } from './sdk';
package/build/index.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Flagsmith = void 0;
7
+ const sdk_1 = __importDefault(require("./sdk"));
8
+ var sdk_2 = require("./sdk");
9
+ Object.defineProperty(exports, "Flagsmith", { enumerable: true, get: function () { return sdk_2.Flagsmith; } });
10
+ // export default Flagsmith;
11
+ module.exports = sdk_1.default;
@@ -0,0 +1,28 @@
1
+ export declare class AnalyticsProcessor {
2
+ private analyticsEndpoint;
3
+ private environmentKey;
4
+ private lastFlushed;
5
+ analyticsData: {
6
+ [key: string]: any;
7
+ };
8
+ private timeout;
9
+ /**
10
+ * AnalyticsProcessor is used to track how often individual Flags are evaluated within
11
+ * the Flagsmith SDK. Docs: https://docs.flagsmith.com/advanced-use/flag-analytics.
12
+ *
13
+ * @param data.environmentKey environment key obtained from the Flagsmith UI
14
+ * @param data.baseApiUrl base api url to override when using self hosted version
15
+ * @param data.timeout used to tell requests to stop waiting for a response after a
16
+ given number of seconds
17
+ */
18
+ constructor(data: {
19
+ environmentKey: string;
20
+ baseApiUrl: string;
21
+ timeout?: number;
22
+ });
23
+ /**
24
+ * Sends all the collected data to the api asynchronously and resets the timer
25
+ */
26
+ flush(): Promise<void>;
27
+ trackFeature(featureId: number): void;
28
+ }
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AnalyticsProcessor = void 0;
7
+ const node_fetch_1 = __importDefault(require("node-fetch"));
8
+ const ANALYTICS_ENDPOINT = 'analytics/flags/';
9
+ // Used to control how often we send data(in seconds)
10
+ const ANALYTICS_TIMER = 10;
11
+ const delay = (ms) => new Promise(resolve => setTimeout(() => resolve(undefined), ms));
12
+ class AnalyticsProcessor {
13
+ analyticsEndpoint;
14
+ environmentKey;
15
+ lastFlushed;
16
+ analyticsData;
17
+ timeout = 3;
18
+ /**
19
+ * AnalyticsProcessor is used to track how often individual Flags are evaluated within
20
+ * the Flagsmith SDK. Docs: https://docs.flagsmith.com/advanced-use/flag-analytics.
21
+ *
22
+ * @param data.environmentKey environment key obtained from the Flagsmith UI
23
+ * @param data.baseApiUrl base api url to override when using self hosted version
24
+ * @param data.timeout used to tell requests to stop waiting for a response after a
25
+ given number of seconds
26
+ */
27
+ constructor(data) {
28
+ this.analyticsEndpoint = data.baseApiUrl + ANALYTICS_ENDPOINT;
29
+ this.environmentKey = data.environmentKey;
30
+ this.lastFlushed = Date.now();
31
+ this.analyticsData = {};
32
+ this.timeout = data.timeout || this.timeout;
33
+ }
34
+ /**
35
+ * Sends all the collected data to the api asynchronously and resets the timer
36
+ */
37
+ async flush() {
38
+ if (!Object.keys(this.analyticsData).length) {
39
+ return;
40
+ }
41
+ await (0, node_fetch_1.default)(this.analyticsEndpoint, {
42
+ method: 'POST',
43
+ body: JSON.stringify(this.analyticsData),
44
+ timeout: this.timeout,
45
+ headers: {
46
+ 'Content-Type': 'application/json',
47
+ 'X-Environment-Key': this.environmentKey
48
+ }
49
+ });
50
+ this.analyticsData = {};
51
+ this.lastFlushed = Date.now();
52
+ }
53
+ trackFeature(featureId) {
54
+ this.analyticsData[featureId] = (this.analyticsData[featureId] || 0) + 1;
55
+ if (Date.now() - this.lastFlushed > ANALYTICS_TIMER * 1000) {
56
+ this.flush();
57
+ }
58
+ }
59
+ }
60
+ exports.AnalyticsProcessor = AnalyticsProcessor;
@@ -0,0 +1,4 @@
1
+ export declare class FlagsmithClientError extends Error {
2
+ }
3
+ export declare class FlagsmithAPIError extends Error {
4
+ }
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FlagsmithAPIError = exports.FlagsmithClientError = void 0;
4
+ class FlagsmithClientError extends Error {
5
+ }
6
+ exports.FlagsmithClientError = FlagsmithClientError;
7
+ class FlagsmithAPIError extends Error {
8
+ }
9
+ exports.FlagsmithAPIError = FlagsmithAPIError;
@@ -0,0 +1,118 @@
1
+ import { EnvironmentModel } from '../flagsmith-engine/environments/models';
2
+ import { DefaultFlag, Flags } from './models';
3
+ import { EnvironmentDataPollingManager } from './polling_manager';
4
+ import { SegmentModel } from '../flagsmith-engine/segments/models';
5
+ export declare class Flagsmith {
6
+ environmentKey?: string;
7
+ apiUrl: string;
8
+ customHeaders?: {
9
+ [key: string]: any;
10
+ };
11
+ requestTimeoutSeconds?: number;
12
+ enableLocalEvaluation?: boolean;
13
+ environmentRefreshIntervalSeconds: number;
14
+ retries?: number;
15
+ enableAnalytics: boolean;
16
+ defaultFlagHandler?: (featureName: string) => DefaultFlag;
17
+ environmentFlagsUrl: string;
18
+ identitiesUrl: string;
19
+ environmentUrl: string;
20
+ environmentDataPollingManager?: EnvironmentDataPollingManager;
21
+ environment: EnvironmentModel;
22
+ private analyticsProcessor?;
23
+ /**
24
+ * A Flagsmith client.
25
+ *
26
+ * Provides an interface for interacting with the Flagsmith http API.
27
+ * Basic Usage::
28
+ *
29
+ * import flagsmith from Flagsmith
30
+ * const flagsmith = new Flagsmith({environmentKey: '<your API key>'});
31
+ * const environmentFlags = flagsmith.getEnvironmentFlags();
32
+ * const featureEnabled = environmentFlags.isFeatureEnabled('foo');
33
+ * const identityFlags = flagsmith.getIdentityFlags('identifier', {'foo': 'bar'});
34
+ * const featureEnabledForIdentity = identityFlags.isFeatureEnabled("foo")
35
+ *
36
+ * @param {string} data.environmentKey: The environment key obtained from Flagsmith interface
37
+ @param {string} data.apiUrl: Override the URL of the Flagsmith API to communicate with
38
+ @param data.customHeaders: Additional headers to add to requests made to the
39
+ Flagsmith API
40
+ @param {number} data.requestTimeoutSeconds: Number of seconds to wait for a request to
41
+ complete before terminating the request
42
+ @param {boolean} data.enableLocalEvaluation: Enables local evaluation of flags
43
+ @param {number} data.environmentRefreshIntervalSeconds: If using local evaluation,
44
+ specify the interval period between refreshes of local environment data
45
+ @param {number} data.retries: a urllib3.Retry object to use on all http requests to the
46
+ Flagsmith API
47
+ @param {boolean} data.enableAnalytics: if enabled, sends additional requests to the Flagsmith
48
+ API to power flag analytics charts
49
+ @param data.defaultFlagHandler: callable which will be used in the case where
50
+ flags cannot be retrieved from the API or a non existent feature is
51
+ requested
52
+ */
53
+ constructor(data: {
54
+ environmentKey: string;
55
+ apiUrl?: string;
56
+ customHeaders?: {
57
+ [key: string]: any;
58
+ };
59
+ requestTimeoutSeconds?: number;
60
+ enableLocalEvaluation?: boolean;
61
+ environmentRefreshIntervalSeconds?: number;
62
+ retries?: number;
63
+ enableAnalytics?: boolean;
64
+ defaultFlagHandler?: (featureName: string) => DefaultFlag;
65
+ });
66
+ /**
67
+ * Get all the default for flags for the current environment.
68
+ *
69
+ * @returns Flags object holding all the flags for the current environment.
70
+ */
71
+ getEnvironmentFlags(): Promise<Flags>;
72
+ /**
73
+ * Get all the flags for the current environment for a given identity. Will also
74
+ upsert all traits to the Flagsmith API for future evaluations. Providing a
75
+ trait with a value of None will remove the trait from the identity if it exists.
76
+ *
77
+ * @param {string} identifier a unique identifier for the identity in the current
78
+ environment, e.g. email address, username, uuid
79
+ * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
80
+ Flagsmith, e.g. {"num_orders": 10}
81
+ * @returns Flags object holding all the flags for the given identity.
82
+ */
83
+ getIdentityFlags(identifier: string, traits?: {
84
+ [key: string]: any;
85
+ }): Promise<Flags>;
86
+ /**
87
+ * Get the segments for the current environment for a given identity. Will also
88
+ upsert all traits to the Flagsmith API for future evaluations. Providing a
89
+ trait with a value of None will remove the trait from the identity if it exists.
90
+ *
91
+ * @param {string} identifier a unique identifier for the identity in the current
92
+ environment, e.g. email address, username, uuid
93
+ * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
94
+ Flagsmith, e.g. {"num_orders": 10}
95
+ * @returns Segments that the given identity belongs to.
96
+ */
97
+ getIdentitySegments(identifier: string, traits?: {
98
+ [key: string]: any;
99
+ }): Promise<SegmentModel[]>;
100
+ /**
101
+ * Updates the environment state for local flag evaluation.
102
+ * Sets a local promise to prevent race conditions in getIdentityFlags / getIdentitySegments.
103
+ * You only need to call this if you wish to bypass environmentRefreshIntervalSeconds.
104
+ */
105
+ updateEnvironment(): Promise<void>;
106
+ private getJSONResponse;
107
+ /**
108
+ * This promise ensures that the environment is retrieved before attempting to locally evaluate.
109
+ */
110
+ private environmentPromise;
111
+ private getEnvironmentFromApi;
112
+ private getEnvironmentFlagsFromDocument;
113
+ private getIdentityFlagsFromDocument;
114
+ private getEnvironmentFlagsFromApi;
115
+ private getIdentityFlagsFromApi;
116
+ private buildIdentityModel;
117
+ }
118
+ export default Flagsmith;