@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 ersinkoc
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,343 @@
1
+ # ReactCheck
2
+
3
+ A zero-dependency React performance scanner that detects unnecessary re-renders, analyzes render chains, and provides actionable fix suggestions.
4
+
5
+ ## Features
6
+
7
+ - **Real-time Render Detection**: Monitor React component renders in real-time via React DevTools hook
8
+ - **Render Chain Analysis**: Trace cascade effects and identify root causes of performance issues
9
+ - **Fix Suggestions**: Get actionable code suggestions (memo, useMemo, useCallback, context splitting)
10
+ - **Multiple Report Formats**: Export reports as HTML, JSON, or Markdown
11
+ - **Framework Detection**: Automatic detection and framework-specific tips for Next.js, Remix, Vite, CRA, Gatsby
12
+ - **Interactive TUI**: Terminal-based UI for real-time monitoring
13
+ - **Browser Overlay**: Visual overlay showing component render statistics
14
+ - **Zero Dependencies**: Core functionality has no external dependencies
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install @oxog/react-check
20
+ ```
21
+
22
+ For CLI usage with browser automation:
23
+
24
+ ```bash
25
+ npm install @oxog/react-check puppeteer
26
+ ```
27
+
28
+ ## Quick Start
29
+
30
+ ### CLI Usage
31
+
32
+ Scan a React application:
33
+
34
+ ```bash
35
+ npx react-check scan http://localhost:3000
36
+ ```
37
+
38
+ With options:
39
+
40
+ ```bash
41
+ npx react-check scan http://localhost:3000 \
42
+ --duration 60000 \
43
+ --output ./reports \
44
+ --format html,json \
45
+ --headless
46
+ ```
47
+
48
+ ### Programmatic Usage
49
+
50
+ ```typescript
51
+ import { createScanner, generateHTMLReport } from '@oxog/react-check';
52
+
53
+ // Create a scanner instance
54
+ const scanner = createScanner({
55
+ thresholds: { critical: 50, warning: 20 },
56
+ include: ['MyComponent*'],
57
+ exclude: ['DebugPanel'],
58
+ });
59
+
60
+ // Listen for render events
61
+ scanner.on('render', (info) => {
62
+ console.log(`${info.componentName} rendered in ${info.renderTime}ms`);
63
+ });
64
+
65
+ // Start scanning
66
+ scanner.start();
67
+
68
+ // Later: get report and generate HTML
69
+ const report = scanner.getReport();
70
+ const html = generateHTMLReport(report);
71
+ ```
72
+
73
+ ### Quick Scan API
74
+
75
+ ```typescript
76
+ import { quickScan } from '@oxog/react-check';
77
+
78
+ const report = await quickScan('http://localhost:3000', {
79
+ duration: 30000,
80
+ headless: true,
81
+ output: './reports',
82
+ formats: ['html', 'json'],
83
+ });
84
+
85
+ console.log(`Found ${report.summary.criticalIssues} critical issues`);
86
+ ```
87
+
88
+ ## CLI Commands
89
+
90
+ ### `scan <url>`
91
+
92
+ Scan a React application for performance issues.
93
+
94
+ ```bash
95
+ react-check scan <url> [options]
96
+
97
+ Options:
98
+ -d, --duration <ms> Scan duration in milliseconds (default: 30000)
99
+ -o, --output <dir> Output directory for reports
100
+ -f, --format <formats> Report formats: html,json,md (default: html,json)
101
+ -t, --threshold <n> Render count threshold for warnings (default: 20)
102
+ -c, --critical <n> Render count threshold for critical (default: 50)
103
+ --headless Run browser in headless mode
104
+ --include <patterns> Component patterns to include
105
+ --exclude <patterns> Component patterns to exclude
106
+ --no-tui Disable TUI, use simple output
107
+ ```
108
+
109
+ ### `report <input>`
110
+
111
+ Generate reports from a JSON scan result.
112
+
113
+ ```bash
114
+ react-check report scan-results.json --format html,md --output ./reports
115
+ ```
116
+
117
+ ### `detect [path]`
118
+
119
+ Detect the React framework in use.
120
+
121
+ ```bash
122
+ react-check detect ./my-react-app
123
+ ```
124
+
125
+ ## Report Formats
126
+
127
+ ### HTML Report
128
+
129
+ Interactive HTML report with:
130
+ - Summary dashboard
131
+ - Component performance table with sorting
132
+ - Render chain visualization
133
+ - Fix suggestions with code examples
134
+
135
+ ### JSON Report
136
+
137
+ Machine-readable JSON format:
138
+
139
+ ```json
140
+ {
141
+ "version": "1.0.0",
142
+ "timestamp": "2025-01-15T10:30:00Z",
143
+ "summary": {
144
+ "totalComponents": 42,
145
+ "totalRenders": 1250,
146
+ "criticalIssues": 3,
147
+ "warnings": 8,
148
+ "healthy": 31
149
+ },
150
+ "components": [...],
151
+ "chains": [...],
152
+ "suggestions": [...]
153
+ }
154
+ ```
155
+
156
+ ### Markdown Report
157
+
158
+ GitHub-friendly Markdown report suitable for issue tracking or documentation.
159
+
160
+ ## Configuration
161
+
162
+ ### Scanner Options
163
+
164
+ ```typescript
165
+ interface ScannerConfig {
166
+ // Render count thresholds
167
+ thresholds: {
168
+ warning: number; // Default: 20
169
+ critical: number; // Default: 50
170
+ };
171
+ // Component name patterns to include
172
+ include?: string[];
173
+ // Component name patterns to exclude
174
+ exclude?: string[];
175
+ // Enable render chain analysis
176
+ chainAnalysis?: boolean;
177
+ // Window size for render grouping (ms)
178
+ windowSize?: number;
179
+ }
180
+ ```
181
+
182
+ ### Fix Categories
183
+
184
+ ReactCheck provides fix suggestions in these categories:
185
+
186
+ - **React.memo**: Wrap components that receive stable props
187
+ - **useMemo**: Memoize expensive computed values
188
+ - **useCallback**: Memoize callback functions passed to children
189
+ - **Context Splitting**: Split large contexts to reduce re-render scope
190
+ - **State Colocation**: Move state closer to where it's used
191
+
192
+ ## API Reference
193
+
194
+ ### Core Classes
195
+
196
+ #### `Scanner`
197
+
198
+ Main scanning engine.
199
+
200
+ ```typescript
201
+ const scanner = new Scanner(config);
202
+ scanner.on('render', handler);
203
+ scanner.on('chain', handler);
204
+ scanner.on('fps-drop', handler);
205
+ scanner.start();
206
+ scanner.stop();
207
+ const report = scanner.getReport();
208
+ ```
209
+
210
+ #### `ChainAnalyzer`
211
+
212
+ Analyzes render chains and cascade effects.
213
+
214
+ ```typescript
215
+ const analyzer = new ChainAnalyzer({ windowSize: 100 });
216
+ analyzer.addRender(renderInfo, parentName);
217
+ const chains = analyzer.getChains();
218
+ ```
219
+
220
+ #### `FixSuggester`
221
+
222
+ Generates fix suggestions based on component statistics.
223
+
224
+ ```typescript
225
+ const suggester = new FixSuggester();
226
+ const suggestions = suggester.analyze(componentStats);
227
+ ```
228
+
229
+ ### Utility Functions
230
+
231
+ ```typescript
232
+ // Report generation
233
+ generateHTMLReport(report);
234
+ generateJSONReport(report);
235
+ generateMarkdownReport(report);
236
+
237
+ // Framework detection
238
+ detectFramework(packageJsonPath?);
239
+ detectFrameworkFromWindow(window);
240
+ getFrameworkTips(framework);
241
+
242
+ // Formatting utilities
243
+ formatDuration(ms);
244
+ formatBytes(bytes);
245
+ formatPercent(value);
246
+ formatRenderTime(ms);
247
+ ```
248
+
249
+ ## Browser Integration
250
+
251
+ ### Manual Injection
252
+
253
+ ```typescript
254
+ import { BrowserScanner, Overlay } from '@oxog/react-check';
255
+
256
+ const scanner = new BrowserScanner(window, config);
257
+ const overlay = new Overlay(config);
258
+
259
+ scanner.on('render', (info) => {
260
+ overlay.update(info);
261
+ });
262
+
263
+ scanner.start();
264
+ overlay.show();
265
+ ```
266
+
267
+ ### Proxy Server
268
+
269
+ ```typescript
270
+ import { ProxyServer, WebSocketServer } from '@oxog/react-check';
271
+
272
+ const wsServer = new WebSocketServer(3099);
273
+ const proxy = new ProxyServer({
274
+ target: 'http://localhost:3000',
275
+ port: 8080,
276
+ wsPort: 3099,
277
+ });
278
+
279
+ await wsServer.start();
280
+ await proxy.start();
281
+
282
+ // Open http://localhost:8080 in browser
283
+ ```
284
+
285
+ ## Framework Support
286
+
287
+ ReactCheck automatically detects and provides tailored tips for:
288
+
289
+ | Framework | Features Detected |
290
+ |-----------|------------------|
291
+ | Next.js | App Router, Pages Router, RSC |
292
+ | Remix | Routes, loaders |
293
+ | Vite | HMR, React plugin |
294
+ | Create React App | react-scripts |
295
+ | Gatsby | gatsby-* packages |
296
+
297
+ ## Architecture
298
+
299
+ ```
300
+ src/
301
+ ├── core/ # Core scanning engine
302
+ │ ├── scanner.ts # Main scanner
303
+ │ ├── chain.ts # Render chain analyzer
304
+ │ ├── fix.ts # Fix suggester
305
+ │ ├── stats.ts # Statistics collector
306
+ │ └── fiber.ts # React fiber utilities
307
+ ├── browser/ # Browser-side modules
308
+ │ ├── scanner.ts # Browser scanner
309
+ │ └── overlay.ts # Visual overlay
310
+ ├── server/ # Node.js server modules
311
+ │ ├── websocket.ts # WebSocket server
312
+ │ ├── proxy.ts # HTTP proxy
313
+ │ └── browser.ts # Puppeteer wrapper
314
+ ├── report/ # Report generators
315
+ │ ├── html.ts # HTML report
316
+ │ ├── json.ts # JSON report
317
+ │ └── markdown.ts # Markdown report
318
+ ├── detect/ # Framework detection
319
+ │ └── framework.ts
320
+ ├── cli/ # CLI implementation
321
+ │ ├── index.ts # CLI entry
322
+ │ └── tui/ # Terminal UI
323
+ └── utils/ # Shared utilities
324
+ ├── colors.ts # ANSI colors
325
+ ├── format.ts # Formatters
326
+ ├── fs.ts # File system
327
+ └── logger.ts # Logging
328
+ ```
329
+
330
+ ## License
331
+
332
+ MIT
333
+
334
+ ## Contributing
335
+
336
+ Contributions are welcome! Please read our contributing guidelines before submitting a PR.
337
+
338
+ 1. Fork the repository
339
+ 2. Create a feature branch
340
+ 3. Make your changes
341
+ 4. Run tests: `npm test`
342
+ 5. Run build: `npm run build`
343
+ 6. Submit a pull request
@@ -0,0 +1,182 @@
1
+ var ReactCheckInjector=(function(exports){'use strict';var C=Object.defineProperty;var R=(i,e,t)=>e in i?C(i,e,{enumerable:true,configurable:true,writable:true,value:t}):i[e]=t;var a=(i,e,t)=>R(i,typeof e!="symbol"?e+"":e,t);var u=class{constructor(){a(this,"_listeners",new Map);a(this,"_onceListeners",new Map);a(this,"maxListeners",0);}on(e,t){let n=this._listeners.get(e);return n||(n=new Set,this._listeners.set(e,n)),this.maxListeners>0&&n.size>=this.maxListeners&&console.warn(`Warning: Possible EventEmitter memory leak detected. ${n.size+1} listeners added for event "${String(e)}". Use setMaxListeners() to increase limit.`),n.add(t),this}addListener(e,t){return this.on(e,t)}once(e,t){let n=this._onceListeners.get(e);return n||(n=new Set,this._onceListeners.set(e,n)),n.add(t),this}off(e,t){let n=this._listeners.get(e);n&&(n.delete(t),n.size===0&&this._listeners.delete(e));let o=this._onceListeners.get(e);return o&&(o.delete(t),o.size===0&&this._onceListeners.delete(e)),this}removeListener(e,t){return this.off(e,t)}removeAllListeners(e){return e!==void 0?(this._listeners.delete(e),this._onceListeners.delete(e)):(this._listeners.clear(),this._onceListeners.clear()),this}emit(e,t){let n=false,o=this._listeners.get(e);if(o)for(let r of o)try{r(t),n=!0;}catch(l){if(e!=="error")this.emit("error",l);else throw l}let s=this._onceListeners.get(e);if(s){let r=Array.from(s);this._onceListeners.delete(e);for(let l of r)try{l(t),n=!0;}catch(d){if(e!=="error")this.emit("error",d);else throw d}}return n}getListeners(e){let t=this._listeners.get(e),n=this._onceListeners.get(e),o=[];return t&&o.push(...Array.from(t)),n&&o.push(...Array.from(n)),o}listenerCount(e){let t=this._listeners.get(e)?.size??0,n=this._onceListeners.get(e)?.size??0;return t+n}eventNames(){let e=new Set;for(let t of this._listeners.keys())e.add(t);for(let t of this._onceListeners.keys())e.add(t);return Array.from(e)}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}prependListener(e,t){let n=this._listeners.get(e);if(!n)return this.on(e,t);let o=Array.from(n);return o.unshift(t),this._listeners.set(e,new Set(o)),this}prependOnceListener(e,t){let n=this._onceListeners.get(e);if(!n)return this.once(e,t);let o=Array.from(n);return o.unshift(t),this._onceListeners.set(e,new Set(o)),this}waitFor(e,t){return new Promise((n,o)=>{let s,r=l=>{s&&clearTimeout(s),n(l);};this.once(e,r),t!==void 0&&t>0&&(s=setTimeout(()=>{this.off(e,r),o(new Error(`Timeout waiting for event "${String(e)}"`));},t));})}};var c={FunctionComponent:0,ClassComponent:1,HostRoot:3,HostComponent:5,HostText:6,Fragment:7,ContextConsumer:9,ContextProvider:10,ForwardRef:11,Profiler:12,SuspenseComponent:13,MemoComponent:14,SimpleMemoComponent:15,LazyComponent:16,IncompleteClassComponent:17};function p(i){if(!i)return "Unknown";let{type:e,tag:t}=i;switch(t){case c.FunctionComponent:case c.ClassComponent:case c.SimpleMemoComponent:case c.IncompleteClassComponent:return g(e)||"Anonymous";case c.ForwardRef:if(e&&typeof e=="object"&&"render"in e){let n=e.render;return `ForwardRef(${g(n)||"Anonymous"})`}return "ForwardRef";case c.MemoComponent:if(e&&typeof e=="object"&&"type"in e){let n=e.type;return `Memo(${g(n)||"Anonymous"})`}return "Memo";case c.LazyComponent:return "Lazy";case c.ContextConsumer:return "Context.Consumer";case c.ContextProvider:return "Context.Provider";case c.SuspenseComponent:return "Suspense";case c.Fragment:return "Fragment";case c.Profiler:return "Profiler";case c.HostRoot:return "Root";case c.HostComponent:return typeof e=="string"?e:"HostComponent";case c.HostText:return "#text";default:return g(e)||"Unknown"}}function g(i){if(i!=null){if(typeof i=="string")return i;if(typeof i=="function")return i.displayName??i.name??void 0;if(typeof i=="object"){let e=i;return e.displayName??e.name??void 0}}}function w(i){let{tag:e}=i;return e===c.FunctionComponent||e===c.ClassComponent||e===c.MemoComponent||e===c.SimpleMemoComponent||e===c.ForwardRef||e===c.LazyComponent}function x(i,e){if(i===e)return [];if(!i||!e)return Object.keys(e??i??{});let t=[],n=new Set([...Object.keys(i),...Object.keys(e)]);for(let o of n)o!=="children"&&i[o]!==e[o]&&t.push(o);return t}function y(i,e,t,n){let o=p(i),s=i.actualDuration??0,r=t?x(t,i.memoizedProps):void 0,l=r&&r.length>0,d=n!==i.memoizedState,v={componentName:o,renderCount:1,renderTime:s,phase:e,necessary:e==="mount"||l||d,timestamp:Date.now()};return r!==void 0&&(v.changedProps=r),d&&(v.changedState=["state"]),v}var T={trackUnnecessary:true,fpsThreshold:30,highlightRenders:true,animationSpeed:"fast"},f=class extends u{constructor(t={},n){super();a(this,"config");a(this,"running",false);a(this,"reactVersion","unknown");a(this,"prevFiberStates",new WeakMap);a(this,"renderCounts",new Map);a(this,"originalOnCommitFiberRoot",null);a(this,"win");this.config={...T,...t},this.win=n??(typeof window<"u"?window:{});}start(){if(!this.running)try{this.hookIntoReact(),this.running=!0;}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t)));}}stop(){this.running&&(this.unhookFromReact(),this.running=false);}reset(){this.renderCounts.clear(),this.prevFiberStates=new WeakMap;}hookIntoReact(){let t=this.win.__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!t){this.installHook();return}this.originalOnCommitFiberRoot=t.onCommitFiberRoot.bind(t),t.onCommitFiberRoot=(n,o,s)=>{this.originalOnCommitFiberRoot&&this.originalOnCommitFiberRoot(n,o,s),this.processCommit(o.current);},this.reactVersion=this.detectReactVersion(t),this.emit("ready",{reactVersion:this.reactVersion});}installHook(){let t={renderers:new Map,supportsFiber:true,inject:n=>{let o=t.renderers.size+1;return t.renderers.set(o,n),o},onCommitFiberRoot:(n,o,s)=>{this.processCommit(o.current);},onCommitFiberUnmount:()=>{}};this.win.__REACT_DEVTOOLS_GLOBAL_HOOK__=t,this.emit("ready",{reactVersion:"unknown (hook installed)"});}unhookFromReact(){let t=this.win.__REACT_DEVTOOLS_GLOBAL_HOOK__;t&&this.originalOnCommitFiberRoot&&(t.onCommitFiberRoot=this.originalOnCommitFiberRoot,this.originalOnCommitFiberRoot=null);}detectReactVersion(t){if(t.renderers.size===0)return "unknown";let n=t.renderers.values().next().value;return n&&typeof n=="object"&&"version"in n?String(n.version):"unknown"}processCommit(t){this.walkFiber(t,null);}walkFiber(t,n){t&&(w(t)&&(this.processFiber(t,n),n=p(t)),this.walkFiber(t.child,n),this.walkFiber(t.sibling,n));}processFiber(t,n){let o=p(t);if(this.shouldFilterComponent(o))return;let s=this.prevFiberStates.get(t),l=y(t,s?"update":"mount",s?.props,s?.state),h=(this.renderCounts.get(o)??0)+1;this.renderCounts.set(o,h),l.renderCount=h,this.prevFiberStates.set(t,{props:t.memoizedProps,state:t.memoizedState}),this.emit("render",l);}shouldFilterComponent(t){if(t.startsWith("__")||t==="Fragment"||t==="Suspense"||t==="Profiler")return true;let{include:n,exclude:o}=this.config;return !!(n&&n.length>0&&!n.some(r=>this.matchPattern(t,r))||o&&o.length>0&&o.some(r=>this.matchPattern(t,r)))}matchPattern(t,n){let o=n.replace(/\*/g,".*").replace(/\?/g,".");try{return new RegExp(`^${o}$`).test(t)}catch{return false}}getConfig(){return {...this.config}}configure(t){this.config={...this.config,...t};}isRunning(){return this.running}getReactVersion(){return this.reactVersion}getRenderCount(t){return this.renderCounts.get(t)??0}getAllRenderCounts(){return new Map(this.renderCounts)}};var k={enabled:true,highlightRenders:true,animationSpeed:"fast",showBadges:true,showToolbar:true},E={critical:"#ef4444",warning:"#eab308",info:"#3b82f6",healthy:"#22c55e",unnecessary:"#6b7280"},L={slow:1e3,fast:300,off:0},m=class{constructor(e={}){a(this,"shadowRoot",null);a(this,"host",null);a(this,"config");a(this,"highlights",new Map);a(this,"badges",new Map);a(this,"renderCounts",new Map);a(this,"toolbar",null);a(this,"visible",true);this.config={...k,...e};}init(){this.host=document.createElement("div"),this.host.id="reactcheck-overlay-host",this.host.style.cssText=`
2
+ position: fixed;
3
+ top: 0;
4
+ left: 0;
5
+ width: 100%;
6
+ height: 100%;
7
+ pointer-events: none;
8
+ z-index: 2147483647;
9
+ `,this.shadowRoot=this.host.attachShadow({mode:"closed"}),this.injectStyles(),this.config.showToolbar&&this.createToolbar(),document.body.appendChild(this.host);}destroy(){this.highlights.clear(),this.badges.clear(),this.renderCounts.clear(),this.host&&(this.host.remove(),this.host=null),this.shadowRoot=null,this.toolbar=null;}injectStyles(){if(!this.shadowRoot)return;let e=document.createElement("style");e.textContent=`
10
+ * {
11
+ box-sizing: border-box;
12
+ }
13
+
14
+ .highlight {
15
+ position: fixed;
16
+ pointer-events: none;
17
+ border-width: 2px;
18
+ border-style: solid;
19
+ transition: opacity 0.3s ease-out;
20
+ z-index: 1;
21
+ }
22
+
23
+ .highlight.fade {
24
+ opacity: 0;
25
+ }
26
+
27
+ .badge {
28
+ position: fixed;
29
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
30
+ font-size: 10px;
31
+ font-weight: bold;
32
+ padding: 2px 6px;
33
+ border-radius: 4px;
34
+ color: white;
35
+ pointer-events: none;
36
+ z-index: 2;
37
+ white-space: nowrap;
38
+ }
39
+
40
+ .toolbar {
41
+ position: fixed;
42
+ top: 10px;
43
+ right: 10px;
44
+ background: rgba(0, 0, 0, 0.9);
45
+ border-radius: 8px;
46
+ padding: 8px 12px;
47
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
48
+ font-size: 12px;
49
+ color: white;
50
+ pointer-events: auto;
51
+ z-index: 10;
52
+ cursor: move;
53
+ user-select: none;
54
+ }
55
+
56
+ .toolbar-header {
57
+ display: flex;
58
+ align-items: center;
59
+ justify-content: space-between;
60
+ margin-bottom: 8px;
61
+ }
62
+
63
+ .toolbar-title {
64
+ font-weight: bold;
65
+ color: #22c55e;
66
+ }
67
+
68
+ .toolbar-close {
69
+ background: none;
70
+ border: none;
71
+ color: #9ca3af;
72
+ cursor: pointer;
73
+ font-size: 16px;
74
+ padding: 0;
75
+ line-height: 1;
76
+ }
77
+
78
+ .toolbar-close:hover {
79
+ color: white;
80
+ }
81
+
82
+ .toolbar-stats {
83
+ display: grid;
84
+ grid-template-columns: repeat(2, 1fr);
85
+ gap: 8px;
86
+ }
87
+
88
+ .stat {
89
+ text-align: center;
90
+ }
91
+
92
+ .stat-value {
93
+ font-size: 18px;
94
+ font-weight: bold;
95
+ }
96
+
97
+ .stat-label {
98
+ font-size: 10px;
99
+ color: #9ca3af;
100
+ text-transform: uppercase;
101
+ }
102
+
103
+ .stat-critical .stat-value { color: #ef4444; }
104
+ .stat-warning .stat-value { color: #eab308; }
105
+ .stat-healthy .stat-value { color: #22c55e; }
106
+
107
+ .toolbar-controls {
108
+ margin-top: 8px;
109
+ display: flex;
110
+ gap: 4px;
111
+ }
112
+
113
+ .toolbar-btn {
114
+ background: rgba(255, 255, 255, 0.1);
115
+ border: none;
116
+ border-radius: 4px;
117
+ color: white;
118
+ padding: 4px 8px;
119
+ font-size: 10px;
120
+ cursor: pointer;
121
+ }
122
+
123
+ .toolbar-btn:hover {
124
+ background: rgba(255, 255, 255, 0.2);
125
+ }
126
+
127
+ .toolbar-btn.active {
128
+ background: #3b82f6;
129
+ }
130
+ `,this.shadowRoot.appendChild(e);}createToolbar(){this.shadowRoot&&(this.toolbar=document.createElement("div"),this.toolbar.className="toolbar",this.toolbar.innerHTML=`
131
+ <div class="toolbar-header">
132
+ <span class="toolbar-title">ReactCheck</span>
133
+ <button class="toolbar-close" title="Close">\xD7</button>
134
+ </div>
135
+ <div class="toolbar-stats">
136
+ <div class="stat stat-critical">
137
+ <div class="stat-value" id="rc-critical">0</div>
138
+ <div class="stat-label">Critical</div>
139
+ </div>
140
+ <div class="stat stat-warning">
141
+ <div class="stat-value" id="rc-warning">0</div>
142
+ <div class="stat-label">Warning</div>
143
+ </div>
144
+ <div class="stat stat-healthy">
145
+ <div class="stat-value" id="rc-healthy">0</div>
146
+ <div class="stat-label">Healthy</div>
147
+ </div>
148
+ <div class="stat">
149
+ <div class="stat-value" id="rc-renders">0</div>
150
+ <div class="stat-label">Renders</div>
151
+ </div>
152
+ </div>
153
+ <div class="toolbar-controls">
154
+ <button class="toolbar-btn active" id="rc-highlights">Highlights</button>
155
+ <button class="toolbar-btn active" id="rc-badges">Badges</button>
156
+ <button class="toolbar-btn" id="rc-clear">Clear</button>
157
+ </div>
158
+ `,this.setupToolbarEvents(),this.makeDraggable(this.toolbar),this.shadowRoot.appendChild(this.toolbar));}setupToolbarEvents(){if(!this.toolbar||!this.shadowRoot)return;let e=this.toolbar.querySelector(".toolbar-close");e&&e.addEventListener("click",()=>{this.hide();});let t=this.shadowRoot.getElementById("rc-highlights");t&&t.addEventListener("click",()=>{this.config.highlightRenders=!this.config.highlightRenders,t.classList.toggle("active",this.config.highlightRenders),this.config.highlightRenders||this.clearHighlights();});let n=this.shadowRoot.getElementById("rc-badges");n&&n.addEventListener("click",()=>{this.config.showBadges=!this.config.showBadges,n.classList.toggle("active",this.config.showBadges),this.config.showBadges||this.clearBadges();});let o=this.shadowRoot.getElementById("rc-clear");o&&o.addEventListener("click",()=>{this.clear();});}makeDraggable(e){let t=false,n=0,o=0,s=0,r=0;e.addEventListener("mousedown",l=>{l.target.tagName!=="BUTTON"&&(t=true,n=l.clientX,o=l.clientY,s=e.offsetLeft,r=e.offsetTop);}),document.addEventListener("mousemove",l=>{if(!t)return;let d=l.clientX-n,h=l.clientY-o;e.style.left=`${s+d}px`,e.style.top=`${r+h}px`,e.style.right="auto";}),document.addEventListener("mouseup",()=>{t=false;});}highlight(e,t){if(!this.config.highlightRenders||!this.shadowRoot||!this.visible)return;let n=t.getBoundingClientRect();if(n.width===0||n.height===0)return;let o=this.getSeverity(e),s=E[o],r=this.highlights.get(e.componentName);r||(r=document.createElement("div"),r.className="highlight",this.shadowRoot.appendChild(r),this.highlights.set(e.componentName,r)),r.style.cssText=`
159
+ position: fixed;
160
+ left: ${n.left}px;
161
+ top: ${n.top}px;
162
+ width: ${n.width}px;
163
+ height: ${n.height}px;
164
+ border: 2px solid ${s};
165
+ pointer-events: none;
166
+ z-index: 1;
167
+ `,r.classList.remove("fade");let l=L[this.config.animationSpeed];l>0&&setTimeout(()=>{r?.classList.add("fade");},l),this.config.showBadges&&this.updateBadge(e,n,s),this.updateStats();}updateBadge(e,t,n){if(!this.shadowRoot)return;let o=(this.renderCounts.get(e.componentName)??0)+1;this.renderCounts.set(e.componentName,o);let s=this.badges.get(e.componentName);s||(s=document.createElement("div"),s.className="badge",this.shadowRoot.appendChild(s),this.badges.set(e.componentName,s)),s.textContent=`${e.componentName}: ${o}`,s.style.cssText=`
168
+ position: fixed;
169
+ left: ${t.left}px;
170
+ top: ${Math.max(0,t.top-20)}px;
171
+ background: ${n};
172
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
173
+ font-size: 10px;
174
+ font-weight: bold;
175
+ padding: 2px 6px;
176
+ border-radius: 4px;
177
+ color: white;
178
+ pointer-events: none;
179
+ z-index: 2;
180
+ white-space: nowrap;
181
+ `;}getSeverity(e){return e.necessary?e.renderCount>50?"critical":e.renderCount>20?"warning":"healthy":"unnecessary"}updateStats(){if(!this.shadowRoot)return;let e=0,t=0,n=0,o=0;for(let[,h]of this.renderCounts)o+=h,h>50?e++:h>20?t++:n++;let s=this.shadowRoot.getElementById("rc-critical"),r=this.shadowRoot.getElementById("rc-warning"),l=this.shadowRoot.getElementById("rc-healthy"),d=this.shadowRoot.getElementById("rc-renders");s&&(s.textContent=String(e)),r&&(r.textContent=String(t)),l&&(l.textContent=String(n)),d&&(d.textContent=String(o));}clearHighlights(){for(let e of this.highlights.values())e.remove();this.highlights.clear();}clearBadges(){for(let e of this.badges.values())e.remove();this.badges.clear();}clear(){this.clearHighlights(),this.clearBadges(),this.renderCounts.clear(),this.updateStats();}show(){this.host&&(this.host.style.display="block",this.visible=true);}hide(){this.host&&(this.host.style.display="none",this.visible=false);}toggle(){this.visible?this.hide():this.show();}configure(e){this.config={...this.config,...e};}isVisible(){return this.visible}};var b=class{constructor(){a(this,"scanner");a(this,"overlay");a(this,"ws",null);a(this,"wsPort");a(this,"reconnectTimeout",null);a(this,"initialized",false);let e=window;this.wsPort=e.__REACTCHECK_PORT__??3099,this.scanner=new f({trackUnnecessary:true,highlightRenders:true,animationSpeed:"fast"},e),this.overlay=new m({enabled:true,highlightRenders:true,showBadges:true,showToolbar:true});}init(){this.initialized||(this.initialized=true,this.overlay.init(),this.setupScannerEvents(),this.connect(),console.log("[ReactCheck] Initialized"));}setupScannerEvents(){this.scanner.on("render",e=>{this.send({type:"render",payload:e});let t=this.findDOMElement(e.componentName);t&&this.overlay.highlight(e,t);}),this.scanner.on("ready",e=>{this.send({type:"ready",payload:e});}),this.scanner.on("error",e=>{this.send({type:"error",payload:{message:e.message,code:"SCANNER_ERROR"}});});}connect(){this.ws&&this.ws.close();try{this.ws=new WebSocket(`ws://localhost:${this.wsPort}`),this.ws.onopen=()=>{console.log("[ReactCheck] Connected to CLI"),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.send({type:"ready",payload:{reactVersion:this.scanner.getReactVersion()}}),this.scanner.start();},this.ws.onmessage=e=>{try{let t=JSON.parse(e.data);this.handleMessage(t);}catch(t){console.warn("[ReactCheck] Invalid message:",t);}},this.ws.onerror=e=>{console.warn("[ReactCheck] WebSocket error:",e);},this.ws.onclose=()=>{console.log("[ReactCheck] Disconnected from CLI"),this.scheduleReconnect();};}catch(e){console.warn("[ReactCheck] Failed to connect:",e),this.scheduleReconnect();}}scheduleReconnect(){this.reconnectTimeout||(this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,console.log("[ReactCheck] Attempting to reconnect..."),this.connect();},2e3));}handleMessage(e){switch(e.type){case "start":this.scanner.start(),this.overlay.show();break;case "stop":this.scanner.stop();break;case "reset":this.scanner.reset(),this.overlay.clear();break;case "config":this.handleConfig(e.payload);break;}}handleConfig(e){this.scanner.configure(e),e.highlightRenders!==void 0&&this.overlay.configure({highlightRenders:e.highlightRenders}),e.animationSpeed!==void 0&&this.overlay.configure({animationSpeed:e.animationSpeed});}send(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e));}findDOMElement(e){let t=document.querySelector(`[data-component="${e}"]`);if(t)return t;let n=document.querySelectorAll('[class*="'+e+'"]');return n.length>0?n[0]??null:null}destroy(){this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.ws&&this.ws.close(),this.scanner.stop(),this.overlay.destroy(),this.initialized=false;}};(function(){let i=window;if(i.__REACTCHECK_INJECTED__)return;i.__REACTCHECK_INJECTED__=true;let e=new b;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{e.init();}):e.init(),window.__REACTCHECK__=e;})();
182
+ exports.BrowserScanner=f;exports.Overlay=m;exports.ReactCheckInjector=b;return exports;})({});