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