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