@be-link/cls-logger 1.0.7 → 1.0.9

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 +94 -76
  2. package/dist/ClsLogger.d.ts +6 -0
  3. package/dist/ClsLogger.d.ts.map +1 -1
  4. package/dist/ClsLoggerCore.d.ts +21 -1
  5. package/dist/ClsLoggerCore.d.ts.map +1 -1
  6. package/dist/behaviorMonitor.d.ts.map +1 -1
  7. package/dist/deviceInfo.d.ts.map +1 -1
  8. package/dist/errorMonitor.d.ts.map +1 -1
  9. package/dist/index.esm.js +2485 -2125
  10. package/dist/index.js +2485 -2125
  11. package/dist/index.umd.js +2485 -2125
  12. package/dist/mini/ClsLogger.d.ts +14 -0
  13. package/dist/mini/ClsLogger.d.ts.map +1 -0
  14. package/dist/mini/behaviorMonitor.d.ts +5 -0
  15. package/dist/mini/behaviorMonitor.d.ts.map +1 -0
  16. package/dist/mini/deviceInfo.d.ts +3 -0
  17. package/dist/mini/deviceInfo.d.ts.map +1 -0
  18. package/dist/mini/errorMonitor.d.ts +5 -0
  19. package/dist/mini/errorMonitor.d.ts.map +1 -0
  20. package/dist/mini/performanceMonitor.d.ts +5 -0
  21. package/dist/mini/performanceMonitor.d.ts.map +1 -0
  22. package/dist/mini/requestMonitor.d.ts +9 -0
  23. package/dist/mini/requestMonitor.d.ts.map +1 -0
  24. package/dist/mini.d.ts +1 -1
  25. package/dist/mini.d.ts.map +1 -1
  26. package/dist/mini.esm.js +1481 -2262
  27. package/dist/mini.js +1481 -2281
  28. package/dist/performanceMonitor.d.ts.map +1 -1
  29. package/dist/requestMonitor.d.ts +1 -5
  30. package/dist/requestMonitor.d.ts.map +1 -1
  31. package/dist/types.d.ts +10 -0
  32. package/dist/types.d.ts.map +1 -1
  33. package/dist/web/ClsLogger.d.ts +14 -0
  34. package/dist/web/ClsLogger.d.ts.map +1 -0
  35. package/dist/web/behaviorMonitor.d.ts +5 -0
  36. package/dist/web/behaviorMonitor.d.ts.map +1 -0
  37. package/dist/web/deviceInfo.d.ts +3 -0
  38. package/dist/web/deviceInfo.d.ts.map +1 -0
  39. package/dist/web/errorMonitor.d.ts +5 -0
  40. package/dist/web/errorMonitor.d.ts.map +1 -0
  41. package/dist/web/performanceMonitor.d.ts +5 -0
  42. package/dist/web/performanceMonitor.d.ts.map +1 -0
  43. package/dist/web/requestMonitor.d.ts +5 -0
  44. package/dist/web/requestMonitor.d.ts.map +1 -0
  45. package/dist/web.d.ts +1 -1
  46. package/dist/web.d.ts.map +1 -1
  47. package/dist/web.esm.js +1627 -2193
  48. package/dist/web.js +1624 -2209
  49. package/package.json +10 -14
  50. package/dist/ClsLoggerMini.d.ts +0 -8
  51. package/dist/ClsLoggerMini.d.ts.map +0 -1
  52. package/dist/ClsLoggerWeb.d.ts +0 -8
  53. package/dist/ClsLoggerWeb.d.ts.map +0 -1
package/dist/web.js CHANGED
@@ -2,27 +2,6 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var WebSdk = require('tencentcloud-cls-sdk-js-web');
6
-
7
- function _interopNamespaceDefault(e) {
8
- var n = Object.create(null);
9
- if (e) {
10
- Object.keys(e).forEach(function (k) {
11
- if (k !== 'default') {
12
- var d = Object.getOwnPropertyDescriptor(e, k);
13
- Object.defineProperty(n, k, d.get ? d : {
14
- enumerable: true,
15
- get: function () { return e[k]; }
16
- });
17
- }
18
- });
19
- }
20
- n.default = e;
21
- return Object.freeze(n);
22
- }
23
-
24
- var WebSdk__namespace = /*#__PURE__*/_interopNamespaceDefault(WebSdk);
25
-
26
5
  function isPlainObject(value) {
27
6
  return Object.prototype.toString.call(value) === '[object Object]';
28
7
  }
@@ -156,2388 +135,1789 @@ function stringifyLogValue(v) {
156
135
  }
157
136
  }
158
137
 
159
- const DEFAULT_IGNORE$1 = ['cls.tencentcs.com', /\/cls\//i];
160
- function isClsSendingNow() {
138
+ function enterClsSendingGuard() {
161
139
  const g = globalThis;
162
- return (g.__beLinkClsLoggerSendingCount__ ?? 0) > 0;
140
+ const next = (g.__beLinkClsLoggerSendingCount__ ?? 0) + 1;
141
+ g.__beLinkClsLoggerSendingCount__ = next;
142
+ return () => {
143
+ const cur = g.__beLinkClsLoggerSendingCount__ ?? 0;
144
+ g.__beLinkClsLoggerSendingCount__ = cur > 0 ? cur - 1 : 0;
145
+ };
163
146
  }
164
- function shouldIgnoreUrl$1(url, ignoreUrls) {
165
- for (const rule of ignoreUrls) {
166
- if (typeof rule === 'string') {
167
- if (url.includes(rule))
168
- return true;
169
- continue;
147
+ /**
148
+ * CLS Logger 核心基类
149
+ * - 负责所有上报、队列、监控逻辑
150
+ * - 不包含具体的 SDK 加载实现(由子类负责)
151
+ * - 这样可以把 web/mini 的 SDK 依赖彻底解耦到子入口
152
+ */
153
+ class ClsLoggerCore {
154
+ constructor() {
155
+ this.sdk = null;
156
+ this.sdkPromise = null;
157
+ this.sdkOverride = null;
158
+ this.sdkLoaderOverride = null;
159
+ this.client = null;
160
+ this.clientPromise = null;
161
+ this.topicId = null;
162
+ this.endpoint = 'ap-shanghai.cls.tencentcs.com';
163
+ this.retryTimes = 10;
164
+ this.source = '127.0.0.1';
165
+ this.enabled = true;
166
+ this.projectId = '';
167
+ this.projectName = '';
168
+ this.appId = '';
169
+ this.appVersion = '';
170
+ this.envType = 'browser';
171
+ this.userGenerateBaseFields = null;
172
+ this.autoGenerateBaseFields = null;
173
+ this.storageKey = 'beLink_logs';
174
+ this.batchSize = 15;
175
+ // 参考文档:内存队列批量发送(500ms 或 20 条触发)
176
+ this.memoryQueue = [];
177
+ this.batchMaxSize = 20;
178
+ this.batchIntervalMs = 500;
179
+ this.batchTimer = null;
180
+ this.batchTimerDueAt = null;
181
+ this.initTs = 0;
182
+ this.startupDelayMs = 0;
183
+ // 参考文档:失败缓存 + 重试
184
+ this.failedCacheKey = 'cls_failed_logs';
185
+ this.failedCacheMax = 200;
186
+ this.requestMonitorStarted = false;
187
+ this.errorMonitorStarted = false;
188
+ this.performanceMonitorStarted = false;
189
+ this.behaviorMonitorStarted = false;
190
+ this.behaviorMonitorCleanup = null;
191
+ }
192
+ /**
193
+ * 子类可按需重写(默认检测 wx)
194
+ */
195
+ detectEnvType() {
196
+ const g = globalThis;
197
+ // 微信、支付宝、字节跳动、UniApp 等小程序环境通常都有特定全局变量
198
+ if ((g.wx && typeof g.wx.getSystemInfoSync === 'function') ||
199
+ (g.my && typeof g.my.getSystemInfoSync === 'function') ||
200
+ (g.tt && typeof g.tt.getSystemInfoSync === 'function') ||
201
+ (g.uni && typeof g.uni.getSystemInfoSync === 'function')) {
202
+ return 'miniprogram';
170
203
  }
171
- try {
172
- if (rule.test(url))
173
- return true;
204
+ return 'browser';
205
+ }
206
+ init(options) {
207
+ this.initTs = Date.now();
208
+ const topicId = options?.tencentCloud?.topicID ?? options?.topic_id ?? options?.topicID ?? this.topicId ?? null;
209
+ const endpoint = options?.tencentCloud?.endpoint ?? options?.endpoint ?? this.endpoint;
210
+ const retryTimes = options?.tencentCloud?.retry_times ?? options?.retry_times ?? this.retryTimes;
211
+ const source = options?.tencentCloud?.source ?? options?.source ?? this.source;
212
+ if (!topicId) {
213
+ // eslint-disable-next-line no-console
214
+ console.warn('ClsLogger.init 没有传 topicID/topic_id');
215
+ return;
174
216
  }
175
- catch {
176
- // ignore invalid regex
217
+ const nextEnvType = options.envType ?? this.detectEnvType();
218
+ // envType/endpoint/retryTimes 变化时:重置 client(以及可能的 sdk)
219
+ const envChanged = nextEnvType !== this.envType;
220
+ const endpointChanged = endpoint !== this.endpoint;
221
+ const retryChanged = retryTimes !== this.retryTimes;
222
+ if (envChanged || endpointChanged || retryChanged) {
223
+ this.client = null;
224
+ this.clientPromise = null;
225
+ }
226
+ if (envChanged) {
227
+ this.sdk = null;
228
+ this.sdkPromise = null;
229
+ }
230
+ this.topicId = topicId;
231
+ this.endpoint = endpoint;
232
+ this.retryTimes = retryTimes;
233
+ this.source = source;
234
+ this.userId = options.userId ?? this.userId;
235
+ this.userName = options.userName ?? this.userName;
236
+ this.projectId = options.projectId ?? this.projectId;
237
+ this.projectName = options.projectName ?? this.projectName;
238
+ this.appId = options.appId ?? this.appId;
239
+ this.appVersion = options.appVersion ?? this.appVersion;
240
+ this.envType = nextEnvType;
241
+ this.enabled = options.enabled ?? true;
242
+ // 可选:外部注入 SDK(优先级:sdkLoader > sdk)
243
+ this.sdkLoaderOverride = options.sdkLoader ?? this.sdkLoaderOverride;
244
+ this.sdkOverride = options.sdk ?? this.sdkOverride;
245
+ this.userGenerateBaseFields = options.generateBaseFields ?? this.userGenerateBaseFields;
246
+ this.autoGenerateBaseFields = this.createDeviceInfoBaseFields(options.deviceInfo);
247
+ this.storageKey = options.storageKey ?? this.storageKey;
248
+ this.batchSize = options.batchSize ?? this.batchSize;
249
+ this.batchMaxSize = options.batch?.maxSize ?? this.batchMaxSize;
250
+ this.batchIntervalMs = options.batch?.intervalMs ?? this.batchIntervalMs;
251
+ this.startupDelayMs = options.batch?.startupDelayMs ?? this.startupDelayMs;
252
+ this.failedCacheKey = options.failedCacheKey ?? this.failedCacheKey;
253
+ this.failedCacheMax = options.failedCacheMax ?? this.failedCacheMax;
254
+ // 预热(避免首条日志触发 import/初始化开销)
255
+ void this.getInstance().catch(() => {
256
+ // ignore
257
+ });
258
+ if (this.enabled) {
259
+ // 启动时尝试发送失败缓存
260
+ this.flushFailed();
261
+ // 初始化后立即启动请求监听
262
+ this.startRequestMonitor(options.requestMonitor);
263
+ // 初始化后立即启动错误监控/性能监控
264
+ this.startErrorMonitor(options.errorMonitor);
265
+ this.startPerformanceMonitor(options.performanceMonitor);
266
+ // 初始化后立即启动行为埋点(PV/UV/点击)
267
+ this.startBehaviorMonitor(options.behaviorMonitor);
177
268
  }
178
269
  }
179
- return false;
180
- }
181
- function sampleHit$2(sampleRate) {
182
- if (sampleRate >= 1)
183
- return true;
184
- if (sampleRate <= 0)
185
- return false;
186
- return Math.random() < sampleRate;
187
- }
188
- function truncate$3(s, maxLen) {
189
- if (!s)
190
- return s;
191
- return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
192
- }
193
- function buildPayload(params) {
194
- const { url, method, query, body, duration, startTime, status, success, error, options } = params;
195
- if (!url)
196
- return null;
197
- if (shouldIgnoreUrl$1(url, options.ignoreUrls))
198
- return null;
199
- if (!sampleHit$2(options.sampleRate))
200
- return null;
201
- const payload = { url };
202
- if (options.includeMethod && method)
203
- payload.method = method;
204
- if (options.includeQuery && query !== undefined)
205
- payload.query = truncate$3(String(query), options.maxParamLength);
206
- if (options.includeBody && body !== undefined)
207
- payload.params = truncate$3(stringifyLogValue(body), options.maxParamLength);
208
- if (typeof startTime === 'number')
209
- payload.startTime = startTime;
210
- if (typeof duration === 'number')
211
- payload.duration = duration;
212
- if (typeof status === 'number')
213
- payload.status = status;
214
- if (typeof success === 'boolean')
215
- payload.success = success ? 1 : 0;
216
- if (error !== undefined)
217
- payload.error = truncate$3(stringifyLogValue(error), options.maxParamLength);
218
- return payload;
219
- }
220
- function getAbsoluteUrlMaybe(url) {
221
- try {
222
- if (typeof window === 'undefined')
223
- return url;
224
- return new URL(url, window.location?.href).toString();
225
- }
226
- catch {
227
- return url;
228
- }
229
- }
230
- function installBrowserFetch(report, options) {
231
- if (typeof window === 'undefined')
232
- return;
233
- const w = window;
234
- if (w.__beLinkClsLoggerFetchInstalled__)
235
- return;
236
- if (typeof w.fetch !== 'function')
237
- return;
238
- w.__beLinkClsLoggerFetchInstalled__ = true;
239
- w.__beLinkClsLoggerRawFetch__ = w.fetch;
240
- w.fetch = async (input, init) => {
241
- // 避免 CLS SDK 上报请求被 requestMonitor 捕获后递归上报(尤其在跨域失败时会“上报失败→再上报”)
242
- if (isClsSendingNow())
243
- return w.__beLinkClsLoggerRawFetch__(input, init);
244
- let url = '';
245
- let method = '';
246
- let body = undefined;
247
- const startTs = Date.now();
270
+ getBaseFields() {
271
+ let auto = undefined;
272
+ let user = undefined;
248
273
  try {
249
- if (typeof input === 'string')
250
- url = input;
251
- else if (input instanceof URL)
252
- url = input.toString();
253
- else
254
- url = input.url ?? '';
255
- method = (init?.method ?? input?.method ?? 'GET');
256
- body = init?.body;
274
+ const autoRaw = this.autoGenerateBaseFields ? this.autoGenerateBaseFields() : undefined;
275
+ if (autoRaw && isPlainObject(autoRaw))
276
+ auto = normalizeFlatFields(autoRaw, 'deviceInfo');
257
277
  }
258
278
  catch {
259
- // ignore
279
+ auto = undefined;
260
280
  }
261
- const absUrl = getAbsoluteUrlMaybe(url);
262
- const query = (() => {
263
- try {
264
- const u = new URL(absUrl);
265
- return u.search ? u.search.slice(1) : '';
266
- }
267
- catch {
268
- return '';
269
- }
270
- })();
271
281
  try {
272
- const res = await w.__beLinkClsLoggerRawFetch__(input, init);
273
- const duration = Date.now() - startTs;
274
- const status = typeof res?.status === 'number' ? res.status : undefined;
275
- const ok = typeof res?.ok === 'boolean' ? res.ok : status !== undefined ? status >= 200 && status < 400 : true;
276
- const payload = buildPayload({
277
- url: absUrl,
278
- method,
279
- query,
280
- body,
281
- startTime: startTs,
282
- duration,
283
- status,
284
- success: ok,
285
- options,
286
- });
287
- if (payload)
288
- report(options.reportType, payload);
289
- return res;
282
+ const userRaw = this.userGenerateBaseFields ? this.userGenerateBaseFields() : undefined;
283
+ if (userRaw && isPlainObject(userRaw))
284
+ user = normalizeFlatFields({ ...userRaw }, 'generateBaseFields');
290
285
  }
291
- catch (err) {
292
- const duration = Date.now() - startTs;
293
- const payload = buildPayload({
294
- url: absUrl,
295
- method,
296
- query,
297
- body,
298
- startTime: startTs,
299
- duration,
300
- success: false,
301
- error: err,
302
- options,
303
- });
304
- if (payload)
305
- report(options.reportType, payload);
306
- throw err;
286
+ catch {
287
+ user = undefined;
307
288
  }
308
- };
309
- }
310
- function installBrowserXhr(report, options) {
311
- if (typeof window === 'undefined')
312
- return;
313
- const w = window;
314
- if (w.__beLinkClsLoggerXhrInstalled__)
315
- return;
316
- if (!w.XMLHttpRequest || !w.XMLHttpRequest.prototype)
317
- return;
318
- w.__beLinkClsLoggerXhrInstalled__ = true;
319
- const XHR = w.XMLHttpRequest;
320
- const rawOpen = XHR.prototype.open;
321
- const rawSend = XHR.prototype.send;
322
- XHR.prototype.open = function (...args) {
289
+ if (auto && user)
290
+ return mergeFields(user, auto);
291
+ if (user)
292
+ return user;
293
+ if (auto)
294
+ return auto;
295
+ return undefined;
296
+ }
297
+ startRequestMonitor(requestMonitor) {
298
+ if (this.requestMonitorStarted)
299
+ return;
300
+ // 默认开启;传 false 则关闭
301
+ const enabled = requestMonitor === undefined ? true : !!requestMonitor;
302
+ if (!enabled)
303
+ return;
304
+ const opts = typeof requestMonitor === 'object' && requestMonitor ? requestMonitor : {};
305
+ this.requestMonitorStarted = true;
306
+ this.installRequestMonitor((type, data) => {
307
+ this.track(type, data);
308
+ }, {
309
+ ...opts,
310
+ enabled: opts.enabled ?? true,
311
+ clsEndpoint: this.endpoint,
312
+ });
313
+ }
314
+ startErrorMonitor(errorMonitor) {
315
+ if (this.errorMonitorStarted)
316
+ return;
317
+ const enabled = errorMonitor === undefined ? true : !!errorMonitor;
318
+ if (!enabled)
319
+ return;
320
+ this.errorMonitorStarted = true;
321
+ this.installErrorMonitor((type, data) => this.track(type, data), errorMonitor ?? true);
322
+ }
323
+ startPerformanceMonitor(performanceMonitor) {
324
+ if (this.performanceMonitorStarted)
325
+ return;
326
+ const enabled = performanceMonitor === undefined ? true : !!performanceMonitor;
327
+ if (!enabled)
328
+ return;
329
+ this.performanceMonitorStarted = true;
330
+ this.installPerformanceMonitor((type, data) => this.track(type, data), performanceMonitor ?? true);
331
+ }
332
+ startBehaviorMonitor(behaviorMonitor) {
333
+ if (this.behaviorMonitorStarted)
334
+ return;
335
+ const enabled = behaviorMonitor === undefined ? true : !!behaviorMonitor;
336
+ if (!enabled)
337
+ return;
338
+ this.behaviorMonitorStarted = true;
339
+ this.behaviorMonitorCleanup = this.installBehaviorMonitor((type, data) => {
340
+ this.track(type, data);
341
+ }, behaviorMonitor ?? true);
342
+ }
343
+ /**
344
+ * 停止行为埋点监听(PV/UV/点击)
345
+ * - 如需重启:可再次调用 init(或自行调用 init 后的默认启动逻辑)
346
+ */
347
+ stopBehaviorMonitor() {
323
348
  try {
324
- this.__beLinkClsLoggerMethod__ = String(args[0] ?? 'GET');
325
- this.__beLinkClsLoggerUrl__ = String(args[1] ?? '');
349
+ this.behaviorMonitorCleanup?.();
326
350
  }
327
351
  catch {
328
352
  // ignore
329
353
  }
330
- return rawOpen.apply(this, args);
331
- };
332
- XHR.prototype.send = function (...args) {
333
- // CLS SDK 发起上报时:跳过监控,避免递归上报
334
- if (isClsSendingNow())
335
- return rawSend.apply(this, args);
336
- const startTs = Date.now();
337
- try {
338
- const method = String(this.__beLinkClsLoggerMethod__ ?? 'GET');
339
- const url = getAbsoluteUrlMaybe(String(this.__beLinkClsLoggerUrl__ ?? ''));
340
- const query = (() => {
341
- try {
342
- const u = new URL(url);
343
- return u.search ? u.search.slice(1) : '';
344
- }
345
- catch {
346
- return '';
347
- }
348
- })();
349
- const body = args?.[0];
350
- this.__beLinkClsLoggerStartTs__ = startTs;
351
- this.__beLinkClsLoggerBody__ = body;
352
- const onDone = (success, error) => {
353
- try {
354
- const st = this.__beLinkClsLoggerStartTs__ ?? startTs;
355
- const duration = Date.now() - st;
356
- const status = typeof this.status === 'number' ? this.status : undefined;
357
- const payload = buildPayload({
358
- url,
359
- method,
360
- query,
361
- body: this.__beLinkClsLoggerBody__,
362
- startTime: st,
363
- duration,
364
- status,
365
- success,
366
- error,
367
- options,
368
- });
369
- if (payload)
370
- report(options.reportType, payload);
371
- }
372
- catch {
373
- // ignore
374
- }
375
- };
376
- // 避免重复绑定
377
- if (!this.__beLinkClsLoggerBound__) {
378
- this.__beLinkClsLoggerBound__ = true;
379
- this.addEventListener('loadend', () => {
380
- try {
381
- const status = typeof this.status === 'number' ? this.status : 0;
382
- onDone(status >= 200 && status < 400);
383
- }
384
- catch {
385
- onDone(true);
386
- }
387
- });
388
- this.addEventListener('error', (e) => onDone(false, e));
389
- this.addEventListener('timeout', () => onDone(false, 'timeout'));
390
- this.addEventListener('abort', () => onDone(false, 'abort'));
391
- }
354
+ this.behaviorMonitorCleanup = null;
355
+ this.behaviorMonitorStarted = false;
356
+ }
357
+ /**
358
+ * 获取 CLS client(按环境懒加载 SDK)
359
+ */
360
+ async getInstance() {
361
+ if (this.client)
362
+ return this.client;
363
+ if (this.clientPromise)
364
+ return this.clientPromise;
365
+ this.clientPromise = this.loadSdk()
366
+ .then(({ AsyncClient }) => {
367
+ const client = new AsyncClient({
368
+ endpoint: this.endpoint,
369
+ retry_times: this.retryTimes,
370
+ });
371
+ this.client = client;
372
+ return client;
373
+ })
374
+ .catch((err) => {
375
+ // 失败后允许下次重试
376
+ this.clientPromise = null;
377
+ throw err;
378
+ });
379
+ return this.clientPromise;
380
+ }
381
+ /**
382
+ * 直接上报:埋点入参必须是一维(扁平)Object
383
+ * - 非原始值(对象/数组等)会被自动 stringify 成 string
384
+ * - 最终会把 fields 展开成 CLS 的 content(key/value 都会转成 string)
385
+ */
386
+ put(fields, options = {}) {
387
+ if (!this.enabled)
388
+ return;
389
+ if (!fields)
390
+ return;
391
+ if (!this.topicId) {
392
+ // eslint-disable-next-line no-console
393
+ console.warn('ClsLogger.put:未初始化 topic_id');
394
+ return;
392
395
  }
393
- catch {
396
+ const mergeBaseFields = options.mergeBaseFields ?? true;
397
+ const base = mergeBaseFields ? this.getBaseFields() : undefined;
398
+ const normalizedFields = normalizeFlatFields(fields, 'put');
399
+ const finalFields = mergeFields(base, {
400
+ projectId: this.projectId || undefined,
401
+ projectName: this.projectName || undefined,
402
+ envType: this.envType,
403
+ appId: this.appId || undefined,
404
+ appVersion: this.appVersion || undefined,
405
+ ...normalizedFields,
406
+ });
407
+ // 同步 API:内部异步发送,避免把网络异常冒泡到业务(尤其小程序)
408
+ void this.putAsync(finalFields).catch(() => {
394
409
  // ignore
410
+ });
411
+ }
412
+ async putAsync(finalFields) {
413
+ if (!this.topicId)
414
+ return;
415
+ const sdk = await this.loadSdk();
416
+ const client = await this.getInstance();
417
+ const logGroup = new sdk.LogGroup('127.0.0.1');
418
+ logGroup.setSource(this.source);
419
+ const log = new sdk.Log(Date.now());
420
+ for (const key of Object.keys(finalFields)) {
421
+ log.addContent(key, stringifyLogValue(finalFields[key]));
395
422
  }
396
- return rawSend.apply(this, args);
397
- };
398
- }
399
- function installMiniProgramWxRequest(report, options) {
400
- const wxAny = globalThis.wx;
401
- if (!wxAny || typeof wxAny.request !== 'function')
402
- return;
403
- if (wxAny.__beLinkClsLoggerWxRequestInstalled__)
404
- return;
405
- wxAny.__beLinkClsLoggerWxRequestInstalled__ = true;
406
- const rawRequest = wxAny.request.bind(wxAny);
407
- wxAny.request = (reqOptions) => {
408
- const startTs = Date.now();
423
+ logGroup.addLog(log);
424
+ const request = new sdk.PutLogsRequest(this.topicId, logGroup);
425
+ const exit = enterClsSendingGuard();
426
+ let p;
409
427
  try {
410
- const url = String(reqOptions?.url ?? '');
411
- const method = String(reqOptions?.method ?? 'GET');
412
- const data = reqOptions?.data;
413
- const wrapCb = (cb, success) => {
414
- return (res) => {
415
- try {
416
- const duration = Date.now() - startTs;
417
- const status = typeof res?.statusCode === 'number'
418
- ? res.statusCode
419
- : typeof res?.status === 'number'
420
- ? res.status
421
- : undefined;
422
- const payload = buildPayload({
423
- url,
424
- method,
425
- query: '',
426
- body: data,
427
- startTime: startTs,
428
- duration,
429
- status,
430
- success,
431
- error: success ? undefined : res,
432
- options,
433
- });
434
- if (payload)
435
- report(options.reportType, payload);
436
- }
437
- catch {
438
- // ignore
439
- }
440
- if (typeof cb === 'function')
441
- return cb(res);
442
- return undefined;
443
- };
444
- };
445
- const next = { ...(reqOptions ?? {}) };
446
- next.success = wrapCb(next.success, true);
447
- next.fail = wrapCb(next.fail, false);
448
- return rawRequest(next);
428
+ p = client.PutLogs(request);
449
429
  }
450
- catch {
451
- // ignore
430
+ finally {
431
+ exit();
452
432
  }
453
- return rawRequest(reqOptions);
454
- };
455
- }
456
- function installMiniProgramWxCloudCallFunction(report, options) {
457
- const wxAny = globalThis.wx;
458
- const cloud = wxAny?.cloud;
459
- if (!cloud || typeof cloud.callFunction !== 'function')
460
- return;
461
- if (cloud.__beLinkClsLoggerWxCloudCallFunctionInstalled__)
462
- return;
463
- cloud.__beLinkClsLoggerWxCloudCallFunctionInstalled__ = true;
464
- const rawCallFunction = cloud.callFunction.bind(cloud);
465
- cloud.callFunction = (callOptions) => {
466
- const startTs = Date.now();
467
- const name = (() => {
468
- try {
469
- return String(callOptions?.name ?? '');
470
- }
471
- catch {
472
- return '';
433
+ await p;
434
+ }
435
+ /**
436
+ * 直接上报:把 data 序列化后放入指定 key(默认 “日志内容”)
437
+ */
438
+ putJson(data, clsLoggerKey = '日志内容', options = {}) {
439
+ // put 的入参要求扁平;这里直接把数据序列化为 string
440
+ this.put({ [clsLoggerKey]: stringifyLogValue(data) }, options);
441
+ }
442
+ /**
443
+ * 入队:写入 localStorage 队列;达到 batchSize 自动 flush
444
+ * - 埋点入参必须是一维(扁平)Object,非原始值会被 stringify
445
+ */
446
+ enqueue(fields, options = {}) {
447
+ if (!this.enabled)
448
+ return;
449
+ if (!fields)
450
+ return;
451
+ const time = Date.now();
452
+ const mergeBaseFields = options.mergeBaseFields ?? true;
453
+ const base = mergeBaseFields ? this.getBaseFields() : undefined;
454
+ const normalizedFields = normalizeFlatFields(fields, 'enqueue');
455
+ const finalFields = mergeFields(base, {
456
+ projectId: this.projectId || undefined,
457
+ projectName: this.projectName || undefined,
458
+ envType: this.envType,
459
+ appId: this.appId || undefined,
460
+ appVersion: this.appVersion || undefined,
461
+ ...normalizedFields,
462
+ });
463
+ const queue = readQueue(this.storageKey);
464
+ const next = [...queue, { time, data: finalFields }];
465
+ if (next.length < this.batchSize) {
466
+ writeQueue(this.storageKey, next);
467
+ return;
468
+ }
469
+ // 达到阈值:flush + 写入新的队列(避免并发下丢失,按“先 flush 旧的”策略)
470
+ this.putBatch(queue);
471
+ writeQueue(this.storageKey, [{ time, data: finalFields }]);
472
+ }
473
+ /**
474
+ * 从 localStorage 读取队列并批量上报
475
+ */
476
+ flush() {
477
+ const queue = readQueue(this.storageKey);
478
+ if (queue.length === 0)
479
+ return;
480
+ this.putBatch(queue);
481
+ writeQueue(this.storageKey, []);
482
+ }
483
+ /**
484
+ * 批量上报(每条 item.data 展开为 log content)
485
+ */
486
+ putBatch(queue) {
487
+ if (!this.enabled)
488
+ return;
489
+ if (!queue || queue.length === 0)
490
+ return;
491
+ if (!this.topicId) {
492
+ // eslint-disable-next-line no-console
493
+ console.warn('ClsLogger.putBatch:未初始化 topic_id');
494
+ return;
495
+ }
496
+ void this.putBatchAsync(queue).catch(() => {
497
+ // ignore
498
+ });
499
+ }
500
+ async putBatchAsync(queue) {
501
+ if (!this.topicId)
502
+ return;
503
+ const sdk = await this.loadSdk();
504
+ const client = await this.getInstance();
505
+ const logGroup = new sdk.LogGroup('127.0.0.1');
506
+ logGroup.setSource(this.source);
507
+ for (const item of queue) {
508
+ const log = new sdk.Log(item.time);
509
+ const data = item.data ?? {};
510
+ for (const key of Object.keys(data)) {
511
+ log.addContent(key, stringifyLogValue(data[key]));
473
512
  }
474
- })();
475
- const data = callOptions?.data;
476
- let reported = false;
477
- const onDone = (success, err) => {
478
- if (reported)
479
- return;
480
- reported = true;
513
+ logGroup.addLog(log);
514
+ }
515
+ if (logGroup.getLogs().length === 0)
516
+ return;
517
+ const request = new sdk.PutLogsRequest(this.topicId, logGroup);
518
+ const exit = enterClsSendingGuard();
519
+ let p;
520
+ try {
521
+ p = client.PutLogs(request);
522
+ }
523
+ finally {
524
+ exit();
525
+ }
526
+ await p;
527
+ }
528
+ /**
529
+ * 参考《一、概述》:统一上报入口(内存队列 + 批量发送)
530
+ */
531
+ report(log) {
532
+ if (!this.enabled)
533
+ return;
534
+ if (!log?.type)
535
+ return;
536
+ if (!this.topicId) {
537
+ // eslint-disable-next-line no-console
538
+ console.warn('ClsLogger.report:未初始化 topicID/topic_id');
539
+ return;
540
+ }
541
+ this.memoryQueue.push(log);
542
+ if (this.memoryQueue.length >= this.batchMaxSize) {
543
+ void this.flushBatch();
544
+ return;
545
+ }
546
+ const now = Date.now();
547
+ const desiredDueAt = this.getDesiredBatchFlushDueAt(now);
548
+ const desiredDelay = Math.max(0, desiredDueAt - now);
549
+ if (!this.batchTimer) {
550
+ this.batchTimerDueAt = desiredDueAt;
551
+ this.batchTimer = setTimeout(() => {
552
+ void this.flushBatch();
553
+ }, desiredDelay);
554
+ return;
555
+ }
556
+ // 启动合并窗口内:如果当前 timer 会“更早”触发,则延后到窗口结束,尽量减少多次发送
557
+ if (this.batchTimerDueAt !== null && this.batchTimerDueAt < desiredDueAt) {
481
558
  try {
482
- const duration = Date.now() - startTs;
483
- const payload = buildPayload({
484
- // 统一走 url 字段,便于和 http 一起检索/聚合
485
- url: `cloud.callFunction/${name || 'unknown'}`,
486
- method: 'callFunction',
487
- query: '',
488
- body: data,
489
- startTime: startTs,
490
- duration,
491
- success,
492
- error: success ? undefined : err,
493
- options,
494
- });
495
- if (payload) {
496
- payload.requestType = 'cloud-function';
497
- payload.name = name || 'unknown';
498
- report(options.reportType, payload);
499
- }
559
+ clearTimeout(this.batchTimer);
500
560
  }
501
561
  catch {
502
562
  // ignore
503
563
  }
504
- };
505
- try {
506
- const next = { ...(callOptions ?? {}) };
507
- const rawSuccess = next.success;
508
- const rawFail = next.fail;
509
- next.success = (res) => {
510
- onDone(true);
511
- if (typeof rawSuccess === 'function')
512
- return rawSuccess(res);
513
- return undefined;
514
- };
515
- next.fail = (err) => {
516
- onDone(false, err?.message ?? err);
517
- if (typeof rawFail === 'function')
518
- return rawFail(err);
519
- return undefined;
520
- };
521
- const ret = rawCallFunction(next);
522
- // 兼容 Promise 风格(有些版本/写法不传 success/fail)
523
- if (ret && typeof ret.then === 'function') {
524
- ret.then(() => onDone(true), (err) => onDone(false, err?.message ?? err));
525
- }
526
- return ret;
527
- }
528
- catch (err) {
529
- onDone(false, err);
530
- throw err;
564
+ this.batchTimerDueAt = desiredDueAt;
565
+ this.batchTimer = setTimeout(() => {
566
+ void this.flushBatch();
567
+ }, desiredDelay);
531
568
  }
532
- };
533
- }
534
- function installRequestMonitor(report, opts = {}) {
535
- const enabled = opts.enabled ?? true;
536
- if (!enabled)
537
- return;
538
- const ignoreUrls = [...DEFAULT_IGNORE$1, ...(opts.ignoreUrls ?? [])];
539
- if (opts.clsEndpoint)
540
- ignoreUrls.push(opts.clsEndpoint);
541
- const options = {
542
- enabled: true,
543
- reportType: opts.reportType ?? 'http',
544
- sampleRate: opts.sampleRate ?? 1,
545
- ignoreUrls,
546
- includeMethod: opts.includeMethod ?? true,
547
- includeQuery: opts.includeQuery ?? true,
548
- includeBody: opts.includeBody ?? true,
549
- maxParamLength: opts.maxParamLength ?? 2000,
550
- clsEndpoint: opts.clsEndpoint ?? '',
551
- };
552
- if (isMiniProgramEnv()) {
553
- installMiniProgramWxRequest(report, options);
554
- installMiniProgramWxCloudCallFunction(report, options);
555
- return;
556
- }
557
- installBrowserFetch(report, options);
558
- installBrowserXhr(report, options);
559
- }
560
-
561
- const DEFAULT_MAX_TEXT = 4000;
562
- const DEFAULT_DEDUPE_WINDOW_MS = 3000;
563
- const DEFAULT_DEDUPE_MAX_KEYS = 200;
564
- function truncate$2(s, maxLen) {
565
- if (!s)
566
- return s;
567
- return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
568
- }
569
- function sampleHit$1(sampleRate) {
570
- if (sampleRate >= 1)
571
- return true;
572
- if (sampleRate <= 0)
573
- return false;
574
- return Math.random() < sampleRate;
575
- }
576
- function getPagePath$1() {
577
- try {
578
- if (typeof window === 'undefined')
579
- return '';
580
- return window.location?.pathname ?? '';
581
569
  }
582
- catch {
583
- return '';
584
- }
585
- }
586
- function getMpPagePath() {
587
- try {
588
- const pages = globalThis.getCurrentPages?.();
589
- if (Array.isArray(pages) && pages.length > 0) {
590
- const page = pages[pages.length - 1];
591
- return page.route || page.__route__ || '';
570
+ getDesiredBatchFlushDueAt(nowTs) {
571
+ const start = this.initTs || nowTs;
572
+ const startupDelay = Number.isFinite(this.startupDelayMs) ? Math.max(0, this.startupDelayMs) : 0;
573
+ if (startupDelay > 0) {
574
+ const end = start + startupDelay;
575
+ if (nowTs < end)
576
+ return end;
592
577
  }
593
- return '';
594
- }
595
- catch {
596
- return '';
578
+ return nowTs + this.batchIntervalMs;
597
579
  }
598
- }
599
- function normalizeErrorLike(err, maxTextLength) {
600
- if (err && typeof err === 'object') {
601
- const anyErr = err;
602
- let rawMsg = anyErr.message;
603
- if (!rawMsg) {
604
- const str = anyErr.toString?.();
605
- if (!str || str === '[object Object]') {
606
- rawMsg = stringifyLogValue(anyErr);
607
- }
608
- else {
609
- rawMsg = str;
610
- }
580
+ info(message, data = {}) {
581
+ let msg = '';
582
+ let extra = {};
583
+ if (message instanceof Error) {
584
+ msg = message.message;
585
+ extra = {
586
+ stack: message.stack,
587
+ name: message.name,
588
+ ...data,
589
+ };
611
590
  }
612
- const message = truncate$2(String(rawMsg ?? ''), maxTextLength);
613
- const name = truncate$2(String(anyErr.name ?? ''), 200);
614
- const stack = truncate$2(String(anyErr.stack ?? ''), maxTextLength);
615
- return { message, name, stack };
616
- }
617
- const message = truncate$2(stringifyLogValue(err), maxTextLength);
618
- return { message, name: '', stack: '' };
619
- }
620
- function createDedupeGuard(options) {
621
- const cache = new Map(); // key -> lastReportAt
622
- const maxKeys = Math.max(0, options.dedupeMaxKeys);
623
- const windowMs = Math.max(0, options.dedupeWindowMs);
624
- function touch(key, now) {
625
- // refresh insertion order
626
- if (cache.has(key))
627
- cache.delete(key);
628
- cache.set(key, now);
629
- if (maxKeys > 0) {
630
- while (cache.size > maxKeys) {
631
- const first = cache.keys().next().value;
632
- if (!first)
633
- break;
634
- cache.delete(first);
635
- }
591
+ else {
592
+ msg = String(message);
593
+ extra = data;
636
594
  }
595
+ const payload = normalizeFlatFields({ message: msg, ...extra }, 'info');
596
+ this.report({ type: 'info', data: payload, timestamp: Date.now() });
637
597
  }
638
- return (key) => {
639
- if (!key)
640
- return true;
641
- if (windowMs <= 0 || maxKeys === 0)
642
- return true;
643
- const now = Date.now();
644
- const last = cache.get(key);
645
- if (typeof last === 'number' && now - last < windowMs)
646
- return false;
647
- touch(key, now);
648
- return true;
649
- };
650
- }
651
- function buildErrorKey(type, payload) {
652
- // 使用最核心、最稳定的字段构造签名,避免把瞬态字段(如 time)带入导致失效
653
- const parts = [
654
- type,
655
- String(payload.source ?? ''),
656
- String(payload.pagePath ?? ''),
657
- String(payload.message ?? ''),
658
- String(payload.errorName ?? ''),
659
- String(payload.stack ?? ''),
660
- String(payload.filename ?? ''),
661
- String(payload.lineno ?? ''),
662
- String(payload.colno ?? ''),
663
- String(payload.tagName ?? ''),
664
- String(payload.resourceUrl ?? ''),
665
- ];
666
- return parts.join('|');
667
- }
668
- function installBrowserErrorMonitor(report, options) {
669
- if (typeof window === 'undefined')
670
- return;
671
- const w = window;
672
- if (w.__beLinkClsLoggerErrorInstalled__)
673
- return;
674
- w.__beLinkClsLoggerErrorInstalled__ = true;
675
- const shouldReport = createDedupeGuard(options);
676
- window.addEventListener('error', (event) => {
677
- try {
678
- if (!sampleHit$1(options.sampleRate))
679
- return;
680
- const payload = {
681
- pagePath: getPagePath$1(),
682
- source: 'window.error',
683
- };
684
- // JS runtime error
685
- if (event && typeof event === 'object' && 'message' in event) {
686
- payload.message = truncate$2(String(event.message ?? ''), options.maxTextLength);
687
- payload.filename = truncate$2(String(event.filename ?? ''), 500);
688
- payload.lineno = typeof event.lineno === 'number' ? event.lineno : undefined;
689
- payload.colno = typeof event.colno === 'number' ? event.colno : undefined;
690
- const err = event.error;
691
- if (err) {
692
- const e = normalizeErrorLike(err, options.maxTextLength);
693
- if (e.name)
694
- payload.errorName = e.name;
695
- if (e.stack)
696
- payload.stack = e.stack;
697
- }
698
- if (!shouldReport(buildErrorKey(options.reportType, payload)))
699
- return;
700
- report(options.reportType, payload);
701
- return;
702
- }
703
- // Resource error (img/script/link)
704
- if (options.captureResourceError) {
705
- const target = event?.target || event?.srcElement;
706
- const tagName = target?.tagName ? String(target.tagName) : '';
707
- const url = String(target?.src || target?.href || '');
708
- payload.source = 'resource.error';
709
- payload.tagName = tagName;
710
- payload.resourceUrl = truncate$2(url, 2000);
711
- if (!shouldReport(buildErrorKey(options.reportType, payload)))
712
- return;
713
- report(options.reportType, payload);
714
- }
715
- }
716
- catch {
717
- // ignore
718
- }
719
- }, true);
720
- window.addEventListener('unhandledrejection', (event) => {
721
- try {
722
- if (!sampleHit$1(options.sampleRate))
723
- return;
724
- const reason = event?.reason;
725
- const e = normalizeErrorLike(reason, options.maxTextLength);
726
- const payload = {
727
- pagePath: getPagePath$1(),
728
- source: 'unhandledrejection',
729
- message: e.message,
730
- errorName: e.name,
731
- stack: e.stack,
598
+ warn(message, data = {}) {
599
+ let msg = '';
600
+ let extra = {};
601
+ if (message instanceof Error) {
602
+ msg = message.message;
603
+ extra = {
604
+ stack: message.stack,
605
+ name: message.name,
606
+ ...data,
732
607
  };
733
- if (!shouldReport(buildErrorKey(options.reportType, payload)))
734
- return;
735
- report(options.reportType, payload);
736
- }
737
- catch {
738
- // ignore
739
- }
740
- });
741
- }
742
- function installMiniProgramErrorMonitor(report, options) {
743
- const g = globalThis;
744
- if (g.__beLinkClsLoggerMpErrorInstalled__)
745
- return;
746
- g.__beLinkClsLoggerMpErrorInstalled__ = true;
747
- const shouldReport = createDedupeGuard(options);
748
- const wxAny = globalThis.wx;
749
- // wx.* 事件(兼容在 App 已经创建后的场景)
750
- try {
751
- if (wxAny && typeof wxAny.onError === 'function') {
752
- wxAny.onError((msg) => {
753
- try {
754
- if (!sampleHit$1(options.sampleRate))
755
- return;
756
- const e = normalizeErrorLike(msg, options.maxTextLength);
757
- const payload = {
758
- pagePath: getMpPagePath(),
759
- source: 'wx.onError',
760
- message: e.message,
761
- errorName: e.name,
762
- stack: e.stack,
763
- };
764
- if (!shouldReport(buildErrorKey(options.reportType, payload)))
765
- return;
766
- report(options.reportType, payload);
767
- }
768
- catch {
769
- // ignore
770
- }
771
- });
772
608
  }
773
- }
774
- catch {
775
- // ignore
776
- }
777
- try {
778
- if (wxAny && typeof wxAny.onUnhandledRejection === 'function') {
779
- wxAny.onUnhandledRejection((res) => {
780
- try {
781
- if (!sampleHit$1(options.sampleRate))
782
- return;
783
- const e = normalizeErrorLike(res?.reason, options.maxTextLength);
784
- const payload = {
785
- pagePath: getMpPagePath(),
786
- source: 'wx.onUnhandledRejection',
787
- message: e.message,
788
- errorName: e.name,
789
- stack: e.stack,
790
- };
791
- if (!shouldReport(buildErrorKey(options.reportType, payload)))
792
- return;
793
- report(options.reportType, payload);
794
- }
795
- catch {
796
- // ignore
797
- }
798
- });
609
+ else {
610
+ msg = String(message);
611
+ extra = data;
799
612
  }
613
+ const payload = normalizeFlatFields({ message: msg, ...extra }, 'warn');
614
+ this.report({ type: 'warn', data: payload, timestamp: Date.now() });
800
615
  }
801
- catch {
802
- // ignore
803
- }
804
- // 包装 App({...}) 注入 onError/onUnhandledRejection(推荐)
805
- try {
806
- if (typeof g.App === 'function' && !g.__beLinkClsLoggerAppWrapped__) {
807
- g.__beLinkClsLoggerAppWrapped__ = true;
808
- const rawApp = g.App;
809
- g.App = (appOptions) => {
810
- const next = { ...(appOptions ?? {}) };
811
- const rawOnError = next.onError;
812
- next.onError = function (...args) {
813
- try {
814
- if (sampleHit$1(options.sampleRate)) {
815
- const e = normalizeErrorLike(args?.[0], options.maxTextLength);
816
- const payload = {
817
- pagePath: getMpPagePath(),
818
- source: 'App.onError',
819
- message: e.message,
820
- errorName: e.name,
821
- stack: e.stack,
822
- };
823
- if (shouldReport(buildErrorKey(options.reportType, payload)))
824
- report(options.reportType, payload);
825
- }
826
- }
827
- catch {
828
- // ignore
829
- }
830
- if (typeof rawOnError === 'function')
831
- return rawOnError.apply(this, args);
832
- return undefined;
833
- };
834
- const rawOnUnhandled = next.onUnhandledRejection;
835
- next.onUnhandledRejection = function (...args) {
836
- try {
837
- if (sampleHit$1(options.sampleRate)) {
838
- const reason = args?.[0]?.reason ?? args?.[0];
839
- const e = normalizeErrorLike(reason, options.maxTextLength);
840
- const payload = {
841
- pagePath: getMpPagePath(),
842
- source: 'App.onUnhandledRejection',
843
- message: e.message,
844
- errorName: e.name,
845
- stack: e.stack,
846
- };
847
- if (shouldReport(buildErrorKey(options.reportType, payload)))
848
- report(options.reportType, payload);
849
- }
850
- }
851
- catch {
852
- // ignore
853
- }
854
- if (typeof rawOnUnhandled === 'function')
855
- return rawOnUnhandled.apply(this, args);
856
- return undefined;
857
- };
858
- return rawApp(next);
616
+ error(message, data = {}) {
617
+ let msg = '';
618
+ let extra = {};
619
+ if (message instanceof Error) {
620
+ msg = message.message;
621
+ extra = {
622
+ stack: message.stack,
623
+ name: message.name,
624
+ ...data,
859
625
  };
860
626
  }
627
+ else {
628
+ msg = String(message);
629
+ extra = data;
630
+ }
631
+ const payload = normalizeFlatFields({ message: msg, ...extra }, 'error');
632
+ this.report({ type: 'error', data: payload, timestamp: Date.now() });
861
633
  }
862
- catch {
863
- // ignore
864
- }
865
- }
866
- function installErrorMonitor(report, opts = {}) {
867
- const enabled = opts === undefined ? true : !!opts;
868
- if (!enabled)
869
- return;
870
- const raw = typeof opts === 'object' && opts ? opts : {};
871
- const options = {
872
- enabled: true,
873
- reportType: raw.reportType ?? 'error',
874
- sampleRate: raw.sampleRate ?? 1,
875
- captureResourceError: raw.captureResourceError ?? true,
876
- maxTextLength: raw.maxTextLength ?? DEFAULT_MAX_TEXT,
877
- dedupeWindowMs: raw.dedupeWindowMs ?? DEFAULT_DEDUPE_WINDOW_MS,
878
- dedupeMaxKeys: raw.dedupeMaxKeys ?? DEFAULT_DEDUPE_MAX_KEYS,
879
- };
880
- if (isMiniProgramEnv()) {
881
- installMiniProgramErrorMonitor(report, options);
882
- return;
634
+ track(trackType, data = {}) {
635
+ if (!trackType)
636
+ return;
637
+ this.report({
638
+ type: trackType,
639
+ data: normalizeFlatFields(data, `track:${trackType}`),
640
+ timestamp: Date.now(),
641
+ });
883
642
  }
884
- installBrowserErrorMonitor(report, options);
885
- }
886
-
887
- const DEFAULT_IGNORE = ['cls.tencentcs.com', /\/cls\//i];
888
- function truncate$1(s, maxLen) {
889
- if (!s)
890
- return s;
891
- return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
892
- }
893
- function sampleHit(sampleRate) {
894
- if (sampleRate >= 1)
895
- return true;
896
- if (sampleRate <= 0)
897
- return false;
898
- return Math.random() < sampleRate;
899
- }
900
- function shouldIgnoreUrl(url, ignoreUrls) {
901
- for (const rule of ignoreUrls) {
902
- if (typeof rule === 'string') {
903
- if (url.includes(rule))
904
- return true;
905
- continue;
643
+ /**
644
+ * 立即发送内存队列
645
+ */
646
+ async flushBatch() {
647
+ if (this.batchTimer) {
648
+ clearTimeout(this.batchTimer);
649
+ this.batchTimer = null;
906
650
  }
651
+ this.batchTimerDueAt = null;
652
+ if (this.memoryQueue.length === 0)
653
+ return;
654
+ const logs = [...this.memoryQueue];
655
+ this.memoryQueue = [];
907
656
  try {
908
- if (rule.test(url))
909
- return true;
657
+ await this.sendReportLogs(logs);
910
658
  }
911
659
  catch {
912
- // ignore invalid regex
660
+ this.retrySendReportLogs(logs, 1);
913
661
  }
914
662
  }
915
- return false;
916
- }
917
- function getPagePath() {
918
- try {
919
- if (typeof window === 'undefined')
920
- return '';
921
- return window.location?.pathname ?? '';
922
- }
923
- catch {
924
- return '';
925
- }
926
- }
927
- function reportMetric(report, reportType, metric, value, extra = {}) {
928
- report(reportType, {
929
- pagePath: getPagePath(),
930
- metric,
931
- value,
932
- ...extra,
933
- });
934
- }
935
- function installBrowserPerformanceMonitor(report, options) {
936
- if (typeof window === 'undefined')
937
- return;
938
- const w = window;
939
- if (w.__beLinkClsLoggerPerfInstalled__)
940
- return;
941
- w.__beLinkClsLoggerPerfInstalled__ = true;
942
- const ignoreUrls = [...DEFAULT_IGNORE, ...(options.ignoreUrls ?? [])];
943
- // Navigation timing: TTFB 等
944
- if (options.navigationTiming) {
945
- try {
946
- const navEntries = performance.getEntriesByType?.('navigation');
947
- const nav = Array.isArray(navEntries) ? navEntries[0] : undefined;
948
- if (nav && typeof nav === 'object') {
949
- const ttfb = typeof nav.responseStart === 'number' && typeof nav.requestStart === 'number'
950
- ? nav.responseStart - nav.requestStart
951
- : -1;
952
- if (ttfb >= 0 && sampleHit(options.sampleRate))
953
- reportMetric(report, options.reportType, 'TTFB', ttfb, { unit: 'ms' });
954
- }
955
- }
956
- catch {
957
- // ignore
958
- }
663
+ buildReportFields(log) {
664
+ const ts = log.timestamp ?? Date.now();
665
+ const base = this.getBaseFields();
666
+ const data = normalizeFlatFields(log.data ?? {}, 'report:data');
667
+ const mergedData = mergeFields(base, data);
668
+ return {
669
+ timestamp: ts,
670
+ type: log.type,
671
+ envType: this.envType,
672
+ projectId: this.projectId || undefined,
673
+ projectName: this.projectName || undefined,
674
+ appId: this.appId || undefined,
675
+ appVersion: this.appVersion || undefined,
676
+ // 保证“一维字段”:业务数据以 JSON 字符串形式落到 CLS
677
+ ...mergedData,
678
+ };
959
679
  }
960
- // Web Vitals: FCP/LCP/CLS/FID
961
- if (options.webVitals && typeof globalThis.PerformanceObserver === 'function') {
962
- // FCP
963
- try {
964
- const po = new PerformanceObserver((list) => {
965
- try {
966
- if (!sampleHit(options.sampleRate))
967
- return;
968
- for (const entry of list.getEntries()) {
969
- if (entry?.name === 'first-contentful-paint' && typeof entry.startTime === 'number') {
970
- reportMetric(report, options.reportType, 'FCP', entry.startTime, { unit: 'ms' });
971
- }
972
- }
973
- }
974
- catch {
975
- // ignore
976
- }
977
- });
978
- po.observe({ type: 'paint', buffered: true });
979
- }
980
- catch {
981
- // ignore
680
+ async sendReportLogs(logs) {
681
+ if (!this.topicId)
682
+ return;
683
+ const sdk = await this.loadSdk();
684
+ const client = await this.getInstance();
685
+ const logGroup = new sdk.LogGroup('127.0.0.1');
686
+ logGroup.setSource(this.source);
687
+ for (const item of logs) {
688
+ const fields = this.buildReportFields(item);
689
+ const log = new sdk.Log(fields.timestamp);
690
+ for (const key of Object.keys(fields)) {
691
+ if (key === 'timestamp')
692
+ continue;
693
+ log.addContent(key, stringifyLogValue(fields[key]));
694
+ }
695
+ logGroup.addLog(log);
982
696
  }
983
- // LCP(最后一次为准)
984
- let lastLcp = null;
697
+ const request = new sdk.PutLogsRequest(this.topicId, logGroup);
698
+ // 只在“发起网络请求”的同步阶段打标记,避免 requestMonitor 监控 CLS 上报请求导致递归
699
+ const exit = enterClsSendingGuard();
700
+ let p;
985
701
  try {
986
- const po = new PerformanceObserver((list) => {
987
- try {
988
- const entries = list.getEntries();
989
- if (entries && entries.length)
990
- lastLcp = entries[entries.length - 1];
991
- }
992
- catch {
993
- // ignore
994
- }
995
- });
996
- po.observe({ type: 'largest-contentful-paint', buffered: true });
997
- const flushLcp = () => {
998
- try {
999
- if (!lastLcp)
1000
- return;
1001
- if (!sampleHit(options.sampleRate))
1002
- return;
1003
- if (typeof lastLcp.startTime === 'number')
1004
- reportMetric(report, options.reportType, 'LCP', lastLcp.startTime, { unit: 'ms' });
1005
- lastLcp = null;
1006
- }
1007
- catch {
1008
- // ignore
1009
- }
1010
- };
1011
- window.addEventListener('pagehide', flushLcp, { once: true });
1012
- document.addEventListener('visibilitychange', () => {
1013
- if (document.visibilityState === 'hidden')
1014
- flushLcp();
1015
- }, { once: true });
1016
- }
1017
- catch {
1018
- // ignore
702
+ p = client.PutLogs(request);
1019
703
  }
1020
- // CLS
1021
- try {
1022
- let clsValue = 0;
1023
- const po = new PerformanceObserver((list) => {
1024
- try {
1025
- for (const entry of list.getEntries()) {
1026
- if (entry && entry.hadRecentInput)
1027
- continue;
1028
- if (typeof entry.value === 'number')
1029
- clsValue += entry.value;
1030
- }
1031
- }
1032
- catch {
1033
- // ignore
1034
- }
1035
- });
1036
- po.observe({ type: 'layout-shift', buffered: true });
1037
- const flushCls = () => {
1038
- try {
1039
- if (!sampleHit(options.sampleRate))
1040
- return;
1041
- reportMetric(report, options.reportType, 'CLS', clsValue, { unit: 'score' });
1042
- }
1043
- catch {
1044
- // ignore
1045
- }
1046
- };
1047
- window.addEventListener('pagehide', flushCls, { once: true });
1048
- document.addEventListener('visibilitychange', () => {
1049
- if (document.visibilityState === 'hidden')
1050
- flushCls();
1051
- }, { once: true });
704
+ finally {
705
+ exit();
1052
706
  }
1053
- catch {
1054
- // ignore
707
+ await p;
708
+ }
709
+ retrySendReportLogs(logs, retryCount) {
710
+ if (retryCount > this.retryTimes) {
711
+ this.cacheFailedReportLogs(logs);
712
+ return;
1055
713
  }
1056
- // FID
714
+ const delayMs = Math.pow(2, retryCount) * 1000;
715
+ setTimeout(async () => {
716
+ try {
717
+ await this.sendReportLogs(logs);
718
+ }
719
+ catch {
720
+ this.retrySendReportLogs(logs, retryCount + 1);
721
+ }
722
+ }, delayMs);
723
+ }
724
+ cacheFailedReportLogs(logs) {
725
+ const raw = readStringStorage(this.failedCacheKey);
726
+ let current = [];
1057
727
  try {
1058
- const po = new PerformanceObserver((list) => {
1059
- try {
1060
- if (!sampleHit(options.sampleRate))
1061
- return;
1062
- for (const entry of list.getEntries()) {
1063
- const startTime = typeof entry.startTime === 'number' ? entry.startTime : -1;
1064
- const processingStart = typeof entry.processingStart === 'number' ? entry.processingStart : -1;
1065
- if (startTime >= 0 && processingStart >= 0) {
1066
- reportMetric(report, options.reportType, 'FID', processingStart - startTime, { unit: 'ms' });
1067
- break;
1068
- }
1069
- }
1070
- }
1071
- catch {
1072
- // ignore
1073
- }
1074
- });
1075
- po.observe({ type: 'first-input', buffered: true });
728
+ const parsed = raw ? JSON.parse(raw) : [];
729
+ current = Array.isArray(parsed) ? parsed : [];
1076
730
  }
1077
731
  catch {
1078
- // ignore
732
+ current = [];
1079
733
  }
734
+ const next = [...current, ...logs].slice(-this.failedCacheMax);
735
+ writeStringStorage(this.failedCacheKey, JSON.stringify(next));
1080
736
  }
1081
- // Resource timing:资源加载耗时
1082
- if (options.resourceTiming && typeof globalThis.PerformanceObserver === 'function') {
737
+ flushFailed() {
738
+ if (!this.enabled)
739
+ return;
740
+ const raw = readStringStorage(this.failedCacheKey);
741
+ if (!raw)
742
+ return;
743
+ let logs = [];
1083
744
  try {
1084
- const po = new PerformanceObserver((list) => {
1085
- try {
1086
- if (!sampleHit(options.sampleRate))
1087
- return;
1088
- for (const entry of list.getEntries()) {
1089
- const name = String(entry?.name ?? '');
1090
- if (!name || shouldIgnoreUrl(name, ignoreUrls))
1091
- continue;
1092
- const initiatorType = String(entry?.initiatorType ?? '');
1093
- // 对齐文档:关注 fetch/xhr/img/script(同时允许 css/other 但不强制)
1094
- if (!['xmlhttprequest', 'fetch', 'img', 'script', 'css'].includes(initiatorType))
1095
- continue;
1096
- const payload = {
1097
- pagePath: getPagePath(),
1098
- metric: 'resource',
1099
- initiatorType,
1100
- url: truncate$1(name, options.maxTextLength),
1101
- startTime: typeof entry?.startTime === 'number' ? entry.startTime : undefined,
1102
- duration: typeof entry?.duration === 'number' ? entry.duration : undefined,
1103
- };
1104
- // 兼容字段(部分浏览器支持)
1105
- if (typeof entry?.transferSize === 'number')
1106
- payload.transferSize = entry.transferSize;
1107
- if (typeof entry?.encodedBodySize === 'number')
1108
- payload.encodedBodySize = entry.encodedBodySize;
1109
- if (typeof entry?.decodedBodySize === 'number')
1110
- payload.decodedBodySize = entry.decodedBodySize;
1111
- if (typeof entry?.nextHopProtocol === 'string')
1112
- payload.nextHopProtocol = entry.nextHopProtocol;
1113
- if (typeof entry?.responseStatus === 'number')
1114
- payload.status = entry.responseStatus;
1115
- report(options.reportType, payload);
1116
- }
1117
- }
1118
- catch {
1119
- // ignore
1120
- }
1121
- });
1122
- po.observe({ type: 'resource', buffered: true });
745
+ const parsed = JSON.parse(raw);
746
+ logs = Array.isArray(parsed) ? parsed : [];
1123
747
  }
1124
748
  catch {
1125
- // ignore
749
+ logs = [];
1126
750
  }
1127
- }
1128
- }
1129
- function installMiniProgramPerformanceMonitor(report, options) {
1130
- const g = globalThis;
1131
- const ctx = g.wx || g.Taro;
1132
- if (!ctx || typeof ctx.getPerformance !== 'function')
1133
- return;
1134
- if (g.__beLinkClsLoggerMpPerfInstalled__)
1135
- return;
1136
- g.__beLinkClsLoggerMpPerfInstalled__ = true;
1137
- try {
1138
- const perf = ctx.getPerformance();
1139
- if (!perf || typeof perf.createObserver !== 'function')
751
+ if (logs.length === 0)
1140
752
  return;
1141
- const observer = perf.createObserver((entryList) => {
753
+ // 先清空,再尝试发送
754
+ writeStringStorage(this.failedCacheKey, JSON.stringify([]));
755
+ this.memoryQueue.unshift(...logs);
756
+ void this.flushBatch();
757
+ }
758
+ /**
759
+ * 统计/计数类日志:按字段展开上报(若 data 为空默认 1)
760
+ */
761
+ stat(param) {
762
+ if (!param)
763
+ return;
764
+ const payload = normalizeFlatFields({
765
+ pagePath: typeof window !== 'undefined' ? window.location?.pathname : '',
766
+ projectId: this.projectId,
767
+ projectName: this.projectName,
768
+ ...param,
769
+ data: param.data ?? 1,
770
+ }, 'stat');
771
+ this.report({ type: 'stat', data: payload, timestamp: Date.now() });
772
+ }
773
+ }
774
+
775
+ function readGlobal(key) {
776
+ try {
777
+ const g = globalThis;
778
+ return g[key] ?? null;
779
+ }
780
+ catch {
781
+ return null;
782
+ }
783
+ }
784
+ function tryRequire(moduleName) {
785
+ try {
786
+ // 说明:
787
+ // - ESM 构建(exports.import/module)里通常不存在模块作用域的 require
788
+ // - 一些小程序运行时/构建链路会把 require 挂到 globalThis 上
789
+ // 因此这里同时探测“模块作用域 require”与 “globalThis.require”
790
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
791
+ const localReq = (typeof require === 'function' ? require : null);
792
+ const globalReq = readGlobal('require');
793
+ const candidates = [localReq, globalReq].filter((fn) => typeof fn === 'function');
794
+ for (const fn of candidates) {
1142
795
  try {
1143
- const entries = entryList.getEntries();
1144
- for (const entry of entries) {
1145
- if (!sampleHit(options.sampleRate))
1146
- continue;
1147
- // Page Render: firstRender
1148
- if (entry.entryType === 'render' && entry.name === 'firstRender') {
1149
- const duration = typeof entry.duration === 'number'
1150
- ? entry.duration
1151
- : typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
1152
- ? entry.endTime - entry.startTime
1153
- : 0;
1154
- report(options.reportType, {
1155
- metric: 'page-render',
1156
- duration,
1157
- pagePath: entry.path || '',
1158
- unit: 'ms',
1159
- });
1160
- }
1161
- // Route Switch: route
1162
- else if (entry.entryType === 'navigation' && entry.name === 'route') {
1163
- const duration = typeof entry.duration === 'number'
1164
- ? entry.duration
1165
- : typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
1166
- ? entry.endTime - entry.startTime
1167
- : 0;
1168
- report(options.reportType, {
1169
- metric: 'route',
1170
- duration,
1171
- pagePath: entry.path || '',
1172
- unit: 'ms',
1173
- });
1174
- }
1175
- // App Launch: appLaunch (Cold)
1176
- else if (entry.entryType === 'navigation' && entry.name === 'appLaunch') {
1177
- report(options.reportType, {
1178
- metric: 'app-launch',
1179
- duration: entry.duration,
1180
- launchType: 'cold',
1181
- unit: 'ms',
1182
- });
1183
- }
1184
- }
796
+ return fn(moduleName);
1185
797
  }
1186
798
  catch {
1187
- // ignore
799
+ // continue
1188
800
  }
1189
- });
1190
- observer.observe({ entryTypes: ['navigation', 'render'] });
801
+ }
802
+ return null;
1191
803
  }
1192
804
  catch {
1193
- // ignore
1194
- }
1195
- }
1196
- function installPerformanceMonitor(report, opts = {}) {
1197
- const enabled = opts === undefined ? true : !!opts;
1198
- if (!enabled)
1199
- return;
1200
- const raw = typeof opts === 'object' && opts ? opts : {};
1201
- const options = {
1202
- enabled: true,
1203
- reportType: raw.reportType ?? 'perf',
1204
- sampleRate: raw.sampleRate ?? 1,
1205
- ignoreUrls: raw.ignoreUrls ?? [],
1206
- webVitals: raw.webVitals ?? true,
1207
- navigationTiming: raw.navigationTiming ?? true,
1208
- resourceTiming: raw.resourceTiming ?? true,
1209
- maxTextLength: raw.maxTextLength ?? 2000,
1210
- };
1211
- if (isMiniProgramEnv()) {
1212
- installMiniProgramPerformanceMonitor(report, options);
1213
- return;
805
+ return null;
1214
806
  }
1215
- installBrowserPerformanceMonitor(report, options);
1216
807
  }
1217
808
 
1218
- function shouldSample(sampleRate) {
1219
- const r = sampleRate ?? 1;
1220
- if (r >= 1)
1221
- return true;
1222
- if (r <= 0)
1223
- return false;
1224
- return Math.random() < r;
1225
- }
1226
- function generateUUID() {
1227
- // 优先使用更安全的 crypto.randomUUID
809
+ const DEFAULT_IGNORE$1 = ['cls.tencentcs.com', /\/cls\//i];
810
+ function isClsSendingNow() {
1228
811
  const g = globalThis;
1229
- if (g.crypto?.randomUUID)
1230
- return g.crypto.randomUUID();
1231
- // fallback
1232
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
1233
- const r = Math.random() * 16 || 0;
1234
- const v = c === 'x' ? r | 0 : ((r | 0) & 0x3) | 0x8;
1235
- return v.toString(16);
1236
- });
812
+ return (g.__beLinkClsLoggerSendingCount__ ?? 0) > 0;
1237
813
  }
1238
- function safeReadUvMeta(key) {
1239
- const raw = readStringStorage(key);
1240
- if (!raw)
1241
- return { firstVisitTs: Date.now(), visitCount: 0 };
1242
- try {
1243
- const parsed = JSON.parse(raw);
1244
- if (!parsed || typeof parsed !== 'object')
1245
- return { firstVisitTs: Date.now(), visitCount: 0 };
1246
- const p = parsed;
1247
- const firstVisitTs = typeof p.firstVisitTs === 'number' && Number.isFinite(p.firstVisitTs) ? p.firstVisitTs : Date.now();
1248
- const visitCount = typeof p.visitCount === 'number' && Number.isFinite(p.visitCount) ? p.visitCount : 0;
1249
- const createdAtTs = typeof p.createdAtTs === 'number' && Number.isFinite(p.createdAtTs) ? p.createdAtTs : undefined;
1250
- const lastSeenTs = typeof p.lastSeenTs === 'number' && Number.isFinite(p.lastSeenTs) ? p.lastSeenTs : undefined;
1251
- return { firstVisitTs, visitCount, createdAtTs, lastSeenTs };
1252
- }
1253
- catch {
1254
- return { firstVisitTs: Date.now(), visitCount: 0 };
814
+ function shouldIgnoreUrl$1(url, ignoreUrls) {
815
+ for (const rule of ignoreUrls) {
816
+ if (typeof rule === 'string') {
817
+ if (url.includes(rule))
818
+ return true;
819
+ continue;
820
+ }
821
+ try {
822
+ if (rule.test(url))
823
+ return true;
824
+ }
825
+ catch {
826
+ // ignore invalid regex
827
+ }
1255
828
  }
829
+ return false;
1256
830
  }
1257
- function writeUvMeta(key, meta) {
1258
- writeStringStorage(key, JSON.stringify(meta));
1259
- }
1260
- function getWebPagePath() {
1261
- if (typeof window === 'undefined')
1262
- return '';
1263
- return window.location?.pathname || '';
831
+ function sampleHit$2(sampleRate) {
832
+ if (sampleRate >= 1)
833
+ return true;
834
+ if (sampleRate <= 0)
835
+ return false;
836
+ return Math.random() < sampleRate;
1264
837
  }
1265
- function getMiniProgramPagePath() {
1266
- const g = globalThis;
1267
- try {
1268
- const pages = typeof g.getCurrentPages === 'function' ? g.getCurrentPages() : [];
1269
- const last = Array.isArray(pages) ? pages[pages.length - 1] : undefined;
1270
- const route = (last?.route || last?.__route__);
1271
- return typeof route === 'string' ? route : '';
1272
- }
1273
- catch {
1274
- return '';
1275
- }
838
+ function truncate$3(s, maxLen) {
839
+ if (!s)
840
+ return s;
841
+ return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
1276
842
  }
1277
- function buildCommonUvFields(uvId, uvMeta, isFirstVisit) {
1278
- return {
1279
- uvId,
1280
- isFirstVisit,
1281
- firstVisitTs: uvMeta.firstVisitTs,
1282
- visitCount: uvMeta.visitCount,
1283
- };
843
+ function buildPayload(params) {
844
+ const { url, method, query, body, duration, startTime, status, success, error, options } = params;
845
+ if (!url)
846
+ return null;
847
+ if (shouldIgnoreUrl$1(url, options.ignoreUrls))
848
+ return null;
849
+ if (!sampleHit$2(options.sampleRate))
850
+ return null;
851
+ const payload = { url };
852
+ if (options.includeMethod && method)
853
+ payload.method = method;
854
+ if (options.includeQuery && query !== undefined)
855
+ payload.query = truncate$3(String(query), options.maxParamLength);
856
+ if (options.includeBody && body !== undefined)
857
+ payload.params = truncate$3(stringifyLogValue(body), options.maxParamLength);
858
+ if (typeof startTime === 'number')
859
+ payload.startTime = startTime;
860
+ if (typeof duration === 'number')
861
+ payload.duration = duration;
862
+ if (typeof status === 'number')
863
+ payload.status = status;
864
+ if (typeof success === 'boolean')
865
+ payload.success = success ? 1 : 0;
866
+ if (error !== undefined)
867
+ payload.error = truncate$3(stringifyLogValue(error), options.maxParamLength);
868
+ return payload;
1284
869
  }
1285
- function getAttr(el, attrName) {
870
+ function getAbsoluteUrlMaybe(url) {
1286
871
  try {
1287
- return el.getAttribute(attrName) ?? '';
872
+ if (typeof window === 'undefined')
873
+ return url;
874
+ return new URL(url, window.location?.href).toString();
1288
875
  }
1289
876
  catch {
1290
- return '';
877
+ return url;
1291
878
  }
1292
879
  }
1293
- function truncateText(s, maxLen) {
1294
- if (!s)
1295
- return '';
1296
- if (s.length <= maxLen)
1297
- return s;
1298
- return s.slice(0, maxLen);
1299
- }
1300
- function installBehaviorMonitor(report, envType, options = {}) {
1301
- const enableTrack = options.enableTrack ?? options.enabled ?? true;
1302
- if (!enableTrack)
1303
- return () => { };
1304
- const pvEnabled = options.pv ?? true;
1305
- const uvEnabled = options.uv ?? true;
1306
- const clickEnabled = options.click ?? true;
1307
- const pvReportType = options.pvReportType ?? 'pv';
1308
- const uvReportType = options.uvReportType ?? 'uv';
1309
- const clickReportType = options.clickReportType ?? 'click';
1310
- const uvIdStorageKey = options.uvIdStorageKey ?? 'cls_uv_id';
1311
- const uvMetaStorageKey = options.uvMetaStorageKey ?? 'cls_uv_meta';
1312
- const lastPagePathStorageKey = options.lastPagePathStorageKey ?? 'cls_last_page_path';
1313
- const uvExpireDaysRaw = options.trackOptions?.uvExpireDays ?? options.uvExpireDays ?? 30;
1314
- const uvExpireDays = Number.isFinite(uvExpireDaysRaw) ? Math.max(0, uvExpireDaysRaw) : 30;
1315
- const uvExpireMs = uvExpireDays * 24 * 60 * 60 * 1000;
1316
- const defaultClickWhiteList = envType === 'miniprogram' || isMiniProgramEnv() ? ['view', 'scroll-view'] : ['body', 'html'];
1317
- const clickWhiteList = (options.trackOptions?.clickWhiteList ?? options.clickWhiteList ?? defaultClickWhiteList).map((s) => String(s).toLowerCase());
1318
- const clickTrackIdAttr = options.clickTrackIdAttr ?? 'data-track-id';
1319
- const clickMaxTextLength = options.clickMaxTextLength ?? 120;
1320
- const getPagePath = options.getPagePath ??
1321
- (() => {
1322
- if (envType === 'miniprogram' || isMiniProgramEnv())
1323
- return getMiniProgramPagePath();
1324
- return getWebPagePath();
1325
- });
1326
- let destroyed = false;
1327
- // UV 状态:可能异步(openid/指纹)
1328
- let firstVisitFlag = false;
1329
- let firstVisitConsumed = false;
1330
- const uvStatePromise = (async () => {
1331
- let existingUvId = readStringStorage(uvIdStorageKey);
1332
- let isFirstVisit = false;
1333
- // 先读 meta,做过期判断(过期则清空 uvId + 重置 meta)
1334
- const now = Date.now();
1335
- const metaBefore = safeReadUvMeta(uvMetaStorageKey);
1336
- const lastSeenForExpire = metaBefore.lastSeenTs ?? metaBefore.createdAtTs ?? metaBefore.firstVisitTs ?? now;
1337
- const expired = uvExpireMs > 0 && now - lastSeenForExpire > uvExpireMs;
1338
- if (expired) {
1339
- existingUvId = null;
1340
- // 重置 meta(visitCount 会在后续 +1)
1341
- writeUvMeta(uvMetaStorageKey, { firstVisitTs: now, visitCount: 0, createdAtTs: now, lastSeenTs: now });
1342
- writeStringStorage(uvIdStorageKey, '');
1343
- }
1344
- // 如果外部提供 getUvId,优先使用;否则本地生成
880
+ function installBrowserFetch(report, options) {
881
+ if (typeof window === 'undefined')
882
+ return;
883
+ const w = window;
884
+ if (w.__beLinkClsLoggerFetchInstalled__)
885
+ return;
886
+ if (typeof w.fetch !== 'function')
887
+ return;
888
+ w.__beLinkClsLoggerFetchInstalled__ = true;
889
+ w.__beLinkClsLoggerRawFetch__ = w.fetch;
890
+ w.fetch = async (input, init) => {
891
+ // 避免 CLS SDK 上报请求被 requestMonitor 捕获后递归上报(尤其在跨域失败时会“上报失败→再上报”)
892
+ if (isClsSendingNow())
893
+ return w.__beLinkClsLoggerRawFetch__(input, init);
894
+ let url = '';
895
+ let method = '';
896
+ let body = undefined;
897
+ const startTs = Date.now();
1345
898
  try {
1346
- if (options.getUvId) {
1347
- const maybe = options.getUvId();
1348
- const resolved = typeof maybe?.then === 'function' ? await maybe : maybe;
1349
- if (resolved && typeof resolved === 'string')
1350
- existingUvId = resolved;
1351
- }
899
+ if (typeof input === 'string')
900
+ url = input;
901
+ else if (input instanceof URL)
902
+ url = input.toString();
903
+ else
904
+ url = input.url ?? '';
905
+ method = (init?.method ?? input?.method ?? 'GET');
906
+ body = init?.body;
1352
907
  }
1353
908
  catch {
1354
909
  // ignore
1355
910
  }
1356
- // 小程序:默认尝试 openid / 设备标识(兼容你给的参考实现)
1357
- if (!existingUvId && (envType === 'miniprogram' || isMiniProgramEnv())) {
1358
- const wxAny = globalThis.wx;
911
+ const absUrl = getAbsoluteUrlMaybe(url);
912
+ const query = (() => {
1359
913
  try {
1360
- const userInfo = wxAny?.getStorageSync?.('userInfo');
1361
- if (userInfo?.openid)
1362
- existingUvId = String(userInfo.openid);
914
+ const u = new URL(absUrl);
915
+ return u.search ? u.search.slice(1) : '';
1363
916
  }
1364
917
  catch {
1365
- // ignore
918
+ return '';
1366
919
  }
1367
- if (!existingUvId) {
1368
- try {
1369
- const sys = wxAny?.getSystemInfoSync?.();
1370
- const deviceId = sys?.deviceId ? String(sys.deviceId) : '';
1371
- const model = sys?.model ? String(sys.model) : '';
1372
- const system = sys?.system ? String(sys.system) : '';
1373
- const base = [deviceId || model, system].filter(Boolean).join('_');
1374
- if (base)
1375
- existingUvId = `${base}_${Date.now()}`;
1376
- }
920
+ })();
921
+ try {
922
+ const res = await w.__beLinkClsLoggerRawFetch__(input, init);
923
+ const duration = Date.now() - startTs;
924
+ const status = typeof res?.status === 'number' ? res.status : undefined;
925
+ const ok = typeof res?.ok === 'boolean' ? res.ok : status !== undefined ? status >= 200 && status < 400 : true;
926
+ const payload = buildPayload({
927
+ url: absUrl,
928
+ method,
929
+ query,
930
+ body,
931
+ startTime: startTs,
932
+ duration,
933
+ status,
934
+ success: ok,
935
+ options,
936
+ });
937
+ if (payload)
938
+ report(options.reportType, payload);
939
+ return res;
940
+ }
941
+ catch (err) {
942
+ const duration = Date.now() - startTs;
943
+ const payload = buildPayload({
944
+ url: absUrl,
945
+ method,
946
+ query,
947
+ body,
948
+ startTime: startTs,
949
+ duration,
950
+ success: false,
951
+ error: err,
952
+ options,
953
+ });
954
+ if (payload)
955
+ report(options.reportType, payload);
956
+ throw err;
957
+ }
958
+ };
959
+ }
960
+ function installBrowserXhr(report, options) {
961
+ if (typeof window === 'undefined')
962
+ return;
963
+ const w = window;
964
+ if (w.__beLinkClsLoggerXhrInstalled__)
965
+ return;
966
+ if (!w.XMLHttpRequest || !w.XMLHttpRequest.prototype)
967
+ return;
968
+ w.__beLinkClsLoggerXhrInstalled__ = true;
969
+ const XHR = w.XMLHttpRequest;
970
+ const rawOpen = XHR.prototype.open;
971
+ const rawSend = XHR.prototype.send;
972
+ XHR.prototype.open = function (...args) {
973
+ try {
974
+ this.__beLinkClsLoggerMethod__ = String(args[0] ?? 'GET');
975
+ this.__beLinkClsLoggerUrl__ = String(args[1] ?? '');
976
+ }
977
+ catch {
978
+ // ignore
979
+ }
980
+ return rawOpen.apply(this, args);
981
+ };
982
+ XHR.prototype.send = function (...args) {
983
+ // CLS SDK 发起上报时:跳过监控,避免递归上报
984
+ if (isClsSendingNow())
985
+ return rawSend.apply(this, args);
986
+ const startTs = Date.now();
987
+ try {
988
+ const method = String(this.__beLinkClsLoggerMethod__ ?? 'GET');
989
+ const url = getAbsoluteUrlMaybe(String(this.__beLinkClsLoggerUrl__ ?? ''));
990
+ const query = (() => {
991
+ try {
992
+ const u = new URL(url);
993
+ return u.search ? u.search.slice(1) : '';
994
+ }
995
+ catch {
996
+ return '';
997
+ }
998
+ })();
999
+ const body = args?.[0];
1000
+ this.__beLinkClsLoggerStartTs__ = startTs;
1001
+ this.__beLinkClsLoggerBody__ = body;
1002
+ const onDone = (success, error) => {
1003
+ try {
1004
+ const st = this.__beLinkClsLoggerStartTs__ ?? startTs;
1005
+ const duration = Date.now() - st;
1006
+ const status = typeof this.status === 'number' ? this.status : undefined;
1007
+ const payload = buildPayload({
1008
+ url,
1009
+ method,
1010
+ query,
1011
+ body: this.__beLinkClsLoggerBody__,
1012
+ startTime: st,
1013
+ duration,
1014
+ status,
1015
+ success,
1016
+ error,
1017
+ options,
1018
+ });
1019
+ if (payload)
1020
+ report(options.reportType, payload);
1021
+ }
1377
1022
  catch {
1378
1023
  // ignore
1379
1024
  }
1025
+ };
1026
+ // 避免重复绑定
1027
+ if (!this.__beLinkClsLoggerBound__) {
1028
+ this.__beLinkClsLoggerBound__ = true;
1029
+ this.addEventListener('loadend', () => {
1030
+ try {
1031
+ const status = typeof this.status === 'number' ? this.status : 0;
1032
+ onDone(status >= 200 && status < 400);
1033
+ }
1034
+ catch {
1035
+ onDone(true);
1036
+ }
1037
+ });
1038
+ this.addEventListener('error', (e) => onDone(false, e));
1039
+ this.addEventListener('timeout', () => onDone(false, 'timeout'));
1040
+ this.addEventListener('abort', () => onDone(false, 'abort'));
1380
1041
  }
1381
1042
  }
1382
- if (!existingUvId) {
1383
- existingUvId = generateUUID();
1384
- isFirstVisit = true;
1385
- }
1386
- // 只要拿到了 uvId,就写入持久化(便于下次启动复用)
1387
- writeStringStorage(uvIdStorageKey, existingUvId);
1388
- const meta = safeReadUvMeta(uvMetaStorageKey);
1389
- // 每次启动都 +1(“累计访问次数”)
1390
- const createdAt = meta.createdAtTs ?? meta.firstVisitTs ?? now;
1391
- const firstVisit = meta.firstVisitTs || now;
1392
- const nextMeta = {
1393
- firstVisitTs: firstVisit,
1394
- visitCount: (meta.visitCount || 0) + 1,
1395
- createdAtTs: createdAt,
1396
- lastSeenTs: now,
1397
- };
1398
- // 如果是首次访问,刷新 firstVisitTs
1399
- if (isFirstVisit) {
1400
- nextMeta.firstVisitTs = now;
1401
- nextMeta.createdAtTs = now;
1043
+ catch {
1044
+ // ignore
1402
1045
  }
1403
- writeUvMeta(uvMetaStorageKey, nextMeta);
1404
- firstVisitFlag = isFirstVisit;
1405
- return { uvId: existingUvId, isFirstVisit, meta: nextMeta };
1406
- })();
1407
- function safeReport(type, data) {
1408
- if (destroyed)
1409
- return;
1410
- if (!shouldSample(options.sampleRate))
1411
- return;
1412
- report(type, data);
1413
- }
1414
- function buildUvFieldsOnce(uvId, meta) {
1415
- const once = firstVisitFlag && !firstVisitConsumed;
1416
- if (once)
1417
- firstVisitConsumed = true;
1418
- return buildCommonUvFields(uvId, meta, once);
1046
+ return rawSend.apply(this, args);
1047
+ };
1048
+ }
1049
+ function installWebRequestMonitor(report, opts = {}) {
1050
+ const enabled = opts.enabled ?? true;
1051
+ if (!enabled)
1052
+ return;
1053
+ const ignoreUrls = [...DEFAULT_IGNORE$1, ...(opts.ignoreUrls ?? [])];
1054
+ if (opts.clsEndpoint)
1055
+ ignoreUrls.push(opts.clsEndpoint);
1056
+ const options = {
1057
+ enabled: true,
1058
+ reportType: opts.reportType ?? 'http',
1059
+ sampleRate: opts.sampleRate ?? 1,
1060
+ ignoreUrls,
1061
+ includeMethod: opts.includeMethod ?? true,
1062
+ includeQuery: opts.includeQuery ?? true,
1063
+ includeBody: opts.includeBody ?? true,
1064
+ maxParamLength: opts.maxParamLength ?? 2000,
1065
+ clsEndpoint: opts.clsEndpoint ?? '',
1066
+ };
1067
+ installBrowserFetch(report, options);
1068
+ installBrowserXhr(report, options);
1069
+ }
1070
+
1071
+ const DEFAULT_MAX_TEXT = 4000;
1072
+ const DEFAULT_DEDUPE_WINDOW_MS = 3000;
1073
+ const DEFAULT_DEDUPE_MAX_KEYS = 200;
1074
+ function truncate$2(s, maxLen) {
1075
+ if (!s)
1076
+ return s;
1077
+ return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
1078
+ }
1079
+ function sampleHit$1(sampleRate) {
1080
+ if (sampleRate >= 1)
1081
+ return true;
1082
+ if (sampleRate <= 0)
1083
+ return false;
1084
+ return Math.random() < sampleRate;
1085
+ }
1086
+ function getPagePath$1() {
1087
+ try {
1088
+ if (typeof window === 'undefined')
1089
+ return '';
1090
+ return window.location?.pathname ?? '';
1419
1091
  }
1420
- function reportUvOncePerSession() {
1421
- if (!uvEnabled)
1422
- return;
1423
- void uvStatePromise.then(({ uvId, meta }) => {
1424
- if (destroyed)
1425
- return;
1426
- safeReport(uvReportType, {
1427
- ...buildUvFieldsOnce(uvId, meta),
1428
- timestamp: Date.now(),
1429
- pagePath: getPagePath(),
1430
- });
1431
- });
1092
+ catch {
1093
+ return '';
1432
1094
  }
1433
- function reportPv(pagePath) {
1434
- if (!pvEnabled)
1435
- return;
1436
- void uvStatePromise.then(({ uvId, meta }) => {
1437
- if (destroyed)
1438
- return;
1439
- const payload = {
1440
- ...buildUvFieldsOnce(uvId, meta),
1441
- timestamp: Date.now(),
1442
- pagePath,
1443
- };
1444
- // Web referrer(小程序为空串)
1445
- if (typeof document !== 'undefined') {
1446
- payload.referrer = document.referrer || '';
1095
+ }
1096
+ function normalizeErrorLike(err, maxTextLength) {
1097
+ if (err && typeof err === 'object') {
1098
+ const anyErr = err;
1099
+ let rawMsg = anyErr.message;
1100
+ if (!rawMsg) {
1101
+ const str = anyErr.toString?.();
1102
+ if (!str || str === '[object Object]') {
1103
+ rawMsg = stringifyLogValue(anyErr);
1447
1104
  }
1448
- else if (envType === 'miniprogram' || isMiniProgramEnv()) {
1449
- payload.referrer = readStringStorage(lastPagePathStorageKey) || '';
1450
- writeStringStorage(lastPagePathStorageKey, pagePath);
1105
+ else {
1106
+ rawMsg = str;
1451
1107
  }
1452
- safeReport(pvReportType, payload);
1453
- });
1454
- }
1455
- // --- Web: PV ---
1456
- let removeWebPvListeners = null;
1457
- if (!destroyed && pvEnabled && typeof window !== 'undefined' && typeof history !== 'undefined') {
1458
- const originalPushState = window.history.pushState?.bind(window.history);
1459
- const originalReplaceState = window.history.replaceState?.bind(window.history);
1460
- const onRouteChanged = () => reportPv(getPagePath());
1461
- // 首次进入页面上报 PV
1462
- onRouteChanged();
1463
- // patch pushState/replaceState
1464
- if (originalPushState) {
1465
- window.history.pushState = ((...args) => {
1466
- const r = originalPushState.apply(window.history, args);
1467
- onRouteChanged();
1468
- return r;
1469
- });
1470
- }
1471
- if (originalReplaceState) {
1472
- window.history.replaceState = ((...args) => {
1473
- const r = originalReplaceState.apply(window.history, args);
1474
- onRouteChanged();
1475
- return r;
1476
- });
1477
1108
  }
1478
- window.addEventListener('popstate', onRouteChanged);
1479
- removeWebPvListeners = () => {
1480
- try {
1481
- window.removeEventListener('popstate', onRouteChanged);
1482
- }
1483
- catch {
1484
- // ignore
1485
- }
1486
- try {
1487
- if (originalPushState)
1488
- window.history.pushState = originalPushState;
1489
- if (originalReplaceState)
1490
- window.history.replaceState = originalReplaceState;
1491
- }
1492
- catch {
1493
- // ignore
1109
+ const message = truncate$2(String(rawMsg ?? ''), maxTextLength);
1110
+ const name = truncate$2(String(anyErr.name ?? ''), 200);
1111
+ const stack = truncate$2(String(anyErr.stack ?? ''), maxTextLength);
1112
+ return { message, name, stack };
1113
+ }
1114
+ const message = truncate$2(stringifyLogValue(err), maxTextLength);
1115
+ return { message, name: '', stack: '' };
1116
+ }
1117
+ function createDedupeGuard(options) {
1118
+ const cache = new Map(); // key -> lastReportAt
1119
+ const maxKeys = Math.max(0, options.dedupeMaxKeys);
1120
+ const windowMs = Math.max(0, options.dedupeWindowMs);
1121
+ function touch(key, now) {
1122
+ if (cache.has(key))
1123
+ cache.delete(key);
1124
+ cache.set(key, now);
1125
+ if (maxKeys > 0) {
1126
+ while (cache.size > maxKeys) {
1127
+ const first = cache.keys().next().value;
1128
+ if (!first)
1129
+ break;
1130
+ cache.delete(first);
1494
1131
  }
1495
- };
1132
+ }
1496
1133
  }
1497
- // --- Web: Click ---
1498
- let removeWebClickListener = null;
1499
- if (!destroyed && clickEnabled && typeof document !== 'undefined') {
1500
- const onClick = (e) => {
1501
- if (destroyed)
1502
- return;
1503
- const target = e.target;
1504
- if (!target)
1505
- return;
1506
- // 向上找最接近的带 trackId 的元素(优先)
1507
- const closestWithTrackId = typeof target.closest === 'function'
1508
- ? target.closest(`[${clickTrackIdAttr}]`)
1509
- : null;
1510
- const el = closestWithTrackId || target;
1511
- const tag = (el.tagName || '').toLowerCase();
1512
- const trackId = getAttr(el, clickTrackIdAttr);
1513
- // 过滤无效点击:白名单 tag + 没有 trackId
1514
- if (clickWhiteList.includes(tag) || !trackId)
1134
+ return (key) => {
1135
+ if (!key)
1136
+ return true;
1137
+ if (windowMs <= 0 || maxKeys === 0)
1138
+ return true;
1139
+ const now = Date.now();
1140
+ const last = cache.get(key);
1141
+ if (typeof last === 'number' && now - last < windowMs)
1142
+ return false;
1143
+ touch(key, now);
1144
+ return true;
1145
+ };
1146
+ }
1147
+ function buildErrorKey(type, payload) {
1148
+ const parts = [
1149
+ type,
1150
+ String(payload.source ?? ''),
1151
+ String(payload.pagePath ?? ''),
1152
+ String(payload.message ?? ''),
1153
+ String(payload.errorName ?? ''),
1154
+ String(payload.stack ?? ''),
1155
+ String(payload.filename ?? ''),
1156
+ String(payload.lineno ?? ''),
1157
+ String(payload.colno ?? ''),
1158
+ String(payload.tagName ?? ''),
1159
+ String(payload.resourceUrl ?? ''),
1160
+ ];
1161
+ return parts.join('|');
1162
+ }
1163
+ function installBrowserErrorMonitor(report, options) {
1164
+ if (typeof window === 'undefined')
1165
+ return;
1166
+ const w = window;
1167
+ if (w.__beLinkClsLoggerErrorInstalled__)
1168
+ return;
1169
+ w.__beLinkClsLoggerErrorInstalled__ = true;
1170
+ const shouldReport = createDedupeGuard(options);
1171
+ window.addEventListener('error', (event) => {
1172
+ try {
1173
+ if (!sampleHit$1(options.sampleRate))
1515
1174
  return;
1516
- void uvStatePromise.then(({ uvId, meta }) => {
1517
- if (destroyed)
1175
+ const payload = {
1176
+ pagePath: getPagePath$1(),
1177
+ source: 'window.error',
1178
+ };
1179
+ if (event && typeof event === 'object' && 'message' in event) {
1180
+ payload.message = truncate$2(String(event.message ?? ''), options.maxTextLength);
1181
+ payload.filename = truncate$2(String(event.filename ?? ''), 500);
1182
+ payload.lineno = typeof event.lineno === 'number' ? event.lineno : undefined;
1183
+ payload.colno = typeof event.colno === 'number' ? event.colno : undefined;
1184
+ const err = event.error;
1185
+ if (err) {
1186
+ const e = normalizeErrorLike(err, options.maxTextLength);
1187
+ if (e.name)
1188
+ payload.errorName = e.name;
1189
+ if (e.stack)
1190
+ payload.stack = e.stack;
1191
+ }
1192
+ if (!shouldReport(buildErrorKey(options.reportType, payload)))
1518
1193
  return;
1519
- safeReport(clickReportType, {
1520
- ...buildUvFieldsOnce(uvId, meta),
1521
- timestamp: Date.now(),
1522
- pagePath: getPagePath(),
1523
- elementTag: el.tagName || '',
1524
- elementId: el.id || '',
1525
- elementClass: stringifyLogValue(el.className ?? ''),
1526
- trackId: trackId || '',
1527
- elementText: truncateText((el.textContent ?? '').trim(), clickMaxTextLength),
1528
- clickX: Number.isFinite(e.clientX) ? e.clientX : 0,
1529
- clickY: Number.isFinite(e.clientY) ? e.clientY : 0,
1530
- });
1531
- });
1532
- };
1533
- document.addEventListener('click', onClick, true);
1534
- removeWebClickListener = () => {
1535
- try {
1536
- document.removeEventListener('click', onClick, true);
1537
- }
1538
- catch {
1539
- // ignore
1194
+ report(options.reportType, payload);
1195
+ return;
1540
1196
  }
1541
- };
1542
- }
1543
- // --- MiniProgram: PV (best-effort) ---
1544
- let restoreMiniProgramPatch = null;
1545
- if (!destroyed && (envType === 'miniprogram' || isMiniProgramEnv())) {
1546
- const g = globalThis;
1547
- const patchedKey = '__beLinkClsLoggerBehaviorPatched__';
1548
- if (!g[patchedKey]) {
1549
- g[patchedKey] = true;
1550
- const originalPage = typeof g.Page === 'function' ? g.Page : null;
1551
- if (originalPage) {
1552
- g.Page = function patchedPage(conf) {
1553
- const originalOnShow = conf?.onShow;
1554
- conf.onShow = function (...args) {
1555
- if (pvEnabled) {
1556
- const pagePath = getPagePath();
1557
- if (pagePath?.length > 0) {
1558
- reportPv(pagePath);
1559
- }
1560
- }
1561
- return typeof originalOnShow === 'function' ? originalOnShow.apply(this, args) : undefined;
1562
- };
1563
- // 点击:wrap 页面 methods(bindtap 等会调用到这里的 handler)
1564
- if (clickEnabled && conf && typeof conf === 'object') {
1565
- for (const key of Object.keys(conf)) {
1566
- const fn = conf[key];
1567
- if (typeof fn !== 'function')
1568
- continue;
1569
- if (fn.__beLinkWrapped__)
1570
- continue;
1571
- conf[key] = function (...args) {
1572
- try {
1573
- const e = args?.[0];
1574
- const type = e?.type;
1575
- const currentTarget = e?.currentTarget;
1576
- const dataset = currentTarget?.dataset;
1577
- const isTap = type === 'tap' || type === 'click';
1578
- if (clickEnabled && isTap && currentTarget && dataset) {
1579
- const tagNameRaw = dataset?.tagName ?? dataset?.tag ?? currentTarget?.tagName ?? '';
1580
- const tagName = String(tagNameRaw || '').toLowerCase();
1581
- const trackId = dataset?.trackId ? String(dataset.trackId) : '';
1582
- if (!(clickWhiteList.includes(tagName) && !trackId)) {
1583
- const x = typeof e?.detail?.x === 'number'
1584
- ? e.detail.x
1585
- : typeof e?.touches?.[0]?.pageX === 'number'
1586
- ? e.touches[0].pageX
1587
- : 0;
1588
- const y = typeof e?.detail?.y === 'number'
1589
- ? e.detail.y
1590
- : typeof e?.touches?.[0]?.pageY === 'number'
1591
- ? e.touches[0].pageY
1592
- : 0;
1593
- void uvStatePromise.then(({ uvId, meta }) => {
1594
- if (destroyed)
1595
- return;
1596
- safeReport(clickReportType, {
1597
- ...buildUvFieldsOnce(uvId, meta),
1598
- timestamp: Date.now(),
1599
- pagePath: getPagePath(),
1600
- elementTag: tagNameRaw ? String(tagNameRaw) : '',
1601
- elementId: currentTarget?.id ? String(currentTarget.id) : '',
1602
- elementClass: dataset?.className ? stringifyLogValue(dataset.className) : '',
1603
- trackId,
1604
- elementText: dataset?.text ? truncateText(String(dataset.text), clickMaxTextLength) : '',
1605
- clickX: x,
1606
- clickY: y,
1607
- });
1608
- });
1609
- }
1610
- }
1611
- }
1612
- catch {
1613
- // ignore
1614
- }
1615
- return fn.apply(this, args);
1616
- };
1617
- conf[key].__beLinkWrapped__ = true;
1618
- }
1619
- }
1620
- return originalPage(conf);
1621
- };
1622
- restoreMiniProgramPatch = () => {
1623
- try {
1624
- g.Page = originalPage;
1625
- g[patchedKey] = false;
1626
- }
1627
- catch {
1628
- // ignore
1629
- }
1630
- };
1197
+ if (options.captureResourceError) {
1198
+ const target = event?.target || event?.srcElement;
1199
+ const tagName = target?.tagName ? String(target.tagName) : '';
1200
+ const url = String(target?.src || target?.href || '');
1201
+ payload.source = 'resource.error';
1202
+ payload.tagName = tagName;
1203
+ payload.resourceUrl = truncate$2(url, 2000);
1204
+ if (!shouldReport(buildErrorKey(options.reportType, payload)))
1205
+ return;
1206
+ report(options.reportType, payload);
1631
1207
  }
1632
1208
  }
1633
- // 启动时也尝试报一次(避免 Page patch 未生效的场景)
1634
- if (pvEnabled)
1635
- reportPv(getPagePath());
1636
- }
1637
- // UV:每次启动上报一次(可关闭)
1638
- reportUvOncePerSession();
1639
- return () => {
1640
- if (destroyed)
1641
- return;
1642
- destroyed = true;
1209
+ catch {
1210
+ // ignore
1211
+ }
1212
+ }, true);
1213
+ window.addEventListener('unhandledrejection', (event) => {
1643
1214
  try {
1644
- removeWebPvListeners?.();
1645
- removeWebClickListener?.();
1646
- restoreMiniProgramPatch?.();
1215
+ if (!sampleHit$1(options.sampleRate))
1216
+ return;
1217
+ const reason = event?.reason;
1218
+ const e = normalizeErrorLike(reason, options.maxTextLength);
1219
+ const payload = {
1220
+ pagePath: getPagePath$1(),
1221
+ source: 'unhandledrejection',
1222
+ message: e.message,
1223
+ errorName: e.name,
1224
+ stack: e.stack,
1225
+ };
1226
+ if (!shouldReport(buildErrorKey(options.reportType, payload)))
1227
+ return;
1228
+ report(options.reportType, payload);
1647
1229
  }
1648
1230
  catch {
1649
1231
  // ignore
1650
1232
  }
1233
+ });
1234
+ }
1235
+ function installWebErrorMonitor(report, opts = {}) {
1236
+ const enabled = opts === undefined ? true : !!opts;
1237
+ if (!enabled)
1238
+ return;
1239
+ const raw = typeof opts === 'object' && opts ? opts : {};
1240
+ const options = {
1241
+ enabled: true,
1242
+ reportType: raw.reportType ?? 'error',
1243
+ sampleRate: raw.sampleRate ?? 1,
1244
+ captureResourceError: raw.captureResourceError ?? true,
1245
+ maxTextLength: raw.maxTextLength ?? DEFAULT_MAX_TEXT,
1246
+ dedupeWindowMs: raw.dedupeWindowMs ?? DEFAULT_DEDUPE_WINDOW_MS,
1247
+ dedupeMaxKeys: raw.dedupeMaxKeys ?? DEFAULT_DEDUPE_MAX_KEYS,
1651
1248
  };
1249
+ installBrowserErrorMonitor(report, options);
1652
1250
  }
1653
1251
 
1654
- function truncate(s, maxLen) {
1252
+ const DEFAULT_IGNORE = ['cls.tencentcs.com', /\/cls\//i];
1253
+ function truncate$1(s, maxLen) {
1655
1254
  if (!s)
1656
1255
  return s;
1657
1256
  return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
1658
1257
  }
1659
- function parseUserAgent(uaRaw) {
1660
- const ua = uaRaw ?? '';
1661
- const isMobile = /Mobile|Android|iPhone|iPad|iPod/i.test(ua);
1662
- // OS
1663
- let osName = 'unknown';
1664
- let osVersion = '';
1665
- const ios = ua.match(/OS (\d+[_\d]*) like Mac OS X/i);
1666
- const android = ua.match(/Android (\d+(\.\d+)*)/i);
1667
- const mac = ua.match(/Mac OS X (\d+[_\d]*)/i);
1668
- const win = ua.match(/Windows NT (\d+(\.\d+)*)/i);
1669
- if (ios) {
1670
- osName = 'iOS';
1671
- osVersion = ios[1].replace(/_/g, '.');
1672
- }
1673
- else if (android) {
1674
- osName = 'Android';
1675
- osVersion = android[1];
1676
- }
1677
- else if (win) {
1678
- osName = 'Windows';
1679
- osVersion = win[1];
1680
- }
1681
- else if (mac) {
1682
- osName = 'macOS';
1683
- osVersion = mac[1].replace(/_/g, '.');
1258
+ function sampleHit(sampleRate) {
1259
+ if (sampleRate >= 1)
1260
+ return true;
1261
+ if (sampleRate <= 0)
1262
+ return false;
1263
+ return Math.random() < sampleRate;
1264
+ }
1265
+ function shouldIgnoreUrl(url, ignoreUrls) {
1266
+ for (const rule of ignoreUrls) {
1267
+ if (typeof rule === 'string') {
1268
+ if (url.includes(rule))
1269
+ return true;
1270
+ continue;
1271
+ }
1272
+ try {
1273
+ if (rule.test(url))
1274
+ return true;
1275
+ }
1276
+ catch {
1277
+ // ignore invalid regex
1278
+ }
1684
1279
  }
1685
- // Browser
1686
- let browserName = 'unknown';
1687
- let browserVersion = '';
1688
- const edge = ua.match(/Edg\/(\d+(\.\d+)*)/);
1689
- const chrome = ua.match(/Chrome\/(\d+(\.\d+)*)/);
1690
- const safari = ua.match(/Version\/(\d+(\.\d+)*) Safari\//);
1691
- const firefox = ua.match(/Firefox\/(\d+(\.\d+)*)/);
1692
- if (edge) {
1693
- browserName = 'Edge';
1694
- browserVersion = edge[1];
1280
+ return false;
1281
+ }
1282
+ function getPagePath() {
1283
+ try {
1284
+ if (typeof window === 'undefined')
1285
+ return '';
1286
+ return window.location?.pathname ?? '';
1695
1287
  }
1696
- else if (chrome) {
1697
- browserName = 'Chrome';
1698
- browserVersion = chrome[1];
1288
+ catch {
1289
+ return '';
1699
1290
  }
1700
- else if (firefox) {
1701
- browserName = 'Firefox';
1702
- browserVersion = firefox[1];
1703
- }
1704
- else if (safari) {
1705
- browserName = 'Safari';
1706
- browserVersion = safari[1];
1707
- }
1708
- return { browserName, browserVersion, osName, osVersion, isMobile };
1709
1291
  }
1710
- function getBrowserDeviceInfo(options) {
1711
- const out = {
1712
- envType: 'browser',
1713
- };
1714
- if (typeof window === 'undefined' || typeof navigator === 'undefined')
1715
- return out;
1716
- const ua = String(navigator.userAgent ?? '');
1717
- const uaParsed = parseUserAgent(ua);
1718
- if (options.includeUserAgent)
1719
- out.ua = truncate(ua, 2000);
1720
- out.browserName = uaParsed.browserName;
1721
- out.browserVersion = uaParsed.browserVersion;
1722
- out.osName = uaParsed.osName;
1723
- out.osVersion = uaParsed.osVersion;
1724
- out.isMobile = uaParsed.isMobile ? 1 : 0;
1725
- out.language = String(navigator.language ?? '');
1726
- out.platform = String(navigator.platform ?? '');
1727
- try {
1728
- const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
1729
- out.timezone = typeof tz === 'string' ? tz : '';
1730
- }
1731
- catch {
1732
- out.timezone = '';
1733
- }
1734
- try {
1735
- const s = window.screen;
1736
- out.screenWidth = s?.width ?? undefined;
1737
- out.screenHeight = s?.height ?? undefined;
1738
- }
1739
- catch {
1740
- // ignore
1741
- }
1742
- try {
1743
- out.dpr = typeof window.devicePixelRatio === 'number' ? window.devicePixelRatio : undefined;
1744
- }
1745
- catch {
1746
- // ignore
1747
- }
1748
- try {
1749
- const navAny = navigator;
1750
- out.hardwareConcurrency = typeof navAny.hardwareConcurrency === 'number' ? navAny.hardwareConcurrency : undefined;
1751
- out.deviceMemory = typeof navAny.deviceMemory === 'number' ? navAny.deviceMemory : undefined;
1752
- }
1753
- catch {
1754
- // ignore
1755
- }
1756
- if (options.includeNetwork) {
1292
+ function reportMetric(report, reportType, metric, value, extra = {}) {
1293
+ report(reportType, {
1294
+ pagePath: getPagePath(),
1295
+ metric,
1296
+ value,
1297
+ ...extra,
1298
+ });
1299
+ }
1300
+ function installBrowserPerformanceMonitor(report, options) {
1301
+ if (typeof window === 'undefined')
1302
+ return;
1303
+ const w = window;
1304
+ if (w.__beLinkClsLoggerPerfInstalled__)
1305
+ return;
1306
+ w.__beLinkClsLoggerPerfInstalled__ = true;
1307
+ const ignoreUrls = [...DEFAULT_IGNORE, ...(options.ignoreUrls ?? [])];
1308
+ // Navigation timing: TTFB
1309
+ if (options.navigationTiming) {
1757
1310
  try {
1758
- const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
1759
- if (conn && isPlainObject(conn)) {
1760
- if (typeof conn.effectiveType === 'string')
1761
- out.netEffectiveType = conn.effectiveType;
1762
- if (typeof conn.downlink === 'number')
1763
- out.netDownlink = conn.downlink;
1764
- if (typeof conn.rtt === 'number')
1765
- out.netRtt = conn.rtt;
1766
- if (typeof conn.saveData === 'boolean')
1767
- out.netSaveData = conn.saveData ? 1 : 0;
1311
+ const navEntries = performance.getEntriesByType?.('navigation');
1312
+ const nav = Array.isArray(navEntries) ? navEntries[0] : undefined;
1313
+ if (nav && typeof nav === 'object') {
1314
+ const ttfb = typeof nav.responseStart === 'number' && typeof nav.requestStart === 'number'
1315
+ ? nav.responseStart - nav.requestStart
1316
+ : -1;
1317
+ if (ttfb >= 0 && sampleHit(options.sampleRate))
1318
+ reportMetric(report, options.reportType, 'TTFB', ttfb, { unit: 'ms' });
1768
1319
  }
1769
1320
  }
1770
1321
  catch {
1771
1322
  // ignore
1772
1323
  }
1773
1324
  }
1774
- return out;
1775
- }
1776
- function getMiniProgramDeviceInfo(options) {
1777
- const out = {
1778
- envType: 'miniprogram',
1779
- };
1780
- const wxAny = globalThis.wx;
1781
- if (!wxAny || typeof wxAny.getSystemInfoSync !== 'function')
1782
- return out;
1783
- try {
1784
- const sys = wxAny.getSystemInfoSync();
1785
- out.mpBrand = sys?.brand ? String(sys.brand) : '';
1786
- out.mpModel = sys?.model ? String(sys.model) : '';
1787
- out.mpSystem = sys?.system ? String(sys.system) : '';
1788
- out.mpPlatform = sys?.platform ? String(sys.platform) : '';
1789
- out.mpWeChatVersion = sys?.version ? String(sys.version) : '';
1790
- out.mpSDKVersion = sys?.SDKVersion ? String(sys.SDKVersion) : '';
1791
- out.mpScreenWidth = typeof sys?.screenWidth === 'number' ? sys.screenWidth : undefined;
1792
- out.mpScreenHeight = typeof sys?.screenHeight === 'number' ? sys.screenHeight : undefined;
1793
- out.mpPixelRatio = typeof sys?.pixelRatio === 'number' ? sys.pixelRatio : undefined;
1794
- out.language = sys?.language ? String(sys.language) : '';
1795
- }
1796
- catch {
1797
- // ignore
1798
- }
1799
- if (options.includeNetworkType) {
1325
+ // Web Vitals: FCP/LCP/CLS/FID
1326
+ if (options.webVitals && typeof globalThis.PerformanceObserver === 'function') {
1327
+ // FCP
1800
1328
  try {
1801
- if (typeof wxAny.getNetworkTypeSync === 'function') {
1802
- const n = wxAny.getNetworkTypeSync();
1803
- out.networkType = n?.networkType ? String(n.networkType) : '';
1804
- }
1805
- else if (typeof wxAny.getNetworkType === 'function') {
1806
- // 异步更新:先不阻塞初始化
1807
- wxAny.getNetworkType({
1808
- success: (res) => {
1809
- try {
1810
- const g = globalThis;
1811
- if (!g.__beLinkClsLoggerDeviceInfo__)
1812
- g.__beLinkClsLoggerDeviceInfo__ = {};
1813
- g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
1814
- }
1815
- catch {
1816
- // ignore
1329
+ const po = new PerformanceObserver((list) => {
1330
+ try {
1331
+ if (!sampleHit(options.sampleRate))
1332
+ return;
1333
+ for (const entry of list.getEntries()) {
1334
+ if (entry?.name === 'first-contentful-paint' && typeof entry.startTime === 'number') {
1335
+ reportMetric(report, options.reportType, 'FCP', entry.startTime, { unit: 'ms' });
1817
1336
  }
1818
- },
1819
- });
1820
- }
1337
+ }
1338
+ }
1339
+ catch {
1340
+ // ignore
1341
+ }
1342
+ });
1343
+ po.observe({ type: 'paint', buffered: true });
1821
1344
  }
1822
1345
  catch {
1823
1346
  // ignore
1824
1347
  }
1348
+ // LCP(最后一次为准)
1349
+ let lastLcp = null;
1825
1350
  try {
1826
- if (typeof wxAny.onNetworkStatusChange === 'function') {
1827
- wxAny.onNetworkStatusChange((res) => {
1828
- try {
1829
- const g = globalThis;
1830
- if (!g.__beLinkClsLoggerDeviceInfo__)
1831
- g.__beLinkClsLoggerDeviceInfo__ = {};
1832
- g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
1833
- }
1834
- catch {
1835
- // ignore
1836
- }
1837
- });
1838
- }
1351
+ const po = new PerformanceObserver((list) => {
1352
+ try {
1353
+ const entries = list.getEntries();
1354
+ if (entries && entries.length)
1355
+ lastLcp = entries[entries.length - 1];
1356
+ }
1357
+ catch {
1358
+ // ignore
1359
+ }
1360
+ });
1361
+ po.observe({ type: 'largest-contentful-paint', buffered: true });
1362
+ const flushLcp = () => {
1363
+ try {
1364
+ if (!lastLcp)
1365
+ return;
1366
+ if (!sampleHit(options.sampleRate))
1367
+ return;
1368
+ if (typeof lastLcp.startTime === 'number')
1369
+ reportMetric(report, options.reportType, 'LCP', lastLcp.startTime, { unit: 'ms' });
1370
+ lastLcp = null;
1371
+ }
1372
+ catch {
1373
+ // ignore
1374
+ }
1375
+ };
1376
+ window.addEventListener('pagehide', flushLcp, { once: true });
1377
+ document.addEventListener('visibilitychange', () => {
1378
+ if (document.visibilityState === 'hidden')
1379
+ flushLcp();
1380
+ }, { once: true });
1839
1381
  }
1840
1382
  catch {
1841
1383
  // ignore
1842
1384
  }
1843
- }
1844
- return out;
1845
- }
1846
- function createAutoDeviceInfoBaseFields(envType, opts) {
1847
- const enabled = opts === undefined ? true : !!opts;
1848
- if (!enabled)
1849
- return null;
1850
- const raw = typeof opts === 'object' && opts ? opts : {};
1851
- const options = {
1852
- includeUserAgent: raw.includeUserAgent ?? true,
1853
- includeNetwork: raw.includeNetwork ?? true,
1854
- includeNetworkType: raw.includeNetworkType ?? true,
1855
- };
1856
- // 缓存:设备信息通常不频繁变化;网络类型可能异步更新,使用全局对象增量写入
1857
- let base = null;
1858
- const globalKey = '__beLinkClsLoggerDeviceInfo__';
1859
- return () => {
1860
- if (!base) {
1861
- base =
1862
- envType === 'miniprogram' || isMiniProgramEnv()
1863
- ? getMiniProgramDeviceInfo(options)
1864
- : getBrowserDeviceInfo(options);
1865
- try {
1866
- const g = globalThis;
1867
- if (!g[globalKey])
1868
- g[globalKey] = { ...base };
1869
- }
1870
- catch {
1871
- // ignore
1872
- }
1385
+ // CLS
1386
+ try {
1387
+ let clsValue = 0;
1388
+ const po = new PerformanceObserver((list) => {
1389
+ try {
1390
+ for (const entry of list.getEntries()) {
1391
+ if (entry && entry.hadRecentInput)
1392
+ continue;
1393
+ if (typeof entry.value === 'number')
1394
+ clsValue += entry.value;
1395
+ }
1396
+ }
1397
+ catch {
1398
+ // ignore
1399
+ }
1400
+ });
1401
+ po.observe({ type: 'layout-shift', buffered: true });
1402
+ const flushCls = () => {
1403
+ try {
1404
+ if (!sampleHit(options.sampleRate))
1405
+ return;
1406
+ reportMetric(report, options.reportType, 'CLS', clsValue, { unit: 'score' });
1407
+ }
1408
+ catch {
1409
+ // ignore
1410
+ }
1411
+ };
1412
+ window.addEventListener('pagehide', flushCls, { once: true });
1413
+ document.addEventListener('visibilitychange', () => {
1414
+ if (document.visibilityState === 'hidden')
1415
+ flushCls();
1416
+ }, { once: true });
1417
+ }
1418
+ catch {
1419
+ // ignore
1873
1420
  }
1421
+ // FID
1874
1422
  try {
1875
- const g = globalThis;
1876
- const extra = g[globalKey];
1877
- if (extra && isPlainObject(extra))
1878
- return { ...base, ...extra };
1423
+ const po = new PerformanceObserver((list) => {
1424
+ try {
1425
+ if (!sampleHit(options.sampleRate))
1426
+ return;
1427
+ for (const entry of list.getEntries()) {
1428
+ const startTime = typeof entry.startTime === 'number' ? entry.startTime : -1;
1429
+ const processingStart = typeof entry.processingStart === 'number' ? entry.processingStart : -1;
1430
+ if (startTime >= 0 && processingStart >= 0) {
1431
+ reportMetric(report, options.reportType, 'FID', processingStart - startTime, { unit: 'ms' });
1432
+ break;
1433
+ }
1434
+ }
1435
+ }
1436
+ catch {
1437
+ // ignore
1438
+ }
1439
+ });
1440
+ po.observe({ type: 'first-input', buffered: true });
1879
1441
  }
1880
1442
  catch {
1881
1443
  // ignore
1882
1444
  }
1883
- return base;
1884
- };
1885
- }
1886
-
1887
- function enterClsSendingGuard() {
1888
- const g = globalThis;
1889
- const next = (g.__beLinkClsLoggerSendingCount__ ?? 0) + 1;
1890
- g.__beLinkClsLoggerSendingCount__ = next;
1891
- return () => {
1892
- const cur = g.__beLinkClsLoggerSendingCount__ ?? 0;
1893
- g.__beLinkClsLoggerSendingCount__ = cur > 0 ? cur - 1 : 0;
1894
- };
1895
- }
1896
- /**
1897
- * CLS Logger 核心基类
1898
- * - 负责所有上报、队列、监控逻辑
1899
- * - 不包含具体的 SDK 加载实现(由子类负责)
1900
- * - 这样可以把 web/mini 的 SDK 依赖彻底解耦到子入口
1901
- */
1902
- class ClsLoggerCore {
1903
- constructor() {
1904
- this.sdk = null;
1905
- this.sdkPromise = null;
1906
- this.sdkOverride = null;
1907
- this.sdkLoaderOverride = null;
1908
- this.client = null;
1909
- this.clientPromise = null;
1910
- this.topicId = null;
1911
- this.endpoint = 'ap-shanghai.cls.tencentcs.com';
1912
- this.retryTimes = 10;
1913
- this.source = '127.0.0.1';
1914
- this.enabled = true;
1915
- this.projectId = '';
1916
- this.projectName = '';
1917
- this.appId = '';
1918
- this.appVersion = '';
1919
- this.envType = 'browser';
1920
- this.userGenerateBaseFields = null;
1921
- this.autoGenerateBaseFields = null;
1922
- this.storageKey = 'beLink_logs';
1923
- this.batchSize = 15;
1924
- // 参考文档:内存队列批量发送(500ms 或 20 条触发)
1925
- this.memoryQueue = [];
1926
- this.batchMaxSize = 20;
1927
- this.batchIntervalMs = 500;
1928
- this.batchTimer = null;
1929
- this.batchTimerDueAt = null;
1930
- this.initTs = 0;
1931
- this.startupDelayMs = 0;
1932
- // 参考文档:失败缓存 + 重试
1933
- this.failedCacheKey = 'cls_failed_logs';
1934
- this.failedCacheMax = 200;
1935
- this.requestMonitorStarted = false;
1936
- this.errorMonitorStarted = false;
1937
- this.performanceMonitorStarted = false;
1938
- this.behaviorMonitorStarted = false;
1939
- this.behaviorMonitorCleanup = null;
1940
- }
1941
- /**
1942
- * 子类可按需重写(默认检测 wx)
1943
- */
1944
- detectEnvType() {
1945
- const g = globalThis;
1946
- // 微信、支付宝、字节跳动、UniApp 等小程序环境通常都有特定全局变量
1947
- if ((g.wx && typeof g.wx.getSystemInfoSync === 'function') ||
1948
- (g.my && typeof g.my.getSystemInfoSync === 'function') ||
1949
- (g.tt && typeof g.tt.getSystemInfoSync === 'function') ||
1950
- (g.uni && typeof g.uni.getSystemInfoSync === 'function')) {
1951
- return 'miniprogram';
1952
- }
1953
- return 'browser';
1954
- }
1955
- init(options) {
1956
- this.initTs = Date.now();
1957
- const topicId = options?.tencentCloud?.topicID ?? options?.topic_id ?? options?.topicID ?? this.topicId ?? null;
1958
- const endpoint = options?.tencentCloud?.endpoint ?? options?.endpoint ?? this.endpoint;
1959
- const retryTimes = options?.tencentCloud?.retry_times ?? options?.retry_times ?? this.retryTimes;
1960
- const source = options?.tencentCloud?.source ?? options?.source ?? this.source;
1961
- if (!topicId) {
1962
- // eslint-disable-next-line no-console
1963
- console.warn('ClsLogger.init 没有传 topicID/topic_id');
1964
- return;
1965
- }
1966
- const nextEnvType = options.envType ?? this.detectEnvType();
1967
- // envType/endpoint/retryTimes 变化时:重置 client(以及可能的 sdk)
1968
- const envChanged = nextEnvType !== this.envType;
1969
- const endpointChanged = endpoint !== this.endpoint;
1970
- const retryChanged = retryTimes !== this.retryTimes;
1971
- if (envChanged || endpointChanged || retryChanged) {
1972
- this.client = null;
1973
- this.clientPromise = null;
1974
- }
1975
- if (envChanged) {
1976
- this.sdk = null;
1977
- this.sdkPromise = null;
1978
- }
1979
- this.topicId = topicId;
1980
- this.endpoint = endpoint;
1981
- this.retryTimes = retryTimes;
1982
- this.source = source;
1983
- this.userId = options.userId ?? this.userId;
1984
- this.userName = options.userName ?? this.userName;
1985
- this.projectId = options.projectId ?? this.projectId;
1986
- this.projectName = options.projectName ?? this.projectName;
1987
- this.appId = options.appId ?? this.appId;
1988
- this.appVersion = options.appVersion ?? this.appVersion;
1989
- this.envType = nextEnvType;
1990
- this.enabled = options.enabled ?? true;
1991
- // 可选:外部注入 SDK(优先级:sdkLoader > sdk)
1992
- this.sdkLoaderOverride = options.sdkLoader ?? this.sdkLoaderOverride;
1993
- this.sdkOverride = options.sdk ?? this.sdkOverride;
1994
- this.userGenerateBaseFields = options.generateBaseFields ?? this.userGenerateBaseFields;
1995
- this.autoGenerateBaseFields = createAutoDeviceInfoBaseFields(this.envType, options.deviceInfo);
1996
- this.storageKey = options.storageKey ?? this.storageKey;
1997
- this.batchSize = options.batchSize ?? this.batchSize;
1998
- this.batchMaxSize = options.batch?.maxSize ?? this.batchMaxSize;
1999
- this.batchIntervalMs = options.batch?.intervalMs ?? this.batchIntervalMs;
2000
- this.startupDelayMs = options.batch?.startupDelayMs ?? this.startupDelayMs;
2001
- this.failedCacheKey = options.failedCacheKey ?? this.failedCacheKey;
2002
- this.failedCacheMax = options.failedCacheMax ?? this.failedCacheMax;
2003
- // 预热(避免首条日志触发 import/初始化开销)
2004
- void this.getInstance().catch(() => {
2005
- // ignore
2006
- });
2007
- if (this.enabled) {
2008
- // 启动时尝试发送失败缓存
2009
- this.flushFailed();
2010
- // 初始化后立即启动请求监听
2011
- this.startRequestMonitor(options.requestMonitor);
2012
- // 初始化后立即启动错误监控/性能监控
2013
- this.startErrorMonitor(options.errorMonitor);
2014
- this.startPerformanceMonitor(options.performanceMonitor);
2015
- // 初始化后立即启动行为埋点(PV/UV/点击)
2016
- this.startBehaviorMonitor(options.behaviorMonitor);
2017
- }
2018
- }
2019
- getBaseFields() {
2020
- let auto = undefined;
2021
- let user = undefined;
2022
- try {
2023
- const autoRaw = this.autoGenerateBaseFields ? this.autoGenerateBaseFields() : undefined;
2024
- if (autoRaw && isPlainObject(autoRaw))
2025
- auto = normalizeFlatFields(autoRaw, 'deviceInfo');
2026
- }
2027
- catch {
2028
- auto = undefined;
2029
- }
2030
- try {
2031
- const userRaw = this.userGenerateBaseFields ? this.userGenerateBaseFields() : undefined;
2032
- if (userRaw && isPlainObject(userRaw))
2033
- user = normalizeFlatFields({ ...userRaw }, 'generateBaseFields');
2034
- }
2035
- catch {
2036
- user = undefined;
2037
- }
2038
- if (auto && user)
2039
- return mergeFields(user, auto);
2040
- if (user)
2041
- return user;
2042
- if (auto)
2043
- return auto;
2044
- return undefined;
2045
- }
2046
- startRequestMonitor(requestMonitor) {
2047
- if (this.requestMonitorStarted)
2048
- return;
2049
- // 默认开启;传 false 则关闭
2050
- const enabled = requestMonitor === undefined ? true : !!requestMonitor;
2051
- if (!enabled)
2052
- return;
2053
- const opts = typeof requestMonitor === 'object' && requestMonitor ? requestMonitor : {};
2054
- this.requestMonitorStarted = true;
2055
- installRequestMonitor((type, data) => {
2056
- this.track(type, data);
2057
- }, {
2058
- ...opts,
2059
- enabled: opts.enabled ?? true,
2060
- clsEndpoint: this.endpoint,
2061
- });
2062
- }
2063
- startErrorMonitor(errorMonitor) {
2064
- if (this.errorMonitorStarted)
2065
- return;
2066
- const enabled = errorMonitor === undefined ? true : !!errorMonitor;
2067
- if (!enabled)
2068
- return;
2069
- this.errorMonitorStarted = true;
2070
- installErrorMonitor((type, data) => this.track(type, data), errorMonitor);
2071
- }
2072
- startPerformanceMonitor(performanceMonitor) {
2073
- if (this.performanceMonitorStarted)
2074
- return;
2075
- const enabled = performanceMonitor === undefined ? true : !!performanceMonitor;
2076
- if (!enabled)
2077
- return;
2078
- this.performanceMonitorStarted = true;
2079
- installPerformanceMonitor((type, data) => this.track(type, data), performanceMonitor);
2080
- }
2081
- startBehaviorMonitor(behaviorMonitor) {
2082
- if (this.behaviorMonitorStarted)
2083
- return;
2084
- const enabled = behaviorMonitor === undefined ? true : !!behaviorMonitor;
2085
- if (!enabled)
2086
- return;
2087
- const opts = typeof behaviorMonitor === 'object' && behaviorMonitor
2088
- ? behaviorMonitor
2089
- : {};
2090
- this.behaviorMonitorStarted = true;
2091
- this.behaviorMonitorCleanup = installBehaviorMonitor((type, data) => {
2092
- this.track(type, data);
2093
- }, this.envType, {
2094
- ...opts,
2095
- enabled: opts.enabled ?? true,
2096
- });
2097
1445
  }
2098
- /**
2099
- * 停止行为埋点监听(PV/UV/点击)
2100
- * - 如需重启:可再次调用 init(或自行调用 init 后的默认启动逻辑)
2101
- */
2102
- stopBehaviorMonitor() {
1446
+ // Resource timing:资源加载耗时
1447
+ if (options.resourceTiming && typeof globalThis.PerformanceObserver === 'function') {
2103
1448
  try {
2104
- this.behaviorMonitorCleanup?.();
2105
- }
2106
- catch {
2107
- // ignore
2108
- }
2109
- this.behaviorMonitorCleanup = null;
2110
- this.behaviorMonitorStarted = false;
2111
- }
2112
- /**
2113
- * 获取 CLS client(按环境懒加载 SDK)
2114
- */
2115
- async getInstance() {
2116
- if (this.client)
2117
- return this.client;
2118
- if (this.clientPromise)
2119
- return this.clientPromise;
2120
- this.clientPromise = this.loadSdk()
2121
- .then(({ AsyncClient }) => {
2122
- const client = new AsyncClient({
2123
- endpoint: this.endpoint,
2124
- retry_times: this.retryTimes,
1449
+ const po = new PerformanceObserver((list) => {
1450
+ try {
1451
+ if (!sampleHit(options.sampleRate))
1452
+ return;
1453
+ for (const entry of list.getEntries()) {
1454
+ const name = String(entry?.name ?? '');
1455
+ if (!name || shouldIgnoreUrl(name, ignoreUrls))
1456
+ continue;
1457
+ const initiatorType = String(entry?.initiatorType ?? '');
1458
+ // 对齐文档:关注 fetch/xhr/img/script(同时允许 css/other 但不强制)
1459
+ if (!['xmlhttprequest', 'fetch', 'img', 'script', 'css'].includes(initiatorType))
1460
+ continue;
1461
+ const payload = {
1462
+ pagePath: getPagePath(),
1463
+ metric: 'resource',
1464
+ initiatorType,
1465
+ url: truncate$1(name, options.maxTextLength),
1466
+ startTime: typeof entry?.startTime === 'number' ? entry.startTime : undefined,
1467
+ duration: typeof entry?.duration === 'number' ? entry.duration : undefined,
1468
+ };
1469
+ // 兼容字段(部分浏览器支持)
1470
+ if (typeof entry?.transferSize === 'number')
1471
+ payload.transferSize = entry.transferSize;
1472
+ if (typeof entry?.encodedBodySize === 'number')
1473
+ payload.encodedBodySize = entry.encodedBodySize;
1474
+ if (typeof entry?.decodedBodySize === 'number')
1475
+ payload.decodedBodySize = entry.decodedBodySize;
1476
+ if (typeof entry?.nextHopProtocol === 'string')
1477
+ payload.nextHopProtocol = entry.nextHopProtocol;
1478
+ if (typeof entry?.responseStatus === 'number')
1479
+ payload.status = entry.responseStatus;
1480
+ report(options.reportType, payload);
1481
+ }
1482
+ }
1483
+ catch {
1484
+ // ignore
1485
+ }
2125
1486
  });
2126
- this.client = client;
2127
- return client;
2128
- })
2129
- .catch((err) => {
2130
- // 失败后允许下次重试
2131
- this.clientPromise = null;
2132
- throw err;
2133
- });
2134
- return this.clientPromise;
2135
- }
2136
- /**
2137
- * 直接上报:埋点入参必须是一维(扁平)Object
2138
- * - 非原始值(对象/数组等)会被自动 stringify 成 string
2139
- * - 最终会把 fields 展开成 CLS 的 content(key/value 都会转成 string)
2140
- */
2141
- put(fields, options = {}) {
2142
- if (!this.enabled)
2143
- return;
2144
- if (!fields)
2145
- return;
2146
- if (!this.topicId) {
2147
- // eslint-disable-next-line no-console
2148
- console.warn('ClsLogger.put:未初始化 topic_id');
2149
- return;
1487
+ po.observe({ type: 'resource', buffered: true });
2150
1488
  }
2151
- const mergeBaseFields = options.mergeBaseFields ?? true;
2152
- const base = mergeBaseFields ? this.getBaseFields() : undefined;
2153
- const normalizedFields = normalizeFlatFields(fields, 'put');
2154
- const finalFields = mergeFields(base, {
2155
- projectId: this.projectId || undefined,
2156
- projectName: this.projectName || undefined,
2157
- envType: this.envType,
2158
- appId: this.appId || undefined,
2159
- appVersion: this.appVersion || undefined,
2160
- ...normalizedFields,
2161
- });
2162
- // 同步 API:内部异步发送,避免把网络异常冒泡到业务(尤其小程序)
2163
- void this.putAsync(finalFields).catch(() => {
1489
+ catch {
2164
1490
  // ignore
2165
- });
2166
- }
2167
- async putAsync(finalFields) {
2168
- if (!this.topicId)
2169
- return;
2170
- const sdk = await this.loadSdk();
2171
- const client = await this.getInstance();
2172
- const logGroup = new sdk.LogGroup('127.0.0.1');
2173
- logGroup.setSource(this.source);
2174
- const log = new sdk.Log(Date.now());
2175
- for (const key of Object.keys(finalFields)) {
2176
- log.addContent(key, stringifyLogValue(finalFields[key]));
2177
- }
2178
- logGroup.addLog(log);
2179
- const request = new sdk.PutLogsRequest(this.topicId, logGroup);
2180
- const exit = enterClsSendingGuard();
2181
- let p;
2182
- try {
2183
- p = client.PutLogs(request);
2184
- }
2185
- finally {
2186
- exit();
2187
1491
  }
2188
- await p;
2189
1492
  }
2190
- /**
2191
- * 直接上报:把 data 序列化后放入指定 key(默认 “日志内容”)
2192
- */
2193
- putJson(data, clsLoggerKey = '日志内容', options = {}) {
2194
- // put 的入参要求扁平;这里直接把数据序列化为 string
2195
- this.put({ [clsLoggerKey]: stringifyLogValue(data) }, options);
1493
+ }
1494
+ function installWebPerformanceMonitor(report, opts = {}) {
1495
+ const enabled = opts === undefined ? true : !!opts;
1496
+ if (!enabled)
1497
+ return;
1498
+ const raw = typeof opts === 'object' && opts ? opts : {};
1499
+ const options = {
1500
+ enabled: true,
1501
+ reportType: raw.reportType ?? 'perf',
1502
+ sampleRate: raw.sampleRate ?? 1,
1503
+ ignoreUrls: raw.ignoreUrls ?? [],
1504
+ webVitals: raw.webVitals ?? true,
1505
+ navigationTiming: raw.navigationTiming ?? true,
1506
+ resourceTiming: raw.resourceTiming ?? true,
1507
+ maxTextLength: raw.maxTextLength ?? 2000,
1508
+ };
1509
+ installBrowserPerformanceMonitor(report, options);
1510
+ }
1511
+
1512
+ function shouldSample(sampleRate) {
1513
+ const r = sampleRate ?? 1;
1514
+ if (r >= 1)
1515
+ return true;
1516
+ if (r <= 0)
1517
+ return false;
1518
+ return Math.random() < r;
1519
+ }
1520
+ function generateUUID() {
1521
+ const g = globalThis;
1522
+ if (g.crypto?.randomUUID)
1523
+ return g.crypto.randomUUID();
1524
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
1525
+ const r = Math.random() * 16 || 0;
1526
+ const v = c === 'x' ? r | 0 : ((r | 0) & 0x3) | 0x8;
1527
+ return v.toString(16);
1528
+ });
1529
+ }
1530
+ function safeReadUvMeta(key) {
1531
+ const raw = readStringStorage(key);
1532
+ if (!raw)
1533
+ return { firstVisitTs: Date.now(), visitCount: 0 };
1534
+ try {
1535
+ const parsed = JSON.parse(raw);
1536
+ if (!parsed || typeof parsed !== 'object')
1537
+ return { firstVisitTs: Date.now(), visitCount: 0 };
1538
+ const p = parsed;
1539
+ const firstVisitTs = typeof p.firstVisitTs === 'number' && Number.isFinite(p.firstVisitTs) ? p.firstVisitTs : Date.now();
1540
+ const visitCount = typeof p.visitCount === 'number' && Number.isFinite(p.visitCount) ? p.visitCount : 0;
1541
+ const createdAtTs = typeof p.createdAtTs === 'number' && Number.isFinite(p.createdAtTs) ? p.createdAtTs : undefined;
1542
+ const lastSeenTs = typeof p.lastSeenTs === 'number' && Number.isFinite(p.lastSeenTs) ? p.lastSeenTs : undefined;
1543
+ return { firstVisitTs, visitCount, createdAtTs, lastSeenTs };
2196
1544
  }
2197
- /**
2198
- * 入队:写入 localStorage 队列;达到 batchSize 自动 flush
2199
- * - 埋点入参必须是一维(扁平)Object,非原始值会被 stringify
2200
- */
2201
- enqueue(fields, options = {}) {
2202
- if (!this.enabled)
2203
- return;
2204
- if (!fields)
2205
- return;
2206
- const time = Date.now();
2207
- const mergeBaseFields = options.mergeBaseFields ?? true;
2208
- const base = mergeBaseFields ? this.getBaseFields() : undefined;
2209
- const normalizedFields = normalizeFlatFields(fields, 'enqueue');
2210
- const finalFields = mergeFields(base, {
2211
- projectId: this.projectId || undefined,
2212
- projectName: this.projectName || undefined,
2213
- envType: this.envType,
2214
- appId: this.appId || undefined,
2215
- appVersion: this.appVersion || undefined,
2216
- ...normalizedFields,
2217
- });
2218
- const queue = readQueue(this.storageKey);
2219
- const next = [...queue, { time, data: finalFields }];
2220
- if (next.length < this.batchSize) {
2221
- writeQueue(this.storageKey, next);
2222
- return;
2223
- }
2224
- // 达到阈值:flush + 写入新的队列(避免并发下丢失,按“先 flush 旧的”策略)
2225
- this.putBatch(queue);
2226
- writeQueue(this.storageKey, [{ time, data: finalFields }]);
1545
+ catch {
1546
+ return { firstVisitTs: Date.now(), visitCount: 0 };
2227
1547
  }
2228
- /**
2229
- * localStorage 读取队列并批量上报
2230
- */
2231
- flush() {
2232
- const queue = readQueue(this.storageKey);
2233
- if (queue.length === 0)
2234
- return;
2235
- this.putBatch(queue);
2236
- writeQueue(this.storageKey, []);
1548
+ }
1549
+ function writeUvMeta(key, meta) {
1550
+ writeStringStorage(key, JSON.stringify(meta));
1551
+ }
1552
+ function getWebPagePath() {
1553
+ if (typeof window === 'undefined')
1554
+ return '';
1555
+ return window.location?.pathname || '';
1556
+ }
1557
+ function buildCommonUvFields(uvId, uvMeta, isFirstVisit) {
1558
+ return {
1559
+ uvId,
1560
+ isFirstVisit,
1561
+ firstVisitTs: uvMeta.firstVisitTs,
1562
+ visitCount: uvMeta.visitCount,
1563
+ };
1564
+ }
1565
+ function getAttr(el, attrName) {
1566
+ try {
1567
+ return el.getAttribute(attrName) ?? '';
2237
1568
  }
2238
- /**
2239
- * 批量上报(每条 item.data 展开为 log content)
2240
- */
2241
- putBatch(queue) {
2242
- if (!this.enabled)
2243
- return;
2244
- if (!queue || queue.length === 0)
2245
- return;
2246
- if (!this.topicId) {
2247
- // eslint-disable-next-line no-console
2248
- console.warn('ClsLogger.putBatch:未初始化 topic_id');
2249
- return;
2250
- }
2251
- void this.putBatchAsync(queue).catch(() => {
2252
- // ignore
2253
- });
1569
+ catch {
1570
+ return '';
2254
1571
  }
2255
- async putBatchAsync(queue) {
2256
- if (!this.topicId)
2257
- return;
2258
- const sdk = await this.loadSdk();
2259
- const client = await this.getInstance();
2260
- const logGroup = new sdk.LogGroup('127.0.0.1');
2261
- logGroup.setSource(this.source);
2262
- for (const item of queue) {
2263
- const log = new sdk.Log(item.time);
2264
- const data = item.data ?? {};
2265
- for (const key of Object.keys(data)) {
2266
- log.addContent(key, stringifyLogValue(data[key]));
2267
- }
2268
- logGroup.addLog(log);
1572
+ }
1573
+ function truncateText(s, maxLen) {
1574
+ if (!s)
1575
+ return '';
1576
+ if (s.length <= maxLen)
1577
+ return s;
1578
+ return s.slice(0, maxLen);
1579
+ }
1580
+ function installWebBehaviorMonitor(report, options = {}) {
1581
+ const enableTrack = options.enableTrack ?? options.enabled ?? true;
1582
+ if (!enableTrack)
1583
+ return () => { };
1584
+ const pvEnabled = options.pv ?? true;
1585
+ const uvEnabled = options.uv ?? true;
1586
+ const clickEnabled = options.click ?? true;
1587
+ const pvReportType = options.pvReportType ?? 'pv';
1588
+ const uvReportType = options.uvReportType ?? 'uv';
1589
+ const clickReportType = options.clickReportType ?? 'click';
1590
+ const uvIdStorageKey = options.uvIdStorageKey ?? 'cls_uv_id';
1591
+ const uvMetaStorageKey = options.uvMetaStorageKey ?? 'cls_uv_meta';
1592
+ const uvExpireDaysRaw = options.trackOptions?.uvExpireDays ?? options.uvExpireDays ?? 30;
1593
+ const uvExpireDays = Number.isFinite(uvExpireDaysRaw) ? Math.max(0, uvExpireDaysRaw) : 30;
1594
+ const uvExpireMs = uvExpireDays * 24 * 60 * 60 * 1000;
1595
+ const clickWhiteList = (options.trackOptions?.clickWhiteList ?? options.clickWhiteList ?? ['body', 'html']).map((s) => String(s).toLowerCase());
1596
+ const clickTrackIdAttr = options.clickTrackIdAttr ?? 'data-track-id';
1597
+ const clickMaxTextLength = options.clickMaxTextLength ?? 120;
1598
+ const getPagePath = options.getPagePath ?? getWebPagePath;
1599
+ let destroyed = false;
1600
+ let firstVisitFlag = false;
1601
+ let firstVisitConsumed = false;
1602
+ const uvStatePromise = (async () => {
1603
+ let existingUvId = readStringStorage(uvIdStorageKey);
1604
+ let isFirstVisit = false;
1605
+ const now = Date.now();
1606
+ const metaBefore = safeReadUvMeta(uvMetaStorageKey);
1607
+ const lastSeenForExpire = metaBefore.lastSeenTs ?? metaBefore.createdAtTs ?? metaBefore.firstVisitTs ?? now;
1608
+ const expired = uvExpireMs > 0 && now - lastSeenForExpire > uvExpireMs;
1609
+ if (expired) {
1610
+ existingUvId = null;
1611
+ writeUvMeta(uvMetaStorageKey, { firstVisitTs: now, visitCount: 0, createdAtTs: now, lastSeenTs: now });
1612
+ writeStringStorage(uvIdStorageKey, '');
2269
1613
  }
2270
- if (logGroup.getLogs().length === 0)
2271
- return;
2272
- const request = new sdk.PutLogsRequest(this.topicId, logGroup);
2273
- const exit = enterClsSendingGuard();
2274
- let p;
2275
1614
  try {
2276
- p = client.PutLogs(request);
1615
+ if (options.getUvId) {
1616
+ const maybe = options.getUvId();
1617
+ const resolved = typeof maybe?.then === 'function' ? await maybe : maybe;
1618
+ if (resolved && typeof resolved === 'string')
1619
+ existingUvId = resolved;
1620
+ }
2277
1621
  }
2278
- finally {
2279
- exit();
1622
+ catch {
1623
+ /* ignore */
2280
1624
  }
2281
- await p;
2282
- }
2283
- /**
2284
- * 参考《一、概述》:统一上报入口(内存队列 + 批量发送)
2285
- */
2286
- report(log) {
2287
- if (!this.enabled)
2288
- return;
2289
- if (!log?.type)
2290
- return;
2291
- if (!this.topicId) {
2292
- // eslint-disable-next-line no-console
2293
- console.warn('ClsLogger.report:未初始化 topicID/topic_id');
2294
- return;
1625
+ if (!existingUvId) {
1626
+ existingUvId = generateUUID();
1627
+ isFirstVisit = true;
2295
1628
  }
2296
- this.memoryQueue.push(log);
2297
- if (this.memoryQueue.length >= this.batchMaxSize) {
2298
- void this.flushBatch();
2299
- return;
1629
+ writeStringStorage(uvIdStorageKey, existingUvId);
1630
+ const meta = safeReadUvMeta(uvMetaStorageKey);
1631
+ const createdAt = meta.createdAtTs ?? meta.firstVisitTs ?? now;
1632
+ const firstVisit = meta.firstVisitTs || now;
1633
+ const nextMeta = {
1634
+ firstVisitTs: firstVisit,
1635
+ visitCount: (meta.visitCount || 0) + 1,
1636
+ createdAtTs: createdAt,
1637
+ lastSeenTs: now,
1638
+ };
1639
+ if (isFirstVisit) {
1640
+ nextMeta.firstVisitTs = now;
1641
+ nextMeta.createdAtTs = now;
2300
1642
  }
2301
- const now = Date.now();
2302
- const desiredDueAt = this.getDesiredBatchFlushDueAt(now);
2303
- const desiredDelay = Math.max(0, desiredDueAt - now);
2304
- if (!this.batchTimer) {
2305
- this.batchTimerDueAt = desiredDueAt;
2306
- this.batchTimer = setTimeout(() => {
2307
- void this.flushBatch();
2308
- }, desiredDelay);
1643
+ writeUvMeta(uvMetaStorageKey, nextMeta);
1644
+ firstVisitFlag = isFirstVisit;
1645
+ return { uvId: existingUvId, isFirstVisit, meta: nextMeta };
1646
+ })();
1647
+ function safeReport(type, data) {
1648
+ if (destroyed)
1649
+ return;
1650
+ if (!shouldSample(options.sampleRate))
1651
+ return;
1652
+ report(type, data);
1653
+ }
1654
+ function buildUvFieldsOnce(uvId, meta) {
1655
+ const once = firstVisitFlag && !firstVisitConsumed;
1656
+ if (once)
1657
+ firstVisitConsumed = true;
1658
+ return buildCommonUvFields(uvId, meta, once);
1659
+ }
1660
+ function reportPv(pagePath) {
1661
+ if (!pvEnabled)
2309
1662
  return;
1663
+ void uvStatePromise.then(({ uvId, meta }) => {
1664
+ if (destroyed)
1665
+ return;
1666
+ const payload = {
1667
+ ...buildUvFieldsOnce(uvId, meta),
1668
+ timestamp: Date.now(),
1669
+ pagePath,
1670
+ referrer: typeof document !== 'undefined' ? document.referrer || '' : '',
1671
+ };
1672
+ safeReport(pvReportType, payload);
1673
+ });
1674
+ }
1675
+ // Web PV Listeners
1676
+ let removeWebPvListeners = null;
1677
+ if (pvEnabled && typeof window !== 'undefined' && typeof history !== 'undefined') {
1678
+ const originalPushState = window.history.pushState?.bind(window.history);
1679
+ const originalReplaceState = window.history.replaceState?.bind(window.history);
1680
+ const onRouteChanged = () => reportPv(getPagePath());
1681
+ onRouteChanged();
1682
+ if (originalPushState) {
1683
+ window.history.pushState = ((...args) => {
1684
+ const r = originalPushState.apply(window.history, args);
1685
+ onRouteChanged();
1686
+ return r;
1687
+ });
2310
1688
  }
2311
- // 启动合并窗口内:如果当前 timer 会“更早”触发,则延后到窗口结束,尽量减少多次发送
2312
- if (this.batchTimerDueAt !== null && this.batchTimerDueAt < desiredDueAt) {
2313
- try {
2314
- clearTimeout(this.batchTimer);
2315
- }
2316
- catch {
2317
- // ignore
2318
- }
2319
- this.batchTimerDueAt = desiredDueAt;
2320
- this.batchTimer = setTimeout(() => {
2321
- void this.flushBatch();
2322
- }, desiredDelay);
1689
+ if (originalReplaceState) {
1690
+ window.history.replaceState = ((...args) => {
1691
+ const r = originalReplaceState.apply(window.history, args);
1692
+ onRouteChanged();
1693
+ return r;
1694
+ });
2323
1695
  }
1696
+ window.addEventListener('popstate', onRouteChanged);
1697
+ removeWebPvListeners = () => {
1698
+ window.removeEventListener('popstate', onRouteChanged);
1699
+ if (originalPushState)
1700
+ window.history.pushState = originalPushState;
1701
+ if (originalReplaceState)
1702
+ window.history.replaceState = originalReplaceState;
1703
+ };
2324
1704
  }
2325
- getDesiredBatchFlushDueAt(nowTs) {
2326
- const start = this.initTs || nowTs;
2327
- const startupDelay = Number.isFinite(this.startupDelayMs) ? Math.max(0, this.startupDelayMs) : 0;
2328
- if (startupDelay > 0) {
2329
- const end = start + startupDelay;
2330
- if (nowTs < end)
2331
- return end;
2332
- }
2333
- return nowTs + this.batchIntervalMs;
1705
+ // Web Click Listener
1706
+ let removeWebClickListener = null;
1707
+ if (clickEnabled && typeof document !== 'undefined') {
1708
+ const onClick = (e) => {
1709
+ if (destroyed)
1710
+ return;
1711
+ const target = e.target;
1712
+ if (!target)
1713
+ return;
1714
+ const closestWithTrackId = typeof target.closest === 'function'
1715
+ ? target.closest(`[${clickTrackIdAttr}]`)
1716
+ : null;
1717
+ const el = closestWithTrackId || target;
1718
+ const tag = (el.tagName || '').toLowerCase();
1719
+ const trackId = getAttr(el, clickTrackIdAttr);
1720
+ if (clickWhiteList.includes(tag) || !trackId)
1721
+ return;
1722
+ void uvStatePromise.then(({ uvId, meta }) => {
1723
+ if (destroyed)
1724
+ return;
1725
+ safeReport(clickReportType, {
1726
+ ...buildUvFieldsOnce(uvId, meta),
1727
+ timestamp: Date.now(),
1728
+ pagePath: getPagePath(),
1729
+ elementTag: el.tagName || '',
1730
+ elementId: el.id || '',
1731
+ elementClass: stringifyLogValue(el.className ?? ''),
1732
+ trackId: trackId || '',
1733
+ elementText: truncateText((el.textContent ?? '').trim(), clickMaxTextLength),
1734
+ clickX: Number.isFinite(e.clientX) ? e.clientX : 0,
1735
+ clickY: Number.isFinite(e.clientY) ? e.clientY : 0,
1736
+ });
1737
+ });
1738
+ };
1739
+ document.addEventListener('click', onClick, true);
1740
+ removeWebClickListener = () => document.removeEventListener('click', onClick, true);
1741
+ }
1742
+ // UV Initial Report
1743
+ if (uvEnabled) {
1744
+ void uvStatePromise.then(({ uvId, meta }) => {
1745
+ if (destroyed)
1746
+ return;
1747
+ safeReport(uvReportType, {
1748
+ ...buildUvFieldsOnce(uvId, meta),
1749
+ timestamp: Date.now(),
1750
+ pagePath: getPagePath(),
1751
+ });
1752
+ });
1753
+ }
1754
+ return () => {
1755
+ destroyed = true;
1756
+ removeWebPvListeners?.();
1757
+ removeWebClickListener?.();
1758
+ };
1759
+ }
1760
+
1761
+ function truncate(s, maxLen) {
1762
+ if (!s)
1763
+ return s;
1764
+ return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
1765
+ }
1766
+ function parseUserAgent(uaRaw) {
1767
+ const ua = uaRaw ?? '';
1768
+ const isMobile = /Mobile|Android|iPhone|iPad|iPod/i.test(ua);
1769
+ // OS
1770
+ let osName = 'unknown';
1771
+ let osVersion = '';
1772
+ const ios = ua.match(/OS (\d+[_\d]*) like Mac OS X/i);
1773
+ const android = ua.match(/Android (\d+(\.\d+)*)/i);
1774
+ const mac = ua.match(/Mac OS X (\d+[_\d]*)/i);
1775
+ const win = ua.match(/Windows NT (\d+(\.\d+)*)/i);
1776
+ if (ios) {
1777
+ osName = 'iOS';
1778
+ osVersion = ios[1].replace(/_/g, '.');
1779
+ }
1780
+ else if (android) {
1781
+ osName = 'Android';
1782
+ osVersion = android[1];
1783
+ }
1784
+ else if (win) {
1785
+ osName = 'Windows';
1786
+ osVersion = win[1];
1787
+ }
1788
+ else if (mac) {
1789
+ osName = 'macOS';
1790
+ osVersion = mac[1].replace(/_/g, '.');
1791
+ }
1792
+ // Browser
1793
+ let browserName = 'unknown';
1794
+ let browserVersion = '';
1795
+ const edge = ua.match(/Edg\/(\d+(\.\d+)*)/);
1796
+ const chrome = ua.match(/Chrome\/(\d+(\.\d+)*)/);
1797
+ const safari = ua.match(/Version\/(\d+(\.\d+)*) Safari\//);
1798
+ const firefox = ua.match(/Firefox\/(\d+(\.\d+)*)/);
1799
+ if (edge) {
1800
+ browserName = 'Edge';
1801
+ browserVersion = edge[1];
1802
+ }
1803
+ else if (chrome) {
1804
+ browserName = 'Chrome';
1805
+ browserVersion = chrome[1];
1806
+ }
1807
+ else if (firefox) {
1808
+ browserName = 'Firefox';
1809
+ browserVersion = firefox[1];
1810
+ }
1811
+ else if (safari) {
1812
+ browserName = 'Safari';
1813
+ browserVersion = safari[1];
1814
+ }
1815
+ return { browserName, browserVersion, osName, osVersion, isMobile };
1816
+ }
1817
+ function getBrowserDeviceInfo(options) {
1818
+ const out = {
1819
+ envType: 'browser',
1820
+ };
1821
+ if (typeof window === 'undefined' || typeof navigator === 'undefined')
1822
+ return out;
1823
+ const ua = String(navigator.userAgent ?? '');
1824
+ const uaParsed = parseUserAgent(ua);
1825
+ if (options.includeUserAgent)
1826
+ out.ua = truncate(ua, 2000);
1827
+ out.browserName = uaParsed.browserName;
1828
+ out.browserVersion = uaParsed.browserVersion;
1829
+ out.osName = uaParsed.osName;
1830
+ out.osVersion = uaParsed.osVersion;
1831
+ out.isMobile = uaParsed.isMobile ? 1 : 0;
1832
+ out.language = String(navigator.language ?? '');
1833
+ out.platform = String(navigator.platform ?? '');
1834
+ try {
1835
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
1836
+ out.timezone = typeof tz === 'string' ? tz : '';
2334
1837
  }
2335
- info(message, data = {}) {
2336
- let msg = '';
2337
- let extra = {};
2338
- if (message instanceof Error) {
2339
- msg = message.message;
2340
- extra = {
2341
- stack: message.stack,
2342
- name: message.name,
2343
- ...data,
2344
- };
2345
- }
2346
- else {
2347
- msg = String(message);
2348
- extra = data;
2349
- }
2350
- const payload = normalizeFlatFields({ message: msg, ...extra }, 'info');
2351
- this.report({ type: 'info', data: payload, timestamp: Date.now() });
1838
+ catch {
1839
+ out.timezone = '';
2352
1840
  }
2353
- warn(message, data = {}) {
2354
- let msg = '';
2355
- let extra = {};
2356
- if (message instanceof Error) {
2357
- msg = message.message;
2358
- extra = {
2359
- stack: message.stack,
2360
- name: message.name,
2361
- ...data,
2362
- };
2363
- }
2364
- else {
2365
- msg = String(message);
2366
- extra = data;
2367
- }
2368
- const payload = normalizeFlatFields({ message: msg, ...extra }, 'warn');
2369
- this.report({ type: 'warn', data: payload, timestamp: Date.now() });
1841
+ try {
1842
+ const s = window.screen;
1843
+ out.screenWidth = s?.width ?? undefined;
1844
+ out.screenHeight = s?.height ?? undefined;
2370
1845
  }
2371
- error(message, data = {}) {
2372
- let msg = '';
2373
- let extra = {};
2374
- if (message instanceof Error) {
2375
- msg = message.message;
2376
- extra = {
2377
- stack: message.stack,
2378
- name: message.name,
2379
- ...data,
2380
- };
2381
- }
2382
- else {
2383
- msg = String(message);
2384
- extra = data;
2385
- }
2386
- const payload = normalizeFlatFields({ message: msg, ...extra }, 'error');
2387
- this.report({ type: 'error', data: payload, timestamp: Date.now() });
1846
+ catch {
1847
+ // ignore
2388
1848
  }
2389
- track(trackType, data = {}) {
2390
- if (!trackType)
2391
- return;
2392
- this.report({
2393
- type: trackType,
2394
- data: normalizeFlatFields(data, `track:${trackType}`),
2395
- timestamp: Date.now(),
2396
- });
1849
+ try {
1850
+ out.dpr = typeof window.devicePixelRatio === 'number' ? window.devicePixelRatio : undefined;
2397
1851
  }
2398
- /**
2399
- * 立即发送内存队列
2400
- */
2401
- async flushBatch() {
2402
- if (this.batchTimer) {
2403
- clearTimeout(this.batchTimer);
2404
- this.batchTimer = null;
2405
- }
2406
- this.batchTimerDueAt = null;
2407
- if (this.memoryQueue.length === 0)
2408
- return;
2409
- const logs = [...this.memoryQueue];
2410
- this.memoryQueue = [];
2411
- try {
2412
- await this.sendReportLogs(logs);
2413
- }
2414
- catch {
2415
- this.retrySendReportLogs(logs, 1);
2416
- }
1852
+ catch {
1853
+ // ignore
2417
1854
  }
2418
- buildReportFields(log) {
2419
- const ts = log.timestamp ?? Date.now();
2420
- const base = this.getBaseFields();
2421
- const data = normalizeFlatFields(log.data ?? {}, 'report:data');
2422
- const mergedData = mergeFields(base, data);
2423
- return {
2424
- timestamp: ts,
2425
- type: log.type,
2426
- envType: this.envType,
2427
- projectId: this.projectId || undefined,
2428
- projectName: this.projectName || undefined,
2429
- appId: this.appId || undefined,
2430
- appVersion: this.appVersion || undefined,
2431
- // 保证“一维字段”:业务数据以 JSON 字符串形式落到 CLS
2432
- ...mergedData,
2433
- };
1855
+ try {
1856
+ const navAny = navigator;
1857
+ out.hardwareConcurrency = typeof navAny.hardwareConcurrency === 'number' ? navAny.hardwareConcurrency : undefined;
1858
+ out.deviceMemory = typeof navAny.deviceMemory === 'number' ? navAny.deviceMemory : undefined;
2434
1859
  }
2435
- async sendReportLogs(logs) {
2436
- if (!this.topicId)
2437
- return;
2438
- const sdk = await this.loadSdk();
2439
- const client = await this.getInstance();
2440
- const logGroup = new sdk.LogGroup('127.0.0.1');
2441
- logGroup.setSource(this.source);
2442
- for (const item of logs) {
2443
- const fields = this.buildReportFields(item);
2444
- const log = new sdk.Log(fields.timestamp);
2445
- for (const key of Object.keys(fields)) {
2446
- if (key === 'timestamp')
2447
- continue;
2448
- log.addContent(key, stringifyLogValue(fields[key]));
2449
- }
2450
- logGroup.addLog(log);
2451
- }
2452
- const request = new sdk.PutLogsRequest(this.topicId, logGroup);
2453
- // 只在“发起网络请求”的同步阶段打标记,避免 requestMonitor 监控 CLS 上报请求导致递归
2454
- const exit = enterClsSendingGuard();
2455
- let p;
1860
+ catch {
1861
+ // ignore
1862
+ }
1863
+ if (options.includeNetwork) {
2456
1864
  try {
2457
- p = client.PutLogs(request);
1865
+ const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
1866
+ if (conn && isPlainObject(conn)) {
1867
+ if (typeof conn.effectiveType === 'string')
1868
+ out.netEffectiveType = conn.effectiveType;
1869
+ if (typeof conn.downlink === 'number')
1870
+ out.netDownlink = conn.downlink;
1871
+ if (typeof conn.rtt === 'number')
1872
+ out.netRtt = conn.rtt;
1873
+ if (typeof conn.saveData === 'boolean')
1874
+ out.netSaveData = conn.saveData ? 1 : 0;
1875
+ }
2458
1876
  }
2459
- finally {
2460
- exit();
1877
+ catch {
1878
+ // ignore
2461
1879
  }
2462
- await p;
2463
1880
  }
2464
- retrySendReportLogs(logs, retryCount) {
2465
- if (retryCount > this.retryTimes) {
2466
- this.cacheFailedReportLogs(logs);
2467
- return;
2468
- }
2469
- const delayMs = Math.pow(2, retryCount) * 1000;
2470
- setTimeout(async () => {
1881
+ return out;
1882
+ }
1883
+ function createWebDeviceInfoBaseFields(opts) {
1884
+ const enabled = opts === undefined ? true : !!opts;
1885
+ if (!enabled)
1886
+ return null;
1887
+ const raw = typeof opts === 'object' && opts ? opts : {};
1888
+ const options = {
1889
+ includeUserAgent: raw.includeUserAgent ?? true,
1890
+ includeNetwork: raw.includeNetwork ?? true,
1891
+ includeNetworkType: raw.includeNetworkType ?? true,
1892
+ };
1893
+ let base = null;
1894
+ const globalKey = '__beLinkClsLoggerDeviceInfo__';
1895
+ return () => {
1896
+ if (!base) {
1897
+ base = getBrowserDeviceInfo(options);
2471
1898
  try {
2472
- await this.sendReportLogs(logs);
1899
+ const g = globalThis;
1900
+ if (!g[globalKey])
1901
+ g[globalKey] = { ...base };
2473
1902
  }
2474
1903
  catch {
2475
- this.retrySendReportLogs(logs, retryCount + 1);
1904
+ // ignore
2476
1905
  }
2477
- }, delayMs);
2478
- }
2479
- cacheFailedReportLogs(logs) {
2480
- const raw = readStringStorage(this.failedCacheKey);
2481
- let current = [];
2482
- try {
2483
- const parsed = raw ? JSON.parse(raw) : [];
2484
- current = Array.isArray(parsed) ? parsed : [];
2485
1906
  }
2486
- catch {
2487
- current = [];
2488
- }
2489
- const next = [...current, ...logs].slice(-this.failedCacheMax);
2490
- writeStringStorage(this.failedCacheKey, JSON.stringify(next));
2491
- }
2492
- flushFailed() {
2493
- if (!this.enabled)
2494
- return;
2495
- const raw = readStringStorage(this.failedCacheKey);
2496
- if (!raw)
2497
- return;
2498
- let logs = [];
2499
1907
  try {
2500
- const parsed = JSON.parse(raw);
2501
- logs = Array.isArray(parsed) ? parsed : [];
1908
+ const g = globalThis;
1909
+ const extra = g[globalKey];
1910
+ if (extra && isPlainObject(extra))
1911
+ return { ...base, ...extra };
2502
1912
  }
2503
1913
  catch {
2504
- logs = [];
1914
+ // ignore
2505
1915
  }
2506
- if (logs.length === 0)
2507
- return;
2508
- // 先清空,再尝试发送
2509
- writeStringStorage(this.failedCacheKey, JSON.stringify([]));
2510
- this.memoryQueue.unshift(...logs);
2511
- void this.flushBatch();
2512
- }
2513
- /**
2514
- * 统计/计数类日志:按字段展开上报(若 data 为空默认 1)
2515
- */
2516
- stat(param) {
2517
- if (!param)
2518
- return;
2519
- const payload = normalizeFlatFields({
2520
- pagePath: typeof window !== 'undefined' ? window.location?.pathname : '',
2521
- projectId: this.projectId,
2522
- projectName: this.projectName,
2523
- ...param,
2524
- data: param.data ?? 1,
2525
- }, 'stat');
2526
- this.report({ type: 'stat', data: payload, timestamp: Date.now() });
2527
- }
2528
- }
2529
-
2530
- function readGlobal(key) {
2531
- try {
2532
- const g = globalThis;
2533
- return g[key] ?? null;
2534
- }
2535
- catch {
2536
- return null;
2537
- }
1916
+ return base;
1917
+ };
2538
1918
  }
2539
1919
 
2540
- // 静态引用 web sdk
1920
+ // 移除静态引用,改为安全的 tryRequire + 动态加载,避免在未安装 SDK 时报错
2541
1921
  class ClsLoggerWeb extends ClsLoggerCore {
2542
1922
  constructor() {
2543
1923
  super(...arguments);
@@ -2546,15 +1926,50 @@ class ClsLoggerWeb extends ClsLoggerCore {
2546
1926
  async loadSdk() {
2547
1927
  if (this.sdk)
2548
1928
  return this.sdk;
2549
- // 优先用 UMD 全局变量(如果存在)
1929
+ // 1) 优先用 UMD 全局变量(如果存在)
2550
1930
  const g = readGlobal('tencentcloudClsSdkJsWeb');
2551
1931
  if (g && g.AsyncClient) {
2552
1932
  this.sdk = this.normalize(g);
2553
1933
  return this.sdk;
2554
1934
  }
2555
- // 否则用静态 import
2556
- this.sdk = this.normalize(WebSdk__namespace);
2557
- return this.sdk;
1935
+ // 2) 尝试同步 tryRequire
1936
+ const req = tryRequire('tencentcloud-cls-sdk-js-web');
1937
+ if (req) {
1938
+ const sdk = this.normalize(req);
1939
+ if (sdk) {
1940
+ this.sdk = sdk;
1941
+ return sdk;
1942
+ }
1943
+ }
1944
+ // 3) 最后尝试带 ignore 的动态导入
1945
+ try {
1946
+ const m = await import(/* @vite-ignore */ 'tencentcloud-cls-sdk-js-web');
1947
+ const sdk = this.normalize(m);
1948
+ if (sdk) {
1949
+ this.sdk = sdk;
1950
+ return sdk;
1951
+ }
1952
+ }
1953
+ catch {
1954
+ // ignore
1955
+ }
1956
+ console.warn('[ClsLogger] Optional SDK "tencentcloud-cls-sdk-js-web" not found. Logging will be disabled.');
1957
+ throw new Error('SDK not found');
1958
+ }
1959
+ installRequestMonitor(report, options) {
1960
+ installWebRequestMonitor(report, options);
1961
+ }
1962
+ installErrorMonitor(report, options) {
1963
+ installWebErrorMonitor(report, options);
1964
+ }
1965
+ installPerformanceMonitor(report, options) {
1966
+ installWebPerformanceMonitor(report, options);
1967
+ }
1968
+ installBehaviorMonitor(report, options) {
1969
+ return installWebBehaviorMonitor(report, typeof options === 'boolean' ? {} : options);
1970
+ }
1971
+ createDeviceInfoBaseFields(options) {
1972
+ return createWebDeviceInfoBaseFields(options);
2558
1973
  }
2559
1974
  normalize(m) {
2560
1975
  const mod = (m?.default && m.default.AsyncClient ? m.default : m);