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