@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
package/esm/xhrProxy.js DELETED
@@ -1,110 +0,0 @@
1
- import { normalizeUrl } from './helper/urlPolyfill';
2
- import { each, relativeNow, clocksNow, elapsed, extend, timeStampNow } from './helper/tools';
3
- var xhrProxySingleton;
4
- var beforeSendCallbacks = [];
5
- var onRequestCompleteCallbacks = [];
6
- var originalXhrOpen;
7
- var originalXhrSend;
8
- var originalXhrAbort;
9
- export function startXhrProxy() {
10
- if (!xhrProxySingleton) {
11
- proxyXhr();
12
- xhrProxySingleton = {
13
- beforeSend: function beforeSend(callback) {
14
- beforeSendCallbacks.push(callback);
15
- },
16
- onRequestComplete: function onRequestComplete(callback) {
17
- onRequestCompleteCallbacks.push(callback);
18
- }
19
- };
20
- }
21
-
22
- return xhrProxySingleton;
23
- }
24
- export function resetXhrProxy() {
25
- if (xhrProxySingleton) {
26
- xhrProxySingleton = undefined;
27
- beforeSendCallbacks.length = 0;
28
- onRequestCompleteCallbacks.length = 0;
29
- XMLHttpRequest.prototype.open = originalXhrOpen;
30
- XMLHttpRequest.prototype.send = originalXhrSend;
31
- XMLHttpRequest.prototype.abort = originalXhrAbort;
32
- }
33
- }
34
-
35
- function proxyXhr() {
36
- originalXhrOpen = XMLHttpRequest.prototype.open;
37
- originalXhrSend = XMLHttpRequest.prototype.send;
38
- originalXhrAbort = XMLHttpRequest.prototype.abort;
39
-
40
- XMLHttpRequest.prototype.open = function (method, url) {
41
- // WARN: since this data structure is tied to the instance, it is shared by both logs and rum
42
- // and can be used by different code versions depending on customer setup
43
- // so it should stay compatible with older versions
44
- this._dataflux_xhr = {
45
- method: method,
46
- startTime: -1,
47
- // computed in send call
48
- url: normalizeUrl(url)
49
- };
50
- return originalXhrOpen.apply(this, arguments);
51
- };
52
-
53
- XMLHttpRequest.prototype.send = function (body) {
54
- var _this = this;
55
-
56
- if (this._dataflux_xhr) {
57
- var xhrPendingContext = this._dataflux_xhr;
58
- xhrPendingContext.startTime = relativeNow();
59
- xhrPendingContext.startClocks = clocksNow();
60
- xhrPendingContext.isAborted = false;
61
- var originalOnreadystatechange = this.onreadystatechange;
62
-
63
- this.onreadystatechange = function () {
64
- if (this.readyState === XMLHttpRequest.DONE) {
65
- reportXhr();
66
- }
67
-
68
- if (originalOnreadystatechange) {
69
- originalOnreadystatechange.apply(this, arguments);
70
- }
71
- };
72
-
73
- var hasBeenReported = false;
74
-
75
- var reportXhr = function reportXhr() {
76
- _this.removeEventListener('loadend', reportXhr);
77
-
78
- if (hasBeenReported) {
79
- return;
80
- }
81
-
82
- hasBeenReported = true;
83
- var xhrCompleteContext = extend({}, xhrPendingContext, {
84
- duration: elapsed(xhrPendingContext.startClocks.timeStamp, timeStampNow()),
85
- response: _this.response,
86
- status: _this.status
87
- });
88
- each(onRequestCompleteCallbacks, function (callback) {
89
- callback(xhrCompleteContext, _this);
90
- });
91
- };
92
-
93
- _this.addEventListener('loadend', reportXhr);
94
-
95
- each(beforeSendCallbacks, function (callback) {
96
- callback(xhrPendingContext, _this);
97
- });
98
- }
99
-
100
- return originalXhrSend.apply(_this, arguments);
101
- };
102
-
103
- XMLHttpRequest.prototype.abort = function () {
104
- if (this._dataflux_xhr) {
105
- this._dataflux_xhr.isAborted = true;
106
- }
107
-
108
- return originalXhrAbort.apply(this, arguments);
109
- };
110
- }
@@ -1,161 +0,0 @@
1
- import {
2
- ONE_KILO_BYTE,
3
- ONE_SECOND,
4
- extend2Lev,
5
- isArray,
6
- includes,
7
- isFunction,
8
- isBoolean,
9
- values
10
- } from './helper/tools'
11
- import { getCurrentSite } from './cookie'
12
- import { haveSameOrigin } from './helper/urlPolyfill'
13
- import { TraceType } from './helper/enums'
14
- var TRIM_REGIX = /^\s+|\s+$/g
15
- export var DEFAULT_CONFIGURATION = {
16
- resourceSampleRate: 100,
17
- sampleRate: 100,
18
- flushTimeout: 30 * ONE_SECOND,
19
- maxErrorsByMinute: 3000,
20
- /**
21
- * Logs intake limit
22
- */
23
- maxBatchSize: 50,
24
- maxMessageSize: 256 * ONE_KILO_BYTE,
25
- /**
26
- * arbitrary value, byte precision not needed
27
- */
28
- requestErrorResponseLengthLimit: 32 * ONE_KILO_BYTE,
29
-
30
- /**
31
- * beacon payload max queue size implementation is 64kb
32
- * ensure that we leave room for logs, rum and potential other users
33
- */
34
- batchBytesLimit: 16 * ONE_KILO_BYTE,
35
- datakitUrl: '',
36
- logsEndpoint: '',
37
- traceType: TraceType.DDTRACE,
38
- traceId128Bit: false,
39
- trackInteractions: false, //是否开启交互action收集
40
- allowedDDTracingOrigins: [], //废弃
41
- allowedTracingOrigins:[], // 新增
42
- isServiceSampling: false, // 是否不抛弃采样是数据, 采用在服务端菜样的方式
43
- isJsBirdge: false,// 是否需要对webview 发送数据,需要装我们对应ios sdk
44
- isLineProtocolToJson: false,
45
- beforeSend: function (event) {},
46
- isServerError: function(request) {return false}, // 判断请求是否为error 请求
47
- isIntakeUrl: function(url) { return false } // 自定义方法根据请求资源 url 判断是否需要采集对应资源数据,默认都采集。 返回:false 表示要采集,true 表示不需要采集
48
- }
49
- function trim(str) {
50
- return str.replace(TRIM_REGIX, '')
51
- }
52
- export function buildCookieOptions(userConfiguration) {
53
- var cookieOptions = {}
54
-
55
- cookieOptions.secure = mustUseSecureCookie(userConfiguration)
56
- cookieOptions.crossSite = !!userConfiguration.useCrossSiteSessionCookie
57
-
58
- if (!!userConfiguration.trackSessionAcrossSubdomains) {
59
- cookieOptions.domain = getCurrentSite()
60
- }
61
-
62
- return cookieOptions
63
- }
64
- function getDatakitUrl(url) {
65
- if (url.lastIndexOf('/') === url.length - 1) return trim(url) + 'v1/write/rum'
66
- return trim(url) + '/v1/write/rum'
67
- }
68
- function getLogsEndPoint(url) {
69
- if (url.lastIndexOf('/') === url.length - 1)
70
- return trim(url) + 'v1/write/logging'
71
- return trim(url) + '/v1/write/logging'
72
- }
73
- export function commonInit(userConfiguration, buildEnv) {
74
- var enableExperimentalFeatures = isArray(
75
- userConfiguration.enableExperimentalFeatures
76
- )
77
- ? userConfiguration.enableExperimentalFeatures
78
- : []
79
- var transportConfiguration = {
80
- applicationId: userConfiguration.applicationId,
81
- env: userConfiguration.env || '',
82
- version: userConfiguration.version || '',
83
- service: userConfiguration.service || 'browser',
84
- sdkVersion: buildEnv.sdkVersion,
85
- sdkName: buildEnv.sdkName,
86
- datakitUrl: getDatakitUrl(
87
- userConfiguration.datakitUrl || userConfiguration.datakitOrigin
88
- ),
89
- logsEndpoint: getLogsEndPoint(userConfiguration.datakitOrigin),
90
- isEnabled: function(feature) {return includes(enableExperimentalFeatures, feature)},
91
- cookieOptions: buildCookieOptions(userConfiguration)
92
- }
93
- if ('isJsBirdge' in userConfiguration) {
94
- transportConfiguration.isJsBirdge = userConfiguration.isJsBirdge
95
- }
96
- if ('isLineProtocolToJson' in userConfiguration) {
97
- transportConfiguration.isLineProtocolToJson = userConfiguration.isLineProtocolToJson
98
- }
99
- if ('allowedDDTracingOrigins' in userConfiguration) {
100
- transportConfiguration.allowedTracingOrigins =
101
- userConfiguration.allowedDDTracingOrigins
102
- }
103
- if ('allowedTracingOrigins' in userConfiguration) {
104
- transportConfiguration.allowedTracingOrigins = userConfiguration.allowedTracingOrigins
105
- }
106
- if ('sampleRate' in userConfiguration) {
107
- transportConfiguration.sampleRate = userConfiguration.sampleRate
108
- }
109
-
110
- if ('resourceSampleRate' in userConfiguration) {
111
- transportConfiguration.resourceSampleRate =
112
- userConfiguration.resourceSampleRate
113
- }
114
-
115
- if ('trackInteractions' in userConfiguration) {
116
- transportConfiguration.trackInteractions = !!userConfiguration.trackInteractions
117
- }
118
- if ('isServerError' in userConfiguration && isFunction(userConfiguration.isServerError) && isBoolean(userConfiguration.isServerError())) {
119
- transportConfiguration.isServerError = userConfiguration.isServerError
120
- }
121
- if ('isIntakeUrl' in userConfiguration && isFunction(userConfiguration.isIntakeUrl) && isBoolean(userConfiguration.isIntakeUrl())) {
122
- transportConfiguration.isIntakeUrl = userConfiguration.isIntakeUrl
123
- }
124
- if ('traceId128Bit' in userConfiguration) {
125
- transportConfiguration.traceId128Bit = !!userConfiguration.traceId128Bit
126
- }
127
- if ('traceType' in userConfiguration && hasTraceType(userConfiguration.traceType)) {
128
- transportConfiguration.traceType = userConfiguration.traceType
129
- }
130
- if ('isServiceSampling' in userConfiguration && isBoolean(userConfiguration.isServiceSampling)) {
131
- transportConfiguration.isServiceSampling = userConfiguration.isServiceSampling
132
- }
133
- return extend2Lev({}, DEFAULT_CONFIGURATION, transportConfiguration)
134
- }
135
- function hasTraceType(traceType) {
136
- if (traceType && values(TraceType).indexOf(traceType) > -1) return true
137
- return false
138
- }
139
- function mustUseSecureCookie(userConfiguration) {
140
- return (
141
- !!userConfiguration.useSecureSessionCookie ||
142
- !!userConfiguration.useCrossSiteSessionCookie
143
- )
144
- }
145
-
146
- export function isIntakeRequest(url, configuration) {
147
- // return haveSameOrigin(url, configuration.datakitUrl)
148
- var notTakeRequest = [configuration.datakitUrl]
149
- if (configuration.logsEndpoint) {
150
- notTakeRequest.push(configuration.logsEndpoint)
151
- }
152
- var isIntake = false
153
- for(var _url of notTakeRequest) {
154
- if (url.indexOf(_url) === 0) {
155
- isIntake = true
156
- break;
157
- }
158
- }
159
- // datakit 地址,log 地址,以及客户自定义过滤方法定义url
160
- return isIntake || configuration.isIntakeUrl(url)
161
- }
@@ -1,170 +0,0 @@
1
- import {
2
- toArray,
3
- jsonStringify,
4
- find,
5
- clocksNow,
6
- map,
7
- extend
8
- } from './helper/tools'
9
- import {
10
- ErrorSource,
11
- formatUnknownError,
12
- toStackTraceString,
13
- formatErrorMessage,
14
- createHandlingStack
15
- } from './helper/errorTools'
16
- import { computeStackTrace, subscribe, unsubscribe } from './tracekit'
17
- import { Observable } from './helper/observable'
18
- import { isIntakeRequest } from './configuration'
19
- import { RequestType, ErrorHandling } from './helper/enums'
20
- import { resetXhrProxy, startXhrProxy } from './xhrProxy'
21
- import { resetFetchProxy, startFetchProxy } from './fetchProxy'
22
-
23
- var errorObservable
24
-
25
- export function startAutomaticErrorCollection(configuration) {
26
- if (!errorObservable) {
27
- errorObservable = new Observable()
28
- trackNetworkError(configuration, errorObservable)
29
- startConsoleTracking(errorObservable)
30
- startRuntimeErrorTracking(errorObservable)
31
- }
32
- return errorObservable
33
- }
34
-
35
- var originalConsoleError
36
-
37
- export function startConsoleTracking(errorObservable) {
38
- originalConsoleError = console.error
39
- console.error = function () {
40
- originalConsoleError.apply(console, arguments)
41
- const handlingStack = createHandlingStack()
42
- errorObservable.notify(
43
- extend({}, buildErrorFromParams(toArray(arguments), handlingStack), {
44
- source: ErrorSource.CONSOLE,
45
- startClocks: clocksNow(),
46
- handling: ErrorHandling.HANDLED
47
- })
48
- )
49
- }
50
- }
51
-
52
- function buildErrorFromParams(params, handlingStack) {
53
- var firstErrorParam = find(params, function (param) {
54
- return param instanceof Error
55
- })
56
- var message = ''
57
- message = map(['console error:'].concat(params), function (param) {
58
- return formatConsoleParameters(param)
59
- }).join(' ')
60
- return {
61
- message: message,
62
- stack: firstErrorParam
63
- ? toStackTraceString(computeStackTrace(firstErrorParam))
64
- : undefined,
65
- handlingStack: handlingStack
66
- }
67
- }
68
-
69
- export function stopConsoleTracking() {
70
- console.error = originalConsoleError
71
- }
72
-
73
- function formatConsoleParameters(param) {
74
- if (typeof param === 'string') {
75
- return param
76
- }
77
- if (param instanceof Error) {
78
- return formatErrorMessage(computeStackTrace(param))
79
- }
80
- return jsonStringify(param, undefined, 2)
81
- }
82
-
83
- var traceKitReportHandler
84
-
85
- export function startRuntimeErrorTracking(errorObservable) {
86
- traceKitReportHandler = function (stackTrace, _, errorObject) {
87
- var error = formatUnknownError(stackTrace, errorObject, 'Uncaught')
88
- errorObservable.notify({
89
- message: error.message,
90
- stack: error.stack,
91
- type: error.type,
92
- source: ErrorSource.SOURCE,
93
- startClocks: clocksNow(),
94
- handling: ErrorHandling.UNHANDLED
95
- })
96
- }
97
-
98
- subscribe(traceKitReportHandler)
99
- }
100
-
101
- export function stopRuntimeErrorTracking() {
102
- unsubscribe(traceKitReportHandler)
103
- }
104
-
105
- export function trackNetworkError(configuration, errorObservable) {
106
- startXhrProxy().onRequestComplete(function (context) {
107
- handleCompleteRequest(RequestType.XHR, context)
108
- })
109
- startFetchProxy().onRequestComplete(function (context) {
110
- handleCompleteRequest(RequestType.FETCH, context)
111
- })
112
-
113
- function handleCompleteRequest(type, request) {
114
- if (
115
- !isIntakeRequest(request.url, configuration) &&
116
- !request.isAborted &&
117
- (isRejected(request) || isServerError(request) || configuration.isServerError(request))
118
- ) {
119
- errorObservable.notify({
120
- message: format(type) + ' error ' + request.method + ' ' + request.url,
121
- resource: {
122
- method: request.method,
123
- statusCode: request.status,
124
- url: request.url,
125
- traceId: request.traceId,
126
- spanId: request.spanId,
127
- },
128
- source: ErrorSource.NETWORK,
129
- stack:
130
- truncateResponse(request.response, configuration) || 'Failed to load',
131
- startClocks: request.startClocks
132
- })
133
- }
134
- }
135
-
136
- return {
137
- stop: () => {
138
- resetXhrProxy()
139
- resetFetchProxy()
140
- }
141
- }
142
- }
143
-
144
- function isRejected(request) {
145
- return request.status === 0 && request.responseType !== 'opaque'
146
- }
147
-
148
- function isServerError(request) {
149
- return request.status >= 500
150
- }
151
-
152
- function truncateResponse(response, configuration) {
153
- if (
154
- response &&
155
- response.length > configuration.requestErrorResponseLengthLimit
156
- ) {
157
- return (
158
- response.substring(0, configuration.requestErrorResponseLengthLimit) +
159
- '...'
160
- )
161
- }
162
- return response
163
- }
164
-
165
- function format(type) {
166
- if (RequestType.XHR === type) {
167
- return 'XHR'
168
- }
169
- return 'Fetch'
170
- }
package/src/fetchProxy.js DELETED
@@ -1,108 +0,0 @@
1
- import { each, timeStampNow, clocksNow, elapsed } from './helper/tools'
2
- import { computeStackTrace } from './tracekit'
3
- import { toStackTraceString } from './helper/errorTools'
4
- import { normalizeUrl } from './helper/urlPolyfill'
5
- var fetchProxySingleton
6
- var originalFetch
7
- var beforeSendCallbacks = []
8
- var onRequestCompleteCallbacks = []
9
-
10
- export function startFetchProxy() {
11
- if (!fetchProxySingleton) {
12
- proxyFetch()
13
- fetchProxySingleton = {
14
- beforeSend: function (callback) {
15
- beforeSendCallbacks.push(callback)
16
- },
17
- onRequestComplete: function (callback) {
18
- onRequestCompleteCallbacks.push(callback)
19
- }
20
- }
21
- }
22
- return fetchProxySingleton
23
- }
24
-
25
- export function resetFetchProxy() {
26
- if (fetchProxySingleton) {
27
- fetchProxySingleton = undefined
28
- beforeSendCallbacks.splice(0, beforeSendCallbacks.length)
29
- onRequestCompleteCallbacks.splice(0, onRequestCompleteCallbacks.length)
30
- window.fetch = originalFetch
31
- }
32
- }
33
- function proxyFetch() {
34
- if (!window.fetch) {
35
- return
36
- }
37
-
38
- originalFetch = window.fetch
39
-
40
- window.fetch = function (input, init) {
41
- var responsePromise
42
- var context = beforeSend.apply(null, [input, init])
43
- if (context) {
44
- responsePromise = originalFetch.call(this, context.input, context.init)
45
- afterSend.apply(null, [responsePromise, context])
46
- } else {
47
- responsePromise = originalFetch.call(this, input, init)
48
- }
49
-
50
- return responsePromise
51
- }
52
- }
53
-
54
- function beforeSend(input, init) {
55
- var method =
56
- (init && init.method) ||
57
- (typeof input === 'object' && input.method) ||
58
- 'GET'
59
- var url = normalizeUrl((typeof input === 'object' && input.url) || input)
60
- var startClocks = clocksNow()
61
-
62
- var context = {
63
- init: init,
64
- input: input,
65
- method: method,
66
- startClocks: startClocks,
67
- url: url
68
- }
69
- each(beforeSendCallbacks, function (callback) {
70
- callback(context)
71
- })
72
-
73
- return context
74
- }
75
-
76
- function afterSend(responsePromise, context) {
77
- var reportFetch = async function (response) {
78
- context.duration = elapsed(context.startClocks.timeStamp, timeStampNow())
79
-
80
- if ('stack' in response || response instanceof Error) {
81
- context.status = 0
82
- context.response = toStackTraceString(computeStackTrace(response))
83
- context.headers = response.headers
84
- context.isAborted =
85
- response instanceof DOMException &&
86
- response.code === DOMException.ABORT_ERR
87
- each(onRequestCompleteCallbacks, function (callback) {
88
- callback(context)
89
- })
90
- } else if ('status' in response) {
91
- var text
92
- try {
93
- text = await response.clone().text()
94
- } catch (e) {
95
- text = 'Unable to retrieve response: ' + e
96
- }
97
- context.response = text
98
- context.responseType = response.type
99
- context.status = response.status
100
- context.headers = response.headers
101
- context.isAborted = false
102
- each(onRequestCompleteCallbacks, function (callback) {
103
- callback(context)
104
- })
105
- }
106
- }
107
- responsePromise.then(reportFetch, reportFetch)
108
- }
@@ -1,38 +0,0 @@
1
- import { ErrorSource } from './errorTools'
2
- import { ONE_MINUTE, clocksNow } from './tools'
3
-
4
- export function createErrorFilter(configuration, onLimitReached) {
5
- var errorCount = 0
6
- var allowNextError = false
7
-
8
- return {
9
- isLimitReached: function () {
10
- if (errorCount === 0) {
11
- setTimeout(function () {
12
- errorCount = 0
13
- }, ONE_MINUTE)
14
- }
15
-
16
- errorCount += 1
17
- if (errorCount <= configuration.maxErrorsByMinute || allowNextError) {
18
- allowNextError = false
19
- return false
20
- }
21
-
22
- if (errorCount === configuration.maxErrorsByMinute + 1) {
23
- allowNextError = true
24
- try {
25
- onLimitReached({
26
- message: `Reached max number of errors by minute: ${configuration.maxErrorsByMinute}`,
27
- source: ErrorSource.AGENT,
28
- startClocks: clocksNow()
29
- })
30
- } finally {
31
- allowNextError = false
32
- }
33
- }
34
-
35
- return true
36
- }
37
- }
38
- }