@splitsoftware/splitio-commons 3.1.1-rc.0 → 3.1.1-rc.10

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 (241) hide show
  1. package/CHANGES.txt +10 -1
  2. package/cjs/evaluator/condition/index.js +1 -1
  3. package/cjs/evaluator/fallbackTreatmentsCalculator/fallbackSanitizer/index.js +8 -5
  4. package/cjs/evaluator/index.js +69 -81
  5. package/cjs/listeners/browser.js +1 -2
  6. package/cjs/listeners/node.js +4 -4
  7. package/cjs/logger/constants.js +20 -15
  8. package/cjs/logger/messages/debug.js +6 -5
  9. package/cjs/logger/messages/error.js +3 -3
  10. package/cjs/logger/messages/info.js +4 -3
  11. package/cjs/logger/messages/warn.js +7 -6
  12. package/cjs/presets/serverSide.js +2 -2
  13. package/cjs/readiness/constants.js +4 -5
  14. package/cjs/readiness/readinessManager.js +23 -23
  15. package/cjs/readiness/sdkReadinessManager.js +17 -1
  16. package/cjs/sdkClient/client.js +34 -9
  17. package/cjs/sdkClient/clientInputValidation.js +17 -6
  18. package/cjs/sdkClient/sdkClient.js +60 -3
  19. package/cjs/sdkFactory/index.js +15 -11
  20. package/cjs/sdkManager/index.js +5 -5
  21. package/cjs/services/decorateHeaders.js +1 -2
  22. package/cjs/services/splitApi.js +1 -14
  23. package/cjs/services/splitHttpClient.js +5 -3
  24. package/cjs/storages/AbstractSplitsCacheAsync.js +51 -0
  25. package/cjs/storages/AbstractSplitsCacheSync.js +76 -0
  26. package/cjs/storages/KeyBuilder.js +6 -6
  27. package/cjs/storages/KeyBuilderCS.js +5 -5
  28. package/cjs/storages/KeyBuilderSS.js +2 -2
  29. package/cjs/storages/getRolloutPlan.js +3 -3
  30. package/cjs/storages/inLocalStorage/MySegmentsCacheInLocal.js +2 -1
  31. package/cjs/storages/inLocalStorage/RBSegmentsCacheInLocal.js +10 -10
  32. package/cjs/storages/inLocalStorage/SplitsCacheInLocal.js +194 -0
  33. package/cjs/storages/inLocalStorage/index.js +6 -6
  34. package/cjs/storages/inLocalStorage/validateCache.js +3 -3
  35. package/cjs/storages/inMemory/InMemoryStorage.js +4 -4
  36. package/cjs/storages/inMemory/InMemoryStorageCS.js +5 -5
  37. package/cjs/storages/inMemory/RBSegmentsCacheInMemory.js +5 -5
  38. package/cjs/storages/inMemory/SegmentsCacheInMemory.js +1 -1
  39. package/cjs/storages/inMemory/SplitsCacheInMemory.js +121 -0
  40. package/cjs/storages/inMemory/TelemetryCacheInMemory.js +5 -5
  41. package/cjs/storages/inRedis/RBSegmentsCacheInRedis.js +1 -1
  42. package/cjs/storages/inRedis/RedisAdapter.js +8 -5
  43. package/cjs/storages/inRedis/{DefinitionsCacheInRedis.js → SplitsCacheInRedis.js} +77 -77
  44. package/cjs/storages/inRedis/index.js +2 -2
  45. package/cjs/storages/pluggable/RBSegmentsCachePluggable.js +1 -1
  46. package/cjs/storages/pluggable/SplitsCachePluggable.js +212 -0
  47. package/cjs/storages/pluggable/index.js +2 -2
  48. package/cjs/storages/setRolloutPlan.js +4 -4
  49. package/cjs/storages/utils.js +0 -1
  50. package/cjs/sync/offline/syncTasks/fromObjectSyncTask.js +5 -5
  51. package/cjs/sync/polling/fetchers/splitChangesFetcher.js +15 -24
  52. package/cjs/sync/polling/pollingManagerCS.js +20 -20
  53. package/cjs/sync/polling/pollingManagerSS.js +15 -15
  54. package/cjs/sync/polling/syncTasks/segmentsSyncTask.js +3 -2
  55. package/cjs/sync/polling/syncTasks/splitsSyncTask.js +13 -0
  56. package/cjs/sync/polling/updaters/mySegmentsUpdater.js +3 -3
  57. package/cjs/sync/polling/updaters/segmentChangesUpdater.js +6 -6
  58. package/cjs/sync/polling/updaters/{definitionChangesUpdater.js → splitChangesUpdater.js} +68 -65
  59. package/cjs/sync/streaming/AuthClient/index.js +1 -1
  60. package/cjs/sync/streaming/SSEHandler/NotificationKeeper.js +1 -1
  61. package/cjs/sync/streaming/SSEHandler/index.js +1 -1
  62. package/cjs/sync/streaming/UpdateWorkers/{DefinitionsUpdateWorker.js → SplitsUpdateWorker.js} +19 -16
  63. package/cjs/sync/streaming/constants.js +3 -3
  64. package/cjs/sync/streaming/parseUtils.js +11 -11
  65. package/cjs/sync/streaming/pushManager.js +16 -16
  66. package/cjs/sync/submitters/eventsSubmitter.js +1 -1
  67. package/cjs/sync/submitters/impressionCountsSubmitter.js +1 -1
  68. package/cjs/sync/submitters/impressionsSubmitter.js +4 -5
  69. package/cjs/sync/submitters/telemetrySubmitter.js +4 -3
  70. package/cjs/sync/submitters/uniqueKeysSubmitter.js +1 -1
  71. package/cjs/sync/syncManagerOnline.js +7 -12
  72. package/cjs/utils/Backoff.js +0 -20
  73. package/cjs/utils/inputValidation/index.js +7 -7
  74. package/cjs/utils/inputValidation/isOperational.js +4 -4
  75. package/cjs/utils/inputValidation/{definition.js → split.js} +10 -10
  76. package/cjs/utils/inputValidation/{definitionExistence.js → splitExistence.js} +6 -6
  77. package/cjs/utils/inputValidation/splits.js +25 -0
  78. package/cjs/utils/labels/index.js +3 -3
  79. package/cjs/utils/settingsValidation/index.js +0 -2
  80. package/cjs/utils/settingsValidation/splitFilters.js +3 -3
  81. package/cjs/utils/settingsValidation/url.js +2 -6
  82. package/esm/evaluator/condition/index.js +1 -1
  83. package/esm/evaluator/fallbackTreatmentsCalculator/fallbackSanitizer/index.js +8 -5
  84. package/esm/evaluator/index.js +69 -80
  85. package/esm/listeners/browser.js +1 -2
  86. package/esm/listeners/node.js +4 -4
  87. package/esm/logger/constants.js +17 -12
  88. package/esm/logger/messages/debug.js +6 -5
  89. package/esm/logger/messages/error.js +3 -3
  90. package/esm/logger/messages/info.js +4 -3
  91. package/esm/logger/messages/warn.js +7 -6
  92. package/esm/presets/serverSide.js +2 -2
  93. package/esm/readiness/constants.js +3 -4
  94. package/esm/readiness/readinessManager.js +24 -24
  95. package/esm/readiness/sdkReadinessManager.js +18 -2
  96. package/esm/sdkClient/client.js +35 -9
  97. package/esm/sdkClient/clientInputValidation.js +19 -8
  98. package/esm/sdkClient/sdkClient.js +60 -3
  99. package/esm/sdkFactory/index.js +16 -12
  100. package/esm/sdkManager/index.js +6 -6
  101. package/esm/services/decorateHeaders.js +1 -2
  102. package/esm/services/splitApi.js +1 -14
  103. package/esm/services/splitHttpClient.js +5 -3
  104. package/esm/storages/AbstractSplitsCacheAsync.js +48 -0
  105. package/esm/storages/AbstractSplitsCacheSync.js +71 -0
  106. package/esm/storages/KeyBuilder.js +6 -6
  107. package/esm/storages/KeyBuilderCS.js +5 -5
  108. package/esm/storages/KeyBuilderSS.js +2 -2
  109. package/esm/storages/getRolloutPlan.js +3 -3
  110. package/esm/storages/inLocalStorage/MySegmentsCacheInLocal.js +2 -1
  111. package/esm/storages/inLocalStorage/RBSegmentsCacheInLocal.js +7 -7
  112. package/esm/storages/inLocalStorage/SplitsCacheInLocal.js +191 -0
  113. package/esm/storages/inLocalStorage/index.js +6 -6
  114. package/esm/storages/inLocalStorage/validateCache.js +3 -3
  115. package/esm/storages/inMemory/InMemoryStorage.js +4 -4
  116. package/esm/storages/inMemory/InMemoryStorageCS.js +5 -5
  117. package/esm/storages/inMemory/RBSegmentsCacheInMemory.js +2 -2
  118. package/esm/storages/inMemory/SegmentsCacheInMemory.js +1 -1
  119. package/esm/storages/inMemory/SplitsCacheInMemory.js +118 -0
  120. package/esm/storages/inMemory/TelemetryCacheInMemory.js +5 -5
  121. package/esm/storages/inRedis/RBSegmentsCacheInRedis.js +1 -1
  122. package/esm/storages/inRedis/RedisAdapter.js +8 -5
  123. package/esm/storages/inRedis/{DefinitionsCacheInRedis.js → SplitsCacheInRedis.js} +76 -76
  124. package/esm/storages/inRedis/index.js +2 -2
  125. package/esm/storages/pluggable/RBSegmentsCachePluggable.js +1 -1
  126. package/esm/storages/pluggable/SplitsCachePluggable.js +209 -0
  127. package/esm/storages/pluggable/index.js +2 -2
  128. package/esm/storages/setRolloutPlan.js +4 -4
  129. package/esm/storages/utils.js +0 -1
  130. package/esm/sync/offline/syncTasks/fromObjectSyncTask.js +6 -6
  131. package/esm/sync/polling/fetchers/splitChangesFetcher.js +16 -25
  132. package/esm/sync/polling/pollingManagerCS.js +17 -17
  133. package/esm/sync/polling/pollingManagerSS.js +15 -15
  134. package/esm/sync/polling/syncTasks/segmentsSyncTask.js +3 -2
  135. package/esm/sync/polling/syncTasks/splitsSyncTask.js +9 -0
  136. package/esm/sync/polling/updaters/mySegmentsUpdater.js +3 -3
  137. package/esm/sync/polling/updaters/segmentChangesUpdater.js +7 -7
  138. package/esm/sync/polling/updaters/{definitionChangesUpdater.js → splitChangesUpdater.js} +68 -65
  139. package/esm/sync/streaming/AuthClient/index.js +1 -1
  140. package/esm/sync/streaming/SSEHandler/NotificationKeeper.js +2 -2
  141. package/esm/sync/streaming/SSEHandler/index.js +2 -2
  142. package/esm/sync/streaming/UpdateWorkers/{DefinitionsUpdateWorker.js → SplitsUpdateWorker.js} +18 -15
  143. package/esm/sync/streaming/constants.js +2 -2
  144. package/esm/sync/streaming/parseUtils.js +9 -9
  145. package/esm/sync/streaming/pushManager.js +18 -18
  146. package/esm/sync/submitters/eventsSubmitter.js +1 -1
  147. package/esm/sync/submitters/impressionCountsSubmitter.js +1 -1
  148. package/esm/sync/submitters/impressionsSubmitter.js +4 -5
  149. package/esm/sync/submitters/telemetrySubmitter.js +4 -3
  150. package/esm/sync/submitters/uniqueKeysSubmitter.js +1 -1
  151. package/esm/sync/syncManagerOnline.js +6 -11
  152. package/esm/utils/Backoff.js +0 -20
  153. package/esm/utils/inputValidation/index.js +3 -3
  154. package/esm/utils/inputValidation/isOperational.js +4 -4
  155. package/esm/utils/inputValidation/{definition.js → split.js} +8 -8
  156. package/esm/utils/inputValidation/splitExistence.js +15 -0
  157. package/esm/utils/inputValidation/splits.js +21 -0
  158. package/esm/utils/labels/index.js +2 -2
  159. package/esm/utils/settingsValidation/index.js +0 -2
  160. package/esm/utils/settingsValidation/splitFilters.js +3 -3
  161. package/esm/utils/settingsValidation/url.js +2 -6
  162. package/package.json +6 -7
  163. package/src/dtos/types.ts +1 -1
  164. package/src/evaluator/Engine.ts +3 -3
  165. package/src/evaluator/condition/index.ts +2 -2
  166. package/src/evaluator/index.ts +27 -35
  167. package/src/evaluator/types.ts +2 -6
  168. package/src/presets/serverSide.ts +3 -3
  169. package/src/sdkClient/client.ts +22 -24
  170. package/src/sdkClient/sdkLifecycle.ts +3 -0
  171. package/src/services/authProvider.ts +41 -19
  172. package/src/services/secureSplitHttpClient.ts +10 -18
  173. package/src/services/serviceApi.ts +27 -24
  174. package/src/services/splitApi.ts +10 -9
  175. package/src/services/types.ts +5 -4
  176. package/src/storages/inRedis/RedisAdapter.ts +8 -5
  177. package/src/sync/polling/pollingManagerCS.ts +80 -78
  178. package/src/sync/polling/pollingManagerSS.ts +49 -45
  179. package/src/sync/polling/updaters/definitionChangesUpdater.ts +3 -3
  180. package/src/sync/polling/updaters/segmentChangesUpdater.ts +1 -1
  181. package/src/sync/streaming/AuthClient/index.ts +14 -15
  182. package/src/sync/streaming/AuthClient/types.ts +9 -13
  183. package/src/sync/streaming/SSEClient/index.ts +2 -2
  184. package/src/sync/streaming/SSEClient/types.ts +2 -2
  185. package/src/sync/streaming/SSEHandler/index.ts +2 -1
  186. package/src/sync/streaming/SSEHandler/types.ts +2 -2
  187. package/src/sync/streaming/constants.ts +1 -0
  188. package/src/sync/streaming/pushManager.ts +32 -42
  189. package/src/sync/streaming/types.ts +3 -2
  190. package/src/sync/submitters/impressionsSubmitter.ts +3 -3
  191. package/src/sync/submitters/types.ts +2 -2
  192. package/src/sync/syncManagerOnline.ts +2 -8
  193. package/src/utils/Backoff.ts +16 -4
  194. package/types/splitio.d.ts +5 -4
  195. package/cjs/platform/browser.js +0 -15
  196. package/cjs/platform/getEventSource/browser.js +0 -8
  197. package/cjs/platform/getEventSource/eventsource.js +0 -480
  198. package/cjs/platform/getEventSource/node.js +0 -26
  199. package/cjs/platform/getFetch/browser.js +0 -9
  200. package/cjs/platform/getFetch/node.js +0 -27
  201. package/cjs/platform/getOptions/node.js +0 -25
  202. package/cjs/platform/node.js +0 -17
  203. package/cjs/sdkClient/sdkLifecycle.js +0 -72
  204. package/cjs/sdkClient/trackMethod.js +0 -56
  205. package/cjs/services/authProvider.js +0 -67
  206. package/cjs/services/secureSplitHttpClient.js +0 -39
  207. package/cjs/services/serviceApi.js +0 -145
  208. package/cjs/storages/AbstractDefinitionsCacheAsync.js +0 -51
  209. package/cjs/storages/AbstractDefinitionsCacheSync.js +0 -76
  210. package/cjs/storages/inLocalStorage/DefinitionsCacheInLocal.js +0 -194
  211. package/cjs/storages/inMemory/DefinitionsCacheInMemory.js +0 -121
  212. package/cjs/storages/pluggable/DefinitionsCachePluggable.js +0 -212
  213. package/cjs/sync/polling/syncTasks/definitionsSyncTask.js +0 -13
  214. package/cjs/utils/EventEmitter.js +0 -391
  215. package/cjs/utils/filter/bloomFilter.js +0 -37
  216. package/cjs/utils/inputValidation/definitions.js +0 -25
  217. package/cjs/utils/inputValidation/target.js +0 -22
  218. package/esm/platform/browser.js +0 -12
  219. package/esm/platform/getEventSource/browser.js +0 -4
  220. package/esm/platform/getEventSource/eventsource.js +0 -480
  221. package/esm/platform/getEventSource/node.js +0 -20
  222. package/esm/platform/getFetch/browser.js +0 -5
  223. package/esm/platform/getFetch/node.js +0 -22
  224. package/esm/platform/getOptions/node.js +0 -20
  225. package/esm/platform/node.js +0 -14
  226. package/esm/sdkClient/sdkLifecycle.js +0 -68
  227. package/esm/sdkClient/trackMethod.js +0 -52
  228. package/esm/services/authProvider.js +0 -63
  229. package/esm/services/secureSplitHttpClient.js +0 -35
  230. package/esm/services/serviceApi.js +0 -141
  231. package/esm/storages/AbstractDefinitionsCacheAsync.js +0 -48
  232. package/esm/storages/AbstractDefinitionsCacheSync.js +0 -71
  233. package/esm/storages/inLocalStorage/DefinitionsCacheInLocal.js +0 -191
  234. package/esm/storages/inMemory/DefinitionsCacheInMemory.js +0 -118
  235. package/esm/storages/pluggable/DefinitionsCachePluggable.js +0 -209
  236. package/esm/sync/polling/syncTasks/definitionsSyncTask.js +0 -9
  237. package/esm/utils/EventEmitter.js +0 -387
  238. package/esm/utils/filter/bloomFilter.js +0 -33
  239. package/esm/utils/inputValidation/definitionExistence.js +0 -15
  240. package/esm/utils/inputValidation/definitions.js +0 -21
  241. package/esm/utils/inputValidation/target.js +0 -18
@@ -1,480 +0,0 @@
1
- "use strict";
2
- /* eslint-disable no-prototype-builtins */
3
- /* eslint-disable no-restricted-syntax */
4
- /*
5
- Modified version of "eventsource" v1.1.2 package (https://www.npmjs.com/package/eventsource/v/1.1.2) that accepts a custom agent.
6
- Requires CommonJS and Node.js globals (require, process, Buffer).
7
-
8
- The MIT License
9
-
10
- Copyright (c) EventSource GitHub organization
11
-
12
- Permission is hereby granted, free of charge, to any person obtaining
13
- a copy of this software and associated documentation files (the
14
- "Software"), to deal in the Software without restriction, including
15
- without limitation the rights to use, copy, modify, merge, publish,
16
- distribute, sublicense, and/or sell copies of the Software, and to
17
- permit persons to whom the Software is furnished to do so, subject to
18
- the following conditions:
19
-
20
- The above copyright notice and this permission notice shall be
21
- included in all copies or substantial portions of the Software.
22
-
23
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27
- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28
- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29
- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30
- */
31
- var parse = require('url').parse;
32
- var events = require('events');
33
- var https = require('https');
34
- var http = require('http');
35
- var util = require('util');
36
- var httpsOptions = [
37
- 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers',
38
- 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity'
39
- ];
40
- var bom = [239, 187, 191];
41
- var colon = 58;
42
- var space = 32;
43
- var lineFeed = 10;
44
- var carriageReturn = 13;
45
- function hasBom(buf) {
46
- return bom.every(function (charCode, index) {
47
- return buf[index] === charCode;
48
- });
49
- }
50
- /**
51
- * Creates a new EventSource object
52
- *
53
- * @param {String} url the URL to which to connect
54
- * @param {Object} [eventSourceInitDict] extra init params. See README for details.
55
- * @api public
56
- **/
57
- function EventSource(url, eventSourceInitDict) {
58
- var readyState = EventSource.CONNECTING;
59
- var headers = eventSourceInitDict && eventSourceInitDict.headers;
60
- var hasNewOrigin = false;
61
- Object.defineProperty(this, 'readyState', {
62
- get: function () {
63
- return readyState;
64
- }
65
- });
66
- Object.defineProperty(this, 'url', {
67
- get: function () {
68
- return url;
69
- }
70
- });
71
- var self = this;
72
- self.reconnectInterval = 1000;
73
- self.connectionInProgress = false;
74
- var reconnectUrl = null;
75
- function onConnectionClosed(message) {
76
- if (readyState === EventSource.CLOSED)
77
- return;
78
- readyState = EventSource.CONNECTING;
79
- _emit('error', new Event('error', { message: message }));
80
- // The url may have been changed by a temporary redirect. If that's the case,
81
- // revert it now, and flag that we are no longer pointing to a new origin
82
- if (reconnectUrl) {
83
- url = reconnectUrl;
84
- reconnectUrl = null;
85
- hasNewOrigin = false;
86
- }
87
- setTimeout(function () {
88
- if (readyState !== EventSource.CONNECTING || self.connectionInProgress) {
89
- return;
90
- }
91
- self.connectionInProgress = true;
92
- connect();
93
- }, self.reconnectInterval);
94
- }
95
- var req;
96
- var lastEventId = '';
97
- if (headers && headers['Last-Event-ID']) {
98
- lastEventId = headers['Last-Event-ID'];
99
- delete headers['Last-Event-ID'];
100
- }
101
- var discardTrailingNewline = false;
102
- var data = '';
103
- var eventName = '';
104
- function connect() {
105
- var options = parse(url);
106
- var isSecure = options.protocol === 'https:';
107
- options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' };
108
- if (lastEventId)
109
- options.headers['Last-Event-ID'] = lastEventId;
110
- if (headers) {
111
- var reqHeaders = hasNewOrigin ? removeUnsafeHeaders(headers) : headers;
112
- for (var i in reqHeaders) {
113
- var header = reqHeaders[i];
114
- if (header) {
115
- options.headers[i] = header;
116
- }
117
- }
118
- }
119
- // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`,
120
- // but for now exists as a backwards-compatibility layer
121
- options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized);
122
- if (eventSourceInitDict && eventSourceInitDict.createConnection !== undefined) {
123
- options.createConnection = eventSourceInitDict.createConnection;
124
- }
125
- // If specify agent, use it.
126
- if (eventSourceInitDict && eventSourceInitDict.agent !== undefined) {
127
- options.agent = eventSourceInitDict.agent;
128
- }
129
- // If specify http proxy, make the request to sent to the proxy server,
130
- // and include the original url in path and Host headers
131
- var useProxy = eventSourceInitDict && eventSourceInitDict.proxy;
132
- if (useProxy) {
133
- var proxy = parse(eventSourceInitDict.proxy);
134
- isSecure = proxy.protocol === 'https:';
135
- options.protocol = isSecure ? 'https:' : 'http:';
136
- options.path = url;
137
- options.headers.Host = options.host;
138
- options.hostname = proxy.hostname;
139
- options.host = proxy.host;
140
- options.port = proxy.port;
141
- }
142
- // If https options are specified, merge them into the request options
143
- if (eventSourceInitDict && eventSourceInitDict.https) {
144
- for (var optName in eventSourceInitDict.https) {
145
- if (httpsOptions.indexOf(optName) === -1) {
146
- continue;
147
- }
148
- var option = eventSourceInitDict.https[optName];
149
- if (option !== undefined) {
150
- options[optName] = option;
151
- }
152
- }
153
- }
154
- // Pass this on to the XHR
155
- if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) {
156
- options.withCredentials = eventSourceInitDict.withCredentials;
157
- }
158
- req = (isSecure ? https : http).request(options, function (res) {
159
- self.connectionInProgress = false;
160
- // Handle HTTP errors
161
- if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) {
162
- _emit('error', new Event('error', { status: res.statusCode, message: res.statusMessage }));
163
- onConnectionClosed();
164
- return;
165
- }
166
- // Handle HTTP redirects
167
- if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) {
168
- var location = res.headers.location;
169
- if (!location) {
170
- // Server sent redirect response without Location header.
171
- _emit('error', new Event('error', { status: res.statusCode, message: res.statusMessage }));
172
- return;
173
- }
174
- var prevOrigin = getOrigin(url);
175
- var nextOrigin = getOrigin(location);
176
- hasNewOrigin = prevOrigin !== nextOrigin;
177
- if (res.statusCode === 307)
178
- reconnectUrl = url;
179
- url = location;
180
- process.nextTick(connect);
181
- return;
182
- }
183
- if (res.statusCode !== 200) {
184
- _emit('error', new Event('error', { status: res.statusCode, message: res.statusMessage }));
185
- return self.close();
186
- }
187
- readyState = EventSource.OPEN;
188
- res.on('close', function () {
189
- res.removeAllListeners('close');
190
- res.removeAllListeners('end');
191
- onConnectionClosed();
192
- });
193
- res.on('end', function () {
194
- res.removeAllListeners('close');
195
- res.removeAllListeners('end');
196
- onConnectionClosed();
197
- });
198
- _emit('open', new Event('open'));
199
- // text/event-stream parser adapted from webkit's
200
- // Source/WebCore/page/EventSource.cpp
201
- var isFirst = true;
202
- var buf;
203
- var startingPos = 0;
204
- var startingFieldLength = -1;
205
- res.on('data', function (chunk) {
206
- buf = buf ? Buffer.concat([buf, chunk]) : chunk;
207
- if (isFirst && hasBom(buf)) {
208
- buf = buf.slice(bom.length);
209
- }
210
- isFirst = false;
211
- var pos = 0;
212
- var length = buf.length;
213
- while (pos < length) {
214
- if (discardTrailingNewline) {
215
- if (buf[pos] === lineFeed) {
216
- ++pos;
217
- }
218
- discardTrailingNewline = false;
219
- }
220
- var lineLength = -1;
221
- var fieldLength = startingFieldLength;
222
- var c;
223
- for (var i = startingPos; lineLength < 0 && i < length; ++i) {
224
- c = buf[i];
225
- if (c === colon) {
226
- if (fieldLength < 0) {
227
- fieldLength = i - pos;
228
- }
229
- }
230
- else if (c === carriageReturn) {
231
- discardTrailingNewline = true;
232
- lineLength = i - pos;
233
- }
234
- else if (c === lineFeed) {
235
- lineLength = i - pos;
236
- }
237
- }
238
- if (lineLength < 0) {
239
- startingPos = length - pos;
240
- startingFieldLength = fieldLength;
241
- break;
242
- }
243
- else {
244
- startingPos = 0;
245
- startingFieldLength = -1;
246
- }
247
- parseEventStreamLine(buf, pos, fieldLength, lineLength);
248
- pos += lineLength + 1;
249
- }
250
- if (pos === length) {
251
- buf = void 0;
252
- }
253
- else if (pos > 0) {
254
- buf = buf.slice(pos);
255
- }
256
- });
257
- });
258
- req.on('error', function (err) {
259
- self.connectionInProgress = false;
260
- onConnectionClosed(err.message);
261
- });
262
- if (req.setNoDelay)
263
- req.setNoDelay(true);
264
- req.end();
265
- }
266
- connect();
267
- function _emit() {
268
- if (self.listeners(arguments[0]).length > 0) {
269
- self.emit.apply(self, arguments);
270
- }
271
- }
272
- this._close = function () {
273
- if (readyState === EventSource.CLOSED)
274
- return;
275
- readyState = EventSource.CLOSED;
276
- if (req.abort)
277
- req.abort();
278
- if (req.xhr && req.xhr.abort)
279
- req.xhr.abort();
280
- };
281
- function parseEventStreamLine(buf, pos, fieldLength, lineLength) {
282
- if (lineLength === 0) {
283
- if (data.length > 0) {
284
- var type = eventName || 'message';
285
- _emit(type, new MessageEvent(type, {
286
- data: data.slice(0, -1),
287
- lastEventId: lastEventId,
288
- origin: getOrigin(url)
289
- }));
290
- data = '';
291
- }
292
- eventName = void 0;
293
- }
294
- else if (fieldLength > 0) {
295
- var noValue = fieldLength < 0;
296
- var step = 0;
297
- var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString();
298
- if (noValue) {
299
- step = lineLength;
300
- }
301
- else if (buf[pos + fieldLength + 1] !== space) {
302
- step = fieldLength + 1;
303
- }
304
- else {
305
- step = fieldLength + 2;
306
- }
307
- pos += step;
308
- var valueLength = lineLength - step;
309
- var value = buf.slice(pos, pos + valueLength).toString();
310
- if (field === 'data') {
311
- data += value + '\n';
312
- }
313
- else if (field === 'event') {
314
- eventName = value;
315
- }
316
- else if (field === 'id') {
317
- lastEventId = value;
318
- }
319
- else if (field === 'retry') {
320
- var retry = parseInt(value, 10);
321
- if (!Number.isNaN(retry)) {
322
- self.reconnectInterval = retry;
323
- }
324
- }
325
- }
326
- }
327
- }
328
- module.exports = EventSource;
329
- util.inherits(EventSource, events.EventEmitter);
330
- EventSource.prototype.constructor = EventSource; // make stacktraces readable
331
- ['open', 'error', 'message'].forEach(function (method) {
332
- Object.defineProperty(EventSource.prototype, 'on' + method, {
333
- /**
334
- * Returns the current listener
335
- *
336
- * @return {Mixed} the set function or undefined
337
- * @api private
338
- */
339
- get: function get() {
340
- var listener = this.listeners(method)[0];
341
- return listener ? (listener._listener ? listener._listener : listener) : undefined;
342
- },
343
- /**
344
- * Start listening for events
345
- *
346
- * @param {Function} listener the listener
347
- * @return {Mixed} the set function or undefined
348
- * @api private
349
- */
350
- set: function set(listener) {
351
- this.removeAllListeners(method);
352
- this.addEventListener(method, listener);
353
- }
354
- });
355
- });
356
- /**
357
- * Ready states
358
- */
359
- Object.defineProperty(EventSource, 'CONNECTING', { enumerable: true, value: 0 });
360
- Object.defineProperty(EventSource, 'OPEN', { enumerable: true, value: 1 });
361
- Object.defineProperty(EventSource, 'CLOSED', { enumerable: true, value: 2 });
362
- EventSource.prototype.CONNECTING = 0;
363
- EventSource.prototype.OPEN = 1;
364
- EventSource.prototype.CLOSED = 2;
365
- /**
366
- * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed)
367
- *
368
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close
369
- * @api public
370
- */
371
- EventSource.prototype.close = function () {
372
- this._close();
373
- };
374
- /**
375
- * Emulates the W3C Browser based WebSocket interface using addEventListener.
376
- *
377
- * @param {String} type A string representing the event type to listen out for
378
- * @param {Function} listener callback
379
- * @see https://developer.mozilla.org/en/DOM/element.addEventListener
380
- * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
381
- * @api public
382
- */
383
- EventSource.prototype.addEventListener = function addEventListener(type, listener) {
384
- if (typeof listener === 'function') {
385
- // store a reference so we can return the original function again
386
- listener._listener = listener;
387
- this.on(type, listener);
388
- }
389
- };
390
- /**
391
- * Emulates the W3C Browser based WebSocket interface using dispatchEvent.
392
- *
393
- * @param {Event} event An event to be dispatched
394
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
395
- * @api public
396
- */
397
- EventSource.prototype.dispatchEvent = function dispatchEvent(event) {
398
- if (!event.type) {
399
- throw new Error('UNSPECIFIED_EVENT_TYPE_ERR');
400
- }
401
- // if event is instance of an CustomEvent (or has 'details' property),
402
- // send the detail object as the payload for the event
403
- this.emit(event.type, event.detail);
404
- };
405
- /**
406
- * Emulates the W3C Browser based WebSocket interface using removeEventListener.
407
- *
408
- * @param {String} type A string representing the event type to remove
409
- * @param {Function} listener callback
410
- * @see https://developer.mozilla.org/en/DOM/element.removeEventListener
411
- * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
412
- * @api public
413
- */
414
- EventSource.prototype.removeEventListener = function removeEventListener(type, listener) {
415
- if (typeof listener === 'function') {
416
- listener._listener = undefined;
417
- this.removeListener(type, listener);
418
- }
419
- };
420
- /**
421
- * W3C Event
422
- *
423
- * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event
424
- * @api private
425
- */
426
- function Event(type, optionalProperties) {
427
- Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true });
428
- if (optionalProperties) {
429
- for (var f in optionalProperties) {
430
- if (optionalProperties.hasOwnProperty(f)) {
431
- Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true });
432
- }
433
- }
434
- }
435
- }
436
- /**
437
- * W3C MessageEvent
438
- *
439
- * @see http://www.w3.org/TR/webmessaging/#event-definitions
440
- * @api private
441
- */
442
- function MessageEvent(type, eventInitDict) {
443
- Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true });
444
- for (var f in eventInitDict) {
445
- if (eventInitDict.hasOwnProperty(f)) {
446
- Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true });
447
- }
448
- }
449
- }
450
- /**
451
- * Returns a new object of headers that does not include any authorization and cookie headers
452
- *
453
- * @param {Object} headers An object of headers ({[headerName]: headerValue})
454
- * @return {Object} a new object of headers
455
- * @api private
456
- */
457
- function removeUnsafeHeaders(headers) {
458
- var safe = {};
459
- for (var key in headers) {
460
- if (/^(cookie|authorization)$/i.test(key)) {
461
- continue;
462
- }
463
- safe[key] = headers[key];
464
- }
465
- return safe;
466
- }
467
- /**
468
- * Transform an URL to a valid origin value.
469
- *
470
- * @param {String|Object} url URL to transform to it's origin.
471
- * @returns {String} The origin.
472
- * @api private
473
- */
474
- function getOrigin(url) {
475
- if (typeof url === 'string')
476
- url = parse(url);
477
- if (!url.protocol || !url.hostname)
478
- return 'null';
479
- return (url.protocol + '//' + url.host).toLowerCase();
480
- }
@@ -1,20 +0,0 @@
1
- var __isCustom = false;
2
- var __eventSource;
3
- // This function is only exposed for testing purposes.
4
- export function __setEventSource(eventSource) {
5
- __eventSource = eventSource;
6
- __isCustom = true;
7
- }
8
- export function __restore() {
9
- __isCustom = false;
10
- }
11
- export function getEventSource() {
12
- // returns EventSource at `eventsource` package. If not available, return global EventSource or undefined
13
- try {
14
- return __isCustom ? __eventSource : require('./eventsource');
15
- }
16
- catch (error) {
17
- // eslint-disable-next-line no-undef -- Feature detection for EventSource
18
- return typeof EventSource === 'function' ? EventSource : undefined;
19
- }
20
- }
@@ -1,5 +0,0 @@
1
- // It doesn't return a ponyfill if global fetch is not available
2
- export function getFetch() {
3
- // eslint-disable-next-line no-undef
4
- return typeof fetch === 'function' ? fetch : undefined;
5
- }
@@ -1,22 +0,0 @@
1
- var nodeFetch;
2
- try {
3
- nodeFetch = require('node-fetch');
4
- // Handle node-fetch issue https://github.com/node-fetch/node-fetch/issues/1037
5
- if (typeof nodeFetch !== 'function')
6
- nodeFetch = nodeFetch.default;
7
- }
8
- catch (error) {
9
- // Try to access global fetch if `node-fetch` package couldn't be imported (e.g., not in a Node environment)
10
- // eslint-disable-next-line no-undef
11
- nodeFetch = typeof fetch === 'function' ? fetch : undefined;
12
- }
13
- // This function is only exposed for testing purposes.
14
- export function __setFetch(fetch) {
15
- nodeFetch = fetch;
16
- }
17
- /**
18
- * Retrieves 'node-fetch', a Fetch API polyfill for Node.js, with fallback to global 'fetch' if available.
19
- */
20
- export function getFetch() {
21
- return nodeFetch;
22
- }
@@ -1,20 +0,0 @@
1
- // @TODO
2
- // 1- handle multiple protocols automatically
3
- // 2- destroy it once the sdk is destroyed
4
- import https from 'https';
5
- import { find } from '../../utils/lang';
6
- var agent = new https.Agent({
7
- keepAlive: true,
8
- keepAliveMsecs: 1500
9
- });
10
- export function getOptions(settings) {
11
- // User provided options take precedence
12
- if (settings.sync.requestOptions)
13
- return settings.sync.requestOptions;
14
- // If some URL is not HTTPS, we don't use the agent, to let the SDK connect to HTTP endpoints
15
- if (find(settings.urls, function (url) { return !url.startsWith('https:'); }))
16
- return;
17
- return {
18
- agent: agent
19
- };
20
- }
@@ -1,14 +0,0 @@
1
- import { EventEmitter } from 'events';
2
- import { getFetch } from '../platform/getFetch/node';
3
- import { getEventSource } from '../platform/getEventSource/node';
4
- import { getOptions } from '../platform/getOptions/node';
5
- import { NodeSignalListener } from '../listeners/node';
6
- import { now } from '../utils/timeTracker/now/node';
7
- export var platform = {
8
- getFetch: getFetch,
9
- getEventSource: getEventSource,
10
- getOptions: getOptions,
11
- EventEmitter: EventEmitter,
12
- now: now,
13
- SignalListener: NodeSignalListener
14
- };
@@ -1,68 +0,0 @@
1
- import { releaseApiKey, validateAndTrackApiKey } from '../utils/inputValidation/apiKey';
2
- import { LOCALHOST_MODE } from '../utils/constants';
3
- var COOLDOWN_TIME_IN_MILLIS = 1000;
4
- /**
5
- * Creates an Sdk client, i.e., a base client with status, init, flush and destroy interface
6
- */
7
- export function sdkLifecycleFactory(params, isSharedClient) {
8
- var sdkReadinessManager = params.sdkReadinessManager, syncManager = params.syncManager, storage = params.storage, settings = params.settings, telemetryTracker = params.telemetryTracker, impressionsTracker = params.impressionsTracker, platform = params.platform, serviceApi = params.serviceApi;
9
- var hasInit = false;
10
- var lastActionTime = 0;
11
- var signalListener = platform.SignalListener && settings.mode !== LOCALHOST_MODE ? new platform.SignalListener(params) : undefined;
12
- function __cooldown(func, time) {
13
- var now = Date.now();
14
- //get the actual time elapsed in ms
15
- var timeElapsed = now - lastActionTime;
16
- //check if the time elapsed is less than desired cooldown
17
- if (timeElapsed < time) {
18
- //if yes, return message with remaining time in seconds
19
- settings.log.warn("Flush cooldown, remaining time ".concat((time - timeElapsed) / 1000, " seconds"));
20
- return Promise.resolve();
21
- }
22
- else {
23
- //Do the requested action and re-assign the lastActionTime
24
- lastActionTime = now;
25
- return func();
26
- }
27
- }
28
- function __flush() {
29
- return syncManager ? syncManager.flush() : Promise.resolve();
30
- }
31
- return {
32
- init: function () {
33
- if (hasInit)
34
- return;
35
- hasInit = true;
36
- if (!isSharedClient) {
37
- validateAndTrackApiKey(settings.log, settings.core.authorizationKey);
38
- sdkReadinessManager.readinessManager.init();
39
- impressionsTracker.start();
40
- syncManager && syncManager.start();
41
- signalListener && signalListener.start();
42
- }
43
- },
44
- flush: function () {
45
- // @TODO define cooldown time
46
- return __cooldown(__flush, COOLDOWN_TIME_IN_MILLIS);
47
- },
48
- destroy: function () {
49
- hasInit = false;
50
- // Mark the SDK as destroyed immediately
51
- sdkReadinessManager.readinessManager.destroy();
52
- // For main client, cleanup the SDK Key, listeners and scheduled jobs, and record stat before flushing data
53
- if (!isSharedClient) {
54
- releaseApiKey(settings.core.authorizationKey);
55
- telemetryTracker.sessionLength();
56
- signalListener && signalListener.stop();
57
- impressionsTracker.stop();
58
- }
59
- // Stop background jobs
60
- syncManager && syncManager.stop();
61
- serviceApi && serviceApi.stop();
62
- return __flush().then(function () {
63
- // Cleanup storage
64
- return storage.destroy();
65
- });
66
- }
67
- };
68
- }
@@ -1,52 +0,0 @@
1
- import { thenable } from '../utils/promise/thenable';
2
- import { getMatching } from '../utils/key';
3
- import { validateTrafficTypeExistence } from '../utils/inputValidation/trafficTypeExistence';
4
- import { validateKey, validateTrafficType, validateEvent, validateEventValue, validateEventProperties, validateIfNotDestroyed } from '../utils/inputValidation';
5
- import { TRACK, TRACK_FN_LABEL } from '../utils/constants';
6
- import { isConsumerMode } from '../utils/settingsValidation/mode';
7
- /**
8
- * Creates a standalone `track` function with input validation.
9
- * Reusable by FF SDK client, Configs SDK, and thin-client SDK.
10
- */
11
- export function trackMethodFactory(params, warnTTExistence) {
12
- if (warnTTExistence === void 0) { warnTTExistence = true; }
13
- var settings = params.settings, definitions = params.storage.definitions, telemetryTracker = params.telemetryTracker, eventTracker = params.eventTracker, readinessManager = params.sdkReadinessManager.readinessManager;
14
- var log = settings.log, mode = settings.mode;
15
- var isAsync = isConsumerMode(mode);
16
- return function track(maybeKey, maybeTT, maybeEvent, maybeEventValue, maybeProperties) {
17
- // Input validation
18
- var key = validateKey(log, maybeKey, TRACK_FN_LABEL);
19
- var trafficTypeName = validateTrafficType(log, maybeTT, TRACK_FN_LABEL);
20
- var eventTypeId = validateEvent(log, maybeEvent, TRACK_FN_LABEL);
21
- var value = validateEventValue(log, maybeEventValue, TRACK_FN_LABEL);
22
- var _a = validateEventProperties(log, maybeProperties, TRACK_FN_LABEL), properties = _a.properties, size = _a.size;
23
- var isNotDestroyed = validateIfNotDestroyed(log, readinessManager, TRACK_FN_LABEL);
24
- if (!(isNotDestroyed && key && trafficTypeName && eventTypeId && value !== false && properties !== false)) {
25
- return isAsync ? Promise.resolve(false) : false;
26
- }
27
- // Core logic
28
- var stopTelemetryTracker = telemetryTracker.trackEval(TRACK);
29
- var eventData = {
30
- eventTypeId: eventTypeId,
31
- trafficTypeName: trafficTypeName,
32
- value: value,
33
- timestamp: Date.now(),
34
- key: getMatching(key),
35
- properties: properties
36
- };
37
- // 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.
38
- if (warnTTExistence)
39
- validateTrafficTypeExistence(log, readinessManager, definitions, mode, trafficTypeName, TRACK_FN_LABEL);
40
- var result = eventTracker.track(eventData, size);
41
- if (thenable(result)) {
42
- return result.then(function (result) {
43
- stopTelemetryTracker();
44
- return result;
45
- });
46
- }
47
- else {
48
- stopTelemetryTracker();
49
- return result;
50
- }
51
- };
52
- }