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