@splitsoftware/splitio-commons 2.10.2-rc.5 → 2.10.2-rc.7

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.
package/CHANGES.txt CHANGED
@@ -1,6 +1,6 @@
1
- 2.11.0 (January XX, 2026)
1
+ 2.11.0 (January 26, 2026)
2
2
  - Added metadata to SDK_UPDATE events to indicate the type of update (FLAGS_UPDATE or SEGMENTS_UPDATE) and the names of updated flags or segments.
3
- - Added metadata to SDK_READY and SDK_READY_FROM_CACHE events, including `initialCacheLoad` (boolean: `true` for fresh install/first app launch, `false` for warm cache/second app launch) and `lastUpdateTimestamp` (Int64 milliseconds since epoch).
3
+ - Added metadata to SDK_READY and SDK_READY_FROM_CACHE events, including `initialCacheLoad` (boolean: `true` for fresh install/first app launch, `false` for warm cache/second app launch) and `lastUpdateTimestamp` (milliseconds since epoch).
4
4
 
5
5
  2.10.1 (December 18, 2025)
6
6
  - Bugfix - Handle `null` prerequisites properly.
@@ -7,7 +7,7 @@ Split SDK is an open source project and we welcome feedback and contribution. Th
7
7
  ### Development process
8
8
 
9
9
  1. Fork the repository and create a topic branch from `development` branch. Please use a descriptive name for your branch.
10
- 2. While developing, use descriptive messages in your commits. Avoid short or meaningless sentences like: "fix bug".
10
+ 2. While developing, use descriptive messages in your commits. Avoid short or meaningless sentences like "fix bug".
11
11
  3. Make sure to add tests for both positive and negative cases.
12
12
  4. Run the linter script of the project and fix any issues you find.
13
13
  5. Run the build script and make sure it runs with no errors.
@@ -40,4 +40,4 @@ Consider running the linter and type check script (`npm run check`) and fixing a
40
40
 
41
41
  # Contact
42
42
 
43
- If you have any other questions or need to contact us directly in a private manner send us a note at sdks@split.io
43
+ If you have any other questions or need to contact us directly in a private manner send us a note at sdks@split.io
package/LICENSE CHANGED
@@ -1,13 +1,202 @@
1
- Copyright © 2025 Split Software, Inc.
2
1
 
3
- Licensed under the Apache License, Version 2.0 (the "License");
4
- you may not use this file except in compliance with the License.
5
- You may obtain a copy of the License at
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
6
5
 
7
- http://www.apache.org/licenses/LICENSE-2.0
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
7
 
9
- Unless required by applicable law or agreed to in writing, software
10
- distributed under the License is distributed on an "AS IS" BASIS,
11
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- See the License for the specific language governing permissions and
13
- limitations under the License.
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -39,9 +39,11 @@ function readinessManagerFactory(EventEmitter, settings, splits, isShared) {
39
39
  // ensure lastUpdate is always increasing per event, is case Date.now() is mocked or its value is the same
40
40
  lastUpdate = dateNow > lastUpdate ? dateNow : lastUpdate + 1;
41
41
  }
42
+ var metadataReady = {
43
+ initialCacheLoad: true
44
+ };
42
45
  // emit SDK_READY_FROM_CACHE
43
46
  var isReadyFromCache = false;
44
- var cacheLastUpdateTimestamp = null;
45
47
  if (splits.splitsCacheLoaded)
46
48
  isReadyFromCache = true; // ready from cache, but doesn't emit SDK_READY_FROM_CACHE
47
49
  else
@@ -70,16 +72,13 @@ function readinessManagerFactory(EventEmitter, settings, splits, isShared) {
70
72
  if (splits.hasInit)
71
73
  __init();
72
74
  function checkIsReadyFromCache(cacheMetadata) {
75
+ metadataReady = cacheMetadata;
73
76
  isReadyFromCache = true;
74
- cacheLastUpdateTimestamp = cacheMetadata.lastUpdateTimestamp;
75
77
  // Don't emit SDK_READY_FROM_CACHE if SDK_READY has been emitted
76
78
  if (!isReady && !isDestroyed) {
77
79
  try {
78
80
  syncLastUpdate();
79
- gate.emit(constants_1.SDK_READY_FROM_CACHE, {
80
- initialCacheLoad: !cacheMetadata.isCacheValid,
81
- lastUpdateTimestamp: cacheLastUpdateTimestamp
82
- });
81
+ gate.emit(constants_1.SDK_READY_FROM_CACHE, cacheMetadata);
83
82
  }
84
83
  catch (e) {
85
84
  // throws user callback exceptions in next tick
@@ -105,19 +104,15 @@ function readinessManagerFactory(EventEmitter, settings, splits, isShared) {
105
104
  clearTimeout(readyTimeoutId);
106
105
  isReady = true;
107
106
  try {
108
- var wasReadyFromCache = isReadyFromCache;
107
+ syncLastUpdate();
109
108
  if (!isReadyFromCache) {
110
109
  isReadyFromCache = true;
111
110
  var metadataReadyFromCache = {
112
111
  initialCacheLoad: true,
113
- lastUpdateTimestamp: null // No cache timestamp when fresh install
112
+ lastUpdateTimestamp: undefined // No cache timestamp when fresh install
114
113
  };
115
114
  gate.emit(constants_1.SDK_READY_FROM_CACHE, metadataReadyFromCache);
116
115
  }
117
- var metadataReady = {
118
- initialCacheLoad: !wasReadyFromCache,
119
- lastUpdateTimestamp: wasReadyFromCache ? cacheLastUpdateTimestamp : null
120
- };
121
116
  gate.emit(constants_1.SDK_READY, metadataReady);
122
117
  }
123
118
  catch (e) {
@@ -159,7 +154,8 @@ function readinessManagerFactory(EventEmitter, settings, splits, isShared) {
159
154
  hasTimedout: function () { return hasTimedout; },
160
155
  isDestroyed: function () { return isDestroyed; },
161
156
  isOperational: function () { return (isReady || isReadyFromCache) && !isDestroyed; },
162
- lastUpdate: function () { return lastUpdate; }
157
+ lastUpdate: function () { return lastUpdate; },
158
+ metadataReady: function () { return metadataReady; }
163
159
  };
164
160
  }
165
161
  exports.readinessManagerFactory = readinessManagerFactory;
@@ -106,7 +106,7 @@ function sdkReadinessManagerFactory(EventEmitter, settings, readinessManager) {
106
106
  whenReady: function () {
107
107
  return new Promise(function (resolve, reject) {
108
108
  if (readinessManager.isReady()) {
109
- resolve();
109
+ resolve(readinessManager.metadataReady());
110
110
  }
111
111
  else if (readinessManager.hasTimedout()) {
112
112
  reject(TIMEOUT_ERROR);
@@ -120,13 +120,13 @@ function sdkReadinessManagerFactory(EventEmitter, settings, readinessManager) {
120
120
  whenReadyFromCache: function () {
121
121
  return new Promise(function (resolve, reject) {
122
122
  if (readinessManager.isReadyFromCache()) {
123
- resolve(readinessManager.isReady());
123
+ resolve(readinessManager.metadataReady());
124
124
  }
125
125
  else if (readinessManager.hasTimedout()) {
126
126
  reject(TIMEOUT_ERROR);
127
127
  }
128
128
  else {
129
- readinessManager.gate.once(constants_1.SDK_READY_FROM_CACHE, function () { return resolve(readinessManager.isReady()); });
129
+ readinessManager.gate.once(constants_1.SDK_READY_FROM_CACHE, resolve);
130
130
  readinessManager.gate.once(constants_1.SDK_READY_TIMED_OUT, function () { return reject(TIMEOUT_ERROR); });
131
131
  }
132
132
  });
@@ -46,17 +46,17 @@ function sdkFactory(params) {
46
46
  return;
47
47
  }
48
48
  readiness.splits.emit(constants_2.SDK_SPLITS_ARRIVED);
49
- readiness.segments.emit(constants_2.SDK_SEGMENTS_ARRIVED, { isCacheValid: true, lastUpdateTimestamp: null });
49
+ readiness.segments.emit(constants_2.SDK_SEGMENTS_ARRIVED);
50
50
  },
51
51
  onReadyFromCacheCb: function () {
52
- readiness.splits.emit(constants_2.SDK_SPLITS_CACHE_LOADED, { isCacheValid: true, lastUpdateTimestamp: null });
52
+ readiness.splits.emit(constants_2.SDK_SPLITS_CACHE_LOADED, { initialCacheLoad: false /* Not an initial load, cache exists */ });
53
53
  }
54
54
  });
55
55
  var fallbackTreatmentsCalculator = new fallbackTreatmentsCalculator_1.FallbackTreatmentsCalculator(settings.fallbackTreatments);
56
56
  if (initialRolloutPlan) {
57
57
  (0, setRolloutPlan_1.setRolloutPlan)(log, initialRolloutPlan, storage, key && (0, key_1.getMatching)(key));
58
58
  if (storage.splits.getChangeNumber() > -1)
59
- readiness.splits.emit(constants_2.SDK_SPLITS_CACHE_LOADED, { isCacheValid: true, lastUpdateTimestamp: null });
59
+ readiness.splits.emit(constants_2.SDK_SPLITS_CACHE_LOADED, { initialCacheLoad: false /* Not an initial load, cache exists */ });
60
60
  }
61
61
  var clients = {};
62
62
  var telemetryTracker = (0, telemetryTracker_1.telemetryTrackerFactory)(storage.telemetry, platform.now);
@@ -55,7 +55,7 @@ function validateExpiration(options, storage, settings, keys, currentTimestamp,
55
55
  * - its hash has changed, i.e., the SDK key, flags filter criteria or flags spec version was modified
56
56
  * - `clearOnInit` was set and cache was not cleared in the last 24 hours
57
57
  *
58
- * @returns Metadata object with `isCacheValid` (true if cache is ready to be used, false otherwise) and `lastUpdateTimestamp` (timestamp of last cache update or null)
58
+ * @returns Metadata object with `initialCacheLoad` (true if is fresh install, false if is ready from cache) and `lastUpdateTimestamp` (timestamp of last cache update or undefined)
59
59
  */
60
60
  function validateCache(options, storage, settings, keys, splits, rbSegments, segments, largeSegments) {
61
61
  return Promise.resolve(storage.load && storage.load()).then(function () {
@@ -63,8 +63,8 @@ function validateCache(options, storage, settings, keys, splits, rbSegments, seg
63
63
  var isThereCache = splits.getChangeNumber() > -1;
64
64
  // Get lastUpdateTimestamp from storage
65
65
  var lastUpdatedTimestampStr = storage.getItem(keys.buildLastUpdatedKey());
66
- var lastUpdatedTimestamp = lastUpdatedTimestampStr ? parseInt(lastUpdatedTimestampStr, 10) : null;
67
- var lastUpdateTimestamp = (!(0, lang_1.isNaNNumber)(lastUpdatedTimestamp) && lastUpdatedTimestamp !== null) ? lastUpdatedTimestamp : null;
66
+ var lastUpdatedTimestamp = lastUpdatedTimestampStr ? parseInt(lastUpdatedTimestampStr, 10) : undefined;
67
+ var lastUpdateTimestamp = (!(0, lang_1.isNaNNumber)(lastUpdatedTimestamp) && lastUpdatedTimestamp !== undefined) ? lastUpdatedTimestamp : undefined;
68
68
  if (validateExpiration(options, storage, settings, keys, currentTimestamp, isThereCache)) {
69
69
  splits.clear();
70
70
  rbSegments.clear();
@@ -81,13 +81,13 @@ function validateCache(options, storage, settings, keys, splits, rbSegments, seg
81
81
  if (storage.save)
82
82
  storage.save();
83
83
  return {
84
- isCacheValid: false,
85
- lastUpdateTimestamp: null
84
+ initialCacheLoad: true,
85
+ lastUpdateTimestamp: undefined
86
86
  };
87
87
  }
88
88
  // Check if ready from cache
89
89
  return {
90
- isCacheValid: isThereCache,
90
+ initialCacheLoad: !isThereCache,
91
91
  lastUpdateTimestamp: lastUpdateTimestamp
92
92
  };
93
93
  });
@@ -45,9 +45,9 @@ function fromObjectUpdaterFactory(splitsParser, storage, readiness, settings) {
45
45
  readiness.splits.emit(constants_2.SDK_SPLITS_ARRIVED, { type: constants_2.FLAGS_UPDATE, names: [] });
46
46
  if (startingUp) {
47
47
  startingUp = false;
48
- Promise.resolve(storage.validateCache ? storage.validateCache() : { isCacheValid: false, lastUpdateTimestamp: null }).then(function (cacheMetadata) {
48
+ Promise.resolve(storage.validateCache ? storage.validateCache() : { initialCacheLoad: true /* Fallback: assume initial load when validateCache doesn't exist */ }).then(function (cacheMetadata) {
49
49
  // Emits SDK_READY_FROM_CACHE
50
- if (cacheMetadata.isCacheValid) {
50
+ if (!cacheMetadata.initialCacheLoad) {
51
51
  readiness.splits.emit(constants_2.SDK_SPLITS_CACHE_LOADED, cacheMetadata);
52
52
  }
53
53
  // Emits SDK_READY
@@ -71,12 +71,12 @@ function syncManagerOnlineFactory(pollingManagerFactory, pushManagerFactory) {
71
71
  running = true;
72
72
  // @TODO once event, impression and telemetry storages support persistence, call when `validateCache` promise is resolved
73
73
  submitterManager.start(!(0, consent_1.isConsentGranted)(settings));
74
- return Promise.resolve(storage.validateCache ? storage.validateCache() : { isCacheValid: false, lastUpdateTimestamp: null }).then(function (cacheMetadata) {
74
+ return Promise.resolve(storage.validateCache ? storage.validateCache() : { initialCacheLoad: true /* Fallback: assume initial load when validateCache doesn't exist */ }).then(function (cacheMetadata) {
75
75
  if (!running)
76
76
  return;
77
77
  if (startFirstTime) {
78
78
  // Emits SDK_READY_FROM_CACHE
79
- if (cacheMetadata.isCacheValid) {
79
+ if (!cacheMetadata.initialCacheLoad) {
80
80
  readiness.splits.emit(constants_4.SDK_SPLITS_CACHE_LOADED, cacheMetadata);
81
81
  }
82
82
  }
@@ -6,7 +6,7 @@ var constants_1 = require("../../../logger/constants");
6
6
  var constants_2 = require("../../../utils/constants");
7
7
  function __InLocalStorageMockFactory(params) {
8
8
  var result = (0, InMemoryStorageCS_1.InMemoryStorageCSFactory)(params);
9
- result.validateCache = function () { return Promise.resolve({ isCacheValid: true, lastUpdateTimestamp: null }); }; // to emit SDK_READY_FROM_CACHE
9
+ result.validateCache = function () { return Promise.resolve({ initialCacheLoad: false /* Not an initial load, cache exists - to emit SDK_READY_FROM_CACHE */ }); };
10
10
  return result;
11
11
  }
12
12
  exports.__InLocalStorageMockFactory = __InLocalStorageMockFactory;
@@ -36,9 +36,11 @@ export function readinessManagerFactory(EventEmitter, settings, splits, isShared
36
36
  // ensure lastUpdate is always increasing per event, is case Date.now() is mocked or its value is the same
37
37
  lastUpdate = dateNow > lastUpdate ? dateNow : lastUpdate + 1;
38
38
  }
39
+ var metadataReady = {
40
+ initialCacheLoad: true
41
+ };
39
42
  // emit SDK_READY_FROM_CACHE
40
43
  var isReadyFromCache = false;
41
- var cacheLastUpdateTimestamp = null;
42
44
  if (splits.splitsCacheLoaded)
43
45
  isReadyFromCache = true; // ready from cache, but doesn't emit SDK_READY_FROM_CACHE
44
46
  else
@@ -67,16 +69,13 @@ export function readinessManagerFactory(EventEmitter, settings, splits, isShared
67
69
  if (splits.hasInit)
68
70
  __init();
69
71
  function checkIsReadyFromCache(cacheMetadata) {
72
+ metadataReady = cacheMetadata;
70
73
  isReadyFromCache = true;
71
- cacheLastUpdateTimestamp = cacheMetadata.lastUpdateTimestamp;
72
74
  // Don't emit SDK_READY_FROM_CACHE if SDK_READY has been emitted
73
75
  if (!isReady && !isDestroyed) {
74
76
  try {
75
77
  syncLastUpdate();
76
- gate.emit(SDK_READY_FROM_CACHE, {
77
- initialCacheLoad: !cacheMetadata.isCacheValid,
78
- lastUpdateTimestamp: cacheLastUpdateTimestamp
79
- });
78
+ gate.emit(SDK_READY_FROM_CACHE, cacheMetadata);
80
79
  }
81
80
  catch (e) {
82
81
  // throws user callback exceptions in next tick
@@ -102,19 +101,15 @@ export function readinessManagerFactory(EventEmitter, settings, splits, isShared
102
101
  clearTimeout(readyTimeoutId);
103
102
  isReady = true;
104
103
  try {
105
- var wasReadyFromCache = isReadyFromCache;
104
+ syncLastUpdate();
106
105
  if (!isReadyFromCache) {
107
106
  isReadyFromCache = true;
108
107
  var metadataReadyFromCache = {
109
108
  initialCacheLoad: true,
110
- lastUpdateTimestamp: null // No cache timestamp when fresh install
109
+ lastUpdateTimestamp: undefined // No cache timestamp when fresh install
111
110
  };
112
111
  gate.emit(SDK_READY_FROM_CACHE, metadataReadyFromCache);
113
112
  }
114
- var metadataReady = {
115
- initialCacheLoad: !wasReadyFromCache,
116
- lastUpdateTimestamp: wasReadyFromCache ? cacheLastUpdateTimestamp : null
117
- };
118
113
  gate.emit(SDK_READY, metadataReady);
119
114
  }
120
115
  catch (e) {
@@ -156,6 +151,7 @@ export function readinessManagerFactory(EventEmitter, settings, splits, isShared
156
151
  hasTimedout: function () { return hasTimedout; },
157
152
  isDestroyed: function () { return isDestroyed; },
158
153
  isOperational: function () { return (isReady || isReadyFromCache) && !isDestroyed; },
159
- lastUpdate: function () { return lastUpdate; }
154
+ lastUpdate: function () { return lastUpdate; },
155
+ metadataReady: function () { return metadataReady; }
160
156
  };
161
157
  }
@@ -103,7 +103,7 @@ export function sdkReadinessManagerFactory(EventEmitter, settings, readinessMana
103
103
  whenReady: function () {
104
104
  return new Promise(function (resolve, reject) {
105
105
  if (readinessManager.isReady()) {
106
- resolve();
106
+ resolve(readinessManager.metadataReady());
107
107
  }
108
108
  else if (readinessManager.hasTimedout()) {
109
109
  reject(TIMEOUT_ERROR);
@@ -117,13 +117,13 @@ export function sdkReadinessManagerFactory(EventEmitter, settings, readinessMana
117
117
  whenReadyFromCache: function () {
118
118
  return new Promise(function (resolve, reject) {
119
119
  if (readinessManager.isReadyFromCache()) {
120
- resolve(readinessManager.isReady());
120
+ resolve(readinessManager.metadataReady());
121
121
  }
122
122
  else if (readinessManager.hasTimedout()) {
123
123
  reject(TIMEOUT_ERROR);
124
124
  }
125
125
  else {
126
- readinessManager.gate.once(SDK_READY_FROM_CACHE, function () { return resolve(readinessManager.isReady()); });
126
+ readinessManager.gate.once(SDK_READY_FROM_CACHE, resolve);
127
127
  readinessManager.gate.once(SDK_READY_TIMED_OUT, function () { return reject(TIMEOUT_ERROR); });
128
128
  }
129
129
  });
@@ -43,17 +43,17 @@ export function sdkFactory(params) {
43
43
  return;
44
44
  }
45
45
  readiness.splits.emit(SDK_SPLITS_ARRIVED);
46
- readiness.segments.emit(SDK_SEGMENTS_ARRIVED, { isCacheValid: true, lastUpdateTimestamp: null });
46
+ readiness.segments.emit(SDK_SEGMENTS_ARRIVED);
47
47
  },
48
48
  onReadyFromCacheCb: function () {
49
- readiness.splits.emit(SDK_SPLITS_CACHE_LOADED, { isCacheValid: true, lastUpdateTimestamp: null });
49
+ readiness.splits.emit(SDK_SPLITS_CACHE_LOADED, { initialCacheLoad: false /* Not an initial load, cache exists */ });
50
50
  }
51
51
  });
52
52
  var fallbackTreatmentsCalculator = new FallbackTreatmentsCalculator(settings.fallbackTreatments);
53
53
  if (initialRolloutPlan) {
54
54
  setRolloutPlan(log, initialRolloutPlan, storage, key && getMatching(key));
55
55
  if (storage.splits.getChangeNumber() > -1)
56
- readiness.splits.emit(SDK_SPLITS_CACHE_LOADED, { isCacheValid: true, lastUpdateTimestamp: null });
56
+ readiness.splits.emit(SDK_SPLITS_CACHE_LOADED, { initialCacheLoad: false /* Not an initial load, cache exists */ });
57
57
  }
58
58
  var clients = {};
59
59
  var telemetryTracker = telemetryTrackerFactory(storage.telemetry, platform.now);
@@ -52,7 +52,7 @@ function validateExpiration(options, storage, settings, keys, currentTimestamp,
52
52
  * - its hash has changed, i.e., the SDK key, flags filter criteria or flags spec version was modified
53
53
  * - `clearOnInit` was set and cache was not cleared in the last 24 hours
54
54
  *
55
- * @returns Metadata object with `isCacheValid` (true if cache is ready to be used, false otherwise) and `lastUpdateTimestamp` (timestamp of last cache update or null)
55
+ * @returns Metadata object with `initialCacheLoad` (true if is fresh install, false if is ready from cache) and `lastUpdateTimestamp` (timestamp of last cache update or undefined)
56
56
  */
57
57
  export function validateCache(options, storage, settings, keys, splits, rbSegments, segments, largeSegments) {
58
58
  return Promise.resolve(storage.load && storage.load()).then(function () {
@@ -60,8 +60,8 @@ export function validateCache(options, storage, settings, keys, splits, rbSegmen
60
60
  var isThereCache = splits.getChangeNumber() > -1;
61
61
  // Get lastUpdateTimestamp from storage
62
62
  var lastUpdatedTimestampStr = storage.getItem(keys.buildLastUpdatedKey());
63
- var lastUpdatedTimestamp = lastUpdatedTimestampStr ? parseInt(lastUpdatedTimestampStr, 10) : null;
64
- var lastUpdateTimestamp = (!isNaNNumber(lastUpdatedTimestamp) && lastUpdatedTimestamp !== null) ? lastUpdatedTimestamp : null;
63
+ var lastUpdatedTimestamp = lastUpdatedTimestampStr ? parseInt(lastUpdatedTimestampStr, 10) : undefined;
64
+ var lastUpdateTimestamp = (!isNaNNumber(lastUpdatedTimestamp) && lastUpdatedTimestamp !== undefined) ? lastUpdatedTimestamp : undefined;
65
65
  if (validateExpiration(options, storage, settings, keys, currentTimestamp, isThereCache)) {
66
66
  splits.clear();
67
67
  rbSegments.clear();
@@ -78,13 +78,13 @@ export function validateCache(options, storage, settings, keys, splits, rbSegmen
78
78
  if (storage.save)
79
79
  storage.save();
80
80
  return {
81
- isCacheValid: false,
82
- lastUpdateTimestamp: null
81
+ initialCacheLoad: true,
82
+ lastUpdateTimestamp: undefined
83
83
  };
84
84
  }
85
85
  // Check if ready from cache
86
86
  return {
87
- isCacheValid: isThereCache,
87
+ initialCacheLoad: !isThereCache,
88
88
  lastUpdateTimestamp: lastUpdateTimestamp
89
89
  };
90
90
  });
@@ -42,9 +42,9 @@ export function fromObjectUpdaterFactory(splitsParser, storage, readiness, setti
42
42
  readiness.splits.emit(SDK_SPLITS_ARRIVED, { type: FLAGS_UPDATE, names: [] });
43
43
  if (startingUp) {
44
44
  startingUp = false;
45
- Promise.resolve(storage.validateCache ? storage.validateCache() : { isCacheValid: false, lastUpdateTimestamp: null }).then(function (cacheMetadata) {
45
+ Promise.resolve(storage.validateCache ? storage.validateCache() : { initialCacheLoad: true /* Fallback: assume initial load when validateCache doesn't exist */ }).then(function (cacheMetadata) {
46
46
  // Emits SDK_READY_FROM_CACHE
47
- if (cacheMetadata.isCacheValid) {
47
+ if (!cacheMetadata.initialCacheLoad) {
48
48
  readiness.splits.emit(SDK_SPLITS_CACHE_LOADED, cacheMetadata);
49
49
  }
50
50
  // Emits SDK_READY
@@ -68,12 +68,12 @@ export function syncManagerOnlineFactory(pollingManagerFactory, pushManagerFacto
68
68
  running = true;
69
69
  // @TODO once event, impression and telemetry storages support persistence, call when `validateCache` promise is resolved
70
70
  submitterManager.start(!isConsentGranted(settings));
71
- return Promise.resolve(storage.validateCache ? storage.validateCache() : { isCacheValid: false, lastUpdateTimestamp: null }).then(function (cacheMetadata) {
71
+ return Promise.resolve(storage.validateCache ? storage.validateCache() : { initialCacheLoad: true /* Fallback: assume initial load when validateCache doesn't exist */ }).then(function (cacheMetadata) {
72
72
  if (!running)
73
73
  return;
74
74
  if (startFirstTime) {
75
75
  // Emits SDK_READY_FROM_CACHE
76
- if (cacheMetadata.isCacheValid) {
76
+ if (!cacheMetadata.initialCacheLoad) {
77
77
  readiness.splits.emit(SDK_SPLITS_CACHE_LOADED, cacheMetadata);
78
78
  }
79
79
  }
@@ -3,7 +3,7 @@ import { ERROR_STORAGE_INVALID } from '../../../logger/constants';
3
3
  import { LOCALHOST_MODE, STANDALONE_MODE, STORAGE_PLUGGABLE, STORAGE_LOCALSTORAGE, STORAGE_MEMORY } from '../../../utils/constants';
4
4
  export function __InLocalStorageMockFactory(params) {
5
5
  var result = InMemoryStorageCSFactory(params);
6
- result.validateCache = function () { return Promise.resolve({ isCacheValid: true, lastUpdateTimestamp: null }); }; // to emit SDK_READY_FROM_CACHE
6
+ result.validateCache = function () { return Promise.resolve({ initialCacheLoad: false /* Not an initial load, cache exists - to emit SDK_READY_FROM_CACHE */ }); };
7
7
  return result;
8
8
  }
9
9
  __InLocalStorageMockFactory.type = STORAGE_MEMORY;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@splitsoftware/splitio-commons",
3
- "version": "2.10.2-rc.5",
3
+ "version": "2.10.2-rc.7",
4
4
  "description": "Split JavaScript SDK common components",
5
5
  "main": "cjs/index.js",
6
6
  "module": "esm/index.js",
@@ -1,9 +1,8 @@
1
1
  import { objectAssign } from '../utils/lang/objectAssign';
2
2
  import { ISettings } from '../types';
3
- import SplitIO from '../../types/splitio';
3
+ import SplitIO, { SdkReadyMetadata } from '../../types/splitio';
4
4
  import { SDK_SPLITS_ARRIVED, SDK_SPLITS_CACHE_LOADED, SDK_SEGMENTS_ARRIVED, SDK_READY_TIMED_OUT, SDK_READY_FROM_CACHE, SDK_UPDATE, SDK_READY } from './constants';
5
5
  import { IReadinessEventEmitter, IReadinessManager, ISegmentsEventEmitter, ISplitsEventEmitter } from './types';
6
- import { CacheValidationMetadata } from '../storages/inLocalStorage/validateCache';
7
6
 
8
7
  function splitsEventEmitterFactory(EventEmitter: new () => SplitIO.IEventEmitter): ISplitsEventEmitter {
9
8
  const splitsEventEmitter = objectAssign(new EventEmitter(), {
@@ -54,9 +53,12 @@ export function readinessManagerFactory(
54
53
  lastUpdate = dateNow > lastUpdate ? dateNow : lastUpdate + 1;
55
54
  }
56
55
 
56
+ let metadataReady: SdkReadyMetadata = {
57
+ initialCacheLoad: true
58
+ };
59
+
57
60
  // emit SDK_READY_FROM_CACHE
58
61
  let isReadyFromCache = false;
59
- let cacheLastUpdateTimestamp: number | null = null;
60
62
  if (splits.splitsCacheLoaded) isReadyFromCache = true; // ready from cache, but doesn't emit SDK_READY_FROM_CACHE
61
63
  else splits.once(SDK_SPLITS_CACHE_LOADED, checkIsReadyFromCache);
62
64
 
@@ -86,17 +88,14 @@ export function readinessManagerFactory(
86
88
  splits.initCallbacks.push(__init);
87
89
  if (splits.hasInit) __init();
88
90
 
89
- function checkIsReadyFromCache(cacheMetadata: CacheValidationMetadata) {
91
+ function checkIsReadyFromCache(cacheMetadata: SdkReadyMetadata) {
92
+ metadataReady = cacheMetadata;
90
93
  isReadyFromCache = true;
91
- cacheLastUpdateTimestamp = cacheMetadata.lastUpdateTimestamp;
92
94
  // Don't emit SDK_READY_FROM_CACHE if SDK_READY has been emitted
93
95
  if (!isReady && !isDestroyed) {
94
96
  try {
95
97
  syncLastUpdate();
96
- gate.emit(SDK_READY_FROM_CACHE, {
97
- initialCacheLoad: !cacheMetadata.isCacheValid,
98
- lastUpdateTimestamp: cacheLastUpdateTimestamp
99
- });
98
+ gate.emit(SDK_READY_FROM_CACHE, cacheMetadata);
100
99
  } catch (e) {
101
100
  // throws user callback exceptions in next tick
102
101
  setTimeout(() => { throw e; }, 0);
@@ -119,19 +118,15 @@ export function readinessManagerFactory(
119
118
  clearTimeout(readyTimeoutId);
120
119
  isReady = true;
121
120
  try {
122
- const wasReadyFromCache = isReadyFromCache;
121
+ syncLastUpdate();
123
122
  if (!isReadyFromCache) {
124
123
  isReadyFromCache = true;
125
124
  const metadataReadyFromCache: SplitIO.SdkReadyMetadata = {
126
- initialCacheLoad: true,
127
- lastUpdateTimestamp: null // No cache timestamp when fresh install
125
+ initialCacheLoad: true, // Fresh install, no cache existed
126
+ lastUpdateTimestamp: undefined // No cache timestamp when fresh install
128
127
  };
129
128
  gate.emit(SDK_READY_FROM_CACHE, metadataReadyFromCache);
130
129
  }
131
- const metadataReady: SplitIO.SdkReadyMetadata = {
132
- initialCacheLoad: !wasReadyFromCache,
133
- lastUpdateTimestamp: wasReadyFromCache ? cacheLastUpdateTimestamp : null
134
- };
135
130
  gate.emit(SDK_READY, metadataReady);
136
131
  } catch (e) {
137
132
  // throws user callback exceptions in next tick
@@ -177,7 +172,8 @@ export function readinessManagerFactory(
177
172
  hasTimedout() { return hasTimedout; },
178
173
  isDestroyed() { return isDestroyed; },
179
174
  isOperational() { return (isReady || isReadyFromCache) && !isDestroyed; },
180
- lastUpdate() { return lastUpdate; }
175
+ lastUpdate() { return lastUpdate; },
176
+ metadataReady() { return metadataReady; }
181
177
  };
182
178
 
183
179
  }
@@ -120,9 +120,9 @@ export function sdkReadinessManagerFactory(
120
120
  },
121
121
 
122
122
  whenReady() {
123
- return new Promise<void>((resolve, reject) => {
123
+ return new Promise<SplitIO.SdkReadyMetadata>((resolve, reject) => {
124
124
  if (readinessManager.isReady()) {
125
- resolve();
125
+ resolve(readinessManager.metadataReady());
126
126
  } else if (readinessManager.hasTimedout()) {
127
127
  reject(TIMEOUT_ERROR);
128
128
  } else {
@@ -133,13 +133,13 @@ export function sdkReadinessManagerFactory(
133
133
  },
134
134
 
135
135
  whenReadyFromCache() {
136
- return new Promise<boolean>((resolve, reject) => {
136
+ return new Promise<SplitIO.SdkReadyMetadata>((resolve, reject) => {
137
137
  if (readinessManager.isReadyFromCache()) {
138
- resolve(readinessManager.isReady());
138
+ resolve(readinessManager.metadataReady());
139
139
  } else if (readinessManager.hasTimedout()) {
140
140
  reject(TIMEOUT_ERROR);
141
141
  } else {
142
- readinessManager.gate.once(SDK_READY_FROM_CACHE, () => resolve(readinessManager.isReady()));
142
+ readinessManager.gate.once(SDK_READY_FROM_CACHE, resolve);
143
143
  readinessManager.gate.once(SDK_READY_TIMED_OUT, () => reject(TIMEOUT_ERROR));
144
144
  }
145
145
  });
@@ -12,19 +12,8 @@ export type IReadinessEvent = SDK_READY_TIMED_OUT | SDK_READY | SDK_READY_FROM_C
12
12
 
13
13
  export interface IReadinessEventEmitter extends SplitIO.IEventEmitter {
14
14
  emit(event: IReadinessEvent, ...args: any[]): boolean
15
- on(event: SDK_READY, listener: (metadata: SplitIO.SdkReadyMetadata) => void): this;
16
- on(event: SDK_READY_FROM_CACHE, listener: (metadata: SplitIO.SdkReadyMetadata) => void): this;
17
- on(event: SDK_UPDATE, listener: (metadata: SplitIO.SdkUpdateMetadata) => void): this;
18
- on(event: string | symbol, listener: (...args: any[]) => void): this;
19
- once(event: SDK_READY, listener: (metadata: SplitIO.SdkReadyMetadata) => void): this;
20
- once(event: SDK_READY_FROM_CACHE, listener: (metadata: SplitIO.SdkReadyMetadata) => void): this;
21
- once(event: SDK_UPDATE, listener: (metadata: SplitIO.SdkUpdateMetadata) => void): this;
22
- once(event: string | symbol, listener: (...args: any[]) => void): this;
23
- addListener(event: SDK_READY, listener: (metadata: SplitIO.SdkReadyMetadata) => void): this;
24
- addListener(event: SDK_READY_FROM_CACHE, listener: (metadata: SplitIO.SdkReadyMetadata) => void): this;
25
- addListener(event: SDK_UPDATE, listener: (metadata: SplitIO.SdkUpdateMetadata) => void): this;
26
- addListener(event: string | symbol, listener: (...args: any[]) => void): this;
27
15
  }
16
+
28
17
  /** Splits data emitter */
29
18
 
30
19
  type SDK_SPLITS_ARRIVED = 'state::splits-arrived'
@@ -71,6 +60,7 @@ export interface IReadinessManager {
71
60
  isDestroyed(): boolean,
72
61
  isOperational(): boolean,
73
62
  lastUpdate(): number,
63
+ metadataReady(): SplitIO.SdkReadyMetadata,
74
64
 
75
65
  timeout(): void,
76
66
  setDestroyed(): void,
@@ -54,10 +54,10 @@ export function sdkFactory(params: ISdkFactoryParams): SplitIO.ISDK | SplitIO.IA
54
54
  return;
55
55
  }
56
56
  readiness.splits.emit(SDK_SPLITS_ARRIVED);
57
- readiness.segments.emit(SDK_SEGMENTS_ARRIVED, { isCacheValid: true, lastUpdateTimestamp: null });
57
+ readiness.segments.emit(SDK_SEGMENTS_ARRIVED);
58
58
  },
59
59
  onReadyFromCacheCb() {
60
- readiness.splits.emit(SDK_SPLITS_CACHE_LOADED, { isCacheValid: true, lastUpdateTimestamp: null });
60
+ readiness.splits.emit(SDK_SPLITS_CACHE_LOADED, { initialCacheLoad: false /* Not an initial load, cache exists */ });
61
61
  }
62
62
  });
63
63
 
@@ -65,7 +65,7 @@ export function sdkFactory(params: ISdkFactoryParams): SplitIO.ISDK | SplitIO.IA
65
65
 
66
66
  if (initialRolloutPlan) {
67
67
  setRolloutPlan(log, initialRolloutPlan, storage as IStorageSync, key && getMatching(key));
68
- if ((storage as IStorageSync).splits.getChangeNumber() > -1) readiness.splits.emit(SDK_SPLITS_CACHE_LOADED, { isCacheValid: true, lastUpdateTimestamp: null });
68
+ if ((storage as IStorageSync).splits.getChangeNumber() > -1) readiness.splits.emit(SDK_SPLITS_CACHE_LOADED, { initialCacheLoad: false /* Not an initial load, cache exists */ });
69
69
  }
70
70
 
71
71
  const clients: Record<string, SplitIO.IBasicClient> = {};
@@ -14,7 +14,7 @@ import { STORAGE_LOCALSTORAGE } from '../../utils/constants';
14
14
  import { shouldRecordTelemetry, TelemetryCacheInMemory } from '../inMemory/TelemetryCacheInMemory';
15
15
  import { UniqueKeysCacheInMemoryCS } from '../inMemory/UniqueKeysCacheInMemoryCS';
16
16
  import { getMatching } from '../../utils/key';
17
- import { validateCache, CacheValidationMetadata } from './validateCache';
17
+ import { validateCache } from './validateCache';
18
18
  import { ILogger } from '../../logger/types';
19
19
  import SplitIO from '../../../types/splitio';
20
20
  import { storageAdapter } from './storageAdapter';
@@ -54,7 +54,7 @@ export function InLocalStorage(options: SplitIO.InLocalStorageOptions = {}): ISt
54
54
  const rbSegments = new RBSegmentsCacheInLocal(settings, keys, storage);
55
55
  const segments = new MySegmentsCacheInLocal(log, keys, storage);
56
56
  const largeSegments = new MySegmentsCacheInLocal(log, myLargeSegmentsKeyBuilder(prefix, matchingKey), storage);
57
- let validateCachePromise: Promise<CacheValidationMetadata> | undefined;
57
+ let validateCachePromise: Promise<SplitIO.SdkReadyMetadata> | undefined;
58
58
 
59
59
  return {
60
60
  splits,
@@ -12,11 +12,6 @@ import { StorageAdapter } from '../types';
12
12
  const DEFAULT_CACHE_EXPIRATION_IN_DAYS = 10;
13
13
  const MILLIS_IN_A_DAY = 86400000;
14
14
 
15
- export interface CacheValidationMetadata {
16
- isCacheValid: boolean;
17
- lastUpdateTimestamp: number | null;
18
- }
19
-
20
15
  /**
21
16
  * Validates if cache should be cleared and sets the cache `hash` if needed.
22
17
  *
@@ -71,9 +66,9 @@ function validateExpiration(options: SplitIO.InLocalStorageOptions, storage: Sto
71
66
  * - its hash has changed, i.e., the SDK key, flags filter criteria or flags spec version was modified
72
67
  * - `clearOnInit` was set and cache was not cleared in the last 24 hours
73
68
  *
74
- * @returns Metadata object with `isCacheValid` (true if cache is ready to be used, false otherwise) and `lastUpdateTimestamp` (timestamp of last cache update or null)
69
+ * @returns Metadata object with `initialCacheLoad` (true if is fresh install, false if is ready from cache) and `lastUpdateTimestamp` (timestamp of last cache update or undefined)
75
70
  */
76
- export function validateCache(options: SplitIO.InLocalStorageOptions, storage: StorageAdapter, settings: ISettings, keys: KeyBuilderCS, splits: SplitsCacheInLocal, rbSegments: RBSegmentsCacheInLocal, segments: MySegmentsCacheInLocal, largeSegments: MySegmentsCacheInLocal): Promise<CacheValidationMetadata> {
71
+ export function validateCache(options: SplitIO.InLocalStorageOptions, storage: StorageAdapter, settings: ISettings, keys: KeyBuilderCS, splits: SplitsCacheInLocal, rbSegments: RBSegmentsCacheInLocal, segments: MySegmentsCacheInLocal, largeSegments: MySegmentsCacheInLocal): Promise<SplitIO.SdkReadyMetadata> {
77
72
 
78
73
  return Promise.resolve(storage.load && storage.load()).then(() => {
79
74
  const currentTimestamp = Date.now();
@@ -81,8 +76,8 @@ export function validateCache(options: SplitIO.InLocalStorageOptions, storage: S
81
76
 
82
77
  // Get lastUpdateTimestamp from storage
83
78
  const lastUpdatedTimestampStr = storage.getItem(keys.buildLastUpdatedKey());
84
- const lastUpdatedTimestamp = lastUpdatedTimestampStr ? parseInt(lastUpdatedTimestampStr, 10) : null;
85
- const lastUpdateTimestamp = (!isNaNNumber(lastUpdatedTimestamp) && lastUpdatedTimestamp !== null) ? lastUpdatedTimestamp : null;
79
+ const lastUpdatedTimestamp = lastUpdatedTimestampStr ? parseInt(lastUpdatedTimestampStr, 10) : undefined;
80
+ const lastUpdateTimestamp = (!isNaNNumber(lastUpdatedTimestamp) && lastUpdatedTimestamp !== undefined) ? lastUpdatedTimestamp : undefined;
86
81
 
87
82
  if (validateExpiration(options, storage, settings, keys, currentTimestamp, isThereCache)) {
88
83
  splits.clear();
@@ -101,14 +96,14 @@ export function validateCache(options: SplitIO.InLocalStorageOptions, storage: S
101
96
  if (storage.save) storage.save();
102
97
 
103
98
  return {
104
- isCacheValid: false,
105
- lastUpdateTimestamp: null
99
+ initialCacheLoad: true, // Cache was cleared, so this is an initial load (no cache existed)
100
+ lastUpdateTimestamp: undefined
106
101
  };
107
102
  }
108
103
 
109
104
  // Check if ready from cache
110
105
  return {
111
- isCacheValid: isThereCache,
106
+ initialCacheLoad: !isThereCache, // true if no cache exists (initial load), false if cache exists (ready from cache)
112
107
  lastUpdateTimestamp
113
108
  };
114
109
  });
@@ -499,7 +499,7 @@ export interface IStorageSync extends IStorageBase<
499
499
  IUniqueKeysCacheSync
500
500
  > {
501
501
  // Defined in client-side
502
- validateCache?: () => Promise<{ isCacheValid: boolean; lastUpdateTimestamp: number | null }>,
502
+ validateCache?: () => Promise<SplitIO.SdkReadyMetadata>,
503
503
  largeSegments?: ISegmentsCacheSync,
504
504
  }
505
505
 
@@ -59,9 +59,9 @@ export function fromObjectUpdaterFactory(
59
59
 
60
60
  if (startingUp) {
61
61
  startingUp = false;
62
- Promise.resolve(storage.validateCache ? storage.validateCache() : { isCacheValid: false, lastUpdateTimestamp: null }).then((cacheMetadata) => {
62
+ Promise.resolve(storage.validateCache ? storage.validateCache() : { initialCacheLoad: true /* Fallback: assume initial load when validateCache doesn't exist */ }).then((cacheMetadata) => {
63
63
  // Emits SDK_READY_FROM_CACHE
64
- if (cacheMetadata.isCacheValid) {
64
+ if (!cacheMetadata.initialCacheLoad) {
65
65
  readiness.splits.emit(SDK_SPLITS_CACHE_LOADED, cacheMetadata);
66
66
  }
67
67
  // Emits SDK_READY
@@ -92,12 +92,12 @@ export function syncManagerOnlineFactory(
92
92
  // @TODO once event, impression and telemetry storages support persistence, call when `validateCache` promise is resolved
93
93
  submitterManager.start(!isConsentGranted(settings));
94
94
 
95
- return Promise.resolve(storage.validateCache ? storage.validateCache() : { isCacheValid: false, lastUpdateTimestamp: null }).then((cacheMetadata) => {
95
+ return Promise.resolve(storage.validateCache ? storage.validateCache() : { initialCacheLoad: true /* Fallback: assume initial load when validateCache doesn't exist */ }).then((cacheMetadata) => {
96
96
  if (!running) return;
97
97
 
98
98
  if (startFirstTime) {
99
99
  // Emits SDK_READY_FROM_CACHE
100
- if (cacheMetadata.isCacheValid) {
100
+ if (!cacheMetadata.initialCacheLoad) {
101
101
  readiness.splits.emit(SDK_SPLITS_CACHE_LOADED, cacheMetadata);
102
102
  }
103
103
 
@@ -8,7 +8,7 @@ import { IStorageFactoryParams, IStorageSync } from '../../../storages/types';
8
8
 
9
9
  export function __InLocalStorageMockFactory(params: IStorageFactoryParams): IStorageSync {
10
10
  const result = InMemoryStorageCSFactory(params);
11
- result.validateCache = () => Promise.resolve({ isCacheValid: true, lastUpdateTimestamp: null }); // to emit SDK_READY_FROM_CACHE
11
+ result.validateCache = () => Promise.resolve({ initialCacheLoad: false /* Not an initial load, cache exists - to emit SDK_READY_FROM_CACHE */ });
12
12
  return result;
13
13
  }
14
14
  __InLocalStorageMockFactory.type = STORAGE_MEMORY;
@@ -83,7 +83,7 @@ interface ISharedSettings {
83
83
  * });
84
84
  * ```
85
85
  */
86
- getHeaderOverrides?: (context: { headers: Record<string, string> }) => Record<string, string>;
86
+ getHeaderOverrides?: (context: { headers: Record<string, string>; }) => Record<string, string>;
87
87
  };
88
88
  };
89
89
  /**
@@ -499,38 +499,34 @@ declare namespace SplitIO {
499
499
  /**
500
500
  * The type of update event.
501
501
  */
502
- type: 'FLAGS_UPDATE' | 'SEGMENTS_UPDATE'
502
+ type: SdkUpdateMetadataType;
503
503
  /**
504
504
  * The names of the flags or segments that were updated.
505
505
  */
506
- names: string[]
506
+ names: string[];
507
507
  }
508
508
 
509
509
  /**
510
- * Metadata keys for SDK update events.
511
- * Use the string literals directly: 'FLAGS_UPDATE' or 'SEGMENTS_UPDATE'
510
+ * Metadata type for SDK update events.
512
511
  */
513
- type SdkUpdateMetadataKeys = {
514
- FLAGS_UPDATE: 'FLAGS_UPDATE';
515
- SEGMENTS_UPDATE: 'SEGMENTS_UPDATE';
516
- };
512
+ type SdkUpdateMetadataType = 'FLAGS_UPDATE' | 'SEGMENTS_UPDATE';
517
513
 
518
514
  /**
519
515
  * Metadata for the ready events emitted when the SDK is ready to evaluate feature flags.
520
516
  */
521
517
  type SdkReadyMetadata = {
522
518
  /**
523
- * Indicates whether the SDK was loaded from cache initially.
524
- * - `true` when SDK_READY_FROM_CACHE is emitted from cache (before SDK_READY)
525
- * - `true` when SDK_READY is emitted and the SDK was ready from cache first
526
- * - `false` when SDK_READY_FROM_CACHE is emitted because SDK became ready without cache
527
- * - `false` when SDK_READY is emitted and the SDK was not ready from cache
519
+ * Indicates whether the SDK was loaded from cache initially. (fresh install or ready from cache)
520
+ * - `false` when SDK_READY_FROM_CACHE is emitted from cache (before SDK_READY)
521
+ * - `false` when SDK_READY is emitted and the SDK was ready from cache first
522
+ * - `true` when SDK_READY_FROM_CACHE is emitted because SDK became ready without cache
523
+ * - `true` when SDK_READY is emitted and the SDK was not ready from cache
528
524
  */
529
- initialCacheLoad: boolean
525
+ initialCacheLoad: boolean;
530
526
  /**
531
- * Timestamp in milliseconds since epoch when the event was emitted.
527
+ * Timestamp in milliseconds since epoch when the cache was last updated. Undefined if `initialCacheLoad` is `true`.
532
528
  */
533
- lastUpdateTimestamp: number | null
529
+ lastUpdateTimestamp?: number;
534
530
  }
535
531
 
536
532
  /**
@@ -662,7 +658,7 @@ declare namespace SplitIO {
662
658
  enabled: boolean;
663
659
  flagSpecVersion: string;
664
660
  requestOptions?: {
665
- getHeaderOverrides?: (context: { headers: Record<string, string> }) => Record<string, string>;
661
+ getHeaderOverrides?: (context: { headers: Record<string, string>; }) => Record<string, string>;
666
662
  };
667
663
  };
668
664
  readonly runtime: {
@@ -835,18 +831,19 @@ declare namespace SplitIO {
835
831
  * As it's meant to provide similar flexibility than event listeners, given that the SDK might be ready after a timeout event, the `whenReady` method will return a resolved promise once the SDK is ready.
836
832
  * You must handle the promise rejection to avoid an unhandled promise rejection error, or set the `startup.readyTimeout` configuration option to 0 to avoid the timeout and thus the rejection.
837
833
  *
838
- * @returns A promise that resolves once the SDK_READY event is emitted or rejects if the SDK has timedout.
834
+ * @returns A promise that resolves once the SDK_READY event is emitted or rejects if the SDK has timedout. The promise resolves with a metadata object that contains the `initialCacheLoad` property,
835
+ * which indicates whether the SDK_READY event was emitted together with the SDK_READY_FROM_CACHE event (i.e., fresh install/first app launch) or not (warm cache/subsequent app launch).
839
836
  */
840
- whenReady(): Promise<void>;
837
+ whenReady(): Promise<SdkReadyMetadata>;
841
838
  /**
842
839
  * Returns a promise that resolves when the SDK is ready for evaluations using cached data, which might not yet be synchronized with the backend (`SDK_READY_FROM_CACHE` event emitted), or rejected if the SDK has timedout (`SDK_READY_TIMED_OUT` event emitted).
843
840
  * As it's meant to provide similar flexibility than event listeners, given that the SDK might be ready from cache after a timeout event, the `whenReadyFromCache` method will return a resolved promise once the SDK is ready from cache.
844
841
  * You must handle the promise rejection to avoid an unhandled promise rejection error, or set the `startup.readyTimeout` configuration option to 0 to avoid the timeout and thus the rejection.
845
842
  *
846
- * @returns A promise that resolves once the SDK_READY_FROM_CACHE event is emitted or rejects if the SDK has timedout. The promise resolves with a boolean value that
847
- * indicates whether the SDK_READY_FROM_CACHE event was emitted together with the SDK_READY event (i.e., the SDK is ready and synchronized with the backend) or not.
843
+ * @returns A promise that resolves once the SDK_READY_FROM_CACHE event is emitted or rejects if the SDK has timedout. The promise resolves with a metadata object that contains the `initialCacheLoad` property,
844
+ * which indicates whether the SDK_READY_FROM_CACHE event was emitted together with the SDK_READY event (i.e., fresh install/first app launch) or not (warm cache/subsequent app launch).
848
845
  */
849
- whenReadyFromCache(): Promise<boolean>;
846
+ whenReadyFromCache(): Promise<SdkReadyMetadata>;
850
847
  }
851
848
  /**
852
849
  * Common definitions between clients for different environments interface.
@@ -1100,7 +1097,7 @@ declare namespace SplitIO {
1100
1097
  /**
1101
1098
  * Prerequisites for the feature flag.
1102
1099
  */
1103
- prerequisites: Array<{ flagName: string, treatments: string[] }>;
1100
+ prerequisites: Array<{ flagName: string; treatments: string[]; }>;
1104
1101
  };
1105
1102
  /**
1106
1103
  * A promise that resolves to a feature flag view or null if the feature flag is not found.
@@ -1370,13 +1367,13 @@ declare namespace SplitIO {
1370
1367
  /**
1371
1368
  * Fallback treatment for all flags.
1372
1369
  */
1373
- global?: Treatment | TreatmentWithConfig,
1370
+ global?: Treatment | TreatmentWithConfig;
1374
1371
  /**
1375
1372
  * Fallback treatments for specific flags. It takes precedence over the global fallback treatment.
1376
1373
  */
1377
1374
  byFlag?: {
1378
- [featureFlagName: string]: Treatment | TreatmentWithConfig
1379
- }
1375
+ [featureFlagName: string]: Treatment | TreatmentWithConfig;
1376
+ };
1380
1377
  }
1381
1378
  /**
1382
1379
  * Logger. Its interface details are not part of the public API. It shouldn't be used directly.
@@ -1603,7 +1600,7 @@ declare namespace SplitIO {
1603
1600
  * });
1604
1601
  * ```
1605
1602
  */
1606
- getHeaderOverrides?: (context: { headers: Record<string, string> }) => Record<string, string>;
1603
+ getHeaderOverrides?: (context: { headers: Record<string, string>; }) => Record<string, string>;
1607
1604
  /**
1608
1605
  * Custom Node.js HTTP(S) Agent used by the SDK for HTTP(S) requests.
1609
1606
  *