@wutiange/log-listener-plugin 1.2.0 → 1.3.0-alpha.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (83) hide show
  1. package/dist/console.js +14 -15
  2. package/dist/console.js.map +1 -1
  3. package/dist/fetch.js +28 -28
  4. package/dist/fetch.js.map +1 -1
  5. package/dist/index.d.ts +2 -23
  6. package/dist/index.js +2 -117
  7. package/dist/index.js.map +1 -1
  8. package/dist/packages/network-logger/Logger.d.ts +28 -0
  9. package/dist/packages/network-logger/Logger.js +192 -0
  10. package/dist/packages/network-logger/Logger.js.map +1 -0
  11. package/dist/packages/network-logger/NetworkRequestInfo.d.ts +36 -0
  12. package/dist/packages/network-logger/NetworkRequestInfo.js +129 -0
  13. package/dist/packages/network-logger/NetworkRequestInfo.js.map +1 -0
  14. package/dist/packages/network-logger/constant.d.ts +2 -0
  15. package/dist/packages/network-logger/constant.js +6 -0
  16. package/dist/packages/network-logger/constant.js.map +1 -0
  17. package/dist/packages/network-logger/types.d.ts +14 -0
  18. package/dist/packages/network-logger/types.js +3 -0
  19. package/dist/packages/network-logger/types.js.map +1 -0
  20. package/dist/packages/network-logger/utils/debounce.d.ts +2 -0
  21. package/dist/packages/network-logger/utils/debounce.js +20 -0
  22. package/dist/packages/network-logger/utils/debounce.js.map +1 -0
  23. package/dist/packages/network-logger/utils/extractHost.d.ts +2 -0
  24. package/dist/packages/network-logger/utils/extractHost.js +9 -0
  25. package/dist/packages/network-logger/utils/extractHost.js.map +1 -0
  26. package/dist/packages/network-logger/utils/fromEntries.d.ts +2 -0
  27. package/dist/packages/network-logger/utils/fromEntries.js +8 -0
  28. package/dist/packages/network-logger/utils/fromEntries.js.map +1 -0
  29. package/dist/packages/network-logger/utils/logger.d.ts +1 -0
  30. package/dist/packages/network-logger/utils/logger.js +6 -0
  31. package/dist/packages/network-logger/utils/logger.js.map +1 -0
  32. package/dist/src/CompatibilityManager.d.ts +27 -0
  33. package/dist/src/CompatibilityManager.js +74 -0
  34. package/dist/src/CompatibilityManager.js.map +1 -0
  35. package/dist/src/__tests__/console.test.d.ts +1 -0
  36. package/dist/{__tests__ → src/__tests__}/console.test.js +2 -2
  37. package/dist/src/__tests__/console.test.js.map +1 -0
  38. package/dist/src/common.js.map +1 -0
  39. package/dist/src/console.d.ts +1 -0
  40. package/dist/src/console.js +20 -0
  41. package/dist/src/console.js.map +1 -0
  42. package/dist/src/fetch.d.ts +1 -0
  43. package/dist/src/fetch.js +48 -0
  44. package/dist/src/fetch.js.map +1 -0
  45. package/dist/src/index.d.ts +2 -0
  46. package/dist/src/index.js +8 -0
  47. package/dist/src/index.js.map +1 -0
  48. package/dist/src/logPlugin.d.ts +32 -0
  49. package/dist/src/logPlugin.js +187 -0
  50. package/dist/src/logPlugin.js.map +1 -0
  51. package/dist/{server.d.ts → src/server.d.ts} +1 -1
  52. package/dist/{server.js → src/server.js} +14 -8
  53. package/dist/src/server.js.map +1 -0
  54. package/dist/src/utils.d.ts +3 -0
  55. package/dist/src/utils.js +38 -0
  56. package/dist/src/utils.js.map +1 -0
  57. package/package.json +13 -5
  58. package/packages/network-logger/Logger.ts +274 -0
  59. package/packages/network-logger/NetworkRequestInfo.ts +133 -0
  60. package/packages/network-logger/constant.ts +3 -0
  61. package/packages/network-logger/types.ts +36 -0
  62. package/packages/network-logger/utils/debounce.ts +21 -0
  63. package/packages/network-logger/utils/extractHost.ts +7 -0
  64. package/packages/network-logger/utils/fromEntries.ts +7 -0
  65. package/packages/network-logger/utils/logger.ts +2 -0
  66. package/src/CompatibilityManager.ts +64 -0
  67. package/src/__tests__/console.test.ts +2 -2
  68. package/src/common.ts +2 -3
  69. package/src/logPlugin.ts +229 -0
  70. package/src/server.ts +28 -23
  71. package/src/utils.ts +38 -0
  72. package/dist/__tests__/console.test.d.ts +0 -1
  73. package/dist/__tests__/console.test.js.map +0 -1
  74. package/dist/common.js.map +0 -1
  75. package/dist/server.js.map +0 -1
  76. package/dist/utils.d.ts +0 -1
  77. package/dist/utils.js +0 -14
  78. package/dist/utils.js.map +0 -1
  79. package/src/console.ts +0 -19
  80. package/src/fetch.ts +0 -35
  81. package/src/index.ts +0 -131
  82. /package/dist/{common.d.ts → src/common.d.ts} +0 -0
  83. /package/dist/{common.js → src/common.js} +0 -0
@@ -0,0 +1,187 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.LogPlugin = void 0;
16
+ const server_1 = __importDefault(require("./server"));
17
+ const Logger_1 = __importDefault(require("../packages/network-logger/Logger"));
18
+ const utils_1 = require("./utils");
19
+ const CompatibilityManager_1 = __importDefault(require("./CompatibilityManager"));
20
+ class LogPlugin {
21
+ constructor() {
22
+ this.server = null;
23
+ this.baseData = {};
24
+ this.timeout = null;
25
+ this.networkLogger = new Logger_1.default();
26
+ this.host = '';
27
+ this.isAuto = false;
28
+ }
29
+ auto() {
30
+ if (this.host) {
31
+ this.startRecordNetwork();
32
+ this.startRecordLog();
33
+ }
34
+ this.isAuto = true;
35
+ }
36
+ unAuto() {
37
+ this.stopRecordLog();
38
+ this.networkLogger.disableXHRInterception();
39
+ this.isAuto = false;
40
+ }
41
+ startRecordLog() {
42
+ const common = require('./common');
43
+ console.log = (...data) => {
44
+ this.log(...data);
45
+ common.log(...data);
46
+ };
47
+ console.warn = (...data) => {
48
+ this.warn(...data);
49
+ common.warn(...data);
50
+ };
51
+ console.error = (...data) => {
52
+ this.error(...data);
53
+ common.error(...data);
54
+ };
55
+ }
56
+ stopRecordLog() {
57
+ const common = require('./common');
58
+ console.log = common.log;
59
+ console.warn = common.warn;
60
+ console.error = common.error;
61
+ }
62
+ startRecordNetwork() {
63
+ this.networkLogger.setCallback((data) => __awaiter(this, void 0, void 0, function* () {
64
+ const sendData = yield CompatibilityManager_1.default.interceptionToNetwork(data);
65
+ sendData.forEach(e => {
66
+ var _a;
67
+ (_a = this.server) === null || _a === void 0 ? void 0 : _a.network(Object.assign(Object.assign({}, this.baseData), e));
68
+ });
69
+ }));
70
+ this.networkLogger.enableXHRInterception({
71
+ ignoredHosts: [(0, utils_1.extractDomain)(this.host)],
72
+ });
73
+ }
74
+ setBaseUrl(url) {
75
+ if (!(url === null || url === void 0 ? void 0 : url.trim())) {
76
+ this.networkLogger.disableXHRInterception();
77
+ this.stopRecordLog();
78
+ return;
79
+ }
80
+ this.host = url.includes("http") ? url : `http://${url}`;
81
+ if (this.server) {
82
+ this.server.updateUrl(url);
83
+ }
84
+ else {
85
+ this.server = new server_1.default(url);
86
+ }
87
+ if (this.isAuto) {
88
+ this.startRecordNetwork();
89
+ this.startRecordLog();
90
+ }
91
+ }
92
+ setTimeout(timeout) {
93
+ var _a;
94
+ if (typeof timeout === 'number') {
95
+ this.timeout = timeout;
96
+ (_a = this.server) === null || _a === void 0 ? void 0 : _a.updateTimeout(this.timeout);
97
+ }
98
+ }
99
+ getTimeout() {
100
+ if (typeof this.timeout === 'number') {
101
+ return this.timeout;
102
+ }
103
+ return null;
104
+ }
105
+ setBaseData(data = {}) {
106
+ this.baseData = data;
107
+ }
108
+ _log(level, tag, ...data) {
109
+ var _a;
110
+ const sendData = Object.assign(Object.assign({}, this.baseData), { message: data, tag, level: level !== null && level !== void 0 ? level : 'log', createTime: Date.now() });
111
+ (_a = this.server) === null || _a === void 0 ? void 0 : _a.log(sendData);
112
+ }
113
+ tag(tag, ...data) {
114
+ this._log('log', tag, ...data);
115
+ }
116
+ log(...data) {
117
+ this._log('log', 'default', ...data);
118
+ }
119
+ warn(...data) {
120
+ this._log('warn', 'default', ...data);
121
+ }
122
+ error(...data) {
123
+ this._log('error', 'default', ...data);
124
+ }
125
+ uniqueReq(uniqueId, input, init) {
126
+ var _a, _b, _c;
127
+ return __awaiter(this, void 0, void 0, function* () {
128
+ let url = null;
129
+ let method = (_a = init === null || init === void 0 ? void 0 : init.method) !== null && _a !== void 0 ? _a : 'get';
130
+ let headers = init === null || init === void 0 ? void 0 : init.headers;
131
+ let body = init === null || init === void 0 ? void 0 : init.body;
132
+ if (input instanceof Request) {
133
+ url = input.url;
134
+ method = (_b = input.method) !== null && _b !== void 0 ? _b : 'get';
135
+ headers = input.headers.map;
136
+ body = input.body;
137
+ }
138
+ else if (input instanceof URL) {
139
+ url = input.href;
140
+ }
141
+ else {
142
+ url = input;
143
+ }
144
+ return (_c = this.server) === null || _c === void 0 ? void 0 : _c.network(Object.assign(Object.assign({}, this.baseData), { url, id: uniqueId, method,
145
+ headers,
146
+ body, createTime: Date.now() }));
147
+ });
148
+ }
149
+ _res(uniqueId, id, response) {
150
+ var _a;
151
+ return __awaiter(this, void 0, void 0, function* () {
152
+ const body = yield (response === null || response === void 0 ? void 0 : response.text());
153
+ return (_a = this.server) === null || _a === void 0 ? void 0 : _a.network(Object.assign(Object.assign({}, this.baseData), { headers: (response === null || response === void 0 ? void 0 : response.headers).map, body, requestId: uniqueId !== null && uniqueId !== void 0 ? uniqueId : Number(id), statusCode: response === null || response === void 0 ? void 0 : response.status, endTime: Date.now() }));
154
+ });
155
+ }
156
+ resTimeout(uniqueId) {
157
+ var _a;
158
+ return __awaiter(this, void 0, void 0, function* () {
159
+ return (_a = this.server) === null || _a === void 0 ? void 0 : _a.network(Object.assign(Object.assign({}, this.baseData), { isTimeout: true, requestId: uniqueId }));
160
+ });
161
+ }
162
+ resResponseError(uniqueId) {
163
+ var _a;
164
+ return __awaiter(this, void 0, void 0, function* () {
165
+ return (_a = this.server) === null || _a === void 0 ? void 0 : _a.network(Object.assign(Object.assign({}, this.baseData), { isResponseError: true, requestId: uniqueId }));
166
+ });
167
+ }
168
+ uniqueRes(uniqueId, response) {
169
+ return __awaiter(this, void 0, void 0, function* () {
170
+ return this._res(uniqueId, undefined, response);
171
+ });
172
+ }
173
+ req(input, init) {
174
+ return __awaiter(this, void 0, void 0, function* () {
175
+ return this.uniqueReq(undefined, input, init);
176
+ });
177
+ }
178
+ res(id, response) {
179
+ return __awaiter(this, void 0, void 0, function* () {
180
+ return this._res(undefined, id, response);
181
+ });
182
+ }
183
+ }
184
+ exports.LogPlugin = LogPlugin;
185
+ const logPlugin = new LogPlugin();
186
+ exports.default = logPlugin;
187
+ //# sourceMappingURL=logPlugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logPlugin.js","sourceRoot":"","sources":["../../src/logPlugin.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,sDAA8B;AAC9B,+EAAuD;AAEvD,mCAAwC;AACxC,kFAA0D;AAE1D,MAAM,SAAS;IAAf;QACU,WAAM,GAAkB,IAAI,CAAC;QAC7B,aAAQ,GAAwB,EAAE,CAAC;QACnC,YAAO,GAAkB,IAAI,CAAC;QAC9B,kBAAa,GAAG,IAAI,gBAAM,EAAE,CAAC;QAC7B,SAAI,GAAG,EAAE,CAAC;QACV,WAAM,GAAG,KAAK,CAAA;IAqNxB,CAAC;IAnNC,IAAI;QACF,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACd,IAAI,CAAC,kBAAkB,EAAE,CAAC;YAC1B,IAAI,CAAC,cAAc,EAAE,CAAC;QACxB,CAAC;QACD,IAAI,CAAC,MAAM,GAAG,IAAI,CAAA;IACpB,CAAC;IAED,MAAM;QACJ,IAAI,CAAC,aAAa,EAAE,CAAA;QACpB,IAAI,CAAC,aAAa,CAAC,sBAAsB,EAAE,CAAA;QAC3C,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,cA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E,OAAO,iCACtB,IAAI,CAAC,QAAQ,KAChB,SAAS,EAAE,IAAI,EACf,SAAS,EAAE,QAAQ,IACnB,CAAC;;KACJ;IAKK,gBAAgB,CAAC,QAAgB;;;YACrC,OAAO,MAAA,IAAI,CAAC,MAAM,0CAAE,OAAO,iCACtB,IAAI,CAAC,QAAQ,KAChB,eAAe,EAAE,IAAI,EACrB,SAAS,EAAE,QAAQ,IACnB,CAAC;;KACJ;IAKK,SAAS,CAAC,QAAgB,EAAE,QAAmB;;YACnD,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;QAClD,CAAC;KAAA;IAKK,GAAG,CAAC,KAAwB,EAAE,IAAkB;;YACpD,OAAO,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;QAChD,CAAC;KAAA;IAKK,GAAG,CAAC,EAAU,EAAE,QAAmB;;YACvC,OAAO,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,EAAE,QAAQ,CAAC,CAAC;QAC5C,CAAC;KAAA;CACF;AAEQ,8BAAS;AADlB,MAAM,SAAS,GAAG,IAAI,SAAS,EAAE,CAAC;AAElC,kBAAe,SAAS,CAAC"}
@@ -1,9 +1,9 @@
1
1
  declare class Server {
2
2
  private baseUrl;
3
- private port;
4
3
  private timeout;
5
4
  constructor(url: string, timeout?: number);
6
5
  updateTimeout(timeout?: number): void;
6
+ private getPort;
7
7
  private send;
8
8
  updateUrl(url: string): void;
9
9
  log(data: Record<string, any>): Promise<string>;
@@ -10,37 +10,43 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  const utils_1 = require("./utils");
13
+ const DEFAULT_PORT = 27751;
13
14
  class Server {
14
15
  constructor(url, timeout = 3000) {
15
16
  this.baseUrl = '';
16
- this.port = 27751;
17
17
  this.updateUrl(url);
18
18
  this.timeout = timeout;
19
19
  }
20
20
  updateTimeout(timeout = 3000) {
21
21
  this.timeout = timeout;
22
22
  }
23
+ getPort() {
24
+ if ((0, utils_1.hasPort)(this.baseUrl)) {
25
+ return '';
26
+ }
27
+ return DEFAULT_PORT;
28
+ }
23
29
  send(path, data) {
24
30
  return __awaiter(this, void 0, void 0, function* () {
25
31
  try {
26
32
  if (!this.baseUrl) {
27
33
  return null;
28
34
  }
29
- const common = yield import('./common.js');
35
+ const common = require('./common');
30
36
  const result = yield Promise.race([
31
- common.tempFetch(`${this.baseUrl}:${this.port}/${path}`, {
37
+ common.tempFetch(`${this.baseUrl}:${this.getPort()}/${path}`, {
32
38
  method: 'POST',
33
39
  headers: {
34
- 'Content-Type': 'application/json;charset=utf-8'
40
+ 'Content-Type': 'application/json;charset=utf-8',
35
41
  },
36
42
  body: JSON.stringify(data, (_, val) => {
37
43
  if (val instanceof Error) {
38
44
  return val.toString();
39
45
  }
40
46
  return val;
41
- })
47
+ }),
42
48
  }),
43
- (0, utils_1.sleep)(this.timeout, true)
49
+ (0, utils_1.sleep)(this.timeout, true),
44
50
  ]);
45
51
  if (result instanceof Response) {
46
52
  return result.text();
@@ -57,12 +63,12 @@ class Server {
57
63
  }
58
64
  log(data) {
59
65
  return __awaiter(this, void 0, void 0, function* () {
60
- return this.send("log", data);
66
+ return this.send('log', data);
61
67
  });
62
68
  }
63
69
  network(data) {
64
70
  return __awaiter(this, void 0, void 0, function* () {
65
- return this.send("network", data);
71
+ return this.send('network', data);
66
72
  });
67
73
  }
68
74
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,mCAAuC;AACvC,MAAM,YAAY,GAAG,KAAK,CAAA;AAC1B,MAAM,MAAM;IAIV,YAAY,GAAW,EAAE,UAAkB,IAAI;QAHvC,YAAO,GAAG,EAAE,CAAC;QAInB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CA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,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;KAAA;IAED,SAAS,CAAC,GAAW;QACnB,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC;IACrB,CAAC;IAEK,GAAG,CAAC,IAAyB;;YACjC,OAAO,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QAChC,CAAC;KAAA;IAEK,OAAO,CAAC,IAAyB;;YACrC,OAAO,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QACpC,CAAC;KAAA;CACF;AAED,kBAAe,MAAM,CAAC"}
@@ -0,0 +1,3 @@
1
+ export declare function sleep(ms: number, isReject?: boolean): Promise<unknown>;
2
+ export declare function extractDomain(url: string): string;
3
+ export declare function hasPort(url: string): boolean;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hasPort = exports.extractDomain = exports.sleep = void 0;
4
+ function sleep(ms, isReject = false) {
5
+ return new Promise((resolve, reject) => {
6
+ setTimeout(isReject ? () => reject({
7
+ code: 11001,
8
+ key: '@wutiange/log-listener-plugin%%timeout',
9
+ msg: 'Timeout'
10
+ }) : resolve, ms);
11
+ });
12
+ }
13
+ exports.sleep = sleep;
14
+ function extractDomain(url) {
15
+ if (!url || typeof url !== 'string') {
16
+ return url;
17
+ }
18
+ const match = url.match(/^(https?:\/\/)?([^/:]+)/i);
19
+ if (!match) {
20
+ return url;
21
+ }
22
+ return match[2];
23
+ }
24
+ exports.extractDomain = extractDomain;
25
+ function hasPort(url) {
26
+ if (!url || typeof url !== 'string') {
27
+ return false;
28
+ }
29
+ try {
30
+ const parsedUrl = new URL(url);
31
+ return parsedUrl.port !== '';
32
+ }
33
+ catch (error) {
34
+ return false;
35
+ }
36
+ }
37
+ exports.hasPort = hasPort;
38
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;;AAAA,SAAgB,KAAK,CAAC,EAAU,EAAE,WAAoB,KAAK;IACzD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC;YACjC,IAAI,EAAE,KAAK;YACX,GAAG,EAAE,wCAAwC;YAC7C,GAAG,EAAE,SAAS;SACf,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAA;IACnB,CAAC,CAAC,CAAA;AACJ,CAAC;AARD,sBAQC;AAED,SAAgB,aAAa,CAAC,GAAW;IAEvC,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QACpC,OAAO,GAAG,CAAC;IACb,CAAC;IAGD,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;IAGpD,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,GAAG,CAAC;IACb,CAAC;IAGD,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC;AAhBD,sCAgBC;AAGD,SAAgB,OAAO,CAAC,GAAW;IAEjC,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QACpC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,CAAC;QAEH,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;QAI/B,OAAO,SAAS,CAAC,IAAI,KAAK,EAAE,CAAC;IAC/B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAEf,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAjBD,0BAiBC"}
package/package.json CHANGED
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "name": "@wutiange/log-listener-plugin",
3
- "version": "1.2.0",
3
+ "version": "1.3.0-alpha.0",
4
4
  "description": "这是log-record的插件,如果需要使用这个日志监听,那么就需要把这个插件安装到项目中",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
- "repository": "https://github.com/wutiange/log-listener-plugin.git",
5
+ "main": "dist/src/index.js",
6
+ "types": "dist/src/index.d.ts",
7
+ "source": "src/index.ts",
8
+ "repository": {
9
+ "url": "https://github.com/wutiange/log-listener-plugin.git"
10
+ },
8
11
  "author": "wutiange <wutiange20@qq,com>",
9
12
  "license": "MIT",
10
13
  "private": false,
@@ -27,11 +30,16 @@
27
30
  "jest": "^29.7.0",
28
31
  "ts-jest": "^29.1.2",
29
32
  "ts-node": "^10.9.2",
30
- "typescript": "^5.3.3"
33
+ "typescript": "^5.3.3",
34
+ "react-native": "0.73.5"
35
+ },
36
+ "peerDependencies": {
37
+ "react-native": "*"
31
38
  },
32
39
  "files": [
33
40
  "src",
34
41
  "package.json",
42
+ "packages",
35
43
  "README.md",
36
44
  "LICENSE",
37
45
  "dist"
@@ -0,0 +1,274 @@
1
+ // @ts-ignore
2
+ import XHRInterceptor from 'react-native/Libraries/Network/XHRInterceptor';
3
+ import NetworkRequestInfo from './NetworkRequestInfo';
4
+ import type {Headers, RequestMethod, StartNetworkLoggingOptions} from './types';
5
+ import {LOGGER_REFRESH_RATE, LOGGER_MAX_REQUESTS} from './constant';
6
+ import extractHost from './utils/extractHost';
7
+ import {warn} from './utils/logger';
8
+ import debounce from './utils/debounce';
9
+
10
+ let nextXHRId = 0;
11
+
12
+ type XHR = {
13
+ _index: number;
14
+ responseHeaders?: Headers;
15
+ };
16
+
17
+
18
+ export default class Logger {
19
+ private requests: NetworkRequestInfo[] = [];
20
+ private xhrIdMap: Map<number, () => number> = new Map();
21
+ private maxRequests: number = LOGGER_MAX_REQUESTS;
22
+ private refreshRate: number = LOGGER_REFRESH_RATE;
23
+ private latestRequestUpdatedAt: number = 0;
24
+ private ignoredHosts: Set<string> | undefined;
25
+ private ignoredUrls: Set<string> | undefined;
26
+ private ignoredPatterns: RegExp[] | undefined;
27
+ public enabled = false;
28
+ public paused = false;
29
+
30
+ callback = (_: NetworkRequestInfo[]): void => null;
31
+
32
+ setCallback = (callback: any) => {
33
+ this.callback = callback;
34
+ };
35
+
36
+ debouncedCallback = debounce(() => {
37
+ if (
38
+ !this.latestRequestUpdatedAt ||
39
+ this.requests.some(r => r.updatedAt > this.latestRequestUpdatedAt)
40
+ ) {
41
+ this.latestRequestUpdatedAt = Date.now();
42
+ // prevent mutation of requests for all subscribers
43
+ this.callback([...this.requests]);
44
+ }
45
+ }, this.refreshRate);
46
+
47
+ private getRequest = (xhrIndex?: number) => {
48
+ if (xhrIndex === undefined) {
49
+ return undefined;
50
+ }
51
+ if (!this.xhrIdMap.has(xhrIndex)) {
52
+ return undefined;
53
+ }
54
+ const index = this.xhrIdMap.get(xhrIndex)!();
55
+ return this.requests[index];
56
+ };
57
+
58
+ private updateRequest = (
59
+ index: number,
60
+ update: Partial<NetworkRequestInfo>,
61
+ ) => {
62
+ const networkInfo = this.getRequest(index);
63
+ if (!networkInfo) {
64
+ return;
65
+ }
66
+ networkInfo.update(update);
67
+ };
68
+
69
+ private openCallback = (method: RequestMethod, url: string, xhr: XHR) => {
70
+ if (this.paused) {
71
+ return;
72
+ }
73
+
74
+ if (this.ignoredHosts) {
75
+ const host = extractHost(url);
76
+ if (host && this.ignoredHosts.has(host)) {
77
+ return;
78
+ }
79
+ }
80
+
81
+ if (this.ignoredUrls && this.ignoredUrls.has(url)) {
82
+ return;
83
+ }
84
+
85
+ if (this.ignoredPatterns) {
86
+ if (
87
+ this.ignoredPatterns.some(pattern => pattern.test(`${method} ${url}`))
88
+ ) {
89
+ return;
90
+ }
91
+ }
92
+
93
+ xhr._index = nextXHRId++;
94
+ this.xhrIdMap.set(xhr._index, () => {
95
+ return this.requests.findIndex(r => r.id === `${xhr._index}`);
96
+ });
97
+
98
+ const newRequest = new NetworkRequestInfo(
99
+ `${xhr._index}`,
100
+ 'XMLHttpRequest',
101
+ method,
102
+ url,
103
+ );
104
+
105
+ if (this.requests.length >= this.maxRequests) {
106
+ this.requests.pop();
107
+ }
108
+
109
+ this.requests.unshift(newRequest);
110
+ };
111
+
112
+ private requestHeadersCallback = (
113
+ header: string,
114
+ value: string,
115
+ xhr: XHR,
116
+ ) => {
117
+ const networkInfo = this.getRequest(xhr._index);
118
+ if (!networkInfo) {
119
+ return;
120
+ }
121
+ networkInfo.requestHeaders[header] = value;
122
+ };
123
+
124
+ private headerReceivedCallback = (
125
+ responseContentType: string,
126
+ responseSize: number,
127
+ responseHeaders: Headers,
128
+ xhr: XHR,
129
+ ) => {
130
+ this.updateRequest(xhr._index, {
131
+ responseContentType,
132
+ responseSize,
133
+ responseHeaders: xhr.responseHeaders,
134
+ });
135
+ };
136
+
137
+ private sendCallback = (data: string, xhr: XHR) => {
138
+ this.updateRequest(xhr._index, {
139
+ startTime: Date.now(),
140
+ dataSent: data,
141
+ });
142
+ this.debouncedCallback();
143
+ };
144
+
145
+ private responseCallback = (
146
+ status: number,
147
+ timeout: number,
148
+ response: string,
149
+ responseURL: string,
150
+ responseType: string,
151
+ xhr: XHR,
152
+ ) => {
153
+ this.updateRequest(xhr._index, {
154
+ endTime: Date.now(),
155
+ status,
156
+ timeout,
157
+ response,
158
+ responseURL,
159
+ responseType,
160
+ });
161
+ this.debouncedCallback();
162
+ };
163
+
164
+ enableXHRInterception = (options?: StartNetworkLoggingOptions) => {
165
+ if (
166
+ this.enabled ||
167
+ (XHRInterceptor.isInterceptorEnabled() && !options?.forceEnable)
168
+ ) {
169
+ if (!this.enabled) {
170
+ warn(
171
+ 'network interceptor has not been enabled as another interceptor is already running (e.g. another debugging program). Use option `forceEnable: true` to override this behaviour.',
172
+ );
173
+ }
174
+ return;
175
+ }
176
+
177
+ if (options?.maxRequests !== undefined) {
178
+ if (typeof options.maxRequests !== 'number' || options.maxRequests < 1) {
179
+ warn(
180
+ 'maxRequests must be a number greater than 0. The logger has not been started.',
181
+ );
182
+ return;
183
+ }
184
+ this.maxRequests = options.maxRequests;
185
+ }
186
+
187
+ if (options?.ignoredHosts) {
188
+ if (
189
+ !Array.isArray(options.ignoredHosts) ||
190
+ typeof options.ignoredHosts[0] !== 'string'
191
+ ) {
192
+ warn(
193
+ 'ignoredHosts must be an array of strings. The logger has not been started.',
194
+ );
195
+ return;
196
+ }
197
+ this.ignoredHosts = new Set(options.ignoredHosts);
198
+ }
199
+
200
+ if (options?.refreshRate) {
201
+ if (typeof options.refreshRate !== 'number' || options.refreshRate < 1) {
202
+ warn(
203
+ 'refreshRate must be a number greater than 0. The logger has not been started.',
204
+ );
205
+ return;
206
+ }
207
+ this.refreshRate = options.refreshRate;
208
+ }
209
+
210
+ if (options?.ignoredPatterns) {
211
+ this.ignoredPatterns = options.ignoredPatterns;
212
+ }
213
+
214
+ if (options?.ignoredUrls) {
215
+ if (
216
+ !Array.isArray(options.ignoredUrls) ||
217
+ typeof options.ignoredUrls[0] !== 'string'
218
+ ) {
219
+ warn(
220
+ 'ignoredUrls must be an array of strings. The logger has not been started.',
221
+ );
222
+ return;
223
+ }
224
+ this.ignoredUrls = new Set(options.ignoredUrls);
225
+ }
226
+
227
+ XHRInterceptor.setOpenCallback(this.openCallback);
228
+ XHRInterceptor.setRequestHeaderCallback(this.requestHeadersCallback);
229
+ XHRInterceptor.setHeaderReceivedCallback(this.headerReceivedCallback);
230
+ XHRInterceptor.setSendCallback(this.sendCallback);
231
+ XHRInterceptor.setResponseCallback(this.responseCallback);
232
+
233
+ XHRInterceptor.enableInterception();
234
+ this.enabled = true;
235
+ };
236
+
237
+ getRequests = () => {
238
+ return this.requests;
239
+ };
240
+
241
+ clearRequests = () => {
242
+ this.requests = [];
243
+ this.latestRequestUpdatedAt = 0;
244
+ this.debouncedCallback();
245
+ };
246
+
247
+ disableXHRInterception = () => {
248
+ if (!this.enabled) {
249
+ return;
250
+ }
251
+
252
+ this.clearRequests();
253
+
254
+ nextXHRId = 0;
255
+ this.enabled = false;
256
+ this.paused = false;
257
+ this.xhrIdMap.clear();
258
+ this.maxRequests = LOGGER_MAX_REQUESTS;
259
+ this.refreshRate = LOGGER_REFRESH_RATE;
260
+ this.ignoredHosts = undefined;
261
+ this.ignoredUrls = undefined;
262
+ this.ignoredPatterns = undefined;
263
+
264
+ const noop = (): void => null;
265
+ // manually reset callbacks even if the XHRInterceptor lib does it for us with 'disableInterception'
266
+ XHRInterceptor.setOpenCallback(noop);
267
+ XHRInterceptor.setRequestHeaderCallback(noop);
268
+ XHRInterceptor.setHeaderReceivedCallback(noop);
269
+ XHRInterceptor.setSendCallback(noop);
270
+ XHRInterceptor.setResponseCallback(noop);
271
+
272
+ XHRInterceptor.disableInterception();
273
+ };
274
+ }