dev3000 0.0.89 → 0.0.90
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/dev-environment.d.ts.map +1 -1
- package/dist/dev-environment.js +5 -0
- package/dist/dev-environment.js.map +1 -1
- package/mcp-server/.next/BUILD_ID +1 -1
- package/mcp-server/.next/build-manifest.json +2 -2
- package/mcp-server/.next/fallback-build-manifest.json +2 -2
- package/mcp-server/.next/next-minimal-server.js.nft.json +1 -1
- package/mcp-server/.next/next-server.js.nft.json +1 -1
- package/mcp-server/.next/prerender-manifest.json +3 -3
- package/mcp-server/.next/server/app/_global-error/page.js.nft.json +1 -1
- package/mcp-server/.next/server/app/_global-error.html +2 -2
- package/mcp-server/.next/server/app/_global-error.rsc +1 -1
- package/mcp-server/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/mcp-server/.next/server/app/_not-found.html +1 -1
- package/mcp-server/.next/server/app/_not-found.rsc +1 -1
- package/mcp-server/.next/server/app/api/jank/[session]/route.js.nft.json +1 -1
- package/mcp-server/.next/server/app/api/logs/append/route.js.nft.json +1 -1
- package/mcp-server/.next/server/app/api/logs/head/route.js.nft.json +1 -1
- package/mcp-server/.next/server/app/api/logs/list/route.js.nft.json +1 -1
- package/mcp-server/.next/server/app/api/logs/rotate/route.js.nft.json +1 -1
- package/mcp-server/.next/server/app/api/logs/stream/route.js.nft.json +1 -1
- package/mcp-server/.next/server/app/api/logs/tail/route.js.nft.json +1 -1
- package/mcp-server/.next/server/app/api/orchestrator/route.js.nft.json +1 -1
- package/mcp-server/.next/server/app/api/screenshots/[filename]/route.js.nft.json +1 -1
- package/mcp-server/.next/server/app/api/screenshots/list/route.js.nft.json +1 -1
- package/mcp-server/.next/server/app/api/tools/route.js.nft.json +1 -1
- package/mcp-server/.next/server/app/index.html +1 -1
- package/mcp-server/.next/server/app/index.rsc +1 -1
- package/mcp-server/.next/server/app/logs/page.js.nft.json +1 -1
- package/mcp-server/.next/server/app/mcp/route.js +2 -2
- package/mcp-server/.next/server/app/mcp/route.js.nft.json +1 -1
- package/mcp-server/.next/server/app/page.js.nft.json +1 -1
- package/mcp-server/.next/server/app/video/[session]/page.js.nft.json +1 -1
- package/mcp-server/.next/server/chunks/[root-of-the-server]__05e38acd._.js.map +1 -1
- package/mcp-server/.next/server/chunks/[root-of-the-server]__94037b23._.js.map +1 -1
- package/mcp-server/.next/server/chunks/[root-of-the-server]__ae49815f._.js +2 -2
- package/mcp-server/.next/server/chunks/[root-of-the-server]__ae49815f._.js.map +1 -1
- package/mcp-server/.next/server/chunks/[root-of-the-server]__cc74dbef._.js.map +1 -1
- package/mcp-server/.next/server/chunks/ssr/mcp-server_app_page_tsx_9fc46577._.js.map +1 -1
- package/mcp-server/.next/server/server-reference-manifest.js +1 -1
- package/mcp-server/.next/server/server-reference-manifest.json +1 -1
- package/mcp-server/app/api/orchestrator/route.ts +1 -1
- package/mcp-server/app/mcp/client-manager.ts +1 -1
- package/mcp-server/app/mcp/tools.ts +117 -3
- package/mcp-server/app/page.tsx +0 -1
- package/package.json +1 -1
- /package/mcp-server/.next/static/{4QTQwT0vriZN0rBeHTIWl → XC8IdMzOP-R6sszO2tUlu}/_buildManifest.js +0 -0
- /package/mcp-server/.next/static/{4QTQwT0vriZN0rBeHTIWl → XC8IdMzOP-R6sszO2tUlu}/_clientMiddlewareManifest.json +0 -0
- /package/mcp-server/.next/static/{4QTQwT0vriZN0rBeHTIWl → XC8IdMzOP-R6sszO2tUlu}/_ssgManifest.js +0 -0
|
@@ -2,7 +2,7 @@ module.exports=[92509,(e,t,s)=>{t.exports=e.x("url",()=>require("url"))},21517,(
|
|
|
2
2
|
`+Object.keys(r).map(e=>`${e}: ${r[e]}`).join("\r\n")+"\r\n\r\n"+s)}function y(e,t,s,r,i,n){if(e.listenerCount("wsClientError")){let r=Error(i);Error.captureStackTrace(r,y),e.emit("wsClientError",r,s,t)}else g(s,r,i,n)}t.exports=class extends r{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:h,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=i.createServer((e,t)=>{let s=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),t.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(let s of Object.keys(t))e.on(s,t[s]);return function(){for(let s of Object.keys(t))e.removeListener(s,t[s])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,s,r)=>{this.handleUpgrade(t,s,r,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state){e&&this.once("close",()=>{e(Error("The server is not running"))}),process.nextTick(f,this);return}if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(f,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{f(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,s,r){t.on("error",m);let i=e.headers["sec-websocket-key"],n=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void y(this,e,t,405,"Invalid HTTP method");if(void 0===n||"websocket"!==n.toLowerCase())return void y(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!p.test(i))return void y(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(13!==o&&8!==o)return void y(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});if(!this.shouldHandle(e))return void g(t,400);let h=e.headers["sec-websocket-protocol"],u=new Set;if(void 0!==h)try{u=l.parse(h)}catch(s){y(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&void 0!==d){let s=new c(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=a.parse(d);e[c.extensionName]&&(s.accept(e[c.extensionName]),f[c.extensionName]=s)}catch(s){y(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let n={origin:e.headers[`${8===o?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(n,(n,o,a,c)=>{if(!n)return g(t,o||401,a,c);this.completeUpgrade(f,i,u,e,t,s,r)});if(!this.options.verifyClient(n))return g(t,401)}this.completeUpgrade(f,i,u,e,t,s,r)}completeUpgrade(e,t,s,r,i,n,l){if(!i.readable||!i.writable)return i.destroy();if(i[d])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return g(i,503);let h=o("sha1").update(t+u).digest("base64"),p=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${h}`],y=new this.options.WebSocket(null,void 0,this.options);if(s.size){let e=this.options.handleProtocols?this.options.handleProtocols(s,r):s.values().next().value;e&&(p.push(`Sec-WebSocket-Protocol: ${e}`),y._protocol=e)}if(e[c.extensionName]){let t=e[c.extensionName].params,s=a.format({[c.extensionName]:[t]});p.push(`Sec-WebSocket-Extensions: ${s}`),y._extensions=e}this.emit("headers",p,r),i.write(p.concat("\r\n").join("\r\n")),i.removeListener("error",m),y.setSocket(i,n,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(y),y.on("close",()=>{this.clients.delete(y),this._shouldEmitClose&&!this.clients.size&&process.nextTick(f,this)})),l(y,r)}}},56891,e=>{"use strict";var t=e.i(33405),s=e.i(22734),r=e.i(46786),i=e.i(14747),n=e.i(73169),o=e.i(60801),a=e.i(24361);e.i(66212),e.i(44047),e.i(60238);var c=e.i(6281);e.i(3441),c.default;let l=(0,a.promisify)(t.exec);function h(){let e=(0,i.join)((0,r.homedir)(),".d3k");if(!(0,s.existsSync)(e))return[];try{return(0,s.readdirSync)(e).filter(e=>e.endsWith(".json")).map(t=>{let r=(0,i.join)(e,t),n=JSON.parse((0,s.readFileSync)(r,"utf-8")),o=(0,s.statSync)(r);return{...n,sessionFile:r,lastModified:o.mtime}}).filter(e=>Date.now()-new Date(e.startTime).getTime()<864e5).sort((e,t)=>new Date(t.startTime).getTime()-new Date(e.startTime).getTime())}catch(e){return[]}}function u(e){if(e){let t=h().find(t=>t.projectName===e);if(t&&(0,s.existsSync)(t.logFilePath))return t.logFilePath}let t=process.env.LOG_FILE_PATH;return t&&(0,s.existsSync)(t)?t:null}async function d({projectName:t,focusArea:r="all",mode:i="snapshot",waitForUserInteraction:n=!1,timeRangeMinutes:o=10,includeTimestampInstructions:a=!0,integrateNextjs:c=!1,integrateChromeDevtools:l=!1,returnRawData:d=!1}){let{getMCPClientManager:p}=await e.A(20654),f=p().getConnectedMCPs(),m=f.includes("nextjs-dev"),g=f.includes("chrome-devtools");f.length>0&&R(`Fix My App: Connected to downstream MCPs: ${f.join(", ")}`),m&&!1===c&&(c=!0),g&&!1===l&&(l=!0);let y=await E();y&&R("Fix My App: Recommending dev3000-nextjs-dev MCP for Next.js-specific analysis");let _=u(t);if(!_){let e=h();if(0===e.length)return{content:[{type:"text",text:"❌ No active dev3000 sessions found. Make sure dev3000 is running!"}]};let t=e.map(e=>`• ${e.projectName} (started ${new Date(e.startTime).toLocaleString()})`).join("\n");return{content:[{type:"text",text:`🔍 Multiple dev3000 sessions detected. Please specify which project to fix:
|
|
3
3
|
${t}
|
|
4
4
|
|
|
5
|
-
💡 Use: projectName: "your-project-name" parameter`}]}}let v=[];if("bisect"===i&&n){let e=new Date().toISOString();return v.push("🕐 **TIMESTAMP BISECT MODE ACTIVATED**"),v.push(`📍 Start Time: ${e}`),v.push(""),v.push("🎯 **NOW INTERACT WITH YOUR APP TO REPRODUCE THE ISSUE!**"),v.push("• Click buttons, navigate, submit forms, etc."),v.push("• Reproduce the exact error scenario"),v.push("• When done, run this tool again WITHOUT waitForUserInteraction"),v.push(""),v.push("💡 I'll analyze everything that happens between these timestamps!"),{content:[{type:"text",text:v.join("\n")}]}}try{let e=(0,s.readFileSync)(_,"utf-8").trim().split("\n").filter(Boolean);if(0===e.length)return v.push("📋 Log file is empty. Make sure your app is running and generating logs."),{content:[{type:"text",text:v.join("\n")}]};v.push(`🔍 **FIX MY APP ANALYSIS** - Mode: ${i.toUpperCase()}`),v.push(`📁 Log file: ${_}`),v.push(`📊 Total log entries: ${e.length}`),v.push("");let n=new Date,u=new Date(n.getTime()-60*o*1e3),p=[/ERROR/i,/FAIL/i,/Exception/i,/CRITICAL/i,/FATAL/i,/crashed/i,/undefined/i,/null reference/i,/cannot read/i,/cannot find/i,/not found/i,/timeout/i,/refused/i,/denied/i,/unauthorized/i,/404/,/500/,/503/,/WARN/i,/WARNING/i,/deprecated/i,/slow/i,/retry/i,/RUNTIME\.ERROR/,/hydration.*mismatch/i,/Uncaught/i,/throwOnHydrationMismatch/i],f=e.filter(e=>{let t=e.match(/\[(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)\]/);if(t)return new Date(t[1])>=u;let s=e.match(/\[(\d{2}):(\d{2}):(\d{2})\.(\d{3})\]/);if(s){let e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate(),parseInt(s[1],10),parseInt(s[2],10),parseInt(s[3],10),parseInt(s[4],10));return t>e&&t.setDate(t.getDate()-1),t>=u}return!0}),m=f.filter(e=>p.some(t=>t.test(e))),g=f.filter(e=>e.includes("react-scan")||e.includes("ReactScan")||e.includes("React render")),E={unnecessaryRenders:g.filter(e=>e.includes("unnecessary")||e.includes("re-render")||e.includes("wasted")),slowComponents:g.filter(e=>e.includes("slow")||e.includes("performance")||/\d+ms/.test(e)),totalRenders:g.filter(e=>e.includes("render")).length},S=[/link rel=preload.*must have.*valid.*as/i,/next\/font/i,/automatically generated/i],w=m.filter(e=>!S.some(t=>t.test(e))),x={serverErrors:w.filter(e=>e.includes("[SERVER]")&&(e.includes("ERROR")||e.includes("Exception"))),browserErrors:w.filter(e=>e.includes("[BROWSER]")&&(e.includes("ERROR")||e.includes("CONSOLE ERROR")||e.includes("RUNTIME.ERROR"))),buildErrors:w.filter(e=>e.includes("Failed to compile")||e.includes("Type error")||e.includes("Build failed")),networkErrors:w.filter(e=>!/\b(200|201|204|304)\b/.test(e)&&(e.includes("NETWORK")||e.includes("404")||e.includes("500")||e.includes("timeout"))),warnings:w.filter(e=>/WARN|WARNING|deprecated/i.test(e)&&!/ERROR|Exception|FAIL/i.test(e))},C=w.length,T=C-x.warnings.length,N=e.filter(e=>p.some(t=>t.test(e))),k=N.length>C,O=(e,t)=>{let s=t.indexOf(e);if(-1===s)return[];let r=[];for(let e=s-1;e>=Math.max(0,s-20)&&r.length<5;e--)(t[e].includes("[INTERACTION]")||t[e].includes("[NAVIGATION]")||t[e].includes("[PAGE]"))&&r.unshift(t[e]);return r};if(0!==C||k){if(0===C&&k)v.push(`⚠️ **NO ERRORS IN LAST ${o} MINUTES** - But found ${N.length} errors in the full log`),v.push(""),v.push("📋 **RECENT ERRORS (outside time range):**"),N.slice(-5).forEach(t=>{let s=O(t,e);if(s.length>0)for(let e of(v.push(" 📍 Preceding interactions:"),s))v.push(` ${e}`);v.push(` ❌ ${t}`),v.push("")}),v.push("💡 **TIP:** Increase timeRangeMinutes parameter to analyze these errors"),v.push("💡 **TIP:** Or use timeRangeMinutes=60 to check the last hour");else if(v.push(`🚨 **${C} ISSUES DETECTED** (${T} critical, ${x.warnings.length} warnings)`),v.push(""),x.serverErrors.length>0&&(v.push("🔥 **SERVER ERRORS:**"),x.serverErrors.slice(-5).forEach(t=>{let s=O(t,e);if(s.length>0)for(let e of(v.push(" 📍 Preceding interactions:"),s))v.push(` ${e}`);v.push(` ❌ ${t}`),v.push("")})),x.browserErrors.length>0&&(v.push("🌐 **BROWSER/CONSOLE ERRORS:**"),x.browserErrors.slice(-5).forEach(t=>{let s=O(t,e);if(s.length>0)for(let e of(v.push(" 📍 Preceding interactions:"),s))v.push(` ${e}`);v.push(` ❌ ${t}`),v.push("")})),x.buildErrors.length>0&&(v.push("🔨 **BUILD/COMPILATION ERRORS:**"),x.buildErrors.slice(-5).forEach(t=>{let s=O(t,e);if(s.length>0)for(let e of(v.push(" 📍 Preceding interactions:"),s))v.push(` ${e}`);v.push(` ❌ ${t}`),v.push("")})),x.networkErrors.length>0&&(v.push("🌐 **NETWORK/API ERRORS:**"),x.networkErrors.slice(-5).forEach(t=>{let s=O(t,e);if(s.length>0)for(let e of(v.push(" 📍 Preceding interactions:"),s))v.push(` ${e}`);v.push(` ❌ ${t}`),v.push("")})),x.warnings.length>0&&"all"===r&&(v.push(`⚠️ **WARNINGS** (${x.warnings.length} found, showing recent):`),v.push(x.warnings.slice(-3).join("\n")),v.push("")),v.push("🪄 **ULTIMATE DEV3000 FIX-IT MAGIC READY:**"),v.push("🎯 **I don't just find errors - I FIX them instantly!**"),v.push(""),v.push("📍 **INTERACTION-BASED VERIFICATION WORKFLOW:**"),v.push("• Each error shows the EXACT user interactions that triggered it"),v.push("• Use these interactions to reproduce the error with execute_browser_action"),v.push("• After fixing, replay the SAME interactions to verify the fix works"),v.push("• Example: If error shows [INTERACTION] Click at (x:450, y:300), use:"),v.push(" execute_browser_action(action='click', params={x:450, y:300})"),v.push(""),v.push("🔧 **FIX WORKFLOW:**"),v.push("1. Analyze error patterns and preceding interactions"),v.push("2. Provide exact fix code with file locations"),v.push("3. Guide you through implementing the fixes"),v.push("4. Use execute_browser_action to replay the interactions"),v.push("5. Verify the error no longer occurs!"),v.push("• Dev3000 AUTO-CAPTURES screenshots during all interactions!"),v.push("• No manual screenshots needed - dev3000 handles it all!"),v.push(""),v.push("📸 **AUTO-SCREENSHOT MAGIC:**"),v.push("• Screenshots captured on EVERY page navigation"),v.push("• Screenshots captured on EVERY error/exception"),v.push("• Screenshots captured on manual triggers"),v.push("• All screenshots timestamped and linked to events!"),c||l){let e=[];c&&e.push("Next.js"),l&&e.push("Chrome DevTools"),R(`Fix Analysis: Using active MCP integrations [${e.join(", ")}] for enhanced error analysis`,t),v.push(""),v.push("🎼 **MCP INTEGRATION ENHANCEMENTS:**"),c&&(v.push(""),v.push("⚛️ **Next.js Integration Active:**"),(await $(m.join(" "))).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";v.push(`• Use nextjs-dev.${e.function}${t}`),v.push(` → ${e.reason}`)}),x.serverErrors.length>0&&(v.push("• Correlate server errors with Next.js build/runtime logs"),v.push("• Check for SSR/hydration mismatches in Next.js context"))),l&&(v.push(""),v.push("🌐 **Chrome DevTools Integration Active:**"),(await L(m.join(" "))).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";v.push(`• Use chrome-devtools.${e.function}${t}`),v.push(` → ${e.reason}`)}),x.browserErrors.length>0&&(v.push("• Cross-reference browser console errors with Chrome DevTools"),v.push("• Use DOM inspection for UI interaction failures")),x.networkErrors.length>0&&(v.push("• Analyze network requests timing with Chrome DevTools"),v.push("• Inspect failed requests for detailed error context"))),c&&l&&(v.push(""),v.push("🚀 **TRIPLE-STACK DEBUGGING POWER:**"),v.push("• dev3000 provides interaction replay + error correlation"),v.push("• nextjs-dev provides server-side framework context"),v.push("• chrome-devtools provides precise browser state inspection"),v.push("• Combined = 90%+ issue resolution rate!"))}}else v.push(`✅ **SYSTEM HEALTHY** - No errors found in last ${o} minutes`),v.push("🎯 App appears to be running smoothly!"),a&&"monitor"!==i&&(v.push(""),v.push("💡 **PROACTIVE MONITORING TIPS:**"),v.push("• Use mode='bisect' with waitForUserInteraction=true before testing new features"),v.push("• Use mode='monitor' for continuous background monitoring"),v.push("• Increase timeRangeMinutes to analyze longer periods"));let P=e.filter(e=>e.includes("[SCREENSHOT]")||e.includes("Screenshot captured"));if(P.length>0&&(v.push(""),v.push(`📸 **SCREENSHOTS CAPTURED** (${P.length} total):`),P.slice(-5).forEach(e=>{let t=e.match(/Screenshot captured: (.+)$/);t&&v.push(`• ${t[1]}`)}),v.push(""),v.push("💡 **TIP**: Use analyze_visual_diff tool to compare screenshots and identify changes"),v.push(" (Advanced: screenshots are also accessible via curl if needed)")),"performance"===r||"all"===r){let e=await I(t);if(e.detections.length>0){let s=h().find(e=>e.projectName===t),r=s&&s.sessionFile.match(/"mcpPort":\s*"(\d+)"/)?.[1]||"3684",i=`http://localhost:${r}/video/${e.sessionId}`;v.push(""),e.realCLS?v.push(`🚨 **LAYOUT SHIFT DETECTED** (${e.detections.length} ${1===e.detections.length?"shift":"shifts"} during page load):`):v.push(`🚨 **LOADING JANK DETECTED** (${e.detections.length} layout ${1===e.detections.length?"shift":"shifts"} found):`),v.push(`📹 **View all frames**: ${i}`),v.push(`🎞️ **Session ID**: ${e.sessionId} (${e.totalFrames} frames)`),v.push(""),e.detections.forEach(e=>{let t="high"===e.severity?"🔴":"medium"===e.severity?"🟡":"🟢";if(e.uxImpact?(v.push(`${t} **${e.timeSinceStart}ms** - ${e.element}`),v.push(` ${e.uxImpact}`)):v.push(`${t} **${e.timeSinceStart}ms**: ${e.visualDiff.toFixed(1)}% of screen changed (${e.severity} severity)`),e.beforeFrameUrl&&e.afterFrameUrl&&(v.push(` 📸 Before: ${e.beforeFrameUrl}`),v.push(` 📸 After: ${e.afterFrameUrl}`),v.push(` 💡 Use analyze_visual_diff tool with these URLs to get a detailed description of what changed`),e.element)){let t=e.element.match(/<(\w+)>/);if(t){let e=t[1].toLowerCase();v.push(` 💡 Use find_component_source tool with selector "${e}" to locate the source code`)}}}),v.push(""),e.detections.some(e=>"high"===e.severity)&&e.realCLS&&(v.push("🎯 **WHY DEV3000 CAUGHT THIS BUT CHROME MIGHT NOT:**"),v.push("• dev3000's PerformanceObserver is installed immediately at page load and buffers ALL shifts from the start"),v.push("• Chrome DevTools performance trace may start AFTER initial load, missing early navigation shifts"),v.push("• Our UX-focused detection flags critical element shifts (nav/header) even when CLS score is technically 'good'"),v.push("")),v.push("✅ **DEV3000'S CLS DETECTION IS AUTHORITATIVE**"),v.push("If Chrome DevTools reports CLS: 0.00 but dev3000 detected shifts, TRUST DEV3000."),v.push("• Chrome DevTools trace may start AFTER the shifts occurred"),v.push("• dev3000's PerformanceObserver captures ALL shifts from page start"),v.push("• CLS: 0.00 in Chrome just means the trace missed the early shifts"),v.push(""),v.push("💡 **LAYOUT SHIFT DEBUGGING TIPS:**"),v.push("• Add explicit width/height to images and media"),v.push("• Reserve space for dynamic content (ads, embeds, etc.)"),v.push("• Avoid inserting content above existing content"),v.push("• Use CSS aspect-ratio for responsive elements"),v.push("• Check for web fonts causing text reflow (font-display: swap)"),v.push(`• Raw screenshots: ${e.screenshotDir}`),v.push(""),v.push("📸 **ANALYZING SCREENSHOTS:**"),v.push("• RECOMMENDED: Use analyze_visual_diff tool with before/after URLs (shown above)"),v.push("• The tool provides structured instructions for comparing frames"),v.push("• Advanced: Screenshots are also accessible via curl if needed"),v.push(""),v.push(`🎬 **IMPORTANT**: Share this frame sequence link with the user: ${i}`)}}if((E.totalRenders>0||"performance"===r||"all"===r)&&(E.unnecessaryRenders.length>0||E.slowComponents.length>0)&&(v.push(""),v.push("⚛️ **REACT PERFORMANCE ANALYSIS (react-scan):**"),E.unnecessaryRenders.length>0&&(v.push(`🔄 **Unnecessary Re-renders Detected (${E.unnecessaryRenders.length}):**`),E.unnecessaryRenders.slice(-5).forEach(e=>{v.push(`• ${e}`)}),v.push("")),E.slowComponents.length>0&&(v.push(`🐌 **Slow Components Found (${E.slowComponents.length}):**`),E.slowComponents.slice(-5).forEach(e=>{v.push(`• ${e}`)}),v.push("")),v.push("💡 **REACT OPTIMIZATION TIPS:**"),v.push("• Use React.memo() for components with expensive renders"),v.push("• Use useMemo/useCallback to prevent unnecessary re-renders"),v.push("• Check for unstable prop references (objects/arrays created in render)"),v.push("• Consider using React DevTools Profiler for deeper analysis")),0===C&&"all"===r){let t=e.filter(e=>e.includes("took")&&e.includes("ms"));t.length>0&&(v.push(""),v.push("⚡ **PERFORMANCE INSIGHTS:**"),t.slice(-5).forEach(e=>{v.push(`• ${e}`)}))}if(d){let s;R(`Structured Output: Returning structured data for Claude orchestration with ${C} errors and ${c||l?"active":"no"} integrations`,t);let i=m.map(t=>{let s=O(t,e),r=x.serverErrors.includes(t)?"server":x.browserErrors.includes(t)?"browser":x.buildErrors.includes(t)?"build":x.networkErrors.includes(t)?"network":x.warnings.includes(t)?"warning":"general",i=x.warnings.includes(t)?"warning":t.includes("CRITICAL")||t.includes("FATAL")||t.includes("crashed")?"critical":"error",n=t.match(/\[(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)\]/)||t.match(/\[(\d{2}:\d{2}:\d{2}\.\d{3})\]/);return{timestamp:n?n[1]:new Date().toISOString(),category:r,message:t,interactions:s,severity:i}}),n=[];i.forEach(e=>{("hydration"===e.category||e.message.includes("hydration"))&&n.push({file:"pages/_app.js or components/[component].tsx",description:"Fix hydration mismatch",code:`// Ensure server and client render the same content
|
|
5
|
+
💡 Use: projectName: "your-project-name" parameter`}]}}let v=[];if("bisect"===i&&n){let e=new Date().toISOString();return v.push("🕐 **TIMESTAMP BISECT MODE ACTIVATED**"),v.push(`📍 Start Time: ${e}`),v.push(""),v.push("🎯 **NOW INTERACT WITH YOUR APP TO REPRODUCE THE ISSUE!**"),v.push("• Click buttons, navigate, submit forms, etc."),v.push("• Reproduce the exact error scenario"),v.push("• When done, run this tool again WITHOUT waitForUserInteraction"),v.push(""),v.push("💡 I'll analyze everything that happens between these timestamps!"),{content:[{type:"text",text:v.join("\n")}]}}try{let e=(0,s.readFileSync)(_,"utf-8").trim().split("\n").filter(Boolean);if(0===e.length)return v.push("📋 Log file is empty. Make sure your app is running and generating logs."),{content:[{type:"text",text:v.join("\n")}]};v.push(`🔍 **FIX MY APP ANALYSIS** - Mode: ${i.toUpperCase()}`),v.push(`📁 Log file: ${_}`),v.push(`📊 Total log entries: ${e.length}`),v.push("");let n=new Date,u=new Date(n.getTime()-60*o*1e3),p=[/ERROR/i,/FAIL/i,/Exception/i,/CRITICAL/i,/FATAL/i,/crashed/i,/undefined/i,/null reference/i,/cannot read/i,/cannot find/i,/not found/i,/timeout/i,/refused/i,/denied/i,/unauthorized/i,/404/,/500/,/503/,/WARN/i,/WARNING/i,/deprecated/i,/slow/i,/retry/i,/RUNTIME\.ERROR/,/hydration.*mismatch/i,/Uncaught/i,/throwOnHydrationMismatch/i],f=e.filter(e=>{let t=e.match(/\[(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)\]/);if(t)return new Date(t[1])>=u;let s=e.match(/\[(\d{2}):(\d{2}):(\d{2})\.(\d{3})\]/);if(s){let e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate(),parseInt(s[1],10),parseInt(s[2],10),parseInt(s[3],10),parseInt(s[4],10));return t>e&&t.setDate(t.getDate()-1),t>=u}return!0}),m=f.filter(e=>p.some(t=>t.test(e))),g=f.filter(e=>e.includes("react-scan")||e.includes("ReactScan")||e.includes("React render")),E={unnecessaryRenders:g.filter(e=>e.includes("unnecessary")||e.includes("re-render")||e.includes("wasted")),slowComponents:g.filter(e=>e.includes("slow")||e.includes("performance")||/\d+ms/.test(e)),totalRenders:g.filter(e=>e.includes("render")).length},S=[/link rel=preload.*must have.*valid.*as/i,/next\/font/i,/automatically generated/i,/\[NETWORK\].*\b(200|201|204|304)\b\s+(OK|Created|No Content|Not Modified)/i],w=m.filter(e=>!S.some(t=>t.test(e))),x={serverErrors:w.filter(e=>e.includes("[SERVER]")&&(e.includes("ERROR")||e.includes("Exception"))),browserErrors:w.filter(e=>e.includes("[BROWSER]")&&(e.includes("ERROR")||e.includes("CONSOLE ERROR")||e.includes("RUNTIME.ERROR"))),buildErrors:w.filter(e=>e.includes("Failed to compile")||e.includes("Type error")||e.includes("Build failed")),networkErrors:w.filter(e=>!/\b(200|201|204|304)\b/.test(e)&&(e.includes("NETWORK")||e.includes("404")||e.includes("500")||e.includes("timeout"))),warnings:w.filter(e=>/WARN|WARNING|deprecated/i.test(e)&&!/ERROR|Exception|FAIL/i.test(e))},C=w.length,T=C-x.warnings.length,N=e.filter(e=>p.some(t=>t.test(e))),k=N.length>C,O=(e,t)=>{let s=t.indexOf(e);if(-1===s)return[];let r=[];for(let e=s-1;e>=Math.max(0,s-20)&&r.length<5;e--)(t[e].includes("[INTERACTION]")||t[e].includes("[NAVIGATION]")||t[e].includes("[PAGE]"))&&r.unshift(t[e]);return r};if(0!==C||k){if(0===C&&k)v.push(`⚠️ **NO ERRORS IN LAST ${o} MINUTES** - But found ${N.length} errors in the full log`),v.push(""),v.push("📋 **RECENT ERRORS (outside time range):**"),N.slice(-5).forEach(t=>{let s=O(t,e);if(s.length>0)for(let e of(v.push(" 📍 Preceding interactions:"),s))v.push(` ${e}`);v.push(` ❌ ${t}`),v.push("")}),v.push("💡 **TIP:** Increase timeRangeMinutes parameter to analyze these errors"),v.push("💡 **TIP:** Or use timeRangeMinutes=60 to check the last hour");else if(v.push(`🚨 **${C} ISSUES DETECTED** (${T} critical, ${x.warnings.length} warnings)`),v.push(""),x.serverErrors.length>0&&(v.push("🔥 **SERVER ERRORS:**"),x.serverErrors.slice(-5).forEach(t=>{let s=O(t,e);if(s.length>0)for(let e of(v.push(" 📍 Preceding interactions:"),s))v.push(` ${e}`);v.push(` ❌ ${t}`),v.push("")})),x.browserErrors.length>0&&(v.push("🌐 **BROWSER/CONSOLE ERRORS:**"),x.browserErrors.slice(-5).forEach(t=>{let s=O(t,e);if(s.length>0)for(let e of(v.push(" 📍 Preceding interactions:"),s))v.push(` ${e}`);v.push(` ❌ ${t}`),v.push("")})),x.buildErrors.length>0&&(v.push("🔨 **BUILD/COMPILATION ERRORS:**"),x.buildErrors.slice(-5).forEach(t=>{let s=O(t,e);if(s.length>0)for(let e of(v.push(" 📍 Preceding interactions:"),s))v.push(` ${e}`);v.push(` ❌ ${t}`),v.push("")})),x.networkErrors.length>0&&(v.push("🌐 **NETWORK/API ERRORS:**"),x.networkErrors.slice(-5).forEach(t=>{let s=O(t,e);if(s.length>0)for(let e of(v.push(" 📍 Preceding interactions:"),s))v.push(` ${e}`);v.push(` ❌ ${t}`),v.push("")})),x.warnings.length>0&&"all"===r&&(v.push(`⚠️ **WARNINGS** (${x.warnings.length} found, showing recent):`),v.push(x.warnings.slice(-3).join("\n")),v.push("")),v.push("🪄 **ULTIMATE DEV3000 FIX-IT MAGIC READY:**"),v.push("🎯 **I don't just find errors - I FIX them instantly!**"),v.push(""),v.push("📍 **INTERACTION-BASED VERIFICATION WORKFLOW:**"),v.push("• Each error shows the EXACT user interactions that triggered it"),v.push("• Use these interactions to reproduce the error with execute_browser_action"),v.push("• After fixing, replay the SAME interactions to verify the fix works"),v.push("• Example: If error shows [INTERACTION] Click at (x:450, y:300), use:"),v.push(" execute_browser_action(action='click', params={x:450, y:300})"),v.push(""),v.push("🔧 **FIX WORKFLOW:**"),v.push("1. Analyze error patterns and preceding interactions"),v.push("2. Provide exact fix code with file locations"),v.push("3. Guide you through implementing the fixes"),v.push("4. Use execute_browser_action to replay the interactions"),v.push("5. Verify the error no longer occurs!"),v.push("• Dev3000 AUTO-CAPTURES screenshots during all interactions!"),v.push("• No manual screenshots needed - dev3000 handles it all!"),v.push(""),v.push("📸 **AUTO-SCREENSHOT MAGIC:**"),v.push("• Screenshots captured on EVERY page navigation"),v.push("• Screenshots captured on EVERY error/exception"),v.push("• Screenshots captured on manual triggers"),v.push("• All screenshots timestamped and linked to events!"),c||l){let e=[];c&&e.push("Next.js"),l&&e.push("Chrome DevTools"),R(`Fix Analysis: Using active MCP integrations [${e.join(", ")}] for enhanced error analysis`,t),v.push(""),v.push("🎼 **MCP INTEGRATION ENHANCEMENTS:**"),c&&(v.push(""),v.push("⚛️ **Next.js Integration Active:**"),(await $(m.join(" "))).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";v.push(`• Use nextjs-dev.${e.function}${t}`),v.push(` → ${e.reason}`)}),x.serverErrors.length>0&&(v.push("• Correlate server errors with Next.js build/runtime logs"),v.push("• Check for SSR/hydration mismatches in Next.js context"))),l&&(v.push(""),v.push("🌐 **Chrome DevTools Integration Active:**"),(await L(m.join(" "))).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";v.push(`• Use chrome-devtools.${e.function}${t}`),v.push(` → ${e.reason}`)}),x.browserErrors.length>0&&(v.push("• Cross-reference browser console errors with Chrome DevTools"),v.push("• Use DOM inspection for UI interaction failures")),x.networkErrors.length>0&&(v.push("• Analyze network requests timing with Chrome DevTools"),v.push("• Inspect failed requests for detailed error context"))),c&&l&&(v.push(""),v.push("🚀 **TRIPLE-STACK DEBUGGING POWER:**"),v.push("• dev3000 provides interaction replay + error correlation"),v.push("• nextjs-dev provides server-side framework context"),v.push("• chrome-devtools provides precise browser state inspection"),v.push("• Combined = 90%+ issue resolution rate!"))}}else v.push(`✅ **SYSTEM HEALTHY** - No errors found in last ${o} minutes`),v.push("🎯 App appears to be running smoothly!"),a&&"monitor"!==i&&(v.push(""),v.push("💡 **PROACTIVE MONITORING TIPS:**"),v.push("• Use mode='bisect' with waitForUserInteraction=true before testing new features"),v.push("• Use mode='monitor' for continuous background monitoring"),v.push("• Increase timeRangeMinutes to analyze longer periods"));let P=e.filter(e=>e.includes("[SCREENSHOT]")||e.includes("Screenshot captured"));if(P.length>0&&(v.push(""),v.push(`📸 **SCREENSHOTS CAPTURED** (${P.length} total):`),P.slice(-5).forEach(e=>{let t=e.match(/Screenshot captured: (.+)$/);t&&v.push(`• ${t[1]}`)}),v.push(""),v.push("💡 **TIP**: Use analyze_visual_diff tool to compare screenshots and identify changes"),v.push(" (Advanced: screenshots are also accessible via curl if needed)")),"performance"===r||"all"===r){let e=await I(t);if(e.detections.length>0){let s=h().find(e=>e.projectName===t),r=s&&s.sessionFile.match(/"mcpPort":\s*"(\d+)"/)?.[1]||"3684",i=`http://localhost:${r}/video/${e.sessionId}`;v.push(""),e.realCLS?v.push(`🚨 **LAYOUT SHIFT DETECTED** (${e.detections.length} ${1===e.detections.length?"shift":"shifts"} during page load):`):v.push(`🚨 **LOADING JANK DETECTED** (${e.detections.length} layout ${1===e.detections.length?"shift":"shifts"} found):`),v.push(`📹 **View all frames**: ${i}`),v.push(`🎞️ **Session ID**: ${e.sessionId} (${e.totalFrames} frames)`),v.push(""),e.detections.forEach(e=>{let t="high"===e.severity?"🔴":"medium"===e.severity?"🟡":"🟢";if(e.uxImpact?(v.push(`${t} **${e.timeSinceStart}ms** - ${e.element}`),v.push(` ${e.uxImpact}`)):v.push(`${t} **${e.timeSinceStart}ms**: ${e.visualDiff.toFixed(1)}% of screen changed (${e.severity} severity)`),e.beforeFrameUrl&&e.afterFrameUrl&&(v.push(` 📸 Before: ${e.beforeFrameUrl}`),v.push(` 📸 After: ${e.afterFrameUrl}`),v.push(` 💡 Use analyze_visual_diff tool with these URLs to get a detailed description of what changed`),e.element)){let t=e.element.match(/<(\w+)>/);if(t){let e=t[1].toLowerCase();v.push(` 💡 Use find_component_source tool with selector "${e}" to locate the source code`)}}}),v.push(""),e.detections.some(e=>"high"===e.severity)&&e.realCLS&&(v.push("🎯 **WHY DEV3000 CAUGHT THIS BUT CHROME MIGHT NOT:**"),v.push("• dev3000's PerformanceObserver is installed immediately at page load and buffers ALL shifts from the start"),v.push("• Chrome DevTools performance trace may start AFTER initial load, missing early navigation shifts"),v.push("• Our UX-focused detection flags critical element shifts (nav/header) even when CLS score is technically 'good'"),v.push("")),v.push("✅ **DEV3000'S CLS DETECTION IS AUTHORITATIVE**"),v.push("If Chrome DevTools reports CLS: 0.00 but dev3000 detected shifts, TRUST DEV3000."),v.push("• Chrome DevTools trace may start AFTER the shifts occurred"),v.push("• dev3000's PerformanceObserver captures ALL shifts from page start"),v.push("• CLS: 0.00 in Chrome just means the trace missed the early shifts"),v.push(""),v.push("💡 **LAYOUT SHIFT DEBUGGING TIPS:**"),v.push("• Add explicit width/height to images and media"),v.push("• Reserve space for dynamic content (ads, embeds, etc.)"),v.push("• Avoid inserting content above existing content"),v.push("• Use CSS aspect-ratio for responsive elements"),v.push("• Check for web fonts causing text reflow (font-display: swap)"),v.push(`• Raw screenshots: ${e.screenshotDir}`),v.push(""),v.push("📸 **ANALYZING SCREENSHOTS:**"),v.push("• RECOMMENDED: Use analyze_visual_diff tool with before/after URLs (shown above)"),v.push("• The tool provides structured instructions for comparing frames"),v.push("• Advanced: Screenshots are also accessible via curl if needed"),v.push(""),v.push(`🎬 **IMPORTANT**: Share this frame sequence link with the user: ${i}`)}}if((E.totalRenders>0||"performance"===r||"all"===r)&&(E.unnecessaryRenders.length>0||E.slowComponents.length>0)&&(v.push(""),v.push("⚛️ **REACT PERFORMANCE ANALYSIS (react-scan):**"),E.unnecessaryRenders.length>0&&(v.push(`🔄 **Unnecessary Re-renders Detected (${E.unnecessaryRenders.length}):**`),E.unnecessaryRenders.slice(-5).forEach(e=>{v.push(`• ${e}`)}),v.push("")),E.slowComponents.length>0&&(v.push(`🐌 **Slow Components Found (${E.slowComponents.length}):**`),E.slowComponents.slice(-5).forEach(e=>{v.push(`• ${e}`)}),v.push("")),v.push("💡 **REACT OPTIMIZATION TIPS:**"),v.push("• Use React.memo() for components with expensive renders"),v.push("• Use useMemo/useCallback to prevent unnecessary re-renders"),v.push("• Check for unstable prop references (objects/arrays created in render)"),v.push("• Consider using React DevTools Profiler for deeper analysis")),0===C&&"all"===r){let t=e.filter(e=>e.includes("took")&&e.includes("ms"));t.length>0&&(v.push(""),v.push("⚡ **PERFORMANCE INSIGHTS:**"),t.slice(-5).forEach(e=>{v.push(`• ${e}`)}))}if(d){let s;R(`Structured Output: Returning structured data for Claude orchestration with ${C} errors and ${c||l?"active":"no"} integrations`,t);let i=m.map(t=>{let s=O(t,e),r=x.serverErrors.includes(t)?"server":x.browserErrors.includes(t)?"browser":x.buildErrors.includes(t)?"build":x.networkErrors.includes(t)?"network":x.warnings.includes(t)?"warning":"general",i=x.warnings.includes(t)?"warning":t.includes("CRITICAL")||t.includes("FATAL")||t.includes("crashed")?"critical":"error",n=t.match(/\[(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)\]/)||t.match(/\[(\d{2}:\d{2}:\d{2}\.\d{3})\]/);return{timestamp:n?n[1]:new Date().toISOString(),category:r,message:t,interactions:s,severity:i}}),n=[];i.forEach(e=>{("hydration"===e.category||e.message.includes("hydration"))&&n.push({file:"pages/_app.js or components/[component].tsx",description:"Fix hydration mismatch",code:`// Ensure server and client render the same content
|
|
6
6
|
// Use useEffect for client-only logic
|
|
7
7
|
useEffect(() => {
|
|
8
8
|
// Client-only code here
|
|
@@ -28,7 +28,7 @@ dev3000-chrome-devtools:${s.function}(${JSON.stringify(t,null,2)})
|
|
|
28
28
|
• **dev3000-chrome-devtools**: Advanced debugging (DOM inspection, breakpoints, performance profiling, network interception)
|
|
29
29
|
|
|
30
30
|
⚡ **Both tools share the same Chrome instance** - no conflicts or duplicate browsers`}]}}async function w({action:e,params:t={}}){try{if(await b(e))return R(`Browser Action Delegation: Routing '${e}' to chrome-devtools MCP`),await S(e,t);R(`Browser Action Fallback: Using dev3000's execute_browser_action for '${e}'`);let r=h();if(0===r.length)return{content:[{type:"text",text:"❌ No active dev3000 sessions found. Make sure dev3000 is running with a browser!"}]};let i=JSON.parse((0,s.readFileSync)(r[0].sessionFile,"utf-8")),n=i.cdpUrl;if(!n)try{let e=await fetch("http://localhost:9222/json"),t=(await e.json()).find(e=>"page"===e.type&&!e.url.startsWith("chrome://"));t&&(n=t.webSocketDebuggerUrl,R(`CDP Discovery: Found fallback CDP URL ${n}`,r[0].projectName))}catch(e){R(`CDP Discovery: Failed to find fallback CDP URL - ${e}`,r[0].projectName)}if(!n)return{content:[{type:"text",text:`❌ No Chrome DevTools Protocol URL found. Make sure dev3000 is running with browser monitoring enabled (not --servers-only mode). Session CDP URL: ${i.cdpUrl||"null"}`}]};let o=await new Promise((s,r)=>{let i=new c.default(n);i.on("open",async()=>{try{i.send(JSON.stringify({id:1,method:"Target.getTargets",params:{}}));let o=null,a=2;async function n(e,t,s,r){return new Promise((i,n)=>{let o=s=>{let r=JSON.parse(s.toString());r.id===t&&(e.removeListener("message",o),r.error?n(Error(r.error.message)):i(r.result))};e.on("message",o),e.send(JSON.stringify({id:t,method:s,params:r})),setTimeout(()=>{e.removeListener("message",o),n(Error(`CDP command timeout: ${s}`))},5e3)})}i.on("message",async c=>{let l=JSON.parse(c.toString());if(1===l.id){let e=l.result.targetInfos.find(e=>"page"===e.type);if(!e){i.close(),r(Error("No page targets found"));return}o=e.targetId,i.send(JSON.stringify({id:a++,method:"Target.attachToTarget",params:{targetId:o,flatten:!0}}));return}if("Target.attachedToTarget"===l.method){let r;switch(l.params.sessionId,e){case"click":if("number"!=typeof t.x||"number"!=typeof t.y)throw Error("Click action requires x and y coordinates as numbers");r=await n(i,a++,"Input.dispatchMouseEvent",{type:"mousePressed",x:t.x,y:t.y,button:"left",clickCount:1}),await n(i,a++,"Input.dispatchMouseEvent",{type:"mouseReleased",x:t.x,y:t.y,button:"left",clickCount:1});break;case"navigate":if("string"!=typeof t.url)throw Error("Navigate action requires url parameter as string");r=await n(i,a++,"Page.navigate",{url:t.url});break;case"screenshot":i.close(),s({warning:"Screenshot action is not recommended!",advice:"Dev3000 automatically captures screenshots during interactions. Instead of manual screenshots, use click/navigate/scroll/type actions to reproduce user workflows, and dev3000 will capture screenshots at optimal times.",suggestion:"Run fix_my_app to see all auto-captured screenshots from your session."});return;case"evaluate":{if("string"!=typeof t.expression)throw Error("Evaluate action requires expression parameter as string");let e=t.expression;if(![/^document\.title$/,/^window\.location\.href$/,/^document\.querySelector\(['"][^'"]*['"]\)\.textContent$/,/^document\.body\.scrollHeight$/,/^window\.scrollY$/,/^window\.scrollX$/,/^\s*\(function\(\)\s*\{[\s\S]*__reactFiber\$[\s\S]*\}\)\(\)\s*$/].some(t=>t.test(e)))throw Error("Expression not in whitelist. Only safe read-only expressions allowed.");r=await n(i,a++,"Runtime.evaluate",{expression:e,returnByValue:!0});break}case"scroll":{let e="number"==typeof t.deltaX?t.deltaX:0,s="number"==typeof t.deltaY?t.deltaY:0;r=await n(i,a++,"Input.dispatchMouseEvent",{type:"mouseWheel",x:"number"==typeof t.x?t.x:500,y:"number"==typeof t.y?t.y:500,deltaX:e,deltaY:s});break}case"type":if("string"!=typeof t.text)throw Error("Type action requires text parameter as string");for(let e of t.text)await n(i,a++,"Input.dispatchKeyEvent",{type:"char",text:e});r={action:"type",text:t.text};break;default:throw Error(`Unsupported action: ${e}`)}i.close(),s(r)}}),i.on("error",r)}catch(e){i.close(),r(e)}}),i.on("error",r)}),a=`Browser action '${e}' executed successfully. Result: ${JSON.stringify(o,null,2)}`;return await b("inspect_element")&&(a+="\n\n🔗 **ENHANCED BROWSER ANALYSIS AVAILABLE**\n\ndev3000 completed the basic browser action above. For deeper browser insights, consider also:",(await L(e)).filter(t=>{let s=t.function.toLowerCase(),r=e.toLowerCase();return!!("screenshot"===r&&(s.includes("inspect")||s.includes("performance"))||"evaluate"===r&&(s.includes("console")||s.includes("inspect"))||"navigate"===r&&(s.includes("network")||s.includes("performance"))||"click"===r&&(s.includes("console")||s.includes("inspect")))||"high"===t.priority}).slice(0,2).forEach(e=>{a+=`
|
|
31
|
-
• \`dev3000-chrome-devtools:${e.function}()\` - ${e.reason}`}),a+="\n\n💡 **Augmented approach:** Use dev3000 for basic automation, chrome-devtools for detailed analysis and debugging."),{content:[{type:"text",text:a}]}}catch(e){return{content:[{type:"text",text:`Browser action failed: ${e instanceof Error?e.message:String(e)}`}]}}}let x={"nextjs-dev":["nextjs-dev","nextjs-dev-mcp","@modelcontextprotocol/server-nextjs-dev","mcp-server-nextjs-dev","nextjs-mcp"],"chrome-devtools":["chrome-devtools","chrome-devtools-mcp","@modelcontextprotocol/server-chrome-devtools","mcp-server-chrome-devtools","chrome-mcp"]},C={"nextjs-dev":[3001,3002,8080,8081],"chrome-devtools":[9222,9223,9224,3003]};async function T(){let e=[];try{process.platform;let{stdout:t}=await l("ps aux"),s=t.toLowerCase();for(let[t,r]of Object.entries(x))for(let i of r)if(s.includes(i.toLowerCase())){e.includes(t)||(e.push(t),R(`MCP Discovery: Found ${t} MCP via process detection [${i}]`));break}}catch(e){R(`MCP Discovery: Process detection failed - ${e instanceof Error?e.message:String(e)}`)}return e}async function N(){let e=[];for(let[t,s]of Object.entries(C))for(let r of s)try{if((await fetch(`http://localhost:${r}/health`,{method:"GET",signal:AbortSignal.timeout(2e3)})).ok){e.push(t),R(`MCP Discovery: Found ${t} MCP via HTTP ping on port ${r}`);break}}catch{try{let s=new c.default(`ws://localhost:${r}`);await new Promise((i,n)=>{let o=setTimeout(()=>{s.close(),n(Error("timeout"))},1e3);s.on("open",()=>{clearTimeout(o),s.close(),e.push(t),R(`MCP Discovery: Found ${t} MCP via WebSocket ping on port ${r}`),i(null)}),s.on("error",()=>{clearTimeout(o),n(Error("connection failed"))})});break}catch{}}return e}async function k(t){R("MCP Discovery: Starting proactive MCP discovery",t);let s=new Set;for(let e of(await T()))s.add(e);try{let r=`/Users/${process.env.USER}/Library/Caches/claude-cli-nodejs`,{readdirSync:i,existsSync:n}=await e.A(23970);if(n(r)){let e=i(r).find(e=>e.includes(process.cwd().replace(/\//g,"-")));if(e){let o=`${r}/${e}`,a=`${o}/mcp-logs-dev3000-chrome-devtools`;n(a)&&i(a).length>0&&(s.add("dev3000-chrome-devtools"),R("MCP Discovery: Found dev3000-chrome-devtools via Claude cache logs",t));let c=`${o}/mcp-logs-dev3000-nextjs-dev`;n(c)&&i(c).length>0&&(s.add("dev3000-nextjs-dev"),R("MCP Discovery: Found dev3000-nextjs-dev via Claude cache logs",t))}}}catch(e){R("MCP Discovery: Claude cache check failed, falling back to port detection",t)}if(0===s.size)for(let e of(R("MCP Discovery: No MCPs found via process or cache detection, trying port pinging",t),await N()))s.add(e);let r=Array.from(s);return r.length>0?R(`MCP Discovery: Successfully discovered MCPs [${r.join(", ")}]`,t):R("MCP Discovery: No MCPs detected - will run in standalone mode",t),r}async function O({mcpName:e}={}){let t=[];t.push("🔍 **MCP CAPABILITY INSPECTOR**"),t.push("");try{let s=await k();if(0===s.length)return t.push("❌ **NO MCPs DETECTED**"),t.push("No dev3000-chrome-devtools or dev3000-nextjs-dev MCPs found."),t.push(""),t.push("💡 **To enable enhanced capabilities:**"),t.push("• Ensure Chrome DevTools MCP is configured: `dev3000-chrome-devtools`"),t.push("• Ensure Next.js Dev MCP is configured: `dev3000-nextjs-dev`"),t.push("• Check that Claude Code has MCPs properly configured"),{content:[{type:"text",text:t.join("\n")}]};t.push(`✅ **DISCOVERED MCPs:** ${s.join(", ")}`),t.push("");let r=e?s.filter(t=>t.includes(e)):s;if(0===r.length&&e)return t.push(`❌ **MCP NOT FOUND:** ${e}`),t.push(`Available MCPs: ${s.join(", ")}`),{content:[{type:"text",text:t.join("\n")}]};for(let e of r){t.push(`📋 **${e.toUpperCase()} CAPABILITIES:**`),t.push("");let s=await g(e);if(0===s.length){t.push(" ❌ No capabilities discovered"),t.push(" 💡 This might indicate the MCP is not properly configured or accessible"),t.push("");continue}let r=s.filter(e=>"advanced"===e.category),i=s.filter(e=>"basic"===e.category);t.push(` 🚀 **ADVANCED CAPABILITIES** (${r.length} functions):`),r.length>0?r.forEach(e=>{t.push(` • \`${e.function}()\` - ${e.reason}`)}):t.push(" No advanced capabilities discovered"),t.push(""),t.push(` ⚙️ **BASIC CAPABILITIES** (${i.length} functions):`),i.length>0?i.forEach(e=>{t.push(` • \`${e.function}()\` - ${e.reason}`)}):t.push(" No basic capabilities discovered"),t.push("");let n=p.get(e);if(n){let e=Date.now()-n.timestamp,s=Math.floor(e/6e4);t.push(` 📝 **CACHE INFO:** Discovered ${s} minutes ago`),e>24e4&&t.push(" ⚠️ Cache will refresh soon on next use")}t.push("")}let i=r.reduce(async(e,t)=>{let s=await e,r=await g(t);return s+r.length},Promise.resolve(0));return t.push("🎯 **AUGMENTED DELEGATION STATUS:**"),t.push(`• Total discovered capabilities: ${await i}`),t.push(`• MCPs with advanced capabilities: ${r.filter(async e=>(await g(e)).some(e=>"advanced"===e.category)).length}`),t.push("• Dynamic discovery: ✅ Active (updates automatically)"),t.push("• Cache TTL: 5 minutes"),t.push(""),t.push("💡 **These capabilities are automatically suggested in dev3000's enhanced responses!**"),{content:[{type:"text",text:t.join("\n")}]}}catch(e){return t.push(`❌ **ERROR INSPECTING CAPABILITIES:** ${e instanceof Error?e.message:String(e)}`),t.push(""),t.push("💡 **Troubleshooting:**"),t.push("• Check that MCPs are properly configured in Claude Code"),t.push("• Verify dev3000 can access Claude cache directories"),t.push("• Try running `discover_available_mcps()` first"),{content:[{type:"text",text:t.join("\n")}]}}}async function I(e){let t,a=process.env.SCREENSHOT_DIR||(0,i.join)((0,r.tmpdir)(),"dev3000-mcp-deps","public","screenshots");if(!(0,s.existsSync)(a))return{detections:[],sessionId:"",totalFrames:0,screenshotDir:a};let c=(0,s.readdirSync)(a).filter(e=>e.includes("-jank-")&&e.endsWith(".png")).sort().reverse();if(0===c.length)return{detections:[],sessionId:"",totalFrames:0,screenshotDir:a};let l=c[0].split("-jank-")[0],h=c.filter(e=>e.startsWith(l)).sort((e,t)=>parseInt(e.match(/-(\d+)ms\.png$/)?.[1]||"0",10)-parseInt(t.match(/-(\d+)ms\.png$/)?.[1]||"0",10));if(h.length<2)return{detections:[],sessionId:l,totalFrames:h.length,screenshotDir:a};let d=(0,i.join)(a,`${l}-metadata.json`);if((0,s.existsSync)(d))try{let e=JSON.parse((0,s.readFileSync)(d,"utf-8"));void 0!==e.layoutShifts&&(t={score:e.totalCLS||0,grade:e.clsGrade||"unknown",shifts:e.layoutShifts})}catch{}let p=[],f=new Map;try{let t=u(e);if(t&&(0,s.existsSync)(t)){let e=(0,s.readFileSync)(t,"utf-8").split("\n");for(let t=0;t<e.length;t++){let s=e[t].match(/\[CDP\] CLS #\d+ \(score: [\d.]+, time: (\d+)ms\):/);if(s){let r=parseInt(s[1],10),i=null,n=null;for(let s=t+1;s<Math.min(t+10,e.length);s++){if(!i){let t=e[s].match(/Before:\s+(http:\/\/\S+)/);t&&(i=t[1])}if(!n){let t=e[s].match(/After:\s+(http:\/\/\S+)/);t&&(n=t[1])}if(i&&n){f.set(r,{before:i,after:n});break}}}}}}catch(e){}if(t)return 0===t.shifts.length?{detections:[],sessionId:l,totalFrames:h.length,screenshotDir:a,realCLS:{score:0,grade:t.grade}}:(t.shifts.forEach(e=>{let t=e.sources?.[0]?.node||"unknown",s=["NAV","HEADER","BUTTON","A"].includes(t.toUpperCase()),r=e.timestamp<1e3,i={NAV:"Navigation header (<nav>)",HEADER:"Page header (<header>)",BUTTON:"Button (<button>)",A:"Link (<a>)"}[t.toUpperCase()]||t,n="low",o="Minor visual adjustment";s&&r?(n="high",o=`🚨 CRITICAL: ${i} shifted during initial load - highly visible and disruptive to user interaction`):s?(n="medium",o=`⚠️ ${i} shifted - affects navigation/interaction`):r&&(n="medium",o="Shift during page load - may cause mis-clicks");let a=Math.round(e.timestamp),c=f.get(a);p.push({timestamp:`${e.timestamp.toFixed(0)}ms`,timeSinceStart:a,visualDiff:100*e.score,severity:n,element:i,clsScore:e.score,uxImpact:o,beforeFrameUrl:c?.before,afterFrameUrl:c?.after})}),{detections:p,sessionId:l,totalFrames:h.length,screenshotDir:a,realCLS:{score:t.score,grade:t.grade}});for(let e=1;e<h.length;e++){let t=(0,i.join)(a,h[e-1]),r=(0,i.join)(a,h[e]);try{let i=o.PNG.sync.read((0,s.readFileSync)(t)),a=o.PNG.sync.read((0,s.readFileSync)(r));if(i.width!==a.width||i.height!==a.height)continue;let c=new o.PNG({width:i.width,height:i.height}),u=(0,n.default)(i.data,a.data,c.data,i.width,i.height,{threshold:.1}),d=i.width*i.height,f=u/d*100;if(f>1){let t=h[e].match(/-(\d+)ms\.png$/),s=t?parseInt(t[1],10):0;p.push({timestamp:l,timeSinceStart:s,visualDiff:f,severity:f>10?"high":f>5?"medium":"low"})}}catch{}}return{detections:p,sessionId:l,totalFrames:h.length,screenshotDir:a}}function R(e,t){try{let r=process.env.HOME||process.env.USERPROFILE;if(!r)return;let n=(0,i.join)(r,".d3k","logs");(0,s.existsSync)(n)||(0,s.mkdirSync)(n,{recursive:!0});let o=t||function(){try{let e=process.env.HOME||process.env.USERPROFILE;if(!e)return null;let t=(0,i.join)(e,".d3k");if(!(0,s.existsSync)(t))return null;let r=(0,s.readdirSync)(t).filter(e=>e.endsWith(".json"));if(0===r.length)return null;let n=(0,i.join)(t,r[0]);return JSON.parse((0,s.readFileSync)(n,"utf8")).projectName||null}catch{return null}}();if(!o)return;let a=(0,i.join)(n,`dev3000-${o}-d3k.log`),c=new Date().toISOString(),l=`[${c}] [D3K] ${e}
|
|
31
|
+
• \`dev3000-chrome-devtools:${e.function}()\` - ${e.reason}`}),a+="\n\n💡 **Augmented approach:** Use dev3000 for basic automation, chrome-devtools for detailed analysis and debugging."),{content:[{type:"text",text:a}]}}catch(e){return{content:[{type:"text",text:`Browser action failed: ${e instanceof Error?e.message:String(e)}`}]}}}let x={"nextjs-dev":["nextjs-dev","nextjs-dev-mcp","@modelcontextprotocol/server-nextjs-dev","mcp-server-nextjs-dev","nextjs-mcp"],"chrome-devtools":["chrome-devtools","chrome-devtools-mcp","@modelcontextprotocol/server-chrome-devtools","mcp-server-chrome-devtools","chrome-mcp"]},C={"nextjs-dev":[3001,3002,8080,8081],"chrome-devtools":[9222,9223,9224,3003]};async function T(){let e=[];try{process.platform;let{stdout:t}=await l("ps aux"),s=t.toLowerCase();for(let[t,r]of Object.entries(x))for(let i of r)if(s.includes(i.toLowerCase())){e.includes(t)||(e.push(t),R(`MCP Discovery: Found ${t} MCP via process detection [${i}]`));break}}catch(e){R(`MCP Discovery: Process detection failed - ${e instanceof Error?e.message:String(e)}`)}return e}async function N(){let e=[];for(let[t,s]of Object.entries(C))for(let r of s)try{if((await fetch(`http://localhost:${r}/health`,{method:"GET",signal:AbortSignal.timeout(2e3)})).ok){e.push(t),R(`MCP Discovery: Found ${t} MCP via HTTP ping on port ${r}`);break}}catch{try{let s=new c.default(`ws://localhost:${r}`);await new Promise((i,n)=>{let o=setTimeout(()=>{s.close(),n(Error("timeout"))},1e3);s.on("open",()=>{clearTimeout(o),s.close(),e.push(t),R(`MCP Discovery: Found ${t} MCP via WebSocket ping on port ${r}`),i(null)}),s.on("error",()=>{clearTimeout(o),n(Error("connection failed"))})});break}catch{}}return e}async function k(t){R("MCP Discovery: Starting proactive MCP discovery",t);let s=new Set;for(let e of(await T()))s.add(e);try{let r=`/Users/${process.env.USER}/Library/Caches/claude-cli-nodejs`,{readdirSync:i,existsSync:n}=await e.A(23970);if(n(r)){let e=i(r).find(e=>e.includes(process.cwd().replace(/\//g,"-")));if(e){let o=`${r}/${e}`,a=`${o}/mcp-logs-dev3000-chrome-devtools`;n(a)&&i(a).length>0&&(s.add("dev3000-chrome-devtools"),R("MCP Discovery: Found dev3000-chrome-devtools via Claude cache logs",t));let c=`${o}/mcp-logs-dev3000-nextjs-dev`;n(c)&&i(c).length>0&&(s.add("dev3000-nextjs-dev"),R("MCP Discovery: Found dev3000-nextjs-dev via Claude cache logs",t))}}}catch(e){R("MCP Discovery: Claude cache check failed, falling back to port detection",t)}if(0===s.size)for(let e of(R("MCP Discovery: No MCPs found via process or cache detection, trying port pinging",t),await N()))s.add(e);let r=Array.from(s);return r.length>0?R(`MCP Discovery: Successfully discovered MCPs [${r.join(", ")}]`,t):R("MCP Discovery: No MCPs detected - will run in standalone mode",t),r}async function O({mcpName:e}={}){let t=[];t.push("🔍 **MCP CAPABILITY INSPECTOR**"),t.push("");try{let s=await k();if(0===s.length)return t.push("❌ **NO MCPs DETECTED**"),t.push("No dev3000-chrome-devtools or dev3000-nextjs-dev MCPs found."),t.push(""),t.push("💡 **To enable enhanced capabilities:**"),t.push("• Ensure Chrome DevTools MCP is configured: `dev3000-chrome-devtools`"),t.push("• Ensure Next.js Dev MCP is configured: `dev3000-nextjs-dev`"),t.push("• Check that Claude Code has MCPs properly configured"),{content:[{type:"text",text:t.join("\n")}]};t.push(`✅ **DISCOVERED MCPs:** ${s.join(", ")}`),t.push("");let r=e?s.filter(t=>t.includes(e)):s;if(0===r.length&&e)return t.push(`❌ **MCP NOT FOUND:** ${e}`),t.push(`Available MCPs: ${s.join(", ")}`),{content:[{type:"text",text:t.join("\n")}]};for(let e of r){t.push(`📋 **${e.toUpperCase()} CAPABILITIES:**`),t.push("");let s=await g(e);if(0===s.length){t.push(" ❌ No capabilities discovered"),t.push(" 💡 This might indicate the MCP is not properly configured or accessible"),t.push("");continue}let r=s.filter(e=>"advanced"===e.category),i=s.filter(e=>"basic"===e.category);t.push(` 🚀 **ADVANCED CAPABILITIES** (${r.length} functions):`),r.length>0?r.forEach(e=>{t.push(` • \`${e.function}()\` - ${e.reason}`)}):t.push(" No advanced capabilities discovered"),t.push(""),t.push(` ⚙️ **BASIC CAPABILITIES** (${i.length} functions):`),i.length>0?i.forEach(e=>{t.push(` • \`${e.function}()\` - ${e.reason}`)}):t.push(" No basic capabilities discovered"),t.push("");let n=p.get(e);if(n){let e=Date.now()-n.timestamp,s=Math.floor(e/6e4);t.push(` 📝 **CACHE INFO:** Discovered ${s} minutes ago`),e>24e4&&t.push(" ⚠️ Cache will refresh soon on next use")}t.push("")}let i=r.reduce(async(e,t)=>{let s=await e,r=await g(t);return s+r.length},Promise.resolve(0));return t.push("🎯 **AUGMENTED DELEGATION STATUS:**"),t.push(`• Total discovered capabilities: ${await i}`),t.push(`• MCPs with advanced capabilities: ${r.filter(async e=>(await g(e)).some(e=>"advanced"===e.category)).length}`),t.push("• Dynamic discovery: ✅ Active (updates automatically)"),t.push("• Cache TTL: 5 minutes"),t.push(""),t.push("💡 **These capabilities are automatically suggested in dev3000's enhanced responses!**"),{content:[{type:"text",text:t.join("\n")}]}}catch(e){return t.push(`❌ **ERROR INSPECTING CAPABILITIES:** ${e instanceof Error?e.message:String(e)}`),t.push(""),t.push("💡 **Troubleshooting:**"),t.push("• Check that MCPs are properly configured in Claude Code"),t.push("• Verify dev3000 can access Claude cache directories"),t.push("• Try running `discover_available_mcps()` first"),{content:[{type:"text",text:t.join("\n")}]}}}async function I(e){let t,a=process.env.SCREENSHOT_DIR||(0,i.join)((0,r.tmpdir)(),"dev3000-mcp-deps","public","screenshots");if(!(0,s.existsSync)(a))return{detections:[],sessionId:"",totalFrames:0,screenshotDir:a};let c=(0,s.readdirSync)(a).filter(e=>e.includes("-jank-")&&e.endsWith(".png")).sort().reverse();if(0===c.length)return{detections:[],sessionId:"",totalFrames:0,screenshotDir:a};let l=c[0].split("-jank-")[0],h=c.filter(e=>e.startsWith(l)).sort((e,t)=>parseInt(e.match(/-(\d+)ms\.png$/)?.[1]||"0",10)-parseInt(t.match(/-(\d+)ms\.png$/)?.[1]||"0",10));if(h.length<2)return{detections:[],sessionId:l,totalFrames:h.length,screenshotDir:a};let d=(0,i.join)(a,`${l}-metadata.json`);if((0,s.existsSync)(d))try{let e=JSON.parse((0,s.readFileSync)(d,"utf-8"));void 0!==e.layoutShifts&&(t={score:e.totalCLS||0,grade:e.clsGrade||"unknown",shifts:e.layoutShifts})}catch{}let p=[],f=new Map;try{let t=u(e);if(t&&(0,s.existsSync)(t)){let e=(0,s.readFileSync)(t,"utf-8").split("\n");for(let t=0;t<e.length;t++){let s=e[t].match(/\[CDP\] CLS #\d+ \(score: [\d.]+, time: (\d+)ms\):/);if(s){let r=parseInt(s[1],10),i=null,n=null;for(let s=t+1;s<Math.min(t+10,e.length);s++){if(!i){let t=e[s].match(/Before:\s+(http:\/\/\S+)/);t&&(i=t[1])}if(!n){let t=e[s].match(/After:\s+(http:\/\/\S+)/);t&&(n=t[1])}if(i&&n){f.set(r,{before:i,after:n});break}}}}}}catch(e){}if(t){if(0===t.shifts.length){let e=h.filter(e=>{let t=e.match(/-(\d+)ms\.png$/);return(t?parseInt(t[1],10):0)<1500}),r=!1;for(let t=1;t<e.length&&t<10;t++){let n=(0,i.join)(a,e[t-1]),c=(0,i.join)(a,e[t]);try{let i=o.PNG.sync.read((0,s.readFileSync)(n)),a=o.PNG.sync.read((0,s.readFileSync)(c));if(i.width!==a.width||i.height!==a.height)continue;let l=function(e,t){let s=e.width,r=e.height,i=Math.floor(r/8),n=Array(8).fill(0);for(let o=0;o<r;o++){let r=Math.min(Math.floor(o/i),7);for(let i=0;i<s;i++){let a=s*o+i<<2,c=Math.abs(e.data[a]-t.data[a]),l=Math.abs(e.data[a+1]-t.data[a+1]),h=Math.abs(e.data[a+2]-t.data[a+2]);(c>30||l>30||h>30)&&n[r]++}}let o=s*i,a=n.map(e=>e/o*100),c=(a[0]+a[1])/2,l=(a[6]+a[7])/2,h=n.reduce((e,t)=>e+t,0);return{isLayoutShift:c>5&&l<2&&c>2*l,shiftScore:h/(s*r)*.1}}(i,a);if(l.isLayoutShift){r=!0;let s=e[t].match(/-(\d+)ms\.png$/),i=s?parseInt(s[1],10):0,n=process.env.MCP_PORT||"3684";p.push({timestamp:`${i}ms`,timeSinceStart:i,visualDiff:100*l.shiftScore,severity:"high",element:"Hydration-related element",clsScore:l.shiftScore,uxImpact:"🚨 CRITICAL: Fast hydration shift detected - Chrome's observer missed this early shift",beforeFrameUrl:`http://localhost:${n}/api/screenshots/${e[t-1]}`,afterFrameUrl:`http://localhost:${n}/api/screenshots/${e[t]}`})}}catch{}}return r?{detections:p,sessionId:l,totalFrames:h.length,screenshotDir:a,realCLS:{score:.05,grade:"good"}}:{detections:[],sessionId:l,totalFrames:h.length,screenshotDir:a,realCLS:{score:0,grade:t.grade}}}return t.shifts.forEach(e=>{let t=e.sources?.[0]?.node||"unknown",s=["NAV","HEADER","BUTTON","A"].includes(t.toUpperCase()),r=e.timestamp<1e3,i={NAV:"Navigation header (<nav>)",HEADER:"Page header (<header>)",BUTTON:"Button (<button>)",A:"Link (<a>)"}[t.toUpperCase()]||t,n="low",o="Minor visual adjustment";s&&r?(n="high",o=`🚨 CRITICAL: ${i} shifted during initial load - highly visible and disruptive to user interaction`):s?(n="medium",o=`⚠️ ${i} shifted - affects navigation/interaction`):r&&(n="medium",o="Shift during page load - may cause mis-clicks");let a=Math.round(e.timestamp),c=f.get(a);p.push({timestamp:`${e.timestamp.toFixed(0)}ms`,timeSinceStart:a,visualDiff:100*e.score,severity:n,element:i,clsScore:e.score,uxImpact:o,beforeFrameUrl:c?.before,afterFrameUrl:c?.after})}),{detections:p,sessionId:l,totalFrames:h.length,screenshotDir:a,realCLS:{score:t.score,grade:t.grade}}}for(let e=1;e<h.length;e++){let t=(0,i.join)(a,h[e-1]),r=(0,i.join)(a,h[e]);try{let i=o.PNG.sync.read((0,s.readFileSync)(t)),a=o.PNG.sync.read((0,s.readFileSync)(r));if(i.width!==a.width||i.height!==a.height)continue;let c=new o.PNG({width:i.width,height:i.height}),u=(0,n.default)(i.data,a.data,c.data,i.width,i.height,{threshold:.1}),d=i.width*i.height,f=u/d*100;if(f>1){let t=h[e].match(/-(\d+)ms\.png$/),s=t?parseInt(t[1],10):0;p.push({timestamp:l,timeSinceStart:s,visualDiff:f,severity:f>10?"high":f>5?"medium":"low"})}}catch{}}return{detections:p,sessionId:l,totalFrames:h.length,screenshotDir:a}}function R(e,t){try{let r=process.env.HOME||process.env.USERPROFILE;if(!r)return;let n=(0,i.join)(r,".d3k","logs");(0,s.existsSync)(n)||(0,s.mkdirSync)(n,{recursive:!0});let o=t||function(){try{let e=process.env.HOME||process.env.USERPROFILE;if(!e)return null;let t=(0,i.join)(e,".d3k");if(!(0,s.existsSync)(t))return null;let r=(0,s.readdirSync)(t).filter(e=>e.endsWith(".json"));if(0===r.length)return null;let n=(0,i.join)(t,r[0]);return JSON.parse((0,s.readFileSync)(n,"utf8")).projectName||null}catch{return null}}();if(!o)return;let a=(0,i.join)(n,`dev3000-${o}-d3k.log`),c=new Date().toISOString(),l=`[${c}] [D3K] ${e}
|
|
32
32
|
`;(0,s.appendFileSync)(a,l)}catch(e){}}function P(e,t){let s=e.includes("nextjs-dev"),r=e.includes("chrome-devtools");if(e.length>0){R(`MCP Detection: Available MCPs [${e.join(", ")}]`,t);let i=[];s&&i.push("Next.js"),r&&i.push("Chrome DevTools"),i.length>0?R(`MCP Integration: Activated integrations [${i.join(", ")}]`,t):R("MCP Integration: No compatible MCPs detected - running in standalone mode",t)}else R("MCP Detection: No MCPs provided - running in standalone mode",t);return{integrateNextjs:s,integrateChromeDevtools:r}}function A(e,t){let s=Math.ceil(Math.min(2*e,20)*(t?.5:1));return s<=5||s<=60?`${s} minutes`:`${Math.ceil(s/60)} hours`}async function $(e){try{let t=await g("dev3000-nextjs-dev"),s=t.filter(e=>"advanced"===e.category).slice(0,8).map(t=>({function:t.function,reason:t.reason,priority:D(t.function,e)}));return R(`Dynamic Suggestions: Generated ${s.length} Next.js suggestions from ${t.length} discovered capabilities`),s}catch(e){return R(`Dynamic Suggestions: Failed to generate Next.js suggestions - ${e}`),[{function:"analyze_build_process",reason:"Advanced Next.js build system analysis",priority:"high"},{function:"debug_server_rendering",reason:"Server-side rendering debugging",priority:"high"}]}}async function L(e){try{let t=await g("dev3000-chrome-devtools"),s=t.filter(e=>"advanced"===e.category).slice(0,8).map(t=>({function:t.function,reason:t.reason,priority:D(t.function,e)}));return R(`Dynamic Suggestions: Generated ${s.length} Chrome DevTools suggestions from ${t.length} discovered capabilities`),s}catch(e){return R(`Dynamic Suggestions: Failed to generate Chrome DevTools suggestions - ${e}`),[{function:"inspect_element",reason:"Deep DOM inspection with DevTools-level detail",priority:"high"},{function:"access_console",reason:"Direct browser console access and manipulation",priority:"high"}]}}function D(e,t){let s=e.toLowerCase(),r=t?.toLowerCase()||"";for(let{pattern:e,keywords:t}of[{pattern:/hydration/,keywords:["hydration","ssr","render"]},{pattern:/build|compile/,keywords:["build","compile","analyze"]},{pattern:/network|fetch|api/,keywords:["network","request","intercept","performance"]},{pattern:/console|error/,keywords:["console","error","debug"]},{pattern:/click|interaction/,keywords:["dom","element","inspect"]}])if(e.test(r)&&t.some(e=>s.includes(e)))return"high";return["debug","profile","analyze","trace","inspect"].some(e=>s.includes(e))?"medium":"low"}async function M({availableMcps:e,focusArea:t="all",errorContext:s}){let r=[];R(`Workflow Creation: Creating integrated workflow with focus area [${t}]${s?`, error context [${s}]`:""}`);let i=e||[];e&&0!==e.length||(R("Workflow Creation: No MCPs provided, starting proactive discovery"),i=await k());let{integrateNextjs:n,integrateChromeDevtools:o}=P(i);r.push("🎼 **INTELLIGENT DEBUGGING ORCHESTRATOR**"),r.push(`🔍 Available MCPs: ${i.length>0?i.join(", "):"none (will attempt discovery)"}`),r.push(`⚡ Integrations: ${n?"✅ Next.js":"❌ Next.js"} | ${o?"✅ Chrome DevTools":"❌ Chrome DevTools"}`),s&&r.push(`🎯 Error Context: ${s}`),r.push("");let a=n?await $(s):[],c=o?await L(s):[];if(!n&&!o)return r.push("⚠️ **NO INTEGRATIONS DETECTED**"),r.push("Running in standalone mode. For enhanced debugging:"),r.push("• Add 'nextjs-dev' MCP for Next.js-specific analysis"),r.push("• Add 'chrome-devtools' MCP for browser inspection"),r.push(""),r.push("💡 **STANDALONE WORKFLOW:**"),r.push("1. Use fix_my_app(mode='snapshot') to analyze current issues"),r.push("2. Use execute_browser_action to reproduce and verify fixes"),r.push("3. Implement suggested code fixes"),{content:[{type:"text",text:r.join("\n")}]};r.push("🎪 **3-PHASE INTEGRATED WORKFLOW**"),r.push(""),r.push("🕐 **PHASE 1: PARALLEL DATA COLLECTION** (2-3 minutes)"),r.push("Execute these functions in parallel across all available MCPs:"),r.push(""),r.push("📊 **dev3000 (this MCP):**"),r.push(`• fix_my_app(focusArea='${t}', integrateNextjs=${n}, integrateChromeDevtools=${o}, returnRawData=true)`),r.push(" → Get comprehensive error analysis with interaction data"),r.push(""),n&&(r.push("⚛️ **nextjs-dev MCP:**"),a.filter(e=>"high"===e.priority).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";r.push(`• ${e.function}${t}`),r.push(` → ${e.reason}`)}),r.push("")),o&&(r.push("🌐 **chrome-devtools MCP:**"),c.filter(e=>"high"===e.priority).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";r.push(`• ${e.function}${t}`),r.push(` → ${e.reason}`)}),r.push("")),r.push("🕑 **PHASE 2: DEEP TARGETED ANALYSIS** (3-5 minutes)"),r.push("Based on Phase 1 findings, execute these functions sequentially:"),r.push(""),r.push("🔗 **Cross-MCP Correlation:**"),r.push("• Compare dev3000 interaction data with browser console errors"),n&&(r.push("• Correlate dev3000 server errors with Next.js build/runtime logs"),r.push("• Match interaction timestamps with Next.js request handling")),r.push("• Identify root cause by combining all data sources"),r.push(""),r.push("🎯 **Targeted Deep Dive:**"),r.push("• Use fix_my_app(mode='bisect') for regression analysis if needed"),o&&c.filter(e=>"medium"===e.priority).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";r.push(`• ${e.function}${t} - ${e.reason}`)}),r.push(""),r.push("🕒 **PHASE 3: FIX IMPLEMENTATION & VERIFICATION** (5-10 minutes)"),r.push("Orchestrated fix implementation with cross-MCP verification:"),r.push(""),r.push("🔧 **Implementation:**"),r.push("• Apply code fixes identified by dev3000 error analysis"),n&&r.push("• Address Next.js-specific issues (hydration, build, etc.)"),r.push("• Use dev3000's interaction data to create comprehensive test scenarios"),r.push(""),r.push("✅ **Verification Workflow:**"),r.push("• Use execute_browser_action to replay exact user interactions that caused errors"),o&&(r.push("• Use chrome-devtools to monitor console for error resolution"),r.push("• Take before/after screenshots to verify UI fixes")),n&&r.push("• Use nextjs-dev to verify build success and runtime stability"),r.push("• Re-run fix_my_app to confirm error resolution"),r.push(""),r.push("🚀 **INTEGRATION BENEFITS:**"),n&&o?(r.push("🎯 **Triple-Stack Coverage:**"),r.push("• dev3000: AI-powered error correlation + interaction replay"),r.push("• nextjs-dev: Framework-specific server-side analysis"),r.push("• chrome-devtools: Precise browser state inspection"),r.push("• Combined: Complete full-stack debugging with 90%+ issue resolution"),r.push(""),r.push("⚡ **Expected Results:**"),r.push("• 3x faster debugging vs using tools individually"),r.push("• AI-powered error correlation across all layers"),r.push("• Systematic fix verification workflow"),r.push("• Comprehensive interaction-based testing")):n?(r.push("🎯 **Server-Side Enhanced Coverage:**"),r.push("• dev3000: Client error analysis + interaction data"),r.push("• nextjs-dev: Server-side logs and build analysis"),r.push("• Combined: Full-stack Next.js debugging coverage")):o&&(r.push("🎯 **Browser-Enhanced Coverage:**"),r.push("• dev3000: Error detection + interaction replay"),r.push("• chrome-devtools: Detailed browser state inspection"),r.push("• Combined: Complete client-side debugging workflow"));let l=A(5,n||o);return r.push(""),r.push(`⏱️ **ESTIMATED TOTAL TIME:** ${l}`),r.push(`🎼 **dev3000 orchestrates ${i.length} MCPs for maximum debugging power!**`),{content:[{type:"text",text:r.join("\n")}]}}async function U(e){let{beforeImageUrl:t,afterImageUrl:s,context:r}=e,i=[];return i.push("🔍 **VISUAL DIFF ANALYSIS**"),i.push(""),i.push("To analyze the visual differences between these two screenshots:"),i.push(""),i.push("**Step 1: Fetch and analyze the BEFORE image**"),i.push(`Use WebFetch with URL: \`${t}\``),i.push('Prompt: "Describe this screenshot in detail, focusing on layout and visible elements"'),i.push(""),i.push("**Step 2: Fetch and analyze the AFTER image**"),i.push(`Use WebFetch with URL: \`${s}\``),i.push('Prompt: "Describe this screenshot in detail, focusing on layout and visible elements"'),i.push(""),i.push("**Step 3: Compare and describe the differences**"),r?i.push(`Focus on: ${r}`):(i.push("Look for:"),i.push("• Elements that appeared or disappeared"),i.push("• Elements that moved or changed position"),i.push("• Elements that changed size or style"),i.push("• New content that pushed existing content")),i.push(""),i.push("**Step 4: Identify the layout shift cause**"),i.push("Describe what visual change occurred that caused the layout shift."),i.push("Be specific about:"),i.push("• Which element(s) changed"),i.push("• What appeared/moved/resized"),i.push("• Why this caused other elements to shift"),{content:[{type:"text",text:i.join("\n")}]}}async function F(e){let{selector:t}=e;try{let e=h();if(0===e.length)return{content:[{type:"text",text:"❌ **NO ACTIVE SESSIONS**\n\nNo active dev3000 sessions found. Make sure your app is running with dev3000."}]};let r=JSON.parse((0,s.readFileSync)(e[0].sessionFile,"utf-8")).cdpUrl;if(!r)try{let e=await fetch("http://localhost:9222/json"),t=(await e.json()).find(e=>"page"===e.type&&!e.url.startsWith("chrome://"));t&&(r=t.webSocketDebuggerUrl)}catch{return{content:[{type:"text",text:"❌ **NO CDP CONNECTION**\n\nFailed to find Chrome DevTools Protocol URL."}]}}if(!r)return{content:[{type:"text",text:"❌ **NO CDP CONNECTION**\n\nNo Chrome DevTools Protocol URL found."}]};let i=`
|
|
33
33
|
(function() {
|
|
34
34
|
try {
|