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