@jasolar/tracker-sdk 1.0.0 → 1.0.2
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/package.json +1 -1
- package/dist/index.cjs.js +0 -433
- package/dist/index.esm.js +0 -430
package/package.json
CHANGED
package/dist/index.cjs.js
DELETED
|
@@ -1,433 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* 数据上报队列,支持批量发送和定时发送。
|
|
5
|
-
*/
|
|
6
|
-
class Queue {
|
|
7
|
-
/**
|
|
8
|
-
* @param {Function} flushFn - 实际发送数据的函数,接收一个数据数组作为参数。
|
|
9
|
-
* @param {Object} options - 配置项
|
|
10
|
-
* @param {number} [options.delay=1000] - 批量发送的延迟时间(毫秒)。
|
|
11
|
-
* @param {number} [options.maxBatchSize=10] - 最大批量大小,达到此数量时立即发送。
|
|
12
|
-
*/
|
|
13
|
-
constructor(flushFn, options = {}) {
|
|
14
|
-
this.list = [];
|
|
15
|
-
this.flushFn = flushFn;
|
|
16
|
-
this.timer = null;
|
|
17
|
-
this.delay = options.delay || 1000;
|
|
18
|
-
this.maxBatchSize = options.maxBatchSize || 10;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* 将数据推入队列。
|
|
23
|
-
* @param {Object} data - 要推入队列的数据。
|
|
24
|
-
*/
|
|
25
|
-
push(data) {
|
|
26
|
-
this.list.push(data);
|
|
27
|
-
|
|
28
|
-
// 如果达到最大批量大小,立即发送
|
|
29
|
-
if (this.list.length >= this.maxBatchSize) {
|
|
30
|
-
this.flush();
|
|
31
|
-
return;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
// 如果没有定时器,则设置一个定时器在延迟后发送
|
|
35
|
-
if (!this.timer) {
|
|
36
|
-
this.timer = setTimeout(() => {
|
|
37
|
-
this.flush();
|
|
38
|
-
}, this.delay);
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* 立即发送队列中的所有数据。
|
|
44
|
-
*/
|
|
45
|
-
flush() {
|
|
46
|
-
if (!this.list.length) {
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// 复制一份数据列表,防止在发送过程中 list 被修改
|
|
51
|
-
const dataToSend = [...this.list];
|
|
52
|
-
this.list = []; // 清空队列
|
|
53
|
-
|
|
54
|
-
try {
|
|
55
|
-
this.flushFn(dataToSend);
|
|
56
|
-
} catch (error) {
|
|
57
|
-
console.error("[Tracker SDK] Failed to flush data:", error);
|
|
58
|
-
// 可以在这里实现简单的重试逻辑,例如将 dataToSend 重新放回队列
|
|
59
|
-
// 但为了简单起见,目前仅打印错误
|
|
60
|
-
} finally {
|
|
61
|
-
clearTimeout(this.timer);
|
|
62
|
-
this.timer = null;
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* 底层数据发送函数。
|
|
69
|
-
* 优先使用 navigator.sendBeacon,如果不支持则使用 fetch 回退。
|
|
70
|
-
*
|
|
71
|
-
* @param {string} url - 数据接收地址
|
|
72
|
-
* @param {Array|Object} data - 要发送的数据,会被转换为 JSON 字符串。
|
|
73
|
-
*/
|
|
74
|
-
function send(url, data) {
|
|
75
|
-
if (!url) {
|
|
76
|
-
return;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
const body = JSON.stringify(data);
|
|
80
|
-
|
|
81
|
-
// 优先使用 sendBeacon (在页面关闭时可靠性最高,且不阻塞主线程)
|
|
82
|
-
if (typeof navigator !== 'undefined' && navigator.sendBeacon) {
|
|
83
|
-
// 使用 Blob 设置正确的 Content-Type,确保后端能正确识别 JSON
|
|
84
|
-
const blob = new Blob([body], { type: 'application/json' });
|
|
85
|
-
const success = navigator.sendBeacon(url, blob);
|
|
86
|
-
|
|
87
|
-
// 如果 sendBeacon 成功,直接返回
|
|
88
|
-
if (success) return;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// 回退到 fetch API
|
|
92
|
-
if (typeof fetch === 'function') {
|
|
93
|
-
fetch(url, {
|
|
94
|
-
method: 'POST',
|
|
95
|
-
body,
|
|
96
|
-
headers: {
|
|
97
|
-
'Content-Type': 'application/json'
|
|
98
|
-
},
|
|
99
|
-
// keepalive 选项允许请求在页面关闭后继续进行(在支持的浏览器中)
|
|
100
|
-
keepalive: true
|
|
101
|
-
}).catch(err => {
|
|
102
|
-
// 埋点上报失败通常不应影响业务流程,仅在控制台静默记录
|
|
103
|
-
console.warn('[Tracker SDK] Data report failed via fetch:', err);
|
|
104
|
-
});
|
|
105
|
-
} else {
|
|
106
|
-
// 如果 fetch 也不支持(极旧浏览器),可以考虑回退到 XHR,但目前大部分现代环境都支持 fetch。
|
|
107
|
-
console.warn('[Tracker SDK] No transport method available (sendBeacon/fetch).');
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
function uuid() {
|
|
112
|
-
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
113
|
-
const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
|
|
114
|
-
return v.toString(16);
|
|
115
|
-
});
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* 简单的本地存储封装
|
|
120
|
-
*/
|
|
121
|
-
const storage = {
|
|
122
|
-
get(key) {
|
|
123
|
-
try {
|
|
124
|
-
const val = localStorage.getItem(key);
|
|
125
|
-
if (!val) return null;
|
|
126
|
-
return JSON.parse(val);
|
|
127
|
-
} catch (e) {
|
|
128
|
-
console.warn(`[Tracker SDK] Error parsing storage key "${key}":`, e);
|
|
129
|
-
return null;
|
|
130
|
-
}
|
|
131
|
-
},
|
|
132
|
-
set(key, value) {
|
|
133
|
-
try {
|
|
134
|
-
localStorage.setItem(key, JSON.stringify(value));
|
|
135
|
-
} catch (e) {
|
|
136
|
-
console.warn(`[Tracker SDK] Error saving to storage key "${key}":`, e);
|
|
137
|
-
}
|
|
138
|
-
},
|
|
139
|
-
remove(key) {
|
|
140
|
-
localStorage.removeItem(key);
|
|
141
|
-
}
|
|
142
|
-
};
|
|
143
|
-
|
|
144
|
-
const now = () => Date.now();
|
|
145
|
-
|
|
146
|
-
// src/core/session.js
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
const SESSION_KEY = 'TRACKER_SESSION_ID';
|
|
150
|
-
const SESSION_TIME_KEY = 'TRACKER_SESSION_TIME';
|
|
151
|
-
|
|
152
|
-
// 默认 30 分钟过期
|
|
153
|
-
const SESSION_EXPIRE = 30 * 60 * 1000;
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* 获取或创建 session_id。
|
|
157
|
-
* 如果 session 不存在或已过期,则生成新的 session_id。
|
|
158
|
-
* @returns {string} 当前的 session_id
|
|
159
|
-
*/
|
|
160
|
-
function getSessionId() {
|
|
161
|
-
const sid = storage.get(SESSION_KEY);
|
|
162
|
-
const lastTime = Number(storage.get(SESSION_TIME_KEY) || 0); // 确保是数字
|
|
163
|
-
|
|
164
|
-
// 如果不存在 或 已过期
|
|
165
|
-
if (!sid || now() - lastTime > SESSION_EXPIRE) {
|
|
166
|
-
const newSid = uuid();
|
|
167
|
-
storage.set(SESSION_KEY, newSid);
|
|
168
|
-
storage.set(SESSION_TIME_KEY, now());
|
|
169
|
-
return newSid;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
return sid;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/**
|
|
176
|
-
* 刷新 session 的活跃时间(用户活跃时调用),延长 session 生命周期。
|
|
177
|
-
*/
|
|
178
|
-
function refreshSession() {
|
|
179
|
-
storage.set(SESSION_TIME_KEY, now());
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* 节流函数:在指定的时间间隔内,无论触发多少次,函数只执行一次。
|
|
184
|
-
* 包含最后一次触发的延迟执行(trailing edge)。
|
|
185
|
-
*
|
|
186
|
-
* @param {Function} fn - 需要节流的函数
|
|
187
|
-
* @param {number} delay - 间隔时间(毫秒)
|
|
188
|
-
* @returns {Function} - 节流后的函数
|
|
189
|
-
*/
|
|
190
|
-
function throttle(fn, delay) {
|
|
191
|
-
var lastTime = 0;
|
|
192
|
-
var timer = null;
|
|
193
|
-
|
|
194
|
-
return function() {
|
|
195
|
-
var context = this;
|
|
196
|
-
var args = arguments;
|
|
197
|
-
var now = Date.now();
|
|
198
|
-
|
|
199
|
-
if (now - lastTime >= delay) {
|
|
200
|
-
// 如果距离上次执行时间超过了延迟时间,立即执行
|
|
201
|
-
if (timer) {
|
|
202
|
-
clearTimeout(timer);
|
|
203
|
-
timer = null;
|
|
204
|
-
}
|
|
205
|
-
fn.apply(context, args);
|
|
206
|
-
lastTime = now;
|
|
207
|
-
} else if (!timer) {
|
|
208
|
-
// 否则,如果没有设置定时器,则设置一个定时器在剩余时间后执行
|
|
209
|
-
// 这保证了最后一次触发一定会被执行(trailing edge)
|
|
210
|
-
timer = setTimeout(function() {
|
|
211
|
-
fn.apply(context, args);
|
|
212
|
-
lastTime = Date.now();
|
|
213
|
-
timer = null;
|
|
214
|
-
}, delay - (now - lastTime));
|
|
215
|
-
}
|
|
216
|
-
};
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
/**
|
|
220
|
-
* Tracker 核心类
|
|
221
|
-
*/
|
|
222
|
-
class Tracker {
|
|
223
|
-
/**
|
|
224
|
-
* @param {Object} options - 初始化配置项
|
|
225
|
-
* @param {string} options.endPoint - 数据上报接口地址
|
|
226
|
-
* @param {number} [options.delay=1000] - 批量上报延迟
|
|
227
|
-
* @param {number} [options.maxBatchSize=10] - 批量上报最大条数
|
|
228
|
-
*/
|
|
229
|
-
constructor(options = {}) {
|
|
230
|
-
if (!options.endPoint) {
|
|
231
|
-
console.error("[Tracker SDK] endPoint is required for initialization.");
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
this.options = {
|
|
235
|
-
delay: 1000,
|
|
236
|
-
maxBatchSize: 10,
|
|
237
|
-
...options
|
|
238
|
-
};
|
|
239
|
-
|
|
240
|
-
this.deviceId = uuid();
|
|
241
|
-
this.sessionId = getSessionId();
|
|
242
|
-
|
|
243
|
-
this.userId = null;
|
|
244
|
-
this.globalExt = {};
|
|
245
|
-
|
|
246
|
-
this.current = null;
|
|
247
|
-
this.lastActiveTime = now();
|
|
248
|
-
|
|
249
|
-
this.queue = new Queue((data) => {
|
|
250
|
-
if (this.options.endPoint) {
|
|
251
|
-
send(this.options.endPoint, data);
|
|
252
|
-
}
|
|
253
|
-
}, {
|
|
254
|
-
delay: this.options.delay,
|
|
255
|
-
maxBatchSize: this.options.maxBatchSize
|
|
256
|
-
});
|
|
257
|
-
|
|
258
|
-
this.plugins = [];
|
|
259
|
-
|
|
260
|
-
// 自动绑定活跃检测和生命周期监听
|
|
261
|
-
this._bindActivity();
|
|
262
|
-
this._bindLifecycle();
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
/***********插件**********/
|
|
266
|
-
/**
|
|
267
|
-
* 使用插件扩展 SDK 功能
|
|
268
|
-
* @param {Function} plugin - 插件函数
|
|
269
|
-
*/
|
|
270
|
-
use(plugin) {
|
|
271
|
-
if (typeof plugin === 'function') {
|
|
272
|
-
plugin(this);
|
|
273
|
-
this.plugins.push(plugin);
|
|
274
|
-
} else {
|
|
275
|
-
console.warn("[Tracker SDK] Plugin must be a function.");
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
/***********用户**********/
|
|
280
|
-
/**
|
|
281
|
-
* 设置用户 ID
|
|
282
|
-
* @param {string|number} userId
|
|
283
|
-
*/
|
|
284
|
-
setUser(userId) {
|
|
285
|
-
this.userId = userId;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/**
|
|
289
|
-
* 设置全局扩展参数
|
|
290
|
-
* @param {Object} ext
|
|
291
|
-
*/
|
|
292
|
-
setExt(ext) {
|
|
293
|
-
this.globalExt = {
|
|
294
|
-
...this.globalExt,
|
|
295
|
-
...ext
|
|
296
|
-
};
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
/***********行为**********/
|
|
300
|
-
/**
|
|
301
|
-
* 记录进入模块
|
|
302
|
-
* @param {Object} module
|
|
303
|
-
*/
|
|
304
|
-
enter(module) {
|
|
305
|
-
// 如果当前已经在某个模块中,先触发离开逻辑
|
|
306
|
-
if (this.current) {
|
|
307
|
-
this.leave();
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
this.current = {
|
|
311
|
-
...module,
|
|
312
|
-
enterTime: now()
|
|
313
|
-
};
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
/**
|
|
317
|
-
* 记录离开模块
|
|
318
|
-
* @param {boolean} force - 是否强制使用当前时间作为结束时间(用于页面卸载等场景)
|
|
319
|
-
*/
|
|
320
|
-
leave(force = false) {
|
|
321
|
-
if (!this.current) {
|
|
322
|
-
return;
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
const endTime = force ? now() : this.lastActiveTime;
|
|
326
|
-
const duration = Math.max(0, endTime - this.current.enterTime);
|
|
327
|
-
|
|
328
|
-
const event = {
|
|
329
|
-
event: 'module_leave',
|
|
330
|
-
timeStamp: now(),
|
|
331
|
-
session_id: this.sessionId,
|
|
332
|
-
user_id: this.userId,
|
|
333
|
-
device_id: this.deviceId,
|
|
334
|
-
context: {
|
|
335
|
-
system: this.current.system,
|
|
336
|
-
module: this.current.module,
|
|
337
|
-
sub_module: this.current.sub_module,
|
|
338
|
-
},
|
|
339
|
-
duration,
|
|
340
|
-
ext: this.globalExt
|
|
341
|
-
};
|
|
342
|
-
|
|
343
|
-
this.queue.push(event);
|
|
344
|
-
this.current = null;
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
/**
|
|
348
|
-
* 上报自定义事件
|
|
349
|
-
* @param {string} eventName
|
|
350
|
-
* @param {Object} params
|
|
351
|
-
*/
|
|
352
|
-
track(eventName, params = {}) {
|
|
353
|
-
this.queue.push({
|
|
354
|
-
event: eventName,
|
|
355
|
-
timeStamp: now(),
|
|
356
|
-
session_id: this.sessionId,
|
|
357
|
-
user_id: this.userId,
|
|
358
|
-
device_id: this.deviceId,
|
|
359
|
-
ext: {
|
|
360
|
-
...this.globalExt,
|
|
361
|
-
...params
|
|
362
|
-
}
|
|
363
|
-
});
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
/***********活跃检测**********/
|
|
367
|
-
_bindActivity() {
|
|
368
|
-
const update = () => {
|
|
369
|
-
this.lastActiveTime = now();
|
|
370
|
-
refreshSession(); // 用户活跃时刷新 Session 有效期
|
|
371
|
-
};
|
|
372
|
-
|
|
373
|
-
const events = ['click', 'keydown', 'touchstart'];
|
|
374
|
-
events.forEach(event => {
|
|
375
|
-
document.addEventListener(event, update, { passive: true });
|
|
376
|
-
});
|
|
377
|
-
|
|
378
|
-
// 对高频事件进行节流
|
|
379
|
-
document.addEventListener('mousemove', throttle(update, 5000), { passive: true });
|
|
380
|
-
document.addEventListener('scroll', throttle(update, 500), { passive: true });
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
/***********生命周期**********/
|
|
384
|
-
_bindLifecycle() {
|
|
385
|
-
// 页面卸载或隐藏时,上报当前模块的停留时间并强制刷新队列
|
|
386
|
-
const flushData = () => {
|
|
387
|
-
this.leave(true);
|
|
388
|
-
this.queue.flush();
|
|
389
|
-
};
|
|
390
|
-
|
|
391
|
-
window.addEventListener('beforeunload', flushData);
|
|
392
|
-
|
|
393
|
-
document.addEventListener('visibilitychange', () => {
|
|
394
|
-
if (document.visibilityState === 'hidden') {
|
|
395
|
-
flushData();
|
|
396
|
-
}
|
|
397
|
-
});
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
let instance = null;
|
|
402
|
-
|
|
403
|
-
/**
|
|
404
|
-
* 初始化 Tracker SDK。
|
|
405
|
-
* 如果 SDK 已经被初始化,将抛出错误。
|
|
406
|
-
* @param {Object} options - 初始化选项
|
|
407
|
-
* @returns {Tracker} Tracker 实例
|
|
408
|
-
* @throws {Error} 如果 SDK 已经被初始化
|
|
409
|
-
*/
|
|
410
|
-
function initTracker(options) {
|
|
411
|
-
if (instance) {
|
|
412
|
-
console.warn("[Tracker SDK] Tracker has already been initialized. Returning existing instance.");
|
|
413
|
-
return instance;
|
|
414
|
-
}
|
|
415
|
-
instance = new Tracker(options);
|
|
416
|
-
return instance;
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
/**
|
|
420
|
-
* 获取 Tracker SDK 实例。
|
|
421
|
-
* 如果 SDK 尚未初始化,将抛出错误。
|
|
422
|
-
* @returns {Tracker} Tracker 实例
|
|
423
|
-
* @throws {Error} 如果 SDK 尚未初始化
|
|
424
|
-
*/
|
|
425
|
-
function getTracker() {
|
|
426
|
-
if (!instance) {
|
|
427
|
-
throw new Error("[Tracker SDK] Tracker has not been initialized. Call initTracker() first.");
|
|
428
|
-
}
|
|
429
|
-
return instance;
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
exports.getTracker = getTracker;
|
|
433
|
-
exports.initTracker = initTracker;
|
package/dist/index.esm.js
DELETED
|
@@ -1,430 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 数据上报队列,支持批量发送和定时发送。
|
|
3
|
-
*/
|
|
4
|
-
class Queue {
|
|
5
|
-
/**
|
|
6
|
-
* @param {Function} flushFn - 实际发送数据的函数,接收一个数据数组作为参数。
|
|
7
|
-
* @param {Object} options - 配置项
|
|
8
|
-
* @param {number} [options.delay=1000] - 批量发送的延迟时间(毫秒)。
|
|
9
|
-
* @param {number} [options.maxBatchSize=10] - 最大批量大小,达到此数量时立即发送。
|
|
10
|
-
*/
|
|
11
|
-
constructor(flushFn, options = {}) {
|
|
12
|
-
this.list = [];
|
|
13
|
-
this.flushFn = flushFn;
|
|
14
|
-
this.timer = null;
|
|
15
|
-
this.delay = options.delay || 1000;
|
|
16
|
-
this.maxBatchSize = options.maxBatchSize || 10;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* 将数据推入队列。
|
|
21
|
-
* @param {Object} data - 要推入队列的数据。
|
|
22
|
-
*/
|
|
23
|
-
push(data) {
|
|
24
|
-
this.list.push(data);
|
|
25
|
-
|
|
26
|
-
// 如果达到最大批量大小,立即发送
|
|
27
|
-
if (this.list.length >= this.maxBatchSize) {
|
|
28
|
-
this.flush();
|
|
29
|
-
return;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// 如果没有定时器,则设置一个定时器在延迟后发送
|
|
33
|
-
if (!this.timer) {
|
|
34
|
-
this.timer = setTimeout(() => {
|
|
35
|
-
this.flush();
|
|
36
|
-
}, this.delay);
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* 立即发送队列中的所有数据。
|
|
42
|
-
*/
|
|
43
|
-
flush() {
|
|
44
|
-
if (!this.list.length) {
|
|
45
|
-
return;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
// 复制一份数据列表,防止在发送过程中 list 被修改
|
|
49
|
-
const dataToSend = [...this.list];
|
|
50
|
-
this.list = []; // 清空队列
|
|
51
|
-
|
|
52
|
-
try {
|
|
53
|
-
this.flushFn(dataToSend);
|
|
54
|
-
} catch (error) {
|
|
55
|
-
console.error("[Tracker SDK] Failed to flush data:", error);
|
|
56
|
-
// 可以在这里实现简单的重试逻辑,例如将 dataToSend 重新放回队列
|
|
57
|
-
// 但为了简单起见,目前仅打印错误
|
|
58
|
-
} finally {
|
|
59
|
-
clearTimeout(this.timer);
|
|
60
|
-
this.timer = null;
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* 底层数据发送函数。
|
|
67
|
-
* 优先使用 navigator.sendBeacon,如果不支持则使用 fetch 回退。
|
|
68
|
-
*
|
|
69
|
-
* @param {string} url - 数据接收地址
|
|
70
|
-
* @param {Array|Object} data - 要发送的数据,会被转换为 JSON 字符串。
|
|
71
|
-
*/
|
|
72
|
-
function send(url, data) {
|
|
73
|
-
if (!url) {
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
const body = JSON.stringify(data);
|
|
78
|
-
|
|
79
|
-
// 优先使用 sendBeacon (在页面关闭时可靠性最高,且不阻塞主线程)
|
|
80
|
-
if (typeof navigator !== 'undefined' && navigator.sendBeacon) {
|
|
81
|
-
// 使用 Blob 设置正确的 Content-Type,确保后端能正确识别 JSON
|
|
82
|
-
const blob = new Blob([body], { type: 'application/json' });
|
|
83
|
-
const success = navigator.sendBeacon(url, blob);
|
|
84
|
-
|
|
85
|
-
// 如果 sendBeacon 成功,直接返回
|
|
86
|
-
if (success) return;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// 回退到 fetch API
|
|
90
|
-
if (typeof fetch === 'function') {
|
|
91
|
-
fetch(url, {
|
|
92
|
-
method: 'POST',
|
|
93
|
-
body,
|
|
94
|
-
headers: {
|
|
95
|
-
'Content-Type': 'application/json'
|
|
96
|
-
},
|
|
97
|
-
// keepalive 选项允许请求在页面关闭后继续进行(在支持的浏览器中)
|
|
98
|
-
keepalive: true
|
|
99
|
-
}).catch(err => {
|
|
100
|
-
// 埋点上报失败通常不应影响业务流程,仅在控制台静默记录
|
|
101
|
-
console.warn('[Tracker SDK] Data report failed via fetch:', err);
|
|
102
|
-
});
|
|
103
|
-
} else {
|
|
104
|
-
// 如果 fetch 也不支持(极旧浏览器),可以考虑回退到 XHR,但目前大部分现代环境都支持 fetch。
|
|
105
|
-
console.warn('[Tracker SDK] No transport method available (sendBeacon/fetch).');
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
function uuid() {
|
|
110
|
-
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
111
|
-
const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
|
|
112
|
-
return v.toString(16);
|
|
113
|
-
});
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* 简单的本地存储封装
|
|
118
|
-
*/
|
|
119
|
-
const storage = {
|
|
120
|
-
get(key) {
|
|
121
|
-
try {
|
|
122
|
-
const val = localStorage.getItem(key);
|
|
123
|
-
if (!val) return null;
|
|
124
|
-
return JSON.parse(val);
|
|
125
|
-
} catch (e) {
|
|
126
|
-
console.warn(`[Tracker SDK] Error parsing storage key "${key}":`, e);
|
|
127
|
-
return null;
|
|
128
|
-
}
|
|
129
|
-
},
|
|
130
|
-
set(key, value) {
|
|
131
|
-
try {
|
|
132
|
-
localStorage.setItem(key, JSON.stringify(value));
|
|
133
|
-
} catch (e) {
|
|
134
|
-
console.warn(`[Tracker SDK] Error saving to storage key "${key}":`, e);
|
|
135
|
-
}
|
|
136
|
-
},
|
|
137
|
-
remove(key) {
|
|
138
|
-
localStorage.removeItem(key);
|
|
139
|
-
}
|
|
140
|
-
};
|
|
141
|
-
|
|
142
|
-
const now = () => Date.now();
|
|
143
|
-
|
|
144
|
-
// src/core/session.js
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
const SESSION_KEY = 'TRACKER_SESSION_ID';
|
|
148
|
-
const SESSION_TIME_KEY = 'TRACKER_SESSION_TIME';
|
|
149
|
-
|
|
150
|
-
// 默认 30 分钟过期
|
|
151
|
-
const SESSION_EXPIRE = 30 * 60 * 1000;
|
|
152
|
-
|
|
153
|
-
/**
|
|
154
|
-
* 获取或创建 session_id。
|
|
155
|
-
* 如果 session 不存在或已过期,则生成新的 session_id。
|
|
156
|
-
* @returns {string} 当前的 session_id
|
|
157
|
-
*/
|
|
158
|
-
function getSessionId() {
|
|
159
|
-
const sid = storage.get(SESSION_KEY);
|
|
160
|
-
const lastTime = Number(storage.get(SESSION_TIME_KEY) || 0); // 确保是数字
|
|
161
|
-
|
|
162
|
-
// 如果不存在 或 已过期
|
|
163
|
-
if (!sid || now() - lastTime > SESSION_EXPIRE) {
|
|
164
|
-
const newSid = uuid();
|
|
165
|
-
storage.set(SESSION_KEY, newSid);
|
|
166
|
-
storage.set(SESSION_TIME_KEY, now());
|
|
167
|
-
return newSid;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
return sid;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* 刷新 session 的活跃时间(用户活跃时调用),延长 session 生命周期。
|
|
175
|
-
*/
|
|
176
|
-
function refreshSession() {
|
|
177
|
-
storage.set(SESSION_TIME_KEY, now());
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* 节流函数:在指定的时间间隔内,无论触发多少次,函数只执行一次。
|
|
182
|
-
* 包含最后一次触发的延迟执行(trailing edge)。
|
|
183
|
-
*
|
|
184
|
-
* @param {Function} fn - 需要节流的函数
|
|
185
|
-
* @param {number} delay - 间隔时间(毫秒)
|
|
186
|
-
* @returns {Function} - 节流后的函数
|
|
187
|
-
*/
|
|
188
|
-
function throttle(fn, delay) {
|
|
189
|
-
var lastTime = 0;
|
|
190
|
-
var timer = null;
|
|
191
|
-
|
|
192
|
-
return function() {
|
|
193
|
-
var context = this;
|
|
194
|
-
var args = arguments;
|
|
195
|
-
var now = Date.now();
|
|
196
|
-
|
|
197
|
-
if (now - lastTime >= delay) {
|
|
198
|
-
// 如果距离上次执行时间超过了延迟时间,立即执行
|
|
199
|
-
if (timer) {
|
|
200
|
-
clearTimeout(timer);
|
|
201
|
-
timer = null;
|
|
202
|
-
}
|
|
203
|
-
fn.apply(context, args);
|
|
204
|
-
lastTime = now;
|
|
205
|
-
} else if (!timer) {
|
|
206
|
-
// 否则,如果没有设置定时器,则设置一个定时器在剩余时间后执行
|
|
207
|
-
// 这保证了最后一次触发一定会被执行(trailing edge)
|
|
208
|
-
timer = setTimeout(function() {
|
|
209
|
-
fn.apply(context, args);
|
|
210
|
-
lastTime = Date.now();
|
|
211
|
-
timer = null;
|
|
212
|
-
}, delay - (now - lastTime));
|
|
213
|
-
}
|
|
214
|
-
};
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
/**
|
|
218
|
-
* Tracker 核心类
|
|
219
|
-
*/
|
|
220
|
-
class Tracker {
|
|
221
|
-
/**
|
|
222
|
-
* @param {Object} options - 初始化配置项
|
|
223
|
-
* @param {string} options.endPoint - 数据上报接口地址
|
|
224
|
-
* @param {number} [options.delay=1000] - 批量上报延迟
|
|
225
|
-
* @param {number} [options.maxBatchSize=10] - 批量上报最大条数
|
|
226
|
-
*/
|
|
227
|
-
constructor(options = {}) {
|
|
228
|
-
if (!options.endPoint) {
|
|
229
|
-
console.error("[Tracker SDK] endPoint is required for initialization.");
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
this.options = {
|
|
233
|
-
delay: 1000,
|
|
234
|
-
maxBatchSize: 10,
|
|
235
|
-
...options
|
|
236
|
-
};
|
|
237
|
-
|
|
238
|
-
this.deviceId = uuid();
|
|
239
|
-
this.sessionId = getSessionId();
|
|
240
|
-
|
|
241
|
-
this.userId = null;
|
|
242
|
-
this.globalExt = {};
|
|
243
|
-
|
|
244
|
-
this.current = null;
|
|
245
|
-
this.lastActiveTime = now();
|
|
246
|
-
|
|
247
|
-
this.queue = new Queue((data) => {
|
|
248
|
-
if (this.options.endPoint) {
|
|
249
|
-
send(this.options.endPoint, data);
|
|
250
|
-
}
|
|
251
|
-
}, {
|
|
252
|
-
delay: this.options.delay,
|
|
253
|
-
maxBatchSize: this.options.maxBatchSize
|
|
254
|
-
});
|
|
255
|
-
|
|
256
|
-
this.plugins = [];
|
|
257
|
-
|
|
258
|
-
// 自动绑定活跃检测和生命周期监听
|
|
259
|
-
this._bindActivity();
|
|
260
|
-
this._bindLifecycle();
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
/***********插件**********/
|
|
264
|
-
/**
|
|
265
|
-
* 使用插件扩展 SDK 功能
|
|
266
|
-
* @param {Function} plugin - 插件函数
|
|
267
|
-
*/
|
|
268
|
-
use(plugin) {
|
|
269
|
-
if (typeof plugin === 'function') {
|
|
270
|
-
plugin(this);
|
|
271
|
-
this.plugins.push(plugin);
|
|
272
|
-
} else {
|
|
273
|
-
console.warn("[Tracker SDK] Plugin must be a function.");
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
/***********用户**********/
|
|
278
|
-
/**
|
|
279
|
-
* 设置用户 ID
|
|
280
|
-
* @param {string|number} userId
|
|
281
|
-
*/
|
|
282
|
-
setUser(userId) {
|
|
283
|
-
this.userId = userId;
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
/**
|
|
287
|
-
* 设置全局扩展参数
|
|
288
|
-
* @param {Object} ext
|
|
289
|
-
*/
|
|
290
|
-
setExt(ext) {
|
|
291
|
-
this.globalExt = {
|
|
292
|
-
...this.globalExt,
|
|
293
|
-
...ext
|
|
294
|
-
};
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
/***********行为**********/
|
|
298
|
-
/**
|
|
299
|
-
* 记录进入模块
|
|
300
|
-
* @param {Object} module
|
|
301
|
-
*/
|
|
302
|
-
enter(module) {
|
|
303
|
-
// 如果当前已经在某个模块中,先触发离开逻辑
|
|
304
|
-
if (this.current) {
|
|
305
|
-
this.leave();
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
this.current = {
|
|
309
|
-
...module,
|
|
310
|
-
enterTime: now()
|
|
311
|
-
};
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
/**
|
|
315
|
-
* 记录离开模块
|
|
316
|
-
* @param {boolean} force - 是否强制使用当前时间作为结束时间(用于页面卸载等场景)
|
|
317
|
-
*/
|
|
318
|
-
leave(force = false) {
|
|
319
|
-
if (!this.current) {
|
|
320
|
-
return;
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
const endTime = force ? now() : this.lastActiveTime;
|
|
324
|
-
const duration = Math.max(0, endTime - this.current.enterTime);
|
|
325
|
-
|
|
326
|
-
const event = {
|
|
327
|
-
event: 'module_leave',
|
|
328
|
-
timeStamp: now(),
|
|
329
|
-
session_id: this.sessionId,
|
|
330
|
-
user_id: this.userId,
|
|
331
|
-
device_id: this.deviceId,
|
|
332
|
-
context: {
|
|
333
|
-
system: this.current.system,
|
|
334
|
-
module: this.current.module,
|
|
335
|
-
sub_module: this.current.sub_module,
|
|
336
|
-
},
|
|
337
|
-
duration,
|
|
338
|
-
ext: this.globalExt
|
|
339
|
-
};
|
|
340
|
-
|
|
341
|
-
this.queue.push(event);
|
|
342
|
-
this.current = null;
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
/**
|
|
346
|
-
* 上报自定义事件
|
|
347
|
-
* @param {string} eventName
|
|
348
|
-
* @param {Object} params
|
|
349
|
-
*/
|
|
350
|
-
track(eventName, params = {}) {
|
|
351
|
-
this.queue.push({
|
|
352
|
-
event: eventName,
|
|
353
|
-
timeStamp: now(),
|
|
354
|
-
session_id: this.sessionId,
|
|
355
|
-
user_id: this.userId,
|
|
356
|
-
device_id: this.deviceId,
|
|
357
|
-
ext: {
|
|
358
|
-
...this.globalExt,
|
|
359
|
-
...params
|
|
360
|
-
}
|
|
361
|
-
});
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
/***********活跃检测**********/
|
|
365
|
-
_bindActivity() {
|
|
366
|
-
const update = () => {
|
|
367
|
-
this.lastActiveTime = now();
|
|
368
|
-
refreshSession(); // 用户活跃时刷新 Session 有效期
|
|
369
|
-
};
|
|
370
|
-
|
|
371
|
-
const events = ['click', 'keydown', 'touchstart'];
|
|
372
|
-
events.forEach(event => {
|
|
373
|
-
document.addEventListener(event, update, { passive: true });
|
|
374
|
-
});
|
|
375
|
-
|
|
376
|
-
// 对高频事件进行节流
|
|
377
|
-
document.addEventListener('mousemove', throttle(update, 5000), { passive: true });
|
|
378
|
-
document.addEventListener('scroll', throttle(update, 500), { passive: true });
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
/***********生命周期**********/
|
|
382
|
-
_bindLifecycle() {
|
|
383
|
-
// 页面卸载或隐藏时,上报当前模块的停留时间并强制刷新队列
|
|
384
|
-
const flushData = () => {
|
|
385
|
-
this.leave(true);
|
|
386
|
-
this.queue.flush();
|
|
387
|
-
};
|
|
388
|
-
|
|
389
|
-
window.addEventListener('beforeunload', flushData);
|
|
390
|
-
|
|
391
|
-
document.addEventListener('visibilitychange', () => {
|
|
392
|
-
if (document.visibilityState === 'hidden') {
|
|
393
|
-
flushData();
|
|
394
|
-
}
|
|
395
|
-
});
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
let instance = null;
|
|
400
|
-
|
|
401
|
-
/**
|
|
402
|
-
* 初始化 Tracker SDK。
|
|
403
|
-
* 如果 SDK 已经被初始化,将抛出错误。
|
|
404
|
-
* @param {Object} options - 初始化选项
|
|
405
|
-
* @returns {Tracker} Tracker 实例
|
|
406
|
-
* @throws {Error} 如果 SDK 已经被初始化
|
|
407
|
-
*/
|
|
408
|
-
function initTracker(options) {
|
|
409
|
-
if (instance) {
|
|
410
|
-
console.warn("[Tracker SDK] Tracker has already been initialized. Returning existing instance.");
|
|
411
|
-
return instance;
|
|
412
|
-
}
|
|
413
|
-
instance = new Tracker(options);
|
|
414
|
-
return instance;
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
/**
|
|
418
|
-
* 获取 Tracker SDK 实例。
|
|
419
|
-
* 如果 SDK 尚未初始化,将抛出错误。
|
|
420
|
-
* @returns {Tracker} Tracker 实例
|
|
421
|
-
* @throws {Error} 如果 SDK 尚未初始化
|
|
422
|
-
*/
|
|
423
|
-
function getTracker() {
|
|
424
|
-
if (!instance) {
|
|
425
|
-
throw new Error("[Tracker SDK] Tracker has not been initialized. Call initTracker() first.");
|
|
426
|
-
}
|
|
427
|
-
return instance;
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
export { getTracker, initTracker };
|