@omfalos/mokosh 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.mjs CHANGED
@@ -1,53 +1,66 @@
1
1
  #!/usr/bin/env node
2
- var Gt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});import Si from"path";import{fileURLToPath as vi}from"url";var ki=()=>vi(import.meta.url),Ci=()=>Si.dirname(ki()),f=Ci();import{StdioServerTransport as bf}from"@modelcontextprotocol/sdk/server/stdio.js";import{Server as hf}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as yf,ListToolsRequestSchema as xf}from"@modelcontextprotocol/sdk/types.js";import fn from"fs";import mn from"path";import Ut from"fs";import Sn from"path";var wi=[".config.","biome.json","tsconfig.json","package.json",".prettierrc",".eslintrc"],Ot=[];function Ve(t){Ot.push(t)}function xn(t){return[...wi,...Ot].some(e=>typeof e=="string"?t.includes(e):e instanceof RegExp?e.test(t):e(t))}var Ei=[".test.",".spec.","-test.","-spec."],jt=[];function Qe(t){jt.push(t)}function ke(){return[...Ei,...jt]}var Fi=["jest","vitest","playwright","cypress","@testing-library/"],zt=[];function Ye(t){zt.push(t)}function Wt(){return[...Fi,...zt]}var bn=.8,$t=bn;function Bt(t){$t=t}function Ht(){return $t}function Ze(){Ot.length=0,jt.length=0,zt.length=0,$t=bn}var Ti=["mokosh.config.js","mokosh.config.cjs","mokosh.config.json"];function Ce(t,{allowJs:e=!0,isExplicitPath:r=!1}={}){if(r){let n=Sn.resolve(t);return Ut.existsSync(n)?n.endsWith(".json")?vn(n):e?kn(n):{}:{}}for(let n of Ti){let s=Sn.resolve(t,n);if(Ut.existsSync(s)){if(n.endsWith(".json"))return vn(s);if(e)return kn(s)}}return{}}function vn(t){return JSON.parse(Ut.readFileSync(t,"utf-8"))}function kn(t){let e=Gt(t);return e&&typeof e=="object"&&"default"in e&&(e=e.default),typeof e=="function"?e({}):e}function Jt(t){Ze();for(let e of t.configMatchers??[])Ve(e);for(let e of t.testPatterns??[])Qe(e);for(let e of t.testLibraries??[])Ye(e);t.barrelThreshold!==void 0&&Bt(t.barrelThreshold)}function U(t){return{gitStats:t?.gitStats??!1,parallelParsing:t?.parallelParsing,pathAliases:t?.pathAliases,additionalIgnoreDirs:t?.ignoreDirs}}var oe="mokosh-cache",we="duplication-tokens.json",Kt="graph.json",qt="branch-graphs",T=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage",".pytest_cache","__pycache__",".gradle","target"],Vt=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".go",".java",".kt",".kts",".scala",".sc",".groovy",".gradle",".feature",".md",".mdx"];import Pi from"fs";import Cn from"path";function Qt(t,e){let r=Cn.resolve(t,e);try{let n=Pi.readFileSync(r,"utf-8"),s=JSON.parse(n),o=new Map;if(typeof s!="object"||s===null)return o;for(let[i,a]of Object.entries(s)){if(i==="total")continue;let c=a?.lines?.pct;if(typeof c!="number")continue;let l=Cn.relative(t,i);o.set(l,c)}return o}catch{return new Map}}var Xe={serialize(t){let e=["graph TD"],r=new Set;for(let n of t.nodes.values()){let s=`"${n.path}"`;for(let o of n.imports){if(!o.toPath)continue;let i=`"${o.toPath}"`,a=`${n.path} -> ${o.toPath}`;if(!r.has(a)){let c=o.isStyle?"-- styles -->":"-->";e.push(` ${s} ${c} ${i}`),r.add(a)}}}return e.join(`
3
- `)}};import wn from"fs";import Ni from"path";function Yt(t,e){let r=t.replace(/^\.\//,"");if(e.nodes.has(r))return r;let n=r.replace(/^dist\//,"src/").replace(/\.(js|mjs|cjs)$/,".ts");return e.nodes.has(n)?n:null}function En(t,e){if(typeof t=="string")return Yt(t,e);if(t&&typeof t=="object"){let r=t;for(let n of["import","require","default"]){let s=En(r[n],e);if(s)return s}}return null}function Di(t){if(!t)return"unknown";let e=t.trimStart();return e.startsWith("interface ")?"interface":e.startsWith("class ")?"class":e.startsWith("enum ")?"enum":e.startsWith("type ")?"type":e.startsWith("namespace ")?"namespace":e.startsWith("const ")||e.startsWith("let ")||e.startsWith("var ")||e.startsWith("readonly ")?"const":e.startsWith("(")||e.startsWith("async ")||e.startsWith("function ")||e.includes("=>")?"function":"unknown"}function Ri(t,e){let r=new Set,n=new Set,s=[...e];for(;s.length;){let o=s.shift();if(n.has(o))continue;n.add(o);let i=t.nodes.get(o);if(i){for(let a of i.exports)r.add(a.name);for(let a of i.imports){if(a.type!=="re-export"||a.isExternal||!a.toPath)continue;if(!a.symbols?.length||a.symbols.includes("*")){let l=t.nodes.get(a.toPath);if(l)for(let p of l.exports)r.add(p.name);s.push(a.toPath)}else for(let l of a.symbols)r.add(l)}}}return r}function Zt(t,e){let r=[],n=Ni.join(e,"package.json");if(wn.existsSync(n))try{let s=JSON.parse(wn.readFileSync(n,"utf8"));if(s.exports&&typeof s.exports=="object"&&!Array.isArray(s.exports))for(let o of Object.values(s.exports)){let i=En(o,t);i&&!r.includes(i)&&r.push(i)}else if(typeof s.exports=="string"){let o=Yt(s.exports,t);o&&r.push(o)}if(r.length===0)for(let o of[s.main,s.module].filter(Boolean)){let i=Yt(o,t);i&&!r.includes(i)&&r.push(i)}}catch{}if(r.length===0){for(let s of["src/index.ts","src/index.js","index.ts","index.js"])if(t.nodes.has(s)){r.push(s);break}}return r}function Ii(t,e){let r=new Set(e);for(let n of e)t.traverse(n,s=>(r.add(s.path),!0),{direction:"outgoing"});return r}function Mi(t,e,r){let n=new Map;for(let s of e){if(r.includes(s))continue;let o=t.nodes.get(s);if(!o)continue;let i=o.category==="barrel";for(let a of o.exports){let c=n.get(a.name),l=!!(a.signature||a.doc);(!c||l&&!i)&&n.set(a.name,{file:s,symbol:a})}}return n}function Li(t,e,r,n){let s=[];for(let o of t){let i=e.get(o),a=n.flatMap(u=>r.nodes.get(u)?.exports??[]).find(u=>u.name===o),c=i?.symbol??a,l=i?.file??n.find(u=>r.nodes.get(u)?.exports.some(g=>g.name===o))??n[0],p={name:o,definedIn:l,kind:Di(c?.signature)};c?.doc&&(p.doc=c.doc),c?.signature&&(p.signature=c.signature),s.push(p)}return s.sort((o,i)=>o.name.localeCompare(i.name)),s}function _i(t,e,r){let n=c=>t.nodes.get(c)?.category==="test",s=[...e].filter(c=>!r.includes(c)&&!n(c)),o=[...t.nodes.keys()].filter(c=>!e.has(c)),i=o.filter(c=>!n(c)),a=o.filter(c=>n(c));return{internalFiles:s,unreachableFromEntry:i,testFiles:a}}function Xt(t,e){if(e.length===0)throw new Error("buildApiSurface requires at least one entry point");for(let l of e)if(!t.nodes.has(l))throw new Error(`Entry point not found in graph: ${l}`);let r=Ii(t,e),n=Mi(t,r,e),s=Ri(t,e),o=Li(s,n,t,e),{internalFiles:i,unreachableFromEntry:a,testFiles:c}=_i(t,r,e);return{entryPoints:e,publicExports:o,internalFiles:i,unreachableFromEntry:a,testFiles:c}}function er(t,e){let r=null,n=[];for(let o of t.nodes.values()){o.exports.some(i=>i.name===e)&&(r=o.path);for(let i of o.callEdges??[])i.to===e&&n.push({file:o.path,callerFunction:i.from})}let s=[];if(r){let o=t.nodes.get(r);for(let i of o?.callEdges??[])i.from===e&&s.push({file:i.toFile,calleeFunction:i.to})}return{functionName:e,definedIn:r,callers:n,callees:s}}import Yf from"fs";import Xf from"path";function Fn(t){let e=[...t.nodes.entries()].sort(([n],[s])=>n.localeCompare(s)).map(([n,s])=>`${n}:${s.mtime}:${s.size}`).join("|"),r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}function tr(t){let e=new Map;for(let r of t.nodes.keys()){let n=[];t.traverse(r,s=>(s.path!==r&&n.push(s.path),!0),{direction:"incoming"}),e.set(r,n)}return{impact:e,graphHash:Fn(t)}}function rr(t,e){return t.impact.get(e)??[]}import ep from"path";import Fe from"fs";import Tn from"path";var Ee=class{constructor(e){this.nodes=e}nodes;findUnusedFiles(e){let r=new Set(this.nodes.keys());return e.filter(n=>!r.has(n))}findHighExportUsage(e){let r=[];for(let n of this.nodes.values()){if(n.maxExportUsage===void 0||n.maxExportUsage<e)continue;let s=n.imports.reduce((o,i)=>(i.exportUsageRatio??0)>(o?.exportUsageRatio??0)?i:o,null);r.push({path:n.path,maxExportUsage:n.maxExportUsage,tightestDep:s?.toPath??""})}return r.sort((n,s)=>s.maxExportUsage-n.maxExportUsage)}findCycles(){let e=[],r=new Set,n=new Set,s=[],o=i=>{r.add(i),n.add(i),s.push(i);let a=this.nodes.get(i);if(a){for(let c of a.imports)if(!(!c.toPath||c.isExternal))if(n.has(c.toPath)){let l=s.indexOf(c.toPath);e.push([...s.slice(l),c.toPath])}else r.has(c.toPath)||o(c.toPath)}n.delete(i),s.pop()};for(let i of this.nodes.keys())r.has(i)||o(i);return e}};var P=class t{constructor(e){this.nodes=e}nodes;_incomingEdgesCache=null;_callIncomingCache=null;serialize(){return{nodes:Array.from(this.nodes.values())}}static deserialize(e){let r=new Map;for(let n of e.nodes)r.set(n.path,n);return new t(r)}getIncomingEdgesMap(){if(this._incomingEdgesCache)return this._incomingEdgesCache;let e=new Map;for(let r of this.nodes.values())for(let n of r.imports)if(n.toPath){let s=e.get(n.toPath)||[];s.push(r.path),e.set(n.toPath,s)}return this._incomingEdgesCache=e,e}dfs(e,r,n,s){let o=new Set,i=n.maxDepth??1/0,a=(c,l,p)=>{if(l>i||o.has(c))return;let u=this.nodes.get(c);if(u&&(o.add(c),r(u,l,p)!==!1))for(let g of s(c))a(g,l+1,c)};a(e,0,null)}traverse(e,r,n={}){let s=n.direction??"outgoing",o=s==="incoming"?this.getIncomingEdgesMap():null;this.dfs(e,r,n,i=>s==="outgoing"?this.nodes.get(i)?.imports.map(a=>a.toPath).filter(Boolean)??[]:o?.get(i)??[])}getCallIncomingCache(){if(this._callIncomingCache)return this._callIncomingCache;let e=new Map;for(let r of this.nodes.values())for(let n of r.callEdges??[]){let s=e.get(n.toFile)??[];s.push(r.path),e.set(n.toFile,s)}return this._callIncomingCache=e,e}traverseCalls(e,r,n={}){let s=n.direction??"outgoing",o=s==="incoming"?this.getCallIncomingCache():null;this.dfs(e,r,n,i=>s==="outgoing"?this.nodes.get(i)?.callEdges?.map(a=>a.toFile)??[]:o?.get(i)??[])}getCallers(e){let r=[];return this.traverseCalls(e,n=>(n.path!==e&&r.push(n.path),!0),{direction:"incoming",maxDepth:1}),r}getCallEdgesFor(e){return this.nodes.get(e)?.callEdges??[]}getNeighbors(e){let r=this.nodes.get(e);return r?r.imports.map(n=>this.nodes.get(n.toPath)).filter(n=>n!==void 0):[]}findUnusedFiles(e){return new Ee(this.nodes).findUnusedFiles(e)}findCycles(){return new Ee(this.nodes).findCycles()}};function et(t){return Tn.join(t,oe,qt)}function Pn(t,e){return Tn.join(et(t),`${e}.json`)}function An(t,e){let r=Pn(t,e);if(!Fe.existsSync(r))return null;try{let n=Fe.readFileSync(r,"utf-8");return P.deserialize(JSON.parse(n))}catch{return null}}function Nn(t,e,r){let n=et(t);Fe.existsSync(n)||Fe.mkdirSync(n,{recursive:!0}),Fe.writeFileSync(Pn(t,e),JSON.stringify(r.serialize()))}import Ge from"fs";import F from"path";import wl from"piscina";import{execFileSync as nr}from"child_process";var tt=class{getChangedFiles(e,r){try{let s=[["diff","--name-only"],["diff","--cached","--name-only"],["ls-files","--others","--exclude-standard"],...r?[["diff","--name-only","--end-of-options",`${r}...HEAD`]]:[]].flatMap(o=>{try{return nr("git",o,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
4
- `).map(a=>a.trim()).filter(a=>a!=="")}catch{return[]}});return Array.from(new Set(s))}catch(n){return console.error("Error getting git diff:",n),[]}}},Dn="%x00%H%x09%ae%x09%at",Rn=256*1024*1024;function In(t,e){let r="",n=0;for(let s of t.split(`
5
- `)){if(s.startsWith("\0")){let[,c,l]=s.slice(1).split(" ");r=c??"",n=l?Number(l)*1e3:0;continue}if(s==="")continue;let o=s.split(" "),i=o[0];if(!i)continue;let a=i.startsWith("R")||i.startsWith("C")?o[2]:o[1];a&&e(a,r,n)}}function Mn(t){let e=new Map;try{let r=nr("git",["-C",t,"log","--since=90 days ago","--name-status","-M",`--format=${Dn}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:Rn});In(r,(n,s,o)=>{let i=e.get(n);if(i){i.commitCount90d+=1;return}e.set(n,{commitCount90d:1,lastAuthor:s||void 0,lastCommitAt:o||void 0})})}catch{return e}try{let r=nr("git",["-C",t,"log","--name-status","-M",`--format=${Dn}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:Rn});In(r,(n,s,o)=>{e.has(n)||e.set(n,{commitCount90d:0,lastAuthor:void 0,lastCommitAt:o||void 0})})}catch{}return e}import rt from"fs";import Gi from"path";import{load as Ln}from"js-yaml";var Te=["package-lock.json","yarn.lock","pnpm-lock.yaml"];function _n(t){let e=t.lastIndexOf("@");return e>0?t.substring(0,e):t}function Oi(t){return t.replace(/:$/,"").split(",").map(e=>{let r=e.trim();return r.startsWith('"')&&(r=r.slice(1)),r.endsWith('"')&&(r=r.slice(0,-1)),_n(r)}).filter(Boolean)}function ji(t,e){let r=t.startsWith("/")?t.slice(1):t,n=r.lastIndexOf("@");return n>0?{name:r.substring(0,n),version:e||r.substring(n+1)}:{name:r,version:e}}function zi(t){try{let e=Ln(t),r={dependencies:{}};for(let[n,s]of Object.entries(e))if(!(n==="__metadata"||!s?.version))for(let o of n.split(", ")){let i=_n(o);i&&(r.dependencies[i]={version:s.version,...s.dependencies!==void 0&&{dependencies:s.dependencies}})}return r}catch{return null}}function Wi(t){let e={dependencies:{}};for(let r of t.split(/\n\n+/)){let n=r.split(`
6
- `).filter(c=>c.trim().length>0&&!c.trim().startsWith("#"));if(n.length<2)continue;let s=n[0];if(!s||s.startsWith(" "))continue;let o=Oi(s);if(o.length===0)continue;let a=n.find(c=>c.trim().startsWith('version "'))?.match(/version "(.*?)"/)?.[1]??"";for(let c of o)e.dependencies[c]={version:a}}return e}function Gn(t){let e=rt.readFileSync(t,"utf-8"),r=JSON.parse(e),n={dependencies:{}};if(r.packages)for(let[s,o]of Object.entries(r.packages)){if(!s.startsWith("node_modules/"))continue;let i=s.replace("node_modules/","");i.includes("node_modules/")||(n.dependencies[i]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}else if(r.dependencies)for(let[s,o]of Object.entries(r.dependencies))n.dependencies[s]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}};return n}function On(t){let e=rt.readFileSync(t,"utf-8");if(e.includes("__metadata:")){let r=zi(e);if(r!==null)return r}return Wi(e)}function jn(t){let e=rt.readFileSync(t,"utf-8"),r={dependencies:{}};try{let n=Ln(e);if(n.packages)for(let[s,o]of Object.entries(n.packages)){let{name:i,version:a}=ji(s,o.version);i&&(r.dependencies[i]={version:a,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}if(n.dependencies)for(let[s,o]of Object.entries(n.dependencies)){if(r.dependencies[s])continue;let i=typeof o=="string"?o:o.version;r.dependencies[s]={version:i||""}}}catch{}return r}var $i={"package-lock.json":Gn,"yarn.lock":On,"pnpm-lock.yaml":jn};function sr(t){for(let e of Te){let r=Gi.join(t,e);if(rt.existsSync(r))return $i[e](r)}return null}import ot from"fs";import st from"path";function zn(t){let e=t.trim();return e.length>=2&&(e[0]==='"'||e[0]==="'")&&e[e.length-1]===e[0]?e.slice(1,-1):e}function Bi(t){let e=t.trim();if(e.startsWith('"')||e.startsWith("'")){let a=zn(e).split(":");return a.length>=3&&a[0]&&a[2]?{group:a[0],version:a[2]}:null}if(!e.startsWith("{"))return null;let r=e.match(/module\s*=\s*["']([^"']+)["']/),n=e.match(/group\s*=\s*["']([^"']+)["']/),s=r?r[1].split(":")[0]:n?.[1];if(!s)return null;let o=e.match(/version\.ref\s*=\s*["']([^"']+)["']/)??e.match(/version\s*=\s*\{\s*ref\s*=\s*["']([^"']+)["']/),i=e.match(/version\s*=\s*["']([^"']+)["']/);return{group:s,...i?.[1]!==void 0&&{version:i[1]},...o?.[1]!==void 0&&{versionRef:o[1]}}}function or(t){let e=t.split(/\r?\n/).map(o=>o.replace(/#.*$/,"").trim()),r={},n="";for(let o of e){let i=o.match(/^\[([\w.-]+)\]$/);if(i){n=i[1];continue}if(n!=="versions"||!o)continue;let a=o.indexOf("=");if(a===-1)continue;let c=o.slice(0,a).trim(),l=zn(o.slice(a+1));c&&l&&(r[c]=l)}let s={};n="";for(let o of e){let i=o.match(/^\[([\w.-]+)\]$/);if(i){n=i[1];continue}if(n!=="libraries"||!o)continue;let a=o.indexOf("=");if(a===-1)continue;let c=Bi(o.slice(a+1));if(!c)continue;let l=c.versionRef?r[c.versionRef]:c.version;l&&(s[c.group]=l)}return s}function ir(t){let e={};for(let r of t.split(/\r?\n/)){let n=r.trim();if(!n||n.startsWith("#")||n.startsWith("empty="))continue;let o=n.split("=")[0].split(":");o.length>=3&&o[0]&&o[2]&&(e[o[0]]=o[2])}return e}function ar(t){let e={},r=/["']([\w.-]+):([\w.-]+):([\w.\-+]+)["']/g;for(let s=r.exec(t);s;s=r.exec(t)){let[,o,,i]=s;o&&i&&/\d/.test(i)&&(e[o]=i)}let n=/group:\s*["']([\w.-]+)["'][^\n)]*?version:\s*["']([\w.\-+]+)["']/g;for(let s=n.exec(t);s;s=n.exec(t))s[1]&&s[2]&&/\d/.test(s[2])&&(e[s[1]]=s[2]);return e}function nt(t){let e={},r=/["']([\w.-]+)["']\s*%%?\s*["']([\w.-]+)["']\s*%\s*["']([\w.\-+]+)["']/g;for(let n=r.exec(t);n;n=r.exec(t)){let[,s,,o]=n;s&&o&&(e[s]=o)}return e}var Hi=new Set(["node_modules","build",".gradle","target",".git","dist"]),Ui=2;function Pe(t){try{return ot.existsSync(t)?ot.readFileSync(t,"utf-8"):null}catch{return null}}function cr(t){let e={},r=p=>{for(let[u,g]of Object.entries(p))!e[u]&&g&&(e[u]=g)},n=Pe(st.join(t,"gradle","libs.versions.toml"));n&&r(or(n));let s=[],o=[],i=[],a=(p,u)=>{let g;try{g=ot.readdirSync(p,{withFileTypes:!0})}catch{return}for(let d of g){let y=st.join(p,d.name);if(d.isDirectory()){u<Ui&&!d.name.startsWith(".")&&!Hi.has(d.name)&&a(y,u+1);continue}d.isFile()&&(d.name==="gradle.lockfile"?s.push(y):d.name==="build.gradle"||d.name==="build.gradle.kts"?o.push(y):d.name==="build.sbt"&&i.push(y))}};a(t,0);for(let p of s){let u=Pe(p);u&&r(ir(u))}for(let p of o){let u=Pe(p);u&&r(ar(u))}for(let p of i){let u=Pe(p);u&&r(nt(u))}try{let p=st.join(t,"project");for(let u of ot.readdirSync(p,{withFileTypes:!0}))if(u.isFile()&&u.name.endsWith(".scala")){let g=Pe(st.join(p,u.name));g&&r(nt(g))}}catch{}let c=Object.keys(e);if(c.length===0)return null;let l={};for(let p of c)l[p]={version:e[p]};return l}function Wn(t){let e=sr(t),r=cr(t);return r?{...e??{dependencies:{}},jvmDependencies:r}:e}import $n from"path";function _(t){switch($n.extname(t).toLowerCase()){case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".ts":case".tsx":return"typescript";case".css":return"css";case".scss":case".sass":return"scss";case".less":return"less";case".styl":return"stylus";case".coffee":return"coffeescript";case".ls":return"livescript";case".lua":return"lua";case".py":return"python";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":case".sc":return"scala";case".groovy":case".gradle":return"groovy";case".cpp":case".cc":case".cxx":case".c":return"unknown";case".feature":return"gherkin";case".md":case".mdx":return"markdown";default:return"unknown"}}function A(t){let e=$n.extname(t).toLowerCase();return[".css",".scss",".sass",".less",".styl"].includes(e)}import Ji from"coffeescript";function W(t){return t.startsWith("'")||t.startsWith('"')?t.slice(1,-1):t}function ie(t){let e=new Set,r=/@tag\s+([a-zA-Z0-9_-]+)/g,n=r.exec(t);for(;n!==null;)n[1]&&e.add(n[1]),n=r.exec(t);return e}function ae(t,e){let r=t.toLowerCase();return r.includes(".test.")||r.includes(".spec.")||e.has("test")?"test":"logic"}function Hn(t){if(t){if(typeof t.originalValue=="string")return t.originalValue;if(typeof t.value=="string")return W(t.value)}}function J(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function Ki(t,e){let r=Hn(e.source);return r?{fromPath:t,toPath:"",rawSpecifier:r,isStyle:A(r),type:"static"}:null}function qi(t,e){let r=e.variable?.base?.value==="require",n=Hn(e.args?.[0]?.base);return!r||!n?null:{fromPath:t,toPath:"",rawSpecifier:n,isStyle:A(n),type:"require"}}function Bn(t,e){if(e)return[{name:e}];let r=t.value;if(r?.constructor?.name==="Class"){let s=J(r.variable);return s?[{name:s}]:[]}if(r?.base?.constructor?.name==="Obj"&&Array.isArray(r.base.properties))return r.base.properties.map(s=>J(s.variable)??J(s)).filter(s=>!!s).map(s=>({name:s}));let n=J(r);return n?[{name:n}]:[]}function Vi(t){if(Array.isArray(t.specifiers))return t.specifiers.map(r=>r.identifier??r.original?.value).filter(r=>!!r).map(r=>({name:r}));let e=J(t.variable)??J(t.variable?.base);return e?[{name:e}]:[]}function Qi(t,e,r,n){let s=e.constructor?.name;if(s==="ImportDeclaration"){let o=Ki(t,e);o&&r.push(o)}else if(s==="Call"){let o=qi(t,e);o&&r.push(o)}else if(s==="Assign"){let o=J(e.variable?.base),i=e.variable?.properties?.[0]?.name?.value;o==="module"&&i==="exports"?n.push(...Bn(e,void 0)):o==="exports"&&typeof i=="string"&&n.push(...Bn(e,i))}else s==="ExportNamedDeclaration"&&e.clause?n.push(...Vi(e.clause)):s==="ExportDefaultDeclaration"&&n.push({name:"default"})}function lr(t,e,r,n){if(!(!e||typeof e!="object")){Qi(t,e,r,n);for(let s in e){if(s==="locationData")continue;let o=e[s];if(!(!o||typeof o!="object"))if(Array.isArray(o))for(let i of o)lr(t,i,r,n);else lr(t,o,r,n)}}}function Un(t,e){let r=ie(e),n=ae(t,r),s=[],o=[];try{lr(t,Ji.nodes(e),s,o)}catch{}let i=new Set,a=o.filter(c=>i.has(c.name)?!1:(i.add(c.name),!0));return{imports:s,exports:a,tags:Array.from(r).map(c=>({name:c,kind:"comment-marker"})),category:n}}import{AstBuilder as Yi,GherkinClassicTokenMatcher as Zi,Parser as Xi}from"@cucumber/gherkin";import{IdGenerator as ea}from"@cucumber/messages";var Jn=new Map;function ce(t,e){Jn.set(t,e)}function Kn(t){return Jn.get(t)}var ta=ea.uuid();function pr(t,e){let r=new Set,n=s=>{for(let o of s)r.add(o.name.startsWith("@")?o.name.slice(1):o.name)};try{let s=new Yi(ta),o=new Zi,a=new Xi(s,o).parse(e);if(a.feature){n(a.feature.tags);for(let c of a.feature.children){if(c.scenario){n(c.scenario.tags);for(let l of c.scenario.examples)n(l.tags)}if(c.rule)for(let l of c.rule.children)l.scenario&&n(l.scenario.tags)}}}catch(s){console.warn(`[GherkinParser] Failed to parse ${t}:`,s)}return{imports:[],exports:[],tags:Array.from(r).map(s=>({name:s,kind:"comment-marker"})),category:"test"}}ce("gherkin",pr);import ia from"path";import{parser as aa}from"@lezer/go";function K(t){let e=[],r=t.firstChild;for(;r;)e.push(r),r=r.nextSibling;return e}function q(t,e){let r=1;for(let n=0;n<e&&n<t.length;n++)t[n]===`
7
- `&&r++;return r}function ra(t,e){let r=1;function n(s){switch(s.type.name){case"IfStatement":case"ForStatement":r++;break;case"Case":{s.firstChild?.type.name==="case"&&r++;break}case"LogicOp":{let i=e.slice(s.from,s.to);(i==="&&"||i==="||")&&r++;break}}let o=s.firstChild;for(;o;)n(o),o=o.nextSibling}return n(t),r}function Vn(t,e,r,n){let s=r?1:1+e,o=K(t),i=r?e:e+1,a=o[1];a&&a.type.name!=="Block"&&(s+=le(a,i,!1,n));let c=o.find(p=>p.type.name==="Block");c&&(s+=le(c,i,!1,n));let l=o.findIndex(p=>p.type.name==="else");if(l>=0){let p=o[l+1];p?.type.name==="IfStatement"?s+=Vn(p,e,!0,n):p&&(s+=1+le(p,e+1,!1,n))}return s}function qn(t,e,r){let n=1+e,s=t.firstChild;for(;s;)n+=le(s,e+1,!1,r),s=s.nextSibling;return n}function na(t,e,r){let n=0,s=t.firstChild;for(;s;)n+=le(s,e,!1,r),s=s.nextSibling;return n}function sa(t,e){let r=e.slice(t.from,t.to);return r==="&&"||r==="||"}function le(t,e,r,n){let s=t.type.name;if(s==="IfStatement")return Vn(t,e,r,n);if(s==="ForStatement"||s==="SwitchStatement"||s==="SelectStatement")return qn(t,e,n);let o=s==="LogicOp"&&sa(t,n)?1:0;return e>0&&s==="FunctionLiteral"?o+qn(t,e,n):o+na(t,e,n)}function oa(t,e){return le(t,0,!1,e)}function it(t,e){return{complexity:ra(t,e),cognitiveComplexity:oa(t,e)}}function ur(t,e){let n=t.getChild("Parameters")?.getChild("Parameter"),s=n?.getChild("TypeName")??n?.getChild("PointerType")?.getChild("TypeName");return s?e.slice(s.from,s.to):void 0}function Qn(t,e){let r=[],n=t.cursor();do if(n.name==="FunctionDecl"){let s=n.node.getChild("DefName");if(s){let o=e.slice(s.from,s.to),{complexity:i,cognitiveComplexity:a}=it(n.node,e);r.push({name:o,line:q(e,n.from),complexity:i,cognitiveComplexity:a})}}else if(n.name==="MethodDecl"){let s=n.node.getChild("FieldName");if(s){let o=e.slice(s.from,s.to),i=ur(n.node,e),a=i?`${i}.${o}`:o,{complexity:c,cognitiveComplexity:l}=it(n.node,e);r.push({name:a,line:q(e,n.from),complexity:c,cognitiveComplexity:l})}}while(n.next());return r}var ca=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/,la=/^\/\/go:build\s+(.+)$/,pa=/^\/\/\s*\+build\s+(.+)$/;function Zn(t,e){let r=[],n=new Map,s=new Set,o=new Set,i=new Map,a=aa.parse(e),c=a.cursor();do switch(c.name){case"LineComment":{let x=e.slice(c.from,c.to),k=x.match(ca);k?.[1]&&s.add(k[1]);let R=x.match(la);R&&Yn(R[1],o);let D=x.match(pa);D&&Yn(D[1],o);break}case"ImportSpec":{let x=c.node.getChild("String");if(x){let R=e.slice(x.from,x.to).slice(1,-1);r.push({fromPath:t,toPath:"",rawSpecifier:R,isExternal:!0,isStyle:!1,type:"static"});let D=c.node.getChild("DefName"),H=D?e.slice(D.from,D.to):R.split("/").pop();H&&H!=="_"&&H!=="."&&i.set(H,R)}break}case"FunctionDecl":case"MethodDecl":case"TypeDecl":case"VarDecl":case"ConstDecl":{let x=c.node.getChild("DefName")??c.node.getChild("FieldName")??c.node.getChild("TypeSpec")?.getChild("DefName")??c.node.getChild("VarSpec")?.getChild("DefName")??c.node.getChild("ConstSpec")?.getChild("DefName");if(x){let k=e.slice(x.from,x.to);k!=="_"&&/^[A-Z]/.test(k)&&!n.has(k)&&n.set(k,{name:k})}break}}while(c.next());let l=r.some(x=>x.rawSpecifier==="testing"),p=ia.basename(t).endsWith("_test.go")||s.has("test")||l?"test":"logic",u=new Set([...s,...o]),{complexity:g,cognitiveComplexity:d}=it(a.topNode,e),y=Qn(a,e),v=p==="test"?[]:ua(a,e,i);return{imports:r,exports:Array.from(n.values()),tags:Array.from(u).map(x=>({name:x,kind:"comment-marker"})),category:p,rawCallEdges:v,complexity:g,cognitiveComplexity:d,...y.length>0?{functions:y}:{}}}function ua(t,e,r){let n=[];function s(i,a){if(i.type.name==="CallExpr"){let l=i.firstChild;if(l?.type.name==="SelectorExpr"){let p=l.firstChild,u=l.getChild("FieldName");if(p?.type.name==="VariableName"&&u){let g=e.slice(p.from,p.to),d=r.get(g);if(d){let y=e.slice(u.from,u.to);n.push({from:a,to:y,toSpecifier:d})}}}}let c=i.firstChild;for(;c;)s(c,a),c=c.nextSibling}let o=t.cursor();do if(o.name==="FunctionDecl"){let i=o.node.getChild("DefName"),a=o.node.getChild("Block");if(i&&a){let c=e.slice(i.from,i.to);/^[A-Z]/.test(c)&&s(a,c)}}else if(o.name==="MethodDecl"){let i=o.node.getChild("FieldName"),a=o.node.getChild("Block");if(i&&a){let c=e.slice(i.from,i.to),l=ur(o.node,e);s(a,l?`${l}.${c}`:c)}}while(o.next());return n}function Yn(t,e){for(let r of t.split(/[\s,&|!()]+/)){let n=r.trim();n&&n!=="ignore"&&e.add(n)}}var fa=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/g,ma=["org.junit","androidx.test","org.robolectric","org.mockito","org.scalatest","munit","spock.lang","io.kotest","org.spekframework"];function pe(t){let e=new Set;for(let r of t.matchAll(fa))r[1]&&e.add(r[1]);return e}function $(t){let e=t.replace(/\/\*[\s\S]*?\*\//g,r=>r.replace(/[^\n]/g," "));return e=e.replace(/\/\/[^\n]*/g,r=>" ".repeat(r.length)),e}function ue(t){let e=$(t),r=new Set;for(let s of e.matchAll(/@([A-Z]\w*)/g))s[1]&&r.add(s[1]);let n=new Set;for(let s of e.matchAll(/\b(?:class|object|interface|trait|enum)\s+([A-Za-z_]\w*)/g))s[1]&&n.add(s[1]);return{annotations:[...r],typeNames:[...n]}}function fe(t,e){return{fromPath:t,toPath:"",rawSpecifier:e,isExternal:!0,isStyle:!1,type:"static"}}function B(t,e){return{fromPath:t,toPath:"",rawSpecifier:`${e}.*`,isExternal:!0,isStyle:!1,type:"side-effect"}}function I(t,e){let r=[];for(let n of $(t).split(`
8
- `)){let s=n.trim();if(!s||s.startsWith("@")||s.startsWith("*"))continue;let o=s.match(/^package\s+(?:object\s+)?([\w.]+)/);if(o?.[1]){if(r.push(o[1]),!e)break;continue}if(!(e&&/^import\s/.test(s)))break}return r.length>0?r.join("."):null}var ga=new Set(["Configuration","SpringBootApplication","EnableAutoConfiguration"]),da=new Set(["Composable","Preview"]),ha=new Set(["RestController","Controller","Service","Repository","Component","Entity","MappedSuperclass","Embeddable"]),ya=["Activity","Fragment","ViewModel","Screen","Composable"];function G(t,e,r={}){let n=t.replace(/\\/g,"/"),s=n.split("/").pop()??"";if(s.endsWith(".gradle")||s==="build.gradle.kts"||s==="settings.gradle.kts")return"config";if(/\/src\/(test|androidTest|integrationTest|it)\//.test(n)||e.some(i=>ma.some(a=>i===a||i.startsWith(`${a}.`))))return"test";let o=r.annotations??[];return o.some(i=>ga.has(i))?"config":o.some(i=>da.has(i))||(r.typeNames??[]).some(i=>ya.some(a=>i.endsWith(a)))?"ui":(o.some(i=>ha.has(i)),"logic")}var xa=/^\s*import\s+(static\s+)?([\w.]+(?:\.\*)?)(?:\s+as\s+\w+)?\s*$/,ba=/^(?:@\w+\s+)*(?:public\s+|private\s+|protected\s+|final\s+|abstract\s+|static\s+)*(class|interface|trait|enum|def)\s+([A-Za-z_][A-Za-z0-9_]*)/;function Sa(t,e){return t?e.endsWith(".*")?e.slice(0,-2)||null:e.split(".").slice(0,-1).join(".")||null:e||null}function Xn(t,e){let r=pe(e),s=$(e).split(`
9
- `),o=[],i=new Set;for(let l of s){let p=l.match(xa);if(p?.[2]){let g=Sa(!!p[1],p[2]);g&&o.push(fe(t,g));continue}let u=l.match(ba);u?.[2]&&i.add(u[2])}let a=I(e,!1);a&&o.push(B(t,a));let c=Array.from(i,l=>({name:l}));return{imports:o,exports:c,tags:Array.from(r).map(l=>({name:l,kind:"comment-marker"})),category:G(t,o.map(l=>l.rawSpecifier),{typeNames:[...i],annotations:ue(e).annotations})}}import{parser as Fa}from"@lezer/java";var es=new Set(["ForStatement","EnhancedForStatement","WhileStatement","DoStatement"]),va=new Set(["ClassDeclaration","InterfaceDeclaration","EnumDeclaration","RecordDeclaration","AnnotationTypeDeclaration"]);function ka(t,e){let r=1;function n(s){let o=s.type.name;if(o==="IfStatement"||o==="CatchClause"||o==="TernaryExpression")r++;else if(es.has(o))r++;else if(o==="SwitchLabel")s.firstChild?.type.name==="case"&&r++;else if(o==="LogicOp"){let a=e.slice(s.from,s.to);(a==="&&"||a==="||")&&r++}let i=s.firstChild;for(;i;)n(i),i=i.nextSibling}return n(t),r}function ts(t,e,r,n){let s=r?1:1+e,o=[];for(let p=t.firstChild;p;p=p.nextSibling)o.push(p);let i=r?e:e+1,a=o[1];a&&a.type.name!=="Block"&&(s+=me(a,i,!1,n));let c=o.find(p=>p.type.name==="Block");c&&(s+=me(c,i,!1,n));let l=o.findIndex(p=>p.type.name==="else");if(l>=0){let p=o[l+1];p?.type.name==="IfStatement"?s+=ts(p,e,!0,n):p&&(s+=1+me(p,e+1,!1,n))}return s}function fr(t,e,r){let n=1+e,s=t.firstChild;for(;s;)n+=me(s,e+1,!1,r),s=s.nextSibling;return n}function Ca(t,e,r){let n=0,s=t.firstChild;for(;s;)n+=me(s,e,!1,r),s=s.nextSibling;return n}function wa(t,e){let r=e.slice(t.from,t.to);return r==="&&"||r==="||"}function me(t,e,r,n){let s=t.type.name;if(s==="IfStatement")return ts(t,e,r,n);if(es.has(s)||s==="SwitchStatement"||s==="CatchClause"||s==="TernaryExpression")return fr(t,e,n);let o=s==="LogicOp"&&wa(t,n)?1:0;return e>0&&s==="LambdaExpression"?o+fr(t,e,n):o+Ca(t,e,n)}function Ea(t,e){return me(t,0,!1,e)}function mr(t,e){return{complexity:ka(t,e),cognitiveComplexity:Ea(t,e)}}function gr(t,e){for(let r=t.parent;r;r=r.parent)if(va.has(r.type.name)){let n=r.getChild("Definition");if(n)return e.slice(n.from,n.to)}}function rs(t,e){let r=[],n=t.cursor();do if(n.name==="MethodDeclaration"||n.name==="ConstructorDeclaration"){let s=n.node.getChild("Definition");if(s){let o=e.slice(s.from,s.to),i=gr(n.node,e),a=i&&n.name==="MethodDeclaration"?`${i}.${o}`:o,{complexity:c,cognitiveComplexity:l}=mr(n.node,e);r.push({name:a,line:q(e,n.from),complexity:c,cognitiveComplexity:l})}}while(n.next());return r}var Ta=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/;function Pa(t,e){let r=t.getChild("ScopedIdentifier");if(!r)return null;let n=t.getChild("static")!=null,s=t.getChild("Asterisk")!=null,o=e.slice(r.from,r.to);return n?(s||(o=o.split(".").slice(0,-1).join(".")),o?{specifier:o,wildcard:!1}:null):s?{specifier:`${o}.*`,wildcard:!0}:{specifier:o,wildcard:!1}}function Aa(t){let e=new Map;for(let r of t){if(r.type==="side-effect")continue;let n=r.rawSpecifier;if(n.endsWith(".*"))continue;let s=n.split(".").pop();s&&e.set(s,n)}return e}function Na(t,e,r){let n=[];function s(i,a){let c=i.type.name;if(c==="MethodInvocation"){let p=i.firstChild;if(p?.type.name==="Identifier"){let u=r.get(e.slice(p.from,p.to)),g=i.getChild("MethodName");u&&g&&n.push({from:a,to:e.slice(g.from,g.to),toSpecifier:u})}}else if(c==="ObjectCreationExpression"){let p=i.getChild("TypeName");if(p){let u=r.get(e.slice(p.from,p.to));u&&n.push({from:a,to:"new",toSpecifier:u})}}let l=i.firstChild;for(;l;)s(l,a),l=l.nextSibling}let o=t.cursor();do if(o.name==="MethodDeclaration"||o.name==="ConstructorDeclaration"){let i=o.node.getChild("Definition"),a=o.node.getChild("Block")??o.node.getChild("ConstructorBody");if(i&&a){let c=e.slice(i.from,i.to),l=gr(o.node,e),p=l&&o.name==="MethodDeclaration"?`${l}.${c}`:c;s(a,p)}}while(o.next());return n}function ns(t,e){let r=[],n=new Map,s=new Set,o=new Set,i;try{i=Fa.parse(e)}catch{return{imports:[],exports:[],tags:[],category:G(t,[])}}let a=i.cursor();do switch(a.name){case"LineComment":{let y=e.slice(a.from,a.to).match(Ta);y?.[1]&&s.add(y[1]);break}case"MarkerAnnotation":case"Annotation":{let y=a.node.getChild("Identifier");y&&o.add(e.slice(y.from,y.to));break}case"ImportDeclaration":{let y=Pa(a.node,e);y&&r.push({fromPath:t,toPath:"",rawSpecifier:y.specifier,isExternal:!0,isStyle:!1,type:"static"});break}case"ClassDeclaration":case"InterfaceDeclaration":case"EnumDeclaration":case"AnnotationTypeDeclaration":{if(a.node.parent?.name==="Program"){let y=a.node.getChild("Definition");if(y){let v=e.slice(y.from,y.to);n.has(v)||n.set(v,{name:v})}}break}}while(a.next());let c=I(e,!1);c&&r.push(B(t,c));let l=G(t,r.map(y=>y.rawSpecifier),{typeNames:[...n.keys()],annotations:[...o]}),{complexity:p,cognitiveComplexity:u}=mr(i.topNode,e),g=rs(i,e),d=l==="test"?[]:Na(i,e,Aa(r));return{imports:r,exports:Array.from(n.values()),tags:Array.from(s).map(y=>({name:y,kind:"comment-marker"})),category:l,rawCallEdges:d,complexity:p,cognitiveComplexity:u,...g.length>0?{functions:g}:{}}}var Da=/^\s*import\s+([\w.]+(?:\.\*)?)(?:\s+as\s+\w+)?\s*$/,dr="(?:public\\s+|internal\\s+|private\\s+|protected\\s+|open\\s+|abstract\\s+|final\\s+|sealed\\s+|data\\s+|value\\s+|inline\\s+|noinline\\s+|crossinline\\s+|external\\s+|expect\\s+|actual\\s+|suspend\\s+|operator\\s+|infix\\s+|tailrec\\s+|const\\s+|lateinit\\s+)*",Ra=new RegExp(`^(?:@[\\w.]+(?:\\([^)]*\\))?\\s+)*${dr}(?:(?:enum|annotation)\\s+)?(class|interface|object|typealias)\\s+([A-Za-z_][A-Za-z0-9_]*)`),Ia=new RegExp(`^(?:@[\\w.]+(?:\\([^)]*\\))?\\s+)*${dr}fun\\s+(?:<[^>]*>\\s*)?(?:[A-Za-z_][\\w.]*(?:<[^>]*>)?\\.)?([A-Za-z_][A-Za-z0-9_]*)\\s*[(<]`),Ma=new RegExp(`^(?:@[\\w.]+(?:\\([^)]*\\))?\\s+)*${dr}(?:val|var)\\s+(?:<[^>]*>\\s*)?([A-Za-z_][A-Za-z0-9_]*)`);function ss(t,e){let r=pe(e),s=$(e).split(`
10
- `),o=[],i=new Set;for(let l of s){let p=l.match(Da);if(p?.[1]){o.push(fe(t,p[1]));continue}let u=l.match(Ra);if(u?.[2]){i.add(u[2]);continue}let g=l.match(Ia);if(g?.[1]){i.add(g[1]);continue}let d=l.match(Ma);d?.[1]&&i.add(d[1])}let a=I(e,!1);a&&o.push(B(t,a));let c=Array.from(i,l=>({name:l}));return{imports:o,exports:c,tags:Array.from(r).map(l=>({name:l,kind:"comment-marker"})),category:G(t,o.map(l=>l.rawSpecifier),{typeNames:[...i],annotations:ue(e).annotations})}}import La from"livescript";function V(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function _a(t){if(!t)return[];if(t.constructor?.name==="Class"){let r=V(t.title);return r?[{name:r}]:[]}if(t.constructor?.name==="Obj"&&Array.isArray(t.items))return t.items.map(r=>V(r.key)??V(r.val)).filter(r=>!!r).map(r=>({name:r}));let e=V(t);return e?[{name:e}]:[]}function Ga(t){let e=t.constructor?.name||t.type;if(e==="Assign"&&t.left?.constructor?.name==="Chain"){let r=t.left,n=V(r.head),o=r.tails?.[0]?.key?.name;if(n==="module"&&o==="exports")return _a(t.right);if(n==="exports"&&typeof o=="string")return[{name:o}];if(r.head?.verb==="out"&&typeof o=="string")return[{name:o}]}if(e==="Import"&&t.left?.verb==="out"){let r=t.right;if(r?.constructor?.name==="Obj"&&Array.isArray(r.items))return r.items.map(n=>V(n.val)??V(n.key)).filter(n=>!!n).map(n=>({name:n}))}return[]}var Oa=new Set(["first_line","first_column","last_line","last_column","line","column"]);function ja(t,e){let r=t.constructor?.name||t.type;if(r==="Import"){let n=t.right?.value;if(typeof n=="string"){let s=W(n);return{fromPath:e,toPath:"",rawSpecifier:s,isStyle:A(s),type:"static"}}}if(r==="Chain"&&t.head?.value==="require"){let n=t.tails?.[0];if(n?.constructor?.name==="Call"||n?.type==="Call"){let s=n.args?.[0]?.value;if(typeof s=="string"){let o=W(s);return{fromPath:e,toPath:"",rawSpecifier:o,isStyle:A(o),type:"require"}}}}return null}function hr(t,e,r){if(!t||typeof t!="object")return[];let n=[],s=ja(t,e);s&&n.push(s),r.push(...Ga(t));for(let o in t){if(Oa.has(o))continue;let i=t[o];if(!(!i||typeof i!="object"))if(Array.isArray(i))for(let a of i)n.push(...hr(a,e,r));else n.push(...hr(i,e,r))}return n}function os(t,e){let r=ie(e),n=ae(t,r),s=[],o=[];try{s=hr(La.ast(e),t,o)}catch{}let i=new Set,a=o.filter(c=>i.has(c.name)?!1:(i.add(c.name),!0));return{imports:s,exports:a,tags:Array.from(r).map(c=>({name:c,kind:"comment-marker"})),category:n}}import za from"luaparse";function Wa(t,e){let r=[];function n(s){if(!(!s||typeof s!="object")){if((s.type==="CallExpression"||s.type==="StringCallExpression")&&s.base?.type==="Identifier"&&s.base?.name==="require"){let o;if(s.type==="CallExpression"){let i=s.arguments?.[0];i?.type==="StringLiteral"&&(o=W(i.raw))}else if(s.type==="StringCallExpression"){let i=s.argument;i?.type==="StringLiteral"&&(o=W(i.raw))}o&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:A(o),type:"require"})}for(let o in s){if(o==="loc")continue;let i=s[o];if(i&&typeof i=="object")if(Array.isArray(i))for(let a of i)n(a);else n(i)}}}return n(t),r}function $a(t){let e=new Set;for(let r of t)r.type==="LocalStatement"&&r.variables.forEach((n,s)=>{r.init[s]?.type==="TableConstructorExpression"&&e.add(n.name)});return e}function Ba(t){let e=t[t.length-1];if(e?.type!=="ReturnStatement")return[];let r=e.arguments[0];if(r?.type!=="TableConstructorExpression")return[];let n=[];for(let s of r.fields)s.type==="TableKeyString"&&n.push({name:s.key.name});return n}function Ha(t){let e=t.body,r=$a(e),n=Ba(e);for(let o of e)if(o.type==="FunctionDeclaration")o.identifier?.type==="MemberExpression"?o.identifier.base.type==="Identifier"&&r.has(o.identifier.base.name)&&n.push({name:o.identifier.identifier.name}):o.identifier?.type==="Identifier"&&!o.isLocal&&n.push({name:o.identifier.name});else if(o.type==="AssignmentStatement")for(let i of o.variables)i.type==="MemberExpression"&&i.base.type==="Identifier"&&r.has(i.base.name)&&n.push({name:i.identifier.name});let s=new Set;return n.filter(o=>s.has(o.name)?!1:(s.add(o.name),!0))}function is(t,e){let r=ie(e),n=ae(t,r),s=[],o=[];try{let i=za.parse(e);s=Wa(i,t),o=Ha(i)}catch{}return{imports:s,exports:o,tags:Array.from(r).map(i=>({name:i,kind:"comment-marker"})),category:n}}var Ua=["http://","https://","mailto:","//"],Ja="ts|tsx|js|jsx|mjs|cjs|py|go|lua|css|scss|less|styl|coffee|ls|feature|md|mdx|json",Ka=new RegExp(`(?:\\.{1,2}/)?[\\w.-]+(?:/[\\w.-]+)*\\.(?:${Ja})\\b`,"g"),as;async function qa(){return as??=(async()=>{let{unified:t}=await import("unified"),e=(await import("remark-parse")).default;return t().use(e)})(),as}function Va(t){let e=t.trim();return e.length===0||e.startsWith("#")||Ua.some(r=>e.startsWith(r))}function Qa(t,e){let r=t.match(Ka);return r?r.map(n=>({fromPath:e,toPath:"",rawSpecifier:n,isStyle:!1,type:"static"})):[]}function cs(t,e,r){if(t.type==="link"&&typeof t.url=="string"&&!Va(t.url)&&r.push({fromPath:e,toPath:"",rawSpecifier:t.url,isStyle:!1,type:"static"}),(t.type==="code"||t.type==="inlineCode")&&typeof t.value=="string"&&r.push(...Qa(t.value,e)),Array.isArray(t.children))for(let n of t.children)cs(n,e,r)}async function ls(t,e){let n=(await qa()).parse(e),s=[];cs(n,t,s);let o=new Set;return{imports:s.filter(a=>o.has(a.rawSpecifier)?!1:(o.add(a.rawSpecifier),!0)),exports:[],tags:[],category:"other"}}import rc from"path";import{parser as nc}from"@lezer/python";function Ya(t){let e=1;function r(n){switch(n.type.name){case"IfStatement":{e+=K(n).filter(o=>o.type.name==="if"||o.type.name==="elif").length;break}case"TryStatement":{e+=K(n).filter(o=>o.type.name==="except").length;break}case"ForStatement":case"WhileStatement":case"ConditionalExpression":e++;break;case"and":case"or":e++;break}let s=n.firstChild;for(;s;)r(s),s=s.nextSibling}return r(t),e}function Za(t,e){let r=0,n=K(t),s=0,o=0;for(;o<n.length;){let i=n[o];if(i?.type.name==="if"||i?.type.name==="elif"){let a=s>0;r+=a?1:1+e;let c=a?e:e+1,l=n[o+1],p=n[o+2];l&&(r+=O(l,c)),p&&(r+=O(p,c)),s++,o+=3}else if(i?.type.name==="else"){r+=1;let a=n[o+1];a&&(r+=O(a,e+1)),o+=2}else o++}return r}function Xa(t,e){let r=0,n=K(t),s=0;for(;s<n.length;){let o=n[s];if(o?.type.name==="except"){for(r+=1+e,s++;s<n.length&&n[s]?.type.name!=="Body";)r+=O(n[s],e),s++;s<n.length&&(r+=O(n[s],e),s++)}else o?.type.name==="Body"&&(r+=O(o,e)),s++}return r}function ps(t,e){let r=1+e,n=t.firstChild;for(;n;)r+=O(n,e+1),n=n.nextSibling;return r}function ec(t,e){let r=0,n=t.firstChild;for(;n;)r+=O(n,e),n=n.nextSibling;return r}function O(t,e){let r=t.type.name;switch(r){case"IfStatement":return Za(t,e);case"TryStatement":return Xa(t,e);case"ForStatement":case"WhileStatement":return ps(t,e);default:{let n=r==="ConditionalExpression"||r==="and"||r==="or"?1:0;return e>0&&(r==="FunctionDefinition"||r==="LambdaExpression")?n+ps(t,e):n+ec(t,e)}}}function tc(t){return O(t,0)}function yr(t){return{complexity:Ya(t),cognitiveComplexity:tc(t)}}function us(t,e){let r=[];function n(i,a){let{complexity:c,cognitiveComplexity:l}=yr(i);r.push({name:a,line:q(e,i.from),complexity:c,cognitiveComplexity:l})}function s(i){let a=i.firstChild;for(;a;)o(a),a=a.nextSibling}function o(i){if(i.type.name==="ClassDefinition"){let a=i.getChild("VariableName"),c=a?e.slice(a.from,a.to):void 0,l=i.getChild("Body");if(l){let p=l.firstChild;for(;p;){if(p.type.name==="FunctionDefinition"){let u=p.getChild("VariableName"),g=u?e.slice(u.from,u.to):void 0;g&&n(p,c?`${c}.${g}`:g),s(p)}else o(p);p=p.nextSibling}}return}if(i.type.name==="FunctionDefinition"){let a=i.getChild("VariableName");a&&n(i,e.slice(a.from,a.to)),s(i);return}s(i)}return o(t.topNode),r}var sc=new Set(["pytest","unittest","nose","hypothesis"]);function fs(t,e){let r=[],n=[],s=new Set,o=rc.basename(t).toLowerCase(),i=nc.parse(e),a=i.cursor();do switch(a.name){case"Comment":{let d=e.slice(a.from,a.to).match(/#\s*@tag\s+([a-zA-Z0-9_-]+)/);d?.[1]&&s.add(d[1]);break}case"ImportStatement":{for(let d of oc(a.node,e,t))r.push(d);break}case"FunctionDefinition":case"ClassDefinition":{let d=a.node.parent;if(d?.name==="Script"||d?.name==="DecoratedStatement"&&d.parent?.name==="Script"){let v=a.node.getChild("VariableName");v&&n.push({name:e.slice(v.from,v.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let d=a.node.firstChild;d?.name==="VariableName"&&n.push({name:e.slice(d.from,d.to)})}break}}while(a.next());let c=uc(o,r,s);c==="test"&&s.add("test");let{complexity:l,cognitiveComplexity:p}=yr(i.topNode),u=us(i,e),g=c==="test"?[]:pc(i,e);return{imports:r,exports:n,tags:Array.from(s).map(d=>({name:d,kind:"comment-marker"})),category:c,rawCallEdges:g,complexity:l,cognitiveComplexity:p,...u.length>0?{functions:u}:{}}}function oc(t,e,r){let n=t.firstChild;return n?n.name==="from"?ic(t,e,r):ac(t,e,r):[]}function ic(t,e,r){let n=t.firstChild;if(!n)return[];let s=n.nextSibling;for(;s&&s.name!=="import";)s=s.nextSibling;if(!s)return[];let o=e.slice(n.to,s.from).trim(),i=cc(s.nextSibling,e);if(!i.length)return[];let a=0;for(;a<o.length&&o[a]===".";)a++;let c=o.slice(a);if(a===0)return[Ae(r,o,i,!0)];let l=a===1?"./":"../".repeat(a-1);return c?[Ae(r,l+c.replace(/\./g,"/"),i,!1)]:i[0]==="*"?[Ae(r,l.slice(0,-1),["*"],!1)]:i.map(p=>Ae(r,l+p,[p],!1))}function ac(t,e,r){let n=[],s=t.firstChild?.nextSibling??null;for(;s;){if(s.name==="VariableName"){let o=e.slice(s.from,s.to);for(;s.nextSibling?.name==="."&&s.nextSibling.nextSibling?.name==="VariableName";)s=s.nextSibling.nextSibling,o+=`.${e.slice(s.from,s.to)}`;s.nextSibling?.name==="as"&&(s=s.nextSibling.nextSibling??s.nextSibling),n.push(Ae(r,o,["*"],!0))}s=s.nextSibling}return n}function cc(t,e){let r=[],n=t;for(;n;)n.name==="*"?r.push("*"):n.name==="VariableName"&&(r.push(e.slice(n.from,n.to)),n.nextSibling?.name==="as"&&(n=n.nextSibling.nextSibling??n.nextSibling)),n=n.nextSibling;return r}function lc(t,e){let r=new Map,n=t.cursor();do{if(n.name!=="ImportStatement")continue;let o=n.node.firstChild;if(o?.type.name!=="from")continue;let i=o.nextSibling;for(;i&&i.type.name!=="import";)i=i.nextSibling;if(!i)continue;let a=e.slice(o.to,i.from).trim(),c=0;for(;c<a.length&&a[c]===".";)c++;let l=a.slice(c),p=c<=1?"./":"../".repeat(c-1),u=i.nextSibling;for(;u;){if(u.type.name==="VariableName"){let g=e.slice(u.from,u.to),d=g;if(u.nextSibling?.type.name==="as"){let v=u.nextSibling.nextSibling;v?.type.name==="VariableName"&&(d=e.slice(v.from,v.to),u=v)}let y=c===0?a:l?p+l.replace(/\./g,"/"):p+g;r.set(d,y)}u=u.nextSibling}}while(n.next());return r}function pc(t,e){let r=lc(t,e),n=[];function s(a,c){if(a.type.name==="CallExpression"&&a.firstChild?.type.name==="VariableName"){let p=a.firstChild,u=e.slice(p.from,p.to),g=r.get(u);g&&n.push({from:c,to:u,toSpecifier:g})}let l=a.firstChild;for(;l;)s(l,c),l=l.nextSibling}function o(a){let c=a.firstChild;for(;c;)i(c),c=c.nextSibling}function i(a){if(a.type.name==="ClassDefinition"){let c=a.getChild("VariableName"),l=c?e.slice(c.from,c.to):void 0,p=a.getChild("Body");if(p){let u=p.firstChild;for(;u;){if(u.type.name==="FunctionDefinition"){let g=u.getChild("VariableName"),d=g?e.slice(g.from,g.to):void 0;d&&s(u,l?`${l}.${d}`:d)}else i(u);u=u.nextSibling}}return}if(a.type.name==="FunctionDefinition"){let c=a.getChild("VariableName");c&&s(a,e.slice(c.from,c.to));return}o(a)}return i(t.topNode),n}function Ae(t,e,r,n){return{fromPath:t,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:n,type:"static",symbols:r.length>0?r:void 0}}function uc(t,e,r){return t.startsWith("test_")||t.endsWith("_test.py")?"test":t==="conftest.py"||t==="setup.py"?"config":r.has("test")||e.some(n=>sc.has(n.rawSpecifier))?"test":"logic"}var fc=/^\s*import\s+(.+?)\s*$/,mc=/^(?:@\w+\s+)*(?:private\s+|protected\s+|final\s+|sealed\s+|abstract\s+|implicit\s+|case\s+)*(class|trait|object|type|enum)\s+([A-Za-z_$][A-Za-z0-9_$]*)/;function gc(t,e){let r=e.split("=>")[0]?.trim();return r?r==="_"||r==="*"||r==="given"?`${t}.*`:`${t}.${r}`:null}function dc(t){let e=t.indexOf("{");if(e!==-1){let n=t.indexOf("}",e),s=t.slice(0,e).trim().replace(/\.$/,""),o=t.slice(e+1,n===-1?void 0:n);return s?o.split(",").map(i=>gc(s,i.trim())).filter(i=>i!=null):[]}let r=[];for(let n of t.split(",")){let s=n.trim().replace(/\s+as\s+\w+$/,"");if(s)if(s.endsWith("._")||s.endsWith(".*")||s.endsWith(".given")){let o=s.replace(/\.(_|\*|given)$/,"");o&&r.push(`${o}.*`)}else r.push(s)}return r}function ms(t,e){let r=pe(e),s=$(e).split(`
11
- `),o=[],i=new Set;for(let l of s){let p=l.match(fc);if(p?.[1]){for(let g of dc(p[1]))o.push(fe(t,g));continue}let u=l.match(mc);u?.[2]&&i.add(u[2])}let a=I(e,!0);a&&o.push(B(t,a));let c=Array.from(i,l=>({name:l}));return{imports:o,exports:c,tags:Array.from(r).map(l=>({name:l,kind:"comment-marker"})),category:G(t,o.map(l=>l.rawSpecifier),{typeNames:[...i],annotations:ue(e).annotations})}}import ys from"path";import h from"typescript";import S from"typescript";function hc(t){let e=1;function r(n){switch(n.kind){case S.SyntaxKind.IfStatement:case S.SyntaxKind.ConditionalExpression:case S.SyntaxKind.ForStatement:case S.SyntaxKind.ForInStatement:case S.SyntaxKind.ForOfStatement:case S.SyntaxKind.WhileStatement:case S.SyntaxKind.DoStatement:case S.SyntaxKind.CatchClause:case S.SyntaxKind.CaseClause:e++;break;case S.SyntaxKind.BinaryExpression:{let s=n.operatorToken.kind;(s===S.SyntaxKind.AmpersandAmpersandToken||s===S.SyntaxKind.BarBarToken||s===S.SyntaxKind.QuestionQuestionToken)&&e++;break}}S.forEachChild(n,r)}return r(t),e}function ds(t,e,r){let n=r?1:1+e,s=r?e:e+1;return n+=Q(t.expression,s,!1),n+=Q(t.thenStatement,s,!1),t.elseStatement&&(S.isIfStatement(t.elseStatement)?n+=ds(t.elseStatement,e,!0):n+=1+Q(t.elseStatement,e+1,!1)),n}function gs(t,e){let r=1+e;return S.forEachChild(t,n=>{r+=Q(n,e+1,!1)}),r}function yc(t,e){let r=1+e;return S.forEachChild(t,n=>{r+=Q(n,e,!1)}),r}function xc(t,e){let r=0;return S.forEachChild(t,n=>{r+=Q(n,e,!1)}),r}function bc(t){let e=t.operatorToken.kind;return e===S.SyntaxKind.AmpersandAmpersandToken||e===S.SyntaxKind.BarBarToken||e===S.SyntaxKind.QuestionQuestionToken}function Q(t,e,r){if(S.isIfStatement(t))return ds(t,e,r);if(S.isForStatement(t)||S.isForInStatement(t)||S.isForOfStatement(t)||S.isWhileStatement(t)||S.isDoStatement(t)||S.isSwitchStatement(t))return gs(t,e);if(S.isCatchClause(t))return yc(t,e);let n=0;return S.isConditionalExpression(t)&&(n+=1),S.isBinaryExpression(t)&&bc(t)&&(n+=1),e>0&&(S.isFunctionDeclaration(t)||S.isFunctionExpression(t)||S.isArrowFunction(t))?n+gs(t,e):n+xc(t,e)}function Sc(t){return Q(t,0,!1)}function xr(t){return{complexity:hc(t),cognitiveComplexity:Sc(t)}}import C from"typescript";var br=new Set(["test","describe","it"]);function hs(t,e){vc(t,e),Cc(t,e),wc(t,e),Ec(t,e)}function vc(t,e){if((C.isFunctionDeclaration(t)||C.isVariableDeclaration(t))&&t.name&&C.isIdentifier(t.name)&&kc(t)){let r;if(C.isFunctionDeclaration(t))r="function";else{let n=t.initializer;r=n&&(C.isArrowFunction(n)||C.isFunctionExpression(n))?"function":"variable"}e.tags.add({name:t.name.text,kind:r})}}function kc(t){if(C.isFunctionDeclaration(t))return C.isSourceFile(t.parent);let e=t.parent?.parent;return!!e&&C.isSourceFile(e.parent)}function Cc(t,e){if(!C.isStringLiteral(t))return;let r=t.text.match(/@[\w-]+/g);if(r)for(let n of r)e.tags.add({name:n.substring(1),kind:"comment-marker"})}function wc(t,e){if(!C.isSourceFile(t))return;let r=/@tag\s+([a-zA-Z0-9_-]+)/g,n=t.getFullText(),s=r.exec(n);for(;s!==null;)s[1]&&e.tags.add({name:s[1],kind:"comment-marker"}),s=r.exec(n)}function Ec(t,e){if(C.isCallExpression(t)&&Fc(t.expression))for(let r of t.arguments)C.isObjectLiteralExpression(r)&&Tc(r,e)}function Fc(t){return C.isIdentifier(t)?br.has(t.text):!!(C.isPropertyAccessExpression(t)&&(br.has(t.name.text)||C.isIdentifier(t.expression)&&br.has(t.expression.text)))}function Tc(t,e){for(let r of t.properties){if(!C.isPropertyAssignment(r)||!C.isIdentifier(r.name)||r.name.text!=="tags"&&r.name.text!=="tag")continue;let{initializer:n}=r,s=C.isArrayLiteralExpression(n)?n.elements.filter(C.isStringLiteral):r.name.text==="tag"&&C.isStringLiteral(n)?[n]:[];for(let o of s)e.tags.add({name:o.text.replace(/^@/,""),kind:"comment-marker"})}}function Sr(t,e,r){let n=[],s=new Map,o=new Set,i=h.createSourceFile(t,e,h.ScriptTarget.Latest,!0,r==="typescript"?h.ScriptKind.TSX:h.ScriptKind.JSX),a={filePath:t,imports:n,exports:s,tags:o,rawCallEdges:[],sourceFile:i,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},c=v=>{Dc(v,a),h.forEachChild(v,c)};c(i);let l=$c(t,a);(l==="test"||l==="barrel")&&o.add({name:l,kind:"comment-marker"}),l!=="test"&&Bc(a,i);let p=i.statements[0],u=p?bs(p):void 0,{complexity:g,cognitiveComplexity:d}=xr(i),y=Pc(i);return{imports:n,exports:Array.from(s.values()),tags:Array.from(o),category:l,rawCallEdges:a.rawCallEdges??[],complexity:g,cognitiveComplexity:d,...y.length>0?{functions:y}:{},...u!==void 0?{description:u}:{}}}function Pc(t){let e=[],r=(s,o)=>{let{complexity:i,cognitiveComplexity:a}=xr(o),c=t.getLineAndCharacterOfPosition(o.getStart(t)).line+1;e.push({name:s,line:c,complexity:i,cognitiveComplexity:a})},n=(s,o)=>{if(h.isFunctionDeclaration(s)&&s.name&&s.body?r(s.name.text,s):h.isVariableDeclaration(s)&&h.isIdentifier(s.name)&&s.initializer&&(h.isArrowFunction(s.initializer)||h.isFunctionExpression(s.initializer))?r(s.name.text,s.initializer):o&&h.isMethodDeclaration(s)&&h.isIdentifier(s.name)&&s.body?r(`${o}.${s.name.text}`,s):o&&h.isConstructorDeclaration(s)&&s.body?r(`${o}.constructor`,s):o&&h.isGetAccessorDeclaration(s)&&h.isIdentifier(s.name)&&s.body?r(`${o}.get ${s.name.text}`,s):o&&h.isSetAccessorDeclaration(s)&&h.isIdentifier(s.name)&&s.body&&r(`${o}.set ${s.name.text}`,s),h.isClassDeclaration(s)&&s.name){let i=s.name.text;h.forEachChild(s,a=>n(a,i));return}h.forEachChild(s,i=>n(i,o))};return n(t,void 0),e}function xs(t,e,r,n){let s={name:t},o=bs(r);o!==void 0&&(s.doc=o);let i=Ac(e);i!==void 0&&(s.flags=i);let a=Nc(e,n);return a!==void 0&&(s.signature=a),s}function bs(t){let e=h.getJSDocCommentsAndTags(t);for(let r of e)if(h.isJSDoc(r)&&r.comment)return h.getTextOfJSDocComment(r.comment)||void 0}function Ac(t){let e=new Set(["deprecated","internal","public","alpha","beta"]),r=h.getJSDocTags(t).map(n=>n.tagName.text).filter(n=>e.has(n));return r.length>0?r:void 0}function Nc(t,e){let r=h.createPrinter({removeComments:!0}),n=s=>r.printNode(h.EmitHint.Unspecified,s,e);if(h.isFunctionDeclaration(t)||h.isMethodDeclaration(t)){let s=t.parameters.map(n).join(", "),o=t.type?n(t.type):"void";return`${t.typeParameters?`<${t.typeParameters.map(a=>a.name.text).join(", ")}>`:""}(${s}) => ${o}`}if(h.isVariableDeclaration(t)){if(t.type)return n(t.type);if(t.initializer&&(h.isArrowFunction(t.initializer)||h.isFunctionExpression(t.initializer))){let s=t.initializer,o=s.parameters.map(n).join(", "),i=s.type?n(s.type):"unknown";return`(${o}) => ${i}`}return}if(h.isClassDeclaration(t)&&t.name)return`class ${t.name.text}`;if(h.isInterfaceDeclaration(t))return`interface ${t.name.text}`;if(h.isTypeAliasDeclaration(t))return n(t.type);if(h.isEnumDeclaration(t))return`enum ${t.name.text}`}function Dc(t,e){Rc(t,e),Ic(t,e),Lc(t,e),_c(t,e),Wc(t,e),hs(t,e)}function Rc(t,e){if(!h.isSourceFile(t))return;let r=t.statements.filter(n=>!h.isEmptyStatement(n));e.totalStatements=r.length,e.exportStatements=r.filter(n=>h.isExportDeclaration(n)||h.isExportAssignment(n)||vr(n)).length}function Ic(t,e){if(h.isJsxElement(t)||h.isJsxSelfClosingElement(t)||h.isJsxFragment(t)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(h.isFunctionDeclaration(t)||h.isMethodDeclaration(t)||h.isArrowFunction(t)||h.isClassDeclaration(t)||h.isVariableStatement(t)||h.isEnumDeclaration(t)){e.hasTypesOnly=!1;return}h.isExportDeclaration(t)&&!Mc(t)&&(e.hasTypesOnly=!1)}function Mc(t){return t.isTypeOnly?!0:!t.exportClause||!h.isNamedExports(t.exportClause)?!1:t.exportClause.elements.every(e=>e.isTypeOnly)}function Lc(t,e){if(!h.isImportDeclaration(t)||!t.moduleSpecifier||!h.isStringLiteral(t.moduleSpecifier))return;let r=[];if(t.importClause&&(t.importClause.name&&r.push("default"),t.importClause.namedBindings))if(h.isNamedImports(t.importClause.namedBindings))for(let s of t.importClause.namedBindings.elements)r.push(s.name.text);else h.isNamespaceImport(t.importClause.namedBindings)&&r.push("*");let n=r.length>0?"static":"side-effect";e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.moduleSpecifier.text,isStyle:A(t.moduleSpecifier.text),type:n,symbols:r.length>0?r:void 0})}function _c(t,e){h.isExportDeclaration(t)?Gc(t,e):h.isExportAssignment(t)?e.exports.set("default",{name:"default"}):vr(t)&&zc(t,e)}function Gc(t,e){if(t.moduleSpecifier&&h.isStringLiteral(t.moduleSpecifier))Oc(t,t.moduleSpecifier.text,e);else if(t.exportClause&&h.isNamedExports(t.exportClause))for(let r of t.exportClause.elements){let n=r.name.text;e.exports.set(n,{name:n})}}function Oc(t,e,r){let n=jc(t),s={fromPath:r.filePath,toPath:"",rawSpecifier:e,isStyle:A(e),type:"re-export"};n.length>0&&(s.symbols=n),r.imports.push(s)}function jc(t){return t.exportClause?h.isNamedExports(t.exportClause)?t.exportClause.elements.map(e=>e.name.text):[]:["*"]}function zc(t,e){if((h.isFunctionDeclaration(t)||h.isClassDeclaration(t)||h.isInterfaceDeclaration(t)||h.isTypeAliasDeclaration(t)||h.isEnumDeclaration(t))&&t.name){let n=t.name.text;e.exports.set(n,xs(n,t,t,e.sourceFile));return}if(h.isVariableStatement(t)){for(let n of t.declarationList.declarations)if(h.isIdentifier(n.name)){let s=n.name.text;e.exports.set(s,xs(s,n,t,e.sourceFile))}}}function Wc(t,e){if(!h.isCallExpression(t))return;let r=t.arguments[0];!r||!h.isStringLiteral(r)||(t.expression.kind===h.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:A(r.text),type:"dynamic"}):h.isIdentifier(t.expression)&&t.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:A(r.text),type:"require"}))}function $c(t,e){let r=ys.basename(t).toLowerCase(),n=ys.extname(t).toLowerCase();return ke().some(o=>r.includes(o))?"test":xn(r)?"config":e.imports.some(o=>Wt().some(i=>o.rawSpecifier.includes(i)))?"test":n===".tsx"||n===".jsx"||e.hasUI?"ui":e.hasTypesOnly&&e.totalStatements>0?"type-only":e.totalStatements>0&&e.exportStatements/e.totalStatements>Ht()?"barrel":"logic"}function vr(t){return h.canHaveModifiers(t)&&h.getModifiers(t)?.some(e=>e.kind===h.SyntaxKind.ExportKeyword)===!0}function Bc(t,e){let r=t.rawCallEdges??[];t.rawCallEdges=r;let n=new Map;for(let s of e.statements){if(!h.isImportDeclaration(s)||!h.isStringLiteral(s.moduleSpecifier))continue;let o=s.moduleSpecifier.text,i=s.importClause;if(i&&(i.name&&n.set(i.name.text,o),i.namedBindings&&h.isNamedImports(i.namedBindings)))for(let a of i.namedBindings.elements)n.set(a.name.text,o)}if(n.size!==0)for(let s of e.statements){let o=Uc(s);if(o){let i=Jc(s);i&&at(i,o,n,r);continue}h.isClassDeclaration(s)&&s.name&&Hc(s,s.name.text,n,r)}}function Hc(t,e,r,n){for(let s of t.members)h.isMethodDeclaration(s)&&s.body&&h.isIdentifier(s.name)?at(s.body,`${e}.${s.name.text}`,r,n):h.isConstructorDeclaration(s)&&s.body&&at(s.body,`${e}.constructor`,r,n)}function Uc(t){if(vr(t)){if(h.isFunctionDeclaration(t)&&t.name)return t.name.text;if(h.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(h.isIdentifier(e.name)&&e.initializer&&(h.isArrowFunction(e.initializer)||h.isFunctionExpression(e.initializer)))return e.name.text}}}function Jc(t){if(h.isFunctionDeclaration(t))return t.body;if(h.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(e.initializer&&(h.isArrowFunction(e.initializer)||h.isFunctionExpression(e.initializer)))return e.initializer}}function at(t,e,r,n){if(h.isCallExpression(t)&&h.isIdentifier(t.expression)){let s=t.expression.text,o=r.get(s);o&&!n.some(i=>i.from===e&&i.to===s&&i.toSpecifier===o)&&n.push({from:e,to:s,toSpecifier:o})}h.forEachChild(t,s=>at(s,e,r,n))}function ct(t,e){if(e.length===0)return"ui";let r=!1;return t.walk(n=>{if(n.type==="rule")return r=!0,!1}),r?"ui":"barrel"}import vs from"postcss";import*as Kc from"postcss-less";var qc=Kc,ks=new Set(["reference","inline"]);function Ss(t){return t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||t.startsWith("data:")}function Vc(t){let e=t.trim();return e.length>0&&!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("//")&&!e.startsWith("data:")&&!e.startsWith("#")}function Qc(t,e){let r=t.match(/^\(([^)]+)\)\s+['"]([^'"]+)['"]/);if(r){let o=r[1]?.trim()??"",i=r[2]??"";if(!i)return null;let a=ks.has(o)?"side-effect":"static";return{fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a,...Ss(i)?{isExternal:!0}:{}}}let n=t.match(/^url\(['"]?([^'")]+)['"]?\)/),s=n?n[1]?.trim()??"":t.match(/^['"]([^'"]+)['"]/)?.[1]??"";return s?{fromPath:e,toPath:"",rawSpecifier:s,isStyle:!0,type:"static",...Ss(s)?{isExternal:!0}:{}}:null}function Yc(t,e){let r=[],n=/url\(['"]?([^'")]+)['"]?\)/g,s=n.exec(t);for(;s!==null;){let o=s[1]?.trim()??"";Vc(o)&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"static"}),s=n.exec(t)}return r}function Cs(t,e){let r=[];return t.walk(n=>{if(n.type==="atrule"&&n.name==="import"){let s=Qc(n.params,e);s&&r.push(s)}n.type==="decl"&&r.push(...Yc(n.value,e))}),r}function Zc(t){return t.replace(/(?<!:)\/\/.*/g,"")}function Xc(t,e){let r=[],n=/@import\s+(?:\(([^)]+)\)\s+)?['"]([^'"]+)['"]/g,s=n.exec(t);for(;s!==null;){let o=s[1]?.trim()??"",i=s[2]??"";if(i){let a=ks.has(o)?"side-effect":"static";r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a})}s=n.exec(t)}return r}function lt(t,e){let r=vs.parse(Zc(t));return{imports:Cs(r,e),root:r}}function el(t){let e=[],r=[];for(let n of t.nodes??[]){if(n.type!=="atrule")continue;let{value:s}=n;if(s===void 0)continue;let o=n.name;o&&(e.push({name:o}),r.push({name:o,kind:"variable"}))}return{exports:e,tags:r}}function pt(t,e){try{let r=qc.parse(t),{exports:n,tags:s}=el(r);return{imports:Cs(r,e),root:r,exports:n,tags:s}}catch{return{imports:Xc(t,e),root:vs.parse(""),exports:[],tags:[]}}}import{parse as tl}from"postcss-scss";function ws(t){return t.startsWith("_")||t.startsWith("-")}function rl(t){return!!(t.startsWith("sass:")||t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||!t.startsWith(".")&&!t.startsWith("/")&&!t.startsWith("_"))}function nl(t){let e=t.match(/^['"]([^'"]+)['"]/);if(!e?.[1])return{specifier:""};let r=e[1],s=t.match(/\bas\s+(\S+)/)?.[1];return s!==void 0?{specifier:r,alias:s}:{specifier:r}}function sl(t){let e=[],r=[];for(let n of t.nodes??[]){if(n.type==="decl"&&n.prop.startsWith("$")){let s=n.prop.slice(1);if(!s||ws(s))continue;e.push({name:s}),r.push({name:s,kind:"variable"});continue}if(n.type==="atrule"&&(n.name==="mixin"||n.name==="function")){let o=n.params.match(/^([\w-]+)/)?.[1];if(!o||ws(o))continue;let i=n.params.trim();e.push(i.includes("(")?{name:o,signature:i}:{name:o}),r.push({name:o,kind:"function"})}}return{exports:e,tags:r}}function ut(t,e){let r=tl(t),n=[];r.walk(i=>{if(i.type!=="atrule")return;let{name:a,params:c}=i;if(a!=="import"&&a!=="use"&&a!=="forward")return;let{specifier:l,alias:p}=nl(c);if(!l)return;let u={fromPath:e,toPath:"",rawSpecifier:l,isStyle:!0,type:a==="forward"?"re-export":"static",...rl(l)?{isExternal:!0}:{}};p&&(u.symbols=[p]),n.push(u)});let{exports:s,tags:o}=sl(r);return{imports:n,root:r,exports:s,tags:o}}function Es(t,e){let r=[],n=/@require\s+['"]([^'"]+)['"]/g,s=n.exec(t);for(;s!==null;){let i=s[1];i&&r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"require"}),s=n.exec(t)}let o=/(?<!@)(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g;for(s=o.exec(t);s!==null;){let i=s[1];i&&r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"static"}),s=o.exec(t)}return r}function Fs(t,e){if(e.length===0)return"ui";try{let r=Gt("stylus");return new r.Parser(t).parse().nodes.some(o=>o.constructor.name!=="Import")?"ui":"barrel"}catch{return t.replace(/^\s*@?(?:require|import)\b.*/gm,"").trim().length>0?"ui":"barrel"}}function Ne(t,e){let r=_(t);if(r==="stylus"){let o=Es(e,t);return{imports:o,exports:[],tags:[],category:Fs(e,o)}}if(r==="scss"){let{imports:o,root:i,exports:a,tags:c}=ut(e,t);return{imports:o,exports:a,tags:c,category:ct(i,o)}}if(r==="less"){let{imports:o,root:i,exports:a,tags:c}=pt(e,t);return{imports:o,exports:a,tags:c,category:ct(i,o)}}let{imports:n,root:s}=lt(e,t);return{imports:n,exports:[],tags:[],category:ct(s,n)}}for(let[t,e]of[["javascript",(r,n)=>Sr(r,n,"javascript")],["typescript",(r,n)=>Sr(r,n,"typescript")],["css",Ne],["scss",Ne],["less",Ne],["stylus",Ne],["coffeescript",Un],["livescript",os],["lua",is],["python",fs],["go",Zn],["java",ns],["kotlin",ss],["scala",ms],["groovy",Xn],["gherkin",pr],["markdown",ls]])ce(t,e);async function Ts(t,e){let r=_(t),n=Kn(r);return n?n(t,e):{imports:[],exports:[],tags:[],category:"other"}}import Ps from"path";function ol(t,e){let r=e.get(t.path);r!==void 0&&(t.coveragePct=r)}function Ns(t,e){for(let r of t)if(r.isExternal){let n=r.rawSpecifier.startsWith("@")?r.rawSpecifier.split("/").slice(0,2).join("/"):r.rawSpecifier.split("/")[0];n&&!e.some(s=>s.name===n)&&e.push({name:n,kind:"library"})}}function il(t,e,r){if(e.isExternal||!e.toPath)return;let n=r.get(e.toPath);n&&(n.category!=="logic"&&n.category!=="barrel"||(n.testedBy??=[],n.testedBy.includes(t.path)||n.testedBy.push(t.path)))}function al(t,e){if(t.type==="markdown")for(let r of t.imports){if(r.isExternal||!r.toPath)continue;let n=e.get(r.toPath);!n||n===t||(n.documentedBy??=[],n.documentedBy.includes(t.path)||n.documentedBy.push(t.path),n.category==="logic"&&(n.lastCommitAt??0)>(t.lastCommitAt??0)&&(t.staleFor??=[],t.staleFor.includes(n.path)||t.staleFor.push(n.path)))}}function As(t){return Math.round(t*1e4)/1e4}function cl(t,e){let r=[];for(let n of t.imports){if(n.isExternal||!n.toPath)continue;let s=e.get(n.toPath);if(!s||s.exports.length===0)continue;let o;if(n.symbols===void 0){if(n.type==="side-effect")continue;o=1}else n.symbols.includes("*")?o=1:o=n.symbols.length/s.exports.length;n.exportUsageRatio=As(Math.min(1,o)),r.push(n.exportUsageRatio)}r.length>0&&(t.avgExportUsage=As(r.reduce((n,s)=>n+s,0)/r.length),t.maxExportUsage=Math.max(...r))}function kr(t,e,r){e&&(t.some(n=>n.name===e&&n.kind===r)||t.push({name:e,kind:r}))}function ll(t,e){let r=e.toPath,n=Ps.basename(r,Ps.extname(r)).replace(/\.(test|spec)$/,"");kr(t.tags,n,"import")}function pl(t,e){if(!(!e.symbols||e.symbols.includes("*")))for(let r of e.symbols)kr(t.tags,r,"import")}function ul(t,e,r){let n=r.get(e.toPath);if(!(!n||n.category==="test"))for(let s of n.tags)s.kind==="comment-marker"&&kr(t.tags,s.name,"comment-marker")}function fl(t,e,r){!e.toPath||e.isExternal||(ll(t,e),pl(t,e),ul(t,e,r))}function Ds(t,e){for(let r of t.values())delete r.testedBy,delete r.documentedBy,delete r.staleFor,r.category==="test"&&(r.tags=r.tags.filter(n=>n.kind!=="import"));for(let r of t.values()){if(cl(r,t),e.size>0&&ol(r,e),r.category==="test")for(let n of r.imports)il(r,n,t),fl(r,n,t);al(r,t)}}var Rs=new Set(["java","kotlin","scala","groovy"]),Is=new Set(["typescript","javascript","python","go","java","kotlin","scala","groovy","scss","less","lua","coffeescript"]),Ms=new Set(["typescript","javascript","python"]),ft=new Set(["typescript","javascript","go","python","java"]);function Cr(t){let e=new Map;for(let r of t.nodes.values())e.set(r.type,(e.get(r.type)??0)+1);return[...e.entries()].map(([r,n])=>({type:r,fileCount:n,exportsTracked:Is.has(r),importSymbolsTracked:Ms.has(r),callEdgesTracked:ft.has(r)})).sort((r,n)=>n.fileCount-r.fileCount)}import dt from"fs";import j from"path";import Gs from"fs";import ge from"path";var De=class{extensions=[".go"];goModCache=new Map;resolve(e,r,n,s){let{mod:o,replaces:i}=this.readGoMod(n);if(!o)return null;let a=this.applyReplace(r,i,n);if(a!==void 0)return _s(a);if(r!==o&&!r.startsWith(`${o}/`))return null;let c=r.slice(o.length).replace(/^\//,"");return c?_s(ge.join(n,c)):null}readGoMod(e){let r=this.goModCache.get(e);if(r!==void 0)return r;let n={mod:null,replaces:new Map};try{let s=Gs.readFileSync(ge.join(e,"go.mod"),"utf-8"),o=ml(s,e);return this.goModCache.set(e,o),o}catch{return this.goModCache.set(e,n),n}}applyReplace(e,r,n){for(let[s,o]of r){if(e===s)return o;if(e.startsWith(`${s}/`)){let i=e.slice(s.length+1);return ge.join(o,i)}}}};function ml(t,e){let r=t.split(`
12
- `),n=null,s=new Map,o=!1;for(let i of r){let a=i.trim();if(a.startsWith("module ")){n=a.slice(7).trim();continue}if(/^replace\s*\(/.test(a)){o=!0;continue}if(o&&a===")"){o=!1;continue}if(o&&a.includes("=>")){Ls(a,e,s);continue}!o&&/^replace\s+/.test(a)&&a.includes("=>")&&Ls(a.replace(/^replace\s+/,""),e,s)}return{mod:n,replaces:s}}function Ls(t,e,r){let[n,s]=t.split("=>").map(a=>a.trim());if(!n||!s)return;let o=n.split(/\s+/)[0];if(!s.startsWith(".")&&!s.startsWith("/"))return;let i=ge.isAbsolute(s)?s:ge.resolve(e,s);r.set(o,i)}function _s(t){let e;try{e=Gs.readdirSync(t,{withFileTypes:!0})}catch{return null}let r=e.filter(n=>n.isFile()&&n.name.endsWith(".go")&&!n.name.endsWith("_test.go")).map(n=>({path:ge.join(t,n.name),isExternal:!1})).sort((n,s)=>n.path.localeCompare(s.path));return r.length>0?r:null}import mt from"fs";import gt from"path";var gl=new Set([".java",".kt",".kts",".scala",".sc",".groovy"]),dl=12,Os=4096,Re=class{extensions=[".java",".kt",".kts",".scala",".sc",".groovy",".gradle"];indexCache=new Map;resolve(e,r,n,s){let o=this.getIndex(n);if(o.size===0)return null;let i=r.endsWith(".*"),a=(i?r.slice(0,-2):r).split(".").filter(Boolean);if(a.length===0)return null;if(i)return wr(o.get(a.join(".")));for(let c=a.length-1;c>=1;c--){let l=o.get(a.slice(0,c).join("."));if(!l)continue;let p=a[c],u=l.filter(g=>xl(g)===p);if(u.length>0)return wr(u);if(c===a.length-1)return wr(l)}return null}getIndex(e){let r=this.indexCache.get(e);if(r)return r;let n=hl(e);return this.indexCache.set(e,n),n}};function hl(t){let e=new Map,r=new Set(T),n=(s,o)=>{if(o>dl)return;let i;try{i=mt.readdirSync(s,{withFileTypes:!0})}catch{return}for(let a of i){let c=gt.join(s,a.name);if(a.isDirectory()){!a.name.startsWith(".")&&!r.has(a.name)&&n(c,o+1);continue}if(!a.isFile())continue;let l=gt.extname(a.name);if(!gl.has(l))continue;let p=yl(c,l===".scala"||l===".sc");if(!p)continue;let u=e.get(p);u?u.push(c):e.set(p,[c])}};n(t,0);for(let s of e.values())s.sort();return e}function yl(t,e){let r;try{let n=mt.openSync(t,"r");try{let s=Buffer.alloc(Os),o=mt.readSync(n,s,0,Os,0);r=s.toString("utf8",0,o)}finally{mt.closeSync(n)}}catch{return null}return I(r,e)}function wr(t){return!t||t.length===0?null:t.map(e=>({path:e,isExternal:!1}))}function xl(t){return gt.basename(t,gt.extname(t))}import bl from"fs";import Er from"path";var Ie=class{extensions=[".lua"];resolve(e,r,n,s){let o=r.replace(/\./g,Er.sep),i=[n,Er.join(n,"lib")];for(let a of i){if(!bl.existsSync(a))continue;let c=s(Er.join(a,"_dummy.lua"),o);if(c)return[c]}return null}};import Sl from"path";var vl=new Set(T),Me=class{extensions=[".md",".mdx"];resolve(e,r,n,s){let o=r.replace(/^\.\//,"").split("/")[0];if(o&&vl.has(o))return null;let i=s(Sl.join(n,"_dummy"),`./${r}`);return i?[i]:null}};import kl from"fs";import Fr from"path";var Le=class{extensions=[".py"];resolve(e,r,n,s){let o=r.replace(/\./g,Fr.sep),i=Fr.join(n,`${o}.py`);if(js(i))return[{path:i,isExternal:!1}];let a=Fr.join(n,o,"__init__.py");return js(a)?[{path:a,isExternal:!1}]:null}};function js(t){try{return kl.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}import zs from"path";var Cl=["~","http://","https://","//","data:","sass:"],_e=class{extensions=[".css",".scss",".sass",".less",".styl"];resolve(e,r,n,s){if(Cl.some(p=>r.startsWith(p)))return null;let o=s(e,r);if(o)return[o];let i=zs.dirname(r),a=zs.basename(r),c=i==="."?`_${a}`:`${i}/_${a}`,l=s(e,c);return l?[l]:null}};var z=class{constructor(e,r={}){this.rootDir=e;this.workspaceMap=r.workspaceMap??new Map,this.tsconfigSearchPaths=r.tsconfigSearchPaths??[e],this.pathAliases=r.pathAliases,this.langResolvers=r.langResolvers??[new Le,new Ie,new De,new Re,new _e,new Me]}rootDir;workspaceMap;tsconfigSearchPaths;pathAliases;langResolvers;resolutionCache=new Map;langBucketFor(e){for(let r=0;r<this.langResolvers.length;r++)if(this.langResolvers[r]?.extensions.some(n=>e.endsWith(n)))return String(r);return"none"}cacheKey(e,r){return`${j.dirname(e)}\0${this.langBucketFor(e)}\0${r}`}resolveAll(e,r){let n=this.cacheKey(e,r),s=this.resolutionCache.get(n);if(s!==void 0)return s??[];let o=this.resolveAllUncached(e,r);return this.resolutionCache.set(n,o.length>0?o:null),o}resolveAllUncached(e,r){let n=this.resolvePathAlias(r);if(n)return[n];if(r.startsWith(".")||r.startsWith("/")){let i=this.resolveLocalPath(e,r);return i?[i]:[]}let s=(i,a)=>this.resolveLocalPath(i,a);for(let i of this.langResolvers)if(i.extensions.some(a=>e.endsWith(a))){let a=i.resolve(e,r,this.rootDir,s);if(a)return a}let o=this.resolveWorkspaceImport(r);return o?[o]:[{path:r,isExternal:!0}]}resolve(e,r){return this.resolveAll(e,r)[0]??null}resolveLocalPath(e,r){let n=j.dirname(e),s=r.startsWith("/")?r:j.resolve(n,r),o=!s.startsWith(this.rootDir),i=["",".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".feature",".md",".mdx"],a=s.match(/\.(js|mjs|cjs)$/);if(a){let c=s.slice(0,-a[0].length);for(let l of[".ts",".tsx"]){let p=this.tryExtensions(c,l,o);if(p)return p}}for(let c of i){let l=this.tryExtensions(s,c,o);if(l)return l}return o?{path:s,isExternal:!0}:null}tryExtensions(e,r,n){let s=e+r;if(this.isFile(s))return{path:s,isExternal:n};let o=j.join(e,`index${r}`);if(this.isFile(o))return{path:o,isExternal:n};if(r===".py"){let i=j.join(e,"__init__.py");if(this.isFile(i))return{path:i,isExternal:n}}return null}isFile(e){try{return dt.statSync(e,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}resolvePathAlias(e){if(this.pathAliases)for(let r in this.pathAliases){let n=this.matchAliasPattern(r,e),s=this.pathAliases[r];if(n&&s){let o=this.tryAliasSubstitutions(s,n[1]||"");if(o)return o}}for(let r of this.tsconfigSearchPaths){let n=j.join(r,"tsconfig.json");if(dt.existsSync(n))try{let o=JSON.parse(dt.readFileSync(n,"utf-8")).compilerOptions?.paths;if(!o)continue;for(let i in o){let a=this.matchAliasPattern(i,e);if(a){let c=this.tryAliasSubstitutions(o[i],a[1]||"",r);if(c)return c}}}catch{}}return null}aliasRegexCache=new Map;matchAliasPattern(e,r){let n=this.aliasRegexCache.get(e);if(!n){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\*","(.*)");n=new RegExp(`^${s}$`),this.aliasRegexCache.set(e,n)}return r.match(n)}tryAliasSubstitutions(e,r,n=this.rootDir){let s=["",".ts",".tsx",".js",".jsx",".coffee",".ls",".lua",".feature"];for(let o of e){let i=o.replace("*",r),a=j.resolve(n,i);for(let c of s){let l=this.tryExtensions(a,c,!1);if(l)return l}}return null}resolveWorkspaceImport(e){if(this.workspaceMap.size===0)return null;for(let[r,n]of this.workspaceMap){if(e!==r&&!e.startsWith(`${r}/`))continue;let s=e.slice(r.length),o={path:"",isExternal:!1,isWorkspace:!0,workspacePackage:r};if(!s){for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"]){let c=j.join(n,a);try{if(dt.statSync(c,{throwIfNoEntry:!1})?.isFile())return{...o,path:c}}catch{}}return{...o,path:n}}let i=this.resolveLocalPath(j.join(n,"_dummy"),s.slice(1));return i?{...o,path:i.path}:null}return null}};var El=["tests","test","__tests__","specs","spec"],Fl=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage",".pytest_cache","__pycache__"],Tl=600;function Pl(){return(process.env.MOKOSH_IGNORE_DIRS??"").split(",").map(t=>t.trim()).filter(Boolean)}function Al(t,e){if(t.length===0)return e;let r=t.map(i=>F.dirname(i).split(F.sep)),n=r[0]??[];for(let i of r.slice(1)){let a=0;for(;a<n.length&&a<i.length&&n[a]===i[a];)a++;n=n.slice(0,a)}let s=n.join(F.sep)||F.sep,o=F.relative(e,s);return o.startsWith("..")||F.isAbsolute(o)?e:s}var Y=class{constructor(e,r=null,n,s,o=!1,i=new Map,a=!0,c=[]){this.rootDir=e;this.enableGitStats=o;this.coverageMap=i;this.parallelParsing=a;this.previousGraph=r,this.walkIgnoreDirs=new Set([...Fl,...c,...Pl()]),this.resolver=n||new z(e),this.lockFile=Wn(e),s&&(this.progressCallback=s)}rootDir;enableGitStats;coverageMap;parallelParsing;graph={nodes:new Map};visited=new Set;queue=[];previousGraph=null;resolver;lockFile=null;progressCallback;pool=null;gitStatsMap=null;walkIgnoreDirs;async build(e){let r=e.map(n=>F.isAbsolute(n)?n:F.resolve(this.rootDir,n));await this.initPool(),this.enableGitStats&&(this.gitStatsMap=Mn(this.rootDir));try{for(let n of r)this.enqueue(n);return await this.drain(),await this.processTestFiles(Al(r,this.rootDir)),await this.processDocFiles(),this.progressCallback&&this.visited.size>=100&&process.stderr.write(`
2
+ var Zn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});import $c from"path";import{fileURLToPath as zc}from"url";var Zs=()=>zc(import.meta.url),Bc=()=>$c.dirname(Zs()),g=Bc(),d=Zs();import{spawnSync as Qd}from"child_process";import jc from"fs";import Yd from"path";import Xd from"v8";import{StdioServerTransport as Zd}from"@modelcontextprotocol/sdk/server/stdio.js";import{Server as Hd}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Jd,ListToolsRequestSchema as Vd}from"@modelcontextprotocol/sdk/types.js";import Md from"crypto";import Ks from"fs";import Q from"path";import Ad from"crypto";import le from"fs";import _e from"path";var me="mokosh-cache",lt="duplication-tokens.json",qn="duplication-result.json",er="graph.json",tr="workspace-graph.json",nr="workspace",pt="manifest.json";var rr="branch-graphs",j=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage",".pytest_cache","__pycache__",".gradle","target"],sr=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".go",".java",".kt",".kts",".scala",".sc",".groovy",".gradle",".feature",".md",".mdx"];import hr from"fs";import ri from"path";var Uc=[".config.","biome.json","tsconfig.json","package.json",".prettierrc",".eslintrc"],ir=[];function Ot(t){ir.push(t)}function qs(t){return[...Uc,...ir].some(e=>typeof e=="string"?t.includes(e):e instanceof RegExp?e.test(t):e(t))}var Kc=[".test.",".spec.","-test.","-spec."],or=[];function jt(t){or.push(t)}function ut(){return[...Kc,...or]}var Hc=["jest","vitest","playwright","cypress","@testing-library/"],ar=[];function Wt(t){ar.push(t)}function cr(){return[...Hc,...ar]}var ei=.8,lr=ei;function pr(t){lr=t}function ur(){return lr}function $t(){ir.length=0,or.length=0,ar.length=0,lr=ei}var zt=["comment-marker","import"],ti=new Set(["test","barrel"]),ni=/^[a-zA-Z][a-zA-Z0-9_-]{1,}$/,Bt=new Set(["index","main","common","shared","types","type","constants","const","config","util","utils","helper","helpers","mock","mocks","fixture","fixtures","setup","spec","test","tests","args","props","options","opts","context","ctx","handler","handlers","callback","cb","fn","impl","run","get","set","use","name","value","data","item","result","node","org","linux","darwin","windows","freebsd","openbsd","netbsd","dragonfly","solaris","android","ios","js","wasm","wasip1","plan9","aix","illumos","amd64","arm","arm64","ppc64","ppc64le","mips","mips64","riscv64","s390x","loong64","cgo","gc","gccgo","unix"]),fr=new Set(Bt);function mr(t){let e=new Set(Bt);for(let n of t?.blocklist??[])e.add(n.toLowerCase());for(let n of t?.allowlist??[])e.delete(n.toLowerCase());fr=e}function gr(){fr=new Set(Bt)}function Ut(t){if(!ni.test(t))return!1;let e=t.toLowerCase();return!ti.has(e)&&!fr.has(e)}function Ce(t){return zt.includes(t.kind)&&Ut(t.name)}function dr(t){let e=new Set,n=[];for(let r of t)!Ce(r)||e.has(r.name)||(e.add(r.name),n.push(r.name));return n}var Jc=["mokosh.config.js","mokosh.config.cjs","mokosh.config.json"];function ft(t,{allowJs:e=!0,isExplicitPath:n=!1}={}){if(n){let r=ri.resolve(t);return hr.existsSync(r)?r.endsWith(".json")?si(r):e?ii(r):{}:{}}for(let r of Jc){let s=ri.resolve(t,r);if(hr.existsSync(s)){if(r.endsWith(".json"))return si(s);if(e)return ii(s)}}return{}}function si(t){return JSON.parse(hr.readFileSync(t,"utf-8"))}function ii(t){let e=Zn(t);return e&&typeof e=="object"&&"default"in e&&(e=e.default),typeof e=="function"?e({}):e}function yr(t){$t(),gr(),mr(t.tags);for(let e of t.configMatchers??[])Ot(e);for(let e of t.testPatterns??[])jt(e);for(let e of t.testLibraries??[])Wt(e);t.barrelThreshold!==void 0&&pr(t.barrelThreshold)}function ge(t){return{gitStats:t?.gitStats??!1,parallelParsing:t?.parallelParsing,pathAliases:t?.pathAliases,additionalIgnoreDirs:t?.ignoreDirs}}import Vc from"fs";import oi from"path";function xr(t,e){let n=oi.resolve(t,e);try{let r=Vc.readFileSync(n,"utf-8"),s=JSON.parse(r),i=new Map;if(typeof s!="object"||s===null)return i;for(let[o,a]of Object.entries(s)){if(o==="total")continue;let c=a?.lines?.pct;if(typeof c!="number")continue;let l=oi.relative(t,o);i.set(l,c)}return i}catch{return new Map}}var Kt={serialize(t){let e=["graph TD"],n=new Set;for(let r of t.nodes.values()){let s=`"${r.path}"`;for(let i of r.imports){if(!i.toPath)continue;let o=`"${i.toPath}"`,a=`${r.path} -> ${i.toPath}`;if(!n.has(a)){let c=i.isStyle?"-- styles -->":"-->";e.push(` ${s} ${c} ${o}`),n.add(a)}}}return e.join(`
3
+ `)}};var Oe=class{constructor(e){this.nodes=e}nodes;findUnusedFiles(e){let n=new Set(this.nodes.keys());return e.filter(r=>!n.has(r))}findHighExportUsage(e){let n=[];for(let r of this.nodes.values()){if(r.maxExportUsage===void 0||r.maxExportUsage<e)continue;let s=r.imports.reduce((i,o)=>(o.exportUsageRatio??0)>(i?.exportUsageRatio??0)?o:i,null);n.push({path:r.path,maxExportUsage:r.maxExportUsage,tightestDep:s?.toPath??""})}return n.sort((r,s)=>s.maxExportUsage-r.maxExportUsage)}traversableTargets(e,n){let r=this.nodes.get(e);if(!r)return[];let s=new Set;for(let i of r.imports)!i.toPath||i.isExternal||i.isSamePackage&&!n.has("samePackage")||i.isDocReference&&!n.has("docReference")||s.add(i.toPath);return[...s]}findCycles(e={}){let n=new Set(e.includeKinds??[]),r=[],s=new Set,i=new Set,o=[],a=c=>{s.add(c),i.add(c),o.push(c);for(let l of this.traversableTargets(c,n))if(i.has(l)){let p=o.indexOf(l);r.push([...o.slice(p),l])}else s.has(l)||a(l);i.delete(c),o.pop()};for(let c of this.nodes.keys())s.has(c)||a(c);return e.expandComponents?r:this.collapseByComponent(r,n)}collapseByComponent(e,n){if(e.length<=1)return e;let r=this.componentIds(n),s=new Map,i=new Map;for(let[o,a]of e.entries()){let c=r.get(a[0]);if(c===void 0)continue;i.has(c)||i.set(c,o);let l=s.get(c);(l===void 0||Yc(a,l))&&s.set(c,a)}return[...s.entries()].sort(([o],[a])=>i.get(o)-i.get(a)).map(([,o])=>o)}componentIds(e){let n=new Map,r=new Map,s=new Set,i=[],o=new Map,a=0,c=0;for(let l of this.nodes.keys()){if(n.has(l))continue;let p=[{node:l,targets:this.traversableTargets(l,e),next:0}];for(n.set(l,a),r.set(l,a),a++,i.push(l),s.add(l);p.length>0;){let u=p[p.length-1];if(u.next<u.targets.length){let f=u.targets[u.next++];n.has(f)?s.has(f)&&r.set(u.node,Math.min(r.get(u.node),n.get(f))):(n.set(f,a),r.set(f,a),a++,i.push(f),s.add(f),p.push({node:f,targets:this.traversableTargets(f,e),next:0}))}else{if(r.get(u.node)===n.get(u.node)){let m=[],h;do h=i.pop(),s.delete(h),m.push(h);while(h!==u.node);if(m.length>1){for(let b of m)o.set(b,c);c++}}p.pop();let f=p[p.length-1];f&&r.set(f.node,Math.min(r.get(f.node),r.get(u.node)))}}}return o}};function Yc(t,e){return t.length!==e.length?t.length<e.length:t.join("\0")<e.join("\0")}import ai from"fs";import Xc from"path";var Zc=25,qc=30,el=50;function br(t,e={}){let n=e.maxExports??qc,r=e.maxUnreachable??el,s={};for(let c of t.publicExports)s[c.kind]=(s[c.kind]??0)+1;let i=t.publicExports.slice(0,n).map(c=>({name:c.name,kind:c.kind})),o=t.unreachableFromEntry.slice(0,r),a={entryPoints:t.entryPoints.slice(0,Zc),entryPointCount:t.entryPoints.length,publicExportCount:t.publicExports.length,publicExports:i,byKind:s,internalFileCount:t.internalFiles.length,unreachableFromEntryCount:t.unreachableFromEntry.length,unreachableFromEntry:o,testFileCount:t.testFiles.length,hint:`Pass view:"exports" for all ${t.publicExports.length} exports with docs, signatures and definedIn; view:"full" for that plus the internalFiles / testFiles path lists.`};return t.entryPoints.length>a.entryPoints.length&&(a.entryPointsTruncated=!0),i.length<t.publicExports.length&&(a.publicExportsTruncated=!0),o.length<t.unreachableFromEntry.length&&(a.unreachableFromEntryTruncated=!0),a}function Ht(t,e){let n=t.replace(/^\.\//,"");if(e.nodes.has(n))return n;let r=n.replace(/^dist\//,"src/").replace(/\.(js|mjs|cjs)$/,".ts");return e.nodes.has(r)?r:null}function ci(t,e){if(typeof t=="string")return Ht(t,e);if(t&&typeof t=="object"){let n=t;for(let r of["import","require","default"]){let s=ci(n[r],e);if(s)return s}}return null}function tl(t){if(!t)return"unknown";let e=t.trimStart();return e.startsWith("interface ")?"interface":e.startsWith("class ")?"class":e.startsWith("enum ")?"enum":e.startsWith("type ")?"type":e.startsWith("namespace ")?"namespace":e.startsWith("const ")||e.startsWith("let ")||e.startsWith("var ")||e.startsWith("readonly ")?"const":e.startsWith("(")||e.startsWith("async ")||e.startsWith("function ")||e.includes("=>")?"function":"unknown"}function nl(t,e){let n=new Set,r=new Set,s=[...e];for(;s.length;){let i=s.shift();if(r.has(i))continue;r.add(i);let o=t.nodes.get(i);if(o){for(let a of o.exports)n.add(a.name);for(let a of o.imports){if(a.type!=="re-export"||a.isExternal||!a.toPath)continue;if(!a.symbols?.length||a.symbols.includes("*")){let l=t.nodes.get(a.toPath);if(l)for(let p of l.exports)n.add(p.name);s.push(a.toPath)}else for(let l of a.symbols)n.add(l)}}}return n}function kr(t,e){let n=[],r=Xc.join(e,"package.json");if(ai.existsSync(r))try{let s=JSON.parse(ai.readFileSync(r,"utf8"));if(s.exports&&typeof s.exports=="object"&&!Array.isArray(s.exports))for(let o of Object.values(s.exports)){let a=ci(o,t);a&&!n.includes(a)&&n.push(a)}else if(typeof s.exports=="string"){let o=Ht(s.exports,t);o&&n.push(o)}let i=typeof s.bin=="string"?[s.bin]:s.bin&&typeof s.bin=="object"&&!Array.isArray(s.bin)?Object.values(s.bin).filter(o=>typeof o=="string"):[];for(let o of i){let a=Ht(o,t);a&&!n.includes(a)&&n.push(a)}if(n.length===0)for(let o of[s.main,s.module].filter(Boolean)){let a=Ht(o,t);a&&!n.includes(a)&&n.push(a)}}catch{}if(n.length===0){for(let s of["src/index.ts","src/index.js","index.ts","index.js"])if(t.nodes.has(s)){n.push(s);break}}return n.length===0?il(t):n}var rl=new Set(["java","kotlin","scala","groovy"]);function sl(t){return t.endsWith("_test.go")||/(^|\/)(test|tests|__tests__|testdata)\//.test(t)||/[._-](test|spec)\.[^/]+$/.test(t)}function il(t){let e=[...t.nodes.values()],n=o=>e.filter(a=>o(a.type)&&a.category!=="test"&&!sl(a.path)),r=n(o=>o==="python");if(r.length>0){let o=r.filter(a=>a.path.replace(/^.*\//,"")==="__init__.py");if(o.length>0){let a=Math.min(...o.map(c=>c.path.split("/").length));return o.filter(c=>c.path.split("/").length===a).map(c=>c.path).sort()}return r.map(a=>a.path).sort()}let s=n(o=>o==="go");if(s.length>0)return s.map(o=>o.path).sort();let i=n(o=>rl.has(o));return i.length>0?i.map(o=>o.path).sort():[]}function ol(t,e){let n=new Set(e);for(let r of e)t.traverse(r,s=>(n.add(s.path),!0),{direction:"outgoing"});return n}function al(t,e,n){let r=new Map;for(let s of e){if(n.includes(s))continue;let i=t.nodes.get(s);if(!i)continue;let o=i.category==="barrel";for(let a of i.exports){let c=r.get(a.name),l=!!(a.signature||a.doc);(!c||l&&!o)&&r.set(a.name,{file:s,symbol:a})}}return r}function cl(t,e,n,r){let s=[];for(let i of t){let o=e.get(i),a=r.flatMap(u=>n.nodes.get(u)?.exports??[]).find(u=>u.name===i),c=o?.symbol??a,l=o?.file??r.find(u=>n.nodes.get(u)?.exports.some(f=>f.name===i))??r[0],p={name:i,definedIn:l,kind:tl(c?.signature)};c?.doc&&(p.doc=c.doc),c?.signature&&(p.signature=c.signature),s.push(p)}return s.sort((i,o)=>i.name.localeCompare(o.name)),s}function ll(t,e,n){let r=c=>t.nodes.get(c)?.category==="test",s=[...e].filter(c=>!n.includes(c)&&!r(c)),i=[...t.nodes.keys()].filter(c=>!e.has(c)),o=i.filter(c=>!r(c)),a=i.filter(c=>r(c));return{internalFiles:s,unreachableFromEntry:o,testFiles:a}}function Jt(t,e){if(e.length===0)throw new Error("buildApiSurface requires at least one entry point");for(let l of e)if(!t.nodes.has(l))throw new Error(`Entry point not found in graph: ${l}`);let n=ol(t,e),r=al(t,n,e),s=nl(t,e),i=cl(s,r,t,e),{internalFiles:o,unreachableFromEntry:a,testFiles:c}=ll(t,n,e);return{entryPoints:e,publicExports:i,internalFiles:o,unreachableFromEntry:a,testFiles:c}}function Sr(t,e){let n=null,r=[];for(let i of t.nodes.values()){i.exports.some(o=>o.name===e)&&(n=i.path);for(let o of i.callEdges??[])o.to===e&&r.push({file:i.path,callerFunction:o.from})}let s=[];if(n){let i=t.nodes.get(n);for(let o of i?.callEdges??[])o.from===e&&s.push({file:o.toFile,calleeFunction:o.to})}return{functionName:e,definedIn:n,callers:r,callees:s}}import Gh from"fs";import jh from"path";function li(t){let e=[...t.nodes.entries()].sort(([r],[s])=>r.localeCompare(s)).map(([r,s])=>`${r}:${s.mtime}:${s.size}`).join("|"),n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")}function vr(t){let e=new Map;for(let n of t.nodes.keys()){let r=[];t.traverse(n,s=>(s.path!==n&&r.push(s.path),!0),{direction:"incoming"}),e.set(n,r)}return{impact:e,graphHash:li(t)}}function Cr(t,e){return t.impact.get(e)??[]}import dm from"path";import mt from"fs";import pi from"path";var P=class t{constructor(e){this.nodes=e}nodes;_incomingEdgesCache=null;_callIncomingCache=null;serialize(){return{nodes:Array.from(this.nodes.values())}}static deserialize(e){let n=new Map;for(let r of e.nodes)n.set(r.path,r);return new t(n)}getIncomingEdgesMap(){if(this._incomingEdgesCache)return this._incomingEdgesCache;let e=new Map;for(let n of this.nodes.values())for(let r of n.imports)if(r.toPath){let s=e.get(r.toPath)||[];s.push(n.path),e.set(r.toPath,s)}return this._incomingEdgesCache=e,e}dfs(e,n,r,s){let i=new Set,o=r.maxDepth??1/0,a=[{path:e,depth:0,parent:null}];for(;a.length>0;){let c=a.pop(),{path:l,depth:p,parent:u}=c;if(p>o||i.has(l))continue;let f=this.nodes.get(l);if(!f||(i.add(l),n(f,p,u)===!1))continue;let m=s(l);for(let h=m.length-1;h>=0;h--)a.push({path:m[h],depth:p+1,parent:l})}}traverse(e,n,r={}){let s=r.direction??"outgoing",i=s==="incoming"?this.getIncomingEdgesMap():null;this.dfs(e,n,r,o=>s==="outgoing"?this.nodes.get(o)?.imports.map(a=>a.toPath).filter(Boolean)??[]:i?.get(o)??[])}getCallIncomingCache(){if(this._callIncomingCache)return this._callIncomingCache;let e=new Map;for(let n of this.nodes.values())for(let r of n.callEdges??[]){let s=e.get(r.toFile)??[];s.push(n.path),e.set(r.toFile,s)}return this._callIncomingCache=e,e}traverseCalls(e,n,r={}){let s=r.direction??"outgoing",i=s==="incoming"?this.getCallIncomingCache():null;this.dfs(e,n,r,o=>s==="outgoing"?this.nodes.get(o)?.callEdges?.map(a=>a.toFile)??[]:i?.get(o)??[])}getCallers(e){let n=[];return this.traverseCalls(e,r=>(r.path!==e&&n.push(r.path),!0),{direction:"incoming",maxDepth:1}),n}getCallEdgesFor(e){return this.nodes.get(e)?.callEdges??[]}getNeighbors(e){let n=this.nodes.get(e);return n?n.imports.map(r=>this.nodes.get(r.toPath)).filter(r=>r!==void 0):[]}findUnusedFiles(e){return new Oe(this.nodes).findUnusedFiles(e)}findCycles(e){return new Oe(this.nodes).findCycles(e)}};function Vt(t){return pi.join(t,me,rr)}function ui(t,e){return pi.join(Vt(t),`${e}.json`)}function fi(t,e){let n=ui(t,e);if(!mt.existsSync(n))return null;try{let r=mt.readFileSync(n,"utf-8");return P.deserialize(JSON.parse(r))}catch{return null}}function mi(t,e,n){let r=Vt(t);mt.existsSync(r)||mt.mkdirSync(r,{recursive:!0}),mt.writeFileSync(ui(t,e),JSON.stringify(n.serialize()))}import wt from"fs";import L from"path";import of from"piscina";import{execFileSync as wr}from"child_process";var Qt=class{getChangedFiles(e,n){try{let s=[["diff","--name-only"],["diff","--cached","--name-only"],["ls-files","--others","--exclude-standard"],...n?[["diff","--name-only","--end-of-options",`${n}...HEAD`]]:[]].flatMap(i=>{try{return wr("git",i,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
4
+ `).map(a=>a.trim()).filter(a=>a!=="")}catch{return[]}});return Array.from(new Set(s))}catch(r){return console.error("Error getting git diff:",r),[]}}},gi="%x00%H%x09%ae%x09%at",di=256*1024*1024;function hi(t,e){let n="",r=0;for(let s of t.split(`
5
+ `)){if(s.startsWith("\0")){let[,c,l]=s.slice(1).split(" ");n=c??"",r=l?Number(l)*1e3:0;continue}if(s==="")continue;let i=s.split(" "),o=i[0];if(!o)continue;let a=o.startsWith("R")||o.startsWith("C")?i[2]:i[1];a&&e(a,n,r)}}function yi(t){let e=new Map;try{let n=wr("git",["-C",t,"log","--since=90 days ago","--name-status","-M",`--format=${gi}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:di});hi(n,(r,s,i)=>{let o=e.get(r);if(o){o.commitCount90d+=1;return}e.set(r,{commitCount90d:1,lastAuthor:s||void 0,lastCommitAt:i||void 0})})}catch{return e}try{let n=wr("git",["-C",t,"log","--name-status","-M",`--format=${gi}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:di});hi(n,(r,s,i)=>{e.has(r)||e.set(r,{commitCount90d:0,lastAuthor:void 0,lastCommitAt:i||void 0})})}catch{}return e}import Yt from"fs";import pl from"path";import{load as xi}from"js-yaml";var gt=["package-lock.json","yarn.lock","pnpm-lock.yaml"];function bi(t){let e=t.lastIndexOf("@");return e>0?t.substring(0,e):t}function ul(t){return t.replace(/:$/,"").split(",").map(e=>{let n=e.trim();return n.startsWith('"')&&(n=n.slice(1)),n.endsWith('"')&&(n=n.slice(0,-1)),bi(n)}).filter(Boolean)}function fl(t,e){let n=t.startsWith("/")?t.slice(1):t,r=n.lastIndexOf("@");return r>0?{name:n.substring(0,r),version:e||n.substring(r+1)}:{name:n,version:e}}function ml(t){try{let e=xi(t),n={dependencies:{}};for(let[r,s]of Object.entries(e))if(!(r==="__metadata"||!s?.version))for(let i of r.split(", ")){let o=bi(i);o&&(n.dependencies[o]={version:s.version,...s.dependencies!==void 0&&{dependencies:s.dependencies}})}return n}catch{return null}}function gl(t){let e={dependencies:{}};for(let n of t.split(/\n\n+/)){let r=n.split(`
6
+ `).filter(c=>c.trim().length>0&&!c.trim().startsWith("#"));if(r.length<2)continue;let s=r[0];if(!s||s.startsWith(" "))continue;let i=ul(s);if(i.length===0)continue;let a=r.find(c=>c.trim().startsWith('version "'))?.match(/version "(.*?)"/)?.[1]??"";for(let c of i)e.dependencies[c]={version:a}}return e}function ki(t){let e=Yt.readFileSync(t,"utf-8"),n=JSON.parse(e),r={dependencies:{}};if(n.packages)for(let[s,i]of Object.entries(n.packages)){if(!s.startsWith("node_modules/"))continue;let o=s.replace("node_modules/","");o.includes("node_modules/")||(r.dependencies[o]={version:i.version,...i.dependencies!==void 0&&{dependencies:i.dependencies}})}else if(n.dependencies)for(let[s,i]of Object.entries(n.dependencies))r.dependencies[s]={version:i.version,...i.dependencies!==void 0&&{dependencies:i.dependencies}};return r}function Si(t){let e=Yt.readFileSync(t,"utf-8");if(e.includes("__metadata:")){let n=ml(e);if(n!==null)return n}return gl(e)}function vi(t){let e=Yt.readFileSync(t,"utf-8"),n={dependencies:{}};try{let r=xi(e);if(r.packages)for(let[s,i]of Object.entries(r.packages)){let{name:o,version:a}=fl(s,i.version);o&&(n.dependencies[o]={version:a,...i.dependencies!==void 0&&{dependencies:i.dependencies}})}if(r.dependencies)for(let[s,i]of Object.entries(r.dependencies)){if(n.dependencies[s])continue;let o=typeof i=="string"?i:i.version;n.dependencies[s]={version:o||""}}}catch{}return n}var dl={"package-lock.json":ki,"yarn.lock":Si,"pnpm-lock.yaml":vi};function Er(t){for(let e of gt){let n=pl.join(t,e);if(Yt.existsSync(n))return dl[e](n)}return null}import qt from"fs";import Zt from"path";function Ci(t){let e=t.trim();return e.length>=2&&(e[0]==='"'||e[0]==="'")&&e[e.length-1]===e[0]?e.slice(1,-1):e}function hl(t){let e=t.trim();if(e.startsWith('"')||e.startsWith("'")){let a=Ci(e).split(":");return a.length>=3&&a[0]&&a[2]?{group:a[0],version:a[2]}:null}if(!e.startsWith("{"))return null;let n=e.match(/module\s*=\s*["']([^"']+)["']/),r=e.match(/group\s*=\s*["']([^"']+)["']/),s=n?n[1].split(":")[0]:r?.[1];if(!s)return null;let i=e.match(/version\.ref\s*=\s*["']([^"']+)["']/)??e.match(/version\s*=\s*\{\s*ref\s*=\s*["']([^"']+)["']/),o=e.match(/version\s*=\s*["']([^"']+)["']/);return{group:s,...o?.[1]!==void 0&&{version:o[1]},...i?.[1]!==void 0&&{versionRef:i[1]}}}function Tr(t){let e=t.split(/\r?\n/).map(i=>i.replace(/#.*$/,"").trim()),n={},r="";for(let i of e){let o=i.match(/^\[([\w.-]+)\]$/);if(o){r=o[1];continue}if(r!=="versions"||!i)continue;let a=i.indexOf("=");if(a===-1)continue;let c=i.slice(0,a).trim(),l=Ci(i.slice(a+1));c&&l&&(n[c]=l)}let s={};r="";for(let i of e){let o=i.match(/^\[([\w.-]+)\]$/);if(o){r=o[1];continue}if(r!=="libraries"||!i)continue;let a=i.indexOf("=");if(a===-1)continue;let c=hl(i.slice(a+1));if(!c)continue;let l=c.versionRef?n[c.versionRef]:c.version;l&&(s[c.group]=l)}return s}function Fr(t){let e={};for(let n of t.split(/\r?\n/)){let r=n.trim();if(!r||r.startsWith("#")||r.startsWith("empty="))continue;let i=r.split("=")[0].split(":");i.length>=3&&i[0]&&i[2]&&(e[i[0]]=i[2])}return e}function Dr(t){let e={},n=/["']([\w.-]+):([\w.-]+):([\w.\-+]+)["']/g;for(let s=n.exec(t);s;s=n.exec(t)){let[,i,,o]=s;i&&o&&/\d/.test(o)&&(e[i]=o)}let r=/group:\s*["']([\w.-]+)["'][^\n)]*?version:\s*["']([\w.\-+]+)["']/g;for(let s=r.exec(t);s;s=r.exec(t))s[1]&&s[2]&&/\d/.test(s[2])&&(e[s[1]]=s[2]);return e}function Xt(t){let e={},n=/["']([\w.-]+)["']\s*%%?\s*["']([\w.-]+)["']\s*%\s*["']([\w.\-+]+)["']/g;for(let r=n.exec(t);r;r=n.exec(t)){let[,s,,i]=r;s&&i&&(e[s]=i)}return e}var yl=new Set(["node_modules","build",".gradle","target",".git","dist"]),xl=2;function dt(t){try{return qt.existsSync(t)?qt.readFileSync(t,"utf-8"):null}catch{return null}}function Pr(t){let e={},n=p=>{for(let[u,f]of Object.entries(p))!e[u]&&f&&(e[u]=f)},r=dt(Zt.join(t,"gradle","libs.versions.toml"));r&&n(Tr(r));let s=[],i=[],o=[],a=(p,u)=>{let f;try{f=qt.readdirSync(p,{withFileTypes:!0})}catch{return}for(let m of f){let h=Zt.join(p,m.name);if(m.isDirectory()){u<xl&&!m.name.startsWith(".")&&!yl.has(m.name)&&a(h,u+1);continue}m.isFile()&&(m.name==="gradle.lockfile"?s.push(h):m.name==="build.gradle"||m.name==="build.gradle.kts"?i.push(h):m.name==="build.sbt"&&o.push(h))}};a(t,0);for(let p of s){let u=dt(p);u&&n(Fr(u))}for(let p of i){let u=dt(p);u&&n(Dr(u))}for(let p of o){let u=dt(p);u&&n(Xt(u))}try{let p=Zt.join(t,"project");for(let u of qt.readdirSync(p,{withFileTypes:!0}))if(u.isFile()&&u.name.endsWith(".scala")){let f=dt(Zt.join(p,u.name));f&&n(Xt(f))}}catch{}let c=Object.keys(e);if(c.length===0)return null;let l={};for(let p of c)l[p]={version:e[p]};return l}function wi(t){let e=Er(t),n=Pr(t);return n?{...e??{dependencies:{}},jvmDependencies:n}:e}import Ei from"path";function J(t){switch(Ei.extname(t).toLowerCase()){case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".ts":case".tsx":return"typescript";case".css":return"css";case".scss":case".sass":return"scss";case".less":return"less";case".styl":return"stylus";case".coffee":return"coffeescript";case".ls":return"livescript";case".lua":return"lua";case".py":return"python";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":case".sc":return"scala";case".groovy":case".gradle":return"groovy";case".cpp":case".cc":case".cxx":case".c":return"unknown";case".feature":return"gherkin";case".md":case".mdx":return"markdown";default:return"unknown"}}function W(t){let e=Ei.extname(t).toLowerCase();return[".css",".scss",".sass",".less",".styl"].includes(e)}import bl from"coffeescript";function de(t){return t.startsWith("'")||t.startsWith('"')?t.slice(1,-1):t}function je(t){let e=new Set,n=/@tag\s+([a-zA-Z0-9_-]+)/g,r=n.exec(t);for(;r!==null;)r[1]&&e.add(r[1]),r=n.exec(t);return e}function We(t,e){let n=t.toLowerCase();return n.includes(".test.")||n.includes(".spec.")||e.has("test")?"test":"logic"}function Fi(t){if(t){if(typeof t.originalValue=="string")return t.originalValue;if(typeof t.value=="string")return de(t.value)}}function we(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function kl(t,e){let n=Fi(e.source);return n?{fromPath:t,toPath:"",rawSpecifier:n,isStyle:W(n),type:"static"}:null}function Sl(t,e){let n=e.variable?.base?.value==="require",r=Fi(e.args?.[0]?.base);return!n||!r?null:{fromPath:t,toPath:"",rawSpecifier:r,isStyle:W(r),type:"require"}}function Ti(t,e){if(e)return[{name:e}];let n=t.value;if(n?.constructor?.name==="Class"){let s=we(n.variable);return s?[{name:s}]:[]}if(n?.base?.constructor?.name==="Obj"&&Array.isArray(n.base.properties))return n.base.properties.map(s=>we(s.variable)??we(s)).filter(s=>!!s).map(s=>({name:s}));let r=we(n);return r?[{name:r}]:[]}function vl(t){if(Array.isArray(t.specifiers))return t.specifiers.map(n=>n.identifier??n.original?.value).filter(n=>!!n).map(n=>({name:n}));let e=we(t.variable)??we(t.variable?.base);return e?[{name:e}]:[]}function Cl(t,e,n,r){let s=e.constructor?.name;if(s==="ImportDeclaration"){let i=kl(t,e);i&&n.push(i)}else if(s==="Call"){let i=Sl(t,e);i&&n.push(i)}else if(s==="Assign"){let i=we(e.variable?.base),o=e.variable?.properties?.[0]?.name?.value;i==="module"&&o==="exports"?r.push(...Ti(e,void 0)):i==="exports"&&typeof o=="string"&&r.push(...Ti(e,o))}else s==="ExportNamedDeclaration"&&e.clause?r.push(...vl(e.clause)):s==="ExportDefaultDeclaration"&&r.push({name:"default"})}function Ar(t,e,n,r){if(!(!e||typeof e!="object")){Cl(t,e,n,r);for(let s in e){if(s==="locationData")continue;let i=e[s];if(!(!i||typeof i!="object"))if(Array.isArray(i))for(let o of i)Ar(t,o,n,r);else Ar(t,i,n,r)}}}function Di(t,e){let n=je(e),r=We(t,n),s=[],i=[];try{Ar(t,bl.nodes(e),s,i)}catch{}let o=new Set,a=i.filter(c=>o.has(c.name)?!1:(o.add(c.name),!0));return{imports:s,exports:a,tags:Array.from(n).map(c=>({name:c,kind:"comment-marker"})),category:r}}import{AstBuilder as wl,GherkinClassicTokenMatcher as El,Parser as Tl}from"@cucumber/gherkin";import{IdGenerator as Fl}from"@cucumber/messages";var Pi=new Map;function $e(t,e){Pi.set(t,e)}function Ai(t){return Pi.get(t)}var Dl=Fl.uuid();function Rr(t,e){let n=new Set,r=s=>{for(let i of s)n.add(i.name.startsWith("@")?i.name.slice(1):i.name)};try{let s=new wl(Dl),i=new El,a=new Tl(s,i).parse(e);if(a.feature){r(a.feature.tags);for(let c of a.feature.children){if(c.scenario){r(c.scenario.tags);for(let l of c.scenario.examples)r(l.tags)}if(c.rule)for(let l of c.rule.children)l.scenario&&r(l.scenario.tags)}}}catch(s){console.warn(`[GherkinParser] Failed to parse ${t}:`,s)}return{imports:[],exports:[],tags:Array.from(n).map(s=>({name:s,kind:"comment-marker"})),category:"test"}}$e("gherkin",Rr);import Ml from"path";import{parser as Il}from"@lezer/go";function Ee(t){let e=[],n=t.firstChild;for(;n;)e.push(n),n=n.nextSibling;return e}function Te(t,e){let n=1;for(let r=0;r<e&&r<t.length;r++)t[r]===`
7
+ `&&n++;return n}function Pl(t,e){let n=1;function r(s){switch(s.type.name){case"IfStatement":case"ForStatement":n++;break;case"Case":{s.firstChild?.type.name==="case"&&n++;break}case"LogicOp":{let o=e.slice(s.from,s.to);(o==="&&"||o==="||")&&n++;break}}let i=s.firstChild;for(;i;)r(i),i=i.nextSibling}return r(t),n}function Ni(t,e,n,r){let s=n?1:1+e,i=Ee(t),o=n?e:e+1,a=i[1];a&&a.type.name!=="Block"&&(s+=ze(a,o,!1,r));let c=i.find(p=>p.type.name==="Block");c&&(s+=ze(c,o,!1,r));let l=i.findIndex(p=>p.type.name==="else");if(l>=0){let p=i[l+1];p?.type.name==="IfStatement"?s+=Ni(p,e,!0,r):p&&(s+=1+ze(p,e+1,!1,r))}return s}function Ri(t,e,n){let r=1+e,s=t.firstChild;for(;s;)r+=ze(s,e+1,!1,n),s=s.nextSibling;return r}function Al(t,e,n){let r=0,s=t.firstChild;for(;s;)r+=ze(s,e,!1,n),s=s.nextSibling;return r}function Rl(t,e){let n=e.slice(t.from,t.to);return n==="&&"||n==="||"}function ze(t,e,n,r){let s=t.type.name;if(s==="IfStatement")return Ni(t,e,n,r);if(s==="ForStatement"||s==="SwitchStatement"||s==="SelectStatement")return Ri(t,e,r);let i=s==="LogicOp"&&Rl(t,r)?1:0;return e>0&&s==="FunctionLiteral"?i+Ri(t,e,r):i+Al(t,e,r)}function Nl(t,e){return ze(t,0,!1,e)}function en(t,e){return{complexity:Pl(t,e),cognitiveComplexity:Nl(t,e)}}function Nr(t,e){let r=t.getChild("Parameters")?.getChild("Parameter"),s=r?.getChild("TypeName")??r?.getChild("PointerType")?.getChild("TypeName");return s?e.slice(s.from,s.to):void 0}function Mi(t,e){let n=[],r=t.cursor();do if(r.name==="FunctionDecl"){let s=r.node.getChild("DefName");if(s){let i=e.slice(s.from,s.to),{complexity:o,cognitiveComplexity:a}=en(r.node,e);n.push({name:i,line:Te(e,r.from),complexity:o,cognitiveComplexity:a})}}else if(r.name==="MethodDecl"){let s=r.node.getChild("FieldName");if(s){let i=e.slice(s.from,s.to),o=Nr(r.node,e),a=o?`${o}.${i}`:i,{complexity:c,cognitiveComplexity:l}=en(r.node,e);n.push({name:a,line:Te(e,r.from),complexity:c,cognitiveComplexity:l})}}while(r.next());return n}var Ll=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/,_l=/^\/\/go:build\s+(.+)$/,Gl=/^\/\/\s*\+build\s+(.+)$/;function Li(t,e){let n=[],r=new Map,s=new Set,i=new Set,o=new Map,a=Il.parse(e),c=a.cursor();do switch(c.name){case"LineComment":{let k=e.slice(c.from,c.to),S=k.match(Ll);S?.[1]&&s.add(S[1]);let w=k.match(_l);w&&Ii(w[1],i);let N=k.match(Gl);N&&Ii(N[1],i);break}case"ImportSpec":{let k=c.node.getChild("String");if(k){let w=e.slice(k.from,k.to).slice(1,-1);n.push({fromPath:t,toPath:"",rawSpecifier:w,isExternal:!0,isStyle:!1,type:"static"});let N=c.node.getChild("DefName"),_=N?e.slice(N.from,N.to):w.split("/").pop();_&&_!=="_"&&_!=="."&&o.set(_,w)}break}case"FunctionDecl":case"MethodDecl":case"TypeDecl":case"VarDecl":case"ConstDecl":{let k=c.node.getChild("DefName")??c.node.getChild("FieldName")??c.node.getChild("TypeSpec")?.getChild("DefName")??c.node.getChild("VarSpec")?.getChild("DefName")??c.node.getChild("ConstSpec")?.getChild("DefName");if(k){let S=e.slice(k.from,k.to);S!=="_"&&/^[A-Z]/.test(S)&&!r.has(S)&&r.set(S,{name:S})}break}}while(c.next());let l=n.some(k=>k.rawSpecifier==="testing"),p=Ml.basename(t).endsWith("_test.go")||s.has("test")||l?"test":"logic",u=new Set([...s,...i]),{complexity:f,cognitiveComplexity:m}=en(a.topNode,e),h=Mi(a,e),b=p==="test"?[]:Ol(a,e,o);return{imports:n,exports:Array.from(r.values()),tags:Array.from(u).map(k=>({name:k,kind:"comment-marker"})),category:p,rawCallEdges:b,complexity:f,cognitiveComplexity:m,...h.length>0?{functions:h}:{}}}function Ol(t,e,n){let r=[];function s(o,a){if(o.type.name==="CallExpr"){let l=o.firstChild;if(l?.type.name==="SelectorExpr"){let p=l.firstChild,u=l.getChild("FieldName");if(p?.type.name==="VariableName"&&u){let f=e.slice(p.from,p.to),m=n.get(f);if(m){let h=e.slice(u.from,u.to);r.push({from:a,to:h,toSpecifier:m})}}}}let c=o.firstChild;for(;c;)s(c,a),c=c.nextSibling}let i=t.cursor();do if(i.name==="FunctionDecl"){let o=i.node.getChild("DefName"),a=i.node.getChild("Block");if(o&&a){let c=e.slice(o.from,o.to);/^[A-Z]/.test(c)&&s(a,c)}}else if(i.name==="MethodDecl"){let o=i.node.getChild("FieldName"),a=i.node.getChild("Block");if(o&&a){let c=e.slice(o.from,o.to),l=Nr(i.node,e);s(a,l?`${l}.${c}`:c)}}while(i.next());return r}function Ii(t,e){for(let n of t.split(/[\s,&|!()]+/)){let r=n.trim();r&&r!=="ignore"&&e.add(r)}}var jl=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/g,Wl=["org.junit","androidx.test","org.robolectric","org.mockito","org.scalatest","munit","spock.lang","io.kotest","org.spekframework","org.testng","org.assertj","com.google.truth","org.hamcrest","io.mockk","com.nhaarman.mockitokotlin2"],Mr=["test","androidTest","integrationTest","it"],$l=new RegExp(`/src/(${Mr.join("|")})/`),zl=/(?:Test|Tests|Spec|IT|ITCase)$/;function Ir(t){let e=t.replace(/\.\w+$/,"");return zl.test(e)}function Be(t){let e=new Set;for(let n of t.matchAll(jl))n[1]&&e.add(n[1]);return e}function he(t){let e=t.replace(/\/\*[\s\S]*?\*\//g,n=>n.replace(/[^\n]/g," "));return e=e.replace(/\/\/[^\n]*/g,n=>" ".repeat(n.length)),e}function Ue(t){let e=he(t),n=new Set;for(let s of e.matchAll(/@([A-Z]\w*)/g))s[1]&&n.add(s[1]);let r=new Set;for(let s of e.matchAll(/\b(?:class|object|interface|trait|enum)\s+([A-Za-z_]\w*)/g))s[1]&&r.add(s[1]);return{annotations:[...n],typeNames:[...r]}}function tn(t){let e=t.split(".").pop();return e&&e!=="*"?e:void 0}function Ke(t,e,n=e){let r=tn(n);return{fromPath:t,toPath:"",rawSpecifier:e,isExternal:!0,isStyle:!1,type:"static",symbols:r?[r]:void 0}}function ye(t,e){return{fromPath:t,toPath:"",rawSpecifier:`${e}.*`,isExternal:!0,isStyle:!1,type:"side-effect",isSamePackage:!0}}function q(t,e){let n=[];for(let r of he(t).split(`
8
+ `)){let s=r.trim();if(!s||s.startsWith("@")||s.startsWith("*"))continue;let i=s.match(/^package\s+(?:object\s+)?([\w.]+)/);if(i?.[1]){if(n.push(i[1]),!e)break;continue}if(!(e&&/^import\s/.test(s)))break}return n.length>0?n.join("."):null}var Bl=new Set(["Configuration","SpringBootApplication","EnableAutoConfiguration"]),Ul=new Set(["Composable","Preview"]),Kl=new Set(["RestController","Controller","Service","Repository","Component","Entity","MappedSuperclass","Embeddable"]),Hl=["Activity","Fragment","ViewModel","Screen","Composable"];function se(t,e,n={}){let r=t.replace(/\\/g,"/"),s=r.split("/").pop()??"";if(s.endsWith(".gradle")||s==="build.gradle.kts"||s==="settings.gradle.kts")return"config";if($l.test(r)||e.some(o=>Wl.some(a=>o===a||o.startsWith(`${a}.`))))return"test";let i=n.annotations??[];return i.some(o=>Bl.has(o))?"config":i.some(o=>Ul.has(o))||(n.typeNames??[]).some(o=>Hl.some(a=>o.endsWith(a)))?"ui":i.some(o=>Kl.has(o))?"logic":Ir(s)?"test":"logic"}var Jl=/^\s*import\s+(static\s+)?([\w.]+(?:\.\*)?)(?:\s+as\s+\w+)?\s*$/,Vl=/^(?:@\w+\s+)*(?:public\s+|private\s+|protected\s+|final\s+|abstract\s+|static\s+)*(class|interface|trait|enum|def)\s+([A-Za-z_][A-Za-z0-9_]*)/;function Ql(t,e){return t?e.endsWith(".*")?e.slice(0,-2)||null:e.split(".").slice(0,-1).join(".")||null:e||null}function _i(t,e){let n=Be(e),s=he(e).split(`
9
+ `),i=[],o=new Set;for(let l of s){let p=l.match(Jl);if(p?.[2]){let f=Ql(!!p[1],p[2]);f&&i.push(Ke(t,f,p[2]));continue}let u=l.match(Vl);u?.[2]&&o.add(u[2])}let a=q(e,!1);a&&i.push(ye(t,a));let c=Array.from(o,l=>({name:l}));return{imports:i,exports:c,tags:Array.from(n).map(l=>({name:l,kind:"comment-marker"})),category:se(t,i.map(l=>l.rawSpecifier),{typeNames:[...o],annotations:Ue(e).annotations})}}import{parser as tp}from"@lezer/java";var Gi=new Set(["ForStatement","EnhancedForStatement","WhileStatement","DoStatement"]),Yl=new Set(["ClassDeclaration","InterfaceDeclaration","EnumDeclaration","RecordDeclaration","AnnotationTypeDeclaration"]);function Xl(t,e){let n=1;function r(s){let i=s.type.name;if(i==="IfStatement"||i==="CatchClause"||i==="TernaryExpression")n++;else if(Gi.has(i))n++;else if(i==="SwitchLabel")s.firstChild?.type.name==="case"&&n++;else if(i==="LogicOp"){let a=e.slice(s.from,s.to);(a==="&&"||a==="||")&&n++}let o=s.firstChild;for(;o;)r(o),o=o.nextSibling}return r(t),n}function Oi(t,e,n,r){let s=n?1:1+e,i=[];for(let p=t.firstChild;p;p=p.nextSibling)i.push(p);let o=n?e:e+1,a=i[1];a&&a.type.name!=="Block"&&(s+=He(a,o,!1,r));let c=i.find(p=>p.type.name==="Block");c&&(s+=He(c,o,!1,r));let l=i.findIndex(p=>p.type.name==="else");if(l>=0){let p=i[l+1];p?.type.name==="IfStatement"?s+=Oi(p,e,!0,r):p&&(s+=1+He(p,e+1,!1,r))}return s}function Lr(t,e,n){let r=1+e,s=t.firstChild;for(;s;)r+=He(s,e+1,!1,n),s=s.nextSibling;return r}function Zl(t,e,n){let r=0,s=t.firstChild;for(;s;)r+=He(s,e,!1,n),s=s.nextSibling;return r}function ql(t,e){let n=e.slice(t.from,t.to);return n==="&&"||n==="||"}function He(t,e,n,r){let s=t.type.name;if(s==="IfStatement")return Oi(t,e,n,r);if(Gi.has(s)||s==="SwitchStatement"||s==="CatchClause"||s==="TernaryExpression")return Lr(t,e,r);let i=s==="LogicOp"&&ql(t,r)?1:0;return e>0&&s==="LambdaExpression"?i+Lr(t,e,r):i+Zl(t,e,r)}function ep(t,e){return He(t,0,!1,e)}function _r(t,e){return{complexity:Xl(t,e),cognitiveComplexity:ep(t,e)}}function Gr(t,e){for(let n=t.parent;n;n=n.parent)if(Yl.has(n.type.name)){let r=n.getChild("Definition");if(r)return e.slice(r.from,r.to)}}function ji(t,e){let n=[],r=t.cursor();do if(r.name==="MethodDeclaration"||r.name==="ConstructorDeclaration"){let s=r.node.getChild("Definition");if(s){let i=e.slice(s.from,s.to),o=Gr(r.node,e),a=o&&r.name==="MethodDeclaration"?`${o}.${i}`:i,{complexity:c,cognitiveComplexity:l}=_r(r.node,e);n.push({name:a,line:Te(e,r.from),complexity:c,cognitiveComplexity:l})}}while(r.next());return n}var np=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/;function rp(t,e){let n=t.getChild("ScopedIdentifier");if(!n)return null;let r=t.getChild("static")!=null,s=t.getChild("Asterisk")!=null,i=e.slice(n.from,n.to);if(r){if(s)return i?{specifier:i,wildcard:!1}:null;let o=i.split(".").slice(0,-1).join(".");return o?{specifier:o,wildcard:!1,symbol:tn(i)}:null}return s?{specifier:`${i}.*`,wildcard:!0}:{specifier:i,wildcard:!1,symbol:tn(i)}}function sp(t){let e=new Map;for(let n of t){if(n.type==="side-effect")continue;let r=n.rawSpecifier;if(r.endsWith(".*"))continue;let s=r.split(".").pop();s&&e.set(s,r)}return e}function ip(t,e){let n=t;if(n.name==="GenericType"&&(n=n.firstChild),!n)return null;if(n.name==="TypeName")return e.slice(n.from,n.to);if(n.name==="ScopedTypeName"){let r=null;for(let s=n.firstChild;s;s=s.nextSibling)s.name==="TypeName"&&(r=s);return r?e.slice(r.from,r.to):null}return null}function op(t,e,n){let r=[];function s(o,a){let c=o.type.name;if(c==="MethodInvocation"){let p=o.firstChild;if(p?.type.name==="Identifier"){let u=n.get(e.slice(p.from,p.to)),f=o.getChild("MethodName");u&&f&&r.push({from:a,to:e.slice(f.from,f.to),toSpecifier:u})}}else if(c==="ObjectCreationExpression"){let p=o.getChild("TypeName")??o.getChild("GenericType")??o.getChild("ScopedTypeName"),u=p&&ip(p,e);if(u){let f=n.get(u);f&&r.push({from:a,to:"new",toSpecifier:f})}}let l=o.firstChild;for(;l;)s(l,a),l=l.nextSibling}let i=t.cursor();do if(i.name==="MethodDeclaration"||i.name==="ConstructorDeclaration"){let o=i.node.getChild("Definition"),a=i.node.getChild("Block")??i.node.getChild("ConstructorBody");if(o&&a){let c=e.slice(o.from,o.to),l=Gr(i.node,e),p=l&&i.name==="MethodDeclaration"?`${l}.${c}`:c;s(a,p)}}while(i.next());return r}function Wi(t,e){let n=[],r=new Map,s=new Set,i=new Set,o;try{o=tp.parse(e)}catch{return{imports:[],exports:[],tags:[],category:se(t,[])}}let a=o.cursor();do switch(a.name){case"LineComment":{let h=e.slice(a.from,a.to).match(np);h?.[1]&&s.add(h[1]);break}case"MarkerAnnotation":case"Annotation":{let h=a.node.getChild("Identifier");h&&i.add(e.slice(h.from,h.to));break}case"ImportDeclaration":{let h=rp(a.node,e);h&&n.push({fromPath:t,toPath:"",rawSpecifier:h.specifier,isExternal:!0,isStyle:!1,type:"static",symbols:h.symbol?[h.symbol]:void 0});break}case"ClassDeclaration":case"InterfaceDeclaration":case"EnumDeclaration":case"AnnotationTypeDeclaration":{if(a.node.parent?.name==="Program"){let h=a.node.getChild("Definition");if(h){let b=e.slice(h.from,h.to);r.has(b)||r.set(b,{name:b})}}break}}while(a.next());let c=q(e,!1);c&&n.push(ye(t,c));let l=se(t,n.map(h=>h.rawSpecifier),{typeNames:[...r.keys()],annotations:[...i]}),{complexity:p,cognitiveComplexity:u}=_r(o.topNode,e),f=ji(o,e),m=l==="test"?[]:op(o,e,sp(n));return{imports:n,exports:Array.from(r.values()),tags:Array.from(s).map(h=>({name:h,kind:"comment-marker"})),category:l,rawCallEdges:m,complexity:p,cognitiveComplexity:u,...f.length>0?{functions:f}:{}}}var ap=/^\s*import\s+([\w.]+(?:\.\*)?)(?:\s+as\s+\w+)?\s*$/,Or="(?:public\\s+|internal\\s+|private\\s+|protected\\s+|open\\s+|abstract\\s+|final\\s+|sealed\\s+|data\\s+|value\\s+|inline\\s+|noinline\\s+|crossinline\\s+|external\\s+|expect\\s+|actual\\s+|suspend\\s+|operator\\s+|infix\\s+|tailrec\\s+|const\\s+|lateinit\\s+)*",cp=new RegExp(`^(?:@[\\w.]+(?:\\([^)]*\\))?\\s+)*${Or}(?:(?:enum|annotation)\\s+)?(class|interface|object|typealias)\\s+([A-Za-z_][A-Za-z0-9_]*)`),lp=new RegExp(`^(?:@[\\w.]+(?:\\([^)]*\\))?\\s+)*${Or}fun\\s+(?:<[^>]*>\\s*)?(?:[A-Za-z_][\\w.]*(?:<[^>]*>)?\\.)?([A-Za-z_][A-Za-z0-9_]*)\\s*[(<]`),pp=new RegExp(`^(?:@[\\w.]+(?:\\([^)]*\\))?\\s+)*${Or}(?:val|var)\\s+(?:<[^>]*>\\s*)?([A-Za-z_][A-Za-z0-9_]*)`);function $i(t,e){let n=Be(e),s=he(e).split(`
10
+ `),i=[],o=new Set;for(let l of s){let p=l.match(ap);if(p?.[1]){i.push(Ke(t,p[1]));continue}let u=l.match(cp);if(u?.[2]){o.add(u[2]);continue}let f=l.match(lp);if(f?.[1]){o.add(f[1]);continue}let m=l.match(pp);m?.[1]&&o.add(m[1])}let a=q(e,!1);a&&i.push(ye(t,a));let c=Array.from(o,l=>({name:l}));return{imports:i,exports:c,tags:Array.from(n).map(l=>({name:l,kind:"comment-marker"})),category:se(t,i.map(l=>l.rawSpecifier),{typeNames:[...o],annotations:Ue(e).annotations})}}import up from"livescript";function Fe(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function fp(t){if(!t)return[];if(t.constructor?.name==="Class"){let n=Fe(t.title);return n?[{name:n}]:[]}if(t.constructor?.name==="Obj"&&Array.isArray(t.items))return t.items.map(n=>Fe(n.key)??Fe(n.val)).filter(n=>!!n).map(n=>({name:n}));let e=Fe(t);return e?[{name:e}]:[]}function mp(t){let e=t.constructor?.name||t.type;if(e==="Assign"&&t.left?.constructor?.name==="Chain"){let n=t.left,r=Fe(n.head),i=n.tails?.[0]?.key?.name;if(r==="module"&&i==="exports")return fp(t.right);if(r==="exports"&&typeof i=="string")return[{name:i}];if(n.head?.verb==="out"&&typeof i=="string")return[{name:i}]}if(e==="Import"&&t.left?.verb==="out"){let n=t.right;if(n?.constructor?.name==="Obj"&&Array.isArray(n.items))return n.items.map(r=>Fe(r.val)??Fe(r.key)).filter(r=>!!r).map(r=>({name:r}))}return[]}var gp=new Set(["first_line","first_column","last_line","last_column","line","column"]);function dp(t,e){let n=t.constructor?.name||t.type;if(n==="Import"){let r=t.right?.value;if(typeof r=="string"){let s=de(r);return{fromPath:e,toPath:"",rawSpecifier:s,isStyle:W(s),type:"static"}}}if(n==="Chain"&&t.head?.value==="require"){let r=t.tails?.[0];if(r?.constructor?.name==="Call"||r?.type==="Call"){let s=r.args?.[0]?.value;if(typeof s=="string"){let i=de(s);return{fromPath:e,toPath:"",rawSpecifier:i,isStyle:W(i),type:"require"}}}}return null}function jr(t,e,n){if(!t||typeof t!="object")return[];let r=[],s=dp(t,e);s&&r.push(s),n.push(...mp(t));for(let i in t){if(gp.has(i))continue;let o=t[i];if(!(!o||typeof o!="object"))if(Array.isArray(o))for(let a of o)r.push(...jr(a,e,n));else r.push(...jr(o,e,n))}return r}function zi(t,e){let n=je(e),r=We(t,n),s=[],i=[];try{s=jr(up.ast(e),t,i)}catch{}let o=new Set,a=i.filter(c=>o.has(c.name)?!1:(o.add(c.name),!0));return{imports:s,exports:a,tags:Array.from(n).map(c=>({name:c,kind:"comment-marker"})),category:r}}import hp from"luaparse";function yp(t,e){let n=[];function r(s){if(!(!s||typeof s!="object")){if((s.type==="CallExpression"||s.type==="StringCallExpression")&&s.base?.type==="Identifier"&&s.base?.name==="require"){let i;if(s.type==="CallExpression"){let o=s.arguments?.[0];o?.type==="StringLiteral"&&(i=de(o.raw))}else if(s.type==="StringCallExpression"){let o=s.argument;o?.type==="StringLiteral"&&(i=de(o.raw))}i&&n.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:W(i),type:"require"})}for(let i in s){if(i==="loc")continue;let o=s[i];if(o&&typeof o=="object")if(Array.isArray(o))for(let a of o)r(a);else r(o)}}}return r(t),n}function xp(t){let e=new Set;for(let n of t)n.type==="LocalStatement"&&n.variables.forEach((r,s)=>{n.init[s]?.type==="TableConstructorExpression"&&e.add(r.name)});return e}function bp(t){let e=t[t.length-1];if(e?.type!=="ReturnStatement")return[];let n=e.arguments[0];if(n?.type!=="TableConstructorExpression")return[];let r=[];for(let s of n.fields)s.type==="TableKeyString"&&r.push({name:s.key.name});return r}function kp(t){let e=t.body,n=xp(e),r=bp(e);for(let i of e)if(i.type==="FunctionDeclaration")i.identifier?.type==="MemberExpression"?i.identifier.base.type==="Identifier"&&n.has(i.identifier.base.name)&&r.push({name:i.identifier.identifier.name}):i.identifier?.type==="Identifier"&&!i.isLocal&&r.push({name:i.identifier.name});else if(i.type==="AssignmentStatement")for(let o of i.variables)o.type==="MemberExpression"&&o.base.type==="Identifier"&&n.has(o.base.name)&&r.push({name:o.identifier.name});let s=new Set;return r.filter(i=>s.has(i.name)?!1:(s.add(i.name),!0))}function Bi(t,e){let n=je(e),r=We(t,n),s=[],i=[];try{let o=hp.parse(e);s=yp(o,t),i=kp(o)}catch{}return{imports:s,exports:i,tags:Array.from(n).map(o=>({name:o,kind:"comment-marker"})),category:r}}var Sp=["http://","https://","mailto:","//"],vp="ts|tsx|js|jsx|mjs|cjs|py|go|lua|css|scss|less|styl|coffee|ls|feature|md|mdx|json",Cp=new RegExp(`(?:\\.{1,2}/)?[\\w.-]+(?:/[\\w.-]+)*\\.(?:${vp})\\b`,"g"),Ui;async function wp(){return Ui??=(async()=>{let{unified:t}=await import("unified"),e=(await import("remark-parse")).default;return t().use(e)})(),Ui}function Ep(t){let e=t.trim();return e.length===0||e.startsWith("#")||Sp.some(n=>e.startsWith(n))}function Tp(t,e){let n=t.match(Cp);return n?n.map(r=>({fromPath:e,toPath:"",rawSpecifier:r,isStyle:!1,type:"static",isDocReference:!0})):[]}function Ki(t,e,n){if(t.type==="link"&&typeof t.url=="string"&&!Ep(t.url)&&n.push({fromPath:e,toPath:"",rawSpecifier:t.url,isStyle:!1,type:"static",isDocReference:!0}),(t.type==="code"||t.type==="inlineCode")&&typeof t.value=="string"&&n.push(...Tp(t.value,e)),Array.isArray(t.children))for(let r of t.children)Ki(r,e,n)}async function Hi(t,e){let r=(await wp()).parse(e),s=[];Ki(r,t,s);let i=new Set;return{imports:s.filter(a=>i.has(a.rawSpecifier)?!1:(i.add(a.rawSpecifier),!0)),exports:[],tags:[],category:"other"}}import Np from"path";import{parser as Mp}from"@lezer/python";function Fp(t){let e=1;function n(r){switch(r.type.name){case"IfStatement":{e+=Ee(r).filter(i=>i.type.name==="if"||i.type.name==="elif").length;break}case"TryStatement":{e+=Ee(r).filter(i=>i.type.name==="except").length;break}case"ForStatement":case"WhileStatement":case"ConditionalExpression":e++;break;case"and":case"or":e++;break}let s=r.firstChild;for(;s;)n(s),s=s.nextSibling}return n(t),e}function Dp(t,e){let n=0,r=Ee(t),s=0,i=0;for(;i<r.length;){let o=r[i];if(o?.type.name==="if"||o?.type.name==="elif"){let a=s>0;n+=a?1:1+e;let c=a?e:e+1,l=r[i+1],p=r[i+2];l&&(n+=ie(l,c)),p&&(n+=ie(p,c)),s++,i+=3}else if(o?.type.name==="else"){n+=1;let a=r[i+1];a&&(n+=ie(a,e+1)),i+=2}else i++}return n}function Pp(t,e){let n=0,r=Ee(t),s=0;for(;s<r.length;){let i=r[s];if(i?.type.name==="except"){for(n+=1+e,s++;s<r.length&&r[s]?.type.name!=="Body";)n+=ie(r[s],e),s++;s<r.length&&(n+=ie(r[s],e),s++)}else i?.type.name==="Body"&&(n+=ie(i,e)),s++}return n}function Ji(t,e){let n=1+e,r=t.firstChild;for(;r;)n+=ie(r,e+1),r=r.nextSibling;return n}function Ap(t,e){let n=0,r=t.firstChild;for(;r;)n+=ie(r,e),r=r.nextSibling;return n}function ie(t,e){let n=t.type.name;switch(n){case"IfStatement":return Dp(t,e);case"TryStatement":return Pp(t,e);case"ForStatement":case"WhileStatement":return Ji(t,e);default:{let r=n==="ConditionalExpression"||n==="and"||n==="or"?1:0;return e>0&&(n==="FunctionDefinition"||n==="LambdaExpression")?r+Ji(t,e):r+Ap(t,e)}}}function Rp(t){return ie(t,0)}function Wr(t){return{complexity:Fp(t),cognitiveComplexity:Rp(t)}}function Vi(t,e){let n=[];function r(o,a){let{complexity:c,cognitiveComplexity:l}=Wr(o);n.push({name:a,line:Te(e,o.from),complexity:c,cognitiveComplexity:l})}function s(o){let a=o.firstChild;for(;a;)i(a),a=a.nextSibling}function i(o){if(o.type.name==="ClassDefinition"){let a=o.getChild("VariableName"),c=a?e.slice(a.from,a.to):void 0,l=o.getChild("Body");if(l){let p=l.firstChild;for(;p;){if(p.type.name==="FunctionDefinition"){let u=p.getChild("VariableName"),f=u?e.slice(u.from,u.to):void 0;f&&r(p,c?`${c}.${f}`:f),s(p)}else i(p);p=p.nextSibling}}return}if(o.type.name==="FunctionDefinition"){let a=o.getChild("VariableName");a&&r(o,e.slice(a.from,a.to)),s(o);return}s(o)}return i(t.topNode),n}var Ip=new Set(["pytest","unittest","nose","hypothesis"]);function Qi(t,e){let n=[],r=[],s=new Set,i=Np.basename(t).toLowerCase(),o=Mp.parse(e),a=o.cursor();do switch(a.name){case"Comment":{let m=e.slice(a.from,a.to).match(/#\s*@tag\s+([a-zA-Z0-9_-]+)/);m?.[1]&&s.add(m[1]);break}case"ImportStatement":{for(let m of Lp(a.node,e,t))n.push(m);break}case"FunctionDefinition":case"ClassDefinition":{let m=a.node.parent;if(m?.name==="Script"||m?.name==="DecoratedStatement"&&m.parent?.name==="Script"){let b=a.node.getChild("VariableName");b&&r.push({name:e.slice(b.from,b.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let m=a.node.firstChild;m?.name==="VariableName"&&r.push({name:e.slice(m.from,m.to)})}break}}while(a.next());let c=$p(i,n,s);c==="test"&&s.add("test");let{complexity:l,cognitiveComplexity:p}=Wr(o.topNode),u=Vi(o,e),f=c==="test"?[]:Wp(o,e);return{imports:n,exports:r,tags:Array.from(s).map(m=>({name:m,kind:"comment-marker"})),category:c,rawCallEdges:f,complexity:l,cognitiveComplexity:p,...u.length>0?{functions:u}:{}}}function Lp(t,e,n){let r=t.firstChild;return r?r.name==="from"?_p(t,e,n):Gp(t,e,n):[]}function _p(t,e,n){let r=t.firstChild;if(!r)return[];let s=r.nextSibling;for(;s&&s.name!=="import";)s=s.nextSibling;if(!s)return[];let i=e.slice(r.to,s.from).trim(),o=Op(s.nextSibling,e);if(!o.length)return[];let a=0;for(;a<i.length&&i[a]===".";)a++;let c=i.slice(a);if(a===0)return[ht(n,i,o,!0)];let l=a===1?"./":"../".repeat(a-1);return c?[ht(n,l+c.replace(/\./g,"/"),o,!1)]:o[0]==="*"?[ht(n,l.slice(0,-1),["*"],!1)]:o.map(p=>ht(n,l+p,[p],!1))}function Gp(t,e,n){let r=[],s=t.firstChild?.nextSibling??null;for(;s;){if(s.name==="VariableName"){let i=e.slice(s.from,s.to);for(;s.nextSibling?.name==="."&&s.nextSibling.nextSibling?.name==="VariableName";)s=s.nextSibling.nextSibling,i+=`.${e.slice(s.from,s.to)}`;s.nextSibling?.name==="as"&&(s=s.nextSibling.nextSibling??s.nextSibling),r.push(ht(n,i,["*"],!0))}s=s.nextSibling}return r}function Op(t,e){let n=[],r=t;for(;r;)r.name==="*"?n.push("*"):r.name==="VariableName"&&(n.push(e.slice(r.from,r.to)),r.nextSibling?.name==="as"&&(r=r.nextSibling.nextSibling??r.nextSibling)),r=r.nextSibling;return n}function jp(t,e){let n=new Map,r=t.cursor();do{if(r.name!=="ImportStatement")continue;let i=r.node.firstChild;if(i?.type.name!=="from")continue;let o=i.nextSibling;for(;o&&o.type.name!=="import";)o=o.nextSibling;if(!o)continue;let a=e.slice(i.to,o.from).trim(),c=0;for(;c<a.length&&a[c]===".";)c++;let l=a.slice(c),p=c<=1?"./":"../".repeat(c-1),u=o.nextSibling;for(;u;){if(u.type.name==="VariableName"){let f=e.slice(u.from,u.to),m=f;if(u.nextSibling?.type.name==="as"){let b=u.nextSibling.nextSibling;b?.type.name==="VariableName"&&(m=e.slice(b.from,b.to),u=b)}let h=c===0?a:l?p+l.replace(/\./g,"/"):p+f;n.set(m,h)}u=u.nextSibling}}while(r.next());return n}function Wp(t,e){let n=jp(t,e),r=[];function s(a,c){if(a.type.name==="CallExpression"&&a.firstChild?.type.name==="VariableName"){let p=a.firstChild,u=e.slice(p.from,p.to),f=n.get(u);f&&r.push({from:c,to:u,toSpecifier:f})}let l=a.firstChild;for(;l;)s(l,c),l=l.nextSibling}function i(a){let c=a.firstChild;for(;c;)o(c),c=c.nextSibling}function o(a){if(a.type.name==="ClassDefinition"){let c=a.getChild("VariableName"),l=c?e.slice(c.from,c.to):void 0,p=a.getChild("Body");if(p){let u=p.firstChild;for(;u;){if(u.type.name==="FunctionDefinition"){let f=u.getChild("VariableName"),m=f?e.slice(f.from,f.to):void 0;m&&s(u,l?`${l}.${m}`:m)}else o(u);u=u.nextSibling}}return}if(a.type.name==="FunctionDefinition"){let c=a.getChild("VariableName");c&&s(a,e.slice(c.from,c.to));return}i(a)}return o(t.topNode),r}function ht(t,e,n,r){return{fromPath:t,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:r,type:"static",symbols:n.length>0?n:void 0}}function $p(t,e,n){return t.startsWith("test_")||t.endsWith("_test.py")?"test":t==="conftest.py"||t==="setup.py"?"config":n.has("test")||e.some(r=>Ip.has(r.rawSpecifier))?"test":"logic"}var zp=/^\s*import\s+(.+?)\s*$/,Bp=/^(?:@\w+\s+)*(?:private\s+|protected\s+|final\s+|sealed\s+|abstract\s+|implicit\s+|case\s+)*(class|trait|object|type|enum)\s+([A-Za-z_$][A-Za-z0-9_$]*)/;function Up(t,e){let n=e.split("=>")[0]?.trim();return n?n==="_"||n==="*"||n==="given"?`${t}.*`:`${t}.${n}`:null}function Kp(t){let e=t.indexOf("{");if(e!==-1){let r=t.indexOf("}",e),s=t.slice(0,e).trim().replace(/\.$/,""),i=t.slice(e+1,r===-1?void 0:r);return s?i.split(",").map(o=>Up(s,o.trim())).filter(o=>o!=null):[]}let n=[];for(let r of t.split(",")){let s=r.trim().replace(/\s+as\s+\w+$/,"");if(s)if(s.endsWith("._")||s.endsWith(".*")||s.endsWith(".given")){let i=s.replace(/\.(_|\*|given)$/,"");i&&n.push(`${i}.*`)}else n.push(s)}return n}function Yi(t,e){let n=Be(e),s=he(e).split(`
11
+ `),i=[],o=new Set;for(let l of s){let p=l.match(zp);if(p?.[1]){for(let f of Kp(p[1]))i.push(Ke(t,f));continue}let u=l.match(Bp);u?.[2]&&o.add(u[2])}let a=q(e,!0);a&&i.push(ye(t,a));let c=Array.from(o,l=>({name:l}));return{imports:i,exports:c,tags:Array.from(n).map(l=>({name:l,kind:"comment-marker"})),category:se(t,i.map(l=>l.rawSpecifier),{typeNames:[...o],annotations:Ue(e).annotations})}}import eo from"path";import y from"typescript";import C from"typescript";function Hp(t){let e=1;function n(r){switch(r.kind){case C.SyntaxKind.IfStatement:case C.SyntaxKind.ConditionalExpression:case C.SyntaxKind.ForStatement:case C.SyntaxKind.ForInStatement:case C.SyntaxKind.ForOfStatement:case C.SyntaxKind.WhileStatement:case C.SyntaxKind.DoStatement:case C.SyntaxKind.CatchClause:case C.SyntaxKind.CaseClause:e++;break;case C.SyntaxKind.BinaryExpression:{let s=r.operatorToken.kind;(s===C.SyntaxKind.AmpersandAmpersandToken||s===C.SyntaxKind.BarBarToken||s===C.SyntaxKind.QuestionQuestionToken)&&e++;break}}C.forEachChild(r,n)}return n(t),e}function Zi(t,e,n){let r=n?1:1+e,s=n?e:e+1;return r+=De(t.expression,s,!1),r+=De(t.thenStatement,s,!1),t.elseStatement&&(C.isIfStatement(t.elseStatement)?r+=Zi(t.elseStatement,e,!0):r+=1+De(t.elseStatement,e+1,!1)),r}function Xi(t,e){let n=1+e;return C.forEachChild(t,r=>{n+=De(r,e+1,!1)}),n}function Jp(t,e){let n=1+e;return C.forEachChild(t,r=>{n+=De(r,e,!1)}),n}function Vp(t,e){let n=0;return C.forEachChild(t,r=>{n+=De(r,e,!1)}),n}function Qp(t){let e=t.operatorToken.kind;return e===C.SyntaxKind.AmpersandAmpersandToken||e===C.SyntaxKind.BarBarToken||e===C.SyntaxKind.QuestionQuestionToken}function De(t,e,n){if(C.isIfStatement(t))return Zi(t,e,n);if(C.isForStatement(t)||C.isForInStatement(t)||C.isForOfStatement(t)||C.isWhileStatement(t)||C.isDoStatement(t)||C.isSwitchStatement(t))return Xi(t,e);if(C.isCatchClause(t))return Jp(t,e);let r=0;return C.isConditionalExpression(t)&&(r+=1),C.isBinaryExpression(t)&&Qp(t)&&(r+=1),e>0&&(C.isFunctionDeclaration(t)||C.isFunctionExpression(t)||C.isArrowFunction(t))?r+Xi(t,e):r+Vp(t,e)}function Yp(t){return De(t,0,!1)}function $r(t){return{complexity:Hp(t),cognitiveComplexity:Yp(t)}}import E from"typescript";var zr=new Set(["test","describe","it"]);function qi(t,e){Xp(t,e),qp(t,e),eu(t,e)}function Xp(t,e){if((E.isFunctionDeclaration(t)||E.isVariableDeclaration(t))&&t.name&&E.isIdentifier(t.name)&&Zp(t)){let n;if(E.isFunctionDeclaration(t))n="function";else{let r=t.initializer;n=r&&(E.isArrowFunction(r)||E.isFunctionExpression(r))?"function":"variable"}e.tags.add({name:t.name.text,kind:n})}}function Zp(t){if(E.isFunctionDeclaration(t))return E.isSourceFile(t.parent);let e=t.parent?.parent;return!!e&&E.isSourceFile(e.parent)}function qp(t,e){if(!E.isSourceFile(t))return;let n=/@tag\s+([a-zA-Z0-9_-]+)/g,r=t.getFullText(),s=n.exec(r);for(;s!==null;)s[1]&&e.tags.add({name:s[1],kind:"comment-marker"}),s=n.exec(r)}function eu(t,e){if(!E.isCallExpression(t)||!tu(t.expression))return;let[n]=t.arguments;if(n&&E.isStringLiteral(n))for(let r of n.text.match(/@[\w-]+/g)??[])e.tags.add({name:r.substring(1),kind:"comment-marker"});for(let r of t.arguments)E.isObjectLiteralExpression(r)&&nu(r,e)}function tu(t){return E.isIdentifier(t)?zr.has(t.text):!!(E.isPropertyAccessExpression(t)&&(zr.has(t.name.text)||E.isIdentifier(t.expression)&&zr.has(t.expression.text)))}function nu(t,e){for(let n of t.properties){if(!E.isPropertyAssignment(n)||!E.isIdentifier(n.name)||n.name.text!=="tags"&&n.name.text!=="tag")continue;let{initializer:r}=n,s=E.isArrayLiteralExpression(r)?r.elements.filter(E.isStringLiteral):n.name.text==="tag"&&E.isStringLiteral(r)?[r]:[];for(let i of s)e.tags.add({name:i.text.replace(/^@/,""),kind:"comment-marker"})}}function Br(t,e,n){let r=[],s=new Map,i=new Set,o=y.createSourceFile(t,e,y.ScriptTarget.Latest,!0,n==="typescript"?y.ScriptKind.TSX:y.ScriptKind.JSX),a={filePath:t,imports:r,exports:s,tags:i,rawCallEdges:[],sourceFile:o,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},c=b=>{ou(b,a),y.forEachChild(b,c)};c(o);let l=yu(t,a);(l==="test"||l==="barrel")&&i.add({name:l,kind:"comment-marker"}),l!=="test"&&xu(a,o);let p=o.statements[0],u=p?no(p):void 0,{complexity:f,cognitiveComplexity:m}=$r(o),h=ru(o);return{imports:r,exports:Array.from(s.values()),tags:Array.from(i),category:l,rawCallEdges:a.rawCallEdges??[],complexity:f,cognitiveComplexity:m,...h.length>0?{functions:h}:{},...u!==void 0?{description:u}:{}}}function ru(t){let e=[],n=(s,i)=>{let{complexity:o,cognitiveComplexity:a}=$r(i),c=t.getLineAndCharacterOfPosition(i.getStart(t)).line+1;e.push({name:s,line:c,complexity:o,cognitiveComplexity:a})},r=(s,i)=>{if(y.isFunctionDeclaration(s)&&s.name&&s.body?n(s.name.text,s):y.isVariableDeclaration(s)&&y.isIdentifier(s.name)&&s.initializer&&(y.isArrowFunction(s.initializer)||y.isFunctionExpression(s.initializer))?n(s.name.text,s.initializer):i&&y.isMethodDeclaration(s)&&y.isIdentifier(s.name)&&s.body?n(`${i}.${s.name.text}`,s):i&&y.isConstructorDeclaration(s)&&s.body?n(`${i}.constructor`,s):i&&y.isGetAccessorDeclaration(s)&&y.isIdentifier(s.name)&&s.body?n(`${i}.get ${s.name.text}`,s):i&&y.isSetAccessorDeclaration(s)&&y.isIdentifier(s.name)&&s.body&&n(`${i}.set ${s.name.text}`,s),y.isClassDeclaration(s)&&s.name){let o=s.name.text;y.forEachChild(s,a=>r(a,o));return}y.forEachChild(s,o=>r(o,i))};return r(t,void 0),e}function to(t,e,n,r){let s={name:t},i=no(n);i!==void 0&&(s.doc=i);let o=su(e);o!==void 0&&(s.flags=o);let a=iu(e,r);return a!==void 0&&(s.signature=a),s}function no(t){let e=y.getJSDocCommentsAndTags(t);for(let n of e)if(y.isJSDoc(n)&&n.comment)return y.getTextOfJSDocComment(n.comment)||void 0}function su(t){let e=new Set(["deprecated","internal","public","alpha","beta"]),n=y.getJSDocTags(t).map(r=>r.tagName.text).filter(r=>e.has(r));return n.length>0?n:void 0}function iu(t,e){let n=y.createPrinter({removeComments:!0}),r=s=>n.printNode(y.EmitHint.Unspecified,s,e);if(y.isFunctionDeclaration(t)||y.isMethodDeclaration(t)){let s=t.parameters.map(r).join(", "),i=t.type?r(t.type):"void";return`${t.typeParameters?`<${t.typeParameters.map(a=>a.name.text).join(", ")}>`:""}(${s}) => ${i}`}if(y.isVariableDeclaration(t)){if(t.type)return r(t.type);if(t.initializer&&(y.isArrowFunction(t.initializer)||y.isFunctionExpression(t.initializer))){let s=t.initializer,i=s.parameters.map(r).join(", "),o=s.type?r(s.type):"unknown";return`(${i}) => ${o}`}return}if(y.isClassDeclaration(t)&&t.name)return`class ${t.name.text}`;if(y.isInterfaceDeclaration(t))return`interface ${t.name.text}`;if(y.isTypeAliasDeclaration(t))return r(t.type);if(y.isEnumDeclaration(t))return`enum ${t.name.text}`}function ou(t,e){au(t,e),cu(t,e),pu(t,e),uu(t,e),hu(t,e),qi(t,e)}function au(t,e){if(!y.isSourceFile(t))return;let n=t.statements.filter(r=>!y.isEmptyStatement(r));e.totalStatements=n.length,e.exportStatements=n.filter(r=>y.isExportDeclaration(r)||y.isExportAssignment(r)||Ur(r)).length}function cu(t,e){if(y.isJsxElement(t)||y.isJsxSelfClosingElement(t)||y.isJsxFragment(t)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(y.isFunctionDeclaration(t)||y.isMethodDeclaration(t)||y.isArrowFunction(t)||y.isClassDeclaration(t)||y.isVariableStatement(t)||y.isEnumDeclaration(t)){e.hasTypesOnly=!1;return}y.isExportDeclaration(t)&&!lu(t)&&(e.hasTypesOnly=!1)}function lu(t){return t.isTypeOnly?!0:!t.exportClause||!y.isNamedExports(t.exportClause)?!1:t.exportClause.elements.every(e=>e.isTypeOnly)}function pu(t,e){if(!y.isImportDeclaration(t)||!t.moduleSpecifier||!y.isStringLiteral(t.moduleSpecifier))return;let n=[];if(t.importClause&&(t.importClause.name&&n.push("default"),t.importClause.namedBindings))if(y.isNamedImports(t.importClause.namedBindings))for(let s of t.importClause.namedBindings.elements)n.push(s.name.text);else y.isNamespaceImport(t.importClause.namedBindings)&&n.push("*");let r=n.length>0?"static":"side-effect";e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.moduleSpecifier.text,isStyle:W(t.moduleSpecifier.text),type:r,symbols:n.length>0?n:void 0})}function uu(t,e){y.isExportDeclaration(t)?fu(t,e):y.isExportAssignment(t)?e.exports.set("default",{name:"default"}):Ur(t)&&du(t,e)}function fu(t,e){if(t.moduleSpecifier&&y.isStringLiteral(t.moduleSpecifier))mu(t,t.moduleSpecifier.text,e);else if(t.exportClause&&y.isNamedExports(t.exportClause))for(let n of t.exportClause.elements){let r=n.name.text;e.exports.set(r,{name:r})}}function mu(t,e,n){let r=gu(t),s={fromPath:n.filePath,toPath:"",rawSpecifier:e,isStyle:W(e),type:"re-export"};r.length>0&&(s.symbols=r),n.imports.push(s)}function gu(t){return t.exportClause?y.isNamedExports(t.exportClause)?t.exportClause.elements.map(e=>e.name.text):[]:["*"]}function du(t,e){if((y.isFunctionDeclaration(t)||y.isClassDeclaration(t)||y.isInterfaceDeclaration(t)||y.isTypeAliasDeclaration(t)||y.isEnumDeclaration(t))&&t.name){let r=t.name.text;e.exports.set(r,to(r,t,t,e.sourceFile));return}if(y.isVariableStatement(t)){for(let r of t.declarationList.declarations)if(y.isIdentifier(r.name)){let s=r.name.text;e.exports.set(s,to(s,r,t,e.sourceFile))}}}function hu(t,e){if(!y.isCallExpression(t))return;let n=t.arguments[0];!n||!y.isStringLiteral(n)||(t.expression.kind===y.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:n.text,isStyle:W(n.text),type:"dynamic"}):y.isIdentifier(t.expression)&&t.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:n.text,isStyle:W(n.text),type:"require"}))}function yu(t,e){let n=eo.basename(t).toLowerCase(),r=eo.extname(t).toLowerCase();return ut().some(i=>n.includes(i))?"test":qs(n)?"config":e.imports.some(i=>cr().some(o=>i.rawSpecifier.includes(o)))?"test":r===".tsx"||r===".jsx"||e.hasUI?"ui":e.hasTypesOnly&&e.totalStatements>0?"type-only":e.totalStatements>0&&e.exportStatements/e.totalStatements>ur()?"barrel":"logic"}function Ur(t){return y.canHaveModifiers(t)&&y.getModifiers(t)?.some(e=>e.kind===y.SyntaxKind.ExportKeyword)===!0}function xu(t,e){let n=t.rawCallEdges??[];t.rawCallEdges=n;let r=new Map;for(let s of e.statements){if(!y.isImportDeclaration(s)||!y.isStringLiteral(s.moduleSpecifier))continue;let i=s.moduleSpecifier.text,o=s.importClause;if(o&&(o.name&&r.set(o.name.text,i),o.namedBindings&&y.isNamedImports(o.namedBindings)))for(let a of o.namedBindings.elements)r.set(a.name.text,i)}if(r.size!==0)for(let s of e.statements){let i=ku(s);if(i){let o=Su(s);o&&nn(o,i,r,n);continue}y.isClassDeclaration(s)&&s.name&&bu(s,s.name.text,r,n)}}function bu(t,e,n,r){for(let s of t.members)y.isMethodDeclaration(s)&&s.body&&y.isIdentifier(s.name)?nn(s.body,`${e}.${s.name.text}`,n,r):y.isConstructorDeclaration(s)&&s.body&&nn(s.body,`${e}.constructor`,n,r)}function ku(t){if(Ur(t)){if(y.isFunctionDeclaration(t)&&t.name)return t.name.text;if(y.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(y.isIdentifier(e.name)&&e.initializer&&(y.isArrowFunction(e.initializer)||y.isFunctionExpression(e.initializer)))return e.name.text}}}function Su(t){if(y.isFunctionDeclaration(t))return t.body;if(y.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(e.initializer&&(y.isArrowFunction(e.initializer)||y.isFunctionExpression(e.initializer)))return e.initializer}}function nn(t,e,n,r){if(y.isCallExpression(t)&&y.isIdentifier(t.expression)){let s=t.expression.text,i=n.get(s);i&&!r.some(o=>o.from===e&&o.to===s&&o.toSpecifier===i)&&r.push({from:e,to:s,toSpecifier:i})}y.forEachChild(t,s=>nn(s,e,n,r))}function rn(t,e){if(e.length===0)return"ui";let n=!1;return t.walk(r=>{if(r.type==="rule")return n=!0,!1}),n?"ui":"barrel"}import so from"postcss";import*as vu from"postcss-less";var Cu=vu,io=new Set(["reference","inline"]);function ro(t){return t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||t.startsWith("data:")}function wu(t){let e=t.trim();return e.length>0&&!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("//")&&!e.startsWith("data:")&&!e.startsWith("#")}function Eu(t,e){let n=t.match(/^\(([^)]+)\)\s+['"]([^'"]+)['"]/);if(n){let i=n[1]?.trim()??"",o=n[2]??"";if(!o)return null;let a=io.has(i)?"side-effect":"static";return{fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:a,...ro(o)?{isExternal:!0}:{}}}let r=t.match(/^url\(['"]?([^'")]+)['"]?\)/),s=r?r[1]?.trim()??"":t.match(/^['"]([^'"]+)['"]/)?.[1]??"";return s?{fromPath:e,toPath:"",rawSpecifier:s,isStyle:!0,type:"static",...ro(s)?{isExternal:!0}:{}}:null}function Tu(t,e){let n=[],r=/url\(['"]?([^'")]+)['"]?\)/g,s=r.exec(t);for(;s!==null;){let i=s[1]?.trim()??"";wu(i)&&n.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"static"}),s=r.exec(t)}return n}function oo(t,e){let n=[];return t.walk(r=>{if(r.type==="atrule"&&r.name==="import"){let s=Eu(r.params,e);s&&n.push(s)}r.type==="decl"&&n.push(...Tu(r.value,e))}),n}function Fu(t){return t.replace(/(?<!:)\/\/.*/g,"")}function Du(t,e){let n=[],r=/@import\s+(?:\(([^)]+)\)\s+)?['"]([^'"]+)['"]/g,s=r.exec(t);for(;s!==null;){let i=s[1]?.trim()??"",o=s[2]??"";if(o){let a=io.has(i)?"side-effect":"static";n.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:a})}s=r.exec(t)}return n}function sn(t,e){let n=so.parse(Fu(t));return{imports:oo(n,e),root:n}}function Pu(t){let e=[],n=[];for(let r of t.nodes??[]){if(r.type!=="atrule")continue;let{value:s}=r;if(s===void 0)continue;let i=r.name;i&&(e.push({name:i}),n.push({name:i,kind:"variable"}))}return{exports:e,tags:n}}function on(t,e){try{let n=Cu.parse(t),{exports:r,tags:s}=Pu(n);return{imports:oo(n,e),root:n,exports:r,tags:s}}catch{return{imports:Du(t,e),root:so.parse(""),exports:[],tags:[]}}}import{parse as Au}from"postcss-scss";function ao(t){return t.startsWith("_")||t.startsWith("-")}function Ru(t){return!!(t.startsWith("sass:")||t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||!t.startsWith(".")&&!t.startsWith("/")&&!t.startsWith("_"))}function Nu(t){let e=t.match(/^['"]([^'"]+)['"]/);if(!e?.[1])return{specifier:""};let n=e[1],s=t.match(/\bas\s+(\S+)/)?.[1];return s!==void 0?{specifier:n,alias:s}:{specifier:n}}function Mu(t){let e=[],n=[];for(let r of t.nodes??[]){if(r.type==="decl"&&r.prop.startsWith("$")){let s=r.prop.slice(1);if(!s||ao(s))continue;e.push({name:s}),n.push({name:s,kind:"variable"});continue}if(r.type==="atrule"&&(r.name==="mixin"||r.name==="function")){let i=r.params.match(/^([\w-]+)/)?.[1];if(!i||ao(i))continue;let o=r.params.trim();e.push(o.includes("(")?{name:i,signature:o}:{name:i}),n.push({name:i,kind:"function"})}}return{exports:e,tags:n}}function an(t,e){let n=Au(t),r=[];n.walk(o=>{if(o.type!=="atrule")return;let{name:a,params:c}=o;if(a!=="import"&&a!=="use"&&a!=="forward")return;let{specifier:l,alias:p}=Nu(c);if(!l)return;let u={fromPath:e,toPath:"",rawSpecifier:l,isStyle:!0,type:a==="forward"?"re-export":"static",...Ru(l)?{isExternal:!0}:{}};p&&(u.symbols=[p]),r.push(u)});let{exports:s,tags:i}=Mu(n);return{imports:r,root:n,exports:s,tags:i}}function co(t,e){let n=[],r=/@require\s+['"]([^'"]+)['"]/g,s=r.exec(t);for(;s!==null;){let o=s[1];o&&n.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"require"}),s=r.exec(t)}let i=/(?<!@)(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g;for(s=i.exec(t);s!==null;){let o=s[1];o&&n.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"static"}),s=i.exec(t)}return n}function lo(t,e){if(e.length===0)return"ui";try{let n=Zn("stylus");return new n.Parser(t).parse().nodes.some(i=>i.constructor.name!=="Import")?"ui":"barrel"}catch{return t.replace(/^\s*@?(?:require|import)\b.*/gm,"").trim().length>0?"ui":"barrel"}}function yt(t,e){let n=J(t);if(n==="stylus"){let i=co(e,t);return{imports:i,exports:[],tags:[],category:lo(e,i)}}if(n==="scss"){let{imports:i,root:o,exports:a,tags:c}=an(e,t);return{imports:i,exports:a,tags:c,category:rn(o,i)}}if(n==="less"){let{imports:i,root:o,exports:a,tags:c}=on(e,t);return{imports:i,exports:a,tags:c,category:rn(o,i)}}let{imports:r,root:s}=sn(e,t);return{imports:r,exports:[],tags:[],category:rn(s,r)}}for(let[t,e]of[["javascript",(n,r)=>Br(n,r,"javascript")],["typescript",(n,r)=>Br(n,r,"typescript")],["css",yt],["scss",yt],["less",yt],["stylus",yt],["coffeescript",Di],["livescript",zi],["lua",Bi],["python",Qi],["go",Li],["java",Wi],["kotlin",$i],["scala",Yi],["groovy",_i],["gherkin",Rr],["markdown",Hi]])$e(t,e);async function po(t,e){let n=J(t),r=Ai(n);return r?r(t,e):{imports:[],exports:[],tags:[],category:"other"}}import uo from"path";function Iu(t,e){let n=e.get(t.path);n!==void 0&&(t.coveragePct=n)}function mo(t,e){for(let n of t)if(n.isExternal){let r=n.rawSpecifier.startsWith("@")?n.rawSpecifier.split("/").slice(0,2).join("/"):n.rawSpecifier.split("/")[0];r&&!e.some(s=>s.name===r)&&e.push({name:r,kind:"library"})}}function Lu(t,e,n){if(e.isExternal||!e.toPath)return;let r=n.get(e.toPath);r&&(r.category!=="logic"&&r.category!=="barrel"||(r.testedBy??=[],r.testedBy.includes(t.path)||r.testedBy.push(t.path)))}function _u(t,e){if(t.type==="markdown")for(let n of t.imports){if(n.isExternal||!n.toPath)continue;let r=e.get(n.toPath);!r||r===t||(r.documentedBy??=[],r.documentedBy.includes(t.path)||r.documentedBy.push(t.path),r.category==="logic"&&(r.lastCommitAt??0)>(t.lastCommitAt??0)&&(t.staleFor??=[],t.staleFor.includes(r.path)||t.staleFor.push(r.path)))}}function fo(t){return Math.round(t*1e4)/1e4}function Gu(t,e){let n=[];for(let r of t.imports){if(r.isExternal||!r.toPath)continue;let s=e.get(r.toPath);if(!s||s.exports.length===0)continue;let i;if(r.symbols===void 0){if(r.type==="side-effect")continue;i=1}else r.symbols.includes("*")?i=1:i=r.symbols.length/s.exports.length;r.exportUsageRatio=fo(Math.min(1,i)),n.push(r.exportUsageRatio)}n.length>0&&(t.avgExportUsage=fo(n.reduce((r,s)=>r+s,0)/n.length),t.maxExportUsage=Math.max(...n))}function go(t,e,n){e&&(t.some(r=>r.name===e&&r.kind===n)||t.push({name:e,kind:n}))}function Ou(t,e){let n=e.toPath,r=uo.basename(n,uo.extname(n)).replace(/\.(test|spec)$/,"");go(t.tags,r,"import")}function ju(t,e,n){let r=n.get(e.toPath);if(!(!r||r.category==="test"))for(let s of r.tags)s.kind==="comment-marker"&&go(t.tags,s.name,"comment-marker")}function Wu(t,e,n){!e.toPath||e.isExternal||(Ou(t,e),ju(t,e,n))}function ho(t,e){for(let n of t.values())delete n.testedBy,delete n.documentedBy,delete n.staleFor,n.category==="test"&&(n.tags=n.tags.filter(r=>r.kind!=="import"));for(let n of t.values()){if(Gu(n,t),e.size>0&&Iu(n,e),n.category==="test")for(let r of n.imports)Lu(n,r,t),Wu(n,r,t);_u(n,t)}}var yo=new Set(["java","kotlin","scala","groovy"]),xo=new Set(["typescript","javascript","python","go","java","kotlin","scala","groovy","scss","less","lua","coffeescript"]),bo=new Set(["typescript","javascript","python","java","kotlin","scala","groovy"]),xt=new Set(["typescript","javascript","go","python","java"]),ko=new Set(["typescript","javascript","go","python","java"]);var So=new Set(["typescript","javascript"]),$u={callEdges:xt,functionComplexity:ko,typeGraph:So},zu={callEdges:"call edges",functionComplexity:"per-function complexity",typeGraph:"type extraction"};function Je(t,e){let n=Array.isArray(t)?t:[t],r=$u[e],s=new Set;for(let c of n)for(let l of c.nodes.values()){if(r.has(l.type))return;l.type!=="markdown"&&l.type!=="unknown"&&s.add(l.type)}let i=[...s].sort(),o=i.length===0?"this project":i.join(", "),a=i.length===1?"is":"are";return`${zu[e]} is only tracked for ${[...r].sort().join(", ")} \u2014 ${o} ${a} unsupported, so this result is empty by design.`}function A(t,e,n,r,s,i,o,a){return{importResolution:t,exportSymbols:e,importSymbols:n,callEdges:r,complexity:s,category:i,duplication:o,testTags:a}}var Kr={typescript:A("full","full","full","full","full","full","partial","full"),javascript:A("full","full","full","full","full","full","partial","full"),python:A("full","partial","partial","full","full","partial","partial","full"),go:A("full","partial","none","full","full","partial","partial","full"),java:A("partial","partial","partial","partial","full","partial","partial","full"),kotlin:A("partial","partial","partial","none","none","partial","partial","full"),scala:A("partial","partial","partial","none","none","partial","partial","full"),groovy:A("partial","partial","partial","none","none","partial","partial","full"),coffeescript:A("partial","partial","none","none","none","partial","partial","none"),livescript:A("partial","none","none","none","none","partial","partial","none"),lua:A("partial","partial","none","none","none","partial","partial","none"),css:A("full","none","none","none","none","full","full","none"),scss:A("full","partial","none","none","none","full","full","none"),less:A("full","partial","none","none","none","full","full","none"),stylus:A("full","none","none","none","none","full","partial","none"),gherkin:A("none","none","none","none","none","full","partial","full"),markdown:A("partial","none","none","none","none","full","partial","none"),unknown:A("none","none","none","none","none","none","none","none")},Bu={importResolution:"import resolution",exportSymbols:"export symbols",importSymbols:"per-import symbol tracking",callEdges:"call edges",complexity:"complexity",category:"category classification",duplication:"duplicate detection",testTags:"test-tag strategy"},Uu={python:{exportSymbols:"tracked at module level, not per-symbol",importSymbols:"only star imports and re-exports are tracked (ADR-002)"},go:{exportSymbols:"identifier-level, no per-symbol doc/signature",importSymbols:"not tracked \u2014 per-import symbol resolution is not implemented"},java:{importResolution:"index-based: matched by type name across the module, not by resolving the exact package path (ADR-017)",exportSymbols:"top-level types only, no field/method-level exports",importSymbols:"one symbol per import (the FQN's last segment, or the static member for `import static`); wildcard imports carry none, and re-exports aren't tracked",callEdges:"static calls and constructors only (incl. through generics), not virtual dispatch"},kotlin:{importResolution:"index-based, shared with Java's JvmLangResolver (ADR-017)",exportSymbols:"top-level types only",importSymbols:"one symbol per import (the FQN's last segment); wildcard imports carry none, and re-exports aren't tracked",callEdges:"not extracted \u2014 Kotlin needs its own grammar (issue 8c)",complexity:"not computed \u2014 Kotlin needs its own grammar (issue 8c)"},scala:{importResolution:"index-based, shared with Java's JvmLangResolver; brace-package imports are a known gap",exportSymbols:"top-level types only",importSymbols:"one symbol per import (the FQN's last segment, brace groups expanded to one edge per member); wildcard imports carry none, and re-exports aren't tracked",callEdges:"not extracted \u2014 Scala needs its own grammar (issue 8c)",complexity:"not computed \u2014 Scala needs its own grammar (issue 8c)"},groovy:{importResolution:"index-based, shared with Java's JvmLangResolver",exportSymbols:"top-level types only",importSymbols:"one symbol per import (the FQN's last segment, or the static member for `import static`); wildcard imports carry none, and re-exports aren't tracked",callEdges:"not extracted \u2014 Groovy needs its own grammar (issue 8c)",complexity:"not computed \u2014 Groovy needs its own grammar (issue 8c)"},coffeescript:{importResolution:"generic relative-path fallback, no ecosystem-specific rules",exportSymbols:"best-effort, less validated than TS/JS",callEdges:"not extracted (backfill planned \u2014 see the language coverage roadmap)",complexity:"not computed (backfill planned \u2014 see the language coverage roadmap)",testTags:"no framework-aware strategy \u2014 falls back to the generic path-glob applier"},livescript:{importResolution:"generic relative-path fallback",exportSymbols:"not tracked",callEdges:"not extracted (backfill planned)",complexity:"not computed (backfill planned)",testTags:"no framework-aware strategy \u2014 falls back to the generic path-glob applier"},lua:{importResolution:"basic dot-path handling only",exportSymbols:"best-effort module-return inspection",callEdges:"not extracted (backfill planned)",complexity:"not computed (backfill planned)",testTags:"no framework-aware strategy \u2014 falls back to the generic path-glob applier"},scss:{exportSymbols:"root-level $/@ variables, mixins and functions only"},less:{exportSymbols:"root-level $/@ variables, mixins and functions only"},stylus:{duplication:"generic token pipeline \u2014 no shared PostCSS AST for structural comparison"},markdown:{importResolution:"edges only via code-span file references (`` `src/foo.ts` ``) (ADR-009)"},gherkin:{importResolution:"feature files have no imports"}},Ku=["importResolution","exportSymbols","importSymbols","callEdges","complexity"];function V(t,e){let n=Array.isArray(t)?t:[t],r=new Set;for(let i of n)for(let o of i.nodes.values())o.type!=="markdown"&&o.type!=="unknown"&&r.add(o.type);let s=[];for(let i of r){let o=Kr[i][e];if(o==="full")continue;let a=Uu[i]?.[e];!a&&o!=="none"||s.push(`${i}: ${Bu[e]} is ${a??"not available for this language \u2014 see docs/language-support.md"}`)}return s.sort()}function Hr(t){let e=new Set;for(let n of Ku)for(let r of V(t,n))e.add(r);return[...e].sort()}function Jr(t){let e=new Map;for(let n of t.nodes.values())e.set(n.type,(e.get(n.type)??0)+1);return[...e.entries()].map(([n,r])=>({type:n,fileCount:r,exportsTracked:xo.has(n),importSymbolsTracked:bo.has(n),callEdgesTracked:xt.has(n),fidelity:Kr[n]})).sort((n,r)=>r.fileCount-n.fileCount)}import un from"fs";import oe from"path";import wo from"fs";import Ve from"path";var bt=class{extensions=[".go"];goModCache=new Map;resolve(e,n,r,s){let{mod:i,replaces:o}=this.readGoMod(r);if(!i)return null;let a=this.applyReplace(n,o,r);if(a!==void 0)return Co(a);if(n!==i&&!n.startsWith(`${i}/`))return null;let c=n.slice(i.length).replace(/^\//,"");return c?Co(Ve.join(r,c)):null}readGoMod(e){let n=this.goModCache.get(e);if(n!==void 0)return n;let r={mod:null,replaces:new Map};try{let s=wo.readFileSync(Ve.join(e,"go.mod"),"utf-8"),i=Hu(s,e);return this.goModCache.set(e,i),i}catch{return this.goModCache.set(e,r),r}}applyReplace(e,n,r){for(let[s,i]of n){if(e===s)return i;if(e.startsWith(`${s}/`)){let o=e.slice(s.length+1);return Ve.join(i,o)}}}};function Hu(t,e){let n=t.split(`
12
+ `),r=null,s=new Map,i=!1;for(let o of n){let a=o.trim();if(a.startsWith("module ")){r=a.slice(7).trim();continue}if(/^replace\s*\(/.test(a)){i=!0;continue}if(i&&a===")"){i=!1;continue}if(i&&a.includes("=>")){vo(a,e,s);continue}!i&&/^replace\s+/.test(a)&&a.includes("=>")&&vo(a.replace(/^replace\s+/,""),e,s)}return{mod:r,replaces:s}}function vo(t,e,n){let[r,s]=t.split("=>").map(a=>a.trim());if(!r||!s)return;let i=r.split(/\s+/)[0];if(!s.startsWith(".")&&!s.startsWith("/"))return;let o=Ve.isAbsolute(s)?s:Ve.resolve(e,s);n.set(i,o)}function Co(t){let e;try{e=wo.readdirSync(t,{withFileTypes:!0})}catch{return null}let n=e.filter(r=>r.isFile()&&r.name.endsWith(".go")&&!r.name.endsWith("_test.go")).map(r=>({path:Ve.join(t,r.name),isExternal:!1})).sort((r,s)=>r.path.localeCompare(s.path));return n.length>0?n:null}import cn from"fs";import ln from"path";var Ju=new Set([".java",".kt",".kts",".scala",".sc",".groovy"]),Vu=12,Eo=4096,Qu=new Set(Mr);function Fo(t){let e=t.replace(/\\/g,"/"),n=e.match(/^(.*)\/src\/([^/]+)(?:\/|$)/);if(!n?.[1]||!n[2]){let i=e.lastIndexOf("/");return{module:i===-1?e:e.slice(0,i),rootSegment:"",sourceRoot:"unknown"}}let r=n[2],s=r==="main"?"main":Qu.has(r)?r:"unknown";return{module:n[1],rootSegment:r,sourceRoot:s}}var Pe=class{constructor(e=[]){this.extraIgnoreDirs=e}extraIgnoreDirs;extensions=[".java",".kt",".kts",".scala",".sc",".groovy",".gradle"];indexCache=new Map;resolve(e,n,r,s){let i=this.getIndex(r);if(i.size===0)return null;let o=n.endsWith(".*"),a=(o?n.slice(0,-2):n).split(".").filter(Boolean);if(a.length===0)return null;if(o){let c=i.get(a.join("."));if(!c)return null;let l=Fo(e),p=c.filter(m=>m.module===l.module&&m.rootSegment===l.rootSegment),u=l.sourceRoot!=="main"&&l.sourceRoot!=="unknown",f=p.flatMap(m=>u?m.files:m.files.filter(h=>!Ir(To(h))));return Vr(f)}for(let c=a.length-1;c>=1;c--){let l=Xu(i,a.slice(0,c).join("."));if(!l)continue;let p=a[c],u=l.filter(f=>To(f)===p);if(u.length>0)return Vr(u);if(c===a.length-1)return Vr(l)}return null}getIndex(e){let n=this.indexCache.get(e);if(n)return n;let r=Yu(e,this.extraIgnoreDirs);return this.indexCache.set(e,r),r}};function Yu(t,e=[]){let n=new Map,r=(process.env.MOKOSH_IGNORE_DIRS??"").split(",").map(a=>a.trim()).filter(Boolean),s=new Set([...j,...r,...e]),i=(a,c)=>{let{module:l,rootSegment:p,sourceRoot:u}=Fo(c),f=n.get(a);if(!f){n.set(a,[{module:l,rootSegment:p,sourceRoot:u,files:[c]}]);return}let m=f.find(h=>h.module===l&&h.rootSegment===p);m?m.files.push(c):f.push({module:l,rootSegment:p,sourceRoot:u,files:[c]})},o=(a,c)=>{if(c>Vu)return;let l;try{l=cn.readdirSync(a,{withFileTypes:!0})}catch{return}for(let p of l){let u=ln.join(a,p.name);if(p.isDirectory()){!p.name.startsWith(".")&&!s.has(p.name)&&o(u,c+1);continue}if(!p.isFile())continue;let f=ln.extname(p.name);if(!Ju.has(f))continue;let m=Zu(u,f===".scala"||f===".sc");m&&i(m,u)}};o(t,0);for(let a of n.values())for(let c of a)c.files.sort();return n}function Xu(t,e){let n=t.get(e);if(!(!n||n.length===0))return n.length===1?n[0]?.files:n.flatMap(r=>r.files).sort()}function Zu(t,e){let n;try{let r=cn.openSync(t,"r");try{let s=Buffer.alloc(Eo),i=cn.readSync(r,s,0,Eo,0);n=s.toString("utf8",0,i)}finally{cn.closeSync(r)}}catch{return null}return q(n,e)}function Vr(t){return!t||t.length===0?null:t.map(e=>({path:e,isExternal:!1}))}function To(t){return ln.basename(t,ln.extname(t))}import qu from"fs";import Qr from"path";var kt=class{extensions=[".lua"];resolve(e,n,r,s){let i=n.replace(/\./g,Qr.sep),o=[r,Qr.join(r,"lib")];for(let a of o){if(!qu.existsSync(a))continue;let c=s(Qr.join(a,"_dummy.lua"),i);if(c)return[c]}return null}};import ef from"path";var tf=new Set(j),St=class{extensions=[".md",".mdx"];resolve(e,n,r,s){let i=n.replace(/^\.\//,"").split("/")[0];if(i&&tf.has(i))return null;let o=s(ef.join(r,"_dummy"),`./${n}`);return o?[o]:null}};import nf from"fs";import Yr from"path";var vt=class{extensions=[".py"];resolve(e,n,r,s){let i=n.replace(/\./g,Yr.sep),o=Yr.join(r,`${i}.py`);if(Do(o))return[{path:o,isExternal:!1}];let a=Yr.join(r,i,"__init__.py");return Do(a)?[{path:a,isExternal:!1}]:null}};function Do(t){try{return nf.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}import Po from"path";var rf=["~","http://","https://","//","data:","sass:"],Ct=class{extensions=[".css",".scss",".sass",".less",".styl"];resolve(e,n,r,s){if(rf.some(p=>n.startsWith(p)))return null;let i=s(e,n);if(i)return[i];let o=Po.dirname(n),a=Po.basename(n),c=o==="."?`_${a}`:`${o}/_${a}`,l=s(e,c);return l?[l]:null}};function pn(t={}){return[new vt,new kt,new bt,t.jvm??new Pe,new Ct,new St]}var Ao=new Set;function sf(t,e){let n=t.constructor?.name??"LangResolver";if(Ao.has(n))return;Ao.add(n);let r=e instanceof Error?e.message:String(e);process.stderr.write(`
13
+ Warning: ${n}.resolve() threw (${r}); affected imports are left unresolved.
14
+ `)}var ae=class{constructor(e,n={}){this.rootDir=e;this.workspaceMap=n.workspaceMap??new Map,this.tsconfigSearchPaths=n.tsconfigSearchPaths??[e],this.pathAliases=n.pathAliases,this.langResolvers=n.langResolvers??pn()}rootDir;workspaceMap;tsconfigSearchPaths;pathAliases;langResolvers;resolutionCache=new Map;langBucketFor(e){for(let n=0;n<this.langResolvers.length;n++)if(this.langResolvers[n]?.extensions.some(r=>e.endsWith(r)))return String(n);return"none"}cacheKey(e,n){return`${oe.dirname(e)}\0${this.langBucketFor(e)}\0${n}`}resolveAll(e,n){let r=this.cacheKey(e,n),s=this.resolutionCache.get(r);if(s!==void 0)return s??[];let i=this.resolveAllUncached(e,n);return this.resolutionCache.set(r,i.length>0?i:null),i}resolveAllUncached(e,n){let r=this.resolvePathAlias(n);if(r)return[r];if(n.startsWith(".")||n.startsWith("/")){let o=this.resolveLocalPath(e,n);return o?[o]:[]}let s=(o,a)=>this.resolveLocalPath(o,a);for(let o of this.langResolvers)if(o.extensions.some(a=>e.endsWith(a))){let a=null;try{a=o.resolve(e,n,this.rootDir,s)}catch(c){sf(o,c)}if(a)return a}let i=this.resolveWorkspaceImport(n);return i?[i]:[{path:n,isExternal:!0}]}resolve(e,n){return this.resolveAll(e,n)[0]??null}resolveLocalPath(e,n){let r=oe.dirname(e),s=n.startsWith("/")?n:oe.resolve(r,n),i=!s.startsWith(this.rootDir),o=["",".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".feature",".md",".mdx"],a=s.match(/\.(js|mjs|cjs)$/);if(a){let c=s.slice(0,-a[0].length);for(let l of[".ts",".tsx"]){let p=this.tryExtensions(c,l,i);if(p)return p}}for(let c of o){let l=this.tryExtensions(s,c,i);if(l)return l}return i?{path:s,isExternal:!0}:null}tryExtensions(e,n,r){let s=e+n;if(this.isFile(s))return{path:s,isExternal:r};let i=oe.join(e,`index${n}`);if(this.isFile(i))return{path:i,isExternal:r};if(n===".py"){let o=oe.join(e,"__init__.py");if(this.isFile(o))return{path:o,isExternal:r}}return null}isFile(e){try{return un.statSync(e,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}resolvePathAlias(e){if(this.pathAliases)for(let n in this.pathAliases){let r=this.matchAliasPattern(n,e),s=this.pathAliases[n];if(r&&s){let i=this.tryAliasSubstitutions(s,r[1]||"");if(i)return i}}for(let n of this.tsconfigSearchPaths){let r=oe.join(n,"tsconfig.json");if(un.existsSync(r))try{let i=JSON.parse(un.readFileSync(r,"utf-8")).compilerOptions?.paths;if(!i)continue;for(let o in i){let a=this.matchAliasPattern(o,e);if(a){let c=this.tryAliasSubstitutions(i[o],a[1]||"",n);if(c)return c}}}catch{}}return null}aliasRegexCache=new Map;matchAliasPattern(e,n){let r=this.aliasRegexCache.get(e);if(!r){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\*","(.*)");r=new RegExp(`^${s}$`),this.aliasRegexCache.set(e,r)}return n.match(r)}tryAliasSubstitutions(e,n,r=this.rootDir){let s=["",".ts",".tsx",".js",".jsx",".coffee",".ls",".lua",".feature"];for(let i of e){let o=i.replace("*",n),a=oe.resolve(r,o);for(let c of s){let l=this.tryExtensions(a,c,!1);if(l)return l}}return null}resolveWorkspaceImport(e){if(this.workspaceMap.size===0)return null;for(let[n,r]of this.workspaceMap){if(e!==n&&!e.startsWith(`${n}/`))continue;let s=e.slice(n.length),i={path:"",isExternal:!1,isWorkspace:!0,workspacePackage:n};if(!s){for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"]){let c=oe.join(r,a);try{if(un.statSync(c,{throwIfNoEntry:!1})?.isFile())return{...i,path:c}}catch{}}return{...i,path:r}}let o=this.resolveLocalPath(oe.join(r,"_dummy"),s.slice(1));return o?{...i,path:o.path}:null}return null}};var af=["tests","test","__tests__","specs","spec"],cf=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage",".pytest_cache","__pycache__"],lf=600;function pf(){return(process.env.MOKOSH_IGNORE_DIRS??"").split(",").map(t=>t.trim()).filter(Boolean)}function uf(t,e){if(t.length===0)return e;let n=t.map(o=>L.dirname(o).split(L.sep)),r=n[0]??[];for(let o of n.slice(1)){let a=0;for(;a<r.length&&a<o.length&&r[a]===o[a];)a++;r=r.slice(0,a)}let s=r.join(L.sep)||L.sep,i=L.relative(e,s);return i.startsWith("..")||L.isAbsolute(i)?e:s}var Ae=class{constructor(e,n=null,r,s,i=!1,o=new Map,a=!0,c=[],l=null){this.rootDir=e;this.enableGitStats=i;this.coverageMap=o;this.parallelParsing=a;this.docFiles=l;this.previousGraph=n,this.walkIgnoreDirs=new Set([...cf,...c,...pf()]),this.resolver=r||new ae(e),this.lockFile=wi(e),s&&(this.progressCallback=s)}rootDir;enableGitStats;coverageMap;parallelParsing;docFiles;graph={nodes:new Map};visited=new Set;queue=[];previousGraph=null;resolver;lockFile=null;progressCallback;pool=null;gitStatsMap=null;walkIgnoreDirs;async build(e){let n=e.map(r=>L.isAbsolute(r)?r:L.resolve(this.rootDir,r));await this.initPool(),this.enableGitStats&&(this.gitStatsMap=yi(this.rootDir));try{for(let r of n)this.enqueue(r);return await this.drain(),await this.processTestFiles(uf(n,this.rootDir)),await this.processDocFiles(),this.progressCallback&&this.visited.size>=100&&process.stderr.write(`
13
15
  Done. Total processed: ${this.visited.size} nodes.
14
- `),Ds(this.graph.nodes,this.coverageMap),new P(this.graph.nodes)}finally{this.pool&&(await this.pool.destroy(),this.pool=null)}}async initPool(){if(this.parallelParsing===!1)return;let e=typeof this.parallelParsing=="object"?this.parallelParsing:{},r=e.minFiles??Tl;if(!(r>0&&!this.hasAtLeastFiles(this.rootDir,r))){e.maxThreads!==void 0&&e.maxThreads<1&&process.stderr.write(`
16
+ `),ho(this.graph.nodes,this.coverageMap),new P(this.graph.nodes)}finally{this.pool&&(await this.pool.destroy(),this.pool=null)}}async initPool(){if(this.parallelParsing===!1)return;let e=typeof this.parallelParsing=="object"?this.parallelParsing:{},n=e.minFiles??lf;if(!(n>0&&!this.hasAtLeastFiles(this.rootDir,n))){e.maxThreads!==void 0&&e.maxThreads<1&&process.stderr.write(`
15
17
  Warning: parallelParsing.maxThreads (${e.maxThreads}) must be at least 1; using 1.
16
- `);try{let n=F.join(f,"parse-worker.js");this.pool=new wl({filename:n,...e.maxThreads!==void 0?{maxThreads:Math.max(1,e.maxThreads)}:{}})}catch(n){process.stderr.write(`
17
- Warning: failed to start parse worker pool, falling back to synchronous parsing: ${n}
18
- `),this.pool=null}}}hasAtLeastFiles(e,r){let n=0,s=[e];for(;s.length>0;){let o=s.pop();if(o===void 0)continue;let i;try{i=Ge.readdirSync(o,{withFileTypes:!0})}catch{continue}for(let a of i)if(a.isDirectory())this.walkIgnoreDirs.has(a.name)||s.push(F.join(o,a.name));else if(a.isFile()&&(n++,n>=r))return!0}return n>=r}async processTestFiles(e){let r=ke(),n=o=>r.some(i=>o.name.includes(i));this.walkProject(e,n);let s=e;for(;s!==this.rootDir;){let o=F.dirname(s);if(o===s)break;for(let i of El){let a=F.join(o,i);try{Ge.statSync(a).isDirectory()&&this.walkProject(a,n)}catch{}}s=o}await this.drain()}async processDocFiles(){this.walkProject(this.rootDir,e=>e.name.endsWith(".md")||e.name.endsWith(".mdx")),await this.drain()}walkProject(e,r){let n;try{n=Ge.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of n){let o=F.join(e,s.name);s.isDirectory()?this.walkIgnoreDirs.has(s.name)||this.walkProject(o,r):s.isFile()&&r(s)&&this.enqueue(o)}}enqueue(e){this.visited.has(e)||(this.visited.add(e),this.showProgress(),this.queue.push(e))}async drain(){for(;this.queue.length>0;){let e=this.queue;this.queue=[],await Promise.all(e.map(r=>this.finishFile(r)))}}async finishFile(e){let r=Ge.statSync(e,{throwIfNoEntry:!1});if(!r?.isFile())return;let n=F.relative(this.rootDir,e),s=await this.getNode(e,n,r);s.imports=await this.resolveImports(e,s.imports),Ns(s.imports,s.tags),this.graph.nodes.set(s.path,s)}async getNode(e,r,n){let s=this.previousGraph?.nodes.get(r);if(s&&s.mtime===n.mtimeMs&&s.size===n.size)return{...s};let o=await this.tryParse(e,r);if(!o)return this.makeStubNode(e,r,n);let i=this.resolveCallEdges(e,o.rawCallEdges),a=this.buildNode(e,r,n,o,i);return this.attachGitStats(a,r),a}async tryParse(e,r){let n=Ge.readFileSync(e,"utf-8");try{return await this.parseContent(e,n)}catch(s){return process.stderr.write(`
19
- Warning: failed to parse ${r}: ${s}
20
- `),null}}parseContent(e,r){return this.pool?this.pool.run({filePath:e,content:r}):Ts(e,r)}makeStubNode(e,r,n){return{path:r,type:_(e),category:"other",imports:[],exports:[],tags:[],mtime:n.mtimeMs,size:n.size}}resolveCallEdges(e,r){let n=[];for(let s of r??[])try{let o=this.resolver.resolve(e,s.toSpecifier);o&&!o.isExternal&&n.push({from:s.from,to:s.to,toFile:F.relative(this.rootDir,o.path)})}catch{}return n}buildNode(e,r,n,s,o){let{imports:i,exports:a,tags:c,category:l,description:p,complexity:u,cognitiveComplexity:g,functions:d}=s;return{path:r,type:_(e),category:l,imports:i,exports:a,tags:c,mtime:n.mtimeMs,size:n.size,...p!==void 0?{description:p}:{},...o.length>0?{callEdges:o}:{},...u!==void 0?{complexity:u}:{},...g!==void 0?{cognitiveComplexity:g}:{},...d!==void 0?{functions:d}:{}}}attachGitStats(e,r){let n=this.gitStatsMap?.get(r);n&&(e.commitCount90d=n.commitCount90d,n.lastAuthor!==void 0&&(e.lastAuthor=n.lastAuthor),n.lastCommitAt!==void 0&&(e.lastCommitAt=n.lastCommitAt))}async resolveImports(e,r){let n=[];for(let s of r){let o=this.resolver.resolveAll(e,s.rawSpecifier);if(!(o.length===0||s.type==="side-effect"&&s.rawSpecifier.endsWith(".*")&&o.every(a=>a.isExternal)))for(let a of o){if(!a.isExternal&&a.path===e)continue;let c={...s,toPath:a.isExternal?a.path:F.relative(this.rootDir,a.path),isExternal:a.isExternal};a.isWorkspace&&(c.isWorkspace=!0,c.workspacePackage=a.workspacePackage),a.isExternal?this.attachLockfileVersion(c):this.enqueue(a.path),n.push(c)}}return n}attachLockfileVersion(e){if(!this.lockFile)return;let r=this.lockFile.jvmDependencies;if(r&&Rs.has(_(e.fromPath))){let o=e.rawSpecifier.replace(/\.\*$/,""),i="";for(let a of Object.keys(r))(o===a||o.startsWith(`${a}.`))&&a.length>i.length&&(i=a);i&&(e.version=r[i]?.version);return}let n=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],s=n?this.lockFile.dependencies[n]:void 0;s&&(e.version=s.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};import{readFile as Ys}from"fs/promises";import je from"path";import Jl from"piscina";var Nl=new Set(["css","scss","less","stylus"]);function Ws(t){return Nl.has(t)?"style":"code"}function Dl(t){return t.trim().replace(/\s+/g," ")}function Rl(t){try{return t.fileType==="scss"?ut(t.source,t.file).root:t.fileType==="less"?pt(t.source,t.file).root:t.fileType==="css"?lt(t.source,t.file).root:void 0}catch{return}}function Il(t){let e=Rl(t);if(!e)return[];let r=[];return e.walkRules(n=>{let s=n.nodes?.filter(p=>p.type==="decl")??[];if(s.length===0)return;let o=s[0],i=s[s.length-1],a=n.source?.start?.line??o?.source?.start?.line,c=i?.source?.end?.line??i?.source?.start?.line??a;if(a===void 0||c===void 0)return;let l=s.map(p=>`${p.prop.trim().toLowerCase()}:${Dl(p.value)}`).join(";");r.push({file:t.file,startLine:a,endLine:c,lines:c-a+1,signature:l,declCount:s.length})}),r}function $s(t,e,r=2){let n=new Map;for(let o of t)for(let i of Il(o)){if(i.declCount<r||i.lines<e)continue;let a=n.get(i.signature);a?a.push(i):n.set(i.signature,[i])}let s=[];for(let o of n.values())for(let i=0;i<o.length;i++)for(let a=i+1;a<o.length;a++){let c=o[i],l=o[a];if(c.file===l.file&&c.startLine===l.startLine&&c.endLine===l.endLine)continue;let p={file:c.file,startLine:c.startLine,endLine:c.endLine},u={file:l.file,startLine:l.startLine,endLine:l.endLine};s.push({occurrences:[p,u],lines:Math.min(c.lines,l.lines),tokens:c.declCount,family:"style"})}return s.sort((o,i)=>i.lines-o.lines)}function Bs(t){let e=t.length,r=[],n=[{lcpLength:0,low:0}];for(let s=1;s<e;s++){let o=s-1;for(;t[s]<n[n.length-1].lcpLength;){let i=n.pop();r.push({lcpLength:i.lcpLength,low:i.low,high:s-1}),o=i.low}t[s]>n[n.length-1].lcpLength&&n.push({lcpLength:t[s],low:o})}for(;n.length>1;){let s=n.pop();r.push({lcpLength:s.lcpLength,low:s.low,high:e-1})}return r}var Ml=new Set(["{","}",":",",","[","]"]);function Hs(t,e,r){let n=0;for(let s=e;s<e+r;s++)Ml.has(t[s].text)&&n++;return n/r}function Us(t){let e=t.length;if(e===0)return[];let r=Array.from({length:e},(o,i)=>i),n=new Array(e);{let o=[...new Set(t)].sort(),i=new Map(o.map((a,c)=>[a,c]));for(let a=0;a<e;a++)n[a]=i.get(t[a])}let s=new Array(e).fill(0);for(let o=1;o<e;o*=2){let i=a=>a+o<e?n[a+o]:-1;r.sort((a,c)=>{let l=n[a]-n[c];return l!==0?l:i(a)-i(c)}),s[r[0]]=0;for(let a=1;a<e;a++){let c=r[a-1],l=r[a],p=n[c]===n[l],u=i(c)===i(l);s[l]=s[c]+(p&&u?0:1)}if([n,s]=[s,n],n[r[e-1]]===e-1)break}return r}function Js(t,e){let r=t.length,n=new Array(r).fill(0);if(r===0)return n;let s=new Array(r);for(let i=0;i<r;i++)s[e[i]]=i;let o=0;for(let i=0;i<r;i++){let a=s[i];if(a>0){let c=e[a-1];for(;i+o<r&&c+o<r&&t[i+o]===t[c+o];)o++;n[a]=o,o>0&&o--}else o=0}return n}function Ks(t,e,r,n=.5){let s=[],o=[],i=new Map;for(let{file:u,tokens:g}of t)if(g.length!==0){i.set(u,g);for(let d=0;d<g.length;d++)s.push(g[d].text),o.push({file:u,localIndex:d});s.push(` ${u}`),o.push({file:u,localIndex:-1})}if(s.length===0)return[];let a=Us(s),c=Js(s,a),l=Bs(c),p=[];for(let u of l){let g=Ll(u,a,o,i,e,r,n);g&&p.push(g)}return p.sort((u,g)=>g.lines-u.lines)}function Ll(t,e,r,n,s,o,i){if(t.lcpLength<s)return;let a=[];for(let d=t.low;d<=t.high;d++){let y=r[e[d]];y.localIndex!==-1&&a.push(y)}if(a.length<2||!_l(a,n))return;let c=Gl(a,t.lcpLength);if(c.length<2)return;let l=c[0],p=n.get(l.file);if(Hs(p,l.localIndex,t.lcpLength)>i)return;let u=c.map(({file:d,localIndex:y})=>{let v=n.get(d);return{file:d,startLine:v[y].line,endLine:v[y+t.lcpLength-1].line}}),g=Math.min(...u.map(d=>d.endLine-d.startLine+1));if(!(g<o))return{occurrences:u,lines:g,tokens:t.lcpLength}}function _l(t,e){let r=null;for(let{file:n,localIndex:s}of t){if(s===0)return!0;let i=e.get(n)[s-1].text;if(r===null)r=i;else if(r!==i)return!0}return!1}function Gl(t,e){let r=new Map;for(let{file:s,localIndex:o}of t){let i=r.get(s);i?i.push(o):r.set(s,[o])}let n=[];for(let[s,o]of r){o.sort((a,c)=>a-c);let i=Number.NEGATIVE_INFINITY;for(let a of o)a>=i&&(n.push({file:s,localIndex:a}),i=a+e)}return n}var Ol={typescript:{line:["//"],block:[["/*","*/"]]},javascript:{line:["//"],block:[["/*","*/"]]},go:{line:["//"],block:[["/*","*/"]]},java:{line:["//"],block:[["/*","*/"]]},kotlin:{line:["//"],block:[["/*","*/"]]},scala:{line:["//"],block:[["/*","*/"]]},groovy:{line:["//"],block:[["/*","*/"]]},css:{block:[["/*","*/"]]},scss:{line:["//"],block:[["/*","*/"]]},less:{line:["//"],block:[["/*","*/"]]},stylus:{line:["//"],block:[["/*","*/"]]},python:{line:["#"]},gherkin:{line:["#"]},coffeescript:{line:["#"],block:[["###","###"]]},livescript:{line:["#"],block:[["###","###"]]},lua:{line:["--"],block:[["--[[","]]"]]},markdown:{block:[["<!--","-->"]]}};function qs(t,e,r){let n=t.slice(e,r).replace(/[^\n]/g," ");return t.slice(0,e)+n+t.slice(r)}function jl(t,e){if(!e)return t;let r=t;for(let[n,s]of e.block??[]){let o=0;for(;;){let i=r.indexOf(n,o);if(i===-1)break;let a=r.indexOf(s,i+n.length),c=a===-1?r.length:a+s.length;r=qs(r,i,c),o=c}}for(let n of e.line??[]){let s=0;for(;;){let o=r.indexOf(n,s);if(o===-1)break;let i=r.indexOf(`
21
- `,o),a=i===-1?r.length:i;r=qs(r,o,a),s=a}}return r}var zl=["===","!==","...","=>","==","!=","<=",">=","&&","||","::","->","..","+=","-=","*=","/="],Tr=new RegExp(`${zl.map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")}|[A-Za-z_$][A-Za-z0-9_$]*|\\d+(?:\\.\\d+)?|"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|\\S`,"g"),Wl=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Vs=/^\d+(?:\.\d+)?$/,$l=/^(".*"|'.*'|`.*`)$/s,Bl=new Set(["if","else","elif","for","while","do","switch","case","default","break","continue","return","function","def","class","struct","interface","const","let","var","local","import","export","from","package","try","catch","except","finally","throw","raise","new","this","self","end","then","yield","async","await","nil","null","None","true","false","True","False","and","or","not","in","of","is"]);function Qs(t,e,r=!0){let n=jl(t,Ol[e]),s=[],o=1,i=0;Tr.lastIndex=0;let a=Tr.exec(n);for(;a!==null;){for(let p=i;p<a.index;p++)n[p]===`
22
- `&&o++;i=a.index;let c=a[0],l=c;Wl.test(c)&&!Bl.has(c)?l="ID":r&&(Vs.test(c)||$l.test(c))&&(l=Vs.test(c)?"NUM":"STR"),s.push({text:l,line:o});for(let p=i;p<a.index+c.length;p++)n[p]===`
23
- `&&o++;i=a.index+c.length,a=Tr.exec(n)}return s}import Oe from"fs";import Hl from"path";function Ul(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.mtime=="number"&&typeof e.size=="number"&&typeof e.ignoreLiterals=="boolean"&&Array.isArray(e.tokens)}function de(t){try{if(!Oe.existsSync(t))return new Map;let e=Oe.readFileSync(t,"utf-8"),r=JSON.parse(e);if(!Array.isArray(r))return new Map;let n=r.filter(s=>Array.isArray(s)&&s.length===2&&typeof s[0]=="string"&&Ul(s[1]));return new Map(n)}catch{return new Map}}function he(t,e){let r=Hl.dirname(e);Oe.existsSync(r)||Oe.mkdirSync(r,{recursive:!0}),Oe.writeFileSync(e,JSON.stringify([...t.entries()]))}var Kl=20,ql=new Set(["css","scss","less"]);function Vl(t){return Te.includes(je.basename(t))}function Ql(t,e){if(e.length===0)return!1;let r=new Set(e);return t.split(je.sep).some(n=>r.has(n))}async function ye(t,e,r={}){let{minLines:n=6,windowSize:s=15,ignoreLiterals:o=!0,maxPunctuationRatio:i=.5,limit:a=50,ignoreDirs:c=T,parallelTokenizing:l=!0,tokenCache:p}=r,u=[...t.nodes.values()].filter(d=>!Vl(d.path)&&!Ql(d.path,c)),g=Yl(l,u.length);try{let d=[],y=new Map;if(await Promise.all(u.map(async x=>{if(ql.has(x.type)){let se;try{se=await Ys(je.join(e,x.path),"utf8")}catch{return}d.push({file:x.path,source:se,fileType:x.type});return}let k=p?.get(x.path),R=k&&k.mtime===x.mtime&&k.size===x.size&&k.ignoreLiterals===o,D;if(R)D=k.tokens;else{let se;try{se=await Ys(je.join(e,x.path),"utf8")}catch{return}D=g?await g.run({source:se,fileType:x.type,ignoreLiterals:o}):Qs(se,x.type,o),p?.set(x.path,{mtime:x.mtime,size:x.size,ignoreLiterals:o,tokens:D})}let H=Ws(x.type),hn={file:x.path,tokens:D},yn=y.get(H);yn?yn.push(hn):y.set(H,[hn])})),p){let x=new Set(u.map(k=>k.path));for(let k of p.keys())x.has(k)||p.delete(k)}let v=$s(d,n);for(let[x,k]of y)for(let R of Ks(k,s,n,i))v.push({...R,family:x});return{groups:v.sort((x,k)=>k.lines-x.lines).slice(0,a)}}finally{g&&await g.destroy()}}function Yl(t,e){if(t===!1)return null;let r=typeof t=="object"?t:{},n=r.minFiles??Kl;if(e<n)return null;r.maxThreads!==void 0&&r.maxThreads<1&&process.stderr.write(`
24
- Warning: parallelTokenizing.maxThreads (${r.maxThreads}) must be at least 1; using 1.
25
- `);try{return new Jl({filename:je.join(f,"duplication-worker.js"),...r.maxThreads!==void 0?{maxThreads:Math.max(1,r.maxThreads)}:{}})}catch(s){return process.stderr.write(`
18
+ `);try{let r=L.join(g,"parse-worker.js");this.pool=new of({filename:r,...e.maxThreads!==void 0?{maxThreads:Math.max(1,e.maxThreads)}:{}})}catch(r){process.stderr.write(`
19
+ Warning: failed to start parse worker pool, falling back to synchronous parsing: ${r}
20
+ `),this.pool=null}}}hasAtLeastFiles(e,n){let r=0,s=[e];for(;s.length>0;){let i=s.pop();if(i===void 0)continue;let o;try{o=wt.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let a of o)if(a.isDirectory())this.walkIgnoreDirs.has(a.name)||s.push(L.join(i,a.name));else if(a.isFile()&&(r++,r>=n))return!0}return r>=n}async processTestFiles(e){let n=ut(),r=i=>n.some(o=>i.name.includes(o));this.walkProject(e,r);let s=e;for(;s!==this.rootDir;){let i=L.dirname(s);if(i===s)break;for(let o of af){let a=L.join(i,o);try{wt.statSync(a).isDirectory()&&this.walkProject(a,r)}catch{}}s=i}await this.drain()}async processDocFiles(){if(this.docFiles!==null){for(let e of this.docFiles)this.enqueue(e);await this.drain();return}this.walkProject(this.rootDir,e=>e.name.endsWith(".md")||e.name.endsWith(".mdx")),await this.drain()}walkProject(e,n){let r;try{r=wt.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of r){let i=L.join(e,s.name);s.isDirectory()?this.walkIgnoreDirs.has(s.name)||this.walkProject(i,n):s.isFile()&&n(s)&&this.enqueue(i)}}enqueue(e){this.visited.has(e)||(this.visited.add(e),this.showProgress(),this.queue.push(e))}async drain(){for(;this.queue.length>0;){let e=this.queue;this.queue=[],await Promise.all(e.map(n=>this.finishFile(n)))}}async finishFile(e){let n=wt.statSync(e,{throwIfNoEntry:!1});if(!n?.isFile())return;let r=L.relative(this.rootDir,e),s=await this.getNode(e,r,n);s.imports=await this.resolveImports(e,s.imports),mo(s.imports,s.tags),this.graph.nodes.set(s.path,s)}async getNode(e,n,r){let s=this.previousGraph?.nodes.get(n);if(s&&s.mtime===r.mtimeMs&&s.size===r.size)return{...s};let i=await this.tryParse(e,n);if(!i)return this.makeStubNode(e,n,r);let o=this.resolveCallEdges(e,i.rawCallEdges),a=this.buildNode(e,n,r,i,o);return this.attachGitStats(a,n),a}async tryParse(e,n){let r=wt.readFileSync(e,"utf-8");try{return await this.parseContent(e,r)}catch(s){return process.stderr.write(`
21
+ Warning: failed to parse ${n}: ${s}
22
+ `),null}}parseContent(e,n){return this.pool?this.pool.run({filePath:e,content:n}):po(e,n)}makeStubNode(e,n,r){return{path:n,type:J(e),category:"other",imports:[],exports:[],tags:[],mtime:r.mtimeMs,size:r.size}}resolveCallEdges(e,n){let r=[];for(let s of n??[])try{let i=this.resolver.resolve(e,s.toSpecifier);i&&!i.isExternal&&r.push({from:s.from,to:s.to,toFile:L.relative(this.rootDir,i.path)})}catch{}return r}buildNode(e,n,r,s,i){let{imports:o,exports:a,tags:c,category:l,description:p,complexity:u,cognitiveComplexity:f,functions:m}=s;return{path:n,type:J(e),category:l,imports:o,exports:a,tags:c,mtime:r.mtimeMs,size:r.size,...p!==void 0?{description:p}:{},...i.length>0?{callEdges:i}:{},...u!==void 0?{complexity:u}:{},...f!==void 0?{cognitiveComplexity:f}:{},...m!==void 0?{functions:m}:{}}}attachGitStats(e,n){let r=this.gitStatsMap?.get(n);r&&(e.commitCount90d=r.commitCount90d,r.lastAuthor!==void 0&&(e.lastAuthor=r.lastAuthor),r.lastCommitAt!==void 0&&(e.lastCommitAt=r.lastCommitAt))}async resolveImports(e,n){let r=[];for(let s of n){let i=this.resolver.resolveAll(e,s.rawSpecifier);if(!(i.length===0||s.type==="side-effect"&&s.rawSpecifier.endsWith(".*")&&i.every(a=>a.isExternal)))for(let a of i){if(!a.isExternal&&a.path===e)continue;let c={...s,toPath:a.isExternal?a.path:L.relative(this.rootDir,a.path),isExternal:a.isExternal};a.isWorkspace&&(c.isWorkspace=!0,c.workspacePackage=a.workspacePackage),a.isExternal?this.attachLockfileVersion(c):this.enqueue(a.path),r.push(c)}}return r}attachLockfileVersion(e){if(!this.lockFile)return;let n=this.lockFile.jvmDependencies;if(n&&yo.has(J(e.fromPath))){let i=e.rawSpecifier.replace(/\.\*$/,""),o="";for(let a of Object.keys(n))(i===a||i.startsWith(`${a}.`))&&a.length>o.length&&(o=a);o&&(e.version=n[o]?.version);return}let r=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],s=r?this.lockFile.dependencies[r]:void 0;s&&(e.version=s.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};import{readFile as ts}from"fs/promises";import qe from"path";import tm from"piscina";function Xr(t,e){return t.startsWith("!")?e!==t.slice(1):e===t}function Ro(t){return t.score??t.lines}function fn(t,e){let n=t.occurrences.map(s=>s.file);if(e.path!==void 0){let s=e.path,i=o=>o.includes(s.startsWith("!")?s.slice(1):s);if(s.startsWith("!")?n.some(i):!n.some(i))return!1}if(e.allPaths!==void 0){let s=e.allPaths,i=s.startsWith("!")?s.slice(1):s,o=n.length>0&&n.every(a=>a.includes(i));if(s.startsWith("!")?o:!o)return!1}if(e.family!==void 0&&!Xr(e.family,t.family))return!1;if(e.type!==void 0){let s=e.type.startsWith("!")?e.type.slice(1):e.type,i=n.length>0&&n.every(o=>J(o)===s);if(e.type.startsWith("!")?i:!i)return!1}if(e.kind!==void 0&&!Xr(e.kind,t.kind??"block")||e.defKind!==void 0&&!Xr(e.defKind,t.defKind)||e.minLines!==void 0&&t.lines<e.minLines||e.maxLines!==void 0&&t.lines>e.maxLines)return!1;let r=Ro(t);if(e.minScore!==void 0&&r<e.minScore||e.maxScore!==void 0&&r>e.maxScore||e.minOccurrences!==void 0&&t.occurrences.length<e.minOccurrences||e.crossFile!==void 0&&new Set(n).size>=2!==e.crossFile)return!1;if(e.signals!==void 0&&e.signals.length>0){let s=new Set(t.signals??[]),i=e.signals.filter(a=>!a.startsWith("!"));if(e.signals.filter(a=>a.startsWith("!")).map(a=>a.slice(1)).some(a=>s.has(a))||i.length>0&&!i.some(a=>s.has(a)))return!1}return!0}function mn(t,e){let n=t;if(e.sort){let r=e.sortDir==="asc"?-1:1,s=e.sort==="score"?Ro:e.sort==="occurrences"?i=>i.occurrences.length:i=>i.lines;n=[...n].sort((i,o)=>(s(o)-s(i))*r)}return e.limit!==void 0&&(n=n.slice(0,Math.max(0,e.limit))),n}var Io={path:{field:"path",kind:"string"},allpaths:{field:"allPaths",kind:"string"},family:{field:"family",kind:"string"},type:{field:"type",kind:"string"},kind:{field:"kind",kind:"string"},defkind:{field:"defKind",kind:"string"},minlines:{field:"minLines",kind:"int"},maxlines:{field:"maxLines",kind:"int"},minscore:{field:"minScore",kind:"int"},maxscore:{field:"maxScore",kind:"int"},minoccurrences:{field:"minOccurrences",kind:"int"},crossfile:{field:"crossFile",kind:"bool"},limit:{field:"limit",kind:"int"}},No=new Set(["lines","score","occurrences"]),Mo=new Set([...Object.keys(Io),"signal","signals","sort","sortdir"]);function ff(t,e,n,r,s){let i=t;if(n==="string"){i[e]=s;return}if(n==="bool"){i[e]=s.toLowerCase()==="true";return}let o=Number(s);if(!Number.isFinite(o))throw new Error(`find_duplicates filter: "${r}" expects a number, got "${s}"`);i[e]=o}function mf(t,e){let n=e.indexOf(":");if(n===-1)throw new Error(`find_duplicates filter: clause "${e}" is not "key:value"`);let r=e.slice(0,n).trim().toLowerCase(),s=e.slice(n+1).trim();if(!r||!s)return;if(!Mo.has(r))throw new Error(`find_duplicates filter: unknown key "${r}". Known keys: ${[...Mo].sort().join(", ")}`);if(r==="signal"||r==="signals"){t.signals=[...t.signals??[],s];return}if(r==="sort"){if(!No.has(s))throw new Error(`find_duplicates filter: sort must be one of ${[...No].join(", ")}, got "${s}"`);t.sort=s;return}if(r==="sortdir"){t.sortDir=s.toLowerCase()==="asc"?"asc":"desc";return}let i=Io[r];i&&ff(t,i.field,i.kind,r,s)}function Qe(t){let e={};for(let n of t.split(",")){let r=n.trim();r&&mf(e,r)}return e}function gf(t){let e=[...t].sort((r,s)=>r.start-s.start),n=[];for(let r of e){let s=n.at(-1);s&&r.start<=s.end+1?s.end=Math.max(s.end,r.end):n.push({...r})}return n}function df(t,e,n){let r=e.flatMap(a=>a.occurrences).filter(a=>a.file===t).map(a=>({start:a.startLine,end:a.endLine})),s=gf(r).reduce((a,c)=>a+(c.end-c.start+1),0),i=n?.get(t),o=i!==void 0&&i>0?Math.round(s/i*1e3)/10:void 0;return{file:t,coveredLines:s,totalLines:i,coveragePct:o}}function Lo(t,e){let n=new Map;for(let s of t){let i=[...new Set(s.occurrences.map(c=>c.file))].sort(),o=i.join("\0"),a=n.get(o);a?a.groups.push(s):n.set(o,{files:i,groups:[s]})}let r=[];for(let{files:s,groups:i}of n.values()){let o=Math.max(...i.map(a=>a.lines));r.push({files:s,groups:[...i].sort((a,c)=>c.lines-a.lines),matchCount:i.length,longestMatch:o,coverage:s.map(a=>df(a,i,e))})}return r.sort((s,i)=>i.longestMatch-s.longestMatch||i.matchCount-s.matchCount)}var hf={css:"style",scss:"style",less:"style",stylus:"style",javascript:"js",typescript:"js",coffeescript:"js",livescript:"js",java:"jvm",kotlin:"jvm",scala:"jvm",groovy:"jvm",python:"python",go:"go",lua:"lua",markdown:"markdown",gherkin:"gherkin"};function _o(t){return hf[t]??"other"}import Go from"path";var yf=new Set(["generated","__generated__","__generated","gen","__snapshots__"]),xf=[".pb.go",".pb.ts",".pb.js","_pb2.py","_pb2.pyi","_pb.dart",".g.dart",".generated.ts",".generated.tsx",".generated.js",".generated.jsx","_generated.go",".gen.go",".gen.ts",".snap"],bf=["@generated","do not edit","code generated by","autogenerated","auto-generated","this file was automatically generated","this is a generated file","jest snapshot v1"],kf=500;function Sf(t,e){let n=t.split(/[\\/]/),r=/^\*\*\/(.+?)\/\*\*$/.exec(e);return r?n.includes(r[1]):e.startsWith("*.")?Go.basename(t).endsWith(e.slice(1)):n.includes(e)}function gn(t,e=[]){if(t.split(/[\\/]/).some(s=>yf.has(s)))return!0;let r=Go.basename(t);return xf.some(s=>r.endsWith(s))?!0:e.some(s=>Sf(t,s))}function Et(t){let e=t.slice(0,kf).toLowerCase();return bf.some(n=>e.includes(n))}import F from"typescript";function Oo(t,e,n){let r=t.tagName.getText(e),s=[];for(let i of t.attributes.properties){if(F.isJsxSpreadAttribute(i))return;let o=i.name.getText(e);if(!i.initializer)s.push(o);else if(F.isStringLiteral(i.initializer))s.push(`${o}=${i.initializer.text}`);else if(F.isJsxExpression(i.initializer))if(!i.initializer.expression)s.push(`${o}={}`);else{let a=n.printNode(F.EmitHint.Unspecified,i.initializer.expression,e);s.push(`${o}=${a}`)}else return}return s.sort(),s.length>0?`${r} ${s.join(" ")}`:r}function vf(t,e,n){if(F.isJsxText(t)){let r=t.text.trim().replace(/\s+/g," ");return r.length===0?"":`T:${r}`}if(F.isJsxExpression(t))return t.expression?`E:${n.printNode(F.EmitHint.Unspecified,t.expression,e)}`:"";if(F.isJsxElement(t)||F.isJsxSelfClosingElement(t)||F.isJsxFragment(t))return jo(t,e,n)}function jo(t,e,n){if(F.isJsxSelfClosingElement(t)){let i=Oo(t,e,n);return i===void 0?void 0:`<${i}/>`}let r=[];for(let i of t.children){let o=vf(i,e,n);if(o===void 0)return;r.push(o)}if(F.isJsxFragment(t))return`<>${r.join("")}</>`;let s=Oo(t.openingElement,e,n);return s===void 0?void 0:`<${s}>${r.join("")}</>`}function Cf(t,e){let n=F.createSourceFile(t.file,t.source,F.ScriptTarget.Latest,!0,F.ScriptKind.TSX),r=F.createPrinter({removeComments:!0}),s=[],i=a=>n.getLineAndCharacterOfPosition(a).line+1,o=a=>{if(F.isJsxElement(a)||F.isJsxSelfClosingElement(a)||F.isJsxFragment(a)){let c=jo(a,n,r);c!==void 0&&c.length>=e&&s.push({file:t.file,startLine:i(a.getStart(n)),endLine:i(a.getEnd()),canonicalShape:c})}F.forEachChild(a,o)};return o(n),s}function wf(t){let e=[...t].sort((s,i)=>i[0].canonicalShape.length-s[0].canonicalShape.length),n=new Map,r=[];for(let s of e){let i=s.filter(o=>!n.get(o.file)?.some(c=>c.start<=o.startLine&&o.endLine<=c.end));if(!(i.length<2)){for(let o of i){let a={start:o.startLine,end:o.endLine},c=n.get(o.file);c?c.push(a):n.set(o.file,[a])}r.push(i)}}return r}function Wo(t,e=40){let n=new Map;for(let i of t)for(let o of Cf(i,e)){let a=n.get(o.canonicalShape);a?a.push(o):n.set(o.canonicalShape,[o])}let r=[...n.values()].filter(i=>i.length>=2),s=[];for(let i of wf(r)){let o=i[0],a=i.map(c=>({file:c.file,startLine:c.startLine,endLine:c.endLine}));s.push({occurrences:a,lines:Math.max(...i.map(c=>c.endLine-c.startLine+1)),tokens:o.canonicalShape.length,kind:"definition",defKind:"jsxElement"})}return s}import M from"typescript";function Ef(t){let e=t;for(;M.isAsExpression(e)||M.isSatisfiesExpression(e)||M.isParenthesizedExpression(e);)e=e.expression;return e}function Tf(t,e,n){if(M.isPropertyAssignment(n)){if(M.isComputedPropertyName(n.name))return;let r=n.name.getText(e),s=t.printNode(M.EmitHint.Unspecified,n.initializer,e);return`${r}:${s}`}if(M.isShorthandPropertyAssignment(n)){let r=n.name.getText(e);return`${r}:${r}`}}function Ff(t){let e=t.filter(n=>n!==void 0);if(!(e.length<2||e.length!==t.length))return[...e].sort().join(";")}function Df(t){let e=M.createSourceFile(t.file,t.source,M.ScriptTarget.Latest,!0,M.ScriptKind.TSX),n=M.createPrinter({removeComments:!0}),r=[],s=o=>e.getLineAndCharacterOfPosition(o).line+1,i=o=>{if(M.isVariableDeclaration(o)&&M.isIdentifier(o.name)&&o.initializer&&M.isVariableDeclarationList(o.parent)&&(o.parent.flags&M.NodeFlags.Const)!==0){let a=Ef(o.initializer);if(M.isObjectLiteralExpression(a)){let c=Ff(a.properties.map(l=>Tf(n,e,l)));c!==void 0&&r.push({file:t.file,name:o.name.text,startLine:s(o.getStart(e)),endLine:s(o.getEnd()),memberCount:a.properties.length,canonicalShape:c})}}M.forEachChild(o,i)};return i(e),r}function $o(t,e=3){let n=new Map;for(let s of t)for(let i of Df(s)){if(i.memberCount<e)continue;let o=n.get(i.canonicalShape);o?o.push(i):n.set(i.canonicalShape,[i])}let r=[];for(let s of n.values()){if(s.length<2)continue;let i=s[0],o=s.map(a=>({file:a.file,startLine:a.startLine,endLine:a.endLine,name:a.name}));r.push({occurrences:o,lines:Math.max(...s.map(a=>a.endLine-a.startLine+1)),tokens:i.memberCount,kind:"definition",defKind:"objectLiteral"})}return r}function dn(t){return t.trim().replace(/\s+/g," ")}function Zr(t){try{return t.fileType==="scss"?an(t.source,t.file).root:t.fileType==="less"?on(t.source,t.file).root:t.fileType==="css"?sn(t.source,t.file).root:void 0}catch{return}}function Pf(t){let e=Zr(t);if(!e)return[];let n=[];return e.walkRules(r=>{let s=r.nodes?.filter(p=>p.type==="decl")??[];if(s.length===0)return;let i=s[0],o=s[s.length-1],a=r.source?.start?.line??i?.source?.start?.line,c=o?.source?.end?.line??o?.source?.start?.line??a;if(a===void 0||c===void 0)return;let l=s.map(p=>`${p.prop.trim().toLowerCase()}:${dn(p.value)}`).join(";");n.push({file:t.file,startLine:a,endLine:c,lines:c-a+1,signature:l,declCount:s.length})}),n}function zo(t,e,n=2){let r=new Map;for(let i of t)for(let o of Pf(i)){if(o.declCount<n||o.lines<e)continue;let a=r.get(o.signature);a?a.push(o):r.set(o.signature,[o])}let s=[];for(let i of r.values())for(let o=0;o<i.length;o++)for(let a=o+1;a<i.length;a++){let c=i[o],l=i[a];if(c.file===l.file&&c.startLine===l.startLine&&c.endLine===l.endLine)continue;let p={file:c.file,startLine:c.startLine,endLine:c.endLine},u={file:l.file,startLine:l.startLine,endLine:l.endLine};s.push({occurrences:[p,u],lines:Math.min(c.lines,l.lines),tokens:c.declCount,family:"style"})}return s.sort((i,o)=>o.lines-i.lines)}function Af(t){let e=Zr(t);if(!e)return[];let n=[];return e.walkDecls(r=>{let s=r.prop.startsWith("--"),i=t.fileType==="scss"&&r.prop.startsWith("$");if(!s&&!i)return;let o=r.source?.start?.line;o!==void 0&&n.push({file:t.file,line:o,name:r.prop,value:dn(r.value)})}),t.fileType==="less"&&e.walkAtRules(r=>{let{value:s}=r;if(s===void 0)return;let i=r.source?.start?.line;i!==void 0&&n.push({file:t.file,line:i,name:`@${r.name}`,value:dn(s)})}),n}function Bo(t,e=2){let n=t.flatMap(Af),r=new Map,s=new Map;for(let a of n){let c=r.get(a.value);c?c.push(a):r.set(a.value,[a]);let l=s.get(a.name);l?l.push(a):s.set(a.name,[a])}let i=(a,c)=>({file:a.file,startLine:a.line,endLine:a.line,name:a.name,...c?{value:a.value}:{}}),o=[];for(let a of r.values())a.length<e||o.push({occurrences:a.map(c=>i(c,!1)),lines:1,tokens:1,kind:"definition",defKind:"cssVar"});for(let a of s.values())a.length<e||new Set(a.map(l=>l.value)).size<2||o.push({occurrences:a.map(l=>i(l,!0)),lines:1,tokens:1,kind:"definition",defKind:"cssVar",signals:["value-drift"]});return o}function Uo(t){let e=t.length,n=[],r=[{lcpLength:0,low:0}];for(let s=1;s<e;s++){let i=s-1;for(;t[s]<r[r.length-1].lcpLength;){let o=r.pop();n.push({lcpLength:o.lcpLength,low:o.low,high:s-1}),i=o.low}t[s]>r[r.length-1].lcpLength&&r.push({lcpLength:t[s],low:i})}for(;r.length>1;){let s=r.pop();n.push({lcpLength:s.lcpLength,low:s.low,high:e-1})}return n}var Rf={typescript:{line:["//"],block:[["/*","*/"]]},javascript:{line:["//"],block:[["/*","*/"]]},go:{line:["//"],block:[["/*","*/"]]},java:{line:["//"],block:[["/*","*/"]]},kotlin:{line:["//"],block:[["/*","*/"]]},scala:{line:["//"],block:[["/*","*/"]]},groovy:{line:["//"],block:[["/*","*/"]]},css:{block:[["/*","*/"]]},scss:{line:["//"],block:[["/*","*/"]]},less:{line:["//"],block:[["/*","*/"]]},stylus:{line:["//"],block:[["/*","*/"]]},python:{line:["#"]},gherkin:{line:["#"]},coffeescript:{line:["#"],block:[["###","###"]]},livescript:{line:["#"],block:[["###","###"]]},lua:{line:["--"],block:[["--[[","]]"]]},markdown:{block:[["<!--","-->"]]}};function Ko(t,e,n){let r=t.slice(e,n).replace(/[^\n]/g," ");return t.slice(0,e)+r+t.slice(n)}function Nf(t,e){if(!e)return t;let n=t;for(let[r,s]of e.block??[]){let i=0;for(;;){let o=n.indexOf(r,i);if(o===-1)break;let a=n.indexOf(s,o+r.length),c=a===-1?n.length:a+s.length;n=Ko(n,o,c),i=c}}for(let r of e.line??[]){let s=0;for(;;){let i=n.indexOf(r,s);if(i===-1)break;let o=n.indexOf(`
23
+ `,i),a=o===-1?n.length:o;n=Ko(n,i,a),s=a}}return n}var Mf={typescript:[/^\s*import[\s{("*]/,/^\s*export\s.*\sfrom\s/],javascript:[/^\s*import[\s{("*]/,/^\s*export\s.*\sfrom\s/],python:[/^\s*import\s+\S/,/^\s*from\s+\S+\s+import[\s(]/],go:[/^\s*import\s+["(]/],java:[/^\s*import\s+/],kotlin:[/^\s*import\s+/],scala:[/^\s*import\s+/],groovy:[/^\s*import\s+/]};function If(t,e){let n=Mf[e];if(!n)return t;let r=t.split(`
24
+ `),s=e==="go",i=!1,o=!1;for(let a=0;a<r.length;a++){let c=r[a],l=()=>{r[a]=c.replace(/[^\r]/g," ")};if(i){l(),c.includes(")")&&(i=!1);continue}if(o){l(),(/}\s*from\s/.test(c)||c.includes("}"))&&(o=!1);continue}n.some(p=>p.test(c))&&(l(),s&&/^\s*import\s+\(/.test(c)&&!c.includes(")")?i=!0:(e==="typescript"||e==="javascript")&&/^\s*import\b/.test(c)&&c.includes("{")&&!c.includes("}")&&(o=!0))}return r.join(`
25
+ `)}var Jo=["===","!==","...","=>","==","!=","<=",">=","&&","||","::","->","..","+=","-=","*=","/="],qr=new RegExp(`${Jo.map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")}|[A-Za-z_$][A-Za-z0-9_$]*|\\d+(?:\\.\\d+)?|"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|\\S`,"g"),Lf=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ho=/^\d+(?:\.\d+)?$/,_f=/^(".*"|'.*'|`.*`)$/s,Vo=new Set(["if","else","elif","for","while","do","switch","case","default","break","continue","return","function","def","class","struct","interface","const","let","var","local","import","export","from","package","try","catch","except","finally","throw","raise","new","this","self","end","then","yield","async","await","nil","null","None","true","false","True","False","and","or","not","in","of","is"]),Gf=new Set(["+","-","*","%","&","|","!","^","~","?"]),Of=new Set(Jo);function Qo(t){return t==="ID"||t==="NUM"||t==="STR"?!1:Vo.has(t)?!0:t.length===1?Gf.has(t):Of.has(t)}function Yo(t,e,n=!0){let r=If(Nf(t,Rf[e]),e),s=[],i=1,o=0;qr.lastIndex=0;let a=qr.exec(r);for(;a!==null;){for(let p=o;p<a.index;p++)r[p]===`
26
+ `&&i++;o=a.index;let c=a[0],l=c;Lf.test(c)&&!Vo.has(c)?l="ID":n&&(Ho.test(c)||_f.test(c))&&(l=Ho.test(c)?"NUM":"STR"),s.push({text:l,line:i});for(let p=o;p<a.index+c.length;p++)r[p]===`
27
+ `&&i++;o=a.index+c.length,a=qr.exec(r)}return s}var jf=new Set(["{","}",":",",","[","]"]);function Xo(t,e,n){let r=0;for(let s=e;s<e+n;s++)jf.has(t[s].text)&&r++;return r/n}function Zo(t,e,n){let r=0;for(let s=e;s<e+n;s++)Qo(t[s].text)&&r++;return r}function qo(t){let e=t.length;if(e===0)return[];let n=Array.from({length:e},(i,o)=>o),r=new Array(e);{let i=[...new Set(t)].sort(),o=new Map(i.map((a,c)=>[a,c]));for(let a=0;a<e;a++)r[a]=o.get(t[a])}let s=new Array(e).fill(0);for(let i=1;i<e;i*=2){let o=a=>a+i<e?r[a+i]:-1;n.sort((a,c)=>{let l=r[a]-r[c];return l!==0?l:o(a)-o(c)}),s[n[0]]=0;for(let a=1;a<e;a++){let c=n[a-1],l=n[a],p=r[c]===r[l],u=o(c)===o(l);s[l]=s[c]+(p&&u?0:1)}if([r,s]=[s,r],r[n[e-1]]===e-1)break}return n}function ea(t,e){let n=t.length,r=new Array(n).fill(0);if(n===0)return r;let s=new Array(n);for(let o=0;o<n;o++)s[e[o]]=o;let i=0;for(let o=0;o<n;o++){let a=s[o];if(a>0){let c=e[a-1];for(;o+i<n&&c+i<n&&t[o+i]===t[c+i];)i++;r[a]=i,i>0&&i--}else i=0}return r}function ta(t,e,n,r=.5){let s=[],i=[],o=new Map;for(let{file:f,tokens:m}of t)if(m.length!==0){o.set(f,m);for(let h=0;h<m.length;h++)s.push(m[h].text),i.push({file:f,localIndex:h});s.push(` ${f}`),i.push({file:f,localIndex:-1})}if(s.length===0)return[];let a=qo(s),c=ea(s,a),l=Uo(c),p=[];for(let f of l){let m=Wf(f,a,i,o,e,n,r);m&&p.push(m)}return $f(p,o).sort((f,m)=>m.lines-f.lines)}function Wf(t,e,n,r,s,i,o){if(t.lcpLength<s)return;let a=[];for(let f=t.low;f<=t.high;f++){let m=n[e[f]];m.localIndex!==-1&&a.push(m)}if(a.length<2||!zf(a,r))return;let c=Bf(a,t.lcpLength);if(c.length<2)return;let l=c[0],p=r.get(l.file);if(!(Xo(p,l.localIndex,t.lcpLength)>o||Math.min(...c.map(({file:f,localIndex:m})=>{let h=r.get(f),b=h[m].line;return h[m+t.lcpLength-1].line-b+1}))<i))return{occurrences:c,lcpLength:t.lcpLength}}function $f(t,e){let n=[...t].sort((i,o)=>o.lcpLength-i.lcpLength),r=new Map,s=[];for(let i of n){let o=i.occurrences.filter(({file:u,localIndex:f})=>{let m=f+i.lcpLength;return!r.get(u)?.some(b=>b.start<=f&&m<=b.end)});if(o.length<2)continue;for(let{file:u,localIndex:f}of o){let m={start:f,end:f+i.lcpLength},h=r.get(u);h?h.push(m):r.set(u,[m])}let a=o.map(({file:u,localIndex:f})=>{let m=e.get(u);return{file:u,startLine:m[f].line,endLine:m[f+i.lcpLength-1].line}}),c=Math.min(...a.map(u=>u.endLine-u.startLine+1)),l=o[0],p=Zo(e.get(l.file),l.localIndex,i.lcpLength);s.push({occurrences:a,lines:c,tokens:i.lcpLength,score:p})}return s}function zf(t,e){let n=null;for(let{file:r,localIndex:s}of t){if(s===0)return!0;let o=e.get(r)[s-1].text;if(n===null)n=o;else if(n!==o)return!0}return!1}function Bf(t,e){let n=new Map;for(let{file:s,localIndex:i}of t){let o=n.get(s);o?o.push(i):n.set(s,[i])}let r=[];for(let[s,i]of n){i.sort((a,c)=>a-c);let o=Number.NEGATIVE_INFINITY;for(let a of i)a>=o&&(r.push({file:s,localIndex:a}),o=a+e)}return r}var Uf=/<\/?\s*(?:svg|path|g|circle|ellipse|rect|line|polygon|polyline|defs|use|symbol|mask|clipPath|linearGradient|radialGradient|stop|pattern|filter|fe[A-Z][A-Za-z]*|marker|foreignObject|tspan|textPath)\b/,Kf=/\b(?:viewBox|xmlns(?::xlink)?|xlink:href|fill-rule|clip-rule|stroke-width|stroke-linecap|stroke-linejoin|stroke-dasharray|stroke-miterlimit|gradientUnits|gradientTransform|patternUnits|patternTransform|preserveAspectRatio|pathLength|d|points|cx|cy|rx|ry)\s*=/,Hf=/^\s*(?:<\/?[A-Za-z>]|\/?>\s*$|[A-Za-z_$][\w:.$-]*\s*=\s*["'{])/;function na(t,e,n,r=.6){let s=t.split(`
28
+ `).slice(Math.max(0,e-1),n),i=0,o=0,a=!1;for(let c of s){if(c.trim().length===0)continue;i++;let l=Uf.test(c)||Kf.test(c);l&&(a=!0),(l||Hf.test(c))&&o++}return a&&i>0&&o/i>=r}import ee from"typescript";function Jf(t,e,n){if(!ee.isPropertySignature(n)||!n.type)return;let r=n.name.getText(e),s=n.questionToken?"?":"",i=t.printNode(ee.EmitHint.Unspecified,n.type,e);return`${r}${s}:${i}`}function Vf(t){let e=t.filter(n=>n!==void 0);if(!(e.length<2||e.length!==t.length))return[...e].sort().join(";")}function Qf(t){let e=ee.createSourceFile(t.file,t.source,ee.ScriptTarget.Latest,!0,ee.ScriptKind.TSX),n=ee.createPrinter({removeComments:!0}),r=[],s=o=>e.getLineAndCharacterOfPosition(o).line+1,i=o=>{let a,c,l;if(ee.isInterfaceDeclaration(o)?(a=o.name.text,c="interface",l=o.members):ee.isTypeAliasDeclaration(o)&&ee.isTypeLiteralNode(o.type)&&(a=o.name.text,c="type",l=o.type.members),a&&c&&l){let p=Vf(l.map(u=>Jf(n,e,u)));p!==void 0&&r.push({file:t.file,name:a,defKind:c,startLine:s(o.getStart(e)),endLine:s(o.getEnd()),memberCount:l.length,canonicalShape:p})}ee.forEachChild(o,i)};return i(e),r}function ra(t,e=2){let n=new Map;for(let s of t)for(let i of Qf(s)){if(i.memberCount<e)continue;let o=n.get(i.canonicalShape);o?o.push(i):n.set(i.canonicalShape,[i])}let r=[];for(let s of n.values()){if(s.length<2)continue;let i=s[0],o=s.map(a=>({file:a.file,startLine:a.startLine,endLine:a.endLine,name:a.name}));r.push({occurrences:o,lines:Math.max(...s.map(a=>a.endLine-a.startLine+1)),tokens:i.memberCount,kind:"definition",defKind:i.defKind})}return r}import Yf from"crypto";import Tt from"fs";import Xf from"path";function hn(t){let e=[];for(let r of t)e.push(`${r.path}\0${r.mtime}\0${r.size}`);e.sort();let n=Yf.createHash("sha256");for(let r of e)n.update(`${r}
29
+ `);return n.digest("hex")}function yn(t){return JSON.stringify({minLines:t.minLines,ignoreLiterals:t.ignoreLiterals,maxPunctuationRatio:t.maxPunctuationRatio,limit:t.limit,scope:t.scope??null,includeGenerated:t.includeGenerated,includeSameFile:t.includeSameFile,includeSvgMarkup:t.includeSvgMarkup,includeDocs:t.includeDocs,ignoreDirs:[...t.ignoreDirs].sort(),ignoreGlobs:[...t.ignoreGlobs].sort()})}function Zf(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.digest=="string"&&typeof e.paramsKey=="string"&&Array.isArray(e.groups)&&Array.isArray(e.clusters)}function xn(t,e,n){try{if(!Tt.existsSync(t))return null;let r=JSON.parse(Tt.readFileSync(t,"utf-8"));return!Zf(r)||r.digest!==e||r.paramsKey!==n?null:{groups:r.groups,clusters:r.clusters}}catch{return null}}function bn(t,e,n,r,s){try{let i=Xf.dirname(t);Tt.existsSync(i)||Tt.mkdirSync(i,{recursive:!0});let o={digest:e,paramsKey:n,groups:[...r],clusters:[...s]};Tt.writeFileSync(t,JSON.stringify(o))}catch(i){process.stderr.write(`Warning: failed to persist duplication result cache: ${i}
30
+ `)}}function es(t){let e=t.indexOf("/");return e===-1?".":t.slice(0,e)}function sa(t){let e={};for(let n of t)e[n]=(e[n]??0)+1;return e}function ia(t){return[...Ft(t)].sort().join("|")}function kn(t,e){let n=new Set;for(let r of e)if(!(r.matchCount<2))for(let s of r.groups)n.add(ia(s));return t.filter(r=>!n.has(ia(r)))}function Sn(t){let e={},n=[],r=0;for(let s of t){s.lines>r&&(r=s.lines);for(let i of s.signals??[])n.push(i);for(let i of new Set(s.occurrences.map(o=>es(o.file))))e[i]=(e[i]??0)+1}return{matched:t.length,byFamily:sa(t.map(s=>s.family??"other")),byTopDir:e,bySignal:sa(n),largestLines:r}}function Ft(t){return t.occurrences.map(e=>`${e.file}:${e.startLine}-${e.endLine}`)}function vn(t){let e=t.package;return{lines:t.lines,...t.score!==void 0&&{score:t.score},...t.family!==void 0&&{family:t.family},...t.kind!==void 0&&{kind:t.kind},...t.defKind!==void 0&&{defKind:t.defKind},...t.signals!==void 0&&{signals:t.signals},...e!==void 0&&{package:e},occurrences:Ft(t)}}function Cn(t){let e=t.package,n=t.groups[0];return{files:t.files,matchCount:t.matchCount,longestMatch:t.longestMatch,...n!==void 0&&{longestMatchAt:Ft(n)},coverage:t.coverage,...e!==void 0&&{package:e}}}import Dt from"fs";import qf from"path";function em(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.mtime=="number"&&typeof e.size=="number"&&typeof e.ignoreLiterals=="boolean"&&typeof e.generated=="boolean"&&Array.isArray(e.tokens)}function Ye(t){try{if(!Dt.existsSync(t))return new Map;let e=Dt.readFileSync(t,"utf-8"),n=JSON.parse(e);if(!Array.isArray(n))return new Map;let r=n.filter(s=>Array.isArray(s)&&s.length===2&&typeof s[0]=="string"&&em(s[1]));return new Map(r)}catch{return new Map}}function Xe(t,e){let n=qf.dirname(e);Dt.existsSync(n)||Dt.mkdirSync(n,{recursive:!0}),Dt.writeFileSync(e,JSON.stringify([...t.entries()]))}var nm=20,rm=new Set(["css","scss","less"]),sm=/(?:^|\/)(?:__tests__|__mocks__|__snapshots__|tests?|e2e)\/|\.(?:test|spec)\.[^/]*$|\.snap$/,im=3,om=6,am=120;function cm(t){return gt.includes(qe.basename(t))}function lm(t,e){if(e.length===0)return!1;let n=new Set(e);return t.split(qe.sep).some(r=>n.has(r))}function Ze(t,e,n){let r=[...t.signals??[]];return new Set(t.occurrences.map(s=>s.file)).size===1&&r.push("same-file"),t.occurrences.some(s=>e.has(s.file))&&r.push("generated"),t.occurrences.some(s=>sm.test(s.file))&&r.push("test"),t.family==="markdown"&&r.push("docs"),t.occurrences.length>0&&t.occurrences.every(s=>{let i=n.get(s.file);return i!==void 0&&na(i,s.startLine,s.endLine)})&&r.push("svg-markup"),r.length>0?{...t,signals:r}:t}function pm(t){return Math.max(0,...t.groups.map(n=>n.tokens))>=am?!0:t.groups.length>=im&&t.files.length<=om}function um(t,e){if(e==="all")return!0;let n=t.groups.some(r=>r.signals?.includes("test"));return e==="tests"?n&&pm(t):!n}async function et(t,e,n={}){let{minLines:r=6,windowSize:s=15,ignoreLiterals:i=!0,maxPunctuationRatio:o=.5,limit:a=50,ignoreDirs:c=j,includeGenerated:l=!1,includeSameFile:p=!1,includeSvgMarkup:u=!1,includeDocs:f=!1,scope:m="src",minScore:h=0,ignoreGlobs:b=[],parallelTokenizing:k=!0,tokenCache:S,filter:w}=n,N=w?Qe(w):void 0,_=[...t.nodes.values()].filter(B=>B.type!=="unknown"&&!cm(B.path)&&!lm(B.path,c)),X=new Set,pe=new Map,Se=fm(k,_.length);try{let B=[],re=[],ve=new Map;if(await Promise.all(_.map(async x=>{let T=gn(x.path,b);if(T&&!l)return;if(rm.has(x.type)){let O;try{O=await ts(qe.join(e,x.path),"utf8")}catch{return}let Ge=T||Et(O);if(Ge&&!l)return;Ge&&X.add(x.path),pe.set(x.path,O.split(`
31
+ `).length),B.push({file:x.path,source:O,fileType:x.type});return}let K=S?.get(x.path),Gt=K&&K.mtime===x.mtime&&K.size===x.size&&K.ignoreLiterals===i,fe,Z,H;if(Gt)fe=K.tokens,Z=K.generated;else{let O;try{O=await ts(qe.join(e,x.path),"utf8")}catch{return}if(Z=T||Et(O),Z&&!l)return;fe=Se?await Se.run({source:O,fileType:x.type,ignoreLiterals:i}):Yo(O,x.type,i),S?.set(x.path,{mtime:x.mtime,size:x.size,ignoreLiterals:i,generated:Z,tokens:fe}),H=O}if(Z&&!l)return;if(Z&&X.add(x.path),pe.set(x.path,H!==void 0?H.split(`
32
+ `).length:fe.at(-1)?.line??0),x.type==="typescript"||x.type==="javascript"){if(H===void 0)try{H=await ts(qe.join(e,x.path),"utf8")}catch{H=void 0}H!==void 0&&re.push({file:x.path,source:H})}let D=_o(x.type),G={file:x.path,tokens:fe},ct=ve.get(D);ct?ct.push(G):ve.set(D,[G])})),S){let x=new Set(_.map(T=>T.path));for(let T of S.keys())x.has(T)||S.delete(T)}let ue=new Map(re.map(x=>[x.file,x.source])),U=zo(B,r).map(x=>Ze(x,X,ue));for(let[x,T]of ve)for(let K of ta(T,s,r,o))U.push(Ze({...K,family:x},X,ue));for(let x of Bo(B))U.push(Ze({...x,family:"style"},X,ue));for(let x of ra(re))U.push(Ze({...x,family:"js"},X,ue));for(let x of $o(re))U.push(Ze({...x,family:"js"},X,ue));for(let x of Wo(re))U.push(Ze({...x,family:"js"},X,ue));let ot=U.filter(x=>!(!p&&x.signals?.includes("same-file")||!u&&x.signals?.includes("svg-markup")||!f&&x.signals?.includes("docs")||h>0&&(x.kind??"block")==="block"&&(x.score??x.tokens)<h||N&&!fn(x,N))),at=Lo(ot,pe).filter(x=>um(x,m)),Xn=new Set(at.flatMap(x=>x.groups)),$=x=>x.score??x.lines;return{groups:ot.filter(x=>Xn.has(x)).sort((x,T)=>$(T)-$(x)||T.lines-x.lines).slice(0,a),clusters:at.sort((x,T)=>Math.max(...T.groups.map($))-Math.max(...x.groups.map($))||T.longestMatch-x.longestMatch).slice(0,a)}}finally{Se&&await Se.destroy()}}function fm(t,e){if(t===!1)return null;let n=typeof t=="object"?t:{},r=n.minFiles??nm;if(e<r)return null;n.maxThreads!==void 0&&n.maxThreads<1&&process.stderr.write(`
33
+ Warning: parallelTokenizing.maxThreads (${n.maxThreads}) must be at least 1; using 1.
34
+ `);try{return new tm({filename:qe.join(g,"duplication-worker.js"),...n.maxThreads!==void 0?{maxThreads:Math.max(1,n.maxThreads)}:{}})}catch(s){return process.stderr.write(`
26
35
  Warning: failed to start duplicate-detection worker pool, falling back to synchronous tokenizing: ${s}
27
- `),null}}var Z=class{affectedSymbols=new Map;constructor(e,r){this.affectedSymbols.set(e,new Set(["default",...r]))}updateAffectedSymbols(e,r){let n=this.affectedSymbols.get(r)||new Set,s=e.imports.find(c=>c.toPath===r);if(!s)return!1;let o=s.symbols||["*"],i=new Set;for(let c of o)(c==="*"||n.has("*")||n.has(c))&&i.add("*");if(i.size===0)return!1;let a=this.affectedSymbols.get(e.path)||new Set;for(let c of i)a.add(c);return this.affectedSymbols.set(e.path,a),!0}};function ze(t,e){let r=t.nodes.get(e);if(r)return{category:r.category,exports:r.exports.map(n=>n.name)}}function Pr(t,e,r=1){let n=[];return t.traverse(e,(s,o,i)=>{if(s.path===e)return!0;let a=i?t.nodes.get(i)?.imports.find(c=>c.toPath===s.path):void 0;return n.push({path:s.path,...a?.symbols?{symbols:a.symbols}:{}}),!0},{direction:"outgoing",maxDepth:r}),n}function We(t,e){let r=[];return t.traverse(e,n=>{if(n.path===e)return!0;let s=n.imports.find(o=>o.toPath===e);return r.push({path:n.path,...s?.symbols?{symbols:s.symbols}:{}}),!0},{direction:"incoming",maxDepth:1}),r}function Ar(t,e,r={}){let{testsOnly:n=!1,changedSymbols:s}=r,o=s?new Z(e,s):null,i=[];return t.traverse(e,(a,c,l)=>{if(a.path===e)return!0;if(o&&l&&!o.updateAffectedSymbols(a,l))return!1;let p=a.category==="test"||a.tags.some(u=>u.name==="test");return(!n||p)&&i.push(a.path),!0},{direction:"incoming"}),i}function Nr(t,e,r={}){let{depth:n=1,withEdgeDetail:s=!1}=r,o=[];return t.traverseCalls(e,i=>{if(i.path===e)return!0;let a={file:i.path};return s&&(a.edges=(i.callEdges??[]).filter(c=>c.toFile===e).map(c=>({from:c.from,to:c.to}))),o.push(a),!0},{direction:"incoming",maxDepth:n}),o}function xe(t,e={}){let{metric:r="cognitiveComplexity",threshold:n=10,limit:s=20}=e;return[...t.nodes.values()].flatMap(o=>(o.functions??[]).filter(i=>i[r]>=n).map(i=>({file:o.path,name:i.name,line:i.line,complexity:i.complexity,cognitiveComplexity:i.cognitiveComplexity}))).sort((o,i)=>i[r]-o[r]).slice(0,s)}function Dr(t){return{nodes:t.nodes.map(r=>({path:r.path,type:r.type,category:r.category,exports:r.exports.map(n=>n.name),tags:r.tags.filter(n=>n.kind==="comment-marker"||n.kind==="import").map(n=>n.name),importsFiles:r.imports.filter(n=>!n.isExternal&&n.toPath).map(n=>n.toPath),...r.description!==void 0&&{description:r.description},...r.testedBy!==void 0&&{testedBy:r.testedBy},...r.coveragePct!==void 0&&{coveragePct:r.coveragePct},...r.avgExportUsage!==void 0&&{avgExportUsage:r.avgExportUsage},...r.maxExportUsage!==void 0&&{maxExportUsage:r.maxExportUsage}})),cycles:t.cycles}}function Rr(t){let e=t.getPackageDependencies(),r=Array.from(t.packages.values()).map(({graph:n,pkg:s})=>({name:s.name,relativeRoot:s.relativeRoot,nodeCount:n.nodes.size,dependsOn:e.get(s.name)??[]}));return{monorepoType:t.type,packageCount:r.length,packages:r}}function X(t){return[...t.nodes.values()].some(e=>e.coveragePct!==void 0)}function Zs(t){return[...t.nodes.values()].some(e=>e.commitCount90d!==void 0)}function be(t,e={}){let{metric:r="cognitiveComplexity",minComplexity:n=10,maxCoveragePct:s=50,minChurn:o=0,limit:i=20}=e,a=Zs(t),c=[...t.nodes.values()].filter(l=>l.coveragePct!==void 0&&l.coveragePct<=s&&(!a||(l.commitCount90d??0)>=o)).flatMap(l=>(l.functions??[]).filter(p=>p[r]>=n).map(p=>({file:l.path,name:p.name,line:p.line,complexity:p.complexity,cognitiveComplexity:p.cognitiveComplexity,coveragePct:l.coveragePct,...l.commitCount90d!==void 0&&{commitCount90d:l.commitCount90d}}))).sort((l,p)=>p[r]-l[r]).slice(0,i);return{hotspots:c,count:c.length,churnDataAvailable:a}}import{execFileSync as Mr}from"child_process";import Ir from"fs";import Zl from"os";import Xl from"path";function Lr(t,e){try{return Mr("git",["rev-parse","--verify",`${e}^{commit}`],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error(`Could not resolve git ref "${e}" in ${t}`)}}async function Xs(t,e,r){let n=Ir.mkdtempSync(Xl.join(Zl.tmpdir(),`mokosh-worktree-${e.slice(0,12)}-`));Ir.rmdirSync(n);try{return Mr("git",["worktree","add","--detach",n,e],{cwd:t,stdio:["ignore","pipe","pipe"]}),await r(n)}finally{try{Mr("git",["worktree","remove","--force",n],{cwd:t,stdio:["ignore","pipe","pipe"]})}catch{Ir.rmSync(n,{recursive:!0,force:!0})}}}async function oo(t,e,r,n={}){let s=Lr(t,e),o=An(t,s);if(o)return{sha:s,graph:o};let i=await Xs(t,s,async a=>{let c=n.pathAliases?new z(a,{pathAliases:n.pathAliases}):void 0;return new Y(a,null,c,void 0,n.gitStats??!1,new Map,n.parallelParsing??!0,n.additionalIgnoreDirs??[]).build(r)});return Nn(t,s,i),{sha:s,graph:i}}var eo=t=>Math.round(t*100)/100,to=t=>t.length>8?t.slice(0,8):t;function tp(t,e){return`${t.file}:${t.line} ${t.name} (${t[e]})`}function rp(t,e){return`${t.file}:${t.line} ${t.name} (${t[e]}, cov ${t.coveragePct}%)`}function np(t,e=4){let r=t.occurrences.slice(0,e).map(o=>`${o.file}:${o.startLine}-${o.endLine}`),n=t.occurrences.length-r.length,s=n>0?`, +${n} more`:"";return`${t.lines}L x${t.occurrences.length}: ${r.join(", ")}${s}`}var ee=(t,e)=>`${t} ${e}${t===1?"":"s"}`;function sp(t,e){let{files:r,staleReferences:n,duplication:s,complexity:o,docDrift:i,coverage:a}=t,c=[],l=[r.added.length&&`${r.added.length} added`,r.changed.length&&`${r.changed.length} changed`,r.removed.length&&`${r.removed.length} removed`].filter(Boolean);c.push(l.length?`Files: ${l.join(", ")}`:"No file changes"),n.length>0&&c.push(`\u26A0 ${ee(n.length,"stale reference")} \u2014 removed export still imported`);let p=o.newHotspots[0];return p?c.push(`+${ee(o.newHotspots.length,"complexity hotspot")} (max ${e} ${p[e]} in ${p.file})`):o.resolvedHotspots.length>0&&c.push(`${ee(o.resolvedHotspots.length,"complexity hotspot")} resolved`),s.newGroups.length>0?c.push(`+${ee(s.newGroups.length,"duplication group")}`):s.resolvedGroups.length>0&&c.push(`${ee(s.resolvedGroups.length,"duplication group")} resolved`),i.newlyStale.length>0&&c.push(`${ee(i.newlyStale.length,"doc")} newly stale`),a&&a.newHotspots.length>0&&c.push(`+${ee(a.newHotspots.length,"risk hotspot")}`),c}function op(t){let{staleReferences:e,duplication:r,complexity:n,docDrift:s,coverage:o}=t;return e.length>0||(o?.newHotspots.length??0)>0?"attention":n.newHotspots.length>0||r.newGroups.length>0||s.newlyStale.length>0?"review-worthy":"clean"}function _r(t,e={}){let r=e.metric??"cognitiveComplexity",n=e.maxItems??8,s=e.maxPathList??100,{files:o,staleReferences:i,duplication:a,complexity:c,docDrift:l,coverage:p}=t,u=eo(c.head.avgCognitiveComplexity-c.base.avgCognitiveComplexity),g=o.added.length+o.changed.length+o.removed.length,d={base:`${t.base.ref}@${to(t.base.sha)}`,head:`${t.head.ref}@${to(t.head.sha)}`,verdict:op(t),headline:sp(t,r),files:{added:o.added.length,changed:o.changed.length,removed:o.removed.length,...g<=s?{paths:{added:o.added,changed:o.changed,removed:o.removed}}:{}}};return i.length>0&&(d.staleReferences=i),(c.newHotspots.length>0||c.resolvedHotspots.length>0)&&(d.complexity={avgDelta:u,newHotspots:c.newHotspots.slice(0,n).map(y=>tp(y,r)),newHotspotCount:c.newHotspots.length,resolvedCount:c.resolvedHotspots.length}),(a.newGroups.length>0||a.resolvedGroups.length>0)&&(d.duplication={newGroups:a.newGroups.slice(0,n).map(y=>np(y)),newGroupCount:a.newGroups.length,resolvedCount:a.resolvedGroups.length,totalGroups:a.head.groups}),(l.newlyStale.length>0||l.resolved.length>0)&&(d.docDrift={newlyStale:l.newlyStale.slice(0,n).map(y=>y.replace("::"," \u2192 ")),newlyStaleCount:l.newlyStale.length,resolvedCount:l.resolved.length}),p&&(p.newHotspots.length>0||p.resolvedHotspots.length>0)&&(d.coverage={avgDelta:eo(p.head.avgCoveragePct-p.base.avgCoveragePct),newHotspots:p.newHotspots.slice(0,n).map(y=>rp(y,r)),newHotspotCount:p.newHotspots.length,resolvedCount:p.resolvedHotspots.length}),d}function ip(t,e){let r=[],n=[];for(let[o,i]of e.nodes){let a=t.nodes.get(o);if(!a){r.push(o);continue}let c=JSON.stringify({category:a.category,exports:a.exports.map(p=>p.name).sort(),imports:a.imports.map(p=>p.toPath).sort()}),l=JSON.stringify({category:i.category,exports:i.exports.map(p=>p.name).sort(),imports:i.imports.map(p=>p.toPath).sort()});c!==l&&n.push(o)}let s=[...t.nodes.keys()].filter(o=>!e.nodes.has(o));return{added:r,removed:s,changed:n}}function ap(t,e){let r=[];for(let[n,s]of t.nodes){let o=e.nodes.get(n);if(!o)continue;let i=new Set(o.exports.map(c=>c.name)),a=s.exports.map(c=>c.name).filter(c=>!i.has(c));if(a.length!==0)for(let c of a){let l=[...e.nodes.values()].filter(p=>p.imports.some(u=>u.toPath===n&&u.symbols?.includes(c))).map(p=>p.path);l.length>0&&r.push({file:n,symbol:c,stillReferencedBy:l})}}return r}function ht(t){return t.occurrences.map(e=>`${e.file}:${e.startLine}-${e.endLine}`).sort().join("|")}async function cp(t,e,r,n,s){let o=ep.join(et(t),`${n}-${we}`),i=de(o),[{groups:a},{groups:c}]=await Promise.all([ye(e,t,{minLines:s,tokenCache:i}),ye(r,t,{minLines:s})]);he(i,o);let l=new Set(a.map(ht)),p=new Set(c.map(ht));return{base:{groups:a.length},head:{groups:c.length},newGroups:c.filter(u=>!l.has(ht(u))),resolvedGroups:a.filter(u=>!p.has(ht(u)))}}function ro(t){let e=[...t.nodes.values()].map(r=>r.cognitiveComplexity).filter(r=>r!==void 0);return e.length===0?0:e.reduce((r,n)=>r+n,0)/e.length}function lp(t,e,r,n){let s=xe(t,{metric:r,threshold:n,limit:1/0}),o=xe(e,{metric:r,threshold:n,limit:1/0}),i=l=>`${l.file}:${l.name}`,a=new Set(s.map(i)),c=new Set(o.map(i));return{base:{avgCognitiveComplexity:ro(t)},head:{avgCognitiveComplexity:ro(e)},newHotspots:o.filter(l=>!a.has(i(l))),resolvedHotspots:s.filter(l=>!c.has(i(l)))}}function no(t){let e=new Set;for(let r of t.nodes.values())if(!(r.type!=="markdown"||!r.staleFor))for(let n of r.staleFor)e.add(`${r.path}::${n}`);return e}function pp(t,e){let r=no(t),n=no(e);return{base:{staleCount:r.size},head:{staleCount:n.size},newlyStale:[...n].filter(s=>!r.has(s)),resolved:[...r].filter(s=>!n.has(s))}}function so(t){let e=[...t.nodes.values()].map(r=>r.coveragePct).filter(r=>r!==void 0);return e.length===0?0:e.reduce((r,n)=>r+n,0)/e.length}function up(t,e,r){if(!X(t)||!X(e))return null;let n=be(t,{maxCoveragePct:r,limit:1/0}).hotspots,s=be(e,{maxCoveragePct:r,limit:1/0}).hotspots,o=c=>`${c.file}:${c.name}`,i=new Set(n.map(o)),a=new Set(s.map(o));return{base:{avgCoveragePct:so(t)},head:{avgCoveragePct:so(e)},newHotspots:s.filter(c=>!i.has(o(c))),resolvedHotspots:n.filter(c=>!a.has(o(c)))}}async function Gr(t,e,r,n={}){let{sha:s,graph:o}=await oo(t,e,n.entryPoints??[],n),i=Lr(t,n.headRef??"HEAD"),[a,c]=await Promise.all([cp(t,o,r,s,n.minDuplicateLines),Promise.resolve(up(o,r,n.maxCoveragePct))]);return{base:{ref:e,sha:s},head:{ref:n.headRef??"HEAD",sha:i},files:ip(o,r),staleReferences:ap(o,r),duplication:a,complexity:lp(o,r,n.complexityMetric,n.complexityThreshold),docDrift:pp(o,r),coverage:c}}import yt from"path";function fp(t){let e=new Map;for(let[r,n]of t){let s=n.imports.filter(o=>o.toPath&&!o.isExternal).length;s>0&&e.set(r,s)}return e}function mp(t,e,r){let n=new Map;for(let[s,o]of e){if(o<r)continue;let i=t.get(s);if(!i||i.category==="test"||i.category==="barrel")continue;let a=yt.extname(s),c=yt.basename(s,a),l=c==="index"?yt.basename(yt.dirname(s)):c;n.set(s,{path:s,outDegree:o,tag:`feature:${l}`})}return n}function te(t,e){let r=e?.minOutDegree??5;return mp(t,fp(t),r)}var gp=(t,e)=>t.outDegree-e.outDegree;function dp(t,e){let r=new Map;for(let n of e.values()){let s=new Set;t.traverse(n.path,o=>(o.path!==n.path&&s.add(o.path),!0),{direction:"outgoing"}),r.set(n.path,s)}return r}function hp(t,e,r,n){let s=new Map;for(let[o]of t){if(e.has(o))continue;let i=null;for(let a of e.values())r.get(a.path)?.has(o)&&(!i||n(a,i)<0)&&(i=a);i&&s.set(o,i.path)}return s}function yp(t,e){let r=new Map;for(let n of t.values()){let s=n.tag.replace("feature:",""),o=[];for(let[i,a]of e)a===n.path&&o.push(i);r.set(s,{hub:n.path,outDegree:n.outDegree,files:o})}return r}function xp(t,e,r){let n=[];for(let s of t.keys())!e.has(s)&&!r.has(s)&&n.push(s);return n}function $e(t,e){let r=e?.detectFn??te,n=e?.hubComparator??gp,s=r(t.nodes,e),o=dp(t,s),i=hp(t.nodes,s,o,n);return{features:yp(s,i),unassigned:xp(t.nodes,s,i)}}var bp=[{role:"component",segments:["component","components"]},{role:"controller",segments:["controller","controllers"]},{role:"middleware",segments:["middleware"]},{role:"router",segments:["router","routes","route"]},{role:"store",segments:["store","stores"]},{role:"service",segments:["service","services"]},{role:"handler",segments:["handler","handlers"]},{role:"adapter",segments:["adapter","adapters"]},{role:"plugin",segments:["plugin","plugins"]},{role:"api",segments:["api"]},{role:"cli",segments:["cli","commands"],basenames:["cli"]},{role:"util",segments:["util","utils","helper","helpers"]},{role:"model",segments:["model","models"],basenames:["model"]},{role:"parser",segments:["parser","parsers"],basenames:["parser"]},{role:"builder",basenames:["builder"]},{role:"resolver",basenames:["resolver"]}];function io(t){if(t.category==="test")return"test";if(t.category==="config")return"config";if(t.category==="type-only")return"types";let e=t.path,r=vp(e);for(let n of bp)if(n.segments?.some(s=>Sp(e,s))||n.basenames?.includes(r))return n.role;return"other"}function Sp(t,e){return t.includes(`/${e}/`)||t.includes(`/${e}.`)}function vp(t){let e=t.slice(t.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function Or(t,e){let r=$e(t,e),n=new Map;for(let[o,i]of r.features){for(let a of i.files)n.set(a,o);n.set(i.hub,o)}let s=new Map;for(let o of t.nodes.values()){let i=n.get(o.path);s.set(o.path,{path:o.path,role:io(o),...o.description?{description:o.description}:{},exports:o.exports.map(a=>a.name),...i?{featureHub:i}:{}})}return s}function jr(t,e){let r=[];for(let n of t.nodes.values())if(n.exports.some(s=>s.name===e))if(ft.has(n.type)){let s=[];for(let o of t.nodes.values())for(let i of o.callEdges??[])i.to===e&&s.push({file:o.path,callerFunction:i.from});r.push({path:n.path,category:n.category,precision:"call",callers:s})}else{let s=We(t,n.path).map(o=>({file:o.path,...o.symbols?{symbols:o.symbols}:{}}));r.push({path:n.path,category:n.category,precision:"file-level",importers:s})}return r}function kp(t){return t?t.startsWith("interface ")?"interface":t.startsWith("class ")?"class":t.startsWith("enum ")?"enum":"type":"type"}function Cp(t,e){if(e==="type-only")return!0;let r=t.signature??"";return r.startsWith("interface ")||r.startsWith("class ")||r.startsWith("enum ")}function zr(t){let e=new Map;for(let n of t.nodes.values())if(!(n.type!=="typescript"&&n.type!=="javascript"))for(let s of n.exports){if(!Cp(s,n.category))continue;let o=`${n.path}::${s.name}`;e.set(o,{name:s.name,file:n.path,kind:kp(s.signature),...s.doc?{doc:s.doc}:{}})}let r=[];for(let n of t.nodes.values())if(!(n.type!=="typescript"&&n.type!=="javascript")){for(let s of n.imports)if(!(!s.toPath||s.isExternal||!s.symbols?.length))for(let o of s.symbols)e.has(`${s.toPath}::${o}`)&&r.push({fromFile:n.path,toType:o,toFile:s.toPath})}return{types:e,edges:r}}function Wr(t,e){let r=null;for(let o of t.types.values())if(o.name===e){r=o;break}if(!r)return{type:null,usedByFiles:[],uses:[]};let n=new Set,s=new Map;for(let o of t.edges)if(o.toType===e&&o.toFile===r.file&&n.add(o.fromFile),o.fromFile===r.file){let i=t.types.get(`${o.toFile}::${o.toType}`);i&&s.set(`${i.file}::${i.name}`,i)}return{type:r,usedByFiles:Array.from(n),uses:Array.from(s.values())}}import $p from"path";import lo from"fs";import po from"path";import wp from"fs";import $r from"path";import ao from"fs";import kx from"path";function xt(t){try{return ao.statSync(t,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function bt(t){try{return ao.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}var Ep=new Set([".java",".kt",".kts",".scala",".sc",".groovy",".gradle"]),Fp=new Set(T);function co(t,e=[]){let r;try{r=wp.readdirSync(t,{withFileTypes:!0})}catch{return e}for(let n of r){let s=$r.join(t,n.name);n.isDirectory()?!Fp.has(n.name)&&!n.name.startsWith(".")&&co(s,e):n.isFile()&&Ep.has($r.extname(n.name).toLowerCase())&&e.push(s)}return e}function St(t,e,r){if(!xt(e))return null;let n=co(e);return n.length===0?null:{name:r,root:e,relativeRoot:$r.relative(t,e),entryPoints:n}}function Tp(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Pp(t){let e=Tp(t),r=new Set;for(let n of e.matchAll(/['"](:[A-Za-z0-9_\-.:]+)['"]/g)){let s=n[1].replace(/^:/,"").replace(/:$/,"");s&&r.add(s)}return[...r]}var uo={type:"gradle",detect(t){let e=["settings.gradle.kts","settings.gradle"].map(o=>po.join(t,o)).find(o=>lo.existsSync(o));if(!e)return null;let r;try{r=lo.readFileSync(e,"utf-8")}catch{return null}let n=Pp(r);if(n.length===0)return null;let s=[];for(let o of n){let i=po.join(t,...o.split(":")),a=St(t,i,o);a&&s.push(a)}return s.length>0?s:null}};import Hr from"fs";import mo from"path";import Be from"fs";import N from"path";function Br(t,e){let r=N.join(e,"package.json");if(!Be.existsSync(r))return null;let n={};try{n=JSON.parse(Be.readFileSync(r,"utf-8"))}catch{return null}let s=n.name;return s?{name:s,root:e,relativeRoot:N.relative(t,e),entryPoints:Ap(e,n)}:null}function Ap(t,e){let r=[];if(e.exports){let s=e.exports;if(typeof s=="string")r.push(N.join(t,s));else if(typeof s=="object"&&s!==null){let o=s["."];if(typeof o=="string")r.push(N.join(t,o));else if(typeof o=="object"&&o!==null){let i=o.import??o.require??o.default;typeof i=="string"&&r.push(N.join(t,i))}}}e.main&&r.push(N.join(t,e.main));for(let s of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])r.push(N.join(t,s));let n=r.filter(bt);return n.length>0?n.slice(0,1):r.slice(0,1)}function Se(t,e){let r=[],n=new Set;for(let s of e){let o=s.replace(/\/$/,"").replace(/^\.\//,"");Np(t,o,n,r)}return r}function Np(t,e,r,n){if(!e.includes("*")){Dp(t,e,r,n);return}let s=e.split("/");s.includes("**")?Rp(t,s,r,n):Ip(t,s,r,n)}function Dp(t,e,r,n){let s=N.join(t,e);if(r.has(s)||!xt(s))return;r.add(s);let o=Br(t,s);o&&n.push(o)}function Rp(t,e,r,n){let s=N.join(t,e[0]==="**"?"":e[0]??"");fo(t,s,r,n)}function Ip(t,e,r,n){let s=e.findIndex(a=>a.includes("*")),o=N.join(t,...e.slice(0,s)),i;try{i=Be.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let c=N.join(o,a.name);if(r.has(c))continue;r.add(c);let l=Br(t,c);l&&n.push(l)}}function fo(t,e,r,n){let s;try{s=Be.readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of s){if(!o.isDirectory()||o.name==="node_modules"||o.name.startsWith("."))continue;let i=N.join(e,o.name);if(Be.existsSync(N.join(i,"package.json"))&&!r.has(i)){r.add(i);let a=Br(t,i);a&&n.push(a)}else fo(t,i,r,n)}}var go={type:"npm",detect(t){let e=mo.join(t,"package.json");if(!Hr.existsSync(e))return null;let r;try{r=JSON.parse(Hr.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r||Hr.existsSync(mo.join(t,"yarn.lock")))return null;let n=Array.isArray(r)?r:r.packages??[];return n.length===0?null:Se(t,n)}};import ve from"fs";import E from"path";var ho={type:"nx",detect(t){return ve.existsSync(E.join(t,"nx.json"))?yo(t,t,new Set,0).map(r=>Mp(t,r,E.join(r,"project.json"))).filter(r=>r!==null):null}};function yo(t,e,r,n){if(n>4)return[];let s;try{s=ve.readdirSync(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let i of s){if(!i.isDirectory())continue;let a=i.name;if(a.startsWith(".")||a==="node_modules"||a==="dist"||a===".nx")continue;let c=E.join(e,a);ve.existsSync(E.join(c,"project.json"))&&!r.has(c)?(r.add(c),o.push(c)):o.push(...yo(t,c,r,n+1))}return o}function Mp(t,e,r){let n={};try{n=JSON.parse(ve.readFileSync(r,"utf-8"))}catch{return null}let s=n.name,o,i,a=E.join(e,"package.json");if(ve.existsSync(a))try{let c=JSON.parse(ve.readFileSync(a,"utf-8"));s=c.name??s,o=c.main,i=c.exports}catch{}return s?{name:s,root:e,relativeRoot:E.relative(t,e),entryPoints:Lp(e,n,o,i)}:null}function Lp(t,e,r,n){let s=[],o=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(o){let a=E.resolve(t,"../..");s.push(E.resolve(a,o)),s.push(E.resolve(t,o))}if(n){let a=n;if(typeof a=="string")s.push(E.join(t,a));else if(typeof a=="object"&&a!==null){let c=a["."];typeof c=="string"&&s.push(E.join(t,c))}}if(r&&s.push(E.join(t,r)),e.sourceRoot){let a=E.resolve(t,"../.."),c=E.resolve(a,e.sourceRoot);s.push(E.join(c,"index.ts"),E.join(c,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])s.push(E.join(t,a));let i=s.filter(bt);return i.length>0?i.slice(0,1):s.slice(0,1)}import xo from"fs";import _p from"path";import{load as Gp}from"js-yaml";var bo={type:"pnpm",detect(t){let e=_p.join(t,"pnpm-workspace.yaml");if(!xo.existsSync(e))return null;let r=[];try{r=Gp(xo.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return Se(t,r)}};import He from"fs";import vt from"path";function Op(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function jp(t){let e=Op(t),r=new Map;for(let n of e.matchAll(/(?:lazy\s+)?val\s+([A-Za-z0-9_]+)\s*=\s*\(?\s*project\b([^\n]*)/g)){let s=n[1],i=n[2].match(/\bfile\s*\(\s*["']([^"']+)["']\s*\)/),a=i?i[1]:s;if(a==="."||a==="./")continue;let c=a.replace(/^\.\//,"").replace(/\/$/,"");r.has(c)||r.set(c,{name:s,dir:c})}return[...r.values()]}var So={type:"sbt",detect(t){let e=vt.join(t,"build.sbt"),r=vt.join(t,"project");if(!He.existsSync(e)||!He.existsSync(r))return null;let n=[];try{n.push(He.readFileSync(e,"utf-8"))}catch{return null}try{for(let a of He.readdirSync(r))a.endsWith(".scala")&&n.push(He.readFileSync(vt.join(r,a),"utf-8"))}catch{}let s=new Set,o=[];for(let a of n)for(let c of jp(a))s.has(c.dir)||(s.add(c.dir),o.push(c));if(o.length===0)return null;let i=[];for(let a of o){let c=vt.join(t,...a.dir.split("/")),l=St(t,c,a.name);l&&i.push(l)}return i.length>0?i:null}};import zp from"fs";import Wp from"path";var vo={type:"turborepo",detect(t){return zp.existsSync(Wp.join(t,"turbo.json"))?[]:null}};import Ur from"fs";import ko from"path";var Co={type:"yarn",detect(t){if(!Ur.existsSync(ko.join(t,"yarn.lock")))return null;let e=ko.join(t,"package.json");if(!Ur.existsSync(e))return null;let r;try{r=JSON.parse(Ur.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r)return null;let n=Array.isArray(r)?r:r.packages??[];return n.length===0?null:Se(t,n)}};var wo=[];function M(t){wo.push(t)}function Eo(){return wo}M(vo);M(ho);M(bo);M(Co);M(go);M(uo);M(So);function Ue(t,e=Eo()){let r=$p.resolve(t),n=new Map,s=[];for(let i of e){let a=i.detect(r);if(a!==null){s.push(i.type);for(let c of a)n.has(c.name)||n.set(c.name,c)}}if(s.length===0)return{root:r,type:"none",types:[],packages:[],packageMap:new Map};let o=Array.from(n.values());return{root:r,type:s[0],types:s,packages:o,packageMap:new Map(o.map(i=>[i.name,i]))}}var Je=class t{constructor(e,r){this.monorepoRoot=e;this.type=r}monorepoRoot;type;packages=new Map;addPackage(e,r){this.packages.set(e.name,{graph:r,pkg:e})}annotateCrossPackageEdges(){for(let{graph:e}of this.packages.values())for(let r of e.nodes.values()){let n=this.getPackageForFile(r.path);if(n)for(let s of r.imports){if(s.isExternal||s.isWorkspace)continue;let o=this.getPackageForFile(s.toPath);o&&o.name!==n.name&&(s.isWorkspace=!0,s.workspacePackage=o.name)}}}getPackageForFile(e){for(let{pkg:r}of this.packages.values())if(e===r.relativeRoot||e.startsWith(`${r.relativeRoot}/`))return r}getPackageDependencies(){let e=new Map;for(let{graph:r,pkg:n}of this.packages.values()){let s=new Set;for(let o of r.nodes.values())for(let i of o.imports)i.isWorkspace&&i.workspacePackage&&s.add(i.workspacePackage);e.set(n.name,[...s])}return e}getAffectedAcrossPackages(e){let r=this.getPackageForFile(e);if(!r)return[];let n=this.packages.get(r.name);if(!n)return[];let s=[];n.graph.traverse(e,o=>(o.path!==e&&s.push({file:o.path,package:r.name}),!0),{direction:"incoming"});for(let{graph:o,pkg:i}of this.packages.values())if(i.name!==r.name)for(let a of o.nodes.values())a.imports.some(l=>l.isWorkspace&&l.workspacePackage===r.name)&&s.push({file:a.path,package:i.name});return s}serialize(){return{monorepoRoot:this.monorepoRoot,type:this.type,packages:Array.from(this.packages.values()).map(({graph:e,pkg:r})=>({pkg:{name:r.name,relativeRoot:r.relativeRoot,entryPoints:r.entryPoints},nodes:Array.from(e.nodes.values())}))}}static deserialize(e){let r=new t(e.monorepoRoot,e.type);for(let{pkg:n,nodes:s}of e.packages){let o=new Map(s.map(a=>[a.path,a])),i=new P(o);r.packages.set(n.name,{graph:i,pkg:{...n,root:""}})}return r}};function Fo(t,e){return e.startsWith("!")?t!==e.slice(1):t===e}function Bp(t,e){return e.startsWith("!")?!t.includes(e.slice(1)):t.includes(e)}var Hp=(t,e)=>!e.category||Fo(t.category,e.category),Up=(t,e)=>!e.type||Fo(t.type,e.type),Jp=(t,e)=>e.lastAuthor?e.lastAuthor.startsWith("!")?t.lastAuthor!==e.lastAuthor.slice(1):t.lastAuthor!==void 0&&t.lastAuthor===e.lastAuthor:!0,Kp=(t,e)=>!e.path||Bp(t.path,e.path),qp=(t,e)=>e.isExternal===void 0?!0:t.imports.some(n=>n.isExternal)===e.isExternal,Vp=(t,e)=>{if(!e.tags||e.tags.length===0)return!0;let r=e.tags.filter(s=>!s.startsWith("!")),n=e.tags.filter(s=>s.startsWith("!")).map(s=>s.slice(1));return!(r.length>0&&!r.some(s=>t.tags.some(o=>o.name===s))||n.some(s=>t.tags.some(o=>o.name===s)))},Qp=(t,e)=>!e.allTags?.length||e.allTags.every(r=>t.tags.some(n=>n.name===r)),Yp=(t,e)=>!e.importsFile||t.imports.some(r=>r.toPath?.includes(e.importsFile)),Zp=(t,e,r)=>e.importedBy===void 0?!0:(r?.get(t.path)??[]).some(s=>s.includes(e.importedBy)),Xp=(t,e)=>e.minImports===void 0||t.imports.length>=e.minImports,eu=(t,e)=>e.maxImports===void 0||t.imports.length<=e.maxImports,tu=(t,e)=>e.minSize===void 0||t.size>=e.minSize,ru=(t,e)=>e.maxSize===void 0||t.size<=e.maxSize,nu=(t,e)=>e.hasDocstring===void 0||!!t.description===e.hasDocstring,su=(t,e)=>e.isDocumented===void 0||!!t.documentedBy?.length===e.isDocumented,ou=(t,e)=>e.isStale===void 0||!!t.staleFor?.length===e.isStale,iu=(t,e)=>e.minCoverage===void 0||(t.coveragePct??101)>=e.minCoverage,au=(t,e)=>e.maxCoverage===void 0||(t.coveragePct??0)<=e.maxCoverage,cu=(t,e)=>e.minExportUsage===void 0||(t.avgExportUsage??-1)>=e.minExportUsage,lu=(t,e)=>e.maxExportUsage===void 0||(t.avgExportUsage??0)<=e.maxExportUsage,pu=(t,e)=>e.minComplexity===void 0||(t.complexity??-1/0)>=e.minComplexity,uu=(t,e)=>e.maxComplexity===void 0||(t.complexity??0)<=e.maxComplexity,fu=(t,e)=>e.minCognitiveComplexity===void 0||(t.cognitiveComplexity??-1/0)>=e.minCognitiveComplexity,mu=(t,e)=>e.maxCognitiveComplexity===void 0||(t.cognitiveComplexity??0)<=e.maxCognitiveComplexity,gu=(t,e)=>e.minCommits===void 0||(t.commitCount90d??-1/0)>=e.minCommits,du=(t,e)=>e.maxCommits===void 0||(t.commitCount90d??0)<=e.maxCommits,hu=(t,e,r)=>!e.any?.length||e.any.some(n=>Ke(t,n,r)),yu=[Hp,Up,Jp,Kp,qp,Vp,Qp,Yp,Zp,Xp,eu,tu,ru,nu,su,ou,iu,au,cu,lu,pu,uu,fu,mu,gu,du,hu];function Ke(t,e,r){return yu.every(n=>n(t,e,r))}function kt(t,e){let r=new Map;if(e.importedBy!==void 0){for(let i of t.nodes)for(let a of i.imports)if(a.toPath){let c=r.get(a.toPath)??[];c.push(i.path),r.set(a.toPath,c)}}let n=t.nodes.filter(i=>Ke(i,e,r)),s=new Set(n.map(i=>i.path)),o=n.map(i=>({...i,imports:i.imports.filter(a=>!a.toPath||s.has(a.toPath))}));if(e.sort){let i=e.sortDir==="asc"?-1:1;o.sort((a,c)=>{let l=0;switch(e.sort){case"size":l=c.size-a.size;break;case"imports":l=c.imports.length-a.imports.length;break;case"commitCount90d":l=(c.commitCount90d??0)-(a.commitCount90d??0);break;case"exportUsage":l=(c.avgExportUsage??0)-(a.avgExportUsage??0);break;case"complexity":l=(c.complexity??0)-(a.complexity??0);break;case"cognitiveComplexity":l=(c.cognitiveComplexity??0)-(a.cognitiveComplexity??0);break}return l*i})}return e.limit!==void 0&&o.splice(e.limit),{nodes:o,cycles:t.cycles?.filter(i=>i.every(a=>s.has(a)))??void 0}}var xu={category:{field:"category",kind:"string"},type:{field:"type",kind:"string"},path:{field:"path",kind:"string"},importsfile:{field:"importsFile",kind:"string"},importedby:{field:"importedBy",kind:"string"},lastauthor:{field:"lastAuthor",kind:"string"},external:{field:"isExternal",kind:"boolIsTrue"},hasdocstring:{field:"hasDocstring",kind:"boolNotFalse"},isdocumented:{field:"isDocumented",kind:"boolNotFalse"},isstale:{field:"isStale",kind:"boolNotFalse"},minimports:{field:"minImports",kind:"int"},maximports:{field:"maxImports",kind:"int"},minsize:{field:"minSize",kind:"int"},maxsize:{field:"maxSize",kind:"int"},limit:{field:"limit",kind:"int"},mincoverage:{field:"minCoverage",kind:"int"},maxcoverage:{field:"maxCoverage",kind:"int"},minexportusage:{field:"minExportUsage",kind:"float"},maxexportusage:{field:"maxExportUsage",kind:"float"},mincomplexity:{field:"minComplexity",kind:"int"},maxcomplexity:{field:"maxComplexity",kind:"int"},mincognitivecomplexity:{field:"minCognitiveComplexity",kind:"int"},maxcognitivecomplexity:{field:"maxCognitiveComplexity",kind:"int"},mincommits:{field:"minCommits",kind:"int"},maxcommits:{field:"maxCommits",kind:"int"}};function bu(t,e,r,n){let s=t;switch(r){case"string":s[e]=n;break;case"int":s[e]=parseInt(n,10);break;case"float":s[e]=parseFloat(n);break;case"boolNotFalse":s[e]=n.toLowerCase()!=="false";break;case"boolIsTrue":s[e]=n.toLowerCase()==="true";break}}function Po(t,e){let r=e.indexOf(":");if(r===-1)return;let n=e.slice(0,r).trim().toLowerCase(),s=e.slice(r+1).trim();if(!n||!s)return;if(n==="tag"||n==="tags"){s.includes("+")?t.allTags=[...t.allTags??[],...s.split("+")]:t.tags=[...t.tags??[],s];return}if(n==="sort"){t.sort=s;return}if(n==="sortdir"){t.sortDir=s.toLowerCase()==="asc"?"asc":"desc";return}let o=xu[n];o&&bu(t,o.field,o.kind,s)}function Su(t){let e=[];for(let r of t.split("|")){let n=r.trim();if(!n)continue;let s={};Po(s,n),Object.keys(s).length>0&&e.push(s)}return e}var To="any(";function Ct(t){let e={},r=t.split(",");for(let n of r){let s=n.trim();if(s.toLowerCase().startsWith(To)&&s.endsWith(")")){let o=s.slice(To.length,-1),i=Su(o);i.length>0&&(e.any=[...e.any??[],...i]);continue}Po(e,n)}return e}import Oo from"fs/promises";import of from"path";import an from"path";import Mt from"typescript";import Cu from"path";import vu from"path";import w from"typescript";var Ao=new Set(["describe","test","it"]);function re(t,e){let r=t[e];if(r===void 0)throw new Error(`Index ${e} out of bounds (length ${t.length})`);return r}function Jr(t){let e=[];for(let r of t.statements){if(!w.isExpressionStatement(r))continue;let n=r.expression;if(!w.isCallExpression(n))continue;let s=n.expression;w.isIdentifier(s)&&Ao.has(s.text)&&e.push(n),w.isPropertyAccessExpression(s)&&w.isIdentifier(s.expression)&&Ao.has(s.expression.text)&&e.push(n)}return e}function Kr(t,e,r){for(let n of t.arguments){if(!w.isObjectLiteralExpression(n))continue;let s=n.properties.find(o=>w.isPropertyAssignment(o)&&w.isIdentifier(o.name)&&o.name.text===e);if(!(!s||!w.isArrayLiteralExpression(s.initializer)))return s.initializer.elements.filter(w.isStringLiteral).map(o=>o.text)}return null}function qr(t,e,r,n){if(t.arguments.length===0)return null;for(let o=1;o<t.arguments.length;o++){let i=re(t.arguments,o);if(!w.isObjectLiteralExpression(i))continue;let a=i.properties.find(l=>w.isPropertyAssignment(l)&&w.isIdentifier(l.name)&&l.name.text===e);if(a)return{start:a.initializer.getStart(n),end:a.initializer.getEnd(),text:r};let c=i.getEnd()-1;return{start:c,end:c,text:`${i.properties.length>0?", ":""}${e}: ${r}`}}let s=re(t.arguments,t.arguments.length-1);return{start:s.getStart(n),end:s.getStart(n),text:`{ ${e}: ${r} }, `}}function Vr(t,e,r){let n=t.arguments;for(let s=1;s<n.length;s++){let o=re(n,s);if(!w.isObjectLiteralExpression(o))continue;let i=o.properties.findIndex(c=>w.isPropertyAssignment(c)&&w.isIdentifier(c.name)&&c.name.text===e);if(i<0)continue;if(o.properties.length===1)return{start:re(n,s-1).getEnd(),end:o.getEnd(),text:""};let a=re(o.properties,i);return i===o.properties.length-1?{start:re(o.properties,i-1).getEnd(),end:a.getEnd(),text:""}:{start:a.getStart(r),end:re(o.properties,i+1).getStart(r),text:""}}return null}function Qr(t,e){let r=[...e].sort((s,o)=>o.start-s.start),n=t;for(let s of r)n=n.slice(0,s.start)+s.text+n.slice(s.end);return n}function Yr(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}var L=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function ku(t){return t.map(e=>e.startsWith("@")?e.slice(1):e)}function wt(t,e,r,n){let s=w.createSourceFile(vu.basename(t),e,w.ScriptTarget.Latest,!0),o=Jr(s),[i]=o;if(!i)return e;let a=Kr(i,n,s),c=[...r].sort();if(a!==null&&JSON.stringify(ku(a).sort())===JSON.stringify(c))return e;let l=Yr(c.map(u=>`@${u}`)),p=o.flatMap(u=>{let g=r.length===0?Vr(u,n,s):qr(u,n,l,s);return g?[g]:[]});return p.length>0?Qr(e,p):e}var Et=class{name="cypress";canHandle(e){return L.has(Cu.extname(e).toLowerCase())}apply(e,r,n){return wt(e,r,n,"tags")}};import wu from"path";var Zr=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,Xr=/^@([a-zA-Z0-9_-]+)/gm;function Eu(t){return`${["# <mokosh-tags>",...t.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
36
+ `),null}}var Re=class{affectedSymbols=new Map;constructor(e,n){this.affectedSymbols.set(e,new Set(["default",...n]))}updateAffectedSymbols(e,n){let r=this.affectedSymbols.get(n)||new Set,s=e.imports.find(c=>c.toPath===n);if(!s)return!1;let i=s.symbols||["*"],o=new Set;for(let c of i)(c==="*"||r.has("*")||r.has(c))&&o.add("*");if(o.size===0)return!1;let a=this.affectedSymbols.get(e.path)||new Set;for(let c of o)a.add(c);return this.affectedSymbols.set(e.path,a),!0}};function Pt(t,e){let n=t.nodes.get(e);if(n)return{category:n.category,exports:n.exports.map(r=>r.name)}}function ns(t,e,n=1){let r=[];return t.traverse(e,(s,i,o)=>{if(s.path===e)return!0;let a=o?t.nodes.get(o)?.imports.find(c=>c.toPath===s.path):void 0;return r.push({path:s.path,...a?.symbols?{symbols:a.symbols}:{}}),!0},{direction:"outgoing",maxDepth:n}),r}function At(t,e){let n=[];return t.traverse(e,r=>{if(r.path===e)return!0;let s=r.imports.find(i=>i.toPath===e);return n.push({path:r.path,...s?.symbols?{symbols:s.symbols}:{}}),!0},{direction:"incoming",maxDepth:1}),n}function rs(t,e,n={}){let{testsOnly:r=!1,changedSymbols:s}=n,i=s?new Re(e,s):null,o=[];return t.traverse(e,(a,c,l)=>{if(a.path===e)return!0;if(i&&l&&!i.updateAffectedSymbols(a,l))return!1;let p=a.category==="test"||a.tags.some(u=>u.name==="test");return(!r||p)&&o.push(a.path),!0},{direction:"incoming"}),o}function ss(t,e,n={}){let{depth:r=1,withEdgeDetail:s=!1}=n,i=[];return t.traverseCalls(e,o=>{if(o.path===e)return!0;let a={file:o.path};return s&&(a.edges=(o.callEdges??[]).filter(c=>c.toFile===e).map(c=>({from:c.from,to:c.to}))),i.push(a),!0},{direction:"incoming",maxDepth:r}),i}function tt(t,e={}){let{metric:n="cognitiveComplexity",threshold:r=10,limit:s=20}=e;return[...t.nodes.values()].flatMap(i=>(i.functions??[]).filter(o=>o[n]>=r).map(o=>({file:i.path,name:o.name,line:o.line,complexity:o.complexity,cognitiveComplexity:o.cognitiveComplexity}))).sort((i,o)=>o[n]-i[n]).slice(0,s)}function is(t){return{nodes:t.nodes.map(n=>({path:n.path,type:n.type,category:n.category,exports:n.exports.map(r=>r.name),tags:n.tags.filter(r=>r.kind==="comment-marker"||r.kind==="import").map(r=>r.name),importsFiles:n.imports.filter(r=>!r.isExternal&&r.toPath).map(r=>r.toPath),...n.package!==void 0&&{package:n.package},...n.description!==void 0&&{description:n.description},...n.testedBy!==void 0&&{testedBy:n.testedBy},...n.coveragePct!==void 0&&{coveragePct:n.coveragePct},...n.avgExportUsage!==void 0&&{avgExportUsage:n.avgExportUsage},...n.maxExportUsage!==void 0&&{maxExportUsage:n.maxExportUsage}})),cycles:t.cycles}}function Ne(t){return[...t.nodes.values()].some(e=>e.coveragePct!==void 0)}function oa(t){return[...t.nodes.values()].some(e=>e.commitCount90d!==void 0)}function os(t){return[...t.nodes.values()].some(e=>e.lastCommitAt!==void 0)}function nt(t,e={}){let{metric:n="cognitiveComplexity",minComplexity:r=10,maxCoveragePct:s=50,minChurn:i=0,limit:o=20}=e,a=oa(t),c=[...t.nodes.values()].filter(l=>l.coveragePct!==void 0&&l.coveragePct<=s&&(!a||(l.commitCount90d??0)>=i)).flatMap(l=>(l.functions??[]).filter(p=>p[n]>=r).map(p=>({file:l.path,name:p.name,line:p.line,complexity:p.complexity,cognitiveComplexity:p.cognitiveComplexity,coveragePct:l.coveragePct,...l.commitCount90d!==void 0&&{commitCount90d:l.commitCount90d}}))).sort((l,p)=>p[n]-l[n]).slice(0,o);return{hotspots:c,count:c.length,churnDataAvailable:a}}import{execFileSync as cs}from"child_process";import as from"fs";import mm from"os";import gm from"path";function ls(t,e){try{return cs("git",["rev-parse","--verify",`${e}^{commit}`],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error(`Could not resolve git ref "${e}" in ${t}`)}}async function aa(t,e,n){let r=as.mkdtempSync(gm.join(mm.tmpdir(),`mokosh-worktree-${e.slice(0,12)}-`));as.rmdirSync(r);try{return cs("git",["worktree","add","--detach",r,e],{cwd:t,stdio:["ignore","pipe","pipe"]}),await n(r)}finally{try{cs("git",["worktree","remove","--force",r],{cwd:t,stdio:["ignore","pipe","pipe"]})}catch{as.rmSync(r,{recursive:!0,force:!0})}}}async function ma(t,e,n,r={}){let s=ls(t,e),i=fi(t,s);if(i)return{sha:s,graph:i};let o=await aa(t,s,async a=>{if(r.workspaceBuilder)return r.workspaceBuilder(a);let c=r.pathAliases?new ae(a,{pathAliases:r.pathAliases}):void 0;return new Ae(a,null,c,void 0,r.gitStats??!1,new Map,r.parallelParsing??!0,r.additionalIgnoreDirs??[]).build(n)});return mi(t,s,o),{sha:s,graph:o}}var ca=t=>Math.round(t*100)/100,la=t=>t.length>8?t.slice(0,8):t;function hm(t,e){return`${t.file}:${t.line} ${t.name} (${t[e]})`}function ym(t,e){return`${t.file}:${t.line} ${t.name} (${t[e]}, cov ${t.coveragePct}%)`}function xm(t,e=4){let n=t.occurrences.slice(0,e).map(i=>`${i.file}:${i.startLine}-${i.endLine}`),r=t.occurrences.length-n.length,s=r>0?`, +${r} more`:"";return`${t.lines}L x${t.occurrences.length}: ${n.join(", ")}${s}`}var Me=(t,e)=>`${t} ${e}${t===1?"":"s"}`;function bm(t,e){let{files:n,staleReferences:r,duplication:s,complexity:i,docDrift:o,coverage:a}=t,c=[],l=[n.added.length&&`${n.added.length} added`,n.changed.length&&`${n.changed.length} changed`,n.removed.length&&`${n.removed.length} removed`].filter(Boolean);c.push(l.length?`Files: ${l.join(", ")}`:"No file changes"),r.length>0&&c.push(`\u26A0 ${Me(r.length,"stale reference")} \u2014 removed export still imported`);let p=i.newHotspots[0];return p?c.push(`+${Me(i.newHotspots.length,"complexity hotspot")} (max ${e} ${p[e]} in ${p.file})`):i.resolvedHotspots.length>0&&c.push(`${Me(i.resolvedHotspots.length,"complexity hotspot")} resolved`),s.newGroups.length>0?c.push(`+${Me(s.newGroups.length,"duplication group")}`):s.resolvedGroups.length>0&&c.push(`${Me(s.resolvedGroups.length,"duplication group")} resolved`),o.newlyStale.length>0&&c.push(`${Me(o.newlyStale.length,"doc")} newly stale`),a&&a.newHotspots.length>0&&c.push(`+${Me(a.newHotspots.length,"risk hotspot")}`),c}function km(t){let{staleReferences:e,duplication:n,complexity:r,docDrift:s,coverage:i}=t;return e.length>0||(i?.newHotspots.length??0)>0?"attention":r.newHotspots.length>0||n.newGroups.length>0||s.newlyStale.length>0?"review-worthy":"clean"}function En(t,e={}){let n=e.metric??"cognitiveComplexity",r=e.maxItems??8,s=e.maxPathList??100,{files:i,staleReferences:o,duplication:a,complexity:c,docDrift:l,coverage:p}=t,u=ca(c.head.avgCognitiveComplexity-c.base.avgCognitiveComplexity),f=i.added.length+i.changed.length+i.removed.length,m={base:`${t.base.ref}@${la(t.base.sha)}`,head:`${t.head.ref}@${la(t.head.sha)}`,verdict:km(t),headline:bm(t,n),files:{added:i.added.length,changed:i.changed.length,removed:i.removed.length,...f<=s?{paths:{added:i.added,changed:i.changed,removed:i.removed}}:{}}};return o.length>0&&(m.staleReferences=o),(c.newHotspots.length>0||c.resolvedHotspots.length>0)&&(m.complexity={avgDelta:u,newHotspots:c.newHotspots.slice(0,r).map(h=>hm(h,n)),newHotspotCount:c.newHotspots.length,resolvedCount:c.resolvedHotspots.length}),(a.newGroups.length>0||a.resolvedGroups.length>0)&&(m.duplication={newGroups:a.newGroups.slice(0,r).map(h=>xm(h)),newGroupCount:a.newGroups.length,resolvedCount:a.resolvedGroups.length,totalGroups:a.head.groups}),(l.newlyStale.length>0||l.resolved.length>0)&&(m.docDrift={newlyStale:l.newlyStale.slice(0,r).map(h=>h.replace("::"," \u2192 ")),newlyStaleCount:l.newlyStale.length,resolvedCount:l.resolved.length}),p&&(p.newHotspots.length>0||p.resolvedHotspots.length>0)&&(m.coverage={avgDelta:ca(p.head.avgCoveragePct-p.base.avgCoveragePct),newHotspots:p.newHotspots.slice(0,r).map(h=>ym(h,n)),newHotspotCount:p.newHotspots.length,resolvedCount:p.resolvedHotspots.length}),m}function Sm(t,e){let n=[],r=[];for(let[i,o]of e.nodes){let a=t.nodes.get(i);if(!a){n.push(i);continue}let c=JSON.stringify({category:a.category,exports:a.exports.map(p=>p.name).sort(),imports:a.imports.map(p=>p.toPath).sort()}),l=JSON.stringify({category:o.category,exports:o.exports.map(p=>p.name).sort(),imports:o.imports.map(p=>p.toPath).sort()});c!==l&&r.push(i)}let s=[...t.nodes.keys()].filter(i=>!e.nodes.has(i));return{added:n,removed:s,changed:r}}function vm(t,e){let n=[];for(let[r,s]of t.nodes){let i=e.nodes.get(r);if(!i)continue;let o=new Set(i.exports.map(c=>c.name)),a=s.exports.map(c=>c.name).filter(c=>!o.has(c));if(a.length!==0)for(let c of a){let l=[...e.nodes.values()].filter(p=>p.imports.some(u=>u.toPath===r&&u.symbols?.includes(c))).map(p=>p.path);l.length>0&&n.push({file:r,symbol:c,stillReferencedBy:l})}}return n}function wn(t){return t.occurrences.map(e=>`${e.file}:${e.startLine}-${e.endLine}`).sort().join("|")}async function Cm(t,e,n,r,s){let i=dm.join(Vt(t),`${r}-${lt}`),o=Ye(i),[{groups:a},{groups:c}]=await Promise.all([et(e,t,{minLines:s,tokenCache:o}),et(n,t,{minLines:s})]);Xe(o,i);let l=new Set(a.map(wn)),p=new Set(c.map(wn));return{base:{groups:a.length},head:{groups:c.length},newGroups:c.filter(u=>!l.has(wn(u))),resolvedGroups:a.filter(u=>!p.has(wn(u)))}}function pa(t){let e=[...t.nodes.values()].map(n=>n.cognitiveComplexity).filter(n=>n!==void 0);return e.length===0?0:e.reduce((n,r)=>n+r,0)/e.length}function wm(t,e,n,r){let s=tt(t,{metric:n,threshold:r,limit:1/0}),i=tt(e,{metric:n,threshold:r,limit:1/0}),o=l=>`${l.file}:${l.name}`,a=new Set(s.map(o)),c=new Set(i.map(o));return{base:{avgCognitiveComplexity:pa(t)},head:{avgCognitiveComplexity:pa(e)},newHotspots:i.filter(l=>!a.has(o(l))),resolvedHotspots:s.filter(l=>!c.has(o(l)))}}function ua(t){let e=new Set;for(let n of t.nodes.values())if(!(n.type!=="markdown"||!n.staleFor))for(let r of n.staleFor)e.add(`${n.path}::${r}`);return e}function Em(t,e){let n=ua(t),r=ua(e);return{base:{staleCount:n.size},head:{staleCount:r.size},newlyStale:[...r].filter(s=>!n.has(s)),resolved:[...n].filter(s=>!r.has(s))}}function fa(t){let e=[...t.nodes.values()].map(n=>n.coveragePct).filter(n=>n!==void 0);return e.length===0?0:e.reduce((n,r)=>n+r,0)/e.length}function Tm(t,e,n){if(!Ne(t)||!Ne(e))return null;let r=nt(t,{maxCoveragePct:n,limit:1/0}).hotspots,s=nt(e,{maxCoveragePct:n,limit:1/0}).hotspots,i=c=>`${c.file}:${c.name}`,o=new Set(r.map(i)),a=new Set(s.map(i));return{base:{avgCoveragePct:fa(t)},head:{avgCoveragePct:fa(e)},newHotspots:s.filter(c=>!o.has(i(c))),resolvedHotspots:r.filter(c=>!a.has(i(c)))}}async function Tn(t,e,n,r={}){let{sha:s,graph:i}=await ma(t,e,r.entryPoints??[],r),o=ls(t,r.headRef??"HEAD"),[a,c]=await Promise.all([Cm(t,i,n,s,r.minDuplicateLines),Promise.resolve(Tm(i,n,r.maxCoveragePct))]);return{base:{ref:e,sha:s},head:{ref:r.headRef??"HEAD",sha:o},files:Sm(i,n),staleReferences:vm(i,n),duplication:a,complexity:wm(i,n,r.complexityMetric,r.complexityThreshold),docDrift:Em(i,n),coverage:c}}import Fn from"path";function Fm(t){let e=new Map;for(let[n,r]of t){let s=r.imports.filter(i=>i.toPath&&!i.isExternal).length;s>0&&e.set(n,s)}return e}function Dm(t,e,n){let r=new Map;for(let[s,i]of e){if(i<n)continue;let o=t.get(s);if(!o||o.category==="test"||o.category==="barrel")continue;let a=Fn.extname(s),c=Fn.basename(s,a),l=c==="index"?Fn.basename(Fn.dirname(s)):c;r.set(s,{path:s,outDegree:i,tag:`feature:${l}`})}return r}function xe(t,e){let n=e?.minOutDegree??5;return Dm(t,Fm(t),n)}var Pm=(t,e)=>t.outDegree-e.outDegree;function Am(t,e){let n=new Map;for(let r of e.values()){let s=new Set;t.traverse(r.path,i=>(i.path!==r.path&&s.add(i.path),!0),{direction:"outgoing"}),n.set(r.path,s)}return n}function Rm(t,e,n,r){let s=new Map;for(let[i]of t){if(e.has(i))continue;let o=null;for(let a of e.values())n.get(a.path)?.has(i)&&(!o||r(a,o)<0)&&(o=a);o&&s.set(i,o.path)}return s}function Nm(t,e){let n=new Map;for(let r of t.values()){let s=r.tag.replace("feature:",""),i=[];for(let[o,a]of e)a===r.path&&i.push(o);n.set(s,{hub:r.path,outDegree:r.outDegree,files:i})}return n}function Mm(t,e,n){let r=[];for(let s of t.keys())!e.has(s)&&!n.has(s)&&r.push(s);return r}function Rt(t,e){let n=e?.detectFn??xe,r=e?.hubComparator??Pm,s=n(t.nodes,e),i=Am(t,s),o=Rm(t.nodes,s,i,r);return{features:Nm(s,o),unassigned:Mm(t.nodes,s,o)}}var Im=[{role:"component",segments:["component","components"]},{role:"controller",segments:["controller","controllers"]},{role:"middleware",segments:["middleware"]},{role:"router",segments:["router","routes","route"]},{role:"store",segments:["store","stores"]},{role:"service",segments:["service","services"]},{role:"handler",segments:["handler","handlers"]},{role:"adapter",segments:["adapter","adapters"]},{role:"plugin",segments:["plugin","plugins"]},{role:"api",segments:["api"]},{role:"cli",segments:["cli","commands"],basenames:["cli"]},{role:"util",segments:["util","utils","helper","helpers"]},{role:"model",segments:["model","models"],basenames:["model"]},{role:"parser",segments:["parser","parsers"],basenames:["parser"]},{role:"builder",basenames:["builder"]},{role:"resolver",basenames:["resolver"]}];function ga(t){if(t.category==="test")return"test";if(t.category==="config")return"config";if(t.category==="type-only")return"types";let e=t.path,n=_m(e);for(let r of Im)if(r.segments?.some(s=>Lm(e,s))||r.basenames?.includes(n))return r.role;return"other"}function Lm(t,e){return t.includes(`/${e}/`)||t.includes(`/${e}.`)}function _m(t){let e=t.slice(t.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function ps(t,e){let n=Rt(t,e),r=new Map;for(let[i,o]of n.features){for(let a of o.files)r.set(a,i);r.set(o.hub,i)}let s=new Map;for(let i of t.nodes.values()){let o=r.get(i.path);s.set(i.path,{path:i.path,role:ga(i),...i.description?{description:i.description}:{},exports:i.exports.map(a=>a.name),...o?{featureHub:o}:{}})}return s}function us(t,e){let n=[];for(let r of t.nodes.values())if(r.exports.some(s=>s.name===e))if(xt.has(r.type)){let s=[];for(let i of t.nodes.values())for(let o of i.callEdges??[])o.to===e&&s.push({file:i.path,callerFunction:o.from});n.push({path:r.path,category:r.category,precision:"call",callers:s})}else{let s=At(t,r.path).map(i=>({file:i.path,...i.symbols?{symbols:i.symbols}:{}}));n.push({path:r.path,category:r.category,precision:"file-level",importers:s})}return n}var fs=zt,ha=2,ya=50,ms=250,da=["function","class","variable","type","import","library","comment-marker"];function gs(t){let e=new Map;for(let r of t)for(let s of r.nodes.values())for(let i of s.tags){let o=e.get(i.name);o===void 0&&(o={name:i.name,count:0,kinds:[]},e.set(i.name,o)),o.count+=1,o.kinds.includes(i.kind)||o.kinds.push(i.kind)}let n={};for(let r of e.values()){r.kinds.sort((s,i)=>da.indexOf(s)-da.indexOf(i));for(let s of r.kinds)n[s]=(n[s]??0)+1}return{entries:e,byKind:n,totalDistinct:e.size}}function ds(t,e={}){let n=Number.isFinite(e.minCount)?Math.max(1,Math.trunc(e.minCount)):ha,r=Number.isFinite(e.limit)?Math.max(0,Math.trunc(e.limit)):ya,s=Math.min(r,ms),i=e.prefix?.toLowerCase(),o=m=>e.kind===void 0?m.kinds.some(h=>fs.includes(h))&&Ut(m.name):e.kind==="all"?!0:m.kinds.includes(e.kind),a=[...t.entries.values()].filter(m=>m.count>=n&&o(m)&&(i===void 0||m.name.toLowerCase().includes(i))).sort((m,h)=>h.count-m.count||m.name.localeCompare(h.name)),c=a.length,l=a.slice(0,s),p=e.kind===void 0?`${fs.join(" + ")} kinds, noise-filtered`:e.kind==="all"?"all kinds":`${e.kind} kind`,u=c>l.length,f={tags:l.map(m=>({name:m.name,count:m.count,kinds:m.kinds})),count:l.length,matched:c,totalDistinct:t.totalDistinct,byKind:t.byKind,hint:`${c} tag${c===1?"":"s"} match (${p}, count>=${n})${u?`; showing the top ${l.length}`:""}. ${t.totalDistinct} distinct tag names exist across all kinds \u2014 see byKind. Narrow with prefix:"\u2026", a higher minCount, or kind:"comment-marker"|"import"|"function"|"variable"|"library"|"all". This response is always capped at ${ms} tags.`};return u&&(f.truncated=!0),f}function Gm(t){return t?t.startsWith("interface ")?"interface":t.startsWith("class ")?"class":t.startsWith("enum ")?"enum":"type":"type"}function Om(t,e){if(e==="type-only")return!0;let n=t.signature??"";return n.startsWith("interface ")||n.startsWith("class ")||n.startsWith("enum ")}function hs(t){let e=new Map;for(let r of t.nodes.values())if(!(r.type!=="typescript"&&r.type!=="javascript"))for(let s of r.exports){if(!Om(s,r.category))continue;let i=`${r.path}::${s.name}`;e.set(i,{name:s.name,file:r.path,kind:Gm(s.signature),...s.doc?{doc:s.doc}:{}})}let n=[];for(let r of t.nodes.values())if(!(r.type!=="typescript"&&r.type!=="javascript")){for(let s of r.imports)if(!(!s.toPath||s.isExternal||!s.symbols?.length))for(let i of s.symbols)e.has(`${s.toPath}::${i}`)&&n.push({fromFile:r.path,toType:i,toFile:s.toPath})}return{types:e,edges:n}}function ys(t,e){let n=null;for(let i of t.types.values())if(i.name===e){n=i;break}if(!n)return{type:null,usedByFiles:[],uses:[]};let r=new Set,s=new Map;for(let i of t.edges)if(i.toType===e&&i.toFile===n.file&&r.add(i.fromFile),i.fromFile===n.file){let o=t.types.get(`${i.toFile}::${i.toType}`);o&&s.set(`${o.file}::${o.name}`,o)}return{type:n,usedByFiles:Array.from(r),uses:Array.from(s.values())}}import cg from"path";import ka from"fs";import Sa from"path";import jm from"fs";import xs from"path";import xa from"fs";import iC from"path";function Dn(t){try{return xa.statSync(t,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function Pn(t){try{return xa.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}var Wm=new Set([".java",".kt",".kts",".scala",".sc",".groovy",".gradle"]),$m=new Set(j);function ba(t,e=[]){let n;try{n=jm.readdirSync(t,{withFileTypes:!0})}catch{return e}for(let r of n){let s=xs.join(t,r.name);r.isDirectory()?!$m.has(r.name)&&!r.name.startsWith(".")&&ba(s,e):r.isFile()&&Wm.has(xs.extname(r.name).toLowerCase())&&e.push(s)}return e}function An(t,e,n){if(!Dn(e))return null;let r=ba(e);return r.length===0?null:{name:n,root:e,relativeRoot:xs.relative(t,e),entryPoints:r}}function zm(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Bm(t){let e=zm(t),n=new Set;for(let r of e.matchAll(/['"](:[A-Za-z0-9_\-.:]+)['"]/g)){let s=r[1].replace(/^:/,"").replace(/:$/,"");s&&n.add(s)}return[...n]}var va={type:"gradle",detect(t){let e=["settings.gradle.kts","settings.gradle"].map(i=>Sa.join(t,i)).find(i=>ka.existsSync(i));if(!e)return null;let n;try{n=ka.readFileSync(e,"utf-8")}catch{return null}let r=Bm(n);if(r.length===0)return null;let s=[];for(let i of r){let o=Sa.join(t,...i.split(":")),a=An(t,o,i);a&&s.push(a)}return s.length>0?s:null}};import Ss from"fs";import wa from"path";import Nt from"fs";import ce from"path";function ks(t,e){let n=ce.join(e,"package.json");if(!Nt.existsSync(n))return null;let r={};try{r=JSON.parse(Nt.readFileSync(n,"utf-8"))}catch{return null}let s=r.name;return s?{name:s,root:e,relativeRoot:ce.relative(t,e),entryPoints:Km(e,r)}:null}var Um=/\.[mc]?[jt]sx?$/;function bs(t,e){if(typeof t=="string"){Um.test(t)&&!t.endsWith(".d.ts")&&e(t);return}if(t&&typeof t=="object"&&!Array.isArray(t))for(let[n,r]of Object.entries(t))n!=="types"&&bs(r,e)}function Km(t,e){let n=[],r=new Set,s=a=>{let c=ce.join(t,a);r.has(c)||(r.add(c),n.push(c))},i=e.exports;if(typeof i=="string")bs(i,s);else if(i&&typeof i=="object"&&!Array.isArray(i))for(let a of Object.values(i))bs(a,s);e.main&&s(e.main);for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])s(a);let o=n.filter(Pn);return o.length>0?o:n.slice(0,1)}function rt(t,e){let n=[],r=new Set;for(let s of e){let i=s.replace(/\/$/,"").replace(/^\.\//,"");Hm(t,i,r,n)}return n}function Hm(t,e,n,r){if(!e.includes("*")){Jm(t,e,n,r);return}let s=e.split("/");s.includes("**")?Vm(t,s,n,r):Qm(t,s,n,r)}function Jm(t,e,n,r){let s=ce.join(t,e);if(n.has(s)||!Dn(s))return;n.add(s);let i=ks(t,s);i&&r.push(i)}function Vm(t,e,n,r){let s=ce.join(t,e[0]==="**"?"":e[0]??"");Ca(t,s,n,r)}function Qm(t,e,n,r){let s=e.findIndex(a=>a.includes("*")),i=ce.join(t,...e.slice(0,s)),o;try{o=Nt.readdirSync(i,{withFileTypes:!0})}catch{return}for(let a of o){if(!a.isDirectory())continue;let c=ce.join(i,a.name);if(n.has(c))continue;n.add(c);let l=ks(t,c);l&&r.push(l)}}function Ca(t,e,n,r){let s;try{s=Nt.readdirSync(e,{withFileTypes:!0})}catch{return}for(let i of s){if(!i.isDirectory()||i.name==="node_modules"||i.name.startsWith("."))continue;let o=ce.join(e,i.name);if(Nt.existsSync(ce.join(o,"package.json"))&&!n.has(o)){n.add(o);let a=ks(t,o);a&&r.push(a)}else Ca(t,o,n,r)}}var Ea={type:"npm",detect(t){let e=wa.join(t,"package.json");if(!Ss.existsSync(e))return null;let n;try{n=JSON.parse(Ss.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!n||Ss.existsSync(wa.join(t,"yarn.lock")))return null;let r=Array.isArray(n)?n:n.packages??[];return r.length===0?null:rt(t,r)}};import st from"fs";import I from"path";var Ta={type:"nx",detect(t){return st.existsSync(I.join(t,"nx.json"))?Fa(t,t,new Set,0).map(n=>Ym(t,n,I.join(n,"project.json"))).filter(n=>n!==null):null}};function Fa(t,e,n,r){if(r>4)return[];let s;try{s=st.readdirSync(e,{withFileTypes:!0})}catch{return[]}let i=[];for(let o of s){if(!o.isDirectory())continue;let a=o.name;if(a.startsWith(".")||a==="node_modules"||a==="dist"||a===".nx")continue;let c=I.join(e,a);st.existsSync(I.join(c,"project.json"))&&!n.has(c)?(n.add(c),i.push(c)):i.push(...Fa(t,c,n,r+1))}return i}function Ym(t,e,n){let r={};try{r=JSON.parse(st.readFileSync(n,"utf-8"))}catch{return null}let s=r.name,i,o,a=I.join(e,"package.json");if(st.existsSync(a))try{let c=JSON.parse(st.readFileSync(a,"utf-8"));s=c.name??s,i=c.main,o=c.exports}catch{}return s?{name:s,root:e,relativeRoot:I.relative(t,e),entryPoints:Xm(e,r,i,o)}:null}function Xm(t,e,n,r){let s=[],i=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(i){let a=I.resolve(t,"../..");s.push(I.resolve(a,i)),s.push(I.resolve(t,i))}if(r){let a=r;if(typeof a=="string")s.push(I.join(t,a));else if(typeof a=="object"&&a!==null){let c=a["."];typeof c=="string"&&s.push(I.join(t,c))}}if(n&&s.push(I.join(t,n)),e.sourceRoot){let a=I.resolve(t,"../.."),c=I.resolve(a,e.sourceRoot);s.push(I.join(c,"index.ts"),I.join(c,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])s.push(I.join(t,a));let o=s.filter(Pn);return o.length>0?o.slice(0,1):s.slice(0,1)}import Da from"fs";import Zm from"path";import{load as qm}from"js-yaml";var Pa={type:"pnpm",detect(t){let e=Zm.join(t,"pnpm-workspace.yaml");if(!Da.existsSync(e))return null;let n=[];try{n=qm(Da.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return rt(t,n)}};import Mt from"fs";import Rn from"path";function eg(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function tg(t){let e=eg(t),n=new Map;for(let r of e.matchAll(/(?:lazy\s+)?val\s+([A-Za-z0-9_]+)\s*=\s*\(?\s*project\b([^\n]*)/g)){let s=r[1],o=r[2].match(/\bfile\s*\(\s*["']([^"']+)["']\s*\)/),a=o?o[1]:s;if(a==="."||a==="./")continue;let c=a.replace(/^\.\//,"").replace(/\/$/,"");n.has(c)||n.set(c,{name:s,dir:c})}return[...n.values()]}var Aa={type:"sbt",detect(t){let e=Rn.join(t,"build.sbt"),n=Rn.join(t,"project");if(!Mt.existsSync(e)||!Mt.existsSync(n))return null;let r=[];try{r.push(Mt.readFileSync(e,"utf-8"))}catch{return null}try{for(let a of Mt.readdirSync(n))a.endsWith(".scala")&&r.push(Mt.readFileSync(Rn.join(n,a),"utf-8"))}catch{}let s=new Set,i=[];for(let a of r)for(let c of tg(a))s.has(c.dir)||(s.add(c.dir),i.push(c));if(i.length===0)return null;let o=[];for(let a of i){let c=Rn.join(t,...a.dir.split("/")),l=An(t,c,a.name);l&&o.push(l)}return o.length>0?o:null}};import ng from"fs";import rg from"path";var Ra={type:"turborepo",detect(t){return ng.existsSync(rg.join(t,"turbo.json"))?[]:null}};import vs from"fs";import Na from"path";var Ma={type:"yarn",detect(t){if(!vs.existsSync(Na.join(t,"yarn.lock")))return null;let e=Na.join(t,"package.json");if(!vs.existsSync(e))return null;let n;try{n=JSON.parse(vs.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!n)return null;let r=Array.isArray(n)?n:n.packages??[];return r.length===0?null:rt(t,r)}};var Ia=[];function te(t){Ia.push(t)}function La(){return Ia}import sg from"fs";import ig from"path";var og=["dependencies","devDependencies","peerDependencies","optionalDependencies"];function ag(t){try{let e=sg.readFileSync(ig.join(t,"package.json"),"utf-8"),n=JSON.parse(e),r=new Set;for(let s of og){let i=n[s];if(i&&typeof i=="object")for(let o of Object.keys(i))r.add(o)}return r}catch{return null}}function It(t,e){if(e){let i=e.getPackageDependencies(),o=Array.from(e.packages.values()).map(({graph:a,pkg:c})=>({name:c.name,relativeRoot:c.relativeRoot,dependsOn:i.get(c.name)??[],nodeCount:a.nodes.size}));return{monorepoType:t.type,monorepoTypes:t.types,packageCount:o.length,packages:o,dependsOnResolved:!0,nodeCountsResolved:!0}}let n=new Set(t.packages.map(i=>i.name)),r=!0,s=t.packages.map(i=>{let o=ag(i.root);if(o===null)return r=!1,{name:i.name,relativeRoot:i.relativeRoot,dependsOn:[]};let a=[...o].filter(c=>c!==i.name&&n.has(c)).sort();return{name:i.name,relativeRoot:i.relativeRoot,dependsOn:a}});return{monorepoType:t.type,monorepoTypes:t.types,packageCount:s.length,packages:s,dependsOnResolved:r,nodeCountsResolved:!1,note:"Layout only \u2014 per-package node counts and (for build-system monorepos without package.json) dependency edges require a full graph. Call analyze with empty entryPoints, then get_workspace_packages again."}}te(Ra);te(Ta);te(Pa);te(Ma);te(Ea);te(va);te(Aa);function Lt(t,e=La()){let n=cg.resolve(t),r=new Map,s=[];for(let o of e){let a=o.detect(n);if(a!==null){s.push(o.type);for(let c of a)r.has(c.name)||r.set(c.name,c)}}if(s.length===0)return{root:n,type:"none",types:[],packages:[],packageMap:new Map};let i=Array.from(r.values());return{root:n,type:s[0],types:s,packages:i,packageMap:new Map(i.map(o=>[o.name,o]))}}function it(t,e){return t===e.relativeRoot||t.startsWith(`${e.relativeRoot}/`)}var Ie=class t{constructor(e,n){this.monorepoRoot=e;this.type=n}monorepoRoot;type;packages=new Map;flattened;addPackage(e,n){this.packages.set(e.name,{graph:n,pkg:e})}annotateCrossPackageEdges(){for(let{graph:e}of this.packages.values())for(let n of e.nodes.values()){let r=this.getPackageForFile(n.path);if(r)for(let s of n.imports){if(s.isExternal||s.isWorkspace)continue;let i=this.getPackageForFile(s.toPath);i&&i.name!==r.name&&(s.isWorkspace=!0,s.workspacePackage=i.name)}}}flatten(){if(this.flattened)return this.flattened;let e=new Map,n=new Map;for(let{graph:r,pkg:s}of this.packages.values())for(let[i,o]of r.nodes)it(i,s)&&(e.set(i,o),n.set(i,s.name));return this.flattened={graph:new P(e),packageOf:n},this.flattened}getPackageForFile(e){for(let{pkg:n}of this.packages.values())if(e===n.relativeRoot||e.startsWith(`${n.relativeRoot}/`))return n}getPackageDependencies(){let e=new Map;for(let{graph:n,pkg:r}of this.packages.values()){let s=new Set;for(let i of n.nodes.values())for(let o of i.imports)o.isWorkspace&&o.workspacePackage&&s.add(o.workspacePackage);e.set(r.name,[...s])}return e}getAffectedAcrossPackages(e){let{graph:n,packageOf:r}=this.flatten();if(!n.nodes.has(e))return[];let s=[];return n.traverse(e,i=>(i.path!==e&&s.push({file:i.path,package:r.get(i.path)??""}),!0),{direction:"incoming"}),s}summarizeAffectedAcrossPackages(e,n={}){let r=n.maxFilesPerPackage??10,s=this.getAffectedAcrossPackages(e),i=new Map;for(let{file:c,package:l}of s){let p=i.get(l)??[];p.push(c),i.set(l,p)}let o=!1,a=[...i.entries()].map(([c,l])=>{let p=l.slice(0,r),u=l.length-p.length;return u>0&&(o=!0),{package:c,count:l.length,sample:p,more:u}}).sort((c,l)=>l.count-c.count);return{file:e,totalAffected:s.length,packageCount:a.length,byPackage:a,truncated:o}}serialize(){return{monorepoRoot:this.monorepoRoot,type:this.type,packages:Array.from(this.packages.values()).map(({graph:e,pkg:n})=>({pkg:{name:n.name,relativeRoot:n.relativeRoot,entryPoints:n.entryPoints},nodes:Array.from(e.nodes.values())}))}}static deserialize(e){let n=new t(e.monorepoRoot,e.type);for(let{pkg:r,nodes:s}of e.packages){let i=new Map(s.map(a=>[a.path,a])),o=new P(i);n.packages.set(r.name,{graph:o,pkg:{...r,root:""}})}return n}};function Cs(t,e){return e.startsWith("!")?t!==e.slice(1):t===e}function lg(t,e){return e.startsWith("!")?!t.includes(e.slice(1)):t.includes(e)}var pg=(t,e)=>!e.category||Cs(t.category,e.category),ug=(t,e)=>!e.type||Cs(t.type,e.type),fg=(t,e)=>e.lastAuthor?e.lastAuthor.startsWith("!")?t.lastAuthor!==e.lastAuthor.slice(1):t.lastAuthor!==void 0&&t.lastAuthor===e.lastAuthor:!0,mg=(t,e)=>!e.path||lg(t.path,e.path),gg=(t,e,n,r)=>{if(!e.package||!r)return!0;let s=r.get(t.path)??"";return Cs(s,e.package)},dg=(t,e)=>e.isExternal===void 0?!0:t.imports.some(r=>r.isExternal)===e.isExternal,hg=(t,e)=>{if(!e.tags||e.tags.length===0)return!0;let n=new Set(t.tags.filter(Ce).map(i=>i.name)),r=e.tags.filter(i=>!i.startsWith("!")),s=e.tags.filter(i=>i.startsWith("!")).map(i=>i.slice(1));return!(r.length>0&&!r.some(i=>n.has(i))||s.some(i=>n.has(i)))},yg=(t,e)=>{if(!e.allTags?.length)return!0;let n=new Set(t.tags.filter(Ce).map(r=>r.name));return e.allTags.every(r=>n.has(r))},xg=(t,e)=>!e.importsFile||t.imports.some(n=>n.toPath?.includes(e.importsFile)),bg=(t,e,n)=>e.importedBy===void 0?!0:(n?.get(t.path)??[]).some(s=>s.includes(e.importedBy)),kg=(t,e)=>e.minImports===void 0||t.imports.length>=e.minImports,Sg=(t,e)=>e.maxImports===void 0||t.imports.length<=e.maxImports,vg=(t,e)=>e.minSize===void 0||t.size>=e.minSize,Cg=(t,e)=>e.maxSize===void 0||t.size<=e.maxSize,wg=(t,e)=>e.hasDocstring===void 0||!!t.description===e.hasDocstring,Eg=(t,e)=>e.isDocumented===void 0||!!t.documentedBy?.length===e.isDocumented,Tg=(t,e)=>e.isStale===void 0||!!t.staleFor?.length===e.isStale,Fg=(t,e)=>e.minCoverage===void 0||(t.coveragePct??101)>=e.minCoverage,Dg=(t,e)=>e.maxCoverage===void 0||(t.coveragePct??0)<=e.maxCoverage,Pg=(t,e)=>e.minExportUsage===void 0||(t.avgExportUsage??-1)>=e.minExportUsage,Ag=(t,e)=>e.maxExportUsage===void 0||(t.avgExportUsage??0)<=e.maxExportUsage,Rg=(t,e)=>e.minComplexity===void 0||(t.complexity??-1/0)>=e.minComplexity,Ng=(t,e)=>e.maxComplexity===void 0||(t.complexity??0)<=e.maxComplexity,Mg=(t,e)=>e.minCognitiveComplexity===void 0||(t.cognitiveComplexity??-1/0)>=e.minCognitiveComplexity,Ig=(t,e)=>e.maxCognitiveComplexity===void 0||(t.cognitiveComplexity??0)<=e.maxCognitiveComplexity,Lg=(t,e)=>e.minCommits===void 0||(t.commitCount90d??-1/0)>=e.minCommits,_g=(t,e)=>e.maxCommits===void 0||(t.commitCount90d??0)<=e.maxCommits,Gg=(t,e,n,r)=>!e.any?.length||e.any.some(s=>_t(t,s,n,r)),Og=[pg,ug,fg,mg,gg,dg,hg,yg,xg,bg,kg,Sg,vg,Cg,wg,Eg,Tg,Fg,Dg,Pg,Ag,Rg,Ng,Mg,Ig,Lg,_g,Gg];function _t(t,e,n,r){return Og.every(s=>s(t,e,n,r))}function Nn(t,e,n={}){let{packageOf:r}=n,s=new Map;if(e.importedBy!==void 0){for(let c of t.nodes)for(let l of c.imports)if(l.toPath){let p=s.get(l.toPath)??[];p.push(c.path),s.set(l.toPath,p)}}let i=t.nodes.filter(c=>_t(c,e,s,r)),o=new Set(i.map(c=>c.path)),a=i.map(c=>{let l=r?.get(c.path);return{...c,imports:c.imports.filter(p=>!p.toPath||o.has(p.toPath)),...l!==void 0&&{package:l}}});if(e.sort){let c=e.sortDir==="asc"?-1:1;a.sort((l,p)=>{let u=0;switch(e.sort){case"size":u=p.size-l.size;break;case"imports":u=p.imports.length-l.imports.length;break;case"commitCount90d":u=(p.commitCount90d??0)-(l.commitCount90d??0);break;case"exportUsage":u=(p.avgExportUsage??0)-(l.avgExportUsage??0);break;case"complexity":u=(p.complexity??0)-(l.complexity??0);break;case"cognitiveComplexity":u=(p.cognitiveComplexity??0)-(l.cognitiveComplexity??0);break}return u*c})}return e.limit!==void 0&&a.splice(e.limit),{nodes:a,cycles:t.cycles?.filter(c=>c.every(l=>o.has(l)))??void 0}}var jg={category:{field:"category",kind:"string"},type:{field:"type",kind:"string"},path:{field:"path",kind:"string"},package:{field:"package",kind:"string"},importsfile:{field:"importsFile",kind:"string"},importedby:{field:"importedBy",kind:"string"},lastauthor:{field:"lastAuthor",kind:"string"},external:{field:"isExternal",kind:"boolIsTrue"},hasdocstring:{field:"hasDocstring",kind:"boolNotFalse"},isdocumented:{field:"isDocumented",kind:"boolNotFalse"},isstale:{field:"isStale",kind:"boolNotFalse"},minimports:{field:"minImports",kind:"int"},maximports:{field:"maxImports",kind:"int"},minsize:{field:"minSize",kind:"int"},maxsize:{field:"maxSize",kind:"int"},limit:{field:"limit",kind:"int"},mincoverage:{field:"minCoverage",kind:"int"},maxcoverage:{field:"maxCoverage",kind:"int"},minexportusage:{field:"minExportUsage",kind:"float"},maxexportusage:{field:"maxExportUsage",kind:"float"},mincomplexity:{field:"minComplexity",kind:"int"},maxcomplexity:{field:"maxComplexity",kind:"int"},mincognitivecomplexity:{field:"minCognitiveComplexity",kind:"int"},maxcognitivecomplexity:{field:"maxCognitiveComplexity",kind:"int"},mincommits:{field:"minCommits",kind:"int"},maxcommits:{field:"maxCommits",kind:"int"}};function Wg(t,e,n,r){let s=t;switch(n){case"string":s[e]=r;break;case"int":s[e]=parseInt(r,10);break;case"float":s[e]=parseFloat(r);break;case"boolNotFalse":s[e]=r.toLowerCase()!=="false";break;case"boolIsTrue":s[e]=r.toLowerCase()==="true";break}}function Ga(t,e){let n=e.indexOf(":");if(n===-1)return;let r=e.slice(0,n).trim().toLowerCase(),s=e.slice(n+1).trim();if(!r||!s)return;if(r==="tag"||r==="tags"){s.includes("+")?t.allTags=[...t.allTags??[],...s.split("+")]:t.tags=[...t.tags??[],s];return}if(r==="sort"){t.sort=s;return}if(r==="sortdir"){t.sortDir=s.toLowerCase()==="asc"?"asc":"desc";return}let i=jg[r];i&&Wg(t,i.field,i.kind,s)}function $g(t){let e=[];for(let n of t.split("|")){let r=n.trim();if(!r)continue;let s={};Ga(s,r),Object.keys(s).length>0&&e.push(s)}return e}var _a="any(";function Mn(t){let e={},n=t.split(",");for(let r of n){let s=r.trim();if(s.toLowerCase().startsWith(_a)&&s.endsWith(")")){let i=s.slice(_a.length,-1),o=$g(i);o.length>0&&(e.any=[...e.any??[],...o]);continue}Ga(e,r)}return e}import Ja from"fs/promises";import Ed from"path";import Gs from"path";import Un from"typescript";import Kg from"path";import Bg from"path";import R from"typescript";var Oa=new Set(["describe","test","it"]);function Le(t,e){let n=t[e];if(n===void 0)throw new Error(`Index ${e} out of bounds (length ${t.length})`);return n}function ws(t){let e=[];for(let n of t.statements){if(!R.isExpressionStatement(n))continue;let r=n.expression;if(!R.isCallExpression(r))continue;let s=r.expression;R.isIdentifier(s)&&Oa.has(s.text)&&e.push(r),R.isPropertyAccessExpression(s)&&R.isIdentifier(s.expression)&&Oa.has(s.expression.text)&&e.push(r)}return e}function Es(t,e,n){for(let r of t.arguments){if(!R.isObjectLiteralExpression(r))continue;let s=r.properties.find(i=>R.isPropertyAssignment(i)&&R.isIdentifier(i.name)&&i.name.text===e);if(!(!s||!R.isArrayLiteralExpression(s.initializer)))return s.initializer.elements.filter(R.isStringLiteral).map(i=>i.text)}return null}function Ts(t,e,n,r){if(t.arguments.length===0)return null;for(let i=1;i<t.arguments.length;i++){let o=Le(t.arguments,i);if(!R.isObjectLiteralExpression(o))continue;let a=o.properties.find(l=>R.isPropertyAssignment(l)&&R.isIdentifier(l.name)&&l.name.text===e);if(a)return{start:a.initializer.getStart(r),end:a.initializer.getEnd(),text:n};let c=o.getEnd()-1;return{start:c,end:c,text:`${o.properties.length>0?", ":""}${e}: ${n}`}}let s=Le(t.arguments,t.arguments.length-1);return{start:s.getStart(r),end:s.getStart(r),text:`{ ${e}: ${n} }, `}}function Fs(t,e,n){let r=t.arguments;for(let s=1;s<r.length;s++){let i=Le(r,s);if(!R.isObjectLiteralExpression(i))continue;let o=i.properties.findIndex(c=>R.isPropertyAssignment(c)&&R.isIdentifier(c.name)&&c.name.text===e);if(o<0)continue;if(i.properties.length===1)return{start:Le(r,s-1).getEnd(),end:i.getEnd(),text:""};let a=Le(i.properties,o);return o===i.properties.length-1?{start:Le(i.properties,o-1).getEnd(),end:a.getEnd(),text:""}:{start:a.getStart(n),end:Le(i.properties,o+1).getStart(n),text:""}}return null}function Ds(t,e){let n=[...e].sort((s,i)=>i.start-s.start),r=t;for(let s of n)r=r.slice(0,s.start)+s.text+r.slice(s.end);return r}function Ps(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}var ne=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function Ug(t){return t.map(e=>e.startsWith("@")?e.slice(1):e)}function In(t,e,n,r){let s=R.createSourceFile(Bg.basename(t),e,R.ScriptTarget.Latest,!0),i=ws(s),[o]=i;if(!o)return e;let a=Es(o,r,s),c=[...n].sort();if(a!==null&&JSON.stringify(Ug(a).sort())===JSON.stringify(c))return e;let l=Ps(c.map(u=>`@${u}`)),p=i.flatMap(u=>{let f=n.length===0?Fs(u,r,s):Ts(u,r,l,s);return f?[f]:[]});return p.length>0?Ds(e,p):e}var Ln=class{name="cypress";canHandle(e){return ne.has(Kg.extname(e).toLowerCase())}apply(e,n,r){return In(e,n,r,"tags")}};import Hg from"path";var As=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,Rs=/^@([a-zA-Z0-9_-]+)/gm;function Jg(t){return`${["# <mokosh-tags>",...t.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
28
37
  `)}
29
38
 
30
- `}function Fu(t){let e=new Set;Xr.lastIndex=0;let r=Xr.exec(t);for(;r!==null;)r[1]&&e.add(r[1]),r=Xr.exec(t);return e}var Ft=class{name="gherkin";canHandle(e){return wu.extname(e).toLowerCase()===".feature"}apply(e,r,n){let s=r.replace(Zr,""),o=Fu(s),i=n.filter(c=>!o.has(c)),a=i.length>0?Eu(i):"";return Zr.test(r)?r.replace(Zr,a):a?r.replace(/^(Feature:)/m,`${a}$1`):r}};function No(t,e){let r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/"),s="";for(let o=0;o<r.length;o++){let i=r[o];i==="*"?r[o+1]==="*"?(s+=".*",o++):s+="[^/]*":i==="?"?s+="[^/]":i!==void 0&&(s+=i.replace(/[.+^${}()|[\]\\]/g,"\\$&"))}return new RegExp(`^${s}$`).test(n)}import Tu from"path";var en=/^\/\/go:build mokosh_[^\n]+\n/m,Pu=/^package\s+\S+/m;function Au(t){return`//go:build ${t.map(r=>`mokosh_${r}`).join(" || ")}
31
- `}function Nu(t){let e=en.exec(t);if(!e)return null;let r=e[0]??"",n=/mokosh_([a-zA-Z0-9_-]+)/g,s=[],o=n.exec(r);for(;o!==null;)o[1]&&s.push(o[1]),o=n.exec(r);return s}var Tt=class{name="go";canHandle(e){return Tu.basename(e).endsWith("_test.go")}apply(e,r,n){let s=Nu(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return r.replace(en,"");let i=Au(o);if(s!==null)return r.replace(en,i);let a=Pu.exec(r);if(!a)return r;let c=a.index;return`${r.slice(0,c)+i}
32
- ${r.slice(c)}`}};import Du from"path";var Ru=/^\/\*\*\n(?: \* @group .+\n)+ \*\/\n+/,tn=/^ \* @group (.+)$/gm;function Iu(t){return`${["/**",...t.map(e=>` * @group ${e}`)," */"].join(`
39
+ `}function Vg(t){let e=new Set;Rs.lastIndex=0;let n=Rs.exec(t);for(;n!==null;)n[1]&&e.add(n[1]),n=Rs.exec(t);return e}var _n=class{name="gherkin";canHandle(e){return Hg.extname(e).toLowerCase()===".feature"}apply(e,n,r){let s=n.replace(As,""),i=Vg(s),o=r.filter(c=>!i.has(c)),a=o.length>0?Jg(o):"";return As.test(n)?n.replace(As,a):a?n.replace(/^(Feature:)/m,`${a}$1`):n}};function ja(t,e){let n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/"),s="";for(let i=0;i<n.length;i++){let o=n[i];o==="*"?n[i+1]==="*"?(s+=".*",i++):s+="[^/]*":o==="?"?s+="[^/]":o!==void 0&&(s+=o.replace(/[.+^${}()|[\]\\]/g,"\\$&"))}return new RegExp(`^${s}$`).test(r)}import Qg from"path";var Ns=/^\/\/go:build mokosh_[^\n]+\n/m,Yg=/^package\s+\S+/m;function Xg(t){return`//go:build ${t.map(n=>`mokosh_${n}`).join(" || ")}
40
+ `}function Zg(t){let e=Ns.exec(t);if(!e)return null;let n=e[0]??"",r=/mokosh_([a-zA-Z0-9_-]+)/g,s=[],i=r.exec(n);for(;i!==null;)i[1]&&s.push(i[1]),i=r.exec(n);return s}var Gn=class{name="go";canHandle(e){return Qg.basename(e).endsWith("_test.go")}apply(e,n,r){let s=Zg(n),i=[...r].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(i))return n;if(r.length===0)return n.replace(Ns,"");let o=Xg(i);if(s!==null)return n.replace(Ns,o);let a=Yg.exec(n);if(!a)return n;let c=a.index;return`${n.slice(0,c)+o}
41
+ ${n.slice(c)}`}};import qg from"path";var ed=/^\/\*\*\n(?: \* @group .+\n)+ \*\/\n+/,Ms=/^ \* @group (.+)$/gm;function td(t){return`${["/**",...t.map(e=>` * @group ${e}`)," */"].join(`
33
42
  `)}
34
43
 
35
- `}function Mu(t){let e=[];tn.lastIndex=0;let r=tn.exec(t);for(;r!==null;)r[1]&&e.push(r[1]),r=tn.exec(t);return e}var Pt=class{name="jest";canHandle(e){return L.has(Du.extname(e).toLowerCase())}apply(e,r,n){let s=Ru.exec(r),o=s?Mu(s[0]):null,i=[...n].sort();if(o!==null&&JSON.stringify([...o].sort())===JSON.stringify(i))return r;let a=s?r.slice(s[0].length):r;return n.length===0?a:Iu(i)+a}};import Lu from"path";var _u="// mokosh:tags",nn=/^\/\/ mokosh:tags\n(?:[ \t]*@Tag\("[^"]*"\)\n)*/m,rn="import org.junit.jupiter.api.Tag;",Ro=/^import org\.junit\.jupiter\.api\.Tag;\n/m,Gu=/^(?:public\s+|final\s+|abstract\s+|sealed\s+|non-sealed\s+|strictfp\s+)*(?:class|interface|enum|record|@interface)\s+\w+/m,Ou=/^import\s+[^\n]+;\n(?![\s\S]*^import\s)/m,ju=/^package\s+[^\n]+;\n/m,zu=/\/src\/(test|androidTest|integrationTest|it)\//,Wu=/(Test|Tests|Spec|IT)\.(java|groovy)$/;function $u(t){let e=nn.exec(t);if(!e)return null;let r=[],n=/@Tag\("([^"]*)"\)/g,s=n.exec(e[0]);for(;s!==null;)s[1]&&r.push(s[1]),s=n.exec(e[0]);return r}function Bu(t){return`${_u}
44
+ `}function nd(t){let e=[];Ms.lastIndex=0;let n=Ms.exec(t);for(;n!==null;)n[1]&&e.push(n[1]),n=Ms.exec(t);return e}var On=class{name="jest";canHandle(e){return ne.has(qg.extname(e).toLowerCase())}apply(e,n,r){let s=ed.exec(n),i=s?nd(s[0]):null,o=[...r].sort();if(i!==null&&JSON.stringify([...i].sort())===JSON.stringify(o))return n;let a=s?n.slice(s[0].length):n;return r.length===0?a:td(o)+a}};import Wa from"path";var rd="// mokosh:tags",Is=/^\/\/ mokosh:tags\n(?:[ \t]*@Tag\("[^"]*"\)\n)*/m,sd=/\/src\/(test|androidTest|integrationTest|it)\//,id=/(Test|Tests|Spec|IT)\.(java|groovy|kt)$/,od={importLine:"import org.junit.jupiter.api.Tag;",importRe:/^import org\.junit\.jupiter\.api\.Tag;?\n/m,typeDeclRe:/^(?:public\s+|final\s+|abstract\s+|sealed\s+|non-sealed\s+|strictfp\s+)*(?:class|interface|enum|record|@interface)\s+\w+/m,lastImportRe:/^import\s+[^\n]+;\n(?![\s\S]*^import\s)/m,packageRe:/^package\s+[^\n]+;\n/m},ad={importLine:"import org.junit.jupiter.api.Tag",importRe:/^import org\.junit\.jupiter\.api\.Tag;?\n/m,typeDeclRe:/^(?:public\s+|private\s+|protected\s+|internal\s+|open\s+|abstract\s+|final\s+|sealed\s+|data\s+|inner\s+|value\s+|annotation\s+)*(?:enum\s+)?(?:class|interface|object)\s+\w+/m,lastImportRe:/^import\s+[^\n]+\n(?![\s\S]*^import\s)/m,packageRe:/^package\s+[^\n]+\n/m};function cd(t){let e=Is.exec(t);if(!e)return null;let n=[],r=/@Tag\("([^"]*)"\)/g,s=r.exec(e[0]);for(;s!==null;)s[1]&&n.push(s[1]),s=r.exec(e[0]);return n}function ld(t){return`${rd}
36
45
  ${t.map(e=>`@Tag("${e}")`).join(`
37
46
  `)}
38
- `}function Do(t){if(Ro.test(t))return t;let e=Ou.exec(t);if(e){let n=e.index+e[0].length;return t.slice(0,n)+rn+`
39
- `+t.slice(n)}let r=ju.exec(t);if(r){let n=r.index+r[0].length;return t.slice(0,n)+`
40
- `+rn+`
41
- `+t.slice(n)}return rn+`
42
- `+t}function Hu(t){return/@Tag\b/.test(t)?t:t.replace(Ro,"")}var At=class{name="junit";canHandle(e){let r=e.replace(/\\/g,"/"),n=Lu.extname(r).toLowerCase();return n!==".java"&&n!==".groovy"?!1:zu.test(r)||Wu.test(r)}apply(e,r,n){let s=$u(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return s===null?r:Hu(r.replace(nn,""));let i=Bu(o);if(s!==null)return Do(r.replace(nn,i));let a=Gu.exec(r);if(!a)return r;let c=r.slice(0,a.index)+i+r.slice(a.index);return Do(c)}};import Uu from"path";var Nt=class{name="playwright";canHandle(e){return L.has(Uu.extname(e).toLowerCase())}apply(e,r,n){return wt(e,r,n,"tag")}};import Ju from"path";var sn=/^pytestmark\s*=\s*.+$/m,Ku=/^import pytest\s*$/m;function qu(t){let e=t.map(r=>`pytest.mark.${r}`).join(", ");return t.length===1?`pytestmark = pytest.mark.${t[0]}`:`pytestmark = [${e}]`}function Vu(t){let e=sn.exec(t);if(!e)return null;let r=e[0],n=[],s=/pytest\.mark\.([a-zA-Z0-9_-]+)/g,o=s.exec(r);for(;o!==null;)o[1]&&n.push(o[1]),o=s.exec(r);return n}var Dt=class{name="pytest";canHandle(e){return Ju.extname(e).toLowerCase()===".py"}apply(e,r,n){let s=Vu(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return r.replace(sn,"").replace(/\n{3,}/g,`
47
+ `}function $a(t,e){if(e.importRe.test(t))return t;let n=e.lastImportRe.exec(t);if(n){let s=n.index+n[0].length;return t.slice(0,s)+e.importLine+`
48
+ `+t.slice(s)}let r=e.packageRe.exec(t);if(r){let s=r.index+r[0].length;return t.slice(0,s)+`
49
+ `+e.importLine+`
50
+ `+t.slice(s)}return e.importLine+`
51
+ `+t}function pd(t,e){return/@Tag\b/.test(t)?t:t.replace(e.importRe,"")}var jn=class{name="junit";canHandle(e){let n=e.replace(/\\/g,"/"),r=Wa.extname(n).toLowerCase();return r!==".java"&&r!==".groovy"&&r!==".kt"?!1:sd.test(n)||id.test(n)}apply(e,n,r){let s=Wa.extname(e.replace(/\\/g,"/")).toLowerCase()===".kt"?ad:od,i=cd(n),o=[...r].sort();if(i!==null&&JSON.stringify([...i].sort())===JSON.stringify(o))return n;if(r.length===0)return i===null?n:pd(n.replace(Is,""),s);let a=ld(o);if(i!==null)return $a(n.replace(Is,a),s);let c=s.typeDeclRe.exec(n);if(!c)return n;let l=n.slice(0,c.index)+a+n.slice(c.index);return $a(l,s)}};import ud from"path";var Wn=class{name="playwright";canHandle(e){return ne.has(ud.extname(e).toLowerCase())}apply(e,n,r){return In(e,n,r,"tag")}};import fd from"path";var Ls=/^pytestmark\s*=\s*.+$/m,md=/^import pytest\s*$/m;function gd(t){let e=t.map(n=>`pytest.mark.${n}`).join(", ");return t.length===1?`pytestmark = pytest.mark.${t[0]}`:`pytestmark = [${e}]`}function dd(t){let e=Ls.exec(t);if(!e)return null;let n=e[0],r=[],s=/pytest\.mark\.([a-zA-Z0-9_-]+)/g,i=s.exec(n);for(;i!==null;)i[1]&&r.push(i[1]),i=s.exec(n);return r}var $n=class{name="pytest";canHandle(e){return fd.extname(e).toLowerCase()===".py"}apply(e,n,r){let s=dd(n),i=[...r].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(i))return n;if(r.length===0)return n.replace(Ls,"").replace(/\n{3,}/g,`
43
52
 
44
- `);let i=qu(o);if(s!==null)return r.replace(sn,i);let a=Ku.test(r),c=Qu(r),l=r.slice(0,c),p=r.slice(c),u=a?"":`import pytest
45
- `,g=l.endsWith(`
53
+ `);let o=gd(i);if(s!==null)return n.replace(Ls,o);let a=md.test(n),c=hd(n),l=n.slice(0,c),p=n.slice(c),u=a?"":`import pytest
54
+ `,f=l.endsWith(`
46
55
 
47
56
  `)?"":`
48
- `;return`${l+g+u+i}
49
- ${p}`}};function Qu(t){let e=t.split(`
50
- `),r=-1;return e.forEach((s,o)=>{(s.trimStart().startsWith("import ")||s.trimStart().startsWith("from "))&&(r=o)}),r<0?0:e.slice(0,r+1).reduce((s,o)=>s+o.length+1,0)}import Yu from"path";var on=/^\/\/ mokosh:tags .*\n/m,Zu=/^(?:sealed\s+|abstract\s+|final\s+|private\s+|implicit\s+|case\s+)*(?:class|object|trait)\s+\w+/m,Xu=/\/src\/(test|it)\//,ef=/(Spec|Suite|Test|Props)\.scala$/;function tf(t){let e=on.exec(t);return e?e[0].replace(/^\/\/ mokosh:tags /,"").trim().split(/\s*,\s*/).filter(Boolean):null}var Rt=class{name="scalatest";canHandle(e){let r=e.replace(/\\/g,"/");return Yu.extname(r).toLowerCase()!==".scala"?!1:Xu.test(r)||ef.test(r)}apply(e,r,n){let s=tf(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return s===null?r:r.replace(on,"");let i=`// mokosh:tags ${o.join(", ")}
51
- `;if(s!==null)return r.replace(on,i);let a=Zu.exec(r);return a?r.slice(0,a.index)+i+r.slice(a.index):r}};import Io from"path";import Mo from"typescript";var rf=/\/\/ <mokosh-tags>[\s\S]*?\/\/ <\/mokosh-tags>\n*/,It=class{name="vitest";canHandle(e){return L.has(Io.extname(e).toLowerCase())}apply(e,r,n){let s=r.replace(rf,""),o=Mo.createSourceFile(Io.basename(e),s,Mo.ScriptTarget.Latest,!0),i=Jr(o),[a]=i;if(!a)return s;let c=Kr(a,"tags",o),l=[...n].sort();if(c!==null&&JSON.stringify([...c].sort())===JSON.stringify(l))return s;let p=i.flatMap(u=>{let g=n.length===0?Vr(u,"tags",o):qr(u,"tags",Yr(l),o);return g?[g]:[]});return p.length>0?Qr(s,p):s}};var Lo={vitest:()=>new It,playwright:()=>new Nt,cypress:()=>new Et,jest:()=>new Pt},nf={"@playwright/test":"playwright",cypress:"cypress","@jest/globals":"jest",vitest:"vitest"};function sf(t){let e=Mt.createSourceFile("detect.ts",t,Mt.ScriptTarget.Latest,!0);for(let r of e.statements){if(!Mt.isImportDeclaration(r)||!Mt.isStringLiteral(r.moduleSpecifier))continue;let n=nf[r.moduleSpecifier.text];if(n)return n}return null}var cn=class{constructor(e,r,n){this.rootDir=e;this.defaultFramework=r;this.frameworkOverrides=n}rootDir;defaultFramework;frameworkOverrides;name="auto";canHandle(e){return L.has(an.extname(e).toLowerCase())}apply(e,r,n){let s=sf(r)??this.matchOverride(e)??this.defaultFramework;return(Lo[s]??Lo.vitest)().apply(e,r,n)}matchOverride(e){let r=an.relative(this.rootDir,e).split(an.sep).join("/");for(let[n,s]of this.frameworkOverrides)if(No(n,r))return s;return null}};function _o(t="vitest",e={},r=process.cwd()){return[new Ft,new Dt,new Tt,new At,new Rt,new cn(r,t,Object.entries(e))]}function Go(t,e){return e.find(r=>r.canHandle(t))??null}var af=/^[a-zA-Z][a-zA-Z0-9_-]{1,}$/,cf=new Set(["import"]),lf=new Set(["common","fixture","fixtures","helper","helpers","index","main","mock","mocks","setup","shared","spec","test","tests","types","util","utils"]);async function pf(t,e,r,n){let s;try{s=await Oo.readFile(t,"utf8")}catch(a){return{path:t,status:"error",error:String(a)}}let o=Go(t,n);if(!o)return{path:t,status:"unchanged"};let i=o.apply(t,s,e);return i===s?{path:t,status:"unchanged"}:(r||await Oo.writeFile(t,i,"utf8"),{path:t,status:"updated"})}async function ln(t,e,r){let n=Ce(e),s=n.tagApplier?.framework??"vitest",o=n.tagApplier?.frameworkOverrides??{},i=_o(s,o,e),a={updated:0,unchanged:0,errors:0,files:[]};for(let c of t.nodes.values()){if(c.category!=="test")continue;let l=new Set,p=[];for(let d of c.tags)cf.has(d.kind)&&af.test(d.name)&&(lf.has(d.name.toLowerCase())||l.has(d.name)||(l.add(d.name),p.push(d.name)));p.sort();let u=of.resolve(e,c.path),g=await pf(u,p,r.dryRun,i);g.path=c.path,a.files.push(g),g.status==="updated"?a.updated++:g.status==="unchanged"?a.unchanged++:a.errors++}return a}var Lt=class{isTestNode(e){return e.category==="test"||e.tags.some(r=>r.name==="test")}};function jo(t,e){return{identifier:e?.identifier??new Lt,featureMap:e?.featureDetection===!1?new Map:te(t.nodes,e?.featureDetection??void 0)}}function zo(t,e,r,n,s){for(let o of e){let i=t.nodes.get(o);if(!i)continue;let a=new Z(o,["*",...i.exports.map(c=>c.name)]);t.traverse(o,(c,l,p)=>{if(!p)return!0;if(!a.updateAffectedSymbols(c,p))return!1;if(l>0){let u=r.get(c.path);if(u)return n(u),!1}return s(c),!0},{direction:"incoming"})}}function pn(t,e,r){let{identifier:n,featureMap:s}=jo(t,r),o=new Set;for(let i of e){let a=s.get(i);a&&o.add(a.tag)}return zo(t,e,s,i=>o.add(i.tag),i=>{if(n.isTestNode(i))for(let a of i.tags)o.add(a.name)}),Array.from(o)}function un(t,e,r){let{identifier:n,featureMap:s}=jo(t,r),o=new Set;return zo(t,e,s,()=>{},i=>{n.isTestNode(i)&&o.add(i.path)}),Array.from(o)}import uf from"fs";import qe from"path";async function Wo(t,e,r=null,n={}){let s=n.silent?void 0:a=>{process.stderr.write(`Processed ${a} files...\r`)},o=qe.resolve(t);return await new Y(o,r,n.pathAliases?new z(o,{pathAliases:n.pathAliases}):void 0,s,n.gitStats??!1,n.coverageMap??new Map,n.parallelParsing??!0,n.additionalIgnoreDirs??[]).build(e)}async function $o(t,e={}){let r=qe.resolve(t),n=Ue(r),s=e.packages?n.packages.filter(a=>e.packages?.includes(a.name)||e.packages?.includes(a.relativeRoot)):n.packages,o=new Map(n.packages.map(a=>[a.name,a.root])),i=new Je(r,n.type);for(let a of s){let c=e.silent?void 0:u=>{process.stderr.write(`[${a.name}] Processed ${u} files...\r`)},p=await new Y(r,null,new z(r,{workspaceMap:o,tsconfigSearchPaths:[a.root,r],pathAliases:e.pathAliases}),c,e.gitStats??!1,new Map,e.parallelParsing??!0).build(a.entryPoints);i.addPackage(a,p)}return i.annotateCrossPackageEdges(),i}function Bo(t,e={}){let r=[],n=new Set([...e.ignoreDirs??T,...e.additionalIgnoreDirs??[]]),s=new Set([...e.extensions??Vt,...e.additionalExtensions??[]]);function o(i){try{let a=uf.readdirSync(i,{withFileTypes:!0});for(let c of a){let l=qe.join(i,c.name);c.isDirectory()?n.has(c.name)||o(l):c.isFile()&&s.has(qe.extname(c.name).toLowerCase())&&r.push(qe.relative(t,l))}}catch{}}return o(t),r}var Ho=/(?:^|[/\\])(?:node_modules|\.git|dist|build|coverage)(?:[/\\]|$)/;function Uo(t){return mn.join(t,oe,we)}function ff(t,e){return e?.cachePath?mn.resolve(t,e.cachePath):mn.join(t,oe,Kt)}function mf(t){try{if(!fn.existsSync(t))return null;let e=fn.readFileSync(t,"utf-8");return P.deserialize(JSON.parse(e))}catch{return null}}var _t=class{graphs=new Map;configs=new Map;workspaceGraphs=new Map;changeImpactCaches=new Map;dirtyRoots=new Set;watchers=new Map;lastAnalyze=new Map;duplicationTokenCaches=new Map;isConfigured(e){return this.configs.has(e)}storeConfig(e,r){this.configs.set(e,r)}getConfig(e){return this.configs.get(e)}async getOrBuild(e,r,n=new Map){let s=this.configs.get(e),o=this.graphs.get(e)??mf(ff(e,s)),i=await Wo(e,r,o,{...U(s),coverageMap:n});return this.graphs.set(e,i),i}require(e){let r=this.graphs.get(e);if(!r)throw new Error('No graph cached for this root. Call "analyze" first.');return r}async getOrBuildWorkspace(e,r={}){let n=this.workspaceGraphs.get(e);if(n)return n;let s=await $o(e,r);return this.workspaceGraphs.set(e,s),s}requireWorkspace(e){let r=this.workspaceGraphs.get(e);if(!r)throw new Error('No workspace graph cached for this root. Call "analyze" first.');return r}hasWorkspace(e){return this.workspaceGraphs.has(e)}getOrBuildChangeImpact(e){let r=this.changeImpactCaches.get(e);if(r)return r;let n=this.require(e),s=tr(n);return this.changeImpactCaches.set(e,s),s}storeLastAnalyze(e,r){this.lastAnalyze.set(e,r)}getLastEntryPoints(e){let r=this.lastAnalyze.get(e);return r?.kind==="single"?r.entryPoints:void 0}startWatching(e){if(!this.watchers.has(e))try{let r=fn.watch(e,{recursive:!0},(n,s)=>{!s||Ho.test(s)||this.dirtyRoots.add(e)});r.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,r)}catch{}}async ensureFresh(e){if(!this.dirtyRoots.has(e))return this.require(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e);let r=this.lastAnalyze.get(e);return r?.kind==="single"?this.getOrBuild(e,r.entryPoints,r.coverageMap):this.require(e)}async ensureFreshWorkspace(e){if(!this.dirtyRoots.has(e))return this.requireWorkspace(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e),this.workspaceGraphs.delete(e);let r=this.configs.get(e);return this.getOrBuildWorkspace(e,U(r))}async getDuplicationTokenCache(e){let r=this.duplicationTokenCaches.get(e);return r||(r=de(Uo(e)),this.duplicationTokenCaches.set(e,r)),r}flushDuplicationTokenCache(e){let r=this.duplicationTokenCaches.get(e);if(r)try{he(r,Uo(e))}catch(n){process.stderr.write(`Warning: failed to persist duplication token cache: ${n}
52
- `)}}invalidate(e){let r=this.graphs.has(e)||this.workspaceGraphs.has(e);return this.graphs.delete(e),this.workspaceGraphs.delete(e),this.changeImpactCaches.delete(e),this.dirtyRoots.delete(e),this.duplicationTokenCaches.delete(e),this.configs.delete(e),r}};import ne from"path";import gf from"fs";import df from"os";import gn from"path";function b(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function Jo(t){if(!gn.isAbsolute(t))throw new Error("root must be an absolute path");let e=gn.resolve(t),r=df.homedir();if(e!==r&&!e.startsWith(r+gn.sep))throw new Error("root must be within the user home directory");let n;try{n=gf.statSync(e)}catch{throw new Error("root does not exist")}if(!n.isDirectory())throw new Error("root is not a directory")}async function Ko(t,e){let{root:r,entryPoints:n}=e;if(!t.isConfigured(r)){let g=Ce(r,{allowJs:!1});Jt(g),t.storeConfig(r,g)}if(n.length===0){let g=Ue(r);if(g.type!=="none"){let d=t.getConfig(r),y=await t.getOrBuildWorkspace(r,U(d));t.storeLastAnalyze(r,{kind:"workspace"}),t.startWatching(r);let v=Array.from(y.packages.values()).map(({graph:x,pkg:k})=>({package:k.name,relativeRoot:k.relativeRoot,nodeCount:x.nodes.size}));return b({monorepoType:g.type,packageCount:y.packages.size,packages:v})}}let s=n.map(g=>ne.resolve(r,g)),o=t.getConfig(r),i=o?.coverageReportPath?Qt(r,o.coverageReportPath):new Map,a=await t.getOrBuild(r,s,i);t.storeLastAnalyze(r,{kind:"single",entryPoints:s,coverageMap:i}),t.startWatching(r);let c=a.serialize(),l=c.nodes.reduce((g,d)=>(g[d.category]=(g[d.category]??0)+1,g),{}),p=a.findCycles(),u=Cr(a);return b({nodeCount:c.nodes.length,categories:l,cycles:p,languageCoverage:u})}async function qo(t,e){let{root:r,file:n,depth:s=1,withMeta:o=!1}=e,i=await t.ensureFresh(r),a=Pr(i,n,s),c=o?a.map(l=>({...l,...ze(i,l.path)})):a;return b({file:n,dependencies:c})}async function Vo(t,e){let{root:r,file:n,withMeta:s=!1}=e,o=await t.ensureFresh(r),i=We(o,n),a=s?i.map(c=>({...c,...ze(o,c.path)})):i;return b({file:n,dependents:a})}async function Qo(t,e){let{root:r,file:n,testsOnly:s=!1,cached:o=!1,changedSymbols:i,withMeta:a=!1}=e,c=await t.ensureFresh(r),l=g=>a?g.map(d=>({path:d,...ze(c,d)})):g;if(o){let g=t.getOrBuildChangeImpact(r),d=rr(g,n),y=s?d.filter(x=>c.nodes.get(x)?.category==="test"):d,v=l(y);return b({file:n,affected:v,count:v.length})}let p=Ar(c,n,{testsOnly:s,changedSymbols:i}),u=l(p);return b({file:n,affected:u,count:u.length})}async function Yo(t,e){let{root:r,baseRef:n,headRef:s,minDuplicateLines:o,complexityMetric:i,complexityThreshold:a}=e,c=await t.ensureFresh(r),l=e.entryPoints??t.getLastEntryPoints(r)?.map(u=>ne.relative(r,u))??[],p=await Gr(r,n,c,{headRef:s,entryPoints:l,minDuplicateLines:o,complexityMetric:i,complexityThreshold:a,maxCoveragePct:e.maxCoveragePct,...U(t.getConfig(r))});return e.detail==="full"?b(p):b(_r(p,{metric:i,maxItems:e.maxItems}))}async function Zo(t,e){let{root:r,file:n,depth:s=1,withEdgeDetail:o=!1}=e,i=await t.ensureFresh(r),a=Nr(i,n,{depth:s,withEdgeDetail:o});return b({file:n,callers:a,count:a.length})}async function Xo(t,e){let{root:r,entryPoints:n}=e,s=n?await t.getOrBuild(r,n.map(c=>ne.resolve(r,c))):await t.ensureFresh(r),o=t.getConfig(r),i=Bo(r,{additionalIgnoreDirs:o?.ignoreDirs??[],additionalExtensions:o?.extensions??[]}),a=s.findUnusedFiles(i);return b({unusedFiles:a,count:a.length})}async function ei(t,e){let{root:r}=e,n=await t.ensureFresh(r),s=new Map;for(let i of n.nodes.values())for(let a of i.tags)s.set(a.name,(s.get(a.name)??0)+1);let o=[...s.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count);return b({tags:o,count:o.length})}async function ti(t,e){let{root:r,coverageThreshold:n}=e,s=await t.ensureFresh(r),o=t.getConfig(r),i=n??o?.coverageThreshold??80;if(!X(s))return b({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let a=[...s.nodes.values()].filter(c=>c.category!=="test"&&c.category!=="config").filter(c=>c.coveragePct!==void 0&&c.coveragePct<i).map(c=>({file:c.path,coveragePct:c.coveragePct}));return b({threshold:i,uncovered:a,count:a.length})}async function ri(t,e){let{root:r}=e,s=[...(await t.ensureFresh(r)).nodes.values()].filter(o=>o.type==="markdown"&&o.staleFor&&o.staleFor.length>0).map(o=>({doc:o.path,staleFor:o.staleFor}));return b({staleDocs:s,count:s.length})}async function ni(t,e){let{root:r,metric:n="cognitiveComplexity",threshold:s=10,limit:o=20}=e,i=await t.ensureFresh(r),a=xe(i,{metric:n,threshold:s,limit:o});return b({metric:n,threshold:s,functions:a,count:a.length})}async function si(t,e){let{root:r,metric:n="cognitiveComplexity",minComplexity:s=10,maxCoveragePct:o=50,minChurn:i=0,limit:a=20}=e,c=await t.ensureFresh(r);if(!X(c))return b({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let{hotspots:l,count:p,churnDataAvailable:u}=be(c,{metric:n,minComplexity:s,maxCoveragePct:o,minChurn:i,limit:a});return b({metric:n,minComplexity:s,maxCoveragePct:o,minChurn:i,churnDataAvailable:u,hotspots:l,count:p})}async function oi(t,e){let{root:r,minLines:n=6,ignoreLiterals:s=!0,maxPunctuationRatio:o=.5,limit:i=50}=e,a=await t.ensureFresh(r),c=e.ignoreDirs??[...T,...t.getConfig(r)?.ignoreDirs??[]],{groups:l}=await ye(a,r,{minLines:n,ignoreLiterals:s,maxPunctuationRatio:o,limit:i,ignoreDirs:c,tokenCache:await t.getDuplicationTokenCache(r)});return t.flushDuplicationTokenCache(r),b({minLines:n,groups:l,count:l.length})}async function ii(t,e){let{root:r,changedFiles:n,base:s,featureThreshold:o,format:i="tags"}=e,a=await t.ensureFresh(r),c=n??new tt().getChangedFiles(r,s).map(u=>ne.relative(r,ne.resolve(r,u))),l=o!==void 0?{featureDetection:{minOutDegree:o}}:void 0;if(i==="paths"){let u=un(a,c,l);return b({changedFiles:c,affectedTests:u,count:u.length})}let p=pn(a,c,l);return b({changedFiles:c,proposedTags:p})}async function ai(t,e){let{root:r,entryPoints:n,featureThreshold:s}=e,o=n?await t.getOrBuild(r,n.map(c=>ne.resolve(r,c))):await t.ensureFresh(r),i=te(o.nodes,s!==void 0?{minOutDegree:s}:void 0),a=Array.from(i.values()).sort((c,l)=>l.outDegree-c.outDegree);return b({features:a,count:a.length})}async function ci(t,e){let{root:r,entryPoints:n,filter:s,mermaid:o=!1,slim:i=!0}=e,a=n?await t.getOrBuild(r,n.map(l=>ne.resolve(r,l))):await t.ensureFresh(r),c=kt(a.serialize(),Ct(s));return o?b(Xe.serialize(P.deserialize(c))):i?b(Dr(c)):b(c)}async function li(t,e){let{root:r}=e,n=await t.ensureFreshWorkspace(r);return b(Rr(n))}async function pi(t,e){let{root:r,file:n}=e,o=(await t.ensureFreshWorkspace(r)).getAffectedAcrossPackages(n);return b({file:n,affected:o,count:o.length})}function ui(t,e){let{root:r}=e,n=t.invalidate(r);return b({root:r,cleared:n,message:n?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function fi(t,e){let{root:r,type:n}=e,s=await t.ensureFresh(r),o=zr(s);if(n)return b(Wr(o,n));let i=Array.from(o.types.values());return b({count:i.length,types:i})}async function mi(t,e){let{root:r,paths:n,minOutDegree:s}=e,o=await t.ensureFresh(r),i=Or(o,s!==void 0?{minOutDegree:s}:void 0);if(n?.length){let c=n.map(l=>i.get(l)).filter(Boolean);return b({count:c.length,modules:c})}let a=Array.from(i.values());return b({count:a.length,modules:a})}async function gi(t,e){let{root:r,minOutDegree:n}=e,s=await t.ensureFresh(r),o=$e(s,n!==void 0?{minOutDegree:n}:void 0),i=Object.fromEntries(o.features);return b({features:i,unassigned:o.unassigned})}async function di(t,e){let{root:r,function:n}=e,s=await t.ensureFresh(r);return b(er(s,n))}async function hi(t,e){let{root:r,name:n}=e,s=await t.ensureFresh(r),o=jr(s,n);return b({name:n,matches:o,count:o.length})}async function yi(t,e){let{root:r,entryPoints:n}=e,s=await t.ensureFresh(r),o=n?.length?n:Zt(s,r);if(o.length===0)throw new Error("No entry points found. Pass entryPoints explicitly or ensure package.json has a main/exports field.");return b(Xt(s,o))}async function xi(t,e){let r=await t.ensureFresh(e.root),n=await ln(r,e.root,{dryRun:e.dryRun??!1});return b(n)}var bi=[{name:"analyze",description:"Build the dependency graph for a project from entry points. Returns a summary of node count, categories, and cycles. Must be called before get_dependencies, get_dependents, get_affected, or propose_tags. Pass an empty entryPoints array to auto-detect a monorepo (pnpm/npm/yarn/Nx/Turborepo) and build per-package graphs \u2014 use get_workspace_packages and get_workspace_affected for monorepo queries.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root (or monorepo root)"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root (e.g. ['src/index.ts']). Pass [] to trigger monorepo auto-detection."}},required:["root","entryPoints"]}},{name:"get_dependencies",description:"Get files that a given file imports (outgoing traversal). depth=1 returns immediate imports; omit for the full transitive tree. Each result includes the specific symbols imported from that file (when known).",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withMeta:{type:"boolean",description:"Include each result's category and export names alongside the path (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"get_dependents",description:"Get files that directly import a given file (one-hop incoming edges). Each result includes the specific symbols that dependent file imports from this file (when known).",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},withMeta:{type:"boolean",description:"Include each result's category and export names alongside the path (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"get_affected",description:"Get all files transitively affected if a given file changes \u2014 full incoming traversal upward. Use before a refactor to understand blast radius. See docs/mcp.md for details on the testsOnly, cached, changedSymbols, and withMeta options.",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},testsOnly:{type:"boolean",description:"Return only test/spec files (default: false)"},cached:{type:"boolean",description:"Use a pre-computed impact cache for O(1) lookup instead of graph traversal. Cache is built lazily on first use and reused for the session (default: false)."},changedSymbols:{type:"array",items:{type:"string"},description:"Restrict blast-radius to files that import at least one of these symbols. Omit to treat the whole file as changed (conservative, same as before)."},withMeta:{type:"boolean",description:"Return each affected file as { path, category, exports } instead of a bare path string (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"compare_branches",description:"Compare the current graph (root) against baseRef, for reviewing a PR/branch: file diff, stale post-rename references, and deltas for duplication, complexity, doc drift, and coverage/risk hotspots. Returns a compact summary by default (verdict + headline + capped delta lists); pass detail:'full' for every entry. See docs/mcp.md for details. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},baseRef:{type:"string",description:"Git ref to compare against, e.g. 'main', 'origin/main', or a commit sha"},headRef:{type:"string",description:"Git ref to label the head side of the comparison (default: 'HEAD'). The graph itself always comes from the already-analyzed root, not a checkout of this ref."},entryPoints:{type:"array",items:{type:"string"},description:"Entry points to build the base-ref graph from, relative to root. Defaults to the entry points from the last analyze() call for this root."},minDuplicateLines:{type:"number",description:"Minimum duplicated block size, in source lines, for the duplication delta (default: 6)"},complexityMetric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which per-function score drives the complexity delta (default: cognitiveComplexity)"},complexityThreshold:{type:"number",description:"Minimum per-function score to count as a complexity hotspot (default: 10)"},maxCoveragePct:{type:"number",description:"Maximum containing-file coverage % to count as a risk hotspot (default: 50)"},detail:{type:"string",enum:["summary","full"],description:"'summary' (default): verdict, headline, and each delta list capped at maxItems with true counts; empty sections omitted. 'full': the complete BranchComparison with every entry."},maxItems:{type:"number",description:"In summary mode, max entries kept per delta list (complexity/duplication/doc-drift/coverage); the true count is always reported alongside (default: 8). Stale references are never truncated."}},required:["root","baseRef"]}},{name:"get_callers",description:"Get files whose exported functions call into a given file (call-graph dependents). More precise than get_affected: only files with actual runtime call edges, not mere imports. Requires prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to project root"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withEdgeDetail:{type:"boolean",description:"Include from/to function names per edge (default: false)"}},required:["root","file"]}},{name:"find_unused",description:"Find files in the project that are not reachable from any entry point. Useful before cleanup passes. Omit entryPoints to reuse the cached graph from a prior analyze() call instead of rebuilding.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to reuse the cached graph from a prior analyze() call."}},required:["root"]}},{name:"list_tags",description:"List every distinct tag name present in the graph, with how many nodes carry each one. Call this before querying with tag:<name> to avoid a speculative filter silently returning zero results. Includes all tag kinds \u2014 a superset of what query's slim mode keeps (slim only retains comment-marker and import tags).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"}},required:["root"]}},{name:"find_uncovered",description:"Find non-test files whose line coverage is below the configured threshold. Requires a prior analyze() call and coverageReportPath set in mokosh.config. coverageThreshold overrides the config default (default: 80).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},coverageThreshold:{type:"number",description:"Line-coverage % below which a file is considered uncovered. Overrides config value."}},required:["root"]}},{name:"check_doc_drift",description:"Find markdown docs whose referenced files changed more recently than the doc itself \u2014 a commit-recency heuristic for stale documentation, not a content diff. Requires a prior analyze() call with gitStats: true in mokosh.config (otherwise no file has commit-timestamp data and nothing is flagged). See docs/adr-009-markdown-parsing.md for known limitations.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"}},required:["root"]}},{name:"find_complex_functions",description:"Find individual functions/methods above a cognitive (or cyclomatic) complexity threshold, sorted worst-first. Requires a prior analyze() call. Populated for TypeScript/JavaScript, Go, and Python.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which score to threshold/sort on (default: cognitiveComplexity)"},threshold:{type:"number",description:"Minimum score to include (default: 10)"},limit:{type:"number",description:"Max results to return, worst-first (default: 20)"}},required:["root"]}},{name:"find_risk_hotspots",description:"Find functions that are complex, in a poorly-covered file, and \u2014 when gitStats is enabled in mokosh.config \u2014 in a frequently-changed file. Requires a prior analyze() call and coverageReportPath set in mokosh.config; errors if no coverage data was loaded. Churn filtering is skipped (churnDataAvailable: false) when gitStats wasn't enabled, since complexity + low coverage alone is still a meaningful signal.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which per-function score to filter/sort on (default: cognitiveComplexity)"},minComplexity:{type:"number",description:"Minimum per-function complexity score to include (default: 10)"},maxCoveragePct:{type:"number",description:"Maximum containing-file coverage % to include (default: 50)"},minChurn:{type:"number",description:"Minimum containing-file 90-day commit count to include (default: 0). Ignored when gitStats wasn't enabled at analyze time."},limit:{type:"number",description:"Max results to return, worst-first by metric (default: 20)"}},required:["root"]}},{name:"find_duplicates",description:"Find duplicated code blocks across the project, largest-first. CSS/SCSS/Less are matched structurally by rule body; every other parsed language is tokenized and matched via suffix array. Lock files and ignored directories are always excluded. Requires a prior analyze() call. See docs/mcp.md for matching-strategy, normalization, and caching details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minLines:{type:"number",description:"Minimum duplicated block size in lines to report (default: 6)"},ignoreLiterals:{type:"boolean",description:"Normalize string/number literals too, not just identifiers, so only structural shape drives a match (default: true). Set false for stricter, exact-text-only matching."},maxPunctuationRatio:{type:"number",description:"Maximum fraction of a token-shingled block's window that may be object/array-literal structural punctuation ({ } : , [ ]) (default: 0.5). Filters out blocks that are mostly schema/object-literal shape instead of substantive shared logic. Does not apply to the CSS/Less/SCSS structural comparator. Set 1 to disable."},ignoreDirs:{type:"array",items:{type:"string"},description:"Directory names to exclude, matched against any path segment (default: DEFAULT_IGNORE_DIRS merged with this root's configured ignoreDirs, if any). Pass [] to disable."},limit:{type:"number",description:"Max duplicate blocks to return, largest-first (default: 50)"}},required:["root"]}},{name:"propose_tags",description:"Propose what to run based on changed files. Pass changedFiles explicitly or omit to use git diff. format='tags' (default) returns test tags for CI tag-filtering; format='paths' returns test file paths ready to pipe directly to a test runner (e.g. vitest). Feature hubs act as traversal boundaries in both modes.",inputSchema:{type:"object",properties:{root:{type:"string"},changedFiles:{type:"array",items:{type:"string"},description:"Changed files relative to root. Omit to read from git diff."},base:{type:"string",description:"Diff against this ref (e.g. 'origin/main') instead of only local working-tree/staged/untracked changes. Ignored when changedFiles is given. Needed in CI, where the checkout is already clean."},featureThreshold:{type:"number",description:"Min importers for a file to be treated as a feature hub (default: 5). A hub short-circuits traversal and emits a feature:<name> tag instead of all downstream tags."},format:{type:"string",enum:["tags","paths"],description:"Output format: 'tags' returns test tag names for CI filtering (default); 'paths' returns test file paths to pipe to a test runner."}},required:["root"]}},{name:"detect_features",description:"Identify feature hub files \u2014 non-test files that import many other internal modules (orchestrators / aggregators like src/parser.ts or src/cli/runner.ts). Returns a list sorted by import count descending.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to use the cached graph."},featureThreshold:{type:"number",description:"Min internal imports a file must have to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"query",description:"Filter the graph by category, tag, path, or other node metadata. Returns matching nodes as JSON or a Mermaid diagram. If entryPoints is omitted the cached graph from a prior 'analyze' call is used. See docs/mcp.md for the full query DSL reference.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry points to build the graph. Omit to reuse the cached graph from a prior 'analyze' call."},filter:{type:"string",description:"Query string e.g. 'category:logic' or 'category:logic,tag:auth'. Supports: category, type, tag, path, external, importsFile, importedBy, minImports, maxImports, minSize, maxSize, hasDocstring, minCoverage, maxCoverage, minExportUsage, maxExportUsage, minComplexity, maxComplexity, minCognitiveComplexity, maxCognitiveComplexity, minCommits, maxCommits, isDocumented, isStale, lastAuthor. OR logic: any(key:val|key:val) matches if any single-key clause holds, ANDed with the rest of the query. sort: size|imports|commitCount90d|exportUsage|complexity|cognitiveComplexity, with sortDir: asc|desc (default desc). limit: N."},mermaid:{type:"boolean",description:"Return a Mermaid diagram (default: false)"},slim:{type:"boolean",description:"Compact response mode (default: true). Returns export names, meaningful tags, and a flat importsFiles path list \u2014 no edge objects, no mtime/size. Tags are filtered to kinds comment-marker and import only; function/class/variable/type/library tags are dropped in slim output. Use list_tags to see the full tag inventory, or pass slim: false to get every tag kind on matching nodes."}},required:["root","filter"]}},{name:"get_workspace_packages",description:"List all workspace packages detected in a monorepo, with their node counts and inter-package dependencies. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"}},required:["root"]}},{name:"get_workspace_affected",description:"Cross-package blast-radius analysis. Returns every file that could be affected if a given file changes, annotated with the package it belongs to. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"},file:{type:"string",description:"Monorepo-root-relative path of the changed file (e.g. 'packages/shared/src/utils.ts')"}},required:["root","file"]}},{name:"get_type_graph",description:"Return type-level relationships for the project. Without a type name, returns an inventory of all interfaces, classes, enums, and type aliases with their file and kind. With a type name, returns which files import that type (usedByFiles) and which types the defining file imports (uses). Requires a prior analyze() call. Only covers TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},type:{type:"string",description:"Exact exported name of the type to look up (e.g. 'FileNode'). Omit to get the full type inventory."}},required:["root"]}},{name:"get_module_responsibility",description:"Return what each file is responsible for: its semantic role, JSDoc description (when present), exported symbol names, and which feature hub it belongs to. Pass specific paths to filter, or omit paths to get all files. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},paths:{type:"array",items:{type:"string"},description:"Project-relative file paths to include. Omit to return all files."},minOutDegree:{type:"number",description:"Min imports for a file to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_feature_graph",description:"Group files by domain: returns which files each feature hub (high-import orchestrator) transitively owns. Each file is assigned to the most specific hub that can reach it (lowest out-degree wins). Use this instead of a full query when answering 'what files are in the X feature/module?' \u2014 it returns only paths grouped by hub, so it's substantially smaller than a full graph query for the same question; compare output sizes yourself if you need an exact figure for your repo.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minOutDegree:{type:"number",description:"Minimum internal imports a file must have to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_call_graph",description:"Look up callers and callees for a named function. Returns the file that defines the function, all files/functions that call it, and all files/functions it calls. Always requires a function name \u2014 never returns the full call graph unfiltered. Call edges are only populated for TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},function:{type:"string",description:"Exact name of the function to look up (e.g. 'parseFile')."}},required:["root","function"]}},{name:"find_symbol",description:"Find every file that exports a symbol by exact name, with the best available usage info per match. Precision varies by the defining file's language \u2014 check each match's `precision` field ('call' | 'file-level') before trusting caller/importer results as symbol-exact. See docs/mcp.md for per-language coverage details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},name:{type:"string",description:"Exact export name to look up (e.g. 'parseFile')."}},required:["root","name"]}},{name:"get_api_surface",description:"Build the API surface report for a project: every exported symbol resolved to its defining file and kind, partitioned into internalFiles, unreachableFromEntry, and testFiles. Requires a prior analyze() call. When entryPoints is omitted, auto-detects from package.json exports/main/module. See docs/mcp.md for the export* expansion and partition semantics.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},entryPoints:{type:"array",items:{type:"string"},description:"Project-relative paths of public entry points (e.g. ['src/index.ts', 'src/utils.ts']). Omit to auto-detect from package.json exports / main / module fields."}},required:["root"]}},{name:"clear_cache",description:"Drop the cached dependency graph and loaded mokosh.config.json for a project root, forcing the next analyze() call to rebuild from disk and re-read config. Call this after editing source files OR mokosh.config.json mid-session \u2014 otherwise get_affected, get_dependencies, and other query tools will reason from stale data (or a stale config).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root to invalidate."}},required:["root"]}},{name:"apply_tags",description:"Write @tag annotations into test file source code based on the dependency graph, as an idempotent block \u2014 re-running is safe, the existing block is replaced in place. Use dryRun=true to preview changes without writing to disk. Requires a prior analyze() call. See docs/mcp.md for tag-kind and per-language block syntax details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root."},dryRun:{type:"boolean",description:"When true, computes which files would change but does not write to disk (default: false)."}},required:["root"]}}];function dn(){let t=new _t,e=new hf({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(xf,async()=>({tools:bi})),e.setRequestHandler(yf,async r=>{let{name:n,arguments:s}=r.params,o=s,a={analyze:c=>Ko(t,c),get_dependencies:c=>qo(t,c),get_dependents:c=>Vo(t,c),get_affected:c=>Qo(t,c),compare_branches:c=>Yo(t,c),get_callers:c=>Zo(t,c),find_symbol:c=>hi(t,c),find_unused:c=>Xo(t,c),find_uncovered:c=>ti(t,c),list_tags:c=>ei(t,c),check_doc_drift:c=>ri(t,c),find_complex_functions:c=>ni(t,c),find_risk_hotspots:c=>si(t,c),find_duplicates:c=>oi(t,c),propose_tags:c=>ii(t,c),detect_features:c=>ai(t,c),get_type_graph:c=>fi(t,c),get_module_responsibility:c=>mi(t,c),get_feature_graph:c=>gi(t,c),get_call_graph:c=>di(t,c),get_api_surface:c=>yi(t,c),query:c=>ci(t,c),get_workspace_packages:c=>li(t,c),get_workspace_affected:c=>pi(t,c),clear_cache:c=>ui(t,c),apply_tags:c=>xi(t,c)}[n];if(!a)throw new Error(`Unknown tool: ${n}`);try{return Jo(o.root),await a(o)}catch(c){return{content:[{type:"text",text:`Error: ${c instanceof Error?c.message:String(c)}`}],isError:!0}}}),e}async function Sf(){let t=dn(),e=new bf;await t.connect(e)}Sf().catch(console.error);export{dn as createMcpServer};
57
+ `;return`${l+f+u+o}
58
+ ${p}`}};function hd(t){let e=t.split(`
59
+ `),n=-1;return e.forEach((s,i)=>{(s.trimStart().startsWith("import ")||s.trimStart().startsWith("from "))&&(n=i)}),n<0?0:e.slice(0,n+1).reduce((s,i)=>s+i.length+1,0)}import yd from"path";var _s=/^\/\/ mokosh:tags .*\n/m,xd=/^(?:sealed\s+|abstract\s+|final\s+|private\s+|implicit\s+|case\s+)*(?:class|object|trait)\s+\w+/m,bd=/\/src\/(test|it)\//,kd=/(Spec|Suite|Test|Props)\.scala$/;function Sd(t){let e=_s.exec(t);return e?e[0].replace(/^\/\/ mokosh:tags /,"").trim().split(/\s*,\s*/).filter(Boolean):null}var zn=class{name="scalatest";canHandle(e){let n=e.replace(/\\/g,"/");return yd.extname(n).toLowerCase()!==".scala"?!1:bd.test(n)||kd.test(n)}apply(e,n,r){let s=Sd(n),i=[...r].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(i))return n;if(r.length===0)return s===null?n:n.replace(_s,"");let o=`// mokosh:tags ${i.join(", ")}
60
+ `;if(s!==null)return n.replace(_s,o);let a=xd.exec(n);return a?n.slice(0,a.index)+o+n.slice(a.index):n}};import za from"path";import Ba from"typescript";var vd=/\/\/ <mokosh-tags>[\s\S]*?\/\/ <\/mokosh-tags>\n*/,Bn=class{name="vitest";canHandle(e){return ne.has(za.extname(e).toLowerCase())}apply(e,n,r){let s=n.replace(vd,""),i=Ba.createSourceFile(za.basename(e),s,Ba.ScriptTarget.Latest,!0),o=ws(i),[a]=o;if(!a)return s;let c=Es(a,"tags",i),l=[...r].sort();if(c!==null&&JSON.stringify([...c].sort())===JSON.stringify(l))return s;let p=o.flatMap(u=>{let f=r.length===0?Fs(u,"tags",i):Ts(u,"tags",Ps(l),i);return f?[f]:[]});return p.length>0?Ds(s,p):s}};var Ua={vitest:()=>new Bn,playwright:()=>new Wn,cypress:()=>new Ln,jest:()=>new On},Cd={"@playwright/test":"playwright",cypress:"cypress","@jest/globals":"jest",vitest:"vitest"};function wd(t){let e=Un.createSourceFile("detect.ts",t,Un.ScriptTarget.Latest,!0);for(let n of e.statements){if(!Un.isImportDeclaration(n)||!Un.isStringLiteral(n.moduleSpecifier))continue;let r=Cd[n.moduleSpecifier.text];if(r)return r}return null}var Os=class{constructor(e,n,r){this.rootDir=e;this.defaultFramework=n;this.frameworkOverrides=r}rootDir;defaultFramework;frameworkOverrides;name="auto";canHandle(e){return ne.has(Gs.extname(e).toLowerCase())}apply(e,n,r){let s=wd(n)??this.matchOverride(e)??this.defaultFramework;return(Ua[s]??Ua.vitest)().apply(e,n,r)}matchOverride(e){let n=Gs.relative(this.rootDir,e).split(Gs.sep).join("/");for(let[r,s]of this.frameworkOverrides)if(ja(r,n))return s;return null}};function Ka(t="vitest",e={},n=process.cwd()){return[new _n,new $n,new Gn,new jn,new zn,new Os(n,t,Object.entries(e))]}function Ha(t,e){return e.find(n=>n.canHandle(t))??null}async function Td(t,e,n,r){let s;try{s=await Ja.readFile(t,"utf8")}catch(a){return{path:t,status:"error",error:String(a)}}let i=Ha(t,r);if(!i)return{path:t,status:"unchanged"};let o=i.apply(t,s,e);return o===s?{path:t,status:"unchanged"}:(n||await Ja.writeFile(t,o,"utf8"),{path:t,status:"updated"})}async function js(t,e,n){let r=ft(e),s=r.tagApplier?.framework??"vitest",i=r.tagApplier?.frameworkOverrides??{},o=Ka(s,i,e),a={updated:0,unchanged:0,errors:0,files:[]};for(let c of t.nodes.values()){if(c.category!=="test")continue;let l=new Set,p=[];for(let m of c.tags)Ce(m)&&(l.has(m.name)||(l.add(m.name),p.push(m.name)));p.sort();let u=Ed.resolve(e,c.path),f=await Td(u,p,n.dryRun,o);f.path=c.path,a.files.push(f),f.status==="updated"?a.updated++:f.status==="unchanged"?a.unchanged++:a.errors++}return a}var Kn=class{isTestNode(e){return e.category==="test"||e.tags.some(n=>n.name==="test")}};function Va(t,e){return{identifier:e?.identifier??new Kn,featureMap:e?.featureDetection===!1?new Map:xe(t.nodes,e?.featureDetection??void 0)}}function Qa(t,e,n,r,s){for(let i of e){let o=t.nodes.get(i);if(!o)continue;let a=new Re(i,["*",...o.exports.map(c=>c.name)]);t.traverse(i,(c,l,p)=>{if(!p)return!0;if(!a.updateAffectedSymbols(c,p))return!1;if(l>0){let u=n.get(c.path);if(u)return r(u),!1}return s(c),!0},{direction:"incoming"})}}function Ws(t,e,n){let{identifier:r,featureMap:s}=Va(t,n),i=new Set;for(let o of e){let a=s.get(o);a&&i.add(a.tag)}return Qa(t,e,s,o=>i.add(o.tag),o=>{if(r.isTestNode(o))for(let a of dr(o.tags))i.add(a)}),Array.from(i)}function $s(t,e,n){let{identifier:r,featureMap:s}=Va(t,n),i=new Set;return Qa(t,e,s,()=>{},o=>{r.isTestNode(o)&&i.add(o.path)}),Array.from(i)}import Xa from"crypto";import Za from"fs";import Fd from"os";import be from"path";async function qa(t,e,n=null,r={}){let s=r.silent?void 0:a=>{process.stderr.write(`Processed ${a} files...\r`)},i=be.resolve(t);return await new Ae(i,n,r.pathAliases?new ae(i,{pathAliases:r.pathAliases}):void 0,s,r.gitStats??!1,r.coverageMap??new Map,r.parallelParsing??!0,r.additionalIgnoreDirs??[],r.docFiles??null).build(e)}function Dd(t){let e=Number.parseInt(process.env.MOKOSH_WORKSPACE_CONCURRENCY??"",10),n=Number.isFinite(e)&&e>0?e:Fd.cpus().length||1;return Math.max(1,Math.min(n,Math.max(1,t)))}function Pd(t,e,n){let r=new Map(e.map(i=>[i.name,[]])),s=[...e].sort((i,o)=>o.root.length-i.root.length);for(let i of n){if(!i.endsWith(".md")&&!i.endsWith(".mdx"))continue;let o=be.join(t,i),a=s.find(c=>o===c.root||o.startsWith(`${c.root}${be.sep}`));a&&r.get(a.name)?.push(o)}return r}function Bs(t){let e=Jn(t),n=Xa.createHash("sha256");for(let r of[...e].sort())n.update(`${ec(t,r)}
61
+ `);return{digest:n.digest("hex"),files:e}}function ec(t,e){try{let n=Za.statSync(be.join(t,e));return`${e}\0${n.mtimeMs}\0${n.size}`}catch{return`${e}\0?\0?`}}function Us(t,e,n){let r=[...e].sort((c,l)=>l.relativeRoot.length-c.relativeRoot.length),s=new Map(e.map(c=>[c.name,[]])),i=[];for(let c of n){let l=r.find(p=>it(c,p));(l?s.get(l.name):i).push(c)}let o=c=>{let l=Xa.createHash("sha256");for(let p of[...c].sort())l.update(`${ec(t,p)}
62
+ `);return l.digest("hex")},a=new Map;for(let[c,l]of s)a.set(c,o(l));return{rootDigest:o(i),packageDigests:a}}async function Hn(t,e={}){let n=be.resolve(t),r=e.layout??Lt(n),s=e.projectFiles??Jn(n),i=e.additionalIgnoreDirs??[],o=e.packages?r.packages.filter(k=>e.packages?.includes(k.name)||e.packages?.includes(k.relativeRoot)):r.packages,a=new Map(r.packages.map(k=>[k.name,k.root])),c=new Ie(n,r.type),l=new Pe(i),p=Pd(n,o,s),u=Dd(o.length),f=u>1?!1:e.parallelParsing??!0,m=new Array(o.length),h=0,b=async()=>{for(let k=h++;k<o.length;k=h++){let S=o[k],w=e.silent?void 0:_=>{process.stderr.write(`[${S.name}] Processed ${_} files...\r`)},N=new Ae(n,e.previousWorkspace?.packages.get(S.name)?.graph??null,new ae(n,{workspaceMap:a,tsconfigSearchPaths:[S.root,n],pathAliases:e.pathAliases,langResolvers:pn({jvm:l})}),w,e.gitStats??!1,new Map,f,i,p.get(S.name)??[]);m[k]=await N.build(S.entryPoints)}};return await Promise.all(Array.from({length:u},b)),o.forEach((k,S)=>{c.addPackage(k,m[S])}),c.annotateCrossPackageEdges(),c}function Jn(t,e={}){let n=[],r=new Set([...e.ignoreDirs??j,...e.additionalIgnoreDirs??[]]),s=new Set([...e.extensions??sr,...e.additionalExtensions??[]]);function i(o){try{let a=Za.readdirSync(o,{withFileTypes:!0});for(let c of a){let l=be.join(o,c.name);c.isDirectory()?r.has(c.name)||i(l):c.isFile()&&s.has(be.extname(c.name).toLowerCase())&&n.push(be.relative(t,l))}}catch{}}return i(t),n}function tc(t){return _e.join(t,nr)}function Rd(t){let e=t.replace(/[^a-zA-Z0-9._-]+/g,"_").replace(/^_+|_+$/g,"")||"pkg",n=Ad.createHash("sha1").update(t).digest("hex").slice(0,8);return`${e}-${n}.json`}function Nd(t){try{le.rmSync(_e.join(t,tr),{force:!0})}catch{}}function nc(t,e,n,r=()=>{}){try{let s=tc(t);le.mkdirSync(s,{recursive:!0});let i=n.serialize(),{rootDigest:o,packageDigests:a}=Us(n.monorepoRoot,i.packages.map(({pkg:u})=>u),e),c=[],l=new Set([pt]);for(let{pkg:u,nodes:f}of i.packages){let m=a.get(u.name)??"",h=JSON.stringify({nodes:f});if(Buffer.byteLength(h)>50331648){c.push({name:u.name,relativeRoot:u.relativeRoot,entryPoints:u.entryPoints,digest:m,nodeCount:f.length,skipped:!0});continue}let b=Rd(u.name);le.writeFileSync(_e.join(s,b),h),l.add(b),c.push({name:u.name,relativeRoot:u.relativeRoot,entryPoints:u.entryPoints,file:b,digest:m,nodeCount:f.length})}for(let u of le.readdirSync(s))u.endsWith(".json")&&!l.has(u)&&le.rmSync(_e.join(s,u),{force:!0});let p={version:1,monorepoRoot:n.monorepoRoot,type:n.type,rootDigest:o,packages:c};le.writeFileSync(_e.join(s,pt),JSON.stringify(p)),Nd(t)}catch(s){r(`failed to persist workspace graph cache: ${s}`)}}function rc(t,e){try{let n=tc(t),r=_e.join(n,pt);if(!le.existsSync(r))return null;let s=JSON.parse(le.readFileSync(r,"utf-8"));if(s.version!==1||!Array.isArray(s.packages))return null;let{rootDigest:i,packageDigests:o}=Us(s.monorepoRoot,s.packages.map(c=>({name:c.name,relativeRoot:c.relativeRoot})),e);if(i!==s.rootDigest)return null;let a=new Ie(s.monorepoRoot,s.type);for(let c of s.packages){if(c.skipped||!c.file||o.get(c.name)!==c.digest)return null;let l=le.readFileSync(_e.join(n,c.file),"utf-8"),{nodes:p}=JSON.parse(l),u=new P(new Map(p.map(f=>[f.path,f])));a.addPackage({name:c.name,relativeRoot:c.relativeRoot,entryPoints:c.entryPoints,root:""},u)}return a}catch{return null}}var sc=/(?:^|[/\\])(?:node_modules|\.git|dist|build|coverage)(?:[/\\]|$)/;function ic(t){return Q.join(t,me,lt)}function Id(t,e,n){let r=e?.cachePath?Q.dirname(Q.resolve(t,e.cachePath)):Q.join(t,me);if(!n)return Q.join(r,qn);let s=Md.createHash("sha1").update(n).digest("hex").slice(0,8);return Q.join(r,`duplication-result-${s}.json`)}function Ld(t,e){return e?.cachePath?Q.resolve(t,e.cachePath):Q.join(t,me,er)}function _d(t,e){return e?.cachePath?Q.dirname(Q.resolve(t,e.cachePath)):Q.join(t,me)}function Gd(t){try{if(!Ks.existsSync(t))return null;let e=Ks.readFileSync(t,"utf-8");return P.deserialize(JSON.parse(e))}catch{return null}}function oc(t,e){let n=new Map([...t.nodes].filter(([r])=>it(r,e)));return new P(n)}function Od(t,e){let n=new Map([...t.graph.nodes].filter(([s])=>t.packageOf.get(s)===e)),r=new Map([...t.packageOf].filter(([s])=>n.has(s)));return{graph:new P(n),packageOf:r}}var Vn=class{graphs=new Map;configs=new Map;workspaceGraphs=new Map;workspaceDigests=new Map;layouts=new Map;workspaceBuilds=new Map;changeImpactCaches=new Map;dirtyRoots=new Set;watchers=new Map;lastAnalyze=new Map;duplicationTokenCaches=new Map;isConfigured(e){return this.configs.has(e)}storeConfig(e,n){this.configs.set(e,n)}getConfig(e){return this.configs.get(e)}async getOrBuild(e,n,r=new Map){let s=this.configs.get(e),i=this.graphs.get(e)??Gd(Ld(e,s)),o=await qa(e,n,i,{...ge(s),coverageMap:r});return this.graphs.set(e,o),o}require(e){let n=this.graphs.get(e);if(!n)throw new Error('No graph cached for this root. Call "analyze" first.');return n}getLayout(e){let n=this.layouts.get(e);if(n)return n;let r=Lt(e);return this.layouts.set(e,r),r}async getOrBuildWorkspace(e,n={}){let r=this.workspaceGraphs.get(e);if(r)return r;let s=this.workspaceBuilds.get(e);if(s)return s;let{forceFresh:i,...o}=n,a=_d(e,this.configs.get(e)),{digest:c,files:l}=Bs(e),p=i?null:rc(a,l);if(p)return this.workspaceGraphs.set(e,p),this.workspaceDigests.set(e,c),p;let u=Hn(e,{...o,layout:this.getLayout(e),projectFiles:l}).then(f=>(this.workspaceGraphs.set(e,f),this.workspaceDigests.set(e,c),nc(a,l,f,m=>process.stderr.write(`Warning: ${m}
63
+ `)),f)).finally(()=>{this.workspaceBuilds.delete(e)});return this.workspaceBuilds.set(e,u),u}requireWorkspace(e){let n=this.workspaceGraphs.get(e);if(!n)throw new Error('No workspace graph cached for this root. Call "analyze" first.');return n}hasWorkspace(e){return this.workspaceGraphs.has(e)}getOrBuildChangeImpact(e){return this.getOrBuildChangeImpactFor(e,()=>this.require(e))}getOrBuildChangeImpactFor(e,n){let r=this.changeImpactCaches.get(e);if(r)return r;let s=vr(n());return this.changeImpactCaches.set(e,s),s}async getOrBuildChangeImpactForFile(e,n,r){if(!this.isWorkspaceRoot(e))return this.getOrBuildChangeImpactFor(e,()=>r);if(!(await this.ensureFreshWorkspace(e)).getPackageForFile(n))throw new Error(`No workspace package owns "${n}". Call get_workspace_packages to list packages.`);return this.getOrBuildChangeImpactFor(`${e}::__flat__`,()=>r)}clearChangeImpactCachesFor(e){this.changeImpactCaches.delete(e);let n=`${e}::`;for(let r of this.changeImpactCaches.keys())r.startsWith(n)&&this.changeImpactCaches.delete(r)}isWorkspaceRoot(e){return this.lastAnalyze.get(e)?.kind==="workspace"}async resolveGraphForFile(e,n){return(await this.resolveFlatGraphForFile(e,n)).graph}async resolveFlatGraphForFile(e,n){if(!this.isWorkspaceRoot(e))return{graph:await this.ensureFresh(e),packageOf:new Map};let r=await this.ensureFreshWorkspace(e);if(!r.getPackageForFile(n))throw new Error(`No workspace package owns "${n}". Call get_workspace_packages to list packages.`);return r.flatten()}async resolveGraphs(e,n){if(!this.isWorkspaceRoot(e))return[{package:"",graph:await this.ensureFresh(e)}];let r=await this.ensureFreshWorkspace(e);if(n){let s=r.packages.get(n);if(!s)throw new Error(`Unknown workspace package "${n}". Call get_workspace_packages to list packages.`);return[{package:n,graph:oc(s.graph,s.pkg)}]}return Array.from(r.packages.entries()).map(([s,{graph:i,pkg:o}])=>({package:s,graph:oc(i,o)}))}async resolveFlatGraph(e,n){if(!this.isWorkspaceRoot(e))return{graph:await this.ensureFresh(e),packageOf:new Map};let r=await this.ensureFreshWorkspace(e),s=r.flatten();if(n){if(!r.packages.has(n))throw new Error(`Unknown workspace package "${n}". Call get_workspace_packages to list packages.`);return Od(s,n)}return s}storeLastAnalyze(e,n){this.lastAnalyze.set(e,n)}getLastEntryPoints(e){let n=this.lastAnalyze.get(e);return n?.kind==="single"?n.entryPoints:void 0}startWatching(e){if(!this.watchers.has(e))try{let n=Ks.watch(e,{recursive:!0},(r,s)=>{!s||sc.test(s)||this.dirtyRoots.add(e)});n.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,n)}catch{}}async ensureFresh(e){if(!this.dirtyRoots.has(e))return this.require(e);this.dirtyRoots.delete(e),this.clearChangeImpactCachesFor(e);let n=this.lastAnalyze.get(e);return n?.kind==="single"?this.getOrBuild(e,n.entryPoints,n.coverageMap):this.require(e)}async ensureFreshWorkspace(e){if(!this.dirtyRoots.has(e)){let i=this.workspaceGraphs.get(e);return i||this.getOrBuildWorkspace(e,ge(this.configs.get(e)))}this.dirtyRoots.delete(e);let n=this.workspaceGraphs.get(e);if(n){let{digest:i}=Bs(e);if(i===this.workspaceDigests.get(e))return n}this.clearChangeImpactCachesFor(e);let r=this.workspaceGraphs.get(e);this.workspaceGraphs.delete(e),this.workspaceDigests.delete(e);let s=this.configs.get(e);return this.getOrBuildWorkspace(e,{...ge(s),forceFresh:!0,previousWorkspace:r})}async getDuplicationTokenCache(e){let n=this.duplicationTokenCaches.get(e);return n||(n=Ye(ic(e)),this.duplicationTokenCaches.set(e,n)),n}flushDuplicationTokenCache(e){let n=this.duplicationTokenCaches.get(e);if(n)try{Xe(n,ic(e))}catch(r){process.stderr.write(`Warning: failed to persist duplication token cache: ${r}
64
+ `)}}duplicationResultCachePath(e,n){return Id(e,this.configs.get(e),n)}invalidate(e){let n=this.graphs.has(e)||this.workspaceGraphs.has(e);return this.graphs.delete(e),this.workspaceGraphs.delete(e),this.workspaceDigests.delete(e),this.workspaceBuilds.delete(e),this.layouts.delete(e),this.clearChangeImpactCachesFor(e),this.dirtyRoots.delete(e),this.duplicationTokenCaches.delete(e),this.configs.delete(e),n}};import ke from"path";import jd from"fs";import Wd from"os";import Hs from"path";function v(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function ac(t){if(!Hs.isAbsolute(t))throw new Error("root must be an absolute path");let e=Hs.resolve(t),n=Wd.homedir();if(e!==n&&!e.startsWith(n+Hs.sep))throw new Error("root must be within the user home directory");let r;try{r=jd.statSync(e)}catch{throw new Error("root does not exist")}if(!r.isDirectory())throw new Error("root is not a directory")}var cc=500,$d=12e4,zd=8;function Js(t,e){return e.size===0?t:t.map(n=>{let r=e.get(n.path);return r?{...n,package:r}:n})}function Y(t,e,n){return n&&e?t.map(r=>({...r,package:e})):t}async function fc(t,e){let{root:n,entryPoints:r}=e;if(!t.isConfigured(n)){let m=ft(n,{allowJs:!1});yr(m),t.storeConfig(n,m)}if(r.length===0){let m=t.getLayout(n);if(m.type!=="none"){let h=t.getConfig(n),b={...ge(h),packages:e.packages};if(t.storeLastAnalyze(n,{kind:"workspace"}),t.startWatching(n),!e.eager){let w=t.hasWorkspace(n)?t.requireWorkspace(n):void 0;return v(It(m,w))}let k=await t.getOrBuildWorkspace(n,b),S=Array.from(k.packages.values()).map(({graph:w,pkg:N})=>({package:N.name,relativeRoot:N.relativeRoot,nodeCount:w.nodes.size}));return v({monorepoType:m.type,packageCount:k.packages.size,packages:S})}}let s=r.map(m=>ke.resolve(n,m)),i=t.getConfig(n),o=i?.coverageReportPath?xr(n,i.coverageReportPath):new Map,a=await t.getOrBuild(n,s,o);t.storeLastAnalyze(n,{kind:"single",entryPoints:s,coverageMap:o}),t.startWatching(n);let c=a.serialize(),l=c.nodes.reduce((m,h)=>(m[h.category]=(m[h.category]??0)+1,m),{}),p=a.findCycles({includeKinds:e.cycleKinds}),u=Jr(a),f=Hr(a);return v({nodeCount:c.nodes.length,categories:l,cycles:p,languageCoverage:u,...f.length>0&&{caveats:f}})}async function mc(t,e){let{root:n,file:r,depth:s=1,withMeta:i=!1}=e,{graph:o,packageOf:a}=await t.resolveFlatGraphForFile(n,r),c=ns(o,r,s),l=i?c.map(f=>({...f,...Pt(o,f.path)})):c,p=Js(l,a),u=V(o,"importResolution");return v({file:r,dependencies:p,...u.length>0&&{caveats:u}})}async function gc(t,e){let{root:n,file:r,withMeta:s=!1}=e,{graph:i,packageOf:o}=await t.resolveFlatGraphForFile(n,r),a=At(i,r),c=s?a.map(u=>({...u,...Pt(i,u.path)})):a,l=Js(c,o),p=V(i,"importResolution");return v({file:r,dependents:l,...p.length>0&&{caveats:p}})}async function dc(t,e){let{root:n,file:r,testsOnly:s=!1,cached:i=!1,changedSymbols:o,withMeta:a=!1}=e,{graph:c,packageOf:l}=await t.resolveFlatGraphForFile(n,r),p=m=>a?Js(m.map(h=>({path:h,...Pt(c,h)})),l):m;if(i){let m=await t.getOrBuildChangeImpactForFile(n,r,c),h=Cr(m,r),b=s?h.filter(S=>c.nodes.get(S)?.category==="test"):h,k=p(b);return v({file:r,affected:k,count:k.length})}let u=rs(c,r,{testsOnly:s,changedSymbols:o}),f=p(u);return v({file:r,affected:f,count:f.length})}async function hc(t,e){let{root:n,baseRef:r,headRef:s,minDuplicateLines:i,complexityMetric:o,complexityThreshold:a}=e,c=ge(t.getConfig(n));if(t.isWorkspaceRoot(n)){if(e.entryPoints?.length)throw new Error("compare_branches on a monorepo root compares the whole workspace \u2014 omit entryPoints. To compare one package, point root at that package's directory.");let f=(await t.ensureFreshWorkspace(n)).flatten().graph,m=await Tn(n,r,f,{headRef:s,entryPoints:[],minDuplicateLines:i,complexityMetric:o,complexityThreshold:a,maxCoveragePct:e.maxCoveragePct,...c,workspaceBuilder:async h=>(await Hn(h,{silent:!0,...c})).flatten().graph});return e.detail==="full"?v(m):v(En(m,{metric:o,maxItems:e.maxItems}))}let l=await t.ensureFresh(n),p=e.entryPoints??t.getLastEntryPoints(n)?.map(f=>ke.relative(n,f))??[],u=await Tn(n,r,l,{headRef:s,entryPoints:p,minDuplicateLines:i,complexityMetric:o,complexityThreshold:a,maxCoveragePct:e.maxCoveragePct,...c});return e.detail==="full"?v(u):v(En(u,{metric:o,maxItems:e.maxItems}))}async function yc(t,e){let{root:n,file:r,depth:s=1,withEdgeDetail:i=!1}=e,{graph:o,packageOf:a}=await t.resolveFlatGraphForFile(n,r),c=ss(o,r,{depth:s,withEdgeDetail:i}),l=a.size===0?c:c.map(f=>{let m=a.get(f.file);return m?{...f,package:m}:f}),p=l.length===0?Je(o,"callEdges"):void 0,u=l.length>0?V(o,"callEdges"):[];return v({file:r,callers:l,count:l.length,...p&&{note:p},...u.length>0&&{caveats:u}})}async function xc(t,e){let{root:n,entryPoints:r,package:s}=e,i=t.getConfig(n),o=Jn(n,{additionalIgnoreDirs:i?.ignoreDirs??[],additionalExtensions:i?.extensions??[]});if(!r&&t.isWorkspaceRoot(n)){let l=await t.ensureFreshWorkspace(n),p=s?[l.packages.get(s)].filter(f=>!!f):Array.from(l.packages.values());if(s&&p.length===0)throw new Error(`Unknown workspace package "${s}". Call get_workspace_packages to list packages.`);let u=p.flatMap(({graph:f,pkg:m})=>{let h=o.filter(b=>b===m.relativeRoot||b.startsWith(`${m.relativeRoot}/`));return f.findUnusedFiles(h)});return v({unusedFiles:u,count:u.length})}let c=(r?await t.getOrBuild(n,r.map(l=>ke.resolve(n,l))):await t.ensureFresh(n)).findUnusedFiles(o);return v({unusedFiles:c,count:c.length})}async function bc(t,e){let{root:n,package:r,kind:s,prefix:i,minCount:o,limit:a}=e,c=await t.resolveGraphs(n,r),l=gs(c.map(({graph:p})=>p));return v(ds(l,{kind:s,prefix:i,minCount:o,limit:a}))}async function kc(t,e){let{root:n,coverageThreshold:r,package:s}=e,i=await t.resolveGraphs(n,s),o=t.getConfig(n),a=r??o?.coverageThreshold??80,c=i.length>1;if(!i.some(({graph:p})=>Ne(p)))return v({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let l=i.flatMap(({graph:p,package:u})=>Y([...p.nodes.values()].filter(f=>f.category!=="test"&&f.category!=="config").filter(f=>f.coveragePct!==void 0&&f.coveragePct<a).map(f=>({file:f.path,coveragePct:f.coveragePct})),u,c));return v({threshold:a,uncovered:l,count:l.length})}async function Sc(t,e){let{root:n,package:r}=e,s=await t.resolveGraphs(n,r),i=s.length>1;if(!s.some(({graph:a})=>os(a)))return v({error:"No git-stats data available. Set gitStats: true in mokosh.config and call analyze again."});let o=s.flatMap(({graph:a,package:c})=>Y([...a.nodes.values()].filter(l=>l.type==="markdown"&&l.staleFor&&l.staleFor.length>0).map(l=>({doc:l.path,staleFor:l.staleFor})),c,i));return v({staleDocs:o,count:o.length})}async function vc(t,e){let{root:n,metric:r="cognitiveComplexity",threshold:s=10,limit:i=20,package:o}=e,a=await t.resolveGraphs(n,o),c=a.length>1,l=a.flatMap(({graph:m,package:h})=>Y(tt(m,{metric:r,threshold:s,limit:c?1/0:i}),h,c)).sort((m,h)=>h[r]-m[r]).slice(0,i),p=a.map(({graph:m})=>m),u=l.length===0?Je(p,"functionComplexity"):void 0,f=l.length>0?V(p,"complexity"):[];return v({metric:r,threshold:s,functions:l,count:l.length,...u&&{note:u},...f.length>0&&{caveats:f}})}async function Cc(t,e){let{root:n,metric:r="cognitiveComplexity",minComplexity:s=10,maxCoveragePct:i=50,minChurn:o=0,limit:a=20,package:c}=e,l=await t.resolveGraphs(n,c),p=l.length>1;if(!l.some(({graph:b})=>Ne(b)))return v({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let u=l.map(({graph:b,package:k})=>({pkgName:k,...nt(b,{metric:r,minComplexity:s,maxCoveragePct:i,minChurn:o,limit:p?1/0:a})})),f=u.flatMap(({hotspots:b,pkgName:k})=>Y(b,k,p)).sort((b,k)=>k[r]-b[r]).slice(0,a),m=u.some(b=>b.churnDataAvailable),h=f.length>0?V(l.map(({graph:b})=>b),"complexity"):[];return v({metric:r,minComplexity:s,maxCoveragePct:i,minChurn:o,churnDataAvailable:m,hotspots:f,count:f.length,...h.length>0&&{caveats:h}})}function Bd(t){let e=Object.keys(t.byTopDir).length,n=Object.keys(t.byFamily).filter(s=>s!=="other"),r=n.length>1?` or filter:"family:${n[0]},sort:score"`:"";return`${t.matched} duplicate group${t.matched===1?"":"s"} across ${e} ${e===1?"dir":"dirs"}; showing the top clusters. Narrow with filter, e.g. filter:"path:src,minScore:15"${r}. Pass view:"groups" for raw spans or view:"full" for both lists.`}async function wc(t,e){let{root:n,minLines:r=6,ignoreLiterals:s=!0,maxPunctuationRatio:i=.5,limit:o=20,filter:a,slim:c=!0,package:l}=e,p=a?Qe(a):void 0,u=p?.limit??o,f=await t.resolveGraphs(n,l),m=f.length>1,h=t.getConfig(n),b=e.ignoreDirs??[...j,...h?.ignoreDirs??[]],k=Math.max(m||p?u*4:u,cc),S={includeGenerated:e.includeGenerated??h?.duplication?.includeGenerated??!1,includeSameFile:e.includeSameFile??h?.duplication?.includeSameFile??!1,includeSvgMarkup:e.includeSvgMarkup??h?.duplication?.includeSvgMarkup??!1,includeDocs:e.includeDocs??h?.duplication?.includeDocs??!1,scope:e.scope??h?.duplication?.scope,ignoreGlobs:h?.duplication?.ignoreGlobs??[]},w={minLines:r,ignoreLiterals:s,maxPunctuationRatio:i,limit:k,scope:S.scope,includeGenerated:S.includeGenerated,includeSameFile:S.includeSameFile,includeSvgMarkup:S.includeSvgMarkup,includeDocs:S.includeDocs,ignoreDirs:b,ignoreGlobs:S.ignoreGlobs},N=yn(w),_=a===void 0,X=await t.getDuplicationTokenCache(n),pe=[],Se=!1;for(let{graph:D,package:G}of f){let ct=t.duplicationResultCachePath(n,m?G:void 0),O=_?hn(D.nodes.values()):"",Ge=_?xn(ct,O,N):null;if(Ge){pe.push({groups:Y(Ge.groups,G,m),clusters:Y(Ge.clusters,G,m)});continue}Se=!0;let{groups:Ys,clusters:Xs}=await et(D,n,{minLines:r,ignoreLiterals:s,maxPunctuationRatio:i,limit:k,ignoreDirs:b,includeGenerated:S.includeGenerated,includeSameFile:S.includeSameFile,includeSvgMarkup:S.includeSvgMarkup,includeDocs:S.includeDocs,scope:S.scope,ignoreGlobs:S.ignoreGlobs,...a!==void 0&&{filter:a},tokenCache:X});_&&bn(ct,O,N,Ys,Xs),pe.push({groups:Y(Ys,G,m),clusters:Y(Xs,G,m)})}Se&&t.flushDuplicationTokenCache(n);let B=pe.flatMap(D=>D.groups),re=Sn(B),ve=p?.sort?mn(B,p):[...B].sort((D,G)=>G.lines-D.lines),ue=pe.flatMap(D=>D.clusters).sort((D,G)=>G.longestMatch-D.longestMatch||G.matchCount-D.matchCount),U=e.view??"summary",ot=a===void 0&&e.view===void 0,Yn=U==="groups"||U==="full",at=U!=="groups",Xn=ot?zd:u,$=at?ue.slice(0,Xn):[],x=[],T;if(Yn)if(U==="full"){let D=kn(ve,$);T=ve.length-D.length,x=D.slice(0,u)}else x=ve.slice(0,u);let K=T!==void 0?{...re,clusteredGroups:T}:re,Gt=()=>c?x.map(vn):x,fe=()=>c?$.map(Cn):$,Z=!1;for(;(x.length>1||$.length>1)&&JSON.stringify({minLines:r,summary:K,groups:Gt(),clusters:fe()}).length>$d;)x=x.slice(0,Math.max(1,Math.floor(x.length/2))),$=$.slice(0,Math.max(1,Math.floor($.length/2))),Z=!0;let H=V(f.map(({graph:D})=>D),"duplication");return v({minLines:r,...a!==void 0&&{filter:a},summary:K,...at&&{clusters:fe()},...Yn&&{groups:Gt(),count:x.length},...ot&&{hint:Bd(re)},...H.length>0&&{caveats:H},...Z&&{truncated:Z}})}async function Ec(t,e){let{root:n,changedFiles:r,base:s,featureThreshold:i,format:o="tags"}=e,a=r??new Qt().getChangedFiles(n,s).map(u=>ke.relative(n,ke.resolve(n,u))),c=i!==void 0?{featureDetection:{minOutDegree:i}}:void 0,l=t.isWorkspaceRoot(n)?await Ud(t,n,a):[{graph:await t.ensureFresh(n),files:a}];if(o==="paths"){let u=[...new Set(l.flatMap(({graph:f,files:m})=>$s(f,m,c)))];return v({changedFiles:a,affectedTests:u,count:u.length})}let p=[...new Set(l.flatMap(({graph:u,files:f})=>Ws(u,f,c)))];return v({changedFiles:a,proposedTags:p})}async function Ud(t,e,n){let r=await t.ensureFreshWorkspace(e),s=new Map;for(let i of n){let o=r.getPackageForFile(i);if(!o)continue;let a=s.get(o.name);a?a.push(i):s.set(o.name,[i])}return Array.from(s.entries()).map(([i,o])=>({graph:r.packages.get(i)?.graph,files:o})).filter(i=>!!i.graph)}async function Tc(t,e){let{root:n,entryPoints:r,featureThreshold:s,package:i}=e,o=s!==void 0?{minOutDegree:s}:void 0;if(r){let p=await t.getOrBuild(n,r.map(m=>ke.resolve(n,m))),u=xe(p.nodes,o),f=Array.from(u.values()).sort((m,h)=>h.outDegree-m.outDegree);return v({features:f,count:f.length})}let a=await t.resolveGraphs(n,i),c=a.length>1,l=a.flatMap(({graph:p,package:u})=>Y(Array.from(xe(p.nodes,o).values()),u,c)).sort((p,u)=>u.outDegree-p.outDegree);return v({features:l,count:l.length})}async function Fc(t,e){let{root:n,entryPoints:r,filter:s,mermaid:i=!1,slim:o=!0,package:a}=e;if(r){let p=await t.getOrBuild(n,r.map(u=>ke.resolve(n,u)));return lc(p,s,i,o)}let{graph:c,packageOf:l}=await t.resolveFlatGraph(n,a);return lc(c,s,i,o,l)}function lc(t,e,n,r,s=new Map){let i=Nn(t.serialize(),Mn(e),{packageOf:s});return n?v(Kt.serialize(P.deserialize(i))):v(r?is(i):i)}async function Dc(t,e){let{root:n}=e,r=t.getLayout(n);if(r.type==="none")throw new Error(`${n} is not a recognized monorepo root (no pnpm/npm/yarn/Nx/Turborepo/Gradle/sbt workspace detected).`);let s=t.hasWorkspace(n)?t.requireWorkspace(n):void 0;return v(It(r,s))}async function Pc(t,e){let{root:n,file:r,maxFilesPerPackage:s}=e,o=(await t.ensureFreshWorkspace(n)).summarizeAffectedAcrossPackages(r,s!==void 0?{maxFilesPerPackage:s}:{});return v(o)}function Ac(t,e){let{root:n}=e,r=t.invalidate(n);return v({root:n,cleared:r,message:r?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function Rc(t,e){let{root:n,type:r,package:s}=e,{graph:i}=await t.resolveFlatGraph(n,s),o=hs(i);if(r)return v(ys(o,r));let a=Array.from(o.types.values()),c=a.length===0?Je(i,"typeGraph"):void 0;return v({count:a.length,types:a,...c&&{note:c}})}async function Nc(t,e){let{root:n,paths:r,minOutDegree:s,package:i}=e,o=await t.resolveGraphs(n,i),a=o.length>1,c=s!==void 0?{minOutDegree:s}:void 0,l=o.flatMap(({graph:p,package:u})=>{let f=ps(p,c),m=r?.length?r.map(h=>f.get(h)).filter(h=>!!h):Array.from(f.values());return Y(m,u,a)});return v({count:l.length,modules:l})}async function Mc(t,e){let{root:n,minOutDegree:r,package:s}=e,{graph:i}=await t.resolveFlatGraph(n,s),o=Rt(i,r!==void 0?{minOutDegree:r}:void 0),a=Object.fromEntries(o.features);return v({features:a,unassigned:o.unassigned})}async function Ic(t,e){let{root:n,function:r,package:s}=e,{graph:i}=await t.resolveFlatGraph(n,s),o=Sr(i,r),a=o.callers.length===0&&o.callees.length===0,c=a?Je(i,"callEdges"):void 0,l=a?[]:V(i,"callEdges");return v({...o,...c&&{note:c},...l.length>0&&{caveats:l}})}async function Lc(t,e){let{root:n,name:r,package:s}=e,i=await t.resolveGraphs(n,s),o=i.length>1,a=i.flatMap(({graph:l,package:p})=>Y(us(l,r),p,o)),c=a.length>0?V(i.map(({graph:l})=>l),"callEdges"):[];return v({name:r,matches:a,count:a.length,...c.length>0&&{caveats:c}})}var pc=25;function Kd(t){return t.length<=pc?{entryPoints:t,entryPointCount:t.length}:{entryPoints:t.slice(0,pc),entryPointCount:t.length,entryPointsTruncated:!0}}function uc(t,e,n){if(e==="full")return v({...t,...Kd(t.entryPoints)});let r=br(t,n===void 0?{}:{maxExports:n});if(e==="exports"){let{publicExportsTruncated:s,...i}=r;return v({...i,publicExports:t.publicExports,hint:'Pass view:"full" for the internalFiles / testFiles path lists.'})}return v(r)}async function _c(t,e){let{root:n,entryPoints:r,package:s,view:i="summary",maxExports:o}=e,a=e.maxExportsPerPackage??10;if(!t.isWorkspaceRoot(n)){let h=await t.ensureFresh(n),b=r?.length?r:kr(h,n);if(b.length===0)throw new Error("No entry points found. Pass entryPoints explicitly, or (JS) ensure package.json has a main/exports field.");return uc(Jt(h,b),i,o)}let c=await t.ensureFreshWorkspace(n),l=await t.resolveGraphs(n,s),p=(h,b)=>{let S=(r?.length?r:(c.packages.get(h)?.pkg.entryPoints??[]).map(w=>ke.relative(n,w))).filter(w=>b.nodes.has(w));return S.length?Jt(b,S):null};if(l.length===1){let h=l[0];if(!h)throw new Error("get_api_surface: no graph resolved for this root.");let b=p(h.package,h.graph);if(!b)throw new Error(`No entry point for package "${h.package}" is present in the analyzed graph. Pass entryPoints explicitly.`);return uc(b,i,o)}let u=[],f=[],m=!1;for(let{package:h,graph:b}of l){let k=p(h,b);if(!k){f.push({package:h,reason:"no entry point resolvable from the WorkspaceGraph"});continue}let S={package:h,entryPointCount:k.entryPoints.length,publicExportCount:k.publicExports.length,internalFileCount:k.internalFiles.length,unreachableFromEntryCount:k.unreachableFromEntry.length,testFileCount:k.testFiles.length};a>0?(S.publicExports=k.publicExports.slice(0,a).map(w=>({name:w.name,kind:w.kind})),S.publicExports.length<k.publicExports.length&&(m=!0)):k.publicExports.length>0&&(m=!0),u.push(S)}return v({packages:u,skipped:f,truncated:m})}async function Gc(t,e){let n=await t.resolveGraphs(e.root,e.package),s=(await Promise.all(n.map(({graph:i})=>js(i,e.root,{dryRun:e.dryRun??!1})))).reduce((i,o)=>({updated:i.updated+o.updated,unchanged:i.unchanged+o.unchanged,errors:i.errors+o.errors,files:[...i.files,...o.files]}));return v(s)}var z={type:"string"},Vs={type:"string",description:"Monorepo: narrow to one package (else whole workspace)."},Oc=[{name:"analyze",description:"Build the dependency graph from entry points; returns node count, categories, and cycles. Call before get_dependencies/get_dependents/get_affected/propose_tags. Empty entryPoints auto-detects a monorepo (pnpm/npm/yarn/Nx/Turborepo/Gradle/sbt): returns the layout at once, builds per-package graphs lazily on the first workspace-aware call \u2014 eager:true builds all up front. Whole-graph tools then run against the flattened workspace; pass package to narrow.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root (or monorepo root)"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root (e.g. ['src/index.ts']). Pass [] to trigger monorepo auto-detection."},eager:{type:"boolean",description:"Monorepo only: build every package graph before returning (restores the { nodeCount, categories, cycles } payload) instead of the fast layout-only response. Default false."},packages:{type:"array",items:{type:"string"},description:"Monorepo only: restrict the build to these package names or relative roots. The escape hatch for very large monorepos."},cycleKinds:{type:"array",items:{type:"string",enum:["docReference","samePackage"]},description:"Include normally-filtered cycle edge kinds in the `cycles` output: 'docReference' (Markdown doc cross-links, ADR-009), 'samePackage' (JVM same-package siblings). Default: none \u2014 only genuine import cycles are reported."}},required:["root","entryPoints"]}},{name:"get_dependencies",description:"Get files that a given file imports (outgoing traversal). depth=1 returns immediate imports; omit for the full transitive tree. Each result includes the specific symbols imported from that file (when known).",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withMeta:{type:"boolean",description:"Include each result's category and export names alongside the path (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"get_dependents",description:"Get files that directly import a given file (one-hop incoming edges). Each result includes the specific symbols that dependent file imports from this file (when known).",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},withMeta:{type:"boolean",description:"Include each result's category and export names alongside the path (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"get_affected",description:"Get all files transitively affected if a given file changes \u2014 full incoming traversal upward. Use before a refactor to understand blast radius. On a monorepo root, blast radius is fully transitive across packages. See docs/mcp.md for the testsOnly, cached, changedSymbols, and withMeta options.",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},testsOnly:{type:"boolean",description:"Return only test/spec files (default: false)"},cached:{type:"boolean",description:"Use a pre-computed impact cache for O(1) lookup instead of graph traversal. Cache is built lazily on first use and reused for the session (default: false)."},changedSymbols:{type:"array",items:{type:"string"},description:"Restrict blast-radius to files that import at least one of these symbols. Omit to treat the whole file as changed (conservative, same as before)."},withMeta:{type:"boolean",description:"Return each affected file as { path, category, exports } instead of a bare path string (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"compare_branches",description:"Compare the current graph (root) against baseRef, for reviewing a PR/branch: file diff, stale post-rename references, and deltas for duplication, complexity, doc drift, and coverage/risk hotspots. Returns a compact summary by default (verdict + headline + capped delta lists); pass detail:'full' for every entry. Monorepo root: whole flattened workspace, no entryPoints. See docs/mcp.md. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},baseRef:{type:"string",description:"Git ref to compare against, e.g. 'main', 'origin/main', or a commit sha"},headRef:{type:"string",description:"Git ref to label the head side of the comparison (default: 'HEAD'). The graph itself always comes from the already-analyzed root, not a checkout of this ref."},entryPoints:{type:"array",items:{type:"string"},description:"Entry points to build the base-ref graph from, relative to root. Defaults to the entry points from the last analyze() call for this root."},minDuplicateLines:{type:"number",description:"Minimum duplicated block size, in source lines, for the duplication delta (default: 6)"},complexityMetric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which per-function score drives the complexity delta (default: cognitiveComplexity)"},complexityThreshold:{type:"number",description:"Minimum per-function score to count as a complexity hotspot (default: 10)"},maxCoveragePct:{type:"number",description:"Maximum containing-file coverage % to count as a risk hotspot (default: 50)"},detail:{type:"string",enum:["summary","full"],description:"'summary' (default): verdict, headline, and each delta list capped at maxItems with true counts; empty sections omitted. 'full': the complete BranchComparison with every entry."},maxItems:{type:"number",description:"In summary mode, max entries kept per delta list (complexity/duplication/doc-drift/coverage); the true count is always reported alongside (default: 8). Stale references are never truncated."}},required:["root","baseRef"]}},{name:"get_callers",description:"Get files whose exported functions call into a given file (call-graph dependents). More precise than get_affected: only files with actual runtime call edges, not mere imports. Requires prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to project root"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withEdgeDetail:{type:"boolean",description:"Include from/to function names per edge (default: false)"}},required:["root","file"]}},{name:"find_unused",description:"Find files in the project that are not reachable from any entry point. Useful before cleanup passes. Omit entryPoints to reuse the cached graph from a prior analyze() call instead of rebuilding.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to reuse the cached graph from a prior analyze() call."},package:z},required:["root"]}},{name:"list_tags",description:"Discover tag:<name> values. Bounded: capped at 250 tags, no full mode. Default = comment-marker + import kinds, count>=2, top 50, plus a byKind histogram over all kinds, totalDistinct and a hint. Narrow with kind, prefix or minCount. See docs/mcp.md.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},kind:{type:"string",enum:["comment-marker","import","function","variable","library","all"],description:'One tag kind, or "all" \u2014 overrides the default comment-marker+import filter. import/library = per-imported file/package on tests; function/variable = declaration names.'},prefix:{type:"string",description:"Case-insensitive substring match on the name."},minCount:{type:"number",description:"Min node count per tag (default 2)."},limit:{type:"number",description:"Max tags returned (default 50, max 250)."},package:z},required:["root"]}},{name:"find_uncovered",description:"Find non-test files whose line coverage is below the configured threshold. Requires a prior analyze() call and coverageReportPath set in mokosh.config. coverageThreshold overrides the config default (default: 80).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},coverageThreshold:{type:"number",description:"Line-coverage % below which a file is considered uncovered. Overrides config value."},package:z},required:["root"]}},{name:"check_doc_drift",description:"Find markdown docs whose referenced files changed more recently than the doc itself \u2014 a commit-recency heuristic for stale docs, not a content diff. Requires a prior analyze() with gitStats: true in mokosh.config (else no commit-timestamp data, nothing flagged). See docs/adr-009-markdown-parsing.md for limitations.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},package:z},required:["root"]}},{name:"find_complex_functions",description:"Find individual functions/methods above a cognitive (or cyclomatic) complexity threshold, sorted worst-first. Requires a prior analyze() call. Populated for TypeScript/JavaScript, Go, and Python.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which score to threshold/sort on (default: cognitiveComplexity)"},threshold:{type:"number",description:"Minimum score to include (default: 10)"},limit:{type:"number",description:"Max results to return, worst-first (default: 20)"},package:z},required:["root"]}},{name:"find_risk_hotspots",description:"Find functions that are complex, in a poorly-covered file, and \u2014 when gitStats is enabled in mokosh.config \u2014 frequently changed. Requires a prior analyze() and coverageReportPath in mokosh.config; errors if no coverage loaded. Churn filtering is skipped (churnDataAvailable: false) without gitStats, since complexity + low coverage alone is still a meaningful signal.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which per-function score to filter/sort on (default: cognitiveComplexity)"},minComplexity:{type:"number",description:"Minimum per-function complexity score to include (default: 10)"},maxCoveragePct:{type:"number",description:"Maximum containing-file coverage % to include (default: 50)"},minChurn:{type:"number",description:"Minimum containing-file 90-day commit count to include (default: 0). Ignored when gitStats wasn't enabled at analyze time."},limit:{type:"number",description:"Max results to return, worst-first by metric (default: 20)"},package:z},required:["root"]}},{name:"find_duplicates",description:"Find duplicated code, largest-first. Summary-first: default = `summary` + `clusters` preview + `hint`, no `groups`. Narrow with `filter`; `view` adds groups. Requires analyze().",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minLines:{type:"number",description:"Min duplicated block size in lines (default 6)"},ignoreLiterals:{type:"boolean",description:"Normalize string/number literals (default true); false = exact text."},maxPunctuationRatio:{type:"number",description:"Max object/array-punctuation fraction (default 0.5); 1 disables."},ignoreDirs:{type:"array",items:{type:"string"},description:"Directory names to exclude (default: DEFAULT_IGNORE_DIRS + config). [] disables."},limit:{type:"number",description:"Max clusters/groups returned (default 20); ignored for the summary view."},includeGenerated:{type:"boolean",description:"Scan generated/vendored files too (default false). signals:['generated']."},includeSameFile:{type:"boolean",description:"Include single-file matches (default false). signals:['same-file']."},includeSvgMarkup:{type:"boolean",description:"Include inline-SVG/JSX-markup matches (default false). signals:['svg-markup']."},scope:{type:"string",enum:["src","tests","all"],description:"Test-file dups (default 'src'): 'src' drops test clusters, 'tests' only substantive test logic, 'all' keeps all."},includeDocs:{type:"boolean",description:"Include markdown-family matches (default false). signals:['docs']."},filter:{type:"string",description:"key:value result filter (AND across keys): path, allPaths, family, type, kind, defKind, min/maxLines, min/maxScore, minOccurrences, crossFile, signal ('!' negates), sort, sortDir, limit. See docs/query.md."},view:{type:"string",enum:["summary","groups","full"],description:"'summary' (default): clusters preview + hint, no groups. 'groups': raw spans, no clusters. 'full': both, groups de-duped vs clusters."},slim:{type:"boolean",description:"Compact response (default true): terse groups, 'path:start-end' occurrences, clusters carry longestMatchAt not group bodies. false = full."},package:z},required:["root"]}},{name:"propose_tags",description:"Propose what to run based on changed files. Pass changedFiles explicitly or omit to use git diff. format='tags' (default) returns test tags for CI tag-filtering; format='paths' returns test file paths ready to pipe directly to a test runner (e.g. vitest). Feature hubs act as traversal boundaries in both modes.",inputSchema:{type:"object",properties:{root:{type:"string"},changedFiles:{type:"array",items:{type:"string"},description:"Changed files relative to root. Omit to read from git diff."},base:{type:"string",description:"Diff against this ref (e.g. 'origin/main') instead of only local working-tree/staged/untracked changes. Ignored when changedFiles is given. Needed in CI, where the checkout is already clean."},featureThreshold:{type:"number",description:"Min importers for a file to be treated as a feature hub (default: 5). A hub short-circuits traversal and emits a feature:<name> tag instead of all downstream tags."},format:{type:"string",enum:["tags","paths"],description:"Output format: 'tags' returns test tag names for CI filtering (default); 'paths' returns test file paths to pipe to a test runner."}},required:["root"]}},{name:"detect_features",description:"Identify feature hub files \u2014 non-test files that import many other internal modules (orchestrators / aggregators like src/parser.ts or src/cli/runner.ts). Returns a list sorted by import count descending.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to use the cached graph."},featureThreshold:{type:"number",description:"Min internal imports a file must have to qualify as a feature hub (default: 5)."},package:z},required:["root"]}},{name:"query",description:"Filter the graph by category, tag, path, or other node metadata. Returns matching nodes as JSON or a Mermaid diagram. If entryPoints is omitted the cached graph from a prior 'analyze' call is used. On a monorepo root: runs against the flattened workspace (global sort/limit, cross-package edges, per-node package); package:<name> narrows. See docs/mcp.md for the full query DSL reference.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry points to build the graph. Omit to reuse the cached graph from a prior 'analyze' call."},filter:{type:"string",description:"Query string e.g. 'category:logic' or 'category:logic,tag:auth'. Keys: category, type, tag, path, package, external, importsFile, importedBy, min/maxImports, min/maxSize, hasDocstring, min/maxCoverage, min/maxExportUsage, min/maxComplexity, min/maxCognitiveComplexity, min/maxCommits, isDocumented, isStale, lastAuthor. OR: any(k:v|k:v). sort: size|imports|commitCount90d|exportUsage|complexity|cognitiveComplexity + sortDir asc|desc. limit: N. Full reference: docs/query.md."},mermaid:{type:"boolean",description:"Return a Mermaid diagram (default: false)"},slim:{type:"boolean",description:"Compact response mode (default: true). Export names, meaningful tags (comment-marker + import kinds only), and a flat importsFiles path list \u2014 no edge objects, no mtime/size. Pass slim: false for every tag kind and full edge metadata; use list_tags (bounded; its byKind histogram shows per-kind totals) to discover tag names."},package:{type:"string",description:"Monorepo: narrow to one package (same as a package:<name> filter clause)."}},required:["root","filter"]}},{name:"get_workspace_packages",description:"List workspace packages in a monorepo: name, relativeRoot, dependsOn. Reads repo layout + package.json manifests alone \u2014 no analyze(), no graph build, fast on large monorepos. Per-package nodeCount (and exact dependsOn edges for Gradle/sbt) appear only when a prior analyze() built the workspace graph; check the dependsOnResolved / nodeCountsResolved flags.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"}},required:["root"]}},{name:"get_workspace_affected",description:"Cross-package blast-radius analysis: files affected if a given file changes, grouped by owning package with each package's sample list capped (counts stay exact). For the full uncapped list call get_affected on the same file. Requires a prior analyze() with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"},file:{type:"string",description:"Monorepo-root-relative path of the changed file (e.g. 'packages/shared/src/utils.ts')"},maxFilesPerPackage:{type:"number",description:"Cap each package's sample list (default 10; 0 = counts only)."}},required:["root","file"]}},{name:"get_type_graph",description:"Type-level relationships. Without a type name: an inventory of all interfaces, classes, enums and type aliases with their file and kind. With a type name: which files import it (usedByFiles) and which types the defining file imports (uses). Requires a prior analyze(). TypeScript/JavaScript only.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},type:{type:"string",description:"Exact exported name of the type to look up (e.g. 'FileNode'). Omit to get the full type inventory."},package:Vs},required:["root"]}},{name:"get_module_responsibility",description:"Return what each file is responsible for: its semantic role, JSDoc description (when present), exported symbol names, and which feature hub it belongs to. Pass specific paths to filter, or omit paths to get all files. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},paths:{type:"array",items:{type:"string"},description:"Project-relative file paths to include. Omit to return all files."},minOutDegree:{type:"number",description:"Min imports for a file to qualify as a feature hub (default: 5)."},package:z},required:["root"]}},{name:"get_feature_graph",description:"Group files by domain: which files each feature hub (high-import orchestrator) transitively owns. Each file goes to the most specific hub that can reach it (lowest out-degree wins). Prefer over a full query for 'what files are in feature X?' \u2014 returns only paths grouped by hub, so it's smaller than a full graph query for the same question.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minOutDegree:{type:"number",description:"Minimum internal imports a file must have to qualify as a feature hub (default: 5)."},package:Vs},required:["root"]}},{name:"get_call_graph",description:"Look up callers and callees for a named function. Returns the file that defines the function, all files/functions that call it, and all files/functions it calls. Always requires a function name \u2014 never returns the full call graph unfiltered. Call edges are only populated for TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},function:{type:"string",description:"Exact name of the function to look up (e.g. 'parseFile')."},package:Vs},required:["root","function"]}},{name:"find_symbol",description:"Find every file that exports a symbol by exact name, with the best available usage info per match. Precision varies by the defining file's language \u2014 check each match's `precision` field ('call' | 'file-level') before trusting caller/importer results as symbol-exact. See docs/mcp.md for per-language coverage details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},name:{type:"string",description:"Exact export name to look up (e.g. 'parseFile')."},package:z},required:["root","name"]}},{name:"get_api_surface",description:"API surface report: exported symbols resolved to defining file + kind, plus internalFiles / unreachableFromEntry / testFiles partitions. Needs a prior analyze(). Entry points auto-detect from package.json exports/bin/main (JS/TS) or every non-test source file (Go/Python/JVM). Summary-first: view 'summary' (default) = counts + byKind + a capped sample + the short unreachableFromEntry list; 'exports'/'full' widen it. Monorepo root without `package`: per-package breakdown + `skipped`. See docs/mcp.md.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},entryPoints:{type:"array",items:{type:"string"},description:"Public entry-point paths. Omit to auto-detect (exports / bin / main)."},package:z,view:{type:"string",enum:["summary","exports","full"],description:"summary (default) | exports (+full publicExports) | full (+path lists)."},maxExports:{type:"number",description:"view 'summary': cap the {name,kind} sample (default 30)."},maxExportsPerPackage:{type:"number",description:"Monorepo, no `package`: cap each package's sample (default 10; 0 = counts)."}},required:["root"]}},{name:"clear_cache",description:"Drop the cached dependency graph and mokosh.config.json for a root, forcing the next analyze() to rebuild from disk and re-read config. Call after editing source files or mokosh.config.json mid-session \u2014 otherwise get_affected, get_dependencies and other query tools reason from stale data.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root to invalidate."}},required:["root"]}},{name:"apply_tags",description:"Write @tag annotations into test file source code based on the dependency graph, as an idempotent block \u2014 re-running is safe, the existing block is replaced in place. Use dryRun=true to preview changes without writing to disk. Requires a prior analyze() call. See docs/mcp.md for tag-kind and per-language block syntax details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root."},dryRun:{type:"boolean",description:"When true, computes which files would change but does not write to disk (default: false)."},package:z},required:["root"]}}];function Qs(){let t=new Vn,e=new Hd({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(Vd,async()=>({tools:Oc})),e.setRequestHandler(Jd,async n=>{let{name:r,arguments:s}=n.params,i=s,a={analyze:c=>fc(t,c),get_dependencies:c=>mc(t,c),get_dependents:c=>gc(t,c),get_affected:c=>dc(t,c),compare_branches:c=>hc(t,c),get_callers:c=>yc(t,c),find_symbol:c=>Lc(t,c),find_unused:c=>xc(t,c),find_uncovered:c=>kc(t,c),list_tags:c=>bc(t,c),check_doc_drift:c=>Sc(t,c),find_complex_functions:c=>vc(t,c),find_risk_hotspots:c=>Cc(t,c),find_duplicates:c=>wc(t,c),propose_tags:c=>Ec(t,c),detect_features:c=>Tc(t,c),get_type_graph:c=>Rc(t,c),get_module_responsibility:c=>Nc(t,c),get_feature_graph:c=>Mc(t,c),get_call_graph:c=>Ic(t,c),get_api_surface:c=>_c(t,c),query:c=>Fc(t,c),get_workspace_packages:c=>Dc(t,c),get_workspace_affected:c=>Pc(t,c),clear_cache:c=>Ac(t,c),apply_tags:c=>Gc(t,c)}[r];if(!a)throw new Error(`Unknown tool: ${r}`);try{return ac(i.root),await a(i)}catch(c){return{content:[{type:"text",text:`Error: ${c instanceof Error?c.message:String(c)}`}],isError:!0}}}),e}var qd=(()=>{try{let t=process.argv[1];return t?jc.realpathSync(Yd.resolve(t))===jc.realpathSync(d):!1}catch{return!1}})(),Wc=4096;function eh(){if(process.env.MOKOSH_MCP_CHILD==="1"||Xd.getHeapStatistics().heap_size_limit/1024/1024>=Wc)return!1;let e=process.argv[1];if(!e)return!1;let n=`${process.env.NODE_OPTIONS??""} --max-old-space-size=${Wc}`.trim(),r=Qd(process.execPath,[e,...process.argv.slice(2)],{stdio:"inherit",env:{...process.env,MOKOSH_MCP_CHILD:"1",NODE_OPTIONS:n}});if(r.error)return Qn("re-exec",r.error),!1;process.exit(r.status??(r.signal?1:0))}function Qn(t,e){let n=e instanceof Error?e.stack??e.message:String(e);process.stderr.write(`[mokosh-mcp] FATAL ${t}: ${n}
65
+ `)}async function th(){process.on("uncaughtException",n=>{Qn("uncaughtException",n),process.exit(1)}),process.on("unhandledRejection",n=>{Qn("unhandledRejection",n),process.exit(1)});let t=Qs(),e=new Zd;await t.connect(e)}qd&&!eh()&&th().catch(t=>{Qn("startup",t),process.exit(1)});export{Qs as createMcpServer};
53
66
  //# sourceMappingURL=mcp.mjs.map