@yysports/tools 2.2.7 → 3.0.2

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 (43) hide show
  1. package/README.md +1 -6
  2. package/dist/Track/Beacon.d.ts +22 -3
  3. package/dist/Track/Beacon.js +93 -33
  4. package/dist/Track/Config.d.ts +4 -0
  5. package/dist/Track/Config.js +5 -1
  6. package/dist/Track/Listener.js +8 -4
  7. package/dist/Track/Log.d.ts +12 -2
  8. package/dist/Track/Log.js +71 -48
  9. package/dist/Track/Replay.d.ts +19 -2
  10. package/dist/Track/Replay.js +97 -48
  11. package/dist/Track/System.d.ts +3 -1
  12. package/dist/Track/System.js +8 -2
  13. package/dist/Track/envelope.d.ts +7 -0
  14. package/dist/Track/envelope.js +40 -0
  15. package/dist/Track/index.js +4 -2
  16. package/dist/index.d.ts +1 -0
  17. package/dist/index.js +2 -1
  18. package/dist/interfaces/protocol.d.ts +94 -0
  19. package/dist/interfaces/protocol.js +65 -0
  20. package/dist/interfaces/track.interface.d.ts +3 -8
  21. package/dist/interfaces/track.interface.js +3 -8
  22. package/lib/Track/Beacon.d.ts +22 -3
  23. package/lib/Track/Beacon.js +70 -28
  24. package/lib/Track/Config.d.ts +4 -0
  25. package/lib/Track/Config.js +5 -1
  26. package/lib/Track/Listener.js +7 -3
  27. package/lib/Track/Log.d.ts +12 -2
  28. package/lib/Track/Log.js +46 -35
  29. package/lib/Track/Replay.d.ts +19 -2
  30. package/lib/Track/Replay.js +53 -26
  31. package/lib/Track/System.d.ts +3 -1
  32. package/lib/Track/System.js +6 -2
  33. package/lib/Track/envelope.d.ts +7 -0
  34. package/lib/Track/envelope.js +76 -0
  35. package/lib/Track/index.js +2 -2
  36. package/lib/index.d.ts +1 -0
  37. package/lib/index.js +3 -1
  38. package/lib/interfaces/protocol.d.ts +94 -0
  39. package/lib/interfaces/protocol.js +66 -0
  40. package/lib/interfaces/track.interface.d.ts +3 -8
  41. package/lib/interfaces/track.interface.js +5 -9
  42. package/package.json +18 -18
  43. package/LICENSE +0 -21
package/README.md CHANGED
@@ -1,6 +1 @@
1
- # @yysports/tools
2
-
3
- [![NPM version](https://img.shields.io/npm/v/@yysports/tools.svg?style=flat)](https://npmjs.org/package/@yysports/tools)
4
- [![NPM downloads](http://img.shields.io/npm/dm/@yysports/tools.svg?style=flat)](https://npmjs.org/package/@yysports/tools)
5
-
6
- [阅读文档](https://track.yysports.com/yysports-tools)
1
+ @yysports/tools
@@ -1,6 +1,25 @@
1
+ import { type TrackV3Event } from '../interfaces/protocol';
2
+ /**
3
+ * 批量日志队列(通道 1)。
4
+ *
5
+ * 发送语义:sendBeacon 返回值只表示浏览器是否成功入队,无法感知服务端 4xx/413——
6
+ * 因此只对「入队失败」重试,被服务端拒绝的丢数由服务端侧计数告警补偿。
7
+ * 无 sendBeacon 环境(部分 WebView / 老浏览器)降级用 fetch(keepalive) 发送。
8
+ */
1
9
  export default class Beacon {
2
10
  private static _queue;
3
- static push(data: any): void;
4
- static send(data?: object | Array<any>, api?: string): void;
5
- static updateVersion(): void;
11
+ private static _timer;
12
+ /** 连续发送失败次数,超过重试上限后丢弃当前批次,避免队列无限增长 */
13
+ private static _failCount;
14
+ private static readonly MAX_RETRIES;
15
+ /** 启动定时 flush(Track.init 时调用) */
16
+ static start(): void;
17
+ /** 入队,达到 batchSize 立即 flush */
18
+ static push(event: TrackV3Event): void;
19
+ /** 发送成功后再出队;失败保留队列等待下次 flush 重试 */
20
+ static flush(): void;
21
+ private static sendBatch;
22
+ private static trySendBeacon;
23
+ /** fetch keepalive:无 sendBeacon 环境的主要通道,已发出即视为送达(不等响应、不阻塞队列) */
24
+ private static trySendKeepalive;
6
25
  }
@@ -1,58 +1,118 @@
1
+ import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
1
2
  import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
2
3
  import _createClass from "@babel/runtime/helpers/esm/createClass";
3
4
  import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
4
- import packageJson from "../../package.json";
5
+ import { TRACK_CONTENT_TYPE, TRACK_LIMITS } from "../interfaces/protocol";
5
6
  import Config from "./Config";
7
+ import { buildEnvelopeBase, trackUrl } from "./envelope";
8
+
9
+ /** 发送结果:sent 已发出;retry 保留队列下次重试;drop 超过重试上限丢弃该批 */
10
+ /**
11
+ * 批量日志队列(通道 1)。
12
+ *
13
+ * 发送语义:sendBeacon 返回值只表示浏览器是否成功入队,无法感知服务端 4xx/413——
14
+ * 因此只对「入队失败」重试,被服务端拒绝的丢数由服务端侧计数告警补偿。
15
+ * 无 sendBeacon 环境(部分 WebView / 老浏览器)降级用 fetch(keepalive) 发送。
16
+ */
6
17
  var Beacon = /*#__PURE__*/function () {
7
18
  function Beacon() {
8
19
  _classCallCheck(this, Beacon);
9
20
  }
10
21
  _createClass(Beacon, null, [{
22
+ key: "start",
23
+ value: /** 启动定时 flush(Track.init 时调用) */
24
+ function start() {
25
+ var _this = this,
26
+ _Config$data$flushInt;
27
+ if (this._timer) return;
28
+ this._timer = setInterval(function () {
29
+ return _this.flush();
30
+ }, (_Config$data$flushInt = Config.data.flushInterval) !== null && _Config$data$flushInt !== void 0 ? _Config$data$flushInt : 10000);
31
+ }
32
+
33
+ /** 入队,达到 batchSize 立即 flush */
34
+ }, {
11
35
  key: "push",
12
- value:
13
- // 加入Beacon消息队列,检测超过5条记录时自动发送
14
- function push(data) {
15
- this._queue.push(data);
16
- if (this._queue.length >= 5) {
17
- this.send();
36
+ value: function push(event) {
37
+ var _Config$data$batchSiz;
38
+ this._queue.push(event);
39
+ if (this._queue.length >= ((_Config$data$batchSiz = Config.data.batchSize) !== null && _Config$data$batchSiz !== void 0 ? _Config$data$batchSiz : TRACK_LIMITS.maxItems)) {
40
+ this.flush();
18
41
  }
19
42
  }
20
43
 
21
- // 发送Beacon消息
44
+ /** 发送成功后再出队;失败保留队列等待下次 flush 重试 */
45
+ }, {
46
+ key: "flush",
47
+ value: function flush() {
48
+ while (this._queue.length > 0) {
49
+ var _Config$data$batchSiz2;
50
+ var batchSize = (_Config$data$batchSiz2 = Config.data.batchSize) !== null && _Config$data$batchSiz2 !== void 0 ? _Config$data$batchSiz2 : TRACK_LIMITS.maxItems;
51
+ var batch = this._queue.slice(0, batchSize);
52
+ var payload = _objectSpread(_objectSpread({}, buildEnvelopeBase()), {}, {
53
+ events: batch
54
+ });
55
+ if (this.sendBatch(JSON.stringify(payload)) === 'retry') return;
56
+ // sent / drop 都出队
57
+ this._queue.splice(0, batch.length);
58
+ }
59
+ }
60
+ }, {
61
+ key: "sendBatch",
62
+ value: function sendBatch(payload) {
63
+ // 优先 sendBeacon(页面卸载场景仍可送达);不可用或入队失败时降级 fetch(keepalive)
64
+ var sent = this.trySendBeacon(payload) || this.trySendKeepalive(payload);
65
+ if (sent) {
66
+ this._failCount = 0;
67
+ return 'sent';
68
+ }
69
+ this._failCount += 1;
70
+ if (this._failCount > this.MAX_RETRIES) {
71
+ this._failCount = 0;
72
+ return 'drop';
73
+ }
74
+ return 'retry';
75
+ }
22
76
  }, {
23
- key: "send",
24
- value: function send(data) {
25
- var _navigator;
26
- var api = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '/pousheng-guard/api/track';
27
- var sendData = data ? data : this._queue.splice(0, 5);
28
- // 判断 sendData 是否为空
29
- if (!sendData || Array.isArray(sendData) && sendData.length === 0) {
30
- return;
77
+ key: "trySendBeacon",
78
+ value: function trySendBeacon(payload) {
79
+ if (typeof navigator === 'undefined' || !navigator.sendBeacon) return false;
80
+ try {
81
+ return navigator.sendBeacon(trackUrl('/batch'), new Blob([payload], {
82
+ type: TRACK_CONTENT_TYPE
83
+ }));
84
+ } catch (error) {
85
+ return false;
31
86
  }
32
- var blob = new Blob([JSON.stringify(sendData)], {
33
- type: 'application/json'
34
- });
35
- (_navigator = navigator) === null || _navigator === void 0 || _navigator.sendBeacon("".concat(Config.data.domain).concat(api), blob);
36
87
  }
37
88
 
38
- // 更新Track版本号
89
+ /** fetch keepalive:无 sendBeacon 环境的主要通道,已发出即视为送达(不等响应、不阻塞队列) */
39
90
  }, {
40
- key: "updateVersion",
41
- value: function updateVersion() {
42
- // 获取缓存中的版本信息
43
- var storageKey = "__TrackVersion__";
44
- var cachedVersion = localStorage.getItem(storageKey);
45
- if (cachedVersion !== packageJson.version) {
46
- this.send({
47
- appId: Config.data.appId,
48
- version: packageJson.version
49
- }, '/pousheng-guard/api/apps/version/update');
50
- localStorage.setItem(storageKey, packageJson.version);
91
+ key: "trySendKeepalive",
92
+ value: function trySendKeepalive(payload) {
93
+ if (typeof fetch !== 'function') return false;
94
+ try {
95
+ void fetch(trackUrl('/batch'), {
96
+ method: 'POST',
97
+ headers: {
98
+ 'Content-Type': TRACK_CONTENT_TYPE
99
+ },
100
+ body: payload,
101
+ keepalive: true
102
+ }).catch(function () {
103
+ return undefined;
104
+ });
105
+ return true;
106
+ } catch (error) {
107
+ return false;
51
108
  }
52
109
  }
53
110
  }]);
54
111
  return Beacon;
55
112
  }();
56
- // 消息队列
57
113
  _defineProperty(Beacon, "_queue", []);
114
+ _defineProperty(Beacon, "_timer", null);
115
+ /** 连续发送失败次数,超过重试上限后丢弃当前批次,避免队列无限增长 */
116
+ _defineProperty(Beacon, "_failCount", 0);
117
+ _defineProperty(Beacon, "MAX_RETRIES", 3);
58
118
  export { Beacon as default };
@@ -3,6 +3,10 @@ export interface IConfig {
3
3
  domain: string;
4
4
  autoReportError?: boolean;
5
5
  enableReplay?: boolean;
6
+ batchSize?: number;
7
+ flushInterval?: number;
8
+ replayMaxBytes?: number;
9
+ replayMaskTextClass?: string | RegExp;
6
10
  }
7
11
  export default class Config {
8
12
  private static _data;
@@ -1,6 +1,7 @@
1
1
  import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
2
2
  import _createClass from "@babel/runtime/helpers/esm/createClass";
3
3
  import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
4
+ import { TRACK_LIMITS } from "../interfaces/protocol";
4
5
  var Config = /*#__PURE__*/function () {
5
6
  function Config() {
6
7
  _classCallCheck(this, Config);
@@ -29,6 +30,9 @@ _defineProperty(Config, "_data", {
29
30
  appId: '',
30
31
  domain: '',
31
32
  autoReportError: true,
32
- enableReplay: true
33
+ enableReplay: true,
34
+ batchSize: TRACK_LIMITS.maxItems,
35
+ flushInterval: 10000,
36
+ replayMaxBytes: 1024 * 1024
33
37
  });
34
38
  export { Config as default };
@@ -22,20 +22,24 @@ var Listener = /*#__PURE__*/function () {
22
22
  clearTimeout(_this._reporter);
23
23
  }
24
24
  _this._reporter = setTimeout(function () {
25
+ var _event$error;
25
26
  // 立即触发上报当前剩余的 Beacon 数据
26
- Beacon.send();
27
- Log.errorLog(event.message);
27
+ Beacon.flush();
28
+ Log.errorLog(event.message, (_event$error = event.error) === null || _event$error === void 0 ? void 0 : _event$error.stack);
28
29
  _this._reporter = null;
29
30
  }, 1000);
30
31
  });
31
32
 
32
- // 监听页面可见性变化
33
+ // 页面隐藏 / 卸载前兜底 flush,保证队列数据送达
33
34
  document.addEventListener('visibilitychange', function () {
34
35
  var _document;
35
36
  if (((_document = document) === null || _document === void 0 ? void 0 : _document.visibilityState) === 'hidden') {
36
- Beacon.send();
37
+ Beacon.flush();
37
38
  }
38
39
  });
40
+ window.addEventListener('pagehide', function () {
41
+ Beacon.flush();
42
+ });
39
43
  this._loaded = true;
40
44
  }
41
45
  }]);
@@ -1,9 +1,19 @@
1
+ /**
2
+ * 日志上报入口。
3
+ *
4
+ * 配置语义:`autoReportError` 只控制是否自动监听 window.onerror(见 Listener);
5
+ * 回放是否随错误一起上报只看 `enableReplay`(见 Replay.run)。
6
+ */
1
7
  export default class Log {
2
8
  private static _module;
3
9
  static get module(): string;
4
- private static _commonProps;
5
10
  static visitLog(module: string): void;
6
11
  static eventLog(content: string): void;
7
- static errorLog(message: string): Promise<void>;
8
12
  static apiLog(log: string): void;
13
+ /**
14
+ * 错误 + 回放一次请求内嵌上报(通道 2)。
15
+ * fetch 失败或页面卸载导致未送达时,用 sendBeacon 补发不含回放的纯错误:
16
+ * 卸载场景 fetch 不可靠,至少保住错误本体,回放可接受丢失。
17
+ */
18
+ static errorLog(message: string, stack?: string): Promise<void>;
9
19
  }
package/dist/Track/Log.js CHANGED
@@ -4,11 +4,17 @@ import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
4
4
  import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
5
5
  import _createClass from "@babel/runtime/helpers/esm/createClass";
6
6
  import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
7
+ import { TRACK_CONTENT_TYPE } from "../interfaces/protocol";
7
8
  import Beacon from "./Beacon";
8
- import Config from "./Config";
9
+ import { buildEnvelopeBase, buildEventBase, trackUrl } from "./envelope";
9
10
  import Replay from "./Replay";
10
- import System from "./System";
11
- import User from "./User";
11
+
12
+ /**
13
+ * 日志上报入口。
14
+ *
15
+ * 配置语义:`autoReportError` 只控制是否自动监听 window.onerror(见 Listener);
16
+ * 回放是否随错误一起上报只看 `enableReplay`(见 Replay.run)。
17
+ */
12
18
  var Log = /*#__PURE__*/function () {
13
19
  function Log() {
14
20
  _classCallCheck(this, Log);
@@ -20,85 +26,102 @@ var Log = /*#__PURE__*/function () {
20
26
  function get() {
21
27
  return this._module;
22
28
  }
23
-
24
- // 上报日志的公共属性
25
- }, {
26
- key: "_commonProps",
27
- value: function _commonProps() {
28
- return _objectSpread(_objectSpread(_objectSpread({}, User.profile), System.profile), {}, {
29
- appId: Config.data.appId,
30
- module: this._module
31
- });
32
- }
33
29
  }, {
34
30
  key: "visitLog",
35
31
  value: function visitLog(module) {
36
32
  this._module = module;
37
33
  var lastModule = this._module.split('-').pop();
38
- Beacon.push(_objectSpread(_objectSpread({}, this._commonProps()), {}, {
34
+ Beacon.push(_objectSpread(_objectSpread({}, buildEventBase()), {}, {
39
35
  type: 'visit',
36
+ module: module,
40
37
  content: "\u8BBF\u95EE\u9875\u9762\uFF1A".concat(lastModule)
41
38
  }));
42
39
  }
43
40
  }, {
44
41
  key: "eventLog",
45
42
  value: function eventLog(content) {
46
- Beacon.push(_objectSpread(_objectSpread({}, this._commonProps()), {}, {
43
+ Beacon.push(_objectSpread(_objectSpread({}, buildEventBase()), {}, {
47
44
  type: 'event',
45
+ module: this._module,
48
46
  content: content
49
47
  }));
50
48
  }
49
+ }, {
50
+ key: "apiLog",
51
+ value: function apiLog(log) {
52
+ Beacon.push(_objectSpread(_objectSpread({}, buildEventBase()), {}, {
53
+ type: 'api',
54
+ module: this._module,
55
+ log: log
56
+ }));
57
+ }
58
+
59
+ /**
60
+ * 错误 + 回放一次请求内嵌上报(通道 2)。
61
+ * fetch 失败或页面卸载导致未送达时,用 sendBeacon 补发不含回放的纯错误:
62
+ * 卸载场景 fetch 不可靠,至少保住错误本体,回放可接受丢失。
63
+ */
51
64
  }, {
52
65
  key: "errorLog",
53
- value: function () {
54
- var _errorLog = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(message) {
55
- var res, _yield$res$json, id;
66
+ value: (function () {
67
+ var _errorLog = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(message, stack) {
68
+ var replay, pureError, payload, res, _navigator, _navigator$sendBeacon;
56
69
  return _regeneratorRuntime().wrap(function _callee$(_context) {
57
70
  while (1) switch (_context.prev = _context.next) {
58
71
  case 0:
59
- _context.next = 2;
60
- return fetch("".concat(Config.data.domain, "/pousheng-guard/api/track/error"), {
72
+ replay = Replay.snapshot();
73
+ pureError = _objectSpread(_objectSpread({}, buildEnvelopeBase()), {}, {
74
+ error: _objectSpread(_objectSpread({}, buildEventBase()), {}, {
75
+ message: message,
76
+ stack: stack,
77
+ module: this._module
78
+ })
79
+ });
80
+ payload = replay.length ? _objectSpread(_objectSpread({}, pureError), {}, {
81
+ replay: replay
82
+ }) : pureError;
83
+ _context.prev = 3;
84
+ _context.next = 6;
85
+ return fetch(trackUrl('/error'), {
61
86
  method: 'POST',
62
87
  headers: {
63
- 'Content-Type': 'application/json'
88
+ 'Content-Type': TRACK_CONTENT_TYPE
64
89
  },
65
- body: JSON.stringify(_objectSpread(_objectSpread({}, this._commonProps()), {}, {
66
- type: 'error',
67
- log: JSON.stringify({
68
- message: message
69
- })
70
- }))
90
+ body: JSON.stringify(payload)
71
91
  });
72
- case 2:
92
+ case 6:
73
93
  res = _context.sent;
74
- _context.next = 5;
75
- return res.json();
76
- case 5:
77
- _yield$res$json = _context.sent;
78
- id = _yield$res$json.data;
79
- if (Config.data.autoReportError) {
80
- // 上报回放片段
81
- Replay.reportSnapshot(id);
94
+ if (res.ok) {
95
+ _context.next = 9;
96
+ break;
97
+ }
98
+ throw new Error("HTTP ".concat(res.status));
99
+ case 9:
100
+ // 上报成功后才移除已携带的回放事件,继续录制(不 stop)
101
+ Replay.commitSnapshot(replay);
102
+ _context.next = 15;
103
+ break;
104
+ case 12:
105
+ _context.prev = 12;
106
+ _context.t0 = _context["catch"](3);
107
+ try {
108
+ (_navigator = navigator) === null || _navigator === void 0 || (_navigator$sendBeacon = _navigator.sendBeacon) === null || _navigator$sendBeacon === void 0 || _navigator$sendBeacon.call(_navigator, trackUrl('/error'), new Blob([JSON.stringify(pureError)], {
109
+ type: TRACK_CONTENT_TYPE
110
+ }));
111
+ } catch (beaconError) {
112
+ // beacon 也不可用(如页面已卸载),放弃本次错误上报,不阻断业务
82
113
  }
83
- case 8:
114
+ case 15:
84
115
  case "end":
85
116
  return _context.stop();
86
117
  }
87
- }, _callee, this);
118
+ }, _callee, this, [[3, 12]]);
88
119
  }));
89
- function errorLog(_x) {
120
+ function errorLog(_x, _x2) {
90
121
  return _errorLog.apply(this, arguments);
91
122
  }
92
123
  return errorLog;
93
- }()
94
- }, {
95
- key: "apiLog",
96
- value: function apiLog(log) {
97
- Beacon.push(_objectSpread(_objectSpread({}, this._commonProps()), {}, {
98
- type: 'api',
99
- log: log
100
- }));
101
- }
124
+ }())
102
125
  }]);
103
126
  return Log;
104
127
  }();
@@ -1,6 +1,23 @@
1
+ type RRWebEvent = any;
1
2
  export default class Replay {
2
3
  private static _events;
3
4
  private static _stop;
4
- static run(): void;
5
- static reportSnapshot(errorId: string): Promise<void>;
5
+ private static _loading;
6
+ private static _bytes;
7
+ /**
8
+ * 启动录制。
9
+ *
10
+ * rrweb(record 与 console 插件)改为动态 import:`enableReplay: false` 时完全不加载,
11
+ * 接入方的打包产物里也就不含 rrweb;开启回放时 rrweb 由接入方打包器拆成独立异步 chunk。
12
+ * 代价是启动异步化——加载完成前发生的错误不带回放(`snapshot()` 返回空数组,
13
+ * 错误本体的上报不受影响)。
14
+ */
15
+ static run(): Promise<void>;
16
+ /** 截断到体积上限,保留最近片段 */
17
+ private static truncate;
18
+ /** 快照当前回放片段(不移除,待上报成功后 commitSnapshot) */
19
+ static snapshot(): RRWebEvent[];
20
+ /** 上报成功后移除已携带的事件,继续录制——不调用 stop,避免下一个错误重复携带上一段 */
21
+ static commitSnapshot(snapshot: RRWebEvent[]): void;
6
22
  }
23
+ export {};
@@ -1,10 +1,11 @@
1
+ import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
1
2
  import _regeneratorRuntime from "@babel/runtime/helpers/esm/regeneratorRuntime";
3
+ import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
4
+ import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
2
5
  import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
3
6
  import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
4
7
  import _createClass from "@babel/runtime/helpers/esm/createClass";
5
8
  import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
6
- import { record } from '@rrweb/record';
7
- import { getRecordConsolePlugin } from '@rrweb/rrweb-plugin-console-record';
8
9
  import Config from "./Config";
9
10
  var Replay = /*#__PURE__*/function () {
10
11
  function Replay() {
@@ -12,70 +13,118 @@ var Replay = /*#__PURE__*/function () {
12
13
  }
13
14
  _createClass(Replay, null, [{
14
15
  key: "run",
15
- value: function run() {
16
- var _this = this;
17
- if (this._stop || !Config.data.enableReplay) {
18
- return;
19
- }
20
- try {
21
- this._stop = record({
22
- emit: function emit(e) {
23
- _this._events.push(e);
24
- // 截断到最大长度
25
- var over = _this._events.length - 1000;
26
- if (over > 0) _this._events.splice(0, over);
27
- },
28
- plugins: [getRecordConsolePlugin({
29
- level: ['log', 'info', 'warn', 'error', 'debug']
30
- })]
31
- });
32
- } catch (err) {
33
- this._stop = undefined;
34
- }
35
- }
36
-
37
- // 快照
38
- }, {
39
- key: "reportSnapshot",
40
- value: function () {
41
- var _reportSnapshot = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(errorId) {
42
- var _this$_stop;
16
+ value: (
17
+ /**
18
+ * 启动录制。
19
+ *
20
+ * rrweb(record 与 console 插件)改为动态 import:`enableReplay: false` 时完全不加载,
21
+ * 接入方的打包产物里也就不含 rrweb;开启回放时 rrweb 由接入方打包器拆成独立异步 chunk。
22
+ * 代价是启动异步化——加载完成前发生的错误不带回放(`snapshot()` 返回空数组,
23
+ * 错误本体的上报不受影响)。
24
+ */
25
+ function () {
26
+ var _run = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
27
+ var _this = this;
28
+ var _yield$Promise$all, _yield$Promise$all2, startRecord, getRecordConsolePlugin;
43
29
  return _regeneratorRuntime().wrap(function _callee$(_context) {
44
30
  while (1) switch (_context.prev = _context.next) {
45
31
  case 0:
46
- if (this._stop) {
32
+ if (!(this._stop || this._loading || !Config.data.enableReplay)) {
47
33
  _context.next = 2;
48
34
  break;
49
35
  }
50
36
  return _context.abrupt("return");
51
37
  case 2:
52
- _context.next = 4;
53
- return fetch("".concat(Config.data.domain, "/pousheng-guard/api/track/error-replay/").concat(errorId), {
54
- method: 'POST',
55
- headers: {
56
- 'Content-Type': 'text/plain'
38
+ this._loading = true;
39
+ _context.prev = 3;
40
+ _context.next = 6;
41
+ return Promise.all([import('@rrweb/record'), import('@rrweb/rrweb-plugin-console-record')]);
42
+ case 6:
43
+ _yield$Promise$all = _context.sent;
44
+ _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2);
45
+ startRecord = _yield$Promise$all2[0].record;
46
+ getRecordConsolePlugin = _yield$Promise$all2[1].getRecordConsolePlugin;
47
+ this._stop = startRecord(_objectSpread(_objectSpread({
48
+ emit: function emit(e) {
49
+ _this._events.push(e);
50
+ _this._bytes += JSON.stringify(e).length;
51
+ _this.truncate();
57
52
  },
58
- body: JSON.stringify(this._events)
59
- });
60
- case 4:
61
- // 上报完成后停止本次行为的录制,清空事件队列
62
- (_this$_stop = this._stop) === null || _this$_stop === void 0 || _this$_stop.call(this);
53
+ // 输入掩码:password 类型强制掩码,防止敏感输入进入回放文件;
54
+ // 其余类型可由接入方通过 replayMaskTextClass 扩展
55
+ maskInputOptions: {
56
+ password: true
57
+ }
58
+ }, Config.data.replayMaskTextClass ? {
59
+ maskTextClass: Config.data.replayMaskTextClass
60
+ } : {}), {}, {
61
+ plugins: [getRecordConsolePlugin({
62
+ level: ['log', 'info', 'warn', 'error', 'debug']
63
+ })]
64
+ }));
65
+ _context.next = 16;
66
+ break;
67
+ case 13:
68
+ _context.prev = 13;
69
+ _context.t0 = _context["catch"](3);
70
+ // 加载或启动失败:静默降级,仅回放不可用
63
71
  this._stop = undefined;
64
- this._events = [];
65
- case 7:
72
+ case 16:
73
+ _context.prev = 16;
74
+ this._loading = false;
75
+ return _context.finish(16);
76
+ case 19:
66
77
  case "end":
67
78
  return _context.stop();
68
79
  }
69
- }, _callee, this);
80
+ }, _callee, this, [[3, 13, 16, 19]]);
70
81
  }));
71
- function reportSnapshot(_x) {
72
- return _reportSnapshot.apply(this, arguments);
82
+ function run() {
83
+ return _run.apply(this, arguments);
84
+ }
85
+ return run;
86
+ }() /** 截断到体积上限,保留最近片段 */)
87
+ }, {
88
+ key: "truncate",
89
+ value: function truncate() {
90
+ var _Config$data$replayMa;
91
+ var maxBytes = (_Config$data$replayMa = Config.data.replayMaxBytes) !== null && _Config$data$replayMa !== void 0 ? _Config$data$replayMa : 1024 * 1024;
92
+ while (this._bytes > maxBytes && this._events.length > 1) {
93
+ var removed = this._events.shift();
94
+ this._bytes -= removed ? JSON.stringify(removed).length : 0;
73
95
  }
74
- return reportSnapshot;
75
- }()
96
+ }
97
+
98
+ /** 快照当前回放片段(不移除,待上报成功后 commitSnapshot) */
99
+ }, {
100
+ key: "snapshot",
101
+ value: function snapshot() {
102
+ return this._stop ? _toConsumableArray(this._events) : [];
103
+ }
104
+
105
+ /** 上报成功后移除已携带的事件,继续录制——不调用 stop,避免下一个错误重复携带上一段 */
106
+ }, {
107
+ key: "commitSnapshot",
108
+ value: function commitSnapshot(snapshot) {
109
+ var _this2 = this;
110
+ if (!snapshot.length) return;
111
+ var sent = new Set(snapshot);
112
+ this._events = this._events.filter(function (e) {
113
+ if (sent.has(e)) {
114
+ _this2._bytes -= JSON.stringify(e).length;
115
+ return false;
116
+ }
117
+ return true;
118
+ });
119
+ if (this._bytes < 0) this._bytes = 0;
120
+ }
76
121
  }]);
77
122
  return Replay;
78
123
  }();
79
124
  _defineProperty(Replay, "_events", []);
80
125
  _defineProperty(Replay, "_stop", void 0);
126
+ // rrweb 异步加载中的标记:避免 init 被重复调用时启动两个录制实例
127
+ _defineProperty(Replay, "_loading", false);
128
+ // 录制阶段的累计体积(近似值),达到 replayMaxBytes 后从最早事件开始截断
129
+ _defineProperty(Replay, "_bytes", 0);
81
130
  export { Replay as default };
@@ -1,5 +1,7 @@
1
1
  import { SystemProfile } from '../interfaces/track.interface';
2
2
  export default class System {
3
- private static IMEI;
3
+ private static readonly _imei;
4
+ /** 会话串,作为信封必填的 imei 上报(生成逻辑不变) */
5
+ static get imei(): string;
4
6
  static get profile(): SystemProfile;
5
7
  }