@oxog/react-check 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,6 +2,10 @@
2
2
  import { access, readFile, writeFile, mkdir, stat, rm, readdir } from 'fs/promises';
3
3
  import { constants } from 'fs';
4
4
  import { dirname, resolve, join, extname, basename } from 'path';
5
+ import { createServer } from 'http';
6
+ import { createHash } from 'crypto';
7
+ import { fileURLToPath } from 'url';
8
+ import { exec } from 'child_process';
5
9
 
6
10
  var __defProp = Object.defineProperty;
7
11
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -274,7 +278,7 @@ function generateHTMLReport(report) {
274
278
  <meta charset="UTF-8">
275
279
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
276
280
  <title>ReactCheck Report - ${escapeHtml(report.session.url)}</title>
277
- <style>${getStyles()}</style>
281
+ <style>${getStyles2()}</style>
278
282
  </head>
279
283
  <body>
280
284
  <div class="container">
@@ -286,11 +290,11 @@ function generateHTMLReport(report) {
286
290
  ${renderAllComponents(report)}
287
291
  ${renderFooter(report)}
288
292
  </div>
289
- <script>${getScript()}</script>
293
+ <script>${getScript2()}</script>
290
294
  </body>
291
295
  </html>`;
292
296
  }
293
- function getStyles() {
297
+ function getStyles2() {
294
298
  return `
295
299
  :root {
296
300
  --bg-primary: #0a0a0a;
@@ -564,7 +568,7 @@ function getStyles() {
564
568
  }
565
569
  `;
566
570
  }
567
- function getScript() {
571
+ function getScript2() {
568
572
  return `
569
573
  // Toggle collapsible sections
570
574
  document.querySelectorAll('.collapsible').forEach(el => {
@@ -1197,6 +1201,16 @@ var FLAG_DEFINITIONS = {
1197
1201
  short: "w",
1198
1202
  description: "Watch mode - keep scanning until quit",
1199
1203
  default: false
1204
+ },
1205
+ webui: {
1206
+ short: "W",
1207
+ description: "Enable WebUI dashboard",
1208
+ default: false
1209
+ },
1210
+ "webui-port": {
1211
+ description: "WebUI dashboard port",
1212
+ takesValue: true,
1213
+ default: "3100"
1200
1214
  }
1201
1215
  };
1202
1216
  function buildShortFlagMap() {
@@ -1229,6 +1243,11 @@ function parseArgs(argv) {
1229
1243
  continue;
1230
1244
  }
1231
1245
  if (i === 0 || result.positional.length === 0 && !result.target) {
1246
+ if (arg === "scan") {
1247
+ result.command = "scan";
1248
+ i++;
1249
+ continue;
1250
+ }
1232
1251
  if (arg === "init") {
1233
1252
  result.command = "init";
1234
1253
  i++;
@@ -2321,13 +2340,13 @@ var EventEmitter = class {
2321
2340
  * @returns Promise that resolves with the event data
2322
2341
  */
2323
2342
  waitFor(event, timeout) {
2324
- return new Promise((resolve2, reject) => {
2343
+ return new Promise((resolve3, reject) => {
2325
2344
  let timeoutId;
2326
2345
  const listener = (data) => {
2327
2346
  if (timeoutId) {
2328
2347
  clearTimeout(timeoutId);
2329
2348
  }
2330
- resolve2(data);
2349
+ resolve3(data);
2331
2350
  };
2332
2351
  this.once(event, listener);
2333
2352
  if (timeout !== void 0 && timeout > 0) {
@@ -4711,13 +4730,13 @@ var InputHandler = class _InputHandler extends EventEmitter {
4711
4730
  * @returns Promise that resolves when key is pressed
4712
4731
  */
4713
4732
  waitForKey(key, timeout) {
4714
- return new Promise((resolve2, reject) => {
4733
+ return new Promise((resolve3, reject) => {
4715
4734
  let timeoutId;
4716
4735
  const handler = (event) => {
4717
4736
  if (_InputHandler.matches(event, key)) {
4718
4737
  if (timeoutId) clearTimeout(timeoutId);
4719
4738
  this.off("key", handler);
4720
- resolve2(event);
4739
+ resolve3(event);
4721
4740
  }
4722
4741
  };
4723
4742
  this.on("key", handler);
@@ -4735,12 +4754,12 @@ var InputHandler = class _InputHandler extends EventEmitter {
4735
4754
  * @returns Promise that resolves with the pressed key
4736
4755
  */
4737
4756
  waitForAnyKey(timeout) {
4738
- return new Promise((resolve2, reject) => {
4757
+ return new Promise((resolve3, reject) => {
4739
4758
  let timeoutId;
4740
4759
  const handler = (event) => {
4741
4760
  if (timeoutId) clearTimeout(timeoutId);
4742
4761
  this.off("key", handler);
4743
- resolve2(event);
4762
+ resolve3(event);
4744
4763
  };
4745
4764
  this.once("key", handler);
4746
4765
  if (timeout) {
@@ -4757,12 +4776,12 @@ var InputHandler = class _InputHandler extends EventEmitter {
4757
4776
  * @returns Promise that resolves with the input line
4758
4777
  */
4759
4778
  waitForLine(timeout) {
4760
- return new Promise((resolve2, reject) => {
4779
+ return new Promise((resolve3, reject) => {
4761
4780
  let timeoutId;
4762
4781
  const handler = (line) => {
4763
4782
  if (timeoutId) clearTimeout(timeoutId);
4764
4783
  this.off("line", handler);
4765
- resolve2(line);
4784
+ resolve3(line);
4766
4785
  };
4767
4786
  this.once("line", handler);
4768
4787
  if (timeout) {
@@ -4867,6 +4886,8 @@ var TUI = class extends EventEmitter {
4867
4886
  renderInterval = null;
4868
4887
  /** Spinner frame */
4869
4888
  spinnerFrame = 0;
4889
+ /** Data provider function for polling */
4890
+ dataProvider = null;
4870
4891
  /**
4871
4892
  * Create a new TUI
4872
4893
  * @param target - Target URL
@@ -4923,10 +4944,28 @@ var TUI = class extends EventEmitter {
4923
4944
  });
4924
4945
  this.renderInterval = setInterval(() => {
4925
4946
  this.spinnerFrame++;
4947
+ if (this.dataProvider) {
4948
+ try {
4949
+ const data = this.dataProvider();
4950
+ this.state = { ...this.state, ...data };
4951
+ if (data.components && data.components.length > 0) {
4952
+ const items = createComponentListItems(data.components);
4953
+ this.componentList.setItems(items);
4954
+ }
4955
+ } catch {
4956
+ }
4957
+ }
4926
4958
  this.render();
4927
4959
  }, 250);
4928
4960
  this.render();
4929
4961
  }
4962
+ /**
4963
+ * Set data provider for polling
4964
+ * @param provider - Function that returns current data
4965
+ */
4966
+ setDataProvider(provider) {
4967
+ this.dataProvider = provider;
4968
+ }
4930
4969
  /**
4931
4970
  * Stop the TUI
4932
4971
  */
@@ -4986,7 +5025,7 @@ var TUI = class extends EventEmitter {
4986
5025
  }
4987
5026
  drawDivider(this.screen, 0, height - 3, width, "single", colors.gray);
4988
5027
  this.renderFooter(1, height - 2, width - 2);
4989
- this.screen.render();
5028
+ this.screen.render(true);
4990
5029
  }
4991
5030
  /**
4992
5031
  * Render header
@@ -5172,179 +5211,2129 @@ var TUI = class extends EventEmitter {
5172
5211
 
5173
5212
  // src/cli/commands/scan.ts
5174
5213
  init_format();
5175
- var logger3 = new Logger({ prefix: "scan", level: 1 /* INFO */ });
5176
- function parseScanOptions(args) {
5177
- return {
5178
- target: normalizeTarget(args.target ?? "localhost:3000"),
5179
- proxy: getBooleanFlag(args, "proxy"),
5180
- tui: getBooleanFlag(args, "tui"),
5181
- silent: getBooleanFlag(args, "silent"),
5182
- report: getBooleanFlag(args, "report"),
5183
- format: getStringFlag(args, "format") ?? "all",
5184
- output: getStringFlag(args, "output") ?? "./reactcheck-reports",
5185
- fix: getBooleanFlag(args, "fix"),
5186
- verbose: getBooleanFlag(args, "verbose"),
5187
- port: getNumberFlag(args, "port") ?? 3099,
5188
- thresholdCritical: getNumberFlag(args, "threshold-critical") ?? 50,
5189
- thresholdWarning: getNumberFlag(args, "threshold-warning") ?? 20,
5190
- fpsThreshold: getNumberFlag(args, "fps-threshold") ?? 30,
5191
- headless: getBooleanFlag(args, "headless"),
5192
- duration: getNumberFlag(args, "duration"),
5193
- watch: getBooleanFlag(args, "watch"),
5194
- configPath: getStringFlag(args, "config")
5195
- };
5196
- }
5197
- async function runScanCommand(args) {
5198
- const options = parseScanOptions(args);
5199
- const { config, configPath, fromFile } = await loadConfig(options.configPath);
5200
- if (fromFile) {
5201
- logger3.info(`Using config: ${configPath}`);
5214
+ var OPCODE = {
5215
+ TEXT: 1,
5216
+ BINARY: 2,
5217
+ CLOSE: 8,
5218
+ PING: 9,
5219
+ PONG: 10
5220
+ };
5221
+ var WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
5222
+ var WebSocketClient = class extends EventEmitter {
5223
+ /** Socket connection */
5224
+ socket;
5225
+ /** Whether connection is open */
5226
+ isOpen = true;
5227
+ /** Partial frame buffer */
5228
+ frameBuffer = Buffer.alloc(0);
5229
+ /**
5230
+ * Create a new WebSocket client
5231
+ * @param socket - TCP socket
5232
+ */
5233
+ constructor(socket) {
5234
+ super();
5235
+ this.socket = socket;
5236
+ this.setupSocketHandlers();
5202
5237
  }
5203
- const configOptions = configToOptions(config);
5204
- const mergedOptions = {
5205
- ...options,
5206
- thresholdCritical: options.thresholdCritical ?? configOptions.thresholds.critical,
5207
- thresholdWarning: options.thresholdWarning ?? configOptions.thresholds.warning,
5208
- fpsThreshold: options.fpsThreshold ?? configOptions.thresholds.fps,
5209
- output: options.output ?? configOptions.report.output
5210
- };
5211
- const session = {
5212
- id: generateId("scan"),
5213
- startTime: Date.now(),
5214
- scanner: new Scanner({
5215
- thresholds: {
5216
- critical: mergedOptions.thresholdCritical,
5217
- warning: mergedOptions.thresholdWarning,
5218
- fps: mergedOptions.fpsThreshold
5219
- }
5220
- }),
5221
- tui: null,
5222
- options: mergedOptions,
5223
- active: true,
5224
- chains: [],
5225
- suggestions: []
5226
- };
5227
- setupScannerEvents(session);
5228
- if (!mergedOptions.silent) {
5229
- session.tui = new TUI(mergedOptions.target);
5230
- setupTUIEvents(session);
5231
- session.tui.start();
5238
+ /**
5239
+ * Set up socket event handlers
5240
+ */
5241
+ setupSocketHandlers() {
5242
+ this.socket.on("data", (data) => {
5243
+ this.frameBuffer = Buffer.concat([this.frameBuffer, data]);
5244
+ this.processFrames();
5245
+ });
5246
+ this.socket.on("close", () => {
5247
+ this.isOpen = false;
5248
+ this.emit("close", { code: 1e3, reason: "Connection closed" });
5249
+ });
5250
+ this.socket.on("error", (error) => {
5251
+ this.emit("error", error);
5252
+ });
5232
5253
  }
5233
- if (mergedOptions.silent) {
5234
- logger3.info(`Starting scan of ${mergedOptions.target}`);
5254
+ /**
5255
+ * Process received frames
5256
+ */
5257
+ processFrames() {
5258
+ while (this.frameBuffer.length >= 2) {
5259
+ const frame = this.parseFrame();
5260
+ if (!frame) break;
5261
+ switch (frame.opcode) {
5262
+ case OPCODE.TEXT:
5263
+ this.emit("message", frame.payload.toString("utf8"));
5264
+ break;
5265
+ case OPCODE.BINARY:
5266
+ this.emit("binary", frame.payload);
5267
+ break;
5268
+ case OPCODE.CLOSE:
5269
+ this.handleClose(frame.payload);
5270
+ break;
5271
+ case OPCODE.PING:
5272
+ this.sendPong(frame.payload);
5273
+ break;
5274
+ case OPCODE.PONG:
5275
+ this.emit("pong", void 0);
5276
+ break;
5277
+ }
5278
+ }
5235
5279
  }
5236
- try {
5237
- session.scanner.start();
5238
- if (mergedOptions.silent && mergedOptions.duration) {
5239
- await new Promise((resolve2) => setTimeout(resolve2, mergedOptions.duration * 1e3));
5240
- session.active = false;
5241
- } else if (!mergedOptions.silent) {
5242
- await waitForQuit(session);
5243
- } else {
5244
- logger3.info("Press Ctrl+C to stop scanning");
5245
- await waitForSignal();
5246
- session.active = false;
5280
+ /**
5281
+ * Parse a WebSocket frame
5282
+ * @returns Parsed frame or null if incomplete
5283
+ */
5284
+ parseFrame() {
5285
+ if (this.frameBuffer.length < 2) return null;
5286
+ const firstByte = this.frameBuffer[0];
5287
+ const secondByte = this.frameBuffer[1];
5288
+ const opcode = firstByte & 15;
5289
+ const masked = (secondByte & 128) !== 0;
5290
+ let payloadLength = secondByte & 127;
5291
+ let offset = 2;
5292
+ if (payloadLength === 126) {
5293
+ if (this.frameBuffer.length < 4) return null;
5294
+ payloadLength = this.frameBuffer.readUInt16BE(2);
5295
+ offset = 4;
5296
+ } else if (payloadLength === 127) {
5297
+ if (this.frameBuffer.length < 10) return null;
5298
+ payloadLength = this.frameBuffer.readUInt32BE(6);
5299
+ offset = 10;
5300
+ }
5301
+ let maskingKey = null;
5302
+ if (masked) {
5303
+ if (this.frameBuffer.length < offset + 4) return null;
5304
+ maskingKey = this.frameBuffer.subarray(offset, offset + 4);
5305
+ offset += 4;
5306
+ }
5307
+ if (this.frameBuffer.length < offset + payloadLength) return null;
5308
+ let payload = this.frameBuffer.subarray(offset, offset + payloadLength);
5309
+ if (masked && maskingKey) {
5310
+ payload = Buffer.from(payload);
5311
+ for (let i = 0; i < payload.length; i++) {
5312
+ payload[i] = payload[i] ^ maskingKey[i % 4];
5313
+ }
5247
5314
  }
5248
- session.scanner.stop();
5249
- if (session.tui) {
5250
- session.tui.stop();
5315
+ this.frameBuffer = this.frameBuffer.subarray(offset + payloadLength);
5316
+ return { opcode, payload };
5317
+ }
5318
+ /**
5319
+ * Handle close frame
5320
+ * @param payload - Close frame payload
5321
+ */
5322
+ handleClose(payload) {
5323
+ let code = 1e3;
5324
+ let reason = "";
5325
+ if (payload.length >= 2) {
5326
+ code = payload.readUInt16BE(0);
5327
+ reason = payload.subarray(2).toString("utf8");
5251
5328
  }
5252
- if (mergedOptions.report) {
5253
- const report = generateReport(session);
5254
- await saveReport(report, mergedOptions);
5329
+ this.close(code, reason);
5330
+ this.emit("close", { code, reason });
5331
+ }
5332
+ /**
5333
+ * Send a pong frame
5334
+ * @param payload - Pong payload (echo of ping)
5335
+ */
5336
+ sendPong(payload) {
5337
+ this.sendFrame(OPCODE.PONG, payload);
5338
+ }
5339
+ /**
5340
+ * Send a WebSocket frame
5341
+ * @param opcode - Frame opcode
5342
+ * @param payload - Frame payload
5343
+ */
5344
+ sendFrame(opcode, payload) {
5345
+ if (!this.isOpen) return;
5346
+ const data = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
5347
+ const length = data.length;
5348
+ let header;
5349
+ if (length < 126) {
5350
+ header = Buffer.alloc(2);
5351
+ header[0] = 128 | opcode;
5352
+ header[1] = length;
5353
+ } else if (length < 65536) {
5354
+ header = Buffer.alloc(4);
5355
+ header[0] = 128 | opcode;
5356
+ header[1] = 126;
5357
+ header.writeUInt16BE(length, 2);
5358
+ } else {
5359
+ header = Buffer.alloc(10);
5360
+ header[0] = 128 | opcode;
5361
+ header[1] = 127;
5362
+ header.writeUInt32BE(0, 2);
5363
+ header.writeUInt32BE(length, 6);
5255
5364
  }
5256
- printSummary(session);
5257
- if (mergedOptions.fix && !mergedOptions.silent) {
5258
- printFixSuggestions(session.suggestions);
5365
+ this.socket.write(Buffer.concat([header, data]));
5366
+ }
5367
+ /**
5368
+ * Send a text message
5369
+ * @param message - Message to send
5370
+ */
5371
+ send(message) {
5372
+ this.sendFrame(OPCODE.TEXT, message);
5373
+ }
5374
+ /**
5375
+ * Send a binary message
5376
+ * @param data - Binary data to send
5377
+ */
5378
+ sendBinary(data) {
5379
+ this.sendFrame(OPCODE.BINARY, data);
5380
+ }
5381
+ /**
5382
+ * Send a ping frame
5383
+ * @param payload - Optional ping payload
5384
+ */
5385
+ ping(payload = Buffer.alloc(0)) {
5386
+ this.sendFrame(OPCODE.PING, payload);
5387
+ }
5388
+ /**
5389
+ * Close the connection
5390
+ * @param code - Close code
5391
+ * @param reason - Close reason
5392
+ */
5393
+ close(code = 1e3, reason = "") {
5394
+ if (!this.isOpen) return;
5395
+ const reasonBuffer = Buffer.from(reason, "utf8");
5396
+ const payload = Buffer.alloc(2 + reasonBuffer.length);
5397
+ payload.writeUInt16BE(code, 0);
5398
+ reasonBuffer.copy(payload, 2);
5399
+ this.sendFrame(OPCODE.CLOSE, payload);
5400
+ this.isOpen = false;
5401
+ setTimeout(() => {
5402
+ this.socket.end();
5403
+ }, 100);
5404
+ }
5405
+ /**
5406
+ * Check if connection is open
5407
+ * @returns true if open
5408
+ */
5409
+ isConnected() {
5410
+ return this.isOpen;
5411
+ }
5412
+ };
5413
+ var WebSocketServer = class extends EventEmitter {
5414
+ /** HTTP server */
5415
+ server;
5416
+ /** Connected clients */
5417
+ clients = /* @__PURE__ */ new Set();
5418
+ /** Server port */
5419
+ port;
5420
+ /**
5421
+ * Create a new WebSocket server
5422
+ * @param port - Port to listen on
5423
+ */
5424
+ constructor(port) {
5425
+ super();
5426
+ this.port = port;
5427
+ this.server = createServer();
5428
+ this.setupServer();
5429
+ }
5430
+ /**
5431
+ * Set up HTTP server for WebSocket upgrade
5432
+ */
5433
+ setupServer() {
5434
+ this.server.on("upgrade", (req, socket, head) => {
5435
+ this.handleUpgrade(req, socket, head);
5436
+ });
5437
+ this.server.on("error", (error) => {
5438
+ this.emit("error", error);
5439
+ });
5440
+ this.server.on("close", () => {
5441
+ this.emit("close", void 0);
5442
+ });
5443
+ }
5444
+ /**
5445
+ * Handle WebSocket upgrade request
5446
+ * @param req - HTTP request
5447
+ * @param socket - TCP socket
5448
+ * @param head - Upgrade head
5449
+ */
5450
+ handleUpgrade(req, socket, head) {
5451
+ const upgrade = req.headers["upgrade"];
5452
+ if (!upgrade || upgrade.toLowerCase() !== "websocket") {
5453
+ socket.destroy();
5454
+ return;
5259
5455
  }
5260
- const summary = session.scanner.getSummary();
5261
- return summary.criticalIssues > 0 ? 1 : 0;
5262
- } catch (error) {
5263
- if (session.tui) {
5264
- session.tui.stop();
5456
+ const key = req.headers["sec-websocket-key"];
5457
+ if (!key) {
5458
+ socket.destroy();
5459
+ return;
5265
5460
  }
5266
- logger3.error("Scan failed:", error);
5267
- return 2;
5461
+ const acceptKey = this.generateAcceptKey(key);
5462
+ const response = [
5463
+ "HTTP/1.1 101 Switching Protocols",
5464
+ "Upgrade: websocket",
5465
+ "Connection: Upgrade",
5466
+ `Sec-WebSocket-Accept: ${acceptKey}`,
5467
+ "",
5468
+ ""
5469
+ ].join("\r\n");
5470
+ socket.write(response);
5471
+ if (head.length > 0) {
5472
+ socket.unshift(head);
5473
+ }
5474
+ const client = new WebSocketClient(socket);
5475
+ this.clients.add(client);
5476
+ client.on("close", () => {
5477
+ this.clients.delete(client);
5478
+ });
5479
+ this.emit("connection", client);
5268
5480
  }
5269
- }
5270
- function setupScannerEvents(session) {
5271
- const { scanner, tui } = session;
5272
- scanner.on("render", (info) => {
5273
- if (tui) {
5274
- tui.update({
5275
- components: scanner.getSnapshot(),
5276
- summary: scanner.getSummary(),
5277
- fps: scanner.getFps()
5481
+ /**
5482
+ * Generate WebSocket accept key
5483
+ * @param key - Client key
5484
+ * @returns Accept key
5485
+ */
5486
+ generateAcceptKey(key) {
5487
+ return createHash("sha1").update(key + WS_GUID).digest("base64");
5488
+ }
5489
+ /**
5490
+ * Start the server
5491
+ */
5492
+ start() {
5493
+ return new Promise((resolve3, reject) => {
5494
+ this.server.once("error", reject);
5495
+ this.server.listen(this.port, () => {
5496
+ this.server.removeListener("error", reject);
5497
+ this.emit("listening", { port: this.port });
5498
+ resolve3();
5278
5499
  });
5279
- }
5280
- });
5281
- scanner.on("chain", (chain) => {
5282
- session.chains.push(chain);
5283
- if (tui) {
5284
- tui.update({ chains: session.chains.slice(-10) });
5285
- }
5286
- });
5287
- scanner.on("fix", (suggestion) => {
5288
- if (!session.suggestions.some(
5289
- (s) => s.componentName === suggestion.componentName && s.fix === suggestion.fix
5290
- )) {
5291
- session.suggestions.push(suggestion);
5292
- if (tui) {
5293
- tui.update({ suggestions: session.suggestions });
5500
+ });
5501
+ }
5502
+ /**
5503
+ * Stop the server
5504
+ */
5505
+ stop() {
5506
+ return new Promise((resolve3) => {
5507
+ for (const client of this.clients) {
5508
+ client.close(1001, "Server shutting down");
5509
+ }
5510
+ this.clients.clear();
5511
+ this.server.close(() => {
5512
+ resolve3();
5513
+ });
5514
+ });
5515
+ }
5516
+ /**
5517
+ * Broadcast message to all clients
5518
+ * @param message - Message to broadcast
5519
+ */
5520
+ broadcast(message) {
5521
+ for (const client of this.clients) {
5522
+ if (client.isConnected()) {
5523
+ client.send(message);
5294
5524
  }
5295
5525
  }
5296
- });
5297
- scanner.on("fps-drop", (fps) => {
5298
- if (session.options.verbose) {
5299
- logger3.warn(`FPS dropped to ${fps}`);
5300
- }
5301
- });
5302
- scanner.on("severityChange", ({ component, to }) => {
5303
- if (session.options.verbose && to === "critical") {
5304
- logger3.warn(`Component ${component} reached critical severity`);
5526
+ }
5527
+ /**
5528
+ * Broadcast CLI message to all clients
5529
+ * @param message - CLI message to broadcast
5530
+ */
5531
+ broadcastCLIMessage(message) {
5532
+ this.broadcast(JSON.stringify(message));
5533
+ }
5534
+ /**
5535
+ * Get connected client count
5536
+ * @returns Number of connected clients
5537
+ */
5538
+ getClientCount() {
5539
+ return this.clients.size;
5540
+ }
5541
+ /**
5542
+ * Get all connected clients
5543
+ * @returns Array of connected clients
5544
+ */
5545
+ getClients() {
5546
+ return Array.from(this.clients);
5547
+ }
5548
+ };
5549
+ function handleBrowserMessages(client, handler) {
5550
+ client.on("message", (data) => {
5551
+ try {
5552
+ const message = JSON.parse(data);
5553
+ handler(message);
5554
+ } catch (error) {
5305
5555
  }
5306
5556
  });
5307
5557
  }
5308
- function setupTUIEvents(session) {
5309
- const { tui, scanner } = session;
5310
- if (!tui) return;
5311
- tui.on("togglePause", () => {
5312
- if (scanner.isRunning()) {
5313
- scanner.stop();
5314
- tui.update({ paused: true });
5315
- } else {
5316
- scanner.start();
5317
- tui.update({ paused: false });
5558
+
5559
+ // src/server/browser.ts
5560
+ var logger3 = new Logger({ prefix: "browser", level: 0 /* DEBUG */ });
5561
+ var BrowserLauncher = class extends EventEmitter {
5562
+ /** Puppeteer browser instance */
5563
+ browser = null;
5564
+ /** Active page */
5565
+ page = null;
5566
+ /** Launch options */
5567
+ options;
5568
+ /** Injection script */
5569
+ injectionScript = null;
5570
+ /**
5571
+ * Create a new browser launcher
5572
+ * @param options - Launch options
5573
+ */
5574
+ constructor(options) {
5575
+ super();
5576
+ this.options = {
5577
+ url: options.url,
5578
+ headless: options.headless ?? false,
5579
+ width: options.width ?? 1280,
5580
+ height: options.height ?? 800,
5581
+ wsPort: options.wsPort ?? 3099,
5582
+ args: options.args ?? [],
5583
+ slowMo: options.slowMo ?? 0,
5584
+ timeout: options.timeout ?? 3e4
5585
+ };
5586
+ }
5587
+ /**
5588
+ * Set the injection script
5589
+ * @param script - Script to inject before page loads
5590
+ */
5591
+ setInjectionScript(script) {
5592
+ this.injectionScript = script;
5593
+ }
5594
+ /**
5595
+ * Launch the browser
5596
+ */
5597
+ async launch() {
5598
+ try {
5599
+ const puppeteer = await import('puppeteer');
5600
+ const args = [
5601
+ "--no-sandbox",
5602
+ "--disable-setuid-sandbox",
5603
+ "--disable-dev-shm-usage",
5604
+ "--disable-gpu",
5605
+ `--window-size=${this.options.width},${this.options.height}`,
5606
+ ...this.options.args
5607
+ ];
5608
+ this.browser = await puppeteer.default.launch({
5609
+ headless: this.options.headless,
5610
+ args,
5611
+ slowMo: this.options.slowMo,
5612
+ defaultViewport: {
5613
+ width: this.options.width,
5614
+ height: this.options.height
5615
+ }
5616
+ });
5617
+ const pages = await this.browser.pages();
5618
+ this.page = pages[0] ?? await this.browser.newPage();
5619
+ this.setupPageHandlers();
5620
+ if (this.injectionScript) {
5621
+ await this.page.evaluateOnNewDocument(this.injectionScript);
5622
+ }
5623
+ const wsPort = this.options.wsPort;
5624
+ await this.page.evaluateOnNewDocument(`
5625
+ window.__REACTCHECK_PORT__ = ${wsPort};
5626
+ window.__REACTCHECK_INJECTED__ = true;
5627
+ `);
5628
+ this.emit("launched", void 0);
5629
+ logger3.info("Browser launched");
5630
+ await this.navigate(this.options.url);
5631
+ } catch (error) {
5632
+ const err = error instanceof Error ? error : new Error(String(error));
5633
+ this.emit("error", err);
5634
+ throw err;
5318
5635
  }
5319
- });
5320
- tui.on("generateReport", async () => {
5321
- const report = generateReport(session);
5322
- await saveReport(report, session.options);
5323
- });
5324
- tui.on("selectComponent", (component) => {
5325
- const suggestions = scanner.analyzeComponent(component.name);
5326
- session.suggestions.push(...suggestions.filter(
5327
- (s) => !session.suggestions.some(
5328
- (ex) => ex.componentName === s.componentName && ex.fix === s.fix
5329
- )
5330
- ));
5331
- tui.update({ suggestions: session.suggestions });
5332
- });
5333
- }
5334
- async function waitForQuit(session) {
5335
- return new Promise((resolve2) => {
5336
- if (session.tui) {
5337
- session.tui.on("quit", () => {
5338
- session.active = false;
5339
- resolve2();
5636
+ }
5637
+ /**
5638
+ * Set up page event handlers
5639
+ */
5640
+ setupPageHandlers() {
5641
+ if (!this.page) return;
5642
+ this.page.on("console", (msg) => {
5643
+ this.emit("console", {
5644
+ type: msg.type(),
5645
+ text: msg.text()
5340
5646
  });
5647
+ });
5648
+ this.page.on("pageerror", (error) => {
5649
+ this.emit("error", error);
5650
+ });
5651
+ this.page.on("framenavigated", (frame) => {
5652
+ if (frame === this.page?.mainFrame()) {
5653
+ this.emit("navigated", { url: frame.url() });
5654
+ }
5655
+ });
5656
+ this.page.on("load", () => {
5657
+ this.emit("loaded", void 0);
5658
+ });
5659
+ }
5660
+ /**
5661
+ * Navigate to a URL
5662
+ * @param url - URL to navigate to
5663
+ */
5664
+ async navigate(url) {
5665
+ if (!this.page) {
5666
+ throw new Error("Browser not launched");
5341
5667
  }
5342
- });
5343
- }
5668
+ try {
5669
+ await this.page.goto(url, {
5670
+ waitUntil: "networkidle2",
5671
+ timeout: this.options.timeout
5672
+ });
5673
+ this.emit("navigated", { url });
5674
+ logger3.info(`Navigated to ${url}`);
5675
+ } catch (error) {
5676
+ const err = error instanceof Error ? error : new Error(String(error));
5677
+ this.emit("error", err);
5678
+ throw err;
5679
+ }
5680
+ }
5681
+ /**
5682
+ * Execute script in page context
5683
+ * @param script - Script to execute
5684
+ * @returns Script result
5685
+ */
5686
+ async evaluate(script) {
5687
+ if (!this.page) {
5688
+ throw new Error("Browser not launched");
5689
+ }
5690
+ return this.page.evaluate(script);
5691
+ }
5692
+ /**
5693
+ * Wait for selector
5694
+ * @param selector - CSS selector
5695
+ * @param timeout - Timeout in ms
5696
+ */
5697
+ async waitForSelector(selector, timeout) {
5698
+ if (!this.page) {
5699
+ throw new Error("Browser not launched");
5700
+ }
5701
+ await this.page.waitForSelector(selector, {
5702
+ timeout: timeout ?? this.options.timeout
5703
+ });
5704
+ }
5705
+ /**
5706
+ * Take a screenshot
5707
+ * @param path - File path to save screenshot
5708
+ */
5709
+ async screenshot(path) {
5710
+ if (!this.page) {
5711
+ throw new Error("Browser not launched");
5712
+ }
5713
+ await this.page.screenshot({ path, fullPage: true });
5714
+ logger3.info(`Screenshot saved to ${path}`);
5715
+ }
5716
+ /**
5717
+ * Reload the page
5718
+ */
5719
+ async reload() {
5720
+ if (!this.page) {
5721
+ throw new Error("Browser not launched");
5722
+ }
5723
+ await this.page.reload({ waitUntil: "networkidle2" });
5724
+ }
5725
+ /**
5726
+ * Get current URL
5727
+ * @returns Current page URL
5728
+ */
5729
+ getUrl() {
5730
+ return this.page?.url() ?? null;
5731
+ }
5732
+ /**
5733
+ * Close the browser
5734
+ */
5735
+ async close() {
5736
+ if (this.browser) {
5737
+ await this.browser.close();
5738
+ this.browser = null;
5739
+ this.page = null;
5740
+ this.emit("closed", void 0);
5741
+ logger3.info("Browser closed");
5742
+ }
5743
+ }
5744
+ /**
5745
+ * Check if browser is open
5746
+ * @returns true if browser is open
5747
+ */
5748
+ isOpen() {
5749
+ return this.browser !== null && this.browser.connected;
5750
+ }
5751
+ /**
5752
+ * Get the page instance (for advanced usage)
5753
+ * @returns Puppeteer page or null
5754
+ */
5755
+ getPage() {
5756
+ return this.page;
5757
+ }
5758
+ /**
5759
+ * Get the browser instance (for advanced usage)
5760
+ * @returns Puppeteer browser or null
5761
+ */
5762
+ getBrowser() {
5763
+ return this.browser;
5764
+ }
5765
+ };
5766
+ async function isPuppeteerAvailable() {
5767
+ try {
5768
+ await import('puppeteer');
5769
+ return true;
5770
+ } catch {
5771
+ return false;
5772
+ }
5773
+ }
5774
+
5775
+ // src/cli/commands/scan.ts
5776
+ init_fs();
5777
+
5778
+ // src/webui/dashboard.ts
5779
+ function generateDashboardHTML(wsPort, target) {
5780
+ return `<!DOCTYPE html>
5781
+ <html lang="en">
5782
+ <head>
5783
+ <meta charset="UTF-8">
5784
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
5785
+ <title>ReactCheck Dashboard</title>
5786
+ <style>${getStyles()}</style>
5787
+ </head>
5788
+ <body>
5789
+ <div class="container">
5790
+ <header class="header">
5791
+ <div class="header-left">
5792
+ <h1>
5793
+ <span class="logo">\u269B\uFE0F</span>
5794
+ ReactCheck
5795
+ <span class="status" id="status">
5796
+ <span class="status-dot"></span>
5797
+ <span class="status-text">Connecting...</span>
5798
+ </span>
5799
+ </h1>
5800
+ <div class="header-meta">
5801
+ <span id="target">Target: ${escapeHtml2(target)}</span>
5802
+ <span class="separator">\u2022</span>
5803
+ <span id="duration">Duration: 0s</span>
5804
+ </div>
5805
+ </div>
5806
+ <div class="header-right">
5807
+ <button id="export-btn" class="btn btn-secondary" disabled>Export Report</button>
5808
+ </div>
5809
+ </header>
5810
+
5811
+ <section class="summary">
5812
+ <div class="summary-grid">
5813
+ <div class="summary-card">
5814
+ <div class="summary-value info" id="components">0</div>
5815
+ <div class="summary-label">Components</div>
5816
+ </div>
5817
+ <div class="summary-card">
5818
+ <div class="summary-value" id="renders">0</div>
5819
+ <div class="summary-label">Total Renders</div>
5820
+ </div>
5821
+ <div class="summary-card">
5822
+ <div class="summary-value critical" id="critical">0</div>
5823
+ <div class="summary-label">Critical</div>
5824
+ </div>
5825
+ <div class="summary-card">
5826
+ <div class="summary-value warning" id="warnings">0</div>
5827
+ <div class="summary-label">Warnings</div>
5828
+ </div>
5829
+ <div class="summary-card">
5830
+ <div class="summary-value healthy" id="healthy">0</div>
5831
+ <div class="summary-label">Healthy</div>
5832
+ </div>
5833
+ <div class="summary-card">
5834
+ <div class="summary-value" id="fps">60</div>
5835
+ <div class="summary-label">Avg FPS</div>
5836
+ </div>
5837
+ </div>
5838
+ </section>
5839
+
5840
+ <section class="content">
5841
+ <div class="panel components-panel">
5842
+ <div class="panel-header">
5843
+ <h2>Components</h2>
5844
+ <input type="text" id="search" placeholder="Search components..." class="search-input">
5845
+ </div>
5846
+ <div class="table-container">
5847
+ <table class="component-table">
5848
+ <thead>
5849
+ <tr>
5850
+ <th class="sortable" data-sort="name">Component</th>
5851
+ <th class="sortable" data-sort="renders">Renders</th>
5852
+ <th class="sortable" data-sort="unnecessary">Unnecessary</th>
5853
+ <th class="sortable" data-sort="avgTime">Avg Time</th>
5854
+ <th class="sortable" data-sort="severity">Severity</th>
5855
+ </tr>
5856
+ </thead>
5857
+ <tbody id="component-list">
5858
+ <tr class="empty-row">
5859
+ <td colspan="5">Waiting for data...</td>
5860
+ </tr>
5861
+ </tbody>
5862
+ </table>
5863
+ </div>
5864
+ </div>
5865
+
5866
+ <div class="panel events-panel">
5867
+ <div class="panel-header">
5868
+ <h2>Live Events</h2>
5869
+ <span class="event-count" id="event-count">0 events</span>
5870
+ </div>
5871
+ <div class="events-container" id="events">
5872
+ <div class="empty-message">Waiting for render events...</div>
5873
+ </div>
5874
+ </div>
5875
+ </section>
5876
+
5877
+ <section class="chains-section">
5878
+ <div class="panel">
5879
+ <div class="panel-header">
5880
+ <h2>Render Chains</h2>
5881
+ </div>
5882
+ <div class="chains-container" id="chains">
5883
+ <div class="empty-message">No render chains detected yet...</div>
5884
+ </div>
5885
+ </div>
5886
+ </section>
5887
+ </div>
5888
+ <script>${getScript(wsPort)}</script>
5889
+ </body>
5890
+ </html>`;
5891
+ }
5892
+ function escapeHtml2(str) {
5893
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
5894
+ }
5895
+ function getStyles() {
5896
+ return `
5897
+ :root {
5898
+ --bg-primary: #0a0a0a;
5899
+ --bg-secondary: #141414;
5900
+ --bg-tertiary: #1f1f1f;
5901
+ --text-primary: #ffffff;
5902
+ --text-secondary: #a1a1aa;
5903
+ --accent-red: #ef4444;
5904
+ --accent-yellow: #eab308;
5905
+ --accent-green: #22c55e;
5906
+ --accent-blue: #3b82f6;
5907
+ --accent-purple: #a855f7;
5908
+ --border-color: #27272a;
5909
+ }
5910
+
5911
+ * {
5912
+ box-sizing: border-box;
5913
+ margin: 0;
5914
+ padding: 0;
5915
+ }
5916
+
5917
+ body {
5918
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
5919
+ background: var(--bg-primary);
5920
+ color: var(--text-primary);
5921
+ line-height: 1.6;
5922
+ min-height: 100vh;
5923
+ }
5924
+
5925
+ .container {
5926
+ max-width: 1400px;
5927
+ margin: 0 auto;
5928
+ padding: 1.5rem;
5929
+ }
5930
+
5931
+ /* Header */
5932
+ .header {
5933
+ display: flex;
5934
+ justify-content: space-between;
5935
+ align-items: flex-start;
5936
+ margin-bottom: 1.5rem;
5937
+ padding-bottom: 1rem;
5938
+ border-bottom: 1px solid var(--border-color);
5939
+ }
5940
+
5941
+ .header h1 {
5942
+ font-size: 1.75rem;
5943
+ color: var(--accent-green);
5944
+ display: flex;
5945
+ align-items: center;
5946
+ gap: 0.5rem;
5947
+ }
5948
+
5949
+ .logo {
5950
+ font-size: 1.5rem;
5951
+ }
5952
+
5953
+ .status {
5954
+ font-size: 0.875rem;
5955
+ font-weight: normal;
5956
+ display: inline-flex;
5957
+ align-items: center;
5958
+ gap: 0.375rem;
5959
+ padding: 0.25rem 0.75rem;
5960
+ background: var(--bg-tertiary);
5961
+ border-radius: 9999px;
5962
+ margin-left: 0.75rem;
5963
+ }
5964
+
5965
+ .status-dot {
5966
+ width: 8px;
5967
+ height: 8px;
5968
+ border-radius: 50%;
5969
+ background: var(--accent-yellow);
5970
+ animation: pulse 2s infinite;
5971
+ }
5972
+
5973
+ .status.connected .status-dot {
5974
+ background: var(--accent-green);
5975
+ animation: none;
5976
+ }
5977
+
5978
+ .status.scanning .status-dot {
5979
+ background: var(--accent-blue);
5980
+ animation: pulse 1s infinite;
5981
+ }
5982
+
5983
+ .status.paused .status-dot {
5984
+ background: var(--accent-yellow);
5985
+ animation: none;
5986
+ }
5987
+
5988
+ @keyframes pulse {
5989
+ 0%, 100% { opacity: 1; }
5990
+ 50% { opacity: 0.5; }
5991
+ }
5992
+
5993
+ .header-meta {
5994
+ color: var(--text-secondary);
5995
+ font-size: 0.875rem;
5996
+ margin-top: 0.5rem;
5997
+ }
5998
+
5999
+ .separator {
6000
+ margin: 0 0.5rem;
6001
+ }
6002
+
6003
+ .btn {
6004
+ padding: 0.5rem 1rem;
6005
+ border-radius: 6px;
6006
+ border: none;
6007
+ font-size: 0.875rem;
6008
+ font-weight: 500;
6009
+ cursor: pointer;
6010
+ transition: all 0.2s;
6011
+ }
6012
+
6013
+ .btn:disabled {
6014
+ opacity: 0.5;
6015
+ cursor: not-allowed;
6016
+ }
6017
+
6018
+ .btn-secondary {
6019
+ background: var(--bg-tertiary);
6020
+ color: var(--text-primary);
6021
+ }
6022
+
6023
+ .btn-secondary:hover:not(:disabled) {
6024
+ background: var(--border-color);
6025
+ }
6026
+
6027
+ /* Summary */
6028
+ .summary {
6029
+ margin-bottom: 1.5rem;
6030
+ }
6031
+
6032
+ .summary-grid {
6033
+ display: grid;
6034
+ grid-template-columns: repeat(6, 1fr);
6035
+ gap: 1rem;
6036
+ }
6037
+
6038
+ @media (max-width: 900px) {
6039
+ .summary-grid {
6040
+ grid-template-columns: repeat(3, 1fr);
6041
+ }
6042
+ }
6043
+
6044
+ @media (max-width: 500px) {
6045
+ .summary-grid {
6046
+ grid-template-columns: repeat(2, 1fr);
6047
+ }
6048
+ }
6049
+
6050
+ .summary-card {
6051
+ background: var(--bg-secondary);
6052
+ border-radius: 8px;
6053
+ padding: 1rem;
6054
+ text-align: center;
6055
+ transition: transform 0.2s;
6056
+ }
6057
+
6058
+ .summary-card:hover {
6059
+ transform: translateY(-2px);
6060
+ }
6061
+
6062
+ .summary-value {
6063
+ font-size: 2rem;
6064
+ font-weight: bold;
6065
+ transition: all 0.3s;
6066
+ }
6067
+
6068
+ .summary-value.updated {
6069
+ transform: scale(1.1);
6070
+ }
6071
+
6072
+ .summary-label {
6073
+ color: var(--text-secondary);
6074
+ font-size: 0.75rem;
6075
+ text-transform: uppercase;
6076
+ letter-spacing: 0.05em;
6077
+ }
6078
+
6079
+ .critical { color: var(--accent-red); }
6080
+ .warning { color: var(--accent-yellow); }
6081
+ .healthy { color: var(--accent-green); }
6082
+ .info { color: var(--accent-blue); }
6083
+
6084
+ /* Content */
6085
+ .content {
6086
+ display: grid;
6087
+ grid-template-columns: 2fr 1fr;
6088
+ gap: 1.5rem;
6089
+ margin-bottom: 1.5rem;
6090
+ }
6091
+
6092
+ @media (max-width: 900px) {
6093
+ .content {
6094
+ grid-template-columns: 1fr;
6095
+ }
6096
+ }
6097
+
6098
+ .panel {
6099
+ background: var(--bg-secondary);
6100
+ border-radius: 8px;
6101
+ overflow: hidden;
6102
+ }
6103
+
6104
+ .panel-header {
6105
+ display: flex;
6106
+ justify-content: space-between;
6107
+ align-items: center;
6108
+ padding: 1rem;
6109
+ border-bottom: 1px solid var(--border-color);
6110
+ }
6111
+
6112
+ .panel-header h2 {
6113
+ font-size: 1rem;
6114
+ font-weight: 600;
6115
+ }
6116
+
6117
+ .search-input {
6118
+ padding: 0.5rem 0.75rem;
6119
+ background: var(--bg-tertiary);
6120
+ border: 1px solid var(--border-color);
6121
+ border-radius: 6px;
6122
+ color: var(--text-primary);
6123
+ font-size: 0.875rem;
6124
+ width: 200px;
6125
+ }
6126
+
6127
+ .search-input:focus {
6128
+ outline: none;
6129
+ border-color: var(--accent-blue);
6130
+ }
6131
+
6132
+ .search-input::placeholder {
6133
+ color: var(--text-secondary);
6134
+ }
6135
+
6136
+ /* Table */
6137
+ .table-container {
6138
+ max-height: 400px;
6139
+ overflow-y: auto;
6140
+ }
6141
+
6142
+ .component-table {
6143
+ width: 100%;
6144
+ border-collapse: collapse;
6145
+ }
6146
+
6147
+ .component-table th,
6148
+ .component-table td {
6149
+ padding: 0.75rem 1rem;
6150
+ text-align: left;
6151
+ }
6152
+
6153
+ .component-table th {
6154
+ background: var(--bg-tertiary);
6155
+ font-size: 0.75rem;
6156
+ text-transform: uppercase;
6157
+ color: var(--text-secondary);
6158
+ position: sticky;
6159
+ top: 0;
6160
+ z-index: 1;
6161
+ }
6162
+
6163
+ .component-table th.sortable {
6164
+ cursor: pointer;
6165
+ }
6166
+
6167
+ .component-table th.sortable:hover {
6168
+ color: var(--text-primary);
6169
+ }
6170
+
6171
+ .component-table th.sorted-asc::after {
6172
+ content: ' \u2191';
6173
+ }
6174
+
6175
+ .component-table th.sorted-desc::after {
6176
+ content: ' \u2193';
6177
+ }
6178
+
6179
+ .component-table tbody tr {
6180
+ border-bottom: 1px solid var(--border-color);
6181
+ transition: background 0.2s;
6182
+ }
6183
+
6184
+ .component-table tbody tr:hover {
6185
+ background: var(--bg-tertiary);
6186
+ }
6187
+
6188
+ .component-table tbody tr.new-row {
6189
+ animation: highlight 1s ease-out;
6190
+ }
6191
+
6192
+ @keyframes highlight {
6193
+ from { background: rgba(59, 130, 246, 0.2); }
6194
+ to { background: transparent; }
6195
+ }
6196
+
6197
+ .component-name {
6198
+ font-weight: 500;
6199
+ display: flex;
6200
+ align-items: center;
6201
+ gap: 0.5rem;
6202
+ }
6203
+
6204
+ .severity-badge {
6205
+ display: inline-block;
6206
+ padding: 0.125rem 0.5rem;
6207
+ border-radius: 9999px;
6208
+ font-size: 0.75rem;
6209
+ font-weight: 500;
6210
+ }
6211
+
6212
+ .severity-badge.critical {
6213
+ background: rgba(239, 68, 68, 0.2);
6214
+ }
6215
+
6216
+ .severity-badge.warning {
6217
+ background: rgba(234, 179, 8, 0.2);
6218
+ }
6219
+
6220
+ .severity-badge.healthy {
6221
+ background: rgba(34, 197, 94, 0.2);
6222
+ }
6223
+
6224
+ .empty-row td {
6225
+ text-align: center;
6226
+ color: var(--text-secondary);
6227
+ padding: 2rem;
6228
+ }
6229
+
6230
+ /* Events */
6231
+ .events-container {
6232
+ max-height: 400px;
6233
+ overflow-y: auto;
6234
+ padding: 0.5rem;
6235
+ }
6236
+
6237
+ .event-count {
6238
+ font-size: 0.75rem;
6239
+ color: var(--text-secondary);
6240
+ }
6241
+
6242
+ .event-item {
6243
+ display: flex;
6244
+ align-items: center;
6245
+ gap: 0.5rem;
6246
+ padding: 0.5rem;
6247
+ border-radius: 4px;
6248
+ font-size: 0.875rem;
6249
+ animation: slideIn 0.3s ease-out;
6250
+ }
6251
+
6252
+ @keyframes slideIn {
6253
+ from {
6254
+ opacity: 0;
6255
+ transform: translateX(-10px);
6256
+ }
6257
+ to {
6258
+ opacity: 1;
6259
+ transform: translateX(0);
6260
+ }
6261
+ }
6262
+
6263
+ .event-item:nth-child(odd) {
6264
+ background: var(--bg-tertiary);
6265
+ }
6266
+
6267
+ .event-dot {
6268
+ width: 6px;
6269
+ height: 6px;
6270
+ border-radius: 50%;
6271
+ flex-shrink: 0;
6272
+ }
6273
+
6274
+ .event-name {
6275
+ flex: 1;
6276
+ overflow: hidden;
6277
+ text-overflow: ellipsis;
6278
+ white-space: nowrap;
6279
+ }
6280
+
6281
+ .event-time {
6282
+ font-size: 0.75rem;
6283
+ color: var(--text-secondary);
6284
+ }
6285
+
6286
+ .empty-message {
6287
+ color: var(--text-secondary);
6288
+ text-align: center;
6289
+ padding: 2rem;
6290
+ font-size: 0.875rem;
6291
+ }
6292
+
6293
+ /* Chains */
6294
+ .chains-section .panel {
6295
+ min-height: 150px;
6296
+ }
6297
+
6298
+ .chains-container {
6299
+ padding: 1rem;
6300
+ max-height: 300px;
6301
+ overflow-y: auto;
6302
+ }
6303
+
6304
+ .chain-item {
6305
+ background: var(--bg-tertiary);
6306
+ border-radius: 6px;
6307
+ padding: 1rem;
6308
+ margin-bottom: 0.75rem;
6309
+ animation: slideIn 0.3s ease-out;
6310
+ }
6311
+
6312
+ .chain-trigger {
6313
+ font-weight: 500;
6314
+ margin-bottom: 0.5rem;
6315
+ color: var(--accent-purple);
6316
+ }
6317
+
6318
+ .chain-flow {
6319
+ font-family: 'SF Mono', 'Fira Code', monospace;
6320
+ font-size: 0.875rem;
6321
+ color: var(--text-secondary);
6322
+ overflow-x: auto;
6323
+ white-space: nowrap;
6324
+ padding: 0.5rem 0;
6325
+ }
6326
+
6327
+ .chain-flow span {
6328
+ color: var(--text-primary);
6329
+ }
6330
+
6331
+ .chain-flow .arrow {
6332
+ color: var(--accent-yellow);
6333
+ margin: 0 0.25rem;
6334
+ }
6335
+
6336
+ .chain-meta {
6337
+ font-size: 0.75rem;
6338
+ color: var(--text-secondary);
6339
+ margin-top: 0.5rem;
6340
+ }
6341
+
6342
+ /* Scrollbar */
6343
+ ::-webkit-scrollbar {
6344
+ width: 8px;
6345
+ height: 8px;
6346
+ }
6347
+
6348
+ ::-webkit-scrollbar-track {
6349
+ background: var(--bg-primary);
6350
+ }
6351
+
6352
+ ::-webkit-scrollbar-thumb {
6353
+ background: var(--border-color);
6354
+ border-radius: 4px;
6355
+ }
6356
+
6357
+ ::-webkit-scrollbar-thumb:hover {
6358
+ background: var(--text-secondary);
6359
+ }
6360
+ `;
6361
+ }
6362
+ function getScript(wsPort) {
6363
+ return `
6364
+ (function() {
6365
+ // State
6366
+ let ws = null;
6367
+ let state = null;
6368
+ let startTime = Date.now();
6369
+ let eventCount = 0;
6370
+ let sortColumn = 'renders';
6371
+ let sortDirection = 'desc';
6372
+ let searchQuery = '';
6373
+
6374
+ // Elements
6375
+ const statusEl = document.getElementById('status');
6376
+ const statusTextEl = statusEl.querySelector('.status-text');
6377
+ const durationEl = document.getElementById('duration');
6378
+ const componentsEl = document.getElementById('components');
6379
+ const rendersEl = document.getElementById('renders');
6380
+ const criticalEl = document.getElementById('critical');
6381
+ const warningsEl = document.getElementById('warnings');
6382
+ const healthyEl = document.getElementById('healthy');
6383
+ const fpsEl = document.getElementById('fps');
6384
+ const componentListEl = document.getElementById('component-list');
6385
+ const eventsEl = document.getElementById('events');
6386
+ const eventCountEl = document.getElementById('event-count');
6387
+ const chainsEl = document.getElementById('chains');
6388
+ const searchEl = document.getElementById('search');
6389
+ const exportBtn = document.getElementById('export-btn');
6390
+
6391
+ // Connect to WebSocket
6392
+ function connect() {
6393
+ ws = new WebSocket('ws://localhost:${wsPort}');
6394
+
6395
+ ws.onopen = () => {
6396
+ statusEl.className = 'status connected';
6397
+ statusTextEl.textContent = 'Connected';
6398
+ exportBtn.disabled = false;
6399
+ };
6400
+
6401
+ ws.onclose = () => {
6402
+ statusEl.className = 'status';
6403
+ statusTextEl.textContent = 'Disconnected';
6404
+ exportBtn.disabled = true;
6405
+ setTimeout(connect, 2000);
6406
+ };
6407
+
6408
+ ws.onerror = () => {
6409
+ ws.close();
6410
+ };
6411
+
6412
+ ws.onmessage = (event) => {
6413
+ try {
6414
+ const msg = JSON.parse(event.data);
6415
+ handleMessage(msg);
6416
+ } catch (e) {
6417
+ console.error('Failed to parse message:', e);
6418
+ }
6419
+ };
6420
+ }
6421
+
6422
+ // Handle incoming messages
6423
+ function handleMessage(msg) {
6424
+ switch (msg.type) {
6425
+ case 'state':
6426
+ state = msg.payload;
6427
+ startTime = msg.payload.startTime;
6428
+ updateStatus(msg.payload);
6429
+ updateSummary(msg.payload.summary);
6430
+ renderComponents(msg.payload.components);
6431
+ renderChains(msg.payload.chains);
6432
+ break;
6433
+
6434
+ case 'summary-update':
6435
+ updateSummary(msg.payload);
6436
+ break;
6437
+
6438
+ case 'component-update':
6439
+ updateComponent(msg.payload);
6440
+ break;
6441
+
6442
+ case 'render-event':
6443
+ addEvent(msg.payload);
6444
+ break;
6445
+
6446
+ case 'chain-detected':
6447
+ addChain(msg.payload);
6448
+ break;
6449
+
6450
+ case 'scanning-status':
6451
+ updateScanningStatus(msg.payload);
6452
+ break;
6453
+ }
6454
+ }
6455
+
6456
+ // Update status
6457
+ function updateStatus(data) {
6458
+ if (data.scanning && !data.paused) {
6459
+ statusEl.className = 'status scanning';
6460
+ statusTextEl.textContent = 'Scanning';
6461
+ } else if (data.paused) {
6462
+ statusEl.className = 'status paused';
6463
+ statusTextEl.textContent = 'Paused';
6464
+ } else {
6465
+ statusEl.className = 'status connected';
6466
+ statusTextEl.textContent = 'Connected';
6467
+ }
6468
+ }
6469
+
6470
+ function updateScanningStatus(data) {
6471
+ if (data.scanning && !data.paused) {
6472
+ statusEl.className = 'status scanning';
6473
+ statusTextEl.textContent = 'Scanning';
6474
+ } else if (data.paused) {
6475
+ statusEl.className = 'status paused';
6476
+ statusTextEl.textContent = 'Paused';
6477
+ } else {
6478
+ statusEl.className = 'status connected';
6479
+ statusTextEl.textContent = 'Connected';
6480
+ }
6481
+ }
6482
+
6483
+ // Update summary with animation
6484
+ function updateSummary(summary) {
6485
+ animateValue(componentsEl, summary.totalComponents);
6486
+ animateValue(rendersEl, summary.totalRenders);
6487
+ animateValue(criticalEl, summary.criticalIssues);
6488
+ animateValue(warningsEl, summary.warnings);
6489
+ animateValue(healthyEl, summary.healthy);
6490
+ animateValue(fpsEl, summary.avgFps);
6491
+ }
6492
+
6493
+ function animateValue(el, value) {
6494
+ const current = parseInt(el.textContent) || 0;
6495
+ if (current !== value) {
6496
+ el.textContent = value;
6497
+ el.classList.add('updated');
6498
+ setTimeout(() => el.classList.remove('updated'), 300);
6499
+ }
6500
+ }
6501
+
6502
+ // Update single component
6503
+ function updateComponent(component) {
6504
+ if (!state) state = { components: [] };
6505
+ const idx = state.components.findIndex(c => c.name === component.name);
6506
+ if (idx >= 0) {
6507
+ state.components[idx] = component;
6508
+ } else {
6509
+ state.components.push(component);
6510
+ }
6511
+ renderComponents(state.components);
6512
+ }
6513
+
6514
+ // Render components table
6515
+ function renderComponents(components) {
6516
+ if (!components || components.length === 0) {
6517
+ componentListEl.innerHTML = '<tr class="empty-row"><td colspan="5">No components detected yet...</td></tr>';
6518
+ return;
6519
+ }
6520
+
6521
+ // Filter
6522
+ let filtered = components;
6523
+ if (searchQuery) {
6524
+ filtered = components.filter(c =>
6525
+ c.name.toLowerCase().includes(searchQuery.toLowerCase())
6526
+ );
6527
+ }
6528
+
6529
+ // Sort
6530
+ filtered.sort((a, b) => {
6531
+ let aVal, bVal;
6532
+ switch (sortColumn) {
6533
+ case 'name': aVal = a.name; bVal = b.name; break;
6534
+ case 'renders': aVal = a.renders; bVal = b.renders; break;
6535
+ case 'unnecessary': aVal = a.unnecessary; bVal = b.unnecessary; break;
6536
+ case 'avgTime': aVal = a.avgRenderTime; bVal = b.avgRenderTime; break;
6537
+ case 'severity':
6538
+ const order = { critical: 0, warning: 1, info: 2, healthy: 3 };
6539
+ aVal = order[a.severity] ?? 4;
6540
+ bVal = order[b.severity] ?? 4;
6541
+ break;
6542
+ default: aVal = a.renders; bVal = b.renders;
6543
+ }
6544
+ if (typeof aVal === 'string') {
6545
+ return sortDirection === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
6546
+ }
6547
+ return sortDirection === 'asc' ? aVal - bVal : bVal - aVal;
6548
+ });
6549
+
6550
+ componentListEl.innerHTML = filtered.slice(0, 100).map(c => \`
6551
+ <tr data-name="\${escapeHtml(c.name)}">
6552
+ <td class="component-name">
6553
+ <span class="severity-indicator \${c.severity}"></span>
6554
+ \${escapeHtml(c.name)}
6555
+ </td>
6556
+ <td>\${c.renders}</td>
6557
+ <td>\${c.unnecessary}</td>
6558
+ <td>\${c.avgRenderTime.toFixed(2)}ms</td>
6559
+ <td><span class="severity-badge \${c.severity}">\${c.severity}</span></td>
6560
+ </tr>
6561
+ \`).join('');
6562
+ }
6563
+
6564
+ // Add event to timeline
6565
+ function addEvent(render) {
6566
+ eventCount++;
6567
+ eventCountEl.textContent = eventCount + ' events';
6568
+
6569
+ const isEmpty = eventsEl.querySelector('.empty-message');
6570
+ if (isEmpty) isEmpty.remove();
6571
+
6572
+ const severityColor = {
6573
+ critical: 'var(--accent-red)',
6574
+ warning: 'var(--accent-yellow)',
6575
+ info: 'var(--accent-blue)',
6576
+ healthy: 'var(--accent-green)'
6577
+ };
6578
+
6579
+ const color = render.renderCount > 50 ? severityColor.critical :
6580
+ render.renderCount > 20 ? severityColor.warning :
6581
+ severityColor.healthy;
6582
+
6583
+ const time = new Date(render.timestamp || Date.now()).toLocaleTimeString();
6584
+
6585
+ const eventHtml = \`
6586
+ <div class="event-item">
6587
+ <div class="event-dot" style="background: \${color}"></div>
6588
+ <span class="event-name">\${escapeHtml(render.componentName)}</span>
6589
+ <span class="event-time">\${time}</span>
6590
+ </div>
6591
+ \`;
6592
+
6593
+ eventsEl.insertAdjacentHTML('afterbegin', eventHtml);
6594
+
6595
+ // Keep only last 100 events
6596
+ while (eventsEl.children.length > 100) {
6597
+ eventsEl.lastChild.remove();
6598
+ }
6599
+ }
6600
+
6601
+ // Render chains
6602
+ function renderChains(chains) {
6603
+ if (!chains || chains.length === 0) {
6604
+ chainsEl.innerHTML = '<div class="empty-message">No render chains detected yet...</div>';
6605
+ return;
6606
+ }
6607
+
6608
+ chainsEl.innerHTML = chains.slice(0, 10).map(chain => \`
6609
+ <div class="chain-item">
6610
+ <div class="chain-trigger">Trigger: \${escapeHtml(chain.trigger)}</div>
6611
+ <div class="chain-flow">
6612
+ \${chain.chain.map((c, i) =>
6613
+ i === 0 ? \`<span style="color: var(--accent-red)">\${escapeHtml(c)}</span>\` :
6614
+ \`<span class="arrow">\u2192</span><span>\${escapeHtml(c)}</span>\`
6615
+ ).join('')}
6616
+ </div>
6617
+ <div class="chain-meta">Depth: \${chain.depth} \u2022 Renders: \${chain.totalRenders}</div>
6618
+ </div>
6619
+ \`).join('');
6620
+ }
6621
+
6622
+ // Add chain
6623
+ function addChain(chain) {
6624
+ if (!state) state = { chains: [] };
6625
+ state.chains.unshift(chain);
6626
+ if (state.chains.length > 20) state.chains.pop();
6627
+ renderChains(state.chains);
6628
+ }
6629
+
6630
+ // Escape HTML
6631
+ function escapeHtml(str) {
6632
+ if (!str) return '';
6633
+ return str.replace(/&/g, '&amp;')
6634
+ .replace(/</g, '&lt;')
6635
+ .replace(/>/g, '&gt;')
6636
+ .replace(/"/g, '&quot;');
6637
+ }
6638
+
6639
+ // Update duration
6640
+ function updateDuration() {
6641
+ const elapsed = Math.floor((Date.now() - startTime) / 1000);
6642
+ const mins = Math.floor(elapsed / 60);
6643
+ const secs = elapsed % 60;
6644
+ durationEl.textContent = 'Duration: ' + (mins > 0 ? mins + 'm ' : '') + secs + 's';
6645
+ }
6646
+
6647
+ // Setup sorting
6648
+ document.querySelectorAll('.sortable').forEach(th => {
6649
+ th.addEventListener('click', () => {
6650
+ const column = th.dataset.sort;
6651
+ if (sortColumn === column) {
6652
+ sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
6653
+ } else {
6654
+ sortColumn = column;
6655
+ sortDirection = 'desc';
6656
+ }
6657
+
6658
+ document.querySelectorAll('.sortable').forEach(el => {
6659
+ el.classList.remove('sorted-asc', 'sorted-desc');
6660
+ });
6661
+ th.classList.add(sortDirection === 'asc' ? 'sorted-asc' : 'sorted-desc');
6662
+
6663
+ if (state && state.components) {
6664
+ renderComponents(state.components);
6665
+ }
6666
+ });
6667
+ });
6668
+
6669
+ // Setup search
6670
+ searchEl.addEventListener('input', (e) => {
6671
+ searchQuery = e.target.value;
6672
+ if (state && state.components) {
6673
+ renderComponents(state.components);
6674
+ }
6675
+ });
6676
+
6677
+ // Setup export
6678
+ exportBtn.addEventListener('click', () => {
6679
+ if (!state) return;
6680
+ const data = JSON.stringify(state, null, 2);
6681
+ const blob = new Blob([data], { type: 'application/json' });
6682
+ const url = URL.createObjectURL(blob);
6683
+ const a = document.createElement('a');
6684
+ a.href = url;
6685
+ a.download = 'reactcheck-export-' + Date.now() + '.json';
6686
+ a.click();
6687
+ URL.revokeObjectURL(url);
6688
+ });
6689
+
6690
+ // Start
6691
+ connect();
6692
+ setInterval(updateDuration, 1000);
6693
+
6694
+ // Mark initial sort column
6695
+ document.querySelector('[data-sort="renders"]').classList.add('sorted-desc');
6696
+ })();
6697
+ `;
6698
+ }
6699
+
6700
+ // src/webui/server.ts
6701
+ var OPCODE2 = {
6702
+ CLOSE: 8,
6703
+ PING: 9};
6704
+ var WS_GUID2 = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
6705
+ var DashboardClient = class {
6706
+ socket;
6707
+ isOpen = true;
6708
+ constructor(socket) {
6709
+ this.socket = socket;
6710
+ this.socket.on("close", () => {
6711
+ this.isOpen = false;
6712
+ });
6713
+ this.socket.on("error", () => {
6714
+ this.isOpen = false;
6715
+ });
6716
+ }
6717
+ /**
6718
+ * Send a message to the client
6719
+ */
6720
+ send(message) {
6721
+ if (!this.isOpen) return;
6722
+ try {
6723
+ const data = JSON.stringify(message);
6724
+ const frame = this.createFrame(data);
6725
+ this.socket.write(frame);
6726
+ } catch {
6727
+ }
6728
+ }
6729
+ /**
6730
+ * Create a WebSocket frame
6731
+ */
6732
+ createFrame(data) {
6733
+ const payload = Buffer.from(data, "utf8");
6734
+ const length = payload.length;
6735
+ let frame;
6736
+ if (length < 126) {
6737
+ frame = Buffer.alloc(2 + length);
6738
+ frame[0] = 129;
6739
+ frame[1] = length;
6740
+ payload.copy(frame, 2);
6741
+ } else if (length < 65536) {
6742
+ frame = Buffer.alloc(4 + length);
6743
+ frame[0] = 129;
6744
+ frame[1] = 126;
6745
+ frame.writeUInt16BE(length, 2);
6746
+ payload.copy(frame, 4);
6747
+ } else {
6748
+ frame = Buffer.alloc(10 + length);
6749
+ frame[0] = 129;
6750
+ frame[1] = 127;
6751
+ frame.writeBigUInt64BE(BigInt(length), 2);
6752
+ payload.copy(frame, 10);
6753
+ }
6754
+ return frame;
6755
+ }
6756
+ /**
6757
+ * Close the connection
6758
+ */
6759
+ close() {
6760
+ if (!this.isOpen) return;
6761
+ this.isOpen = false;
6762
+ try {
6763
+ const frame = Buffer.alloc(2);
6764
+ frame[0] = 136;
6765
+ frame[1] = 0;
6766
+ this.socket.write(frame);
6767
+ this.socket.end();
6768
+ } catch {
6769
+ }
6770
+ }
6771
+ /**
6772
+ * Check if client is connected
6773
+ */
6774
+ isConnected() {
6775
+ return this.isOpen;
6776
+ }
6777
+ };
6778
+ var WebUIServer = class extends EventEmitter {
6779
+ server = null;
6780
+ clients = /* @__PURE__ */ new Set();
6781
+ port;
6782
+ target;
6783
+ currentState;
6784
+ constructor(port = 3100, target = "") {
6785
+ super();
6786
+ this.port = port;
6787
+ this.target = target;
6788
+ this.currentState = this.createInitialState();
6789
+ }
6790
+ /**
6791
+ * Create initial dashboard state
6792
+ */
6793
+ createInitialState() {
6794
+ return {
6795
+ target: this.target,
6796
+ startTime: Date.now(),
6797
+ scanning: false,
6798
+ paused: false,
6799
+ fps: 60,
6800
+ summary: {
6801
+ totalComponents: 0,
6802
+ totalRenders: 0,
6803
+ criticalIssues: 0,
6804
+ warnings: 0,
6805
+ healthy: 0,
6806
+ avgFps: 60,
6807
+ minFps: 60,
6808
+ unnecessaryRenders: 0
6809
+ },
6810
+ components: [],
6811
+ chains: [],
6812
+ recentRenders: []
6813
+ };
6814
+ }
6815
+ /**
6816
+ * Start the server
6817
+ */
6818
+ async start() {
6819
+ return new Promise((resolve3, reject) => {
6820
+ this.server = createServer((req, res) => {
6821
+ this.handleHttpRequest(req, res);
6822
+ });
6823
+ this.server.on("upgrade", (req, socket, head) => {
6824
+ this.handleUpgrade(req, socket);
6825
+ });
6826
+ this.server.on("error", (error) => {
6827
+ if (error.code === "EADDRINUSE") {
6828
+ this.port++;
6829
+ this.server?.close();
6830
+ this.start().then(resolve3).catch(reject);
6831
+ } else {
6832
+ this.emit("error", error);
6833
+ reject(error);
6834
+ }
6835
+ });
6836
+ this.server.listen(this.port, () => {
6837
+ this.emit("listening", this.port);
6838
+ resolve3(this.port);
6839
+ });
6840
+ });
6841
+ }
6842
+ /**
6843
+ * Stop the server
6844
+ */
6845
+ stop() {
6846
+ for (const client of this.clients) {
6847
+ client.close();
6848
+ }
6849
+ this.clients.clear();
6850
+ if (this.server) {
6851
+ this.server.close();
6852
+ this.server = null;
6853
+ }
6854
+ this.emit("close", void 0);
6855
+ }
6856
+ /**
6857
+ * Handle HTTP requests
6858
+ */
6859
+ handleHttpRequest(req, res) {
6860
+ const url = req.url ?? "/";
6861
+ if (url === "/" || url === "/index.html") {
6862
+ const html = generateDashboardHTML(this.port, this.target);
6863
+ res.writeHead(200, {
6864
+ "Content-Type": "text/html; charset=utf-8",
6865
+ "Cache-Control": "no-cache"
6866
+ });
6867
+ res.end(html);
6868
+ } else if (url === "/health") {
6869
+ res.writeHead(200, { "Content-Type": "application/json" });
6870
+ res.end(JSON.stringify({ status: "ok", clients: this.clients.size }));
6871
+ } else {
6872
+ res.writeHead(404, { "Content-Type": "text/plain" });
6873
+ res.end("Not Found");
6874
+ }
6875
+ }
6876
+ /**
6877
+ * Handle WebSocket upgrade
6878
+ */
6879
+ handleUpgrade(req, socket) {
6880
+ const key = req.headers["sec-websocket-key"];
6881
+ if (!key) {
6882
+ socket.destroy();
6883
+ return;
6884
+ }
6885
+ const acceptKey = createHash("sha1").update(key + WS_GUID2).digest("base64");
6886
+ const headers = [
6887
+ "HTTP/1.1 101 Switching Protocols",
6888
+ "Upgrade: websocket",
6889
+ "Connection: Upgrade",
6890
+ `Sec-WebSocket-Accept: ${acceptKey}`,
6891
+ "",
6892
+ ""
6893
+ ].join("\r\n");
6894
+ socket.write(headers);
6895
+ const client = new DashboardClient(socket);
6896
+ this.clients.add(client);
6897
+ this.emit("client-connected", void 0);
6898
+ client.send({ type: "state", payload: this.currentState });
6899
+ socket.on("close", () => {
6900
+ this.clients.delete(client);
6901
+ this.emit("client-disconnected", void 0);
6902
+ });
6903
+ socket.on("data", (data) => {
6904
+ this.handleClientData(client, socket, data);
6905
+ });
6906
+ }
6907
+ /**
6908
+ * Handle data from client
6909
+ */
6910
+ handleClientData(client, socket, data) {
6911
+ if (data.length < 2) return;
6912
+ const opcode = data[0] & 15;
6913
+ if (opcode === OPCODE2.PING) {
6914
+ const pong = Buffer.alloc(2);
6915
+ pong[0] = 138;
6916
+ pong[1] = 0;
6917
+ socket.write(pong);
6918
+ } else if (opcode === OPCODE2.CLOSE) {
6919
+ this.clients.delete(client);
6920
+ client.close();
6921
+ }
6922
+ }
6923
+ /**
6924
+ * Update target URL
6925
+ */
6926
+ setTarget(target) {
6927
+ this.target = target;
6928
+ this.currentState.target = target;
6929
+ }
6930
+ /**
6931
+ * Update scanning status
6932
+ */
6933
+ setScanning(scanning, paused = false) {
6934
+ this.currentState.scanning = scanning;
6935
+ this.currentState.paused = paused;
6936
+ this.broadcast({ type: "scanning-status", payload: { scanning, paused } });
6937
+ }
6938
+ /**
6939
+ * Update summary
6940
+ */
6941
+ updateSummary(summary) {
6942
+ this.currentState.summary = summary;
6943
+ this.broadcast({ type: "summary-update", payload: summary });
6944
+ }
6945
+ /**
6946
+ * Update components
6947
+ */
6948
+ updateComponents(components) {
6949
+ this.currentState.components = components;
6950
+ }
6951
+ /**
6952
+ * Update FPS
6953
+ */
6954
+ updateFps(fps) {
6955
+ this.currentState.fps = fps;
6956
+ }
6957
+ /**
6958
+ * Add render event
6959
+ */
6960
+ addRenderEvent(render) {
6961
+ this.currentState.recentRenders.unshift(render);
6962
+ if (this.currentState.recentRenders.length > 50) {
6963
+ this.currentState.recentRenders.pop();
6964
+ }
6965
+ this.broadcast({ type: "render-event", payload: render });
6966
+ }
6967
+ /**
6968
+ * Add chain detected
6969
+ */
6970
+ addChain(chain) {
6971
+ this.currentState.chains.unshift(chain);
6972
+ if (this.currentState.chains.length > 20) {
6973
+ this.currentState.chains.pop();
6974
+ }
6975
+ this.broadcast({ type: "chain-detected", payload: chain });
6976
+ }
6977
+ /**
6978
+ * Update component
6979
+ */
6980
+ updateComponent(component) {
6981
+ const index = this.currentState.components.findIndex((c) => c.name === component.name);
6982
+ if (index >= 0) {
6983
+ this.currentState.components[index] = component;
6984
+ } else {
6985
+ this.currentState.components.push(component);
6986
+ }
6987
+ this.broadcast({ type: "component-update", payload: component });
6988
+ }
6989
+ /**
6990
+ * Broadcast full state to all clients
6991
+ */
6992
+ broadcastState() {
6993
+ this.broadcast({ type: "state", payload: this.currentState });
6994
+ }
6995
+ /**
6996
+ * Broadcast message to all clients
6997
+ */
6998
+ broadcast(message) {
6999
+ for (const client of this.clients) {
7000
+ if (client.isConnected()) {
7001
+ client.send(message);
7002
+ } else {
7003
+ this.clients.delete(client);
7004
+ }
7005
+ }
7006
+ }
7007
+ /**
7008
+ * Get current port
7009
+ */
7010
+ getPort() {
7011
+ return this.port;
7012
+ }
7013
+ /**
7014
+ * Get client count
7015
+ */
7016
+ getClientCount() {
7017
+ return this.clients.size;
7018
+ }
7019
+ /**
7020
+ * Get dashboard URL
7021
+ */
7022
+ getUrl() {
7023
+ return `http://localhost:${this.port}`;
7024
+ }
7025
+ };
7026
+ var logger4 = new Logger({ prefix: "scan", level: 1 /* INFO */ });
7027
+ function parseScanOptions(args) {
7028
+ return {
7029
+ target: normalizeTarget(args.target ?? "localhost:3000"),
7030
+ proxy: getBooleanFlag(args, "proxy"),
7031
+ tui: getBooleanFlag(args, "tui"),
7032
+ silent: getBooleanFlag(args, "silent"),
7033
+ report: getBooleanFlag(args, "report"),
7034
+ format: getStringFlag(args, "format") ?? "all",
7035
+ output: getStringFlag(args, "output") ?? "./reactcheck-reports",
7036
+ fix: getBooleanFlag(args, "fix"),
7037
+ verbose: getBooleanFlag(args, "verbose"),
7038
+ port: getNumberFlag(args, "port") ?? 3099,
7039
+ thresholdCritical: getNumberFlag(args, "threshold-critical") ?? 50,
7040
+ thresholdWarning: getNumberFlag(args, "threshold-warning") ?? 20,
7041
+ fpsThreshold: getNumberFlag(args, "fps-threshold") ?? 30,
7042
+ headless: getBooleanFlag(args, "headless"),
7043
+ duration: getNumberFlag(args, "duration"),
7044
+ watch: getBooleanFlag(args, "watch"),
7045
+ configPath: getStringFlag(args, "config"),
7046
+ webui: getBooleanFlag(args, "webui"),
7047
+ webuiPort: getNumberFlag(args, "webui-port") ?? 3100
7048
+ };
7049
+ }
7050
+ async function getInjectionScript(wsPort) {
7051
+ try {
7052
+ const currentFile = fileURLToPath(import.meta.url);
7053
+ const currentDir = dirname(currentFile);
7054
+ const scriptPath = resolve(currentDir, "browser-inject.global.js");
7055
+ logger4.debug(`Loading injection script from: ${scriptPath}`);
7056
+ const script = await readTextFile(scriptPath);
7057
+ return `window.__REACTCHECK_PORT__ = ${wsPort};
7058
+ ${script}`;
7059
+ } catch (error) {
7060
+ logger4.debug(`Failed to load injection script: ${error}`);
7061
+ logger4.warn("Could not load injection script, using minimal version");
7062
+ return `
7063
+ window.__REACTCHECK_PORT__ = ${wsPort};
7064
+ window.__REACTCHECK_INJECTED__ = true;
7065
+
7066
+ // Install React DevTools hook
7067
+ if (!window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
7068
+ const hook = {
7069
+ renderers: new Map(),
7070
+ supportsFiber: true,
7071
+ inject: function(renderer) {
7072
+ const id = this.renderers.size + 1;
7073
+ this.renderers.set(id, renderer);
7074
+ return id;
7075
+ },
7076
+ onCommitFiberRoot: function(id, root) {
7077
+ // Will be overwritten by full script
7078
+ },
7079
+ onCommitFiberUnmount: function() {},
7080
+ };
7081
+ window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook;
7082
+ console.log('[ReactCheck] DevTools hook installed (minimal)');
7083
+ }
7084
+ `;
7085
+ }
7086
+ }
7087
+ async function runScanCommand(args) {
7088
+ const options = parseScanOptions(args);
7089
+ const { config, configPath, fromFile } = await loadConfig(options.configPath);
7090
+ if (fromFile) {
7091
+ logger4.info(`Using config: ${configPath}`);
7092
+ }
7093
+ const configOptions = configToOptions(config);
7094
+ const mergedOptions = {
7095
+ ...options,
7096
+ thresholdCritical: options.thresholdCritical ?? configOptions.thresholds.critical,
7097
+ thresholdWarning: options.thresholdWarning ?? configOptions.thresholds.warning,
7098
+ fpsThreshold: options.fpsThreshold ?? configOptions.thresholds.fps,
7099
+ output: options.output ?? configOptions.report.output
7100
+ };
7101
+ const session = {
7102
+ id: generateId("scan"),
7103
+ startTime: Date.now(),
7104
+ scanner: new Scanner({
7105
+ thresholds: {
7106
+ critical: mergedOptions.thresholdCritical,
7107
+ warning: mergedOptions.thresholdWarning,
7108
+ fps: mergedOptions.fpsThreshold
7109
+ }
7110
+ }),
7111
+ tui: null,
7112
+ wsServer: null,
7113
+ browser: null,
7114
+ webui: null,
7115
+ options: mergedOptions,
7116
+ active: true,
7117
+ chains: [],
7118
+ suggestions: []
7119
+ };
7120
+ setupScannerEvents(session);
7121
+ const useTUI = !mergedOptions.silent && !mergedOptions.proxy;
7122
+ if (useTUI) {
7123
+ session.tui = new TUI(mergedOptions.target);
7124
+ setupTUIEvents(session);
7125
+ session.tui.setDataProvider(() => ({
7126
+ components: session.scanner.getSnapshot(),
7127
+ summary: session.scanner.getSummary(),
7128
+ fps: session.scanner.getFps()
7129
+ }));
7130
+ session.tui.start();
7131
+ }
7132
+ if (mergedOptions.webui) {
7133
+ session.webui = new WebUIServer(mergedOptions.webuiPort, mergedOptions.target);
7134
+ setupWebUIEvents(session);
7135
+ }
7136
+ if (!useTUI) {
7137
+ logger4.info(`Starting scan of ${mergedOptions.target}`);
7138
+ }
7139
+ if (useTUI) {
7140
+ logger4.setLevel(4 /* SILENT */);
7141
+ }
7142
+ try {
7143
+ session.wsServer = new WebSocketServer(mergedOptions.port);
7144
+ await session.wsServer.start();
7145
+ logger4.info(`WebSocket server listening on port ${mergedOptions.port}`);
7146
+ session.wsServer.on("connection", (client) => {
7147
+ logger4.info("Browser connected");
7148
+ handleBrowserMessages(client, (message) => {
7149
+ switch (message.type) {
7150
+ case "render":
7151
+ session.scanner.addRender(message.payload);
7152
+ break;
7153
+ case "ready":
7154
+ logger4.info(`React detected: ${message.payload.reactVersion}`);
7155
+ client.send(JSON.stringify({ type: "start" }));
7156
+ break;
7157
+ case "error":
7158
+ logger4.error("Browser error:", message.payload.message);
7159
+ break;
7160
+ }
7161
+ });
7162
+ client.on("close", () => {
7163
+ logger4.info("Browser disconnected");
7164
+ });
7165
+ });
7166
+ session.scanner.start();
7167
+ if (session.webui) {
7168
+ const webuiPort = await session.webui.start();
7169
+ session.webui.setScanning(true);
7170
+ const webuiUrl = session.webui.getUrl();
7171
+ logger4.info(`WebUI dashboard: ${webuiUrl}`);
7172
+ openBrowser(webuiUrl);
7173
+ }
7174
+ if (mergedOptions.proxy) {
7175
+ console.log("");
7176
+ console.log(colors.cyan + colors.bold + "\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557" + colors.reset);
7177
+ console.log(colors.cyan + colors.bold + "\u2551 PROXY MODE ACTIVE \u2551" + colors.reset);
7178
+ console.log(colors.cyan + colors.bold + "\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D" + colors.reset);
7179
+ console.log("");
7180
+ console.log(` Add this script to your HTML before React loads:`);
7181
+ console.log("");
7182
+ console.log(colors.yellow + ` <script>window.__REACTCHECK_PORT__ = ${mergedOptions.port};</script>` + colors.reset);
7183
+ console.log(colors.yellow + ` <script src="http://localhost:${mergedOptions.port + 1}/reactcheck.js"></script>` + colors.reset);
7184
+ console.log("");
7185
+ console.log(` Or open: ${colors.cyan}${mergedOptions.target}${colors.reset}`);
7186
+ console.log("");
7187
+ console.log(` Press ${colors.bold}Ctrl+C${colors.reset} to stop scanning`);
7188
+ console.log("");
7189
+ } else {
7190
+ const hasPuppeteer = await isPuppeteerAvailable();
7191
+ if (!hasPuppeteer) {
7192
+ logger4.error("Puppeteer is not installed. Install it with: npm install puppeteer");
7193
+ logger4.info("Alternatively, use --proxy mode to scan with your own browser");
7194
+ await session.wsServer.stop();
7195
+ return 2;
7196
+ }
7197
+ const injectionScript = await getInjectionScript(mergedOptions.port);
7198
+ session.browser = new BrowserLauncher({
7199
+ url: mergedOptions.target,
7200
+ headless: mergedOptions.headless,
7201
+ wsPort: mergedOptions.port
7202
+ });
7203
+ session.browser.setInjectionScript(injectionScript);
7204
+ session.browser.on("console", ({ type, text }) => {
7205
+ if (text.includes("[ReactCheck]")) {
7206
+ logger4.info(`Browser: ${text}`);
7207
+ }
7208
+ });
7209
+ session.browser.on("error", (error) => {
7210
+ logger4.error("Browser error:", error.message);
7211
+ });
7212
+ logger4.info("Launching browser...");
7213
+ await session.browser.launch();
7214
+ logger4.info("Browser launched, scanning...");
7215
+ }
7216
+ if (mergedOptions.duration) {
7217
+ await new Promise((resolve3) => setTimeout(resolve3, mergedOptions.duration * 1e3));
7218
+ session.active = false;
7219
+ } else if (session.tui) {
7220
+ await waitForQuit(session);
7221
+ } else {
7222
+ await waitForSignal();
7223
+ session.active = false;
7224
+ }
7225
+ await cleanupSession(session);
7226
+ if (mergedOptions.report) {
7227
+ const report = generateReport(session);
7228
+ await saveReport(report, mergedOptions);
7229
+ }
7230
+ printSummary(session);
7231
+ if (mergedOptions.fix && !mergedOptions.silent) {
7232
+ printFixSuggestions(session.suggestions);
7233
+ }
7234
+ const summary = session.scanner.getSummary();
7235
+ return summary.criticalIssues > 0 ? 1 : 0;
7236
+ } catch (error) {
7237
+ await cleanupSession(session);
7238
+ logger4.error("Scan failed:", error);
7239
+ return 2;
7240
+ }
7241
+ }
7242
+ async function cleanupSession(session) {
7243
+ session.scanner.stop();
7244
+ if (session.tui) {
7245
+ session.tui.stop();
7246
+ }
7247
+ if (session.webui) {
7248
+ session.webui.stop();
7249
+ }
7250
+ if (session.browser) {
7251
+ await session.browser.close();
7252
+ }
7253
+ if (session.wsServer) {
7254
+ await session.wsServer.stop();
7255
+ }
7256
+ }
7257
+ function setupScannerEvents(session) {
7258
+ const { scanner } = session;
7259
+ scanner.on("render", () => {
7260
+ if (session.tui) {
7261
+ const snapshot = scanner.getSnapshot();
7262
+ const summary = scanner.getSummary();
7263
+ session.tui.update({
7264
+ components: snapshot,
7265
+ summary,
7266
+ fps: scanner.getFps()
7267
+ });
7268
+ }
7269
+ });
7270
+ scanner.on("chain", (chain) => {
7271
+ session.chains.push(chain);
7272
+ if (session.tui) {
7273
+ session.tui.update({ chains: session.chains.slice(-10) });
7274
+ }
7275
+ });
7276
+ scanner.on("fix", (suggestion) => {
7277
+ if (!session.suggestions.some(
7278
+ (s) => s.componentName === suggestion.componentName && s.fix === suggestion.fix
7279
+ )) {
7280
+ session.suggestions.push(suggestion);
7281
+ if (session.tui) {
7282
+ session.tui.update({ suggestions: session.suggestions });
7283
+ }
7284
+ }
7285
+ });
7286
+ scanner.on("fps-drop", (fps) => {
7287
+ if (session.options.verbose) {
7288
+ logger4.warn(`FPS dropped to ${fps}`);
7289
+ }
7290
+ });
7291
+ scanner.on("severityChange", ({ component, to }) => {
7292
+ if (session.options.verbose && to === "critical") {
7293
+ logger4.warn(`Component ${component} reached critical severity`);
7294
+ }
7295
+ });
7296
+ }
7297
+ function setupTUIEvents(session) {
7298
+ const { tui, scanner } = session;
7299
+ if (!tui) return;
7300
+ tui.on("togglePause", () => {
7301
+ if (scanner.isRunning()) {
7302
+ scanner.stop();
7303
+ tui.update({ paused: true });
7304
+ } else {
7305
+ scanner.start();
7306
+ tui.update({ paused: false });
7307
+ }
7308
+ });
7309
+ tui.on("generateReport", async () => {
7310
+ const report = generateReport(session);
7311
+ await saveReport(report, session.options);
7312
+ });
7313
+ tui.on("selectComponent", (component) => {
7314
+ const suggestions = scanner.analyzeComponent(component.name);
7315
+ session.suggestions.push(...suggestions.filter(
7316
+ (s) => !session.suggestions.some(
7317
+ (ex) => ex.componentName === s.componentName && ex.fix === s.fix
7318
+ )
7319
+ ));
7320
+ tui.update({ suggestions: session.suggestions });
7321
+ });
7322
+ }
7323
+ async function waitForQuit(session) {
7324
+ return new Promise((resolve3) => {
7325
+ if (session.tui) {
7326
+ session.tui.on("quit", () => {
7327
+ session.active = false;
7328
+ resolve3();
7329
+ });
7330
+ }
7331
+ });
7332
+ }
5344
7333
  async function waitForSignal() {
5345
- return new Promise((resolve2) => {
5346
- process.once("SIGINT", () => resolve2());
5347
- process.once("SIGTERM", () => resolve2());
7334
+ return new Promise((resolve3) => {
7335
+ process.once("SIGINT", () => resolve3());
7336
+ process.once("SIGTERM", () => resolve3());
5348
7337
  });
5349
7338
  }
5350
7339
  function generateReport(session) {
@@ -5400,7 +7389,7 @@ async function saveReport(report, options) {
5400
7389
  const filename = `reactcheck-report-${timestamp}.${extension}`;
5401
7390
  const filepath = joinPath2(options.output, filename);
5402
7391
  await writeTextFile2(filepath, content);
5403
- logger3.info(`Report saved: ${filepath}`);
7392
+ logger4.info(`Report saved: ${filepath}`);
5404
7393
  }
5405
7394
  }
5406
7395
  function printSummary(session) {
@@ -5449,35 +7438,74 @@ function printFixSuggestions(suggestions) {
5449
7438
  console.log("");
5450
7439
  }
5451
7440
  }
7441
+ function setupWebUIEvents(session) {
7442
+ const { scanner, webui } = session;
7443
+ if (!webui) return;
7444
+ scanner.on("render", (render) => {
7445
+ webui.addRenderEvent(render);
7446
+ webui.updateSummary(scanner.getSummary());
7447
+ webui.updateComponents(scanner.getSnapshot());
7448
+ webui.updateFps(scanner.getFps());
7449
+ });
7450
+ scanner.on("chain", (chain) => {
7451
+ webui.addChain(chain);
7452
+ });
7453
+ scanner.on("severityChange", ({ component }) => {
7454
+ const stats = scanner.getSnapshot().find((c) => c.name === component);
7455
+ if (stats) {
7456
+ webui.updateComponent(stats);
7457
+ }
7458
+ });
7459
+ }
7460
+ function openBrowser(url) {
7461
+ const platform = process.platform;
7462
+ let command;
7463
+ switch (platform) {
7464
+ case "darwin":
7465
+ command = `open "${url}"`;
7466
+ break;
7467
+ case "win32":
7468
+ command = `start "" "${url}"`;
7469
+ break;
7470
+ default:
7471
+ command = `xdg-open "${url}"`;
7472
+ break;
7473
+ }
7474
+ exec(command, (error) => {
7475
+ if (error) {
7476
+ logger4.debug(`Failed to open browser: ${error.message}`);
7477
+ }
7478
+ });
7479
+ }
5452
7480
 
5453
7481
  // src/cli/commands/init.ts
5454
7482
  init_fs();
5455
- var logger4 = new Logger({ prefix: "init", level: 1 /* INFO */ });
7483
+ var logger5 = new Logger({ prefix: "init", level: 1 /* INFO */ });
5456
7484
  var DEFAULT_CONFIG_NAME = "reactcheck.config.js";
5457
7485
  async function runInitCommand(args) {
5458
7486
  const configPath = args.positional[0] ?? DEFAULT_CONFIG_NAME;
5459
7487
  if (await exists(configPath)) {
5460
- logger4.warn(`Config file already exists: ${configPath}`);
7488
+ logger5.warn(`Config file already exists: ${configPath}`);
5461
7489
  try {
5462
7490
  const content2 = await readTextFile(configPath);
5463
7491
  if (configPath.endsWith(".json")) {
5464
7492
  const config = JSON.parse(content2);
5465
7493
  const errors = validateConfig(config);
5466
7494
  if (errors.length > 0) {
5467
- logger4.warn("Existing config has validation errors:");
7495
+ logger5.warn("Existing config has validation errors:");
5468
7496
  for (const error of errors) {
5469
- logger4.warn(` - ${error}`);
7497
+ logger5.warn(` - ${error}`);
5470
7498
  }
5471
7499
  } else {
5472
- logger4.info("Existing config is valid.");
7500
+ logger5.info("Existing config is valid.");
5473
7501
  }
5474
7502
  }
5475
7503
  } catch (error) {
5476
- logger4.warn("Could not validate existing config:", error);
7504
+ logger5.warn("Could not validate existing config:", error);
5477
7505
  }
5478
7506
  console.log("");
5479
7507
  console.log(colors.yellow + "? Overwrite existing config? (y/N) " + colors.reset);
5480
- logger4.info("To overwrite, delete the existing file and run init again.");
7508
+ logger5.info("To overwrite, delete the existing file and run init again.");
5481
7509
  return 0;
5482
7510
  }
5483
7511
  const format = configPath.endsWith(".json") ? "json" : "js";
@@ -5503,13 +7531,13 @@ async function runInitCommand(args) {
5503
7531
  console.log("");
5504
7532
  return 0;
5505
7533
  } catch (error) {
5506
- logger4.error(`Failed to create config file:`, error);
7534
+ logger5.error(`Failed to create config file:`, error);
5507
7535
  return 1;
5508
7536
  }
5509
7537
  }
5510
7538
 
5511
7539
  // src/cli/index.ts
5512
- var logger5 = new Logger({ prefix: "ReactCheck", level: 1 /* INFO */ });
7540
+ var logger6 = new Logger({ prefix: "ReactCheck", level: 1 /* INFO */ });
5513
7541
  var VERSION = "1.0.0";
5514
7542
  function printVersion() {
5515
7543
  console.log(`@oxog/react-check v${VERSION}`);
@@ -5560,7 +7588,7 @@ var CLI = class {
5560
7588
  const errors = validateArgs(args);
5561
7589
  if (errors.length > 0) {
5562
7590
  for (const error of errors) {
5563
- logger5.error(error);
7591
+ logger6.error(error);
5564
7592
  }
5565
7593
  console.log("");
5566
7594
  console.log("Run " + colors.cyan + "react-check --help" + colors.reset + " for usage information.");
@@ -5569,7 +7597,7 @@ var CLI = class {
5569
7597
  return await runScanCommand(args);
5570
7598
  }
5571
7599
  } catch (error) {
5572
- logger5.error("Unexpected error:", error);
7600
+ logger6.error("Unexpected error:", error);
5573
7601
  return 1;
5574
7602
  }
5575
7603
  }