flagsmith-nodejs 3.3.3 → 4.0.0-beta.1

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 (190) hide show
  1. package/.github/workflows/publish.yml +2 -2
  2. package/.github/workflows/pull_request.yaml +3 -4
  3. package/build/{flagsmith-engine → cjs/flagsmith-engine}/environments/models.d.ts +3 -3
  4. package/build/{flagsmith-engine → cjs/flagsmith-engine}/environments/models.js +20 -13
  5. package/build/{flagsmith-engine → cjs/flagsmith-engine}/environments/util.d.ts +1 -1
  6. package/build/cjs/flagsmith-engine/environments/util.js +23 -0
  7. package/build/cjs/flagsmith-engine/features/models.js +118 -0
  8. package/build/{flagsmith-engine → cjs/flagsmith-engine}/features/util.d.ts +1 -1
  9. package/build/cjs/flagsmith-engine/features/util.js +27 -0
  10. package/build/{flagsmith-engine → cjs/flagsmith-engine}/identities/models.d.ts +2 -2
  11. package/build/cjs/flagsmith-engine/identities/models.js +48 -0
  12. package/build/{flagsmith-engine → cjs/flagsmith-engine}/identities/traits/models.js +5 -4
  13. package/build/{flagsmith-engine → cjs/flagsmith-engine}/identities/util.d.ts +2 -2
  14. package/build/cjs/flagsmith-engine/identities/util.js +22 -0
  15. package/build/cjs/flagsmith-engine/index.d.ts +14 -0
  16. package/build/cjs/flagsmith-engine/index.js +75 -0
  17. package/build/cjs/flagsmith-engine/organisations/models.js +21 -0
  18. package/build/{flagsmith-engine → cjs/flagsmith-engine}/organisations/util.d.ts +1 -1
  19. package/build/cjs/flagsmith-engine/organisations/util.js +8 -0
  20. package/build/{flagsmith-engine → cjs/flagsmith-engine}/projects/models.d.ts +2 -2
  21. package/build/{flagsmith-engine → cjs/flagsmith-engine}/projects/models.js +8 -5
  22. package/build/{flagsmith-engine → cjs/flagsmith-engine}/projects/util.d.ts +1 -1
  23. package/build/cjs/flagsmith-engine/projects/util.js +15 -0
  24. package/build/{flagsmith-engine → cjs/flagsmith-engine}/segments/evaluators.d.ts +4 -4
  25. package/build/cjs/flagsmith-engine/segments/evaluators.js +37 -0
  26. package/build/{flagsmith-engine → cjs/flagsmith-engine}/segments/models.d.ts +1 -1
  27. package/build/cjs/flagsmith-engine/segments/models.js +114 -0
  28. package/build/{flagsmith-engine → cjs/flagsmith-engine}/segments/util.d.ts +1 -1
  29. package/build/{flagsmith-engine → cjs/flagsmith-engine}/segments/util.js +9 -11
  30. package/build/{flagsmith-engine → cjs/flagsmith-engine}/utils/collections.d.ts +1 -1
  31. package/build/cjs/flagsmith-engine/utils/collections.js +6 -0
  32. package/build/cjs/flagsmith-engine/utils/errors.js +6 -0
  33. package/build/{flagsmith-engine → cjs/flagsmith-engine}/utils/hashing/index.js +8 -11
  34. package/build/{flagsmith-engine → cjs/flagsmith-engine}/utils/index.js +5 -5
  35. package/build/{index.d.ts → cjs/index.d.ts} +3 -3
  36. package/build/{index.js → cjs/index.js} +17 -17
  37. package/build/cjs/package.json +1 -0
  38. package/build/{sdk → cjs/sdk}/analytics.d.ts +3 -0
  39. package/build/cjs/sdk/analytics.js +73 -0
  40. package/build/cjs/sdk/errors.js +9 -0
  41. package/build/{sdk → cjs/sdk}/index.d.ts +19 -18
  42. package/build/cjs/sdk/index.js +400 -0
  43. package/build/{sdk → cjs/sdk}/models.d.ts +2 -2
  44. package/build/cjs/sdk/models.js +101 -0
  45. package/build/{sdk → cjs/sdk}/offline_handlers.d.ts +1 -1
  46. package/build/cjs/sdk/offline_handlers.js +46 -0
  47. package/build/{sdk → cjs/sdk}/polling_manager.d.ts +1 -1
  48. package/build/cjs/sdk/polling_manager.js +29 -0
  49. package/build/{sdk → cjs/sdk}/types.d.ts +15 -7
  50. package/build/cjs/sdk/utils.d.ts +36 -0
  51. package/build/cjs/sdk/utils.js +63 -0
  52. package/build/esm/flagsmith-engine/environments/models.d.ts +22 -0
  53. package/build/esm/flagsmith-engine/environments/models.js +32 -0
  54. package/build/esm/flagsmith-engine/environments/util.d.ts +3 -0
  55. package/build/esm/flagsmith-engine/environments/util.js +18 -0
  56. package/build/esm/flagsmith-engine/features/constants.d.ts +4 -0
  57. package/build/esm/flagsmith-engine/features/constants.js +4 -0
  58. package/build/esm/flagsmith-engine/features/models.d.ts +37 -0
  59. package/build/esm/flagsmith-engine/features/models.js +110 -0
  60. package/build/esm/flagsmith-engine/features/util.d.ts +4 -0
  61. package/build/esm/flagsmith-engine/features/util.js +21 -0
  62. package/build/esm/flagsmith-engine/identities/models.d.ts +15 -0
  63. package/build/esm/flagsmith-engine/identities/models.js +44 -0
  64. package/build/esm/flagsmith-engine/identities/traits/models.d.ts +5 -0
  65. package/build/esm/flagsmith-engine/identities/traits/models.js +8 -0
  66. package/build/esm/flagsmith-engine/identities/util.d.ts +4 -0
  67. package/build/esm/flagsmith-engine/identities/util.js +17 -0
  68. package/build/esm/flagsmith-engine/index.d.ts +14 -0
  69. package/build/esm/flagsmith-engine/index.js +62 -0
  70. package/build/esm/flagsmith-engine/organisations/models.d.ts +9 -0
  71. package/build/esm/flagsmith-engine/organisations/models.js +17 -0
  72. package/build/esm/flagsmith-engine/organisations/util.d.ts +2 -0
  73. package/build/esm/flagsmith-engine/organisations/util.js +4 -0
  74. package/build/esm/flagsmith-engine/projects/models.d.ts +10 -0
  75. package/build/esm/flagsmith-engine/projects/models.js +13 -0
  76. package/build/esm/flagsmith-engine/projects/util.d.ts +2 -0
  77. package/build/esm/flagsmith-engine/projects/util.js +11 -0
  78. package/build/esm/flagsmith-engine/segments/constants.d.ts +34 -0
  79. package/build/esm/flagsmith-engine/segments/constants.js +36 -0
  80. package/build/esm/flagsmith-engine/segments/evaluators.d.ts +7 -0
  81. package/build/esm/flagsmith-engine/segments/evaluators.js +31 -0
  82. package/build/esm/flagsmith-engine/segments/models.d.ts +37 -0
  83. package/build/esm/flagsmith-engine/segments/models.js +102 -0
  84. package/build/esm/flagsmith-engine/segments/util.d.ts +6 -0
  85. package/build/esm/flagsmith-engine/segments/util.js +23 -0
  86. package/build/esm/flagsmith-engine/utils/collections.d.ts +3 -0
  87. package/build/esm/flagsmith-engine/utils/collections.js +2 -0
  88. package/build/esm/flagsmith-engine/utils/errors.d.ts +2 -0
  89. package/build/esm/flagsmith-engine/utils/errors.js +2 -0
  90. package/build/esm/flagsmith-engine/utils/hashing/index.d.ts +9 -0
  91. package/build/esm/flagsmith-engine/utils/hashing/index.js +50 -0
  92. package/build/esm/flagsmith-engine/utils/index.d.ts +1 -0
  93. package/build/esm/flagsmith-engine/utils/index.js +13 -0
  94. package/build/esm/index.d.ts +3 -0
  95. package/build/esm/index.js +4 -0
  96. package/build/esm/sdk/analytics.d.ts +35 -0
  97. package/build/esm/sdk/analytics.js +69 -0
  98. package/build/esm/sdk/errors.d.ts +4 -0
  99. package/build/esm/sdk/errors.js +4 -0
  100. package/build/esm/sdk/index.d.ts +131 -0
  101. package/build/esm/sdk/index.js +390 -0
  102. package/build/esm/sdk/models.d.ts +55 -0
  103. package/build/esm/sdk/models.js +94 -0
  104. package/build/esm/sdk/offline_handlers.d.ts +9 -0
  105. package/build/esm/sdk/offline_handlers.js +18 -0
  106. package/build/esm/sdk/polling_manager.d.ts +9 -0
  107. package/build/esm/sdk/polling_manager.js +25 -0
  108. package/build/esm/sdk/types.d.ts +38 -0
  109. package/build/esm/sdk/types.js +1 -0
  110. package/build/esm/sdk/utils.d.ts +36 -0
  111. package/build/esm/sdk/utils.js +56 -0
  112. package/flagsmith-engine/environments/models.ts +3 -3
  113. package/flagsmith-engine/environments/util.ts +4 -4
  114. package/flagsmith-engine/features/models.ts +1 -1
  115. package/flagsmith-engine/features/util.ts +1 -1
  116. package/flagsmith-engine/identities/models.ts +3 -4
  117. package/flagsmith-engine/identities/traits/models.ts +0 -1
  118. package/flagsmith-engine/identities/util.ts +4 -4
  119. package/flagsmith-engine/index.ts +13 -13
  120. package/flagsmith-engine/organisations/util.ts +1 -1
  121. package/flagsmith-engine/projects/models.ts +2 -2
  122. package/flagsmith-engine/projects/util.ts +4 -4
  123. package/flagsmith-engine/segments/evaluators.ts +6 -6
  124. package/flagsmith-engine/segments/models.ts +4 -4
  125. package/flagsmith-engine/segments/util.ts +3 -3
  126. package/flagsmith-engine/utils/collections.ts +1 -1
  127. package/flagsmith-engine/utils/index.ts +1 -1
  128. package/index.ts +4 -4
  129. package/package.json +21 -9
  130. package/sdk/analytics.ts +7 -5
  131. package/sdk/index.ts +55 -46
  132. package/sdk/models.ts +2 -3
  133. package/sdk/offline_handlers.ts +2 -2
  134. package/sdk/polling_manager.ts +2 -3
  135. package/sdk/types.ts +35 -24
  136. package/sdk/utils.ts +49 -37
  137. package/tests/engine/e2e/engine.test.ts +5 -5
  138. package/tests/engine/unit/engine.test.ts +5 -5
  139. package/tests/engine/unit/segments/segment_evaluators.test.ts +9 -9
  140. package/tests/engine/unit/utils/utils.test.ts +1 -1
  141. package/tests/sdk/analytics.test.ts +8 -13
  142. package/tests/sdk/data/identity-with-transient-traits.json +41 -0
  143. package/tests/sdk/data/transient-identity.json +29 -0
  144. package/tests/sdk/flagsmith-cache.test.ts +16 -32
  145. package/tests/sdk/flagsmith-environment-flags.test.ts +21 -36
  146. package/tests/sdk/flagsmith-identity-flags.test.ts +83 -32
  147. package/tests/sdk/flagsmith.test.ts +67 -99
  148. package/tests/sdk/offline-handlers.test.ts +4 -5
  149. package/tests/sdk/polling.test.ts +6 -8
  150. package/tests/sdk/utils.ts +19 -15
  151. package/tsconfig.cjs.json +7 -0
  152. package/tsconfig.esm.json +7 -0
  153. package/tsconfig.json +7 -3
  154. package/vitest.config.ts +17 -0
  155. package/build/flagsmith-engine/environments/util.js +0 -27
  156. package/build/flagsmith-engine/features/models.js +0 -132
  157. package/build/flagsmith-engine/features/util.js +0 -27
  158. package/build/flagsmith-engine/identities/models.js +0 -113
  159. package/build/flagsmith-engine/identities/util.js +0 -46
  160. package/build/flagsmith-engine/index.d.ts +0 -14
  161. package/build/flagsmith-engine/index.js +0 -127
  162. package/build/flagsmith-engine/organisations/models.js +0 -21
  163. package/build/flagsmith-engine/organisations/util.js +0 -8
  164. package/build/flagsmith-engine/projects/util.js +0 -15
  165. package/build/flagsmith-engine/segments/evaluators.js +0 -45
  166. package/build/flagsmith-engine/segments/models.js +0 -147
  167. package/build/flagsmith-engine/utils/collections.js +0 -26
  168. package/build/flagsmith-engine/utils/errors.js +0 -26
  169. package/build/sdk/analytics.js +0 -120
  170. package/build/sdk/errors.js +0 -34
  171. package/build/sdk/index.js +0 -594
  172. package/build/sdk/models.js +0 -149
  173. package/build/sdk/offline_handlers.js +0 -66
  174. package/build/sdk/polling_manager.js +0 -72
  175. package/build/sdk/utils.d.ts +0 -12
  176. package/build/sdk/utils.js +0 -107
  177. package/jest.config.js +0 -5
  178. package/tests/index.js +0 -0
  179. /package/build/{flagsmith-engine → cjs/flagsmith-engine}/features/constants.d.ts +0 -0
  180. /package/build/{flagsmith-engine → cjs/flagsmith-engine}/features/constants.js +0 -0
  181. /package/build/{flagsmith-engine → cjs/flagsmith-engine}/features/models.d.ts +0 -0
  182. /package/build/{flagsmith-engine → cjs/flagsmith-engine}/identities/traits/models.d.ts +0 -0
  183. /package/build/{flagsmith-engine → cjs/flagsmith-engine}/organisations/models.d.ts +0 -0
  184. /package/build/{flagsmith-engine → cjs/flagsmith-engine}/segments/constants.d.ts +0 -0
  185. /package/build/{flagsmith-engine → cjs/flagsmith-engine}/segments/constants.js +0 -0
  186. /package/build/{flagsmith-engine → cjs/flagsmith-engine}/utils/errors.d.ts +0 -0
  187. /package/build/{flagsmith-engine → cjs/flagsmith-engine}/utils/hashing/index.d.ts +0 -0
  188. /package/build/{flagsmith-engine → cjs/flagsmith-engine}/utils/index.d.ts +0 -0
  189. /package/build/{sdk → cjs/sdk}/errors.d.ts +0 -0
  190. /package/build/{sdk → cjs/sdk}/types.js +0 -0
@@ -1,594 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (_) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __values = (this && this.__values) || function(o) {
39
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
40
- if (m) return m.call(o);
41
- if (o && typeof o.length === "number") return {
42
- next: function () {
43
- if (o && i >= o.length) o = void 0;
44
- return { value: o && o[i++], done: !o };
45
- }
46
- };
47
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
48
- };
49
- var __read = (this && this.__read) || function (o, n) {
50
- var m = typeof Symbol === "function" && o[Symbol.iterator];
51
- if (!m) return o;
52
- var i = m.call(o), r, ar = [], e;
53
- try {
54
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
- }
56
- catch (error) { e = { error: error }; }
57
- finally {
58
- try {
59
- if (r && !r.done && (m = i["return"])) m.call(i);
60
- }
61
- finally { if (e) throw e.error; }
62
- }
63
- return ar;
64
- };
65
- var __importDefault = (this && this.__importDefault) || function (mod) {
66
- return (mod && mod.__esModule) ? mod : { "default": mod };
67
- };
68
- Object.defineProperty(exports, "__esModule", { value: true });
69
- exports.Flagsmith = exports.EnvironmentDataPollingManager = exports.Flags = exports.DefaultFlag = exports.FlagsmithClientError = exports.FlagsmithAPIError = exports.AnalyticsProcessor = void 0;
70
- var flagsmith_engine_1 = require("../flagsmith-engine");
71
- var util_1 = require("../flagsmith-engine/environments/util");
72
- var models_1 = require("../flagsmith-engine/identities/models");
73
- var models_2 = require("../flagsmith-engine/identities/traits/models");
74
- var analytics_1 = require("./analytics");
75
- var errors_1 = require("./errors");
76
- var models_3 = require("./models");
77
- var polling_manager_1 = require("./polling_manager");
78
- var utils_1 = require("./utils");
79
- var evaluators_1 = require("../flagsmith-engine/segments/evaluators");
80
- var pino_1 = __importDefault(require("pino"));
81
- var analytics_2 = require("./analytics");
82
- Object.defineProperty(exports, "AnalyticsProcessor", { enumerable: true, get: function () { return analytics_2.AnalyticsProcessor; } });
83
- var errors_2 = require("./errors");
84
- Object.defineProperty(exports, "FlagsmithAPIError", { enumerable: true, get: function () { return errors_2.FlagsmithAPIError; } });
85
- Object.defineProperty(exports, "FlagsmithClientError", { enumerable: true, get: function () { return errors_2.FlagsmithClientError; } });
86
- var models_4 = require("./models");
87
- Object.defineProperty(exports, "DefaultFlag", { enumerable: true, get: function () { return models_4.DefaultFlag; } });
88
- Object.defineProperty(exports, "Flags", { enumerable: true, get: function () { return models_4.Flags; } });
89
- var polling_manager_2 = require("./polling_manager");
90
- Object.defineProperty(exports, "EnvironmentDataPollingManager", { enumerable: true, get: function () { return polling_manager_2.EnvironmentDataPollingManager; } });
91
- var DEFAULT_API_URL = 'https://edge.api.flagsmith.com/api/v1/';
92
- var DEFAULT_REQUEST_TIMEOUT_SECONDS = 10;
93
- var Flagsmith = /** @class */ (function () {
94
- /**
95
- * A Flagsmith client.
96
- *
97
- * Provides an interface for interacting with the Flagsmith http API.
98
- * Basic Usage::
99
- *
100
- * import flagsmith from Flagsmith
101
- * const flagsmith = new Flagsmith({environmentKey: '<your API key>'});
102
- * const environmentFlags = flagsmith.getEnvironmentFlags();
103
- * const featureEnabled = environmentFlags.isFeatureEnabled('foo');
104
- * const identityFlags = flagsmith.getIdentityFlags('identifier', {'foo': 'bar'});
105
- * const featureEnabledForIdentity = identityFlags.isFeatureEnabled("foo")
106
- *
107
- * @param {string} data.environmentKey: The environment key obtained from Flagsmith interface
108
- * Required unless offlineMode is True.
109
- @param {string} data.apiUrl: Override the URL of the Flagsmith API to communicate with
110
- @param data.customHeaders: Additional headers to add to requests made to the
111
- Flagsmith API
112
- @param {number} data.requestTimeoutSeconds: Number of seconds to wait for a request to
113
- complete before terminating the request
114
- @param {boolean} data.enableLocalEvaluation: Enables local evaluation of flags
115
- @param {number} data.environmentRefreshIntervalSeconds: If using local evaluation,
116
- specify the interval period between refreshes of local environment data
117
- @param {number} data.retries: a urllib3.Retry object to use on all http requests to the
118
- Flagsmith API
119
- @param {boolean} data.enableAnalytics: if enabled, sends additional requests to the Flagsmith
120
- API to power flag analytics charts
121
- @param data.defaultFlagHandler: callable which will be used in the case where
122
- flags cannot be retrieved from the API or a non-existent feature is
123
- requested
124
- @param data.logger: an instance of the pino Logger class to use for logging
125
- @param {boolean} data.offlineMode: sets the client into offline mode. Relies on offlineHandler for
126
- evaluating flags.
127
- @param {BaseOfflineHandler} data.offlineHandler: provide a handler for offline logic. Used to get environment
128
- document from another source when in offlineMode. Works in place of
129
- defaultFlagHandler if offlineMode is not set and using remote evaluation.
130
- */
131
- function Flagsmith(data) {
132
- // if (!data.offlineMode && !data.environmentKey) {
133
- // throw new Error('ValueError: environmentKey is required.');
134
- // }
135
- if (data === void 0) { data = {}; }
136
- var _a;
137
- this.environmentKey = undefined;
138
- this.apiUrl = undefined;
139
- this.enableLocalEvaluation = false;
140
- this.environmentRefreshIntervalSeconds = 60;
141
- this.enableAnalytics = false;
142
- this.offlineMode = false;
143
- this.offlineHandler = undefined;
144
- this.agent = data.agent;
145
- this.environmentKey = data.environmentKey;
146
- this.apiUrl = data.apiUrl || this.apiUrl;
147
- this.customHeaders = data.customHeaders;
148
- this.requestTimeoutMs =
149
- 1000 * ((_a = data.requestTimeoutSeconds) !== null && _a !== void 0 ? _a : DEFAULT_REQUEST_TIMEOUT_SECONDS);
150
- this.enableLocalEvaluation = data.enableLocalEvaluation;
151
- this.environmentRefreshIntervalSeconds =
152
- data.environmentRefreshIntervalSeconds || this.environmentRefreshIntervalSeconds;
153
- this.retries = data.retries;
154
- this.enableAnalytics = data.enableAnalytics || false;
155
- this.defaultFlagHandler = data.defaultFlagHandler;
156
- this.onEnvironmentChange = data.onEnvironmentChange;
157
- this.logger = data.logger || (0, pino_1.default)();
158
- this.offlineMode = data.offlineMode || false;
159
- this.offlineHandler = data.offlineHandler;
160
- // argument validation
161
- if (this.offlineMode && !this.offlineHandler) {
162
- throw new Error('ValueError: offlineHandler must be provided to use offline mode.');
163
- }
164
- else if (this.defaultFlagHandler && this.offlineHandler) {
165
- throw new Error('ValueError: Cannot use both defaultFlagHandler and offlineHandler.');
166
- }
167
- if (this.offlineHandler) {
168
- this.environment = this.offlineHandler.getEnvironment();
169
- }
170
- if (!!data.cache) {
171
- var missingMethods = ['has', 'get', 'set'].filter(function (method) { return data.cache && !data.cache[method]; });
172
- if (missingMethods.length > 0) {
173
- throw new Error("Please implement the following methods in your cache: ".concat(missingMethods.join(', ')));
174
- }
175
- this.cache = data.cache;
176
- }
177
- if (!this.offlineMode) {
178
- if (!this.environmentKey) {
179
- throw new Error('ValueError: environmentKey is required.');
180
- }
181
- var apiUrl = data.apiUrl || DEFAULT_API_URL;
182
- this.apiUrl = apiUrl.endsWith('/') ? apiUrl : "".concat(apiUrl, "/");
183
- this.environmentFlagsUrl = "".concat(this.apiUrl, "flags/");
184
- this.identitiesUrl = "".concat(this.apiUrl, "identities/");
185
- this.environmentUrl = "".concat(this.apiUrl, "environment-document/");
186
- if (this.enableLocalEvaluation) {
187
- if (!this.environmentKey.startsWith('ser.')) {
188
- console.error('In order to use local evaluation, please generate a server key in the environment settings page.');
189
- }
190
- this.environmentDataPollingManager = new polling_manager_1.EnvironmentDataPollingManager(this, this.environmentRefreshIntervalSeconds);
191
- this.environmentDataPollingManager.start();
192
- this.updateEnvironment();
193
- }
194
- this.analyticsProcessor = data.enableAnalytics
195
- ? new analytics_1.AnalyticsProcessor({
196
- environmentKey: this.environmentKey,
197
- baseApiUrl: this.apiUrl,
198
- requestTimeoutMs: this.requestTimeoutMs,
199
- logger: this.logger
200
- })
201
- : undefined;
202
- }
203
- }
204
- /**
205
- * Get all the default for flags for the current environment.
206
- *
207
- * @returns Flags object holding all the flags for the current environment.
208
- */
209
- Flagsmith.prototype.getEnvironmentFlags = function () {
210
- return __awaiter(this, void 0, void 0, function () {
211
- var cachedItem, _a;
212
- var _this = this;
213
- return __generator(this, function (_b) {
214
- switch (_b.label) {
215
- case 0:
216
- _a = !!this.cache;
217
- if (!_a) return [3 /*break*/, 2];
218
- return [4 /*yield*/, this.cache.get("flags")];
219
- case 1:
220
- _a = (_b.sent());
221
- _b.label = 2;
222
- case 2:
223
- cachedItem = _a;
224
- if (!!cachedItem) {
225
- return [2 /*return*/, cachedItem];
226
- }
227
- if (this.enableLocalEvaluation && !this.offlineMode) {
228
- return [2 /*return*/, new Promise(function (resolve, reject) {
229
- return _this.environmentPromise.then(function () {
230
- resolve(_this.getEnvironmentFlagsFromDocument());
231
- }).catch(function (e) { return reject(e); });
232
- })];
233
- }
234
- if (this.environment) {
235
- return [2 /*return*/, this.getEnvironmentFlagsFromDocument()];
236
- }
237
- return [2 /*return*/, this.getEnvironmentFlagsFromApi()];
238
- }
239
- });
240
- });
241
- };
242
- /**
243
- * Get all the flags for the current environment for a given identity. Will also
244
- upsert all traits to the Flagsmith API for future evaluations. Providing a
245
- trait with a value of None will remove the trait from the identity if it exists.
246
- *
247
- * @param {string} identifier a unique identifier for the identity in the current
248
- environment, e.g. email address, username, uuid
249
- * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
250
- Flagsmith, e.g. {"num_orders": 10}
251
- * @returns Flags object holding all the flags for the given identity.
252
- */
253
- Flagsmith.prototype.getIdentityFlags = function (identifier, traits) {
254
- return __awaiter(this, void 0, void 0, function () {
255
- var cachedItem, _a;
256
- var _this = this;
257
- return __generator(this, function (_b) {
258
- switch (_b.label) {
259
- case 0:
260
- if (!identifier) {
261
- throw new Error('`identifier` argument is missing or invalid.');
262
- }
263
- _a = !!this.cache;
264
- if (!_a) return [3 /*break*/, 2];
265
- return [4 /*yield*/, this.cache.get("flags-".concat(identifier))];
266
- case 1:
267
- _a = (_b.sent());
268
- _b.label = 2;
269
- case 2:
270
- cachedItem = _a;
271
- if (!!cachedItem) {
272
- return [2 /*return*/, cachedItem];
273
- }
274
- traits = traits || {};
275
- if (this.enableLocalEvaluation) {
276
- return [2 /*return*/, new Promise(function (resolve, reject) {
277
- return _this.environmentPromise.then(function () {
278
- resolve(_this.getIdentityFlagsFromDocument(identifier, traits || {}));
279
- }).catch(function (e) { return reject(e); });
280
- })];
281
- }
282
- if (this.offlineMode) {
283
- return [2 /*return*/, this.getIdentityFlagsFromDocument(identifier, traits || {})];
284
- }
285
- return [2 /*return*/, this.getIdentityFlagsFromApi(identifier, traits)];
286
- }
287
- });
288
- });
289
- };
290
- /**
291
- * Get the segments for the current environment for a given identity. Will also
292
- upsert all traits to the Flagsmith API for future evaluations. Providing a
293
- trait with a value of None will remove the trait from the identity if it exists.
294
- *
295
- * @param {string} identifier a unique identifier for the identity in the current
296
- environment, e.g. email address, username, uuid
297
- * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
298
- Flagsmith, e.g. {"num_orders": 10}
299
- * @returns Segments that the given identity belongs to.
300
- */
301
- Flagsmith.prototype.getIdentitySegments = function (identifier, traits) {
302
- var _this = this;
303
- if (!identifier) {
304
- throw new Error('`identifier` argument is missing or invalid.');
305
- }
306
- traits = traits || {};
307
- if (this.enableLocalEvaluation) {
308
- return new Promise(function (resolve, reject) {
309
- return _this.environmentPromise.then(function () {
310
- var identityModel = _this.getIdentityModel(identifier, Object.keys(traits || {}).map(function (key) { return ({
311
- key: key,
312
- value: traits === null || traits === void 0 ? void 0 : traits[key]
313
- }); }));
314
- var segments = (0, evaluators_1.getIdentitySegments)(_this.environment, identityModel);
315
- return resolve(segments);
316
- }).catch(function (e) { return reject(e); });
317
- });
318
- }
319
- console.error('This function is only permitted with local evaluation.');
320
- return Promise.resolve([]);
321
- };
322
- /**
323
- * Updates the environment state for local flag evaluation.
324
- * Sets a local promise to prevent race conditions in getIdentityFlags / getIdentitySegments.
325
- * You only need to call this if you wish to bypass environmentRefreshIntervalSeconds.
326
- */
327
- Flagsmith.prototype.updateEnvironment = function () {
328
- var _a;
329
- return __awaiter(this, void 0, void 0, function () {
330
- var request, _b, e_1;
331
- var _this = this;
332
- return __generator(this, function (_c) {
333
- switch (_c.label) {
334
- case 0:
335
- _c.trys.push([0, 5, , 6]);
336
- request = this.getEnvironmentFromApi();
337
- if (!!this.environmentPromise) return [3 /*break*/, 2];
338
- this.environmentPromise = request.then(function (res) {
339
- _this.environment = res;
340
- });
341
- return [4 /*yield*/, this.environmentPromise];
342
- case 1:
343
- _c.sent();
344
- return [3 /*break*/, 4];
345
- case 2:
346
- _b = this;
347
- return [4 /*yield*/, request];
348
- case 3:
349
- _b.environment = _c.sent();
350
- _c.label = 4;
351
- case 4:
352
- if ((_a = this.environment.identityOverrides) === null || _a === void 0 ? void 0 : _a.length) {
353
- this.identitiesWithOverridesByIdentifier = new Map(this.environment.identityOverrides.map(function (identity) { return [identity.identifier, identity]; }));
354
- }
355
- if (this.onEnvironmentChange) {
356
- this.onEnvironmentChange(null, this.environment);
357
- }
358
- return [3 /*break*/, 6];
359
- case 5:
360
- e_1 = _c.sent();
361
- if (this.onEnvironmentChange) {
362
- this.onEnvironmentChange(e_1, this.environment);
363
- }
364
- return [3 /*break*/, 6];
365
- case 6: return [2 /*return*/];
366
- }
367
- });
368
- });
369
- };
370
- Flagsmith.prototype.close = function () {
371
- var _a;
372
- return __awaiter(this, void 0, void 0, function () {
373
- return __generator(this, function (_b) {
374
- (_a = this.environmentDataPollingManager) === null || _a === void 0 ? void 0 : _a.stop();
375
- return [2 /*return*/];
376
- });
377
- });
378
- };
379
- Flagsmith.prototype.getJSONResponse = function (url, method, body) {
380
- return __awaiter(this, void 0, void 0, function () {
381
- var headers, _a, _b, _c, k, v, data;
382
- var e_2, _d;
383
- return __generator(this, function (_e) {
384
- switch (_e.label) {
385
- case 0:
386
- headers = { 'Content-Type': 'application/json' };
387
- if (this.environmentKey) {
388
- headers['X-Environment-Key'] = this.environmentKey;
389
- }
390
- if (this.customHeaders) {
391
- try {
392
- for (_a = __values(Object.entries(this.customHeaders)), _b = _a.next(); !_b.done; _b = _a.next()) {
393
- _c = __read(_b.value, 2), k = _c[0], v = _c[1];
394
- headers[k] = v;
395
- }
396
- }
397
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
398
- finally {
399
- try {
400
- if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
401
- }
402
- finally { if (e_2) throw e_2.error; }
403
- }
404
- }
405
- return [4 /*yield*/, (0, utils_1.retryFetch)(url, {
406
- agent: this.agent,
407
- method: method,
408
- body: JSON.stringify(body),
409
- headers: headers
410
- }, this.retries, this.requestTimeoutMs || undefined)];
411
- case 1:
412
- data = _e.sent();
413
- if (data.status !== 200) {
414
- throw new errors_1.FlagsmithAPIError("Invalid request made to Flagsmith API. Response status code: ".concat(data.status));
415
- }
416
- return [2 /*return*/, data.json()];
417
- }
418
- });
419
- });
420
- };
421
- Flagsmith.prototype.getEnvironmentFromApi = function () {
422
- return __awaiter(this, void 0, void 0, function () {
423
- var environment_data;
424
- return __generator(this, function (_a) {
425
- switch (_a.label) {
426
- case 0:
427
- if (!this.environmentUrl) {
428
- throw new Error('`apiUrl` argument is missing or invalid.');
429
- }
430
- return [4 /*yield*/, this.getJSONResponse(this.environmentUrl, 'GET')];
431
- case 1:
432
- environment_data = _a.sent();
433
- return [2 /*return*/, (0, util_1.buildEnvironmentModel)(environment_data)];
434
- }
435
- });
436
- });
437
- };
438
- Flagsmith.prototype.getEnvironmentFlagsFromDocument = function () {
439
- return __awaiter(this, void 0, void 0, function () {
440
- var flags;
441
- return __generator(this, function (_a) {
442
- switch (_a.label) {
443
- case 0:
444
- flags = models_3.Flags.fromFeatureStateModels({
445
- featureStates: (0, flagsmith_engine_1.getEnvironmentFeatureStates)(this.environment),
446
- analyticsProcessor: this.analyticsProcessor,
447
- defaultFlagHandler: this.defaultFlagHandler
448
- });
449
- if (!!!this.cache) return [3 /*break*/, 2];
450
- // @ts-ignore node-cache types are incorrect, ttl should be optional
451
- return [4 /*yield*/, this.cache.set('flags', flags)];
452
- case 1:
453
- // @ts-ignore node-cache types are incorrect, ttl should be optional
454
- _a.sent();
455
- _a.label = 2;
456
- case 2: return [2 /*return*/, flags];
457
- }
458
- });
459
- });
460
- };
461
- Flagsmith.prototype.getIdentityFlagsFromDocument = function (identifier, traits) {
462
- return __awaiter(this, void 0, void 0, function () {
463
- var identityModel, featureStates, flags;
464
- return __generator(this, function (_a) {
465
- switch (_a.label) {
466
- case 0:
467
- identityModel = this.getIdentityModel(identifier, Object.keys(traits).map(function (key) { return ({
468
- key: key,
469
- value: traits[key]
470
- }); }));
471
- featureStates = (0, flagsmith_engine_1.getIdentityFeatureStates)(this.environment, identityModel);
472
- flags = models_3.Flags.fromFeatureStateModels({
473
- featureStates: featureStates,
474
- analyticsProcessor: this.analyticsProcessor,
475
- defaultFlagHandler: this.defaultFlagHandler,
476
- identityID: identityModel.djangoID || identityModel.compositeKey
477
- });
478
- if (!!!this.cache) return [3 /*break*/, 2];
479
- // @ts-ignore node-cache types are incorrect, ttl should be optional
480
- return [4 /*yield*/, this.cache.set("flags-".concat(identifier), flags)];
481
- case 1:
482
- // @ts-ignore node-cache types are incorrect, ttl should be optional
483
- _a.sent();
484
- _a.label = 2;
485
- case 2: return [2 /*return*/, flags];
486
- }
487
- });
488
- });
489
- };
490
- Flagsmith.prototype.getEnvironmentFlagsFromApi = function () {
491
- return __awaiter(this, void 0, void 0, function () {
492
- var apiFlags, flags, e_3;
493
- return __generator(this, function (_a) {
494
- switch (_a.label) {
495
- case 0:
496
- if (!this.environmentFlagsUrl) {
497
- throw new Error('`apiUrl` argument is missing or invalid.');
498
- }
499
- _a.label = 1;
500
- case 1:
501
- _a.trys.push([1, 5, , 6]);
502
- return [4 /*yield*/, this.getJSONResponse(this.environmentFlagsUrl, 'GET')];
503
- case 2:
504
- apiFlags = _a.sent();
505
- flags = models_3.Flags.fromAPIFlags({
506
- apiFlags: apiFlags,
507
- analyticsProcessor: this.analyticsProcessor,
508
- defaultFlagHandler: this.defaultFlagHandler
509
- });
510
- if (!!!this.cache) return [3 /*break*/, 4];
511
- // @ts-ignore node-cache types are incorrect, ttl should be optional
512
- return [4 /*yield*/, this.cache.set('flags', flags)];
513
- case 3:
514
- // @ts-ignore node-cache types are incorrect, ttl should be optional
515
- _a.sent();
516
- _a.label = 4;
517
- case 4: return [2 /*return*/, flags];
518
- case 5:
519
- e_3 = _a.sent();
520
- if (this.offlineHandler) {
521
- return [2 /*return*/, this.getEnvironmentFlagsFromDocument()];
522
- }
523
- if (this.defaultFlagHandler) {
524
- return [2 /*return*/, new models_3.Flags({
525
- flags: {},
526
- defaultFlagHandler: this.defaultFlagHandler
527
- })];
528
- }
529
- throw e_3;
530
- case 6: return [2 /*return*/];
531
- }
532
- });
533
- });
534
- };
535
- Flagsmith.prototype.getIdentityFlagsFromApi = function (identifier, traits) {
536
- return __awaiter(this, void 0, void 0, function () {
537
- var data, jsonResponse, flags, e_4;
538
- return __generator(this, function (_a) {
539
- switch (_a.label) {
540
- case 0:
541
- if (!this.identitiesUrl) {
542
- throw new Error('`apiUrl` argument is missing or invalid.');
543
- }
544
- _a.label = 1;
545
- case 1:
546
- _a.trys.push([1, 5, , 6]);
547
- data = (0, utils_1.generateIdentitiesData)(identifier, traits);
548
- return [4 /*yield*/, this.getJSONResponse(this.identitiesUrl, 'POST', data)];
549
- case 2:
550
- jsonResponse = _a.sent();
551
- flags = models_3.Flags.fromAPIFlags({
552
- apiFlags: jsonResponse['flags'],
553
- analyticsProcessor: this.analyticsProcessor,
554
- defaultFlagHandler: this.defaultFlagHandler
555
- });
556
- if (!!!this.cache) return [3 /*break*/, 4];
557
- // @ts-ignore node-cache types are incorrect, ttl should be optional
558
- return [4 /*yield*/, this.cache.set("flags-".concat(identifier), flags)];
559
- case 3:
560
- // @ts-ignore node-cache types are incorrect, ttl should be optional
561
- _a.sent();
562
- _a.label = 4;
563
- case 4: return [2 /*return*/, flags];
564
- case 5:
565
- e_4 = _a.sent();
566
- if (this.offlineHandler) {
567
- return [2 /*return*/, this.getIdentityFlagsFromDocument(identifier, traits)];
568
- }
569
- if (this.defaultFlagHandler) {
570
- return [2 /*return*/, new models_3.Flags({
571
- flags: {},
572
- defaultFlagHandler: this.defaultFlagHandler
573
- })];
574
- }
575
- throw e_4;
576
- case 6: return [2 /*return*/];
577
- }
578
- });
579
- });
580
- };
581
- Flagsmith.prototype.getIdentityModel = function (identifier, traits) {
582
- var _a;
583
- var traitModels = traits.map(function (trait) { return new models_2.TraitModel(trait.key, trait.value); });
584
- var identityWithOverrides = (_a = this.identitiesWithOverridesByIdentifier) === null || _a === void 0 ? void 0 : _a.get(identifier);
585
- if (identityWithOverrides) {
586
- identityWithOverrides.updateTraits(traitModels);
587
- return identityWithOverrides;
588
- }
589
- return new models_1.IdentityModel('0', traitModels, [], this.environment.apiKey, identifier);
590
- };
591
- return Flagsmith;
592
- }());
593
- exports.Flagsmith = Flagsmith;
594
- exports.default = Flagsmith;