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