@yysports/tools 2.2.6 → 3.0.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 (45) 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 +9 -1
  10. package/dist/Track/Replay.js +49 -44
  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 +2 -1
  16. package/dist/Utils/route.js +1 -1
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.js +2 -1
  19. package/dist/interfaces/protocol.d.ts +94 -0
  20. package/dist/interfaces/protocol.js +65 -0
  21. package/dist/interfaces/track.interface.d.ts +3 -8
  22. package/dist/interfaces/track.interface.js +3 -8
  23. package/lib/Track/Beacon.d.ts +22 -3
  24. package/lib/Track/Beacon.js +70 -28
  25. package/lib/Track/Config.d.ts +4 -0
  26. package/lib/Track/Config.js +5 -1
  27. package/lib/Track/Listener.js +7 -3
  28. package/lib/Track/Log.d.ts +12 -2
  29. package/lib/Track/Log.js +46 -35
  30. package/lib/Track/Replay.d.ts +9 -1
  31. package/lib/Track/Replay.js +32 -20
  32. package/lib/Track/System.d.ts +3 -1
  33. package/lib/Track/System.js +6 -2
  34. package/lib/Track/envelope.d.ts +7 -0
  35. package/lib/Track/envelope.js +76 -0
  36. package/lib/Track/index.js +1 -1
  37. package/lib/Utils/route.js +1 -1
  38. package/lib/index.d.ts +1 -0
  39. package/lib/index.js +3 -1
  40. package/lib/interfaces/protocol.d.ts +94 -0
  41. package/lib/interfaces/protocol.js +66 -0
  42. package/lib/interfaces/track.interface.d.ts +3 -8
  43. package/lib/interfaces/track.interface.js +5 -9
  44. package/package.json +20 -20
  45. 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,14 @@
1
+ type RRWebEvent = any;
1
2
  export default class Replay {
2
3
  private static _events;
3
4
  private static _stop;
5
+ private static _bytes;
4
6
  static run(): void;
5
- static reportSnapshot(errorId: string): Promise<void>;
7
+ /** 截断到体积上限,保留最近片段 */
8
+ private static truncate;
9
+ /** 快照当前回放片段(不移除,待上报成功后 commitSnapshot) */
10
+ static snapshot(): RRWebEvent[];
11
+ /** 上报成功后移除已携带的事件,继续录制——不调用 stop,避免下一个错误重复携带上一段 */
12
+ static commitSnapshot(snapshot: RRWebEvent[]): void;
6
13
  }
14
+ export {};
@@ -1,5 +1,5 @@
1
- import _regeneratorRuntime from "@babel/runtime/helpers/esm/regeneratorRuntime";
2
- import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
1
+ import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
2
+ import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
3
3
  import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
4
4
  import _createClass from "@babel/runtime/helpers/esm/createClass";
5
5
  import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
@@ -18,64 +18,69 @@ var Replay = /*#__PURE__*/function () {
18
18
  return;
19
19
  }
20
20
  try {
21
- this._stop = record({
21
+ this._stop = record(_objectSpread(_objectSpread({
22
22
  emit: function emit(e) {
23
23
  _this._events.push(e);
24
- // 截断到最大长度
25
- var over = _this._events.length - 1000;
26
- if (over > 0) _this._events.splice(0, over);
24
+ _this._bytes += JSON.stringify(e).length;
25
+ _this.truncate();
27
26
  },
27
+ // 输入掩码:password 类型强制掩码,防止敏感输入进入回放文件;
28
+ // 其余类型可由接入方通过 replayMaskTextClass 扩展
29
+ maskInputOptions: {
30
+ password: true
31
+ }
32
+ }, Config.data.replayMaskTextClass ? {
33
+ maskTextClass: Config.data.replayMaskTextClass
34
+ } : {}), {}, {
28
35
  plugins: [getRecordConsolePlugin({
29
36
  level: ['log', 'info', 'warn', 'error', 'debug']
30
37
  })]
31
- });
38
+ }));
32
39
  } catch (err) {
33
40
  this._stop = undefined;
34
41
  }
35
42
  }
36
43
 
37
- // 快照
44
+ /** 截断到体积上限,保留最近片段 */
38
45
  }, {
39
- key: "reportSnapshot",
40
- value: function () {
41
- var _reportSnapshot = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(errorId) {
42
- var _this$_stop;
43
- return _regeneratorRuntime().wrap(function _callee$(_context) {
44
- while (1) switch (_context.prev = _context.next) {
45
- case 0:
46
- if (this._stop) {
47
- _context.next = 2;
48
- break;
49
- }
50
- return _context.abrupt("return");
51
- 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'
57
- },
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);
63
- this._stop = undefined;
64
- this._events = [];
65
- case 7:
66
- case "end":
67
- return _context.stop();
68
- }
69
- }, _callee, this);
70
- }));
71
- function reportSnapshot(_x) {
72
- return _reportSnapshot.apply(this, arguments);
46
+ key: "truncate",
47
+ value: function truncate() {
48
+ var _Config$data$replayMa;
49
+ var maxBytes = (_Config$data$replayMa = Config.data.replayMaxBytes) !== null && _Config$data$replayMa !== void 0 ? _Config$data$replayMa : 1024 * 1024;
50
+ while (this._bytes > maxBytes && this._events.length > 1) {
51
+ var removed = this._events.shift();
52
+ this._bytes -= removed ? JSON.stringify(removed).length : 0;
73
53
  }
74
- return reportSnapshot;
75
- }()
54
+ }
55
+
56
+ /** 快照当前回放片段(不移除,待上报成功后 commitSnapshot) */
57
+ }, {
58
+ key: "snapshot",
59
+ value: function snapshot() {
60
+ return this._stop ? _toConsumableArray(this._events) : [];
61
+ }
62
+
63
+ /** 上报成功后移除已携带的事件,继续录制——不调用 stop,避免下一个错误重复携带上一段 */
64
+ }, {
65
+ key: "commitSnapshot",
66
+ value: function commitSnapshot(snapshot) {
67
+ var _this2 = this;
68
+ if (!snapshot.length) return;
69
+ var sent = new Set(snapshot);
70
+ this._events = this._events.filter(function (e) {
71
+ if (sent.has(e)) {
72
+ _this2._bytes -= JSON.stringify(e).length;
73
+ return false;
74
+ }
75
+ return true;
76
+ });
77
+ if (this._bytes < 0) this._bytes = 0;
78
+ }
76
79
  }]);
77
80
  return Replay;
78
81
  }();
79
82
  _defineProperty(Replay, "_events", []);
80
83
  _defineProperty(Replay, "_stop", void 0);
84
+ // 录制阶段的累计体积(近似值),达到 replayMaxBytes 后从最早事件开始截断
85
+ _defineProperty(Replay, "_bytes", 0);
81
86
  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
  }
@@ -7,10 +7,16 @@ var System = /*#__PURE__*/function () {
7
7
  _classCallCheck(this, System);
8
8
  }
9
9
  _createClass(System, null, [{
10
+ key: "imei",
11
+ get: /** 会话串,作为信封必填的 imei 上报(生成逻辑不变) */
12
+ function get() {
13
+ return this._imei;
14
+ }
15
+ }, {
10
16
  key: "profile",
11
17
  get: function get() {
12
18
  return {
13
- IMEI: this.IMEI,
19
+ imei: this._imei,
14
20
  innerHeight: typeof window !== 'undefined' ? window.innerHeight : 0,
15
21
  innerWidth: typeof window !== 'undefined' ? window.innerWidth : 0,
16
22
  href: typeof location !== 'undefined' ? location.href : '',
@@ -20,5 +26,5 @@ var System = /*#__PURE__*/function () {
20
26
  }]);
21
27
  return System;
22
28
  }();
23
- _defineProperty(System, "IMEI", generateRandomString(6));
29
+ _defineProperty(System, "_imei", generateRandomString(6));
24
30
  export { System as default };
@@ -0,0 +1,7 @@
1
+ import type { TrackV3Envelope, TrackV3Event } from '../interfaces/protocol';
2
+ /** 请求级公共段(信封):字段与实体属性同名(camelCase),每次请求仅一份 */
3
+ export declare function buildEnvelopeBase(): TrackV3Envelope;
4
+ /** 条级事件公共字段:href / 视口 / 毫秒时间戳在批量窗口内会变,逐条携带 */
5
+ export declare function buildEventBase(): Pick<TrackV3Event, 'systemTime' | 'href' | 'innerWidth' | 'innerHeight'>;
6
+ /** V3 上报地址:鉴权参数位统一走 URL query(sendBeacon 无法自定义 header) */
7
+ export declare function trackUrl(path: '/batch' | '/error'): string;
@@ -0,0 +1,40 @@
1
+ import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
2
+ import packageJson from "../../package.json";
3
+ import Config from "./Config";
4
+ import System from "./System";
5
+ import User from "./User";
6
+
7
+ /** 请求级公共段(信封):字段与实体属性同名(camelCase),每次请求仅一份 */
8
+ export function buildEnvelopeBase() {
9
+ var profile = User.profile;
10
+ return _objectSpread({
11
+ appId: Config.data.appId,
12
+ sdkVersion: packageJson.version,
13
+ imei: System.imei
14
+ }, profile ? {
15
+ user: {
16
+ userId: profile.userId,
17
+ userName: profile.userName,
18
+ orgCode: profile.orgCode,
19
+ orgTitle: profile.orgTitle,
20
+ dataScopeZonePermissions: profile.dataScopeZonePermissions,
21
+ dataScopeRoles: profile.dataScopeRoles
22
+ }
23
+ } : {});
24
+ }
25
+
26
+ /** 条级事件公共字段:href / 视口 / 毫秒时间戳在批量窗口内会变,逐条携带 */
27
+ export function buildEventBase() {
28
+ return {
29
+ systemTime: Date.now(),
30
+ href: typeof location !== 'undefined' ? location.href : '',
31
+ innerWidth: typeof window !== 'undefined' ? window.innerWidth : 0,
32
+ innerHeight: typeof window !== 'undefined' ? window.innerHeight : 0
33
+ };
34
+ }
35
+
36
+ /** V3 上报地址:鉴权参数位统一走 URL query(sendBeacon 无法自定义 header) */
37
+ export function trackUrl(path) {
38
+ var appId = encodeURIComponent(Config.data.appId);
39
+ return "".concat(Config.data.domain, "/pousheng-guard/api/track/v3").concat(path, "?appId=").concat(appId);
40
+ }