@pluve/logger-sdk 0.0.5 → 0.0.7

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/loggerSDK.js CHANGED
@@ -1,7 +1,5 @@
1
1
  function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
2
  function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
3
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
5
3
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
6
4
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
7
5
  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
@@ -11,17 +9,23 @@ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key i
11
9
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
12
10
  function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
13
11
  import { defaultTransport } from "./transportAdapter";
14
- import { isBrowser, isWeChatMiniProgram, now, getSessionId, getCurrentUrl, getEnvironmentInfo, parseBrowserInfo, generateUUID } from "./utils";
12
+ import { isBrowser, isWeChatMiniProgram, now, getSessionId, getCurrentUrl, collectEnvironmentTags, generateUUID, logDebug } from "./utils";
15
13
  import { QueueManager } from "./queueManager";
16
14
  import { RetryManager } from "./retryManager";
17
15
  export var LoggerSDK = /*#__PURE__*/function () {
18
- function LoggerSDK(options) {
16
+ function LoggerSDK() {
19
17
  _classCallCheck(this, LoggerSDK);
20
18
  _defineProperty(this, "opts", void 0);
19
+ /** 事件序列编号,用于事件去重 */
21
20
  _defineProperty(this, "seq", 0);
21
+ /** 是否已关闭 */
22
22
  _defineProperty(this, "closed", false);
23
- /** 预收集的环境信息 tags */
24
- _defineProperty(this, "envTags", void 0);
23
+ /** 预收集的环境信息 tags(仅用于初始化上报) */
24
+ _defineProperty(this, "envTags", {});
25
+ /** 是否已初始化 */
26
+ _defineProperty(this, "initialized", false);
27
+ /** 初始化时生成并锁定的会话标识 */
28
+ _defineProperty(this, "sessionId", void 0);
25
29
  /** 队列管理器 */
26
30
  _defineProperty(this, "queueManager", void 0);
27
31
  /** 重试管理器 */
@@ -30,108 +34,107 @@ export var LoggerSDK = /*#__PURE__*/function () {
30
34
  _defineProperty(this, "batchTimer", void 0);
31
35
  /** 是否正在上报 */
32
36
  _defineProperty(this, "isSending", false);
33
- this.opts = {
34
- endpoint: options.endpoint,
35
- appId: options.appId || 'unknown',
36
- env: options.env || 'dev',
37
- debug: !!options.debug,
38
- pixelParam: options.pixelParam || 'data',
39
- maxPixelUrlLen: options.maxPixelUrlLen || 1900,
40
- enableGzip: !!options.enableGzip,
41
- // 批量上报配置
42
- enableBatch: options.enableBatch !== false,
43
- // 默认启用
44
- batchSize: options.batchSize || 10,
45
- batchInterval: options.batchInterval || 5000,
46
- maxQueueSize: options.maxQueueSize || 100,
47
- // 持久化存储配置
48
- enableStorage: options.enableStorage !== false,
49
- // 默认启用
50
- storagePrefix: options.storagePrefix || 'logger_sdk',
51
- // 重试配置
52
- enableRetry: options.enableRetry !== false,
53
- // 默认启用
54
- maxRetries: options.maxRetries || 3,
55
- retryDelay: options.retryDelay || 1000,
56
- retryBackoff: options.retryBackoff !== false // 默认启用
57
- };
37
+ // 初始化时生成并锁定会话标识
38
+ this.sessionId = getSessionId();
39
+ }
40
+ _createClass(LoggerSDK, [{
41
+ key: "init",
42
+ value:
43
+ /**
44
+ * 初始化:配置参数、收集环境信息与 UA,并生成 sessionId,完成初始上报
45
+ */
46
+ function init(options) {
47
+ this.opts = {
48
+ endpoint: options.endpoint,
49
+ appId: options.appId || 'unknown',
50
+ env: options.env || 'dev',
51
+ debug: !!options.debug,
52
+ /** 是否启用 gzip 压缩,默认 true */
53
+ enableGzip: options.enableGzip !== false,
54
+ // 默认启用
55
+ /** 最大像素图 URL 长度,默认 1900 */
56
+ maxPixelUrlLen: options.maxPixelUrlLen || 4096,
57
+ // 批量上报配置(默认关闭,需显式开启)
58
+ enableBatch: options.enableBatch === true,
59
+ batchSize: options.batchSize || 10,
60
+ batchInterval: options.batchInterval || 5000,
61
+ maxQueueSize: options.maxQueueSize || 100,
62
+ // 持久化存储配置
63
+ enableStorage: options.enableStorage !== false,
64
+ // 默认启用
65
+ storagePrefix: options.storagePrefix || 'logger_sdk',
66
+ // 重试配置
67
+ enableRetry: options.enableRetry !== false,
68
+ // 默认启用
69
+ maxRetries: options.maxRetries || 3,
70
+ retryDelay: options.retryDelay || 1000,
71
+ retryBackoff: options.retryBackoff !== false // 默认启用
72
+ };
58
73
 
59
- // 初始化时收集环境信息
60
- this.envTags = this.collectEnvironmentTags();
74
+ // 初始化队列管理器
75
+ if (this.opts.enableBatch) {
76
+ this.queueManager = new QueueManager({
77
+ maxSize: this.opts.maxQueueSize,
78
+ enableStorage: this.opts.enableStorage,
79
+ storagePrefix: this.opts.storagePrefix,
80
+ debug: this.opts.debug
81
+ });
82
+ }
61
83
 
62
- // 初始化队列管理器
63
- if (this.opts.enableBatch) {
64
- this.queueManager = new QueueManager({
65
- maxSize: this.opts.maxQueueSize,
66
- enableStorage: this.opts.enableStorage,
67
- storagePrefix: this.opts.storagePrefix,
68
- debug: this.opts.debug
69
- });
70
- }
84
+ // 初始化重试管理器
85
+ if (this.opts.enableRetry) {
86
+ this.retryManager = new RetryManager({
87
+ maxRetries: this.opts.maxRetries,
88
+ baseDelay: this.opts.retryDelay,
89
+ useBackoff: this.opts.retryBackoff,
90
+ debug: this.opts.debug
91
+ });
92
+ }
71
93
 
72
- // 初始化重试管理器
73
- if (this.opts.enableRetry) {
74
- this.retryManager = new RetryManager({
75
- maxRetries: this.opts.maxRetries,
76
- baseDelay: this.opts.retryDelay,
77
- useBackoff: this.opts.retryBackoff,
78
- debug: this.opts.debug
79
- });
80
- }
94
+ // 监听页面卸载事件
95
+ this.attachUnloadHandlers();
81
96
 
82
- // 启动批量上报定时器
83
- if (this.opts.enableBatch) {
84
- this.startBatchTimer();
85
- }
97
+ // 生成并缓存 sessionId(便于 UV 统计),并锁定到实例生命周期
98
+ // TODO 通过后端接口获取 sessionId
99
+ this.sessionId = getSessionId();
86
100
 
87
- // 监听页面卸载事件
88
- this.attachUnloadHandlers();
89
- }
90
- _createClass(LoggerSDK, [{
91
- key: "logDebug",
92
- value: function logDebug() {
93
- var _console;
94
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
95
- args[_key] = arguments[_key];
101
+ // 收集 UA / 环境信息并完成初始上报(便于后端统计 UA 和 UV)
102
+ this.envTags = collectEnvironmentTags(this.opts.debug);
103
+
104
+ // 调用接口初始化
105
+
106
+ // this.track('session_start', 'Session started', undefined, {
107
+ // level: 'info',
108
+ // tags: this.envTags,
109
+ // }).catch((err) => {
110
+ // logDebug(this.opts.debug, 'Failed to report session_start', err);
111
+ // });
112
+
113
+ // 启动批量上报定时器
114
+ if (this.opts.enableBatch) {
115
+ this.startBatchTimer();
96
116
  }
97
- if (this.opts.debug) (_console = console).debug.apply(_console, ['[LoggerSDK]'].concat(args));
117
+ this.initialized = true;
98
118
  }
99
119
 
100
120
  /**
101
- * 收集环境信息并生成 tags(仅在初始化时执行一次)
121
+ * 设置用户信息
102
122
  */
103
123
  }, {
104
- key: "collectEnvironmentTags",
105
- value: function collectEnvironmentTags() {
106
- var envInfo = getEnvironmentInfo();
107
- var tags = {
108
- platform: envInfo.platform
109
- };
110
-
111
- // 浏览器环境
112
- if (envInfo.platform === 'browser' && envInfo.userAgent) {
113
- var browserInfo = parseBrowserInfo(envInfo.userAgent);
114
- tags.browser = browserInfo.browser;
115
- tags.browserVersion = browserInfo.browserVersion;
116
- tags.os = browserInfo.os;
117
- tags.osVersion = browserInfo.osVersion;
118
- tags.screenWidth = envInfo.screenWidth;
119
- tags.screenHeight = envInfo.screenHeight;
120
- tags.language = envInfo.language;
124
+ key: "identify",
125
+ value: function identify(userId) {
126
+ logDebug(this.opts.debug, 'identify', userId);
127
+ if (this.opts) {
128
+ this.opts.userId = userId;
121
129
  }
122
- // 微信小程序环境
123
- else if (envInfo.platform === 'wechat' && envInfo.systemInfo) {
124
- tags.brand = envInfo.systemInfo.brand;
125
- tags.model = envInfo.systemInfo.model;
126
- tags.system = envInfo.systemInfo.system;
127
- tags.wechatVersion = envInfo.systemInfo.version;
128
- tags.SDKVersion = envInfo.systemInfo.SDKVersion;
129
- tags.screenWidth = envInfo.screenWidth;
130
- tags.screenHeight = envInfo.screenHeight;
131
- tags.language = envInfo.language;
130
+ }
131
+ }, {
132
+ key: "setStoreCode",
133
+ value: function setStoreCode(storeCode) {
134
+ logDebug(this.opts.debug, 'setStoreCode', storeCode);
135
+ if (this.opts) {
136
+ this.opts.storeCode = storeCode;
132
137
  }
133
- this.logDebug('Environment tags collected:', tags);
134
- return tags;
135
138
  }
136
139
 
137
140
  /**
@@ -140,93 +143,105 @@ export var LoggerSDK = /*#__PURE__*/function () {
140
143
  }, {
141
144
  key: "track",
142
145
  value: (function () {
143
- var _track = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(eventType, message, traceId, options) {
144
- var logEvent;
146
+ var _track = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
147
+ var _error$stack;
148
+ var message, error, traceId, logLevel, logEvent;
145
149
  return _regeneratorRuntime().wrap(function _callee$(_context) {
146
150
  while (1) switch (_context.prev = _context.next) {
147
151
  case 0:
152
+ message = _ref.message, error = _ref.error, traceId = _ref.traceId, logLevel = _ref.logLevel;
148
153
  if (!this.closed) {
149
- _context.next = 2;
154
+ _context.next = 3;
150
155
  break;
151
156
  }
152
157
  return _context.abrupt("return");
153
- case 2:
158
+ case 3:
159
+ if (this.initialized) {
160
+ _context.next = 6;
161
+ break;
162
+ }
163
+ logDebug(this.opts.debug, 'SDK not initialized, skip track');
164
+ return _context.abrupt("return");
165
+ case 6:
154
166
  this.seq += 1;
155
167
 
156
168
  // 构建标准化日志格式
157
169
  logEvent = {
170
+ /** 日志 ID */
158
171
  logId: "".concat(this.opts.appId).concat(generateUUID()).concat(now()),
159
172
  // UUID
160
- traceId: traceId,
161
- eventType: eventType,
162
- ts: now(),
173
+ /** 应用标识 */
163
174
  appId: this.opts.appId || 'unknown',
164
- env: this.opts.env || 'dev',
165
- level: (options === null || options === void 0 ? void 0 : options.level) || 'info',
166
- message: message,
167
- stack: options === null || options === void 0 ? void 0 : options.stack,
175
+ /** 环境标识 */
176
+ stage: this.opts.env || 'dev',
177
+ /** 日志级别:info/warn/error/fatal */
178
+ level: logLevel || 'info',
179
+ /** 可选:跟踪 ID(跨服务调用链跟踪) */
180
+ traceId: traceId,
181
+ /** 会话标识,同 sessionId */
182
+ frontendId: this.sessionId,
183
+ // 同 sessionId
184
+ /** 发生页面 URL */
168
185
  url: getCurrentUrl(),
169
- userId: options === null || options === void 0 ? void 0 : options.userId,
170
- sessionId: getSessionId(),
171
- // 合并预收集的环境 tags 和用户自定义 tags
172
- tags: _objectSpread(_objectSpread({}, this.envTags), (options === null || options === void 0 ? void 0 : options.tags) || {})
186
+ /** 异常发生位置,结构待定 */
187
+ location: (error === null || error === void 0 || (_error$stack = error.stack) === null || _error$stack === void 0 ? void 0 : _error$stack.split('\n')[2]) || '',
188
+ /** 异常信息 */
189
+ message: message,
190
+ /** 可选:堆栈信息(长字符串) */
191
+ throwable: error === null || error === void 0 ? void 0 : error.stack,
192
+ /** 可选:用户 ID(脱敏) */
193
+ userId: this.opts.userId,
194
+ /** 可选:店铺编码 */
195
+ storeCode: this.opts.storeCode,
196
+ /** 可选的结构化额外信息 */
197
+ tags: this.envTags
173
198
  };
174
- this.logDebug('track', logEvent);
199
+ logDebug(this.opts.debug, 'track', logEvent);
175
200
 
176
201
  // 如果启用批量上报,添加到队列
177
202
  if (!(this.opts.enableBatch && this.queueManager)) {
178
- _context.next = 13;
203
+ _context.next = 17;
179
204
  break;
180
205
  }
181
206
  this.queueManager.enqueue(logEvent);
182
207
  // 如果队列已满,立即上报
183
208
  if (!(this.queueManager.size() >= this.opts.batchSize)) {
184
- _context.next = 11;
209
+ _context.next = 15;
185
210
  break;
186
211
  }
187
- this.logDebug('Queue size reached batch size, flushing immediately');
188
- _context.next = 11;
212
+ logDebug(this.opts.debug, 'Queue size reached batch size, flushing immediately');
213
+ _context.next = 15;
189
214
  return this.flush();
190
- case 11:
191
- _context.next = 21;
215
+ case 15:
216
+ _context.next = 25;
192
217
  break;
193
- case 13:
194
- _context.prev = 13;
195
- _context.next = 16;
218
+ case 17:
219
+ _context.prev = 17;
220
+ _context.next = 20;
196
221
  return this.sendEvent(logEvent);
197
- case 16:
198
- _context.next = 21;
222
+ case 20:
223
+ _context.next = 25;
199
224
  break;
200
- case 18:
201
- _context.prev = 18;
202
- _context.t0 = _context["catch"](13);
203
- this.logDebug('track failed', _context.t0);
225
+ case 22:
226
+ _context.prev = 22;
227
+ _context.t0 = _context["catch"](17);
228
+ logDebug(this.opts.debug, 'track failed', _context.t0);
204
229
  // 静默失败,不影响主流程
205
- case 21:
230
+ case 25:
206
231
  case "end":
207
232
  return _context.stop();
208
233
  }
209
- }, _callee, this, [[13, 18]]);
234
+ }, _callee, this, [[17, 22]]);
210
235
  }));
211
- function track(_x, _x2, _x3, _x4) {
236
+ function track(_x) {
212
237
  return _track.apply(this, arguments);
213
238
  }
214
239
  return track;
215
240
  }()
216
- /**
217
- * 设置用户信息
218
- */
219
- )
220
- }, {
221
- key: "identify",
222
- value: function identify(userId) {
223
- this.logDebug('identify', userId);
224
- // userId 将在 track 时传入
225
- }
226
-
227
241
  /**
228
242
  * 手动刷新队列,立即上报所有待发送日志
229
243
  */
244
+ )
230
245
  }, {
231
246
  key: "flush",
232
247
  value: (function () {
@@ -245,11 +260,11 @@ export var LoggerSDK = /*#__PURE__*/function () {
245
260
  _context2.next = 5;
246
261
  break;
247
262
  }
248
- this.logDebug('Already sending, skip flush');
263
+ logDebug(this.opts.debug, 'Already sending, skip flush');
249
264
  return _context2.abrupt("return");
250
265
  case 5:
251
266
  this.isSending = true;
252
- this.logDebug("Flushing ".concat(this.queueManager.size(), " events"));
267
+ logDebug(this.opts.debug, "Flushing ".concat(this.queueManager.size(), " events"));
253
268
  _context2.prev = 7;
254
269
  // 获取所有待发送的日志(不移除)
255
270
  events = this.queueManager.peek(this.queueManager.size());
@@ -264,13 +279,13 @@ export var LoggerSDK = /*#__PURE__*/function () {
264
279
  case 13:
265
280
  // 发送成功后,从队列中移除
266
281
  this.queueManager.dequeue(events.length);
267
- this.logDebug("Flushed ".concat(events.length, " events successfully"));
282
+ logDebug(this.opts.debug, "Flushed ".concat(events.length, " events successfully"));
268
283
  _context2.next = 20;
269
284
  break;
270
285
  case 17:
271
286
  _context2.prev = 17;
272
287
  _context2.t0 = _context2["catch"](7);
273
- this.logDebug('Flush failed', _context2.t0);
288
+ logDebug(this.opts.debug, 'Flush failed', _context2.t0);
274
289
  // 失败不移除队列,下次继续重试
275
290
  case 20:
276
291
  _context2.prev = 20;
@@ -317,7 +332,10 @@ export var LoggerSDK = /*#__PURE__*/function () {
317
332
  if (this.retryManager) {
318
333
  this.retryManager.clear();
319
334
  }
320
- case 6:
335
+ this.initialized = false;
336
+ this.sessionId = undefined;
337
+ LoggerSDK.instance = undefined;
338
+ case 9:
321
339
  case "end":
322
340
  return _context3.stop();
323
341
  }
@@ -342,7 +360,7 @@ export var LoggerSDK = /*#__PURE__*/function () {
342
360
  while (1) switch (_context5.prev = _context5.next) {
343
361
  case 0:
344
362
  sendFn = /*#__PURE__*/function () {
345
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
363
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
346
364
  return _regeneratorRuntime().wrap(function _callee4$(_context4) {
347
365
  while (1) switch (_context4.prev = _context4.next) {
348
366
  case 0:
@@ -355,7 +373,7 @@ export var LoggerSDK = /*#__PURE__*/function () {
355
373
  }, _callee4);
356
374
  }));
357
375
  return function sendFn() {
358
- return _ref.apply(this, arguments);
376
+ return _ref2.apply(this, arguments);
359
377
  };
360
378
  }(); // 如果启用重试
361
379
  if (!(this.opts.enableRetry && this.retryManager)) {
@@ -376,7 +394,7 @@ export var LoggerSDK = /*#__PURE__*/function () {
376
394
  }
377
395
  }, _callee5, this);
378
396
  }));
379
- function sendEvent(_x5) {
397
+ function sendEvent(_x2) {
380
398
  return _sendEvent.apply(this, arguments);
381
399
  }
382
400
  return sendEvent;
@@ -402,7 +420,7 @@ export var LoggerSDK = /*#__PURE__*/function () {
402
420
  // 生成批次 ID
403
421
  batchId = "batch_".concat(now(), "_").concat(Math.random().toString(36).substring(2, 9));
404
422
  sendFn = /*#__PURE__*/function () {
405
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
423
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
406
424
  return _regeneratorRuntime().wrap(function _callee6$(_context6) {
407
425
  while (1) switch (_context6.prev = _context6.next) {
408
426
  case 0:
@@ -415,7 +433,7 @@ export var LoggerSDK = /*#__PURE__*/function () {
415
433
  }, _callee6);
416
434
  }));
417
435
  return function sendFn() {
418
- return _ref2.apply(this, arguments);
436
+ return _ref3.apply(this, arguments);
419
437
  };
420
438
  }(); // 如果启用重试
421
439
  if (!(this.opts.enableRetry && this.retryManager)) {
@@ -436,7 +454,7 @@ export var LoggerSDK = /*#__PURE__*/function () {
436
454
  }
437
455
  }, _callee7, this);
438
456
  }));
439
- function sendBatch(_x6) {
457
+ function sendBatch(_x3) {
440
458
  return _sendBatch.apply(this, arguments);
441
459
  }
442
460
  return sendBatch;
@@ -452,13 +470,13 @@ export var LoggerSDK = /*#__PURE__*/function () {
452
470
  if (this.batchTimer) return;
453
471
  this.batchTimer = setInterval(function () {
454
472
  if (!_this3.closed && _this3.queueManager && _this3.queueManager.size() > 0) {
455
- _this3.logDebug('Batch timer triggered, flushing queue');
473
+ logDebug(_this3.opts.debug, 'Batch timer triggered, flushing queue');
456
474
  _this3.flush().catch(function (error) {
457
- _this3.logDebug('Batch timer flush failed', error);
475
+ logDebug(_this3.opts.debug, 'Batch timer flush failed', error);
458
476
  });
459
477
  }
460
478
  }, this.opts.batchInterval);
461
- this.logDebug("Batch timer started with interval ".concat(this.opts.batchInterval, "ms"));
479
+ logDebug(this.opts.debug, "Batch timer started with interval ".concat(this.opts.batchInterval, "ms"));
462
480
  }
463
481
 
464
482
  // ========== 自动采集 ===========
@@ -474,7 +492,7 @@ export var LoggerSDK = /*#__PURE__*/function () {
474
492
  if (isWeChatMiniProgram()) {
475
493
  // 微信小程序使用 App 生命周期
476
494
  // 注意:这里需要在 App() 中配置,此处仅做示意
477
- this.logDebug('WeChat MiniProgram environment detected');
495
+ logDebug(this.opts.debug, 'WeChat MiniProgram environment detected');
478
496
  return;
479
497
  }
480
498
 
@@ -490,7 +508,7 @@ export var LoggerSDK = /*#__PURE__*/function () {
490
508
  _this4.flush().catch(function () {
491
509
  // 忽略错误
492
510
  });
493
- console.log('Page hidden, flushed queue');
511
+ logDebug(_this4.opts.debug, 'Page hidden, flushed queue');
494
512
  }
495
513
  } catch (_unused) {
496
514
  //
@@ -501,10 +519,11 @@ export var LoggerSDK = /*#__PURE__*/function () {
501
519
  win.addEventListener && win.addEventListener('pagehide', function () {
502
520
  try {
503
521
  // 页面隐藏时刷新队列(同步)
522
+ logDebug(_this4.opts.debug, 'Page hide, flushed queue');
504
523
  _this4.flush().catch(function () {
505
524
  // 忽略错误
506
525
  });
507
- console.log('Page hide, flushed queue');
526
+ logDebug(_this4.opts.debug, 'Page hide, flushed queue');
508
527
  } catch (_unused2) {
509
528
  //
510
529
  }
@@ -514,18 +533,28 @@ export var LoggerSDK = /*#__PURE__*/function () {
514
533
  win.addEventListener && win.addEventListener('beforeunload', function () {
515
534
  try {
516
535
  // 页面卸载前刷新队列(同步)
536
+ logDebug(_this4.opts.debug, 'Page unload, flushed queue');
517
537
  _this4.flush().catch(function () {
518
538
  // 忽略错误
519
539
  });
520
- console.log('Page unload, flushed queue');
540
+ logDebug(_this4.opts.debug, 'Page unload, flushed queue');
521
541
  } catch (_unused3) {
522
542
  //
523
543
  }
524
544
  });
525
545
  }
546
+ }], [{
547
+ key: "getInstance",
548
+ value: function getInstance() {
549
+ if (!LoggerSDK.instance) {
550
+ LoggerSDK.instance = new LoggerSDK();
551
+ }
552
+ return LoggerSDK.instance;
553
+ }
526
554
  }]);
527
555
  return LoggerSDK;
528
556
  }();
529
557
 
530
558
  // 兼容导出(UMD/ESM)
559
+ _defineProperty(LoggerSDK, "instance", void 0);
531
560
  export default LoggerSDK;
@@ -52,8 +52,4 @@ export declare class QueueManager {
52
52
  * 从持久化存储移除队列
53
53
  */
54
54
  private removeFromStorage;
55
- /**
56
- * 调试日志
57
- */
58
- private logDebug;
59
55
  }