@kameleoon/javascript-sdk-core 0.0.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 (107) hide show
  1. package/README.md +8 -0
  2. package/dist/configurations/configuration.d.ts +15 -0
  3. package/dist/configurations/configuration.js +31 -0
  4. package/dist/configurations/configuration.js.map +1 -0
  5. package/dist/configurations/experiment.d.ts +13 -0
  6. package/dist/configurations/experiment.js +54 -0
  7. package/dist/configurations/experiment.js.map +1 -0
  8. package/dist/configurations/featureFlag.d.ts +23 -0
  9. package/dist/configurations/featureFlag.js +105 -0
  10. package/dist/configurations/featureFlag.js.map +1 -0
  11. package/dist/configurations/variation.d.ts +15 -0
  12. package/dist/configurations/variation.js +14 -0
  13. package/dist/configurations/variation.js.map +1 -0
  14. package/dist/constants.d.ts +17 -0
  15. package/dist/constants.js +23 -0
  16. package/dist/constants.js.map +1 -0
  17. package/dist/data.d.ts +67 -0
  18. package/dist/data.js +127 -0
  19. package/dist/data.js.map +1 -0
  20. package/dist/exceptions/credentialsNotFound.d.ts +6 -0
  21. package/dist/exceptions/credentialsNotFound.js +29 -0
  22. package/dist/exceptions/credentialsNotFound.js.map +1 -0
  23. package/dist/exceptions/experimentConfigurationNotFound.d.ts +6 -0
  24. package/dist/exceptions/experimentConfigurationNotFound.js +29 -0
  25. package/dist/exceptions/experimentConfigurationNotFound.js.map +1 -0
  26. package/dist/exceptions/featureConfigurationNotFound.d.ts +6 -0
  27. package/dist/exceptions/featureConfigurationNotFound.js +29 -0
  28. package/dist/exceptions/featureConfigurationNotFound.js.map +1 -0
  29. package/dist/exceptions/notActivated.d.ts +6 -0
  30. package/dist/exceptions/notActivated.js +29 -0
  31. package/dist/exceptions/notActivated.js.map +1 -0
  32. package/dist/exceptions/notTargeted.d.ts +6 -0
  33. package/dist/exceptions/notTargeted.js +29 -0
  34. package/dist/exceptions/notTargeted.js.map +1 -0
  35. package/dist/exceptions/siteCodeDisabled.d.ts +5 -0
  36. package/dist/exceptions/siteCodeDisabled.js +30 -0
  37. package/dist/exceptions/siteCodeDisabled.js.map +1 -0
  38. package/dist/exceptions/variationConfigurationNotFound.d.ts +6 -0
  39. package/dist/exceptions/variationConfigurationNotFound.js +29 -0
  40. package/dist/exceptions/variationConfigurationNotFound.js.map +1 -0
  41. package/dist/exceptions/visitorCodeNotValid.d.ts +5 -0
  42. package/dist/exceptions/visitorCodeNotValid.js +30 -0
  43. package/dist/exceptions/visitorCodeNotValid.js.map +1 -0
  44. package/dist/index.d.ts +3 -0
  45. package/dist/index.js +11 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/interfaces/interfaces.d.ts +81 -0
  48. package/dist/interfaces/interfaces.js +3 -0
  49. package/dist/interfaces/interfaces.js.map +1 -0
  50. package/dist/kameleoonClient.d.ts +102 -0
  51. package/dist/kameleoonClient.js +732 -0
  52. package/dist/kameleoonClient.js.map +1 -0
  53. package/dist/kameleoonUtils.d.ts +11 -0
  54. package/dist/kameleoonUtils.js +107 -0
  55. package/dist/kameleoonUtils.js.map +1 -0
  56. package/dist/nonce.d.ts +1 -0
  57. package/dist/nonce.js +16 -0
  58. package/dist/nonce.js.map +1 -0
  59. package/dist/realTimeConfigurationService.d.ts +12 -0
  60. package/dist/realTimeConfigurationService.js +24 -0
  61. package/dist/realTimeConfigurationService.js.map +1 -0
  62. package/dist/storage/types.d.ts +13 -0
  63. package/dist/storage/types.js +3 -0
  64. package/dist/storage/types.js.map +1 -0
  65. package/dist/storage/variationStorage.d.ts +11 -0
  66. package/dist/storage/variationStorage.js +159 -0
  67. package/dist/storage/variationStorage.js.map +1 -0
  68. package/dist/storage/visitorVariation.d.ts +9 -0
  69. package/dist/storage/visitorVariation.js +22 -0
  70. package/dist/storage/visitorVariation.js.map +1 -0
  71. package/dist/targeting/conditions/customDatum.d.ts +12 -0
  72. package/dist/targeting/conditions/customDatum.js +129 -0
  73. package/dist/targeting/conditions/customDatum.js.map +1 -0
  74. package/dist/targeting/conditions/exclusiveExperiment.d.ts +9 -0
  75. package/dist/targeting/conditions/exclusiveExperiment.js +45 -0
  76. package/dist/targeting/conditions/exclusiveExperiment.js.map +1 -0
  77. package/dist/targeting/conditions/targetExperiment.d.ts +14 -0
  78. package/dist/targeting/conditions/targetExperiment.js +57 -0
  79. package/dist/targeting/conditions/targetExperiment.js.map +1 -0
  80. package/dist/targeting/conditions/types.d.ts +12 -0
  81. package/dist/targeting/conditions/types.js +3 -0
  82. package/dist/targeting/conditions/types.js.map +1 -0
  83. package/dist/targeting/targetingCondition.d.ts +7 -0
  84. package/dist/targeting/targetingCondition.js +9 -0
  85. package/dist/targeting/targetingCondition.js.map +1 -0
  86. package/dist/targeting/targetingConditionsFactory.d.ts +7 -0
  87. package/dist/targeting/targetingConditionsFactory.js +30 -0
  88. package/dist/targeting/targetingConditionsFactory.js.map +1 -0
  89. package/dist/targeting/targetingData.d.ts +7 -0
  90. package/dist/targeting/targetingData.js +11 -0
  91. package/dist/targeting/targetingData.js.map +1 -0
  92. package/dist/targeting/targetingEngine.d.ts +6 -0
  93. package/dist/targeting/targetingEngine.js +130 -0
  94. package/dist/targeting/targetingEngine.js.map +1 -0
  95. package/dist/targeting/targetingSegment.d.ts +5 -0
  96. package/dist/targeting/targetingSegment.js +9 -0
  97. package/dist/targeting/targetingSegment.js.map +1 -0
  98. package/dist/targeting/targetingTree.d.ts +9 -0
  99. package/dist/targeting/targetingTree.js +13 -0
  100. package/dist/targeting/targetingTree.js.map +1 -0
  101. package/dist/targeting/targetingTreeBuilder.d.ts +8 -0
  102. package/dist/targeting/targetingTreeBuilder.js +127 -0
  103. package/dist/targeting/targetingTreeBuilder.js.map +1 -0
  104. package/dist/types.d.ts +5 -0
  105. package/dist/types.js +3 -0
  106. package/dist/types.js.map +1 -0
  107. package/package.json +39 -0
@@ -0,0 +1,732 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __generator = (this && this.__generator) || function (thisArg, body) {
35
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
36
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
37
+ function verb(n) { return function (v) { return step([n, v]); }; }
38
+ function step(op) {
39
+ if (f) throw new TypeError("Generator is already executing.");
40
+ while (_) try {
41
+ 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;
42
+ if (y = 0, t) op = [op[0] & 2, t.value];
43
+ switch (op[0]) {
44
+ case 0: case 1: t = op; break;
45
+ case 4: _.label++; return { value: op[1], done: false };
46
+ case 5: _.label++; y = op[1]; op = [0]; continue;
47
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
48
+ default:
49
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
50
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
51
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
52
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
53
+ if (t[2]) _.ops.pop();
54
+ _.trys.pop(); continue;
55
+ }
56
+ op = body.call(thisArg, _);
57
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
58
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
+ }
60
+ };
61
+ var __importDefault = (this && this.__importDefault) || function (mod) {
62
+ return (mod && mod.__esModule) ? mod : { "default": mod };
63
+ };
64
+ Object.defineProperty(exports, "__esModule", { value: true });
65
+ exports.KameleoonException = exports.KameleoonClient = void 0;
66
+ var async_storage_1 = __importDefault(require("@react-native-async-storage/async-storage"));
67
+ var configuration_1 = __importDefault(require("./configurations/configuration"));
68
+ var data_1 = __importDefault(require("./data"));
69
+ var kameleoonUtils_1 = __importStar(require("./kameleoonUtils"));
70
+ var targetingData_1 = __importDefault(require("./targeting/targetingData"));
71
+ var experimentConfigurationNotFound_1 = __importDefault(require("./exceptions/experimentConfigurationNotFound"));
72
+ var featureConfigurationNotFound_1 = __importDefault(require("./exceptions/featureConfigurationNotFound"));
73
+ var notActivated_1 = __importDefault(require("./exceptions/notActivated"));
74
+ var notTargeted_1 = __importDefault(require("./exceptions/notTargeted"));
75
+ var variationConfigurationNotFound_1 = __importDefault(require("./exceptions/variationConfigurationNotFound"));
76
+ var credentialsNotFound_1 = __importDefault(require("./exceptions/credentialsNotFound"));
77
+ var visitorCodeNotValid_1 = require("./exceptions/visitorCodeNotValid");
78
+ var siteCodeDisabled_1 = require("./exceptions/siteCodeDisabled");
79
+ var nonce_1 = require("./nonce");
80
+ var realTimeConfigurationService_1 = require("./realTimeConfigurationService");
81
+ var variationStorage_1 = require("./storage/variationStorage");
82
+ var constants_1 = require("./constants");
83
+ var targetingEngine_1 = require("./targeting/targetingEngine");
84
+ var KameleoonClient = /** @class */ (function () {
85
+ function KameleoonClient(siteCode, configuration) {
86
+ var _this = this;
87
+ this.ready = false;
88
+ this.readyCallbacks = [];
89
+ this.minutesBetweenConfigurationUpdate = 30;
90
+ this.targetingData = {};
91
+ this.unsentData = {};
92
+ this.visitorDataMaximumSize = 1;
93
+ this.environment = null;
94
+ this.realTimeConfigurationService = null;
95
+ this.handlerUpdateConfiguration = null;
96
+ this.variationStorage = new variationStorage_1.VariationStorage();
97
+ this.updateCampaignConfiguration = function (timeStamp) { return __awaiter(_this, void 0, void 0, function () {
98
+ var data, savedTargetingData, savedConfiguration, needUpdate, parsedConfiguration, siteCodeStringUrl, environmentStringUrl, timeStampStringUrl, configurationUrl;
99
+ var _this = this;
100
+ var _a;
101
+ return __generator(this, function (_b) {
102
+ switch (_b.label) {
103
+ case 0:
104
+ if (!(typeof document !== 'undefined')) return [3 /*break*/, 1];
105
+ data = localStorage.getItem('kameleoonJavaScriptClientData');
106
+ return [3 /*break*/, 3];
107
+ case 1:
108
+ if (!(typeof navigator !== 'undefined' &&
109
+ navigator.product === 'ReactNative')) return [3 /*break*/, 3];
110
+ return [4 /*yield*/, async_storage_1.default.getItem('kameleoonJavaScriptClientData')];
111
+ case 2:
112
+ data = _b.sent();
113
+ _b.label = 3;
114
+ case 3:
115
+ if (data) {
116
+ try {
117
+ data = JSON.parse(data);
118
+ }
119
+ catch (e) {
120
+ console.log(e);
121
+ }
122
+ }
123
+ if (!data) {
124
+ data = {
125
+ kameleoonTargetingData: {},
126
+ kameleoonConfiguration: {},
127
+ };
128
+ }
129
+ savedTargetingData = data.kameleoonTargetingData;
130
+ if (savedTargetingData) {
131
+ try {
132
+ this.targetingData = savedTargetingData;
133
+ this.emptyTargetingData();
134
+ }
135
+ catch (e) {
136
+ this.targetingData = {};
137
+ }
138
+ }
139
+ savedConfiguration = data.kameleoonConfiguration;
140
+ needUpdate = false;
141
+ if (!savedConfiguration || timeStamp != null) {
142
+ // timeStamp != null means update by SSE event and requires force update
143
+ needUpdate = true;
144
+ }
145
+ else {
146
+ try {
147
+ parsedConfiguration = new configuration_1.default(this.siteCode, {
148
+ configuration: savedConfiguration.configuration,
149
+ experiments: savedConfiguration.experiments,
150
+ featureFlags: savedConfiguration.featureFlags,
151
+ updateTime: savedConfiguration.updateTime,
152
+ });
153
+ if (parsedConfiguration.updateTime <
154
+ new Date().getTime() -
155
+ this.minutesBetweenConfigurationUpdate * 1000 * 60 || //refresh by polling interval
156
+ parsedConfiguration.settings.realTimeUpdate) {
157
+ //streaming initial refresh, need to update to recent version of configuration
158
+ needUpdate = true;
159
+ }
160
+ else {
161
+ this.configurations = parsedConfiguration;
162
+ }
163
+ }
164
+ catch (e) {
165
+ needUpdate = true;
166
+ }
167
+ }
168
+ if (needUpdate) {
169
+ siteCodeStringUrl = "mobile?siteCode=".concat(this.siteCode);
170
+ environmentStringUrl = ((_a = this.environment) === null || _a === void 0 ? void 0 : _a.length)
171
+ ? "&environment=".concat(this.environment)
172
+ : '';
173
+ timeStampStringUrl = timeStamp ? "&ts=".concat(timeStamp) : '';
174
+ configurationUrl = constants_1.CONFIGURATION_URL +
175
+ siteCodeStringUrl +
176
+ environmentStringUrl +
177
+ timeStampStringUrl;
178
+ kameleoonUtils_1.default.doRequest(configurationUrl, kameleoonUtils_1.HttpMethod.GET, null, function (response) { return __awaiter(_this, void 0, void 0, function () {
179
+ return __generator(this, function (_a) {
180
+ try {
181
+ this.configurations = new configuration_1.default(this.siteCode, JSON.parse(response));
182
+ this.ready = true;
183
+ this.clearCallbacks(true);
184
+ this.saveConfiguration();
185
+ this.fireUpdateConfigurationHandler(Boolean(timeStamp)); //fire handler after configuration was updated with SSE event
186
+ this.manageConfiguraitonUpdate(this.configurations.settings.realTimeUpdate);
187
+ }
188
+ catch (e) {
189
+ console.log(e);
190
+ }
191
+ return [2 /*return*/];
192
+ });
193
+ }); }, false);
194
+ }
195
+ else {
196
+ this.ready = true;
197
+ this.clearCallbacks(true);
198
+ }
199
+ return [2 /*return*/];
200
+ }
201
+ });
202
+ }); };
203
+ this.runWhenReady = function (successCallback, errorCallback, timeout) {
204
+ if (_this.ready) {
205
+ successCallback && successCallback();
206
+ }
207
+ else {
208
+ _this.readyCallbacks.push({
209
+ error: errorCallback,
210
+ success: successCallback,
211
+ timeout: setTimeout(function () {
212
+ _this.clearCallbacks(false, errorCallback);
213
+ }, timeout),
214
+ });
215
+ }
216
+ };
217
+ this.clearCallbacks = function (success, errorCallback) {
218
+ var callbacksToKeep = [];
219
+ _this.readyCallbacks.forEach(function (c) {
220
+ if (success) {
221
+ c.success && c.success();
222
+ clearTimeout(c.timeout);
223
+ }
224
+ else {
225
+ if (!success && errorCallback == c.error) {
226
+ c.error && c.error();
227
+ }
228
+ else {
229
+ callbacksToKeep.push(c);
230
+ }
231
+ }
232
+ });
233
+ _this.readyCallbacks = callbacksToKeep;
234
+ };
235
+ this.trackConversion = function (visitorCode, goalId, revenue) {
236
+ _this.validateVisitorCode(visitorCode);
237
+ _this.addData(visitorCode, new data_1.default.Conversion(goalId, revenue, false));
238
+ _this.flush(visitorCode);
239
+ };
240
+ this.flush = function (visitorCode) {
241
+ if (visitorCode != null) {
242
+ var body = _this.getAndClearUnsentData(visitorCode);
243
+ kameleoonUtils_1.default.doRequest(constants_1.API_SSX_URL + _this.getDataTrackingURL(visitorCode), kameleoonUtils_1.HttpMethod.POST, body, null);
244
+ }
245
+ else {
246
+ _this.getUnsentUsers().forEach(function (vc) { return _this.flush(vc); });
247
+ }
248
+ };
249
+ this.triggerExperiment = function (visitorCode, experimentId) {
250
+ var _a;
251
+ _this.validateVisitorCode(visitorCode);
252
+ var xpConf = (_a = _this.configurations) === null || _a === void 0 ? void 0 : _a.experiments[experimentId];
253
+ _this.checkSiteEnabled(xpConf);
254
+ if (_this.checkTargeting(visitorCode, experimentId, false)) {
255
+ var variationId = 0;
256
+ var noneVariation = true;
257
+ var savedVariationId = _this.variationStorage.getVariationId(visitorCode, experimentId);
258
+ if (savedVariationId) {
259
+ variationId = savedVariationId;
260
+ noneVariation = false;
261
+ }
262
+ else {
263
+ if (xpConf) {
264
+ var hashDouble = _this.obtainHashDouble(experimentId, visitorCode, xpConf);
265
+ var total = 0.0;
266
+ for (var key in xpConf.variationConfigurations) {
267
+ var variationConfiguration = xpConf.variationConfigurations[key];
268
+ total += variationConfiguration.deviation;
269
+ if (total >= hashDouble) {
270
+ noneVariation = false;
271
+ variationId = parseInt(key);
272
+ _this.variationStorage.updateVariation(visitorCode, experimentId, variationConfiguration);
273
+ break;
274
+ }
275
+ }
276
+ var body = _this.getAndClearUnsentData(visitorCode);
277
+ kameleoonUtils_1.default.doRequest(constants_1.API_SSX_URL +
278
+ _this.getExperimentRegisterURL(visitorCode, experimentId, variationId, noneVariation), kameleoonUtils_1.HttpMethod.POST, body);
279
+ }
280
+ else {
281
+ throw new experimentConfigurationNotFound_1.default('KameleoonException.ExperimentConfigurationNotFound');
282
+ }
283
+ }
284
+ if (noneVariation) {
285
+ throw new notActivated_1.default('KameleoonException.NotActivated');
286
+ }
287
+ return variationId;
288
+ }
289
+ else {
290
+ throw new notTargeted_1.default('KameleoonException.NotTargeted');
291
+ }
292
+ };
293
+ this.activateFeature = function (visitorCode, featureIdOrName) {
294
+ var _a, _b;
295
+ _this.checkFeatureKeyOrId(featureIdOrName);
296
+ _this.validateVisitorCode(visitorCode);
297
+ var featureFlag = null;
298
+ var featureId = -1;
299
+ for (var key in (_a = _this.configurations) === null || _a === void 0 ? void 0 : _a.featureFlags) {
300
+ var ff = (_b = _this.configurations) === null || _b === void 0 ? void 0 : _b.featureFlags[key];
301
+ if (key == featureIdOrName || (ff === null || ff === void 0 ? void 0 : ff.identificationKey) == featureIdOrName) {
302
+ featureId = parseInt(key);
303
+ featureFlag = ff;
304
+ }
305
+ }
306
+ _this.checkSiteEnabled(featureFlag);
307
+ if (_this.checkTargeting(visitorCode, featureId, true)) {
308
+ if (featureFlag && featureId) {
309
+ var result = false;
310
+ if (featureFlag.isScheduleActive()) {
311
+ var hashDouble = _this.obtainHashDouble(featureId, visitorCode, featureFlag);
312
+ var total = 0.0;
313
+ var variationId = 0;
314
+ var noneVariation = true;
315
+ for (var key in featureFlag.variationConfigurations) {
316
+ var variationConfiguration = featureFlag.variationConfigurations[key];
317
+ total += variationConfiguration.deviation;
318
+ if (total >= hashDouble) {
319
+ noneVariation = false;
320
+ variationId = parseInt(key);
321
+ break;
322
+ }
323
+ }
324
+ var body = _this.getAndClearUnsentData(visitorCode);
325
+ kameleoonUtils_1.default.doRequest(constants_1.API_SSX_URL +
326
+ _this.getExperimentRegisterURL(visitorCode, featureId, variationId, noneVariation), kameleoonUtils_1.HttpMethod.POST, body);
327
+ result = variationId != 0;
328
+ }
329
+ return result;
330
+ }
331
+ else {
332
+ throw new featureConfigurationNotFound_1.default('KameleoonException.FeatureConfigurationNotFound');
333
+ }
334
+ }
335
+ else {
336
+ throw new notTargeted_1.default('KameleoonException.NotTargeted');
337
+ }
338
+ };
339
+ this.generateRandomString = function () {
340
+ var alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';
341
+ var alphabetLength = alphabet.length;
342
+ var randomVisitorCode = '';
343
+ for (var i = 0; i < 16; ++i) {
344
+ var randomNumber = Math.floor(Math.random() * alphabetLength);
345
+ randomVisitorCode += alphabet[randomNumber];
346
+ }
347
+ return randomVisitorCode;
348
+ };
349
+ this.obtainAsyncVisitorCode = function (domain, defaultVisitorCode) { return __awaiter(_this, void 0, void 0, function () {
350
+ var savedVisitorCode;
351
+ return __generator(this, function (_a) {
352
+ switch (_a.label) {
353
+ case 0:
354
+ savedVisitorCode = null;
355
+ return [4 /*yield*/, async_storage_1.default.getItem('kameleoonVisitorCode')];
356
+ case 1:
357
+ savedVisitorCode = _a.sent();
358
+ if (!(savedVisitorCode == null)) return [3 /*break*/, 3];
359
+ savedVisitorCode = defaultVisitorCode || this.generateRandomString();
360
+ return [4 /*yield*/, async_storage_1.default.setItem('kameleoonVisitorCode', savedVisitorCode)];
361
+ case 2:
362
+ _a.sent();
363
+ _a.label = 3;
364
+ case 3: return [2 /*return*/, savedVisitorCode];
365
+ }
366
+ });
367
+ }); };
368
+ this.obtainVisitorCode = function (domain, defaultVisitorCode) {
369
+ var value;
370
+ var name = 'kameleoonVisitorCode';
371
+ var cookies = document.cookie.split(';');
372
+ for (var i = 0, cookiesLength = cookies.length; i < cookiesLength; ++i) {
373
+ var cookie = cookies[i];
374
+ var valuePos = cookie.indexOf('=');
375
+ if (cookie.substring(0, valuePos).trim() == name) {
376
+ value = cookie.substring(valuePos + 1);
377
+ break;
378
+ }
379
+ }
380
+ if (value) {
381
+ return value;
382
+ }
383
+ value = defaultVisitorCode || _this.generateRandomString();
384
+ document.cookie =
385
+ 'kameleoonVisitorCode=' +
386
+ value +
387
+ '; Max-Age=32832000; Path=/; Domain=' +
388
+ domain;
389
+ return value;
390
+ };
391
+ this.obtainHashDouble = function (containerId, visitorCode, xpConf) {
392
+ var joinedRespoolTime = '';
393
+ for (var variationId in xpConf.variationConfigurations) {
394
+ var variation = xpConf.variationConfigurations[variationId];
395
+ if (variation.respoolTime && variation.respoolTime != 0) {
396
+ joinedRespoolTime += variation.respoolTime;
397
+ }
398
+ }
399
+ var identifier = visitorCode + containerId + joinedRespoolTime;
400
+ var buff = kameleoonUtils_1.default.computeStringSha256(identifier);
401
+ return parseInt(buff, 16) / Math.pow(2, 256);
402
+ };
403
+ this.getCommonSSXParameters = function (visitorCode) {
404
+ return ('&nonce=' +
405
+ (0, nonce_1.obtainNonce)() +
406
+ '&siteCode=' +
407
+ _this.siteCode +
408
+ '&visitorCode=' +
409
+ visitorCode);
410
+ };
411
+ this.getDataTrackingURL = function (visitorCode) {
412
+ return 'dataTracking?' + _this.getCommonSSXParameters(visitorCode);
413
+ };
414
+ this.getAPIDataRequestURL = function (key) {
415
+ return "".concat(constants_1.API_DATA_URL, "data?siteCode=").concat(_this.siteCode, "&key=").concat(key);
416
+ };
417
+ this.getEventsRequestURL = function (siteCode) {
418
+ return "".concat(constants_1.EVENTS_URL, "sse?siteCode=").concat(siteCode);
419
+ };
420
+ this.getExperimentRegisterURL = function (visitorCode, experimentId, variationId, noneVariation) {
421
+ var baseURL = 'experimentTracking?' +
422
+ _this.getCommonSSXParameters(visitorCode) +
423
+ '&experimentId=' +
424
+ experimentId;
425
+ if (variationId == null) {
426
+ return baseURL;
427
+ }
428
+ else {
429
+ return (baseURL +
430
+ '&variationId=' +
431
+ variationId +
432
+ (noneVariation ? '&noneVariation=true' : ''));
433
+ }
434
+ };
435
+ this.getUnsentUsers = function () {
436
+ return Object.getOwnPropertyNames(_this.unsentData);
437
+ };
438
+ this.getUnsentData = function (visitorCode) {
439
+ if (!_this.unsentData[visitorCode]) {
440
+ _this.unsentData[visitorCode] = [];
441
+ }
442
+ return _this.unsentData[visitorCode];
443
+ };
444
+ this.getTargetingData = function (visitorCode) {
445
+ if (_this.targetingData[visitorCode] == null) {
446
+ _this.targetingData[visitorCode] = [];
447
+ }
448
+ return _this.targetingData[visitorCode];
449
+ };
450
+ this.emptyUnsentData = function (visitorCode) {
451
+ delete _this.unsentData[visitorCode];
452
+ };
453
+ this.emptyTargetingData = function () {
454
+ var currentTime = new Date().getTime();
455
+ for (var visitorCode in _this.targetingData) {
456
+ _this.targetingData[visitorCode] = _this.targetingData[visitorCode].reduce(function (arr, data) {
457
+ if (data.lastActivityTime + constants_1.MINUTES_SESSION_DURATION > currentTime) {
458
+ arr.push(data);
459
+ }
460
+ return arr;
461
+ }, []);
462
+ }
463
+ _this.saveConfiguration();
464
+ };
465
+ this.addData = function (visitorCode) {
466
+ var data = [];
467
+ for (var _i = 1; _i < arguments.length; _i++) {
468
+ data[_i - 1] = arguments[_i];
469
+ }
470
+ return __awaiter(_this, void 0, void 0, function () {
471
+ var listData, targetingDataList;
472
+ var _this = this;
473
+ return __generator(this, function (_a) {
474
+ this.validateVisitorCode(visitorCode);
475
+ listData = this.getUnsentData(visitorCode);
476
+ targetingDataList = this.getTargetingData(visitorCode);
477
+ data.forEach(function (d) { return __awaiter(_this, void 0, void 0, function () {
478
+ return __generator(this, function (_a) {
479
+ switch (_a.label) {
480
+ case 0:
481
+ listData.push(d);
482
+ if (targetingDataList.length < this.targetingDataNumberEntriesAuthorized) {
483
+ targetingDataList.push(new targetingData_1.default(new Date().getTime(), d));
484
+ }
485
+ else {
486
+ targetingDataList.splice(0, 1);
487
+ targetingDataList.push(new targetingData_1.default(new Date().getTime(), d));
488
+ }
489
+ return [4 /*yield*/, this.saveConfiguration()];
490
+ case 1:
491
+ _a.sent();
492
+ return [2 /*return*/];
493
+ }
494
+ });
495
+ }); });
496
+ return [2 /*return*/];
497
+ });
498
+ });
499
+ };
500
+ // Targeting Engine
501
+ // check targeting
502
+ this.checkTargeting = function (visitorCode, campaignId, isFF) {
503
+ var _a, _b;
504
+ var targeting = true;
505
+ var xpConf = null;
506
+ // performing targeting
507
+ if (isFF) {
508
+ xpConf = (_a = _this.configurations) === null || _a === void 0 ? void 0 : _a.featureFlags[campaignId];
509
+ }
510
+ else {
511
+ xpConf = (_b = _this.configurations) === null || _b === void 0 ? void 0 : _b.experiments[campaignId];
512
+ }
513
+ if (xpConf != null) {
514
+ if (true == xpConf.forceTargeting) {
515
+ // assigning targeting to container
516
+ targeting = true;
517
+ }
518
+ else {
519
+ var targetingTree = void 0;
520
+ if (null != xpConf.targetingSegment) {
521
+ targetingTree = xpConf.targetingSegment.targetingTree;
522
+ }
523
+ // obtaining targeting checking result and assigning targeting to container
524
+ targeting = targetingEngine_1.TargetingEngine.checkTargetingTree(targetingTree, function (type) {
525
+ return _this.getConditionData(type, visitorCode, campaignId);
526
+ });
527
+ }
528
+ }
529
+ return targeting;
530
+ };
531
+ this.getConditionData = function (type, visitorCode, campaignId) {
532
+ switch (type) {
533
+ case constants_1.ConditionTypes.CUSTOM_DATUM:
534
+ return {
535
+ targetingData: _this.getTargetingData(visitorCode),
536
+ };
537
+ case constants_1.ConditionTypes.EXCLUSIVE_EXPERIMENT:
538
+ return {
539
+ currentExperimentId: campaignId,
540
+ variationStorage: _this.variationStorage.getMapVariationId(visitorCode),
541
+ };
542
+ case constants_1.ConditionTypes.TARGET_EXPERIMENT:
543
+ return {
544
+ variationStorage: _this.variationStorage.getMapVariationId(visitorCode),
545
+ };
546
+ default:
547
+ return null;
548
+ }
549
+ };
550
+ this.obtainVariationAssociatedData = function (variationId) {
551
+ var _a, _b, _c;
552
+ for (var vid in (_a = _this.configurations) === null || _a === void 0 ? void 0 : _a.experiments) {
553
+ var experiment = (_b = _this.configurations) === null || _b === void 0 ? void 0 : _b.experiments[vid];
554
+ if (experiment === null || experiment === void 0 ? void 0 : experiment.variationConfigurations[variationId]) {
555
+ return ((_c = experiment === null || experiment === void 0 ? void 0 : experiment.variationConfigurations[variationId].customJson) !== null && _c !== void 0 ? _c : {});
556
+ }
557
+ }
558
+ throw new variationConfigurationNotFound_1.default('KameleoonException.VariationConfigurationNotFound');
559
+ };
560
+ this.obtainFeatureVariable = function (featureIdOrName, variable) {
561
+ var _a, _b, _c, _d;
562
+ _this.checkFeatureKeyOrId(featureIdOrName);
563
+ for (var ffid in (_a = _this.configurations) === null || _a === void 0 ? void 0 : _a.featureFlags) {
564
+ var ff = (_b = _this.configurations) === null || _b === void 0 ? void 0 : _b.featureFlags[ffid];
565
+ if (ffid == featureIdOrName ||
566
+ (ff === null || ff === void 0 ? void 0 : ff.identificationKey) === featureIdOrName) {
567
+ for (var vid in ff === null || ff === void 0 ? void 0 : ff.variationConfigurations) {
568
+ if (vid !== '0') {
569
+ return _this._parseJsonValue((_d = (_c = ff === null || ff === void 0 ? void 0 : ff.variationConfigurations[vid]) === null || _c === void 0 ? void 0 : _c.customJson) === null || _d === void 0 ? void 0 : _d[variable]);
570
+ }
571
+ }
572
+ }
573
+ }
574
+ throw new featureConfigurationNotFound_1.default('KameleoonExceptinpmon.FeatureConfigurationNotFound');
575
+ };
576
+ this.retrieveDataFromRemoteSource = function (key) { return __awaiter(_this, void 0, void 0, function () {
577
+ var _this = this;
578
+ return __generator(this, function (_a) {
579
+ return [2 /*return*/, new Promise(function (resolve) {
580
+ kameleoonUtils_1.default.doRequest(_this.getAPIDataRequestURL(key), kameleoonUtils_1.HttpMethod.GET, null, function (response) {
581
+ resolve(JSON.parse(response));
582
+ });
583
+ })];
584
+ });
585
+ }); };
586
+ this._parseJsonValue = function (obj) {
587
+ if (obj == null) {
588
+ throw new featureConfigurationNotFound_1.default('KameleoonException.FeatureConfigurationNotFound');
589
+ }
590
+ else {
591
+ switch (obj.type) {
592
+ case 'Boolean':
593
+ return obj.value == 'True';
594
+ case 'Number':
595
+ return parseInt(obj.value);
596
+ case 'JSON':
597
+ return JSON.parse(obj.value);
598
+ default:
599
+ return obj.value;
600
+ }
601
+ }
602
+ };
603
+ this.saveConfiguration = function () { return __awaiter(_this, void 0, void 0, function () {
604
+ var data, e_1;
605
+ var _a, _b;
606
+ return __generator(this, function (_c) {
607
+ switch (_c.label) {
608
+ case 0:
609
+ if (!this.configurations) return [3 /*break*/, 6];
610
+ data = {
611
+ kameleoonTargetingData: this.targetingData,
612
+ kameleoonConfiguration: {
613
+ updateTime: this.configurations.updateTime,
614
+ experiments: (_a = this.configurations.configuration) === null || _a === void 0 ? void 0 : _a.experiments,
615
+ featureFlags: (_b = this.configurations.configuration) === null || _b === void 0 ? void 0 : _b.featureFlags,
616
+ configuration: this.configurations.settings,
617
+ },
618
+ };
619
+ _c.label = 1;
620
+ case 1:
621
+ _c.trys.push([1, 5, , 6]);
622
+ if (!(typeof document !== 'undefined')) return [3 /*break*/, 2];
623
+ localStorage.setItem('kameleoonJavaScriptClientData', JSON.stringify(data));
624
+ return [3 /*break*/, 4];
625
+ case 2:
626
+ if (!(typeof navigator !== 'undefined' &&
627
+ navigator.product === 'ReactNative')) return [3 /*break*/, 4];
628
+ return [4 /*yield*/, async_storage_1.default.setItem('kameleoonJavaScriptClientData', JSON.stringify(data))];
629
+ case 3:
630
+ _c.sent();
631
+ _c.label = 4;
632
+ case 4: return [3 /*break*/, 6];
633
+ case 5:
634
+ e_1 = _c.sent();
635
+ console.log(e_1);
636
+ return [3 /*break*/, 6];
637
+ case 6: return [2 /*return*/];
638
+ }
639
+ });
640
+ }); };
641
+ this.validateVisitorCode = function (visitorCode) {
642
+ if (visitorCode == null || visitorCode.length == 0) {
643
+ throw new visitorCodeNotValid_1.VisitorCodeNotValid('Visitor code is empty');
644
+ }
645
+ else if (visitorCode.length > KameleoonClient.VISITOR_CODE_MAX_LENGTH) {
646
+ throw new visitorCodeNotValid_1.VisitorCodeNotValid('Visitor code max length is ' +
647
+ KameleoonClient.VISITOR_CODE_MAX_LENGTH +
648
+ ' characters');
649
+ }
650
+ };
651
+ this.onUpdateConfiguration = function (handler) {
652
+ _this.handlerUpdateConfiguration = handler;
653
+ };
654
+ this.siteCode = siteCode;
655
+ if (configuration) {
656
+ if (configuration.visitor_data_maximum_size) {
657
+ this.visitorDataMaximumSize = configuration.visitor_data_maximum_size;
658
+ }
659
+ if (configuration.actions_configuration_refresh_interval) {
660
+ this.minutesBetweenConfigurationUpdate =
661
+ configuration.actions_configuration_refresh_interval;
662
+ }
663
+ if (configuration.environment) {
664
+ this.environment = configuration.environment;
665
+ }
666
+ }
667
+ this.targetingDataNumberEntriesAuthorized =
668
+ (this.visitorDataMaximumSize * 1000000) /
669
+ constants_1.TARGETING_DATA_MAXIMUM_SIZE_BYTES;
670
+ this.updateCampaignConfiguration();
671
+ setInterval(this.emptyTargetingData, constants_1.DEFAULT_MILLISECONDS_BETWEEN_TARGETING_DATA_UPDATE);
672
+ }
673
+ KameleoonClient.prototype.checkSiteEnabled = function (experimentOrFeatureFlag) {
674
+ if (experimentOrFeatureFlag != null &&
675
+ !experimentOrFeatureFlag.siteEnabled) {
676
+ throw new siteCodeDisabled_1.SiteCodeDisabled(this.siteCode);
677
+ }
678
+ };
679
+ KameleoonClient.prototype.checkFeatureKeyOrId = function (featureIdOrName) {
680
+ if (typeof featureIdOrName === 'string') {
681
+ console.log('Please use `featureIdOrName` with type of `string`. This is necessary to support multi-environment feature. Supporting of `number` type will be removed in next releases');
682
+ }
683
+ };
684
+ KameleoonClient.prototype.getAndClearUnsentData = function (visitorCode) {
685
+ var body = '';
686
+ this.getUnsentData(visitorCode).forEach(function (element) {
687
+ body += element.obtainFullPostTextLine() + '\n';
688
+ });
689
+ this.emptyUnsentData(visitorCode);
690
+ return body;
691
+ };
692
+ KameleoonClient.prototype.manageConfiguraitonUpdate = function (subsciptionRequired) {
693
+ var _this = this;
694
+ if (subsciptionRequired && !this.realTimeConfigurationService) {
695
+ this.realTimeConfigurationService = new realTimeConfigurationService_1.RealTimeConfigurationService(this.getEventsRequestURL(this.siteCode), function (event) { return __awaiter(_this, void 0, void 0, function () {
696
+ return __generator(this, function (_a) {
697
+ switch (_a.label) {
698
+ case 0: return [4 /*yield*/, this.updateCampaignConfiguration(event.ts)];
699
+ case 1:
700
+ _a.sent();
701
+ return [2 /*return*/];
702
+ }
703
+ });
704
+ }); });
705
+ }
706
+ else if (!subsciptionRequired) {
707
+ if (this.realTimeConfigurationService) {
708
+ this.realTimeConfigurationService.disconnect();
709
+ this.realTimeConfigurationService = null;
710
+ }
711
+ setTimeout(this.updateCampaignConfiguration, this.minutesBetweenConfigurationUpdate * constants_1.Milliseconds.Minute);
712
+ }
713
+ };
714
+ KameleoonClient.prototype.fireUpdateConfigurationHandler = function (fire) {
715
+ fire &&
716
+ this.handlerUpdateConfiguration &&
717
+ this.handlerUpdateConfiguration();
718
+ };
719
+ KameleoonClient.VISITOR_CODE_MAX_LENGTH = 255;
720
+ return KameleoonClient;
721
+ }());
722
+ exports.KameleoonClient = KameleoonClient;
723
+ var KameleoonException = {
724
+ ExperimentConfigurationNotFound: experimentConfigurationNotFound_1.default,
725
+ FeatureConfigurationNotFound: featureConfigurationNotFound_1.default,
726
+ VariationConfigurationNotFound: variationConfigurationNotFound_1.default,
727
+ NotTargeted: notTargeted_1.default,
728
+ NotActivated: notActivated_1.default,
729
+ CredentialsNotFound: credentialsNotFound_1.default,
730
+ };
731
+ exports.KameleoonException = KameleoonException;
732
+ //# sourceMappingURL=kameleoonClient.js.map