@be-link/cls-logger 1.0.1-beta.2 → 1.0.1-beta.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +356 -32
  2. package/dist/ClsLogger.d.ts +15 -96
  3. package/dist/ClsLogger.d.ts.map +1 -1
  4. package/dist/ClsLoggerCore.d.ts +177 -0
  5. package/dist/ClsLoggerCore.d.ts.map +1 -0
  6. package/dist/behaviorMonitor.d.ts.map +1 -1
  7. package/dist/clsSdkTypes.d.ts +18 -0
  8. package/dist/clsSdkTypes.d.ts.map +1 -0
  9. package/dist/deviceInfo.d.ts.map +1 -1
  10. package/dist/errorMonitor.d.ts.map +1 -1
  11. package/dist/index.esm.js +2246 -1396
  12. package/dist/index.js +2246 -1396
  13. package/dist/index.umd.js +2249 -1399
  14. package/dist/mini/ClsLogger.d.ts +14 -0
  15. package/dist/mini/ClsLogger.d.ts.map +1 -0
  16. package/dist/mini/behaviorMonitor.d.ts +5 -0
  17. package/dist/mini/behaviorMonitor.d.ts.map +1 -0
  18. package/dist/mini/deviceInfo.d.ts +3 -0
  19. package/dist/mini/deviceInfo.d.ts.map +1 -0
  20. package/dist/mini/errorMonitor.d.ts +5 -0
  21. package/dist/mini/errorMonitor.d.ts.map +1 -0
  22. package/dist/mini/performanceMonitor.d.ts +5 -0
  23. package/dist/mini/performanceMonitor.d.ts.map +1 -0
  24. package/dist/mini/requestMonitor.d.ts +9 -0
  25. package/dist/mini/requestMonitor.d.ts.map +1 -0
  26. package/dist/mini.d.ts +6 -0
  27. package/dist/mini.d.ts.map +1 -0
  28. package/dist/mini.esm.js +1945 -0
  29. package/dist/mini.js +1970 -0
  30. package/dist/performanceMonitor.d.ts.map +1 -1
  31. package/dist/requestMonitor.d.ts +1 -5
  32. package/dist/requestMonitor.d.ts.map +1 -1
  33. package/dist/sdkUtils.d.ts +3 -0
  34. package/dist/sdkUtils.d.ts.map +1 -0
  35. package/dist/types.d.ts +99 -14
  36. package/dist/types.d.ts.map +1 -1
  37. package/dist/web/ClsLogger.d.ts +14 -0
  38. package/dist/web/ClsLogger.d.ts.map +1 -0
  39. package/dist/web/behaviorMonitor.d.ts +5 -0
  40. package/dist/web/behaviorMonitor.d.ts.map +1 -0
  41. package/dist/web/deviceInfo.d.ts +3 -0
  42. package/dist/web/deviceInfo.d.ts.map +1 -0
  43. package/dist/web/errorMonitor.d.ts +5 -0
  44. package/dist/web/errorMonitor.d.ts.map +1 -0
  45. package/dist/web/performanceMonitor.d.ts +5 -0
  46. package/dist/web/performanceMonitor.d.ts.map +1 -0
  47. package/dist/web/requestMonitor.d.ts +5 -0
  48. package/dist/web/requestMonitor.d.ts.map +1 -0
  49. package/dist/web.d.ts +6 -0
  50. package/dist/web.d.ts.map +1 -0
  51. package/dist/web.esm.js +2094 -0
  52. package/dist/web.js +2119 -0
  53. package/package.json +36 -2
package/dist/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import { AsyncClient, LogGroup, Log, PutLogsRequest } from 'tencentcloud-cls-sdk-js-web';
1
+ import { onFCP, onLCP, onCLS, onINP, onTTFB } from 'web-vitals';
2
2
 
3
3
  function isPlainObject(value) {
4
4
  return Object.prototype.toString.call(value) === '[object Object]';
@@ -133,163 +133,979 @@ function stringifyLogValue(v) {
133
133
  }
134
134
  }
135
135
 
136
- const DEFAULT_IGNORE$1 = ['cls.tencentcs.com', /\/cls\//i];
137
- function isClsSendingNow() {
136
+ function enterClsSendingGuard() {
138
137
  const g = globalThis;
139
- return (g.__beLinkClsLoggerSendingCount__ ?? 0) > 0;
138
+ const next = (g.__beLinkClsLoggerSendingCount__ ?? 0) + 1;
139
+ g.__beLinkClsLoggerSendingCount__ = next;
140
+ return () => {
141
+ const cur = g.__beLinkClsLoggerSendingCount__ ?? 0;
142
+ g.__beLinkClsLoggerSendingCount__ = cur > 0 ? cur - 1 : 0;
143
+ };
140
144
  }
141
- function shouldIgnoreUrl$1(url, ignoreUrls) {
142
- for (const rule of ignoreUrls) {
143
- if (typeof rule === 'string') {
144
- if (url.includes(rule))
145
- return true;
146
- continue;
145
+ /**
146
+ * CLS Logger 核心基类
147
+ * - 负责所有上报、队列、监控逻辑
148
+ * - 不包含具体的 SDK 加载实现(由子类负责)
149
+ * - 这样可以把 web/mini 的 SDK 依赖彻底解耦到子入口
150
+ */
151
+ class ClsLoggerCore {
152
+ constructor() {
153
+ this.sdk = null;
154
+ this.sdkPromise = null;
155
+ this.sdkOverride = null;
156
+ this.sdkLoaderOverride = null;
157
+ this.client = null;
158
+ this.clientPromise = null;
159
+ this.topicId = '17475bcd-6315-4b20-859c-e7b087fb3683';
160
+ this.endpoint = 'https://ap-shanghai.cls.tencentcs.com';
161
+ this.retryTimes = 3;
162
+ this.source = '127.0.0.1';
163
+ this.enabled = true;
164
+ this.projectId = '';
165
+ this.projectName = '';
166
+ this.appId = '';
167
+ this.appVersion = '';
168
+ this.envType = 'browser';
169
+ this.userGenerateBaseFields = null;
170
+ this.autoGenerateBaseFields = null;
171
+ this.storageKey = 'beLink_logs';
172
+ this.batchSize = 15;
173
+ // 参考文档:内存队列批量发送(500ms 或 20 条触发)
174
+ this.memoryQueue = [];
175
+ this.batchMaxSize = 20;
176
+ this.batchIntervalMs = 500;
177
+ this.batchTimer = null;
178
+ this.batchTimerDueAt = null;
179
+ this.initTs = 0;
180
+ this.startupDelayMs = 0;
181
+ this.useIdleCallback = false;
182
+ this.idleTimeout = 3000;
183
+ this.visibilityCleanup = null;
184
+ // 参考文档:失败缓存 + 重试
185
+ this.failedCacheKey = 'cls_failed_logs';
186
+ this.failedCacheMax = 200;
187
+ this.requestMonitorStarted = false;
188
+ this.errorMonitorStarted = false;
189
+ this.performanceMonitorStarted = false;
190
+ this.behaviorMonitorStarted = false;
191
+ this.behaviorMonitorCleanup = null;
192
+ }
193
+ /**
194
+ * 子类可按需重写(默认检测 wx)
195
+ */
196
+ detectEnvType() {
197
+ const g = globalThis;
198
+ // 微信、支付宝、字节跳动、UniApp 等小程序环境通常都有特定全局变量
199
+ if ((g.wx && typeof g.wx.getSystemInfoSync === 'function') ||
200
+ (g.my && typeof g.my.getSystemInfoSync === 'function') ||
201
+ (g.tt && typeof g.tt.getSystemInfoSync === 'function') ||
202
+ (g.uni && typeof g.uni.getSystemInfoSync === 'function')) {
203
+ return 'miniprogram';
204
+ }
205
+ return 'browser';
206
+ }
207
+ init(options) {
208
+ this.initTs = Date.now();
209
+ const topicId = options?.tencentCloud?.topicID ?? options?.topic_id ?? options?.topicID ?? this.topicId;
210
+ const endpoint = options?.tencentCloud?.endpoint ?? options?.endpoint ?? this.endpoint;
211
+ const retryTimes = options?.tencentCloud?.retry_times ?? options?.retry_times ?? this.retryTimes;
212
+ const source = options?.source ?? this.source;
213
+ if (!topicId) {
214
+ // eslint-disable-next-line no-console
215
+ console.warn('ClsLogger.init 没有传 topicID/topic_id');
216
+ return;
217
+ }
218
+ const nextEnvType = options.envType ?? this.detectEnvType();
219
+ // envType/endpoint/retryTimes 变化时:重置 client(以及可能的 sdk)
220
+ const envChanged = nextEnvType !== this.envType;
221
+ const endpointChanged = endpoint !== this.endpoint;
222
+ const retryChanged = retryTimes !== this.retryTimes;
223
+ if (envChanged || endpointChanged || retryChanged) {
224
+ this.client = null;
225
+ this.clientPromise = null;
147
226
  }
227
+ if (envChanged) {
228
+ this.sdk = null;
229
+ this.sdkPromise = null;
230
+ }
231
+ this.topicId = topicId;
232
+ this.endpoint = endpoint;
233
+ this.retryTimes = retryTimes;
234
+ this.source = source;
235
+ this.userId = options.userId ?? this.userId;
236
+ this.userName = options.userName ?? this.userName;
237
+ this.projectId = options.projectId ?? this.projectId;
238
+ this.projectName = options.projectName ?? this.projectName;
239
+ this.appId = options.appId ?? this.appId;
240
+ this.appVersion = options.appVersion ?? this.appVersion;
241
+ this.envType = nextEnvType;
242
+ this.enabled = options.enabled ?? true;
243
+ // 可选:外部注入 SDK(优先级:sdkLoader > sdk)
244
+ this.sdkLoaderOverride = options.sdkLoader ?? this.sdkLoaderOverride;
245
+ this.sdkOverride = options.sdk ?? this.sdkOverride;
246
+ this.userGenerateBaseFields = options.generateBaseFields ?? this.userGenerateBaseFields;
247
+ this.autoGenerateBaseFields = this.createDeviceInfoBaseFields(options.deviceInfo);
248
+ this.storageKey = options.storageKey ?? this.storageKey;
249
+ this.batchSize = options.batchSize ?? this.batchSize;
250
+ this.batchMaxSize = options.batch?.maxSize ?? this.batchMaxSize;
251
+ this.batchIntervalMs = options.batch?.intervalMs ?? this.batchIntervalMs;
252
+ this.startupDelayMs = options.batch?.startupDelayMs ?? this.startupDelayMs;
253
+ this.useIdleCallback = options.batch?.useIdleCallback ?? this.useIdleCallback;
254
+ this.idleTimeout = options.batch?.idleTimeout ?? this.idleTimeout;
255
+ this.failedCacheKey = options.failedCacheKey ?? this.failedCacheKey;
256
+ this.failedCacheMax = options.failedCacheMax ?? this.failedCacheMax;
257
+ // 预热(避免首条日志触发 import/初始化开销)
258
+ void this.getInstance().catch(() => {
259
+ // ignore
260
+ });
261
+ if (this.enabled) {
262
+ // 启动时尝试发送失败缓存
263
+ this.flushFailed();
264
+ // 添加页面可见性监听(确保页面关闭时数据不丢失)
265
+ this.setupVisibilityListener();
266
+ // 初始化后立即启动请求监听
267
+ this.startRequestMonitor(options.requestMonitor);
268
+ // 初始化后立即启动错误监控/性能监控
269
+ this.startErrorMonitor(options.errorMonitor);
270
+ this.startPerformanceMonitor(options.performanceMonitor);
271
+ // 初始化后立即启动行为埋点(PV/UV/点击)
272
+ this.startBehaviorMonitor(options.behaviorMonitor);
273
+ }
274
+ }
275
+ getBaseFields() {
276
+ let auto = undefined;
277
+ let user = undefined;
148
278
  try {
149
- if (rule.test(url))
150
- return true;
279
+ const autoRaw = this.autoGenerateBaseFields ? this.autoGenerateBaseFields() : undefined;
280
+ if (autoRaw && isPlainObject(autoRaw))
281
+ auto = normalizeFlatFields(autoRaw, 'deviceInfo');
151
282
  }
152
283
  catch {
153
- // ignore invalid regex
284
+ auto = undefined;
154
285
  }
155
- }
156
- return false;
157
- }
158
- function sampleHit$2(sampleRate) {
159
- if (sampleRate >= 1)
160
- return true;
161
- if (sampleRate <= 0)
162
- return false;
163
- return Math.random() < sampleRate;
164
- }
165
- function truncate$3(s, maxLen) {
166
- if (!s)
167
- return s;
168
- return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
169
- }
170
- function buildPayload(params) {
171
- const { url, method, query, body, duration, startTime, status, success, error, options } = params;
172
- if (!url)
173
- return null;
174
- if (shouldIgnoreUrl$1(url, options.ignoreUrls))
175
- return null;
176
- if (!sampleHit$2(options.sampleRate))
177
- return null;
178
- const payload = { url };
179
- if (options.includeMethod && method)
180
- payload.method = method;
181
- if (options.includeQuery && query !== undefined)
182
- payload.query = truncate$3(String(query), options.maxParamLength);
183
- if (options.includeBody && body !== undefined)
184
- payload.params = truncate$3(stringifyLogValue(body), options.maxParamLength);
185
- if (typeof startTime === 'number')
186
- payload.startTime = startTime;
187
- if (typeof duration === 'number')
188
- payload.duration = duration;
189
- if (typeof status === 'number')
190
- payload.status = status;
191
- if (typeof success === 'boolean')
192
- payload.success = success ? 1 : 0;
193
- if (error !== undefined)
194
- payload.error = truncate$3(stringifyLogValue(error), options.maxParamLength);
195
- return payload;
196
- }
197
- function getAbsoluteUrlMaybe(url) {
198
- try {
199
- if (typeof window === 'undefined')
200
- return url;
201
- return new URL(url, window.location?.href).toString();
202
- }
203
- catch {
204
- return url;
205
- }
206
- }
207
- function installBrowserFetch(report, options) {
208
- if (typeof window === 'undefined')
209
- return;
210
- const w = window;
211
- if (w.__beLinkClsLoggerFetchInstalled__)
212
- return;
213
- if (typeof w.fetch !== 'function')
214
- return;
215
- w.__beLinkClsLoggerFetchInstalled__ = true;
216
- w.__beLinkClsLoggerRawFetch__ = w.fetch;
217
- w.fetch = async (input, init) => {
218
- // 避免 CLS SDK 上报请求被 requestMonitor 捕获后递归上报(尤其在跨域失败时会“上报失败→再上报”)
219
- if (isClsSendingNow())
220
- return w.__beLinkClsLoggerRawFetch__(input, init);
221
- let url = '';
222
- let method = '';
223
- let body = undefined;
224
- const startTs = Date.now();
225
286
  try {
226
- if (typeof input === 'string')
227
- url = input;
228
- else if (input instanceof URL)
229
- url = input.toString();
230
- else
231
- url = input.url ?? '';
232
- method = (init?.method ?? input?.method ?? 'GET');
233
- body = init?.body;
287
+ const userRaw = this.userGenerateBaseFields ? this.userGenerateBaseFields() : undefined;
288
+ if (userRaw && isPlainObject(userRaw))
289
+ user = normalizeFlatFields({ ...userRaw }, 'generateBaseFields');
234
290
  }
235
291
  catch {
236
- // ignore
292
+ user = undefined;
237
293
  }
238
- const absUrl = getAbsoluteUrlMaybe(url);
239
- const query = (() => {
294
+ if (auto && user)
295
+ return mergeFields(user, auto);
296
+ if (user)
297
+ return user;
298
+ if (auto)
299
+ return auto;
300
+ return undefined;
301
+ }
302
+ /**
303
+ * 设置页面可见性监听
304
+ * - visibilitychange: 页面隐藏时使用 sendBeacon 发送队列
305
+ * - pagehide: 作为移动端 fallback
306
+ */
307
+ setupVisibilityListener() {
308
+ if (typeof document === 'undefined' || typeof window === 'undefined')
309
+ return;
310
+ // 避免重复监听
311
+ if (this.visibilityCleanup)
312
+ return;
313
+ const handleVisibilityChange = () => {
314
+ if (document.visibilityState === 'hidden') {
315
+ this.flushBatchSync();
316
+ }
317
+ };
318
+ const handlePageHide = () => {
319
+ this.flushBatchSync();
320
+ };
321
+ document.addEventListener('visibilitychange', handleVisibilityChange);
322
+ window.addEventListener('pagehide', handlePageHide);
323
+ this.visibilityCleanup = () => {
324
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
325
+ window.removeEventListener('pagehide', handlePageHide);
326
+ };
327
+ }
328
+ /**
329
+ * 同步发送内存队列(使用 sendBeacon)
330
+ * - 用于页面关闭时确保数据发送
331
+ * - sendBeacon 不可用时降级为缓存到 localStorage
332
+ */
333
+ flushBatchSync() {
334
+ if (this.memoryQueue.length === 0)
335
+ return;
336
+ // 清除定时器
337
+ if (this.batchTimer) {
240
338
  try {
241
- const u = new URL(absUrl);
242
- return u.search ? u.search.slice(1) : '';
339
+ if (this.useIdleCallback && typeof cancelIdleCallback !== 'undefined') {
340
+ cancelIdleCallback(this.batchTimer);
341
+ }
342
+ else {
343
+ clearTimeout(this.batchTimer);
344
+ }
243
345
  }
244
346
  catch {
245
- return '';
347
+ // ignore
246
348
  }
247
- })();
248
- try {
249
- const res = await w.__beLinkClsLoggerRawFetch__(input, init);
250
- const duration = Date.now() - startTs;
251
- const status = typeof res?.status === 'number' ? res.status : undefined;
252
- const ok = typeof res?.ok === 'boolean' ? res.ok : status !== undefined ? status >= 200 && status < 400 : true;
253
- const payload = buildPayload({
254
- url: absUrl,
255
- method,
256
- query,
257
- body,
258
- startTime: startTs,
259
- duration,
260
- status,
261
- success: ok,
262
- options,
263
- });
264
- if (payload)
265
- report(options.reportType, payload);
266
- return res;
349
+ this.batchTimer = null;
267
350
  }
268
- catch (err) {
269
- const duration = Date.now() - startTs;
270
- const payload = buildPayload({
271
- url: absUrl,
272
- method,
273
- query,
274
- body,
275
- startTime: startTs,
276
- duration,
277
- success: false,
278
- error: err,
279
- options,
280
- });
281
- if (payload)
282
- report(options.reportType, payload);
283
- throw err;
351
+ this.batchTimerDueAt = null;
352
+ const logs = [...this.memoryQueue];
353
+ this.memoryQueue = [];
354
+ // 优先使用 sendBeacon(页面关闭时可靠发送)
355
+ if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
356
+ try {
357
+ const payload = this.buildSendBeaconPayload(logs);
358
+ const blob = new Blob([payload], { type: 'application/json' });
359
+ const url = `${this.endpoint}/structuredlog?topic_id=${this.topicId}`;
360
+ const success = navigator.sendBeacon(url, blob);
361
+ if (!success) {
362
+ // sendBeacon 返回 false 时,降级缓存
363
+ this.cacheFailedReportLogs(logs);
364
+ }
365
+ }
366
+ catch {
367
+ this.cacheFailedReportLogs(logs);
368
+ }
284
369
  }
285
- };
286
- }
287
- function installBrowserXhr(report, options) {
288
- if (typeof window === 'undefined')
289
- return;
290
- const w = window;
291
- if (w.__beLinkClsLoggerXhrInstalled__)
292
- return;
370
+ else {
371
+ // 不支持 sendBeacon,降级缓存到 localStorage
372
+ this.cacheFailedReportLogs(logs);
373
+ }
374
+ }
375
+ /**
376
+ * 构建 sendBeacon 的 payload
377
+ */
378
+ buildSendBeaconPayload(logs) {
379
+ const logList = logs.map((log) => this.buildReportFields(log));
380
+ return JSON.stringify({
381
+ source: this.source,
382
+ logs: logList,
383
+ });
384
+ }
385
+ startRequestMonitor(requestMonitor) {
386
+ if (this.requestMonitorStarted)
387
+ return;
388
+ // 默认开启;传 false 则关闭
389
+ const enabled = requestMonitor === undefined ? true : !!requestMonitor;
390
+ if (!enabled)
391
+ return;
392
+ const opts = typeof requestMonitor === 'object' && requestMonitor ? requestMonitor : {};
393
+ this.requestMonitorStarted = true;
394
+ this.installRequestMonitor((type, data) => {
395
+ this.track(type, data);
396
+ }, {
397
+ ...opts,
398
+ enabled: opts.enabled ?? true,
399
+ clsEndpoint: this.endpoint,
400
+ });
401
+ }
402
+ startErrorMonitor(errorMonitor) {
403
+ if (this.errorMonitorStarted)
404
+ return;
405
+ const enabled = errorMonitor === undefined ? true : !!errorMonitor;
406
+ if (!enabled)
407
+ return;
408
+ this.errorMonitorStarted = true;
409
+ this.installErrorMonitor((type, data) => this.track(type, data), errorMonitor ?? true);
410
+ }
411
+ startPerformanceMonitor(performanceMonitor) {
412
+ if (this.performanceMonitorStarted)
413
+ return;
414
+ const enabled = performanceMonitor === undefined ? true : !!performanceMonitor;
415
+ if (!enabled)
416
+ return;
417
+ this.performanceMonitorStarted = true;
418
+ this.installPerformanceMonitor((type, data) => this.track(type, data), performanceMonitor ?? true);
419
+ }
420
+ startBehaviorMonitor(behaviorMonitor) {
421
+ if (this.behaviorMonitorStarted)
422
+ return;
423
+ const enabled = behaviorMonitor === undefined ? true : !!behaviorMonitor;
424
+ if (!enabled)
425
+ return;
426
+ this.behaviorMonitorStarted = true;
427
+ this.behaviorMonitorCleanup = this.installBehaviorMonitor((type, data) => {
428
+ this.track(type, data);
429
+ }, behaviorMonitor ?? true);
430
+ }
431
+ /**
432
+ * 停止行为埋点监听(PV/UV/点击)
433
+ * - 如需重启:可再次调用 init(或自行调用 init 后的默认启动逻辑)
434
+ */
435
+ stopBehaviorMonitor() {
436
+ try {
437
+ this.behaviorMonitorCleanup?.();
438
+ }
439
+ catch {
440
+ // ignore
441
+ }
442
+ this.behaviorMonitorCleanup = null;
443
+ this.behaviorMonitorStarted = false;
444
+ }
445
+ /**
446
+ * 获取 CLS client(按环境懒加载 SDK)
447
+ */
448
+ async getInstance() {
449
+ if (this.client)
450
+ return this.client;
451
+ if (this.clientPromise)
452
+ return this.clientPromise;
453
+ this.clientPromise = this.loadSdk()
454
+ .then(({ AsyncClient }) => {
455
+ const client = new AsyncClient({
456
+ endpoint: this.endpoint,
457
+ retry_times: this.retryTimes,
458
+ });
459
+ this.client = client;
460
+ return client;
461
+ })
462
+ .catch((err) => {
463
+ // 失败后允许下次重试
464
+ this.clientPromise = null;
465
+ throw err;
466
+ });
467
+ return this.clientPromise;
468
+ }
469
+ /**
470
+ * 直接上报:埋点入参必须是一维(扁平)Object
471
+ * - 非原始值(对象/数组等)会被自动 stringify 成 string
472
+ * - 最终会把 fields 展开成 CLS 的 content(key/value 都会转成 string)
473
+ */
474
+ put(fields, options = {}) {
475
+ if (!this.enabled)
476
+ return;
477
+ if (!fields)
478
+ return;
479
+ if (!this.topicId) {
480
+ // eslint-disable-next-line no-console
481
+ console.warn('ClsLogger.put:未初始化 topic_id');
482
+ return;
483
+ }
484
+ const mergeBaseFields = options.mergeBaseFields ?? true;
485
+ const base = mergeBaseFields ? this.getBaseFields() : undefined;
486
+ const normalizedFields = normalizeFlatFields(fields, 'put');
487
+ const finalFields = mergeFields(base, {
488
+ projectId: this.projectId || undefined,
489
+ projectName: this.projectName || undefined,
490
+ envType: this.envType,
491
+ appId: this.appId || undefined,
492
+ appVersion: this.appVersion || undefined,
493
+ ...normalizedFields,
494
+ });
495
+ // 同步 API:内部异步发送,避免把网络异常冒泡到业务(尤其小程序)
496
+ void this.putAsync(finalFields).catch(() => {
497
+ // ignore
498
+ });
499
+ }
500
+ async putAsync(finalFields) {
501
+ if (!this.topicId)
502
+ return;
503
+ const sdk = await this.loadSdk();
504
+ const client = await this.getInstance();
505
+ const logGroup = new sdk.LogGroup('127.0.0.1');
506
+ logGroup.setSource(this.source);
507
+ const log = new sdk.Log(Date.now());
508
+ for (const key of Object.keys(finalFields)) {
509
+ log.addContent(key, stringifyLogValue(finalFields[key]));
510
+ }
511
+ logGroup.addLog(log);
512
+ const request = new sdk.PutLogsRequest(this.topicId, logGroup);
513
+ const exit = enterClsSendingGuard();
514
+ let p;
515
+ try {
516
+ p = client.PutLogs(request);
517
+ }
518
+ finally {
519
+ exit();
520
+ }
521
+ await p;
522
+ }
523
+ /**
524
+ * 直接上报:把 data 序列化后放入指定 key(默认 “日志内容”)
525
+ */
526
+ putJson(data, clsLoggerKey = '日志内容', options = {}) {
527
+ // put 的入参要求扁平;这里直接把数据序列化为 string
528
+ this.put({ [clsLoggerKey]: stringifyLogValue(data) }, options);
529
+ }
530
+ /**
531
+ * 入队:写入 localStorage 队列;达到 batchSize 自动 flush
532
+ * - 埋点入参必须是一维(扁平)Object,非原始值会被 stringify
533
+ */
534
+ enqueue(fields, options = {}) {
535
+ if (!this.enabled)
536
+ return;
537
+ if (!fields)
538
+ return;
539
+ const time = Date.now();
540
+ const mergeBaseFields = options.mergeBaseFields ?? true;
541
+ const base = mergeBaseFields ? this.getBaseFields() : undefined;
542
+ const normalizedFields = normalizeFlatFields(fields, 'enqueue');
543
+ const finalFields = mergeFields(base, {
544
+ projectId: this.projectId || undefined,
545
+ projectName: this.projectName || undefined,
546
+ envType: this.envType,
547
+ appId: this.appId || undefined,
548
+ appVersion: this.appVersion || undefined,
549
+ ...normalizedFields,
550
+ });
551
+ const queue = readQueue(this.storageKey);
552
+ const next = [...queue, { time, data: finalFields }];
553
+ if (next.length < this.batchSize) {
554
+ writeQueue(this.storageKey, next);
555
+ return;
556
+ }
557
+ // 达到阈值:flush + 写入新的队列(避免并发下丢失,按“先 flush 旧的”策略)
558
+ this.putBatch(queue);
559
+ writeQueue(this.storageKey, [{ time, data: finalFields }]);
560
+ }
561
+ /**
562
+ * 从 localStorage 读取队列并批量上报
563
+ */
564
+ flush() {
565
+ const queue = readQueue(this.storageKey);
566
+ if (queue.length === 0)
567
+ return;
568
+ this.putBatch(queue);
569
+ writeQueue(this.storageKey, []);
570
+ }
571
+ /**
572
+ * 批量上报(每条 item.data 展开为 log content)
573
+ */
574
+ putBatch(queue) {
575
+ if (!this.enabled)
576
+ return;
577
+ if (!queue || queue.length === 0)
578
+ return;
579
+ if (!this.topicId) {
580
+ // eslint-disable-next-line no-console
581
+ console.warn('ClsLogger.putBatch:未初始化 topic_id');
582
+ return;
583
+ }
584
+ void this.putBatchAsync(queue).catch(() => {
585
+ // ignore
586
+ });
587
+ }
588
+ async putBatchAsync(queue) {
589
+ if (!this.topicId)
590
+ return;
591
+ const sdk = await this.loadSdk();
592
+ const client = await this.getInstance();
593
+ const logGroup = new sdk.LogGroup('127.0.0.1');
594
+ logGroup.setSource(this.source);
595
+ for (const item of queue) {
596
+ const log = new sdk.Log(item.time);
597
+ const data = item.data ?? {};
598
+ for (const key of Object.keys(data)) {
599
+ log.addContent(key, stringifyLogValue(data[key]));
600
+ }
601
+ logGroup.addLog(log);
602
+ }
603
+ if (logGroup.getLogs().length === 0)
604
+ return;
605
+ const request = new sdk.PutLogsRequest(this.topicId, logGroup);
606
+ const exit = enterClsSendingGuard();
607
+ let p;
608
+ try {
609
+ p = client.PutLogs(request);
610
+ }
611
+ finally {
612
+ exit();
613
+ }
614
+ await p;
615
+ }
616
+ /**
617
+ * 参考《一、概述》:统一上报入口(内存队列 + 批量发送)
618
+ */
619
+ report(log) {
620
+ if (!this.enabled)
621
+ return;
622
+ if (!log?.type)
623
+ return;
624
+ if (!this.topicId) {
625
+ // eslint-disable-next-line no-console
626
+ console.warn('ClsLogger.report:未初始化 topicID/topic_id');
627
+ return;
628
+ }
629
+ this.memoryQueue.push(log);
630
+ if (this.memoryQueue.length >= this.batchMaxSize) {
631
+ void this.flushBatch();
632
+ return;
633
+ }
634
+ const now = Date.now();
635
+ const desiredDueAt = this.getDesiredBatchFlushDueAt(now);
636
+ const desiredDelay = Math.max(0, desiredDueAt - now);
637
+ if (!this.batchTimer) {
638
+ this.batchTimerDueAt = desiredDueAt;
639
+ this.scheduleFlush(desiredDelay);
640
+ return;
641
+ }
642
+ // 启动合并窗口内:如果当前 timer 会"更早"触发,则延后到窗口结束,尽量减少多次发送
643
+ if (this.batchTimerDueAt !== null && this.batchTimerDueAt < desiredDueAt) {
644
+ this.cancelScheduledFlush();
645
+ this.batchTimerDueAt = desiredDueAt;
646
+ this.scheduleFlush(desiredDelay);
647
+ }
648
+ }
649
+ /**
650
+ * 调度批量发送
651
+ * - 支持 requestIdleCallback(浏览器空闲时执行)
652
+ * - 降级为 setTimeout
653
+ */
654
+ scheduleFlush(desiredDelay) {
655
+ if (this.useIdleCallback && typeof requestIdleCallback !== 'undefined') {
656
+ // 使用 requestIdleCallback,设置 timeout 保证最终执行
657
+ const idleId = requestIdleCallback(() => {
658
+ void this.flushBatch();
659
+ }, { timeout: Math.max(desiredDelay, this.idleTimeout) });
660
+ // 存储 idleId 以便清理(类型兼容处理)
661
+ this.batchTimer = idleId;
662
+ }
663
+ else {
664
+ this.batchTimer = setTimeout(() => {
665
+ void this.flushBatch();
666
+ }, desiredDelay);
667
+ }
668
+ }
669
+ /**
670
+ * 取消已调度的批量发送
671
+ */
672
+ cancelScheduledFlush() {
673
+ if (!this.batchTimer)
674
+ return;
675
+ try {
676
+ if (this.useIdleCallback && typeof cancelIdleCallback !== 'undefined') {
677
+ cancelIdleCallback(this.batchTimer);
678
+ }
679
+ else {
680
+ clearTimeout(this.batchTimer);
681
+ }
682
+ }
683
+ catch {
684
+ // ignore
685
+ }
686
+ this.batchTimer = null;
687
+ }
688
+ getDesiredBatchFlushDueAt(nowTs) {
689
+ const start = this.initTs || nowTs;
690
+ const startupDelay = Number.isFinite(this.startupDelayMs) ? Math.max(0, this.startupDelayMs) : 0;
691
+ if (startupDelay > 0) {
692
+ const end = start + startupDelay;
693
+ if (nowTs < end)
694
+ return end;
695
+ }
696
+ return nowTs + this.batchIntervalMs;
697
+ }
698
+ info(message, data = {}, options) {
699
+ let msg = '';
700
+ let extra = {};
701
+ if (message instanceof Error) {
702
+ msg = message.message;
703
+ extra = {
704
+ stack: message.stack,
705
+ name: message.name,
706
+ ...data,
707
+ };
708
+ }
709
+ else {
710
+ msg = String(message);
711
+ extra = data;
712
+ }
713
+ const payload = normalizeFlatFields({ message: msg, ...extra }, 'info');
714
+ const log = { type: 'info', data: payload, timestamp: Date.now() };
715
+ // info 默认走批量队列,支持 immediate 选项立即发送
716
+ if (options?.immediate) {
717
+ void this.sendReportLogs([log]).catch(() => {
718
+ this.cacheFailedReportLogs([log]);
719
+ });
720
+ }
721
+ else {
722
+ this.report(log);
723
+ }
724
+ }
725
+ warn(message, data = {}, options) {
726
+ let msg = '';
727
+ let extra = {};
728
+ if (message instanceof Error) {
729
+ msg = message.message;
730
+ extra = {
731
+ stack: message.stack,
732
+ name: message.name,
733
+ ...data,
734
+ };
735
+ }
736
+ else {
737
+ msg = String(message);
738
+ extra = data;
739
+ }
740
+ const payload = normalizeFlatFields({ message: msg, ...extra }, 'warn');
741
+ const log = { type: 'warn', data: payload, timestamp: Date.now() };
742
+ // warn 默认走批量队列,支持 immediate 选项立即发送
743
+ if (options?.immediate) {
744
+ void this.sendReportLogs([log]).catch(() => {
745
+ this.cacheFailedReportLogs([log]);
746
+ });
747
+ }
748
+ else {
749
+ this.report(log);
750
+ }
751
+ }
752
+ error(message, data = {}, options) {
753
+ let msg = '';
754
+ let extra = {};
755
+ if (message instanceof Error) {
756
+ msg = message.message;
757
+ extra = {
758
+ stack: message.stack,
759
+ name: message.name,
760
+ ...data,
761
+ };
762
+ }
763
+ else {
764
+ msg = String(message);
765
+ extra = data;
766
+ }
767
+ const payload = normalizeFlatFields({ message: msg, ...extra }, 'error');
768
+ const log = { type: 'error', data: payload, timestamp: Date.now() };
769
+ // error 默认即时上报,除非显式指定 immediate: false
770
+ const immediate = options?.immediate ?? true;
771
+ if (immediate) {
772
+ void this.sendReportLogs([log]).catch(() => {
773
+ this.cacheFailedReportLogs([log]);
774
+ });
775
+ }
776
+ else {
777
+ this.report(log);
778
+ }
779
+ }
780
+ track(trackType, data = {}) {
781
+ if (!trackType)
782
+ return;
783
+ this.report({
784
+ type: trackType,
785
+ data: normalizeFlatFields(data, `track:${trackType}`),
786
+ timestamp: Date.now(),
787
+ });
788
+ }
789
+ /**
790
+ * 立即发送内存队列
791
+ */
792
+ async flushBatch() {
793
+ this.cancelScheduledFlush();
794
+ this.batchTimerDueAt = null;
795
+ if (this.memoryQueue.length === 0)
796
+ return;
797
+ const logs = [...this.memoryQueue];
798
+ this.memoryQueue = [];
799
+ try {
800
+ await this.sendReportLogs(logs);
801
+ }
802
+ catch {
803
+ this.retrySendReportLogs(logs, 1);
804
+ }
805
+ }
806
+ buildReportFields(log) {
807
+ const ts = log.timestamp ?? Date.now();
808
+ const base = this.getBaseFields();
809
+ const data = normalizeFlatFields(log.data ?? {}, 'report:data');
810
+ const mergedData = mergeFields(base, data);
811
+ return {
812
+ timestamp: ts,
813
+ type: log.type,
814
+ envType: this.envType,
815
+ projectId: this.projectId || undefined,
816
+ projectName: this.projectName || undefined,
817
+ appId: this.appId || undefined,
818
+ appVersion: this.appVersion || undefined,
819
+ // 保证“一维字段”:业务数据以 JSON 字符串形式落到 CLS
820
+ ...mergedData,
821
+ };
822
+ }
823
+ async sendReportLogs(logs) {
824
+ if (!this.topicId)
825
+ return;
826
+ const sdk = await this.loadSdk();
827
+ const client = await this.getInstance();
828
+ const logGroup = new sdk.LogGroup('127.0.0.1');
829
+ logGroup.setSource(this.source);
830
+ for (const item of logs) {
831
+ const fields = this.buildReportFields(item);
832
+ const log = new sdk.Log(fields.timestamp);
833
+ for (const key of Object.keys(fields)) {
834
+ if (key === 'timestamp')
835
+ continue;
836
+ log.addContent(key, stringifyLogValue(fields[key]));
837
+ }
838
+ logGroup.addLog(log);
839
+ }
840
+ const request = new sdk.PutLogsRequest(this.topicId, logGroup);
841
+ // 只在“发起网络请求”的同步阶段打标记,避免 requestMonitor 监控 CLS 上报请求导致递归
842
+ const exit = enterClsSendingGuard();
843
+ let p;
844
+ try {
845
+ p = client.PutLogs(request);
846
+ }
847
+ finally {
848
+ exit();
849
+ }
850
+ await p;
851
+ }
852
+ retrySendReportLogs(logs, retryCount) {
853
+ if (retryCount > this.retryTimes) {
854
+ this.cacheFailedReportLogs(logs);
855
+ return;
856
+ }
857
+ const delayMs = Math.pow(2, retryCount) * 1000;
858
+ setTimeout(async () => {
859
+ try {
860
+ await this.sendReportLogs(logs);
861
+ }
862
+ catch {
863
+ this.retrySendReportLogs(logs, retryCount + 1);
864
+ }
865
+ }, delayMs);
866
+ }
867
+ cacheFailedReportLogs(logs) {
868
+ const raw = readStringStorage(this.failedCacheKey);
869
+ let current = [];
870
+ try {
871
+ const parsed = raw ? JSON.parse(raw) : [];
872
+ current = Array.isArray(parsed) ? parsed : [];
873
+ }
874
+ catch {
875
+ current = [];
876
+ }
877
+ const next = [...current, ...logs].slice(-this.failedCacheMax);
878
+ writeStringStorage(this.failedCacheKey, JSON.stringify(next));
879
+ }
880
+ flushFailed() {
881
+ if (!this.enabled)
882
+ return;
883
+ const raw = readStringStorage(this.failedCacheKey);
884
+ if (!raw)
885
+ return;
886
+ let logs = [];
887
+ try {
888
+ const parsed = JSON.parse(raw);
889
+ logs = Array.isArray(parsed) ? parsed : [];
890
+ }
891
+ catch {
892
+ logs = [];
893
+ }
894
+ if (logs.length === 0)
895
+ return;
896
+ // 先清空,再尝试发送
897
+ writeStringStorage(this.failedCacheKey, JSON.stringify([]));
898
+ this.memoryQueue.unshift(...logs);
899
+ void this.flushBatch();
900
+ }
901
+ /**
902
+ * 统计/计数类日志:按字段展开上报(若 data 为空默认 1)
903
+ */
904
+ stat(param) {
905
+ if (!param)
906
+ return;
907
+ const payload = normalizeFlatFields({
908
+ pagePath: typeof window !== 'undefined' ? window.location?.pathname : '',
909
+ projectId: this.projectId,
910
+ projectName: this.projectName,
911
+ ...param,
912
+ data: param.data ?? 1,
913
+ }, 'stat');
914
+ this.report({ type: 'stat', data: payload, timestamp: Date.now() });
915
+ }
916
+ }
917
+
918
+ function readGlobal(key) {
919
+ try {
920
+ const g = globalThis;
921
+ return g[key] ?? null;
922
+ }
923
+ catch {
924
+ return null;
925
+ }
926
+ }
927
+ function tryRequire(moduleName) {
928
+ try {
929
+ // 说明:
930
+ // - ESM 构建(exports.import/module)里通常不存在模块作用域的 require
931
+ // - 一些小程序运行时/构建链路会把 require 挂到 globalThis 上
932
+ // 因此这里同时探测“模块作用域 require”与 “globalThis.require”
933
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
934
+ const localReq = (typeof require === 'function' ? require : null);
935
+ const globalReq = readGlobal('require');
936
+ const candidates = [localReq, globalReq].filter((fn) => typeof fn === 'function');
937
+ for (const fn of candidates) {
938
+ try {
939
+ return fn(moduleName);
940
+ }
941
+ catch {
942
+ // continue
943
+ }
944
+ }
945
+ return null;
946
+ }
947
+ catch {
948
+ return null;
949
+ }
950
+ }
951
+
952
+ const DEFAULT_IGNORE$2 = ['cls.tencentcs.com', /\/cls\//i];
953
+ function isClsSendingNow() {
954
+ const g = globalThis;
955
+ return (g.__beLinkClsLoggerSendingCount__ ?? 0) > 0;
956
+ }
957
+ function shouldIgnoreUrl$2(url, ignoreUrls) {
958
+ for (const rule of ignoreUrls) {
959
+ if (typeof rule === 'string') {
960
+ if (url.includes(rule))
961
+ return true;
962
+ continue;
963
+ }
964
+ try {
965
+ if (rule.test(url))
966
+ return true;
967
+ }
968
+ catch {
969
+ // ignore invalid regex
970
+ }
971
+ }
972
+ return false;
973
+ }
974
+ function sampleHit$5(sampleRate) {
975
+ if (sampleRate >= 1)
976
+ return true;
977
+ if (sampleRate <= 0)
978
+ return false;
979
+ return Math.random() < sampleRate;
980
+ }
981
+ function truncate$5(s, maxLen) {
982
+ if (!s)
983
+ return s;
984
+ return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
985
+ }
986
+ function buildPayload$1(params) {
987
+ const { url, method, query, body, duration, startTime, status, success, error, options } = params;
988
+ if (!url)
989
+ return null;
990
+ if (shouldIgnoreUrl$2(url, options.ignoreUrls))
991
+ return null;
992
+ if (!sampleHit$5(options.sampleRate))
993
+ return null;
994
+ const payload = { url };
995
+ if (options.includeMethod && method)
996
+ payload.method = method;
997
+ if (options.includeQuery && query !== undefined)
998
+ payload.query = truncate$5(String(query), options.maxParamLength);
999
+ if (options.includeBody && body !== undefined)
1000
+ payload.params = truncate$5(stringifyLogValue(body), options.maxParamLength);
1001
+ if (typeof startTime === 'number')
1002
+ payload.startTime = startTime;
1003
+ if (typeof duration === 'number')
1004
+ payload.duration = duration;
1005
+ if (typeof status === 'number')
1006
+ payload.status = status;
1007
+ if (typeof success === 'boolean')
1008
+ payload.success = success ? 1 : 0;
1009
+ if (error !== undefined)
1010
+ payload.error = truncate$5(stringifyLogValue(error), options.maxParamLength);
1011
+ return payload;
1012
+ }
1013
+ function getAbsoluteUrlMaybe(url) {
1014
+ try {
1015
+ if (typeof window === 'undefined')
1016
+ return url;
1017
+ return new URL(url, window.location?.href).toString();
1018
+ }
1019
+ catch {
1020
+ return url;
1021
+ }
1022
+ }
1023
+ function installBrowserFetch(report, options) {
1024
+ if (typeof window === 'undefined')
1025
+ return;
1026
+ const w = window;
1027
+ if (w.__beLinkClsLoggerFetchInstalled__)
1028
+ return;
1029
+ if (typeof w.fetch !== 'function')
1030
+ return;
1031
+ w.__beLinkClsLoggerFetchInstalled__ = true;
1032
+ w.__beLinkClsLoggerRawFetch__ = w.fetch;
1033
+ w.fetch = async (input, init) => {
1034
+ // 避免 CLS SDK 上报请求被 requestMonitor 捕获后递归上报(尤其在跨域失败时会“上报失败→再上报”)
1035
+ if (isClsSendingNow())
1036
+ return w.__beLinkClsLoggerRawFetch__(input, init);
1037
+ let url = '';
1038
+ let method = '';
1039
+ let body = undefined;
1040
+ const startTs = Date.now();
1041
+ try {
1042
+ if (typeof input === 'string')
1043
+ url = input;
1044
+ else if (input instanceof URL)
1045
+ url = input.toString();
1046
+ else
1047
+ url = input.url ?? '';
1048
+ method = (init?.method ?? input?.method ?? 'GET');
1049
+ body = init?.body;
1050
+ }
1051
+ catch {
1052
+ // ignore
1053
+ }
1054
+ const absUrl = getAbsoluteUrlMaybe(url);
1055
+ const query = (() => {
1056
+ try {
1057
+ const u = new URL(absUrl);
1058
+ return u.search ? u.search.slice(1) : '';
1059
+ }
1060
+ catch {
1061
+ return '';
1062
+ }
1063
+ })();
1064
+ try {
1065
+ const res = await w.__beLinkClsLoggerRawFetch__(input, init);
1066
+ const duration = Date.now() - startTs;
1067
+ const status = typeof res?.status === 'number' ? res.status : undefined;
1068
+ const ok = typeof res?.ok === 'boolean' ? res.ok : status !== undefined ? status >= 200 && status < 400 : true;
1069
+ const payload = buildPayload$1({
1070
+ url: absUrl,
1071
+ method,
1072
+ query,
1073
+ body,
1074
+ startTime: startTs,
1075
+ duration,
1076
+ status,
1077
+ success: ok,
1078
+ options,
1079
+ });
1080
+ if (payload)
1081
+ report(options.reportType, payload);
1082
+ return res;
1083
+ }
1084
+ catch (err) {
1085
+ const duration = Date.now() - startTs;
1086
+ const payload = buildPayload$1({
1087
+ url: absUrl,
1088
+ method,
1089
+ query,
1090
+ body,
1091
+ startTime: startTs,
1092
+ duration,
1093
+ success: false,
1094
+ error: err,
1095
+ options,
1096
+ });
1097
+ if (payload)
1098
+ report(options.reportType, payload);
1099
+ throw err;
1100
+ }
1101
+ };
1102
+ }
1103
+ function installBrowserXhr(report, options) {
1104
+ if (typeof window === 'undefined')
1105
+ return;
1106
+ const w = window;
1107
+ if (w.__beLinkClsLoggerXhrInstalled__)
1108
+ return;
293
1109
  if (!w.XMLHttpRequest || !w.XMLHttpRequest.prototype)
294
1110
  return;
295
1111
  w.__beLinkClsLoggerXhrInstalled__ = true;
@@ -331,7 +1147,7 @@ function installBrowserXhr(report, options) {
331
1147
  const st = this.__beLinkClsLoggerStartTs__ ?? startTs;
332
1148
  const duration = Date.now() - st;
333
1149
  const status = typeof this.status === 'number' ? this.status : undefined;
334
- const payload = buildPayload({
1150
+ const payload = buildPayload$1({
335
1151
  url,
336
1152
  method,
337
1153
  query,
@@ -373,6 +1189,85 @@ function installBrowserXhr(report, options) {
373
1189
  return rawSend.apply(this, args);
374
1190
  };
375
1191
  }
1192
+ function installWebRequestMonitor(report, opts = {}) {
1193
+ const enabled = opts.enabled ?? true;
1194
+ if (!enabled)
1195
+ return;
1196
+ const ignoreUrls = [...DEFAULT_IGNORE$2, ...(opts.ignoreUrls ?? [])];
1197
+ if (opts.clsEndpoint)
1198
+ ignoreUrls.push(opts.clsEndpoint);
1199
+ const options = {
1200
+ enabled: true,
1201
+ reportType: opts.reportType ?? 'http',
1202
+ sampleRate: opts.sampleRate ?? 1,
1203
+ ignoreUrls,
1204
+ includeMethod: opts.includeMethod ?? true,
1205
+ includeQuery: opts.includeQuery ?? true,
1206
+ includeBody: opts.includeBody ?? true,
1207
+ maxParamLength: opts.maxParamLength ?? 2000,
1208
+ clsEndpoint: opts.clsEndpoint ?? '',
1209
+ };
1210
+ installBrowserFetch(report, options);
1211
+ installBrowserXhr(report, options);
1212
+ }
1213
+
1214
+ const DEFAULT_IGNORE$1 = ['cls.tencentcs.com', /\/cls\//i];
1215
+ function shouldIgnoreUrl$1(url, ignoreUrls) {
1216
+ for (const rule of ignoreUrls) {
1217
+ if (typeof rule === 'string') {
1218
+ if (url.includes(rule))
1219
+ return true;
1220
+ continue;
1221
+ }
1222
+ try {
1223
+ if (rule.test(url))
1224
+ return true;
1225
+ }
1226
+ catch {
1227
+ // ignore invalid regex
1228
+ }
1229
+ }
1230
+ return false;
1231
+ }
1232
+ function sampleHit$4(sampleRate) {
1233
+ if (sampleRate >= 1)
1234
+ return true;
1235
+ if (sampleRate <= 0)
1236
+ return false;
1237
+ return Math.random() < sampleRate;
1238
+ }
1239
+ function truncate$4(s, maxLen) {
1240
+ if (!s)
1241
+ return s;
1242
+ return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
1243
+ }
1244
+ function buildPayload(params) {
1245
+ const { url, method, query, body, duration, startTime, status, success, error, options } = params;
1246
+ if (!url)
1247
+ return null;
1248
+ if (shouldIgnoreUrl$1(url, options.ignoreUrls))
1249
+ return null;
1250
+ if (!sampleHit$4(options.sampleRate))
1251
+ return null;
1252
+ const payload = { url };
1253
+ if (options.includeMethod && method)
1254
+ payload.method = method;
1255
+ if (options.includeQuery && query !== undefined)
1256
+ payload.query = truncate$4(String(query), options.maxParamLength);
1257
+ if (options.includeBody && body !== undefined)
1258
+ payload.params = truncate$4(stringifyLogValue(body), options.maxParamLength);
1259
+ if (typeof startTime === 'number')
1260
+ payload.startTime = startTime;
1261
+ if (typeof duration === 'number')
1262
+ payload.duration = duration;
1263
+ if (typeof status === 'number')
1264
+ payload.status = status;
1265
+ if (typeof success === 'boolean')
1266
+ payload.success = success ? 1 : 0;
1267
+ if (error !== undefined)
1268
+ payload.error = truncate$4(stringifyLogValue(error), options.maxParamLength);
1269
+ return payload;
1270
+ }
376
1271
  function installMiniProgramWxRequest(report, options) {
377
1272
  const wxAny = globalThis.wx;
378
1273
  if (!wxAny || typeof wxAny.request !== 'function')
@@ -508,7 +1403,7 @@ function installMiniProgramWxCloudCallFunction(report, options) {
508
1403
  }
509
1404
  };
510
1405
  }
511
- function installRequestMonitor(report, opts = {}) {
1406
+ function installMiniRequestMonitor(report, opts = {}) {
512
1407
  const enabled = opts.enabled ?? true;
513
1408
  if (!enabled)
514
1409
  return;
@@ -526,49 +1421,127 @@ function installRequestMonitor(report, opts = {}) {
526
1421
  maxParamLength: opts.maxParamLength ?? 2000,
527
1422
  clsEndpoint: opts.clsEndpoint ?? '',
528
1423
  };
1424
+ installMiniProgramWxRequest(report, options);
1425
+ installMiniProgramWxCloudCallFunction(report, options);
1426
+ }
1427
+
1428
+ function installRequestMonitor(report, opts = {}) {
529
1429
  if (isMiniProgramEnv()) {
530
- installMiniProgramWxRequest(report, options);
531
- installMiniProgramWxCloudCallFunction(report, options);
532
- return;
1430
+ return installMiniRequestMonitor(report, opts);
533
1431
  }
534
- installBrowserFetch(report, options);
535
- installBrowserXhr(report, options);
1432
+ return installWebRequestMonitor(report, opts);
536
1433
  }
537
1434
 
538
- const DEFAULT_MAX_TEXT = 4000;
539
- function truncate$2(s, maxLen) {
1435
+ const DEFAULT_MAX_TEXT$1 = 4000;
1436
+ const DEFAULT_DEDUPE_WINDOW_MS$1 = 3000;
1437
+ const DEFAULT_DEDUPE_MAX_KEYS$1 = 200;
1438
+ /** 默认忽略的无意义错误信息 */
1439
+ const DEFAULT_IGNORE_MESSAGES$1 = [
1440
+ 'Script error.',
1441
+ 'Script error',
1442
+ /^ResizeObserver loop/,
1443
+ 'Permission was denied',
1444
+ ];
1445
+ function truncate$3(s, maxLen) {
540
1446
  if (!s)
541
1447
  return s;
542
1448
  return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
543
1449
  }
544
- function sampleHit$1(sampleRate) {
1450
+ function sampleHit$3(sampleRate) {
545
1451
  if (sampleRate >= 1)
546
1452
  return true;
547
1453
  if (sampleRate <= 0)
548
1454
  return false;
549
1455
  return Math.random() < sampleRate;
550
1456
  }
1457
+ /** 检查消息是否应该被忽略 */
1458
+ function shouldIgnoreMessage$1(message, ignorePatterns) {
1459
+ if (!message || ignorePatterns.length === 0)
1460
+ return false;
1461
+ return ignorePatterns.some((pattern) => {
1462
+ if (typeof pattern === 'string') {
1463
+ return message === pattern || message.includes(pattern);
1464
+ }
1465
+ return pattern.test(message);
1466
+ });
1467
+ }
551
1468
  function getPagePath$1() {
552
1469
  try {
553
1470
  if (typeof window === 'undefined')
554
1471
  return '';
555
- return window.location?.pathname ?? '';
1472
+ return window.location?.href ?? '';
556
1473
  }
557
1474
  catch {
558
1475
  return '';
559
1476
  }
560
1477
  }
561
- function normalizeErrorLike(err, maxTextLength) {
1478
+ function normalizeErrorLike$1(err, maxTextLength) {
562
1479
  if (err && typeof err === 'object') {
563
1480
  const anyErr = err;
564
- const message = truncate$2(String(anyErr.message ?? anyErr.toString?.() ?? ''), maxTextLength);
565
- const name = truncate$2(String(anyErr.name ?? ''), 200);
566
- const stack = truncate$2(String(anyErr.stack ?? ''), maxTextLength);
1481
+ let rawMsg = anyErr.message;
1482
+ if (!rawMsg) {
1483
+ const str = anyErr.toString?.();
1484
+ if (!str || str === '[object Object]') {
1485
+ rawMsg = stringifyLogValue(anyErr);
1486
+ }
1487
+ else {
1488
+ rawMsg = str;
1489
+ }
1490
+ }
1491
+ const message = truncate$3(String(rawMsg ?? ''), maxTextLength);
1492
+ const name = truncate$3(String(anyErr.name ?? ''), 200);
1493
+ const stack = truncate$3(String(anyErr.stack ?? ''), maxTextLength);
567
1494
  return { message, name, stack };
568
1495
  }
569
- const message = truncate$2(stringifyLogValue(err), maxTextLength);
1496
+ const message = truncate$3(stringifyLogValue(err), maxTextLength);
570
1497
  return { message, name: '', stack: '' };
571
1498
  }
1499
+ function createDedupeGuard$1(options) {
1500
+ const cache = new Map(); // key -> lastReportAt
1501
+ const maxKeys = Math.max(0, options.dedupeMaxKeys);
1502
+ const windowMs = Math.max(0, options.dedupeWindowMs);
1503
+ function touch(key, now) {
1504
+ if (cache.has(key))
1505
+ cache.delete(key);
1506
+ cache.set(key, now);
1507
+ if (maxKeys > 0) {
1508
+ while (cache.size > maxKeys) {
1509
+ const first = cache.keys().next().value;
1510
+ if (!first)
1511
+ break;
1512
+ cache.delete(first);
1513
+ }
1514
+ }
1515
+ }
1516
+ return (key) => {
1517
+ if (!key)
1518
+ return true;
1519
+ if (windowMs <= 0 || maxKeys === 0)
1520
+ return true;
1521
+ const now = Date.now();
1522
+ const last = cache.get(key);
1523
+ if (typeof last === 'number' && now - last < windowMs)
1524
+ return false;
1525
+ touch(key, now);
1526
+ return true;
1527
+ };
1528
+ }
1529
+ function buildErrorKey$1(type, payload) {
1530
+ const parts = [
1531
+ type,
1532
+ String(payload.source ?? ''),
1533
+ String(payload.pagePath ?? ''),
1534
+ String(payload.message ?? ''),
1535
+ String(payload.errorName ?? ''),
1536
+ String(payload.stack ?? ''),
1537
+ String(payload.filename ?? ''),
1538
+ String(payload.lineno ?? ''),
1539
+ String(payload.colno ?? ''),
1540
+ String(payload.tagName ?? ''),
1541
+ String(payload.resourceUrl ?? ''),
1542
+ ];
1543
+ return parts.join('|');
1544
+ }
572
1545
  function installBrowserErrorMonitor(report, options) {
573
1546
  if (typeof window === 'undefined')
574
1547
  return;
@@ -576,39 +1549,45 @@ function installBrowserErrorMonitor(report, options) {
576
1549
  if (w.__beLinkClsLoggerErrorInstalled__)
577
1550
  return;
578
1551
  w.__beLinkClsLoggerErrorInstalled__ = true;
1552
+ const shouldReport = createDedupeGuard$1(options);
579
1553
  window.addEventListener('error', (event) => {
580
1554
  try {
581
- if (!sampleHit$1(options.sampleRate))
1555
+ if (!sampleHit$3(options.sampleRate))
582
1556
  return;
583
1557
  const payload = {
584
1558
  pagePath: getPagePath$1(),
585
1559
  source: 'window.error',
586
1560
  };
587
- // JS runtime error
588
1561
  if (event && typeof event === 'object' && 'message' in event) {
589
- payload.message = truncate$2(String(event.message ?? ''), options.maxTextLength);
590
- payload.filename = truncate$2(String(event.filename ?? ''), 500);
1562
+ payload.message = truncate$3(String(event.message ?? ''), options.maxTextLength);
1563
+ // 检查是否应该忽略此错误
1564
+ if (shouldIgnoreMessage$1(String(event.message ?? ''), options.ignoreMessages))
1565
+ return;
1566
+ payload.filename = truncate$3(String(event.filename ?? ''), 500);
591
1567
  payload.lineno = typeof event.lineno === 'number' ? event.lineno : undefined;
592
1568
  payload.colno = typeof event.colno === 'number' ? event.colno : undefined;
593
1569
  const err = event.error;
594
1570
  if (err) {
595
- const e = normalizeErrorLike(err, options.maxTextLength);
1571
+ const e = normalizeErrorLike$1(err, options.maxTextLength);
596
1572
  if (e.name)
597
1573
  payload.errorName = e.name;
598
1574
  if (e.stack)
599
1575
  payload.stack = e.stack;
600
1576
  }
1577
+ if (!shouldReport(buildErrorKey$1(options.reportType, payload)))
1578
+ return;
601
1579
  report(options.reportType, payload);
602
1580
  return;
603
1581
  }
604
- // Resource error (img/script/link)
605
1582
  if (options.captureResourceError) {
606
1583
  const target = event?.target || event?.srcElement;
607
1584
  const tagName = target?.tagName ? String(target.tagName) : '';
608
1585
  const url = String(target?.src || target?.href || '');
609
1586
  payload.source = 'resource.error';
610
1587
  payload.tagName = tagName;
611
- payload.resourceUrl = truncate$2(url, 2000);
1588
+ payload.resourceUrl = truncate$3(url, 2000);
1589
+ if (!shouldReport(buildErrorKey$1(options.reportType, payload)))
1590
+ return;
612
1591
  report(options.reportType, payload);
613
1592
  }
614
1593
  }
@@ -618,10 +1597,13 @@ function installBrowserErrorMonitor(report, options) {
618
1597
  }, true);
619
1598
  window.addEventListener('unhandledrejection', (event) => {
620
1599
  try {
621
- if (!sampleHit$1(options.sampleRate))
1600
+ if (!sampleHit$3(options.sampleRate))
622
1601
  return;
623
1602
  const reason = event?.reason;
624
- const e = normalizeErrorLike(reason, options.maxTextLength);
1603
+ const e = normalizeErrorLike$1(reason, options.maxTextLength);
1604
+ // 检查是否应该忽略此错误
1605
+ if (shouldIgnoreMessage$1(e.message, options.ignoreMessages))
1606
+ return;
625
1607
  const payload = {
626
1608
  pagePath: getPagePath$1(),
627
1609
  source: 'unhandledrejection',
@@ -629,6 +1611,8 @@ function installBrowserErrorMonitor(report, options) {
629
1611
  errorName: e.name,
630
1612
  stack: e.stack,
631
1613
  };
1614
+ if (!shouldReport(buildErrorKey$1(options.reportType, payload)))
1615
+ return;
632
1616
  report(options.reportType, payload);
633
1617
  }
634
1618
  catch {
@@ -636,23 +1620,174 @@ function installBrowserErrorMonitor(report, options) {
636
1620
  }
637
1621
  });
638
1622
  }
1623
+ function installWebErrorMonitor(report, opts = {}) {
1624
+ const enabled = opts === undefined ? true : !!opts;
1625
+ if (!enabled)
1626
+ return;
1627
+ const raw = typeof opts === 'object' && opts ? opts : {};
1628
+ const options = {
1629
+ enabled: true,
1630
+ reportType: raw.reportType ?? 'error',
1631
+ sampleRate: raw.sampleRate ?? 1,
1632
+ captureResourceError: raw.captureResourceError ?? true,
1633
+ maxTextLength: raw.maxTextLength ?? DEFAULT_MAX_TEXT$1,
1634
+ dedupeWindowMs: raw.dedupeWindowMs ?? DEFAULT_DEDUPE_WINDOW_MS$1,
1635
+ dedupeMaxKeys: raw.dedupeMaxKeys ?? DEFAULT_DEDUPE_MAX_KEYS$1,
1636
+ ignoreMessages: raw.ignoreMessages ?? DEFAULT_IGNORE_MESSAGES$1,
1637
+ };
1638
+ installBrowserErrorMonitor(report, options);
1639
+ }
1640
+
1641
+ const DEFAULT_MAX_TEXT = 4000;
1642
+ const DEFAULT_DEDUPE_WINDOW_MS = 3000;
1643
+ const DEFAULT_DEDUPE_MAX_KEYS = 200;
1644
+ /** 默认忽略的无意义错误信息 */
1645
+ const DEFAULT_IGNORE_MESSAGES = [
1646
+ 'Script error.',
1647
+ 'Script error',
1648
+ /^ResizeObserver loop/,
1649
+ 'Permission was denied',
1650
+ ];
1651
+ function truncate$2(s, maxLen) {
1652
+ if (!s)
1653
+ return s;
1654
+ return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
1655
+ }
1656
+ function sampleHit$2(sampleRate) {
1657
+ if (sampleRate >= 1)
1658
+ return true;
1659
+ if (sampleRate <= 0)
1660
+ return false;
1661
+ return Math.random() < sampleRate;
1662
+ }
1663
+ /** 检查消息是否应该被忽略 */
1664
+ function shouldIgnoreMessage(message, ignorePatterns) {
1665
+ if (!message || ignorePatterns.length === 0)
1666
+ return false;
1667
+ return ignorePatterns.some((pattern) => {
1668
+ if (typeof pattern === 'string') {
1669
+ return message === pattern || message.includes(pattern);
1670
+ }
1671
+ return pattern.test(message);
1672
+ });
1673
+ }
1674
+ function getMpPagePath() {
1675
+ try {
1676
+ const pages = globalThis.getCurrentPages?.();
1677
+ if (Array.isArray(pages) && pages.length > 0) {
1678
+ const page = pages[pages.length - 1];
1679
+ const route = page.route || page.__route__;
1680
+ if (typeof route === 'string') {
1681
+ let path = route.startsWith('/') ? route : `/${route}`;
1682
+ const options = page.options || {};
1683
+ const keys = Object.keys(options);
1684
+ if (keys.length > 0) {
1685
+ const qs = keys.map((k) => `${k}=${options[k]}`).join('&');
1686
+ path = `${path}?${qs}`;
1687
+ }
1688
+ return path;
1689
+ }
1690
+ }
1691
+ return '';
1692
+ }
1693
+ catch {
1694
+ return '';
1695
+ }
1696
+ }
1697
+ function normalizeErrorLike(err, maxTextLength) {
1698
+ if (err && typeof err === 'object') {
1699
+ const anyErr = err;
1700
+ let rawMsg = anyErr.message;
1701
+ if (!rawMsg) {
1702
+ const str = anyErr.toString?.();
1703
+ if (!str || str === '[object Object]') {
1704
+ rawMsg = stringifyLogValue(anyErr);
1705
+ }
1706
+ else {
1707
+ rawMsg = str;
1708
+ }
1709
+ }
1710
+ const message = truncate$2(String(rawMsg ?? ''), maxTextLength);
1711
+ const name = truncate$2(String(anyErr.name ?? ''), 200);
1712
+ const stack = truncate$2(String(anyErr.stack ?? ''), maxTextLength);
1713
+ return { message, name, stack };
1714
+ }
1715
+ const message = truncate$2(stringifyLogValue(err), maxTextLength);
1716
+ return { message, name: '', stack: '' };
1717
+ }
1718
+ function createDedupeGuard(options) {
1719
+ const cache = new Map(); // key -> lastReportAt
1720
+ const maxKeys = Math.max(0, options.dedupeMaxKeys);
1721
+ const windowMs = Math.max(0, options.dedupeWindowMs);
1722
+ function touch(key, now) {
1723
+ if (cache.has(key))
1724
+ cache.delete(key);
1725
+ cache.set(key, now);
1726
+ if (maxKeys > 0) {
1727
+ while (cache.size > maxKeys) {
1728
+ const first = cache.keys().next().value;
1729
+ if (!first)
1730
+ break;
1731
+ cache.delete(first);
1732
+ }
1733
+ }
1734
+ }
1735
+ return (key) => {
1736
+ if (!key)
1737
+ return true;
1738
+ if (windowMs <= 0 || maxKeys === 0)
1739
+ return true;
1740
+ const now = Date.now();
1741
+ const last = cache.get(key);
1742
+ if (typeof last === 'number' && now - last < windowMs)
1743
+ return false;
1744
+ touch(key, now);
1745
+ return true;
1746
+ };
1747
+ }
1748
+ function buildErrorKey(type, payload) {
1749
+ const parts = [
1750
+ type,
1751
+ String(payload.source ?? ''),
1752
+ String(payload.pagePath ?? ''),
1753
+ String(payload.message ?? ''),
1754
+ String(payload.errorName ?? ''),
1755
+ String(payload.stack ?? ''),
1756
+ String(payload.filename ?? ''),
1757
+ String(payload.lineno ?? ''),
1758
+ String(payload.colno ?? ''),
1759
+ String(payload.tagName ?? ''),
1760
+ String(payload.resourceUrl ?? ''),
1761
+ ];
1762
+ return parts.join('|');
1763
+ }
639
1764
  function installMiniProgramErrorMonitor(report, options) {
640
1765
  const g = globalThis;
641
1766
  if (g.__beLinkClsLoggerMpErrorInstalled__)
642
1767
  return;
643
1768
  g.__beLinkClsLoggerMpErrorInstalled__ = true;
1769
+ const shouldReport = createDedupeGuard(options);
644
1770
  const wxAny = globalThis.wx;
645
- // wx.* 事件(兼容在 App 已经创建后的场景)
646
1771
  try {
647
1772
  if (wxAny && typeof wxAny.onError === 'function') {
648
1773
  wxAny.onError((msg) => {
649
1774
  try {
650
- if (!sampleHit$1(options.sampleRate))
1775
+ if (!sampleHit$2(options.sampleRate))
651
1776
  return;
652
- report(options.reportType, {
1777
+ const e = normalizeErrorLike(msg, options.maxTextLength);
1778
+ // 检查是否应该忽略此错误
1779
+ if (shouldIgnoreMessage(e.message, options.ignoreMessages))
1780
+ return;
1781
+ const payload = {
1782
+ pagePath: getMpPagePath(),
653
1783
  source: 'wx.onError',
654
- message: truncate$2(String(msg ?? ''), options.maxTextLength),
655
- });
1784
+ message: e.message,
1785
+ errorName: e.name,
1786
+ stack: e.stack,
1787
+ };
1788
+ if (!shouldReport(buildErrorKey(options.reportType, payload)))
1789
+ return;
1790
+ report(options.reportType, payload);
656
1791
  }
657
1792
  catch {
658
1793
  // ignore
@@ -667,15 +1802,22 @@ function installMiniProgramErrorMonitor(report, options) {
667
1802
  if (wxAny && typeof wxAny.onUnhandledRejection === 'function') {
668
1803
  wxAny.onUnhandledRejection((res) => {
669
1804
  try {
670
- if (!sampleHit$1(options.sampleRate))
1805
+ if (!sampleHit$2(options.sampleRate))
671
1806
  return;
672
1807
  const e = normalizeErrorLike(res?.reason, options.maxTextLength);
673
- report(options.reportType, {
1808
+ // 检查是否应该忽略此错误
1809
+ if (shouldIgnoreMessage(e.message, options.ignoreMessages))
1810
+ return;
1811
+ const payload = {
1812
+ pagePath: getMpPagePath(),
674
1813
  source: 'wx.onUnhandledRejection',
675
1814
  message: e.message,
676
1815
  errorName: e.name,
677
1816
  stack: e.stack,
678
- });
1817
+ };
1818
+ if (!shouldReport(buildErrorKey(options.reportType, payload)))
1819
+ return;
1820
+ report(options.reportType, payload);
679
1821
  }
680
1822
  catch {
681
1823
  // ignore
@@ -686,7 +1828,6 @@ function installMiniProgramErrorMonitor(report, options) {
686
1828
  catch {
687
1829
  // ignore
688
1830
  }
689
- // 包装 App({...}) 注入 onError/onUnhandledRejection(推荐)
690
1831
  try {
691
1832
  if (typeof g.App === 'function' && !g.__beLinkClsLoggerAppWrapped__) {
692
1833
  g.__beLinkClsLoggerAppWrapped__ = true;
@@ -696,11 +1837,20 @@ function installMiniProgramErrorMonitor(report, options) {
696
1837
  const rawOnError = next.onError;
697
1838
  next.onError = function (...args) {
698
1839
  try {
699
- if (sampleHit$1(options.sampleRate)) {
700
- report(options.reportType, {
701
- source: 'App.onError',
702
- message: truncate$2(String(args?.[0] ?? ''), options.maxTextLength),
703
- });
1840
+ if (sampleHit$2(options.sampleRate)) {
1841
+ const e = normalizeErrorLike(args?.[0], options.maxTextLength);
1842
+ // 检查是否应该忽略此错误
1843
+ if (!shouldIgnoreMessage(e.message, options.ignoreMessages)) {
1844
+ const payload = {
1845
+ pagePath: getMpPagePath(),
1846
+ source: 'App.onError',
1847
+ message: e.message,
1848
+ errorName: e.name,
1849
+ stack: e.stack,
1850
+ };
1851
+ if (shouldReport(buildErrorKey(options.reportType, payload)))
1852
+ report(options.reportType, payload);
1853
+ }
704
1854
  }
705
1855
  }
706
1856
  catch {
@@ -713,15 +1863,21 @@ function installMiniProgramErrorMonitor(report, options) {
713
1863
  const rawOnUnhandled = next.onUnhandledRejection;
714
1864
  next.onUnhandledRejection = function (...args) {
715
1865
  try {
716
- if (sampleHit$1(options.sampleRate)) {
1866
+ if (sampleHit$2(options.sampleRate)) {
717
1867
  const reason = args?.[0]?.reason ?? args?.[0];
718
1868
  const e = normalizeErrorLike(reason, options.maxTextLength);
719
- report(options.reportType, {
720
- source: 'App.onUnhandledRejection',
721
- message: e.message,
722
- errorName: e.name,
723
- stack: e.stack,
724
- });
1869
+ // 检查是否应该忽略此错误
1870
+ if (!shouldIgnoreMessage(e.message, options.ignoreMessages)) {
1871
+ const payload = {
1872
+ pagePath: getMpPagePath(),
1873
+ source: 'App.onUnhandledRejection',
1874
+ message: e.message,
1875
+ errorName: e.name,
1876
+ stack: e.stack,
1877
+ };
1878
+ if (shouldReport(buildErrorKey(options.reportType, payload)))
1879
+ report(options.reportType, payload);
1880
+ }
725
1881
  }
726
1882
  }
727
1883
  catch {
@@ -739,7 +1895,7 @@ function installMiniProgramErrorMonitor(report, options) {
739
1895
  // ignore
740
1896
  }
741
1897
  }
742
- function installErrorMonitor(report, opts = {}) {
1898
+ function installMiniErrorMonitor(report, opts = {}) {
743
1899
  const enabled = opts === undefined ? true : !!opts;
744
1900
  if (!enabled)
745
1901
  return;
@@ -750,12 +1906,18 @@ function installErrorMonitor(report, opts = {}) {
750
1906
  sampleRate: raw.sampleRate ?? 1,
751
1907
  captureResourceError: raw.captureResourceError ?? true,
752
1908
  maxTextLength: raw.maxTextLength ?? DEFAULT_MAX_TEXT,
1909
+ dedupeWindowMs: raw.dedupeWindowMs ?? DEFAULT_DEDUPE_WINDOW_MS,
1910
+ dedupeMaxKeys: raw.dedupeMaxKeys ?? DEFAULT_DEDUPE_MAX_KEYS,
1911
+ ignoreMessages: raw.ignoreMessages ?? DEFAULT_IGNORE_MESSAGES,
753
1912
  };
1913
+ installMiniProgramErrorMonitor(report, options);
1914
+ }
1915
+
1916
+ function installErrorMonitor(report, opts = {}) {
754
1917
  if (isMiniProgramEnv()) {
755
- installMiniProgramErrorMonitor(report, options);
756
- return;
1918
+ return installMiniErrorMonitor(report, opts);
757
1919
  }
758
- installBrowserErrorMonitor(report, options);
1920
+ return installWebErrorMonitor(report, opts);
759
1921
  }
760
1922
 
761
1923
  const DEFAULT_IGNORE = ['cls.tencentcs.com', /\/cls\//i];
@@ -764,7 +1926,7 @@ function truncate$1(s, maxLen) {
764
1926
  return s;
765
1927
  return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
766
1928
  }
767
- function sampleHit(sampleRate) {
1929
+ function sampleHit$1(sampleRate) {
768
1930
  if (sampleRate >= 1)
769
1931
  return true;
770
1932
  if (sampleRate <= 0)
@@ -792,20 +1954,16 @@ function getPagePath() {
792
1954
  try {
793
1955
  if (typeof window === 'undefined')
794
1956
  return '';
795
- return window.location?.pathname ?? '';
1957
+ return window.location?.href ?? '';
796
1958
  }
797
1959
  catch {
798
1960
  return '';
799
1961
  }
800
1962
  }
801
- function reportMetric(report, reportType, metric, value, extra = {}) {
802
- report(reportType, {
803
- pagePath: getPagePath(),
804
- metric,
805
- value,
806
- ...extra,
807
- });
808
- }
1963
+ /**
1964
+ * 安装浏览器性能监控
1965
+ * 使用 Google web-vitals 库实现 Core Web Vitals 指标采集
1966
+ */
809
1967
  function installBrowserPerformanceMonitor(report, options) {
810
1968
  if (typeof window === 'undefined')
811
1969
  return;
@@ -814,159 +1972,130 @@ function installBrowserPerformanceMonitor(report, options) {
814
1972
  return;
815
1973
  w.__beLinkClsLoggerPerfInstalled__ = true;
816
1974
  const ignoreUrls = [...DEFAULT_IGNORE, ...(options.ignoreUrls ?? [])];
817
- // Navigation timing: TTFB
818
- if (options.navigationTiming) {
1975
+ // Web Vitals: 使用 Google web-vitals 库
1976
+ // 这个库会自动处理:
1977
+ // - LCP 在用户交互后停止观察
1978
+ // - firstHiddenTime 过滤(页面隐藏后的数据不计入)
1979
+ // - CLS 5秒会话窗口算法
1980
+ // - BFCache 恢复时自动重置指标
1981
+ if (options.webVitals) {
1982
+ // FCP
819
1983
  try {
820
- const navEntries = performance.getEntriesByType?.('navigation');
821
- const nav = Array.isArray(navEntries) ? navEntries[0] : undefined;
822
- if (nav && typeof nav === 'object') {
823
- const ttfb = typeof nav.responseStart === 'number' && typeof nav.requestStart === 'number'
824
- ? nav.responseStart - nav.requestStart
825
- : -1;
826
- if (ttfb >= 0 && sampleHit(options.sampleRate))
827
- reportMetric(report, options.reportType, 'TTFB', ttfb, { unit: 'ms' });
828
- }
1984
+ onFCP((metric) => {
1985
+ report(options.reportType, {
1986
+ pagePath: getPagePath(),
1987
+ metric: 'FCP',
1988
+ value: metric.value,
1989
+ unit: 'ms',
1990
+ rating: metric.rating,
1991
+ id: metric.id,
1992
+ navigationType: metric.navigationType,
1993
+ });
1994
+ });
829
1995
  }
830
1996
  catch {
831
1997
  // ignore
832
1998
  }
833
- }
834
- // Web Vitals: FCP/LCP/CLS/FID
835
- if (options.webVitals && typeof globalThis.PerformanceObserver === 'function') {
836
- // FCP
1999
+ // LCP(自动处理用户交互后停止)
837
2000
  try {
838
- const po = new PerformanceObserver((list) => {
839
- try {
840
- if (!sampleHit(options.sampleRate))
841
- return;
842
- for (const entry of list.getEntries()) {
843
- if (entry?.name === 'first-contentful-paint' && typeof entry.startTime === 'number') {
844
- reportMetric(report, options.reportType, 'FCP', entry.startTime, { unit: 'ms' });
845
- }
846
- }
847
- }
848
- catch {
849
- // ignore
850
- }
2001
+ onLCP((metric) => {
2002
+ report(options.reportType, {
2003
+ pagePath: getPagePath(),
2004
+ metric: 'LCP',
2005
+ value: metric.value,
2006
+ unit: 'ms',
2007
+ rating: metric.rating,
2008
+ id: metric.id,
2009
+ navigationType: metric.navigationType,
2010
+ });
851
2011
  });
852
- po.observe({ type: 'paint', buffered: true });
853
2012
  }
854
2013
  catch {
855
2014
  // ignore
856
2015
  }
857
- // LCP(最后一次为准)
858
- let lastLcp = null;
2016
+ // CLS(自动处理会话窗口)
859
2017
  try {
860
- const po = new PerformanceObserver((list) => {
861
- try {
862
- const entries = list.getEntries();
863
- if (entries && entries.length)
864
- lastLcp = entries[entries.length - 1];
865
- }
866
- catch {
867
- // ignore
868
- }
2018
+ onCLS((metric) => {
2019
+ report(options.reportType, {
2020
+ pagePath: getPagePath(),
2021
+ metric: 'CLS',
2022
+ value: metric.value,
2023
+ unit: 'score',
2024
+ rating: metric.rating,
2025
+ id: metric.id,
2026
+ navigationType: metric.navigationType,
2027
+ });
869
2028
  });
870
- po.observe({ type: 'largest-contentful-paint', buffered: true });
871
- const flushLcp = () => {
872
- try {
873
- if (!lastLcp)
874
- return;
875
- if (!sampleHit(options.sampleRate))
876
- return;
877
- if (typeof lastLcp.startTime === 'number')
878
- reportMetric(report, options.reportType, 'LCP', lastLcp.startTime, { unit: 'ms' });
879
- lastLcp = null;
880
- }
881
- catch {
882
- // ignore
883
- }
884
- };
885
- window.addEventListener('pagehide', flushLcp, { once: true });
886
- document.addEventListener('visibilitychange', () => {
887
- if (document.visibilityState === 'hidden')
888
- flushLcp();
889
- }, { once: true });
890
2029
  }
891
2030
  catch {
892
2031
  // ignore
893
2032
  }
894
- // CLS
2033
+ // INP(替代 FID,2024年3月起成为核心指标)
895
2034
  try {
896
- let clsValue = 0;
897
- const po = new PerformanceObserver((list) => {
898
- try {
899
- for (const entry of list.getEntries()) {
900
- if (entry && entry.hadRecentInput)
901
- continue;
902
- if (typeof entry.value === 'number')
903
- clsValue += entry.value;
904
- }
905
- }
906
- catch {
907
- // ignore
908
- }
2035
+ onINP((metric) => {
2036
+ report(options.reportType, {
2037
+ pagePath: getPagePath(),
2038
+ metric: 'INP',
2039
+ value: metric.value,
2040
+ unit: 'ms',
2041
+ rating: metric.rating,
2042
+ id: metric.id,
2043
+ navigationType: metric.navigationType,
2044
+ });
909
2045
  });
910
- po.observe({ type: 'layout-shift', buffered: true });
911
- const flushCls = () => {
912
- try {
913
- if (!sampleHit(options.sampleRate))
914
- return;
915
- reportMetric(report, options.reportType, 'CLS', clsValue, { unit: 'score' });
916
- }
917
- catch {
918
- // ignore
919
- }
920
- };
921
- window.addEventListener('pagehide', flushCls, { once: true });
922
- document.addEventListener('visibilitychange', () => {
923
- if (document.visibilityState === 'hidden')
924
- flushCls();
925
- }, { once: true });
926
2046
  }
927
2047
  catch {
928
2048
  // ignore
929
2049
  }
930
- // FID
2050
+ // TTFB
931
2051
  try {
932
- const po = new PerformanceObserver((list) => {
933
- try {
934
- if (!sampleHit(options.sampleRate))
935
- return;
936
- for (const entry of list.getEntries()) {
937
- const startTime = typeof entry.startTime === 'number' ? entry.startTime : -1;
938
- const processingStart = typeof entry.processingStart === 'number' ? entry.processingStart : -1;
939
- if (startTime >= 0 && processingStart >= 0) {
940
- reportMetric(report, options.reportType, 'FID', processingStart - startTime, { unit: 'ms' });
941
- break;
942
- }
943
- }
944
- }
945
- catch {
946
- // ignore
947
- }
2052
+ onTTFB((metric) => {
2053
+ report(options.reportType, {
2054
+ pagePath: getPagePath(),
2055
+ metric: 'TTFB',
2056
+ value: metric.value,
2057
+ unit: 'ms',
2058
+ rating: metric.rating,
2059
+ id: metric.id,
2060
+ navigationType: metric.navigationType,
2061
+ });
948
2062
  });
949
- po.observe({ type: 'first-input', buffered: true });
950
2063
  }
951
2064
  catch {
952
2065
  // ignore
953
2066
  }
954
2067
  }
955
- // Resource timing:资源加载耗时
2068
+ // Resource timing:资源加载耗时(web-vitals 不包含此功能,保留原有实现)
956
2069
  if (options.resourceTiming && typeof globalThis.PerformanceObserver === 'function') {
957
2070
  try {
958
2071
  const po = new PerformanceObserver((list) => {
959
2072
  try {
960
- if (!sampleHit(options.sampleRate))
2073
+ if (!sampleHit$1(options.sampleRate))
961
2074
  return;
962
2075
  for (const entry of list.getEntries()) {
963
2076
  const name = String(entry?.name ?? '');
964
2077
  if (!name || shouldIgnoreUrl(name, ignoreUrls))
965
2078
  continue;
966
2079
  const initiatorType = String(entry?.initiatorType ?? '');
967
- // 对齐文档:关注 fetch/xhr/img/script(同时允许 css/other 但不强制)
2080
+ // 关注 fetch/xhr/img/script(同时允许 css/other 但不强制)
968
2081
  if (!['xmlhttprequest', 'fetch', 'img', 'script', 'css'].includes(initiatorType))
969
2082
  continue;
2083
+ // 时序分解(便于定位慢在哪个阶段)
2084
+ const domainLookupStart = entry.domainLookupStart ?? 0;
2085
+ const domainLookupEnd = entry.domainLookupEnd ?? 0;
2086
+ const connectStart = entry.connectStart ?? 0;
2087
+ const connectEnd = entry.connectEnd ?? 0;
2088
+ const requestStart = entry.requestStart ?? 0;
2089
+ const responseStart = entry.responseStart ?? 0;
2090
+ const responseEnd = entry.responseEnd ?? 0;
2091
+ const dns = domainLookupEnd - domainLookupStart;
2092
+ const tcp = connectEnd - connectStart;
2093
+ const ttfb = responseStart - requestStart;
2094
+ const download = responseEnd - responseStart;
2095
+ // 缓存检测:transferSize=0 且 decodedBodySize>0 表示缓存命中
2096
+ const transferSize = entry.transferSize ?? 0;
2097
+ const decodedBodySize = entry.decodedBodySize ?? 0;
2098
+ const cached = transferSize === 0 && decodedBodySize > 0;
970
2099
  const payload = {
971
2100
  pagePath: getPagePath(),
972
2101
  metric: 'resource',
@@ -974,16 +2103,26 @@ function installBrowserPerformanceMonitor(report, options) {
974
2103
  url: truncate$1(name, options.maxTextLength),
975
2104
  startTime: typeof entry?.startTime === 'number' ? entry.startTime : undefined,
976
2105
  duration: typeof entry?.duration === 'number' ? entry.duration : undefined,
2106
+ // 时序分解(跨域资源可能为 0)
2107
+ dns: dns > 0 ? Math.round(dns) : undefined,
2108
+ tcp: tcp > 0 ? Math.round(tcp) : undefined,
2109
+ ttfb: ttfb > 0 ? Math.round(ttfb) : undefined,
2110
+ download: download > 0 ? Math.round(download) : undefined,
2111
+ // 缓存标记
2112
+ cached,
977
2113
  };
978
- // 兼容字段(部分浏览器支持)
979
- if (typeof entry?.transferSize === 'number')
980
- payload.transferSize = entry.transferSize;
981
- if (typeof entry?.encodedBodySize === 'number')
2114
+ // 尺寸字段(跨域资源可能为 0)
2115
+ if (transferSize > 0)
2116
+ payload.transferSize = transferSize;
2117
+ if (typeof entry?.encodedBodySize === 'number' && entry.encodedBodySize > 0) {
982
2118
  payload.encodedBodySize = entry.encodedBodySize;
983
- if (typeof entry?.decodedBodySize === 'number')
984
- payload.decodedBodySize = entry.decodedBodySize;
985
- if (typeof entry?.nextHopProtocol === 'string')
2119
+ }
2120
+ if (decodedBodySize > 0)
2121
+ payload.decodedBodySize = decodedBodySize;
2122
+ // 协议和状态
2123
+ if (typeof entry?.nextHopProtocol === 'string' && entry.nextHopProtocol) {
986
2124
  payload.nextHopProtocol = entry.nextHopProtocol;
2125
+ }
987
2126
  if (typeof entry?.responseStatus === 'number')
988
2127
  payload.status = entry.responseStatus;
989
2128
  report(options.reportType, payload);
@@ -1000,146 +2139,98 @@ function installBrowserPerformanceMonitor(report, options) {
1000
2139
  }
1001
2140
  }
1002
2141
  }
1003
- function wrapMiniProgramRouteApi(report, reportType, apiName, options) {
1004
- const wxAny = globalThis.wx;
1005
- if (!wxAny || typeof wxAny[apiName] !== 'function')
1006
- return;
1007
- const flagKey = `__beLinkClsLoggerMpRouteWrapped__${apiName}`;
1008
- if (wxAny[flagKey])
2142
+ function installWebPerformanceMonitor(report, opts = {}) {
2143
+ const enabled = opts === undefined ? true : !!opts;
2144
+ if (!enabled)
1009
2145
  return;
1010
- wxAny[flagKey] = true;
1011
- const raw = wxAny[apiName].bind(wxAny);
1012
- wxAny[apiName] = (opts) => {
1013
- const start = Date.now();
1014
- const url = opts?.url ? String(opts.url) : '';
1015
- const wrapCb = (cb, success) => {
1016
- return (...args) => {
1017
- try {
1018
- if (sampleHit(options.sampleRate)) {
1019
- report(reportType, {
1020
- metric: 'route',
1021
- api: apiName,
1022
- url,
1023
- duration: Date.now() - start,
1024
- success: success ? 1 : 0,
1025
- error: success ? '' : truncate$1(stringifyLogValue(args?.[0]), options.maxTextLength),
1026
- unit: 'ms',
1027
- });
1028
- }
1029
- }
1030
- catch {
1031
- // ignore
1032
- }
1033
- if (typeof cb === 'function')
1034
- return cb(...args);
1035
- return undefined;
1036
- };
1037
- };
1038
- const next = { ...(opts ?? {}) };
1039
- next.success = wrapCb(next.success, true);
1040
- next.fail = wrapCb(next.fail, false);
1041
- return raw(next);
2146
+ const raw = typeof opts === 'object' && opts ? opts : {};
2147
+ const options = {
2148
+ enabled: true,
2149
+ reportType: raw.reportType ?? 'perf',
2150
+ sampleRate: raw.sampleRate ?? 1,
2151
+ ignoreUrls: raw.ignoreUrls ?? [],
2152
+ webVitals: raw.webVitals ?? true,
2153
+ resourceTiming: raw.resourceTiming ?? true,
2154
+ maxTextLength: raw.maxTextLength ?? 2000,
1042
2155
  };
2156
+ installBrowserPerformanceMonitor(report, options);
1043
2157
  }
1044
- function installMiniProgramPageRenderMonitor(report, reportType, options) {
1045
- const g = globalThis;
1046
- if (typeof g.Page !== 'function')
1047
- return;
1048
- if (g.__beLinkClsLoggerPageWrapped__)
1049
- return;
1050
- g.__beLinkClsLoggerPageWrapped__ = true;
1051
- const rawPage = g.Page;
1052
- g.Page = (pageOptions) => {
1053
- const next = { ...(pageOptions ?? {}) };
1054
- const rawOnLoad = next.onLoad;
1055
- const rawOnReady = next.onReady;
1056
- next.onLoad = function (...args) {
1057
- try {
1058
- this.__beLinkClsLoggerPageLoadTs__ = Date.now();
1059
- }
1060
- catch {
1061
- // ignore
1062
- }
1063
- if (typeof rawOnLoad === 'function')
1064
- return rawOnLoad.apply(this, args);
1065
- return undefined;
1066
- };
1067
- next.onReady = function (...args) {
1068
- try {
1069
- const start = this.__beLinkClsLoggerPageLoadTs__;
1070
- if (typeof start === 'number' && sampleHit(options.sampleRate)) {
1071
- report(reportType, {
1072
- metric: 'page-render',
1073
- route: this?.route ? String(this.route) : '',
1074
- duration: Date.now() - start,
1075
- unit: 'ms',
1076
- });
1077
- }
1078
- }
1079
- catch {
1080
- // ignore
1081
- }
1082
- if (typeof rawOnReady === 'function')
1083
- return rawOnReady.apply(this, args);
1084
- return undefined;
1085
- };
1086
- return rawPage(next);
1087
- };
2158
+
2159
+ function sampleHit(sampleRate) {
2160
+ if (sampleRate >= 1)
2161
+ return true;
2162
+ if (sampleRate <= 0)
2163
+ return false;
2164
+ return Math.random() < sampleRate;
1088
2165
  }
1089
2166
  function installMiniProgramPerformanceMonitor(report, options) {
1090
2167
  const g = globalThis;
2168
+ const ctx = g.wx || g.Taro;
2169
+ if (!ctx || typeof ctx.getPerformance !== 'function')
2170
+ return;
1091
2171
  if (g.__beLinkClsLoggerMpPerfInstalled__)
1092
2172
  return;
1093
2173
  g.__beLinkClsLoggerMpPerfInstalled__ = true;
1094
- // 路由切换耗时(用 API 回调近似)
1095
- for (const apiName of ['navigateTo', 'redirectTo', 'switchTab', 'reLaunch']) {
1096
- try {
1097
- wrapMiniProgramRouteApi(report, options.reportType, apiName, options);
1098
- }
1099
- catch {
1100
- // ignore
1101
- }
1102
- }
1103
- // 页面渲染耗时(onLoad -> onReady)
1104
- try {
1105
- installMiniProgramPageRenderMonitor(report, options.reportType, options);
1106
- }
1107
- catch {
1108
- // ignore
1109
- }
1110
- // wx.getPerformance()(若可用,尝试读取已有 entries)
1111
2174
  try {
1112
- const wxAny = globalThis.wx;
1113
- if (wxAny && typeof wxAny.getPerformance === 'function') {
1114
- const perf = wxAny.getPerformance();
1115
- if (perf && isPlainObject(perf)) {
1116
- // 不同基础库实现差异较大:尽量容错
1117
- setTimeout(() => {
1118
- try {
1119
- if (!sampleHit(options.sampleRate))
1120
- return;
1121
- const entries = typeof perf.getEntries === 'function'
1122
- ? perf.getEntries()
1123
- : typeof perf.getEntriesByType === 'function'
1124
- ? perf.getEntriesByType('navigation')
1125
- : [];
2175
+ const perf = ctx.getPerformance();
2176
+ if (!perf || typeof perf.createObserver !== 'function')
2177
+ return;
2178
+ const observer = perf.createObserver((entryList) => {
2179
+ try {
2180
+ const entries = entryList.getEntries();
2181
+ for (const entry of entries) {
2182
+ if (!sampleHit(options.sampleRate))
2183
+ continue;
2184
+ // Page Render: firstRender
2185
+ if (entry.entryType === 'render' && entry.name === 'firstRender') {
2186
+ const duration = typeof entry.duration === 'number'
2187
+ ? entry.duration
2188
+ : typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
2189
+ ? entry.endTime - entry.startTime
2190
+ : 0;
1126
2191
  report(options.reportType, {
1127
- metric: 'mp-performance',
1128
- entries: truncate$1(stringifyLogValue(entries), options.maxTextLength),
2192
+ metric: 'page-render',
2193
+ duration,
2194
+ pagePath: entry.path || '',
2195
+ unit: 'ms',
1129
2196
  });
1130
2197
  }
1131
- catch {
1132
- // ignore
2198
+ // Route Switch: route
2199
+ else if (entry.entryType === 'navigation' && entry.name === 'route') {
2200
+ const duration = typeof entry.duration === 'number'
2201
+ ? entry.duration
2202
+ : typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
2203
+ ? entry.endTime - entry.startTime
2204
+ : 0;
2205
+ report(options.reportType, {
2206
+ metric: 'route',
2207
+ duration,
2208
+ pagePath: entry.path || '',
2209
+ unit: 'ms',
2210
+ });
2211
+ }
2212
+ // App Launch: appLaunch (Cold)
2213
+ else if (entry.entryType === 'navigation' && entry.name === 'appLaunch') {
2214
+ report(options.reportType, {
2215
+ metric: 'app-launch',
2216
+ duration: entry.duration,
2217
+ launchType: 'cold',
2218
+ unit: 'ms',
2219
+ });
1133
2220
  }
1134
- }, 0);
2221
+ }
1135
2222
  }
1136
- }
2223
+ catch {
2224
+ // ignore
2225
+ }
2226
+ });
2227
+ observer.observe({ entryTypes: ['navigation', 'render'] });
1137
2228
  }
1138
2229
  catch {
1139
2230
  // ignore
1140
2231
  }
1141
2232
  }
1142
- function installPerformanceMonitor(report, opts = {}) {
2233
+ function installMiniPerformanceMonitor(report, opts = {}) {
1143
2234
  const enabled = opts === undefined ? true : !!opts;
1144
2235
  if (!enabled)
1145
2236
  return;
@@ -1150,18 +2241,20 @@ function installPerformanceMonitor(report, opts = {}) {
1150
2241
  sampleRate: raw.sampleRate ?? 1,
1151
2242
  ignoreUrls: raw.ignoreUrls ?? [],
1152
2243
  webVitals: raw.webVitals ?? true,
1153
- navigationTiming: raw.navigationTiming ?? true,
1154
2244
  resourceTiming: raw.resourceTiming ?? true,
1155
2245
  maxTextLength: raw.maxTextLength ?? 2000,
1156
2246
  };
2247
+ installMiniProgramPerformanceMonitor(report, options);
2248
+ }
2249
+
2250
+ function installPerformanceMonitor(report, opts = {}) {
1157
2251
  if (isMiniProgramEnv()) {
1158
- installMiniProgramPerformanceMonitor(report, options);
1159
- return;
2252
+ return installMiniPerformanceMonitor(report, opts);
1160
2253
  }
1161
- installBrowserPerformanceMonitor(report, options);
2254
+ return installWebPerformanceMonitor(report, opts);
1162
2255
  }
1163
2256
 
1164
- function shouldSample(sampleRate) {
2257
+ function shouldSample$1(sampleRate) {
1165
2258
  const r = sampleRate ?? 1;
1166
2259
  if (r >= 1)
1167
2260
  return true;
@@ -1169,19 +2262,17 @@ function shouldSample(sampleRate) {
1169
2262
  return false;
1170
2263
  return Math.random() < r;
1171
2264
  }
1172
- function generateUUID() {
1173
- // 优先使用更安全的 crypto.randomUUID
2265
+ function generateUUID$1() {
1174
2266
  const g = globalThis;
1175
2267
  if (g.crypto?.randomUUID)
1176
2268
  return g.crypto.randomUUID();
1177
- // fallback
1178
2269
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
1179
2270
  const r = Math.random() * 16 || 0;
1180
2271
  const v = c === 'x' ? r | 0 : ((r | 0) & 0x3) | 0x8;
1181
2272
  return v.toString(16);
1182
2273
  });
1183
2274
  }
1184
- function safeReadUvMeta(key) {
2275
+ function safeReadUvMeta$1(key) {
1185
2276
  const raw = readStringStorage(key);
1186
2277
  if (!raw)
1187
2278
  return { firstVisitTs: Date.now(), visitCount: 0 };
@@ -1200,27 +2291,15 @@ function safeReadUvMeta(key) {
1200
2291
  return { firstVisitTs: Date.now(), visitCount: 0 };
1201
2292
  }
1202
2293
  }
1203
- function writeUvMeta(key, meta) {
2294
+ function writeUvMeta$1(key, meta) {
1204
2295
  writeStringStorage(key, JSON.stringify(meta));
1205
2296
  }
1206
2297
  function getWebPagePath() {
1207
2298
  if (typeof window === 'undefined')
1208
2299
  return '';
1209
- return window.location?.pathname || '';
1210
- }
1211
- function getMiniProgramPagePath() {
1212
- const g = globalThis;
1213
- try {
1214
- const pages = typeof g.getCurrentPages === 'function' ? g.getCurrentPages() : [];
1215
- const last = Array.isArray(pages) ? pages[pages.length - 1] : undefined;
1216
- const route = (last?.route || last?.__route__);
1217
- return typeof route === 'string' ? route : '';
1218
- }
1219
- catch {
1220
- return '';
1221
- }
2300
+ return window.location?.href || '';
1222
2301
  }
1223
- function buildCommonUvFields(uvId, uvMeta, isFirstVisit) {
2302
+ function buildCommonUvFields$1(uvId, uvMeta, isFirstVisit) {
1224
2303
  return {
1225
2304
  uvId,
1226
2305
  isFirstVisit,
@@ -1236,14 +2315,14 @@ function getAttr(el, attrName) {
1236
2315
  return '';
1237
2316
  }
1238
2317
  }
1239
- function truncateText(s, maxLen) {
2318
+ function truncateText$1(s, maxLen) {
1240
2319
  if (!s)
1241
2320
  return '';
1242
2321
  if (s.length <= maxLen)
1243
2322
  return s;
1244
2323
  return s.slice(0, maxLen);
1245
2324
  }
1246
- function installBehaviorMonitor(report, envType, options = {}) {
2325
+ function installWebBehaviorMonitor(report, options = {}) {
1247
2326
  const enableTrack = options.enableTrack ?? options.enabled ?? true;
1248
2327
  if (!enableTrack)
1249
2328
  return () => { };
@@ -1255,39 +2334,28 @@ function installBehaviorMonitor(report, envType, options = {}) {
1255
2334
  const clickReportType = options.clickReportType ?? 'click';
1256
2335
  const uvIdStorageKey = options.uvIdStorageKey ?? 'cls_uv_id';
1257
2336
  const uvMetaStorageKey = options.uvMetaStorageKey ?? 'cls_uv_meta';
1258
- const lastPagePathStorageKey = options.lastPagePathStorageKey ?? 'cls_last_page_path';
1259
2337
  const uvExpireDaysRaw = options.trackOptions?.uvExpireDays ?? options.uvExpireDays ?? 30;
1260
2338
  const uvExpireDays = Number.isFinite(uvExpireDaysRaw) ? Math.max(0, uvExpireDaysRaw) : 30;
1261
2339
  const uvExpireMs = uvExpireDays * 24 * 60 * 60 * 1000;
1262
- const defaultClickWhiteList = envType === 'miniprogram' || isMiniProgramEnv() ? ['view', 'scroll-view'] : ['body', 'html'];
1263
- const clickWhiteList = (options.trackOptions?.clickWhiteList ?? options.clickWhiteList ?? defaultClickWhiteList).map((s) => String(s).toLowerCase());
2340
+ const clickWhiteList = (options.trackOptions?.clickWhiteList ?? options.clickWhiteList ?? ['body', 'html']).map((s) => String(s).toLowerCase());
1264
2341
  const clickTrackIdAttr = options.clickTrackIdAttr ?? 'data-track-id';
1265
2342
  const clickMaxTextLength = options.clickMaxTextLength ?? 120;
1266
- const getPagePath = options.getPagePath ??
1267
- (() => {
1268
- if (envType === 'miniprogram' || isMiniProgramEnv())
1269
- return getMiniProgramPagePath();
1270
- return getWebPagePath();
1271
- });
2343
+ const getPagePath = options.getPagePath ?? getWebPagePath;
1272
2344
  let destroyed = false;
1273
- // UV 状态:可能异步(openid/指纹)
1274
2345
  let firstVisitFlag = false;
1275
2346
  let firstVisitConsumed = false;
1276
2347
  const uvStatePromise = (async () => {
1277
2348
  let existingUvId = readStringStorage(uvIdStorageKey);
1278
2349
  let isFirstVisit = false;
1279
- // 先读 meta,做过期判断(过期则清空 uvId + 重置 meta)
1280
2350
  const now = Date.now();
1281
- const metaBefore = safeReadUvMeta(uvMetaStorageKey);
2351
+ const metaBefore = safeReadUvMeta$1(uvMetaStorageKey);
1282
2352
  const lastSeenForExpire = metaBefore.lastSeenTs ?? metaBefore.createdAtTs ?? metaBefore.firstVisitTs ?? now;
1283
2353
  const expired = uvExpireMs > 0 && now - lastSeenForExpire > uvExpireMs;
1284
2354
  if (expired) {
1285
2355
  existingUvId = null;
1286
- // 重置 meta(visitCount 会在后续 +1)
1287
- writeUvMeta(uvMetaStorageKey, { firstVisitTs: now, visitCount: 0, createdAtTs: now, lastSeenTs: now });
2356
+ writeUvMeta$1(uvMetaStorageKey, { firstVisitTs: now, visitCount: 0, createdAtTs: now, lastSeenTs: now });
1288
2357
  writeStringStorage(uvIdStorageKey, '');
1289
2358
  }
1290
- // 如果外部提供 getUvId,优先使用;否则本地生成
1291
2359
  try {
1292
2360
  if (options.getUvId) {
1293
2361
  const maybe = options.getUvId();
@@ -1297,42 +2365,14 @@ function installBehaviorMonitor(report, envType, options = {}) {
1297
2365
  }
1298
2366
  }
1299
2367
  catch {
1300
- // ignore
1301
- }
1302
- // 小程序:默认尝试 openid / 设备标识(兼容你给的参考实现)
1303
- if (!existingUvId && (envType === 'miniprogram' || isMiniProgramEnv())) {
1304
- const wxAny = globalThis.wx;
1305
- try {
1306
- const userInfo = wxAny?.getStorageSync?.('userInfo');
1307
- if (userInfo?.openid)
1308
- existingUvId = String(userInfo.openid);
1309
- }
1310
- catch {
1311
- // ignore
1312
- }
1313
- if (!existingUvId) {
1314
- try {
1315
- const sys = wxAny?.getSystemInfoSync?.();
1316
- const deviceId = sys?.deviceId ? String(sys.deviceId) : '';
1317
- const model = sys?.model ? String(sys.model) : '';
1318
- const system = sys?.system ? String(sys.system) : '';
1319
- const base = [deviceId || model, system].filter(Boolean).join('_');
1320
- if (base)
1321
- existingUvId = `${base}_${Date.now()}`;
1322
- }
1323
- catch {
1324
- // ignore
1325
- }
1326
- }
2368
+ /* ignore */
1327
2369
  }
1328
2370
  if (!existingUvId) {
1329
- existingUvId = generateUUID();
2371
+ existingUvId = generateUUID$1();
1330
2372
  isFirstVisit = true;
1331
2373
  }
1332
- // 只要拿到了 uvId,就写入持久化(便于下次启动复用)
1333
2374
  writeStringStorage(uvIdStorageKey, existingUvId);
1334
- const meta = safeReadUvMeta(uvMetaStorageKey);
1335
- // 每次启动都 +1(“累计访问次数”)
2375
+ const meta = safeReadUvMeta$1(uvMetaStorageKey);
1336
2376
  const createdAt = meta.createdAtTs ?? meta.firstVisitTs ?? now;
1337
2377
  const firstVisit = meta.firstVisitTs || now;
1338
2378
  const nextMeta = {
@@ -1341,19 +2381,18 @@ function installBehaviorMonitor(report, envType, options = {}) {
1341
2381
  createdAtTs: createdAt,
1342
2382
  lastSeenTs: now,
1343
2383
  };
1344
- // 如果是首次访问,刷新 firstVisitTs
1345
2384
  if (isFirstVisit) {
1346
2385
  nextMeta.firstVisitTs = now;
1347
2386
  nextMeta.createdAtTs = now;
1348
2387
  }
1349
- writeUvMeta(uvMetaStorageKey, nextMeta);
2388
+ writeUvMeta$1(uvMetaStorageKey, nextMeta);
1350
2389
  firstVisitFlag = isFirstVisit;
1351
2390
  return { uvId: existingUvId, isFirstVisit, meta: nextMeta };
1352
2391
  })();
1353
2392
  function safeReport(type, data) {
1354
2393
  if (destroyed)
1355
2394
  return;
1356
- if (!shouldSample(options.sampleRate))
2395
+ if (!shouldSample$1(options.sampleRate))
1357
2396
  return;
1358
2397
  report(type, data);
1359
2398
  }
@@ -1361,20 +2400,7 @@ function installBehaviorMonitor(report, envType, options = {}) {
1361
2400
  const once = firstVisitFlag && !firstVisitConsumed;
1362
2401
  if (once)
1363
2402
  firstVisitConsumed = true;
1364
- return buildCommonUvFields(uvId, meta, once);
1365
- }
1366
- function reportUvOncePerSession() {
1367
- if (!uvEnabled)
1368
- return;
1369
- void uvStatePromise.then(({ uvId, meta }) => {
1370
- if (destroyed)
1371
- return;
1372
- safeReport(uvReportType, {
1373
- ...buildUvFieldsOnce(uvId, meta),
1374
- timestamp: Date.now(),
1375
- pagePath: getPagePath(),
1376
- });
1377
- });
2403
+ return buildCommonUvFields$1(uvId, meta, once);
1378
2404
  }
1379
2405
  function reportPv(pagePath) {
1380
2406
  if (!pvEnabled)
@@ -1386,956 +2412,780 @@ function installBehaviorMonitor(report, envType, options = {}) {
1386
2412
  ...buildUvFieldsOnce(uvId, meta),
1387
2413
  timestamp: Date.now(),
1388
2414
  pagePath,
2415
+ referrer: typeof document !== 'undefined' ? document.referrer || '' : '',
1389
2416
  };
1390
- // Web referrer(小程序为空串)
1391
- if (typeof document !== 'undefined') {
1392
- payload.referrer = document.referrer || '';
1393
- }
1394
- else if (envType === 'miniprogram' || isMiniProgramEnv()) {
1395
- payload.referrer = readStringStorage(lastPagePathStorageKey) || '';
1396
- writeStringStorage(lastPagePathStorageKey, pagePath);
1397
- }
1398
2417
  safeReport(pvReportType, payload);
1399
2418
  });
1400
2419
  }
1401
- // --- Web: PV ---
2420
+ // Web PV Listeners
1402
2421
  let removeWebPvListeners = null;
1403
- if (!destroyed && pvEnabled && typeof window !== 'undefined' && typeof history !== 'undefined') {
2422
+ if (pvEnabled && typeof window !== 'undefined' && typeof history !== 'undefined') {
1404
2423
  const originalPushState = window.history.pushState?.bind(window.history);
1405
2424
  const originalReplaceState = window.history.replaceState?.bind(window.history);
1406
- const onRouteChanged = () => reportPv(getPagePath());
1407
- // 首次进入页面上报 PV
1408
- onRouteChanged();
1409
- // patch pushState/replaceState
1410
- if (originalPushState) {
1411
- window.history.pushState = ((...args) => {
1412
- const r = originalPushState.apply(window.history, args);
1413
- onRouteChanged();
1414
- return r;
1415
- });
1416
- }
1417
- if (originalReplaceState) {
1418
- window.history.replaceState = ((...args) => {
1419
- const r = originalReplaceState.apply(window.history, args);
1420
- onRouteChanged();
1421
- return r;
1422
- });
1423
- }
1424
- window.addEventListener('popstate', onRouteChanged);
1425
- removeWebPvListeners = () => {
1426
- try {
1427
- window.removeEventListener('popstate', onRouteChanged);
1428
- }
1429
- catch {
1430
- // ignore
1431
- }
1432
- try {
1433
- if (originalPushState)
1434
- window.history.pushState = originalPushState;
1435
- if (originalReplaceState)
1436
- window.history.replaceState = originalReplaceState;
1437
- }
1438
- catch {
1439
- // ignore
1440
- }
1441
- };
1442
- }
1443
- // --- Web: Click ---
1444
- let removeWebClickListener = null;
1445
- if (!destroyed && clickEnabled && typeof document !== 'undefined') {
1446
- const onClick = (e) => {
1447
- if (destroyed)
1448
- return;
1449
- const target = e.target;
1450
- if (!target)
1451
- return;
1452
- // 向上找最接近的带 trackId 的元素(优先)
1453
- const closestWithTrackId = typeof target.closest === 'function'
1454
- ? target.closest(`[${clickTrackIdAttr}]`)
1455
- : null;
1456
- const el = closestWithTrackId || target;
1457
- const tag = (el.tagName || '').toLowerCase();
1458
- const trackId = getAttr(el, clickTrackIdAttr);
1459
- // 过滤无效点击:白名单 tag + 没有 trackId
1460
- if (clickWhiteList.includes(tag) && !trackId)
1461
- return;
1462
- void uvStatePromise.then(({ uvId, meta }) => {
1463
- if (destroyed)
1464
- return;
1465
- safeReport(clickReportType, {
1466
- ...buildUvFieldsOnce(uvId, meta),
1467
- timestamp: Date.now(),
1468
- pagePath: getPagePath(),
1469
- elementTag: el.tagName || '',
1470
- elementId: el.id || '',
1471
- elementClass: stringifyLogValue(el.className ?? ''),
1472
- trackId: trackId || '',
1473
- elementText: truncateText((el.textContent ?? '').trim(), clickMaxTextLength),
1474
- clickX: Number.isFinite(e.clientX) ? e.clientX : 0,
1475
- clickY: Number.isFinite(e.clientY) ? e.clientY : 0,
1476
- });
1477
- });
1478
- };
1479
- document.addEventListener('click', onClick, true);
1480
- removeWebClickListener = () => {
1481
- try {
1482
- document.removeEventListener('click', onClick, true);
1483
- }
1484
- catch {
1485
- // ignore
1486
- }
1487
- };
1488
- }
1489
- // --- MiniProgram: PV (best-effort) ---
1490
- let restoreMiniProgramPatch = null;
1491
- if (!destroyed && (envType === 'miniprogram' || isMiniProgramEnv())) {
1492
- const g = globalThis;
1493
- const patchedKey = '__beLinkClsLoggerBehaviorPatched__';
1494
- if (!g[patchedKey]) {
1495
- g[patchedKey] = true;
1496
- const originalPage = typeof g.Page === 'function' ? g.Page : null;
1497
- if (originalPage) {
1498
- g.Page = function patchedPage(conf) {
1499
- const originalOnShow = conf?.onShow;
1500
- conf.onShow = function (...args) {
1501
- if (pvEnabled)
1502
- reportPv(getPagePath());
1503
- return typeof originalOnShow === 'function' ? originalOnShow.apply(this, args) : undefined;
1504
- };
1505
- // 点击:wrap 页面 methods(bindtap 等会调用到这里的 handler)
1506
- if (clickEnabled && conf && typeof conf === 'object') {
1507
- for (const key of Object.keys(conf)) {
1508
- const fn = conf[key];
1509
- if (typeof fn !== 'function')
1510
- continue;
1511
- if (fn.__beLinkWrapped__)
1512
- continue;
1513
- conf[key] = function (...args) {
1514
- try {
1515
- const e = args?.[0];
1516
- const type = e?.type;
1517
- const currentTarget = e?.currentTarget;
1518
- const dataset = currentTarget?.dataset;
1519
- const isTap = type === 'tap' || type === 'click';
1520
- if (clickEnabled && isTap && currentTarget && dataset) {
1521
- const tagNameRaw = dataset?.tagName ?? dataset?.tag ?? currentTarget?.tagName ?? '';
1522
- const tagName = String(tagNameRaw || '').toLowerCase();
1523
- const trackId = dataset?.trackId ? String(dataset.trackId) : '';
1524
- if (!(clickWhiteList.includes(tagName) && !trackId)) {
1525
- const x = typeof e?.detail?.x === 'number'
1526
- ? e.detail.x
1527
- : typeof e?.touches?.[0]?.pageX === 'number'
1528
- ? e.touches[0].pageX
1529
- : 0;
1530
- const y = typeof e?.detail?.y === 'number'
1531
- ? e.detail.y
1532
- : typeof e?.touches?.[0]?.pageY === 'number'
1533
- ? e.touches[0].pageY
1534
- : 0;
1535
- void uvStatePromise.then(({ uvId, meta }) => {
1536
- if (destroyed)
1537
- return;
1538
- safeReport(clickReportType, {
1539
- ...buildUvFieldsOnce(uvId, meta),
1540
- timestamp: Date.now(),
1541
- pagePath: getPagePath(),
1542
- elementTag: tagNameRaw ? String(tagNameRaw) : '',
1543
- elementId: currentTarget?.id ? String(currentTarget.id) : '',
1544
- elementClass: dataset?.className ? stringifyLogValue(dataset.className) : '',
1545
- trackId,
1546
- elementText: dataset?.text ? truncateText(String(dataset.text), clickMaxTextLength) : '',
1547
- clickX: x,
1548
- clickY: y,
1549
- });
1550
- });
1551
- }
1552
- }
1553
- }
1554
- catch {
1555
- // ignore
1556
- }
1557
- return fn.apply(this, args);
1558
- };
1559
- conf[key].__beLinkWrapped__ = true;
1560
- }
1561
- }
1562
- return originalPage(conf);
1563
- };
1564
- restoreMiniProgramPatch = () => {
1565
- try {
1566
- g.Page = originalPage;
1567
- g[patchedKey] = false;
1568
- }
1569
- catch {
1570
- // ignore
1571
- }
1572
- };
1573
- }
1574
- }
1575
- // 启动时也尝试报一次(避免 Page patch 未生效的场景)
1576
- if (pvEnabled)
1577
- reportPv(getPagePath());
1578
- }
1579
- // UV:每次启动上报一次(可关闭)
1580
- reportUvOncePerSession();
1581
- return () => {
1582
- if (destroyed)
1583
- return;
1584
- destroyed = true;
1585
- try {
1586
- removeWebPvListeners?.();
1587
- removeWebClickListener?.();
1588
- restoreMiniProgramPatch?.();
1589
- }
1590
- catch {
1591
- // ignore
1592
- }
1593
- };
1594
- }
1595
-
1596
- function truncate(s, maxLen) {
1597
- if (!s)
1598
- return s;
1599
- return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
1600
- }
1601
- function parseUserAgent(uaRaw) {
1602
- const ua = uaRaw ?? '';
1603
- const isMobile = /Mobile|Android|iPhone|iPad|iPod/i.test(ua);
1604
- // OS
1605
- let osName = 'unknown';
1606
- let osVersion = '';
1607
- const ios = ua.match(/OS (\d+[_\d]*) like Mac OS X/i);
1608
- const android = ua.match(/Android (\d+(\.\d+)*)/i);
1609
- const mac = ua.match(/Mac OS X (\d+[_\d]*)/i);
1610
- const win = ua.match(/Windows NT (\d+(\.\d+)*)/i);
1611
- if (ios) {
1612
- osName = 'iOS';
1613
- osVersion = ios[1].replace(/_/g, '.');
1614
- }
1615
- else if (android) {
1616
- osName = 'Android';
1617
- osVersion = android[1];
1618
- }
1619
- else if (win) {
1620
- osName = 'Windows';
1621
- osVersion = win[1];
1622
- }
1623
- else if (mac) {
1624
- osName = 'macOS';
1625
- osVersion = mac[1].replace(/_/g, '.');
1626
- }
1627
- // Browser
1628
- let browserName = 'unknown';
1629
- let browserVersion = '';
1630
- const edge = ua.match(/Edg\/(\d+(\.\d+)*)/);
1631
- const chrome = ua.match(/Chrome\/(\d+(\.\d+)*)/);
1632
- const safari = ua.match(/Version\/(\d+(\.\d+)*) Safari\//);
1633
- const firefox = ua.match(/Firefox\/(\d+(\.\d+)*)/);
1634
- if (edge) {
1635
- browserName = 'Edge';
1636
- browserVersion = edge[1];
1637
- }
1638
- else if (chrome) {
1639
- browserName = 'Chrome';
1640
- browserVersion = chrome[1];
1641
- }
1642
- else if (firefox) {
1643
- browserName = 'Firefox';
1644
- browserVersion = firefox[1];
1645
- }
1646
- else if (safari) {
1647
- browserName = 'Safari';
1648
- browserVersion = safari[1];
1649
- }
1650
- return { browserName, browserVersion, osName, osVersion, isMobile };
1651
- }
1652
- function getBrowserDeviceInfo(options) {
1653
- const out = {
1654
- envType: 'browser',
1655
- };
1656
- if (typeof window === 'undefined' || typeof navigator === 'undefined')
1657
- return out;
1658
- const ua = String(navigator.userAgent ?? '');
1659
- const uaParsed = parseUserAgent(ua);
1660
- if (options.includeUserAgent)
1661
- out.ua = truncate(ua, 2000);
1662
- out.browserName = uaParsed.browserName;
1663
- out.browserVersion = uaParsed.browserVersion;
1664
- out.osName = uaParsed.osName;
1665
- out.osVersion = uaParsed.osVersion;
1666
- out.isMobile = uaParsed.isMobile ? 1 : 0;
1667
- out.language = String(navigator.language ?? '');
1668
- out.platform = String(navigator.platform ?? '');
1669
- try {
1670
- const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
1671
- out.timezone = typeof tz === 'string' ? tz : '';
1672
- }
1673
- catch {
1674
- out.timezone = '';
1675
- }
1676
- try {
1677
- const s = window.screen;
1678
- out.screenWidth = s?.width ?? undefined;
1679
- out.screenHeight = s?.height ?? undefined;
1680
- }
1681
- catch {
1682
- // ignore
2425
+ const onRouteChanged = () => reportPv(getPagePath());
2426
+ onRouteChanged();
2427
+ if (originalPushState) {
2428
+ window.history.pushState = ((...args) => {
2429
+ const r = originalPushState.apply(window.history, args);
2430
+ onRouteChanged();
2431
+ return r;
2432
+ });
2433
+ }
2434
+ if (originalReplaceState) {
2435
+ window.history.replaceState = ((...args) => {
2436
+ const r = originalReplaceState.apply(window.history, args);
2437
+ onRouteChanged();
2438
+ return r;
2439
+ });
2440
+ }
2441
+ window.addEventListener('popstate', onRouteChanged);
2442
+ removeWebPvListeners = () => {
2443
+ window.removeEventListener('popstate', onRouteChanged);
2444
+ if (originalPushState)
2445
+ window.history.pushState = originalPushState;
2446
+ if (originalReplaceState)
2447
+ window.history.replaceState = originalReplaceState;
2448
+ };
1683
2449
  }
1684
- try {
1685
- out.dpr = typeof window.devicePixelRatio === 'number' ? window.devicePixelRatio : undefined;
2450
+ // Web Click Listener
2451
+ let removeWebClickListener = null;
2452
+ if (clickEnabled && typeof document !== 'undefined') {
2453
+ const onClick = (e) => {
2454
+ if (destroyed)
2455
+ return;
2456
+ const target = e.target;
2457
+ if (!target)
2458
+ return;
2459
+ const closestWithTrackId = typeof target.closest === 'function'
2460
+ ? target.closest(`[${clickTrackIdAttr}]`)
2461
+ : null;
2462
+ const el = closestWithTrackId || target;
2463
+ const tag = (el.tagName || '').toLowerCase();
2464
+ const trackId = getAttr(el, clickTrackIdAttr);
2465
+ if (clickWhiteList.includes(tag) || !trackId)
2466
+ return;
2467
+ void uvStatePromise.then(({ uvId, meta }) => {
2468
+ if (destroyed)
2469
+ return;
2470
+ safeReport(clickReportType, {
2471
+ ...buildUvFieldsOnce(uvId, meta),
2472
+ timestamp: Date.now(),
2473
+ pagePath: getPagePath(),
2474
+ elementTag: el.tagName || '',
2475
+ elementId: el.id || '',
2476
+ elementClass: stringifyLogValue(el.className ?? ''),
2477
+ trackId: trackId || '',
2478
+ elementText: truncateText$1((el.textContent ?? '').trim(), clickMaxTextLength),
2479
+ clickX: Number.isFinite(e.clientX) ? e.clientX : 0,
2480
+ clickY: Number.isFinite(e.clientY) ? e.clientY : 0,
2481
+ });
2482
+ });
2483
+ };
2484
+ document.addEventListener('click', onClick, true);
2485
+ removeWebClickListener = () => document.removeEventListener('click', onClick, true);
1686
2486
  }
1687
- catch {
1688
- // ignore
2487
+ // UV Initial Report
2488
+ if (uvEnabled) {
2489
+ void uvStatePromise.then(({ uvId, meta }) => {
2490
+ if (destroyed)
2491
+ return;
2492
+ safeReport(uvReportType, {
2493
+ ...buildUvFieldsOnce(uvId, meta),
2494
+ timestamp: Date.now(),
2495
+ pagePath: getPagePath(),
2496
+ });
2497
+ });
1689
2498
  }
2499
+ return () => {
2500
+ destroyed = true;
2501
+ removeWebPvListeners?.();
2502
+ removeWebClickListener?.();
2503
+ };
2504
+ }
2505
+
2506
+ function shouldSample(sampleRate) {
2507
+ const r = sampleRate ?? 1;
2508
+ if (r >= 1)
2509
+ return true;
2510
+ if (r <= 0)
2511
+ return false;
2512
+ return Math.random() < r;
2513
+ }
2514
+ function generateUUID() {
2515
+ const g = globalThis;
2516
+ if (g.crypto?.randomUUID)
2517
+ return g.crypto.randomUUID();
2518
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
2519
+ const r = Math.random() * 16 || 0;
2520
+ const v = c === 'x' ? r | 0 : ((r | 0) & 0x3) | 0x8;
2521
+ return v.toString(16);
2522
+ });
2523
+ }
2524
+ function safeReadUvMeta(key) {
2525
+ const raw = readStringStorage(key);
2526
+ if (!raw)
2527
+ return { firstVisitTs: Date.now(), visitCount: 0 };
1690
2528
  try {
1691
- const navAny = navigator;
1692
- out.hardwareConcurrency = typeof navAny.hardwareConcurrency === 'number' ? navAny.hardwareConcurrency : undefined;
1693
- out.deviceMemory = typeof navAny.deviceMemory === 'number' ? navAny.deviceMemory : undefined;
2529
+ const parsed = JSON.parse(raw);
2530
+ if (!parsed || typeof parsed !== 'object')
2531
+ return { firstVisitTs: Date.now(), visitCount: 0 };
2532
+ const p = parsed;
2533
+ const firstVisitTs = typeof p.firstVisitTs === 'number' && Number.isFinite(p.firstVisitTs) ? p.firstVisitTs : Date.now();
2534
+ const visitCount = typeof p.visitCount === 'number' && Number.isFinite(p.visitCount) ? p.visitCount : 0;
2535
+ const createdAtTs = typeof p.createdAtTs === 'number' && Number.isFinite(p.createdAtTs) ? p.createdAtTs : undefined;
2536
+ const lastSeenTs = typeof p.lastSeenTs === 'number' && Number.isFinite(p.lastSeenTs) ? p.lastSeenTs : undefined;
2537
+ return { firstVisitTs, visitCount, createdAtTs, lastSeenTs };
1694
2538
  }
1695
2539
  catch {
1696
- // ignore
1697
- }
1698
- if (options.includeNetwork) {
1699
- try {
1700
- const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
1701
- if (conn && isPlainObject(conn)) {
1702
- if (typeof conn.effectiveType === 'string')
1703
- out.netEffectiveType = conn.effectiveType;
1704
- if (typeof conn.downlink === 'number')
1705
- out.netDownlink = conn.downlink;
1706
- if (typeof conn.rtt === 'number')
1707
- out.netRtt = conn.rtt;
1708
- if (typeof conn.saveData === 'boolean')
1709
- out.netSaveData = conn.saveData ? 1 : 0;
1710
- }
1711
- }
1712
- catch {
1713
- // ignore
1714
- }
2540
+ return { firstVisitTs: Date.now(), visitCount: 0 };
1715
2541
  }
1716
- return out;
1717
2542
  }
1718
- function getMiniProgramDeviceInfo(options) {
1719
- const out = {
1720
- envType: 'miniprogram',
1721
- };
1722
- const wxAny = globalThis.wx;
1723
- if (!wxAny || typeof wxAny.getSystemInfoSync !== 'function')
1724
- return out;
2543
+ function writeUvMeta(key, meta) {
2544
+ writeStringStorage(key, JSON.stringify(meta));
2545
+ }
2546
+ function getMiniProgramPagePath() {
2547
+ const g = globalThis;
1725
2548
  try {
1726
- const sys = wxAny.getSystemInfoSync();
1727
- out.mpBrand = sys?.brand ? String(sys.brand) : '';
1728
- out.mpModel = sys?.model ? String(sys.model) : '';
1729
- out.mpSystem = sys?.system ? String(sys.system) : '';
1730
- out.mpPlatform = sys?.platform ? String(sys.platform) : '';
1731
- out.mpWeChatVersion = sys?.version ? String(sys.version) : '';
1732
- out.mpSDKVersion = sys?.SDKVersion ? String(sys.SDKVersion) : '';
1733
- out.mpScreenWidth = typeof sys?.screenWidth === 'number' ? sys.screenWidth : undefined;
1734
- out.mpScreenHeight = typeof sys?.screenHeight === 'number' ? sys.screenHeight : undefined;
1735
- out.mpPixelRatio = typeof sys?.pixelRatio === 'number' ? sys.pixelRatio : undefined;
1736
- out.language = sys?.language ? String(sys.language) : '';
2549
+ const pages = typeof g.getCurrentPages === 'function' ? g.getCurrentPages() : [];
2550
+ const last = Array.isArray(pages) ? pages[pages.length - 1] : undefined;
2551
+ const route = (last?.route || last?.__route__);
2552
+ if (typeof route !== 'string')
2553
+ return '';
2554
+ let path = route.startsWith('/') ? route : `/${route}`;
2555
+ const options = last?.options || {};
2556
+ const keys = Object.keys(options);
2557
+ if (keys.length > 0) {
2558
+ const qs = keys.map((k) => `${k}=${options[k]}`).join('&');
2559
+ path = `${path}?${qs}`;
2560
+ }
2561
+ return path;
1737
2562
  }
1738
2563
  catch {
1739
- // ignore
1740
- }
1741
- if (options.includeNetworkType) {
1742
- try {
1743
- if (typeof wxAny.getNetworkTypeSync === 'function') {
1744
- const n = wxAny.getNetworkTypeSync();
1745
- out.networkType = n?.networkType ? String(n.networkType) : '';
1746
- }
1747
- else if (typeof wxAny.getNetworkType === 'function') {
1748
- // 异步更新:先不阻塞初始化
1749
- wxAny.getNetworkType({
1750
- success: (res) => {
1751
- try {
1752
- const g = globalThis;
1753
- if (!g.__beLinkClsLoggerDeviceInfo__)
1754
- g.__beLinkClsLoggerDeviceInfo__ = {};
1755
- g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
1756
- }
1757
- catch {
1758
- // ignore
1759
- }
1760
- },
1761
- });
1762
- }
1763
- }
1764
- catch {
1765
- // ignore
1766
- }
1767
- try {
1768
- if (typeof wxAny.onNetworkStatusChange === 'function') {
1769
- wxAny.onNetworkStatusChange((res) => {
1770
- try {
1771
- const g = globalThis;
1772
- if (!g.__beLinkClsLoggerDeviceInfo__)
1773
- g.__beLinkClsLoggerDeviceInfo__ = {};
1774
- g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
1775
- }
1776
- catch {
1777
- // ignore
1778
- }
1779
- });
1780
- }
1781
- }
1782
- catch {
1783
- // ignore
1784
- }
2564
+ return '';
1785
2565
  }
1786
- return out;
1787
2566
  }
1788
- function createAutoDeviceInfoBaseFields(envType, opts) {
1789
- const enabled = opts === undefined ? true : !!opts;
1790
- if (!enabled)
1791
- return null;
1792
- const raw = typeof opts === 'object' && opts ? opts : {};
1793
- const options = {
1794
- includeUserAgent: raw.includeUserAgent ?? true,
1795
- includeNetwork: raw.includeNetwork ?? true,
1796
- includeNetworkType: raw.includeNetworkType ?? true,
2567
+ function buildCommonUvFields(uvId, uvMeta, isFirstVisit) {
2568
+ return {
2569
+ uvId,
2570
+ isFirstVisit,
2571
+ firstVisitTs: uvMeta.firstVisitTs,
2572
+ visitCount: uvMeta.visitCount,
1797
2573
  };
1798
- // 缓存:设备信息通常不频繁变化;网络类型可能异步更新,使用全局对象增量写入
1799
- let base = null;
1800
- const globalKey = '__beLinkClsLoggerDeviceInfo__';
1801
- return () => {
1802
- if (!base) {
1803
- base =
1804
- envType === 'miniprogram' || isMiniProgramEnv()
1805
- ? getMiniProgramDeviceInfo(options)
1806
- : getBrowserDeviceInfo(options);
2574
+ }
2575
+ function truncateText(s, maxLen) {
2576
+ if (!s)
2577
+ return '';
2578
+ if (s.length <= maxLen)
2579
+ return s;
2580
+ return s.slice(0, maxLen);
2581
+ }
2582
+ function installMiniBehaviorMonitor(report, options = {}) {
2583
+ const enableTrack = options.enableTrack ?? options.enabled ?? true;
2584
+ if (!enableTrack)
2585
+ return () => { };
2586
+ const pvEnabled = options.pv ?? true;
2587
+ const uvEnabled = options.uv ?? true;
2588
+ const clickEnabled = options.click ?? true;
2589
+ const pvReportType = options.pvReportType ?? 'pv';
2590
+ const uvReportType = options.uvReportType ?? 'uv';
2591
+ const clickReportType = options.clickReportType ?? 'click';
2592
+ const uvIdStorageKey = options.uvIdStorageKey ?? 'cls_uv_id';
2593
+ const uvMetaStorageKey = options.uvMetaStorageKey ?? 'cls_uv_meta';
2594
+ const lastPagePathStorageKey = options.lastPagePathStorageKey ?? 'cls_last_page_path';
2595
+ const uvExpireDaysRaw = options.trackOptions?.uvExpireDays ?? options.uvExpireDays ?? 30;
2596
+ const uvExpireDays = Number.isFinite(uvExpireDaysRaw) ? Math.max(0, uvExpireDaysRaw) : 30;
2597
+ const uvExpireMs = uvExpireDays * 24 * 60 * 60 * 1000;
2598
+ const clickWhiteList = (options.trackOptions?.clickWhiteList ??
2599
+ options.clickWhiteList ?? ['view', 'scroll-view']).map((s) => String(s).toLowerCase());
2600
+ const clickMaxTextLength = options.clickMaxTextLength ?? 120;
2601
+ const getPagePath = options.getPagePath ?? getMiniProgramPagePath;
2602
+ let destroyed = false;
2603
+ let firstVisitFlag = false;
2604
+ let firstVisitConsumed = false;
2605
+ const uvStatePromise = (async () => {
2606
+ let existingUvId = readStringStorage(uvIdStorageKey);
2607
+ let isFirstVisit = false;
2608
+ const now = Date.now();
2609
+ const metaBefore = safeReadUvMeta(uvMetaStorageKey);
2610
+ const lastSeenForExpire = metaBefore.lastSeenTs ?? metaBefore.createdAtTs ?? metaBefore.firstVisitTs ?? now;
2611
+ const expired = uvExpireMs > 0 && now - lastSeenForExpire > uvExpireMs;
2612
+ if (expired) {
2613
+ existingUvId = null;
2614
+ writeUvMeta(uvMetaStorageKey, { firstVisitTs: now, visitCount: 0, createdAtTs: now, lastSeenTs: now });
2615
+ writeStringStorage(uvIdStorageKey, '');
2616
+ }
2617
+ try {
2618
+ if (options.getUvId) {
2619
+ const maybe = options.getUvId();
2620
+ const resolved = typeof maybe?.then === 'function' ? await maybe : maybe;
2621
+ if (resolved && typeof resolved === 'string')
2622
+ existingUvId = resolved;
2623
+ }
2624
+ }
2625
+ catch {
2626
+ /* ignore */
2627
+ }
2628
+ if (!existingUvId) {
2629
+ const wxAny = globalThis.wx;
1807
2630
  try {
1808
- const g = globalThis;
1809
- if (!g[globalKey])
1810
- g[globalKey] = { ...base };
2631
+ const userInfo = wxAny?.getStorageSync?.('userInfo');
2632
+ if (userInfo?.openid)
2633
+ existingUvId = String(userInfo.openid);
1811
2634
  }
1812
2635
  catch {
1813
- // ignore
2636
+ /* ignore */
2637
+ }
2638
+ if (!existingUvId) {
2639
+ try {
2640
+ const sys = wxAny?.getSystemInfoSync?.();
2641
+ const deviceId = sys?.deviceId ? String(sys.deviceId) : '';
2642
+ const model = sys?.model ? String(sys.model) : '';
2643
+ const system = sys?.system ? String(sys.system) : '';
2644
+ const base = [deviceId || model, system].filter(Boolean).join('_');
2645
+ if (base)
2646
+ existingUvId = `${base}_${Date.now()}`;
2647
+ }
2648
+ catch {
2649
+ /* ignore */
2650
+ }
1814
2651
  }
1815
2652
  }
1816
- try {
1817
- const g = globalThis;
1818
- const extra = g[globalKey];
1819
- if (extra && isPlainObject(extra))
1820
- return { ...base, ...extra };
2653
+ if (!existingUvId) {
2654
+ existingUvId = generateUUID();
2655
+ isFirstVisit = true;
1821
2656
  }
1822
- catch {
1823
- // ignore
2657
+ writeStringStorage(uvIdStorageKey, existingUvId);
2658
+ const meta = safeReadUvMeta(uvMetaStorageKey);
2659
+ const createdAt = meta.createdAtTs ?? meta.firstVisitTs ?? now;
2660
+ const firstVisit = meta.firstVisitTs || now;
2661
+ const nextMeta = {
2662
+ firstVisitTs: firstVisit,
2663
+ visitCount: (meta.visitCount || 0) + 1,
2664
+ createdAtTs: createdAt,
2665
+ lastSeenTs: now,
2666
+ };
2667
+ if (isFirstVisit) {
2668
+ nextMeta.firstVisitTs = now;
2669
+ nextMeta.createdAtTs = now;
1824
2670
  }
1825
- return base;
1826
- };
1827
- }
1828
-
1829
- function enterClsSendingGuard() {
2671
+ writeUvMeta(uvMetaStorageKey, nextMeta);
2672
+ firstVisitFlag = isFirstVisit;
2673
+ return { uvId: existingUvId, isFirstVisit, meta: nextMeta };
2674
+ })();
2675
+ function safeReport(type, data) {
2676
+ if (destroyed)
2677
+ return;
2678
+ if (!shouldSample(options.sampleRate))
2679
+ return;
2680
+ report(type, data);
2681
+ }
2682
+ function buildUvFieldsOnce(uvId, meta) {
2683
+ const once = firstVisitFlag && !firstVisitConsumed;
2684
+ if (once)
2685
+ firstVisitConsumed = true;
2686
+ return buildCommonUvFields(uvId, meta, once);
2687
+ }
2688
+ function reportPv(pagePath) {
2689
+ if (!pvEnabled)
2690
+ return;
2691
+ void uvStatePromise.then(({ uvId, meta }) => {
2692
+ if (destroyed)
2693
+ return;
2694
+ const payload = {
2695
+ ...buildUvFieldsOnce(uvId, meta),
2696
+ timestamp: Date.now(),
2697
+ pagePath,
2698
+ referrer: readStringStorage(lastPagePathStorageKey) || '',
2699
+ };
2700
+ writeStringStorage(lastPagePathStorageKey, pagePath);
2701
+ safeReport(pvReportType, payload);
2702
+ });
2703
+ }
2704
+ // MiniProgram Page Patch
2705
+ let restoreMiniProgramPatch = null;
1830
2706
  const g = globalThis;
1831
- const next = (g.__beLinkClsLoggerSendingCount__ ?? 0) + 1;
1832
- g.__beLinkClsLoggerSendingCount__ = next;
2707
+ const patchedKey = '__beLinkClsLoggerBehaviorPatched__';
2708
+ if (!g[patchedKey]) {
2709
+ g[patchedKey] = true;
2710
+ const originalPage = typeof g.Page === 'function' ? g.Page : null;
2711
+ if (originalPage) {
2712
+ g.Page = function patchedPage(conf) {
2713
+ const originalOnShow = conf?.onShow;
2714
+ conf.onShow = function (...args) {
2715
+ if (pvEnabled) {
2716
+ const pagePath = getPagePath();
2717
+ if (pagePath?.length > 0)
2718
+ reportPv(pagePath);
2719
+ }
2720
+ return typeof originalOnShow === 'function' ? originalOnShow.apply(this, args) : undefined;
2721
+ };
2722
+ if (clickEnabled && conf && typeof conf === 'object') {
2723
+ for (const key of Object.keys(conf)) {
2724
+ const fn = conf[key];
2725
+ if (typeof fn !== 'function')
2726
+ continue;
2727
+ if (fn.__beLinkWrapped__)
2728
+ continue;
2729
+ conf[key] = function (...args) {
2730
+ try {
2731
+ const e = args?.[0];
2732
+ const type = e?.type;
2733
+ const currentTarget = e?.currentTarget;
2734
+ const dataset = currentTarget?.dataset;
2735
+ const isTap = type === 'tap' || type === 'click';
2736
+ if (isTap && currentTarget && dataset) {
2737
+ const tagNameRaw = dataset?.tagName ?? dataset?.tag ?? currentTarget?.tagName ?? '';
2738
+ const tagName = String(tagNameRaw || '').toLowerCase();
2739
+ const trackId = dataset?.trackId ? String(dataset.trackId) : '';
2740
+ if (!(clickWhiteList.includes(tagName) && !trackId)) {
2741
+ const x = typeof e?.detail?.x === 'number' ? e.detail.x : (e?.touches?.[0]?.pageX ?? 0);
2742
+ const y = typeof e?.detail?.y === 'number' ? e.detail.y : (e?.touches?.[0]?.pageY ?? 0);
2743
+ void uvStatePromise.then(({ uvId, meta }) => {
2744
+ if (destroyed)
2745
+ return;
2746
+ safeReport(clickReportType, {
2747
+ ...buildUvFieldsOnce(uvId, meta),
2748
+ timestamp: Date.now(),
2749
+ pagePath: getPagePath(),
2750
+ elementTag: tagNameRaw ? String(tagNameRaw) : '',
2751
+ elementId: currentTarget?.id ? String(currentTarget.id) : '',
2752
+ elementClass: dataset?.className ? stringifyLogValue(dataset.className) : '',
2753
+ trackId,
2754
+ elementText: dataset?.text ? truncateText(String(dataset.text), clickMaxTextLength) : '',
2755
+ clickX: x,
2756
+ clickY: y,
2757
+ });
2758
+ });
2759
+ }
2760
+ }
2761
+ }
2762
+ catch {
2763
+ /* ignore */
2764
+ }
2765
+ return fn.apply(this, args);
2766
+ };
2767
+ conf[key].__beLinkWrapped__ = true;
2768
+ }
2769
+ }
2770
+ return originalPage(conf);
2771
+ };
2772
+ restoreMiniProgramPatch = () => {
2773
+ g.Page = originalPage;
2774
+ g[patchedKey] = false;
2775
+ };
2776
+ }
2777
+ }
2778
+ if (pvEnabled)
2779
+ reportPv(getPagePath());
2780
+ if (uvEnabled) {
2781
+ void uvStatePromise.then(({ uvId, meta }) => {
2782
+ if (destroyed)
2783
+ return;
2784
+ safeReport(uvReportType, {
2785
+ ...buildUvFieldsOnce(uvId, meta),
2786
+ timestamp: Date.now(),
2787
+ pagePath: getPagePath(),
2788
+ });
2789
+ });
2790
+ }
1833
2791
  return () => {
1834
- const cur = g.__beLinkClsLoggerSendingCount__ ?? 0;
1835
- g.__beLinkClsLoggerSendingCount__ = cur > 0 ? cur - 1 : 0;
2792
+ destroyed = true;
2793
+ restoreMiniProgramPatch?.();
1836
2794
  };
1837
2795
  }
1838
- class ClsLogger {
1839
- constructor() {
1840
- this.client = null;
1841
- this.topicId = null;
1842
- this.endpoint = 'ap-shanghai.cls.tencentcs.com';
1843
- this.retryTimes = 10;
1844
- this.source = '127.0.0.1';
1845
- this.projectId = '';
1846
- this.projectName = '';
1847
- this.appId = '';
1848
- this.appVersion = '';
1849
- this.envType = 'browser';
1850
- this.userGenerateBaseFields = null;
1851
- this.autoGenerateBaseFields = null;
1852
- this.storageKey = 'beLink_logs';
1853
- this.batchSize = 15;
1854
- // 参考文档:内存队列批量发送(500ms 或 20 条触发)
1855
- this.memoryQueue = [];
1856
- this.batchMaxSize = 20;
1857
- this.batchIntervalMs = 500;
1858
- this.batchTimer = null;
1859
- this.batchTimerDueAt = null;
1860
- this.initTs = 0;
1861
- this.startupDelayMs = 0;
1862
- // 参考文档:失败缓存 + 重试
1863
- this.failedCacheKey = 'cls_failed_logs';
1864
- this.failedCacheMax = 200;
1865
- this.requestMonitorStarted = false;
1866
- this.errorMonitorStarted = false;
1867
- this.performanceMonitorStarted = false;
1868
- this.behaviorMonitorStarted = false;
1869
- this.behaviorMonitorCleanup = null;
2796
+
2797
+ function installBehaviorMonitor(report, envType, options = {}) {
2798
+ if (envType === 'miniprogram' || isMiniProgramEnv()) {
2799
+ return installMiniBehaviorMonitor(report, options);
1870
2800
  }
1871
- init(options) {
1872
- this.initTs = Date.now();
1873
- const topicId = options?.tencentCloud?.topicID ?? options?.topic_id ?? options?.topicID ?? this.topicId ?? null;
1874
- const endpoint = options?.tencentCloud?.endpoint ?? options?.endpoint ?? this.endpoint;
1875
- const retryTimes = options?.tencentCloud?.retry_times ?? options?.retry_times ?? this.retryTimes;
1876
- const source = options?.tencentCloud?.source ?? options?.source ?? this.source;
1877
- if (!topicId) {
1878
- // eslint-disable-next-line no-console
1879
- console.warn('ClsLogger.init 没有传 topicID/topic_id');
1880
- return;
1881
- }
1882
- this.topicId = topicId;
1883
- this.endpoint = endpoint;
1884
- this.retryTimes = retryTimes;
1885
- this.source = source;
1886
- this.userId = options.userId ?? this.userId;
1887
- this.userName = options.userName ?? this.userName;
1888
- this.projectId = options.projectId ?? this.projectId;
1889
- this.projectName = options.projectName ?? this.projectName;
1890
- this.appId = options.appId ?? this.appId;
1891
- this.appVersion = options.appVersion ?? this.appVersion;
1892
- this.envType = options.envType ?? this.detectEnvType();
1893
- this.userGenerateBaseFields = options.generateBaseFields ?? this.userGenerateBaseFields;
1894
- this.autoGenerateBaseFields = createAutoDeviceInfoBaseFields(this.envType, options.deviceInfo);
1895
- this.storageKey = options.storageKey ?? this.storageKey;
1896
- this.batchSize = options.batchSize ?? this.batchSize;
1897
- this.batchMaxSize = options.batch?.maxSize ?? this.batchMaxSize;
1898
- this.batchIntervalMs = options.batch?.intervalMs ?? this.batchIntervalMs;
1899
- this.startupDelayMs = options.batch?.startupDelayMs ?? this.startupDelayMs;
1900
- this.failedCacheKey = options.failedCacheKey ?? this.failedCacheKey;
1901
- this.failedCacheMax = options.failedCacheMax ?? this.failedCacheMax;
1902
- // 预热 client
1903
- this.getInstance();
1904
- // 启动时尝试发送失败缓存
1905
- this.flushFailed();
1906
- // 初始化后立即启动请求监听
1907
- this.startRequestMonitor(options.requestMonitor);
1908
- // 初始化后立即启动错误监控/性能监控
1909
- this.startErrorMonitor(options.errorMonitor);
1910
- this.startPerformanceMonitor(options.performanceMonitor);
1911
- // 初始化后立即启动行为埋点(PV/UV/点击)
1912
- this.startBehaviorMonitor(options.behaviorMonitor);
2801
+ return installWebBehaviorMonitor(report, options);
2802
+ }
2803
+
2804
+ function truncate(s, maxLen) {
2805
+ if (!s)
2806
+ return s;
2807
+ return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
2808
+ }
2809
+ function parseUserAgent(uaRaw) {
2810
+ const ua = uaRaw ?? '';
2811
+ const isMobile = /Mobile|Android|iPhone|iPad|iPod/i.test(ua);
2812
+ // OS
2813
+ let osName = 'unknown';
2814
+ let osVersion = '';
2815
+ const ios = ua.match(/OS (\d+[_\d]*) like Mac OS X/i);
2816
+ const android = ua.match(/Android (\d+(\.\d+)*)/i);
2817
+ const mac = ua.match(/Mac OS X (\d+[_\d]*)/i);
2818
+ const win = ua.match(/Windows NT (\d+(\.\d+)*)/i);
2819
+ if (ios) {
2820
+ osName = 'iOS';
2821
+ osVersion = ios[1].replace(/_/g, '.');
1913
2822
  }
1914
- getBaseFields() {
1915
- let auto = undefined;
1916
- let user = undefined;
1917
- try {
1918
- const autoRaw = this.autoGenerateBaseFields ? this.autoGenerateBaseFields() : undefined;
1919
- if (autoRaw && isPlainObject(autoRaw))
1920
- auto = normalizeFlatFields(autoRaw, 'deviceInfo');
1921
- }
1922
- catch {
1923
- auto = undefined;
1924
- }
1925
- try {
1926
- const userRaw = this.userGenerateBaseFields ? this.userGenerateBaseFields() : undefined;
1927
- if (userRaw && isPlainObject(userRaw))
1928
- user = normalizeFlatFields({ ...userRaw, userId: this.userId, userName: this.userName }, 'generateBaseFields');
1929
- }
1930
- catch {
1931
- user = undefined;
1932
- }
1933
- if (auto && user)
1934
- return mergeFields(user, auto);
1935
- if (user)
1936
- return user;
1937
- if (auto)
1938
- return auto;
1939
- return undefined;
2823
+ else if (android) {
2824
+ osName = 'Android';
2825
+ osVersion = android[1];
1940
2826
  }
1941
- startRequestMonitor(requestMonitor) {
1942
- if (this.requestMonitorStarted)
1943
- return;
1944
- // 默认开启;传 false 则关闭
1945
- const enabled = requestMonitor === undefined ? true : !!requestMonitor;
1946
- if (!enabled)
1947
- return;
1948
- const opts = typeof requestMonitor === 'object' && requestMonitor ? requestMonitor : {};
1949
- this.requestMonitorStarted = true;
1950
- installRequestMonitor((type, data) => {
1951
- this.track(type, data);
1952
- }, {
1953
- ...opts,
1954
- enabled: opts.enabled ?? true,
1955
- clsEndpoint: this.endpoint,
1956
- });
2827
+ else if (win) {
2828
+ osName = 'Windows';
2829
+ osVersion = win[1];
2830
+ }
2831
+ else if (mac) {
2832
+ osName = 'macOS';
2833
+ osVersion = mac[1].replace(/_/g, '.');
2834
+ }
2835
+ // Browser
2836
+ let browserName = 'unknown';
2837
+ let browserVersion = '';
2838
+ const edge = ua.match(/Edg\/(\d+(\.\d+)*)/);
2839
+ const chrome = ua.match(/Chrome\/(\d+(\.\d+)*)/);
2840
+ const safari = ua.match(/Version\/(\d+(\.\d+)*) Safari\//);
2841
+ const firefox = ua.match(/Firefox\/(\d+(\.\d+)*)/);
2842
+ if (edge) {
2843
+ browserName = 'Edge';
2844
+ browserVersion = edge[1];
1957
2845
  }
1958
- startErrorMonitor(errorMonitor) {
1959
- if (this.errorMonitorStarted)
1960
- return;
1961
- const enabled = errorMonitor === undefined ? true : !!errorMonitor;
1962
- if (!enabled)
1963
- return;
1964
- this.errorMonitorStarted = true;
1965
- installErrorMonitor((type, data) => this.track(type, data), errorMonitor);
2846
+ else if (chrome) {
2847
+ browserName = 'Chrome';
2848
+ browserVersion = chrome[1];
1966
2849
  }
1967
- startPerformanceMonitor(performanceMonitor) {
1968
- if (this.performanceMonitorStarted)
1969
- return;
1970
- const enabled = performanceMonitor === undefined ? true : !!performanceMonitor;
1971
- if (!enabled)
1972
- return;
1973
- this.performanceMonitorStarted = true;
1974
- installPerformanceMonitor((type, data) => this.track(type, data), performanceMonitor);
2850
+ else if (firefox) {
2851
+ browserName = 'Firefox';
2852
+ browserVersion = firefox[1];
1975
2853
  }
1976
- startBehaviorMonitor(behaviorMonitor) {
1977
- if (this.behaviorMonitorStarted)
1978
- return;
1979
- const enabled = behaviorMonitor === undefined ? true : !!behaviorMonitor;
1980
- if (!enabled)
1981
- return;
1982
- const opts = typeof behaviorMonitor === 'object' && behaviorMonitor
1983
- ? behaviorMonitor
1984
- : {};
1985
- this.behaviorMonitorStarted = true;
1986
- this.behaviorMonitorCleanup = installBehaviorMonitor((type, data) => {
1987
- this.track(type, data);
1988
- }, this.envType, {
1989
- ...opts,
1990
- enabled: opts.enabled ?? true,
1991
- });
2854
+ else if (safari) {
2855
+ browserName = 'Safari';
2856
+ browserVersion = safari[1];
1992
2857
  }
1993
- /**
1994
- * 停止行为埋点监听(PV/UV/点击)
1995
- * - 如需重启:可再次调用 init(或自行调用 init 后的默认启动逻辑)
1996
- */
1997
- stopBehaviorMonitor() {
1998
- try {
1999
- this.behaviorMonitorCleanup?.();
2000
- }
2001
- catch {
2002
- // ignore
2003
- }
2004
- this.behaviorMonitorCleanup = null;
2005
- this.behaviorMonitorStarted = false;
2858
+ return { browserName, browserVersion, osName, osVersion, isMobile };
2859
+ }
2860
+ function getBrowserDeviceInfo(options) {
2861
+ const out = {
2862
+ envType: 'browser',
2863
+ };
2864
+ if (typeof window === 'undefined' || typeof navigator === 'undefined')
2865
+ return out;
2866
+ const ua = String(navigator.userAgent ?? '');
2867
+ const uaParsed = parseUserAgent(ua);
2868
+ if (options.includeUserAgent)
2869
+ out.ua = truncate(ua, 2000);
2870
+ out.browserName = uaParsed.browserName;
2871
+ out.browserVersion = uaParsed.browserVersion;
2872
+ out.osName = uaParsed.osName;
2873
+ out.osVersion = uaParsed.osVersion;
2874
+ out.isMobile = uaParsed.isMobile ? 1 : 0;
2875
+ out.language = String(navigator.language ?? '');
2876
+ out.platform = String(navigator.platform ?? '');
2877
+ try {
2878
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
2879
+ out.timezone = typeof tz === 'string' ? tz : '';
2006
2880
  }
2007
- getInstance() {
2008
- if (this.client)
2009
- return this.client;
2010
- this.client = new AsyncClient({
2011
- endpoint: this.endpoint,
2012
- retry_times: this.retryTimes,
2013
- });
2014
- return this.client;
2881
+ catch {
2882
+ out.timezone = '';
2015
2883
  }
2016
- detectEnvType() {
2017
- const wxAny = globalThis.wx;
2018
- if (wxAny && typeof wxAny.getSystemInfoSync === 'function')
2019
- return 'miniprogram';
2020
- return 'browser';
2884
+ try {
2885
+ const s = window.screen;
2886
+ out.screenWidth = s?.width ?? undefined;
2887
+ out.screenHeight = s?.height ?? undefined;
2021
2888
  }
2022
- /**
2023
- * 直接上报:埋点入参必须是一维(扁平)Object
2024
- * - 非原始值(对象/数组等)会被自动 stringify 成 string
2025
- * - 最终会把 fields 展开成 CLS 的 content(key/value 都会转成 string)
2026
- */
2027
- put(fields, options = {}) {
2028
- if (!fields)
2029
- return;
2030
- if (!this.topicId) {
2031
- // eslint-disable-next-line no-console
2032
- console.warn('ClsLogger.put:未初始化 topic_id');
2033
- return;
2034
- }
2035
- const mergeBaseFields = options.mergeBaseFields ?? true;
2036
- const base = mergeBaseFields ? this.getBaseFields() : undefined;
2037
- const normalizedFields = normalizeFlatFields(fields, 'put');
2038
- const finalFields = mergeFields(base, {
2039
- projectId: this.projectId || undefined,
2040
- projectName: this.projectName || undefined,
2041
- envType: this.envType,
2042
- appId: this.appId || undefined,
2043
- appVersion: this.appVersion || undefined,
2044
- ...normalizedFields,
2045
- });
2046
- const client = this.getInstance();
2047
- const logGroup = new LogGroup('127.0.0.1');
2048
- logGroup.setSource(this.source);
2049
- const log = new Log(Date.now());
2050
- for (const key of Object.keys(finalFields)) {
2051
- log.addContent(key, stringifyLogValue(finalFields[key]));
2052
- }
2053
- logGroup.addLog(log);
2054
- const request = new PutLogsRequest(this.topicId, logGroup);
2055
- const exit = enterClsSendingGuard();
2056
- try {
2057
- client.PutLogs(request);
2058
- }
2059
- finally {
2060
- exit();
2061
- }
2889
+ catch {
2890
+ // ignore
2062
2891
  }
2063
- /**
2064
- * 直接上报:把 data 序列化后放入指定 key(默认 “日志内容”)
2065
- */
2066
- putJson(data, clsLoggerKey = '日志内容', options = {}) {
2067
- // put 的入参要求扁平;这里直接把数据序列化为 string
2068
- this.put({ [clsLoggerKey]: stringifyLogValue(data) }, options);
2892
+ try {
2893
+ out.dpr = typeof window.devicePixelRatio === 'number' ? window.devicePixelRatio : undefined;
2069
2894
  }
2070
- /**
2071
- * 入队:写入 localStorage 队列;达到 batchSize 自动 flush
2072
- * - 埋点入参必须是一维(扁平)Object,非原始值会被 stringify
2073
- */
2074
- enqueue(fields, options = {}) {
2075
- if (!fields)
2076
- return;
2077
- const time = Date.now();
2078
- const mergeBaseFields = options.mergeBaseFields ?? true;
2079
- const base = mergeBaseFields ? this.getBaseFields() : undefined;
2080
- const normalizedFields = normalizeFlatFields(fields, 'enqueue');
2081
- const finalFields = mergeFields(base, {
2082
- projectId: this.projectId || undefined,
2083
- projectName: this.projectName || undefined,
2084
- envType: this.envType,
2085
- appId: this.appId || undefined,
2086
- appVersion: this.appVersion || undefined,
2087
- ...normalizedFields,
2088
- });
2089
- const queue = readQueue(this.storageKey);
2090
- const next = [...queue, { time, data: finalFields }];
2091
- if (next.length < this.batchSize) {
2092
- writeQueue(this.storageKey, next);
2093
- return;
2094
- }
2095
- // 达到阈值:flush + 写入新的队列(避免并发下丢失,按“先 flush 旧的”策略)
2096
- this.putBatch(queue);
2097
- writeQueue(this.storageKey, [{ time, data: finalFields }]);
2895
+ catch {
2896
+ // ignore
2098
2897
  }
2099
- /**
2100
- * localStorage 读取队列并批量上报
2101
- */
2102
- flush() {
2103
- const queue = readQueue(this.storageKey);
2104
- if (queue.length === 0)
2105
- return;
2106
- this.putBatch(queue);
2107
- writeQueue(this.storageKey, []);
2898
+ try {
2899
+ const navAny = navigator;
2900
+ out.hardwareConcurrency = typeof navAny.hardwareConcurrency === 'number' ? navAny.hardwareConcurrency : undefined;
2901
+ out.deviceMemory = typeof navAny.deviceMemory === 'number' ? navAny.deviceMemory : undefined;
2108
2902
  }
2109
- /**
2110
- * 批量上报(每条 item.data 展开为 log content)
2111
- */
2112
- putBatch(queue) {
2113
- if (!queue || queue.length === 0)
2114
- return;
2115
- if (!this.topicId) {
2116
- // eslint-disable-next-line no-console
2117
- console.warn('ClsLogger.putBatch:未初始化 topic_id');
2118
- return;
2119
- }
2120
- const client = this.getInstance();
2121
- const logGroup = new LogGroup('127.0.0.1');
2122
- logGroup.setSource(this.source);
2123
- for (const item of queue) {
2124
- const log = new Log(item.time);
2125
- const data = item.data ?? {};
2126
- for (const key of Object.keys(data)) {
2127
- log.addContent(key, stringifyLogValue(data[key]));
2128
- }
2129
- logGroup.addLog(log);
2130
- }
2131
- if (logGroup.getLogs().length === 0)
2132
- return;
2133
- const request = new PutLogsRequest(this.topicId, logGroup);
2134
- const exit = enterClsSendingGuard();
2903
+ catch {
2904
+ // ignore
2905
+ }
2906
+ if (options.includeNetwork) {
2135
2907
  try {
2136
- client.PutLogs(request);
2908
+ const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
2909
+ if (conn && isPlainObject(conn)) {
2910
+ if (typeof conn.effectiveType === 'string')
2911
+ out.netEffectiveType = conn.effectiveType;
2912
+ if (typeof conn.downlink === 'number')
2913
+ out.netDownlink = conn.downlink;
2914
+ if (typeof conn.rtt === 'number')
2915
+ out.netRtt = conn.rtt;
2916
+ if (typeof conn.saveData === 'boolean')
2917
+ out.netSaveData = conn.saveData ? 1 : 0;
2918
+ }
2137
2919
  }
2138
- finally {
2139
- exit();
2920
+ catch {
2921
+ // ignore
2140
2922
  }
2141
2923
  }
2142
- /**
2143
- * 参考《一、概述》:统一上报入口(内存队列 + 批量发送)
2144
- */
2145
- report(log) {
2146
- if (!log?.type)
2147
- return;
2148
- if (!this.topicId) {
2149
- // eslint-disable-next-line no-console
2150
- console.warn('ClsLogger.report:未初始化 topicID/topic_id');
2151
- return;
2152
- }
2153
- this.memoryQueue.push(log);
2154
- if (this.memoryQueue.length >= this.batchMaxSize) {
2155
- void this.flushBatch();
2156
- return;
2157
- }
2158
- const now = Date.now();
2159
- const desiredDueAt = this.getDesiredBatchFlushDueAt(now);
2160
- const desiredDelay = Math.max(0, desiredDueAt - now);
2161
- if (!this.batchTimer) {
2162
- this.batchTimerDueAt = desiredDueAt;
2163
- this.batchTimer = setTimeout(() => {
2164
- void this.flushBatch();
2165
- }, desiredDelay);
2166
- return;
2167
- }
2168
- // 启动合并窗口内:如果当前 timer 会“更早”触发,则延后到窗口结束,尽量减少多次发送
2169
- if (this.batchTimerDueAt !== null && this.batchTimerDueAt < desiredDueAt) {
2924
+ return out;
2925
+ }
2926
+ function createWebDeviceInfoBaseFields(opts) {
2927
+ const enabled = opts === undefined ? true : !!opts;
2928
+ if (!enabled)
2929
+ return null;
2930
+ const raw = typeof opts === 'object' && opts ? opts : {};
2931
+ const options = {
2932
+ includeUserAgent: raw.includeUserAgent ?? true,
2933
+ includeNetwork: raw.includeNetwork ?? true,
2934
+ includeNetworkType: raw.includeNetworkType ?? true,
2935
+ };
2936
+ let base = null;
2937
+ const globalKey = '__beLinkClsLoggerDeviceInfo__';
2938
+ return () => {
2939
+ if (!base) {
2940
+ base = getBrowserDeviceInfo(options);
2170
2941
  try {
2171
- clearTimeout(this.batchTimer);
2942
+ const g = globalThis;
2943
+ if (!g[globalKey])
2944
+ g[globalKey] = { ...base };
2172
2945
  }
2173
2946
  catch {
2174
2947
  // ignore
2175
2948
  }
2176
- this.batchTimerDueAt = desiredDueAt;
2177
- this.batchTimer = setTimeout(() => {
2178
- void this.flushBatch();
2179
- }, desiredDelay);
2180
- }
2181
- }
2182
- getDesiredBatchFlushDueAt(nowTs) {
2183
- const start = this.initTs || nowTs;
2184
- const startupDelay = Number.isFinite(this.startupDelayMs) ? Math.max(0, this.startupDelayMs) : 0;
2185
- if (startupDelay > 0) {
2186
- const end = start + startupDelay;
2187
- if (nowTs < end)
2188
- return end;
2189
- }
2190
- return nowTs + this.batchIntervalMs;
2191
- }
2192
- info(message, data = {}) {
2193
- const payload = normalizeFlatFields({ message, ...data }, 'info');
2194
- this.report({ type: 'info', data: payload, timestamp: Date.now() });
2195
- }
2196
- warn(message, data = {}) {
2197
- const payload = normalizeFlatFields({ message, ...data }, 'warn');
2198
- this.report({ type: 'warn', data: payload, timestamp: Date.now() });
2199
- }
2200
- error(message, data = {}) {
2201
- const payload = normalizeFlatFields({ message, ...data }, 'error');
2202
- this.report({ type: 'error', data: payload, timestamp: Date.now() });
2203
- }
2204
- track(trackType, data = {}) {
2205
- if (!trackType)
2206
- return;
2207
- this.report({
2208
- type: trackType,
2209
- data: normalizeFlatFields(data, `track:${trackType}`),
2210
- timestamp: Date.now(),
2211
- });
2212
- }
2213
- /**
2214
- * 立即发送内存队列
2215
- */
2216
- async flushBatch() {
2217
- if (this.batchTimer) {
2218
- clearTimeout(this.batchTimer);
2219
- this.batchTimer = null;
2220
2949
  }
2221
- this.batchTimerDueAt = null;
2222
- if (this.memoryQueue.length === 0)
2223
- return;
2224
- const logs = [...this.memoryQueue];
2225
- this.memoryQueue = [];
2226
2950
  try {
2227
- await this.sendReportLogs(logs);
2951
+ const g = globalThis;
2952
+ const extra = g[globalKey];
2953
+ if (extra && isPlainObject(extra))
2954
+ return { ...base, ...extra };
2228
2955
  }
2229
2956
  catch {
2230
- this.retrySendReportLogs(logs, 1);
2957
+ // ignore
2231
2958
  }
2959
+ return base;
2960
+ };
2961
+ }
2962
+
2963
+ function getMiniProgramDeviceInfo(options) {
2964
+ const out = {
2965
+ envType: 'miniprogram',
2966
+ };
2967
+ const wxAny = globalThis.wx;
2968
+ if (!wxAny || typeof wxAny.getSystemInfoSync !== 'function')
2969
+ return out;
2970
+ try {
2971
+ const sys = wxAny.getSystemInfoSync();
2972
+ out.mpBrand = sys?.brand ? String(sys.brand) : '';
2973
+ out.mpModel = sys?.model ? String(sys.model) : '';
2974
+ out.mpSystem = sys?.system ? String(sys.system) : '';
2975
+ out.mpPlatform = sys?.platform ? String(sys.platform) : '';
2976
+ out.mpWeChatVersion = sys?.version ? String(sys.version) : '';
2977
+ out.mpSDKVersion = sys?.SDKVersion ? String(sys.SDKVersion) : '';
2978
+ out.mpScreenWidth = typeof sys?.screenWidth === 'number' ? sys.screenWidth : undefined;
2979
+ out.mpScreenHeight = typeof sys?.screenHeight === 'number' ? sys.screenHeight : undefined;
2980
+ out.mpPixelRatio = typeof sys?.pixelRatio === 'number' ? sys.pixelRatio : undefined;
2981
+ out.language = sys?.language ? String(sys.language) : '';
2232
2982
  }
2233
- buildReportFields(log) {
2234
- const ts = log.timestamp ?? Date.now();
2235
- const base = this.getBaseFields();
2236
- const data = normalizeFlatFields(log.data ?? {}, 'report:data');
2237
- const mergedData = mergeFields(base, data);
2238
- return {
2239
- timestamp: ts,
2240
- type: log.type,
2241
- envType: this.envType,
2242
- projectId: this.projectId || undefined,
2243
- projectName: this.projectName || undefined,
2244
- appId: this.appId || undefined,
2245
- appVersion: this.appVersion || undefined,
2246
- // 保证“一维字段”:业务数据以 JSON 字符串形式落到 CLS
2247
- ...mergedData,
2248
- };
2983
+ catch {
2984
+ // ignore
2249
2985
  }
2250
- async sendReportLogs(logs) {
2251
- if (!this.topicId)
2252
- return;
2253
- const client = this.getInstance();
2254
- const logGroup = new LogGroup('127.0.0.1');
2255
- logGroup.setSource(this.source);
2256
- for (const item of logs) {
2257
- const fields = this.buildReportFields(item);
2258
- const log = new Log(fields.timestamp);
2259
- for (const key of Object.keys(fields)) {
2260
- if (key === 'timestamp')
2261
- continue;
2262
- log.addContent(key, stringifyLogValue(fields[key]));
2986
+ if (options.includeNetworkType) {
2987
+ try {
2988
+ if (typeof wxAny.getNetworkTypeSync === 'function') {
2989
+ const n = wxAny.getNetworkTypeSync();
2990
+ out.networkType = n?.networkType ? String(n.networkType) : '';
2991
+ }
2992
+ else if (typeof wxAny.getNetworkType === 'function') {
2993
+ // 异步更新:先不阻塞初始化
2994
+ wxAny.getNetworkType({
2995
+ success: (res) => {
2996
+ try {
2997
+ const g = globalThis;
2998
+ if (!g.__beLinkClsLoggerDeviceInfo__)
2999
+ g.__beLinkClsLoggerDeviceInfo__ = {};
3000
+ g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
3001
+ }
3002
+ catch {
3003
+ // ignore
3004
+ }
3005
+ },
3006
+ });
2263
3007
  }
2264
- logGroup.addLog(log);
2265
3008
  }
2266
- const request = new PutLogsRequest(this.topicId, logGroup);
2267
- // 只在“发起网络请求”的同步阶段打标记,避免 requestMonitor 监控 CLS 上报请求导致递归
2268
- const exit = enterClsSendingGuard();
2269
- let p;
3009
+ catch {
3010
+ // ignore
3011
+ }
2270
3012
  try {
2271
- p = client.PutLogs(request);
3013
+ if (typeof wxAny.onNetworkStatusChange === 'function') {
3014
+ wxAny.onNetworkStatusChange((res) => {
3015
+ try {
3016
+ const g = globalThis;
3017
+ if (!g.__beLinkClsLoggerDeviceInfo__)
3018
+ g.__beLinkClsLoggerDeviceInfo__ = {};
3019
+ g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
3020
+ }
3021
+ catch {
3022
+ // ignore
3023
+ }
3024
+ });
3025
+ }
2272
3026
  }
2273
- finally {
2274
- exit();
3027
+ catch {
3028
+ // ignore
2275
3029
  }
2276
- await p;
2277
3030
  }
2278
- retrySendReportLogs(logs, retryCount) {
2279
- if (retryCount > this.retryTimes) {
2280
- this.cacheFailedReportLogs(logs);
2281
- return;
2282
- }
2283
- const delayMs = Math.pow(2, retryCount) * 1000;
2284
- setTimeout(async () => {
3031
+ return out;
3032
+ }
3033
+ function createMiniDeviceInfoBaseFields(opts) {
3034
+ const enabled = opts === undefined ? true : !!opts;
3035
+ if (!enabled)
3036
+ return null;
3037
+ const raw = typeof opts === 'object' && opts ? opts : {};
3038
+ const options = {
3039
+ includeUserAgent: raw.includeUserAgent ?? true,
3040
+ includeNetwork: raw.includeNetwork ?? true,
3041
+ includeNetworkType: raw.includeNetworkType ?? true,
3042
+ };
3043
+ let base = null;
3044
+ const globalKey = '__beLinkClsLoggerDeviceInfo__';
3045
+ return () => {
3046
+ if (!base) {
3047
+ base = getMiniProgramDeviceInfo(options);
2285
3048
  try {
2286
- await this.sendReportLogs(logs);
3049
+ const g = globalThis;
3050
+ if (!g[globalKey])
3051
+ g[globalKey] = { ...base };
2287
3052
  }
2288
3053
  catch {
2289
- this.retrySendReportLogs(logs, retryCount + 1);
3054
+ // ignore
2290
3055
  }
2291
- }, delayMs);
2292
- }
2293
- cacheFailedReportLogs(logs) {
2294
- const raw = readStringStorage(this.failedCacheKey);
2295
- let current = [];
3056
+ }
2296
3057
  try {
2297
- const parsed = raw ? JSON.parse(raw) : [];
2298
- current = Array.isArray(parsed) ? parsed : [];
3058
+ const g = globalThis;
3059
+ const extra = g[globalKey];
3060
+ if (extra && isPlainObject(extra))
3061
+ return { ...base, ...extra };
2299
3062
  }
2300
3063
  catch {
2301
- current = [];
3064
+ // ignore
2302
3065
  }
2303
- const next = [...current, ...logs].slice(-this.failedCacheMax);
2304
- writeStringStorage(this.failedCacheKey, JSON.stringify(next));
3066
+ return base;
3067
+ };
3068
+ }
3069
+
3070
+ function createAutoDeviceInfoBaseFields(envType, opts) {
3071
+ if (envType === 'miniprogram' || isMiniProgramEnv()) {
3072
+ return createMiniDeviceInfoBaseFields(opts);
2305
3073
  }
2306
- flushFailed() {
2307
- const raw = readStringStorage(this.failedCacheKey);
2308
- if (!raw)
2309
- return;
2310
- let logs = [];
3074
+ return createWebDeviceInfoBaseFields(opts);
3075
+ }
3076
+
3077
+ /**
3078
+ * 兼容版 ClsLogger(默认入口)
3079
+ * - 保留了自动识别环境 + 动态 import 的逻辑
3080
+ * - 如果业务想瘦身,建议改用 @be-link/cls-logger/web 或 /mini
3081
+ */
3082
+ class ClsLogger extends ClsLoggerCore {
3083
+ async loadSdk() {
3084
+ if (this.sdk)
3085
+ return this.sdk;
3086
+ if (this.sdkPromise)
3087
+ return this.sdkPromise;
3088
+ const normalizeSdk = (m) => {
3089
+ const mod = (m?.default && m.default.AsyncClient ? m.default : m);
3090
+ if (mod?.AsyncClient && mod?.Log && mod?.LogGroup && mod?.PutLogsRequest) {
3091
+ return {
3092
+ AsyncClient: mod.AsyncClient,
3093
+ Log: mod.Log,
3094
+ LogGroup: mod.LogGroup,
3095
+ PutLogsRequest: mod.PutLogsRequest,
3096
+ };
3097
+ }
3098
+ return null;
3099
+ };
3100
+ // 1) 外部注入的 loader(最高优先级)
3101
+ if (this.sdkLoaderOverride) {
3102
+ try {
3103
+ const loaded = await this.sdkLoaderOverride();
3104
+ const sdk = normalizeSdk(loaded);
3105
+ if (sdk) {
3106
+ this.sdk = sdk;
3107
+ return sdk;
3108
+ }
3109
+ }
3110
+ catch {
3111
+ // ignore and fallback
3112
+ }
3113
+ }
3114
+ // 2) 外部直接注入的 sdk
3115
+ if (this.sdkOverride) {
3116
+ const sdk = normalizeSdk(this.sdkOverride);
3117
+ if (sdk) {
3118
+ this.sdk = sdk;
3119
+ return sdk;
3120
+ }
3121
+ }
3122
+ const isMini = this.envType === 'miniprogram';
3123
+ // 3) 尝试使用 tryRequire / 全局变量
3124
+ if (isMini) {
3125
+ const reqMod = tryRequire('tencentcloud-cls-sdk-js-mini');
3126
+ const reqSdk = normalizeSdk(reqMod);
3127
+ if (reqSdk) {
3128
+ this.sdk = reqSdk;
3129
+ return reqSdk;
3130
+ }
3131
+ }
3132
+ else {
3133
+ // Web: 优先读全局变量 (UMD)
3134
+ const g = readGlobal('tencentcloudClsSdkJsWeb');
3135
+ const sdk = normalizeSdk(g);
3136
+ if (sdk) {
3137
+ this.sdk = sdk;
3138
+ return sdk;
3139
+ }
3140
+ // Web: 尝试 require
3141
+ const reqMod = tryRequire('tencentcloud-cls-sdk-js-web');
3142
+ const reqSdk = normalizeSdk(reqMod);
3143
+ if (reqSdk) {
3144
+ this.sdk = reqSdk;
3145
+ return reqSdk;
3146
+ }
3147
+ }
3148
+ // 4) 动态导入(兜底方案)
3149
+ // 注意:在某些严格的小程序 ESM 环境下,动态 import 可能失效
2311
3150
  try {
2312
- const parsed = JSON.parse(raw);
2313
- logs = Array.isArray(parsed) ? parsed : [];
3151
+ if (isMini) {
3152
+ const m = await import(/* @vite-ignore */ 'tencentcloud-cls-sdk-js-mini');
3153
+ const sdk = normalizeSdk(m);
3154
+ if (sdk) {
3155
+ this.sdk = sdk;
3156
+ return sdk;
3157
+ }
3158
+ }
3159
+ else {
3160
+ const m = await import(/* @vite-ignore */ 'tencentcloud-cls-sdk-js-web');
3161
+ const sdk = normalizeSdk(m);
3162
+ if (sdk) {
3163
+ this.sdk = sdk;
3164
+ return sdk;
3165
+ }
3166
+ }
2314
3167
  }
2315
3168
  catch {
2316
- logs = [];
3169
+ // ignore
2317
3170
  }
2318
- if (logs.length === 0)
2319
- return;
2320
- // 先清空,再尝试发送
2321
- writeStringStorage(this.failedCacheKey, JSON.stringify([]));
2322
- this.memoryQueue.unshift(...logs);
2323
- void this.flushBatch();
3171
+ // 5) 最终失败警告
3172
+ console.warn(`[ClsLogger] SDK "${isMini ? 'tencentcloud-cls-sdk-js-mini' : 'tencentcloud-cls-sdk-js-web'}" not found. Logging will be disabled.`);
3173
+ throw new Error('SDK not found');
2324
3174
  }
2325
- /**
2326
- * 统计/计数类日志:按字段展开上报(若 data 为空默认 1)
2327
- */
2328
- stat(param) {
2329
- if (!param)
2330
- return;
2331
- const payload = normalizeFlatFields({
2332
- pagePath: typeof window !== 'undefined' ? window.location?.pathname : '',
2333
- projectId: this.projectId,
2334
- projectName: this.projectName,
2335
- ...param,
2336
- data: param.data ?? 1,
2337
- }, 'stat');
2338
- this.report({ type: 'stat', data: payload, timestamp: Date.now() });
3175
+ installRequestMonitor(report, options) {
3176
+ installRequestMonitor(report, options);
3177
+ }
3178
+ installErrorMonitor(report, options) {
3179
+ installErrorMonitor(report, options);
3180
+ }
3181
+ installPerformanceMonitor(report, options) {
3182
+ installPerformanceMonitor(report, options);
3183
+ }
3184
+ installBehaviorMonitor(report, options) {
3185
+ return installBehaviorMonitor(report, this.envType, typeof options === 'boolean' ? {} : options);
3186
+ }
3187
+ createDeviceInfoBaseFields(options) {
3188
+ return createAutoDeviceInfoBaseFields(this.envType, options);
2339
3189
  }
2340
3190
  }
2341
3191