@0x1f320.sh/why-did-you-render-mcp 1.1.0-dev.3 → 1.1.0-dev.5

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.
@@ -1,12 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{McpServer as e}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as t}from"@modelcontextprotocol/sdk/server/stdio.js";import{io as n}from"socket.io-client";import{z as r}from"zod";import{existsSync as i,mkdirSync as a,readFileSync as o,readdirSync as s,unlinkSync as c,writeFileSync as l}from"node:fs";import{homedir as u}from"node:os";import{join as d}from"node:path";import ee from"xxhash-wasm";import f from"node:http";import{Server as te}from"socket.io";let p=null,m=4649;function h(e){m=e}function g(){return p||=n(`http://127.0.0.1:${m}`,{transports:[`websocket`],reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:3}),p}function _(e){g().emit(`relay-pause`,e)}function v(e){g().emit(`relay-resume`,e)}function y(){p&&=(p.close(),null)}const b=`@@dict`,x=`@@ref:`;let S;const C=ee().then(e=>{S=e.h64ToString});function w(){return C}function T(e){return S(JSON.stringify(e))}function E(e){return typeof e==`object`&&!!e}function D(e,t){return e?e.map(e=>{let{prevValue:n,nextValue:r}=e;if(E(n)){let e=T(n);t[e]??=n,n=`${x}${e}`}if(E(r)){let e=T(r);t[e]??=r,r=`${x}${e}`}return n===e.prevValue&&r===e.nextValue?e:{...e,prevValue:n,nextValue:r}}):!1}function ne(e,t){let{propsDifferences:n,stateDifferences:r,hookDifferences:i}=e.reason,a=D(n,t),o=D(r,t),s=D(i,t);return a===n&&o===r&&s===i?e:{...e,reason:{propsDifferences:a,stateDifferences:o,hookDifferences:s}}}function O(e,t){return e?e.map(e=>{let{prevValue:n,nextValue:r}=e;return typeof n==`string`&&n.startsWith(x)&&(n=t[n.slice(6)]??n),typeof r==`string`&&r.startsWith(x)&&(r=t[r.slice(6)]??r),n===e.prevValue&&r===e.nextValue?e:{...e,prevValue:n,nextValue:r}}):!1}function k(e,t){let{propsDifferences:n,stateDifferences:r,hookDifferences:i}=e.reason,a=O(n,t),o=O(r,t),s=O(i,t);return a===n&&o===r&&s===i?e:{...e,reason:{propsDifferences:a,stateDifferences:o,hookDifferences:s}}}function A(e){if(!i(e))return[];let t=o(e,`utf-8`).split(`
3
- `).filter(Boolean);if(t.length===0)return[];let n,r=0,a=JSON.parse(t[0]);`@@dict`in a&&(n=a[b],r=1);let s=t.slice(r).map(e=>JSON.parse(e));return n?s.map(e=>k(e,n)):s}function j(e){return e.replaceAll(/[^a-zA-Z0-9_.-]/g,`_`)}function M(e){return{project:e.projectId,displayName:e.displayName,reason:e.reason,...e.hookName!=null&&{hookName:e.hookName},...e.commitId!=null&&{commitId:e.commitId},...e.timestamp!=null&&{timestamp:e.timestamp},...e.stackFrames!=null&&e.stackFrames.length>0&&{stackFrames:e.stackFrames}}}const N=`nocommit`,P=new class{dir;buffers=new Map;timers=new Map;dicts=new Map;bufferMeta=new Map;trackedComponents=new Map;wdyrConfigs=new Map;constructor(e){this.dir=e??d(u(),`.wdyr-mcp`,`renders`),a(this.dir,{recursive:!0})}addRender(e,t,n){let r={...e,projectId:t,timestamp:Date.now(),...n!=null&&{commitId:n}},i=this.bufferKey(t,n),a=this.buffers.get(i);a||(a=[],this.buffers.set(i,a),this.bufferMeta.set(i,{projectId:t,commitId:n})),a.push(r);let o=this.timers.get(i);o&&clearTimeout(o),this.timers.set(i,setTimeout(()=>{this.flushAsync(t,n).catch(e=>console.error(`[wdyr-mcp] flush error for ${i}:`,e))},200))}async flushAsync(e,t){await w(),this.flush(e,t)}flush(e,t){if(e!=null&&t!==void 0)this.flushBuffer(this.bufferKey(e,t));else if(e!=null)for(let t of this.bufferKeysForProject(e))this.flushBuffer(t);else for(let e of[...this.buffers.keys()])this.flushBuffer(e)}flushBuffer(e){let t=this.buffers.get(e);if(!t||t.length===0)return;let n=this.bufferMeta.get(e);if(!n)return;let r=this.dicts.get(e);r||(r={},this.dicts.set(e,r));let i=t.map(e=>ne(e,r)),a=this.commitFile(n.projectId,n.commitId),o=this.readDataLines(a),s=i.map(e=>JSON.stringify(e)),c=[...o,...s];l(a,`${(Object.keys(r).length>0?[JSON.stringify({[b]:r}),...c]:c).join(`
2
+ import{McpServer as e}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as t}from"@modelcontextprotocol/sdk/server/stdio.js";import{io as n}from"socket.io-client";import{z as r}from"zod";import{existsSync as i,mkdirSync as a,readFileSync as o,readdirSync as s,unlinkSync as c,writeFileSync as l}from"node:fs";import{homedir as u}from"node:os";import{join as d}from"node:path";import f from"xxhash-wasm";import p from"node:http";import{Server as ee}from"socket.io";let m=null,h=4649;function te(e){h=e}function g(){return m||=n(`http://127.0.0.1:${h}`,{transports:[`websocket`],reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:3}),m}function _(e){g().emit(`relay-pause`,e)}function ne(e){g().emit(`relay-resume`,e)}function re(){m&&=(m.close(),null)}const v=`@@dict`,y=`@@ref:`;let b;const ie=f().then(e=>{b=e.h64ToString});function ae(){return ie}function x(e){return b(JSON.stringify(e))}function S(e){return typeof e==`object`&&!!e}function C(e,t){return e?e.map(e=>{let{prevValue:n,nextValue:r}=e;if(S(n)){let e=x(n);t[e]??=n,n=`${y}${e}`}if(S(r)){let e=x(r);t[e]??=r,r=`${y}${e}`}return n===e.prevValue&&r===e.nextValue?e:{...e,prevValue:n,nextValue:r}}):!1}function oe(e,t){let{propsDifferences:n,stateDifferences:r,hookDifferences:i}=e.reason,a=C(n,t),o=C(r,t),s=C(i,t);return a===n&&o===r&&s===i?e:{...e,reason:{propsDifferences:a,stateDifferences:o,hookDifferences:s}}}function w(e,t){return e?e.map(e=>{let{prevValue:n,nextValue:r}=e;return typeof n==`string`&&n.startsWith(y)&&(n=t[n.slice(6)]??n),typeof r==`string`&&r.startsWith(y)&&(r=t[r.slice(6)]??r),n===e.prevValue&&r===e.nextValue?e:{...e,prevValue:n,nextValue:r}}):!1}function T(e,t){let{propsDifferences:n,stateDifferences:r,hookDifferences:i}=e.reason,a=w(n,t),o=w(r,t),s=w(i,t);return a===n&&o===r&&s===i?e:{...e,reason:{propsDifferences:a,stateDifferences:o,hookDifferences:s}}}function E(e){if(!i(e))return[];let t=o(e,`utf-8`).split(`
3
+ `).filter(Boolean);if(t.length===0)return[];let n,r=0,a=JSON.parse(t[0]);`@@dict`in a&&(n=a[v],r=1);let s=t.slice(r).map(e=>JSON.parse(e));return n?s.map(e=>T(e,n)):s}function D(e){return e.replaceAll(/[^a-zA-Z0-9_.-]/g,`_`)}function O(e){return{project:e.projectId,displayName:e.displayName,reason:e.reason,...e.hookName!=null&&{hookName:e.hookName},...e.commitId!=null&&{commitId:e.commitId},...e.timestamp!=null&&{timestamp:e.timestamp},...e.stackFrames!=null&&e.stackFrames.length>0&&{stackFrames:e.stackFrames}}}const k=`nocommit`,A=new class{dir;snapshotsDir;buffers=new Map;timers=new Map;dicts=new Map;bufferMeta=new Map;trackedComponents=new Map;wdyrConfigs=new Map;constructor(e){this.dir=e??d(u(),`.wdyr-mcp`,`renders`),this.snapshotsDir=d(u(),`.wdyr-mcp`,`snapshots`),a(this.dir,{recursive:!0})}addRender(e,t,n){let r={...e,projectId:t,timestamp:Date.now(),...n!=null&&{commitId:n}},i=this.bufferKey(t,n),a=this.buffers.get(i);a||(a=[],this.buffers.set(i,a),this.bufferMeta.set(i,{projectId:t,commitId:n})),a.push(r);let o=this.timers.get(i);o&&clearTimeout(o),this.timers.set(i,setTimeout(()=>{this.flushAsync(t,n).catch(e=>console.error(`[wdyr-mcp] flush error for ${i}:`,e))},200))}async flushAsync(e,t){await ae(),this.flush(e,t)}flush(e,t){if(e!=null&&t!==void 0)this.flushBuffer(this.bufferKey(e,t));else if(e!=null)for(let t of this.bufferKeysForProject(e))this.flushBuffer(t);else for(let e of[...this.buffers.keys()])this.flushBuffer(e)}flushBuffer(e){let t=this.buffers.get(e);if(!t||t.length===0)return;let n=this.bufferMeta.get(e);if(!n)return;let r=this.dicts.get(e);r||(r={},this.dicts.set(e,r));let i=t.map(e=>oe(e,r)),a=this.commitFile(n.projectId,n.commitId),o=this.readDataLines(a),s=i.map(e=>JSON.stringify(e)),c=[...o,...s];l(a,`${(Object.keys(r).length>0?[JSON.stringify({[v]:r}),...c]:c).join(`
4
4
  `)}\n`),t.length=0;let u=this.timers.get(e);u&&(clearTimeout(u),this.timers.delete(e))}readDataLines(e){return i(e)?o(e,`utf-8`).split(`
5
- `).filter(e=>!(!e||e.startsWith(`{"@@dict"`))):[]}getAllRenders(e){return this.flush(e),e?this.projectFiles(e).flatMap(e=>A(d(this.dir,e)).map(M)):this.jsonlFiles().flatMap(e=>A(d(this.dir,e)).map(M))}getRendersByComponent(e,t){return this.getAllRenders(t).filter(t=>t.displayName===e)}clearRenders(e){if(e){for(let t of this.bufferKeysForProject(e)){this.buffers.delete(t),this.dicts.delete(t),this.bufferMeta.delete(t);let e=this.timers.get(t);e&&(clearTimeout(e),this.timers.delete(t))}for(let t of this.projectFiles(e))c(d(this.dir,t))}else{for(let[,e]of this.timers)clearTimeout(e);this.buffers.clear(),this.timers.clear(),this.dicts.clear(),this.bufferMeta.clear();for(let e of this.jsonlFiles())c(d(this.dir,e))}}clearRendersByComponent(e,t){this.flush(t);let n=t?this.projectFiles(t):this.jsonlFiles(),r=0;for(let t of n){let n=d(this.dir,t),i=A(n),a=i.length,o=i.filter(t=>t.displayName!==e);r+=a-o.length,o.length===0?(c(n),this.clearBuffersForFile(t)):o.length<a&&(this.rewriteFile(n,o),this.clearBuffersForFile(t))}return r}clearRendersByCommit(e,t){this.flush(t);let n=t?this.projectFiles(t):this.jsonlFiles(),r=0;for(let t of n){let n=this.parseFilename(t);n?.commitId!=null&&n.commitId<e&&(c(d(this.dir,t)),this.clearBuffersForFile(t),r++)}return r}getProjects(){this.flush();let e=new Set,t=new Set;for(let n of this.jsonlFiles()){let r=this.parseFilename(n);if(!r||t.has(r.projectSanitized))continue;t.add(r.projectSanitized);let i=o(d(this.dir,n),`utf-8`).split(`
6
- `);for(let t of i){if(!t)continue;let n=JSON.parse(t);if(!(`@@dict`in n)){e.add(n.projectId);break}}}return[...e]}getCommitIds(e){this.flush(e);let t=e?this.projectFiles(e):this.jsonlFiles(),n=new Set;for(let e of t){let t=this.parseFilename(e);t?.commitId!=null&&n.add(t.commitId)}return[...n].sort((e,t)=>e-t)}getCommits(e){this.flush(e);let t=e?this.projectFiles(e):this.jsonlFiles(),n=[];for(let e of t){let t=this.parseFilename(e);if(t?.commitId==null)continue;let r=A(d(this.dir,e));r.length!==0&&n.push({commitId:t.commitId,timestamp:r.find(e=>e.timestamp!=null)?.timestamp??null,renderCount:r.length,components:[...new Set(r.map(e=>e.displayName))]})}return n.sort((e,t)=>e.commitId-t.commitId)}getRendersByCommit(e,t){if(t)return this.flush(t,e),A(this.commitFile(t,e)).map(M);this.flush();let n=`_commit_${e}.jsonl`;return this.jsonlFiles().filter(e=>e.endsWith(n)).flatMap(e=>A(d(this.dir,e)).map(M))}getSummary(e){let t=this.getAllRenders(e),n={};for(let e of t){n[e.project]??={};let t=n[e.project];t[e.displayName]??={count:0,reasons:{props:0,state:0,hooks:0}};let r=t[e.displayName];r.count++,Array.isArray(e.reason.propsDifferences)&&r.reasons.props++,Array.isArray(e.reason.stateDifferences)&&r.reasons.state++,Array.isArray(e.reason.hookDifferences)&&r.reasons.hooks++,typeof e.actualDuration==`number`&&(r.totalDuration=(r.totalDuration??0)+e.actualDuration)}return n}getSummaryByCommit(e){let t=this.getAllRenders(e),n={};for(let e of t){if(e.commitId==null)continue;n[e.project]??={},n[e.project][e.commitId]??={};let t=n[e.project][e.commitId];t[e.displayName]??={count:0,reasons:{props:0,state:0,hooks:0}};let r=t[e.displayName];r.count++,Array.isArray(e.reason.propsDifferences)&&r.reasons.props++,Array.isArray(e.reason.stateDifferences)&&r.reasons.state++,Array.isArray(e.reason.hookDifferences)&&r.reasons.hooks++,typeof e.actualDuration==`number`&&(r.totalDuration=(r.totalDuration??0)+e.actualDuration)}return n}setTrackedComponents(e,t){this.trackedComponents.set(t,e)}getTrackedComponents(e){let t={},n=e?[e]:this.getProjects();for(let e of n){let n=[...new Set(this.getAllRenders(e).map(e=>e.displayName))];t[e]={registered:this.trackedComponents.get(e)??[],observed:n}}return t}setWdyrConfig(e,t){this.wdyrConfigs.set(t,e)}getWdyrConfig(e){let t={};if(e){let n=this.wdyrConfigs.get(e);n&&(t[e]=n)}else for(let[e,n]of this.wdyrConfigs)t[e]=n;return t}rewriteFile(e,t){l(e,`${t.map(e=>JSON.stringify(e)).join(`
7
- `)}\n`)}clearBuffersForFile(e){let t=this.parseFilename(e);if(t)for(let[e,n]of this.bufferMeta){if(j(n.projectId)!==t.projectSanitized||!(t.commitId==null?n.commitId==null:n.commitId===t.commitId))continue;this.buffers.delete(e),this.dicts.delete(e),this.bufferMeta.delete(e);let r=this.timers.get(e);r&&(clearTimeout(r),this.timers.delete(e))}}bufferKey(e,t){return`${e}\0${t??N}`}bufferKeysForProject(e){let t=`${e}\0`;return[...this.buffers.keys()].filter(e=>e.startsWith(t))}commitFile(e,t){let n=j(e),r=t==null?`_${N}`:`_commit_${t}`;return d(this.dir,`${n}${r}.jsonl`)}projectFiles(e){let t=j(e);return s(this.dir).filter(e=>e.startsWith(t)&&e.endsWith(`.jsonl`))}parseFilename(e){if(!e.endsWith(`.jsonl`))return null;let t=e.slice(0,-6),n=t.match(/^(.+)_commit_(\d+)$/);if(n)return{projectSanitized:n[1],commitId:Number(n[2])};let r=t.match(/^(.+)_nocommit$/);return r?{projectSanitized:r[1]}:{projectSanitized:t}}jsonlFiles(){return s(this.dir).filter(e=>e.endsWith(`.jsonl`))}};function F(e){if(e)return{projectId:e};let t=P.getProjects();return t.length===0?{projectId:void 0}:t.length===1?{projectId:t[0]}:{projectId:void 0,error:[`Multiple projects are recording render data. Ask the user which project they are working on (e.g. their dev server URL like http://localhost:3000).`,``,`Active projects:`,...t.map(e=>`- ${e}`)].join(`
8
- `)}}function I(e){return{content:[{type:`text`,text:e}]}}function L(e){e.registerTool(`clear_renders`,{title:`Clear Renders`,description:`Clears collected render data. Supports filtering by component name or by commit ID threshold. When no filter is given, clears all data. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`),component:r.string().optional().describe(`Clear only renders for this component (by displayName).`),beforeCommit:r.number().optional().describe(`Clear all renders from commits with an ID strictly less than this value.`)}},async({project:e,component:t,beforeCommit:n})=>{let r=F(e);return r.error?I(r.error):t?I(`Cleared ${P.clearRendersByComponent(t,r.projectId)} render(s) for component "${t}".`):n==null?(P.clearRenders(r.projectId),I(r.projectId?`Render data cleared for ${r.projectId}.`:`All render data cleared.`)):I(`Cleared renders from ${P.clearRendersByCommit(n,r.projectId)} commit file(s) before commit #${n}.`)})}function R(e){e.registerTool(`get_commits`,{title:`Get Commits`,description:`Returns a list of React commit IDs that have recorded render data for a project. Use these IDs with get_renders_by_commit to inspect individual commits.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=F(e);if(t.error)return I(t.error);let n=P.getCommits(t.projectId);return n.length===0?I(`No commits recorded yet. Make sure the browser is connected and triggering re-renders.`):I(JSON.stringify(n,null,2))})}function z(e){e.registerTool(`get_projects`,{title:`Get Projects`,description:`Returns a list of project identifiers (browser origin URLs) that have recorded render data.`,inputSchema:{}},async()=>{let e=P.getProjects();return e.length===0?I(`No projects have recorded render data yet.`):I(`Active projects:\n${e.map(e=>`- ${e}`).join(`
9
- `)}`)})}function B(e){e.registerTool(`get_render_summary`,{title:`Get Render Summary`,description:`Returns a summary of re-renders grouped by component name with counts. Use groupBy: 'commit' to get per-commit breakdowns instead of a single aggregate. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`),groupBy:r.enum([`commit`]).optional().describe(`Group results by commit. When set to 'commit', returns per-commit render summaries instead of a single aggregate.`)}},async({project:e,groupBy:t})=>{let n=F(e);return n.error?I(n.error):t===`commit`?W(n.projectId):U(n.projectId)})}function V(e){return e==null?``:` (${e.toFixed(1)}ms)`}function H(e){let t=[];return e.props>0&&t.push(`props: ${e.props}`),e.state>0&&t.push(`state: ${e.state}`),e.hooks>0&&t.push(`hooks: ${e.hooks}`),t.length>0?` ${t.join(`, `)}`:``}function U(e){let t=P.getSummary(e);if(Object.keys(t).length===0)return I(`No renders recorded yet.`);let n=[];for(let[e,r]of Object.entries(t)){n.push(`[${e}]`);for(let[e,{count:t,reasons:i,totalDuration:a}]of Object.entries(r))n.push(` ${e}: ${t} re-render(s)${H(i)}${V(a)}`)}return I(`Re-render summary:\n\n${n.join(`
10
- `)}`)}function W(e){let t=P.getSummaryByCommit(e);if(Object.keys(t).length===0)return I(`No renders with commit IDs recorded yet.`);let n=[];for(let[e,r]of Object.entries(t)){n.push(`[${e}]`);let t=Object.keys(r).map(Number).sort((e,t)=>e-t);for(let e of t){let t=r[e],i=Object.values(t).reduce((e,t)=>e+t.count,0);n.push(` Commit #${e} (${i} re-render(s)):`);for(let[e,{count:r,reasons:i,totalDuration:a}]of Object.entries(t))n.push(` ${e}: ${r}${H(i)}${V(a)}`)}}return I(`Re-render summary (by commit):\n\n${n.join(`
11
- `)}`)}function G(e){e.registerTool(`get_renders_by_commit`,{title:`Get Renders by Commit`,description:`Returns all re-renders for a specific React commit ID, including stack traces that show the hook chain and component tree that triggered each render. Use the stackFrames field to locate the exact source file and line. Use get_commits first to discover available commit IDs.`,inputSchema:{commitId:r.number().describe(`The React commit ID to filter by.`),component:r.string().optional().describe(`Filter by component name. Omit to get all renders.`),project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({commitId:e,component:t,project:n})=>{let r=F(n);if(r.error)return I(r.error);let i=P.getRendersByCommit(e,r.projectId);return t&&(i=i.filter(e=>e.displayName===t)),i.length===0?I(t?`No renders recorded for component "${t}" in commit ${e}.`:`No renders recorded for commit ${e}.`):I(JSON.stringify(i,null,2))})}function K(e){e.registerTool(`get_renders`,{title:`Get Renders`,description:`Returns all re-renders collected from the browser, including stack traces that show the hook chain and component tree that triggered each render. Use the stackFrames field to locate the exact source file and line. If multiple projects are active and no project is specified, the tool will ask you to disambiguate by asking the user for their dev server URL.`,inputSchema:{component:r.string().optional().describe(`Filter by component name. Omit to get all renders.`),project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({component:e,project:t})=>{let n=F(t);if(n.error)return I(n.error);let r=e?P.getRendersByComponent(e,n.projectId):P.getAllRenders(n.projectId);return r.length===0?I(e?`No renders recorded for "${e}".`:`No renders recorded yet. Make sure the browser is connected and triggering re-renders.`):I(JSON.stringify(r,null,2))})}function q(e){let t=[];if(e.include?.length){t.push(` include:`);for(let n of e.include)t.push(` - /${n}/`)}if(e.exclude?.length){t.push(` exclude:`);for(let n of e.exclude)t.push(` - /${n}/`)}if(e.trackAllPureComponents!=null&&t.push(` trackAllPureComponents: ${e.trackAllPureComponents}`),e.trackHooks!=null&&t.push(` trackHooks: ${e.trackHooks}`),e.trackExtraHooks?.length){t.push(` trackExtraHooks:`);for(let n of e.trackExtraHooks)t.push(` - ${n}`)}return e.logOnDifferentValues!=null&&t.push(` logOnDifferentValues: ${e.logOnDifferentValues}`),e.logOwnerReasons!=null&&t.push(` logOwnerReasons: ${e.logOwnerReasons}`),t}function J(e){e.registerTool(`get_tracked_components`,{title:`Get Tracked Components`,description:`Returns the why-did-you-render configuration for the connected project, including include/exclude filters and tracking options. Also shows components observed in render data. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=F(e);if(t.error)return I(t.error);let n=P.getWdyrConfig(t.projectId),r=P.getTrackedComponents(t.projectId),i=Object.keys(n).length>0,a=Object.keys(r).length>0;if(!i&&!a)return I(`No configuration or tracked components found. Make sure the browser is connected and triggering re-renders.`);let o=[],s=new Set([...Object.keys(n),...Object.keys(r)]);for(let e of s){o.push(`[${e}]`);let t=n[e];if(t){o.push(`Configuration:`);let e=q(t);e.length>0?o.push(...e):o.push(` (default options)`)}let i=r[e];if(i?.observed.length){o.push(`Observed in renders:`);for(let e of i.observed)o.push(` - ${e}`)}}return I(o.join(`
12
- `))})}let Y=null;function X(e){Y=e}function Z(){return Y}function re(e){e.registerTool(`pause_renders`,{title:`Pause Render Collection`,description:`Pauses render data collection in the browser. Connected clients will stop reporting renders until resume_renders is called. Useful when you want to ignore renders from irrelevant interactions. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=F(e);if(t.error)return I(t.error);let n=Z();if(!n)return _(t.projectId??void 0),I(`Paused render collection for ${t.projectId??`all projects`} (relayed via WS owner).`);if(t.projectId){let e=await n.fetchSockets();for(let n of e)n.data.projectId===t.projectId&&n.emit(`pause`);return I(`Paused render collection for ${t.projectId}.`)}return n.emit(`pause`),I(`Paused render collection for all projects.`)})}function ie(e){e.registerTool(`resume_renders`,{title:`Resume Render Collection`,description:`Resumes render data collection that was previously paused with pause_renders. Connected clients will start reporting renders again. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=F(e);if(t.error)return I(t.error);let n=Z();if(!n)return v(t.projectId??void 0),I(`Resumed render collection for ${t.projectId??`all projects`} (relayed via WS owner).`);if(t.projectId){let e=await n.fetchSockets();for(let n of e)n.data.projectId===t.projectId&&n.emit(`resume`);return I(`Resumed render collection for ${t.projectId}.`)}return n.emit(`resume`),I(`Resumed render collection for all projects.`)})}function ae(e){K(e),B(e),R(e),G(e),z(e),J(e),L(e),re(e),ie(e)}const Q=3e3;function oe(e,t){e.on(`connection`,n=>{console.error(`[wdyr-mcp] browser connected (http://localhost:${t})`),n.data.projectId=null,n.on(`render`,(e,t,r)=>{n.data.projectId=t,P.addRender(e,t,r)}),n.on(`render-batch`,(e,t,r)=>{n.data.projectId=t;for(let n of e)P.addRender(n,t,r)}),n.on(`register`,(e,t)=>{n.data.projectId=t,P.setTrackedComponents(e,t)}),n.on(`config`,(e,t)=>{n.data.projectId=t,P.setWdyrConfig(e,t)}),n.on(`relay-pause`,async t=>{if(t){let n=await e.fetchSockets();for(let e of n)e.data.projectId===t&&e.emit(`pause`)}else e.emit(`pause`)}),n.on(`relay-resume`,async t=>{if(t){let n=await e.fetchSockets();for(let e of n)e.data.projectId===t&&e.emit(`resume`)}else e.emit(`resume`)}),n.on(`disconnect`,()=>{console.error(`[wdyr-mcp] browser disconnected`);let t=n.data.projectId;t&&([...e.sockets.sockets.values()].some(e=>e.id!==n.id&&e.data.projectId===t)||(console.error(`[wdyr-mcp] last client for ${t} disconnected, clearing render data`),P.clearRenders(t)))})})}function se(e){let t=null,n=null,r=null,i=!1;function a(){i||(r=f.createServer(),n=new te(r,{cors:{origin:`*`},serveClient:!1,transports:[`websocket`],maxHttpBufferSize:5e7}),oe(n,e),r.once(`error`,t=>{t.code===`EADDRINUSE`?(console.error(`[wdyr-mcp] Port ${e} in use, will retry every ${Q/1e3}s`),n?.close(),n=null,X(null),r=null,o()):console.error(`[wdyr-mcp] server error:`,t)}),r.listen(e,`127.0.0.1`,()=>{console.error(`[wdyr-mcp] socket.io server listening on http://localhost:${e}`),X(n),s()}))}function o(){t||i||(t=setInterval(a,Q))}function s(){t&&=(clearInterval(t),null)}return a(),{close(){i=!0,s(),n?.close(),X(null)}}}const $=new e({name:`why-did-you-render`,version:`0.0.0`});ae($);async function ce(){let e=Number(process.env.WDYR_WS_PORT)||4649;h(e);let n=se(e),r=new t;await $.connect(r),console.error(`[wdyr-mcp] MCP server running on stdio`);let i=!1;async function a(){i||(i=!0,console.error(`[wdyr-mcp] Shutting down…`),y(),n.close(),await $.close(),process.exit(0))}process.stdin.on(`end`,a),process.on(`SIGTERM`,a),process.on(`SIGINT`,a)}ce().catch(e=>{console.error(`[wdyr-mcp] Fatal error:`,e),process.exit(1)});export{};
5
+ `).filter(e=>!(!e||e.startsWith(`{"@@dict"`))):[]}getAllRenders(e){return this.flush(e),e?this.projectFiles(e).flatMap(e=>E(d(this.dir,e)).map(O)):this.jsonlFiles().flatMap(e=>E(d(this.dir,e)).map(O))}getRendersByComponent(e,t){return this.getAllRenders(t).filter(t=>t.displayName===e)}clearRenders(e){if(e){for(let t of this.bufferKeysForProject(e)){this.buffers.delete(t),this.dicts.delete(t),this.bufferMeta.delete(t);let e=this.timers.get(t);e&&(clearTimeout(e),this.timers.delete(t))}for(let t of this.projectFiles(e))c(d(this.dir,t))}else{for(let[,e]of this.timers)clearTimeout(e);this.buffers.clear(),this.timers.clear(),this.dicts.clear(),this.bufferMeta.clear();for(let e of this.jsonlFiles())c(d(this.dir,e))}}clearRendersByComponent(e,t){this.flush(t);let n=t?this.projectFiles(t):this.jsonlFiles(),r=0;for(let t of n){let n=d(this.dir,t),i=E(n),a=i.length,o=i.filter(t=>t.displayName!==e);r+=a-o.length,o.length===0?(c(n),this.clearBuffersForFile(t)):o.length<a&&(this.rewriteFile(n,o),this.clearBuffersForFile(t))}return r}clearRendersByCommit(e,t){this.flush(t);let n=t?this.projectFiles(t):this.jsonlFiles(),r=0;for(let t of n){let n=this.parseFilename(t);n?.commitId!=null&&n.commitId<e&&(c(d(this.dir,t)),this.clearBuffersForFile(t),r++)}return r}getProjects(){this.flush();let e=new Set,t=new Set;for(let n of this.jsonlFiles()){let r=this.parseFilename(n);if(!r||t.has(r.projectSanitized))continue;t.add(r.projectSanitized);let i=o(d(this.dir,n),`utf-8`).split(`
6
+ `);for(let t of i){if(!t)continue;let n=JSON.parse(t);if(!(`@@dict`in n)){e.add(n.projectId);break}}}return[...e]}getCommitIds(e){this.flush(e);let t=e?this.projectFiles(e):this.jsonlFiles(),n=new Set;for(let e of t){let t=this.parseFilename(e);t?.commitId!=null&&n.add(t.commitId)}return[...n].sort((e,t)=>e-t)}getCommits(e){this.flush(e);let t=e?this.projectFiles(e):this.jsonlFiles(),n=[];for(let e of t){let t=this.parseFilename(e);if(t?.commitId==null)continue;let r=E(d(this.dir,e));r.length!==0&&n.push({commitId:t.commitId,timestamp:r.find(e=>e.timestamp!=null)?.timestamp??null,renderCount:r.length,components:[...new Set(r.map(e=>e.displayName))]})}return n.sort((e,t)=>e.commitId-t.commitId)}getRendersByCommit(e,t){if(t)return this.flush(t,e),E(this.commitFile(t,e)).map(O);this.flush();let n=`_commit_${e}.jsonl`;return this.jsonlFiles().filter(e=>e.endsWith(n)).flatMap(e=>E(d(this.dir,e)).map(O))}getSummary(e){let t=this.getAllRenders(e),n={};for(let e of t){n[e.project]??={};let t=n[e.project];t[e.displayName]??={count:0,reasons:{props:0,state:0,hooks:0}};let r=t[e.displayName];r.count++,Array.isArray(e.reason.propsDifferences)&&r.reasons.props++,Array.isArray(e.reason.stateDifferences)&&r.reasons.state++,Array.isArray(e.reason.hookDifferences)&&r.reasons.hooks++,typeof e.actualDuration==`number`&&(r.totalDuration=(r.totalDuration??0)+e.actualDuration)}return n}getSummaryByCommit(e){let t=this.getAllRenders(e),n={};for(let e of t){if(e.commitId==null)continue;n[e.project]??={},n[e.project][e.commitId]??={};let t=n[e.project][e.commitId];t[e.displayName]??={count:0,reasons:{props:0,state:0,hooks:0}};let r=t[e.displayName];r.count++,Array.isArray(e.reason.propsDifferences)&&r.reasons.props++,Array.isArray(e.reason.stateDifferences)&&r.reasons.state++,Array.isArray(e.reason.hookDifferences)&&r.reasons.hooks++,typeof e.actualDuration==`number`&&(r.totalDuration=(r.totalDuration??0)+e.actualDuration)}return n}setTrackedComponents(e,t){this.trackedComponents.set(t,e)}getTrackedComponents(e){let t={},n=e?[e]:this.getProjects();for(let e of n){let n=[...new Set(this.getAllRenders(e).map(e=>e.displayName))];t[e]={registered:this.trackedComponents.get(e)??[],observed:n}}return t}setWdyrConfig(e,t){this.wdyrConfigs.set(t,e)}getWdyrConfig(e){let t={};if(e){let n=this.wdyrConfigs.get(e);n&&(t[e]=n)}else for(let[e,n]of this.wdyrConfigs)t[e]=n;return t}saveSnapshot(e,t){a(this.snapshotsDir,{recursive:!0});let n={name:e,timestamp:Date.now(),data:this.getSummary(t)};l(d(this.snapshotsDir,`${e}.json`),JSON.stringify(n,null,2))}listSnapshots(){return i(this.snapshotsDir)?s(this.snapshotsDir).filter(e=>e.endsWith(`.json`)).map(e=>{let t=o(d(this.snapshotsDir,e),`utf-8`),n=JSON.parse(t);return{name:n.name,timestamp:n.timestamp}}):[]}getSnapshot(e){let t=d(this.snapshotsDir,`${e}.json`);return i(t)?JSON.parse(o(t,`utf-8`)):null}deleteSnapshot(e){let t=d(this.snapshotsDir,`${e}.json`);return i(t)?(c(t),!0):!1}rewriteFile(e,t){l(e,`${t.map(e=>JSON.stringify(e)).join(`
7
+ `)}\n`)}clearBuffersForFile(e){let t=this.parseFilename(e);if(t)for(let[e,n]of this.bufferMeta){if(D(n.projectId)!==t.projectSanitized||!(t.commitId==null?n.commitId==null:n.commitId===t.commitId))continue;this.buffers.delete(e),this.dicts.delete(e),this.bufferMeta.delete(e);let r=this.timers.get(e);r&&(clearTimeout(r),this.timers.delete(e))}}bufferKey(e,t){return`${e}\0${t??k}`}bufferKeysForProject(e){let t=`${e}\0`;return[...this.buffers.keys()].filter(e=>e.startsWith(t))}commitFile(e,t){let n=D(e),r=t==null?`_${k}`:`_commit_${t}`;return d(this.dir,`${n}${r}.jsonl`)}projectFiles(e){let t=D(e);return s(this.dir).filter(e=>e.startsWith(t)&&e.endsWith(`.jsonl`))}parseFilename(e){if(!e.endsWith(`.jsonl`))return null;let t=e.slice(0,-6),n=t.match(/^(.+)_commit_(\d+)$/);if(n)return{projectSanitized:n[1],commitId:Number(n[2])};let r=t.match(/^(.+)_nocommit$/);return r?{projectSanitized:r[1]}:{projectSanitized:t}}jsonlFiles(){return s(this.dir).filter(e=>e.endsWith(`.jsonl`))}};function j(e){if(e)return{projectId:e};let t=A.getProjects();return t.length===0?{projectId:void 0}:t.length===1?{projectId:t[0]}:{projectId:void 0,error:[`Multiple projects are recording render data. Ask the user which project they are working on (e.g. their dev server URL like http://localhost:3000).`,``,`Active projects:`,...t.map(e=>`- ${e}`)].join(`
8
+ `)}}function M(e){return{content:[{type:`text`,text:e}]}}function se(e){e.registerTool(`clear_renders`,{title:`Clear Renders`,description:`Clears collected render data. Supports filtering by component name or by commit ID threshold. When no filter is given, clears all data. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`),component:r.string().optional().describe(`Clear only renders for this component (by displayName).`),beforeCommit:r.number().optional().describe(`Clear all renders from commits with an ID strictly less than this value.`)}},async({project:e,component:t,beforeCommit:n})=>{let r=j(e);return r.error?M(r.error):t?M(`Cleared ${A.clearRendersByComponent(t,r.projectId)} render(s) for component "${t}".`):n==null?(A.clearRenders(r.projectId),M(r.projectId?`Render data cleared for ${r.projectId}.`:`All render data cleared.`)):M(`Cleared renders from ${A.clearRendersByCommit(n,r.projectId)} commit file(s) before commit #${n}.`)})}function ce(e){e.registerTool(`compare_snapshots`,{title:`Compare Snapshots`,description:`Compares two saved render snapshots and shows per-component render count changes.`,inputSchema:{before:r.string().describe(`The name of the baseline snapshot.`),after:r.string().describe(`The name of the snapshot to compare against the baseline.`)}},async({before:e,after:t})=>{let n=A.getSnapshot(e);if(!n)return M(`Snapshot "${e}" not found.`);let r=A.getSnapshot(t);if(!r)return M(`Snapshot "${t}" not found.`);let i=new Set([...Object.keys(n.data),...Object.keys(r.data)]);if(i.size===0)return M(`Both snapshots are empty.`);let a=[],o=0,s=0,c=0,l=0,u=!1;for(let e of[...i].sort()){a.push(`[${e}]`);let t=n.data[e]??{},i=r.data[e]??{},d=new Set([...Object.keys(t),...Object.keys(i)]);for(let e of[...d].sort()){let n=t[e],r=i[e],d=n?.count??0,f=r?.count??0;o+=d,s+=f;let p=``;if(n?.totalDuration!=null||r?.totalDuration!=null){u=!0;let e=n?.totalDuration??0,t=r?.totalDuration??0;c+=e,l+=t,p=` [${e.toFixed(1)}ms ${t.toFixed(1)}ms]`}a.push(` ${e}: ${d} ${f} (${N(d,f)})${p}`)}}a.push(``);let d=`Total: ${o} ${s} (${N(o,s)})`;return u&&(d+=` [${c.toFixed(1)}ms ${l.toFixed(1)}ms]`),a.push(d),M(`Snapshot comparison: "${e}" → "${t}"\n\n${a.join(`
9
+ `)}`)})}function N(e,t){if(e===0&&t===0)return`no change`;if(e===0)return`new`;if(t===0)return`removed`;if(e===t)return`no change`;let n=((t-e)/e*100).toFixed(1);return`${Number(n)>0?`+`:``}${n}%`}function le(e){e.registerTool(`delete_snapshot`,{title:`Delete Snapshot`,description:`Deletes a saved render snapshot by name.`,inputSchema:{name:r.string().describe(`The name of the snapshot to delete.`)}},async({name:e})=>A.deleteSnapshot(e)?M(`Snapshot "${e}" deleted.`):M(`Snapshot "${e}" not found.`))}function P(e){e.registerTool(`get_commits`,{title:`Get Commits`,description:`Returns a list of React commit IDs that have recorded render data for a project. Use these IDs with get_renders_by_commit to inspect individual commits.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=j(e);if(t.error)return M(t.error);let n=A.getCommits(t.projectId);return n.length===0?M(`No commits recorded yet. Make sure the browser is connected and triggering re-renders.`):M(JSON.stringify(n,null,2))})}function F(e){e.registerTool(`get_projects`,{title:`Get Projects`,description:`Returns a list of project identifiers (browser origin URLs) that have recorded render data.`,inputSchema:{}},async()=>{let e=A.getProjects();return e.length===0?M(`No projects have recorded render data yet.`):M(`Active projects:\n${e.map(e=>`- ${e}`).join(`
10
+ `)}`)})}function I(e){e.registerTool(`get_render_summary`,{title:`Get Render Summary`,description:`Returns a summary of re-renders grouped by component name with counts. Use groupBy: 'commit' to get per-commit breakdowns instead of a single aggregate. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`),groupBy:r.enum([`commit`]).optional().describe(`Group results by commit. When set to 'commit', returns per-commit render summaries instead of a single aggregate.`)}},async({project:e,groupBy:t})=>{let n=j(e);return n.error?M(n.error):t===`commit`?B(n.projectId):z(n.projectId)})}function L(e){return e==null?``:` (${e.toFixed(1)}ms)`}function R(e){let t=[];return e.props>0&&t.push(`props: ${e.props}`),e.state>0&&t.push(`state: ${e.state}`),e.hooks>0&&t.push(`hooks: ${e.hooks}`),t.length>0?` ${t.join(`, `)}`:``}function z(e){let t=A.getSummary(e);if(Object.keys(t).length===0)return M(`No renders recorded yet.`);let n=[];for(let[e,r]of Object.entries(t)){n.push(`[${e}]`);for(let[e,{count:t,reasons:i,totalDuration:a}]of Object.entries(r))n.push(` ${e}: ${t} re-render(s)${R(i)}${L(a)}`)}return M(`Re-render summary:\n\n${n.join(`
11
+ `)}`)}function B(e){let t=A.getSummaryByCommit(e);if(Object.keys(t).length===0)return M(`No renders with commit IDs recorded yet.`);let n=[];for(let[e,r]of Object.entries(t)){n.push(`[${e}]`);let t=Object.keys(r).map(Number).sort((e,t)=>e-t);for(let e of t){let t=r[e],i=Object.values(t).reduce((e,t)=>e+t.count,0);n.push(` Commit #${e} (${i} re-render(s)):`);for(let[e,{count:r,reasons:i,totalDuration:a}]of Object.entries(t))n.push(` ${e}: ${r}${R(i)}${L(a)}`)}}return M(`Re-render summary (by commit):\n\n${n.join(`
12
+ `)}`)}function V(e){e.registerTool(`get_renders_by_commit`,{title:`Get Renders by Commit`,description:`Returns all re-renders for a specific React commit ID, including stack traces that show the hook chain and component tree that triggered each render. Use the stackFrames field to locate the exact source file and line. Use get_commits first to discover available commit IDs.`,inputSchema:{commitId:r.number().describe(`The React commit ID to filter by.`),component:r.string().optional().describe(`Filter by component name. Omit to get all renders.`),project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({commitId:e,component:t,project:n})=>{let r=j(n);if(r.error)return M(r.error);let i=A.getRendersByCommit(e,r.projectId);return t&&(i=i.filter(e=>e.displayName===t)),i.length===0?M(t?`No renders recorded for component "${t}" in commit ${e}.`:`No renders recorded for commit ${e}.`):M(JSON.stringify(i,null,2))})}function H(e){e.registerTool(`get_renders`,{title:`Get Renders`,description:`Returns all re-renders collected from the browser, including stack traces that show the hook chain and component tree that triggered each render. Use the stackFrames field to locate the exact source file and line. If multiple projects are active and no project is specified, the tool will ask you to disambiguate by asking the user for their dev server URL.`,inputSchema:{component:r.string().optional().describe(`Filter by component name. Omit to get all renders.`),project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({component:e,project:t})=>{let n=j(t);if(n.error)return M(n.error);let r=e?A.getRendersByComponent(e,n.projectId):A.getAllRenders(n.projectId);return r.length===0?M(e?`No renders recorded for "${e}".`:`No renders recorded yet. Make sure the browser is connected and triggering re-renders.`):M(JSON.stringify(r,null,2))})}function U(e){let t=[];if(e.include?.length){t.push(` include:`);for(let n of e.include)t.push(` - /${n}/`)}if(e.exclude?.length){t.push(` exclude:`);for(let n of e.exclude)t.push(` - /${n}/`)}if(e.trackAllPureComponents!=null&&t.push(` trackAllPureComponents: ${e.trackAllPureComponents}`),e.trackHooks!=null&&t.push(` trackHooks: ${e.trackHooks}`),e.trackExtraHooks?.length){t.push(` trackExtraHooks:`);for(let n of e.trackExtraHooks)t.push(` - ${n}`)}return e.logOnDifferentValues!=null&&t.push(` logOnDifferentValues: ${e.logOnDifferentValues}`),e.logOwnerReasons!=null&&t.push(` logOwnerReasons: ${e.logOwnerReasons}`),t}function ue(e){e.registerTool(`get_tracked_components`,{title:`Get Tracked Components`,description:`Returns the why-did-you-render configuration for the connected project, including include/exclude filters and tracking options. Also shows components observed in render data. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=j(e);if(t.error)return M(t.error);let n=A.getWdyrConfig(t.projectId),r=A.getTrackedComponents(t.projectId),i=Object.keys(n).length>0,a=Object.keys(r).length>0;if(!i&&!a)return M(`No configuration or tracked components found. Make sure the browser is connected and triggering re-renders.`);let o=[],s=new Set([...Object.keys(n),...Object.keys(r)]);for(let e of s){o.push(`[${e}]`);let t=n[e];if(t){o.push(`Configuration:`);let e=U(t);e.length>0?o.push(...e):o.push(` (default options)`)}let i=r[e];if(i?.observed.length){o.push(`Observed in renders:`);for(let e of i.observed)o.push(` - ${e}`)}}return M(o.join(`
13
+ `))})}function de(e){e.registerTool(`list_snapshots`,{title:`List Snapshots`,description:`Lists all saved render snapshots with their timestamps.`,inputSchema:{}},async()=>{let e=A.listSnapshots();return e.length===0?M(`No snapshots saved yet.`):M(`Saved snapshots:\n\n${e.map(e=>`- ${e.name} (${new Date(e.timestamp).toISOString()})`).join(`
14
+ `)}`)})}let W=null;function G(e){W=e}function K(){return W}const q=new Set;function fe(){return q.has(null)}function J(e){return q.has(null)||q.has(e)}function Y(e){q.add(e)}function X(e){e===null?q.clear():q.delete(e)}function pe(e){e.registerTool(`pause_renders`,{title:`Pause Render Collection`,description:`Pauses render data collection in the browser. Connected clients will stop reporting renders until resume_renders is called. Useful when you want to ignore renders from irrelevant interactions. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=j(e);if(t.error)return M(t.error);Y(t.projectId??null);let n=K();if(!n)return _(t.projectId??void 0),M(`Paused render collection for ${t.projectId??`all projects`} (relayed via WS owner).`);if(t.projectId){let e=await n.fetchSockets();for(let n of e)n.data.projectId===t.projectId&&n.emit(`pause`);return M(`Paused render collection for ${t.projectId}.`)}return n.emit(`pause`),M(`Paused render collection for all projects.`)})}function me(e){e.registerTool(`resume_renders`,{title:`Resume Render Collection`,description:`Resumes render data collection that was previously paused with pause_renders. Connected clients will start reporting renders again. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=j(e);if(t.error)return M(t.error);X(t.projectId??null);let n=K();if(!n)return ne(t.projectId??void 0),M(`Resumed render collection for ${t.projectId??`all projects`} (relayed via WS owner).`);if(t.projectId){let e=await n.fetchSockets();for(let n of e)n.data.projectId===t.projectId&&n.emit(`resume`);return M(`Resumed render collection for ${t.projectId}.`)}return n.emit(`resume`),M(`Resumed render collection for all projects.`)})}function he(e){e.registerTool(`save_snapshot`,{title:`Save Snapshot`,description:`Saves the current render summary as a named snapshot for later comparison. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{name:r.string().describe(`A name for this snapshot (used to reference it later).`),project:r.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({name:e,project:t})=>{let n=j(t);return n.error?M(n.error):(A.saveSnapshot(e,n.projectId),M(`Snapshot "${e}" saved.`))})}function ge(e){H(e),I(e),P(e),V(e),F(e),ue(e),se(e),pe(e),me(e),he(e),de(e),ce(e),le(e)}const Z=3e3;function _e(e,t){e.on(`connection`,n=>{console.error(`[wdyr-mcp] browser connected (http://localhost:${t})`),n.data.projectId=null,fe()&&n.emit(`pause`),n.on(`render`,(e,t,r)=>{n.data.projectId=t,!J(t)&&A.addRender(e,t,r)}),n.on(`render-batch`,(e,t,r)=>{if(n.data.projectId=t,!J(t))for(let n of e)A.addRender(n,t,r)}),n.on(`register`,(e,t)=>{n.data.projectId=t,A.setTrackedComponents(e,t),J(t)&&n.emit(`pause`)}),n.on(`config`,(e,t)=>{n.data.projectId=t,A.setWdyrConfig(e,t)}),n.on(`relay-pause`,async t=>{if(Y(t??null),t){let n=await e.fetchSockets();for(let e of n)e.data.projectId===t&&e.emit(`pause`)}else e.emit(`pause`)}),n.on(`relay-resume`,async t=>{if(X(t??null),t){let n=await e.fetchSockets();for(let e of n)e.data.projectId===t&&e.emit(`resume`)}else e.emit(`resume`)}),n.on(`disconnect`,()=>{console.error(`[wdyr-mcp] browser disconnected`);let t=n.data.projectId;t&&([...e.sockets.sockets.values()].some(e=>e.id!==n.id&&e.data.projectId===t)||(console.error(`[wdyr-mcp] last client for ${t} disconnected, clearing render data`),A.clearRenders(t)))})})}function Q(e){let t=null,n=null,r=null,i=!1;function a(){i||(r=p.createServer(),n=new ee(r,{cors:{origin:`*`},serveClient:!1,transports:[`websocket`],maxHttpBufferSize:5e7}),_e(n,e),r.once(`error`,t=>{t.code===`EADDRINUSE`?(console.error(`[wdyr-mcp] Port ${e} in use, will retry every ${Z/1e3}s`),n?.close(),n=null,G(null),r=null,o()):console.error(`[wdyr-mcp] server error:`,t)}),r.listen(e,`127.0.0.1`,()=>{console.error(`[wdyr-mcp] socket.io server listening on http://localhost:${e}`),G(n),s()}))}function o(){t||i||(t=setInterval(a,Z))}function s(){t&&=(clearInterval(t),null)}return a(),{close(){i=!0,s(),n?.close(),G(null)}}}const $=new e({name:`why-did-you-render`,version:`0.0.0`});ge($);async function ve(){let e=Number(process.env.WDYR_WS_PORT)||4649;te(e);let n=Q(e),r=new t;await $.connect(r),console.error(`[wdyr-mcp] MCP server running on stdio`);let i=!1;async function a(){i||(i=!0,console.error(`[wdyr-mcp] Shutting down…`),re(),n.close(),await $.close(),process.exit(0))}process.stdin.on(`end`,a),process.on(`SIGTERM`,a),process.on(`SIGINT`,a)}ve().catch(e=>{console.error(`[wdyr-mcp] Fatal error:`,e),process.exit(1)});export{};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0x1f320.sh/why-did-you-render-mcp",
3
- "version": "1.1.0-dev.3",
3
+ "version": "1.1.0-dev.5",
4
4
  "type": "module",
5
5
  "description": "MCP server that collects why-did-you-render data from browser and exposes it to coding agents",
6
6
  "license": "MIT",