flagsmith-nodejs 2.0.0-beta.5 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/.github/workflows/pull_request.yaml +37 -29
  2. package/.tool-versions +1 -0
  3. package/README.md +7 -0
  4. package/example/package-lock.json +1 -996
  5. package/flagsmith-engine/features/models.ts +28 -6
  6. package/flagsmith-engine/features/util.ts +9 -0
  7. package/flagsmith-engine/identities/models.ts +1 -1
  8. package/flagsmith-engine/index.ts +7 -5
  9. package/flagsmith-engine/organisations/models.ts +1 -1
  10. package/flagsmith-engine/segments/models.ts +21 -4
  11. package/flagsmith-engine/segments/util.ts +8 -0
  12. package/flagsmith-engine/utils/collections.ts +1 -12
  13. package/flagsmith-engine/utils/hashing/index.ts +5 -2
  14. package/flagsmith-engine/utils/index.ts +6 -2
  15. package/package.json +4 -1
  16. package/sdk/analytics.ts +0 -2
  17. package/sdk/index.ts +84 -28
  18. package/sdk/polling_manager.ts +0 -1
  19. package/sdk/types.ts +8 -0
  20. package/sdk/utils.ts +4 -5
  21. package/tests/engine/unit/{egine.test.ts → engine.test.ts} +20 -0
  22. package/tests/engine/unit/features/models.test.ts +8 -4
  23. package/tests/engine/unit/identities/identities_builders.test.ts +13 -0
  24. package/tests/engine/unit/identities/identities_models.test.ts +3 -14
  25. package/tests/engine/unit/organization/models.test.ts +1 -1
  26. package/tests/engine/unit/segments/segments_model.test.ts +22 -1
  27. package/tests/engine/unit/utils.ts +1 -1
  28. package/tests/sdk/analytics.test.ts +11 -0
  29. package/tests/sdk/flagsmith-cache.test.ts +150 -0
  30. package/tests/sdk/flagsmith-environment-flags.test.ts +197 -0
  31. package/tests/sdk/flagsmith-identity-flags.test.ts +140 -0
  32. package/tests/sdk/flagsmith.test.ts +100 -85
  33. package/tests/sdk/polling.test.ts +25 -0
  34. package/tests/sdk/utils.ts +21 -2
  35. package/tsconfig.json +2 -1
  36. package/.idea/flagsmith-nodejs-client.iml +0 -12
  37. package/.idea/modules.xml +0 -8
  38. package/.idea/vcs.xml +0 -6
  39. package/build/flagsmith-engine/environments/integrations/models.d.ts +0 -4
  40. package/build/flagsmith-engine/environments/integrations/models.js +0 -8
  41. package/build/flagsmith-engine/environments/models.d.ts +0 -25
  42. package/build/flagsmith-engine/environments/models.js +0 -40
  43. package/build/flagsmith-engine/environments/util.d.ts +0 -3
  44. package/build/flagsmith-engine/environments/util.js +0 -19
  45. package/build/flagsmith-engine/features/constants.d.ts +0 -4
  46. package/build/flagsmith-engine/features/constants.js +0 -7
  47. package/build/flagsmith-engine/features/models.d.ts +0 -32
  48. package/build/flagsmith-engine/features/models.js +0 -85
  49. package/build/flagsmith-engine/features/util.d.ts +0 -3
  50. package/build/flagsmith-engine/features/util.js +0 -20
  51. package/build/flagsmith-engine/identities/models.d.ts +0 -15
  52. package/build/flagsmith-engine/identities/models.js +0 -47
  53. package/build/flagsmith-engine/identities/traits/models.d.ts +0 -5
  54. package/build/flagsmith-engine/identities/traits/models.js +0 -12
  55. package/build/flagsmith-engine/identities/util.d.ts +0 -4
  56. package/build/flagsmith-engine/identities/util.js +0 -22
  57. package/build/flagsmith-engine/index.d.ts +0 -8
  58. package/build/flagsmith-engine/index.js +0 -61
  59. package/build/flagsmith-engine/organisations/models.d.ts +0 -9
  60. package/build/flagsmith-engine/organisations/models.js +0 -21
  61. package/build/flagsmith-engine/organisations/util.d.ts +0 -2
  62. package/build/flagsmith-engine/organisations/util.js +0 -8
  63. package/build/flagsmith-engine/projects/models.d.ts +0 -10
  64. package/build/flagsmith-engine/projects/models.js +0 -17
  65. package/build/flagsmith-engine/projects/util.d.ts +0 -2
  66. package/build/flagsmith-engine/projects/util.js +0 -15
  67. package/build/flagsmith-engine/segments/constants.d.ts +0 -26
  68. package/build/flagsmith-engine/segments/constants.js +0 -31
  69. package/build/flagsmith-engine/segments/evaluators.d.ts +0 -6
  70. package/build/flagsmith-engine/segments/evaluators.js +0 -29
  71. package/build/flagsmith-engine/segments/models.d.ts +0 -31
  72. package/build/flagsmith-engine/segments/models.js +0 -83
  73. package/build/flagsmith-engine/segments/util.d.ts +0 -4
  74. package/build/flagsmith-engine/segments/util.js +0 -23
  75. package/build/flagsmith-engine/utils/collections.d.ts +0 -4
  76. package/build/flagsmith-engine/utils/collections.js +0 -16
  77. package/build/flagsmith-engine/utils/errors.d.ts +0 -2
  78. package/build/flagsmith-engine/utils/errors.js +0 -6
  79. package/build/flagsmith-engine/utils/hashing/index.d.ts +0 -9
  80. package/build/flagsmith-engine/utils/hashing/index.js +0 -54
  81. package/build/flagsmith-engine/utils/index.d.ts +0 -1
  82. package/build/flagsmith-engine/utils/index.js +0 -14
  83. package/build/index.d.ts +0 -1
  84. package/build/index.js +0 -11
  85. package/build/sdk/analytics.d.ts +0 -28
  86. package/build/sdk/analytics.js +0 -60
  87. package/build/sdk/errors.d.ts +0 -4
  88. package/build/sdk/errors.js +0 -9
  89. package/build/sdk/index.d.ts +0 -118
  90. package/build/sdk/index.js +0 -263
  91. package/build/sdk/models.d.ts +0 -55
  92. package/build/sdk/models.js +0 -101
  93. package/build/sdk/polling_manager.d.ts +0 -9
  94. package/build/sdk/polling_manager.js +0 -31
  95. package/build/sdk/utils.d.ts +0 -12
  96. package/build/sdk/utils.js +0 -45
  97. package/tests/engine/engine-tests/engine-test-data/data/environment_n9fbf9h3v4fFgH3U3ngWhb.json +0 -12393
  98. package/tests/engine/engine-tests/engine-test-data/readme.md +0 -30
@@ -1,28 +0,0 @@
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
- }
@@ -1,60 +0,0 @@
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;
@@ -1,4 +0,0 @@
1
- export declare class FlagsmithClientError extends Error {
2
- }
3
- export declare class FlagsmithAPIError extends Error {
4
- }
@@ -1,9 +0,0 @@
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;
@@ -1,118 +0,0 @@
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;
@@ -1,263 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Flagsmith = void 0;
4
- const flagsmith_engine_1 = require("../flagsmith-engine");
5
- const util_1 = require("../flagsmith-engine/environments/util");
6
- const models_1 = require("../flagsmith-engine/identities/models");
7
- const models_2 = require("../flagsmith-engine/identities/traits/models");
8
- const analytics_1 = require("./analytics");
9
- const errors_1 = require("./errors");
10
- const models_3 = require("./models");
11
- const polling_manager_1 = require("./polling_manager");
12
- const utils_1 = require("./utils");
13
- const evaluators_1 = require("../flagsmith-engine/segments/evaluators");
14
- const DEFAULT_API_URL = 'https://api.flagsmith.com/api/v1/';
15
- class Flagsmith {
16
- environmentKey;
17
- apiUrl = DEFAULT_API_URL;
18
- customHeaders;
19
- requestTimeoutSeconds;
20
- enableLocalEvaluation = false;
21
- environmentRefreshIntervalSeconds = 60;
22
- retries;
23
- enableAnalytics = false;
24
- defaultFlagHandler;
25
- environmentFlagsUrl;
26
- identitiesUrl;
27
- environmentUrl;
28
- environmentDataPollingManager;
29
- environment;
30
- analyticsProcessor;
31
- /**
32
- * A Flagsmith client.
33
- *
34
- * Provides an interface for interacting with the Flagsmith http API.
35
- * Basic Usage::
36
- *
37
- * import flagsmith from Flagsmith
38
- * const flagsmith = new Flagsmith({environmentKey: '<your API key>'});
39
- * const environmentFlags = flagsmith.getEnvironmentFlags();
40
- * const featureEnabled = environmentFlags.isFeatureEnabled('foo');
41
- * const identityFlags = flagsmith.getIdentityFlags('identifier', {'foo': 'bar'});
42
- * const featureEnabledForIdentity = identityFlags.isFeatureEnabled("foo")
43
- *
44
- * @param {string} data.environmentKey: The environment key obtained from Flagsmith interface
45
- @param {string} data.apiUrl: Override the URL of the Flagsmith API to communicate with
46
- @param data.customHeaders: Additional headers to add to requests made to the
47
- Flagsmith API
48
- @param {number} data.requestTimeoutSeconds: Number of seconds to wait for a request to
49
- complete before terminating the request
50
- @param {boolean} data.enableLocalEvaluation: Enables local evaluation of flags
51
- @param {number} data.environmentRefreshIntervalSeconds: If using local evaluation,
52
- specify the interval period between refreshes of local environment data
53
- @param {number} data.retries: a urllib3.Retry object to use on all http requests to the
54
- Flagsmith API
55
- @param {boolean} data.enableAnalytics: if enabled, sends additional requests to the Flagsmith
56
- API to power flag analytics charts
57
- @param data.defaultFlagHandler: callable which will be used in the case where
58
- flags cannot be retrieved from the API or a non existent feature is
59
- requested
60
- */
61
- constructor(data) {
62
- this.environmentKey = data.environmentKey;
63
- this.apiUrl = data.apiUrl || this.apiUrl;
64
- this.customHeaders = data.customHeaders;
65
- this.requestTimeoutSeconds = data.requestTimeoutSeconds;
66
- this.enableLocalEvaluation = data.enableLocalEvaluation;
67
- this.environmentRefreshIntervalSeconds =
68
- data.environmentRefreshIntervalSeconds || this.environmentRefreshIntervalSeconds;
69
- this.retries = data.retries;
70
- this.enableAnalytics = data.enableAnalytics || false;
71
- this.defaultFlagHandler = data.defaultFlagHandler;
72
- this.environmentFlagsUrl = `${this.apiUrl}flags/`;
73
- this.identitiesUrl = `${this.apiUrl}identities/`;
74
- this.environmentUrl = `${this.apiUrl}environment-document/`;
75
- if (this.enableLocalEvaluation) {
76
- if (!this.environmentKey.startsWith('ser.')) {
77
- console.error('In order to use local evaluation, please generate a server key in the environment settings page.');
78
- }
79
- this.environmentDataPollingManager = new polling_manager_1.EnvironmentDataPollingManager(this, this.environmentRefreshIntervalSeconds);
80
- this.environmentDataPollingManager.start();
81
- this.updateEnvironment();
82
- }
83
- this.analyticsProcessor = data.enableAnalytics
84
- ? new analytics_1.AnalyticsProcessor({
85
- environmentKey: this.environmentKey,
86
- baseApiUrl: this.apiUrl,
87
- timeout: this.requestTimeoutSeconds
88
- })
89
- : undefined;
90
- }
91
- /**
92
- * Get all the default for flags for the current environment.
93
- *
94
- * @returns Flags object holding all the flags for the current environment.
95
- */
96
- async getEnvironmentFlags() {
97
- if (this.environment) {
98
- return new Promise(resolve => resolve(this.getEnvironmentFlagsFromDocument()));
99
- }
100
- return this.getEnvironmentFlagsFromApi();
101
- }
102
- /**
103
- * Get all the flags for the current environment for a given identity. Will also
104
- upsert all traits to the Flagsmith API for future evaluations. Providing a
105
- trait with a value of None will remove the trait from the identity if it exists.
106
- *
107
- * @param {string} identifier a unique identifier for the identity in the current
108
- environment, e.g. email address, username, uuid
109
- * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
110
- Flagsmith, e.g. {"num_orders": 10}
111
- * @returns Flags object holding all the flags for the given identity.
112
- */
113
- getIdentityFlags(identifier, traits) {
114
- traits = traits || {};
115
- if (this.enableLocalEvaluation) {
116
- return new Promise(resolve => this.environmentPromise.then(() => {
117
- resolve(this.getIdentityFlagsFromDocument(identifier, traits || {}));
118
- }));
119
- }
120
- return this.getIdentityFlagsFromApi(identifier, traits);
121
- }
122
- /**
123
- * Get the segments for the current environment for a given identity. Will also
124
- upsert all traits to the Flagsmith API for future evaluations. Providing a
125
- trait with a value of None will remove the trait from the identity if it exists.
126
- *
127
- * @param {string} identifier a unique identifier for the identity in the current
128
- environment, e.g. email address, username, uuid
129
- * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
130
- Flagsmith, e.g. {"num_orders": 10}
131
- * @returns Segments that the given identity belongs to.
132
- */
133
- getIdentitySegments(identifier, traits) {
134
- traits = traits || {};
135
- if (this.enableLocalEvaluation) {
136
- return this.environmentPromise.then(() => {
137
- return new Promise(resolve => {
138
- const identityModel = this.buildIdentityModel(identifier, Object.keys(traits || {}).map(key => ({
139
- key,
140
- value: traits?.[key]
141
- })));
142
- const segments = (0, evaluators_1.getIdentitySegments)(this.environment, identityModel);
143
- return resolve(segments);
144
- });
145
- });
146
- }
147
- console.error('This function is only permitted with local evaluation.');
148
- return Promise.resolve([]);
149
- }
150
- /**
151
- * Updates the environment state for local flag evaluation.
152
- * Sets a local promise to prevent race conditions in getIdentityFlags / getIdentitySegments.
153
- * You only need to call this if you wish to bypass environmentRefreshIntervalSeconds.
154
- */
155
- async updateEnvironment() {
156
- const request = this.getEnvironmentFromApi();
157
- if (!this.environmentPromise) {
158
- this.environmentPromise = request.then(res => {
159
- this.environment = res;
160
- });
161
- await this.environmentPromise;
162
- }
163
- else {
164
- this.environment = await request;
165
- }
166
- }
167
- async getJSONResponse(url, method, body) {
168
- const headers = { 'Content-Type': 'application/json' };
169
- if (this.environmentKey) {
170
- headers['X-Environment-Key'] = this.environmentKey;
171
- }
172
- if (this.customHeaders) {
173
- for (const [k, v] of Object.entries(this.customHeaders)) {
174
- headers[k] = v;
175
- }
176
- }
177
- const data = await (0, utils_1.retryFetch)(url, {
178
- method: method,
179
- timeout: this.requestTimeoutSeconds || undefined,
180
- body: JSON.stringify(body),
181
- headers: headers
182
- }, this.retries, 1000, (this.requestTimeoutSeconds || 10) * 1000);
183
- if (data.status !== 200) {
184
- throw new errors_1.FlagsmithAPIError(`Invalid request made to Flagsmith API. Response status code: ${data.status}`);
185
- }
186
- return data.json();
187
- }
188
- /**
189
- * This promise ensures that the environment is retrieved before attempting to locally evaluate.
190
- */
191
- environmentPromise;
192
- async getEnvironmentFromApi() {
193
- const environment_data = await this.getJSONResponse(this.environmentUrl, 'GET');
194
- return (0, util_1.buildEnvironmentModel)(environment_data);
195
- }
196
- getEnvironmentFlagsFromDocument() {
197
- return models_3.Flags.fromFeatureStateModels({
198
- featureStates: (0, flagsmith_engine_1.getEnvironmentFeatureStates)(this.environment),
199
- analyticsProcessor: this.analyticsProcessor,
200
- defaultFlagHandler: this.defaultFlagHandler
201
- });
202
- }
203
- getIdentityFlagsFromDocument(identifier, traits) {
204
- const identityModel = this.buildIdentityModel(identifier, Object.keys(traits).map(key => ({
205
- key,
206
- value: traits[key]
207
- })));
208
- const featureStates = (0, flagsmith_engine_1.getIdentityFeatureStates)(this.environment, identityModel);
209
- return models_3.Flags.fromFeatureStateModels({
210
- featureStates: featureStates,
211
- analyticsProcessor: this.analyticsProcessor,
212
- defaultFlagHandler: this.defaultFlagHandler
213
- });
214
- }
215
- async getEnvironmentFlagsFromApi() {
216
- try {
217
- const apiFlags = await this.getJSONResponse(this.environmentFlagsUrl, 'GET');
218
- return models_3.Flags.fromAPIFlags({
219
- apiFlags: apiFlags,
220
- analyticsProcessor: this.analyticsProcessor,
221
- defaultFlagHandler: this.defaultFlagHandler
222
- });
223
- }
224
- catch (e) {
225
- if (this.defaultFlagHandler) {
226
- return new models_3.Flags({
227
- flags: {},
228
- defaultFlagHandler: this.defaultFlagHandler
229
- });
230
- }
231
- throw e;
232
- }
233
- }
234
- async getIdentityFlagsFromApi(identifier, traits) {
235
- try {
236
- const data = (0, utils_1.generateIdentitiesData)(identifier, traits);
237
- const jsonResponse = await this.getJSONResponse(this.identitiesUrl, 'POST', data);
238
- return models_3.Flags.fromAPIFlags({
239
- apiFlags: jsonResponse['flags'],
240
- analyticsProcessor: this.analyticsProcessor,
241
- defaultFlagHandler: this.defaultFlagHandler
242
- });
243
- }
244
- catch (e) {
245
- if (this.defaultFlagHandler) {
246
- return new models_3.Flags({
247
- flags: {},
248
- defaultFlagHandler: this.defaultFlagHandler
249
- });
250
- }
251
- throw e;
252
- }
253
- }
254
- buildIdentityModel(identifier, traits) {
255
- if (!this.environment) {
256
- throw new errors_1.FlagsmithClientError('Unable to build identity model when no local environment present.');
257
- }
258
- const traitModels = traits.map(trait => new models_2.TraitModel(trait.key, trait.value));
259
- return new models_1.IdentityModel('0', traitModels, [], this.environment.apiKey, identifier);
260
- }
261
- }
262
- exports.Flagsmith = Flagsmith;
263
- exports.default = Flagsmith;
@@ -1,55 +0,0 @@
1
- import { FeatureStateModel } from '../flagsmith-engine/features/models';
2
- import { AnalyticsProcessor } from './analytics';
3
- export declare class BaseFlag {
4
- enabled: boolean;
5
- value: string | number | boolean | undefined;
6
- isDefault: boolean;
7
- constructor(value: string | number | boolean | undefined, enabled: boolean, isDefault: boolean);
8
- }
9
- export declare class DefaultFlag extends BaseFlag {
10
- constructor(value: string | number | boolean | undefined, enabled: boolean);
11
- }
12
- export declare class Flag extends BaseFlag {
13
- featureId: number;
14
- featureName: string;
15
- constructor(params: {
16
- value: string | number | boolean | undefined;
17
- enabled: boolean;
18
- isDefault?: boolean;
19
- featureId: number;
20
- featureName: string;
21
- });
22
- static fromFeatureStateModel(fsm: FeatureStateModel, identityId: number | string | undefined): Flag;
23
- static fromAPIFlag(flagData: any): Flag;
24
- }
25
- export declare class Flags {
26
- flags: {
27
- [key: string]: Flag;
28
- };
29
- defaultFlagHandler?: (featureName: string) => DefaultFlag;
30
- analyticsProcessor?: AnalyticsProcessor;
31
- constructor(data: {
32
- flags: {
33
- [key: string]: Flag;
34
- };
35
- defaultFlagHandler?: (v: string) => DefaultFlag;
36
- analyticsProcessor?: AnalyticsProcessor;
37
- });
38
- static fromFeatureStateModels(data: {
39
- featureStates: FeatureStateModel[];
40
- analyticsProcessor?: AnalyticsProcessor;
41
- defaultFlagHandler?: (f: string) => DefaultFlag;
42
- identityID?: string | number;
43
- }): Flags;
44
- static fromAPIFlags(data: {
45
- apiFlags: {
46
- [key: string]: any;
47
- }[];
48
- analyticsProcessor?: AnalyticsProcessor;
49
- defaultFlagHandler?: (v: string) => DefaultFlag;
50
- }): Flags;
51
- allFlags(): Flag[];
52
- getFlag(featureName: string): BaseFlag;
53
- getFeatureValue(featureName: string): any;
54
- isFeatureEnabled(featureName: string): boolean;
55
- }
@@ -1,101 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Flags = exports.Flag = exports.DefaultFlag = exports.BaseFlag = void 0;
4
- class BaseFlag {
5
- enabled;
6
- value;
7
- isDefault;
8
- constructor(value, enabled, isDefault) {
9
- this.value = value;
10
- this.enabled = enabled;
11
- this.isDefault = isDefault;
12
- }
13
- }
14
- exports.BaseFlag = BaseFlag;
15
- class DefaultFlag extends BaseFlag {
16
- constructor(value, enabled) {
17
- super(value, enabled, true);
18
- }
19
- }
20
- exports.DefaultFlag = DefaultFlag;
21
- class Flag extends BaseFlag {
22
- featureId;
23
- featureName;
24
- constructor(params) {
25
- super(params.value, params.enabled, !!params.isDefault);
26
- this.featureId = params.featureId;
27
- this.featureName = params.featureName;
28
- }
29
- static fromFeatureStateModel(fsm, identityId) {
30
- return new Flag({
31
- value: fsm.getValue(identityId),
32
- enabled: fsm.enabled,
33
- featureId: fsm.feature.id,
34
- featureName: fsm.feature.name
35
- });
36
- }
37
- static fromAPIFlag(flagData) {
38
- return new Flag({
39
- enabled: flagData['enabled'],
40
- value: flagData['feature_state_value'] || flagData['value'],
41
- featureId: flagData['feature']['id'],
42
- featureName: flagData['feature']['name']
43
- });
44
- }
45
- }
46
- exports.Flag = Flag;
47
- class Flags {
48
- flags = {};
49
- defaultFlagHandler;
50
- analyticsProcessor;
51
- constructor(data) {
52
- this.flags = data.flags;
53
- this.defaultFlagHandler = data.defaultFlagHandler;
54
- this.analyticsProcessor = data.analyticsProcessor;
55
- }
56
- static fromFeatureStateModels(data) {
57
- const flags = {};
58
- for (const fs of data.featureStates) {
59
- flags[fs.feature.name] = Flag.fromFeatureStateModel(fs, data.identityID);
60
- }
61
- return new Flags({
62
- flags: flags,
63
- defaultFlagHandler: data.defaultFlagHandler,
64
- analyticsProcessor: data.analyticsProcessor
65
- });
66
- }
67
- static fromAPIFlags(data) {
68
- const flags = {};
69
- for (const flagData of data.apiFlags) {
70
- flags[flagData['feature']['name']] = Flag.fromAPIFlag(flagData);
71
- }
72
- return new Flags({
73
- flags: flags,
74
- defaultFlagHandler: data.defaultFlagHandler,
75
- analyticsProcessor: data.analyticsProcessor
76
- });
77
- }
78
- allFlags() {
79
- return Object.values(this.flags);
80
- }
81
- getFlag(featureName) {
82
- const flag = this.flags[featureName];
83
- if (!flag) {
84
- if (this.defaultFlagHandler) {
85
- return this.defaultFlagHandler(featureName);
86
- }
87
- return { enabled: false, isDefault: true, value: undefined };
88
- }
89
- if (this.analyticsProcessor && flag.featureId) {
90
- this.analyticsProcessor.trackFeature(flag.featureId);
91
- }
92
- return flag;
93
- }
94
- getFeatureValue(featureName) {
95
- return this.getFlag(featureName).value;
96
- }
97
- isFeatureEnabled(featureName) {
98
- return this.getFlag(featureName).enabled;
99
- }
100
- }
101
- exports.Flags = Flags;
@@ -1,9 +0,0 @@
1
- import Flagsmith from '.';
2
- export declare class EnvironmentDataPollingManager {
3
- private interval?;
4
- private main;
5
- private refreshIntervalSeconds;
6
- constructor(main: Flagsmith, refreshIntervalSeconds: number);
7
- start(): void;
8
- stop(): void;
9
- }
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EnvironmentDataPollingManager = void 0;
4
- class EnvironmentDataPollingManager {
5
- interval;
6
- main;
7
- refreshIntervalSeconds;
8
- constructor(main, refreshIntervalSeconds) {
9
- this.main = main;
10
- this.refreshIntervalSeconds = refreshIntervalSeconds;
11
- }
12
- start() {
13
- const updateEnvironment = () => {
14
- if (this.interval)
15
- clearInterval(this.interval);
16
- this.interval = setInterval(async () => {
17
- await this.main.updateEnvironment();
18
- }, this.refreshIntervalSeconds * 1000);
19
- };
20
- // todo: this call should be awaited for getIdentityFlags/getEnvironmentFlags when enableLocalEvaluation is true
21
- this.main.updateEnvironment();
22
- updateEnvironment();
23
- }
24
- stop() {
25
- if (!this.interval) {
26
- return;
27
- }
28
- clearInterval(this.interval);
29
- }
30
- }
31
- exports.EnvironmentDataPollingManager = EnvironmentDataPollingManager;