flagsmith-nodejs 2.0.0 → 2.0.3

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 (72) 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/README.md +1 -1
  5. package/build/flagsmith-engine/environments/integrations/models.d.ts +4 -0
  6. package/build/flagsmith-engine/environments/integrations/models.js +11 -0
  7. package/build/flagsmith-engine/environments/models.d.ts +25 -0
  8. package/build/flagsmith-engine/environments/models.js +29 -0
  9. package/build/flagsmith-engine/environments/util.d.ts +3 -0
  10. package/build/flagsmith-engine/environments/util.js +21 -0
  11. package/build/flagsmith-engine/features/constants.d.ts +4 -0
  12. package/build/flagsmith-engine/features/constants.js +7 -0
  13. package/build/flagsmith-engine/features/models.d.ts +37 -0
  14. package/build/flagsmith-engine/features/models.js +122 -0
  15. package/build/flagsmith-engine/features/util.d.ts +4 -0
  16. package/build/flagsmith-engine/features/util.js +27 -0
  17. package/build/flagsmith-engine/identities/models.d.ts +15 -0
  18. package/build/flagsmith-engine/identities/models.js +112 -0
  19. package/build/flagsmith-engine/identities/traits/models.d.ts +5 -0
  20. package/build/flagsmith-engine/identities/traits/models.js +11 -0
  21. package/build/flagsmith-engine/identities/util.d.ts +4 -0
  22. package/build/flagsmith-engine/identities/util.js +46 -0
  23. package/build/flagsmith-engine/index.d.ts +8 -0
  24. package/build/flagsmith-engine/index.js +115 -0
  25. package/build/flagsmith-engine/organisations/models.d.ts +9 -0
  26. package/build/flagsmith-engine/organisations/models.js +21 -0
  27. package/build/flagsmith-engine/organisations/util.d.ts +2 -0
  28. package/build/flagsmith-engine/organisations/util.js +8 -0
  29. package/build/flagsmith-engine/projects/models.d.ts +10 -0
  30. package/build/flagsmith-engine/projects/models.js +14 -0
  31. package/build/flagsmith-engine/projects/util.d.ts +2 -0
  32. package/build/flagsmith-engine/projects/util.js +15 -0
  33. package/build/flagsmith-engine/segments/constants.d.ts +26 -0
  34. package/build/flagsmith-engine/segments/constants.js +31 -0
  35. package/build/flagsmith-engine/segments/evaluators.d.ts +6 -0
  36. package/build/flagsmith-engine/segments/evaluators.js +37 -0
  37. package/build/flagsmith-engine/segments/models.d.ts +37 -0
  38. package/build/flagsmith-engine/segments/models.js +114 -0
  39. package/build/flagsmith-engine/segments/util.d.ts +6 -0
  40. package/build/flagsmith-engine/segments/util.js +33 -0
  41. package/build/flagsmith-engine/utils/collections.d.ts +3 -0
  42. package/build/flagsmith-engine/utils/collections.js +26 -0
  43. package/build/flagsmith-engine/utils/errors.d.ts +2 -0
  44. package/build/flagsmith-engine/utils/errors.js +26 -0
  45. package/build/flagsmith-engine/utils/hashing/index.d.ts +9 -0
  46. package/build/flagsmith-engine/utils/hashing/index.js +60 -0
  47. package/build/flagsmith-engine/utils/index.d.ts +1 -0
  48. package/build/flagsmith-engine/utils/index.js +17 -0
  49. package/build/index.d.ts +1 -0
  50. package/build/index.js +11 -0
  51. package/build/sdk/analytics.d.ts +28 -0
  52. package/build/sdk/analytics.js +102 -0
  53. package/build/sdk/errors.d.ts +4 -0
  54. package/build/sdk/errors.js +34 -0
  55. package/build/sdk/index.d.ts +123 -0
  56. package/build/sdk/index.js +492 -0
  57. package/build/sdk/models.d.ts +55 -0
  58. package/build/sdk/models.js +149 -0
  59. package/build/sdk/polling_manager.d.ts +9 -0
  60. package/build/sdk/polling_manager.js +72 -0
  61. package/build/sdk/types.d.ts +7 -0
  62. package/build/sdk/types.js +2 -0
  63. package/build/sdk/utils.d.ts +12 -0
  64. package/build/sdk/utils.js +92 -0
  65. package/example/package-lock.json +996 -1
  66. package/example/server/api/index.js +6 -3
  67. package/example/server/index.js +1 -1
  68. package/package.json +3 -2
  69. package/sdk/index.ts +4 -0
  70. package/sdk/types.ts +4 -4
  71. package/tests/sdk/utils.ts +2 -1
  72. package/.tool-versions +0 -1
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCastingFunction = void 0;
4
+ var util_1 = require("../segments/util");
5
+ function getCastingFunction(traitType) {
6
+ switch (traitType) {
7
+ case 'boolean':
8
+ return function (x) { return !['False', 'false'].includes(x); };
9
+ case 'number':
10
+ return function (x) { return parseFloat(x); };
11
+ case 'semver':
12
+ return function (x) { return (0, util_1.removeSemverSuffix)(x); };
13
+ default:
14
+ return function (x) { return String(x); };
15
+ }
16
+ }
17
+ 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
+ var 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,102 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.AnalyticsProcessor = void 0;
43
+ var node_fetch_1 = __importDefault(require("node-fetch"));
44
+ var ANALYTICS_ENDPOINT = 'analytics/flags/';
45
+ // Used to control how often we send data(in seconds)
46
+ var ANALYTICS_TIMER = 10;
47
+ var AnalyticsProcessor = /** @class */ (function () {
48
+ /**
49
+ * AnalyticsProcessor is used to track how often individual Flags are evaluated within
50
+ * the Flagsmith SDK. Docs: https://docs.flagsmith.com/advanced-use/flag-analytics.
51
+ *
52
+ * @param data.environmentKey environment key obtained from the Flagsmith UI
53
+ * @param data.baseApiUrl base api url to override when using self hosted version
54
+ * @param data.timeout used to tell requests to stop waiting for a response after a
55
+ given number of seconds
56
+ */
57
+ function AnalyticsProcessor(data) {
58
+ this.timeout = 3;
59
+ this.analyticsEndpoint = data.baseApiUrl + ANALYTICS_ENDPOINT;
60
+ this.environmentKey = data.environmentKey;
61
+ this.lastFlushed = Date.now();
62
+ this.analyticsData = {};
63
+ this.timeout = data.timeout || this.timeout;
64
+ }
65
+ /**
66
+ * Sends all the collected data to the api asynchronously and resets the timer
67
+ */
68
+ AnalyticsProcessor.prototype.flush = function () {
69
+ return __awaiter(this, void 0, void 0, function () {
70
+ return __generator(this, function (_a) {
71
+ switch (_a.label) {
72
+ case 0:
73
+ if (!Object.keys(this.analyticsData).length) {
74
+ return [2 /*return*/];
75
+ }
76
+ return [4 /*yield*/, (0, node_fetch_1.default)(this.analyticsEndpoint, {
77
+ method: 'POST',
78
+ body: JSON.stringify(this.analyticsData),
79
+ timeout: this.timeout,
80
+ headers: {
81
+ 'Content-Type': 'application/json',
82
+ 'X-Environment-Key': this.environmentKey
83
+ }
84
+ })];
85
+ case 1:
86
+ _a.sent();
87
+ this.analyticsData = {};
88
+ this.lastFlushed = Date.now();
89
+ return [2 /*return*/];
90
+ }
91
+ });
92
+ });
93
+ };
94
+ AnalyticsProcessor.prototype.trackFeature = function (featureId) {
95
+ this.analyticsData[featureId] = (this.analyticsData[featureId] || 0) + 1;
96
+ if (Date.now() - this.lastFlushed > ANALYTICS_TIMER * 1000) {
97
+ this.flush();
98
+ }
99
+ };
100
+ return AnalyticsProcessor;
101
+ }());
102
+ 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,34 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.FlagsmithAPIError = exports.FlagsmithClientError = void 0;
19
+ var FlagsmithClientError = /** @class */ (function (_super) {
20
+ __extends(FlagsmithClientError, _super);
21
+ function FlagsmithClientError() {
22
+ return _super !== null && _super.apply(this, arguments) || this;
23
+ }
24
+ return FlagsmithClientError;
25
+ }(Error));
26
+ exports.FlagsmithClientError = FlagsmithClientError;
27
+ var FlagsmithAPIError = /** @class */ (function (_super) {
28
+ __extends(FlagsmithAPIError, _super);
29
+ function FlagsmithAPIError() {
30
+ return _super !== null && _super.apply(this, arguments) || this;
31
+ }
32
+ return FlagsmithAPIError;
33
+ }(Error));
34
+ exports.FlagsmithAPIError = FlagsmithAPIError;
@@ -0,0 +1,123 @@
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
+ import { FlagsmithCache } from './types';
6
+ export declare class Flagsmith {
7
+ environmentKey?: string;
8
+ apiUrl: string;
9
+ customHeaders?: {
10
+ [key: string]: any;
11
+ };
12
+ requestTimeoutSeconds?: number;
13
+ enableLocalEvaluation?: boolean;
14
+ environmentRefreshIntervalSeconds: number;
15
+ retries?: number;
16
+ enableAnalytics: boolean;
17
+ defaultFlagHandler?: (featureName: string) => DefaultFlag;
18
+ environmentFlagsUrl: string;
19
+ identitiesUrl: string;
20
+ environmentUrl: string;
21
+ environmentDataPollingManager?: EnvironmentDataPollingManager;
22
+ environment: EnvironmentModel;
23
+ private cache?;
24
+ private onEnvironmentChange?;
25
+ private analyticsProcessor?;
26
+ /**
27
+ * A Flagsmith client.
28
+ *
29
+ * Provides an interface for interacting with the Flagsmith http API.
30
+ * Basic Usage::
31
+ *
32
+ * import flagsmith from Flagsmith
33
+ * const flagsmith = new Flagsmith({environmentKey: '<your API key>'});
34
+ * const environmentFlags = flagsmith.getEnvironmentFlags();
35
+ * const featureEnabled = environmentFlags.isFeatureEnabled('foo');
36
+ * const identityFlags = flagsmith.getIdentityFlags('identifier', {'foo': 'bar'});
37
+ * const featureEnabledForIdentity = identityFlags.isFeatureEnabled("foo")
38
+ *
39
+ * @param {string} data.environmentKey: The environment key obtained from Flagsmith interface
40
+ @param {string} data.apiUrl: Override the URL of the Flagsmith API to communicate with
41
+ @param data.customHeaders: Additional headers to add to requests made to the
42
+ Flagsmith API
43
+ @param {number} data.requestTimeoutSeconds: Number of seconds to wait for a request to
44
+ complete before terminating the request
45
+ @param {boolean} data.enableLocalEvaluation: Enables local evaluation of flags
46
+ @param {number} data.environmentRefreshIntervalSeconds: If using local evaluation,
47
+ specify the interval period between refreshes of local environment data
48
+ @param {number} data.retries: a urllib3.Retry object to use on all http requests to the
49
+ Flagsmith API
50
+ @param {boolean} data.enableAnalytics: if enabled, sends additional requests to the Flagsmith
51
+ API to power flag analytics charts
52
+ @param data.defaultFlagHandler: callable which will be used in the case where
53
+ flags cannot be retrieved from the API or a non existent feature is
54
+ requested
55
+ */
56
+ constructor(data: {
57
+ environmentKey: string;
58
+ apiUrl?: string;
59
+ customHeaders?: {
60
+ [key: string]: any;
61
+ };
62
+ requestTimeoutSeconds?: number;
63
+ enableLocalEvaluation?: boolean;
64
+ environmentRefreshIntervalSeconds?: number;
65
+ retries?: number;
66
+ enableAnalytics?: boolean;
67
+ defaultFlagHandler?: (featureName: string) => DefaultFlag;
68
+ cache?: FlagsmithCache;
69
+ onEnvironmentChange?: (error: Error | null, result: EnvironmentModel) => void;
70
+ });
71
+ /**
72
+ * Get all the default for flags for the current environment.
73
+ *
74
+ * @returns Flags object holding all the flags for the current environment.
75
+ */
76
+ getEnvironmentFlags(): Promise<Flags>;
77
+ /**
78
+ * Get all the flags for the current environment for a given identity. Will also
79
+ upsert all traits to the Flagsmith API for future evaluations. Providing a
80
+ trait with a value of None will remove the trait from the identity if it exists.
81
+ *
82
+ * @param {string} identifier a unique identifier for the identity in the current
83
+ environment, e.g. email address, username, uuid
84
+ * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
85
+ Flagsmith, e.g. {"num_orders": 10}
86
+ * @returns Flags object holding all the flags for the given identity.
87
+ */
88
+ getIdentityFlags(identifier: string, traits?: {
89
+ [key: string]: any;
90
+ }): Promise<Flags>;
91
+ /**
92
+ * Get the segments for the current environment for a given identity. Will also
93
+ upsert all traits to the Flagsmith API for future evaluations. Providing a
94
+ trait with a value of None will remove the trait from the identity if it exists.
95
+ *
96
+ * @param {string} identifier a unique identifier for the identity in the current
97
+ environment, e.g. email address, username, uuid
98
+ * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
99
+ Flagsmith, e.g. {"num_orders": 10}
100
+ * @returns Segments that the given identity belongs to.
101
+ */
102
+ getIdentitySegments(identifier: string, traits?: {
103
+ [key: string]: any;
104
+ }): Promise<SegmentModel[]>;
105
+ /**
106
+ * Updates the environment state for local flag evaluation.
107
+ * Sets a local promise to prevent race conditions in getIdentityFlags / getIdentitySegments.
108
+ * You only need to call this if you wish to bypass environmentRefreshIntervalSeconds.
109
+ */
110
+ updateEnvironment(): Promise<void>;
111
+ private getJSONResponse;
112
+ /**
113
+ * This promise ensures that the environment is retrieved before attempting to locally evaluate.
114
+ */
115
+ private environmentPromise;
116
+ private getEnvironmentFromApi;
117
+ private getEnvironmentFlagsFromDocument;
118
+ private getIdentityFlagsFromDocument;
119
+ private getEnvironmentFlagsFromApi;
120
+ private getIdentityFlagsFromApi;
121
+ private buildIdentityModel;
122
+ }
123
+ export default Flagsmith;