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