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