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