mon-reactive-h5 1.0.9 → 1.0.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.
@@ -3,12 +3,6 @@
3
3
  function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
4
4
  function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
5
5
  function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
6
- function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
7
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
8
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
9
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
10
- function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
11
- function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
12
6
  function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
13
7
  function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
14
8
  function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
@@ -47,26 +41,15 @@ Object.defineProperty(exports, "__esModule", {
47
41
  exports.MonitorSDK = void 0;
48
42
  var BatchReporter_1 = require("./BatchReporter");
49
43
  var reporters_1 = require("./reporters");
50
- /**
51
- * 前端监控SDK核心类
52
- */
53
44
  var MonitorSDK = /*#__PURE__*/function () {
54
- /**
55
- * 构造函数
56
- * @param config SDK配置
57
- */
58
45
  function MonitorSDK(config) {
59
46
  _classCallCheck(this, MonitorSDK);
60
- // 记录上一页URL,用于单页应用路由变化时的referrer
61
47
  this.lastPageUrl = document.referrer || '';
62
48
  this.appId = config.appId || '';
63
49
  this.reportUrl = config.reportUrl || '';
64
- // 确保sampleRates是Record<string, number>类型
65
50
  if (config.sampleRates) {
66
- this.sampleRates = Object.entries(config.sampleRates).reduce(function (acc, _ref) {
67
- var _ref2 = _slicedToArray(_ref, 2),
68
- key = _ref2[0],
69
- value = _ref2[1];
51
+ this.sampleRates = Object.keys(config.sampleRates).reduce(function (acc, key) {
52
+ var value = config.sampleRates[key];
70
53
  acc[key] = value !== undefined ? value : 1;
71
54
  return acc;
72
55
  }, {});
@@ -84,65 +67,41 @@ var MonitorSDK = /*#__PURE__*/function () {
84
67
  interval: config.interval || 5000
85
68
  });
86
69
  this.sessionId = this.generateSessionId();
87
- // 优先使用配置中的userId,如果没有则尝试从token中提取
88
70
  this.userId = config.userId || this.getUserIdFromToken();
89
- // 获取版本号,PC端从process.env.VUE_APP_VERSION获取,小程序和APP使用各自的版本号
90
71
  this.version = this.getAppVersion(config);
91
72
  this.init();
92
73
  }
93
- /**
94
- * 获取应用版本号
95
- */
96
74
  return _createClass(MonitorSDK, [{
97
75
  key: "getAppVersion",
98
76
  value: function getAppVersion(config) {
99
- // 优先使用配置传入的版本号
100
77
  if (config.version) {
101
78
  return config.version;
102
79
  }
103
- // PC端尝试从环境变量获取
104
80
  if (typeof process !== 'undefined' && process.env && process.env.VUE_APP_VERSION) {
105
81
  return process.env.VUE_APP_VERSION;
106
82
  }
107
- // 小程序环境检测
108
83
  if (typeof wx !== 'undefined' && wx.getSystemInfoSync) {
109
84
  try {
110
85
  var systemInfo = wx.getSystemInfoSync();
111
86
  return systemInfo.AppVersion || systemInfo.version || '1.0.0';
112
- } catch (e) {
113
- // 忽略错误
114
- }
87
+ } catch (e) {}
115
88
  }
116
- // APP环境检测
117
89
  if (typeof window !== 'undefined' && window.navigator && window.navigator.userAgent) {
118
- // 根据实际APP的userAgent格式调整
119
90
  var ua = window.navigator.userAgent;
120
- // 这里可以根据具体APP的UA格式进行解析
121
91
  }
122
- return '1.0.0'; // 默认版本号
92
+ return '1.0.0';
123
93
  }
124
- /**
125
- * 生成会话ID
126
- */
127
94
  }, {
128
95
  key: "generateSessionId",
129
96
  value: function generateSessionId() {
130
97
  return "".concat(Date.now(), "_").concat(Math.random().toString(36).substring(2, 9));
131
98
  }
132
- /**
133
- * 从token中提取userId
134
- * 小程序环境:直接从本地缓存中取"token"
135
- * 网页环境:先尝试从sessionStorage中取"-token",再尝试从cookie里取"Admin-Token"
136
- * 取出token后截取最后12位作为userid
137
- */
138
99
  }, {
139
100
  key: "getUserIdFromToken",
140
101
  value: function getUserIdFromToken() {
141
102
  var token = null;
142
- // 1. 先检查是否为小程序环境
143
103
  try {
144
104
  if (typeof wx !== 'undefined' && wx.getStorageSync) {
145
- // 小程序环境,直接从本地缓存中获取token
146
105
  var wxToken = wx.getStorageSync('token');
147
106
  if (wxToken) {
148
107
  token = wxToken;
@@ -151,7 +110,6 @@ var MonitorSDK = /*#__PURE__*/function () {
151
110
  } catch (error) {
152
111
  console.warn('Failed to get token from wx storage:', error);
153
112
  }
154
- // 2. 如果不是小程序环境或未获取到token,尝试从sessionStorage中获取token
155
113
  if (!token) {
156
114
  try {
157
115
  if (typeof window !== 'undefined' && window.sessionStorage) {
@@ -161,7 +119,6 @@ var MonitorSDK = /*#__PURE__*/function () {
161
119
  console.warn('Failed to get token from sessionStorage:', error);
162
120
  }
163
121
  }
164
- // 3. 如果sessionStorage中没有token,尝试从cookie中获取
165
122
  if (!token) {
166
123
  try {
167
124
  if (typeof document !== 'undefined') {
@@ -174,46 +131,33 @@ var MonitorSDK = /*#__PURE__*/function () {
174
131
  console.warn('Failed to get token from cookie:', error);
175
132
  }
176
133
  }
177
- // 4. 从token中提取userId(截取最后12位)
178
134
  if (token && token.length >= 12) {
179
135
  return token.slice(-12);
180
136
  }
181
137
  return undefined;
182
138
  }
183
- /**
184
- * 初始化SDK
185
- */
186
139
  }, {
187
140
  key: "init",
188
141
  value: function init() {
189
142
  var _this = this;
190
- // 初始化各类监控
191
143
  this.initPageViewMonitor();
192
144
  this.initErrorMonitor();
193
145
  this.initApiMonitor();
194
146
  this.initResourceMonitor();
195
- // 页面卸载时清理
196
147
  window.addEventListener('unload', function () {
197
148
  _this.cleanup();
198
149
  });
199
150
  }
200
- /**
201
- * 清理资源
202
- */
203
151
  }, {
204
152
  key: "cleanup",
205
153
  value: function cleanup() {
206
154
  if (this.originalXHRSend) {
207
155
  XMLHttpRequest.prototype.send = this.originalXHRSend;
208
156
  }
209
- // 销毁批量上报器
210
157
  if (this.batchReporter) {
211
158
  this.batchReporter.destroy();
212
159
  }
213
160
  }
214
- /**
215
- * 页面浏览监控
216
- */
217
161
  }, {
218
162
  key: "initPageViewMonitor",
219
163
  value: function initPageViewMonitor() {
@@ -225,9 +169,7 @@ var MonitorSDK = /*#__PURE__*/function () {
225
169
  referrer: document.referrer,
226
170
  timestamp: startTime
227
171
  };
228
- // 更新lastPageUrl为当前页面URL
229
172
  this.lastPageUrl = window.location.href;
230
- // 页面加载完成上报
231
173
  window.addEventListener('load', function () {
232
174
  var performanceData = _this2.getPerformanceData();
233
175
  _this2.reportPageView(Object.assign(Object.assign({}, pageInfo), {
@@ -236,14 +178,11 @@ var MonitorSDK = /*#__PURE__*/function () {
236
178
  performance: performanceData
237
179
  }));
238
180
  });
239
- // 单页应用路由变化监控
240
181
  if (window.history.pushState) {
241
182
  var originalPushState = window.history.pushState;
242
183
  var originalReplaceState = window.history.replaceState;
243
184
  var handleHistoryChange = function handleHistoryChange() {
244
- // 获取当前URL
245
185
  var currentUrl = window.location.href;
246
- // 只有当URL真正变化时才上报,避免replaceState导致的重复上报
247
186
  if (currentUrl !== _this2.lastPageUrl) {
248
187
  _this2.reportPageView({
249
188
  pageUrl: currentUrl,
@@ -254,7 +193,6 @@ var MonitorSDK = /*#__PURE__*/function () {
254
193
  isFirstVisit: false,
255
194
  performance: _this2.getPerformanceData()
256
195
  });
257
- // 更新上一页URL为当前URL
258
196
  _this2.lastPageUrl = currentUrl;
259
197
  }
260
198
  };
@@ -266,7 +204,6 @@ var MonitorSDK = /*#__PURE__*/function () {
266
204
  handleHistoryChange();
267
205
  };
268
206
  window.history.replaceState = function () {
269
- // 保存调用前的URL
270
207
  var prevUrl = window.location.href;
271
208
  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
272
209
  args[_key2] = arguments[_key2];
@@ -274,18 +211,13 @@ var MonitorSDK = /*#__PURE__*/function () {
274
211
  originalReplaceState.apply(this, args);
275
212
  handleHistoryChange();
276
213
  };
277
- // 监听popstate事件
278
214
  window.addEventListener('popstate', handleHistoryChange);
279
215
  }
280
216
  }
281
- /**
282
- * 错误监控
283
- */
284
217
  }, {
285
218
  key: "initErrorMonitor",
286
219
  value: function initErrorMonitor() {
287
220
  var _this3 = this;
288
- // JS错误
289
221
  window.addEventListener('error', function (event) {
290
222
  _this3.reportJSError({
291
223
  message: event.message,
@@ -298,7 +230,6 @@ var MonitorSDK = /*#__PURE__*/function () {
298
230
  timestamp: Date.now()
299
231
  });
300
232
  });
301
- // Promise错误
302
233
  window.addEventListener('unhandledrejection', function (event) {
303
234
  _this3.reportJSError({
304
235
  message: event.reason ? String(event.reason) : 'Promise rejection',
@@ -312,118 +243,45 @@ var MonitorSDK = /*#__PURE__*/function () {
312
243
  });
313
244
  });
314
245
  }
315
- /**
316
- * API监控
317
- */
318
246
  }, {
319
247
  key: "initApiMonitor",
320
248
  value: function initApiMonitor() {
321
- // 生成请求ID
322
249
  var generateRequestId = function generateRequestId() {
323
250
  return "".concat(Date.now(), "_").concat(Math.random().toString(36).substring(2, 11));
324
251
  };
325
- // 解析URL,分离基础URL和完整URL
326
252
  var parseUrl = function parseUrl(urlStr) {
327
253
  try {
328
254
  var urlList = urlStr.split('?');
329
- // 基础URL(不包含查询参数和hash)
330
255
  var baseUrl = urlList[0];
331
- // 完整URL(包含查询参数和hash)
332
256
  var fullUrl = urlStr;
333
257
  return {
334
258
  baseUrl: baseUrl,
335
259
  fullUrl: fullUrl
336
260
  };
337
261
  } catch (_a) {
338
- // 如果URL解析失败,则使用原始URL
339
262
  return {
340
263
  baseUrl: urlStr,
341
264
  fullUrl: urlStr
342
265
  };
343
266
  }
344
267
  };
345
- // 重写fetch
346
- // this.originalFetch = window.fetch;
347
- // window.fetch = async (...args) => {
348
- // const [url, options] = args;
349
- // const urlStr = typeof url === 'string' ? url : url.toString();
350
- // // 排除SDK自身的上报请求,避免死循环
351
- // // 1. 检查是否有特殊标记表示这是SDK内部请求
352
- // const isSdkInternalRequest = options?.headers?.['x-sdk-internal'] === 'true';
353
- // // 2. 检查是否是已知的SDK上报路径,包括批量上报相关路径
354
- // const knownReportPaths = ['/v1/report/collect', '/v1/report/collectImg', '/api/report/collect'];
355
- // const isKnownReportPath = knownReportPaths.some(path => urlStr.includes(path));
356
- // // 3. 检查是否是配置的上报URL
357
- // const isConfiguredReportUrl = this.reportUrl && urlStr.includes(this.reportUrl);
358
- // // 4. 对于没有头信息的请求(如sendBeacon和img上报),增加更严格的路径匹配
359
- // const isBatchReportPath = urlStr.includes('/v1/report/collect') || urlStr.includes('/v1/report/collectImg');
360
- // // 如果是SDK自身的上报请求,则直接使用原始fetch
361
- // if (isSdkInternalRequest || isKnownReportPath || isConfiguredReportUrl || isBatchReportPath) {
362
- // return this.originalFetch!(...args);
363
- // }
364
- // const startTime = Date.now();
365
- // const method = options?.method || 'GET';
366
- // const requestId = generateRequestId();
367
- // const { baseUrl, fullUrl } = parseUrl(urlStr);
368
- // try {
369
- // const response = await this.originalFetch!(...args);
370
- // const reportData = {
371
- // requestId,
372
- // url: baseUrl,
373
- // fullUrl,
374
- // method,
375
- // status: response.status,
376
- // isError: response.status >= 400,
377
- // responseTime: Date.now() - startTime,
378
- // timestamp: startTime,
379
- // pageUrl: window.location.href
380
- // };
381
- // // 上报API数据
382
- // this.reportApi(reportData);
383
- // return response;
384
- // } catch (error) {
385
- // const reportData = {
386
- // requestId,
387
- // url: baseUrl,
388
- // fullUrl,
389
- // method,
390
- // status: 0,
391
- // isError: true,
392
- // errorType: (error as Error).name || 'FetchError',
393
- // responseTime: Date.now() - startTime,
394
- // timestamp: startTime,
395
- // pageUrl: window.location.href
396
- // };
397
- // // 上报错误API
398
- // this.reportApi(reportData);
399
- // throw error;
400
- // }
401
- // };
402
- // 重写XMLHttpRequest
403
268
  var originalXHROpen = XMLHttpRequest.prototype.open;
404
269
  var originalSend = XMLHttpRequest.prototype.send;
405
270
  this.originalXHRSend = originalSend;
406
271
  var xhrMap = new WeakMap();
407
272
  var that = this;
408
- // 覆盖XMLHttpRequest.open方法
409
273
  var originalOpen = originalXHROpen;
410
274
  XMLHttpRequest.prototype.open = function (method, url, async, username, password) {
411
275
  var urlStr = typeof url === 'string' ? url : url.toString();
412
- // 排除SDK自身的上报请求,避免死循环
413
- // 1. 检查是否有特殊标记表示这是SDK内部请求(通过自定义属性)
414
276
  if (this._isSdkInternalRequest) {
415
277
  return originalOpen.call(this, method, url, async === undefined ? true : async, username, password);
416
278
  }
417
- // 2. 检查是否是已知的SDK上报路径,包括批量上报相关路径
418
279
  var knownReportPaths = ['/v1/report/collect', '/v1/report/collectImg', '/api/report/collect'];
419
280
  var isKnownReportPath = knownReportPaths.some(function (path) {
420
281
  return urlStr.includes(path);
421
282
  });
422
- // 3. 检查是否是配置的上报URL
423
283
  var isConfiguredReportUrl = that.reportUrl && urlStr.includes(that.reportUrl);
424
- // 4. 对于没有头信息的请求(如sendBeacon和img上报),增加更严格的路径匹配
425
284
  var isBatchReportPath = urlStr.includes('/v1/report/collect') || urlStr.includes('/v1/report/collectImg');
426
- // 如果是SDK自身的上报请求,则直接使用原始open方法
427
285
  if (isKnownReportPath || isConfiguredReportUrl || isBatchReportPath) {
428
286
  return originalOpen.call(this, method, url, async === undefined ? true : async, username, password);
429
287
  }
@@ -447,29 +305,21 @@ var MonitorSDK = /*#__PURE__*/function () {
447
305
  args[_key3] = arguments[_key3];
448
306
  }
449
307
  if (!xhrInfo) {
450
- // @ts-ignore
451
308
  return originalSend.apply(this, args);
452
309
  }
453
- // 获取请求体大小(字节)
454
310
  var requestBodySize = 0;
455
311
  if (args && args[0] !== undefined && args[0] !== null) {
456
312
  if (typeof args[0] === 'string') {
457
- // 字符串请求体,使用TextEncoder获取字节长度
458
313
  try {
459
314
  requestBodySize = new TextEncoder().encode(args[0]).length;
460
315
  } catch (e) {
461
- // 降级方案:估算字节长度
462
316
  requestBodySize = args[0].length;
463
317
  }
464
318
  } else if (args[0] instanceof FormData) {
465
- // FormData请求体,尝试估算大小
466
- // 注意:由于安全限制,无法精确获取FormData的大小
467
- requestBodySize = -1; // 表示未知大小
319
+ requestBodySize = -1;
468
320
  } else if (args[0] instanceof Blob) {
469
- // Blob/File请求体
470
321
  requestBodySize = args[0].size;
471
322
  } else {
472
- // 其他类型,尝试转换为字符串估算
473
323
  try {
474
324
  var str = JSON.stringify(args[0]);
475
325
  requestBodySize = new TextEncoder().encode(str).length;
@@ -478,7 +328,6 @@ var MonitorSDK = /*#__PURE__*/function () {
478
328
  }
479
329
  }
480
330
  }
481
- // 保存请求体大小到xhrInfo中
482
331
  Object.assign(xhrInfo, {
483
332
  requestBodySize: requestBodySize
484
333
  });
@@ -486,7 +335,6 @@ var MonitorSDK = /*#__PURE__*/function () {
486
335
  var endTime = Date.now();
487
336
  var responseTime = endTime - xhrInfo.startTime;
488
337
  var status = _this4.status;
489
- // 获取响应体大小(字节)
490
338
  var responseBodySize = 0;
491
339
  try {
492
340
  if (_this4.responseText) {
@@ -499,7 +347,6 @@ var MonitorSDK = /*#__PURE__*/function () {
499
347
  } else if (_this4.response instanceof Blob) {
500
348
  responseBodySize = _this4.response.size;
501
349
  } else {
502
- // 尝试JSON序列化估算
503
350
  try {
504
351
  var _str = JSON.stringify(_this4.response);
505
352
  responseBodySize = new TextEncoder().encode(_str).length;
@@ -509,7 +356,6 @@ var MonitorSDK = /*#__PURE__*/function () {
509
356
  }
510
357
  }
511
358
  } catch (e) {
512
- // 如果无法获取响应体大小,设置为-1
513
359
  responseBodySize = -1;
514
360
  }
515
361
  var reportData = {
@@ -526,27 +372,21 @@ var MonitorSDK = /*#__PURE__*/function () {
526
372
  requestBodySize: requestBodySize,
527
373
  responseBodySize: responseBodySize
528
374
  };
529
- // 上报API数据
530
375
  that.reportApi(reportData);
531
376
  });
532
377
  return originalSend.apply(this, args);
533
378
  };
534
379
  }
535
- /**
536
- * 资源监控
537
- */
538
380
  }, {
539
381
  key: "initResourceMonitor",
540
382
  value: function initResourceMonitor() {
541
383
  var _this5 = this;
542
- // 通过PerformanceObserver监控资源加载
543
384
  if ('PerformanceObserver' in window) {
544
385
  try {
545
386
  var observer = new PerformanceObserver(function (list) {
546
387
  list.getEntries().forEach(function (entry) {
547
388
  if (entry.entryType === 'resource') {
548
389
  var resourceEntry = entry;
549
- // 检查资源是否加载失败 - 使用类型断言处理responseStatus
550
390
  var typedEntry = resourceEntry;
551
391
  if (typedEntry.responseStatus && typedEntry.responseStatus >= 400) {
552
392
  _this5.reportResource({
@@ -571,7 +411,6 @@ var MonitorSDK = /*#__PURE__*/function () {
571
411
  console.error('PerformanceObserver初始化失败:', error);
572
412
  }
573
413
  }
574
- // 监听资源错误事件
575
414
  window.addEventListener('error', function (event) {
576
415
  if (event.target && (event.target instanceof HTMLScriptElement || event.target instanceof HTMLLinkElement || event.target instanceof HTMLImageElement || event.target instanceof HTMLAudioElement || event.target instanceof HTMLVideoElement)) {
577
416
  var target = event.target;
@@ -589,26 +428,20 @@ var MonitorSDK = /*#__PURE__*/function () {
589
428
  }
590
429
  }, true);
591
430
  }
592
- /**
593
- * 获取资源类型
594
- */
595
431
  }, {
596
432
  key: "getResourceType",
597
433
  value: function getResourceType(url) {
598
434
  var _a;
599
435
  var ext = (_a = url.split('?')[0].split('.').pop()) === null || _a === void 0 ? void 0 : _a.toLowerCase();
600
436
  if (!ext) return 'other';
601
- if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico'].includes(ext)) return 'image';
602
- if (['js'].includes(ext)) return 'js';
603
- if (['css'].includes(ext)) return 'css';
604
- if (['woff', 'woff2', 'ttf', 'eot', 'otf'].includes(ext)) return 'font';
605
- if (['mp4', 'webm', 'ogg'].includes(ext)) return 'video';
606
- if (['mp3', 'wav', 'ogg'].includes(ext)) return 'audio';
437
+ if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico'].indexOf(ext) !== -1) return 'image';
438
+ if (['js'].indexOf(ext) !== -1) return 'js';
439
+ if (['css'].indexOf(ext) !== -1) return 'css';
440
+ if (['woff', 'woff2', 'ttf', 'eot', 'otf'].indexOf(ext) !== -1) return 'font';
441
+ if (['mp4', 'webm', 'ogg'].indexOf(ext) !== -1) return 'video';
442
+ if (['mp3', 'wav', 'ogg'].indexOf(ext) !== -1) return 'audio';
607
443
  return 'other';
608
444
  }
609
- /**
610
- * 获取性能数据
611
- */
612
445
  }, {
613
446
  key: "getPerformanceData",
614
447
  value: function getPerformanceData() {
@@ -619,9 +452,6 @@ var MonitorSDK = /*#__PURE__*/function () {
619
452
  loadEventEnd: timing.loadEventEnd
620
453
  };
621
454
  }
622
- /**
623
- * 判断是否首次访问
624
- */
625
455
  }, {
626
456
  key: "isFirstVisit",
627
457
  value: function isFirstVisit() {
@@ -632,9 +462,6 @@ var MonitorSDK = /*#__PURE__*/function () {
632
462
  }
633
463
  return false;
634
464
  }
635
- /**
636
- * 上报页面浏览
637
- */
638
465
  }, {
639
466
  key: "reportPageView",
640
467
  value: function reportPageView(data) {
@@ -651,9 +478,6 @@ var MonitorSDK = /*#__PURE__*/function () {
651
478
  };
652
479
  this.doReport(payload, 'pageview');
653
480
  }
654
- /**
655
- * 上报JS错误
656
- */
657
481
  }, {
658
482
  key: "reportJSError",
659
483
  value: function reportJSError(data) {
@@ -669,9 +493,6 @@ var MonitorSDK = /*#__PURE__*/function () {
669
493
  };
670
494
  this.doReport(payload, 'jserror');
671
495
  }
672
- /**
673
- * 上报API数据
674
- */
675
496
  }, {
676
497
  key: "reportApi",
677
498
  value: function reportApi(data) {
@@ -687,9 +508,6 @@ var MonitorSDK = /*#__PURE__*/function () {
687
508
  };
688
509
  this.doReport(payload, 'api');
689
510
  }
690
- /**
691
- * 上报资源错误
692
- */
693
511
  }, {
694
512
  key: "reportResource",
695
513
  value: function reportResource(data) {
@@ -704,41 +522,25 @@ var MonitorSDK = /*#__PURE__*/function () {
704
522
  };
705
523
  this.doReport(payload, 'resource');
706
524
  }
707
- /**
708
- * 统一上报处理
709
- */
710
525
  }, {
711
526
  key: "doReport",
712
527
  value: function doReport(payload, type) {
713
528
  var _a;
714
- // 采样处理
715
529
  var sampleRate = (_a = this.sampleRates[type]) !== null && _a !== void 0 ? _a : 1;
716
530
  if (Math.random() > sampleRate) return;
717
- // 数据脱敏
718
531
  var sanitizedPayload = Object.assign(Object.assign({}, payload), {
719
532
  data: this.sanitizeData(Object.assign(Object.assign({}, payload.data), {
720
533
  version: this.version
721
534
  }))
722
535
  });
723
- // 根据数据类型选择上报方式
724
536
  if (type === 'pageview' && typeof navigator.sendBeacon === 'function') {
725
- // 页面浏览使用sendBeacon
726
537
  (0, reporters_1.reportByBeacon)(sanitizedPayload, this.reportUrl);
727
538
  } else if (type === 'jserror' || type === 'resource') {
728
- // 错误数据立即上报
729
- // reportByApi(sanitizedPayload, this.reportUrl).catch(() => {
730
- // // 降级到img上报
731
- // reportByImg(sanitizedPayload, this.reportUrl);
732
- // });
733
539
  (0, reporters_1.reportWithFallback)(sanitizedPayload, this.reportUrl);
734
540
  } else {
735
- // 其他数据批量上报
736
541
  this.batchReporter.report(sanitizedPayload);
737
542
  }
738
543
  }
739
- /**
740
- * 获取设备信息
741
- */
742
544
  }, {
743
545
  key: "getDeviceInfo",
744
546
  value: function getDeviceInfo() {
@@ -754,13 +556,9 @@ var MonitorSDK = /*#__PURE__*/function () {
754
556
  language: navigator.language || ''
755
557
  };
756
558
  }
757
- /**
758
- * 获取网络信息
759
- */
760
559
  }, {
761
560
  key: "getNetworkInfo",
762
561
  value: function getNetworkInfo() {
763
- // 安全地获取网络信息
764
562
  var connection = navigator.connection || null;
765
563
  if (connection) {
766
564
  return {
@@ -773,9 +571,6 @@ var MonitorSDK = /*#__PURE__*/function () {
773
571
  effectiveType: 'unknown'
774
572
  };
775
573
  }
776
- /**
777
- * 获取浏览器信息
778
- */
779
574
  }, {
780
575
  key: "getBrowser",
781
576
  value: function getBrowser(ua) {
@@ -786,20 +581,13 @@ var MonitorSDK = /*#__PURE__*/function () {
786
581
  if (ua.includes('Trident') || ua.includes('MSIE')) return 'IE';
787
582
  return 'Unknown';
788
583
  }
789
- /**
790
- * 获取浏览器版本
791
- */
792
584
  }, {
793
585
  key: "getBrowserVersion",
794
586
  value: function getBrowserVersion(ua) {
795
- // 简化版本,实际项目中可能需要更复杂的正则匹配
796
587
  var versionRegex = /(Chrome|Safari|Firefox|Edge|MSIE)\/?\s*(\d+\.\d*)/i;
797
588
  var match = ua.match(versionRegex);
798
589
  return match ? match[2] : 'Unknown';
799
590
  }
800
- /**
801
- * 获取操作系统
802
- */
803
591
  }, {
804
592
  key: "getOS",
805
593
  value: function getOS(ua) {
@@ -810,13 +598,9 @@ var MonitorSDK = /*#__PURE__*/function () {
810
598
  if (ua.includes('Linux')) return 'Linux';
811
599
  return 'Unknown';
812
600
  }
813
- /**
814
- * 获取操作系统版本
815
- */
816
601
  }, {
817
602
  key: "getOSVersion",
818
603
  value: function getOSVersion(ua) {
819
- // 简化版本
820
604
  if (ua.includes('Windows')) {
821
605
  if (ua.includes('Windows NT 10.0')) return '10';
822
606
  if (ua.includes('Windows NT 6.3')) return '8.1';
@@ -826,9 +610,6 @@ var MonitorSDK = /*#__PURE__*/function () {
826
610
  }
827
611
  return 'Unknown';
828
612
  }
829
- /**
830
- * 获取设备类型
831
- */
832
613
  }, {
833
614
  key: "getDeviceType",
834
615
  value: function getDeviceType() {
@@ -838,35 +619,22 @@ var MonitorSDK = /*#__PURE__*/function () {
838
619
  }
839
620
  return 'desktop';
840
621
  }
841
- /**
842
- * 数据脱敏
843
- */
844
622
  }, {
845
623
  key: "sanitizeData",
846
624
  value: function sanitizeData(data) {
847
- // 深拷贝数据,避免修改原始数据
848
625
  var sanitized = JSON.parse(JSON.stringify(data));
849
- // 脱敏处理函数
850
626
  var _sanitize = function sanitize(obj) {
851
627
  if (!obj || _typeof(obj) !== 'object') return obj;
852
- // 遍历对象属性
853
628
  Object.keys(obj).forEach(function (key) {
854
- // 对常见敏感字段进行脱敏
855
629
  if (['password', 'token', 'auth', 'credential', 'key'].some(function (sensitive) {
856
630
  return key.toLowerCase().includes(sensitive);
857
631
  })) {
858
632
  obj[key] = '***';
859
- }
860
- // 邮箱脱敏
861
- else if (key.toLowerCase().includes('email') && typeof obj[key] === 'string') {
633
+ } else if (key.toLowerCase().includes('email') && typeof obj[key] === 'string') {
862
634
  obj[key] = obj[key].replace(/(.{2})(.*)(@.*)/, '$1***$3');
863
- }
864
- // 手机号脱敏
865
- else if (key.toLowerCase().includes('phone') && typeof obj[key] === 'string') {
635
+ } else if (key.toLowerCase().includes('phone') && typeof obj[key] === 'string') {
866
636
  obj[key] = obj[key].replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
867
- }
868
- // 递归处理嵌套对象
869
- else if (_typeof(obj[key]) === 'object') {
637
+ } else if (_typeof(obj[key]) === 'object') {
870
638
  _sanitize(obj[key]);
871
639
  }
872
640
  });
@@ -874,14 +642,10 @@ var MonitorSDK = /*#__PURE__*/function () {
874
642
  _sanitize(sanitized);
875
643
  return sanitized;
876
644
  }
877
- /**
878
- * 上报自定义事件
879
- */
880
645
  }, {
881
646
  key: "reportCustomEvent",
882
647
  value: function reportCustomEvent(eventType, eventData) {
883
648
  var _a;
884
- // 根据采样率决定是否上报
885
649
  var sampleRate = (_a = this.sampleRates['custom']) !== null && _a !== void 0 ? _a : 1;
886
650
  if (Math.random() > sampleRate) {
887
651
  return;
@@ -899,12 +663,8 @@ var MonitorSDK = /*#__PURE__*/function () {
899
663
  pageUrl: window.location.href
900
664
  }
901
665
  };
902
- // 使用批量上报
903
666
  this.batchReporter.report(reportData);
904
667
  }
905
- /**
906
- * 立即上报缓冲区数据
907
- */
908
668
  }, {
909
669
  key: "flush",
910
670
  value: function flush() {
@@ -924,9 +684,6 @@ var MonitorSDK = /*#__PURE__*/function () {
924
684
  }, _callee, this);
925
685
  }));
926
686
  }
927
- /**
928
- * 销毁SDK实例
929
- */
930
687
  }, {
931
688
  key: "destroy",
932
689
  value: function destroy() {