@wtdlee/repomap 0.11.2 → 0.11.3

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 +1 @@
1
- export{f as ALL_GRAPHQL_HOOKS,a as BaseAnalyzer,B as DataFlowAnalyzer,h as GRAPHQL_INDICATORS,d as GRAPHQL_MUTATION_HOOKS,e as GRAPHQL_OTHER_HOOKS,c as GRAPHQL_QUERY_HOOKS,A as GraphQLAnalyzer,g as HOOK_TYPE_MAP,z as PagesAnalyzer,C as RestApiAnalyzer,o as cleanOperationName,s as extractGraphQLContext,x as extractGraphQLOperationsFromFile,t as extractOperationNameFromGqlCall,u as extractOperationNameFromTemplate,q as getCalleeName,y as getHookInfoString,m as getHookType,v as hasGraphQLArgument,n as hasGraphQLIndicators,l as isGraphQLHook,j as isMutationHook,i as isQueryHook,k as isSubscriptionHook,p as parseToAst,w as resolveOperationName,r as traverseAst}from'../chunk-5PWKCCT7.js';
1
+ export{f as ALL_GRAPHQL_HOOKS,a as BaseAnalyzer,B as DataFlowAnalyzer,h as GRAPHQL_INDICATORS,d as GRAPHQL_MUTATION_HOOKS,e as GRAPHQL_OTHER_HOOKS,c as GRAPHQL_QUERY_HOOKS,A as GraphQLAnalyzer,g as HOOK_TYPE_MAP,z as PagesAnalyzer,C as RestApiAnalyzer,o as cleanOperationName,s as extractGraphQLContext,x as extractGraphQLOperationsFromFile,t as extractOperationNameFromGqlCall,u as extractOperationNameFromTemplate,q as getCalleeName,y as getHookInfoString,m as getHookType,v as hasGraphQLArgument,n as hasGraphQLIndicators,l as isGraphQLHook,j as isMutationHook,i as isQueryHook,k as isSubscriptionHook,p as parseToAst,w as resolveOperationName,r as traverseAst}from'../chunk-NFF4OUJ6.js';
@@ -1,4 +1,4 @@
1
- import {k}from'./chunk-H7VVRHQZ.js';import*as d from'fs';import*as m from'path';var c=`
1
+ import {k}from'./chunk-I7GO54AS.js';import*as d from'fs';import*as m from'path';var c=`
2
2
  <svg xmlns="http://www.w3.org/2000/svg" style="position:absolute;width:0;height:0;overflow:hidden" aria-hidden="true" focusable="false">
3
3
  <symbol id="icon-zoom-in" viewBox="0 0 24 24">
4
4
  <circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" stroke-width="2"/>
@@ -1,32 +1,32 @@
1
- import*as G from'fs';import*as x from'path';import {Parser,Language}from'web-tree-sitter';import {fileURLToPath}from'url';import {createRequire}from'module';import {glob}from'glob';import*as A from'fs/promises';var ue=createRequire(import.meta.url);var me=fileURLToPath(import.meta.url);x.dirname(me);var te=false,O=null,D=null;async function se(){if(D&&O)return D;te||(await Parser.init(),te=true),D=new Parser;let l=null;try{let e=ue.resolve("tree-sitter-wasms/package.json");l=x.join(x.dirname(e),"out/tree-sitter-ruby.wasm");}catch{let e=x.join(process.cwd(),"node_modules/tree-sitter-wasms/out/tree-sitter-ruby.wasm");G.existsSync(e)&&(l=e);}if(!l||!G.existsSync(l))throw new Error("tree-sitter-ruby.wasm not found. Please ensure tree-sitter-wasms package is installed.");return O=await Language.load(l),D.setLanguage(O),D}async function ne(l){let t=(await se()).parse(l);if(!t)throw new Error("Failed to parse Ruby code");return t}async function N(l){let e=G.readFileSync(l,"utf-8");return ne(e)}function R(l,e){let t=[];l.type===e&&t.push(l);for(let o=0;o<l.childCount;o++){let n=l.child(o);n&&t.push(...R(n,e));}return t}function L(l,e){for(let t=0;t<l.childCount;t++){let o=l.child(t);if(o&&o.type===e)return o}return null}function w(l,e){let t=[];for(let o=0;o<l.childCount;o++){let n=l.child(o);n&&n.type===e&&t.push(n);}return t}function S(l){let e=l.childForFieldName("arguments");if(!e)return [];let t=[];for(let o=0;o<e.childCount;o++){let n=e.child(o);n&&n.type!=="("&&n.type!==")"&&n.type!==","&&t.push(n);}return t}function F(l){let e=l.childForFieldName("name");return e?e.text:null}function M(l){let e=l.childForFieldName("superclass");if(!e)return null;let t=L(e,"constant")||L(e,"scope_resolution");return t?t.text:null}function U(l){let e=l.childForFieldName("name");return e?e.text:null}function Z(l){let e=l.childForFieldName("parameters");if(!e)return [];let t=[];for(let o=0;o<e.childCount;o++){let n=e.child(o);if(n&&(n.type==="identifier"||n.type==="keyword_parameter"||n.type==="optional_parameter"||n.type==="splat_parameter")){let s=n.childForFieldName("name")||n;s.type==="identifier"?t.push(s.text):t.push(n.text);}}return t}var k=class{constructor(e){this.rootPath=e;this.routesDir=x.join(e,"config","routes");}routesDir;routes=[];namespaces=[];resources=[];mountedEngines=[];drawnFiles=[];errors=[];async analyze(){let e=x.join(this.rootPath,"config","routes.rb");if(!G.existsSync(e))return {routes:[],namespaces:[],resources:[],mountedEngines:[],drawnFiles:[],errors:[`routes.rb not found at ${e}`]};try{await this.parseRoutesFile(e,[]);}catch(t){this.errors.push(`Error parsing ${e}: ${t}`);}return {routes:this.routes,namespaces:[...new Set(this.namespaces)],resources:this.resources,mountedEngines:this.mountedEngines,drawnFiles:this.drawnFiles,errors:this.errors}}async parseRoutesFile(e,t){let n=(await N(e)).rootNode,s=R(n,"call");for(let a of s){let r=a.childForFieldName("method");if(!r)continue;let c=r.text,i=a.startPosition.row+1;switch(c){case "get":case "post":case "put":case "patch":case "delete":case "match":this.parseHttpRoute(a,c,t,i);break;case "resources":case "resource":await this.parseResources(a,t,i,c==="resource");break;case "namespace":await this.parseNamespace(a,t,e);break;case "mount":this.parseMount(a,i);break;case "draw":await this.parseDraw(a,t);break;case "devise_for":this.parseDeviseFor(a,t,i);break;case "root":this.parseRoot(a,t,i);break}}}parseHttpRoute(e,t,o,n){let s=S(e);if(s.length===0)return;let a=s[0],r=this.extractStringValue(a);if(!r)return;let c="",i="";for(let p of s)if(p.type==="hash"||p.type==="pair"){let m=p.type==="hash"?w(p,"pair"):[p];for(let d of m){let y=d.child(0)?.text?.replace(/^:/,""),f=d.child(2);if(y==="to"&&f){let g=this.extractStringValue(f);g&&g.includes("#")&&([c,i]=g.split("#"));}}}else if(p.type==="string"||p.type==="string_content"){let m=this.extractStringValue(p);m&&m.includes("#")&&!c&&([c,i]=m.split("#"));}if(!c&&!i){let p=r.replace(/^\//,"").split("/");c=p[0]||"",i=p[1]||"index";}o.length>0&&c&&!c.includes("/")&&(c=`${o.join("/")}/${c}`);let u=this.buildPath(o,r);this.routes.push({method:t==="match"?"ALL":t.toUpperCase(),path:u,controller:c,action:i,namespace:o.join("/")||void 0,line:n});}async parseResources(e,t,o,n){let s=S(e);if(s.length===0)return;let r=s[0].text.replace(/^:/,""),c={name:r,controller:t.length>0?`${t.join("/")}/${r}`:r,nested:[],memberRoutes:[],collectionRoutes:[],line:o};for(let u of s)if(u.type==="hash"){let p=w(u,"pair");for(let m of p){let d=m.child(0)?.text?.replace(/^:/,""),y=m.child(2);d==="only"&&y?c.only=this.extractArrayValues(y):d==="except"&&y&&(c.except=this.extractArrayValues(y));}}this.generateResourceRoutes(c,t,n),this.resources.push(c);let i=e.childForFieldName("block");if(i){let u=R(i,"call");for(let p of u){let m=p.childForFieldName("method")?.text;if(m==="member"){let d=p.childForFieldName("block");d&&this.parseMemberCollectionRoutes(d,c,t,"member");}else if(m==="collection"){let d=p.childForFieldName("block");d&&this.parseMemberCollectionRoutes(d,c,t,"collection");}}}}parseMemberCollectionRoutes(e,t,o,n){let s=R(e,"call");for(let a of s){let r=a.childForFieldName("method");if(!r)continue;let c=r.text;if(!["get","post","put","patch","delete"].includes(c))continue;let i=S(a);if(i.length===0)continue;let u=i[0].text.replace(/^:/,""),p=n==="member"?`/${t.name}/:id/${u}`:`/${t.name}/${u}`,m={method:c.toUpperCase(),path:this.buildPath(o,p),controller:t.controller,action:u,namespace:o.join("/")||void 0,line:a.startPosition.row+1};n==="member"?t.memberRoutes.push(m):t.collectionRoutes.push(m),this.routes.push(m);}}async parseNamespace(e,t,o){let n=S(e);if(n.length===0)return;let s=n[0].text.replace(/^:/,"");this.namespaces.push(s);let a=[...t,s],r=e.childForFieldName("block");if(r){let c=R(r,"call");for(let i of c){let u=i.childForFieldName("method");if(!u)continue;let p=u.text,m=i.startPosition.row+1;switch(p){case "get":case "post":case "put":case "patch":case "delete":case "match":this.parseHttpRoute(i,p,a,m);break;case "resources":case "resource":await this.parseResources(i,a,m,p==="resource");break;case "draw":await this.parseDraw(i,a);break}}}}parseMount(e,t){let o=S(e);if(o.length===0)return;let s=o[0].text,a="/";for(let r of o)if(r.type==="hash"||r.type==="pair"){let c=r.type==="hash"?w(r,"pair"):[r];for(let i of c){let u=i.child(0)?.text?.replace(/^:/,""),p=i.child(2);u==="at"&&p&&(a=this.extractStringValue(p)||a);}}else if(r.type==="string"){let c=this.extractStringValue(r);c&&c.startsWith("/")&&(a=c);}this.mountedEngines.push({engine:s,mountPath:a,line:t});}async parseDraw(e,t){let o=S(e);if(o.length===0)return;let n=o[0].text.replace(/^:/,""),s=x.join(this.routesDir,`${n}.rb`);if(G.existsSync(s)){this.drawnFiles.push(s);try{await this.parseRoutesFile(s,t);}catch(a){this.errors.push(`Error parsing drawn file ${s}: ${a}`);}}}parseDeviseFor(e,t,o){let n=S(e);if(n.length===0)return;let s=n[0].text.replace(/^:/,""),a=[{method:"GET",path:`/${s}/sign_in`,action:"new",controller:"devise/sessions"},{method:"POST",path:`/${s}/sign_in`,action:"create",controller:"devise/sessions"},{method:"DELETE",path:`/${s}/sign_out`,action:"destroy",controller:"devise/sessions"},{method:"GET",path:`/${s}/password/new`,action:"new",controller:"devise/passwords"},{method:"POST",path:`/${s}/password`,action:"create",controller:"devise/passwords"},{method:"GET",path:`/${s}/sign_up`,action:"new",controller:"devise/registrations"},{method:"POST",path:`/${s}`,action:"create",controller:"devise/registrations"}];for(let r of a)this.routes.push({method:r.method,path:this.buildPath(t,r.path),controller:r.controller,action:r.action,namespace:t.join("/")||void 0,line:o,authenticated:false});}parseRoot(e,t,o){let n=S(e),s="",a="index";for(let r of n)if(r.type==="string"){let c=this.extractStringValue(r);c&&c.includes("#")&&([s,a]=c.split("#"));}else if(r.type==="hash"||r.type==="pair"){let c=r.type==="hash"?w(r,"pair"):[r];for(let i of c){let u=i.child(0)?.text?.replace(/^:/,""),p=i.child(2);if(u==="to"&&p){let m=this.extractStringValue(p);m&&m.includes("#")&&([s,a]=m.split("#"));}}}s&&this.routes.push({method:"GET",path:this.buildPath(t,"/"),controller:s,action:a,namespace:t.join("/")||void 0,line:o});}generateResourceRoutes(e,t,o){let n=this.buildPath(t,`/${e.name}`),s=o?["show","new","create","edit","update","destroy"]:["index","show","new","create","edit","update","destroy"],a=e.only||(e.except?s.filter(i=>!e.except.includes(i)):s),r=[];o||a.includes("index")&&r.push({method:"GET",path:n,action:"index"}),a.includes("new")&&r.push({method:"GET",path:`${n}/new`,action:"new"}),a.includes("create")&&r.push({method:"POST",path:n,action:"create"});let c=o?n:`${n}/:id`;a.includes("show")&&r.push({method:"GET",path:c,action:"show"}),a.includes("edit")&&r.push({method:"GET",path:`${c}/edit`,action:"edit"}),a.includes("update")&&(r.push({method:"PUT",path:c,action:"update"}),r.push({method:"PATCH",path:c,action:"update"})),a.includes("destroy")&&r.push({method:"DELETE",path:c,action:"destroy"});for(let i of r)this.routes.push({method:i.method,path:i.path,controller:e.controller,action:i.action,namespace:t.join("/")||void 0,line:e.line});}buildPath(e,t){return t.startsWith("/")?t:`${e.length>0?`/${e.join("/")}`:""}/${t}`}extractStringValue(e){if(e.type==="string"){let t=L(e,"string_content");return t?t.text:e.text.replace(/^["']|["']$/g,"")}return e.type==="string_content"?e.text:e.type==="simple_symbol"||e.type==="symbol"?e.text.replace(/^:/,""):e.text.replace(/^["']|["']$/g,"")}extractArrayValues(e){let t=[];if(e.type==="array")for(let o=0;o<e.childCount;o++){let n=e.child(o);if(n&&n.type!=="["&&n.type!=="]"&&n.type!==","){let s=this.extractStringValue(n);s&&t.push(s);}}else {let o=this.extractStringValue(e);o&&t.push(o);}return t}};async function de(){let l=process.argv[2]||process.cwd();console.log(`Analyzing routes in: ${l}`);let t=await new k(l).analyze();if(console.log(`
1
+ import*as G from'fs';import*as x from'path';import {Parser,Language}from'web-tree-sitter';import {fileURLToPath}from'url';import {createRequire}from'module';import {glob}from'glob';import*as A from'fs/promises';var ue=createRequire(import.meta.url);var de=fileURLToPath(import.meta.url);x.dirname(de);var te=false,O=null,D=null;async function se(){if(D&&O)return D;te||(await Parser.init(),te=true),D=new Parser;let l=null;try{let e=ue.resolve("tree-sitter-ruby/package.json");l=x.join(x.dirname(e),"tree-sitter-ruby.wasm");}catch{let e=x.join(process.cwd(),"node_modules/tree-sitter-ruby/tree-sitter-ruby.wasm");G.existsSync(e)&&(l=e);}if(!l||!G.existsSync(l))throw new Error("tree-sitter-ruby.wasm not found. Please ensure tree-sitter-ruby package is installed.");return O=await Language.load(l),D.setLanguage(O),D}async function ne(l){let t=(await se()).parse(l);if(!t)throw new Error("Failed to parse Ruby code");return t}async function N(l){let e=G.readFileSync(l,"utf-8");return ne(e)}function R(l,e){let t=[];l.type===e&&t.push(l);for(let o=0;o<l.childCount;o++){let n=l.child(o);n&&t.push(...R(n,e));}return t}function L(l,e){for(let t=0;t<l.childCount;t++){let o=l.child(t);if(o&&o.type===e)return o}return null}function w(l,e){let t=[];for(let o=0;o<l.childCount;o++){let n=l.child(o);n&&n.type===e&&t.push(n);}return t}function S(l){let e=l.childForFieldName("arguments");if(!e)return [];let t=[];for(let o=0;o<e.childCount;o++){let n=e.child(o);n&&n.type!=="("&&n.type!==")"&&n.type!==","&&t.push(n);}return t}function F(l){let e=l.childForFieldName("name");return e?e.text:null}function M(l){let e=l.childForFieldName("superclass");if(!e)return null;let t=L(e,"constant")||L(e,"scope_resolution");return t?t.text:null}function U(l){let e=l.childForFieldName("name");return e?e.text:null}function Z(l){let e=l.childForFieldName("parameters");if(!e)return [];let t=[];for(let o=0;o<e.childCount;o++){let n=e.child(o);if(n&&(n.type==="identifier"||n.type==="keyword_parameter"||n.type==="optional_parameter"||n.type==="splat_parameter")){let s=n.childForFieldName("name")||n;s.type==="identifier"?t.push(s.text):t.push(n.text);}}return t}var k=class{constructor(e){this.rootPath=e;this.routesDir=x.join(e,"config","routes");}routesDir;routes=[];namespaces=[];resources=[];mountedEngines=[];drawnFiles=[];errors=[];async analyze(){let e=x.join(this.rootPath,"config","routes.rb");if(!G.existsSync(e))return {routes:[],namespaces:[],resources:[],mountedEngines:[],drawnFiles:[],errors:[`routes.rb not found at ${e}`]};try{await this.parseRoutesFile(e,[]);}catch(t){this.errors.push(`Error parsing ${e}: ${t}`);}return {routes:this.routes,namespaces:[...new Set(this.namespaces)],resources:this.resources,mountedEngines:this.mountedEngines,drawnFiles:this.drawnFiles,errors:this.errors}}async parseRoutesFile(e,t){let n=(await N(e)).rootNode,s=R(n,"call");for(let a of s){let r=a.childForFieldName("method");if(!r)continue;let c=r.text,i=a.startPosition.row+1;switch(c){case "get":case "post":case "put":case "patch":case "delete":case "match":this.parseHttpRoute(a,c,t,i);break;case "resources":case "resource":await this.parseResources(a,t,i,c==="resource");break;case "namespace":await this.parseNamespace(a,t,e);break;case "mount":this.parseMount(a,i);break;case "draw":await this.parseDraw(a,t);break;case "devise_for":this.parseDeviseFor(a,t,i);break;case "root":this.parseRoot(a,t,i);break}}}parseHttpRoute(e,t,o,n){let s=S(e);if(s.length===0)return;let a=s[0],r=this.extractStringValue(a);if(!r)return;let c="",i="";for(let p of s)if(p.type==="hash"||p.type==="pair"){let d=p.type==="hash"?w(p,"pair"):[p];for(let f of d){let y=f.child(0)?.text?.replace(/^:/,""),m=f.child(2);if(y==="to"&&m){let g=this.extractStringValue(m);g&&g.includes("#")&&([c,i]=g.split("#"));}}}else if(p.type==="string"||p.type==="string_content"){let d=this.extractStringValue(p);d&&d.includes("#")&&!c&&([c,i]=d.split("#"));}if(!c&&!i){let p=r.replace(/^\//,"").split("/");c=p[0]||"",i=p[1]||"index";}o.length>0&&c&&!c.includes("/")&&(c=`${o.join("/")}/${c}`);let u=this.buildPath(o,r);this.routes.push({method:t==="match"?"ALL":t.toUpperCase(),path:u,controller:c,action:i,namespace:o.join("/")||void 0,line:n});}async parseResources(e,t,o,n){let s=S(e);if(s.length===0)return;let r=s[0].text.replace(/^:/,""),c={name:r,controller:t.length>0?`${t.join("/")}/${r}`:r,nested:[],memberRoutes:[],collectionRoutes:[],line:o};for(let u of s)if(u.type==="hash"){let p=w(u,"pair");for(let d of p){let f=d.child(0)?.text?.replace(/^:/,""),y=d.child(2);f==="only"&&y?c.only=this.extractArrayValues(y):f==="except"&&y&&(c.except=this.extractArrayValues(y));}}this.generateResourceRoutes(c,t,n),this.resources.push(c);let i=e.childForFieldName("block");if(i){let u=R(i,"call");for(let p of u){let d=p.childForFieldName("method")?.text;if(d==="member"){let f=p.childForFieldName("block");f&&this.parseMemberCollectionRoutes(f,c,t,"member");}else if(d==="collection"){let f=p.childForFieldName("block");f&&this.parseMemberCollectionRoutes(f,c,t,"collection");}}}}parseMemberCollectionRoutes(e,t,o,n){let s=R(e,"call");for(let a of s){let r=a.childForFieldName("method");if(!r)continue;let c=r.text;if(!["get","post","put","patch","delete"].includes(c))continue;let i=S(a);if(i.length===0)continue;let u=i[0].text.replace(/^:/,""),p=n==="member"?`/${t.name}/:id/${u}`:`/${t.name}/${u}`,d={method:c.toUpperCase(),path:this.buildPath(o,p),controller:t.controller,action:u,namespace:o.join("/")||void 0,line:a.startPosition.row+1};n==="member"?t.memberRoutes.push(d):t.collectionRoutes.push(d),this.routes.push(d);}}async parseNamespace(e,t,o){let n=S(e);if(n.length===0)return;let s=n[0].text.replace(/^:/,"");this.namespaces.push(s);let a=[...t,s],r=e.childForFieldName("block");if(r){let c=R(r,"call");for(let i of c){let u=i.childForFieldName("method");if(!u)continue;let p=u.text,d=i.startPosition.row+1;switch(p){case "get":case "post":case "put":case "patch":case "delete":case "match":this.parseHttpRoute(i,p,a,d);break;case "resources":case "resource":await this.parseResources(i,a,d,p==="resource");break;case "draw":await this.parseDraw(i,a);break}}}}parseMount(e,t){let o=S(e);if(o.length===0)return;let s=o[0].text,a="/";for(let r of o)if(r.type==="hash"||r.type==="pair"){let c=r.type==="hash"?w(r,"pair"):[r];for(let i of c){let u=i.child(0)?.text?.replace(/^:/,""),p=i.child(2);u==="at"&&p&&(a=this.extractStringValue(p)||a);}}else if(r.type==="string"){let c=this.extractStringValue(r);c&&c.startsWith("/")&&(a=c);}this.mountedEngines.push({engine:s,mountPath:a,line:t});}async parseDraw(e,t){let o=S(e);if(o.length===0)return;let n=o[0].text.replace(/^:/,""),s=x.join(this.routesDir,`${n}.rb`);if(G.existsSync(s)){this.drawnFiles.push(s);try{await this.parseRoutesFile(s,t);}catch(a){this.errors.push(`Error parsing drawn file ${s}: ${a}`);}}}parseDeviseFor(e,t,o){let n=S(e);if(n.length===0)return;let s=n[0].text.replace(/^:/,""),a=[{method:"GET",path:`/${s}/sign_in`,action:"new",controller:"devise/sessions"},{method:"POST",path:`/${s}/sign_in`,action:"create",controller:"devise/sessions"},{method:"DELETE",path:`/${s}/sign_out`,action:"destroy",controller:"devise/sessions"},{method:"GET",path:`/${s}/password/new`,action:"new",controller:"devise/passwords"},{method:"POST",path:`/${s}/password`,action:"create",controller:"devise/passwords"},{method:"GET",path:`/${s}/sign_up`,action:"new",controller:"devise/registrations"},{method:"POST",path:`/${s}`,action:"create",controller:"devise/registrations"}];for(let r of a)this.routes.push({method:r.method,path:this.buildPath(t,r.path),controller:r.controller,action:r.action,namespace:t.join("/")||void 0,line:o,authenticated:false});}parseRoot(e,t,o){let n=S(e),s="",a="index";for(let r of n)if(r.type==="string"){let c=this.extractStringValue(r);c&&c.includes("#")&&([s,a]=c.split("#"));}else if(r.type==="hash"||r.type==="pair"){let c=r.type==="hash"?w(r,"pair"):[r];for(let i of c){let u=i.child(0)?.text?.replace(/^:/,""),p=i.child(2);if(u==="to"&&p){let d=this.extractStringValue(p);d&&d.includes("#")&&([s,a]=d.split("#"));}}}s&&this.routes.push({method:"GET",path:this.buildPath(t,"/"),controller:s,action:a,namespace:t.join("/")||void 0,line:o});}generateResourceRoutes(e,t,o){let n=this.buildPath(t,`/${e.name}`),s=o?["show","new","create","edit","update","destroy"]:["index","show","new","create","edit","update","destroy"],a=e.only||(e.except?s.filter(i=>!e.except.includes(i)):s),r=[];o||a.includes("index")&&r.push({method:"GET",path:n,action:"index"}),a.includes("new")&&r.push({method:"GET",path:`${n}/new`,action:"new"}),a.includes("create")&&r.push({method:"POST",path:n,action:"create"});let c=o?n:`${n}/:id`;a.includes("show")&&r.push({method:"GET",path:c,action:"show"}),a.includes("edit")&&r.push({method:"GET",path:`${c}/edit`,action:"edit"}),a.includes("update")&&(r.push({method:"PUT",path:c,action:"update"}),r.push({method:"PATCH",path:c,action:"update"})),a.includes("destroy")&&r.push({method:"DELETE",path:c,action:"destroy"});for(let i of r)this.routes.push({method:i.method,path:i.path,controller:e.controller,action:i.action,namespace:t.join("/")||void 0,line:e.line});}buildPath(e,t){return t.startsWith("/")?t:`${e.length>0?`/${e.join("/")}`:""}/${t}`}extractStringValue(e){if(e.type==="string"){let t=L(e,"string_content");return t?t.text:e.text.replace(/^["']|["']$/g,"")}return e.type==="string_content"?e.text:e.type==="simple_symbol"||e.type==="symbol"?e.text.replace(/^:/,""):e.text.replace(/^["']|["']$/g,"")}extractArrayValues(e){let t=[];if(e.type==="array")for(let o=0;o<e.childCount;o++){let n=e.child(o);if(n&&n.type!=="["&&n.type!=="]"&&n.type!==","){let s=this.extractStringValue(n);s&&t.push(s);}}else {let o=this.extractStringValue(e);o&&t.push(o);}return t}};async function fe(){let l=process.argv[2]||process.cwd();console.log(`Analyzing routes in: ${l}`);let t=await new k(l).analyze();if(console.log(`
2
2
  === Rails Routes Analysis ===
3
3
  `),console.log(`Total routes: ${t.routes.length}`),console.log(`Namespaces: ${t.namespaces.join(", ")||"(none)"}`),console.log(`Resources: ${t.resources.length}`),console.log(`Mounted engines: ${t.mountedEngines.length}`),console.log(`External route files: ${t.drawnFiles.length}`),t.errors.length>0){console.log(`
4
4
  --- Errors ---`);for(let o of t.errors)console.log(` \u274C ${o}`);}console.log(`
5
5
  --- Sample Routes (first 30) ---`);for(let o of t.routes.slice(0,30))console.log(` ${o.method.padEnd(7)} ${o.path.padEnd(50)} => ${o.controller}#${o.action}`);console.log(`
6
6
  --- Mounted Engines ---`);for(let o of t.mountedEngines)console.log(` ${o.engine} => ${o.mountPath}`);console.log(`
7
- --- External Route Files ---`);for(let o of t.drawnFiles)console.log(` ${x.basename(o)}`);}var fe=import.meta.url===`file://${process.argv[1]}`;fe&&de().catch(console.error);var V=class{constructor(e){this.rootPath=e;this.controllersDir=x.join(e,"app","controllers");}controllersDir;controllers=[];errors=[];async analyze(){if(!G.existsSync(this.controllersDir))return {controllers:[],totalActions:0,namespaces:[],concerns:[],errors:[`Controllers directory not found at ${this.controllersDir}`]};let e=await glob("**/*_controller.rb",{cwd:this.controllersDir,ignore:["concerns/**"]});for(let s of e){let a=x.join(this.controllersDir,s);try{let r=await this.parseControllerFile(a,s);r&&this.controllers.push(r);}catch(r){this.errors.push(`Error parsing ${s}: ${r}`);}}let t=[...new Set(this.controllers.filter(s=>s.namespace).map(s=>s.namespace))],o=[...new Set(this.controllers.flatMap(s=>s.concerns))],n=this.controllers.reduce((s,a)=>s+a.actions.length,0);return {controllers:this.controllers,totalActions:n,namespaces:t,concerns:o,errors:this.errors}}async parseControllerFile(e,t){let n=(await N(e)).rootNode,s=t.replace(/_controller\.rb$/,"").split("/"),a=s.length>1?s.slice(0,-1).join("/"):void 0,r=s[s.length-1],c=R(n,"class");if(c.length===0)return null;let i=c[0],u=F(i),p=M(i);if(!u)return null;let m={name:r,filePath:t,className:u,parentClass:p||"ApplicationController",namespace:a,actions:[],beforeActions:[],afterActions:[],aroundActions:[],skipBeforeActions:[],concerns:[],helpers:[],rescueFrom:[],line:i.startPosition.row+1},d=R(i,"call");for(let h of d){let b=h.childForFieldName("method");if(!b)continue;let v=b.text,C=h.startPosition.row+1;switch(v){case "before_action":case "before_filter":this.parseFilter(h,m.beforeActions,C);break;case "after_action":case "after_filter":this.parseFilter(h,m.afterActions,C);break;case "around_action":case "around_filter":this.parseFilter(h,m.aroundActions,C);break;case "skip_before_action":case "skip_before_filter":this.parseFilter(h,m.skipBeforeActions,C);break;case "include":this.parseInclude(h,m.concerns);break;case "helper":this.parseHelper(h,m.helpers);break;case "layout":m.layoutInfo=this.parseLayout(h);break;case "rescue_from":this.parseRescueFrom(h,m.rescueFrom,C);break}}R(i,"method");let f="public",g=i.childForFieldName("body");if(g)for(let h=0;h<g.childCount;h++){let b=g.child(h);if(b){if(b.type==="identifier"){let v=b.text;v==="private"?f="private":v==="protected"?f="protected":v==="public"&&(f="public");}else if(b.type==="method"){let v=this.parseMethod(b,f);v&&m.actions.push(v);}}}return m}parseFilter(e,t,o){let n=this.getCallArguments(e);if(n.length===0)return;let r={name:n[0].text.replace(/^:/,""),line:o};for(let c of n.slice(1))if(c.type==="hash"){let i=w(c,"pair");for(let u of i){let p=u.child(0)?.text?.replace(/^:/,""),m=u.child(2);if(!(!p||!m))switch(p){case "only":r.only=this.extractArrayValues(m);break;case "except":r.except=this.extractArrayValues(m);break;case "if":r.if=m.text;break;case "unless":r.unless=m.text;break}}}t.push(r);}parseInclude(e,t){let o=this.getCallArguments(e);for(let n of o)(n.type==="constant"||n.type==="scope_resolution")&&t.push(n.text);}parseHelper(e,t){let o=this.getCallArguments(e);for(let n of o){let s=n.text.replace(/^:/,"");t.push(s);}}parseLayout(e){let t=this.getCallArguments(e);if(t.length===0)return;let o=t[0],n=o.text.replace(/^["']|["']$/g,"");n.startsWith(":")&&(n=n.substring(1)),(o.type==="lambda"||o.type==="proc")&&(n="(dynamic)");let s={name:n};for(let a of t.slice(1))a.type==="hash"&&(s.conditions=a.text);return s}parseRescueFrom(e,t,o){let n=this.getCallArguments(e);if(n.length===0)return;let s=n[0].text,a="unknown";for(let r of n.slice(1))if(r.type==="hash"||r.type==="pair"){let c=r.type==="hash"?w(r,"pair"):[r];for(let i of c){let u=i.child(0)?.text?.replace(/^:/,""),p=i.child(2);u==="with"&&p&&(a=p.text.replace(/^:/,""));}}t.push({exception:s,handler:a,line:o});}parseMethod(e,t){let o=U(e);if(!o||e.text.includes("def self."))return null;let n={name:o,line:e.startPosition.row+1,visibility:t,parameters:Z(e),servicesCalled:[],modelsCalled:[],methodCalls:[],instanceVarAssignments:[]},s=e.text,a=/@([a-z_][a-z0-9_]*)\s*=\s*([^\n]+)/gi,r;for(;(r=a.exec(s))!==null;){let u=r[1],p=r[2].trim().slice(0,100),m,d=p.match(/^([A-Z][a-zA-Z0-9]+)\.(find|find_by|find_by!|where|all|first|last|new|create|create!|build)/);d&&(m=d[1]);let y=p.match(/^@([a-z_]+)\.([a-z_]+)/);y&&!m&&(m=`${y[1]}.${y[2]}`);let f=p.match(/^current_([a-z_]+)/);f&&!m&&(m=f[1].charAt(0).toUpperCase()+f[1].slice(1));let g=p.match(/^([A-Z][a-zA-Z0-9]+Service)\.(call|new|perform)/);g&&!m&&(m=`Service:${g[1]}`),n.instanceVarAssignments&&n.instanceVarAssignments.push({name:u,assignedType:m,assignedValue:p.length>60?p.slice(0,57)+"...":p});}(s.includes("render json:")||s.includes("render :json"))&&(n.rendersJson=true),s.includes("render")&&!n.rendersJson&&(n.rendersHtml=true);let c=s.match(/redirect_to\s+([^,\n]+)/);if(c&&(n.redirectsTo=c[1].trim()),s.includes("respond_to")){let u=[];s.includes("format.html")&&u.push("html"),s.includes("format.json")&&u.push("json"),s.includes("format.xml")&&u.push("xml"),s.includes("format.js")&&u.push("js"),s.includes("format.csv")&&u.push("csv"),s.includes("format.pdf")&&u.push("pdf"),u.length>0&&(n.respondsTo=u);}let i=R(e,"call");for(let u of i){let p=u.childForFieldName("receiver"),m=u.childForFieldName("method");if(p&&m){let d=p.text,y=m.text;d.endsWith("Service")&&["call","new","perform","execute"].includes(y)&&(n.servicesCalled.includes(d)||n.servicesCalled.push(d));let f=["find","find_by","find_by!","where","all","first","last","create","create!","new","update","update!","destroy","delete"];/^[A-Z][a-zA-Z]+$/.test(d)&&f.includes(y)&&(["Rails","ActiveRecord","ActionController","ApplicationRecord"].includes(d)||n.modelsCalled.includes(d)||n.modelsCalled.push(d)),n.methodCalls.push(`${d}.${y}`);}else m&&!p&&n.methodCalls.push(m.text);}return n}getCallArguments(e){let t=e.childForFieldName("arguments");if(!t){let n=[];for(let s=0;s<e.childCount;s++){let a=e.child(s);a&&!["identifier","(",")",",","call"].includes(a.type)&&a!==e.childForFieldName("method")&&a!==e.childForFieldName("receiver")&&n.push(a);}return n}let o=[];for(let n=0;n<t.childCount;n++){let s=t.child(n);s&&s.type!=="("&&s.type!==")"&&s.type!==","&&o.push(s);}return o}extractArrayValues(e){let t=[];if(e.type==="array")for(let o=0;o<e.childCount;o++){let n=e.child(o);n&&n.type!=="["&&n.type!=="]"&&n.type!==","&&t.push(n.text.replace(/^:/,""));}else t.push(e.text.replace(/^:/,""));return t}};async function ge(){let l=process.argv[2]||process.cwd();console.log(`Analyzing controllers in: ${l}`);let t=await new V(l).analyze();if(console.log(`
7
+ --- External Route Files ---`);for(let o of t.drawnFiles)console.log(` ${x.basename(o)}`);}var me=import.meta.url===`file://${process.argv[1]}`;me&&fe().catch(console.error);var V=class{constructor(e){this.rootPath=e;this.controllersDir=x.join(e,"app","controllers");}controllersDir;controllers=[];errors=[];async analyze(){if(!G.existsSync(this.controllersDir))return {controllers:[],totalActions:0,namespaces:[],concerns:[],errors:[`Controllers directory not found at ${this.controllersDir}`]};let e=await glob("**/*_controller.rb",{cwd:this.controllersDir,ignore:["concerns/**"]});for(let s of e){let a=x.join(this.controllersDir,s);try{let r=await this.parseControllerFile(a,s);r&&this.controllers.push(r);}catch(r){this.errors.push(`Error parsing ${s}: ${r}`);}}let t=[...new Set(this.controllers.filter(s=>s.namespace).map(s=>s.namespace))],o=[...new Set(this.controllers.flatMap(s=>s.concerns))],n=this.controllers.reduce((s,a)=>s+a.actions.length,0);return {controllers:this.controllers,totalActions:n,namespaces:t,concerns:o,errors:this.errors}}async parseControllerFile(e,t){let n=(await N(e)).rootNode,s=t.replace(/_controller\.rb$/,"").split("/"),a=s.length>1?s.slice(0,-1).join("/"):void 0,r=s[s.length-1],c=R(n,"class");if(c.length===0)return null;let i=c[0],u=F(i),p=M(i);if(!u)return null;let d={name:r,filePath:t,className:u,parentClass:p||"ApplicationController",namespace:a,actions:[],beforeActions:[],afterActions:[],aroundActions:[],skipBeforeActions:[],concerns:[],helpers:[],rescueFrom:[],line:i.startPosition.row+1},f=R(i,"call");for(let h of f){let b=h.childForFieldName("method");if(!b)continue;let v=b.text,C=h.startPosition.row+1;switch(v){case "before_action":case "before_filter":this.parseFilter(h,d.beforeActions,C);break;case "after_action":case "after_filter":this.parseFilter(h,d.afterActions,C);break;case "around_action":case "around_filter":this.parseFilter(h,d.aroundActions,C);break;case "skip_before_action":case "skip_before_filter":this.parseFilter(h,d.skipBeforeActions,C);break;case "include":this.parseInclude(h,d.concerns);break;case "helper":this.parseHelper(h,d.helpers);break;case "layout":d.layoutInfo=this.parseLayout(h);break;case "rescue_from":this.parseRescueFrom(h,d.rescueFrom,C);break}}R(i,"method");let m="public",g=i.childForFieldName("body");if(g)for(let h=0;h<g.childCount;h++){let b=g.child(h);if(b){if(b.type==="identifier"){let v=b.text;v==="private"?m="private":v==="protected"?m="protected":v==="public"&&(m="public");}else if(b.type==="method"){let v=this.parseMethod(b,m);v&&d.actions.push(v);}}}return d}parseFilter(e,t,o){let n=this.getCallArguments(e);if(n.length===0)return;let r={name:n[0].text.replace(/^:/,""),line:o};for(let c of n.slice(1))if(c.type==="hash"){let i=w(c,"pair");for(let u of i){let p=u.child(0)?.text?.replace(/^:/,""),d=u.child(2);if(!(!p||!d))switch(p){case "only":r.only=this.extractArrayValues(d);break;case "except":r.except=this.extractArrayValues(d);break;case "if":r.if=d.text;break;case "unless":r.unless=d.text;break}}}t.push(r);}parseInclude(e,t){let o=this.getCallArguments(e);for(let n of o)(n.type==="constant"||n.type==="scope_resolution")&&t.push(n.text);}parseHelper(e,t){let o=this.getCallArguments(e);for(let n of o){let s=n.text.replace(/^:/,"");t.push(s);}}parseLayout(e){let t=this.getCallArguments(e);if(t.length===0)return;let o=t[0],n=o.text.replace(/^["']|["']$/g,"");n.startsWith(":")&&(n=n.substring(1)),(o.type==="lambda"||o.type==="proc")&&(n="(dynamic)");let s={name:n};for(let a of t.slice(1))a.type==="hash"&&(s.conditions=a.text);return s}parseRescueFrom(e,t,o){let n=this.getCallArguments(e);if(n.length===0)return;let s=n[0].text,a="unknown";for(let r of n.slice(1))if(r.type==="hash"||r.type==="pair"){let c=r.type==="hash"?w(r,"pair"):[r];for(let i of c){let u=i.child(0)?.text?.replace(/^:/,""),p=i.child(2);u==="with"&&p&&(a=p.text.replace(/^:/,""));}}t.push({exception:s,handler:a,line:o});}parseMethod(e,t){let o=U(e);if(!o||e.text.includes("def self."))return null;let n={name:o,line:e.startPosition.row+1,visibility:t,parameters:Z(e),servicesCalled:[],modelsCalled:[],methodCalls:[],instanceVarAssignments:[]},s=e.text,a=/@([a-z_][a-z0-9_]*)\s*=\s*([^\n]+)/gi,r;for(;(r=a.exec(s))!==null;){let u=r[1],p=r[2].trim().slice(0,100),d,f=p.match(/^([A-Z][a-zA-Z0-9]+)\.(find|find_by|find_by!|where|all|first|last|new|create|create!|build)/);f&&(d=f[1]);let y=p.match(/^@([a-z_]+)\.([a-z_]+)/);y&&!d&&(d=`${y[1]}.${y[2]}`);let m=p.match(/^current_([a-z_]+)/);m&&!d&&(d=m[1].charAt(0).toUpperCase()+m[1].slice(1));let g=p.match(/^([A-Z][a-zA-Z0-9]+Service)\.(call|new|perform)/);g&&!d&&(d=`Service:${g[1]}`),n.instanceVarAssignments&&n.instanceVarAssignments.push({name:u,assignedType:d,assignedValue:p.length>60?p.slice(0,57)+"...":p});}(s.includes("render json:")||s.includes("render :json"))&&(n.rendersJson=true),s.includes("render")&&!n.rendersJson&&(n.rendersHtml=true);let c=s.match(/redirect_to\s+([^,\n]+)/);if(c&&(n.redirectsTo=c[1].trim()),s.includes("respond_to")){let u=[];s.includes("format.html")&&u.push("html"),s.includes("format.json")&&u.push("json"),s.includes("format.xml")&&u.push("xml"),s.includes("format.js")&&u.push("js"),s.includes("format.csv")&&u.push("csv"),s.includes("format.pdf")&&u.push("pdf"),u.length>0&&(n.respondsTo=u);}let i=R(e,"call");for(let u of i){let p=u.childForFieldName("receiver"),d=u.childForFieldName("method");if(p&&d){let f=p.text,y=d.text;f.endsWith("Service")&&["call","new","perform","execute"].includes(y)&&(n.servicesCalled.includes(f)||n.servicesCalled.push(f));let m=["find","find_by","find_by!","where","all","first","last","create","create!","new","update","update!","destroy","delete"];/^[A-Z][a-zA-Z]+$/.test(f)&&m.includes(y)&&(["Rails","ActiveRecord","ActionController","ApplicationRecord"].includes(f)||n.modelsCalled.includes(f)||n.modelsCalled.push(f)),n.methodCalls.push(`${f}.${y}`);}else d&&!p&&n.methodCalls.push(d.text);}return n}getCallArguments(e){let t=e.childForFieldName("arguments");if(!t){let n=[];for(let s=0;s<e.childCount;s++){let a=e.child(s);a&&!["identifier","(",")",",","call"].includes(a.type)&&a!==e.childForFieldName("method")&&a!==e.childForFieldName("receiver")&&n.push(a);}return n}let o=[];for(let n=0;n<t.childCount;n++){let s=t.child(n);s&&s.type!=="("&&s.type!==")"&&s.type!==","&&o.push(s);}return o}extractArrayValues(e){let t=[];if(e.type==="array")for(let o=0;o<e.childCount;o++){let n=e.child(o);n&&n.type!=="["&&n.type!=="]"&&n.type!==","&&t.push(n.text.replace(/^:/,""));}else t.push(e.text.replace(/^:/,""));return t}};async function ge(){let l=process.argv[2]||process.cwd();console.log(`Analyzing controllers in: ${l}`);let t=await new V(l).analyze();if(console.log(`
8
8
  === Rails Controllers Analysis ===
9
9
  `),console.log(`Total controllers: ${t.controllers.length}`),console.log(`Total actions: ${t.totalActions}`),console.log(`Namespaces: ${t.namespaces.join(", ")||"(none)"}`),console.log(`Shared concerns: ${t.concerns.length}`),t.errors.length>0){console.log(`
10
10
  --- Errors (${t.errors.length}) ---`);for(let s of t.errors.slice(0,5))console.log(` \u274C ${s}`);t.errors.length>5&&console.log(` ... and ${t.errors.length-5} more`);}console.log(`
11
11
  --- Sample Controllers (first 10) ---`);for(let s of t.controllers.slice(0,10))console.log(`
12
12
  \u{1F4C1} ${s.className} (${s.filePath})`),console.log(` Parent: ${s.parentClass}`),console.log(` Actions (${s.actions.length}): ${s.actions.map(a=>a.name).slice(0,5).join(", ")}${s.actions.length>5?"...":""}`),s.beforeActions.length>0&&console.log(` Before: ${s.beforeActions.map(a=>a.name).join(", ")}`),s.concerns.length>0&&console.log(` Concerns: ${s.concerns.join(", ")}`);let o=t.controllers.flatMap(s=>s.actions.filter(a=>a.visibility==="public")),n=t.controllers.flatMap(s=>s.actions.filter(a=>a.visibility==="private"));console.log(`
13
- --- Action Visibility Summary ---`),console.log(` Public: ${o.length}`),console.log(` Private: ${n.length}`);}var ye=import.meta.url===`file://${process.argv[1]}`;ye&&ge().catch(console.error);var j=class{constructor(e){this.rootPath=e;this.modelsDir=x.join(e,"app","models");}modelsDir;models=[];errors=[];async analyze(){if(!G.existsSync(this.modelsDir))return {models:[],totalAssociations:0,totalValidations:0,concerns:[],namespaces:[],errors:[`Models directory not found at ${this.modelsDir}`]};let e=await glob("**/*.rb",{cwd:this.modelsDir,ignore:["concerns/**","application_record.rb"]});for(let a of e){let r=x.join(this.modelsDir,a);try{let c=await this.parseModelFile(r,a);c&&this.models.push(c);}catch(c){this.errors.push(`Error parsing ${a}: ${c}`);}}let t=[...new Set(this.models.flatMap(a=>a.concerns))],o=[...new Set(this.models.map(a=>{let r=a.filePath.split("/");return r.length>1?r.slice(0,-1).join("/"):null}).filter(a=>a!==null))],n=this.models.reduce((a,r)=>a+r.associations.length,0),s=this.models.reduce((a,r)=>a+r.validations.length,0);return {models:this.models,totalAssociations:n,totalValidations:s,concerns:t,namespaces:o,errors:this.errors}}async parseModelFile(e,t){let n=(await N(e)).rootNode,s=R(n,"class");if(s.length===0)return null;let a=s[0],r=F(a),c=M(a);if(!r)return null;c&&this.isActiveRecordModel(c);let i={name:r.replace(/.*::/,""),filePath:t,className:r,parentClass:c||"ApplicationRecord",associations:[],validations:[],callbacks:[],scopes:[],concerns:[],enums:[],attributes:[],classMethodsCount:0,instanceMethodsCount:0,line:a.startPosition.row+1};i.tableName=this.parseTableName(a);let u=R(a,"call");for(let d of u){let y=d.childForFieldName("method");if(!y)continue;let f=y.text,g=d.startPosition.row+1;["belongs_to","has_one","has_many","has_and_belongs_to_many"].includes(f)?this.parseAssociation(d,f,i.associations,g):f.startsWith("validates")||f==="validate"?this.parseValidation(d,f,i.validations,g):this.isCallback(f)?this.parseCallback(d,f,i.callbacks,g):f==="scope"?this.parseScope(d,i.scopes,g):f==="include"?this.parseInclude(d,i.concerns):f==="enum"?this.parseEnum(d,i.enums,g):f==="attribute"&&this.parseAttribute(d,i.attributes,g);}let p=R(a,"method"),m=R(a,"singleton_method");return i.instanceMethodsCount=p.length,i.classMethodsCount=m.length,i}isActiveRecordModel(e){return ["ApplicationRecord","ActiveRecord::Base","ActiveRecord"].some(o=>e.includes(o))}parseTableName(e){let t=R(e,"call");for(let n of t)if(n.childForFieldName("method")?.text==="table_name="){let a=this.getCallArguments(n);if(a.length>0)return a[0].text.replace(/^["']|["']$/g,"")}let o=R(e,"assignment");for(let n of o)if(n.child(0)?.text?.includes("table_name")){let a=n.child(2);if(a)return a.text.replace(/^["']|["']$/g,"")}}parseAssociation(e,t,o,n){let s=this.getCallArguments(e);if(s.length===0)return;let r=s[0].text.replace(/^:/,""),c={type:t,name:r,line:n};for(let i of s.slice(1))if(i.type==="hash"){let u=w(i,"pair");for(let p of u){let m=p.child(0)?.text?.replace(/^:/,""),d=p.child(2);if(!(!m||!d))switch(m){case "class_name":c.className=d.text.replace(/^["']|["']$/g,"");break;case "foreign_key":c.foreignKey=d.text.replace(/^["']|["']$/g,"").replace(/^:/,"");break;case "through":c.through=d.text.replace(/^:/,"");break;case "polymorphic":c.polymorphic=d.text==="true";break;case "dependent":c.dependent=d.text.replace(/^:/,"");break;case "optional":c.optional=d.text==="true";break}}}o.push(c);}parseValidation(e,t,o,n){let s=this.getCallArguments(e);if(s.length===0)return;let a=[],r={},c=t;for(let i of s)if(i.type==="simple_symbol"||i.type==="symbol")a.push(i.text.replace(/^:/,""));else if(i.type==="hash"){let u=w(i,"pair");for(let p of u){let m=p.child(0)?.text?.replace(/^:/,""),d=p.child(2);m&&d&&(["presence","uniqueness","numericality","length","format","inclusion","exclusion","acceptance","confirmation"].includes(m)&&(c=m),r[m]=d.text);}}(a.length>0||t==="validate")&&o.push({type:c,attributes:a,options:Object.keys(r).length>0?r:void 0,line:n});}isCallback(e){return ["before_validation","after_validation","before_save","around_save","after_save","before_create","around_create","after_create","before_update","around_update","after_update","before_destroy","around_destroy","after_destroy","after_commit","after_rollback","after_initialize","after_find","after_touch"].includes(e)}parseCallback(e,t,o,n){let s=this.getCallArguments(e);if(s.length===0)return;let r=s[0].text.replace(/^:/,""),c={type:t,method:r,line:n};for(let i of s.slice(1))if(i.type==="hash"){let u=w(i,"pair");for(let p of u){let m=p.child(0)?.text?.replace(/^:/,""),d=p.child(2);m&&d&&["if","unless"].includes(m)&&(c.conditions=`${m}: ${d.text}`);}}o.push(c);}parseScope(e,t,o){let n=this.getCallArguments(e);if(n.length===0)return;let a=n[0].text.replace(/^:/,""),r=n.length>1&&(n[1].type==="lambda"||n[1].text.includes("->"));t.push({name:a,lambda:r,line:o});}parseInclude(e,t){let o=this.getCallArguments(e);for(let n of o)(n.type==="constant"||n.type==="scope_resolution")&&t.push(n.text);}parseEnum(e,t,o){let n=this.getCallArguments(e);if(n.length!==0){for(let s of n)if(s.type==="hash"){let a=w(s,"pair");for(let r of a){let c=r.child(0)?.text?.replace(/^:/,""),i=r.child(2);if(c&&i&&i.type==="hash"){let u=[],p=w(i,"pair");for(let m of p){let d=m.child(0)?.text?.replace(/^:/,"");d&&u.push(d);}t.push({name:c,values:u,line:o});}else if(c&&i&&i.type==="array"){let u=[];for(let p=0;p<i.childCount;p++){let m=i.child(p);m&&m.type!=="["&&m.type!=="]"&&m.type!==","&&u.push(m.text.replace(/^:/,""));}t.push({name:c,values:u,line:o});}}}}}parseAttribute(e,t,o){let n=this.getCallArguments(e);if(n.length===0)return;let r={name:n[0].text.replace(/^:/,""),line:o};if(n.length>1){let c=n[1];r.type=c.text.replace(/^:/,"");}for(let c of n)if(c.type==="hash"){let i=w(c,"pair");for(let u of i){let p=u.child(0)?.text?.replace(/^:/,""),m=u.child(2);p==="default"&&m&&(r.default=m.text);}}t.push(r);}getCallArguments(e){let t=e.childForFieldName("arguments");if(!t){let n=[];for(let s=0;s<e.childCount;s++){let a=e.child(s);a&&!["identifier","(",")",",","call"].includes(a.type)&&a!==e.childForFieldName("method")&&a!==e.childForFieldName("receiver")&&n.push(a);}return n}let o=[];for(let n=0;n<t.childCount;n++){let s=t.child(n);s&&s.type!=="("&&s.type!==")"&&s.type!==","&&o.push(s);}return o}};async function xe(){let l=process.argv[2]||process.cwd();console.log(`Analyzing models in: ${l}`);let t=await new j(l).analyze();if(console.log(`
13
+ --- Action Visibility Summary ---`),console.log(` Public: ${o.length}`),console.log(` Private: ${n.length}`);}var ye=import.meta.url===`file://${process.argv[1]}`;ye&&ge().catch(console.error);var j=class{constructor(e){this.rootPath=e;this.modelsDir=x.join(e,"app","models");}modelsDir;models=[];errors=[];async analyze(){if(!G.existsSync(this.modelsDir))return {models:[],totalAssociations:0,totalValidations:0,concerns:[],namespaces:[],errors:[`Models directory not found at ${this.modelsDir}`]};let e=await glob("**/*.rb",{cwd:this.modelsDir,ignore:["concerns/**","application_record.rb"]});for(let a of e){let r=x.join(this.modelsDir,a);try{let c=await this.parseModelFile(r,a);c&&this.models.push(c);}catch(c){this.errors.push(`Error parsing ${a}: ${c}`);}}let t=[...new Set(this.models.flatMap(a=>a.concerns))],o=[...new Set(this.models.map(a=>{let r=a.filePath.split("/");return r.length>1?r.slice(0,-1).join("/"):null}).filter(a=>a!==null))],n=this.models.reduce((a,r)=>a+r.associations.length,0),s=this.models.reduce((a,r)=>a+r.validations.length,0);return {models:this.models,totalAssociations:n,totalValidations:s,concerns:t,namespaces:o,errors:this.errors}}async parseModelFile(e,t){let n=(await N(e)).rootNode,s=R(n,"class");if(s.length===0)return null;let a=s[0],r=F(a),c=M(a);if(!r)return null;c&&this.isActiveRecordModel(c);let i={name:r.replace(/.*::/,""),filePath:t,className:r,parentClass:c||"ApplicationRecord",associations:[],validations:[],callbacks:[],scopes:[],concerns:[],enums:[],attributes:[],classMethodsCount:0,instanceMethodsCount:0,line:a.startPosition.row+1};i.tableName=this.parseTableName(a);let u=R(a,"call");for(let f of u){let y=f.childForFieldName("method");if(!y)continue;let m=y.text,g=f.startPosition.row+1;["belongs_to","has_one","has_many","has_and_belongs_to_many"].includes(m)?this.parseAssociation(f,m,i.associations,g):m.startsWith("validates")||m==="validate"?this.parseValidation(f,m,i.validations,g):this.isCallback(m)?this.parseCallback(f,m,i.callbacks,g):m==="scope"?this.parseScope(f,i.scopes,g):m==="include"?this.parseInclude(f,i.concerns):m==="enum"?this.parseEnum(f,i.enums,g):m==="attribute"&&this.parseAttribute(f,i.attributes,g);}let p=R(a,"method"),d=R(a,"singleton_method");return i.instanceMethodsCount=p.length,i.classMethodsCount=d.length,i}isActiveRecordModel(e){return ["ApplicationRecord","ActiveRecord::Base","ActiveRecord"].some(o=>e.includes(o))}parseTableName(e){let t=R(e,"call");for(let n of t)if(n.childForFieldName("method")?.text==="table_name="){let a=this.getCallArguments(n);if(a.length>0)return a[0].text.replace(/^["']|["']$/g,"")}let o=R(e,"assignment");for(let n of o)if(n.child(0)?.text?.includes("table_name")){let a=n.child(2);if(a)return a.text.replace(/^["']|["']$/g,"")}}parseAssociation(e,t,o,n){let s=this.getCallArguments(e);if(s.length===0)return;let r=s[0].text.replace(/^:/,""),c={type:t,name:r,line:n};for(let i of s.slice(1))if(i.type==="hash"){let u=w(i,"pair");for(let p of u){let d=p.child(0)?.text?.replace(/^:/,""),f=p.child(2);if(!(!d||!f))switch(d){case "class_name":c.className=f.text.replace(/^["']|["']$/g,"");break;case "foreign_key":c.foreignKey=f.text.replace(/^["']|["']$/g,"").replace(/^:/,"");break;case "through":c.through=f.text.replace(/^:/,"");break;case "polymorphic":c.polymorphic=f.text==="true";break;case "dependent":c.dependent=f.text.replace(/^:/,"");break;case "optional":c.optional=f.text==="true";break}}}o.push(c);}parseValidation(e,t,o,n){let s=this.getCallArguments(e);if(s.length===0)return;let a=[],r={},c=t;for(let i of s)if(i.type==="simple_symbol"||i.type==="symbol")a.push(i.text.replace(/^:/,""));else if(i.type==="hash"){let u=w(i,"pair");for(let p of u){let d=p.child(0)?.text?.replace(/^:/,""),f=p.child(2);d&&f&&(["presence","uniqueness","numericality","length","format","inclusion","exclusion","acceptance","confirmation"].includes(d)&&(c=d),r[d]=f.text);}}(a.length>0||t==="validate")&&o.push({type:c,attributes:a,options:Object.keys(r).length>0?r:void 0,line:n});}isCallback(e){return ["before_validation","after_validation","before_save","around_save","after_save","before_create","around_create","after_create","before_update","around_update","after_update","before_destroy","around_destroy","after_destroy","after_commit","after_rollback","after_initialize","after_find","after_touch"].includes(e)}parseCallback(e,t,o,n){let s=this.getCallArguments(e);if(s.length===0)return;let r=s[0].text.replace(/^:/,""),c={type:t,method:r,line:n};for(let i of s.slice(1))if(i.type==="hash"){let u=w(i,"pair");for(let p of u){let d=p.child(0)?.text?.replace(/^:/,""),f=p.child(2);d&&f&&["if","unless"].includes(d)&&(c.conditions=`${d}: ${f.text}`);}}o.push(c);}parseScope(e,t,o){let n=this.getCallArguments(e);if(n.length===0)return;let a=n[0].text.replace(/^:/,""),r=n.length>1&&(n[1].type==="lambda"||n[1].text.includes("->"));t.push({name:a,lambda:r,line:o});}parseInclude(e,t){let o=this.getCallArguments(e);for(let n of o)(n.type==="constant"||n.type==="scope_resolution")&&t.push(n.text);}parseEnum(e,t,o){let n=this.getCallArguments(e);if(n.length!==0){for(let s of n)if(s.type==="hash"){let a=w(s,"pair");for(let r of a){let c=r.child(0)?.text?.replace(/^:/,""),i=r.child(2);if(c&&i&&i.type==="hash"){let u=[],p=w(i,"pair");for(let d of p){let f=d.child(0)?.text?.replace(/^:/,"");f&&u.push(f);}t.push({name:c,values:u,line:o});}else if(c&&i&&i.type==="array"){let u=[];for(let p=0;p<i.childCount;p++){let d=i.child(p);d&&d.type!=="["&&d.type!=="]"&&d.type!==","&&u.push(d.text.replace(/^:/,""));}t.push({name:c,values:u,line:o});}}}}}parseAttribute(e,t,o){let n=this.getCallArguments(e);if(n.length===0)return;let r={name:n[0].text.replace(/^:/,""),line:o};if(n.length>1){let c=n[1];r.type=c.text.replace(/^:/,"");}for(let c of n)if(c.type==="hash"){let i=w(c,"pair");for(let u of i){let p=u.child(0)?.text?.replace(/^:/,""),d=u.child(2);p==="default"&&d&&(r.default=d.text);}}t.push(r);}getCallArguments(e){let t=e.childForFieldName("arguments");if(!t){let n=[];for(let s=0;s<e.childCount;s++){let a=e.child(s);a&&!["identifier","(",")",",","call"].includes(a.type)&&a!==e.childForFieldName("method")&&a!==e.childForFieldName("receiver")&&n.push(a);}return n}let o=[];for(let n=0;n<t.childCount;n++){let s=t.child(n);s&&s.type!=="("&&s.type!==")"&&s.type!==","&&o.push(s);}return o}};async function xe(){let l=process.argv[2]||process.cwd();console.log(`Analyzing models in: ${l}`);let t=await new j(l).analyze();if(console.log(`
14
14
  === Rails Models Analysis ===
15
15
  `),console.log(`Total models: ${t.models.length}`),console.log(`Total associations: ${t.totalAssociations}`),console.log(`Total validations: ${t.totalValidations}`),console.log(`Shared concerns: ${t.concerns.length}`),console.log(`Namespaces: ${t.namespaces.join(", ")||"(none)"}`),t.errors.length>0){console.log(`
16
16
  --- Errors (${t.errors.length}) ---`);for(let r of t.errors.slice(0,5))console.log(` \u274C ${r}`);t.errors.length>5&&console.log(` ... and ${t.errors.length-5} more`);}console.log(`
17
17
  --- Sample Models (first 15) ---`);for(let r of t.models.slice(0,15)){if(console.log(`
18
18
  \u{1F4E6} ${r.className} (${r.filePath})`),console.log(` Parent: ${r.parentClass}`),r.associations.length>0){let c=r.associations.slice(0,3).map(i=>`${i.type} :${i.name}`);console.log(` Associations: ${c.join(", ")}${r.associations.length>3?"...":""}`);}if(r.validations.length>0&&console.log(` Validations: ${r.validations.length}`),r.scopes.length>0){let c=r.scopes.slice(0,3).map(i=>i.name);console.log(` Scopes: ${c.join(", ")}${r.scopes.length>3?"...":""}`);}if(r.enums.length>0){let c=r.enums.map(i=>`${i.name}(${i.values.length})`);console.log(` Enums: ${c.join(", ")}`);}r.concerns.length>0&&console.log(` Concerns: ${r.concerns.slice(0,3).join(", ")}${r.concerns.length>3?"...":""}`);}let o=t.models.flatMap(r=>r.associations),n=o.filter(r=>r.type==="belongs_to").length,s=o.filter(r=>r.type==="has_many").length,a=o.filter(r=>r.type==="has_one").length;console.log(`
19
- --- Association Summary ---`),console.log(` belongs_to: ${n}`),console.log(` has_many: ${s}`),console.log(` has_one: ${a}`);}var Re=import.meta.url===`file://${process.argv[1]}`;Re&&xe().catch(console.error);var T=class{constructor(e){this.rootPath=e;this.grpcDir=x.join(e,"app","grpc_services");}grpcDir;services=[];errors=[];async analyze(){if(!G.existsSync(this.grpcDir))return {services:[],totalRpcs:0,namespaces:[],errors:[`gRPC services directory not found at ${this.grpcDir}`]};let e=await glob("**/*_grpc_service.rb",{cwd:this.grpcDir});for(let n of e){let s=x.join(this.grpcDir,n);try{let a=await this.parseServiceFile(s,n);a&&this.services.push(a);}catch(a){this.errors.push(`Error parsing ${n}: ${a}`);}}let t=[...new Set(this.services.filter(n=>n.namespace).map(n=>n.namespace))],o=this.services.reduce((n,s)=>n+s.rpcs.length,0);return {services:this.services,totalRpcs:o,namespaces:t,errors:this.errors}}async parseServiceFile(e,t){let n=(await N(e)).rootNode,s=t.replace(/_grpc_service\.rb$/,"").split("/"),a=s.length>1?s.slice(0,-1).join("/"):void 0,r=s[s.length-1],c=R(n,"class");if(c.length===0)return null;let i=c[0],u=F(i),p=M(i);if(!u)return null;let m={name:r,filePath:t,className:u,parentClass:p||"Unknown",namespace:a,rpcs:[],policies:[],serializers:[],concerns:[],line:i.startPosition.row+1};p&&p.match(/(\w+)::Service$/)&&(m.protoService=p.replace("::Service",""));let d=R(i,"call");for(let h of d)if(h.childForFieldName("method")?.text==="include"){let v=this.getCallArguments(h);for(let C of v)(C.type==="constant"||C.type==="scope_resolution")&&m.concerns.push(C.text);}R(i,"method");let f="public",g=i.childForFieldName("body");if(g)for(let h=0;h<g.childCount;h++){let b=g.child(h);if(b){if(b.type==="identifier"){let v=b.text;v==="private"?f="private":v==="protected"?f="protected":v==="public"&&(f="public");}else if(b.type==="method"&&f==="public"){let v=this.parseRpcMethod(b);if(v){let C=R(b,"call");for(let X of C){let B=X.childForFieldName("method")?.text,_=X.childForFieldName("receiver")?.text;(B==="authorize!"||B==="new")&&_?.includes("Policy")&&(m.policies.includes(_)||m.policies.push(_),v.policyMethod="authorize!"),_?.includes("Serializer")&&B==="new"&&(m.serializers.includes(_)||m.serializers.push(_));}m.rpcs.push(v);}}}}return m}parseRpcMethod(e){let t=U(e);if(!t||["initialize","to_s","inspect","call","perform","execute"].includes(t))return null;Z(e);let s=e.text,a={name:t,line:e.startPosition.row+1,streaming:"none",modelsUsed:[],servicesUsed:[]},r=s.match(/@param\s+\[([^\]]+)\]\s+req/);r&&(a.requestType=r[1]);let c=s.match(/@return\s+\[([^\]]+)\]/);c&&(a.responseType=c[1]);let i=s.matchAll(/\b([A-Z][a-zA-Z]+)\.(find|find_by|where|all|first|last|create|joins|includes)\b/g);for(let p of i){let m=p[1];!["Rails","ActiveRecord","GRPC","Visit","Google"].includes(m)&&!a.modelsUsed.includes(m)&&a.modelsUsed.push(m);}let u=s.matchAll(/\b(\w+Service)\.(call|new|perform)\b/g);for(let p of u){let m=p[1];a.servicesUsed.includes(m)||a.servicesUsed.push(m);}return a}getCallArguments(e){let t=e.childForFieldName("arguments");if(!t){let n=[];for(let s=0;s<e.childCount;s++){let a=e.child(s);a&&!["identifier","(",")",",","call"].includes(a.type)&&a!==e.childForFieldName("method")&&a!==e.childForFieldName("receiver")&&n.push(a);}return n}let o=[];for(let n=0;n<t.childCount;n++){let s=t.child(n);s&&s.type!=="("&&s.type!==")"&&s.type!==","&&o.push(s);}return o}};async function we(){let l=process.argv[2]||process.cwd();console.log(`Analyzing gRPC services in: ${l}`);let t=await new T(l).analyze();if(console.log(`
19
+ --- Association Summary ---`),console.log(` belongs_to: ${n}`),console.log(` has_many: ${s}`),console.log(` has_one: ${a}`);}var Re=import.meta.url===`file://${process.argv[1]}`;Re&&xe().catch(console.error);var T=class{constructor(e){this.rootPath=e;this.grpcDir=x.join(e,"app","grpc_services");}grpcDir;services=[];errors=[];async analyze(){if(!G.existsSync(this.grpcDir))return {services:[],totalRpcs:0,namespaces:[],errors:[`gRPC services directory not found at ${this.grpcDir}`]};let e=await glob("**/*_grpc_service.rb",{cwd:this.grpcDir});for(let n of e){let s=x.join(this.grpcDir,n);try{let a=await this.parseServiceFile(s,n);a&&this.services.push(a);}catch(a){this.errors.push(`Error parsing ${n}: ${a}`);}}let t=[...new Set(this.services.filter(n=>n.namespace).map(n=>n.namespace))],o=this.services.reduce((n,s)=>n+s.rpcs.length,0);return {services:this.services,totalRpcs:o,namespaces:t,errors:this.errors}}async parseServiceFile(e,t){let n=(await N(e)).rootNode,s=t.replace(/_grpc_service\.rb$/,"").split("/"),a=s.length>1?s.slice(0,-1).join("/"):void 0,r=s[s.length-1],c=R(n,"class");if(c.length===0)return null;let i=c[0],u=F(i),p=M(i);if(!u)return null;let d={name:r,filePath:t,className:u,parentClass:p||"Unknown",namespace:a,rpcs:[],policies:[],serializers:[],concerns:[],line:i.startPosition.row+1};p&&p.match(/(\w+)::Service$/)&&(d.protoService=p.replace("::Service",""));let f=R(i,"call");for(let h of f)if(h.childForFieldName("method")?.text==="include"){let v=this.getCallArguments(h);for(let C of v)(C.type==="constant"||C.type==="scope_resolution")&&d.concerns.push(C.text);}R(i,"method");let m="public",g=i.childForFieldName("body");if(g)for(let h=0;h<g.childCount;h++){let b=g.child(h);if(b){if(b.type==="identifier"){let v=b.text;v==="private"?m="private":v==="protected"?m="protected":v==="public"&&(m="public");}else if(b.type==="method"&&m==="public"){let v=this.parseRpcMethod(b);if(v){let C=R(b,"call");for(let X of C){let B=X.childForFieldName("method")?.text,_=X.childForFieldName("receiver")?.text;(B==="authorize!"||B==="new")&&_?.includes("Policy")&&(d.policies.includes(_)||d.policies.push(_),v.policyMethod="authorize!"),_?.includes("Serializer")&&B==="new"&&(d.serializers.includes(_)||d.serializers.push(_));}d.rpcs.push(v);}}}}return d}parseRpcMethod(e){let t=U(e);if(!t||["initialize","to_s","inspect","call","perform","execute"].includes(t))return null;Z(e);let s=e.text,a={name:t,line:e.startPosition.row+1,streaming:"none",modelsUsed:[],servicesUsed:[]},r=s.match(/@param\s+\[([^\]]+)\]\s+req/);r&&(a.requestType=r[1]);let c=s.match(/@return\s+\[([^\]]+)\]/);c&&(a.responseType=c[1]);let i=s.matchAll(/\b([A-Z][a-zA-Z]+)\.(find|find_by|where|all|first|last|create|joins|includes)\b/g);for(let p of i){let d=p[1];!["Rails","ActiveRecord","GRPC","Visit","Google"].includes(d)&&!a.modelsUsed.includes(d)&&a.modelsUsed.push(d);}let u=s.matchAll(/\b(\w+Service)\.(call|new|perform)\b/g);for(let p of u){let d=p[1];a.servicesUsed.includes(d)||a.servicesUsed.push(d);}return a}getCallArguments(e){let t=e.childForFieldName("arguments");if(!t){let n=[];for(let s=0;s<e.childCount;s++){let a=e.child(s);a&&!["identifier","(",")",",","call"].includes(a.type)&&a!==e.childForFieldName("method")&&a!==e.childForFieldName("receiver")&&n.push(a);}return n}let o=[];for(let n=0;n<t.childCount;n++){let s=t.child(n);s&&s.type!=="("&&s.type!==")"&&s.type!==","&&o.push(s);}return o}};async function we(){let l=process.argv[2]||process.cwd();console.log(`Analyzing gRPC services in: ${l}`);let t=await new T(l).analyze();if(console.log(`
20
20
  === Rails gRPC Services Analysis ===
21
21
  `),console.log(`Total services: ${t.services.length}`),console.log(`Total RPCs: ${t.totalRpcs}`),console.log(`Namespaces: ${t.namespaces.join(", ")||"(none)"}`),t.errors.length>0){console.log(`
22
22
  --- Errors (${t.errors.length}) ---`);for(let s of t.errors.slice(0,5))console.log(` \u274C ${s}`);}console.log(`
23
23
  --- Sample Services (first 15) ---`);for(let s of t.services.slice(0,15))console.log(`
24
24
  \u{1F4E1} ${s.className} (${s.filePath})`),console.log(` Proto: ${s.protoService||"unknown"}`),console.log(` RPCs (${s.rpcs.length}): ${s.rpcs.map(a=>a.name).join(", ")}`),s.policies.length>0&&console.log(` Policies: ${s.policies.join(", ")}`),s.serializers.length>0&&console.log(` Serializers: ${s.serializers.join(", ")}`);let o=t.services.flatMap(s=>s.rpcs),n=o.filter(s=>s.modelsUsed.length>0);console.log(`
25
- --- RPC Summary ---`),console.log(` Total RPCs: ${o.length}`),console.log(` RPCs using models: ${n.length}`);}var Ae=import.meta.url===`file://${process.argv[1]}`;Ae&&we().catch(console.error);async function K(l){let e=x.join(l,"app/views"),t=x.join(l,"app/controllers");try{await A.access(e);}catch{return {views:[],pages:[],summary:{totalViews:0,totalPages:0,byController:{},byTemplate:{}}}}let o=await glob("**/*.{haml,erb,html.haml,html.erb,yml}",{cwd:e,nodir:true}),n=[],s={},a={};for(let c of o){let i=await Ce(e,c);i&&(n.push(i),s[i.controller]=(s[i.controller]||0)+1,a[i.template]=(a[i.template]||0)+1);}let r=await Fe(t,n,l);return {views:n,pages:r,summary:{totalViews:n.length,totalPages:r.length,byController:s,byTemplate:a}}}async function Ce(l,e){let t=x.join(l,e);try{let o=await A.readFile(t,"utf-8"),n=e.split("/");if(n.some(g=>g.endsWith("_mailer")||g==="layouts"||g==="shared"||g==="devise"))return null;let s=n.pop()||"",a=n.join("/")||"application",r=s.split("."),c=r[0].replace(/^_/,""),i=s.startsWith("_"),u;s.endsWith(".yml")?u="yml":s.endsWith(".haml")?u="haml":s.endsWith(".erb")?u="erb":u="other";let p=r.length>2?r[1]:"html";if(i)return null;let m=[],d=[],y=[],f=[];return u==="yml"?(y=_e(o),f=[{name:"App",ssr:!0,propsVar:"@yml_data"}]):(m=Ne(o,u),d=Se(o,u),y=$e(o),f=Pe(o,u)),{name:c,path:e,controller:a,action:c,format:p,template:u,partials:m,helpers:d,instanceVars:y,reactComponents:f}}catch{return null}}function Ne(l,e){let t=[];if(e==="haml"){let o=l.matchAll(/=\s*render\s+(?:partial:\s*)?['"]([^'"]+)['"]/g);for(let n of o)t.push(n[1]);}else if(e==="erb"){let o=l.matchAll(/<%=?\s*render\s+(?:partial:\s*)?['"]([^'"]+)['"]/g);for(let n of o)t.push(n[1]);}return [...new Set(t)]}function Se(l,e){let t=[],o=/\b(link_to|form_for|form_with|image_tag|content_for|yield|render|t|l|raw|html_safe|simple_form_for)\b/g,n=l.matchAll(o);for(let s of n)t.push(s[1]);return [...new Set(t)]}function Pe(l,e){let t=[],o=/render_react_component\s*\(?\s*["']([^"']+)["'](?:,\s*\{[^}]*\})?\s*(?:,\s*ssr:\s*(true|false))?\)?/g,n;for(;(n=o.exec(l))!==null;)t.push({name:n[1],ssr:n[2]==="true"});let s=/data:\s*\{\s*react_component:\s*["']([^"']+)["'](?:,\s*react_component_props:\s*(@?\w+)(?:\.to_json)?)?/g;for(;(n=s.exec(l))!==null;)t.push({name:n[1],propsVar:n[2],ssr:false});let a=/ReactComponent\s+name=["']([^"']+)["']/g;for(;(n=a.exec(l))!==null;)t.push({name:n[1],ssr:false});let r=new Set;return t.filter(c=>r.has(c.name)?false:(r.add(c.name),true))}function _e(l){let e=[],t=l.split(`
26
- `);for(let o of t){let n=o.match(/^([a-z_]+):/);n&&!n[1].startsWith("_")&&e.push(n[1]);let s=o.match(/^\s+-\s+(\w+)/);s&&e.push(s[1]);}return [...new Set(e)].slice(0,50)}function $e(l){let e=[],t=l.matchAll(/@(\w+)/g);for(let o of t)["import","media","keyframes","charset"].includes(o[1])||e.push(o[1]);return [...new Set(e)]}async function Fe(l,e,t){let o=[];try{await A.access(l);}catch{return o}let n=await glob("**/*_controller.rb",{cwd:l,nodir:true}),s=await Me(t);for(let a of n){let r=x.join(l,a),c=await A.readFile(r,"utf-8"),i=a.replace(/_controller\.rb$/,"").replace(/\//g,"/"),u=Ie(c,i,a,e,s);o.push(...u);}return o}async function Me(l){let e=new Map;try{let t=x.join(l,".repomap","rails-routes.json"),o=await A.readFile(t,"utf-8"),n=JSON.parse(o);for(let s of n){let a=`${s.controller}#${s.action}`;e.set(a,{path:s.path,method:s.method});}}catch{}return e}function Ie(l,e,t,o,n){let s=[],a=l.split(/\n\s*(private|protected)\b/)[0],r=/def\s+(\w+)/g,c;for(;(c=r.exec(a))!==null;){let i=c[1];["initialize","new","create","update","destroy","index","show","edit"].includes(i)||i.startsWith("set_")||i.startsWith("_");let u=c.index,p=ke(a,u),m=Ve(p,t),d=je(p),y=Te(p),f=ze(p),g=o.find(v=>v.controller===e&&v.action===i),h=`${e}#${i}`,b=n.get(h);s.push({route:b?.path||`/${e}/${i}`,method:b?.method||"GET",controller:e,action:i,view:g,apis:m,services:d,grpcCalls:y,modelAccess:f});}return s}function ke(l,e){let t=0,o=false,n="";for(let s=e;s<l.length;s++){let a=l.slice(s,l.indexOf(`
25
+ --- RPC Summary ---`),console.log(` Total RPCs: ${o.length}`),console.log(` RPCs using models: ${n.length}`);}var Ae=import.meta.url===`file://${process.argv[1]}`;Ae&&we().catch(console.error);async function K(l){let e=x.join(l,"app/views"),t=x.join(l,"app/controllers");try{await A.access(e);}catch{return {views:[],pages:[],summary:{totalViews:0,totalPages:0,byController:{},byTemplate:{}}}}let o=await glob("**/*.{haml,erb,html.haml,html.erb,yml}",{cwd:e,nodir:true}),n=[],s={},a={};for(let c of o){let i=await Ce(e,c);i&&(n.push(i),s[i.controller]=(s[i.controller]||0)+1,a[i.template]=(a[i.template]||0)+1);}let r=await Fe(t,n,l);return {views:n,pages:r,summary:{totalViews:n.length,totalPages:r.length,byController:s,byTemplate:a}}}async function Ce(l,e){let t=x.join(l,e);try{let o=await A.readFile(t,"utf-8"),n=e.split("/");if(n.some(g=>g.endsWith("_mailer")||g==="layouts"||g==="shared"||g==="devise"))return null;let s=n.pop()||"",a=n.join("/")||"application",r=s.split("."),c=r[0].replace(/^_/,""),i=s.startsWith("_"),u;s.endsWith(".yml")?u="yml":s.endsWith(".haml")?u="haml":s.endsWith(".erb")?u="erb":u="other";let p=r.length>2?r[1]:"html";if(i)return null;let d=[],f=[],y=[],m=[];return u==="yml"?(y=_e(o),m=[{name:"App",ssr:!0,propsVar:"@yml_data"}]):(d=Ne(o,u),f=Se(o,u),y=$e(o),m=Pe(o,u)),{name:c,path:e,controller:a,action:c,format:p,template:u,partials:d,helpers:f,instanceVars:y,reactComponents:m}}catch{return null}}function Ne(l,e){let t=[];if(e==="haml"){let o=l.matchAll(/=\s*render\s+(?:partial:\s*)?['"]([^'"]+)['"]/g);for(let n of o)t.push(n[1]);}else if(e==="erb"){let o=l.matchAll(/<%=?\s*render\s+(?:partial:\s*)?['"]([^'"]+)['"]/g);for(let n of o)t.push(n[1]);}return [...new Set(t)]}function Se(l,e){let t=[],o=/\b(link_to|form_for|form_with|image_tag|content_for|yield|render|t|l|raw|html_safe|simple_form_for)\b/g,n=l.matchAll(o);for(let s of n)t.push(s[1]);return [...new Set(t)]}function Pe(l,e){let t=[],o=/render_react_component\s*\(?\s*["']([^"']+)["'](?:,\s*\{[^}]*\})?\s*(?:,\s*ssr:\s*(true|false))?\)?/g,n;for(;(n=o.exec(l))!==null;)t.push({name:n[1],ssr:n[2]==="true"});let s=/data:\s*\{\s*react_component:\s*["']([^"']+)["'](?:,\s*react_component_props:\s*(@?\w+)(?:\.to_json)?)?/g;for(;(n=s.exec(l))!==null;)t.push({name:n[1],propsVar:n[2],ssr:false});let a=/ReactComponent\s+name=["']([^"']+)["']/g;for(;(n=a.exec(l))!==null;)t.push({name:n[1],ssr:false});let r=new Set;return t.filter(c=>r.has(c.name)?false:(r.add(c.name),true))}function _e(l){let e=[],t=l.split(`
26
+ `);for(let o of t){let n=o.match(/^([a-z_]+):/);n&&!n[1].startsWith("_")&&e.push(n[1]);let s=o.match(/^\s+-\s+(\w+)/);s&&e.push(s[1]);}return [...new Set(e)].slice(0,50)}function $e(l){let e=[],t=l.matchAll(/@(\w+)/g);for(let o of t)["import","media","keyframes","charset"].includes(o[1])||e.push(o[1]);return [...new Set(e)]}async function Fe(l,e,t){let o=[];try{await A.access(l);}catch{return o}let n=await glob("**/*_controller.rb",{cwd:l,nodir:true}),s=await Me(t);for(let a of n){let r=x.join(l,a),c=await A.readFile(r,"utf-8"),i=a.replace(/_controller\.rb$/,"").replace(/\//g,"/"),u=Ie(c,i,a,e,s);o.push(...u);}return o}async function Me(l){let e=new Map;try{let t=x.join(l,".repomap","rails-routes.json"),o=await A.readFile(t,"utf-8"),n=JSON.parse(o);for(let s of n){let a=`${s.controller}#${s.action}`;e.set(a,{path:s.path,method:s.method});}}catch{}return e}function Ie(l,e,t,o,n){let s=[],a=l.split(/\n\s*(private|protected)\b/)[0],r=/def\s+(\w+)/g,c;for(;(c=r.exec(a))!==null;){let i=c[1];["initialize","new","create","update","destroy","index","show","edit"].includes(i)||i.startsWith("set_")||i.startsWith("_");let u=c.index,p=ke(a,u),d=Ve(p,t),f=je(p),y=Te(p),m=ze(p),g=o.find(v=>v.controller===e&&v.action===i),h=`${e}#${i}`,b=n.get(h);s.push({route:b?.path||`/${e}/${i}`,method:b?.method||"GET",controller:e,action:i,view:g,apis:d,services:f,grpcCalls:y,modelAccess:m});}return s}function ke(l,e){let t=0,o=false,n="";for(let s=e;s<l.length;s++){let a=l.slice(s,l.indexOf(`
27
27
  `,s)+1||l.length);if(a.match(/^\s*(def|class|module|if|unless|case|while|until|for|begin|do)\b/)&&(t++,o=true),a.match(/^\s*end\b/)&&(t--,o&&t===0)||(n+=a,s=l.indexOf(`
28
- `,s),s===-1))break}return n}function Ve(l,e){let t=[],o=[/HTTPClient\.(get|post|put|patch|delete)\s*\(\s*['"]([^'"]+)['"]/gi,/RestClient\.(get|post|put|patch|delete)\s*\(\s*['"]([^'"]+)['"]/gi,/Faraday\.(get|post|put|patch|delete)\s*\(\s*['"]([^'"]+)['"]/gi,/Net::HTTP\.(get|post)\s*\(/gi];for(let n of o){let s;for(;(s=n.exec(l))!==null;)t.push({type:"http",name:s[2]||"HTTP call",method:s[1]?.toUpperCase(),source:e});}return t}function je(l){let e=[],t=/(\w+(?:::\w+)*Service)\.(?:call!?|new)/g,o;for(;(o=t.exec(l))!==null;)e.push(o[1]);return [...new Set(e)]}function Te(l){let e=[],t=[/(\w+(?:::\w+)*Grpc(?:::\w+)?)\./g,/Grpc::(\w+(?:::\w+)*)/g,/(\w+GrpcService)\./g];for(let o of t){let n;for(;(n=o.exec(l))!==null;)e.push(n[1]);}return [...new Set(e)]}function ze(l){let e=[],t=/([A-Z][a-zA-Z0-9]+)\.(?:find|where|find_by|first|last|all|create|update|destroy|new)/g,o;for(;(o=t.exec(l))!==null;)["File","Dir","Time","Date","DateTime","JSON","YAML","CSV","Logger"].includes(o[1])||e.push(o[1]);return [...new Set(e)]}var Ee=["app/javascript/packs","app/javascript/entrypoints","app/frontend/entrypoints","app/javascript/application","frontend/assets/javascripts/entries","frontend/entries","app/assets/javascripts/entries","client/entries","src/entries"],De=["app/javascript/components","app/javascript/react","app/javascript/src/components","app/javascript/bundles","app/frontend/components","app/frontend/react","frontend/assets/javascripts/react","frontend/assets/javascripts/components","frontend/src","frontend/src/components","frontend/components","client/components","src/components"],E={dataReactComponent:/react_component:\s*["']([A-Za-z0-9_/]+)["']/g,renderReactComponent:/render_react_component\s*\(?\s*["']([A-Za-z0-9_/]+)["']/g,reactComponent:/<%=?\s*react_component\s*\(\s*["']([A-Za-z0-9_/]+)["']/g,reduxStore:/<%=?\s*redux_store\s*\(\s*["']([A-Za-z0-9_/]+)["']/g,dataComponent:/data-component\s*[=:]\s*["']([A-Za-z0-9_/]+)["']/g,dataReactClass:/data-react-class\s*[=:]\s*["']([A-Za-z0-9_/]+)["']/g};async function Q(l){let e=new Map,t=[],o=await Ge(l);for(let r of o.entryDirs){let c=x.join(l,r);try{await A.access(c);let i=await glob("**/*.{tsx,ts,jsx,js}",{cwd:c,nodir:!0,ignore:["**/*.d.ts","**/*.test.*","**/*.spec.*"]});for(let u of i){let p=await Ze(x.join(c,u),u,r);if(p&&(t.push(p),p.componentName)){let m=e.get(p.componentName);m?(m.entryFile=x.join(r,u),m.importPath=p.imports[0]):e.set(p.componentName,{name:p.componentName,entryFile:x.join(r,u),importPath:p.imports[0],ssr:!1,usedIn:[]});}}}catch{}}let n=x.join(l,"app/views");try{await A.access(n);let r=await glob("**/*.{haml,erb,html.haml,html.erb,slim}",{cwd:n,nodir:!0});for(let c of r){let i=await Be(x.join(n,c),c);for(let u of i){let p=e.get(u.componentName);p?(p.usedIn.push({viewPath:c,controller:u.controller,action:u.action,propsVar:u.propsVar,line:u.line,pattern:u.pattern}),u.ssr&&(p.ssr=!0)):e.set(u.componentName,{name:u.componentName,ssr:u.ssr,usedIn:[{viewPath:c,controller:u.controller,action:u.action,propsVar:u.propsVar,line:u.line,pattern:u.pattern}]});}}}catch{}await Oe(l,e,o.componentDirs);let s=Array.from(e.values()),a=s.filter(r=>r.ssr).length;return {components:s,entryPoints:t,detectedPaths:o,summary:{totalComponents:s.length,totalEntryPoints:t.length,ssrComponents:a,clientComponents:s.length-a}}}async function Ge(l){let e=[],t=[],o="unknown";for(let n of Ee){let s=x.join(l,n);try{(await A.stat(s)).isDirectory()&&e.push(n);}catch{}}for(let n of De){let s=x.join(l,n);try{(await A.stat(s)).isDirectory()&&t.push(n);}catch{}}if(o=await Le(l),e.length===0){let n=await Ue(l);e.push(...n);}return t.length===0&&e.length>0&&t.push(...e),{entryDirs:e,componentDirs:t,integrationPattern:o}}async function Le(l){try{let e=x.join(l,"Gemfile"),t=await A.readFile(e,"utf-8");if(t.includes("react_on_rails"))return "react_on_rails";if(t.includes("react-rails"))return "react-rails";if(t.includes("vite_rails")||t.includes("vite_ruby"))return "vite";if(t.includes("webpacker"))return "webpacker";try{return await A.access(x.join(l,"vite.config.ts")),"vite"}catch{}try{return await A.access(x.join(l,"vite.config.js")),"vite"}catch{}return "custom"}catch{return "unknown"}}async function Ue(l){let e=[],t=["app/**/entries","app/**/packs","frontend/**/entries","client/**/entries","src/**/entries"];for(let o of t)try{let n=await glob(o,{cwd:l,nodir:!1});for(let s of n){let a=x.join(l,s);try{(await A.stat(a)).isDirectory()&&e.push(s);}catch{}}}catch{}return e}async function Ze(l,e,t){try{let o=await A.readFile(l,"utf-8"),n=[/\[data-react-component[=:][\s]*["']?([A-Za-z0-9_]+)["']?\]/,/\[data-component[=:][\s]*["']?([A-Za-z0-9_]+)["']?\]/,/\[data-react-class[=:][\s]*["']?([A-Za-z0-9_]+)["']?\]/,/getElementById\s*\(\s*["']([A-Za-z0-9_-]+)["']\s*\)/,/querySelector\s*\(\s*["']#([A-Za-z0-9_-]+)["']\s*\)/],s=null,a;for(let u of n){let p=o.match(u);if(p){s=p[1],a=p[0];break}}s||(s=x.basename(e,x.extname(e)).split(/[-_]/).map(p=>p.charAt(0).toUpperCase()+p.slice(1)).join(""));let r=[],c=o.matchAll(/import\s+(?:\{[^}]+\}|\*\s+as\s+\w+|\w+)\s+from\s+["']([^"']+)["']/g);for(let u of c){let p=u[1];(p.includes("/react/")||p.includes("/components/")||p.includes("/containers/")||p.includes("/bundles/")||p.includes("/pages/")||p.match(/\/[A-Z][a-zA-Z0-9]*/))&&r.push(p);}let i=o.matchAll(/require\s*\(\s*["']([^"']+)["']\s*\)/g);for(let u of i){let p=u[1];(p.includes("/react/")||p.includes("/components/")||p.includes("/containers/"))&&r.push(p);}return !s&&r.length===0?null:{file:e,fullPath:x.join(t,e),componentName:s||"",imports:r,selector:a}}catch{return null}}async function Be(l,e){let t=[];try{let n=(await A.readFile(l,"utf-8")).split(`
29
- `),s=e.split("/"),a=s.pop()||"",r=s.join("/")||"application",c=a.split(".")[0].replace(/^_/,""),i=0;for(let u of n){i++;let p=u.matchAll(E.dataReactComponent);for(let h of p){let b=u.match(/react_component_props:\s*(@?\w+(?:\.\w+)*)/);t.push({componentName:h[1],controller:r,action:c,propsVar:b?b[1]:void 0,line:i,pattern:"data-react-component",ssr:!1});}let m=u.match(E.renderReactComponent);if(m){let h=u.match(/ssr:\s*(true|false|@\w+)/);t.push({componentName:m[1],controller:r,action:c,line:i,pattern:"render_react_component",ssr:h?h[1]==="true"||h[1].startsWith("@"):!1});}let d=u.match(E.reactComponent);if(d){let h=u.match(/props:\s*(@?\w+(?:\.\w+)*)/),b=u.match(/prerender:\s*(true|false)/);t.push({componentName:d[1],controller:r,action:c,propsVar:h?h[1]:void 0,line:i,pattern:"react_component",ssr:b?b[1]==="true":!1});}let y=u.match(E.reduxStore);y&&t.push({componentName:y[1],controller:r,action:c,line:i,pattern:"redux_store",ssr:!1});let f=u.match(E.dataComponent);f&&t.push({componentName:f[1],controller:r,action:c,line:i,pattern:"data-react-component",ssr:!1});let g=u.match(E.dataReactClass);g&&t.push({componentName:g[1],controller:r,action:c,line:i,pattern:"data-react-component",ssr:!1});}}catch{}return t}async function Oe(l,e,t){for(let[o,n]of e)if(!(!o||typeof o!="string")){if(n.importPath&&typeof n.importPath=="string"){let s=n.importPath.replace(/\.js$/,"").replace(/\.tsx?$/,"").replace(/^\.\.\//,"").replace(/^\.\//,"");n.sourceFile=s;}else if(!n.sourceFile){let s=[".tsx",".ts",".jsx",".js"],a=[o,We(o),He(o)].filter(Boolean),r=false;for(let c of t){if(r)break;for(let i of a){if(r)break;for(let u of s){let p=[x.join(l,c,i,`index${u}`),x.join(l,c,i,`${i}${u}`),x.join(l,c,`${i}${u}`),x.join(l,c,"components",`${i}${u}`),x.join(l,c,"containers",`${i}${u}`)];for(let m of p)try{await A.access(m),n.sourceFile=x.relative(l,m),r=!0;break}catch{}}}}}}}function We(l){return l?l.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""):""}function He(l){return l?l.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""):""}async function qe(l){let e=process.env.REPOMAP_VERBOSE==="1",o=await new k(l).analyze(),s=await new V(l).analyze(),r=await new j(l).analyze(),i=await new T(l).analyze(),u=await K(l),p=await Q(l);e&&console.log(` Rails: ${o.routes.length} routes, ${s.controllers.length} controllers, ${r.models.length} models`);let m=[...new Set([...o.namespaces,...s.namespaces,...r.namespaces,...i.namespaces])],d=[...new Set([...s.concerns,...r.concerns])],y={totalRoutes:o.routes.length,totalControllers:s.controllers.length,totalActions:s.totalActions,totalModels:r.models.length,totalAssociations:r.totalAssociations,totalValidations:r.totalValidations,totalGrpcServices:i.services.length,totalRpcs:i.totalRpcs,totalViews:u.summary.totalViews,totalPages:u.summary.totalPages,totalReactComponents:p.summary.totalComponents,ssrReactComponents:p.summary.ssrComponents,namespaces:m,concerns:d};return {routes:o,controllers:s,models:r,grpc:i,views:u,react:p,summary:y}}async function Je(){let l=process.argv[2]||process.cwd(),e=await qe(l);console.log(`
28
+ `,s),s===-1))break}return n}function Ve(l,e){let t=[],o=[/HTTPClient\.(get|post|put|patch|delete)\s*\(\s*['"]([^'"]+)['"]/gi,/RestClient\.(get|post|put|patch|delete)\s*\(\s*['"]([^'"]+)['"]/gi,/Faraday\.(get|post|put|patch|delete)\s*\(\s*['"]([^'"]+)['"]/gi,/Net::HTTP\.(get|post)\s*\(/gi];for(let n of o){let s;for(;(s=n.exec(l))!==null;)t.push({type:"http",name:s[2]||"HTTP call",method:s[1]?.toUpperCase(),source:e});}return t}function je(l){let e=[],t=/(\w+(?:::\w+)*Service)\.(?:call!?|new)/g,o;for(;(o=t.exec(l))!==null;)e.push(o[1]);return [...new Set(e)]}function Te(l){let e=[],t=[/(\w+(?:::\w+)*Grpc(?:::\w+)?)\./g,/Grpc::(\w+(?:::\w+)*)/g,/(\w+GrpcService)\./g];for(let o of t){let n;for(;(n=o.exec(l))!==null;)e.push(n[1]);}return [...new Set(e)]}function ze(l){let e=[],t=/([A-Z][a-zA-Z0-9]+)\.(?:find|where|find_by|first|last|all|create|update|destroy|new)/g,o;for(;(o=t.exec(l))!==null;)["File","Dir","Time","Date","DateTime","JSON","YAML","CSV","Logger"].includes(o[1])||e.push(o[1]);return [...new Set(e)]}var Ee=["app/javascript/packs","app/javascript/entrypoints","app/frontend/entrypoints","app/javascript/application","frontend/assets/javascripts/entries","frontend/entries","app/assets/javascripts/entries","client/entries","src/entries"],De=["app/javascript/components","app/javascript/react","app/javascript/src/components","app/javascript/bundles","app/frontend/components","app/frontend/react","frontend/assets/javascripts/react","frontend/assets/javascripts/components","frontend/src","frontend/src/components","frontend/components","client/components","src/components"],E={dataReactComponent:/react_component:\s*["']([A-Za-z0-9_/]+)["']/g,renderReactComponent:/render_react_component\s*\(?\s*["']([A-Za-z0-9_/]+)["']/g,reactComponent:/<%=?\s*react_component\s*\(\s*["']([A-Za-z0-9_/]+)["']/g,reduxStore:/<%=?\s*redux_store\s*\(\s*["']([A-Za-z0-9_/]+)["']/g,dataComponent:/data-component\s*[=:]\s*["']([A-Za-z0-9_/]+)["']/g,dataReactClass:/data-react-class\s*[=:]\s*["']([A-Za-z0-9_/]+)["']/g};async function Q(l){let e=new Map,t=[],o=await Ge(l);for(let r of o.entryDirs){let c=x.join(l,r);try{await A.access(c);let i=await glob("**/*.{tsx,ts,jsx,js}",{cwd:c,nodir:!0,ignore:["**/*.d.ts","**/*.test.*","**/*.spec.*"]});for(let u of i){let p=await Ze(x.join(c,u),u,r);if(p&&(t.push(p),p.componentName)){let d=e.get(p.componentName);d?(d.entryFile=x.join(r,u),d.importPath=p.imports[0]):e.set(p.componentName,{name:p.componentName,entryFile:x.join(r,u),importPath:p.imports[0],ssr:!1,usedIn:[]});}}}catch{}}let n=x.join(l,"app/views");try{await A.access(n);let r=await glob("**/*.{haml,erb,html.haml,html.erb,slim}",{cwd:n,nodir:!0});for(let c of r){let i=await Be(x.join(n,c),c);for(let u of i){let p=e.get(u.componentName);p?(p.usedIn.push({viewPath:c,controller:u.controller,action:u.action,propsVar:u.propsVar,line:u.line,pattern:u.pattern}),u.ssr&&(p.ssr=!0)):e.set(u.componentName,{name:u.componentName,ssr:u.ssr,usedIn:[{viewPath:c,controller:u.controller,action:u.action,propsVar:u.propsVar,line:u.line,pattern:u.pattern}]});}}}catch{}await Oe(l,e,o.componentDirs);let s=Array.from(e.values()),a=s.filter(r=>r.ssr).length;return {components:s,entryPoints:t,detectedPaths:o,summary:{totalComponents:s.length,totalEntryPoints:t.length,ssrComponents:a,clientComponents:s.length-a}}}async function Ge(l){let e=[],t=[],o="unknown";for(let n of Ee){let s=x.join(l,n);try{(await A.stat(s)).isDirectory()&&e.push(n);}catch{}}for(let n of De){let s=x.join(l,n);try{(await A.stat(s)).isDirectory()&&t.push(n);}catch{}}if(o=await Le(l),e.length===0){let n=await Ue(l);e.push(...n);}return t.length===0&&e.length>0&&t.push(...e),{entryDirs:e,componentDirs:t,integrationPattern:o}}async function Le(l){try{let e=x.join(l,"Gemfile"),t=await A.readFile(e,"utf-8");if(t.includes("react_on_rails"))return "react_on_rails";if(t.includes("react-rails"))return "react-rails";if(t.includes("vite_rails")||t.includes("vite_ruby"))return "vite";if(t.includes("webpacker"))return "webpacker";try{return await A.access(x.join(l,"vite.config.ts")),"vite"}catch{}try{return await A.access(x.join(l,"vite.config.js")),"vite"}catch{}return "custom"}catch{return "unknown"}}async function Ue(l){let e=[],t=["app/**/entries","app/**/packs","frontend/**/entries","client/**/entries","src/**/entries"];for(let o of t)try{let n=await glob(o,{cwd:l,nodir:!1});for(let s of n){let a=x.join(l,s);try{(await A.stat(a)).isDirectory()&&e.push(s);}catch{}}}catch{}return e}async function Ze(l,e,t){try{let o=await A.readFile(l,"utf-8"),n=[/\[data-react-component[=:][\s]*["']?([A-Za-z0-9_]+)["']?\]/,/\[data-component[=:][\s]*["']?([A-Za-z0-9_]+)["']?\]/,/\[data-react-class[=:][\s]*["']?([A-Za-z0-9_]+)["']?\]/,/getElementById\s*\(\s*["']([A-Za-z0-9_-]+)["']\s*\)/,/querySelector\s*\(\s*["']#([A-Za-z0-9_-]+)["']\s*\)/],s=null,a;for(let u of n){let p=o.match(u);if(p){s=p[1],a=p[0];break}}s||(s=x.basename(e,x.extname(e)).split(/[-_]/).map(p=>p.charAt(0).toUpperCase()+p.slice(1)).join(""));let r=[],c=o.matchAll(/import\s+(?:\{[^}]+\}|\*\s+as\s+\w+|\w+)\s+from\s+["']([^"']+)["']/g);for(let u of c){let p=u[1];(p.includes("/react/")||p.includes("/components/")||p.includes("/containers/")||p.includes("/bundles/")||p.includes("/pages/")||p.match(/\/[A-Z][a-zA-Z0-9]*/))&&r.push(p);}let i=o.matchAll(/require\s*\(\s*["']([^"']+)["']\s*\)/g);for(let u of i){let p=u[1];(p.includes("/react/")||p.includes("/components/")||p.includes("/containers/"))&&r.push(p);}return !s&&r.length===0?null:{file:e,fullPath:x.join(t,e),componentName:s||"",imports:r,selector:a}}catch{return null}}async function Be(l,e){let t=[];try{let n=(await A.readFile(l,"utf-8")).split(`
29
+ `),s=e.split("/"),a=s.pop()||"",r=s.join("/")||"application",c=a.split(".")[0].replace(/^_/,""),i=0;for(let u of n){i++;let p=u.matchAll(E.dataReactComponent);for(let h of p){let b=u.match(/react_component_props:\s*(@?\w+(?:\.\w+)*)/);t.push({componentName:h[1],controller:r,action:c,propsVar:b?b[1]:void 0,line:i,pattern:"data-react-component",ssr:!1});}let d=u.match(E.renderReactComponent);if(d){let h=u.match(/ssr:\s*(true|false|@\w+)/);t.push({componentName:d[1],controller:r,action:c,line:i,pattern:"render_react_component",ssr:h?h[1]==="true"||h[1].startsWith("@"):!1});}let f=u.match(E.reactComponent);if(f){let h=u.match(/props:\s*(@?\w+(?:\.\w+)*)/),b=u.match(/prerender:\s*(true|false)/);t.push({componentName:f[1],controller:r,action:c,propsVar:h?h[1]:void 0,line:i,pattern:"react_component",ssr:b?b[1]==="true":!1});}let y=u.match(E.reduxStore);y&&t.push({componentName:y[1],controller:r,action:c,line:i,pattern:"redux_store",ssr:!1});let m=u.match(E.dataComponent);m&&t.push({componentName:m[1],controller:r,action:c,line:i,pattern:"data-react-component",ssr:!1});let g=u.match(E.dataReactClass);g&&t.push({componentName:g[1],controller:r,action:c,line:i,pattern:"data-react-component",ssr:!1});}}catch{}return t}async function Oe(l,e,t){for(let[o,n]of e)if(!(!o||typeof o!="string")){if(n.importPath&&typeof n.importPath=="string"){let s=n.importPath.replace(/\.js$/,"").replace(/\.tsx?$/,"").replace(/^\.\.\//,"").replace(/^\.\//,"");n.sourceFile=s;}else if(!n.sourceFile){let s=[".tsx",".ts",".jsx",".js"],a=[o,We(o),He(o)].filter(Boolean),r=false;for(let c of t){if(r)break;for(let i of a){if(r)break;for(let u of s){let p=[x.join(l,c,i,`index${u}`),x.join(l,c,i,`${i}${u}`),x.join(l,c,`${i}${u}`),x.join(l,c,"components",`${i}${u}`),x.join(l,c,"containers",`${i}${u}`)];for(let d of p)try{await A.access(d),n.sourceFile=x.relative(l,d),r=!0;break}catch{}}}}}}}function We(l){return l?l.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""):""}function He(l){return l?l.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""):""}async function qe(l){let e=process.env.REPOMAP_VERBOSE==="1",o=await new k(l).analyze(),s=await new V(l).analyze(),r=await new j(l).analyze(),i=await new T(l).analyze(),u=await K(l),p=await Q(l);e&&console.log(` Rails: ${o.routes.length} routes, ${s.controllers.length} controllers, ${r.models.length} models`);let d=[...new Set([...o.namespaces,...s.namespaces,...r.namespaces,...i.namespaces])],f=[...new Set([...s.concerns,...r.concerns])],y={totalRoutes:o.routes.length,totalControllers:s.controllers.length,totalActions:s.totalActions,totalModels:r.models.length,totalAssociations:r.totalAssociations,totalValidations:r.totalValidations,totalGrpcServices:i.services.length,totalRpcs:i.totalRpcs,totalViews:u.summary.totalViews,totalPages:u.summary.totalPages,totalReactComponents:p.summary.totalComponents,ssrReactComponents:p.summary.ssrComponents,namespaces:d,concerns:f};return {routes:o,controllers:s,models:r,grpc:i,views:u,react:p,summary:y}}async function Je(){let l=process.argv[2]||process.cwd(),e=await qe(l);console.log(`
30
30
  `+"=".repeat(60)),console.log("\u{1F4CA} RAILS APPLICATION ANALYSIS SUMMARY"),console.log("=".repeat(60)+`
31
31
  `),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 Routes \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Total routes: ${String(e.summary.totalRoutes).padStart(6)} \u2502`),console.log(`\u2502 Resources: ${String(e.routes.resources.length).padStart(6)} \u2502`),console.log(`\u2502 Mounted engines: ${String(e.routes.mountedEngines.length).padStart(6)} \u2502`),console.log(`\u2502 External files: ${String(e.routes.drawnFiles.length).padStart(6)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 Controllers \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Total controllers: ${String(e.summary.totalControllers).padStart(6)} \u2502`),console.log(`\u2502 Total actions: ${String(e.summary.totalActions).padStart(6)} \u2502`),console.log(`\u2502 Namespaces: ${String(e.controllers.namespaces.length).padStart(6)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 Models \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Total models: ${String(e.summary.totalModels).padStart(6)} \u2502`),console.log(`\u2502 Associations: ${String(e.summary.totalAssociations).padStart(6)} \u2502`),console.log(`\u2502 Validations: ${String(e.summary.totalValidations).padStart(6)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 gRPC Services \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Total services: ${String(e.summary.totalGrpcServices).padStart(6)} \u2502`),console.log(`\u2502 Total RPCs: ${String(e.summary.totalRpcs).padStart(6)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 Shared \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(`\u2502 Total namespaces: ${String(e.summary.namespaces.length).padStart(6)} \u2502`),console.log(`\u2502 Total concerns: ${String(e.summary.concerns.length).padStart(6)} \u2502`),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518");let t=e.routes.errors.length+e.controllers.errors.length+e.models.errors.length+e.grpc.errors.length;t>0?console.log(`
32
32
  \u26A0\uFE0F Total errors: ${t}`):console.log(`
@@ -0,0 +1,3 @@
1
+ import {parseSync}from'@swc/core';import {glob}from'glob';import*as y from'path';import*as F from'fs';import*as T from'fs/promises';import h from'typescript';import {parse,getLocation}from'graphql';var A=class{config;basePath;constructor(e){this.config=e,this.basePath=e.path;}resolvePath(e){return `${this.basePath}/${e}`}getSetting(e,t=""){return this.config.settings[e]??t}getListSetting(e,t=[]){let r=this.getSetting(e,"");return r?r.split(/[,\n]/g).map(s=>s.trim()).filter(Boolean):t}getGraphQLHookPatterns(){let e=(this.getSetting("graphqlHookPreset","auto")||"auto").trim().toLowerCase(),t=this.getListSetting("graphqlHookPatterns",[]),r=["useLazyLoadQuery","usePreloadedQuery","useQueryLoader","useMutation","useSubscription","useFragment","usePaginationFragment","useRefetchableFragment","useRelayEnvironment"],s=["useUrql*"],i=["useGql*","useGraphQL*","useGraphql*","useApiQuery*","useApiMutation*"],n=[];return e==="none"||e==="off"||e==="false"?n=[]:e==="apollo"?n=[]:e==="urql"?n=s:e==="relay"?n=r:n=[...r,...s,...i],Array.from(new Set([...n,...t]))}log(e){process.env.REPOMAP_VERBOSE==="1"&&console.log(`[${this.getName()}] ${e}`);}warn(e){console.warn(`\u26A0\uFE0F ${e}`);}error(e,t){console.error(`\u274C ${e}`,t?.message||"");}};var ee=["useQuery","useLazyQuery","useSuspenseQuery","useBackgroundQuery","useReadQuery"],te=["useMutation"],ve=["useSubscription","useFragment","useApolloClient"],W=[...ee,...te,...ve],X={useQuery:"useQuery",useSuspenseQuery:"useQuery",useBackgroundQuery:"useQuery",useReadQuery:"useQuery",useLazyQuery:"useLazyQuery",useMutation:"useMutation",useSubscription:"useSubscription"},be=["Document","useQuery","useMutation","useLazyQuery","useSuspenseQuery","useBackgroundQuery","useSubscription","Query","Mutation","gql","graphql","GET_","FETCH_","SEARCH_","CREATE_","UPDATE_","DELETE_","SUBSCRIBE_","@apollo","ApolloClient","@urql","urql","react-relay","Relay"];function Ce(p,e){if(!e)return false;if(e===p)return true;if(!e.includes("*"))return false;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`).test(p)}function E(p,e){for(let t of e)if(Ce(p,t))return true;return false}function R(p,e=[]){return E(p,e)?/Query$/.test(p)||!/(Mutation|Subscription)$/.test(p):ee.includes(p)||/^use[A-Z].*Query$/.test(p)}function Q(p,e=[]){return E(p,e)?/Mutation$/.test(p)||p.toLowerCase().includes("mutation"):te.includes(p)||/^use[A-Z].*Mutation$/.test(p)}function ne(p,e=[]){return E(p,e)?/Subscription$/.test(p)||p.toLowerCase().includes("subscription"):p==="useSubscription"}function $(p,e=[]){return E(p,e)?true:W.includes(p)||R(p,e)||Q(p,e)}function q(p,e=[]){return X[p]?X[p]:p.includes("Mutation")||E(p,e)?"useMutation":p.includes("Lazy")?"useLazyQuery":p.includes("Subscription")?"useSubscription":"useQuery"}function H(p){return be.some(e=>p.includes(e))}function d(p){return p.replace(/^(GET_|FETCH_|CREATE_|UPDATE_|DELETE_)/,"").replace(/_QUERY$|_MUTATION$/,"").replace(/Document$/,"").replace(/Query$|Mutation$|Variables$|Subscription$/,"")}function Ae(p){try{return parseSync(p,{syntax:"typescript",tsx:!0,comments:!1})}catch{return null}}function v(p){return p?p.type==="Identifier"?p.value:p.type==="MemberExpression"&&p.property?.type==="Identifier"?p.property.value:null:null}function M(p,e){if(!(!p||typeof p!="object")){e(p);for(let t of Object.keys(p)){let r=p[t];if(Array.isArray(r))for(let s of r)M(s,e);else r&&typeof r=="object"&&M(r,e);}}}function V(p,e,t){let r={documentImports:new Map,variableOperations:new Map,staticPropertyOperations:new Map,codegenMap:t||new Map};return M(p,s=>{s.type==="ImportDeclaration"&&we(s,r.documentImports),s.type==="VariableDeclarator"&&Fe(s,e,r.variableOperations),s.type==="AssignmentExpression"&&Ne(s,e,r.staticPropertyOperations);}),r}function we(p,e){let t=p.source?.value||"",r=t.includes("__generated__")||t.includes("generated")||t.includes("graphql")||t.includes(".generated")||t.endsWith(".graphql");for(let s of p.specifiers||[]){let i;(s.type==="ImportSpecifier"||s.type==="ImportDefaultSpecifier")&&(i=s.local?.value),i&&((i.endsWith("Document")||r)&&e.set(i,i.replace(/Document$/,"")),(i.endsWith("Query")||i.endsWith("Mutation"))&&e.set(i,i.replace(/Query$|Mutation$/,"")));}}function Fe(p,e,t){if(p.id?.type!=="Identifier")return;let r=p.id.value,s=p.init;if(!s)return;let i=null;if(s.type==="CallExpression"){let n=v(s.callee);(n==="gql"||n==="graphql")&&(i=U(s,e));}if(s.type==="TaggedTemplateExpression"){let n=v(s.tag);(n==="gql"||n==="graphql")&&(i=P(s.template));}if(s.type==="Identifier"){let n=s.value;if(n.endsWith("Document")||n.endsWith("Query")||n.endsWith("Mutation")){t.set(r,n);return}}i&&t.set(r,i);}function Ne(p,e,t){if(p.left?.type!=="MemberExpression")return;let r=p.left.object,s=p.left.property;if(r?.type!=="Identifier"||s?.type!=="Identifier")return;let i=`${r.value}.${s.value}`,n=p.right;if(!n)return;let a=null;if(n.type==="CallExpression"){let o=v(n.callee);(o==="gql"||o==="graphql")&&(a=U(n,e));}if(n.type==="TaggedTemplateExpression"){let o=v(n.tag);(o==="gql"||o==="graphql")&&(a=P(n.template));}a&&t.set(i,a);}function U(p,e){if(!p.arguments?.length)return null;let t=p.arguments[0],r=t?.expression||t;if(r?.type==="TemplateLiteral")return P(r);if(p.span){let i=e.slice(p.span.start,p.span.end).match(/(?:query|mutation|subscription)\s+(\w+)/i);if(i)return i[1]}return null}function P(p,e){if(!p?.quasis?.[0])return null;let r=(p.quasis[0].raw||p.quasis[0].cooked||"").match(/(?:query|mutation|subscription)\s+(\w+)/i);return r?r[1]:null}function re(p,e,t){if(!p.arguments?.length)return false;let r=p.arguments[0],s=r?.expression||r;if(!s)return false;if(p.typeArguments?.params?.length>0){let n=p.typeArguments.params[0];if(n?.type==="TsTypeReference"&&n.typeName?.type==="Identifier"){let a=n.typeName.value;if(/Query$|Mutation$|Subscription$|Document$/.test(a))return true}}if(s.type==="Identifier"){let n=s.value;if(t.documentImports.has(n)||t.variableOperations.has(n)||n.endsWith("Document")||/^[A-Z][a-zA-Z0-9]*Query$/.test(n)||/^[A-Z][a-zA-Z0-9]*Mutation$/.test(n)||/^[A-Z][A-Z0-9_]*_QUERY$/.test(n)||/^[A-Z][A-Z0-9_]*_MUTATION$/.test(n))return true}if(s.type==="TaggedTemplateExpression"){let n=v(s.tag);if(n==="gql"||n==="graphql")return true}if(s.type==="CallExpression"){let n=v(s.callee);if(n==="gql"||n==="graphql")return true}if(s.type==="TemplateLiteral"&&s.quasis?.[0]?.raw){let n=s.quasis[0].raw;if(/(?:query|mutation|subscription)\s+\w+/i.test(n))return true}if(s.type==="MemberExpression"){let n=s.property?.value;if(n&&/Query$|Mutation$|Document$/.test(n))return true;let a=s.object?.type==="Identifier"?s.object.value:null;if(a&&n){let o=`${a}.${n}`;if(t.staticPropertyOperations.has(o))return true}}if(s.type==="ObjectExpression")for(let n of s.properties||[]){if(n.type!=="KeyValueProperty")continue;let a=n.key?.type==="Identifier"||n.key?.type==="StringLiteral"?n.key.value:null;if(!a||!["query","mutation","document","subscription"].includes(a))continue;let o=n.value;if(o&&K(o,e,t))return true}let i=p.span;if(i){let n=e.slice(i.start,Math.min(i.end,i.start+500));if(/\bDocument\b/.test(n)||/\bgql\s*[`(]/.test(n)||/\bgraphql\s*[`(]/.test(n)||/query\s+[A-Z]\w+\s*[({]/.test(n)||/mutation\s+[A-Z]\w+\s*[({]/.test(n))return true}return false}function Z(p,e,t){let r=Me(p,e);if(r)return r;if(p.arguments?.length>0){let s=p.arguments[0],i=s?.expression||s;if(i){let n=K(i,e,t);if(n)return n}}return null}function Me(p,e){if(p.typeArguments?.params?.length>0){let t=p.typeArguments.params[0];if(t?.type==="TsTypeReference"&&t.typeName?.type==="Identifier")return d(t.typeName.value)}if(p.callee?.span&&p.span){let t=p.callee.span.end,r=Math.min(t+150,p.span.end),i=e.slice(t,r).match(/^<\s*(\w+)(?:Query|Mutation|Variables|Subscription)?[\s,>]/);if(i)return d(i[1])}return null}function K(p,e,t){if(p.type==="Identifier")return se(p.value,t);if(p.type==="MemberExpression")return Se(p,t);if(p.type==="TaggedTemplateExpression"){let r=v(p.tag);if(r==="gql"||r==="graphql")return P(p.template)}if(p.type==="TemplateLiteral")return P(p);if(p.type==="CallExpression"){let r=v(p.callee);if(r==="gql"||r==="graphql")return U(p,e)}return p.type==="ObjectExpression"?ie(p,e,t):null}function se(p,e){let t=e.variableOperations.get(p);if(t)return e.variableOperations.has(t)?se(t,e):t.endsWith("Document")||t.endsWith("Query")||t.endsWith("Mutation")?e.documentImports.get(t)||d(t):t;let r=e.documentImports.get(p);if(r)return r;let s=e.codegenMap.get(p);return s?s.operationName:/^(Query|Mutation|QUERY|MUTATION|Document)$/i.test(p)?null:d(p)}function Se(p,e){let t=p.object?.type==="Identifier"?p.object.value:null,r=p.property?.type==="Identifier"?p.property.value:null;if(!r)return null;if(t){let s=`${t}.${r}`,i=e.staticPropertyOperations.get(s);if(i)return i}return d(r)}function ie(p,e,t){for(let r of p.properties||[])if(r.type==="KeyValueProperty"&&r.key?.type==="Identifier"&&r.key.value==="query")return K(r.value,e,t);return null}function je(p,e){let t=[],r=new Set;if(!H(p))return t;let s=Ae(p);if(!s)return t;let i=V(s,p,e);return M(s,n=>{if(n.type!=="CallExpression")return;let a=v(n.callee);if(a){if($(a)){let o=Z(n,p,i),l=q(a),u=`${l}:${o||"unknown"}`;r.has(u)||(r.add(u),t.push({operationName:o||"unknown",hookName:a,type:l}));}if((a==="query"||a==="mutate")&&n.arguments?.length>0){let o=n.arguments[0],l=o?.expression||o;if(l?.type==="ObjectExpression"){let u=ie(l,p,i),f=a==="mutate"?"useMutation":"useQuery",c=`${f}:${u||"unknown"}`;u&&!r.has(c)&&(r.add(c),t.push({operationName:u,hookName:`client.${a}`,type:f}));}}}}),t}function Ge(p){return `${{useQuery:"Query",useLazyQuery:"Query",useMutation:"Mutation",useSubscription:"Subscription"}[p.type]||"Query"}: ${p.operationName}`}async function S(p,e,t=8){let r=new Array(p.length).fill(null),s=0;async function i(){for(;s<p.length;){let a=s++;if(a<p.length)try{r[a]=await e(p[a],a);}catch{r[a]=null;}}}let n=Array(Math.min(t,p.length)).fill(null).map(()=>i());return await Promise.all(n),r.filter(a=>a!==null)}function k(p,e){let t=h.createSourceFile(e,p,h.ScriptTarget.Latest,true,h.ScriptKind.TS),r=[],s=i=>{if(h.isVariableStatement(i)&&Ie(i.modifiers))for(let n of i.declarationList.declarations){if(!h.isIdentifier(n.name))continue;let a=n.name.text;if(!a.endsWith("Document")||!n.initializer)continue;let o=Pe(n.initializer),l=Ee(o);if(!l)continue;let u=Re(l);if(!u)continue;let c=h.getLineAndCharacterOfPosition(t,n.name.getStart(t)).line+1;r.push({documentName:a,operationName:u.operationName,operationType:u.operationType,document:l,line:c});}h.forEachChild(i,s);};return s(t),r}function Ie(p){return p?p.some(e=>e.kind===h.SyntaxKind.ExportKeyword):false}function Pe(p){let e=p;for(;;){if(h.isParenthesizedExpression(e)){e=e.expression;continue}if(h.isAsExpression(e)){e=e.expression;continue}if(h.isTypeAssertionExpression(e)){e=e.expression;continue}if(h.isNonNullExpression(e)){e=e.expression;continue}break}return e}function Ee(p){if(!h.isObjectLiteralExpression(p))return null;let e=B(p);if(!e||typeof e!="object")return null;let t=e.kind,r=e.definitions;return t!=="Document"||!Array.isArray(r)?null:e}function Re(p){let e=p.definitions;if(!Array.isArray(e)||e.length===0)return null;let t=e[0];if(!t||typeof t!="object"||t.kind!=="OperationDefinition")return null;let s=t.operation,i=t.name,n=s==="mutation"||s==="subscription"?s:"query",a="";if(i&&typeof i=="object"){let o=i.value;typeof o=="string"&&(a=o);}return a?{operationName:a,operationType:n}:null}function B(p){if(h.isObjectLiteralExpression(p)){let e={};for(let t of p.properties){if(h.isPropertyAssignment(t)){let r=Qe(t.name);if(!r)continue;e[r]=B(t.initializer);continue}h.isShorthandPropertyAssignment(t);}return e}return h.isArrayLiteralExpression(p)?p.elements.map(e=>h.isExpression(e)?B(e):null):h.isStringLiteral(p)||h.isNoSubstitutionTemplateLiteral(p)?p.text:h.isNumericLiteral(p)?Number(p.text):p.kind===h.SyntaxKind.TrueKeyword?true:p.kind===h.SyntaxKind.FalseKeyword?false:(p.kind===h.SyntaxKind.NullKeyword,null)}function Qe(p){return h.isIdentifier(p)||h.isStringLiteral(p)||h.isNumericLiteral(p)?p.text:(h.isComputedPropertyName(p),null)}var O=class{repoRootAbs;knownFiles;configCache=new Map;configPathCache=new Map;constructor(e,t){this.repoRootAbs=y.resolve(e),this.knownFiles=t;}resolve(e,t){if(!t||!t.startsWith(".")&&!t.startsWith("/")&&!t.startsWith("@")&&!t.includes("/"))return null;let r=y.join(this.repoRootAbs,e),s=this.getParsedConfigForFile(r),i={fileExists:m=>F.existsSync(m),readFile:m=>{try{return F.readFileSync(m,"utf8")}catch{return}},directoryExists:m=>{try{return F.existsSync(m)&&F.statSync(m).isDirectory()}catch{return false}},getCurrentDirectory:()=>this.repoRootAbs,realpath:h.sys.realpath},n=s?.options||{moduleResolution:h.ModuleResolutionKind.NodeNext,jsx:h.JsxEmit.ReactJSX,allowJs:true},o=h.resolveModuleName(t,r,n,i).resolvedModule?.resolvedFileName;if(!o)return null;let l=this.toRepoRelative(o);if(!l)return null;let u=this.normalizeRel(l),f=this.pickKnownFile(u);if(!f)return null;let c=this.getConfigPathForFile(r),g=c&&this.toRepoRelative(c)||void 0;return {file:f,evidence:{fromFile:this.normalizeRel(e),specifier:t,resolvedFile:f,configFile:g}}}getConfigPathForFile(e){let t=y.dirname(e),r=this.configPathCache.get(t);if(r!==void 0)return r;let s=this.findNearestConfig(t);return this.configPathCache.set(t,s),s}getParsedConfigForFile(e){let t=this.getConfigPathForFile(e);if(!t)return null;let r=this.configCache.get(t);if(r!==void 0)return r;try{let s=h.readConfigFile(t,h.sys.readFile);if(s.error)return this.configCache.set(t,null),null;let i=h.parseJsonConfigFileContent(s.config,h.sys,y.dirname(t),void 0,t);return this.configCache.set(t,i),i}catch{return this.configCache.set(t,null),null}}findNearestConfig(e){let t=y.resolve(e),r=this.repoRootAbs;for(;;){let s=y.join(t,"tsconfig.json"),i=y.join(t,"jsconfig.json");if(F.existsSync(s))return s;if(F.existsSync(i))return i;if(t===r)break;let n=y.dirname(t);if(n===t||(t=n,!t.startsWith(r)))break}return null}toRepoRelative(e){let t=y.resolve(e);if(!t.startsWith(this.repoRootAbs))return null;let r=y.relative(this.repoRootAbs,t);return this.normalizeRel(r)}normalizeRel(e){return y.normalize(e).replace(/\\/g,"/")}pickKnownFile(e){if(this.knownFiles.has(e))return e;let t=e.replace(/\.(ts|tsx|js|jsx|mts|cts|mjs|cjs|d\.ts)$/,""),r=this.firstKnownByStem(t);if(r)return r;let s=this.firstKnownByStem(`${t}/index`);return s||null}firstKnownByStem(e){let t=[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"];for(let r of t){let s=`${e}${r}`;if(this.knownFiles.has(s))return s}return null}};var oe=class extends A{codegenMap=new Map;tsResolver=null;coverage={tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0};constructor(e){super(e);}getName(){return "PagesAnalyzer"}async analyze(){this.log("Starting page analysis..."),await this.loadCodegenMapping();let e=await this.findPageFiles();this.coverage.tsFilesScanned+=e.length,this.log(`Found ${e.length} page files`);let t=50,r=new Map;for(let n=0;n<e.length;n+=t){let a=e.slice(n,n+t),o=await Promise.all(a.map(async l=>{try{let u=await T.readFile(l,"utf-8");return {filePath:l,content:u}}catch{return null}}));for(let l of o)l&&r.set(l.filePath,l.content);}let i=(await S(e,async n=>{let a=r.get(n);if(!a)return null;let o=this.detectPagesRoot(n);return this.analyzePageFile(n,a,o)},8)).filter(n=>n!==null);return this.log(`Analyzed ${i.length} pages successfully`),{pages:i,coverage:this.coverage}}async loadCodegenMapping(){let e=await glob(["**/__generated__/graphql.ts","**/__generated__/gql.ts","**/generated/graphql.ts","**/generated/gql.ts","**/*.generated.ts","**/graphql.ts"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],absolute:true});for(let t of e)try{let r=await T.readFile(t,"utf-8"),s=y.relative(this.basePath,t);if(!r.includes("Document")||!r.includes("definitions"))continue;this.coverage.codegenFilesDetected+=1;let i=k(r,s);this.coverage.codegenFilesParsed+=1,this.coverage.codegenExportsFound+=i.length;for(let n of i)this.codegenMap.set(n.documentName,{operationName:n.operationName,operationType:n.operationType});i.length>0&&this.log(`Loaded ${i.length} codegen mappings from ${s}`);}catch{}}analyzePageFile(e,t,r){try{let s=e.endsWith(".tsx")||e.endsWith(".jsx"),i=parseSync(t,{syntax:e.endsWith(".ts")||e.endsWith(".tsx")?"typescript":"ecmascript",tsx:s,jsx:s,comments:!1}),n=y.relative(r,e),a=this.filePathToRoutePath(n),o=this.findPageComponent(i,t);if(!o)return null;let l=this.extractRouteParams(a),u=this.extractImports(i),f=this.extractLayout(i,t),c=this.extractAuthRequirement(i,t,e),g=this.extractPermissions(t),m=this.extractDataFetching(i,t,u),x=this.extractLinkedPages(i,t),C=this.extractNavigation(t),I=this.extractSteps(t);return {path:a,filePath:n,component:o,params:l,layout:f,authentication:c,permissions:g,dataFetching:m,navigation:C,linkedPages:x,steps:I.length>0?I:void 0}}catch{return this.coverage.tsParseFailures+=1,null}}async findPageFiles(){let e=this.getSetting("pagesDir","src/pages"),t=[],s=[...new Set([e,"pages","src/pages","app","src/app"])];for(let n of s){if(n==="app"||n==="src/app"){let o=["controllers","models","views","helpers"],l=this.resolvePath(n);if(o.some(f=>{try{return F.existsSync(y.join(l,f))}catch{return false}}))continue}let a=this.resolvePath(n);try{let l=n==="app"||n==="src/app"||n.endsWith("/app")?["**/page.{tsx,ts,jsx,js}"]:["**/*.tsx","**/*.ts","**/*.jsx","**/*.js"],u=await glob(l,{cwd:a,ignore:["_app.tsx","_app.ts","_app.jsx","_app.js","_document.tsx","_document.ts","_error.tsx","api/**","**/*.test.*","**/*.spec.*","**/node_modules/**","**/components/pages/**"],absolute:!0});t.push(...u),u.length>0&&this.log(`Found ${u.length} pages in ${n}`);}catch{}}let i=["frontend/src/**/pages","app/javascript/**/pages"];for(let n of i)try{let a=await glob([`${n}/**/*.tsx`,`${n}/**/*.ts`,`${n}/**/*.jsx`,`${n}/**/*.js`],{cwd:this.basePath,ignore:["**/*.test.*","**/*.spec.*","**/node_modules/**","**/components/pages/**"],absolute:!0});t.push(...a);}catch{}if(t.length===0){let n=await this.findSPARoutes();n.length>0&&(this.log(`Found ${n.length} SPA routes from App.tsx`),t.push(...n));}return [...new Set(t)]}async findSPARoutes(){let e=[];if(!this.tsResolver)try{let r=await glob(["**/*.{ts,tsx,js,jsx}"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],absolute:!1,nodir:!0,dot:!1});this.tsResolver=new O(this.basePath,new Set(r.map(s=>s.replace(/\\/g,"/"))));}catch{this.tsResolver=null;}let t=["src/App.tsx","src/App.jsx","src/App.js","App.tsx","App.jsx","App.js"];for(let r of t){let s=this.resolvePath(r);if(F.existsSync(s))try{let i=await T.readFile(s,"utf-8");if(!i.includes("react-router")&&!i.includes("Route"))continue;let n=parseSync(i,{syntax:"typescript",tsx:!0}),a=this.extractImports(n);this.traverseNode(n,o=>{if(o.type==="JSXOpeningElement"){let l=this.getJsxTagName(o);if(l==="Route"||l==="PrivateRoute"){let u=this.getJsxAttribute(o,"component"),f=this.getJsxAttribute(o,"element"),c=u||f,g=c?a.get(c):void 0;if(g){let m=this.resolveImportPath(s,g);m&&F.existsSync(m)&&e.push(m);}}}}),e.length>0&&e.push(s);}catch{}}return e}resolveImportPath(e,t){if(!t.startsWith(".")){let n=y.relative(this.basePath,e).replace(/\\/g,"/");if(this.tsResolver){let a=this.tsResolver.resolve(n,t);if(a)return y.join(this.basePath,a.file)}return null}let r=[".tsx",".ts",".jsx",".js","/index.tsx","/index.ts","/index.jsx","/index.js"],s=y.dirname(e),i=y.resolve(s,t);for(let n of r){let a=i+n;if(F.existsSync(a))return a}if(F.existsSync(i)&&F.statSync(i).isDirectory())for(let n of ["/index.tsx","/index.ts","/index.jsx","/index.js"]){let a=i+n;if(F.existsSync(a))return a}return null}detectPagesRoot(e){let t=["/src/pages/","/pages/","/src/app/","/app/","/frontend/src/pages/","/app/javascript/pages/"];for(let r of t){let s=e.indexOf(r);if(s!==-1)return e.substring(0,s+r.length-1)}return this.basePath}filePathToRoutePath(e){let t=e.replace(/\\/g,"/").replace(/\.(tsx?|jsx?)$/,"");return t=t.replace(/\/page$/,"").replace(/^page$/,""),t=t.replace(/\/route$/,"").replace(/^route$/,""),"/"+t.split("/").filter(Boolean).map(n=>n.replace(/^\(\.\.\.\)|^\(\.\.\)|^\(\.\)/,"")).filter(n=>!(n.startsWith("(")&&n.endsWith(")")||n.startsWith("@"))).join("/").replace(/\/index$/,"").replace(/\[\[\.\.\.(\w+)\]\]/g,"*").replace(/\[\.\.\.(\w+)\]/g,"*").replace(/\[(\w+)\]/g,":$1")}extractRouteParams(e){let t=[],r=e.match(/:(\w+)/g);if(r)for(let s of r)t.push(s.slice(1));return t}findDefaultExportName(e){for(let t of e.body){if(t.type==="ExportDefaultDeclaration"){let r=t.decl;if((r?.type==="FunctionExpression"||r?.type==="FunctionDeclaration")&&r.identifier?.value||(r?.type==="ClassDeclaration"||r?.type==="ClassExpression")&&r.identifier?.value)return r.identifier.value;if(r?.type==="Identifier")return r.value}if(t.type==="ExportDefaultExpression"){let r=t.expression;if(r?.type==="Identifier")return r.value}}return null}findPageComponent(e,t){let r=this.findDefaultExportName(e);if(r&&r!=="Page"&&r!=="default")return r;let s=this.findMainJsxComponent(e,t);if(s&&s!=="Page"&&s!=="default")return s;for(let i of e.body){if(i.type==="ExportDefaultDeclaration"){let n=i.decl;if((n?.type==="FunctionExpression"||n?.type==="FunctionDeclaration")&&n.identifier?.value){let a=n.identifier.value;if(a!=="Page")return a}if((n?.type==="ClassDeclaration"||n?.type==="ClassExpression")&&n.identifier?.value){let a=n.identifier.value;if(a!=="Page")return a}if(n?.type==="Identifier"){let a=n.value;if(a!=="Page")return a}if(n?.type==="ArrowFunctionExpression"||(n?.type==="FunctionExpression"||n?.type==="FunctionDeclaration")&&!n.identifier)return s||"default"}if(i.type==="ExportDefaultExpression"){let n=i.expression;if(n?.type==="Identifier"){let a=n.value;if(a!=="Page")return a}}}if(s)return s;for(let i of e.body)if(i.type==="VariableDeclaration"){for(let n of i.declarations)if(n.id?.type==="Identifier"&&n.id.value==="Page")return "Page"}for(let i of e.body)if(i.type==="ExportDeclaration"&&i.declaration?.type==="FunctionDeclaration"){let n=i.declaration.identifier?.value;if(n&&/^[A-Z]/.test(n))return n}for(let i of e.body){if(i.type==="FunctionDeclaration"){let n=i.identifier?.value;if(n&&/^[A-Z]/.test(n))return n}if(i.type==="VariableDeclaration"){for(let n of i.declarations)if(n.id?.type==="Identifier"){let a=n.id.value;if(a&&/^[A-Z]/.test(a)&&t.includes("return")&&t.includes("<"))return a}}}return null}isProjectImport(e){return e.startsWith("./")||e.startsWith("../")||/^[@~#]\//.test(e)?true:!(e.startsWith("@")&&!e.startsWith("@/")||/^[a-z]/.test(e))}findMainJsxComponent(e,t){let r=this.extractImports(e),s=new Set;for(let[a,o]of r)/^[A-Z]/.test(a)&&this.isProjectImport(o)&&s.add(a);let i=[];for(let a of s){let o=new RegExp(`<${a}[\\s/>]`,"g"),l;for(;(l=o.exec(t))!==null;)i.push({name:a,index:l.index});}let n=i.find(a=>a.name.includes("Container")||a.name.includes("Page")||a.name.includes("View")||a.name.includes("Screen"));return n?n.name:i.length>0?(i.sort((a,o)=>a.index-o.index),i[0].name):null}extractImports(e){let t=new Map;for(let r of e.body)if(r.type==="ImportDeclaration"){let s=r.source?.value||"";for(let i of r.specifiers||[])i.type==="ImportSpecifier"&&i.local?.value&&t.set(i.local.value,s),i.type==="ImportDefaultSpecifier"&&i.local?.value&&t.set(i.local.value,s);}return t}extractLayout(e,t){if(t.includes("getLayout")){let r=t.match(/getLayout\s*=.*?<(\w+Layout|\w+Shell)/);if(r)return r[1]}}extractAuthRequirement(e,t,r){let s=y.basename(r),a={required:!["404.tsx","permission-denied.tsx","_app.tsx","_document.tsx","_error.tsx"].some(l=>s===l)},o=["RequiredCondition","ProtectedRoute","AuthGuard","PrivateRoute","WithAuth","RequireAuth","Authenticated","Authorized"];for(let l of o)if(t.includes(`<${l}`)){a.condition="Additional permissions required";let u=this.extractRolesFromContent(t);u.length>0&&(a.roles=u);break}return a}extractRolesFromContent(e){let t=[];this.traverseNode({content:e},()=>{});let r=e.matchAll(/(\w+Role|\w+Permission)\.(\w+)/g);for(let s of r)t.push(s[2]);return [...new Set(t)]}extractPermissions(e){let t=[],r=e.matchAll(/(?:Permission|Role|isAdmin)\.\w+/g);for(let s of r)t.includes(s[0])||t.push(s[0]);return t}extractDataFetching(e,t,r){let s=[],i=new Set,n=new Map;for(let[l,u]of this.codegenMap)n.set(l,{operationName:u.operationName,type:u.operationType});let a=V(e,t,n),o=this.getGraphQLHookPatterns();if(M(e,l=>{if(l.type==="CallExpression"){let u=l,f=v(u.callee);if(!f)return;if($(f,o)&&re(u,t,a)){let c=Z(u,t,a),m={type:q(f,o),operationName:c||"unknown"},x=this.extractVariablesFromCall(u);Object.keys(x).length>0&&(m.variables=x);let C=`${m.type}:${m.operationName}`;i.has(C)||(i.add(C),s.push(m));}if(f==="query"||f==="mutate"){let c=this.analyzeClientDirectCall(u,t,a);if(c){let g=`${c.type}:${c.operationName}`;i.has(g)||(i.add(g),s.push(c));}}}}),this.extractSSRDataFetching(e,t,s,i),t.includes("getStaticProps")){let l="getStaticProps:getStaticProps";i.has(l)||(i.add(l),s.push({type:"getStaticProps",operationName:"getStaticProps"}));}return s}analyzeClientDirectCall(e,t,r){if(!e.arguments?.length)return null;let s=e.arguments[0],i=s?.expression||s;if(i?.type!=="ObjectExpression")return null;for(let n of i.properties||[])if(n.type==="KeyValueProperty"&&n.key?.type==="Identifier"&&n.key.value==="query"){let a=n.value,o=null;if(a?.type==="Identifier"){let l=a.value;o=r.variableOperations.get(l)||r.documentImports.get(l)||d(l);}if(a?.type==="MemberExpression"){let l=a.object?.type==="Identifier"?a.object.value:null,u=a.property?.type==="Identifier"?a.property.value:null;if(l&&u){let f=`${l}.${u}`;o=r.staticPropertyOperations.get(f)||d(u);}}if(o)return {type:v(e.callee)==="mutate"?"useMutation":"useQuery",operationName:o}}return null}extractDocumentImports(e){let t=new Map;for(let r of e.body)if(r.type==="ImportDeclaration"){let s=r.source?.value||"",i=s.includes("__generated__")||s.includes("generated")||s.includes("graphql")||s.includes(".generated");for(let n of r.specifiers||[]){let a=n.type==="ImportSpecifier"||n.type==="ImportDefaultSpecifier"?n.local?.value:null;if(a){if(a.endsWith("Document")||i){let o=a.replace(/Document$/,"");t.set(a,o);}(a.endsWith("Query")||a.endsWith("Mutation"))&&t.set(a,a.replace(/Query$|Mutation$/,""));}}}return t}extractVariableAssignments(e,t){let r=new Map;return this.traverseNode(e,s=>{if(s.type==="VariableDeclarator"&&s.id?.type==="Identifier"){let i=s.id.value,n=s.init;if(!n)return;if(n.type==="Identifier"){let a=n.value;(a.endsWith("Document")||a.endsWith("Query"))&&r.set(i,a);}if(n.type==="CallExpression"){let a=this.getCalleeName(n.callee);if(a==="gql"||a==="graphql"){let o=this.extractOperationNameFromGqlCall(n,t);o&&r.set(i,o);}}if(n.type==="TaggedTemplateExpression"){let a=this.getCalleeName(n.tag);if(a==="gql"||a==="graphql"){let o=n.template;if(o?.quasis?.[0]?.raw){let u=o.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);u&&r.set(i,u[1]);}}}}}),r}extractOperationNameFromGqlCall(e,t){if(!e.arguments?.length)return null;let r=e.arguments[0],s=r?.expression||r;if(s?.type==="TemplateLiteral"&&s.quasis?.[0]?.raw){let n=s.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}if(e.span){let n=t.slice(e.span.start,e.span.end).match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}return null}analyzeGraphQLHookCall(e,t,r,s){let i=this.getCalleeName(e.callee);if(!i)return null;let n=this.getGraphQLHookPatterns(),a=W.includes(i),o=R(i,n)&&!i.includes("Params"),l=Q(i,n);if(!a&&!o&&!l)return null;let u=q(i,n),f=i.replace(/^use/,"").replace(/Query$|Mutation$/,""),c=this.extractTypeGeneric(e,t);if(c&&(f=c.replace(/Query$|Mutation$|Variables$/,"")),e.arguments&&e.arguments.length>0){let m=e.arguments[0],x=m?.expression||m,C=this.extractOperationFromArgument(x,r,s);C&&(f=C);}let g=this.extractVariablesFromCall(e);return {type:u,operationName:f,variables:g}}extractTypeGeneric(e,t){if(e.typeArguments?.params?.length>0){let r=e.typeArguments.params[0];if(r?.type==="TsTypeReference"&&r.typeName?.type==="Identifier")return r.typeName.value}if(e.callee?.span){let r=e.callee.span.end,i=t.slice(r,r+100).match(/^<(\w+)(?:Query|Mutation|Variables)?[,>]/);if(i)return i[1]}return null}extractOperationFromArgument(e,t,r){if(!e)return null;if(e.type==="Identifier"){let s=e.value;if(["[","{","'",'"',"`"].some(o=>s.startsWith(o)))return null;let i=r.get(s);if(i)return !i.endsWith("Document")&&!i.endsWith("Query")?i:t.get(i)||i.replace(/Document$/,"");let n=t.get(s);if(n)return n;let a=this.codegenMap.get(s);return a?a.operationName:/^(Query|Mutation|QUERY|MUTATION)$/i.test(s)?null:s.replace(/Document$/,"").replace(/Query$|Mutation$/,"")}if(e.type==="MemberExpression"&&e.property?.type==="Identifier")return e.property.value.replace(/Document$/,"").replace(/Query$|Mutation$/,"");if(e.type==="TaggedTemplateExpression"&&e.template?.quasis?.[0]?.raw){let i=e.template.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(i)return i[1]}if(e.type==="CallExpression"){let s=this.getCalleeName(e.callee);if((s==="graphql"||s==="gql")&&e.arguments?.length>0){let i=e.arguments[0],n=i?.expression||i;if(n?.type==="TemplateLiteral"&&n.quasis?.[0]?.raw){let o=n.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(o)return o[1]}}}if(e.type==="TemplateLiteral"&&e.quasis?.[0]?.raw){let i=e.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(i)return i[1]}return null}extractVariablesFromCall(e){let t=[];if(e.arguments&&e.arguments.length>1){let r=e.arguments[1],s=r?.expression||r;if(s?.type==="ObjectExpression"){for(let i of s.properties||[])if(i.type==="KeyValueProperty"&&i.key?.type==="Identifier"&&i.key.value==="variables"&&i.value?.type==="ObjectExpression")for(let n of i.value.properties||[])n.type==="KeyValueProperty"&&n.key?.type==="Identifier"?t.push(n.key.value):n.type==="Identifier"&&t.push(n.value);}}return t}extractSSRDataFetching(e,t,r,s){let i=this.extractImports(e),n=this.extractDocumentImports(e);for(let a of e.body)if(a.type==="ExportDeclaration"){let o=a.declaration;if(o?.type==="VariableDeclaration")for(let l of o.declarations)l.id?.type==="Identifier"&&l.id.value==="getServerSideProps"&&this.extractSSRQueriesFromNode(l,t,i,n,r,s);o?.type==="FunctionDeclaration"&&o.identifier?.value==="getServerSideProps"&&this.extractSSRQueriesFromNode(o,t,i,n,r,s);}}extractSSRQueriesFromNode(e,t,r,s,i,n){M(e,a=>{if(a.type!=="CallExpression")return;let o=v(a.callee);if(o==="query"||o==="mutate"){let l=this.extractQueryFromClientCall(a,t,r,s);if(l){let u=`getServerSideProps:\u2192 ${l}`;n.has(u)||(n.add(u),i.push({type:"getServerSideProps",operationName:`\u2192 ${l}`}));}}});}extractQueryFromClientCall(e,t,r,s){if(!e.arguments?.length)return null;let i=e.arguments[0],n=i?.expression||i;if(n?.type!=="ObjectExpression")return null;for(let a of n.properties||[])if(a.type==="KeyValueProperty"&&a.key?.type==="Identifier"&&a.key.value==="query"){let o=a.value;if(o?.type==="Identifier"){let l=o.value;if(s.has(l))return s.get(l)||null;let u=this.codegenMap.get(l);return u?u.operationName:r.get(l)?d(l):d(l)}if(o?.type==="MemberExpression"){let l=o.object?.type==="Identifier"?o.object.value:null,u=o.property?.type==="Identifier"?o.property.value:null;if(l&&u)return `${l}.${u}`}}return null}extractNavigation(e){let t={visible:true,currentNavItem:null};(e.includes("hideNavigation")||e.includes("noNav"))&&(t.visible=false),(e.includes("miniNav")||e.includes("collapsedNav"))&&(t.mini=true);let r=e.match(/currentNav(?:Item)?[:\s=]+['"`]([^'"`]+)['"`]/);return r&&(t.currentNavItem=r[1]),t}extractLinkedPages(e,t){let r=[];return this.traverseNode(e,s=>{if(s.type==="JSXOpeningElement"&&this.getJsxTagName(s)==="Link"){let n=this.getJsxAttribute(s,"href");if(n&&n.startsWith("/")&&!n.includes("http")){let a=n.split("?")[0].split("#")[0];r.includes(a)||r.push(a);}}}),r}extractSteps(e){let t=[],r=e.matchAll(/(?:step|Step)\s*[:=]\s*['"`]([^'"`]+)['"`]/g),s=0;for(let i of r)t.push({id:s++,name:i[1]});return t}traverseNode(e,t){if(!(!e||typeof e!="object")){t(e);for(let r of Object.keys(e)){let s=e[r];if(Array.isArray(s))for(let i of s)this.traverseNode(i,t);else s&&typeof s=="object"&&this.traverseNode(s,t);}}}getCalleeName(e){if(e.type==="Identifier")return e.value;if(e.type==="MemberExpression"){let t=e.object,r=e.property;if(t.type==="Identifier"&&r.type==="Identifier")return `${t.value}.${r.value}`}return null}getJsxTagName(e){return e.name?.type==="Identifier"?e.name.value:null}getJsxAttribute(e,t){if(!e.attributes)return null;for(let r of e.attributes)if(r.type==="JSXAttribute"&&r.name?.value===t){if(r.value?.type==="StringLiteral")return r.value.value;if(r.value?.type==="JSXExpressionContainer"&&(r.value.expression?.type==="Identifier"||r.value.expression?.type==="StringLiteral"))return r.value.expression.value}return null}};var ue=class extends A{coverage={tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0};constructor(e){super(e);}getName(){return "GraphQLAnalyzer"}async analyze(){this.log("Starting GraphQL analysis...");let e=[];this.log("[GraphQLAnalyzer] Step 1: Analyzing .graphql files...");let t=await this.analyzeGraphQLFiles();e.push(...t),this.log(`[GraphQLAnalyzer] Step 1 done: ${t.length} from .graphql files`),this.log("[GraphQLAnalyzer] Step 2: Analyzing inline GraphQL...");let r=await this.analyzeInlineGraphQL();e.push(...r),this.log(`[GraphQLAnalyzer] Step 2 done: ${r.length} inline operations`),this.log("[GraphQLAnalyzer] Step 3: Analyzing codegen output...");let s=await this.analyzeCodegenGenerated();e.push(...s),this.log(`[GraphQLAnalyzer] Step 3 done: ${s.length} from codegen`);let i=this.deduplicateOperations(e);return this.log(`[GraphQLAnalyzer] Deduplicated: ${i.length} unique operations`),this.log("[GraphQLAnalyzer] Step 4: Finding operation usage..."),await this.findOperationUsage(i),this.log("[GraphQLAnalyzer] Step 4 done"),this.log(`Found ${i.length} GraphQL operations`),{graphqlOperations:i,coverage:this.coverage}}deduplicateOperations(e){let t=new Map;for(let r of e)if(!t.has(r.name))t.set(r.name,r);else {let s=t.get(r.name);if(s)for(let i of r.usedIn)s.usedIn.includes(i)||s.usedIn.push(i);}return Array.from(t.values())}async analyzeCodegenGenerated(){let e=[],t=await glob(["**/__generated__/graphql.ts","**/__generated__/gql.ts","**/generated/graphql.ts","**/generated/gql.ts","**/*.generated.ts","**/*.generated.tsx","**/graphql/generated.ts","**/gql/generated.ts"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],absolute:true});for(let r of t)try{let s=await T.readFile(r,"utf-8"),i=y.relative(this.basePath,r);if(!s.includes("Document")||!s.includes("definitions"))continue;this.coverage.codegenFilesDetected+=1;let n=k(s,i);this.coverage.codegenFilesParsed+=1,this.coverage.codegenExportsFound+=n.length;for(let a of n){let l=a.document?.definitions?.[0];if(!l||l.kind!=="OperationDefinition")continue;let u=(l.variableDefinitions||[]).map(f=>({name:f.variable?.name?.value||"unknown",type:this.extractTypeFromAst(f.type),required:f.type?.kind==="NonNullType"}));e.push({name:a.operationName,type:a.operationType,filePath:i,usedIn:[],variables:u,returnType:this.inferReturnTypeFromAst(l),fragments:this.extractFragmentReferencesFromAst(l),fields:this.extractFieldsFromAst(l.selectionSet),variableNames:[a.documentName]});}n.length>0&&this.log(`Found ${n.length} operations in codegen output: ${i}`);}catch(s){this.warn(`Failed to analyze codegen file ${r}: ${s.message}`);}return e}extractTypeFromAst(e){return e?e.kind==="NonNullType"?`${this.extractTypeFromAst(e.type)}!`:e.kind==="ListType"?`[${this.extractTypeFromAst(e.type)}]`:e.kind==="NamedType"&&e.name?.value||"unknown":"unknown"}extractFieldsFromAst(e,t=0){if(!e?.selections||t>5)return [];let r=[];for(let s of e.selections)if(s.kind==="Field"){let i={name:s.name?.value||"unknown"};if(s.arguments?.length>0){let n=s.arguments.map(a=>a.name?.value).join(", ");i.type=`(${n})`;}s.selectionSet&&(i.fields=this.extractFieldsFromAst(s.selectionSet,t+1)),r.push(i);}else if(s.kind==="FragmentSpread")r.push({name:`...${s.name?.value}`,type:"fragment"});else if(s.kind==="InlineFragment"){let i=s.typeCondition?.name?.value||"inline";r.push({name:`... on ${i}`,type:"inline-fragment",fields:this.extractFieldsFromAst(s.selectionSet,t+1)});}return r}extractFragmentReferencesFromAst(e){let t=[],r=s=>{if(s&&(s.kind==="FragmentSpread"&&t.push(s.name?.value),s.selectionSet?.selections))for(let i of s.selectionSet.selections)r(i);};return r(e),t.filter(Boolean)}inferReturnTypeFromAst(e){if(e.selectionSet?.selections?.length>0){let t=e.selectionSet.selections[0];if(t.kind==="Field")return t.name?.value||"unknown"}return "unknown"}async analyzeGraphQLFiles(){let e=await glob(["**/*.graphql"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**"],absolute:true});return (await S(e,async r=>{let s=await T.readFile(r,"utf-8");try{let i=parse(s);return this.extractOperationsFromDocument(i,y.relative(this.basePath,r))}catch{return this.coverage.graphqlParseFailures+=1,[]}})).flat()}async analyzeInlineGraphQL(){let e=[],t=await glob(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__tests__/**","**/*.test.*","**/*.spec.*","**/__generated__/**"],absolute:true});this.coverage.tsFilesScanned+=t.length;let r=50;for(let s=0;s<t.length;s+=r){let i=t.slice(s,s+r),n=await S(i,async a=>{try{let o=await T.readFile(a,"utf-8");if(!o.includes("gql")&&!o.includes("graphql"))return [];let l=y.relative(this.basePath,a),u=a.endsWith(".tsx")||a.endsWith(".jsx"),f=parseSync(o,{syntax:a.endsWith(".ts")||a.endsWith(".tsx")?"typescript":"ecmascript",tsx:u,jsx:u});return this.analyzeModuleForGraphQL(f,o,l)}catch{return this.coverage.tsParseFailures+=1,[]}},10);e.push(...n.flat());}return e}analyzeModuleForGraphQL(e,t,r){let s=[],i=[];return this.traverseNodeWithContext(e,i,(n,a)=>{if(n.type==="TaggedTemplateExpression"){let o=n,l=this.getTagName(o.tag);if(l==="gql"||l==="graphql"){let u=this.extractTemplateContent(o.template,t);if(u)try{let f=parse(u),c=this.extractOperationsFromDocument(f,r);if(a)for(let g of c)g.variableNames=g.variableNames||[],g.variableNames.push(a),g.variableNames.push(`${g.name}Document`);s.push(...c);}catch{this.coverage.graphqlParseFailures+=1;}}}if(n.type==="CallExpression"){let o=n,l=this.getCalleeName(o.callee);if((l==="gql"||l==="graphql")&&o.arguments.length>0){let u=o.arguments[0].expression,f=this.extractGraphQLFromExpression(u,t);if(f)try{let c=parse(f),g=this.extractOperationsFromDocument(c,r);if(a)for(let m of g)m.variableNames=m.variableNames||[],m.variableNames.push(a),m.variableNames.push(`${m.name}Document`);s.push(...g);}catch{this.coverage.graphqlParseFailures+=1;}}}}),s}traverseNodeWithContext(e,t,r){if(!e||typeof e!="object")return;let s=false;e.type==="VariableDeclarator"&&e.id?.type==="Identifier"&&(t.push(e.id.value),s=true),r(e,t.length>0?t[t.length-1]:null);for(let i of Object.keys(e)){let n=e[i];if(Array.isArray(n))for(let a of n)this.traverseNodeWithContext(a,t,r);else n&&typeof n=="object"&&this.traverseNodeWithContext(n,t,r);}s&&t.pop();}getTagName(e){return e.type==="Identifier"?e.value:null}getCalleeName(e){return e.type==="Identifier"?e.value:null}extractTemplateContent(e,t){if(e.type==="TemplateLiteral"){if(e.quasis.length===1&&e.expressions.length===0)return e.quasis[0].raw;let r=e.span.start,s=e.span.end;return t.slice(r,s).slice(1,-1).replace(/\$\{[^}]*\}/g,"")}return null}extractGraphQLFromExpression(e,t){return e.type==="TemplateLiteral"?this.extractTemplateContent(e,t):e.type==="StringLiteral"?e.value:null}extractOperationsFromDocument(e,t){let r=[];for(let s of e.definitions){let i=this.extractOperation(s,t);i&&r.push(i);}return r}extractOperation(e,t){if(e.kind==="OperationDefinition"){let r=e.name?.value||"anonymous",s=e.operation,i=this.extractVariables(e),n=this.extractFragmentReferences(e),a=this.extractFields(e),o=e.loc?getLocation(e.loc.source,e.loc.start):null;return {name:r,type:s,filePath:t,line:o?.line,column:o?.column,usedIn:[],variables:i,returnType:this.inferReturnType(e),fragments:n,fields:a}}if(e.kind==="FragmentDefinition"){let r=e.loc?getLocation(e.loc.source,e.loc.start):null;return {name:e.name.value,type:"fragment",filePath:t,line:r?.line,column:r?.column,usedIn:[],variables:[],returnType:e.typeCondition.name.value,fragments:this.extractFragmentReferences(e),fields:this.extractFields(e)}}return null}extractFields(e){let t=[],r=(s,i=0)=>{if(!s||!s.selections||i>5)return [];let n=[];for(let a of s.selections)if(a.kind==="Field"){let o={name:a.name.value};if(a.arguments&&a.arguments.length>0){let l=a.arguments.map(u=>u.name.value).join(", ");o.type=`(${l})`;}a.selectionSet&&(o.fields=r(a.selectionSet,i+1)),n.push(o);}else if(a.kind==="FragmentSpread")n.push({name:`...${a.name.value}`,type:"fragment"});else if(a.kind==="InlineFragment"&&a.selectionSet){let o=a.typeCondition?.name?.value||"inline";n.push({name:`... on ${o}`,type:"inline-fragment",fields:r(a.selectionSet,i+1)});}return n};return e.selectionSet?r(e.selectionSet):t}extractVariables(e){let t=[];if(e.variableDefinitions)for(let r of e.variableDefinitions){let s=r.variable.name.value,i=this.typeNodeToString(r.type),n=r.type.kind==="NonNullType";t.push({name:s,type:i,required:n});}return t}typeNodeToString(e){return e.kind==="NonNullType"?`${this.typeNodeToString(e.type)}!`:e.kind==="ListType"?`[${this.typeNodeToString(e.type)}]`:e.kind==="NamedType"?e.name.value:"unknown"}extractFragmentReferences(e){let t=[],r=s=>{if(s&&(s.kind==="FragmentSpread"&&t.push(s.name.value),s.selectionSet))for(let i of s.selectionSet.selections)r(i);};return r(e),t}inferReturnType(e){if(e.selectionSet&&e.selectionSet.selections.length>0){let t=e.selectionSet.selections[0];if(t.kind==="Field")return t.name.value}return "unknown"}async findOperationUsage(e){if(e.length===0)return;let t=this.getGraphQLHookPatterns(),r=await glob(["**/*.ts","**/*.tsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__generated__/**","**/dist/**","**/build/**"],absolute:true}),s=new Map,i=new Map,n=new Map,a=new Map;for(let c of e)if(s.set(c.name,c),i.set(`${c.name}Document`,c),a.set(`${c.name}Query`,c),a.set(`${c.name}Mutation`,c),a.set(`${c.name}Subscription`,c),a.set(`${c.name}QueryVariables`,c),a.set(`${c.name}MutationVariables`,c),c.variableNames)for(let g of c.variableNames)n.set(g,c);let o=new Set;for(let c of e)if(o.add(c.name),o.add(`${c.name}Document`),o.add(`${c.name}Query`),o.add(`${c.name}Mutation`),o.add(`${c.name}Subscription`),c.variableNames)for(let g of c.variableNames)o.add(g);let l=null,u=Array.from(o);if(u.length>0&&u.length<2e3){let c=u.sort((g,m)=>m.length-g.length).map(g=>g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));l=new RegExp(`\\b(${c.join("|")})\\b`,"g");}let f=50;for(let c=0;c<r.length;c+=f){let g=r.slice(c,c+f);await Promise.all(g.map(async m=>{try{let x=await T.readFile(m,"utf-8"),C=y.relative(this.basePath,m);if(!H(x))return;if(l){let I=new Set,Y;for(;(Y=l.exec(x))!==null;)I.add(Y[1]);l.lastIndex=0;for(let z of I){let L=i.get(z)||n.get(z)||s.get(z);L&&C!==L.filePath&&(L.usedIn.includes(C)||L.usedIn.push(C));}}await this.findUsageWithAST(x,m,C,s,a,n,t);}catch{}}));}}async findUsageWithAST(e,t,r,s,i,n,a){try{let o=t.endsWith(".tsx")||t.endsWith(".jsx"),l=parseSync(e,{syntax:t.endsWith(".ts")||t.endsWith(".tsx")?"typescript":"ecmascript",tsx:o,jsx:o,comments:!1});this.traverseNodeForUsage(l,e,u=>{if(u.type==="CallExpression"){let f=this.getCalleeNameForUsage(u.callee);if(f&&$(f,a)){let c=this.extractTypeGenericFromCall(u,e);if(c){let m=i.get(c)||s.get(c.replace(/Query$|Mutation$|Variables$/,""));m&&r!==m.filePath&&(m.usedIn.includes(r)||m.usedIn.push(r));}let g=this.extractFirstArgName(u);if(g){let m=g.replace(/Document$/,""),x=n.get(g)||n.get(m)||s.get(m)||i.get(g);x&&r!==x.filePath&&(x.usedIn.includes(r)||x.usedIn.push(r));}}}});}catch{}}traverseNodeForUsage(e,t,r){if(!(!e||typeof e!="object")){r(e);for(let s of Object.keys(e)){let i=e[s];if(Array.isArray(i))for(let n of i)this.traverseNodeForUsage(n,t,r);else i&&typeof i=="object"&&this.traverseNodeForUsage(i,t,r);}}}getCalleeNameForUsage(e){return e?e.type==="Identifier"?e.value:e.type==="MemberExpression"&&e.property?.type==="Identifier"?e.property.value:null:null}extractTypeGenericFromCall(e,t){if(e.typeArguments?.params?.length>0){let r=e.typeArguments.params[0];if(r?.type==="TsTypeReference"&&r.typeName?.type==="Identifier")return r.typeName.value}if(e.callee?.span){let r=e.callee.span.end,i=t.slice(r,r+150).match(/^<\s*(\w+)(?:Query|Mutation|Variables|Subscription)?(?:\s*,|\s*>)/);if(i)return i[1]}return null}extractFirstArgName(e){if(e.arguments?.length>0){let t=e.arguments[0].expression;if(t?.type==="Identifier")return t.value;if(t?.type==="MemberExpression"&&t.property?.type==="Identifier")return t.property.value}return null}};var fe=class extends A{componentCache=new Map;coverage={tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0};constructor(e){super(e);}getName(){return "DataFlowAnalyzer"}async analyze(){this.log("Starting data flow analysis...");let e=await this.analyzeComponents(),t=await this.analyzeDataFlows(e);return this.log(`Analyzed ${e.length} components and ${t.length} data flows`),{components:e,dataFlows:t,coverage:this.coverage}}async analyzeComponents(){let e=[],t=[this.getSetting("featuresDir",""),this.getSetting("componentsDir",""),this.getSetting("pagesDir","")].filter(Boolean),r=["src/features","src/components","src/common/components","src/common","src/pages","src/app","src/modules","src/views","src/screens","components","pages","app"],i=[...new Set([...t,...r])].flatMap(o=>[`${o}/**/*.tsx`,`${o}/**/*.ts`]),n=await glob(i,{cwd:this.basePath,ignore:["**/*.test.*","**/*.spec.*","**/*.stories.*","**/node_modules/**","**/__generated__/**"],absolute:true,nodir:true});this.log(`[DataFlowAnalyzer] Found ${n.length} component files to analyze`),this.coverage.tsFilesScanned+=n.length;let a=50;for(let o=0;o<n.length;o+=a){let l=n.slice(o,o+a),u=await Promise.all(l.map(async f=>{try{let c=await T.readFile(f,"utf-8");return {filePath:f,content:c}}catch{return null}}));for(let f of u)if(f)try{let c=parseSync(f.content,{syntax:"typescript",tsx:!0,comments:!1}),g=y.relative(this.basePath,f.filePath),m=this.analyzeComponentFile(c,g,f.content);e.push(...m);}catch{this.coverage.tsParseFailures+=1;}}return this.log(`[DataFlowAnalyzer] Extracted ${e.length} components`),this.buildDependencyGraph(e),e}analyzeComponentFile(e,t,r){let s=[],i=this.extractImports(e);for(let n of e.body){if(n.type==="ExportDeclaration"&&n.declaration?.type==="FunctionDeclaration"){let a=n.declaration.identifier?.value;if(a&&this.isComponentName(a)){let o=this.extractComponentInfo(a,t,r,i);s.push(o),this.componentCache.set(a,o);}}if(n.type==="FunctionDeclaration"){let a=n.identifier?.value;if(a&&this.isComponentName(a)){let o=this.extractComponentInfo(a,t,r,i);s.push(o),this.componentCache.set(a,o);}}if(n.type==="ExportDefaultDeclaration"&&n.decl?.type==="FunctionExpression"){let a=n.decl.identifier?.value;if(a&&this.isComponentName(a)){let o=this.extractComponentInfo(a,t,r,i);s.push(o),this.componentCache.set(a,o);}}if(n.type==="VariableDeclaration"){for(let a of n.declarations)if(a.id?.type==="Identifier"){let o=a.id.value;if(o&&(this.isComponentName(o)||o.startsWith("use"))&&a.init&&(a.init.type==="ArrowFunctionExpression"||a.init.type==="FunctionExpression")){let l=this.extractComponentInfo(o,t,r,i);s.push(l),this.componentCache.set(o,l);}}}if(n.type==="ExportDeclaration"&&n.declaration?.type==="VariableDeclaration"){for(let a of n.declaration.declarations)if(a.id?.type==="Identifier"){let o=a.id.value;if(o&&(this.isComponentName(o)||o.startsWith("use"))&&a.init&&(a.init.type==="ArrowFunctionExpression"||a.init.type==="FunctionExpression")){let l=this.extractComponentInfo(o,t,r,i);s.push(l),this.componentCache.set(o,l);}}}}return s}extractImports(e){let t=new Map,r=this.getListSetting("aliasPrefixes",["@/","~/","#/"]);for(let s of e.body)if(s.type==="ImportDeclaration"){let i=s.source?.value||"",n=r.some(a=>i.startsWith(a));if(i.startsWith(".")||n)for(let a of s.specifiers||[])a.type==="ImportSpecifier"&&a.local?.value&&t.set(a.local.value,i),a.type==="ImportDefaultSpecifier"&&a.local?.value&&t.set(a.local.value,i);}return t}isComponentName(e){return /^[A-Z][a-zA-Z0-9]*$/.test(e)}extractComponentInfo(e,t,r,s){let i="presentational";["/pages/","/app/","/routes/","/views/","/screens/"].some(f=>t.includes(f))?i="page":e.includes("Container")||e.includes("Provider")?i="container":e.includes("Layout")||e.includes("Shell")||e.includes("Wrapper")||e.includes("Frame")||e.includes("Scaffold")||t.includes("/layouts/")||t.includes("/layout/")?i="layout":e.startsWith("use")&&(i="hook");let a=this.extractHooksUsed(r),o=Array.from(s.keys()).filter(f=>this.isComponentName(f)||f.startsWith("use")),l=[];for(let[f,c]of s)l.push({name:f,path:c});let u=this.extractStateManagement(r);return {name:e,filePath:t,type:i,props:[],dependencies:o,dependents:[],hooks:a,stateManagement:u,imports:l}}extractHooksUsed(e){let t=[],r=new Set;if(!e.includes("use"))return t;try{let s=parseSync(e,{syntax:"typescript",tsx:!0,comments:!1}),i=this.extractDocumentImportsFromAst(s),n=this.extractVariableOperationMap(s,e);this.traverseForHooks(s,e,i,n,t,r);}catch{this.extractHooksWithRegex(e,t,r);}return t}extractDocumentImportsFromAst(e){let t=new Map;for(let r of e.body)if(r.type==="ImportDeclaration"){let s=r.source?.value||"",i=s.includes("__generated__")||s.includes("generated")||s.includes("graphql")||s.includes(".generated");for(let n of r.specifiers||[]){let a;(n.type==="ImportSpecifier"||n.type==="ImportDefaultSpecifier")&&(a=n.local?.value),a&&((a.endsWith("Document")||i)&&t.set(a,a.replace(/Document$/,"")),(a.endsWith("Query")||a.endsWith("Mutation"))&&t.set(a,a.replace(/Query$|Mutation$/,"")));}}return t}extractVariableOperationMap(e,t){let r=new Map,s=n=>{if(n.type!=="VariableDeclarator"||n.id?.type!=="Identifier")return;let a=n.id.value,o=n.init;if(o){if(o.type==="CallExpression"){let l=this.getCalleeNameFromNode(o.callee);if(l==="gql"||l==="graphql"){let u=this.extractOperationNameFromGqlCall(o,t);u&&r.set(a,u);}}if(o.type==="TaggedTemplateExpression"){let l=this.getCalleeNameFromNode(o.tag);if((l==="gql"||l==="graphql")&&o.template?.quasis?.[0]?.raw){let f=o.template.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);f&&r.set(a,f[1]);}}}},i=n=>{if(!(!n||typeof n!="object")){s(n);for(let a of Object.keys(n)){let o=n[a];if(Array.isArray(o))for(let l of o)i(l);else o&&typeof o=="object"&&i(o);}}};return i(e),r}extractOperationNameFromGqlCall(e,t){if(!e.arguments?.length)return null;let r=e.arguments[0],s=r?.expression||r;if(s?.type==="TemplateLiteral"&&s.quasis?.[0]?.raw){let n=s.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}if(e.span){let n=t.slice(e.span.start,e.span.end).match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}return null}traverseForHooks(e,t,r,s,i,n){if(!(!e||typeof e!="object")){e.type==="CallExpression"&&this.analyzeHookCall(e,t,r,s,i,n);for(let a of Object.keys(e)){let o=e[a];if(Array.isArray(o))for(let l of o)this.traverseForHooks(l,t,r,s,i,n);else o&&typeof o=="object"&&this.traverseForHooks(o,t,r,s,i,n);}}}analyzeHookCall(e,t,r,s,i,n){let a=this.getCalleeNameFromNode(e.callee);if(!a||!a.startsWith("use"))return;let o=R(a),l=Q(a),u=ne(a);if((o||l||u)&&this.hasGraphQLArgument(e,t,r,s)){let c=this.extractOperationNameFromCall(e,t,r,s),g=l?"Mutation":u?"Subscription":"Query",m=c?`${g}: ${c}`:`${g}: unknown`;n.has(m)||(n.add(m),i.push(m));return}if(a==="useContext"){let f=this.extractContextName(e);if(f){let c=`\u{1F504} Context: ${f}`;n.has(c)||(n.add(c),i.push(c));}return}n.has(a)||(n.add(a),i.push(a));}hasGraphQLArgument(e,t,r,s){if(!e.arguments?.length)return false;let i=e.arguments[0],n=i?.expression||i;if(!n)return false;if(n.type==="Identifier"){let a=n.value;if(r.has(a)||s.has(a)||a.endsWith("Document")||/[A-Z][a-z]*Query$/.test(a)||/[A-Z][a-z]*Mutation$/.test(a)||/^[A-Z][A-Z0-9_]*_QUERY$/.test(a)||/^[A-Z][A-Z0-9_]*_MUTATION$/.test(a))return true}if(n.type==="TaggedTemplateExpression"){let a=this.getCalleeNameFromNode(n.tag);if(a==="gql"||a==="graphql")return true}if(n.type==="CallExpression"){let a=this.getCalleeNameFromNode(n.callee);if(a==="gql"||a==="graphql")return true}if(n.type==="TemplateLiteral"&&n.quasis?.[0]?.raw){let a=n.quasis[0].raw;if(/(?:query|mutation|subscription)\s+\w+/i.test(a))return true}if(n.type==="MemberExpression"){let a=n.property?.value;if(a&&/Query$|Mutation$|Document$/.test(a))return true}if(e.span){let a=t.slice(e.span.start,Math.min(e.span.end,e.span.start+500));if(a.includes("Document")||/\bgql\s*[`(]/.test(a)||/\bgraphql\s*[`(]/.test(a)||/query\s+\w+\s*[({]/.test(a)||/mutation\s+\w+\s*[({]/.test(a))return true}return false}getCalleeNameFromNode(e){return e?e.type==="Identifier"?e.value:e.type==="MemberExpression"&&e.property?.type==="Identifier"?e.property.value:null:null}extractOperationNameFromCall(e,t,r,s){if(e.typeArguments?.params?.length>0){let i=e.typeArguments.params[0];if(i?.type==="TsTypeReference"&&i.typeName?.type==="Identifier"){let n=i.typeName.value;return d(n)}}if(e.callee?.span&&e.span){let i=e.callee.span.end,n=Math.min(i+150,e.span.end),o=t.slice(i,n).match(/^<\s*(\w+)(?:Query|Mutation|Variables|Subscription)?[\s,>]/);if(o)return d(o[1])}if(e.arguments?.length>0){let i=e.arguments[0],n=i?.expression||i;if(!n)return null;if(n.type==="Identifier"){let a=n.value,o=s.get(a);if(o)return o;let l=r.get(a);return l||(/^(Query|Mutation|QUERY|MUTATION)$/i.test(a)?null:d(a))}if(n.type==="MemberExpression"&&n.property?.type==="Identifier")return d(n.property.value);if(n.type==="TaggedTemplateExpression"&&n.template?.quasis?.[0]?.raw){let o=n.template.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(o)return o[1]}if(n.type==="CallExpression"){let a=this.getCalleeNameFromNode(n.callee);if((a==="graphql"||a==="gql")&&n.arguments?.length>0){let o=n.arguments[0],l=o?.expression||o;if(l?.type==="TemplateLiteral"&&l.quasis?.[0]?.raw){let f=l.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(f)return f[1]}}}if(n.type==="TemplateLiteral"&&n.quasis?.[0]?.raw){let o=n.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(o)return o[1]}}if(e.span){let i=t.slice(e.span.start,e.span.end),n=i.match(/\b([A-Z][a-zA-Z0-9]*Document)\b/);if(n)return d(n[1]);let a=i.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(a)return a[1]}return null}extractContextName(e){if(e.arguments?.length>0){let t=e.arguments[0].expression;if(t?.type==="Identifier")return t.value.replace(/Context$/,"")}return null}extractHooksWithRegex(e,t,r){let s=/\b(useQuery|useMutation|useLazyQuery|useSuspenseQuery|useBackgroundQuery|useSubscription)(?:<[^>]*>)?\s*\(\s*([A-Z_][A-Za-z0-9_]*)?/gs,i;for(;(i=s.exec(e))!==null;){let o=i[1],l=i[2];if(l&&/^(Query|Mutation|QUERY|MUTATION)$/i.test(l))continue;let u=l?d(l):"unknown",c=`${o.includes("Mutation")?"Mutation":o.includes("Subscription")?"Subscription":"Query"}: ${u}`;r.has(c)||(r.add(c),t.push(c));}let n=/\b(use[A-Z][a-zA-Z0-9]*)\s*\(/g,a;for(;(a=n.exec(e))!==null;){let o=a[1];if(!["useQuery","useMutation","useLazyQuery","useSuspenseQuery","useBackgroundQuery","useSubscription"].includes(o))if(o==="useContext"){let l=e.slice(a.index).match(/useContext\s*\(\s*([A-Z][A-Za-z0-9]*)/);if(l){let f=`\u{1F504} Context: ${l[1].replace(/Context$/,"")}`;r.has(f)||(r.add(f),t.push(f));}}else r.has(o)||(r.add(o),t.push(o));}}extractStateManagement(e){let t=[];return e.includes("useState")&&t.push("useState"),e.includes("useReducer")&&t.push("useReducer"),e.includes("useContext")&&t.push("useContext"),e.includes("useQuery")&&t.push("Apollo Query"),e.includes("useMutation")&&t.push("Apollo Mutation"),e.includes("useRecoil")&&t.push("Recoil"),(e.includes("useSelector")||e.includes("useDispatch"))&&t.push("Redux"),t}buildDependencyGraph(e){let t=new Map;for(let r of e)t.set(r.name,r);for(let r of e)for(let s of r.dependencies){let i=t.get(s);i&&!i.dependents.includes(r.name)&&i.dependents.push(r.name);}}async analyzeDataFlows(e){let t=[],r=1,s=this.analyzeContextFlows(e);t.push(...s.map(a=>({...a,id:`flow-${r++}`})));let i=this.analyzeApolloFlows(e);t.push(...i.map(a=>({...a,id:`flow-${r++}`})));let n=this.analyzePropDrilling(e);return t.push(...n.map(a=>({...a,id:`flow-${r++}`}))),t}analyzeContextFlows(e){let t=[],r=e.filter(i=>i.name.includes("Provider")||i.name.includes("Context")),s=e.filter(i=>i.hooks.some(n=>n.includes("Context")));for(let i of r){let n=i.name.replace("Provider","").replace("Context","");for(let a of s){let o=a.hooks.find(l=>l.includes("Context")&&l.includes(n));(o||a.hooks.some(l=>l.includes(n)))&&t.push({name:`\u{1F504} ${n} Context`,description:`Data flows from ${i.name} to ${a.name} via Context`,source:{type:"context",name:i.name},target:{type:"component",name:a.name},via:[],operations:[o||`useContext(${n})`]});}}return t}analyzeApolloFlows(e){let t=[];for(let r of e){let s=r.hooks.filter(n=>n.includes("Query:")||n==="useQuery"||n==="useLazyQuery");for(let n of s){let a=n.includes(":")?n.split(":")[1].trim():r.name;t.push({name:`Query: ${a}`,description:`${r.name} fetches ${a} via Apollo`,source:{type:"api",name:`GraphQL: ${a}`},target:{type:"component",name:r.name},via:[{type:"cache",name:"Apollo Cache"}],operations:[n]});}let i=r.hooks.filter(n=>n.includes("Mutation:")||n==="useMutation");for(let n of i){let a=n.includes(":")?n.split(":")[1].trim():r.name;t.push({name:`Mutation: ${a}`,description:`${r.name} mutates ${a} via Apollo`,source:{type:"component",name:r.name},target:{type:"api",name:`GraphQL: ${a}`},via:[],operations:[n]});}}return t}analyzePropDrilling(e){let t=[];for(let r of e)r.props.length>5&&r.dependents.length>0&&t.push({name:`Prop Drilling through ${r.name}`,description:`${r.name} passes ${r.props.length} props to children`,source:{type:"component",name:r.name},target:{type:"component",name:r.dependents[0]},via:[],operations:["props"]});return t}};var he=class p extends A{apiCallCounter=0;constructor(e){super(e);}getName(){return "RestApiAnalyzer"}async analyze(){this.log("Starting REST API analysis...");let e=await glob(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__tests__/**","**/*.test.*","**/*.spec.*","**/*.stories.*","**/__generated__/**","**/dist/**","**/build/**"],absolute:true}),t=50,r=[];for(let s=0;s<e.length;s+=t){let i=e.slice(s,s+t),n=await S(i,async a=>{try{let o=await T.readFile(a,"utf-8"),l=y.relative(this.basePath,a),u=a.endsWith(".tsx")||a.endsWith(".jsx"),f=parseSync(o,{syntax:a.endsWith(".ts")||a.endsWith(".tsx")?"typescript":"ecmascript",tsx:u,jsx:u});return this.analyzeModule(f,o,l)}catch{return []}},10);r.push(...n.flat());}return this.log(`Found ${r.length} REST API calls`),{apiCalls:r}}analyzeModule(e,t,r){let s=[],i=t.split(`
2
+ `);return this.traverseNode(e,n=>{if(n.type==="CallExpression"){let a=n,o=this.analyzeCallExpression(a,r,i);o&&s.push(o);}}),s}traverseNode(e,t){if(!(!e||typeof e!="object")){t(e);for(let r of Object.keys(e)){let s=e[r];if(Array.isArray(s))for(let i of s)this.traverseNode(i,t);else s&&typeof s=="object"&&this.traverseNode(s,t);}}}analyzeCallExpression(e,t,r){let s=e.callee;if(s.type==="Super"||s.type==="Import")return null;let i=this.getCalleeName(s);if(!i)return null;if(i==="fetch"||i==="window.fetch")return this.extractFetchCall(e,t,r);let n=i.match(/^axios\.(get|post|put|delete|patch)$/i);return n?this.extractAxiosMethodCall(e,t,r,n[1].toUpperCase()):i==="axios"?this.extractAxiosDirectCall(e,t,r):i==="useSWR"||i==="useSWRImmutable"?this.extractSwrCall(e,t,r):null}getCalleeName(e){if(e.type==="Identifier")return e.value;if(e.type==="MemberExpression"){let t=e.object,r=e.property;if(t.type==="Identifier"&&r.type==="Identifier")return `${t.value}.${r.value}`}return null}extractFetchCall(e,t,r){if(e.arguments.length===0)return null;let s=e.arguments[0],i=this.extractUrlFromExpression(s.expression);if(!i.url||!i.isPlaceholder&&!this.isApiUrl(i.url))return null;let n="GET",a=false;if(e.arguments.length>1){let l=e.arguments[1].expression;if(l.type==="ObjectExpression")for(let u of l.properties)u.type==="KeyValueProperty"&&u.key.type==="Identifier"&&(u.key.value==="method"&&u.value.type==="StringLiteral"&&(n=this.normalizeMethod(u.value.value)),(u.key.value==="credentials"||u.key.value==="headers")&&(a=true));}let o=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:n,url:i.url,callType:"fetch",filePath:t,line:o,containingFunction:"unknown",usedIn:[],requiresAuth:a,category:this.categorizeApi(i.url)}}extractAxiosMethodCall(e,t,r,s){if(e.arguments.length===0)return null;let i=e.arguments[0],n=this.extractUrlFromExpression(i.expression);if(!n.url)return null;let a=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:this.normalizeMethod(s),url:n.url,callType:"axios",filePath:t,line:a,containingFunction:"unknown",usedIn:[],requiresAuth:false,category:this.categorizeApi(n.url)}}extractAxiosDirectCall(e,t,r){if(e.arguments.length===0)return null;let s=e.arguments[0].expression;if(s.type!=="ObjectExpression")return null;let i=null,n="GET";for(let o of s.properties)o.type==="KeyValueProperty"&&o.key.type==="Identifier"&&(o.key.value==="url"&&o.value.type==="StringLiteral"&&(i=o.value.value),o.key.value==="method"&&o.value.type==="StringLiteral"&&(n=this.normalizeMethod(o.value.value)));if(!i)return null;let a=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:n,url:i,callType:"axios",filePath:t,line:a,containingFunction:"unknown",usedIn:[],requiresAuth:false,category:this.categorizeApi(i)}}extractSwrCall(e,t,r){if(e.arguments.length===0)return null;let s=e.arguments[0].expression,i=this.extractUrlFromExpression(s);if(!i.url)return null;let n=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:"GET",url:i.url,callType:"useSWR",filePath:t,line:n,containingFunction:"unknown",usedIn:[],requiresAuth:false,category:this.categorizeApi(i.url)}}extractUrlFromExpression(e){if(e.type==="StringLiteral")return {url:e.value,isPlaceholder:false};if(e.type==="TemplateLiteral")return e.quasis.length===1&&e.expressions.length===0?{url:e.quasis[0].raw,isPlaceholder:false}:{url:e.quasis.map(s=>s.raw).join(":param"),isPlaceholder:true};if(e.type==="Identifier")return {url:`[${e.value}]`,isPlaceholder:true};if(e.type==="MemberExpression"){let t=e.object.type==="Identifier"?e.object.value:"?",r=e.property.type==="Identifier"?e.property.value:"?";return {url:`[${t}.${r}]`,isPlaceholder:true}}if(e.type==="ConditionalExpression"){let t=this.extractUrlFromExpression(e.consequent);return t.url?t:this.extractUrlFromExpression(e.alternate)}return {url:null,isPlaceholder:false}}getLineNumber(e,t){let r=0;for(let s=0;s<t.length;s++)if(r+=t[s].length+1,r>e)return s+1;return t.length}static STATIC_FILE_EXTENSIONS=/\.(css|js|mjs|cjs|ts|tsx|jsx|png|jpg|jpeg|gif|webp|svg|ico|woff|woff2|ttf|eot|otf|mp3|mp4|webm|ogg|wav|pdf|doc|docx|xls|xlsx|ppt|pptx|zip|tar|gz|rar|html|htm|xml|txt|md|map|wasm)$/i;static NON_API_SCHEMES=/^(data:|blob:|javascript:|mailto:|tel:|file:)/;isApiUrl(e){return p.NON_API_SCHEMES.test(e)||p.STATIC_FILE_EXTENSIONS.test(e)||!e.trim()?false:!!(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("[")||e.includes("/api/")||e.includes("/v1/")||e.includes("/v2/")||e.includes("/graphql"))}static SERVICE_PATTERNS=[{pattern:/amazonaws\.com|\.s3\./i,name:"AWS"},{pattern:/googleapis\.com|google\.com\/api/i,name:"Google API"},{pattern:/graph\.facebook\.com|facebook\.com\/v\d+/i,name:"Facebook"},{pattern:/api\.twitter\.com|twitter\.com\/\d+/i,name:"Twitter/X"},{pattern:/api\.github\.com|github\.com\/api/i,name:"GitHub API"},{pattern:/stripe\.com/i,name:"Stripe"},{pattern:/paypal\.com/i,name:"PayPal"},{pattern:/slack\.com/i,name:"Slack"},{pattern:/discord\.com|discordapp\.com/i,name:"Discord"},{pattern:/twilio\.com/i,name:"Twilio"},{pattern:/sendgrid\.(com|net)/i,name:"SendGrid"},{pattern:/mailchimp\.com/i,name:"Mailchimp"},{pattern:/hubspot\.com|hsforms\.com/i,name:"HubSpot"},{pattern:/salesforce\.com/i,name:"Salesforce"},{pattern:/zendesk\.com/i,name:"Zendesk"},{pattern:/intercom\.io/i,name:"Intercom"},{pattern:/firebase(io)?\.com|firestore\.googleapis/i,name:"Firebase"},{pattern:/supabase\.(co|com|io)/i,name:"Supabase"},{pattern:/auth0\.com/i,name:"Auth0"},{pattern:/okta\.com/i,name:"Okta"},{pattern:/clerk\.(dev|com)/i,name:"Clerk"},{pattern:/cloudflare\.com|workers\.dev/i,name:"Cloudflare"},{pattern:/vercel\.com|vercel\.app/i,name:"Vercel"},{pattern:/netlify\.com|netlify\.app/i,name:"Netlify"},{pattern:/heroku\.com|herokuapp\.com/i,name:"Heroku"},{pattern:/railway\.app/i,name:"Railway"},{pattern:/render\.com/i,name:"Render"},{pattern:/digitalocean\.com/i,name:"DigitalOcean"},{pattern:/algolia\.(com|net|io)/i,name:"Algolia"},{pattern:/elastic\.co|elasticsearch/i,name:"Elasticsearch"},{pattern:/mongodb\.com|mongodb\.net/i,name:"MongoDB"},{pattern:/planetscale\.com/i,name:"PlanetScale"},{pattern:/sentry\.io/i,name:"Sentry"},{pattern:/datadog\.com/i,name:"Datadog"},{pattern:/segment\.(com|io)/i,name:"Segment"},{pattern:/mixpanel\.com/i,name:"Mixpanel"},{pattern:/amplitude\.com/i,name:"Amplitude"},{pattern:/openai\.com/i,name:"OpenAI"},{pattern:/anthropic\.com/i,name:"Anthropic"},{pattern:/cohere\.(ai|com)/i,name:"Cohere"}];categorizeApi(e){if(e.startsWith("["))return "Dynamic URL";if(e.startsWith("/"))return e.startsWith("/api/")?"Internal API":e.includes("/graphql")?"GraphQL":"Internal Route";for(let{pattern:t,name:r}of p.SERVICE_PATTERNS)if(t.test(e))return r;try{let s=new URL(e).hostname.replace(/^(api\.|www\.)/,"").split(".");if(s.length>=2){let i=s[s.length-2];return i.charAt(0).toUpperCase()+i.slice(1)+" API"}}catch{}return "External API"}normalizeMethod(e){let t=e.toUpperCase();return ["GET","POST","PUT","DELETE","PATCH"].includes(t)?t:"unknown"}};
3
+ export{ue as A,fe as B,he as C,A as a,O as b,ee as c,te as d,ve as e,W as f,X as g,be as h,R as i,Q as j,ne as k,$ as l,q as m,H as n,d as o,Ae as p,v as q,M as r,V as s,U as t,P as u,re as v,Z as w,je as x,Ge as y,oe as z};
@@ -1,4 +1,4 @@
1
- import {b as b$2,a as a$2}from'./chunk-DSYVU23K.js';import {a as a$3}from'./chunk-VV3A3UE3.js';import {C,B,A as A$1,z,b as b$1}from'./chunk-5PWKCCT7.js';import {a,b}from'./chunk-QBSB6BIU.js';import {a as a$1}from'./chunk-JBPSEUZS.js';import {k}from'./chunk-H7VVRHQZ.js';import {simpleGit}from'simple-git';import*as A from'fs/promises';import*as R from'path';import {parseSync}from'@swc/core';import he from'express';import {Server}from'socket.io';import*as ye from'http';import {marked}from'marked';import*as ue from'net';var W=class{config;mermaidGenerator;markdownGenerator;constructor(o){this.config=o,this.mermaidGenerator=new a,this.markdownGenerator=new b;}async generate(){let o=[];for(let k of this.config.repositories)try{let x=await this.analyzeRepository(k);o.push(x);}catch(x){console.error(`\u274C ${k.name}: ${x.message}`);}let r=this.analyzeCrossRepo(o),e=o.map(k=>k.analysis),a=this.extractCrossRepoLinks(e),s=this.mermaidGenerator.generateAll(e,a),i={generatedAt:new Date().toISOString(),repositories:o,crossRepoAnalysis:r,diagrams:s};return await this.writeDocumentation(i),i}async analyzeRepository(o){let{version:r,commitHash:e}=await this.getRepoInfo(o),a=o.analyzers.map(b=>this.createAnalyzer(b,o)).filter(b=>b!==null),s=Date.now(),i=await Promise.all(a.map(b=>b.analyze())),k=((Date.now()-s)/1e3).toFixed(1);console.log(` Analyzed ${o.displayName} in ${k}s`);let x=this.mergeAnalysisResults(i,o.name,r,e);await this.enrichPagesWithHookGraphQL(x,o.path);let T={totalPages:x.pages.length,totalComponents:x.components.length,totalGraphQLOperations:x.graphqlOperations.length,totalDataFlows:x.dataFlows.length,authRequiredPages:x.pages.filter(b=>b.authentication.required).length,publicPages:x.pages.filter(b=>!b.authentication.required).length};return {name:o.name,displayName:o.displayName,version:r,commitHash:e,analysis:x,summary:T}}async getRepoInfo(o){try{let a=(await simpleGit(o.path).log({n:1})).latest?.hash||"unknown",s="unknown";try{let i=R.join(o.path,"package.json");s=JSON.parse(await A.readFile(i,"utf-8")).version||"unknown";}catch{}return {version:s,commitHash:a}}catch{return {version:"unknown",commitHash:"unknown"}}}createAnalyzer(o,r){switch(o){case "pages":if(r.type==="nextjs"||r.type==="rails"||r.type==="generic")return new z(r);break;case "graphql":return new A$1(r);case "dataflow":case "components":return new B(r);case "rest-api":case "api":return new C(r)}return null}mergeAnalysisResults(o,r,e,a){let s={repository:r,timestamp:new Date().toISOString(),version:e,commitHash:a,coverage:{tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0},pages:[],graphqlOperations:[],apiCalls:[],components:[],dataFlows:[],apiEndpoints:[],models:[],crossRepoLinks:[]};for(let i of o)i.coverage&&s.coverage&&(s.coverage.tsFilesScanned+=i.coverage.tsFilesScanned||0,s.coverage.tsParseFailures+=i.coverage.tsParseFailures||0,s.coverage.graphqlParseFailures+=i.coverage.graphqlParseFailures||0,s.coverage.codegenFilesDetected+=i.coverage.codegenFilesDetected||0,s.coverage.codegenFilesParsed+=i.coverage.codegenFilesParsed||0,s.coverage.codegenExportsFound+=i.coverage.codegenExportsFound||0),i.pages&&s.pages.push(...i.pages),i.graphqlOperations&&s.graphqlOperations.push(...i.graphqlOperations),i.apiCalls&&s.apiCalls.push(...i.apiCalls),i.components&&s.components.push(...i.components),i.dataFlows&&s.dataFlows.push(...i.dataFlows),i.apiEndpoints&&s.apiEndpoints.push(...i.apiEndpoints),i.models&&s.models.push(...i.models),i.crossRepoLinks&&s.crossRepoLinks.push(...i.crossRepoLinks);return s}analyzeCrossRepo(o){let r=[],e=[],a=[],s=[],i=new Map;for(let T of o)for(let b of T.analysis.graphqlOperations){let $=i.get(b.name)||[];$.push(T.name),i.set(b.name,$);}for(let[T,b]of i)b.length>1&&r.push(T);let k=o.filter(T=>T.analysis.pages.length>0),x=o.filter(T=>T.analysis.apiEndpoints.length>0);for(let T of k)for(let b of x)for(let $ of b.analysis.apiEndpoints)e.push({frontend:T.name,backend:b.name,endpoint:$.path,operations:T.analysis.graphqlOperations.filter(N=>N.usedIn.length>0).map(N=>N.name)});return {sharedTypes:r,apiConnections:e,navigationFlows:a,dataFlowAcrossRepos:s}}extractCrossRepoLinks(o){let r=[],e=new Map;for(let a of o)for(let s of a.graphqlOperations){let i=e.get(s.name)||[];i.push(a),e.set(s.name,i);}for(let[a,s]of e)s.length>1&&r.push({sourceRepo:s[0].repository,sourcePath:`graphql/${a}`,targetRepo:s[1].repository,targetPath:`graphql/${a}`,linkType:"graphql-operation",description:`Shared GraphQL operation: ${a}`});return r}async enrichPagesWithHookGraphQL(o,r){let e=o.graphqlOperations.filter(n=>n.type==="query"||n.type==="mutation"||n.type==="subscription"),a=/\.(ts|tsx|js|jsx)$/,s=n=>R.normalize(n).replace(/\\/g,"/"),i=(this.config.analysis?.include||["**/*.ts","**/*.tsx"]).map(String),k=(this.config.analysis?.exclude||[]).map(String),x=(await import('fast-glob')).default,T=await x(i,{cwd:r,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**","**/coverage/**",...k],onlyFiles:true,unique:true,dot:false}),b=new Set(T.map(s)),$=new Map;for(let n of b){let t=n.replace(a,"");$.has(t)||$.set(t,n);}let N=new b$1(r,b),Z=new Set(["src/"]);for(let n of b){let t=n.indexOf("/src/");t!==-1&&Z.add(n.slice(0,t+5));}let F=n=>{let t=s(n).replace(a,""),p=$.get(t);if(p)return p;let c=$.get(t+"/index");return c||null},ve=async()=>{let n=["tsconfig.json","jsconfig.json"];for(let t of n)try{let p=await A.readFile(R.join(r,t),"utf-8"),l=JSON.parse(p)?.compilerOptions||{},d=typeof l.baseUrl=="string"?l.baseUrl:void 0,q=typeof l.paths=="object"&&l.paths?l.paths:void 0;return {baseUrl:d,paths:q}}catch{}return {}},{baseUrl:D,paths:V}=await ve(),we=n=>{if(!V)return [];let t=[];for(let[p,c]of Object.entries(V)){if(!p.includes("*")){n===p&&t.push(...c);continue}let[l,d]=p.split("*");if(!n.startsWith(l)||!n.endsWith(d))continue;let q=n.slice(l.length,n.length-d.length);for(let w of c)w.includes("*")?t.push(w.replace("*",q)):t.push(w);}return t},I=(n,t)=>{if(!t)return null;let p=N.resolve(n,t);if(p)return p.file;if(t.startsWith(".")){let l=R.dirname(n);return F(R.join(l,t))}if(t.startsWith("@/")){let l=t.replace("@/","");if(D){let d=F(R.join(D,l));if(d)return d}for(let d of Z){let q=F(d+l);if(q)return q}return null}let c=we(t);if(c.length>0)for(let l of c){let d=F(D?R.join(D,l):l);if(d)return d}if(D){let l=F(R.join(D,t));if(l)return l}return null},j=new Map,_=new Map,Q=async n=>{let t=s(n),p=_.get(t);if(p!==void 0)return p;try{let c=R.join(r,t),l=await A.readFile(c,"utf-8");return _.set(t,l),l}catch{return _.set(t,""),null}},xe=async n=>{let t=s(n),p=j.get(t);if(p)return p.map(h=>({spec:h,names:null}));let c=await Q(t);if(!c)return j.set(t,[]),[];let l;try{let h=t.endsWith(".ts")||t.endsWith(".tsx"),g=t.endsWith(".tsx")||t.endsWith(".jsx");l=parseSync(c,{syntax:h?"typescript":"ecmascript",tsx:g,jsx:g,comments:!1});}catch{return j.set(t,[]),[]}let d=new Set,q=[],w=(h,g,m)=>{typeof h!="string"||h.length===0||(d.add(h),q.push({spec:h,names:g,pos:m}));},f=h=>{if(!h||typeof h!="object")return;let g=h,m=g;if(m.type==="ImportDeclaration"){if(!m.typeOnly){let v=m.source?.value,u=[],y=m.specifiers||[];for(let E of y){let M=E,B=M.type;if(B==="ImportDefaultSpecifier"||B==="ImportNamespaceSpecifier"){u=null;break}if(B==="ImportSpecifier"){let G=M.imported?.value,P=M.local?.value,z=G||P;z&&u.push(z);}}Array.isArray(u)&&u.length===0&&(u=null),w(v,u,m.span?.start);}}else if(m.type==="ExportAllDeclaration")w(m.source?.value,null,m.span?.start);else if(m.type==="ExportNamedDeclaration"){let v=m.source?.value,u=m.specifiers||[],y=[];for(let E of u){let M=E;if(M.type==="ExportSpecifier"){let G=M.exported?.value,P=M.orig?.value,z=G||P;z&&y.push(z);}}w(v,y.length>0?y:null,m.span?.start);}else if(m.type==="CallExpression"){let v=m.callee||null;if(v?.type==="Identifier"&&v.value==="require"){let u=m.arguments?.[0]?.expression;u?.type==="StringLiteral"&&w(u.value,null,m.span?.start);}if(v?.type==="Import"){let u=m.arguments?.[0]?.expression;u?.type==="StringLiteral"&&w(u.value,null,m.span?.start);}}for(let v of Object.keys(g)){let u=g[v];if(Array.isArray(u))for(let y of u)f(y);else u&&typeof u=="object"&&f(u);}};f(l);let C=Array.from(d);return j.set(t,C),q.filter(h=>typeof h.spec=="string"&&h.spec.length>0)},be=(n,t)=>{if(t===void 0||t<0)return;let p=1;for(let c=0;c<n.length&&c<t;c++)n.charCodeAt(c)===10&&p++;return p},ke=(n,t)=>{if(t<0)return;let p=1;for(let c=0;c<n.length&&c<t;c++)n.charCodeAt(c)===10&&p++;return p},H=new Map,Y=async n=>{let t=s(n),p=H.get(t);if(p)return p;let c=await Q(t);if(!c){let h={named:new Map,stars:[],isBarrel:false};return H.set(t,h),h}let l;try{let h=t.endsWith(".ts")||t.endsWith(".tsx"),g=t.endsWith(".tsx")||t.endsWith(".jsx");l=parseSync(c,{syntax:h?"typescript":"ecmascript",tsx:g,jsx:g,comments:!1});}catch{let h={named:new Map,stars:[],isBarrel:false};return H.set(t,h),h}let d=new Map,q=[],w=true,f=l?.body;if(Array.isArray(f))for(let h of f){let g=h,m=g.type;if(m&&m!=="ImportDeclaration"){if(m==="ExportAllDeclaration"){let v=g.source?.value;typeof v=="string"&&q.push(v);continue}if(m==="ExportNamedDeclaration"){let v=g.source?.value,u=g.specifiers||[];if(typeof v=="string"&&Array.isArray(u))for(let y of u){let E=y;if(E.type!=="ExportSpecifier")continue;let B=E.exported?.value,G=E.orig?.value,P=B||G;P&&d.set(P,v);}continue}w=false;}}else w=false;let C={named:d,stars:q,isBarrel:w};return H.set(t,C),C},ee=async(n,t,p)=>{let c=s(n);if(p.has(c))return null;p.add(c);let l=await Y(c),d=l.named.get(t);if(d)return I(c,d);for(let q of l.stars){let w=I(c,q);if(!w)continue;let f=await ee(w,t,p);if(f)return f}return null},X=new Map;for(let n of e){let t=new Set;n.filePath&&t.add(n.filePath);for(let p of n.usedIn||[])t.add(p);for(let p of t){let c=X.get(p)||[];c.push({opName:n.name,opType:n.type}),X.set(p,c);}}let Me=n=>{if(!n)return null;let t=[`src/pages/${n}`,`pages/${n}`,`src/app/${n}`,`app/${n}`,`frontend/src/pages/${n}`,`frontend/src/app/${n}`,`app/javascript/pages/${n}`,`app/javascript/app/${n}`];for(let l of t){if(b.has(l))return l;let d=F(l);if(d)return d}let p=[],c=[`/pages/${n}`,`/app/${n}`,`/${n}`];for(let l of b)for(let d of c)if(l.endsWith(d)&&!(d.startsWith("/pages/")&&!l.includes("/pages/"))&&!(d.startsWith("/app/")&&!l.includes("/app/"))){p.push(l);break}return p.length===0?null:(p.sort((l,d)=>l.length-d.length),p[0])},K=new Map,U=new Map;for(let n of o.pages){let t=Me(n.filePath);if(!t)continue;let p=new Map,c=new Set,l=[{f:t,depth:0}],d=new Map,q=30,w=2e4;for(;l.length>0;){let f=l.shift();if(!f)break;if(c.has(f.f))continue;if(c.add(f.f),c.size>=w)break;let C=X.get(f.f);if(C)for(let g of C){let m=p.get(g.opName);(!m||f.depth<m.distance)&&p.set(g.opName,{opName:g.opName,opType:g.opType,sourceFile:f.f,distance:f.depth});}if(f.depth>=q)continue;let h=await xe(f.f);for(let g of h){let m=I(f.f,g.spec);if(m){if(!c.has(m)&&(l.push({f:m,depth:f.depth+1}),!d.has(m))){let v=await Q(f.f),u=v?be(v,g.pos):void 0,y=Array.isArray(g.names)&&g.names.length>0?`names:${g.names.join(",")}`:void 0;d.set(m,{from:f.f,spec:g.spec,line:u,detail:y});}if(Array.isArray(g.names)&&g.names.length>0){if((await Y(m)).isBarrel)for(let u of g.names){let y=await ee(m,u,new Set);y&&!c.has(y)&&(l.push({f:y,depth:f.depth+2}),d.has(y)||d.set(y,{from:m,spec:`re-export:${u}`,line:void 0,detail:"barrel"}));}}else if(g.names===null){let v=await Y(m);if(v.isBarrel){for(let u of v.stars){let y=I(m,u);y&&!c.has(y)&&l.push({f:y,depth:f.depth+2});}for(let u of v.named.values()){let y=I(m,u);y&&!c.has(y)&&l.push({f:y,depth:f.depth+2});}}}}}}K.set(n.path,{page:n,entryFile:t,parent:d,bestByOp:p});for(let f of c)U.set(f,(U.get(f)||0)+1);}let Re=K.size,qe=Array.from(U.values()).sort((n,t)=>n-t),Te=((n,t)=>{if(n.length===0)return 0;let p=Math.min(n.length-1,Math.max(0,Math.floor(n.length*t)));return n[p]})(qe,.9),Se=Math.max(10,Te),$e=Math.max(2,Math.floor(Re*.05));for(let{page:n,entryFile:t,parent:p,bestByOp:c}of K.values()){let l=new Set((n.dataFetching||[]).map(d=>d.operationName?.replace(/^[→\->\s]+/,"")||""));for(let{opName:d,opType:q,sourceFile:w,distance:f}of c.values()){if(l.has(d))continue;l.add(d);let C=U.get(w)||0,h;f===0?h=void 0:C>=Se?h=`common:${w}`:f<=2||C<=$e?h=`close:${w}`:h=`indirect:${w}`;let g=f===0||f<=2?"certain":h?.startsWith("common:")?"unknown":"likely",m=[];if(f>0&&w!==t){let u=[],y=w,E=new Set;for(;y!==t&&!E.has(y);){E.add(y);let M=p.get(y);if(!M)break;u.push({from:M.from,to:y,spec:M.spec,line:M.line,detail:M.detail}),y=M.from;}u.reverse();for(let M of u)m.push({kind:"import-edge",file:M.from,line:M.line,detail:`${M.spec} -> ${M.to}${M.detail?` (${M.detail})`:""}`});}let v=await Q(w);if(v){let u=v.indexOf(`${d}Document`)>=0?v.indexOf(`${d}Document`):v.indexOf(d),y=u>=0?ke(v,u):void 0;m.push({kind:"operation-reference",file:w,line:y,detail:`ref:${d}`});}else m.push({kind:"operation-reference",file:w,detail:`ref:${d}`});n.dataFetching.push({type:q==="mutation"?"useMutation":q==="subscription"?"useSubscription":"useQuery",operationName:d,source:h,confidence:g,evidence:m.length>0?m:void 0});}}}async writeDocumentation(o){let r=this.config.outputDir;await A.mkdir(r,{recursive:true});let e=this.markdownGenerator.generateDocumentation(o);for(let[s,i]of e){let k=R.join(r,s),x=R.dirname(k);await A.mkdir(x,{recursive:true}),await A.writeFile(k,i,"utf-8");}let a=R.join(r,"report.json");await A.writeFile(a,JSON.stringify(o,null,2),"utf-8");}};function Ee(L){return new Promise(o=>{let r=ue.createServer();r.once("error",e=>{e.code,o(false);}),r.once("listening",()=>{r.close(),o(true);}),r.listen(L);})}async function fe(L,o=10){for(let r=0;r<o;r++){let e=L+r;if(await Ee(e))return e}throw new Error(`No available port found between ${L} and ${L+o-1}`)}var ge=class{config;port;app;server;io;engine;currentReport=null;envResult=null;railsAnalysis=null;constructor(o,r=3030){this.config=o,this.port=r,this.app=he(),this.server=ye.createServer(this.app),this.io=new Server(this.server),this.engine=new W(o),this.setupRoutes(),this.setupSocketIO();}setupRoutes(){this.app.use("/assets",he.static(R.join(this.config.outputDir,"assets"))),this.app.get("/icons.svg",async(e,a)=>{let s=[R.join(R.dirname(new URL(import.meta.url).pathname),"generators","assets","icons.svg"),R.join(R.dirname(new URL(import.meta.url).pathname),"..","generators","assets","icons.svg"),R.join(process.cwd(),"dist","generators","assets","icons.svg"),R.join(process.cwd(),"src","generators","assets","icons.svg")];for(let i of s)try{let k=await A.readFile(i);a.type("image/svg+xml").send(k);return}catch{}a.status(404).send("icons.svg not found");}),["common.css","page-map.css","docs.css","rails-map.css"].forEach(e=>{this.app.get(`/${e}`,async(a,s)=>{let i=[R.join(R.dirname(new URL(import.meta.url).pathname),"generators","assets",e),R.join(R.dirname(new URL(import.meta.url).pathname),"..","generators","assets",e),R.join(process.cwd(),"dist","generators","assets",e),R.join(process.cwd(),"src","generators","assets",e)];for(let k of i)try{let x=await A.readFile(k,"utf-8");s.type("text/css").send(x);return}catch{}s.status(404).send("CSS not found");});}),["favicon.ico","favicon.svg","favicon-96x96.png","apple-touch-icon.png","site.webmanifest","web-app-manifest-192x192.png","web-app-manifest-512x512.png"].forEach(e=>{(e==="favicon.ico"?[`/${e}`,`/favicon/${e}`]:[`/favicon/${e}`]).forEach(s=>{this.app.get(s,async(i,k)=>{let x=[R.join(R.dirname(new URL(import.meta.url).pathname),"generators","assets","favicon",e),R.join(R.dirname(new URL(import.meta.url).pathname),"..","generators","assets","favicon",e),R.join(process.cwd(),"dist","generators","assets","favicon",e),R.join(process.cwd(),"src","generators","assets","favicon",e)];for(let T of x)try{let b=await A.readFile(T),$=e.split(".").pop(),N={ico:"image/x-icon",svg:"image/svg+xml",png:"image/png",webmanifest:"application/manifest+json"};k.type(N[$||""]||"application/octet-stream").send(b);return}catch{}k.status(404).send("File not found");});});}),this.app.get("/",(e,a)=>{a.redirect("/page-map");}),this.app.get("/page-map",(e,a)=>{if(!this.currentReport){a.status(503).send("Documentation not ready yet");return}let s=new a$1;a.send(s.generatePageMapHtml(this.currentReport,{envResult:this.envResult,railsAnalysis:this.railsAnalysis}));}),this.app.get("/rails-map",(e,a)=>{if(!this.railsAnalysis){a.status(404).send("No Rails environment detected");return}let s=new b$2;a.send(s.generateFromResult(this.railsAnalysis));}),this.app.get("/docs",async(e,a)=>{a.send(await this.renderPage("index"));}),this.app.get("/docs/*path",async(e,a)=>{let s=e.params.path,i=Array.isArray(s)?s.join("/"):s||"index";a.send(await this.renderPage(i));}),this.app.get("/api/report",(e,a)=>{a.json(this.currentReport);}),this.app.get("/api/env",(e,a)=>{a.json(this.envResult);}),this.app.get("/api/rails",(e,a)=>{this.railsAnalysis?a.json(this.railsAnalysis):a.status(404).json({error:"No Rails analysis available"});}),this.app.get("/api/diagram/:name",(e,a)=>{let s=this.currentReport?.diagrams.find(i=>i.title.toLowerCase().replace(/\s+/g,"-")===e.params.name);s?a.json(s):a.status(404).json({error:"Diagram not found"});}),this.app.post("/api/regenerate",async(e,a)=>{try{await this.regenerate(),a.json({success:!0});}catch(s){a.status(500).json({error:s.message});}});}setupSocketIO(){this.io.on("connection",o=>{o.on("disconnect",()=>{});});}async renderPage(o){let r=o.replace(/\.md$/,""),e=R.join(this.config.outputDir,`${r}.md`),a="";try{let s=await A.readFile(e,"utf-8"),i=await marked.parse(s);i=i.replace(/<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g,'<div class="mermaid">$1</div>'),i=i.replace(/<table>/g,'<div class="table-wrapper"><table>'),i=i.replace(/<\/table>/g,"</table></div>"),a=i;}catch(s){let i=s;if(i.code==="ENOENT"){let k=this.currentReport?.repositories.map(x=>x.name)||[];a=`
1
+ import {b as b$2,a as a$2}from'./chunk-HDMI7PTT.js';import {a as a$3}from'./chunk-VV3A3UE3.js';import {C,B,A as A$1,z,b as b$1}from'./chunk-NFF4OUJ6.js';import {a,b}from'./chunk-QBSB6BIU.js';import {a as a$1}from'./chunk-JBPSEUZS.js';import {k}from'./chunk-I7GO54AS.js';import {simpleGit}from'simple-git';import*as A from'fs/promises';import*as R from'path';import {parseSync}from'@swc/core';import he from'express';import {Server}from'socket.io';import*as ye from'http';import {marked}from'marked';import*as ue from'net';var W=class{config;mermaidGenerator;markdownGenerator;constructor(o){this.config=o,this.mermaidGenerator=new a,this.markdownGenerator=new b;}async generate(){let o=[];for(let k of this.config.repositories)try{let x=await this.analyzeRepository(k);o.push(x);}catch(x){console.error(`\u274C ${k.name}: ${x.message}`);}let r=this.analyzeCrossRepo(o),e=o.map(k=>k.analysis),a=this.extractCrossRepoLinks(e),s=this.mermaidGenerator.generateAll(e,a),i={generatedAt:new Date().toISOString(),repositories:o,crossRepoAnalysis:r,diagrams:s};return await this.writeDocumentation(i),i}async analyzeRepository(o){let{version:r,commitHash:e}=await this.getRepoInfo(o),a=o.analyzers.map(b=>this.createAnalyzer(b,o)).filter(b=>b!==null),s=Date.now(),i=await Promise.all(a.map(b=>b.analyze())),k=((Date.now()-s)/1e3).toFixed(1);console.log(` Analyzed ${o.displayName} in ${k}s`);let x=this.mergeAnalysisResults(i,o.name,r,e);await this.enrichPagesWithHookGraphQL(x,o.path);let q={totalPages:x.pages.length,totalComponents:x.components.length,totalGraphQLOperations:x.graphqlOperations.length,totalDataFlows:x.dataFlows.length,authRequiredPages:x.pages.filter(b=>b.authentication.required).length,publicPages:x.pages.filter(b=>!b.authentication.required).length};return {name:o.name,displayName:o.displayName,version:r,commitHash:e,analysis:x,summary:q}}async getRepoInfo(o){try{let a=(await simpleGit(o.path).log({n:1})).latest?.hash||"unknown",s="unknown";try{let i=R.join(o.path,"package.json");s=JSON.parse(await A.readFile(i,"utf-8")).version||"unknown";}catch{}return {version:s,commitHash:a}}catch{return {version:"unknown",commitHash:"unknown"}}}createAnalyzer(o,r){switch(o){case "pages":if(r.type==="nextjs"||r.type==="rails"||r.type==="generic")return new z(r);break;case "graphql":return new A$1(r);case "dataflow":case "components":return new B(r);case "rest-api":case "api":return new C(r)}return null}mergeAnalysisResults(o,r,e,a){let s={repository:r,timestamp:new Date().toISOString(),version:e,commitHash:a,coverage:{tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0},pages:[],graphqlOperations:[],apiCalls:[],components:[],dataFlows:[],apiEndpoints:[],models:[],crossRepoLinks:[]};for(let i of o)i.coverage&&s.coverage&&(s.coverage.tsFilesScanned+=i.coverage.tsFilesScanned||0,s.coverage.tsParseFailures+=i.coverage.tsParseFailures||0,s.coverage.graphqlParseFailures+=i.coverage.graphqlParseFailures||0,s.coverage.codegenFilesDetected+=i.coverage.codegenFilesDetected||0,s.coverage.codegenFilesParsed+=i.coverage.codegenFilesParsed||0,s.coverage.codegenExportsFound+=i.coverage.codegenExportsFound||0),i.pages&&s.pages.push(...i.pages),i.graphqlOperations&&s.graphqlOperations.push(...i.graphqlOperations),i.apiCalls&&s.apiCalls.push(...i.apiCalls),i.components&&s.components.push(...i.components),i.dataFlows&&s.dataFlows.push(...i.dataFlows),i.apiEndpoints&&s.apiEndpoints.push(...i.apiEndpoints),i.models&&s.models.push(...i.models),i.crossRepoLinks&&s.crossRepoLinks.push(...i.crossRepoLinks);return s}analyzeCrossRepo(o){let r=[],e=[],a=[],s=[],i=new Map;for(let q of o)for(let b of q.analysis.graphqlOperations){let $=i.get(b.name)||[];$.push(q.name),i.set(b.name,$);}for(let[q,b]of i)b.length>1&&r.push(q);let k=o.filter(q=>q.analysis.pages.length>0),x=o.filter(q=>q.analysis.apiEndpoints.length>0);for(let q of k)for(let b of x)for(let $ of b.analysis.apiEndpoints)e.push({frontend:q.name,backend:b.name,endpoint:$.path,operations:q.analysis.graphqlOperations.filter(N=>N.usedIn.length>0).map(N=>N.name)});return {sharedTypes:r,apiConnections:e,navigationFlows:a,dataFlowAcrossRepos:s}}extractCrossRepoLinks(o){let r=[],e=new Map;for(let a of o)for(let s of a.graphqlOperations){let i=e.get(s.name)||[];i.push(a),e.set(s.name,i);}for(let[a,s]of e)s.length>1&&r.push({sourceRepo:s[0].repository,sourcePath:`graphql/${a}`,targetRepo:s[1].repository,targetPath:`graphql/${a}`,linkType:"graphql-operation",description:`Shared GraphQL operation: ${a}`});return r}async enrichPagesWithHookGraphQL(o,r){let e=o.graphqlOperations.filter(n=>n.type==="query"||n.type==="mutation"||n.type==="subscription"),a=/\.(ts|tsx|js|jsx)$/,s=n=>R.normalize(n).replace(/\\/g,"/"),i=(this.config.analysis?.include||["**/*.ts","**/*.tsx"]).map(String),k=(this.config.analysis?.exclude||[]).map(String),{glob:x}=await import('glob'),q=await x(i,{cwd:r,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**","**/coverage/**",...k],nodir:true,dot:false}),b=new Set(q.map(s)),$=new Map;for(let n of b){let t=n.replace(a,"");$.has(t)||$.set(t,n);}let N=new b$1(r,b),Z=new Set(["src/"]);for(let n of b){let t=n.indexOf("/src/");t!==-1&&Z.add(n.slice(0,t+5));}let F=n=>{let t=s(n).replace(a,""),p=$.get(t);if(p)return p;let c=$.get(t+"/index");return c||null},ve=async()=>{let n=["tsconfig.json","jsconfig.json"];for(let t of n)try{let p=await A.readFile(R.join(r,t),"utf-8"),l=JSON.parse(p)?.compilerOptions||{},d=typeof l.baseUrl=="string"?l.baseUrl:void 0,T=typeof l.paths=="object"&&l.paths?l.paths:void 0;return {baseUrl:d,paths:T}}catch{}return {}},{baseUrl:D,paths:V}=await ve(),we=n=>{if(!V)return [];let t=[];for(let[p,c]of Object.entries(V)){if(!p.includes("*")){n===p&&t.push(...c);continue}let[l,d]=p.split("*");if(!n.startsWith(l)||!n.endsWith(d))continue;let T=n.slice(l.length,n.length-d.length);for(let w of c)w.includes("*")?t.push(w.replace("*",T)):t.push(w);}return t},I=(n,t)=>{if(!t)return null;let p=N.resolve(n,t);if(p)return p.file;if(t.startsWith(".")){let l=R.dirname(n);return F(R.join(l,t))}if(t.startsWith("@/")){let l=t.replace("@/","");if(D){let d=F(R.join(D,l));if(d)return d}for(let d of Z){let T=F(d+l);if(T)return T}return null}let c=we(t);if(c.length>0)for(let l of c){let d=F(D?R.join(D,l):l);if(d)return d}if(D){let l=F(R.join(D,t));if(l)return l}return null},j=new Map,_=new Map,Q=async n=>{let t=s(n),p=_.get(t);if(p!==void 0)return p;try{let c=R.join(r,t),l=await A.readFile(c,"utf-8");return _.set(t,l),l}catch{return _.set(t,""),null}},xe=async n=>{let t=s(n),p=j.get(t);if(p)return p.map(h=>({spec:h,names:null}));let c=await Q(t);if(!c)return j.set(t,[]),[];let l;try{let h=t.endsWith(".ts")||t.endsWith(".tsx"),g=t.endsWith(".tsx")||t.endsWith(".jsx");l=parseSync(c,{syntax:h?"typescript":"ecmascript",tsx:g,jsx:g,comments:!1});}catch{return j.set(t,[]),[]}let d=new Set,T=[],w=(h,g,m)=>{typeof h!="string"||h.length===0||(d.add(h),T.push({spec:h,names:g,pos:m}));},f=h=>{if(!h||typeof h!="object")return;let g=h,m=g;if(m.type==="ImportDeclaration"){if(!m.typeOnly){let v=m.source?.value,u=[],y=m.specifiers||[];for(let E of y){let M=E,B=M.type;if(B==="ImportDefaultSpecifier"||B==="ImportNamespaceSpecifier"){u=null;break}if(B==="ImportSpecifier"){let G=M.imported?.value,P=M.local?.value,z=G||P;z&&u.push(z);}}Array.isArray(u)&&u.length===0&&(u=null),w(v,u,m.span?.start);}}else if(m.type==="ExportAllDeclaration")w(m.source?.value,null,m.span?.start);else if(m.type==="ExportNamedDeclaration"){let v=m.source?.value,u=m.specifiers||[],y=[];for(let E of u){let M=E;if(M.type==="ExportSpecifier"){let G=M.exported?.value,P=M.orig?.value,z=G||P;z&&y.push(z);}}w(v,y.length>0?y:null,m.span?.start);}else if(m.type==="CallExpression"){let v=m.callee||null;if(v?.type==="Identifier"&&v.value==="require"){let u=m.arguments?.[0]?.expression;u?.type==="StringLiteral"&&w(u.value,null,m.span?.start);}if(v?.type==="Import"){let u=m.arguments?.[0]?.expression;u?.type==="StringLiteral"&&w(u.value,null,m.span?.start);}}for(let v of Object.keys(g)){let u=g[v];if(Array.isArray(u))for(let y of u)f(y);else u&&typeof u=="object"&&f(u);}};f(l);let C=Array.from(d);return j.set(t,C),T.filter(h=>typeof h.spec=="string"&&h.spec.length>0)},be=(n,t)=>{if(t===void 0||t<0)return;let p=1;for(let c=0;c<n.length&&c<t;c++)n.charCodeAt(c)===10&&p++;return p},ke=(n,t)=>{if(t<0)return;let p=1;for(let c=0;c<n.length&&c<t;c++)n.charCodeAt(c)===10&&p++;return p},H=new Map,Y=async n=>{let t=s(n),p=H.get(t);if(p)return p;let c=await Q(t);if(!c){let h={named:new Map,stars:[],isBarrel:false};return H.set(t,h),h}let l;try{let h=t.endsWith(".ts")||t.endsWith(".tsx"),g=t.endsWith(".tsx")||t.endsWith(".jsx");l=parseSync(c,{syntax:h?"typescript":"ecmascript",tsx:g,jsx:g,comments:!1});}catch{let h={named:new Map,stars:[],isBarrel:false};return H.set(t,h),h}let d=new Map,T=[],w=true,f=l?.body;if(Array.isArray(f))for(let h of f){let g=h,m=g.type;if(m&&m!=="ImportDeclaration"){if(m==="ExportAllDeclaration"){let v=g.source?.value;typeof v=="string"&&T.push(v);continue}if(m==="ExportNamedDeclaration"){let v=g.source?.value,u=g.specifiers||[];if(typeof v=="string"&&Array.isArray(u))for(let y of u){let E=y;if(E.type!=="ExportSpecifier")continue;let B=E.exported?.value,G=E.orig?.value,P=B||G;P&&d.set(P,v);}continue}w=false;}}else w=false;let C={named:d,stars:T,isBarrel:w};return H.set(t,C),C},ee=async(n,t,p)=>{let c=s(n);if(p.has(c))return null;p.add(c);let l=await Y(c),d=l.named.get(t);if(d)return I(c,d);for(let T of l.stars){let w=I(c,T);if(!w)continue;let f=await ee(w,t,p);if(f)return f}return null},X=new Map;for(let n of e){let t=new Set;n.filePath&&t.add(n.filePath);for(let p of n.usedIn||[])t.add(p);for(let p of t){let c=X.get(p)||[];c.push({opName:n.name,opType:n.type}),X.set(p,c);}}let Me=n=>{if(!n)return null;let t=[`src/pages/${n}`,`pages/${n}`,`src/app/${n}`,`app/${n}`,`frontend/src/pages/${n}`,`frontend/src/app/${n}`,`app/javascript/pages/${n}`,`app/javascript/app/${n}`];for(let l of t){if(b.has(l))return l;let d=F(l);if(d)return d}let p=[],c=[`/pages/${n}`,`/app/${n}`,`/${n}`];for(let l of b)for(let d of c)if(l.endsWith(d)&&!(d.startsWith("/pages/")&&!l.includes("/pages/"))&&!(d.startsWith("/app/")&&!l.includes("/app/"))){p.push(l);break}return p.length===0?null:(p.sort((l,d)=>l.length-d.length),p[0])},K=new Map,U=new Map;for(let n of o.pages){let t=Me(n.filePath);if(!t)continue;let p=new Map,c=new Set,l=[{f:t,depth:0}],d=new Map,T=30,w=2e4;for(;l.length>0;){let f=l.shift();if(!f)break;if(c.has(f.f))continue;if(c.add(f.f),c.size>=w)break;let C=X.get(f.f);if(C)for(let g of C){let m=p.get(g.opName);(!m||f.depth<m.distance)&&p.set(g.opName,{opName:g.opName,opType:g.opType,sourceFile:f.f,distance:f.depth});}if(f.depth>=T)continue;let h=await xe(f.f);for(let g of h){let m=I(f.f,g.spec);if(m){if(!c.has(m)&&(l.push({f:m,depth:f.depth+1}),!d.has(m))){let v=await Q(f.f),u=v?be(v,g.pos):void 0,y=Array.isArray(g.names)&&g.names.length>0?`names:${g.names.join(",")}`:void 0;d.set(m,{from:f.f,spec:g.spec,line:u,detail:y});}if(Array.isArray(g.names)&&g.names.length>0){if((await Y(m)).isBarrel)for(let u of g.names){let y=await ee(m,u,new Set);y&&!c.has(y)&&(l.push({f:y,depth:f.depth+2}),d.has(y)||d.set(y,{from:m,spec:`re-export:${u}`,line:void 0,detail:"barrel"}));}}else if(g.names===null){let v=await Y(m);if(v.isBarrel){for(let u of v.stars){let y=I(m,u);y&&!c.has(y)&&l.push({f:y,depth:f.depth+2});}for(let u of v.named.values()){let y=I(m,u);y&&!c.has(y)&&l.push({f:y,depth:f.depth+2});}}}}}}K.set(n.path,{page:n,entryFile:t,parent:d,bestByOp:p});for(let f of c)U.set(f,(U.get(f)||0)+1);}let Re=K.size,Te=Array.from(U.values()).sort((n,t)=>n-t),qe=((n,t)=>{if(n.length===0)return 0;let p=Math.min(n.length-1,Math.max(0,Math.floor(n.length*t)));return n[p]})(Te,.9),Se=Math.max(10,qe),$e=Math.max(2,Math.floor(Re*.05));for(let{page:n,entryFile:t,parent:p,bestByOp:c}of K.values()){let l=new Set((n.dataFetching||[]).map(d=>d.operationName?.replace(/^[→\->\s]+/,"")||""));for(let{opName:d,opType:T,sourceFile:w,distance:f}of c.values()){if(l.has(d))continue;l.add(d);let C=U.get(w)||0,h;f===0?h=void 0:C>=Se?h=`common:${w}`:f<=2||C<=$e?h=`close:${w}`:h=`indirect:${w}`;let g=f===0||f<=2?"certain":h?.startsWith("common:")?"unknown":"likely",m=[];if(f>0&&w!==t){let u=[],y=w,E=new Set;for(;y!==t&&!E.has(y);){E.add(y);let M=p.get(y);if(!M)break;u.push({from:M.from,to:y,spec:M.spec,line:M.line,detail:M.detail}),y=M.from;}u.reverse();for(let M of u)m.push({kind:"import-edge",file:M.from,line:M.line,detail:`${M.spec} -> ${M.to}${M.detail?` (${M.detail})`:""}`});}let v=await Q(w);if(v){let u=v.indexOf(`${d}Document`)>=0?v.indexOf(`${d}Document`):v.indexOf(d),y=u>=0?ke(v,u):void 0;m.push({kind:"operation-reference",file:w,line:y,detail:`ref:${d}`});}else m.push({kind:"operation-reference",file:w,detail:`ref:${d}`});n.dataFetching.push({type:T==="mutation"?"useMutation":T==="subscription"?"useSubscription":"useQuery",operationName:d,source:h,confidence:g,evidence:m.length>0?m:void 0});}}}async writeDocumentation(o){let r=this.config.outputDir;await A.mkdir(r,{recursive:true});let e=this.markdownGenerator.generateDocumentation(o);for(let[s,i]of e){let k=R.join(r,s),x=R.dirname(k);await A.mkdir(x,{recursive:true}),await A.writeFile(k,i,"utf-8");}let a=R.join(r,"report.json");await A.writeFile(a,JSON.stringify(o,null,2),"utf-8");}};function Ee(L){return new Promise(o=>{let r=ue.createServer();r.once("error",e=>{e.code,o(false);}),r.once("listening",()=>{r.close(),o(true);}),r.listen(L);})}async function fe(L,o=10){for(let r=0;r<o;r++){let e=L+r;if(await Ee(e))return e}throw new Error(`No available port found between ${L} and ${L+o-1}`)}var ge=class{config;port;app;server;io;engine;currentReport=null;envResult=null;railsAnalysis=null;constructor(o,r=3030){this.config=o,this.port=r,this.app=he(),this.server=ye.createServer(this.app),this.io=new Server(this.server),this.engine=new W(o),this.setupRoutes(),this.setupSocketIO();}setupRoutes(){this.app.use("/assets",he.static(R.join(this.config.outputDir,"assets"))),this.app.get("/icons.svg",async(e,a)=>{let s=[R.join(R.dirname(new URL(import.meta.url).pathname),"generators","assets","icons.svg"),R.join(R.dirname(new URL(import.meta.url).pathname),"..","generators","assets","icons.svg"),R.join(process.cwd(),"dist","generators","assets","icons.svg"),R.join(process.cwd(),"src","generators","assets","icons.svg")];for(let i of s)try{let k=await A.readFile(i);a.type("image/svg+xml").send(k);return}catch{}a.status(404).send("icons.svg not found");}),["common.css","page-map.css","docs.css","rails-map.css"].forEach(e=>{this.app.get(`/${e}`,async(a,s)=>{let i=[R.join(R.dirname(new URL(import.meta.url).pathname),"generators","assets",e),R.join(R.dirname(new URL(import.meta.url).pathname),"..","generators","assets",e),R.join(process.cwd(),"dist","generators","assets",e),R.join(process.cwd(),"src","generators","assets",e)];for(let k of i)try{let x=await A.readFile(k,"utf-8");s.type("text/css").send(x);return}catch{}s.status(404).send("CSS not found");});}),["favicon.ico","favicon.svg","favicon-96x96.png","apple-touch-icon.png","site.webmanifest","web-app-manifest-192x192.png","web-app-manifest-512x512.png"].forEach(e=>{(e==="favicon.ico"?[`/${e}`,`/favicon/${e}`]:[`/favicon/${e}`]).forEach(s=>{this.app.get(s,async(i,k)=>{let x=[R.join(R.dirname(new URL(import.meta.url).pathname),"generators","assets","favicon",e),R.join(R.dirname(new URL(import.meta.url).pathname),"..","generators","assets","favicon",e),R.join(process.cwd(),"dist","generators","assets","favicon",e),R.join(process.cwd(),"src","generators","assets","favicon",e)];for(let q of x)try{let b=await A.readFile(q),$=e.split(".").pop(),N={ico:"image/x-icon",svg:"image/svg+xml",png:"image/png",webmanifest:"application/manifest+json"};k.type(N[$||""]||"application/octet-stream").send(b);return}catch{}k.status(404).send("File not found");});});}),this.app.get("/",(e,a)=>{a.redirect("/page-map");}),this.app.get("/page-map",(e,a)=>{if(!this.currentReport){a.status(503).send("Documentation not ready yet");return}let s=new a$1;a.send(s.generatePageMapHtml(this.currentReport,{envResult:this.envResult,railsAnalysis:this.railsAnalysis}));}),this.app.get("/rails-map",(e,a)=>{if(!this.railsAnalysis){a.status(404).send("No Rails environment detected");return}let s=new b$2;a.send(s.generateFromResult(this.railsAnalysis));}),this.app.get("/docs",async(e,a)=>{a.send(await this.renderPage("index"));}),this.app.get("/docs/*path",async(e,a)=>{let s=e.params.path,i=Array.isArray(s)?s.join("/"):s||"index";a.send(await this.renderPage(i));}),this.app.get("/api/report",(e,a)=>{a.json(this.currentReport);}),this.app.get("/api/env",(e,a)=>{a.json(this.envResult);}),this.app.get("/api/rails",(e,a)=>{this.railsAnalysis?a.json(this.railsAnalysis):a.status(404).json({error:"No Rails analysis available"});}),this.app.get("/api/diagram/:name",(e,a)=>{let s=this.currentReport?.diagrams.find(i=>i.title.toLowerCase().replace(/\s+/g,"-")===e.params.name);s?a.json(s):a.status(404).json({error:"Diagram not found"});}),this.app.post("/api/regenerate",async(e,a)=>{try{await this.regenerate(),a.json({success:!0});}catch(s){a.status(500).json({error:s.message});}});}setupSocketIO(){this.io.on("connection",o=>{o.on("disconnect",()=>{});});}async renderPage(o){let r=o.replace(/\.md$/,""),e=R.join(this.config.outputDir,`${r}.md`),a="";try{let s=await A.readFile(e,"utf-8"),i=await marked.parse(s);i=i.replace(/<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g,'<div class="mermaid">$1</div>'),i=i.replace(/<table>/g,'<div class="table-wrapper"><table>'),i=i.replace(/<\/table>/g,"</table></div>"),a=i;}catch(s){let i=s;if(i.code==="ENOENT"){let k=this.currentReport?.repositories.map(x=>x.name)||[];a=`
2
2
  <h1>Page not found</h1>
3
3
  <p>The requested path <code>${r}</code> does not exist.</p>
4
4
  ${k.length>0?`
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import {a,b}from'./chunk-CWAQJQVH.js';import'./chunk-DSYVU23K.js';import'./chunk-VV3A3UE3.js';import'./chunk-5PWKCCT7.js';import'./chunk-QBSB6BIU.js';import'./chunk-JBPSEUZS.js';import'./chunk-H7VVRHQZ.js';import {Command}from'commander';import s from'chalk';import*as c from'path';import*as v from'fs';import*as n from'fs/promises';import*as P from'os';function x(){let e=P.tmpdir();return c.join(e,`repomap-${Date.now()}`)}function S(e){let t=async()=>{try{await n.rm(e,{recursive:!0,force:!0});}catch{}process.exit(0);};process.on("SIGINT",t),process.on("SIGTERM",t);}function E(){try{let e=new URL("../package.json",import.meta.url),t=v.readFileSync(e,"utf-8");return JSON.parse(t).version||"0.0.0"}catch{return "0.0.0"}}var h=new Command;h.name("repomap").description("Interactive documentation generator for code repositories").version(E());async function C(e){let t=c.basename(e),a=false,o=c.join(e,"Gemfile"),p=c.join(e,"config","routes.rb");try{await n.access(o),await n.access(p);let d=await n.readFile(o,"utf-8");a=d.includes("gem 'rails'")||d.includes('gem "rails"');}catch{}let r=c.join(e,"package.json"),i=false,l=false,f={};try{let d=JSON.parse(await n.readFile(r,"utf-8")),w={...d.dependencies,...d.devDependencies};i=!!w.react,l=!!w.next;let m=["src/pages","pages","app","src/app","frontend/src"];for(let u of m)try{await n.access(c.join(e,u)),f.pagesDir=u;break}catch{}let b=["src/features","features","src/modules","modules","frontend/src"];for(let u of b)try{await n.access(c.join(e,u)),f.featuresDir=u;break}catch{}let D=["src/components","components","src/common/components","frontend/src"];for(let u of D)try{await n.access(c.join(e,u)),f.componentsDir=u;break}catch{}}catch{}let g=[];(i||l)&&g.push("pages","graphql","dataflow","rest-api");let y="generic";return l?y="nextjs":a&&(y="rails"),!a&&!i&&!l?null:{name:t,displayName:t,description:a&&i?"Rails + React application":a?"Rails application":"",path:e,branch:"main",type:y,analyzers:g,settings:f}}async function N(e){let t=await C(e);if(!t)throw new Error("Could not detect project. Please create a repomap.config.ts file or run 'repomap init'.");return {outputDir:"./.repomap",site:{title:`${t.displayName} Documentation`,description:"Auto-generated documentation",baseUrl:"/docs"},repositories:[t],analysis:{include:["**/*.tsx","**/*.ts"],exclude:["**/node_modules/**","**/__tests__/**","**/*.test.*","**/*.spec.*","**/dist/**","**/.next/**"],maxDepth:5},diagrams:{enabled:true,types:["flowchart","sequence"],theme:"default"},watch:{enabled:false,debounce:1e3},integrations:{github:{enabled:false,organization:""},slack:{enabled:false}}}}async function $(e,t){let a=e?[e]:["repomap.config.ts","repomap.config.js","repomap.config.mjs"];for(let o of a){let p=c.resolve(t,o);try{await n.access(p);let r=await import(p);return r.config||r.default}catch{}}return N(t)}h.command("generate").description("Generate documentation from source code").option("-c, --config <path>","Path to config file").option("-o, --output <path>","Output directory").option("--temp","Use temporary directory (no files in repository)").option("--repo <name>","Analyze specific repository only").option("--watch","Watch for changes and regenerate").option("--format <type>","Output format: json, html, markdown (default: all)","all").option("--ci","CI mode: minimal output, exit codes for errors").option("--static","Generate standalone HTML files (for GitHub Pages)").action(async e=>{let t=e.ci||process.env.CI==="true";t||console.log(s.blue.bold(`
2
+ import {a,b}from'./chunk-SMFBFVZH.js';import'./chunk-HDMI7PTT.js';import'./chunk-VV3A3UE3.js';import'./chunk-NFF4OUJ6.js';import'./chunk-QBSB6BIU.js';import'./chunk-JBPSEUZS.js';import'./chunk-I7GO54AS.js';import {Command}from'commander';import s from'chalk';import*as c from'path';import*as v from'fs';import*as n from'fs/promises';import*as P from'os';function x(){let e=P.tmpdir();return c.join(e,`repomap-${Date.now()}`)}function S(e){let t=async()=>{try{await n.rm(e,{recursive:!0,force:!0});}catch{}process.exit(0);};process.on("SIGINT",t),process.on("SIGTERM",t);}function E(){try{let e=new URL("../package.json",import.meta.url),t=v.readFileSync(e,"utf-8");return JSON.parse(t).version||"0.0.0"}catch{return "0.0.0"}}var h=new Command;h.name("repomap").description("Interactive documentation generator for code repositories").version(E());async function C(e){let t=c.basename(e),a=false,o=c.join(e,"Gemfile"),p=c.join(e,"config","routes.rb");try{await n.access(o),await n.access(p);let d=await n.readFile(o,"utf-8");a=d.includes("gem 'rails'")||d.includes('gem "rails"');}catch{}let r=c.join(e,"package.json"),i=false,l=false,f={};try{let d=JSON.parse(await n.readFile(r,"utf-8")),w={...d.dependencies,...d.devDependencies};i=!!w.react,l=!!w.next;let m=["src/pages","pages","app","src/app","frontend/src"];for(let u of m)try{await n.access(c.join(e,u)),f.pagesDir=u;break}catch{}let b=["src/features","features","src/modules","modules","frontend/src"];for(let u of b)try{await n.access(c.join(e,u)),f.featuresDir=u;break}catch{}let D=["src/components","components","src/common/components","frontend/src"];for(let u of D)try{await n.access(c.join(e,u)),f.componentsDir=u;break}catch{}}catch{}let g=[];(i||l)&&g.push("pages","graphql","dataflow","rest-api");let y="generic";return l?y="nextjs":a&&(y="rails"),!a&&!i&&!l?null:{name:t,displayName:t,description:a&&i?"Rails + React application":a?"Rails application":"",path:e,branch:"main",type:y,analyzers:g,settings:f}}async function N(e){let t=await C(e);if(!t)throw new Error("Could not detect project. Please create a repomap.config.ts file or run 'repomap init'.");return {outputDir:"./.repomap",site:{title:`${t.displayName} Documentation`,description:"Auto-generated documentation",baseUrl:"/docs"},repositories:[t],analysis:{include:["**/*.tsx","**/*.ts"],exclude:["**/node_modules/**","**/__tests__/**","**/*.test.*","**/*.spec.*","**/dist/**","**/.next/**"],maxDepth:5},diagrams:{enabled:true,types:["flowchart","sequence"],theme:"default"},watch:{enabled:false,debounce:1e3},integrations:{github:{enabled:false,organization:""},slack:{enabled:false}}}}async function $(e,t){let a=e?[e]:["repomap.config.ts","repomap.config.js","repomap.config.mjs"];for(let o of a){let p=c.resolve(t,o);try{await n.access(p);let r=await import(p);return r.config||r.default}catch{}}return N(t)}h.command("generate").description("Generate documentation from source code").option("-c, --config <path>","Path to config file").option("-o, --output <path>","Output directory").option("--temp","Use temporary directory (no files in repository)").option("--repo <name>","Analyze specific repository only").option("--watch","Watch for changes and regenerate").option("--format <type>","Output format: json, html, markdown (default: all)","all").option("--ci","CI mode: minimal output, exit codes for errors").option("--static","Generate standalone HTML files (for GitHub Pages)").action(async e=>{let t=e.ci||process.env.CI==="true";t||console.log(s.blue.bold(`
3
3
  \u{1F4DA} Repomap
4
4
  `));try{let a$1=process.cwd(),o=await $(e.config,a$1);e.temp&&(o.outputDir=x(),t||console.log(s.cyan(`\u{1F4C1} Using temp directory: ${o.outputDir}
5
5
  `))),e.output&&(o.outputDir=e.output),e.repo&&(o.repositories=o.repositories.filter(r=>r.name===e.repo),o.repositories.length===0&&(console.error(s.red(`Repository "${e.repo}" not found in config`)),process.exit(1)));let p=new a(o);if(e.watch)console.log(s.yellow(`\u{1F440} Watch mode enabled. Press Ctrl+C to stop.
6
- `)),await k(p,o);else {let r=await p.generate();if(e.format==="json"||e.static){let i=c.join(o.outputDir,"report.json");await n.mkdir(o.outputDir,{recursive:!0}),await n.writeFile(i,JSON.stringify(r,null,2)),t||console.log(s.gray(` \u2192 ${i}`));}if(e.static&&await F(o,r,t),!t)O(r);else {let i=r.repositories.reduce((l,f)=>l+f.summary.totalPages,0);console.log(`\u2705 Generated: ${i} pages, ${r.repositories.length} repos`);}}}catch(a){console.error(t?`Error: ${a.message}`:s.red("Error:"),a.message),process.exit(1);}});async function F(e,t,a){let{PageMapGenerator:o}=await import('./page-map-generator-SL3H6CKF.js'),{detectEnvironments:p}=await import('./env-detector-BIWJ7OYF.js'),r=e.outputDir;await n.mkdir(r,{recursive:true});let i=e.repositories[0]?.path||process.cwd(),l=await p(i),f=null;if(l.hasRails){let{analyzeRailsApp:m}=await import('./rails-3HNUFTQV.js');f=await m(i);}let y=new o().generatePageMapHtml(t,{envResult:l,railsAnalysis:f,staticMode:true});if(await n.writeFile(c.join(r,"index.html"),y),a||console.log(s.gray(` \u2192 ${c.join(r,"index.html")}`)),f){let{RailsMapGenerator:m}=await import('./rails-map-generator-GV4ZIVJJ.js'),D=new m().generateFromResult(f);await n.writeFile(c.join(r,"rails-map.html"),D),a||console.log(s.gray(` \u2192 ${c.join(r,"rails-map.html")}`));}let d=["common.css","page-map.css","docs.css","rails-map.css"],w=c.join(r,"assets");await n.mkdir(w,{recursive:true});for(let m of d)try{let b=new URL(`./generators/assets/${m}`,import.meta.url),D=await n.readFile(b,"utf-8");await n.writeFile(c.join(w,m),D);}catch{}a||console.log(s.green(`
6
+ `)),await k(p,o);else {let r=await p.generate();if(e.format==="json"||e.static){let i=c.join(o.outputDir,"report.json");await n.mkdir(o.outputDir,{recursive:!0}),await n.writeFile(i,JSON.stringify(r,null,2)),t||console.log(s.gray(` \u2192 ${i}`));}if(e.static&&await F(o,r,t),!t)O(r);else {let i=r.repositories.reduce((l,f)=>l+f.summary.totalPages,0);console.log(`\u2705 Generated: ${i} pages, ${r.repositories.length} repos`);}}}catch(a){console.error(t?`Error: ${a.message}`:s.red("Error:"),a.message),process.exit(1);}});async function F(e,t,a){let{PageMapGenerator:o}=await import('./page-map-generator-SL3H6CKF.js'),{detectEnvironments:p}=await import('./env-detector-BIWJ7OYF.js'),r=e.outputDir;await n.mkdir(r,{recursive:true});let i=e.repositories[0]?.path||process.cwd(),l=await p(i),f=null;if(l.hasRails){let{analyzeRailsApp:m}=await import('./rails-5ZSMAFU5.js');f=await m(i);}let y=new o().generatePageMapHtml(t,{envResult:l,railsAnalysis:f,staticMode:true});if(await n.writeFile(c.join(r,"index.html"),y),a||console.log(s.gray(` \u2192 ${c.join(r,"index.html")}`)),f){let{RailsMapGenerator:m}=await import('./rails-map-generator-LQ4D7EKB.js'),D=new m().generateFromResult(f);await n.writeFile(c.join(r,"rails-map.html"),D),a||console.log(s.gray(` \u2192 ${c.join(r,"rails-map.html")}`));}let d=["common.css","page-map.css","docs.css","rails-map.css"],w=c.join(r,"assets");await n.mkdir(w,{recursive:true});for(let m of d)try{let b=new URL(`./generators/assets/${m}`,import.meta.url),D=await n.readFile(b,"utf-8");await n.writeFile(c.join(w,m),D);}catch{}a||console.log(s.green(`
7
7
  \u2705 Static site generated: ${r}`));}h.command("serve").description("Start local documentation server with live reload").option("-c, --config <path>","Path to config file").option("--path <path>","Path to repository to analyze (auto-detect if no config)").option("-o, --output <path>","Output directory (default: .repomap in target path)").option("-p, --port <number>","Server port","3030").option("--temp","Use temporary directory (no files in repository)").option("--no-open","Don't open browser automatically").action(async e=>{console.log(s.blue.bold(`
8
8
  \u{1F310} Repomap
9
9
  `));try{let t=e.path||process.cwd(),a=await $(e.config,t);e.temp&&(a.outputDir=x(),console.log(s.cyan(`\u{1F4C1} Using temp directory: ${a.outputDir}
@@ -56,7 +56,7 @@ export default config;
56
56
  `;await n.writeFile(t,g,"utf-8"),console.log(s.green(`\u2705 Created ${t}`)),console.log(s.gray(`
57
57
  Run 'npx repomap serve' to start the documentation server.`));}catch(a){console.error(s.red("Failed to create config:"),a.message);}});h.command("rails").description("Analyze a Rails application and generate interactive map").option("--path <path>","Path to Rails application").option("-o, --output <path>","Output HTML file path").action(async e=>{console.log(s.blue.bold(`
58
58
  \u{1F6E4}\uFE0F Repomap Rails
59
- `));try{let t=e.path||process.cwd();try{await n.access(c.join(t,"config","routes.rb"));}catch{console.error(s.red("Not a Rails project (config/routes.rb not found)")),process.exit(1);}let{RailsMapGenerator:a}=await import('./rails-map-generator-GV4ZIVJJ.js'),o=e.output||c.join(t,"rails-map.html");await new a(t).generate({title:`${c.basename(t)} - Rails Map`,outputPath:o}),console.log(s.green(`\u2705 Rails map generated: ${o}`));let{exec:r}=await import('child_process');r(`open "${o}"`);}catch(t){console.error(s.red("Error:"),t.message),process.exit(1);}});h.command("diff").description("Show documentation changes since last generation").option("-c, --config <path>","Path to config file").action(async e=>{console.log(s.blue.bold(`
59
+ `));try{let t=e.path||process.cwd();try{await n.access(c.join(t,"config","routes.rb"));}catch{console.error(s.red("Not a Rails project (config/routes.rb not found)")),process.exit(1);}let{RailsMapGenerator:a}=await import('./rails-map-generator-LQ4D7EKB.js'),o=e.output||c.join(t,"rails-map.html");await new a(t).generate({title:`${c.basename(t)} - Rails Map`,outputPath:o}),console.log(s.green(`\u2705 Rails map generated: ${o}`));let{exec:r}=await import('child_process');r(`open "${o}"`);}catch(t){console.error(s.red("Error:"),t.message),process.exit(1);}});h.command("diff").description("Show documentation changes since last generation").option("-c, --config <path>","Path to config file").action(async e=>{console.log(s.blue.bold(`
60
60
  \u{1F4CA} Documentation Diff
61
61
  `));try{let t=process.cwd(),a$1=await $(e.config,t),o=c.join(a$1.outputDir,"report.json");if(!await n.access(o).then(()=>!0).catch(()=>!1)){console.log(s.yellow("No previous report found. Run 'generate' first."));return}let r=JSON.parse(await n.readFile(o,"utf-8")),l=await new a(a$1).generate();T(r,l);}catch(t){console.error(s.red("Failed to generate diff:"),t.message);}});async function k(e,t){await e.generate();let a=t.repositories.map(o=>o.path);for(let o of a){let p=n.watch(o,{recursive:true}),r=null;for await(let i of p)i.filename&&(i.filename.endsWith(".ts")||i.filename.endsWith(".tsx"))&&(r&&clearTimeout(r),r=setTimeout(async()=>{console.log(s.yellow(`
62
62
  \u{1F504} Change detected: ${i.filename}`)),await e.generate();},t.watch.debounce));}}function O(e){console.log(s.green.bold(`
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import'./chunk-6F4PWJZI.js';export{a as DocGeneratorEngine,b as DocServer}from'./chunk-CWAQJQVH.js';import'./chunk-DSYVU23K.js';import'./chunk-VV3A3UE3.js';export{a as BaseAnalyzer,B as DataFlowAnalyzer,A as GraphQLAnalyzer,z as PagesAnalyzer}from'./chunk-5PWKCCT7.js';export{b as MarkdownGenerator,a as MermaidGenerator}from'./chunk-QBSB6BIU.js';export{a as PageMapGenerator}from'./chunk-JBPSEUZS.js';import'./chunk-H7VVRHQZ.js';
1
+ import'./chunk-6F4PWJZI.js';export{a as DocGeneratorEngine,b as DocServer}from'./chunk-SMFBFVZH.js';import'./chunk-HDMI7PTT.js';import'./chunk-VV3A3UE3.js';export{a as BaseAnalyzer,B as DataFlowAnalyzer,A as GraphQLAnalyzer,z as PagesAnalyzer}from'./chunk-NFF4OUJ6.js';export{b as MarkdownGenerator,a as MermaidGenerator}from'./chunk-QBSB6BIU.js';export{a as PageMapGenerator}from'./chunk-JBPSEUZS.js';import'./chunk-I7GO54AS.js';
@@ -1 +1 @@
1
- export{f as RailsControllerAnalyzer,h as RailsGrpcAnalyzer,g as RailsModelAnalyzer,e as RailsRoutesAnalyzer,k as analyzeRailsApp,i as analyzeRailsViews,j as analyzeReactComponents,d as findNodes,a as initRubyParser,b as parseRuby,c as parseRubyFile}from'./chunk-H7VVRHQZ.js';
1
+ export{f as RailsControllerAnalyzer,h as RailsGrpcAnalyzer,g as RailsModelAnalyzer,e as RailsRoutesAnalyzer,k as analyzeRailsApp,i as analyzeRailsViews,j as analyzeReactComponents,d as findNodes,a as initRubyParser,b as parseRuby,c as parseRubyFile}from'./chunk-I7GO54AS.js';
@@ -0,0 +1 @@
1
+ export{b as RailsMapGenerator}from'./chunk-HDMI7PTT.js';import'./chunk-I7GO54AS.js';
@@ -1 +1 @@
1
- export{b as DocServer}from'../chunk-CWAQJQVH.js';import'../chunk-DSYVU23K.js';import'../chunk-VV3A3UE3.js';import'../chunk-5PWKCCT7.js';import'../chunk-QBSB6BIU.js';import'../chunk-JBPSEUZS.js';import'../chunk-H7VVRHQZ.js';
1
+ export{b as DocServer}from'../chunk-SMFBFVZH.js';import'../chunk-HDMI7PTT.js';import'../chunk-VV3A3UE3.js';import'../chunk-NFF4OUJ6.js';import'../chunk-QBSB6BIU.js';import'../chunk-JBPSEUZS.js';import'../chunk-I7GO54AS.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtdlee/repomap",
3
- "version": "0.11.2",
3
+ "version": "0.11.3",
4
4
  "description": "Interactive documentation generator for code repositories - visualize pages, components, GraphQL operations, and data flows",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -87,7 +87,6 @@
87
87
  "chalk": "^5.3.0",
88
88
  "commander": "^14.0.2",
89
89
  "express": "^5.2.1",
90
- "fast-glob": "^3.3.2",
91
90
  "glob": "^13.0.0",
92
91
  "graphql": "^16.8.1",
93
92
  "marked": "^17.0.1",
@@ -95,8 +94,8 @@
95
94
  "simple-git": "^3.21.0",
96
95
  "socket.io": "^4.7.2",
97
96
  "typescript": "^5.3.2",
98
- "tree-sitter-wasms": "^0.1.13",
99
- "web-tree-sitter": "^0.25.10",
97
+ "tree-sitter-ruby": "^0.23.1",
98
+ "web-tree-sitter": "^0.26.3",
100
99
  "yaml": "^2.3.4"
101
100
  },
102
101
  "devDependencies": {
@@ -1,3 +0,0 @@
1
- import {parseSync}from'@swc/core';import j from'fast-glob';import*as y from'path';import*as F from'fs';import*as T from'fs/promises';import h from'typescript';import {parse,getLocation}from'graphql';var A=class{config;basePath;constructor(e){this.config=e,this.basePath=e.path;}resolvePath(e){return `${this.basePath}/${e}`}getSetting(e,t=""){return this.config.settings[e]??t}getListSetting(e,t=[]){let r=this.getSetting(e,"");return r?r.split(/[,\n]/g).map(s=>s.trim()).filter(Boolean):t}getGraphQLHookPatterns(){let e=(this.getSetting("graphqlHookPreset","auto")||"auto").trim().toLowerCase(),t=this.getListSetting("graphqlHookPatterns",[]),r=["useLazyLoadQuery","usePreloadedQuery","useQueryLoader","useMutation","useSubscription","useFragment","usePaginationFragment","useRefetchableFragment","useRelayEnvironment"],s=["useUrql*"],i=["useGql*","useGraphQL*","useGraphql*","useApiQuery*","useApiMutation*"],n=[];return e==="none"||e==="off"||e==="false"?n=[]:e==="apollo"?n=[]:e==="urql"?n=s:e==="relay"?n=r:n=[...r,...s,...i],Array.from(new Set([...n,...t]))}log(e){process.env.REPOMAP_VERBOSE==="1"&&console.log(`[${this.getName()}] ${e}`);}warn(e){console.warn(`\u26A0\uFE0F ${e}`);}error(e,t){console.error(`\u274C ${e}`,t?.message||"");}};var ee=["useQuery","useLazyQuery","useSuspenseQuery","useBackgroundQuery","useReadQuery"],te=["useMutation"],ve=["useSubscription","useFragment","useApolloClient"],W=[...ee,...te,...ve],X={useQuery:"useQuery",useSuspenseQuery:"useQuery",useBackgroundQuery:"useQuery",useReadQuery:"useQuery",useLazyQuery:"useLazyQuery",useMutation:"useMutation",useSubscription:"useSubscription"},be=["Document","useQuery","useMutation","useLazyQuery","useSuspenseQuery","useBackgroundQuery","useSubscription","Query","Mutation","gql","graphql","GET_","FETCH_","SEARCH_","CREATE_","UPDATE_","DELETE_","SUBSCRIBE_","@apollo","ApolloClient","@urql","urql","react-relay","Relay"];function Ce(p,e){if(!e)return false;if(e===p)return true;if(!e.includes("*"))return false;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`).test(p)}function E(p,e){for(let t of e)if(Ce(p,t))return true;return false}function R(p,e=[]){return E(p,e)?/Query$/.test(p)||!/(Mutation|Subscription)$/.test(p):ee.includes(p)||/^use[A-Z].*Query$/.test(p)}function Q(p,e=[]){return E(p,e)?/Mutation$/.test(p)||p.toLowerCase().includes("mutation"):te.includes(p)||/^use[A-Z].*Mutation$/.test(p)}function ne(p,e=[]){return E(p,e)?/Subscription$/.test(p)||p.toLowerCase().includes("subscription"):p==="useSubscription"}function $(p,e=[]){return E(p,e)?true:W.includes(p)||R(p,e)||Q(p,e)}function q(p,e=[]){return X[p]?X[p]:p.includes("Mutation")||E(p,e)?"useMutation":p.includes("Lazy")?"useLazyQuery":p.includes("Subscription")?"useSubscription":"useQuery"}function H(p){return be.some(e=>p.includes(e))}function d(p){return p.replace(/^(GET_|FETCH_|CREATE_|UPDATE_|DELETE_)/,"").replace(/_QUERY$|_MUTATION$/,"").replace(/Document$/,"").replace(/Query$|Mutation$|Variables$|Subscription$/,"")}function Ae(p){try{return parseSync(p,{syntax:"typescript",tsx:!0,comments:!1})}catch{return null}}function v(p){return p?p.type==="Identifier"?p.value:p.type==="MemberExpression"&&p.property?.type==="Identifier"?p.property.value:null:null}function M(p,e){if(!(!p||typeof p!="object")){e(p);for(let t of Object.keys(p)){let r=p[t];if(Array.isArray(r))for(let s of r)M(s,e);else r&&typeof r=="object"&&M(r,e);}}}function V(p,e,t){let r={documentImports:new Map,variableOperations:new Map,staticPropertyOperations:new Map,codegenMap:t||new Map};return M(p,s=>{s.type==="ImportDeclaration"&&we(s,r.documentImports),s.type==="VariableDeclarator"&&Fe(s,e,r.variableOperations),s.type==="AssignmentExpression"&&Ne(s,e,r.staticPropertyOperations);}),r}function we(p,e){let t=p.source?.value||"",r=t.includes("__generated__")||t.includes("generated")||t.includes("graphql")||t.includes(".generated")||t.endsWith(".graphql");for(let s of p.specifiers||[]){let i;(s.type==="ImportSpecifier"||s.type==="ImportDefaultSpecifier")&&(i=s.local?.value),i&&((i.endsWith("Document")||r)&&e.set(i,i.replace(/Document$/,"")),(i.endsWith("Query")||i.endsWith("Mutation"))&&e.set(i,i.replace(/Query$|Mutation$/,"")));}}function Fe(p,e,t){if(p.id?.type!=="Identifier")return;let r=p.id.value,s=p.init;if(!s)return;let i=null;if(s.type==="CallExpression"){let n=v(s.callee);(n==="gql"||n==="graphql")&&(i=U(s,e));}if(s.type==="TaggedTemplateExpression"){let n=v(s.tag);(n==="gql"||n==="graphql")&&(i=P(s.template));}if(s.type==="Identifier"){let n=s.value;if(n.endsWith("Document")||n.endsWith("Query")||n.endsWith("Mutation")){t.set(r,n);return}}i&&t.set(r,i);}function Ne(p,e,t){if(p.left?.type!=="MemberExpression")return;let r=p.left.object,s=p.left.property;if(r?.type!=="Identifier"||s?.type!=="Identifier")return;let i=`${r.value}.${s.value}`,n=p.right;if(!n)return;let a=null;if(n.type==="CallExpression"){let o=v(n.callee);(o==="gql"||o==="graphql")&&(a=U(n,e));}if(n.type==="TaggedTemplateExpression"){let o=v(n.tag);(o==="gql"||o==="graphql")&&(a=P(n.template));}a&&t.set(i,a);}function U(p,e){if(!p.arguments?.length)return null;let t=p.arguments[0],r=t?.expression||t;if(r?.type==="TemplateLiteral")return P(r);if(p.span){let i=e.slice(p.span.start,p.span.end).match(/(?:query|mutation|subscription)\s+(\w+)/i);if(i)return i[1]}return null}function P(p,e){if(!p?.quasis?.[0])return null;let r=(p.quasis[0].raw||p.quasis[0].cooked||"").match(/(?:query|mutation|subscription)\s+(\w+)/i);return r?r[1]:null}function re(p,e,t){if(!p.arguments?.length)return false;let r=p.arguments[0],s=r?.expression||r;if(!s)return false;if(p.typeArguments?.params?.length>0){let n=p.typeArguments.params[0];if(n?.type==="TsTypeReference"&&n.typeName?.type==="Identifier"){let a=n.typeName.value;if(/Query$|Mutation$|Subscription$|Document$/.test(a))return true}}if(s.type==="Identifier"){let n=s.value;if(t.documentImports.has(n)||t.variableOperations.has(n)||n.endsWith("Document")||/^[A-Z][a-zA-Z0-9]*Query$/.test(n)||/^[A-Z][a-zA-Z0-9]*Mutation$/.test(n)||/^[A-Z][A-Z0-9_]*_QUERY$/.test(n)||/^[A-Z][A-Z0-9_]*_MUTATION$/.test(n))return true}if(s.type==="TaggedTemplateExpression"){let n=v(s.tag);if(n==="gql"||n==="graphql")return true}if(s.type==="CallExpression"){let n=v(s.callee);if(n==="gql"||n==="graphql")return true}if(s.type==="TemplateLiteral"&&s.quasis?.[0]?.raw){let n=s.quasis[0].raw;if(/(?:query|mutation|subscription)\s+\w+/i.test(n))return true}if(s.type==="MemberExpression"){let n=s.property?.value;if(n&&/Query$|Mutation$|Document$/.test(n))return true;let a=s.object?.type==="Identifier"?s.object.value:null;if(a&&n){let o=`${a}.${n}`;if(t.staticPropertyOperations.has(o))return true}}if(s.type==="ObjectExpression")for(let n of s.properties||[]){if(n.type!=="KeyValueProperty")continue;let a=n.key?.type==="Identifier"||n.key?.type==="StringLiteral"?n.key.value:null;if(!a||!["query","mutation","document","subscription"].includes(a))continue;let o=n.value;if(o&&K(o,e,t))return true}let i=p.span;if(i){let n=e.slice(i.start,Math.min(i.end,i.start+500));if(/\bDocument\b/.test(n)||/\bgql\s*[`(]/.test(n)||/\bgraphql\s*[`(]/.test(n)||/query\s+[A-Z]\w+\s*[({]/.test(n)||/mutation\s+[A-Z]\w+\s*[({]/.test(n))return true}return false}function Z(p,e,t){let r=Me(p,e);if(r)return r;if(p.arguments?.length>0){let s=p.arguments[0],i=s?.expression||s;if(i){let n=K(i,e,t);if(n)return n}}return null}function Me(p,e){if(p.typeArguments?.params?.length>0){let t=p.typeArguments.params[0];if(t?.type==="TsTypeReference"&&t.typeName?.type==="Identifier")return d(t.typeName.value)}if(p.callee?.span&&p.span){let t=p.callee.span.end,r=Math.min(t+150,p.span.end),i=e.slice(t,r).match(/^<\s*(\w+)(?:Query|Mutation|Variables|Subscription)?[\s,>]/);if(i)return d(i[1])}return null}function K(p,e,t){if(p.type==="Identifier")return se(p.value,t);if(p.type==="MemberExpression")return Se(p,t);if(p.type==="TaggedTemplateExpression"){let r=v(p.tag);if(r==="gql"||r==="graphql")return P(p.template)}if(p.type==="TemplateLiteral")return P(p);if(p.type==="CallExpression"){let r=v(p.callee);if(r==="gql"||r==="graphql")return U(p,e)}return p.type==="ObjectExpression"?ie(p,e,t):null}function se(p,e){let t=e.variableOperations.get(p);if(t)return e.variableOperations.has(t)?se(t,e):t.endsWith("Document")||t.endsWith("Query")||t.endsWith("Mutation")?e.documentImports.get(t)||d(t):t;let r=e.documentImports.get(p);if(r)return r;let s=e.codegenMap.get(p);return s?s.operationName:/^(Query|Mutation|QUERY|MUTATION|Document)$/i.test(p)?null:d(p)}function Se(p,e){let t=p.object?.type==="Identifier"?p.object.value:null,r=p.property?.type==="Identifier"?p.property.value:null;if(!r)return null;if(t){let s=`${t}.${r}`,i=e.staticPropertyOperations.get(s);if(i)return i}return d(r)}function ie(p,e,t){for(let r of p.properties||[])if(r.type==="KeyValueProperty"&&r.key?.type==="Identifier"&&r.key.value==="query")return K(r.value,e,t);return null}function je(p,e){let t=[],r=new Set;if(!H(p))return t;let s=Ae(p);if(!s)return t;let i=V(s,p,e);return M(s,n=>{if(n.type!=="CallExpression")return;let a=v(n.callee);if(a){if($(a)){let o=Z(n,p,i),l=q(a),u=`${l}:${o||"unknown"}`;r.has(u)||(r.add(u),t.push({operationName:o||"unknown",hookName:a,type:l}));}if((a==="query"||a==="mutate")&&n.arguments?.length>0){let o=n.arguments[0],l=o?.expression||o;if(l?.type==="ObjectExpression"){let u=ie(l,p,i),f=a==="mutate"?"useMutation":"useQuery",c=`${f}:${u||"unknown"}`;u&&!r.has(c)&&(r.add(c),t.push({operationName:u,hookName:`client.${a}`,type:f}));}}}}),t}function Ge(p){return `${{useQuery:"Query",useLazyQuery:"Query",useMutation:"Mutation",useSubscription:"Subscription"}[p.type]||"Query"}: ${p.operationName}`}async function S(p,e,t=8){let r=new Array(p.length).fill(null),s=0;async function i(){for(;s<p.length;){let a=s++;if(a<p.length)try{r[a]=await e(p[a],a);}catch{r[a]=null;}}}let n=Array(Math.min(t,p.length)).fill(null).map(()=>i());return await Promise.all(n),r.filter(a=>a!==null)}function k(p,e){let t=h.createSourceFile(e,p,h.ScriptTarget.Latest,true,h.ScriptKind.TS),r=[],s=i=>{if(h.isVariableStatement(i)&&Ie(i.modifiers))for(let n of i.declarationList.declarations){if(!h.isIdentifier(n.name))continue;let a=n.name.text;if(!a.endsWith("Document")||!n.initializer)continue;let o=Pe(n.initializer),l=Ee(o);if(!l)continue;let u=Re(l);if(!u)continue;let c=h.getLineAndCharacterOfPosition(t,n.name.getStart(t)).line+1;r.push({documentName:a,operationName:u.operationName,operationType:u.operationType,document:l,line:c});}h.forEachChild(i,s);};return s(t),r}function Ie(p){return p?p.some(e=>e.kind===h.SyntaxKind.ExportKeyword):false}function Pe(p){let e=p;for(;;){if(h.isParenthesizedExpression(e)){e=e.expression;continue}if(h.isAsExpression(e)){e=e.expression;continue}if(h.isTypeAssertionExpression(e)){e=e.expression;continue}if(h.isNonNullExpression(e)){e=e.expression;continue}break}return e}function Ee(p){if(!h.isObjectLiteralExpression(p))return null;let e=B(p);if(!e||typeof e!="object")return null;let t=e.kind,r=e.definitions;return t!=="Document"||!Array.isArray(r)?null:e}function Re(p){let e=p.definitions;if(!Array.isArray(e)||e.length===0)return null;let t=e[0];if(!t||typeof t!="object"||t.kind!=="OperationDefinition")return null;let s=t.operation,i=t.name,n=s==="mutation"||s==="subscription"?s:"query",a="";if(i&&typeof i=="object"){let o=i.value;typeof o=="string"&&(a=o);}return a?{operationName:a,operationType:n}:null}function B(p){if(h.isObjectLiteralExpression(p)){let e={};for(let t of p.properties){if(h.isPropertyAssignment(t)){let r=Qe(t.name);if(!r)continue;e[r]=B(t.initializer);continue}h.isShorthandPropertyAssignment(t);}return e}return h.isArrayLiteralExpression(p)?p.elements.map(e=>h.isExpression(e)?B(e):null):h.isStringLiteral(p)||h.isNoSubstitutionTemplateLiteral(p)?p.text:h.isNumericLiteral(p)?Number(p.text):p.kind===h.SyntaxKind.TrueKeyword?true:p.kind===h.SyntaxKind.FalseKeyword?false:(p.kind===h.SyntaxKind.NullKeyword,null)}function Qe(p){return h.isIdentifier(p)||h.isStringLiteral(p)||h.isNumericLiteral(p)?p.text:(h.isComputedPropertyName(p),null)}var O=class{repoRootAbs;knownFiles;configCache=new Map;configPathCache=new Map;constructor(e,t){this.repoRootAbs=y.resolve(e),this.knownFiles=t;}resolve(e,t){if(!t||!t.startsWith(".")&&!t.startsWith("/")&&!t.startsWith("@")&&!t.includes("/"))return null;let r=y.join(this.repoRootAbs,e),s=this.getParsedConfigForFile(r),i={fileExists:m=>F.existsSync(m),readFile:m=>{try{return F.readFileSync(m,"utf8")}catch{return}},directoryExists:m=>{try{return F.existsSync(m)&&F.statSync(m).isDirectory()}catch{return false}},getCurrentDirectory:()=>this.repoRootAbs,realpath:h.sys.realpath},n=s?.options||{moduleResolution:h.ModuleResolutionKind.NodeNext,jsx:h.JsxEmit.ReactJSX,allowJs:true},o=h.resolveModuleName(t,r,n,i).resolvedModule?.resolvedFileName;if(!o)return null;let l=this.toRepoRelative(o);if(!l)return null;let u=this.normalizeRel(l),f=this.pickKnownFile(u);if(!f)return null;let c=this.getConfigPathForFile(r),g=c&&this.toRepoRelative(c)||void 0;return {file:f,evidence:{fromFile:this.normalizeRel(e),specifier:t,resolvedFile:f,configFile:g}}}getConfigPathForFile(e){let t=y.dirname(e),r=this.configPathCache.get(t);if(r!==void 0)return r;let s=this.findNearestConfig(t);return this.configPathCache.set(t,s),s}getParsedConfigForFile(e){let t=this.getConfigPathForFile(e);if(!t)return null;let r=this.configCache.get(t);if(r!==void 0)return r;try{let s=h.readConfigFile(t,h.sys.readFile);if(s.error)return this.configCache.set(t,null),null;let i=h.parseJsonConfigFileContent(s.config,h.sys,y.dirname(t),void 0,t);return this.configCache.set(t,i),i}catch{return this.configCache.set(t,null),null}}findNearestConfig(e){let t=y.resolve(e),r=this.repoRootAbs;for(;;){let s=y.join(t,"tsconfig.json"),i=y.join(t,"jsconfig.json");if(F.existsSync(s))return s;if(F.existsSync(i))return i;if(t===r)break;let n=y.dirname(t);if(n===t||(t=n,!t.startsWith(r)))break}return null}toRepoRelative(e){let t=y.resolve(e);if(!t.startsWith(this.repoRootAbs))return null;let r=y.relative(this.repoRootAbs,t);return this.normalizeRel(r)}normalizeRel(e){return y.normalize(e).replace(/\\/g,"/")}pickKnownFile(e){if(this.knownFiles.has(e))return e;let t=e.replace(/\.(ts|tsx|js|jsx|mts|cts|mjs|cjs|d\.ts)$/,""),r=this.firstKnownByStem(t);if(r)return r;let s=this.firstKnownByStem(`${t}/index`);return s||null}firstKnownByStem(e){let t=[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"];for(let r of t){let s=`${e}${r}`;if(this.knownFiles.has(s))return s}return null}};var oe=class extends A{codegenMap=new Map;tsResolver=null;coverage={tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0};constructor(e){super(e);}getName(){return "PagesAnalyzer"}async analyze(){this.log("Starting page analysis..."),await this.loadCodegenMapping();let e=await this.findPageFiles();this.coverage.tsFilesScanned+=e.length,this.log(`Found ${e.length} page files`);let t=50,r=new Map;for(let n=0;n<e.length;n+=t){let a=e.slice(n,n+t),o=await Promise.all(a.map(async l=>{try{let u=await T.readFile(l,"utf-8");return {filePath:l,content:u}}catch{return null}}));for(let l of o)l&&r.set(l.filePath,l.content);}let i=(await S(e,async n=>{let a=r.get(n);if(!a)return null;let o=this.detectPagesRoot(n);return this.analyzePageFile(n,a,o)},8)).filter(n=>n!==null);return this.log(`Analyzed ${i.length} pages successfully`),{pages:i,coverage:this.coverage}}async loadCodegenMapping(){let e=await j(["**/__generated__/graphql.ts","**/__generated__/gql.ts","**/generated/graphql.ts","**/generated/gql.ts","**/*.generated.ts","**/graphql.ts"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],absolute:true});for(let t of e)try{let r=await T.readFile(t,"utf-8"),s=y.relative(this.basePath,t);if(!r.includes("Document")||!r.includes("definitions"))continue;this.coverage.codegenFilesDetected+=1;let i=k(r,s);this.coverage.codegenFilesParsed+=1,this.coverage.codegenExportsFound+=i.length;for(let n of i)this.codegenMap.set(n.documentName,{operationName:n.operationName,operationType:n.operationType});i.length>0&&this.log(`Loaded ${i.length} codegen mappings from ${s}`);}catch{}}analyzePageFile(e,t,r){try{let s=e.endsWith(".tsx")||e.endsWith(".jsx"),i=parseSync(t,{syntax:e.endsWith(".ts")||e.endsWith(".tsx")?"typescript":"ecmascript",tsx:s,jsx:s,comments:!1}),n=y.relative(r,e),a=this.filePathToRoutePath(n),o=this.findPageComponent(i,t);if(!o)return null;let l=this.extractRouteParams(a),u=this.extractImports(i),f=this.extractLayout(i,t),c=this.extractAuthRequirement(i,t,e),g=this.extractPermissions(t),m=this.extractDataFetching(i,t,u),x=this.extractLinkedPages(i,t),C=this.extractNavigation(t),I=this.extractSteps(t);return {path:a,filePath:n,component:o,params:l,layout:f,authentication:c,permissions:g,dataFetching:m,navigation:C,linkedPages:x,steps:I.length>0?I:void 0}}catch{return this.coverage.tsParseFailures+=1,null}}async findPageFiles(){let e=this.getSetting("pagesDir","src/pages"),t=[],s=[...new Set([e,"pages","src/pages","app","src/app"])];for(let n of s){if(n==="app"||n==="src/app"){let o=["controllers","models","views","helpers"],l=this.resolvePath(n);if(o.some(f=>{try{return F.existsSync(y.join(l,f))}catch{return false}}))continue}let a=this.resolvePath(n);try{let l=n==="app"||n==="src/app"||n.endsWith("/app")?["**/page.{tsx,ts,jsx,js}"]:["**/*.tsx","**/*.ts","**/*.jsx","**/*.js"],u=await j(l,{cwd:a,ignore:["_app.tsx","_app.ts","_app.jsx","_app.js","_document.tsx","_document.ts","_error.tsx","api/**","**/*.test.*","**/*.spec.*","**/node_modules/**","**/components/pages/**"],absolute:!0});t.push(...u),u.length>0&&this.log(`Found ${u.length} pages in ${n}`);}catch{}}let i=["frontend/src/**/pages","app/javascript/**/pages"];for(let n of i)try{let a=await j([`${n}/**/*.tsx`,`${n}/**/*.ts`,`${n}/**/*.jsx`,`${n}/**/*.js`],{cwd:this.basePath,ignore:["**/*.test.*","**/*.spec.*","**/node_modules/**","**/components/pages/**"],absolute:!0});t.push(...a);}catch{}if(t.length===0){let n=await this.findSPARoutes();n.length>0&&(this.log(`Found ${n.length} SPA routes from App.tsx`),t.push(...n));}return [...new Set(t)]}async findSPARoutes(){let e=[];if(!this.tsResolver)try{let r=await j(["**/*.{ts,tsx,js,jsx}"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],absolute:!1,onlyFiles:!0,unique:!0,dot:!1});this.tsResolver=new O(this.basePath,new Set(r.map(s=>s.replace(/\\/g,"/"))));}catch{this.tsResolver=null;}let t=["src/App.tsx","src/App.jsx","src/App.js","App.tsx","App.jsx","App.js"];for(let r of t){let s=this.resolvePath(r);if(F.existsSync(s))try{let i=await T.readFile(s,"utf-8");if(!i.includes("react-router")&&!i.includes("Route"))continue;let n=parseSync(i,{syntax:"typescript",tsx:!0}),a=this.extractImports(n);this.traverseNode(n,o=>{if(o.type==="JSXOpeningElement"){let l=this.getJsxTagName(o);if(l==="Route"||l==="PrivateRoute"){let u=this.getJsxAttribute(o,"component"),f=this.getJsxAttribute(o,"element"),c=u||f,g=c?a.get(c):void 0;if(g){let m=this.resolveImportPath(s,g);m&&F.existsSync(m)&&e.push(m);}}}}),e.length>0&&e.push(s);}catch{}}return e}resolveImportPath(e,t){if(!t.startsWith(".")){let n=y.relative(this.basePath,e).replace(/\\/g,"/");if(this.tsResolver){let a=this.tsResolver.resolve(n,t);if(a)return y.join(this.basePath,a.file)}return null}let r=[".tsx",".ts",".jsx",".js","/index.tsx","/index.ts","/index.jsx","/index.js"],s=y.dirname(e),i=y.resolve(s,t);for(let n of r){let a=i+n;if(F.existsSync(a))return a}if(F.existsSync(i)&&F.statSync(i).isDirectory())for(let n of ["/index.tsx","/index.ts","/index.jsx","/index.js"]){let a=i+n;if(F.existsSync(a))return a}return null}detectPagesRoot(e){let t=["/src/pages/","/pages/","/src/app/","/app/","/frontend/src/pages/","/app/javascript/pages/"];for(let r of t){let s=e.indexOf(r);if(s!==-1)return e.substring(0,s+r.length-1)}return this.basePath}filePathToRoutePath(e){let t=e.replace(/\\/g,"/").replace(/\.(tsx?|jsx?)$/,"");return t=t.replace(/\/page$/,"").replace(/^page$/,""),t=t.replace(/\/route$/,"").replace(/^route$/,""),"/"+t.split("/").filter(Boolean).map(n=>n.replace(/^\(\.\.\.\)|^\(\.\.\)|^\(\.\)/,"")).filter(n=>!(n.startsWith("(")&&n.endsWith(")")||n.startsWith("@"))).join("/").replace(/\/index$/,"").replace(/\[\[\.\.\.(\w+)\]\]/g,"*").replace(/\[\.\.\.(\w+)\]/g,"*").replace(/\[(\w+)\]/g,":$1")}extractRouteParams(e){let t=[],r=e.match(/:(\w+)/g);if(r)for(let s of r)t.push(s.slice(1));return t}findDefaultExportName(e){for(let t of e.body){if(t.type==="ExportDefaultDeclaration"){let r=t.decl;if((r?.type==="FunctionExpression"||r?.type==="FunctionDeclaration")&&r.identifier?.value||(r?.type==="ClassDeclaration"||r?.type==="ClassExpression")&&r.identifier?.value)return r.identifier.value;if(r?.type==="Identifier")return r.value}if(t.type==="ExportDefaultExpression"){let r=t.expression;if(r?.type==="Identifier")return r.value}}return null}findPageComponent(e,t){let r=this.findDefaultExportName(e);if(r&&r!=="Page"&&r!=="default")return r;let s=this.findMainJsxComponent(e,t);if(s&&s!=="Page"&&s!=="default")return s;for(let i of e.body){if(i.type==="ExportDefaultDeclaration"){let n=i.decl;if((n?.type==="FunctionExpression"||n?.type==="FunctionDeclaration")&&n.identifier?.value){let a=n.identifier.value;if(a!=="Page")return a}if((n?.type==="ClassDeclaration"||n?.type==="ClassExpression")&&n.identifier?.value){let a=n.identifier.value;if(a!=="Page")return a}if(n?.type==="Identifier"){let a=n.value;if(a!=="Page")return a}if(n?.type==="ArrowFunctionExpression"||(n?.type==="FunctionExpression"||n?.type==="FunctionDeclaration")&&!n.identifier)return s||"default"}if(i.type==="ExportDefaultExpression"){let n=i.expression;if(n?.type==="Identifier"){let a=n.value;if(a!=="Page")return a}}}if(s)return s;for(let i of e.body)if(i.type==="VariableDeclaration"){for(let n of i.declarations)if(n.id?.type==="Identifier"&&n.id.value==="Page")return "Page"}for(let i of e.body)if(i.type==="ExportDeclaration"&&i.declaration?.type==="FunctionDeclaration"){let n=i.declaration.identifier?.value;if(n&&/^[A-Z]/.test(n))return n}for(let i of e.body){if(i.type==="FunctionDeclaration"){let n=i.identifier?.value;if(n&&/^[A-Z]/.test(n))return n}if(i.type==="VariableDeclaration"){for(let n of i.declarations)if(n.id?.type==="Identifier"){let a=n.id.value;if(a&&/^[A-Z]/.test(a)&&t.includes("return")&&t.includes("<"))return a}}}return null}isProjectImport(e){return e.startsWith("./")||e.startsWith("../")||/^[@~#]\//.test(e)?true:!(e.startsWith("@")&&!e.startsWith("@/")||/^[a-z]/.test(e))}findMainJsxComponent(e,t){let r=this.extractImports(e),s=new Set;for(let[a,o]of r)/^[A-Z]/.test(a)&&this.isProjectImport(o)&&s.add(a);let i=[];for(let a of s){let o=new RegExp(`<${a}[\\s/>]`,"g"),l;for(;(l=o.exec(t))!==null;)i.push({name:a,index:l.index});}let n=i.find(a=>a.name.includes("Container")||a.name.includes("Page")||a.name.includes("View")||a.name.includes("Screen"));return n?n.name:i.length>0?(i.sort((a,o)=>a.index-o.index),i[0].name):null}extractImports(e){let t=new Map;for(let r of e.body)if(r.type==="ImportDeclaration"){let s=r.source?.value||"";for(let i of r.specifiers||[])i.type==="ImportSpecifier"&&i.local?.value&&t.set(i.local.value,s),i.type==="ImportDefaultSpecifier"&&i.local?.value&&t.set(i.local.value,s);}return t}extractLayout(e,t){if(t.includes("getLayout")){let r=t.match(/getLayout\s*=.*?<(\w+Layout|\w+Shell)/);if(r)return r[1]}}extractAuthRequirement(e,t,r){let s=y.basename(r),a={required:!["404.tsx","permission-denied.tsx","_app.tsx","_document.tsx","_error.tsx"].some(l=>s===l)},o=["RequiredCondition","ProtectedRoute","AuthGuard","PrivateRoute","WithAuth","RequireAuth","Authenticated","Authorized"];for(let l of o)if(t.includes(`<${l}`)){a.condition="Additional permissions required";let u=this.extractRolesFromContent(t);u.length>0&&(a.roles=u);break}return a}extractRolesFromContent(e){let t=[];this.traverseNode({content:e},()=>{});let r=e.matchAll(/(\w+Role|\w+Permission)\.(\w+)/g);for(let s of r)t.push(s[2]);return [...new Set(t)]}extractPermissions(e){let t=[],r=e.matchAll(/(?:Permission|Role|isAdmin)\.\w+/g);for(let s of r)t.includes(s[0])||t.push(s[0]);return t}extractDataFetching(e,t,r){let s=[],i=new Set,n=new Map;for(let[l,u]of this.codegenMap)n.set(l,{operationName:u.operationName,type:u.operationType});let a=V(e,t,n),o=this.getGraphQLHookPatterns();if(M(e,l=>{if(l.type==="CallExpression"){let u=l,f=v(u.callee);if(!f)return;if($(f,o)&&re(u,t,a)){let c=Z(u,t,a),m={type:q(f,o),operationName:c||"unknown"},x=this.extractVariablesFromCall(u);Object.keys(x).length>0&&(m.variables=x);let C=`${m.type}:${m.operationName}`;i.has(C)||(i.add(C),s.push(m));}if(f==="query"||f==="mutate"){let c=this.analyzeClientDirectCall(u,t,a);if(c){let g=`${c.type}:${c.operationName}`;i.has(g)||(i.add(g),s.push(c));}}}}),this.extractSSRDataFetching(e,t,s,i),t.includes("getStaticProps")){let l="getStaticProps:getStaticProps";i.has(l)||(i.add(l),s.push({type:"getStaticProps",operationName:"getStaticProps"}));}return s}analyzeClientDirectCall(e,t,r){if(!e.arguments?.length)return null;let s=e.arguments[0],i=s?.expression||s;if(i?.type!=="ObjectExpression")return null;for(let n of i.properties||[])if(n.type==="KeyValueProperty"&&n.key?.type==="Identifier"&&n.key.value==="query"){let a=n.value,o=null;if(a?.type==="Identifier"){let l=a.value;o=r.variableOperations.get(l)||r.documentImports.get(l)||d(l);}if(a?.type==="MemberExpression"){let l=a.object?.type==="Identifier"?a.object.value:null,u=a.property?.type==="Identifier"?a.property.value:null;if(l&&u){let f=`${l}.${u}`;o=r.staticPropertyOperations.get(f)||d(u);}}if(o)return {type:v(e.callee)==="mutate"?"useMutation":"useQuery",operationName:o}}return null}extractDocumentImports(e){let t=new Map;for(let r of e.body)if(r.type==="ImportDeclaration"){let s=r.source?.value||"",i=s.includes("__generated__")||s.includes("generated")||s.includes("graphql")||s.includes(".generated");for(let n of r.specifiers||[]){let a=n.type==="ImportSpecifier"||n.type==="ImportDefaultSpecifier"?n.local?.value:null;if(a){if(a.endsWith("Document")||i){let o=a.replace(/Document$/,"");t.set(a,o);}(a.endsWith("Query")||a.endsWith("Mutation"))&&t.set(a,a.replace(/Query$|Mutation$/,""));}}}return t}extractVariableAssignments(e,t){let r=new Map;return this.traverseNode(e,s=>{if(s.type==="VariableDeclarator"&&s.id?.type==="Identifier"){let i=s.id.value,n=s.init;if(!n)return;if(n.type==="Identifier"){let a=n.value;(a.endsWith("Document")||a.endsWith("Query"))&&r.set(i,a);}if(n.type==="CallExpression"){let a=this.getCalleeName(n.callee);if(a==="gql"||a==="graphql"){let o=this.extractOperationNameFromGqlCall(n,t);o&&r.set(i,o);}}if(n.type==="TaggedTemplateExpression"){let a=this.getCalleeName(n.tag);if(a==="gql"||a==="graphql"){let o=n.template;if(o?.quasis?.[0]?.raw){let u=o.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);u&&r.set(i,u[1]);}}}}}),r}extractOperationNameFromGqlCall(e,t){if(!e.arguments?.length)return null;let r=e.arguments[0],s=r?.expression||r;if(s?.type==="TemplateLiteral"&&s.quasis?.[0]?.raw){let n=s.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}if(e.span){let n=t.slice(e.span.start,e.span.end).match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}return null}analyzeGraphQLHookCall(e,t,r,s){let i=this.getCalleeName(e.callee);if(!i)return null;let n=this.getGraphQLHookPatterns(),a=W.includes(i),o=R(i,n)&&!i.includes("Params"),l=Q(i,n);if(!a&&!o&&!l)return null;let u=q(i,n),f=i.replace(/^use/,"").replace(/Query$|Mutation$/,""),c=this.extractTypeGeneric(e,t);if(c&&(f=c.replace(/Query$|Mutation$|Variables$/,"")),e.arguments&&e.arguments.length>0){let m=e.arguments[0],x=m?.expression||m,C=this.extractOperationFromArgument(x,r,s);C&&(f=C);}let g=this.extractVariablesFromCall(e);return {type:u,operationName:f,variables:g}}extractTypeGeneric(e,t){if(e.typeArguments?.params?.length>0){let r=e.typeArguments.params[0];if(r?.type==="TsTypeReference"&&r.typeName?.type==="Identifier")return r.typeName.value}if(e.callee?.span){let r=e.callee.span.end,i=t.slice(r,r+100).match(/^<(\w+)(?:Query|Mutation|Variables)?[,>]/);if(i)return i[1]}return null}extractOperationFromArgument(e,t,r){if(!e)return null;if(e.type==="Identifier"){let s=e.value;if(["[","{","'",'"',"`"].some(o=>s.startsWith(o)))return null;let i=r.get(s);if(i)return !i.endsWith("Document")&&!i.endsWith("Query")?i:t.get(i)||i.replace(/Document$/,"");let n=t.get(s);if(n)return n;let a=this.codegenMap.get(s);return a?a.operationName:/^(Query|Mutation|QUERY|MUTATION)$/i.test(s)?null:s.replace(/Document$/,"").replace(/Query$|Mutation$/,"")}if(e.type==="MemberExpression"&&e.property?.type==="Identifier")return e.property.value.replace(/Document$/,"").replace(/Query$|Mutation$/,"");if(e.type==="TaggedTemplateExpression"&&e.template?.quasis?.[0]?.raw){let i=e.template.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(i)return i[1]}if(e.type==="CallExpression"){let s=this.getCalleeName(e.callee);if((s==="graphql"||s==="gql")&&e.arguments?.length>0){let i=e.arguments[0],n=i?.expression||i;if(n?.type==="TemplateLiteral"&&n.quasis?.[0]?.raw){let o=n.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(o)return o[1]}}}if(e.type==="TemplateLiteral"&&e.quasis?.[0]?.raw){let i=e.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(i)return i[1]}return null}extractVariablesFromCall(e){let t=[];if(e.arguments&&e.arguments.length>1){let r=e.arguments[1],s=r?.expression||r;if(s?.type==="ObjectExpression"){for(let i of s.properties||[])if(i.type==="KeyValueProperty"&&i.key?.type==="Identifier"&&i.key.value==="variables"&&i.value?.type==="ObjectExpression")for(let n of i.value.properties||[])n.type==="KeyValueProperty"&&n.key?.type==="Identifier"?t.push(n.key.value):n.type==="Identifier"&&t.push(n.value);}}return t}extractSSRDataFetching(e,t,r,s){let i=this.extractImports(e),n=this.extractDocumentImports(e);for(let a of e.body)if(a.type==="ExportDeclaration"){let o=a.declaration;if(o?.type==="VariableDeclaration")for(let l of o.declarations)l.id?.type==="Identifier"&&l.id.value==="getServerSideProps"&&this.extractSSRQueriesFromNode(l,t,i,n,r,s);o?.type==="FunctionDeclaration"&&o.identifier?.value==="getServerSideProps"&&this.extractSSRQueriesFromNode(o,t,i,n,r,s);}}extractSSRQueriesFromNode(e,t,r,s,i,n){M(e,a=>{if(a.type!=="CallExpression")return;let o=v(a.callee);if(o==="query"||o==="mutate"){let l=this.extractQueryFromClientCall(a,t,r,s);if(l){let u=`getServerSideProps:\u2192 ${l}`;n.has(u)||(n.add(u),i.push({type:"getServerSideProps",operationName:`\u2192 ${l}`}));}}});}extractQueryFromClientCall(e,t,r,s){if(!e.arguments?.length)return null;let i=e.arguments[0],n=i?.expression||i;if(n?.type!=="ObjectExpression")return null;for(let a of n.properties||[])if(a.type==="KeyValueProperty"&&a.key?.type==="Identifier"&&a.key.value==="query"){let o=a.value;if(o?.type==="Identifier"){let l=o.value;if(s.has(l))return s.get(l)||null;let u=this.codegenMap.get(l);return u?u.operationName:r.get(l)?d(l):d(l)}if(o?.type==="MemberExpression"){let l=o.object?.type==="Identifier"?o.object.value:null,u=o.property?.type==="Identifier"?o.property.value:null;if(l&&u)return `${l}.${u}`}}return null}extractNavigation(e){let t={visible:true,currentNavItem:null};(e.includes("hideNavigation")||e.includes("noNav"))&&(t.visible=false),(e.includes("miniNav")||e.includes("collapsedNav"))&&(t.mini=true);let r=e.match(/currentNav(?:Item)?[:\s=]+['"`]([^'"`]+)['"`]/);return r&&(t.currentNavItem=r[1]),t}extractLinkedPages(e,t){let r=[];return this.traverseNode(e,s=>{if(s.type==="JSXOpeningElement"&&this.getJsxTagName(s)==="Link"){let n=this.getJsxAttribute(s,"href");if(n&&n.startsWith("/")&&!n.includes("http")){let a=n.split("?")[0].split("#")[0];r.includes(a)||r.push(a);}}}),r}extractSteps(e){let t=[],r=e.matchAll(/(?:step|Step)\s*[:=]\s*['"`]([^'"`]+)['"`]/g),s=0;for(let i of r)t.push({id:s++,name:i[1]});return t}traverseNode(e,t){if(!(!e||typeof e!="object")){t(e);for(let r of Object.keys(e)){let s=e[r];if(Array.isArray(s))for(let i of s)this.traverseNode(i,t);else s&&typeof s=="object"&&this.traverseNode(s,t);}}}getCalleeName(e){if(e.type==="Identifier")return e.value;if(e.type==="MemberExpression"){let t=e.object,r=e.property;if(t.type==="Identifier"&&r.type==="Identifier")return `${t.value}.${r.value}`}return null}getJsxTagName(e){return e.name?.type==="Identifier"?e.name.value:null}getJsxAttribute(e,t){if(!e.attributes)return null;for(let r of e.attributes)if(r.type==="JSXAttribute"&&r.name?.value===t){if(r.value?.type==="StringLiteral")return r.value.value;if(r.value?.type==="JSXExpressionContainer"&&(r.value.expression?.type==="Identifier"||r.value.expression?.type==="StringLiteral"))return r.value.expression.value}return null}};var ue=class extends A{coverage={tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0};constructor(e){super(e);}getName(){return "GraphQLAnalyzer"}async analyze(){this.log("Starting GraphQL analysis...");let e=[];this.log("[GraphQLAnalyzer] Step 1: Analyzing .graphql files...");let t=await this.analyzeGraphQLFiles();e.push(...t),this.log(`[GraphQLAnalyzer] Step 1 done: ${t.length} from .graphql files`),this.log("[GraphQLAnalyzer] Step 2: Analyzing inline GraphQL...");let r=await this.analyzeInlineGraphQL();e.push(...r),this.log(`[GraphQLAnalyzer] Step 2 done: ${r.length} inline operations`),this.log("[GraphQLAnalyzer] Step 3: Analyzing codegen output...");let s=await this.analyzeCodegenGenerated();e.push(...s),this.log(`[GraphQLAnalyzer] Step 3 done: ${s.length} from codegen`);let i=this.deduplicateOperations(e);return this.log(`[GraphQLAnalyzer] Deduplicated: ${i.length} unique operations`),this.log("[GraphQLAnalyzer] Step 4: Finding operation usage..."),await this.findOperationUsage(i),this.log("[GraphQLAnalyzer] Step 4 done"),this.log(`Found ${i.length} GraphQL operations`),{graphqlOperations:i,coverage:this.coverage}}deduplicateOperations(e){let t=new Map;for(let r of e)if(!t.has(r.name))t.set(r.name,r);else {let s=t.get(r.name);if(s)for(let i of r.usedIn)s.usedIn.includes(i)||s.usedIn.push(i);}return Array.from(t.values())}async analyzeCodegenGenerated(){let e=[],t=await j(["**/__generated__/graphql.ts","**/__generated__/gql.ts","**/generated/graphql.ts","**/generated/gql.ts","**/*.generated.ts","**/*.generated.tsx","**/graphql/generated.ts","**/gql/generated.ts"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],absolute:true});for(let r of t)try{let s=await T.readFile(r,"utf-8"),i=y.relative(this.basePath,r);if(!s.includes("Document")||!s.includes("definitions"))continue;this.coverage.codegenFilesDetected+=1;let n=k(s,i);this.coverage.codegenFilesParsed+=1,this.coverage.codegenExportsFound+=n.length;for(let a of n){let l=a.document?.definitions?.[0];if(!l||l.kind!=="OperationDefinition")continue;let u=(l.variableDefinitions||[]).map(f=>({name:f.variable?.name?.value||"unknown",type:this.extractTypeFromAst(f.type),required:f.type?.kind==="NonNullType"}));e.push({name:a.operationName,type:a.operationType,filePath:i,usedIn:[],variables:u,returnType:this.inferReturnTypeFromAst(l),fragments:this.extractFragmentReferencesFromAst(l),fields:this.extractFieldsFromAst(l.selectionSet),variableNames:[a.documentName]});}n.length>0&&this.log(`Found ${n.length} operations in codegen output: ${i}`);}catch(s){this.warn(`Failed to analyze codegen file ${r}: ${s.message}`);}return e}extractTypeFromAst(e){return e?e.kind==="NonNullType"?`${this.extractTypeFromAst(e.type)}!`:e.kind==="ListType"?`[${this.extractTypeFromAst(e.type)}]`:e.kind==="NamedType"&&e.name?.value||"unknown":"unknown"}extractFieldsFromAst(e,t=0){if(!e?.selections||t>5)return [];let r=[];for(let s of e.selections)if(s.kind==="Field"){let i={name:s.name?.value||"unknown"};if(s.arguments?.length>0){let n=s.arguments.map(a=>a.name?.value).join(", ");i.type=`(${n})`;}s.selectionSet&&(i.fields=this.extractFieldsFromAst(s.selectionSet,t+1)),r.push(i);}else if(s.kind==="FragmentSpread")r.push({name:`...${s.name?.value}`,type:"fragment"});else if(s.kind==="InlineFragment"){let i=s.typeCondition?.name?.value||"inline";r.push({name:`... on ${i}`,type:"inline-fragment",fields:this.extractFieldsFromAst(s.selectionSet,t+1)});}return r}extractFragmentReferencesFromAst(e){let t=[],r=s=>{if(s&&(s.kind==="FragmentSpread"&&t.push(s.name?.value),s.selectionSet?.selections))for(let i of s.selectionSet.selections)r(i);};return r(e),t.filter(Boolean)}inferReturnTypeFromAst(e){if(e.selectionSet?.selections?.length>0){let t=e.selectionSet.selections[0];if(t.kind==="Field")return t.name?.value||"unknown"}return "unknown"}async analyzeGraphQLFiles(){let e=await j(["**/*.graphql"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**"],absolute:true});return (await S(e,async r=>{let s=await T.readFile(r,"utf-8");try{let i=parse(s);return this.extractOperationsFromDocument(i,y.relative(this.basePath,r))}catch{return this.coverage.graphqlParseFailures+=1,[]}})).flat()}async analyzeInlineGraphQL(){let e=[],t=await j(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__tests__/**","**/*.test.*","**/*.spec.*","**/__generated__/**"],absolute:true});this.coverage.tsFilesScanned+=t.length;let r=50;for(let s=0;s<t.length;s+=r){let i=t.slice(s,s+r),n=await S(i,async a=>{try{let o=await T.readFile(a,"utf-8");if(!o.includes("gql")&&!o.includes("graphql"))return [];let l=y.relative(this.basePath,a),u=a.endsWith(".tsx")||a.endsWith(".jsx"),f=parseSync(o,{syntax:a.endsWith(".ts")||a.endsWith(".tsx")?"typescript":"ecmascript",tsx:u,jsx:u});return this.analyzeModuleForGraphQL(f,o,l)}catch{return this.coverage.tsParseFailures+=1,[]}},10);e.push(...n.flat());}return e}analyzeModuleForGraphQL(e,t,r){let s=[],i=[];return this.traverseNodeWithContext(e,i,(n,a)=>{if(n.type==="TaggedTemplateExpression"){let o=n,l=this.getTagName(o.tag);if(l==="gql"||l==="graphql"){let u=this.extractTemplateContent(o.template,t);if(u)try{let f=parse(u),c=this.extractOperationsFromDocument(f,r);if(a)for(let g of c)g.variableNames=g.variableNames||[],g.variableNames.push(a),g.variableNames.push(`${g.name}Document`);s.push(...c);}catch{this.coverage.graphqlParseFailures+=1;}}}if(n.type==="CallExpression"){let o=n,l=this.getCalleeName(o.callee);if((l==="gql"||l==="graphql")&&o.arguments.length>0){let u=o.arguments[0].expression,f=this.extractGraphQLFromExpression(u,t);if(f)try{let c=parse(f),g=this.extractOperationsFromDocument(c,r);if(a)for(let m of g)m.variableNames=m.variableNames||[],m.variableNames.push(a),m.variableNames.push(`${m.name}Document`);s.push(...g);}catch{this.coverage.graphqlParseFailures+=1;}}}}),s}traverseNodeWithContext(e,t,r){if(!e||typeof e!="object")return;let s=false;e.type==="VariableDeclarator"&&e.id?.type==="Identifier"&&(t.push(e.id.value),s=true),r(e,t.length>0?t[t.length-1]:null);for(let i of Object.keys(e)){let n=e[i];if(Array.isArray(n))for(let a of n)this.traverseNodeWithContext(a,t,r);else n&&typeof n=="object"&&this.traverseNodeWithContext(n,t,r);}s&&t.pop();}getTagName(e){return e.type==="Identifier"?e.value:null}getCalleeName(e){return e.type==="Identifier"?e.value:null}extractTemplateContent(e,t){if(e.type==="TemplateLiteral"){if(e.quasis.length===1&&e.expressions.length===0)return e.quasis[0].raw;let r=e.span.start,s=e.span.end;return t.slice(r,s).slice(1,-1).replace(/\$\{[^}]*\}/g,"")}return null}extractGraphQLFromExpression(e,t){return e.type==="TemplateLiteral"?this.extractTemplateContent(e,t):e.type==="StringLiteral"?e.value:null}extractOperationsFromDocument(e,t){let r=[];for(let s of e.definitions){let i=this.extractOperation(s,t);i&&r.push(i);}return r}extractOperation(e,t){if(e.kind==="OperationDefinition"){let r=e.name?.value||"anonymous",s=e.operation,i=this.extractVariables(e),n=this.extractFragmentReferences(e),a=this.extractFields(e),o=e.loc?getLocation(e.loc.source,e.loc.start):null;return {name:r,type:s,filePath:t,line:o?.line,column:o?.column,usedIn:[],variables:i,returnType:this.inferReturnType(e),fragments:n,fields:a}}if(e.kind==="FragmentDefinition"){let r=e.loc?getLocation(e.loc.source,e.loc.start):null;return {name:e.name.value,type:"fragment",filePath:t,line:r?.line,column:r?.column,usedIn:[],variables:[],returnType:e.typeCondition.name.value,fragments:this.extractFragmentReferences(e),fields:this.extractFields(e)}}return null}extractFields(e){let t=[],r=(s,i=0)=>{if(!s||!s.selections||i>5)return [];let n=[];for(let a of s.selections)if(a.kind==="Field"){let o={name:a.name.value};if(a.arguments&&a.arguments.length>0){let l=a.arguments.map(u=>u.name.value).join(", ");o.type=`(${l})`;}a.selectionSet&&(o.fields=r(a.selectionSet,i+1)),n.push(o);}else if(a.kind==="FragmentSpread")n.push({name:`...${a.name.value}`,type:"fragment"});else if(a.kind==="InlineFragment"&&a.selectionSet){let o=a.typeCondition?.name?.value||"inline";n.push({name:`... on ${o}`,type:"inline-fragment",fields:r(a.selectionSet,i+1)});}return n};return e.selectionSet?r(e.selectionSet):t}extractVariables(e){let t=[];if(e.variableDefinitions)for(let r of e.variableDefinitions){let s=r.variable.name.value,i=this.typeNodeToString(r.type),n=r.type.kind==="NonNullType";t.push({name:s,type:i,required:n});}return t}typeNodeToString(e){return e.kind==="NonNullType"?`${this.typeNodeToString(e.type)}!`:e.kind==="ListType"?`[${this.typeNodeToString(e.type)}]`:e.kind==="NamedType"?e.name.value:"unknown"}extractFragmentReferences(e){let t=[],r=s=>{if(s&&(s.kind==="FragmentSpread"&&t.push(s.name.value),s.selectionSet))for(let i of s.selectionSet.selections)r(i);};return r(e),t}inferReturnType(e){if(e.selectionSet&&e.selectionSet.selections.length>0){let t=e.selectionSet.selections[0];if(t.kind==="Field")return t.name.value}return "unknown"}async findOperationUsage(e){if(e.length===0)return;let t=this.getGraphQLHookPatterns(),r=await j(["**/*.ts","**/*.tsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__generated__/**","**/dist/**","**/build/**"],absolute:true}),s=new Map,i=new Map,n=new Map,a=new Map;for(let c of e)if(s.set(c.name,c),i.set(`${c.name}Document`,c),a.set(`${c.name}Query`,c),a.set(`${c.name}Mutation`,c),a.set(`${c.name}Subscription`,c),a.set(`${c.name}QueryVariables`,c),a.set(`${c.name}MutationVariables`,c),c.variableNames)for(let g of c.variableNames)n.set(g,c);let o=new Set;for(let c of e)if(o.add(c.name),o.add(`${c.name}Document`),o.add(`${c.name}Query`),o.add(`${c.name}Mutation`),o.add(`${c.name}Subscription`),c.variableNames)for(let g of c.variableNames)o.add(g);let l=null,u=Array.from(o);if(u.length>0&&u.length<2e3){let c=u.sort((g,m)=>m.length-g.length).map(g=>g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));l=new RegExp(`\\b(${c.join("|")})\\b`,"g");}let f=50;for(let c=0;c<r.length;c+=f){let g=r.slice(c,c+f);await Promise.all(g.map(async m=>{try{let x=await T.readFile(m,"utf-8"),C=y.relative(this.basePath,m);if(!H(x))return;if(l){let I=new Set,Y;for(;(Y=l.exec(x))!==null;)I.add(Y[1]);l.lastIndex=0;for(let z of I){let L=i.get(z)||n.get(z)||s.get(z);L&&C!==L.filePath&&(L.usedIn.includes(C)||L.usedIn.push(C));}}await this.findUsageWithAST(x,m,C,s,a,n,t);}catch{}}));}}async findUsageWithAST(e,t,r,s,i,n,a){try{let o=t.endsWith(".tsx")||t.endsWith(".jsx"),l=parseSync(e,{syntax:t.endsWith(".ts")||t.endsWith(".tsx")?"typescript":"ecmascript",tsx:o,jsx:o,comments:!1});this.traverseNodeForUsage(l,e,u=>{if(u.type==="CallExpression"){let f=this.getCalleeNameForUsage(u.callee);if(f&&$(f,a)){let c=this.extractTypeGenericFromCall(u,e);if(c){let m=i.get(c)||s.get(c.replace(/Query$|Mutation$|Variables$/,""));m&&r!==m.filePath&&(m.usedIn.includes(r)||m.usedIn.push(r));}let g=this.extractFirstArgName(u);if(g){let m=g.replace(/Document$/,""),x=n.get(g)||n.get(m)||s.get(m)||i.get(g);x&&r!==x.filePath&&(x.usedIn.includes(r)||x.usedIn.push(r));}}}});}catch{}}traverseNodeForUsage(e,t,r){if(!(!e||typeof e!="object")){r(e);for(let s of Object.keys(e)){let i=e[s];if(Array.isArray(i))for(let n of i)this.traverseNodeForUsage(n,t,r);else i&&typeof i=="object"&&this.traverseNodeForUsage(i,t,r);}}}getCalleeNameForUsage(e){return e?e.type==="Identifier"?e.value:e.type==="MemberExpression"&&e.property?.type==="Identifier"?e.property.value:null:null}extractTypeGenericFromCall(e,t){if(e.typeArguments?.params?.length>0){let r=e.typeArguments.params[0];if(r?.type==="TsTypeReference"&&r.typeName?.type==="Identifier")return r.typeName.value}if(e.callee?.span){let r=e.callee.span.end,i=t.slice(r,r+150).match(/^<\s*(\w+)(?:Query|Mutation|Variables|Subscription)?(?:\s*,|\s*>)/);if(i)return i[1]}return null}extractFirstArgName(e){if(e.arguments?.length>0){let t=e.arguments[0].expression;if(t?.type==="Identifier")return t.value;if(t?.type==="MemberExpression"&&t.property?.type==="Identifier")return t.property.value}return null}};var fe=class extends A{componentCache=new Map;coverage={tsFilesScanned:0,tsParseFailures:0,graphqlParseFailures:0,codegenFilesDetected:0,codegenFilesParsed:0,codegenExportsFound:0};constructor(e){super(e);}getName(){return "DataFlowAnalyzer"}async analyze(){this.log("Starting data flow analysis...");let e=await this.analyzeComponents(),t=await this.analyzeDataFlows(e);return this.log(`Analyzed ${e.length} components and ${t.length} data flows`),{components:e,dataFlows:t,coverage:this.coverage}}async analyzeComponents(){let e=[],t=[this.getSetting("featuresDir",""),this.getSetting("componentsDir",""),this.getSetting("pagesDir","")].filter(Boolean),r=["src/features","src/components","src/common/components","src/common","src/pages","src/app","src/modules","src/views","src/screens","components","pages","app"],i=[...new Set([...t,...r])].flatMap(o=>[`${o}/**/*.tsx`,`${o}/**/*.ts`]),n=await j(i,{cwd:this.basePath,ignore:["**/*.test.*","**/*.spec.*","**/*.stories.*","**/node_modules/**","**/__generated__/**"],absolute:true,onlyFiles:true,unique:true});this.log(`[DataFlowAnalyzer] Found ${n.length} component files to analyze`),this.coverage.tsFilesScanned+=n.length;let a=50;for(let o=0;o<n.length;o+=a){let l=n.slice(o,o+a),u=await Promise.all(l.map(async f=>{try{let c=await T.readFile(f,"utf-8");return {filePath:f,content:c}}catch{return null}}));for(let f of u)if(f)try{let c=parseSync(f.content,{syntax:"typescript",tsx:!0,comments:!1}),g=y.relative(this.basePath,f.filePath),m=this.analyzeComponentFile(c,g,f.content);e.push(...m);}catch{this.coverage.tsParseFailures+=1;}}return this.log(`[DataFlowAnalyzer] Extracted ${e.length} components`),this.buildDependencyGraph(e),e}analyzeComponentFile(e,t,r){let s=[],i=this.extractImports(e);for(let n of e.body){if(n.type==="ExportDeclaration"&&n.declaration?.type==="FunctionDeclaration"){let a=n.declaration.identifier?.value;if(a&&this.isComponentName(a)){let o=this.extractComponentInfo(a,t,r,i);s.push(o),this.componentCache.set(a,o);}}if(n.type==="FunctionDeclaration"){let a=n.identifier?.value;if(a&&this.isComponentName(a)){let o=this.extractComponentInfo(a,t,r,i);s.push(o),this.componentCache.set(a,o);}}if(n.type==="ExportDefaultDeclaration"&&n.decl?.type==="FunctionExpression"){let a=n.decl.identifier?.value;if(a&&this.isComponentName(a)){let o=this.extractComponentInfo(a,t,r,i);s.push(o),this.componentCache.set(a,o);}}if(n.type==="VariableDeclaration"){for(let a of n.declarations)if(a.id?.type==="Identifier"){let o=a.id.value;if(o&&(this.isComponentName(o)||o.startsWith("use"))&&a.init&&(a.init.type==="ArrowFunctionExpression"||a.init.type==="FunctionExpression")){let l=this.extractComponentInfo(o,t,r,i);s.push(l),this.componentCache.set(o,l);}}}if(n.type==="ExportDeclaration"&&n.declaration?.type==="VariableDeclaration"){for(let a of n.declaration.declarations)if(a.id?.type==="Identifier"){let o=a.id.value;if(o&&(this.isComponentName(o)||o.startsWith("use"))&&a.init&&(a.init.type==="ArrowFunctionExpression"||a.init.type==="FunctionExpression")){let l=this.extractComponentInfo(o,t,r,i);s.push(l),this.componentCache.set(o,l);}}}}return s}extractImports(e){let t=new Map,r=this.getListSetting("aliasPrefixes",["@/","~/","#/"]);for(let s of e.body)if(s.type==="ImportDeclaration"){let i=s.source?.value||"",n=r.some(a=>i.startsWith(a));if(i.startsWith(".")||n)for(let a of s.specifiers||[])a.type==="ImportSpecifier"&&a.local?.value&&t.set(a.local.value,i),a.type==="ImportDefaultSpecifier"&&a.local?.value&&t.set(a.local.value,i);}return t}isComponentName(e){return /^[A-Z][a-zA-Z0-9]*$/.test(e)}extractComponentInfo(e,t,r,s){let i="presentational";["/pages/","/app/","/routes/","/views/","/screens/"].some(f=>t.includes(f))?i="page":e.includes("Container")||e.includes("Provider")?i="container":e.includes("Layout")||e.includes("Shell")||e.includes("Wrapper")||e.includes("Frame")||e.includes("Scaffold")||t.includes("/layouts/")||t.includes("/layout/")?i="layout":e.startsWith("use")&&(i="hook");let a=this.extractHooksUsed(r),o=Array.from(s.keys()).filter(f=>this.isComponentName(f)||f.startsWith("use")),l=[];for(let[f,c]of s)l.push({name:f,path:c});let u=this.extractStateManagement(r);return {name:e,filePath:t,type:i,props:[],dependencies:o,dependents:[],hooks:a,stateManagement:u,imports:l}}extractHooksUsed(e){let t=[],r=new Set;if(!e.includes("use"))return t;try{let s=parseSync(e,{syntax:"typescript",tsx:!0,comments:!1}),i=this.extractDocumentImportsFromAst(s),n=this.extractVariableOperationMap(s,e);this.traverseForHooks(s,e,i,n,t,r);}catch{this.extractHooksWithRegex(e,t,r);}return t}extractDocumentImportsFromAst(e){let t=new Map;for(let r of e.body)if(r.type==="ImportDeclaration"){let s=r.source?.value||"",i=s.includes("__generated__")||s.includes("generated")||s.includes("graphql")||s.includes(".generated");for(let n of r.specifiers||[]){let a;(n.type==="ImportSpecifier"||n.type==="ImportDefaultSpecifier")&&(a=n.local?.value),a&&((a.endsWith("Document")||i)&&t.set(a,a.replace(/Document$/,"")),(a.endsWith("Query")||a.endsWith("Mutation"))&&t.set(a,a.replace(/Query$|Mutation$/,"")));}}return t}extractVariableOperationMap(e,t){let r=new Map,s=n=>{if(n.type!=="VariableDeclarator"||n.id?.type!=="Identifier")return;let a=n.id.value,o=n.init;if(o){if(o.type==="CallExpression"){let l=this.getCalleeNameFromNode(o.callee);if(l==="gql"||l==="graphql"){let u=this.extractOperationNameFromGqlCall(o,t);u&&r.set(a,u);}}if(o.type==="TaggedTemplateExpression"){let l=this.getCalleeNameFromNode(o.tag);if((l==="gql"||l==="graphql")&&o.template?.quasis?.[0]?.raw){let f=o.template.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);f&&r.set(a,f[1]);}}}},i=n=>{if(!(!n||typeof n!="object")){s(n);for(let a of Object.keys(n)){let o=n[a];if(Array.isArray(o))for(let l of o)i(l);else o&&typeof o=="object"&&i(o);}}};return i(e),r}extractOperationNameFromGqlCall(e,t){if(!e.arguments?.length)return null;let r=e.arguments[0],s=r?.expression||r;if(s?.type==="TemplateLiteral"&&s.quasis?.[0]?.raw){let n=s.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}if(e.span){let n=t.slice(e.span.start,e.span.end).match(/(?:query|mutation|subscription)\s+(\w+)/i);if(n)return n[1]}return null}traverseForHooks(e,t,r,s,i,n){if(!(!e||typeof e!="object")){e.type==="CallExpression"&&this.analyzeHookCall(e,t,r,s,i,n);for(let a of Object.keys(e)){let o=e[a];if(Array.isArray(o))for(let l of o)this.traverseForHooks(l,t,r,s,i,n);else o&&typeof o=="object"&&this.traverseForHooks(o,t,r,s,i,n);}}}analyzeHookCall(e,t,r,s,i,n){let a=this.getCalleeNameFromNode(e.callee);if(!a||!a.startsWith("use"))return;let o=R(a),l=Q(a),u=ne(a);if((o||l||u)&&this.hasGraphQLArgument(e,t,r,s)){let c=this.extractOperationNameFromCall(e,t,r,s),g=l?"Mutation":u?"Subscription":"Query",m=c?`${g}: ${c}`:`${g}: unknown`;n.has(m)||(n.add(m),i.push(m));return}if(a==="useContext"){let f=this.extractContextName(e);if(f){let c=`\u{1F504} Context: ${f}`;n.has(c)||(n.add(c),i.push(c));}return}n.has(a)||(n.add(a),i.push(a));}hasGraphQLArgument(e,t,r,s){if(!e.arguments?.length)return false;let i=e.arguments[0],n=i?.expression||i;if(!n)return false;if(n.type==="Identifier"){let a=n.value;if(r.has(a)||s.has(a)||a.endsWith("Document")||/[A-Z][a-z]*Query$/.test(a)||/[A-Z][a-z]*Mutation$/.test(a)||/^[A-Z][A-Z0-9_]*_QUERY$/.test(a)||/^[A-Z][A-Z0-9_]*_MUTATION$/.test(a))return true}if(n.type==="TaggedTemplateExpression"){let a=this.getCalleeNameFromNode(n.tag);if(a==="gql"||a==="graphql")return true}if(n.type==="CallExpression"){let a=this.getCalleeNameFromNode(n.callee);if(a==="gql"||a==="graphql")return true}if(n.type==="TemplateLiteral"&&n.quasis?.[0]?.raw){let a=n.quasis[0].raw;if(/(?:query|mutation|subscription)\s+\w+/i.test(a))return true}if(n.type==="MemberExpression"){let a=n.property?.value;if(a&&/Query$|Mutation$|Document$/.test(a))return true}if(e.span){let a=t.slice(e.span.start,Math.min(e.span.end,e.span.start+500));if(a.includes("Document")||/\bgql\s*[`(]/.test(a)||/\bgraphql\s*[`(]/.test(a)||/query\s+\w+\s*[({]/.test(a)||/mutation\s+\w+\s*[({]/.test(a))return true}return false}getCalleeNameFromNode(e){return e?e.type==="Identifier"?e.value:e.type==="MemberExpression"&&e.property?.type==="Identifier"?e.property.value:null:null}extractOperationNameFromCall(e,t,r,s){if(e.typeArguments?.params?.length>0){let i=e.typeArguments.params[0];if(i?.type==="TsTypeReference"&&i.typeName?.type==="Identifier"){let n=i.typeName.value;return d(n)}}if(e.callee?.span&&e.span){let i=e.callee.span.end,n=Math.min(i+150,e.span.end),o=t.slice(i,n).match(/^<\s*(\w+)(?:Query|Mutation|Variables|Subscription)?[\s,>]/);if(o)return d(o[1])}if(e.arguments?.length>0){let i=e.arguments[0],n=i?.expression||i;if(!n)return null;if(n.type==="Identifier"){let a=n.value,o=s.get(a);if(o)return o;let l=r.get(a);return l||(/^(Query|Mutation|QUERY|MUTATION)$/i.test(a)?null:d(a))}if(n.type==="MemberExpression"&&n.property?.type==="Identifier")return d(n.property.value);if(n.type==="TaggedTemplateExpression"&&n.template?.quasis?.[0]?.raw){let o=n.template.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(o)return o[1]}if(n.type==="CallExpression"){let a=this.getCalleeNameFromNode(n.callee);if((a==="graphql"||a==="gql")&&n.arguments?.length>0){let o=n.arguments[0],l=o?.expression||o;if(l?.type==="TemplateLiteral"&&l.quasis?.[0]?.raw){let f=l.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(f)return f[1]}}}if(n.type==="TemplateLiteral"&&n.quasis?.[0]?.raw){let o=n.quasis[0].raw.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(o)return o[1]}}if(e.span){let i=t.slice(e.span.start,e.span.end),n=i.match(/\b([A-Z][a-zA-Z0-9]*Document)\b/);if(n)return d(n[1]);let a=i.match(/(?:query|mutation|subscription)\s+(\w+)/i);if(a)return a[1]}return null}extractContextName(e){if(e.arguments?.length>0){let t=e.arguments[0].expression;if(t?.type==="Identifier")return t.value.replace(/Context$/,"")}return null}extractHooksWithRegex(e,t,r){let s=/\b(useQuery|useMutation|useLazyQuery|useSuspenseQuery|useBackgroundQuery|useSubscription)(?:<[^>]*>)?\s*\(\s*([A-Z_][A-Za-z0-9_]*)?/gs,i;for(;(i=s.exec(e))!==null;){let o=i[1],l=i[2];if(l&&/^(Query|Mutation|QUERY|MUTATION)$/i.test(l))continue;let u=l?d(l):"unknown",c=`${o.includes("Mutation")?"Mutation":o.includes("Subscription")?"Subscription":"Query"}: ${u}`;r.has(c)||(r.add(c),t.push(c));}let n=/\b(use[A-Z][a-zA-Z0-9]*)\s*\(/g,a;for(;(a=n.exec(e))!==null;){let o=a[1];if(!["useQuery","useMutation","useLazyQuery","useSuspenseQuery","useBackgroundQuery","useSubscription"].includes(o))if(o==="useContext"){let l=e.slice(a.index).match(/useContext\s*\(\s*([A-Z][A-Za-z0-9]*)/);if(l){let f=`\u{1F504} Context: ${l[1].replace(/Context$/,"")}`;r.has(f)||(r.add(f),t.push(f));}}else r.has(o)||(r.add(o),t.push(o));}}extractStateManagement(e){let t=[];return e.includes("useState")&&t.push("useState"),e.includes("useReducer")&&t.push("useReducer"),e.includes("useContext")&&t.push("useContext"),e.includes("useQuery")&&t.push("Apollo Query"),e.includes("useMutation")&&t.push("Apollo Mutation"),e.includes("useRecoil")&&t.push("Recoil"),(e.includes("useSelector")||e.includes("useDispatch"))&&t.push("Redux"),t}buildDependencyGraph(e){let t=new Map;for(let r of e)t.set(r.name,r);for(let r of e)for(let s of r.dependencies){let i=t.get(s);i&&!i.dependents.includes(r.name)&&i.dependents.push(r.name);}}async analyzeDataFlows(e){let t=[],r=1,s=this.analyzeContextFlows(e);t.push(...s.map(a=>({...a,id:`flow-${r++}`})));let i=this.analyzeApolloFlows(e);t.push(...i.map(a=>({...a,id:`flow-${r++}`})));let n=this.analyzePropDrilling(e);return t.push(...n.map(a=>({...a,id:`flow-${r++}`}))),t}analyzeContextFlows(e){let t=[],r=e.filter(i=>i.name.includes("Provider")||i.name.includes("Context")),s=e.filter(i=>i.hooks.some(n=>n.includes("Context")));for(let i of r){let n=i.name.replace("Provider","").replace("Context","");for(let a of s){let o=a.hooks.find(l=>l.includes("Context")&&l.includes(n));(o||a.hooks.some(l=>l.includes(n)))&&t.push({name:`\u{1F504} ${n} Context`,description:`Data flows from ${i.name} to ${a.name} via Context`,source:{type:"context",name:i.name},target:{type:"component",name:a.name},via:[],operations:[o||`useContext(${n})`]});}}return t}analyzeApolloFlows(e){let t=[];for(let r of e){let s=r.hooks.filter(n=>n.includes("Query:")||n==="useQuery"||n==="useLazyQuery");for(let n of s){let a=n.includes(":")?n.split(":")[1].trim():r.name;t.push({name:`Query: ${a}`,description:`${r.name} fetches ${a} via Apollo`,source:{type:"api",name:`GraphQL: ${a}`},target:{type:"component",name:r.name},via:[{type:"cache",name:"Apollo Cache"}],operations:[n]});}let i=r.hooks.filter(n=>n.includes("Mutation:")||n==="useMutation");for(let n of i){let a=n.includes(":")?n.split(":")[1].trim():r.name;t.push({name:`Mutation: ${a}`,description:`${r.name} mutates ${a} via Apollo`,source:{type:"component",name:r.name},target:{type:"api",name:`GraphQL: ${a}`},via:[],operations:[n]});}}return t}analyzePropDrilling(e){let t=[];for(let r of e)r.props.length>5&&r.dependents.length>0&&t.push({name:`Prop Drilling through ${r.name}`,description:`${r.name} passes ${r.props.length} props to children`,source:{type:"component",name:r.name},target:{type:"component",name:r.dependents[0]},via:[],operations:["props"]});return t}};var he=class p extends A{apiCallCounter=0;constructor(e){super(e);}getName(){return "RestApiAnalyzer"}async analyze(){this.log("Starting REST API analysis...");let e=await j(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx"],{cwd:this.basePath,ignore:["**/node_modules/**","**/.next/**","**/__tests__/**","**/*.test.*","**/*.spec.*","**/*.stories.*","**/__generated__/**","**/dist/**","**/build/**"],absolute:true}),t=50,r=[];for(let s=0;s<e.length;s+=t){let i=e.slice(s,s+t),n=await S(i,async a=>{try{let o=await T.readFile(a,"utf-8"),l=y.relative(this.basePath,a),u=a.endsWith(".tsx")||a.endsWith(".jsx"),f=parseSync(o,{syntax:a.endsWith(".ts")||a.endsWith(".tsx")?"typescript":"ecmascript",tsx:u,jsx:u});return this.analyzeModule(f,o,l)}catch{return []}},10);r.push(...n.flat());}return this.log(`Found ${r.length} REST API calls`),{apiCalls:r}}analyzeModule(e,t,r){let s=[],i=t.split(`
2
- `);return this.traverseNode(e,n=>{if(n.type==="CallExpression"){let a=n,o=this.analyzeCallExpression(a,r,i);o&&s.push(o);}}),s}traverseNode(e,t){if(!(!e||typeof e!="object")){t(e);for(let r of Object.keys(e)){let s=e[r];if(Array.isArray(s))for(let i of s)this.traverseNode(i,t);else s&&typeof s=="object"&&this.traverseNode(s,t);}}}analyzeCallExpression(e,t,r){let s=e.callee;if(s.type==="Super"||s.type==="Import")return null;let i=this.getCalleeName(s);if(!i)return null;if(i==="fetch"||i==="window.fetch")return this.extractFetchCall(e,t,r);let n=i.match(/^axios\.(get|post|put|delete|patch)$/i);return n?this.extractAxiosMethodCall(e,t,r,n[1].toUpperCase()):i==="axios"?this.extractAxiosDirectCall(e,t,r):i==="useSWR"||i==="useSWRImmutable"?this.extractSwrCall(e,t,r):null}getCalleeName(e){if(e.type==="Identifier")return e.value;if(e.type==="MemberExpression"){let t=e.object,r=e.property;if(t.type==="Identifier"&&r.type==="Identifier")return `${t.value}.${r.value}`}return null}extractFetchCall(e,t,r){if(e.arguments.length===0)return null;let s=e.arguments[0],i=this.extractUrlFromExpression(s.expression);if(!i.url||!i.isPlaceholder&&!this.isApiUrl(i.url))return null;let n="GET",a=false;if(e.arguments.length>1){let l=e.arguments[1].expression;if(l.type==="ObjectExpression")for(let u of l.properties)u.type==="KeyValueProperty"&&u.key.type==="Identifier"&&(u.key.value==="method"&&u.value.type==="StringLiteral"&&(n=this.normalizeMethod(u.value.value)),(u.key.value==="credentials"||u.key.value==="headers")&&(a=true));}let o=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:n,url:i.url,callType:"fetch",filePath:t,line:o,containingFunction:"unknown",usedIn:[],requiresAuth:a,category:this.categorizeApi(i.url)}}extractAxiosMethodCall(e,t,r,s){if(e.arguments.length===0)return null;let i=e.arguments[0],n=this.extractUrlFromExpression(i.expression);if(!n.url)return null;let a=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:this.normalizeMethod(s),url:n.url,callType:"axios",filePath:t,line:a,containingFunction:"unknown",usedIn:[],requiresAuth:false,category:this.categorizeApi(n.url)}}extractAxiosDirectCall(e,t,r){if(e.arguments.length===0)return null;let s=e.arguments[0].expression;if(s.type!=="ObjectExpression")return null;let i=null,n="GET";for(let o of s.properties)o.type==="KeyValueProperty"&&o.key.type==="Identifier"&&(o.key.value==="url"&&o.value.type==="StringLiteral"&&(i=o.value.value),o.key.value==="method"&&o.value.type==="StringLiteral"&&(n=this.normalizeMethod(o.value.value)));if(!i)return null;let a=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:n,url:i,callType:"axios",filePath:t,line:a,containingFunction:"unknown",usedIn:[],requiresAuth:false,category:this.categorizeApi(i)}}extractSwrCall(e,t,r){if(e.arguments.length===0)return null;let s=e.arguments[0].expression,i=this.extractUrlFromExpression(s);if(!i.url)return null;let n=this.getLineNumber(e.span.start,r);return {id:`api-${++this.apiCallCounter}`,method:"GET",url:i.url,callType:"useSWR",filePath:t,line:n,containingFunction:"unknown",usedIn:[],requiresAuth:false,category:this.categorizeApi(i.url)}}extractUrlFromExpression(e){if(e.type==="StringLiteral")return {url:e.value,isPlaceholder:false};if(e.type==="TemplateLiteral")return e.quasis.length===1&&e.expressions.length===0?{url:e.quasis[0].raw,isPlaceholder:false}:{url:e.quasis.map(s=>s.raw).join(":param"),isPlaceholder:true};if(e.type==="Identifier")return {url:`[${e.value}]`,isPlaceholder:true};if(e.type==="MemberExpression"){let t=e.object.type==="Identifier"?e.object.value:"?",r=e.property.type==="Identifier"?e.property.value:"?";return {url:`[${t}.${r}]`,isPlaceholder:true}}if(e.type==="ConditionalExpression"){let t=this.extractUrlFromExpression(e.consequent);return t.url?t:this.extractUrlFromExpression(e.alternate)}return {url:null,isPlaceholder:false}}getLineNumber(e,t){let r=0;for(let s=0;s<t.length;s++)if(r+=t[s].length+1,r>e)return s+1;return t.length}static STATIC_FILE_EXTENSIONS=/\.(css|js|mjs|cjs|ts|tsx|jsx|png|jpg|jpeg|gif|webp|svg|ico|woff|woff2|ttf|eot|otf|mp3|mp4|webm|ogg|wav|pdf|doc|docx|xls|xlsx|ppt|pptx|zip|tar|gz|rar|html|htm|xml|txt|md|map|wasm)$/i;static NON_API_SCHEMES=/^(data:|blob:|javascript:|mailto:|tel:|file:)/;isApiUrl(e){return p.NON_API_SCHEMES.test(e)||p.STATIC_FILE_EXTENSIONS.test(e)||!e.trim()?false:!!(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("[")||e.includes("/api/")||e.includes("/v1/")||e.includes("/v2/")||e.includes("/graphql"))}static SERVICE_PATTERNS=[{pattern:/amazonaws\.com|\.s3\./i,name:"AWS"},{pattern:/googleapis\.com|google\.com\/api/i,name:"Google API"},{pattern:/graph\.facebook\.com|facebook\.com\/v\d+/i,name:"Facebook"},{pattern:/api\.twitter\.com|twitter\.com\/\d+/i,name:"Twitter/X"},{pattern:/api\.github\.com|github\.com\/api/i,name:"GitHub API"},{pattern:/stripe\.com/i,name:"Stripe"},{pattern:/paypal\.com/i,name:"PayPal"},{pattern:/slack\.com/i,name:"Slack"},{pattern:/discord\.com|discordapp\.com/i,name:"Discord"},{pattern:/twilio\.com/i,name:"Twilio"},{pattern:/sendgrid\.(com|net)/i,name:"SendGrid"},{pattern:/mailchimp\.com/i,name:"Mailchimp"},{pattern:/hubspot\.com|hsforms\.com/i,name:"HubSpot"},{pattern:/salesforce\.com/i,name:"Salesforce"},{pattern:/zendesk\.com/i,name:"Zendesk"},{pattern:/intercom\.io/i,name:"Intercom"},{pattern:/firebase(io)?\.com|firestore\.googleapis/i,name:"Firebase"},{pattern:/supabase\.(co|com|io)/i,name:"Supabase"},{pattern:/auth0\.com/i,name:"Auth0"},{pattern:/okta\.com/i,name:"Okta"},{pattern:/clerk\.(dev|com)/i,name:"Clerk"},{pattern:/cloudflare\.com|workers\.dev/i,name:"Cloudflare"},{pattern:/vercel\.com|vercel\.app/i,name:"Vercel"},{pattern:/netlify\.com|netlify\.app/i,name:"Netlify"},{pattern:/heroku\.com|herokuapp\.com/i,name:"Heroku"},{pattern:/railway\.app/i,name:"Railway"},{pattern:/render\.com/i,name:"Render"},{pattern:/digitalocean\.com/i,name:"DigitalOcean"},{pattern:/algolia\.(com|net|io)/i,name:"Algolia"},{pattern:/elastic\.co|elasticsearch/i,name:"Elasticsearch"},{pattern:/mongodb\.com|mongodb\.net/i,name:"MongoDB"},{pattern:/planetscale\.com/i,name:"PlanetScale"},{pattern:/sentry\.io/i,name:"Sentry"},{pattern:/datadog\.com/i,name:"Datadog"},{pattern:/segment\.(com|io)/i,name:"Segment"},{pattern:/mixpanel\.com/i,name:"Mixpanel"},{pattern:/amplitude\.com/i,name:"Amplitude"},{pattern:/openai\.com/i,name:"OpenAI"},{pattern:/anthropic\.com/i,name:"Anthropic"},{pattern:/cohere\.(ai|com)/i,name:"Cohere"}];categorizeApi(e){if(e.startsWith("["))return "Dynamic URL";if(e.startsWith("/"))return e.startsWith("/api/")?"Internal API":e.includes("/graphql")?"GraphQL":"Internal Route";for(let{pattern:t,name:r}of p.SERVICE_PATTERNS)if(t.test(e))return r;try{let s=new URL(e).hostname.replace(/^(api\.|www\.)/,"").split(".");if(s.length>=2){let i=s[s.length-2];return i.charAt(0).toUpperCase()+i.slice(1)+" API"}}catch{}return "External API"}normalizeMethod(e){let t=e.toUpperCase();return ["GET","POST","PUT","DELETE","PATCH"].includes(t)?t:"unknown"}};
3
- export{ue as A,fe as B,he as C,A as a,O as b,ee as c,te as d,ve as e,W as f,X as g,be as h,R as i,Q as j,ne as k,$ as l,q as m,H as n,d as o,Ae as p,v as q,M as r,V as s,U as t,P as u,re as v,Z as w,je as x,Ge as y,oe as z};
@@ -1 +0,0 @@
1
- export{b as RailsMapGenerator}from'./chunk-DSYVU23K.js';import'./chunk-H7VVRHQZ.js';