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