@jasolar/tracker-sdk 1.0.10 → 1.0.12

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.
package/dist/index.esm.js CHANGED
@@ -92,6 +92,15 @@ function _toPropertyKey(t) {
92
92
  var i = _toPrimitive(t, "string");
93
93
  return "symbol" == typeof i ? i : i + "";
94
94
  }
95
+ function _typeof(o) {
96
+ "@babel/helpers - typeof";
97
+
98
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
99
+ return typeof o;
100
+ } : function (o) {
101
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
102
+ }, _typeof(o);
103
+ }
95
104
  function _unsupportedIterableToArray(r, a) {
96
105
  if (r) {
97
106
  if ("string" == typeof r) return _arrayLikeToArray(r, a);
@@ -109,6 +118,7 @@ var Queue = /*#__PURE__*/function () {
109
118
  * @param {Object} options - 配置项
110
119
  * @param {number} [options.delay=1000] - 批量发送的延迟时间(毫秒)。
111
120
  * @param {number} [options.maxBatchSize=10] - 最大批量大小,达到此数量时立即发送。
121
+ * @param {Function} [options.log] - debug 日志函数。
112
122
  */
113
123
  function Queue(flushFn) {
114
124
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@@ -118,6 +128,7 @@ var Queue = /*#__PURE__*/function () {
118
128
  this.timer = null;
119
129
  this.delay = options.delay || 1000;
120
130
  this.maxBatchSize = options.maxBatchSize || 10;
131
+ this.log = options.log || function () {};
121
132
  }
122
133
 
123
134
  /**
@@ -151,27 +162,22 @@ var Queue = /*#__PURE__*/function () {
151
162
  }, {
152
163
  key: "flush",
153
164
  value: function flush() {
154
- var _this2 = this;
155
165
  var isFlush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
156
166
  if (!this.list.length) {
157
- console.log('[Tracker SDK] Queue flush called but queue is empty');
167
+ this.log("Queue flush called but queue is empty");
158
168
  return;
159
169
  }
160
- console.log('[Tracker SDK] Flushing queue, items:', this.list.length, 'isFlush:', isFlush);
170
+ this.log("Flushing queue, items:", this.list.length, "isFlush:", isFlush);
161
171
 
162
172
  // 复制一份数据列表,防止在发送过程中 list 被修改
163
173
  var dataToSend = _toConsumableArray(this.list);
164
174
  this.list = []; // 清空队列
165
175
 
166
176
  try {
167
- // 逐条发送数据,而不是批量发送
168
- dataToSend.forEach(function (item, index) {
169
- console.log("[Tracker SDK] Sending event ".concat(index + 1, "/").concat(dataToSend.length, ":"), item.event);
170
- _this2.flushFn(item, isFlush);
171
- });
172
- console.log('[Tracker SDK] All events sent successfully');
177
+ // 一次把整批交给 transport;是否真正合并成一个请求由 transport 的 batch 选项决定。
178
+ this.flushFn(dataToSend, isFlush);
173
179
  } catch (error) {
174
- console.error("[Tracker SDK] Failed to flush data:", error);
180
+ this.log("Failed to flush data:", error);
175
181
  } finally {
176
182
  clearTimeout(this.timer);
177
183
  this.timer = null;
@@ -183,90 +189,129 @@ var Queue = /*#__PURE__*/function () {
183
189
  /**
184
190
  * 发送数据到服务器。
185
191
  *
186
- * 优化逻辑:
187
- * 1. 优先使用 fetch + keepalive,以支持自定义 Authorization Header。
188
- * 2. 如果 fetch 不可用或由于 payload 过大导致失败,回退到 navigator.sendBeacon。
189
- * 3. 由于 sendBeacon 不支持 Headers,Token 会被附加到 URL 参数中。
192
+ * 兼容两种调用方式:
193
+ * - send(url, data, token, useBeacon) 旧签名(内部兼容)
194
+ * - send(url, data, { token, headers, batch, ... }) 新签名
195
+ *
196
+ * 安全默认值:
197
+ * - sendBeacon 默认不把 token 拼进 URL(beaconAuth: "none"),依赖同源网关注入身份;
198
+ * 确需 query 认证时显式设置 beaconAuth: "query"。
199
+ * - debug 关闭时不打印任何事件数据或初始化参数。
190
200
  */
191
201
 
192
- /*
193
- @param {string} url - 服务器地址
194
- @param {Object} data - 要发送的数据
195
- @param {Object} token - 认证令牌
196
- @param {boolean} useBeacon - 是否强制使用 sendBeacon(用于页面关闭场景)
197
- */
198
- function send(url, data) {
199
- var token = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
200
- var useBeacon = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
201
- if (!url) {
202
- console.warn('[Tracker SDK] Send called without URL');
203
- return;
202
+ function normalizeOptions(options, legacyUseBeacon) {
203
+ if (options && _typeof(options) === "object" && !Array.isArray(options) && ("token" in options || "headers" in options || "batch" in options || "debug" in options || "beaconAuth" in options || "useBeacon" in options)) {
204
+ return options;
204
205
  }
205
- console.log('[Tracker SDK] Sending data:', {
206
- url: url,
207
- event: data.event,
208
- module: data.module,
209
- useBeacon: useBeacon,
210
- hasToken: !!token
211
- });
212
- var body = JSON.stringify(data);
213
-
214
- // 构造请求头
215
- var headers = {
216
- 'Content-Type': 'application/json'
206
+ return {
207
+ token: options,
208
+ useBeacon: Boolean(legacyUseBeacon)
217
209
  };
218
- if (token) {
219
- headers['Authorization'] = "Bearer ".concat(token);
220
- }
221
-
222
- // 1. 如果强制使用 Beacon 或 fetch 不可用,直接使用 sendBeacon
223
- if (useBeacon && typeof navigator !== 'undefined' && navigator.sendBeacon) {
224
- console.log('[Tracker SDK] Using sendBeacon for transport');
225
- var beaconUrl = url;
226
- if (token) {
227
- var separator = url.includes('?') ? '&' : '?';
228
- beaconUrl = "".concat(url).concat(separator, "Authorization=").concat(encodeURIComponent('Bearer ' + token));
210
+ }
211
+ function appendBeaconToken(url, token) {
212
+ if (!token) return url;
213
+ var separator = url.includes("?") ? "&" : "?";
214
+ return "".concat(url).concat(separator, "Authorization=").concat(encodeURIComponent("Bearer " + token));
215
+ }
216
+ function sendOne(url, payload, options) {
217
+ var token = options.token,
218
+ _options$headers = options.headers,
219
+ extraHeaders = _options$headers === void 0 ? {} : _options$headers,
220
+ _options$useBeacon = options.useBeacon,
221
+ useBeacon = _options$useBeacon === void 0 ? false : _options$useBeacon,
222
+ _options$debug = options.debug,
223
+ debug = _options$debug === void 0 ? false : _options$debug,
224
+ _options$beaconAuth = options.beaconAuth,
225
+ beaconAuth = _options$beaconAuth === void 0 ? "none" : _options$beaconAuth,
226
+ _options$maxKeepalive = options.maxKeepaliveBytes,
227
+ maxKeepaliveBytes = _options$maxKeepalive === void 0 ? 60 * 1024 : _options$maxKeepalive,
228
+ _options$credentials = options.credentials,
229
+ credentials = _options$credentials === void 0 ? "same-origin" : _options$credentials;
230
+ var log = function log() {
231
+ var _console;
232
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
233
+ args[_key] = arguments[_key];
229
234
  }
235
+ if (debug) (_console = console).log.apply(_console, ["[Tracker SDK]"].concat(args));
236
+ };
237
+ var body = JSON.stringify(payload);
238
+ if (useBeacon && typeof navigator !== "undefined" && navigator.sendBeacon) {
239
+ var beaconUrl = beaconAuth === "query" ? appendBeaconToken(url, token) : url;
230
240
  var blob = new Blob([body], {
231
- type: 'application/json'
241
+ type: "application/json"
232
242
  });
233
243
  var result = navigator.sendBeacon(beaconUrl, blob);
234
- console.log('[Tracker SDK] sendBeacon result:', result);
244
+ log("sendBeacon", {
245
+ ok: result,
246
+ beaconAuth: beaconAuth
247
+ });
235
248
  return result;
236
249
  }
237
-
238
- // 2. 正常场景优先使用 fetch + keepalive
239
- if (typeof fetch === 'function') {
250
+ if (typeof fetch === "function") {
251
+ var headers = _objectSpread2({
252
+ "Content-Type": "application/json"
253
+ }, extraHeaders);
254
+ if (token) headers.Authorization = "Bearer ".concat(token);
255
+ var canKeepalive = body.length <= maxKeepaliveBytes;
240
256
  try {
241
257
  fetch(url, {
242
- method: 'POST',
258
+ method: "POST",
243
259
  body: body,
244
260
  headers: headers,
245
- keepalive: true,
246
- mode: 'cors'
261
+ credentials: credentials,
262
+ mode: "cors",
263
+ keepalive: canKeepalive
247
264
  }).catch(function (err) {
248
- console.warn('[Tracker SDK] fetch report failed:', err);
265
+ log("fetch report failed:", (err === null || err === void 0 ? void 0 : err.message) || err);
266
+ });
267
+ log("fetch report", {
268
+ bytes: body.length,
269
+ keepalive: canKeepalive
249
270
  });
250
271
  return;
251
272
  } catch (e) {
252
- console.warn('[Tracker SDK] fetch keepalive failed, trying sendBeacon:', e);
273
+ log("fetch keepalive failed, trying sendBeacon:", (e === null || e === void 0 ? void 0 : e.message) || e);
253
274
  }
254
275
  }
255
-
256
- // 3. 备选方案:navigator.sendBeacon
257
- if (typeof navigator !== 'undefined' && navigator.sendBeacon) {
258
- var _beaconUrl = url;
259
- if (token) {
260
- var _separator = url.includes('?') ? '&' : '?';
261
- _beaconUrl = "".concat(url).concat(_separator, "Authorization=").concat(encodeURIComponent('Bearer ' + token));
262
- }
276
+ if (typeof navigator !== "undefined" && navigator.sendBeacon) {
277
+ var _beaconUrl = beaconAuth === "query" ? appendBeaconToken(url, token) : url;
263
278
  var _blob = new Blob([body], {
264
- type: 'application/json'
279
+ type: "application/json"
265
280
  });
266
281
  var success = navigator.sendBeacon(_beaconUrl, _blob);
282
+ log("sendBeacon fallback", {
283
+ ok: success,
284
+ beaconAuth: beaconAuth
285
+ });
267
286
  if (success) return;
268
287
  }
269
- console.warn('[Tracker SDK] No available transport method.');
288
+ log("No available transport method.");
289
+ }
290
+ function send(url, data) {
291
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
292
+ var legacyUseBeacon = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
293
+ if (!url) {
294
+ console.warn("[Tracker SDK] Send called without URL");
295
+ return;
296
+ }
297
+ var normalized = normalizeOptions(options, legacyUseBeacon);
298
+ var _normalized$batch = normalized.batch,
299
+ batch = _normalized$batch === void 0 ? true : _normalized$batch;
300
+ if (Array.isArray(data)) {
301
+ if (batch) {
302
+ sendOne(url, {
303
+ events: data
304
+ }, normalized);
305
+ } else {
306
+ data.forEach(function (item) {
307
+ return sendOne(url, item, _objectSpread2(_objectSpread2({}, normalized), {}, {
308
+ batch: true
309
+ }));
310
+ });
311
+ }
312
+ return;
313
+ }
314
+ sendOne(url, data, normalized);
270
315
  }
271
316
 
272
317
  function uuid() {
@@ -278,30 +323,45 @@ function uuid() {
278
323
  }
279
324
 
280
325
  /**
281
- * 简单的本地存储封装
326
+ * 简单的本地存储封装。
327
+ * 存储不可用(隐私模式、iframe 限制)时静默回退,不影响业务。
282
328
  */
283
- var storage = {
284
- get: function get(key) {
285
- try {
286
- var val = localStorage.getItem(key);
287
- if (!val) return null;
288
- return JSON.parse(val);
289
- } catch (e) {
290
- console.warn("[Tracker SDK] Error parsing storage key \"".concat(key, "\":"), e);
291
- return null;
292
- }
293
- },
294
- set: function set(key, value) {
295
- try {
296
- localStorage.setItem(key, JSON.stringify(value));
297
- } catch (e) {
298
- console.warn("[Tracker SDK] Error saving to storage key \"".concat(key, "\":"), e);
329
+ function createStore(getStorage) {
330
+ return {
331
+ get: function get(key) {
332
+ try {
333
+ var store = getStorage();
334
+ if (!store) return null;
335
+ var val = store.getItem(key);
336
+ if (!val) return null;
337
+ return JSON.parse(val);
338
+ } catch (e) {
339
+ return null;
340
+ }
341
+ },
342
+ set: function set(key, value) {
343
+ try {
344
+ var store = getStorage();
345
+ if (!store) return;
346
+ store.setItem(key, JSON.stringify(value));
347
+ } catch (e) {
348
+ // ignore
349
+ }
350
+ },
351
+ remove: function remove(key) {
352
+ try {
353
+ var store = getStorage();
354
+ if (store) store.removeItem(key);
355
+ } catch (e) {
356
+ // ignore
357
+ }
299
358
  }
300
- },
301
- remove: function remove(key) {
302
- localStorage.removeItem(key);
303
- }
304
- };
359
+ };
360
+ }
361
+ var storage = createStore(function () {
362
+ if (typeof localStorage === "undefined") return null;
363
+ return localStorage;
364
+ });
305
365
 
306
366
  /**
307
367
  * 获取当前时间戳(毫秒)
@@ -329,30 +389,42 @@ function formatTime() {
329
389
 
330
390
  // src/core/session.js
331
391
 
332
-
333
- var SESSION_KEY = 'TRACKER_SESSION_ID';
334
- var SESSION_TIME_KEY = 'TRACKER_SESSION_TIME';
392
+ var SESSION_KEY = "TRACKER_SESSION_ID";
393
+ var SESSION_TIME_KEY = "TRACKER_SESSION_TIME";
394
+ var DEVICE_KEY = "TRACKER_DEVICE_ID";
335
395
 
336
396
  // 默认 30 分钟过期
337
397
  var SESSION_EXPIRE = 30 * 60 * 1000;
398
+ function readOrCreate(store, key, timeKey, expireMs) {
399
+ var id = store.get(key);
400
+ var lastTime = Number(store.get(timeKey) || 0);
401
+ if (!id || now() - lastTime > expireMs) {
402
+ var next = uuid();
403
+ store.set(key, next);
404
+ store.set(timeKey, now());
405
+ return next;
406
+ }
407
+ return id;
408
+ }
338
409
 
339
410
  /**
340
- * 获取或创建 session_id。
341
- * 如果 session 不存在或已过期,则生成新的 session_id。
342
- * @returns {string} 当前的 session_id
411
+ * 获取或创建会话 ID(localStorage,跨 tab 共享)。
412
+ * @param {number} [expireMs] - 过期时间,默认 30 分钟
343
413
  */
344
414
  function getSessionId() {
345
- var sid = storage.get(SESSION_KEY);
346
- var lastTime = Number(storage.get(SESSION_TIME_KEY) || 0); // 确保是数字
347
-
348
- // 如果不存在 或 已过期
349
- if (!sid || now() - lastTime > SESSION_EXPIRE) {
350
- var newSid = uuid();
351
- storage.set(SESSION_KEY, newSid);
352
- storage.set(SESSION_TIME_KEY, now());
353
- return newSid;
354
- }
355
- return sid;
415
+ var expireMs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : SESSION_EXPIRE;
416
+ return readOrCreate(storage, SESSION_KEY, SESSION_TIME_KEY, expireMs);
417
+ }
418
+
419
+ /**
420
+ * 获取稳定的设备 ID(localStorage 持久化)。
421
+ */
422
+ function getDeviceId() {
423
+ var saved = storage.get(DEVICE_KEY);
424
+ if (saved) return saved;
425
+ var id = uuid();
426
+ storage.set(DEVICE_KEY, id);
427
+ return id;
356
428
  }
357
429
 
358
430
  /**
@@ -408,7 +480,39 @@ function throttle(fn, delay) {
408
480
  };
409
481
  }
410
482
 
411
- var _excluded = ["system", "module", "sub_module"],
483
+ /**
484
+ * 统一日志开关。
485
+ * 生产环境(debug=false)不打印任何事件数据或初始化参数,避免 token/业务属性进控制台。
486
+ */
487
+ function createLogger() {
488
+ var debug = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
489
+ var enabled = debug === true;
490
+ return {
491
+ log: function log() {
492
+ var _console;
493
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
494
+ args[_key] = arguments[_key];
495
+ }
496
+ if (enabled) (_console = console).log.apply(_console, ["[Tracker SDK]"].concat(args));
497
+ },
498
+ warn: function warn() {
499
+ var _console2;
500
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
501
+ args[_key2] = arguments[_key2];
502
+ }
503
+ if (enabled) (_console2 = console).warn.apply(_console2, ["[Tracker SDK]"].concat(args));
504
+ },
505
+ error: function error() {
506
+ var _console3;
507
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
508
+ args[_key3] = arguments[_key3];
509
+ }
510
+ (_console3 = console).error.apply(_console3, ["[Tracker SDK]"].concat(args));
511
+ }
512
+ };
513
+ }
514
+
515
+ var _excluded = ["system", "module", "sub_module", "duration", "event_id", "schema_version", "occurred_at"],
412
516
  _excluded2 = ["enterTime"];
413
517
 
414
518
  /**
@@ -418,10 +522,19 @@ var Tracker = /*#__PURE__*/function () {
418
522
  /**
419
523
  * @param {Object} options - 初始化配置项
420
524
  * @param {string} options.endPoint - 数据上报接口地址
525
+ * @param {string} [options.appId] - 应用标识
421
526
  * @param {number} [options.delay=1000] - 批量上报延迟
422
527
  * @param {number} [options.maxBatchSize=10] - 批量上报最大条数
423
528
  * @param {string} [options.token] - 数据上报接口的 Token
424
529
  * @param {number} [options.sessionTimeout=1800000] - Session 超时时间(毫秒),默认30分钟
530
+ * @param {boolean} [options.debug=false] - 是否输出 SDK 调试日志
531
+ * @param {Object} [options.headers] - 额外请求头
532
+ * @param {boolean} [options.batch=false] - 是否把同批事件合并成 { events: [...] }
533
+ * @param {"none"|"query"} [options.beaconAuth="none"] - beacon 是否把 token 拼到 URL
534
+ * @param {number} [options.maxKeepaliveBytes=61440] - 超过该字节数时不使用 keepalive
535
+ * @param {"emit"|"silent"|"ignore"} [options.visibilityBehavior="emit"] - 页面恢复可见时的行为
536
+ * @param {boolean} [options.enableActivityTimeout=true] - 是否启用不活跃自动 leave
537
+ * @param {Function} [options.beforeSend] - 发送前最后一道过滤;返回 false 丢弃事件
425
538
  */
426
539
  function Tracker() {
427
540
  var _this = this;
@@ -433,50 +546,59 @@ var Tracker = /*#__PURE__*/function () {
433
546
  this.options = _objectSpread2({
434
547
  delay: 1000,
435
548
  maxBatchSize: 10,
436
- sessionTimeout: 30 * 60 * 1000
549
+ sessionTimeout: 30 * 60 * 1000,
550
+ appId: "",
551
+ debug: false,
552
+ headers: {},
553
+ batch: false,
554
+ beaconAuth: "none",
555
+ maxKeepaliveBytes: 60 * 1024,
556
+ credentials: "same-origin",
557
+ visibilityBehavior: "emit",
558
+ enableActivityTimeout: true,
559
+ persistDeviceId: true,
560
+ beforeSend: null
437
561
  }, options);
438
- this.deviceId = uuid();
439
- this.sessionId = getSessionId();
562
+ this.log = createLogger(this.options.debug);
563
+ this.deviceId = this.options.deviceId || (this.options.persistDeviceId !== false ? getDeviceId() : uuid());
564
+ this.sessionId = getSessionId(this.options.sessionTimeout);
440
565
  this.userId = null;
441
566
  this.globalExt = {};
442
567
  this.current = null;
443
568
  this.lastActiveTime = now();
444
-
445
- // 超时检测定时器
446
569
  this.timeoutTimer = null;
447
-
448
- // 标记是否因超时而离开(用于重新激活时判断)
449
570
  this.isTimedOut = false;
571
+ this._isFlushing = false;
572
+ this._cleanupFns = [];
450
573
  this.queue = new Queue(function (data, isFlush) {
451
574
  if (_this.options.endPoint) {
452
- // 如果是 flush 触发的(通常是页面关闭),强制使用 sendBeacon
453
- send(_this.options.endPoint, data, _this.options.token, isFlush);
575
+ send(_this.options.endPoint, data, {
576
+ token: _this.options.token,
577
+ headers: _this.options.headers,
578
+ useBeacon: isFlush,
579
+ debug: _this.options.debug,
580
+ batch: _this.options.batch,
581
+ beaconAuth: _this.options.beaconAuth,
582
+ maxKeepaliveBytes: _this.options.maxKeepaliveBytes,
583
+ credentials: _this.options.credentials
584
+ });
454
585
  }
455
586
  }, {
456
587
  delay: this.options.delay,
457
- maxBatchSize: this.options.maxBatchSize
588
+ maxBatchSize: this.options.maxBatchSize,
589
+ log: this.log.log
458
590
  });
459
591
  this.plugins = [];
460
-
461
- // 自动绑定活跃检测和生命周期监听
462
592
  this._bindActivity();
463
593
  this._bindLifecycle();
464
-
465
- // 启动超时检测
466
594
  this._startTimeoutCheck();
467
595
  }
468
596
 
469
597
  /***********插件**********/
470
- /**
471
- * 使用插件扩展 SDK 功能
472
- * @param {Function} plugin - 插件函数
473
- * @param {Object} [options] - 插件配置项(可选)
474
- */
475
598
  return _createClass(Tracker, [{
476
599
  key: "use",
477
600
  value: function use(plugin, options) {
478
- if (typeof plugin === 'function') {
479
- // 如果提供了 options,传递给插件函数
601
+ if (typeof plugin === "function") {
480
602
  if (options !== undefined) {
481
603
  plugin(this, options);
482
604
  } else {
@@ -484,173 +606,161 @@ var Tracker = /*#__PURE__*/function () {
484
606
  }
485
607
  this.plugins.push(plugin);
486
608
  } else {
487
- console.warn("[Tracker SDK] Plugin must be a function.");
609
+ this.log.warn("Plugin must be a function.");
488
610
  }
489
611
  }
490
612
 
491
613
  /***********用户**********/
492
- /**
493
- * 设置用户 ID
494
- * @param {string|number} userId
495
- */
496
614
  }, {
497
615
  key: "setUser",
498
616
  value: function setUser(userId) {
499
617
  this.userId = userId;
500
618
  }
501
-
502
- /**
503
- * 设置全局扩展参数
504
- * @param {Object} ext
505
- */
506
619
  }, {
507
620
  key: "setExt",
508
621
  value: function setExt(ext) {
509
622
  this.globalExt = _objectSpread2(_objectSpread2({}, this.globalExt), ext);
510
623
  }
511
624
 
625
+ /***********事件信封**********/
626
+ }, {
627
+ key: "_context",
628
+ value: function _context() {
629
+ return {
630
+ device_id: this.deviceId,
631
+ session_id: this.sessionId,
632
+ user_id: this.userId
633
+ };
634
+ }
635
+ }, {
636
+ key: "_buildEvent",
637
+ value: function _buildEvent(eventName) {
638
+ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
639
+ _ref$system = _ref.system,
640
+ system = _ref$system === void 0 ? "" : _ref$system,
641
+ _ref$module = _ref.module,
642
+ module = _ref$module === void 0 ? "" : _ref$module,
643
+ _ref$sub_module = _ref.sub_module,
644
+ sub_module = _ref$sub_module === void 0 ? "" : _ref$sub_module,
645
+ _ref$duration = _ref.duration,
646
+ duration = _ref$duration === void 0 ? 0 : _ref$duration,
647
+ event_id = _ref.event_id,
648
+ schema_version = _ref.schema_version,
649
+ occurred_at = _ref.occurred_at,
650
+ _ref$ext = _ref.ext,
651
+ ext = _ref$ext === void 0 ? {} : _ref$ext;
652
+ return {
653
+ app_id: this.options.appId || "",
654
+ event_id: event_id || uuid(),
655
+ schema_version: schema_version || 1,
656
+ occurred_at: occurred_at || new Date().toISOString(),
657
+ system: system,
658
+ module: module,
659
+ sub_module: sub_module,
660
+ duration: duration,
661
+ event: eventName,
662
+ // 保留旧字段,兼容已有服务端解析
663
+ timestamp: formatTime(now()),
664
+ context: this._context(),
665
+ ext: _objectSpread2(_objectSpread2({}, this.globalExt), ext)
666
+ };
667
+ }
668
+ }, {
669
+ key: "_enqueue",
670
+ value: function _enqueue(event) {
671
+ try {
672
+ if (typeof this.options.beforeSend === "function") {
673
+ var result = this.options.beforeSend(event);
674
+ if (result === false) {
675
+ this.log.log("Event dropped by beforeSend:", event.event);
676
+ return;
677
+ }
678
+ }
679
+ this.queue.push(event);
680
+ } catch (error) {
681
+ this.log.warn("Failed to enqueue event:", error);
682
+ }
683
+ }
684
+
512
685
  /***********行为**********/
513
- /**
514
- * 记录进入模块
515
- * @param {Object} module
516
- */
517
686
  }, {
518
687
  key: "enter",
519
688
  value: function enter(module) {
520
- // 如果当前已经在某个模块中,先触发离开逻辑
521
689
  if (this.current) {
522
690
  this.leave();
523
691
  }
524
692
  this.current = _objectSpread2(_objectSpread2({}, module), {}, {
525
693
  enterTime: now()
526
694
  });
527
-
528
- // 清除超时标记
529
695
  this.isTimedOut = false;
530
-
531
- // 构建 context 对象
532
- var context = {
533
- device_id: this.deviceId,
534
- session_id: this.sessionId,
535
- user_id: this.userId
536
- };
537
-
538
- // 构建 ext 对象(合并全局扩展参数和当前模块的额外信息)
539
- var extData = _objectSpread2(_objectSpread2({}, this.globalExt), this.current.ext);
540
-
541
- // 上报 module_enter 事件
542
- var event = {
543
- system: this.current.system || '',
544
- module: this.current.module || '',
545
- sub_module: this.current.sub_module || '',
696
+ this._enqueue(this._buildEvent("module_enter", {
697
+ system: this.current.system || "",
698
+ module: this.current.module || "",
699
+ sub_module: this.current.sub_module || "",
546
700
  duration: 0,
547
- event: 'module_enter',
548
- timestamp: formatTime(now()),
549
- context: context,
550
- ext: extData
551
- };
552
- this.queue.push(event);
701
+ ext: _objectSpread2({}, this.current.ext)
702
+ }));
553
703
  }
554
704
 
555
705
  /**
556
- * 记录离开模块
557
- * @param {boolean} force - 是否强制使用当前时间作为结束时间(用于页面卸载等场景)
558
- * @param {boolean} isTimeout - 是否因为超时而离开(内部使用)
559
- * @param {string} reason - 离开原因(可选):'timeout' | 'visibility' | 'normal'
706
+ * @param {boolean} force - 是否强制使用当前时间作为结束时间
707
+ * @param {boolean} isTimeout - 是否因超时离开
708
+ * @param {string} reason - normal | visibility | timeout
560
709
  */
561
710
  }, {
562
711
  key: "leave",
563
712
  value: function leave() {
564
713
  var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
565
714
  var isTimeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
566
- var reason = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'normal';
715
+ var reason = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "normal";
567
716
  if (!this.current) {
568
- console.log('[Tracker SDK] Leave called but no current module');
717
+ this.log.log("Leave called but no current module");
569
718
  return;
570
719
  }
571
720
  var endTime = force ? now() : this.lastActiveTime;
572
721
  var duration = Math.max(0, endTime - this.current.enterTime);
573
- console.log('[Tracker SDK] Leaving module:', {
574
- module: this.current.module,
575
- system: this.current.system,
576
- duration: duration,
577
- force: force,
578
- isTimeout: isTimeout,
579
- reason: reason
580
- });
581
-
582
- // 构建 context 对象
583
- var context = {
584
- device_id: this.deviceId,
585
- session_id: this.sessionId,
586
- user_id: this.userId
587
- };
588
-
589
- // 构建 ext 对象(合并全局扩展参数和当前模块的额外信息)
590
- var extData = _objectSpread2(_objectSpread2({}, this.globalExt), this.current.ext);
591
- var event = {
592
- system: this.current.system || '',
593
- module: this.current.module || '',
594
- sub_module: this.current.sub_module || '',
722
+ this._enqueue(this._buildEvent("module_leave", {
723
+ system: this.current.system || "",
724
+ module: this.current.module || "",
725
+ sub_module: this.current.sub_module || "",
595
726
  duration: duration,
596
- event: 'module_leave',
597
- timestamp: formatTime(now()),
598
- context: context,
599
- ext: _objectSpread2(_objectSpread2({}, extData), {}, {
600
- leave_reason: reason // 添加离开原因
727
+ ext: _objectSpread2(_objectSpread2({}, this.current.ext), {}, {
728
+ leave_reason: reason
601
729
  })
602
- };
603
- console.log('[Tracker SDK] Pushing module_leave event to queue:', event);
604
- this.queue.push(event);
605
-
606
- // 如果是因为超时而离开,保留 current 信息以便重新激活时使用
730
+ }));
607
731
  if (isTimeout) {
608
732
  this.isTimedOut = true;
609
- console.log('[Tracker SDK] Module info preserved for re-activation');
610
733
  } else {
611
- // 正常离开,清除 current
612
734
  this.current = null;
613
735
  this.isTimedOut = false;
614
736
  }
615
737
  }
616
-
617
- /**
618
- * 上报自定义事件
619
- * @param {string} eventName
620
- * @param {Object} params - 扩展参数,可包含 system, module, sub_module
621
- */
622
738
  }, {
623
739
  key: "track",
624
740
  value: function track(eventName) {
625
741
  var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
626
- // 从 params 中提取模块信息(如果存在)
627
742
  var _params$system = params.system,
628
- system = _params$system === void 0 ? '' : _params$system,
743
+ system = _params$system === void 0 ? "" : _params$system,
629
744
  _params$module = params.module,
630
- module = _params$module === void 0 ? '' : _params$module,
745
+ module = _params$module === void 0 ? "" : _params$module,
631
746
  _params$sub_module = params.sub_module,
632
- sub_module = _params$sub_module === void 0 ? '' : _params$sub_module,
747
+ sub_module = _params$sub_module === void 0 ? "" : _params$sub_module,
748
+ _params$duration = params.duration,
749
+ duration = _params$duration === void 0 ? 0 : _params$duration,
750
+ event_id = params.event_id,
751
+ schema_version = params.schema_version,
752
+ occurred_at = params.occurred_at,
633
753
  restParams = _objectWithoutProperties(params, _excluded);
634
-
635
- // 构建 context 对象
636
- var context = {
637
- device_id: this.deviceId,
638
- session_id: this.sessionId,
639
- user_id: this.userId
640
- };
641
-
642
- // 构建 ext 对象(合并全局扩展参数和剩余的事件参数)
643
- var extData = _objectSpread2(_objectSpread2({}, this.globalExt), restParams);
644
- this.queue.push({
754
+ this._enqueue(this._buildEvent(eventName, {
645
755
  system: system,
646
756
  module: module,
647
757
  sub_module: sub_module,
648
- duration: 0,
649
- event: eventName,
650
- timestamp: formatTime(now()),
651
- context: context,
652
- ext: extData
653
- });
758
+ duration: duration,
759
+ event_id: event_id,
760
+ schema_version: schema_version,
761
+ occurred_at: occurred_at,
762
+ ext: restParams
763
+ }));
654
764
  }
655
765
 
656
766
  /***********活跃检测**********/
@@ -660,97 +770,68 @@ var Tracker = /*#__PURE__*/function () {
660
770
  var _this2 = this;
661
771
  var update = function update() {
662
772
  var wasInactive = _this2._checkInactive();
773
+ if (_this2.options.enableActivityTimeout && wasInactive && !_this2.isTimedOut && _this2.current) {
774
+ _this2.leave(false, true, "timeout");
775
+ _this2.sessionId = resetSession(_this2.options.sessionTimeout);
776
+ }
663
777
  _this2.lastActiveTime = now();
664
- refreshSession(); // 用户活跃时刷新 Session 有效期
665
-
666
- // 如果之前因为超时而离开了,现在重新激活,需要重新 enter
667
- if (wasInactive && _this2.isTimedOut && _this2.current) {
668
- console.log('[Tracker SDK] User became active again after timeout');
669
-
670
- // 重置超时标记
778
+ refreshSession(_this2.options.sessionTimeout);
779
+ if (_this2.options.enableActivityTimeout && wasInactive && _this2.isTimedOut && _this2.current) {
671
780
  _this2.isTimedOut = false;
672
-
673
- // 重新记录进入时间
674
781
  _this2.current.enterTime = now();
675
-
676
- // 构建 context 对象
677
- var context = {
678
- device_id: _this2.deviceId,
679
- session_id: _this2.sessionId,
680
- user_id: _this2.userId
681
- };
682
-
683
- // 构建 ext 对象
684
- var extData = _objectSpread2(_objectSpread2({}, _this2.globalExt), _this2.current.ext);
685
-
686
- // 上报 module_enter 事件
687
- var event = {
688
- system: _this2.current.system || '',
689
- module: _this2.current.module || '',
690
- sub_module: _this2.current.sub_module || '',
782
+ _this2._enqueue(_this2._buildEvent("module_enter", {
783
+ system: _this2.current.system || "",
784
+ module: _this2.current.module || "",
785
+ sub_module: _this2.current.sub_module || "",
691
786
  duration: 0,
692
- event: 'module_enter',
693
- timestamp: formatTime(now()),
694
- context: context,
695
- ext: extData
696
- };
697
- _this2.queue.push(event);
698
- console.log('[Tracker SDK] Re-entered module after inactivity:', _this2.current.module);
787
+ ext: _objectSpread2({}, _this2.current.ext)
788
+ }));
789
+ _this2.log.log("Re-entered module after inactivity:", _this2.current.module);
699
790
  }
700
791
  };
701
- var events = ['click', 'keydown', 'touchstart'];
792
+ var events = ["click", "keydown", "touchstart"];
702
793
  events.forEach(function (event) {
703
- document.addEventListener(event, update, {
794
+ var handler = update;
795
+ document.addEventListener(event, handler, {
704
796
  passive: true
705
797
  });
798
+ _this2._cleanupFns.push(function () {
799
+ return document.removeEventListener(event, handler);
800
+ });
706
801
  });
707
-
708
- // 对高频事件进行节流
709
- document.addEventListener('mousemove', throttle(update, 5000), {
802
+ var moveHandler = throttle(update, 5000);
803
+ var scrollHandler = throttle(update, 500);
804
+ document.addEventListener("mousemove", moveHandler, {
710
805
  passive: true
711
806
  });
712
- document.addEventListener('scroll', throttle(update, 500), {
807
+ document.addEventListener("scroll", scrollHandler, {
713
808
  passive: true
714
809
  });
810
+ this._cleanupFns.push(function () {
811
+ document.removeEventListener("mousemove", moveHandler);
812
+ document.removeEventListener("scroll", scrollHandler);
813
+ });
715
814
  }
716
-
717
- /**
718
- * 检查用户是否处于非活跃状态(超过超时时间)
719
- * @returns {boolean} 是否是非活跃状态
720
- */
721
815
  }, {
722
816
  key: "_checkInactive",
723
817
  value: function _checkInactive() {
724
- var inactiveTime = now() - this.lastActiveTime;
725
- return inactiveTime >= this.options.sessionTimeout;
818
+ if (!this.options.enableActivityTimeout) return false;
819
+ return now() - this.lastActiveTime >= this.options.sessionTimeout;
726
820
  }
727
-
728
- /**
729
- * 启动超时检测定时器
730
- */
731
821
  }, {
732
822
  key: "_startTimeoutCheck",
733
823
  value: function _startTimeoutCheck() {
734
824
  var _this3 = this;
735
- // 动态计算检测间隔:超时时间的 1/6,但不超过 30 秒,不少于 5 秒
825
+ this._stopTimeoutCheck();
826
+ if (!this.options.enableActivityTimeout) return;
736
827
  var checkInterval = Math.min(Math.max(this.options.sessionTimeout / 6, 5 * 1000), 30 * 1000);
737
- console.log('[Tracker SDK] Timeout check interval:', (checkInterval / 1000).toFixed(1), 's');
738
828
  this.timeoutTimer = setInterval(function () {
739
- // 只要有 current 且未处于超时状态,就检测是否超时
740
829
  if (_this3.current && !_this3.isTimedOut && _this3._checkInactive()) {
741
- console.log('[Tracker SDK] User inactive for too long, triggering auto leave');
742
- _this3.leave(true, true); // 强制上报离开事件,标记为超时
743
-
744
- // 重置 Session,认为会话结束
745
- _this3.sessionId = resetSession();
746
- console.log('[Tracker SDK] Session reset due to inactivity, new sessionId:', _this3.sessionId);
830
+ _this3.leave(false, true, "timeout");
831
+ _this3.sessionId = resetSession(_this3.options.sessionTimeout);
747
832
  }
748
833
  }, checkInterval);
749
834
  }
750
-
751
- /**
752
- * 停止超时检测
753
- */
754
835
  }, {
755
836
  key: "_stopTimeoutCheck",
756
837
  value: function _stopTimeoutCheck() {
@@ -765,59 +846,80 @@ var Tracker = /*#__PURE__*/function () {
765
846
  key: "_bindLifecycle",
766
847
  value: function _bindLifecycle() {
767
848
  var _this4 = this;
768
- // 用于保存页面隐藏前的模块信息
769
849
  var hiddenModule = null;
770
-
771
- // 页面卸载或隐藏时,上报当前模块的停留时间并强制刷新队列
772
850
  var flushData = function flushData() {
773
- console.log('[Tracker SDK] Lifecycle: Page hidden/unloading, flushing data...');
774
- console.log('[Tracker SDK] Current module:', _this4.current);
775
- console.log('[Tracker SDK] Queue length:', _this4.queue.list.length);
776
-
777
- // 停止超时检测
851
+ if (_this4._isFlushing) return;
852
+ _this4._isFlushing = true;
778
853
  _this4._stopTimeoutCheck();
779
-
780
- // 保存当前模块信息,以便页面恢复时重新 enter
781
854
  if (_this4.current) {
782
855
  hiddenModule = _objectSpread2({}, _this4.current);
783
- console.log('[Tracker SDK] Saved module info for restoration:', hiddenModule.module);
784
856
  }
785
- _this4.leave(true, false, 'visibility'); // 标记为可见性变化导致的离开
786
- _this4.queue.flush(true); // 传入 true,标记为页面关闭场景
787
-
788
- console.log('[Tracker SDK] Data flushed successfully');
857
+ _this4.leave(true, false, "visibility");
858
+ _this4.queue.flush(true);
859
+ };
860
+ var onPageHide = function onPageHide() {
861
+ return flushData();
789
862
  };
790
- window.addEventListener('beforeunload', flushData);
791
- document.addEventListener('visibilitychange', function () {
792
- console.log('[Tracker SDK] Visibility changed:', document.visibilityState);
793
- if (document.visibilityState === 'hidden') {
794
- console.log('[Tracker SDK] Page is now hidden, triggering flush...');
863
+ var onBeforeUnload = function onBeforeUnload() {
864
+ return flushData();
865
+ };
866
+ var onVisibilityChange = function onVisibilityChange() {
867
+ if (_this4.options.visibilityBehavior === "ignore") return;
868
+ if (document.visibilityState === "hidden") {
795
869
  flushData();
796
- } else if (document.visibilityState === 'visible') {
797
- console.log('[Tracker SDK] Page is now visible');
798
-
799
- // 重新启动超时检测
800
- _this4._startTimeoutCheck();
801
-
802
- // 如果之前有保存的模块信息,重新 enter
803
- if (hiddenModule) {
804
- console.log('[Tracker SDK] Restoring module:', hiddenModule.module);
805
-
806
- // 清除 enterTime,使用当前时间作为新的进入时间
807
- var _hiddenModule = hiddenModule;
808
- _hiddenModule.enterTime;
809
- var moduleInfo = _objectWithoutProperties(_hiddenModule, _excluded2);
810
- _this4.enter(moduleInfo);
811
-
812
- // 重置 hiddenModule
813
- hiddenModule = null;
814
- console.log('[Tracker SDK] Module restored successfully');
815
- } else {
816
- console.log('[Tracker SDK] No module to restore');
817
- }
870
+ return;
871
+ }
872
+ if (document.visibilityState !== "visible") return;
873
+ _this4._isFlushing = false;
874
+ _this4._startTimeoutCheck();
875
+ if (!hiddenModule) return;
876
+ var _hiddenModule = hiddenModule;
877
+ _hiddenModule.enterTime;
878
+ var moduleInfo = _objectWithoutProperties(_hiddenModule, _excluded2);
879
+ hiddenModule = null;
880
+ if (_this4.options.visibilityBehavior === "emit") {
881
+ _this4.enter(moduleInfo);
882
+ } else if (_this4.options.visibilityBehavior === "silent") {
883
+ // 恢复当前模块,但不再上报一次 module_enter,避免切 tab 造成页面曝光重复计数。
884
+ _this4.current = _objectSpread2(_objectSpread2({}, moduleInfo), {}, {
885
+ enterTime: now()
886
+ });
887
+ _this4.isTimedOut = false;
888
+ _this4.lastActiveTime = now();
818
889
  }
890
+ };
891
+ window.addEventListener("pagehide", onPageHide);
892
+ window.addEventListener("beforeunload", onBeforeUnload);
893
+ document.addEventListener("visibilitychange", onVisibilityChange);
894
+ this._cleanupFns.push(function () {
895
+ window.removeEventListener("pagehide", onPageHide);
896
+ window.removeEventListener("beforeunload", onBeforeUnload);
897
+ document.removeEventListener("visibilitychange", onVisibilityChange);
819
898
  });
820
899
  }
900
+
901
+ /***********公开方法**********/
902
+ }, {
903
+ key: "flush",
904
+ value: function flush() {
905
+ this.queue.flush(false);
906
+ }
907
+ }, {
908
+ key: "destroy",
909
+ value: function destroy() {
910
+ var _this5 = this;
911
+ this._stopTimeoutCheck();
912
+ this._cleanupFns.forEach(function (fn) {
913
+ try {
914
+ fn();
915
+ } catch (error) {
916
+ _this5.log.warn("Cleanup failed:", error);
917
+ }
918
+ });
919
+ this._cleanupFns = [];
920
+ this.flush();
921
+ this.current = null;
922
+ }
821
923
  }]);
822
924
  }();
823
925
 
@@ -1136,31 +1238,97 @@ function autoTrackPlugin(tracker) {
1136
1238
  }, true); // 使用捕获模式,确保能更早捕获事件
1137
1239
  }
1138
1240
 
1241
+ /**
1242
+ * 脱敏错误上报插件。
1243
+ *
1244
+ * 与旧 errorPlugin 的区别:
1245
+ * - 不上报 pageUrl(可能带 token 等查询参数)
1246
+ * - 不上报 stack
1247
+ * - 默认不上报原始 message,只上报错误类型 + 哈希
1248
+ */
1249
+
1250
+ function hash(input) {
1251
+ var value = 0x811c9dc5;
1252
+ var text = String(input || "");
1253
+ for (var i = 0; i < text.length; i += 1) {
1254
+ value ^= text.charCodeAt(i);
1255
+ value = Math.imul(value, 0x01000193);
1256
+ }
1257
+ return (value >>> 0).toString(16);
1258
+ }
1259
+ function safeErrorPlugin(tracker) {
1260
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1261
+ var _options$captureMessa = options.captureMessage,
1262
+ captureMessage = _options$captureMessa === void 0 ? false : _options$captureMessa,
1263
+ _options$maxMessageLe = options.maxMessageLength,
1264
+ maxMessageLength = _options$maxMessageLe === void 0 ? 200 : _options$maxMessageLe;
1265
+ var report = function report(payload) {
1266
+ try {
1267
+ tracker.track("client.error", _objectSpread2({
1268
+ result: "fail"
1269
+ }, payload));
1270
+ } catch (e) {
1271
+ // 埋点失败不影响业务
1272
+ }
1273
+ };
1274
+ window.addEventListener("error", function (event) {
1275
+ var target = event.target;
1276
+ if (target && (target.src || target.href)) {
1277
+ report({
1278
+ error_type: "resource_error",
1279
+ error_name: target.tagName,
1280
+ error_hash: hash(target.src || target.href)
1281
+ });
1282
+ return;
1283
+ }
1284
+ var message = event.message || "";
1285
+ var payload = {
1286
+ error_type: "uncaught_exception",
1287
+ error_name: event.error && event.error.name ? event.error.name : "Error",
1288
+ error_hash: hash("".concat(message, "|").concat(event.filename || "", "|").concat(event.lineno || 0, "|").concat(event.colno || 0))
1289
+ };
1290
+ if (captureMessage && message) {
1291
+ payload.error_message = message.slice(0, maxMessageLength);
1292
+ }
1293
+ report(payload);
1294
+ }, true);
1295
+ window.addEventListener("unhandledrejection", function (event) {
1296
+ var reason = event.reason || {};
1297
+ var message = reason.message || String(reason);
1298
+ var payload = {
1299
+ error_type: "unhandled_rejection",
1300
+ error_name: reason.name || "Error",
1301
+ error_hash: hash(message)
1302
+ };
1303
+ if (captureMessage && message) {
1304
+ payload.error_message = message.slice(0, maxMessageLength);
1305
+ }
1306
+ report(payload);
1307
+ });
1308
+ }
1309
+
1310
+ var TRACKER_VERSION = "1.0.12";
1139
1311
  var instance = null;
1140
1312
 
1141
1313
  /**
1142
1314
  * 初始化 Tracker SDK。
1143
- * 如果 SDK 已经被初始化,将抛出错误。
1144
1315
  * @param {Object} options - 初始化选项
1145
1316
  * @returns {Tracker} Tracker 实例
1146
- * @throws {Error} 如果 SDK 已经被初始化
1147
1317
  */
1148
- function initTracker(options) {
1149
- console.log('[Tracker SDK] Initializing with options:', options);
1318
+ function initTracker() {
1319
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1320
+ var log = createLogger(options.debug);
1150
1321
  if (instance) {
1151
- console.warn("[Tracker SDK] Tracker has already been initialized. Returning existing instance.");
1322
+ log.warn("Tracker already initialized, returning existing instance.");
1152
1323
  return instance;
1153
1324
  }
1154
1325
  instance = new Tracker(options);
1155
- console.log('[Tracker SDK] Initialized successfully, instance:', instance);
1156
1326
  return instance;
1157
1327
  }
1158
1328
 
1159
1329
  /**
1160
1330
  * 获取 Tracker SDK 实例。
1161
- * 如果 SDK 尚未初始化,将抛出错误。
1162
1331
  * @returns {Tracker} Tracker 实例
1163
- * @throws {Error} 如果 SDK 尚未初始化
1164
1332
  */
1165
1333
  function getTracker() {
1166
1334
  if (!instance) {
@@ -1169,4 +1337,17 @@ function getTracker() {
1169
1337
  return instance;
1170
1338
  }
1171
1339
 
1172
- export { autoTrackPlugin as autoTracker, errorPlugin, getTracker, initTracker, performancePlugin, routerPlugin };
1340
+ /** 立即发送当前队列。 */
1341
+ function flushTracker() {
1342
+ if (instance) instance.flush();
1343
+ }
1344
+
1345
+ /** 清理监听与定时器,并发送剩余队列。 */
1346
+ function destroyTracker() {
1347
+ if (instance) {
1348
+ instance.destroy();
1349
+ instance = null;
1350
+ }
1351
+ }
1352
+
1353
+ export { TRACKER_VERSION, autoTrackPlugin as autoTracker, destroyTracker, errorPlugin, flushTracker, getTracker, initTracker, performancePlugin, routerPlugin, safeErrorPlugin };