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