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

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