@yysports/tools 1.1.0 → 2.0.0

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.
Files changed (56) hide show
  1. package/dist/Track/core/auth.d.ts +16 -0
  2. package/dist/Track/core/auth.js +83 -0
  3. package/dist/Track/core/constants.d.ts +14 -0
  4. package/dist/Track/core/constants.js +25 -0
  5. package/dist/Track/core/envelope.d.ts +9 -0
  6. package/dist/Track/core/envelope.js +54 -0
  7. package/dist/Track/core/instance.d.ts +108 -0
  8. package/dist/Track/core/instance.js +365 -0
  9. package/dist/Track/core/lifecycle.d.ts +18 -0
  10. package/dist/Track/core/lifecycle.js +59 -0
  11. package/dist/Track/core/profile.d.ts +5 -0
  12. package/dist/Track/core/profile.js +30 -0
  13. package/dist/Track/core/queue.d.ts +13 -0
  14. package/dist/Track/core/queue.js +36 -0
  15. package/dist/Track/core/replay.d.ts +17 -0
  16. package/dist/Track/core/replay.js +117 -0
  17. package/dist/Track/core/router.d.ts +6 -0
  18. package/dist/Track/core/router.js +15 -0
  19. package/dist/Track/core/system.d.ts +14 -0
  20. package/dist/Track/core/system.js +36 -0
  21. package/dist/Track/core/transport.d.ts +18 -0
  22. package/dist/Track/core/transport.js +151 -0
  23. package/dist/Track/index.d.ts +31 -28
  24. package/dist/Track/index.js +212 -392
  25. package/dist/Utils/common.js +5 -6
  26. package/dist/Utils/route.js +1 -6
  27. package/dist/Utils/url.js +1 -3
  28. package/dist/Utils/wx.js +2 -7
  29. package/dist/interfaces/track.interface.d.ts +14 -4
  30. package/lib/Track/core/auth.d.ts +16 -0
  31. package/lib/Track/core/auth.js +67 -0
  32. package/lib/Track/core/constants.d.ts +14 -0
  33. package/lib/Track/core/constants.js +56 -0
  34. package/lib/Track/core/envelope.d.ts +9 -0
  35. package/lib/Track/core/envelope.js +61 -0
  36. package/lib/Track/core/instance.d.ts +108 -0
  37. package/lib/Track/core/instance.js +257 -0
  38. package/lib/Track/core/lifecycle.d.ts +18 -0
  39. package/lib/Track/core/lifecycle.js +74 -0
  40. package/lib/Track/core/profile.d.ts +5 -0
  41. package/lib/Track/core/profile.js +47 -0
  42. package/lib/Track/core/queue.d.ts +13 -0
  43. package/lib/Track/core/queue.js +49 -0
  44. package/lib/Track/core/replay.d.ts +17 -0
  45. package/lib/Track/core/replay.js +131 -0
  46. package/lib/Track/core/router.d.ts +6 -0
  47. package/lib/Track/core/router.js +39 -0
  48. package/lib/Track/core/system.d.ts +14 -0
  49. package/lib/Track/core/system.js +53 -0
  50. package/lib/Track/core/transport.d.ts +18 -0
  51. package/lib/Track/core/transport.js +115 -0
  52. package/lib/Track/index.d.ts +31 -28
  53. package/lib/Track/index.js +126 -312
  54. package/lib/Utils/common.js +4 -6
  55. package/lib/interfaces/track.interface.d.ts +14 -4
  56. package/package.json +11 -10
@@ -1,8 +1,6 @@
1
- var __create = Object.create;
2
1
  var __defProp = Object.defineProperty;
3
2
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
5
  var __export = (target, all) => {
8
6
  for (var name in all)
@@ -16,330 +14,146 @@ var __copyProps = (to, from, except, desc) => {
16
14
  }
17
15
  return to;
18
16
  };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
17
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
18
 
29
19
  // src/Track/index.ts
30
20
  var Track_exports = {};
31
21
  __export(Track_exports, {
22
+ createTracker: () => createTracker,
32
23
  default: () => Track_default
33
24
  });
34
25
  module.exports = __toCommonJS(Track_exports);
35
- var import_pako = __toESM(require("pako"));
36
- var import_package = require("../../package.json");
37
- var import_Utils = require("../Utils");
38
- var Track = class {
39
- // 检查必填配置项
40
- static checkConfig(config) {
41
- if (!config) {
42
- throw new Error("请配置Track");
43
- }
44
- if (!config.domain) {
45
- throw new Error("请设置信息采集中心域名");
46
- }
47
- if (!config.appId) {
48
- throw new Error("请设置appId");
49
- }
50
- this.config = config;
51
- }
52
- // 发送埋点数据
53
- static async send() {
54
- const { debug } = this.config;
55
- const data = this.trackQueue.splice(0, this.trackQueue.length);
56
- const compressed = import_pako.default.deflate(JSON.stringify(data));
57
- if (data.length) {
58
- debug && console.debug("[track:debug] push data", data);
59
- navigator.sendBeacon(
60
- `${this.config.domain}/pousheng-guard/api/track`,
61
- compressed
62
- );
63
- }
64
- }
65
- // 挂载自动化任务
66
- static mountAutoTask() {
67
- const { autoReportError } = this.config;
68
- if (autoReportError) {
69
- addEventListener("error", (event) => {
70
- const { message, filename } = event;
71
- const errorInfo = {
72
- message,
73
- fileName: filename
74
- };
75
- this.errorLog(errorInfo);
76
- console.error("[track:error] catch error", event);
77
- });
78
- }
79
- addEventListener("visibilitychange", () => {
80
- if (document.visibilityState === "hidden") {
81
- this.send();
26
+ var import_instance = require("./core/instance");
27
+ function createTracker(config, options) {
28
+ const { lazy } = options || {};
29
+ const ins = new import_instance.TrackerInstance(config);
30
+ if (lazy)
31
+ return ins;
32
+ return (async () => {
33
+ await ins.init();
34
+ return ins;
35
+ })();
36
+ }
37
+ var TrackFacade = class {
38
+ /** 初始化(必须先调用一次)。重复调用直接返回已存在实例 */
39
+ static async init(config) {
40
+ if (this._instance)
41
+ return this._instance;
42
+ if (!this._initPromise) {
43
+ this._initPromise = (async () => {
44
+ const ins = new import_instance.TrackerInstance(config);
45
+ await ins.init();
46
+ this._instance = ins;
47
+ this._queue.forEach(
48
+ ({ method, args }) => ins[method](...args)
49
+ );
50
+ this._queue.length = 0;
51
+ return ins;
52
+ })();
53
+ }
54
+ return this._initPromise;
55
+ }
56
+ /** 是否已就绪 */
57
+ static isReady() {
58
+ return !!this._instance;
59
+ }
60
+ /** 获取内部实例(未初始化时抛错) */
61
+ static getInstance() {
62
+ if (!this._instance)
63
+ throw new Error("Track 未初始化,请先调用 Track.init(config)");
64
+ return this._instance;
65
+ }
66
+ /** 延迟调用帮助:未 init 时先入队 */
67
+ static invoke(method, ...args) {
68
+ if (this._instance) {
69
+ this._instance[method](...args);
70
+ } else if (this._initPromise) {
71
+ this._queue.push({ method, args });
72
+ } else {
73
+ this._queue.push({ method, args });
74
+ if (!this._warned) {
75
+ console.warn(
76
+ "[track] 在 Track.init 前调用了日志方法,已暂存至初始化后回放"
77
+ );
78
+ this._warned = true;
82
79
  }
83
- });
84
- }
85
- // 获取系统信息
86
- static getSystemProfile() {
87
- const IMEI = localStorage.getItem("__IMEI__");
88
- if (!IMEI) {
89
- localStorage.setItem("__IMEI__", (0, import_Utils.generateRandomString)(16));
90
- }
91
- return {
92
- innerHeight,
93
- innerWidth,
94
- href: location.href,
95
- systemTime: /* @__PURE__ */ new Date(),
96
- IMEI: localStorage.getItem("__IMEI__")
97
- };
98
- }
99
- // 获取当前用户信息,返回格式化后的用户信息
100
- static getUserProfile() {
101
- let userProfile = this.userProfile;
102
- if (!(userProfile == null ? void 0 : userProfile.userId)) {
103
- userProfile.userId = "";
104
- }
105
- if (!(userProfile == null ? void 0 : userProfile.userName)) {
106
- userProfile.userName = "";
107
- }
108
- return userProfile;
109
- }
110
- // 设置当前用户信息
111
- static setUserProfile(userProfile) {
112
- this.userProfile = userProfile;
113
- }
114
- // 初始化权限中心数据
115
- static async initAuthCenterData({
116
- getAuth,
117
- menuBuild,
118
- getDataScopeZonePermissions,
119
- menuNameMap,
120
- routes
121
- }) {
122
- const authCenterApi = [];
123
- if (getAuth) {
124
- authCenterApi.push(getAuth);
125
- }
126
- if (menuBuild) {
127
- authCenterApi.push(menuBuild);
128
- }
129
- if (getDataScopeZonePermissions) {
130
- authCenterApi.push(getDataScopeZonePermissions);
131
- }
132
- const [authInfo = {}, menuData = [], dataScopeZonePermissions] = await Promise.all(
133
- authCenterApi.map((v) => {
134
- if (v) {
135
- return v();
136
- } else {
137
- return Promise.resolve();
138
- }
139
- })
140
- );
141
- const { user = {}, roles = [] } = authInfo || {};
142
- const { roles: dataScopeRoles, ...restUser } = user;
143
- const isAdmin = roles.includes("admin");
144
- const accessPage = [];
145
- if (routes) {
146
- const routesMap = (0, import_Utils.getRoutesMap)(routes, menuNameMap);
147
- routesMap.forEach((value) => {
148
- const { access } = value;
149
- if (access.length === 0) {
150
- return;
151
- }
152
- if (isAdmin) {
153
- accessPage.push(...access);
154
- return;
155
- }
156
- access.forEach((key) => {
157
- if (roles.includes(key)) {
158
- accessPage.push(key);
159
- }
160
- });
161
- });
162
- this.routesMap = routesMap;
163
- }
164
- this.authMap = (0, import_Utils.getAuthMapByAuthCenter)(menuData);
165
- const authCenterUserProfile = {
166
- ...restUser,
167
- dataScopeRoles,
168
- roles,
169
- accessPage
170
- };
171
- if (dataScopeZonePermissions) {
172
- Object.assign(authCenterUserProfile, { dataScopeZonePermissions });
173
80
  }
174
- this.authCenterUserProfile = authCenterUserProfile;
175
- return authCenterUserProfile;
176
81
  }
177
- // 挂载初始配置
178
- static async init({
179
- userProfile,
180
- menuNameMap,
181
- routes,
182
- getAuth,
183
- menuBuild,
184
- getDataScopeZonePermissions,
185
- ...restConfig
186
- }) {
187
- var _a, _b, _c;
188
- this.checkConfig(restConfig);
189
- this.config = restConfig;
190
- await this.initAuthCenterData({
191
- getAuth,
192
- menuBuild,
193
- getDataScopeZonePermissions,
194
- menuNameMap,
195
- routes
196
- });
197
- const currentUserProfile = {};
198
- if (this.authCenterUserProfile.userName) {
199
- Object.assign(currentUserProfile, {
200
- userId: this.authCenterUserProfile.userName,
201
- userName: this.authCenterUserProfile.nickName,
202
- orgCode: this.authCenterUserProfile.orgCode,
203
- orgTitle: this.authCenterUserProfile.orgTitle,
204
- dataScopeRoles: (_a = this.authCenterUserProfile.dataScopeRoles) == null ? void 0 : _a.map((role) => role.name).join(",")
205
- });
206
- }
207
- if (this.authCenterUserProfile.dataScopeZonePermissions && ((_c = (_b = this.authCenterUserProfile.dataScopeZonePermissions) == null ? void 0 : _b.list) == null ? void 0 : _c.length) > 0) {
208
- Object.assign(currentUserProfile, {
209
- dataScopeZonePermissions: this.authCenterUserProfile.dataScopeZonePermissions.list.map((item) => item.list.map((zone) => zone.zoneId).join(",")).join(",")
210
- });
211
- }
212
- if (userProfile) {
213
- Object.assign(currentUserProfile, userProfile);
214
- }
215
- this.setUserProfile(currentUserProfile);
216
- this.mountAutoTask();
217
- this.registerAppInfo();
218
- return this.authCenterUserProfile;
219
- }
220
- // 注册更新应用信息
221
- static registerAppInfo() {
222
- const { appId } = this.config;
223
- navigator.sendBeacon(
224
- `${this.config.domain}/pousheng-guard/api/apps/version/update`,
225
- import_pako.default.deflate(
226
- JSON.stringify({
227
- appId,
228
- version: import_package.version
229
- })
230
- )
231
- );
232
- }
233
- // 推送埋点信息进入队列
234
- static pushQueue({
235
- type,
236
- log
237
- }) {
238
- const config = this.config;
239
- this.checkConfig(config);
240
- const reqData = {
241
- ...this.getSystemProfile(),
242
- ...this.getUserProfile(),
243
- type,
244
- appId: config.appId,
245
- log: JSON.stringify(log)
246
- };
247
- this.trackQueue.push(reqData);
248
- if (this.trackQueue.length > 4) {
249
- this.send();
250
- }
251
- }
252
- // 获取格式化base后的路径
253
- static getFormatBasePath() {
254
- const { base = "/" } = this.config;
255
- const { pathname } = location;
256
- return pathname.replace(base, "/");
257
- }
258
- // 获取模块名称
259
- static getPageModuleName() {
260
- const routeInfo = this.routesMap.get(this.getFormatBasePath());
261
- return (routeInfo == null ? void 0 : routeInfo.module) || [];
262
- }
263
- // 推送错误日志
264
- static errorLog(errorLog) {
265
- this.pushQueue({
266
- log: errorLog,
267
- type: "error"
268
- });
269
- }
270
- // 推送用户触发日志
271
- static eventLog(eventLog) {
272
- const copyEventLog = {
273
- module: "",
274
- content: ""
275
- };
276
- if (typeof eventLog === "string") {
277
- const actionLog = this.authMap.get(eventLog);
278
- if (actionLog) {
279
- copyEventLog.content = "触发: " + actionLog;
280
- } else {
281
- copyEventLog.content = eventLog;
82
+ /**
83
+ * 发送事件日志(通用事件)
84
+ * - 若未初始化:自动排队等待 init 完成后回放
85
+ */
86
+ static eventLog(...args) {
87
+ this.invoke("eventLog", ...args);
88
+ }
89
+ /**
90
+ * 发送访问/页面曝光日志
91
+ * - 用于记录页面 / 场景进入等行为
92
+ */
93
+ static visitLog(...args) {
94
+ this.invoke("visitLog", ...args);
95
+ }
96
+ /**
97
+ * 发送错误日志
98
+ * - 适用于运行时异常、资源加载失败、接口异常包装等
99
+ */
100
+ static errorLog(...args) {
101
+ this.invoke("errorLog", ...args);
102
+ }
103
+ /**
104
+ * 发送接口调用相关日志
105
+ * - 记录接口耗时 / 结果状态
106
+ */
107
+ static apiLog(...args) {
108
+ this.invoke("apiLog", ...args);
109
+ }
110
+ /**
111
+ * 强制立即 flush 已缓冲的日志(若实例策略存在缓冲)
112
+ */
113
+ static flush() {
114
+ if (!this._instance)
115
+ return;
116
+ this._instance.flush();
117
+ }
118
+ /**
119
+ * 销毁当前单例实例
120
+ * - 停止上报 / 释放资源
121
+ * - 再次使用需重新 init
122
+ */
123
+ static destroy() {
124
+ if (!this._instance)
125
+ return;
126
+ this._instance.destroy();
127
+ this._instance = null;
128
+ this._initPromise = null;
129
+ }
130
+ /**
131
+ * 设置用户画像 / 用户基础属性
132
+ * - 若在 init 前调用:会延迟到实例 ready 后再真正执行
133
+ */
134
+ static setUserProfile(profile) {
135
+ if (!this._instance) {
136
+ this._queue.push({ method: "eventLog", args: [] });
137
+ const prevInit = this._initPromise;
138
+ if (prevInit) {
139
+ prevInit.then((ins) => ins.setUserProfile(profile));
282
140
  }
283
- } else {
284
- Object.assign(copyEventLog, eventLog);
285
- }
286
- if (!copyEventLog.module) {
287
- const routeNames = this.getPageModuleName();
288
- copyEventLog.module = (routeNames == null ? void 0 : routeNames.join("-")) || "-";
289
- }
290
- this.pushQueue({
291
- log: copyEventLog,
292
- type: "event"
293
- });
294
- }
295
- // 推送页面访问日志
296
- static visitLog(visitLog) {
297
- const routeInfo = this.routesMap.get(this.getFormatBasePath());
298
- if (routeInfo == null ? void 0 : routeInfo.isRedirect) {
299
141
  return;
300
142
  }
301
- if (visitLog === void 0) {
302
- visitLog = { module: "", content: "" };
303
- const routeNames = this.getPageModuleName();
304
- Object.assign(visitLog, {
305
- module: routeNames.join("-"),
306
- content: `访问页面: ${[...routeNames].pop()}`
307
- });
308
- }
309
- this.pushQueue({
310
- log: visitLog,
311
- type: "visit"
312
- });
143
+ this._instance.setUserProfile(profile);
313
144
  }
314
- // 推送接口访问日志
315
- static apiLog(apiLog) {
316
- const config = this.config;
317
- navigator.sendBeacon(
318
- `${this.config.domain}/pousheng-guard/api/track`,
319
- import_pako.default.deflate(
320
- JSON.stringify([
321
- {
322
- appId: config.appId,
323
- log: apiLog,
324
- type: "api",
325
- ...this.getSystemProfile(),
326
- ...this.getUserProfile()
327
- }
328
- ])
329
- )
330
- );
145
+ /** 获取当前配置(未初始化时返回 undefined) */
146
+ static getConfig() {
147
+ var _a;
148
+ return (_a = this._instance) == null ? void 0 : _a.getConfig();
331
149
  }
332
150
  };
333
- // 配置信息
334
- Track.config = {};
335
- // 需要传入到后端的用户信息
336
- Track.userProfile = {};
337
- // 权限中心用户信息
338
- Track.authCenterUserProfile = {};
339
- // 路径信息映射
340
- Track.routesMap = /* @__PURE__ */ new Map();
341
- // 权限信息映射
342
- Track.authMap = /* @__PURE__ */ new Map();
343
- // 埋点队列
344
- Track.trackQueue = [];
345
- var Track_default = Track;
151
+ TrackFacade._instance = null;
152
+ TrackFacade._initPromise = null;
153
+ TrackFacade._queue = [];
154
+ TrackFacade._warned = false;
155
+ var Track_default = TrackFacade;
156
+ // Annotate the CommonJS export names for ESM import in node:
157
+ 0 && (module.exports = {
158
+ createTracker
159
+ });
@@ -49,13 +49,11 @@ function checkChromeVersion(minVersion) {
49
49
  return false;
50
50
  }
51
51
  function generateRandomString(length) {
52
- let result = "";
53
52
  const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
54
- const charactersLength = characters.length;
55
- for (let i = 0; i < length; i++) {
56
- result += characters.charAt(Math.floor(Math.random() * charactersLength));
57
- }
58
- return result;
53
+ return Array.from(
54
+ { length },
55
+ () => characters.charAt(Math.floor(Math.random() * characters.length))
56
+ ).join("");
59
57
  }
60
58
  // Annotate the CommonJS export names for ESM import in node:
61
59
  0 && (module.exports = {
@@ -21,8 +21,6 @@ export type MenuNameMapType = {
21
21
  };
22
22
  export interface TrackConfig {
23
23
  appId: string;
24
- debug?: boolean;
25
- autoReportError?: boolean;
26
24
  userProfile?: UserProfile;
27
25
  base?: string;
28
26
  getAuth?: () => Promise<any>;
@@ -34,6 +32,7 @@ export interface TrackConfig {
34
32
  zoneName: string;
35
33
  }[]>;
36
34
  domain: string;
35
+ enableReplay?: boolean;
37
36
  }
38
37
  export declare enum TrackTypeEnum {
39
38
  error = "\u9519\u8BEF\u4FE1\u606F",
@@ -86,8 +85,7 @@ export interface SystemProfile {
86
85
  }
87
86
  export interface CustomizeProfile {
88
87
  content: string;
89
- module?: string;
90
- [key: string]: any;
88
+ module: string;
91
89
  }
92
90
  export interface ErrorProfile {
93
91
  fileName: string;
@@ -116,3 +114,15 @@ export type AuthDataType = {
116
114
  title: string;
117
115
  };
118
116
  };
117
+ export interface TrackEventEnvelope extends SystemProfile, UserProfile, CustomizeProfile {
118
+ appId: string;
119
+ type: TrackType;
120
+ /**
121
+ * V2.0.0 版本后为非必填字段,如需传入请使用JSON.stringify格式化为字符串
122
+ */
123
+ log?: string;
124
+ /**
125
+ * V2.0.0 版本后为非必填字段,错误类型时携带回放片段
126
+ */
127
+ replay?: string;
128
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yysports/tools",
3
- "version": "1.1.0",
3
+ "version": "2.0.0",
4
4
  "description": "常用工具函数库",
5
5
  "homepage": "https://git.pousheng.com/sport-service-department/pousheng-guard/yysports_tools#readme",
6
6
  "bugs": {
@@ -60,29 +60,30 @@
60
60
  ]
61
61
  },
62
62
  "dependencies": {
63
- "image-conversion": "^2.1.1",
64
- "pako": "^2.1.0"
63
+ "@babel/runtime": "^7.28.3",
64
+ "@rrweb/record": "2.0.0-alpha.18",
65
+ "@rrweb/rrweb-plugin-console-record": "2.0.0-alpha.18",
66
+ "image-conversion": "^2.1.1"
65
67
  },
66
68
  "devDependencies": {
67
69
  "@ant-design/pro-components": "^2.8.10",
68
70
  "@commitlint/cli": "^19.8.1",
69
71
  "@commitlint/config-conventional": "^19.8.1",
70
- "@types/pako": "^2.0.3",
71
72
  "@types/react": "^18.3.23",
72
73
  "@types/react-dom": "^18.3.7",
73
- "@umijs/lint": "^4.4.11",
74
- "antd": "^5.26.6",
74
+ "@umijs/lint": "^4.4.12",
75
+ "antd": "^5.27.0",
75
76
  "dumi": "^2.4.21",
76
- "eslint": "^9.31.0",
77
- "father": "^4.6.1",
77
+ "eslint": "^9.33.0",
78
+ "father": "^4.6.2",
78
79
  "husky": "^9.1.7",
79
- "lint-staged": "^16.1.2",
80
+ "lint-staged": "^16.1.5",
80
81
  "prettier": "^3.6.2",
81
82
  "prettier-plugin-organize-imports": "^4.2.0",
82
83
  "prettier-plugin-packagejson": "^2.5.19",
83
84
  "react": "^18.3.1",
84
85
  "react-dom": "^18.3.1",
85
- "stylelint": "^16.22.0"
86
+ "stylelint": "^16.23.1"
86
87
  },
87
88
  "publishConfig": {
88
89
  "access": "public"