@oxog/react-check 1.2.0 → 1.3.1
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/CHANGELOG.md +129 -0
- package/README.md +177 -62
- package/dist/browser-inject.global.js +13 -13
- package/dist/chain.cjs +8 -531
- package/dist/chain.cjs.map +1 -1
- package/dist/chain.d.cts +2 -2
- package/dist/chain.d.ts +2 -2
- package/dist/chain.js +2 -533
- package/dist/chain.js.map +1 -1
- package/dist/chunk-35I3PLS3.js +751 -0
- package/dist/chunk-35I3PLS3.js.map +1 -0
- package/dist/chunk-7R4KKJTW.cjs +255 -0
- package/dist/chunk-7R4KKJTW.cjs.map +1 -0
- package/dist/chunk-DSXOHC6R.cjs +755 -0
- package/dist/chunk-DSXOHC6R.cjs.map +1 -0
- package/dist/chunk-DWM55ACO.cjs +294 -0
- package/dist/chunk-DWM55ACO.cjs.map +1 -0
- package/dist/chunk-GS7T56RP.cjs +9 -0
- package/dist/chunk-GS7T56RP.cjs.map +1 -0
- package/dist/chunk-LFY7MUHJ.cjs +483 -0
- package/dist/chunk-LFY7MUHJ.cjs.map +1 -0
- package/dist/chunk-NLWGB4IE.cjs +380 -0
- package/dist/chunk-NLWGB4IE.cjs.map +1 -0
- package/dist/chunk-PIXJPQO7.js +481 -0
- package/dist/chunk-PIXJPQO7.js.map +1 -0
- package/dist/chunk-REEPUD73.js +362 -0
- package/dist/chunk-REEPUD73.js.map +1 -0
- package/dist/chunk-RQYHXWUC.js +292 -0
- package/dist/chunk-RQYHXWUC.js.map +1 -0
- package/dist/chunk-WLN7ZVO4.js +253 -0
- package/dist/chunk-WLN7ZVO4.js.map +1 -0
- package/dist/cli.js +1195 -297
- package/dist/cli.js.map +1 -1
- package/dist/detect.cjs +22 -324
- package/dist/detect.cjs.map +1 -1
- package/dist/detect.d.cts +8 -2
- package/dist/detect.d.ts +8 -2
- package/dist/detect.js +1 -324
- package/dist/detect.js.map +1 -1
- package/dist/{event-emitter-CxKUDo9q.d.cts → event-emitter-BVYUPYLd.d.cts} +3 -2
- package/dist/{event-emitter-CxKUDo9q.d.ts → event-emitter-BVYUPYLd.d.ts} +3 -2
- package/dist/fix.cjs +6 -715
- package/dist/fix.cjs.map +1 -1
- package/dist/fix.d.cts +8 -2
- package/dist/fix.d.ts +8 -2
- package/dist/fix.js +2 -719
- package/dist/fix.js.map +1 -1
- package/dist/index.cjs +1400 -3075
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +237 -57
- package/dist/index.d.ts +237 -57
- package/dist/index.js +1222 -2970
- package/dist/index.js.map +1 -1
- package/dist/{scanner-Cc2187fH.d.ts → scanner-BJFA0354.d.ts} +33 -4
- package/dist/{scanner-S7BtVIpW.d.cts → scanner-DZL2rIFv.d.cts} +33 -4
- package/dist/scanner.cjs +8 -1652
- package/dist/scanner.cjs.map +1 -1
- package/dist/scanner.d.cts +3 -3
- package/dist/scanner.d.ts +3 -3
- package/dist/scanner.js +4 -1656
- package/dist/scanner.js.map +1 -1
- package/dist/{types-DuZyBVVV.d.cts → types-BMDemwIs.d.cts} +35 -10
- package/dist/{types-DuZyBVVV.d.ts → types-BMDemwIs.d.ts} +35 -10
- package/package.json +16 -9
package/dist/index.js
CHANGED
|
@@ -1,2352 +1,44 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import { matchComponentPattern, Scanner } from './chunk-35I3PLS3.js';
|
|
2
|
+
export { Scanner, StatsCollector, matchComponentPattern } from './chunk-35I3PLS3.js';
|
|
3
|
+
export { ChainAnalyzer } from './chunk-RQYHXWUC.js';
|
|
4
|
+
export { FixSuggester } from './chunk-PIXJPQO7.js';
|
|
5
|
+
import { EventEmitter } from './chunk-WLN7ZVO4.js';
|
|
6
|
+
export { EventEmitter } from './chunk-WLN7ZVO4.js';
|
|
7
|
+
import { ensureDir, joinPath, writeTextFile } from './chunk-REEPUD73.js';
|
|
8
|
+
export { detectFramework, detectFrameworkFromWindow, ensureDir, exists, findUp, FRAMEWORK_DETECTORS as frameworkDetectors, getBaseName, getDirName, getExtension, getFrameworkTips, joinPath, readJsonFile, readTextFile, resolvePath, writeJsonFile, writeTextFile } from './chunk-REEPUD73.js';
|
|
4
9
|
import { createServer, request as request$1 } from 'http';
|
|
5
10
|
import { createHash } from 'crypto';
|
|
6
11
|
import { request } from 'https';
|
|
7
|
-
import { URL } from 'url';
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
13
|
-
};
|
|
14
|
-
var __export = (target, all) => {
|
|
15
|
-
for (var name in all)
|
|
16
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
17
|
-
};
|
|
18
|
-
|
|
19
|
-
// src/utils/event-emitter.ts
|
|
20
|
-
var EventEmitter;
|
|
21
|
-
var init_event_emitter = __esm({
|
|
22
|
-
"src/utils/event-emitter.ts"() {
|
|
23
|
-
EventEmitter = class {
|
|
24
|
-
/** Map of event names to their listeners */
|
|
25
|
-
_listeners = /* @__PURE__ */ new Map();
|
|
26
|
-
/** Map of event names to their one-time listeners */
|
|
27
|
-
_onceListeners = /* @__PURE__ */ new Map();
|
|
28
|
-
/** Maximum number of listeners per event (0 = unlimited) */
|
|
29
|
-
maxListeners = 0;
|
|
30
|
-
/**
|
|
31
|
-
* Add an event listener
|
|
32
|
-
* @param event - Event name
|
|
33
|
-
* @param listener - Callback function
|
|
34
|
-
* @returns this for chaining
|
|
35
|
-
*/
|
|
36
|
-
on(event, listener) {
|
|
37
|
-
let eventListeners = this._listeners.get(event);
|
|
38
|
-
if (!eventListeners) {
|
|
39
|
-
eventListeners = /* @__PURE__ */ new Set();
|
|
40
|
-
this._listeners.set(event, eventListeners);
|
|
41
|
-
}
|
|
42
|
-
if (this.maxListeners > 0 && eventListeners.size >= this.maxListeners) {
|
|
43
|
-
console.warn(
|
|
44
|
-
`Warning: Possible EventEmitter memory leak detected. ${eventListeners.size + 1} listeners added for event "${String(event)}". Use setMaxListeners() to increase limit.`
|
|
45
|
-
);
|
|
46
|
-
}
|
|
47
|
-
eventListeners.add(listener);
|
|
48
|
-
return this;
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Alias for on()
|
|
52
|
-
*/
|
|
53
|
-
addListener(event, listener) {
|
|
54
|
-
return this.on(event, listener);
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
|
-
* Add a one-time event listener
|
|
58
|
-
* @param event - Event name
|
|
59
|
-
* @param listener - Callback function
|
|
60
|
-
* @returns this for chaining
|
|
61
|
-
*/
|
|
62
|
-
once(event, listener) {
|
|
63
|
-
let eventListeners = this._onceListeners.get(event);
|
|
64
|
-
if (!eventListeners) {
|
|
65
|
-
eventListeners = /* @__PURE__ */ new Set();
|
|
66
|
-
this._onceListeners.set(event, eventListeners);
|
|
67
|
-
}
|
|
68
|
-
eventListeners.add(listener);
|
|
69
|
-
return this;
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* Remove an event listener
|
|
73
|
-
* @param event - Event name
|
|
74
|
-
* @param listener - Callback function to remove
|
|
75
|
-
* @returns this for chaining
|
|
76
|
-
*/
|
|
77
|
-
off(event, listener) {
|
|
78
|
-
const eventListeners = this._listeners.get(event);
|
|
79
|
-
if (eventListeners) {
|
|
80
|
-
eventListeners.delete(listener);
|
|
81
|
-
if (eventListeners.size === 0) {
|
|
82
|
-
this._listeners.delete(event);
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
const onceEventListeners = this._onceListeners.get(event);
|
|
86
|
-
if (onceEventListeners) {
|
|
87
|
-
onceEventListeners.delete(listener);
|
|
88
|
-
if (onceEventListeners.size === 0) {
|
|
89
|
-
this._onceListeners.delete(event);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
return this;
|
|
93
|
-
}
|
|
94
|
-
/**
|
|
95
|
-
* Alias for off()
|
|
96
|
-
*/
|
|
97
|
-
removeListener(event, listener) {
|
|
98
|
-
return this.off(event, listener);
|
|
99
|
-
}
|
|
100
|
-
/**
|
|
101
|
-
* Remove all listeners for an event, or all events if no event specified
|
|
102
|
-
* @param event - Optional event name
|
|
103
|
-
* @returns this for chaining
|
|
104
|
-
*/
|
|
105
|
-
removeAllListeners(event) {
|
|
106
|
-
if (event !== void 0) {
|
|
107
|
-
this._listeners.delete(event);
|
|
108
|
-
this._onceListeners.delete(event);
|
|
109
|
-
} else {
|
|
110
|
-
this._listeners.clear();
|
|
111
|
-
this._onceListeners.clear();
|
|
112
|
-
}
|
|
113
|
-
return this;
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Emit an event
|
|
117
|
-
* @param event - Event name
|
|
118
|
-
* @param data - Event data
|
|
119
|
-
* @returns true if any listeners were called
|
|
120
|
-
*/
|
|
121
|
-
emit(event, data) {
|
|
122
|
-
let called = false;
|
|
123
|
-
const eventListeners = this._listeners.get(event);
|
|
124
|
-
if (eventListeners) {
|
|
125
|
-
for (const listener of eventListeners) {
|
|
126
|
-
try {
|
|
127
|
-
listener(data);
|
|
128
|
-
called = true;
|
|
129
|
-
} catch (error) {
|
|
130
|
-
if (event !== "error") {
|
|
131
|
-
this.emit("error", error);
|
|
132
|
-
} else {
|
|
133
|
-
throw error;
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
const onceEventListeners = this._onceListeners.get(event);
|
|
139
|
-
if (onceEventListeners) {
|
|
140
|
-
const listenersToCall = Array.from(onceEventListeners);
|
|
141
|
-
this._onceListeners.delete(event);
|
|
142
|
-
for (const listener of listenersToCall) {
|
|
143
|
-
try {
|
|
144
|
-
listener(data);
|
|
145
|
-
called = true;
|
|
146
|
-
} catch (error) {
|
|
147
|
-
if (event !== "error") {
|
|
148
|
-
this.emit("error", error);
|
|
149
|
-
} else {
|
|
150
|
-
throw error;
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
return called;
|
|
156
|
-
}
|
|
157
|
-
/**
|
|
158
|
-
* Get all listener functions for an event
|
|
159
|
-
* @param event - Event name
|
|
160
|
-
* @returns Array of listener functions
|
|
161
|
-
*/
|
|
162
|
-
getListeners(event) {
|
|
163
|
-
const regular = this._listeners.get(event);
|
|
164
|
-
const once = this._onceListeners.get(event);
|
|
165
|
-
const result = [];
|
|
166
|
-
if (regular) {
|
|
167
|
-
result.push(...Array.from(regular));
|
|
168
|
-
}
|
|
169
|
-
if (once) {
|
|
170
|
-
result.push(...Array.from(once));
|
|
171
|
-
}
|
|
172
|
-
return result;
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
|
-
* Get the number of listeners for an event
|
|
176
|
-
* @param event - Event name
|
|
177
|
-
* @returns Number of listeners
|
|
178
|
-
*/
|
|
179
|
-
listenerCount(event) {
|
|
180
|
-
const regular = this._listeners.get(event)?.size ?? 0;
|
|
181
|
-
const once = this._onceListeners.get(event)?.size ?? 0;
|
|
182
|
-
return regular + once;
|
|
183
|
-
}
|
|
184
|
-
/**
|
|
185
|
-
* Get all event names that have listeners
|
|
186
|
-
* @returns Array of event names
|
|
187
|
-
*/
|
|
188
|
-
eventNames() {
|
|
189
|
-
const names = /* @__PURE__ */ new Set();
|
|
190
|
-
for (const name of this._listeners.keys()) {
|
|
191
|
-
names.add(name);
|
|
192
|
-
}
|
|
193
|
-
for (const name of this._onceListeners.keys()) {
|
|
194
|
-
names.add(name);
|
|
195
|
-
}
|
|
196
|
-
return Array.from(names);
|
|
197
|
-
}
|
|
198
|
-
/**
|
|
199
|
-
* Set the maximum number of listeners per event
|
|
200
|
-
* @param n - Maximum listeners (0 for unlimited)
|
|
201
|
-
* @returns this for chaining
|
|
202
|
-
*/
|
|
203
|
-
setMaxListeners(n) {
|
|
204
|
-
this.maxListeners = n;
|
|
205
|
-
return this;
|
|
206
|
-
}
|
|
207
|
-
/**
|
|
208
|
-
* Get the maximum number of listeners per event
|
|
209
|
-
* @returns Maximum listeners
|
|
210
|
-
*/
|
|
211
|
-
getMaxListeners() {
|
|
212
|
-
return this.maxListeners;
|
|
213
|
-
}
|
|
214
|
-
/**
|
|
215
|
-
* Prepend a listener to the beginning of the listeners array
|
|
216
|
-
* @param event - Event name
|
|
217
|
-
* @param listener - Callback function
|
|
218
|
-
* @returns this for chaining
|
|
219
|
-
*/
|
|
220
|
-
prependListener(event, listener) {
|
|
221
|
-
const eventListeners = this._listeners.get(event);
|
|
222
|
-
if (!eventListeners) {
|
|
223
|
-
return this.on(event, listener);
|
|
224
|
-
}
|
|
225
|
-
const arr = Array.from(eventListeners);
|
|
226
|
-
arr.unshift(listener);
|
|
227
|
-
this._listeners.set(event, new Set(arr));
|
|
228
|
-
return this;
|
|
229
|
-
}
|
|
230
|
-
/**
|
|
231
|
-
* Prepend a one-time listener to the beginning
|
|
232
|
-
* @param event - Event name
|
|
233
|
-
* @param listener - Callback function
|
|
234
|
-
* @returns this for chaining
|
|
235
|
-
*/
|
|
236
|
-
prependOnceListener(event, listener) {
|
|
237
|
-
const eventListeners = this._onceListeners.get(event);
|
|
238
|
-
if (!eventListeners) {
|
|
239
|
-
return this.once(event, listener);
|
|
240
|
-
}
|
|
241
|
-
const arr = Array.from(eventListeners);
|
|
242
|
-
arr.unshift(listener);
|
|
243
|
-
this._onceListeners.set(event, new Set(arr));
|
|
244
|
-
return this;
|
|
245
|
-
}
|
|
246
|
-
/**
|
|
247
|
-
* Wait for an event to be emitted
|
|
248
|
-
* @param event - Event name
|
|
249
|
-
* @param timeout - Optional timeout in milliseconds
|
|
250
|
-
* @returns Promise that resolves with the event data
|
|
251
|
-
*/
|
|
252
|
-
waitFor(event, timeout) {
|
|
253
|
-
return new Promise((resolve2, reject) => {
|
|
254
|
-
let timeoutId;
|
|
255
|
-
const listener = (data) => {
|
|
256
|
-
if (timeoutId) {
|
|
257
|
-
clearTimeout(timeoutId);
|
|
258
|
-
}
|
|
259
|
-
resolve2(data);
|
|
260
|
-
};
|
|
261
|
-
this.once(event, listener);
|
|
262
|
-
if (timeout !== void 0 && timeout > 0) {
|
|
263
|
-
timeoutId = setTimeout(() => {
|
|
264
|
-
this.off(event, listener);
|
|
265
|
-
reject(new Error(`Timeout waiting for event "${String(event)}"`));
|
|
266
|
-
}, timeout);
|
|
267
|
-
}
|
|
268
|
-
});
|
|
269
|
-
}
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
});
|
|
273
|
-
|
|
274
|
-
// src/utils/colors.ts
|
|
275
|
-
function checkColorSupport() {
|
|
276
|
-
if (process.env["FORCE_COLOR"] !== void 0) {
|
|
277
|
-
return process.env["FORCE_COLOR"] !== "0";
|
|
278
|
-
}
|
|
279
|
-
if (process.env["NO_COLOR"] !== void 0) {
|
|
280
|
-
return false;
|
|
281
|
-
}
|
|
282
|
-
if (!process.stdout.isTTY) {
|
|
283
|
-
return false;
|
|
284
|
-
}
|
|
285
|
-
if (process.env["TERM"] === "dumb") {
|
|
286
|
-
return false;
|
|
287
|
-
}
|
|
288
|
-
if (process.env["CI"] !== void 0) {
|
|
289
|
-
const ciEnvs = ["TRAVIS", "CIRCLECI", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE"];
|
|
290
|
-
return ciEnvs.some((env) => process.env[env] !== void 0);
|
|
291
|
-
}
|
|
292
|
-
return true;
|
|
293
|
-
}
|
|
294
|
-
function colorize(text, ...codes) {
|
|
295
|
-
if (!supportsColor || codes.length === 0) {
|
|
296
|
-
return text;
|
|
297
|
-
}
|
|
298
|
-
return codes.join("") + text + colors.reset;
|
|
299
|
-
}
|
|
300
|
-
function createColorizer(code) {
|
|
301
|
-
return (text) => colorize(text, code);
|
|
302
|
-
}
|
|
303
|
-
function stripAnsi(text) {
|
|
304
|
-
return text.replace(/\x1b\[[0-9;]*m/g, "");
|
|
305
|
-
}
|
|
306
|
-
var supportsColor, colors, semantic;
|
|
307
|
-
var init_colors = __esm({
|
|
308
|
-
"src/utils/colors.ts"() {
|
|
309
|
-
supportsColor = checkColorSupport();
|
|
310
|
-
colors = {
|
|
311
|
-
// Reset
|
|
312
|
-
reset: supportsColor ? "\x1B[0m" : "",
|
|
313
|
-
// Text styles
|
|
314
|
-
bold: supportsColor ? "\x1B[1m" : "",
|
|
315
|
-
dim: supportsColor ? "\x1B[2m" : "",
|
|
316
|
-
italic: supportsColor ? "\x1B[3m" : "",
|
|
317
|
-
underline: supportsColor ? "\x1B[4m" : "",
|
|
318
|
-
blink: supportsColor ? "\x1B[5m" : "",
|
|
319
|
-
inverse: supportsColor ? "\x1B[7m" : "",
|
|
320
|
-
hidden: supportsColor ? "\x1B[8m" : "",
|
|
321
|
-
strikethrough: supportsColor ? "\x1B[9m" : "",
|
|
322
|
-
// Foreground colors
|
|
323
|
-
black: supportsColor ? "\x1B[30m" : "",
|
|
324
|
-
red: supportsColor ? "\x1B[31m" : "",
|
|
325
|
-
green: supportsColor ? "\x1B[32m" : "",
|
|
326
|
-
yellow: supportsColor ? "\x1B[33m" : "",
|
|
327
|
-
blue: supportsColor ? "\x1B[34m" : "",
|
|
328
|
-
magenta: supportsColor ? "\x1B[35m" : "",
|
|
329
|
-
cyan: supportsColor ? "\x1B[36m" : "",
|
|
330
|
-
white: supportsColor ? "\x1B[37m" : "",
|
|
331
|
-
gray: supportsColor ? "\x1B[90m" : "",
|
|
332
|
-
grey: supportsColor ? "\x1B[90m" : "",
|
|
333
|
-
// Bright foreground colors
|
|
334
|
-
brightRed: supportsColor ? "\x1B[91m" : "",
|
|
335
|
-
brightGreen: supportsColor ? "\x1B[92m" : "",
|
|
336
|
-
brightYellow: supportsColor ? "\x1B[93m" : "",
|
|
337
|
-
brightBlue: supportsColor ? "\x1B[94m" : "",
|
|
338
|
-
brightMagenta: supportsColor ? "\x1B[95m" : "",
|
|
339
|
-
brightCyan: supportsColor ? "\x1B[96m" : "",
|
|
340
|
-
brightWhite: supportsColor ? "\x1B[97m" : "",
|
|
341
|
-
// Background colors
|
|
342
|
-
bgBlack: supportsColor ? "\x1B[40m" : "",
|
|
343
|
-
bgRed: supportsColor ? "\x1B[41m" : "",
|
|
344
|
-
bgGreen: supportsColor ? "\x1B[42m" : "",
|
|
345
|
-
bgYellow: supportsColor ? "\x1B[43m" : "",
|
|
346
|
-
bgBlue: supportsColor ? "\x1B[44m" : "",
|
|
347
|
-
bgMagenta: supportsColor ? "\x1B[45m" : "",
|
|
348
|
-
bgCyan: supportsColor ? "\x1B[46m" : "",
|
|
349
|
-
bgWhite: supportsColor ? "\x1B[47m" : "",
|
|
350
|
-
bgGray: supportsColor ? "\x1B[100m" : "",
|
|
351
|
-
// Bright background colors
|
|
352
|
-
bgBrightRed: supportsColor ? "\x1B[101m" : "",
|
|
353
|
-
bgBrightGreen: supportsColor ? "\x1B[102m" : "",
|
|
354
|
-
bgBrightYellow: supportsColor ? "\x1B[103m" : "",
|
|
355
|
-
bgBrightBlue: supportsColor ? "\x1B[104m" : "",
|
|
356
|
-
bgBrightMagenta: supportsColor ? "\x1B[105m" : "",
|
|
357
|
-
bgBrightCyan: supportsColor ? "\x1B[106m" : "",
|
|
358
|
-
bgBrightWhite: supportsColor ? "\x1B[107m" : ""
|
|
359
|
-
};
|
|
360
|
-
semantic = {
|
|
361
|
-
/** Critical issues (red) */
|
|
362
|
-
critical: createColorizer(colors.red),
|
|
363
|
-
/** Warnings (yellow) */
|
|
364
|
-
warning: createColorizer(colors.yellow),
|
|
365
|
-
/** Healthy/success (green) */
|
|
366
|
-
healthy: createColorizer(colors.green),
|
|
367
|
-
/** Info/links (blue) */
|
|
368
|
-
info: createColorizer(colors.blue),
|
|
369
|
-
/** Secondary text (gray) */
|
|
370
|
-
secondary: createColorizer(colors.gray),
|
|
371
|
-
/** Highlighted text (cyan) */
|
|
372
|
-
highlight: createColorizer(colors.cyan),
|
|
373
|
-
/** Error text (bright red, bold) */
|
|
374
|
-
error: (text) => colorize(text, colors.brightRed, colors.bold),
|
|
375
|
-
/** Success text (bright green, bold) */
|
|
376
|
-
success: (text) => colorize(text, colors.brightGreen, colors.bold),
|
|
377
|
-
/** Title text (bold) */
|
|
378
|
-
title: createColorizer(colors.bold),
|
|
379
|
-
/** Dimmed text */
|
|
380
|
-
dimmed: createColorizer(colors.dim)
|
|
381
|
-
};
|
|
382
|
-
}
|
|
383
|
-
});
|
|
384
|
-
|
|
385
|
-
// src/utils/logger.ts
|
|
386
|
-
var LogLevel, LOG_LEVEL_NAMES, Logger;
|
|
387
|
-
var init_logger = __esm({
|
|
388
|
-
"src/utils/logger.ts"() {
|
|
389
|
-
init_colors();
|
|
390
|
-
LogLevel = /* @__PURE__ */ ((LogLevel2) => {
|
|
391
|
-
LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
|
|
392
|
-
LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
|
|
393
|
-
LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
|
|
394
|
-
LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
|
|
395
|
-
LogLevel2[LogLevel2["SILENT"] = 4] = "SILENT";
|
|
396
|
-
return LogLevel2;
|
|
397
|
-
})(LogLevel || {});
|
|
398
|
-
LOG_LEVEL_NAMES = {
|
|
399
|
-
[0 /* DEBUG */]: "DEBUG",
|
|
400
|
-
[1 /* INFO */]: "INFO",
|
|
401
|
-
[2 /* WARN */]: "WARN",
|
|
402
|
-
[3 /* ERROR */]: "ERROR",
|
|
403
|
-
[4 /* SILENT */]: "SILENT"
|
|
404
|
-
};
|
|
405
|
-
Logger = class _Logger {
|
|
406
|
-
prefix;
|
|
407
|
-
level;
|
|
408
|
-
showTimestamp;
|
|
409
|
-
showLevel;
|
|
410
|
-
output;
|
|
411
|
-
/**
|
|
412
|
-
* Create a new Logger instance
|
|
413
|
-
* @param options - Logger configuration
|
|
414
|
-
*/
|
|
415
|
-
constructor(options = {}) {
|
|
416
|
-
this.prefix = options.prefix ?? "";
|
|
417
|
-
this.level = options.level ?? 1 /* INFO */;
|
|
418
|
-
this.showTimestamp = options.showTimestamp ?? false;
|
|
419
|
-
this.showLevel = options.showLevel ?? true;
|
|
420
|
-
this.output = options.output ?? {
|
|
421
|
-
/* eslint-disable no-console */
|
|
422
|
-
log: (msg) => console.log(msg),
|
|
423
|
-
warn: (msg) => console.warn(msg),
|
|
424
|
-
error: (msg) => console.error(msg)
|
|
425
|
-
/* eslint-enable no-console */
|
|
426
|
-
};
|
|
427
|
-
}
|
|
428
|
-
/**
|
|
429
|
-
* Format a log message
|
|
430
|
-
* @param level - Log level
|
|
431
|
-
* @param message - Message to format
|
|
432
|
-
* @returns Formatted message
|
|
433
|
-
*/
|
|
434
|
-
format(level, message) {
|
|
435
|
-
const parts = [];
|
|
436
|
-
if (this.showTimestamp) {
|
|
437
|
-
const now = /* @__PURE__ */ new Date();
|
|
438
|
-
const time = now.toISOString().slice(11, 23);
|
|
439
|
-
parts.push(semantic.secondary(`[${time}]`));
|
|
440
|
-
}
|
|
441
|
-
if (this.showLevel) {
|
|
442
|
-
const levelName = LOG_LEVEL_NAMES[level] ?? "UNKNOWN";
|
|
443
|
-
let levelStr;
|
|
444
|
-
switch (level) {
|
|
445
|
-
case 0 /* DEBUG */:
|
|
446
|
-
levelStr = semantic.secondary(levelName);
|
|
447
|
-
break;
|
|
448
|
-
case 1 /* INFO */:
|
|
449
|
-
levelStr = semantic.info(levelName);
|
|
450
|
-
break;
|
|
451
|
-
case 2 /* WARN */:
|
|
452
|
-
levelStr = semantic.warning(levelName);
|
|
453
|
-
break;
|
|
454
|
-
case 3 /* ERROR */:
|
|
455
|
-
levelStr = semantic.error(levelName);
|
|
456
|
-
break;
|
|
457
|
-
default:
|
|
458
|
-
levelStr = levelName;
|
|
459
|
-
}
|
|
460
|
-
parts.push(`[${levelStr}]`);
|
|
461
|
-
}
|
|
462
|
-
if (this.prefix) {
|
|
463
|
-
parts.push(semantic.highlight(`[${this.prefix}]`));
|
|
464
|
-
}
|
|
465
|
-
parts.push(message);
|
|
466
|
-
return parts.join(" ");
|
|
467
|
-
}
|
|
468
|
-
/**
|
|
469
|
-
* Log a debug message
|
|
470
|
-
* @param message - Message to log
|
|
471
|
-
* @param args - Additional arguments to log
|
|
472
|
-
*/
|
|
473
|
-
debug(message, ...args) {
|
|
474
|
-
if (this.level > 0 /* DEBUG */) return;
|
|
475
|
-
const formatted = this.format(0 /* DEBUG */, message);
|
|
476
|
-
if (args.length > 0) {
|
|
477
|
-
this.output.log(formatted + " " + args.map(String).join(" "));
|
|
478
|
-
} else {
|
|
479
|
-
this.output.log(formatted);
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
/**
|
|
483
|
-
* Log an info message
|
|
484
|
-
* @param message - Message to log
|
|
485
|
-
* @param args - Additional arguments to log
|
|
486
|
-
*/
|
|
487
|
-
info(message, ...args) {
|
|
488
|
-
if (this.level > 1 /* INFO */) return;
|
|
489
|
-
const formatted = this.format(1 /* INFO */, message);
|
|
490
|
-
if (args.length > 0) {
|
|
491
|
-
this.output.log(formatted + " " + args.map(String).join(" "));
|
|
492
|
-
} else {
|
|
493
|
-
this.output.log(formatted);
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
/**
|
|
497
|
-
* Log a warning message
|
|
498
|
-
* @param message - Message to log
|
|
499
|
-
* @param args - Additional arguments to log
|
|
500
|
-
*/
|
|
501
|
-
warn(message, ...args) {
|
|
502
|
-
if (this.level > 2 /* WARN */) return;
|
|
503
|
-
const formatted = this.format(2 /* WARN */, message);
|
|
504
|
-
if (args.length > 0) {
|
|
505
|
-
this.output.warn(formatted + " " + args.map(String).join(" "));
|
|
506
|
-
} else {
|
|
507
|
-
this.output.warn(formatted);
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
/**
|
|
511
|
-
* Log an error message
|
|
512
|
-
* @param message - Message to log
|
|
513
|
-
* @param args - Additional arguments to log
|
|
514
|
-
*/
|
|
515
|
-
error(message, ...args) {
|
|
516
|
-
if (this.level > 3 /* ERROR */) return;
|
|
517
|
-
const formatted = this.format(3 /* ERROR */, message);
|
|
518
|
-
if (args.length > 0) {
|
|
519
|
-
this.output.error(formatted + " " + args.map(String).join(" "));
|
|
520
|
-
} else {
|
|
521
|
-
this.output.error(formatted);
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
/**
|
|
525
|
-
* Log a success message (always shown unless silent)
|
|
526
|
-
* @param message - Message to log
|
|
527
|
-
*/
|
|
528
|
-
success(message) {
|
|
529
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
530
|
-
const prefix = this.prefix ? `[${semantic.highlight(this.prefix)}] ` : "";
|
|
531
|
-
this.output.log(prefix + semantic.success("\u2713 ") + message);
|
|
532
|
-
}
|
|
533
|
-
/**
|
|
534
|
-
* Log a failure message (always shown unless silent)
|
|
535
|
-
* @param message - Message to log
|
|
536
|
-
*/
|
|
537
|
-
fail(message) {
|
|
538
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
539
|
-
const prefix = this.prefix ? `[${semantic.highlight(this.prefix)}] ` : "";
|
|
540
|
-
this.output.error(prefix + semantic.error("\u2717 ") + message);
|
|
541
|
-
}
|
|
542
|
-
/**
|
|
543
|
-
* Create a child logger with a sub-prefix
|
|
544
|
-
* @param prefix - Sub-prefix for the child logger
|
|
545
|
-
* @returns New Logger instance
|
|
546
|
-
*/
|
|
547
|
-
child(prefix) {
|
|
548
|
-
const childPrefix = this.prefix ? `${this.prefix}:${prefix}` : prefix;
|
|
549
|
-
return new _Logger({
|
|
550
|
-
prefix: childPrefix,
|
|
551
|
-
level: this.level,
|
|
552
|
-
showTimestamp: this.showTimestamp,
|
|
553
|
-
showLevel: this.showLevel,
|
|
554
|
-
output: this.output
|
|
555
|
-
});
|
|
556
|
-
}
|
|
557
|
-
/**
|
|
558
|
-
* Set the log level
|
|
559
|
-
* @param level - New log level
|
|
560
|
-
*/
|
|
561
|
-
setLevel(level) {
|
|
562
|
-
this.level = level;
|
|
563
|
-
}
|
|
564
|
-
/**
|
|
565
|
-
* Get the current log level
|
|
566
|
-
* @returns Current log level
|
|
567
|
-
*/
|
|
568
|
-
getLevel() {
|
|
569
|
-
return this.level;
|
|
570
|
-
}
|
|
571
|
-
/**
|
|
572
|
-
* Check if a log level is enabled
|
|
573
|
-
* @param level - Level to check
|
|
574
|
-
* @returns true if the level would be logged
|
|
575
|
-
*/
|
|
576
|
-
isLevelEnabled(level) {
|
|
577
|
-
return this.level <= level;
|
|
578
|
-
}
|
|
579
|
-
/**
|
|
580
|
-
* Create a timer for performance logging
|
|
581
|
-
* @param label - Timer label
|
|
582
|
-
* @returns Object with end() method to log duration
|
|
583
|
-
*/
|
|
584
|
-
time(label) {
|
|
585
|
-
const start = performance.now();
|
|
586
|
-
return {
|
|
587
|
-
end: () => {
|
|
588
|
-
const duration = performance.now() - start;
|
|
589
|
-
this.debug(`${label}: ${duration.toFixed(2)}ms`);
|
|
590
|
-
}
|
|
591
|
-
};
|
|
592
|
-
}
|
|
593
|
-
/**
|
|
594
|
-
* Log a table of data
|
|
595
|
-
* @param data - Array of objects to display
|
|
596
|
-
* @param columns - Optional column names to show
|
|
597
|
-
*/
|
|
598
|
-
table(data, columns) {
|
|
599
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
600
|
-
if (data.length === 0) {
|
|
601
|
-
this.info("(empty table)");
|
|
602
|
-
return;
|
|
603
|
-
}
|
|
604
|
-
const cols = columns ?? Object.keys(data[0] ?? {});
|
|
605
|
-
if (cols.length === 0) {
|
|
606
|
-
this.info("(no columns)");
|
|
607
|
-
return;
|
|
608
|
-
}
|
|
609
|
-
const widths = {};
|
|
610
|
-
for (const col of cols) {
|
|
611
|
-
widths[col] = col.length;
|
|
612
|
-
for (const row of data) {
|
|
613
|
-
const value = String(row[col] ?? "");
|
|
614
|
-
widths[col] = Math.max(widths[col] ?? 0, value.length);
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
const header = cols.map((col) => col.padEnd(widths[col] ?? 0)).join(" \u2502 ");
|
|
618
|
-
const separator = cols.map((col) => "\u2500".repeat(widths[col] ?? 0)).join("\u2500\u253C\u2500");
|
|
619
|
-
this.output.log(colors.bold + header + colors.reset);
|
|
620
|
-
this.output.log(separator);
|
|
621
|
-
for (const row of data) {
|
|
622
|
-
const line = cols.map((col) => String(row[col] ?? "").padEnd(widths[col] ?? 0)).join(" \u2502 ");
|
|
623
|
-
this.output.log(line);
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
/**
|
|
627
|
-
* Log a progress message (overwrites previous line)
|
|
628
|
-
* @param message - Progress message
|
|
629
|
-
*/
|
|
630
|
-
progress(message) {
|
|
631
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
632
|
-
if (process.stdout.isTTY) {
|
|
633
|
-
process.stdout.write(`\r\x1B[K${message}`);
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
/**
|
|
637
|
-
* Clear the progress line
|
|
638
|
-
*/
|
|
639
|
-
clearProgress() {
|
|
640
|
-
if (process.stdout.isTTY) {
|
|
641
|
-
process.stdout.write("\r\x1B[K");
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
/**
|
|
645
|
-
* Log a newline
|
|
646
|
-
*/
|
|
647
|
-
newline() {
|
|
648
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
649
|
-
this.output.log("");
|
|
650
|
-
}
|
|
651
|
-
/**
|
|
652
|
-
* Log a horizontal rule
|
|
653
|
-
* @param char - Character to use for the rule
|
|
654
|
-
* @param width - Width of the rule
|
|
655
|
-
*/
|
|
656
|
-
hr(char = "\u2500", width = 60) {
|
|
657
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
658
|
-
this.output.log(colors.gray + char.repeat(width) + colors.reset);
|
|
659
|
-
}
|
|
660
|
-
/**
|
|
661
|
-
* Group related log messages
|
|
662
|
-
* @param label - Group label
|
|
663
|
-
* @param fn - Function containing log calls
|
|
664
|
-
*/
|
|
665
|
-
group(label, fn) {
|
|
666
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
667
|
-
this.output.log(colors.bold + "\u250C " + label + colors.reset);
|
|
668
|
-
fn();
|
|
669
|
-
this.output.log(colors.bold + "\u2514" + "\u2500".repeat(label.length + 1) + colors.reset);
|
|
670
|
-
}
|
|
671
|
-
};
|
|
672
|
-
new Logger({ prefix: "ReactCheck" });
|
|
673
|
-
}
|
|
674
|
-
});
|
|
675
|
-
|
|
676
|
-
// src/server/browser.ts
|
|
677
|
-
var browser_exports = {};
|
|
678
|
-
__export(browser_exports, {
|
|
679
|
-
BrowserLauncher: () => BrowserLauncher,
|
|
680
|
-
isPuppeteerAvailable: () => isPuppeteerAvailable
|
|
681
|
-
});
|
|
682
|
-
async function isPuppeteerAvailable() {
|
|
683
|
-
try {
|
|
684
|
-
await import('puppeteer');
|
|
685
|
-
return true;
|
|
686
|
-
} catch {
|
|
687
|
-
return false;
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
var logger3, BrowserLauncher;
|
|
691
|
-
var init_browser = __esm({
|
|
692
|
-
"src/server/browser.ts"() {
|
|
693
|
-
init_event_emitter();
|
|
694
|
-
init_logger();
|
|
695
|
-
logger3 = new Logger({ prefix: "browser", level: 0 /* DEBUG */ });
|
|
696
|
-
BrowserLauncher = class extends EventEmitter {
|
|
697
|
-
/** Puppeteer browser instance */
|
|
698
|
-
browser = null;
|
|
699
|
-
/** Active page */
|
|
700
|
-
page = null;
|
|
701
|
-
/** Launch options */
|
|
702
|
-
options;
|
|
703
|
-
/** Injection script */
|
|
704
|
-
injectionScript = null;
|
|
705
|
-
/**
|
|
706
|
-
* Create a new browser launcher
|
|
707
|
-
* @param options - Launch options
|
|
708
|
-
*/
|
|
709
|
-
constructor(options) {
|
|
710
|
-
super();
|
|
711
|
-
this.options = {
|
|
712
|
-
url: options.url,
|
|
713
|
-
headless: options.headless ?? false,
|
|
714
|
-
width: options.width ?? 1280,
|
|
715
|
-
height: options.height ?? 800,
|
|
716
|
-
wsPort: options.wsPort ?? 3099,
|
|
717
|
-
args: options.args ?? [],
|
|
718
|
-
slowMo: options.slowMo ?? 0,
|
|
719
|
-
timeout: options.timeout ?? 3e4
|
|
720
|
-
};
|
|
721
|
-
}
|
|
722
|
-
/**
|
|
723
|
-
* Set the injection script
|
|
724
|
-
* @param script - Script to inject before page loads
|
|
725
|
-
*/
|
|
726
|
-
setInjectionScript(script) {
|
|
727
|
-
this.injectionScript = script;
|
|
728
|
-
}
|
|
729
|
-
/**
|
|
730
|
-
* Launch the browser
|
|
731
|
-
*/
|
|
732
|
-
async launch() {
|
|
733
|
-
try {
|
|
734
|
-
const puppeteer = await import('puppeteer');
|
|
735
|
-
const args = [
|
|
736
|
-
"--no-sandbox",
|
|
737
|
-
"--disable-setuid-sandbox",
|
|
738
|
-
"--disable-dev-shm-usage",
|
|
739
|
-
"--disable-gpu",
|
|
740
|
-
"--ignore-certificate-errors",
|
|
741
|
-
"--ignore-certificate-errors-spki-list",
|
|
742
|
-
`--window-size=${this.options.width},${this.options.height}`,
|
|
743
|
-
...this.options.args
|
|
744
|
-
];
|
|
745
|
-
this.browser = await puppeteer.default.launch({
|
|
746
|
-
headless: this.options.headless,
|
|
747
|
-
args,
|
|
748
|
-
slowMo: this.options.slowMo,
|
|
749
|
-
defaultViewport: {
|
|
750
|
-
width: this.options.width,
|
|
751
|
-
height: this.options.height
|
|
752
|
-
}
|
|
753
|
-
});
|
|
754
|
-
const pages = await this.browser.pages();
|
|
755
|
-
this.page = pages[0] ?? await this.browser.newPage();
|
|
756
|
-
this.setupPageHandlers();
|
|
757
|
-
if (this.injectionScript) {
|
|
758
|
-
logger3.debug("Injecting ReactCheck script into page...");
|
|
759
|
-
await this.page.evaluateOnNewDocument(this.injectionScript);
|
|
760
|
-
logger3.debug("Injection script registered");
|
|
761
|
-
}
|
|
762
|
-
this.emit("launched", void 0);
|
|
763
|
-
logger3.info("Browser launched");
|
|
764
|
-
await this.navigate(this.options.url);
|
|
765
|
-
} catch (error) {
|
|
766
|
-
const err = error instanceof Error ? error : new Error(String(error));
|
|
767
|
-
this.emit("error", err);
|
|
768
|
-
throw err;
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
/**
|
|
772
|
-
* Set up page event handlers
|
|
773
|
-
*/
|
|
774
|
-
setupPageHandlers() {
|
|
775
|
-
if (!this.page) return;
|
|
776
|
-
this.page.on("console", (msg) => {
|
|
777
|
-
this.emit("console", {
|
|
778
|
-
type: msg.type(),
|
|
779
|
-
text: msg.text()
|
|
780
|
-
});
|
|
781
|
-
});
|
|
782
|
-
this.page.on("pageerror", (error) => {
|
|
783
|
-
this.emit("error", error);
|
|
784
|
-
});
|
|
785
|
-
this.page.on("framenavigated", (frame) => {
|
|
786
|
-
if (frame === this.page?.mainFrame()) {
|
|
787
|
-
this.emit("navigated", { url: frame.url() });
|
|
788
|
-
}
|
|
789
|
-
});
|
|
790
|
-
this.page.on("load", () => {
|
|
791
|
-
this.emit("loaded", void 0);
|
|
792
|
-
});
|
|
793
|
-
}
|
|
794
|
-
/**
|
|
795
|
-
* Navigate to a URL with retry support
|
|
796
|
-
* @param url - URL to navigate to
|
|
797
|
-
* @param retries - Number of retries (default: 3)
|
|
798
|
-
* @param retryDelay - Delay between retries in ms (default: 2000)
|
|
799
|
-
*/
|
|
800
|
-
async navigate(url, retries = 3, retryDelay = 2e3) {
|
|
801
|
-
if (!this.page) {
|
|
802
|
-
throw new Error("Browser not launched");
|
|
803
|
-
}
|
|
804
|
-
let lastError = null;
|
|
805
|
-
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
806
|
-
try {
|
|
807
|
-
await this.page.goto(url, {
|
|
808
|
-
waitUntil: "networkidle2",
|
|
809
|
-
timeout: this.options.timeout
|
|
810
|
-
});
|
|
811
|
-
this.emit("navigated", { url });
|
|
812
|
-
logger3.info(`Navigated to ${url}`);
|
|
813
|
-
return;
|
|
814
|
-
} catch (error) {
|
|
815
|
-
lastError = error instanceof Error ? error : new Error(String(error));
|
|
816
|
-
this.emit("error", lastError);
|
|
817
|
-
if (lastError.message.includes("ERR_CONNECTION_REFUSED") && attempt < retries) {
|
|
818
|
-
logger3.warn(`Connection refused, retrying in ${retryDelay}ms... (${attempt}/${retries})`);
|
|
819
|
-
await new Promise((resolve2) => setTimeout(resolve2, retryDelay));
|
|
820
|
-
continue;
|
|
821
|
-
}
|
|
822
|
-
throw lastError;
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
throw lastError ?? new Error("Navigation failed");
|
|
826
|
-
}
|
|
827
|
-
/**
|
|
828
|
-
* Execute script in page context
|
|
829
|
-
* @param script - Script to execute
|
|
830
|
-
* @returns Script result
|
|
831
|
-
*/
|
|
832
|
-
async evaluate(script) {
|
|
833
|
-
if (!this.page) {
|
|
834
|
-
throw new Error("Browser not launched");
|
|
835
|
-
}
|
|
836
|
-
return this.page.evaluate(script);
|
|
837
|
-
}
|
|
838
|
-
/**
|
|
839
|
-
* Wait for selector
|
|
840
|
-
* @param selector - CSS selector
|
|
841
|
-
* @param timeout - Timeout in ms
|
|
842
|
-
*/
|
|
843
|
-
async waitForSelector(selector, timeout) {
|
|
844
|
-
if (!this.page) {
|
|
845
|
-
throw new Error("Browser not launched");
|
|
846
|
-
}
|
|
847
|
-
await this.page.waitForSelector(selector, {
|
|
848
|
-
timeout: timeout ?? this.options.timeout
|
|
849
|
-
});
|
|
850
|
-
}
|
|
851
|
-
/**
|
|
852
|
-
* Take a screenshot
|
|
853
|
-
* @param path - File path to save screenshot
|
|
854
|
-
*/
|
|
855
|
-
async screenshot(path) {
|
|
856
|
-
if (!this.page) {
|
|
857
|
-
throw new Error("Browser not launched");
|
|
858
|
-
}
|
|
859
|
-
await this.page.screenshot({ path, fullPage: true });
|
|
860
|
-
logger3.info(`Screenshot saved to ${path}`);
|
|
861
|
-
}
|
|
862
|
-
/**
|
|
863
|
-
* Reload the page
|
|
864
|
-
*/
|
|
865
|
-
async reload() {
|
|
866
|
-
if (!this.page) {
|
|
867
|
-
throw new Error("Browser not launched");
|
|
868
|
-
}
|
|
869
|
-
await this.page.reload({ waitUntil: "networkidle2" });
|
|
870
|
-
}
|
|
871
|
-
/**
|
|
872
|
-
* Get current URL
|
|
873
|
-
* @returns Current page URL
|
|
874
|
-
*/
|
|
875
|
-
getUrl() {
|
|
876
|
-
return this.page?.url() ?? null;
|
|
877
|
-
}
|
|
878
|
-
/**
|
|
879
|
-
* Close the browser
|
|
880
|
-
*/
|
|
881
|
-
async close() {
|
|
882
|
-
if (this.browser) {
|
|
883
|
-
await this.browser.close();
|
|
884
|
-
this.browser = null;
|
|
885
|
-
this.page = null;
|
|
886
|
-
this.emit("closed", void 0);
|
|
887
|
-
logger3.info("Browser closed");
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
/**
|
|
891
|
-
* Check if browser is open
|
|
892
|
-
* @returns true if browser is open
|
|
893
|
-
*/
|
|
894
|
-
isOpen() {
|
|
895
|
-
return this.browser !== null && this.browser.connected;
|
|
896
|
-
}
|
|
897
|
-
/**
|
|
898
|
-
* Get the page instance (for advanced usage)
|
|
899
|
-
* @returns Puppeteer page or null
|
|
900
|
-
*/
|
|
901
|
-
getPage() {
|
|
902
|
-
return this.page;
|
|
903
|
-
}
|
|
904
|
-
/**
|
|
905
|
-
* Get the browser instance (for advanced usage)
|
|
906
|
-
* @returns Puppeteer browser or null
|
|
907
|
-
*/
|
|
908
|
-
getBrowser() {
|
|
909
|
-
return this.browser;
|
|
910
|
-
}
|
|
911
|
-
};
|
|
912
|
-
}
|
|
913
|
-
});
|
|
12
|
+
import { URL, fileURLToPath } from 'url';
|
|
13
|
+
import { readFile } from 'fs/promises';
|
|
14
|
+
import { dirname, resolve, join } from 'path';
|
|
15
|
+
import { createRequire } from 'module';
|
|
16
|
+
import { homedir } from 'os';
|
|
914
17
|
|
|
915
18
|
// src/types.ts
|
|
916
19
|
var ErrorCode = /* @__PURE__ */ ((ErrorCode2) => {
|
|
917
20
|
ErrorCode2["CONFIG_INVALID"] = "CONFIG_INVALID";
|
|
918
|
-
ErrorCode2["CONFIG_NOT_FOUND"] = "CONFIG_NOT_FOUND";
|
|
919
|
-
ErrorCode2["CONNECTION_FAILED"] = "CONNECTION_FAILED";
|
|
920
|
-
ErrorCode2["REACT_NOT_FOUND"] = "REACT_NOT_FOUND";
|
|
921
|
-
ErrorCode2["BROWSER_LAUNCH_FAILED"] = "BROWSER_LAUNCH_FAILED";
|
|
922
|
-
ErrorCode2["WEBSOCKET_ERROR"] = "WEBSOCKET_ERROR";
|
|
923
|
-
ErrorCode2["REPORT_WRITE_FAILED"] = "REPORT_WRITE_FAILED";
|
|
924
|
-
ErrorCode2["INVALID_URL"] = "INVALID_URL";
|
|
925
|
-
ErrorCode2["TIMEOUT"] = "TIMEOUT";
|
|
926
|
-
ErrorCode2["UNKNOWN"] = "UNKNOWN";
|
|
927
|
-
return ErrorCode2;
|
|
928
|
-
})(ErrorCode || {});
|
|
929
|
-
var ReactCheckError = class extends Error {
|
|
930
|
-
/** Error code */
|
|
931
|
-
code;
|
|
932
|
-
/** Additional error details */
|
|
933
|
-
details;
|
|
934
|
-
constructor(code, message, details) {
|
|
935
|
-
super(message);
|
|
936
|
-
this.name = "ReactCheckError";
|
|
937
|
-
this.code = code;
|
|
938
|
-
this.details = details;
|
|
939
|
-
}
|
|
940
|
-
};
|
|
941
|
-
|
|
942
|
-
// src/core/scanner.ts
|
|
943
|
-
init_event_emitter();
|
|
944
|
-
|
|
945
|
-
// src/core/stats.ts
|
|
946
|
-
init_event_emitter();
|
|
947
|
-
var DEFAULT_THRESHOLDS = {
|
|
948
|
-
critical: 50,
|
|
949
|
-
warning: 20,
|
|
950
|
-
fps: 30
|
|
951
|
-
};
|
|
952
|
-
var StatsCollector = class extends EventEmitter {
|
|
953
|
-
/** Map of component names to their statistics */
|
|
954
|
-
components = /* @__PURE__ */ new Map();
|
|
955
|
-
/** Threshold configuration */
|
|
956
|
-
thresholds;
|
|
957
|
-
/** Session start time */
|
|
958
|
-
sessionStart;
|
|
959
|
-
/** Total render count across all components */
|
|
960
|
-
totalRenders = 0;
|
|
961
|
-
/** FPS samples for averaging */
|
|
962
|
-
fpsSamples = [];
|
|
963
|
-
/** Maximum FPS samples to keep */
|
|
964
|
-
maxFpsSamples = 100;
|
|
965
|
-
/**
|
|
966
|
-
* Create a new StatsCollector
|
|
967
|
-
* @param thresholds - Threshold configuration
|
|
968
|
-
*/
|
|
969
|
-
constructor(thresholds = {}) {
|
|
970
|
-
super();
|
|
971
|
-
this.thresholds = { ...DEFAULT_THRESHOLDS, ...thresholds };
|
|
972
|
-
this.sessionStart = Date.now();
|
|
973
|
-
}
|
|
974
|
-
/**
|
|
975
|
-
* Add a render event to the statistics
|
|
976
|
-
* @param render - Render information
|
|
977
|
-
*/
|
|
978
|
-
addRender(render) {
|
|
979
|
-
const stats = this.getOrCreateStats(render.componentName);
|
|
980
|
-
const previousSeverity = stats.severity;
|
|
981
|
-
stats.renders++;
|
|
982
|
-
this.totalRenders++;
|
|
983
|
-
stats.totalRenderTime += render.renderTime;
|
|
984
|
-
stats.avgRenderTime = stats.totalRenderTime / stats.renders;
|
|
985
|
-
stats.maxRenderTime = Math.max(stats.maxRenderTime, render.renderTime);
|
|
986
|
-
stats.minRenderTime = Math.min(stats.minRenderTime, render.renderTime);
|
|
987
|
-
if (!render.necessary) {
|
|
988
|
-
stats.unnecessary++;
|
|
989
|
-
}
|
|
990
|
-
if (stats.firstRender === 0) {
|
|
991
|
-
stats.firstRender = render.timestamp;
|
|
992
|
-
}
|
|
993
|
-
stats.lastRender = render.timestamp;
|
|
994
|
-
if (render.changedProps && render.changedProps.length > 0) {
|
|
995
|
-
stats.propsChanged = true;
|
|
996
|
-
}
|
|
997
|
-
if (render.changedState && render.changedState.length > 0) {
|
|
998
|
-
stats.stateChanged = true;
|
|
999
|
-
}
|
|
1000
|
-
const sessionDuration = Date.now() - this.sessionStart;
|
|
1001
|
-
const sessionMinutes = sessionDuration / 6e4;
|
|
1002
|
-
stats.expectedRenders = Math.max(1, Math.ceil(sessionMinutes * 5));
|
|
1003
|
-
this.updateSeverity(stats);
|
|
1004
|
-
this.emit("update", stats);
|
|
1005
|
-
if (stats.severity !== previousSeverity) {
|
|
1006
|
-
this.emit("severityChange", {
|
|
1007
|
-
component: stats.name,
|
|
1008
|
-
from: previousSeverity,
|
|
1009
|
-
to: stats.severity
|
|
1010
|
-
});
|
|
1011
|
-
if (stats.severity === "critical" && previousSeverity !== "critical") {
|
|
1012
|
-
this.emit("critical", stats);
|
|
1013
|
-
} else if (stats.severity === "warning" && previousSeverity === "healthy") {
|
|
1014
|
-
this.emit("warning", stats);
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
/**
|
|
1019
|
-
* Record an FPS sample
|
|
1020
|
-
* @param fps - FPS value
|
|
1021
|
-
*/
|
|
1022
|
-
addFpsSample(fps) {
|
|
1023
|
-
this.fpsSamples.push(fps);
|
|
1024
|
-
if (this.fpsSamples.length > this.maxFpsSamples) {
|
|
1025
|
-
this.fpsSamples.shift();
|
|
1026
|
-
}
|
|
1027
|
-
}
|
|
1028
|
-
/**
|
|
1029
|
-
* Get or create stats for a component
|
|
1030
|
-
* @param name - Component name
|
|
1031
|
-
* @returns Component stats
|
|
1032
|
-
*/
|
|
1033
|
-
getOrCreateStats(name) {
|
|
1034
|
-
let stats = this.components.get(name);
|
|
1035
|
-
if (!stats) {
|
|
1036
|
-
stats = this.createEmptyStats(name);
|
|
1037
|
-
this.components.set(name, stats);
|
|
1038
|
-
}
|
|
1039
|
-
return stats;
|
|
1040
|
-
}
|
|
1041
|
-
/**
|
|
1042
|
-
* Create empty stats for a component
|
|
1043
|
-
* @param name - Component name
|
|
1044
|
-
* @returns Empty component stats
|
|
1045
|
-
*/
|
|
1046
|
-
createEmptyStats(name) {
|
|
1047
|
-
return {
|
|
1048
|
-
name,
|
|
1049
|
-
renders: 0,
|
|
1050
|
-
expectedRenders: 1,
|
|
1051
|
-
avgRenderTime: 0,
|
|
1052
|
-
maxRenderTime: 0,
|
|
1053
|
-
minRenderTime: Infinity,
|
|
1054
|
-
totalRenderTime: 0,
|
|
1055
|
-
unnecessary: 0,
|
|
1056
|
-
severity: "healthy",
|
|
1057
|
-
chain: [],
|
|
1058
|
-
fixes: [],
|
|
1059
|
-
firstRender: 0,
|
|
1060
|
-
lastRender: 0,
|
|
1061
|
-
propsChanged: false,
|
|
1062
|
-
stateChanged: false
|
|
1063
|
-
};
|
|
1064
|
-
}
|
|
1065
|
-
/**
|
|
1066
|
-
* Update severity for a component based on thresholds
|
|
1067
|
-
* @param stats - Component stats to update
|
|
1068
|
-
*/
|
|
1069
|
-
updateSeverity(stats) {
|
|
1070
|
-
if (stats.renders >= this.thresholds.critical) {
|
|
1071
|
-
stats.severity = "critical";
|
|
1072
|
-
} else if (stats.renders >= this.thresholds.warning) {
|
|
1073
|
-
stats.severity = "warning";
|
|
1074
|
-
} else {
|
|
1075
|
-
stats.severity = "healthy";
|
|
1076
|
-
}
|
|
1077
|
-
}
|
|
1078
|
-
/**
|
|
1079
|
-
* Get stats for a specific component
|
|
1080
|
-
* @param name - Component name
|
|
1081
|
-
* @returns Component stats or undefined
|
|
1082
|
-
*/
|
|
1083
|
-
getComponentStats(name) {
|
|
1084
|
-
return this.components.get(name);
|
|
1085
|
-
}
|
|
1086
|
-
/**
|
|
1087
|
-
* Get all component stats
|
|
1088
|
-
* @returns Array of component stats
|
|
1089
|
-
*/
|
|
1090
|
-
getAllStats() {
|
|
1091
|
-
return Array.from(this.components.values());
|
|
1092
|
-
}
|
|
1093
|
-
/**
|
|
1094
|
-
* Get a snapshot of all stats sorted by severity/render count
|
|
1095
|
-
* @returns Sorted array of component stats
|
|
1096
|
-
*/
|
|
1097
|
-
getSnapshot() {
|
|
1098
|
-
return this.getAllStats().sort((a, b) => {
|
|
1099
|
-
const severityOrder = {
|
|
1100
|
-
critical: 0,
|
|
1101
|
-
warning: 1,
|
|
1102
|
-
info: 2,
|
|
1103
|
-
healthy: 3
|
|
1104
|
-
};
|
|
1105
|
-
const severityDiff = severityOrder[a.severity] - severityOrder[b.severity];
|
|
1106
|
-
if (severityDiff !== 0) return severityDiff;
|
|
1107
|
-
return b.renders - a.renders;
|
|
1108
|
-
});
|
|
1109
|
-
}
|
|
1110
|
-
/**
|
|
1111
|
-
* Get components by severity
|
|
1112
|
-
* @param severity - Severity level to filter
|
|
1113
|
-
* @returns Array of matching component stats
|
|
1114
|
-
*/
|
|
1115
|
-
getComponentsBySeverity(severity) {
|
|
1116
|
-
return this.getAllStats().filter((s) => s.severity === severity);
|
|
1117
|
-
}
|
|
1118
|
-
/**
|
|
1119
|
-
* Get session summary
|
|
1120
|
-
* @returns Session summary statistics
|
|
1121
|
-
*/
|
|
1122
|
-
getSummary() {
|
|
1123
|
-
const stats = this.getAllStats();
|
|
1124
|
-
const criticalCount = stats.filter((s) => s.severity === "critical").length;
|
|
1125
|
-
const warningCount = stats.filter((s) => s.severity === "warning").length;
|
|
1126
|
-
const healthyCount = stats.filter((s) => s.severity === "healthy").length;
|
|
1127
|
-
const unnecessaryCount = stats.reduce((sum, s) => sum + s.unnecessary, 0);
|
|
1128
|
-
let avgFps = 60;
|
|
1129
|
-
let minFps = 60;
|
|
1130
|
-
if (this.fpsSamples.length > 0) {
|
|
1131
|
-
avgFps = this.fpsSamples.reduce((a, b) => a + b, 0) / this.fpsSamples.length;
|
|
1132
|
-
minFps = Math.min(...this.fpsSamples);
|
|
1133
|
-
}
|
|
1134
|
-
return {
|
|
1135
|
-
totalComponents: stats.length,
|
|
1136
|
-
totalRenders: this.totalRenders,
|
|
1137
|
-
criticalIssues: criticalCount,
|
|
1138
|
-
warnings: warningCount,
|
|
1139
|
-
healthy: healthyCount,
|
|
1140
|
-
avgFps: Math.round(avgFps),
|
|
1141
|
-
minFps: Math.round(minFps),
|
|
1142
|
-
unnecessaryRenders: unnecessaryCount
|
|
1143
|
-
};
|
|
1144
|
-
}
|
|
1145
|
-
/**
|
|
1146
|
-
* Get the most problematic components
|
|
1147
|
-
* @param limit - Maximum number to return
|
|
1148
|
-
* @returns Top problematic components
|
|
1149
|
-
*/
|
|
1150
|
-
getTopProblems(limit = 10) {
|
|
1151
|
-
return this.getSnapshot().filter((s) => s.severity !== "healthy").slice(0, limit);
|
|
1152
|
-
}
|
|
1153
|
-
/**
|
|
1154
|
-
* Update chain information for a component
|
|
1155
|
-
* @param componentName - Component name
|
|
1156
|
-
* @param chain - Render chain
|
|
1157
|
-
*/
|
|
1158
|
-
setComponentChain(componentName, chain) {
|
|
1159
|
-
const stats = this.components.get(componentName);
|
|
1160
|
-
if (stats) {
|
|
1161
|
-
stats.chain = chain;
|
|
1162
|
-
}
|
|
1163
|
-
}
|
|
1164
|
-
/**
|
|
1165
|
-
* Update parent information for a component
|
|
1166
|
-
* @param componentName - Component name
|
|
1167
|
-
* @param parentName - Parent component name
|
|
1168
|
-
*/
|
|
1169
|
-
setComponentParent(componentName, parentName) {
|
|
1170
|
-
const stats = this.components.get(componentName);
|
|
1171
|
-
if (stats) {
|
|
1172
|
-
stats.parent = parentName;
|
|
1173
|
-
}
|
|
1174
|
-
}
|
|
1175
|
-
/**
|
|
1176
|
-
* Reset all statistics
|
|
1177
|
-
*/
|
|
1178
|
-
reset() {
|
|
1179
|
-
this.components.clear();
|
|
1180
|
-
this.totalRenders = 0;
|
|
1181
|
-
this.fpsSamples = [];
|
|
1182
|
-
this.sessionStart = Date.now();
|
|
1183
|
-
}
|
|
1184
|
-
/**
|
|
1185
|
-
* Update threshold configuration
|
|
1186
|
-
* @param thresholds - New thresholds
|
|
1187
|
-
*/
|
|
1188
|
-
setThresholds(thresholds) {
|
|
1189
|
-
this.thresholds = { ...this.thresholds, ...thresholds };
|
|
1190
|
-
for (const stats of this.components.values()) {
|
|
1191
|
-
const previousSeverity = stats.severity;
|
|
1192
|
-
this.updateSeverity(stats);
|
|
1193
|
-
if (stats.severity !== previousSeverity) {
|
|
1194
|
-
this.emit("severityChange", {
|
|
1195
|
-
component: stats.name,
|
|
1196
|
-
from: previousSeverity,
|
|
1197
|
-
to: stats.severity
|
|
1198
|
-
});
|
|
1199
|
-
}
|
|
1200
|
-
}
|
|
1201
|
-
}
|
|
1202
|
-
/**
|
|
1203
|
-
* Get current thresholds
|
|
1204
|
-
* @returns Current threshold configuration
|
|
1205
|
-
*/
|
|
1206
|
-
getThresholds() {
|
|
1207
|
-
return { ...this.thresholds };
|
|
1208
|
-
}
|
|
1209
|
-
/**
|
|
1210
|
-
* Get session duration in milliseconds
|
|
1211
|
-
* @returns Session duration
|
|
1212
|
-
*/
|
|
1213
|
-
getSessionDuration() {
|
|
1214
|
-
return Date.now() - this.sessionStart;
|
|
1215
|
-
}
|
|
1216
|
-
/**
|
|
1217
|
-
* Get total render count
|
|
1218
|
-
* @returns Total renders across all components
|
|
1219
|
-
*/
|
|
1220
|
-
getTotalRenders() {
|
|
1221
|
-
return this.totalRenders;
|
|
1222
|
-
}
|
|
1223
|
-
/**
|
|
1224
|
-
* Get component count
|
|
1225
|
-
* @returns Number of tracked components
|
|
1226
|
-
*/
|
|
1227
|
-
getComponentCount() {
|
|
1228
|
-
return this.components.size;
|
|
1229
|
-
}
|
|
1230
|
-
/**
|
|
1231
|
-
* Check if FPS is below threshold
|
|
1232
|
-
* @returns true if average FPS is below threshold
|
|
1233
|
-
*/
|
|
1234
|
-
isFpsBelowThreshold() {
|
|
1235
|
-
if (this.fpsSamples.length === 0) return false;
|
|
1236
|
-
const avgFps = this.fpsSamples.reduce((a, b) => a + b, 0) / this.fpsSamples.length;
|
|
1237
|
-
return avgFps < this.thresholds.fps;
|
|
1238
|
-
}
|
|
1239
|
-
/**
|
|
1240
|
-
* Export stats for serialization
|
|
1241
|
-
* @returns Serializable stats object
|
|
1242
|
-
*/
|
|
1243
|
-
export() {
|
|
1244
|
-
return {
|
|
1245
|
-
components: this.getSnapshot(),
|
|
1246
|
-
summary: this.getSummary(),
|
|
1247
|
-
thresholds: this.getThresholds(),
|
|
1248
|
-
sessionDuration: this.getSessionDuration()
|
|
1249
|
-
};
|
|
1250
|
-
}
|
|
1251
|
-
};
|
|
1252
|
-
|
|
1253
|
-
// src/core/chain.ts
|
|
1254
|
-
init_event_emitter();
|
|
1255
|
-
var ChainAnalyzer = class extends EventEmitter {
|
|
1256
|
-
/** Time window size in ms (one frame at 60fps) */
|
|
1257
|
-
windowSize;
|
|
1258
|
-
/** Current render windows being tracked */
|
|
1259
|
-
windows = /* @__PURE__ */ new Map();
|
|
1260
|
-
/** Component parent relationships */
|
|
1261
|
-
parentMap = /* @__PURE__ */ new Map();
|
|
1262
|
-
/** Recently detected chains to avoid duplicates */
|
|
1263
|
-
recentChains = /* @__PURE__ */ new Set();
|
|
1264
|
-
/** Minimum chain depth to report */
|
|
1265
|
-
minChainDepth;
|
|
1266
|
-
/** Maximum time to keep recent chains */
|
|
1267
|
-
recentChainTtl;
|
|
1268
|
-
/**
|
|
1269
|
-
* Create a new ChainAnalyzer
|
|
1270
|
-
* @param options - Configuration options
|
|
1271
|
-
*/
|
|
1272
|
-
constructor(options = {}) {
|
|
1273
|
-
super();
|
|
1274
|
-
this.windowSize = options.windowSize ?? 16;
|
|
1275
|
-
this.minChainDepth = options.minChainDepth ?? 2;
|
|
1276
|
-
this.recentChainTtl = options.recentChainTtl ?? 1e3;
|
|
1277
|
-
}
|
|
1278
|
-
/**
|
|
1279
|
-
* Add a render event for analysis
|
|
1280
|
-
* @param render - Render information
|
|
1281
|
-
* @param parent - Optional parent component name
|
|
1282
|
-
*/
|
|
1283
|
-
addRender(render, parent) {
|
|
1284
|
-
const trackedRender = {
|
|
1285
|
-
...render,
|
|
1286
|
-
...parent !== void 0 ? { parent } : {},
|
|
1287
|
-
contextTriggered: this.isContextTriggered(render)
|
|
1288
|
-
};
|
|
1289
|
-
if (parent) {
|
|
1290
|
-
this.parentMap.set(render.componentName, parent);
|
|
1291
|
-
}
|
|
1292
|
-
const windowKey = this.getWindowKey(render.timestamp);
|
|
1293
|
-
let window2 = this.windows.get(windowKey);
|
|
1294
|
-
if (!window2) {
|
|
1295
|
-
window2 = {
|
|
1296
|
-
renders: [],
|
|
1297
|
-
startTime: render.timestamp
|
|
1298
|
-
};
|
|
1299
|
-
this.windows.set(windowKey, window2);
|
|
1300
|
-
}
|
|
1301
|
-
window2.renders.push(trackedRender);
|
|
1302
|
-
if (window2.renders.length >= this.minChainDepth) {
|
|
1303
|
-
this.analyzeWindow(windowKey);
|
|
1304
|
-
}
|
|
1305
|
-
this.cleanupWindows(render.timestamp);
|
|
1306
|
-
}
|
|
1307
|
-
/**
|
|
1308
|
-
* Set parent relationship for a component
|
|
1309
|
-
* @param child - Child component name
|
|
1310
|
-
* @param parent - Parent component name
|
|
1311
|
-
*/
|
|
1312
|
-
setParent(child, parent) {
|
|
1313
|
-
this.parentMap.set(child, parent);
|
|
1314
|
-
}
|
|
1315
|
-
/**
|
|
1316
|
-
* Get window key for a timestamp
|
|
1317
|
-
* @param timestamp - Timestamp in ms
|
|
1318
|
-
* @returns Window key
|
|
1319
|
-
*/
|
|
1320
|
-
getWindowKey(timestamp) {
|
|
1321
|
-
return Math.floor(timestamp / this.windowSize);
|
|
1322
|
-
}
|
|
1323
|
-
/**
|
|
1324
|
-
* Check if a render was likely triggered by context
|
|
1325
|
-
* @param render - Render information
|
|
1326
|
-
* @returns true if context-triggered
|
|
1327
|
-
*/
|
|
1328
|
-
isContextTriggered(render) {
|
|
1329
|
-
return !render.changedProps?.length && !render.changedState?.length && render.phase === "update";
|
|
1330
|
-
}
|
|
1331
|
-
/**
|
|
1332
|
-
* Analyze a render window for chains
|
|
1333
|
-
* @param windowKey - Window key to analyze
|
|
1334
|
-
*/
|
|
1335
|
-
analyzeWindow(windowKey) {
|
|
1336
|
-
const window2 = this.windows.get(windowKey);
|
|
1337
|
-
if (!window2 || window2.renders.length < this.minChainDepth) {
|
|
1338
|
-
return;
|
|
1339
|
-
}
|
|
1340
|
-
const sortedRenders = [...window2.renders].sort((a, b) => a.timestamp - b.timestamp);
|
|
1341
|
-
const chains = this.buildChains(sortedRenders);
|
|
1342
|
-
for (const chain of chains) {
|
|
1343
|
-
const chainKey = this.getChainKey(chain);
|
|
1344
|
-
if (this.recentChains.has(chainKey)) {
|
|
1345
|
-
continue;
|
|
1346
|
-
}
|
|
1347
|
-
this.recentChains.add(chainKey);
|
|
1348
|
-
setTimeout(() => {
|
|
1349
|
-
this.recentChains.delete(chainKey);
|
|
1350
|
-
}, this.recentChainTtl);
|
|
1351
|
-
this.emit("chain", chain);
|
|
1352
|
-
if (chain.isContextTriggered) {
|
|
1353
|
-
this.emit("contextChain", chain);
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
}
|
|
1357
|
-
/**
|
|
1358
|
-
* Build chains from a sorted render sequence
|
|
1359
|
-
* @param renders - Sorted render events
|
|
1360
|
-
* @returns Detected chains
|
|
1361
|
-
*/
|
|
1362
|
-
buildChains(renders) {
|
|
1363
|
-
const chains = [];
|
|
1364
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1365
|
-
const chainComponents = [];
|
|
1366
|
-
for (const render of renders) {
|
|
1367
|
-
if (visited.has(render.componentName)) {
|
|
1368
|
-
continue;
|
|
1369
|
-
}
|
|
1370
|
-
const chain = this.traceChain(render.componentName, renders, visited);
|
|
1371
|
-
if (chain.length >= this.minChainDepth) {
|
|
1372
|
-
chainComponents.push(chain);
|
|
1373
|
-
}
|
|
1374
|
-
}
|
|
1375
|
-
for (const chain of chainComponents) {
|
|
1376
|
-
const chainRenders = renders.filter((r) => chain.includes(r.componentName));
|
|
1377
|
-
const isContextTriggered = chainRenders.some((r) => r.contextTriggered);
|
|
1378
|
-
const rootCause = this.findRootCause(chain, renders);
|
|
1379
|
-
const trigger = this.determineTrigger(rootCause, renders);
|
|
1380
|
-
chains.push({
|
|
1381
|
-
trigger,
|
|
1382
|
-
chain,
|
|
1383
|
-
depth: chain.length,
|
|
1384
|
-
totalRenders: chainRenders.length,
|
|
1385
|
-
rootCause,
|
|
1386
|
-
timestamp: Date.now(),
|
|
1387
|
-
isContextTriggered
|
|
1388
|
-
});
|
|
1389
|
-
}
|
|
1390
|
-
return chains;
|
|
1391
|
-
}
|
|
1392
|
-
/**
|
|
1393
|
-
* Trace a chain starting from a component
|
|
1394
|
-
* @param startComponent - Starting component
|
|
1395
|
-
* @param renders - All renders in window
|
|
1396
|
-
* @param visited - Already visited components
|
|
1397
|
-
* @returns Chain of component names
|
|
1398
|
-
*/
|
|
1399
|
-
traceChain(startComponent, renders, visited) {
|
|
1400
|
-
const chain = [];
|
|
1401
|
-
const queue = [startComponent];
|
|
1402
|
-
while (queue.length > 0) {
|
|
1403
|
-
const current = queue.shift();
|
|
1404
|
-
if (!current || visited.has(current)) {
|
|
1405
|
-
continue;
|
|
1406
|
-
}
|
|
1407
|
-
visited.add(current);
|
|
1408
|
-
chain.push(current);
|
|
1409
|
-
const parent = this.parentMap.get(current);
|
|
1410
|
-
if (parent && renders.some((r) => r.componentName === parent) && !visited.has(parent)) {
|
|
1411
|
-
queue.unshift(parent);
|
|
1412
|
-
}
|
|
1413
|
-
for (const [child, p] of this.parentMap) {
|
|
1414
|
-
if (p === current && renders.some((r) => r.componentName === child) && !visited.has(child)) {
|
|
1415
|
-
queue.push(child);
|
|
1416
|
-
}
|
|
1417
|
-
}
|
|
1418
|
-
}
|
|
1419
|
-
return chain;
|
|
1420
|
-
}
|
|
1421
|
-
/**
|
|
1422
|
-
* Find the root cause component in a chain
|
|
1423
|
-
* @param chain - Component chain
|
|
1424
|
-
* @param renders - All renders
|
|
1425
|
-
* @returns Root cause component name
|
|
1426
|
-
*/
|
|
1427
|
-
findRootCause(chain, renders) {
|
|
1428
|
-
const chainRenders = renders.filter((r) => chain.includes(r.componentName)).sort((a, b) => a.timestamp - b.timestamp);
|
|
1429
|
-
for (const render of chainRenders) {
|
|
1430
|
-
if (render.changedState?.length ?? render.changedProps?.length) {
|
|
1431
|
-
return render.componentName;
|
|
1432
|
-
}
|
|
1433
|
-
}
|
|
1434
|
-
return chain[0] ?? "Unknown";
|
|
1435
|
-
}
|
|
1436
|
-
/**
|
|
1437
|
-
* Determine what triggered a chain
|
|
1438
|
-
* @param rootCause - Root cause component
|
|
1439
|
-
* @param renders - All renders
|
|
1440
|
-
* @returns Trigger description
|
|
1441
|
-
*/
|
|
1442
|
-
determineTrigger(rootCause, renders) {
|
|
1443
|
-
const render = renders.find((r) => r.componentName === rootCause);
|
|
1444
|
-
if (!render) {
|
|
1445
|
-
return `Unknown trigger in ${rootCause}`;
|
|
1446
|
-
}
|
|
1447
|
-
if (render.changedState?.length) {
|
|
1448
|
-
return `setState in ${rootCause}`;
|
|
1449
|
-
}
|
|
1450
|
-
if (render.changedProps?.length) {
|
|
1451
|
-
const props = render.changedProps.slice(0, 3).join(", ");
|
|
1452
|
-
const more = render.changedProps.length > 3 ? "..." : "";
|
|
1453
|
-
return `Props changed (${props}${more}) in ${rootCause}`;
|
|
1454
|
-
}
|
|
1455
|
-
if (render.contextTriggered) {
|
|
1456
|
-
return `Context update affecting ${rootCause}`;
|
|
1457
|
-
}
|
|
1458
|
-
if (render.phase === "mount") {
|
|
1459
|
-
return `Initial mount of ${rootCause}`;
|
|
1460
|
-
}
|
|
1461
|
-
return `Re-render of ${rootCause}`;
|
|
1462
|
-
}
|
|
1463
|
-
/**
|
|
1464
|
-
* Generate a unique key for a chain to detect duplicates
|
|
1465
|
-
* @param chain - Chain info
|
|
1466
|
-
* @returns Unique key
|
|
1467
|
-
*/
|
|
1468
|
-
getChainKey(chain) {
|
|
1469
|
-
return `${chain.rootCause}:${chain.chain.join("->")}`;
|
|
1470
|
-
}
|
|
1471
|
-
/**
|
|
1472
|
-
* Clean up old render windows
|
|
1473
|
-
* @param currentTime - Current timestamp
|
|
1474
|
-
*/
|
|
1475
|
-
cleanupWindows(currentTime) {
|
|
1476
|
-
const cutoff = currentTime - this.windowSize * 10;
|
|
1477
|
-
for (const [key, window2] of this.windows) {
|
|
1478
|
-
if (window2.startTime < cutoff) {
|
|
1479
|
-
this.windows.delete(key);
|
|
1480
|
-
}
|
|
1481
|
-
}
|
|
1482
|
-
}
|
|
1483
|
-
/**
|
|
1484
|
-
* Get the parent of a component
|
|
1485
|
-
* @param componentName - Component name
|
|
1486
|
-
* @returns Parent name or undefined
|
|
1487
|
-
*/
|
|
1488
|
-
getParent(componentName) {
|
|
1489
|
-
return this.parentMap.get(componentName);
|
|
1490
|
-
}
|
|
1491
|
-
/**
|
|
1492
|
-
* Get all known parent relationships
|
|
1493
|
-
* @returns Map of child to parent
|
|
1494
|
-
*/
|
|
1495
|
-
getParentMap() {
|
|
1496
|
-
return new Map(this.parentMap);
|
|
1497
|
-
}
|
|
1498
|
-
/**
|
|
1499
|
-
* Build a full chain for a component (tracing up to root)
|
|
1500
|
-
* @param componentName - Starting component
|
|
1501
|
-
* @returns Chain from root to component
|
|
1502
|
-
*/
|
|
1503
|
-
getComponentChain(componentName) {
|
|
1504
|
-
const chain = [];
|
|
1505
|
-
let current = componentName;
|
|
1506
|
-
while (current) {
|
|
1507
|
-
chain.unshift(current);
|
|
1508
|
-
current = this.parentMap.get(current);
|
|
1509
|
-
if (chain.length > 100) {
|
|
1510
|
-
break;
|
|
1511
|
-
}
|
|
1512
|
-
}
|
|
1513
|
-
return chain;
|
|
1514
|
-
}
|
|
1515
|
-
/**
|
|
1516
|
-
* Clear all tracked data
|
|
1517
|
-
*/
|
|
1518
|
-
reset() {
|
|
1519
|
-
this.windows.clear();
|
|
1520
|
-
this.parentMap.clear();
|
|
1521
|
-
this.recentChains.clear();
|
|
1522
|
-
}
|
|
1523
|
-
/**
|
|
1524
|
-
* Get statistics about current tracking
|
|
1525
|
-
* @returns Tracking statistics
|
|
1526
|
-
*/
|
|
1527
|
-
getStats() {
|
|
1528
|
-
return {
|
|
1529
|
-
windowCount: this.windows.size,
|
|
1530
|
-
parentRelationships: this.parentMap.size,
|
|
1531
|
-
recentChains: this.recentChains.size
|
|
1532
|
-
};
|
|
1533
|
-
}
|
|
1534
|
-
};
|
|
1535
|
-
|
|
1536
|
-
// src/core/fix.ts
|
|
1537
|
-
init_event_emitter();
|
|
1538
|
-
var BUILTIN_RULES = [
|
|
1539
|
-
// React.memo rule
|
|
1540
|
-
{
|
|
1541
|
-
id: "unnecessary-rerenders-memo",
|
|
1542
|
-
name: "Unnecessary Re-renders (memo)",
|
|
1543
|
-
description: "Component re-renders frequently without prop changes",
|
|
1544
|
-
fixType: "React.memo",
|
|
1545
|
-
priority: 1,
|
|
1546
|
-
detect: (stats) => {
|
|
1547
|
-
const unnecessaryRatio = stats.renders > 0 ? stats.unnecessary / stats.renders : 0;
|
|
1548
|
-
return stats.renders >= 10 && unnecessaryRatio >= 0.5 && !stats.propsChanged;
|
|
1549
|
-
},
|
|
1550
|
-
suggest: (stats) => ({
|
|
1551
|
-
severity: stats.severity === "healthy" ? "info" : stats.severity,
|
|
1552
|
-
issue: `Component "${stats.name}" re-renders ${stats.unnecessary} times unnecessarily out of ${stats.renders} total renders`,
|
|
1553
|
-
cause: stats.parent ? `Parent component "${stats.parent}" re-renders and causes cascading updates` : "Parent component re-renders propagate to this component",
|
|
1554
|
-
codeBefore: generateComponentCode(stats.name),
|
|
1555
|
-
codeAfter: generateMemoCode(stats.name),
|
|
1556
|
-
explanation: "React.memo is a higher-order component that prevents re-renders when props are unchanged. It performs a shallow comparison of props and skips rendering if they match.",
|
|
1557
|
-
impact: `Could prevent ~${stats.unnecessary} unnecessary renders (${Math.round(stats.unnecessary / stats.renders * 100)}% reduction)`
|
|
1558
|
-
})
|
|
1559
|
-
},
|
|
1560
|
-
// useMemo rule for expensive computations
|
|
1561
|
-
{
|
|
1562
|
-
id: "expensive-computation-memo",
|
|
1563
|
-
name: "Expensive Computation",
|
|
1564
|
-
description: "Component has high render times suggesting expensive calculations",
|
|
1565
|
-
fixType: "useMemo",
|
|
1566
|
-
priority: 2,
|
|
1567
|
-
detect: (stats) => {
|
|
1568
|
-
return stats.avgRenderTime > 16 && stats.renders >= 5;
|
|
1569
|
-
},
|
|
1570
|
-
suggest: (stats) => ({
|
|
1571
|
-
severity: stats.avgRenderTime > 50 ? "critical" : "warning",
|
|
1572
|
-
issue: `Component "${stats.name}" has slow renders averaging ${stats.avgRenderTime.toFixed(1)}ms`,
|
|
1573
|
-
cause: "Expensive calculations or data transformations are being performed on every render",
|
|
1574
|
-
codeBefore: generateExpensiveCode(stats.name),
|
|
1575
|
-
codeAfter: generateUseMemoCode(stats.name),
|
|
1576
|
-
explanation: "useMemo caches the result of expensive computations between renders. It only recalculates when dependencies change, improving performance.",
|
|
1577
|
-
impact: `Could reduce render time from ${stats.avgRenderTime.toFixed(1)}ms to <1ms for cached renders`
|
|
1578
|
-
})
|
|
1579
|
-
},
|
|
1580
|
-
// useCallback rule for function props
|
|
1581
|
-
{
|
|
1582
|
-
id: "function-prop-stability",
|
|
1583
|
-
name: "Unstable Function Props",
|
|
1584
|
-
description: "Component passes inline functions as props causing child re-renders",
|
|
1585
|
-
fixType: "useCallback",
|
|
1586
|
-
priority: 3,
|
|
1587
|
-
detect: (stats) => {
|
|
1588
|
-
return stats.renders >= 15 && stats.propsChanged;
|
|
1589
|
-
},
|
|
1590
|
-
suggest: (stats) => ({
|
|
1591
|
-
severity: stats.severity === "healthy" ? "info" : stats.severity,
|
|
1592
|
-
issue: `Component "${stats.name}" may be passing unstable function references as props`,
|
|
1593
|
-
cause: "Inline arrow functions are recreated on every render, causing children with React.memo to re-render",
|
|
1594
|
-
codeBefore: generateInlineFunctionCode(stats.name),
|
|
1595
|
-
codeAfter: generateUseCallbackCode(stats.name),
|
|
1596
|
-
explanation: "useCallback returns a memoized callback that only changes when dependencies change. This stabilizes function references passed to child components.",
|
|
1597
|
-
impact: "Stabilized function props allow memoized children to skip re-renders"
|
|
1598
|
-
})
|
|
1599
|
-
},
|
|
1600
|
-
// Context split rule
|
|
1601
|
-
{
|
|
1602
|
-
id: "context-over-subscription",
|
|
1603
|
-
name: "Context Over-subscription",
|
|
1604
|
-
description: "Context updates trigger unnecessary re-renders in unrelated components",
|
|
1605
|
-
fixType: "context-split",
|
|
1606
|
-
priority: 4,
|
|
1607
|
-
detect: (stats) => {
|
|
1608
|
-
return stats.renders >= 20 && stats.unnecessary > stats.renders * 0.7 && !stats.propsChanged && !stats.stateChanged;
|
|
1609
|
-
},
|
|
1610
|
-
suggest: (stats) => ({
|
|
1611
|
-
severity: stats.severity === "healthy" ? "warning" : stats.severity,
|
|
1612
|
-
issue: `Component "${stats.name}" re-renders due to context updates it doesn't use`,
|
|
1613
|
-
cause: "A context this component subscribes to contains unrelated state that changes frequently",
|
|
1614
|
-
codeBefore: generateContextCode("AppContext"),
|
|
1615
|
-
codeAfter: generateSplitContextCode(),
|
|
1616
|
-
explanation: "Splitting large contexts into smaller, focused contexts prevents unrelated updates from triggering re-renders in components that only need part of the context.",
|
|
1617
|
-
impact: `Could eliminate ${stats.unnecessary} unnecessary renders caused by unrelated context updates`
|
|
1618
|
-
})
|
|
1619
|
-
},
|
|
1620
|
-
// State colocation rule
|
|
1621
|
-
{
|
|
1622
|
-
id: "state-too-high",
|
|
1623
|
-
name: "State Location",
|
|
1624
|
-
description: "State is managed too high in the component tree",
|
|
1625
|
-
fixType: "state-colocation",
|
|
1626
|
-
priority: 5,
|
|
1627
|
-
detect: (stats) => {
|
|
1628
|
-
const chainDepth = stats.chain.length;
|
|
1629
|
-
return stats.renders >= 30 && chainDepth >= 3 && stats.stateChanged;
|
|
1630
|
-
},
|
|
1631
|
-
suggest: (stats) => ({
|
|
1632
|
-
severity: stats.severity === "healthy" ? "warning" : stats.severity,
|
|
1633
|
-
issue: `State changes in "${stats.name}" trigger a cascade of ${stats.chain.length} component re-renders`,
|
|
1634
|
-
cause: `State that only affects a subtree is managed at the "${stats.name}" level, causing unnecessary updates`,
|
|
1635
|
-
codeBefore: generateStateHighCode(stats.name),
|
|
1636
|
-
codeAfter: generateStateColocationCode(stats.name),
|
|
1637
|
-
explanation: "Moving state closer to where it's used (colocation) reduces the re-render scope. Only components that actually need the state will update.",
|
|
1638
|
-
impact: `Could reduce cascade depth from ${stats.chain.length} to 1-2 components`
|
|
1639
|
-
})
|
|
1640
|
-
},
|
|
1641
|
-
// Component extraction rule
|
|
1642
|
-
{
|
|
1643
|
-
id: "extract-heavy-child",
|
|
1644
|
-
name: "Component Extraction",
|
|
1645
|
-
description: "Part of the component updates independently and should be extracted",
|
|
1646
|
-
fixType: "component-extraction",
|
|
1647
|
-
priority: 6,
|
|
1648
|
-
detect: (stats) => {
|
|
1649
|
-
return stats.renders >= 50 && stats.avgRenderTime > 5;
|
|
1650
|
-
},
|
|
1651
|
-
suggest: (stats) => ({
|
|
1652
|
-
severity: stats.severity === "healthy" ? "info" : stats.severity,
|
|
1653
|
-
issue: `Component "${stats.name}" renders frequently (${stats.renders} times) with mixed concerns`,
|
|
1654
|
-
cause: "The component contains parts that update at different rates, causing full re-renders",
|
|
1655
|
-
codeBefore: generateMonolithCode(stats.name),
|
|
1656
|
-
codeAfter: generateExtractedCode(stats.name),
|
|
1657
|
-
explanation: "Extracting frequently-updating parts into separate components allows React to optimize renders for each part independently.",
|
|
1658
|
-
impact: "Isolates render cycles so fast-updating parts don't affect slow-updating parts"
|
|
1659
|
-
})
|
|
1660
|
-
}
|
|
1661
|
-
];
|
|
1662
|
-
function generateComponentCode(name, type) {
|
|
1663
|
-
return `function ${name}({ prop1, prop2 }) {
|
|
1664
|
-
return (
|
|
1665
|
-
<div>
|
|
1666
|
-
{/* component content */}
|
|
1667
|
-
</div>
|
|
1668
|
-
);
|
|
1669
|
-
}
|
|
1670
|
-
|
|
1671
|
-
export default ${name};`;
|
|
1672
|
-
}
|
|
1673
|
-
function generateMemoCode(name) {
|
|
1674
|
-
return `import { memo } from 'react';
|
|
1675
|
-
|
|
1676
|
-
const ${name} = memo(function ${name}({ prop1, prop2 }) {
|
|
1677
|
-
return (
|
|
1678
|
-
<div>
|
|
1679
|
-
{/* component content */}
|
|
1680
|
-
</div>
|
|
1681
|
-
);
|
|
1682
|
-
});
|
|
1683
|
-
|
|
1684
|
-
export default ${name};`;
|
|
1685
|
-
}
|
|
1686
|
-
function generateExpensiveCode(name) {
|
|
1687
|
-
return `function ${name}({ items }) {
|
|
1688
|
-
// Expensive computation on every render
|
|
1689
|
-
const processed = items
|
|
1690
|
-
.filter(item => item.active)
|
|
1691
|
-
.map(item => transform(item))
|
|
1692
|
-
.sort((a, b) => a.value - b.value);
|
|
1693
|
-
|
|
1694
|
-
return <List items={processed} />;
|
|
1695
|
-
}`;
|
|
1696
|
-
}
|
|
1697
|
-
function generateUseMemoCode(name) {
|
|
1698
|
-
return `import { useMemo } from 'react';
|
|
1699
|
-
|
|
1700
|
-
function ${name}({ items }) {
|
|
1701
|
-
// Computation cached until items change
|
|
1702
|
-
const processed = useMemo(() => {
|
|
1703
|
-
return items
|
|
1704
|
-
.filter(item => item.active)
|
|
1705
|
-
.map(item => transform(item))
|
|
1706
|
-
.sort((a, b) => a.value - b.value);
|
|
1707
|
-
}, [items]);
|
|
1708
|
-
|
|
1709
|
-
return <List items={processed} />;
|
|
1710
|
-
}`;
|
|
1711
|
-
}
|
|
1712
|
-
function generateInlineFunctionCode(name) {
|
|
1713
|
-
return `function ${name}({ data }) {
|
|
1714
|
-
return (
|
|
1715
|
-
<ChildComponent
|
|
1716
|
-
onAction={(id) => handleAction(id)} // New function every render!
|
|
1717
|
-
onClick={() => setOpen(true)} // New function every render!
|
|
1718
|
-
/>
|
|
1719
|
-
);
|
|
1720
|
-
}`;
|
|
1721
|
-
}
|
|
1722
|
-
function generateUseCallbackCode(name) {
|
|
1723
|
-
return `import { useCallback } from 'react';
|
|
1724
|
-
|
|
1725
|
-
function ${name}({ data }) {
|
|
1726
|
-
const handleAction = useCallback((id) => {
|
|
1727
|
-
// Handle action
|
|
1728
|
-
}, []); // Empty deps if no external dependencies
|
|
1729
|
-
|
|
1730
|
-
const handleClick = useCallback(() => {
|
|
1731
|
-
setOpen(true);
|
|
1732
|
-
}, []);
|
|
1733
|
-
|
|
1734
|
-
return (
|
|
1735
|
-
<ChildComponent
|
|
1736
|
-
onAction={handleAction} // Stable reference
|
|
1737
|
-
onClick={handleClick} // Stable reference
|
|
1738
|
-
/>
|
|
1739
|
-
);
|
|
1740
|
-
}`;
|
|
1741
|
-
}
|
|
1742
|
-
function generateContextCode(contextName) {
|
|
1743
|
-
return `// Single large context with mixed concerns
|
|
1744
|
-
const ${contextName} = createContext({
|
|
1745
|
-
user: null,
|
|
1746
|
-
theme: 'light',
|
|
1747
|
-
notifications: [],
|
|
1748
|
-
settings: {},
|
|
1749
|
-
cart: [],
|
|
1750
|
-
// ... many more values
|
|
1751
|
-
});
|
|
1752
|
-
|
|
1753
|
-
// Every consumer re-renders when ANY value changes
|
|
1754
|
-
function Component() {
|
|
1755
|
-
const { theme } = useContext(${contextName});
|
|
1756
|
-
// Re-renders when user, notifications, cart change too!
|
|
1757
|
-
return <div className={theme}>...</div>;
|
|
1758
|
-
}`;
|
|
1759
|
-
}
|
|
1760
|
-
function generateSplitContextCode() {
|
|
1761
|
-
return `// Split into focused contexts
|
|
1762
|
-
const UserContext = createContext(null);
|
|
1763
|
-
const ThemeContext = createContext('light');
|
|
1764
|
-
const NotificationContext = createContext([]);
|
|
1765
|
-
|
|
1766
|
-
// Only re-renders when theme changes
|
|
1767
|
-
function Component() {
|
|
1768
|
-
const theme = useContext(ThemeContext);
|
|
1769
|
-
return <div className={theme}>...</div>;
|
|
1770
|
-
}
|
|
1771
|
-
|
|
1772
|
-
// Provider composition
|
|
1773
|
-
function App() {
|
|
1774
|
-
return (
|
|
1775
|
-
<UserContext.Provider value={user}>
|
|
1776
|
-
<ThemeContext.Provider value={theme}>
|
|
1777
|
-
<NotificationContext.Provider value={notifications}>
|
|
1778
|
-
<MainContent />
|
|
1779
|
-
</NotificationContext.Provider>
|
|
1780
|
-
</ThemeContext.Provider>
|
|
1781
|
-
</UserContext.Provider>
|
|
1782
|
-
);
|
|
1783
|
-
}`;
|
|
1784
|
-
}
|
|
1785
|
-
function generateStateHighCode(name) {
|
|
1786
|
-
return `function ${name}() {
|
|
1787
|
-
// State managed at top level
|
|
1788
|
-
const [search, setSearch] = useState('');
|
|
1789
|
-
const [filter, setFilter] = useState('all');
|
|
1790
|
-
|
|
1791
|
-
return (
|
|
1792
|
-
<div>
|
|
1793
|
-
<Header />
|
|
1794
|
-
<Sidebar />
|
|
1795
|
-
{/* Only SearchBox needs search state */}
|
|
1796
|
-
<SearchBox value={search} onChange={setSearch} />
|
|
1797
|
-
<MainContent filter={filter} />
|
|
1798
|
-
<Footer />
|
|
1799
|
-
</div>
|
|
1800
|
-
);
|
|
1801
|
-
}`;
|
|
1802
|
-
}
|
|
1803
|
-
function generateStateColocationCode(name) {
|
|
1804
|
-
return `function ${name}() {
|
|
1805
|
-
// Only filter needed at this level
|
|
1806
|
-
const [filter, setFilter] = useState('all');
|
|
1807
|
-
|
|
1808
|
-
return (
|
|
1809
|
-
<div>
|
|
1810
|
-
<Header />
|
|
1811
|
-
<Sidebar />
|
|
1812
|
-
{/* SearchBox manages its own state */}
|
|
1813
|
-
<SearchBox />
|
|
1814
|
-
<MainContent filter={filter} />
|
|
1815
|
-
<Footer />
|
|
1816
|
-
</div>
|
|
1817
|
-
);
|
|
1818
|
-
}
|
|
1819
|
-
|
|
1820
|
-
// State colocated with component that uses it
|
|
1821
|
-
function SearchBox() {
|
|
1822
|
-
const [search, setSearch] = useState('');
|
|
1823
|
-
return <input value={search} onChange={e => setSearch(e.target.value)} />;
|
|
1824
|
-
}`;
|
|
1825
|
-
}
|
|
1826
|
-
function generateMonolithCode(name) {
|
|
1827
|
-
return `function ${name}() {
|
|
1828
|
-
const [counter, setCounter] = useState(0);
|
|
1829
|
-
const [data, setData] = useState(null);
|
|
1830
|
-
|
|
1831
|
-
// Counter updates 10x/second
|
|
1832
|
-
useEffect(() => {
|
|
1833
|
-
const id = setInterval(() => setCounter(c => c + 1), 100);
|
|
1834
|
-
return () => clearInterval(id);
|
|
1835
|
-
}, []);
|
|
1836
|
-
|
|
1837
|
-
return (
|
|
1838
|
-
<div>
|
|
1839
|
-
<span>Count: {counter}</span> {/* Updates frequently */}
|
|
1840
|
-
<ExpensiveChart data={data} /> {/* Re-renders unnecessarily! */}
|
|
1841
|
-
<DataTable data={data} /> {/* Re-renders unnecessarily! */}
|
|
1842
|
-
</div>
|
|
1843
|
-
);
|
|
1844
|
-
}`;
|
|
1845
|
-
}
|
|
1846
|
-
function generateExtractedCode(name) {
|
|
1847
|
-
return `function ${name}() {
|
|
1848
|
-
const [data, setData] = useState(null);
|
|
1849
|
-
|
|
1850
|
-
return (
|
|
1851
|
-
<div>
|
|
1852
|
-
<LiveCounter /> {/* Isolated updates */}
|
|
1853
|
-
<ExpensiveChart data={data} /> {/* Only updates when data changes */}
|
|
1854
|
-
<DataTable data={data} /> {/* Only updates when data changes */}
|
|
1855
|
-
</div>
|
|
1856
|
-
);
|
|
1857
|
-
}
|
|
1858
|
-
|
|
1859
|
-
// Extracted component with isolated state
|
|
1860
|
-
function LiveCounter() {
|
|
1861
|
-
const [counter, setCounter] = useState(0);
|
|
1862
|
-
|
|
1863
|
-
useEffect(() => {
|
|
1864
|
-
const id = setInterval(() => setCounter(c => c + 1), 100);
|
|
1865
|
-
return () => clearInterval(id);
|
|
1866
|
-
}, []);
|
|
1867
|
-
|
|
1868
|
-
return <span>Count: {counter}</span>;
|
|
1869
|
-
}`;
|
|
1870
|
-
}
|
|
1871
|
-
var FixSuggester = class extends EventEmitter {
|
|
1872
|
-
/** Active rules */
|
|
1873
|
-
rules;
|
|
1874
|
-
/** Generated suggestions cache */
|
|
1875
|
-
suggestions = /* @__PURE__ */ new Map();
|
|
1876
|
-
/** Rule configuration */
|
|
1877
|
-
ruleConfig = /* @__PURE__ */ new Map();
|
|
1878
|
-
/**
|
|
1879
|
-
* Create a new FixSuggester
|
|
1880
|
-
* @param options - Configuration options
|
|
1881
|
-
*/
|
|
1882
|
-
constructor(options = {}) {
|
|
1883
|
-
super();
|
|
1884
|
-
this.rules = [...BUILTIN_RULES];
|
|
1885
|
-
if (options.rules) {
|
|
1886
|
-
for (const [ruleId, setting] of Object.entries(options.rules)) {
|
|
1887
|
-
this.ruleConfig.set(ruleId, setting);
|
|
1888
|
-
}
|
|
1889
|
-
}
|
|
1890
|
-
}
|
|
1891
|
-
/**
|
|
1892
|
-
* Analyze a component and generate fix suggestions
|
|
1893
|
-
* @param stats - Component statistics
|
|
1894
|
-
* @returns Array of fix suggestions
|
|
1895
|
-
*/
|
|
1896
|
-
analyze(stats) {
|
|
1897
|
-
const suggestions = [];
|
|
1898
|
-
for (const rule of this.rules) {
|
|
1899
|
-
const config = this.ruleConfig.get(rule.id);
|
|
1900
|
-
if (config === "off") {
|
|
1901
|
-
continue;
|
|
1902
|
-
}
|
|
1903
|
-
if (!rule.detect(stats)) {
|
|
1904
|
-
continue;
|
|
1905
|
-
}
|
|
1906
|
-
const partialSuggestion = rule.suggest(stats);
|
|
1907
|
-
const suggestion = {
|
|
1908
|
-
componentName: stats.name,
|
|
1909
|
-
fix: rule.fixType,
|
|
1910
|
-
...partialSuggestion
|
|
1911
|
-
};
|
|
1912
|
-
if (config === "warn") {
|
|
1913
|
-
suggestion.severity = "warning";
|
|
1914
|
-
} else if (config === "error") {
|
|
1915
|
-
suggestion.severity = "critical";
|
|
1916
|
-
}
|
|
1917
|
-
suggestions.push(suggestion);
|
|
1918
|
-
this.emit("suggestion", suggestion);
|
|
1919
|
-
}
|
|
1920
|
-
suggestions.sort((a, b) => {
|
|
1921
|
-
const severityOrder = { critical: 0, warning: 1, info: 2 };
|
|
1922
|
-
const severityDiff = severityOrder[a.severity] - severityOrder[b.severity];
|
|
1923
|
-
if (severityDiff !== 0) return severityDiff;
|
|
1924
|
-
const ruleA = this.rules.find((r) => r.fixType === a.fix);
|
|
1925
|
-
const ruleB = this.rules.find((r) => r.fixType === b.fix);
|
|
1926
|
-
return (ruleA?.priority ?? 99) - (ruleB?.priority ?? 99);
|
|
1927
|
-
});
|
|
1928
|
-
this.suggestions.set(stats.name, suggestions);
|
|
1929
|
-
return suggestions;
|
|
1930
|
-
}
|
|
1931
|
-
/**
|
|
1932
|
-
* Get cached suggestions for a component
|
|
1933
|
-
* @param componentName - Component name
|
|
1934
|
-
* @returns Cached suggestions or empty array
|
|
1935
|
-
*/
|
|
1936
|
-
getSuggestions(componentName) {
|
|
1937
|
-
return this.suggestions.get(componentName) ?? [];
|
|
1938
|
-
}
|
|
1939
|
-
/**
|
|
1940
|
-
* Get all cached suggestions
|
|
1941
|
-
* @returns All suggestions
|
|
1942
|
-
*/
|
|
1943
|
-
getAllSuggestions() {
|
|
1944
|
-
return Array.from(this.suggestions.values()).flat();
|
|
1945
|
-
}
|
|
1946
|
-
/**
|
|
1947
|
-
* Get suggestions by severity
|
|
1948
|
-
* @param severity - Severity level
|
|
1949
|
-
* @returns Matching suggestions
|
|
1950
|
-
*/
|
|
1951
|
-
getSuggestionsBySeverity(severity) {
|
|
1952
|
-
return this.getAllSuggestions().filter((s) => s.severity === severity);
|
|
1953
|
-
}
|
|
1954
|
-
/**
|
|
1955
|
-
* Get suggestions by fix type
|
|
1956
|
-
* @param fixType - Fix type
|
|
1957
|
-
* @returns Matching suggestions
|
|
1958
|
-
*/
|
|
1959
|
-
getSuggestionsByType(fixType) {
|
|
1960
|
-
return this.getAllSuggestions().filter((s) => s.fix === fixType);
|
|
1961
|
-
}
|
|
1962
|
-
/**
|
|
1963
|
-
* Clear cached suggestions
|
|
1964
|
-
* @param componentName - Optional component to clear (clears all if not specified)
|
|
1965
|
-
*/
|
|
1966
|
-
clearSuggestions(componentName) {
|
|
1967
|
-
if (componentName) {
|
|
1968
|
-
this.suggestions.delete(componentName);
|
|
1969
|
-
} else {
|
|
1970
|
-
this.suggestions.clear();
|
|
1971
|
-
}
|
|
1972
|
-
}
|
|
1973
|
-
/**
|
|
1974
|
-
* Configure a rule
|
|
1975
|
-
* @param ruleId - Rule identifier
|
|
1976
|
-
* @param setting - Rule setting
|
|
1977
|
-
*/
|
|
1978
|
-
configureRule(ruleId, setting) {
|
|
1979
|
-
this.ruleConfig.set(ruleId, setting);
|
|
1980
|
-
}
|
|
1981
|
-
/**
|
|
1982
|
-
* Get available rule IDs
|
|
1983
|
-
* @returns Array of rule IDs
|
|
1984
|
-
*/
|
|
1985
|
-
getRuleIds() {
|
|
1986
|
-
return this.rules.map((r) => r.id);
|
|
1987
|
-
}
|
|
1988
|
-
/**
|
|
1989
|
-
* Get rule information
|
|
1990
|
-
* @param ruleId - Rule identifier
|
|
1991
|
-
* @returns Rule info or undefined
|
|
1992
|
-
*/
|
|
1993
|
-
getRule(ruleId) {
|
|
1994
|
-
const rule = this.rules.find((r) => r.id === ruleId);
|
|
1995
|
-
if (!rule) return void 0;
|
|
1996
|
-
return {
|
|
1997
|
-
id: rule.id,
|
|
1998
|
-
name: rule.name,
|
|
1999
|
-
description: rule.description,
|
|
2000
|
-
fixType: rule.fixType
|
|
2001
|
-
};
|
|
2002
|
-
}
|
|
2003
|
-
};
|
|
2004
|
-
|
|
2005
|
-
// src/core/scanner.ts
|
|
2006
|
-
var DEFAULT_CONFIG = {
|
|
2007
|
-
trackUnnecessary: true,
|
|
2008
|
-
fpsThreshold: 30,
|
|
2009
|
-
highlightRenders: true,
|
|
2010
|
-
animationSpeed: "fast"
|
|
2011
|
-
};
|
|
2012
|
-
var DEFAULT_THRESHOLDS2 = {
|
|
2013
|
-
critical: 50,
|
|
2014
|
-
warning: 20,
|
|
2015
|
-
fps: 30
|
|
2016
|
-
};
|
|
2017
|
-
var Scanner = class extends EventEmitter {
|
|
2018
|
-
/** Statistics collector */
|
|
2019
|
-
stats;
|
|
2020
|
-
/** Chain analyzer */
|
|
2021
|
-
chainAnalyzer;
|
|
2022
|
-
/** Fix suggester */
|
|
2023
|
-
fixSuggester;
|
|
2024
|
-
/** Scanner configuration */
|
|
2025
|
-
config;
|
|
2026
|
-
/** Whether scanner is currently running */
|
|
2027
|
-
running = false;
|
|
2028
|
-
/** Last recorded FPS */
|
|
2029
|
-
lastFps = 60;
|
|
2030
|
-
/** FPS tracking */
|
|
2031
|
-
frameCount = 0;
|
|
2032
|
-
lastFpsUpdate = 0;
|
|
2033
|
-
fpsInterval = null;
|
|
2034
|
-
/** Batch processing */
|
|
2035
|
-
renderBatch = [];
|
|
2036
|
-
batchTimeout = null;
|
|
2037
|
-
batchSize = 10;
|
|
2038
|
-
batchDelay = 100;
|
|
2039
|
-
/**
|
|
2040
|
-
* Create a new Scanner instance
|
|
2041
|
-
* @param options - Configuration options
|
|
2042
|
-
*/
|
|
2043
|
-
constructor(options = {}) {
|
|
2044
|
-
super();
|
|
2045
|
-
this.config = { ...DEFAULT_CONFIG, ...options.config };
|
|
2046
|
-
const thresholds = { ...DEFAULT_THRESHOLDS2, ...options.thresholds };
|
|
2047
|
-
this.stats = new StatsCollector(thresholds);
|
|
2048
|
-
this.chainAnalyzer = new ChainAnalyzer();
|
|
2049
|
-
this.fixSuggester = new FixSuggester();
|
|
2050
|
-
this.setupEventForwarding();
|
|
2051
|
-
}
|
|
2052
|
-
/**
|
|
2053
|
-
* Set up event forwarding from sub-modules
|
|
2054
|
-
*/
|
|
2055
|
-
setupEventForwarding() {
|
|
2056
|
-
this.stats.on("update", (stats) => {
|
|
2057
|
-
this.emit("stats", stats);
|
|
2058
|
-
});
|
|
2059
|
-
this.stats.on("severityChange", (change) => {
|
|
2060
|
-
this.emit("severityChange", change);
|
|
2061
|
-
const stats = this.stats.getComponentStats(change.component);
|
|
2062
|
-
if (stats && (change.to === "critical" || change.to === "warning")) {
|
|
2063
|
-
const suggestions = this.fixSuggester.analyze(stats);
|
|
2064
|
-
for (const suggestion of suggestions) {
|
|
2065
|
-
this.emit("fix", suggestion);
|
|
2066
|
-
}
|
|
2067
|
-
}
|
|
2068
|
-
});
|
|
2069
|
-
this.chainAnalyzer.on("chain", (chain) => {
|
|
2070
|
-
this.emit("chain", chain);
|
|
2071
|
-
for (const componentName of chain.chain) {
|
|
2072
|
-
this.stats.setComponentChain(componentName, chain.chain);
|
|
2073
|
-
}
|
|
2074
|
-
});
|
|
2075
|
-
}
|
|
2076
|
-
/**
|
|
2077
|
-
* Start the scanner
|
|
2078
|
-
*/
|
|
2079
|
-
start() {
|
|
2080
|
-
if (this.running) return;
|
|
2081
|
-
this.running = true;
|
|
2082
|
-
this.lastFpsUpdate = Date.now();
|
|
2083
|
-
this.frameCount = 0;
|
|
2084
|
-
this.startFpsMonitoring();
|
|
2085
|
-
this.emit("start", void 0);
|
|
2086
|
-
}
|
|
2087
|
-
/**
|
|
2088
|
-
* Stop the scanner
|
|
2089
|
-
*/
|
|
2090
|
-
stop() {
|
|
2091
|
-
if (!this.running) return;
|
|
2092
|
-
this.running = false;
|
|
2093
|
-
this.stopFpsMonitoring();
|
|
2094
|
-
this.flushBatch();
|
|
2095
|
-
this.emit("stop", void 0);
|
|
2096
|
-
}
|
|
2097
|
-
/**
|
|
2098
|
-
* Reset the scanner, clearing all data
|
|
2099
|
-
*/
|
|
2100
|
-
reset() {
|
|
2101
|
-
this.stop();
|
|
2102
|
-
this.stats.reset();
|
|
2103
|
-
this.chainAnalyzer.reset();
|
|
2104
|
-
this.fixSuggester.clearSuggestions();
|
|
2105
|
-
this.renderBatch = [];
|
|
2106
|
-
this.emit("reset", void 0);
|
|
2107
|
-
}
|
|
2108
|
-
/**
|
|
2109
|
-
* Process a render event
|
|
2110
|
-
* @param render - Render information
|
|
2111
|
-
* @param parent - Optional parent component name
|
|
2112
|
-
*/
|
|
2113
|
-
addRender(render, parent) {
|
|
2114
|
-
if (!this.running) return;
|
|
2115
|
-
this.renderBatch.push(render);
|
|
2116
|
-
this.stats.addRender(render);
|
|
2117
|
-
this.chainAnalyzer.addRender(render, parent);
|
|
2118
|
-
this.emit("render", render);
|
|
2119
|
-
this.frameCount++;
|
|
2120
|
-
this.scheduleBatchProcessing();
|
|
2121
|
-
}
|
|
2122
|
-
/**
|
|
2123
|
-
* Record a frame for FPS calculation
|
|
2124
|
-
*/
|
|
2125
|
-
recordFrame() {
|
|
2126
|
-
this.frameCount++;
|
|
2127
|
-
}
|
|
2128
|
-
/**
|
|
2129
|
-
* Schedule batch processing
|
|
2130
|
-
*/
|
|
2131
|
-
scheduleBatchProcessing() {
|
|
2132
|
-
if (this.batchTimeout) return;
|
|
2133
|
-
if (this.renderBatch.length >= this.batchSize) {
|
|
2134
|
-
this.flushBatch();
|
|
2135
|
-
} else {
|
|
2136
|
-
this.batchTimeout = setTimeout(() => {
|
|
2137
|
-
this.flushBatch();
|
|
2138
|
-
}, this.batchDelay);
|
|
2139
|
-
}
|
|
2140
|
-
}
|
|
2141
|
-
/**
|
|
2142
|
-
* Flush the render batch
|
|
2143
|
-
*/
|
|
2144
|
-
flushBatch() {
|
|
2145
|
-
if (this.batchTimeout) {
|
|
2146
|
-
clearTimeout(this.batchTimeout);
|
|
2147
|
-
this.batchTimeout = null;
|
|
2148
|
-
}
|
|
2149
|
-
if (this.renderBatch.length === 0) return;
|
|
2150
|
-
this.processBatch(this.renderBatch);
|
|
2151
|
-
this.renderBatch = [];
|
|
2152
|
-
}
|
|
2153
|
-
/**
|
|
2154
|
-
* Process a batch of renders for patterns
|
|
2155
|
-
* @param batch - Render batch
|
|
2156
|
-
*/
|
|
2157
|
-
processBatch(batch) {
|
|
2158
|
-
const byComponent = /* @__PURE__ */ new Map();
|
|
2159
|
-
for (const render of batch) {
|
|
2160
|
-
const existing = byComponent.get(render.componentName) ?? [];
|
|
2161
|
-
existing.push(render);
|
|
2162
|
-
byComponent.set(render.componentName, existing);
|
|
2163
|
-
}
|
|
2164
|
-
for (const [componentName, renders] of byComponent) {
|
|
2165
|
-
if (renders.length >= 3) {
|
|
2166
|
-
const stats = this.stats.getComponentStats(componentName);
|
|
2167
|
-
if (stats) {
|
|
2168
|
-
const suggestions = this.fixSuggester.analyze(stats);
|
|
2169
|
-
for (const suggestion of suggestions) {
|
|
2170
|
-
this.emit("fix", suggestion);
|
|
2171
|
-
}
|
|
2172
|
-
}
|
|
2173
|
-
}
|
|
2174
|
-
}
|
|
2175
|
-
}
|
|
2176
|
-
/**
|
|
2177
|
-
* Start FPS monitoring
|
|
2178
|
-
*/
|
|
2179
|
-
startFpsMonitoring() {
|
|
2180
|
-
this.fpsInterval = setInterval(() => {
|
|
2181
|
-
const now = Date.now();
|
|
2182
|
-
const elapsed = now - this.lastFpsUpdate;
|
|
2183
|
-
if (elapsed > 0) {
|
|
2184
|
-
this.lastFps = Math.round(this.frameCount * 1e3 / elapsed);
|
|
2185
|
-
this.stats.addFpsSample(this.lastFps);
|
|
2186
|
-
if (this.lastFps < this.config.fpsThreshold) {
|
|
2187
|
-
this.emit("fps-drop", this.lastFps);
|
|
2188
|
-
}
|
|
2189
|
-
}
|
|
2190
|
-
this.frameCount = 0;
|
|
2191
|
-
this.lastFpsUpdate = now;
|
|
2192
|
-
}, 1e3);
|
|
2193
|
-
}
|
|
2194
|
-
/**
|
|
2195
|
-
* Stop FPS monitoring
|
|
2196
|
-
*/
|
|
2197
|
-
stopFpsMonitoring() {
|
|
2198
|
-
if (this.fpsInterval) {
|
|
2199
|
-
clearInterval(this.fpsInterval);
|
|
2200
|
-
this.fpsInterval = null;
|
|
2201
|
-
}
|
|
2202
|
-
}
|
|
2203
|
-
/**
|
|
2204
|
-
* Get current FPS
|
|
2205
|
-
* @returns Current FPS value
|
|
2206
|
-
*/
|
|
2207
|
-
getFps() {
|
|
2208
|
-
return this.lastFps;
|
|
2209
|
-
}
|
|
2210
|
-
/**
|
|
2211
|
-
* Check if scanner is running
|
|
2212
|
-
* @returns true if running
|
|
2213
|
-
*/
|
|
2214
|
-
isRunning() {
|
|
2215
|
-
return this.running;
|
|
2216
|
-
}
|
|
2217
|
-
/**
|
|
2218
|
-
* Get scanner configuration
|
|
2219
|
-
* @returns Current configuration
|
|
2220
|
-
*/
|
|
2221
|
-
getConfig() {
|
|
2222
|
-
return { ...this.config };
|
|
2223
|
-
}
|
|
2224
|
-
/**
|
|
2225
|
-
* Update scanner configuration
|
|
2226
|
-
* @param config - Partial configuration to update
|
|
2227
|
-
*/
|
|
2228
|
-
configure(config) {
|
|
2229
|
-
this.config = { ...this.config, ...config };
|
|
2230
|
-
}
|
|
2231
|
-
/**
|
|
2232
|
-
* Update threshold configuration
|
|
2233
|
-
* @param thresholds - New thresholds
|
|
2234
|
-
*/
|
|
2235
|
-
setThresholds(thresholds) {
|
|
2236
|
-
this.stats.setThresholds(thresholds);
|
|
2237
|
-
}
|
|
2238
|
-
/**
|
|
2239
|
-
* Get current thresholds
|
|
2240
|
-
* @returns Current threshold configuration
|
|
2241
|
-
*/
|
|
2242
|
-
getThresholds() {
|
|
2243
|
-
return this.stats.getThresholds();
|
|
2244
|
-
}
|
|
2245
|
-
/**
|
|
2246
|
-
* Get component statistics
|
|
2247
|
-
* @param name - Component name (optional, returns all if not specified)
|
|
2248
|
-
* @returns Component stats
|
|
2249
|
-
*/
|
|
2250
|
-
getStats(name) {
|
|
2251
|
-
if (name) {
|
|
2252
|
-
return this.stats.getComponentStats(name);
|
|
2253
|
-
}
|
|
2254
|
-
return this.stats.getAllStats();
|
|
2255
|
-
}
|
|
2256
|
-
/**
|
|
2257
|
-
* Get a snapshot of all stats sorted by severity
|
|
2258
|
-
* @returns Sorted stats array
|
|
2259
|
-
*/
|
|
2260
|
-
getSnapshot() {
|
|
2261
|
-
return this.stats.getSnapshot();
|
|
2262
|
-
}
|
|
2263
|
-
/**
|
|
2264
|
-
* Get session summary
|
|
2265
|
-
* @returns Session summary statistics
|
|
2266
|
-
*/
|
|
2267
|
-
getSummary() {
|
|
2268
|
-
return this.stats.getSummary();
|
|
2269
|
-
}
|
|
2270
|
-
/**
|
|
2271
|
-
* Get top problematic components
|
|
2272
|
-
* @param limit - Maximum number to return
|
|
2273
|
-
* @returns Top problems
|
|
2274
|
-
*/
|
|
2275
|
-
getTopProblems(limit = 10) {
|
|
2276
|
-
return this.stats.getTopProblems(limit);
|
|
2277
|
-
}
|
|
2278
|
-
/**
|
|
2279
|
-
* Get all fix suggestions
|
|
2280
|
-
* @returns All suggestions
|
|
2281
|
-
*/
|
|
2282
|
-
getSuggestions() {
|
|
2283
|
-
return this.fixSuggester.getAllSuggestions();
|
|
2284
|
-
}
|
|
2285
|
-
/**
|
|
2286
|
-
* Get suggestions for a specific component
|
|
2287
|
-
* @param componentName - Component name
|
|
2288
|
-
* @returns Component suggestions
|
|
2289
|
-
*/
|
|
2290
|
-
getComponentSuggestions(componentName) {
|
|
2291
|
-
return this.fixSuggester.getSuggestions(componentName);
|
|
2292
|
-
}
|
|
2293
|
-
/**
|
|
2294
|
-
* Set parent relationship for a component
|
|
2295
|
-
* @param child - Child component name
|
|
2296
|
-
* @param parent - Parent component name
|
|
2297
|
-
*/
|
|
2298
|
-
setParent(child, parent) {
|
|
2299
|
-
this.chainAnalyzer.setParent(child, parent);
|
|
2300
|
-
this.stats.setComponentParent(child, parent);
|
|
2301
|
-
}
|
|
2302
|
-
/**
|
|
2303
|
-
* Get the render chain for a component
|
|
2304
|
-
* @param componentName - Component name
|
|
2305
|
-
* @returns Render chain
|
|
2306
|
-
*/
|
|
2307
|
-
getComponentChain(componentName) {
|
|
2308
|
-
return this.chainAnalyzer.getComponentChain(componentName);
|
|
2309
|
-
}
|
|
2310
|
-
/**
|
|
2311
|
-
* Get session duration
|
|
2312
|
-
* @returns Duration in milliseconds
|
|
2313
|
-
*/
|
|
2314
|
-
getSessionDuration() {
|
|
2315
|
-
return this.stats.getSessionDuration();
|
|
2316
|
-
}
|
|
2317
|
-
/**
|
|
2318
|
-
* Export scanner data for reporting
|
|
2319
|
-
* @returns Exportable data object
|
|
2320
|
-
*/
|
|
2321
|
-
export() {
|
|
2322
|
-
return {
|
|
2323
|
-
stats: this.stats.export(),
|
|
2324
|
-
suggestions: this.getSuggestions(),
|
|
2325
|
-
config: this.getConfig()
|
|
2326
|
-
};
|
|
2327
|
-
}
|
|
2328
|
-
/**
|
|
2329
|
-
* Analyze a specific component and generate suggestions
|
|
2330
|
-
* @param componentName - Component name
|
|
2331
|
-
* @returns Fix suggestions for the component
|
|
2332
|
-
*/
|
|
2333
|
-
analyzeComponent(componentName) {
|
|
2334
|
-
const stats = this.stats.getComponentStats(componentName);
|
|
2335
|
-
if (!stats) return [];
|
|
2336
|
-
return this.fixSuggester.analyze(stats);
|
|
2337
|
-
}
|
|
2338
|
-
/**
|
|
2339
|
-
* Analyze all components and generate suggestions
|
|
2340
|
-
* @returns All fix suggestions
|
|
2341
|
-
*/
|
|
2342
|
-
analyzeAll() {
|
|
2343
|
-
const allStats = this.stats.getAllStats();
|
|
2344
|
-
const allSuggestions = [];
|
|
2345
|
-
for (const stats of allStats) {
|
|
2346
|
-
const suggestions = this.fixSuggester.analyze(stats);
|
|
2347
|
-
allSuggestions.push(...suggestions);
|
|
2348
|
-
}
|
|
2349
|
-
return allSuggestions;
|
|
21
|
+
ErrorCode2["CONFIG_NOT_FOUND"] = "CONFIG_NOT_FOUND";
|
|
22
|
+
ErrorCode2["CONNECTION_FAILED"] = "CONNECTION_FAILED";
|
|
23
|
+
ErrorCode2["REACT_NOT_FOUND"] = "REACT_NOT_FOUND";
|
|
24
|
+
ErrorCode2["BROWSER_LAUNCH_FAILED"] = "BROWSER_LAUNCH_FAILED";
|
|
25
|
+
ErrorCode2["WEBSOCKET_ERROR"] = "WEBSOCKET_ERROR";
|
|
26
|
+
ErrorCode2["REPORT_WRITE_FAILED"] = "REPORT_WRITE_FAILED";
|
|
27
|
+
ErrorCode2["INVALID_URL"] = "INVALID_URL";
|
|
28
|
+
ErrorCode2["TIMEOUT"] = "TIMEOUT";
|
|
29
|
+
ErrorCode2["UNKNOWN"] = "UNKNOWN";
|
|
30
|
+
return ErrorCode2;
|
|
31
|
+
})(ErrorCode || {});
|
|
32
|
+
var ReactCheckError = class extends Error {
|
|
33
|
+
/** Error code */
|
|
34
|
+
code;
|
|
35
|
+
/** Additional error details */
|
|
36
|
+
details;
|
|
37
|
+
constructor(code, message, details) {
|
|
38
|
+
super(message);
|
|
39
|
+
this.name = "ReactCheckError";
|
|
40
|
+
this.code = code;
|
|
41
|
+
this.details = details;
|
|
2350
42
|
}
|
|
2351
43
|
};
|
|
2352
44
|
|
|
@@ -2450,6 +142,24 @@ function isUserComponent(fiber) {
|
|
|
2450
142
|
const { tag } = fiber;
|
|
2451
143
|
return tag === FiberTag.FunctionComponent || tag === FiberTag.ClassComponent || tag === FiberTag.MemoComponent || tag === FiberTag.SimpleMemoComponent || tag === FiberTag.ForwardRef || tag === FiberTag.LazyComponent;
|
|
2452
144
|
}
|
|
145
|
+
var PERFORMED_WORK_FLAG = 1;
|
|
146
|
+
function didFiberRender(fiber) {
|
|
147
|
+
const prev = fiber.alternate;
|
|
148
|
+
if (!prev) return true;
|
|
149
|
+
switch (fiber.tag) {
|
|
150
|
+
case FiberTag.FunctionComponent:
|
|
151
|
+
case FiberTag.ClassComponent:
|
|
152
|
+
case FiberTag.ContextConsumer:
|
|
153
|
+
case FiberTag.ForwardRef:
|
|
154
|
+
case FiberTag.MemoComponent:
|
|
155
|
+
case FiberTag.SimpleMemoComponent: {
|
|
156
|
+
const flags = fiber.flags ?? fiber.effectTag ?? 0;
|
|
157
|
+
return (flags & PERFORMED_WORK_FLAG) === PERFORMED_WORK_FLAG;
|
|
158
|
+
}
|
|
159
|
+
default:
|
|
160
|
+
return prev.memoizedProps !== fiber.memoizedProps || prev.memoizedState !== fiber.memoizedState;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
2453
163
|
function isHostComponent(fiber) {
|
|
2454
164
|
return fiber.tag === FiberTag.HostComponent;
|
|
2455
165
|
}
|
|
@@ -2534,7 +244,7 @@ function createRenderInfo(fiber, phase, prevProps, prevState) {
|
|
|
2534
244
|
const renderTime = fiber.actualDuration ?? 0;
|
|
2535
245
|
const changedProps = prevProps ? getChangedProps(prevProps, fiber.memoizedProps) : void 0;
|
|
2536
246
|
const propsChanged = changedProps && changedProps.length > 0;
|
|
2537
|
-
const stateChanged = prevState !== fiber.memoizedState;
|
|
247
|
+
const stateChanged = phase === "update" && prevState !== fiber.memoizedState;
|
|
2538
248
|
const necessary = phase === "mount" || propsChanged || stateChanged;
|
|
2539
249
|
const result = {
|
|
2540
250
|
componentName,
|
|
@@ -2766,6 +476,9 @@ function formatRenderTime(ms) {
|
|
|
2766
476
|
}
|
|
2767
477
|
return `${(ms / 1e3).toFixed(2)}s`;
|
|
2768
478
|
}
|
|
479
|
+
function formatDate(date = /* @__PURE__ */ new Date()) {
|
|
480
|
+
return date.toISOString();
|
|
481
|
+
}
|
|
2769
482
|
function pad(str, length, char = " ", position = "right") {
|
|
2770
483
|
if (str.length >= length) {
|
|
2771
484
|
return str;
|
|
@@ -2789,6 +502,11 @@ function escapeHtml(str) {
|
|
|
2789
502
|
};
|
|
2790
503
|
return str.replace(/[&<>"']/g, (char) => escapeMap[char] ?? char);
|
|
2791
504
|
}
|
|
505
|
+
function generateId(prefix = "") {
|
|
506
|
+
const timestamp = Date.now().toString(36);
|
|
507
|
+
const random = Math.random().toString(36).slice(2, 8);
|
|
508
|
+
return prefix ? `${prefix}_${timestamp}${random}` : `${timestamp}${random}`;
|
|
509
|
+
}
|
|
2792
510
|
|
|
2793
511
|
// src/report/markdown.ts
|
|
2794
512
|
function generateMarkdownReport(report) {
|
|
@@ -3500,71 +1218,6 @@ function renderFooter(report) {
|
|
|
3500
1218
|
</footer>
|
|
3501
1219
|
`;
|
|
3502
1220
|
}
|
|
3503
|
-
async function exists(path) {
|
|
3504
|
-
try {
|
|
3505
|
-
await access(path, constants.F_OK);
|
|
3506
|
-
return true;
|
|
3507
|
-
} catch {
|
|
3508
|
-
return false;
|
|
3509
|
-
}
|
|
3510
|
-
}
|
|
3511
|
-
async function readTextFile(path, encoding = "utf-8") {
|
|
3512
|
-
return readFile(path, { encoding });
|
|
3513
|
-
}
|
|
3514
|
-
async function writeTextFile(path, content, encoding = "utf-8") {
|
|
3515
|
-
const dir = dirname(path);
|
|
3516
|
-
await ensureDir(dir);
|
|
3517
|
-
await writeFile(path, content, { encoding });
|
|
3518
|
-
}
|
|
3519
|
-
async function readJsonFile(path) {
|
|
3520
|
-
const content = await readTextFile(path);
|
|
3521
|
-
return JSON.parse(content);
|
|
3522
|
-
}
|
|
3523
|
-
async function writeJsonFile(path, data, pretty = true) {
|
|
3524
|
-
const content = pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);
|
|
3525
|
-
await writeTextFile(path, content);
|
|
3526
|
-
}
|
|
3527
|
-
async function ensureDir(path) {
|
|
3528
|
-
if (!await exists(path)) {
|
|
3529
|
-
await mkdir(path, { recursive: true });
|
|
3530
|
-
}
|
|
3531
|
-
}
|
|
3532
|
-
function getExtension(path) {
|
|
3533
|
-
return extname(path).slice(1);
|
|
3534
|
-
}
|
|
3535
|
-
function getBaseName(path) {
|
|
3536
|
-
const ext = extname(path);
|
|
3537
|
-
return basename(path, ext);
|
|
3538
|
-
}
|
|
3539
|
-
function resolvePath(base, ...paths) {
|
|
3540
|
-
return resolve(base, ...paths);
|
|
3541
|
-
}
|
|
3542
|
-
function joinPath(...paths) {
|
|
3543
|
-
return join(...paths);
|
|
3544
|
-
}
|
|
3545
|
-
function getDirName(path) {
|
|
3546
|
-
return dirname(path);
|
|
3547
|
-
}
|
|
3548
|
-
async function findUp(filename, startDir = process.cwd()) {
|
|
3549
|
-
let currentDir = resolve(startDir);
|
|
3550
|
-
const root = dirname(currentDir);
|
|
3551
|
-
while (currentDir !== root) {
|
|
3552
|
-
const filePath = join(currentDir, filename);
|
|
3553
|
-
if (await exists(filePath)) {
|
|
3554
|
-
return filePath;
|
|
3555
|
-
}
|
|
3556
|
-
const parentDir = dirname(currentDir);
|
|
3557
|
-
if (parentDir === currentDir) {
|
|
3558
|
-
break;
|
|
3559
|
-
}
|
|
3560
|
-
currentDir = parentDir;
|
|
3561
|
-
}
|
|
3562
|
-
const rootFilePath = join(currentDir, filename);
|
|
3563
|
-
if (await exists(rootFilePath)) {
|
|
3564
|
-
return rootFilePath;
|
|
3565
|
-
}
|
|
3566
|
-
return null;
|
|
3567
|
-
}
|
|
3568
1221
|
|
|
3569
1222
|
// src/report/index.ts
|
|
3570
1223
|
function generateReport(report, format) {
|
|
@@ -3576,7 +1229,7 @@ function generateReport(report, format) {
|
|
|
3576
1229
|
case "md":
|
|
3577
1230
|
return generateMarkdownReport(report);
|
|
3578
1231
|
default:
|
|
3579
|
-
throw new Error(`Unknown report format: ${format}`);
|
|
1232
|
+
throw new Error(`Unknown report format: ${String(format)}`);
|
|
3580
1233
|
}
|
|
3581
1234
|
}
|
|
3582
1235
|
async function saveReport(report, format, outputDir, filename) {
|
|
@@ -3670,289 +1323,417 @@ var ReportGenerator = class {
|
|
|
3670
1323
|
}
|
|
3671
1324
|
};
|
|
3672
1325
|
|
|
3673
|
-
// src/
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
name: "next",
|
|
3678
|
-
dependencies: ["next"],
|
|
3679
|
-
features: [
|
|
3680
|
-
{
|
|
3681
|
-
name: "app-router",
|
|
3682
|
-
detect: async (_, dir) => exists(joinPath(dir, "app"))
|
|
3683
|
-
},
|
|
3684
|
-
{
|
|
3685
|
-
name: "pages-router",
|
|
3686
|
-
detect: async (_, dir) => exists(joinPath(dir, "pages"))
|
|
3687
|
-
},
|
|
3688
|
-
{
|
|
3689
|
-
name: "rsc",
|
|
3690
|
-
deps: ["next"],
|
|
3691
|
-
detect: async (pkg) => {
|
|
3692
|
-
const version = pkg.dependencies?.["next"] ?? "";
|
|
3693
|
-
const major = parseInt(version.replace(/[^0-9]/g, "").slice(0, 2), 10);
|
|
3694
|
-
return major >= 13;
|
|
3695
|
-
}
|
|
3696
|
-
},
|
|
3697
|
-
{
|
|
3698
|
-
name: "middleware",
|
|
3699
|
-
detect: async (_, dir) => exists(joinPath(dir, "middleware.ts")) || exists(joinPath(dir, "middleware.js"))
|
|
3700
|
-
}
|
|
3701
|
-
],
|
|
3702
|
-
tips: [
|
|
3703
|
-
'Use "use client" directive only for interactive components',
|
|
3704
|
-
"Keep server components as the default for better performance",
|
|
3705
|
-
"Consider using Server Actions for mutations",
|
|
3706
|
-
"Use next/dynamic for code splitting heavy components",
|
|
3707
|
-
"Avoid passing serializable props through server/client boundary"
|
|
3708
|
-
]
|
|
3709
|
-
},
|
|
3710
|
-
// Remix
|
|
3711
|
-
{
|
|
3712
|
-
name: "remix",
|
|
3713
|
-
dependencies: ["@remix-run/react", "@remix-run/node", "@remix-run/cloudflare"],
|
|
3714
|
-
features: [
|
|
3715
|
-
{
|
|
3716
|
-
name: "v2-routes",
|
|
3717
|
-
detect: async (_, dir) => exists(joinPath(dir, "app", "routes"))
|
|
3718
|
-
},
|
|
3719
|
-
{
|
|
3720
|
-
name: "defer",
|
|
3721
|
-
deps: ["@remix-run/react"],
|
|
3722
|
-
detect: async (pkg) => {
|
|
3723
|
-
const version = pkg.dependencies?.["@remix-run/react"] ?? "";
|
|
3724
|
-
return version.includes("1.") || version.includes("2.");
|
|
3725
|
-
}
|
|
3726
|
-
}
|
|
3727
|
-
],
|
|
3728
|
-
tips: [
|
|
3729
|
-
"Use loader data efficiently to minimize client state",
|
|
3730
|
-
"Prefer fetcher over useNavigate for non-navigation mutations",
|
|
3731
|
-
"Use defer for streaming slow data",
|
|
3732
|
-
"Consider using useFetcher.load for background data fetching",
|
|
3733
|
-
"Avoid useEffect for data fetching, use loaders instead"
|
|
3734
|
-
]
|
|
3735
|
-
},
|
|
3736
|
-
// Vite
|
|
3737
|
-
{
|
|
3738
|
-
name: "vite",
|
|
3739
|
-
dependencies: [],
|
|
3740
|
-
devDependencies: ["vite"],
|
|
3741
|
-
features: [
|
|
3742
|
-
{
|
|
3743
|
-
name: "react-plugin",
|
|
3744
|
-
deps: ["@vitejs/plugin-react", "@vitejs/plugin-react-swc"]
|
|
3745
|
-
},
|
|
3746
|
-
{
|
|
3747
|
-
name: "ssr",
|
|
3748
|
-
detect: async (_, dir) => exists(joinPath(dir, "vite.config.ts")) || exists(joinPath(dir, "vite.config.js"))
|
|
3749
|
-
}
|
|
3750
|
-
],
|
|
3751
|
-
tips: [
|
|
3752
|
-
"Use React.lazy with Suspense for code splitting",
|
|
3753
|
-
"Configure build.rollupOptions.output.manualChunks for optimal chunking",
|
|
3754
|
-
"Enable build.sourcemap only in development",
|
|
3755
|
-
"Use @vitejs/plugin-react-swc for faster builds",
|
|
3756
|
-
"Consider using vite-plugin-pwa for PWA support"
|
|
3757
|
-
]
|
|
3758
|
-
},
|
|
3759
|
-
// Create React App
|
|
3760
|
-
{
|
|
3761
|
-
name: "cra",
|
|
3762
|
-
dependencies: ["react-scripts"],
|
|
3763
|
-
features: [
|
|
3764
|
-
{
|
|
3765
|
-
name: "typescript",
|
|
3766
|
-
deps: ["typescript"]
|
|
3767
|
-
},
|
|
3768
|
-
{
|
|
3769
|
-
name: "testing-library",
|
|
3770
|
-
deps: ["@testing-library/react"]
|
|
3771
|
-
}
|
|
3772
|
-
],
|
|
3773
|
-
tips: [
|
|
3774
|
-
"Consider migrating to Vite for faster development builds",
|
|
3775
|
-
"Use React.lazy for code splitting",
|
|
3776
|
-
'Run "npm run build -- --stats" to analyze bundle size',
|
|
3777
|
-
"Use REACT_APP_ prefix for environment variables",
|
|
3778
|
-
"Consider ejecting only if absolutely necessary"
|
|
3779
|
-
]
|
|
3780
|
-
},
|
|
3781
|
-
// Gatsby
|
|
3782
|
-
{
|
|
3783
|
-
name: "gatsby",
|
|
3784
|
-
dependencies: ["gatsby"],
|
|
3785
|
-
features: [
|
|
3786
|
-
{
|
|
3787
|
-
name: "v5",
|
|
3788
|
-
deps: ["gatsby"],
|
|
3789
|
-
detect: async (pkg) => {
|
|
3790
|
-
const version = pkg.dependencies?.["gatsby"] ?? "";
|
|
3791
|
-
return version.includes("5.") || version.includes("^5");
|
|
3792
|
-
}
|
|
3793
|
-
},
|
|
3794
|
-
{
|
|
3795
|
-
name: "image",
|
|
3796
|
-
deps: ["gatsby-plugin-image"]
|
|
3797
|
-
},
|
|
3798
|
-
{
|
|
3799
|
-
name: "graphql",
|
|
3800
|
-
deps: ["gatsby"]
|
|
3801
|
-
}
|
|
3802
|
-
],
|
|
3803
|
-
tips: [
|
|
3804
|
-
"Use gatsby-plugin-image for optimized images",
|
|
3805
|
-
"Prefer StaticQuery over page queries for reusable components",
|
|
3806
|
-
"Use incremental builds for faster development",
|
|
3807
|
-
"Configure proper caching headers for static assets",
|
|
3808
|
-
"Consider using DSG (Deferred Static Generation) for large sites"
|
|
3809
|
-
]
|
|
3810
|
-
}
|
|
3811
|
-
];
|
|
3812
|
-
async function detectFramework(packageJsonPath) {
|
|
3813
|
-
let pkgPath = packageJsonPath;
|
|
3814
|
-
if (!pkgPath) {
|
|
3815
|
-
pkgPath = await findUp("package.json") ?? void 0;
|
|
3816
|
-
}
|
|
3817
|
-
if (!pkgPath || !await exists(pkgPath)) {
|
|
3818
|
-
return null;
|
|
1326
|
+
// src/utils/colors.ts
|
|
1327
|
+
function checkColorSupport() {
|
|
1328
|
+
if (process.env["FORCE_COLOR"] !== void 0) {
|
|
1329
|
+
return process.env["FORCE_COLOR"] !== "0";
|
|
3819
1330
|
}
|
|
3820
|
-
|
|
3821
|
-
|
|
3822
|
-
packageJson = await readJsonFile(pkgPath);
|
|
3823
|
-
} catch {
|
|
3824
|
-
return null;
|
|
1331
|
+
if (process.env["NO_COLOR"] !== void 0) {
|
|
1332
|
+
return false;
|
|
3825
1333
|
}
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
3833
|
-
|
|
3834
|
-
|
|
3835
|
-
|
|
3836
|
-
|
|
3837
|
-
tips: [
|
|
3838
|
-
"Consider using React.memo for frequently re-rendering components",
|
|
3839
|
-
"Use useCallback for event handlers passed to child components",
|
|
3840
|
-
"Use useMemo for expensive computations",
|
|
3841
|
-
"Avoid inline object/array creation in render"
|
|
3842
|
-
]
|
|
3843
|
-
};
|
|
1334
|
+
if (!process.stdout.isTTY) {
|
|
1335
|
+
return false;
|
|
1336
|
+
}
|
|
1337
|
+
if (process.env["TERM"] === "dumb") {
|
|
1338
|
+
return false;
|
|
1339
|
+
}
|
|
1340
|
+
if (process.env["CI"] !== void 0) {
|
|
1341
|
+
const ciEnvs = ["TRAVIS", "CIRCLECI", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE"];
|
|
1342
|
+
return ciEnvs.some((env) => process.env[env] !== void 0);
|
|
1343
|
+
}
|
|
1344
|
+
return true;
|
|
3844
1345
|
}
|
|
3845
|
-
|
|
3846
|
-
|
|
3847
|
-
|
|
3848
|
-
|
|
3849
|
-
|
|
3850
|
-
|
|
3851
|
-
|
|
3852
|
-
|
|
1346
|
+
var supportsColor = checkColorSupport();
|
|
1347
|
+
var colors = {
|
|
1348
|
+
// Reset
|
|
1349
|
+
reset: supportsColor ? "\x1B[0m" : "",
|
|
1350
|
+
// Text styles
|
|
1351
|
+
bold: supportsColor ? "\x1B[1m" : "",
|
|
1352
|
+
dim: supportsColor ? "\x1B[2m" : "",
|
|
1353
|
+
italic: supportsColor ? "\x1B[3m" : "",
|
|
1354
|
+
underline: supportsColor ? "\x1B[4m" : "",
|
|
1355
|
+
blink: supportsColor ? "\x1B[5m" : "",
|
|
1356
|
+
inverse: supportsColor ? "\x1B[7m" : "",
|
|
1357
|
+
hidden: supportsColor ? "\x1B[8m" : "",
|
|
1358
|
+
strikethrough: supportsColor ? "\x1B[9m" : "",
|
|
1359
|
+
// Foreground colors
|
|
1360
|
+
black: supportsColor ? "\x1B[30m" : "",
|
|
1361
|
+
red: supportsColor ? "\x1B[31m" : "",
|
|
1362
|
+
green: supportsColor ? "\x1B[32m" : "",
|
|
1363
|
+
yellow: supportsColor ? "\x1B[33m" : "",
|
|
1364
|
+
blue: supportsColor ? "\x1B[34m" : "",
|
|
1365
|
+
magenta: supportsColor ? "\x1B[35m" : "",
|
|
1366
|
+
cyan: supportsColor ? "\x1B[36m" : "",
|
|
1367
|
+
white: supportsColor ? "\x1B[37m" : "",
|
|
1368
|
+
gray: supportsColor ? "\x1B[90m" : "",
|
|
1369
|
+
grey: supportsColor ? "\x1B[90m" : "",
|
|
1370
|
+
// Bright foreground colors
|
|
1371
|
+
brightRed: supportsColor ? "\x1B[91m" : "",
|
|
1372
|
+
brightGreen: supportsColor ? "\x1B[92m" : "",
|
|
1373
|
+
brightYellow: supportsColor ? "\x1B[93m" : "",
|
|
1374
|
+
brightBlue: supportsColor ? "\x1B[94m" : "",
|
|
1375
|
+
brightMagenta: supportsColor ? "\x1B[95m" : "",
|
|
1376
|
+
brightCyan: supportsColor ? "\x1B[96m" : "",
|
|
1377
|
+
brightWhite: supportsColor ? "\x1B[97m" : "",
|
|
1378
|
+
// Background colors
|
|
1379
|
+
bgBlack: supportsColor ? "\x1B[40m" : "",
|
|
1380
|
+
bgRed: supportsColor ? "\x1B[41m" : "",
|
|
1381
|
+
bgGreen: supportsColor ? "\x1B[42m" : "",
|
|
1382
|
+
bgYellow: supportsColor ? "\x1B[43m" : "",
|
|
1383
|
+
bgBlue: supportsColor ? "\x1B[44m" : "",
|
|
1384
|
+
bgMagenta: supportsColor ? "\x1B[45m" : "",
|
|
1385
|
+
bgCyan: supportsColor ? "\x1B[46m" : "",
|
|
1386
|
+
bgWhite: supportsColor ? "\x1B[47m" : "",
|
|
1387
|
+
bgGray: supportsColor ? "\x1B[100m" : "",
|
|
1388
|
+
// Bright background colors
|
|
1389
|
+
bgBrightRed: supportsColor ? "\x1B[101m" : "",
|
|
1390
|
+
bgBrightGreen: supportsColor ? "\x1B[102m" : "",
|
|
1391
|
+
bgBrightYellow: supportsColor ? "\x1B[103m" : "",
|
|
1392
|
+
bgBrightBlue: supportsColor ? "\x1B[104m" : "",
|
|
1393
|
+
bgBrightMagenta: supportsColor ? "\x1B[105m" : "",
|
|
1394
|
+
bgBrightCyan: supportsColor ? "\x1B[106m" : "",
|
|
1395
|
+
bgBrightWhite: supportsColor ? "\x1B[107m" : ""
|
|
1396
|
+
};
|
|
1397
|
+
function colorize(text, ...codes) {
|
|
1398
|
+
if (!supportsColor || codes.length === 0) {
|
|
1399
|
+
return text;
|
|
1400
|
+
}
|
|
1401
|
+
return codes.join("") + text + colors.reset;
|
|
1402
|
+
}
|
|
1403
|
+
function createColorizer(code) {
|
|
1404
|
+
return (text) => colorize(text, code);
|
|
1405
|
+
}
|
|
1406
|
+
var semantic = {
|
|
1407
|
+
/** Critical issues (red) */
|
|
1408
|
+
critical: createColorizer(colors.red),
|
|
1409
|
+
/** Warnings (yellow) */
|
|
1410
|
+
warning: createColorizer(colors.yellow),
|
|
1411
|
+
/** Healthy/success (green) */
|
|
1412
|
+
healthy: createColorizer(colors.green),
|
|
1413
|
+
/** Info/links (blue) */
|
|
1414
|
+
info: createColorizer(colors.blue),
|
|
1415
|
+
/** Secondary text (gray) */
|
|
1416
|
+
secondary: createColorizer(colors.gray),
|
|
1417
|
+
/** Highlighted text (cyan) */
|
|
1418
|
+
highlight: createColorizer(colors.cyan),
|
|
1419
|
+
/** Error text (bright red, bold) */
|
|
1420
|
+
error: (text) => colorize(text, colors.brightRed, colors.bold),
|
|
1421
|
+
/** Success text (bright green, bold) */
|
|
1422
|
+
success: (text) => colorize(text, colors.brightGreen, colors.bold),
|
|
1423
|
+
/** Title text (bold) */
|
|
1424
|
+
title: createColorizer(colors.bold),
|
|
1425
|
+
/** Dimmed text */
|
|
1426
|
+
dimmed: createColorizer(colors.dim)
|
|
1427
|
+
};
|
|
1428
|
+
function stripAnsi(text) {
|
|
1429
|
+
return text.replace(/\x1b\[[0-9;]*m/g, "");
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
// src/utils/logger.ts
|
|
1433
|
+
var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
|
|
1434
|
+
LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
|
|
1435
|
+
LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
|
|
1436
|
+
LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
|
|
1437
|
+
LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
|
|
1438
|
+
LogLevel2[LogLevel2["SILENT"] = 4] = "SILENT";
|
|
1439
|
+
return LogLevel2;
|
|
1440
|
+
})(LogLevel || {});
|
|
1441
|
+
var LOG_LEVEL_NAMES = {
|
|
1442
|
+
[0 /* DEBUG */]: "DEBUG",
|
|
1443
|
+
[1 /* INFO */]: "INFO",
|
|
1444
|
+
[2 /* WARN */]: "WARN",
|
|
1445
|
+
[3 /* ERROR */]: "ERROR",
|
|
1446
|
+
[4 /* SILENT */]: "SILENT"
|
|
1447
|
+
};
|
|
1448
|
+
var Logger = class _Logger {
|
|
1449
|
+
prefix;
|
|
1450
|
+
level;
|
|
1451
|
+
showTimestamp;
|
|
1452
|
+
showLevel;
|
|
1453
|
+
output;
|
|
1454
|
+
/**
|
|
1455
|
+
* Create a new Logger instance
|
|
1456
|
+
* @param options - Logger configuration
|
|
1457
|
+
*/
|
|
1458
|
+
constructor(options = {}) {
|
|
1459
|
+
this.prefix = options.prefix ?? "";
|
|
1460
|
+
this.level = options.level ?? 1 /* INFO */;
|
|
1461
|
+
this.showTimestamp = options.showTimestamp ?? false;
|
|
1462
|
+
this.showLevel = options.showLevel ?? true;
|
|
1463
|
+
this.output = options.output ?? {
|
|
1464
|
+
/* eslint-disable no-console */
|
|
1465
|
+
log: (msg) => console.log(msg),
|
|
1466
|
+
warn: (msg) => console.warn(msg),
|
|
1467
|
+
error: (msg) => console.error(msg)
|
|
1468
|
+
/* eslint-enable no-console */
|
|
1469
|
+
};
|
|
3853
1470
|
}
|
|
3854
|
-
|
|
3855
|
-
|
|
3856
|
-
|
|
3857
|
-
|
|
3858
|
-
|
|
3859
|
-
|
|
3860
|
-
|
|
3861
|
-
|
|
3862
|
-
|
|
3863
|
-
|
|
3864
|
-
|
|
1471
|
+
/**
|
|
1472
|
+
* Format a log message
|
|
1473
|
+
* @param level - Log level
|
|
1474
|
+
* @param message - Message to format
|
|
1475
|
+
* @returns Formatted message
|
|
1476
|
+
*/
|
|
1477
|
+
format(level, message) {
|
|
1478
|
+
const parts = [];
|
|
1479
|
+
if (this.showTimestamp) {
|
|
1480
|
+
const now = /* @__PURE__ */ new Date();
|
|
1481
|
+
const time = now.toISOString().slice(11, 23);
|
|
1482
|
+
parts.push(semantic.secondary(`[${time}]`));
|
|
1483
|
+
}
|
|
1484
|
+
if (this.showLevel) {
|
|
1485
|
+
const levelName = LOG_LEVEL_NAMES[level] ?? "UNKNOWN";
|
|
1486
|
+
let levelStr;
|
|
1487
|
+
switch (level) {
|
|
1488
|
+
case 0 /* DEBUG */:
|
|
1489
|
+
levelStr = semantic.secondary(levelName);
|
|
3865
1490
|
break;
|
|
3866
|
-
|
|
1491
|
+
case 1 /* INFO */:
|
|
1492
|
+
levelStr = semantic.info(levelName);
|
|
1493
|
+
break;
|
|
1494
|
+
case 2 /* WARN */:
|
|
1495
|
+
levelStr = semantic.warning(levelName);
|
|
1496
|
+
break;
|
|
1497
|
+
case 3 /* ERROR */:
|
|
1498
|
+
levelStr = semantic.error(levelName);
|
|
1499
|
+
break;
|
|
1500
|
+
default:
|
|
1501
|
+
levelStr = levelName;
|
|
3867
1502
|
}
|
|
1503
|
+
parts.push(`[${levelStr}]`);
|
|
3868
1504
|
}
|
|
3869
|
-
if (
|
|
3870
|
-
|
|
3871
|
-
detected = await feature.detect(packageJson, projectDir);
|
|
3872
|
-
} catch {
|
|
3873
|
-
}
|
|
1505
|
+
if (this.prefix) {
|
|
1506
|
+
parts.push(semantic.highlight(`[${this.prefix}]`));
|
|
3874
1507
|
}
|
|
3875
|
-
|
|
3876
|
-
|
|
1508
|
+
parts.push(message);
|
|
1509
|
+
return parts.join(" ");
|
|
1510
|
+
}
|
|
1511
|
+
/**
|
|
1512
|
+
* Log a debug message
|
|
1513
|
+
* @param message - Message to log
|
|
1514
|
+
* @param args - Additional arguments to log
|
|
1515
|
+
*/
|
|
1516
|
+
debug(message, ...args) {
|
|
1517
|
+
if (this.level > 0 /* DEBUG */) return;
|
|
1518
|
+
const formatted = this.format(0 /* DEBUG */, message);
|
|
1519
|
+
if (args.length > 0) {
|
|
1520
|
+
this.output.log(formatted + " " + args.map(String).join(" "));
|
|
1521
|
+
} else {
|
|
1522
|
+
this.output.log(formatted);
|
|
3877
1523
|
}
|
|
3878
1524
|
}
|
|
3879
|
-
|
|
3880
|
-
|
|
3881
|
-
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
|
|
3885
|
-
|
|
3886
|
-
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
case "next":
|
|
3892
|
-
tips.push("Consider using server components to avoid client-side context re-renders");
|
|
3893
|
-
break;
|
|
3894
|
-
case "remix":
|
|
3895
|
-
tips.push("Use loader data instead of context for server data");
|
|
3896
|
-
break;
|
|
3897
|
-
default:
|
|
3898
|
-
tips.push("Split large contexts into smaller, focused contexts");
|
|
1525
|
+
/**
|
|
1526
|
+
* Log an info message
|
|
1527
|
+
* @param message - Message to log
|
|
1528
|
+
* @param args - Additional arguments to log
|
|
1529
|
+
*/
|
|
1530
|
+
info(message, ...args) {
|
|
1531
|
+
if (this.level > 1 /* INFO */) return;
|
|
1532
|
+
const formatted = this.format(1 /* INFO */, message);
|
|
1533
|
+
if (args.length > 0) {
|
|
1534
|
+
this.output.log(formatted + " " + args.map(String).join(" "));
|
|
1535
|
+
} else {
|
|
1536
|
+
this.output.log(formatted);
|
|
3899
1537
|
}
|
|
3900
1538
|
}
|
|
3901
|
-
|
|
3902
|
-
|
|
3903
|
-
|
|
3904
|
-
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
3909
|
-
|
|
3910
|
-
|
|
1539
|
+
/**
|
|
1540
|
+
* Log a warning message
|
|
1541
|
+
* @param message - Message to log
|
|
1542
|
+
* @param args - Additional arguments to log
|
|
1543
|
+
*/
|
|
1544
|
+
warn(message, ...args) {
|
|
1545
|
+
if (this.level > 2 /* WARN */) return;
|
|
1546
|
+
const formatted = this.format(2 /* WARN */, message);
|
|
1547
|
+
if (args.length > 0) {
|
|
1548
|
+
this.output.warn(formatted + " " + args.map(String).join(" "));
|
|
1549
|
+
} else {
|
|
1550
|
+
this.output.warn(formatted);
|
|
3911
1551
|
}
|
|
3912
1552
|
}
|
|
3913
|
-
|
|
3914
|
-
|
|
3915
|
-
|
|
3916
|
-
|
|
3917
|
-
|
|
1553
|
+
/**
|
|
1554
|
+
* Log an error message
|
|
1555
|
+
* @param message - Message to log
|
|
1556
|
+
* @param args - Additional arguments to log
|
|
1557
|
+
*/
|
|
1558
|
+
error(message, ...args) {
|
|
1559
|
+
if (this.level > 3 /* ERROR */) return;
|
|
1560
|
+
const formatted = this.format(3 /* ERROR */, message);
|
|
1561
|
+
if (args.length > 0) {
|
|
1562
|
+
this.output.error(formatted + " " + args.map(String).join(" "));
|
|
1563
|
+
} else {
|
|
1564
|
+
this.output.error(formatted);
|
|
1565
|
+
}
|
|
3918
1566
|
}
|
|
3919
|
-
|
|
3920
|
-
|
|
3921
|
-
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
3925
|
-
|
|
3926
|
-
|
|
3927
|
-
tips: []
|
|
3928
|
-
};
|
|
1567
|
+
/**
|
|
1568
|
+
* Log a success message (always shown unless silent)
|
|
1569
|
+
* @param message - Message to log
|
|
1570
|
+
*/
|
|
1571
|
+
success(message) {
|
|
1572
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1573
|
+
const prefix = this.prefix ? `[${semantic.highlight(this.prefix)}] ` : "";
|
|
1574
|
+
this.output.log(prefix + semantic.success("\u2713 ") + message);
|
|
3929
1575
|
}
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
3933
|
-
|
|
3934
|
-
|
|
3935
|
-
|
|
3936
|
-
};
|
|
1576
|
+
/**
|
|
1577
|
+
* Log a failure message (always shown unless silent)
|
|
1578
|
+
* @param message - Message to log
|
|
1579
|
+
*/
|
|
1580
|
+
fail(message) {
|
|
1581
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1582
|
+
const prefix = this.prefix ? `[${semantic.highlight(this.prefix)}] ` : "";
|
|
1583
|
+
this.output.error(prefix + semantic.error("\u2717 ") + message);
|
|
1584
|
+
}
|
|
1585
|
+
/**
|
|
1586
|
+
* Create a child logger with a sub-prefix
|
|
1587
|
+
* @param prefix - Sub-prefix for the child logger
|
|
1588
|
+
* @returns New Logger instance
|
|
1589
|
+
*/
|
|
1590
|
+
child(prefix) {
|
|
1591
|
+
const childPrefix = this.prefix ? `${this.prefix}:${prefix}` : prefix;
|
|
1592
|
+
return new _Logger({
|
|
1593
|
+
prefix: childPrefix,
|
|
1594
|
+
level: this.level,
|
|
1595
|
+
showTimestamp: this.showTimestamp,
|
|
1596
|
+
showLevel: this.showLevel,
|
|
1597
|
+
output: this.output
|
|
1598
|
+
});
|
|
1599
|
+
}
|
|
1600
|
+
/**
|
|
1601
|
+
* Set the log level
|
|
1602
|
+
* @param level - New log level
|
|
1603
|
+
*/
|
|
1604
|
+
setLevel(level) {
|
|
1605
|
+
this.level = level;
|
|
1606
|
+
}
|
|
1607
|
+
/**
|
|
1608
|
+
* Get the current log level
|
|
1609
|
+
* @returns Current log level
|
|
1610
|
+
*/
|
|
1611
|
+
getLevel() {
|
|
1612
|
+
return this.level;
|
|
1613
|
+
}
|
|
1614
|
+
/**
|
|
1615
|
+
* Check if a log level is enabled
|
|
1616
|
+
* @param level - Level to check
|
|
1617
|
+
* @returns true if the level would be logged
|
|
1618
|
+
*/
|
|
1619
|
+
isLevelEnabled(level) {
|
|
1620
|
+
return this.level <= level;
|
|
3937
1621
|
}
|
|
3938
|
-
|
|
1622
|
+
/**
|
|
1623
|
+
* Create a timer for performance logging
|
|
1624
|
+
* @param label - Timer label
|
|
1625
|
+
* @returns Object with end() method to log duration
|
|
1626
|
+
*/
|
|
1627
|
+
time(label) {
|
|
1628
|
+
const start = performance.now();
|
|
3939
1629
|
return {
|
|
3940
|
-
|
|
3941
|
-
|
|
3942
|
-
|
|
3943
|
-
|
|
1630
|
+
end: () => {
|
|
1631
|
+
const duration = performance.now() - start;
|
|
1632
|
+
this.debug(`${label}: ${duration.toFixed(2)}ms`);
|
|
1633
|
+
}
|
|
3944
1634
|
};
|
|
3945
1635
|
}
|
|
3946
|
-
|
|
1636
|
+
/**
|
|
1637
|
+
* Log a table of data
|
|
1638
|
+
* @param data - Array of objects to display
|
|
1639
|
+
* @param columns - Optional column names to show
|
|
1640
|
+
*/
|
|
1641
|
+
table(data, columns) {
|
|
1642
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1643
|
+
if (data.length === 0) {
|
|
1644
|
+
this.info("(empty table)");
|
|
1645
|
+
return;
|
|
1646
|
+
}
|
|
1647
|
+
const cols = columns ?? Object.keys(data[0] ?? {});
|
|
1648
|
+
if (cols.length === 0) {
|
|
1649
|
+
this.info("(no columns)");
|
|
1650
|
+
return;
|
|
1651
|
+
}
|
|
1652
|
+
const widths = {};
|
|
1653
|
+
for (const col of cols) {
|
|
1654
|
+
widths[col] = col.length;
|
|
1655
|
+
for (const row of data) {
|
|
1656
|
+
const value = formatCell(row[col]);
|
|
1657
|
+
widths[col] = Math.max(widths[col] ?? 0, value.length);
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
const header = cols.map((col) => col.padEnd(widths[col] ?? 0)).join(" \u2502 ");
|
|
1661
|
+
const separator = cols.map((col) => "\u2500".repeat(widths[col] ?? 0)).join("\u2500\u253C\u2500");
|
|
1662
|
+
this.output.log(colors.bold + header + colors.reset);
|
|
1663
|
+
this.output.log(separator);
|
|
1664
|
+
for (const row of data) {
|
|
1665
|
+
const line = cols.map((col) => formatCell(row[col]).padEnd(widths[col] ?? 0)).join(" \u2502 ");
|
|
1666
|
+
this.output.log(line);
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* Log a progress message (overwrites previous line)
|
|
1671
|
+
* @param message - Progress message
|
|
1672
|
+
*/
|
|
1673
|
+
progress(message) {
|
|
1674
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1675
|
+
if (process.stdout.isTTY) {
|
|
1676
|
+
process.stdout.write(`\r\x1B[K${message}`);
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
/**
|
|
1680
|
+
* Clear the progress line
|
|
1681
|
+
*/
|
|
1682
|
+
clearProgress() {
|
|
1683
|
+
if (process.stdout.isTTY) {
|
|
1684
|
+
process.stdout.write("\r\x1B[K");
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
/**
|
|
1688
|
+
* Log a newline
|
|
1689
|
+
*/
|
|
1690
|
+
newline() {
|
|
1691
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1692
|
+
this.output.log("");
|
|
1693
|
+
}
|
|
1694
|
+
/**
|
|
1695
|
+
* Log a horizontal rule
|
|
1696
|
+
* @param char - Character to use for the rule
|
|
1697
|
+
* @param width - Width of the rule
|
|
1698
|
+
*/
|
|
1699
|
+
hr(char = "\u2500", width = 60) {
|
|
1700
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1701
|
+
this.output.log(colors.gray + char.repeat(width) + colors.reset);
|
|
1702
|
+
}
|
|
1703
|
+
/**
|
|
1704
|
+
* Group related log messages
|
|
1705
|
+
* @param label - Group label
|
|
1706
|
+
* @param fn - Function containing log calls
|
|
1707
|
+
*/
|
|
1708
|
+
group(label, fn) {
|
|
1709
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1710
|
+
this.output.log(colors.bold + "\u250C " + label + colors.reset);
|
|
1711
|
+
fn();
|
|
1712
|
+
this.output.log(colors.bold + "\u2514" + "\u2500".repeat(label.length + 1) + colors.reset);
|
|
1713
|
+
}
|
|
1714
|
+
};
|
|
1715
|
+
new Logger({ prefix: "ReactCheck" });
|
|
1716
|
+
function formatCell(value) {
|
|
1717
|
+
if (value === null || value === void 0) return "";
|
|
1718
|
+
if (typeof value === "object") {
|
|
1719
|
+
try {
|
|
1720
|
+
return JSON.stringify(value);
|
|
1721
|
+
} catch {
|
|
1722
|
+
return Object.prototype.toString.call(value);
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
switch (typeof value) {
|
|
1726
|
+
case "string":
|
|
1727
|
+
return value;
|
|
1728
|
+
case "number":
|
|
1729
|
+
case "boolean":
|
|
1730
|
+
case "bigint":
|
|
1731
|
+
case "symbol":
|
|
1732
|
+
return value.toString();
|
|
1733
|
+
default:
|
|
1734
|
+
return "[function]";
|
|
1735
|
+
}
|
|
3947
1736
|
}
|
|
3948
|
-
|
|
3949
|
-
// src/utils/index.ts
|
|
3950
|
-
init_colors();
|
|
3951
|
-
init_event_emitter();
|
|
3952
|
-
init_logger();
|
|
3953
|
-
|
|
3954
|
-
// src/server/websocket.ts
|
|
3955
|
-
init_event_emitter();
|
|
3956
1737
|
var OPCODE = {
|
|
3957
1738
|
TEXT: 1,
|
|
3958
1739
|
BINARY: 2,
|
|
@@ -3961,6 +1742,7 @@ var OPCODE = {
|
|
|
3961
1742
|
PONG: 10
|
|
3962
1743
|
};
|
|
3963
1744
|
var WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
1745
|
+
var MAX_FRAME_PAYLOAD = 16 * 1024 * 1024;
|
|
3964
1746
|
var WebSocketClient = class extends EventEmitter {
|
|
3965
1747
|
/** Socket connection */
|
|
3966
1748
|
socket;
|
|
@@ -3997,7 +1779,7 @@ var WebSocketClient = class extends EventEmitter {
|
|
|
3997
1779
|
* Process received frames
|
|
3998
1780
|
*/
|
|
3999
1781
|
processFrames() {
|
|
4000
|
-
while (this.frameBuffer.length >= 2) {
|
|
1782
|
+
while (this.isOpen && this.frameBuffer.length >= 2) {
|
|
4001
1783
|
const frame = this.parseFrame();
|
|
4002
1784
|
if (!frame) break;
|
|
4003
1785
|
switch (frame.opcode) {
|
|
@@ -4037,8 +1819,18 @@ var WebSocketClient = class extends EventEmitter {
|
|
|
4037
1819
|
offset = 4;
|
|
4038
1820
|
} else if (payloadLength === 127) {
|
|
4039
1821
|
if (this.frameBuffer.length < 10) return null;
|
|
1822
|
+
const high = this.frameBuffer.readUInt32BE(2);
|
|
4040
1823
|
payloadLength = this.frameBuffer.readUInt32BE(6);
|
|
4041
1824
|
offset = 10;
|
|
1825
|
+
if (high !== 0) {
|
|
1826
|
+
payloadLength = Number.POSITIVE_INFINITY;
|
|
1827
|
+
}
|
|
1828
|
+
}
|
|
1829
|
+
if (payloadLength > MAX_FRAME_PAYLOAD) {
|
|
1830
|
+
this.frameBuffer = Buffer.alloc(0);
|
|
1831
|
+
this.close(1009, "Message too big");
|
|
1832
|
+
this.socket.destroy();
|
|
1833
|
+
return null;
|
|
4042
1834
|
}
|
|
4043
1835
|
let maskingKey = null;
|
|
4044
1836
|
if (masked) {
|
|
@@ -4236,6 +2028,10 @@ var WebSocketServer = class extends EventEmitter {
|
|
|
4236
2028
|
this.server.once("error", reject);
|
|
4237
2029
|
this.server.listen(this.port, () => {
|
|
4238
2030
|
this.server.removeListener("error", reject);
|
|
2031
|
+
const address = this.server.address();
|
|
2032
|
+
if (address && typeof address === "object") {
|
|
2033
|
+
this.port = address.port;
|
|
2034
|
+
}
|
|
4239
2035
|
this.emit("listening", { port: this.port });
|
|
4240
2036
|
resolve2();
|
|
4241
2037
|
});
|
|
@@ -4255,6 +2051,14 @@ var WebSocketServer = class extends EventEmitter {
|
|
|
4255
2051
|
});
|
|
4256
2052
|
});
|
|
4257
2053
|
}
|
|
2054
|
+
/**
|
|
2055
|
+
* Get the port the server listens on (the real port after start() when
|
|
2056
|
+
* constructed with port 0)
|
|
2057
|
+
* @returns Port number
|
|
2058
|
+
*/
|
|
2059
|
+
getPort() {
|
|
2060
|
+
return this.port;
|
|
2061
|
+
}
|
|
4258
2062
|
/**
|
|
4259
2063
|
* Broadcast message to all clients
|
|
4260
2064
|
* @param message - Message to broadcast
|
|
@@ -4290,18 +2094,67 @@ var WebSocketServer = class extends EventEmitter {
|
|
|
4290
2094
|
};
|
|
4291
2095
|
function handleBrowserMessages(client, handler) {
|
|
4292
2096
|
client.on("message", (data) => {
|
|
2097
|
+
let message;
|
|
4293
2098
|
try {
|
|
4294
|
-
|
|
4295
|
-
|
|
4296
|
-
|
|
2099
|
+
message = JSON.parse(data);
|
|
2100
|
+
} catch {
|
|
2101
|
+
return;
|
|
2102
|
+
}
|
|
2103
|
+
if (message === null || typeof message !== "object" || typeof message.type !== "string") {
|
|
2104
|
+
return;
|
|
4297
2105
|
}
|
|
2106
|
+
handler(message);
|
|
4298
2107
|
});
|
|
4299
2108
|
}
|
|
2109
|
+
var INJECTION_SCRIPT_FILE = "browser-inject.global.js";
|
|
2110
|
+
function getInjectionScriptCandidates() {
|
|
2111
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
2112
|
+
return [
|
|
2113
|
+
resolve(here, INJECTION_SCRIPT_FILE),
|
|
2114
|
+
resolve(here, "..", INJECTION_SCRIPT_FILE),
|
|
2115
|
+
resolve(here, "..", "..", "dist", INJECTION_SCRIPT_FILE)
|
|
2116
|
+
];
|
|
2117
|
+
}
|
|
2118
|
+
async function loadInjectionScript(wsPort) {
|
|
2119
|
+
const port = Math.trunc(Number(wsPort));
|
|
2120
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
2121
|
+
throw new RangeError(`Invalid WebSocket port: ${String(wsPort)}`);
|
|
2122
|
+
}
|
|
2123
|
+
for (const candidate of getInjectionScriptCandidates()) {
|
|
2124
|
+
try {
|
|
2125
|
+
const script = await readFile(candidate, "utf8");
|
|
2126
|
+
return `window.__REACTCHECK_PORT__ = ${port};
|
|
2127
|
+
${script}`;
|
|
2128
|
+
} catch {
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
throw new Error(
|
|
2132
|
+
`ReactCheck browser script (${INJECTION_SCRIPT_FILE}) not found next to the installed package. Reinstall @oxog/react-check or run "npm run build" when working from source.`
|
|
2133
|
+
);
|
|
2134
|
+
}
|
|
4300
2135
|
|
|
4301
2136
|
// src/server/proxy.ts
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
2137
|
+
var logger2 = new Logger({ prefix: "proxy", level: 1 /* INFO */ });
|
|
2138
|
+
var SCANNER_SCRIPT_PATH = "/__reactcheck__/scanner.js";
|
|
2139
|
+
function injectScriptTag(html) {
|
|
2140
|
+
const tag = `<script src="${SCANNER_SCRIPT_PATH}"></script>`;
|
|
2141
|
+
if (html.includes(tag)) return html;
|
|
2142
|
+
const head = /<head(?:\s[^>]*)?>/i.exec(html);
|
|
2143
|
+
if (head) {
|
|
2144
|
+
const at = head.index + head[0].length;
|
|
2145
|
+
return html.slice(0, at) + tag + html.slice(at);
|
|
2146
|
+
}
|
|
2147
|
+
const htmlTag = /<html(?:\s[^>]*)?>/i.exec(html);
|
|
2148
|
+
if (htmlTag) {
|
|
2149
|
+
const at = htmlTag.index + htmlTag[0].length;
|
|
2150
|
+
return html.slice(0, at) + tag + html.slice(at);
|
|
2151
|
+
}
|
|
2152
|
+
const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
|
|
2153
|
+
if (doctype) {
|
|
2154
|
+
return doctype[0] + tag + html.slice(doctype[0].length);
|
|
2155
|
+
}
|
|
2156
|
+
return tag + html;
|
|
2157
|
+
}
|
|
4305
2158
|
var ProxyServer = class extends EventEmitter {
|
|
4306
2159
|
/** HTTP server instance */
|
|
4307
2160
|
server;
|
|
@@ -4309,7 +2162,7 @@ var ProxyServer = class extends EventEmitter {
|
|
|
4309
2162
|
options;
|
|
4310
2163
|
/** Target URL parsed */
|
|
4311
2164
|
targetUrl;
|
|
4312
|
-
/** Injection script */
|
|
2165
|
+
/** Injection script (loaded from the bundled browser script on start() when not provided) */
|
|
4313
2166
|
injectionScript;
|
|
4314
2167
|
/**
|
|
4315
2168
|
* Create a new proxy server
|
|
@@ -4319,101 +2172,18 @@ var ProxyServer = class extends EventEmitter {
|
|
|
4319
2172
|
super();
|
|
4320
2173
|
this.options = options;
|
|
4321
2174
|
this.targetUrl = new URL(options.target);
|
|
4322
|
-
this.injectionScript = options.injectionScript ??
|
|
2175
|
+
this.injectionScript = options.injectionScript ?? null;
|
|
4323
2176
|
this.server = createServer((req, res) => {
|
|
4324
2177
|
this.handleRequest(req, res).catch((error) => {
|
|
4325
2178
|
logger2.error("Request handling error:", error);
|
|
4326
2179
|
this.emit("error", error);
|
|
4327
2180
|
res.statusCode = 500;
|
|
4328
|
-
res.end("Internal Server Error");
|
|
4329
|
-
});
|
|
4330
|
-
});
|
|
4331
|
-
this.server.on("error", (error) => {
|
|
4332
|
-
this.emit("error", error);
|
|
4333
|
-
});
|
|
4334
|
-
}
|
|
4335
|
-
/**
|
|
4336
|
-
* Build the injection script
|
|
4337
|
-
* @returns Injection script string
|
|
4338
|
-
*/
|
|
4339
|
-
buildInjectionScript() {
|
|
4340
|
-
const { wsPort } = this.options;
|
|
4341
|
-
return `
|
|
4342
|
-
(function() {
|
|
4343
|
-
if (window.__REACTCHECK_INJECTED__) return;
|
|
4344
|
-
window.__REACTCHECK_INJECTED__ = true;
|
|
4345
|
-
window.__REACTCHECK_PORT__ = ${wsPort};
|
|
4346
|
-
|
|
4347
|
-
// Load the main scanner script
|
|
4348
|
-
const script = document.createElement('script');
|
|
4349
|
-
script.src = '/__reactcheck__/scanner.js';
|
|
4350
|
-
script.async = true;
|
|
4351
|
-
document.head.appendChild(script);
|
|
4352
|
-
|
|
4353
|
-
// Fallback: Connect WebSocket directly if script fails to load
|
|
4354
|
-
script.onerror = function() {
|
|
4355
|
-
console.warn('[ReactCheck] Failed to load scanner script, using minimal mode');
|
|
4356
|
-
connectWebSocket();
|
|
4357
|
-
};
|
|
4358
|
-
|
|
4359
|
-
function connectWebSocket() {
|
|
4360
|
-
const ws = new WebSocket('ws://localhost:${wsPort}');
|
|
4361
|
-
|
|
4362
|
-
ws.onopen = function() {
|
|
4363
|
-
ws.send(JSON.stringify({
|
|
4364
|
-
type: 'ready',
|
|
4365
|
-
payload: { reactVersion: detectReactVersion() }
|
|
4366
|
-
}));
|
|
4367
|
-
};
|
|
4368
|
-
|
|
4369
|
-
ws.onmessage = function(event) {
|
|
4370
|
-
try {
|
|
4371
|
-
const msg = JSON.parse(event.data);
|
|
4372
|
-
handleMessage(msg);
|
|
4373
|
-
} catch (e) {}
|
|
4374
|
-
};
|
|
4375
|
-
|
|
4376
|
-
ws.onerror = function(error) {
|
|
4377
|
-
console.error('[ReactCheck] WebSocket error:', error);
|
|
4378
|
-
};
|
|
4379
|
-
|
|
4380
|
-
ws.onclose = function() {
|
|
4381
|
-
// Try to reconnect after 2 seconds
|
|
4382
|
-
setTimeout(connectWebSocket, 2000);
|
|
4383
|
-
};
|
|
4384
|
-
}
|
|
4385
|
-
|
|
4386
|
-
function detectReactVersion() {
|
|
4387
|
-
if (window.React && window.React.version) {
|
|
4388
|
-
return window.React.version;
|
|
4389
|
-
}
|
|
4390
|
-
if (window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
|
|
4391
|
-
const renderers = window.__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers;
|
|
4392
|
-
if (renderers && renderers.size > 0) {
|
|
4393
|
-
const renderer = renderers.values().next().value;
|
|
4394
|
-
if (renderer && renderer.version) {
|
|
4395
|
-
return renderer.version;
|
|
4396
|
-
}
|
|
4397
|
-
}
|
|
4398
|
-
}
|
|
4399
|
-
return 'unknown';
|
|
4400
|
-
}
|
|
4401
|
-
|
|
4402
|
-
function handleMessage(msg) {
|
|
4403
|
-
switch (msg.type) {
|
|
4404
|
-
case 'start':
|
|
4405
|
-
console.log('[ReactCheck] Scanning started');
|
|
4406
|
-
break;
|
|
4407
|
-
case 'stop':
|
|
4408
|
-
console.log('[ReactCheck] Scanning stopped');
|
|
4409
|
-
break;
|
|
4410
|
-
case 'config':
|
|
4411
|
-
console.log('[ReactCheck] Config updated:', msg.payload);
|
|
4412
|
-
break;
|
|
4413
|
-
}
|
|
4414
|
-
}
|
|
4415
|
-
})();
|
|
4416
|
-
`;
|
|
2181
|
+
res.end("Internal Server Error");
|
|
2182
|
+
});
|
|
2183
|
+
});
|
|
2184
|
+
this.server.on("error", (error) => {
|
|
2185
|
+
this.emit("error", error);
|
|
2186
|
+
});
|
|
4417
2187
|
}
|
|
4418
2188
|
/**
|
|
4419
2189
|
* Handle incoming request
|
|
@@ -4436,12 +2206,13 @@ var ProxyServer = class extends EventEmitter {
|
|
|
4436
2206
|
* @param res - Server response
|
|
4437
2207
|
*/
|
|
4438
2208
|
handleReactCheckRoute(url, res) {
|
|
4439
|
-
if (url ===
|
|
2209
|
+
if (url === SCANNER_SCRIPT_PATH || url.startsWith(`${SCANNER_SCRIPT_PATH}?`)) {
|
|
4440
2210
|
res.writeHead(200, {
|
|
4441
|
-
"Content-Type": "application/javascript",
|
|
4442
|
-
"Cache-Control": "no-cache"
|
|
2211
|
+
"Content-Type": "application/javascript; charset=utf-8",
|
|
2212
|
+
"Cache-Control": "no-cache",
|
|
2213
|
+
"Access-Control-Allow-Origin": "*"
|
|
4443
2214
|
});
|
|
4444
|
-
res.end(
|
|
2215
|
+
res.end(this.injectionScript ?? "");
|
|
4445
2216
|
return;
|
|
4446
2217
|
}
|
|
4447
2218
|
res.writeHead(404);
|
|
@@ -4469,7 +2240,8 @@ var ProxyServer = class extends EventEmitter {
|
|
|
4469
2240
|
};
|
|
4470
2241
|
const proxyReq = requestFn(options, (proxyRes) => {
|
|
4471
2242
|
const contentType = proxyRes.headers["content-type"] ?? "";
|
|
4472
|
-
|
|
2243
|
+
const contentEncoding = String(proxyRes.headers["content-encoding"] ?? "identity").toLowerCase();
|
|
2244
|
+
if (contentType.includes("text/html") && (contentEncoding === "identity" || contentEncoding === "")) {
|
|
4473
2245
|
this.injectAndRespond(proxyRes, res, targetUrl.href);
|
|
4474
2246
|
resolve2();
|
|
4475
2247
|
return;
|
|
@@ -4498,19 +2270,12 @@ var ProxyServer = class extends EventEmitter {
|
|
|
4498
2270
|
});
|
|
4499
2271
|
proxyRes.on("end", () => {
|
|
4500
2272
|
const body = Buffer.concat(chunks).toString("utf-8");
|
|
4501
|
-
|
|
4502
|
-
const scriptTag = `<script>${this.injectionScript}</script>`;
|
|
4503
|
-
if (body.includes("</body>")) {
|
|
4504
|
-
injected = body.replace("</body>", `${scriptTag}</body>`);
|
|
4505
|
-
} else if (body.includes("</head>")) {
|
|
4506
|
-
injected = body.replace("</head>", `${scriptTag}</head>`);
|
|
4507
|
-
} else {
|
|
4508
|
-
injected = body + scriptTag;
|
|
4509
|
-
}
|
|
2273
|
+
const injected = injectScriptTag(body);
|
|
4510
2274
|
this.emit("inject", { url });
|
|
4511
2275
|
const headers = {};
|
|
4512
2276
|
for (const [key, value] of Object.entries(proxyRes.headers)) {
|
|
4513
|
-
|
|
2277
|
+
const lower = key.toLowerCase();
|
|
2278
|
+
if (lower !== "content-length" && lower !== "transfer-encoding" && value !== void 0) {
|
|
4514
2279
|
headers[key] = Array.isArray(value) ? value.join(", ") : value;
|
|
4515
2280
|
}
|
|
4516
2281
|
}
|
|
@@ -4527,11 +2292,18 @@ var ProxyServer = class extends EventEmitter {
|
|
|
4527
2292
|
/**
|
|
4528
2293
|
* Start the proxy server
|
|
4529
2294
|
*/
|
|
4530
|
-
start() {
|
|
2295
|
+
async start() {
|
|
2296
|
+
if (this.injectionScript === null) {
|
|
2297
|
+
this.injectionScript = await loadInjectionScript(this.options.wsPort);
|
|
2298
|
+
}
|
|
4531
2299
|
return new Promise((resolve2, reject) => {
|
|
4532
2300
|
this.server.once("error", reject);
|
|
4533
2301
|
this.server.listen(this.options.port, () => {
|
|
4534
2302
|
this.server.removeListener("error", reject);
|
|
2303
|
+
const address = this.server.address();
|
|
2304
|
+
if (address && typeof address === "object") {
|
|
2305
|
+
this.options.port = address.port;
|
|
2306
|
+
}
|
|
4535
2307
|
this.emit("listening", { port: this.options.port });
|
|
4536
2308
|
logger2.info(`Proxy server listening on http://localhost:${this.options.port}`);
|
|
4537
2309
|
logger2.info(`Proxying to ${this.options.target}`);
|
|
@@ -4565,15 +2337,272 @@ var ProxyServer = class extends EventEmitter {
|
|
|
4565
2337
|
this.injectionScript = script;
|
|
4566
2338
|
}
|
|
4567
2339
|
};
|
|
2340
|
+
function getPuppeteerInstallDir(env = process.env, platform = process.platform, home = homedir()) {
|
|
2341
|
+
const explicit = env["REACTCHECK_PUPPETEER_DIR"];
|
|
2342
|
+
if (explicit !== void 0 && explicit !== "") return explicit;
|
|
2343
|
+
const cacheRoot = platform === "win32" ? env["LOCALAPPDATA"] !== void 0 && env["LOCALAPPDATA"] !== "" ? env["LOCALAPPDATA"] : join(home, "AppData", "Local") : env["XDG_CACHE_HOME"] !== void 0 && env["XDG_CACHE_HOME"] !== "" ? env["XDG_CACHE_HOME"] : join(home, ".cache");
|
|
2344
|
+
return join(cacheRoot, "react-check", "puppeteer");
|
|
2345
|
+
}
|
|
2346
|
+
function toPuppeteer(loaded) {
|
|
2347
|
+
const candidates = [
|
|
2348
|
+
loaded?.default,
|
|
2349
|
+
loaded,
|
|
2350
|
+
loaded?.default?.default
|
|
2351
|
+
];
|
|
2352
|
+
for (const candidate of candidates) {
|
|
2353
|
+
if (candidate !== null && typeof candidate === "object" && typeof candidate.launch === "function") {
|
|
2354
|
+
return candidate;
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
return null;
|
|
2358
|
+
}
|
|
2359
|
+
async function loadPuppeteer(installDir = getPuppeteerInstallDir()) {
|
|
2360
|
+
try {
|
|
2361
|
+
const found = toPuppeteer(await import('puppeteer'));
|
|
2362
|
+
if (found) return found;
|
|
2363
|
+
} catch {
|
|
2364
|
+
}
|
|
2365
|
+
try {
|
|
2366
|
+
const requireFromDir = createRequire(join(installDir, "package.json"));
|
|
2367
|
+
return toPuppeteer(requireFromDir("puppeteer"));
|
|
2368
|
+
} catch {
|
|
2369
|
+
return null;
|
|
2370
|
+
}
|
|
2371
|
+
}
|
|
4568
2372
|
|
|
4569
|
-
// src/server/
|
|
4570
|
-
|
|
4571
|
-
|
|
4572
|
-
|
|
4573
|
-
|
|
2373
|
+
// src/server/browser.ts
|
|
2374
|
+
var logger3 = new Logger({ prefix: "browser", level: 1 /* INFO */ });
|
|
2375
|
+
var BrowserLauncher = class extends EventEmitter {
|
|
2376
|
+
/** Puppeteer browser instance */
|
|
2377
|
+
browser = null;
|
|
2378
|
+
/** Active page */
|
|
2379
|
+
page = null;
|
|
2380
|
+
/** Launch options */
|
|
2381
|
+
options;
|
|
2382
|
+
/** Injection script */
|
|
2383
|
+
injectionScript = null;
|
|
2384
|
+
/**
|
|
2385
|
+
* Create a new browser launcher
|
|
2386
|
+
* @param options - Launch options
|
|
2387
|
+
*/
|
|
2388
|
+
constructor(options) {
|
|
2389
|
+
super();
|
|
2390
|
+
this.options = {
|
|
2391
|
+
url: options.url,
|
|
2392
|
+
headless: options.headless ?? false,
|
|
2393
|
+
width: options.width ?? 1280,
|
|
2394
|
+
height: options.height ?? 800,
|
|
2395
|
+
wsPort: options.wsPort ?? 3099,
|
|
2396
|
+
args: options.args ?? [],
|
|
2397
|
+
slowMo: options.slowMo ?? 0,
|
|
2398
|
+
timeout: options.timeout ?? 3e4
|
|
2399
|
+
};
|
|
2400
|
+
}
|
|
2401
|
+
/**
|
|
2402
|
+
* Set the injection script
|
|
2403
|
+
* @param script - Script to inject before page loads
|
|
2404
|
+
*/
|
|
2405
|
+
setInjectionScript(script) {
|
|
2406
|
+
this.injectionScript = script;
|
|
2407
|
+
}
|
|
2408
|
+
/**
|
|
2409
|
+
* Launch the browser
|
|
2410
|
+
*/
|
|
2411
|
+
async launch() {
|
|
2412
|
+
try {
|
|
2413
|
+
const puppeteer = await loadPuppeteer();
|
|
2414
|
+
if (!puppeteer) {
|
|
2415
|
+
throw new Error("Puppeteer is not installed. Install it with: npm install puppeteer");
|
|
2416
|
+
}
|
|
2417
|
+
const args = [
|
|
2418
|
+
"--no-sandbox",
|
|
2419
|
+
"--disable-setuid-sandbox",
|
|
2420
|
+
"--disable-dev-shm-usage",
|
|
2421
|
+
"--disable-gpu",
|
|
2422
|
+
"--ignore-certificate-errors",
|
|
2423
|
+
"--ignore-certificate-errors-spki-list",
|
|
2424
|
+
`--window-size=${this.options.width},${this.options.height}`,
|
|
2425
|
+
...this.options.args
|
|
2426
|
+
];
|
|
2427
|
+
this.browser = await puppeteer.launch({
|
|
2428
|
+
headless: this.options.headless,
|
|
2429
|
+
args,
|
|
2430
|
+
slowMo: this.options.slowMo,
|
|
2431
|
+
defaultViewport: {
|
|
2432
|
+
width: this.options.width,
|
|
2433
|
+
height: this.options.height
|
|
2434
|
+
}
|
|
2435
|
+
});
|
|
2436
|
+
const pages = await this.browser.pages();
|
|
2437
|
+
this.page = pages[0] ?? await this.browser.newPage();
|
|
2438
|
+
this.setupPageHandlers();
|
|
2439
|
+
if (this.injectionScript) {
|
|
2440
|
+
logger3.debug("Injecting ReactCheck script into page...");
|
|
2441
|
+
await this.page.evaluateOnNewDocument(this.injectionScript);
|
|
2442
|
+
logger3.debug("Injection script registered");
|
|
2443
|
+
}
|
|
2444
|
+
this.emit("launched", void 0);
|
|
2445
|
+
logger3.info("Browser launched");
|
|
2446
|
+
await this.navigate(this.options.url);
|
|
2447
|
+
} catch (error) {
|
|
2448
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
2449
|
+
this.emit("error", err);
|
|
2450
|
+
throw err;
|
|
2451
|
+
}
|
|
2452
|
+
}
|
|
2453
|
+
/**
|
|
2454
|
+
* Set up page event handlers
|
|
2455
|
+
*/
|
|
2456
|
+
setupPageHandlers() {
|
|
2457
|
+
if (!this.page) return;
|
|
2458
|
+
this.page.on("console", (msg) => {
|
|
2459
|
+
this.emit("console", {
|
|
2460
|
+
type: msg.type(),
|
|
2461
|
+
text: msg.text()
|
|
2462
|
+
});
|
|
2463
|
+
});
|
|
2464
|
+
this.page.on("pageerror", (error) => {
|
|
2465
|
+
this.emit("error", error);
|
|
2466
|
+
});
|
|
2467
|
+
this.page.on("framenavigated", (frame) => {
|
|
2468
|
+
if (frame === this.page?.mainFrame()) {
|
|
2469
|
+
this.emit("navigated", { url: frame.url() });
|
|
2470
|
+
}
|
|
2471
|
+
});
|
|
2472
|
+
this.page.on("load", () => {
|
|
2473
|
+
this.emit("loaded", void 0);
|
|
2474
|
+
});
|
|
2475
|
+
}
|
|
2476
|
+
/**
|
|
2477
|
+
* Navigate to a URL with retry support
|
|
2478
|
+
* @param url - URL to navigate to
|
|
2479
|
+
* @param retries - Number of retries (default: 3)
|
|
2480
|
+
* @param retryDelay - Delay between retries in ms (default: 2000)
|
|
2481
|
+
*/
|
|
2482
|
+
async navigate(url, retries = 3, retryDelay = 2e3) {
|
|
2483
|
+
if (!this.page) {
|
|
2484
|
+
throw new Error("Browser not launched");
|
|
2485
|
+
}
|
|
2486
|
+
let lastError = null;
|
|
2487
|
+
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
2488
|
+
try {
|
|
2489
|
+
await this.page.goto(url, {
|
|
2490
|
+
waitUntil: "networkidle2",
|
|
2491
|
+
timeout: this.options.timeout
|
|
2492
|
+
});
|
|
2493
|
+
this.emit("navigated", { url });
|
|
2494
|
+
logger3.info(`Navigated to ${url}`);
|
|
2495
|
+
return;
|
|
2496
|
+
} catch (error) {
|
|
2497
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
2498
|
+
this.emit("error", lastError);
|
|
2499
|
+
if (lastError.message.includes("ERR_CONNECTION_REFUSED") && attempt < retries) {
|
|
2500
|
+
logger3.warn(`Connection refused, retrying in ${retryDelay}ms... (${attempt}/${retries})`);
|
|
2501
|
+
await new Promise((resolve2) => setTimeout(resolve2, retryDelay));
|
|
2502
|
+
continue;
|
|
2503
|
+
}
|
|
2504
|
+
throw lastError;
|
|
2505
|
+
}
|
|
2506
|
+
}
|
|
2507
|
+
throw lastError ?? new Error("Navigation failed");
|
|
2508
|
+
}
|
|
2509
|
+
/**
|
|
2510
|
+
* Execute script in page context
|
|
2511
|
+
* @param script - Script to execute
|
|
2512
|
+
* @returns Script result
|
|
2513
|
+
*/
|
|
2514
|
+
async evaluate(script) {
|
|
2515
|
+
if (!this.page) {
|
|
2516
|
+
throw new Error("Browser not launched");
|
|
2517
|
+
}
|
|
2518
|
+
return this.page.evaluate(script);
|
|
2519
|
+
}
|
|
2520
|
+
/**
|
|
2521
|
+
* Wait for selector
|
|
2522
|
+
* @param selector - CSS selector
|
|
2523
|
+
* @param timeout - Timeout in ms
|
|
2524
|
+
*/
|
|
2525
|
+
async waitForSelector(selector, timeout) {
|
|
2526
|
+
if (!this.page) {
|
|
2527
|
+
throw new Error("Browser not launched");
|
|
2528
|
+
}
|
|
2529
|
+
await this.page.waitForSelector(selector, {
|
|
2530
|
+
timeout: timeout ?? this.options.timeout
|
|
2531
|
+
});
|
|
2532
|
+
}
|
|
2533
|
+
/**
|
|
2534
|
+
* Take a screenshot
|
|
2535
|
+
* @param path - File path to save screenshot
|
|
2536
|
+
*/
|
|
2537
|
+
async screenshot(path) {
|
|
2538
|
+
if (!this.page) {
|
|
2539
|
+
throw new Error("Browser not launched");
|
|
2540
|
+
}
|
|
2541
|
+
await this.page.screenshot({ path, fullPage: true });
|
|
2542
|
+
logger3.info(`Screenshot saved to ${path}`);
|
|
2543
|
+
}
|
|
2544
|
+
/**
|
|
2545
|
+
* Reload the page
|
|
2546
|
+
*/
|
|
2547
|
+
async reload() {
|
|
2548
|
+
if (!this.page) {
|
|
2549
|
+
throw new Error("Browser not launched");
|
|
2550
|
+
}
|
|
2551
|
+
await this.page.reload({ waitUntil: "networkidle2" });
|
|
2552
|
+
}
|
|
2553
|
+
/**
|
|
2554
|
+
* Get current URL
|
|
2555
|
+
* @returns Current page URL
|
|
2556
|
+
*/
|
|
2557
|
+
getUrl() {
|
|
2558
|
+
return this.page?.url() ?? null;
|
|
2559
|
+
}
|
|
2560
|
+
/**
|
|
2561
|
+
* Close the browser
|
|
2562
|
+
*/
|
|
2563
|
+
async close() {
|
|
2564
|
+
if (this.browser) {
|
|
2565
|
+
await this.browser.close();
|
|
2566
|
+
this.browser = null;
|
|
2567
|
+
this.page = null;
|
|
2568
|
+
this.emit("closed", void 0);
|
|
2569
|
+
logger3.info("Browser closed");
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
/**
|
|
2573
|
+
* Check if browser is open
|
|
2574
|
+
* @returns true if browser is open
|
|
2575
|
+
*/
|
|
2576
|
+
isOpen() {
|
|
2577
|
+
return this.browser !== null && this.browser.connected;
|
|
2578
|
+
}
|
|
2579
|
+
/**
|
|
2580
|
+
* Get the page instance (for advanced usage). The return type is a
|
|
2581
|
+
* structural subset of Puppeteer's `Page`; pass the real type for the full
|
|
2582
|
+
* API: `getPage<import('puppeteer').Page>()`.
|
|
2583
|
+
* @returns Puppeteer page or null
|
|
2584
|
+
*/
|
|
2585
|
+
getPage() {
|
|
2586
|
+
return this.page;
|
|
2587
|
+
}
|
|
2588
|
+
/**
|
|
2589
|
+
* Get the browser instance (for advanced usage); see {@link getPage}
|
|
2590
|
+
* @returns Puppeteer browser or null
|
|
2591
|
+
*/
|
|
2592
|
+
getBrowser() {
|
|
2593
|
+
return this.browser;
|
|
2594
|
+
}
|
|
2595
|
+
};
|
|
2596
|
+
async function isPuppeteerAvailable() {
|
|
2597
|
+
return await loadPuppeteer() !== null;
|
|
2598
|
+
}
|
|
4574
2599
|
|
|
4575
2600
|
// src/browser/overlay.ts
|
|
4576
|
-
|
|
2601
|
+
function escapeOverlayHtml(value) {
|
|
2602
|
+
return String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
2603
|
+
}
|
|
2604
|
+
var DEFAULT_OVERLAY_THRESHOLDS = { warning: 20, critical: 50 };
|
|
2605
|
+
var DEFAULT_CONFIG = {
|
|
4577
2606
|
enabled: true,
|
|
4578
2607
|
highlightRenders: true,
|
|
4579
2608
|
showToolbar: true,
|
|
@@ -4622,10 +2651,14 @@ var Overlay = class _Overlay {
|
|
|
4622
2651
|
* @param config - Overlay configuration
|
|
4623
2652
|
*/
|
|
4624
2653
|
constructor(config = {}) {
|
|
4625
|
-
this.config = { ...
|
|
2654
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
4626
2655
|
}
|
|
4627
2656
|
/** Retry count for init */
|
|
4628
2657
|
initRetryCount = 0;
|
|
2658
|
+
/** Pending init retry timer (document.body not ready yet) */
|
|
2659
|
+
initRetryTimer = null;
|
|
2660
|
+
/** Aborts document-level listeners (drag handling) on destroy */
|
|
2661
|
+
documentListeners = null;
|
|
4629
2662
|
/**
|
|
4630
2663
|
* Initialize the overlay
|
|
4631
2664
|
*/
|
|
@@ -4634,9 +2667,12 @@ var Overlay = class _Overlay {
|
|
|
4634
2667
|
return;
|
|
4635
2668
|
}
|
|
4636
2669
|
if (!document.body) {
|
|
4637
|
-
if (this.initRetryCount < 10) {
|
|
2670
|
+
if (this.initRetryCount < 10 && this.initRetryTimer === null) {
|
|
4638
2671
|
this.initRetryCount++;
|
|
4639
|
-
setTimeout(() =>
|
|
2672
|
+
this.initRetryTimer = setTimeout(() => {
|
|
2673
|
+
this.initRetryTimer = null;
|
|
2674
|
+
this.init();
|
|
2675
|
+
}, 100);
|
|
4640
2676
|
}
|
|
4641
2677
|
return;
|
|
4642
2678
|
}
|
|
@@ -4667,6 +2703,14 @@ var Overlay = class _Overlay {
|
|
|
4667
2703
|
* Destroy the overlay
|
|
4668
2704
|
*/
|
|
4669
2705
|
destroy() {
|
|
2706
|
+
if (this.initRetryTimer !== null) {
|
|
2707
|
+
clearTimeout(this.initRetryTimer);
|
|
2708
|
+
this.initRetryTimer = null;
|
|
2709
|
+
}
|
|
2710
|
+
if (this.documentListeners) {
|
|
2711
|
+
this.documentListeners.abort();
|
|
2712
|
+
this.documentListeners = null;
|
|
2713
|
+
}
|
|
4670
2714
|
if (this.statsInterval) {
|
|
4671
2715
|
clearInterval(this.statsInterval);
|
|
4672
2716
|
this.statsInterval = null;
|
|
@@ -5601,6 +3645,8 @@ var Overlay = class _Overlay {
|
|
|
5601
3645
|
initialX = element.offsetLeft;
|
|
5602
3646
|
initialY = element.offsetTop;
|
|
5603
3647
|
});
|
|
3648
|
+
this.documentListeners ??= new AbortController();
|
|
3649
|
+
const { signal } = this.documentListeners;
|
|
5604
3650
|
document.addEventListener("mousemove", (e) => {
|
|
5605
3651
|
if (!isDragging) return;
|
|
5606
3652
|
const dx = e.clientX - startX;
|
|
@@ -5608,10 +3654,10 @@ var Overlay = class _Overlay {
|
|
|
5608
3654
|
element.style.left = `${initialX + dx}px`;
|
|
5609
3655
|
element.style.top = `${initialY + dy}px`;
|
|
5610
3656
|
element.style.right = "auto";
|
|
5611
|
-
});
|
|
3657
|
+
}, { signal });
|
|
5612
3658
|
document.addEventListener("mouseup", () => {
|
|
5613
3659
|
isDragging = false;
|
|
5614
|
-
});
|
|
3660
|
+
}, { signal });
|
|
5615
3661
|
}
|
|
5616
3662
|
/** Maximum number of highlights to show at once */
|
|
5617
3663
|
static MAX_HIGHLIGHTS = 50;
|
|
@@ -5797,8 +3843,17 @@ var Overlay = class _Overlay {
|
|
|
5797
3843
|
*/
|
|
5798
3844
|
getSeverity(render) {
|
|
5799
3845
|
if (!render.necessary) return "unnecessary";
|
|
5800
|
-
|
|
5801
|
-
|
|
3846
|
+
return this.severityForCount(render.renderCount);
|
|
3847
|
+
}
|
|
3848
|
+
/**
|
|
3849
|
+
* Severity for a render count using the configured thresholds (a count at or
|
|
3850
|
+
* above a threshold reaches that level, like the scanner's stats)
|
|
3851
|
+
* @param count - Render count
|
|
3852
|
+
*/
|
|
3853
|
+
severityForCount(count) {
|
|
3854
|
+
const { warning, critical } = this.config.thresholds ?? DEFAULT_OVERLAY_THRESHOLDS;
|
|
3855
|
+
if (count >= critical) return "critical";
|
|
3856
|
+
if (count >= warning) return "warning";
|
|
5802
3857
|
return "healthy";
|
|
5803
3858
|
}
|
|
5804
3859
|
/**
|
|
@@ -5826,8 +3881,9 @@ var Overlay = class _Overlay {
|
|
|
5826
3881
|
let warning = 0;
|
|
5827
3882
|
let healthy = 0;
|
|
5828
3883
|
for (const tracked of this.trackedComponents.values()) {
|
|
5829
|
-
|
|
5830
|
-
|
|
3884
|
+
const level = this.severityForCount(tracked.count);
|
|
3885
|
+
if (level === "critical") critical++;
|
|
3886
|
+
else if (level === "warning") warning++;
|
|
5831
3887
|
else healthy++;
|
|
5832
3888
|
}
|
|
5833
3889
|
const criticalEl = this.shadowRoot.getElementById("rc-critical");
|
|
@@ -5886,7 +3942,7 @@ var Overlay = class _Overlay {
|
|
|
5886
3942
|
<div class="component-item">
|
|
5887
3943
|
<div class="component-severity" style="background: ${color}"></div>
|
|
5888
3944
|
<div class="component-info">
|
|
5889
|
-
<div class="component-name">${name}</div>
|
|
3945
|
+
<div class="component-name">${escapeOverlayHtml(name)}</div>
|
|
5890
3946
|
<div class="component-meta">${avgTime}ms avg \xB7 ${timeStr}</div>
|
|
5891
3947
|
</div>
|
|
5892
3948
|
<div class="component-count" style="color: ${color}">${tracked.count}</div>
|
|
@@ -5911,11 +3967,11 @@ var Overlay = class _Overlay {
|
|
|
5911
3967
|
return;
|
|
5912
3968
|
}
|
|
5913
3969
|
list.innerHTML = this.renderChains.slice(0, 10).map((chain) => {
|
|
5914
|
-
const flow = chain.chain.map((c) => `<span class="chain-node">${c}</span>`).join('<span class="chain-arrow">\u2192</span>');
|
|
3970
|
+
const flow = chain.chain.map((c) => `<span class="chain-node">${escapeOverlayHtml(c)}</span>`).join('<span class="chain-arrow">\u2192</span>');
|
|
5915
3971
|
return `
|
|
5916
3972
|
<div class="chain-item">
|
|
5917
3973
|
<div class="chain-header">
|
|
5918
|
-
<span class="chain-trigger">${chain.trigger}</span>
|
|
3974
|
+
<span class="chain-trigger">${escapeOverlayHtml(chain.trigger)}</span>
|
|
5919
3975
|
<span class="chain-count">${chain.chain.length} components</span>
|
|
5920
3976
|
</div>
|
|
5921
3977
|
<div class="chain-flow">${flow}</div>
|
|
@@ -5995,7 +4051,7 @@ var Overlay = class _Overlay {
|
|
|
5995
4051
|
};
|
|
5996
4052
|
|
|
5997
4053
|
// src/browser/scanner.ts
|
|
5998
|
-
var
|
|
4054
|
+
var DEFAULT_CONFIG2 = {
|
|
5999
4055
|
trackUnnecessary: true,
|
|
6000
4056
|
fpsThreshold: 30,
|
|
6001
4057
|
highlightRenders: true,
|
|
@@ -6008,8 +4064,6 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6008
4064
|
running = false;
|
|
6009
4065
|
/** React version detected */
|
|
6010
4066
|
reactVersion = "unknown";
|
|
6011
|
-
/** Previous fiber states for comparison */
|
|
6012
|
-
prevFiberStates = /* @__PURE__ */ new WeakMap();
|
|
6013
4067
|
/** Component render counts */
|
|
6014
4068
|
renderCounts = /* @__PURE__ */ new Map();
|
|
6015
4069
|
/** Original DevTools hook methods */
|
|
@@ -6025,7 +4079,7 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6025
4079
|
*/
|
|
6026
4080
|
constructor(config = {}, win) {
|
|
6027
4081
|
super();
|
|
6028
|
-
this.config = { ...
|
|
4082
|
+
this.config = { ...DEFAULT_CONFIG2, ...config };
|
|
6029
4083
|
this.win = win ?? (typeof window !== "undefined" ? window : {});
|
|
6030
4084
|
}
|
|
6031
4085
|
/**
|
|
@@ -6036,6 +4090,9 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6036
4090
|
* @returns DOM Element or null
|
|
6037
4091
|
*/
|
|
6038
4092
|
getDOMElement(fiber) {
|
|
4093
|
+
if (typeof Element === "undefined") {
|
|
4094
|
+
return null;
|
|
4095
|
+
}
|
|
6039
4096
|
if (fiber.stateNode instanceof Element) {
|
|
6040
4097
|
return fiber.stateNode;
|
|
6041
4098
|
}
|
|
@@ -6112,7 +4169,6 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6112
4169
|
*/
|
|
6113
4170
|
reset() {
|
|
6114
4171
|
this.renderCounts.clear();
|
|
6115
|
-
this.prevFiberStates = /* @__PURE__ */ new WeakMap();
|
|
6116
4172
|
}
|
|
6117
4173
|
/**
|
|
6118
4174
|
* Hook into React DevTools global hook
|
|
@@ -6123,12 +4179,13 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6123
4179
|
this.installHook();
|
|
6124
4180
|
return;
|
|
6125
4181
|
}
|
|
6126
|
-
|
|
4182
|
+
const original = hook.onCommitFiberRoot;
|
|
4183
|
+
this.originalOnCommitFiberRoot = original;
|
|
6127
4184
|
hook.onCommitFiberRoot = (rendererID, root, priorityLevel) => {
|
|
6128
|
-
|
|
6129
|
-
|
|
4185
|
+
original.call(hook, rendererID, root, priorityLevel);
|
|
4186
|
+
if (this.running) {
|
|
4187
|
+
this.processCommit(root.current);
|
|
6130
4188
|
}
|
|
6131
|
-
this.processCommit(root.current);
|
|
6132
4189
|
};
|
|
6133
4190
|
this.reactVersion = this.detectReactVersion(hook);
|
|
6134
4191
|
this.emit("ready", { reactVersion: this.reactVersion });
|
|
@@ -6146,7 +4203,9 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6146
4203
|
return id;
|
|
6147
4204
|
},
|
|
6148
4205
|
onCommitFiberRoot: (_rendererID, root, _priorityLevel) => {
|
|
6149
|
-
this.
|
|
4206
|
+
if (this.running) {
|
|
4207
|
+
this.processCommit(root.current);
|
|
4208
|
+
}
|
|
6150
4209
|
},
|
|
6151
4210
|
onCommitFiberUnmount: () => {
|
|
6152
4211
|
}
|
|
@@ -6180,52 +4239,63 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6180
4239
|
return "unknown";
|
|
6181
4240
|
}
|
|
6182
4241
|
/**
|
|
6183
|
-
* Process a fiber commit (public for IIFE hook integration)
|
|
6184
|
-
*
|
|
4242
|
+
* Process a fiber commit (public for IIFE hook integration).
|
|
4243
|
+
*
|
|
4244
|
+
* Only components that actually rendered in this commit are reported: React
|
|
4245
|
+
* reuses untouched subtrees (their `child` pointer is shared with the
|
|
4246
|
+
* alternate) and bailed-out components do not get the `PerformedWork` flag.
|
|
4247
|
+
* @param rootFiber - Root fiber of the committed tree (`root.current`)
|
|
6185
4248
|
*/
|
|
6186
4249
|
processCommit(rootFiber) {
|
|
6187
|
-
|
|
6188
|
-
|
|
6189
|
-
|
|
6190
|
-
|
|
6191
|
-
|
|
6192
|
-
|
|
6193
|
-
|
|
6194
|
-
|
|
6195
|
-
|
|
6196
|
-
|
|
6197
|
-
|
|
6198
|
-
|
|
4250
|
+
const stack = [{ fiber: rootFiber, parent: null }];
|
|
4251
|
+
while (stack.length > 0) {
|
|
4252
|
+
const item = stack.pop();
|
|
4253
|
+
if (!item) continue;
|
|
4254
|
+
const { fiber } = item;
|
|
4255
|
+
let parent = item.parent;
|
|
4256
|
+
if (fiber.sibling) {
|
|
4257
|
+
stack.push({ fiber: fiber.sibling, parent: item.parent });
|
|
4258
|
+
}
|
|
4259
|
+
if (isUserComponent(fiber)) {
|
|
4260
|
+
if (fiber.tag !== FiberTag.MemoComponent && didFiberRender(fiber)) {
|
|
4261
|
+
this.processFiber(fiber, parent);
|
|
4262
|
+
}
|
|
4263
|
+
parent = getComponentName(fiber);
|
|
4264
|
+
}
|
|
4265
|
+
const alternate = fiber.alternate;
|
|
4266
|
+
if (alternate && fiber !== rootFiber && fiber.child === alternate.child) {
|
|
4267
|
+
continue;
|
|
4268
|
+
}
|
|
4269
|
+
if (fiber.child) {
|
|
4270
|
+
stack.push({ fiber: fiber.child, parent });
|
|
4271
|
+
}
|
|
6199
4272
|
}
|
|
6200
|
-
this.walkFiber(fiber.child, parent);
|
|
6201
|
-
this.walkFiber(fiber.sibling, parent);
|
|
6202
4273
|
}
|
|
6203
4274
|
/**
|
|
6204
4275
|
* Process a single fiber
|
|
6205
4276
|
* @param fiber - Fiber to process
|
|
6206
4277
|
* @param parent - Parent component name
|
|
6207
4278
|
*/
|
|
6208
|
-
processFiber(fiber,
|
|
4279
|
+
processFiber(fiber, parent) {
|
|
6209
4280
|
const componentName = getComponentName(fiber);
|
|
6210
4281
|
if (this.shouldFilterComponent(componentName)) {
|
|
6211
4282
|
return;
|
|
6212
4283
|
}
|
|
6213
|
-
const
|
|
6214
|
-
const phase =
|
|
4284
|
+
const alternate = fiber.alternate ?? null;
|
|
4285
|
+
const phase = alternate ? "update" : "mount";
|
|
6215
4286
|
const renderInfo = createRenderInfo(
|
|
6216
4287
|
fiber,
|
|
6217
4288
|
phase,
|
|
6218
|
-
|
|
6219
|
-
|
|
4289
|
+
alternate ? alternate.memoizedProps ?? {} : null,
|
|
4290
|
+
alternate ? alternate.memoizedState : void 0
|
|
6220
4291
|
);
|
|
6221
4292
|
const currentCount = this.renderCounts.get(componentName) ?? 0;
|
|
6222
4293
|
const newCount = currentCount + 1;
|
|
6223
4294
|
this.renderCounts.set(componentName, newCount);
|
|
6224
4295
|
renderInfo.renderCount = newCount;
|
|
6225
|
-
|
|
6226
|
-
|
|
6227
|
-
|
|
6228
|
-
});
|
|
4296
|
+
if (parent) {
|
|
4297
|
+
renderInfo.parent = parent;
|
|
4298
|
+
}
|
|
6229
4299
|
const domElement = this.getDOMElement(fiber);
|
|
6230
4300
|
if (this.overlay && this.config.highlightRenders) {
|
|
6231
4301
|
if (domElement) {
|
|
@@ -6264,13 +4334,7 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6264
4334
|
* @returns true if matches
|
|
6265
4335
|
*/
|
|
6266
4336
|
matchPattern(name, pattern) {
|
|
6267
|
-
|
|
6268
|
-
try {
|
|
6269
|
-
const regex = new RegExp(`^${regexPattern}$`);
|
|
6270
|
-
return regex.test(name);
|
|
6271
|
-
} catch {
|
|
6272
|
-
return false;
|
|
6273
|
-
}
|
|
4337
|
+
return matchComponentPattern(name, pattern);
|
|
6274
4338
|
}
|
|
6275
4339
|
/**
|
|
6276
4340
|
* Get current configuration
|
|
@@ -6298,6 +4362,15 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6298
4362
|
* @returns React version string
|
|
6299
4363
|
*/
|
|
6300
4364
|
getReactVersion() {
|
|
4365
|
+
if (this.reactVersion.startsWith("unknown")) {
|
|
4366
|
+
const hook = this.win.__REACT_DEVTOOLS_GLOBAL_HOOK__;
|
|
4367
|
+
if (hook?.renderers instanceof Map) {
|
|
4368
|
+
const version = this.detectReactVersion(hook);
|
|
4369
|
+
if (version !== "unknown") {
|
|
4370
|
+
this.reactVersion = version;
|
|
4371
|
+
}
|
|
4372
|
+
}
|
|
4373
|
+
}
|
|
6301
4374
|
return this.reactVersion;
|
|
6302
4375
|
}
|
|
6303
4376
|
/**
|
|
@@ -6317,7 +4390,10 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6317
4390
|
}
|
|
6318
4391
|
};
|
|
6319
4392
|
|
|
6320
|
-
// src/browser/
|
|
4393
|
+
// src/browser/injector.ts
|
|
4394
|
+
var MAX_QUEUED_MESSAGES = 5e3;
|
|
4395
|
+
var MAX_PENDING_COMMITS = 500;
|
|
4396
|
+
var RECONNECT_DELAY_MS = 2e3;
|
|
6321
4397
|
var ReactCheckInjector = class {
|
|
6322
4398
|
/** Browser scanner instance */
|
|
6323
4399
|
scanner;
|
|
@@ -6331,36 +4407,71 @@ var ReactCheckInjector = class {
|
|
|
6331
4407
|
reconnectTimeout = null;
|
|
6332
4408
|
/** Whether initialized */
|
|
6333
4409
|
initialized = false;
|
|
4410
|
+
/** Whether destroyed (no more reconnects, commits are ignored) */
|
|
4411
|
+
destroyed = false;
|
|
4412
|
+
/** Whether commit processing is paused (CLI sent `stop`) */
|
|
4413
|
+
paused = false;
|
|
4414
|
+
/** Commits received before `init()` */
|
|
4415
|
+
pendingCommits = [];
|
|
4416
|
+
/** Message queue for messages sent before connection */
|
|
4417
|
+
messageQueue = [];
|
|
4418
|
+
/** requestAnimationFrame handle for FPS measurement */
|
|
4419
|
+
rafHandle = null;
|
|
4420
|
+
/** Restores the React DevTools hook to its state before installation */
|
|
4421
|
+
restoreHook = null;
|
|
4422
|
+
/** Window reference */
|
|
4423
|
+
win;
|
|
4424
|
+
/** React version last reported to the CLI in a `ready` message */
|
|
4425
|
+
reportedReactVersion = "unknown";
|
|
6334
4426
|
/**
|
|
6335
4427
|
* Create the injector
|
|
4428
|
+
* @param win - Window object (defaults to the global window)
|
|
6336
4429
|
*/
|
|
6337
|
-
constructor() {
|
|
6338
|
-
|
|
6339
|
-
this.wsPort = win.__REACTCHECK_PORT__ ?? 3099;
|
|
4430
|
+
constructor(win) {
|
|
4431
|
+
this.win = win ?? window;
|
|
4432
|
+
this.wsPort = this.win.__REACTCHECK_PORT__ ?? 3099;
|
|
6340
4433
|
this.scanner = new BrowserScanner({
|
|
6341
4434
|
trackUnnecessary: true,
|
|
6342
4435
|
highlightRenders: true,
|
|
6343
4436
|
animationSpeed: "fast"
|
|
6344
|
-
}, win);
|
|
4437
|
+
}, this.win);
|
|
6345
4438
|
this.overlay = new Overlay({
|
|
6346
4439
|
enabled: true,
|
|
6347
4440
|
highlightRenders: true,
|
|
6348
4441
|
showToolbar: true
|
|
6349
4442
|
});
|
|
6350
4443
|
}
|
|
4444
|
+
/**
|
|
4445
|
+
* Feed a committed fiber root to the scanner. Called from the React DevTools
|
|
4446
|
+
* hook installed by {@link installReactCheck}.
|
|
4447
|
+
* @param root - Fiber root passed to `onCommitFiberRoot`
|
|
4448
|
+
*/
|
|
4449
|
+
handleCommit(root) {
|
|
4450
|
+
if (this.destroyed || this.paused || !root?.current) return;
|
|
4451
|
+
if (!this.initialized) {
|
|
4452
|
+
if (this.pendingCommits.length >= MAX_PENDING_COMMITS) {
|
|
4453
|
+
this.pendingCommits.shift();
|
|
4454
|
+
}
|
|
4455
|
+
this.pendingCommits.push(root.current);
|
|
4456
|
+
return;
|
|
4457
|
+
}
|
|
4458
|
+
this.scanner.processCommit(root.current);
|
|
4459
|
+
}
|
|
6351
4460
|
/**
|
|
6352
4461
|
* Initialize the injector
|
|
6353
4462
|
*/
|
|
6354
4463
|
init() {
|
|
6355
|
-
if (this.initialized) return;
|
|
4464
|
+
if (this.initialized || this.destroyed) return;
|
|
6356
4465
|
this.initialized = true;
|
|
6357
4466
|
this.overlay.init();
|
|
6358
4467
|
this.setupScannerEvents();
|
|
6359
4468
|
this.connect();
|
|
6360
|
-
const
|
|
6361
|
-
|
|
6362
|
-
|
|
4469
|
+
const pending = this.pendingCommits;
|
|
4470
|
+
this.pendingCommits = [];
|
|
4471
|
+
for (const fiber of pending) {
|
|
4472
|
+
this.scanner.processCommit(fiber);
|
|
6363
4473
|
}
|
|
4474
|
+
this.startFpsMeasurement();
|
|
6364
4475
|
console.log("[ReactCheck] Initialized");
|
|
6365
4476
|
}
|
|
6366
4477
|
/**
|
|
@@ -6368,6 +4479,12 @@ var ReactCheckInjector = class {
|
|
|
6368
4479
|
*/
|
|
6369
4480
|
setupScannerEvents() {
|
|
6370
4481
|
this.scanner.on("render", ({ render, element }) => {
|
|
4482
|
+
if (this.reportedReactVersion.startsWith("unknown") && this.ws?.readyState === WebSocket.OPEN) {
|
|
4483
|
+
const version = this.scanner.getReactVersion();
|
|
4484
|
+
if (!version.startsWith("unknown")) {
|
|
4485
|
+
this.sendReady();
|
|
4486
|
+
}
|
|
4487
|
+
}
|
|
6371
4488
|
this.send({ type: "render", payload: render });
|
|
6372
4489
|
this.overlay.recordRender(render);
|
|
6373
4490
|
if (element) {
|
|
@@ -6384,28 +4501,55 @@ var ReactCheckInjector = class {
|
|
|
6384
4501
|
});
|
|
6385
4502
|
});
|
|
6386
4503
|
}
|
|
4504
|
+
/**
|
|
4505
|
+
* Measure frames per second with requestAnimationFrame and report it
|
|
4506
|
+
*/
|
|
4507
|
+
startFpsMeasurement() {
|
|
4508
|
+
const raf = this.win.requestAnimationFrame;
|
|
4509
|
+
if (typeof raf !== "function") return;
|
|
4510
|
+
let frames = 0;
|
|
4511
|
+
let windowStart = Date.now();
|
|
4512
|
+
const tick = () => {
|
|
4513
|
+
if (this.destroyed) return;
|
|
4514
|
+
frames++;
|
|
4515
|
+
const now = Date.now();
|
|
4516
|
+
const elapsed = now - windowStart;
|
|
4517
|
+
if (elapsed >= 1e3) {
|
|
4518
|
+
const fps = Math.round(frames * 1e3 / elapsed);
|
|
4519
|
+
frames = 0;
|
|
4520
|
+
windowStart = now;
|
|
4521
|
+
this.overlay.updateFps(fps);
|
|
4522
|
+
if (!this.paused) {
|
|
4523
|
+
this.send({ type: "fps", payload: fps });
|
|
4524
|
+
}
|
|
4525
|
+
}
|
|
4526
|
+
this.rafHandle = raf.call(this.win, tick);
|
|
4527
|
+
};
|
|
4528
|
+
this.rafHandle = raf.call(this.win, tick);
|
|
4529
|
+
}
|
|
6387
4530
|
/**
|
|
6388
4531
|
* Connect to CLI WebSocket server
|
|
6389
4532
|
*/
|
|
6390
4533
|
connect() {
|
|
4534
|
+
if (this.destroyed) return;
|
|
6391
4535
|
if (this.ws) {
|
|
4536
|
+
this.detachSocket(this.ws);
|
|
6392
4537
|
this.ws.close();
|
|
4538
|
+
this.ws = null;
|
|
6393
4539
|
}
|
|
6394
4540
|
try {
|
|
6395
|
-
|
|
6396
|
-
this.ws
|
|
4541
|
+
const ws = new WebSocket(`ws://localhost:${this.wsPort}`);
|
|
4542
|
+
this.ws = ws;
|
|
4543
|
+
ws.onopen = () => {
|
|
6397
4544
|
console.log("[ReactCheck] Connected to CLI");
|
|
6398
4545
|
if (this.reconnectTimeout) {
|
|
6399
4546
|
clearTimeout(this.reconnectTimeout);
|
|
6400
4547
|
this.reconnectTimeout = null;
|
|
6401
4548
|
}
|
|
6402
|
-
this.
|
|
6403
|
-
type: "ready",
|
|
6404
|
-
payload: { reactVersion: this.scanner.getReactVersion() }
|
|
6405
|
-
});
|
|
4549
|
+
this.sendReady();
|
|
6406
4550
|
this.flushMessageQueue();
|
|
6407
4551
|
};
|
|
6408
|
-
|
|
4552
|
+
ws.onmessage = (event) => {
|
|
6409
4553
|
try {
|
|
6410
4554
|
const message = JSON.parse(event.data);
|
|
6411
4555
|
this.handleMessage(message);
|
|
@@ -6413,10 +4557,10 @@ var ReactCheckInjector = class {
|
|
|
6413
4557
|
console.warn("[ReactCheck] Invalid message:", error);
|
|
6414
4558
|
}
|
|
6415
4559
|
};
|
|
6416
|
-
|
|
4560
|
+
ws.onerror = (error) => {
|
|
6417
4561
|
console.warn("[ReactCheck] WebSocket error:", error);
|
|
6418
4562
|
};
|
|
6419
|
-
|
|
4563
|
+
ws.onclose = () => {
|
|
6420
4564
|
console.log("[ReactCheck] Disconnected from CLI");
|
|
6421
4565
|
this.scheduleReconnect();
|
|
6422
4566
|
};
|
|
@@ -6425,16 +4569,28 @@ var ReactCheckInjector = class {
|
|
|
6425
4569
|
this.scheduleReconnect();
|
|
6426
4570
|
}
|
|
6427
4571
|
}
|
|
4572
|
+
/**
|
|
4573
|
+
* Remove event handlers from a socket so that closing it does not trigger
|
|
4574
|
+
* reconnects
|
|
4575
|
+
* @param ws - Socket
|
|
4576
|
+
*/
|
|
4577
|
+
detachSocket(ws) {
|
|
4578
|
+
ws.onopen = null;
|
|
4579
|
+
ws.onmessage = null;
|
|
4580
|
+
ws.onerror = null;
|
|
4581
|
+
ws.onclose = null;
|
|
4582
|
+
}
|
|
6428
4583
|
/**
|
|
6429
4584
|
* Schedule a reconnection attempt
|
|
6430
4585
|
*/
|
|
6431
4586
|
scheduleReconnect() {
|
|
6432
|
-
if (this.reconnectTimeout) return;
|
|
4587
|
+
if (this.reconnectTimeout || this.destroyed) return;
|
|
6433
4588
|
this.reconnectTimeout = setTimeout(() => {
|
|
6434
4589
|
this.reconnectTimeout = null;
|
|
4590
|
+
if (this.destroyed) return;
|
|
6435
4591
|
console.log("[ReactCheck] Attempting to reconnect...");
|
|
6436
4592
|
this.connect();
|
|
6437
|
-
},
|
|
4593
|
+
}, RECONNECT_DELAY_MS);
|
|
6438
4594
|
}
|
|
6439
4595
|
/**
|
|
6440
4596
|
* Handle message from CLI
|
|
@@ -6443,11 +4599,11 @@ var ReactCheckInjector = class {
|
|
|
6443
4599
|
handleMessage(message) {
|
|
6444
4600
|
switch (message.type) {
|
|
6445
4601
|
case "start":
|
|
6446
|
-
this.
|
|
4602
|
+
this.paused = false;
|
|
6447
4603
|
this.overlay.show();
|
|
6448
4604
|
break;
|
|
6449
4605
|
case "stop":
|
|
6450
|
-
this.
|
|
4606
|
+
this.paused = true;
|
|
6451
4607
|
break;
|
|
6452
4608
|
case "reset":
|
|
6453
4609
|
this.scanner.reset();
|
|
@@ -6501,17 +4657,33 @@ var ReactCheckInjector = class {
|
|
|
6501
4657
|
if (config.highlightRenders !== void 0) {
|
|
6502
4658
|
this.overlay.configure({ highlightRenders: config.highlightRenders });
|
|
6503
4659
|
}
|
|
4660
|
+
const thresholds = config.thresholds;
|
|
4661
|
+
if (thresholds && Number.isFinite(thresholds.warning) && Number.isFinite(thresholds.critical)) {
|
|
4662
|
+
this.overlay.configure({ thresholds: { warning: thresholds.warning, critical: thresholds.critical } });
|
|
4663
|
+
}
|
|
4664
|
+
}
|
|
4665
|
+
/**
|
|
4666
|
+
* Send a `ready` message with the React version detected so far
|
|
4667
|
+
*/
|
|
4668
|
+
sendReady() {
|
|
4669
|
+
this.reportedReactVersion = this.scanner.getReactVersion();
|
|
4670
|
+
this.send({
|
|
4671
|
+
type: "ready",
|
|
4672
|
+
payload: { reactVersion: this.reportedReactVersion }
|
|
4673
|
+
});
|
|
6504
4674
|
}
|
|
6505
|
-
/** Message queue for messages sent before connection */
|
|
6506
|
-
messageQueue = [];
|
|
6507
4675
|
/**
|
|
6508
4676
|
* Send message to CLI
|
|
6509
4677
|
* @param message - Browser message
|
|
6510
4678
|
*/
|
|
6511
4679
|
send(message) {
|
|
4680
|
+
if (this.destroyed) return;
|
|
6512
4681
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
6513
4682
|
this.ws.send(JSON.stringify(message));
|
|
6514
4683
|
} else {
|
|
4684
|
+
if (this.messageQueue.length >= MAX_QUEUED_MESSAGES) {
|
|
4685
|
+
this.messageQueue.shift();
|
|
4686
|
+
}
|
|
6515
4687
|
this.messageQueue.push(message);
|
|
6516
4688
|
}
|
|
6517
4689
|
}
|
|
@@ -6527,160 +4699,240 @@ var ReactCheckInjector = class {
|
|
|
6527
4699
|
}
|
|
6528
4700
|
}
|
|
6529
4701
|
/**
|
|
6530
|
-
*
|
|
4702
|
+
* Register a function that restores the DevTools hook on destroy
|
|
4703
|
+
* @param restore - Restore callback
|
|
4704
|
+
*/
|
|
4705
|
+
setHookRestorer(restore) {
|
|
4706
|
+
this.restoreHook = restore;
|
|
4707
|
+
}
|
|
4708
|
+
/**
|
|
4709
|
+
* Destroy the injector: stops reconnecting, closes the socket, restores the
|
|
4710
|
+
* React DevTools hook, removes the overlay and cancels all timers.
|
|
6531
4711
|
*/
|
|
6532
4712
|
destroy() {
|
|
4713
|
+
if (this.destroyed) return;
|
|
4714
|
+
this.destroyed = true;
|
|
6533
4715
|
if (this.reconnectTimeout) {
|
|
6534
4716
|
clearTimeout(this.reconnectTimeout);
|
|
4717
|
+
this.reconnectTimeout = null;
|
|
4718
|
+
}
|
|
4719
|
+
if (this.rafHandle !== null) {
|
|
4720
|
+
const caf = this.win.cancelAnimationFrame;
|
|
4721
|
+
if (typeof caf === "function") {
|
|
4722
|
+
caf.call(this.win, this.rafHandle);
|
|
4723
|
+
}
|
|
4724
|
+
this.rafHandle = null;
|
|
6535
4725
|
}
|
|
6536
4726
|
if (this.ws) {
|
|
4727
|
+
this.detachSocket(this.ws);
|
|
6537
4728
|
this.ws.close();
|
|
4729
|
+
this.ws = null;
|
|
6538
4730
|
}
|
|
4731
|
+
if (this.restoreHook) {
|
|
4732
|
+
this.restoreHook();
|
|
4733
|
+
this.restoreHook = null;
|
|
4734
|
+
}
|
|
4735
|
+
this.pendingCommits = [];
|
|
4736
|
+
this.messageQueue = [];
|
|
6539
4737
|
this.scanner.stop();
|
|
4738
|
+
this.scanner.removeAllListeners();
|
|
6540
4739
|
this.overlay.destroy();
|
|
6541
4740
|
this.initialized = false;
|
|
6542
4741
|
}
|
|
6543
4742
|
};
|
|
6544
|
-
|
|
6545
|
-
const currentUrl =
|
|
4743
|
+
function installReactCheck(win) {
|
|
4744
|
+
const currentUrl = win.location.href;
|
|
6546
4745
|
if (currentUrl === "about:blank" || currentUrl.startsWith("chrome://") || currentUrl.startsWith("chrome-extension://") || currentUrl.startsWith("devtools://")) {
|
|
6547
|
-
return;
|
|
4746
|
+
return null;
|
|
6548
4747
|
}
|
|
6549
|
-
const win = window;
|
|
6550
4748
|
if (win.__REACTCHECK_INJECTED__) {
|
|
6551
|
-
return;
|
|
4749
|
+
return null;
|
|
6552
4750
|
}
|
|
6553
4751
|
win.__REACTCHECK_INJECTED__ = true;
|
|
6554
|
-
const injector = new ReactCheckInjector();
|
|
6555
|
-
const
|
|
6556
|
-
|
|
6557
|
-
const handleCommit = (root) => {
|
|
6558
|
-
if (injectorReady) {
|
|
6559
|
-
const scanner = injector.scanner;
|
|
6560
|
-
if (scanner) {
|
|
6561
|
-
const fiber = root.current;
|
|
6562
|
-
scanner.processCommit(fiber);
|
|
6563
|
-
}
|
|
6564
|
-
} else {
|
|
6565
|
-
pendingCommits.push({ rendererID: 0, root });
|
|
6566
|
-
}
|
|
6567
|
-
};
|
|
6568
|
-
const processPendingCommits = () => {
|
|
6569
|
-
injectorReady = true;
|
|
6570
|
-
const scanner = injector.scanner;
|
|
6571
|
-
if (scanner) {
|
|
6572
|
-
for (const { root } of pendingCommits) {
|
|
6573
|
-
scanner.processCommit(root.current);
|
|
6574
|
-
}
|
|
6575
|
-
pendingCommits.length = 0;
|
|
6576
|
-
}
|
|
6577
|
-
};
|
|
6578
|
-
if (!win.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
|
|
4752
|
+
const injector = new ReactCheckInjector(win);
|
|
4753
|
+
const existingHook = win.__REACT_DEVTOOLS_GLOBAL_HOOK__;
|
|
4754
|
+
if (!existingHook) {
|
|
6579
4755
|
const hook = {
|
|
6580
4756
|
renderers: /* @__PURE__ */ new Map(),
|
|
6581
4757
|
supportsFiber: true,
|
|
6582
|
-
inject
|
|
6583
|
-
const id =
|
|
6584
|
-
|
|
4758
|
+
inject(renderer) {
|
|
4759
|
+
const id = hook.renderers.size + 1;
|
|
4760
|
+
hook.renderers.set(id, renderer);
|
|
6585
4761
|
return id;
|
|
6586
4762
|
},
|
|
6587
|
-
onCommitFiberRoot
|
|
6588
|
-
handleCommit(root);
|
|
4763
|
+
onCommitFiberRoot(_rendererID, root) {
|
|
4764
|
+
injector.handleCommit(root);
|
|
6589
4765
|
},
|
|
6590
|
-
onCommitFiberUnmount
|
|
4766
|
+
onCommitFiberUnmount() {
|
|
6591
4767
|
}
|
|
6592
4768
|
};
|
|
6593
4769
|
win.__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook;
|
|
4770
|
+
injector.setHookRestorer(() => {
|
|
4771
|
+
hook.onCommitFiberRoot = () => {
|
|
4772
|
+
};
|
|
4773
|
+
});
|
|
6594
4774
|
console.log("[ReactCheck] DevTools hook installed");
|
|
6595
4775
|
} else {
|
|
6596
|
-
const
|
|
6597
|
-
const originalOnCommit = existingHook.onCommitFiberRoot.bind(existingHook);
|
|
4776
|
+
const originalOnCommit = existingHook.onCommitFiberRoot;
|
|
6598
4777
|
existingHook.onCommitFiberRoot = (rendererID, root, priorityLevel) => {
|
|
6599
|
-
originalOnCommit(rendererID, root, priorityLevel);
|
|
6600
|
-
handleCommit(root);
|
|
4778
|
+
originalOnCommit.call(existingHook, rendererID, root, priorityLevel);
|
|
4779
|
+
injector.handleCommit(root);
|
|
6601
4780
|
};
|
|
4781
|
+
injector.setHookRestorer(() => {
|
|
4782
|
+
existingHook.onCommitFiberRoot = originalOnCommit;
|
|
4783
|
+
});
|
|
6602
4784
|
console.log("[ReactCheck] Wrapped existing DevTools hook");
|
|
6603
4785
|
}
|
|
6604
|
-
|
|
6605
|
-
|
|
6606
|
-
|
|
6607
|
-
if (document.readyState === "loading") {
|
|
6608
|
-
document.addEventListener("DOMContentLoaded", () => {
|
|
4786
|
+
const doc = win.document;
|
|
4787
|
+
if (doc.readyState === "loading") {
|
|
4788
|
+
doc.addEventListener("DOMContentLoaded", () => {
|
|
6609
4789
|
injector.init();
|
|
6610
|
-
});
|
|
4790
|
+
}, { once: true });
|
|
6611
4791
|
} else {
|
|
6612
4792
|
injector.init();
|
|
6613
4793
|
}
|
|
6614
|
-
|
|
6615
|
-
|
|
6616
|
-
|
|
6617
|
-
// src/index.ts
|
|
6618
|
-
var VERSION = "1.0.0";
|
|
6619
|
-
function createScanner(options = {}) {
|
|
6620
|
-
return new Scanner({
|
|
6621
|
-
thresholds: {
|
|
6622
|
-
critical: options.thresholds?.critical ?? 50,
|
|
6623
|
-
warning: options.thresholds?.warning ?? 20
|
|
6624
|
-
}
|
|
6625
|
-
});
|
|
6626
|
-
}
|
|
6627
|
-
function createReportGenerator(options = {}) {
|
|
6628
|
-
return new ReportGenerator({
|
|
6629
|
-
enabled: true,
|
|
6630
|
-
formats: options.formats ?? ["html", "json"],
|
|
6631
|
-
output: options.output ?? "./reactcheck-reports",
|
|
6632
|
-
includeSourceCode: options.includeSourceCode ?? false
|
|
6633
|
-
});
|
|
4794
|
+
win.__REACTCHECK__ = injector;
|
|
4795
|
+
return injector;
|
|
6634
4796
|
}
|
|
4797
|
+
|
|
4798
|
+
// src/version.ts
|
|
4799
|
+
var VERSION = "1.3.1";
|
|
4800
|
+
|
|
4801
|
+
// src/quick-scan.ts
|
|
6635
4802
|
async function quickScan(url, options = {}) {
|
|
6636
|
-
|
|
6637
|
-
const puppeteerAvailable = await isPuppeteerAvailable2();
|
|
6638
|
-
if (!puppeteerAvailable) {
|
|
4803
|
+
if (!await isPuppeteerAvailable()) {
|
|
6639
4804
|
throw new ReactCheckError(
|
|
6640
4805
|
"BROWSER_LAUNCH_FAILED" /* BROWSER_LAUNCH_FAILED */,
|
|
6641
4806
|
"Puppeteer is required for quickScan. Install it with: npm install puppeteer"
|
|
6642
4807
|
);
|
|
6643
4808
|
}
|
|
6644
|
-
const
|
|
6645
|
-
url,
|
|
6646
|
-
headless: options.headless ?? true
|
|
6647
|
-
});
|
|
4809
|
+
const target = url.includes("://") ? url : `http://${url}`;
|
|
6648
4810
|
const duration = options.duration ?? 3e4;
|
|
6649
|
-
|
|
6650
|
-
|
|
6651
|
-
const
|
|
6652
|
-
|
|
6653
|
-
|
|
6654
|
-
|
|
6655
|
-
|
|
6656
|
-
|
|
6657
|
-
|
|
6658
|
-
|
|
6659
|
-
|
|
6660
|
-
|
|
4811
|
+
const startTime = Date.now();
|
|
4812
|
+
const critical = options.thresholds?.critical ?? 50;
|
|
4813
|
+
const warning = options.thresholds?.warning ?? 20;
|
|
4814
|
+
const scanner = new Scanner({
|
|
4815
|
+
thresholds: {
|
|
4816
|
+
critical,
|
|
4817
|
+
warning,
|
|
4818
|
+
...options.thresholds?.fps !== void 0 ? { fps: options.thresholds.fps } : {}
|
|
4819
|
+
},
|
|
4820
|
+
config: {
|
|
4821
|
+
...options.include ? { include: options.include } : {},
|
|
4822
|
+
...options.exclude ? { exclude: options.exclude } : {}
|
|
4823
|
+
}
|
|
4824
|
+
});
|
|
4825
|
+
const chains = [];
|
|
4826
|
+
scanner.on("chain", (chain) => {
|
|
4827
|
+
chains.push(chain);
|
|
6661
4828
|
});
|
|
6662
|
-
|
|
6663
|
-
|
|
4829
|
+
const wsServer = new WebSocketServer(options.port ?? 0);
|
|
4830
|
+
let launcher = null;
|
|
4831
|
+
try {
|
|
4832
|
+
await wsServer.start();
|
|
4833
|
+
wsServer.on("connection", (client) => {
|
|
4834
|
+
handleBrowserMessages(client, (message) => {
|
|
4835
|
+
switch (message.type) {
|
|
4836
|
+
case "render":
|
|
4837
|
+
scanner.addRender(message.payload);
|
|
4838
|
+
break;
|
|
4839
|
+
case "fps":
|
|
4840
|
+
scanner.recordFps(message.payload);
|
|
4841
|
+
break;
|
|
4842
|
+
case "ready":
|
|
4843
|
+
client.send(JSON.stringify({ type: "start" }));
|
|
4844
|
+
client.send(JSON.stringify({ type: "config", payload: { thresholds: { warning, critical } } }));
|
|
4845
|
+
break;
|
|
4846
|
+
default:
|
|
4847
|
+
break;
|
|
4848
|
+
}
|
|
4849
|
+
});
|
|
4850
|
+
});
|
|
4851
|
+
scanner.start();
|
|
4852
|
+
launcher = new BrowserLauncher({
|
|
4853
|
+
url: target,
|
|
4854
|
+
headless: options.headless ?? true,
|
|
4855
|
+
wsPort: wsServer.getPort(),
|
|
4856
|
+
...options.browserArgs ? { args: options.browserArgs } : {}
|
|
4857
|
+
});
|
|
4858
|
+
launcher.on("error", () => {
|
|
4859
|
+
});
|
|
4860
|
+
launcher.setInjectionScript(await loadInjectionScript(wsServer.getPort()));
|
|
4861
|
+
try {
|
|
4862
|
+
await launcher.launch();
|
|
4863
|
+
} catch (error) {
|
|
4864
|
+
throw new ReactCheckError(
|
|
4865
|
+
"BROWSER_LAUNCH_FAILED" /* BROWSER_LAUNCH_FAILED */,
|
|
4866
|
+
`Could not open ${target}: ${error instanceof Error ? error.message : String(error)}`
|
|
4867
|
+
);
|
|
4868
|
+
}
|
|
4869
|
+
await new Promise((resolve2) => setTimeout(resolve2, duration));
|
|
4870
|
+
} finally {
|
|
4871
|
+
scanner.stop();
|
|
4872
|
+
if (launcher) {
|
|
4873
|
+
await launcher.close().catch(() => void 0);
|
|
4874
|
+
}
|
|
4875
|
+
await wsServer.stop();
|
|
4876
|
+
}
|
|
4877
|
+
const exported = scanner.export();
|
|
4878
|
+
if (exported.stats.summary.totalRenders === 0) {
|
|
6664
4879
|
throw new ReactCheckError(
|
|
6665
4880
|
"REACT_NOT_FOUND" /* REACT_NOT_FOUND */,
|
|
6666
|
-
"
|
|
4881
|
+
"No React renders were observed. Make sure the page uses React (development or production build) and is reachable."
|
|
6667
4882
|
);
|
|
6668
4883
|
}
|
|
6669
|
-
|
|
6670
|
-
|
|
6671
|
-
|
|
6672
|
-
|
|
6673
|
-
|
|
6674
|
-
|
|
6675
|
-
|
|
6676
|
-
|
|
6677
|
-
|
|
4884
|
+
const report = {
|
|
4885
|
+
version: VERSION,
|
|
4886
|
+
generated: formatDate(),
|
|
4887
|
+
session: {
|
|
4888
|
+
url: target,
|
|
4889
|
+
duration: Date.now() - startTime,
|
|
4890
|
+
timestamp: formatDate(new Date(startTime)),
|
|
4891
|
+
id: generateId("scan")
|
|
4892
|
+
},
|
|
4893
|
+
summary: exported.stats.summary,
|
|
4894
|
+
components: exported.stats.components,
|
|
4895
|
+
chains,
|
|
4896
|
+
timeline: [],
|
|
4897
|
+
framework: null,
|
|
4898
|
+
// Regenerated from the final stats (suggestions made mid-scan go stale)
|
|
4899
|
+
suggestions: exported.suggestions
|
|
4900
|
+
};
|
|
4901
|
+
if (options.output) {
|
|
4902
|
+
const generator = new ReportGenerator({
|
|
4903
|
+
enabled: true,
|
|
4904
|
+
formats: options.formats ?? ["html", "json"],
|
|
4905
|
+
output: options.output,
|
|
4906
|
+
includeSourceCode: false
|
|
6678
4907
|
});
|
|
6679
|
-
await generator.saveAll(
|
|
4908
|
+
await generator.saveAll(report);
|
|
6680
4909
|
}
|
|
6681
|
-
return
|
|
4910
|
+
return report;
|
|
4911
|
+
}
|
|
4912
|
+
|
|
4913
|
+
// src/index.ts
|
|
4914
|
+
function createScanner(options = {}) {
|
|
4915
|
+
const config = {};
|
|
4916
|
+
if (options.include) config.include = options.include;
|
|
4917
|
+
if (options.exclude) config.exclude = options.exclude;
|
|
4918
|
+
return new Scanner({
|
|
4919
|
+
thresholds: {
|
|
4920
|
+
critical: options.thresholds?.critical ?? 50,
|
|
4921
|
+
warning: options.thresholds?.warning ?? 20,
|
|
4922
|
+
...options.thresholds?.fps !== void 0 ? { fps: options.thresholds.fps } : {}
|
|
4923
|
+
},
|
|
4924
|
+
config
|
|
4925
|
+
});
|
|
4926
|
+
}
|
|
4927
|
+
function createReportGenerator(options = {}) {
|
|
4928
|
+
return new ReportGenerator({
|
|
4929
|
+
enabled: true,
|
|
4930
|
+
formats: options.formats ?? ["html", "json"],
|
|
4931
|
+
output: options.output ?? "./reactcheck-reports",
|
|
4932
|
+
includeSourceCode: options.includeSourceCode ?? false
|
|
4933
|
+
});
|
|
6682
4934
|
}
|
|
6683
4935
|
|
|
6684
|
-
export { BrowserLauncher, BrowserScanner,
|
|
4936
|
+
export { BrowserLauncher, BrowserScanner, ErrorCode, FiberTag, LogLevel, Logger, Overlay, ProxyServer, ReactCheckError, ReactCheckInjector, ReportGenerator, VERSION, WebSocketClient, WebSocketServer, colors, createRenderInfo, createReportGenerator, createScanner, escapeHtml, findFiberByName, formatBytes, formatDuration, formatNumber, formatPercent, formatRenderTime, generateHTMLReport, generateJSONReport, generateMarkdownReport, generateReport, getChangedProps, getComponentName, getComponentPath, getFiberDOMNode, getOwner, getParentFiber, getReactVersion, handleBrowserMessages, installReactCheck, isHostComponent, isMemoized, isPuppeteerAvailable, isUserComponent, loadInjectionScript, pad, parseJSONReport, quickScan, saveReport, saveReports, shallowEqual, stripAnsi, supportsColor, truncate, validateJSONReport, walkFiberTree };
|
|
6685
4937
|
//# sourceMappingURL=index.js.map
|
|
6686
4938
|
//# sourceMappingURL=index.js.map
|