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