@be-link/cls-logger 1.0.1-beta.11 → 1.0.1-beta.13

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