@oxog/react-check 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1658 @@
1
+ // src/utils/event-emitter.ts
2
+ var EventEmitter = class {
3
+ /** Map of event names to their listeners */
4
+ _listeners = /* @__PURE__ */ new Map();
5
+ /** Map of event names to their one-time listeners */
6
+ _onceListeners = /* @__PURE__ */ new Map();
7
+ /** Maximum number of listeners per event (0 = unlimited) */
8
+ maxListeners = 0;
9
+ /**
10
+ * Add an event listener
11
+ * @param event - Event name
12
+ * @param listener - Callback function
13
+ * @returns this for chaining
14
+ */
15
+ on(event, listener) {
16
+ let eventListeners = this._listeners.get(event);
17
+ if (!eventListeners) {
18
+ eventListeners = /* @__PURE__ */ new Set();
19
+ this._listeners.set(event, eventListeners);
20
+ }
21
+ if (this.maxListeners > 0 && eventListeners.size >= this.maxListeners) {
22
+ console.warn(
23
+ `Warning: Possible EventEmitter memory leak detected. ${eventListeners.size + 1} listeners added for event "${String(event)}". Use setMaxListeners() to increase limit.`
24
+ );
25
+ }
26
+ eventListeners.add(listener);
27
+ return this;
28
+ }
29
+ /**
30
+ * Alias for on()
31
+ */
32
+ addListener(event, listener) {
33
+ return this.on(event, listener);
34
+ }
35
+ /**
36
+ * Add a one-time event listener
37
+ * @param event - Event name
38
+ * @param listener - Callback function
39
+ * @returns this for chaining
40
+ */
41
+ once(event, listener) {
42
+ let eventListeners = this._onceListeners.get(event);
43
+ if (!eventListeners) {
44
+ eventListeners = /* @__PURE__ */ new Set();
45
+ this._onceListeners.set(event, eventListeners);
46
+ }
47
+ eventListeners.add(listener);
48
+ return this;
49
+ }
50
+ /**
51
+ * Remove an event listener
52
+ * @param event - Event name
53
+ * @param listener - Callback function to remove
54
+ * @returns this for chaining
55
+ */
56
+ off(event, listener) {
57
+ const eventListeners = this._listeners.get(event);
58
+ if (eventListeners) {
59
+ eventListeners.delete(listener);
60
+ if (eventListeners.size === 0) {
61
+ this._listeners.delete(event);
62
+ }
63
+ }
64
+ const onceEventListeners = this._onceListeners.get(event);
65
+ if (onceEventListeners) {
66
+ onceEventListeners.delete(listener);
67
+ if (onceEventListeners.size === 0) {
68
+ this._onceListeners.delete(event);
69
+ }
70
+ }
71
+ return this;
72
+ }
73
+ /**
74
+ * Alias for off()
75
+ */
76
+ removeListener(event, listener) {
77
+ return this.off(event, listener);
78
+ }
79
+ /**
80
+ * Remove all listeners for an event, or all events if no event specified
81
+ * @param event - Optional event name
82
+ * @returns this for chaining
83
+ */
84
+ removeAllListeners(event) {
85
+ if (event !== void 0) {
86
+ this._listeners.delete(event);
87
+ this._onceListeners.delete(event);
88
+ } else {
89
+ this._listeners.clear();
90
+ this._onceListeners.clear();
91
+ }
92
+ return this;
93
+ }
94
+ /**
95
+ * Emit an event
96
+ * @param event - Event name
97
+ * @param data - Event data
98
+ * @returns true if any listeners were called
99
+ */
100
+ emit(event, data) {
101
+ let called = false;
102
+ const eventListeners = this._listeners.get(event);
103
+ if (eventListeners) {
104
+ for (const listener of eventListeners) {
105
+ try {
106
+ listener(data);
107
+ called = true;
108
+ } catch (error) {
109
+ if (event !== "error") {
110
+ this.emit("error", error);
111
+ } else {
112
+ throw error;
113
+ }
114
+ }
115
+ }
116
+ }
117
+ const onceEventListeners = this._onceListeners.get(event);
118
+ if (onceEventListeners) {
119
+ const listenersToCall = Array.from(onceEventListeners);
120
+ this._onceListeners.delete(event);
121
+ for (const listener of listenersToCall) {
122
+ try {
123
+ listener(data);
124
+ called = true;
125
+ } catch (error) {
126
+ if (event !== "error") {
127
+ this.emit("error", error);
128
+ } else {
129
+ throw error;
130
+ }
131
+ }
132
+ }
133
+ }
134
+ return called;
135
+ }
136
+ /**
137
+ * Get all listener functions for an event
138
+ * @param event - Event name
139
+ * @returns Array of listener functions
140
+ */
141
+ getListeners(event) {
142
+ const regular = this._listeners.get(event);
143
+ const once = this._onceListeners.get(event);
144
+ const result = [];
145
+ if (regular) {
146
+ result.push(...Array.from(regular));
147
+ }
148
+ if (once) {
149
+ result.push(...Array.from(once));
150
+ }
151
+ return result;
152
+ }
153
+ /**
154
+ * Get the number of listeners for an event
155
+ * @param event - Event name
156
+ * @returns Number of listeners
157
+ */
158
+ listenerCount(event) {
159
+ const regular = this._listeners.get(event)?.size ?? 0;
160
+ const once = this._onceListeners.get(event)?.size ?? 0;
161
+ return regular + once;
162
+ }
163
+ /**
164
+ * Get all event names that have listeners
165
+ * @returns Array of event names
166
+ */
167
+ eventNames() {
168
+ const names = /* @__PURE__ */ new Set();
169
+ for (const name of this._listeners.keys()) {
170
+ names.add(name);
171
+ }
172
+ for (const name of this._onceListeners.keys()) {
173
+ names.add(name);
174
+ }
175
+ return Array.from(names);
176
+ }
177
+ /**
178
+ * Set the maximum number of listeners per event
179
+ * @param n - Maximum listeners (0 for unlimited)
180
+ * @returns this for chaining
181
+ */
182
+ setMaxListeners(n) {
183
+ this.maxListeners = n;
184
+ return this;
185
+ }
186
+ /**
187
+ * Get the maximum number of listeners per event
188
+ * @returns Maximum listeners
189
+ */
190
+ getMaxListeners() {
191
+ return this.maxListeners;
192
+ }
193
+ /**
194
+ * Prepend a listener to the beginning of the listeners array
195
+ * @param event - Event name
196
+ * @param listener - Callback function
197
+ * @returns this for chaining
198
+ */
199
+ prependListener(event, listener) {
200
+ const eventListeners = this._listeners.get(event);
201
+ if (!eventListeners) {
202
+ return this.on(event, listener);
203
+ }
204
+ const arr = Array.from(eventListeners);
205
+ arr.unshift(listener);
206
+ this._listeners.set(event, new Set(arr));
207
+ return this;
208
+ }
209
+ /**
210
+ * Prepend a one-time listener to the beginning
211
+ * @param event - Event name
212
+ * @param listener - Callback function
213
+ * @returns this for chaining
214
+ */
215
+ prependOnceListener(event, listener) {
216
+ const eventListeners = this._onceListeners.get(event);
217
+ if (!eventListeners) {
218
+ return this.once(event, listener);
219
+ }
220
+ const arr = Array.from(eventListeners);
221
+ arr.unshift(listener);
222
+ this._onceListeners.set(event, new Set(arr));
223
+ return this;
224
+ }
225
+ /**
226
+ * Wait for an event to be emitted
227
+ * @param event - Event name
228
+ * @param timeout - Optional timeout in milliseconds
229
+ * @returns Promise that resolves with the event data
230
+ */
231
+ waitFor(event, timeout) {
232
+ return new Promise((resolve, reject) => {
233
+ let timeoutId;
234
+ const listener = (data) => {
235
+ if (timeoutId) {
236
+ clearTimeout(timeoutId);
237
+ }
238
+ resolve(data);
239
+ };
240
+ this.once(event, listener);
241
+ if (timeout !== void 0 && timeout > 0) {
242
+ timeoutId = setTimeout(() => {
243
+ this.off(event, listener);
244
+ reject(new Error(`Timeout waiting for event "${String(event)}"`));
245
+ }, timeout);
246
+ }
247
+ });
248
+ }
249
+ };
250
+
251
+ // src/core/stats.ts
252
+ var DEFAULT_THRESHOLDS = {
253
+ critical: 50,
254
+ warning: 20,
255
+ fps: 30
256
+ };
257
+ var StatsCollector = class extends EventEmitter {
258
+ /** Map of component names to their statistics */
259
+ components = /* @__PURE__ */ new Map();
260
+ /** Threshold configuration */
261
+ thresholds;
262
+ /** Session start time */
263
+ sessionStart;
264
+ /** Total render count across all components */
265
+ totalRenders = 0;
266
+ /** FPS samples for averaging */
267
+ fpsSamples = [];
268
+ /** Maximum FPS samples to keep */
269
+ maxFpsSamples = 100;
270
+ /**
271
+ * Create a new StatsCollector
272
+ * @param thresholds - Threshold configuration
273
+ */
274
+ constructor(thresholds = {}) {
275
+ super();
276
+ this.thresholds = { ...DEFAULT_THRESHOLDS, ...thresholds };
277
+ this.sessionStart = Date.now();
278
+ }
279
+ /**
280
+ * Add a render event to the statistics
281
+ * @param render - Render information
282
+ */
283
+ addRender(render) {
284
+ const stats = this.getOrCreateStats(render.componentName);
285
+ const previousSeverity = stats.severity;
286
+ stats.renders++;
287
+ this.totalRenders++;
288
+ stats.totalRenderTime += render.renderTime;
289
+ stats.avgRenderTime = stats.totalRenderTime / stats.renders;
290
+ stats.maxRenderTime = Math.max(stats.maxRenderTime, render.renderTime);
291
+ stats.minRenderTime = Math.min(stats.minRenderTime, render.renderTime);
292
+ if (!render.necessary) {
293
+ stats.unnecessary++;
294
+ }
295
+ if (stats.firstRender === 0) {
296
+ stats.firstRender = render.timestamp;
297
+ }
298
+ stats.lastRender = render.timestamp;
299
+ if (render.changedProps && render.changedProps.length > 0) {
300
+ stats.propsChanged = true;
301
+ }
302
+ if (render.changedState && render.changedState.length > 0) {
303
+ stats.stateChanged = true;
304
+ }
305
+ const sessionDuration = Date.now() - this.sessionStart;
306
+ const sessionMinutes = sessionDuration / 6e4;
307
+ stats.expectedRenders = Math.max(1, Math.ceil(sessionMinutes * 5));
308
+ this.updateSeverity(stats);
309
+ this.emit("update", stats);
310
+ if (stats.severity !== previousSeverity) {
311
+ this.emit("severityChange", {
312
+ component: stats.name,
313
+ from: previousSeverity,
314
+ to: stats.severity
315
+ });
316
+ if (stats.severity === "critical" && previousSeverity !== "critical") {
317
+ this.emit("critical", stats);
318
+ } else if (stats.severity === "warning" && previousSeverity === "healthy") {
319
+ this.emit("warning", stats);
320
+ }
321
+ }
322
+ }
323
+ /**
324
+ * Record an FPS sample
325
+ * @param fps - FPS value
326
+ */
327
+ addFpsSample(fps) {
328
+ this.fpsSamples.push(fps);
329
+ if (this.fpsSamples.length > this.maxFpsSamples) {
330
+ this.fpsSamples.shift();
331
+ }
332
+ }
333
+ /**
334
+ * Get or create stats for a component
335
+ * @param name - Component name
336
+ * @returns Component stats
337
+ */
338
+ getOrCreateStats(name) {
339
+ let stats = this.components.get(name);
340
+ if (!stats) {
341
+ stats = this.createEmptyStats(name);
342
+ this.components.set(name, stats);
343
+ }
344
+ return stats;
345
+ }
346
+ /**
347
+ * Create empty stats for a component
348
+ * @param name - Component name
349
+ * @returns Empty component stats
350
+ */
351
+ createEmptyStats(name) {
352
+ return {
353
+ name,
354
+ renders: 0,
355
+ expectedRenders: 1,
356
+ avgRenderTime: 0,
357
+ maxRenderTime: 0,
358
+ minRenderTime: Infinity,
359
+ totalRenderTime: 0,
360
+ unnecessary: 0,
361
+ severity: "healthy",
362
+ chain: [],
363
+ fixes: [],
364
+ firstRender: 0,
365
+ lastRender: 0,
366
+ propsChanged: false,
367
+ stateChanged: false
368
+ };
369
+ }
370
+ /**
371
+ * Update severity for a component based on thresholds
372
+ * @param stats - Component stats to update
373
+ */
374
+ updateSeverity(stats) {
375
+ if (stats.renders >= this.thresholds.critical) {
376
+ stats.severity = "critical";
377
+ } else if (stats.renders >= this.thresholds.warning) {
378
+ stats.severity = "warning";
379
+ } else {
380
+ stats.severity = "healthy";
381
+ }
382
+ }
383
+ /**
384
+ * Get stats for a specific component
385
+ * @param name - Component name
386
+ * @returns Component stats or undefined
387
+ */
388
+ getComponentStats(name) {
389
+ return this.components.get(name);
390
+ }
391
+ /**
392
+ * Get all component stats
393
+ * @returns Array of component stats
394
+ */
395
+ getAllStats() {
396
+ return Array.from(this.components.values());
397
+ }
398
+ /**
399
+ * Get a snapshot of all stats sorted by severity/render count
400
+ * @returns Sorted array of component stats
401
+ */
402
+ getSnapshot() {
403
+ return this.getAllStats().sort((a, b) => {
404
+ const severityOrder = {
405
+ critical: 0,
406
+ warning: 1,
407
+ info: 2,
408
+ healthy: 3
409
+ };
410
+ const severityDiff = severityOrder[a.severity] - severityOrder[b.severity];
411
+ if (severityDiff !== 0) return severityDiff;
412
+ return b.renders - a.renders;
413
+ });
414
+ }
415
+ /**
416
+ * Get components by severity
417
+ * @param severity - Severity level to filter
418
+ * @returns Array of matching component stats
419
+ */
420
+ getComponentsBySeverity(severity) {
421
+ return this.getAllStats().filter((s) => s.severity === severity);
422
+ }
423
+ /**
424
+ * Get session summary
425
+ * @returns Session summary statistics
426
+ */
427
+ getSummary() {
428
+ const stats = this.getAllStats();
429
+ const criticalCount = stats.filter((s) => s.severity === "critical").length;
430
+ const warningCount = stats.filter((s) => s.severity === "warning").length;
431
+ const healthyCount = stats.filter((s) => s.severity === "healthy").length;
432
+ const unnecessaryCount = stats.reduce((sum, s) => sum + s.unnecessary, 0);
433
+ let avgFps = 60;
434
+ let minFps = 60;
435
+ if (this.fpsSamples.length > 0) {
436
+ avgFps = this.fpsSamples.reduce((a, b) => a + b, 0) / this.fpsSamples.length;
437
+ minFps = Math.min(...this.fpsSamples);
438
+ }
439
+ return {
440
+ totalComponents: stats.length,
441
+ totalRenders: this.totalRenders,
442
+ criticalIssues: criticalCount,
443
+ warnings: warningCount,
444
+ healthy: healthyCount,
445
+ avgFps: Math.round(avgFps),
446
+ minFps: Math.round(minFps),
447
+ unnecessaryRenders: unnecessaryCount
448
+ };
449
+ }
450
+ /**
451
+ * Get the most problematic components
452
+ * @param limit - Maximum number to return
453
+ * @returns Top problematic components
454
+ */
455
+ getTopProblems(limit = 10) {
456
+ return this.getSnapshot().filter((s) => s.severity !== "healthy").slice(0, limit);
457
+ }
458
+ /**
459
+ * Update chain information for a component
460
+ * @param componentName - Component name
461
+ * @param chain - Render chain
462
+ */
463
+ setComponentChain(componentName, chain) {
464
+ const stats = this.components.get(componentName);
465
+ if (stats) {
466
+ stats.chain = chain;
467
+ }
468
+ }
469
+ /**
470
+ * Update parent information for a component
471
+ * @param componentName - Component name
472
+ * @param parentName - Parent component name
473
+ */
474
+ setComponentParent(componentName, parentName) {
475
+ const stats = this.components.get(componentName);
476
+ if (stats) {
477
+ stats.parent = parentName;
478
+ }
479
+ }
480
+ /**
481
+ * Reset all statistics
482
+ */
483
+ reset() {
484
+ this.components.clear();
485
+ this.totalRenders = 0;
486
+ this.fpsSamples = [];
487
+ this.sessionStart = Date.now();
488
+ }
489
+ /**
490
+ * Update threshold configuration
491
+ * @param thresholds - New thresholds
492
+ */
493
+ setThresholds(thresholds) {
494
+ this.thresholds = { ...this.thresholds, ...thresholds };
495
+ for (const stats of this.components.values()) {
496
+ const previousSeverity = stats.severity;
497
+ this.updateSeverity(stats);
498
+ if (stats.severity !== previousSeverity) {
499
+ this.emit("severityChange", {
500
+ component: stats.name,
501
+ from: previousSeverity,
502
+ to: stats.severity
503
+ });
504
+ }
505
+ }
506
+ }
507
+ /**
508
+ * Get current thresholds
509
+ * @returns Current threshold configuration
510
+ */
511
+ getThresholds() {
512
+ return { ...this.thresholds };
513
+ }
514
+ /**
515
+ * Get session duration in milliseconds
516
+ * @returns Session duration
517
+ */
518
+ getSessionDuration() {
519
+ return Date.now() - this.sessionStart;
520
+ }
521
+ /**
522
+ * Get total render count
523
+ * @returns Total renders across all components
524
+ */
525
+ getTotalRenders() {
526
+ return this.totalRenders;
527
+ }
528
+ /**
529
+ * Get component count
530
+ * @returns Number of tracked components
531
+ */
532
+ getComponentCount() {
533
+ return this.components.size;
534
+ }
535
+ /**
536
+ * Check if FPS is below threshold
537
+ * @returns true if average FPS is below threshold
538
+ */
539
+ isFpsBelowThreshold() {
540
+ if (this.fpsSamples.length === 0) return false;
541
+ const avgFps = this.fpsSamples.reduce((a, b) => a + b, 0) / this.fpsSamples.length;
542
+ return avgFps < this.thresholds.fps;
543
+ }
544
+ /**
545
+ * Export stats for serialization
546
+ * @returns Serializable stats object
547
+ */
548
+ export() {
549
+ return {
550
+ components: this.getSnapshot(),
551
+ summary: this.getSummary(),
552
+ thresholds: this.getThresholds(),
553
+ sessionDuration: this.getSessionDuration()
554
+ };
555
+ }
556
+ };
557
+
558
+ // src/core/chain.ts
559
+ var ChainAnalyzer = class extends EventEmitter {
560
+ /** Time window size in ms (one frame at 60fps) */
561
+ windowSize;
562
+ /** Current render windows being tracked */
563
+ windows = /* @__PURE__ */ new Map();
564
+ /** Component parent relationships */
565
+ parentMap = /* @__PURE__ */ new Map();
566
+ /** Recently detected chains to avoid duplicates */
567
+ recentChains = /* @__PURE__ */ new Set();
568
+ /** Minimum chain depth to report */
569
+ minChainDepth;
570
+ /** Maximum time to keep recent chains */
571
+ recentChainTtl;
572
+ /**
573
+ * Create a new ChainAnalyzer
574
+ * @param options - Configuration options
575
+ */
576
+ constructor(options = {}) {
577
+ super();
578
+ this.windowSize = options.windowSize ?? 16;
579
+ this.minChainDepth = options.minChainDepth ?? 2;
580
+ this.recentChainTtl = options.recentChainTtl ?? 1e3;
581
+ }
582
+ /**
583
+ * Add a render event for analysis
584
+ * @param render - Render information
585
+ * @param parent - Optional parent component name
586
+ */
587
+ addRender(render, parent) {
588
+ const trackedRender = {
589
+ ...render,
590
+ ...parent !== void 0 ? { parent } : {},
591
+ contextTriggered: this.isContextTriggered(render)
592
+ };
593
+ if (parent) {
594
+ this.parentMap.set(render.componentName, parent);
595
+ }
596
+ const windowKey = this.getWindowKey(render.timestamp);
597
+ let window = this.windows.get(windowKey);
598
+ if (!window) {
599
+ window = {
600
+ renders: [],
601
+ startTime: render.timestamp
602
+ };
603
+ this.windows.set(windowKey, window);
604
+ }
605
+ window.renders.push(trackedRender);
606
+ if (window.renders.length >= this.minChainDepth) {
607
+ this.analyzeWindow(windowKey);
608
+ }
609
+ this.cleanupWindows(render.timestamp);
610
+ }
611
+ /**
612
+ * Set parent relationship for a component
613
+ * @param child - Child component name
614
+ * @param parent - Parent component name
615
+ */
616
+ setParent(child, parent) {
617
+ this.parentMap.set(child, parent);
618
+ }
619
+ /**
620
+ * Get window key for a timestamp
621
+ * @param timestamp - Timestamp in ms
622
+ * @returns Window key
623
+ */
624
+ getWindowKey(timestamp) {
625
+ return Math.floor(timestamp / this.windowSize);
626
+ }
627
+ /**
628
+ * Check if a render was likely triggered by context
629
+ * @param render - Render information
630
+ * @returns true if context-triggered
631
+ */
632
+ isContextTriggered(render) {
633
+ return !render.changedProps?.length && !render.changedState?.length && render.phase === "update";
634
+ }
635
+ /**
636
+ * Analyze a render window for chains
637
+ * @param windowKey - Window key to analyze
638
+ */
639
+ analyzeWindow(windowKey) {
640
+ const window = this.windows.get(windowKey);
641
+ if (!window || window.renders.length < this.minChainDepth) {
642
+ return;
643
+ }
644
+ const sortedRenders = [...window.renders].sort((a, b) => a.timestamp - b.timestamp);
645
+ const chains = this.buildChains(sortedRenders);
646
+ for (const chain of chains) {
647
+ const chainKey = this.getChainKey(chain);
648
+ if (this.recentChains.has(chainKey)) {
649
+ continue;
650
+ }
651
+ this.recentChains.add(chainKey);
652
+ setTimeout(() => {
653
+ this.recentChains.delete(chainKey);
654
+ }, this.recentChainTtl);
655
+ this.emit("chain", chain);
656
+ if (chain.isContextTriggered) {
657
+ this.emit("contextChain", chain);
658
+ }
659
+ }
660
+ }
661
+ /**
662
+ * Build chains from a sorted render sequence
663
+ * @param renders - Sorted render events
664
+ * @returns Detected chains
665
+ */
666
+ buildChains(renders) {
667
+ const chains = [];
668
+ const visited = /* @__PURE__ */ new Set();
669
+ const chainComponents = [];
670
+ for (const render of renders) {
671
+ if (visited.has(render.componentName)) {
672
+ continue;
673
+ }
674
+ const chain = this.traceChain(render.componentName, renders, visited);
675
+ if (chain.length >= this.minChainDepth) {
676
+ chainComponents.push(chain);
677
+ }
678
+ }
679
+ for (const chain of chainComponents) {
680
+ const chainRenders = renders.filter((r) => chain.includes(r.componentName));
681
+ const isContextTriggered = chainRenders.some((r) => r.contextTriggered);
682
+ const rootCause = this.findRootCause(chain, renders);
683
+ const trigger = this.determineTrigger(rootCause, renders);
684
+ chains.push({
685
+ trigger,
686
+ chain,
687
+ depth: chain.length,
688
+ totalRenders: chainRenders.length,
689
+ rootCause,
690
+ timestamp: Date.now(),
691
+ isContextTriggered
692
+ });
693
+ }
694
+ return chains;
695
+ }
696
+ /**
697
+ * Trace a chain starting from a component
698
+ * @param startComponent - Starting component
699
+ * @param renders - All renders in window
700
+ * @param visited - Already visited components
701
+ * @returns Chain of component names
702
+ */
703
+ traceChain(startComponent, renders, visited) {
704
+ const chain = [];
705
+ const queue = [startComponent];
706
+ while (queue.length > 0) {
707
+ const current = queue.shift();
708
+ if (!current || visited.has(current)) {
709
+ continue;
710
+ }
711
+ visited.add(current);
712
+ chain.push(current);
713
+ const parent = this.parentMap.get(current);
714
+ if (parent && renders.some((r) => r.componentName === parent) && !visited.has(parent)) {
715
+ queue.unshift(parent);
716
+ }
717
+ for (const [child, p] of this.parentMap) {
718
+ if (p === current && renders.some((r) => r.componentName === child) && !visited.has(child)) {
719
+ queue.push(child);
720
+ }
721
+ }
722
+ }
723
+ return chain;
724
+ }
725
+ /**
726
+ * Find the root cause component in a chain
727
+ * @param chain - Component chain
728
+ * @param renders - All renders
729
+ * @returns Root cause component name
730
+ */
731
+ findRootCause(chain, renders) {
732
+ const chainRenders = renders.filter((r) => chain.includes(r.componentName)).sort((a, b) => a.timestamp - b.timestamp);
733
+ for (const render of chainRenders) {
734
+ if (render.changedState?.length ?? render.changedProps?.length) {
735
+ return render.componentName;
736
+ }
737
+ }
738
+ return chain[0] ?? "Unknown";
739
+ }
740
+ /**
741
+ * Determine what triggered a chain
742
+ * @param rootCause - Root cause component
743
+ * @param renders - All renders
744
+ * @returns Trigger description
745
+ */
746
+ determineTrigger(rootCause, renders) {
747
+ const render = renders.find((r) => r.componentName === rootCause);
748
+ if (!render) {
749
+ return `Unknown trigger in ${rootCause}`;
750
+ }
751
+ if (render.changedState?.length) {
752
+ return `setState in ${rootCause}`;
753
+ }
754
+ if (render.changedProps?.length) {
755
+ const props = render.changedProps.slice(0, 3).join(", ");
756
+ const more = render.changedProps.length > 3 ? "..." : "";
757
+ return `Props changed (${props}${more}) in ${rootCause}`;
758
+ }
759
+ if (render.contextTriggered) {
760
+ return `Context update affecting ${rootCause}`;
761
+ }
762
+ if (render.phase === "mount") {
763
+ return `Initial mount of ${rootCause}`;
764
+ }
765
+ return `Re-render of ${rootCause}`;
766
+ }
767
+ /**
768
+ * Generate a unique key for a chain to detect duplicates
769
+ * @param chain - Chain info
770
+ * @returns Unique key
771
+ */
772
+ getChainKey(chain) {
773
+ return `${chain.rootCause}:${chain.chain.join("->")}`;
774
+ }
775
+ /**
776
+ * Clean up old render windows
777
+ * @param currentTime - Current timestamp
778
+ */
779
+ cleanupWindows(currentTime) {
780
+ const cutoff = currentTime - this.windowSize * 10;
781
+ for (const [key, window] of this.windows) {
782
+ if (window.startTime < cutoff) {
783
+ this.windows.delete(key);
784
+ }
785
+ }
786
+ }
787
+ /**
788
+ * Get the parent of a component
789
+ * @param componentName - Component name
790
+ * @returns Parent name or undefined
791
+ */
792
+ getParent(componentName) {
793
+ return this.parentMap.get(componentName);
794
+ }
795
+ /**
796
+ * Get all known parent relationships
797
+ * @returns Map of child to parent
798
+ */
799
+ getParentMap() {
800
+ return new Map(this.parentMap);
801
+ }
802
+ /**
803
+ * Build a full chain for a component (tracing up to root)
804
+ * @param componentName - Starting component
805
+ * @returns Chain from root to component
806
+ */
807
+ getComponentChain(componentName) {
808
+ const chain = [];
809
+ let current = componentName;
810
+ while (current) {
811
+ chain.unshift(current);
812
+ current = this.parentMap.get(current);
813
+ if (chain.length > 100) {
814
+ break;
815
+ }
816
+ }
817
+ return chain;
818
+ }
819
+ /**
820
+ * Clear all tracked data
821
+ */
822
+ reset() {
823
+ this.windows.clear();
824
+ this.parentMap.clear();
825
+ this.recentChains.clear();
826
+ }
827
+ /**
828
+ * Get statistics about current tracking
829
+ * @returns Tracking statistics
830
+ */
831
+ getStats() {
832
+ return {
833
+ windowCount: this.windows.size,
834
+ parentRelationships: this.parentMap.size,
835
+ recentChains: this.recentChains.size
836
+ };
837
+ }
838
+ };
839
+
840
+ // src/core/fix.ts
841
+ var BUILTIN_RULES = [
842
+ // React.memo rule
843
+ {
844
+ id: "unnecessary-rerenders-memo",
845
+ name: "Unnecessary Re-renders (memo)",
846
+ description: "Component re-renders frequently without prop changes",
847
+ fixType: "React.memo",
848
+ priority: 1,
849
+ detect: (stats) => {
850
+ const unnecessaryRatio = stats.renders > 0 ? stats.unnecessary / stats.renders : 0;
851
+ return stats.renders >= 10 && unnecessaryRatio >= 0.5 && !stats.propsChanged;
852
+ },
853
+ suggest: (stats) => ({
854
+ severity: stats.severity === "healthy" ? "info" : stats.severity,
855
+ issue: `Component "${stats.name}" re-renders ${stats.unnecessary} times unnecessarily out of ${stats.renders} total renders`,
856
+ cause: stats.parent ? `Parent component "${stats.parent}" re-renders and causes cascading updates` : "Parent component re-renders propagate to this component",
857
+ codeBefore: generateComponentCode(stats.name),
858
+ codeAfter: generateMemoCode(stats.name),
859
+ 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.",
860
+ impact: `Could prevent ~${stats.unnecessary} unnecessary renders (${Math.round(stats.unnecessary / stats.renders * 100)}% reduction)`
861
+ })
862
+ },
863
+ // useMemo rule for expensive computations
864
+ {
865
+ id: "expensive-computation-memo",
866
+ name: "Expensive Computation",
867
+ description: "Component has high render times suggesting expensive calculations",
868
+ fixType: "useMemo",
869
+ priority: 2,
870
+ detect: (stats) => {
871
+ return stats.avgRenderTime > 16 && stats.renders >= 5;
872
+ },
873
+ suggest: (stats) => ({
874
+ severity: stats.avgRenderTime > 50 ? "critical" : "warning",
875
+ issue: `Component "${stats.name}" has slow renders averaging ${stats.avgRenderTime.toFixed(1)}ms`,
876
+ cause: "Expensive calculations or data transformations are being performed on every render",
877
+ codeBefore: generateExpensiveCode(stats.name),
878
+ codeAfter: generateUseMemoCode(stats.name),
879
+ explanation: "useMemo caches the result of expensive computations between renders. It only recalculates when dependencies change, improving performance.",
880
+ impact: `Could reduce render time from ${stats.avgRenderTime.toFixed(1)}ms to <1ms for cached renders`
881
+ })
882
+ },
883
+ // useCallback rule for function props
884
+ {
885
+ id: "function-prop-stability",
886
+ name: "Unstable Function Props",
887
+ description: "Component passes inline functions as props causing child re-renders",
888
+ fixType: "useCallback",
889
+ priority: 3,
890
+ detect: (stats) => {
891
+ return stats.renders >= 15 && stats.propsChanged;
892
+ },
893
+ suggest: (stats) => ({
894
+ severity: stats.severity === "healthy" ? "info" : stats.severity,
895
+ issue: `Component "${stats.name}" may be passing unstable function references as props`,
896
+ cause: "Inline arrow functions are recreated on every render, causing children with React.memo to re-render",
897
+ codeBefore: generateInlineFunctionCode(stats.name),
898
+ codeAfter: generateUseCallbackCode(stats.name),
899
+ explanation: "useCallback returns a memoized callback that only changes when dependencies change. This stabilizes function references passed to child components.",
900
+ impact: "Stabilized function props allow memoized children to skip re-renders"
901
+ })
902
+ },
903
+ // Context split rule
904
+ {
905
+ id: "context-over-subscription",
906
+ name: "Context Over-subscription",
907
+ description: "Context updates trigger unnecessary re-renders in unrelated components",
908
+ fixType: "context-split",
909
+ priority: 4,
910
+ detect: (stats) => {
911
+ return stats.renders >= 20 && stats.unnecessary > stats.renders * 0.7 && !stats.propsChanged && !stats.stateChanged;
912
+ },
913
+ suggest: (stats) => ({
914
+ severity: stats.severity === "healthy" ? "warning" : stats.severity,
915
+ issue: `Component "${stats.name}" re-renders due to context updates it doesn't use`,
916
+ cause: "A context this component subscribes to contains unrelated state that changes frequently",
917
+ codeBefore: generateContextCode("AppContext"),
918
+ codeAfter: generateSplitContextCode(),
919
+ explanation: "Splitting large contexts into smaller, focused contexts prevents unrelated updates from triggering re-renders in components that only need part of the context.",
920
+ impact: `Could eliminate ${stats.unnecessary} unnecessary renders caused by unrelated context updates`
921
+ })
922
+ },
923
+ // State colocation rule
924
+ {
925
+ id: "state-too-high",
926
+ name: "State Location",
927
+ description: "State is managed too high in the component tree",
928
+ fixType: "state-colocation",
929
+ priority: 5,
930
+ detect: (stats) => {
931
+ const chainDepth = stats.chain.length;
932
+ return stats.renders >= 30 && chainDepth >= 3 && stats.stateChanged;
933
+ },
934
+ suggest: (stats) => ({
935
+ severity: stats.severity === "healthy" ? "warning" : stats.severity,
936
+ issue: `State changes in "${stats.name}" trigger a cascade of ${stats.chain.length} component re-renders`,
937
+ cause: `State that only affects a subtree is managed at the "${stats.name}" level, causing unnecessary updates`,
938
+ codeBefore: generateStateHighCode(stats.name),
939
+ codeAfter: generateStateColocationCode(stats.name),
940
+ explanation: "Moving state closer to where it's used (colocation) reduces the re-render scope. Only components that actually need the state will update.",
941
+ impact: `Could reduce cascade depth from ${stats.chain.length} to 1-2 components`
942
+ })
943
+ },
944
+ // Component extraction rule
945
+ {
946
+ id: "extract-heavy-child",
947
+ name: "Component Extraction",
948
+ description: "Part of the component updates independently and should be extracted",
949
+ fixType: "component-extraction",
950
+ priority: 6,
951
+ detect: (stats) => {
952
+ return stats.renders >= 50 && stats.avgRenderTime > 5;
953
+ },
954
+ suggest: (stats) => ({
955
+ severity: stats.severity === "healthy" ? "info" : stats.severity,
956
+ issue: `Component "${stats.name}" renders frequently (${stats.renders} times) with mixed concerns`,
957
+ cause: "The component contains parts that update at different rates, causing full re-renders",
958
+ codeBefore: generateMonolithCode(stats.name),
959
+ codeAfter: generateExtractedCode(stats.name),
960
+ explanation: "Extracting frequently-updating parts into separate components allows React to optimize renders for each part independently.",
961
+ impact: "Isolates render cycles so fast-updating parts don't affect slow-updating parts"
962
+ })
963
+ }
964
+ ];
965
+ function generateComponentCode(name, type) {
966
+ return `function ${name}({ prop1, prop2 }) {
967
+ return (
968
+ <div>
969
+ {/* component content */}
970
+ </div>
971
+ );
972
+ }
973
+
974
+ export default ${name};`;
975
+ }
976
+ function generateMemoCode(name) {
977
+ return `import { memo } from 'react';
978
+
979
+ const ${name} = memo(function ${name}({ prop1, prop2 }) {
980
+ return (
981
+ <div>
982
+ {/* component content */}
983
+ </div>
984
+ );
985
+ });
986
+
987
+ export default ${name};`;
988
+ }
989
+ function generateExpensiveCode(name) {
990
+ return `function ${name}({ items }) {
991
+ // Expensive computation on every render
992
+ const processed = items
993
+ .filter(item => item.active)
994
+ .map(item => transform(item))
995
+ .sort((a, b) => a.value - b.value);
996
+
997
+ return <List items={processed} />;
998
+ }`;
999
+ }
1000
+ function generateUseMemoCode(name) {
1001
+ return `import { useMemo } from 'react';
1002
+
1003
+ function ${name}({ items }) {
1004
+ // Computation cached until items change
1005
+ const processed = useMemo(() => {
1006
+ return items
1007
+ .filter(item => item.active)
1008
+ .map(item => transform(item))
1009
+ .sort((a, b) => a.value - b.value);
1010
+ }, [items]);
1011
+
1012
+ return <List items={processed} />;
1013
+ }`;
1014
+ }
1015
+ function generateInlineFunctionCode(name) {
1016
+ return `function ${name}({ data }) {
1017
+ return (
1018
+ <ChildComponent
1019
+ onAction={(id) => handleAction(id)} // New function every render!
1020
+ onClick={() => setOpen(true)} // New function every render!
1021
+ />
1022
+ );
1023
+ }`;
1024
+ }
1025
+ function generateUseCallbackCode(name) {
1026
+ return `import { useCallback } from 'react';
1027
+
1028
+ function ${name}({ data }) {
1029
+ const handleAction = useCallback((id) => {
1030
+ // Handle action
1031
+ }, []); // Empty deps if no external dependencies
1032
+
1033
+ const handleClick = useCallback(() => {
1034
+ setOpen(true);
1035
+ }, []);
1036
+
1037
+ return (
1038
+ <ChildComponent
1039
+ onAction={handleAction} // Stable reference
1040
+ onClick={handleClick} // Stable reference
1041
+ />
1042
+ );
1043
+ }`;
1044
+ }
1045
+ function generateContextCode(contextName) {
1046
+ return `// Single large context with mixed concerns
1047
+ const ${contextName} = createContext({
1048
+ user: null,
1049
+ theme: 'light',
1050
+ notifications: [],
1051
+ settings: {},
1052
+ cart: [],
1053
+ // ... many more values
1054
+ });
1055
+
1056
+ // Every consumer re-renders when ANY value changes
1057
+ function Component() {
1058
+ const { theme } = useContext(${contextName});
1059
+ // Re-renders when user, notifications, cart change too!
1060
+ return <div className={theme}>...</div>;
1061
+ }`;
1062
+ }
1063
+ function generateSplitContextCode() {
1064
+ return `// Split into focused contexts
1065
+ const UserContext = createContext(null);
1066
+ const ThemeContext = createContext('light');
1067
+ const NotificationContext = createContext([]);
1068
+
1069
+ // Only re-renders when theme changes
1070
+ function Component() {
1071
+ const theme = useContext(ThemeContext);
1072
+ return <div className={theme}>...</div>;
1073
+ }
1074
+
1075
+ // Provider composition
1076
+ function App() {
1077
+ return (
1078
+ <UserContext.Provider value={user}>
1079
+ <ThemeContext.Provider value={theme}>
1080
+ <NotificationContext.Provider value={notifications}>
1081
+ <MainContent />
1082
+ </NotificationContext.Provider>
1083
+ </ThemeContext.Provider>
1084
+ </UserContext.Provider>
1085
+ );
1086
+ }`;
1087
+ }
1088
+ function generateStateHighCode(name) {
1089
+ return `function ${name}() {
1090
+ // State managed at top level
1091
+ const [search, setSearch] = useState('');
1092
+ const [filter, setFilter] = useState('all');
1093
+
1094
+ return (
1095
+ <div>
1096
+ <Header />
1097
+ <Sidebar />
1098
+ {/* Only SearchBox needs search state */}
1099
+ <SearchBox value={search} onChange={setSearch} />
1100
+ <MainContent filter={filter} />
1101
+ <Footer />
1102
+ </div>
1103
+ );
1104
+ }`;
1105
+ }
1106
+ function generateStateColocationCode(name) {
1107
+ return `function ${name}() {
1108
+ // Only filter needed at this level
1109
+ const [filter, setFilter] = useState('all');
1110
+
1111
+ return (
1112
+ <div>
1113
+ <Header />
1114
+ <Sidebar />
1115
+ {/* SearchBox manages its own state */}
1116
+ <SearchBox />
1117
+ <MainContent filter={filter} />
1118
+ <Footer />
1119
+ </div>
1120
+ );
1121
+ }
1122
+
1123
+ // State colocated with component that uses it
1124
+ function SearchBox() {
1125
+ const [search, setSearch] = useState('');
1126
+ return <input value={search} onChange={e => setSearch(e.target.value)} />;
1127
+ }`;
1128
+ }
1129
+ function generateMonolithCode(name) {
1130
+ return `function ${name}() {
1131
+ const [counter, setCounter] = useState(0);
1132
+ const [data, setData] = useState(null);
1133
+
1134
+ // Counter updates 10x/second
1135
+ useEffect(() => {
1136
+ const id = setInterval(() => setCounter(c => c + 1), 100);
1137
+ return () => clearInterval(id);
1138
+ }, []);
1139
+
1140
+ return (
1141
+ <div>
1142
+ <span>Count: {counter}</span> {/* Updates frequently */}
1143
+ <ExpensiveChart data={data} /> {/* Re-renders unnecessarily! */}
1144
+ <DataTable data={data} /> {/* Re-renders unnecessarily! */}
1145
+ </div>
1146
+ );
1147
+ }`;
1148
+ }
1149
+ function generateExtractedCode(name) {
1150
+ return `function ${name}() {
1151
+ const [data, setData] = useState(null);
1152
+
1153
+ return (
1154
+ <div>
1155
+ <LiveCounter /> {/* Isolated updates */}
1156
+ <ExpensiveChart data={data} /> {/* Only updates when data changes */}
1157
+ <DataTable data={data} /> {/* Only updates when data changes */}
1158
+ </div>
1159
+ );
1160
+ }
1161
+
1162
+ // Extracted component with isolated state
1163
+ function LiveCounter() {
1164
+ const [counter, setCounter] = useState(0);
1165
+
1166
+ useEffect(() => {
1167
+ const id = setInterval(() => setCounter(c => c + 1), 100);
1168
+ return () => clearInterval(id);
1169
+ }, []);
1170
+
1171
+ return <span>Count: {counter}</span>;
1172
+ }`;
1173
+ }
1174
+ var FixSuggester = class extends EventEmitter {
1175
+ /** Active rules */
1176
+ rules;
1177
+ /** Generated suggestions cache */
1178
+ suggestions = /* @__PURE__ */ new Map();
1179
+ /** Rule configuration */
1180
+ ruleConfig = /* @__PURE__ */ new Map();
1181
+ /**
1182
+ * Create a new FixSuggester
1183
+ * @param options - Configuration options
1184
+ */
1185
+ constructor(options = {}) {
1186
+ super();
1187
+ this.rules = [...BUILTIN_RULES];
1188
+ if (options.rules) {
1189
+ for (const [ruleId, setting] of Object.entries(options.rules)) {
1190
+ this.ruleConfig.set(ruleId, setting);
1191
+ }
1192
+ }
1193
+ }
1194
+ /**
1195
+ * Analyze a component and generate fix suggestions
1196
+ * @param stats - Component statistics
1197
+ * @returns Array of fix suggestions
1198
+ */
1199
+ analyze(stats) {
1200
+ const suggestions = [];
1201
+ for (const rule of this.rules) {
1202
+ const config = this.ruleConfig.get(rule.id);
1203
+ if (config === "off") {
1204
+ continue;
1205
+ }
1206
+ if (!rule.detect(stats)) {
1207
+ continue;
1208
+ }
1209
+ const partialSuggestion = rule.suggest(stats);
1210
+ const suggestion = {
1211
+ componentName: stats.name,
1212
+ fix: rule.fixType,
1213
+ ...partialSuggestion
1214
+ };
1215
+ if (config === "warn") {
1216
+ suggestion.severity = "warning";
1217
+ } else if (config === "error") {
1218
+ suggestion.severity = "critical";
1219
+ }
1220
+ suggestions.push(suggestion);
1221
+ this.emit("suggestion", suggestion);
1222
+ }
1223
+ suggestions.sort((a, b) => {
1224
+ const severityOrder = { critical: 0, warning: 1, info: 2 };
1225
+ const severityDiff = severityOrder[a.severity] - severityOrder[b.severity];
1226
+ if (severityDiff !== 0) return severityDiff;
1227
+ const ruleA = this.rules.find((r) => r.fixType === a.fix);
1228
+ const ruleB = this.rules.find((r) => r.fixType === b.fix);
1229
+ return (ruleA?.priority ?? 99) - (ruleB?.priority ?? 99);
1230
+ });
1231
+ this.suggestions.set(stats.name, suggestions);
1232
+ return suggestions;
1233
+ }
1234
+ /**
1235
+ * Get cached suggestions for a component
1236
+ * @param componentName - Component name
1237
+ * @returns Cached suggestions or empty array
1238
+ */
1239
+ getSuggestions(componentName) {
1240
+ return this.suggestions.get(componentName) ?? [];
1241
+ }
1242
+ /**
1243
+ * Get all cached suggestions
1244
+ * @returns All suggestions
1245
+ */
1246
+ getAllSuggestions() {
1247
+ return Array.from(this.suggestions.values()).flat();
1248
+ }
1249
+ /**
1250
+ * Get suggestions by severity
1251
+ * @param severity - Severity level
1252
+ * @returns Matching suggestions
1253
+ */
1254
+ getSuggestionsBySeverity(severity) {
1255
+ return this.getAllSuggestions().filter((s) => s.severity === severity);
1256
+ }
1257
+ /**
1258
+ * Get suggestions by fix type
1259
+ * @param fixType - Fix type
1260
+ * @returns Matching suggestions
1261
+ */
1262
+ getSuggestionsByType(fixType) {
1263
+ return this.getAllSuggestions().filter((s) => s.fix === fixType);
1264
+ }
1265
+ /**
1266
+ * Clear cached suggestions
1267
+ * @param componentName - Optional component to clear (clears all if not specified)
1268
+ */
1269
+ clearSuggestions(componentName) {
1270
+ if (componentName) {
1271
+ this.suggestions.delete(componentName);
1272
+ } else {
1273
+ this.suggestions.clear();
1274
+ }
1275
+ }
1276
+ /**
1277
+ * Configure a rule
1278
+ * @param ruleId - Rule identifier
1279
+ * @param setting - Rule setting
1280
+ */
1281
+ configureRule(ruleId, setting) {
1282
+ this.ruleConfig.set(ruleId, setting);
1283
+ }
1284
+ /**
1285
+ * Get available rule IDs
1286
+ * @returns Array of rule IDs
1287
+ */
1288
+ getRuleIds() {
1289
+ return this.rules.map((r) => r.id);
1290
+ }
1291
+ /**
1292
+ * Get rule information
1293
+ * @param ruleId - Rule identifier
1294
+ * @returns Rule info or undefined
1295
+ */
1296
+ getRule(ruleId) {
1297
+ const rule = this.rules.find((r) => r.id === ruleId);
1298
+ if (!rule) return void 0;
1299
+ return {
1300
+ id: rule.id,
1301
+ name: rule.name,
1302
+ description: rule.description,
1303
+ fixType: rule.fixType
1304
+ };
1305
+ }
1306
+ };
1307
+
1308
+ // src/core/scanner.ts
1309
+ var DEFAULT_CONFIG = {
1310
+ trackUnnecessary: true,
1311
+ fpsThreshold: 30,
1312
+ highlightRenders: true,
1313
+ animationSpeed: "fast"
1314
+ };
1315
+ var DEFAULT_THRESHOLDS2 = {
1316
+ critical: 50,
1317
+ warning: 20,
1318
+ fps: 30
1319
+ };
1320
+ var Scanner = class extends EventEmitter {
1321
+ /** Statistics collector */
1322
+ stats;
1323
+ /** Chain analyzer */
1324
+ chainAnalyzer;
1325
+ /** Fix suggester */
1326
+ fixSuggester;
1327
+ /** Scanner configuration */
1328
+ config;
1329
+ /** Whether scanner is currently running */
1330
+ running = false;
1331
+ /** Last recorded FPS */
1332
+ lastFps = 60;
1333
+ /** FPS tracking */
1334
+ frameCount = 0;
1335
+ lastFpsUpdate = 0;
1336
+ fpsInterval = null;
1337
+ /** Batch processing */
1338
+ renderBatch = [];
1339
+ batchTimeout = null;
1340
+ batchSize = 10;
1341
+ batchDelay = 100;
1342
+ /**
1343
+ * Create a new Scanner instance
1344
+ * @param options - Configuration options
1345
+ */
1346
+ constructor(options = {}) {
1347
+ super();
1348
+ this.config = { ...DEFAULT_CONFIG, ...options.config };
1349
+ const thresholds = { ...DEFAULT_THRESHOLDS2, ...options.thresholds };
1350
+ this.stats = new StatsCollector(thresholds);
1351
+ this.chainAnalyzer = new ChainAnalyzer();
1352
+ this.fixSuggester = new FixSuggester();
1353
+ this.setupEventForwarding();
1354
+ }
1355
+ /**
1356
+ * Set up event forwarding from sub-modules
1357
+ */
1358
+ setupEventForwarding() {
1359
+ this.stats.on("update", (stats) => {
1360
+ this.emit("stats", stats);
1361
+ });
1362
+ this.stats.on("severityChange", (change) => {
1363
+ this.emit("severityChange", change);
1364
+ const stats = this.stats.getComponentStats(change.component);
1365
+ if (stats && (change.to === "critical" || change.to === "warning")) {
1366
+ const suggestions = this.fixSuggester.analyze(stats);
1367
+ for (const suggestion of suggestions) {
1368
+ this.emit("fix", suggestion);
1369
+ }
1370
+ }
1371
+ });
1372
+ this.chainAnalyzer.on("chain", (chain) => {
1373
+ this.emit("chain", chain);
1374
+ for (const componentName of chain.chain) {
1375
+ this.stats.setComponentChain(componentName, chain.chain);
1376
+ }
1377
+ });
1378
+ }
1379
+ /**
1380
+ * Start the scanner
1381
+ */
1382
+ start() {
1383
+ if (this.running) return;
1384
+ this.running = true;
1385
+ this.lastFpsUpdate = Date.now();
1386
+ this.frameCount = 0;
1387
+ this.startFpsMonitoring();
1388
+ this.emit("start", void 0);
1389
+ }
1390
+ /**
1391
+ * Stop the scanner
1392
+ */
1393
+ stop() {
1394
+ if (!this.running) return;
1395
+ this.running = false;
1396
+ this.stopFpsMonitoring();
1397
+ this.flushBatch();
1398
+ this.emit("stop", void 0);
1399
+ }
1400
+ /**
1401
+ * Reset the scanner, clearing all data
1402
+ */
1403
+ reset() {
1404
+ this.stop();
1405
+ this.stats.reset();
1406
+ this.chainAnalyzer.reset();
1407
+ this.fixSuggester.clearSuggestions();
1408
+ this.renderBatch = [];
1409
+ this.emit("reset", void 0);
1410
+ }
1411
+ /**
1412
+ * Process a render event
1413
+ * @param render - Render information
1414
+ * @param parent - Optional parent component name
1415
+ */
1416
+ addRender(render, parent) {
1417
+ if (!this.running) return;
1418
+ this.renderBatch.push(render);
1419
+ this.stats.addRender(render);
1420
+ this.chainAnalyzer.addRender(render, parent);
1421
+ this.emit("render", render);
1422
+ this.frameCount++;
1423
+ this.scheduleBatchProcessing();
1424
+ }
1425
+ /**
1426
+ * Record a frame for FPS calculation
1427
+ */
1428
+ recordFrame() {
1429
+ this.frameCount++;
1430
+ }
1431
+ /**
1432
+ * Schedule batch processing
1433
+ */
1434
+ scheduleBatchProcessing() {
1435
+ if (this.batchTimeout) return;
1436
+ if (this.renderBatch.length >= this.batchSize) {
1437
+ this.flushBatch();
1438
+ } else {
1439
+ this.batchTimeout = setTimeout(() => {
1440
+ this.flushBatch();
1441
+ }, this.batchDelay);
1442
+ }
1443
+ }
1444
+ /**
1445
+ * Flush the render batch
1446
+ */
1447
+ flushBatch() {
1448
+ if (this.batchTimeout) {
1449
+ clearTimeout(this.batchTimeout);
1450
+ this.batchTimeout = null;
1451
+ }
1452
+ if (this.renderBatch.length === 0) return;
1453
+ this.processBatch(this.renderBatch);
1454
+ this.renderBatch = [];
1455
+ }
1456
+ /**
1457
+ * Process a batch of renders for patterns
1458
+ * @param batch - Render batch
1459
+ */
1460
+ processBatch(batch) {
1461
+ const byComponent = /* @__PURE__ */ new Map();
1462
+ for (const render of batch) {
1463
+ const existing = byComponent.get(render.componentName) ?? [];
1464
+ existing.push(render);
1465
+ byComponent.set(render.componentName, existing);
1466
+ }
1467
+ for (const [componentName, renders] of byComponent) {
1468
+ if (renders.length >= 3) {
1469
+ const stats = this.stats.getComponentStats(componentName);
1470
+ if (stats) {
1471
+ const suggestions = this.fixSuggester.analyze(stats);
1472
+ for (const suggestion of suggestions) {
1473
+ this.emit("fix", suggestion);
1474
+ }
1475
+ }
1476
+ }
1477
+ }
1478
+ }
1479
+ /**
1480
+ * Start FPS monitoring
1481
+ */
1482
+ startFpsMonitoring() {
1483
+ this.fpsInterval = setInterval(() => {
1484
+ const now = Date.now();
1485
+ const elapsed = now - this.lastFpsUpdate;
1486
+ if (elapsed > 0) {
1487
+ this.lastFps = Math.round(this.frameCount * 1e3 / elapsed);
1488
+ this.stats.addFpsSample(this.lastFps);
1489
+ if (this.lastFps < this.config.fpsThreshold) {
1490
+ this.emit("fps-drop", this.lastFps);
1491
+ }
1492
+ }
1493
+ this.frameCount = 0;
1494
+ this.lastFpsUpdate = now;
1495
+ }, 1e3);
1496
+ }
1497
+ /**
1498
+ * Stop FPS monitoring
1499
+ */
1500
+ stopFpsMonitoring() {
1501
+ if (this.fpsInterval) {
1502
+ clearInterval(this.fpsInterval);
1503
+ this.fpsInterval = null;
1504
+ }
1505
+ }
1506
+ /**
1507
+ * Get current FPS
1508
+ * @returns Current FPS value
1509
+ */
1510
+ getFps() {
1511
+ return this.lastFps;
1512
+ }
1513
+ /**
1514
+ * Check if scanner is running
1515
+ * @returns true if running
1516
+ */
1517
+ isRunning() {
1518
+ return this.running;
1519
+ }
1520
+ /**
1521
+ * Get scanner configuration
1522
+ * @returns Current configuration
1523
+ */
1524
+ getConfig() {
1525
+ return { ...this.config };
1526
+ }
1527
+ /**
1528
+ * Update scanner configuration
1529
+ * @param config - Partial configuration to update
1530
+ */
1531
+ configure(config) {
1532
+ this.config = { ...this.config, ...config };
1533
+ }
1534
+ /**
1535
+ * Update threshold configuration
1536
+ * @param thresholds - New thresholds
1537
+ */
1538
+ setThresholds(thresholds) {
1539
+ this.stats.setThresholds(thresholds);
1540
+ }
1541
+ /**
1542
+ * Get current thresholds
1543
+ * @returns Current threshold configuration
1544
+ */
1545
+ getThresholds() {
1546
+ return this.stats.getThresholds();
1547
+ }
1548
+ /**
1549
+ * Get component statistics
1550
+ * @param name - Component name (optional, returns all if not specified)
1551
+ * @returns Component stats
1552
+ */
1553
+ getStats(name) {
1554
+ if (name) {
1555
+ return this.stats.getComponentStats(name);
1556
+ }
1557
+ return this.stats.getAllStats();
1558
+ }
1559
+ /**
1560
+ * Get a snapshot of all stats sorted by severity
1561
+ * @returns Sorted stats array
1562
+ */
1563
+ getSnapshot() {
1564
+ return this.stats.getSnapshot();
1565
+ }
1566
+ /**
1567
+ * Get session summary
1568
+ * @returns Session summary statistics
1569
+ */
1570
+ getSummary() {
1571
+ return this.stats.getSummary();
1572
+ }
1573
+ /**
1574
+ * Get top problematic components
1575
+ * @param limit - Maximum number to return
1576
+ * @returns Top problems
1577
+ */
1578
+ getTopProblems(limit = 10) {
1579
+ return this.stats.getTopProblems(limit);
1580
+ }
1581
+ /**
1582
+ * Get all fix suggestions
1583
+ * @returns All suggestions
1584
+ */
1585
+ getSuggestions() {
1586
+ return this.fixSuggester.getAllSuggestions();
1587
+ }
1588
+ /**
1589
+ * Get suggestions for a specific component
1590
+ * @param componentName - Component name
1591
+ * @returns Component suggestions
1592
+ */
1593
+ getComponentSuggestions(componentName) {
1594
+ return this.fixSuggester.getSuggestions(componentName);
1595
+ }
1596
+ /**
1597
+ * Set parent relationship for a component
1598
+ * @param child - Child component name
1599
+ * @param parent - Parent component name
1600
+ */
1601
+ setParent(child, parent) {
1602
+ this.chainAnalyzer.setParent(child, parent);
1603
+ this.stats.setComponentParent(child, parent);
1604
+ }
1605
+ /**
1606
+ * Get the render chain for a component
1607
+ * @param componentName - Component name
1608
+ * @returns Render chain
1609
+ */
1610
+ getComponentChain(componentName) {
1611
+ return this.chainAnalyzer.getComponentChain(componentName);
1612
+ }
1613
+ /**
1614
+ * Get session duration
1615
+ * @returns Duration in milliseconds
1616
+ */
1617
+ getSessionDuration() {
1618
+ return this.stats.getSessionDuration();
1619
+ }
1620
+ /**
1621
+ * Export scanner data for reporting
1622
+ * @returns Exportable data object
1623
+ */
1624
+ export() {
1625
+ return {
1626
+ stats: this.stats.export(),
1627
+ suggestions: this.getSuggestions(),
1628
+ config: this.getConfig()
1629
+ };
1630
+ }
1631
+ /**
1632
+ * Analyze a specific component and generate suggestions
1633
+ * @param componentName - Component name
1634
+ * @returns Fix suggestions for the component
1635
+ */
1636
+ analyzeComponent(componentName) {
1637
+ const stats = this.stats.getComponentStats(componentName);
1638
+ if (!stats) return [];
1639
+ return this.fixSuggester.analyze(stats);
1640
+ }
1641
+ /**
1642
+ * Analyze all components and generate suggestions
1643
+ * @returns All fix suggestions
1644
+ */
1645
+ analyzeAll() {
1646
+ const allStats = this.stats.getAllStats();
1647
+ const allSuggestions = [];
1648
+ for (const stats of allStats) {
1649
+ const suggestions = this.fixSuggester.analyze(stats);
1650
+ allSuggestions.push(...suggestions);
1651
+ }
1652
+ return allSuggestions;
1653
+ }
1654
+ };
1655
+
1656
+ export { Scanner };
1657
+ //# sourceMappingURL=scanner.js.map
1658
+ //# sourceMappingURL=scanner.js.map