@splitsoftware/splitio-commons 1.2.1-rc.4 → 1.2.1-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/cjs/listeners/browser.js +14 -10
  2. package/cjs/logger/constants.js +5 -3
  3. package/cjs/logger/messages/error.js +2 -1
  4. package/cjs/logger/messages/info.js +1 -0
  5. package/cjs/sdkClient/client.js +10 -4
  6. package/cjs/sdkFactory/index.js +5 -4
  7. package/cjs/sdkFactory/userConsentProps.js +34 -0
  8. package/cjs/storages/KeyBuilderCS.js +11 -1
  9. package/cjs/storages/inLocalStorage/MySegmentsCacheInLocal.js +23 -3
  10. package/cjs/sync/submitters/eventsSyncTask.js +6 -2
  11. package/cjs/sync/submitters/impressionsSyncTask.js +6 -2
  12. package/cjs/sync/syncManagerOnline.js +11 -7
  13. package/cjs/utils/consent.js +10 -0
  14. package/cjs/utils/constants/index.js +5 -1
  15. package/cjs/utils/settingsValidation/consent.js +16 -0
  16. package/cjs/utils/settingsValidation/impressionsMode.js +6 -6
  17. package/cjs/utils/settingsValidation/index.js +4 -1
  18. package/esm/listeners/browser.js +14 -10
  19. package/esm/logger/constants.js +3 -1
  20. package/esm/logger/messages/error.js +2 -1
  21. package/esm/logger/messages/info.js +1 -0
  22. package/esm/sdkClient/client.js +11 -5
  23. package/esm/sdkFactory/index.js +5 -4
  24. package/esm/sdkFactory/userConsentProps.js +30 -0
  25. package/esm/storages/KeyBuilderCS.js +11 -1
  26. package/esm/storages/inLocalStorage/MySegmentsCacheInLocal.js +23 -3
  27. package/esm/sync/submitters/eventsSyncTask.js +6 -2
  28. package/esm/sync/submitters/impressionsSyncTask.js +6 -2
  29. package/esm/sync/syncManagerOnline.js +11 -7
  30. package/esm/utils/consent.js +6 -0
  31. package/esm/utils/constants/index.js +4 -0
  32. package/esm/utils/settingsValidation/consent.js +12 -0
  33. package/esm/utils/settingsValidation/impressionsMode.js +7 -7
  34. package/esm/utils/settingsValidation/index.js +4 -1
  35. package/package.json +1 -1
  36. package/src/listeners/browser.ts +13 -9
  37. package/src/logger/constants.ts +3 -1
  38. package/src/logger/messages/error.ts +2 -1
  39. package/src/logger/messages/info.ts +1 -0
  40. package/src/sdkClient/client.ts +7 -5
  41. package/src/sdkFactory/index.ts +5 -4
  42. package/src/sdkFactory/types.ts +2 -0
  43. package/src/sdkFactory/userConsentProps.ts +37 -0
  44. package/src/storages/KeyBuilderCS.ts +13 -1
  45. package/src/storages/inLocalStorage/MySegmentsCacheInLocal.ts +23 -3
  46. package/src/sync/submitters/eventsSyncTask.ts +6 -2
  47. package/src/sync/submitters/impressionsSyncTask.ts +6 -2
  48. package/src/sync/syncManagerOnline.ts +13 -7
  49. package/src/sync/types.ts +4 -1
  50. package/src/types.ts +6 -0
  51. package/src/utils/consent.ts +8 -0
  52. package/src/utils/constants/index.ts +5 -0
  53. package/src/utils/settingsValidation/consent.ts +14 -0
  54. package/src/utils/settingsValidation/impressionsMode.ts +7 -8
  55. package/src/utils/settingsValidation/index.ts +5 -1
  56. package/src/utils/settingsValidation/types.ts +2 -0
  57. package/types/logger/constants.d.ts +3 -1
  58. package/types/sdkFactory/types.d.ts +1 -0
  59. package/types/sdkFactory/userConsentProps.d.ts +6 -0
  60. package/types/storages/KeyBuilderCS.d.ts +2 -0
  61. package/types/sync/types.d.ts +3 -0
  62. package/types/types.d.ts +6 -0
  63. package/types/utils/consent.d.ts +2 -0
  64. package/types/utils/constants/index.d.ts +3 -0
  65. package/types/utils/settingsValidation/consent.d.ts +5 -0
  66. package/types/utils/settingsValidation/impressionsMode.d.ts +1 -1
  67. package/types/utils/settingsValidation/types.d.ts +2 -0
  68. package/types/utils/settingsValidation/userConsent.d.ts +5 -0
@@ -8,11 +8,12 @@ import { createLoggerAPI } from '../logger/sdkLogger';
8
8
  import { NEW_FACTORY, RETRIEVE_MANAGER } from '../logger/constants';
9
9
  import { metadataBuilder } from '../storages/metadataBuilder';
10
10
  import { SDK_SPLITS_ARRIVED, SDK_SEGMENTS_ARRIVED } from '../readiness/constants';
11
+ import { objectAssign } from '../utils/lang/objectAssign';
11
12
  /**
12
13
  * Modular SDK factory
13
14
  */
14
15
  export function sdkFactory(params) {
15
- var settings = params.settings, platform = params.platform, storageFactory = params.storageFactory, splitApiFactory = params.splitApiFactory, syncManagerFactory = params.syncManagerFactory, SignalListener = params.SignalListener, impressionsObserverFactory = params.impressionsObserverFactory, impressionListener = params.impressionListener, integrationsManagerFactory = params.integrationsManagerFactory, sdkManagerFactory = params.sdkManagerFactory, sdkClientMethodFactory = params.sdkClientMethodFactory;
16
+ var settings = params.settings, platform = params.platform, storageFactory = params.storageFactory, splitApiFactory = params.splitApiFactory, extraProps = params.extraProps, syncManagerFactory = params.syncManagerFactory, SignalListener = params.SignalListener, impressionsObserverFactory = params.impressionsObserverFactory, impressionListener = params.impressionListener, integrationsManagerFactory = params.integrationsManagerFactory, sdkManagerFactory = params.sdkManagerFactory, sdkClientMethodFactory = params.sdkClientMethodFactory;
16
17
  var log = settings.log;
17
18
  // @TODO handle non-recoverable errors: not start sync, mark the SDK as destroyed, etc.
18
19
  // We will just log and allow for the SDK to end up throwing an SDK_TIMEOUT event for devs to handle.
@@ -65,11 +66,11 @@ export function sdkFactory(params) {
65
66
  syncManager && syncManager.start();
66
67
  signalListener && signalListener.start();
67
68
  log.info(NEW_FACTORY);
68
- return {
69
+ // @ts-ignore
70
+ return objectAssign({
69
71
  // Split evaluation and event tracking engine
70
72
  client: clientMethod,
71
73
  // Manager API to explore available information
72
- // @ts-ignore
73
74
  manager: function () {
74
75
  log.debug(RETRIEVE_MANAGER);
75
76
  return managerInstance;
@@ -77,5 +78,5 @@ export function sdkFactory(params) {
77
78
  // Logger wrapper API
78
79
  Logger: createLoggerAPI(settings.log),
79
80
  settings: settings,
80
- };
81
+ }, extraProps && extraProps(settings, syncManager));
81
82
  }
@@ -0,0 +1,30 @@
1
+ import { ERROR_NOT_BOOLEAN, USER_CONSENT_UPDATED } from '../logger/constants';
2
+ import { CONSENT_GRANTED, CONSENT_DECLINED } from '../utils/constants';
3
+ // Extend client-side factory instances with user consent getter/setter
4
+ export function userConsentProps(settings, syncManager) {
5
+ var log = settings.log;
6
+ return {
7
+ setUserConsent: function (consent) {
8
+ var _a, _b;
9
+ // validate input param
10
+ if (typeof consent !== 'boolean') {
11
+ log.error(ERROR_NOT_BOOLEAN, ['setUserConsent']);
12
+ return false;
13
+ }
14
+ var newConsentStatus = consent ? CONSENT_GRANTED : CONSENT_DECLINED;
15
+ if (settings.userConsent !== newConsentStatus) {
16
+ // resume/pause submitters
17
+ if (consent)
18
+ (_a = syncManager === null || syncManager === void 0 ? void 0 : syncManager.submitter) === null || _a === void 0 ? void 0 : _a.start();
19
+ else
20
+ (_b = syncManager === null || syncManager === void 0 ? void 0 : syncManager.submitter) === null || _b === void 0 ? void 0 : _b.stop();
21
+ log.info(USER_CONSENT_UPDATED, [settings.userConsent, newConsentStatus]); // @ts-ignore, modify readonly prop
22
+ settings.userConsent = newConsentStatus;
23
+ }
24
+ return true;
25
+ },
26
+ getUserConsent: function () {
27
+ return settings.userConsent;
28
+ }
29
+ };
30
+ }
@@ -13,9 +13,19 @@ var KeyBuilderCS = /** @class */ (function (_super) {
13
13
  * @override
14
14
  */
15
15
  KeyBuilderCS.prototype.buildSegmentNameKey = function (segmentName) {
16
- return this.matchingKey + "." + this.prefix + ".segment." + segmentName;
16
+ return this.prefix + "." + this.matchingKey + ".segment." + segmentName;
17
17
  };
18
18
  KeyBuilderCS.prototype.extractSegmentName = function (builtSegmentKeyName) {
19
+ var prefix = this.prefix + "." + this.matchingKey + ".segment.";
20
+ if (startsWith(builtSegmentKeyName, prefix))
21
+ return builtSegmentKeyName.substr(prefix.length);
22
+ };
23
+ // @BREAKING: The key used to start with the matching key instead of the prefix, this was changed on version 10.17.3
24
+ KeyBuilderCS.prototype.buildOldSegmentNameKey = function (segmentName) {
25
+ return this.matchingKey + "." + this.prefix + ".segment." + segmentName;
26
+ };
27
+ // @BREAKING: The key used to start with the matching key instead of the prefix, this was changed on version 10.17.3
28
+ KeyBuilderCS.prototype.extractOldSegmentKey = function (builtSegmentKeyName) {
19
29
  var prefix = this.matchingKey + "." + this.prefix + ".segment.";
20
30
  if (startsWith(builtSegmentKeyName, prefix))
21
31
  return builtSegmentKeyName.substr(prefix.length);
@@ -57,9 +57,29 @@ var MySegmentsCacheInLocal = /** @class */ (function (_super) {
57
57
  var index;
58
58
  // Scan current values from localStorage
59
59
  var storedSegmentNames = Object.keys(localStorage).reduce(function (accum, key) {
60
- var name = _this.keys.extractSegmentName(key);
61
- if (name)
62
- accum.push(name);
60
+ var segmentName = _this.keys.extractSegmentName(key);
61
+ if (segmentName) {
62
+ accum.push(segmentName);
63
+ }
64
+ else {
65
+ // @BREAKING: This is only to clean up "old" keys. Remove this whole else code block.
66
+ segmentName = _this.keys.extractOldSegmentKey(key);
67
+ if (segmentName) { // this was an old segment key, let's clean up.
68
+ var newSegmentKey = _this.keys.buildSegmentNameKey(segmentName);
69
+ try {
70
+ // If the new format key is not there, create it.
71
+ if (!localStorage.getItem(newSegmentKey) && names.indexOf(segmentName) > -1) {
72
+ localStorage.setItem(newSegmentKey, DEFINED);
73
+ // we are migrating a segment, let's track it.
74
+ accum.push(segmentName);
75
+ }
76
+ localStorage.removeItem(key); // we migrated the current key, let's delete it.
77
+ }
78
+ catch (e) {
79
+ _this.log.error(e);
80
+ }
81
+ }
82
+ }
63
83
  return accum;
64
84
  }, []);
65
85
  // Extreme fast => everything is empty
@@ -22,8 +22,12 @@ export function eventsSyncTaskFactory(log, postEventsBulk, eventsCache, eventsPu
22
22
  }
23
23
  // register events submitter to be executed when events cache is full
24
24
  eventsCache.setOnFullQueueCb(function () {
25
- log.info(SUBMITTERS_PUSH_FULL_QUEUE, [DATA_NAME]);
26
- syncTask.execute();
25
+ if (syncTask.isRunning()) {
26
+ log.info(SUBMITTERS_PUSH_FULL_QUEUE, [DATA_NAME]);
27
+ syncTask.execute();
28
+ }
29
+ // If submitter is stopped (e.g., user consent declined or unknown, or app state offline), we don't send the data.
30
+ // Data will be sent when submitter is resumed.
27
31
  });
28
32
  return syncTask;
29
33
  }
@@ -37,8 +37,12 @@ export function impressionsSyncTaskFactory(log, postTestImpressionsBulk, impress
37
37
  var syncTask = submitterSyncTaskFactory(log, postTestImpressionsBulk, impressionsCache, impressionsRefreshRate, DATA_NAME, latencyTracker, fromImpressionsCollector.bind(undefined, sendLabels), 1);
38
38
  // register impressions submitter to be executed when impressions cache is full
39
39
  impressionsCache.setOnFullQueueCb(function () {
40
- log.info(SUBMITTERS_PUSH_FULL_QUEUE, [DATA_NAME]);
41
- syncTask.execute();
40
+ if (syncTask.isRunning()) {
41
+ log.info(SUBMITTERS_PUSH_FULL_QUEUE, [DATA_NAME]);
42
+ syncTask.execute();
43
+ }
44
+ // If submitter is stopped (e.g., user consent declined or unknown, or app state offline), we don't send the data.
45
+ // Data will be sent when submitter is resumed.
42
46
  });
43
47
  return syncTask;
44
48
  }
@@ -1,6 +1,7 @@
1
1
  import { submitterManagerFactory } from './submitters/submitterManager';
2
2
  import { PUSH_SUBSYSTEM_UP, PUSH_SUBSYSTEM_DOWN } from './streaming/constants';
3
3
  import { SYNC_START_POLLING, SYNC_CONTINUE_POLLING, SYNC_STOP_POLLING } from '../logger/constants';
4
+ import { isConsentGranted } from '../utils/consent';
4
5
  /**
5
6
  * Online SyncManager factory.
6
7
  * Can be used for server-side API, and client-side API with or without multiple clients.
@@ -14,7 +15,7 @@ export function syncManagerOnlineFactory(pollingManagerFactory, pushManagerFacto
14
15
  * SyncManager factory for modular SDK
15
16
  */
16
17
  return function (params) {
17
- var _a = params.settings, log = _a.log, streamingEnabled = _a.streamingEnabled;
18
+ var settings = params.settings, _a = params.settings, log = _a.log, streamingEnabled = _a.streamingEnabled;
18
19
  /** Polling Manager */
19
20
  var pollingManager = pollingManagerFactory && pollingManagerFactory(params);
20
21
  /** Push Manager */
@@ -49,11 +50,16 @@ export function syncManagerOnlineFactory(pollingManagerFactory, pushManagerFacto
49
50
  var running = false; // flag that indicates whether the syncManager has been started (true) or stopped (false)
50
51
  var startFirstTime = true; // flag to distinguish calling the `start` method for the first time, to support pausing and resuming the synchronization
51
52
  return {
53
+ // Exposed for fine-grained control of synchronization.
54
+ // E.g.: user consent, app state changes (Page hide, Foreground/Background, Online/Offline).
55
+ pollingManager: pollingManager,
52
56
  pushManager: pushManager,
57
+ submitter: submitter,
53
58
  /**
54
59
  * Method used to start the syncManager for the first time, or resume it after being stopped.
55
60
  */
56
61
  start: function () {
62
+ running = true;
57
63
  // start syncing splits and segments
58
64
  if (pollingManager) {
59
65
  if (pushManager) {
@@ -69,29 +75,27 @@ export function syncManagerOnlineFactory(pollingManagerFactory, pushManagerFacto
69
75
  }
70
76
  }
71
77
  // start periodic data recording (events, impressions, telemetry).
72
- if (submitter)
78
+ if (isConsentGranted(settings))
73
79
  submitter.start();
74
- running = true;
75
80
  },
76
81
  /**
77
82
  * Method used to stop/pause the syncManager.
78
83
  */
79
84
  stop: function () {
85
+ running = false;
80
86
  // stop syncing
81
87
  if (pushManager)
82
88
  pushManager.stop();
83
89
  if (pollingManager && pollingManager.isRunning())
84
90
  pollingManager.stop();
85
91
  // stop periodic data recording (events, impressions, telemetry).
86
- if (submitter)
87
- submitter.stop();
88
- running = false;
92
+ submitter.stop();
89
93
  },
90
94
  isRunning: function () {
91
95
  return running;
92
96
  },
93
97
  flush: function () {
94
- if (submitter)
98
+ if (isConsentGranted(settings))
95
99
  return submitter.execute();
96
100
  else
97
101
  return Promise.resolve();
@@ -0,0 +1,6 @@
1
+ import { CONSENT_GRANTED } from './constants';
2
+ export function isConsentGranted(settings) {
3
+ var userConsent = settings.userConsent;
4
+ // undefined userConsent is handled as granted (default)
5
+ return !userConsent || userConsent === CONSENT_GRANTED;
6
+ }
@@ -24,3 +24,7 @@ export var STORAGE_MEMORY = 'MEMORY';
24
24
  export var STORAGE_LOCALSTORAGE = 'LOCALSTORAGE';
25
25
  export var STORAGE_REDIS = 'REDIS';
26
26
  export var STORAGE_PLUGGABLE = 'PLUGGABLE';
27
+ // User consent
28
+ export var CONSENT_GRANTED = 'GRANTED'; // The user has granted consent for tracking events and impressions
29
+ export var CONSENT_DECLINED = 'DECLINED'; // The user has declined consent for tracking events and impressions
30
+ export var CONSENT_UNKNOWN = 'UNKNOWN'; // The user has neither granted nor declined consent for tracking events and impressions
@@ -0,0 +1,12 @@
1
+ import { ERROR_INVALID_CONFIG_PARAM } from '../../logger/constants';
2
+ import { CONSENT_DECLINED, CONSENT_GRANTED, CONSENT_UNKNOWN } from '../constants';
3
+ var userConsentValues = [CONSENT_DECLINED, CONSENT_GRANTED, CONSENT_UNKNOWN];
4
+ export function validateConsent(_a) {
5
+ var userConsent = _a.userConsent, log = _a.log;
6
+ if (typeof userConsent === 'string')
7
+ userConsent = userConsent.toUpperCase();
8
+ if (userConsentValues.indexOf(userConsent) > -1)
9
+ return userConsent;
10
+ log.error(ERROR_INVALID_CONFIG_PARAM, ['userConsent', userConsentValues, CONSENT_GRANTED]);
11
+ return CONSENT_GRANTED;
12
+ }
@@ -1,10 +1,10 @@
1
- import { ERROR_INVALID_IMPRESSIONS_MODE } from '../../logger/constants';
1
+ import { ERROR_INVALID_CONFIG_PARAM } from '../../logger/constants';
2
2
  import { DEBUG, OPTIMIZED } from '../constants';
3
3
  export function validImpressionsMode(log, impressionsMode) {
4
- impressionsMode = impressionsMode.toUpperCase();
5
- if ([DEBUG, OPTIMIZED].indexOf(impressionsMode) === -1) {
6
- log.error(ERROR_INVALID_IMPRESSIONS_MODE, [[DEBUG, OPTIMIZED], OPTIMIZED]);
7
- impressionsMode = OPTIMIZED;
8
- }
9
- return impressionsMode;
4
+ if (typeof impressionsMode === 'string')
5
+ impressionsMode = impressionsMode.toUpperCase();
6
+ if ([DEBUG, OPTIMIZED].indexOf(impressionsMode) > -1)
7
+ return impressionsMode;
8
+ log.error(ERROR_INVALID_CONFIG_PARAM, ['impressionsMode', [DEBUG, OPTIMIZED], OPTIMIZED]);
9
+ return OPTIMIZED;
10
10
  }
@@ -80,7 +80,7 @@ function fromSecondsToMillis(n) {
80
80
  * @param validationParams defaults and fields validators used to validate and creates a settings object from a given config
81
81
  */
82
82
  export function settingsValidation(config, validationParams) {
83
- var defaults = validationParams.defaults, runtime = validationParams.runtime, storage = validationParams.storage, integrations = validationParams.integrations, logger = validationParams.logger, localhost = validationParams.localhost;
83
+ var defaults = validationParams.defaults, runtime = validationParams.runtime, storage = validationParams.storage, integrations = validationParams.integrations, logger = validationParams.logger, localhost = validationParams.localhost, consent = validationParams.consent;
84
84
  // creates a settings object merging base, defaults and config objects.
85
85
  var withDefaults = merge({}, base, defaults, config);
86
86
  // ensure a valid logger.
@@ -133,5 +133,8 @@ export function settingsValidation(config, validationParams) {
133
133
  withDefaults.sync.__splitFiltersValidation = splitFiltersValidation;
134
134
  // ensure a valid impressionsMode
135
135
  withDefaults.sync.impressionsMode = validImpressionsMode(log, withDefaults.sync.impressionsMode);
136
+ // ensure a valid user consent value
137
+ // @ts-ignore, modify readonly prop
138
+ withDefaults.userConsent = consent(withDefaults);
136
139
  return withDefaults;
137
140
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@splitsoftware/splitio-commons",
3
- "version": "1.2.1-rc.4",
3
+ "version": "1.2.1-rc.5",
4
4
  "description": "Split Javascript SDK common components",
5
5
  "main": "cjs/index.js",
6
6
  "module": "esm/index.js",
@@ -11,6 +11,7 @@ import { OPTIMIZED, DEBUG } from '../utils/constants';
11
11
  import { objectAssign } from '../utils/lang/objectAssign';
12
12
  import { CLEANUP_REGISTERING, CLEANUP_DEREGISTERING } from '../logger/constants';
13
13
  import { ISyncManager } from '../sync/types';
14
+ import { isConsentGranted } from '../utils/consent';
14
15
 
15
16
  // 'unload' event is used instead of 'beforeunload', since 'unload' is not a cancelable event, so no other listeners can stop the event from occurring.
16
17
  const UNLOAD_DOM_EVENT = 'unload';
@@ -65,15 +66,18 @@ export class BrowserSignalListener implements ISignalListener {
65
66
  flushData() {
66
67
  if (!this.syncManager) return; // In consumer mode there is not sync manager and data to flush
67
68
 
68
- const eventsUrl = this.settings.urls.events;
69
- const extraMetadata = {
70
- // sim stands for Sync/Split Impressions Mode
71
- sim: this.settings.sync.impressionsMode === OPTIMIZED ? OPTIMIZED : DEBUG
72
- };
69
+ // Flush data if there is user consent
70
+ if (isConsentGranted(this.settings)) {
71
+ const eventsUrl = this.settings.urls.events;
72
+ const extraMetadata = {
73
+ // sim stands for Sync/Split Impressions Mode
74
+ sim: this.settings.sync.impressionsMode === OPTIMIZED ? OPTIMIZED : DEBUG
75
+ };
73
76
 
74
- this._flushData(eventsUrl + '/testImpressions/beacon', this.storage.impressions, this.serviceApi.postTestImpressionsBulk, this.fromImpressionsCollector, extraMetadata);
75
- this._flushData(eventsUrl + '/events/beacon', this.storage.events, this.serviceApi.postEventsBulk);
76
- if (this.storage.impressionCounts) this._flushData(eventsUrl + '/testImpressions/count/beacon', this.storage.impressionCounts, this.serviceApi.postTestImpressionsCount, fromImpressionCountsCollector);
77
+ this._flushData(eventsUrl + '/testImpressions/beacon', this.storage.impressions, this.serviceApi.postTestImpressionsBulk, this.fromImpressionsCollector, extraMetadata);
78
+ this._flushData(eventsUrl + '/events/beacon', this.storage.events, this.serviceApi.postEventsBulk);
79
+ if (this.storage.impressionCounts) this._flushData(eventsUrl + '/testImpressions/count/beacon', this.storage.impressionCounts, this.serviceApi.postTestImpressionsCount, fromImpressionCountsCollector);
80
+ }
77
81
 
78
82
  // Close streaming connection
79
83
  if (this.syncManager.pushManager) this.syncManager.pushManager.stop();
@@ -84,7 +88,7 @@ export class BrowserSignalListener implements ISignalListener {
84
88
  if (!cache.isEmpty()) {
85
89
  const dataPayload = fromCacheToPayload ? fromCacheToPayload(cache.state()) : cache.state();
86
90
  if (!this._sendBeacon(url, dataPayload, extraMetadata)) {
87
- postService(JSON.stringify(dataPayload)).catch(() => { }); // no-op just to catch a possible exceptions
91
+ postService(JSON.stringify(dataPayload)).catch(() => { }); // no-op just to catch a possible exception
88
92
  }
89
93
  cache.clear();
90
94
  }
@@ -68,6 +68,7 @@ export const SYNC_CONTINUE_POLLING = 118;
68
68
  export const SYNC_STOP_POLLING = 119;
69
69
  export const EVENTS_TRACKER_SUCCESS = 120;
70
70
  export const IMPRESSIONS_TRACKER_SUCCESS = 121;
71
+ export const USER_CONSENT_UPDATED = 122;
71
72
 
72
73
  export const ENGINE_VALUE_INVALID = 200;
73
74
  export const ENGINE_VALUE_NO_ATTRIBUTES = 201;
@@ -115,10 +116,11 @@ export const ERROR_INVALID_KEY_OBJECT = 317;
115
116
  export const ERROR_INVALID = 318;
116
117
  export const ERROR_EMPTY = 319;
117
118
  export const ERROR_EMPTY_ARRAY = 320;
118
- export const ERROR_INVALID_IMPRESSIONS_MODE = 321;
119
+ export const ERROR_INVALID_CONFIG_PARAM = 321;
119
120
  export const ERROR_HTTP = 322;
120
121
  export const ERROR_LOCALHOST_MODULE_REQUIRED = 323;
121
122
  export const ERROR_STORAGE_INVALID = 324;
123
+ export const ERROR_NOT_BOOLEAN = 325;
122
124
 
123
125
  // Log prefixes (a.k.a. tags or categories)
124
126
  export const LOG_PREFIX_SETTINGS = 'settings';
@@ -28,8 +28,9 @@ export const codesError: [number, string][] = [
28
28
  [c.ERROR_INVALID, '%s: you passed an invalid %s. It must be a non-empty string.'],
29
29
  [c.ERROR_EMPTY, '%s: you passed an empty %s. It must be a non-empty string.'],
30
30
  [c.ERROR_EMPTY_ARRAY, '%s: %s must be a non-empty array.'],
31
+ [c.ERROR_NOT_BOOLEAN, '%s: you must provide a boolean param.'],
31
32
  // initialization / settings validation
32
- [c.ERROR_INVALID_IMPRESSIONS_MODE, c.LOG_PREFIX_SETTINGS + ': you passed an invalid "impressionsMode". It should be one of the following values: %s. Defaulting to "%s" mode.'],
33
+ [c.ERROR_INVALID_CONFIG_PARAM, c.LOG_PREFIX_SETTINGS + ': you passed an invalid "%s" config param. It should be one of the following values: %s. Defaulting to "%s".'],
33
34
  [c.ERROR_LOCALHOST_MODULE_REQUIRED, c.LOG_PREFIX_SETTINGS + ': an invalid value was received for "sync.localhostMode" config. A valid entity should be provided for localhost mode.'],
34
35
  [c.ERROR_STORAGE_INVALID, c.LOG_PREFIX_SETTINGS+': The provided storage is invalid.%s Fallbacking into default MEMORY storage'],
35
36
  ];
@@ -14,6 +14,7 @@ export const codesInfo: [number, string][] = codesWarn.concat([
14
14
  [c.NEW_FACTORY, ' New Split SDK instance created.'],
15
15
  [c.EVENTS_TRACKER_SUCCESS, c.LOG_PREFIX_EVENTS_TRACKER + 'Successfully queued %s'],
16
16
  [c.IMPRESSIONS_TRACKER_SUCCESS, c.LOG_PREFIX_IMPRESSIONS_TRACKER + 'Successfully stored %s impression(s).'],
17
+ [c.USER_CONSENT_UPDATED, 'User consent changed from %s to %s.'],
17
18
 
18
19
  // synchronizer
19
20
  [c.POLLING_SMART_PAUSING, c.LOG_PREFIX_SYNC_POLLING + 'Turning segments data polling %s.'],
@@ -4,7 +4,7 @@ import { getMatching, getBucketing } from '../utils/key';
4
4
  import { validateSplitExistance } from '../utils/inputValidation/splitExistance';
5
5
  import { validateTrafficTypeExistance } from '../utils/inputValidation/trafficTypeExistance';
6
6
  import { SDK_NOT_READY } from '../utils/labels';
7
- import { CONTROL } from '../utils/constants';
7
+ import { CONSENT_DECLINED, CONTROL } from '../utils/constants';
8
8
  import { IClientFactoryParams } from './types';
9
9
  import { IEvaluationResult } from '../evaluator/types';
10
10
  import { SplitIO, ImpressionDTO } from '../types';
@@ -16,13 +16,14 @@ import { IMPRESSION, IMPRESSION_QUEUEING } from '../logger/constants';
16
16
  */
17
17
  // @TODO missing time tracking to collect telemetry
18
18
  export function clientFactory(params: IClientFactoryParams): SplitIO.IClient | SplitIO.IAsyncClient {
19
- const { sdkReadinessManager: { readinessManager }, storage, settings: { log, mode }, impressionsTracker, eventTracker } = params;
19
+ const { sdkReadinessManager: { readinessManager }, storage, settings, impressionsTracker, eventTracker } = params;
20
+ const { log, mode } = settings;
20
21
 
21
22
  function getTreatment(key: SplitIO.SplitKey, splitName: string, attributes: SplitIO.Attributes | undefined, withConfig = false) {
22
23
  const wrapUp = (evaluationResult: IEvaluationResult) => {
23
24
  const queue: ImpressionDTO[] = [];
24
25
  const treatment = processEvaluation(evaluationResult, splitName, key, attributes, withConfig, `getTreatment${withConfig ? 'withConfig' : ''}`, queue);
25
- impressionsTracker.track(queue, attributes);
26
+ if (settings.userConsent !== CONSENT_DECLINED) impressionsTracker.track(queue, attributes);
26
27
  return treatment;
27
28
  };
28
29
 
@@ -42,7 +43,7 @@ export function clientFactory(params: IClientFactoryParams): SplitIO.IClient | S
42
43
  Object.keys(evaluationResults).forEach(splitName => {
43
44
  treatments[splitName] = processEvaluation(evaluationResults[splitName], splitName, key, attributes, withConfig, `getTreatments${withConfig ? 'withConfig' : ''}`, queue);
44
45
  });
45
- impressionsTracker.track(queue, attributes);
46
+ if (settings.userConsent !== CONSENT_DECLINED) impressionsTracker.track(queue, attributes);
46
47
  return treatments;
47
48
  };
48
49
 
@@ -115,7 +116,8 @@ export function clientFactory(params: IClientFactoryParams): SplitIO.IClient | S
115
116
  // This may be async but we only warn, we don't actually care if it is valid or not in terms of queueing the event.
116
117
  validateTrafficTypeExistance(log, readinessManager, storage.splits, mode, trafficTypeName, 'track');
117
118
 
118
- return eventTracker.track(eventData, size);
119
+ if (settings.userConsent !== CONSENT_DECLINED) return eventTracker.track(eventData, size);
120
+ else return false;
119
121
  }
120
122
 
121
123
  return {
@@ -12,13 +12,14 @@ import { createLoggerAPI } from '../logger/sdkLogger';
12
12
  import { NEW_FACTORY, RETRIEVE_MANAGER } from '../logger/constants';
13
13
  import { metadataBuilder } from '../storages/metadataBuilder';
14
14
  import { SDK_SPLITS_ARRIVED, SDK_SEGMENTS_ARRIVED } from '../readiness/constants';
15
+ import { objectAssign } from '../utils/lang/objectAssign';
15
16
 
16
17
  /**
17
18
  * Modular SDK factory
18
19
  */
19
20
  export function sdkFactory(params: ISdkFactoryParams): SplitIO.ICsSDK | SplitIO.ISDK | SplitIO.IAsyncSDK {
20
21
 
21
- const { settings, platform, storageFactory, splitApiFactory,
22
+ const { settings, platform, storageFactory, splitApiFactory, extraProps,
22
23
  syncManagerFactory, SignalListener, impressionsObserverFactory, impressionListener,
23
24
  integrationsManagerFactory, sdkManagerFactory, sdkClientMethodFactory } = params;
24
25
  const log = settings.log;
@@ -88,12 +89,12 @@ export function sdkFactory(params: ISdkFactoryParams): SplitIO.ICsSDK | SplitIO.
88
89
 
89
90
  log.info(NEW_FACTORY);
90
91
 
91
- return {
92
+ // @ts-ignore
93
+ return objectAssign({
92
94
  // Split evaluation and event tracking engine
93
95
  client: clientMethod,
94
96
 
95
97
  // Manager API to explore available information
96
- // @ts-ignore
97
98
  manager() {
98
99
  log.debug(RETRIEVE_MANAGER);
99
100
  return managerInstance;
@@ -103,5 +104,5 @@ export function sdkFactory(params: ISdkFactoryParams): SplitIO.ICsSDK | SplitIO.
103
104
  Logger: createLoggerAPI(settings.log),
104
105
 
105
106
  settings,
106
- };
107
+ }, extraProps && extraProps(settings, syncManager));
107
108
  }
@@ -70,4 +70,6 @@ export interface ISdkFactoryParams {
70
70
  // Impression observer factory. If provided, will be used for impressions dedupe
71
71
  impressionsObserverFactory?: () => IImpressionObserver
72
72
 
73
+ // Optional function to assign additional properties to the factory instance
74
+ extraProps?: (settings: ISettings, syncManager?: ISyncManager) => object
73
75
  }
@@ -0,0 +1,37 @@
1
+ import { ERROR_NOT_BOOLEAN, USER_CONSENT_UPDATED } from '../logger/constants';
2
+ import { ISyncManager } from '../sync/types';
3
+ import { ISettings } from '../types';
4
+ import { CONSENT_GRANTED, CONSENT_DECLINED } from '../utils/constants';
5
+
6
+ // Extend client-side factory instances with user consent getter/setter
7
+ export function userConsentProps(settings: ISettings, syncManager?: ISyncManager) {
8
+
9
+ const log = settings.log;
10
+
11
+ return {
12
+ setUserConsent(consent: unknown) {
13
+ // validate input param
14
+ if (typeof consent !== 'boolean') {
15
+ log.error(ERROR_NOT_BOOLEAN, ['setUserConsent']);
16
+ return false;
17
+ }
18
+
19
+ const newConsentStatus = consent ? CONSENT_GRANTED : CONSENT_DECLINED;
20
+
21
+ if (settings.userConsent !== newConsentStatus) {
22
+ // resume/pause submitters
23
+ if (consent) syncManager?.submitter?.start();
24
+ else syncManager?.submitter?.stop();
25
+
26
+ log.info(USER_CONSENT_UPDATED, [settings.userConsent, newConsentStatus]); // @ts-ignore, modify readonly prop
27
+ settings.userConsent = newConsentStatus;
28
+ }
29
+
30
+ return true;
31
+ },
32
+
33
+ getUserConsent() {
34
+ return settings.userConsent;
35
+ }
36
+ };
37
+ }
@@ -16,10 +16,22 @@ export class KeyBuilderCS extends KeyBuilder {
16
16
  * @override
17
17
  */
18
18
  buildSegmentNameKey(segmentName: string) {
19
- return `${this.matchingKey}.${this.prefix}.segment.${segmentName}`;
19
+ return `${this.prefix}.${this.matchingKey}.segment.${segmentName}`;
20
20
  }
21
21
 
22
22
  extractSegmentName(builtSegmentKeyName: string) {
23
+ const prefix = `${this.prefix}.${this.matchingKey}.segment.`;
24
+
25
+ if (startsWith(builtSegmentKeyName, prefix))
26
+ return builtSegmentKeyName.substr(prefix.length);
27
+ }
28
+
29
+ // @BREAKING: The key used to start with the matching key instead of the prefix, this was changed on version 10.17.3
30
+ buildOldSegmentNameKey(segmentName: string) {
31
+ return `${this.matchingKey}.${this.prefix}.segment.${segmentName}`;
32
+ }
33
+ // @BREAKING: The key used to start with the matching key instead of the prefix, this was changed on version 10.17.3
34
+ extractOldSegmentKey(builtSegmentKeyName: string) {
23
35
  const prefix = `${this.matchingKey}.${this.prefix}.segment.`;
24
36
 
25
37
  if (startsWith(builtSegmentKeyName, prefix))
@@ -67,9 +67,29 @@ export class MySegmentsCacheInLocal extends AbstractSegmentsCacheSync {
67
67
 
68
68
  // Scan current values from localStorage
69
69
  const storedSegmentNames = Object.keys(localStorage).reduce((accum, key) => {
70
- const name = this.keys.extractSegmentName(key);
71
-
72
- if (name) accum.push(name);
70
+ let segmentName = this.keys.extractSegmentName(key);
71
+
72
+ if (segmentName) {
73
+ accum.push(segmentName);
74
+ } else {
75
+ // @BREAKING: This is only to clean up "old" keys. Remove this whole else code block.
76
+ segmentName = this.keys.extractOldSegmentKey(key);
77
+
78
+ if (segmentName) { // this was an old segment key, let's clean up.
79
+ const newSegmentKey = this.keys.buildSegmentNameKey(segmentName);
80
+ try {
81
+ // If the new format key is not there, create it.
82
+ if (!localStorage.getItem(newSegmentKey) && names.indexOf(segmentName) > -1) {
83
+ localStorage.setItem(newSegmentKey, DEFINED);
84
+ // we are migrating a segment, let's track it.
85
+ accum.push(segmentName);
86
+ }
87
+ localStorage.removeItem(key); // we migrated the current key, let's delete it.
88
+ } catch (e) {
89
+ this.log.error(e);
90
+ }
91
+ }
92
+ }
73
93
 
74
94
  return accum;
75
95
  }, [] as string[]);
@@ -38,8 +38,12 @@ export function eventsSyncTaskFactory(
38
38
 
39
39
  // register events submitter to be executed when events cache is full
40
40
  eventsCache.setOnFullQueueCb(() => {
41
- log.info(SUBMITTERS_PUSH_FULL_QUEUE, [DATA_NAME]);
42
- syncTask.execute();
41
+ if (syncTask.isRunning()) {
42
+ log.info(SUBMITTERS_PUSH_FULL_QUEUE, [DATA_NAME]);
43
+ syncTask.execute();
44
+ }
45
+ // If submitter is stopped (e.g., user consent declined or unknown, or app state offline), we don't send the data.
46
+ // Data will be sent when submitter is resumed.
43
47
  });
44
48
 
45
49
  return syncTask;
@@ -57,8 +57,12 @@ export function impressionsSyncTaskFactory(
57
57
 
58
58
  // register impressions submitter to be executed when impressions cache is full
59
59
  impressionsCache.setOnFullQueueCb(() => {
60
- log.info(SUBMITTERS_PUSH_FULL_QUEUE, [DATA_NAME]);
61
- syncTask.execute();
60
+ if (syncTask.isRunning()) {
61
+ log.info(SUBMITTERS_PUSH_FULL_QUEUE, [DATA_NAME]);
62
+ syncTask.execute();
63
+ }
64
+ // If submitter is stopped (e.g., user consent declined or unknown, or app state offline), we don't send the data.
65
+ // Data will be sent when submitter is resumed.
62
66
  });
63
67
 
64
68
  return syncTask;