@cloudcare/browser-core 1.1.3 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/cjs/{cookie.js → browser/cookie.js} +6 -37
  2. package/cjs/browser/fetchObservable.js +91 -0
  3. package/cjs/browser/xhrObservable.js +118 -0
  4. package/cjs/configuration/configuration.js +70 -0
  5. package/cjs/configuration/transportConfiguration.js +64 -0
  6. package/cjs/console/consoleObservable.js +84 -0
  7. package/cjs/dataMap.js +26 -21
  8. package/cjs/error/trackRuntimeError.js +27 -0
  9. package/cjs/helper/catchUserErrors.js +20 -0
  10. package/cjs/helper/contextHistory.js +134 -0
  11. package/cjs/helper/createEventRateLimiter.js +47 -0
  12. package/cjs/helper/deviceInfo.js +8 -25
  13. package/cjs/helper/display.js +31 -0
  14. package/cjs/helper/enums.js +28 -2
  15. package/cjs/helper/errorTools.js +63 -2
  16. package/cjs/helper/instrumentMethod.js +93 -0
  17. package/cjs/helper/lifeCycle.js +5 -3
  18. package/cjs/helper/observable.js +40 -2
  19. package/cjs/helper/tools.js +185 -9
  20. package/cjs/index.js +153 -23
  21. package/cjs/init.js +17 -27
  22. package/cjs/report/reportObservable.js +112 -0
  23. package/cjs/session/sessionConstants.js +13 -0
  24. package/cjs/session/sessionCookieStore.js +188 -0
  25. package/cjs/session/sessionManagement.js +96 -0
  26. package/cjs/session/sessionStore.js +150 -0
  27. package/cjs/synthetics/syntheticsWorkerValues.js +32 -0
  28. package/cjs/synthetics/usr.js +32 -0
  29. package/cjs/tracekit/computeStackTrace.js +73 -563
  30. package/cjs/tracekit/index.js +3 -15
  31. package/cjs/tracekit/tracekit.js +113 -0
  32. package/cjs/transport/batch.js +332 -0
  33. package/cjs/transport/httpRequest.js +112 -0
  34. package/cjs/transport/index.js +29 -0
  35. package/cjs/transport/sendWithRetryStrategy.js +177 -0
  36. package/cjs/transport/startBatchWithReplica.js +24 -0
  37. package/esm/{cookie.js → browser/cookie.js} +4 -35
  38. package/esm/browser/fetchObservable.js +77 -0
  39. package/esm/browser/xhrObservable.js +106 -0
  40. package/esm/configuration/configuration.js +55 -0
  41. package/esm/configuration/transportConfiguration.js +54 -0
  42. package/esm/console/consoleObservable.js +70 -0
  43. package/esm/dataMap.js +26 -21
  44. package/esm/error/trackRuntimeError.js +16 -0
  45. package/esm/helper/catchUserErrors.js +12 -0
  46. package/esm/helper/contextHistory.js +106 -0
  47. package/esm/helper/createEventRateLimiter.js +38 -0
  48. package/esm/helper/deviceInfo.js +6 -25
  49. package/esm/helper/display.js +21 -0
  50. package/esm/helper/enums.js +25 -1
  51. package/esm/helper/errorTools.js +58 -3
  52. package/esm/helper/instrumentMethod.js +81 -0
  53. package/esm/helper/lifeCycle.js +5 -3
  54. package/esm/helper/observable.js +39 -3
  55. package/esm/helper/tools.js +147 -1
  56. package/esm/index.js +17 -7
  57. package/esm/init.js +17 -22
  58. package/esm/report/reportObservable.js +98 -0
  59. package/esm/session/sessionConstants.js +3 -0
  60. package/esm/session/sessionCookieStore.js +168 -0
  61. package/esm/session/sessionManagement.js +78 -0
  62. package/esm/session/sessionStore.js +139 -0
  63. package/esm/synthetics/syntheticsWorkerValues.js +15 -0
  64. package/esm/synthetics/usr.js +18 -0
  65. package/esm/tracekit/computeStackTrace.js +73 -557
  66. package/esm/tracekit/index.js +1 -1
  67. package/esm/tracekit/tracekit.js +103 -0
  68. package/esm/transport/batch.js +316 -0
  69. package/esm/transport/httpRequest.js +104 -0
  70. package/esm/transport/index.js +3 -0
  71. package/esm/transport/sendWithRetryStrategy.js +165 -0
  72. package/esm/transport/startBatchWithReplica.js +15 -0
  73. package/package.json +2 -2
  74. package/src/.DS_Store +0 -0
  75. package/src/{cookie.js → browser/cookie.js} +6 -34
  76. package/src/browser/fetchObservable.js +86 -0
  77. package/src/browser/xhrObservable.js +102 -0
  78. package/src/configuration/configuration.js +61 -0
  79. package/src/configuration/transportConfiguration.js +42 -0
  80. package/src/console/consoleObservable.js +65 -0
  81. package/src/dataMap.js +26 -21
  82. package/src/error/trackRuntimeError.js +19 -0
  83. package/src/helper/catchUserErrors.js +12 -0
  84. package/src/helper/contextHistory.js +85 -0
  85. package/src/helper/createEventRateLimiter.js +37 -0
  86. package/src/helper/deviceInfo.js +5 -51
  87. package/src/helper/display.js +21 -0
  88. package/src/helper/enums.js +38 -14
  89. package/src/helper/errorTools.js +76 -12
  90. package/src/helper/instrumentMethod.js +97 -0
  91. package/src/helper/lifeCycle.js +5 -3
  92. package/src/helper/observable.js +33 -2
  93. package/src/helper/tools.js +135 -4
  94. package/src/index.js +18 -7
  95. package/src/init.js +17 -18
  96. package/src/report/reportObservable.js +113 -0
  97. package/src/session/sessionConstants.js +3 -0
  98. package/src/session/sessionCookieStore.js +159 -0
  99. package/src/session/sessionManagement.js +89 -0
  100. package/src/session/sessionStore.js +139 -0
  101. package/src/synthetics/syntheticsWorkerValues.js +22 -0
  102. package/src/synthetics/usr.js +18 -0
  103. package/src/tracekit/computeStackTrace.js +75 -551
  104. package/src/tracekit/index.js +1 -1
  105. package/src/tracekit/tracekit.js +100 -0
  106. package/src/transport/batch.js +289 -0
  107. package/src/transport/httpRequest.js +109 -0
  108. package/src/transport/index.js +3 -0
  109. package/src/transport/sendWithRetryStrategy.js +186 -0
  110. package/src/transport/startBatchWithReplica.js +26 -0
  111. package/cjs/configuration.js +0 -193
  112. package/cjs/errorCollection.js +0 -167
  113. package/cjs/fetchProxy.js +0 -161
  114. package/cjs/helper/errorFilter.js +0 -47
  115. package/cjs/sessionManagement.js +0 -221
  116. package/cjs/tracekit/report.js +0 -289
  117. package/cjs/transport.js +0 -373
  118. package/cjs/xhrProxy.js +0 -122
  119. package/esm/configuration.js +0 -176
  120. package/esm/errorCollection.js +0 -141
  121. package/esm/fetchProxy.js +0 -115
  122. package/esm/helper/errorFilter.js +0 -38
  123. package/esm/sessionManagement.js +0 -195
  124. package/esm/tracekit/report.js +0 -273
  125. package/esm/transport.js +0 -357
  126. package/esm/xhrProxy.js +0 -110
  127. package/src/configuration.js +0 -161
  128. package/src/errorCollection.js +0 -170
  129. package/src/fetchProxy.js +0 -108
  130. package/src/helper/errorFilter.js +0 -38
  131. package/src/sessionManagement.js +0 -224
  132. package/src/tracekit/report.js +0 -284
  133. package/src/transport.js +0 -380
  134. package/src/xhrProxy.js +0 -106
@@ -9,25 +9,13 @@ Object.defineProperty(exports, "computeStackTrace", {
9
9
  return _computeStackTrace.computeStackTrace;
10
10
  }
11
11
  });
12
- Object.defineProperty(exports, "report", {
12
+ Object.defineProperty(exports, "startUnhandledErrorCollection", {
13
13
  enumerable: true,
14
14
  get: function get() {
15
- return _report.report;
16
- }
17
- });
18
- Object.defineProperty(exports, "subscribe", {
19
- enumerable: true,
20
- get: function get() {
21
- return _report.subscribe;
22
- }
23
- });
24
- Object.defineProperty(exports, "unsubscribe", {
25
- enumerable: true,
26
- get: function get() {
27
- return _report.unsubscribe;
15
+ return _tracekit.startUnhandledErrorCollection;
28
16
  }
29
17
  });
30
18
 
31
19
  var _computeStackTrace = require("./computeStackTrace");
32
20
 
33
- var _report = require("./report");
21
+ var _tracekit = require("./tracekit");
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.startUnhandledErrorCollection = startUnhandledErrorCollection;
7
+
8
+ var _instrumentMethod = require("../helper/instrumentMethod");
9
+
10
+ var _computeStackTrace = require("./computeStackTrace");
11
+
12
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_types
13
+ var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/;
14
+ /**
15
+ * Cross-browser collection of unhandled errors
16
+ *
17
+ * Supports:
18
+ * - Firefox: full stack trace with line numbers, plus column number
19
+ * on top frame; column number is not guaranteed
20
+ * - Opera: full stack trace with line and column numbers
21
+ * - Chrome: full stack trace with line and column numbers
22
+ * - Safari: line and column number for the top frame only; some frames
23
+ * may be missing, and column number is not guaranteed
24
+ * - IE: line and column number for the top frame only; some frames
25
+ * may be missing, and column number is not guaranteed
26
+ *
27
+ * In theory, TraceKit should work on all of the following versions:
28
+ * - IE5.5+ (only 8.0 tested)
29
+ * - Firefox 0.9+ (only 3.5+ tested)
30
+ * - Opera 7+ (only 10.50 tested; versions 9 and earlier may require
31
+ * Exceptions Have Stacktrace to be enabled in opera:config)
32
+ * - Safari 3+ (only 4+ tested)
33
+ * - Chrome 1+ (only 5+ tested)
34
+ * - Konqueror 3.5+ (untested)
35
+ *
36
+ * Tries to catch all unhandled errors and report them to the
37
+ * callback.
38
+ *
39
+ * Callbacks receive a StackTrace object as described in the
40
+ * computeStackTrace docs.
41
+ *
42
+ * @memberof TraceKit
43
+ * @namespace
44
+ */
45
+
46
+ function startUnhandledErrorCollection(callback) {
47
+ var _instrumentOnError = instrumentOnError(callback);
48
+
49
+ var _instrumentUnhandledRejection = instrumentUnhandledRejection(callback);
50
+
51
+ return {
52
+ stop: function stop() {
53
+ _instrumentOnError.stop();
54
+
55
+ _instrumentUnhandledRejection.stop();
56
+ }
57
+ };
58
+ }
59
+ /**
60
+ * Install a global onerror handler
61
+ */
62
+
63
+
64
+ function instrumentOnError(callback) {
65
+ return (0, _instrumentMethod.instrumentMethodAndCallOriginal)(window, 'onerror', {
66
+ before: function before(message, url, lineNo, columnNo, errorObj) {
67
+ var stack;
68
+
69
+ if (errorObj) {
70
+ stack = (0, _computeStackTrace.computeStackTrace)(errorObj);
71
+ callback(stack, errorObj);
72
+ } else {
73
+ var location = {
74
+ url: url,
75
+ column: columnNo,
76
+ line: lineNo
77
+ };
78
+ var name;
79
+ var msg = message;
80
+
81
+ if ({}.toString.call(message) === '[object String]') {
82
+ var groups = ERROR_TYPES_RE.exec(msg);
83
+
84
+ if (groups) {
85
+ name = groups[1];
86
+ msg = groups[2];
87
+ }
88
+ }
89
+
90
+ stack = {
91
+ name: name,
92
+ message: typeof msg === 'string' ? msg : undefined,
93
+ stack: [location]
94
+ };
95
+ callback(stack, message);
96
+ }
97
+ }
98
+ });
99
+ }
100
+ /**
101
+ * Install a global onunhandledrejection handler
102
+ */
103
+
104
+
105
+ function instrumentUnhandledRejection(callback) {
106
+ return (0, _instrumentMethod.instrumentMethodAndCallOriginal)(window, 'onunhandledrejection', {
107
+ before: function before(e) {
108
+ var reason = e.reason || 'Empty reason';
109
+ var stack = (0, _computeStackTrace.computeStackTrace)(reason);
110
+ callback(stack, reason);
111
+ }
112
+ });
113
+ }
@@ -0,0 +1,332 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.processedMessageByDataMap = exports.Batch = void 0;
7
+
8
+ var _display = require("../helper/display");
9
+
10
+ var _tools = require("../helper/tools");
11
+
12
+ var _dataMap = require("../dataMap");
13
+
14
+ var _enums = require("../helper/enums");
15
+
16
+ // https://en.wikipedia.org/wiki/UTF-8
17
+ // eslint-disable-next-line no-control-regex
18
+ var HAS_MULTI_BYTES_CHARACTERS = /[^\u0000-\u007F]/;
19
+ var CUSTOM_KEYS = 'custom_keys';
20
+
21
+ var processedMessageByDataMap = function processedMessageByDataMap(message) {
22
+ if (!message || !message.type) return {
23
+ rowStr: '',
24
+ rowData: undefined
25
+ };
26
+ var rowData = {
27
+ tags: {},
28
+ fields: {}
29
+ };
30
+ var hasFileds = false;
31
+ var rowStr = '';
32
+ (0, _tools.each)(_dataMap.dataMap, function (value, key) {
33
+ if (value.type === message.type) {
34
+ rowStr += key + ',';
35
+ rowData.measurement = key;
36
+ var tagsStr = [];
37
+ var tags = (0, _tools.extend)({}, _dataMap.commonTags, value.tags);
38
+ var filterFileds = ['date', 'type', CUSTOM_KEYS]; // 已经在datamap中定义过的fields和tags
39
+
40
+ (0, _tools.each)(tags, function (value_path, _key) {
41
+ var _value = (0, _tools.findByPath)(message, value_path);
42
+
43
+ filterFileds.push(_key);
44
+
45
+ if (_value || (0, _tools.isNumber)(_value)) {
46
+ rowData.tags[_key] = (0, _tools.escapeJsonValue)(_value);
47
+ tagsStr.push((0, _tools.escapeRowData)(_key) + '=' + (0, _tools.escapeRowData)(_value));
48
+ }
49
+ });
50
+ var fieldsStr = [];
51
+ (0, _tools.each)(value.fields, function (_value, _key) {
52
+ if ((0, _tools.isArray)(_value) && _value.length === 2) {
53
+ var type = _value[0],
54
+ value_path = _value[1];
55
+
56
+ var _valueData = (0, _tools.findByPath)(message, value_path);
57
+
58
+ filterFileds.push(_key);
59
+
60
+ if (_valueData || (0, _tools.isNumber)(_valueData)) {
61
+ rowData.fields[_key] = _valueData; // 这里不需要转译
62
+ // _valueData =
63
+ // type === 'string'
64
+ // ? '"' +
65
+ // _valueData.replace(/[\\]*"/g, '"').replace(/"/g, '\\"') +
66
+ // '"'
67
+ // : escapeRowData(_valueData)
68
+
69
+ fieldsStr.push((0, _tools.escapeRowData)(_key) + '=' + (0, _tools.escapeRowField)(_valueData));
70
+ }
71
+ } else if ((0, _tools.isString)(_value)) {
72
+ var _valueData = (0, _tools.findByPath)(message, _value);
73
+
74
+ filterFileds.push(_key);
75
+
76
+ if (_valueData || (0, _tools.isNumber)(_valueData)) {
77
+ rowData.fields[_key] = _valueData; // 这里不需要转译
78
+
79
+ fieldsStr.push((0, _tools.escapeRowData)(_key) + '=' + (0, _tools.escapeRowField)(_valueData));
80
+ }
81
+ }
82
+ });
83
+
84
+ if (message.tags && (0, _tools.isObject)(message.tags) && !(0, _tools.isEmptyObject)(message.tags)) {
85
+ // 自定义tag, 存储成field
86
+ var _tagKeys = [];
87
+ (0, _tools.each)(message.tags, function (_value, _key) {
88
+ // 如果和之前tag重名,则舍弃
89
+ if (filterFileds.indexOf(_key) > -1) return;
90
+ filterFileds.push(_key);
91
+
92
+ if (_value || (0, _tools.isNumber)(_value)) {
93
+ _tagKeys.push(_key);
94
+
95
+ rowData.fields[_key] = _value; // 这里不需要转译
96
+
97
+ fieldsStr.push((0, _tools.escapeRowData)(_key) + '=' + (0, _tools.escapeRowField)(_value));
98
+ }
99
+ });
100
+
101
+ if (_tagKeys.length) {
102
+ rowData.fields[CUSTOM_KEYS] = (0, _tools.escapeRowField)(_tagKeys);
103
+ fieldsStr.push((0, _tools.escapeRowData)(CUSTOM_KEYS) + '=' + (0, _tools.escapeRowField)(_tagKeys));
104
+ }
105
+ }
106
+
107
+ if (message.type === _enums.RumEventType.LOGGER) {
108
+ // 这里处理日志类型数据自定义字段
109
+ (0, _tools.each)(message, function (value, key) {
110
+ if (filterFileds.indexOf(key) === -1 && ((0, _tools.isNumber)(value) || (0, _tools.isString)(value) || (0, _tools.isBoolean)(value))) {
111
+ rowData.fields[key] = value; // 这里不需要转译
112
+
113
+ fieldsStr.push((0, _tools.escapeRowData)(key) + '=' + (0, _tools.escapeRowField)(value));
114
+ }
115
+ });
116
+ }
117
+
118
+ if (tagsStr.length) {
119
+ rowStr += tagsStr.join(',');
120
+ }
121
+
122
+ if (fieldsStr.length) {
123
+ rowStr += ' ';
124
+ rowStr += fieldsStr.join(',');
125
+ hasFileds = true;
126
+ }
127
+
128
+ rowStr = rowStr + ' ' + message.date;
129
+ rowData.time = (0, _tools.toServerDuration)(message.date); // 这里不需要转译
130
+ }
131
+ });
132
+ return {
133
+ rowStr: hasFileds ? rowStr : '',
134
+ rowData: hasFileds ? rowData : undefined
135
+ };
136
+ };
137
+
138
+ exports.processedMessageByDataMap = processedMessageByDataMap;
139
+
140
+ var batch = function batch(request, batchMessagesLimit, batchBytesLimit, messageBytesLimit, flushTimeout, beforeUnloadCallback) {
141
+ this.pushOnlyBuffer = [];
142
+ this.upsertBuffer = {};
143
+ this.bufferBytesCount = 0;
144
+ this.bufferMessagesCount = 0;
145
+ this.request = request;
146
+ this.batchMessagesLimit = batchMessagesLimit;
147
+ this.batchBytesLimit = batchBytesLimit;
148
+ this.messageBytesLimit = messageBytesLimit;
149
+ this.flushTimeout = flushTimeout;
150
+
151
+ if (typeof beforeUnloadCallback === 'function') {
152
+ this.beforeUnloadCallback = beforeUnloadCallback;
153
+ } else {
154
+ this.beforeUnloadCallback = _tools.noop;
155
+ }
156
+
157
+ this.setupFlushOnExit();
158
+ this.flushPeriodically();
159
+ };
160
+
161
+ batch.prototype.add = function (message) {
162
+ this.addOrUpdate(message);
163
+ };
164
+
165
+ batch.prototype.upsert = function (message, key) {
166
+ this.addOrUpdate(message, key);
167
+ };
168
+
169
+ batch.prototype.flush = function (sendFn) {
170
+ if (typeof sendFn !== 'function') {
171
+ sendFn = this.request.send;
172
+ }
173
+
174
+ if (this.bufferMessagesCount !== 0) {
175
+ var messages = this.pushOnlyBuffer.concat((0, _tools.values)(this.upsertBuffer));
176
+ var bytesCount = this.bufferBytesCount;
177
+ this.pushOnlyBuffer = [];
178
+ this.upsertBuffer = {};
179
+ this.bufferBytesCount = 0;
180
+ this.bufferMessagesCount = 0;
181
+
182
+ if (messages.length > 0) {
183
+ sendFn({
184
+ data: messages.join('\n'),
185
+ bytesCount: bytesCount
186
+ });
187
+ }
188
+ }
189
+ };
190
+
191
+ batch.prototype.flushOnExit = function () {
192
+ this.flush(this.request.sendOnExit);
193
+ };
194
+
195
+ batch.prototype.computeBytesCount = function (candidate) {
196
+ // Accurate bytes count computations can degrade performances when there is a lot of events to process
197
+ if (!HAS_MULTI_BYTES_CHARACTERS.test(candidate)) {
198
+ return candidate.length;
199
+ }
200
+
201
+ if (window.TextEncoder !== undefined) {
202
+ return new TextEncoder().encode(candidate).length;
203
+ }
204
+
205
+ return new Blob([candidate]).size;
206
+ };
207
+
208
+ batch.prototype.addOrUpdate = function (message, key) {
209
+ var _process = this.process(message);
210
+
211
+ var processedMessage = _process.processedMessage;
212
+ var messageBytesCount = _process.messageBytesCount;
213
+
214
+ if (messageBytesCount >= this.messageBytesLimit) {
215
+ _display.display.warn('Discarded a message whose size was bigger than the maximum allowed size ' + this.messageBytesLimit + 'KB.');
216
+
217
+ return;
218
+ }
219
+
220
+ if (this.hasMessageFor(key)) {
221
+ this.remove(key);
222
+ }
223
+
224
+ if (this.willReachedBytesLimitWith(messageBytesCount)) {
225
+ this.flush();
226
+ }
227
+
228
+ this.push(processedMessage, messageBytesCount, key);
229
+
230
+ if (this.isFull()) {
231
+ this.flush();
232
+ }
233
+ };
234
+
235
+ batch.prototype.process = function (message) {
236
+ var processedMessage = processedMessageByDataMap(message).rowStr;
237
+ var messageBytesCount = this.computeBytesCount(processedMessage);
238
+ return {
239
+ processedMessage: processedMessage,
240
+ messageBytesCount: messageBytesCount
241
+ };
242
+ };
243
+
244
+ batch.prototype.push = function (processedMessage, messageBytesCount, key) {
245
+ if (this.bufferMessagesCount > 0) {
246
+ // \n separator at serialization
247
+ this.bufferBytesCount += 1;
248
+ }
249
+
250
+ if (key !== undefined) {
251
+ this.upsertBuffer[key] = processedMessage;
252
+ } else {
253
+ this.pushOnlyBuffer.push(processedMessage);
254
+ }
255
+
256
+ this.bufferBytesCount += messageBytesCount;
257
+ this.bufferMessagesCount += 1;
258
+ };
259
+
260
+ batch.prototype.remove = function (key) {
261
+ var removedMessage = this.upsertBuffer[key];
262
+ delete this.upsertBuffer[key];
263
+ var messageBytesCount = this.computeBytesCount(removedMessage);
264
+ this.bufferBytesCount -= messageBytesCount;
265
+ this.bufferMessagesCount -= 1;
266
+
267
+ if (this.bufferMessagesCount > 0) {
268
+ this.bufferBytesCount -= 1;
269
+ }
270
+ };
271
+
272
+ batch.prototype.hasMessageFor = function (key) {
273
+ return key !== undefined && this.upsertBuffer[key] !== undefined;
274
+ };
275
+
276
+ batch.prototype.willReachedBytesLimitWith = function (messageBytesCount) {
277
+ // byte of the separator at the end of the message
278
+ return this.bufferBytesCount + messageBytesCount + 1 >= this.batchBytesLimit;
279
+ };
280
+
281
+ batch.prototype.isFull = function () {
282
+ return this.bufferMessagesCount === this.batchMessagesLimit || this.bufferBytesCount >= this.batchBytesLimit;
283
+ };
284
+
285
+ batch.prototype.flushPeriodically = function () {
286
+ var _this = this;
287
+
288
+ setTimeout(function () {
289
+ _this.flush();
290
+
291
+ _this.flushPeriodically();
292
+ }, this.flushTimeout);
293
+ };
294
+
295
+ batch.prototype.setupFlushOnExit = function () {
296
+ /**
297
+ * With sendBeacon, requests are guaranteed to be successfully sent during document unload
298
+ */
299
+ // @ts-ignore this function is not always defined
300
+ var _this = this;
301
+
302
+ if (navigator.sendBeacon) {
303
+ /**
304
+ * beforeunload is called before visibilitychange
305
+ * register first to be sure to be called before flush on beforeunload
306
+ * caveat: unload can still be canceled by another listener
307
+ */
308
+ (0, _tools.addEventListener)(window, _enums.DOM_EVENT.BEFORE_UNLOAD, this.beforeUnloadCallback);
309
+ /**
310
+ * Only event that guarantee to fire on mobile devices when the page transitions to background state
311
+ * (e.g. when user switches to a different application, goes to homescreen, etc), or is being unloaded.
312
+ */
313
+
314
+ (0, _tools.addEventListener)(document, _enums.DOM_EVENT.VISIBILITY_CHANGE, function () {
315
+ if (document.visibilityState === 'hidden') {
316
+ _this.flushOnExit();
317
+ }
318
+ });
319
+ /**
320
+ * Safari does not support yet to send a request during:
321
+ * - a visibility change during doc unload (cf: https://bugs.webkit.org/show_bug.cgi?id=194897)
322
+ * - a page hide transition (cf: https://bugs.webkit.org/show_bug.cgi?id=188329)
323
+ */
324
+
325
+ (0, _tools.addEventListener)(window, _enums.DOM_EVENT.BEFORE_UNLOAD, function () {
326
+ return _this.flushOnExit();
327
+ });
328
+ }
329
+ };
330
+
331
+ var Batch = batch;
332
+ exports.Batch = Batch;
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createHttpRequest = createHttpRequest;
7
+ exports.fetchKeepAliveStrategy = fetchKeepAliveStrategy;
8
+
9
+ var _sendWithRetryStrategy = require("./sendWithRetryStrategy");
10
+
11
+ /**
12
+ * Use POST request without content type to:
13
+ * - avoid CORS preflight requests
14
+ * - allow usage of sendBeacon
15
+ *
16
+ * multiple elements are sent separated by \n in order
17
+ * to be parsed correctly without content type header
18
+ */
19
+ function addBatchPrecision(url) {
20
+ if (!url) return url;
21
+ return url + (url.indexOf('?') === -1 ? '?' : '&') + 'precision=ms';
22
+ }
23
+
24
+ function createHttpRequest(endpointUrl, bytesLimit, reportError) {
25
+ var retryState = (0, _sendWithRetryStrategy.newRetryState)();
26
+
27
+ var sendStrategyForRetry = function sendStrategyForRetry(payload, onResponse) {
28
+ return fetchKeepAliveStrategy(endpointUrl, bytesLimit, payload, onResponse);
29
+ };
30
+
31
+ return {
32
+ send: function send(payload) {
33
+ (0, _sendWithRetryStrategy.sendWithRetryStrategy)(payload, retryState, sendStrategyForRetry, reportError);
34
+ },
35
+
36
+ /**
37
+ * Since fetch keepalive behaves like regular fetch on Firefox,
38
+ * keep using sendBeaconStrategy on exit
39
+ */
40
+ sendOnExit: function sendOnExit(payload) {
41
+ sendBeaconStrategy(endpointUrl, bytesLimit, payload);
42
+ }
43
+ };
44
+ }
45
+
46
+ function sendBeaconStrategy(endpointUrl, bytesLimit, payload) {
47
+ var data = payload.data;
48
+ var bytesCount = payload.bytesCount;
49
+ var url = addBatchPrecision(endpointUrl);
50
+ var canUseBeacon = !!navigator.sendBeacon && bytesCount < bytesLimit;
51
+
52
+ if (canUseBeacon) {
53
+ try {
54
+ var isQueued = navigator.sendBeacon(url, data);
55
+
56
+ if (isQueued) {
57
+ return;
58
+ }
59
+ } catch (e) {// reportBeaconError(e)
60
+ }
61
+ }
62
+
63
+ sendXHR(url, data);
64
+ }
65
+
66
+ function fetchKeepAliveStrategy(endpointUrl, bytesLimit, payload, onResponse) {
67
+ var data = payload.data;
68
+ var bytesCount = payload.bytesCount;
69
+ var url = addBatchPrecision(endpointUrl);
70
+ var canUseKeepAlive = isKeepAliveSupported() && bytesCount < bytesLimit;
71
+
72
+ if (canUseKeepAlive) {
73
+ fetch(url, {
74
+ method: 'POST',
75
+ body: data,
76
+ keepalive: true
77
+ }).then(function (response) {
78
+ if (typeof onResponse === 'function') {
79
+ onResponse({
80
+ status: response.status
81
+ });
82
+ }
83
+ }, function () {
84
+ // failed to queue the request
85
+ sendXHR(url, data, onResponse);
86
+ });
87
+ } else {
88
+ sendXHR(url, data, onResponse);
89
+ }
90
+ }
91
+
92
+ function isKeepAliveSupported() {
93
+ // Request can throw, cf https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#errors
94
+ try {
95
+ return window.Request && 'keepalive' in new Request('http://a');
96
+ } catch (_unused) {
97
+ return false;
98
+ }
99
+ }
100
+
101
+ function sendXHR(url, data, onResponse) {
102
+ var request = new XMLHttpRequest();
103
+ request.open('POST', url, true);
104
+ request.send(data);
105
+ request.addEventListener('loadend', function () {
106
+ if (typeof onResponse === 'function') {
107
+ onResponse({
108
+ status: request.status
109
+ });
110
+ }
111
+ });
112
+ }
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ Object.defineProperty(exports, "Batch", {
7
+ enumerable: true,
8
+ get: function get() {
9
+ return _batch.Batch;
10
+ }
11
+ });
12
+ Object.defineProperty(exports, "createHttpRequest", {
13
+ enumerable: true,
14
+ get: function get() {
15
+ return _httpRequest.createHttpRequest;
16
+ }
17
+ });
18
+ Object.defineProperty(exports, "startBatchWithReplica", {
19
+ enumerable: true,
20
+ get: function get() {
21
+ return _startBatchWithReplica.startBatchWithReplica;
22
+ }
23
+ });
24
+
25
+ var _httpRequest = require("./httpRequest");
26
+
27
+ var _batch = require("./batch");
28
+
29
+ var _startBatchWithReplica = require("./startBatchWithReplica");