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