@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/mini.esm.js
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import * as MiniSdk from 'tencentcloud-cls-sdk-js-mini';
|
|
2
|
-
|
|
3
1
|
function isPlainObject(value) {
|
|
4
2
|
return Object.prototype.toString.call(value) === '[object Object]';
|
|
5
3
|
}
|
|
@@ -133,2329 +131,1607 @@ 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;
|
|
278
|
+
const userRaw = this.userGenerateBaseFields ? this.userGenerateBaseFields() : undefined;
|
|
279
|
+
if (userRaw && isPlainObject(userRaw))
|
|
280
|
+
user = normalizeFlatFields({ ...userRaw }, 'generateBaseFields');
|
|
267
281
|
}
|
|
268
|
-
catch
|
|
269
|
-
|
|
270
|
-
const payload = buildPayload({
|
|
271
|
-
url: absUrl,
|
|
272
|
-
method,
|
|
273
|
-
query,
|
|
274
|
-
body,
|
|
275
|
-
startTime: startTs,
|
|
276
|
-
duration,
|
|
277
|
-
success: false,
|
|
278
|
-
error: err,
|
|
279
|
-
options,
|
|
280
|
-
});
|
|
281
|
-
if (payload)
|
|
282
|
-
report(options.reportType, payload);
|
|
283
|
-
throw err;
|
|
282
|
+
catch {
|
|
283
|
+
user = undefined;
|
|
284
284
|
}
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
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() {
|
|
300
344
|
try {
|
|
301
|
-
this.
|
|
302
|
-
this.__beLinkClsLoggerUrl__ = String(args[1] ?? '');
|
|
345
|
+
this.behaviorMonitorCleanup?.();
|
|
303
346
|
}
|
|
304
347
|
catch {
|
|
305
348
|
// ignore
|
|
306
349
|
}
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
XHR.prototype.send = function (...args) {
|
|
310
|
-
// CLS SDK 发起上报时:跳过监控,避免递归上报
|
|
311
|
-
if (isClsSendingNow())
|
|
312
|
-
return rawSend.apply(this, args);
|
|
313
|
-
const startTs = Date.now();
|
|
314
|
-
try {
|
|
315
|
-
const method = String(this.__beLinkClsLoggerMethod__ ?? 'GET');
|
|
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
|
-
}
|
|
369
|
-
}
|
|
370
|
-
catch {
|
|
371
|
-
// ignore
|
|
372
|
-
}
|
|
373
|
-
return rawSend.apply(this, args);
|
|
374
|
-
};
|
|
375
|
-
}
|
|
376
|
-
function installMiniProgramWxRequest(report, options) {
|
|
377
|
-
const wxAny = globalThis.wx;
|
|
378
|
-
if (!wxAny || typeof wxAny.request !== 'function')
|
|
379
|
-
return;
|
|
380
|
-
if (wxAny.__beLinkClsLoggerWxRequestInstalled__)
|
|
381
|
-
return;
|
|
382
|
-
wxAny.__beLinkClsLoggerWxRequestInstalled__ = true;
|
|
383
|
-
const rawRequest = wxAny.request.bind(wxAny);
|
|
384
|
-
wxAny.request = (reqOptions) => {
|
|
385
|
-
const startTs = Date.now();
|
|
386
|
-
try {
|
|
387
|
-
const url = String(reqOptions?.url ?? '');
|
|
388
|
-
const method = String(reqOptions?.method ?? 'GET');
|
|
389
|
-
const data = reqOptions?.data;
|
|
390
|
-
const wrapCb = (cb, success) => {
|
|
391
|
-
return (res) => {
|
|
392
|
-
try {
|
|
393
|
-
const duration = Date.now() - startTs;
|
|
394
|
-
const status = typeof res?.statusCode === 'number'
|
|
395
|
-
? res.statusCode
|
|
396
|
-
: typeof res?.status === 'number'
|
|
397
|
-
? res.status
|
|
398
|
-
: undefined;
|
|
399
|
-
const payload = buildPayload({
|
|
400
|
-
url,
|
|
401
|
-
method,
|
|
402
|
-
query: '',
|
|
403
|
-
body: data,
|
|
404
|
-
startTime: startTs,
|
|
405
|
-
duration,
|
|
406
|
-
status,
|
|
407
|
-
success,
|
|
408
|
-
error: success ? undefined : res,
|
|
409
|
-
options,
|
|
410
|
-
});
|
|
411
|
-
if (payload)
|
|
412
|
-
report(options.reportType, payload);
|
|
413
|
-
}
|
|
414
|
-
catch {
|
|
415
|
-
// ignore
|
|
416
|
-
}
|
|
417
|
-
if (typeof cb === 'function')
|
|
418
|
-
return cb(res);
|
|
419
|
-
return undefined;
|
|
420
|
-
};
|
|
421
|
-
};
|
|
422
|
-
const next = { ...(reqOptions ?? {}) };
|
|
423
|
-
next.success = wrapCb(next.success, true);
|
|
424
|
-
next.fail = wrapCb(next.fail, false);
|
|
425
|
-
return rawRequest(next);
|
|
426
|
-
}
|
|
427
|
-
catch {
|
|
428
|
-
// ignore
|
|
429
|
-
}
|
|
430
|
-
return rawRequest(reqOptions);
|
|
431
|
-
};
|
|
432
|
-
}
|
|
433
|
-
function installMiniProgramWxCloudCallFunction(report, options) {
|
|
434
|
-
const wxAny = globalThis.wx;
|
|
435
|
-
const cloud = wxAny?.cloud;
|
|
436
|
-
if (!cloud || typeof cloud.callFunction !== 'function')
|
|
437
|
-
return;
|
|
438
|
-
if (cloud.__beLinkClsLoggerWxCloudCallFunctionInstalled__)
|
|
439
|
-
return;
|
|
440
|
-
cloud.__beLinkClsLoggerWxCloudCallFunctionInstalled__ = true;
|
|
441
|
-
const rawCallFunction = cloud.callFunction.bind(cloud);
|
|
442
|
-
cloud.callFunction = (callOptions) => {
|
|
443
|
-
const startTs = Date.now();
|
|
444
|
-
const name = (() => {
|
|
445
|
-
try {
|
|
446
|
-
return String(callOptions?.name ?? '');
|
|
447
|
-
}
|
|
448
|
-
catch {
|
|
449
|
-
return '';
|
|
450
|
-
}
|
|
451
|
-
})();
|
|
452
|
-
const data = callOptions?.data;
|
|
453
|
-
let reported = false;
|
|
454
|
-
const onDone = (success, err) => {
|
|
455
|
-
if (reported)
|
|
456
|
-
return;
|
|
457
|
-
reported = true;
|
|
458
|
-
try {
|
|
459
|
-
const duration = Date.now() - startTs;
|
|
460
|
-
const payload = buildPayload({
|
|
461
|
-
// 统一走 url 字段,便于和 http 一起检索/聚合
|
|
462
|
-
url: `cloud.callFunction/${name || 'unknown'}`,
|
|
463
|
-
method: 'callFunction',
|
|
464
|
-
query: '',
|
|
465
|
-
body: data,
|
|
466
|
-
startTime: startTs,
|
|
467
|
-
duration,
|
|
468
|
-
success,
|
|
469
|
-
error: success ? undefined : err,
|
|
470
|
-
options,
|
|
471
|
-
});
|
|
472
|
-
if (payload) {
|
|
473
|
-
payload.requestType = 'cloud-function';
|
|
474
|
-
payload.name = name || 'unknown';
|
|
475
|
-
report(options.reportType, payload);
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
catch {
|
|
479
|
-
// ignore
|
|
480
|
-
}
|
|
481
|
-
};
|
|
482
|
-
try {
|
|
483
|
-
const next = { ...(callOptions ?? {}) };
|
|
484
|
-
const rawSuccess = next.success;
|
|
485
|
-
const rawFail = next.fail;
|
|
486
|
-
next.success = (res) => {
|
|
487
|
-
onDone(true);
|
|
488
|
-
if (typeof rawSuccess === 'function')
|
|
489
|
-
return rawSuccess(res);
|
|
490
|
-
return undefined;
|
|
491
|
-
};
|
|
492
|
-
next.fail = (err) => {
|
|
493
|
-
onDone(false, err?.message ?? err);
|
|
494
|
-
if (typeof rawFail === 'function')
|
|
495
|
-
return rawFail(err);
|
|
496
|
-
return undefined;
|
|
497
|
-
};
|
|
498
|
-
const ret = rawCallFunction(next);
|
|
499
|
-
// 兼容 Promise 风格(有些版本/写法不传 success/fail)
|
|
500
|
-
if (ret && typeof ret.then === 'function') {
|
|
501
|
-
ret.then(() => onDone(true), (err) => onDone(false, err?.message ?? err));
|
|
502
|
-
}
|
|
503
|
-
return ret;
|
|
504
|
-
}
|
|
505
|
-
catch (err) {
|
|
506
|
-
onDone(false, err);
|
|
507
|
-
throw err;
|
|
508
|
-
}
|
|
509
|
-
};
|
|
510
|
-
}
|
|
511
|
-
function installRequestMonitor(report, opts = {}) {
|
|
512
|
-
const enabled = opts.enabled ?? true;
|
|
513
|
-
if (!enabled)
|
|
514
|
-
return;
|
|
515
|
-
const ignoreUrls = [...DEFAULT_IGNORE$1, ...(opts.ignoreUrls ?? [])];
|
|
516
|
-
if (opts.clsEndpoint)
|
|
517
|
-
ignoreUrls.push(opts.clsEndpoint);
|
|
518
|
-
const options = {
|
|
519
|
-
enabled: true,
|
|
520
|
-
reportType: opts.reportType ?? 'http',
|
|
521
|
-
sampleRate: opts.sampleRate ?? 1,
|
|
522
|
-
ignoreUrls,
|
|
523
|
-
includeMethod: opts.includeMethod ?? true,
|
|
524
|
-
includeQuery: opts.includeQuery ?? true,
|
|
525
|
-
includeBody: opts.includeBody ?? true,
|
|
526
|
-
maxParamLength: opts.maxParamLength ?? 2000,
|
|
527
|
-
clsEndpoint: opts.clsEndpoint ?? '',
|
|
528
|
-
};
|
|
529
|
-
if (isMiniProgramEnv()) {
|
|
530
|
-
installMiniProgramWxRequest(report, options);
|
|
531
|
-
installMiniProgramWxCloudCallFunction(report, options);
|
|
532
|
-
return;
|
|
533
|
-
}
|
|
534
|
-
installBrowserFetch(report, options);
|
|
535
|
-
installBrowserXhr(report, options);
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
const DEFAULT_MAX_TEXT = 4000;
|
|
539
|
-
const DEFAULT_DEDUPE_WINDOW_MS = 3000;
|
|
540
|
-
const DEFAULT_DEDUPE_MAX_KEYS = 200;
|
|
541
|
-
function truncate$2(s, maxLen) {
|
|
542
|
-
if (!s)
|
|
543
|
-
return s;
|
|
544
|
-
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
545
|
-
}
|
|
546
|
-
function sampleHit$1(sampleRate) {
|
|
547
|
-
if (sampleRate >= 1)
|
|
548
|
-
return true;
|
|
549
|
-
if (sampleRate <= 0)
|
|
550
|
-
return false;
|
|
551
|
-
return Math.random() < sampleRate;
|
|
552
|
-
}
|
|
553
|
-
function getPagePath$1() {
|
|
554
|
-
try {
|
|
555
|
-
if (typeof window === 'undefined')
|
|
556
|
-
return '';
|
|
557
|
-
return window.location?.pathname ?? '';
|
|
558
|
-
}
|
|
559
|
-
catch {
|
|
560
|
-
return '';
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
function normalizeErrorLike(err, maxTextLength) {
|
|
564
|
-
if (err && typeof err === 'object') {
|
|
565
|
-
const anyErr = err;
|
|
566
|
-
let rawMsg = anyErr.message;
|
|
567
|
-
if (!rawMsg) {
|
|
568
|
-
const str = anyErr.toString?.();
|
|
569
|
-
if (!str || str === '[object Object]') {
|
|
570
|
-
rawMsg = stringifyLogValue(anyErr);
|
|
571
|
-
}
|
|
572
|
-
else {
|
|
573
|
-
rawMsg = str;
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
const message = truncate$2(String(rawMsg ?? ''), maxTextLength);
|
|
577
|
-
const name = truncate$2(String(anyErr.name ?? ''), 200);
|
|
578
|
-
const stack = truncate$2(String(anyErr.stack ?? ''), maxTextLength);
|
|
579
|
-
return { message, name, stack };
|
|
580
|
-
}
|
|
581
|
-
const message = truncate$2(stringifyLogValue(err), maxTextLength);
|
|
582
|
-
return { message, name: '', stack: '' };
|
|
583
|
-
}
|
|
584
|
-
function createDedupeGuard(options) {
|
|
585
|
-
const cache = new Map(); // key -> lastReportAt
|
|
586
|
-
const maxKeys = Math.max(0, options.dedupeMaxKeys);
|
|
587
|
-
const windowMs = Math.max(0, options.dedupeWindowMs);
|
|
588
|
-
function touch(key, now) {
|
|
589
|
-
// refresh insertion order
|
|
590
|
-
if (cache.has(key))
|
|
591
|
-
cache.delete(key);
|
|
592
|
-
cache.set(key, now);
|
|
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);
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
return (key) => {
|
|
603
|
-
if (!key)
|
|
604
|
-
return true;
|
|
605
|
-
if (windowMs <= 0 || maxKeys === 0)
|
|
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) => {
|
|
641
|
-
try {
|
|
642
|
-
if (!sampleHit$1(options.sampleRate))
|
|
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
|
-
}
|
|
679
|
-
}
|
|
680
|
-
catch {
|
|
681
|
-
// ignore
|
|
682
|
-
}
|
|
683
|
-
}, true);
|
|
684
|
-
window.addEventListener('unhandledrejection', (event) => {
|
|
685
|
-
try {
|
|
686
|
-
if (!sampleHit$1(options.sampleRate))
|
|
687
|
-
return;
|
|
688
|
-
const reason = event?.reason;
|
|
689
|
-
const e = normalizeErrorLike(reason, options.maxTextLength);
|
|
690
|
-
const payload = {
|
|
691
|
-
pagePath: getPagePath$1(),
|
|
692
|
-
source: 'unhandledrejection',
|
|
693
|
-
message: e.message,
|
|
694
|
-
errorName: e.name,
|
|
695
|
-
stack: e.stack,
|
|
696
|
-
};
|
|
697
|
-
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
698
|
-
return;
|
|
699
|
-
report(options.reportType, payload);
|
|
700
|
-
}
|
|
701
|
-
catch {
|
|
702
|
-
// ignore
|
|
703
|
-
}
|
|
704
|
-
});
|
|
705
|
-
}
|
|
706
|
-
function installMiniProgramErrorMonitor(report, options) {
|
|
707
|
-
const g = globalThis;
|
|
708
|
-
if (g.__beLinkClsLoggerMpErrorInstalled__)
|
|
709
|
-
return;
|
|
710
|
-
g.__beLinkClsLoggerMpErrorInstalled__ = true;
|
|
711
|
-
const shouldReport = createDedupeGuard(options);
|
|
712
|
-
const wxAny = globalThis.wx;
|
|
713
|
-
// wx.* 事件(兼容在 App 已经创建后的场景)
|
|
714
|
-
try {
|
|
715
|
-
if (wxAny && typeof wxAny.onError === 'function') {
|
|
716
|
-
wxAny.onError((msg) => {
|
|
717
|
-
try {
|
|
718
|
-
if (!sampleHit$1(options.sampleRate))
|
|
719
|
-
return;
|
|
720
|
-
const e = normalizeErrorLike(msg, options.maxTextLength);
|
|
721
|
-
const payload = {
|
|
722
|
-
source: 'wx.onError',
|
|
723
|
-
message: e.message,
|
|
724
|
-
errorName: e.name,
|
|
725
|
-
stack: e.stack,
|
|
726
|
-
};
|
|
727
|
-
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
728
|
-
return;
|
|
729
|
-
report(options.reportType, payload);
|
|
730
|
-
}
|
|
731
|
-
catch {
|
|
732
|
-
// ignore
|
|
733
|
-
}
|
|
734
|
-
});
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
catch {
|
|
738
|
-
// ignore
|
|
739
|
-
}
|
|
740
|
-
try {
|
|
741
|
-
if (wxAny && typeof wxAny.onUnhandledRejection === 'function') {
|
|
742
|
-
wxAny.onUnhandledRejection((res) => {
|
|
743
|
-
try {
|
|
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
|
-
});
|
|
761
|
-
}
|
|
762
|
-
}
|
|
763
|
-
catch {
|
|
764
|
-
// ignore
|
|
765
|
-
}
|
|
766
|
-
// 包装 App({...}) 注入 onError/onUnhandledRejection(推荐)
|
|
767
|
-
try {
|
|
768
|
-
if (typeof g.App === 'function' && !g.__beLinkClsLoggerAppWrapped__) {
|
|
769
|
-
g.__beLinkClsLoggerAppWrapped__ = true;
|
|
770
|
-
const rawApp = g.App;
|
|
771
|
-
g.App = (appOptions) => {
|
|
772
|
-
const next = { ...(appOptions ?? {}) };
|
|
773
|
-
const rawOnError = next.onError;
|
|
774
|
-
next.onError = function (...args) {
|
|
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);
|
|
819
|
-
};
|
|
820
|
-
}
|
|
821
|
-
}
|
|
822
|
-
catch {
|
|
823
|
-
// ignore
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
function installErrorMonitor(report, opts = {}) {
|
|
827
|
-
const enabled = opts === undefined ? true : !!opts;
|
|
828
|
-
if (!enabled)
|
|
829
|
-
return;
|
|
830
|
-
const raw = typeof opts === 'object' && opts ? opts : {};
|
|
831
|
-
const options = {
|
|
832
|
-
enabled: true,
|
|
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;
|
|
843
|
-
}
|
|
844
|
-
installBrowserErrorMonitor(report, options);
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
const DEFAULT_IGNORE = ['cls.tencentcs.com', /\/cls\//i];
|
|
848
|
-
function truncate$1(s, maxLen) {
|
|
849
|
-
if (!s)
|
|
850
|
-
return s;
|
|
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;
|
|
866
|
-
}
|
|
867
|
-
try {
|
|
868
|
-
if (rule.test(url))
|
|
869
|
-
return true;
|
|
870
|
-
}
|
|
871
|
-
catch {
|
|
872
|
-
// ignore invalid regex
|
|
873
|
-
}
|
|
874
|
-
}
|
|
875
|
-
return false;
|
|
876
|
-
}
|
|
877
|
-
function getPagePath() {
|
|
878
|
-
try {
|
|
879
|
-
if (typeof window === 'undefined')
|
|
880
|
-
return '';
|
|
881
|
-
return window.location?.pathname ?? '';
|
|
882
|
-
}
|
|
883
|
-
catch {
|
|
884
|
-
return '';
|
|
885
|
-
}
|
|
886
|
-
}
|
|
887
|
-
function reportMetric(report, reportType, metric, value, extra = {}) {
|
|
888
|
-
report(reportType, {
|
|
889
|
-
pagePath: getPagePath(),
|
|
890
|
-
metric,
|
|
891
|
-
value,
|
|
892
|
-
...extra,
|
|
893
|
-
});
|
|
894
|
-
}
|
|
895
|
-
function installBrowserPerformanceMonitor(report, options) {
|
|
896
|
-
if (typeof window === 'undefined')
|
|
897
|
-
return;
|
|
898
|
-
const w = window;
|
|
899
|
-
if (w.__beLinkClsLoggerPerfInstalled__)
|
|
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' });
|
|
914
|
-
}
|
|
915
|
-
}
|
|
916
|
-
catch {
|
|
917
|
-
// ignore
|
|
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;
|
|
945
|
-
try {
|
|
946
|
-
const po = new PerformanceObserver((list) => {
|
|
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
|
|
979
|
-
}
|
|
980
|
-
// CLS
|
|
981
|
-
try {
|
|
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 });
|
|
1012
|
-
}
|
|
1013
|
-
catch {
|
|
1014
|
-
// ignore
|
|
1015
|
-
}
|
|
1016
|
-
// FID
|
|
1017
|
-
try {
|
|
1018
|
-
const po = new PerformanceObserver((list) => {
|
|
1019
|
-
try {
|
|
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 });
|
|
1036
|
-
}
|
|
1037
|
-
catch {
|
|
1038
|
-
// ignore
|
|
1039
|
-
}
|
|
1040
|
-
}
|
|
1041
|
-
// Resource timing:资源加载耗时
|
|
1042
|
-
if (options.resourceTiming && typeof globalThis.PerformanceObserver === 'function') {
|
|
1043
|
-
try {
|
|
1044
|
-
const po = new PerformanceObserver((list) => {
|
|
1045
|
-
try {
|
|
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 });
|
|
1083
|
-
}
|
|
1084
|
-
catch {
|
|
1085
|
-
// ignore
|
|
1086
|
-
}
|
|
1087
|
-
}
|
|
1088
|
-
}
|
|
1089
|
-
function installMiniProgramPerformanceMonitor(report, options) {
|
|
1090
|
-
const g = globalThis;
|
|
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;
|
|
1097
|
-
try {
|
|
1098
|
-
const perf = ctx.getPerformance();
|
|
1099
|
-
if (!perf || typeof perf.createObserver !== 'function')
|
|
1100
|
-
return;
|
|
1101
|
-
const observer = perf.createObserver((entryList) => {
|
|
1102
|
-
try {
|
|
1103
|
-
const entries = entryList.getEntries();
|
|
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
|
-
}
|
|
1135
|
-
}
|
|
1136
|
-
catch {
|
|
1137
|
-
// ignore
|
|
1138
|
-
}
|
|
1139
|
-
});
|
|
1140
|
-
observer.observe({ entryTypes: ['navigation', 'render'] });
|
|
1141
|
-
}
|
|
1142
|
-
catch {
|
|
1143
|
-
// ignore
|
|
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;
|
|
1164
|
-
}
|
|
1165
|
-
installBrowserPerformanceMonitor(report, options);
|
|
1166
|
-
}
|
|
1167
|
-
|
|
1168
|
-
function shouldSample(sampleRate) {
|
|
1169
|
-
const r = sampleRate ?? 1;
|
|
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
|
|
1178
|
-
const g = globalThis;
|
|
1179
|
-
if (g.crypto?.randomUUID)
|
|
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
|
-
});
|
|
1187
|
-
}
|
|
1188
|
-
function safeReadUvMeta(key) {
|
|
1189
|
-
const raw = readStringStorage(key);
|
|
1190
|
-
if (!raw)
|
|
1191
|
-
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1192
|
-
try {
|
|
1193
|
-
const parsed = JSON.parse(raw);
|
|
1194
|
-
if (!parsed || typeof parsed !== 'object')
|
|
1195
|
-
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1196
|
-
const p = parsed;
|
|
1197
|
-
const firstVisitTs = typeof p.firstVisitTs === 'number' && Number.isFinite(p.firstVisitTs) ? p.firstVisitTs : Date.now();
|
|
1198
|
-
const visitCount = typeof p.visitCount === 'number' && Number.isFinite(p.visitCount) ? p.visitCount : 0;
|
|
1199
|
-
const createdAtTs = typeof p.createdAtTs === 'number' && Number.isFinite(p.createdAtTs) ? p.createdAtTs : undefined;
|
|
1200
|
-
const lastSeenTs = typeof p.lastSeenTs === 'number' && Number.isFinite(p.lastSeenTs) ? p.lastSeenTs : undefined;
|
|
1201
|
-
return { firstVisitTs, visitCount, createdAtTs, lastSeenTs };
|
|
1202
|
-
}
|
|
1203
|
-
catch {
|
|
1204
|
-
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1205
|
-
}
|
|
1206
|
-
}
|
|
1207
|
-
function writeUvMeta(key, meta) {
|
|
1208
|
-
writeStringStorage(key, JSON.stringify(meta));
|
|
1209
|
-
}
|
|
1210
|
-
function getWebPagePath() {
|
|
1211
|
-
if (typeof window === 'undefined')
|
|
1212
|
-
return '';
|
|
1213
|
-
return window.location?.pathname || '';
|
|
1214
|
-
}
|
|
1215
|
-
function getMiniProgramPagePath() {
|
|
1216
|
-
const g = globalThis;
|
|
1217
|
-
try {
|
|
1218
|
-
const pages = typeof g.getCurrentPages === 'function' ? g.getCurrentPages() : [];
|
|
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
|
-
}
|
|
1226
|
-
}
|
|
1227
|
-
function buildCommonUvFields(uvId, uvMeta, isFirstVisit) {
|
|
1228
|
-
return {
|
|
1229
|
-
uvId,
|
|
1230
|
-
isFirstVisit,
|
|
1231
|
-
firstVisitTs: uvMeta.firstVisitTs,
|
|
1232
|
-
visitCount: uvMeta.visitCount,
|
|
1233
|
-
};
|
|
1234
|
-
}
|
|
1235
|
-
function getAttr(el, attrName) {
|
|
1236
|
-
try {
|
|
1237
|
-
return el.getAttribute(attrName) ?? '';
|
|
1238
|
-
}
|
|
1239
|
-
catch {
|
|
1240
|
-
return '';
|
|
1241
|
-
}
|
|
1242
|
-
}
|
|
1243
|
-
function truncateText(s, maxLen) {
|
|
1244
|
-
if (!s)
|
|
1245
|
-
return '';
|
|
1246
|
-
if (s.length <= maxLen)
|
|
1247
|
-
return s;
|
|
1248
|
-
return s.slice(0, maxLen);
|
|
1249
|
-
}
|
|
1250
|
-
function installBehaviorMonitor(report, envType, options = {}) {
|
|
1251
|
-
const enableTrack = options.enableTrack ?? options.enabled ?? true;
|
|
1252
|
-
if (!enableTrack)
|
|
1253
|
-
return () => { };
|
|
1254
|
-
const pvEnabled = options.pv ?? true;
|
|
1255
|
-
const uvEnabled = options.uv ?? true;
|
|
1256
|
-
const clickEnabled = options.click ?? true;
|
|
1257
|
-
const pvReportType = options.pvReportType ?? 'pv';
|
|
1258
|
-
const uvReportType = options.uvReportType ?? 'uv';
|
|
1259
|
-
const clickReportType = options.clickReportType ?? 'click';
|
|
1260
|
-
const uvIdStorageKey = options.uvIdStorageKey ?? 'cls_uv_id';
|
|
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,优先使用;否则本地生成
|
|
1295
|
-
try {
|
|
1296
|
-
if (options.getUvId) {
|
|
1297
|
-
const maybe = options.getUvId();
|
|
1298
|
-
const resolved = typeof maybe?.then === 'function' ? await maybe : maybe;
|
|
1299
|
-
if (resolved && typeof resolved === 'string')
|
|
1300
|
-
existingUvId = resolved;
|
|
1301
|
-
}
|
|
1302
|
-
}
|
|
1303
|
-
catch {
|
|
1304
|
-
// ignore
|
|
1305
|
-
}
|
|
1306
|
-
// 小程序:默认尝试 openid / 设备标识(兼容你给的参考实现)
|
|
1307
|
-
if (!existingUvId && (envType === 'miniprogram' || isMiniProgramEnv())) {
|
|
1308
|
-
const wxAny = globalThis.wx;
|
|
1309
|
-
try {
|
|
1310
|
-
const userInfo = wxAny?.getStorageSync?.('userInfo');
|
|
1311
|
-
if (userInfo?.openid)
|
|
1312
|
-
existingUvId = String(userInfo.openid);
|
|
1313
|
-
}
|
|
1314
|
-
catch {
|
|
1315
|
-
// ignore
|
|
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);
|
|
1401
|
-
}
|
|
1402
|
-
safeReport(pvReportType, payload);
|
|
1403
|
-
});
|
|
1404
|
-
}
|
|
1405
|
-
// --- Web: PV ---
|
|
1406
|
-
let removeWebPvListeners = null;
|
|
1407
|
-
if (!destroyed && pvEnabled && typeof window !== 'undefined' && typeof history !== 'undefined') {
|
|
1408
|
-
const originalPushState = window.history.pushState?.bind(window.history);
|
|
1409
|
-
const originalReplaceState = window.history.replaceState?.bind(window.history);
|
|
1410
|
-
const onRouteChanged = () => reportPv(getPagePath());
|
|
1411
|
-
// 首次进入页面上报 PV
|
|
1412
|
-
onRouteChanged();
|
|
1413
|
-
// patch pushState/replaceState
|
|
1414
|
-
if (originalPushState) {
|
|
1415
|
-
window.history.pushState = ((...args) => {
|
|
1416
|
-
const r = originalPushState.apply(window.history, args);
|
|
1417
|
-
onRouteChanged();
|
|
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;
|
|
1426
|
-
});
|
|
1427
|
-
}
|
|
1428
|
-
window.addEventListener('popstate', onRouteChanged);
|
|
1429
|
-
removeWebPvListeners = () => {
|
|
1430
|
-
try {
|
|
1431
|
-
window.removeEventListener('popstate', onRouteChanged);
|
|
1432
|
-
}
|
|
1433
|
-
catch {
|
|
1434
|
-
// ignore
|
|
1435
|
-
}
|
|
1436
|
-
try {
|
|
1437
|
-
if (originalPushState)
|
|
1438
|
-
window.history.pushState = originalPushState;
|
|
1439
|
-
if (originalReplaceState)
|
|
1440
|
-
window.history.replaceState = originalReplaceState;
|
|
1441
|
-
}
|
|
1442
|
-
catch {
|
|
1443
|
-
// ignore
|
|
1444
|
-
}
|
|
1445
|
-
};
|
|
350
|
+
this.behaviorMonitorCleanup = null;
|
|
351
|
+
this.behaviorMonitorStarted = false;
|
|
1446
352
|
}
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
const
|
|
1458
|
-
|
|
1459
|
-
:
|
|
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
|
-
});
|
|
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,
|
|
1481
366
|
});
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
};
|
|
367
|
+
this.client = client;
|
|
368
|
+
return client;
|
|
369
|
+
})
|
|
370
|
+
.catch((err) => {
|
|
371
|
+
// 失败后允许下次重试
|
|
372
|
+
this.clientPromise = null;
|
|
373
|
+
throw err;
|
|
374
|
+
});
|
|
375
|
+
return this.clientPromise;
|
|
1492
376
|
}
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
if (pagePath?.length > 0) {
|
|
1508
|
-
reportPv(pagePath);
|
|
1509
|
-
}
|
|
1510
|
-
}
|
|
1511
|
-
return typeof originalOnShow === 'function' ? originalOnShow.apply(this, args) : undefined;
|
|
1512
|
-
};
|
|
1513
|
-
// 点击:wrap 页面 methods(bindtap 等会调用到这里的 handler)
|
|
1514
|
-
if (clickEnabled && conf && typeof conf === 'object') {
|
|
1515
|
-
for (const key of Object.keys(conf)) {
|
|
1516
|
-
const fn = conf[key];
|
|
1517
|
-
if (typeof fn !== 'function')
|
|
1518
|
-
continue;
|
|
1519
|
-
if (fn.__beLinkWrapped__)
|
|
1520
|
-
continue;
|
|
1521
|
-
conf[key] = function (...args) {
|
|
1522
|
-
try {
|
|
1523
|
-
const e = args?.[0];
|
|
1524
|
-
const type = e?.type;
|
|
1525
|
-
const currentTarget = e?.currentTarget;
|
|
1526
|
-
const dataset = currentTarget?.dataset;
|
|
1527
|
-
const isTap = type === 'tap' || type === 'click';
|
|
1528
|
-
if (clickEnabled && isTap && currentTarget && dataset) {
|
|
1529
|
-
const tagNameRaw = dataset?.tagName ?? dataset?.tag ?? currentTarget?.tagName ?? '';
|
|
1530
|
-
const tagName = String(tagNameRaw || '').toLowerCase();
|
|
1531
|
-
const trackId = dataset?.trackId ? String(dataset.trackId) : '';
|
|
1532
|
-
if (!(clickWhiteList.includes(tagName) && !trackId)) {
|
|
1533
|
-
const x = typeof e?.detail?.x === 'number'
|
|
1534
|
-
? e.detail.x
|
|
1535
|
-
: typeof e?.touches?.[0]?.pageX === 'number'
|
|
1536
|
-
? e.touches[0].pageX
|
|
1537
|
-
: 0;
|
|
1538
|
-
const y = typeof e?.detail?.y === 'number'
|
|
1539
|
-
? e.detail.y
|
|
1540
|
-
: typeof e?.touches?.[0]?.pageY === 'number'
|
|
1541
|
-
? e.touches[0].pageY
|
|
1542
|
-
: 0;
|
|
1543
|
-
void uvStatePromise.then(({ uvId, meta }) => {
|
|
1544
|
-
if (destroyed)
|
|
1545
|
-
return;
|
|
1546
|
-
safeReport(clickReportType, {
|
|
1547
|
-
...buildUvFieldsOnce(uvId, meta),
|
|
1548
|
-
timestamp: Date.now(),
|
|
1549
|
-
pagePath: getPagePath(),
|
|
1550
|
-
elementTag: tagNameRaw ? String(tagNameRaw) : '',
|
|
1551
|
-
elementId: currentTarget?.id ? String(currentTarget.id) : '',
|
|
1552
|
-
elementClass: dataset?.className ? stringifyLogValue(dataset.className) : '',
|
|
1553
|
-
trackId,
|
|
1554
|
-
elementText: dataset?.text ? truncateText(String(dataset.text), clickMaxTextLength) : '',
|
|
1555
|
-
clickX: x,
|
|
1556
|
-
clickY: y,
|
|
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 = () => {
|
|
1573
|
-
try {
|
|
1574
|
-
g.Page = originalPage;
|
|
1575
|
-
g[patchedKey] = false;
|
|
1576
|
-
}
|
|
1577
|
-
catch {
|
|
1578
|
-
// ignore
|
|
1579
|
-
}
|
|
1580
|
-
};
|
|
1581
|
-
}
|
|
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;
|
|
1582
391
|
}
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
392
|
+
const mergeBaseFields = options.mergeBaseFields ?? true;
|
|
393
|
+
const base = mergeBaseFields ? this.getBaseFields() : undefined;
|
|
394
|
+
const normalizedFields = normalizeFlatFields(fields, 'put');
|
|
395
|
+
const finalFields = mergeFields(base, {
|
|
396
|
+
projectId: this.projectId || undefined,
|
|
397
|
+
projectName: this.projectName || undefined,
|
|
398
|
+
envType: this.envType,
|
|
399
|
+
appId: this.appId || undefined,
|
|
400
|
+
appVersion: this.appVersion || undefined,
|
|
401
|
+
...normalizedFields,
|
|
402
|
+
});
|
|
403
|
+
// 同步 API:内部异步发送,避免把网络异常冒泡到业务(尤其小程序)
|
|
404
|
+
void this.putAsync(finalFields).catch(() => {
|
|
405
|
+
// ignore
|
|
406
|
+
});
|
|
1586
407
|
}
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
return () => {
|
|
1590
|
-
if (destroyed)
|
|
408
|
+
async putAsync(finalFields) {
|
|
409
|
+
if (!this.topicId)
|
|
1591
410
|
return;
|
|
1592
|
-
|
|
411
|
+
const sdk = await this.loadSdk();
|
|
412
|
+
const client = await this.getInstance();
|
|
413
|
+
const logGroup = new sdk.LogGroup('127.0.0.1');
|
|
414
|
+
logGroup.setSource(this.source);
|
|
415
|
+
const log = new sdk.Log(Date.now());
|
|
416
|
+
for (const key of Object.keys(finalFields)) {
|
|
417
|
+
log.addContent(key, stringifyLogValue(finalFields[key]));
|
|
418
|
+
}
|
|
419
|
+
logGroup.addLog(log);
|
|
420
|
+
const request = new sdk.PutLogsRequest(this.topicId, logGroup);
|
|
421
|
+
const exit = enterClsSendingGuard();
|
|
422
|
+
let p;
|
|
1593
423
|
try {
|
|
1594
|
-
|
|
1595
|
-
removeWebClickListener?.();
|
|
1596
|
-
restoreMiniProgramPatch?.();
|
|
424
|
+
p = client.PutLogs(request);
|
|
1597
425
|
}
|
|
1598
|
-
|
|
1599
|
-
|
|
426
|
+
finally {
|
|
427
|
+
exit();
|
|
1600
428
|
}
|
|
1601
|
-
|
|
1602
|
-
}
|
|
1603
|
-
|
|
1604
|
-
function truncate(s, maxLen) {
|
|
1605
|
-
if (!s)
|
|
1606
|
-
return s;
|
|
1607
|
-
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
1608
|
-
}
|
|
1609
|
-
function parseUserAgent(uaRaw) {
|
|
1610
|
-
const ua = uaRaw ?? '';
|
|
1611
|
-
const isMobile = /Mobile|Android|iPhone|iPad|iPod/i.test(ua);
|
|
1612
|
-
// OS
|
|
1613
|
-
let osName = 'unknown';
|
|
1614
|
-
let osVersion = '';
|
|
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 };
|
|
1659
|
-
}
|
|
1660
|
-
function getBrowserDeviceInfo(options) {
|
|
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;
|
|
429
|
+
await p;
|
|
1694
430
|
}
|
|
1695
|
-
|
|
1696
|
-
|
|
431
|
+
/**
|
|
432
|
+
* 直接上报:把 data 序列化后放入指定 key(默认 “日志内容”)
|
|
433
|
+
*/
|
|
434
|
+
putJson(data, clsLoggerKey = '日志内容', options = {}) {
|
|
435
|
+
// put 的入参要求扁平;这里直接把数据序列化为 string
|
|
436
|
+
this.put({ [clsLoggerKey]: stringifyLogValue(data) }, options);
|
|
1697
437
|
}
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
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 }]);
|
|
1702
468
|
}
|
|
1703
|
-
|
|
1704
|
-
|
|
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, []);
|
|
1705
478
|
}
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
}
|
|
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;
|
|
1719
491
|
}
|
|
1720
|
-
catch {
|
|
492
|
+
void this.putBatchAsync(queue).catch(() => {
|
|
1721
493
|
// ignore
|
|
1722
|
-
}
|
|
1723
|
-
}
|
|
1724
|
-
return out;
|
|
1725
|
-
}
|
|
1726
|
-
function getMiniProgramDeviceInfo(options) {
|
|
1727
|
-
const out = {
|
|
1728
|
-
envType: 'miniprogram',
|
|
1729
|
-
};
|
|
1730
|
-
const wxAny = globalThis.wx;
|
|
1731
|
-
if (!wxAny || typeof wxAny.getSystemInfoSync !== 'function')
|
|
1732
|
-
return out;
|
|
1733
|
-
try {
|
|
1734
|
-
const sys = wxAny.getSystemInfoSync();
|
|
1735
|
-
out.mpBrand = sys?.brand ? String(sys.brand) : '';
|
|
1736
|
-
out.mpModel = sys?.model ? String(sys.model) : '';
|
|
1737
|
-
out.mpSystem = sys?.system ? String(sys.system) : '';
|
|
1738
|
-
out.mpPlatform = sys?.platform ? String(sys.platform) : '';
|
|
1739
|
-
out.mpWeChatVersion = sys?.version ? String(sys.version) : '';
|
|
1740
|
-
out.mpSDKVersion = sys?.SDKVersion ? String(sys.SDKVersion) : '';
|
|
1741
|
-
out.mpScreenWidth = typeof sys?.screenWidth === 'number' ? sys.screenWidth : undefined;
|
|
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
|
|
494
|
+
});
|
|
1748
495
|
}
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
if (!g.__beLinkClsLoggerDeviceInfo__)
|
|
1762
|
-
g.__beLinkClsLoggerDeviceInfo__ = {};
|
|
1763
|
-
g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
|
|
1764
|
-
}
|
|
1765
|
-
catch {
|
|
1766
|
-
// ignore
|
|
1767
|
-
}
|
|
1768
|
-
},
|
|
1769
|
-
});
|
|
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]));
|
|
1770
508
|
}
|
|
509
|
+
logGroup.addLog(log);
|
|
1771
510
|
}
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
511
|
+
if (logGroup.getLogs().length === 0)
|
|
512
|
+
return;
|
|
513
|
+
const request = new sdk.PutLogsRequest(this.topicId, logGroup);
|
|
514
|
+
const exit = enterClsSendingGuard();
|
|
515
|
+
let p;
|
|
1775
516
|
try {
|
|
1776
|
-
|
|
1777
|
-
wxAny.onNetworkStatusChange((res) => {
|
|
1778
|
-
try {
|
|
1779
|
-
const g = globalThis;
|
|
1780
|
-
if (!g.__beLinkClsLoggerDeviceInfo__)
|
|
1781
|
-
g.__beLinkClsLoggerDeviceInfo__ = {};
|
|
1782
|
-
g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
|
|
1783
|
-
}
|
|
1784
|
-
catch {
|
|
1785
|
-
// ignore
|
|
1786
|
-
}
|
|
1787
|
-
});
|
|
1788
|
-
}
|
|
517
|
+
p = client.PutLogs(request);
|
|
1789
518
|
}
|
|
1790
|
-
|
|
1791
|
-
|
|
519
|
+
finally {
|
|
520
|
+
exit();
|
|
1792
521
|
}
|
|
522
|
+
await p;
|
|
1793
523
|
}
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
524
|
+
/**
|
|
525
|
+
* 参考《一、概述》:统一上报入口(内存队列 + 批量发送)
|
|
526
|
+
*/
|
|
527
|
+
report(log) {
|
|
528
|
+
if (!this.enabled)
|
|
529
|
+
return;
|
|
530
|
+
if (!log?.type)
|
|
531
|
+
return;
|
|
532
|
+
if (!this.topicId) {
|
|
533
|
+
// eslint-disable-next-line no-console
|
|
534
|
+
console.warn('ClsLogger.report:未初始化 topicID/topic_id');
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
this.memoryQueue.push(log);
|
|
538
|
+
if (this.memoryQueue.length >= this.batchMaxSize) {
|
|
539
|
+
void this.flushBatch();
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
const now = Date.now();
|
|
543
|
+
const desiredDueAt = this.getDesiredBatchFlushDueAt(now);
|
|
544
|
+
const desiredDelay = Math.max(0, desiredDueAt - now);
|
|
545
|
+
if (!this.batchTimer) {
|
|
546
|
+
this.batchTimerDueAt = desiredDueAt;
|
|
547
|
+
this.batchTimer = setTimeout(() => {
|
|
548
|
+
void this.flushBatch();
|
|
549
|
+
}, desiredDelay);
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
// 启动合并窗口内:如果当前 timer 会“更早”触发,则延后到窗口结束,尽量减少多次发送
|
|
553
|
+
if (this.batchTimerDueAt !== null && this.batchTimerDueAt < desiredDueAt) {
|
|
1815
554
|
try {
|
|
1816
|
-
|
|
1817
|
-
if (!g[globalKey])
|
|
1818
|
-
g[globalKey] = { ...base };
|
|
555
|
+
clearTimeout(this.batchTimer);
|
|
1819
556
|
}
|
|
1820
557
|
catch {
|
|
1821
558
|
// ignore
|
|
1822
559
|
}
|
|
560
|
+
this.batchTimerDueAt = desiredDueAt;
|
|
561
|
+
this.batchTimer = setTimeout(() => {
|
|
562
|
+
void this.flushBatch();
|
|
563
|
+
}, desiredDelay);
|
|
1823
564
|
}
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
565
|
+
}
|
|
566
|
+
getDesiredBatchFlushDueAt(nowTs) {
|
|
567
|
+
const start = this.initTs || nowTs;
|
|
568
|
+
const startupDelay = Number.isFinite(this.startupDelayMs) ? Math.max(0, this.startupDelayMs) : 0;
|
|
569
|
+
if (startupDelay > 0) {
|
|
570
|
+
const end = start + startupDelay;
|
|
571
|
+
if (nowTs < end)
|
|
572
|
+
return end;
|
|
1829
573
|
}
|
|
1830
|
-
|
|
1831
|
-
|
|
574
|
+
return nowTs + this.batchIntervalMs;
|
|
575
|
+
}
|
|
576
|
+
info(message, data = {}) {
|
|
577
|
+
let msg = '';
|
|
578
|
+
let extra = {};
|
|
579
|
+
if (message instanceof Error) {
|
|
580
|
+
msg = message.message;
|
|
581
|
+
extra = {
|
|
582
|
+
stack: message.stack,
|
|
583
|
+
name: message.name,
|
|
584
|
+
...data,
|
|
585
|
+
};
|
|
1832
586
|
}
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
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;
|
|
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() });
|
|
1889
593
|
}
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
return 'miniprogram';
|
|
594
|
+
warn(message, data = {}) {
|
|
595
|
+
let msg = '';
|
|
596
|
+
let extra = {};
|
|
597
|
+
if (message instanceof Error) {
|
|
598
|
+
msg = message.message;
|
|
599
|
+
extra = {
|
|
600
|
+
stack: message.stack,
|
|
601
|
+
name: message.name,
|
|
602
|
+
...data,
|
|
603
|
+
};
|
|
1901
604
|
}
|
|
1902
|
-
|
|
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() });
|
|
1903
611
|
}
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
612
|
+
error(message, data = {}) {
|
|
613
|
+
let msg = '';
|
|
614
|
+
let extra = {};
|
|
615
|
+
if (message instanceof Error) {
|
|
616
|
+
msg = message.message;
|
|
617
|
+
extra = {
|
|
618
|
+
stack: message.stack,
|
|
619
|
+
name: message.name,
|
|
620
|
+
...data,
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
else {
|
|
624
|
+
msg = String(message);
|
|
625
|
+
extra = data;
|
|
626
|
+
}
|
|
627
|
+
const payload = normalizeFlatFields({ message: msg, ...extra }, 'error');
|
|
628
|
+
this.report({ type: 'error', data: payload, timestamp: Date.now() });
|
|
629
|
+
}
|
|
630
|
+
track(trackType, data = {}) {
|
|
631
|
+
if (!trackType)
|
|
1913
632
|
return;
|
|
633
|
+
this.report({
|
|
634
|
+
type: trackType,
|
|
635
|
+
data: normalizeFlatFields(data, `track:${trackType}`),
|
|
636
|
+
timestamp: Date.now(),
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* 立即发送内存队列
|
|
641
|
+
*/
|
|
642
|
+
async flushBatch() {
|
|
643
|
+
if (this.batchTimer) {
|
|
644
|
+
clearTimeout(this.batchTimer);
|
|
645
|
+
this.batchTimer = null;
|
|
1914
646
|
}
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
const
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
this.
|
|
1922
|
-
this.clientPromise = null;
|
|
647
|
+
this.batchTimerDueAt = null;
|
|
648
|
+
if (this.memoryQueue.length === 0)
|
|
649
|
+
return;
|
|
650
|
+
const logs = [...this.memoryQueue];
|
|
651
|
+
this.memoryQueue = [];
|
|
652
|
+
try {
|
|
653
|
+
await this.sendReportLogs(logs);
|
|
1923
654
|
}
|
|
1924
|
-
|
|
1925
|
-
this.
|
|
1926
|
-
this.sdkPromise = null;
|
|
655
|
+
catch {
|
|
656
|
+
this.retrySendReportLogs(logs, 1);
|
|
1927
657
|
}
|
|
1928
|
-
this.topicId = topicId;
|
|
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(() => {
|
|
1953
|
-
// ignore
|
|
1954
|
-
});
|
|
1955
|
-
// 启动时尝试发送失败缓存
|
|
1956
|
-
this.flushFailed();
|
|
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
658
|
}
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
659
|
+
buildReportFields(log) {
|
|
660
|
+
const ts = log.timestamp ?? Date.now();
|
|
661
|
+
const base = this.getBaseFields();
|
|
662
|
+
const data = normalizeFlatFields(log.data ?? {}, 'report:data');
|
|
663
|
+
const mergedData = mergeFields(base, data);
|
|
664
|
+
return {
|
|
665
|
+
timestamp: ts,
|
|
666
|
+
type: log.type,
|
|
667
|
+
envType: this.envType,
|
|
668
|
+
projectId: this.projectId || undefined,
|
|
669
|
+
projectName: this.projectName || undefined,
|
|
670
|
+
appId: this.appId || undefined,
|
|
671
|
+
appVersion: this.appVersion || undefined,
|
|
672
|
+
// 保证“一维字段”:业务数据以 JSON 字符串形式落到 CLS
|
|
673
|
+
...mergedData,
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
async sendReportLogs(logs) {
|
|
677
|
+
if (!this.topicId)
|
|
678
|
+
return;
|
|
679
|
+
const sdk = await this.loadSdk();
|
|
680
|
+
const client = await this.getInstance();
|
|
681
|
+
const logGroup = new sdk.LogGroup('127.0.0.1');
|
|
682
|
+
logGroup.setSource(this.source);
|
|
683
|
+
for (const item of logs) {
|
|
684
|
+
const fields = this.buildReportFields(item);
|
|
685
|
+
const log = new sdk.Log(fields.timestamp);
|
|
686
|
+
for (const key of Object.keys(fields)) {
|
|
687
|
+
if (key === 'timestamp')
|
|
688
|
+
continue;
|
|
689
|
+
log.addContent(key, stringifyLogValue(fields[key]));
|
|
690
|
+
}
|
|
691
|
+
logGroup.addLog(log);
|
|
692
|
+
}
|
|
693
|
+
const request = new sdk.PutLogsRequest(this.topicId, logGroup);
|
|
694
|
+
// 只在“发起网络请求”的同步阶段打标记,避免 requestMonitor 监控 CLS 上报请求导致递归
|
|
695
|
+
const exit = enterClsSendingGuard();
|
|
696
|
+
let p;
|
|
1968
697
|
try {
|
|
1969
|
-
|
|
1970
|
-
if (autoRaw && isPlainObject(autoRaw))
|
|
1971
|
-
auto = normalizeFlatFields(autoRaw, 'deviceInfo');
|
|
698
|
+
p = client.PutLogs(request);
|
|
1972
699
|
}
|
|
1973
|
-
|
|
1974
|
-
|
|
700
|
+
finally {
|
|
701
|
+
exit();
|
|
702
|
+
}
|
|
703
|
+
await p;
|
|
704
|
+
}
|
|
705
|
+
retrySendReportLogs(logs, retryCount) {
|
|
706
|
+
if (retryCount > this.retryTimes) {
|
|
707
|
+
this.cacheFailedReportLogs(logs);
|
|
708
|
+
return;
|
|
1975
709
|
}
|
|
710
|
+
const delayMs = Math.pow(2, retryCount) * 1000;
|
|
711
|
+
setTimeout(async () => {
|
|
712
|
+
try {
|
|
713
|
+
await this.sendReportLogs(logs);
|
|
714
|
+
}
|
|
715
|
+
catch {
|
|
716
|
+
this.retrySendReportLogs(logs, retryCount + 1);
|
|
717
|
+
}
|
|
718
|
+
}, delayMs);
|
|
719
|
+
}
|
|
720
|
+
cacheFailedReportLogs(logs) {
|
|
721
|
+
const raw = readStringStorage(this.failedCacheKey);
|
|
722
|
+
let current = [];
|
|
1976
723
|
try {
|
|
1977
|
-
const
|
|
1978
|
-
|
|
1979
|
-
user = normalizeFlatFields({ ...userRaw }, 'generateBaseFields');
|
|
724
|
+
const parsed = raw ? JSON.parse(raw) : [];
|
|
725
|
+
current = Array.isArray(parsed) ? parsed : [];
|
|
1980
726
|
}
|
|
1981
727
|
catch {
|
|
1982
|
-
|
|
728
|
+
current = [];
|
|
1983
729
|
}
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
if (user)
|
|
1987
|
-
return user;
|
|
1988
|
-
if (auto)
|
|
1989
|
-
return auto;
|
|
1990
|
-
return undefined;
|
|
730
|
+
const next = [...current, ...logs].slice(-this.failedCacheMax);
|
|
731
|
+
writeStringStorage(this.failedCacheKey, JSON.stringify(next));
|
|
1991
732
|
}
|
|
1992
|
-
|
|
1993
|
-
if (this.
|
|
1994
|
-
return;
|
|
1995
|
-
// 默认开启;传 false 则关闭
|
|
1996
|
-
const enabled = requestMonitor === undefined ? true : !!requestMonitor;
|
|
1997
|
-
if (!enabled)
|
|
733
|
+
flushFailed() {
|
|
734
|
+
if (!this.enabled)
|
|
1998
735
|
return;
|
|
1999
|
-
const
|
|
2000
|
-
|
|
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)
|
|
736
|
+
const raw = readStringStorage(this.failedCacheKey);
|
|
737
|
+
if (!raw)
|
|
2011
738
|
return;
|
|
2012
|
-
|
|
2013
|
-
|
|
739
|
+
let logs = [];
|
|
740
|
+
try {
|
|
741
|
+
const parsed = JSON.parse(raw);
|
|
742
|
+
logs = Array.isArray(parsed) ? parsed : [];
|
|
743
|
+
}
|
|
744
|
+
catch {
|
|
745
|
+
logs = [];
|
|
746
|
+
}
|
|
747
|
+
if (logs.length === 0)
|
|
2014
748
|
return;
|
|
2015
|
-
|
|
2016
|
-
|
|
749
|
+
// 先清空,再尝试发送
|
|
750
|
+
writeStringStorage(this.failedCacheKey, JSON.stringify([]));
|
|
751
|
+
this.memoryQueue.unshift(...logs);
|
|
752
|
+
void this.flushBatch();
|
|
2017
753
|
}
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
if (!
|
|
754
|
+
/**
|
|
755
|
+
* 统计/计数类日志:按字段展开上报(若 data 为空默认 1)
|
|
756
|
+
*/
|
|
757
|
+
stat(param) {
|
|
758
|
+
if (!param)
|
|
2023
759
|
return;
|
|
2024
|
-
|
|
2025
|
-
|
|
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() });
|
|
2026
768
|
}
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
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
|
-
});
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
function readGlobal(key) {
|
|
772
|
+
try {
|
|
773
|
+
const g = globalThis;
|
|
774
|
+
return g[key] ?? null;
|
|
2043
775
|
}
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
776
|
+
catch {
|
|
777
|
+
return null;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
function tryRequire(moduleName) {
|
|
781
|
+
try {
|
|
782
|
+
// 说明:
|
|
783
|
+
// - ESM 构建(exports.import/module)里通常不存在模块作用域的 require
|
|
784
|
+
// - 一些小程序运行时/构建链路会把 require 挂到 globalThis 上
|
|
785
|
+
// 因此这里同时探测“模块作用域 require”与 “globalThis.require”
|
|
786
|
+
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
|
787
|
+
const localReq = (typeof require === 'function' ? require : null);
|
|
788
|
+
const globalReq = readGlobal('require');
|
|
789
|
+
const candidates = [localReq, globalReq].filter((fn) => typeof fn === 'function');
|
|
790
|
+
for (const fn of candidates) {
|
|
791
|
+
try {
|
|
792
|
+
return fn(moduleName);
|
|
793
|
+
}
|
|
794
|
+
catch {
|
|
795
|
+
// continue
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
return null;
|
|
799
|
+
}
|
|
800
|
+
catch {
|
|
801
|
+
return null;
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
const DEFAULT_IGNORE = ['cls.tencentcs.com', /\/cls\//i];
|
|
806
|
+
function shouldIgnoreUrl(url, ignoreUrls) {
|
|
807
|
+
for (const rule of ignoreUrls) {
|
|
808
|
+
if (typeof rule === 'string') {
|
|
809
|
+
if (url.includes(rule))
|
|
810
|
+
return true;
|
|
811
|
+
continue;
|
|
812
|
+
}
|
|
2049
813
|
try {
|
|
2050
|
-
|
|
814
|
+
if (rule.test(url))
|
|
815
|
+
return true;
|
|
816
|
+
}
|
|
817
|
+
catch {
|
|
818
|
+
// ignore invalid regex
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
return false;
|
|
822
|
+
}
|
|
823
|
+
function sampleHit$2(sampleRate) {
|
|
824
|
+
if (sampleRate >= 1)
|
|
825
|
+
return true;
|
|
826
|
+
if (sampleRate <= 0)
|
|
827
|
+
return false;
|
|
828
|
+
return Math.random() < sampleRate;
|
|
829
|
+
}
|
|
830
|
+
function truncate$1(s, maxLen) {
|
|
831
|
+
if (!s)
|
|
832
|
+
return s;
|
|
833
|
+
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
834
|
+
}
|
|
835
|
+
function buildPayload(params) {
|
|
836
|
+
const { url, method, query, body, duration, startTime, status, success, error, options } = params;
|
|
837
|
+
if (!url)
|
|
838
|
+
return null;
|
|
839
|
+
if (shouldIgnoreUrl(url, options.ignoreUrls))
|
|
840
|
+
return null;
|
|
841
|
+
if (!sampleHit$2(options.sampleRate))
|
|
842
|
+
return null;
|
|
843
|
+
const payload = { url };
|
|
844
|
+
if (options.includeMethod && method)
|
|
845
|
+
payload.method = method;
|
|
846
|
+
if (options.includeQuery && query !== undefined)
|
|
847
|
+
payload.query = truncate$1(String(query), options.maxParamLength);
|
|
848
|
+
if (options.includeBody && body !== undefined)
|
|
849
|
+
payload.params = truncate$1(stringifyLogValue(body), options.maxParamLength);
|
|
850
|
+
if (typeof startTime === 'number')
|
|
851
|
+
payload.startTime = startTime;
|
|
852
|
+
if (typeof duration === 'number')
|
|
853
|
+
payload.duration = duration;
|
|
854
|
+
if (typeof status === 'number')
|
|
855
|
+
payload.status = status;
|
|
856
|
+
if (typeof success === 'boolean')
|
|
857
|
+
payload.success = success ? 1 : 0;
|
|
858
|
+
if (error !== undefined)
|
|
859
|
+
payload.error = truncate$1(stringifyLogValue(error), options.maxParamLength);
|
|
860
|
+
return payload;
|
|
861
|
+
}
|
|
862
|
+
function installMiniProgramWxRequest(report, options) {
|
|
863
|
+
const wxAny = globalThis.wx;
|
|
864
|
+
if (!wxAny || typeof wxAny.request !== 'function')
|
|
865
|
+
return;
|
|
866
|
+
if (wxAny.__beLinkClsLoggerWxRequestInstalled__)
|
|
867
|
+
return;
|
|
868
|
+
wxAny.__beLinkClsLoggerWxRequestInstalled__ = true;
|
|
869
|
+
const rawRequest = wxAny.request.bind(wxAny);
|
|
870
|
+
wxAny.request = (reqOptions) => {
|
|
871
|
+
const startTs = Date.now();
|
|
872
|
+
try {
|
|
873
|
+
const url = String(reqOptions?.url ?? '');
|
|
874
|
+
const method = String(reqOptions?.method ?? 'GET');
|
|
875
|
+
const data = reqOptions?.data;
|
|
876
|
+
const wrapCb = (cb, success) => {
|
|
877
|
+
return (res) => {
|
|
878
|
+
try {
|
|
879
|
+
const duration = Date.now() - startTs;
|
|
880
|
+
const status = typeof res?.statusCode === 'number'
|
|
881
|
+
? res.statusCode
|
|
882
|
+
: typeof res?.status === 'number'
|
|
883
|
+
? res.status
|
|
884
|
+
: undefined;
|
|
885
|
+
const payload = buildPayload({
|
|
886
|
+
url,
|
|
887
|
+
method,
|
|
888
|
+
query: '',
|
|
889
|
+
body: data,
|
|
890
|
+
startTime: startTs,
|
|
891
|
+
duration,
|
|
892
|
+
status,
|
|
893
|
+
success,
|
|
894
|
+
error: success ? undefined : res,
|
|
895
|
+
options,
|
|
896
|
+
});
|
|
897
|
+
if (payload)
|
|
898
|
+
report(options.reportType, payload);
|
|
899
|
+
}
|
|
900
|
+
catch {
|
|
901
|
+
// ignore
|
|
902
|
+
}
|
|
903
|
+
if (typeof cb === 'function')
|
|
904
|
+
return cb(res);
|
|
905
|
+
return undefined;
|
|
906
|
+
};
|
|
907
|
+
};
|
|
908
|
+
const next = { ...(reqOptions ?? {}) };
|
|
909
|
+
next.success = wrapCb(next.success, true);
|
|
910
|
+
next.fail = wrapCb(next.fail, false);
|
|
911
|
+
return rawRequest(next);
|
|
2051
912
|
}
|
|
2052
913
|
catch {
|
|
2053
914
|
// ignore
|
|
2054
915
|
}
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
916
|
+
return rawRequest(reqOptions);
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
function installMiniProgramWxCloudCallFunction(report, options) {
|
|
920
|
+
const wxAny = globalThis.wx;
|
|
921
|
+
const cloud = wxAny?.cloud;
|
|
922
|
+
if (!cloud || typeof cloud.callFunction !== 'function')
|
|
923
|
+
return;
|
|
924
|
+
if (cloud.__beLinkClsLoggerWxCloudCallFunctionInstalled__)
|
|
925
|
+
return;
|
|
926
|
+
cloud.__beLinkClsLoggerWxCloudCallFunctionInstalled__ = true;
|
|
927
|
+
const rawCallFunction = cloud.callFunction.bind(cloud);
|
|
928
|
+
cloud.callFunction = (callOptions) => {
|
|
929
|
+
const startTs = Date.now();
|
|
930
|
+
const name = (() => {
|
|
931
|
+
try {
|
|
932
|
+
return String(callOptions?.name ?? '');
|
|
933
|
+
}
|
|
934
|
+
catch {
|
|
935
|
+
return '';
|
|
936
|
+
}
|
|
937
|
+
})();
|
|
938
|
+
const data = callOptions?.data;
|
|
939
|
+
let reported = false;
|
|
940
|
+
const onDone = (success, err) => {
|
|
941
|
+
if (reported)
|
|
942
|
+
return;
|
|
943
|
+
reported = true;
|
|
944
|
+
try {
|
|
945
|
+
const duration = Date.now() - startTs;
|
|
946
|
+
const payload = buildPayload({
|
|
947
|
+
// 统一走 url 字段,便于和 http 一起检索/聚合
|
|
948
|
+
url: `cloud.callFunction/${name || 'unknown'}`,
|
|
949
|
+
method: 'callFunction',
|
|
950
|
+
query: '',
|
|
951
|
+
body: data,
|
|
952
|
+
startTime: startTs,
|
|
953
|
+
duration,
|
|
954
|
+
success,
|
|
955
|
+
error: success ? undefined : err,
|
|
956
|
+
options,
|
|
957
|
+
});
|
|
958
|
+
if (payload) {
|
|
959
|
+
payload.requestType = 'cloud-function';
|
|
960
|
+
payload.name = name || 'unknown';
|
|
961
|
+
report(options.reportType, payload);
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
catch {
|
|
965
|
+
// ignore
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
try {
|
|
969
|
+
const next = { ...(callOptions ?? {}) };
|
|
970
|
+
const rawSuccess = next.success;
|
|
971
|
+
const rawFail = next.fail;
|
|
972
|
+
next.success = (res) => {
|
|
973
|
+
onDone(true);
|
|
974
|
+
if (typeof rawSuccess === 'function')
|
|
975
|
+
return rawSuccess(res);
|
|
976
|
+
return undefined;
|
|
977
|
+
};
|
|
978
|
+
next.fail = (err) => {
|
|
979
|
+
onDone(false, err?.message ?? err);
|
|
980
|
+
if (typeof rawFail === 'function')
|
|
981
|
+
return rawFail(err);
|
|
982
|
+
return undefined;
|
|
983
|
+
};
|
|
984
|
+
const ret = rawCallFunction(next);
|
|
985
|
+
// 兼容 Promise 风格(有些版本/写法不传 success/fail)
|
|
986
|
+
if (ret && typeof ret.then === 'function') {
|
|
987
|
+
ret.then(() => onDone(true), (err) => onDone(false, err?.message ?? err));
|
|
988
|
+
}
|
|
989
|
+
return ret;
|
|
990
|
+
}
|
|
991
|
+
catch (err) {
|
|
992
|
+
onDone(false, err);
|
|
2078
993
|
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;
|
|
2094
994
|
}
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
995
|
+
};
|
|
996
|
+
}
|
|
997
|
+
function installMiniRequestMonitor(report, opts = {}) {
|
|
998
|
+
const enabled = opts.enabled ?? true;
|
|
999
|
+
if (!enabled)
|
|
1000
|
+
return;
|
|
1001
|
+
const ignoreUrls = [...DEFAULT_IGNORE, ...(opts.ignoreUrls ?? [])];
|
|
1002
|
+
if (opts.clsEndpoint)
|
|
1003
|
+
ignoreUrls.push(opts.clsEndpoint);
|
|
1004
|
+
const options = {
|
|
1005
|
+
enabled: true,
|
|
1006
|
+
reportType: opts.reportType ?? 'http',
|
|
1007
|
+
sampleRate: opts.sampleRate ?? 1,
|
|
1008
|
+
ignoreUrls,
|
|
1009
|
+
includeMethod: opts.includeMethod ?? true,
|
|
1010
|
+
includeQuery: opts.includeQuery ?? true,
|
|
1011
|
+
includeBody: opts.includeBody ?? true,
|
|
1012
|
+
maxParamLength: opts.maxParamLength ?? 2000,
|
|
1013
|
+
clsEndpoint: opts.clsEndpoint ?? '',
|
|
1014
|
+
};
|
|
1015
|
+
installMiniProgramWxRequest(report, options);
|
|
1016
|
+
installMiniProgramWxCloudCallFunction(report, options);
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
const DEFAULT_MAX_TEXT = 4000;
|
|
1020
|
+
const DEFAULT_DEDUPE_WINDOW_MS = 3000;
|
|
1021
|
+
const DEFAULT_DEDUPE_MAX_KEYS = 200;
|
|
1022
|
+
function truncate(s, maxLen) {
|
|
1023
|
+
if (!s)
|
|
1024
|
+
return s;
|
|
1025
|
+
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
1026
|
+
}
|
|
1027
|
+
function sampleHit$1(sampleRate) {
|
|
1028
|
+
if (sampleRate >= 1)
|
|
1029
|
+
return true;
|
|
1030
|
+
if (sampleRate <= 0)
|
|
1031
|
+
return false;
|
|
1032
|
+
return Math.random() < sampleRate;
|
|
1033
|
+
}
|
|
1034
|
+
function getMpPagePath() {
|
|
1035
|
+
try {
|
|
1036
|
+
const pages = globalThis.getCurrentPages?.();
|
|
1037
|
+
if (Array.isArray(pages) && pages.length > 0) {
|
|
1038
|
+
const page = pages[pages.length - 1];
|
|
1039
|
+
return page.route || page.__route__ || '';
|
|
1040
|
+
}
|
|
1041
|
+
return '';
|
|
2110
1042
|
}
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
1043
|
+
catch {
|
|
1044
|
+
return '';
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
function normalizeErrorLike(err, maxTextLength) {
|
|
1048
|
+
if (err && typeof err === 'object') {
|
|
1049
|
+
const anyErr = err;
|
|
1050
|
+
let rawMsg = anyErr.message;
|
|
1051
|
+
if (!rawMsg) {
|
|
1052
|
+
const str = anyErr.toString?.();
|
|
1053
|
+
if (!str || str === '[object Object]') {
|
|
1054
|
+
rawMsg = stringifyLogValue(anyErr);
|
|
1055
|
+
}
|
|
1056
|
+
else {
|
|
1057
|
+
rawMsg = str;
|
|
1058
|
+
}
|
|
2121
1059
|
}
|
|
2122
|
-
|
|
2123
|
-
const
|
|
2124
|
-
const
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
1060
|
+
const message = truncate(String(rawMsg ?? ''), maxTextLength);
|
|
1061
|
+
const name = truncate(String(anyErr.name ?? ''), 200);
|
|
1062
|
+
const stack = truncate(String(anyErr.stack ?? ''), maxTextLength);
|
|
1063
|
+
return { message, name, stack };
|
|
1064
|
+
}
|
|
1065
|
+
const message = truncate(stringifyLogValue(err), maxTextLength);
|
|
1066
|
+
return { message, name: '', stack: '' };
|
|
1067
|
+
}
|
|
1068
|
+
function createDedupeGuard(options) {
|
|
1069
|
+
const cache = new Map(); // key -> lastReportAt
|
|
1070
|
+
const maxKeys = Math.max(0, options.dedupeMaxKeys);
|
|
1071
|
+
const windowMs = Math.max(0, options.dedupeWindowMs);
|
|
1072
|
+
function touch(key, now) {
|
|
1073
|
+
if (cache.has(key))
|
|
1074
|
+
cache.delete(key);
|
|
1075
|
+
cache.set(key, now);
|
|
1076
|
+
if (maxKeys > 0) {
|
|
1077
|
+
while (cache.size > maxKeys) {
|
|
1078
|
+
const first = cache.keys().next().value;
|
|
1079
|
+
if (!first)
|
|
1080
|
+
break;
|
|
1081
|
+
cache.delete(first);
|
|
1082
|
+
}
|
|
2128
1083
|
}
|
|
2129
|
-
|
|
2130
|
-
|
|
1084
|
+
}
|
|
1085
|
+
return (key) => {
|
|
1086
|
+
if (!key)
|
|
1087
|
+
return true;
|
|
1088
|
+
if (windowMs <= 0 || maxKeys === 0)
|
|
1089
|
+
return true;
|
|
1090
|
+
const now = Date.now();
|
|
1091
|
+
const last = cache.get(key);
|
|
1092
|
+
if (typeof last === 'number' && now - last < windowMs)
|
|
1093
|
+
return false;
|
|
1094
|
+
touch(key, now);
|
|
1095
|
+
return true;
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
function buildErrorKey(type, payload) {
|
|
1099
|
+
const parts = [
|
|
1100
|
+
type,
|
|
1101
|
+
String(payload.source ?? ''),
|
|
1102
|
+
String(payload.pagePath ?? ''),
|
|
1103
|
+
String(payload.message ?? ''),
|
|
1104
|
+
String(payload.errorName ?? ''),
|
|
1105
|
+
String(payload.stack ?? ''),
|
|
1106
|
+
String(payload.filename ?? ''),
|
|
1107
|
+
String(payload.lineno ?? ''),
|
|
1108
|
+
String(payload.colno ?? ''),
|
|
1109
|
+
String(payload.tagName ?? ''),
|
|
1110
|
+
String(payload.resourceUrl ?? ''),
|
|
1111
|
+
];
|
|
1112
|
+
return parts.join('|');
|
|
1113
|
+
}
|
|
1114
|
+
function installMiniProgramErrorMonitor(report, options) {
|
|
1115
|
+
const g = globalThis;
|
|
1116
|
+
if (g.__beLinkClsLoggerMpErrorInstalled__)
|
|
1117
|
+
return;
|
|
1118
|
+
g.__beLinkClsLoggerMpErrorInstalled__ = true;
|
|
1119
|
+
const shouldReport = createDedupeGuard(options);
|
|
1120
|
+
const wxAny = globalThis.wx;
|
|
1121
|
+
try {
|
|
1122
|
+
if (wxAny && typeof wxAny.onError === 'function') {
|
|
1123
|
+
wxAny.onError((msg) => {
|
|
1124
|
+
try {
|
|
1125
|
+
if (!sampleHit$1(options.sampleRate))
|
|
1126
|
+
return;
|
|
1127
|
+
const e = normalizeErrorLike(msg, options.maxTextLength);
|
|
1128
|
+
const payload = {
|
|
1129
|
+
pagePath: getMpPagePath(),
|
|
1130
|
+
source: 'wx.onError',
|
|
1131
|
+
message: e.message,
|
|
1132
|
+
errorName: e.name,
|
|
1133
|
+
stack: e.stack,
|
|
1134
|
+
};
|
|
1135
|
+
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
1136
|
+
return;
|
|
1137
|
+
report(options.reportType, payload);
|
|
1138
|
+
}
|
|
1139
|
+
catch {
|
|
1140
|
+
// ignore
|
|
1141
|
+
}
|
|
1142
|
+
});
|
|
2131
1143
|
}
|
|
2132
|
-
await p;
|
|
2133
1144
|
}
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
*/
|
|
2137
|
-
putJson(data, clsLoggerKey = '日志内容', options = {}) {
|
|
2138
|
-
// put 的入参要求扁平;这里直接把数据序列化为 string
|
|
2139
|
-
this.put({ [clsLoggerKey]: stringifyLogValue(data) }, options);
|
|
1145
|
+
catch {
|
|
1146
|
+
// ignore
|
|
2140
1147
|
}
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
writeQueue(this.storageKey, next);
|
|
2164
|
-
return;
|
|
1148
|
+
try {
|
|
1149
|
+
if (wxAny && typeof wxAny.onUnhandledRejection === 'function') {
|
|
1150
|
+
wxAny.onUnhandledRejection((res) => {
|
|
1151
|
+
try {
|
|
1152
|
+
if (!sampleHit$1(options.sampleRate))
|
|
1153
|
+
return;
|
|
1154
|
+
const e = normalizeErrorLike(res?.reason, options.maxTextLength);
|
|
1155
|
+
const payload = {
|
|
1156
|
+
pagePath: getMpPagePath(),
|
|
1157
|
+
source: 'wx.onUnhandledRejection',
|
|
1158
|
+
message: e.message,
|
|
1159
|
+
errorName: e.name,
|
|
1160
|
+
stack: e.stack,
|
|
1161
|
+
};
|
|
1162
|
+
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
1163
|
+
return;
|
|
1164
|
+
report(options.reportType, payload);
|
|
1165
|
+
}
|
|
1166
|
+
catch {
|
|
1167
|
+
// ignore
|
|
1168
|
+
}
|
|
1169
|
+
});
|
|
2165
1170
|
}
|
|
2166
|
-
// 达到阈值:flush + 写入新的队列(避免并发下丢失,按“先 flush 旧的”策略)
|
|
2167
|
-
this.putBatch(queue);
|
|
2168
|
-
writeQueue(this.storageKey, [{ time, data: finalFields }]);
|
|
2169
1171
|
}
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
*/
|
|
2173
|
-
flush() {
|
|
2174
|
-
const queue = readQueue(this.storageKey);
|
|
2175
|
-
if (queue.length === 0)
|
|
2176
|
-
return;
|
|
2177
|
-
this.putBatch(queue);
|
|
2178
|
-
writeQueue(this.storageKey, []);
|
|
1172
|
+
catch {
|
|
1173
|
+
// ignore
|
|
2179
1174
|
}
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
1175
|
+
try {
|
|
1176
|
+
if (typeof g.App === 'function' && !g.__beLinkClsLoggerAppWrapped__) {
|
|
1177
|
+
g.__beLinkClsLoggerAppWrapped__ = true;
|
|
1178
|
+
const rawApp = g.App;
|
|
1179
|
+
g.App = (appOptions) => {
|
|
1180
|
+
const next = { ...(appOptions ?? {}) };
|
|
1181
|
+
const rawOnError = next.onError;
|
|
1182
|
+
next.onError = function (...args) {
|
|
1183
|
+
try {
|
|
1184
|
+
if (sampleHit$1(options.sampleRate)) {
|
|
1185
|
+
const e = normalizeErrorLike(args?.[0], options.maxTextLength);
|
|
1186
|
+
const payload = {
|
|
1187
|
+
pagePath: getMpPagePath(),
|
|
1188
|
+
source: 'App.onError',
|
|
1189
|
+
message: e.message,
|
|
1190
|
+
errorName: e.name,
|
|
1191
|
+
stack: e.stack,
|
|
1192
|
+
};
|
|
1193
|
+
if (shouldReport(buildErrorKey(options.reportType, payload)))
|
|
1194
|
+
report(options.reportType, payload);
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
catch {
|
|
1198
|
+
// ignore
|
|
1199
|
+
}
|
|
1200
|
+
if (typeof rawOnError === 'function')
|
|
1201
|
+
return rawOnError.apply(this, args);
|
|
1202
|
+
return undefined;
|
|
1203
|
+
};
|
|
1204
|
+
const rawOnUnhandled = next.onUnhandledRejection;
|
|
1205
|
+
next.onUnhandledRejection = function (...args) {
|
|
1206
|
+
try {
|
|
1207
|
+
if (sampleHit$1(options.sampleRate)) {
|
|
1208
|
+
const reason = args?.[0]?.reason ?? args?.[0];
|
|
1209
|
+
const e = normalizeErrorLike(reason, options.maxTextLength);
|
|
1210
|
+
const payload = {
|
|
1211
|
+
pagePath: getMpPagePath(),
|
|
1212
|
+
source: 'App.onUnhandledRejection',
|
|
1213
|
+
message: e.message,
|
|
1214
|
+
errorName: e.name,
|
|
1215
|
+
stack: e.stack,
|
|
1216
|
+
};
|
|
1217
|
+
if (shouldReport(buildErrorKey(options.reportType, payload)))
|
|
1218
|
+
report(options.reportType, payload);
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
catch {
|
|
1222
|
+
// ignore
|
|
1223
|
+
}
|
|
1224
|
+
if (typeof rawOnUnhandled === 'function')
|
|
1225
|
+
return rawOnUnhandled.apply(this, args);
|
|
1226
|
+
return undefined;
|
|
1227
|
+
};
|
|
1228
|
+
return rawApp(next);
|
|
1229
|
+
};
|
|
2190
1230
|
}
|
|
2191
|
-
void this.putBatchAsync(queue).catch(() => {
|
|
2192
|
-
// ignore
|
|
2193
|
-
});
|
|
2194
1231
|
}
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
return;
|
|
2198
|
-
const sdk = await this.loadSdk();
|
|
2199
|
-
const client = await this.getInstance();
|
|
2200
|
-
const logGroup = new sdk.LogGroup('127.0.0.1');
|
|
2201
|
-
logGroup.setSource(this.source);
|
|
2202
|
-
for (const item of queue) {
|
|
2203
|
-
const log = new sdk.Log(item.time);
|
|
2204
|
-
const data = item.data ?? {};
|
|
2205
|
-
for (const key of Object.keys(data)) {
|
|
2206
|
-
log.addContent(key, stringifyLogValue(data[key]));
|
|
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);
|
|
2217
|
-
}
|
|
2218
|
-
finally {
|
|
2219
|
-
exit();
|
|
2220
|
-
}
|
|
2221
|
-
await p;
|
|
1232
|
+
catch {
|
|
1233
|
+
// ignore
|
|
2222
1234
|
}
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
1235
|
+
}
|
|
1236
|
+
function installMiniErrorMonitor(report, opts = {}) {
|
|
1237
|
+
const enabled = opts === undefined ? true : !!opts;
|
|
1238
|
+
if (!enabled)
|
|
1239
|
+
return;
|
|
1240
|
+
const raw = typeof opts === 'object' && opts ? opts : {};
|
|
1241
|
+
const options = {
|
|
1242
|
+
enabled: true,
|
|
1243
|
+
reportType: raw.reportType ?? 'error',
|
|
1244
|
+
sampleRate: raw.sampleRate ?? 1,
|
|
1245
|
+
captureResourceError: raw.captureResourceError ?? true,
|
|
1246
|
+
maxTextLength: raw.maxTextLength ?? DEFAULT_MAX_TEXT,
|
|
1247
|
+
dedupeWindowMs: raw.dedupeWindowMs ?? DEFAULT_DEDUPE_WINDOW_MS,
|
|
1248
|
+
dedupeMaxKeys: raw.dedupeMaxKeys ?? DEFAULT_DEDUPE_MAX_KEYS,
|
|
1249
|
+
};
|
|
1250
|
+
installMiniProgramErrorMonitor(report, options);
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
function sampleHit(sampleRate) {
|
|
1254
|
+
if (sampleRate >= 1)
|
|
1255
|
+
return true;
|
|
1256
|
+
if (sampleRate <= 0)
|
|
1257
|
+
return false;
|
|
1258
|
+
return Math.random() < sampleRate;
|
|
1259
|
+
}
|
|
1260
|
+
function installMiniProgramPerformanceMonitor(report, options) {
|
|
1261
|
+
const g = globalThis;
|
|
1262
|
+
const ctx = g.wx || g.Taro;
|
|
1263
|
+
if (!ctx || typeof ctx.getPerformance !== 'function')
|
|
1264
|
+
return;
|
|
1265
|
+
if (g.__beLinkClsLoggerMpPerfInstalled__)
|
|
1266
|
+
return;
|
|
1267
|
+
g.__beLinkClsLoggerMpPerfInstalled__ = true;
|
|
1268
|
+
try {
|
|
1269
|
+
const perf = ctx.getPerformance();
|
|
1270
|
+
if (!perf || typeof perf.createObserver !== 'function')
|
|
2247
1271
|
return;
|
|
2248
|
-
|
|
2249
|
-
// 启动合并窗口内:如果当前 timer 会“更早”触发,则延后到窗口结束,尽量减少多次发送
|
|
2250
|
-
if (this.batchTimerDueAt !== null && this.batchTimerDueAt < desiredDueAt) {
|
|
1272
|
+
const observer = perf.createObserver((entryList) => {
|
|
2251
1273
|
try {
|
|
2252
|
-
|
|
1274
|
+
const entries = entryList.getEntries();
|
|
1275
|
+
for (const entry of entries) {
|
|
1276
|
+
if (!sampleHit(options.sampleRate))
|
|
1277
|
+
continue;
|
|
1278
|
+
// Page Render: firstRender
|
|
1279
|
+
if (entry.entryType === 'render' && entry.name === 'firstRender') {
|
|
1280
|
+
const duration = typeof entry.duration === 'number'
|
|
1281
|
+
? entry.duration
|
|
1282
|
+
: typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
|
|
1283
|
+
? entry.endTime - entry.startTime
|
|
1284
|
+
: 0;
|
|
1285
|
+
report(options.reportType, {
|
|
1286
|
+
metric: 'page-render',
|
|
1287
|
+
duration,
|
|
1288
|
+
pagePath: entry.path || '',
|
|
1289
|
+
unit: 'ms',
|
|
1290
|
+
});
|
|
1291
|
+
}
|
|
1292
|
+
// Route Switch: route
|
|
1293
|
+
else if (entry.entryType === 'navigation' && entry.name === 'route') {
|
|
1294
|
+
const duration = typeof entry.duration === 'number'
|
|
1295
|
+
? entry.duration
|
|
1296
|
+
: typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
|
|
1297
|
+
? entry.endTime - entry.startTime
|
|
1298
|
+
: 0;
|
|
1299
|
+
report(options.reportType, {
|
|
1300
|
+
metric: 'route',
|
|
1301
|
+
duration,
|
|
1302
|
+
pagePath: entry.path || '',
|
|
1303
|
+
unit: 'ms',
|
|
1304
|
+
});
|
|
1305
|
+
}
|
|
1306
|
+
// App Launch: appLaunch (Cold)
|
|
1307
|
+
else if (entry.entryType === 'navigation' && entry.name === 'appLaunch') {
|
|
1308
|
+
report(options.reportType, {
|
|
1309
|
+
metric: 'app-launch',
|
|
1310
|
+
duration: entry.duration,
|
|
1311
|
+
launchType: 'cold',
|
|
1312
|
+
unit: 'ms',
|
|
1313
|
+
});
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
2253
1316
|
}
|
|
2254
1317
|
catch {
|
|
2255
1318
|
// ignore
|
|
2256
1319
|
}
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
void this.flushBatch();
|
|
2260
|
-
}, desiredDelay);
|
|
2261
|
-
}
|
|
1320
|
+
});
|
|
1321
|
+
observer.observe({ entryTypes: ['navigation', 'render'] });
|
|
2262
1322
|
}
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
const startupDelay = Number.isFinite(this.startupDelayMs) ? Math.max(0, this.startupDelayMs) : 0;
|
|
2266
|
-
if (startupDelay > 0) {
|
|
2267
|
-
const end = start + startupDelay;
|
|
2268
|
-
if (nowTs < end)
|
|
2269
|
-
return end;
|
|
2270
|
-
}
|
|
2271
|
-
return nowTs + this.batchIntervalMs;
|
|
1323
|
+
catch {
|
|
1324
|
+
// ignore
|
|
2272
1325
|
}
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
1326
|
+
}
|
|
1327
|
+
function installMiniPerformanceMonitor(report, opts = {}) {
|
|
1328
|
+
const enabled = opts === undefined ? true : !!opts;
|
|
1329
|
+
if (!enabled)
|
|
1330
|
+
return;
|
|
1331
|
+
const raw = typeof opts === 'object' && opts ? opts : {};
|
|
1332
|
+
const options = {
|
|
1333
|
+
enabled: true,
|
|
1334
|
+
reportType: raw.reportType ?? 'perf',
|
|
1335
|
+
sampleRate: raw.sampleRate ?? 1,
|
|
1336
|
+
ignoreUrls: raw.ignoreUrls ?? [],
|
|
1337
|
+
webVitals: raw.webVitals ?? true,
|
|
1338
|
+
navigationTiming: raw.navigationTiming ?? true,
|
|
1339
|
+
resourceTiming: raw.resourceTiming ?? true,
|
|
1340
|
+
maxTextLength: raw.maxTextLength ?? 2000,
|
|
1341
|
+
};
|
|
1342
|
+
installMiniProgramPerformanceMonitor(report, options);
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
function shouldSample(sampleRate) {
|
|
1346
|
+
const r = sampleRate ?? 1;
|
|
1347
|
+
if (r >= 1)
|
|
1348
|
+
return true;
|
|
1349
|
+
if (r <= 0)
|
|
1350
|
+
return false;
|
|
1351
|
+
return Math.random() < r;
|
|
1352
|
+
}
|
|
1353
|
+
function generateUUID() {
|
|
1354
|
+
const g = globalThis;
|
|
1355
|
+
if (g.crypto?.randomUUID)
|
|
1356
|
+
return g.crypto.randomUUID();
|
|
1357
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
1358
|
+
const r = Math.random() * 16 || 0;
|
|
1359
|
+
const v = c === 'x' ? r | 0 : ((r | 0) & 0x3) | 0x8;
|
|
1360
|
+
return v.toString(16);
|
|
1361
|
+
});
|
|
1362
|
+
}
|
|
1363
|
+
function safeReadUvMeta(key) {
|
|
1364
|
+
const raw = readStringStorage(key);
|
|
1365
|
+
if (!raw)
|
|
1366
|
+
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1367
|
+
try {
|
|
1368
|
+
const parsed = JSON.parse(raw);
|
|
1369
|
+
if (!parsed || typeof parsed !== 'object')
|
|
1370
|
+
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1371
|
+
const p = parsed;
|
|
1372
|
+
const firstVisitTs = typeof p.firstVisitTs === 'number' && Number.isFinite(p.firstVisitTs) ? p.firstVisitTs : Date.now();
|
|
1373
|
+
const visitCount = typeof p.visitCount === 'number' && Number.isFinite(p.visitCount) ? p.visitCount : 0;
|
|
1374
|
+
const createdAtTs = typeof p.createdAtTs === 'number' && Number.isFinite(p.createdAtTs) ? p.createdAtTs : undefined;
|
|
1375
|
+
const lastSeenTs = typeof p.lastSeenTs === 'number' && Number.isFinite(p.lastSeenTs) ? p.lastSeenTs : undefined;
|
|
1376
|
+
return { firstVisitTs, visitCount, createdAtTs, lastSeenTs };
|
|
2276
1377
|
}
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
this.report({ type: 'warn', data: payload, timestamp: Date.now() });
|
|
1378
|
+
catch {
|
|
1379
|
+
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
2280
1380
|
}
|
|
2281
|
-
|
|
2282
|
-
|
|
2283
|
-
|
|
1381
|
+
}
|
|
1382
|
+
function writeUvMeta(key, meta) {
|
|
1383
|
+
writeStringStorage(key, JSON.stringify(meta));
|
|
1384
|
+
}
|
|
1385
|
+
function getMiniProgramPagePath() {
|
|
1386
|
+
const g = globalThis;
|
|
1387
|
+
try {
|
|
1388
|
+
const pages = typeof g.getCurrentPages === 'function' ? g.getCurrentPages() : [];
|
|
1389
|
+
const last = Array.isArray(pages) ? pages[pages.length - 1] : undefined;
|
|
1390
|
+
const route = (last?.route || last?.__route__);
|
|
1391
|
+
return typeof route === 'string' ? route : '';
|
|
2284
1392
|
}
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
return;
|
|
2288
|
-
this.report({
|
|
2289
|
-
type: trackType,
|
|
2290
|
-
data: normalizeFlatFields(data, `track:${trackType}`),
|
|
2291
|
-
timestamp: Date.now(),
|
|
2292
|
-
});
|
|
1393
|
+
catch {
|
|
1394
|
+
return '';
|
|
2293
1395
|
}
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
1396
|
+
}
|
|
1397
|
+
function buildCommonUvFields(uvId, uvMeta, isFirstVisit) {
|
|
1398
|
+
return {
|
|
1399
|
+
uvId,
|
|
1400
|
+
isFirstVisit,
|
|
1401
|
+
firstVisitTs: uvMeta.firstVisitTs,
|
|
1402
|
+
visitCount: uvMeta.visitCount,
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
function truncateText(s, maxLen) {
|
|
1406
|
+
if (!s)
|
|
1407
|
+
return '';
|
|
1408
|
+
if (s.length <= maxLen)
|
|
1409
|
+
return s;
|
|
1410
|
+
return s.slice(0, maxLen);
|
|
1411
|
+
}
|
|
1412
|
+
function installMiniBehaviorMonitor(report, options = {}) {
|
|
1413
|
+
const enableTrack = options.enableTrack ?? options.enabled ?? true;
|
|
1414
|
+
if (!enableTrack)
|
|
1415
|
+
return () => { };
|
|
1416
|
+
const pvEnabled = options.pv ?? true;
|
|
1417
|
+
const uvEnabled = options.uv ?? true;
|
|
1418
|
+
const clickEnabled = options.click ?? true;
|
|
1419
|
+
const pvReportType = options.pvReportType ?? 'pv';
|
|
1420
|
+
const uvReportType = options.uvReportType ?? 'uv';
|
|
1421
|
+
const clickReportType = options.clickReportType ?? 'click';
|
|
1422
|
+
const uvIdStorageKey = options.uvIdStorageKey ?? 'cls_uv_id';
|
|
1423
|
+
const uvMetaStorageKey = options.uvMetaStorageKey ?? 'cls_uv_meta';
|
|
1424
|
+
const lastPagePathStorageKey = options.lastPagePathStorageKey ?? 'cls_last_page_path';
|
|
1425
|
+
const uvExpireDaysRaw = options.trackOptions?.uvExpireDays ?? options.uvExpireDays ?? 30;
|
|
1426
|
+
const uvExpireDays = Number.isFinite(uvExpireDaysRaw) ? Math.max(0, uvExpireDaysRaw) : 30;
|
|
1427
|
+
const uvExpireMs = uvExpireDays * 24 * 60 * 60 * 1000;
|
|
1428
|
+
const clickWhiteList = (options.trackOptions?.clickWhiteList ??
|
|
1429
|
+
options.clickWhiteList ?? ['view', 'scroll-view']).map((s) => String(s).toLowerCase());
|
|
1430
|
+
const clickMaxTextLength = options.clickMaxTextLength ?? 120;
|
|
1431
|
+
const getPagePath = options.getPagePath ?? getMiniProgramPagePath;
|
|
1432
|
+
let destroyed = false;
|
|
1433
|
+
let firstVisitFlag = false;
|
|
1434
|
+
let firstVisitConsumed = false;
|
|
1435
|
+
const uvStatePromise = (async () => {
|
|
1436
|
+
let existingUvId = readStringStorage(uvIdStorageKey);
|
|
1437
|
+
let isFirstVisit = false;
|
|
1438
|
+
const now = Date.now();
|
|
1439
|
+
const metaBefore = safeReadUvMeta(uvMetaStorageKey);
|
|
1440
|
+
const lastSeenForExpire = metaBefore.lastSeenTs ?? metaBefore.createdAtTs ?? metaBefore.firstVisitTs ?? now;
|
|
1441
|
+
const expired = uvExpireMs > 0 && now - lastSeenForExpire > uvExpireMs;
|
|
1442
|
+
if (expired) {
|
|
1443
|
+
existingUvId = null;
|
|
1444
|
+
writeUvMeta(uvMetaStorageKey, { firstVisitTs: now, visitCount: 0, createdAtTs: now, lastSeenTs: now });
|
|
1445
|
+
writeStringStorage(uvIdStorageKey, '');
|
|
2301
1446
|
}
|
|
2302
|
-
this.batchTimerDueAt = null;
|
|
2303
|
-
if (this.memoryQueue.length === 0)
|
|
2304
|
-
return;
|
|
2305
|
-
const logs = [...this.memoryQueue];
|
|
2306
|
-
this.memoryQueue = [];
|
|
2307
1447
|
try {
|
|
2308
|
-
|
|
1448
|
+
if (options.getUvId) {
|
|
1449
|
+
const maybe = options.getUvId();
|
|
1450
|
+
const resolved = typeof maybe?.then === 'function' ? await maybe : maybe;
|
|
1451
|
+
if (resolved && typeof resolved === 'string')
|
|
1452
|
+
existingUvId = resolved;
|
|
1453
|
+
}
|
|
2309
1454
|
}
|
|
2310
1455
|
catch {
|
|
2311
|
-
|
|
1456
|
+
/* ignore */
|
|
2312
1457
|
}
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
const logGroup = new sdk.LogGroup('127.0.0.1');
|
|
2337
|
-
logGroup.setSource(this.source);
|
|
2338
|
-
for (const item of logs) {
|
|
2339
|
-
const fields = this.buildReportFields(item);
|
|
2340
|
-
const log = new sdk.Log(fields.timestamp);
|
|
2341
|
-
for (const key of Object.keys(fields)) {
|
|
2342
|
-
if (key === 'timestamp')
|
|
2343
|
-
continue;
|
|
2344
|
-
log.addContent(key, stringifyLogValue(fields[key]));
|
|
1458
|
+
if (!existingUvId) {
|
|
1459
|
+
const wxAny = globalThis.wx;
|
|
1460
|
+
try {
|
|
1461
|
+
const userInfo = wxAny?.getStorageSync?.('userInfo');
|
|
1462
|
+
if (userInfo?.openid)
|
|
1463
|
+
existingUvId = String(userInfo.openid);
|
|
1464
|
+
}
|
|
1465
|
+
catch {
|
|
1466
|
+
/* ignore */
|
|
1467
|
+
}
|
|
1468
|
+
if (!existingUvId) {
|
|
1469
|
+
try {
|
|
1470
|
+
const sys = wxAny?.getSystemInfoSync?.();
|
|
1471
|
+
const deviceId = sys?.deviceId ? String(sys.deviceId) : '';
|
|
1472
|
+
const model = sys?.model ? String(sys.model) : '';
|
|
1473
|
+
const system = sys?.system ? String(sys.system) : '';
|
|
1474
|
+
const base = [deviceId || model, system].filter(Boolean).join('_');
|
|
1475
|
+
if (base)
|
|
1476
|
+
existingUvId = `${base}_${Date.now()}`;
|
|
1477
|
+
}
|
|
1478
|
+
catch {
|
|
1479
|
+
/* ignore */
|
|
1480
|
+
}
|
|
2345
1481
|
}
|
|
2346
|
-
logGroup.addLog(log);
|
|
2347
1482
|
}
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
let p;
|
|
2352
|
-
try {
|
|
2353
|
-
p = client.PutLogs(request);
|
|
1483
|
+
if (!existingUvId) {
|
|
1484
|
+
existingUvId = generateUUID();
|
|
1485
|
+
isFirstVisit = true;
|
|
2354
1486
|
}
|
|
2355
|
-
|
|
2356
|
-
|
|
1487
|
+
writeStringStorage(uvIdStorageKey, existingUvId);
|
|
1488
|
+
const meta = safeReadUvMeta(uvMetaStorageKey);
|
|
1489
|
+
const createdAt = meta.createdAtTs ?? meta.firstVisitTs ?? now;
|
|
1490
|
+
const firstVisit = meta.firstVisitTs || now;
|
|
1491
|
+
const nextMeta = {
|
|
1492
|
+
firstVisitTs: firstVisit,
|
|
1493
|
+
visitCount: (meta.visitCount || 0) + 1,
|
|
1494
|
+
createdAtTs: createdAt,
|
|
1495
|
+
lastSeenTs: now,
|
|
1496
|
+
};
|
|
1497
|
+
if (isFirstVisit) {
|
|
1498
|
+
nextMeta.firstVisitTs = now;
|
|
1499
|
+
nextMeta.createdAtTs = now;
|
|
2357
1500
|
}
|
|
2358
|
-
|
|
1501
|
+
writeUvMeta(uvMetaStorageKey, nextMeta);
|
|
1502
|
+
firstVisitFlag = isFirstVisit;
|
|
1503
|
+
return { uvId: existingUvId, isFirstVisit, meta: nextMeta };
|
|
1504
|
+
})();
|
|
1505
|
+
function safeReport(type, data) {
|
|
1506
|
+
if (destroyed)
|
|
1507
|
+
return;
|
|
1508
|
+
if (!shouldSample(options.sampleRate))
|
|
1509
|
+
return;
|
|
1510
|
+
report(type, data);
|
|
2359
1511
|
}
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
1512
|
+
function buildUvFieldsOnce(uvId, meta) {
|
|
1513
|
+
const once = firstVisitFlag && !firstVisitConsumed;
|
|
1514
|
+
if (once)
|
|
1515
|
+
firstVisitConsumed = true;
|
|
1516
|
+
return buildCommonUvFields(uvId, meta, once);
|
|
1517
|
+
}
|
|
1518
|
+
function reportPv(pagePath) {
|
|
1519
|
+
if (!pvEnabled)
|
|
2363
1520
|
return;
|
|
1521
|
+
void uvStatePromise.then(({ uvId, meta }) => {
|
|
1522
|
+
if (destroyed)
|
|
1523
|
+
return;
|
|
1524
|
+
const payload = {
|
|
1525
|
+
...buildUvFieldsOnce(uvId, meta),
|
|
1526
|
+
timestamp: Date.now(),
|
|
1527
|
+
pagePath,
|
|
1528
|
+
referrer: readStringStorage(lastPagePathStorageKey) || '',
|
|
1529
|
+
};
|
|
1530
|
+
writeStringStorage(lastPagePathStorageKey, pagePath);
|
|
1531
|
+
safeReport(pvReportType, payload);
|
|
1532
|
+
});
|
|
1533
|
+
}
|
|
1534
|
+
// MiniProgram Page Patch
|
|
1535
|
+
let restoreMiniProgramPatch = null;
|
|
1536
|
+
const g = globalThis;
|
|
1537
|
+
const patchedKey = '__beLinkClsLoggerBehaviorPatched__';
|
|
1538
|
+
if (!g[patchedKey]) {
|
|
1539
|
+
g[patchedKey] = true;
|
|
1540
|
+
const originalPage = typeof g.Page === 'function' ? g.Page : null;
|
|
1541
|
+
if (originalPage) {
|
|
1542
|
+
g.Page = function patchedPage(conf) {
|
|
1543
|
+
const originalOnShow = conf?.onShow;
|
|
1544
|
+
conf.onShow = function (...args) {
|
|
1545
|
+
if (pvEnabled) {
|
|
1546
|
+
const pagePath = getPagePath();
|
|
1547
|
+
if (pagePath?.length > 0)
|
|
1548
|
+
reportPv(pagePath);
|
|
1549
|
+
}
|
|
1550
|
+
return typeof originalOnShow === 'function' ? originalOnShow.apply(this, args) : undefined;
|
|
1551
|
+
};
|
|
1552
|
+
if (clickEnabled && conf && typeof conf === 'object') {
|
|
1553
|
+
for (const key of Object.keys(conf)) {
|
|
1554
|
+
const fn = conf[key];
|
|
1555
|
+
if (typeof fn !== 'function')
|
|
1556
|
+
continue;
|
|
1557
|
+
if (fn.__beLinkWrapped__)
|
|
1558
|
+
continue;
|
|
1559
|
+
conf[key] = function (...args) {
|
|
1560
|
+
try {
|
|
1561
|
+
const e = args?.[0];
|
|
1562
|
+
const type = e?.type;
|
|
1563
|
+
const currentTarget = e?.currentTarget;
|
|
1564
|
+
const dataset = currentTarget?.dataset;
|
|
1565
|
+
const isTap = type === 'tap' || type === 'click';
|
|
1566
|
+
if (isTap && currentTarget && dataset) {
|
|
1567
|
+
const tagNameRaw = dataset?.tagName ?? dataset?.tag ?? currentTarget?.tagName ?? '';
|
|
1568
|
+
const tagName = String(tagNameRaw || '').toLowerCase();
|
|
1569
|
+
const trackId = dataset?.trackId ? String(dataset.trackId) : '';
|
|
1570
|
+
if (!(clickWhiteList.includes(tagName) && !trackId)) {
|
|
1571
|
+
const x = typeof e?.detail?.x === 'number' ? e.detail.x : (e?.touches?.[0]?.pageX ?? 0);
|
|
1572
|
+
const y = typeof e?.detail?.y === 'number' ? e.detail.y : (e?.touches?.[0]?.pageY ?? 0);
|
|
1573
|
+
void uvStatePromise.then(({ uvId, meta }) => {
|
|
1574
|
+
if (destroyed)
|
|
1575
|
+
return;
|
|
1576
|
+
safeReport(clickReportType, {
|
|
1577
|
+
...buildUvFieldsOnce(uvId, meta),
|
|
1578
|
+
timestamp: Date.now(),
|
|
1579
|
+
pagePath: getPagePath(),
|
|
1580
|
+
elementTag: tagNameRaw ? String(tagNameRaw) : '',
|
|
1581
|
+
elementId: currentTarget?.id ? String(currentTarget.id) : '',
|
|
1582
|
+
elementClass: dataset?.className ? stringifyLogValue(dataset.className) : '',
|
|
1583
|
+
trackId,
|
|
1584
|
+
elementText: dataset?.text ? truncateText(String(dataset.text), clickMaxTextLength) : '',
|
|
1585
|
+
clickX: x,
|
|
1586
|
+
clickY: y,
|
|
1587
|
+
});
|
|
1588
|
+
});
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
catch {
|
|
1593
|
+
/* ignore */
|
|
1594
|
+
}
|
|
1595
|
+
return fn.apply(this, args);
|
|
1596
|
+
};
|
|
1597
|
+
conf[key].__beLinkWrapped__ = true;
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
return originalPage(conf);
|
|
1601
|
+
};
|
|
1602
|
+
restoreMiniProgramPatch = () => {
|
|
1603
|
+
g.Page = originalPage;
|
|
1604
|
+
g[patchedKey] = false;
|
|
1605
|
+
};
|
|
2364
1606
|
}
|
|
2365
|
-
const delayMs = Math.pow(2, retryCount) * 1000;
|
|
2366
|
-
setTimeout(async () => {
|
|
2367
|
-
try {
|
|
2368
|
-
await this.sendReportLogs(logs);
|
|
2369
|
-
}
|
|
2370
|
-
catch {
|
|
2371
|
-
this.retrySendReportLogs(logs, retryCount + 1);
|
|
2372
|
-
}
|
|
2373
|
-
}, delayMs);
|
|
2374
1607
|
}
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
1608
|
+
if (pvEnabled)
|
|
1609
|
+
reportPv(getPagePath());
|
|
1610
|
+
if (uvEnabled) {
|
|
1611
|
+
void uvStatePromise.then(({ uvId, meta }) => {
|
|
1612
|
+
if (destroyed)
|
|
1613
|
+
return;
|
|
1614
|
+
safeReport(uvReportType, {
|
|
1615
|
+
...buildUvFieldsOnce(uvId, meta),
|
|
1616
|
+
timestamp: Date.now(),
|
|
1617
|
+
pagePath: getPagePath(),
|
|
1618
|
+
});
|
|
1619
|
+
});
|
|
1620
|
+
}
|
|
1621
|
+
return () => {
|
|
1622
|
+
destroyed = true;
|
|
1623
|
+
restoreMiniProgramPatch?.();
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1626
|
+
|
|
1627
|
+
function getMiniProgramDeviceInfo(options) {
|
|
1628
|
+
const out = {
|
|
1629
|
+
envType: 'miniprogram',
|
|
1630
|
+
};
|
|
1631
|
+
const wxAny = globalThis.wx;
|
|
1632
|
+
if (!wxAny || typeof wxAny.getSystemInfoSync !== 'function')
|
|
1633
|
+
return out;
|
|
1634
|
+
try {
|
|
1635
|
+
const sys = wxAny.getSystemInfoSync();
|
|
1636
|
+
out.mpBrand = sys?.brand ? String(sys.brand) : '';
|
|
1637
|
+
out.mpModel = sys?.model ? String(sys.model) : '';
|
|
1638
|
+
out.mpSystem = sys?.system ? String(sys.system) : '';
|
|
1639
|
+
out.mpPlatform = sys?.platform ? String(sys.platform) : '';
|
|
1640
|
+
out.mpWeChatVersion = sys?.version ? String(sys.version) : '';
|
|
1641
|
+
out.mpSDKVersion = sys?.SDKVersion ? String(sys.SDKVersion) : '';
|
|
1642
|
+
out.mpScreenWidth = typeof sys?.screenWidth === 'number' ? sys.screenWidth : undefined;
|
|
1643
|
+
out.mpScreenHeight = typeof sys?.screenHeight === 'number' ? sys.screenHeight : undefined;
|
|
1644
|
+
out.mpPixelRatio = typeof sys?.pixelRatio === 'number' ? sys.pixelRatio : undefined;
|
|
1645
|
+
out.language = sys?.language ? String(sys.language) : '';
|
|
1646
|
+
}
|
|
1647
|
+
catch {
|
|
1648
|
+
// ignore
|
|
1649
|
+
}
|
|
1650
|
+
if (options.includeNetworkType) {
|
|
2378
1651
|
try {
|
|
2379
|
-
|
|
2380
|
-
|
|
1652
|
+
if (typeof wxAny.getNetworkTypeSync === 'function') {
|
|
1653
|
+
const n = wxAny.getNetworkTypeSync();
|
|
1654
|
+
out.networkType = n?.networkType ? String(n.networkType) : '';
|
|
1655
|
+
}
|
|
1656
|
+
else if (typeof wxAny.getNetworkType === 'function') {
|
|
1657
|
+
// 异步更新:先不阻塞初始化
|
|
1658
|
+
wxAny.getNetworkType({
|
|
1659
|
+
success: (res) => {
|
|
1660
|
+
try {
|
|
1661
|
+
const g = globalThis;
|
|
1662
|
+
if (!g.__beLinkClsLoggerDeviceInfo__)
|
|
1663
|
+
g.__beLinkClsLoggerDeviceInfo__ = {};
|
|
1664
|
+
g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
|
|
1665
|
+
}
|
|
1666
|
+
catch {
|
|
1667
|
+
// ignore
|
|
1668
|
+
}
|
|
1669
|
+
},
|
|
1670
|
+
});
|
|
1671
|
+
}
|
|
2381
1672
|
}
|
|
2382
1673
|
catch {
|
|
2383
|
-
|
|
1674
|
+
// ignore
|
|
2384
1675
|
}
|
|
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
1676
|
try {
|
|
2394
|
-
|
|
2395
|
-
|
|
1677
|
+
if (typeof wxAny.onNetworkStatusChange === 'function') {
|
|
1678
|
+
wxAny.onNetworkStatusChange((res) => {
|
|
1679
|
+
try {
|
|
1680
|
+
const g = globalThis;
|
|
1681
|
+
if (!g.__beLinkClsLoggerDeviceInfo__)
|
|
1682
|
+
g.__beLinkClsLoggerDeviceInfo__ = {};
|
|
1683
|
+
g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
|
|
1684
|
+
}
|
|
1685
|
+
catch {
|
|
1686
|
+
// ignore
|
|
1687
|
+
}
|
|
1688
|
+
});
|
|
1689
|
+
}
|
|
2396
1690
|
}
|
|
2397
1691
|
catch {
|
|
2398
|
-
|
|
1692
|
+
// ignore
|
|
2399
1693
|
}
|
|
2400
|
-
if (logs.length === 0)
|
|
2401
|
-
return;
|
|
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
1694
|
}
|
|
1695
|
+
return out;
|
|
2422
1696
|
}
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
const g = globalThis;
|
|
2427
|
-
return g[key] ?? null;
|
|
2428
|
-
}
|
|
2429
|
-
catch {
|
|
1697
|
+
function createMiniDeviceInfoBaseFields(opts) {
|
|
1698
|
+
const enabled = opts === undefined ? true : !!opts;
|
|
1699
|
+
if (!enabled)
|
|
2430
1700
|
return null;
|
|
2431
|
-
}
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
const candidates = [localReq, globalReq].filter((fn) => typeof fn === 'function');
|
|
2443
|
-
for (const fn of candidates) {
|
|
1701
|
+
const raw = typeof opts === 'object' && opts ? opts : {};
|
|
1702
|
+
const options = {
|
|
1703
|
+
includeUserAgent: raw.includeUserAgent ?? true,
|
|
1704
|
+
includeNetwork: raw.includeNetwork ?? true,
|
|
1705
|
+
includeNetworkType: raw.includeNetworkType ?? true,
|
|
1706
|
+
};
|
|
1707
|
+
let base = null;
|
|
1708
|
+
const globalKey = '__beLinkClsLoggerDeviceInfo__';
|
|
1709
|
+
return () => {
|
|
1710
|
+
if (!base) {
|
|
1711
|
+
base = getMiniProgramDeviceInfo(options);
|
|
2444
1712
|
try {
|
|
2445
|
-
|
|
1713
|
+
const g = globalThis;
|
|
1714
|
+
if (!g[globalKey])
|
|
1715
|
+
g[globalKey] = { ...base };
|
|
2446
1716
|
}
|
|
2447
1717
|
catch {
|
|
2448
|
-
//
|
|
1718
|
+
// ignore
|
|
2449
1719
|
}
|
|
2450
1720
|
}
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
1721
|
+
try {
|
|
1722
|
+
const g = globalThis;
|
|
1723
|
+
const extra = g[globalKey];
|
|
1724
|
+
if (extra && isPlainObject(extra))
|
|
1725
|
+
return { ...base, ...extra };
|
|
1726
|
+
}
|
|
1727
|
+
catch {
|
|
1728
|
+
// ignore
|
|
1729
|
+
}
|
|
1730
|
+
return base;
|
|
1731
|
+
};
|
|
2456
1732
|
}
|
|
2457
1733
|
|
|
2458
|
-
//
|
|
1734
|
+
// 移除静态引用,改为安全的 tryRequire + 动态加载,避免在未安装 SDK 时报错
|
|
2459
1735
|
class ClsLoggerMini extends ClsLoggerCore {
|
|
2460
1736
|
constructor() {
|
|
2461
1737
|
super(...arguments);
|
|
@@ -2464,7 +1740,7 @@ class ClsLoggerMini extends ClsLoggerCore {
|
|
|
2464
1740
|
async loadSdk() {
|
|
2465
1741
|
if (this.sdk)
|
|
2466
1742
|
return this.sdk;
|
|
2467
|
-
// 优先尝试
|
|
1743
|
+
// 1) 优先尝试 tryRequire(小程序环境可能已经有 require)
|
|
2468
1744
|
const req = tryRequire('tencentcloud-cls-sdk-js-mini');
|
|
2469
1745
|
if (req) {
|
|
2470
1746
|
const sdk = this.normalize(req);
|
|
@@ -2473,9 +1749,35 @@ class ClsLoggerMini extends ClsLoggerCore {
|
|
|
2473
1749
|
return sdk;
|
|
2474
1750
|
}
|
|
2475
1751
|
}
|
|
2476
|
-
//
|
|
2477
|
-
|
|
2478
|
-
|
|
1752
|
+
// 2) 否则尝试带 ignore 的动态导入
|
|
1753
|
+
try {
|
|
1754
|
+
const m = await import(/* @vite-ignore */ 'tencentcloud-cls-sdk-js-mini');
|
|
1755
|
+
const sdk = this.normalize(m);
|
|
1756
|
+
if (sdk) {
|
|
1757
|
+
this.sdk = sdk;
|
|
1758
|
+
return sdk;
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
catch {
|
|
1762
|
+
// ignore
|
|
1763
|
+
}
|
|
1764
|
+
console.warn('[ClsLogger] Optional SDK "tencentcloud-cls-sdk-js-mini" not found. Logging will be disabled.');
|
|
1765
|
+
throw new Error('SDK not found');
|
|
1766
|
+
}
|
|
1767
|
+
installRequestMonitor(report, options) {
|
|
1768
|
+
installMiniRequestMonitor(report, options);
|
|
1769
|
+
}
|
|
1770
|
+
installErrorMonitor(report, options) {
|
|
1771
|
+
installMiniErrorMonitor(report, options);
|
|
1772
|
+
}
|
|
1773
|
+
installPerformanceMonitor(report, options) {
|
|
1774
|
+
installMiniPerformanceMonitor(report, options);
|
|
1775
|
+
}
|
|
1776
|
+
installBehaviorMonitor(report, options) {
|
|
1777
|
+
return installMiniBehaviorMonitor(report, typeof options === 'boolean' ? {} : options);
|
|
1778
|
+
}
|
|
1779
|
+
createDeviceInfoBaseFields(options) {
|
|
1780
|
+
return createMiniDeviceInfoBaseFields(options);
|
|
2479
1781
|
}
|
|
2480
1782
|
normalize(m) {
|
|
2481
1783
|
const mod = (m?.default && m.default.AsyncClient ? m.default : m);
|